diff --git a/.codespell/exclude-file.txt b/.codespell/exclude-file.txt index 08e1a2b9059..7e6bad4bf0b 100644 --- a/.codespell/exclude-file.txt +++ b/.codespell/exclude-file.txt @@ -8,3 +8,4 @@ i1Qb$TE"rl ZEN = "the zen of python beautiful is better than ugly explicit is better than implicit simple is better than complex complex is better than complicated flat is better than nested sparse is better than dense readability counts special cases arent special enough to break the rules although practicality beats purity errors should never pass silently unless explicitly silenced in the face of ambiguity refuse the temptation to guess there should be one and preferably only one obvious way to do it although that way may not be obvious at first unless youre dutch now is better than never although never is often better than right now if the implementation is hard to explain its a bad idea if the implementation is easy to explain it may be a good idea namespaces are one honking great idea lets do more of those" "arent", "youre", +USB_MANUFACTURER = "Wee Noise Makers" diff --git a/.codespell/ignore-words.txt b/.codespell/ignore-words.txt index fc8feaca978..2ae7d88d6ba 100644 --- a/.codespell/ignore-words.txt +++ b/.codespell/ignore-words.txt @@ -26,3 +26,6 @@ ftbfs straightaway ftbs ftb +curren +mabey +rsource diff --git a/.crit.config.json b/.crit.config.json new file mode 100644 index 00000000000..7183f68a052 --- /dev/null +++ b/.crit.config.json @@ -0,0 +1 @@ +{ "base_branch": "adafruit/main" } diff --git a/.devcontainer/add_kitware_archive.sh b/.devcontainer/add_kitware_archive.sh deleted file mode 100755 index aff0b6c8d0f..00000000000 --- a/.devcontainer/add_kitware_archive.sh +++ /dev/null @@ -1,107 +0,0 @@ -#!/bin/sh -# ----------------------------------------------------------------------------- -# This script is from: https://apt.kitware.com/kitware-archive.sh -# -# It installs key and repo for the kitware CMAKE-archive. -# -# Author: Bernhard Bablok -# -# ----------------------------------------------------------------------------- - -set -eu - -help() { - echo "Usage: $0 [--release ] [--rc]" > /dev/stderr -} - -doing= -rc= -release= -help= -for opt in "$@" -do - case "${doing}" in - release) - release="${opt}" - doing= - ;; - "") - case "${opt}" in - --rc) - rc=1 - ;; - --release) - doing=release - ;; - --help) - help=1 - ;; - esac - ;; - esac -done - -if [ -n "${doing}" ] -then - echo "--${doing} option given no argument." > /dev/stderr - echo > /dev/stderr - help - exit 1 -fi - -if [ -n "${help}" ] -then - help - exit -fi - -if [ -z "${release}" ] -then - unset UBUNTU_CODENAME - . /etc/os-release - - if [ -z "${UBUNTU_CODENAME+x}" ] - then - echo "This is not an Ubuntu system. Aborting." > /dev/stderr - exit 1 - fi - - release="${UBUNTU_CODENAME}" -fi - -case "${release}" in -noble|jammy|focal) - packages= - keyring_packages="ca-certificates gpg wget" - ;; -*) - echo "Only Ubuntu Noble (24.04), Jammy (22.04), and Focal (20.04) are supported. Aborting." > /dev/stderr - exit 1 - ;; -esac - -get_keyring= -if [ ! -f /usr/share/doc/kitware-archive-keyring/copyright ] -then - packages="${packages} ${keyring_packages}" - get_keyring=1 -fi - -# Start the real work -set -x - -apt-get update -# shellcheck disable=SC2086 -apt-get install -y ${packages} - -test -n "${get_keyring}" && (wget -O - https://apt.kitware.com/keys/kitware-archive-latest.asc 2>/dev/null | gpg --dearmor - > /usr/share/keyrings/kitware-archive-keyring.gpg) - -echo "deb [signed-by=/usr/share/keyrings/kitware-archive-keyring.gpg] https://apt.kitware.com/ubuntu/ ${release} main" > /etc/apt/sources.list.d/kitware.list -if [ -n "${rc}" ] -then - echo "deb [signed-by=/usr/share/keyrings/kitware-archive-keyring.gpg] https://apt.kitware.com/ubuntu/ ${release}-rc main" >> /etc/apt/sources.list.d/kitware.list -fi - -apt-get update -test -n "${get_keyring}" && rm /usr/share/keyrings/kitware-archive-keyring.gpg -apt-get install -y kitware-archive-keyring diff --git a/.devcontainer/common_tools.sh b/.devcontainer/common_tools.sh index d94977b01cc..1231b8e4f4b 100755 --- a/.devcontainer/common_tools.sh +++ b/.devcontainer/common_tools.sh @@ -9,16 +9,18 @@ # ----------------------------------------------------------------------------- REPO_ROOT="/workspaces/circuitpython" +CMAKE_VERSION="3.31.12" echo -e "[common_tools.sh] starting install" cd "$REPO_ROOT" # --- repositories and tools ------------------------------------------------ -echo -e "[common_tools.sh] adding kitware-archive (for current CMAKE)" -sudo .devcontainer/add_kitware_archive.sh -echo -e "[common_tools.sh] installing current version of CMAKE" -sudo apt-get -y install cmake +echo -e "[common_tools.sh] installing CMAKE $CMAKE_VERSION" +wget -q https://github.com/Kitware/CMake/releases/download/v$CMAKE_VERSION/cmake-$CMAKE_VERSION-linux-$(arch).sh +chmod +x cmake-$CMAKE_VERSION-linux-$(arch).sh +sudo ./cmake-$CMAKE_VERSION-linux-$(arch).sh --prefix=/usr/local --skip-license +rm cmake-$CMAKE_VERSION-linux-$(arch).sh echo -e "[common_tools.sh] adding pybricks/ppa" sudo add-apt-repository -y ppa:pybricks/ppa diff --git a/.devcontainer/cortex-m-toolchain.sh b/.devcontainer/cortex-m-toolchain.sh index de1ccde6274..7fe5135ebc2 100755 --- a/.devcontainer/cortex-m-toolchain.sh +++ b/.devcontainer/cortex-m-toolchain.sh @@ -14,10 +14,10 @@ echo -e "[cortex-m-toolchain.sh] downloading and installing gcc-arm-non-eabi too cd /workspaces wget -qO gcc-arm-none-eabi.tar.xz \ - https://developer.arm.com/-/media/Files/downloads/gnu/13.2.rel1/binrel/arm-gnu-toolchain-13.2.rel1-x86_64-arm-none-eabi.tar.xz + https://gitlab.arm.com/api/v4/projects/tooling%2Fgnu-toolchains-for-arm/packages/generic/gnu-toolchain/15.3.rel1/arm-gnu-toolchain-15.3.rel1-x86_64-arm-none-eabi.tar.xz tar -xJf gcc-arm-none-eabi.tar.xz -ln -s arm-gnu-toolchain-13.2.Rel1-x86_64-arm-none-eabi gcc-arm-none-eabi +ln -s arm-gnu-toolchain-15.3.rel1-x86_64-arm-none-eabi gcc-arm-none-eabi rm -f gcc-arm-none-eabi.tar.xz echo -e "[cortex-m-toolchain.sh] update PATH in environment" diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index 195e1e06eea..97b5e558f40 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -1,3 +1,6 @@ +# all: Apply code formatting to new paths. +48c7daaa3d7068c127c5bc395ffa72029ab9bba1 + # all: Prune trailing whitespace. dda9b9c6da5d3c31fa8769e581a753e95a270803 diff --git a/.gitattributes b/.gitattributes index 38bba729fc1..890c9cead6c 100644 --- a/.gitattributes +++ b/.gitattributes @@ -13,12 +13,14 @@ # CIRCUITPY-CHANGE: add some more binary types. # These are binary so should never be modified by git. *.a binary +*.FLM binary *.ico binary *.png binary *.jpg binary *.dxf binary *.mpy binary *.der binary +*.bin binary *.deb binary *.zip binary *.pdf binary @@ -27,4 +29,5 @@ # These should also not be modified by git. tests/basics/string_cr_conversion.py -text tests/basics/string_crlf_conversion.py -text +tests/micropython/test_normalize_newlines.py.exp -text # CIRCUITPY-CHANGE: remove non-CircuitPython tests diff --git a/.github/actions/deps/apt_packages/action.yml b/.github/actions/deps/apt_packages/action.yml new file mode 100644 index 00000000000..2c58d569edf --- /dev/null +++ b/.github/actions/deps/apt_packages/action.yml @@ -0,0 +1,60 @@ +name: Install apt packages, caching the downloaded files + +inputs: + packages: + description: 'The apt packages to install, separated by spaces' + required: true + +runs: + using: composite + steps: + - name: Name the cache + id: cache-name + run: echo "prefix=apt-$ImageOS-$(echo "$PACKAGES" | sha256sum | cut -c1-16)-" >> $GITHUB_OUTPUT + shell: bash + env: + PACKAGES: ${{ inputs.packages }} + - name: Restore downloaded packages + id: restore + uses: actions/cache/restore@v5 + with: + path: ~/apt-archives + key: ${{ steps.cache-name.outputs.prefix }} + restore-keys: ${{ steps.cache-name.outputs.prefix }} + - name: Install packages + id: install + # apt only downloads packages whose newest version isn't already in ~/apt-archives. + # If Ubuntu's servers can't be reached, install the cached versions without checking + # for updates. autoclean drops versions the mirror no longer has. The cache key names + # the .deb files kept, so it changes whenever a package is updated. + run: | + mkdir -p ~/apt-archives/partial + # Azure's Ubuntu mirror sometimes stops resolving on the runners. Use Ubuntu's own. + sudo sed -i 's|azure\.archive\.ubuntu\.com|archive.ubuntu.com|g' /etc/apt/apt-mirrors.txt /etc/apt/sources.list.d/*.sources 2>/dev/null || true + if sudo apt-get update --error-on=any; then + sudo apt-get install -y -o Dir::Cache::Archives="$HOME/apt-archives" $PACKAGES + # The runner image has no package lists for extra architectures such as i386. + # Keep them with the cached files, so the offline install can find those packages. + rm -rf ~/apt-archives/lists + mkdir -p ~/apt-archives/lists + for arch in $(dpkg --print-foreign-architectures); do + cp /var/lib/apt/lists/*_binary-"$arch"_Packages* ~/apt-archives/lists/ 2>/dev/null || true + done + else + sudo cp ~/apt-archives/lists/* /var/lib/apt/lists/ 2>/dev/null || true + sudo apt-get install -y --no-download -o Dir::Cache::Archives="$HOME/apt-archives" $PACKAGES + fi + sudo apt-get autoclean -o Dir::Cache::Archives="$HOME/apt-archives" + sudo rm -rf ~/apt-archives/partial ~/apt-archives/lock + sudo chown -R "$(id -un)" ~/apt-archives + echo "key=$PREFIX$(ls ~/apt-archives | sha256sum | cut -c1-16)" >> $GITHUB_OUTPUT + shell: bash + env: + PACKAGES: ${{ inputs.packages }} + PREFIX: ${{ steps.cache-name.outputs.prefix }} + - name: Save downloaded packages + if: github.event_name == 'push' && steps.restore.outputs.cache-matched-key != steps.install.outputs.key + uses: actions/cache/save@v5 + with: + path: ~/apt-archives + key: ${{ steps.install.outputs.key }} diff --git a/.github/actions/deps/external/action.yml b/.github/actions/deps/external/action.yml index 0b1444a820d..0624042b45b 100644 --- a/.github/actions/deps/external/action.yml +++ b/.github/actions/deps/external/action.yml @@ -21,25 +21,18 @@ runs: - name: Get arm toolchain if: >- inputs.port != 'none' && - inputs.port != 'litex' && inputs.port != 'espressif' && inputs.port != 'zephyr-cp' uses: carlosperate/arm-none-eabi-gcc-action@v1 with: - # When changing this update what Windows grabs too! - release: '13.2.Rel1' + release: '15.3.Rel1' # espressif - - name: Get espressif toolchain - if: inputs.port == 'espressif' - run: | - sudo apt-get update - sudo apt-get install -y ninja-build - shell: bash - name: Install IDF tools if: inputs.port == 'espressif' run: | $IDF_PATH/install.sh + $IDF_PATH/tools/idf_tools.py install ninja rm -rf $IDF_TOOLS_PATH/dist shell: bash - name: Set environment @@ -47,6 +40,7 @@ runs: run: | source $IDF_PATH/export.sh echo >> $GITHUB_ENV "IDF_PYTHON_ENV_PATH=$IDF_PYTHON_ENV_PATH" + echo >> $GITHUB_ENV "ESP_IDF_VERSION=$ESP_IDF_VERSION" echo >> $GITHUB_PATH "$PATH" shell: bash @@ -56,6 +50,16 @@ runs: uses: ./.github/actions/deps/python with: action: ${{ inputs.action }} + - name: Set ESP-IDF constraints path + if: inputs.port == 'espressif' + run: python3 -u tools/ci_set_idf_constraint.py + shell: bash + - name: Install python dependencies - run: pip install -r requirements-dev.txt + run: | + if [ -n "${IDF_CONSTRAINT_FILE:-}" ] && [ -f "$IDF_CONSTRAINT_FILE" ]; then + pip install -c "$IDF_CONSTRAINT_FILE" -r requirements-dev.txt + else + pip install -r requirements-dev.txt + fi shell: bash diff --git a/.github/actions/deps/ports/action.yml b/.github/actions/deps/ports/action.yml index 6f91ea62cec..77e04a45e16 100644 --- a/.github/actions/deps/ports/action.yml +++ b/.github/actions/deps/ports/action.yml @@ -11,18 +11,10 @@ inputs: runs: using: composite steps: - - name: Set up broadcom - if: inputs.port == 'broadcom' - uses: ./.github/actions/deps/ports/broadcom - - name: Set up espressif if: inputs.port == 'espressif' uses: ./.github/actions/deps/ports/espressif - - name: Set up litex - if: inputs.port == 'litex' - uses: ./.github/actions/deps/ports/litex - - name: Set up nordic if: inputs.port == 'nordic' uses: ./.github/actions/deps/ports/nordic @@ -30,3 +22,5 @@ runs: - name: Set up Zephyr if: inputs.port == 'zephyr-cp' uses: ./.github/actions/deps/ports/zephyr-cp + with: + sdl: ${{ startsWith(inputs.board, 'native_') }} diff --git a/.github/actions/deps/ports/broadcom/action.yml b/.github/actions/deps/ports/broadcom/action.yml deleted file mode 100644 index 99f53064b3f..00000000000 --- a/.github/actions/deps/ports/broadcom/action.yml +++ /dev/null @@ -1,22 +0,0 @@ -name: Fetch broadcom port deps - -runs: - using: composite - steps: - - name: Get broadcom toolchain - run: | - wget --no-verbose https://adafruit-circuit-python.s3.amazonaws.com/gcc-arm-10.3-2021.07-x86_64-aarch64-none-elf.tar.xz - sudo tar -C /usr --strip-components=1 -xaf gcc-arm-10.3-2021.07-x86_64-aarch64-none-elf.tar.xz - sudo apt-get update - sudo apt-get install -y mtools - shell: bash - - name: Install mkfs.fat - run: | - wget https://github.com/dosfstools/dosfstools/releases/download/v4.2/dosfstools-4.2.tar.gz - tar -xaf dosfstools-4.2.tar.gz - cd dosfstools-4.2 - ./configure - make -j4 - cd src - echo >> $GITHUB_PATH $(pwd) - shell: bash diff --git a/.github/actions/deps/ports/espressif/action.yml b/.github/actions/deps/ports/espressif/action.yml index 122940bb95a..a25c96d190e 100644 --- a/.github/actions/deps/ports/espressif/action.yml +++ b/.github/actions/deps/ports/espressif/action.yml @@ -7,6 +7,7 @@ runs: run: | echo >> $GITHUB_ENV "IDF_PATH=$GITHUB_WORKSPACE/ports/espressif/esp-idf" echo >> $GITHUB_ENV "IDF_TOOLS_PATH=$GITHUB_WORKSPACE/.idf_tools" + echo >> $GITHUB_ENV "ESP_ROM_ELF_DIR=$GITHUB_WORKSPACE/.idf_tools" shell: bash - name: Get IDF commit @@ -18,7 +19,7 @@ runs: shell: bash - name: Cache IDF submodules - uses: actions/cache@v4 + uses: actions/cache@v5 with: path: | .git/modules/ports/espressif/esp-idf @@ -26,10 +27,10 @@ runs: key: submodules-idf-${{ steps.idf-commit.outputs.commit }} - name: Cache IDF tools - uses: actions/cache@v4 + uses: actions/cache@v5 with: path: ${{ env.IDF_TOOLS_PATH }} - key: ${{ runner.os }}-${{ env.pythonLocation }}-tools-idf-${{ steps.idf-commit.outputs.commit }} + key: ${{ runner.os }}-${{ env.pythonLocation }}-tools-idf-${{ steps.idf-commit.outputs.commit }}-20260911 - name: Initialize IDF submodules run: git submodule update --init --depth=1 --recursive $IDF_PATH diff --git a/.github/actions/deps/ports/litex/action.yml b/.github/actions/deps/ports/litex/action.yml deleted file mode 100644 index a89a2225052..00000000000 --- a/.github/actions/deps/ports/litex/action.yml +++ /dev/null @@ -1,10 +0,0 @@ -name: Fetch litex port deps - -runs: - using: composite - steps: - - name: Get litex toolchain - run: | - wget https://static.dev.sifive.com/dev-tools/riscv64-unknown-elf-gcc-8.3.0-2019.08.0-x86_64-linux-centos6.tar.gz - sudo tar -C /usr --strip-components=1 -xaf riscv64-unknown-elf-gcc-8.3.0-2019.08.0-x86_64-linux-centos6.tar.gz - shell: bash diff --git a/.github/actions/deps/ports/nordic/action.yml b/.github/actions/deps/ports/nordic/action.yml index 5f08b17ca7a..96754be9507 100644 --- a/.github/actions/deps/ports/nordic/action.yml +++ b/.github/actions/deps/ports/nordic/action.yml @@ -5,7 +5,7 @@ runs: steps: - name: Get nrfutil 7+ run: | - wget https://developer.nordicsemi.com/.pc-tools/nrfutil/x64-linux/nrfutil + wget https://files.nordicsemi.com/artifactory/swtools/external/nrfutil/executables/x86_64-unknown-linux-gnu/nrfutil chmod +x nrfutil ./nrfutil install nrf5sdk-tools mkdir -p $HOME/.local/bin diff --git a/.github/actions/deps/ports/zephyr-cp/action.yml b/.github/actions/deps/ports/zephyr-cp/action.yml index cfa1177598e..b39cc49e592 100644 --- a/.github/actions/deps/ports/zephyr-cp/action.yml +++ b/.github/actions/deps/ports/zephyr-cp/action.yml @@ -1,15 +1,53 @@ name: Fetch Zephyr port deps +inputs: + sdl: + description: 'Install the 32-bit SDL2 packages native_sim needs' + required: false + default: 'false' + runs: using: composite steps: + - name: Show CPU model + if: runner.os == 'Linux' + run: grep "model name" /proc/cpuinfo | head -1 + shell: bash + - name: Get Linux build dependencies + if: runner.os == 'Linux' + uses: ./.github/actions/deps/apt_packages + with: + # The last four are the packages action-zephyr-setup@v1 installs, so its apt-get has nothing to download. + packages: libusb-1.0-0-dev libudev-dev pkg-config mtools ccache gperf libc6-dev-i386 g++-multilib + - name: Prepare for 32-bit SDL2 + if: runner.os == 'Linux' && inputs.sdl == 'true' + run: | + sudo dpkg --add-architecture i386 + # We have to hold python3 so the following install works. See https://github.com/actions/runner-images/issues/13803 + sudo apt-mark hold python3 + echo "PKG_CONFIG_PATH=/usr/lib/i386-linux-gnu/pkgconfig${PKG_CONFIG_PATH:+:$PKG_CONFIG_PATH}" >> $GITHUB_ENV + shell: bash + - name: Get SDL2 for native_sim + if: runner.os == 'Linux' && inputs.sdl == 'true' + uses: ./.github/actions/deps/apt_packages + with: + packages: libsdl2-dev:i386 libsdl2-image-dev:i386 - name: Setup Zephyr project uses: zephyrproject-rtos/action-zephyr-setup@v1 with: app-path: zephyr-config base-path: ports/zephyr-cp - toolchains: arm-zephyr-eabi + toolchains: arm-zephyr-eabi:riscv64-zephyr-elf + # The action's ccache stores a new ~150 MB entry per board job under one key + # shared by every board, and each job restores whichever entry was saved last. + # Measured across all 30 boards: hits on 5 boards by luck, none on the other 25, + # and no build-time difference either way. The entries were filling the + # repository's 10 GB Actions cache and evicting the SDK and other caches. + enable-ccache: false - name: Export cmake info run: west zephyr-export shell: bash working-directory: ports/zephyr-cp + - name: Install Zephyr protobuf dependency + run: pip install protobuf==6.33.5 + shell: bash diff --git a/.github/actions/deps/python/action.yml b/.github/actions/deps/python/action.yml index da59b87b17a..bc8b578c147 100644 --- a/.github/actions/deps/python/action.yml +++ b/.github/actions/deps/python/action.yml @@ -16,7 +16,7 @@ runs: - name: Cache python dependencies id: cache-python-deps if: inputs.action == 'cache' - uses: actions/cache@v4 + uses: actions/cache@v5 with: path: .cp_tools key: ${{ runner.os }}-${{ env.pythonLocation }}-tools-cp-${{ hashFiles('requirements-dev.txt') }} @@ -24,7 +24,7 @@ runs: - name: Restore python dependencies id: restore-python-deps if: inputs.action == 'restore' - uses: actions/cache/restore@v4 + uses: actions/cache/restore@v5 with: path: .cp_tools key: ${{ runner.os }}-${{ env.pythonLocation }}-tools-cp-${{ hashFiles('requirements-dev.txt') }} diff --git a/.github/actions/deps/submodules/action.yml b/.github/actions/deps/submodules/action.yml index eed83af41f4..65a303f71c5 100644 --- a/.github/actions/deps/submodules/action.yml +++ b/.github/actions/deps/submodules/action.yml @@ -12,6 +12,12 @@ inputs: default: '["extmod/ulab", "lib/", "tools/"]' type: string + port: + description: 'Also cache the submodules of this port, in their own entry' + required: false + default: '' + type: string + action: description: 'The cache action to use' required: false @@ -48,7 +54,7 @@ runs: - name: Cache submodules if: ${{ inputs.action == 'cache' }} - uses: actions/cache@v4 + uses: actions/cache@v5 with: path: ".git/modules/\n${{ join(fromJSON(steps.create-submodule-status.outputs.submodules), '\n') }}" key: submodules-common-${{ hashFiles('submodule_status') }} @@ -56,14 +62,33 @@ runs: - name: Restore submodules if: ${{ inputs.action == 'restore' }} - uses: actions/cache/restore@v4 + uses: actions/cache/restore@v5 with: path: ".git/modules/\n${{ join(fromJSON(steps.create-submodule-status.outputs.submodules), '\n') }}" key: submodules-common-${{ hashFiles('submodule_status') }} enableCrossOsArchive: true + - name: Port submodule status + id: port-submodule-status + # The ports whose board jobs clone the most over the network: 29 CMSIS and HAL + # repositories on stm, the sdk and lwip on raspberrypi and mimxrt10xx. espressif + # and zephyr-cp fetch theirs in their own way; the rest have little to gain. + if: ${{ contains(fromJSON('["stm", "raspberrypi", "mimxrt10xx"]'), inputs.port) }} + run: | + git submodule status ports/${{ inputs.port }} > port_submodule_status + echo $(cut -d ' ' -f 2 port_submodule_status) | echo "submodules=[\"$(sed "s/ /\", \"/g")\"]" >> $GITHUB_OUTPUT + shell: bash + + - name: Cache port submodules + if: ${{ steps.port-submodule-status.outcome == 'success' }} + uses: actions/cache@v5 + with: + path: ".git/modules/ports/${{ inputs.port }}\n${{ join(fromJSON(steps.port-submodule-status.outputs.submodules), '\n') }}" + key: submodules-${{ inputs.port }}-${{ hashFiles('port_submodule_status') }} + enableCrossOsArchive: true + - name: Remove submodule status - run: rm submodule_status + run: rm -f submodule_status port_submodule_status shell: bash - name: CircuitPython dependencies diff --git a/.github/actions/mpy_cross/action.yml b/.github/actions/mpy_cross/action.yml index 8839f790915..1eda5855353 100644 --- a/.github/actions/mpy_cross/action.yml +++ b/.github/actions/mpy_cross/action.yml @@ -16,7 +16,7 @@ runs: id: download-mpy-cross if: inputs.download == 'true' continue-on-error: true - uses: actions/download-artifact@v4 + uses: actions/download-artifact@v8 with: name: mpy-cross path: mpy-cross/build @@ -28,7 +28,7 @@ runs: - name: Build mpy-cross if: inputs.download == 'false' || steps.download-mpy-cross.outcome == 'failure' - run: make -C mpy-cross -j4 + run: make -C mpy-cross -j$(nproc) shell: bash env: CP_VERSION: ${{ inputs.cp-version }} @@ -36,7 +36,7 @@ runs: - name: Upload mpy-cross if: inputs.download == 'false' || steps.download-mpy-cross.outcome == 'failure' continue-on-error: true - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v7 with: name: mpy-cross path: mpy-cross/build/mpy-cross diff --git a/.github/workflows/build-board-custom.yml b/.github/workflows/build-board-custom.yml index bf18d7d7259..2f8c0f68d8c 100644 --- a/.github/workflows/build-board-custom.yml +++ b/.github/workflows/build-board-custom.yml @@ -70,9 +70,9 @@ jobs: run: | > custom-build && git add custom-build - name: Set up python - uses: actions/setup-python@v5 + uses: actions/setup-python@v6 with: - python-version: 3.x + python-version: "3.14" # minify_html has no Python 3.15 wheel yet - name: Board to port id: board-to-port run: | @@ -121,10 +121,10 @@ jobs: BOARD: ${{ inputs.board }} FLAGS: ${{ inputs.flags }} DEBUG: ${{ inputs.debug && '1' || '0' }} - run: make -j4 $FLAGS BOARD="$BOARD" DEBUG=$DEBUG TRANSLATION="$TRANSLATION" + run: make -j$(nproc) $FLAGS BOARD="$BOARD" DEBUG=$DEBUG TRANSLATION="$TRANSLATION" working-directory: ports/${{ steps.board-to-port.outputs.port }} - name: Upload artifact - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v7 with: name: ${{ inputs.board }}-${{ inputs.language }}-${{ inputs.version }}${{ inputs.flags != '' && '-custom' || '' }}${{ inputs.debug && '-debug' || '' }} path: ports/${{ steps.board-to-port.outputs.port }}/build-${{ inputs.board }}/firmware.* diff --git a/.github/workflows/build-boards.yml b/.github/workflows/build-boards.yml index 7e5156d4011..0610103faa4 100644 --- a/.github/workflows/build-boards.yml +++ b/.github/workflows/build-boards.yml @@ -24,12 +24,12 @@ jobs: env: CP_VERSION: ${{ inputs.cp-version }} strategy: - fail-fast: false + fail-fast: ${{ github.event_name == 'merge_group' }} matrix: board: ${{ fromJSON(inputs.boards) }} steps: - name: Set up repository - uses: actions/checkout@v4 + uses: actions/checkout@v6 with: submodules: false show-progress: false @@ -37,9 +37,9 @@ jobs: persist-credentials: false - name: Set up python - uses: actions/setup-python@v5 + uses: actions/setup-python@v6 with: - python-version: 3.x + python-version: ${{ inputs.port == 'zephyr-cp' && '3.13' || '3.14' }} # minify_html has no Python 3.15 wheel yet - name: Set up port id: set-up-port @@ -51,6 +51,8 @@ jobs: - name: Set up submodules id: set-up-submodules uses: ./.github/actions/deps/submodules + with: + port: ${{ inputs.port }} - name: Set up external uses: ./.github/actions/deps/external @@ -87,11 +89,22 @@ jobs: HEAD_COMMIT_MESSAGE: ${{ github.event.head_commit.message }} - name: Upload artifact - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v7 with: name: ${{ matrix.board }} path: bin/${{ matrix.board }} + - name: Upload firmware sizes + # "zz-" sorts the size records after every board in the run's artifact list. + if: ${{ always() }} + uses: actions/upload-artifact@v7 + with: + name: zz-sizes-${{ matrix.board }} + path: sizes/${{ matrix.board }}.json + if-no-files-found: ignore + # build-ci merges these into the 0-sizes reports; delete them after one day. + retention-days: 1 + - name: Upload to S3 uses: ./.github/actions/upload_aws with: diff --git a/.github/workflows/build-mpy-cross.yml b/.github/workflows/build-mpy-cross.yml index 831ad308227..a338632cfea 100644 --- a/.github/workflows/build-mpy-cross.yml +++ b/.github/workflows/build-mpy-cross.yml @@ -16,7 +16,7 @@ jobs: build: runs-on: ubuntu-24.04 strategy: - fail-fast: false + fail-fast: ${{ github.event_name == 'merge_group' }} matrix: mpy-cross: ["static", "static-aarch64", "static-mingw", "static-raspbian"] env: @@ -28,16 +28,16 @@ jobs: OS_static-raspbian: linux-raspbian steps: - name: Set up repository - uses: actions/checkout@v4 + uses: actions/checkout@v6 with: submodules: false show-progress: false fetch-depth: 1 persist-credentials: false - name: Set up python - uses: actions/setup-python@v5 + uses: actions/setup-python@v6 with: - python-version: 3.x + python-version: "3.14" # minify_html has no Python 3.15 wheel yet - name: Set up submodules uses: ./.github/actions/deps/submodules with: @@ -45,17 +45,17 @@ jobs: - name: Install toolchain (aarch64) if: matrix.mpy-cross == 'static-aarch64' - run: | - sudo apt-get update - sudo apt-get install -y gcc-aarch64-linux-gnu + uses: ./.github/actions/deps/apt_packages + with: + packages: gcc-aarch64-linux-gnu - name: Install toolchain (mingw) if: matrix.mpy-cross == 'static-mingw' - run: | - sudo apt-get update - sudo apt-get install -y mingw-w64 + uses: ./.github/actions/deps/apt_packages + with: + packages: gcc-mingw-w64-x86-64-win32 - name: Build mpy-cross.${{ matrix.mpy-cross }} - run: make -C mpy-cross -j4 -f Makefile.${{ matrix.mpy-cross }} + run: make -C mpy-cross -j$(nproc) -f Makefile.${{ matrix.mpy-cross }} - name: Set output env: @@ -66,7 +66,7 @@ jobs: echo >> $GITHUB_ENV "OS=$OS" - name: Upload artifact - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v7 with: name: mpy-cross.${{ env.EX }} path: mpy-cross/build-${{ matrix.mpy-cross }}/mpy-cross.${{ env.EX }} diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index eb6a9a0c263..cf29a7b677e 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -6,12 +6,17 @@ name: Build CI on: push: + branches: + - main + - '*.x' pull_request: + merge_group: + types: [checks_requested] release: types: [published] concurrency: - group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.head_ref || github.ref || github.run_id }} cancel-in-progress: true jobs: @@ -19,8 +24,10 @@ jobs: runs-on: ubuntu-24.04 outputs: docs: ${{ steps.set-matrix.outputs.docs }} + zephyr-tests: ${{ steps.set-matrix.outputs.zephyr-tests }} + tests: ${{ steps.set-matrix.outputs.tests }} + mpy-cross: ${{ steps.set-matrix.outputs.mpy-cross }} ports: ${{ steps.set-matrix.outputs.ports }} - windows: ${{ steps.set-matrix.outputs.windows }} cp-version: ${{ steps.set-up-submodules.outputs.version }} steps: - name: Dump GitHub context @@ -28,16 +35,16 @@ jobs: env: GITHUB_CONTEXT: ${{ toJson(github) }} - name: Set up repository - uses: actions/checkout@v4 + uses: actions/checkout@v6 with: submodules: false show-progress: false fetch-depth: 1 persist-credentials: false - name: Set up python - uses: actions/setup-python@v5 + uses: actions/setup-python@v6 with: - python-version: 3.x + python-version: "3.14" # minify_html has no Python 3.15 wheel yet - name: Duplicate USB VID/PID check run: python3 -u -m tools.ci_check_duplicate_usb_vid_pid - name: Set up submodules @@ -66,15 +73,15 @@ jobs: GITHUB_TOKEN: ${{ github.token }} EXCLUDE_COMMIT: ${{ github.event.pull_request.head.sha }} - name: Set head sha (pull) - if: github.event_name == 'pull_request' + if: github.event_name == 'pull_request' || github.event_name == 'merge_group' env: - HEAD_SHA: ${{ github.event.pull_request.head.sha }} + HEAD_SHA: ${{ github.event.pull_request.head.sha || github.event.merge_group.head_sha }} run: echo "HEAD_SHA=$HEAD_SHA" >> $GITHUB_ENV - name: Set base sha (pull) - if: github.event_name == 'pull_request' + if: github.event_name == 'pull_request' || github.event_name == 'merge_group' run: git cat-file -e $SHA && echo "BASE_SHA=$SHA" >> $GITHUB_ENV || true env: - SHA: ${{ steps.get-last-commit-with-checks.outputs.commit_sha || github.event.pull_request.base.sha }} + SHA: ${{ steps.get-last-commit-with-checks.outputs.commit_sha || github.event.pull_request.base.sha || github.event.merge_group.base_sha }} - name: Set head sha (push) if: github.event_name == 'push' env: @@ -94,36 +101,44 @@ jobs: tests: needs: scheduler + if: needs.scheduler.outputs.tests == 'True' uses: ./.github/workflows/run-tests.yml with: cp-version: ${{ needs.scheduler.outputs.cp-version }} + zephyr-tests: + needs: scheduler + if: needs.scheduler.outputs.zephyr-tests == 'True' + uses: ./.github/workflows/run-zephyr-tests.yml + with: + cp-version: ${{ needs.scheduler.outputs.cp-version }} + mpy-cross: needs: scheduler - if: needs.scheduler.outputs.ports != '{}' + if: needs.scheduler.outputs.mpy-cross == 'True' uses: ./.github/workflows/build-mpy-cross.yml secrets: inherit with: cp-version: ${{ needs.scheduler.outputs.cp-version }} mpy-cross-mac: - runs-on: macos-13 + runs-on: macos-latest needs: scheduler - if: needs.scheduler.outputs.ports != '{}' + if: needs.scheduler.outputs.mpy-cross == 'True' env: CP_VERSION: ${{ needs.scheduler.outputs.cp-version }} steps: - name: Set up repository - uses: actions/checkout@v4 + uses: actions/checkout@v6 with: submodules: false show-progress: false fetch-depth: 1 persist-credentials: false - name: Set up python - uses: actions/setup-python@v5 + uses: actions/setup-python@v6 with: - python-version: 3.x + python-version: "3.14" # minify_html has no Python 3.15 wheel yet - name: Set up submodules uses: ./.github/actions/deps/submodules - name: Versions @@ -131,33 +146,18 @@ jobs: gcc --version python3 --version msgfmt --version - - name: Build mpy-cross - run: make -C mpy-cross -j4 - - uses: actions/upload-artifact@v4 - with: - name: mpy-cross-macos-x64 - path: mpy-cross/build/mpy-cross - name: Build mpy-cross (arm64) - run: make -C mpy-cross -j4 -f Makefile.m1 V=2 - - uses: actions/upload-artifact@v4 + run: make -C mpy-cross -j$(sysctl -n hw.ncpu) -f Makefile.m1 V=2 + - uses: actions/upload-artifact@v7 with: name: mpy-cross-macos-arm64 path: mpy-cross/build-arm64/mpy-cross-arm64 - - name: Make universal binary - run: lipo -create -output mpy-cross-macos-universal mpy-cross/build/mpy-cross mpy-cross/build-arm64/mpy-cross-arm64 - - name: Upload artifact - uses: actions/upload-artifact@v4 - with: - name: mpy-cross-macos-universal - path: mpy-cross-macos-universal - name: Upload to S3 if: >- (github.event_name == 'push' && github.ref == 'refs/heads/main' && github.repository_owner == 'adafruit') || (github.event_name == 'release' && (github.event.action == 'published' || github.event.action == 'rerequested')) run: | - [ -z "$AWS_ACCESS_KEY_ID" ] || aws s3 cp mpy-cross-macos-universal s3://adafruit-circuit-python/bin/mpy-cross/macos/mpy-cross-macos-"${CP_VERSION}"-universal --no-progress --region us-east-1 [ -z "$AWS_ACCESS_KEY_ID" ] || aws s3 cp mpy-cross/build-arm64/mpy-cross-arm64 s3://adafruit-circuit-python/bin/mpy-cross/macos/mpy-cross-macos-"${CP_VERSION}"-arm64 --no-progress --region us-east-1 - [ -z "$AWS_ACCESS_KEY_ID" ] || aws s3 cp mpy-cross/build/mpy-cross s3://adafruit-circuit-python/bin/mpy-cross/macos/mpy-cross-macos-"${CP_VERSION}"-x64 --no-progress --region us-east-1 env: AWS_PAGER: '' AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} @@ -171,41 +171,42 @@ jobs: CP_VERSION: ${{ needs.scheduler.outputs.cp-version }} steps: - name: Set up repository - uses: actions/checkout@v4 + uses: actions/checkout@v6 with: submodules: false show-progress: false fetch-depth: 1 persist-credentials: false - name: Set up python - uses: actions/setup-python@v5 + uses: actions/setup-python@v6 with: - python-version: 3.x + python-version: "3.14" # minify_html has no Python 3.15 wheel yet - name: Set up submodules uses: ./.github/actions/deps/submodules with: version: true - name: Install dependencies - run: | - sudo apt-get update - sudo apt-get install -y latexmk librsvg2-bin texlive-fonts-recommended texlive-latex-recommended texlive-latex-extra - pip install -r requirements-doc.txt + uses: ./.github/actions/deps/apt_packages + with: + packages: latexmk librsvg2-bin texlive-fonts-recommended texlive-latex-recommended texlive-latex-extra + - name: Install Python dependencies + run: pip install -r requirements-doc.txt - name: Build and Validate Stubs - run: make check-stubs -j4 - - uses: actions/upload-artifact@v4 + run: make check-stubs -j$(nproc) + - uses: actions/upload-artifact@v7 with: name: stubs path: circuitpython-stubs/dist/* - name: Test Documentation Build (HTML) - run: sphinx-build -E -W -b html -D version="$CP_VERSION" -D release="$CP_VERSION" . _build/html - - uses: actions/upload-artifact@v4 + run: sphinx-build -E -W -j auto -b html -D version="$CP_VERSION" -D release="$CP_VERSION" . _build/html + - uses: actions/upload-artifact@v7 with: name: docs-html path: _build/html - name: Test Documentation Build (LaTeX/PDF) run: | make latexpdf - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@v7 with: name: docs-latexpdf path: _build/latex @@ -226,118 +227,114 @@ jobs: [ -z "$TWINE_USERNAME" ] || echo "Uploading dev release to PyPi" [ -z "$TWINE_USERNAME" ] || twine upload circuitpython-stubs/dist/* - windows: - runs-on: windows-2022 - needs: scheduler - if: needs.scheduler.outputs.windows == 'True' - env: - CP_VERSION: ${{ needs.scheduler.outputs.cp-version }} - defaults: - run: - # We define a custom shell script here, although `msys2.cmd` does neither exist nor is it available in the PATH yet - shell: msys2 {0} - steps: - # We want to change the configuration of the git command that actions/checkout will be using - # (since it is not possible to set autocrlf through the action yet, see actions/checkout#226). - - run: git config --global core.autocrlf input - shell: bash - - name: Check python coding (cmd) - run: python -c "import sys, locale; print(sys.getdefaultencoding(), locale.getpreferredencoding(False))" - shell: cmd - # We use a JS Action, which calls the system terminal or other custom terminals directly, if required - - uses: msys2/setup-msys2@v2 - with: - install: base-devel git wget unzip gcc python-pip - # The goal of this was to test how things worked when the default file encoding (locale.getpreferedencoding()) - # was not UTF-8. However, msys2 python does use utf-8 as the preferred file encoding, and using actions/setup-python - # python3.8 gave a broken build, so we're not really testing what we wanted to test. - # However, commandline length limits are being tested so that does some good. - - name: Check python coding (msys2) - run: | - locale -v - which python; python --version - python -c "import sys, locale; print(sys.getdefaultencoding(), locale.getpreferredencoding(False))" - which python3; python3 --version - python3 -c "import sys, locale; print(sys.getdefaultencoding(), locale.getpreferredencoding(False))" - - name: Install dependencies - run: | - wget --no-verbose -O gcc-arm.zip https://developer.arm.com/-/media/Files/downloads/gnu/13.2.rel1/binrel/arm-gnu-toolchain-13.2.rel1-mingw-w64-i686-arm-none-eabi.zip - unzip -q -d /tmp gcc-arm.zip - tar -C /tmp/arm-gnu-toolchain* -cf - . | tar -C /usr/local -xf - - # We could use a venv instead, but that requires entering the venv on each run step - # that runs in its own shell. There are some actions that help with that, but not for msys2 - # that I can find. (dhalbert) - pip install --break-system-packages wheel - # requirements-dev.txt doesn't install on windows. (with msys2 python) - # instead, pick a subset for what we want to do - pip install --break-system-packages cascadetoml jinja2 typer click intelhex - # check that installed packages work....? - which python; python --version; python -c "import cascadetoml" - which python3; python3 --version; python3 -c "import cascadetoml" - - name: Set up repository - uses: actions/checkout@v4 - with: - submodules: false - show-progress: false - fetch-depth: 1 - persist-credentials: false - - name: Set up submodules - uses: ./.github/actions/deps/submodules - - name: build mpy-cross - run: make -j4 -C mpy-cross - - name: build rp2040 - run: make -j4 -C ports/raspberrypi BOARD=adafruit_feather_rp2040 TRANSLATION=de_DE - - name: build samd21 - run: make -j4 -C ports/atmel-samd BOARD=feather_m0_express TRANSLATION=zh_Latn_pinyin - - name: build samd51 - run: make -j4 -C ports/atmel-samd BOARD=feather_m4_express TRANSLATION=es - - name: build nordic - run: make -j4 -C ports/nordic BOARD=feather_nrf52840_express TRANSLATION=fr - - name: build stm - run: make -j4 -C ports/stm BOARD=feather_stm32f405_express TRANSLATION=pt_BR - # I gave up trying to do esp builds on windows when I saw - # ERROR: Platform MINGW64_NT-10.0-17763-x86_64 appears to be unsupported - # https://github.com/espressif/esp-idf/issues/7062 - - windows-zephyr: + ports: + needs: [scheduler, tests] + # Without !failure() and !cancelled(), a skipped tests job would skip this job too. + if: ${{ !failure() && !cancelled() && needs.scheduler.outputs.ports != '{}' }} + uses: ./.github/workflows/build-boards.yml + secrets: inherit strategy: + fail-fast: ${{ github.event_name == 'merge_group' }} + max-parallel: 55 matrix: - os: [windows-2022, windows-2025] - runs-on: ${{ matrix.os }} - needs: scheduler - if: needs.scheduler.outputs.windows == 'True' + port: ${{ fromJSON(needs.scheduler.outputs.ports).ports }} + with: + boards: ${{ toJSON(fromJSON(needs.scheduler.outputs.ports)[matrix.port]) }} + cp-version: ${{ needs.scheduler.outputs.cp-version }} + port: ${{ fromJSON(needs.scheduler.outputs.ports).split_ports[matrix.port] || matrix.port }} + + build-ci: + # Final gate for ruleset checks: always runs so the required check is + # reported, and fails if any job (or matrix leg) failed or was cancelled. + needs: [scheduler, tests, zephyr-tests, mpy-cross, mpy-cross-mac, docs, ports] + if: ${{ always() }} + runs-on: ubuntu-24.04 env: CP_VERSION: ${{ needs.scheduler.outputs.cp-version }} steps: + # Firmware size report. Each board job uploads its sizes/.json as zz-sizes-; + # merge them into one table and a job summary. This is reporting only, so none of it + # may fail the gate: every step continues on error. - name: Set up repository - uses: actions/checkout@v4 + continue-on-error: true + uses: actions/checkout@v6 with: submodules: false show-progress: false fetch-depth: 1 persist-credentials: false - - uses: actions/setup-python@v5 + + # actions/download-artifact matches a pattern against a listing of the run's + # artifacts that stops at 1000, and a full build has more. The script fetches each + # board's record by exact name instead, from the board list the scheduler produced. + # It runs from github-script because only action steps get the artifact API token. + - name: Install the artifact client + continue-on-error: true + run: npm install --no-save --no-package-lock --no-audit --no-fund @actions/artifact@6 + + - name: Download firmware sizes + continue-on-error: true + uses: actions/github-script@v9 + env: + BOARDS: ${{ needs.scheduler.outputs.ports }} with: - python-version: '3.13' - - name: Set up Zephyr - uses: ./.github/actions/deps/ports/zephyr-cp - - name: Set up submodules - uses: ./.github/actions/deps/submodules - - name: build mpy-cross - run: make -j4 -C mpy-cross - - name: build ek_ra8d1 - run: make -j4 -C ports/zephyr-cp BOARD=renesas_ek_ra8d1 + script: | + const { pathToFileURL } = require("node:url"); + const sizes = await import(pathToFileURL(`${process.env.GITHUB_WORKSPACE}/tools/ci_download_sizes.mjs`)); + await sizes.downloadSizes({ + boards: sizes.boardsFromSchedule(JSON.parse(process.env.BOARDS || "{}")), + outDir: "sizes", + info: core.info, + warning: core.warning, + }); - ports: - needs: [scheduler, mpy-cross, tests] - if: needs.scheduler.outputs.ports != '{}' - uses: ./.github/workflows/build-boards.yml - secrets: inherit - strategy: - fail-fast: false - matrix: - port: ${{ fromJSON(needs.scheduler.outputs.ports).ports }} - with: - boards: ${{ toJSON(fromJSON(needs.scheduler.outputs.ports)[matrix.port]) }} - cp-version: ${{ needs.scheduler.outputs.cp-version }} - port: ${{ matrix.port }} + - name: Summarize firmware sizes + continue-on-error: true + run: python3 tools/ci_firmware_sizes.py sizes sizes-report + + # Uploaded unzipped, one file per artifact, so each opens directly; with + # `archive: false` the file name is the artifact name. + - name: Upload firmware size report (HTML) + continue-on-error: true + uses: actions/upload-artifact@v7 + with: + path: sizes-report/0-sizes.html + archive: false + if-no-files-found: ignore + + - name: Upload firmware size report (JSON) + continue-on-error: true + uses: actions/upload-artifact@v7 + with: + path: sizes-report/0-sizes.json + archive: false + if-no-files-found: ignore + + # The action itself only uploads on pushes to main and release branches and on + # published releases. The S3 names carry the version, so the directory keeps a history. + - name: Upload firmware size report to S3 (HTML) + continue-on-error: true + uses: ./.github/actions/upload_aws + with: + source: sizes-report/0-sizes.html + destination: 0-sizes/adafruit-circuitpython-sizes-${{ env.CP_VERSION }}.html + AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + + - name: Upload firmware size report to S3 (JSON) + continue-on-error: true + uses: ./.github/actions/upload_aws + with: + source: sizes-report/0-sizes.json + destination: 0-sizes/adafruit-circuitpython-sizes-${{ env.CP_VERSION }}.json + AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + + - name: Check build results + run: | + echo "Job results: ${{ toJSON(needs.*.result) }}" + if [[ "${{ contains(needs.*.result, 'failure') }}" == "true" ]] || [[ "${{ contains(needs.*.result, 'cancelled') }}" == "true" ]]; then + echo "One or more jobs failed or were cancelled" + exit 1 + fi + echo "All build jobs succeeded" diff --git a/.github/workflows/bundle_cron.yml b/.github/workflows/bundle_cron.yml new file mode 100644 index 00000000000..eefffaaa5b9 --- /dev/null +++ b/.github/workflows/bundle_cron.yml @@ -0,0 +1,58 @@ +# SPDX-FileCopyrightText: 2019 Michael Schroeder +# +# SPDX-License-Identifier: MIT + +name: Update Bundles + +on: + schedule: + - cron: 0 5 * * * + workflow_dispatch: + +jobs: + check-repo-owner: + # This job is so the entire workflow will end successfully and give some + # output to explain why it hasn't run on a non-Adafruit fork. + runs-on: ubuntu-latest + steps: + - name: repository + env: + OWNER_IS_ADAFRUIT: ${{ startswith(github.repository, 'adafruit/') }} + run: | + echo "This workflow will only run if Adafruit is the repository owner." + echo "Repository owner is Adafruit: $OWNER_IS_ADAFRUIT" + update-bundles: + runs-on: ubuntu-latest + # Only run the build on Adafruit's repository. Forks won't have the secrets. + # It's necessary to do this here, since 'schedule' events cannot (currently) + # be limited (they run on all forks' default branches). + if: startswith(github.repository, 'adafruit/') + steps: + - name: Set up Python 3.12 + uses: actions/setup-python@v6 + with: + python-version: 3.12 + - name: Load contributor cache + uses: actions/cache@v5 + with: + key: "contributor-cache" + path: "contributors.json" + - name: Versions + run: | + python3 --version + - uses: actions/checkout@v6 + with: + repository: 'adafruit/adabot' + submodules: true + - name: Install deps + run: | + pip install -r requirements.txt + - name: Run adabot.circuitpython_bundle + env: + ADABOT_EMAIL: ${{ secrets.ADABOT_EMAIL }} + ADABOT_GITHUB_USER: ${{ secrets.ADABOT_GITHUB_USER }} + ADABOT_GITHUB_ACCESS_TOKEN: ${{ secrets.ADABOT_GITHUB_ACCESS_TOKEN }} + BIGQUERY_PRIVATE_KEY: ${{ secrets.BIGQUERY_PRIVATE_KEY }} + BIGQUERY_CLIENT_EMAIL: ${{ secrets.BIGQUERY_CLIENT_EMAIL }} + run: | + python3 -u -m adabot.circuitpython_bundle diff --git a/.github/workflows/create-website-pr.yml b/.github/workflows/create-website-pr.yml index 32c1792fa6c..25e4943d549 100644 --- a/.github/workflows/create-website-pr.yml +++ b/.github/workflows/create-website-pr.yml @@ -17,16 +17,16 @@ jobs: env: GITHUB_CONTEXT: ${{ toJson(github) }} - name: Set up repository - uses: actions/checkout@v4 + uses: actions/checkout@v6 with: submodules: false show-progress: false fetch-depth: 1 persist-credentials: false - name: Set up python - uses: actions/setup-python@v5 + uses: actions/setup-python@v6 with: - python-version: 3.x + python-version: "3.14" # minify_html has no Python 3.15 wheel yet - name: Set up submodules uses: ./.github/actions/deps/submodules with: diff --git a/.github/workflows/learn_cron.yml b/.github/workflows/learn_cron.yml new file mode 100644 index 00000000000..135089bfd5e --- /dev/null +++ b/.github/workflows/learn_cron.yml @@ -0,0 +1,41 @@ +# SPDX-FileCopyrightText: 2021 Jeff Epler for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +name: Tag Learning System Guides + +on: + schedule: + - cron: 0 5 * * * + +jobs: + check-repo-owner: + # This job is so the entire workflow will end successfully and give some + # output to explain why it hasn't run on a non-Adafruit fork. + runs-on: ubuntu-latest + if: ${{ (github.repository_owner != 'adafruit') }} + steps: + - run: | + echo "This workflow is only intended to run in the adafruit fork" + + update-learn: + runs-on: ubuntu-latest + # Only run the build if the access token has been configured. This will be + # the case on Adafruit's repository. It's necessary to do this here, since + # 'schedule' events cannot (currently) be limited (they run on all forks' + # default branches). + if: ${{ (github.repository_owner == 'adafruit') }} + steps: + - uses: actions/checkout@v6 + with: + repository: ${{ github.repository_owner }}/Adafruit_Learning_System_Guides + token: ${{ secrets.ADABOT_GITHUB_ACCESS_TOKEN }} + - name: Tag a release + env: + ADABOT_EMAIL: ${{ secrets.ADABOT_EMAIL }} + run: | + git config --global user.name adabot + git config --global user.email "$ADABOT_EMAIL" + TAG_NAME=`date +%Y%m%d` + git tag $TAG_NAME + git push origin $TAG_NAME diff --git a/.github/workflows/notify-on-issue-label.yml b/.github/workflows/notify-on-issue-label.yml index da1ac0a18e2..2465851e35b 100644 --- a/.github/workflows/notify-on-issue-label.yml +++ b/.github/workflows/notify-on-issue-label.yml @@ -10,7 +10,7 @@ jobs: permissions: issues: write steps: - - uses: tekktrik/issue-labeled-ping@v1 + - uses: tekktrik/issue-labeled-ping@v3 with: github-token: ${{ secrets.GITHUB_TOKEN }} user: v923z diff --git a/.github/workflows/pre-commit.yml b/.github/workflows/pre-commit.yml index 778270dc08c..c7cb7be69c7 100644 --- a/.github/workflows/pre-commit.yml +++ b/.github/workflows/pre-commit.yml @@ -6,10 +6,14 @@ name: pre-commit on: push: + branches-ignore: + - 'gh-readonly-queue/**' pull_request: + merge_group: + types: [checks_requested] concurrency: - group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.head_ref || github.ref || github.run_id }} cancel-in-progress: true jobs: @@ -17,24 +21,24 @@ jobs: runs-on: ubuntu-24.04 steps: - name: Set up repository - uses: actions/checkout@v4 + uses: actions/checkout@v6 with: submodules: false show-progress: false fetch-depth: 1 persist-credentials: false - name: Set up python - uses: actions/setup-python@v5 + uses: actions/setup-python@v6 with: - python-version: 3.x + python-version: "3.14" # minify_html has no Python 3.15 wheel yet - name: Set up submodules uses: ./.github/actions/deps/submodules - name: Set up external uses: ./.github/actions/deps/external - name: Install dependencies - run: | - sudo apt-get update - sudo apt-get install -y gettext + uses: ./.github/actions/deps/apt_packages + with: + packages: gettext - name: Run pre-commit uses: pre-commit/action@v3.0.1 - name: Make patch @@ -42,7 +46,7 @@ jobs: run: git diff > ~/pre-commit.patch - name: Upload patch if: failure() - uses: actions/upload-artifact@v4 + uses: actions/upload-artifact@v7 with: name: patch path: ~/pre-commit.patch diff --git a/.github/workflows/reports_cron.yml b/.github/workflows/reports_cron.yml new file mode 100644 index 00000000000..476ead95d25 --- /dev/null +++ b/.github/workflows/reports_cron.yml @@ -0,0 +1,91 @@ +# SPDX-FileCopyrightText: 2019 Michael Schroeder +# +# SPDX-License-Identifier: MIT + +name: Run Daily Reports + +on: + schedule: + # The actor (github.actor) that runs the cron job may be the user who created the cron job + # initially. It does not appear to be settable via a secret or environment variable. + - cron: 15 5 * * * + workflow_dispatch: + + +jobs: + check-repo-owner: + # This job is so the entire workflow will end successfully and give some + # output to explain why it hasn't run on a non-Adafruit fork. + runs-on: ubuntu-latest + steps: + - name: repository + env: + OWNER_IS_ADAFRUIT: ${{ startswith(github.repository, 'adafruit/') }} + run: | + echo "This workflow will only run if Adafruit is the repository owner." + echo "Repository owner is Adafruit: $OWNER_IS_ADAFRUIT" + run-reports: + runs-on: ubuntu-latest + # Only run the build on Adafruit's repository. Forks won't have the secrets. + # It's necessary to do this here, since 'schedule' events cannot (currently) + # be limited (they run on all forks' default branches). + if: startswith(github.repository, 'adafruit/') + env: + ADABOT_GITHUB_USER: ${{ secrets.ADABOT_GITHUB_USER }} + ADABOT_GITHUB_ACCESS_TOKEN: ${{ secrets.ADABOT_GITHUB_ACCESS_TOKEN }} + RTD_TOKEN: ${{ secrets.RTD_TOKEN }} + BIGQUERY_PRIVATE_KEY: ${{ secrets.BIGQUERY_PRIVATE_KEY }} + BIGQUERY_CLIENT_EMAIL: ${{ secrets.BIGQUERY_CLIENT_EMAIL }} + steps: + - name: Set up Python 3.11 + uses: actions/setup-python@v6 + with: + python-version: 3.11 + - name: Versions + run: | + python3 --version + - uses: actions/checkout@v6 + with: + repository: 'adafruit/adabot' + submodules: true + - name: Install deps + run: | + pip install -r requirements.txt + - name: Make Directory For Report Files + run: mkdir -p bin/adabot + - name: Set Date Variable + id: today + run: | + echo date=$( + date +%Y%m%d + ) >> $GITHUB_OUTPUT + - name: Run adabot.circuitpython_libraries + env: + # LIB_CHECK_CP_FILE is for circuitpython_libraries.py output + LIB_CHECK_CP_FILE: bin/adabot/circuitpython_library_report_${{ steps.today.outputs.date }}.txt + run: | + python3 -u -m adabot.circuitpython_libraries -o $LIB_CHECK_CP_FILE + continue-on-error: true + - name: Run adabot.circuitpython_library_download_stats + env: + # LIB_DL_STATS_FILE is for future Bundle and PyPi download stats script + LIB_DL_STATS_FILE: bin/adabot/library_download_stats_${{ steps.today.outputs.date }}.txt + run: | + python3 -u -m adabot.circuitpython_library_download_stats -o $LIB_DL_STATS_FILE + continue-on-error: true + - name: Run adabot.arduino_libraries + env: + # LIB_CHECK_ARD_FILE is for arduino_libraries.py output + LIB_CHECK_ARD_FILE: bin/adabot/arduino_library_report_${{ steps.today.outputs.date }}.txt + run: | + python3 -u -m adabot.arduino_libraries -o $LIB_CHECK_ARD_FILE + continue-on-error: true + - name: Check For Files + run: | + ls bin/adabot + - name: Upload Reports To AWS S3 + if: ${{ github.event_name != 'workflow_dispatch' }} + env: + AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }} + AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }} + run: "[ -z \"$AWS_ACCESS_KEY_ID\" ] || aws s3 cp bin/adabot/ s3://adafruit-circuit-python/adabot/bin/reports/ --recursive --no-progress --region us-east-1" diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index 80bfc72bd98..db4f5b0e316 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -11,7 +11,7 @@ jobs: run: runs-on: ubuntu-24.04 strategy: - fail-fast: false + fail-fast: ${{ github.event_name == 'merge_group' }} matrix: test: [all, mpy, native, native_mpy] env: @@ -23,46 +23,45 @@ jobs: TEST_native: --emit native TEST_native_mpy: --via-mpy --emit native -d basics float micropython steps: - - name: Set up repository - uses: actions/checkout@v4 - with: - submodules: false - show-progress: false - fetch-depth: 1 - - name: Set up python - uses: actions/setup-python@v5 - with: - python-version: 3.12 - - name: Set up submodules - uses: ./.github/actions/deps/submodules - with: - target: tests - - name: Set up external - if: matrix.test == 'all' - uses: ./.github/actions/deps/external - - name: Set up mpy-cross - uses: ./.github/actions/mpy_cross - with: - cp-version: ${{ inputs.cp-version }} - - name: Build unix port - run: make -C ports/unix VARIANT=coverage -j4 - - name: Run tests - run: ./run-tests.py -j4 ${{ env[format('TEST_{0}', matrix.test)] }} - working-directory: tests - - name: Print failure info - run: ./run-tests.py -j4 --print-failures - if: failure() - working-directory: tests - # Not working after MicroPython v1.23 merge. - # - name: Build native modules - # if: matrix.test == 'all' - # run: | - # make -C examples/natmod/features1 - # make -C examples/natmod/features2 - # make -C examples/natmod/heapq - # make -C examples/natmod/random - # make -C examples/natmod/re - # - name: Test native modules - # if: matrix.test == 'all' - # run: ./run-natmodtests.py extmod/{heapq*,random*,re*}.py - # working-directory: tests + - name: Set up repository + uses: actions/checkout@v6 + with: + submodules: false + show-progress: false + fetch-depth: 1 + - name: Set up python + uses: actions/setup-python@v6 + with: + python-version: 3.12 + - name: Set up submodules + uses: ./.github/actions/deps/submodules + with: + target: tests + - name: Set up external + if: matrix.test == 'all' + uses: ./.github/actions/deps/external + - name: Set up mpy-cross + uses: ./.github/actions/mpy_cross + with: + cp-version: ${{ inputs.cp-version }} + - name: Build unix port + run: make -C ports/unix VARIANT=coverage -j$(nproc) + - name: Run tests + run: ./run-tests.py -j$(nproc) ${{ env[format('TEST_{0}', matrix.test)] }} + working-directory: tests + - name: Print failure info + run: ./run-tests.py -j$(nproc) --print-failures + if: failure() + working-directory: tests + - name: Build native modules + if: matrix.test == 'all' + run: | + make -C examples/natmod/features1 + make -C examples/natmod/features2 + make -C examples/natmod/heapq + make -C examples/natmod/random + make -C examples/natmod/re + - name: Test native modules + if: matrix.test == 'all' + run: ./run-natmodtests.py extmod/{heapq*,random*,re*}.py + working-directory: tests diff --git a/.github/workflows/run-zephyr-tests.yml b/.github/workflows/run-zephyr-tests.yml new file mode 100644 index 00000000000..ab51e43a44a --- /dev/null +++ b/.github/workflows/run-zephyr-tests.yml @@ -0,0 +1,76 @@ +name: Run Zephyr tests + +on: + workflow_call: + inputs: + cp-version: + required: true + type: string + +jobs: + zephyr: + runs-on: ubuntu-24.04 + name: ${{ matrix.shard }} + strategy: + fail-fast: ${{ github.event_name == 'merge_group' }} + # One job per board, so each job builds one firmware. Each bsim suite is also split + # by the zephyr_sample marker, so the tests that build Zephyr samples get their own job. + matrix: + include: + - shard: native_sim + boards: native_native_sim + pytest_args: tests/ --ignore=tests/bsim -k 'not native_native_sim_asan and not native_native_sim_lfs and not native_native_sim_lvgl' -n $(nproc) --dist loadfile + - shard: native_sim_lvgl + boards: native_native_sim_lvgl + pytest_args: tests/ --ignore=tests/bsim -k 'native_native_sim_lvgl and not native_native_sim_lvgl_asan' -n $(nproc) --dist loadfile + - shard: native_sim_lvgl_asan + boards: native_native_sim_lvgl_asan + pytest_args: tests/ --ignore=tests/bsim -k native_native_sim_lvgl_asan -n $(nproc) --dist loadfile + - shard: native_sim_asan + boards: native_native_sim_asan + pytest_args: tests/ --ignore=tests/bsim -k native_native_sim_asan -n $(nproc) --dist loadfile + - shard: native_sim_lfs + boards: native_native_sim_lfs + pytest_args: tests/ --ignore=tests/bsim -k native_native_sim_lfs -n $(nproc) --dist loadfile + - shard: nrf5340bsim + boards: native_nrf5340bsim + pytest_args: tests/bsim -k native_nrf5340bsim -m 'not zephyr_sample' -n $(nproc) --dist loadfile + - shard: nrf5340bsim-samples + boards: native_nrf5340bsim + pytest_args: tests/bsim -k native_nrf5340bsim -m zephyr_sample -n $(nproc) --dist loadfile + - shard: nrf54lm20bsim + boards: native_nrf54lm20bsim + pytest_args: tests/bsim -k native_nrf54lm20bsim -m 'not zephyr_sample' -n $(nproc) --dist loadfile + - shard: nrf54lm20bsim-samples + boards: native_nrf54lm20bsim + pytest_args: tests/bsim -k native_nrf54lm20bsim -m zephyr_sample -n $(nproc) --dist loadfile + env: + CP_VERSION: ${{ inputs.cp-version }} + steps: + - name: Set up repository + uses: actions/checkout@v6 + with: + submodules: false + show-progress: false + fetch-depth: 1 + - name: Set up python + uses: actions/setup-python@v6 + with: + python-version: 3.13 + - name: Set up Zephyr + uses: ./.github/actions/deps/ports/zephyr-cp + with: + sdl: true + - name: Set up submodules + id: set-up-submodules + uses: ./.github/actions/deps/submodules + with: + target: zephyr-cp + - name: Set up external + uses: ./.github/actions/deps/external + - name: Build bsim + if: contains(matrix.shard, 'bsim') + run: make -j $(nproc) everything + working-directory: ports/zephyr-cp/tools/bsim + - name: Run Zephyr tests + run: make -C ports/zephyr-cp -j$(nproc) test TEST_BOARDS="${{ matrix.boards }}" PYTEST_ARGS="${{ matrix.pytest_args }}" diff --git a/.github/workflows/zephyr-autogen-pr.yml b/.github/workflows/zephyr-autogen-pr.yml new file mode 100644 index 00000000000..25a0e9e686e --- /dev/null +++ b/.github/workflows/zephyr-autogen-pr.yml @@ -0,0 +1,111 @@ +# SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) +# +# SPDX-License-Identifier: MIT + +# Build every zephyr-cp board and open a PR when the committed autogenerated +# files (autogen_board_info.toml) changed as a result. + +name: Update Zephyr autogenerated files + +on: + push: + branches: + - main + # Test branches: push a branch matching this pattern to run manually. + - 'zephyr-autogen-*' + workflow_dispatch: + +# The default GITHUB_TOKEN needs elevated permissions to push the autogen +# branch and open the PR. +permissions: + contents: write + pull-requests: write + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + autogen: + name: Build all zephyr-cp boards + runs-on: ubuntu-24.04 + timeout-minutes: 360 + steps: + - name: Set up repository + uses: actions/checkout@v6 + with: + submodules: false + show-progress: false + fetch-depth: 1 + - name: Set up python + uses: actions/setup-python@v6 + with: + python-version: 3.13 + - name: Set up Zephyr + uses: ./.github/actions/deps/ports/zephyr-cp + with: + # native_sim needs the 32-bit SDL2 packages + sdl: true + - name: Set up submodules + uses: ./.github/actions/deps/submodules + with: + target: zephyr-cp + version: true + - name: Set up external + uses: ./.github/actions/deps/external + - name: Build all boards + run: make -C ports/zephyr-cp -j$(nproc) all + - name: Print build logs + if: always() + run: | + shopt -s nullglob + for log in ports/zephyr-cp/build-logs/*.log; do + echo "::group::$(basename "$log" .log)" + cat "$log" + echo "::endgroup::" + done + - name: Check for autogenerated changes + id: diff + run: | + if [ -n "$(git status --porcelain -- 'ports/zephyr-cp/boards/**/autogen_board_info.toml')" ]; then + echo "changed=true" >> "$GITHUB_OUTPUT" + git status --short -- 'ports/zephyr-cp/boards/**/autogen_board_info.toml' + fi + - name: Find existing open autogen PR + id: pr + env: + GH_TOKEN: ${{ github.token }} + run: | + pr=$(gh pr list --state open --head zephyr-autogen-board-info --json number --jq '.[0].number // empty') + echo "number=$pr" >> "$GITHUB_OUTPUT" + if [ -n "$pr" ]; then + echo "Found existing open autogen PR #$pr; will push to it." + fi + - name: Delete stale autogen branch + # A new pull request cannot be created from a head branch that already + # had one. If the previous autogen PR was closed without merging, the + # branch lingers on; delete it so create-pull-request can start over. + if: steps.diff.outputs.changed == 'true' && steps.pr.outputs.number == '' + run: | + if git ls-remote --heads origin zephyr-autogen-board-info | grep -q zephyr-autogen-board-info; then + git push origin --delete zephyr-autogen-board-info + fi + - name: Create PR + if: steps.diff.outputs.changed == 'true' + uses: peter-evans/create-pull-request@v8 + with: + add-paths: ports/zephyr-cp/boards/**/autogen_board_info.toml + commit-message: Regenerate zephyr-cp autogen_board_info.toml files + title: Regenerate zephyr-cp autogenerated board info + # create-pull-request pushes to the branch of an existing open PR, + # so a still-open autogen PR is updated in place instead of spawning + # a second one. + body: | + The `autogen_board_info.toml` files changed after building all zephyr-cp + boards on `main`. Created by the "Update Zephyr autogenerated files" + workflow. + + Based on commit: ${{ github.sha }} + Workflow run: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + branch: zephyr-autogen-board-info + delete-branch: true diff --git a/.gitignore b/.gitignore index 9679ed5e0e2..ec4811a6e30 100644 --- a/.gitignore +++ b/.gitignore @@ -9,6 +9,7 @@ *.o *.a !atmel-samd/asf/**/*.a +!ports/espressif/microros-lib/**/*.a *.elf *.bin !*.toml.bin @@ -35,13 +36,18 @@ dist/ ###################### build/ bin/ +sizes/ +node_modules/ circuitpython-stubs/ test-stubs/ build-*/ +docs/genrst/ +.mpy_ld_cache-*/ -# Test failure outputs +# Test failure outputs and intermediate artifacts ###################### tests/results/* +tests/ports/unix/ffi_lib.so # Python cache files ###################### @@ -52,6 +58,9 @@ __pycache__/ ###################### GNUmakefile user.props +user_pre_mpconfigport.mk +user_post_mpconfigport.mk +user_post_circuitpy_defns.mk # Sphinx output ############### @@ -75,6 +84,7 @@ TAGS #################### *~ +# MacOS desktop metadata files *.DS_Store **/*.DS_Store *.icloud @@ -97,3 +107,16 @@ TAGS # clangd cache ############## .cache + +**/CLAUDE.local.md +.claude + +# windsurf rules +.windsurfrules + +# git-review-web outputs +.review + +# Zephyr trace files +**/channel0_0 +**/*.perfetto-trace diff --git a/.gitmodules b/.gitmodules index 2c96c3dec5f..9167ec80fa5 100644 --- a/.gitmodules +++ b/.gitmodules @@ -7,7 +7,7 @@ url = https://github.com/micropython/axtls.git [submodule "lib/libffi"] path = lib/libffi - url = https://github.com/atgreen/libffi + url = https://github.com/libffi/libffi [submodule "lib/berkeley-db-1.xx"] path = lib/berkeley-db-1.xx url = https://github.com/micropython/berkeley-db-1.xx @@ -143,11 +143,11 @@ [submodule "ports/espressif/esp-idf"] path = ports/espressif/esp-idf url = https://github.com/adafruit/esp-idf.git - branch = circuitpython-v5.3.2 + branch = circuitpython-v6.1 [submodule "ports/espressif/esp-protocols"] path = ports/espressif/esp-protocols url = https://github.com/adafruit/esp-protocols.git - branch = circuitpython + branch = circuitpython2026 [submodule "ports/espressif/esp-camera"] path = ports/espressif/esp-camera url = https://github.com/adafruit/esp32-camera.git @@ -173,6 +173,7 @@ [submodule "ports/raspberrypi/sdk"] path = ports/raspberrypi/sdk url = https://github.com/raspberrypi/pico-sdk.git + branch = force_inline_critical_section_2.1.1 [submodule "data/nvm.toml"] path = data/nvm.toml url = https://github.com/adafruit/nvm.toml.git @@ -189,11 +190,6 @@ [submodule "frozen/Adafruit_CircuitPython_APDS9960"] path = frozen/Adafruit_CircuitPython_APDS9960 url = https://github.com/adafruit/Adafruit_CircuitPython_APDS9960 -[submodule "rpi-firmware"] - path = ports/broadcom/firmware - url = https://github.com/raspberrypi/rpi-firmware.git - branch = master - shallow = true [submodule "lib/adafruit_floppy"] path = lib/adafruit_floppy url = https://github.com/adafruit/Adafruit_Floppy @@ -307,25 +303,21 @@ url = https://github.com/elecfreaks/circuitpython_picoed.git [submodule "ports/raspberrypi/lib/cyw43-driver"] path = ports/raspberrypi/lib/cyw43-driver - url = https://github.com/georgerobotics/cyw43-driver - branch = main + url = https://github.com/adafruit/cyw43-driver + branch = circuitpython11 [submodule "ports/raspberrypi/lib/lwip"] path = ports/raspberrypi/lib/lwip url = https://github.com/adafruit/lwip.git branch = circuitpython9 [submodule "lib/mbedtls"] path = lib/mbedtls - url = https://github.com/ARMmbed/mbedtls.git + url = https://github.com/Mbed-TLS/mbedtls.git [submodule "frozen/Adafruit_CircuitPython_UC8151D"] path = frozen/Adafruit_CircuitPython_UC8151D url = https://github.com/adafruit/Adafruit_CircuitPython_UC8151D [submodule "frozen/Adafruit_CircuitPython_SSD1680"] path = frozen/Adafruit_CircuitPython_SSD1680 url = https://github.com/adafruit/Adafruit_CircuitPython_SSD1680 -[submodule "ports/broadcom/peripherals"] - path = ports/broadcom/peripherals - url = https://github.com/adafruit/broadcom-peripherals.git - branch = main-build [submodule "ports/silabs/gecko_sdk"] path = ports/silabs/gecko_sdk url = https://github.com/SiliconLabs/gecko_sdk.git @@ -411,3 +403,31 @@ [submodule "ports/analog/msdk"] path = ports/analog/msdk url = https://github.com/analogdevicesinc/msdk.git +[submodule "ports/espressif/microros-lib"] + path = ports/espressif/microros-lib + url = https://github.com/hierophect/microros-lib.git +[submodule "frozen/Adafruit_CircuitPython_OPT4048"] + path = frozen/Adafruit_CircuitPython_OPT4048 + url = https://github.com/adafruit/Adafruit_CircuitPython_OPT4048.git +[submodule "frozen/CircuitPython_edupico2_paj7620"] + path = frozen/CircuitPython_edupico2_paj7620 + url = https://github.com/CytronTechnologies/CircuitPython_edupico2_paj7620.git +[submodule "frozen/Adafruit_CircuitPython_BLE_File_Transfer"] + path = frozen/Adafruit_CircuitPython_BLE_File_Transfer + url = https://github.com/adafruit/Adafruit_CircuitPython_BLE_File_Transfer.git +[submodule "frozen/Adafruit_CircuitPython_CS42L42"] + path = frozen/Adafruit_CircuitPython_CS42L42 + url = https://github.com/adafruit/Adafruit_CircuitPython_CS42L42.git +[submodule "frozen/Adafruit_CircuitPython_TAS2505"] + path = frozen/Adafruit_CircuitPython_TAS2505 + url = https://github.com/adafruit/Adafruit_CircuitPython_TAS2505.git +[submodule "ports/espressif/esp-hosted"] + path = ports/espressif/esp-hosted + url = https://github.com/espressif/esp-hosted-mcu.git +[submodule "ports/espressif/esp-adf-libs"] + path = ports/espressif/esp-adf-libs + url = https://github.com/espressif/esp-adf-libs.git +[submodule "lib/lvgl"] + path = lib/lvgl + url = https://github.com/adafruit/lvgl.git + branch = circuitpython-v9.6 diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 95bc8065721..d92045c62ec 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -4,19 +4,34 @@ # CIRCUITPY-CHANGE: CircuitPython-specific. +# Note that by default, pre-commit hooks do not look inside submodules. +# So you don't need to exclude submodules explicitly here. + repos: -- repo: https://github.com/pre-commit/pre-commit-hooks - rev: v5.0.0 + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v6.0.0 hooks: - - id: check-yaml - - id: end-of-file-fixer - exclude: '^(tests/.*\.exp|tests/cmdline/.*|tests/.*/data/.*|ports/mimxrt10xx/sdk|ports/raspberrypi/sdk|lib/tinyusb)' - - id: trailing-whitespace - exclude: '^(tests/.*\.exp|tests/cmdline/.*|tests/.*/data/.*|lib/mbedtls_errors/generate_errors.diff|ports/raspberrypi/sdk|ports/mimxrt10xx/sdk|lib/tinyusb)' -- repo: https://github.com/codespell-project/codespell - rev: v2.2.4 + - id: check-yaml + - id: end-of-file-fixer + exclude: | + (?x)^( + tests/.*\.exp| + tests/cmdline/.*| + tests/.*/data/.* + ) + - id: trailing-whitespace + exclude: | + (?x)^( + tests/.*\.exp| + tests/cmdline/.*| + tests/.*/data/.*| + lib/mbedtls_errors/generate_errors.diff| + lib/mbedtls_config/psa_dispatch.patch + ) + - repo: https://github.com/codespell-project/codespell + rev: v2.4.1 hooks: - - id: codespell + - id: codespell args: [-w] exclude: | (?x)^( @@ -25,38 +40,30 @@ repos: tests/unicode/data/utf-8_invalid.txt| tests/extmod/data/qr.pgm| tests/basics/bytearray_byte_operations.py| - ports/raspberrypi/sdk| ports/zephyr-cp/cptools/compat2driver.py ) -- repo: local + - repo: local hooks: - - id: translations + - id: translations name: Translations entry: sh -c "if ! make check-translate; then make translate; fi" types: [c] pass_filenames: false language: system - - id: formatting + - id: formatting name: Formatting - entry: python3 tools/codeformat.py - types: [c] - language: system - exclude: | - (?x)^( - lib/tinyusb| - ports/raspberrypi/sdk - ) -- repo: https://github.com/astral-sh/ruff-pre-commit - # Ruff version. - rev: v0.9.4 - hooks: - # Run the linter. - - id: ruff - args: [ --fix ] - # Run the formatter. - - id: ruff-format -- repo: https://github.com/tox-dev/pyproject-fmt - rev: "v2.5.0" - hooks: - - id: pyproject-fmt - exclude: '^(ports/mimxrt10xx/sdk)' + entry: python3 tools/codeformat.py -v -c + language: python + - repo: https://github.com/astral-sh/ruff-pre-commit + # Ruff version. + rev: v0.15.7 + hooks: + # Run the linter. + - id: ruff + args: [ --fix ] + # Run the formatter. + - id: ruff-format + - repo: https://github.com/tox-dev/pyproject-fmt + rev: "v2.21.0" + hooks: + - id: pyproject-fmt diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 00000000000..acefd1df574 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,4 @@ +- Capture CircuitPython output by finding the matching device in `/dev/serial/by-id` or `/dev/sandbox` +- You can mount the CIRCUITPY drive by doing `udisksctl mount -b /dev/disk/by-label/CIRCUITPY` and access it via `/run/media//CIRCUITPY`. +- `circup` is a command line tool to install libraries and examples to CIRCUITPY. +- When connecting to serial devices on Linux use /dev/serial/by-id or /dev/sandbox. These will be more stable than /dev/ttyACM*. diff --git a/BUILDING.md b/BUILDING.md index 34cd544d736..6986dbb7224 100644 --- a/BUILDING.md +++ b/BUILDING.md @@ -25,13 +25,20 @@ Please ensure you set up your build environment appropriately, as per the guide. This project has a bunch of git submodules. You will need to update them regularly. -In the root folder of the CircuitPython repository, execute the following: +Fetch only what the board you are building needs. From the root folder of the CircuitPython +repository: - make fetch-all-submodules + make -C ports/raspberrypi fetch-board-submodules BOARD=raspberry_pi_pico + +Or everything one port needs, which is what you want if you build several boards from it: -Or, in the ports directory for the particular port you are building, do: + make -C ports/raspberrypi fetch-port-submodules - make fetch-port-submodules +There is also a target that fetches the submodules of every port at once. That is a few gigabytes +against a few hundred megabytes for one board, so use it only if you really are building for +more than one port: + + make fetch-all-submodules ### Required Python Packages @@ -64,6 +71,52 @@ If you aren't sure what boards exist, have a peek in the boards subdirectory of If you have a fast computer with many cores, consider adding `-j` to your build flags, such as `-j17` on a 6-core 12-thread machine. +## Configuration + +Ports and boards are preconfigured, thus make knows how to build a specific +board. Power users can change the configuration of a specific board or port, +either by passing compile-time options to make, or by creating appropriate +make include files. + +The configuration system is hierarchical. A higher level will typically only +set an option that a lower level hasn't configured: + +* board configuration: `mpconfigport.mk` +* pre-port user configuration: `user_pre_mpconfigport.mk` +* port configuration: `mpconfigport.mk` +* post-port user configuration: `user_post_mpconfigport.mk` +* global configuration: `py/circuitpython_mpconfig.mk` + +The board configuration is within the board-directory, e.g. +`ports/raspberrypi/boards/raspberry_pi_pico/`, the port configuration is +in the port-directory, e.g. `ports/raspberrypi/`. + +Editing these configuration files is the way to go if you want to change +the default behavior and ultimately create a pull-request. Otherwise, +changes should go into one of the user configuration files. + +User specific configurations are optional and should be maintained out of +tree. Passing `-I directory` tells make where to search for the additional +configuration files. E.g. to speed up boots by removing the wait-time for +the save-mode button press, you would: + +* create a directory: `mkdir -p ~/my_cp_config` +* create the config file: `echo 'CIRCUITPY_SKIP_SAFE_MODE_WAIT=0' > ~/my_cp_config/user_pre_mpconfigport.mk` +* run make with: `make -I ~/my_cp_config BOARD=raspberry_pi_pico` + +Besides the `user*mpconfigport.mk` files, there is another optional file +named `user_post_circuitpy_defns.mk`. This file is included at the end +and can be used to tweak compiler-definitions that are not covered by +one of the compile time options `CIRCUITPY_*`. + +Example: to create a build for the Pico2-W with an integrated saves-partition, +you would create a `user_post_circuitpy_defns.mk` with the following content: + + $(info ===> processing user_post_circuitpy_defns.mk) + ifeq (${BOARD},raspberry_pi_pico2_w) + CFLAGS += -DCIRCUITPY_SAVES_PARTITION_SIZE=1048576 + endif + ## Testing If you are working on changes to the core language, you might find it useful to run the test suite. diff --git a/LICENSE b/LICENSE index a9ba6ea5926..2b332548d80 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2013-2023 Damien P. George +Copyright (c) 2013-2026 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 @@ -22,8 +22,6 @@ THE SOFTWARE. -------------------------------------------------------------------------------- -# CIRCUITPY-CHANGE: - Unless specified otherwise (see below), the above license and copyright applies to all files derived from MicroPython in this repository. diff --git a/LICENSE_MicroPython b/LICENSE_MicroPython index 469ae192739..1fad9b4134e 100644 --- a/LICENSE_MicroPython +++ b/LICENSE_MicroPython @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2013-2024 Damien P. George +Copyright (c) 2013-2025 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 diff --git a/Makefile b/Makefile index ea0e26adfce..ca0539fd4ee 100644 --- a/Makefile +++ b/Makefile @@ -7,8 +7,11 @@ # You can set these variables from the command line. PYTHON = python3 -SPHINXOPTS = -W --keep-going +SPHINXOPTS = -W --keep-going -j auto SPHINXBUILD = sphinx-build +# -silent hides pdflatex's progress output, including the thousands of undefined-reference +# warnings from its first pass. Warnings left after the last pass, and errors, are still reported. +LATEXMKOPTS = -silent PAPER = # path to build the generated docs BUILDDIR = _build @@ -40,7 +43,7 @@ ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(BASEOPTS) # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(BASEOPTS) -TRANSLATE_SOURCES = extmod lib main.c ports/atmel-samd ports/analog ports/cxd56 ports/espressif ports/mimxrt10xx ports/nordic ports/raspberrypi ports/renode ports/stm ports/zephyr-cp py shared-bindings shared-module supervisor +TRANSLATE_SOURCES = extmod lib main.c ports/atmel-samd ports/analog ports/cxd56 ports/espressif ports/mimxrt10xx ports/nordic ports/raspberrypi ports/stm ports/zephyr-cp py shared-bindings shared-module supervisor # Paths to exclude from TRANSLATE_SOURCES # Each must be preceded by "-path"; if any wildcards, enclose in quotes. # Separate by "-o" (Find's "or" operand) @@ -93,8 +96,13 @@ help: @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" - @echo " fetch-all-submodules to fetch submodules for all ports" + @echo " fetch-all-submodules to fetch submodules for all ports (several GB)" @echo " remove-all-submodules remove all submodules, including files and .git/ data" + @echo "" + @echo "To build one board you only need its own submodules, which is a much smaller" + @echo "download. From a port directory:" + @echo " make fetch-board-submodules BOARD= submodules for one board" + @echo " make fetch-port-submodules submodules for every board of that port" clean: rm -rf $(BUILDDIR)/* @@ -166,7 +174,7 @@ latex: latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." - $(MAKE) -C $(BUILDDIR)/latex all-pdf + $(MAKE) -C $(BUILDDIR)/latex all-pdf LATEXMKOPTS="$(LATEXMKOPTS)" @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." # seems to be malfunctioning @@ -236,8 +244,8 @@ pseudoxml: .PHONY: all-source all-source: -TRANSLATE_CHECK_SUBMODULES=if ! [ -f extmod/ulab/README.md ]; then python tools/ci_fetch_deps.py translate; fi -TRANSLATE_COMMAND=find $(TRANSLATE_SOURCES) -type d \( $(TRANSLATE_SOURCES_EXC) \) -prune -o -type f \( -iname "*.c" -o -iname "*.h" \) -print | (LC_ALL=C sort) | xgettext -x locale/synthetic.pot -f- -L C -s --add-location=file --keyword=MP_ERROR_TEXT -o - | sed -e '/"POT-Creation-Date: /d' +TRANSLATE_CHECK_SUBMODULES=if ! [ -f extmod/ulab/README.md ]; then $(PYTHON) tools/ci_fetch_deps.py translate; fi +TRANSLATE_COMMAND=find $(TRANSLATE_SOURCES) -type d \( $(TRANSLATE_SOURCES_EXC) \) -prune -o -type f \( -iname "*.c" -o -iname "*.h" \) -print | (LC_ALL=C sort) | xgettext -x locale/synthetic.pot -f- -L C --sort-by-file --add-location=file --keyword=MP_ERROR_TEXT -o - | sed -e '/"POT-Creation-Date: /d' locale/circuitpython.pot: all-source $(TRANSLATE_CHECK_SUBMODULES) $(TRANSLATE_COMMAND) > $@ @@ -255,7 +263,7 @@ translate: locale/circuitpython.pot # needed we preserve a rule to do it. .PHONY: msgmerge msgmerge: - for po in $(shell ls locale/*.po); do msgmerge -U $$po -s --no-fuzzy-matching --add-location=file locale/circuitpython.pot; done + for po in $(shell ls locale/*.po); do msgmerge -U $$po --sort-by-file --no-fuzzy-matching --add-location=file locale/circuitpython.pot; done merge-translate: git merge HEAD 1>&2 2> /dev/null; test $$? -eq 128 @@ -271,20 +279,21 @@ check-translate: .PHONY: stubs stubs: - @rm -rf circuitpython-stubs - @mkdir circuitpython-stubs - @$(PYTHON) tools/extract_pyi.py shared-bindings/ $(STUBDIR) - @$(PYTHON) tools/extract_pyi.py extmod/ulab/code/ $(STUBDIR)/ulab - @for d in ports/*/bindings; do \ + rm -rf circuitpython-stubs + mkdir circuitpython-stubs + $(PYTHON) tools/extract_pyi.py shared-bindings/ $(STUBDIR) + $(PYTHON) tools/extract_pyi.py extmod/ulab/code/ $(STUBDIR)/ulab + for d in ports/*/bindings; do \ $(PYTHON) tools/extract_pyi.py "$$d" $(STUBDIR); done - @sed -e "s,__version__,`python -msetuptools_scm`," < setup.py-stubs > circuitpython-stubs/setup.py - @cp README.rst-stubs circuitpython-stubs/README.rst - @cp MANIFEST.in-stubs circuitpython-stubs/MANIFEST.in - @$(PYTHON) tools/board_stubs/build_board_specific_stubs/board_stub_builder.py - @cp -r tools/board_stubs/circuitpython_setboard circuitpython-stubs/circuitpython_setboard - @$(PYTHON) -m build circuitpython-stubs - @touch circuitpython-stubs/board/__init__.py - @touch circuitpython-stubs/board_definitions/__init__.py + sed -e "s,__version__,`python -msetuptools_scm`," < setup.py-stubs > circuitpython-stubs/setup.py + cp README.rst-stubs circuitpython-stubs/README.rst + cp MANIFEST.in-stubs circuitpython-stubs/MANIFEST.in + cp -r stubs/* circuitpython-stubs + $(PYTHON) tools/board_stubs/build_board_specific_stubs/board_stub_builder.py + cp -r tools/board_stubs/circuitpython_setboard circuitpython-stubs/circuitpython_setboard + $(PYTHON) -m build circuitpython-stubs + touch circuitpython-stubs/board/__init__.py + touch circuitpython-stubs/board_definitions/__init__.py .PHONY: check-stubs check-stubs: stubs @@ -296,7 +305,10 @@ update-frozen-libraries: @echo "Updating all frozen libraries to latest tagged version." cd frozen; for library in *; do cd $$library; ../../tools/git-checkout-latest-tag.sh; cd ..; done -one-of-each: samd21 litex mimxrt10xx nordic stm +one-of-each: samd21 mimxrt10xx nordic stm + +analog: + $(MAKE) -C ports/analog/ BOARD=apard32690 samd21: $(MAKE) -C ports/atmel-samd BOARD=trinket_m0 @@ -307,9 +319,6 @@ samd51: espressif: $(MAKE) -C ports/espressif BOARD=espressif_saola_1_wroom -litex: - $(MAKE) -C ports/litex BOARD=fomu - mimxrt10xx: $(MAKE) -C ports/mimxrt10xx BOARD=feather_mimxrt1011 @@ -319,7 +328,7 @@ nordic: stm: $(MAKE) -C ports/stm BOARD=feather_stm32f405_express -clean-one-of-each: clean-samd21 clean-samd51 clean-espressif clean-litex clean-mimxrt10xx clean-nordic clean-stm +clean-one-of-each: clean-samd21 clean-samd51 clean-espressif clean-mimxrt10xx clean-nordic clean-stm clean-samd21: $(MAKE) -C ports/atmel-samd BOARD=trinket_m0 clean @@ -330,9 +339,6 @@ clean-samd51: clean-espressif: $(MAKE) -C ports/espressif BOARD=espressif_saola_1_wroom clean -clean-litex: - $(MAKE) -C ports/litex BOARD=fomu clean - clean-mimxrt10xx: $(MAKE) -C ports/mimxrt10xx BOARD=feather_mimxrt1011 clean @@ -371,5 +377,6 @@ coverage-fresh: make -j -C ports/unix VARIANT=coverage .PHONY: run-tests +# If TESTS="abc.py def.py" is specified as an arg, run only those tests. Otherwise, run all tests. run-tests: - cd tests; MICROPY_MICROPYTHON=../ports/unix/build-coverage/micropython ./run-tests.py + cd tests; MICROPY_MICROPYTHON=../ports/unix/build-coverage/micropython ./run-tests.py $(TESTS) diff --git a/README.rst b/README.rst index 80aa1b2aee2..7cb5ccc27f8 100644 --- a/README.rst +++ b/README.rst @@ -226,7 +226,7 @@ Ports Ports include the code unique to a microcontroller line. -The following ports are available: ``atmel-samd``, ``cxd56``, ``espressif``, ``litex``, ``mimxrt10xx``, ``nordic``, ``raspberrypi``, ``renode``, ``silabs`` (``efr32``), ``stm``, ``unix``. +The following ports are available: ``atmel-samd``, ``cxd56``, ``espressif``, ``mimxrt10xx``, ``nordic``, ``raspberrypi``, ``silabs`` (``efr32``), ``stm``, ``unix``, and ``zephyr-cp``. However, not all ports are fully functional. Some have limited functionality and known serious bugs. For details, refer to the **Port status** section in the `latest release `__ notes. diff --git a/conf.py b/conf.py index 75555401747..277d4f355ad 100644 --- a/conf.py +++ b/conf.py @@ -36,6 +36,7 @@ # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath("docs")) +sys.path.insert(0, os.path.abspath("tools")) sys.path.insert(0, os.path.abspath(".")) import shared_bindings_matrix @@ -45,11 +46,14 @@ # Grab the JSON values to use while building the module support matrix # in 'shared-bindings/index.rst' -# The stubs must be built before we calculate the shared bindings matrix +# Building the stubs also saves the board data the support matrix needs, so the +# slow per-board collection runs only once. If that file is missing, +# support_matrix_by_board() collects the data itself. subprocess.check_output(["make", "stubs"]) +board_data = shared_bindings_matrix.read_board_data("circuitpython-stubs/board_data.json") # modules_support_matrix = shared_bindings_matrix.support_matrix_excluded_boards() -modules_support_matrix = shared_bindings_matrix.support_matrix_by_board() +modules_support_matrix = shared_bindings_matrix.support_matrix_by_board(board_data=board_data) modules_support_matrix_reverse = defaultdict(list) for board, matrix_info in modules_support_matrix.items(): for module in matrix_info["modules"]: @@ -83,6 +87,18 @@ "sphinx_search.extension", "rstjinja", "myst_parser", + "llms_txt", +] + +# llms.txt: an index of every page for coding agents (docs/llms_txt.py) +llms_txt_description = ( + "Adafruit CircuitPython - Python for microcontrollers. " + "Each page is also served as Markdown with the Accept: text/markdown header." +) +llms_txt_exclude = [ + "docs/porting", + "docs/pdf", + "shared-bindings/support_matrix", ] # Add any paths that contain templates here, relative to this directory. @@ -192,7 +208,13 @@ def autoapi_prepare_jinja_env(jinja_env): # Port READMEs in various formats "ports/*/README*", ] -exclude_patterns = ["docs/autoapi/templates/**", "docs/README.md"] +exclude_patterns = [ + "docs/autoapi/templates/**", + "docs/README.md", + "AGENTS.md", + "**/AGENTS.md", + "docs/library/weakref.rst", +] # The reST default role (used for this markup: `text`) to use for all # documents. @@ -325,6 +347,7 @@ def autoapi_prepare_jinja_env(jinja_env): \hbadness=99999 \hfuzz=20pt \usepackage{pdflscape} +\DeclareUnicodeCharacter{FFFD}{?} """, } @@ -434,11 +457,11 @@ def generate_redirects(app): return if not isinstance(app.builder, builders.StandaloneHTMLBuilder): - logging.warn( + logging.warning( "The 'sphinxcontib-redirects' plugin is only supported " "by the 'html' builder and subclasses. Skipping..." ) - logging.warn(f"Builder is {app.builder.name} ({type(app.builder)})") + logging.warning(f"Builder is {app.builder.name} ({type(app.builder)})") return with open(path) as redirects: diff --git a/data/nvm.toml b/data/nvm.toml index 6b678f15e37..3a38be56271 160000 --- a/data/nvm.toml +++ b/data/nvm.toml @@ -1 +1 @@ -Subproject commit 6b678f15e378edce820f2ffdef3286b3e55449e7 +Subproject commit 3a38be562718fce8f545eebaf8c7a6c0f367b345 diff --git a/devices/ble_hci/common-hal/_bleio/Adapter.c b/devices/ble_hci/common-hal/_bleio/Adapter.c index fac7eb9f5fd..1d5d436f460 100644 --- a/devices/ble_hci/common-hal/_bleio/Adapter.c +++ b/devices/ble_hci/common-hal/_bleio/Adapter.c @@ -29,10 +29,6 @@ #include "shared-bindings/_bleio/ScanEntry.h" #include "shared-bindings/time/__init__.h" -#if CIRCUITPY_OS_GETENV -#include "shared-bindings/os/__init__.h" -#endif - #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) @@ -164,6 +160,13 @@ static void check_enabled(bleio_adapter_obj_t *adapter) { } } +// A controller that supports extended advertising refuses legacy advertising +// commands (Command Disallowed) once any extended command has been sent, so +// use the extended command set exclusively on such controllers. +static bool adapter_uses_extended_advertising(bleio_adapter_obj_t *adapter) { + return BT_FEAT_LE_EXT_ADV(adapter->features); +} + // 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; @@ -247,9 +250,6 @@ static void check_enabled(bleio_adapter_obj_t *adapter) { // return true; // } -// Includes trailing null. -char default_ble_name[] = { 'C', 'I', 'R', 'C', 'U', 'I', 'T', 'P', 'Y', 0, 0, 0, 0, 0}; - static void _adapter_set_name(bleio_adapter_obj_t *self, mp_obj_str_t *name_obj) { mp_buffer_info_t bufinfo; mp_get_buffer_raise(name_obj, &bufinfo, MP_BUFFER_READ); @@ -259,30 +259,6 @@ static void _adapter_set_name(bleio_adapter_obj_t *self, mp_obj_str_t *name_obj) // Get various values and limits set by the adapter. // Set event mask. static void bleio_adapter_hci_init(bleio_adapter_obj_t *self) { - mp_int_t name_len = 0; - - #if CIRCUITPY_OS_GETENV - mp_obj_t name = common_hal_os_getenv("CIRCUITPY_BLE_NAME", mp_const_none); - if (name != mp_const_none) { - mp_arg_validate_type_string(name, MP_QSTR_CIRCUITPY_BLE_NAME); - self->name = name; - } - #endif - - if (!self->name) { - name_len = sizeof(default_ble_name) - 1; - bt_addr_t addr; - hci_check_error(hci_read_bd_addr(&addr)); - - default_ble_name[name_len - 4] = nibble_to_hex_lower[addr.val[1] >> 4 & 0xf]; - default_ble_name[name_len - 3] = nibble_to_hex_lower[addr.val[1] & 0xf]; - default_ble_name[name_len - 2] = nibble_to_hex_lower[addr.val[0] >> 4 & 0xf]; - default_ble_name[name_len - 1] = nibble_to_hex_lower[addr.val[0] & 0xf]; - // default_ble_name[name_len] will be zero. - self->name = mp_obj_new_str(default_ble_name, (uint8_t)name_len); - } - _adapter_set_name(self, self->name); - // Get version information. if (hci_read_local_version(&self->hci_version, &self->hci_revision, &self->lmp_version, &self->manufacturer, &self->lmp_subversion) != HCI_OK) { @@ -324,20 +300,12 @@ static void bleio_adapter_hci_init(bleio_adapter_obj_t *self) { self->max_acl_num_buffers = acl_max_num; } - // Get max advertising length if extended advertising is supported. - if (BT_FEAT_LE_EXT_ADV(self->features)) { - uint16_t max_adv_data_len; - if (hci_le_read_maximum_advertising_data_length(&max_adv_data_len) != HCI_OK) { - mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Could not get max advertising length")); - } - self->max_adv_data_len = max_adv_data_len; - } else { - self->max_adv_data_len = MAX_ADVERTISEMENT_SIZE; - } + // After the address is read: the default name includes it. + self->name = NULL; + bleio_adapter_reset_name(self); } void common_hal_bleio_adapter_construct_hci_uart(bleio_adapter_obj_t *self, busio_uart_obj_t *uart, digitalio_digitalinout_obj_t *rts, digitalio_digitalinout_obj_t *cts) { - self->allocated = true; self->hci_uart = uart; self->rts_digitalinout = rts; self->cts_digitalinout = cts; @@ -346,7 +314,8 @@ void common_hal_bleio_adapter_construct_hci_uart(bleio_adapter_obj_t *self, busi self->enabled = false; common_hal_bleio_adapter_set_enabled(self, true); - bleio_adapter_hci_init(self); + // Not when enabling failed: the adapter is not kept. + self->allocated = true; } void common_hal_bleio_adapter_set_enabled(bleio_adapter_obj_t *self, bool enabled) { @@ -357,30 +326,46 @@ void common_hal_bleio_adapter_set_enabled(bleio_adapter_obj_t *self, bool enable return; } - self->enabled = enabled; - // We must poll for input from the HCI adapter. // TODO Can we instead trigger an interrupt on UART input traffic? if (enabled) { + self->enabled = true; supervisor_enable_tick(); - } else { - supervisor_disable_tick(); } - // Enabling or disabling: stop any current activity; reset to known state. + // Enabling or disabling: stop any current activity; reset to known state. While disabling, + // stay enabled until the reset's reply has been read. hci_reset(); + // The reset ended all links without Disconnection Complete events. + bleio_hci_reset(); + self->connection_objs = NULL; + if (!enabled) { + self->enabled = false; + supervisor_disable_tick(); + } self->now_advertising = false; - self->extended_advertising = false; self->circuitpython_advertising = false; self->advertising_timeout_msecs = 0; if (enabled) { - // Reset list of known attributes. - // Indices into the list are handles. Handle 0x0000 designates an invalid handle, - // so store None there to skip it. - self->attributes = mp_obj_new_list(0, NULL); - bleio_adapter_add_attribute(self, mp_const_none); - add_generic_services(self); + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + // Reset list of known attributes. + // Indices into the list are handles. Handle 0x0000 designates an invalid handle, + // so store None there to skip it. + self->attributes = mp_obj_new_list(0, NULL); + bleio_adapter_add_attribute(self, mp_const_none); + add_generic_services(self); + + // The reset cleared the event mask: set the controller up again. + bleio_adapter_hci_init(self); + nlr_pop(); + } else { + // On failure, leave the adapter off. + self->enabled = false; + supervisor_disable_tick(); + nlr_jump(nlr.ret_val); + } } } @@ -394,18 +379,14 @@ bleio_address_obj_t *common_hal_bleio_adapter_get_address(bleio_adapter_obj_t *s bt_addr_t addr; hci_check_error(hci_read_bd_addr(&addr)); - bleio_address_obj_t *address = mp_obj_malloc(bleio_address_obj_t, &bleio_address_type); - - common_hal_bleio_address_construct(address, addr.val, BT_ADDR_LE_PUBLIC); - return address; + // The cached address is refreshed on every call. + common_hal_bleio_address_construct(&self->address, addr.val, BT_ADDR_LE_PUBLIC); + self->address.base.type = &bleio_address_type; + return &self->address; } bool common_hal_bleio_adapter_set_address(bleio_adapter_obj_t *self, bleio_address_obj_t *address) { - mp_buffer_info_t bufinfo; - if (!mp_get_buffer(address->bytes, &bufinfo, MP_BUFFER_READ)) { - return false; - } - return hci_le_set_random_address(bufinfo.buf) == HCI_OK; + return hci_le_set_random_address(address->bytes) == HCI_OK; } mp_obj_str_t *common_hal_bleio_adapter_get_name(bleio_adapter_obj_t *self) { @@ -571,7 +552,6 @@ mp_obj_t common_hal_bleio_adapter_connect(bleio_adapter_obj_t *self, bleio_addre // ble_drv_add_event_handler(connect_on_ble_evt, &event_info); // event_info.done = false; - vm_used_ble = true; // uint32_t err_code = sd_ble_gap_connect(&addr, &scan_params, &conn_params, BLE_CONN_CFG_TAG_CUSTOM); // if (err_code != NRF_SUCCESS) { @@ -660,26 +640,21 @@ uint32_t _common_hal_bleio_adapter_start_advertising(bleio_adapter_obj_t *self, // Copy peer address, if supplied. if (directed_to) { - mp_buffer_info_t bufinfo; - if (mp_get_buffer(directed_to->bytes, &bufinfo, MP_BUFFER_READ)) { - peer_addr.type = directed_to->type; - memcpy(&peer_addr.a.val, bufinfo.buf, sizeof(peer_addr.a.val)); - } + peer_addr.type = directed_to->type; + memcpy(&peer_addr.a.val, directed_to->bytes, sizeof(peer_addr.a.val)); } - bool extended = - advertising_data_len > self->max_adv_data_len || scan_response_data_len > self->max_adv_data_len; - - if (extended) { - if (!BT_FEAT_LE_EXT_ADV(self->features)) { - mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Data length needs extended advertising, but this adapter does not support it")); - } - - uint16_t props = 0; + if (adapter_uses_extended_advertising(self)) { + // Use legacy PDUs (ADV_IND etc.) so that 4.x centrals still see us and the + // 31-byte data limit applies unchanged; only the HCI command set is extended. + uint16_t props = BT_HCI_LE_ADV_PROP_LEGACY; if (connectable) { - props |= BT_HCI_LE_ADV_PROP_CONN; - } - if (scan_response_data_len > 0) { + if (directed_to) { + props |= BT_HCI_LE_ADV_PROP_CONN | BT_HCI_LE_ADV_PROP_DIRECT; + } else { + props |= BT_HCI_LE_ADV_PROP_CONN | BT_HCI_LE_ADV_PROP_SCAN; + } + } else if (scan_response_data_len > 0) { props |= BT_HCI_LE_ADV_PROP_SCAN; } @@ -694,32 +669,53 @@ uint32_t _common_hal_bleio_adapter_start_advertising(bleio_adapter_obj_t *self, interval_units, // max interval 0b111, // channel map: channels 37, 38, 39 anonymous ? BT_ADDR_LE_RANDOM : BT_ADDR_LE_PUBLIC, - &peer_addr, // peer_addr, + &peer_addr, 0x00, // filter policy: no filter - DEFAULT_TX_POWER, - BT_HCI_LE_EXT_SCAN_PHY_1M, // Secondary PHY to use - 0x00, // AUX_ADV_IND shall be sent prior to next adv event - BT_HCI_LE_EXT_SCAN_PHY_1M, // Secondary PHY to use - 0x00, // Advertising SID - 0x00 // Scan req notify disable + BT_HCI_LE_ADV_TX_POWER_NO_PREF, + BT_HCI_LE_EXT_SCAN_PHY_1M, // primary PHY + 0x00, // secondary max skip (unused with legacy PDUs) + BT_HCI_LE_EXT_SCAN_PHY_1M, // secondary PHY (unused with legacy PDUs) + 0x00, // advertising SID + 0x00 // scan request notification disabled )); - // We can use the duration mechanism provided, instead of our own. - self->advertising_timeout_msecs = 0; + hci_check_error( + hci_le_set_extended_advertising_data( + 0, // handle + BT_HCI_LE_EXT_ADV_OP_COMPLETE_DATA, + BT_HCI_LE_EXT_ADV_FRAG_DISABLED, + advertising_data_len, + (uint8_t *)advertising_data)); + + // A scannable set must have scan response data defined before it is enabled, + // even if that data is empty. + if (props & BT_HCI_LE_ADV_PROP_SCAN) { + hci_check_error( + hci_le_set_extended_scan_response_data( + 0, // handle + BT_HCI_LE_EXT_ADV_OP_COMPLETE_DATA, + BT_HCI_LE_EXT_ADV_FRAG_DISABLED, + scan_response_data_len, + (uint8_t *)scan_response_data)); + } + // Use our own timeout rather than the controller's duration, so that we don't + // depend on receiving the LE Advertising Set Terminated event. + self->advertising_timeout_msecs = timeout * 1000; + self->advertising_start_ticks = supervisor_ticks_ms64(); + + // Duration 0 and max events 0 mean "advertise until disabled by the host". uint8_t handle[1] = { 0 }; - uint16_t duration_10msec[1] = { timeout * 100 }; + uint16_t duration_forever[1] = { 0 }; uint8_t max_ext_adv_evts[1] = { 0 }; hci_check_error( hci_le_set_extended_advertising_enable( BT_HCI_LE_ADV_ENABLE, 1, // one advertising set. handle, - duration_10msec, + duration_forever, max_ext_adv_evts )); - - self->extended_advertising = true; } else { // Legacy advertising (not extended). @@ -754,11 +750,12 @@ uint32_t _common_hal_bleio_adapter_start_advertising(bleio_adapter_obj_t *self, uint8_t full_data[MAX_ADVERTISEMENT_SIZE] = { 0 }; memcpy(full_data, advertising_data, MIN(sizeof(full_data), advertising_data_len)); hci_check_error(hci_le_set_advertising_data(advertising_data_len, full_data)); + // Always set, even empty: the controller keeps the previous scan response. memset(full_data, 0, sizeof(full_data)); if (scan_response_data_len > 0) { memcpy(full_data, scan_response_data, MIN(sizeof(full_data), scan_response_data_len)); - hci_check_error(hci_le_set_scan_response_data(scan_response_data_len, full_data)); } + hci_check_error(hci_le_set_scan_response_data(scan_response_data_len, full_data)); // No duration mechanism is provided for legacy advertising, so we need to do our own. self->advertising_timeout_msecs = timeout * 1000; @@ -766,10 +763,8 @@ uint32_t _common_hal_bleio_adapter_start_advertising(bleio_adapter_obj_t *self, // Start advertising. hci_check_error(hci_le_set_advertising_enable(BT_HCI_LE_ADV_ENABLE)); - self->extended_advertising = false; } // end legacy advertising setup - vm_used_ble = true; self->now_advertising = true; return 0; } @@ -823,16 +818,26 @@ void common_hal_bleio_adapter_start_advertising(bleio_adapter_obj_t *self, void common_hal_bleio_adapter_stop_advertising(bleio_adapter_obj_t *self) { check_enabled(self); + // A connection already stopped advertising in the controller. + if (!self->now_advertising) { + self->circuitpython_advertising = false; + return; + } self->now_advertising = false; - self->extended_advertising = false; self->circuitpython_advertising = false; - int result = hci_le_set_advertising_enable(BT_HCI_LE_ADV_DISABLE); - // OK if we're already stopped. There seems to be an ESP32 HCI bug: - // If advertising is already off, then LE_SET_ADV_ENABLE does not return a response. - if (result != HCI_RESPONSE_TIMEOUT) { - hci_check_error(result); + int result; + if (adapter_uses_extended_advertising(self)) { + // Duration and max events are ignored when disabling. + uint8_t handle[1] = { 0 }; + uint16_t duration_forever[1] = { 0 }; + uint8_t max_ext_adv_evts[1] = { 0 }; + result = hci_le_set_extended_advertising_enable(BT_HCI_LE_ADV_DISABLE, 1, handle, duration_forever, max_ext_adv_evts); + } else { + result = hci_le_set_advertising_enable(BT_HCI_LE_ADV_DISABLE); } + // Not checked: from a background task, an exception would stop them all. + (void)result; // TODO startup CircuitPython advertising again. } @@ -841,7 +846,6 @@ void common_hal_bleio_adapter_stop_advertising(bleio_adapter_obj_t *self) { // 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; self->circuitpython_advertising = false; } @@ -932,25 +936,21 @@ void bleio_adapter_gc_collect(bleio_adapter_obj_t *adapter) { } void bleio_adapter_reset(bleio_adapter_obj_t *adapter) { - - if (!common_hal_bleio_adapter_get_enabled(adapter)) { - return; - } - - // Adapter will be reset. + // Disabling resets the controller and forgets the links it ends. common_hal_bleio_adapter_set_enabled(adapter, false); + // These objects are on the heap of the program that is ending. + // bleio_adapter_gc_collect() would keep whatever the next program puts there. + adapter->scan_results = NULL; + adapter->name = NULL; adapter->connection_objs = NULL; - for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) { - bleio_connection_internal_t *connection = &bleio_connections[i]; - // Disconnect all connections with Python state cleanly. Keep any supervisor-only connections. - if (connection->connection_obj != mp_const_none && - connection->conn_handle != BLE_CONN_HANDLE_INVALID) { - common_hal_bleio_connection_disconnect(connection); - } - connection->connection_obj = mp_const_none; - } - + adapter->hci_uart = NULL; + adapter->rts_digitalinout = NULL; + adapter->cts_digitalinout = NULL; + adapter->device_name_characteristic = NULL; + adapter->appearance_characteristic = NULL; + adapter->service_changed_characteristic = NULL; + adapter->attributes = NULL; } void bleio_adapter_background(bleio_adapter_obj_t *adapter) { @@ -958,14 +958,16 @@ void bleio_adapter_background(bleio_adapter_obj_t *adapter) { return; } + // Not while a command or an ACL packet is in flight: answers would get mixed up. + if (hci_busy()) { + return; + } + if (adapter->advertising_timeout_msecs > 0 && supervisor_ticks_ms64() - adapter->advertising_start_ticks > adapter->advertising_timeout_msecs) { adapter->advertising_timeout_msecs = 0; common_hal_bleio_adapter_stop_advertising(adapter); } - hci_result_t result = hci_poll_for_incoming_pkt(); - if (result != HCI_OK) { - mp_printf(&mp_plat_print, "bad hci_poll_for_incoming_pkt() result in background: %d\n", result); - } + hci_poll_for_incoming_pkt(); } diff --git a/devices/ble_hci/common-hal/_bleio/Adapter.h b/devices/ble_hci/common-hal/_bleio/Adapter.h index fda1c11d6cb..ee7672649dd 100644 --- a/devices/ble_hci/common-hal/_bleio/Adapter.h +++ b/devices/ble_hci/common-hal/_bleio/Adapter.h @@ -11,6 +11,7 @@ #include "py/obj.h" #include "py/objtuple.h" +#include "shared-bindings/_bleio/Address.h" #include "shared-bindings/_bleio/Characteristic.h" #include "shared-bindings/_bleio/Connection.h" #include "shared-bindings/_bleio/ScanResults.h" @@ -33,7 +34,6 @@ typedef struct _bleio_adapter_obj_t { digitalio_digitalinout_obj_t *cts_digitalinout; bool allocated; // True when in use. bool now_advertising; - bool extended_advertising; bool circuitpython_advertising; bool enabled; @@ -55,7 +55,6 @@ typedef struct _bleio_adapter_obj_t { uint16_t max_acl_buffer_len; uint16_t max_acl_num_buffers; - uint16_t max_adv_data_len; uint8_t features[8]; // Supported BLE features. // All the local attributes for this device. The index into the list @@ -65,6 +64,10 @@ typedef struct _bleio_adapter_obj_t { // the service they belong to. This vets that. uint16_t last_added_service_handle; uint16_t last_added_characteristic_handle; + // Cached local address returned by common_hal_bleio_adapter_get_address(). + // Stored inline so it never needs to allocate, even when read before the + // heap is available (e.g. from bleio_adapter_reset_name). + bleio_address_obj_t address; } bleio_adapter_obj_t; uint16_t bleio_adapter_add_attribute(bleio_adapter_obj_t *adapter, mp_obj_t *attribute); diff --git a/devices/ble_hci/common-hal/_bleio/Characteristic.c b/devices/ble_hci/common-hal/_bleio/Characteristic.c index a33b8ff4784..49b66d38e72 100644 --- a/devices/ble_hci/common-hal/_bleio/Characteristic.c +++ b/devices/ble_hci/common-hal/_bleio/Characteristic.c @@ -180,7 +180,7 @@ void common_hal_bleio_characteristic_set_cccd(bleio_characteristic_obj_t *self, } const uint16_t conn_handle = bleio_connection_get_conn_handle(self->service->connection); - common_hal_bleio_check_connected(conn_handle); + bleio_check_connected(conn_handle); uint16_t cccd_value = (notify ? CCCD_NOTIFY : 0) | diff --git a/devices/ble_hci/common-hal/_bleio/Connection.c b/devices/ble_hci/common-hal/_bleio/Connection.c index 30ed0af575c..148cb6e8471 100644 --- a/devices/ble_hci/common-hal/_bleio/Connection.c +++ b/devices/ble_hci/common-hal/_bleio/Connection.c @@ -323,6 +323,18 @@ bool common_hal_bleio_connection_get_connected(bleio_connection_obj_t *self) { return self->connection->conn_handle != BLE_CONN_HANDLE_INVALID; } +bool common_hal_bleio_connection_get_authenticated(bleio_connection_obj_t *self) { + return false; +} + +mp_obj_t common_hal_bleio_connection_get_numeric_comparison(bleio_connection_obj_t *self) { + return mp_const_none; +} + +void common_hal_bleio_connection_confirm_pairing(bleio_connection_obj_t *self, bool accept) { + mp_raise_NotImplementedError(NULL); +} + void common_hal_bleio_connection_disconnect(bleio_connection_internal_t *self) { hci_disconnect(self->conn_handle); } @@ -705,13 +717,8 @@ 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); - 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; + // Discovery is not implemented. + return (mp_obj_tuple_t *)&mp_const_empty_tuple_obj; } uint16_t bleio_connection_get_conn_handle(bleio_connection_obj_t *self) { diff --git a/devices/ble_hci/common-hal/_bleio/Connection.h b/devices/ble_hci/common-hal/_bleio/Connection.h index 04edb104ddc..02a000501bf 100644 --- a/devices/ble_hci/common-hal/_bleio/Connection.h +++ b/devices/ble_hci/common-hal/_bleio/Connection.h @@ -61,6 +61,7 @@ typedef struct { uint8_t disconnect_reason; } bleio_connection_obj_t; +void bleio_check_connected(uint16_t conn_handle); 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); bleio_connection_internal_t *bleio_conn_handle_to_connection(uint16_t conn_handle); diff --git a/devices/ble_hci/common-hal/_bleio/PacketBuffer.c b/devices/ble_hci/common-hal/_bleio/PacketBuffer.c index 771a1509f39..f29f4dd88a7 100644 --- a/devices/ble_hci/common-hal/_bleio/PacketBuffer.c +++ b/devices/ble_hci/common-hal/_bleio/PacketBuffer.c @@ -245,6 +245,8 @@ void common_hal_bleio_packet_buffer_deinit(bleio_packet_buffer_obj_t *self) { if (!common_hal_bleio_packet_buffer_deinited(self)) { bleio_characteristic_clear_observer(self->characteristic); ringbuf_deinit(&self->ringbuf); + // Mark as deinited, so common_hal_bleio_packet_buffer_deinited() reports it. + self->characteristic = NULL; } } diff --git a/devices/ble_hci/common-hal/_bleio/PacketBuffer.h b/devices/ble_hci/common-hal/_bleio/PacketBuffer.h index 563f365d21b..4e001339fe3 100644 --- a/devices/ble_hci/common-hal/_bleio/PacketBuffer.h +++ b/devices/ble_hci/common-hal/_bleio/PacketBuffer.h @@ -28,4 +28,7 @@ typedef struct { bool packet_queued; } bleio_packet_buffer_obj_t; +// Unused, but needed for _common_hal_bleio_packet_buffer_construct() +typedef void *ble_event_handler_t; + void bleio_packet_buffer_update(bleio_packet_buffer_obj_t *self, mp_buffer_info_t *bufinfo); diff --git a/devices/ble_hci/common-hal/_bleio/Service.c b/devices/ble_hci/common-hal/_bleio/Service.c index a39efc614ee..610091b86f3 100644 --- a/devices/ble_hci/common-hal/_bleio/Service.c +++ b/devices/ble_hci/common-hal/_bleio/Service.c @@ -19,8 +19,6 @@ uint32_t _common_hal_bleio_service_construct(bleio_service_obj_t *self, bleio_uu self->connection = NULL; self->is_secondary = is_secondary; - vm_used_ble = true; - self->handle = bleio_adapter_add_attribute(&common_hal_bleio_adapter_obj, MP_OBJ_TO_PTR(self)); self->start_handle = self->handle; self->end_handle = self->handle; diff --git a/devices/ble_hci/common-hal/_bleio/__init__.c b/devices/ble_hci/common-hal/_bleio/__init__.c index 9663e706998..c5244f5ef12 100644 --- a/devices/ble_hci/common-hal/_bleio/__init__.c +++ b/devices/ble_hci/common-hal/_bleio/__init__.c @@ -21,8 +21,6 @@ // UUID shared by all cccd's. bleio_uuid_obj_t cccd_uuid; -bool vm_used_ble; - // void check_sec_status(uint8_t sec_status) { // if (sec_status == BLE_GAP_SEC_STATUS_SUCCESS) { // return; @@ -30,7 +28,7 @@ bool vm_used_ble; // switch (sec_status) { // case BLE_GAP_SEC_STATUS_UNSPECIFIED: -// mp_raise_bleio_SecurityError(MP_ERROR_TEXT("Unspecified issue. Can be that the pairing prompt on the other device was declined or ignored.")); +// mp_raise_bleio_SecurityError(MP_ERROR_TEXT("Unspecified issue. The pairing request on the other device may have been declined or ignored.")); // return; // default: // mp_raise_bleio_SecurityError(MP_ERROR_TEXT("Unknown security error: 0x%04x"), sec_status); @@ -38,31 +36,36 @@ bool vm_used_ble; // } void common_hal_bleio_init(void) { + // Called on every import of _bleio. This is the only initialization HCI gets: + // unlike other ports, nothing runs at board startup, because HCI is unusable + // until user code supplies an adapter (UART, etc.) anyway. + // Create a UUID object for all CCCD's. + cccd_uuid.base.type = &bleio_uuid_type; + common_hal_bleio_uuid_construct(&cccd_uuid, BLE_UUID_CCCD, NULL); + // Keep an enabled adapter's state: every module that uses _bleio imports it again. + // bleio_reset() resets at the end of each run. + if (!common_hal_bleio_adapter_obj.enabled) { + bleio_hci_reset(); + } } -void bleio_user_reset() { +void bleio_user_reset(void) { // HCI doesn't support the BLE workflow so just do a full reset. bleio_reset(); } // Turn off BLE on a reset or reload. -void bleio_reset() { - // Create a UUID object for all CCCD's. - cccd_uuid.base.type = &bleio_uuid_type; - common_hal_bleio_uuid_construct(&cccd_uuid, BLE_UUID_CCCD, NULL); - +void bleio_reset(void) { bleio_hci_reset(); - if (!common_hal_bleio_adapter_get_enabled(&common_hal_bleio_adapter_obj)) { - return; - } - bleio_adapter_reset(&common_hal_bleio_adapter_obj); - if (!vm_used_ble) { - // No user-code BLE operations were done, so we can maintain the supervisor state. + bleio_adapter_obj_t *adapter = &common_hal_bleio_adapter_obj; + // The adapter belongs to the program and its UART is on the VM heap: always free it. + // Also when the adapter was not kept because enabling it failed. + bleio_adapter_reset(adapter); + if (!adapter->allocated) { return; } - common_hal_bleio_adapter_set_enabled(&common_hal_bleio_adapter_obj, false); - common_hal_bleio_adapter_obj.allocated = false; + adapter->allocated = false; bleio_set_adapter(mp_const_none); @@ -84,7 +87,7 @@ bleio_adapter_obj_t *common_hal_bleio_allocate_adapter_or_raise(void) { return &common_hal_bleio_adapter_obj; } -void common_hal_bleio_check_connected(uint16_t conn_handle) { +void bleio_check_connected(uint16_t conn_handle) { if (conn_handle == BLE_CONN_HANDLE_INVALID) { mp_raise_ConnectionError(MP_ERROR_TEXT("Not connected")); } diff --git a/devices/ble_hci/common-hal/_bleio/__init__.h b/devices/ble_hci/common-hal/_bleio/__init__.h index ae1d3c6559c..a286aae1e73 100644 --- a/devices/ble_hci/common-hal/_bleio/__init__.h +++ b/devices/ble_hci/common-hal/_bleio/__init__.h @@ -31,8 +31,5 @@ typedef struct { #define BLE_GATTS_FIX_ATTR_LEN_MAX (510) /**< Maximum length for fixed length Attribute Values. */ #define BLE_GATTS_VAR_ATTR_LEN_MAX (512) /**< Maximum length for variable length Attribute Values. */ -// Track if the user code modified the BLE state to know if we need to undo it on reload. -extern bool vm_used_ble; - // UUID shared by all CCCD's. extern bleio_uuid_obj_t cccd_uuid; diff --git a/devices/ble_hci/common-hal/_bleio/att.c b/devices/ble_hci/common-hal/_bleio/att.c index 930b4793161..14981f29e86 100644 --- a/devices/ble_hci/common-hal/_bleio/att.c +++ b/devices/ble_hci/common-hal/_bleio/att.c @@ -56,9 +56,6 @@ 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 uint16_t long_write_value_length = 0; // When we send a request, fill this struct with info about the expected response. // We check this against the actual received response. @@ -136,6 +133,8 @@ static void send_error(uint16_t conn_handle, uint8_t opcode, uint16_t handle, ui .code = BT_ATT_OP_ERROR_RSP, }, { .request = opcode, + .handle = handle, + .error = code, }}; hci_send_acl_pkt(conn_handle, BT_L2CAP_CID_ATT, sizeof(rsp), (uint8_t *)&rsp); @@ -187,19 +186,28 @@ static void check_and_save_expected_rsp(uint16_t conn_handle, uint8_t opcode, ui } } +// Frees a slot. The program's Connection is detached, so it doesn't see the next link there. +static void clear_slot(bleio_connection_internal_t *slot, uint8_t reason) { + mp_obj_t connection_obj = slot->connection_obj; + if (connection_obj != NULL && connection_obj != mp_const_none) { + bleio_connection_obj_t *connection = MP_OBJ_TO_PTR(connection_obj); + connection->connection = NULL; + connection->disconnect_reason = reason; + } + slot->connection_obj = mp_const_none; + slot->conn_handle = BLE_CONN_HANDLE_INVALID; + slot->role = 0x00; + memset(&slot->addr, 0x00, sizeof(slot->addr)); + slot->mtu = BT_ATT_DEFAULT_LE_MTU; + slot->remote_service_list = NULL; +} + void bleio_att_reset(void) { max_mtu = BT_ATT_DEFAULT_LE_MTU; timeout = 5000; - long_write_handle = BLE_GATT_HANDLE_INVALID; - long_write_value = NULL; - long_write_value_length = 0; for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) { - bleio_connections[i].conn_handle = BLE_CONN_HANDLE_INVALID; - bleio_connections[i].role = 0x00; - bleio_connections[i].addr.type = 0; - memset(bleio_connections[i].addr.a.val, 0, sizeof_field(bt_addr_t, val)); - bleio_connections[i].mtu = BT_ATT_DEFAULT_LE_MTU; + clear_slot(&bleio_connections[i], BT_HCI_ERR_LOCALHOST_TERM_CONN); } } @@ -513,14 +521,20 @@ void att_add_connection(uint16_t handle, uint8_t role, bt_addr_le_t *peer_addr, } bleio_connections[peer_index].conn_handle = handle; + bleio_connections[peer_index].connection_obj = mp_const_none; + // adapter.connections is built again with this one. + common_hal_bleio_adapter_obj.connection_objs = NULL; bleio_connections[peer_index].role = role; bleio_connections[peer_index].mtu = BT_ATT_DEFAULT_LE_MTU; memcpy(&bleio_connections[peer_index].addr, peer_addr, sizeof(bleio_connections[peer_index].addr)); + // Made by discover_remote_services(), on the program's heap. + bleio_connections[peer_index].remote_service_list = NULL; } void att_remove_connection(uint16_t conn_handle, uint8_t reason) { - (void)reason; + // adapter.connections is built again from what is left. + common_hal_bleio_adapter_obj.connection_objs = NULL; int peer_index = -1; int peer_count = 0; @@ -559,15 +573,9 @@ void att_remove_connection(uint16_t conn_handle, uint8_t reason) { } } } - - long_write_handle = BLE_GATT_HANDLE_INVALID; - long_write_value_length = 0; } - bleio_connections[peer_index].conn_handle = 0xffff; - bleio_connections[peer_index].role = 0x00; - memset(&bleio_connections[peer_index].addr, 0x00, sizeof(bleio_connections[peer_index].addr)); - bleio_connections[peer_index].mtu = BT_ATT_DEFAULT_LE_MTU; + clear_slot(&bleio_connections[peer_index], reason); } uint16_t att_conn_handle(bt_addr_le_t *addr) { @@ -728,52 +736,29 @@ 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; - 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); return; } - uint16_t mtu = req->mtu; - - if (mtu > max_mtu) { - mtu = max_mtu; - } - - for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) { - if (bleio_connections[i].conn_handle == conn_handle) { - bleio_connections[i].mtu = mtu; - break; - } - } - + // Our receive MTU is 23, so the link keeps 23. struct __packed { struct bt_att_hdr h; struct bt_att_exchange_mtu_rsp r; } rsp = { { .code = BT_ATT_OP_MTU_RSP, }, { - .mtu = mtu, + .mtu = max_mtu, }}; 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; - if (dlen != sizeof(struct bt_att_exchange_mtu_rsp)) { return; } - for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) { - if (bleio_connections[i].conn_handle == conn_handle) { - bleio_connections[i].mtu = rsp->mtu; - break; - } - } - check_and_save_expected_rsp(conn_handle, BT_ATT_OP_MTU_RSP, dlen, data); } @@ -784,6 +769,10 @@ static void process_find_info_req(uint16_t conn_handle, uint16_t mtu, uint8_t dl send_error(conn_handle, BT_ATT_OP_FIND_INFO_REQ, req->start_handle, BT_ATT_ERR_INVALID_PDU); return; } + if (req->start_handle == 0 || req->start_handle > req->end_handle) { + send_error(conn_handle, BT_ATT_OP_FIND_INFO_REQ, req->start_handle, BT_ATT_ERR_INVALID_HANDLE); + return; + } typedef struct __packed { struct bt_att_hdr h; @@ -892,49 +881,12 @@ 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[]) { + (void)mtu; 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); - return; - } - - uint8_t response[mtu]; - uint16_t response_length; - - response[0] = BT_ATT_OP_FIND_TYPE_RSP; - response_length = 1; - - // 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); - - // if ((attribute->type() == find_type_req->type) && (attribute->uuidLength() == value_length) && memcmp(attribute->uuidData(), value, value_length) == 0) { - // BLELocalService* service = (BLELocalService*)attribute; - - // // add the start handle - // uint16_t start_handle = service->start_handle(); - // memcpy(&response[response_length], &start_handle, sizeof(start_handle)); - // response_length += sizeof(start_handle); - - // // add the end handle - // uint16_t end_handle = service->end_handle(); - // memcpy(&response[response_length], &end_handle, sizeof(end_handle)); - // response_length += sizeof(end_handle); - // } - - // if ((response_length + 4) > mtu) { - // break; - // } - // } - // } - - if (response_length == 1) { - send_error(conn_handle, BT_ATT_OP_FIND_TYPE_RSP, req->start_handle, BT_ATT_ERR_ATTRIBUTE_NOT_FOUND); - } else { - hci_send_acl_pkt(conn_handle, BT_L2CAP_CID_ATT, response_length, response); - } + // Find By Type Value is not supported. The error must name the request. + send_error(conn_handle, BT_ATT_OP_FIND_TYPE_REQ, req->start_handle, + dlen < sizeof(struct bt_att_find_type_req) ? BT_ATT_ERR_INVALID_PDU : BT_ATT_ERR_ATTRIBUTE_NOT_FOUND); } static void process_read_group_req(uint16_t conn_handle, uint16_t mtu, uint8_t dlen, uint8_t data[]) { @@ -1098,7 +1050,7 @@ static void process_read_or_read_blob_req(uint16_t conn_handle, uint16_t mtu, ui mp_obj_t *attribute_obj = bleio_adapter_get_attribute(&common_hal_bleio_adapter_obj, handle); if (mp_obj_is_type(attribute_obj, &bleio_service_type)) { if (offset) { - send_error(conn_handle, BT_ATT_ERR_ATTRIBUTE_NOT_LONG, handle, BT_ATT_ERR_INVALID_PDU); + send_error(conn_handle, opcode, handle, BT_ATT_ERR_ATTRIBUTE_NOT_LONG); return; } @@ -1139,7 +1091,7 @@ static void process_read_or_read_blob_req(uint16_t conn_handle, uint16_t mtu, ui mp_buffer_info_t bufinfo; mp_get_buffer(characteristic->value, &bufinfo, MP_BUFFER_READ); - if (offset >= bufinfo.len) { + if (offset > bufinfo.len) { send_error(conn_handle, opcode, handle, BT_ATT_ERR_INVALID_OFFSET); return; } @@ -1154,7 +1106,7 @@ static void process_read_or_read_blob_req(uint16_t conn_handle, uint16_t mtu, ui mp_buffer_info_t bufinfo; mp_get_buffer(descriptor->value, &bufinfo, MP_BUFFER_READ); - if (offset >= bufinfo.len) { + if (offset > bufinfo.len) { send_error(conn_handle, opcode, handle, BT_ATT_ERR_INVALID_OFFSET); return; } @@ -1263,46 +1215,34 @@ static void process_read_type_req(uint16_t conn_handle, uint16_t mtu, uint8_t dl rsp_length += data_length; no_data = false; - } else if (mp_obj_is_type(attribute_obj, &bleio_descriptor_type)) { - // 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]; - - att_data->handle = handle; - - mp_buffer_info_t bufinfo; - if (!mp_get_buffer(descriptor->value, &bufinfo, MP_BUFFER_READ)) { - break; + } else { + // Match the value's handle, not the characteristic declaration's. + mp_obj_t value = MP_OBJ_NULL; + if (mp_obj_is_type(attribute_obj, &bleio_descriptor_type)) { + bleio_descriptor_obj_t *descriptor = MP_OBJ_TO_PTR(attribute_obj); + if (bleio_uuid_get_uuid16_or_unknown(descriptor->uuid) == type_uuid) { + value = descriptor->value; + } + } else if (mp_obj_is_type(attribute_obj, &bleio_characteristic_type)) { + bleio_characteristic_obj_t *characteristic = MP_OBJ_TO_PTR(attribute_obj); + if (characteristic->handle == handle && + bleio_uuid_get_uuid16_or_unknown(characteristic->uuid) == type_uuid) { + value = characteristic->value; } - uint16_t value_size = MIN(mtu - rsp_length, bufinfo.len); - memcpy(att_data->value, bufinfo.buf, value_size); - rsp_length += value_size; - - // Only return one descriptor value. - no_data = false; - break; } - - } else if (mp_obj_is_type(attribute_obj, &bleio_characteristic_type)) { - // See if request is for a characteristic value with a 16-bit UUID. - 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]; - - att_data->handle = handle; - + if (value != MP_OBJ_NULL) { mp_buffer_info_t bufinfo; - if (!mp_get_buffer(characteristic->value, &bufinfo, MP_BUFFER_READ)) { - // This shouldn't happen. There should be a buf in characteristic->value. + if (!mp_get_buffer(value, &bufinfo, MP_BUFFER_READ)) { break; } - uint16_t value_size = MIN(mtu - rsp_length, bufinfo.len); + struct bt_att_data *att_data = (struct bt_att_data *)&rsp_bytes[rsp_length]; + att_data->handle = handle; + // The handle and as much of the value as fits in the MTU. + uint16_t value_size = MIN(mtu - rsp_length - sizeof(att_data->handle), bufinfo.len); memcpy(att_data->value, bufinfo.buf, value_size); - rsp_length += value_size; + rsp->r.len = sizeof(att_data->handle) + value_size; + rsp_length += rsp->r.len; - // Only return one characteristic value. no_data = false; break; } @@ -1400,6 +1340,13 @@ static void process_write_req_or_cmd(uint16_t conn_handle, uint16_t mtu, uint8_t return; } + // A CCCD is two bytes; the setter would raise inside the background poll. + if (bufinfo.len != 2) { + if (with_response) { + send_error(conn_handle, BT_ATT_OP_WRITE_REQ, req->handle, BT_ATT_ERR_INVALID_ATTRIBUTE_LEN); + } + return; + } common_hal_bleio_descriptor_set_value(descriptor, &bufinfo); } @@ -1421,107 +1368,6 @@ static void process_write_rsp(uint16_t conn_handle, uint8_t dlen, uint8_t data[] check_and_save_expected_rsp(conn_handle, BT_ATT_OP_WRITE_RSP, dlen, 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; - - 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); - return; - } - - uint16_t handle = req->handle; - uint16_t offset = req->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); - return; - } - - mp_obj_t *attribute = bleio_adapter_get_attribute(&common_hal_bleio_adapter_obj, handle); - - if (!mp_obj_is_type(attribute, &bleio_characteristic_type)) { - send_error(conn_handle, BT_ATT_OP_PREPARE_WRITE_REQ, handle, BT_ATT_ERR_ATTRIBUTE_NOT_LONG); - return; - } - - 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); - return; - } - - if ((characteristic->props & CHAR_PROP_WRITE) == 0) { - send_error(conn_handle, BT_ATT_OP_PREPARE_WRITE_REQ, handle, BT_ATT_ERR_WRITE_NOT_PERMITTED); - return; - } - - // FIX if (long_write_handle == BLE_GATT_HANDLE_INVALID) - // int valueSize = characteristic->valueSize(); - - // long_write_value = (uint8_t*)realloc(long_write_value, valueSize); - // long_write_value_length = 0; - // long_write_handle = handle; - - // memset(long_write_value, 0x00, valueSize); - // } else if (long_write_handle != handle) { - // send_error(conn_handle, BT_ATT_OP_PREPARE_WRITE_REQ, handle, BT_ATT_ERR_UNLIKELY); - // return; - // } - - // uint8_t value_length = dlen - sizeof(struct bt_att_prepare_write_req); - // uint8_t* value = &data[sizeof(struct bt_att_prepare_write_req)]; - - // if ((offset != long_write_value_length) || ((offset + value_length) > (uint16_t)characteristic->valueSize())) { - // send_error(conn_handle, BT_ATT_OP_PREPARE_WRITE_REQ, handle, BT_ATT_ERR_INVALID_OFFSET); - // return; - // } - - // memcpy(long_write_value + offset, value, value_length); - // long_write_value_length += value_length; - - // uint8_t response[mtu]; - // uint16_t response_length; - - // response[0] = BT_ATT_OP_PREP_WRITE_RSP; - // memcpy(&response[1], data, dlen); - // response_length = dlen + 1; - - // hci_send_acl_pkt(conn_handle, BT_L2CAP_CID_ATT, response_length, response); -} - -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; - - 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); - return; - } - - if (long_write_handle && (req->flags & 0x01)) { - // 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); - break; - } - } - } - - long_write_handle = BLE_GATT_HANDLE_INVALID; - long_write_value_length = 0; - - uint8_t response[mtu]; - uint16_t response_length; - - response[0] = BT_ATT_OP_EXEC_WRITE_RSP; - response_length = 1; - - hci_send_acl_pkt(conn_handle, BT_L2CAP_CID_ATT, response_length, response); -} - static void process_notify_or_indicate(uint16_t conn_handle, uint8_t opcode, uint8_t dlen, uint8_t data[]) { if (dlen < 2) { return; // drop @@ -1632,7 +1478,13 @@ void att_write_cmd(uint16_t conn_handle, uint16_t handle, const uint8_t *data, u send_req(conn_handle, sizeof(cmd_bytes), cmd_bytes); } +// An ATT opcode with this bit set is a command. +#define ATT_CMD_FLAG 0x40 + void att_process_data(uint16_t conn_handle, uint8_t dlen, uint8_t data[]) { + if (dlen == 0) { + return; + } // Opcode is a single byte at the front of the data. uint8_t opcode = data[0]; @@ -1642,27 +1494,17 @@ void att_process_data(uint16_t conn_handle, uint8_t dlen, uint8_t data[]) { uint16_t mtu = att_mtu(conn_handle); + // Server only: the ATT client is not implemented, so responses and notifications fall to + // the default and are dropped. An indication still gets its Confirmation. switch (opcode) { - case BT_ATT_OP_ERROR_RSP: - process_error(conn_handle, dlen, data); - break; - case BT_ATT_OP_MTU_REQ: process_mtu_req(conn_handle, dlen, data); break; - case BT_ATT_OP_MTU_RSP: - process_mtu_rsp(conn_handle, dlen, data); - break; - case BT_ATT_OP_FIND_INFO_REQ: process_find_info_req(conn_handle, mtu, dlen, data); break; - case BT_ATT_OP_FIND_INFO_RSP: - process_find_info_rsp(conn_handle, dlen, data); - break; - case BT_ATT_OP_FIND_TYPE_REQ: process_find_type_req(conn_handle, mtu, dlen, data); break; @@ -1671,45 +1513,20 @@ void att_process_data(uint16_t conn_handle, uint8_t dlen, uint8_t data[]) { process_read_type_req(conn_handle, mtu, dlen, data); break; - case BT_ATT_OP_READ_TYPE_RSP: - process_read_type_rsp(conn_handle, dlen, data); - break; - case BT_ATT_OP_READ_GROUP_REQ: process_read_group_req(conn_handle, mtu, dlen, data); break; - case BT_ATT_OP_READ_GROUP_RSP: - process_read_group_rsp(conn_handle, dlen, data); - break; - case BT_ATT_OP_READ_REQ: case BT_ATT_OP_READ_BLOB_REQ: process_read_or_read_blob_req(conn_handle, mtu, opcode, dlen, data); break; - case BT_ATT_OP_READ_RSP: - process_read_rsp(conn_handle, dlen, data); - break; - case BT_ATT_OP_WRITE_REQ: case BT_ATT_OP_WRITE_CMD: process_write_req_or_cmd(conn_handle, mtu, opcode, dlen, data); break; - case BT_ATT_OP_WRITE_RSP: - process_write_rsp(conn_handle, dlen, data); - break; - - case BT_ATT_OP_PREPARE_WRITE_REQ: - process_prepare_write_req(conn_handle, mtu, dlen, data); - break; - - case BT_ATT_OP_EXEC_WRITE_REQ: - process_exec_write_req(conn_handle, mtu, dlen, data); - break; - - case BT_ATT_OP_NOTIFY: case BT_ATT_OP_INDICATE: process_notify_or_indicate(conn_handle, opcode, dlen, data); break; @@ -1718,10 +1535,12 @@ void att_process_data(uint16_t conn_handle, uint8_t dlen, uint8_t data[]) { process_confirm(conn_handle, dlen, data); break; - case BT_ATT_OP_READ_MULT_REQ: - case BT_ATT_OP_SIGNED_WRITE_CMD: default: - send_error(conn_handle, opcode, 0x00, BT_ATT_ERR_NOT_SUPPORTED); + // Answer only requests: a command has the command flag, and responses, + // notifications and indications have odd opcodes (a confirmation has its case). + if (!(opcode & (ATT_CMD_FLAG | 0x01))) { + send_error(conn_handle, opcode, 0x00, BT_ATT_ERR_NOT_SUPPORTED); + } break; } } diff --git a/devices/ble_hci/common-hal/_bleio/hci.c b/devices/ble_hci/common-hal/_bleio/hci.c index 126f05fbae2..3ae80fc037c 100644 --- a/devices/ble_hci/common-hal/_bleio/hci.c +++ b/devices/ble_hci/common-hal/_bleio/hci.c @@ -70,9 +70,10 @@ typedef struct __attribute__ ((packed)) { typedef struct __attribute__ ((packed)) { uint8_t pkt_type; + // One type for all three, so the MS bitfield layout (MinGW) packs them into 16 bits. 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. + uint16_t pb : 2; // Packet boundary flag: ACL_DATA_PB values. + uint16_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; @@ -118,6 +119,8 @@ static size_t cmd_response_len; static uint8_t *cmd_response_data; static volatile bool hci_poll_in_progress = false; +// Commands or ACL writes in flight: the advertising timeout waits until there are none. +static volatile uint8_t hci_waits; ////////////////////////////////////////////////////////////////////// @@ -129,6 +132,13 @@ static volatile bool hci_poll_in_progress = false; 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; + // Drop a frame longer than the buffer, and continuation fragments with no frame started. + const bool middle = pkt->pb == ACL_DATA_PB_MIDDLE; + if ((middle && acl_data_len == 0) || + (middle ? acl_data_len : 0) + pkt->data_len > sizeof(acl_data_buffer)) { + acl_data_len = 0; + return; + } if (pkt->pb != ACL_DATA_PB_MIDDLE) { // This is the start of a fragmented acl_data packet or is a full packet. memcpy(acl_data_buffer, pkt->data, pkt->data_len); @@ -141,10 +151,11 @@ static void process_acl_data_pkt(uint8_t pkt_len, uint8_t pkt_data[]) { } acl_data_t *acl = (acl_data_t *)&acl_data_buffer; - if (acl_data_len != sizeof(acl) + acl->acl_data_len) { + if (acl_data_len != sizeof(*acl) + acl->acl_data_len) { // We don't have the full packet yet. return; } + acl_data_len = 0; if (acl->cid == BT_L2CAP_CID_ATT) { att_process_data(pkt->handle, acl->acl_data_len, acl->acl_data); @@ -168,9 +179,13 @@ static void process_acl_data_pkt(uint8_t pkt_len, uint8_t pkt_data[]) { // Process number of completed packets. Reduce number of pending packets by reported // number of completed. static void process_num_comp_pkts(uint16_t handle, uint16_t num_pkts) { - if (num_pkts && pending_pkt > num_pkts) { - pending_pkt -= num_pkts; - } else { + pending_pkt -= MIN(pending_pkt, num_pkts); +} + +static void remove_link(uint16_t handle, uint8_t reason) { + att_remove_connection(handle, reason); + // The controller frees a link's buffers without Number of Completed Packets. + if (!att_is_connected()) { pending_pkt = 0; } } @@ -184,7 +199,7 @@ static void process_evt_pkt(size_t pkt_len, uint8_t pkt_data[]) { (struct bt_hci_evt_disconn_complete *)pkt->params; (void)disconn_complete; - att_remove_connection(disconn_complete->handle, disconn_complete->reason); + remove_link(disconn_complete->handle, disconn_complete->reason); // FIX L2CAPSignaling.removeConnection(disconn_complete->handle, disconn_complete->reason); break; } @@ -283,7 +298,7 @@ static void process_evt_pkt(size_t pkt_len, uint8_t pkt_data[]) { default: #if HCI_DEBUG - mp_printf(&mp_plat_print, "process_evt_pkt: Unknown event: %02x\n"); + mp_printf(&mp_plat_print, "process_evt_pkt: Unknown event: %02x\n", pkt->evt); #endif break; } @@ -293,6 +308,7 @@ void bleio_hci_reset(void) { rx_idx = 0; pending_pkt = 0; hci_poll_in_progress = false; + hci_waits = 0; bleio_att_reset(); } @@ -308,7 +324,6 @@ hci_result_t hci_poll_for_incoming_pkt(void) { // Assert RTS low to say we're ready to read data. common_hal_digitalio_digitalinout_set_value(common_hal_bleio_adapter_obj.rts_digitalinout, false); - int errcode = 0; bool packet_is_complete = false; // Read bytes until we run out. There may be more than one packet in the input buffer. @@ -316,10 +331,13 @@ hci_result_t hci_poll_for_incoming_pkt(void) { common_hal_busio_uart_rx_characters_available(common_hal_bleio_adapter_obj.hci_uart) > 0) { // Read just one character a a time, so we don't accidentally get part of a second - // packet. + // packet. A read can fail with EAGAIN although a character is waiting: the next + // read must not see that error. + int errcode = 0; size_t num_read = common_hal_busio_uart_read(common_hal_bleio_adapter_obj.hci_uart, rx_buffer + rx_idx, 1, &errcode); if (num_read == 0) { + hci_poll_in_progress = false; return HCI_OK; } if (errcode) { @@ -327,12 +345,16 @@ hci_result_t hci_poll_for_incoming_pkt(void) { continue; } hci_poll_in_progress = false; + #if HCI_DEBUG mp_printf(&mp_plat_print, "HCI_READ_ERROR, errcode: %x\n", errcode); + #endif return HCI_READ_ERROR; } rx_idx++; if (rx_idx >= sizeof(rx_buffer)) { // Incoming packet is too large. Should not happen. + rx_idx = 0; + hci_poll_in_progress = false; return HCI_READ_ERROR; } @@ -345,6 +367,8 @@ hci_result_t hci_poll_for_incoming_pkt(void) { packet_is_complete = true; } if (rx_idx > total_len) { + rx_idx = 0; + hci_poll_in_progress = false; return HCI_PACKET_SIZE_ERROR; } } @@ -358,6 +382,8 @@ hci_result_t hci_poll_for_incoming_pkt(void) { packet_is_complete = true; } if (rx_idx > total_len) { + rx_idx = 0; + hci_poll_in_progress = false; return HCI_PACKET_SIZE_ERROR; } } @@ -448,37 +474,60 @@ static hci_result_t send_command(uint16_t opcode, uint8_t params_len, void *para dump_cmd_pkt(true, sizeof(tx_buffer), tx_buffer); #endif + // Busy from before the write: a UART write may run background tasks. + hci_waits++; + cmd_response_received = false; int result = write_pkt(tx_buffer, cmd_pkt_len); if (result != HCI_OK) { + hci_waits--; return result; } - cmd_response_received = false; - // Wait for a response. Note that other packets may be received that are not // command responses. + result = HCI_RESPONSE_TIMEOUT; uint64_t start = supervisor_ticks_ms64(); while (supervisor_ticks_ms64() - start < RESPONSE_TIMEOUT_MSECS) { - // RUN_BACKGROUND_TASKS includes hci_poll_for_incoming_pkt(); RUN_BACKGROUND_TASKS; + // Poll here too: background tasks don't nest, so from one nothing else would read the + // answer. + hci_poll_for_incoming_pkt(); if (cmd_response_received && cmd_response_opcode == opcode) { // If this is definitely a response to the command that was sent, // return the status value, which will will be // BT_HCI_ERR_SUCCESS (0x00) if the command succeeded, // or a BT_HCI_ERR_x value (> 0x00) if there was a problem. - return cmd_response_status; + result = cmd_response_status; + break; } } + hci_waits--; + + // HCI_RESPONSE_TIMEOUT: no I/O error, but no response sent back in time. + return result; +} - // No I/O error, but no response sent back in time. - return HCI_RESPONSE_TIMEOUT; +bool hci_busy(void) { + return hci_waits > 0 || hci_poll_in_progress; } hci_result_t hci_send_acl_pkt(uint16_t handle, uint8_t cid, uint16_t data_len, uint8_t *data) { - // Wait for all backlogged packets to finish. - while (pending_pkt >= common_hal_bleio_adapter_obj.max_acl_num_buffers) { - // RUN_BACKGROUND_TASKS includes hci_poll_for_incoming_pkt(); + // Wait for a free controller buffer, but not forever. Outside the poll, one is kept + // for the responses the poll sends. + const size_t max_pkt = common_hal_bleio_adapter_obj.max_acl_num_buffers; + const bool in_poll = hci_poll_in_progress; + // Busy until the packet is written: the wait and the UART write may run background tasks. + hci_waits++; + uint64_t start = supervisor_ticks_ms64(); + while (pending_pkt + (max_pkt > 1 && !in_poll) >= max_pkt) { + // Inside the poll no credit can come back. + if (in_poll || supervisor_ticks_ms64() - start > RESPONSE_TIMEOUT_MSECS) { + hci_waits--; + return HCI_WRITE_TIMEOUT; + } RUN_BACKGROUND_TASKS; + // As in send_command(): the credits arrive in packets read here. + hci_poll_for_incoming_pkt(); } // buf_len is size of entire packet including header. @@ -489,7 +538,9 @@ hci_result_t hci_send_acl_pkt(uint16_t handle, uint8_t cid, uint16_t data_len, u 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; + // Host-to-controller LE data must use the non-flushable start flag; NimBLE + // controllers (ESP32-C6) silently discard packets with ACL_DATA_PB_FIRST_FLUSH. + acl_pkt->pb = ACL_DATA_PB_FIRST_NON_FLUSH; acl_pkt->bc = 0; acl_pkt->data_len = (uint16_t)(sizeof(acl_data_t) + data_len); acl_data->acl_data_len = data_len; @@ -505,7 +556,10 @@ hci_result_t hci_send_acl_pkt(uint16_t handle, uint8_t cid, uint16_t data_len, u int errcode = 0; common_hal_busio_uart_write(common_hal_bleio_adapter_obj.hci_uart, tx_buffer, buf_len, &errcode); + hci_waits--; if (errcode) { + // Not sent: give the credit back. + pending_pkt--; return HCI_WRITE_ERROR; } return HCI_OK; @@ -608,7 +662,9 @@ hci_result_t hci_le_set_extended_advertising_parameters(uint8_t handle, uint16_t .prim_channel_map = prim_channel_map, .own_addr_type = own_addr_type, // .peer_addr set below. + .filter_policy = filter_policy, .tx_power = tx_power, + .prim_adv_phy = prim_adv_phy, .sec_adv_max_skip = sec_adv_max_skip, .sec_adv_phy = sec_adv_phy, .sid = sid, @@ -619,6 +675,7 @@ hci_result_t hci_le_set_extended_advertising_parameters(uint8_t handle, uint16_t 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)); + params.peer_addr.type = peer_addr->type; 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); } @@ -672,6 +729,18 @@ hci_result_t hci_le_set_extended_advertising_data(uint8_t handle, uint8_t op, ui return send_command(BT_HCI_OP_LE_SET_EXT_ADV_DATA, sizeof(params) - (max_len - valid_len), ¶ms); } +hci_result_t hci_le_set_extended_scan_response_data(uint8_t handle, uint8_t op, uint8_t frag_pref, uint8_t len, uint8_t data[]) { + const uint8_t max_len = sizeof_field(struct bt_hci_cp_le_set_ext_scan_rsp_data, data); + uint8_t valid_len = MIN(len, max_len); + struct bt_hci_cp_le_set_ext_scan_rsp_data params = { + .handle = handle, + .op = op, + .frag_pref = frag_pref, + .len = valid_len, + }; + memcpy(params.data, data, valid_len); + return send_command(BT_HCI_OP_LE_SET_EXT_SCAN_RSP_DATA, sizeof(params) - (max_len - valid_len), ¶ms); +} hci_result_t hci_le_set_scan_response_data(uint8_t len, uint8_t data[]) { struct bt_hci_cp_le_set_scan_rsp_data params = { @@ -769,7 +838,12 @@ hci_result_t hci_disconnect(uint16_t handle) { .reason = BT_HCI_ERR_REMOTE_USER_TERM_CONN, }; - return send_command(BT_HCI_OP_DISCONNECT, sizeof(params), ¶ms); + hci_result_t result = send_command(BT_HCI_OP_DISCONNECT, sizeof(params), ¶ms); + // The controller no longer knows the link: its Disconnection Complete was lost. + if (result == BT_HCI_ERR_UNKNOWN_CONN_ID) { + remove_link(handle, result); + } + return result; } void hci_check_error(hci_result_t result) { diff --git a/devices/ble_hci/common-hal/_bleio/hci.h b/devices/ble_hci/common-hal/_bleio/hci.h index fffed7ee151..58bf35943f1 100644 --- a/devices/ble_hci/common-hal/_bleio/hci.h +++ b/devices/ble_hci/common-hal/_bleio/hci.h @@ -28,6 +28,7 @@ #pragma once +#include #include #include "common-hal/_bleio/hci_include/hci.h" @@ -68,6 +69,9 @@ hci_result_t hci_le_set_advertising_parameters(uint16_t min_interval, uint16_t m hci_result_t hci_le_set_extended_advertising_data(uint8_t handle, uint8_t op, uint8_t frag_pref, uint8_t len, uint8_t data[]); 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[]); hci_result_t hci_le_set_extended_advertising_parameters(uint8_t handle, uint16_t props, uint32_t prim_min_interval, uint32_t prim_max_interval, 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); +// Sends at most one fragment (251 bytes); longer data is truncated. +// Returns HCI_OK or the HCI error status; no output values. +hci_result_t hci_le_set_extended_scan_response_data(uint8_t handle, uint8_t op, uint8_t frag_pref, uint8_t len, uint8_t data[]); hci_result_t hci_le_set_random_address(uint8_t addr[6]); hci_result_t hci_le_set_scan_enable(uint8_t enable, uint8_t filter_dup); @@ -75,6 +79,8 @@ hci_result_t hci_le_set_scan_parameters(uint8_t scan_type, uint16_t interval, ui hci_result_t hci_le_set_scan_response_data(uint8_t length, uint8_t data[]); hci_result_t hci_poll_for_incoming_pkt(void); +// A command or ACL write is in flight, or a packet is being handled: send no command now. +bool hci_busy(void); hci_result_t hci_read_bd_addr(bt_addr_t *addr); hci_result_t hci_read_buffer_size(uint16_t *acl_max_len, uint8_t *sco_max_len, uint16_t *acl_max_num, uint16_t *sco_max_num); diff --git a/docs/README.md b/docs/README.md index cddc45b03b3..fb29feb7c21 100644 --- a/docs/README.md +++ b/docs/README.md @@ -23,6 +23,23 @@ In `circuitpython/`, build the docs: You'll find the index page at `_build/html/index.html`. +### Building the PDF + +The PDF build also needs LaTeX and `rsvg-convert`. On Debian or Ubuntu, install them with: + + sudo apt install latexmk librsvg2-bin texlive-fonts-recommended texlive-latex-recommended texlive-latex-extra + +Then build the PDF: + + make latexpdf + +You'll find it at `_build/latex/CircuitPython.pdf`. + +`pdflatex`'s output is verbose, with thousands of inconsequential warnings, so it goes to +`_build/latex/CircuitPython.log` instead of the console. To see it on the console anyway: + + make latexpdf LATEXMKOPTS= + ### More flexibility Running `make` by itself will list out the multiple doc generating commands available. @@ -38,8 +55,9 @@ All commands will, by default, run with `-E` (forces a rebuild from scratch of d # will turn OFF the force rebuild and make it doubly verbose when running make html FORCE= VERBOSE="-v -v" -You can also pass other options to sphinx by using `SPHINXOPTS`. +You can also pass other options to sphinx by using `SPHINXOPTS`. It replaces the default +options, `-W --keep-going -j auto`, so include any of those you still want: - make html SPHINXOPTS="-T" + make html SPHINXOPTS="-W --keep-going -j auto -T" For more flexibility and customization, take a look at the Makefile for all variables you can pass in and overwrite. diff --git a/docs/environment.rst b/docs/environment.rst index 82d7e8790bc..cf52962624a 100644 --- a/docs/environment.rst +++ b/docs/environment.rst @@ -1,70 +1,94 @@ Environment Variables ===================== -CircuitPython 8.0.0 introduces support for environment variables. Environment -variables are commonly used to store "secrets" such as Wi-Fi passwords and API -keys. This method *does not* make them secure. It only separates them from the -code. +CircuitPython provides support for environment variables. These values +can be examined by user code, and are also used as settings by CircuitPython during startup. + +CircuitPython looks for a file called ``settings.toml`` at the **CIRCUITPY** drive root +to find the values of environment variables, +The file format is a subset of the `TOML config file language `__. -CircuitPython uses a file called ``settings.toml`` at the drive root (no -folder) as the environment. User code can access the values from the file -using `os.getenv()`. It is recommended to save any values used repeatedly in a -variable because `os.getenv()` will parse the ``settings.toml`` file contents -on every access. +User code can access the values from the file using either `os.getenv()` or `supervisor.get_setting()` +The value returned by `os.getenv()` is always a string, but `supervisor.get_setting()` +will parse a value into a Python object: a string, an integer, a float, or a boolean. -CircuitPython only supports a subset of the full toml specification, see below -for more details. The subset is very "Python-like", which is a key reason we -selected the format. +Both `os.getenv()` and `supervisor.get_setting()` +read and parse the ``settings.toml`` file on every access. +It will save time to copy any values you use repeatedly into variables. -Due to technical limitations it probably also accepts some files that are -not valid TOML files; bugs of this nature are subject to change (i.e., be -fixed) without the usual deprecation period for incompatible changes. +Environment variables are sometimes used to store "secrets" such as Wi-Fi passwords and API +keys. The ``settings.toml`` file *does not* make the secrets secure. It only separates them from the +code. -File format example: +CircuitPython supports only a subset of the full TOML specification; see below for more details. +The subset is very "Python-like", which is a key reason the format was selected. +To make the code simpler, the implementation accepts some files that are +not valid TOML, but do not depend on this. -.. code-block:: +The full TOML specification provides for tables labeled with table names in brackets, like +``[table_name]``. +CircuitPython does not support this and ignores any explicit inline TOML tables. - str_key="Hello world" # with trailing comment - int_key = 7 - unicode_key="œuvre" - unicode_key2="\\u0153uvre" # same as above - unicode_key3="\\U00000153uvre" # same as above - escape_codes="supported, including \\r\\n\\"\\\\" - # comment - [subtable] - subvalue="cannot retrieve this using getenv" +Here is an example ``settings.toml`` file. +Entries consist of a key and value, separated by an ``=`` sign. +Upper and lower case may both be used in the key name. +.. code-block:: -Details of the toml language subset + # Comment. + CIRCUITPY_WIFI_PASSWORD = "mypassword" + GREETING="Hello world" # trailing comments are ok + REPEAT_COUNT = 7 # an integer + CIRCUITPY_SDCARD_USB = false # a boolean + delay = 0.75 # a float + FRENCH="œuvre" # unicode can be used + FRENCH2="\u0153uvre" # same unicode string, using a 16-bit escape code + FRENCH3="\U00000153uvre" # same unicode string, using a 32-bit escape code + STRING_WITH_ESCAPE_CODES="supported, including \r \n \" \\" + +Details of the TOML language subset ----------------------------------- -* The content is required to be in UTF-8 encoding -* The supported data types are string and integer -* Only basic strings are supported, not triple-quoted strings -* Only integers supported by strtol. (no 0o, no 0b, no underscores 1_000, 011 - is 9, not 11) -* Only bare keys are supported +* The content must be in UTF-8 encoding +* The supported data types are strings, integers, floats, and booleans. +* Whitespace is allowed. +* Only basic strings are supported, not triple-quoted strings. +* Integers may be decimal, hexadecimal ``0x1F``, octal ``0o17``, or binary ``0b101``, + and may contain underscores ``1_000``. + Unlike TOML, a sign is also allowed before ``0x``, ``0o``, and ``0b``, + the prefix may be uppercase, and underscores need not be between digits. +* Leading zeros are not allowed: ``011`` is an error, not 9 or 11. +* Only bare keys are supported. * Duplicate keys are not diagnosed. -* Comments are supported -* Only values from the "root table" can be retrieved -* due to technical limitations, the content of multi-line - strings can erroneously be parsed as a value. +* Comments are allowed. +* Only values from the "root table" can be retrieved. + CircuitPython behavior ---------------------- -CircuitPython will also read the environment to configure its behavior. Other -keys are ignored by CircuitPython. Here are the keys it uses: +On startup, CircuitPython looks for for certain key/value pairs to use as configuration values. +Some values are read only once, after a hard reset, and others are read on each reload (ctrl-D in the REPL). +If you edit ``settings.toml`` and a reload doesn't read your changes, +then try a hard reset (a power cycle or pressing the reset button). +You can also include any other key/value pairs in the file for use with your own code. + +Keys that affect CircuitPython behavior +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +CIRCUITPY_BLE_NAME (string) +~~~~~~~~~~~~~~~~~~~~~~~~~~~ +If supplied, sets the BLE name the board advertises as, including for the BLE workflow. +Otherwise, defaults to ``CIRCUITPYxxxx``, where ``xxxx`` varies per board. -Core CircuitPython keys -^^^^^^^^^^^^^^^^^^^^^^^ +CIRCUITPY_BLE_WORKFLOW (boolean) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +If ``false``, disable the BLE workflow. Defaults to ``true``. If ``false``, +changing ``supervisor.runtime.ble_workflow`` has no effect. -CIRCUITPY_BLE_NAME -~~~~~~~~~~~~~~~~~~ -Default BLE name the board advertises as, including for the BLE workflow. -CIRCUITPY_HEAP_START_SIZE -~~~~~~~~~~~~~~~~~~~~~~~~~ +CIRCUITPY_HEAP_START_SIZE (integer) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Sets the initial size of the python heap, allocated from the outer heap. Must be a multiple of 4. The default is currently 8192. The python heap will grow by doubling and redoubling this initial size until it cannot fit in the outer heap. @@ -72,37 +96,110 @@ Larger values will reserve more RAM for python use and prevent the supervisor an from large allocations of their own. Smaller values will likely grow sooner than large start sizes. -CIRCUITPY_PYSTACK_SIZE -~~~~~~~~~~~~~~~~~~~~~~ +CIRCUITPY_PYSTACK_SIZE (integer) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Sets the size of the python stack. Must be a multiple of 4. The default value is currently 1536. Increasing the stack reduces the size of the heap available to python code. Used to avoid "Pystack exhausted" errors when the code can't be reworked to avoid it. -CIRCUITPY_WEB_API_PASSWORD -~~~~~~~~~~~~~~~~~~~~~~~~~~ +CIRCUITPY_USB_HOST_ISO_BUFFER_SIZE (integer) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Allocates a buffer for incoming isochronous USB data, such as from a USB camera +read with ``usb.core``, on boards with a ``usb_host.Port``. Without it, isochronous IN +transfers return at most one packet per USB frame, so data arriving while code is busy is lost. +The value is rounded up to the next power of two and limited to the range 2048 +to 65536. A typical value for a USB camera is 16384. The buffer is allocated when +the USB host port is created and is never freed. +Only available on rp2 boards with isochronous host support. + +CIRCUITPY_WEB_API_PASSWORD (string) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Password required to make modifications to the board from the Web Workflow. +If the password is not specified, the Web Workflow is not enabled. -CIRCUITPY_WEB_API_PORT -~~~~~~~~~~~~~~~~~~~~~~ -TCP port number used for the web HTTP API. Defaults to 80 when omitted. +CIRCUITPY_WEB_API_PORT (integer) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +TCP port number used for the Web Workflow HTTP API. Defaults to 80 when omitted. -CIRCUITPY_WEB_INSTANCE_NAME -~~~~~~~~~~~~~~~~~~~~~~~~~~~ -Name the board advertises as for the WEB workflow. Defaults to human readable board name if omitted. +CIRCUITPY_WEB_INSTANCE_NAME (string) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Human-friendly name the board advertises over mDNS for the Web Workflow. +Defaults to the human-readable board name if omitted. +This is not the hostname. + +CIRCUITPY_WEB_DISPLAY_RATE_LIMIT (integer) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Most bytes per second sent to a viewer of the board's display (the ``/cp/display/`` +page or a VNC viewer). No limit when omitted or ``0``. A lower limit leaves more time +for ``code.py`` while the display changes a lot, but the viewer catches up more slowly. +Useful on boards whose network co-processor is reached over SPI (AirLift), where sending +can hold up code that has to keep up with something else, such as USB or audio +streaming; ``12800`` suits the Fruit Jam. + +CIRCUITPY_WEB_VNC_PORT (integer) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +TCP port number for VNC viewers to show the board's display, typically 5900. +Off when omitted. There is no password, so anyone who can reach the board +on the network can see the display. + +CIRCUITPY_WEB_VNC_KEYS (boolean) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Set to ``true`` to send keys typed into a VNC viewer on ``CIRCUITPY_WEB_VNC_PORT`` to the +serial console. Defaults to ``false``, which ignores them. There is no password, so +this lets anyone who can reach the board on the network interrupt code and use the REPL, +and only belongs on a network you trust. + +CIRCUITPY_WIFI_SSID (string) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +CIRCUITPY_WIFI_PASSWORD (string) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +If these values are supplied, connects automatically to a local WiFi network +with the specified SSID and password before ``boot.py`` and/or ``code.py`` are run. + +CIRCUITPY_WIFI_HOSTNAME (string) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +If supplied, sets the initial ``wifi.radio.hostname`` to the given value. +Otherwise, the default value is ``cpy--``, +with some shortening for length if necessary. +If the supplied value is an invalid hostname or is too long, it is ignored. + +CIRCUITPY_SDCARD_USB (boolean) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Present a mounted SD card as a USB MSC device. If the board has default pins for an SD card socket, +the card is mounted automatically on startup. +Only one card can be presented. +Defaults to ``true``, except on the Adafruit Memento board, where it defaults to ``false`` +for now to avoid a bug. +SD card presentation can slow down board startup, +so set this to ``false`` if you don't need this feature. + + +Additional board-specific keys +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -CIRCUITPY_WIFI_PASSWORD -~~~~~~~~~~~~~~~~~~~~~~~ -Wi-Fi password used to auto connect to CIRCUITPY_WIFI_SSID. +CIRCUITPY_BOARD_VARIANT (string) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Selects a hardware variant for boards sold in versions that the chip can't tell apart, +such as clones with a different status LED color order. Each board documents the values it +accepts in its ``board.c``. Unknown values are ignored and the board uses its default. +Read at startup. -CIRCUITPY_WIFI_SSID -~~~~~~~~~~~~~~~~~~~ -Wi-Fi SSID to auto-connect to even if user code is not running. +`ESP32-S3 SuperMini `_: +``"rgb_led"`` for boards whose status NeoPixel takes RGB order. To check, run this. +If the LED shows green instead of red, set ``CIRCUITPY_BOARD_VARIANT = "rgb_led"`` +and power cycle. -Additional board specific keys -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +.. code-block:: python + + import board, neopixel + p = neopixel.NeoPixel(board.NEOPIXEL, 1, pixel_order=neopixel.GRB) + p[0] = (255, 0, 0) + +CIRCUITPY_DISPLAY_WIDTH (integer) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +(Sunton, MaTouch boards) -CIRCUITPY_DISPLAY_WIDTH (Sunton, MaTouch) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Selects the correct screen resolution (1024x600 or 800x640) for the particular board variant. If the CIRCUITPY_DISPLAY_WIDTH parameter is set to a value of 1024 the display is initialized during power up at 1024x600 otherwise the display will be initialized at a resolution @@ -112,8 +209,8 @@ of 800x480. `Sunton ESP32-2432S028 `_ `Sunton ESP32-2432S024C `_ -CIRCUITPY_DISPLAY_ROTATION -~~~~~~~~~~~~~~~~~~~~~~~~~~ +CIRCUITPY_DISPLAY_ROTATION (integer) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Selects the correct screen rotation (0, 90, 180 or 270) for the particular board variant. If the CIRCUITPY_DISPLAY_ROTATION parameter is set the display will be initialized during power up with the selected rotation, otherwise the display will be initialized with @@ -124,8 +221,8 @@ a rotation of 0. Attempting to initialize the screen with a rotation other than `Adafruit Feather RP2350 `_ `Adafruit Metro RP2350 `_ -CIRCUITPY_DISPLAY_FREQUENCY -~~~~~~~~~~~~~~~~~~~~~~~~~~~ +CIRCUITPY_DISPLAY_FREQUENCY (integer) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Allows the entry of a display frequency used during the "dotclock" framebuffer construction. If a valid frequency is not defined the board will initialize the framebuffer with a frequency of 12500000hz (12.5Mhz). The value should be entered as an integer in hertz @@ -135,8 +232,8 @@ display frequency. `Sunton ESP32-8048S050 `_ -CIRCUITPY_PICODVI_ENABLE -~~~~~~~~~~~~~~~~~~~~~~~~ +CIRCUITPY_PICODVI_ENABLE (string) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Whether to configure the display at board initialization time, one of the following: .. code-block:: @@ -146,14 +243,22 @@ Whether to configure the display at board initialization time, one of the follow CIRCUITPY_PICODVI_ENABLE="never" A display configured in this manner is available at ``supervisor.runtime.display`` -until it is released by ``displayio.release_displays()``. It does not appear at +until it is released by ``supervisor.runtime.display.deinit()``. It does not appear at ``board.DISPLAY``. `Adafruit Feather RP2350 `_ `Adafruit Metro RP2350 `_ -CIRCUITPY_DISPLAY_WIDTH, CIRCUITPY_DISPLAY_HEIGHT, and CIRCUITPY_DISPLAY_COLOR_DEPTH (RP2350 boards with DVI or HSTX connector) -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +CIRCUITPY_DISPLAY_WIDTH (integer) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +CIRCUITPY_DISPLAY_HEIGHT (integer) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +CIRCUITPY_DISPLAY_COLOR_DEPTH (integer) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +(RP2350 boards with DVI or HSTX connector) + Selects the desired resolution and color depth. Supported resolutions are: @@ -179,14 +284,77 @@ Example: Configure the display to 640x480 black and white (1 bit per pixel): `Adafruit Feather RP2350 `_ `Adafruit Metro RP2350 `_ -CIRCUITPY_TERMINAL_SCALE -~~~~~~~~~~~~~~~~~~~~~~~~ +CIRCUITPY_PICODVI_AUDIO (boolean) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Whether the display configured at board initialization also sends sound through +the DVI cable, as ``supervisor.runtime.audio``. Defaults to true. It needs a 640-wide +output: 640x480, 320x240 or 160x120. Audio uses about 37 KB of internal RAM +next to a 640x480 display. Set this to false to keep that RAM free, for +example on a monitor without speakers. + +``supervisor.runtime.audio`` is a :py:class:`picodvi.AudioOut`. It becomes ``None`` when +the display is released, such as by ``supervisor.runtime.display.deinit()``, or when it is +deinitialized, and stays ``None`` until the next reset. + +`Adafruit Feather RP2350 `_ +`Adafruit Fruit Jam `_ +`Adafruit Metro RP2350 `_ + +CIRCUITPY_SAFEMODE_DELAY (float) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Wait for the specified amount of time, in seconds, for the user to press the reset button +to initiate safe mode after a hard reset. +The status LED blinks during this time. +If not specified, use the default delay, which is one second. + +CIRCUITPY_STORAGE_MAP_FILE (boolean) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Controls direct flash mapping for :py:func:`storage.map_file` and automatic +:py:class:`displayio.OnDiskBitmap` mapping. Defaults to ``true`` on builds that +support file mapping. Set it to ``false`` to use cached file reads for +``OnDiskBitmap`` instead; explicit ``storage.map_file()`` calls then raise +``OSError`` with ``EOPNOTSUPP``, and a ``.mpy`` file is imported into RAM instead +of being run from flash. + +On the Qualia ESP32-S3 RGB666, disabling mapping allows PSRAM XIP to keep the +external-memory cache available during flash writes, so the RGB driver's +bounce-buffer refill can continue. Bitmap drawing may be slower without +mapping; leave it enabled for applications that prioritize bitmap performance. + +This setting is read once after mounting CIRCUITPY at startup. Press RESET or +power-cycle the board after changing it; a reload or Ctrl-D does not change it +because existing flash mappings can persist across reloads. It cannot enable +mapping on builds that do not support it. + +Example: disable file mapping to avoid flash-write display interruptions on +the Qualia: + +.. code-block:: toml + + CIRCUITPY_STORAGE_MAP_FILE = false + +CIRCUITPY_TERMINAL_SCALE (integer) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Allows the entry of a display scaling factor used during the terminalio console construction. The entered scaling factor only affects the terminalio console and has no impact on the UART, Web Workflow, BLE Workflow, etc consoles. -This feature is not enabled on boards that the CIRCUITPY_OS_GETENV (os CIRCUIPTY_FULL_BUILD) +This feature is not enabled on boards that the CIRCUITPY_SETTINGS_TOML (or CIRCUITPY_FULL_BUILD) flag has been set to 0. Currently this is primarily boards with limited flash including some of the Atmel_samd boards based on the SAMD21/M0 microprocessor. +CIRCUITPY_TERMINAL_FONT (string) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Specifies a custom font file path to use for the terminalio console instead of the default +``/fonts/terminal.lvfontbin``. This allows users to create and use custom fonts for the +CircuitPython console. + +This feature requires both CIRCUITPY_SETTINGS_TOML and CIRCUITPY_LVFONTIO to be enabled. + +Example: + +.. code-block:: + + CIRCUITPY_TERMINAL_FONT="/fonts/myfont.lvfontbin" + `boards that the terminalio core module is available on `_ diff --git a/docs/library/array.rst b/docs/library/array.rst index a7a3b5952e1..e1d474cca4f 100644 --- a/docs/library/array.rst +++ b/docs/library/array.rst @@ -8,7 +8,8 @@ Supported format codes: ``b``, ``B``, ``h``, ``H``, ``i``, ``I``, ``l``, ``L``, ``q``, ``Q``, ``f``, ``d`` (the latter 2 depending on the -floating-point support). +floating-point support). ``d`` is not available on non-full builds, such as +most SAMD21 boards. Classes ------- @@ -19,6 +20,10 @@ Classes array are given by an `iterable`. If it is not provided, an empty array is created. + In addition to the methods below, array objects also implement the buffer + protocol. This means the contents of the entire array can be accessed as raw + bytes via a `memoryview` or other interfaces which use this protocol. + .. method:: append(val) Append new element ``val`` to the end of array, growing it. diff --git a/docs/library/binascii.rst b/docs/library/binascii.rst index 1eba46652d7..0797692b020 100644 --- a/docs/library/binascii.rst +++ b/docs/library/binascii.rst @@ -39,6 +39,6 @@ Functions .. function:: crc32(data, value=0, /) - Compute CRC-32, the 32-bit checksum of the bytes in *data* starting with an + Compute CRC-32, the 32-bit checksum of the bytes in ``data`` starting with an initial CRC of *value*. The default initial CRC is 0. The algorithm is consistent with the ZIP file checksum. diff --git a/docs/library/builtins.rst b/docs/library/builtins.rst index 6003c23fb13..c8e05d895e5 100644 --- a/docs/library/builtins.rst +++ b/docs/library/builtins.rst @@ -31,10 +31,41 @@ Functions and types .. class:: bytearray() + |see_cpython| `python:bytearray`. + .. class:: bytes() |see_cpython| `python:bytes`. + .. method:: bytes.decode(encoding='utf-8', errors='strict') + + Decode the bytes object to a string using the specified *encoding*. + + MicroPython supports the following encodings: + + - ``'utf-8'`` or ``'utf8'`` - UTF-8 encoding (default) + - ``'ascii'`` - ASCII encoding (subset of UTF-8) + + The *errors* parameter controls how decoding errors are handled: + + - ``'strict'`` - Raise a ``UnicodeError`` on invalid UTF-8 (default) + - ``'ignore'`` - Skip invalid bytes (requires ``MICROPY_PY_BUILTINS_BYTES_DECODE_ERRORS``) + - ``'replace'`` - Replace invalid bytes with U+FFFD '�' (requires ``MICROPY_PY_BUILTINS_BYTES_DECODE_ERRORS``) + + .. note:: + Error handler support depends on build configuration. On constrained + systems, only ``'strict'`` mode may be available. + + Example:: + + >>> b'\xc2\xa9 2024'.decode('utf-8') # © symbol + '© 2024' + >>> b'hello\xffworld'.decode('utf-8', 'ignore') # Skip invalid bytes + 'helloworld' + + Raises ``LookupError`` if the encoding is not supported, or + ``UnicodeError`` if the data contains invalid UTF-8 and ``errors='strict'``. + .. function:: callable() .. function:: chr() @@ -86,15 +117,9 @@ Functions and types .. class:: int() - .. classmethod:: from_bytes(bytes, byteorder) - - In CircuitPython, the ``byteorder`` parameter must be positional (this is - compatible with CPython). - - .. method:: to_bytes(size, byteorder) + .. classmethod:: from_bytes(bytes, byteorder="big", *, signed=False) - In CircuitPython, the ``byteorder`` parameter must be positional (this is - compatible with CPython). + .. method:: to_bytes(length=1, byteorder="big", *, signed=False) .. function:: isinstance() @@ -156,6 +181,35 @@ Functions and types .. class:: str() + .. method:: str.encode(encoding='utf-8') + + Encode the string to bytes using the specified *encoding*. + + MicroPython supports the following encodings: + + - ``'utf-8'`` or ``'utf8'`` - UTF-8 encoding (default) + - ``'ascii'`` - ASCII encoding (subset of UTF-8) + + Example:: + + >>> '© 2024'.encode('utf-8') # Copyright symbol + b'\xc2\xa9 2024' + + Raises ``LookupError`` if the encoding is not supported. + + .. method:: str.center(width) + + Return a centered string of length *width*. Padding is done using spaces. + + When Unicode support is enabled (``MICROPY_PY_BUILTINS_STR_UNICODE``), this + method counts Unicode characters rather than bytes, ensuring proper alignment + for multi-byte UTF-8 characters. + + Example:: + + >>> 'café'.center(10) # é is 2 bytes in UTF-8 + ' café ' + .. function:: sum() .. function:: super() diff --git a/docs/library/collections.rst b/docs/library/collections.rst index b006a97dcaf..c3ec763d20e 100644 --- a/docs/library/collections.rst +++ b/docs/library/collections.rst @@ -109,3 +109,19 @@ Classes a 2 w 5 b 3 + + .. method:: OrderedDict.popitem() + + Remove and return a (key, value) pair from the dictionary. + Pairs are returned in LIFO order. + + .. admonition:: Difference to CPython + :class: attention + + ``OrderedDict.popitem()`` does not support the ``last=False`` argument and + will always remove and return the last item if present. + + A workaround for this is to use ``pop()`` to remove the first item:: + + first_key = next(iter(d)) + d.pop(first_key) diff --git a/docs/library/errno.rst b/docs/library/errno.rst index 10ecd4d2c79..89f09741d2e 100644 --- a/docs/library/errno.rst +++ b/docs/library/errno.rst @@ -7,7 +7,21 @@ |see_cpython_module| :mod:`python:errno`. This module provides access to symbolic error codes for `OSError` exception. -Some codes are not available on the smallest CircuitPython builds, such as SAMD21, for space reasons. +Most SAMD21 boards, including all SAMD21 boards without external flash, do not include :mod:`errno`. +A few other small builds also do not include it. +To check a particular board, see the :ref:`module-support-matrix`. + +The available codes depend on the build: + +* Most builds provide ``EACCES``, ``EADDRINUSE``, ``EAGAIN``, ``EALREADY``, ``EBADF``, + ``EBUSY``, ``ECONNABORTED``, ``ECONNREFUSED``, ``ECONNRESET``, ``EEXIST``, + ``EHOSTUNREACH``, ``EINPROGRESS``, ``EINVAL``, ``EIO``, ``EISDIR``, ``ENOBUFS``, + ``ENODEV``, ``ENOENT``, ``ENOMEM``, ``ENOSPC``, ``ENOTCONN``, ``EOPNOTSUPP``, + ``EPERM``, ``EROFS``, and ``ETIMEDOUT``. +* SAMD21 builds that include :mod:`errno` provide only ``EACCES``, ``EAGAIN``, ``EEXIST``, + ``EINVAL``, ``EIO``, ``EISDIR``, ``ENODEV``, ``ENOENT``, ``ENOMEM``, and ``EPERM``. + +``dir(errno)`` lists the codes available on a particular board. Constants --------- diff --git a/docs/library/gc.rst b/docs/library/gc.rst index d1625c0d8f3..7e946469f63 100644 --- a/docs/library/gc.rst +++ b/docs/library/gc.rst @@ -2,7 +2,8 @@ ========================================== .. module:: gc - :synopsis: control the garbage collector + :synopsis: control the garbage collector which automatically frees + :ref:`heap memory ` |see_cpython_module| :mod:`python:gc`. @@ -18,6 +19,10 @@ Functions Disable automatic garbage collection. Heap memory can still be allocated, and garbage collection can still be initiated manually using :meth:`gc.collect`. +.. function:: isenabled() + + Returns True if automatic garbage collection is enabled, and False otherwise. + .. function:: collect() Run a garbage collection. @@ -64,3 +69,40 @@ Functions This function is a MicroPython extension. CPython has a similar function - ``set_threshold()``, but due to different GC implementations, its signature and semantics are different. + + Examples + ^^^^^^^^ + + To trigger a garbage collection each time 32768 bytes of RAM have been allocated in total:: + + gc.threshold(32768) + + To restore the default behaviour, only triggering garbage collection when out of memory:: + + gc.threshold(-1) + +Example +------- + +.. code-block:: bash + + >>> import gc + >>> gc.mem_free() # Gets number of bytes free in memory + 8192 + >>> gc.mem_alloc() # Gets number of bytes allocated in memory + 1024 + >>> foo = bytearray(1000) # Create a big array of data + >>> gc.mem_free() # Show that there's less memory available + 7168 + >>> gc.mem_alloc() # Show that there's more memory used + 2048 + >>> del foo # Delete the object + >>> gc.mem_free() # Show that collection hasn't run yet + 7168 + >>> gc.mem_alloc() # That memory is still allocated + 2048 + >>> gc.collect() # Manually run the collection + >>> gc.mem_free() # Now we have reclaimed that memory + 8192 + >>> gc.mem_alloc() # That memory is no longer allocated + 1024 diff --git a/docs/library/index.rst b/docs/library/index.rst index 18b2530a9b5..d5f0b240f1b 100644 --- a/docs/library/index.rst +++ b/docs/library/index.rst @@ -33,8 +33,9 @@ These libraries are not currently enabled in any CircuitPython build, but may be json.rst platform.rst re.rst - sys.rst select.rst + string.templatelib.rst + sys.rst Omitted ``string`` functions ---------------------------- @@ -54,4 +55,4 @@ the following libraries. .. toctree:: :maxdepth: 1 - micropython.rst + ../../shared-bindings/micropython/index.rst diff --git a/docs/library/io.rst b/docs/library/io.rst index ad1fb03c777..8ebb2e8c63f 100644 --- a/docs/library/io.rst +++ b/docs/library/io.rst @@ -71,8 +71,9 @@ buffered, they aren't in MicroPython. (Indeed, that's one of the cases for which we may introduce buffering support.) Note that for efficiency, MicroPython doesn't provide abstract base -classes corresponding to the hierarchy above, and it's not possible -to implement, or subclass, a stream class in pure Python. +classes corresponding to the hierarchy above. However, the +:class:`IOBase` class can be subclassed to implement custom stream +objects in pure Python. Functions --------- @@ -95,6 +96,68 @@ Classes This is type of a file open in text mode, e.g. using ``open(name, "rt")``. You should not instantiate this class directly. +.. class:: IOBase() + + Base class for implementing custom stream objects in Python. Subclasses + can override ``readinto``, ``write``, and ``ioctl`` to create objects + that work with ``print()``, ``json.dump()``, ``select.poll()``, + ``open()`` via a user filesystem, and other stream consumers. + + .. admonition:: Difference to CPython + :class: attention + + In CPython, ``io.IOBase`` has a much larger API surface. MicroPython's + ``IOBase`` is minimal: the C stream infrastructure provides standard + methods like ``read()``, ``readline()``, ``seek()``, ``close()``, and + ``flush()`` automatically. Subclasses only need to implement the + methods below. + + Subclasses implement some or all of the following methods. The C stream + layer calls these internally when user code calls standard stream + functions. + + .. method:: IOBase.readinto(buf) + + Read data into *buf* (a ``bytearray`` sized by the caller). Return the + number of bytes read, 0 at EOF, or ``None`` if no data is available on + a non-blocking stream. Return a negative errno value (e.g. ``-errno.EIO`` + or ``-1``) to signal an error. + + .. method:: IOBase.write(buf) + + Write *buf* (a ``bytearray``) to the stream. Return the number of + bytes written, or ``None`` if a non-blocking stream cannot accept data. + Return a negative errno value to signal an error. + + .. method:: IOBase.ioctl(op, arg) + + Control the stream and query its properties. The operation to perform + is given by *op* which is one of the following integers: + + - 1 -- flush write buffers (*arg* is unused) + - 3 -- poll for readiness; *arg* is a bitmask of events to check, + return a bitmask of ready events. Poll flags: + + * ``0x0001`` -- data available for reading + * ``0x0004`` -- stream ready for writing + * ``0x0008`` -- error condition + * ``0x0010`` -- hang up (e.g. connection closed) + * ``0x0020`` -- invalid request + + - 4 -- close the stream (*arg* is unused) + - 11 -- return the preferred read buffer size, or 0 (*arg* is unused) + + As a minimum ``ioctl(4, ...)`` should be handled to support stream + closure. Implement ``ioctl(3, ...)`` if the stream will be used with + ``select.poll()`` or ``asyncio``. + + Other operations exist for advanced use cases (2 = seek, 5 = timeout, + 10 = fileno); see ``py/stream.h`` for the full list. + + Must always return an integer. Return 0 for success, or ``-1`` for + unsupported operations. (Returning 0 for an unhandled operation tells + the C layer the operation was processed successfully, which may cause + incorrect behaviour.) .. class:: StringIO([string]) .. class:: BytesIO([string]) @@ -129,3 +192,77 @@ Classes :class: attention These constructors are a MicroPython extension. + +IOBase Examples +--------------- + +A minimal write-only stream that collects output into a buffer:: + + import io + + class MyOutput(io.IOBase): + def __init__(self): + self.data = bytearray() + + def write(self, buf): + self.data.extend(buf) + return len(buf) + + def ioctl(self, op, arg): + if op == 4: # close + return 0 + return -1 + + s = MyOutput() + print("hello", file=s) + print(s.data) # bytearray(b'hello\n') + +A readable stream that can be used with ``select.poll()``:: + + import io, select + from micropython import const + + _MP_STREAM_POLL = const(3) + _MP_STREAM_POLL_RD = const(0x0001) + _MP_STREAM_CLOSE = const(4) + + class RingBuffer(io.IOBase): + def __init__(self, size): + self._buf = bytearray(size) + self._size = size + self._wpos = 0 + self._rpos = 0 + + def _available(self): + return (self._wpos - self._rpos) % self._size + + def put(self, data): + for b in data: + self._buf[self._wpos % self._size] = b + self._wpos = (self._wpos + 1) % self._size + + def readinto(self, buf): + n = min(len(buf), self._available()) + for i in range(n): + buf[i] = self._buf[self._rpos % self._size] + self._rpos = (self._rpos + 1) % self._size + return n + + def ioctl(self, op, arg): + if op == _MP_STREAM_POLL: + if arg & _MP_STREAM_POLL_RD and self._available() > 0: + return _MP_STREAM_POLL_RD + return 0 + if op == _MP_STREAM_CLOSE: + return 0 + return -1 + + rb = RingBuffer(64) + rb.put(b"test data") + + poller = select.poll() + poller.register(rb, select.POLLIN) + for obj, flags in poller.poll(0): + buf = bytearray(16) + n = obj.readinto(buf) + print(buf[:n]) # bytearray(b'test data') diff --git a/docs/library/micropython.rst b/docs/library/micropython.rst deleted file mode 100644 index 166192de3a3..00000000000 --- a/docs/library/micropython.rst +++ /dev/null @@ -1,28 +0,0 @@ -:mod:`micropython` -- MicroPython extensions and internals -========================================================== - -.. module:: micropython - :synopsis: access and control MicroPython internals - -Functions ---------- - -.. function:: const(expr) - - Used to declare that the expression is a constant so that the compiler can - optimise it. The use of this function should be as follows:: - - from micropython import const - - CONST_X = const(123) - CONST_Y = const(2 * CONST_X + 1) - - Constants declared this way are still accessible as global variables from - outside the module they are declared in. On the other hand, if a constant - begins with an underscore then it is hidden, it is not available as a global - variable, and does not take up any memory during execution. - - This `const` function is recognised directly by the MicroPython parser and is - provided as part of the :mod:`micropython` module mainly so that scripts can be - written which run under both CPython and MicroPython, by following the above - pattern. diff --git a/docs/library/platform.rst b/docs/library/platform.rst index c091477d84c..c19ef0f5df5 100644 --- a/docs/library/platform.rst +++ b/docs/library/platform.rst @@ -36,3 +36,11 @@ Functions Returns a tuple of strings *(lib, version)*, where *lib* is the name of the libc that MicroPython is linked to, and *version* the corresponding version of this libc. + +.. function:: processor() + + Returns a string with a detailed name of the processor, if one is available. + If no name for the processor is known, it will return an empty string + instead. + + This is currently available only on RISC-V targets (both 32 and 64 bits). diff --git a/docs/library/re.rst b/docs/library/re.rst index 19b15d2d2c2..47f623c5600 100644 --- a/docs/library/re.rst +++ b/docs/library/re.rst @@ -54,6 +54,10 @@ Supported operators and special sequences are: Grouping. Each group is capturing (a substring it captures can be accessed with `match.group()` method). +``(?:...)`` + Non-capturing grouping. Each group is matched using the same rules as + regular grouping, but will not be part of the match object. + ``\d`` Matches digit. Equivalent to ``[0-9]``. @@ -87,7 +91,6 @@ Supported operators and special sequences are: * 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 @@ -154,8 +157,8 @@ Regex objects Compiled regular expression. Instances of this class are created using `re.compile()`. -.. method:: regex.match(string) - regex.search(string) +.. method:: regex.match(string, [pos, [endpos]]) + regex.search(string, [pos, [endpos]]) regex.sub(replace, string, count=0, flags=0, /) Similar to the module-level functions :meth:`match`, :meth:`search` @@ -163,6 +166,16 @@ Compiled regular expression. Instances of this class are created using Using methods is (much) more efficient if the same regex is applied to multiple strings. + The optional second parameter *pos* gives an index in the string where the + search is to start; it defaults to ``0``. This is not completely equivalent + to slicing the string; the ``'^'`` pattern character matches at the real + beginning of the string and at positions just after a newline, but not + necessarily at the index where the search is to start. + + The optional parameter *endpos* limits how far the string will be searched; + it will be as if the string is *endpos* characters long, so only the + characters from *pos* to ``endpos - 1`` will be searched for a match. + .. method:: regex.split(string, max_split=-1, /) Split a *string* using regex. If *max_split* is given, it specifies diff --git a/docs/library/select.rst b/docs/library/select.rst index 08bbe08df2c..dcf1aa781b6 100644 --- a/docs/library/select.rst +++ b/docs/library/select.rst @@ -76,6 +76,9 @@ Methods In case of timeout, an empty list is returned. + Calling ``poll.poll`` is guaranteed to call pending callback functions + before entering the polling loop. + .. admonition:: Difference to CPython :class: attention @@ -93,6 +96,9 @@ Methods won't be processed until new mask is set with `poll.modify()`. This behaviour is useful for asynchronous I/O schedulers. + Calling ``poll.ipoll`` is guaranteed to call pending callback functions + before entering the polling loop. + .. admonition:: Difference to CPython :class: attention diff --git a/docs/library/string.templatelib.rst b/docs/library/string.templatelib.rst new file mode 100644 index 00000000000..4d10bdf124f --- /dev/null +++ b/docs/library/string.templatelib.rst @@ -0,0 +1,225 @@ +:mod:`string.templatelib` -- Template String Support +==================================================== + +.. module:: string.templatelib + :synopsis: PEP 750 template string support + +This module provides support for template strings (t-strings) as defined in +`PEP 750 `_. Template strings are created +using the ``t`` prefix and provide access to both the literal string parts and +interpolated values before they are combined. + +Classes +------- + +.. class:: Template(*args) + + Represents a template string. Template objects are typically created by + t-string syntax (``t"..."``) but can also be constructed directly using + the constructor. + + .. attribute:: strings + + A tuple of string literals that appear between interpolations. + + .. attribute:: interpolations + + A tuple of :class:`Interpolation` objects representing the interpolated + expressions. + + .. attribute:: values + + A read-only property that returns a tuple containing the ``value`` + attribute from each interpolation in the template. + + .. method:: __iter__() + + Iterate over the template contents, yielding string parts and + :class:`Interpolation` objects in the order they appear. Empty strings + are omitted. + + .. method:: __add__(other) + + Concatenate two templates. Returns a new :class:`Template` combining + the strings and interpolations from both templates. + + :raises TypeError: if *other* is not a :class:`Template` + + Template concatenation with ``str`` is prohibited to avoid ambiguity + about whether the string should be treated as a literal or interpolation:: + + t1 = t"Hello " + t2 = t"World" + result = t1 + t2 # Valid + + # TypeError: cannot concatenate str to Template + result = t1 + "World" + +.. class:: Interpolation(value, expression='', conversion=None, format_spec='') + + Represents an interpolated expression within a template string. All + arguments can be passed as keyword arguments. + + .. attribute:: value + + The evaluated value of the interpolated expression. + + .. attribute:: expression + + The string representation of the expression as it appeared in the + template string. + + .. attribute:: conversion + + The conversion specifier (``'s'`` or ``'r'``) if present, otherwise ``None``. + Note that MicroPython does not support the ``'a'`` conversion. + + .. attribute:: format_spec + + The format specification string if present, otherwise an empty string. + +Template String Syntax +---------------------- + +Template strings use the same syntax as f-strings but with a ``t`` prefix:: + + name = "World" + template = t"Hello {name}!" + + # Access template components + print(template.strings) # ('Hello ', '!') + print(template.values) # ('World',) + print(template.interpolations[0].expression) # 'name' + +Conversion Specifiers +~~~~~~~~~~~~~~~~~~~~~ + +Template strings store conversion specifiers as metadata. Unlike f-strings, +the conversion is not applied automatically:: + + value = "test" + t = t"{value!r}" + # t.interpolations[0].value == "test" (not repr(value)) + # t.interpolations[0].conversion == "r" + +Processing code must explicitly apply conversions when needed. + +Format Specifications +~~~~~~~~~~~~~~~~~~~~~ + +Format specifications are stored as metadata in the ``Interpolation`` object. +Unlike f-strings, formatting is not applied automatically:: + + pi = 3.14159 + t = t"{pi:.2f}" + # t.interpolations[0].value == 3.14159 (not formatted) + # t.interpolations[0].format_spec == ".2f" + +Per PEP 750, processing code is not required to use format specifications, but +when present they should be respected and match f-string behavior where possible. + +Debug Format +~~~~~~~~~~~~ + +The debug format ``{expr=}`` is supported:: + + x = 42 + t = t"{x=}" + # t.strings == ("x=", "") + # t.interpolations[0].expression == "x" + # t.interpolations[0].conversion == "r" + +.. admonition:: Important + :class: attention + + As per PEP 750, unlike f-strings, template strings do not automatically + apply conversions or format specifications. This is by design to allow + processing code to control how these are handled. Processing code must + explicitly handle these attributes. + + MicroPython does not provide the ``format()`` built-in function. Use + string formatting methods like ``str.format()`` instead. + +Example Usage +------------- + +Basic processing without format support:: + + def simple_process(template): + """Simple template processing""" + parts = [] + for item in template: + if isinstance(item, str): + parts.append(item) + else: + parts.append(str(item.value)) + return "".join(parts) + +Processing template with format support:: + + from string.templatelib import Template, Interpolation + + def convert(value, conversion): + """Apply conversion specifier to value""" + if conversion == "r": + return repr(value) + elif conversion == "s": + return str(value) + return value + + def process_template(template): + """Process template with conversion and format support""" + result = [] + for part in template: + if isinstance(part, str): + result.append(part) + else: # Interpolation + value = convert(part.value, part.conversion) + if part.format_spec: + # Apply format specification using str.format + value = ("{:" + part.format_spec + "}").format(value) + else: + value = str(value) + result.append(value) + return "".join(result) + + pi = 3.14159 + name = "Alice" + t = t"{name!r}: {pi:.2f}" + print(process_template(t)) + # Output: "'Alice': 3.14" + + # Other format specifications work too + value = 42 + print(process_template(t"{value:>10}")) # " 42" + print(process_template(t"{value:04d}")) # "0042" + +HTML escaping example:: + + def html_escape(value): + """Escape HTML special characters""" + if not isinstance(value, str): + value = str(value) + return value.replace("&", "&").replace("<", "<").replace(">", ">") + + def safe_html(template): + """Convert template to HTML-safe string""" + result = [] + for part in template: + if isinstance(part, str): + result.append(part) + else: + result.append(html_escape(part.value)) + return "".join(result) + + user_input = "" + t = t"User said: {user_input}" + print(safe_html(t)) + # Output: "User said: <script>alert('xss')</script>" + +See Also +-------- + +* `PEP 750 `_ - Template Strings specification +* :ref:`python:formatstrings` - Format string syntax +* `Formatted string literals `_ - f-strings in Python diff --git a/docs/library/sys.rst b/docs/library/sys.rst index 8def36a2b07..c9c687df359 100644 --- a/docs/library/sys.rst +++ b/docs/library/sys.rst @@ -12,17 +12,9 @@ Functions .. function:: exit(retval=0, /) Terminate current program with a given exit code. Underlyingly, this - function raise as `SystemExit` exception. If an argument is given, its + function raises a `SystemExit` exception. If an argument is given, its value given as an argument to `SystemExit`. -.. function:: print_exception(exc, file=sys.stdout, /) - - This function is deprecated and will be removed starting in - CircuitPython 10.x, `traceback.print_exception()` should be used instead. - - Print exception with a traceback to a file-like object *file* (or - `sys.stdout` by default). - .. admonition:: Difference to CPython :class: attention @@ -52,6 +44,8 @@ Constants * *version* - tuple (major, minor, micro), e.g. (1, 7, 0) * *_machine* - string describing the underlying machine * *_mpy* - supported mpy file-format version (optional attribute) + * *_build* - string that can help identify the configuration that + MicroPython was built with This object is the recommended way to distinguish CircuitPython from other Python implementations (note that it still may not exist in the very @@ -116,15 +110,15 @@ Constants .. data:: stderr - Standard error ``stream``. + Standard error `stream`. .. data:: stdin - Standard input ``stream``. + Standard input `stream`. .. data:: stdout - Standard output ``stream``. + Standard output `stream`. .. data:: version diff --git a/docs/library/weakref.rst b/docs/library/weakref.rst new file mode 100644 index 00000000000..ffebc91277b --- /dev/null +++ b/docs/library/weakref.rst @@ -0,0 +1,78 @@ +:mod:`weakref` -- Python object lifetime management +=================================================== + +.. module:: weakref + :synopsis: Create weak references to Python objects + +|see_cpython_module| :mod:`python:weakref`. + +This module allows creation of weak references to Python objects. A weak reference +is a non-traceable reference to a heap-allocated Python object, so the garbage +collector can still reclaim the object even though the weak reference refers to it. + +Python callbacks can be registered to be called when an object is reclaimed by the +garbage collector. This provides a safe way to clean up when objects are no longer +needed. + +**Availability:** the weakref module requires ``MICROPY_PY_WEAKREF`` to be enabled +at compile time. It is enabled on the unix coverage variant and the webassembly +pyscript variant. + +ref objects +----------- + +A ref object is the simplest way to make a weak reference. + +.. class:: ref(object [, callback], /) + + Return a weak reference to the given *object*. + + If *callback* is given and is not ``None`` then, when *object* is reclaimed + by the garbage collector and if the weak reference object is still alive, the + *callback* will be called. The *callback* will be passed the weak reference + object as its single argument. + +.. method:: ref.__call__() + + Calling the weak reference object will return its referenced object if that + object is still alive. Otherwise ``None`` will be returned. + +finalize objects +---------------- + +A finalize object is an extended version of a ref object that is more convenient to +use, and allows more control over the callback. + +.. class:: finalize(object, callback, /, *args, **kwargs) + + Return a weak reference to the given *object*. In contrast to *weakref.ref* + objects, finalize objects are held onto internally and will not be collected until + *object* is collected. + + A finalize object starts off alive. It transitions to the dead state when the + finalize object is called, either explicitly or when *object* is collected. It also + transitions to dead if the `finalize.detach()` method is called. + + When *object* is reclaimed by the garbage collector (or the finalize object is + explicitly called by user code) and the finalize object is still in the alive state, + the *callback* will be called. The *callback* will be passed arguments as: + ``callback(*args, **kwargs)``. + +.. method:: finalize.__call__() + + If the finalize object is alive then it transitions to the dead state and returns + the value of ``callback(*args, **kwargs)``. Otherwise ``None`` will be returned. + +.. method:: finalize.alive + + Read-only boolean attribute that indicates if the finalizer is in the alive state. + +.. method:: finalize.peek() + + If the finalize object is alive then return ``(object, callback, args, kwargs)``. + Otherwise return ``None``. + +.. method:: finalize.detach() + + If the finalize object is alive then it transitions to the dead state and returns + ``(object, callback, args, kwargs)``. Otherwise ``None`` will be returned. diff --git a/docs/llms_txt.py b/docs/llms_txt.py new file mode 100644 index 00000000000..001ff9e24c1 --- /dev/null +++ b/docs/llms_txt.py @@ -0,0 +1,82 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +# +# SPDX-License-Identifier: MIT + +"""Write llms.txt, an index of the docs for LLM agents (https://llmstxt.org/). + +It reuses what the HTML build already parsed: one line per page with its title +and first paragraph, in table-of-contents order. Read the Docs serves each page +as Markdown on request, so the index links the normal HTML pages. +""" + +from docutils import nodes +from sphinx import addnodes + +DESCRIPTION_LENGTH = 160 + + +def page_order(env, docname, seen): + """Yield docnames depth-first in table-of-contents order.""" + if docname in seen: + return + seen.add(docname) + yield docname + for child in env.toctree_includes.get(docname, []): + yield from page_order(env, child, seen) + + +def is_skipped(node): + """Raw HTML, parameter lists and notes; an API description counts.""" + if isinstance(node, (nodes.raw, nodes.field_list, nodes.comment)): + return True + # Sphinx derives API descriptions from Admonition too, so keep those. + return isinstance(node, nodes.Admonition) and not isinstance(node, addnodes.desc) + + +def first_paragraph(doctree): + """Plain text of the first paragraph worth using as a description.""" + for paragraph in doctree.findall(nodes.paragraph): + parent = paragraph.parent + while parent is not None and not is_skipped(parent): + parent = parent.parent + if parent is not None: + continue + text = " ".join(paragraph.astext().split()) + if text: + if len(text) > DESCRIPTION_LENGTH: + text = text[: DESCRIPTION_LENGTH - 3].rstrip() + "..." + return text + return "" + + +def write_llms_txt(app, exception): + if exception is not None or app.builder.name not in ("html", "dirhtml"): + return + env = app.env + excluded = set(app.config.llms_txt_exclude) + lines = ["# " + app.config.project, ""] + if app.config.llms_txt_description: + lines += ["> " + app.config.llms_txt_description, ""] + lines += ["## Pages", ""] + seen = set() + ordered = list(page_order(env, app.config.root_doc, seen)) + ordered += sorted(env.found_docs - seen) + for docname in ordered: + if docname in excluded or docname not in env.titles: + continue + title = env.titles[docname].astext().strip() + description = first_paragraph(env.get_doctree(docname)) + link = app.builder.get_target_uri(docname) + entry = "- [{}]({})".format(title, link) + if description: + entry += ": " + description + lines.append(entry) + with open(app.outdir / "llms.txt", "w", encoding="utf-8") as f: + f.write("\n".join(lines) + "\n") + + +def setup(app): + app.add_config_value("llms_txt_description", "", "html") + app.add_config_value("llms_txt_exclude", [], "html") + app.connect("build-finished", write_llms_txt) + return {"version": "1.0", "parallel_read_safe": True, "parallel_write_safe": True} diff --git a/docs/redirects.txt b/docs/redirects.txt index 1016d0bd70b..b2d4b5621fb 100644 --- a/docs/redirects.txt +++ b/docs/redirects.txt @@ -1,4 +1,5 @@ index.rst README.html +docs/library/micropython.rst shared-bindings/micropython shared-bindings//__init__.rst shared-bindings// shared-bindings/_bleio/Adapter.rst shared-bindings/_bleio/#_bleio.Adapter shared-bindings/_bleio/Address.rst shared-bindings/_bleio/#_bleio.Address diff --git a/docs/reference/glossary.rst b/docs/reference/glossary.rst index 9e9330de4cc..391dc307d23 100644 --- a/docs/reference/glossary.rst +++ b/docs/reference/glossary.rst @@ -186,6 +186,13 @@ Glossary Most MicroPython boards make a REPL available over a UART, and this is typically accessible on a host PC via USB. + small integer + MicroPython optimises the internal representation of integers such that + "small" values do not take up space on the heap, and calculations with + them do not require heap allocation. On most 32-bit ports, this + corresponds to values in the interval ``-2**30 <= x < 2**30``, but this + should be considered an implementation detail and not relied upon. + stream Also known as a "file-like object". A Python object which provides sequential read-write access to the underlying data. A stream object diff --git a/docs/rstjinja.py b/docs/rstjinja.py index e7d8a312f1f..ab940dc7134 100644 --- a/docs/rstjinja.py +++ b/docs/rstjinja.py @@ -5,7 +5,7 @@ def render_with_jinja(docname, source): - if re.search("^\s*.. jinja$", source[0], re.M): + if re.search(r"^\s*.. jinja$", source[0], re.M): return True return False @@ -38,3 +38,7 @@ def rstjinja(app, docname, source): def setup(app): app.connect("source-read", rstjinja) + return { + "parallel_read_safe": True, + "parallel_write_safe": True, + } diff --git a/docs/shared_bindings_matrix.py b/docs/shared_bindings_matrix.py deleted file mode 100644 index 4aedd2382d5..00000000000 --- a/docs/shared_bindings_matrix.py +++ /dev/null @@ -1,488 +0,0 @@ -# The MIT License (MIT) -# -# SPDX-FileCopyrightText: Copyright (c) 2019 Michael Schroeder -# -# 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 json -import os -import pathlib -import re -import subprocess -import tomllib - -from concurrent.futures import ThreadPoolExecutor - -SUPPORTED_PORTS = [ - "analog", - "atmel-samd", - "broadcom", - "cxd56", - "espressif", - "litex", - "mimxrt10xx", - "nordic", - "raspberrypi", - "renode", - "silabs", - "stm", - "zephyr-cp", -] - -ALIASES_BY_BOARD = { - "circuitplayground_express": [ - "circuitplayground_express_4h", - "circuitplayground_express_digikey_pycon2019", - ], - "pybadge": ["edgebadge"], - "pyportal": ["pyportal_pynt"], - "gemma_m0": ["gemma_m0_pycon2018"], -} - -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", -} - -ADDITIONAL_MODULES = { - "_asyncio": "MICROPY_PY_ASYNCIO", - "_eve": "CIRCUITPY__EVE", - "adafruit_bus_device": "CIRCUITPY_BUSDEVICE", - "adafruit_pixelbuf": "CIRCUITPY_PIXELBUF", - "array": "CIRCUITPY_ARRAY", - # always available, so depend on something that's always 1. - "builtins": "CIRCUITPY", - "builtins.pow3": "CIRCUITPY_BUILTINS_POW3", - "busio.SPI": "CIRCUITPY_BUSIO_SPI", - "busio.UART": "CIRCUITPY_BUSIO_UART", - "collections": "CIRCUITPY_COLLECTIONS", - "fontio": "CIRCUITPY_DISPLAYIO", - "io": "CIRCUITPY_IO", - "keypad.KeyMatrix": "CIRCUITPY_KEYPAD_KEYMATRIX", - "keypad.Keys": "CIRCUITPY_KEYPAD_KEYS", - "keypad.ShiftRegisterKeys": "CIRCUITPY_KEYPAD_SHIFTREGISTERKEYS", - "keypad_demux.DemuxKeyMatrix": "CIRCUITPY_KEYPAD_DEMUX", - "os.getenv": "CIRCUITPY_OS_GETENV", - "select": "MICROPY_PY_SELECT_SELECT", - "sys": "CIRCUITPY_SYS", - "terminalio": "CIRCUITPY_DISPLAYIO", - "usb": "CIRCUITPY_PYUSB", - "socketpool.socketpool.AF_INET6": "CIRCUITPY_SOCKETPOOL_IPV6", -} - -MODULES_NOT_IN_BINDINGS = ["binascii", "errno", "json", "re", "ulab"] - -FROZEN_EXCLUDES = ["examples", "docs", "tests", "utils", "conf.py", "setup.py"] -"""Files and dirs at the root of a frozen directory that should be ignored. -This is the same list as in the preprocess_frozen_modules script.""" - -repository_urls = {} -"""Cache of repository URLs for frozen modules.""" - -root_dir = pathlib.Path(__file__).resolve().parent.parent - - -def get_circuitpython_root_dir(): - """The path to the root './circuitpython' directory.""" - return root_dir - - -def get_bindings(): - """Get a list of modules in shared-bindings and ports/*/bindings - based on folder names.""" - shared_bindings_modules = [ - module.name - for module in (get_circuitpython_root_dir() / "shared-bindings").iterdir() - if module.is_dir() - ] - bindings_modules = [] - for d in get_circuitpython_root_dir().glob("ports/*/bindings"): - bindings_modules.extend(module.name for module in d.iterdir() if d.is_dir()) - return ( - shared_bindings_modules - + bindings_modules - + MODULES_NOT_IN_BINDINGS - + list(ADDITIONAL_MODULES.keys()) - ) - - -def get_board_mapping(): - """ - Compiles the list of boards from the directories, with aliases and mapping - to the port. - """ - boards = {} - for port in SUPPORTED_PORTS: - board_path = root_dir / "ports" / port / "boards" - # Zephyr port has vendor specific subdirectories to match zephyr (and - # clean up the boards folder.) - g = "*/*" if port == "zephyr-cp" else "*" - for board_path in board_path.glob(g): - if board_path.is_dir(): - board_id = board_path.name - if port == "zephyr-cp": - vendor = board_path.parent.name - board_id = f"{vendor}_{board_id}" - aliases = ALIASES_BY_BOARD.get(board_path.name, []) - boards[board_id] = { - "port": port, - "download_count": 0, - "aliases": aliases, - "directory": board_path, - } - for alias in aliases: - boards[alias] = { - "port": port, - "download_count": 0, - "alias": True, - "aliases": [], - "directory": board_path, - } - return boards - - -def build_module_map(): - """Establish the base of the JSON file, based on the contents from - `configs`. Base contains the module name and the controlling C macro name. - """ - base = dict() - modules = get_bindings() - for module in modules: - full_name = module - if module in ADDITIONAL_MODULES: - search_identifier = ADDITIONAL_MODULES[module] - else: - search_identifier = "CIRCUITPY_" + module.lstrip("_").upper() - - base[module] = { - "name": full_name, - "key": search_identifier, - } - - return base - - -def get_settings_from_makefile(port_dir, board_name): - """Invoke make to print the value of critical build settings - - This means that the effect of all Makefile directives is taken - into account, without having to re-encode the logic that sets them - in this script, something that has proved error-prone - - This list must explicitly include any setting queried by tools/ci_set_matrix.py. - """ - if os.getenv("NO_BINDINGS_MATRIX"): - return {"CIRCUITPY_BUILD_EXTENSIONS": ".bin"} - - contents = subprocess.run( - [ - "make", - "-C", - port_dir, - "-f", - "Makefile", - f"BOARD={board_name}", - "print-CFLAGS", - "print-CIRCUITPY_BUILD_EXTENSIONS", - "print-FROZEN_MPY_DIRS", - "print-SRC_PATTERNS", - "print-SRC_SUPERVISOR", - ], - encoding="utf-8", - errors="replace", - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - ) - # Make signals errors with exit status 2; 0 and 1 are "non-error" statuses - if contents.returncode not in (0, 1): - error_msg = ( - f"Invoking '{' '.join(contents.args)}' exited with " - f"{contents.returncode}: {contents.stderr}" - ) - raise RuntimeError(error_msg) - - settings = {} - for line in contents.stdout.split("\n"): - if line.startswith("CFLAGS ="): - for m in re.findall(r"-D([A-Z][A-Z0-9_]*)=(\d+)", line): - settings[m[0]] = m[1] - elif m := re.match(r"^([A-Z][A-Z0-9_]*) = (.*)$", line): - settings[m.group(1)] = m.group(2) - - return settings - - -def get_repository_url(directory): - if directory in repository_urls: - return repository_urls[directory] - readme = None - for readme_path in ( - os.path.join(directory, "README.rst"), - os.path.join(os.path.dirname(directory), "README.rst"), - ): - if os.path.exists(readme_path): - readme = readme_path - break - path = None - if readme: - with open(readme, "r") as fp: - for line in fp.readlines(): - if m := re.match( - r"\s+:target:\s+(http\S+(docs.circuitpython|readthedocs)\S+)\s*", - line, - ): - path = m.group(1) - break - if m := re.search(r"<(http[^>]+)>", line): - path = m.group(1) - break - if path is None: - contents = subprocess.run( - ["git", "remote", "get-url", "origin"], - encoding="utf-8", - errors="replace", - stdout=subprocess.PIPE, - stderr=subprocess.PIPE, - cwd=directory, - ) - path = contents.stdout.strip() - repository_urls[directory] = path - return path - - -def remove_prefix(s, prefix): - if not s.startswith(prefix): - raise ValueError(f"{s=} does not start with {prefix=}") - return s.removeprefix(prefix) - - -def frozen_modules_from_dirs(frozen_mpy_dirs, withurl): - """ - Go through the list of frozen directories and extract the python modules. - Paths are of the type: - $(TOP)/frozen/Adafruit_CircuitPython_CircuitPlayground - $(TOP)/frozen/circuitpython-stage/meowbit - Python modules are at the root of the path, and are python files or directories - containing python files. Except the ones in the FROZEN_EXCLUDES list. - """ - frozen_modules = [] - for frozen_path in filter(lambda x: x, frozen_mpy_dirs.split(" ")): - frozen_path = remove_prefix(frozen_path, "../../") - source_dir = get_circuitpython_root_dir() / frozen_path - url_repository = get_repository_url(source_dir) - for sub in source_dir.glob("*"): - if sub.name in FROZEN_EXCLUDES: - continue - if sub.name.endswith(".py"): - if withurl: - frozen_modules.append((sub.name[:-3], url_repository)) - else: - frozen_modules.append(sub.name[:-3]) - continue - if next(sub.glob("**/*.py"), None): # tests if not empty - if withurl: - frozen_modules.append((sub.name, url_repository)) - else: - frozen_modules.append(sub.name) - return frozen_modules - - -def lookup_setting(settings, key, default=""): - while True: - value = settings.get(key, default) - if not value.startswith("$"): - break - key = value[2:-1] - return value - - -def support_matrix_by_board( - use_branded_name=True, - withurl=True, - add_port=False, - add_chips=False, - add_pins=False, - add_branded_name=False, -): - """Compiles a list of the available core modules available for each - board. - """ - base = build_module_map() - - def support_matrix(arg): - board_id, board_info = arg - port = board_info["port"] - board_directory = board_info["directory"] - port_dir = board_directory.parent.parent - if port != "zephyr-cp": - settings = get_settings_from_makefile(str(port_dir), board_directory.name) - autogen_board_info = None - else: - circuitpython_toml_fn = board_directory / "circuitpython.toml" - with circuitpython_toml_fn.open("rb") as f: - settings = tomllib.load(f) - - autogen_board_info_fn = board_directory / "autogen_board_info.toml" - with autogen_board_info_fn.open("rb") as f: - autogen_board_info = tomllib.load(f) - - if use_branded_name or add_branded_name: - if autogen_board_info: - branded_name = autogen_board_info["name"] - else: - with open(board_directory / "mpconfigboard.h") as get_name: - board_contents = get_name.read() - board_name_re = re.search(r"(?<=MICROPY_HW_BOARD_NAME)\s+(.+)", board_contents) - if board_name_re: - branded_name = board_name_re.group(1).strip('"') - if '"' in branded_name: # sometimes the closing " is not at line end - branded_name = branded_name[: branded_name.index('"')] - board_name = branded_name - - if use_branded_name: - board_name = branded_name - else: - board_name = board_id - - if add_chips: - with open(board_directory / "mpconfigboard.h") as get_name: - board_contents = get_name.read() - mcu_re = re.search(r"(?<=MICROPY_HW_MCU_NAME)\s+(.+)", board_contents) - if mcu_re: - mcu = mcu_re.group(1).strip('"') - if '"' in mcu: # in case the closing " is not at line end - mcu = mcu[: mcu.index('"')] - else: - mcu = "" - with open(board_directory / "mpconfigboard.mk") as get_name: - board_contents = get_name.read() - flash_re = re.search(r"(?<=EXTERNAL_FLASH_DEVICES)\s+=\s+(.+)", board_contents) - if flash_re: - # deal with the variability in the way multiple flash chips - # are denoted. We want them to end up as a quoted, - # comma separated string - flash = flash_re.group(1).replace('"', "") - flash = f'"{flash}"' - else: - flash = "" - - if add_pins: - pins = [] - try: - with open(board_directory / "pins.c") as get_name: - pin_lines = get_name.readlines() - except FileNotFoundError: # silabs boards have no pins.c - pass - else: - for p in pin_lines: - pin_re = re.search(r"QSTR_([^\)]+).+pin_([^\)]+)", p) - if pin_re: - board_pin = pin_re.group(1) - chip_pin = pin_re.group(2) - pins.append((board_pin, chip_pin)) - - board_modules = [] - if autogen_board_info: - autogen_modules = autogen_board_info["modules"] - for k in autogen_modules: - if autogen_modules[k]: - board_modules.append(k) - else: - for module in base: - key = base[module]["key"] - if int(lookup_setting(settings, key, "0")): - board_modules.append(base[module]["name"]) - board_modules.sort() - - if "CIRCUITPY_BUILD_EXTENSIONS" in settings: - board_extensions = settings["CIRCUITPY_BUILD_EXTENSIONS"] - if isinstance(board_extensions, str): - board_extensions = [extension.strip() for extension in board_extensions.split(",")] - else: - raise OSError(f"Board extensions undefined: {board_name}.") - - frozen_modules = [] - if "FROZEN_MPY_DIRS" in settings: - frozen_modules = frozen_modules_from_dirs(settings["FROZEN_MPY_DIRS"], withurl) - if frozen_modules: - frozen_modules.sort() - - # generate alias boards too - - board_info = { - "modules": board_modules, - "frozen_libraries": frozen_modules, - "extensions": board_extensions, - } - if add_branded_name: - board_info["branded_name"] = branded_name - if add_port: - board_info["port"] = port - if add_chips: - board_info["mcu"] = mcu - board_info["flash"] = flash - if add_pins: - board_info["pins"] = pins - board_matrix = [(board_name, board_info)] - if board_id in ALIASES_BY_BOARD: - for alias in ALIASES_BY_BOARD[board_id]: - if use_branded_name: - if alias in ALIASES_BRAND_NAMES: - alias = ALIASES_BRAND_NAMES[alias] - else: - alias = alias.replace("_", " ").title() - board_info = { - "modules": board_modules, - "frozen_libraries": frozen_modules, - "extensions": board_extensions, - } - if add_branded_name: - board_info["branded_name"] = branded_name - if add_port: - board_info["port"] = port - if add_chips: - board_info["mcu"] = mcu - board_info["flash"] = flash - if add_pins: - board_info["pins"] = pins - board_matrix.append((alias, board_info)) - - return board_matrix # this is now a list of (board,modules) - - board_mapping = get_board_mapping() - real_boards = [] - for board in board_mapping: - if not board_mapping[board].get("alias", False): - real_boards.append((board, board_mapping[board])) - executor = ThreadPoolExecutor(max_workers=os.cpu_count()) - mapped_exec = executor.map(support_matrix, real_boards) - # flatmap with comprehensions - boards = dict( - sorted([board for matrix in mapped_exec for board in matrix], key=lambda x: x[0]) - ) - - return boards - - -if __name__ == "__main__": - print(json.dumps(support_matrix_by_board(), indent=2)) diff --git a/docs/supported_ports.rst b/docs/supported_ports.rst index ca36999f423..20f713e17e0 100644 --- a/docs/supported_ports.rst +++ b/docs/supported_ports.rst @@ -14,14 +14,11 @@ Additional testing is limited. ../ports/analog/README ../ports/atmel-samd/README - ../ports/broadcom/README ../ports/cxd56/README ../ports/espressif/README - ../ports/litex/README ../ports/mimxrt10xx/README ../ports/nordic/README ../ports/raspberrypi/README - ../ports/renode/README ../ports/silabs/README ../ports/stm/README ../ports/unix/README diff --git a/docs/troubleshooting.rst b/docs/troubleshooting.rst index 7fad2aac181..22cfcde368e 100644 --- a/docs/troubleshooting.rst +++ b/docs/troubleshooting.rst @@ -7,22 +7,22 @@ variety of errors that can happen, what they mean and how to fix them. File system issues ------------------ -If your host computer starts complaining that your ``CIRCUITPY`` drive is corrupted +If your host computer starts complaining that your **CIRCUITPY** drive is corrupted or files cannot be overwritten or deleted, then you will have to erase it completely. -When CircuitPython restarts it will create a fresh empty ``CIRCUITPY`` filesystem. +When CircuitPython restarts it will create a fresh empty **CIRCUITPY** filesystem. -Corruption often happens on Windows when the ``CIRCUITPY`` disk is not safely ejected +Corruption often happens on Windows when the **CIRCUITPY** disk is not safely ejected before being reset by the button or being disconnected from USB. This can also happen on Linux and Mac OSX but it's less likely. -.. caution:: To erase and re-create ``CIRCUITPY`` (for example, to correct a corrupted filesystem), +.. caution:: To erase and re-create **CIRCUITPY** (for example, to correct a corrupted filesystem), follow one of the procedures below. It's important to note that **any files stored on the** - ``CIRCUITPY`` **drive will be erased. Back up your code if possible before continuing!** + **CIRCUITPY** **drive will be erased. Back up your code if possible before continuing!** REPL Erase Method ^^^^^^^^^^^^^^^^^ This is the recommended method of erasing your board. If you are having trouble accessing the -``CIRCUITPY`` drive or the REPL, consider first putting your board into +**CIRCUITPY** drive or the REPL, consider first putting your board into `safe mode `_. **To erase any board if you have access to the REPL:** @@ -30,7 +30,7 @@ This is the recommended method of erasing your board. If you are having trouble #. Connect to the CircuitPython REPL using a terminal program. #. Type ``import storage`` into the REPL. #. Then, type ``storage.erase_filesystem()`` into the REPL. -#. The ``CIRCUITPY`` drive will be erased and the board will restart with an empty ``CIRCUITPY`` drive. +#. The **CIRCUITPY** drive will be erased and the board will restart with an empty **CIRCUITPY** drive. Erase File Method ^^^^^^^^^^^^^^^^^ @@ -56,3 +56,20 @@ all available in the `Adafruit bundle `_ and the `Community bundle `_. Make sure to download a version with 7.0.0 or higher in the filename. + +The error can also come from a ``.mpy`` file that contains native code for a different +kind of chip. On boards that can run native code, ``import foo`` looks for ``foo.py``, +then ``foo..mpy``, then ``foo.mpy``, where ```` is +``microcontroller.cpu.architecture``, for example ``foo.armv7emsp.mpy``. A +``foo..mpy`` built for another architecture or CircuitPython version raises this +error instead of falling back to ``foo.mpy``. + +SyntaxError: invalid micropython decorator +------------------------------------------ + +CircuitPython cannot compile ``@micropython.native`` or ``@micropython.viper`` functions from a +``.py`` file on the board. Add ``optional=True``, for example ``@micropython.viper(optional=True)``, +to run the function as ordinary bytecode instead. ``mpy-cross`` does the same when it is run +without ``-march``. Viper code that uses ``ptr8``, ``uint`` or other viper-only types raises +``NameError`` when it runs as bytecode, so it needs a native ``.mpy`` file on a board that can +load one. diff --git a/docs/workflows.md b/docs/workflows.md index 727cc5401ca..7c4969bb4d0 100644 --- a/docs/workflows.md +++ b/docs/workflows.md @@ -4,11 +4,11 @@ Workflows are the process used to 1) manipulate files on the CircuitPython devic with the serial connection to CircuitPython. The serial connection is usually used to access the REPL. -Starting with CircuitPython 3.x we moved to a USB-only workflow. Prior to that, we used the serial -connection alone to do the whole workflow. In CircuitPython 7.x, a BLE workflow was added with the -advantage of working with mobile devices. CircuitPython 8.x added a web workflow that works over the -local network (usually Wi-Fi) and a web browser. Other clients can also use the Web REST API. Boards -should clearly document which workflows are supported. +CircuitPython started with a USB mass storage device workflow for filesystem operations. +CircuitPython 7.x added a BLE workflow with the advantage of working with mobile devices. +CircuitPython 8.x added a web workflow that works over the +local network (usually Wi-Fi) and a web browser. +Other clients can also use the Web REST API. Boards should clearly document which workflows are supported. Code for workflows lives in `supervisor/shared`. @@ -19,39 +19,81 @@ The workflow APIs are documented here. These USB interfaces are enabled by default on boards with USB support. They are usable once the device has been plugged into a host. -### CIRCUITPY drive +### Mass Storage CircuitPython exposes a standard mass storage (MSC) interface to enable file manipulation over a -standard interface. This interface works underneath the file system at the block level so using it -excludes other types of workflows from manipulating the file system at the same time. +standard interface. The board appears as a USB drive. This interface works underneath the file system at +the block level so using it excludes other types of workflows from manipulating the file system at +the same time. + +CircuitPython 10.x adds multiple Logical Units (LUNs) to the mass storage interface. This allows for +multiple drives to be accessed and ejected independently. + +#### CIRCUITPY drive +The CIRCUITPY drive is the main drive that CircuitPython presents. It is writable by the host by default +and read-only to CircuitPython. `storage.remount()` can be used to remount the drive to +CircuitPython as read-write. + +#### CPSAVES drive +The board may also expose a CPSAVES drive. (This is based on the `CIRCUITPY_SAVES_PARTITION_SIZE` +setting in `mpconfigboard.h`.) It is a portion of the main flash that is writable by CircuitPython +by default. The CPSAVES drive becomes visible to the attached host computer after a few seconds. +By default it is read-only to the host, but `storage.remount()` can be used to remount the drive +as read-write to the host + +#### SD card drive +A few boards auomatically mount an SD card, if present, to the `/sd` mount point. +Boards that do this have `DEFAULT_SD` settings in`mpconfigboard.h` which allow detecting the +presence of an SD card, and fixed pin settings for the SD card socket. +The mounted SD card is writable from CircuitPython by default and read-only to the host. +`storage.remount()` can be used to remount the drive to the host as read-write. + +If `CIRCUITPY_SDCARD_USB` in settings.toml is `true` (the default), +an SD card mounted in user code at `/sd` will become visible on the attached host computer +after a few seconds, as an additional drive besides CIRCUITPY and (if present) CPSAVES. +It will present with the volume label on the SD card. +Depending on the host operating system settings, the drive may or may not be +auto-mounted on the host. +Host writes to drives mounted by user code will not trigger a reload. ### CDC serial -CircuitPython exposes one CDC USB interface for CircuitPython serial. This is a standard serial -USB interface. +CircuitPython exposes a standard serial CDC USB interface for the CircuitPython REPL. +Setting the CDC's baudrate 1200 and disconnecting will reboot the board into a bootloader. +This technique was first used by Arduino boards and the Arduino IDE to trigger a reset into bootloader. -TODO: Document how it designates itself from the user CDC. +A second CDC interface is optionally available for binary data transfer (see `usb_cdc`). -Setting baudrate 1200 and disconnecting will reboot into a bootloader. (Used by Arduino to trigger -a reset into bootloader.) ## BLE -The BLE workflow is enabled for Nordic boards. By default, to prevent malicious access, it is disabled. -To connect to the BLE workflow, press the reset button while the status led blinks blue quickly -after the safe mode blinks. The board will restart and broadcast the file transfer service UUID -(`0xfebb`) along with the board's [Creation IDs](https://github.com/creationid/creators). This -public broadcast is done at a lower transmit level so the devices must be closer. On connection, the -device will need to pair and bond. Once bonded, the device will broadcast whenever disconnected -using a rotating key rather than a static one. Non-bonded devices won't be able to resolve it. After -connection, the central device can discover two default services. One for file transfer and one for -CircuitPython specifically that includes serial characteristics. +The BLE workflow provides file transfer and REPL access over BLE. +It can be controlled by setting `CIRCUITPY_BLE_WORKFLOW` to be `true` or `false`. +in `settings.toml`. The default is `true`. + +To prevent malicious access, even if `CIRCUITPY_BLE_WORKFLOW=true`, +the user must initiate a bonded connection with the host. +To bond, press the reset button when the status led blinks blue quickly after reset, +after the safe mode blinks. +Entering discovery mode erases all bonds stored on the board. +A host that bonded earlier with the board still has the old pairing, and it may fail to connect. +On that host, remove the board from the Bluetooth settings, then pair again. +The board will restart and advertise the file transfer service UUID (`0xfebb`) +along with the board's [Creation ID](https://github.com/creationid/creators). +This public advertisement is done at a lower transmit level so the devices must be closer. +On connection, the device will need to pair and bond. +Once bonded, the device will advertise whenever disconnected, +using a rotating key rather than a static one. +Non-bonded devices won't be able to resolve it. + +After connection, will discover two default services: one is for file transfer and +the other provides version information and a serial connection to the CircuitPython REPL. To change the default BLE advertising name without (or before) running user code, the desired name -can be put in the `settings.toml` file. The key is `CIRCUITPY_BLE_NAME`. It's limited to approximately -30 characters depending on the port's settings and will be truncated if longer. +can be put in the `settings.toml` using the `CIRCUITPY_BLE_NAME` key. The name is limited to approximately +30 characters, depending on the port, and will be truncated if longer. ### File Transfer API -CircuitPython uses [an open File Transfer API](https://github.com/adafruit/Adafruit_CircuitPython_BLE_File_Transfer) +The file transfer service provides [an open File Transfer API](https://github.com/adafruit/Adafruit_CircuitPython_BLE_File_Transfer) to enable file system access. ### CircuitPython Service @@ -61,22 +103,22 @@ replaced by the four specific digits below. The service itself is `0001`. #### TX - `0002` / RX - `0003` -These characteristic work just like the Nordic Uart Service (NUS) but have different UUIDs to prevent -conflicts with user created NUS services. +The TX and RX characteristics for the CircuitPython service work just like the Nordic Uart Service (NUS) +but have different UUIDs to prevent conflicts with user-created NUS services. #### Version - `0100` -Read-only characteristic that returns the UTF-8 encoded version string. +The Version characteristic is read-only and returns the UTF-8 encoded version string. ## Web If the keys `CIRCUITPY_WIFI_SSID` and `CIRCUITPY_WIFI_PASSWORD` are set in `settings.toml`, CircuitPython will automatically connect to the given Wi-Fi network on boot and upon reload. -If `CIRCUITPY_WEB_API_PASSWORD` is set, MDNS and the http server for the web workflow will also start. +If `CIRCUITPY_WEB_API_PASSWORD` is set, MDNS and the HTTP server for the web workflow will also start. -The webserver is on port 80 unless overridden by `CIRCUITPY_WEB_API_PORT`. It also enables MDNS. +The webserver is on port 80 unless overridden by `CIRCUITPY_WEB_API_PORT`. It also enables mDNS. The name of the board as advertised to the network can be overridden by `CIRCUITPY_WEB_INSTANCE_NAME`. -Here is an example `/settings.toml`: +Here is an example `settings.toml`: ```bash # To auto-connect to Wi-Fi @@ -223,7 +265,7 @@ curl -v -u :passw0rd -X PUT -L --location-trusted http://circuitpython.local/fs/ ``` ##### Move -Moves the directory at the given path to ``X-Destination``. Also known as rename. +Moves the directory at the given path to `X-Destination`. Also known as rename. The custom `X-Destination` header stores the destination path of the directory. @@ -247,7 +289,7 @@ Deletes the directory and all of its contents. * `401 Unauthorized` - Incorrect password * `403 Forbidden` - No `CIRCUITPY_WEB_API_PASSWORD` set * `404 Not Found` - No directory -* `409 Conflict` - USB is active and preventing file system modification +* `409 Conflict` - USB is active and preventing file system modification, or a file in it is mapped in the REPL Example: @@ -272,7 +314,7 @@ Returns: * `401 Unauthorized` - Incorrect password * `403 Forbidden` - No `CIRCUITPY_WEB_API_PASSWORD` set * `404 Not Found` - Missing parent directory -* `409 Conflict` - USB is active and preventing file system modification +* `409 Conflict` - USB is active and preventing file system modification, or the file is mapped in the REPL * `413 Payload Too Large` - `Expect` header not sent and file is too large * `417 Expectation Failed` - `Expect` header sent and file is too large * `500 Server Error` - Other, unhandled error @@ -309,7 +351,7 @@ curl -v -u :passw0rd -L --location-trusted http://circuitpython.local/fs/lib/hel ##### Move -Moves the file at the given path to the ``X-Destination``. Also known as rename. +Moves the file at the given path to the `X-Destination`. Also known as rename. The custom `X-Destination` header stores the destination path of the file. @@ -335,7 +377,7 @@ Deletes the file. * `401 Unauthorized` - Incorrect password * `403 Forbidden` - No `CIRCUITPY_WEB_API_PASSWORD` set * `404 Not Found` - File not found -* `409 Conflict` - USB is active and preventing file system modification +* `409 Conflict` - USB is active and preventing file system modification, or the file is mapped in the REPL Example: @@ -422,6 +464,7 @@ Returns information about the device. * `build_date`: CircuitPython build date. * `board_name`: Human readable name of the board. * `mcu_name`: Human readable name of the microcontroller. +* `architecture`: Name of the native `.mpy` architecture this build can load, as used by `mpy-cross -march`. Omitted when the build cannot load native code. * `board_id`: Board id used in code and on circuitpython.org. * `creator_id`: Creator ID for the board. * `creation_id`: Creation ID for the board, set by the creator. diff --git a/examples/natmod/README.md b/examples/natmod/README.md index 0cc4010ef42..ca6b887d034 100644 --- a/examples/natmod/README.md +++ b/examples/natmod/README.md @@ -1,12 +1,12 @@ # Dynamic Native Modules Dynamic Native Modules are .mpy files that contain native machine code from a -language other than Python. For more info see [the documentation] -(https://docs.micropython.org/en/latest/develop/natmod.html). +language other than Python. For more info see [the +documentation](https://docs.micropython.org/en/latest/develop/natmod.html). -This should not be confused with [User C Modules] -(https://docs.micropython.org/en/latest/develop/cmodules.html) which are a -mechanism to add additional out-of-tree modules into the firmware build. +This should not be confused with [User C +Modules](https://docs.micropython.org/en/latest/develop/cmodules.html) which are +a mechanism to add additional out-of-tree modules into the firmware build. ## Examples @@ -65,7 +65,7 @@ your system package manager or installed from PyPI in a virtual environment with `pip`. Each example provides a Makefile. You should specify the `ARCH` argument to -make (one of x86, x64, armv6m, armv7m, xtensa, xtensawin): +make (one of x86, x64, armv6m, armv7m, xtensa, xtensawin, rv32imc): ``` $ cd features0 diff --git a/examples/natmod/btree/Makefile b/examples/natmod/btree/Makefile new file mode 100644 index 00000000000..040fa770396 --- /dev/null +++ b/examples/natmod/btree/Makefile @@ -0,0 +1,62 @@ +# Location of top-level MicroPython directory +MPY_DIR = ../../.. + +# Name of module (different to built-in btree so it can coexist) +MOD_BASE = btree +MOD = $(MOD_BASE)_$(ARCH) + +# Source files (.c or .py) +SRC = btree_c.c + +# Architecture to build for (x86, x64, armv7m, xtensa, xtensawin, rv32imc) +ARCH = x64 + +BTREE_DIR = $(MPY_DIR)/lib/berkeley-db-1.xx +BERKELEY_DB_CONFIG_FILE ?= \"extmod/berkeley-db/berkeley_db_config_port.h\" +CFLAGS += -I$(BTREE_DIR)/include +CFLAGS += -DBERKELEY_DB_CONFIG_FILE=$(BERKELEY_DB_CONFIG_FILE) +CFLAGS += -Wno-old-style-definition -Wno-sign-compare -Wno-unused-parameter +CFLAGS += -Wno-deprecated-non-prototype + +SRC += $(addprefix $(realpath $(BTREE_DIR))/,\ + btree/bt_close.c \ + btree/bt_conv.c \ + btree/bt_delete.c \ + btree/bt_get.c \ + btree/bt_open.c \ + btree/bt_overflow.c \ + btree/bt_page.c \ + btree/bt_put.c \ + btree/bt_search.c \ + btree/bt_seq.c \ + btree/bt_split.c \ + btree/bt_utils.c \ + mpool/mpool.c \ + ) + +ifeq ($(ARCH),xtensa) +MPY_EXTERN_SYM_FILE=$(MPY_DIR)/ports/esp8266/boards/eagle.rom.addr.v6.ld +endif + +# Use our own errno implementation if Picolibc is used +CFLAGS += -D__PICOLIBC_ERRNO_FUNCTION=__errno + +ifeq ($(ARCH),armv6m) +# Link with libgcc.a for division helper functions +LINK_RUNTIME = 1 +endif + +# Strip the architecture name from the internal filename. +MPY_LD_FLAGS = "--source-name=$(MOD_BASE).mpy" + +ifeq ($(ARCH),armv7m) +ifeq ($(findstring clang,$(shell $(CC) --version)),clang) +# Link with libclang_rt.builtins.a for memset/memcpy. +LINK_RUNTIME = 1 +endif +endif + +include $(MPY_DIR)/py/dynruntime.mk + +# btree needs gnu99 defined +CFLAGS += -std=gnu99 diff --git a/examples/natmod/btree/btree_c.c b/examples/natmod/btree/btree_c.c new file mode 100644 index 00000000000..c26dbcc8478 --- /dev/null +++ b/examples/natmod/btree/btree_c.c @@ -0,0 +1,158 @@ +#define MICROPY_PY_BTREE (1) + +#include "py/dynruntime.h" + +#include + +void *malloc(size_t n) { + void *ptr = m_malloc(n); + return ptr; +} +void *realloc(void *ptr, size_t n) { + mp_printf(&mp_plat_print, "UNDEF %d\n", __LINE__); + return NULL; +} +void *calloc(size_t n, size_t m) { + void *ptr = m_malloc(n * m); + // memory already cleared by conservative GC + return ptr; +} + +void free(void *ptr) { + m_free(ptr); +} + +void abort_(void) { + nlr_raise(mp_obj_new_exception(mp_load_global(MP_QSTR_RuntimeError))); +} + +int puts(const char *s) { + return mp_printf(&mp_plat_print, "%s\n", s); +} + +int native_errno; +#if defined(__linux__) +int *__errno_location(void) +#else +int *__errno(void) +#endif +{ + return &native_errno; +} + +ssize_t mp_stream_posix_write(void *stream, const void *buf, size_t len) { + mp_obj_base_t *o = stream; + const mp_stream_p_t *stream_p = MP_OBJ_TYPE_GET_SLOT(o->type, protocol); + mp_uint_t out_sz = stream_p->write(MP_OBJ_FROM_PTR(stream), buf, len, &native_errno); + if (out_sz == MP_STREAM_ERROR) { + return -1; + } else { + return out_sz; + } +} + +ssize_t mp_stream_posix_read(void *stream, void *buf, size_t len) { + mp_obj_base_t *o = stream; + const mp_stream_p_t *stream_p = MP_OBJ_TYPE_GET_SLOT(o->type, protocol); + mp_uint_t out_sz = stream_p->read(MP_OBJ_FROM_PTR(stream), buf, len, &native_errno); + if (out_sz == MP_STREAM_ERROR) { + return -1; + } else { + return out_sz; + } +} + +off_t mp_stream_posix_lseek(void *stream, off_t offset, int whence) { + const mp_obj_base_t *o = stream; + const mp_stream_p_t *stream_p = MP_OBJ_TYPE_GET_SLOT(o->type, protocol); + struct mp_stream_seek_t seek_s; + seek_s.offset = offset; + seek_s.whence = whence; + mp_uint_t res = stream_p->ioctl(MP_OBJ_FROM_PTR(stream), MP_STREAM_SEEK, (mp_uint_t)(uintptr_t)&seek_s, &native_errno); + if (res == MP_STREAM_ERROR) { + return -1; + } + return seek_s.offset; +} + +int mp_stream_posix_fsync(void *stream) { + mp_obj_base_t *o = stream; + const mp_stream_p_t *stream_p = MP_OBJ_TYPE_GET_SLOT(o->type, protocol); + mp_uint_t res = stream_p->ioctl(MP_OBJ_FROM_PTR(stream), MP_STREAM_FLUSH, 0, &native_errno); + if (res == MP_STREAM_ERROR) { + return -1; + } + return res; +} + +mp_obj_full_type_t btree_type; +mp_getiter_iternext_custom_t btree_getiter_iternext; + +#include "extmod/modbtree.c" + +mp_map_elem_t btree_locals_dict_table[8]; +static MP_DEFINE_CONST_DICT(btree_locals_dict, btree_locals_dict_table); + +static mp_obj_t btree_open(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + // The allowed_args array must have its qstr's populated at runtime. + enum { ARG_flags, ARG_cachesize, ARG_pagesize, ARG_minkeypage }; + mp_arg_t allowed_args[] = { + { MP_QSTR_, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, + }; + allowed_args[0].qst = MP_QSTR_flags; + allowed_args[1].qst = MP_QSTR_cachesize; + allowed_args[2].qst = MP_QSTR_pagesize; + allowed_args[3].qst = MP_QSTR_minkeypage; + + // Make sure we got a stream object + mp_get_stream_raise(pos_args[0], MP_STREAM_OP_READ | MP_STREAM_OP_WRITE | MP_STREAM_OP_IOCTL); + + 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); + + BTREEINFO openinfo = {0}; + openinfo.flags = args[ARG_flags].u_int; + openinfo.cachesize = args[ARG_cachesize].u_int; + openinfo.psize = args[ARG_pagesize].u_int; + openinfo.minkeypage = args[ARG_minkeypage].u_int; + DB *db = __bt_open(MP_OBJ_TO_PTR(pos_args[0]), &btree_stream_fvtable, &openinfo, 0); + if (db == NULL) { + mp_raise_OSError(native_errno); + } + + return MP_OBJ_FROM_PTR(btree_new(db, pos_args[0])); +} +static MP_DEFINE_CONST_FUN_OBJ_KW(btree_open_obj, 1, btree_open); + +mp_obj_t mpy_init(mp_obj_fun_bc_t *self, size_t n_args, size_t n_kw, mp_obj_t *args) { + MP_DYNRUNTIME_INIT_ENTRY + + btree_getiter_iternext.getiter = btree_getiter; + btree_getiter_iternext.iternext = btree_iternext; + + btree_type.base.type = (void *)&mp_fun_table.type_type; + btree_type.flags = MP_TYPE_FLAG_ITER_IS_CUSTOM; + btree_type.name = MP_QSTR_btree; + MP_OBJ_TYPE_SET_SLOT(&btree_type, print, btree_print, 0); + MP_OBJ_TYPE_SET_SLOT(&btree_type, iter, &btree_getiter_iternext, 1); + MP_OBJ_TYPE_SET_SLOT(&btree_type, binary_op, btree_binary_op, 2); + MP_OBJ_TYPE_SET_SLOT(&btree_type, subscr, btree_subscr, 3); + btree_locals_dict_table[0] = (mp_map_elem_t) { MP_OBJ_NEW_QSTR(MP_QSTR_close), MP_OBJ_FROM_PTR(&btree_close_obj) }; + btree_locals_dict_table[1] = (mp_map_elem_t) { MP_OBJ_NEW_QSTR(MP_QSTR_flush), MP_OBJ_FROM_PTR(&btree_flush_obj) }; + btree_locals_dict_table[2] = (mp_map_elem_t) { MP_OBJ_NEW_QSTR(MP_QSTR_get), MP_OBJ_FROM_PTR(&btree_get_obj) }; + btree_locals_dict_table[3] = (mp_map_elem_t) { MP_OBJ_NEW_QSTR(MP_QSTR_put), MP_OBJ_FROM_PTR(&btree_put_obj) }; + btree_locals_dict_table[4] = (mp_map_elem_t) { MP_OBJ_NEW_QSTR(MP_QSTR_seq), MP_OBJ_FROM_PTR(&btree_seq_obj) }; + btree_locals_dict_table[5] = (mp_map_elem_t) { MP_OBJ_NEW_QSTR(MP_QSTR_keys), MP_OBJ_FROM_PTR(&btree_keys_obj) }; + btree_locals_dict_table[6] = (mp_map_elem_t) { MP_OBJ_NEW_QSTR(MP_QSTR_values), MP_OBJ_FROM_PTR(&btree_values_obj) }; + btree_locals_dict_table[7] = (mp_map_elem_t) { MP_OBJ_NEW_QSTR(MP_QSTR_items), MP_OBJ_FROM_PTR(&btree_items_obj) }; + MP_OBJ_TYPE_SET_SLOT(&btree_type, locals_dict, (void *)&btree_locals_dict, 4); + + mp_store_global(MP_QSTR_open, MP_OBJ_FROM_PTR(&btree_open_obj)); + mp_store_global(MP_QSTR_INCL, MP_OBJ_NEW_SMALL_INT(FLAG_END_KEY_INCL)); + mp_store_global(MP_QSTR_DESC, MP_OBJ_NEW_SMALL_INT(FLAG_DESC)); + + MP_DYNRUNTIME_INIT_EXIT +} diff --git a/examples/natmod/deflate/Makefile b/examples/natmod/deflate/Makefile index 86ef29b6324..aa0951e88ef 100644 --- a/examples/natmod/deflate/Makefile +++ b/examples/natmod/deflate/Makefile @@ -2,12 +2,34 @@ MPY_DIR = ../../.. # Name of module (different to built-in uzlib so it can coexist) -MOD = deflate_$(ARCH) +MOD_BASE = deflate +MOD = $(MOD_BASE)_$(ARCH) # Source files (.c or .py) SRC = deflate.c -# Architecture to build for (x86, x64, armv7m, xtensa, xtensawin) -ARCH = x64 +# Architecture to build for (x86, x64, armv7m, xtensa, xtensawin, rv32imc, rv64imc) +ARCH ?= x64 + +ifeq ($(ARCH),armv7m) +ifeq ($(findstring clang,$(shell $(CC) --version)),clang) +# Link with libclang_rt.a for memset +LINK_RUNTIME = 1 +endif +endif + +ifeq ($(ARCH),armv6m) +# Link with libgcc.a or libclang_rt.a for division helper functions +LINK_RUNTIME = 1 +endif + +ifeq ($(ARCH),xtensa) +# Link with libm.a and libgcc.a from the toolchain +LINK_RUNTIME = 1 +MPY_EXTERN_SYM_FILE=$(MPY_DIR)/ports/esp8266/boards/eagle.rom.addr.v6.ld +endif + +# Strip the architecture name from the internal filename. +MPY_LD_FLAGS = "--source-name=$(MOD_BASE).mpy" include $(MPY_DIR)/py/dynruntime.mk diff --git a/examples/natmod/deflate/deflate.c b/examples/natmod/deflate/deflate.c index 9de7e101a76..3c470aca9f0 100644 --- a/examples/natmod/deflate/deflate.c +++ b/examples/natmod/deflate/deflate.c @@ -3,15 +3,6 @@ #include "py/dynruntime.h" -#if !defined(__linux__) -void *memcpy(void *dst, const void *src, size_t n) { - return mp_fun_table.memmove_(dst, src, n); -} -void *memset(void *s, int c, size_t n) { - return mp_fun_table.memset_(s, c, n); -} -#endif - mp_obj_full_type_t deflateio_type; #include "extmod/moddeflate.c" @@ -51,14 +42,14 @@ mp_obj_t mpy_init(mp_obj_fun_bc_t *self, size_t n_args, size_t n_kw, mp_obj_t *a deflateio_type.name = MP_QSTR_DeflateIO; MP_OBJ_TYPE_SET_SLOT(&deflateio_type, make_new, &deflateio_make_new, 0); MP_OBJ_TYPE_SET_SLOT(&deflateio_type, protocol, &deflateio_stream_p, 1); - deflateio_locals_dict_table[0] = (mp_map_elem_t){ MP_OBJ_NEW_QSTR(MP_QSTR_read), MP_OBJ_FROM_PTR(&mp_stream_read_obj) }; - deflateio_locals_dict_table[1] = (mp_map_elem_t){ MP_OBJ_NEW_QSTR(MP_QSTR_readinto), MP_OBJ_FROM_PTR(&mp_stream_readinto_obj) }; - deflateio_locals_dict_table[2] = (mp_map_elem_t){ MP_OBJ_NEW_QSTR(MP_QSTR_readline), MP_OBJ_FROM_PTR(&mp_stream_unbuffered_readline_obj) }; - deflateio_locals_dict_table[3] = (mp_map_elem_t){ MP_OBJ_NEW_QSTR(MP_QSTR_write), MP_OBJ_FROM_PTR(&mp_stream_write_obj) }; - deflateio_locals_dict_table[4] = (mp_map_elem_t){ MP_OBJ_NEW_QSTR(MP_QSTR_close), MP_OBJ_FROM_PTR(&mp_stream_close_obj) }; - deflateio_locals_dict_table[5] = (mp_map_elem_t){ MP_OBJ_NEW_QSTR(MP_QSTR___enter__), MP_OBJ_FROM_PTR(&mp_identity_obj) }; - deflateio_locals_dict_table[6] = (mp_map_elem_t){ MP_OBJ_NEW_QSTR(MP_QSTR___exit__), MP_OBJ_FROM_PTR(&mp_stream___exit___obj) }; - MP_OBJ_TYPE_SET_SLOT(&deflateio_type, locals_dict, (void*)&deflateio_locals_dict, 2); + deflateio_locals_dict_table[0] = (mp_map_elem_t) { MP_OBJ_NEW_QSTR(MP_QSTR_read), MP_OBJ_FROM_PTR(&mp_stream_read_obj) }; + deflateio_locals_dict_table[1] = (mp_map_elem_t) { MP_OBJ_NEW_QSTR(MP_QSTR_readinto), MP_OBJ_FROM_PTR(&mp_stream_readinto_obj) }; + deflateio_locals_dict_table[2] = (mp_map_elem_t) { MP_OBJ_NEW_QSTR(MP_QSTR_readline), MP_OBJ_FROM_PTR(&mp_stream_unbuffered_readline_obj) }; + deflateio_locals_dict_table[3] = (mp_map_elem_t) { MP_OBJ_NEW_QSTR(MP_QSTR_write), MP_OBJ_FROM_PTR(&mp_stream_write_obj) }; + deflateio_locals_dict_table[4] = (mp_map_elem_t) { MP_OBJ_NEW_QSTR(MP_QSTR_close), MP_OBJ_FROM_PTR(&mp_stream_close_obj) }; + deflateio_locals_dict_table[5] = (mp_map_elem_t) { MP_OBJ_NEW_QSTR(MP_QSTR___enter__), MP_OBJ_FROM_PTR(&mp_identity_obj) }; + deflateio_locals_dict_table[6] = (mp_map_elem_t) { MP_OBJ_NEW_QSTR(MP_QSTR___exit__), MP_OBJ_FROM_PTR(&mp_stream___exit___obj) }; + MP_OBJ_TYPE_SET_SLOT(&deflateio_type, locals_dict, (void *)&deflateio_locals_dict, 2); mp_store_global(MP_QSTR___name__, MP_OBJ_NEW_QSTR(MP_QSTR_deflate)); mp_store_global(MP_QSTR_DeflateIO, MP_OBJ_FROM_PTR(&deflateio_type)); diff --git a/examples/natmod/features0/Makefile b/examples/natmod/features0/Makefile index 57490df90ab..9bc4bbf23b8 100644 --- a/examples/natmod/features0/Makefile +++ b/examples/natmod/features0/Makefile @@ -7,7 +7,7 @@ MOD = features0 # Source files (.c or .py) SRC = features0.c -# Architecture to build for (x86, x64, armv7m, xtensa, xtensawin) +# Architecture to build for (x86, x64, armv7m, xtensa, xtensawin, rv32imc) ARCH = x64 # Include to get the rules for compiling and linking the module diff --git a/examples/natmod/features1/Makefile b/examples/natmod/features1/Makefile index 010640daf97..49040511020 100644 --- a/examples/natmod/features1/Makefile +++ b/examples/natmod/features1/Makefile @@ -7,7 +7,7 @@ MOD = features1 # Source files (.c or .py) SRC = features1.c -# Architecture to build for (x86, x64, armv7m, xtensa, xtensawin) +# Architecture to build for (x86, x64, armv7m, xtensa, xtensawin, rv32imc) ARCH = x64 # Include to get the rules for compiling and linking the module diff --git a/examples/natmod/features2/Makefile b/examples/natmod/features2/Makefile index 4fd23c6879d..2129974048f 100644 --- a/examples/natmod/features2/Makefile +++ b/examples/natmod/features2/Makefile @@ -10,5 +10,15 @@ SRC = main.c prod.c test.py # Architecture to build for (x86, x64, armv7m, xtensa, xtensawin) ARCH = x64 +ifeq ($(findstring clang,$(shell $(CC) --version)),clang) +ifeq ($(ARCH),$(filter $(ARCH),armv6m armv7m rv32imc)) +# Link with both libc.a and libclang_rt.builtins.a +LINK_CLANG_LIBC = 1 +endif +endif + +# Link with libm.a and libgcc.a from the toolchain +LINK_RUNTIME = 1 + # Include to get the rules for compiling and linking the module include $(MPY_DIR)/py/dynruntime.mk diff --git a/examples/natmod/features2/main.c b/examples/natmod/features2/main.c index 22961aa494f..5ce8e7b0130 100644 --- a/examples/natmod/features2/main.c +++ b/examples/natmod/features2/main.c @@ -1,5 +1,6 @@ /* This example demonstrates the following features in a native module: - using floats + - calling math functions from libm.a - defining additional code in Python (see test.py) - have extra C code in a separate file (see prod.c) */ @@ -10,6 +11,9 @@ // Include the header for auxiliary C code for this module #include "prod.h" +// Include standard library header +#include + // Automatically detect if this module should include double-precision code. // If double precision is supported by the target architecture then it can // be used in native module regardless of what float setting the target @@ -41,6 +45,12 @@ static mp_obj_t add_d(mp_obj_t x, mp_obj_t y) { static MP_DEFINE_CONST_FUN_OBJ_2(add_d_obj, add_d); #endif +// A function that uses libm +static mp_obj_t call_round(mp_obj_t x) { + return mp_obj_new_float_from_f(roundf(mp_obj_get_float_to_f(x))); +} +static MP_DEFINE_CONST_FUN_OBJ_1(round_obj, call_round); + // A function that computes the product of floats in an array. // This function uses the most general C argument interface, which is more difficult // to use but has access to the globals dict of the module via self->globals. @@ -74,6 +84,7 @@ mp_obj_t mpy_init(mp_obj_fun_bc_t *self, size_t n_args, size_t n_kw, mp_obj_t *a #if USE_DOUBLE mp_store_global(MP_QSTR_add_d, MP_OBJ_FROM_PTR(&add_d_obj)); #endif + mp_store_global(MP_QSTR_round, MP_OBJ_FROM_PTR(&round_obj)); // The productf function uses the most general C argument interface mp_store_global(MP_QSTR_productf, MP_DYNRUNTIME_MAKE_FUNCTION(productf)); diff --git a/examples/natmod/features3/Makefile b/examples/natmod/features3/Makefile index 4a5f71b8f25..3573f41caca 100644 --- a/examples/natmod/features3/Makefile +++ b/examples/natmod/features3/Makefile @@ -7,7 +7,7 @@ MOD = features3 # Source files (.c or .py) SRC = features3.c -# Architecture to build for (x86, x64, armv7m, xtensa, xtensawin) +# Architecture to build for (x86, x64, armv7m, xtensa, xtensawin, rv32imc) ARCH = x64 # Include to get the rules for compiling and linking the module diff --git a/examples/natmod/features4/Makefile b/examples/natmod/features4/Makefile index f76a31a7cc1..34fc3a7ef7b 100644 --- a/examples/natmod/features4/Makefile +++ b/examples/natmod/features4/Makefile @@ -7,7 +7,7 @@ MOD = features4 # Source files (.c or .py) SRC = features4.c -# Architecture to build for (x86, x64, armv7m, xtensa, xtensawin) +# Architecture to build for (x86, x64, armv7m, xtensa, xtensawin, rv32imc) ARCH = x64 # Include to get the rules for compiling and linking the module diff --git a/examples/natmod/features4/features4.c b/examples/natmod/features4/features4.c index e64c7f75921..c4d82a1f700 100644 --- a/examples/natmod/features4/features4.c +++ b/examples/natmod/features4/features4.c @@ -68,12 +68,12 @@ mp_obj_t mpy_init(mp_obj_fun_bc_t *self, size_t n_args, size_t n_kw, mp_obj_t *a MP_DYNRUNTIME_INIT_ENTRY // Initialise the type. - mp_type_factorial.base.type = (void*)&mp_type_type; + mp_type_factorial.base.type = (void *)&mp_type_type; mp_type_factorial.flags = MP_TYPE_FLAG_NONE; mp_type_factorial.name = MP_QSTR_Factorial; MP_OBJ_TYPE_SET_SLOT(&mp_type_factorial, make_new, factorial_make_new, 0); - factorial_locals_dict_table[0] = (mp_map_elem_t){ MP_OBJ_NEW_QSTR(MP_QSTR_calculate), MP_OBJ_FROM_PTR(&factorial_calculate_obj) }; - MP_OBJ_TYPE_SET_SLOT(&mp_type_factorial, locals_dict, (void*)&factorial_locals_dict, 1); + factorial_locals_dict_table[0] = (mp_map_elem_t) { MP_OBJ_NEW_QSTR(MP_QSTR_calculate), MP_OBJ_FROM_PTR(&factorial_calculate_obj) }; + MP_OBJ_TYPE_SET_SLOT(&mp_type_factorial, locals_dict, (void *)&factorial_locals_dict, 1); // Make the Factorial type available on the module. mp_store_global(MP_QSTR_Factorial, MP_OBJ_FROM_PTR(&mp_type_factorial)); diff --git a/examples/natmod/framebuf/Makefile b/examples/natmod/framebuf/Makefile new file mode 100644 index 00000000000..86a201d23bd --- /dev/null +++ b/examples/natmod/framebuf/Makefile @@ -0,0 +1,33 @@ +# Location of top-level MicroPython directory +MPY_DIR = ../../.. + +# Name of module (different to built-in framebuf so it can coexist) +MOD_BASE = framebuf +MOD = $(MOD_BASE)_$(ARCH) + +# Source files (.c or .py) +SRC = framebuf.c + +# Architecture to build for (x86, x64, armv7m, xtensa, xtensawin, rv32imc, rv64imc) +ARCH ?= x64 + +ifeq ($(ARCH),armv7m) +ifeq ($(findstring clang,$(shell $(CC) --version)),clang) +# Link with libclang_rt.a for memset +LINK_RUNTIME = 1 +endif +endif + +ifeq ($(ARCH),armv6m) +# Link with libgcc.a for division helper functions +LINK_RUNTIME = 1 +endif + +ifeq ($(ARCH),xtensa) +MPY_EXTERN_SYM_FILE=$(MPY_DIR)/ports/esp8266/boards/eagle.rom.addr.v6.ld +endif + +# Strip the architecture name from the internal filename. +MPY_LD_FLAGS = "--source-name=$(MOD_BASE).mpy" + +include $(MPY_DIR)/py/dynruntime.mk diff --git a/examples/natmod/framebuf/framebuf.c b/examples/natmod/framebuf/framebuf.c new file mode 100644 index 00000000000..6e672439fe9 --- /dev/null +++ b/examples/natmod/framebuf/framebuf.c @@ -0,0 +1,45 @@ +#define MICROPY_PY_ARRAY (1) +#define MICROPY_PY_FRAMEBUF (1) + +#include "py/dynruntime.h" + +mp_obj_full_type_t mp_type_framebuf; + +#include "extmod/modframebuf.c" + +mp_map_elem_t framebuf_locals_dict_table[12]; +static MP_DEFINE_CONST_DICT(framebuf_locals_dict, framebuf_locals_dict_table); + +mp_obj_t mpy_init(mp_obj_fun_bc_t *self, size_t n_args, size_t n_kw, mp_obj_t *args) { + MP_DYNRUNTIME_INIT_ENTRY + + mp_type_framebuf.base.type = (void *)&mp_type_type; + mp_type_framebuf.name = MP_QSTR_FrameBuffer; + MP_OBJ_TYPE_SET_SLOT(&mp_type_framebuf, make_new, framebuf_make_new, 0); + MP_OBJ_TYPE_SET_SLOT(&mp_type_framebuf, buffer, framebuf_get_buffer, 1); + framebuf_locals_dict_table[0] = (mp_map_elem_t) { MP_OBJ_NEW_QSTR(MP_QSTR_fill), MP_OBJ_FROM_PTR(&framebuf_fill_obj) }; + framebuf_locals_dict_table[1] = (mp_map_elem_t) { MP_OBJ_NEW_QSTR(MP_QSTR_fill_rect), MP_OBJ_FROM_PTR(&framebuf_fill_rect_obj) }; + framebuf_locals_dict_table[2] = (mp_map_elem_t) { MP_OBJ_NEW_QSTR(MP_QSTR_pixel), MP_OBJ_FROM_PTR(&framebuf_pixel_obj) }; + framebuf_locals_dict_table[3] = (mp_map_elem_t) { MP_OBJ_NEW_QSTR(MP_QSTR_hline), MP_OBJ_FROM_PTR(&framebuf_hline_obj) }; + framebuf_locals_dict_table[4] = (mp_map_elem_t) { MP_OBJ_NEW_QSTR(MP_QSTR_vline), MP_OBJ_FROM_PTR(&framebuf_vline_obj) }; + framebuf_locals_dict_table[5] = (mp_map_elem_t) { MP_OBJ_NEW_QSTR(MP_QSTR_rect), MP_OBJ_FROM_PTR(&framebuf_rect_obj) }; + framebuf_locals_dict_table[6] = (mp_map_elem_t) { MP_OBJ_NEW_QSTR(MP_QSTR_line), MP_OBJ_FROM_PTR(&framebuf_line_obj) }; + framebuf_locals_dict_table[7] = (mp_map_elem_t) { MP_OBJ_NEW_QSTR(MP_QSTR_ellipse), MP_OBJ_FROM_PTR(&framebuf_ellipse_obj) }; + framebuf_locals_dict_table[8] = (mp_map_elem_t) { MP_OBJ_NEW_QSTR(MP_QSTR_poly), MP_OBJ_FROM_PTR(&framebuf_poly_obj) }; + framebuf_locals_dict_table[9] = (mp_map_elem_t) { MP_OBJ_NEW_QSTR(MP_QSTR_blit), MP_OBJ_FROM_PTR(&framebuf_blit_obj) }; + framebuf_locals_dict_table[10] = (mp_map_elem_t) { MP_OBJ_NEW_QSTR(MP_QSTR_scroll), MP_OBJ_FROM_PTR(&framebuf_scroll_obj) }; + framebuf_locals_dict_table[11] = (mp_map_elem_t) { MP_OBJ_NEW_QSTR(MP_QSTR_text), MP_OBJ_FROM_PTR(&framebuf_text_obj) }; + MP_OBJ_TYPE_SET_SLOT(&mp_type_framebuf, locals_dict, (void *)&framebuf_locals_dict, 2); + + mp_store_global(MP_QSTR_FrameBuffer, MP_OBJ_FROM_PTR(&mp_type_framebuf)); + mp_store_global(MP_QSTR_MVLSB, MP_OBJ_NEW_SMALL_INT(FRAMEBUF_MVLSB)); + mp_store_global(MP_QSTR_MONO_VLSB, MP_OBJ_NEW_SMALL_INT(FRAMEBUF_MVLSB)); + mp_store_global(MP_QSTR_RGB565, MP_OBJ_NEW_SMALL_INT(FRAMEBUF_RGB565)); + mp_store_global(MP_QSTR_GS2_HMSB, MP_OBJ_NEW_SMALL_INT(FRAMEBUF_GS2_HMSB)); + mp_store_global(MP_QSTR_GS4_HMSB, MP_OBJ_NEW_SMALL_INT(FRAMEBUF_GS4_HMSB)); + mp_store_global(MP_QSTR_GS8, MP_OBJ_NEW_SMALL_INT(FRAMEBUF_GS8)); + mp_store_global(MP_QSTR_MONO_HLSB, MP_OBJ_NEW_SMALL_INT(FRAMEBUF_MHLSB)); + mp_store_global(MP_QSTR_MONO_HMSB, MP_OBJ_NEW_SMALL_INT(FRAMEBUF_MHMSB)); + + MP_DYNRUNTIME_INIT_EXIT +} diff --git a/examples/natmod/heapq/Makefile b/examples/natmod/heapq/Makefile index af45b472da1..7068b55dfd0 100644 --- a/examples/natmod/heapq/Makefile +++ b/examples/natmod/heapq/Makefile @@ -2,12 +2,16 @@ MPY_DIR = ../../.. # Name of module (different to built-in heapq so it can coexist) -MOD = heapq_$(ARCH) +MOD_BASE = heapq +MOD = $(MOD_BASE)_$(ARCH) # Source files (.c or .py) SRC = heapq.c -# Architecture to build for (x86, x64, armv7m, xtensa, xtensawin) +# Architecture to build for (x86, x64, armv7m, xtensa, xtensawin, rv32imc) ARCH = x64 +# Strip the architecture name from the internal filename. +MPY_LD_FLAGS = "--source-name=$(MOD_BASE).mpy" + include $(MPY_DIR)/py/dynruntime.mk diff --git a/examples/natmod/random/Makefile b/examples/natmod/random/Makefile index 5c50227b15f..ae0970604b3 100644 --- a/examples/natmod/random/Makefile +++ b/examples/natmod/random/Makefile @@ -2,12 +2,16 @@ MPY_DIR = ../../.. # Name of module (different to built-in random so it can coexist) -MOD = random_$(ARCH) +MOD_BASE = random +MOD = $(MOD_BASE)_$(ARCH) # Source files (.c or .py) SRC = random.c -# Architecture to build for (x86, x64, armv7m, xtensa, xtensawin) +# Architecture to build for (x86, x64, armv7m, xtensa, xtensawin, rv32imc) ARCH = x64 +# Strip the architecture name from the internal filename. +MPY_LD_FLAGS = "--source-name=$(MOD_BASE).mpy" + include $(MPY_DIR)/py/dynruntime.mk diff --git a/examples/natmod/random/random.c b/examples/natmod/random/random.c index 92257b8bc68..d73b53e2e7d 100644 --- a/examples/natmod/random/random.c +++ b/examples/natmod/random/random.c @@ -12,7 +12,7 @@ uint8_t yasmarang_dat; mp_obj_t mpy_init(mp_obj_fun_bc_t *self, size_t n_args, size_t n_kw, mp_obj_t *args) { MP_DYNRUNTIME_INIT_ENTRY - yasmarang_pad = 0xeda4baba; + yasmarang_pad = 0xeda4baba; yasmarang_n = 69; yasmarang_d = 233; diff --git a/examples/natmod/re/Makefile b/examples/natmod/re/Makefile index 1ba54011065..2596437546d 100644 --- a/examples/natmod/re/Makefile +++ b/examples/natmod/re/Makefile @@ -2,12 +2,28 @@ MPY_DIR = ../../.. # Name of module (different to built-in re so it can coexist) -MOD = re_$(ARCH) +MOD_BASE = re +MOD = $(MOD_BASE)_$(ARCH) # Source files (.c or .py) SRC = re.c -# Architecture to build for (x86, x64, armv7m, xtensa, xtensawin) +# Architecture to build for (x86, x64, armv7m, xtensa, xtensawin, rv32imc) ARCH = x64 +ifeq ($(ARCH),armv7m) +ifeq ($(findstring clang,$(shell $(CC) --version)),clang) +# Link with libclang_rt.a for memmove +LINK_RUNTIME = 1 +endif +endif + +ifeq ($(ARCH),armv6m) +# Link with libgcc.a for division helper functions +LINK_RUNTIME = 1 +endif + +# Strip the architecture name from the internal filename. +MPY_LD_FLAGS = "--source-name=$(MOD_BASE).mpy" + include $(MPY_DIR)/py/dynruntime.mk diff --git a/examples/natmod/re/re.c b/examples/natmod/re/re.c index 7ae72a578f4..6c5c65842d6 100644 --- a/examples/natmod/re/re.c +++ b/examples/natmod/re/re.c @@ -4,14 +4,27 @@ #define MICROPY_PY_RE_MATCH_SPAN_START_END (1) #define MICROPY_PY_RE_SUB (0) // requires vstr interface +#if defined __has_builtin +#if __has_builtin(__builtin_alloca) +#define alloca __builtin_alloca +#endif +#endif + +#if !defined(alloca) +#if defined(_PICOLIBC__) && !defined(HAVE_BUILTIN_ALLOCA) +#define alloca(n) m_malloc(n) +#else #include +#endif +#endif + #include "py/dynruntime.h" #define STACK_LIMIT (2048) const char *stack_top; -void mp_stack_check(void) { +void mp_cstack_check(void) { // Assumes descending stack on target volatile char dummy; if (stack_top - &dummy >= STACK_LIMIT) { @@ -19,19 +32,6 @@ void mp_stack_check(void) { } } -#if !defined(__linux__) -void *memcpy(void *dst, const void *src, size_t n) { - return mp_fun_table.memmove_(dst, src, n); -} -void *memset(void *s, int c, size_t n) { - return mp_fun_table.memset_(s, c, n); -} -#endif - -void *memmove(void *dest, const void *src, size_t n) { - return mp_fun_table.memmove_(dest, src, n); -} - mp_obj_full_type_t match_type; mp_obj_full_type_t re_type; @@ -52,23 +52,23 @@ mp_obj_t mpy_init(mp_obj_fun_bc_t *self, size_t n_args, size_t n_kw, mp_obj_t *a // Because MP_QSTR_start/end/split are static, xtensa and xtensawin will make a small data section // to copy in this key/value pair if they are specified as a struct, so assign them separately. - match_type.base.type = (void*)&mp_fun_table.type_type; + match_type.base.type = (void *)&mp_fun_table.type_type; match_type.name = MP_QSTR_match; MP_OBJ_TYPE_SET_SLOT(&match_type, print, match_print, 0); - match_locals_dict_table[0] = (mp_map_elem_t){ MP_OBJ_NEW_QSTR(MP_QSTR_group), MP_OBJ_FROM_PTR(&match_group_obj) }; - match_locals_dict_table[1] = (mp_map_elem_t){ MP_OBJ_NEW_QSTR(MP_QSTR_groups), MP_OBJ_FROM_PTR(&match_groups_obj) }; - match_locals_dict_table[2] = (mp_map_elem_t){ MP_OBJ_NEW_QSTR(MP_QSTR_span), MP_OBJ_FROM_PTR(&match_span_obj) }; - match_locals_dict_table[3] = (mp_map_elem_t){ MP_OBJ_NEW_QSTR(MP_QSTR_start), MP_OBJ_FROM_PTR(&match_start_obj) }; - match_locals_dict_table[4] = (mp_map_elem_t){ MP_OBJ_NEW_QSTR(MP_QSTR_end), MP_OBJ_FROM_PTR(&match_end_obj) }; - MP_OBJ_TYPE_SET_SLOT(&match_type, locals_dict, (void*)&match_locals_dict, 1); - - re_type.base.type = (void*)&mp_fun_table.type_type; + match_locals_dict_table[0] = (mp_map_elem_t) { MP_OBJ_NEW_QSTR(MP_QSTR_group), MP_OBJ_FROM_PTR(&match_group_obj) }; + match_locals_dict_table[1] = (mp_map_elem_t) { MP_OBJ_NEW_QSTR(MP_QSTR_groups), MP_OBJ_FROM_PTR(&match_groups_obj) }; + match_locals_dict_table[2] = (mp_map_elem_t) { MP_OBJ_NEW_QSTR(MP_QSTR_span), MP_OBJ_FROM_PTR(&match_span_obj) }; + match_locals_dict_table[3] = (mp_map_elem_t) { MP_OBJ_NEW_QSTR(MP_QSTR_start), MP_OBJ_FROM_PTR(&match_start_obj) }; + match_locals_dict_table[4] = (mp_map_elem_t) { MP_OBJ_NEW_QSTR(MP_QSTR_end), MP_OBJ_FROM_PTR(&match_end_obj) }; + MP_OBJ_TYPE_SET_SLOT(&match_type, locals_dict, (void *)&match_locals_dict, 1); + + re_type.base.type = (void *)&mp_fun_table.type_type; re_type.name = MP_QSTR_re; MP_OBJ_TYPE_SET_SLOT(&re_type, print, re_print, 0); - re_locals_dict_table[0] = (mp_map_elem_t){ MP_OBJ_NEW_QSTR(MP_QSTR_match), MP_OBJ_FROM_PTR(&re_match_obj) }; - re_locals_dict_table[1] = (mp_map_elem_t){ MP_OBJ_NEW_QSTR(MP_QSTR_search), MP_OBJ_FROM_PTR(&re_search_obj) }; - re_locals_dict_table[2] = (mp_map_elem_t){ MP_OBJ_NEW_QSTR(MP_QSTR_split), MP_OBJ_FROM_PTR(&re_split_obj) }; - MP_OBJ_TYPE_SET_SLOT(&re_type, locals_dict, (void*)&re_locals_dict, 1); + re_locals_dict_table[0] = (mp_map_elem_t) { MP_OBJ_NEW_QSTR(MP_QSTR_match), MP_OBJ_FROM_PTR(&re_match_obj) }; + re_locals_dict_table[1] = (mp_map_elem_t) { MP_OBJ_NEW_QSTR(MP_QSTR_search), MP_OBJ_FROM_PTR(&re_search_obj) }; + re_locals_dict_table[2] = (mp_map_elem_t) { MP_OBJ_NEW_QSTR(MP_QSTR_split), MP_OBJ_FROM_PTR(&re_split_obj) }; + MP_OBJ_TYPE_SET_SLOT(&re_type, locals_dict, (void *)&re_locals_dict, 1); mp_store_global(MP_QSTR_compile, MP_OBJ_FROM_PTR(&mod_re_compile_obj)); mp_store_global(MP_QSTR_match, MP_OBJ_FROM_PTR(&re_match_obj)); diff --git a/examples/usercmodule/cexample/examplemodule.c b/examples/usercmodule/cexample/examplemodule.c deleted file mode 100644 index 2988fbd565f..00000000000 --- a/examples/usercmodule/cexample/examplemodule.c +++ /dev/null @@ -1,90 +0,0 @@ -// Include MicroPython API. -#include "py/runtime.h" - -// Used to get the time in the Timer class example. -#include "py/mphal.h" - -// This is the function which will be called from Python as cexample.add_ints(a, b). -static mp_obj_t example_add_ints(mp_obj_t a_obj, mp_obj_t b_obj) { - // Extract the ints from the micropython input objects. - int a = mp_obj_get_int(a_obj); - int b = mp_obj_get_int(b_obj); - - // Calculate the addition and convert to MicroPython object. - return mp_obj_new_int(a + b); -} -// Define a Python reference to the function above. -static MP_DEFINE_CONST_FUN_OBJ_2(example_add_ints_obj, example_add_ints); - -// This structure represents Timer instance objects. -typedef struct _example_Timer_obj_t { - // All objects start with the base. - mp_obj_base_t base; - // Everything below can be thought of as instance attributes, but they - // cannot be accessed by MicroPython code directly. In this example we - // store the time at which the object was created. - mp_uint_t start_time; -} example_Timer_obj_t; - -// This is the Timer.time() method. After creating a Timer object, this -// can be called to get the time elapsed since creating the Timer. -static mp_obj_t example_Timer_time(mp_obj_t self_in) { - // The first argument is self. It is cast to the *example_Timer_obj_t - // type so we can read its attributes. - example_Timer_obj_t *self = MP_OBJ_TO_PTR(self_in); - - // Get the elapsed time and return it as a MicroPython integer. - mp_uint_t elapsed = mp_hal_ticks_ms() - self->start_time; - return mp_obj_new_int_from_uint(elapsed); -} -static MP_DEFINE_CONST_FUN_OBJ_1(example_Timer_time_obj, example_Timer_time); - -// This represents Timer.__new__ and Timer.__init__, which is called when -// the user instantiates a Timer object. -static mp_obj_t example_Timer_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { - // Allocates the new object and sets the type. - example_Timer_obj_t *self = mp_obj_malloc(example_Timer_obj_t, type); - - // Initializes the time for this Timer instance. - self->start_time = mp_hal_ticks_ms(); - - // The make_new function always returns self. - return MP_OBJ_FROM_PTR(self); -} - -// This collects all methods and other static class attributes of the Timer. -// The table structure is similar to the module table, as detailed below. -static const mp_rom_map_elem_t example_Timer_locals_dict_table[] = { - { MP_ROM_QSTR(MP_QSTR_time), MP_ROM_PTR(&example_Timer_time_obj) }, -}; -static MP_DEFINE_CONST_DICT(example_Timer_locals_dict, example_Timer_locals_dict_table); - -// This defines the type(Timer) object. -MP_DEFINE_CONST_OBJ_TYPE( - example_type_Timer, - MP_QSTR_Timer, - MP_TYPE_FLAG_NONE, - make_new, example_Timer_make_new, - locals_dict, &example_Timer_locals_dict - ); - -// Define all attributes of the module. -// Table entries are key/value pairs of the attribute name (a string) -// and the MicroPython object reference. -// All identifiers and strings are written as MP_QSTR_xxx and will be -// optimized to word-sized integers by the build system (interned strings). -static const mp_rom_map_elem_t example_module_globals_table[] = { - { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_cexample) }, - { MP_ROM_QSTR(MP_QSTR_add_ints), MP_ROM_PTR(&example_add_ints_obj) }, - { MP_ROM_QSTR(MP_QSTR_Timer), MP_ROM_PTR(&example_type_Timer) }, -}; -static MP_DEFINE_CONST_DICT(example_module_globals, example_module_globals_table); - -// Define module object. -const mp_obj_module_t example_user_cmodule = { - .base = { &mp_type_module }, - .globals = (mp_obj_dict_t *)&example_module_globals, -}; - -// Register the module to make it available in Python. -MP_REGISTER_MODULE(MP_QSTR_cexample, example_user_cmodule); diff --git a/examples/usercmodule/cexample/micropython.cmake b/examples/usercmodule/cexample/micropython.cmake deleted file mode 100644 index ba076a16b24..00000000000 --- a/examples/usercmodule/cexample/micropython.cmake +++ /dev/null @@ -1,15 +0,0 @@ -# Create an INTERFACE library for our C module. -add_library(usermod_cexample INTERFACE) - -# Add our source files to the lib -target_sources(usermod_cexample INTERFACE - ${CMAKE_CURRENT_LIST_DIR}/examplemodule.c -) - -# Add the current directory as an include directory. -target_include_directories(usermod_cexample INTERFACE - ${CMAKE_CURRENT_LIST_DIR} -) - -# Link our INTERFACE library to the usermod target. -target_link_libraries(usermod INTERFACE usermod_cexample) diff --git a/examples/usercmodule/cexample/micropython.mk b/examples/usercmodule/cexample/micropython.mk deleted file mode 100644 index d6801dac0ba..00000000000 --- a/examples/usercmodule/cexample/micropython.mk +++ /dev/null @@ -1,8 +0,0 @@ -CEXAMPLE_MOD_DIR := $(USERMOD_DIR) - -# Add all C files to SRC_USERMOD. -SRC_USERMOD += $(CEXAMPLE_MOD_DIR)/examplemodule.c - -# We can add our module folder to include paths if needed -# This is not actually needed in this example. -CFLAGS_USERMOD += -I$(CEXAMPLE_MOD_DIR) diff --git a/examples/usercmodule/cppexample/example.cpp b/examples/usercmodule/cppexample/example.cpp deleted file mode 100644 index 2df832baa76..00000000000 --- a/examples/usercmodule/cppexample/example.cpp +++ /dev/null @@ -1,24 +0,0 @@ -extern "C" { -#include -#include - -// Here we implement the function using C++ code, but since it's -// declaration has to be compatible with C everything goes in extern "C" scope. -mp_obj_t cppfunc(mp_obj_t a_obj, mp_obj_t b_obj) { - // The following no-ops are just here to verify the static assertions used in - // the public API all compile with C++. - MP_STATIC_ASSERT_STR_ARRAY_COMPATIBLE; - if (mp_obj_is_type(a_obj, &mp_type_BaseException)) { - } - - // Prove we have (at least) C++11 features. - const auto a = mp_obj_get_int(a_obj); - const auto b = mp_obj_get_int(b_obj); - const auto sum = [&]() { - return mp_obj_new_int(a + b); - } (); - // Prove we're being scanned for QSTRs. - mp_obj_t tup[] = {sum, MP_ROM_QSTR(MP_QSTR_hellocpp)}; - return mp_obj_new_tuple(2, tup); -} -} diff --git a/examples/usercmodule/cppexample/examplemodule.c b/examples/usercmodule/cppexample/examplemodule.c deleted file mode 100644 index 5d4637b8978..00000000000 --- a/examples/usercmodule/cppexample/examplemodule.c +++ /dev/null @@ -1,25 +0,0 @@ -#include - -// Define a Python reference to the function we'll make available. -// See example.cpp for the definition. -static MP_DEFINE_CONST_FUN_OBJ_2(cppfunc_obj, cppfunc); - -// Define all attributes of the module. -// Table entries are key/value pairs of the attribute name (a string) -// and the MicroPython object reference. -// All identifiers and strings are written as MP_QSTR_xxx and will be -// optimized to word-sized integers by the build system (interned strings). -static const mp_rom_map_elem_t cppexample_module_globals_table[] = { - { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_cppexample) }, - { MP_ROM_QSTR(MP_QSTR_cppfunc), MP_ROM_PTR(&cppfunc_obj) }, -}; -static MP_DEFINE_CONST_DICT(cppexample_module_globals, cppexample_module_globals_table); - -// Define module object. -const mp_obj_module_t cppexample_user_cmodule = { - .base = { &mp_type_module }, - .globals = (mp_obj_dict_t *)&cppexample_module_globals, -}; - -// Register the module to make it available in Python. -MP_REGISTER_MODULE(MP_QSTR_cppexample, cppexample_user_cmodule); diff --git a/examples/usercmodule/cppexample/examplemodule.h b/examples/usercmodule/cppexample/examplemodule.h deleted file mode 100644 index d89384a6300..00000000000 --- a/examples/usercmodule/cppexample/examplemodule.h +++ /dev/null @@ -1,5 +0,0 @@ -// Include MicroPython API. -#include "py/runtime.h" - -// Declare the function we'll make available in Python as cppexample.cppfunc(). -extern mp_obj_t cppfunc(mp_obj_t a_obj, mp_obj_t b_obj); diff --git a/examples/usercmodule/cppexample/micropython.cmake b/examples/usercmodule/cppexample/micropython.cmake deleted file mode 100644 index 6da972c94e3..00000000000 --- a/examples/usercmodule/cppexample/micropython.cmake +++ /dev/null @@ -1,16 +0,0 @@ -# Create an INTERFACE library for our CPP module. -add_library(usermod_cppexample INTERFACE) - -# Add our source files to the library. -target_sources(usermod_cppexample INTERFACE - ${CMAKE_CURRENT_LIST_DIR}/example.cpp - ${CMAKE_CURRENT_LIST_DIR}/examplemodule.c -) - -# Add the current directory as an include directory. -target_include_directories(usermod_cppexample INTERFACE - ${CMAKE_CURRENT_LIST_DIR} -) - -# Link our INTERFACE library to the usermod target. -target_link_libraries(usermod INTERFACE usermod_cppexample) diff --git a/examples/usercmodule/cppexample/micropython.mk b/examples/usercmodule/cppexample/micropython.mk deleted file mode 100644 index 0071d4fcc72..00000000000 --- a/examples/usercmodule/cppexample/micropython.mk +++ /dev/null @@ -1,12 +0,0 @@ -CPPEXAMPLE_MOD_DIR := $(USERMOD_DIR) - -# Add our source files to the respective variables. -SRC_USERMOD += $(CPPEXAMPLE_MOD_DIR)/examplemodule.c -SRC_USERMOD_CXX += $(CPPEXAMPLE_MOD_DIR)/example.cpp - -# Add our module directory to the include path. -CFLAGS_USERMOD += -I$(CPPEXAMPLE_MOD_DIR) -CXXFLAGS_USERMOD += -I$(CPPEXAMPLE_MOD_DIR) -std=c++11 - -# We use C++ features so have to link against the standard library. -LDFLAGS_USERMOD += -lstdc++ diff --git a/examples/usercmodule/micropython.cmake b/examples/usercmodule/micropython.cmake deleted file mode 100644 index b9802401fa9..00000000000 --- a/examples/usercmodule/micropython.cmake +++ /dev/null @@ -1,10 +0,0 @@ -# This top-level micropython.cmake is responsible for listing -# the individual modules we want to include. -# Paths are absolute, and ${CMAKE_CURRENT_LIST_DIR} can be -# used to prefix subdirectories. - -# Add the C example. -include(${CMAKE_CURRENT_LIST_DIR}/cexample/micropython.cmake) - -# Add the CPP example. -include(${CMAKE_CURRENT_LIST_DIR}/cppexample/micropython.cmake) diff --git a/examples/usercmodule/subpackage/README.md b/examples/usercmodule/subpackage/README.md deleted file mode 100644 index c7f2ee53a24..00000000000 --- a/examples/usercmodule/subpackage/README.md +++ /dev/null @@ -1 +0,0 @@ -This is an example of a user C module that includes subpackages. diff --git a/examples/usercmodule/subpackage/micropython.cmake b/examples/usercmodule/subpackage/micropython.cmake deleted file mode 100644 index a51e7a80613..00000000000 --- a/examples/usercmodule/subpackage/micropython.cmake +++ /dev/null @@ -1,19 +0,0 @@ -# Create an INTERFACE library for our C module. -add_library(usermod_subpackage_example INTERFACE) - -# Add our source files to the lib -target_sources(usermod_subpackage_example INTERFACE - ${CMAKE_CURRENT_LIST_DIR}/examplemodule.c -) - -# Add the current directory as an include directory. -target_include_directories(usermod_subpackage_example INTERFACE - ${CMAKE_CURRENT_LIST_DIR} -) - -target_compile_definitions(usermod_subpackage_example INTERFACE - MICROPY_MODULE_BUILTIN_SUBPACKAGES=1 -) - -# Link our INTERFACE library to the usermod target. -target_link_libraries(usermod INTERFACE usermod_subpackage_example) diff --git a/examples/usercmodule/subpackage/micropython.mk b/examples/usercmodule/subpackage/micropython.mk deleted file mode 100644 index 99ebf13ec19..00000000000 --- a/examples/usercmodule/subpackage/micropython.mk +++ /dev/null @@ -1,10 +0,0 @@ -SUBPACKAGE_EXAMPLE_MOD_DIR := $(USERMOD_DIR) - -# Add all C files to SRC_USERMOD. -SRC_USERMOD += $(SUBPACKAGE_EXAMPLE_MOD_DIR)/modexamplepackage.c - -# We can add our module folder to include paths if needed -# This is not actually needed in this example. -CFLAGS_USERMOD += -I$(SUBPACKAGE_EXAMPLE_MOD_DIR) -DMICROPY_MODULE_BUILTIN_SUBPACKAGES=1 - -QSTR_DEFS += $(SUBPACKAGE_EXAMPLE_MOD_DIR)/qstrdefsexamplepackage.h diff --git a/examples/usercmodule/subpackage/modexamplepackage.c b/examples/usercmodule/subpackage/modexamplepackage.c deleted file mode 100644 index d68d0528398..00000000000 --- a/examples/usercmodule/subpackage/modexamplepackage.c +++ /dev/null @@ -1,84 +0,0 @@ -// Include MicroPython API. -#include "py/runtime.h" - -// Define example_package.foo.bar.f() -static mp_obj_t example_package_foo_bar_f(void) { - mp_printf(&mp_plat_print, "example_package.foo.bar.f\n"); - return mp_const_none; -} -static MP_DEFINE_CONST_FUN_OBJ_0(example_package_foo_bar_f_obj, example_package_foo_bar_f); - -// Define all attributes of the second-level sub-package (example_package.foo.bar). -static const mp_rom_map_elem_t example_package_foo_bar_globals_table[] = { - { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_example_package_dot_foo_dot_bar) }, - { MP_ROM_QSTR(MP_QSTR_f), MP_ROM_PTR(&example_package_foo_bar_f_obj) }, -}; -static MP_DEFINE_CONST_DICT(example_package_foo_bar_globals, example_package_foo_bar_globals_table); - -// Define example_package.foo.bar module object. -const mp_obj_module_t example_package_foo_bar_user_cmodule = { - .base = { &mp_type_module }, - .globals = (mp_obj_dict_t *)&example_package_foo_bar_globals, -}; - -// Define example_package.foo.f() -static mp_obj_t example_package_foo_f(void) { - mp_printf(&mp_plat_print, "example_package.foo.f\n"); - return mp_const_none; -} -static MP_DEFINE_CONST_FUN_OBJ_0(example_package_foo_f_obj, example_package_foo_f); - -// Define all attributes of the first-level sub-package (example_package.foo). -static const mp_rom_map_elem_t example_package_foo_globals_table[] = { - { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_example_package_dot_foo) }, - { MP_ROM_QSTR(MP_QSTR_bar), MP_ROM_PTR(&example_package_foo_bar_user_cmodule) }, - { MP_ROM_QSTR(MP_QSTR_f), MP_ROM_PTR(&example_package_foo_f_obj) }, -}; -static MP_DEFINE_CONST_DICT(example_package_foo_globals, example_package_foo_globals_table); - -// Define example_package.foo module object. -const mp_obj_module_t example_package_foo_user_cmodule = { - .base = { &mp_type_module }, - .globals = (mp_obj_dict_t *)&example_package_foo_globals, -}; - -// Define example_package.f() -static mp_obj_t example_package_f(void) { - mp_printf(&mp_plat_print, "example_package.f\n"); - return mp_const_none; -} -static MP_DEFINE_CONST_FUN_OBJ_0(example_package_f_obj, example_package_f); - -static mp_obj_t example_package___init__(void) { - if (!MP_STATE_VM(example_package_initialised)) { - // __init__ for builtins is called each time the module is imported, - // so ensure that initialisation only happens once. - MP_STATE_VM(example_package_initialised) = true; - mp_printf(&mp_plat_print, "example_package.__init__\n"); - } - return mp_const_none; -} -static MP_DEFINE_CONST_FUN_OBJ_0(example_package___init___obj, example_package___init__); - -// The "initialised" state is stored on mp_state so that it is cleared on soft -// reset. -MP_REGISTER_ROOT_POINTER(int example_package_initialised); - -// Define all attributes of the top-level package (example_package). -static const mp_rom_map_elem_t example_package_globals_table[] = { - { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_example_package) }, - { MP_ROM_QSTR(MP_QSTR___init__), MP_ROM_PTR(&example_package___init___obj) }, - { MP_ROM_QSTR(MP_QSTR_foo), MP_ROM_PTR(&example_package_foo_user_cmodule) }, - { MP_ROM_QSTR(MP_QSTR_f), MP_ROM_PTR(&example_package_f_obj) }, -}; -static MP_DEFINE_CONST_DICT(example_package_globals, example_package_globals_table); - -// Define module object. -const mp_obj_module_t example_package_user_cmodule = { - .base = { &mp_type_module }, - .globals = (mp_obj_dict_t *)&example_package_globals, -}; - -// Register the module to make it available in Python. -// Note: subpackages should not be registered with MP_REGISTER_MODULE. -MP_REGISTER_MODULE(MP_QSTR_example_package, example_package_user_cmodule); diff --git a/examples/usercmodule/subpackage/qstrdefsexamplepackage.h b/examples/usercmodule/subpackage/qstrdefsexamplepackage.h deleted file mode 100644 index 057ec5279d0..00000000000 --- a/examples/usercmodule/subpackage/qstrdefsexamplepackage.h +++ /dev/null @@ -1,2 +0,0 @@ -Q(example_package.foo) -Q(example_package.foo.bar) diff --git a/extmod/extmod.mk b/extmod/extmod.mk index b81b44af376..5b2772e4e2a 100644 --- a/extmod/extmod.mk +++ b/extmod/extmod.mk @@ -24,7 +24,6 @@ SRC_EXTMOD_C += \ extmod/vfs_posix.c \ extmod/vfs_posix_file.c \ extmod/vfs_reader.c \ - extmod/virtpin.c \ shared/libc/abort_.c \ shared/libc/printf.c \ @@ -129,6 +128,7 @@ SRC_LIB_LIBM_DBL_SQRT_HW_C += lib/libm_dbl/thumb_vfp_sqrt.c # Too many warnings in libm_dbl, disable for now. $(BUILD)/lib/libm_dbl/%.o: CFLAGS += -Wno-double-promotion -Wno-float-conversion +$(BUILD)/lib/libm_dbl/__rem_pio2_large.o: CFLAGS += -Wno-maybe-uninitialized ################################################################################ # VFS FAT FS @@ -162,7 +162,7 @@ endif ifeq ($(MICROPY_VFS_LFS2),1) CFLAGS_EXTMOD += -DMICROPY_VFS_LFS2=1 -CFLAGS_THIRDPARTY += -DLFS2_NO_MALLOC -DLFS2_NO_DEBUG -DLFS2_NO_WARN -DLFS2_NO_ERROR -DLFS2_NO_ASSERT +CFLAGS_THIRDPARTY += -DLFS2_NO_MALLOC -DLFS2_NO_DEBUG -DLFS2_NO_WARN -DLFS2_NO_ERROR -DLFS2_NO_ASSERT -DLFS2_DEFINES=extmod/littlefs-include/lfs2_defines.h SRC_THIRDPARTY_C += $(addprefix $(LITTLEFS_DIR)/,\ lfs2.c \ lfs2_util.c \ @@ -203,6 +203,10 @@ MBEDTLS_CONFIG_FILE ?= \"mbedtls/mbedtls_config_port.h\" GIT_SUBMODULES += $(MBEDTLS_DIR) CFLAGS_EXTMOD += -DMBEDTLS_CONFIG_FILE=$(MBEDTLS_CONFIG_FILE) CFLAGS_EXTMOD += -DMICROPY_SSL_MBEDTLS=1 -I$(TOP)/$(MBEDTLS_DIR)/include +ifeq ($(MICROPY_PY_SSL_ECDSA_SIGN_ALT),1) +CFLAGS_EXTMOD += -DMICROPY_PY_SSL_ECDSA_SIGN_ALT=1 +LDFLAGS_EXTMOD += -Wl,--wrap=mbedtls_ecdsa_write_signature +endif SRC_THIRDPARTY_C += lib/mbedtls_errors/mp_mbedtls_errors.c SRC_THIRDPARTY_C += $(addprefix $(MBEDTLS_DIR)/library/,\ aes.c \ @@ -248,6 +252,7 @@ SRC_THIRDPARTY_C += $(addprefix $(MBEDTLS_DIR)/library/,\ pkcs12.c \ pkcs5.c \ pkparse.c \ + pk_ecc.c \ pk_wrap.c \ pkwrite.c \ platform.c \ @@ -294,6 +299,8 @@ $(BUILD)/$(LWIP_DIR)/core/ipv4/dhcp.o: CFLAGS += -Wno-address SRC_THIRDPARTY_C += shared/netutils/netutils.c SRC_THIRDPARTY_C += $(addprefix $(LWIP_DIR)/,\ apps/mdns/mdns.c \ + apps/mdns/mdns_domain.c \ + apps/mdns/mdns_out.c \ core/def.c \ core/dns.c \ core/inet_chksum.c \ @@ -311,6 +318,7 @@ SRC_THIRDPARTY_C += $(addprefix $(LWIP_DIR)/,\ core/tcp_out.c \ core/timeouts.c \ core/udp.c \ + core/ipv4/acd.c \ core/ipv4/autoip.c \ core/ipv4/dhcp.c \ core/ipv4/etharp.c \ @@ -329,6 +337,32 @@ SRC_THIRDPARTY_C += $(addprefix $(LWIP_DIR)/,\ core/ipv6/mld6.c \ core/ipv6/nd6.c \ netif/ethernet.c \ + netif/ppp/auth.c \ + netif/ppp/ccp.c \ + netif/ppp/chap-md5.c \ + netif/ppp/chap_ms.c \ + netif/ppp/chap-new.c \ + netif/ppp/demand.c \ + netif/ppp/eap.c \ + netif/ppp/ecp.c \ + netif/ppp/eui64.c \ + netif/ppp/fsm.c \ + netif/ppp/ipcp.c \ + netif/ppp/ipv6cp.c \ + netif/ppp/lcp.c \ + netif/ppp/magic.c \ + netif/ppp/mppe.c \ + netif/ppp/multilink.c \ + netif/ppp/polarssl/md5.c \ + netif/ppp/pppapi.c \ + netif/ppp/ppp.c \ + netif/ppp/pppcrypt.c \ + netif/ppp/pppoe.c \ + netif/ppp/pppol2tp.c \ + netif/ppp/pppos.c \ + netif/ppp/upap.c \ + netif/ppp/utils.c \ + netif/ppp/vj.c \ ) ifeq ($(MICROPY_PY_LWIP_LOOPBACK),1) CFLAGS_EXTMOD += -DLWIP_NETIF_LOOPBACK=1 @@ -377,15 +411,14 @@ CYW43_DIR = lib/cyw43-driver GIT_SUBMODULES += $(CYW43_DIR) CFLAGS_EXTMOD += -DMICROPY_PY_NETWORK_CYW43=1 SRC_THIRDPARTY_C += $(addprefix $(CYW43_DIR)/src/,\ + cyw43_bthci_uart.c \ cyw43_ctrl.c \ cyw43_lwip.c \ cyw43_ll.c \ cyw43_sdio.c \ + cyw43_spi.c \ cyw43_stats.c \ ) -ifeq ($(MICROPY_PY_BLUETOOTH),1) -DRIVERS_SRC_C += drivers/cyw43/cywbt.c -endif $(BUILD)/$(CYW43_DIR)/src/cyw43_%.o: CFLAGS += -std=c11 endif # MICROPY_PY_NETWORK_CYW43 @@ -428,7 +461,7 @@ ESP_HOSTED_SRC_C = $(addprefix $(ESP_HOSTED_DIR)/,\ ) ifeq ($(MICROPY_PY_BLUETOOTH),1) -ESP_HOSTED_SRC_C += $(ESP_HOSTED_DIR)/esp_hosted_bthci.c +ESP_HOSTED_SRC_C += $(ESP_HOSTED_DIR)/esp_hosted_bthci_uart.c endif # Include the protobuf-c support functions @@ -489,6 +522,7 @@ ifeq ($(MICROPY_PY_OPENAMP),1) OPENAMP_DIR = lib/open-amp LIBMETAL_DIR = lib/libmetal GIT_SUBMODULES += $(LIBMETAL_DIR) $(OPENAMP_DIR) +MICROPY_PY_OPENAMP_MODE ?= 0 include $(TOP)/extmod/libmetal/libmetal.mk INC += -I$(TOP)/$(OPENAMP_DIR) @@ -498,12 +532,21 @@ ifeq ($(MICROPY_PY_OPENAMP_REMOTEPROC),1) CFLAGS += -DMICROPY_PY_OPENAMP_REMOTEPROC=1 endif +ifeq ($(MICROPY_PY_OPENAMP_MODE),0) +CFLAGS += -DMICROPY_PY_OPENAMP_HOST=1 +CFLAGS_THIRDPARTY += -DVIRTIO_DRIVER_ONLY +else ifeq ($(MICROPY_PY_OPENAMP_MODE),1) +CFLAGS += -DMICROPY_PY_OPENAMP_DEVICE=1 +CFLAGS_THIRDPARTY += -DVIRTIO_DEVICE_ONLY +else +$(error Invalid Open-AMP mode specified: $(MICROPY_PY_OPENAMP_MODE)) +endif + CFLAGS_THIRDPARTY += \ -I$(BUILD)/openamp \ -I$(TOP)/$(OPENAMP_DIR) \ -I$(TOP)/$(OPENAMP_DIR)/lib/include/ \ -DMETAL_INTERNAL \ - -DVIRTIO_DRIVER_ONLY \ -DNO_ATOMIC_64_SUPPORT \ -DRPMSG_BUFFER_SIZE=512 \ @@ -533,6 +576,6 @@ $(BUILD)/$(OPENAMP_DIR)/lib/virtio_mmio/virtio_mmio_drv.o: CFLAGS += -Wno-unused # We need to have generated libmetal before compiling OpenAMP. $(addprefix $(BUILD)/, $(SRC_OPENAMP_C:.c=.o)): $(BUILD)/openamp/metal/config.h -SRC_THIRDPARTY_C += $(SRC_LIBMETAL_C) $(SRC_OPENAMP_C) +SRC_THIRDPARTY_C += $(SRC_OPENAMP_C) $(SRC_LIBMETAL_C:$(BUILD)/%=%) endif # MICROPY_PY_OPENAMP diff --git a/extmod/lwip-include/arch/cc.h b/extmod/lwip-include/arch/cc.h deleted file mode 100644 index 400dc6ec75d..00000000000 --- a/extmod/lwip-include/arch/cc.h +++ /dev/null @@ -1,41 +0,0 @@ -#ifndef MICROPY_INCLUDED_EXTMOD_LWIP_INCLUDE_ARCH_CC_H -#define MICROPY_INCLUDED_EXTMOD_LWIP_INCLUDE_ARCH_CC_H - -#include - -// Generate lwip's internal types from stdint - -typedef uint8_t u8_t; -typedef int8_t s8_t; -typedef uint16_t u16_t; -typedef int16_t s16_t; -typedef uint32_t u32_t; -typedef int32_t s32_t; - -typedef u32_t mem_ptr_t; - -#define U16_F "hu" -#define S16_F "hd" -#define X16_F "hx" -#define U32_F "u" -#define S32_F "d" -#define X32_F "x" - -#define X8_F "02x" -#define SZT_F "u" - -#define BYTE_ORDER LITTLE_ENDIAN - -#define LWIP_CHKSUM_ALGORITHM 2 - -#include -#define LWIP_PLATFORM_DIAG(x) -#define LWIP_PLATFORM_ASSERT(x) { assert(1); } - -//#define PACK_STRUCT_FIELD(x) x __attribute__((packed)) -#define PACK_STRUCT_FIELD(x) x -#define PACK_STRUCT_STRUCT __attribute__((packed)) -#define PACK_STRUCT_BEGIN -#define PACK_STRUCT_END - -#endif // MICROPY_INCLUDED_EXTMOD_LWIP_INCLUDE_ARCH_CC_H diff --git a/extmod/lwip-include/arch/perf.h b/extmod/lwip-include/arch/perf.h deleted file mode 100644 index d310fc339f1..00000000000 --- a/extmod/lwip-include/arch/perf.h +++ /dev/null @@ -1,7 +0,0 @@ -#ifndef MICROPY_INCLUDED_EXTMOD_LWIP_INCLUDE_ARCH_PERF_H -#define MICROPY_INCLUDED_EXTMOD_LWIP_INCLUDE_ARCH_PERF_H - -#define PERF_START /* null definition */ -#define PERF_STOP(x) /* null definition */ - -#endif // MICROPY_INCLUDED_EXTMOD_LWIP_INCLUDE_ARCH_PERF_H diff --git a/extmod/lwip-include/lwipopts.h b/extmod/lwip-include/lwipopts.h deleted file mode 100644 index 584decfe85f..00000000000 --- a/extmod/lwip-include/lwipopts.h +++ /dev/null @@ -1,36 +0,0 @@ -#ifndef MICROPY_INCLUDED_EXTMOD_LWIP_INCLUDE_LWIPOPTS_H -#define MICROPY_INCLUDED_EXTMOD_LWIP_INCLUDE_LWIPOPTS_H - -#include -#include -#include - -// We're running without an OS for this port. We don't provide any services except light protection. -#define NO_SYS 1 - -#define SYS_LIGHTWEIGHT_PROT 1 -#include -typedef uint32_t sys_prot_t; - -#define TCP_LISTEN_BACKLOG 1 - -// We'll put these into a proper ifdef once somebody implements an ethernet driver -#define LWIP_ARP 0 -#define LWIP_ETHERNET 0 - -#define LWIP_DNS 1 - -#define LWIP_NETCONN 0 -#define LWIP_SOCKET 0 - -// CIRCUITPY-CHANGE: #if instead of #ifdef -#if MICROPY_PY_LWIP_SLIP -#define LWIP_HAVE_SLIPIF 1 -#endif - -// For now, we can simply define this as a macro for the timer code. But this function isn't -// universal and other ports will need to do something else. It may be necessary to move -// things like this into a port-provided header file. -#define sys_now mp_hal_ticks_ms - -#endif // MICROPY_INCLUDED_EXTMOD_LWIP_INCLUDE_LWIPOPTS_H diff --git a/extmod/modasyncio.c b/extmod/modasyncio.c index 4672f6940c1..28ca14290b2 100644 --- a/extmod/modasyncio.c +++ b/extmod/modasyncio.c @@ -31,8 +31,8 @@ #if MICROPY_PY_ASYNCIO -// CIRCUITPY-CHANGE -#if CIRCUITPY && !(defined(__unix__) || defined(__APPLE__)) +// CIRCUITPY-CHANGE: the unix port has no supervisor. +#if CIRCUITPY && CIRCUITPY_SUPERVISOR #include "shared-bindings/supervisor/__init__.h" #endif @@ -58,6 +58,9 @@ typedef struct _mp_obj_task_t { typedef struct _mp_obj_task_queue_t { mp_obj_base_t base; mp_obj_task_t *heap; + #if MICROPY_PY_ASYNCIO_TASK_QUEUE_PUSH_CALLBACK + mp_obj_t push_callback; + #endif } mp_obj_task_queue_t; static const mp_obj_type_t task_queue_type; @@ -73,7 +76,7 @@ static mp_obj_t task_queue_make_new(const mp_obj_type_t *type, size_t n_args, si #define _TICKS_MAX (_TICKS_PERIOD - 1) #define _TICKS_HALFPERIOD (_TICKS_PERIOD >> 1) -#if !CIRCUITPY || (defined(__unix__) || defined(__APPLE__)) +#if !CIRCUITPY || !CIRCUITPY_SUPERVISOR static mp_obj_t ticks(void) { return MP_OBJ_NEW_SMALL_INT(mp_hal_ticks_ms() & _TICKS_MAX); } @@ -105,9 +108,16 @@ static int task_lt(mp_pairheap_t *n1, mp_pairheap_t *n2) { static mp_obj_t task_queue_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { (void)args; - mp_arg_check_num(n_args, n_kw, 0, 0, false); + mp_arg_check_num(n_args, n_kw, 0, MICROPY_PY_ASYNCIO_TASK_QUEUE_PUSH_CALLBACK ? 1 : 0, false); mp_obj_task_queue_t *self = mp_obj_malloc(mp_obj_task_queue_t, type); self->heap = (mp_obj_task_t *)mp_pairheap_new(task_lt); + #if MICROPY_PY_ASYNCIO_TASK_QUEUE_PUSH_CALLBACK + if (n_args == 1) { + self->push_callback = args[0]; + } else { + self->push_callback = MP_OBJ_NULL; + } + #endif return MP_OBJ_FROM_PTR(self); } @@ -132,6 +142,11 @@ static mp_obj_t task_queue_push(size_t n_args, const mp_obj_t *args) { task->ph_key = args[2]; } self->heap = (mp_obj_task_t *)mp_pairheap_push(task_lt, TASK_PAIRHEAP(self->heap), TASK_PAIRHEAP(task)); + #if MICROPY_PY_ASYNCIO_TASK_QUEUE_PUSH_CALLBACK + if (self->push_callback != MP_OBJ_NULL) { + mp_call_function_1(self->push_callback, MP_OBJ_NEW_SMALL_INT(0)); + } + #endif return mp_const_none; } static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(task_queue_push_obj, 2, 3, task_queue_push); @@ -160,11 +175,6 @@ static const mp_rom_map_elem_t task_queue_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_push), MP_ROM_PTR(&task_queue_push_obj) }, { MP_ROM_QSTR(MP_QSTR_pop), MP_ROM_PTR(&task_queue_pop_obj) }, { MP_ROM_QSTR(MP_QSTR_remove), MP_ROM_PTR(&task_queue_remove_obj) }, - - // CIRCUITPY-CHANGE: Remove these in CircuitPython 10.0.0 - { MP_ROM_QSTR(MP_QSTR_push_head), MP_ROM_PTR(&task_queue_push_obj) }, - { MP_ROM_QSTR(MP_QSTR_push_sorted), MP_ROM_PTR(&task_queue_push_obj) }, - { MP_ROM_QSTR(MP_QSTR_pop_head), MP_ROM_PTR(&task_queue_pop_obj) }, }; static MP_DEFINE_CONST_DICT(task_queue_locals_dict, task_queue_locals_dict_table); diff --git a/extmod/moddeflate.c b/extmod/moddeflate.c index c0c3bb26a8b..920b898b2cc 100644 --- a/extmod/moddeflate.c +++ b/extmod/moddeflate.c @@ -142,7 +142,7 @@ static bool deflateio_init_read(mp_obj_deflateio_t *self) { } } - size_t window_len = 1 << wbits; + size_t window_len = (size_t)1 << wbits; self->read->window = m_new(uint8_t, window_len); uzlib_uncompress_init(&self->read->decomp, self->read->window, window_len); @@ -168,16 +168,20 @@ static bool deflateio_init_write(mp_obj_deflateio_t *self) { const mp_stream_p_t *stream = mp_get_stream_raise(self->stream, MP_STREAM_OP_WRITE); - self->write = m_new_obj(mp_obj_deflateio_write_t); - self->write->input_len = 0; - int wbits = self->window_bits; if (wbits == 0) { // Same default wbits for all formats. wbits = DEFLATEIO_DEFAULT_WBITS; } + + // Allocate the large window before allocating the mp_obj_deflateio_write_t, in case the + // window allocation fails the mp_obj_deflateio_t object will remain in a consistent state. size_t window_len = 1 << wbits; - self->write->window = m_new(uint8_t, window_len); + uint8_t *window = m_new(uint8_t, window_len); + + self->write = m_new_obj(mp_obj_deflateio_write_t); + self->write->window = window; + self->write->input_len = 0; uzlib_lz77_init(&self->write->lz77, self->write->window, window_len); self->write->lz77.dest_write_data = self; diff --git a/extmod/modjson.c b/extmod/modjson.c index 67da36f0ccf..77f4a336aa8 100644 --- a/extmod/modjson.c +++ b/extmod/modjson.c @@ -227,7 +227,8 @@ static mp_obj_t _mod_json_load(mp_obj_t stream_obj, bool return_first_json) { for (;;) { cont: if (S_END(s)) { - break; + // Input finished abruptly in the middle of a composite entity. + goto fail; } mp_obj_t next = MP_OBJ_NULL; bool enter = false; diff --git a/extmod/modos.c b/extmod/modos.c index 7f1e31fba77..c330162e102 100644 --- a/extmod/modos.c +++ b/extmod/modos.c @@ -145,6 +145,21 @@ static mp_obj_t mp_os_dupterm_notify(mp_obj_t obj_in) { static MP_DEFINE_CONST_FUN_OBJ_1(mp_os_dupterm_notify_obj, mp_os_dupterm_notify); #endif +#if MICROPY_PY_OS_URANDOM +// This wraps the port-specific mp_hal_get_random(), which is usually defined in mphalport.c. +static mp_obj_t mp_os_urandom(mp_obj_t num) { + mp_int_t n = mp_obj_get_int(num); + if (n < 0) { + mp_raise_ValueError(NULL); + } + vstr_t vstr; + vstr_init_len(&vstr, n); + mp_hal_get_random(n, (uint8_t *)vstr.buf); + return mp_obj_new_bytes_from_vstr(&vstr); +} +static MP_DEFINE_CONST_FUN_OBJ_1(mp_os_urandom_obj, mp_os_urandom); +#endif + static const mp_rom_map_elem_t os_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_os) }, @@ -153,9 +168,6 @@ static const mp_rom_map_elem_t os_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_putenv), MP_ROM_PTR(&mp_os_putenv_obj) }, { MP_ROM_QSTR(MP_QSTR_unsetenv), MP_ROM_PTR(&mp_os_unsetenv_obj) }, #endif - #if MICROPY_PY_OS_SEP - { MP_ROM_QSTR(MP_QSTR_sep), MP_ROM_QSTR(MP_QSTR__slash_) }, - #endif #if MICROPY_PY_OS_SYNC { MP_ROM_QSTR(MP_QSTR_sync), MP_ROM_PTR(&mp_os_sync_obj) }, #endif @@ -170,16 +182,19 @@ static const mp_rom_map_elem_t os_module_globals_table[] = { #endif #if MICROPY_VFS + { MP_ROM_QSTR(MP_QSTR_sep), MP_ROM_QSTR(MP_QSTR__slash_) }, { MP_ROM_QSTR(MP_QSTR_chdir), MP_ROM_PTR(&mp_vfs_chdir_obj) }, { MP_ROM_QSTR(MP_QSTR_getcwd), MP_ROM_PTR(&mp_vfs_getcwd_obj) }, { MP_ROM_QSTR(MP_QSTR_listdir), MP_ROM_PTR(&mp_vfs_listdir_obj) }, + #if MICROPY_VFS_WRITABLE { MP_ROM_QSTR(MP_QSTR_mkdir), MP_ROM_PTR(&mp_vfs_mkdir_obj) }, { MP_ROM_QSTR(MP_QSTR_remove), MP_ROM_PTR(&mp_vfs_remove_obj) }, { MP_ROM_QSTR(MP_QSTR_rename), MP_ROM_PTR(&mp_vfs_rename_obj) }, { MP_ROM_QSTR(MP_QSTR_rmdir), MP_ROM_PTR(&mp_vfs_rmdir_obj) }, + { MP_ROM_QSTR(MP_QSTR_unlink), MP_ROM_PTR(&mp_vfs_remove_obj) }, // unlink aliases to remove + #endif { MP_ROM_QSTR(MP_QSTR_stat), MP_ROM_PTR(&mp_vfs_stat_obj) }, { MP_ROM_QSTR(MP_QSTR_statvfs), MP_ROM_PTR(&mp_vfs_statvfs_obj) }, - { MP_ROM_QSTR(MP_QSTR_unlink), MP_ROM_PTR(&mp_vfs_remove_obj) }, // unlink aliases to remove #endif // The following are MicroPython extensions. diff --git a/extmod/modplatform.c b/extmod/modplatform.c index c6d4d31b97e..e1f5476c3b3 100644 --- a/extmod/modplatform.c +++ b/extmod/modplatform.c @@ -61,11 +61,49 @@ static mp_obj_t platform_libc_ver(size_t n_args, const mp_obj_t *pos_args, mp_ma } static MP_DEFINE_CONST_FUN_OBJ_KW(platform_libc_ver_obj, 0, platform_libc_ver); +#ifdef __riscv +static mp_obj_t platform_processor(void) { + #if (__riscv_xlen <= 64) && !defined(__linux__) + uintptr_t misa_csr = 0; + + // Load the MISA CSR directly. + __asm volatile ( + "csrr %0, misa \n" + : "+r" (misa_csr) + : + : + ); + + char processor_buffer[31] = { // "RV32"/"RV64" + up to 26 chars. + #if (__riscv_xlen < 64) + "RV32" + #else + "RV64" + #endif + }; + mp_uint_t offset = 4; + for (mp_uint_t bit = 0; bit < 26; bit++) { + if (misa_csr & (1U << bit)) { + processor_buffer[offset++] = 'A' + bit; + } + } + + return mp_obj_new_str(processor_buffer, offset); + #else + return MP_OBJ_NEW_QSTR(MP_QSTR_); + #endif +} +static MP_DEFINE_CONST_FUN_OBJ_0(platform_processor_obj, platform_processor); +#endif + static const mp_rom_map_elem_t modplatform_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_platform) }, { MP_ROM_QSTR(MP_QSTR_platform), MP_ROM_PTR(&platform_platform_obj) }, { MP_ROM_QSTR(MP_QSTR_python_compiler), MP_ROM_PTR(&platform_python_compiler_obj) }, { MP_ROM_QSTR(MP_QSTR_libc_ver), MP_ROM_PTR(&platform_libc_ver_obj) }, + #ifdef __riscv + { MP_ROM_QSTR(MP_QSTR_processor), MP_ROM_PTR(&platform_processor_obj) }, + #endif }; static MP_DEFINE_CONST_DICT(modplatform_globals, modplatform_globals_table); diff --git a/extmod/modplatform.h b/extmod/modplatform.h index 56a50e53c54..2417a007b3a 100644 --- a/extmod/modplatform.h +++ b/extmod/modplatform.h @@ -36,7 +36,11 @@ // See: https://sourceforge.net/p/predef/wiki/Home/ #if defined(__ARM_ARCH) +#if defined(__ARM_ARCH_ISA_A64) +#define MICROPY_PLATFORM_ARCH "aarch64" +#else #define MICROPY_PLATFORM_ARCH "arm" +#endif #elif defined(__x86_64__) || defined(_M_X64) #define MICROPY_PLATFORM_ARCH "x86_64" #elif defined(__i386__) || defined(_M_IX86) @@ -44,12 +48,24 @@ #elif defined(__xtensa__) #define MICROPY_PLATFORM_ARCH "xtensa" #elif defined(__riscv) +#if __riscv_xlen == 64 +#define MICROPY_PLATFORM_ARCH "riscv64" +#else #define MICROPY_PLATFORM_ARCH "riscv" +#endif +#elif defined(__loongarch__) && defined(__loongarch64) +#define MICROPY_PLATFORM_ARCH "loongarch64" #else #define MICROPY_PLATFORM_ARCH "" #endif -#if defined(__GNUC__) +#if defined(__clang__) +#define MICROPY_PLATFORM_COMPILER \ + "Clang " \ + MP_STRINGIFY(__clang_major__) "." \ + MP_STRINGIFY(__clang_minor__) "." \ + MP_STRINGIFY(__clang_patchlevel__) +#elif defined(__GNUC__) #define MICROPY_PLATFORM_COMPILER \ "GCC " \ MP_STRINGIFY(__GNUC__) "." \ @@ -83,13 +99,26 @@ #elif defined(__NEWLIB__) #define MICROPY_PLATFORM_LIBC_LIB "newlib" #define MICROPY_PLATFORM_LIBC_VER _NEWLIB_VERSION +#elif defined(_PICOLIBC__) +#define MICROPY_PLATFORM_LIBC_LIB "picolibc" +#define MICROPY_PLATFORM_LIBC_VER _PICOLIBC_VERSION +#elif defined(__ANDROID__) +#define MICROPY_PLATFORM_LIBC_LIB "bionic" +#define MICROPY_PLATFORM_LIBC_VER MP_STRINGIFY(__ANDROID_API__) +#elif defined(__FreeBSD__) +#define MICROPY_PLATFORM_LIBC_LIB "libc" +#define MICROPY_PLATFORM_LIBC_VER "" #else #define MICROPY_PLATFORM_LIBC_LIB "" #define MICROPY_PLATFORM_LIBC_VER "" #endif -#if defined(__linux) +#if defined(__ANDROID__) +#define MICROPY_PLATFORM_SYSTEM "Android" +#elif defined(__linux) #define MICROPY_PLATFORM_SYSTEM "Linux" +#elif defined(__FreeBSD__) +#define MICROPY_PLATFORM_SYSTEM "FreeBSD" #elif defined(__unix__) #define MICROPY_PLATFORM_SYSTEM "Unix" #elif defined(__CYGWIN__) diff --git a/extmod/modre.c b/extmod/modre.c index a7e784a6ac9..36fff1d1dc6 100644 --- a/extmod/modre.c +++ b/extmod/modre.c @@ -31,7 +31,7 @@ #include "py/runtime.h" #include "py/binary.h" #include "py/objstr.h" -#include "py/stackctrl.h" +#include "py/cstack.h" #if MICROPY_PY_BUILTINS_STR_UNICODE #include "py/unicode.h" @@ -39,7 +39,7 @@ #if MICROPY_PY_RE -#define re1_5_stack_chk() MP_STACK_CHECK() +#define re1_5_stack_chk() mp_cstack_check() #include "lib/re1.5/re1.5.h" @@ -194,11 +194,13 @@ static void re_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t mp_printf(print, "", self); } -static mp_obj_t re_exec(bool is_anchored, uint n_args, const mp_obj_t *args) { - (void)n_args; +// Note: this function can't be named re_exec because it may clash with system headers, eg on FreeBSD +static mp_obj_t re_exec_helper(bool is_anchored, uint n_args, const mp_obj_t *args) { mp_obj_re_t *self; + bool was_compiled = false; if (mp_obj_is_type(args[0], (mp_obj_type_t *)&re_type)) { self = MP_OBJ_TO_PTR(args[0]); + was_compiled = true; } else { self = MP_OBJ_TO_PTR(mod_re_compile(1, args)); } @@ -206,37 +208,28 @@ static mp_obj_t re_exec(bool is_anchored, uint n_args, const mp_obj_t *args) { size_t len; subj.begin_line = subj.begin = mp_obj_str_get_data(args[1], &len); subj.end = subj.begin + len; - // CIRCUITPY-CHANGE - #if MICROPY_PY_RE_MATCH_SPAN_START_END && !(defined(MICROPY_ENABLE_DYNRUNTIME) && MICROPY_ENABLE_DYNRUNTIME) - - 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(args[1])); - const byte *begin = (const byte *)subj.begin; - int pos = mp_obj_get_int(args[2]); - if (pos >= str_len) { - return mp_const_none; - } - if (pos < 0) { - pos = 0; + if (was_compiled && n_args > 2) { + // Arg #2 is starting-pos + mp_int_t startpos = mp_obj_get_int(args[2]); + if (startpos > (mp_int_t)len) { + startpos = len; + } else if (startpos < 0) { + startpos = 0; } - const byte *pos_ptr = str_index_to_ptr(self_type, begin, len, MP_OBJ_NEW_SMALL_INT(pos), true); - - const byte *endpos_ptr = (const byte *)subj.end; + subj.begin += startpos; if (n_args > 3) { - int endpos = mp_obj_get_int(args[3]); - if (endpos <= pos) { - return mp_const_none; + // Arg #3 is ending-pos + mp_int_t endpos = mp_obj_get_int(args[3]); + if (endpos > (mp_int_t)len) { + endpos = len; + } else if (endpos < startpos) { + endpos = startpos; } - // Will cap to length - endpos_ptr = str_index_to_ptr(self_type, begin, len, args[3], true); + subj.end = subj.begin_line + endpos; } - - subj.begin = (const char *)pos_ptr; - subj.end = (const char *)endpos_ptr; } - #endif + int caps_num = (self->re.sub + 1) * 2; mp_obj_match_t *match = m_new_obj_var(mp_obj_match_t, caps, 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 @@ -254,12 +247,12 @@ static mp_obj_t re_exec(bool is_anchored, uint n_args, const mp_obj_t *args) { } static mp_obj_t re_match(size_t n_args, const mp_obj_t *args) { - return re_exec(true, n_args, args); + return re_exec_helper(true, n_args, args); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(re_match_obj, 2, 4, re_match); static mp_obj_t re_search(size_t n_args, const mp_obj_t *args) { - return re_exec(false, n_args, args); + return re_exec_helper(false, n_args, args); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(re_search_obj, 2, 4, re_search); @@ -457,6 +450,9 @@ static mp_obj_t mod_re_compile(size_t n_args, const mp_obj_t *args) { const char *re_str = mp_obj_str_get_str(args[0]); int size = re1_5_sizecode(re_str); if (size == -1) { + #if MICROPY_ERROR_REPORTING >= MICROPY_ERROR_REPORTING_NORMAL + mp_raise_ValueError(MP_ERROR_TEXT("regex too complex")); + #endif goto error; } mp_obj_re_t *o = mp_obj_malloc_var(mp_obj_re_t, re.insts, char, size, (mp_obj_type_t *)&re_type); @@ -469,6 +465,7 @@ static mp_obj_t mod_re_compile(size_t n_args, const mp_obj_t *args) { int error = re1_5_compilecode(&o->re, re_str); if (error != 0) { error: + // CIRCUITPY-CHANGE: capitalized mp_raise_ValueError(MP_ERROR_TEXT("Error in regex")); } #if MICROPY_PY_RE_DEBUG diff --git a/extmod/modselect.c b/extmod/modselect.c index c4edee6a56b..72566e024f0 100644 --- a/extmod/modselect.c +++ b/extmod/modselect.c @@ -344,6 +344,8 @@ static mp_uint_t poll_set_poll_until_ready_or_timeout(poll_set_t *poll_set, size mp_uint_t start_ticks = mp_hal_ticks_ms(); bool has_timeout = timeout != (mp_uint_t)-1; + mp_handle_pending(true); + #if MICROPY_PY_SELECT_POSIX_OPTIMISATIONS for (;;) { diff --git a/extmod/modtime.c b/extmod/modtime.c index deb4bb4c9ac..ee898828a4a 100644 --- a/extmod/modtime.c +++ b/extmod/modtime.c @@ -53,26 +53,26 @@ // - weekday is 0-6 for Mon-Sun // - yearday is 1-366 static mp_obj_t time_localtime(size_t n_args, const mp_obj_t *args) { + timeutils_struct_time_t tm; if (n_args == 0 || args[0] == mp_const_none) { // Get current date and time. - return mp_time_localtime_get(); + mp_time_localtime_get(&tm); } else { // Convert given seconds to tuple. - mp_int_t seconds = mp_obj_get_int(args[0]); - timeutils_struct_time_t tm; + mp_timestamp_t seconds = timeutils_obj_get_timestamp(args[0]); timeutils_seconds_since_epoch_to_struct_time(seconds, &tm); - mp_obj_t tuple[8] = { - tuple[0] = mp_obj_new_int(tm.tm_year), - tuple[1] = mp_obj_new_int(tm.tm_mon), - tuple[2] = mp_obj_new_int(tm.tm_mday), - tuple[3] = mp_obj_new_int(tm.tm_hour), - tuple[4] = mp_obj_new_int(tm.tm_min), - tuple[5] = mp_obj_new_int(tm.tm_sec), - tuple[6] = mp_obj_new_int(tm.tm_wday), - tuple[7] = mp_obj_new_int(tm.tm_yday), - }; - return mp_obj_new_tuple(8, tuple); } + mp_obj_t tuple[8] = { + mp_obj_new_int(tm.tm_year), + mp_obj_new_int(tm.tm_mon), + mp_obj_new_int(tm.tm_mday), + mp_obj_new_int(tm.tm_hour), + mp_obj_new_int(tm.tm_min), + mp_obj_new_int(tm.tm_sec), + mp_obj_new_int(tm.tm_wday), + mp_obj_new_int(tm.tm_yday), + }; + return mp_obj_new_tuple(8, tuple); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_time_localtime_obj, 0, 1, time_localtime); @@ -90,7 +90,7 @@ static mp_obj_t time_mktime(mp_obj_t tuple) { mp_raise_TypeError(MP_ERROR_TEXT("mktime needs a tuple of length 8 or 9")); } - return mp_obj_new_int_from_uint(timeutils_mktime(mp_obj_get_int(elem[0]), + return timeutils_obj_from_timestamp(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]))); } diff --git a/extmod/ulab b/extmod/ulab index 1d3ddd8f522..15e99974707 160000 --- a/extmod/ulab +++ b/extmod/ulab @@ -1 +1 @@ -Subproject commit 1d3ddd8f5228e2c7335dac71f4846e6abb0ec9f9 +Subproject commit 15e999747079205b2415e71a6aa2840b8f85f9dc diff --git a/extmod/vfs.c b/extmod/vfs.c index e7230e5ca03..86e96c3da16 100644 --- a/extmod/vfs.c +++ b/extmod/vfs.c @@ -42,11 +42,46 @@ #include "extmod/vfs_lfs.h" #endif -// CIRCUITPY-CHANGE: handle undefined without a warning -#if defined(MICROPY_VFS_POSIX) && MICROPY_VFS_POSIX +#if MICROPY_VFS_POSIX #include "extmod/vfs_posix.h" #endif +// CIRCUITPY-CHANGE: Shared bindings that take an already-opened file check +// mp_type_fileio for a binary file. That is aliased to the FAT fileio type, +// but files opened on a mounted littlefs (or posix) filesystem are a +// different type, so provide this check that accepts any filesystem's binary +// file type. +bool mp_obj_is_fileio(mp_obj_t file) { + #if MICROPY_VFS_FAT + // CIRCUITPY-CHANGE: mp_type_fileio is only aliased to the FAT fileio type + // by CircuitPython port configs; unix tests reference the FAT type directly. + if (mp_obj_is_type(file, &mp_type_vfs_fat_fileio)) { + return true; + } + #endif + #if MICROPY_VFS_LFS1 + if (mp_obj_is_type(file, &mp_type_vfs_lfs1_fileio)) { + return true; + } + #endif + #if MICROPY_VFS_LFS2 + if (mp_obj_is_type(file, &mp_type_vfs_lfs2_fileio)) { + return true; + } + #endif + #if MICROPY_VFS_POSIX + if (mp_obj_is_type(file, &mp_type_vfs_posix_fileio)) { + return true; + } + #endif + return false; +} + + +#if CIRCUITPY_SDCARDIO +#include "shared-module/sdcardio/__init__.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) @@ -67,6 +102,10 @@ mp_vfs_mount_t *mp_vfs_lookup_path(const char *path, const char **path_out) { // path is "" or "/" so return virtual root return MP_VFS_ROOT; } + // CIRCUITPY-CHANGE: Try and automount the SD card. + #if CIRCUITPY_SDCARDIO + automount_sd_card(); + #endif for (mp_vfs_mount_t *vfs = MP_STATE_VM(vfs_mount_table); vfs != NULL; vfs = vfs->next) { size_t len = vfs->len - 1; if (len == 0) { @@ -93,7 +132,7 @@ mp_vfs_mount_t *mp_vfs_lookup_path(const char *path, const char **path_out) { return MP_STATE_VM(vfs_cur); } -// Version of mp_vfs_lookup_path that takes and returns uPy string objects. +// Version of mp_vfs_lookup_path that takes and returns MicroPython string objects. static mp_vfs_mount_t *lookup_path(mp_obj_t path_in, mp_obj_t *path_out) { const char *path = mp_obj_str_get_str(path_in); const char *p_out; @@ -140,7 +179,7 @@ mp_import_stat_t mp_vfs_import_stat(const char *path) { } // delegate to vfs.stat() method - mp_obj_t path_o = mp_obj_new_str(path_out, strlen(path_out)); + mp_obj_t path_o = mp_obj_new_str_from_cstr(path_out); mp_obj_t stat; nlr_buf_t nlr; if (nlr_push(&nlr) == 0) { @@ -170,7 +209,9 @@ static mp_obj_t mp_vfs_autodetect(mp_obj_t bdev_obj) { mp_vfs_blockdev_init(&blockdev, bdev_obj); uint8_t buf[44]; for (size_t block_num = 0; block_num <= 1; ++block_num) { - mp_vfs_blockdev_read_ext(&blockdev, block_num, 8, sizeof(buf), buf); + if (mp_vfs_blockdev_read_ext(&blockdev, block_num, 8, sizeof(buf), buf) != 0) { + continue; + } #if MICROPY_VFS_LFS1 if (memcmp(&buf[32], "littlefs", 8) == 0) { // LFS1 @@ -203,22 +244,36 @@ static mp_obj_t mp_vfs_autodetect(mp_obj_t bdev_obj) { } mp_obj_t mp_vfs_mount(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - enum { ARG_readonly, ARG_mkfs }; + if (n_args == 0) { + // zero-args, output a table of all current mountpoints + mp_obj_t mount_list = mp_obj_new_list(0, NULL); + mp_vfs_mount_t *vfsp = MP_STATE_VM(vfs_mount_table); + while (vfsp != NULL) { + mp_obj_t items[] = { vfsp->obj, mp_obj_new_str(vfsp->str, vfsp->len) }; + mp_obj_list_append(mount_list, mp_obj_new_tuple(MP_ARRAY_SIZE(items), items)); + vfsp = vfsp->next; + } + return mount_list; + } + + enum { ARG_fsobj, ARG_mount_point, ARG_readonly, ARG_mkfs }; static const mp_arg_t allowed_args[] = { + { MP_QSTR_, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, { MP_QSTR_readonly, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_FALSE} }, { MP_QSTR_mkfs, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = MP_ROM_FALSE} }, }; // parse args mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; - mp_arg_parse_all(n_args - 2, pos_args + 2, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); // get the mount point size_t mnt_len; - const char *mnt_str = mp_obj_str_get_data(pos_args[1], &mnt_len); + const char *mnt_str = mp_obj_str_get_data(args[ARG_mount_point].u_obj, &mnt_len); // see if we need to auto-detect and create the filesystem - mp_obj_t vfs_obj = pos_args[0]; + mp_obj_t vfs_obj = args[ARG_fsobj].u_obj; mp_obj_t dest[2]; mp_load_method_maybe(vfs_obj, MP_QSTR_mount, dest); if (dest[0] == MP_OBJ_NULL) { @@ -235,11 +290,13 @@ 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_arg_val_t *proxy_args = &args[ARG_readonly]; + size_t proxy_args_len = MP_ARRAY_SIZE(args) - ARG_readonly; + mp_vfs_proxy_call(vfs, MP_QSTR_mount, proxy_args_len, (mp_obj_t *)proxy_args); // check that the destination mount point is unused const char *path_out; - mp_vfs_mount_t *existing_mount = mp_vfs_lookup_path(mp_obj_str_get_str(pos_args[1]), &path_out); + mp_vfs_mount_t *existing_mount = mp_vfs_lookup_path(mp_obj_str_get_str(args[ARG_mount_point].u_obj), &path_out); if (existing_mount != MP_VFS_NONE && existing_mount != MP_VFS_ROOT) { if (vfs->len != 1 && existing_mount->len == 1) { // if root dir is mounted, still allow to mount something within a subdir of root @@ -263,7 +320,7 @@ mp_obj_t mp_vfs_mount(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args return mp_const_none; } -MP_DEFINE_CONST_FUN_OBJ_KW(mp_vfs_mount_obj, 2, mp_vfs_mount); +MP_DEFINE_CONST_FUN_OBJ_KW(mp_vfs_mount_obj, 0, mp_vfs_mount); mp_obj_t mp_vfs_umount(mp_obj_t mnt_in) { // remove vfs from the mount table @@ -274,7 +331,7 @@ mp_obj_t mp_vfs_umount(mp_obj_t mnt_in) { mnt_str = mp_obj_str_get_data(mnt_in, &mnt_len); } for (mp_vfs_mount_t **vfsp = &MP_STATE_VM(vfs_mount_table); *vfsp != NULL; vfsp = &(*vfsp)->next) { - if ((mnt_str != NULL && !memcmp(mnt_str, (*vfsp)->str, mnt_len + 1)) || (*vfsp)->obj == mnt_in) { + if ((mnt_str != NULL && mnt_len == (*vfsp)->len && !memcmp(mnt_str, (*vfsp)->str, mnt_len)) || (*vfsp)->obj == mnt_in) { vfs = *vfsp; *vfsp = (*vfsp)->next; break; @@ -311,8 +368,7 @@ 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); - // CIRCUITPY-CHANGE: handle undefined without a warning - #if defined(MICROPY_VFS_POSIX) && MICROPY_VFS_POSIX + #if 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_vfs_posix_textio, args[ARG_file].u_obj, args[ARG_mode].u_obj); @@ -367,8 +423,18 @@ mp_obj_t mp_vfs_getcwd(void) { } MP_DEFINE_CONST_FUN_OBJ_0(mp_vfs_getcwd_obj, mp_vfs_getcwd); -// CIRCUITPY-CHANGE: accessible from shared-module/os/__init__.c -mp_obj_t mp_vfs_ilistdir_it_iternext(mp_obj_t self_in) { +typedef struct _mp_vfs_ilistdir_it_t { + mp_obj_base_t base; + mp_fun_1_t iternext; + union { + mp_vfs_mount_t *vfs; + mp_obj_t iter; + } cur; + bool is_str; + bool is_iter; +} mp_vfs_ilistdir_it_t; + +static mp_obj_t mp_vfs_ilistdir_it_iternext(mp_obj_t self_in) { mp_vfs_ilistdir_it_t *self = MP_OBJ_TO_PTR(self_in); if (self->is_iter) { // continue delegating to root dir @@ -435,6 +501,8 @@ mp_obj_t mp_vfs_listdir(size_t n_args, const mp_obj_t *args) { } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_vfs_listdir_obj, 0, 1, mp_vfs_listdir); +#if MICROPY_VFS_WRITABLE + mp_obj_t mp_vfs_mkdir(mp_obj_t path_in) { // CIRCUITPY-CHANGE: initialize mp_obj_t path_out = mp_const_none; @@ -472,6 +540,8 @@ mp_obj_t mp_vfs_rmdir(mp_obj_t path_in) { } MP_DEFINE_CONST_FUN_OBJ_1(mp_vfs_rmdir_obj, mp_vfs_rmdir); +#endif // MICROPY_VFS_WRITABLE + mp_obj_t mp_vfs_stat(mp_obj_t path_in) { mp_obj_t path_out; mp_vfs_mount_t *vfs = lookup_path(path_in, &path_out); @@ -541,6 +611,32 @@ int mp_vfs_mount_and_chdir_protected(mp_obj_t bdev, mp_obj_t mount_point) { return ret; } +#if MICROPY_VFS_ROM && MICROPY_VFS_ROM_IOCTL + +int mp_vfs_mount_romfs_protected(void) { + int ret; + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + mp_obj_t args[2] = { MP_OBJ_NEW_SMALL_INT(MP_VFS_ROM_IOCTL_GET_SEGMENT), MP_OBJ_NEW_SMALL_INT(0) }; + mp_obj_t rom = mp_vfs_rom_ioctl(2, args); + mp_obj_t romfs = mp_call_function_1(MP_OBJ_FROM_PTR(&mp_type_vfs_rom), rom); + mp_obj_t mount_point = MP_OBJ_NEW_QSTR(MP_QSTR__slash_rom); + mp_call_function_2(MP_OBJ_FROM_PTR(&mp_vfs_mount_obj), romfs, mount_point); + #if MICROPY_PY_SYS_PATH_ARGV_DEFAULTS + // Add "/rom" and "/rom/lib" to `sys.path`. + mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR__slash_rom)); + mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR__slash_rom_slash_lib)); + #endif + ret = 0; // success + nlr_pop(); + } else { + ret = -MP_EIO; + } + return ret; +} + +#endif + MP_REGISTER_ROOT_POINTER(struct _mp_vfs_mount_t *vfs_cur); MP_REGISTER_ROOT_POINTER(struct _mp_vfs_mount_t *vfs_mount_table); diff --git a/extmod/vfs.h b/extmod/vfs.h index 65cf4ece985..8696569d69d 100644 --- a/extmod/vfs.h +++ b/extmod/vfs.h @@ -41,7 +41,9 @@ #define MP_S_IFREG (0x8000) // these are the values for mp_vfs_blockdev_t.flags +#if MICROPY_VFS_BLOCKDEV_NATIVE #define MP_BLOCKDEV_FLAG_NATIVE (0x0001) // readblocks[2]/writeblocks[2] contain native func +#endif #define MP_BLOCKDEV_FLAG_FREE_OBJ (0x0002) // fs_user_mount_t obj should be freed on umount #define MP_BLOCKDEV_FLAG_HAVE_IOCTL (0x0004) // new protocol with ioctl #define MP_BLOCKDEV_FLAG_NO_FILESYSTEM (0x0008) // the block device has no filesystem on it @@ -52,6 +54,8 @@ #define MP_BLOCKDEV_FLAG_CONCURRENT_WRITE_PROTECTED (0x0020) // Bit set when something has claimed the right to mutate the blockdev. #define MP_BLOCKDEV_FLAG_LOCKED (0x0040) +// Ignore write protections. Used to override other flags temporarily. +#define MP_BLOCKDEV_FLAG_IGNORE_WRITE_PROTECTION (0x0080) // constants for block protocol ioctl #define MP_BLOCKDEV_IOCTL_INIT (1) @@ -61,6 +65,22 @@ #define MP_BLOCKDEV_IOCTL_BLOCK_SIZE (5) #define MP_BLOCKDEV_IOCTL_BLOCK_ERASE (6) +// Constants for vfs.rom_ioctl() function. +// The 4-arg form of WRITE_PREPARE is only available if GET_MIN_PREPARE returns >0. +#define MP_VFS_ROM_IOCTL_GET_NUMBER_OF_SEGMENTS (1) // rom_ioctl(1) +#define MP_VFS_ROM_IOCTL_GET_SEGMENT (2) // rom_ioctl(2, ) +#define MP_VFS_ROM_IOCTL_WRITE_PREPARE (3) // rom_ioctl(3, , ) or rom_ioctl(3, , , ) +#define MP_VFS_ROM_IOCTL_WRITE (4) // rom_ioctl(4, , , ) +#define MP_VFS_ROM_IOCTL_WRITE_COMPLETE (5) // rom_ioctl(5, ) +#define MP_VFS_ROM_IOCTL_GET_MIN_PREPARE (6) // rom_ioctl(6, ) + +#if MICROPY_VFS_BLOCKDEV_NATIVE +// Function signatures used when MP_BLOCKDEV_FLAG_NATIVE is set. +// Should return 0 for success, or a negative errno code for failure. +typedef int (*mp_vfs_blockdev_native_readblocks)(uint8_t *, uint32_t, uint32_t); +typedef int (*mp_vfs_blockdev_native_writeblocks)(const uint8_t *, uint32_t, uint32_t); +#endif + // At the moment the VFS protocol just has import_stat, but could be extended to other methods typedef struct _mp_vfs_proto_t { // CIRCUITPY-CHANGE @@ -94,19 +114,6 @@ typedef struct _mp_vfs_mount_t { struct _mp_vfs_mount_t *next; } mp_vfs_mount_t; -// CIRCUITPY-CHANGE: allow outside use of ilistdir_it_iternext -typedef struct _mp_vfs_ilistdir_it_t { - mp_obj_base_t base; - mp_fun_1_t iternext; - union { - mp_vfs_mount_t *vfs; - mp_obj_t iter; - } cur; - bool is_str; - bool is_iter; -} mp_vfs_ilistdir_it_t; - -mp_obj_t mp_vfs_ilistdir_it_iternext(mp_obj_t self_in); void mp_vfs_blockdev_init(mp_vfs_blockdev_t *self, mp_obj_t bdev); int mp_vfs_blockdev_read(mp_vfs_blockdev_t *self, size_t block_num, size_t num_blocks, uint8_t *buf); int mp_vfs_blockdev_read_ext(mp_vfs_blockdev_t *self, size_t block_num, size_t block_off, size_t len, uint8_t *buf); @@ -123,14 +130,19 @@ mp_obj_t mp_vfs_chdir(mp_obj_t path_in); mp_obj_t mp_vfs_getcwd(void); mp_obj_t mp_vfs_ilistdir(size_t n_args, const mp_obj_t *args); mp_obj_t mp_vfs_listdir(size_t n_args, const mp_obj_t *args); +#if MICROPY_VFS_WRITABLE mp_obj_t mp_vfs_mkdir(mp_obj_t path_in); mp_obj_t mp_vfs_remove(mp_obj_t path_in); mp_obj_t mp_vfs_rename(mp_obj_t old_path_in, mp_obj_t new_path_in); mp_obj_t mp_vfs_rmdir(mp_obj_t path_in); +#endif mp_obj_t mp_vfs_stat(mp_obj_t path_in); mp_obj_t mp_vfs_statvfs(mp_obj_t path_in); int mp_vfs_mount_and_chdir_protected(mp_obj_t bdev, mp_obj_t mount_point); +#if MICROPY_VFS_ROM && MICROPY_VFS_ROM_IOCTL +int mp_vfs_mount_romfs_protected(void); +#endif MP_DECLARE_CONST_FUN_OBJ_KW(mp_vfs_mount_obj); MP_DECLARE_CONST_FUN_OBJ_1(mp_vfs_umount_obj); @@ -139,11 +151,28 @@ MP_DECLARE_CONST_FUN_OBJ_1(mp_vfs_chdir_obj); MP_DECLARE_CONST_FUN_OBJ_0(mp_vfs_getcwd_obj); MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(mp_vfs_ilistdir_obj); MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(mp_vfs_listdir_obj); +#if MICROPY_VFS_WRITABLE MP_DECLARE_CONST_FUN_OBJ_1(mp_vfs_mkdir_obj); MP_DECLARE_CONST_FUN_OBJ_1(mp_vfs_remove_obj); MP_DECLARE_CONST_FUN_OBJ_2(mp_vfs_rename_obj); MP_DECLARE_CONST_FUN_OBJ_1(mp_vfs_rmdir_obj); +#endif MP_DECLARE_CONST_FUN_OBJ_1(mp_vfs_stat_obj); MP_DECLARE_CONST_FUN_OBJ_1(mp_vfs_statvfs_obj); +#if MICROPY_VFS_ROM_IOCTL +// When MICROPY_VFS_ROM_IOCTL is enabled a port must define the following function. +// This is a generic interface to allow querying and modifying the user-accessible, +// read-only memory area of a device, if it is configured with such an area. +// Supported ioctl commands are given by MP_VFS_ROM_IOCTL_xxx. +mp_obj_t mp_vfs_rom_ioctl(size_t n_args, const mp_obj_t *args); +#endif + +// CIRCUITPY-CHANGE: Shared bindings that take an already-opened file check +// mp_type_fileio for a binary file. That is aliased to the FAT fileio type in +// py/circuitpy_mpconfig.h, but files opened on a mounted littlefs (or posix) +// filesystem are a different type, so provide this check that accepts any +// filesystem's binary file type. +bool mp_obj_is_fileio(mp_obj_t file); + #endif // MICROPY_INCLUDED_EXTMOD_VFS_H diff --git a/extmod/vfs_blockdev.c b/extmod/vfs_blockdev.c index eda5cecc147..db6fc28e2ec 100644 --- a/extmod/vfs_blockdev.c +++ b/extmod/vfs_blockdev.c @@ -38,6 +38,10 @@ #include "shared-bindings/sdioio/SDCard.h" #endif +#if CIRCUITPY_EMMCIO +#include "shared-bindings/emmcio/EMMC.h" +#endif + #if MICROPY_VFS @@ -63,7 +67,35 @@ void mp_vfs_blockdev_init(mp_vfs_blockdev_t *self, mp_obj_t bdev) { #endif #if CIRCUITPY_SDIOIO if (mp_obj_get_type(bdev) == &sdioio_SDCard_type) { - // TODO: Enable native blockdev for SDIO too. + self->flags |= MP_BLOCKDEV_FLAG_NATIVE | MP_BLOCKDEV_FLAG_HAVE_IOCTL; + self->readblocks[0] = mp_const_none; + self->readblocks[1] = bdev; + self->readblocks[2] = (mp_obj_t)sdioio_sdcard_readblocks; // native version + self->writeblocks[0] = mp_const_none; + self->writeblocks[1] = bdev; + self->writeblocks[2] = (mp_obj_t)sdioio_sdcard_writeblocks; // native version + self->u.ioctl[0] = mp_const_none; + self->u.ioctl[1] = bdev; + self->u.ioctl[2] = (mp_obj_t)sdioio_sdcard_ioctl; // native version + } + #endif + + #if CIRCUITPY_EMMCIO + if (mp_obj_get_type(bdev) == &emmcio_emmc_type) { + self->flags |= MP_BLOCKDEV_FLAG_NATIVE | MP_BLOCKDEV_FLAG_HAVE_IOCTL; + self->readblocks[0] = mp_const_none; + self->readblocks[1] = bdev; + self->readblocks[2] = (mp_obj_t)emmcio_emmc_readblocks_native; + if (emmcio_emmc_is_write_enabled(bdev)) { + self->writeblocks[0] = mp_const_none; + self->writeblocks[1] = bdev; + self->writeblocks[2] = (mp_obj_t)emmcio_emmc_writeblocks_native; + } else { + self->writeblocks[0] = MP_OBJ_NULL; + } + self->u.ioctl[0] = mp_const_none; + self->u.ioctl[1] = bdev; + self->u.ioctl[2] = (mp_obj_t)emmcio_emmc_ioctl_native; } #endif if (self->u.ioctl[0] != MP_OBJ_NULL) { @@ -76,33 +108,46 @@ void mp_vfs_blockdev_init(mp_vfs_blockdev_t *self, mp_obj_t bdev) { } } +// Helper function to minimise code size of read/write functions +// note the n_args argument is moved to the end for further code size reduction (args keep same position in caller and callee). +static int mp_vfs_blockdev_call_rw(mp_obj_t *args, size_t block_num, size_t block_off, size_t len, void *buf, size_t n_args) { + #if MICROPY_PY_BUILTINS_MEMORYVIEW + mp_obj_array_t ar = {{&mp_type_memoryview}, 'B' | MP_OBJ_ARRAY_TYPECODE_FLAG_RW, 0, len, buf}; + #else + mp_obj_array_t ar = {{&mp_type_bytearray}, BYTEARRAY_TYPECODE, 0, len, buf}; + #endif + args[2] = MP_OBJ_NEW_SMALL_INT(block_num); + args[3] = MP_OBJ_FROM_PTR(&ar); + args[4] = MP_OBJ_NEW_SMALL_INT(block_off); // ignored for n_args == 2 + mp_obj_t ret = mp_call_method_n_kw(n_args, 0, args); + + if (ret == mp_const_none) { + return 0; + } else { + // Block device functions are expected to return 0 on success + // and negative integer on errors. Check for positive integer + // results as some callers (i.e. littlefs) will produce corrupt + // results from these. + int i = mp_obj_get_int(ret); + return i > 0 ? (-MP_EINVAL) : i; + } +} + int mp_vfs_blockdev_read(mp_vfs_blockdev_t *self, size_t block_num, size_t num_blocks, uint8_t *buf) { + #if MICROPY_VFS_BLOCKDEV_NATIVE if (self->flags & MP_BLOCKDEV_FLAG_NATIVE) { // CIRCUITPY-CHANGE: Pass the blockdev object into native readblocks so // it has the corresponding state. mp_uint_t (*f)(mp_obj_t self, uint8_t *, uint32_t, uint32_t) = (void *)(uintptr_t)self->readblocks[2]; return f(self->readblocks[1], buf, block_num, num_blocks); - } else { - mp_obj_array_t ar = {{&mp_type_bytearray}, BYTEARRAY_TYPECODE, 0, num_blocks *self->block_size, buf}; - self->readblocks[2] = MP_OBJ_NEW_SMALL_INT(block_num); - self->readblocks[3] = MP_OBJ_FROM_PTR(&ar); - mp_call_method_n_kw(2, 0, self->readblocks); - // TODO handle error return - return 0; } + #endif + + return mp_vfs_blockdev_call_rw(self->readblocks, block_num, 0, num_blocks * self->block_size, buf, 2); } int mp_vfs_blockdev_read_ext(mp_vfs_blockdev_t *self, size_t block_num, size_t block_off, size_t len, uint8_t *buf) { - mp_obj_array_t ar = {{&mp_type_bytearray}, BYTEARRAY_TYPECODE, 0, len, buf}; - self->readblocks[2] = MP_OBJ_NEW_SMALL_INT(block_num); - self->readblocks[3] = MP_OBJ_FROM_PTR(&ar); - self->readblocks[4] = MP_OBJ_NEW_SMALL_INT(block_off); - mp_obj_t ret = mp_call_method_n_kw(3, 0, self->readblocks); - if (ret == mp_const_none) { - return 0; - } else { - return MP_OBJ_SMALL_INT_VALUE(ret); - } + return mp_vfs_blockdev_call_rw(self->readblocks, block_num, block_off, len, buf, 3); } int mp_vfs_blockdev_write(mp_vfs_blockdev_t *self, size_t block_num, size_t num_blocks, const uint8_t *buf) { @@ -111,19 +156,16 @@ int mp_vfs_blockdev_write(mp_vfs_blockdev_t *self, size_t block_num, size_t num_ return -MP_EROFS; } + #if MICROPY_VFS_BLOCKDEV_NATIVE if (self->flags & MP_BLOCKDEV_FLAG_NATIVE) { - // CIRCUITPY-CHANGE: Pass the blockdev object into native readblocks so + // CIRCUITPY-CHANGE: Pass the blockdev object into native writeblocks so // it has the corresponding state. mp_uint_t (*f)(mp_obj_t self, const uint8_t *, uint32_t, uint32_t) = (void *)(uintptr_t)self->writeblocks[2]; return f(self->writeblocks[1], buf, block_num, num_blocks); - } else { - mp_obj_array_t ar = {{&mp_type_bytearray}, BYTEARRAY_TYPECODE, 0, num_blocks *self->block_size, (void *)buf}; - self->writeblocks[2] = MP_OBJ_NEW_SMALL_INT(block_num); - self->writeblocks[3] = MP_OBJ_FROM_PTR(&ar); - mp_call_method_n_kw(2, 0, self->writeblocks); - // TODO handle error return - return 0; } + #endif + + return mp_vfs_blockdev_call_rw(self->writeblocks, block_num, 0, num_blocks * self->block_size, (void *)buf, 2); } int mp_vfs_blockdev_write_ext(mp_vfs_blockdev_t *self, size_t block_num, size_t block_off, size_t len, const uint8_t *buf) { @@ -131,22 +173,13 @@ int mp_vfs_blockdev_write_ext(mp_vfs_blockdev_t *self, size_t block_num, size_t // read-only block device return -MP_EROFS; } - - mp_obj_array_t ar = {{&mp_type_bytearray}, BYTEARRAY_TYPECODE, 0, len, (void *)buf}; - self->writeblocks[2] = MP_OBJ_NEW_SMALL_INT(block_num); - self->writeblocks[3] = MP_OBJ_FROM_PTR(&ar); - self->writeblocks[4] = MP_OBJ_NEW_SMALL_INT(block_off); - mp_obj_t ret = mp_call_method_n_kw(3, 0, self->writeblocks); - if (ret == mp_const_none) { - return 0; - } else { - return MP_OBJ_SMALL_INT_VALUE(ret); - } + return mp_vfs_blockdev_call_rw(self->writeblocks, block_num, block_off, len, (void *)buf, 3); } mp_obj_t mp_vfs_blockdev_ioctl(mp_vfs_blockdev_t *self, uintptr_t cmd, uintptr_t arg) { if (self->flags & MP_BLOCKDEV_FLAG_HAVE_IOCTL) { // CIRCUITPY-CHANGE: Support native IOCTL so it can run outside of the VM. + #if MICROPY_VFS_BLOCKDEV_NATIVE if (self->flags & MP_BLOCKDEV_FLAG_NATIVE) { size_t out_value; bool (*f)(mp_obj_t self, uint32_t, uint32_t, size_t *) = (void *)(uintptr_t)self->u.ioctl[2]; @@ -156,6 +189,7 @@ mp_obj_t mp_vfs_blockdev_ioctl(mp_vfs_blockdev_t *self, uintptr_t cmd, uintptr_t } return MP_OBJ_NEW_SMALL_INT(out_value); } + #endif // New protocol with ioctl self->u.ioctl[2] = MP_OBJ_NEW_SMALL_INT(cmd); self->u.ioctl[3] = MP_OBJ_NEW_SMALL_INT(arg); diff --git a/extmod/vfs_fat.c b/extmod/vfs_fat.c index 929bd5fd98e..d7bb87aafed 100644 --- a/extmod/vfs_fat.c +++ b/extmod/vfs_fat.c @@ -38,6 +38,7 @@ // CIRCUITPY-CHANGE: extra includes #include +#include "py/gc.h" #include "py/obj.h" #include "py/objproperty.h" #include "py/runtime.h" @@ -46,6 +47,9 @@ #include "extmod/vfs_fat.h" #include "shared/timeutils/timeutils.h" #include "supervisor/filesystem.h" +#if CIRCUITPY_STORAGE_MAP_FILE +#include "shared-bindings/storage/__init__.h" +#endif #if FF_MAX_SS == FF_MIN_SS #define SECSIZE(fs) (FF_MIN_SS) @@ -57,7 +61,7 @@ // CIRCUITPY-CHANGE // Factoring this common call saves about 90 bytes. -static NORETURN void mp_raise_OSError_fresult(FRESULT res) { +static MP_NORETURN void mp_raise_OSError_fresult(FRESULT res) { mp_raise_OSError(fresult_to_errno_table[res]); } @@ -103,7 +107,7 @@ static mp_obj_t fat_vfs_make_new(const mp_obj_type_t *type, size_t n_args, size_ // CIRCUITPY-CHANGE static void verify_fs_writable(fs_user_mount_t *vfs) { - if (!filesystem_is_writable_by_python(vfs)) { + if (!filesystem_is_writable_by_python((supervisor_vfs_t *)vfs)) { mp_raise_OSError(MP_EROFS); } } @@ -133,6 +137,11 @@ static mp_obj_t fat_vfs_mkfs(mp_obj_t bdev_in) { mp_raise_OSError_fresult(res); } + // set the filesystem label if it's configured + #ifdef MICROPY_HW_FLASH_FS_LABEL + f_setlabel(&vfs->fatfs, MICROPY_HW_FLASH_FS_LABEL); + #endif + return mp_const_none; } static MP_DEFINE_CONST_FUN_OBJ_1(fat_vfs_mkfs_fun_obj, fat_vfs_mkfs); @@ -163,7 +172,7 @@ static mp_obj_t mp_vfs_fat_ilistdir_it_iternext(mp_obj_t self_in) { // make 4-tuple with info about this entry mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(4, NULL)); if (self->is_str) { - t->items[0] = mp_obj_new_str(fn, strlen(fn)); + t->items[0] = mp_obj_new_str_from_cstr(fn); } else { t->items[0] = mp_obj_new_bytes((const byte *)fn, strlen(fn)); } @@ -237,6 +246,11 @@ static mp_obj_t fat_vfs_remove_internal(mp_obj_t vfs_in, mp_obj_t path_in, mp_in // check if path is a file or directory if ((fno.fattrib & AM_DIR) == attr) { + #if CIRCUITPY_STORAGE_MAP_FILE + if (attr == 0) { + storage_map_file_check_writable(self, path); + } + #endif res = f_unlink(&self->fatfs, path); if (res != FR_OK) { @@ -322,7 +336,7 @@ static mp_obj_t fat_vfs_getcwd(mp_obj_t vfs_in) { // CIRCUITPY-CHANGE mp_raise_OSError_fresult(res); } - return mp_obj_new_str(buf, strlen(buf)); + return mp_obj_new_str_from_cstr(buf); } static MP_DEFINE_CONST_FUN_OBJ_1(fat_vfs_getcwd_obj, fat_vfs_getcwd); @@ -342,7 +356,10 @@ static mp_obj_t fat_vfs_stat(mp_obj_t vfs_in, mp_obj_t path_in) { FRESULT res = f_stat(&self->fatfs, path, &fno); if (res != FR_OK) { // CIRCUITPY-CHANGE - mp_raise_OSError_fresult(res); + if (gc_alloc_possible()) { + mp_raise_OSError_fresult(res); + } + return mp_const_none; } } @@ -418,13 +435,13 @@ static MP_DEFINE_CONST_FUN_OBJ_2(fat_vfs_statvfs_obj, fat_vfs_statvfs); static mp_obj_t vfs_fat_mount(mp_obj_t self_in, mp_obj_t readonly, mp_obj_t mkfs) { fs_user_mount_t *self = MP_OBJ_TO_PTR(self_in); - // Read-only device indicated by writeblocks[0] == MP_OBJ_NULL. - // User can specify read-only device by: - // 1. readonly=True keyword argument - // 2. nonexistent writeblocks method (then writeblocks[0] == MP_OBJ_NULL already) - if (mp_obj_is_true(readonly)) { - self->blockdev.writeblocks[0] = MP_OBJ_NULL; - } + // CIRCUITPY-CHANGE: Use MP_BLOCKDEV_FLAG_USB_WRITABLE instead of writeblocks[0] =/!= MP_OBJ_NULL + // to specify read-write. + // If readonly to Python, it's writable by USB and vice versa. + // CIRCUITPY-CHANGE: The flag helpers take a supervisor_vfs_t so they work + // for the FAT and littlefs root filesystems alike. A VfsFat is always a + // fs_user_mount_t, whose blockdev prefix matches both vfs kinds. + filesystem_set_writable_by_usb((supervisor_vfs_t *)self, mp_obj_is_true(readonly)); // check if we need to make the filesystem FRESULT res = (self->blockdev.flags & MP_BLOCKDEV_FLAG_NO_FILESYSTEM) ? FR_NO_FILESYSTEM : FR_OK; @@ -481,7 +498,7 @@ static MP_DEFINE_CONST_FUN_OBJ_3(fat_vfs_utime_obj, vfs_fat_utime); static mp_obj_t vfs_fat_getreadonly(mp_obj_t self_in) { fs_user_mount_t *self = MP_OBJ_TO_PTR(self_in); - return mp_obj_new_bool(!filesystem_is_writable_by_python(self)); + return mp_obj_new_bool(!filesystem_is_writable_by_python((supervisor_vfs_t *)self)); } static MP_DEFINE_CONST_FUN_OBJ_1(fat_vfs_getreadonly_obj, vfs_fat_getreadonly); diff --git a/extmod/vfs_fat.h b/extmod/vfs_fat.h index b25950100e6..feca4b4e7d4 100644 --- a/extmod/vfs_fat.h +++ b/extmod/vfs_fat.h @@ -47,10 +47,13 @@ extern const mp_obj_type_t mp_type_vfs_fat_textio; MP_DECLARE_CONST_FUN_OBJ_3(fat_vfs_open_obj); -// CIRCUITPY-CHANGE +// CIRCUITPY-CHANGE: moved here from vfs_fat_file.c so other code can use the FIL. +// holds_lock added. typedef struct _pyb_file_obj_t { mp_obj_base_t base; FIL fp; + // True if this file took the filesystem lock when it was opened for writing. + bool holds_lock; } pyb_file_obj_t; #endif // MICROPY_INCLUDED_EXTMOD_VFS_FAT_H diff --git a/extmod/vfs_fat_diskio.c b/extmod/vfs_fat_diskio.c index 6f500104d1e..5d99ce24d5b 100644 --- a/extmod/vfs_fat_diskio.c +++ b/extmod/vfs_fat_diskio.c @@ -43,6 +43,9 @@ #include "lib/oofatfs/diskio.h" #include "extmod/vfs_fat.h" +// CIRCUITPY-CHANGE +#include "supervisor/filesystem.h" + typedef void *bdev_t; static fs_user_mount_t *disk_get_device(void *bdev) { return (fs_user_mount_t *)bdev; @@ -153,7 +156,8 @@ DRESULT disk_ioctl( if (ret != mp_const_none && MP_OBJ_SMALL_INT_VALUE(ret) != 0) { // error initialising stat = STA_NOINIT; - } else if (vfs->blockdev.writeblocks[0] == MP_OBJ_NULL) { + // CIRCUITPY-CHANGE: writability from Python check + } else if (!filesystem_is_writable_by_python((supervisor_vfs_t *)vfs)) { stat = STA_PROTECT; } else { stat = 0; diff --git a/extmod/vfs_fat_file.c b/extmod/vfs_fat_file.c index 2a3021ee9a8..13ad624ee22 100644 --- a/extmod/vfs_fat_file.c +++ b/extmod/vfs_fat_file.c @@ -37,6 +37,9 @@ #include "lib/oofatfs/ff.h" #include "extmod/vfs_fat.h" #include "supervisor/filesystem.h" +#if CIRCUITPY_STORAGE_MAP_FILE +#include "shared-bindings/storage/__init__.h" +#endif // this table converts from FRESULT to POSIX errno const byte fresult_to_errno_table[20] = { @@ -102,15 +105,15 @@ static mp_uint_t file_obj_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, struct mp_stream_seek_t *s = (struct mp_stream_seek_t *)(uintptr_t)arg; switch (s->whence) { - case 0: // SEEK_SET + case MP_SEEK_SET: f_lseek(&self->fp, s->offset); break; - case 1: // SEEK_CUR + case MP_SEEK_CUR: f_lseek(&self->fp, f_tell(&self->fp) + s->offset); break; - case 2: // SEEK_END + case MP_SEEK_END: f_lseek(&self->fp, f_size(&self->fp) + s->offset); break; } @@ -129,11 +132,19 @@ static mp_uint_t file_obj_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, } else if (request == MP_STREAM_CLOSE) { // if fs==NULL then the file is closed and in that case this method is a no-op if (self->fp.obj.fs != NULL) { + // CIRCUITPY-CHANGE: get the mount now, because a successful f_close() clears obj.fs. + supervisor_vfs_t *mount = (supervisor_vfs_t *)self->fp.obj.fs->drv; FRESULT res = f_close(&self->fp); if (res != FR_OK) { *errcode = fresult_to_errno_table[res]; return MP_STREAM_ERROR; } + // CIRCUITPY-CHANGE: release the lock taken when the file was opened for writing. + // If f_close() fails, the file is still open and keeps the lock. + if (self->holds_lock) { + filesystem_unlock(mount); + self->holds_lock = false; + } } return 0; @@ -246,16 +257,37 @@ static mp_obj_t fat_vfs_open(mp_obj_t self_in, mp_obj_t path_in, mp_obj_t mode_i } assert(self != NULL); - if ((mode & FA_WRITE) != 0 && !filesystem_is_writable_by_python(self)) { + if ((mode & FA_WRITE) != 0 && !filesystem_is_writable_by_python((supervisor_vfs_t *)self)) { mp_raise_OSError(MP_EROFS); } + #if CIRCUITPY_STORAGE_MAP_FILE + if ((mode & FA_WRITE) != 0) { + storage_map_file_check_writable(self, mp_obj_str_get_str(path_in)); + } + #endif - + // CIRCUITPY-CHANGE: get fname first, because it can raise. + const char *fname = mp_obj_str_get_str(path_in); pyb_file_obj_t *o = mp_obj_malloc_with_finaliser(pyb_file_obj_t, type); - const char *fname = mp_obj_str_get_str(path_in); + // CIRCUITPY-CHANGE: a file open for writing holds the filesystem lock until it is closed, + // so USB MSC cannot make the filesystem writable to the host underneath it. + // With concurrent write protection off, Python and the host share the filesystem on purpose. + o->holds_lock = false; + if ((mode & FA_WRITE) != 0 && (self->blockdev.flags & MP_BLOCKDEV_FLAG_CONCURRENT_WRITE_PROTECTED) != 0) { + if (!filesystem_lock((supervisor_vfs_t *)self)) { + m_del_obj(pyb_file_obj_t, o); + mp_raise_OSError(MP_EROFS); + } + o->holds_lock = true; + } + FRESULT res = f_open(&self->fatfs, &o->fp, fname, mode); if (res != FR_OK) { + // CIRCUITPY-CHANGE + if (o->holds_lock) { + filesystem_unlock((supervisor_vfs_t *)self); + } m_del_obj(pyb_file_obj_t, o); mp_raise_OSError_errno_str(fresult_to_errno_table[res], path_in); } diff --git a/extmod/vfs_lfs.c b/extmod/vfs_lfs.c index 19063d63066..eed6946fc26 100644 --- a/extmod/vfs_lfs.c +++ b/extmod/vfs_lfs.c @@ -26,6 +26,7 @@ #include "py/runtime.h" #include "py/mphal.h" +#include "supervisor/fatfs.h" #if MICROPY_VFS && (MICROPY_VFS_LFS1 || MICROPY_VFS_LFS2) @@ -105,15 +106,6 @@ mp_obj_t mp_vfs_lfs1_file_open(mp_obj_t self_in, mp_obj_t path_in, mp_obj_t mode // Attribute ids for lfs2_attr.type. #define LFS_ATTR_MTIME (1) // 64-bit little endian, nanoseconds since 1970/1/1 -typedef struct _mp_obj_vfs_lfs2_t { - mp_obj_base_t base; - mp_vfs_blockdev_t blockdev; - bool enable_mtime; - vstr_t cur_dir; - struct lfs2_config config; - lfs2_t lfs; -} mp_obj_vfs_lfs2_t; - typedef struct _mp_obj_vfs_lfs2_file_t { mp_obj_base_t base; mp_obj_vfs_lfs2_t *vfs; @@ -128,8 +120,10 @@ const char *mp_vfs_lfs2_make_path(mp_obj_vfs_lfs2_t *self, mp_obj_t path_in); mp_obj_t mp_vfs_lfs2_file_open(mp_obj_t self_in, mp_obj_t path_in, mp_obj_t mode_in); static void lfs_get_mtime(uint8_t buf[8]) { - // On-disk storage of timestamps uses 1970 as the Epoch, so convert from host's Epoch. - uint64_t ns = timeutils_nanoseconds_since_epoch_to_nanoseconds_since_1970(mp_hal_time_ns()); + // CIRCUITPY-CHANGE: Use the same RTC-based time that get_fattime() gives + // the FAT filesystems, so every filesystem kind stamps files alike. + // On-disk storage of timestamps is 64-bit little endian, ns since 1970/1/1. + uint64_t ns = get_fattime_ns(); // Store "ns" to "buf" in little-endian format (essentially htole64). for (size_t i = 0; i < 8; ++i) { buf[i] = ns; @@ -140,6 +134,50 @@ static void lfs_get_mtime(uint8_t buf[8]) { #include "extmod/vfs_lfsx.c" #include "extmod/vfs_lfsx_file.c" +// CIRCUITPY-CHANGE: Supervisor-facing littlefs mount. The caller prepares the +// mp_obj_vfs_lfs2_t (zeroed, with blockdev callbacks and lfs2_config geometry +// already filled in) and the port allocator for the littlefs caches. This runs +// without the VM or its GC, so no MicroPython allocations may happen here. +mp_obj_t mp_vfs_lfs2_mount_supervisor(mp_obj_vfs_lfs2_t *self, void *(*alloc)(size_t), bool format_allowed, bool *formatted_out, int *mount_err) { + struct lfs2_config *config = &self->config; + + config->block_cycles = 100; + config->cache_size = MIN(config->block_size, (4 * MAX(config->read_size, config->prog_size))); + config->lookahead_size = 32; + config->read_buffer = alloc(config->cache_size); + config->prog_buffer = alloc(config->cache_size); + config->lookahead_buffer = alloc(config->lookahead_size); + if (config->read_buffer == NULL || config->prog_buffer == NULL || config->lookahead_buffer == NULL) { + if (mount_err != NULL) { + *mount_err = LFS2_ERR_NOMEM; + } + return MP_OBJ_NULL; + } + + bool formatted = false; + int ret = lfs2_mount(&self->lfs, config); + if (ret < 0 && format_allowed) { + // Empty or corrupted. Format a fresh filesystem and try again. + ret = lfs2_format(&self->lfs, config); + if (ret >= 0) { + formatted = true; + ret = lfs2_mount(&self->lfs, config); + } + } + if (formatted_out != NULL && formatted) { + // Only ever set true: the caller may have formatted the filesystem + // itself (force reformat) and needs that to survive the mount. + *formatted_out = true; + } + if (mount_err != NULL) { + *mount_err = ret; + } + if (ret < 0) { + return MP_OBJ_NULL; + } + return MP_OBJ_FROM_PTR(self); +} + #endif // MICROPY_VFS_LFS2 #endif // MICROPY_VFS && (MICROPY_VFS_LFS1 || MICROPY_VFS_LFS2) diff --git a/extmod/vfs_lfs.h b/extmod/vfs_lfs.h index 1fdf792f1b3..3cb50b75087 100644 --- a/extmod/vfs_lfs.h +++ b/extmod/vfs_lfs.h @@ -36,4 +36,31 @@ extern const mp_obj_type_t mp_type_vfs_lfs2; extern const mp_obj_type_t mp_type_vfs_lfs2_fileio; extern const mp_obj_type_t mp_type_vfs_lfs2_textio; +// CIRCUITPY-CHANGE: Export the lfs2 VFS object so the supervisor can mount +// littlefs directly (before the VM and its GC are running) using the same +// layout the VFS methods in vfs_lfsx.c expect. +#if MICROPY_VFS_LFS2 +#include "lib/littlefs/lfs2.h" +#include "extmod/vfs.h" + +typedef struct _mp_obj_vfs_lfs2_t { + mp_obj_base_t base; + mp_vfs_blockdev_t blockdev; + bool enable_mtime; + vstr_t cur_dir; + struct lfs2_config config; + lfs2_t lfs; +} mp_obj_vfs_lfs2_t; + +// Mount (and optionally format first) a littlefs filesystem on the +// caller-prepared lfs2_config at self->config. self must be zeroed static or +// VM-heap storage; buffers are allocated via alloc(). Returns self_in on +// success or MP_OBJ_NULL on mount failure (the errno-like lfs2 return code is +// passed out via mount_err). formatted_out is set to true when a fresh +// filesystem was formatted before mounting successfully; it is never cleared, +// so the caller must initialize it to false (and may set it true itself after +// an explicit format). +mp_obj_t mp_vfs_lfs2_mount_supervisor(mp_obj_vfs_lfs2_t *self, void *(*alloc)(size_t), bool format_allowed, bool *formatted_out, int *mount_err); +#endif + #endif // MICROPY_INCLUDED_EXTMOD_VFS_LFS_H diff --git a/extmod/vfs_lfsx.c b/extmod/vfs_lfsx.c index 19da4417e6d..20a9f5e665a 100644 --- a/extmod/vfs_lfsx.c +++ b/extmod/vfs_lfsx.c @@ -37,6 +37,7 @@ #include "py/objstr.h" #include "py/mperrno.h" #include "extmod/vfs.h" +#include "supervisor/filesystem.h" #include "shared/timeutils/timeutils.h" #if !MICROPY_ENABLE_FINALISER @@ -104,6 +105,12 @@ static void MP_VFS_LFSx(init_config)(MP_OBJ_VFS_LFSx * self, mp_obj_t bdev, size config->read_buffer = m_new(uint8_t, config->cache_size); config->prog_buffer = m_new(uint8_t, config->cache_size); config->lookahead_buffer = m_new(uint8_t, config->lookahead_size); + #ifdef LFS2_MULTIVERSION + // This can be set to override the on-disk lfs version. + // eg. for compat with lfs2 < v2.6 add the following to make: + // CFLAGS += '-DLFS2_MULTIVERSION=0x00020000' + config->disk_version = LFS2_MULTIVERSION; + #endif #endif } @@ -192,7 +199,7 @@ static mp_obj_t MP_VFS_LFSx(ilistdir_it_iternext)(mp_obj_t self_in) { // make 4-tuple with info about this entry mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(4, NULL)); if (self->is_str) { - t->items[0] = mp_obj_new_str(info.name, strlen(info.name)); + t->items[0] = mp_obj_new_str_from_cstr(info.name); } else { t->items[0] = mp_obj_new_bytes((const byte *)info.name, strlen(info.name)); } @@ -238,8 +245,18 @@ static mp_obj_t MP_VFS_LFSx(ilistdir_func)(size_t n_args, const mp_obj_t *args) } static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(MP_VFS_LFSx(ilistdir_obj), 1, 2, MP_VFS_LFSx(ilistdir_func)); +static void MP_VFS_LFSx(verify_fs_writable)(MP_OBJ_VFS_LFSx * self) { + // CIRCUITPY-CHANGE: Honor the supervisor's write protection flags so that + // storage.remount(mount, readonly=True) also applies to littlefs mounts, + // matching what the FAT VFS does. + if (!filesystem_is_writable_by_python((supervisor_vfs_t *)self)) { + mp_raise_OSError(MP_EROFS); + } +} + static mp_obj_t MP_VFS_LFSx(remove)(mp_obj_t self_in, mp_obj_t path_in) { MP_OBJ_VFS_LFSx *self = MP_OBJ_TO_PTR(self_in); + MP_VFS_LFSx(verify_fs_writable)(self); const char *path = MP_VFS_LFSx(make_path)(self, path_in); int ret = LFSx_API(remove)(&self->lfs, path); if (ret < 0) { @@ -251,6 +268,7 @@ static MP_DEFINE_CONST_FUN_OBJ_2(MP_VFS_LFSx(remove_obj), MP_VFS_LFSx(remove)); static mp_obj_t MP_VFS_LFSx(rmdir)(mp_obj_t self_in, mp_obj_t path_in) { MP_OBJ_VFS_LFSx *self = MP_OBJ_TO_PTR(self_in); + MP_VFS_LFSx(verify_fs_writable)(self); const char *path = MP_VFS_LFSx(make_path)(self, path_in); int ret = LFSx_API(remove)(&self->lfs, path); if (ret < 0) { @@ -262,6 +280,7 @@ static MP_DEFINE_CONST_FUN_OBJ_2(MP_VFS_LFSx(rmdir_obj), MP_VFS_LFSx(rmdir)); static mp_obj_t MP_VFS_LFSx(rename)(mp_obj_t self_in, mp_obj_t path_old_in, mp_obj_t path_new_in) { MP_OBJ_VFS_LFSx *self = MP_OBJ_TO_PTR(self_in); + MP_VFS_LFSx(verify_fs_writable)(self); const char *path_old = MP_VFS_LFSx(make_path)(self, path_old_in); const char *path = mp_obj_str_get_str(path_new_in); vstr_t path_new; @@ -281,6 +300,7 @@ static MP_DEFINE_CONST_FUN_OBJ_3(MP_VFS_LFSx(rename_obj), MP_VFS_LFSx(rename)); static mp_obj_t MP_VFS_LFSx(mkdir)(mp_obj_t self_in, mp_obj_t path_o) { MP_OBJ_VFS_LFSx *self = MP_OBJ_TO_PTR(self_in); + MP_VFS_LFSx(verify_fs_writable)(self); const char *path = MP_VFS_LFSx(make_path)(self, path_o); int ret = LFSx_API(mkdir)(&self->lfs, path); if (ret < 0) { @@ -300,7 +320,7 @@ static mp_obj_t MP_VFS_LFSx(chdir)(mp_obj_t self_in, mp_obj_t path_in) { struct LFSx_API (info) info; int ret = LFSx_API(stat)(&self->lfs, path, &info); if (ret < 0 || info.type != LFSx_MACRO(_TYPE_DIR)) { - mp_raise_OSError(-MP_ENOENT); + mp_raise_OSError(MP_ENOENT); } } @@ -378,7 +398,7 @@ static mp_obj_t MP_VFS_LFSx(stat)(mp_obj_t self_in, mp_obj_t path_in) { mp_raise_OSError(-ret); } - mp_uint_t mtime = 0; + mp_timestamp_t mtime = 0; #if LFS_BUILD_VERSION == 2 uint8_t mtime_buf[8]; lfs2_ssize_t sz = lfs2_getattr(&self->lfs, path, LFS_ATTR_MTIME, &mtime_buf, sizeof(mtime_buf)); @@ -400,9 +420,9 @@ static mp_obj_t MP_VFS_LFSx(stat)(mp_obj_t self_in, mp_obj_t path_in) { t->items[4] = MP_OBJ_NEW_SMALL_INT(0); // st_uid t->items[5] = MP_OBJ_NEW_SMALL_INT(0); // st_gid t->items[6] = mp_obj_new_int_from_uint(info.size); // st_size - t->items[7] = mp_obj_new_int_from_uint(mtime); // st_atime - t->items[8] = mp_obj_new_int_from_uint(mtime); // st_mtime - t->items[9] = mp_obj_new_int_from_uint(mtime); // st_ctime + t->items[7] = timeutils_obj_from_timestamp(mtime); // st_atime + t->items[8] = timeutils_obj_from_timestamp(mtime); // st_mtime + t->items[9] = timeutils_obj_from_timestamp(mtime); // st_ctime return MP_OBJ_FROM_PTR(t); } diff --git a/extmod/vfs_lfsx_file.c b/extmod/vfs_lfsx_file.c index ab5cce50088..c72fcf5b59d 100644 --- a/extmod/vfs_lfsx_file.c +++ b/extmod/vfs_lfsx_file.c @@ -89,10 +89,16 @@ mp_obj_t MP_VFS_LFSx(file_open)(mp_obj_t self_in, mp_obj_t path_in, mp_obj_t mod flags = LFSx_MACRO(_O_RDONLY); } + // CIRCUITPY-CHANGE: Writes honor the supervisor's write protection flags, + // like the FAT VFS does, so storage.remount() readonly applies too. + if ((flags & LFSx_MACRO(_O_WRONLY)) != 0) { + MP_VFS_LFSx(verify_fs_writable)(self); + } + #if LFS_BUILD_VERSION == 1 - MP_OBJ_VFS_LFSx_FILE *o = mp_obj_malloc_var_with_finaliser(MP_OBJ_VFS_LFSx_FILE, uint8_t, self->lfs.cfg->prog_size, type); + MP_OBJ_VFS_LFSx_FILE *o = mp_obj_malloc_var_with_finaliser(MP_OBJ_VFS_LFSx_FILE, file_buffer, uint8_t, self->lfs.cfg->prog_size, type); #else - MP_OBJ_VFS_LFSx_FILE *o = mp_obj_malloc_var_with_finaliser(MP_OBJ_VFS_LFSx_FILE, uint8_t, self->lfs.cfg->cache_size, type); + MP_OBJ_VFS_LFSx_FILE *o = mp_obj_malloc_var_with_finaliser(MP_OBJ_VFS_LFSx_FILE, file_buffer, uint8_t, self->lfs.cfg->cache_size, type); #endif o->vfs = self; #if !MICROPY_GC_CONSERVATIVE_CLEAR @@ -152,11 +158,8 @@ static mp_uint_t MP_VFS_LFSx(file_write)(mp_obj_t self_in, const void *buf, mp_u static mp_uint_t MP_VFS_LFSx(file_ioctl)(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) { MP_OBJ_VFS_LFSx_FILE *self = MP_OBJ_TO_PTR(self_in); - if (request != MP_STREAM_CLOSE) { - MP_VFS_LFSx(check_open)(self); - } - if (request == MP_STREAM_SEEK) { + MP_VFS_LFSx(check_open)(self); struct mp_stream_seek_t *s = (struct mp_stream_seek_t *)(uintptr_t)arg; int res = LFSx_API(file_seek)(&self->vfs->lfs, &self->file, s->offset, s->whence); if (res < 0) { @@ -171,6 +174,7 @@ static mp_uint_t MP_VFS_LFSx(file_ioctl)(mp_obj_t self_in, mp_uint_t request, ui s->offset = res; return 0; } else if (request == MP_STREAM_FLUSH) { + MP_VFS_LFSx(check_open)(self); int res = LFSx_API(file_sync)(&self->vfs->lfs, &self->file); if (res < 0) { *errcode = -res; diff --git a/extmod/vfs_posix.c b/extmod/vfs_posix.c index ed4c06e3673..90030db1965 100644 --- a/extmod/vfs_posix.c +++ b/extmod/vfs_posix.c @@ -137,7 +137,7 @@ static mp_obj_t vfs_posix_make_new(const mp_obj_type_t *type, size_t n_args, siz vstr_add_char(&vfs->root, '/'); } vfs->root_len = vfs->root.len; - vfs->readonly = false; + vfs->readonly = !MICROPY_VFS_POSIX_WRITABLE; return MP_OBJ_FROM_PTR(vfs); } @@ -160,10 +160,21 @@ static mp_obj_t vfs_posix_umount(mp_obj_t self_in) { } static MP_DEFINE_CONST_FUN_OBJ_1(vfs_posix_umount_obj, vfs_posix_umount); +static inline bool vfs_posix_is_readonly(mp_obj_vfs_posix_t *self) { + return !MICROPY_VFS_POSIX_WRITABLE || self->readonly; +} + +static void vfs_posix_require_writable(mp_obj_t self_in) { + mp_obj_vfs_posix_t *self = MP_OBJ_TO_PTR(self_in); + if (vfs_posix_is_readonly(self)) { + mp_raise_OSError(MP_EROFS); + } +} + static mp_obj_t vfs_posix_open(mp_obj_t self_in, mp_obj_t path_in, mp_obj_t mode_in) { mp_obj_vfs_posix_t *self = MP_OBJ_TO_PTR(self_in); const char *mode = mp_obj_str_get_str(mode_in); - if (self->readonly + if (vfs_posix_is_readonly(self) && (strchr(mode, 'w') != NULL || strchr(mode, 'a') != NULL || strchr(mode, '+') != NULL)) { mp_raise_OSError(MP_EROFS); } @@ -194,7 +205,7 @@ static mp_obj_t vfs_posix_getcwd(mp_obj_t self_in) { } #endif } - return mp_obj_new_str(ret, strlen(ret)); + return mp_obj_new_str_from_cstr(ret); } static MP_DEFINE_CONST_FUN_OBJ_1(vfs_posix_getcwd_obj, vfs_posix_getcwd); @@ -234,7 +245,7 @@ static mp_obj_t vfs_posix_ilistdir_it_iternext(mp_obj_t self_in) { mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(3, NULL)); if (self->is_str) { - t->items[0] = mp_obj_new_str(fn, strlen(fn)); + t->items[0] = mp_obj_new_str_from_cstr(fn); } else { t->items[0] = mp_obj_new_bytes((const byte *)fn, strlen(fn)); } @@ -303,6 +314,7 @@ typedef struct _mp_obj_listdir_t { } mp_obj_listdir_t; static mp_obj_t vfs_posix_mkdir(mp_obj_t self_in, mp_obj_t path_in) { + vfs_posix_require_writable(self_in); mp_obj_vfs_posix_t *self = MP_OBJ_TO_PTR(self_in); const char *path = vfs_posix_get_path_str(self, path_in); MP_THREAD_GIL_EXIT(); @@ -320,17 +332,23 @@ static mp_obj_t vfs_posix_mkdir(mp_obj_t self_in, mp_obj_t path_in) { static MP_DEFINE_CONST_FUN_OBJ_2(vfs_posix_mkdir_obj, vfs_posix_mkdir); static mp_obj_t vfs_posix_remove(mp_obj_t self_in, mp_obj_t path_in) { + vfs_posix_require_writable(self_in); return vfs_posix_fun1_helper(self_in, path_in, unlink); } static MP_DEFINE_CONST_FUN_OBJ_2(vfs_posix_remove_obj, vfs_posix_remove); static mp_obj_t vfs_posix_rename(mp_obj_t self_in, mp_obj_t old_path_in, mp_obj_t new_path_in) { + vfs_posix_require_writable(self_in); mp_obj_vfs_posix_t *self = MP_OBJ_TO_PTR(self_in); const char *old_path = vfs_posix_get_path_str(self, old_path_in); + size_t old_path_len = strlen(old_path) + 1; + char *old_path_copy = m_new(char, old_path_len); + memcpy(old_path_copy, old_path, old_path_len); const char *new_path = vfs_posix_get_path_str(self, new_path_in); MP_THREAD_GIL_EXIT(); - int ret = rename(old_path, new_path); + int ret = rename(old_path_copy, new_path); MP_THREAD_GIL_ENTER(); + m_del(char, old_path_copy, old_path_len); if (ret != 0) { mp_raise_OSError(errno); } @@ -339,6 +357,7 @@ static mp_obj_t vfs_posix_rename(mp_obj_t self_in, mp_obj_t old_path_in, mp_obj_ static MP_DEFINE_CONST_FUN_OBJ_3(vfs_posix_rename_obj, vfs_posix_rename); static mp_obj_t vfs_posix_rmdir(mp_obj_t self_in, mp_obj_t path_in) { + vfs_posix_require_writable(self_in); return vfs_posix_fun1_helper(self_in, path_in, rmdir); } static MP_DEFINE_CONST_FUN_OBJ_2(vfs_posix_rmdir_obj, vfs_posix_rmdir); diff --git a/extmod/vfs_posix_file.c b/extmod/vfs_posix_file.c index bc06bc74db1..5fe330d7fcf 100644 --- a/extmod/vfs_posix_file.c +++ b/extmod/vfs_posix_file.c @@ -146,12 +146,9 @@ static mp_uint_t vfs_posix_file_write(mp_obj_t o_in, const void *buf, mp_uint_t static mp_uint_t vfs_posix_file_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, int *errcode) { mp_obj_vfs_posix_file_t *o = MP_OBJ_TO_PTR(o_in); - if (request != MP_STREAM_CLOSE) { - check_fd_is_open(o); - } - switch (request) { case MP_STREAM_FLUSH: { + check_fd_is_open(o); int ret; // fsync(stdin/stdout/stderr) may fail with EINVAL (or ENOTSUP on macos or EBADF // on windows), because the OS doesn't buffer these except for instance when they @@ -160,12 +157,27 @@ static mp_uint_t vfs_posix_file_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_ #if defined(__APPLE__) #define VFS_POSIX_STREAM_STDIO_ERR_CATCH (err == EINVAL || err == ENOTSUP) #elif defined(_MSC_VER) + // In debug builds fsync (i.e. _commit on windows) will generate a debug report via _ASSERTE when + // called with non-redirected stdin/stdout/stderr (i.e. _isatty) handles because FlushFileBuffers, + // which it calls internally, will fail since console output is not buffered. + // In release builds it also fails, but merely returns an error which is handled appropriately below. + // The check for the handle being stdin/stdout/stderr is added explicitly because according to + // the documentation _isatty is also true for serial ports for instance. + #ifdef _DEBUG + if ((o->fd == STDIN_FILENO || o->fd == STDOUT_FILENO || o->fd == STDERR_FILENO) && _isatty(o->fd)) { + return 0; + } + #endif #define VFS_POSIX_STREAM_STDIO_ERR_CATCH (err == EINVAL || err == EBADF) #else #define VFS_POSIX_STREAM_STDIO_ERR_CATCH (err == EINVAL) #endif MP_HAL_RETRY_SYSCALL(ret, fsync(o->fd), { if (VFS_POSIX_STREAM_STDIO_ERR_CATCH + // Note: comparing fd against the standard FILENOs is technically not correct, for example: + // sys.stderr.close() in Python code results in close(STDERR_FILENO) here, but because + // open() uses the next available file descriptor, opening an arbitrary file with + // fd = open('/some/file') means that fd becomes STDERR_FILENO. && (o->fd == STDIN_FILENO || o->fd == STDOUT_FILENO || o->fd == STDERR_FILENO)) { return 0; } @@ -175,6 +187,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: { + check_fd_is_open(o); struct mp_stream_seek_t *s = (struct mp_stream_seek_t *)arg; MP_THREAD_GIL_EXIT(); off_t off = lseek(o->fd, s->offset, s->whence); @@ -195,12 +208,14 @@ static mp_uint_t vfs_posix_file_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_ o->fd = -1; return 0; case MP_STREAM_GET_FILENO: + check_fd_is_open(o); return o->fd; #if MICROPY_PY_SELECT && !MICROPY_PY_SELECT_POSIX_OPTIMISATIONS case MP_STREAM_POLL: { #ifdef _WIN32 mp_raise_NotImplementedError(MP_ERROR_TEXT("poll on file not available on win32")); #else + check_fd_is_open(o); mp_uint_t ret = 0; uint8_t pollevents = 0; if (arg & MP_STREAM_POLL_RD) { diff --git a/extmod/vfs_reader.c b/extmod/vfs_reader.c index 80d0fa6344a..cb213acf0b2 100644 --- a/extmod/vfs_reader.c +++ b/extmod/vfs_reader.c @@ -56,6 +56,7 @@ static mp_uint_t mp_reader_vfs_readbyte(void *data) { return MP_READER_EOF; } else { int errcode; + mp_event_handle_nowait(); reader->buflen = mp_stream_rw(reader->file, reader->buf, reader->bufsize, &errcode, MP_STREAM_RW_READ | MP_STREAM_RW_ONCE); if (errcode != 0) { // TODO handle errors properly @@ -83,8 +84,21 @@ void mp_reader_new_file(mp_reader_t *reader, qstr filename) { }; mp_obj_t file = mp_vfs_open(MP_ARRAY_SIZE(args), &args[0], (mp_map_t *)&mp_const_empty_map); - const mp_stream_p_t *stream_p = mp_get_stream(file); + const mp_stream_p_t *stream_p = mp_get_stream_raise(file, MP_STREAM_OP_READ); int errcode = 0; + + // CIRCUITPY-CHANGE: no CircuitPython file object supports the buffer protocol; a mapped + // CIRCUITPY .mpy reaches the ROM loader through storage_map_file_reader() instead. + #if MICROPY_VFS_ROM && !CIRCUITPY_STORAGE_MAP_IMPORT + // Check if the stream can be memory mapped. + mp_buffer_info_t bufinfo; + if (mp_get_buffer(file, &bufinfo, MP_BUFFER_READ)) { + mp_reader_new_mem(reader, bufinfo.buf, bufinfo.len, MP_READER_IS_ROM); + return; + } + #endif + + // Determine how big the input buffer should be, if the stream requests a certain size or not. mp_uint_t bufsize = stream_p->ioctl(file, MP_STREAM_GET_BUFFER_SIZE, 0, &errcode); if (bufsize == MP_STREAM_ERROR || bufsize == 0) { // bufsize == 0 is included here to support mpremote v1.21 and older where mount file ioctl @@ -94,6 +108,7 @@ void mp_reader_new_file(mp_reader_t *reader, qstr filename) { bufsize = MIN(MICROPY_READER_VFS_MAX_BUFFER_SIZE, MAX(MICROPY_READER_VFS_MIN_BUFFER_SIZE, bufsize)); } + // Create the reader. mp_reader_vfs_t *rf = m_new_obj_var(mp_reader_vfs_t, buf, byte, bufsize); rf->file = file; rf->bufsize = bufsize; diff --git a/extmod/vfs_rom.c b/extmod/vfs_rom.c new file mode 100644 index 00000000000..7d814cb9805 --- /dev/null +++ b/extmod/vfs_rom.c @@ -0,0 +1,471 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2022 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. + */ + +// ROMFS filesystem format +// ======================= +// +// ROMFS is a flexible and extensible filesystem format designed to represent a +// directory hierarchy with files, where those files are read-only and their data +// can be memory mapped. +// +// Concepts: +// - varuint: An unsigned integer that is encoded in a variable number of bytes. It is +// stored big-endian with the high bit of the byte set if there are following bytes. +// - record: A variable sized element with a type. It is stored as two varuint's and then +// a payload. The first varuint is the record kind and the second varuint is the +// payload length (which may be zero bytes long). +// +// A ROMFS filesystem is a record with record kind 0x14a6b1, chosen so the encoded value +// is 0xd2-0xcd-0x31 which is "RM1" with the first two bytes having their high bit set. +// If the ROMFS record's payload is non-empty then it contains records. +// +// Record types: +// - 0 = unused, can be used to detect corruption of the filesystem. +// - 1 = padding/comments, can contain any data in their payload. +// - 2 = verbatim data, used to store file data. +// - 3 = indirect data, pointer to offset within the ROMFS payload. +// - 4 = a directory: payload contains a varuint which is the length of the directory +// name in bytes, then the name, then optional nested records for the contents +// of the directory (including optional metadata). +// - 5 = a file: payload contains a varuint which is the length of the filename in bytes +// then the name, then optional nested records. +// +// Remarks: +// - A varuint can be padded if needed by prepending with one or more 0x80 bytes. This +// padding does not change any semantics. +// - The size of the ROMFS record (including kind and length and payload) must be a +// multiple of 2 (because it's not possible to add a padding record of one byte). +// - File data can be optionally aligned using padding records and/or indirect data +// records. +// - There is no limit to the size of directory/file names or file data. +// +// Unknown record types must be skipped over. They may in the future add optional +// features, while still retaining backwards compatibility. Such features may be: +// - Alignment requirements of the ROMFS record. +// - Timestamps on directories/files. +// - A precomputed hash of a file, or other metadata. +// - An optimised lookup table indexing the directory hierarchy. + +#include + +#include "py/bc.h" +#include "py/runtime.h" +#include "py/mperrno.h" +#include "extmod/vfs.h" +#include "extmod/vfs_rom.h" + +#if MICROPY_VFS_ROM + +#define ROMFS_SIZE_MIN (4) +#define ROMFS_HEADER_BYTE0 (0x80 | 'R') +#define ROMFS_HEADER_BYTE1 (0x80 | 'M') +#define ROMFS_HEADER_BYTE2 (0x00 | '1') + +// Values for `record_kind_t`. +#define ROMFS_RECORD_KIND_UNUSED (0) +#define ROMFS_RECORD_KIND_PADDING (1) +#define ROMFS_RECORD_KIND_DATA_VERBATIM (2) +#define ROMFS_RECORD_KIND_DATA_POINTER (3) +#define ROMFS_RECORD_KIND_DIRECTORY (4) +#define ROMFS_RECORD_KIND_FILE (5) +#define ROMFS_RECORD_KIND_FILESYSTEM (0x14a6b1) + +typedef mp_uint_t record_kind_t; + +struct _mp_obj_vfs_rom_t { + mp_obj_base_t base; + mp_obj_t memory; + const uint8_t *filesystem; + const uint8_t *filesystem_end; +}; + +// Returns 0 for success, -1 for failure. +static int mp_decode_uint_checked(const uint8_t **ptr, const uint8_t *ptr_max, mp_uint_t *value_out) { + mp_uint_t unum = 0; + byte val; + const uint8_t *p = *ptr; + do { + if (p >= ptr_max) { + return -1; + } + val = *p++; + unum = (unum << 7) | (val & 0x7f); + } while ((val & 0x80) != 0); + *ptr = p; + *value_out = unum; + return 0; +} + +static record_kind_t extract_record(const uint8_t **fs, const uint8_t **fs_next, const uint8_t *fs_max) { + mp_uint_t record_kind; + if (mp_decode_uint_checked(fs, fs_max, &record_kind) != 0) { + return ROMFS_RECORD_KIND_UNUSED; + } + mp_uint_t record_len; + if (mp_decode_uint_checked(fs, fs_max, &record_len) != 0) { + return ROMFS_RECORD_KIND_UNUSED; + } + *fs_next = *fs + record_len; + return record_kind; +} + +// Returns 0 for success, a negative integer for failure. +static int extract_data(mp_obj_vfs_rom_t *self, const uint8_t *fs, const uint8_t *fs_top, size_t *size_out, const uint8_t **data_out) { + while (fs < fs_top) { + const uint8_t *fs_next; + record_kind_t record_kind = extract_record(&fs, &fs_next, fs_top); + if (record_kind == ROMFS_RECORD_KIND_UNUSED) { + // Corrupt filesystem. + break; + } else if (record_kind == ROMFS_RECORD_KIND_DATA_VERBATIM) { + // Verbatim data. + if (size_out != NULL) { + *size_out = fs_next - fs; + *data_out = fs; + } + return 0; + } else if (record_kind == ROMFS_RECORD_KIND_DATA_POINTER) { + // Pointer to data. + mp_uint_t size; + if (mp_decode_uint_checked(&fs, fs_next, &size) != 0) { + break; + } + mp_uint_t offset; + if (mp_decode_uint_checked(&fs, fs_next, &offset) != 0) { + break; + } + if (size_out != NULL) { + *size_out = size; + *data_out = self->filesystem + offset; + } + return 0; + } else { + // Skip this record. + fs = fs_next; + } + } + return -MP_EIO; +} + +// Searches for `path` in the filesystem. +// `path` must be null-terminated. +mp_import_stat_t mp_vfs_rom_search_filesystem(mp_obj_vfs_rom_t *self, const char *path, size_t *size_out, const uint8_t **data_out) { + const uint8_t *fs = self->filesystem; + const uint8_t *fs_top = self->filesystem_end; + size_t path_len = strlen(path); + if (*path == '/') { + // An optional slash at the start of the path enters the top-level filesystem. + ++path; + --path_len; + } + while (path_len > 0 && fs < fs_top) { + const uint8_t *fs_next; + record_kind_t record_kind = extract_record(&fs, &fs_next, fs_top); + if (record_kind == ROMFS_RECORD_KIND_UNUSED) { + // Corrupt filesystem. + return MP_IMPORT_STAT_NO_EXIST; + } else if (record_kind == ROMFS_RECORD_KIND_DIRECTORY || record_kind == ROMFS_RECORD_KIND_FILE) { + // A directory or file record. + mp_uint_t name_len; + if (mp_decode_uint_checked(&fs, fs_next, &name_len) != 0) { + // Corrupt filesystem. + return MP_IMPORT_STAT_NO_EXIST; + } + if ((name_len == path_len + || (name_len < path_len && path[name_len] == '/')) + && memcmp(path, fs, name_len) == 0) { + // Name matches, so enter this record. + fs += name_len; + fs_top = fs_next; + path += name_len; + path_len -= name_len; + if (record_kind == ROMFS_RECORD_KIND_DIRECTORY) { + // Continue searching in this directory. + if (*path == '/') { + ++path; + --path_len; + } + } else { + // Return this file. + if (path_len != 0) { + return MP_IMPORT_STAT_NO_EXIST; + } + if (extract_data(self, fs, fs_top, size_out, data_out) != 0) { + // Corrupt filesystem. + return MP_IMPORT_STAT_NO_EXIST; + } + return MP_IMPORT_STAT_FILE; + } + } else { + // Skip this directory/file record. + fs = fs_next; + } + } else { + // Skip this record. + fs = fs_next; + } + } + if (path_len == 0) { + if (size_out != NULL) { + *size_out = fs_top - fs; + *data_out = fs; + } + return MP_IMPORT_STAT_DIR; + } + return MP_IMPORT_STAT_NO_EXIST; +} + +static mp_obj_t vfs_rom_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, 1, 1, false); + + mp_obj_vfs_rom_t *self = m_new_obj(mp_obj_vfs_rom_t); + self->base.type = type; + self->memory = args[0]; + + // Get the ROMFS memory region. + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(self->memory, &bufinfo, MP_BUFFER_READ); + if (bufinfo.len < ROMFS_SIZE_MIN) { + mp_raise_OSError(MP_ENODEV); + } + self->filesystem = bufinfo.buf; + + // Verify it is a ROMFS. + if (!(self->filesystem[0] == ROMFS_HEADER_BYTE0 + && self->filesystem[1] == ROMFS_HEADER_BYTE1 + && self->filesystem[2] == ROMFS_HEADER_BYTE2)) { + mp_raise_OSError(MP_ENODEV); + } + + // The ROMFS is a record itself, so enter into it and compute its limit. + record_kind_t record_kind = extract_record(&self->filesystem, &self->filesystem_end, self->filesystem + bufinfo.len); + if (record_kind != ROMFS_RECORD_KIND_FILESYSTEM) { + mp_raise_OSError(MP_ENODEV); + } + + // Check the filesystem is within the limits of the input buffer. + if (self->filesystem_end > (const uint8_t *)bufinfo.buf + bufinfo.len) { + mp_raise_OSError(MP_ENODEV); + } + + return MP_OBJ_FROM_PTR(self); +} + +static mp_obj_t vfs_rom_mount(mp_obj_t self_in, mp_obj_t readonly, mp_obj_t mkfs) { + (void)self_in; + (void)readonly; + if (mp_obj_is_true(mkfs)) { + mp_raise_OSError(MP_EPERM); + } + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_3(vfs_rom_mount_obj, vfs_rom_mount); + +// mp_vfs_rom_file_open is implemented in vfs_rom_file.c. +static MP_DEFINE_CONST_FUN_OBJ_3(vfs_rom_open_obj, mp_vfs_rom_file_open); + +static mp_obj_t vfs_rom_chdir(mp_obj_t self_in, mp_obj_t path_in) { + mp_obj_vfs_rom_t *self = MP_OBJ_TO_PTR(self_in); + const char *path = mp_vfs_rom_get_path_str(self, path_in); + if (path[0] == '/' && path[1] == '\0') { + // Allow chdir to the root of the filesystem. + } else { + // Don't allow chdir to any subdirectory (not currently implemented). + mp_raise_OSError(MP_EOPNOTSUPP); + } + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(vfs_rom_chdir_obj, vfs_rom_chdir); + +static mp_obj_t vfs_rom_getcwd(mp_obj_t self_in) { + (void)self_in; + // The current directory is always the root of the ROMFS. + return MP_OBJ_NEW_QSTR(MP_QSTR_); +} +static MP_DEFINE_CONST_FUN_OBJ_1(vfs_rom_getcwd_obj, vfs_rom_getcwd); + +typedef struct _vfs_rom_ilistdir_it_t { + mp_obj_base_t base; + mp_fun_1_t iternext; + mp_obj_vfs_rom_t *vfs_rom; + bool is_str; + const uint8_t *index; + const uint8_t *index_top; +} vfs_rom_ilistdir_it_t; + +static mp_obj_t vfs_rom_ilistdir_it_iternext(mp_obj_t self_in) { + vfs_rom_ilistdir_it_t *self = MP_OBJ_TO_PTR(self_in); + + while (self->index < self->index_top) { + const uint8_t *index_next; + record_kind_t record_kind = extract_record(&self->index, &index_next, self->index_top); + uint32_t type; + mp_uint_t name_len; + size_t data_len; + if (record_kind == ROMFS_RECORD_KIND_UNUSED) { + // Corrupt filesystem. + self->index = self->index_top; + break; + } else if (record_kind == ROMFS_RECORD_KIND_DIRECTORY || record_kind == ROMFS_RECORD_KIND_FILE) { + // A directory or file record. + if (mp_decode_uint_checked(&self->index, index_next, &name_len) != 0) { + // Corrupt filesystem. + self->index = self->index_top; + break; + } + if (record_kind == ROMFS_RECORD_KIND_DIRECTORY) { + // A directory. + type = MP_S_IFDIR; + data_len = index_next - self->index - name_len; + } else { + // A file. + type = MP_S_IFREG; + const uint8_t *data_value; + if (extract_data(self->vfs_rom, self->index + name_len, index_next, &data_len, &data_value) != 0) { + // Corrupt filesystem. + break; + } + } + } else { + // Skip this record. + self->index = index_next; + continue; + } + + const uint8_t *name_str = self->index; + self->index = index_next; + + // Make 4-tuple with info about this entry: (name, attr, inode, size) + mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(4, NULL)); + + if (self->is_str) { + t->items[0] = mp_obj_new_str((const char *)name_str, name_len); + } else { + t->items[0] = mp_obj_new_bytes(name_str, name_len); + } + + t->items[1] = MP_OBJ_NEW_SMALL_INT(type); + t->items[2] = MP_OBJ_NEW_SMALL_INT(0); + t->items[3] = mp_obj_new_int(data_len); + + return MP_OBJ_FROM_PTR(t); + } + + return MP_OBJ_STOP_ITERATION; +} + +static mp_obj_t vfs_rom_ilistdir(mp_obj_t self_in, mp_obj_t path_in) { + mp_obj_vfs_rom_t *self = MP_OBJ_TO_PTR(self_in); + vfs_rom_ilistdir_it_t *iter = m_new_obj(vfs_rom_ilistdir_it_t); + iter->base.type = &mp_type_polymorph_iter; + iter->iternext = vfs_rom_ilistdir_it_iternext; + iter->vfs_rom = self; + iter->is_str = mp_obj_get_type(path_in) == &mp_type_str; + const char *path = mp_vfs_rom_get_path_str(self, path_in); + size_t size; + if (mp_vfs_rom_search_filesystem(self, path, &size, &iter->index) != MP_IMPORT_STAT_DIR) { + mp_raise_OSError(MP_ENOENT); + } + iter->index_top = iter->index + size; + return MP_OBJ_FROM_PTR(iter); +} +static MP_DEFINE_CONST_FUN_OBJ_2(vfs_rom_ilistdir_obj, vfs_rom_ilistdir); + +static mp_obj_t vfs_rom_stat(mp_obj_t self_in, mp_obj_t path_in) { + mp_obj_vfs_rom_t *self = MP_OBJ_TO_PTR(self_in); + const char *path = mp_vfs_rom_get_path_str(self, path_in); + size_t file_size; + const uint8_t *file_data; + mp_import_stat_t stat = mp_vfs_rom_search_filesystem(self, path, &file_size, &file_data); + if (stat == MP_IMPORT_STAT_NO_EXIST) { + mp_raise_OSError(MP_ENOENT); + } + mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(10, NULL)); + t->items[0] = MP_OBJ_NEW_SMALL_INT(stat == MP_IMPORT_STAT_FILE ? MP_S_IFREG : MP_S_IFDIR); // st_mode + t->items[1] = MP_OBJ_NEW_SMALL_INT(0); // st_ino + t->items[2] = MP_OBJ_NEW_SMALL_INT(0); // st_dev + t->items[3] = MP_OBJ_NEW_SMALL_INT(0); // st_nlink + t->items[4] = MP_OBJ_NEW_SMALL_INT(0); // st_uid + t->items[5] = MP_OBJ_NEW_SMALL_INT(0); // st_gid + t->items[6] = MP_OBJ_NEW_SMALL_INT(file_size); // st_size + t->items[7] = MP_OBJ_NEW_SMALL_INT(0); // st_atime + t->items[8] = MP_OBJ_NEW_SMALL_INT(0); // st_mtime + t->items[9] = MP_OBJ_NEW_SMALL_INT(0); // st_ctime + return MP_OBJ_FROM_PTR(t); +} +static MP_DEFINE_CONST_FUN_OBJ_2(vfs_rom_stat_obj, vfs_rom_stat); + +static mp_obj_t vfs_rom_statvfs(mp_obj_t self_in, mp_obj_t path_in) { + mp_obj_vfs_rom_t *self = MP_OBJ_TO_PTR(self_in); + (void)path_in; + size_t filesystem_len = self->filesystem_end - self->filesystem; + mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(10, NULL)); + t->items[0] = MP_OBJ_NEW_SMALL_INT(1); // f_bsize + t->items[1] = MP_OBJ_NEW_SMALL_INT(0); // f_frsize + t->items[2] = mp_obj_new_int_from_uint(filesystem_len); // f_blocks + t->items[3] = MP_OBJ_NEW_SMALL_INT(0); // f_bfree + t->items[4] = MP_OBJ_NEW_SMALL_INT(0); // f_bavail + t->items[5] = MP_OBJ_NEW_SMALL_INT(0); // f_files + t->items[6] = MP_OBJ_NEW_SMALL_INT(0); // f_ffree + t->items[7] = MP_OBJ_NEW_SMALL_INT(0); // f_favail + t->items[8] = MP_OBJ_NEW_SMALL_INT(0); // f_flags + t->items[9] = MP_OBJ_NEW_SMALL_INT(32767); // f_namemax + return MP_OBJ_FROM_PTR(t); +} +static MP_DEFINE_CONST_FUN_OBJ_2(vfs_rom_statvfs_obj, vfs_rom_statvfs); + +static const mp_rom_map_elem_t vfs_rom_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_mount), MP_ROM_PTR(&vfs_rom_mount_obj) }, + { MP_ROM_QSTR(MP_QSTR_umount), MP_ROM_PTR(&mp_identity_obj) }, + { MP_ROM_QSTR(MP_QSTR_open), MP_ROM_PTR(&vfs_rom_open_obj) }, + + { MP_ROM_QSTR(MP_QSTR_chdir), MP_ROM_PTR(&vfs_rom_chdir_obj) }, + { MP_ROM_QSTR(MP_QSTR_getcwd), MP_ROM_PTR(&vfs_rom_getcwd_obj) }, + { MP_ROM_QSTR(MP_QSTR_ilistdir), MP_ROM_PTR(&vfs_rom_ilistdir_obj) }, + { MP_ROM_QSTR(MP_QSTR_stat), MP_ROM_PTR(&vfs_rom_stat_obj) }, + { MP_ROM_QSTR(MP_QSTR_statvfs), MP_ROM_PTR(&vfs_rom_statvfs_obj) }, +}; +static MP_DEFINE_CONST_DICT(vfs_rom_locals_dict, vfs_rom_locals_dict_table); + +static mp_import_stat_t mp_vfs_rom_import_stat(void *self_in, const char *path) { + mp_obj_vfs_rom_t *self = MP_OBJ_TO_PTR(self_in); + return mp_vfs_rom_search_filesystem(self, path, NULL, NULL); +} + +static const mp_vfs_proto_t vfs_rom_proto = { + .import_stat = mp_vfs_rom_import_stat, +}; + +MP_DEFINE_CONST_OBJ_TYPE( + mp_type_vfs_rom, + MP_QSTR_VfsRom, + MP_TYPE_FLAG_NONE, + make_new, vfs_rom_make_new, + protocol, &vfs_rom_proto, + locals_dict, &vfs_rom_locals_dict + ); + +#endif // MICROPY_VFS_ROM diff --git a/extmod/vfs_rom.h b/extmod/vfs_rom.h new file mode 100644 index 00000000000..d8e2b911ba0 --- /dev/null +++ b/extmod/vfs_rom.h @@ -0,0 +1,47 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2022 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. + */ +#ifndef MICROPY_INCLUDED_EXTMOD_VFS_ROM_H +#define MICROPY_INCLUDED_EXTMOD_VFS_ROM_H + +#include "py/builtin.h" +#include "py/obj.h" + +#if MICROPY_VFS_ROM + +typedef struct _mp_obj_vfs_rom_t mp_obj_vfs_rom_t; + +extern const mp_obj_type_t mp_type_vfs_rom; + +static inline const char *mp_vfs_rom_get_path_str(mp_obj_vfs_rom_t *self, mp_obj_t path) { + return mp_obj_str_get_str(path); +} + +mp_import_stat_t mp_vfs_rom_search_filesystem(mp_obj_vfs_rom_t *self, const char *path, size_t *size_out, const uint8_t **data_out); +mp_obj_t mp_vfs_rom_file_open(mp_obj_t self_in, mp_obj_t path_in, mp_obj_t mode_in); + +#endif // MICROPY_VFS_ROM + +#endif // MICROPY_INCLUDED_EXTMOD_VFS_ROM_H diff --git a/extmod/vfs_rom_file.c b/extmod/vfs_rom_file.c new file mode 100644 index 00000000000..6d7c47111f5 --- /dev/null +++ b/extmod/vfs_rom_file.c @@ -0,0 +1,180 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2022 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 + +#include "py/reader.h" +#include "py/runtime.h" +#include "py/stream.h" +#include "extmod/vfs_rom.h" + +#if MICROPY_VFS_ROM + +typedef struct _mp_obj_vfs_rom_file_t { + mp_obj_base_t base; + size_t file_size; + size_t file_offset; + const uint8_t *file_data; +} mp_obj_vfs_rom_file_t; + +static const mp_obj_type_t mp_type_vfs_rom_fileio; +static const mp_obj_type_t mp_type_vfs_rom_textio; + +mp_obj_t mp_vfs_rom_file_open(mp_obj_t self_in, mp_obj_t path_in, mp_obj_t mode_in) { + mp_obj_vfs_rom_t *self = MP_OBJ_TO_PTR(self_in); + + const char *mode_s = mp_obj_str_get_str(mode_in); + const mp_obj_type_t *type = &mp_type_vfs_rom_textio; + while (*mode_s) { + switch (*mode_s++) { + case 'r': + break; + case 'w': + case 'a': + case '+': + mp_raise_OSError(MP_EROFS); + case 'b': + type = &mp_type_vfs_rom_fileio; + break; + case 't': + type = &mp_type_vfs_rom_textio; + break; + } + } + + mp_obj_vfs_rom_file_t *o = m_new_obj(mp_obj_vfs_rom_file_t); + o->base.type = type; + o->file_offset = 0; + + const char *path = mp_vfs_rom_get_path_str(self, path_in); + mp_import_stat_t stat = mp_vfs_rom_search_filesystem(self, path, &o->file_size, &o->file_data); + if (stat == MP_IMPORT_STAT_NO_EXIST) { + mp_raise_OSError(MP_ENOENT); + } else if (stat == MP_IMPORT_STAT_DIR) { + mp_raise_OSError(MP_EISDIR); + } + + return MP_OBJ_FROM_PTR(o); +} + +static mp_int_t vfs_rom_file_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags) { + mp_obj_vfs_rom_file_t *self = MP_OBJ_TO_PTR(self_in); + if (flags == MP_BUFFER_READ) { + bufinfo->buf = (void *)self->file_data; + bufinfo->len = self->file_size; + bufinfo->typecode = 'B'; + return 0; + } else { + // Can't write to a ROM file. + return 1; + } +} + +static mp_uint_t vfs_rom_file_read(mp_obj_t o_in, void *buf, mp_uint_t size, int *errcode) { + mp_obj_vfs_rom_file_t *self = MP_OBJ_TO_PTR(o_in); + size_t remain = self->file_size - self->file_offset; + if (size > remain) { + size = remain; + } + memcpy(buf, self->file_data + self->file_offset, size); + self->file_offset += size; + return size; +} + +static mp_uint_t vfs_rom_file_ioctl(mp_obj_t o_in, mp_uint_t request, uintptr_t arg, int *errcode) { + mp_obj_vfs_rom_file_t *self = MP_OBJ_TO_PTR(o_in); + + switch (request) { + case MP_STREAM_SEEK: { + struct mp_stream_seek_t *s = (struct mp_stream_seek_t *)arg; + if (s->whence == MP_SEEK_SET) { + self->file_offset = (size_t)s->offset; + } else if (s->whence == MP_SEEK_CUR) { + self->file_offset += s->offset; + } else { // MP_SEEK_END + self->file_offset = self->file_size + s->offset; + } + if (self->file_offset > self->file_size) { + if (s->offset < 0) { + // Seek to before the start of the file. + *errcode = MP_EINVAL; + return MP_STREAM_ERROR; + } + self->file_offset = self->file_size; + } + s->offset = self->file_offset; + return 0; + } + case MP_STREAM_CLOSE: + return 0; + default: + *errcode = MP_EINVAL; + return MP_STREAM_ERROR; + } +} + +static const mp_rom_map_elem_t vfs_rom_rawfile_locals_dict_table[] = { + { 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_readlines), MP_ROM_PTR(&mp_stream_unbuffered_readlines_obj) }, + { MP_ROM_QSTR(MP_QSTR_seek), MP_ROM_PTR(&mp_stream_seek_obj) }, + { MP_ROM_QSTR(MP_QSTR_tell), MP_ROM_PTR(&mp_stream_tell_obj) }, + { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_stream_close_obj) }, + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&mp_identity_obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&mp_stream___exit___obj) }, +}; +static MP_DEFINE_CONST_DICT(vfs_rom_rawfile_locals_dict, vfs_rom_rawfile_locals_dict_table); + +static const mp_stream_p_t vfs_rom_fileio_stream_p = { + .read = vfs_rom_file_read, + .ioctl = vfs_rom_file_ioctl, +}; + +static MP_DEFINE_CONST_OBJ_TYPE( + mp_type_vfs_rom_fileio, + MP_QSTR_FileIO, + MP_TYPE_FLAG_ITER_IS_STREAM, + buffer, vfs_rom_file_get_buffer, + protocol, &vfs_rom_fileio_stream_p, + locals_dict, &vfs_rom_rawfile_locals_dict + ); + +static const mp_stream_p_t vfs_rom_textio_stream_p = { + .read = vfs_rom_file_read, + .ioctl = vfs_rom_file_ioctl, + .is_text = true, +}; + +static MP_DEFINE_CONST_OBJ_TYPE( + mp_type_vfs_rom_textio, + MP_QSTR_TextIOWrapper, + MP_TYPE_FLAG_ITER_IS_STREAM, + protocol, &vfs_rom_textio_stream_p, + locals_dict, &vfs_rom_rawfile_locals_dict + ); + +#endif // MICROPY_VFS_ROM diff --git a/extmod/virtpin.c b/extmod/virtpin.c deleted file mode 100644 index cd0b9f92f83..00000000000 --- a/extmod/virtpin.c +++ /dev/null @@ -1,39 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2016 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 - * 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 "extmod/virtpin.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_pin_p_t *pin_p = (mp_pin_p_t *)MP_OBJ_TYPE_GET_SLOT(s->type, protocol); - 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_pin_p_t *pin_p = (mp_pin_p_t *)MP_OBJ_TYPE_GET_SLOT(s->type, protocol); - pin_p->ioctl(pin, MP_PIN_WRITE, value, NULL); -} diff --git a/extmod/virtpin.h b/extmod/virtpin.h deleted file mode 100644 index 81094f21cf1..00000000000 --- a/extmod/virtpin.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2016 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 - * 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_EXTMOD_VIRTPIN_H -#define MICROPY_INCLUDED_EXTMOD_VIRTPIN_H - -#include "py/obj.h" -// CIRCUITPY-CHANGE -#include "py/proto.h" - -#define MP_PIN_READ (1) -#define MP_PIN_WRITE (2) -#define MP_PIN_INPUT (3) -#define MP_PIN_OUTPUT (4) - -// Pin protocol -typedef struct _mp_pin_p_t { - // CIRCUITPY-CHANGE - MP_PROTOCOL_HEAD - mp_uint_t (*ioctl)(mp_obj_t obj, mp_uint_t request, uintptr_t arg, int *errcode); -} mp_pin_p_t; - -int mp_virtual_pin_read(mp_obj_t pin); -void mp_virtual_pin_write(mp_obj_t pin, int value); - -// If a port exposes a Pin object, it's constructor should be like this -mp_obj_t mp_pin_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args); - -#endif // MICROPY_INCLUDED_EXTMOD_VIRTPIN_H diff --git a/frozen/Adafruit_CircuitPython_AHTx0 b/frozen/Adafruit_CircuitPython_AHTx0 index 8d602419432..3dd249f5695 160000 --- a/frozen/Adafruit_CircuitPython_AHTx0 +++ b/frozen/Adafruit_CircuitPython_AHTx0 @@ -1 +1 @@ -Subproject commit 8d602419432e65a3833a6b1a1de5e11aad3812ae +Subproject commit 3dd249f56957d1927dee6e6e31742039c6699cef diff --git a/frozen/Adafruit_CircuitPython_APDS9960 b/frozen/Adafruit_CircuitPython_APDS9960 index 863d6ac6141..75a7b1abef0 160000 --- a/frozen/Adafruit_CircuitPython_APDS9960 +++ b/frozen/Adafruit_CircuitPython_APDS9960 @@ -1 +1 @@ -Subproject commit 863d6ac6141c94a8da15b92d377ff4dce247e204 +Subproject commit 75a7b1abef02342a7cdead30271ce168243bf1fa diff --git a/frozen/Adafruit_CircuitPython_BLE b/frozen/Adafruit_CircuitPython_BLE index ed26cc119f0..11bf2f7b3eb 160000 --- a/frozen/Adafruit_CircuitPython_BLE +++ b/frozen/Adafruit_CircuitPython_BLE @@ -1 +1 @@ -Subproject commit ed26cc119f05a30b1d4afcf293362cbda2662809 +Subproject commit 11bf2f7b3eb278e094121954d39cc1f8e58d7d12 diff --git a/frozen/Adafruit_CircuitPython_BLE_Apple_Notification_Center b/frozen/Adafruit_CircuitPython_BLE_Apple_Notification_Center index 36b72bbebae..7c081325944 160000 --- a/frozen/Adafruit_CircuitPython_BLE_Apple_Notification_Center +++ b/frozen/Adafruit_CircuitPython_BLE_Apple_Notification_Center @@ -1 +1 @@ -Subproject commit 36b72bbebae3b8a9949d2f824747b44723164b83 +Subproject commit 7c08132594453a021812f45e86a2972d6945672e diff --git a/frozen/Adafruit_CircuitPython_BLE_File_Transfer b/frozen/Adafruit_CircuitPython_BLE_File_Transfer new file mode 160000 index 00000000000..14c0870bc91 --- /dev/null +++ b/frozen/Adafruit_CircuitPython_BLE_File_Transfer @@ -0,0 +1 @@ +Subproject commit 14c0870bc915aba90cf6e8a4002adeb563bc95fe diff --git a/frozen/Adafruit_CircuitPython_Bitmap_Font b/frozen/Adafruit_CircuitPython_Bitmap_Font index 51b4032f680..040e2b26851 160000 --- a/frozen/Adafruit_CircuitPython_Bitmap_Font +++ b/frozen/Adafruit_CircuitPython_Bitmap_Font @@ -1 +1 @@ -Subproject commit 51b4032f6809e5b4177d95ef5d70520352081eb8 +Subproject commit 040e2b26851facaae06e48b568ddc6fcf226bd32 diff --git a/frozen/Adafruit_CircuitPython_BusDevice b/frozen/Adafruit_CircuitPython_BusDevice index 87dd7ca81e2..686728c7b11 160000 --- a/frozen/Adafruit_CircuitPython_BusDevice +++ b/frozen/Adafruit_CircuitPython_BusDevice @@ -1 +1 @@ -Subproject commit 87dd7ca81e2ed335077dde4a4d0c24bf4f2f059f +Subproject commit 686728c7b11eb0b7ffb62691b68ccead413e7cc5 diff --git a/frozen/Adafruit_CircuitPython_CS42L42 b/frozen/Adafruit_CircuitPython_CS42L42 new file mode 160000 index 00000000000..d254bbaf680 --- /dev/null +++ b/frozen/Adafruit_CircuitPython_CS42L42 @@ -0,0 +1 @@ +Subproject commit d254bbaf680c835896165ad2a28bd0216fa0ab42 diff --git a/frozen/Adafruit_CircuitPython_CircuitPlayground b/frozen/Adafruit_CircuitPython_CircuitPlayground index f4ee2000d0b..852e7206e5e 160000 --- a/frozen/Adafruit_CircuitPython_CircuitPlayground +++ b/frozen/Adafruit_CircuitPython_CircuitPlayground @@ -1 +1 @@ -Subproject commit f4ee2000d0b3e036cf437c5879349cbc9bc2849f +Subproject commit 852e7206e5ed26ec3929a25bc8331b0951fee20e diff --git a/frozen/Adafruit_CircuitPython_ConnectionManager b/frozen/Adafruit_CircuitPython_ConnectionManager index 42073559468..69542345f3d 160000 --- a/frozen/Adafruit_CircuitPython_ConnectionManager +++ b/frozen/Adafruit_CircuitPython_ConnectionManager @@ -1 +1 @@ -Subproject commit 42073559468d0c8af9bb1fe5e06fccd4d1d9a845 +Subproject commit 69542345f3dc6f9060eb5d78d5dcd4e636bf66b9 diff --git a/frozen/Adafruit_CircuitPython_Crickit b/frozen/Adafruit_CircuitPython_Crickit index 240deb5f0a5..aa213ba6f89 160000 --- a/frozen/Adafruit_CircuitPython_Crickit +++ b/frozen/Adafruit_CircuitPython_Crickit @@ -1 +1 @@ -Subproject commit 240deb5f0a5261c4cd469c66efd9336702aeaea0 +Subproject commit aa213ba6f897cdeb45ce4e961f44f862e3832c03 diff --git a/frozen/Adafruit_CircuitPython_DRV2605 b/frozen/Adafruit_CircuitPython_DRV2605 index 7a1f56f5de8..2b8443ff94a 160000 --- a/frozen/Adafruit_CircuitPython_DRV2605 +++ b/frozen/Adafruit_CircuitPython_DRV2605 @@ -1 +1 @@ -Subproject commit 7a1f56f5de85d4ef9878bb8dff15c284da131516 +Subproject commit 2b8443ff94a179a027efd9f62d905c398f4f7b43 diff --git a/frozen/Adafruit_CircuitPython_DS3231 b/frozen/Adafruit_CircuitPython_DS3231 index 30e89dca4cd..5dc331cd999 160000 --- a/frozen/Adafruit_CircuitPython_DS3231 +++ b/frozen/Adafruit_CircuitPython_DS3231 @@ -1 +1 @@ -Subproject commit 30e89dca4cd4b9ca5252ee3c3560e85d07a31b12 +Subproject commit 5dc331cd99930dd209c63f77256764c2b41016f2 diff --git a/frozen/Adafruit_CircuitPython_DisplayIO_SSD1306 b/frozen/Adafruit_CircuitPython_DisplayIO_SSD1306 index 3d752eca151..45520b642df 160000 --- a/frozen/Adafruit_CircuitPython_DisplayIO_SSD1306 +++ b/frozen/Adafruit_CircuitPython_DisplayIO_SSD1306 @@ -1 +1 @@ -Subproject commit 3d752eca15104a952fa862c1d8babce3959f10fa +Subproject commit 45520b642df77b1718befb24e5e6853b1172792f diff --git a/frozen/Adafruit_CircuitPython_Display_Shapes b/frozen/Adafruit_CircuitPython_Display_Shapes index 95f0ab08e32..7f0466c1d3a 160000 --- a/frozen/Adafruit_CircuitPython_Display_Shapes +++ b/frozen/Adafruit_CircuitPython_Display_Shapes @@ -1 +1 @@ -Subproject commit 95f0ab08e328ab1170f9e3a3049e75b86ba3cd18 +Subproject commit 7f0466c1d3ac344bb8ef282d09c5eb8c1a521d72 diff --git a/frozen/Adafruit_CircuitPython_Display_Text b/frozen/Adafruit_CircuitPython_Display_Text index 46340b3772b..b368c38fc2c 160000 --- a/frozen/Adafruit_CircuitPython_Display_Text +++ b/frozen/Adafruit_CircuitPython_Display_Text @@ -1 +1 @@ -Subproject commit 46340b3772b03a2acc584cbcb30ad801c902dc42 +Subproject commit b368c38fc2c520557adacd2623f8359d5bf6618d diff --git a/frozen/Adafruit_CircuitPython_DotStar b/frozen/Adafruit_CircuitPython_DotStar index d422769a2b2..d08e231d5f9 160000 --- a/frozen/Adafruit_CircuitPython_DotStar +++ b/frozen/Adafruit_CircuitPython_DotStar @@ -1 +1 @@ -Subproject commit d422769a2b2e086c491a9163ed7ddbf967b79abd +Subproject commit d08e231d5f95566a09f2a0c08cb647703882262d diff --git a/frozen/Adafruit_CircuitPython_ESP32SPI b/frozen/Adafruit_CircuitPython_ESP32SPI index 2ddf9fa4e62..0da9c2e02ab 160000 --- a/frozen/Adafruit_CircuitPython_ESP32SPI +++ b/frozen/Adafruit_CircuitPython_ESP32SPI @@ -1 +1 @@ -Subproject commit 2ddf9fa4e629478188f5e21f1ed580b7bbf0ff04 +Subproject commit 0da9c2e02ab77a85617550f4bdbeb3559d4edf4b diff --git a/frozen/Adafruit_CircuitPython_FakeRequests b/frozen/Adafruit_CircuitPython_FakeRequests index 897f5e10417..130a3d7fcfb 160000 --- a/frozen/Adafruit_CircuitPython_FakeRequests +++ b/frozen/Adafruit_CircuitPython_FakeRequests @@ -1 +1 @@ -Subproject commit 897f5e1041757dc796de4ded074fcbef3677313f +Subproject commit 130a3d7fcfbba67bb86232f22ca08ba862873947 diff --git a/frozen/Adafruit_CircuitPython_FocalTouch b/frozen/Adafruit_CircuitPython_FocalTouch index 1444d0dd975..2070d7853cd 160000 --- a/frozen/Adafruit_CircuitPython_FocalTouch +++ b/frozen/Adafruit_CircuitPython_FocalTouch @@ -1 +1 @@ -Subproject commit 1444d0dd9758effd246fc41f58960cee9d94d565 +Subproject commit 2070d7853cd1fe81381e02f4bc0af1bb145cb69e diff --git a/frozen/Adafruit_CircuitPython_HID b/frozen/Adafruit_CircuitPython_HID index d26db6955ae..693baa60eb6 160000 --- a/frozen/Adafruit_CircuitPython_HID +++ b/frozen/Adafruit_CircuitPython_HID @@ -1 +1 @@ -Subproject commit d26db6955aeb556611377a5433a15b7cbeafe1c9 +Subproject commit 693baa60eb684bb53379d98c6a036f56b8010666 diff --git a/frozen/Adafruit_CircuitPython_HTTPServer b/frozen/Adafruit_CircuitPython_HTTPServer index 09e5431071d..c1d964fe7bf 160000 --- a/frozen/Adafruit_CircuitPython_HTTPServer +++ b/frozen/Adafruit_CircuitPython_HTTPServer @@ -1 +1 @@ -Subproject commit 09e5431071d9e484726df87841a5b9bbe33b6d76 +Subproject commit c1d964fe7bf8734f7a858e798583d0f1304ae1c1 diff --git a/frozen/Adafruit_CircuitPython_IRRemote b/frozen/Adafruit_CircuitPython_IRRemote index d3d8d7396d9..bb14c81e07a 160000 --- a/frozen/Adafruit_CircuitPython_IRRemote +++ b/frozen/Adafruit_CircuitPython_IRRemote @@ -1 +1 @@ -Subproject commit d3d8d7396d9db5ccb4967ab171a2275eccadcfb4 +Subproject commit bb14c81e07aa798b36a53923059b5ab8a914915b diff --git a/frozen/Adafruit_CircuitPython_IS31FL3731 b/frozen/Adafruit_CircuitPython_IS31FL3731 index 0cd04eb83ed..3becc08e451 160000 --- a/frozen/Adafruit_CircuitPython_IS31FL3731 +++ b/frozen/Adafruit_CircuitPython_IS31FL3731 @@ -1 +1 @@ -Subproject commit 0cd04eb83ed210b9f565c204f3cff685781702f5 +Subproject commit 3becc08e451eeb2b6678a3d17547f5b0922e4660 diff --git a/frozen/Adafruit_CircuitPython_ImageLoad b/frozen/Adafruit_CircuitPython_ImageLoad index b9eb5660084..11855997455 160000 --- a/frozen/Adafruit_CircuitPython_ImageLoad +++ b/frozen/Adafruit_CircuitPython_ImageLoad @@ -1 +1 @@ -Subproject commit b9eb566008491e08433ac7213c310aab5e49e410 +Subproject commit 11855997455465bc93670e2a3f92e73bc9f7caee diff --git a/frozen/Adafruit_CircuitPython_LC709203F b/frozen/Adafruit_CircuitPython_LC709203F index 61716f6e30c..bcbb0cfead8 160000 --- a/frozen/Adafruit_CircuitPython_LC709203F +++ b/frozen/Adafruit_CircuitPython_LC709203F @@ -1 +1 @@ -Subproject commit 61716f6e30c37a97c9d22ce7e5463e007a4e6471 +Subproject commit bcbb0cfead8650a61357a167bc47058f05fba159 diff --git a/frozen/Adafruit_CircuitPython_LED_Animation b/frozen/Adafruit_CircuitPython_LED_Animation index 83b87ef8673..38a3c7844b4 160000 --- a/frozen/Adafruit_CircuitPython_LED_Animation +++ b/frozen/Adafruit_CircuitPython_LED_Animation @@ -1 +1 @@ -Subproject commit 83b87ef8673c8b33bf7e57b0c2ab49ff9e310df6 +Subproject commit 38a3c7844b4c59235fac46ee01e20caf872dad43 diff --git a/frozen/Adafruit_CircuitPython_LIS3DH b/frozen/Adafruit_CircuitPython_LIS3DH index 60f2706f592..cd40b482a09 160000 --- a/frozen/Adafruit_CircuitPython_LIS3DH +++ b/frozen/Adafruit_CircuitPython_LIS3DH @@ -1 +1 @@ -Subproject commit 60f2706f592da44ae1f773d5c680a92b79a8c837 +Subproject commit cd40b482a098a62ecce1b4c62a1f1930be984e16 diff --git a/frozen/Adafruit_CircuitPython_LSM6DS b/frozen/Adafruit_CircuitPython_LSM6DS index 0aefcb69b26..cdfc14a687a 160000 --- a/frozen/Adafruit_CircuitPython_LSM6DS +++ b/frozen/Adafruit_CircuitPython_LSM6DS @@ -1 +1 @@ -Subproject commit 0aefcb69b26b72e2b46c81651f2ae1731da311a9 +Subproject commit cdfc14a687a138aa0f2c6abab061bfc1bfafa561 diff --git a/frozen/Adafruit_CircuitPython_MIDI b/frozen/Adafruit_CircuitPython_MIDI index 5d496cb671d..6f5d6812474 160000 --- a/frozen/Adafruit_CircuitPython_MIDI +++ b/frozen/Adafruit_CircuitPython_MIDI @@ -1 +1 @@ -Subproject commit 5d496cb671d592ef7a3e0e2ec9d46e4c90ff9c9a +Subproject commit 6f5d6812474a0460e9418278ea7da1e2269d2c0d diff --git a/frozen/Adafruit_CircuitPython_MPU6050 b/frozen/Adafruit_CircuitPython_MPU6050 index b3cd655c924..b049c0a1353 160000 --- a/frozen/Adafruit_CircuitPython_MPU6050 +++ b/frozen/Adafruit_CircuitPython_MPU6050 @@ -1 +1 @@ -Subproject commit b3cd655c9242e0eab79a5b35c98e7474e2b29145 +Subproject commit b049c0a1353dccbde9e464c498b0bb1da6c38e4f diff --git a/frozen/Adafruit_CircuitPython_Motor b/frozen/Adafruit_CircuitPython_Motor index c49ae717480..dc0c88c1d7c 160000 --- a/frozen/Adafruit_CircuitPython_Motor +++ b/frozen/Adafruit_CircuitPython_Motor @@ -1 +1 @@ -Subproject commit c49ae717480b9fb6b9e551666bf51878d4f8253e +Subproject commit dc0c88c1d7ca386a434d17c65a1e5efa5fc31a5f diff --git a/frozen/Adafruit_CircuitPython_NeoPixel b/frozen/Adafruit_CircuitPython_NeoPixel index 37ff533cb42..aa82c0724cc 160000 --- a/frozen/Adafruit_CircuitPython_NeoPixel +++ b/frozen/Adafruit_CircuitPython_NeoPixel @@ -1 +1 @@ -Subproject commit 37ff533cb427c0e20c1b7a9b7ae493c8fae6d7a3 +Subproject commit aa82c0724ccb68fbd94605c9f4f09b19c5d2919d diff --git a/frozen/Adafruit_CircuitPython_OPT4048 b/frozen/Adafruit_CircuitPython_OPT4048 new file mode 160000 index 00000000000..97e63d8cd24 --- /dev/null +++ b/frozen/Adafruit_CircuitPython_OPT4048 @@ -0,0 +1 @@ +Subproject commit 97e63d8cd2425248c0aee323c3d8a6422404eaa5 diff --git a/frozen/Adafruit_CircuitPython_PCF8563 b/frozen/Adafruit_CircuitPython_PCF8563 index 36e62a96602..c4ca8d355b7 160000 --- a/frozen/Adafruit_CircuitPython_PCF8563 +++ b/frozen/Adafruit_CircuitPython_PCF8563 @@ -1 +1 @@ -Subproject commit 36e62a966026e7dbbf695c5d727e273ae73bc126 +Subproject commit c4ca8d355b79179b44716544577925442a801bc0 diff --git a/frozen/Adafruit_CircuitPython_Pixel_Framebuf b/frozen/Adafruit_CircuitPython_Pixel_Framebuf index 2074f9e18bd..ffd3e8a6926 160000 --- a/frozen/Adafruit_CircuitPython_Pixel_Framebuf +++ b/frozen/Adafruit_CircuitPython_Pixel_Framebuf @@ -1 +1 @@ -Subproject commit 2074f9e18bd6a3d1719a28aed10f5edaa80f38af +Subproject commit ffd3e8a692676d076a2fa3f725e3a8ea63441139 diff --git a/frozen/Adafruit_CircuitPython_PortalBase b/frozen/Adafruit_CircuitPython_PortalBase index 53c1666ee15..d39c3d6b205 160000 --- a/frozen/Adafruit_CircuitPython_PortalBase +++ b/frozen/Adafruit_CircuitPython_PortalBase @@ -1 +1 @@ -Subproject commit 53c1666ee15d1d811226a1fee79e4fd890936f42 +Subproject commit d39c3d6b2053a64ab67be668d778751a523a2cd6 diff --git a/frozen/Adafruit_CircuitPython_ProgressBar b/frozen/Adafruit_CircuitPython_ProgressBar index 283822cd1a1..e720f6ff61a 160000 --- a/frozen/Adafruit_CircuitPython_ProgressBar +++ b/frozen/Adafruit_CircuitPython_ProgressBar @@ -1 +1 @@ -Subproject commit 283822cd1a1c43031a460405d1f46be3d04ee28c +Subproject commit e720f6ff61aa41485a5611d8df3f7fa25fe8fb79 diff --git a/frozen/Adafruit_CircuitPython_RFM69 b/frozen/Adafruit_CircuitPython_RFM69 index 04f21dbcf96..2f8a38c3cae 160000 --- a/frozen/Adafruit_CircuitPython_RFM69 +++ b/frozen/Adafruit_CircuitPython_RFM69 @@ -1 +1 @@ -Subproject commit 04f21dbcf96a646cb0b8e1d700c614eb7ab82156 +Subproject commit 2f8a38c3cae772aa73216499dd40fde695878566 diff --git a/frozen/Adafruit_CircuitPython_RFM9x b/frozen/Adafruit_CircuitPython_RFM9x index 66e045343e7..b2a843ddff2 160000 --- a/frozen/Adafruit_CircuitPython_RFM9x +++ b/frozen/Adafruit_CircuitPython_RFM9x @@ -1 +1 @@ -Subproject commit 66e045343e7aaa4006a981912045638a84c18a9f +Subproject commit b2a843ddff22cec5a2b6ee79ba0c52e17cbf9dd2 diff --git a/frozen/Adafruit_CircuitPython_Register b/frozen/Adafruit_CircuitPython_Register index 8bdf5dcb324..04051d28e3e 160000 --- a/frozen/Adafruit_CircuitPython_Register +++ b/frozen/Adafruit_CircuitPython_Register @@ -1 +1 @@ -Subproject commit 8bdf5dcb3244890edeb9aa662f18d447634539ec +Subproject commit 04051d28e3eceb13d2705471f67810641121f52d diff --git a/frozen/Adafruit_CircuitPython_Requests b/frozen/Adafruit_CircuitPython_Requests index 6c33451d4f4..d01449ee9a1 160000 --- a/frozen/Adafruit_CircuitPython_Requests +++ b/frozen/Adafruit_CircuitPython_Requests @@ -1 +1 @@ -Subproject commit 6c33451d4f4097f069862ba2c19236e8197d9eaf +Subproject commit d01449ee9a1ba161d1e2290911cf4b65997ebc10 diff --git a/frozen/Adafruit_CircuitPython_SD b/frozen/Adafruit_CircuitPython_SD index 988199f3881..e85d264ad6e 160000 --- a/frozen/Adafruit_CircuitPython_SD +++ b/frozen/Adafruit_CircuitPython_SD @@ -1 +1 @@ -Subproject commit 988199f38810f1741defa87793f94d6980e701f3 +Subproject commit e85d264ad6eaa286333fd3dbbf7a95b9ea7f0af3 diff --git a/frozen/Adafruit_CircuitPython_SHT4x b/frozen/Adafruit_CircuitPython_SHT4x index 7c209601e33..c29695027b1 160000 --- a/frozen/Adafruit_CircuitPython_SHT4x +++ b/frozen/Adafruit_CircuitPython_SHT4x @@ -1 +1 @@ -Subproject commit 7c209601e3341639e3265a5b0a5a6c8fdc3716ea +Subproject commit c29695027b1d5f5140b570f31c91ace373f45843 diff --git a/frozen/Adafruit_CircuitPython_SSD1306 b/frozen/Adafruit_CircuitPython_SSD1306 index cdb1dcc3a6d..f8fa41a320f 160000 --- a/frozen/Adafruit_CircuitPython_SSD1306 +++ b/frozen/Adafruit_CircuitPython_SSD1306 @@ -1 +1 @@ -Subproject commit cdb1dcc3a6da3cb1a5f64608f2d1e8e3023fe128 +Subproject commit f8fa41a320f0bb29be6f37d340e69eba16b7a311 diff --git a/frozen/Adafruit_CircuitPython_SSD1680 b/frozen/Adafruit_CircuitPython_SSD1680 index 25131d7c8b8..d3eb6f27c0d 160000 --- a/frozen/Adafruit_CircuitPython_SSD1680 +++ b/frozen/Adafruit_CircuitPython_SSD1680 @@ -1 +1 @@ -Subproject commit 25131d7c8b884e541a42c5772091f301a074ad23 +Subproject commit d3eb6f27c0d89e7e8a08bdaf0c6a6e40f7fc512c diff --git a/frozen/Adafruit_CircuitPython_ST7789 b/frozen/Adafruit_CircuitPython_ST7789 index ea32f33ada7..24a0feec2b2 160000 --- a/frozen/Adafruit_CircuitPython_ST7789 +++ b/frozen/Adafruit_CircuitPython_ST7789 @@ -1 +1 @@ -Subproject commit ea32f33ada7ad6da33cead40a2d7393a9d60c029 +Subproject commit 24a0feec2b24517c9f606f5063b6b48db4ce370e diff --git a/frozen/Adafruit_CircuitPython_SimpleIO b/frozen/Adafruit_CircuitPython_SimpleIO index 5770df8b88e..5762bd0ec13 160000 --- a/frozen/Adafruit_CircuitPython_SimpleIO +++ b/frozen/Adafruit_CircuitPython_SimpleIO @@ -1 +1 @@ -Subproject commit 5770df8b88e66ea0690fa0fb04b16b01f96b6fbd +Subproject commit 5762bd0ec1309f9ef489633ed8bcc17d1bc7f560 diff --git a/frozen/Adafruit_CircuitPython_SimpleMath b/frozen/Adafruit_CircuitPython_SimpleMath index d9bec262de9..3653b67541b 160000 --- a/frozen/Adafruit_CircuitPython_SimpleMath +++ b/frozen/Adafruit_CircuitPython_SimpleMath @@ -1 +1 @@ -Subproject commit d9bec262de9a7aeef0f4b02622b89e2da5347572 +Subproject commit 3653b67541b7dbf0fbaaa65628c25cc6900dea87 diff --git a/frozen/Adafruit_CircuitPython_TAS2505 b/frozen/Adafruit_CircuitPython_TAS2505 new file mode 160000 index 00000000000..8363a155b5e --- /dev/null +++ b/frozen/Adafruit_CircuitPython_TAS2505 @@ -0,0 +1 @@ +Subproject commit 8363a155b5e03f13b0c796b350e086ed4e9edc75 diff --git a/frozen/Adafruit_CircuitPython_Thermistor b/frozen/Adafruit_CircuitPython_Thermistor index 1024a5b3087..86b15255613 160000 --- a/frozen/Adafruit_CircuitPython_Thermistor +++ b/frozen/Adafruit_CircuitPython_Thermistor @@ -1 +1 @@ -Subproject commit 1024a5b30879a12728330f8adf077580fb5b2c85 +Subproject commit 86b152556138624979cad2df3210cadc38b5b344 diff --git a/frozen/Adafruit_CircuitPython_Ticks b/frozen/Adafruit_CircuitPython_Ticks index d15da5afc87..0b27bc3dad3 160000 --- a/frozen/Adafruit_CircuitPython_Ticks +++ b/frozen/Adafruit_CircuitPython_Ticks @@ -1 +1 @@ -Subproject commit d15da5afc871b70d152158b5262d8e7d2cd35311 +Subproject commit 0b27bc3dad368b2cd6f18cb4faba3fcb41d54477 diff --git a/frozen/Adafruit_CircuitPython_UC8151D b/frozen/Adafruit_CircuitPython_UC8151D index 372032b65e4..9a37fc43eeb 160000 --- a/frozen/Adafruit_CircuitPython_UC8151D +++ b/frozen/Adafruit_CircuitPython_UC8151D @@ -1 +1 @@ -Subproject commit 372032b65e4c5159073b48518948b701826c92cd +Subproject commit 9a37fc43eeb277f698614e8d657c4104a75a44aa diff --git a/frozen/Adafruit_CircuitPython_Wave b/frozen/Adafruit_CircuitPython_Wave index 892e9925f22..b2dd41fa0e3 160000 --- a/frozen/Adafruit_CircuitPython_Wave +++ b/frozen/Adafruit_CircuitPython_Wave @@ -1 +1 @@ -Subproject commit 892e9925f22dc3f3afa6ba11b487908f2fb63dee +Subproject commit b2dd41fa0e3757c187a4693147eb7d83a84b5119 diff --git a/frozen/Adafruit_CircuitPython_Wiznet5k b/frozen/Adafruit_CircuitPython_Wiznet5k index 4502430c0ce..f01275e34ad 160000 --- a/frozen/Adafruit_CircuitPython_Wiznet5k +++ b/frozen/Adafruit_CircuitPython_Wiznet5k @@ -1 +1 @@ -Subproject commit 4502430c0ceb1183216dd12cf983b9282d3bd0f3 +Subproject commit f01275e34ad2e5f7ddd9d074e963a8359011a297 diff --git a/frozen/Adafruit_CircuitPython_asyncio b/frozen/Adafruit_CircuitPython_asyncio index b74b18efd39..705ae0cbda8 160000 --- a/frozen/Adafruit_CircuitPython_asyncio +++ b/frozen/Adafruit_CircuitPython_asyncio @@ -1 +1 @@ -Subproject commit b74b18efd391e830d165125738441d2710485028 +Subproject commit 705ae0cbda87c4bb4d82fb81aa8fb718b5a4b385 diff --git a/frozen/Adafruit_CircuitPython_framebuf b/frozen/Adafruit_CircuitPython_framebuf index 3cbefc6e9f2..6f6c89891de 160000 --- a/frozen/Adafruit_CircuitPython_framebuf +++ b/frozen/Adafruit_CircuitPython_framebuf @@ -1 +1 @@ -Subproject commit 3cbefc6e9f2eab270826330eb19dc77c3dd4e4ae +Subproject commit 6f6c89891de7d96c43028c4fdff5765763dffe16 diff --git a/frozen/Adafruit_CircuitPython_seesaw b/frozen/Adafruit_CircuitPython_seesaw index 8464fcbeb27..13ba8ba2a2c 160000 --- a/frozen/Adafruit_CircuitPython_seesaw +++ b/frozen/Adafruit_CircuitPython_seesaw @@ -1 +1 @@ -Subproject commit 8464fcbeb2789dc81709f6476d63f5ad7cdc26ba +Subproject commit 13ba8ba2a2cecb9df5a41390f991ce6c0cd76e14 diff --git a/frozen/CircuitPython_edupico2_paj7620 b/frozen/CircuitPython_edupico2_paj7620 new file mode 160000 index 00000000000..16a4d784724 --- /dev/null +++ b/frozen/CircuitPython_edupico2_paj7620 @@ -0,0 +1 @@ +Subproject commit 16a4d784724992862cffd594aeed8c627ecc18b3 diff --git a/frozen/circuitpython-stage b/frozen/circuitpython-stage index ccac175f5e9..7b71363acb6 160000 --- a/frozen/circuitpython-stage +++ b/frozen/circuitpython-stage @@ -1 +1 @@ -Subproject commit ccac175f5e9c8392d436058d4364a8ca5e58abc7 +Subproject commit 7b71363acb67cb1b254b12607f35280cfb4ad6c1 diff --git a/lib/AnimatedGIF/AnimatedGIF_circuitpy.h b/lib/AnimatedGIF/AnimatedGIF_circuitpy.h index c1f359194f5..63c71e665e5 100644 --- a/lib/AnimatedGIF/AnimatedGIF_circuitpy.h +++ b/lib/AnimatedGIF/AnimatedGIF_circuitpy.h @@ -33,7 +33,6 @@ #define MAX_CHUNK_SIZE 255 #define LZW_BUF_SIZE (6 * MAX_CHUNK_SIZE) #define LZW_HIGHWATER (4 * MAX_CHUNK_SIZE) -#define MAX_WIDTH 320 #define FILE_BUF_SIZE 4096 #define PIXEL_FIRST 0 @@ -140,7 +139,7 @@ typedef struct gif_image_tag //unsigned char *pFrameBuffer; unsigned int *pFrameBuffer; unsigned char *pPixels, *pOldPixels; - unsigned char ucLineBuf[MAX_WIDTH]; // current line + unsigned char *ucLineBuf; // current line, at least iCanvasWidth bytes. Set by GIF_init(). unsigned char ucFileBuf[FILE_BUF_SIZE]; // holds temp data and pixel stack unsigned short pPalette[384]; // can hold RGB565 or RGB888 - set in begin() unsigned short pLocalPalette[384]; // color palettes for GIF images @@ -166,7 +165,10 @@ int GIF_getComment(GIFIMAGE *pGIF, char *destBuffer); int GIF_getInfo(GIFIMAGE *pGIF, GIFINFO *pInfo); int GIF_getLastError(GIFIMAGE *pGIF); int GIF_getLoopCount(GIFIMAGE *pGIF); -int GIF_init(GIFIMAGE *pGIF); +// Reads the header and fills in the canvas size. pLineBuf holds one line of pixels and must be +// at least iCanvasWidth bytes, or this fails with GIF_TOO_WIDE. Pass NULL and 0 to only measure +// the canvas, then call again with a buffer before decoding. Returns 1 on success, 0 on failure. +int GIF_init(GIFIMAGE *pGIF, unsigned char *pLineBuf, int iLineBufSize); void GIF_setDrawCallback(GIFIMAGE *pGIF, GIF_DRAW_CALLBACK *pfnDraw); void GIF_scaleHalf(uint16_t *pCurrent, uint16_t *pPrev, int iWidth, int bBigEndian); diff --git a/lib/AnimatedGIF/gif.c b/lib/AnimatedGIF/gif.c index 0822b608c18..fe800c88962 100644 --- a/lib/AnimatedGIF/gif.c +++ b/lib/AnimatedGIF/gif.c @@ -23,7 +23,7 @@ // #include "AnimatedGIF_circuitpy.h" -#ifdef HAL_ESP32_HAL_H_ +#ifndef memcpy_P #define memcpy_P memcpy #endif @@ -163,8 +163,16 @@ int GIF_getLastError(GIFIMAGE *pGIF) return pGIF->iError; } /* GIF_getLastError() */ -int GIF_init(GIFIMAGE *pGIF) { - return GIFInit(pGIF); +int GIF_init(GIFIMAGE *pGIF, unsigned char *pLineBuf, int iLineBufSize) { + pGIF->ucLineBuf = pLineBuf; + if (!GIFInit(pGIF)) { + return 0; + } + if (pLineBuf != NULL && pGIF->iCanvasWidth > iLineBufSize) { + pGIF->iError = GIF_TOO_WIDE; + return 0; + } + return 1; } // @@ -253,10 +261,6 @@ static int GIFInit(GIFIMAGE *pGIF) if (!GIFParseInfo(pGIF, 1)) // gather info for the first frame return 0; // something went wrong; not a GIF file? (*pGIF->pfnSeek)(&pGIF->GIFFile, 0); // seek back to start of the file - if (pGIF->iCanvasWidth > MAX_WIDTH) { // need to allocate more space - pGIF->iError = GIF_TOO_WIDE; - return 0; - } return 1; } /* GIFInit() */ @@ -445,6 +449,11 @@ static int GIFParseInfo(GIFIMAGE *pPage, int bInfoOnly) pPage->iWidth = INTELSHORT(&p[iOffset+4]); pPage->iHeight = INTELSHORT(&p[iOffset+6]); iOffset += 8; + // The line buffer is sized to the canvas, so a frame must fit inside it. + if (pPage->iX + pPage->iWidth > pPage->iCanvasWidth) { + pPage->iError = GIF_DECODE_ERROR; + return 0; + } /* Image descriptor 7 6 5 4 3 2 1 0 M=0 - use global color map, ignore pixel diff --git a/lib/berkeley-db-1.xx b/lib/berkeley-db-1.xx index 85373b548f1..0f3bb6947c2 160000 --- a/lib/berkeley-db-1.xx +++ b/lib/berkeley-db-1.xx @@ -1 +1 @@ -Subproject commit 85373b548f1fb0119a463582570b44189dfb09ae +Subproject commit 0f3bb6947c2f57233916dccd7bb425d7bf86e5a6 diff --git a/lib/certificates b/lib/certificates index ad28d2ee548..f6ac64c2278 160000 --- a/lib/certificates +++ b/lib/certificates @@ -1 +1 @@ -Subproject commit ad28d2ee548bd55033f0a88df6f8902589c365a6 +Subproject commit f6ac64c2278a8748672501e73d48039abfe67680 diff --git a/lib/libffi b/lib/libffi index e9de7e35f23..3d0ce1e6fcf 160000 --- a/lib/libffi +++ b/lib/libffi @@ -1 +1 @@ -Subproject commit e9de7e35f2339598b16cbb375f9992643ed81209 +Subproject commit 3d0ce1e6fcf19f853894862abcbac0ae78a7be60 diff --git a/lib/libm/libm.h b/lib/libm/libm.h index f782249e534..75a2a775f89 100644 --- a/lib/libm/libm.h +++ b/lib/libm/libm.h @@ -19,7 +19,15 @@ #include #include +// CIRCUITPY-CHANGE: prevent undefined warnings +#ifndef FLT_EVAL_METHOD #define FLT_EVAL_METHOD 0 +#endif + +// These lines verify that FLT_EVAL_METHOD==0, MicroPython's libm requires this. +// If compilation fails here then check the host compiler's FLT_EVAL_METHOD. +typedef float float_t; +typedef double double_t; #define FORCE_EVAL(x) do { \ if (sizeof(x) == sizeof(float)) { \ diff --git a/lib/libm/wf_lgamma.c b/lib/libm/wf_lgamma.c index bcf3705420e..7580d2f74e5 100644 --- a/lib/libm/wf_lgamma.c +++ b/lib/libm/wf_lgamma.c @@ -24,7 +24,9 @@ */ #include "fdlibm.h" +#ifndef _IEEE_LIBM #define _IEEE_LIBM 1 +#endif #ifdef __STDC__ float lgammaf(float x) diff --git a/lib/libm/wf_tgamma.c b/lib/libm/wf_tgamma.c index 3ff05f331d0..1a6c74ca11d 100644 --- a/lib/libm/wf_tgamma.c +++ b/lib/libm/wf_tgamma.c @@ -24,7 +24,9 @@ #include "math.h" #include "fdlibm.h" +#ifndef _IEEE_LIBM #define _IEEE_LIBM 1 +#endif #ifdef __STDC__ float tgammaf(float x) diff --git a/lib/libm_dbl/libm.h b/lib/libm_dbl/libm.h index dc0b431a448..fa49ad1cddd 100644 --- a/lib/libm_dbl/libm.h +++ b/lib/libm_dbl/libm.h @@ -15,7 +15,10 @@ #include #include -#define FLT_EVAL_METHOD 0 +// These lines verify that FLT_EVAL_METHOD==0, MicroPython's libm requires this. +// If compilation fails here then check the host compiler's FLT_EVAL_METHOD. +typedef float float_t; +typedef double double_t; #define FORCE_EVAL(x) do { \ if (sizeof(x) == sizeof(float)) { \ @@ -86,7 +89,9 @@ do { \ (d) = __u.f; \ } while (0) +#if !defined(DBL_EPSILON) #define DBL_EPSILON 2.22044604925031308085e-16 +#endif int __rem_pio2(double, double*); int __rem_pio2_large(double*, double*, int, int, int); diff --git a/lib/libm_dbl/rint.c b/lib/libm_dbl/rint.c index fbba390e7d7..b85dec8f246 100644 --- a/lib/libm_dbl/rint.c +++ b/lib/libm_dbl/rint.c @@ -2,7 +2,7 @@ #include #include -#if FLT_EVAL_METHOD==0 || FLT_EVAL_METHOD==1 +#if FLT_EVAL_METHOD==0 || FLT_EVAL_METHOD==1 || FLT_EVAL_METHOD==16 #define EPS DBL_EPSILON #elif FLT_EVAL_METHOD==2 #define EPS LDBL_EPSILON diff --git a/lib/littlefs/lfs1.c b/lib/littlefs/lfs1.c index 6a3fd670012..ec18dc47025 100644 --- a/lib/littlefs/lfs1.c +++ b/lib/littlefs/lfs1.c @@ -2141,7 +2141,7 @@ int lfs1_format(lfs1_t *lfs1, const struct lfs1_config *cfg) { .d.elen = sizeof(superblock.d) - sizeof(superblock.d.magic) - 4, .d.nlen = sizeof(superblock.d.magic), .d.version = LFS1_DISK_VERSION, - .d.magic = {"littlefs"}, + .d.magic = {'l', 'i', 't', 't', 'l', 'e', 'f', 's'}, .d.block_size = lfs1->cfg->block_size, .d.block_count = lfs1->cfg->block_count, .d.root = {lfs1->root[0], lfs1->root[1]}, diff --git a/lib/littlefs/lfs2.c b/lib/littlefs/lfs2.c index 613213669c8..8c65397384b 100644 --- a/lib/littlefs/lfs2.c +++ b/lib/littlefs/lfs2.c @@ -93,6 +93,7 @@ static int lfs2_bd_read(lfs2_t *lfs2, // bypass cache? diff = lfs2_aligndown(diff, lfs2->cfg->read_size); int err = lfs2->cfg->read(lfs2->cfg, block, off, data, diff); + LFS2_ASSERT(err <= 0); if (err) { return err; } @@ -257,7 +258,7 @@ static int lfs2_bd_prog(lfs2_t *lfs2, continue; } - // pcache must have been flushed, either by programming and + // pcache must have been flushed, either by programming an // entire block or manually flushing the pcache LFS2_ASSERT(pcache->block == LFS2_BLOCK_NULL); @@ -282,6 +283,21 @@ static int lfs2_bd_erase(lfs2_t *lfs2, lfs2_block_t block) { /// Small type-level utilities /// + +// some operations on paths +static inline lfs2_size_t lfs2_path_namelen(const char *path) { + return (lfs2_size_t)strcspn(path, "/"); +} + +static inline bool lfs2_path_islast(const char *path) { + lfs2_size_t namelen = lfs2_path_namelen(path); + return path[namelen + strspn(path + namelen, "/")] == '\0'; +} + +static inline bool lfs2_path_isdir(const char *path) { + return path[lfs2_path_namelen(path)] != '\0'; +} + // operations on block pairs static inline void lfs2_pair_swap(lfs2_block_t pair[2]) { lfs2_block_t t = pair[0]; @@ -389,18 +405,15 @@ struct lfs2_diskoff { // operations on global state static inline void lfs2_gstate_xor(lfs2_gstate_t *a, const lfs2_gstate_t *b) { - for (int i = 0; i < 3; i++) { - ((uint32_t*)a)[i] ^= ((const uint32_t*)b)[i]; - } + a->tag ^= b->tag; + a->pair[0] ^= b->pair[0]; + a->pair[1] ^= b->pair[1]; } static inline bool lfs2_gstate_iszero(const lfs2_gstate_t *a) { - for (int i = 0; i < 3; i++) { - if (((uint32_t*)a)[i] != 0) { - return false; - } - } - return true; + return a->tag == 0 + && a->pair[0] == 0 + && a->pair[1] == 0; } #ifndef LFS2_READONLY @@ -550,9 +563,9 @@ static int lfs2_dir_compact(lfs2_t *lfs2, lfs2_mdir_t *source, uint16_t begin, uint16_t end); static lfs2_ssize_t lfs2_file_flushedwrite(lfs2_t *lfs2, lfs2_file_t *file, const void *buffer, lfs2_size_t size); -static lfs2_ssize_t lfs2_file_rawwrite(lfs2_t *lfs2, lfs2_file_t *file, +static lfs2_ssize_t lfs2_file_write_(lfs2_t *lfs2, lfs2_file_t *file, const void *buffer, lfs2_size_t size); -static int lfs2_file_rawsync(lfs2_t *lfs2, lfs2_file_t *file); +static int lfs2_file_sync_(lfs2_t *lfs2, lfs2_file_t *file); static int lfs2_file_outline(lfs2_t *lfs2, lfs2_file_t *file); static int lfs2_file_flush(lfs2_t *lfs2, lfs2_file_t *file); @@ -574,65 +587,72 @@ static int lfs21_traverse(lfs2_t *lfs2, int (*cb)(void*, lfs2_block_t), void *data); #endif -static int lfs2_dir_rawrewind(lfs2_t *lfs2, lfs2_dir_t *dir); +static int lfs2_dir_rewind_(lfs2_t *lfs2, lfs2_dir_t *dir); static lfs2_ssize_t lfs2_file_flushedread(lfs2_t *lfs2, lfs2_file_t *file, void *buffer, lfs2_size_t size); -static lfs2_ssize_t lfs2_file_rawread(lfs2_t *lfs2, lfs2_file_t *file, +static lfs2_ssize_t lfs2_file_read_(lfs2_t *lfs2, lfs2_file_t *file, void *buffer, lfs2_size_t size); -static int lfs2_file_rawclose(lfs2_t *lfs2, lfs2_file_t *file); -static lfs2_soff_t lfs2_file_rawsize(lfs2_t *lfs2, lfs2_file_t *file); +static int lfs2_file_close_(lfs2_t *lfs2, lfs2_file_t *file); +static lfs2_soff_t lfs2_file_size_(lfs2_t *lfs2, lfs2_file_t *file); -static lfs2_ssize_t lfs2_fs_rawsize(lfs2_t *lfs2); -static int lfs2_fs_rawtraverse(lfs2_t *lfs2, +static lfs2_ssize_t lfs2_fs_size_(lfs2_t *lfs2); +static int lfs2_fs_traverse_(lfs2_t *lfs2, int (*cb)(void *data, lfs2_block_t block), void *data, bool includeorphans); static int lfs2_deinit(lfs2_t *lfs2); -static int lfs2_rawunmount(lfs2_t *lfs2); +static int lfs2_unmount_(lfs2_t *lfs2); /// Block allocator /// + +// allocations should call this when all allocated blocks are committed to +// the filesystem +// +// after a checkpoint, the block allocator may realloc any untracked blocks +static void lfs2_alloc_ckpoint(lfs2_t *lfs2) { + lfs2->lookahead.ckpoint = lfs2->block_count; +} + +// drop the lookahead buffer, this is done during mounting and failed +// traversals in order to avoid invalid lookahead state +static void lfs2_alloc_drop(lfs2_t *lfs2) { + lfs2->lookahead.size = 0; + lfs2->lookahead.next = 0; + lfs2_alloc_ckpoint(lfs2); +} + #ifndef LFS2_READONLY static int lfs2_alloc_lookahead(void *p, lfs2_block_t block) { lfs2_t *lfs2 = (lfs2_t*)p; - lfs2_block_t off = ((block - lfs2->free.off) + lfs2_block_t off = ((block - lfs2->lookahead.start) + lfs2->block_count) % lfs2->block_count; - if (off < lfs2->free.size) { - lfs2->free.buffer[off / 32] |= 1U << (off % 32); + if (off < lfs2->lookahead.size) { + lfs2->lookahead.buffer[off / 8] |= 1U << (off % 8); } return 0; } #endif -// indicate allocated blocks have been committed into the filesystem, this -// is to prevent blocks from being garbage collected in the middle of a -// commit operation -static void lfs2_alloc_ack(lfs2_t *lfs2) { - lfs2->free.ack = lfs2->block_count; -} - -// drop the lookahead buffer, this is done during mounting and failed -// traversals in order to avoid invalid lookahead state -static void lfs2_alloc_drop(lfs2_t *lfs2) { - lfs2->free.size = 0; - lfs2->free.i = 0; - lfs2_alloc_ack(lfs2); -} - #ifndef LFS2_READONLY -static int lfs2_fs_rawgc(lfs2_t *lfs2) { - // Move free offset at the first unused block (lfs2->free.i) - // lfs2->free.i is equal lfs2->free.size when all blocks are used - lfs2->free.off = (lfs2->free.off + lfs2->free.i) % lfs2->block_count; - lfs2->free.size = lfs2_min(8*lfs2->cfg->lookahead_size, lfs2->free.ack); - lfs2->free.i = 0; +static int lfs2_alloc_scan(lfs2_t *lfs2) { + // move lookahead buffer to the first unused block + // + // note we limit the lookahead buffer to at most the amount of blocks + // checkpointed, this prevents the math in lfs2_alloc from underflowing + lfs2->lookahead.start = (lfs2->lookahead.start + lfs2->lookahead.next) + % lfs2->block_count; + lfs2->lookahead.next = 0; + lfs2->lookahead.size = lfs2_min( + 8*lfs2->cfg->lookahead_size, + lfs2->lookahead.ckpoint); // find mask of free blocks from tree - memset(lfs2->free.buffer, 0, lfs2->cfg->lookahead_size); - int err = lfs2_fs_rawtraverse(lfs2, lfs2_alloc_lookahead, lfs2, true); + memset(lfs2->lookahead.buffer, 0, lfs2->cfg->lookahead_size); + int err = lfs2_fs_traverse_(lfs2, lfs2_alloc_lookahead, lfs2, true); if (err) { lfs2_alloc_drop(lfs2); return err; @@ -645,36 +665,49 @@ static int lfs2_fs_rawgc(lfs2_t *lfs2) { #ifndef LFS2_READONLY static int lfs2_alloc(lfs2_t *lfs2, lfs2_block_t *block) { while (true) { - while (lfs2->free.i != lfs2->free.size) { - lfs2_block_t off = lfs2->free.i; - lfs2->free.i += 1; - lfs2->free.ack -= 1; - - if (!(lfs2->free.buffer[off / 32] & (1U << (off % 32)))) { + // scan our lookahead buffer for free blocks + while (lfs2->lookahead.next < lfs2->lookahead.size) { + if (!(lfs2->lookahead.buffer[lfs2->lookahead.next / 8] + & (1U << (lfs2->lookahead.next % 8)))) { // found a free block - *block = (lfs2->free.off + off) % lfs2->block_count; - - // eagerly find next off so an alloc ack can - // discredit old lookahead blocks - while (lfs2->free.i != lfs2->free.size && - (lfs2->free.buffer[lfs2->free.i / 32] - & (1U << (lfs2->free.i % 32)))) { - lfs2->free.i += 1; - lfs2->free.ack -= 1; + *block = (lfs2->lookahead.start + lfs2->lookahead.next) + % lfs2->block_count; + + // eagerly find next free block to maximize how many blocks + // lfs2_alloc_ckpoint makes available for scanning + while (true) { + lfs2->lookahead.next += 1; + lfs2->lookahead.ckpoint -= 1; + + if (lfs2->lookahead.next >= lfs2->lookahead.size + || !(lfs2->lookahead.buffer[lfs2->lookahead.next / 8] + & (1U << (lfs2->lookahead.next % 8)))) { + return 0; + } } - - return 0; } + + lfs2->lookahead.next += 1; + lfs2->lookahead.ckpoint -= 1; } - // check if we have looked at all blocks since last ack - if (lfs2->free.ack == 0) { - LFS2_ERROR("No more free space %"PRIu32, - lfs2->free.i + lfs2->free.off); + // In order to keep our block allocator from spinning forever when our + // filesystem is full, we mark points where there are no in-flight + // allocations with a checkpoint before starting a set of allocations. + // + // If we've looked at all blocks since the last checkpoint, we report + // the filesystem as out of storage. + // + if (lfs2->lookahead.ckpoint <= 0) { + LFS2_ERROR("No more free space 0x%"PRIx32, + (lfs2->lookahead.start + lfs2->lookahead.next) + % lfs2->block_count); return LFS2_ERR_NOSPC; } - int err = lfs2_fs_rawgc(lfs2); + // No blocks in our lookahead buffer, we need to scan the filesystem for + // unused blocks in the next lookahead window. + int err = lfs2_alloc_scan(lfs2); if(err) { return err; } @@ -690,11 +723,14 @@ static lfs2_stag_t lfs2_dir_getslice(lfs2_t *lfs2, const lfs2_mdir_t *dir, lfs2_tag_t ntag = dir->etag; lfs2_stag_t gdiff = 0; + // synthetic moves if (lfs2_gstate_hasmovehere(&lfs2->gdisk, dir->pair) && - lfs2_tag_id(gmask) != 0 && - lfs2_tag_id(lfs2->gdisk.tag) <= lfs2_tag_id(gtag)) { - // synthetic moves - gdiff -= LFS2_MKTAG(0, 1, 0); + lfs2_tag_id(gmask) != 0) { + if (lfs2_tag_id(lfs2->gdisk.tag) == lfs2_tag_id(gtag)) { + return LFS2_ERR_NOENT; + } else if (lfs2_tag_id(lfs2->gdisk.tag) < lfs2_tag_id(gtag)) { + gdiff -= LFS2_MKTAG(0, 1, 0); + } } // iterate over dir block backwards (for faster lookups) @@ -704,6 +740,7 @@ static lfs2_stag_t lfs2_dir_getslice(lfs2_t *lfs2, const lfs2_mdir_t *dir, int err = lfs2_bd_read(lfs2, NULL, &lfs2->rcache, sizeof(ntag), dir->pair[0], off, &ntag, sizeof(ntag)); + LFS2_ASSERT(err <= 0); if (err) { return err; } @@ -732,6 +769,7 @@ static lfs2_stag_t lfs2_dir_getslice(lfs2_t *lfs2, const lfs2_mdir_t *dir, err = lfs2_bd_read(lfs2, NULL, &lfs2->rcache, diff, dir->pair[0], off+sizeof(tag)+goff, gbuffer, diff); + LFS2_ASSERT(err <= 0); if (err) { return err; } @@ -793,9 +831,6 @@ static int lfs2_dir_getread(lfs2_t *lfs2, const lfs2_mdir_t *dir, size -= diff; continue; } - - // rcache takes priority - diff = lfs2_min(diff, rcache->off-off); } // load to cache, first condition can no longer fail @@ -1247,6 +1282,7 @@ static lfs2_stag_t lfs2_dir_fetchmatch(lfs2_t *lfs2, if (err == LFS2_ERR_CORRUPT) { break; } + return err; } lfs2_fcrc_fromle32(&fcrc); @@ -1255,6 +1291,7 @@ static lfs2_stag_t lfs2_dir_fetchmatch(lfs2_t *lfs2, // found a match for our fetcher? if ((fmask & tag) == (fmask & ftag)) { + LFS2_ASSERT(cb != NULL); int res = cb(data, tag, &(struct lfs2_diskoff){ dir->pair[0], off+sizeof(tag)}); if (res < 0) { @@ -1438,44 +1475,60 @@ static int lfs2_dir_find_match(void *data, return LFS2_CMP_EQ; } +// lfs2_dir_find tries to set path and id even if file is not found +// +// returns: +// - 0 if file is found +// - LFS2_ERR_NOENT if file or parent is not found +// - LFS2_ERR_NOTDIR if parent is not a dir static lfs2_stag_t lfs2_dir_find(lfs2_t *lfs2, lfs2_mdir_t *dir, const char **path, uint16_t *id) { // we reduce path to a single name if we can find it const char *name = *path; - if (id) { - *id = 0x3ff; - } // default to root dir lfs2_stag_t tag = LFS2_MKTAG(LFS2_TYPE_DIR, 0x3ff, 0); dir->tail[0] = lfs2->root[0]; dir->tail[1] = lfs2->root[1]; + // empty paths are not allowed + if (*name == '\0') { + return LFS2_ERR_INVAL; + } + while (true) { nextname: - // skip slashes - name += strspn(name, "/"); - lfs2_size_t namelen = strcspn(name, "/"); + // skip slashes if we're a directory + if (lfs2_tag_type3(tag) == LFS2_TYPE_DIR) { + name += strspn(name, "/"); + } + lfs2_size_t namelen = (lfs2_size_t)strcspn(name, "/"); - // skip '.' and root '..' - if ((namelen == 1 && memcmp(name, ".", 1) == 0) || - (namelen == 2 && memcmp(name, "..", 2) == 0)) { + // skip '.' + if (namelen == 1 && memcmp(name, ".", 1) == 0) { name += namelen; goto nextname; } + // error on unmatched '..', trying to go above root? + if (namelen == 2 && memcmp(name, "..", 2) == 0) { + return LFS2_ERR_INVAL; + } + // skip if matched by '..' in name const char *suffix = name + namelen; lfs2_size_t sufflen; int depth = 1; while (true) { suffix += strspn(suffix, "/"); - sufflen = strcspn(suffix, "/"); + sufflen = (lfs2_size_t)strcspn(suffix, "/"); if (sufflen == 0) { break; } - if (sufflen == 2 && memcmp(suffix, "..", 2) == 0) { + if (sufflen == 1 && memcmp(suffix, ".", 1) == 0) { + // noop + } else if (sufflen == 2 && memcmp(suffix, "..", 2) == 0) { depth -= 1; if (depth == 0) { name = suffix + sufflen; @@ -1489,14 +1542,14 @@ static lfs2_stag_t lfs2_dir_find(lfs2_t *lfs2, lfs2_mdir_t *dir, } // found path - if (name[0] == '\0') { + if (*name == '\0') { return tag; } // update what we've found so far *path = name; - // only continue if we hit a directory + // only continue if we're a directory if (lfs2_tag_type3(tag) != LFS2_TYPE_DIR) { return LFS2_ERR_NOTDIR; } @@ -1516,8 +1569,7 @@ static lfs2_stag_t lfs2_dir_find(lfs2_t *lfs2, lfs2_mdir_t *dir, tag = lfs2_dir_fetchmatch(lfs2, dir, dir->tail, LFS2_MKTAG(0x780, 0, 0), LFS2_MKTAG(LFS2_TYPE_NAME, 0, namelen), - // are we last name? - (strchr(name, '/') == NULL) ? id : NULL, + id, lfs2_dir_find_match, &(struct lfs2_dir_find_match){ lfs2, name, namelen}); if (tag < 0) { @@ -1710,7 +1762,7 @@ static int lfs2_dir_commitcrc(lfs2_t *lfs2, struct lfs2_commit *commit) { commit->off = noff; // perturb valid bit? - commit->ptag = ntag ^ ((0x80UL & ~eperturb) << 24); + commit->ptag = ntag ^ ((lfs2_tag_t)(0x80 & ~eperturb) << 24); // reset crc for next commit commit->crc = 0xffffffff; @@ -2105,13 +2157,14 @@ static int lfs2_dir_splittingcompact(lfs2_t *lfs2, lfs2_mdir_t *dir, // And we cap at half a block to avoid degenerate cases with // nearly-full metadata blocks. // + lfs2_size_t metadata_max = (lfs2->cfg->metadata_max) + ? lfs2->cfg->metadata_max + : lfs2->cfg->block_size; if (end - split < 0xff && size <= lfs2_min( - lfs2->cfg->block_size - 40, + metadata_max - 40, lfs2_alignup( - (lfs2->cfg->metadata_max - ? lfs2->cfg->metadata_max - : lfs2->cfg->block_size)/2, + metadata_max/2, lfs2->cfg->prog_size))) { break; } @@ -2146,14 +2199,16 @@ static int lfs2_dir_splittingcompact(lfs2_t *lfs2, lfs2_mdir_t *dir, && lfs2_pair_cmp(dir->pair, (const lfs2_block_t[2]){0, 1}) == 0) { // oh no! we're writing too much to the superblock, // should we expand? - lfs2_ssize_t size = lfs2_fs_rawsize(lfs2); + lfs2_ssize_t size = lfs2_fs_size_(lfs2); if (size < 0) { return size; } - // do we have extra space? littlefs can't reclaim this space - // by itself, so expand cautiously - if ((lfs2_size_t)size < lfs2->block_count/2) { + // littlefs cannot reclaim expanded superblocks, so expand cautiously + // + // if our filesystem is more than ~88% full, don't expand, this is + // somewhat arbitrary + if (lfs2->block_count - size > lfs2->block_count/8) { LFS2_DEBUG("Expanding superblock at rev %"PRIu32, dir->rev); int err = lfs2_dir_split(lfs2, dir, attrs, attrcount, source, begin, end); @@ -2166,7 +2221,8 @@ static int lfs2_dir_splittingcompact(lfs2_t *lfs2, lfs2_mdir_t *dir, // we can do, we'll error later if we've become frozen LFS2_WARN("Unable to expand superblock"); } else { - end = begin; + // duplicate the superblock entry into the new superblock + end = 1; } } } @@ -2213,7 +2269,7 @@ static int lfs2_dir_relocatingcommit(lfs2_t *lfs2, lfs2_mdir_t *dir, } } - if (dir->erased) { + if (dir->erased && dir->count < 0xff) { // try to commit struct lfs2_commit commit = { .block = dir->pair[0], @@ -2312,7 +2368,8 @@ fixmlist:; if (d->m.pair != pair) { for (int i = 0; i < attrcount; i++) { if (lfs2_tag_type3(attrs[i].tag) == LFS2_TYPE_DELETE && - d->id == lfs2_tag_id(attrs[i].tag)) { + d->id == lfs2_tag_id(attrs[i].tag) && + d->type != LFS2_TYPE_DIR) { d->m.pair[0] = LFS2_BLOCK_NULL; d->m.pair[1] = LFS2_BLOCK_NULL; } else if (lfs2_tag_type3(attrs[i].tag) == LFS2_TYPE_DELETE && @@ -2333,7 +2390,9 @@ fixmlist:; while (d->id >= d->m.count && d->m.split) { // we split and id is on tail now - d->id -= d->m.count; + if (lfs2_pair_cmp(d->m.tail, lfs2->root) != 0) { + d->id -= d->m.count; + } int err = lfs2_dir_fetch(lfs2, &d->m, d->m.tail); if (err) { return err; @@ -2499,7 +2558,7 @@ static int lfs2_dir_orphaningcommit(lfs2_t *lfs2, lfs2_mdir_t *dir, if (err != LFS2_ERR_NOENT) { if (lfs2_gstate_hasorphans(&lfs2->gstate)) { // next step, clean up orphans - err = lfs2_fs_preporphans(lfs2, -hasparent); + err = lfs2_fs_preporphans(lfs2, -(int8_t)hasparent); if (err) { return err; } @@ -2564,7 +2623,7 @@ static int lfs2_dir_commit(lfs2_t *lfs2, lfs2_mdir_t *dir, /// Top level directory operations /// #ifndef LFS2_READONLY -static int lfs2_rawmkdir(lfs2_t *lfs2, const char *path) { +static int lfs2_mkdir_(lfs2_t *lfs2, const char *path) { // deorphan if we haven't yet, needed at most once after poweron int err = lfs2_fs_forceconsistency(lfs2); if (err) { @@ -2575,18 +2634,18 @@ static int lfs2_rawmkdir(lfs2_t *lfs2, const char *path) { cwd.next = lfs2->mlist; uint16_t id; err = lfs2_dir_find(lfs2, &cwd.m, &path, &id); - if (!(err == LFS2_ERR_NOENT && id != 0x3ff)) { + if (!(err == LFS2_ERR_NOENT && lfs2_path_islast(path))) { return (err < 0) ? err : LFS2_ERR_EXIST; } // check that name fits - lfs2_size_t nlen = strlen(path); + lfs2_size_t nlen = lfs2_path_namelen(path); if (nlen > lfs2->name_max) { return LFS2_ERR_NAMETOOLONG; } // build up new directory - lfs2_alloc_ack(lfs2); + lfs2_alloc_ckpoint(lfs2); lfs2_mdir_t dir; err = lfs2_dir_alloc(lfs2, &dir); if (err) { @@ -2660,7 +2719,7 @@ static int lfs2_rawmkdir(lfs2_t *lfs2, const char *path) { } #endif -static int lfs2_dir_rawopen(lfs2_t *lfs2, lfs2_dir_t *dir, const char *path) { +static int lfs2_dir_open_(lfs2_t *lfs2, lfs2_dir_t *dir, const char *path) { lfs2_stag_t tag = lfs2_dir_find(lfs2, &dir->m, &path, NULL); if (tag < 0) { return tag; @@ -2704,14 +2763,14 @@ static int lfs2_dir_rawopen(lfs2_t *lfs2, lfs2_dir_t *dir, const char *path) { return 0; } -static int lfs2_dir_rawclose(lfs2_t *lfs2, lfs2_dir_t *dir) { +static int lfs2_dir_close_(lfs2_t *lfs2, lfs2_dir_t *dir) { // remove from list of mdirs lfs2_mlist_remove(lfs2, (struct lfs2_mlist *)dir); return 0; } -static int lfs2_dir_rawread(lfs2_t *lfs2, lfs2_dir_t *dir, struct lfs2_info *info) { +static int lfs2_dir_read_(lfs2_t *lfs2, lfs2_dir_t *dir, struct lfs2_info *info) { memset(info, 0, sizeof(*info)); // special offset for '.' and '..' @@ -2756,9 +2815,9 @@ static int lfs2_dir_rawread(lfs2_t *lfs2, lfs2_dir_t *dir, struct lfs2_info *inf return true; } -static int lfs2_dir_rawseek(lfs2_t *lfs2, lfs2_dir_t *dir, lfs2_off_t off) { +static int lfs2_dir_seek_(lfs2_t *lfs2, lfs2_dir_t *dir, lfs2_off_t off) { // simply walk from head dir - int err = lfs2_dir_rawrewind(lfs2, dir); + int err = lfs2_dir_rewind_(lfs2, dir); if (err) { return err; } @@ -2793,12 +2852,12 @@ static int lfs2_dir_rawseek(lfs2_t *lfs2, lfs2_dir_t *dir, lfs2_off_t off) { return 0; } -static lfs2_soff_t lfs2_dir_rawtell(lfs2_t *lfs2, lfs2_dir_t *dir) { +static lfs2_soff_t lfs2_dir_tell_(lfs2_t *lfs2, lfs2_dir_t *dir) { (void)lfs2; return dir->pos; } -static int lfs2_dir_rawrewind(lfs2_t *lfs2, lfs2_dir_t *dir) { +static int lfs2_dir_rewind_(lfs2_t *lfs2, lfs2_dir_t *dir) { // reload the head dir int err = lfs2_dir_fetch(lfs2, &dir->m, dir->head); if (err) { @@ -3004,7 +3063,7 @@ static int lfs2_ctz_traverse(lfs2_t *lfs2, /// Top level file operations /// -static int lfs2_file_rawopencfg(lfs2_t *lfs2, lfs2_file_t *file, +static int lfs2_file_opencfg_(lfs2_t *lfs2, lfs2_file_t *file, const char *path, int flags, const struct lfs2_file_config *cfg) { #ifndef LFS2_READONLY @@ -3029,7 +3088,7 @@ static int lfs2_file_rawopencfg(lfs2_t *lfs2, lfs2_file_t *file, // allocate entry for file if it doesn't exist lfs2_stag_t tag = lfs2_dir_find(lfs2, &file->m, &path, &file->id); - if (tag < 0 && !(tag == LFS2_ERR_NOENT && file->id != 0x3ff)) { + if (tag < 0 && !(tag == LFS2_ERR_NOENT && lfs2_path_islast(path))) { err = tag; goto cleanup; } @@ -3049,8 +3108,14 @@ static int lfs2_file_rawopencfg(lfs2_t *lfs2, lfs2_file_t *file, goto cleanup; } + // don't allow trailing slashes + if (lfs2_path_isdir(path)) { + err = LFS2_ERR_NOTDIR; + goto cleanup; + } + // check that name fits - lfs2_size_t nlen = strlen(path); + lfs2_size_t nlen = lfs2_path_namelen(path); if (nlen > lfs2->name_max) { err = LFS2_ERR_NAMETOOLONG; goto cleanup; @@ -3166,24 +3231,26 @@ static int lfs2_file_rawopencfg(lfs2_t *lfs2, lfs2_file_t *file, #ifndef LFS2_READONLY file->flags |= LFS2_F_ERRED; #endif - lfs2_file_rawclose(lfs2, file); + lfs2_file_close_(lfs2, file); return err; } #ifndef LFS2_NO_MALLOC -static int lfs2_file_rawopen(lfs2_t *lfs2, lfs2_file_t *file, +static int lfs2_file_open_(lfs2_t *lfs2, lfs2_file_t *file, const char *path, int flags) { static const struct lfs2_file_config defaults = {0}; - int err = lfs2_file_rawopencfg(lfs2, file, path, flags, &defaults); + int err = lfs2_file_opencfg_(lfs2, file, path, flags, &defaults); return err; } #endif -static int lfs2_file_rawclose(lfs2_t *lfs2, lfs2_file_t *file) { -#ifndef LFS2_READONLY - int err = lfs2_file_rawsync(lfs2, file); -#else +static int lfs2_file_close_(lfs2_t *lfs2, lfs2_file_t *file) { int err = 0; +#ifndef LFS2_READONLY + // it's not safe to do anything if our file errored + if (!(file->flags & LFS2_F_ERRED)) { + err = lfs2_file_sync_(lfs2, file); + } #endif // remove from list of mdirs @@ -3272,7 +3339,7 @@ static int lfs2_file_relocate(lfs2_t *lfs2, lfs2_file_t *file) { #ifndef LFS2_READONLY static int lfs2_file_outline(lfs2_t *lfs2, lfs2_file_t *file) { file->off = file->pos; - lfs2_alloc_ack(lfs2); + lfs2_alloc_ckpoint(lfs2); int err = lfs2_file_relocate(lfs2, file); if (err) { return err; @@ -3364,21 +3431,24 @@ static int lfs2_file_flush(lfs2_t *lfs2, lfs2_file_t *file) { } #ifndef LFS2_READONLY -static int lfs2_file_rawsync(lfs2_t *lfs2, lfs2_file_t *file) { - if (file->flags & LFS2_F_ERRED) { - // it's not safe to do anything if our file errored - return 0; - } - +static int lfs2_file_sync_(lfs2_t *lfs2, lfs2_file_t *file) { int err = lfs2_file_flush(lfs2, file); if (err) { file->flags |= LFS2_F_ERRED; return err; } - if ((file->flags & LFS2_F_DIRTY) && !lfs2_pair_isnull(file->m.pair)) { + // before we commit metadata, we need sync the disk to make sure + // data writes don't complete after metadata writes + if (!(file->flags & LFS2_F_INLINE)) { + err = lfs2_bd_sync(lfs2, &lfs2->pcache, &lfs2->rcache, false); + if (err) { + return err; + } + } + // update dir entry uint16_t type; const void *buffer; @@ -3412,6 +3482,17 @@ static int lfs2_file_rawsync(lfs2_t *lfs2, lfs2_file_t *file) { file->flags &= ~LFS2_F_DIRTY; } + // mark any other file handles as dirty + desync + for (lfs2_file_t *f = (lfs2_file_t*)lfs2->mlist; f; f = f->next) { + if (file != f + && f->type == LFS2_TYPE_REG + && lfs2_pair_cmp(f->m.pair, file->m.pair) == 0 + && f->id == file->id) { + f->flags |= LFS2_F_DUSTY; + } + } + + file->flags &= ~LFS2_F_ERRED & ~LFS2_F_DUSTY; return 0; } #endif @@ -3477,7 +3558,7 @@ static lfs2_ssize_t lfs2_file_flushedread(lfs2_t *lfs2, lfs2_file_t *file, return size; } -static lfs2_ssize_t lfs2_file_rawread(lfs2_t *lfs2, lfs2_file_t *file, +static lfs2_ssize_t lfs2_file_read_(lfs2_t *lfs2, lfs2_file_t *file, void *buffer, lfs2_size_t size) { LFS2_ASSERT((file->flags & LFS2_O_RDONLY) == LFS2_O_RDONLY); @@ -3502,11 +3583,7 @@ static lfs2_ssize_t lfs2_file_flushedwrite(lfs2_t *lfs2, lfs2_file_t *file, lfs2_size_t nsize = size; if ((file->flags & LFS2_F_INLINE) && - lfs2_max(file->pos+nsize, file->ctz.size) > - lfs2_min(0x3fe, lfs2_min( - lfs2->cfg->cache_size, - (lfs2->cfg->metadata_max ? - lfs2->cfg->metadata_max : lfs2->cfg->block_size) / 8))) { + lfs2_max(file->pos+nsize, file->ctz.size) > lfs2->inline_max) { // inline file doesn't fit anymore int err = lfs2_file_outline(lfs2, file); if (err) { @@ -3535,7 +3612,7 @@ static lfs2_ssize_t lfs2_file_flushedwrite(lfs2_t *lfs2, lfs2_file_t *file, } // extend file with new blocks - lfs2_alloc_ack(lfs2); + lfs2_alloc_ckpoint(lfs2); int err = lfs2_ctz_extend(lfs2, &file->cache, &lfs2->rcache, file->block, file->pos, &file->block, &file->off); @@ -3578,13 +3655,13 @@ static lfs2_ssize_t lfs2_file_flushedwrite(lfs2_t *lfs2, lfs2_file_t *file, data += diff; nsize -= diff; - lfs2_alloc_ack(lfs2); + lfs2_alloc_ckpoint(lfs2); } return size; } -static lfs2_ssize_t lfs2_file_rawwrite(lfs2_t *lfs2, lfs2_file_t *file, +static lfs2_ssize_t lfs2_file_write_(lfs2_t *lfs2, lfs2_file_t *file, const void *buffer, lfs2_size_t size) { LFS2_ASSERT((file->flags & LFS2_O_WRONLY) == LFS2_O_WRONLY); @@ -3623,30 +3700,24 @@ static lfs2_ssize_t lfs2_file_rawwrite(lfs2_t *lfs2, lfs2_file_t *file, return nsize; } - file->flags &= ~LFS2_F_ERRED; + file->flags &= ~LFS2_F_ERRED & ~LFS2_F_DUSTY; return nsize; } #endif -static lfs2_soff_t lfs2_file_rawseek(lfs2_t *lfs2, lfs2_file_t *file, +static lfs2_soff_t lfs2_file_seek_(lfs2_t *lfs2, lfs2_file_t *file, lfs2_soff_t off, int whence) { // find new pos + // + // fortunately for us, littlefs is limited to 31-bit file sizes, so we + // don't have to worry too much about integer overflow lfs2_off_t npos = file->pos; if (whence == LFS2_SEEK_SET) { npos = off; } else if (whence == LFS2_SEEK_CUR) { - if ((lfs2_soff_t)file->pos + off < 0) { - return LFS2_ERR_INVAL; - } else { - npos = file->pos + off; - } + npos = file->pos + (lfs2_off_t)off; } else if (whence == LFS2_SEEK_END) { - lfs2_soff_t res = lfs2_file_rawsize(lfs2, file) + off; - if (res < 0) { - return LFS2_ERR_INVAL; - } else { - npos = res; - } + npos = (lfs2_off_t)lfs2_file_size_(lfs2, file) + (lfs2_off_t)off; } if (npos > lfs2->file_max) { @@ -3661,13 +3732,8 @@ static lfs2_soff_t lfs2_file_rawseek(lfs2_t *lfs2, lfs2_file_t *file, // if we're only reading and our new offset is still in the file's cache // we can avoid flushing and needing to reread the data - if ( -#ifndef LFS2_READONLY - !(file->flags & LFS2_F_WRITING) -#else - true -#endif - ) { + if ((file->flags & LFS2_F_READING) + && file->off != lfs2->cfg->block_size) { int oindex = lfs2_ctz_index(lfs2, &(lfs2_off_t){file->pos}); lfs2_off_t noff = npos; int nindex = lfs2_ctz_index(lfs2, &noff); @@ -3692,7 +3758,7 @@ static lfs2_soff_t lfs2_file_rawseek(lfs2_t *lfs2, lfs2_file_t *file, } #ifndef LFS2_READONLY -static int lfs2_file_rawtruncate(lfs2_t *lfs2, lfs2_file_t *file, lfs2_off_t size) { +static int lfs2_file_truncate_(lfs2_t *lfs2, lfs2_file_t *file, lfs2_off_t size) { LFS2_ASSERT((file->flags & LFS2_O_WRONLY) == LFS2_O_WRONLY); if (size > LFS2_FILE_MAX) { @@ -3700,15 +3766,12 @@ static int lfs2_file_rawtruncate(lfs2_t *lfs2, lfs2_file_t *file, lfs2_off_t siz } lfs2_off_t pos = file->pos; - lfs2_off_t oldsize = lfs2_file_rawsize(lfs2, file); + lfs2_off_t oldsize = lfs2_file_size_(lfs2, file); if (size < oldsize) { // revert to inline file? - if (size <= lfs2_min(0x3fe, lfs2_min( - lfs2->cfg->cache_size, - (lfs2->cfg->metadata_max ? - lfs2->cfg->metadata_max : lfs2->cfg->block_size) / 8))) { + if (size <= lfs2->inline_max) { // flush+seek to head - lfs2_soff_t res = lfs2_file_rawseek(lfs2, file, 0, LFS2_SEEK_SET); + lfs2_soff_t res = lfs2_file_seek_(lfs2, file, 0, LFS2_SEEK_SET); if (res < 0) { return (int)res; } @@ -3753,14 +3816,14 @@ static int lfs2_file_rawtruncate(lfs2_t *lfs2, lfs2_file_t *file, lfs2_off_t siz } } else if (size > oldsize) { // flush+seek if not already at end - lfs2_soff_t res = lfs2_file_rawseek(lfs2, file, 0, LFS2_SEEK_END); + lfs2_soff_t res = lfs2_file_seek_(lfs2, file, 0, LFS2_SEEK_END); if (res < 0) { return (int)res; } // fill with zeros while (file->pos < size) { - res = lfs2_file_rawwrite(lfs2, file, &(uint8_t){0}, 1); + res = lfs2_file_write_(lfs2, file, &(uint8_t){0}, 1); if (res < 0) { return (int)res; } @@ -3768,7 +3831,7 @@ static int lfs2_file_rawtruncate(lfs2_t *lfs2, lfs2_file_t *file, lfs2_off_t siz } // restore pos - lfs2_soff_t res = lfs2_file_rawseek(lfs2, file, pos, LFS2_SEEK_SET); + lfs2_soff_t res = lfs2_file_seek_(lfs2, file, pos, LFS2_SEEK_SET); if (res < 0) { return (int)res; } @@ -3777,13 +3840,13 @@ static int lfs2_file_rawtruncate(lfs2_t *lfs2, lfs2_file_t *file, lfs2_off_t siz } #endif -static lfs2_soff_t lfs2_file_rawtell(lfs2_t *lfs2, lfs2_file_t *file) { +static lfs2_soff_t lfs2_file_tell_(lfs2_t *lfs2, lfs2_file_t *file) { (void)lfs2; return file->pos; } -static int lfs2_file_rawrewind(lfs2_t *lfs2, lfs2_file_t *file) { - lfs2_soff_t res = lfs2_file_rawseek(lfs2, file, 0, LFS2_SEEK_SET); +static int lfs2_file_rewind_(lfs2_t *lfs2, lfs2_file_t *file) { + lfs2_soff_t res = lfs2_file_seek_(lfs2, file, 0, LFS2_SEEK_SET); if (res < 0) { return (int)res; } @@ -3791,7 +3854,7 @@ static int lfs2_file_rawrewind(lfs2_t *lfs2, lfs2_file_t *file) { return 0; } -static lfs2_soff_t lfs2_file_rawsize(lfs2_t *lfs2, lfs2_file_t *file) { +static lfs2_soff_t lfs2_file_size_(lfs2_t *lfs2, lfs2_file_t *file) { (void)lfs2; #ifndef LFS2_READONLY @@ -3805,18 +3868,24 @@ static lfs2_soff_t lfs2_file_rawsize(lfs2_t *lfs2, lfs2_file_t *file) { /// General fs operations /// -static int lfs2_rawstat(lfs2_t *lfs2, const char *path, struct lfs2_info *info) { +static int lfs2_stat_(lfs2_t *lfs2, const char *path, struct lfs2_info *info) { lfs2_mdir_t cwd; lfs2_stag_t tag = lfs2_dir_find(lfs2, &cwd, &path, NULL); if (tag < 0) { return (int)tag; } + // only allow trailing slashes on dirs + if (strchr(path, '/') != NULL + && lfs2_tag_type3(tag) != LFS2_TYPE_DIR) { + return LFS2_ERR_NOTDIR; + } + return lfs2_dir_getinfo(lfs2, &cwd, lfs2_tag_id(tag), info); } #ifndef LFS2_READONLY -static int lfs2_rawremove(lfs2_t *lfs2, const char *path) { +static int lfs2_remove_(lfs2_t *lfs2, const char *path) { // deorphan if we haven't yet, needed at most once after poweron int err = lfs2_fs_forceconsistency(lfs2); if (err) { @@ -3872,7 +3941,9 @@ static int lfs2_rawremove(lfs2_t *lfs2, const char *path) { } lfs2->mlist = dir.next; - if (lfs2_tag_type3(tag) == LFS2_TYPE_DIR) { + if (lfs2_gstate_hasorphans(&lfs2->gstate)) { + LFS2_ASSERT(lfs2_tag_type3(tag) == LFS2_TYPE_DIR); + // fix orphan err = lfs2_fs_preporphans(lfs2, -1); if (err) { @@ -3895,7 +3966,7 @@ static int lfs2_rawremove(lfs2_t *lfs2, const char *path) { #endif #ifndef LFS2_READONLY -static int lfs2_rawrename(lfs2_t *lfs2, const char *oldpath, const char *newpath) { +static int lfs2_rename_(lfs2_t *lfs2, const char *oldpath, const char *newpath) { // deorphan if we haven't yet, needed at most once after poweron int err = lfs2_fs_forceconsistency(lfs2); if (err) { @@ -3914,7 +3985,7 @@ static int lfs2_rawrename(lfs2_t *lfs2, const char *oldpath, const char *newpath uint16_t newid; lfs2_stag_t prevtag = lfs2_dir_find(lfs2, &newcwd, &newpath, &newid); if ((prevtag < 0 || lfs2_tag_id(prevtag) == 0x3ff) && - !(prevtag == LFS2_ERR_NOENT && newid != 0x3ff)) { + !(prevtag == LFS2_ERR_NOENT && lfs2_path_islast(newpath))) { return (prevtag < 0) ? (int)prevtag : LFS2_ERR_INVAL; } @@ -3925,8 +3996,14 @@ static int lfs2_rawrename(lfs2_t *lfs2, const char *oldpath, const char *newpath struct lfs2_mlist prevdir; prevdir.next = lfs2->mlist; if (prevtag == LFS2_ERR_NOENT) { + // if we're a file, don't allow trailing slashes + if (lfs2_path_isdir(newpath) + && lfs2_tag_type3(oldtag) != LFS2_TYPE_DIR) { + return LFS2_ERR_NOTDIR; + } + // check that name fits - lfs2_size_t nlen = strlen(newpath); + lfs2_size_t nlen = lfs2_path_namelen(newpath); if (nlen > lfs2->name_max) { return LFS2_ERR_NAMETOOLONG; } @@ -3938,7 +4015,9 @@ static int lfs2_rawrename(lfs2_t *lfs2, const char *oldpath, const char *newpath newoldid += 1; } } else if (lfs2_tag_type3(prevtag) != lfs2_tag_type3(oldtag)) { - return LFS2_ERR_ISDIR; + return (lfs2_tag_type3(prevtag) == LFS2_TYPE_DIR) + ? LFS2_ERR_ISDIR + : LFS2_ERR_NOTDIR; } else if (samepair && newid == newoldid) { // we're renaming to ourselves?? return 0; @@ -3984,7 +4063,8 @@ static int lfs2_rawrename(lfs2_t *lfs2, const char *oldpath, const char *newpath {LFS2_MKTAG_IF(prevtag != LFS2_ERR_NOENT, LFS2_TYPE_DELETE, newid, 0), NULL}, {LFS2_MKTAG(LFS2_TYPE_CREATE, newid, 0), NULL}, - {LFS2_MKTAG(lfs2_tag_type3(oldtag), newid, strlen(newpath)), newpath}, + {LFS2_MKTAG(lfs2_tag_type3(oldtag), + newid, lfs2_path_namelen(newpath)), newpath}, {LFS2_MKTAG(LFS2_FROM_MOVE, newid, lfs2_tag_id(oldtag)), &oldcwd}, {LFS2_MKTAG_IF(samepair, LFS2_TYPE_DELETE, newoldid, 0), NULL})); @@ -4007,8 +4087,10 @@ static int lfs2_rawrename(lfs2_t *lfs2, const char *oldpath, const char *newpath } lfs2->mlist = prevdir.next; - if (prevtag != LFS2_ERR_NOENT - && lfs2_tag_type3(prevtag) == LFS2_TYPE_DIR) { + if (lfs2_gstate_hasorphans(&lfs2->gstate)) { + LFS2_ASSERT(prevtag != LFS2_ERR_NOENT + && lfs2_tag_type3(prevtag) == LFS2_TYPE_DIR); + // fix orphan err = lfs2_fs_preporphans(lfs2, -1); if (err) { @@ -4030,7 +4112,7 @@ static int lfs2_rawrename(lfs2_t *lfs2, const char *oldpath, const char *newpath } #endif -static lfs2_ssize_t lfs2_rawgetattr(lfs2_t *lfs2, const char *path, +static lfs2_ssize_t lfs2_getattr_(lfs2_t *lfs2, const char *path, uint8_t type, void *buffer, lfs2_size_t size) { lfs2_mdir_t cwd; lfs2_stag_t tag = lfs2_dir_find(lfs2, &cwd, &path, NULL); @@ -4088,7 +4170,7 @@ static int lfs2_commitattr(lfs2_t *lfs2, const char *path, #endif #ifndef LFS2_READONLY -static int lfs2_rawsetattr(lfs2_t *lfs2, const char *path, +static int lfs2_setattr_(lfs2_t *lfs2, const char *path, uint8_t type, const void *buffer, lfs2_size_t size) { if (size > lfs2->attr_max) { return LFS2_ERR_NOSPC; @@ -4099,13 +4181,28 @@ static int lfs2_rawsetattr(lfs2_t *lfs2, const char *path, #endif #ifndef LFS2_READONLY -static int lfs2_rawremoveattr(lfs2_t *lfs2, const char *path, uint8_t type) { +static int lfs2_removeattr_(lfs2_t *lfs2, const char *path, uint8_t type) { return lfs2_commitattr(lfs2, path, type, NULL, 0x3ff); } #endif /// Filesystem operations /// + +// compile time checks, see lfs2.h for why these limits exist +#if LFS2_NAME_MAX > 1022 +#error "Invalid LFS2_NAME_MAX, must be <= 1022" +#endif + +#if LFS2_FILE_MAX > 2147483647 +#error "Invalid LFS2_FILE_MAX, must be <= 2147483647" +#endif + +#if LFS2_ATTR_MAX > 1022 +#error "Invalid LFS2_ATTR_MAX, must be <= 1022" +#endif + +// common filesystem initialization static int lfs2_init(lfs2_t *lfs2, const struct lfs2_config *cfg) { lfs2->cfg = cfg; lfs2->block_count = cfg->block_count; // May be 0 @@ -4126,6 +4223,14 @@ static int lfs2_init(lfs2_t *lfs2, const struct lfs2_config *cfg) { // which littlefs currently does not support LFS2_ASSERT((bool)0x80000000); + // check that the required io functions are provided + LFS2_ASSERT(lfs2->cfg->read != NULL); +#ifndef LFS2_READONLY + LFS2_ASSERT(lfs2->cfg->prog != NULL); + LFS2_ASSERT(lfs2->cfg->erase != NULL); + LFS2_ASSERT(lfs2->cfg->sync != NULL); +#endif + // validate that the lfs2-cfg sizes were initiated properly before // performing any arithmetic logics with them LFS2_ASSERT(lfs2->cfg->read_size != 0); @@ -4153,6 +4258,23 @@ static int lfs2_init(lfs2_t *lfs2, const struct lfs2_config *cfg) { // wear-leveling. LFS2_ASSERT(lfs2->cfg->block_cycles != 0); + // check that compact_thresh makes sense + // + // metadata can't be compacted below block_size/2, and metadata can't + // exceed a block_size + LFS2_ASSERT(lfs2->cfg->compact_thresh == 0 + || lfs2->cfg->compact_thresh >= lfs2->cfg->block_size/2); + LFS2_ASSERT(lfs2->cfg->compact_thresh == (lfs2_size_t)-1 + || lfs2->cfg->compact_thresh <= lfs2->cfg->block_size); + + // check that metadata_max is a multiple of read_size and prog_size, + // and a factor of the block_size + LFS2_ASSERT(!lfs2->cfg->metadata_max + || lfs2->cfg->metadata_max % lfs2->cfg->read_size == 0); + LFS2_ASSERT(!lfs2->cfg->metadata_max + || lfs2->cfg->metadata_max % lfs2->cfg->prog_size == 0); + LFS2_ASSERT(!lfs2->cfg->metadata_max + || lfs2->cfg->block_size % lfs2->cfg->metadata_max == 0); // setup read cache if (lfs2->cfg->read_buffer) { @@ -4180,15 +4302,14 @@ static int lfs2_init(lfs2_t *lfs2, const struct lfs2_config *cfg) { lfs2_cache_zero(lfs2, &lfs2->rcache); lfs2_cache_zero(lfs2, &lfs2->pcache); - // setup lookahead, must be multiple of 64-bits, 32-bit aligned + // setup lookahead buffer, note mount finishes initializing this after + // we establish a decent pseudo-random seed LFS2_ASSERT(lfs2->cfg->lookahead_size > 0); - LFS2_ASSERT(lfs2->cfg->lookahead_size % 8 == 0 && - (uintptr_t)lfs2->cfg->lookahead_buffer % 4 == 0); if (lfs2->cfg->lookahead_buffer) { - lfs2->free.buffer = lfs2->cfg->lookahead_buffer; + lfs2->lookahead.buffer = lfs2->cfg->lookahead_buffer; } else { - lfs2->free.buffer = lfs2_malloc(lfs2->cfg->lookahead_size); - if (!lfs2->free.buffer) { + lfs2->lookahead.buffer = lfs2_malloc(lfs2->cfg->lookahead_size); + if (!lfs2->lookahead.buffer) { err = LFS2_ERR_NOMEM; goto cleanup; } @@ -4215,6 +4336,27 @@ static int lfs2_init(lfs2_t *lfs2, const struct lfs2_config *cfg) { LFS2_ASSERT(lfs2->cfg->metadata_max <= lfs2->cfg->block_size); + LFS2_ASSERT(lfs2->cfg->inline_max == (lfs2_size_t)-1 + || lfs2->cfg->inline_max <= lfs2->cfg->cache_size); + LFS2_ASSERT(lfs2->cfg->inline_max == (lfs2_size_t)-1 + || lfs2->cfg->inline_max <= lfs2->attr_max); + LFS2_ASSERT(lfs2->cfg->inline_max == (lfs2_size_t)-1 + || lfs2->cfg->inline_max <= ((lfs2->cfg->metadata_max) + ? lfs2->cfg->metadata_max + : lfs2->cfg->block_size)/8); + lfs2->inline_max = lfs2->cfg->inline_max; + if (lfs2->inline_max == (lfs2_size_t)-1) { + lfs2->inline_max = 0; + } else if (lfs2->inline_max == 0) { + lfs2->inline_max = lfs2_min( + lfs2->cfg->cache_size, + lfs2_min( + lfs2->attr_max, + ((lfs2->cfg->metadata_max) + ? lfs2->cfg->metadata_max + : lfs2->cfg->block_size)/8)); + } + // setup default state lfs2->root[0] = LFS2_BLOCK_NULL; lfs2->root[1] = LFS2_BLOCK_NULL; @@ -4245,7 +4387,7 @@ static int lfs2_deinit(lfs2_t *lfs2) { } if (!lfs2->cfg->lookahead_buffer) { - lfs2_free(lfs2->free.buffer); + lfs2_free(lfs2->lookahead.buffer); } return 0; @@ -4254,7 +4396,7 @@ static int lfs2_deinit(lfs2_t *lfs2) { #ifndef LFS2_READONLY -static int lfs2_rawformat(lfs2_t *lfs2, const struct lfs2_config *cfg) { +static int lfs2_format_(lfs2_t *lfs2, const struct lfs2_config *cfg) { int err = 0; { err = lfs2_init(lfs2, cfg); @@ -4265,12 +4407,12 @@ static int lfs2_rawformat(lfs2_t *lfs2, const struct lfs2_config *cfg) { LFS2_ASSERT(cfg->block_count != 0); // create free lookahead - memset(lfs2->free.buffer, 0, lfs2->cfg->lookahead_size); - lfs2->free.off = 0; - lfs2->free.size = lfs2_min(8*lfs2->cfg->lookahead_size, + memset(lfs2->lookahead.buffer, 0, lfs2->cfg->lookahead_size); + lfs2->lookahead.start = 0; + lfs2->lookahead.size = lfs2_min(8*lfs2->cfg->lookahead_size, lfs2->block_count); - lfs2->free.i = 0; - lfs2_alloc_ack(lfs2); + lfs2->lookahead.next = 0; + lfs2_alloc_ckpoint(lfs2); // create root dir lfs2_mdir_t root; @@ -4321,7 +4463,31 @@ static int lfs2_rawformat(lfs2_t *lfs2, const struct lfs2_config *cfg) { } #endif -static int lfs2_rawmount(lfs2_t *lfs2, const struct lfs2_config *cfg) { +struct lfs2_tortoise_t { + lfs2_block_t pair[2]; + lfs2_size_t i; + lfs2_size_t period; +}; + +static int lfs2_tortoise_detectcycles( + const lfs2_mdir_t *dir, struct lfs2_tortoise_t *tortoise) { + // detect cycles with Brent's algorithm + if (lfs2_pair_issync(dir->tail, tortoise->pair)) { + LFS2_WARN("Cycle detected in tail list"); + return LFS2_ERR_CORRUPT; + } + if (tortoise->i == tortoise->period) { + tortoise->pair[0] = dir->tail[0]; + tortoise->pair[1] = dir->tail[1]; + tortoise->i = 0; + tortoise->period *= 2; + } + tortoise->i += 1; + + return LFS2_ERR_OK; +} + +static int lfs2_mount_(lfs2_t *lfs2, const struct lfs2_config *cfg) { int err = lfs2_init(lfs2, cfg); if (err) { return err; @@ -4329,23 +4495,16 @@ static int lfs2_rawmount(lfs2_t *lfs2, const struct lfs2_config *cfg) { // scan directory blocks for superblock and any global updates lfs2_mdir_t dir = {.tail = {0, 1}}; - lfs2_block_t tortoise[2] = {LFS2_BLOCK_NULL, LFS2_BLOCK_NULL}; - lfs2_size_t tortoise_i = 1; - lfs2_size_t tortoise_period = 1; + struct lfs2_tortoise_t tortoise = { + .pair = {LFS2_BLOCK_NULL, LFS2_BLOCK_NULL}, + .i = 1, + .period = 1, + }; while (!lfs2_pair_isnull(dir.tail)) { - // detect cycles with Brent's algorithm - if (lfs2_pair_issync(dir.tail, tortoise)) { - LFS2_WARN("Cycle detected in tail list"); - err = LFS2_ERR_CORRUPT; + err = lfs2_tortoise_detectcycles(&dir, &tortoise); + if (err < 0) { goto cleanup; } - if (tortoise_i == tortoise_period) { - tortoise[0] = dir.tail[0]; - tortoise[1] = dir.tail[1]; - tortoise_i = 0; - tortoise_period *= 2; - } - tortoise_i += 1; // fetch next block in tail list lfs2_stag_t tag = lfs2_dir_fetchmatch(lfs2, &dir, dir.tail, @@ -4394,6 +4553,7 @@ static int lfs2_rawmount(lfs2_t *lfs2, const struct lfs2_config *cfg) { // found older minor version? set an in-device only bit in the // gstate so we know we need to rewrite the superblock before // the first write + bool needssuperblock = false; if (minor_version < lfs2_fs_disk_version_minor(lfs2)) { LFS2_DEBUG("Found older minor version " "v%"PRIu16".%"PRIu16" < v%"PRIu16".%"PRIu16, @@ -4401,10 +4561,11 @@ static int lfs2_rawmount(lfs2_t *lfs2, const struct lfs2_config *cfg) { minor_version, lfs2_fs_disk_version_major(lfs2), lfs2_fs_disk_version_minor(lfs2)); - // note this bit is reserved on disk, so fetching more gstate - // will not interfere here - lfs2_fs_prepsuperblock(lfs2, true); + needssuperblock = true; } + // note this bit is reserved on disk, so fetching more gstate + // will not interfere here + lfs2_fs_prepsuperblock(lfs2, needssuperblock); // check superblock configuration if (superblock.name_max) { @@ -4438,6 +4599,9 @@ static int lfs2_rawmount(lfs2_t *lfs2, const struct lfs2_config *cfg) { } lfs2->attr_max = superblock.attr_max; + + // we also need to update inline_max in case attr_max changed + lfs2->inline_max = lfs2_min(lfs2->inline_max, lfs2->attr_max); } // this is where we get the block_count from disk if block_count=0 @@ -4478,23 +4642,23 @@ static int lfs2_rawmount(lfs2_t *lfs2, const struct lfs2_config *cfg) { // setup free lookahead, to distribute allocations uniformly across // boots, we start the allocator at a random location - lfs2->free.off = lfs2->seed % lfs2->block_count; + lfs2->lookahead.start = lfs2->seed % lfs2->block_count; lfs2_alloc_drop(lfs2); return 0; cleanup: - lfs2_rawunmount(lfs2); + lfs2_unmount_(lfs2); return err; } -static int lfs2_rawunmount(lfs2_t *lfs2) { +static int lfs2_unmount_(lfs2_t *lfs2) { return lfs2_deinit(lfs2); } /// Filesystem filesystem operations /// -static int lfs2_fs_rawstat(lfs2_t *lfs2, struct lfs2_fsinfo *fsinfo) { +static int lfs2_fs_stat_(lfs2_t *lfs2, struct lfs2_fsinfo *fsinfo) { // if the superblock is up-to-date, we must be on the most recent // minor version of littlefs if (!lfs2_gstate_needssuperblock(&lfs2->gstate)) { @@ -4534,7 +4698,7 @@ static int lfs2_fs_rawstat(lfs2_t *lfs2, struct lfs2_fsinfo *fsinfo) { return 0; } -int lfs2_fs_rawtraverse(lfs2_t *lfs2, +int lfs2_fs_traverse_(lfs2_t *lfs2, int (*cb)(void *data, lfs2_block_t block), void *data, bool includeorphans) { // iterate over metadata pairs @@ -4553,22 +4717,17 @@ int lfs2_fs_rawtraverse(lfs2_t *lfs2, } #endif - lfs2_block_t tortoise[2] = {LFS2_BLOCK_NULL, LFS2_BLOCK_NULL}; - lfs2_size_t tortoise_i = 1; - lfs2_size_t tortoise_period = 1; + struct lfs2_tortoise_t tortoise = { + .pair = {LFS2_BLOCK_NULL, LFS2_BLOCK_NULL}, + .i = 1, + .period = 1, + }; + int err = LFS2_ERR_OK; while (!lfs2_pair_isnull(dir.tail)) { - // detect cycles with Brent's algorithm - if (lfs2_pair_issync(dir.tail, tortoise)) { - LFS2_WARN("Cycle detected in tail list"); + err = lfs2_tortoise_detectcycles(&dir, &tortoise); + if (err < 0) { return LFS2_ERR_CORRUPT; } - if (tortoise_i == tortoise_period) { - tortoise[0] = dir.tail[0]; - tortoise[1] = dir.tail[1]; - tortoise_i = 0; - tortoise_period *= 2; - } - tortoise_i += 1; for (int i = 0; i < 2; i++) { int err = cb(data, dir.tail[i]); @@ -4620,7 +4779,8 @@ int lfs2_fs_rawtraverse(lfs2_t *lfs2, continue; } - if ((f->flags & LFS2_F_DIRTY) && !(f->flags & LFS2_F_INLINE)) { + if (((f->flags & LFS2_F_DIRTY) || (f->flags & LFS2_F_DUSTY)) + && !(f->flags & LFS2_F_INLINE)) { int err = lfs2_ctz_traverse(lfs2, &f->cache, &lfs2->rcache, f->ctz.head, f->ctz.size, cb, data); if (err) { @@ -4647,22 +4807,17 @@ static int lfs2_fs_pred(lfs2_t *lfs2, // iterate over all directory directory entries pdir->tail[0] = 0; pdir->tail[1] = 1; - lfs2_block_t tortoise[2] = {LFS2_BLOCK_NULL, LFS2_BLOCK_NULL}; - lfs2_size_t tortoise_i = 1; - lfs2_size_t tortoise_period = 1; + struct lfs2_tortoise_t tortoise = { + .pair = {LFS2_BLOCK_NULL, LFS2_BLOCK_NULL}, + .i = 1, + .period = 1, + }; + int err = LFS2_ERR_OK; while (!lfs2_pair_isnull(pdir->tail)) { - // detect cycles with Brent's algorithm - if (lfs2_pair_issync(pdir->tail, tortoise)) { - LFS2_WARN("Cycle detected in tail list"); + err = lfs2_tortoise_detectcycles(pdir, &tortoise); + if (err < 0) { return LFS2_ERR_CORRUPT; } - if (tortoise_i == tortoise_period) { - tortoise[0] = pdir->tail[0]; - tortoise[1] = pdir->tail[1]; - tortoise_i = 0; - tortoise_period *= 2; - } - tortoise_i += 1; if (lfs2_pair_cmp(pdir->tail, pair) == 0) { return 0; @@ -4712,22 +4867,17 @@ static lfs2_stag_t lfs2_fs_parent(lfs2_t *lfs2, const lfs2_block_t pair[2], // use fetchmatch with callback to find pairs parent->tail[0] = 0; parent->tail[1] = 1; - lfs2_block_t tortoise[2] = {LFS2_BLOCK_NULL, LFS2_BLOCK_NULL}; - lfs2_size_t tortoise_i = 1; - lfs2_size_t tortoise_period = 1; + struct lfs2_tortoise_t tortoise = { + .pair = {LFS2_BLOCK_NULL, LFS2_BLOCK_NULL}, + .i = 1, + .period = 1, + }; + int err = LFS2_ERR_OK; while (!lfs2_pair_isnull(parent->tail)) { - // detect cycles with Brent's algorithm - if (lfs2_pair_issync(parent->tail, tortoise)) { - LFS2_WARN("Cycle detected in tail list"); - return LFS2_ERR_CORRUPT; - } - if (tortoise_i == tortoise_period) { - tortoise[0] = parent->tail[0]; - tortoise[1] = parent->tail[1]; - tortoise_i = 0; - tortoise_period *= 2; + err = lfs2_tortoise_detectcycles(parent, &tortoise); + if (err < 0) { + return err; } - tortoise_i += 1; lfs2_stag_t tag = lfs2_dir_fetchmatch(lfs2, parent, parent->tail, LFS2_MKTAG(0x7ff, 0, 0x3ff), @@ -4999,7 +5149,7 @@ static int lfs2_fs_forceconsistency(lfs2_t *lfs2) { #endif #ifndef LFS2_READONLY -static int lfs2_fs_rawmkconsistent(lfs2_t *lfs2) { +static int lfs2_fs_mkconsistent_(lfs2_t *lfs2) { // lfs2_fs_forceconsistency does most of the work here int err = lfs2_fs_forceconsistency(lfs2); if (err) { @@ -5035,9 +5185,9 @@ static int lfs2_fs_size_count(void *p, lfs2_block_t block) { return 0; } -static lfs2_ssize_t lfs2_fs_rawsize(lfs2_t *lfs2) { +static lfs2_ssize_t lfs2_fs_size_(lfs2_t *lfs2) { lfs2_size_t size = 0; - int err = lfs2_fs_rawtraverse(lfs2, lfs2_fs_size_count, &size, false); + int err = lfs2_fs_traverse_(lfs2, lfs2_fs_size_count, &size, false); if (err) { return err; } @@ -5045,41 +5195,118 @@ static lfs2_ssize_t lfs2_fs_rawsize(lfs2_t *lfs2) { return size; } +// explicit garbage collection #ifndef LFS2_READONLY -static int lfs2_fs_rawgrow(lfs2_t *lfs2, lfs2_size_t block_count) { - // shrinking is not supported - LFS2_ASSERT(block_count >= lfs2->block_count); +static int lfs2_fs_gc_(lfs2_t *lfs2) { + // force consistency, even if we're not necessarily going to write, + // because this function is supposed to take care of janitorial work + // isn't it? + int err = lfs2_fs_forceconsistency(lfs2); + if (err) { + return err; + } + + // try to compact metadata pairs, note we can't really accomplish + // anything if compact_thresh doesn't at least leave a prog_size + // available + if (lfs2->cfg->compact_thresh + < lfs2->cfg->block_size - lfs2->cfg->prog_size) { + // iterate over all mdirs + lfs2_mdir_t mdir = {.tail = {0, 1}}; + while (!lfs2_pair_isnull(mdir.tail)) { + err = lfs2_dir_fetch(lfs2, &mdir, mdir.tail); + if (err) { + return err; + } - if (block_count > lfs2->block_count) { - lfs2->block_count = block_count; + // not erased? exceeds our compaction threshold? + if (!mdir.erased || ((lfs2->cfg->compact_thresh == 0) + ? mdir.off > lfs2->cfg->block_size - lfs2->cfg->block_size/8 + : mdir.off > lfs2->cfg->compact_thresh)) { + // the easiest way to trigger a compaction is to mark + // the mdir as unerased and add an empty commit + mdir.erased = false; + err = lfs2_dir_commit(lfs2, &mdir, NULL, 0); + if (err) { + return err; + } + } + } + } - // fetch the root - lfs2_mdir_t root; - int err = lfs2_dir_fetch(lfs2, &root, lfs2->root); + // try to populate the lookahead buffer, unless it's already full + if (lfs2->lookahead.size < lfs2_min( + 8 * lfs2->cfg->lookahead_size, + lfs2->block_count)) { + err = lfs2_alloc_scan(lfs2); if (err) { return err; } + } - // update the superblock - lfs2_superblock_t superblock; - lfs2_stag_t tag = lfs2_dir_get(lfs2, &root, LFS2_MKTAG(0x7ff, 0x3ff, 0), - LFS2_MKTAG(LFS2_TYPE_INLINESTRUCT, 0, sizeof(superblock)), - &superblock); - if (tag < 0) { - return tag; - } - lfs2_superblock_fromle32(&superblock); + return 0; +} +#endif - superblock.block_count = lfs2->block_count; +#ifndef LFS2_READONLY +#ifdef LFS2_SHRINKNONRELOCATING +static int lfs2_shrink_checkblock(void *data, lfs2_block_t block) { + lfs2_size_t threshold = *((lfs2_size_t*)data); + if (block >= threshold) { + return LFS2_ERR_NOTEMPTY; + } + return 0; +} +#endif - lfs2_superblock_tole32(&superblock); - err = lfs2_dir_commit(lfs2, &root, LFS2_MKATTRS( - {tag, &superblock})); +static int lfs2_fs_grow_(lfs2_t *lfs2, lfs2_size_t block_count) { + int err; + + if (block_count == lfs2->block_count) { + return 0; + } + + +#ifndef LFS2_SHRINKNONRELOCATING + // shrinking is not supported + LFS2_ASSERT(block_count >= lfs2->block_count); +#endif +#ifdef LFS2_SHRINKNONRELOCATING + if (block_count < lfs2->block_count) { + err = lfs2_fs_traverse_(lfs2, lfs2_shrink_checkblock, &block_count, true); if (err) { return err; } } +#endif + + lfs2->block_count = block_count; + + // fetch the root + lfs2_mdir_t root; + err = lfs2_dir_fetch(lfs2, &root, lfs2->root); + if (err) { + return err; + } + // update the superblock + lfs2_superblock_t superblock; + lfs2_stag_t tag = lfs2_dir_get(lfs2, &root, LFS2_MKTAG(0x7ff, 0x3ff, 0), + LFS2_MKTAG(LFS2_TYPE_INLINESTRUCT, 0, sizeof(superblock)), + &superblock); + if (tag < 0) { + return tag; + } + lfs2_superblock_fromle32(&superblock); + + superblock.block_count = lfs2->block_count; + + lfs2_superblock_tole32(&superblock); + err = lfs2_dir_commit(lfs2, &root, LFS2_MKATTRS( + {tag, &superblock})); + if (err) { + return err; + } return 0; } #endif @@ -5451,10 +5678,10 @@ static int lfs21_mount(lfs2_t *lfs2, struct lfs21 *lfs21, lfs2->lfs21->root[1] = LFS2_BLOCK_NULL; // setup free lookahead - lfs2->free.off = 0; - lfs2->free.size = 0; - lfs2->free.i = 0; - lfs2_alloc_ack(lfs2); + lfs2->lookahead.start = 0; + lfs2->lookahead.size = 0; + lfs2->lookahead.next = 0; + lfs2_alloc_ckpoint(lfs2); // load superblock lfs21_dir_t dir; @@ -5505,7 +5732,7 @@ static int lfs21_unmount(lfs2_t *lfs2) { } /// v1 migration /// -static int lfs2_rawmigrate(lfs2_t *lfs2, const struct lfs2_config *cfg) { +static int lfs2_migrate_(lfs2_t *lfs2, const struct lfs2_config *cfg) { struct lfs21 lfs21; // Indeterminate filesystem size not allowed for migration. @@ -5759,7 +5986,7 @@ int lfs2_format(lfs2_t *lfs2, const struct lfs2_config *cfg) { ".read=%p, .prog=%p, .erase=%p, .sync=%p, " ".read_size=%"PRIu32", .prog_size=%"PRIu32", " ".block_size=%"PRIu32", .block_count=%"PRIu32", " - ".block_cycles=%"PRIu32", .cache_size=%"PRIu32", " + ".block_cycles=%"PRId32", .cache_size=%"PRIu32", " ".lookahead_size=%"PRIu32", .read_buffer=%p, " ".prog_buffer=%p, .lookahead_buffer=%p, " ".name_max=%"PRIu32", .file_max=%"PRIu32", " @@ -5772,7 +5999,7 @@ int lfs2_format(lfs2_t *lfs2, const struct lfs2_config *cfg) { cfg->read_buffer, cfg->prog_buffer, cfg->lookahead_buffer, cfg->name_max, cfg->file_max, cfg->attr_max); - err = lfs2_rawformat(lfs2, cfg); + err = lfs2_format_(lfs2, cfg); LFS2_TRACE("lfs2_format -> %d", err); LFS2_UNLOCK(cfg); @@ -5789,7 +6016,7 @@ int lfs2_mount(lfs2_t *lfs2, const struct lfs2_config *cfg) { ".read=%p, .prog=%p, .erase=%p, .sync=%p, " ".read_size=%"PRIu32", .prog_size=%"PRIu32", " ".block_size=%"PRIu32", .block_count=%"PRIu32", " - ".block_cycles=%"PRIu32", .cache_size=%"PRIu32", " + ".block_cycles=%"PRId32", .cache_size=%"PRIu32", " ".lookahead_size=%"PRIu32", .read_buffer=%p, " ".prog_buffer=%p, .lookahead_buffer=%p, " ".name_max=%"PRIu32", .file_max=%"PRIu32", " @@ -5802,7 +6029,7 @@ int lfs2_mount(lfs2_t *lfs2, const struct lfs2_config *cfg) { cfg->read_buffer, cfg->prog_buffer, cfg->lookahead_buffer, cfg->name_max, cfg->file_max, cfg->attr_max); - err = lfs2_rawmount(lfs2, cfg); + err = lfs2_mount_(lfs2, cfg); LFS2_TRACE("lfs2_mount -> %d", err); LFS2_UNLOCK(cfg); @@ -5816,7 +6043,7 @@ int lfs2_unmount(lfs2_t *lfs2) { } LFS2_TRACE("lfs2_unmount(%p)", (void*)lfs2); - err = lfs2_rawunmount(lfs2); + err = lfs2_unmount_(lfs2); LFS2_TRACE("lfs2_unmount -> %d", err); LFS2_UNLOCK(lfs2->cfg); @@ -5831,7 +6058,7 @@ int lfs2_remove(lfs2_t *lfs2, const char *path) { } LFS2_TRACE("lfs2_remove(%p, \"%s\")", (void*)lfs2, path); - err = lfs2_rawremove(lfs2, path); + err = lfs2_remove_(lfs2, path); LFS2_TRACE("lfs2_remove -> %d", err); LFS2_UNLOCK(lfs2->cfg); @@ -5847,7 +6074,7 @@ int lfs2_rename(lfs2_t *lfs2, const char *oldpath, const char *newpath) { } LFS2_TRACE("lfs2_rename(%p, \"%s\", \"%s\")", (void*)lfs2, oldpath, newpath); - err = lfs2_rawrename(lfs2, oldpath, newpath); + err = lfs2_rename_(lfs2, oldpath, newpath); LFS2_TRACE("lfs2_rename -> %d", err); LFS2_UNLOCK(lfs2->cfg); @@ -5862,7 +6089,7 @@ int lfs2_stat(lfs2_t *lfs2, const char *path, struct lfs2_info *info) { } LFS2_TRACE("lfs2_stat(%p, \"%s\", %p)", (void*)lfs2, path, (void*)info); - err = lfs2_rawstat(lfs2, path, info); + err = lfs2_stat_(lfs2, path, info); LFS2_TRACE("lfs2_stat -> %d", err); LFS2_UNLOCK(lfs2->cfg); @@ -5878,7 +6105,7 @@ lfs2_ssize_t lfs2_getattr(lfs2_t *lfs2, const char *path, LFS2_TRACE("lfs2_getattr(%p, \"%s\", %"PRIu8", %p, %"PRIu32")", (void*)lfs2, path, type, buffer, size); - lfs2_ssize_t res = lfs2_rawgetattr(lfs2, path, type, buffer, size); + lfs2_ssize_t res = lfs2_getattr_(lfs2, path, type, buffer, size); LFS2_TRACE("lfs2_getattr -> %"PRId32, res); LFS2_UNLOCK(lfs2->cfg); @@ -5895,7 +6122,7 @@ int lfs2_setattr(lfs2_t *lfs2, const char *path, LFS2_TRACE("lfs2_setattr(%p, \"%s\", %"PRIu8", %p, %"PRIu32")", (void*)lfs2, path, type, buffer, size); - err = lfs2_rawsetattr(lfs2, path, type, buffer, size); + err = lfs2_setattr_(lfs2, path, type, buffer, size); LFS2_TRACE("lfs2_setattr -> %d", err); LFS2_UNLOCK(lfs2->cfg); @@ -5911,7 +6138,7 @@ int lfs2_removeattr(lfs2_t *lfs2, const char *path, uint8_t type) { } LFS2_TRACE("lfs2_removeattr(%p, \"%s\", %"PRIu8")", (void*)lfs2, path, type); - err = lfs2_rawremoveattr(lfs2, path, type); + err = lfs2_removeattr_(lfs2, path, type); LFS2_TRACE("lfs2_removeattr -> %d", err); LFS2_UNLOCK(lfs2->cfg); @@ -5926,10 +6153,10 @@ int lfs2_file_open(lfs2_t *lfs2, lfs2_file_t *file, const char *path, int flags) return err; } LFS2_TRACE("lfs2_file_open(%p, %p, \"%s\", %x)", - (void*)lfs2, (void*)file, path, flags); + (void*)lfs2, (void*)file, path, (unsigned)flags); LFS2_ASSERT(!lfs2_mlist_isopen(lfs2->mlist, (struct lfs2_mlist*)file)); - err = lfs2_file_rawopen(lfs2, file, path, flags); + err = lfs2_file_open_(lfs2, file, path, flags); LFS2_TRACE("lfs2_file_open -> %d", err); LFS2_UNLOCK(lfs2->cfg); @@ -5946,11 +6173,11 @@ int lfs2_file_opencfg(lfs2_t *lfs2, lfs2_file_t *file, } LFS2_TRACE("lfs2_file_opencfg(%p, %p, \"%s\", %x, %p {" ".buffer=%p, .attrs=%p, .attr_count=%"PRIu32"})", - (void*)lfs2, (void*)file, path, flags, + (void*)lfs2, (void*)file, path, (unsigned)flags, (void*)cfg, cfg->buffer, (void*)cfg->attrs, cfg->attr_count); LFS2_ASSERT(!lfs2_mlist_isopen(lfs2->mlist, (struct lfs2_mlist*)file)); - err = lfs2_file_rawopencfg(lfs2, file, path, flags, cfg); + err = lfs2_file_opencfg_(lfs2, file, path, flags, cfg); LFS2_TRACE("lfs2_file_opencfg -> %d", err); LFS2_UNLOCK(lfs2->cfg); @@ -5965,7 +6192,7 @@ int lfs2_file_close(lfs2_t *lfs2, lfs2_file_t *file) { LFS2_TRACE("lfs2_file_close(%p, %p)", (void*)lfs2, (void*)file); LFS2_ASSERT(lfs2_mlist_isopen(lfs2->mlist, (struct lfs2_mlist*)file)); - err = lfs2_file_rawclose(lfs2, file); + err = lfs2_file_close_(lfs2, file); LFS2_TRACE("lfs2_file_close -> %d", err); LFS2_UNLOCK(lfs2->cfg); @@ -5981,7 +6208,7 @@ int lfs2_file_sync(lfs2_t *lfs2, lfs2_file_t *file) { LFS2_TRACE("lfs2_file_sync(%p, %p)", (void*)lfs2, (void*)file); LFS2_ASSERT(lfs2_mlist_isopen(lfs2->mlist, (struct lfs2_mlist*)file)); - err = lfs2_file_rawsync(lfs2, file); + err = lfs2_file_sync_(lfs2, file); LFS2_TRACE("lfs2_file_sync -> %d", err); LFS2_UNLOCK(lfs2->cfg); @@ -5999,7 +6226,7 @@ lfs2_ssize_t lfs2_file_read(lfs2_t *lfs2, lfs2_file_t *file, (void*)lfs2, (void*)file, buffer, size); LFS2_ASSERT(lfs2_mlist_isopen(lfs2->mlist, (struct lfs2_mlist*)file)); - lfs2_ssize_t res = lfs2_file_rawread(lfs2, file, buffer, size); + lfs2_ssize_t res = lfs2_file_read_(lfs2, file, buffer, size); LFS2_TRACE("lfs2_file_read -> %"PRId32, res); LFS2_UNLOCK(lfs2->cfg); @@ -6017,7 +6244,7 @@ lfs2_ssize_t lfs2_file_write(lfs2_t *lfs2, lfs2_file_t *file, (void*)lfs2, (void*)file, buffer, size); LFS2_ASSERT(lfs2_mlist_isopen(lfs2->mlist, (struct lfs2_mlist*)file)); - lfs2_ssize_t res = lfs2_file_rawwrite(lfs2, file, buffer, size); + lfs2_ssize_t res = lfs2_file_write_(lfs2, file, buffer, size); LFS2_TRACE("lfs2_file_write -> %"PRId32, res); LFS2_UNLOCK(lfs2->cfg); @@ -6035,7 +6262,7 @@ lfs2_soff_t lfs2_file_seek(lfs2_t *lfs2, lfs2_file_t *file, (void*)lfs2, (void*)file, off, whence); LFS2_ASSERT(lfs2_mlist_isopen(lfs2->mlist, (struct lfs2_mlist*)file)); - lfs2_soff_t res = lfs2_file_rawseek(lfs2, file, off, whence); + lfs2_soff_t res = lfs2_file_seek_(lfs2, file, off, whence); LFS2_TRACE("lfs2_file_seek -> %"PRId32, res); LFS2_UNLOCK(lfs2->cfg); @@ -6052,7 +6279,7 @@ int lfs2_file_truncate(lfs2_t *lfs2, lfs2_file_t *file, lfs2_off_t size) { (void*)lfs2, (void*)file, size); LFS2_ASSERT(lfs2_mlist_isopen(lfs2->mlist, (struct lfs2_mlist*)file)); - err = lfs2_file_rawtruncate(lfs2, file, size); + err = lfs2_file_truncate_(lfs2, file, size); LFS2_TRACE("lfs2_file_truncate -> %d", err); LFS2_UNLOCK(lfs2->cfg); @@ -6068,7 +6295,7 @@ lfs2_soff_t lfs2_file_tell(lfs2_t *lfs2, lfs2_file_t *file) { LFS2_TRACE("lfs2_file_tell(%p, %p)", (void*)lfs2, (void*)file); LFS2_ASSERT(lfs2_mlist_isopen(lfs2->mlist, (struct lfs2_mlist*)file)); - lfs2_soff_t res = lfs2_file_rawtell(lfs2, file); + lfs2_soff_t res = lfs2_file_tell_(lfs2, file); LFS2_TRACE("lfs2_file_tell -> %"PRId32, res); LFS2_UNLOCK(lfs2->cfg); @@ -6082,7 +6309,7 @@ int lfs2_file_rewind(lfs2_t *lfs2, lfs2_file_t *file) { } LFS2_TRACE("lfs2_file_rewind(%p, %p)", (void*)lfs2, (void*)file); - err = lfs2_file_rawrewind(lfs2, file); + err = lfs2_file_rewind_(lfs2, file); LFS2_TRACE("lfs2_file_rewind -> %d", err); LFS2_UNLOCK(lfs2->cfg); @@ -6097,9 +6324,9 @@ lfs2_soff_t lfs2_file_size(lfs2_t *lfs2, lfs2_file_t *file) { LFS2_TRACE("lfs2_file_size(%p, %p)", (void*)lfs2, (void*)file); LFS2_ASSERT(lfs2_mlist_isopen(lfs2->mlist, (struct lfs2_mlist*)file)); - lfs2_soff_t res = lfs2_file_rawsize(lfs2, file); + lfs2_soff_t res = lfs2_file_size_(lfs2, file); - LFS2_TRACE("lfs2_file_size -> %"PRId32, res); + LFS2_TRACE("lfs2_file_size -> %"PRIu32, res); LFS2_UNLOCK(lfs2->cfg); return res; } @@ -6112,7 +6339,7 @@ int lfs2_mkdir(lfs2_t *lfs2, const char *path) { } LFS2_TRACE("lfs2_mkdir(%p, \"%s\")", (void*)lfs2, path); - err = lfs2_rawmkdir(lfs2, path); + err = lfs2_mkdir_(lfs2, path); LFS2_TRACE("lfs2_mkdir -> %d", err); LFS2_UNLOCK(lfs2->cfg); @@ -6128,7 +6355,7 @@ int lfs2_dir_open(lfs2_t *lfs2, lfs2_dir_t *dir, const char *path) { LFS2_TRACE("lfs2_dir_open(%p, %p, \"%s\")", (void*)lfs2, (void*)dir, path); LFS2_ASSERT(!lfs2_mlist_isopen(lfs2->mlist, (struct lfs2_mlist*)dir)); - err = lfs2_dir_rawopen(lfs2, dir, path); + err = lfs2_dir_open_(lfs2, dir, path); LFS2_TRACE("lfs2_dir_open -> %d", err); LFS2_UNLOCK(lfs2->cfg); @@ -6142,7 +6369,7 @@ int lfs2_dir_close(lfs2_t *lfs2, lfs2_dir_t *dir) { } LFS2_TRACE("lfs2_dir_close(%p, %p)", (void*)lfs2, (void*)dir); - err = lfs2_dir_rawclose(lfs2, dir); + err = lfs2_dir_close_(lfs2, dir); LFS2_TRACE("lfs2_dir_close -> %d", err); LFS2_UNLOCK(lfs2->cfg); @@ -6157,7 +6384,7 @@ int lfs2_dir_read(lfs2_t *lfs2, lfs2_dir_t *dir, struct lfs2_info *info) { LFS2_TRACE("lfs2_dir_read(%p, %p, %p)", (void*)lfs2, (void*)dir, (void*)info); - err = lfs2_dir_rawread(lfs2, dir, info); + err = lfs2_dir_read_(lfs2, dir, info); LFS2_TRACE("lfs2_dir_read -> %d", err); LFS2_UNLOCK(lfs2->cfg); @@ -6172,7 +6399,7 @@ int lfs2_dir_seek(lfs2_t *lfs2, lfs2_dir_t *dir, lfs2_off_t off) { LFS2_TRACE("lfs2_dir_seek(%p, %p, %"PRIu32")", (void*)lfs2, (void*)dir, off); - err = lfs2_dir_rawseek(lfs2, dir, off); + err = lfs2_dir_seek_(lfs2, dir, off); LFS2_TRACE("lfs2_dir_seek -> %d", err); LFS2_UNLOCK(lfs2->cfg); @@ -6186,7 +6413,7 @@ lfs2_soff_t lfs2_dir_tell(lfs2_t *lfs2, lfs2_dir_t *dir) { } LFS2_TRACE("lfs2_dir_tell(%p, %p)", (void*)lfs2, (void*)dir); - lfs2_soff_t res = lfs2_dir_rawtell(lfs2, dir); + lfs2_soff_t res = lfs2_dir_tell_(lfs2, dir); LFS2_TRACE("lfs2_dir_tell -> %"PRId32, res); LFS2_UNLOCK(lfs2->cfg); @@ -6200,7 +6427,7 @@ int lfs2_dir_rewind(lfs2_t *lfs2, lfs2_dir_t *dir) { } LFS2_TRACE("lfs2_dir_rewind(%p, %p)", (void*)lfs2, (void*)dir); - err = lfs2_dir_rawrewind(lfs2, dir); + err = lfs2_dir_rewind_(lfs2, dir); LFS2_TRACE("lfs2_dir_rewind -> %d", err); LFS2_UNLOCK(lfs2->cfg); @@ -6214,7 +6441,7 @@ int lfs2_fs_stat(lfs2_t *lfs2, struct lfs2_fsinfo *fsinfo) { } LFS2_TRACE("lfs2_fs_stat(%p, %p)", (void*)lfs2, (void*)fsinfo); - err = lfs2_fs_rawstat(lfs2, fsinfo); + err = lfs2_fs_stat_(lfs2, fsinfo); LFS2_TRACE("lfs2_fs_stat -> %d", err); LFS2_UNLOCK(lfs2->cfg); @@ -6228,7 +6455,7 @@ lfs2_ssize_t lfs2_fs_size(lfs2_t *lfs2) { } LFS2_TRACE("lfs2_fs_size(%p)", (void*)lfs2); - lfs2_ssize_t res = lfs2_fs_rawsize(lfs2); + lfs2_ssize_t res = lfs2_fs_size_(lfs2); LFS2_TRACE("lfs2_fs_size -> %"PRId32, res); LFS2_UNLOCK(lfs2->cfg); @@ -6243,7 +6470,7 @@ int lfs2_fs_traverse(lfs2_t *lfs2, int (*cb)(void *, lfs2_block_t), void *data) LFS2_TRACE("lfs2_fs_traverse(%p, %p, %p)", (void*)lfs2, (void*)(uintptr_t)cb, data); - err = lfs2_fs_rawtraverse(lfs2, cb, data, true); + err = lfs2_fs_traverse_(lfs2, cb, data, true); LFS2_TRACE("lfs2_fs_traverse -> %d", err); LFS2_UNLOCK(lfs2->cfg); @@ -6251,32 +6478,32 @@ int lfs2_fs_traverse(lfs2_t *lfs2, int (*cb)(void *, lfs2_block_t), void *data) } #ifndef LFS2_READONLY -int lfs2_fs_gc(lfs2_t *lfs2) { +int lfs2_fs_mkconsistent(lfs2_t *lfs2) { int err = LFS2_LOCK(lfs2->cfg); if (err) { return err; } - LFS2_TRACE("lfs2_fs_gc(%p)", (void*)lfs2); + LFS2_TRACE("lfs2_fs_mkconsistent(%p)", (void*)lfs2); - err = lfs2_fs_rawgc(lfs2); + err = lfs2_fs_mkconsistent_(lfs2); - LFS2_TRACE("lfs2_fs_gc -> %d", err); + LFS2_TRACE("lfs2_fs_mkconsistent -> %d", err); LFS2_UNLOCK(lfs2->cfg); return err; } #endif #ifndef LFS2_READONLY -int lfs2_fs_mkconsistent(lfs2_t *lfs2) { +int lfs2_fs_gc(lfs2_t *lfs2) { int err = LFS2_LOCK(lfs2->cfg); if (err) { return err; } - LFS2_TRACE("lfs2_fs_mkconsistent(%p)", (void*)lfs2); + LFS2_TRACE("lfs2_fs_gc(%p)", (void*)lfs2); - err = lfs2_fs_rawmkconsistent(lfs2); + err = lfs2_fs_gc_(lfs2); - LFS2_TRACE("lfs2_fs_mkconsistent -> %d", err); + LFS2_TRACE("lfs2_fs_gc -> %d", err); LFS2_UNLOCK(lfs2->cfg); return err; } @@ -6290,7 +6517,7 @@ int lfs2_fs_grow(lfs2_t *lfs2, lfs2_size_t block_count) { } LFS2_TRACE("lfs2_fs_grow(%p, %"PRIu32")", (void*)lfs2, block_count); - err = lfs2_fs_rawgrow(lfs2, block_count); + err = lfs2_fs_grow_(lfs2, block_count); LFS2_TRACE("lfs2_fs_grow -> %d", err); LFS2_UNLOCK(lfs2->cfg); @@ -6308,7 +6535,7 @@ int lfs2_migrate(lfs2_t *lfs2, const struct lfs2_config *cfg) { ".read=%p, .prog=%p, .erase=%p, .sync=%p, " ".read_size=%"PRIu32", .prog_size=%"PRIu32", " ".block_size=%"PRIu32", .block_count=%"PRIu32", " - ".block_cycles=%"PRIu32", .cache_size=%"PRIu32", " + ".block_cycles=%"PRId32", .cache_size=%"PRIu32", " ".lookahead_size=%"PRIu32", .read_buffer=%p, " ".prog_buffer=%p, .lookahead_buffer=%p, " ".name_max=%"PRIu32", .file_max=%"PRIu32", " @@ -6321,7 +6548,7 @@ int lfs2_migrate(lfs2_t *lfs2, const struct lfs2_config *cfg) { cfg->read_buffer, cfg->prog_buffer, cfg->lookahead_buffer, cfg->name_max, cfg->file_max, cfg->attr_max); - err = lfs2_rawmigrate(lfs2, cfg); + err = lfs2_migrate_(lfs2, cfg); LFS2_TRACE("lfs2_migrate -> %d", err); LFS2_UNLOCK(cfg); diff --git a/lib/littlefs/lfs2.h b/lib/littlefs/lfs2.h index 559ccebac92..53f2a1569ee 100644 --- a/lib/littlefs/lfs2.h +++ b/lib/littlefs/lfs2.h @@ -21,7 +21,7 @@ extern "C" // Software library version // Major (top-nibble), incremented on backwards incompatible changes // Minor (bottom-nibble), incremented on feature additions -#define LFS2_VERSION 0x00020008 +#define LFS2_VERSION 0x0002000b #define LFS2_VERSION_MAJOR (0xffff & (LFS2_VERSION >> 16)) #define LFS2_VERSION_MINOR (0xffff & (LFS2_VERSION >> 0)) @@ -52,16 +52,15 @@ typedef uint32_t lfs2_block_t; #endif // Maximum size of a file in bytes, may be redefined to limit to support other -// drivers. Limited on disk to <= 4294967296. However, above 2147483647 the -// functions lfs2_file_seek, lfs2_file_size, and lfs2_file_tell will return -// incorrect values due to using signed integers. Stored in superblock and -// must be respected by other littlefs drivers. +// drivers. Limited on disk to <= 2147483647. Stored in superblock and must be +// respected by other littlefs drivers. #ifndef LFS2_FILE_MAX #define LFS2_FILE_MAX 2147483647 #endif // Maximum size of custom attributes in bytes, may be redefined, but there is -// no real benefit to using a smaller LFS2_ATTR_MAX. Limited to <= 1022. +// no real benefit to using a smaller LFS2_ATTR_MAX. Limited to <= 1022. Stored +// in superblock and must be respected by other littlefs drivers. #ifndef LFS2_ATTR_MAX #define LFS2_ATTR_MAX 1022 #endif @@ -136,14 +135,15 @@ enum lfs2_open_flags { // internally used flags #ifndef LFS2_READONLY - LFS2_F_DIRTY = 0x010000, // File does not match storage - LFS2_F_WRITING = 0x020000, // File has been written since last flush + LFS2_F_DIRTY = 0x00010000, // File does not match storage due to write + LFS2_F_DUSTY = 0x00020000, // File does not match storage due to desync + LFS2_F_WRITING = 0x00040000, // File has been written since last flush #endif - LFS2_F_READING = 0x040000, // File has been read since last flush + LFS2_F_READING = 0x00080000, // File has been read since last flush #ifndef LFS2_READONLY - LFS2_F_ERRED = 0x080000, // An error occurred during write + LFS2_F_ERRED = 0x00100000, // An error occurred during write #endif - LFS2_F_INLINE = 0x100000, // Currently inlined in directory entry + LFS2_F_INLINE = 0x01000000, // Currently inlined in directory entry }; // File seek flags @@ -205,7 +205,8 @@ struct lfs2_config { // program sizes. lfs2_size_t block_size; - // Number of erasable blocks on the device. + // Number of erasable blocks on the device. Defaults to block_count stored + // on disk when zero. lfs2_size_t block_count; // Number of erase cycles before littlefs evicts metadata logs and moves @@ -226,9 +227,20 @@ struct lfs2_config { // Size of the lookahead buffer in bytes. A larger lookahead buffer // increases the number of blocks found during an allocation pass. The // lookahead buffer is stored as a compact bitmap, so each byte of RAM - // can track 8 blocks. Must be a multiple of 8. + // can track 8 blocks. lfs2_size_t lookahead_size; + // Threshold for metadata compaction during lfs2_fs_gc in bytes. Metadata + // pairs that exceed this threshold will be compacted during lfs2_fs_gc. + // Defaults to ~88% block_size when zero, though the default may change + // in the future. + // + // Note this only affects lfs2_fs_gc. Normal compactions still only occur + // when full. + // + // Set to -1 to disable metadata compaction during lfs2_fs_gc. + lfs2_size_t compact_thresh; + // Optional statically allocated read buffer. Must be cache_size. // By default lfs2_malloc is used to allocate this buffer. void *read_buffer; @@ -237,25 +249,24 @@ struct lfs2_config { // By default lfs2_malloc is used to allocate this buffer. void *prog_buffer; - // Optional statically allocated lookahead buffer. Must be lookahead_size - // and aligned to a 32-bit boundary. By default lfs2_malloc is used to - // allocate this buffer. + // Optional statically allocated lookahead buffer. Must be lookahead_size. + // By default lfs2_malloc is used to allocate this buffer. void *lookahead_buffer; // Optional upper limit on length of file names in bytes. No downside for // larger names except the size of the info struct which is controlled by - // the LFS2_NAME_MAX define. Defaults to LFS2_NAME_MAX when zero. Stored in - // superblock and must be respected by other littlefs drivers. + // the LFS2_NAME_MAX define. Defaults to LFS2_NAME_MAX or name_max stored on + // disk when zero. lfs2_size_t name_max; // Optional upper limit on files in bytes. No downside for larger files - // but must be <= LFS2_FILE_MAX. Defaults to LFS2_FILE_MAX when zero. Stored - // in superblock and must be respected by other littlefs drivers. + // but must be <= LFS2_FILE_MAX. Defaults to LFS2_FILE_MAX or file_max stored + // on disk when zero. lfs2_size_t file_max; // Optional upper limit on custom attributes in bytes. No downside for // larger attributes size but must be <= LFS2_ATTR_MAX. Defaults to - // LFS2_ATTR_MAX when zero. + // LFS2_ATTR_MAX or attr_max stored on disk when zero. lfs2_size_t attr_max; // Optional upper limit on total space given to metadata pairs in bytes. On @@ -264,6 +275,15 @@ struct lfs2_config { // Defaults to block_size when zero. lfs2_size_t metadata_max; + // Optional upper limit on inlined files in bytes. Inlined files live in + // metadata and decrease storage requirements, but may be limited to + // improve metadata-related performance. Must be <= cache_size, <= + // attr_max, and <= block_size/8. Defaults to the largest possible + // inline_max when zero. + // + // Set to -1 to disable inlined files. + lfs2_size_t inline_max; + #ifdef LFS2_MULTIVERSION // On-disk version to use when writing in the form of 16-bit major version // + 16-bit minor version. This limiting metadata to what is supported by @@ -430,19 +450,20 @@ typedef struct lfs2 { lfs2_gstate_t gdisk; lfs2_gstate_t gdelta; - struct lfs2_free { - lfs2_block_t off; + struct lfs2_lookahead { + lfs2_block_t start; lfs2_block_t size; - lfs2_block_t i; - lfs2_block_t ack; - uint32_t *buffer; - } free; + lfs2_block_t next; + lfs2_block_t ckpoint; + uint8_t *buffer; + } lookahead; const struct lfs2_config *cfg; lfs2_size_t block_count; lfs2_size_t name_max; lfs2_size_t file_max; lfs2_size_t attr_max; + lfs2_size_t inline_max; #ifdef LFS2_MIGRATE struct lfs21 *lfs21; @@ -712,18 +733,6 @@ lfs2_ssize_t lfs2_fs_size(lfs2_t *lfs2); // Returns a negative error code on failure. int lfs2_fs_traverse(lfs2_t *lfs2, int (*cb)(void*, lfs2_block_t), void *data); -// Attempt to proactively find free blocks -// -// Calling this function is not required, but may allowing the offloading of -// the expensive block allocation scan to a less time-critical code path. -// -// Note: littlefs currently does not persist any found free blocks to disk. -// This may change in the future. -// -// Returns a negative error code on failure. Finding no free blocks is -// not an error. -int lfs2_fs_gc(lfs2_t *lfs2); - #ifndef LFS2_READONLY // Attempt to make the filesystem consistent and ready for writing // @@ -736,11 +745,33 @@ int lfs2_fs_gc(lfs2_t *lfs2); int lfs2_fs_mkconsistent(lfs2_t *lfs2); #endif +#ifndef LFS2_READONLY +// Attempt any janitorial work +// +// This currently: +// 1. Calls mkconsistent if not already consistent +// 2. Compacts metadata > compact_thresh +// 3. Populates the block allocator +// +// Though additional janitorial work may be added in the future. +// +// Calling this function is not required, but may allow the offloading of +// expensive janitorial work to a less time-critical code path. +// +// Returns a negative error code on failure. Accomplishing nothing is not +// an error. +int lfs2_fs_gc(lfs2_t *lfs2); +#endif + #ifndef LFS2_READONLY // Grows the filesystem to a new size, updating the superblock with the new // block count. // -// Note: This is irreversible. +// If LFS2_SHRINKNONRELOCATING is defined, this function will also accept +// block_counts smaller than the current configuration, after checking +// that none of the blocks that are being removed are in use. +// Note that littlefs's pseudorandom block allocation means that +// this is very unlikely to work in the general case. // // Returns a negative error code on failure. int lfs2_fs_grow(lfs2_t *lfs2, lfs2_size_t block_count); diff --git a/lib/littlefs/lfs2_util.c b/lib/littlefs/lfs2_util.c index c9850e78869..4fe7e5340ce 100644 --- a/lib/littlefs/lfs2_util.c +++ b/lib/littlefs/lfs2_util.c @@ -11,6 +11,8 @@ #ifndef LFS2_CONFIG +// If user provides their own CRC impl we don't need this +#ifndef LFS2_CRC // Software CRC implementation with small lookup table uint32_t lfs2_crc(uint32_t crc, const void *buffer, size_t size) { static const uint32_t rtable[16] = { @@ -29,6 +31,7 @@ uint32_t lfs2_crc(uint32_t crc, const void *buffer, size_t size) { return crc; } +#endif #endif diff --git a/lib/littlefs/lfs2_util.h b/lib/littlefs/lfs2_util.h index dd2cbcc106d..12c82a630b0 100644 --- a/lib/littlefs/lfs2_util.h +++ b/lib/littlefs/lfs2_util.h @@ -8,6 +8,9 @@ #ifndef LFS2_UTIL_H #define LFS2_UTIL_H +#define LFS2_STRINGIZE(x) LFS2_STRINGIZE2(x) +#define LFS2_STRINGIZE2(x) #x + // Users can override lfs2_util.h with their own configuration by defining // LFS2_CONFIG as a header file to include (-DLFS2_CONFIG=lfs2_config.h). // @@ -15,11 +18,26 @@ // provided by the config file. To start, I would suggest copying lfs2_util.h // and modifying as needed. #ifdef LFS2_CONFIG -#define LFS2_STRINGIZE(x) LFS2_STRINGIZE2(x) -#define LFS2_STRINGIZE2(x) #x #include LFS2_STRINGIZE(LFS2_CONFIG) #else +// Alternatively, users can provide a header file which defines +// macros and other things consumed by littlefs. +// +// For example, provide my_defines.h, which contains +// something like: +// +// #include +// extern void *my_malloc(size_t sz); +// #define LFS2_MALLOC(sz) my_malloc(sz) +// +// And build littlefs with the header by defining LFS2_DEFINES. +// (-DLFS2_DEFINES=my_defines.h) + +#ifdef LFS2_DEFINES +#include LFS2_STRINGIZE(LFS2_DEFINES) +#endif + // System includes #include #include @@ -177,10 +195,10 @@ static inline uint32_t lfs2_fromle32(uint32_t a) { (defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)) return __builtin_bswap32(a); #else - return (((uint8_t*)&a)[0] << 0) | - (((uint8_t*)&a)[1] << 8) | - (((uint8_t*)&a)[2] << 16) | - (((uint8_t*)&a)[3] << 24); + return ((uint32_t)((uint8_t*)&a)[0] << 0) | + ((uint32_t)((uint8_t*)&a)[1] << 8) | + ((uint32_t)((uint8_t*)&a)[2] << 16) | + ((uint32_t)((uint8_t*)&a)[3] << 24); #endif } @@ -200,10 +218,10 @@ static inline uint32_t lfs2_frombe32(uint32_t a) { (defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__) return a; #else - return (((uint8_t*)&a)[0] << 24) | - (((uint8_t*)&a)[1] << 16) | - (((uint8_t*)&a)[2] << 8) | - (((uint8_t*)&a)[3] << 0); + return ((uint32_t)((uint8_t*)&a)[0] << 24) | + ((uint32_t)((uint8_t*)&a)[1] << 16) | + ((uint32_t)((uint8_t*)&a)[2] << 8) | + ((uint32_t)((uint8_t*)&a)[3] << 0); #endif } @@ -212,12 +230,22 @@ static inline uint32_t lfs2_tobe32(uint32_t a) { } // Calculate CRC-32 with polynomial = 0x04c11db7 +#ifdef LFS2_CRC +static inline uint32_t lfs2_crc(uint32_t crc, const void *buffer, size_t size) { + return LFS2_CRC(crc, buffer, size); +} +#else uint32_t lfs2_crc(uint32_t crc, const void *buffer, size_t size); +#endif // Allocate memory, only used if buffers are not provided to littlefs -// Note, memory must be 64-bit aligned +// +// littlefs current has no alignment requirements, as it only allocates +// byte-level buffers. static inline void *lfs2_malloc(size_t size) { -#ifndef LFS2_NO_MALLOC +#if defined(LFS2_MALLOC) + return LFS2_MALLOC(size); +#elif !defined(LFS2_NO_MALLOC) return malloc(size); #else (void)size; @@ -227,7 +255,9 @@ static inline void *lfs2_malloc(size_t size) { // Deallocate memory, only used if buffers are not provided to littlefs static inline void lfs2_free(void *p) { -#ifndef LFS2_NO_MALLOC +#if defined(LFS2_FREE) + LFS2_FREE(p); +#elif !defined(LFS2_NO_MALLOC) free(p); #else (void)p; diff --git a/lib/lvgl b/lib/lvgl new file mode 160000 index 00000000000..9b1022d1c61 --- /dev/null +++ b/lib/lvgl @@ -0,0 +1 @@ +Subproject commit 9b1022d1c612adebcde34d8727d888c2599919c2 diff --git a/lib/mbedtls b/lib/mbedtls index 981743de6fc..ece41aa84d7 160000 --- a/lib/mbedtls +++ b/lib/mbedtls @@ -1 +1 @@ -Subproject commit 981743de6fcdbe672e482b6fd724d31d0a0d2476 +Subproject commit ece41aa84d7879d7e55c59e955a5884b541f7f3b diff --git a/lib/mbedtls_config/crt_bundle.c b/lib/mbedtls_config/crt_bundle.c index 9c546a26883..2b8fabd8bcd 100644 --- a/lib/mbedtls_config/crt_bundle.c +++ b/lib/mbedtls_config/crt_bundle.c @@ -25,6 +25,15 @@ #define BUNDLE_HEADER_OFFSET 2 #define CRT_HEADER_OFFSET 4 +/* Bundle format (tools/gen_crt_bundle.py): a certificate count, then for each root a 4-byte + * header with the name hash length and the public key length, the name hash and the DER public + * key. The name hash is the first NAME_HASH_LEN bytes of the SHA-256 of the root's DER subject + * name, and the roots are sorted by it for the binary search below. Storing the hash instead of + * the name saves about 13 KB. The hash only chooses which root to try: a certificate is trusted + * when its signature verifies with that root's public key, or when it is itself a bundled root + * (same subject and public key). Two roots can share a hash, so all roots with the same hash are + * tried. */ +#define NAME_HASH_LEN 8 /* a dummy certificate so that * cacert_ptr passes non-NULL check during handshake */ @@ -56,10 +65,6 @@ static crt_bundle_t s_crt_bundle; static int crt_check_signature(mbedtls_x509_crt *child, const uint8_t *pub_key_buf, size_t pub_key_len); -#if MBEDTLS_VERSION_MAJOR < 3 -#define MBEDTLS_PRIVATE(x) x -#endif - static int crt_check_signature(mbedtls_x509_crt *child, const uint8_t *pub_key_buf, size_t pub_key_len) { int ret = 0; mbedtls_x509_crt parent; @@ -74,13 +79,6 @@ static int crt_check_signature(mbedtls_x509_crt *child, const uint8_t *pub_key_b } - // Fast check to avoid expensive computations when not necessary - if (!mbedtls_pk_can_do(&parent.pk, child->MBEDTLS_PRIVATE(sig_pk))) { - LOGE(TAG, "Simple compare failed"); - ret = -1; - goto cleanup; - } - md_info = mbedtls_md_info_from_type(child->MBEDTLS_PRIVATE(sig_md)); if ((ret = mbedtls_md(md_info, child->tbs.p, child->tbs.len, hash)) != 0) { LOGE(TAG, "Internal mbedTLS error %X", ret); @@ -88,10 +86,9 @@ static int crt_check_signature(mbedtls_x509_crt *child, const uint8_t *pub_key_b } if ((ret = mbedtls_pk_verify_ext( - child->MBEDTLS_PRIVATE(sig_pk), child->MBEDTLS_PRIVATE(sig_opts), &parent.pk, + child->MBEDTLS_PRIVATE(sig_pk), &parent.pk, child->MBEDTLS_PRIVATE(sig_md), hash, mbedtls_md_get_size(md_info), child->MBEDTLS_PRIVATE(sig).p, child->MBEDTLS_PRIVATE(sig).len)) != 0) { - LOGE(TAG, "PK verify failed with error %X", ret); goto cleanup; } @@ -102,6 +99,36 @@ static int crt_check_signature(mbedtls_x509_crt *child, const uint8_t *pub_key_b } +/* Index of the first bundled root whose name hash matches `name`, or -1. The hash is left in + * `hash` (32 bytes) for crt_name_hash_equal(). */ +static int crt_bundle_find(const mbedtls_x509_buf *name, unsigned char *hash) { + if (mbedtls_md(mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), name->p, name->len, hash) != 0) { + return -1; + } + int start = 0; + int end = s_crt_bundle.num_certs - 1; + while (start <= end) { + int middle = (start + end) / 2; + int cmp_res = memcmp(hash, s_crt_bundle.crts[middle] + CRT_HEADER_OFFSET, NAME_HASH_LEN); + if (cmp_res == 0) { + while (middle > 0 && + memcmp(hash, s_crt_bundle.crts[middle - 1] + CRT_HEADER_OFFSET, NAME_HASH_LEN) == 0) { + middle--; + } + return middle; + } else if (cmp_res < 0) { + end = middle - 1; + } else { + start = middle + 1; + } + } + return -1; +} + +static bool crt_name_hash_equal(const unsigned char *hash, int i) { + return memcmp(hash, s_crt_bundle.crts[i] + CRT_HEADER_OFFSET, NAME_HASH_LEN) == 0; +} + /* This callback is called for every certificate in the chain. If the chain * is proper each intermediate certificate is validated through its parent * in the x509_crt_verify_chain() function. So this callback should @@ -127,35 +154,26 @@ static int crt_verify_callback(void *buf, mbedtls_x509_crt *crt, int depth, uint LOGD(TAG, "%d certificates in bundle", s_crt_bundle.num_certs); - size_t name_len = 0; - const uint8_t *crt_name; - - bool crt_found = false; - int start = 0; - int end = s_crt_bundle.num_certs - 1; - int middle = (end - start) / 2; - - /* Look for the certificate using binary search on subject name */ - while (start <= end) { - name_len = s_crt_bundle.crts[middle][0] << 8 | s_crt_bundle.crts[middle][1]; - crt_name = s_crt_bundle.crts[middle] + CRT_HEADER_OFFSET; - - int cmp_res = memcmp(child->issuer_raw.p, crt_name, name_len); - if (cmp_res == 0) { - crt_found = true; - break; - } else if (cmp_res < 0) { - end = middle - 1; - } else { - start = middle + 1; + /* A chain can carry a cross-signed copy of a root that is in the bundle, issued by a root + * that is not (GTS Root R4 signed by the retired GlobalSign Root CA). Trust that copy when + * its subject and public key match the bundled root. */ + unsigned char name_hash[32]; + int i = crt_bundle_find(&child->subject_raw, name_hash); + for (; i >= 0 && i < s_crt_bundle.num_certs && crt_name_hash_equal(name_hash, i); i++) { + size_t key_len = s_crt_bundle.crts[i][2] << 8 | s_crt_bundle.crts[i][3]; + if (key_len == child->pk_raw.len && + memcmp(s_crt_bundle.crts[i] + CRT_HEADER_OFFSET + NAME_HASH_LEN, child->pk_raw.p, key_len) == 0) { + *flags = 0; + return 0; } - middle = (start + end) / 2; } + /* Otherwise the root that issued this certificate must verify its signature */ int ret = MBEDTLS_ERR_X509_FATAL_ERROR; - if (crt_found) { - size_t key_len = s_crt_bundle.crts[middle][2] << 8 | s_crt_bundle.crts[middle][3]; - ret = crt_check_signature(child, s_crt_bundle.crts[middle] + CRT_HEADER_OFFSET + name_len, key_len); + i = crt_bundle_find(&child->issuer_raw, name_hash); + for (; i >= 0 && i < s_crt_bundle.num_certs && ret != 0 && crt_name_hash_equal(name_hash, i); i++) { + size_t key_len = s_crt_bundle.crts[i][2] << 8 | s_crt_bundle.crts[i][3]; + ret = crt_check_signature(child, s_crt_bundle.crts[i] + CRT_HEADER_OFFSET + NAME_HASH_LEN, key_len); } if (ret == 0) { @@ -206,6 +224,11 @@ static int crt_bundle_init(const uint8_t *x509_bundle, size_t bundle_size) { } size_t name_len = cur_crt[0] << 8 | cur_crt[1]; size_t key_len = cur_crt[2] << 8 | cur_crt[3]; + if (name_len != NAME_HASH_LEN) { + LOGE(TAG, "Invalid certificate bundle"); + m_tracked_free(crts); + return -MP_EINVAL; + } cur_crt = cur_crt + CRT_HEADER_OFFSET + name_len + key_len; } diff --git a/lib/mbedtls_config/hashlib_psa_port.c b/lib/mbedtls_config/hashlib_psa_port.c new file mode 100644 index 00000000000..88a3b96adba --- /dev/null +++ b/lib/mbedtls_config/hashlib_psa_port.c @@ -0,0 +1,32 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Dan Halbert for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// Platform glue for ports that build the PSA crypto core for hashlib but not for ssl. +// The ssl equivalent is mbedtls_port.c; the two are mutually exclusive, because +// CIRCUITPY_HASHLIB_MBEDTLS_ONLY means hashlib without ssl. + +#include + +#if CIRCUITPY_HASHLIB_MBEDTLS_ONLY + +#include "psa/crypto.h" + +#include "shared-bindings/os/__init__.h" + +// Required by MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG. psa_crypto_init() initializes the RNG +// subsystem even in a build that only ever hashes, so this has to exist. +psa_status_t mbedtls_psa_external_get_random( + mbedtls_psa_external_random_context_t *context, + uint8_t *output, size_t output_size, size_t *output_length) { + (void)context; + if (!common_hal_os_urandom(output, output_size)) { + return PSA_ERROR_INSUFFICIENT_ENTROPY; + } + *output_length = output_size; + return PSA_SUCCESS; +} + +#endif diff --git a/lib/mbedtls_config/mbedtls_config.h b/lib/mbedtls_config/mbedtls_config.h index 3791924a13c..062ad11ff17 100644 --- a/lib/mbedtls_config/mbedtls_config.h +++ b/lib/mbedtls_config/mbedtls_config.h @@ -1,128 +1,102 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2018-2019 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. - */ -#ifndef MICROPY_INCLUDED_MBEDTLS_CONFIG_H -#define MICROPY_INCLUDED_MBEDTLS_CONFIG_H - -// If you want to debug MBEDTLS uncomment the following and -// Pass 3 to mbedtls_debug_set_threshold in socket_new +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018-2019 Damien P. George +// SPDX-FileCopyrightText: Copyright (c) 2026 Dan Halbert for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// mbedtls TLS and X.509 configuration, selected with MBEDTLS_CONFIG_FILE. +// +// As of mbedtls 4.0 this file covers only TLS and X.509. Everything cryptographic -- +// algorithms, key types, the platform hooks and the RNG -- is configured in +// tf_psa_crypto_config.h next to this file, and selected with +// TF_PSA_CRYPTO_CONFIG_FILE. + +#pragma once + +// If you want to debug mbedtls, uncomment the following. SSLSocket.c raises the debug +// threshold to 4 when it is set. // #define MBEDTLS_DEBUG_C -// Set mbedtls configuration -#define MBEDTLS_PLATFORM_MEMORY -#define MBEDTLS_PLATFORM_NO_STD_FUNCTIONS -#define MBEDTLS_DEPRECATED_REMOVED -#define MBEDTLS_ENTROPY_HARDWARE_ALT -#define MBEDTLS_AES_ROM_TABLES -#define MBEDTLS_CIPHER_MODE_CBC -#define MBEDTLS_ECP_DP_SECP192R1_ENABLED -#define MBEDTLS_ECP_DP_SECP224R1_ENABLED -#define MBEDTLS_ECP_DP_SECP256R1_ENABLED -#define MBEDTLS_ECP_DP_SECP384R1_ENABLED -#define MBEDTLS_ECP_DP_SECP521R1_ENABLED -#define MBEDTLS_ECP_DP_SECP192K1_ENABLED -#define MBEDTLS_ECP_DP_SECP224K1_ENABLED -#define MBEDTLS_ECP_DP_SECP256K1_ENABLED -#define MBEDTLS_ECP_DP_BP256R1_ENABLED -#define MBEDTLS_ECP_DP_BP384R1_ENABLED -#define MBEDTLS_ECP_DP_BP512R1_ENABLED -#define MBEDTLS_ECP_DP_CURVE25519_ENABLED -#define MBEDTLS_ECP_NIST_OPTIM -#define MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED -#define MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED -#define MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED -#define MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED -#define MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED -#define MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED -#define MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED -#define MBEDTLS_KEY_EXCHANGE_PSK_ENABLED -#define MBEDTLS_KEY_EXCHANGE_RSA_ENABLED -#define MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED -#define MBEDTLS_NO_PLATFORM_ENTROPY -#define MBEDTLS_PKCS1_V15 -#define MBEDTLS_SHA256_SMALLER -#define MBEDTLS_SSL_PROTO_TLS1 -#define MBEDTLS_SSL_PROTO_TLS1_1 +// Protocol versions + +// TLS 1.0 and 1.1 were removed in mbedtls 3.0, and were obsolete long before that. +// +// TLS 1.3 is available in 4.x but is turned off, to match espressif +// It also cost 25648 bytes on Pico W, which has only ~50 KB of firmware +// space left. Enabling it here would also require enabling +// MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED, and PSA_WANT_ALG_HKDF* in +// tf_psa_crypto_config.h for the 1.3 key schedule. #define MBEDTLS_SSL_PROTO_TLS1_2 + +// DTLS is deliberately off: common_hal_ssl_sslcontext_wrap_socket() rejects anything +// that is not SOCKETPOOL_SOCK_STREAM, so it could never be reached. + +#define MBEDTLS_SSL_CLI_C +#define MBEDTLS_SSL_SRV_C +#define MBEDTLS_SSL_TLS_C + +// Key exchanges. Without at least one of these there are no TLS 1.2 ciphersuites at +// all, the ClientHello offers nothing, and the server answers with a fatal +// handshake_failure alert. These two are what espressif enables +// (CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_{RSA,ECDSA}) and cover the public web. The PSK +// and ECJPAKE exchanges that 4.x also still offers are not reachable from the ssl +// module, and the static-RSA and DHE exchanges the mbedtls 2.28 config enabled are +// gone from 4.x upstream. +#define MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED +#define MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED + +// Extensions + #define MBEDTLS_SSL_SERVER_NAME_INDICATION +#define MBEDTLS_SSL_KEEP_PEER_CERTIFICATE +#define MBEDTLS_SSL_ENCRYPT_THEN_MAC +#define MBEDTLS_SSL_EXTENDED_MASTER_SECRET + +// Buffers -// Use a smaller output buffer to reduce size of SSL context +// Accept a full-size record inbound, since we do not control what the peer sends, +// but use a smaller outbound buffer to reduce the SSL context size. #define MBEDTLS_SSL_MAX_CONTENT_LEN (16384) #define MBEDTLS_SSL_IN_CONTENT_LEN (MBEDTLS_SSL_MAX_CONTENT_LEN) #define MBEDTLS_SSL_OUT_CONTENT_LEN (4096) -// Enable mbedtls modules -#define MBEDTLS_AES_C -#define MBEDTLS_ASN1_PARSE_C -#define MBEDTLS_ASN1_WRITE_C -#define MBEDTLS_BASE64_C -#define MBEDTLS_BIGNUM_C -#define MBEDTLS_CIPHER_C -#define MBEDTLS_CTR_DRBG_C -#define MBEDTLS_ECDH_C -#define MBEDTLS_ECDSA_C -#define MBEDTLS_ECP_C -#define MBEDTLS_ENTROPY_C -#define MBEDTLS_ERROR_C -#define MBEDTLS_GCM_C -#define MBEDTLS_MD_C -#define MBEDTLS_MD5_C -#define MBEDTLS_OID_C -#define MBEDTLS_PKCS5_C -#define MBEDTLS_PEM_PARSE_C -#define MBEDTLS_PK_C -#define MBEDTLS_PK_PARSE_C -#define MBEDTLS_PLATFORM_C -#define MBEDTLS_RSA_C -#define MBEDTLS_SHA1_C -#define MBEDTLS_SHA256_C -#define MBEDTLS_SHA512_C -#define MBEDTLS_SSL_CLI_C -#define MBEDTLS_SSL_SRV_C -#define MBEDTLS_SSL_TLS_C -#define MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_KEY_EXCHANGE -#define MBEDTLS_X509_CRT_PARSE_C +// X.509 + #define MBEDTLS_X509_USE_C -#define MBEDTLS_HAVE_TIME -#define MBEDTLS_DHM_C // needed by DHE_PSK -#undef MBEDTLS_HAVE_TIME_DATE - -// Memory allocation hooks -#include -#include -void *m_tracked_calloc(size_t nmemb, size_t size); -void m_tracked_free(void *ptr); -#define MBEDTLS_PLATFORM_STD_CALLOC m_tracked_calloc -#define MBEDTLS_PLATFORM_STD_FREE m_tracked_free -#define MBEDTLS_PLATFORM_SNPRINTF_MACRO snprintf - -// Time hook -#include -time_t rp2_rtctime_seconds(time_t *timer); -#define MBEDTLS_PLATFORM_TIME_MACRO rp2_rtctime_seconds - -#include "mbedtls/check_config.h" - -#endif /* MICROPY_INCLUDED_MBEDTLS_CONFIG_H */ +#define MBEDTLS_X509_CRT_PARSE_C +#define MBEDTLS_X509_RSASSA_PSS_SUPPORT + +// MBEDTLS_HAVE_TIME_DATE is deliberately left off, so certificate notBefore/notAfter +// are not checked (see the BADCERT_EXPIRED/BADCERT_FUTURE tests in x509_crt.c, which +// are compiled out without it). CircuitPython does not know the wall clock time unless +// the program sets it explicitly, which often does not happen; with an unset clock, +// checking the dates would reject valid certificates rather than catch expired ones. +// espressif does not set CONFIG_MBEDTLS_HAVE_TIME_DATE either. +// +// Nothing else we enable consumes time -- no session tickets, no context +// serialization, no DTLS, no TLS 1.3 -- so MBEDTLS_HAVE_TIME is off as well, and +// mbedtls_port.c needs neither a wall clock nor mbedtls_ms_time(). + +// Error strings + +// SSLSocket.c keys off MBEDTLS_ERROR_C to decide whether to put a message on the +// OSError it raises. mbedtls's own error.c is not built; lib/mbedtls_errors supplies +// a smaller mbedtls_strerror() instead. +#define MBEDTLS_ERROR_C + +// Sanity checks +// +// mbedtls's own mbedtls_check_config.h only validates the prerequisites of options +// that are enabled, so it says nothing when a whole category is missing. This is where +// TF_PSA_CRYPTO_CONFIG_FILE replacing psa/crypto_config.h rather than overlaying it +// bites: every default we rely on has to be restated here, and forgetting one produces +// a build that compiles and links but cannot complete a handshake. +#if !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) && \ + !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) && \ + !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) && \ + !defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) && \ + !defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) +#error "No MBEDTLS_KEY_EXCHANGE_* enabled: ciphersuite_definitions[] would be empty, " \ + "so the ClientHello would offer nothing and every TLS 1.2 handshake would fail." +#endif diff --git a/lib/mbedtls_config/mbedtls_config_port.h b/lib/mbedtls_config/mbedtls_config_port.h deleted file mode 100644 index 1752d946529..00000000000 --- a/lib/mbedtls_config/mbedtls_config_port.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2018-2019 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. - */ -#ifndef MICROPY_INCLUDED_MBEDTLS_CONFIG_H -#define MICROPY_INCLUDED_MBEDTLS_CONFIG_H - -// If you want to debug MBEDTLS uncomment the following and -// Pass 3 to mbedtls_debug_set_threshold in socket_new -// #define MBEDTLS_DEBUG_C - -// Set mbedtls configuration -#define MBEDTLS_PLATFORM_C -#define MBEDTLS_PLATFORM_MEMORY -#define MBEDTLS_PLATFORM_NO_STD_FUNCTIONS -#define MBEDTLS_DEPRECATED_REMOVED -#define MBEDTLS_ENTROPY_HARDWARE_ALT - -// Enable mbedtls modules -#define MBEDTLS_MD_C -#define MBEDTLS_MD5_C -#define MBEDTLS_SHA1_C -#define MBEDTLS_SHA256_C -#define MBEDTLS_SHA512_C -#undef MBEDTLS_HAVE_TIME_DATE - -<<<<<<<< HEAD:lib/mbedtls_config/mbedtls_config_hashlib.h -// Memory allocation hooks -#include -#include -void *m_tracked_calloc(size_t nmemb, size_t size); -void m_tracked_free(void *ptr); -#define MBEDTLS_PLATFORM_STD_CALLOC m_tracked_calloc -#define MBEDTLS_PLATFORM_STD_FREE m_tracked_free -#define MBEDTLS_PLATFORM_SNPRINTF_MACRO snprintf -======== -// Time hook -#include -time_t rp2_rtctime_seconds(time_t *timer); -#define MBEDTLS_PLATFORM_TIME_MACRO rp2_rtctime_seconds -#define MBEDTLS_PLATFORM_MS_TIME_ALT mbedtls_ms_time ->>>>>>>> v1.23.0:lib/mbedtls_config/mbedtls_config_port.h - -#include "mbedtls/check_config.h" - -#endif /* MICROPY_INCLUDED_MBEDTLS_CONFIG_H */ diff --git a/lib/mbedtls_config/mbedtls_port.c b/lib/mbedtls_config/mbedtls_port.c index b7e8ceae5de..cc29145e803 100644 --- a/lib/mbedtls_config/mbedtls_port.c +++ b/lib/mbedtls_config/mbedtls_port.c @@ -1,53 +1,29 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2019 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 +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018-2019 Damien P. George +// SPDX-FileCopyrightText: Copyright (c) 2026 Dan Halbert for Adafruit Industries + +#include "py/mpconfig.h" #if CIRCUITPY_SSL_MBEDTLS -#include "py/runtime.h" -#include "mbedtls_config.h" -#include "mbedtls/entropy_poll.h" +#include "psa/crypto.h" -#include "shared/timeutils/timeutils.h" #include "shared-bindings/os/__init__.h" -#include "shared-bindings/time/__init__.h" - -extern uint8_t rosc_random_u8(size_t cycles); - -int mbedtls_hardware_poll(void *data, unsigned char *output, size_t len, size_t *olen) { - *olen = len; - common_hal_os_urandom(data, len); - return 0; -} -time_t rp2_rtctime_seconds(time_t *timer) { - mp_obj_t datetime = mp_load_attr(MP_STATE_VM(rtc_time_source), MP_QSTR_datetime); - timeutils_struct_time_t tm; - struct_time_to_tm(datetime, &tm); - return timeutils_seconds_since_epoch(tm.tm_year, tm.tm_mon, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); +// The RNG behind MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG. mbedtls asks for randomness through +// this instead of seeding its own entropy accumulator and CTR-DRBG, so the port's TRNG +// is the only source. `context` is unused; mbedtls initializes it to 0 and we keep no +// state of our own. +psa_status_t mbedtls_psa_external_get_random( + mbedtls_psa_external_random_context_t *context, + uint8_t *output, size_t output_size, size_t *output_length) { + (void)context; + if (!common_hal_os_urandom(output, output_size)) { + return PSA_ERROR_INSUFFICIENT_ENTROPY; + } + *output_length = output_size; + return PSA_SUCCESS; } #endif diff --git a/lib/mbedtls_config/psa_dispatch.patch b/lib/mbedtls_config/psa_dispatch.patch new file mode 100644 index 00000000000..90992cec7c8 --- /dev/null +++ b/lib/mbedtls_config/psa_dispatch.patch @@ -0,0 +1,88 @@ +SPDX-FileCopyrightText: Copyright (c) 2026 Mikey Sklar for Adafruit Industries +SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later + +Adds port PSA drivers to mbedtls's dispatch layer: the hash dispatch in the driver +wrapper template, and each driver's context in the PSA operation unions. mbedtls +doesn't generate these from a driver description yet, so its driver guide says to +edit the dispatch layer by hand (docs/psa-driver-example-and-guide.md). The layout +follows mbedtls's dispatch directory (driver_templates/, include/psa/). +Applied by py/circuitpy_defns.mk with no fuzz, so an mbedtls update that moves this +code stops the build. + +--- a/driver_templates/psa_crypto_driver_wrappers.h.jinja ++++ b/driver_templates/psa_crypto_driver_wrappers.h.jinja +@@ -56,4 +56,7 @@ + /* END-driver id */ + ++#include "rp2_sha256_psa.h" ++#define CIRCUITPY_RP2_SHA256_DRIVER_ID (0x43505348u) /* "CPSH", clear of generated IDs */ ++ + /* BEGIN-Common Macro definitions */ + {% macro entry_point_name(capability, entry_point, driver) -%} +@@ -1853,4 +1856,8 @@ + return( status ); + #endif ++ status = rp2_sha256_psa_hash_compute( alg, input, input_length, ++ hash, hash_size, hash_length ); ++ if( status != PSA_ERROR_NOT_SUPPORTED ) ++ return( status ); + + /* If software fallback is compiled in, try fallback */ +@@ -1888,5 +1895,11 @@ + return( status ); + #endif ++ status = rp2_sha256_psa_hash_setup( &operation->ctx.rp2_sha256_ctx, alg ); ++ if( status == PSA_SUCCESS ) ++ operation->id = CIRCUITPY_RP2_SHA256_DRIVER_ID; + ++ if( status != PSA_ERROR_NOT_SUPPORTED ) ++ return( status ); ++ + /* If software fallback is compiled in, try fallback */ + #if defined(MBEDTLS_PSA_BUILTIN_HASH) +@@ -1911,4 +1924,8 @@ + switch( source_operation->id ) + { ++ case CIRCUITPY_RP2_SHA256_DRIVER_ID: ++ target_operation->id = CIRCUITPY_RP2_SHA256_DRIVER_ID; ++ return( rp2_sha256_psa_hash_clone( &source_operation->ctx.rp2_sha256_ctx, ++ &target_operation->ctx.rp2_sha256_ctx ) ); + #if defined(MBEDTLS_PSA_BUILTIN_HASH) + case PSA_CRYPTO_MBED_TLS_DRIVER_ID: +@@ -1937,4 +1954,7 @@ + switch( operation->id ) + { ++ case CIRCUITPY_RP2_SHA256_DRIVER_ID: ++ return( rp2_sha256_psa_hash_update( &operation->ctx.rp2_sha256_ctx, ++ input, input_length ) ); + #if defined(MBEDTLS_PSA_BUILTIN_HASH) + case PSA_CRYPTO_MBED_TLS_DRIVER_ID: +@@ -1963,4 +1983,7 @@ + switch( operation->id ) + { ++ case CIRCUITPY_RP2_SHA256_DRIVER_ID: ++ return( rp2_sha256_psa_hash_finish( &operation->ctx.rp2_sha256_ctx, ++ hash, hash_size, hash_length ) ); + #if defined(MBEDTLS_PSA_BUILTIN_HASH) + case PSA_CRYPTO_MBED_TLS_DRIVER_ID: +@@ -1987,4 +2010,6 @@ + switch( operation->id ) + { ++ case CIRCUITPY_RP2_SHA256_DRIVER_ID: ++ return( rp2_sha256_psa_hash_abort( &operation->ctx.rp2_sha256_ctx ) ); + #if defined(MBEDTLS_PSA_BUILTIN_HASH) + case PSA_CRYPTO_MBED_TLS_DRIVER_ID: +--- a/include/psa/crypto_driver_contexts_primitives.h ++++ b/include/psa/crypto_driver_contexts_primitives.h +@@ -28,4 +28,5 @@ + /* Include the context structure definitions for the Mbed TLS software drivers */ + #include "mbedtls/private/crypto_builtin_primitives.h" ++#include "rp2_sha256_psa_ctx.h" + + /* Include the context structure definitions for those drivers that were +@@ -110,4 +111,5 @@ + unsigned dummy; /* Make sure this union is always non-empty */ + mbedtls_psa_hash_operation_t mbedtls_ctx; ++ rp2_sha256_psa_hash_operation_t rp2_sha256_ctx; + #if defined(PSA_CRYPTO_DRIVER_TEST) + mbedtls_transparent_test_driver_hash_operation_t test_driver_ctx; diff --git a/lib/mbedtls_config/tf_psa_crypto_config.h b/lib/mbedtls_config/tf_psa_crypto_config.h new file mode 100644 index 00000000000..a1773dbeae7 --- /dev/null +++ b/lib/mbedtls_config/tf_psa_crypto_config.h @@ -0,0 +1,134 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018-2019 Damien P. George +// SPDX-FileCopyrightText: Copyright (c) 2026 Dan Halbert for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// TF-PSA-Crypto configuration, selected with TF_PSA_CRYPTO_CONFIG_FILE. +// +// mbedtls 4.0 split its configuration in two: MBEDTLS_CONFIG_FILE now covers only +// TLS and X.509 (see mbedtls_config.h next to this file), and everything +// cryptographic moved here. Algorithms and key types are requested with PSA_WANT_* +// rather than the old MBEDTLS__C module switches; the builtin implementations +// they need are derived from those by tf-psa-crypto's own config_adjust headers. + +#pragma once + +// Platform integration /////////////////////////////////////////////////////// + +#define MBEDTLS_PLATFORM_C +#define MBEDTLS_PLATFORM_MEMORY +#define MBEDTLS_PLATFORM_NO_STD_FUNCTIONS +#define MBEDTLS_DEPRECATED_REMOVED + +// Memory allocation hooks, so mbedtls allocations are tracked like the rest of the +// VM's. +#include +#include +void *m_tracked_calloc(size_t nmemb, size_t size); +void m_tracked_free(void *ptr); +#define MBEDTLS_PLATFORM_STD_CALLOC m_tracked_calloc +#define MBEDTLS_PLATFORM_STD_FREE m_tracked_free +#define MBEDTLS_PLATFORM_SNPRINTF_MACRO snprintf + +// Randomness ///////////////////////////////////////////////////////////////// + +// Take randomness straight from the port's TRNG rather than seeding mbedtls's own +// entropy accumulator and CTR-DRBG. mbedtls 4.x dropped MBEDTLS_ENTROPY_HARDWARE_ALT, +// which is how this was wired before, and going direct also keeps entropy.c and +// ctr_drbg.c out of the build. mbedtls_psa_external_get_random() is in +// mbedtls_port.c. +#define MBEDTLS_PSA_CRYPTO_C +#define MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG + +// Size/speed tradeoffs /////////////////////////////////////////////////////// + +#define MBEDTLS_AES_ROM_TABLES +#define MBEDTLS_AES_FEWER_TABLES +#define MBEDTLS_SHA256_SMALLER +#define MBEDTLS_ECP_NIST_OPTIM + +// Hashes ///////////////////////////////////////////////////////////////////// + +// SHA-1 is still needed to parse certificates that sign with it, and is what +// hashlib exposes as "sha1". +#define PSA_WANT_ALG_SHA_1 +#define PSA_WANT_ALG_SHA_224 +#define PSA_WANT_ALG_SHA_256 +#define PSA_WANT_ALG_SHA_384 +#define PSA_WANT_ALG_SHA_512 +#define PSA_WANT_ALG_HMAC +#define PSA_WANT_KEY_TYPE_HMAC + +// Key derivation ///////////////////////////////////////////////////////////// + +// The TLS 1.2 key schedule. HKDF is deliberately absent: it is the TLS 1.3 key +// schedule, and mbedtls_config.h enables TLS 1.2 only. +#define PSA_WANT_ALG_TLS12_PRF +#define PSA_WANT_ALG_TLS12_PSK_TO_MS +#define PSA_WANT_KEY_TYPE_DERIVE +#define PSA_WANT_KEY_TYPE_RAW_DATA + +// Bulk ciphers /////////////////////////////////////////////////////////////// + +#define PSA_WANT_KEY_TYPE_AES +#define PSA_WANT_ALG_GCM +#define PSA_WANT_ALG_CCM +#define PSA_WANT_ALG_CBC_NO_PADDING +#define PSA_WANT_ALG_CBC_PKCS7 +#define PSA_WANT_ALG_ECB_NO_PADDING + +// RP2 has no AES accelerator, so ChaCha20-Poly1305 is 40-70% faster than AES-GCM here, +// measured over HTTPS on Pico W and Pico 2 W. mbedtls offers it ahead of AES-GCM, and +// real-world CDNs do negotiate it. Costs about 6 kB. espressif leaves it off, since +// ESP32 has AES hardware. +#define PSA_WANT_KEY_TYPE_CHACHA20 +#define PSA_WANT_ALG_CHACHA20_POLY1305 + +// Public key ///////////////////////////////////////////////////////////////// + +#define PSA_WANT_ALG_RSA_PKCS1V15_CRYPT +#define PSA_WANT_ALG_RSA_PKCS1V15_SIGN +#define PSA_WANT_ALG_RSA_PSS +#define PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY +#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_BASIC +#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_IMPORT + +#define PSA_WANT_ALG_ECDH +#define PSA_WANT_ALG_ECDSA +#define PSA_WANT_ALG_DETERMINISTIC_ECDSA +#define PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY +#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC +#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_IMPORT +// An ECDHE handshake generates an ephemeral key pair, sends its public part, then +// runs the key agreement, so it needs GENERATE, EXPORT and DERIVE as well as the two +// above. Without them psa_generate_key() fails and the TLS 1.2 client reports +// MBEDTLS_ERR_SSL_HW_ACCEL_FAILED -- a legacy name that in 4.x just means a PSA call +// failed. See ssl_tls12_client.c. +#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_GENERATE +#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_EXPORT +#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE + +// P-256 and P-384 cover essentially every public CA. Curve25519 is here for x25519 +// ECDHE, which servers commonly prefer (RFC 8422). Deliberately absent: +// - P-521: no public CA issues from it, and it cost 5792 bytes on Pico W. +// - Brainpool and secp256k1: unused on the public web. espressif enables secp256k1 +// only because ESP-IDF defaults it on. +// The 192- and 224-bit curves the mbedtls 2.28 config enabled are gone from 4.x +// upstream; there is no PSA_WANT_ECC_SECP_R1_192/_224 to select. +#define PSA_WANT_ECC_SECP_R1_256 +#define PSA_WANT_ECC_SECP_R1_384 +#define PSA_WANT_ECC_MONTGOMERY_255 + +// Key and certificate parsing //////////////////////////////////////////////// + +#define MBEDTLS_PK_C +#define MBEDTLS_PK_PARSE_C +#define MBEDTLS_PK_WRITE_C +#define MBEDTLS_MD_C +#define MBEDTLS_PEM_PARSE_C +#define MBEDTLS_BASE64_C +#define MBEDTLS_PKCS5_C +#define MBEDTLS_ASN1_PARSE_C +#define MBEDTLS_ASN1_WRITE_C diff --git a/lib/mbedtls_config/tf_psa_crypto_config_hashlib.h b/lib/mbedtls_config/tf_psa_crypto_config_hashlib.h new file mode 100644 index 00000000000..737ef8a5bc0 --- /dev/null +++ b/lib/mbedtls_config/tf_psa_crypto_config_hashlib.h @@ -0,0 +1,53 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018-2019 Damien P. George +// SPDX-FileCopyrightText: Copyright (c) 2026 Dan Halbert for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// TF-PSA-Crypto configuration for ports that want hashlib but not ssl, selected with +// TF_PSA_CRYPTO_CONFIG_FILE when CIRCUITPY_HASHLIB_MBEDTLS_ONLY is set. +// +// Only the crypto config is needed here: nothing on this path includes +// mbedtls/build_info.h, so no TLS/X.509 configuration is required. +// +// The PSA core is enabled so that hashlib can use the same psa_hash_*() interface on +// every port. It also means PSA_WANT_* behaves as documented: tf-psa-crypto/build_info.h +// only derives the builtin implementations from PSA_WANT_* when MBEDTLS_PSA_CRYPTO_C is +// set, so without it PSA_WANT_ALG_SHA_256 would silently select nothing. + +#pragma once + +#define MBEDTLS_PLATFORM_C +#define MBEDTLS_PLATFORM_MEMORY +#define MBEDTLS_PLATFORM_NO_STD_FUNCTIONS +#define MBEDTLS_DEPRECATED_REMOVED + +// Everything runs in one address space, so PSA functions don't need to copy their +// buffers before using them. The copies are heap allocations on every call, and web +// workflow hashes (the websocket handshake) while no VM, and so no VM heap, exists. +#define MBEDTLS_PSA_ASSUME_EXCLUSIVE_BUFFERS + +#undef MBEDTLS_HAVE_TIME +#undef MBEDTLS_HAVE_TIME_DATE + +// The digests hashlib exposes. +#define PSA_WANT_ALG_SHA_1 +#define PSA_WANT_ALG_SHA_256 + +// psa_crypto_init() initializes the RNG subsystem even in a build that only hashes, so +// a random generator has to be available. Take it straight from the port TRNG, which +// keeps entropy.c and ctr_drbg.c out of the build; see hashlib_psa_port.c. +#define MBEDTLS_PSA_CRYPTO_C +#define MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG + +#define MBEDTLS_SHA256_SMALLER + +// Memory allocation hooks +#include +#include +void *m_tracked_calloc(size_t nmemb, size_t size); +void m_tracked_free(void *ptr); +#define MBEDTLS_PLATFORM_STD_CALLOC m_tracked_calloc +#define MBEDTLS_PLATFORM_STD_FREE m_tracked_free +#define MBEDTLS_PLATFORM_SNPRINTF_MACRO snprintf diff --git a/lib/mbedtls_errors/do-mp.sh b/lib/mbedtls_errors/do-mp.sh index 5c6b9711794..3713b0087a7 100755 --- a/lib/mbedtls_errors/do-mp.sh +++ b/lib/mbedtls_errors/do-mp.sh @@ -1,4 +1,15 @@ #! /bin/bash -e # Generate mp_mbedtls_errors.c for inclusion in ports that use $MPY/lib/mbedtls +# +# As of mbedtls 4.0 the error #defines live in two trees: TLS and X.509 in +# mbedtls/include/mbedtls, and the legacy crypto modules in tf-psa-crypto, so +# generate_errors.pl now takes the crypto include directory as well. patch -o mp_generate_errors.pl ../mbedtls/scripts/generate_errors.pl -#if defined(MBEDTLS_AES_C) -#include "mbedtls/aes.h" +#if defined(MBEDTLS_NET_C) +#include "mbedtls/net_sockets.h" #endif -#if defined(MBEDTLS_ARC4_C) -#include "mbedtls/arc4.h" +#if defined(MBEDTLS_PKCS7_C) +#include "mbedtls/pkcs7.h" #endif -#if defined(MBEDTLS_ARIA_C) -#include "mbedtls/aria.h" +#if defined(MBEDTLS_SSL_TLS_C) +#include "mbedtls/ssl.h" #endif -#if defined(MBEDTLS_ASN1_PARSE_C) -#include "mbedtls/asn1.h" +#if defined(MBEDTLS_X509_USE_C) || \ + defined(MBEDTLS_X509_CREATE_C) +#include "mbedtls/x509.h" #endif -#if defined(MBEDTLS_BASE64_C) -#include "mbedtls/base64.h" +#if defined(MBEDTLS_AES_C) +#include "mbedtls/private/aes.h" #endif -#if defined(MBEDTLS_BIGNUM_C) -#include "mbedtls/bignum.h" +#if defined(MBEDTLS_ARIA_C) +#include "mbedtls/private/aria.h" #endif -#if defined(MBEDTLS_BLOWFISH_C) -#include "mbedtls/blowfish.h" +#if defined(MBEDTLS_BIGNUM_C) +#include "mbedtls/private/bignum.h" #endif #if defined(MBEDTLS_CAMELLIA_C) -#include "mbedtls/camellia.h" -#endif - -#if defined(MBEDTLS_CCM_C) -#include "mbedtls/ccm.h" -#endif - -#if defined(MBEDTLS_CHACHA20_C) -#include "mbedtls/chacha20.h" +#include "mbedtls/private/camellia.h" #endif #if defined(MBEDTLS_CHACHAPOLY_C) -#include "mbedtls/chachapoly.h" +#include "mbedtls/private/chachapoly.h" #endif #if defined(MBEDTLS_CIPHER_C) -#include "mbedtls/cipher.h" -#endif - -#if defined(MBEDTLS_CMAC_C) -#include "mbedtls/cmac.h" +#include "mbedtls/private/cipher.h" #endif #if defined(MBEDTLS_CTR_DRBG_C) -#include "mbedtls/ctr_drbg.h" -#endif - -#if defined(MBEDTLS_DES_C) -#include "mbedtls/des.h" -#endif - -#if defined(MBEDTLS_DHM_C) -#include "mbedtls/dhm.h" +#include "mbedtls/private/ctr_drbg.h" #endif #if defined(MBEDTLS_ECP_C) -#include "mbedtls/ecp.h" +#include "mbedtls/private/ecp.h" #endif #if defined(MBEDTLS_ENTROPY_C) -#include "mbedtls/entropy.h" -#endif - -#if defined(MBEDTLS_ERROR_C) -#include "mbedtls/error.h" -#endif - -#if defined(MBEDTLS_GCM_C) -#include "mbedtls/gcm.h" -#endif - -#if defined(MBEDTLS_HKDF_C) -#include "mbedtls/hkdf.h" +#include "mbedtls/private/entropy.h" #endif #if defined(MBEDTLS_HMAC_DRBG_C) -#include "mbedtls/hmac_drbg.h" -#endif - -#if defined(MBEDTLS_MD_C) -#include "mbedtls/md.h" -#endif - -#if defined(MBEDTLS_MD2_C) -#include "mbedtls/md2.h" -#endif - -#if defined(MBEDTLS_MD4_C) -#include "mbedtls/md4.h" -#endif - -#if defined(MBEDTLS_MD5_C) -#include "mbedtls/md5.h" -#endif - -#if defined(MBEDTLS_NET_C) -#include "mbedtls/net_sockets.h" -#endif - -#if defined(MBEDTLS_OID_C) -#include "mbedtls/oid.h" -#endif - -#if defined(MBEDTLS_PADLOCK_C) -#if defined(MBEDTLS_PADLOCK_FILE) -#include MBEDTLS_PADLOCK_FILE -#else -#include "mbedtls/padlock.h" -#endif -#endif - -#if defined(MBEDTLS_PEM_PARSE_C) || defined(MBEDTLS_PEM_WRITE_C) -#include "mbedtls/pem.h" -#endif - -#if defined(MBEDTLS_PK_C) -#include "mbedtls/pk.h" -#endif - -#if defined(MBEDTLS_PKCS12_C) -#include "mbedtls/pkcs12.h" +#include "mbedtls/private/hmac_drbg.h" #endif #if defined(MBEDTLS_PKCS5_C) -#include "mbedtls/pkcs5.h" -#endif - -#if defined(MBEDTLS_PLATFORM_C) -#include "mbedtls/platform.h" -#endif - -#if defined(MBEDTLS_POLY1305_C) -#include "mbedtls/poly1305.h" -#endif - -#if defined(MBEDTLS_RIPEMD160_C) -#include "mbedtls/ripemd160.h" +#include "mbedtls/private/pkcs5.h" #endif #if defined(MBEDTLS_RSA_C) -#include "mbedtls/rsa.h" -#endif - -#if defined(MBEDTLS_SHA1_C) -#include "mbedtls/sha1.h" -#endif - -#if defined(MBEDTLS_SHA256_C) -#include "mbedtls/sha256.h" -#endif - -#if defined(MBEDTLS_SHA512_C) -#include "mbedtls/sha512.h" -#endif - -#if defined(MBEDTLS_SSL_TLS_C) -#include "mbedtls/ssl.h" -#endif - -#if defined(MBEDTLS_THREADING_C) -#include "mbedtls/threading.h" -#endif - -#if defined(MBEDTLS_X509_USE_C) || defined(MBEDTLS_X509_CREATE_C) -#include "mbedtls/x509.h" -#endif - -#if defined(MBEDTLS_XTEA_C) -#include "mbedtls/xtea.h" +#include "mbedtls/private/rsa.h" #endif @@ -231,197 +112,44 @@ struct ssl_errs { // Table of high level error codes static const struct ssl_errs mbedtls_high_level_error_tab[] = { // BEGIN generated code -#if defined(MBEDTLS_CIPHER_C) - { -(MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE), "CIPHER_FEATURE_UNAVAILABLE" }, - { -(MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA), "CIPHER_BAD_INPUT_DATA" }, - { -(MBEDTLS_ERR_CIPHER_ALLOC_FAILED), "CIPHER_ALLOC_FAILED" }, - { -(MBEDTLS_ERR_CIPHER_INVALID_PADDING), "CIPHER_INVALID_PADDING" }, - { -(MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED), "CIPHER_FULL_BLOCK_EXPECTED" }, - { -(MBEDTLS_ERR_CIPHER_AUTH_FAILED), "CIPHER_AUTH_FAILED" }, - { -(MBEDTLS_ERR_CIPHER_INVALID_CONTEXT), "CIPHER_INVALID_CONTEXT" }, -#if defined(MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED) - { -(MBEDTLS_ERR_CIPHER_HW_ACCEL_FAILED), "CIPHER_HW_ACCEL_FAILED" }, -#endif -#endif /* MBEDTLS_CIPHER_C */ - -#if defined(MBEDTLS_DHM_C) - { -(MBEDTLS_ERR_DHM_BAD_INPUT_DATA), "DHM_BAD_INPUT_DATA" }, - { -(MBEDTLS_ERR_DHM_READ_PARAMS_FAILED), "DHM_READ_PARAMS_FAILED" }, - { -(MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED), "DHM_MAKE_PARAMS_FAILED" }, - { -(MBEDTLS_ERR_DHM_READ_PUBLIC_FAILED), "DHM_READ_PUBLIC_FAILED" }, - { -(MBEDTLS_ERR_DHM_MAKE_PUBLIC_FAILED), "DHM_MAKE_PUBLIC_FAILED" }, - { -(MBEDTLS_ERR_DHM_CALC_SECRET_FAILED), "DHM_CALC_SECRET_FAILED" }, - { -(MBEDTLS_ERR_DHM_INVALID_FORMAT), "DHM_INVALID_FORMAT" }, - { -(MBEDTLS_ERR_DHM_ALLOC_FAILED), "DHM_ALLOC_FAILED" }, - { -(MBEDTLS_ERR_DHM_FILE_IO_ERROR), "DHM_FILE_IO_ERROR" }, - { -(MBEDTLS_ERR_DHM_HW_ACCEL_FAILED), "DHM_HW_ACCEL_FAILED" }, - { -(MBEDTLS_ERR_DHM_SET_GROUP_FAILED), "DHM_SET_GROUP_FAILED" }, -#endif /* MBEDTLS_DHM_C */ - -#if defined(MBEDTLS_ECP_C) - { -(MBEDTLS_ERR_ECP_BAD_INPUT_DATA), "ECP_BAD_INPUT_DATA" }, - { -(MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL), "ECP_BUFFER_TOO_SMALL" }, - { -(MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE), "ECP_FEATURE_UNAVAILABLE" }, - { -(MBEDTLS_ERR_ECP_VERIFY_FAILED), "ECP_VERIFY_FAILED" }, - { -(MBEDTLS_ERR_ECP_ALLOC_FAILED), "ECP_ALLOC_FAILED" }, - { -(MBEDTLS_ERR_ECP_RANDOM_FAILED), "ECP_RANDOM_FAILED" }, - { -(MBEDTLS_ERR_ECP_INVALID_KEY), "ECP_INVALID_KEY" }, - { -(MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH), "ECP_SIG_LEN_MISMATCH" }, -#if defined(MBEDTLS_ERR_ECP_HW_ACCEL_FAILED) - { -(MBEDTLS_ERR_ECP_HW_ACCEL_FAILED), "ECP_HW_ACCEL_FAILED" }, -#endif - { -(MBEDTLS_ERR_ECP_IN_PROGRESS), "ECP_IN_PROGRESS" }, -#endif /* MBEDTLS_ECP_C */ - -#if defined(MBEDTLS_MD_C) - { -(MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE), "MD_FEATURE_UNAVAILABLE" }, - { -(MBEDTLS_ERR_MD_BAD_INPUT_DATA), "MD_BAD_INPUT_DATA" }, - { -(MBEDTLS_ERR_MD_ALLOC_FAILED), "MD_ALLOC_FAILED" }, - { -(MBEDTLS_ERR_MD_FILE_IO_ERROR), "MD_FILE_IO_ERROR" }, -#if defined(MBEDTLS_ERR_MD_HW_ACCEL_FAILED) - { -(MBEDTLS_ERR_MD_HW_ACCEL_FAILED), "MD_HW_ACCEL_FAILED" }, -#endif -#endif /* MBEDTLS_MD_C */ - -#if defined(MBEDTLS_PEM_PARSE_C) || defined(MBEDTLS_PEM_WRITE_C) - { -(MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT), "PEM_NO_HEADER_FOOTER_PRESENT" }, - { -(MBEDTLS_ERR_PEM_INVALID_DATA), "PEM_INVALID_DATA" }, - { -(MBEDTLS_ERR_PEM_ALLOC_FAILED), "PEM_ALLOC_FAILED" }, - { -(MBEDTLS_ERR_PEM_INVALID_ENC_IV), "PEM_INVALID_ENC_IV" }, - { -(MBEDTLS_ERR_PEM_UNKNOWN_ENC_ALG), "PEM_UNKNOWN_ENC_ALG" }, - { -(MBEDTLS_ERR_PEM_PASSWORD_REQUIRED), "PEM_PASSWORD_REQUIRED" }, - { -(MBEDTLS_ERR_PEM_PASSWORD_MISMATCH), "PEM_PASSWORD_MISMATCH" }, - { -(MBEDTLS_ERR_PEM_FEATURE_UNAVAILABLE), "PEM_FEATURE_UNAVAILABLE" }, - { -(MBEDTLS_ERR_PEM_BAD_INPUT_DATA), "PEM_BAD_INPUT_DATA" }, -#endif /* MBEDTLS_PEM_PARSE_C || MBEDTLS_PEM_WRITE_C */ - -#if defined(MBEDTLS_PK_C) - { -(MBEDTLS_ERR_PK_ALLOC_FAILED), "PK_ALLOC_FAILED" }, - { -(MBEDTLS_ERR_PK_TYPE_MISMATCH), "PK_TYPE_MISMATCH" }, - { -(MBEDTLS_ERR_PK_BAD_INPUT_DATA), "PK_BAD_INPUT_DATA" }, - { -(MBEDTLS_ERR_PK_FILE_IO_ERROR), "PK_FILE_IO_ERROR" }, - { -(MBEDTLS_ERR_PK_KEY_INVALID_VERSION), "PK_KEY_INVALID_VERSION" }, - { -(MBEDTLS_ERR_PK_KEY_INVALID_FORMAT), "PK_KEY_INVALID_FORMAT" }, - { -(MBEDTLS_ERR_PK_UNKNOWN_PK_ALG), "PK_UNKNOWN_PK_ALG" }, - { -(MBEDTLS_ERR_PK_PASSWORD_REQUIRED), "PK_PASSWORD_REQUIRED" }, - { -(MBEDTLS_ERR_PK_PASSWORD_MISMATCH), "PK_PASSWORD_MISMATCH" }, - { -(MBEDTLS_ERR_PK_INVALID_PUBKEY), "PK_INVALID_PUBKEY" }, - { -(MBEDTLS_ERR_PK_INVALID_ALG), "PK_INVALID_ALG" }, - { -(MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE), "PK_UNKNOWN_NAMED_CURVE" }, - { -(MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE), "PK_FEATURE_UNAVAILABLE" }, - { -(MBEDTLS_ERR_PK_SIG_LEN_MISMATCH), "PK_SIG_LEN_MISMATCH" }, -#if defined(MBEDTLS_ERR_PK_HW_ACCEL_FAILED) - { -(MBEDTLS_ERR_PK_HW_ACCEL_FAILED), "PK_HW_ACCEL_FAILED" }, -#endif -#endif /* MBEDTLS_PK_C */ - -#if defined(MBEDTLS_PKCS12_C) - { -(MBEDTLS_ERR_PKCS12_BAD_INPUT_DATA), "PKCS12_BAD_INPUT_DATA" }, - { -(MBEDTLS_ERR_PKCS12_FEATURE_UNAVAILABLE), "PKCS12_FEATURE_UNAVAILABLE" }, - { -(MBEDTLS_ERR_PKCS12_PBE_INVALID_FORMAT), "PKCS12_PBE_INVALID_FORMAT" }, - { -(MBEDTLS_ERR_PKCS12_PASSWORD_MISMATCH), "PKCS12_PASSWORD_MISMATCH" }, -#endif /* MBEDTLS_PKCS12_C */ - -#if defined(MBEDTLS_PKCS5_C) - { -(MBEDTLS_ERR_PKCS5_BAD_INPUT_DATA), "PKCS5_BAD_INPUT_DATA" }, - { -(MBEDTLS_ERR_PKCS5_INVALID_FORMAT), "PKCS5_INVALID_FORMAT" }, - { -(MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE), "PKCS5_FEATURE_UNAVAILABLE" }, - { -(MBEDTLS_ERR_PKCS5_PASSWORD_MISMATCH), "PKCS5_PASSWORD_MISMATCH" }, -#endif /* MBEDTLS_PKCS5_C */ - -#if defined(MBEDTLS_RSA_C) - { -(MBEDTLS_ERR_RSA_BAD_INPUT_DATA), "RSA_BAD_INPUT_DATA" }, - { -(MBEDTLS_ERR_RSA_INVALID_PADDING), "RSA_INVALID_PADDING" }, - { -(MBEDTLS_ERR_RSA_KEY_GEN_FAILED), "RSA_KEY_GEN_FAILED" }, - { -(MBEDTLS_ERR_RSA_KEY_CHECK_FAILED), "RSA_KEY_CHECK_FAILED" }, - { -(MBEDTLS_ERR_RSA_PUBLIC_FAILED), "RSA_PUBLIC_FAILED" }, - { -(MBEDTLS_ERR_RSA_PRIVATE_FAILED), "RSA_PRIVATE_FAILED" }, - { -(MBEDTLS_ERR_RSA_VERIFY_FAILED), "RSA_VERIFY_FAILED" }, - { -(MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE), "RSA_OUTPUT_TOO_LARGE" }, - { -(MBEDTLS_ERR_RSA_RNG_FAILED), "RSA_RNG_FAILED" }, -#if defined(MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION) - { -(MBEDTLS_ERR_RSA_UNSUPPORTED_OPERATION), "RSA_UNSUPPORTED_OPERATION" }, -#endif -#if defined(MBEDTLS_ERR_RSA_HW_ACCEL_FAILED) - { -(MBEDTLS_ERR_RSA_HW_ACCEL_FAILED), "RSA_HW_ACCEL_FAILED" }, -#endif -#endif /* MBEDTLS_RSA_C */ +#if defined(MBEDTLS_PKCS7_C) + { -(MBEDTLS_ERR_PKCS7_INVALID_FORMAT), "PKCS7_INVALID_FORMAT" }, + { -(MBEDTLS_ERR_PKCS7_FEATURE_UNAVAILABLE), "PKCS7_FEATURE_UNAVAILABLE" }, + { -(MBEDTLS_ERR_PKCS7_INVALID_VERSION), "PKCS7_INVALID_VERSION" }, + { -(MBEDTLS_ERR_PKCS7_INVALID_CONTENT_INFO), "PKCS7_INVALID_CONTENT_INFO" }, + { -(MBEDTLS_ERR_PKCS7_INVALID_ALG), "PKCS7_INVALID_ALG" }, + { -(MBEDTLS_ERR_PKCS7_INVALID_CERT), "PKCS7_INVALID_CERT" }, + { -(MBEDTLS_ERR_PKCS7_INVALID_SIGNATURE), "PKCS7_INVALID_SIGNATURE" }, + { -(MBEDTLS_ERR_PKCS7_INVALID_SIGNER_INFO), "PKCS7_INVALID_SIGNER_INFO" }, + { -(MBEDTLS_ERR_PKCS7_CERT_DATE_INVALID), "PKCS7_CERT_DATE_INVALID" }, +#endif /* MBEDTLS_PKCS7_C */ #if defined(MBEDTLS_SSL_TLS_C) + { -(MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS), "SSL_CRYPTO_IN_PROGRESS" }, { -(MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE), "SSL_FEATURE_UNAVAILABLE" }, - { -(MBEDTLS_ERR_SSL_BAD_INPUT_DATA), "SSL_BAD_INPUT_DATA" }, { -(MBEDTLS_ERR_SSL_INVALID_MAC), "SSL_INVALID_MAC" }, { -(MBEDTLS_ERR_SSL_INVALID_RECORD), "SSL_INVALID_RECORD" }, { -(MBEDTLS_ERR_SSL_CONN_EOF), "SSL_CONN_EOF" }, -#if defined(MBEDTLS_ERR_SSL_UNKNOWN_CIPHER) - { -(MBEDTLS_ERR_SSL_UNKNOWN_CIPHER), "SSL_UNKNOWN_CIPHER" }, -#endif -#if defined(MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN) - { -(MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN), "SSL_NO_CIPHER_CHOSEN" }, -#endif + { -(MBEDTLS_ERR_SSL_DECODE_ERROR), "SSL_DECODE_ERROR" }, { -(MBEDTLS_ERR_SSL_NO_RNG), "SSL_NO_RNG" }, { -(MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE), "SSL_NO_CLIENT_CERTIFICATE" }, -#if defined(MBEDTLS_ERR_SSL_CERTIFICATE_TOO_LARGE) - { -(MBEDTLS_ERR_SSL_CERTIFICATE_TOO_LARGE), "SSL_CERTIFICATE_TOO_LARGE" }, -#endif -#if defined(MBEDTLS_ERR_SSL_CERTIFICATE_REQUIRED) - { -(MBEDTLS_ERR_SSL_CERTIFICATE_REQUIRED), "SSL_CERTIFICATE_REQUIRED" }, -#endif + { -(MBEDTLS_ERR_SSL_UNSUPPORTED_EXTENSION), "SSL_UNSUPPORTED_EXTENSION" }, + { -(MBEDTLS_ERR_SSL_NO_APPLICATION_PROTOCOL), "SSL_NO_APPLICATION_PROTOCOL" }, { -(MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED), "SSL_PRIVATE_KEY_REQUIRED" }, { -(MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED), "SSL_CA_CHAIN_REQUIRED" }, { -(MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE), "SSL_UNEXPECTED_MESSAGE" }, -#if defined(MBEDTLS_ERR_SSL_PEER_VERIFY_FAILED) - { -(MBEDTLS_ERR_SSL_PEER_VERIFY_FAILED), "SSL_PEER_VERIFY_FAILED" }, -#endif + { -(MBEDTLS_ERR_SSL_UNRECOGNIZED_NAME), "SSL_UNRECOGNIZED_NAME" }, { -(MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY), "SSL_PEER_CLOSE_NOTIFY" }, -#if defined(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO) - { -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO), "SSL_BAD_HS_CLIENT_HELLO" }, -#endif -#if defined(MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO) - { -(MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO), "SSL_BAD_HS_SERVER_HELLO" }, -#endif -#if defined(MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE) - { -(MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE), "SSL_BAD_HS_CERTIFICATE" }, -#endif -#if defined(MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST) - { -(MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST), "SSL_BAD_HS_CERTIFICATE_REQUEST" }, -#endif -#if defined(MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE) - { -(MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE), "SSL_BAD_HS_SERVER_KEY_EXCHANGE" }, -#endif -#if defined(MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO_DONE) - { -(MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO_DONE), "SSL_BAD_HS_SERVER_HELLO_DONE" }, -#endif -#if defined(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE) - { -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE), "SSL_BAD_HS_CLIENT_KEY_EXCHANGE" }, -#endif -#if defined(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP) - { -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP), "SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP" }, -#endif -#if defined(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS) - { -(MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS), "SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS" }, -#endif -#if defined(MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY) - { -(MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY), "SSL_BAD_HS_CERTIFICATE_VERIFY" }, -#endif -#if defined(MBEDTLS_ERR_SSL_BAD_HS_CHANGE_CIPHER_SPEC) - { -(MBEDTLS_ERR_SSL_BAD_HS_CHANGE_CIPHER_SPEC), "SSL_BAD_HS_CHANGE_CIPHER_SPEC" }, -#endif -#if defined(MBEDTLS_ERR_SSL_BAD_HS_FINISHED) - { -(MBEDTLS_ERR_SSL_BAD_HS_FINISHED), "SSL_BAD_HS_FINISHED" }, -#endif - { -(MBEDTLS_ERR_SSL_ALLOC_FAILED), "SSL_ALLOC_FAILED" }, + { -(MBEDTLS_ERR_SSL_BAD_CERTIFICATE), "SSL_BAD_CERTIFICATE" }, + { -(MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET), "SSL_RECEIVED_NEW_SESSION_TICKET" }, + { -(MBEDTLS_ERR_SSL_CANNOT_READ_EARLY_DATA), "SSL_CANNOT_READ_EARLY_DATA" }, + { -(MBEDTLS_ERR_SSL_RECEIVED_EARLY_DATA), "SSL_RECEIVED_EARLY_DATA" }, + { -(MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA), "SSL_CANNOT_WRITE_EARLY_DATA" }, + { -(MBEDTLS_ERR_SSL_CACHE_ENTRY_NOT_FOUND), "SSL_CACHE_ENTRY_NOT_FOUND" }, { -(MBEDTLS_ERR_SSL_HW_ACCEL_FAILED), "SSL_HW_ACCEL_FAILED" }, { -(MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH), "SSL_HW_ACCEL_FALLTHROUGH" }, -#if defined(MBEDTLS_ERR_SSL_COMPRESSION_FAILED) - { -(MBEDTLS_ERR_SSL_COMPRESSION_FAILED), "SSL_COMPRESSION_FAILED" }, -#endif -#if defined(MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION) - { -(MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION), "SSL_BAD_HS_PROTOCOL_VERSION" }, -#endif -#if defined(MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET) - { -(MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET), "SSL_BAD_HS_NEW_SESSION_TICKET" }, -#endif + { -(MBEDTLS_ERR_SSL_BAD_PROTOCOL_VERSION), "SSL_BAD_PROTOCOL_VERSION" }, + { -(MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE), "SSL_HANDSHAKE_FAILURE" }, { -(MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED), "SSL_SESSION_TICKET_EXPIRED" }, { -(MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH), "SSL_PK_TYPE_MISMATCH" }, { -(MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY), "SSL_UNKNOWN_IDENTITY" }, @@ -429,29 +157,24 @@ static const struct ssl_errs mbedtls_high_level_error_tab[] = { { -(MBEDTLS_ERR_SSL_COUNTER_WRAPPING), "SSL_COUNTER_WRAPPING" }, { -(MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO), "SSL_WAITING_SERVER_HELLO_RENEGO" }, { -(MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED), "SSL_HELLO_VERIFY_REQUIRED" }, - { -(MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL), "SSL_BUFFER_TOO_SMALL" }, -#if defined(MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE) - { -(MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE), "SSL_NO_USABLE_CIPHERSUITE" }, -#endif { -(MBEDTLS_ERR_SSL_WANT_READ), "SSL_WANT_READ" }, { -(MBEDTLS_ERR_SSL_WANT_WRITE), "SSL_WANT_WRITE" }, { -(MBEDTLS_ERR_SSL_TIMEOUT), "SSL_TIMEOUT" }, { -(MBEDTLS_ERR_SSL_CLIENT_RECONNECT), "SSL_CLIENT_RECONNECT" }, { -(MBEDTLS_ERR_SSL_UNEXPECTED_RECORD), "SSL_UNEXPECTED_RECORD" }, { -(MBEDTLS_ERR_SSL_NON_FATAL), "SSL_NON_FATAL" }, -#if defined(MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH) - { -(MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH), "SSL_INVALID_VERIFY_HASH" }, -#endif + { -(MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER), "SSL_ILLEGAL_PARAMETER" }, { -(MBEDTLS_ERR_SSL_CONTINUE_PROCESSING), "SSL_CONTINUE_PROCESSING" }, { -(MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS), "SSL_ASYNC_IN_PROGRESS" }, { -(MBEDTLS_ERR_SSL_EARLY_MESSAGE), "SSL_EARLY_MESSAGE" }, { -(MBEDTLS_ERR_SSL_UNEXPECTED_CID), "SSL_UNEXPECTED_CID" }, { -(MBEDTLS_ERR_SSL_VERSION_MISMATCH), "SSL_VERSION_MISMATCH" }, - { -(MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS), "SSL_CRYPTO_IN_PROGRESS" }, { -(MBEDTLS_ERR_SSL_BAD_CONFIG), "SSL_BAD_CONFIG" }, + { -(MBEDTLS_ERR_SSL_CERTIFICATE_VERIFICATION_WITHOUT_HOSTNAME), "SSL_CERTIFICATE_VERIFICATION_WITHOUT_HOSTNAME" }, #endif /* MBEDTLS_SSL_TLS_C */ -#if defined(MBEDTLS_X509_USE_C) || defined(MBEDTLS_X509_CREATE_C) +#if defined(MBEDTLS_X509_USE_C) || \ + defined(MBEDTLS_X509_CREATE_C) { -(MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE), "X509_FEATURE_UNAVAILABLE" }, { -(MBEDTLS_ERR_X509_UNKNOWN_OID), "X509_UNKNOWN_OID" }, { -(MBEDTLS_ERR_X509_INVALID_FORMAT), "X509_INVALID_FORMAT" }, @@ -468,11 +191,34 @@ static const struct ssl_errs mbedtls_high_level_error_tab[] = { { -(MBEDTLS_ERR_X509_CERT_VERIFY_FAILED), "X509_CERT_VERIFY_FAILED" }, { -(MBEDTLS_ERR_X509_CERT_UNKNOWN_FORMAT), "X509_CERT_UNKNOWN_FORMAT" }, { -(MBEDTLS_ERR_X509_BAD_INPUT_DATA), "X509_BAD_INPUT_DATA" }, - { -(MBEDTLS_ERR_X509_ALLOC_FAILED), "X509_ALLOC_FAILED" }, { -(MBEDTLS_ERR_X509_FILE_IO_ERROR), "X509_FILE_IO_ERROR" }, - { -(MBEDTLS_ERR_X509_BUFFER_TOO_SMALL), "X509_BUFFER_TOO_SMALL" }, { -(MBEDTLS_ERR_X509_FATAL_ERROR), "X509_FATAL_ERROR" }, -#endif /* MBEDTLS_X509_USE_C || MBEDTLS_X509_CREATE_C */ +#endif /* MBEDTLS_X509_USE_C || + MBEDTLS_X509_CREATE_C */ + +#if defined(MBEDTLS_CIPHER_C) + { -(MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE), "CIPHER_FEATURE_UNAVAILABLE" }, + { -(MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED), "CIPHER_FULL_BLOCK_EXPECTED" }, + { -(MBEDTLS_ERR_CIPHER_INVALID_CONTEXT), "CIPHER_INVALID_CONTEXT" }, +#endif /* MBEDTLS_CIPHER_C */ + +#if defined(MBEDTLS_ECP_C) + { -(MBEDTLS_ERR_ECP_INVALID_KEY), "ECP_INVALID_KEY" }, +#endif /* MBEDTLS_ECP_C */ + +#if defined(MBEDTLS_PKCS5_C) + { -(MBEDTLS_ERR_PKCS5_INVALID_FORMAT), "PKCS5_INVALID_FORMAT" }, + { -(MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE), "PKCS5_FEATURE_UNAVAILABLE" }, + { -(MBEDTLS_ERR_PKCS5_PASSWORD_MISMATCH), "PKCS5_PASSWORD_MISMATCH" }, +#endif /* MBEDTLS_PKCS5_C */ + +#if defined(MBEDTLS_RSA_C) + { -(MBEDTLS_ERR_RSA_KEY_GEN_FAILED), "RSA_KEY_GEN_FAILED" }, + { -(MBEDTLS_ERR_RSA_KEY_CHECK_FAILED), "RSA_KEY_CHECK_FAILED" }, + { -(MBEDTLS_ERR_RSA_PUBLIC_FAILED), "RSA_PUBLIC_FAILED" }, + { -(MBEDTLS_ERR_RSA_PRIVATE_FAILED), "RSA_PRIVATE_FAILED" }, + { -(MBEDTLS_ERR_RSA_RNG_FAILED), "RSA_RNG_FAILED" }, +#endif /* MBEDTLS_RSA_C */ // END generated code }; @@ -480,98 +226,46 @@ static const struct ssl_errs mbedtls_low_level_error_tab[] = { // Low level error codes // // BEGIN generated code +#if defined(MBEDTLS_NET_C) + { -(MBEDTLS_ERR_NET_SOCKET_FAILED), "NET_SOCKET_FAILED" }, + { -(MBEDTLS_ERR_NET_CONNECT_FAILED), "NET_CONNECT_FAILED" }, + { -(MBEDTLS_ERR_NET_BIND_FAILED), "NET_BIND_FAILED" }, + { -(MBEDTLS_ERR_NET_LISTEN_FAILED), "NET_LISTEN_FAILED" }, + { -(MBEDTLS_ERR_NET_ACCEPT_FAILED), "NET_ACCEPT_FAILED" }, + { -(MBEDTLS_ERR_NET_RECV_FAILED), "NET_RECV_FAILED" }, + { -(MBEDTLS_ERR_NET_SEND_FAILED), "NET_SEND_FAILED" }, + { -(MBEDTLS_ERR_NET_CONN_RESET), "NET_CONN_RESET" }, + { -(MBEDTLS_ERR_NET_UNKNOWN_HOST), "NET_UNKNOWN_HOST" }, + { -(MBEDTLS_ERR_NET_INVALID_CONTEXT), "NET_INVALID_CONTEXT" }, + { -(MBEDTLS_ERR_NET_POLL_FAILED), "NET_POLL_FAILED" }, + { -(MBEDTLS_ERR_NET_BAD_INPUT_DATA), "NET_BAD_INPUT_DATA" }, +#endif /* MBEDTLS_NET_C */ + #if defined(MBEDTLS_AES_C) { -(MBEDTLS_ERR_AES_INVALID_KEY_LENGTH), "AES_INVALID_KEY_LENGTH" }, { -(MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH), "AES_INVALID_INPUT_LENGTH" }, - { -(MBEDTLS_ERR_AES_BAD_INPUT_DATA), "AES_BAD_INPUT_DATA" }, -#if defined(MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE) - { -(MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE), "AES_FEATURE_UNAVAILABLE" }, -#endif -#if defined(MBEDTLS_ERR_AES_HW_ACCEL_FAILED) - { -(MBEDTLS_ERR_AES_HW_ACCEL_FAILED), "AES_HW_ACCEL_FAILED" }, -#endif #endif /* MBEDTLS_AES_C */ -#if defined(MBEDTLS_ARC4_C) - { -(MBEDTLS_ERR_ARC4_HW_ACCEL_FAILED), "ARC4_HW_ACCEL_FAILED" }, -#endif /* MBEDTLS_ARC4_C */ - #if defined(MBEDTLS_ARIA_C) - { -(MBEDTLS_ERR_ARIA_BAD_INPUT_DATA), "ARIA_BAD_INPUT_DATA" }, { -(MBEDTLS_ERR_ARIA_INVALID_INPUT_LENGTH), "ARIA_INVALID_INPUT_LENGTH" }, -#if defined(MBEDTLS_ERR_ARIA_FEATURE_UNAVAILABLE) - { -(MBEDTLS_ERR_ARIA_FEATURE_UNAVAILABLE), "ARIA_FEATURE_UNAVAILABLE" }, -#endif -#if defined(MBEDTLS_ERR_ARIA_HW_ACCEL_FAILED) - { -(MBEDTLS_ERR_ARIA_HW_ACCEL_FAILED), "ARIA_HW_ACCEL_FAILED" }, -#endif #endif /* MBEDTLS_ARIA_C */ -#if defined(MBEDTLS_ASN1_PARSE_C) - { -(MBEDTLS_ERR_ASN1_OUT_OF_DATA), "ASN1_OUT_OF_DATA" }, - { -(MBEDTLS_ERR_ASN1_UNEXPECTED_TAG), "ASN1_UNEXPECTED_TAG" }, - { -(MBEDTLS_ERR_ASN1_INVALID_LENGTH), "ASN1_INVALID_LENGTH" }, - { -(MBEDTLS_ERR_ASN1_LENGTH_MISMATCH), "ASN1_LENGTH_MISMATCH" }, - { -(MBEDTLS_ERR_ASN1_INVALID_DATA), "ASN1_INVALID_DATA" }, - { -(MBEDTLS_ERR_ASN1_ALLOC_FAILED), "ASN1_ALLOC_FAILED" }, - { -(MBEDTLS_ERR_ASN1_BUF_TOO_SMALL), "ASN1_BUF_TOO_SMALL" }, -#endif /* MBEDTLS_ASN1_PARSE_C */ - -#if defined(MBEDTLS_BASE64_C) - { -(MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL), "BASE64_BUFFER_TOO_SMALL" }, - { -(MBEDTLS_ERR_BASE64_INVALID_CHARACTER), "BASE64_INVALID_CHARACTER" }, -#endif /* MBEDTLS_BASE64_C */ - #if defined(MBEDTLS_BIGNUM_C) { -(MBEDTLS_ERR_MPI_FILE_IO_ERROR), "MPI_FILE_IO_ERROR" }, - { -(MBEDTLS_ERR_MPI_BAD_INPUT_DATA), "MPI_BAD_INPUT_DATA" }, { -(MBEDTLS_ERR_MPI_INVALID_CHARACTER), "MPI_INVALID_CHARACTER" }, - { -(MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL), "MPI_BUFFER_TOO_SMALL" }, { -(MBEDTLS_ERR_MPI_NEGATIVE_VALUE), "MPI_NEGATIVE_VALUE" }, { -(MBEDTLS_ERR_MPI_DIVISION_BY_ZERO), "MPI_DIVISION_BY_ZERO" }, { -(MBEDTLS_ERR_MPI_NOT_ACCEPTABLE), "MPI_NOT_ACCEPTABLE" }, - { -(MBEDTLS_ERR_MPI_ALLOC_FAILED), "MPI_ALLOC_FAILED" }, #endif /* MBEDTLS_BIGNUM_C */ -#if defined(MBEDTLS_BLOWFISH_C) - { -(MBEDTLS_ERR_BLOWFISH_BAD_INPUT_DATA), "BLOWFISH_BAD_INPUT_DATA" }, - { -(MBEDTLS_ERR_BLOWFISH_INVALID_INPUT_LENGTH), "BLOWFISH_INVALID_INPUT_LENGTH" }, - { -(MBEDTLS_ERR_BLOWFISH_HW_ACCEL_FAILED), "BLOWFISH_HW_ACCEL_FAILED" }, -#endif /* MBEDTLS_BLOWFISH_C */ - #if defined(MBEDTLS_CAMELLIA_C) - { -(MBEDTLS_ERR_CAMELLIA_BAD_INPUT_DATA), "CAMELLIA_BAD_INPUT_DATA" }, { -(MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH), "CAMELLIA_INVALID_INPUT_LENGTH" }, - { -(MBEDTLS_ERR_CAMELLIA_HW_ACCEL_FAILED), "CAMELLIA_HW_ACCEL_FAILED" }, #endif /* MBEDTLS_CAMELLIA_C */ -#if defined(MBEDTLS_CCM_C) - { -(MBEDTLS_ERR_CCM_BAD_INPUT), "CCM_BAD_INPUT" }, - { -(MBEDTLS_ERR_CCM_AUTH_FAILED), "CCM_AUTH_FAILED" }, -#if defined(MBEDTLS_ERR_CCM_HW_ACCEL_FAILED) - { -(MBEDTLS_ERR_CCM_HW_ACCEL_FAILED), "CCM_HW_ACCEL_FAILED" }, -#endif -#endif /* MBEDTLS_CCM_C */ - -#if defined(MBEDTLS_CHACHA20_C) - { -(MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA), "CHACHA20_BAD_INPUT_DATA" }, - { -(MBEDTLS_ERR_CHACHA20_FEATURE_UNAVAILABLE), "CHACHA20_FEATURE_UNAVAILABLE" }, -#if defined(MBEDTLS_ERR_CHACHA20_HW_ACCEL_FAILED) - { -(MBEDTLS_ERR_CHACHA20_HW_ACCEL_FAILED), "CHACHA20_HW_ACCEL_FAILED" }, -#endif -#endif /* MBEDTLS_CHACHA20_C */ - #if defined(MBEDTLS_CHACHAPOLY_C) { -(MBEDTLS_ERR_CHACHAPOLY_BAD_STATE), "CHACHAPOLY_BAD_STATE" }, - { -(MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED), "CHACHAPOLY_AUTH_FAILED" }, #endif /* MBEDTLS_CHACHAPOLY_C */ -#if defined(MBEDTLS_CMAC_C) -#if defined(MBEDTLS_ERR_CMAC_HW_ACCEL_FAILED) - { -(MBEDTLS_ERR_CMAC_HW_ACCEL_FAILED), "CMAC_HW_ACCEL_FAILED" }, -#endif -#endif /* MBEDTLS_CMAC_C */ - #if defined(MBEDTLS_CTR_DRBG_C) { -(MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED), "CTR_DRBG_ENTROPY_SOURCE_FAILED" }, { -(MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG), "CTR_DRBG_REQUEST_TOO_BIG" }, @@ -579,128 +273,19 @@ static const struct ssl_errs mbedtls_low_level_error_tab[] = { { -(MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR), "CTR_DRBG_FILE_IO_ERROR" }, #endif /* MBEDTLS_CTR_DRBG_C */ -#if defined(MBEDTLS_DES_C) - { -(MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH), "DES_INVALID_INPUT_LENGTH" }, - { -(MBEDTLS_ERR_DES_HW_ACCEL_FAILED), "DES_HW_ACCEL_FAILED" }, -#endif /* MBEDTLS_DES_C */ - #if defined(MBEDTLS_ENTROPY_C) - { -(MBEDTLS_ERR_ENTROPY_SOURCE_FAILED), "ENTROPY_SOURCE_FAILED" }, { -(MBEDTLS_ERR_ENTROPY_MAX_SOURCES), "ENTROPY_MAX_SOURCES" }, { -(MBEDTLS_ERR_ENTROPY_NO_SOURCES_DEFINED), "ENTROPY_NO_SOURCES_DEFINED" }, { -(MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE), "ENTROPY_NO_STRONG_SOURCE" }, { -(MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR), "ENTROPY_FILE_IO_ERROR" }, #endif /* MBEDTLS_ENTROPY_C */ -#if defined(MBEDTLS_ERROR_C) - { -(MBEDTLS_ERR_ERROR_GENERIC_ERROR), "ERROR_GENERIC_ERROR" }, - { -(MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED), "ERROR_CORRUPTION_DETECTED" }, -#endif /* MBEDTLS_ERROR_C */ - -#if defined(MBEDTLS_GCM_C) - { -(MBEDTLS_ERR_GCM_AUTH_FAILED), "GCM_AUTH_FAILED" }, -#if defined(MBEDTLS_ERR_GCM_HW_ACCEL_FAILED) - { -(MBEDTLS_ERR_GCM_HW_ACCEL_FAILED), "GCM_HW_ACCEL_FAILED" }, -#endif - { -(MBEDTLS_ERR_GCM_BAD_INPUT), "GCM_BAD_INPUT" }, -#endif /* MBEDTLS_GCM_C */ - -#if defined(MBEDTLS_HKDF_C) - { -(MBEDTLS_ERR_HKDF_BAD_INPUT_DATA), "HKDF_BAD_INPUT_DATA" }, -#endif /* MBEDTLS_HKDF_C */ - #if defined(MBEDTLS_HMAC_DRBG_C) { -(MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG), "HMAC_DRBG_REQUEST_TOO_BIG" }, { -(MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG), "HMAC_DRBG_INPUT_TOO_BIG" }, { -(MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR), "HMAC_DRBG_FILE_IO_ERROR" }, { -(MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED), "HMAC_DRBG_ENTROPY_SOURCE_FAILED" }, #endif /* MBEDTLS_HMAC_DRBG_C */ - -#if defined(MBEDTLS_MD2_C) - { -(MBEDTLS_ERR_MD2_HW_ACCEL_FAILED), "MD2_HW_ACCEL_FAILED" }, -#endif /* MBEDTLS_MD2_C */ - -#if defined(MBEDTLS_MD4_C) - { -(MBEDTLS_ERR_MD4_HW_ACCEL_FAILED), "MD4_HW_ACCEL_FAILED" }, -#endif /* MBEDTLS_MD4_C */ - -#if defined(MBEDTLS_MD5_C) -#if defined(MBEDTLS_ERR_MD5_HW_ACCEL_FAILED) - { -(MBEDTLS_ERR_MD5_HW_ACCEL_FAILED), "MD5_HW_ACCEL_FAILED" }, -#endif -#endif /* MBEDTLS_MD5_C */ - -#if defined(MBEDTLS_NET_C) - { -(MBEDTLS_ERR_NET_SOCKET_FAILED), "NET_SOCKET_FAILED" }, - { -(MBEDTLS_ERR_NET_CONNECT_FAILED), "NET_CONNECT_FAILED" }, - { -(MBEDTLS_ERR_NET_BIND_FAILED), "NET_BIND_FAILED" }, - { -(MBEDTLS_ERR_NET_LISTEN_FAILED), "NET_LISTEN_FAILED" }, - { -(MBEDTLS_ERR_NET_ACCEPT_FAILED), "NET_ACCEPT_FAILED" }, - { -(MBEDTLS_ERR_NET_RECV_FAILED), "NET_RECV_FAILED" }, - { -(MBEDTLS_ERR_NET_SEND_FAILED), "NET_SEND_FAILED" }, - { -(MBEDTLS_ERR_NET_CONN_RESET), "NET_CONN_RESET" }, - { -(MBEDTLS_ERR_NET_UNKNOWN_HOST), "NET_UNKNOWN_HOST" }, - { -(MBEDTLS_ERR_NET_BUFFER_TOO_SMALL), "NET_BUFFER_TOO_SMALL" }, - { -(MBEDTLS_ERR_NET_INVALID_CONTEXT), "NET_INVALID_CONTEXT" }, - { -(MBEDTLS_ERR_NET_POLL_FAILED), "NET_POLL_FAILED" }, - { -(MBEDTLS_ERR_NET_BAD_INPUT_DATA), "NET_BAD_INPUT_DATA" }, -#endif /* MBEDTLS_NET_C */ - -#if defined(MBEDTLS_OID_C) - { -(MBEDTLS_ERR_OID_NOT_FOUND), "OID_NOT_FOUND" }, - { -(MBEDTLS_ERR_OID_BUF_TOO_SMALL), "OID_BUF_TOO_SMALL" }, -#endif /* MBEDTLS_OID_C */ - -#if defined(MBEDTLS_PADLOCK_C) - { -(MBEDTLS_ERR_PADLOCK_DATA_MISALIGNED), "PADLOCK_DATA_MISALIGNED" }, -#endif /* MBEDTLS_PADLOCK_C */ - -#if defined(MBEDTLS_PLATFORM_C) - { -(MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED), "PLATFORM_HW_ACCEL_FAILED" }, - { -(MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED), "PLATFORM_FEATURE_UNSUPPORTED" }, -#endif /* MBEDTLS_PLATFORM_C */ - -#if defined(MBEDTLS_POLY1305_C) - { -(MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA), "POLY1305_BAD_INPUT_DATA" }, - { -(MBEDTLS_ERR_POLY1305_FEATURE_UNAVAILABLE), "POLY1305_FEATURE_UNAVAILABLE" }, - { -(MBEDTLS_ERR_POLY1305_HW_ACCEL_FAILED), "POLY1305_HW_ACCEL_FAILED" }, -#endif /* MBEDTLS_POLY1305_C */ - -#if defined(MBEDTLS_RIPEMD160_C) - { -(MBEDTLS_ERR_RIPEMD160_HW_ACCEL_FAILED), "RIPEMD160_HW_ACCEL_FAILED" }, -#endif /* MBEDTLS_RIPEMD160_C */ - -#if defined(MBEDTLS_SHA1_C) -#if defined(MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED) - { -(MBEDTLS_ERR_SHA1_HW_ACCEL_FAILED), "SHA1_HW_ACCEL_FAILED" }, -#endif - { -(MBEDTLS_ERR_SHA1_BAD_INPUT_DATA), "SHA1_BAD_INPUT_DATA" }, -#endif /* MBEDTLS_SHA1_C */ - -#if defined(MBEDTLS_SHA256_C) -#if defined(MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED) - { -(MBEDTLS_ERR_SHA256_HW_ACCEL_FAILED), "SHA256_HW_ACCEL_FAILED" }, -#endif - { -(MBEDTLS_ERR_SHA256_BAD_INPUT_DATA), "SHA256_BAD_INPUT_DATA" }, -#endif /* MBEDTLS_SHA256_C */ - -#if defined(MBEDTLS_SHA512_C) -#if defined(MBEDTLS_ERR_SHA512_HW_ACCEL_FAILED) - { -(MBEDTLS_ERR_SHA512_HW_ACCEL_FAILED), "SHA512_HW_ACCEL_FAILED" }, -#endif - { -(MBEDTLS_ERR_SHA512_BAD_INPUT_DATA), "SHA512_BAD_INPUT_DATA" }, -#endif /* MBEDTLS_SHA512_C */ - -#if defined(MBEDTLS_THREADING_C) - { -(MBEDTLS_ERR_THREADING_FEATURE_UNAVAILABLE), "THREADING_FEATURE_UNAVAILABLE" }, - { -(MBEDTLS_ERR_THREADING_BAD_INPUT_DATA), "THREADING_BAD_INPUT_DATA" }, - { -(MBEDTLS_ERR_THREADING_MUTEX_ERROR), "THREADING_MUTEX_ERROR" }, -#endif /* MBEDTLS_THREADING_C */ - -#if defined(MBEDTLS_XTEA_C) - { -(MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH), "XTEA_INVALID_INPUT_LENGTH" }, - { -(MBEDTLS_ERR_XTEA_HW_ACCEL_FAILED), "XTEA_HW_ACCEL_FAILED" }, -#endif /* MBEDTLS_XTEA_C */ // END generated code }; diff --git a/lib/micropython-lib b/lib/micropython-lib index 50ed36fbeb9..ee4bb8ff139 160000 --- a/lib/micropython-lib +++ b/lib/micropython-lib @@ -1 +1 @@ -Subproject commit 50ed36fbeb919753bcc26ce13a8cffd7691d06ef +Subproject commit ee4bb8ff139e24c42b739935fbd8ec7c4d061e02 diff --git a/lib/protomatter b/lib/protomatter index 0bd9873153a..0f51ca23474 160000 --- a/lib/protomatter +++ b/lib/protomatter @@ -1 +1 @@ -Subproject commit 0bd9873153ab0a91d6737c392622159a4515a2e5 +Subproject commit 0f51ca2347479228d8cb96fd3f410b032fe6dbad diff --git a/lib/re1.5/compilecode.c b/lib/re1.5/compilecode.c index 63ae1e02b8d..77a0b8ff2a6 100644 --- a/lib/re1.5/compilecode.c +++ b/lib/re1.5/compilecode.c @@ -50,6 +50,8 @@ static const char *_compilecode(const char *re, ByteProg *prog, int sizecode) int term = PC; int alt_label = 0; + re1_5_stack_chk(); + for (; *re && *re != ')'; re++) { switch (*re) { case '\\': diff --git a/lib/tinytest/README b/lib/tinytest/README deleted file mode 100644 index 28165d8bc79..00000000000 --- a/lib/tinytest/README +++ /dev/null @@ -1,17 +0,0 @@ -Tinytest is a tiny little test framework written in C by Nick Mathewson. - -It is distributed under the 3-clause BSD license. You can use it in -your own programs so long as you follow the license's conditions. - -It's been tested on Windows, Mac, and many of the free Unixes. - -It knows how to fork before running certain tests, and it makes -text-mode output in a format I like. - -For info on how to use it, check out tinytest_demo.c. - -You can get the latest version using Git, by pulling from - git://github.com/nmathewson/tinytest.git - -Patches are welcome. Patches that turn this from tinytest to hugetest -will not be applied. If you want a huge test framework, use CUnit. diff --git a/lib/tinytest/tinytest.c b/lib/tinytest/tinytest.c deleted file mode 100644 index 1a5030ae3c5..00000000000 --- a/lib/tinytest/tinytest.c +++ /dev/null @@ -1,473 +0,0 @@ -/* tinytest.c -- Copyright 2009-2012 Nick Mathewson - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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. - */ -#ifdef TINYTEST_LOCAL -#include "tinytest_local.h" -#endif - -#include -#include -#include -#include - -#ifndef NO_FORKING - -#ifdef _WIN32 -#include -#else -#include -#include -#include -#endif - -#if defined(__APPLE__) && defined(__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__) -#if (__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ >= 1060 && \ - __ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__ < 1070) -/* Workaround for a stupid bug in OSX 10.6 */ -#define FORK_BREAKS_GCOV -#include -#endif -#endif - -#endif /* !NO_FORKING */ - -#ifndef __GNUC__ -#define __attribute__(x) -#endif - -#include "tinytest.h" -#include "tinytest_macros.h" - -#define LONGEST_TEST_NAME 16384 - -static int in_tinytest_main = 0; /**< true if we're in tinytest_main().*/ -static int n_ok = 0; /**< Number of tests that have passed */ -static int n_bad = 0; /**< Number of tests that have failed. */ -static int n_skipped = 0; /**< Number of tests that have been skipped. */ - -static int opt_forked = 0; /**< True iff we're called from inside a win32 fork*/ -static int opt_nofork = 0; /**< Suppress calls to fork() for debugging. */ -static int opt_verbosity = 1; /**< -==quiet,0==terse,1==normal,2==verbose */ -const char *verbosity_flag = ""; - -const struct testlist_alias_t *cfg_aliases=NULL; - -enum outcome { SKIP=2, OK=1, FAIL=0 }; -static enum outcome cur_test_outcome = 0; -const char *cur_test_prefix = NULL; /**< prefix of the current test group */ -/** Name of the current test, if we haven't logged is yet. Used for --quiet */ -const char *cur_test_name = NULL; - -#ifdef _WIN32 -/* Copy of argv[0] for win32. */ -static char commandname[MAX_PATH+1]; -#endif - -static void usage(struct testgroup_t *groups, int list_groups) - __attribute__((noreturn)); -static int process_test_option(struct testgroup_t *groups, const char *test); - -static enum outcome -testcase_run_bare_(const struct testcase_t *testcase) -{ - void *env = NULL; - int outcome; - if (testcase->setup) { - env = testcase->setup->setup_fn(testcase); - if (!env) - return FAIL; - else if (env == (void*)TT_SKIP) - return SKIP; - } - - cur_test_outcome = OK; - testcase->fn(env); - outcome = cur_test_outcome; - - if (testcase->setup) { - if (testcase->setup->cleanup_fn(testcase, env) == 0) - outcome = FAIL; - } - - return outcome; -} - -#define MAGIC_EXITCODE 42 - -#ifndef NO_FORKING - -static enum outcome -testcase_run_forked_(const struct testgroup_t *group, - const struct testcase_t *testcase) -{ -#ifdef _WIN32 - /* Fork? On Win32? How primitive! We'll do what the smart kids do: - we'll invoke our own exe (whose name we recall from the command - line) with a command line that tells it to run just the test we - want, and this time without forking. - - (No, threads aren't an option. The whole point of forking is to - share no state between tests.) - */ - int ok; - char buffer[LONGEST_TEST_NAME+256]; - STARTUPINFOA si; - PROCESS_INFORMATION info; - DWORD exitcode; - - if (!in_tinytest_main) { - printf("\nERROR. On Windows, testcase_run_forked_ must be" - " called from within tinytest_main.\n"); - abort(); - } - if (opt_verbosity>0) - printf("[forking] "); - - snprintf(buffer, sizeof(buffer), "%s --RUNNING-FORKED %s %s%s", - commandname, verbosity_flag, group->prefix, testcase->name); - - memset(&si, 0, sizeof(si)); - memset(&info, 0, sizeof(info)); - si.cb = sizeof(si); - - ok = CreateProcessA(commandname, buffer, NULL, NULL, 0, - 0, NULL, NULL, &si, &info); - if (!ok) { - printf("CreateProcess failed!\n"); - return 0; - } - WaitForSingleObject(info.hProcess, INFINITE); - GetExitCodeProcess(info.hProcess, &exitcode); - CloseHandle(info.hProcess); - CloseHandle(info.hThread); - if (exitcode == 0) - return OK; - else if (exitcode == MAGIC_EXITCODE) - return SKIP; - else - return FAIL; -#else - int outcome_pipe[2]; - pid_t pid; - (void)group; - - if (pipe(outcome_pipe)) - perror("opening pipe"); - - if (opt_verbosity>0) - printf("[forking] "); - pid = fork(); -#ifdef FORK_BREAKS_GCOV - vproc_transaction_begin(0); -#endif - if (!pid) { - /* child. */ - int test_r, write_r; - char b[1]; - close(outcome_pipe[0]); - test_r = testcase_run_bare_(testcase); - assert(0<=(int)test_r && (int)test_r<=2); - b[0] = "NYS"[test_r]; - write_r = (int)write(outcome_pipe[1], b, 1); - if (write_r != 1) { - perror("write outcome to pipe"); - exit(1); - } - exit(0); - return FAIL; /* unreachable */ - } else { - /* parent */ - int status, r; - char b[1]; - /* Close this now, so that if the other side closes it, - * our read fails. */ - close(outcome_pipe[1]); - r = (int)read(outcome_pipe[0], b, 1); - if (r == 0) { - printf("[Lost connection!] "); - return 0; - } else if (r != 1) { - perror("read outcome from pipe"); - } - waitpid(pid, &status, 0); - close(outcome_pipe[0]); - return b[0]=='Y' ? OK : (b[0]=='S' ? SKIP : FAIL); - } -#endif -} - -#endif /* !NO_FORKING */ - -int -testcase_run_one(const struct testgroup_t *group, - const struct testcase_t *testcase) -{ - enum outcome outcome; - - if (testcase->flags & (TT_SKIP|TT_OFF_BY_DEFAULT)) { - if (opt_verbosity>0) - printf("%s%s: %s\n", - group->prefix, testcase->name, - (testcase->flags & TT_SKIP) ? "SKIPPED" : "DISABLED"); - ++n_skipped; - return SKIP; - } - - if (opt_verbosity>0 && !opt_forked) { - printf("%s%s: ", group->prefix, testcase->name); - } else { - if (opt_verbosity==0) printf("."); - cur_test_prefix = group->prefix; - cur_test_name = testcase->name; - } - -#ifndef NO_FORKING - if ((testcase->flags & TT_FORK) && !(opt_forked||opt_nofork)) { - outcome = testcase_run_forked_(group, testcase); - } else { -#else - { -#endif - outcome = testcase_run_bare_(testcase); - } - - if (outcome == OK) { - ++n_ok; - if (opt_verbosity>0 && !opt_forked) - puts(opt_verbosity==1?"OK":""); - } else if (outcome == SKIP) { - ++n_skipped; - if (opt_verbosity>0 && !opt_forked) - puts("SKIPPED"); - } else { - ++n_bad; - if (!opt_forked) - printf("\n [%s FAILED]\n", testcase->name); - } - - if (opt_forked) { - exit(outcome==OK ? 0 : (outcome==SKIP?MAGIC_EXITCODE : 1)); - return 1; /* unreachable */ - } else { - return (int)outcome; - } -} - -int -tinytest_set_flag_(struct testgroup_t *groups, const char *arg, int set, unsigned long flag) -{ - int i, j; - size_t length = LONGEST_TEST_NAME; - char fullname[LONGEST_TEST_NAME]; - int found=0; - if (strstr(arg, "..")) - length = strstr(arg,"..")-arg; - for (i=0; groups[i].prefix; ++i) { - for (j=0; groups[i].cases[j].name; ++j) { - struct testcase_t *testcase = &groups[i].cases[j]; - snprintf(fullname, sizeof(fullname), "%s%s", - groups[i].prefix, testcase->name); - if (!flag) { /* Hack! */ - printf(" %s", fullname); - if (testcase->flags & TT_OFF_BY_DEFAULT) - puts(" (Off by default)"); - else if (testcase->flags & TT_SKIP) - puts(" (DISABLED)"); - else - puts(""); - } - if (!strncmp(fullname, arg, length)) { - if (set) - testcase->flags |= flag; - else - testcase->flags &= ~flag; - ++found; - } - } - } - return found; -} - -static void -usage(struct testgroup_t *groups, int list_groups) -{ - puts("Options are: [--verbose|--quiet|--terse] [--no-fork]"); - puts(" Specify tests by name, or using a prefix ending with '..'"); - puts(" To skip a test, prefix its name with a colon."); - puts(" To enable a disabled test, prefix its name with a plus."); - puts(" Use --list-tests for a list of tests."); - if (list_groups) { - puts("Known tests are:"); - tinytest_set_flag_(groups, "..", 1, 0); - } - exit(0); -} - -static int -process_test_alias(struct testgroup_t *groups, const char *test) -{ - int i, j, n, r; - for (i=0; cfg_aliases && cfg_aliases[i].name; ++i) { - if (!strcmp(cfg_aliases[i].name, test)) { - n = 0; - for (j = 0; cfg_aliases[i].tests[j]; ++j) { - r = process_test_option(groups, cfg_aliases[i].tests[j]); - if (r<0) - return -1; - n += r; - } - return n; - } - } - printf("No such test alias as @%s!",test); - return -1; -} - -static int -process_test_option(struct testgroup_t *groups, const char *test) -{ - int flag = TT_ENABLED_; - int n = 0; - if (test[0] == '@') { - return process_test_alias(groups, test + 1); - } else if (test[0] == ':') { - ++test; - flag = TT_SKIP; - } else if (test[0] == '+') { - ++test; - ++n; - if (!tinytest_set_flag_(groups, test, 0, TT_OFF_BY_DEFAULT)) { - printf("No such test as %s!\n", test); - return -1; - } - } else { - ++n; - } - if (!tinytest_set_flag_(groups, test, 1, flag)) { - printf("No such test as %s!\n", test); - return -1; - } - return n; -} - -void -tinytest_set_aliases(const struct testlist_alias_t *aliases) -{ - cfg_aliases = aliases; -} - -int -tinytest_main(int c, const char **v, struct testgroup_t *groups) -{ - int i, j, n=0; - -#ifdef _WIN32 - const char *sp = strrchr(v[0], '.'); - const char *extension = ""; - if (!sp || stricmp(sp, ".exe")) - extension = ".exe"; /* Add an exe so CreateProcess will work */ - snprintf(commandname, sizeof(commandname), "%s%s", v[0], extension); - commandname[MAX_PATH]='\0'; -#endif - for (i=1; i= 1) - printf("%d tests ok. (%d skipped)\n", n_ok, n_skipped); - - return (n_bad == 0) ? 0 : 1; -} - -int -tinytest_get_verbosity_(void) -{ - return opt_verbosity; -} - -void -tinytest_set_test_failed_(void) -{ - if (opt_verbosity <= 0 && cur_test_name) { - if (opt_verbosity==0) puts(""); - printf("%s%s: ", cur_test_prefix, cur_test_name); - cur_test_name = NULL; - } - cur_test_outcome = 0; -} - -void -tinytest_set_test_skipped_(void) -{ - if (cur_test_outcome==OK) - cur_test_outcome = SKIP; -} diff --git a/lib/tinytest/tinytest.h b/lib/tinytest/tinytest.h deleted file mode 100644 index dff440e3190..00000000000 --- a/lib/tinytest/tinytest.h +++ /dev/null @@ -1,98 +0,0 @@ -/* tinytest.h -- Copyright 2009-2012 Nick Mathewson - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 TINYTEST_H_INCLUDED_ -#define TINYTEST_H_INCLUDED_ - -/** Flag for a test that needs to run in a subprocess. */ -#define TT_FORK (1<<0) -/** Runtime flag for a test we've decided to skip. */ -#define TT_SKIP (1<<1) -/** Internal runtime flag for a test we've decided to run. */ -#define TT_ENABLED_ (1<<2) -/** Flag for a test that's off by default. */ -#define TT_OFF_BY_DEFAULT (1<<3) -/** If you add your own flags, make them start at this point. */ -#define TT_FIRST_USER_FLAG (1<<4) - -typedef void (*testcase_fn)(void *); - -struct testcase_t; - -/** Functions to initialize/teardown a structure for a testcase. */ -struct testcase_setup_t { - /** Return a new structure for use by a given testcase. */ - void *(*setup_fn)(const struct testcase_t *); - /** Clean/free a structure from setup_fn. Return 1 if ok, 0 on err. */ - int (*cleanup_fn)(const struct testcase_t *, void *); -}; - -/** A single test-case that you can run. */ -struct testcase_t { - const char *name; /**< An identifier for this case. */ - testcase_fn fn; /**< The function to run to implement this case. */ - unsigned long flags; /**< Bitfield of TT_* flags. */ - const struct testcase_setup_t *setup; /**< Optional setup/cleanup fns*/ - void *setup_data; /**< Extra data usable by setup function */ -}; -#define END_OF_TESTCASES { NULL, NULL, 0, NULL, NULL } - -/** A group of tests that are selectable together. */ -struct testgroup_t { - const char *prefix; /**< Prefix to prepend to testnames. */ - struct testcase_t *cases; /** Array, ending with END_OF_TESTCASES */ -}; -#define END_OF_GROUPS { NULL, NULL} - -struct testlist_alias_t { - const char *name; - const char **tests; -}; -#define END_OF_ALIASES { NULL, NULL } - -/** Implementation: called from a test to indicate failure, before logging. */ -void tinytest_set_test_failed_(void); -/** Implementation: called from a test to indicate that we're skipping. */ -void tinytest_set_test_skipped_(void); -/** Implementation: return 0 for quiet, 1 for normal, 2 for loud. */ -int tinytest_get_verbosity_(void); -/** Implementation: Set a flag on tests matching a name; returns number - * of tests that matched. */ -int tinytest_set_flag_(struct testgroup_t *, const char *, int set, unsigned long); - -/** Set all tests in 'groups' matching the name 'named' to be skipped. */ -#define tinytest_skip(groups, named) \ - tinytest_set_flag_(groups, named, 1, TT_SKIP) - -/** Run a single testcase in a single group. */ -int testcase_run_one(const struct testgroup_t *,const struct testcase_t *); - -void tinytest_set_aliases(const struct testlist_alias_t *aliases); - -/** Run a set of testcases from an END_OF_GROUPS-terminated array of groups, - as selected from the command line. */ -int tinytest_main(int argc, const char **argv, struct testgroup_t *groups); - -#endif diff --git a/lib/tinytest/tinytest_macros.h b/lib/tinytest/tinytest_macros.h deleted file mode 100644 index 9ff69b1d506..00000000000 --- a/lib/tinytest/tinytest_macros.h +++ /dev/null @@ -1,184 +0,0 @@ -/* tinytest_macros.h -- Copyright 2009-2012 Nick Mathewson - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. 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. - * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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 TINYTEST_MACROS_H_INCLUDED_ -#define TINYTEST_MACROS_H_INCLUDED_ - -/* Helpers for defining statement-like macros */ -#define TT_STMT_BEGIN do { -#define TT_STMT_END } while (0) - -/* Redefine this if your test functions want to abort with something besides - * "goto end;" */ -#ifndef TT_EXIT_TEST_FUNCTION -#define TT_EXIT_TEST_FUNCTION TT_STMT_BEGIN goto end; TT_STMT_END -#endif - -/* Redefine this if you want to note success/failure in some different way. */ -#ifndef TT_DECLARE -#define TT_DECLARE(prefix, args) \ - TT_STMT_BEGIN \ - printf("\n %s %s:%d: ",prefix,__FILE__,__LINE__); \ - printf args ; \ - TT_STMT_END -#endif - -/* Announce a failure. Args are parenthesized printf args. */ -#define TT_GRIPE(args) TT_DECLARE("FAIL", args) - -/* Announce a non-failure if we're verbose. */ -#define TT_BLATHER(args) \ - TT_STMT_BEGIN \ - if (tinytest_get_verbosity_()>1) TT_DECLARE(" OK", args); \ - TT_STMT_END - -#define TT_DIE(args) \ - TT_STMT_BEGIN \ - tinytest_set_test_failed_(); \ - TT_GRIPE(args); \ - TT_EXIT_TEST_FUNCTION; \ - TT_STMT_END - -#define TT_FAIL(args) \ - TT_STMT_BEGIN \ - tinytest_set_test_failed_(); \ - TT_GRIPE(args); \ - TT_STMT_END - -/* Fail and abort the current test for the reason in msg */ -#define tt_abort_printf(msg) TT_DIE(msg) -#define tt_abort_perror(op) TT_DIE(("%s: %s [%d]",(op),strerror(errno), errno)) -#define tt_abort_msg(msg) TT_DIE(("%s", msg)) -#define tt_abort() TT_DIE(("%s", "(Failed.)")) - -/* Fail but do not abort the current test for the reason in msg. */ -#define tt_failprint_f(msg) TT_FAIL(msg) -#define tt_fail_perror(op) TT_FAIL(("%s: %s [%d]",(op),strerror(errno), errno)) -#define tt_fail_msg(msg) TT_FAIL(("%s", msg)) -#define tt_fail() TT_FAIL(("%s", "(Failed.)")) - -/* End the current test, and indicate we are skipping it. */ -#define tt_skip() \ - TT_STMT_BEGIN \ - tinytest_set_test_skipped_(); \ - TT_EXIT_TEST_FUNCTION; \ - TT_STMT_END - -#define tt_want_(b, msg, fail) \ - TT_STMT_BEGIN \ - if (!(b)) { \ - tinytest_set_test_failed_(); \ - TT_GRIPE(("%s",msg)); \ - fail; \ - } else { \ - TT_BLATHER(("%s",msg)); \ - } \ - TT_STMT_END - -/* Assert b, but do not stop the test if b fails. Log msg on failure. */ -#define tt_want_msg(b, msg) \ - tt_want_(b, msg, ); - -/* Assert b and stop the test if b fails. Log msg on failure. */ -#define tt_assert_msg(b, msg) \ - tt_want_(b, msg, TT_EXIT_TEST_FUNCTION); - -/* Assert b, but do not stop the test if b fails. */ -#define tt_want(b) tt_want_msg( (b), "want("#b")") -/* Assert b, and stop the test if b fails. */ -#define tt_assert(b) tt_assert_msg((b), "assert("#b")") - -#define tt_assert_test_fmt_type(a,b,str_test,type,test,printf_type,printf_fmt, \ - setup_block,cleanup_block,die_on_fail) \ - TT_STMT_BEGIN \ - type val1_ = (type)(a); \ - type val2_ = (type)(b); \ - int tt_status_ = (test); \ - if (!tt_status_ || tinytest_get_verbosity_()>1) { \ - printf_type print_; \ - printf_type print1_; \ - printf_type print2_; \ - type value_ = val1_; \ - setup_block; \ - print1_ = print_; \ - value_ = val2_; \ - setup_block; \ - print2_ = print_; \ - TT_DECLARE(tt_status_?" OK":"FAIL", \ - ("assert(%s): "printf_fmt" vs "printf_fmt, \ - str_test, print1_, print2_)); \ - print_ = print1_; \ - cleanup_block; \ - print_ = print2_; \ - cleanup_block; \ - if (!tt_status_) { \ - tinytest_set_test_failed_(); \ - die_on_fail ; \ - } \ - } \ - TT_STMT_END - -#define tt_assert_test_type(a,b,str_test,type,test,fmt,die_on_fail) \ - tt_assert_test_fmt_type(a,b,str_test,type,test,type,fmt, \ - {print_=value_;},{},die_on_fail) - -/* Helper: assert that a op b, when cast to type. Format the values with - * printf format fmt on failure. */ -#define tt_assert_op_type(a,op,b,type,fmt) \ - tt_assert_test_type(a,b,#a" "#op" "#b,type,(val1_ op val2_),fmt, \ - TT_EXIT_TEST_FUNCTION) - -#define tt_int_op(a,op,b) \ - tt_assert_test_type(a,b,#a" "#op" "#b,long,(val1_ op val2_), \ - "%ld",TT_EXIT_TEST_FUNCTION) - -#define tt_uint_op(a,op,b) \ - tt_assert_test_type(a,b,#a" "#op" "#b,unsigned long, \ - (val1_ op val2_),"%lu",TT_EXIT_TEST_FUNCTION) - -#define tt_ptr_op(a,op,b) \ - tt_assert_test_type(a,b,#a" "#op" "#b,void*, \ - (val1_ op val2_),"%p",TT_EXIT_TEST_FUNCTION) - -#define tt_str_op(a,op,b) \ - tt_assert_test_type(a,b,#a" "#op" "#b,const char *, \ - (strcmp(val1_,val2_) op 0),"<%s>",TT_EXIT_TEST_FUNCTION) - -#define tt_want_int_op(a,op,b) \ - tt_assert_test_type(a,b,#a" "#op" "#b,long,(val1_ op val2_),"%ld",(void)0) - -#define tt_want_uint_op(a,op,b) \ - tt_assert_test_type(a,b,#a" "#op" "#b,unsigned long, \ - (val1_ op val2_),"%lu",(void)0) - -#define tt_want_ptr_op(a,op,b) \ - tt_assert_test_type(a,b,#a" "#op" "#b,void*, \ - (val1_ op val2_),"%p",(void)0) - -#define tt_want_str_op(a,op,b) \ - tt_assert_test_type(a,b,#a" "#op" "#b,const char *, \ - (strcmp(val1_,val2_) op 0),"<%s>",(void)0) - -#endif diff --git a/lib/tinyusb b/lib/tinyusb index 8c1802e41d3..12611f81a2c 160000 --- a/lib/tinyusb +++ b/lib/tinyusb @@ -1 +1 @@ -Subproject commit 8c1802e41d37c915334a19b859b24cb2a1b48ee5 +Subproject commit 12611f81a2c7fe99ddf63ce050e8df22346ee009 diff --git a/locale/ID.po b/locale/ID.po index 20ed79ca405..ca862a97147 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: 2024-11-12 08:09+0000\n" -"Last-Translator: Iqbal Rifai \n" +"PO-Revision-Date: 2026-02-13 15:09+0000\n" +"Last-Translator: Arif Budiman \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 5.8.2\n" +"X-Generator: Weblate 5.16-dev\n" #: main.c msgid "" @@ -76,7 +76,7 @@ msgstr " tidak ketemu.\n" #: main.c msgid " output:\n" -msgstr "output:\n" +msgstr " output:\n" #: py/objstr.c #, c-format @@ -94,7 +94,7 @@ msgstr "" msgid "%q and %q contain duplicate pins" msgstr "%q dan %q berisi pin duplikat" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: shared-bindings/audioio/AudioOut.c msgid "%q and %q must be different" msgstr "%q dan %q harus berbeda" @@ -114,6 +114,10 @@ msgstr "%q berisi pin duplikat" msgid "%q failure: %d" msgstr "%q gagal: %d" +#: shared-module/audiodelays/MultiTapDelay.c +msgid "%q in %q must be of type %q or %q, not %q" +msgstr "%q dalam %q harus bertipe %q atau %q, bukan %q" + #: py/argcheck.c shared-module/audiofilters/Filter.c msgid "%q in %q must be of type %q, not %q" msgstr "%q dalam %q harus bertipe %q, bukan %q" @@ -166,7 +170,7 @@ msgstr "%q panjangnya harus <= %d" msgid "%q length must be >= %d" msgstr "%q panjangnya harus >= %d" -#: py/modsys.c py/objmodule.c py/runtime.c +#: py/modsys.c py/runtime.c msgid "%q moved from %q to %q" msgstr "%q dipindahkan dari %q ke %q" @@ -227,7 +231,7 @@ msgstr "%q harus kelipatan 8." #: shared-bindings/bitmapfilter/__init__.c shared-bindings/canio/CAN.c #: shared-bindings/digitalio/Pull.c shared-bindings/supervisor/__init__.c #: shared-module/audiofilters/Filter.c shared-module/displayio/__init__.c -#: shared-module/synthio/Biquad.c shared-module/synthio/Synthesizer.c +#: shared-module/synthio/Synthesizer.c msgid "%q must be of type %q or %q, not %q" msgstr "%q harus bertipe %q atau %q, bukan %q" @@ -236,9 +240,10 @@ msgid "%q must be of type %q, %q, or %q, not %q" msgstr "%q harus bertipe %q, %q, atau %q, bukan %q" #: py/argcheck.c py/runtime.c shared-bindings/bitmapfilter/__init__.c +#: shared-module/audiodelays/MultiTapDelay.c shared-module/synthio/Note.c #: shared-module/synthio/__init__.c msgid "%q must be of type %q, not %q" -msgstr "%q harus bertipe %q, %q, atau %q, bukan %q" +msgstr "%q harus dari tipe %q, bukan %q" #: ports/atmel-samd/common-hal/busio/UART.c msgid "%q must be power of 2" @@ -284,7 +289,7 @@ msgstr "%q, %q, dan %q semuanya harus memiliki panjang yang sama" #: py/objint.c shared-bindings/_bleio/Connection.c #: shared-bindings/storage/__init__.c msgid "%q=%q" -msgstr "" +msgstr "%q=%q" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "%q[%u] shifts in more bits than pin count" @@ -316,7 +321,7 @@ msgid "'%q' object does not support '%q'" msgstr "Objek '%q' tidak mendukung '%q'" #: py/runtime.c -msgid "'%q' object is not an iterator" +msgid "'%q' object isn't an iterator" msgstr "Objek '%q' bukan merupakan iterator" #: py/objtype.c py/runtime.c shared-module/atexit/__init__.c @@ -324,7 +329,7 @@ msgid "'%q' object is not callable" msgstr "Objek '%q' tidak dapat dipanggil" #: py/runtime.c -msgid "'%q' object is not iterable" +msgid "'%q' object isn't iterable" msgstr "Objek '%q' tidak dapat diulang" #: py/emitinlinethumb.c py/emitinlinextensa.c @@ -561,7 +566,7 @@ msgstr "Sudah disebarkan." #: ports/atmel-samd/common-hal/canio/Listener.c msgid "Already have all-matches listener" -msgstr "" +msgstr "Sudah memiliki listener semua-kecocokan" #: ports/espressif/common-hal/_bleio/__init__.c msgid "Already in progress" @@ -605,7 +610,7 @@ msgstr "Nilai array harus berupa byte tunggal." #: ports/atmel-samd/common-hal/spitarget/SPITarget.c msgid "Async SPI transfer in progress on this bus, keep awaiting." -msgstr "" +msgstr "Transfer SPI async sedang berlangsung pada bus ini, terus menunggu." #: shared-module/memorymonitor/AllocationAlarm.c #, c-format @@ -619,7 +624,7 @@ msgstr "Konversi audio belum diimplementasikan" #: ports/raspberrypi/common-hal/audiobusio/I2SOut.c #: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "Audio source error" -msgstr "" +msgstr "Kesalahan sumber audio" #: shared-bindings/wifi/Radio.c msgid "AuthMode.OPEN is not used with password" @@ -762,7 +767,7 @@ msgstr "" #: ports/espressif/common-hal/audioio/AudioOut.c msgid "Can't construct AudioOut because continuous channel already open" -msgstr "" +msgstr "Tidak dapat membuat AudioOut karena kanal berkelanjutan sudah terbuka" #: ports/espressif/common-hal/_bleio/Characteristic.c #: ports/nordic/common-hal/_bleio/Characteristic.c @@ -811,8 +816,8 @@ msgid "Cannot record to a file" msgstr "Tidak dapat merekam ke file" #: shared-module/storage/__init__.c -msgid "Cannot remount '/' when visible via USB." -msgstr "Tidak dapat memasang kembali '/' saat terlihat melalui USB." +msgid "Cannot remount path when visible via USB." +msgstr "Tidak dapat me-remount jalur ketika terlihat melalui USB." #: shared-bindings/digitalio/DigitalInOut.c msgid "Cannot set value when direction is input." @@ -829,7 +834,7 @@ msgstr "Tidak dapat membuat subkelas dari irisan" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "Cannot use GPIO0..15 together with GPIO32..47" -msgstr "" +msgstr "Tidak dapat menggunakan GPIO0..15 bersamaan dengan GPIO32..47" #: ports/nordic/common-hal/alarm/pin/PinAlarm.c msgid "Cannot wake on pin edge, only level" @@ -866,6 +871,10 @@ msgstr "Deretan koordinat memiliki panjang yang berbeda" msgid "Coordinate arrays types have different sizes" msgstr "Tipe array koordinat memiliki ukuran yang berbeda" +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "Could not publish to ROS topic" +msgstr "Tidak dapat mempublikasikan ke topik ROS" + #: shared-bindings/_bleio/Adapter.c msgid "Could not set address" msgstr "Tidak dapat mengatur alamat" @@ -878,6 +887,11 @@ msgstr "Tidak dapat memulai interupsi, RX sibuk" msgid "Couldn't allocate decoder" msgstr "Tidak dapat mengalokasikan dekoder" +#: ports/espressif/common-hal/rclcpy/__init__.c +#, c-format +msgid "Critical ROS failure during soft reboot, reset required: %d" +msgstr "Kegagalan ROS kritis selama soft reboot, reset diperlukan: %d" + #: ports/stm/common-hal/analogio/AnalogOut.c msgid "DAC Channel Init Error" msgstr "Terjadi kesalahan saat menginisialisasi kanal DAC" @@ -995,28 +1009,30 @@ msgstr "Gagal memperoleh mutex, err 0x%04x" #: ports/raspberrypi/common-hal/mdns/Server.c msgid "Failed to add service TXT record" -msgstr "" +msgstr "Gagal menambahkan record TXT layanan" #: shared-bindings/mdns/Server.c msgid "" "Failed to add service TXT record; non-string or bytes found in txt_records" msgstr "" +"Gagal menambahkan record TXT layanan; ditemukan non-string atau bytes dalam " +"txt_records" #: shared-module/rgbmatrix/RGBMatrix.c msgid "Failed to allocate %q buffer" -msgstr "" +msgstr "Gagal mengalokasikan buffer %q" #: ports/espressif/common-hal/wifi/__init__.c msgid "Failed to allocate Wifi memory" -msgstr "" +msgstr "Gagal mengalokasikan memori Wifi" #: ports/espressif/common-hal/wifi/ScannedNetworks.c msgid "Failed to allocate wifi scan memory" -msgstr "" +msgstr "Gagal mengalokasikan memori pemindaian wifi" #: ports/stm/common-hal/audiopwmio/PWMAudioOut.c msgid "Failed to buffer the sample" -msgstr "" +msgstr "Gagal membuffer sampel" #: ports/espressif/common-hal/_bleio/Adapter.c #: ports/nordic/common-hal/_bleio/Adapter.c @@ -1029,23 +1045,23 @@ msgstr "Gagal terhubung: habis waktu" #: ports/espressif/common-hal/audioio/AudioOut.c msgid "Failed to create continuous channels: invalid arg" -msgstr "" +msgstr "Gagal membuat kanal berkelanjutan: argumen tidak valid" #: ports/espressif/common-hal/audioio/AudioOut.c msgid "Failed to create continuous channels: invalid state" -msgstr "" +msgstr "Gagal membuat kanal berkelanjutan: status tidak valid" #: ports/espressif/common-hal/audioio/AudioOut.c msgid "Failed to create continuous channels: no mem" -msgstr "" +msgstr "Gagal membuat kanal berkelanjutan: tidak ada memori" #: ports/espressif/common-hal/audioio/AudioOut.c msgid "Failed to create continuous channels: not found" -msgstr "" +msgstr "Gagal membuat kanal berkelanjutan: tidak ditemukan" #: ports/espressif/common-hal/audioio/AudioOut.c msgid "Failed to enable continuous" -msgstr "" +msgstr "Gagal mengaktifkan berkelanjutan" #: shared-module/audiomp3/MP3Decoder.c msgid "Failed to parse MP3 file" @@ -1053,7 +1069,7 @@ msgstr "Gagal mengurai file MP3" #: ports/espressif/common-hal/audioio/AudioOut.c msgid "Failed to register continuous events callback" -msgstr "" +msgstr "Gagal mendaftarkan callback event berkelanjutan" #: ports/nordic/sd_mutex.c #, c-format @@ -1062,11 +1078,11 @@ msgstr "Gagal melepaskan mutex, err 0x%04x" #: ports/zephyr-cp/common-hal/wifi/Radio.c msgid "Failed to set hostname" -msgstr "" +msgstr "Gagal menetapkan hostname" #: ports/espressif/common-hal/audioio/AudioOut.c msgid "Failed to start async audio" -msgstr "" +msgstr "Gagal memulai audio async" #: supervisor/shared/safe_mode.c msgid "Failed to write internal flash." @@ -1076,45 +1092,47 @@ msgstr "Gagal menulis flash internal." msgid "File exists" msgstr "File sudah ada" +#: shared-bindings/supervisor/__init__.c shared-module/lvfontio/OnDiskFont.c #: shared-module/os/getenv.c msgid "File not found" -msgstr "" +msgstr "File tidak ditemukan" #: ports/atmel-samd/common-hal/canio/Listener.c #: ports/espressif/common-hal/canio/Listener.c #: ports/mimxrt10xx/common-hal/canio/Listener.c #: ports/stm/common-hal/canio/Listener.c msgid "Filters too complex" -msgstr "" +msgstr "Filter terlalu kompleks" #: ports/espressif/common-hal/dualbank/__init__.c msgid "Firmware is duplicate" -msgstr "" +msgstr "Firmware adalah duplikat" #: ports/espressif/common-hal/dualbank/__init__.c msgid "Firmware is invalid" -msgstr "" +msgstr "Firmware tidak valid" #: ports/espressif/common-hal/dualbank/__init__.c msgid "Firmware is too big" -msgstr "" +msgstr "Firmware terlalu besar" #: shared-bindings/bitmaptools/__init__.c msgid "For L8 colorspace, input bitmap must have 8 bits per pixel" -msgstr "" +msgstr "Untuk colorspace L8, bitmap input harus memiliki 8 bit per piksel" #: shared-bindings/bitmaptools/__init__.c msgid "For RGB colorspaces, input bitmap must have 16 bits per pixel" -msgstr "" +msgstr "Untuk colorspace RGB, bitmap input harus memiliki 16 bit per piksel" -#: ports/cxd56/common-hal/camera/Camera.c +#: ports/cxd56/common-hal/camera/Camera.c shared-module/audiocore/WaveFile.c msgid "Format not supported" -msgstr "" +msgstr "Format tidak didukung" #: ports/mimxrt10xx/common-hal/microcontroller/Processor.c msgid "" "Frequency must be 24, 150, 396, 450, 528, 600, 720, 816, 912, 960 or 1008 Mhz" msgstr "" +"Frekuensi harus 24, 150, 396, 450, 528, 600, 720, 816, 912, 960 atau 1008 Mhz" #: shared-bindings/bitbangio/I2C.c shared-bindings/bitbangio/SPI.c #: shared-bindings/busio/I2C.c shared-bindings/busio/SPI.c @@ -1123,11 +1141,11 @@ msgstr "Fungsinya membutuhkan kunci" #: ports/cxd56/common-hal/gnss/GNSS.c msgid "GNSS init" -msgstr "" +msgstr "Inisialisasi GNSS" #: ports/espressif/common-hal/espidf/__init__.c msgid "Generic Failure" -msgstr "" +msgstr "Kegagalan Umum" #: shared-bindings/framebufferio/FramebufferDisplay.c #: shared-module/busdisplay/BusDisplay.c @@ -1137,7 +1155,7 @@ msgstr "Grup sudah digunakan" #: supervisor/shared/safe_mode.c msgid "Hard fault: memory access or instruction error." -msgstr "" +msgstr "Hard fault: kesalahan akses memori atau instruksi." #: ports/mimxrt10xx/common-hal/busio/SPI.c #: ports/mimxrt10xx/common-hal/busio/UART.c ports/stm/common-hal/busio/I2C.c @@ -1148,7 +1166,7 @@ msgstr "Perangkat keras sedang digunakan, coba pin alternatif" #: supervisor/shared/safe_mode.c msgid "Heap allocation when VM not running." -msgstr "" +msgstr "Alokasi heap ketika VM tidak berjalan." #: extmod/vfs_posix_file.c py/objstringio.c msgid "I/O operation on closed file" @@ -1156,16 +1174,16 @@ msgstr "operasi I/O pada file tertutup" #: ports/stm/common-hal/busio/I2C.c msgid "I2C init error" -msgstr "" +msgstr "Kesalahan inisialisasi I2C" #: ports/raspberrypi/common-hal/busio/I2C.c #: ports/raspberrypi/common-hal/i2ctarget/I2CTarget.c msgid "I2C peripheral in use" -msgstr "" +msgstr "Periferal I2C sedang digunakan" #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "In-buffer elements must be <= 4 bytes long" -msgstr "" +msgstr "Elemen in-buffer harus <= 4 byte panjangnya" #: shared-bindings/_pew/PewPew.c msgid "Incorrect buffer size" @@ -1173,24 +1191,25 @@ msgstr "Ukuran penyangga salah" #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "Init program size invalid" -msgstr "" +msgstr "Ukuran program inisialisasi tidak valid" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "Initial set pin direction conflicts with initial out pin direction" -msgstr "" +msgstr "Arah pin set awal berkonflik dengan arah pin out awal" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "Initial set pin state conflicts with initial out pin state" -msgstr "" +msgstr "Status pin set awal berkonflik dengan status pin out awal" #: shared-bindings/bitops/__init__.c #, c-format msgid "Input buffer length (%d) must be a multiple of the strand count (%d)" msgstr "" +"Panjang buffer input (%d) harus merupakan kelipatan dari jumlah strand (%d)" #: ports/atmel-samd/common-hal/pulseio/PulseIn.c msgid "Input taking too long" -msgstr "" +msgstr "Input memakan waktu terlalu lama" #: py/moderrno.c msgid "Input/output error" @@ -1208,20 +1227,20 @@ msgstr "Enkripsi tidak cukup" #: shared-module/jpegio/JpegDecoder.c msgid "Insufficient memory pool for the image" -msgstr "" +msgstr "Pool memori tidak mencukupi untuk gambar" #: shared-module/jpegio/JpegDecoder.c msgid "Insufficient stream input buffer" -msgstr "" +msgstr "Buffer input stream tidak mencukupi" #: ports/espressif/common-hal/wifi/Radio.c #: ports/zephyr-cp/common-hal/wifi/Radio.c msgid "Interface must be started" -msgstr "" +msgstr "Interface harus dimulai" #: ports/atmel-samd/audio_dma.c ports/raspberrypi/audio_dma.c msgid "Internal audio buffer too small" -msgstr "" +msgstr "Buffer audio internal terlalu kecil" #: ports/stm/common-hal/busio/UART.c msgid "Internal define error" @@ -1229,7 +1248,7 @@ msgstr "Kesalahan definisi internal" #: shared-bindings/pwmio/PWMOut.c shared-module/os/getenv.c msgid "Internal error" -msgstr "" +msgstr "Kesalahan internal" #: shared-module/rgbmatrix/RGBMatrix.c #, c-format @@ -1247,19 +1266,19 @@ msgstr "Kesalahan internal #%d" #: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c #: shared-bindings/pwmio/PWMOut.c msgid "Internal resource(s) in use" -msgstr "" +msgstr "Sumber daya internal sedang digunakan" #: supervisor/shared/safe_mode.c msgid "Internal watchdog timer expired." -msgstr "" +msgstr "Timer watchdog internal kedaluwarsa." #: supervisor/shared/safe_mode.c msgid "Interrupt error." -msgstr "" +msgstr "Kesalahan interrupt." #: shared-module/jpegio/JpegDecoder.c msgid "Interrupted by output function" -msgstr "" +msgstr "Diinterupsi oleh fungsi output" #: ports/espressif/common-hal/_bleio/Service.c #: ports/espressif/common-hal/espulp/ULP.c @@ -1271,14 +1290,16 @@ msgstr "" #: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c py/argcheck.c #: shared-bindings/digitalio/DigitalInOut.c #: shared-bindings/epaperdisplay/EPaperDisplay.c shared-bindings/pwmio/PWMOut.c +#: shared-bindings/supervisor/__init__.c #: shared-module/aurora_epaper/aurora_framebuffer.c +#: shared-module/lvfontio/OnDiskFont.c msgid "Invalid %q" -msgstr "" +msgstr "%q tidak valid" #: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c #: shared-module/aurora_epaper/aurora_framebuffer.c msgid "Invalid %q and %q" -msgstr "" +msgstr "%q dan %q tidak valid" #: ports/atmel-samd/common-hal/microcontroller/Pin.c #: ports/espressif/common-hal/dotclockframebuffer/DotClockFramebuffer.c @@ -1294,15 +1315,19 @@ msgstr "Nilai Unit ADC tidak valid" #: ports/espressif/common-hal/_bleio/__init__.c #: ports/nordic/common-hal/_bleio/__init__.c msgid "Invalid BLE parameter" -msgstr "" +msgstr "Parameter BLE tidak valid" #: shared-bindings/wifi/Radio.c msgid "Invalid BSSID" -msgstr "" +msgstr "BSSID tidak valid" #: shared-bindings/wifi/Radio.c msgid "Invalid MAC address" -msgstr "" +msgstr "Alamat MAC tidak valid" + +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "Invalid ROS domain ID" +msgstr "ID domain ROS tidak valid" #: ports/espressif/common-hal/espidf/__init__.c py/moderrno.c msgid "Invalid argument" @@ -1315,16 +1340,16 @@ msgstr "Bit per nilai tidak valid" #: shared-module/os/getenv.c #, c-format msgid "Invalid byte %.*s" -msgstr "" +msgstr "Byte tidak valid %.*s" #: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c #, c-format msgid "Invalid data_pins[%d]" -msgstr "" +msgstr "data_pins[%d] tidak valid" #: shared-module/msgpack/__init__.c msgid "Invalid format" -msgstr "" +msgstr "Format tidak valid" #: shared-module/audiocore/WaveFile.c msgid "Invalid format chunk size" @@ -1332,29 +1357,29 @@ msgstr "Ukuran potongan format tidak valid" #: shared-bindings/wifi/Radio.c msgid "Invalid hex password" -msgstr "" +msgstr "Password hex tidak valid" #: ports/espressif/common-hal/wifi/Radio.c #: ports/zephyr-cp/common-hal/wifi/Radio.c msgid "Invalid multicast MAC address" -msgstr "" +msgstr "Alamat MAC multicast tidak valid" #: ports/espressif/common-hal/espidf/__init__.c msgid "Invalid size" -msgstr "" +msgstr "Ukuran tidak valid" #: shared-module/ssl/SSLSocket.c msgid "Invalid socket for TLS" -msgstr "" +msgstr "Socket tidak valid untuk TLS" #: ports/espressif/common-hal/espidf/__init__.c #: ports/nordic/common-hal/_bleio/__init__.c msgid "Invalid state" -msgstr "" +msgstr "Status tidak valid" #: shared-module/os/getenv.c msgid "Invalid unicode escape" -msgstr "" +msgstr "Escape unicode tidak valid" #: shared-bindings/aesio/aes.c msgid "Key must be 16, 24, or 32 bytes long" @@ -1362,11 +1387,11 @@ msgstr "Panjang kunci harus 16, 24, atau 32 byte" #: shared-module/os/getenv.c msgid "Key not found" -msgstr "" +msgstr "Kunci tidak ditemukan" #: shared-module/is31fl3741/FrameBuffer.c msgid "LED mappings must match display size" -msgstr "" +msgstr "Pemetaan LED harus sesuai dengan ukuran display" #: py/compile.c msgid "LHS of keyword arg must be an id" @@ -1374,69 +1399,75 @@ msgstr "LHS dari keyword arg harus menjadi sebuah id" #: shared-module/displayio/Group.c msgid "Layer already in a group" -msgstr "" +msgstr "Layer sudah ada dalam grup" #: shared-module/displayio/Group.c msgid "Layer must be a Group or TileGrid subclass" -msgstr "" +msgstr "Layer harus merupakan subclass Group atau TileGrid" #: shared-bindings/audiocore/RawSample.c msgid "Length of %q must be an even multiple of channel_count * type_size" msgstr "" +"Panjang %q harus merupakan kelipatan genap dari channel_count * type_size" #: ports/espressif/common-hal/espidf/__init__.c msgid "MAC address was invalid" -msgstr "" +msgstr "Alamat MAC tidak valid" #: ports/espressif/common-hal/_bleio/Characteristic.c #: ports/espressif/common-hal/_bleio/Descriptor.c msgid "MITM security not supported" -msgstr "" +msgstr "Keamanan MITM tidak didukung" + +#: ports/stm/common-hal/sdioio/SDCard.c +#, c-format +msgid "MMC/SDIO Clock Error %x" +msgstr "Kesalahan Clock MMC/SDIO %x" #: shared-bindings/is31fl3741/IS31FL3741.c msgid "Mapping must be a tuple" -msgstr "" +msgstr "Mapping harus berupa tuple" #: ports/raspberrypi/bindings/rp2pio/StateMachine.c #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "Mismatched data size" -msgstr "" +msgstr "Ukuran data tidak cocok" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "Mismatched swap flag" -msgstr "" +msgstr "Flag swap tidak cocok" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "Missing first_in_pin. %q[%u] reads pin(s)" -msgstr "" +msgstr "first_in_pin tidak ada. %q[%u] membaca pin" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "Missing first_in_pin. %q[%u] shifts in from pin(s)" -msgstr "" +msgstr "first_in_pin tidak ada. %q[%u] melakukan shift in dari pin" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "Missing first_in_pin. %q[%u] waits based on pin" -msgstr "" +msgstr "first_in_pin tidak ada. %q[%u] menunggu berdasarkan pin" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "Missing first_out_pin. %q[%u] shifts out to pin(s)" -msgstr "" +msgstr "first_out_pin tidak ada. %q[%u] melakukan shift out ke pin" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "Missing first_out_pin. %q[%u] writes pin(s)" -msgstr "" +msgstr "first_out_pin tidak ada. %q[%u] menulis pin" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "Missing first_set_pin. %q[%u] sets pin(s)" -msgstr "" +msgstr "first_set_pin tidak ada. %q[%u] menetapkan pin" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "Missing jmp_pin. %q[%u] jumps on pin" -msgstr "" +msgstr "jmp_pin tidak ada. %q[%u] melompat pada pin" #: shared-module/storage/__init__.c msgid "Mount point directory missing" -msgstr "" +msgstr "Direktori titik mount tidak ada" #: ports/zephyr-cp/bindings/zephyr_serial/UART.c shared-bindings/busio/UART.c #: shared-bindings/displayio/Group.c @@ -1445,7 +1476,7 @@ msgstr "Harus berupa subclass %q." #: ports/espressif/common-hal/dotclockframebuffer/DotClockFramebuffer.c msgid "Must provide 5/6/5 RGB pins" -msgstr "" +msgstr "Harus menyediakan pin RGB 5/6/5" #: ports/mimxrt10xx/common-hal/busio/SPI.c shared-bindings/busio/SPI.c msgid "Must provide MISO or MOSI pin" @@ -1458,23 +1489,23 @@ msgstr "Harus menggunakan kelipatan 6 pin rgb, bukan %d" #: supervisor/shared/safe_mode.c msgid "NLR jump failed. Likely memory corruption." -msgstr "" +msgstr "Lompatan NLR gagal. Kemungkinan korupsi memori." #: ports/espressif/common-hal/nvm/ByteArray.c msgid "NVS Error" -msgstr "" +msgstr "Kesalahan NVS" #: shared-bindings/socketpool/SocketPool.c msgid "Name or service not known" -msgstr "" +msgstr "Nama atau layanan tidak diketahui" #: shared-bindings/displayio/TileGrid.c msgid "New bitmap must be same size as old bitmap" -msgstr "" +msgstr "Bitmap baru harus berukuran sama dengan bitmap lama" #: ports/espressif/common-hal/_bleio/__init__.c msgid "Nimble out of memory" -msgstr "" +msgstr "Nimble kehabisan memori" #: ports/atmel-samd/common-hal/busio/UART.c #: ports/espressif/common-hal/busio/SPI.c @@ -1509,26 +1540,26 @@ msgstr "tidak ada channel DMA ditemukan" #: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "No DMA pacing timer found" -msgstr "" +msgstr "Tidak ditemukan timer pacing DMA" #: shared-module/adafruit_bus_device/i2c_device/I2CDevice.c #, c-format msgid "No I2C device at address: 0x%x" -msgstr "" +msgstr "Tidak ada perangkat I2C pada alamat: 0x%x" #: supervisor/shared/web_workflow/web_workflow.c msgid "No IP" -msgstr "" +msgstr "Tidak ada IP" #: ports/atmel-samd/common-hal/microcontroller/__init__.c #: ports/cxd56/common-hal/microcontroller/__init__.c #: ports/mimxrt10xx/common-hal/microcontroller/__init__.c msgid "No bootloader present" -msgstr "" +msgstr "Tidak ada bootloader" #: shared-module/usb/core/Device.c msgid "No configuration set" -msgstr "" +msgstr "Tidak ada konfigurasi yang ditetapkan" #: shared-bindings/_bleio/PacketBuffer.c msgid "No connection: length cannot be determined" @@ -1550,11 +1581,11 @@ msgstr "Tidak ada perangkat keras acak yang tersedia" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "No in in program" -msgstr "" +msgstr "Tidak ada in dalam program" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "No in or out in program" -msgstr "" +msgstr "Tidak ada in atau out dalam program" #: py/objint.c shared-bindings/time/__init__.c msgid "No long integer support" @@ -1562,30 +1593,34 @@ msgstr "Tidak ada dukungan bilangan bulat yang panjang" #: shared-bindings/wifi/Radio.c msgid "No network with that ssid" -msgstr "" +msgstr "Tidak ada jaringan dengan ssid tersebut" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "No out in program" -msgstr "" +msgstr "Tidak ada out dalam program" #: ports/atmel-samd/common-hal/busio/I2C.c #: ports/espressif/common-hal/busio/I2C.c #: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nordic/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 "" +msgstr "Tidak ditemukan pull up pada SDA atau SCL; periksa pengkabelan Anda" #: shared-module/touchio/TouchIn.c msgid "No pulldown on pin; 1Mohm recommended" msgstr "Tidak ada pull-down pada pin; 1Mohm direkomendasikan" +#: shared-module/touchio/TouchIn.c +msgid "No pullup on pin; 1Mohm recommended" +msgstr "Tidak ada pullup pada pin; 1Mohm direkomendasikan" + #: py/moderrno.c msgid "No space left on device" msgstr "Tidak ada ruang yang tersisa di perangkat" #: py/moderrno.c msgid "No such device" -msgstr "" +msgstr "Perangkat tidak ada" #: py/moderrno.c msgid "No such file/directory" @@ -1597,15 +1632,15 @@ msgstr "Penghitung waktu tidak tersedia" #: shared-module/usb/core/Device.c msgid "No usb host port initialized" -msgstr "" +msgstr "Tidak ada port host usb yang diinisialisasi" #: ports/nordic/common-hal/_bleio/__init__.c msgid "Nordic system firmware out of memory" -msgstr "" +msgstr "Firmware sistem Nordic kehabisan memori" #: shared-bindings/ipaddress/IPv4Address.c shared-bindings/ipaddress/__init__.c msgid "Not a valid IP string" -msgstr "" +msgstr "Bukan string IP yang valid" #: ports/espressif/common-hal/_bleio/__init__.c #: ports/nordic/common-hal/_bleio/__init__.c @@ -1626,7 +1661,7 @@ msgstr "" #: ports/espressif/common-hal/sdioio/SDCard.c #, c-format msgid "Number of data_pins must be %d or %d, not %d" -msgstr "" +msgstr "Jumlah data_pins harus %d atau %d, bukan %d" #: shared-bindings/util.c msgid "" @@ -1640,17 +1675,17 @@ msgstr "Parity ganjil tidak didukung" #: supervisor/shared/bluetooth/bluetooth.c msgid "Off" -msgstr "" +msgstr "Mati" #: supervisor/shared/bluetooth/bluetooth.c msgid "Ok" -msgstr "" +msgstr "Ok" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c #: ports/raspberrypi/common-hal/audiobusio/PDMIn.c #, c-format msgid "Only 8 or 16 bit mono with %dx oversampling supported." -msgstr "" +msgstr "Hanya mono 8 atau 16 bit dengan oversampling %dx yang didukung." #: ports/espressif/common-hal/wifi/__init__.c #: ports/raspberrypi/common-hal/wifi/__init__.c @@ -1671,51 +1706,51 @@ msgstr "" #: shared-bindings/_bleio/Adapter.c msgid "Only connectable advertisements can be directed" -msgstr "" +msgstr "Hanya advertisement yang dapat terhubung yang dapat diarahkan" #: ports/stm/common-hal/alarm/pin/PinAlarm.c msgid "Only edge detection is available on this hardware" -msgstr "" +msgstr "Hanya deteksi tepi yang tersedia pada perangkat keras ini" #: shared-bindings/ipaddress/__init__.c msgid "Only int or string supported for ip" -msgstr "" +msgstr "Hanya int atau string yang didukung untuk ip" #: ports/espressif/common-hal/alarm/touch/TouchAlarm.c msgid "Only one %q can be set in deep sleep." -msgstr "" +msgstr "Hanya satu %q yang dapat ditetapkan dalam deep sleep." #: ports/espressif/common-hal/espulp/ULPAlarm.c msgid "Only one %q can be set." -msgstr "" +msgstr "Hanya satu %q yang dapat ditetapkan." #: ports/espressif/common-hal/i2ctarget/I2CTarget.c #: ports/raspberrypi/common-hal/i2ctarget/I2CTarget.c msgid "Only one address is allowed" -msgstr "" +msgstr "Hanya satu alamat yang diperbolehkan" #: ports/atmel-samd/common-hal/alarm/time/TimeAlarm.c #: ports/nordic/common-hal/alarm/time/TimeAlarm.c #: ports/stm/common-hal/alarm/time/TimeAlarm.c msgid "Only one alarm.time alarm can be set" -msgstr "" +msgstr "Hanya satu alarm alarm.time yang dapat ditetapkan" #: ports/espressif/common-hal/alarm/time/TimeAlarm.c #: ports/raspberrypi/common-hal/alarm/time/TimeAlarm.c msgid "Only one alarm.time alarm can be set." -msgstr "" +msgstr "Hanya satu alarm alarm.time yang dapat ditetapkan." #: shared-module/displayio/ColorConverter.c msgid "Only one color can be transparent at a time" -msgstr "" +msgstr "Hanya satu warna yang dapat transparan pada satu waktu" #: py/moderrno.c msgid "Operation not permitted" -msgstr "" +msgstr "Operasi tidak diizinkan" #: ports/espressif/common-hal/espidf/__init__.c msgid "Operation or feature not supported" -msgstr "" +msgstr "Operasi atau fitur tidak didukung" #: ports/espressif/common-hal/espidf/__init__.c msgid "Operation timed out" @@ -1723,7 +1758,7 @@ msgstr "Waktu habis" #: ports/raspberrypi/common-hal/mdns/Server.c msgid "Out of MDNS service slots" -msgstr "" +msgstr "Kehabisan slot layanan MDNS" #: ports/espressif/common-hal/espidf/__init__.c msgid "Out of memory" @@ -1737,27 +1772,27 @@ msgstr "Kehabisan socket" #: ports/raspberrypi/bindings/rp2pio/StateMachine.c msgid "Out-buffer elements must be <= 4 bytes long" -msgstr "" +msgstr "Elemen out-buffer harus <= 4 byte panjangnya" #: ports/stm/common-hal/pwmio/PWMOut.c msgid "PWM restart" -msgstr "" +msgstr "Restart PWM" #: ports/raspberrypi/common-hal/countio/Counter.c msgid "PWM slice already in use" -msgstr "" +msgstr "Slice PWM sudah digunakan" #: ports/raspberrypi/common-hal/countio/Counter.c msgid "PWM slice channel A already in use" -msgstr "" +msgstr "Channel A slice PWM sudah digunakan" #: shared-bindings/spitarget/SPITarget.c msgid "Packet buffers for an SPI transfer must have the same length." -msgstr "" +msgstr "Buffer paket untuk transfer SPI harus memiliki panjang yang sama." #: shared-module/jpegio/JpegDecoder.c msgid "Parameter error" -msgstr "" +msgstr "Kesalahan parameter" #: ports/espressif/common-hal/audiobusio/__init__.c msgid "Peripheral in use" @@ -1769,7 +1804,7 @@ msgstr "Izin ditolak" #: ports/stm/common-hal/alarm/pin/PinAlarm.c msgid "Pin cannot wake from Deep Sleep" -msgstr "" +msgstr "Pin tidak dapat membangunkan dari Deep Sleep" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "Pin count too large" @@ -1813,7 +1848,7 @@ msgstr "Pin harus berbagi potongan PWM" #: shared-module/usb/core/Device.c msgid "Pipe error" -msgstr "" +msgstr "Kesalahan pipe" #: py/builtinhelp.c msgid "Plus any modules on the filesystem\n" @@ -1839,7 +1874,7 @@ msgstr "" #: main.c msgid "Pretending to deep sleep until alarm, CTRL-C or file write.\n" -msgstr "" +msgstr "Berpura-pura deep sleep sampai alarm, CTRL-C atau penulisan file.\n" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "Program does IN without loading ISR" @@ -1857,6 +1892,10 @@ msgstr "Ukuran program tidak valid" msgid "Program too long" msgstr "Program terlalu lama" +#: shared-bindings/rclcpy/Publisher.c +msgid "Publishers can only be created from a parent node" +msgstr "Publisher hanya dapat dibuat dari node induk" + #: shared-bindings/digitalio/DigitalInOut.c msgid "Pull not used when direction is output." msgstr "Pull tidak digunakan saat arah output." @@ -1877,10 +1916,30 @@ msgstr "Kesalahan DeInit RNG" msgid "RNG Init Error" msgstr "Kesalahan Init RNG" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS failed to initialize. Is agent connected?" +msgstr "ROS gagal diinisialisasi. Apakah agen terhubung?" + +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS internal setup failure" +msgstr "Kegagalan pengaturan internal ROS" + +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS memory allocator failure" +msgstr "Kegagalan alokator memori ROS" + +#: ports/espressif/common-hal/rclcpy/Node.c +msgid "ROS node failed to initialize" +msgstr "Node ROS gagal diinisialisasi" + +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "ROS topic failed to initialize" +msgstr "Topik ROS gagal diinisialisasi" + #: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c #: ports/nordic/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c msgid "RS485" -msgstr "" +msgstr "RS485" #: ports/espressif/common-hal/busio/UART.c #: ports/mimxrt10xx/common-hal/busio/UART.c @@ -1942,7 +2001,6 @@ msgstr "Format benar tapi tidak didukung" msgid "Running in safe mode! Not running saved code.\n" msgstr "" "Berjalan di mode aman(safe mode)! Tidak menjalankan kode yang disimpan.\n" -"Berjalan di mode aman(safe mode)! tidak menjalankan kode yang tersimpan.\n" #: shared-module/sdcardio/SDCard.c msgid "SD card CSD format not supported" @@ -1950,18 +2008,18 @@ msgstr "Kartu SD Format CSD tidak didukung" #: ports/cxd56/common-hal/sdioio/SDCard.c msgid "SDCard init" -msgstr "" +msgstr "Inisialisasi SDCard" #: ports/stm/common-hal/sdioio/SDCard.c #, c-format msgid "SDIO GetCardInfo Error %d" -msgstr "" +msgstr "Kesalahan GetCardInfo SDIO %d" #: ports/espressif/common-hal/sdioio/SDCard.c #: ports/stm/common-hal/sdioio/SDCard.c #, c-format msgid "SDIO Init Error %x" -msgstr "" +msgstr "Kesalahan Init SDIO %x" #: ports/espressif/common-hal/busio/SPI.c msgid "SPI configuration failed" @@ -1969,7 +2027,7 @@ msgstr "Konfigurasi SPI gagal" #: ports/stm/common-hal/busio/SPI.c msgid "SPI init error" -msgstr "" +msgstr "Kesalahan inisialisasi SPI" #: ports/raspberrypi/common-hal/busio/SPI.c msgid "SPI peripheral in use" @@ -1977,7 +2035,7 @@ msgstr "Periferal SPI sedang digunakan" #: ports/stm/common-hal/busio/SPI.c msgid "SPI re-init" -msgstr "" +msgstr "Inisialisasi ulang SPI" #: shared-bindings/is31fl3741/FrameBuffer.c msgid "Scale dimensions must divide by 3" @@ -2010,6 +2068,7 @@ msgstr "Potongan dan nilai panjangnya berbeda." #: shared-bindings/displayio/TileGrid.c #: shared-bindings/memorymonitor/AllocationSize.c #: shared-bindings/pulseio/PulseIn.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c msgid "Slices not supported" msgstr "Potongan tidak didukung" @@ -2080,7 +2139,9 @@ msgstr "" msgid "Tile height must exactly divide bitmap height" msgstr "Tinggi tile harus persis membagi tinggi bitmap" -#: shared-bindings/displayio/TileGrid.c shared-module/displayio/TileGrid.c +#: shared-bindings/displayio/TileGrid.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-module/displayio/TileGrid.c msgid "Tile index out of bounds" msgstr "Indeks ubin di luar batas" @@ -2088,6 +2149,10 @@ msgstr "Indeks ubin di luar batas" msgid "Tile width must exactly divide bitmap width" msgstr "Lebar ubin harus persis membagi lebar bitmap" +#: shared-module/tilepalettemapper/TilePaletteMapper.c +msgid "TilePaletteMapper may only be bound to a TileGrid once" +msgstr "TilePaletteMapper hanya dapat diikat ke TileGrid sekali" + #: shared-bindings/alarm/time/TimeAlarm.c msgid "Time is in the past." msgstr "Waktu sudah berlalu." @@ -2105,7 +2170,7 @@ msgstr "Sampel memiliki terlalu banyak saluran" #: ports/raspberrypi/common-hal/audiobusio/I2SOut.c msgid "Too many channels in sample." -msgstr "Terlalu banyak channel dalam sampel" +msgstr "Terlalu banyak channel dalam sampel." #: ports/espressif/common-hal/_bleio/Characteristic.c msgid "Too many descriptors" @@ -2137,12 +2202,12 @@ msgstr "Traceback (bagian terakhir dari panggilan terkini):\n" #: ports/stm/common-hal/busio/UART.c msgid "UART de-init" -msgstr "" +msgstr "De-inisialisasi UART" #: ports/cxd56/common-hal/busio/UART.c ports/espressif/common-hal/busio/UART.c #: ports/stm/common-hal/busio/UART.c msgid "UART init" -msgstr "" +msgstr "Inisialisasi UART" #: ports/raspberrypi/common-hal/busio/UART.c msgid "UART peripheral in use" @@ -2150,19 +2215,19 @@ msgstr "Periferal UART sedang digunakan" #: ports/stm/common-hal/busio/UART.c msgid "UART re-init" -msgstr "" +msgstr "Inisialisasi ulang UART" #: ports/stm/common-hal/busio/UART.c msgid "UART write" -msgstr "" +msgstr "Penulisan UART" #: main.c msgid "UID:" -msgstr "" +msgstr "UID:" #: shared-module/usb_hid/Device.c msgid "USB busy" -msgstr "" +msgstr "USB sibuk" #: supervisor/shared/safe_mode.c msgid "USB devices need more endpoints than are available." @@ -2174,7 +2239,7 @@ msgstr "Perangkat USB menggunakan terlalu banyak nama antarmuka." #: shared-module/usb_hid/Device.c msgid "USB error" -msgstr "" +msgstr "Kesalahan USB" #: shared-bindings/_bleio/UUID.c msgid "UUID integer value must be 0-0xffff" @@ -2223,7 +2288,7 @@ msgstr "Tidak dapat membaca data palet warna" #: ports/mimxrt10xx/common-hal/canio/CAN.c msgid "Unable to send CAN Message: all Tx message buffers are busy" -msgstr "" +msgstr "Tidak dapat mengirim Pesan CAN: semua buffer pesan Tx sibuk" #: ports/espressif/common-hal/mdns/Server.c #: ports/raspberrypi/common-hal/mdns/Server.c @@ -2301,7 +2366,7 @@ msgstr "Kesalahan firmware sistem tidak diketahui: %d" #: shared-module/_pixelmap/PixelMap.c #, c-format msgid "Unmatched number of items on RHS (expected %d, got %d)." -msgstr "Jumlah item pada RHS tidak cocok (diharapkan %d, didapatkan %d)." +msgstr "Jumlah item pada RHS tidak cocok (diharapkan %d, didapatkan %d)." #: ports/nordic/common-hal/_bleio/__init__.c msgid "" @@ -2313,16 +2378,12 @@ msgstr "" #: shared-bindings/bitmaptools/__init__.c msgid "Unsupported colorspace" -msgstr "" +msgstr "Colorspace tidak didukung" #: shared-module/displayio/bus_core.c msgid "Unsupported display bus type" msgstr "Tipe bus tampilan tidak didukung" -#: shared-module/audiocore/WaveFile.c -msgid "Unsupported format" -msgstr "Format tidak didukung" - #: shared-bindings/hashlib/__init__.c msgid "Unsupported hash algorithm" msgstr "Algoritma hash tidak didukung" @@ -2383,15 +2444,17 @@ msgstr "" #: supervisor/shared/web_workflow/web_workflow.c msgid "Wi-Fi: " -msgstr "" +msgstr "Wi-Fi: " +#: ports/espressif/common-hal/wifi/Radio.c #: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "Wifi is not enabled" -msgstr "Wifi tidak diaktifkan" +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "WiFi is not enabled" +msgstr "WiFi tidak diaktifkan" #: main.c msgid "Woken up by alarm.\n" -msgstr "" +msgstr "Dibangunkan oleh alarm.\n" #: ports/espressif/common-hal/_bleio/PacketBuffer.c #: ports/nordic/common-hal/_bleio/PacketBuffer.c @@ -2425,7 +2488,7 @@ msgstr "Anda menekan tombol BOOT saat memulai" #: ports/espressif/boards/adafruit_itsybitsy_esp32/mpconfigboard.h #: ports/espressif/boards/waveshare_esp32_c6_lcd_1_47/mpconfigboard.h msgid "You pressed the BOOT button at start up." -msgstr "Anda menekan tombol BOOT saat memulai" +msgstr "Anda menekan tombol BOOT saat memulai." #: ports/espressif/boards/adafruit_huzzah32_breakout/mpconfigboard.h msgid "You pressed the GPIO0 button at start up." @@ -2470,7 +2533,7 @@ msgstr "__init __() harus mengembalikan None" #: py/objtype.c #, c-format msgid "__init__() should return None, not '%s'" -msgstr "" +msgstr "__init__() harus mengembalikan None, bukan '%s'" #: py/objobject.c msgid "__new__ arg must be a user-type" @@ -2486,7 +2549,7 @@ msgstr "alamatnya kosong" #: ports/espressif/common-hal/audioio/AudioOut.c msgid "already playing" -msgstr "" +msgstr "sudah diputar" #: py/compile.c msgid "annotation must be an identifier" @@ -2510,15 +2573,15 @@ msgstr "Argumen argsort harus berupa ndarray" #: extmod/ulab/code/numpy/numerical.c msgid "argsort is not implemented for flattened arrays" -msgstr "" +msgstr "argsort tidak diimplementasikan untuk array yang diratakan" #: extmod/ulab/code/numpy/random/random.c msgid "argument must be None, an integer or a tuple of integers" -msgstr "" +msgstr "argumen harus None, integer atau tuple integer" #: py/compile.c msgid "argument name reused" -msgstr "" +msgstr "nama argumen digunakan kembali" #: py/argcheck.c shared-bindings/_stage/__init__.c #: shared-bindings/digitalio/DigitalInOut.c @@ -2531,15 +2594,15 @@ msgstr "argumen harus berupa ndarrays" #: extmod/ulab/code/ndarray.c msgid "array and index length must be equal" -msgstr "" +msgstr "panjang array dan indeks harus sama" #: extmod/ulab/code/numpy/io/io.c msgid "array has too many dimensions" -msgstr "" +msgstr "array memiliki terlalu banyak dimensi" #: extmod/ulab/code/ndarray.c msgid "array is too big" -msgstr "" +msgstr "array terlalu besar" #: py/objarray.c shared-bindings/alarm/SleepMemory.c #: shared-bindings/memorymap/AddressRange.c shared-bindings/nvm/ByteArray.c @@ -2548,15 +2611,15 @@ msgstr "diperlukan array/byte di sisi kanan" #: py/asmxtensa.c msgid "asm overflow" -msgstr "" +msgstr "asm overflow" #: py/compile.c msgid "async for/with outside async function" -msgstr "" +msgstr "async for/with di luar fungsi async" #: extmod/ulab/code/numpy/numerical.c msgid "attempt to get (arg)min/(arg)max of empty sequence" -msgstr "" +msgstr "percobaan untuk mendapatkan (arg)min/(arg)max dari urutan kosong" #: extmod/ulab/code/numpy/numerical.c msgid "attempt to get argmin/argmax of an empty sequence" @@ -2564,27 +2627,27 @@ msgstr "berusaha mendapatkan argmin/argmax dari urutan kosong" #: py/objstr.c msgid "attributes not supported" -msgstr "" +msgstr "atribut tidak didukung" #: ports/espressif/common-hal/audioio/AudioOut.c msgid "audio format not supported" -msgstr "" +msgstr "format audio tidak didukung" #: extmod/ulab/code/ulab_tools.c msgid "axis is out of bounds" -msgstr "" +msgstr "axis berada di luar batas" #: extmod/ulab/code/numpy/numerical.c extmod/ulab/code/ulab_tools.c msgid "axis must be None, or an integer" -msgstr "" +msgstr "axis harus None, atau integer" #: extmod/ulab/code/numpy/numerical.c msgid "axis too long" -msgstr "" +msgstr "axis terlalu panjang" #: shared-bindings/bitmaptools/__init__.c msgid "background value out of range of target" -msgstr "" +msgstr "nilai latar belakang di luar jangkauan target" #: py/builtinevex.c msgid "bad compile mode" @@ -2596,7 +2659,7 @@ msgstr "specifier salah konversi" #: py/objstr.c msgid "bad format string" -msgstr "" +msgstr "string format salah" #: py/binary.c py/objarray.c msgid "bad typecode" @@ -2604,41 +2667,48 @@ msgstr "typecode buruk" #: py/emitnative.c msgid "binary op %q not implemented" -msgstr "" +msgstr "operasi biner %q tidak diimplementasikan" #: ports/espressif/common-hal/audiobusio/PDMIn.c msgid "bit_depth must be 8, 16, 24, or 32." -msgstr "" +msgstr "bit_depth harus 8, 16, 24, atau 32." #: shared-module/bitmapfilter/__init__.c msgid "bitmap size and depth must match" -msgstr "" +msgstr "ukuran dan kedalaman bitmap harus cocok" #: shared-bindings/bitmaptools/__init__.c msgid "bitmap sizes must match" -msgstr "" +msgstr "ukuran bitmap harus cocok" #: extmod/modrandom.c msgid "bits must be 32 or less" -msgstr "" +msgstr "bit harus 32 atau kurang" + +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "bits_per_sample must be 16" +msgstr "bits_per_sample harus 16" -#: shared-bindings/audiodelays/Echo.c shared-bindings/audiodelays/PitchShift.c +#: shared-bindings/audiodelays/Chorus.c shared-bindings/audiodelays/Echo.c +#: shared-bindings/audiodelays/MultiTapDelay.c +#: shared-bindings/audiodelays/PitchShift.c #: shared-bindings/audiofilters/Distortion.c -#: shared-bindings/audiofilters/Filter.c shared-bindings/audiomixer/Mixer.c +#: shared-bindings/audiofilters/Filter.c shared-bindings/audiofilters/Phaser.c +#: shared-bindings/audiomixer/Mixer.c msgid "bits_per_sample must be 8 or 16" -msgstr "" +msgstr "bits_per_sample harus 8 atau 16" #: py/emitinlinethumb.c msgid "branch not in range" -msgstr "" +msgstr "branch tidak dalam jangkauan" #: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c msgid "buffer is smaller than requested size" -msgstr "" +msgstr "buffer lebih kecil dari ukuran yang diminta" #: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c msgid "buffer size must be a multiple of element size" -msgstr "" +msgstr "ukuran buffer harus kelipatan dari ukuran elemen" #: shared-module/struct/__init__.c msgid "buffer size must match format" @@ -2646,27 +2716,27 @@ 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" -msgstr "" +msgstr "potongan buffer harus memiliki panjang yang sama" #: py/modstruct.c shared-module/struct/__init__.c msgid "buffer too small" -msgstr "" +msgstr "buffer terlalu kecil" #: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c msgid "buffer too small for requested bytes" -msgstr "" +msgstr "buffer terlalu kecil untuk byte yang diminta" #: py/emitbc.c msgid "bytecode overflow" -msgstr "" +msgstr "bytecode overflow" #: py/objarray.c msgid "bytes length not a multiple of item size" -msgstr "" +msgstr "panjang bytes bukan kelipatan dari ukuran item" #: py/objstr.c msgid "bytes value out of range" -msgstr "" +msgstr "nilai bytes di luar jangkauan" #: ports/atmel-samd/bindings/samd/Clock.c msgid "calibration is out of range" @@ -2679,7 +2749,7 @@ msgstr "kalibrasi adalah read only" #: shared-module/vectorio/Circle.c shared-module/vectorio/Polygon.c #: shared-module/vectorio/Rectangle.c msgid "can only have one parent" -msgstr "" +msgstr "hanya dapat memiliki satu induk" #: py/emitinlinethumb.c msgid "can only have up to 4 parameters to Thumb assembly" @@ -2687,15 +2757,15 @@ msgstr "hanya mampu memiliki hingga 4 parameter untuk Thumb assembly" #: py/emitinlinextensa.c msgid "can only have up to 4 parameters to Xtensa assembly" -msgstr "" +msgstr "hanya dapat memiliki hingga 4 parameter untuk assembly Xtensa" #: extmod/ulab/code/ndarray.c msgid "can only specify one unknown dimension" -msgstr "" +msgstr "hanya dapat menentukan satu dimensi yang tidak diketahui" #: py/objtype.c msgid "can't add special method to already-subclassed class" -msgstr "" +msgstr "tidak dapat menambahkan metode khusus ke kelas yang sudah di-subclass" #: py/compile.c msgid "can't assign to expression" @@ -2703,50 +2773,50 @@ msgstr "tidak dapat menetapkan ke ekspresi" #: extmod/modasyncio.c msgid "can't cancel self" -msgstr "" +msgstr "tidak dapat membatalkan diri sendiri" #: py/obj.c shared-module/adafruit_pixelbuf/PixelBuf.c msgid "can't convert %q to %q" -msgstr "" +msgstr "tidak dapat mengonversi %q ke %q" #: py/obj.c #, c-format msgid "can't convert %s to complex" -msgstr "" +msgstr "tidak dapat mengonversi %s ke complex" #: py/obj.c #, c-format msgid "can't convert %s to float" -msgstr "" +msgstr "tidak dapat mengonversi %s ke float" #: py/objint.c py/runtime.c #, c-format msgid "can't convert %s to int" -msgstr "" +msgstr "tidak dapat mengonversi %s ke int" #: py/objstr.c msgid "can't convert '%q' object to %q implicitly" -msgstr "" +msgstr "tidak dapat mengonversi objek '%q' ke %q secara implisit" #: extmod/ulab/code/numpy/vector.c msgid "can't convert complex to float" -msgstr "" +msgstr "tidak dapat mengonversi complex ke float" #: py/obj.c msgid "can't convert to complex" -msgstr "" +msgstr "tidak dapat mengonversi ke complex" #: py/obj.c msgid "can't convert to float" -msgstr "" +msgstr "tidak dapat mengonversi ke float" #: py/runtime.c msgid "can't convert to int" -msgstr "" +msgstr "tidak dapat mengonversi ke int" #: py/objstr.c msgid "can't convert to str implicitly" -msgstr "" +msgstr "tidak dapat mengonversi ke str secara implisit" #: py/compile.c msgid "can't declare nonlocal in outer code" @@ -2758,93 +2828,95 @@ msgstr "tidak bisa menghapus ekspresi" #: py/emitnative.c msgid "can't do binary op between '%q' and '%q'" -msgstr "" +msgstr "tidak dapat melakukan operasi biner antara '%q' dan '%q'" #: py/emitnative.c msgid "can't do unary op of '%q'" -msgstr "" +msgstr "tidak dapat melakukan operasi unary dari '%q'" #: py/emitnative.c msgid "can't implicitly convert '%q' to 'bool'" -msgstr "" +msgstr "tidak dapat mengonversi '%q' ke 'bool' secara implisit" #: py/runtime.c msgid "can't import name %q" -msgstr "" +msgstr "tidak dapat mengimpor nama %q" #: py/emitnative.c msgid "can't load from '%q'" -msgstr "" +msgstr "tidak dapat memuat dari '%q'" #: py/emitnative.c msgid "can't load with '%q' index" -msgstr "" +msgstr "tidak dapat memuat dengan indeks '%q'" #: py/builtinimport.c msgid "can't perform relative import" -msgstr "" +msgstr "tidak dapat melakukan impor relatif" #: py/objgenerator.c msgid "can't send non-None value to a just-started generator" -msgstr "" +msgstr "tidak dapat mengirim nilai non-None ke generator yang baru dimulai" #: shared-module/sdcardio/SDCard.c msgid "can't set 512 block size" -msgstr "" +msgstr "tidak dapat mengatur ukuran blok 512" #: py/objexcept.c py/objnamedtuple.c msgid "can't set attribute" -msgstr "" +msgstr "tidak dapat mengatur atribut" #: py/runtime.c msgid "can't set attribute '%q'" -msgstr "" +msgstr "tidak dapat mengatur atribut '%q'" #: py/emitnative.c msgid "can't store '%q'" -msgstr "" +msgstr "tidak dapat menyimpan '%q'" #: py/emitnative.c msgid "can't store to '%q'" -msgstr "" +msgstr "tidak dapat menyimpan ke '%q'" #: py/emitnative.c msgid "can't store with '%q' index" -msgstr "" +msgstr "tidak dapat menyimpan dengan indeks '%q'" #: py/objstr.c msgid "" "can't switch from automatic field numbering to manual field specification" msgstr "" +"tidak dapat beralih dari penomoran field otomatis ke spesifikasi field manual" #: py/objstr.c msgid "" "can't switch from manual field specification to automatic field numbering" msgstr "" +"tidak dapat beralih dari spesifikasi field manual ke penomoran field otomatis" #: py/objcomplex.c msgid "can't truncate-divide a complex number" -msgstr "" +msgstr "tidak dapat truncate-divide bilangan complex" #: extmod/modasyncio.c msgid "can't wait" -msgstr "" +msgstr "tidak dapat menunggu" #: extmod/ulab/code/ndarray.c msgid "cannot assign new shape" -msgstr "" +msgstr "tidak dapat menetapkan bentuk baru" #: extmod/ulab/code/ndarray_operators.c msgid "cannot cast output with casting rule" -msgstr "" +msgstr "tidak dapat melakukan cast output dengan aturan casting" #: extmod/ulab/code/ndarray.c msgid "cannot convert complex to dtype" -msgstr "" +msgstr "tidak dapat mengonversi complex ke dtype" #: extmod/ulab/code/ndarray.c msgid "cannot convert complex type" -msgstr "" +msgstr "tidak dapat mengonversi tipe complex" #: py/objtype.c msgid "cannot create '%q' instances" @@ -2852,71 +2924,71 @@ msgstr "" #: py/objtype.c msgid "cannot create instance" -msgstr "" +msgstr "tidak dapat membuat instance" #: extmod/ulab/code/ndarray.c msgid "cannot delete array elements" -msgstr "" +msgstr "tidak dapat menghapus elemen array" #: extmod/ulab/code/ndarray.c msgid "cannot reshape array" -msgstr "" +msgstr "tidak dapat membentuk ulang array" #: py/emitnative.c msgid "casting" -msgstr "" +msgstr "casting" #: ports/stm/common-hal/pwmio/PWMOut.c msgid "channel re-init" -msgstr "" +msgstr "inisialisasi ulang channel" #: shared-bindings/_stage/Text.c msgid "chars buffer too small" -msgstr "" +msgstr "buffer chars terlalu kecil" #: py/modbuiltins.c msgid "chr() arg not in range(0x110000)" -msgstr "" +msgstr "argumen chr() tidak dalam rentang(0x110000)" #: py/modbuiltins.c msgid "chr() arg not in range(256)" -msgstr "" +msgstr "argumen chr() tidak dalam rentang(256)" #: shared-bindings/bitmaptools/__init__.c msgid "clip point must be (x,y) tuple" -msgstr "" +msgstr "clip point harus berupa tuple (x,y)" #: shared-bindings/msgpack/ExtType.c msgid "code outside range 0~127" -msgstr "" +msgstr "kode di luar rentang 0~127" #: shared-bindings/displayio/Palette.c msgid "color buffer must be 3 bytes (RGB) or 4 bytes (RGB + pad byte)" -msgstr "" +msgstr "buffer warna harus 3 byte (RGB) atau 4 byte (RGB + pad byte)" #: shared-bindings/displayio/Palette.c msgid "color buffer must be a buffer, tuple, list, or int" -msgstr "" +msgstr "buffer warna harus berupa buffer, tuple, list, atau int" #: shared-bindings/displayio/Palette.c msgid "color buffer must be a bytearray or array of type 'b' or 'B'" -msgstr "" +msgstr "buffer warna harus berupa bytearray atau array bertipe 'b' atau 'B'" #: shared-bindings/displayio/Palette.c msgid "color must be between 0x000000 and 0xffffff" -msgstr "" +msgstr "warna harus antara 0x000000 dan 0xffffff" #: py/emitnative.c msgid "comparison of int and uint" -msgstr "" +msgstr "perbandingan int dan uint" #: py/objcomplex.c msgid "complex divide by zero" -msgstr "" +msgstr "pembagian complex dengan nol" #: py/objfloat.c py/parsenum.c msgid "complex values not supported" -msgstr "" +msgstr "nilai complex tidak didukung" #: extmod/modzlib.c msgid "compression header" @@ -2924,56 +2996,56 @@ msgstr "kompresi header" #: py/emitnative.c msgid "conversion to object" -msgstr "" +msgstr "konversi ke objek" #: extmod/ulab/code/numpy/filter.c msgid "convolve arguments must be linear arrays" -msgstr "" +msgstr "argumen convolve harus berupa array linear" #: extmod/ulab/code/numpy/filter.c msgid "convolve arguments must be ndarrays" -msgstr "" +msgstr "argumen convolve harus berupa ndarray" #: extmod/ulab/code/numpy/filter.c msgid "convolve arguments must not be empty" -msgstr "" +msgstr "argumen convolve tidak boleh kosong" #: extmod/ulab/code/numpy/io/io.c msgid "corrupted file" -msgstr "" +msgstr "file rusak" #: extmod/ulab/code/numpy/poly.c msgid "could not invert Vandermonde matrix" -msgstr "" +msgstr "tidak dapat membalik matriks Vandermonde" #: shared-module/sdcardio/SDCard.c msgid "couldn't determine SD card version" -msgstr "" +msgstr "tidak dapat menentukan versi kartu SD" #: extmod/ulab/code/numpy/numerical.c msgid "cross is defined for 1D arrays of length 3" -msgstr "" +msgstr "cross didefinisikan untuk array 1D dengan panjang 3" #: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be iterable" -msgstr "" +msgstr "data harus dapat diiterasi" #: extmod/ulab/code/scipy/optimize/optimize.c msgid "data must be of equal length" -msgstr "" +msgstr "data harus memiliki panjang yang sama" #: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c #, c-format msgid "data pin #%d in use" -msgstr "" +msgstr "pin data #%d sedang digunakan" #: extmod/ulab/code/ndarray.c msgid "data type not understood" -msgstr "" +msgstr "tipe data tidak dipahami" #: py/parsenum.c msgid "decimal numbers not supported" -msgstr "" +msgstr "angka desimal tidak didukung" #: py/compile.c msgid "default 'except' must be last" @@ -2981,60 +3053,62 @@ msgstr "'except' standar harus terakhir" #: shared-bindings/msgpack/__init__.c msgid "default is not a function" -msgstr "" +msgstr "default bukan fungsi" #: shared-bindings/audiobusio/PDMIn.c msgid "" "destination buffer must be a bytearray or array of type 'B' for bit_depth = 8" msgstr "" +"buffer tujuan harus berupa bytearray atau array bertipe 'B' untuk bit_depth " +"= 8" #: shared-bindings/audiobusio/PDMIn.c msgid "destination buffer must be an array of type 'H' for bit_depth = 16" -msgstr "" +msgstr "buffer tujuan harus berupa array bertipe 'H' untuk bit_depth = 16" #: py/objdict.c msgid "dict update sequence has wrong length" -msgstr "" +msgstr "urutan pembaruan dict memiliki panjang yang salah" #: extmod/ulab/code/numpy/numerical.c msgid "diff argument must be an ndarray" -msgstr "" +msgstr "argumen diff harus berupa ndarray" #: extmod/ulab/code/numpy/numerical.c msgid "differentiation order out of range" -msgstr "" +msgstr "urutan diferensiasi di luar jangkauan" #: extmod/ulab/code/numpy/transform.c msgid "dimensions do not match" -msgstr "" +msgstr "dimensi tidak cocok" #: py/emitnative.c msgid "div/mod not implemented for uint" -msgstr "" +msgstr "div/mod tidak diimplementasikan untuk uint" #: extmod/ulab/code/numpy/create.c msgid "divide by zero" -msgstr "" +msgstr "pembagian dengan nol" #: py/runtime.c msgid "division by zero" -msgstr "" +msgstr "pembagian dengan nol" #: extmod/ulab/code/numpy/vector.c msgid "dtype must be float, or complex" -msgstr "" +msgstr "dtype harus float, atau complex" #: extmod/ulab/code/ndarray_operators.c msgid "dtype of int32 is not supported" -msgstr "" +msgstr "dtype int32 tidak didukung" #: py/objdeque.c msgid "empty" -msgstr "" +msgstr "kosong" #: extmod/ulab/code/numpy/io/io.c msgid "empty file" -msgstr "" +msgstr "file kosong" #: extmod/modasyncio.c extmod/modheapq.c msgid "empty heap" @@ -3042,19 +3116,19 @@ msgstr "heap kosong" #: py/objstr.c msgid "empty separator" -msgstr "" +msgstr "pemisah kosong" #: shared-bindings/random/__init__.c msgid "empty sequence" -msgstr "" +msgstr "urutan kosong" #: py/objstr.c msgid "end of format while looking for conversion specifier" -msgstr "" +msgstr "akhir format saat mencari spesifier konversi" #: shared-bindings/alarm/time/TimeAlarm.c msgid "epoch_time not supported on this board" -msgstr "" +msgstr "epoch_time tidak didukung pada board ini" #: ports/nordic/common-hal/busio/UART.c #, c-format @@ -3063,19 +3137,19 @@ msgstr "error = 0x%08lX" #: py/runtime.c msgid "exceptions must derive from BaseException" -msgstr "" +msgstr "exception harus diturunkan dari BaseException" #: py/objstr.c msgid "expected ':' after format specifier" -msgstr "" +msgstr "mengharapkan ':' setelah spesifier format" #: py/obj.c msgid "expected tuple/list" -msgstr "" +msgstr "mengharapkan tuple/list" #: py/modthread.c msgid "expecting a dict for keyword args" -msgstr "" +msgstr "mengharapkan dict untuk argumen keyword" #: py/compile.c msgid "expecting an assembler instruction" @@ -3091,7 +3165,7 @@ msgstr "key:value diharapkan untuk dict" #: shared-bindings/msgpack/__init__.c msgid "ext_hook is not a function" -msgstr "" +msgstr "ext_hook bukan fungsi" #: py/argcheck.c msgid "extra keyword arguments given" @@ -3105,11 +3179,11 @@ msgstr "argumen posisi ekstra telah diberikan" #: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/gifio/OnDiskGif.c #: shared-bindings/synthio/__init__.c shared-module/gifio/GifWriter.c msgid "file must be a file opened in byte mode" -msgstr "" +msgstr "file harus berupa file yang dibuka dalam mode byte" #: shared-bindings/traceback/__init__.c msgid "file write is not available" -msgstr "" +msgstr "penulisan file tidak tersedia" #: shared-bindings/storage/__init__.c msgid "filesystem must provide mount method" @@ -3117,63 +3191,63 @@ msgstr "" #: extmod/ulab/code/numpy/vector.c msgid "first argument must be a callable" -msgstr "" +msgstr "argumen pertama harus dapat dipanggil" #: extmod/ulab/code/scipy/optimize/optimize.c msgid "first argument must be a function" -msgstr "" +msgstr "argumen pertama harus berupa fungsi" #: extmod/ulab/code/numpy/create.c msgid "first argument must be a tuple of ndarrays" -msgstr "" +msgstr "argumen pertama harus berupa tuple ndarray" #: extmod/ulab/code/numpy/transform.c extmod/ulab/code/numpy/vector.c msgid "first argument must be an ndarray" -msgstr "" +msgstr "argumen pertama harus berupa ndarray" #: py/objtype.c msgid "first argument to super() must be type" -msgstr "" +msgstr "argumen pertama untuk super() harus bertipe type" #: extmod/ulab/code/scipy/linalg/linalg.c msgid "first two arguments must be ndarrays" -msgstr "" +msgstr "dua argumen pertama harus berupa ndarray" #: extmod/ulab/code/ndarray.c msgid "flattening order must be either 'C', or 'F'" -msgstr "" +msgstr "urutan perataan harus 'C', atau 'F'" #: extmod/ulab/code/numpy/numerical.c msgid "flip argument must be an ndarray" -msgstr "" +msgstr "argumen flip harus berupa ndarray" #: py/objint.c msgid "float too big" -msgstr "" +msgstr "float terlalu besar" #: py/nativeglue.c msgid "float unsupported" -msgstr "" +msgstr "float tidak didukung" #: shared-bindings/_stage/Text.c msgid "font must be 2048 bytes long" -msgstr "" +msgstr "font harus sepanjang 2048 byte" #: extmod/moddeflate.c msgid "format" -msgstr "" +msgstr "format" #: py/objstr.c -msgid "format requires a dict" -msgstr "" +msgid "format needs a dict" +msgstr "format memerlukan dict" #: py/objdeque.c msgid "full" -msgstr "" +msgstr "penuh" #: py/argcheck.c msgid "function doesn't take keyword arguments" -msgstr "" +msgstr "fungsi tidak menerima argumen keyword" #: py/argcheck.c #, c-format @@ -3186,15 +3260,15 @@ msgstr "fungsi mendapatkan nilai ganda untuk argumen '%q'" #: extmod/ulab/code/scipy/optimize/optimize.c msgid "function has the same sign at the ends of interval" -msgstr "" +msgstr "fungsi memiliki tanda yang sama pada ujung interval" #: extmod/ulab/code/ndarray.c msgid "function is defined for ndarrays only" -msgstr "" +msgstr "fungsi didefinisikan hanya untuk ndarray" #: extmod/ulab/code/numpy/carray/carray.c msgid "function is implemented for ndarrays only" -msgstr "" +msgstr "fungsi diimplementasikan hanya untuk ndarray" #: py/argcheck.c #, c-format @@ -3222,23 +3296,23 @@ msgstr "fungsi mengambil posisi argumen %d tapi %d yang diberikan" #: py/objgenerator.c msgid "generator already executing" -msgstr "" +msgstr "generator sudah berjalan" #: py/objgenerator.c msgid "generator ignored GeneratorExit" -msgstr "" +msgstr "generator mengabaikan GeneratorExit" #: py/objgenerator.c py/runtime.c msgid "generator raised StopIteration" -msgstr "" +msgstr "generator memunculkan StopIteration" #: shared-bindings/_stage/Layer.c msgid "graphic must be 2048 bytes long" -msgstr "" +msgstr "grafik harus sepanjang 2048 byte" #: extmod/modhashlib.c msgid "hash is final" -msgstr "" +msgstr "hash bersifat final" #: extmod/modheapq.c msgid "heap must be a list" @@ -3254,23 +3328,23 @@ msgstr "identifier didefinisi ulang sebagai nonlocal" #: py/compile.c msgid "import * not at module level" -msgstr "" +msgstr "import * tidak pada tingkat modul" #: py/persistentcode.c msgid "incompatible .mpy arch" -msgstr "" +msgstr "arsitektur .mpy tidak kompatibel" #: py/persistentcode.c msgid "incompatible .mpy file" -msgstr "" +msgstr "file .mpy tidak kompatibel" #: py/objstr.c msgid "incomplete format" -msgstr "" +msgstr "format tidak lengkap" #: py/objstr.c msgid "incomplete format key" -msgstr "" +msgstr "kunci format tidak lengkap" #: extmod/modbinascii.c msgid "incorrect padding" @@ -3278,11 +3352,11 @@ msgstr "lapisan (padding) tidak benar" #: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/transform.c msgid "index is out of bounds" -msgstr "" +msgstr "indeks berada di luar batas" #: shared-bindings/_pixelmap/PixelMap.c msgid "index must be tuple or int" -msgstr "" +msgstr "indeks harus berupa tuple atau int" #: extmod/ulab/code/numpy/numerical.c extmod/ulab/code/ulab_tools.c #: ports/espressif/common-hal/pulseio/PulseIn.c @@ -3292,19 +3366,19 @@ msgstr "index keluar dari jangkauan" #: py/obj.c msgid "indices must be integers" -msgstr "" +msgstr "indeks harus berupa integer" #: extmod/ulab/code/ndarray.c msgid "indices must be integers, slices, or Boolean lists" -msgstr "" +msgstr "indeks harus berupa integer, slice, atau list Boolean" #: extmod/ulab/code/scipy/optimize/optimize.c msgid "initial values must be iterable" -msgstr "" +msgstr "nilai awal harus dapat diiterasi" #: shared-bindings/_bleio/Characteristic.c shared-bindings/_bleio/Descriptor.c msgid "initial_value length is wrong" -msgstr "" +msgstr "panjang initial_value salah" #: py/compile.c msgid "inline assembler must be a function" @@ -3312,98 +3386,98 @@ msgstr "inline assembler harus sebuah fungsi" #: extmod/ulab/code/numpy/vector.c msgid "input and output dimensions differ" -msgstr "" +msgstr "dimensi input dan output berbeda" #: extmod/ulab/code/numpy/vector.c msgid "input and output shapes differ" -msgstr "" +msgstr "bentuk input dan output berbeda" #: extmod/ulab/code/numpy/create.c msgid "input argument must be an integer, a tuple, or a list" -msgstr "" +msgstr "argumen input harus berupa integer, tuple, atau list" #: extmod/ulab/code/numpy/fft/fft_tools.c msgid "input array length must be power of 2" -msgstr "" +msgstr "panjang array input harus pangkat 2" #: extmod/ulab/code/numpy/create.c msgid "input arrays are not compatible" -msgstr "" +msgstr "array input tidak kompatibel" #: extmod/ulab/code/numpy/poly.c msgid "input data must be an iterable" -msgstr "" +msgstr "data input harus dapat diiterasi" #: extmod/ulab/code/numpy/vector.c msgid "input dtype must be float or complex" -msgstr "" +msgstr "dtype input harus float atau complex" #: extmod/ulab/code/numpy/poly.c msgid "input is not iterable" -msgstr "" +msgstr "input tidak dapat diiterasi" #: extmod/ulab/code/numpy/linalg/linalg.c msgid "input matrix is asymmetric" -msgstr "" +msgstr "matriks input asimetris" #: extmod/ulab/code/numpy/linalg/linalg.c #: extmod/ulab/code/scipy/linalg/linalg.c msgid "input matrix is singular" -msgstr "" +msgstr "matriks input singular" #: extmod/ulab/code/numpy/create.c msgid "input must be 1- or 2-d" -msgstr "" +msgstr "input harus 1- atau 2-d" #: extmod/ulab/code/numpy/carray/carray.c msgid "input must be a 1D ndarray" -msgstr "" +msgstr "input harus berupa ndarray 1D" #: extmod/ulab/code/scipy/linalg/linalg.c extmod/ulab/code/user/user.c msgid "input must be a dense ndarray" -msgstr "" +msgstr "input harus berupa ndarray padat" #: extmod/ulab/code/user/user.c shared-bindings/_eve/__init__.c msgid "input must be an ndarray" -msgstr "" +msgstr "input harus berupa ndarray" #: extmod/ulab/code/numpy/carray/carray.c msgid "input must be an ndarray, or a scalar" -msgstr "" +msgstr "input harus berupa ndarray, atau skalar" #: extmod/ulab/code/scipy/signal/signal.c msgid "input must be one-dimensional" -msgstr "" +msgstr "input harus satu dimensi" #: extmod/ulab/code/ulab_tools.c msgid "input must be square matrix" -msgstr "" +msgstr "input harus berupa matriks persegi" #: extmod/ulab/code/numpy/numerical.c msgid "input must be tuple, list, range, or ndarray" -msgstr "" +msgstr "input harus berupa tuple, list, range, atau ndarray" #: extmod/ulab/code/numpy/poly.c msgid "input vectors must be of equal length" -msgstr "" +msgstr "vektor input harus memiliki panjang yang sama" #: extmod/ulab/code/numpy/approx.c msgid "interp is defined for 1D iterables of equal length" -msgstr "" +msgstr "interp didefinisikan untuk iterable 1D dengan panjang yang sama" #: shared-bindings/_bleio/Adapter.c #, c-format msgid "interval must be in range %s-%s" -msgstr "" +msgstr "interval harus dalam rentang %s-%s" #: py/compile.c msgid "invalid arch" -msgstr "" +msgstr "arsitektur tidak valid" #: shared-bindings/bitmaptools/__init__.c #, c-format msgid "invalid bits_per_pixel %d, must be, 1, 2, 4, 8, 16, 24, or 32" -msgstr "" +msgstr "bits_per_pixel %d tidak valid, harus 1, 2, 4, 8, 16, 24, atau 32" #: shared-module/ssl/SSLSocket.c msgid "invalid cert" @@ -3412,24 +3486,24 @@ msgstr "cert tidak valid" #: shared-bindings/bitmaptools/__init__.c #, c-format msgid "invalid element size %d for bits_per_pixel %d\n" -msgstr "" +msgstr "element size %d tidak valid untuk bits_per_pixel %d\n" #: shared-bindings/bitmaptools/__init__.c #, c-format msgid "invalid element_size %d, must be, 1, 2, or 4" -msgstr "" +msgstr "element_size %d tidak valid, harus 1, 2, atau 4" #: shared-bindings/traceback/__init__.c msgid "invalid exception" -msgstr "" +msgstr "exception tidak valid" #: py/objstr.c msgid "invalid format specifier" -msgstr "" +msgstr "spesifier format tidak valid" #: shared-bindings/wifi/Radio.c msgid "invalid hostname" -msgstr "" +msgstr "hostname tidak valid" #: shared-module/ssl/SSLSocket.c msgid "invalid key" @@ -3441,11 +3515,11 @@ msgstr "micropython decorator tidak valid" #: ports/espressif/common-hal/espcamera/Camera.c msgid "invalid setting" -msgstr "" +msgstr "pengaturan tidak valid" #: shared-bindings/random/__init__.c msgid "invalid step" -msgstr "" +msgstr "step tidak valid" #: py/compile.c py/parse.c msgid "invalid syntax" @@ -3453,40 +3527,42 @@ msgstr "syntax tidak valid" #: py/parsenum.c msgid "invalid syntax for integer" -msgstr "" +msgstr "sintaks tidak valid untuk integer" #: py/parsenum.c #, c-format msgid "invalid syntax for integer with base %d" -msgstr "" +msgstr "sintaks tidak valid untuk integer dengan basis %d" #: py/parsenum.c msgid "invalid syntax for number" -msgstr "" +msgstr "sintaks tidak valid untuk angka" #: py/objtype.c msgid "issubclass() arg 1 must be a class" -msgstr "" +msgstr "argumen 1 issubclass() harus berupa class" #: py/objtype.c msgid "issubclass() arg 2 must be a class or a tuple of classes" -msgstr "" +msgstr "argumen 2 issubclass() harus berupa class atau tuple class" #: extmod/ulab/code/numpy/linalg/linalg.c msgid "iterations did not converge" -msgstr "" +msgstr "iterasi tidak konvergen" #: py/objstr.c msgid "join expects a list of str/bytes objects consistent with self object" -msgstr "" +msgstr "join mengharapkan list objek str/bytes yang konsisten dengan objek self" #: py/argcheck.c msgid "keyword argument(s) not implemented - use normal args instead" msgstr "" +"argumen keyword tidak diimplementasikan - gunakan argumen normal sebagai " +"gantinya" #: py/emitinlinethumb.c py/emitinlinextensa.c msgid "label '%q' not defined" -msgstr "" +msgstr "label '%q' tidak didefinisikan" #: py/compile.c msgid "label redefined" @@ -3494,101 +3570,101 @@ msgstr "label didefinis ulang" #: py/objarray.c msgid "lhs and rhs should be compatible" -msgstr "" +msgstr "lhs dan rhs harus kompatibel" #: py/emitnative.c msgid "local '%q' has type '%q' but source is '%q'" -msgstr "" +msgstr "lokal '%q' memiliki tipe '%q' tetapi sumber adalah '%q'" #: py/emitnative.c msgid "local '%q' used before type known" -msgstr "" +msgstr "lokal '%q' digunakan sebelum tipe diketahui" #: py/vm.c msgid "local variable referenced before assignment" -msgstr "" +msgstr "variabel lokal direferensikan sebelum penetapan" #: ports/espressif/common-hal/canio/CAN.c msgid "loopback + silent mode not supported by peripheral" -msgstr "" +msgstr "mode loopback + silent tidak didukung oleh periferal" #: ports/espressif/common-hal/mdns/Server.c #: ports/raspberrypi/common-hal/mdns/Server.c msgid "mDNS already initialized" -msgstr "" +msgstr "mDNS sudah diinisialisasi" #: ports/espressif/common-hal/mdns/Server.c #: ports/raspberrypi/common-hal/mdns/Server.c msgid "mDNS only works with built-in WiFi" -msgstr "" +msgstr "mDNS hanya bekerja dengan WiFi bawaan" #: py/parse.c msgid "malformed f-string" -msgstr "" +msgstr "f-string salah bentuk" #: shared-bindings/_stage/Layer.c msgid "map buffer too small" -msgstr "" +msgstr "buffer peta terlalu kecil" #: py/modmath.c shared-bindings/math/__init__.c msgid "math domain error" -msgstr "" +msgstr "kesalahan domain matematika" #: extmod/ulab/code/numpy/linalg/linalg.c msgid "matrix is not positive definite" -msgstr "" +msgstr "matriks tidak definit positif" #: ports/espressif/common-hal/_bleio/Descriptor.c #: ports/nordic/common-hal/_bleio/Characteristic.c #: ports/nordic/common-hal/_bleio/Descriptor.c #, c-format msgid "max_length must be 0-%d when fixed_length is %s" -msgstr "" +msgstr "max_length harus 0-%d ketika fixed_length adalah %s" #: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/random/random.c msgid "maximum number of dimensions is " -msgstr "" +msgstr "jumlah maksimum dimensi adalah " #: py/runtime.c msgid "maximum recursion depth exceeded" -msgstr "" +msgstr "kedalaman rekursi maksimum terlampaui" #: extmod/ulab/code/scipy/optimize/optimize.c msgid "maxiter must be > 0" -msgstr "" +msgstr "maxiter harus > 0" #: extmod/ulab/code/scipy/optimize/optimize.c msgid "maxiter should be > 0" -msgstr "" +msgstr "maxiter harus > 0" #: extmod/ulab/code/numpy/numerical.c msgid "median argument must be an ndarray" -msgstr "" +msgstr "argumen median harus berupa ndarray" #: py/runtime.c #, c-format msgid "memory allocation failed, allocating %u bytes" -msgstr "" +msgstr "alokasi memori gagal, mengalokasikan %u byte" #: py/runtime.c msgid "memory allocation failed, heap is locked" -msgstr "" +msgstr "alokasi memori gagal, heap terkunci" #: py/objarray.c msgid "memoryview offset too large" -msgstr "" +msgstr "offset memoryview terlalu besar" #: py/objarray.c msgid "memoryview: length is not a multiple of itemsize" -msgstr "" +msgstr "memoryview: panjang bukan kelipatan dari itemsize" #: extmod/modtime.c msgid "mktime needs a tuple of length 8 or 9" -msgstr "" +msgstr "mktime memerlukan tuple dengan panjang 8 atau 9" #: extmod/ulab/code/numpy/linalg/linalg.c msgid "mode must be complete, or reduced" -msgstr "" +msgstr "mode harus complete, atau reduced" #: py/builtinimport.c msgid "module not found" @@ -3596,11 +3672,11 @@ msgstr "modul tidak ditemukan" #: ports/espressif/common-hal/wifi/Monitor.c msgid "monitor init failed" -msgstr "" +msgstr "inisialisasi monitor gagal" #: extmod/ulab/code/numpy/poly.c msgid "more degrees of freedom than data points" -msgstr "" +msgstr "lebih banyak derajat kebebasan daripada titik data" #: py/compile.c msgid "multiple *x in assignment" @@ -3608,76 +3684,76 @@ msgstr "perkalian *x dalam assignment" #: py/objtype.c msgid "multiple bases have instance lay-out conflict" -msgstr "" +msgstr "beberapa basis memiliki konflik tata letak instance" #: py/objtype.c msgid "multiple inheritance not supported" -msgstr "" +msgstr "pewarisan berganda tidak didukung" #: py/emitnative.c msgid "must raise an object" -msgstr "" +msgstr "harus memunculkan objek" #: py/modbuiltins.c msgid "must use keyword argument for key function" -msgstr "" +msgstr "harus menggunakan argumen keyword untuk fungsi kunci" #: py/runtime.c -msgid "name '%q' is not defined" -msgstr "" +msgid "name '%q' isn't defined" +msgstr "nama '%q' tidak didefinisikan" #: py/runtime.c msgid "name not defined" -msgstr "" +msgstr "nama tidak didefinisikan" #: py/qstr.c msgid "name too long" -msgstr "" +msgstr "nama terlalu panjang" #: py/persistentcode.c msgid "native code in .mpy unsupported" -msgstr "" +msgstr "kode native dalam .mpy tidak didukung" #: py/asmthumb.c msgid "native method too big" -msgstr "" +msgstr "metode native terlalu besar" #: py/emitnative.c msgid "native yield" -msgstr "" +msgstr "yield native" #: extmod/ulab/code/ndarray.c msgid "ndarray length overflows" -msgstr "" +msgstr "panjang ndarray meluap" #: py/runtime.c #, c-format msgid "need more than %d values to unpack" -msgstr "" +msgstr "memerlukan lebih dari %d nilai untuk membongkar" #: py/modmath.c msgid "negative factorial" -msgstr "" +msgstr "faktorial negatif" #: py/objint_longlong.c py/objint_mpz.c py/runtime.c msgid "negative power with no float support" -msgstr "" +msgstr "pangkat negatif tanpa dukungan float" #: py/objint_mpz.c py/runtime.c msgid "negative shift count" -msgstr "" +msgstr "jumlah shift negatif" #: shared-bindings/_pixelmap/PixelMap.c msgid "nested index must be int" -msgstr "" +msgstr "indeks bersarang harus int" #: shared-module/sdcardio/SDCard.c msgid "no SD card" -msgstr "" +msgstr "tidak ada kartu SD" #: py/vm.c msgid "no active exception to reraise" -msgstr "" +msgstr "tidak ada exception aktif untuk dimunculkan kembali" #: py/compile.c msgid "no binding for nonlocal found" @@ -3685,11 +3761,11 @@ msgstr "tidak ada ikatan/bind pada temuan nonlocal" #: shared-module/msgpack/__init__.c msgid "no default packer" -msgstr "" +msgstr "tidak ada packer default" #: extmod/modrandom.c extmod/ulab/code/numpy/random/random.c msgid "no default seed" -msgstr "" +msgstr "tidak ada seed default" #: py/builtinimport.c msgid "no module named '%q'" @@ -3697,16 +3773,16 @@ msgstr "tidak ada modul yang bernama '%q'" #: shared-module/sdcardio/SDCard.c msgid "no response from SD card" -msgstr "" +msgstr "tidak ada respons dari kartu SD" #: ports/espressif/common-hal/espcamera/Camera.c py/objobject.c py/runtime.c msgid "no such attribute" -msgstr "" +msgstr "atribut tidak ada" #: ports/espressif/common-hal/_bleio/Connection.c #: ports/nordic/common-hal/_bleio/Connection.c msgid "non-UUID found in service_uuids_whitelist" -msgstr "" +msgstr "non-UUID ditemukan dalam service_uuids_whitelist" #: py/compile.c msgid "non-default argument follows default argument" @@ -3718,19 +3794,19 @@ msgstr "digit non-hex ditemukan" #: ports/nordic/common-hal/_bleio/Adapter.c msgid "non-zero timeout must be > 0.01" -msgstr "" +msgstr "timeout non-nol harus > 0.01" #: shared-bindings/_bleio/Adapter.c msgid "non-zero timeout must be >= interval" -msgstr "" +msgstr "timeout non-nol harus >= interval" #: shared-bindings/_bleio/UUID.c msgid "not a 128-bit UUID" -msgstr "" +msgstr "bukan UUID 128-bit" #: py/parse.c msgid "not a constant" -msgstr "" +msgstr "bukan konstanta" #: py/objstr.c msgid "not all arguments converted during string formatting" @@ -3742,65 +3818,65 @@ msgstr "" #: extmod/ulab/code/numpy/carray/carray_tools.c msgid "not implemented for complex dtype" -msgstr "" +msgstr "tidak diimplementasikan untuk dtype complex" #: extmod/ulab/code/numpy/bitwise.c msgid "not supported for input types" -msgstr "" +msgstr "tidak didukung untuk tipe input" #: extmod/ulab/code/numpy/create.c msgid "number of points must be at least 2" -msgstr "" +msgstr "jumlah titik harus setidaknya 2" #: py/builtinhelp.c msgid "object " -msgstr "" +msgstr "objek " #: py/obj.c #, c-format msgid "object '%s' isn't a tuple or list" -msgstr "" +msgstr "objek '%s' bukan tuple atau list" #: py/obj.c msgid "object doesn't support item assignment" -msgstr "" +msgstr "objek tidak mendukung penetapan item" #: py/obj.c msgid "object doesn't support item deletion" -msgstr "" +msgstr "objek tidak mendukung penghapusan item" #: py/obj.c msgid "object has no len" -msgstr "" +msgstr "objek tidak memiliki len" #: py/obj.c msgid "object isn't subscriptable" -msgstr "" +msgstr "objek tidak dapat disubskripsikan" #: py/runtime.c msgid "object not an iterator" -msgstr "" +msgstr "objek bukan iterator" #: py/objtype.c py/runtime.c msgid "object not callable" -msgstr "" +msgstr "objek tidak dapat dipanggil" #: py/sequence.c shared-bindings/displayio/Group.c msgid "object not in sequence" -msgstr "" +msgstr "objek tidak dalam urutan" #: py/runtime.c msgid "object not iterable" -msgstr "" +msgstr "objek tidak dapat diiterasi" #: py/obj.c #, c-format msgid "object of type '%s' has no len()" -msgstr "" +msgstr "objek bertipe '%s' tidak memiliki len()" #: py/obj.c msgid "object with buffer protocol required" -msgstr "" +msgstr "objek dengan protokol buffer diperlukan" #: py/objstr.c msgid "odd-length string" @@ -3808,146 +3884,146 @@ msgstr "panjang data string memiliki keganjilan (odd-length)" #: supervisor/shared/web_workflow/web_workflow.c msgid "off" -msgstr "" +msgstr "mati" #: extmod/ulab/code/utils/utils.c msgid "offset is too large" -msgstr "" +msgstr "offset terlalu besar" #: shared-bindings/dualbank/__init__.c msgid "offset must be >= 0" -msgstr "" +msgstr "offset harus >= 0" #: extmod/ulab/code/numpy/create.c msgid "offset must be non-negative and no greater than buffer length" -msgstr "" +msgstr "offset harus non-negatif dan tidak lebih besar dari panjang buffer" #: ports/nordic/common-hal/audiobusio/PDMIn.c #: ports/stm/common-hal/audiobusio/PDMIn.c msgid "only bit_depth=16 is supported" -msgstr "" +msgstr "hanya bit_depth=16 yang didukung" #: ports/stm/common-hal/audiobusio/PDMIn.c msgid "only mono is supported" -msgstr "" +msgstr "hanya mono yang didukung" #: extmod/ulab/code/numpy/create.c msgid "only ndarrays can be concatenated" -msgstr "" +msgstr "hanya ndarray yang dapat digabungkan" #: ports/stm/common-hal/audiobusio/PDMIn.c msgid "only oversample=64 is supported" -msgstr "" +msgstr "hanya oversample=64 yang didukung" #: ports/nordic/common-hal/audiobusio/PDMIn.c #: ports/stm/common-hal/audiobusio/PDMIn.c msgid "only sample_rate=16000 is supported" -msgstr "" +msgstr "hanya sample_rate=16000 yang didukung" #: py/objarray.c py/objstr.c py/objstrunicode.c py/objtuple.c #: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c #: shared-bindings/nvm/ByteArray.c msgid "only slices with step=1 (aka None) are supported" -msgstr "" +msgstr "hanya slice dengan step=1 (alias None) yang didukung" #: py/vm.c msgid "opcode" -msgstr "" +msgstr "opcode" #: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/bitwise.c #: extmod/ulab/code/numpy/compare.c extmod/ulab/code/numpy/vector.c msgid "operands could not be broadcast together" -msgstr "" +msgstr "operan tidak dapat di-broadcast bersama" #: extmod/ulab/code/numpy/linalg/linalg.c msgid "operation is defined for 2D arrays only" -msgstr "" +msgstr "operasi didefinisikan hanya untuk array 2D" #: extmod/ulab/code/numpy/linalg/linalg.c msgid "operation is defined for ndarrays only" -msgstr "" +msgstr "operasi didefinisikan hanya untuk ndarray" #: extmod/ulab/code/ndarray.c msgid "operation is implemented for 1D Boolean arrays only" -msgstr "" +msgstr "operasi diimplementasikan hanya untuk array Boolean 1D" #: extmod/ulab/code/numpy/numerical.c msgid "operation is not implemented on ndarrays" -msgstr "" +msgstr "operasi tidak diimplementasikan pada ndarray" #: extmod/ulab/code/ndarray.c msgid "operation is not supported for given type" -msgstr "" +msgstr "operasi tidak didukung untuk tipe yang diberikan" #: extmod/ulab/code/ndarray_operators.c msgid "operation not supported for the input types" -msgstr "" +msgstr "operasi tidak didukung untuk tipe input" #: py/modbuiltins.c msgid "ord expects a character" -msgstr "" +msgstr "ord mengharapkan karakter" #: py/modbuiltins.c #, c-format msgid "ord() expected a character, but string of length %d found" -msgstr "" +msgstr "ord() mengharapkan karakter, tetapi string dengan panjang %d ditemukan" #: extmod/ulab/code/utils/utils.c msgid "out array is too small" -msgstr "" +msgstr "array out terlalu kecil" #: extmod/ulab/code/numpy/random/random.c msgid "out has wrong type" -msgstr "" +msgstr "out memiliki tipe yang salah" #: extmod/ulab/code/numpy/vector.c msgid "out keyword is not supported for complex dtype" -msgstr "" +msgstr "keyword out tidak didukung untuk dtype complex" #: extmod/ulab/code/numpy/vector.c msgid "out keyword is not supported for function" -msgstr "" +msgstr "keyword out tidak didukung untuk fungsi" #: extmod/ulab/code/utils/utils.c msgid "out must be a float dense array" -msgstr "" +msgstr "out harus berupa array padat float" #: extmod/ulab/code/numpy/vector.c msgid "out must be an ndarray" -msgstr "" +msgstr "out harus berupa ndarray" #: extmod/ulab/code/numpy/vector.c msgid "out must be of float dtype" -msgstr "" +msgstr "out harus bertipe dtype float" #: shared-bindings/bitmaptools/__init__.c msgid "out of range of target" -msgstr "" +msgstr "di luar jangkauan target" #: extmod/ulab/code/numpy/random/random.c msgid "output array has wrong type" -msgstr "" +msgstr "array output memiliki tipe yang salah" #: extmod/ulab/code/numpy/random/random.c msgid "output array must be contiguous" -msgstr "" +msgstr "array output harus berdekatan" #: py/objint_mpz.c msgid "overflow converting long int to machine word" -msgstr "" +msgstr "overflow saat mengonversi long int ke machine word" #: py/modstruct.c #, c-format msgid "pack expected %d items for packing (got %d)" -msgstr "" +msgstr "pack mengharapkan %d item untuk packing (mendapat %d)" #: shared-bindings/_stage/Layer.c shared-bindings/_stage/Text.c msgid "palette must be 32 bytes long" -msgstr "" +msgstr "palet harus sepanjang 32 byte" #: py/emitinlinextensa.c msgid "parameters must be registers in sequence a2 to a5" -msgstr "" +msgstr "parameter harus berupa register dalam urutan a2 hingga a5" #: py/emitinlinethumb.c msgid "parameters must be registers in sequence r0 to r3" @@ -3955,7 +4031,7 @@ msgstr "parameter harus menjadi register dalam urutan r0 sampai r3" #: extmod/vfs_posix_file.c msgid "poll on file not available on win32" -msgstr "" +msgstr "poll pada file tidak tersedia di win32" #: ports/espressif/common-hal/pulseio/PulseIn.c msgid "pop from an empty PulseIn" @@ -3968,31 +4044,31 @@ msgstr "Muncul dari PulseIn yang kosong" #: 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 "" +msgstr "pop dari %q kosong" #: shared-bindings/socketpool/Socket.c msgid "port must be >= 0" -msgstr "" +msgstr "port harus >= 0" #: py/compile.c msgid "positional arg after **" -msgstr "" +msgstr "argumen posisional setelah **" #: py/compile.c msgid "positional arg after keyword arg" -msgstr "" +msgstr "argumen posisional setelah argumen keyword" #: py/objint_mpz.c msgid "pow() 3rd argument cannot be 0" -msgstr "" +msgstr "argumen ketiga pow() tidak boleh 0" #: py/objint_mpz.c msgid "pow() with 3 arguments requires integers" -msgstr "" +msgstr "pow() dengan 3 argumen memerlukan integer" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "pull masks conflict with direction masks" -msgstr "" +msgstr "mask pull berkonflik dengan mask arah" #: py/parse.c msgid "raw f-strings are not supported" @@ -4000,20 +4076,20 @@ msgstr "" #: extmod/ulab/code/numpy/fft/fft_tools.c msgid "real and imaginary parts must be of equal length" -msgstr "" +msgstr "bagian real dan imajiner harus memiliki panjang yang sama" #: py/builtinimport.c msgid "relative import" -msgstr "relative import" +msgstr "impor relatif" #: py/obj.c #, c-format msgid "requested length %d but object has length %d" -msgstr "" +msgstr "panjang yang diminta %d tetapi objek memiliki panjang %d" #: extmod/ulab/code/ndarray_operators.c msgid "results cannot be cast to specified type" -msgstr "" +msgstr "hasil tidak dapat di-cast ke tipe yang ditentukan" #: py/compile.c msgid "return annotation must be an identifier" @@ -4021,25 +4097,29 @@ msgstr "anotasi return harus sebuah identifier" #: py/emitnative.c msgid "return expected '%q' but got '%q'" -msgstr "" +msgstr "return mengharapkan '%q' tetapi mendapat '%q'" #: shared-bindings/rgbmatrix/RGBMatrix.c #, c-format msgid "rgb_pins[%d] duplicates another pin assignment" -msgstr "" +msgstr "rgb_pins[%d] menduplikasi penetapan pin lain" #: shared-bindings/rgbmatrix/RGBMatrix.c #, c-format msgid "rgb_pins[%d] is not on the same port as clock" -msgstr "" +msgstr "rgb_pins[%d] tidak pada port yang sama dengan clock" #: extmod/ulab/code/numpy/numerical.c msgid "roll argument must be an ndarray" -msgstr "" +msgstr "argumen roll harus berupa ndarray" #: py/objstr.c msgid "rsplit(None,n)" -msgstr "" +msgstr "rsplit(None,n)" + +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "samples_signed must be true" +msgstr "samples_signed harus true" #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c #: ports/raspberrypi/common-hal/audiobusio/PDMIn.c @@ -4048,7 +4128,7 @@ msgstr "nilai sampling keluar dari jangkauan" #: py/modmicropython.c msgid "schedule queue full" -msgstr "" +msgstr "antrian jadwal penuh" #: py/builtinimport.c msgid "script compilation not supported" @@ -4056,43 +4136,43 @@ msgstr "kompilasi script tidak didukung" #: py/nativeglue.c msgid "set unsupported" -msgstr "" +msgstr "set tidak didukung" #: extmod/ulab/code/numpy/random/random.c msgid "shape must be None, and integer or a tuple of integers" -msgstr "" +msgstr "shape harus None, dan integer atau tuple integer" #: extmod/ulab/code/ndarray.c msgid "shape must be integer or tuple of integers" -msgstr "" +msgstr "shape harus integer atau tuple integer" #: shared-module/msgpack/__init__.c msgid "short read" -msgstr "" +msgstr "pembacaan pendek" #: py/objstr.c msgid "sign not allowed in string format specifier" -msgstr "" +msgstr "tanda tidak diperbolehkan dalam spesifier format string" #: py/objstr.c msgid "sign not allowed with integer format specifier 'c'" -msgstr "" +msgstr "tanda tidak diperbolehkan dengan spesifier format integer 'c'" #: extmod/ulab/code/ulab_tools.c msgid "size is defined for ndarrays only" -msgstr "" +msgstr "size didefinisikan hanya untuk ndarray" #: extmod/ulab/code/numpy/random/random.c msgid "size must match out.shape when used together" -msgstr "" +msgstr "size harus cocok dengan out.shape ketika digunakan bersama" #: py/nativeglue.c msgid "slice unsupported" -msgstr "" +msgstr "slice tidak didukung" #: py/objint.c py/sequence.c msgid "small int overflow" -msgstr "" +msgstr "overflow int kecil" #: main.c msgid "soft reboot\n" @@ -4100,39 +4180,39 @@ msgstr "memulai ulang software(soft reboot)\n" #: extmod/ulab/code/numpy/numerical.c msgid "sort argument must be an ndarray" -msgstr "" +msgstr "argumen sort harus berupa ndarray" #: extmod/ulab/code/scipy/signal/signal.c msgid "sos array must be of shape (n_section, 6)" -msgstr "" +msgstr "array sos harus berbentuk (n_section, 6)" #: extmod/ulab/code/scipy/signal/signal.c msgid "sos[:, 3] should be all ones" -msgstr "" +msgstr "sos[:, 3] harus semuanya satu" #: extmod/ulab/code/scipy/signal/signal.c msgid "sosfilt requires iterable arguments" -msgstr "" +msgstr "sosfilt memerlukan argumen yang dapat diiterasi" #: shared-bindings/bitmaptools/__init__.c msgid "source palette too large" -msgstr "" +msgstr "palet sumber terlalu besar" #: shared-bindings/bitmaptools/__init__.c msgid "source_bitmap must have value_count of 2 or 65536" -msgstr "" +msgstr "source_bitmap harus memiliki value_count 2 atau 65536" #: shared-bindings/bitmaptools/__init__.c msgid "source_bitmap must have value_count of 65536" -msgstr "" +msgstr "source_bitmap harus memiliki value_count 65536" #: shared-bindings/bitmaptools/__init__.c msgid "source_bitmap must have value_count of 8" -msgstr "" +msgstr "source_bitmap harus memiliki value_count 8" #: extmod/modre.c msgid "splitting with sub-captures" -msgstr "" +msgstr "pemisahan dengan sub-capture" #: py/objstr.c msgid "start/end indices" @@ -4140,28 +4220,28 @@ msgstr "" #: shared-bindings/random/__init__.c msgid "stop not reachable from start" -msgstr "" +msgstr "stop tidak dapat dijangkau dari start" #: py/stream.c shared-bindings/getpass/__init__.c msgid "stream operation not supported" -msgstr "" +msgstr "operasi stream tidak didukung" #: py/objarray.c py/objstr.c msgid "string argument without an encoding" -msgstr "" +msgstr "argumen string tanpa encoding" #: py/objstrunicode.c msgid "string index out of range" -msgstr "" +msgstr "indeks string di luar jangkauan" #: py/objstrunicode.c #, c-format msgid "string indices must be integers, not %s" -msgstr "" +msgstr "indeks string harus integer, bukan %s" #: py/objarray.c py/objstr.c msgid "substring not found" -msgstr "" +msgstr "substring tidak ditemukan" #: py/compile.c msgid "super() can't find self" @@ -4173,115 +4253,115 @@ msgstr "sintaksis error pada JSON" #: extmod/modtime.c msgid "ticks interval overflow" -msgstr "" +msgstr "overflow interval tick" #: ports/nordic/common-hal/watchdog/WatchDogTimer.c msgid "timeout duration exceeded the maximum supported value" -msgstr "" +msgstr "durasi timeout melebihi nilai maksimum yang didukung" #: ports/nordic/common-hal/_bleio/Adapter.c msgid "timeout must be < 655.35 secs" -msgstr "" +msgstr "timeout harus < 655.35 detik" #: ports/raspberrypi/common-hal/floppyio/__init__.c msgid "timeout waiting for flux" -msgstr "" +msgstr "timeout menunggu flux" #: ports/raspberrypi/common-hal/floppyio/__init__.c #: shared-module/floppyio/__init__.c msgid "timeout waiting for index pulse" -msgstr "" +msgstr "timeout menunggu pulsa indeks" #: shared-module/sdcardio/SDCard.c msgid "timeout waiting for v1 card" -msgstr "" +msgstr "timeout menunggu kartu v1" #: shared-module/sdcardio/SDCard.c msgid "timeout waiting for v2 card" -msgstr "" +msgstr "timeout menunggu kartu v2" #: ports/stm/common-hal/pwmio/PWMOut.c msgid "timer re-init" -msgstr "" +msgstr "inisialisasi ulang timer" #: shared-bindings/time/__init__.c msgid "timestamp out of range for platform time_t" -msgstr "" +msgstr "timestamp di luar jangkauan untuk time_t platform" #: extmod/ulab/code/ndarray.c msgid "tobytes can be invoked for dense arrays only" -msgstr "" +msgstr "tobytes hanya dapat dipanggil untuk array padat" #: py/compile.c msgid "too many args" -msgstr "" +msgstr "terlalu banyak argumen" #: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/create.c msgid "too many dimensions" -msgstr "" +msgstr "terlalu banyak dimensi" #: extmod/ulab/code/ndarray.c msgid "too many indices" -msgstr "" +msgstr "terlalu banyak indeks" #: py/asmthumb.c msgid "too many locals for native method" -msgstr "" +msgstr "terlalu banyak lokal untuk metode native" #: py/runtime.c #, c-format msgid "too many values to unpack (expected %d)" -msgstr "" +msgstr "terlalu banyak nilai untuk dibongkar (diharapkan %d)" #: extmod/ulab/code/numpy/approx.c msgid "trapz is defined for 1D arrays of equal length" -msgstr "" +msgstr "trapz didefinisikan untuk array 1D dengan panjang yang sama" #: extmod/ulab/code/numpy/approx.c msgid "trapz is defined for 1D iterables" -msgstr "" +msgstr "trapz didefinisikan untuk iterable 1D" #: py/obj.c msgid "tuple/list has wrong length" -msgstr "" +msgstr "tuple/list memiliki panjang yang salah" #: ports/espressif/common-hal/canio/CAN.c #, c-format msgid "twai_driver_install returned esp-idf error #%d" -msgstr "" +msgstr "twai_driver_install mengembalikan kesalahan esp-idf #%d" #: ports/espressif/common-hal/canio/CAN.c #, c-format msgid "twai_start returned esp-idf error #%d" -msgstr "" +msgstr "twai_start mengembalikan kesalahan esp-idf #%d" #: shared-bindings/busio/UART.c shared-bindings/canio/CAN.c msgid "tx and rx cannot both be None" msgstr "tx dan rx keduanya tidak boleh kosong" #: py/objtype.c -msgid "type '%q' is not an acceptable base type" -msgstr "" +msgid "type '%q' isn't an acceptable base type" +msgstr "tipe '%q' bukan tipe basis yang dapat diterima" #: py/objtype.c -msgid "type is not an acceptable base type" -msgstr "" +msgid "type isn't an acceptable base type" +msgstr "tipe bukan tipe basis yang dapat diterima" #: py/runtime.c msgid "type object '%q' has no attribute '%q'" -msgstr "" +msgstr "objek tipe '%q' tidak memiliki atribut '%q'" #: py/objtype.c msgid "type takes 1 or 3 arguments" -msgstr "" +msgstr "type memerlukan 1 atau 3 argumen" #: py/objint_longlong.c msgid "ulonglong too large" -msgstr "" +msgstr "ulonglong terlalu besar" #: py/parse.c msgid "unexpected indent" -msgstr "" +msgstr "indentasi tak terduga" #: py/bc.c msgid "unexpected keyword argument" @@ -4294,20 +4374,20 @@ msgstr "keyword argumen '%q' tidak diharapkan" #: py/lexer.c msgid "unicode name escapes" -msgstr "" +msgstr "escape nama unicode" #: py/parse.c msgid "unindent doesn't match any outer indent level" -msgstr "" +msgstr "unindent tidak cocok dengan tingkat indentasi luar mana pun" #: py/objstr.c #, c-format msgid "unknown conversion specifier %c" -msgstr "" +msgstr "spesifier konversi tidak dikenal %c" #: py/objstr.c msgid "unknown format code '%c' for object of type '%q'" -msgstr "" +msgstr "kode format tidak dikenal '%c' untuk objek bertipe '%q'" #: py/compile.c msgid "unknown type" @@ -4315,104 +4395,102 @@ msgstr "tipe tidak diketahui" #: py/compile.c msgid "unknown type '%q'" -msgstr "" +msgstr "tipe tidak dikenal '%q'" #: py/objstr.c #, c-format msgid "unmatched '%c' in format" -msgstr "" +msgstr "'%c' tidak cocok dalam format" #: py/objtype.c py/runtime.c msgid "unreadable attribute" -msgstr "" +msgstr "atribut tidak dapat dibaca" -#: shared-bindings/displayio/TileGrid.c shared-bindings/vectorio/VectorShape.c +#: shared-bindings/displayio/TileGrid.c shared-bindings/terminalio/Terminal.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-bindings/vectorio/VectorShape.c msgid "unsupported %q type" -msgstr "" +msgstr "tipe %q tidak didukung" #: py/emitinlinethumb.c #, c-format msgid "unsupported Thumb instruction '%s' with %d arguments" -msgstr "" +msgstr "instruksi Thumb tidak didukung '%s' dengan %d argumen" #: py/emitinlinextensa.c #, c-format msgid "unsupported Xtensa instruction '%s' with %d arguments" -msgstr "" +msgstr "instruksi Xtensa tidak didukung '%s' dengan %d argumen" #: shared-module/bitmapfilter/__init__.c msgid "unsupported bitmap depth" -msgstr "" +msgstr "kedalaman bitmap tidak didukung" #: shared-module/gifio/GifWriter.c msgid "unsupported colorspace for GifWriter" -msgstr "" +msgstr "colorspace tidak didukung untuk GifWriter" #: shared-bindings/bitmaptools/__init__.c msgid "unsupported colorspace for dither" -msgstr "" +msgstr "colorspace tidak didukung untuk dither" #: py/objstr.c #, c-format msgid "unsupported format character '%c' (0x%x) at index %d" -msgstr "" +msgstr "karakter format tidak didukung '%c' (0x%x) pada indeks %d" #: py/runtime.c msgid "unsupported type for %q: '%s'" -msgstr "" +msgstr "tipe tidak didukung untuk %q: '%s'" #: py/runtime.c msgid "unsupported type for operator" -msgstr "" +msgstr "tipe tidak didukung untuk operator" #: py/runtime.c msgid "unsupported types for %q: '%q', '%q'" -msgstr "" +msgstr "tipe tidak didukung untuk %q: '%q', '%q'" #: extmod/ulab/code/numpy/io/io.c msgid "usecols is too high" -msgstr "" +msgstr "usecols terlalu tinggi" #: extmod/ulab/code/numpy/io/io.c msgid "usecols keyword must be specified" -msgstr "" +msgstr "keyword usecols harus ditentukan" #: py/objint.c #, c-format msgid "value must fit in %d byte(s)" -msgstr "" +msgstr "nilai harus muat dalam %d byte" #: shared-bindings/bitmaptools/__init__.c msgid "value out of range of target" -msgstr "" +msgstr "nilai di luar jangkauan target" #: extmod/moddeflate.c msgid "wbits" -msgstr "" +msgstr "wbit" #: shared-bindings/bitmapfilter/__init__.c msgid "" "weights must be a sequence with an odd square number of elements (usually 9 " "or 25)" msgstr "" +"weights harus berupa urutan dengan jumlah persegi ganjil elemen (biasanya 9 " +"atau 25)" #: shared-bindings/bitmapfilter/__init__.c msgid "weights must be an object of type %q, %q, %q, or %q, not %q " -msgstr "" +msgstr "weights harus berupa objek bertipe %q, %q, %q, atau %q, bukan %q " #: shared-bindings/is31fl3741/FrameBuffer.c msgid "width must be greater than zero" -msgstr "" - -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/raspberrypi/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "wifi is not enabled" -msgstr "wifi tidak diaktifkan" +msgstr "lebar harus lebih besar dari nol" #: ports/raspberrypi/common-hal/wifi/Monitor.c msgid "wifi.Monitor not available" -msgstr "" +msgstr "wifi.Monitor tidak tersedia" #: shared-bindings/_bleio/Adapter.c msgid "window must be <= interval" @@ -4428,11 +4506,11 @@ msgstr "sumbu yang ditentukan salah" #: extmod/ulab/code/numpy/io/io.c msgid "wrong dtype" -msgstr "" +msgstr "dtype salah" #: extmod/ulab/code/numpy/transform.c msgid "wrong index type" -msgstr "" +msgstr "tipe indeks salah" #: extmod/ulab/code/numpy/compare.c extmod/ulab/code/numpy/create.c #: extmod/ulab/code/numpy/io/io.c extmod/ulab/code/numpy/transform.c @@ -4442,11 +4520,11 @@ msgstr "tipe input salah" #: extmod/ulab/code/numpy/transform.c msgid "wrong length of condition array" -msgstr "" +msgstr "panjang array kondisi salah" #: extmod/ulab/code/numpy/transform.c msgid "wrong length of index array" -msgstr "" +msgstr "panjang array indeks salah" #: extmod/ulab/code/numpy/create.c py/objarray.c py/objstr.c msgid "wrong number of arguments" @@ -4472,6 +4550,18 @@ msgstr "zi harus berjenis float" msgid "zi must be of shape (n_section, 2)" msgstr "Zi harus berbentuk (n_section, 2)" +#~ msgid "Unsupported format" +#~ msgstr "Format tidak didukung" + +#~ msgid "Wifi is not enabled" +#~ msgstr "Wifi tidak diaktifkan" + +#~ msgid "wifi is not enabled" +#~ msgstr "wifi tidak diaktifkan" + +#~ msgid "Cannot remount '/' when visible via USB." +#~ msgstr "Tidak dapat memasang kembali '/' saat terlihat melalui USB." + #~ msgid "%q must be a %q object, %q, or %q" #~ msgstr "%q harus berupa objek %q, %q, atau %q" @@ -4669,13 +4759,13 @@ msgstr "Zi harus berbentuk (n_section, 2)" #~ msgid "'%s' object does not support item deletion" #~ msgstr "Objek '%s' tidak mendukung penghapusan item" -#~ msgid "'%s' object is not an iterator" +#~ msgid "'%s' object isn't an iterator" #~ msgstr "Objek '%s' bukan iterator" #~ msgid "'%s' object is not callable" #~ msgstr "Objek '%s' tidak dapat dipanggil" -#~ msgid "'%s' object is not iterable" +#~ msgid "'%s' object isn't iterable" #~ msgstr "'%s' objek tidak dapat diulang" #~ msgid "'%s' object is not subscriptable" @@ -5485,7 +5575,7 @@ msgstr "Zi harus berbentuk (n_section, 2)" #~ msgid "frequency can only be either 80Mhz or 160MHz" #~ msgstr "frekuensi hanya bisa didefinisikan 80Mhz atau 160Mhz" -#~ msgid "function does not take keyword arguments" +#~ msgid "function doesn't take keyword arguments" #~ msgstr "fungsi tidak dapat mengambil argumen keyword" #~ msgid "impossible baudrate" @@ -5540,7 +5630,7 @@ msgstr "Zi harus berbentuk (n_section, 2)" #~ msgid "name must be a string" #~ msgstr "keyword harus berupa string" -#~ msgid "name reused for argument" +#~ msgid "argument name reused" #~ msgstr "nama digunakan kembali untuk argumen" #~ msgid "non-keyword arg after */**" diff --git a/locale/circuitpython.pot b/locale/circuitpython.pot index 167fb20ff9e..eba81297747 100644 --- a/locale/circuitpython.pot +++ b/locale/circuitpython.pot @@ -16,1050 +16,1639 @@ msgstr "" "Content-Type: text/plain; charset=CHARSET\n" "Content-Transfer-Encoding: 8bit\n" -#: main.c -msgid "" -"\n" -"Code done running.\n" +#: extmod/modasyncio.c extmod/modheapq.c +msgid "empty heap" msgstr "" -#: main.c -msgid "" -"\n" -"Code stopped by auto-reload. Reloading soon.\n" +#: extmod/modasyncio.c +msgid "can't cancel self" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "" -"\n" -"Please file an issue with your program at github.com/adafruit/circuitpython/" -"issues." +#: extmod/modasyncio.c +msgid "can't wait" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "" -"\n" -"Press reset to exit safe mode.\n" +#: extmod/modbinascii.c extmod/modhashlib.c py/objarray.c +msgid "a bytes-like object is required" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "" -"\n" -"You are in safe mode because:\n" +#: extmod/modbinascii.c +msgid "incorrect padding" msgstr "" -#: py/obj.c -msgid " File \"%q\"" +#: extmod/moddeflate.c +msgid "format" msgstr "" -#: py/obj.c -msgid " File \"%q\", line %d" +#: extmod/moddeflate.c +msgid "wbits" msgstr "" -#: py/builtinhelp.c -msgid " is of type %q\n" +#: extmod/modhashlib.c +msgid "hash is final" msgstr "" -#: main.c -msgid " not found.\n" +#: extmod/modheapq.c +msgid "heap must be a list" msgstr "" -#: main.c -msgid " output:\n" +#: extmod/modjson.c +msgid "syntax error in JSON" msgstr "" -#: py/objstr.c -#, c-format -msgid "%%c requires int or char" +#: extmod/modrandom.c +msgid "bits must be 32 or less" msgstr "" -#: shared-bindings/rgbmatrix/RGBMatrix.c -#, c-format -msgid "" -"%d address pins, %d rgb pins and %d tiles indicate a height of %d, not %d" +#: extmod/modrandom.c extmod/ulab/code/numpy/random/random.c +msgid "no default seed" msgstr "" -#: shared-bindings/microcontroller/Pin.c -msgid "%q and %q contain duplicate pins" +#: extmod/modre.c +msgid "splitting with sub-captures" msgstr "" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c -msgid "%q and %q must be different" +#: extmod/modre.c +msgid "regex too complex" msgstr "" -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -msgid "%q and %q must share a clock unit" +#: extmod/modre.c +msgid "Error in regex" msgstr "" -#: ports/nordic/common-hal/watchdog/WatchDogTimer.c -msgid "%q cannot be changed once mode is set to %q" +#: extmod/modtime.c +msgid "mktime needs a tuple of length 8 or 9" msgstr "" -#: shared-bindings/microcontroller/Pin.c -msgid "%q contains duplicate pins" +#: extmod/modtime.c +msgid "ticks interval overflow" msgstr "" -#: ports/atmel-samd/common-hal/sdioio/SDCard.c -msgid "%q failure: %d" +#: extmod/modzlib.c +msgid "compression header" msgstr "" -#: py/argcheck.c shared-module/audiofilters/Filter.c -msgid "%q in %q must be of type %q, not %q" +#: extmod/ulab/code/ndarray.c +msgid "data type not understood" msgstr "" -#: ports/espressif/common-hal/espulp/ULP.c -#: ports/mimxrt10xx/common-hal/audiobusio/__init__.c -#: ports/mimxrt10xx/common-hal/usb_host/Port.c -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -#: ports/raspberrypi/common-hal/usb_host/Port.c -#: shared-bindings/digitalio/DigitalInOut.c -#: shared-bindings/microcontroller/Pin.c shared-module/max3421e/Max3421E.c -msgid "%q in use" +#: extmod/ulab/code/ndarray.c +msgid "array is too big" msgstr "" -#: py/objstr.c -msgid "%q index out of range" +#: extmod/ulab/code/ndarray.c +msgid "ndarray length overflows" msgstr "" -#: py/obj.c -msgid "%q indices must be integers, not %s" +#: extmod/ulab/code/ndarray.c +msgid "maximum number of dimensions is " msgstr "" -#: shared-module/bitbangio/SPI.c -msgid "%q init failed" +#: extmod/ulab/code/ndarray.c +msgid "cannot convert complex type" msgstr "" -#: ports/espressif/bindings/espnow/Peer.c shared-bindings/dualbank/__init__.c -msgid "%q is %q" +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/create.c +msgid "too many dimensions" msgstr "" -#: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "%q is read-only for this board" +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/transform.c +msgid "index is out of bounds" msgstr "" -#: py/argcheck.c shared-bindings/usb_hid/Device.c -msgid "%q length must be %d" +#: extmod/ulab/code/ndarray.c +msgid "indices must be integers, slices, or Boolean lists" msgstr "" -#: py/argcheck.c -msgid "%q length must be %d-%d" +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/bitwise.c +#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/numpy/vector.c +msgid "operands could not be broadcast together" msgstr "" -#: py/argcheck.c -msgid "%q length must be <= %d" +#: extmod/ulab/code/ndarray.c +msgid "array and index length must be equal" msgstr "" -#: py/argcheck.c -msgid "%q length must be >= %d" +#: extmod/ulab/code/ndarray.c +msgid "cannot convert complex to dtype" msgstr "" -#: py/modsys.c py/objmodule.c py/runtime.c -msgid "%q moved from %q to %q" +#: extmod/ulab/code/ndarray.c +msgid "operation is implemented for 1D Boolean arrays only" msgstr "" -#: py/argcheck.c -msgid "%q must be %d" +#: extmod/ulab/code/ndarray.c +msgid "too many indices" msgstr "" -#: py/argcheck.c shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/displayio/Bitmap.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -#: shared-bindings/is31fl3741/FrameBuffer.c -#: shared-bindings/rgbmatrix/RGBMatrix.c -msgid "%q must be %d-%d" +#: extmod/ulab/code/ndarray.c +msgid "cannot delete array elements" msgstr "" -#: shared-bindings/busdisplay/BusDisplay.c -msgid "%q must be 1 when %q is True" +#: extmod/ulab/code/ndarray.c +msgid "flattening order must be either 'C', or 'F'" msgstr "" -#: py/argcheck.c shared-bindings/gifio/GifWriter.c -#: shared-module/gifio/OnDiskGif.c -msgid "%q must be <= %d" +#: extmod/ulab/code/ndarray.c +msgid "tobytes can be invoked for dense arrays only" msgstr "" -#: ports/espressif/common-hal/watchdog/WatchDogTimer.c -msgid "%q must be <= %u" +#: extmod/ulab/code/ndarray.c +msgid "operation is not supported for given type" msgstr "" -#: py/argcheck.c -msgid "%q must be >= %d" +#: extmod/ulab/code/ndarray.c +msgid "keyword argument must be tuple of integers" msgstr "" -#: shared-bindings/analogbufio/BufferedIn.c -msgid "%q must be a bytearray or array of type 'H' or 'B'" +#: extmod/ulab/code/ndarray.c +msgid "too many axes specified" msgstr "" -#: shared-bindings/audiocore/RawSample.c -msgid "%q must be a bytearray or array of type 'h', 'H', 'b', or 'B'" +#: extmod/ulab/code/ndarray.c +msgid "axis index out of bounds" msgstr "" -#: shared-bindings/warnings/__init__.c -msgid "%q must be a subclass of %q" +#: extmod/ulab/code/ndarray.c +msgid "repeated indices" msgstr "" -#: ports/espressif/common-hal/analogbufio/BufferedIn.c -msgid "%q must be array of type 'H'" +#: extmod/ulab/code/ndarray.c +msgid "shape must be integer or tuple of integers" msgstr "" -#: shared-module/synthio/__init__.c -msgid "%q must be array of type 'h'" +#: extmod/ulab/code/ndarray.c +msgid "can only specify one unknown dimension" msgstr "" -#: shared-bindings/audiobusio/PDMIn.c -msgid "%q must be multiple of 8." +#: extmod/ulab/code/ndarray.c +msgid "cannot reshape array" msgstr "" -#: ports/raspberrypi/bindings/cyw43/__init__.c py/argcheck.c py/objexcept.c -#: shared-bindings/bitmapfilter/__init__.c shared-bindings/canio/CAN.c -#: shared-bindings/digitalio/Pull.c shared-bindings/supervisor/__init__.c -#: shared-module/audiofilters/Filter.c shared-module/displayio/__init__.c -#: shared-module/synthio/Biquad.c shared-module/synthio/Synthesizer.c -msgid "%q must be of type %q or %q, not %q" +#: extmod/ulab/code/ndarray.c +msgid "cannot assign new shape" msgstr "" -#: shared-bindings/jpegio/JpegDecoder.c -msgid "%q must be of type %q, %q, or %q, not %q" +#: extmod/ulab/code/ndarray.c +msgid "function is defined for ndarrays only" msgstr "" -#: py/argcheck.c py/runtime.c shared-bindings/bitmapfilter/__init__.c -#: shared-module/synthio/__init__.c -msgid "%q must be of type %q, not %q" +#: extmod/ulab/code/ndarray_operators.c +msgid "operation not supported for the input types" msgstr "" -#: ports/atmel-samd/common-hal/busio/UART.c -msgid "%q must be power of 2" +#: extmod/ulab/code/ndarray_operators.c +msgid "dtype of int32 is not supported" msgstr "" -#: shared-bindings/wifi/Monitor.c -msgid "%q out of bounds" +#: extmod/ulab/code/ndarray_operators.c +msgid "cannot cast output with casting rule" msgstr "" -#: ports/atmel-samd/common-hal/pulseio/PulseIn.c -#: ports/cxd56/common-hal/pulseio/PulseIn.c -#: ports/nordic/common-hal/pulseio/PulseIn.c -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -#: ports/stm/common-hal/pulseio/PulseIn.c py/argcheck.c -#: shared-bindings/canio/Match.c shared-bindings/time/__init__.c -msgid "%q out of range" +#: extmod/ulab/code/ndarray_operators.c +msgid "results cannot be cast to specified type" msgstr "" -#: py/objmodule.c py/runtime.c -msgid "%q renamed %q" +#: extmod/ulab/code/numpy/approx.c +msgid "interp is defined for 1D iterables of equal length" msgstr "" -#: py/objrange.c py/objslice.c shared-bindings/random/__init__.c -msgid "%q step cannot be zero" +#: extmod/ulab/code/numpy/approx.c +msgid "trapz is defined for 1D iterables" msgstr "" -#: shared-module/bitbangio/I2C.c -msgid "%q too long" +#: extmod/ulab/code/numpy/approx.c +msgid "trapz is defined for 1D arrays of equal length" msgstr "" -#: py/bc.c py/objnamedtuple.c -msgid "%q() takes %d positional arguments but %d were given" +#: extmod/ulab/code/numpy/bitwise.c +msgid "not supported for input types" msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "%q() without %q()" +#: extmod/ulab/code/numpy/carray/carray.c +msgid "function is implemented for ndarrays only" msgstr "" -#: shared-bindings/usb_hid/Device.c -msgid "%q, %q, and %q must all be the same length" +#: extmod/ulab/code/numpy/carray/carray.c +msgid "input must be an ndarray, or a scalar" msgstr "" -#: py/objint.c shared-bindings/_bleio/Connection.c -#: shared-bindings/storage/__init__.c -msgid "%q=%q" +#: extmod/ulab/code/numpy/carray/carray.c +msgid "input must be a 1D ndarray" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "%q[%u] shifts in more bits than pin count" +#: extmod/ulab/code/numpy/carray/carray_tools.c +msgid "not implemented for complex dtype" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "%q[%u] shifts out more bits than pin count" +#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/user/user.c +#: shared-bindings/_eve/__init__.c +msgid "input must be an ndarray" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "%q[%u] uses extra pin" +#: extmod/ulab/code/numpy/compare.c +msgid "object too deep for desired array" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "%q[%u] waits on input outside of count" +#: extmod/ulab/code/numpy/compare.c +msgid "cannot cast array data from dtype" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -#, c-format -msgid "%s error 0x%x" +#: extmod/ulab/code/numpy/compare.c +msgid "minlength must not be negative" msgstr "" -#: py/argcheck.c -msgid "'%q' argument required" +#: extmod/ulab/code/numpy/compare.c +msgid "the weights and list don't have the same length" msgstr "" -#: py/proto.c -msgid "'%q' object does not support '%q'" +#: extmod/ulab/code/numpy/compare.c +msgid "cannot cast weigths to float" msgstr "" -#: py/runtime.c -msgid "'%q' object is not an iterator" -msgstr "" - -#: py/objtype.c py/runtime.c shared-module/atexit/__init__.c -msgid "'%q' object is not callable" +#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/numpy/create.c +#: extmod/ulab/code/numpy/io/io.c extmod/ulab/code/numpy/transform.c +#: extmod/ulab/code/numpy/vector.c +msgid "wrong input type" msgstr "" -#: py/runtime.c -msgid "'%q' object is not iterable" +#: extmod/ulab/code/numpy/create.c +msgid "input argument must be an integer, a tuple, or a list" msgstr "" -#: py/emitinlinethumb.c py/emitinlinextensa.c -#, c-format -msgid "'%s' expects a label" +#: extmod/ulab/code/numpy/create.c py/objarray.c py/objstr.c +msgid "wrong number of arguments" msgstr "" -#: py/emitinlinethumb.c py/emitinlinextensa.c -#, c-format -msgid "'%s' expects a register" +#: extmod/ulab/code/numpy/create.c py/objint_longlong.c py/objint_mpz.c +msgid "divide by zero" msgstr "" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects a special register" +#: extmod/ulab/code/numpy/create.c +msgid "arange: cannot compute length" msgstr "" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects an FPU register" +#: extmod/ulab/code/numpy/create.c +msgid "first argument must be a tuple of ndarrays" msgstr "" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects an address of the form [a, b]" +#: extmod/ulab/code/numpy/create.c +msgid "only ndarrays can be concatenated" msgstr "" -#: py/emitinlinethumb.c py/emitinlinextensa.c -#, c-format -msgid "'%s' expects an integer" +#: extmod/ulab/code/numpy/create.c +msgid "wrong axis specified" msgstr "" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects at most r%d" +#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c +msgid "input arrays are not compatible" msgstr "" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects {r0, r1, ...}" +#: extmod/ulab/code/numpy/create.c +msgid "input must be 1- or 2-d" msgstr "" -#: py/emitinlinextensa.c -#, c-format -msgid "'%s' integer %d isn't within range %d..%d" +#: extmod/ulab/code/numpy/create.c +msgid "number of points must be at least 2" msgstr "" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' integer 0x%x doesn't fit in mask 0x%x" +#: extmod/ulab/code/numpy/create.c +msgid "indexing should be 'xy' or 'ij'" msgstr "" -#: py/obj.c -#, c-format -msgid "'%s' object doesn't support item assignment" +#: extmod/ulab/code/numpy/create.c +msgid "indexing must be 'xy' or 'ij'" msgstr "" -#: py/obj.c -#, c-format -msgid "'%s' object doesn't support item deletion" +#: extmod/ulab/code/numpy/create.c +msgid "too many input arrays" msgstr "" -#: py/runtime.c -msgid "'%s' object has no attribute '%q'" +#: extmod/ulab/code/numpy/create.c extmod/ulab/code/numpy/numerical.c +#: extmod/ulab/code/numpy/transform.c +msgid "arguments must be ndarrays" msgstr "" -#: py/obj.c -#, c-format -msgid "'%s' object isn't subscriptable" +#: extmod/ulab/code/numpy/create.c +msgid "arguments must be 1D arrays" msgstr "" -#: py/objstr.c -msgid "'=' alignment not allowed in string format specifier" +#: extmod/ulab/code/numpy/create.c +msgid "input is not an array" msgstr "" -#: shared-module/struct/__init__.c -msgid "'S' and 'O' are not supported format types" +#: extmod/ulab/code/numpy/create.c extmod/ulab/code/numpy/numerical.c +#: ports/espressif/common-hal/pulseio/PulseIn.c +#: shared-bindings/bitmaptools/__init__.c +msgid "index out of range" msgstr "" -#: py/compile.c -msgid "'align' requires 1 argument" +#: extmod/ulab/code/numpy/create.c +msgid "mode should be raise, wrap or clip" msgstr "" -#: py/compile.c -msgid "'await' outside function" +#: extmod/ulab/code/numpy/create.c +msgid "index must not be negative" msgstr "" -#: py/compile.c -msgid "'break'/'continue' outside loop" +#: extmod/ulab/code/numpy/create.c +msgid "offset must be non-negative and no greater than buffer length" msgstr "" -#: py/compile.c -msgid "'data' requires at least 2 arguments" +#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c +msgid "buffer size must be a multiple of element size" msgstr "" -#: py/compile.c -msgid "'data' requires integer arguments" +#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c +msgid "buffer is smaller than requested size" msgstr "" -#: py/compile.c -msgid "'label' requires 1 argument" +#: extmod/ulab/code/numpy/fft/fft_tools.c +msgid "FFT is defined for ndarrays only" msgstr "" -#: py/emitnative.c -msgid "'not' not implemented" +#: extmod/ulab/code/numpy/fft/fft_tools.c +msgid "FFT is implemented for linear arrays only" msgstr "" -#: py/compile.c -msgid "'return' outside function" +#: extmod/ulab/code/numpy/fft/fft_tools.c extmod/ulab/code/utils/utils.c +msgid "input array length must be power of 2" msgstr "" -#: py/compile.c -msgid "'yield from' inside async function" +#: extmod/ulab/code/numpy/fft/fft_tools.c +msgid "real and imaginary parts must be of equal length" msgstr "" -#: py/compile.c -msgid "'yield' outside function" +#: extmod/ulab/code/numpy/filter.c +msgid "convolve arguments must be ndarrays" msgstr "" -#: py/compile.c -msgid "* arg after **" +#: extmod/ulab/code/numpy/filter.c +msgid "convolve arguments must be linear arrays" msgstr "" -#: py/compile.c -msgid "*x must be assignment target" +#: extmod/ulab/code/numpy/filter.c +msgid "convolve arguments must not be empty" msgstr "" -#: py/obj.c -msgid ", in %q\n" +#: extmod/ulab/code/numpy/io/io.c +msgid "corrupted file" msgstr "" -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/epaperdisplay/EPaperDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -msgid ".show(x) removed. Use .root_group = x" +#: extmod/ulab/code/numpy/io/io.c +msgid "wrong dtype" msgstr "" -#: py/objcomplex.c -msgid "0.0 to a complex power" +#: extmod/ulab/code/numpy/io/io.c +msgid "usecols keyword must be specified" msgstr "" -#: py/modbuiltins.c -msgid "3-arg pow() not supported" +#: extmod/ulab/code/numpy/io/io.c +msgid "empty file" msgstr "" -#: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "AP could not be started" +#: extmod/ulab/code/numpy/io/io.c +msgid "usecols is too high" msgstr "" -#: shared-bindings/_bleio/Address.c shared-bindings/ipaddress/IPv4Address.c -#, c-format -msgid "Address must be %d bytes long" +#: extmod/ulab/code/numpy/io/io.c +msgid "array has too many dimensions" msgstr "" -#: ports/espressif/common-hal/memorymap/AddressRange.c -#: ports/nordic/common-hal/memorymap/AddressRange.c -#: ports/raspberrypi/common-hal/memorymap/AddressRange.c -msgid "Address range not allowed" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "input matrix is asymmetric" msgstr "" -#: shared-bindings/memorymap/AddressRange.c -msgid "Address range wraps around" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "matrix is not positive definite" msgstr "" -#: ports/espressif/common-hal/canio/CAN.c -msgid "All CAN peripherals are in use" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "iterations did not converge" msgstr "" -#: ports/espressif/common-hal/busio/I2C.c -#: ports/espressif/common-hal/i2ctarget/I2CTarget.c -#: ports/nordic/common-hal/busio/I2C.c -msgid "All I2C peripherals are in use" +#: extmod/ulab/code/numpy/linalg/linalg.c +#: extmod/ulab/code/scipy/linalg/linalg.c +msgid "input matrix is singular" msgstr "" -#: ports/atmel-samd/common-hal/canio/Listener.c -#: ports/espressif/common-hal/canio/Listener.c -#: ports/stm/common-hal/canio/Listener.c -msgid "All RX FIFOs in use" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "operation is defined for ndarrays only" msgstr "" -#: ports/espressif/common-hal/busio/SPI.c ports/nordic/common-hal/busio/SPI.c -msgid "All SPI peripherals are in use" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "operation is defined for 2D arrays only" msgstr "" -#: ports/espressif/common-hal/busio/UART.c ports/nordic/common-hal/busio/UART.c -msgid "All UART peripherals are in use" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "mode must be complete, or reduced" msgstr "" -#: ports/nordic/common-hal/countio/Counter.c -#: ports/nordic/common-hal/pulseio/PulseIn.c -#: ports/nordic/common-hal/rotaryio/IncrementalEncoder.c -msgid "All channels in use" +#: extmod/ulab/code/numpy/numerical.c +msgid "attempt to get argmin/argmax of an empty sequence" msgstr "" -#: ports/raspberrypi/common-hal/usb_host/Port.c -msgid "All dma channels in use" +#: extmod/ulab/code/numpy/numerical.c +msgid "attempt to get (arg)min/(arg)max of empty sequence" msgstr "" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c -msgid "All event channels in use" +#: extmod/ulab/code/numpy/numerical.c extmod/ulab/code/ulab_tools.c +msgid "axis must be None, or an integer" msgstr "" -#: ports/raspberrypi/common-hal/floppyio/__init__.c -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -#: ports/raspberrypi/common-hal/usb_host/Port.c -msgid "All state machines in use" +#: extmod/ulab/code/numpy/numerical.c +msgid "operation is not implemented on ndarrays" msgstr "" -#: ports/atmel-samd/audio_dma.c -msgid "All sync event channels in use" +#: extmod/ulab/code/numpy/numerical.c +msgid "input must be tuple, list, range, or ndarray" msgstr "" -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c -msgid "All timers for this pin are in use" +#: extmod/ulab/code/numpy/numerical.c +msgid "sort argument must be an ndarray" msgstr "" -#: ports/atmel-samd/common-hal/_pew/PewPew.c -#: ports/atmel-samd/common-hal/audioio/AudioOut.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/nordic/common-hal/audiopwmio/PWMAudioOut.c -#: ports/nordic/common-hal/pulseio/PulseIn.c -#: ports/nordic/peripherals/nrf/timers.c -#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c -msgid "All timers in use" +#: extmod/ulab/code/numpy/numerical.c +msgid "argsort argument must be an ndarray" msgstr "" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Already advertising." +#: extmod/ulab/code/numpy/numerical.c +msgid "argsort is not implemented for flattened arrays" msgstr "" -#: ports/atmel-samd/common-hal/canio/Listener.c -msgid "Already have all-matches listener" +#: extmod/ulab/code/numpy/numerical.c +msgid "axis too long" msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -msgid "Already in progress" +#: extmod/ulab/code/numpy/numerical.c +msgid "cross is defined for 1D arrays of length 3" msgstr "" -#: ports/espressif/bindings/espnow/ESPNow.c -#: ports/espressif/common-hal/espulp/ULP.c -#: shared-module/memorymonitor/AllocationAlarm.c -#: shared-module/memorymonitor/AllocationSize.c -msgid "Already running" +#: extmod/ulab/code/numpy/numerical.c +msgid "diff argument must be an ndarray" msgstr "" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/raspberrypi/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "Already scanning for wifi networks" +#: extmod/ulab/code/numpy/numerical.c +msgid "differentiation order out of range" msgstr "" -#: shared-module/os/getenv.c -#, c-format -msgid "An error occurred while retrieving '%s':\n" +#: extmod/ulab/code/numpy/numerical.c +msgid "flip argument must be an ndarray" msgstr "" -#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c -msgid "Another PWMAudioOut is already active" +#: extmod/ulab/code/numpy/numerical.c +msgid "wrong axis index" msgstr "" -#: ports/atmel-samd/common-hal/pulseio/PulseOut.c -#: ports/cxd56/common-hal/pulseio/PulseOut.c -msgid "Another send is already active" +#: extmod/ulab/code/numpy/numerical.c +msgid "median argument must be an ndarray" msgstr "" -#: shared-bindings/pulseio/PulseOut.c -msgid "Array must contain halfwords (type 'H')" +#: extmod/ulab/code/numpy/numerical.c +msgid "roll argument must be an ndarray" msgstr "" -#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c -#: shared-bindings/nvm/ByteArray.c -msgid "Array values should be single bytes." +#: extmod/ulab/code/numpy/poly.c +msgid "input data must be an iterable" msgstr "" -#: ports/atmel-samd/common-hal/spitarget/SPITarget.c -msgid "Async SPI transfer in progress on this bus, keep awaiting." +#: extmod/ulab/code/numpy/poly.c +msgid "more degrees of freedom than data points" msgstr "" -#: shared-module/memorymonitor/AllocationAlarm.c -#, c-format -msgid "Attempt to allocate %d blocks" +#: extmod/ulab/code/numpy/poly.c +msgid "input vectors must be of equal length" msgstr "" -#: ports/raspberrypi/audio_dma.c -msgid "Audio conversion not implemented" +#: extmod/ulab/code/numpy/poly.c +msgid "could not invert Vandermonde matrix" msgstr "" -#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c -#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c -msgid "Audio source error" +#: extmod/ulab/code/numpy/poly.c +msgid "input is not iterable" msgstr "" -#: shared-bindings/wifi/Radio.c -msgid "AuthMode.OPEN is not used with password" +#: extmod/ulab/code/numpy/random/random.c +msgid "argument must be None, an integer or a tuple of integers" msgstr "" -#: shared-bindings/wifi/Radio.c supervisor/shared/web_workflow/web_workflow.c -msgid "Authentication failure" +#: extmod/ulab/code/numpy/random/random.c +msgid "shape must be None, an integer or a tuple of integers" msgstr "" -#: main.c -msgid "Auto-reload is off.\n" +#: extmod/ulab/code/numpy/random/random.c extmod/ulab/code/ulab_tools.c +msgid "out has wrong type" msgstr "" -#: main.c -msgid "" -"Auto-reload is on. Simply save files over USB to run them or enter REPL to " -"disable.\n" +#: extmod/ulab/code/numpy/random/random.c +msgid "output array has wrong type" msgstr "" -#: ports/espressif/common-hal/canio/CAN.c -msgid "Baudrate not supported by peripheral" +#: extmod/ulab/code/numpy/random/random.c +msgid "size must match out.shape when used together" msgstr "" -#: shared-module/busdisplay/BusDisplay.c -#: shared-module/framebufferio/FramebufferDisplay.c -msgid "Below minimum frame rate" +#: extmod/ulab/code/numpy/random/random.c extmod/ulab/code/ulab_tools.c +msgid "output array must be contiguous" msgstr "" -#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c -msgid "Bit clock and word select must be sequential GPIO pins" +#: extmod/ulab/code/numpy/transform.c +msgid "wrong length of condition array" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "Bitmap size and bits per value must match" +#: extmod/ulab/code/numpy/transform.c extmod/ulab/code/numpy/vector.c +msgid "first argument must be an ndarray" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Boot device must be first (interface #0)." +#: extmod/ulab/code/numpy/transform.c +msgid "wrong index type" msgstr "" -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Both RX and TX required for flow control" +#: extmod/ulab/code/numpy/transform.c +msgid "wrong length of index array" msgstr "" -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -msgid "Brightness not adjustable" +#: extmod/ulab/code/numpy/transform.c +msgid "dimensions do not match" msgstr "" -#: shared-bindings/_bleio/UUID.c -#, c-format -msgid "Buffer + offset too small %d %d %d" +#: extmod/ulab/code/numpy/vector.c extmod/ulab/code/utils/utils.c +msgid "out must be an ndarray" msgstr "" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "Buffer elements must be 4 bytes long or less" +#: extmod/ulab/code/numpy/vector.c +msgid "out must be of float dtype" msgstr "" -#: shared-bindings/framebufferio/FramebufferDisplay.c -msgid "Buffer is not a bytearray." +#: extmod/ulab/code/numpy/vector.c +msgid "input and output dimensions differ" msgstr "" -#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c -#, c-format -msgid "Buffer length %d too big. It must be less than %d" +#: extmod/ulab/code/numpy/vector.c +msgid "input and output shapes differ" msgstr "" -#: ports/atmel-samd/common-hal/sdioio/SDCard.c -#: ports/cxd56/common-hal/sdioio/SDCard.c -#: ports/espressif/common-hal/sdioio/SDCard.c -#: ports/stm/common-hal/sdioio/SDCard.c shared-bindings/floppyio/__init__.c -#: shared-module/sdcardio/SDCard.c -#, c-format -msgid "Buffer must be a multiple of %d bytes" +#: extmod/ulab/code/numpy/vector.c +msgid "out keyword is not supported for function" msgstr "" -#: shared-bindings/_bleio/PacketBuffer.c -#, c-format -msgid "Buffer too short by %d bytes" +#: extmod/ulab/code/numpy/vector.c +msgid "out keyword is not supported for complex dtype" msgstr "" -#: ports/cxd56/common-hal/camera/Camera.c -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -#: shared-bindings/struct/__init__.c shared-module/struct/__init__.c -msgid "Buffer too small" +#: extmod/ulab/code/numpy/vector.c +msgid "dtype must be float, or complex" msgstr "" -#: ports/atmel-samd/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/nordic/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/raspberrypi/common-hal/paralleldisplaybus/ParallelBus.c -#, c-format -msgid "Bus pin %d is already in use" +#: extmod/ulab/code/numpy/vector.c +msgid "can't convert complex to float" msgstr "" -#: shared-bindings/_bleio/UUID.c -msgid "Byte buffer must be 16 bytes." +#: extmod/ulab/code/numpy/vector.c +msgid "input dtype must be float or complex" msgstr "" -#: shared-bindings/aesio/aes.c -msgid "CBC blocks must be multiples of 16 bytes" +#: extmod/ulab/code/numpy/vector.c extmod/ulab/code/scipy/integrate/integrate.c +msgid "first argument must be a callable" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "CIRCUITPY drive could not be found or created." +#: extmod/ulab/code/numpy/vector.c +msgid "wrong output type" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "CRC or checksum was invalid" +#: extmod/ulab/code/scipy/integrate/integrate.c +#, c-format +msgid "can't convert arg %d from %s to float" msgstr "" -#: py/objtype.c -msgid "Call super().__init__() before accessing native object." +#: extmod/ulab/code/scipy/integrate/integrate.c +msgid "levels needs to be a positive integer" msgstr "" -#: ports/cxd56/common-hal/camera/Camera.c -msgid "Camera init" +#: extmod/ulab/code/scipy/integrate/integrate.c +msgid "steps needs to be a positive integer" msgstr "" -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Can only alarm on RTC IO from deep sleep." +#: extmod/ulab/code/scipy/integrate/integrate.c +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "first argument must be a function" msgstr "" -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Can only alarm on one low pin while others alarm high from deep sleep." +#: extmod/ulab/code/scipy/integrate/integrate.c +msgid "order needs to be a positive integer" msgstr "" -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Can only alarm on two low pins from deep sleep." +#: extmod/ulab/code/scipy/linalg/linalg.c +msgid "first two arguments must be ndarrays" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Can't construct AudioOut because continuous channel already open" +#: extmod/ulab/code/scipy/linalg/linalg.c extmod/ulab/code/user/user.c +msgid "input must be a dense ndarray" msgstr "" -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Characteristic.c -msgid "Can't set CCCD on local Characteristic" +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "function has the same sign at the ends of interval" msgstr "" -#: shared-bindings/storage/__init__.c shared-bindings/usb_cdc/__init__.c -#: shared-bindings/usb_hid/__init__.c shared-bindings/usb_midi/__init__.c -#: shared-bindings/usb_video/__init__.c -msgid "Cannot change USB devices now" +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "maxiter should be > 0" msgstr "" -#: shared-bindings/_bleio/Adapter.c -msgid "Cannot create a new Adapter; use _bleio.adapter;" +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "maxiter must be > 0" msgstr "" -#: shared-bindings/displayio/Bitmap.c -#: shared-bindings/memorymonitor/AllocationSize.c -#: shared-bindings/pulseio/PulseIn.c -msgid "Cannot delete values" +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "data must be iterable" msgstr "" -#: ports/atmel-samd/common-hal/digitalio/DigitalInOut.c -#: ports/mimxrt10xx/common-hal/digitalio/DigitalInOut.c -#: ports/nordic/common-hal/digitalio/DigitalInOut.c -#: ports/raspberrypi/common-hal/digitalio/DigitalInOut.c -msgid "Cannot get pull while in output mode" +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "initial values must be iterable" msgstr "" -#: ports/nordic/common-hal/microcontroller/Processor.c -msgid "Cannot get temperature" +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "data must be of equal length" msgstr "" -#: shared-bindings/_bleio/Adapter.c -msgid "Cannot have scan responses for extended, connectable advertisements." +#: extmod/ulab/code/scipy/signal/signal.c +msgid "sosfilt requires iterable arguments" msgstr "" -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Cannot pull on input-only pin." +#: extmod/ulab/code/scipy/signal/signal.c +msgid "input must be one-dimensional" msgstr "" -#: shared-bindings/audiobusio/PDMIn.c -msgid "Cannot record to a file" +#: extmod/ulab/code/scipy/signal/signal.c +msgid "zi must be an ndarray" msgstr "" -#: shared-module/storage/__init__.c -msgid "Cannot remount '/' when visible via USB." +#: extmod/ulab/code/scipy/signal/signal.c +msgid "zi must be of shape (n_section, 2)" msgstr "" -#: shared-bindings/digitalio/DigitalInOut.c -msgid "Cannot set value when direction is input." +#: extmod/ulab/code/scipy/signal/signal.c +msgid "zi must be of float type" msgstr "" -#: ports/espressif/common-hal/busio/UART.c -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Cannot specify RTS or CTS in RS485 mode" +#: extmod/ulab/code/scipy/signal/signal.c +msgid "sos array must be of shape (n_section, 6)" msgstr "" -#: py/objslice.c -msgid "Cannot subclass slice" +#: extmod/ulab/code/scipy/signal/signal.c +msgid "sos[:, 3] should be all ones" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Cannot use GPIO0..15 together with GPIO32..47" +#: extmod/ulab/code/ulab_tools.c +msgid "axis is out of bounds" msgstr "" -#: ports/nordic/common-hal/alarm/pin/PinAlarm.c -msgid "Cannot wake on pin edge, only level" +#: extmod/ulab/code/ulab_tools.c +msgid "size is defined for ndarrays only" msgstr "" -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Cannot wake on pin edge. Only level." +#: extmod/ulab/code/ulab_tools.c +msgid "input must be square matrix" msgstr "" -#: shared-bindings/_bleio/CharacteristicBuffer.c -msgid "CharacteristicBuffer writing not provided" +#: extmod/ulab/code/ulab_tools.c +msgid "out array has wrong dtype" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "CircuitPython core code crashed hard. Whoops!\n" +#: extmod/ulab/code/ulab_tools.c +msgid "out array has wrong dimension" msgstr "" -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -msgid "Clock unit in use" +#: extmod/ulab/code/ulab_tools.c +msgid "out array has wrong shape" msgstr "" -#: shared-bindings/_bleio/Connection.c -msgid "" -"Connection has been disconnected and can no longer be used. Create a new " -"connection." +#: extmod/ulab/code/utils/utils.c +msgid "out must be a float dense array" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "Coordinate arrays have different lengths" +#: extmod/ulab/code/utils/utils.c +msgid "offset is too large" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "Coordinate arrays types have different sizes" +#: extmod/ulab/code/utils/utils.c +msgid "out array is too small" msgstr "" -#: shared-bindings/_bleio/Adapter.c -msgid "Could not set address" +#: extmod/ulab/code/utils/utils.c +msgid "spectrogram is defined for ndarrays only" msgstr "" -#: ports/stm/common-hal/busio/UART.c -msgid "Could not start interrupt, RX busy" +#: extmod/ulab/code/utils/utils.c +msgid "spectrogram is implemented for 1D arrays only" msgstr "" -#: shared-module/audiomp3/MP3Decoder.c -msgid "Couldn't allocate decoder" +#: extmod/ulab/code/utils/utils.c +msgid "out array must be a 1D array of float type" msgstr "" -#: ports/stm/common-hal/analogio/AnalogOut.c -msgid "DAC Channel Init Error" +#: extmod/ulab/code/utils/utils.c +msgid "input and out arrays must have same length" +msgstr "" + +#: extmod/ulab/code/utils/utils.c +msgid "scratchpad must be an ndarray" +msgstr "" + +#: extmod/ulab/code/utils/utils.c +msgid "scratchpad must be a 1D dense float array" +msgstr "" + +#: extmod/ulab/code/utils/utils.c +msgid "scratchpad must be twice as long as input" +msgstr "" + +#: extmod/vfs_fat.c py/moderrno.c +msgid "Read-only filesystem" +msgstr "" + +#: extmod/vfs_posix_file.c py/objstringio.c +msgid "I/O operation on closed file" +msgstr "" + +#: extmod/vfs_posix_file.c +msgid "poll on file not available on win32" +msgstr "" + +#: main.c +msgid "Done" +msgstr "" + +#: main.c +msgid " output:\n" +msgstr "" + +#: main.c +msgid "" +"Auto-reload is on. Simply save files over USB to run them or enter REPL to " +"disable.\n" +msgstr "" + +#: main.c +msgid "Auto-reload is off.\n" +msgstr "" + +#: main.c +msgid "Running in safe mode! Not running saved code.\n" +msgstr "" + +#: main.c +msgid " not found.\n" +msgstr "" + +#: main.c +msgid "WARNING: Your code filename has two extensions\n" +msgstr "" + +#: main.c +msgid "" +"\n" +"Code stopped by auto-reload. Reloading soon.\n" +msgstr "" + +#: main.c +msgid "" +"\n" +"Code done running.\n" +msgstr "" + +#: main.c +msgid "Woken up by alarm.\n" +msgstr "" + +#: main.c +msgid "Press any key to enter the REPL. Use CTRL-D to reload.\n" +msgstr "" + +#: main.c +msgid "Pretending to deep sleep until alarm, CTRL-C or file write.\n" +msgstr "" + +#: main.c +msgid "UID:" +msgstr "" + +#: main.c +msgid "soft reboot\n" +msgstr "" + +#: ports/analog/common-hal/busio/SPI.c ports/analog/common-hal/busio/UART.c +#: ports/cxd56/common-hal/busio/SPI.c ports/stm/common-hal/audioio/AudioOut.c +#: shared-bindings/digitalio/DigitalInOutProtocol.c +#: shared-module/displayio/bus_core.c shared-module/ssl/SSLContext.c +msgid "%q init failed" +msgstr "" + +#: ports/analog/common-hal/busio/SPI.c +msgid "SPI needs MOSI, MISO, and SCK" +msgstr "" + +#: ports/analog/common-hal/busio/SPI.c +#: ports/atmel-samd/common-hal/pulseio/PulseIn.c +#: ports/cxd56/common-hal/pulseio/PulseIn.c +#: ports/nordic/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#: ports/stm/common-hal/pulseio/PulseIn.c py/argcheck.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/canio/Match.c +#: shared-bindings/time/__init__.c +msgid "%q out of range" +msgstr "" + +#: ports/analog/common-hal/busio/SPI.c +#: ports/espressif/common-hal/espidf/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: shared-bindings/epaperdisplay/EPaperDisplay.c +msgid "Invalid state" +msgstr "" + +#: ports/analog/common-hal/busio/SPI.c +msgid "Failed to set SPI Clock Mode" +msgstr "" + +#: ports/analog/common-hal/busio/UART.c +#: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c +#: ports/nordic/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/zephyr-cp/common-hal/busio/UART.c +msgid "RS485" +msgstr "" + +#: ports/analog/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c +msgid "UART needs TX & RX" +msgstr "" + +#: ports/analog/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c +msgid "Both RX and TX required for flow control" +msgstr "" + +#: ports/analog/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/usb_host/Port.c +#: shared-module/rgbmatrix/RGBMatrix.c +msgid "Failed to allocate %q buffer" +msgstr "" + +#: ports/analog/common-hal/busio/UART.c +msgid "UART read error" +msgstr "" + +#: ports/analog/common-hal/busio/UART.c +msgid "UART transaction timeout" +msgstr "" + +#: ports/analog/common-hal/busio/UART.c ports/espressif/common-hal/busio/UART.c +#: ports/nordic/common-hal/busio/UART.c ports/zephyr-cp/common-hal/busio/UART.c +msgid "All UART peripherals are in use" +msgstr "" + +#: ports/analog/common-hal/busio/UART.c +#: ports/analog/peripherals/max32690/max32_i2c.c +#: ports/analog/peripherals/max32690/max32_spi.c +#: ports/analog/peripherals/max32690/max32_uart.c +#: ports/espressif/common-hal/_bleio/Service.c +#: ports/espressif/common-hal/espulp/ULP.c +#: ports/espressif/common-hal/jpegio/JpegDecoder.c +#: ports/espressif/common-hal/microcontroller/Processor.c +#: ports/espressif/common-hal/mipidsi/Display.c +#: ports/mimxrt10xx/common-hal/audiobusio/__init__.c +#: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c +#: ports/raspberrypi/bindings/picodvi/Framebuffer.c +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +#: ports/raspberrypi/common-hal/picodvi/AudioOut.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c +#: ports/raspberrypi/common-hal/usb_host_bulk/InStream.c py/argcheck.c +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/utils/__init__.c +#: shared-bindings/digitalio/DigitalInOut.c +#: shared-bindings/epaperdisplay/EPaperDisplay.c +#: shared-bindings/i2cioexpander/IOPin.c shared-bindings/mipidsi/Display.c +#: shared-bindings/pwmio/PWMOut.c shared-bindings/supervisor/__init__.c +#: shared-module/aurora_epaper/aurora_framebuffer.c +#: shared-module/cryptography/hazmat/primitives/asymmetric/ec/EllipticCurvePublicKey.c +#: shared-module/jpegio/JpegDecoder.c shared-module/lvfontio/OnDiskFont.c +msgid "Invalid %q" +msgstr "" + +#: ports/analog/common-hal/busio/UART.c +msgid "Timeout must be < 100 seconds" +msgstr "" + +#: ports/atmel-samd/audio_dma.c +msgid "All sync event channels in use" +msgstr "" + +#: ports/atmel-samd/audio_dma.c ports/raspberrypi/audio_dma.c +msgid "Internal audio buffer too small" +msgstr "" + +#: ports/atmel-samd/bindings/samd/Clock.c +msgid "calibration is read only" +msgstr "" + +#: ports/atmel-samd/bindings/samd/Clock.c +msgid "calibration is out of range" +msgstr "" + +#: 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/meowmeow/mpconfigboard.h +msgid "You pressed both buttons at start up." +msgstr "" + +#: ports/atmel-samd/common-hal/_pew/PewPew.c +#: ports/atmel-samd/common-hal/audioio/AudioOut.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/nordic/common-hal/audiopwmio/PWMAudioOut.c +#: ports/nordic/common-hal/pulseio/PulseIn.c +#: ports/nordic/peripherals/nrf/timers.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +#: ports/stm/common-hal/pulseio/PulseOut.c +msgid "All timers in use" +msgstr "" + +#: ports/atmel-samd/common-hal/alarm/pin/PinAlarm.c +#: ports/atmel-samd/common-hal/countio/Counter.c +#: ports/atmel-samd/common-hal/frequencyio/FrequencyIn.c +#: ports/atmel-samd/common-hal/max3421e/Max3421E.c +#: ports/atmel-samd/common-hal/ps2io/Ps2.c +#: ports/atmel-samd/common-hal/pulseio/PulseIn.c +#: ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.c +#: ports/cxd56/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c +#: ports/zephyr-cp/common-hal/async_spi/SPI.c +#: ports/zephyr-cp/common-hal/busio/I2C.c +#: ports/zephyr-cp/common-hal/busio/UART.c +msgid "Internal resource(s) in use" +msgstr "" + +#: ports/atmel-samd/common-hal/alarm/pin/PinAlarm.c +#: supervisor/shared/safe_mode.c +msgid "Unknown reason." +msgstr "" + +#: ports/atmel-samd/common-hal/alarm/time/TimeAlarm.c +#: ports/nordic/common-hal/alarm/time/TimeAlarm.c +#: ports/stm/common-hal/alarm/time/TimeAlarm.c +msgid "Only one alarm.time alarm can be set" +msgstr "" + +#: ports/atmel-samd/common-hal/analogio/AnalogOut.c +#: ports/stm/common-hal/analogio/AnalogOut.c +#: ports/stm/common-hal/audioio/AudioOut.c +msgid "No DAC on chip" +msgstr "" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +msgid "%q and %q must share a clock unit" +msgstr "" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +msgid "Serializer in use" +msgstr "" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +msgid "Clock unit in use" +msgstr "" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/atmel-samd/common-hal/touchio/TouchIn.c +msgid "No free GCLKs" +msgstr "" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +msgid "Too many channels in sample" +msgstr "" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +#: ports/raspberrypi/common-hal/mcp4822/MCP4822.c +msgid "No DMA channel found" +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 +#: ports/raspberrypi/common-hal/mcp4822/MCP4822.c +msgid "Unable to allocate buffers for signed conversion" +msgstr "" + +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c +#, c-format +msgid "Only 8 or 16 bit mono with %dx oversampling supported." +msgstr "" + +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c +msgid "sampling rate out of range" +msgstr "" + +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +msgid "DAC already in use" +msgstr "" + +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +msgid "Right channel unsupported" +msgstr "" + +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +msgid "All event channels in use" +msgstr "" + +#: ports/atmel-samd/common-hal/busio/I2C.c +#: ports/espressif/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nordic/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 "" + +#: ports/atmel-samd/common-hal/busio/UART.c +#: shared-bindings/usb_host_bulk/InStream.c +msgid "%q must be power of 2" +msgstr "" + +#: ports/atmel-samd/common-hal/busio/UART.c +#: ports/espressif/common-hal/busio/SPI.c +#: ports/espressif/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/SPI.c +#: ports/mimxrt10xx/common-hal/busio/UART.c +#: ports/nordic/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c ports/stm/common-hal/busio/SPI.c +#: ports/stm/common-hal/busio/UART.c shared-bindings/fourwire/FourWire.c +#: shared-bindings/i2cdisplaybus/I2CDisplayBus.c +#: shared-bindings/paralleldisplaybus/ParallelBus.c +#: shared-bindings/qspibus/QSPIBus.c shared-module/bitbangio/SPI.c +msgid "No %q pin" +msgstr "" + +#: ports/atmel-samd/common-hal/canio/Listener.c +#: ports/espressif/common-hal/canio/Listener.c +#: ports/stm/common-hal/canio/Listener.c +msgid "All RX FIFOs in use" +msgstr "" + +#: ports/atmel-samd/common-hal/canio/Listener.c +msgid "Already have all-matches listener" +msgstr "" + +#: ports/atmel-samd/common-hal/canio/Listener.c +#: ports/espressif/common-hal/canio/Listener.c +#: ports/mimxrt10xx/common-hal/canio/Listener.c +#: ports/stm/common-hal/canio/Listener.c +msgid "Filters too complex" +msgstr "" + +#: ports/atmel-samd/common-hal/digitalio/DigitalInOut.c +#: ports/mimxrt10xx/common-hal/digitalio/DigitalInOut.c +#: ports/nordic/common-hal/digitalio/DigitalInOut.c +#: ports/raspberrypi/common-hal/digitalio/DigitalInOut.c +msgid "Cannot get pull while in output mode" +msgstr "" + +#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c +#, c-format +msgid "Invalid data_pins[%d]" +msgstr "" + +#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c +#, c-format +msgid "data pin #%d in use" +msgstr "" + +#: ports/atmel-samd/common-hal/microcontroller/Pin.c +#: ports/espressif/common-hal/dotclockframebuffer/DotClockFramebuffer.c +#: ports/mimxrt10xx/common-hal/microcontroller/Pin.c +#: shared-bindings/emmcio/EMMC.c shared-bindings/microcontroller/Pin.c +msgid "Invalid %q pin" +msgstr "" + +#: ports/atmel-samd/common-hal/microcontroller/__init__.c +#: ports/cxd56/common-hal/microcontroller/__init__.c +#: ports/mimxrt10xx/common-hal/microcontroller/__init__.c +msgid "No bootloader present" +msgstr "" + +#: ports/atmel-samd/common-hal/paralleldisplaybus/ParallelBus.c +#: ports/nordic/common-hal/paralleldisplaybus/ParallelBus.c +msgid "Data 0 pin must be byte aligned" +msgstr "" + +#: ports/atmel-samd/common-hal/paralleldisplaybus/ParallelBus.c +#: ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c +#: ports/nordic/common-hal/paralleldisplaybus/ParallelBus.c +#: ports/raspberrypi/common-hal/paralleldisplaybus/ParallelBus.c +#, c-format +msgid "Bus pin %d is already in use" +msgstr "" + +#: ports/atmel-samd/common-hal/pulseio/PulseIn.c +#: ports/cxd56/common-hal/pulseio/PulseIn.c +#: ports/nordic/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 "" + +#: ports/atmel-samd/common-hal/pulseio/PulseIn.c +msgid "Input taking too long" +msgstr "" + +#: ports/atmel-samd/common-hal/pulseio/PulseOut.c +#: ports/cxd56/common-hal/pulseio/PulseOut.c +msgid "Another send is already active" +msgstr "" + +#: ports/atmel-samd/common-hal/sdioio/SDCard.c +#: ports/espressif/common-hal/mii/Ethernet.c +#: ports/espressif/common-hal/qspibus/QSPIBus.c shared-bindings/emmcio/EMMC.c +#: shared-bindings/socketpool/SocketPool.c +msgid "%q failure: %d" +msgstr "" + +#: ports/atmel-samd/common-hal/sdioio/SDCard.c +#: ports/cxd56/common-hal/sdioio/SDCard.c +#: ports/espressif/common-hal/sdioio/SDCard.c +#: ports/raspberrypi/common-hal/sdioio/SDCard.c +#: ports/stm/common-hal/sdioio/SDCard.c shared-bindings/audiocore/WaveFile.c +#: shared-bindings/emmcio/EMMC.c shared-bindings/floppyio/__init__.c +#: shared-bindings/picogame/Canvas.c shared-module/sdcardio/SDCard.c +#, c-format +msgid "Buffer must be a multiple of %d bytes" +msgstr "" + +#: ports/atmel-samd/common-hal/spitarget/SPITarget.c +msgid "Async SPI transfer in progress on this bus, keep awaiting." +msgstr "" + +#: ports/cxd56/common-hal/busio/UART.c ports/espressif/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c +msgid "UART init" msgstr "" -#: ports/stm/common-hal/analogio/AnalogOut.c -msgid "DAC Device Init Error" +#: ports/cxd56/common-hal/camera/Camera.c +msgid "Camera init" msgstr "" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c -msgid "DAC already in use" +#: ports/cxd56/common-hal/camera/Camera.c +msgid "Size not supported" msgstr "" -#: ports/atmel-samd/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/nordic/common-hal/paralleldisplaybus/ParallelBus.c -msgid "Data 0 pin must be byte aligned" +#: ports/cxd56/common-hal/camera/Camera.c +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +#: shared-bindings/struct/__init__.c shared-module/struct/__init__.c +#: shared-module/videocore/VideoBuffer.c +msgid "Buffer too small" msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "Data format error (may be broken data)" +#: ports/cxd56/common-hal/camera/Camera.c +#: ports/espressif/common-hal/jpegio/JpegDecoder.c +#: shared-module/audiocore/WaveFile.c +#: shared-module/busdisplay/lvgl/BusDisplay.c +#: shared-module/displayio/lvgl/TileGrid.c +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "Format not supported" +msgstr "" + +#: ports/cxd56/common-hal/gnss/GNSS.c +msgid "GNSS init" +msgstr "" + +#: ports/cxd56/common-hal/sdioio/SDCard.c +msgid "SDCard init" +msgstr "" + +#: ports/espressif/bindings/espnow/ESPNow.c +#: ports/espressif/common-hal/espulp/ULP.c +#: ports/raspberrypi/common-hal/usb_host_bulk/InStream.c +#: shared-module/memorymonitor/AllocationAlarm.c +#: shared-module/memorymonitor/AllocationSize.c +msgid "Already running" +msgstr "" + +#: ports/espressif/bindings/espnow/Peer.c shared-bindings/dualbank/__init__.c +msgid "%q is %q" +msgstr "" + +#: ports/espressif/boards/adafruit_feather_esp32_v2/mpconfigboard.h +msgid "You pressed the SW38 button at start up." +msgstr "" + +#: ports/espressif/boards/adafruit_feather_esp32c6_4mbflash_nopsram/mpconfigboard.h +#: ports/espressif/boards/adafruit_itsybitsy_esp32/mpconfigboard.h +#: ports/espressif/boards/waveshare_esp32_c5_lcd_1_47/mpconfigboard.h +#: ports/espressif/boards/waveshare_esp32_c6_lcd_1_47/mpconfigboard.h +msgid "You pressed the BOOT button at start up." +msgstr "" + +#: ports/espressif/boards/adafruit_huzzah32_breakout/mpconfigboard.h +msgid "You pressed the GPIO0 button at start up." +msgstr "" + +#: ports/espressif/boards/espressif_esp32_lyrat/mpconfigboard.h +msgid "You pressed the Rec button at start up." +msgstr "" + +#: ports/espressif/boards/hardkernel_odroid_go/mpconfigboard.h +#: ports/espressif/boards/vidi_x/mpconfigboard.h +msgid "You pressed the VOLUME button at start up." +msgstr "" + +#: ports/espressif/boards/m5stack_atom_echo/mpconfigboard.h +#: ports/espressif/boards/m5stack_atom_lite/mpconfigboard.h +#: ports/espressif/boards/m5stack_atom_matrix/mpconfigboard.h +#: ports/espressif/boards/m5stack_atom_u/mpconfigboard.h +msgid "You pressed the central button at start up." +msgstr "" + +#: ports/espressif/boards/m5stack_core_basic/mpconfigboard.h +#: ports/espressif/boards/m5stack_core_fire/mpconfigboard.h +#: ports/espressif/boards/m5stack_stick_c/mpconfigboard.h +#: ports/espressif/boards/m5stack_stick_c_plus/mpconfigboard.h +#: ports/espressif/boards/m5stack_stick_c_plus2/mpconfigboard.h +msgid "You pressed button A at start up." +msgstr "" + +#: ports/espressif/boards/m5stack_m5paper/mpconfigboard.h +msgid "You pressed button DOWN at start up." +msgstr "" + +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/espressif/common-hal/dualbank/__init__.c +msgid "Update failed" msgstr "" #: ports/espressif/common-hal/_bleio/Adapter.c #: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Data not supported with directed advertising" +msgid "Scan already in progress. Stop with stop_scan." +msgstr "" + +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +#: ports/zephyr-cp/common-hal/_bleio/Adapter.c +msgid "Failed to connect: timeout" +msgstr "" + +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +#: ports/zephyr-cp/common-hal/_bleio/Adapter.c +msgid "Failed to connect: internal error" msgstr "" #: ports/espressif/common-hal/_bleio/Adapter.c #: ports/nordic/common-hal/_bleio/Adapter.c +#: ports/zephyr-cp/common-hal/_bleio/Adapter.c msgid "Data too large for advertisement packet" msgstr "" -#: ports/stm/common-hal/alarm/pin/PinAlarm.c -msgid "Deep sleep pins must use a rising edge with pulldown" +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "Already advertising." msgstr "" -#: shared-bindings/audiobusio/PDMIn.c -msgid "Destination capacity is smaller than destination_length." +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "Extended advertisements with scan response not supported." msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "Device error or wrong termination of input stream" +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "Data not supported with directed advertising" msgstr "" -#: ports/nordic/common-hal/audiobusio/I2SOut.c -msgid "Device in use" +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +#, c-format +msgid "Timeout is too long: Maximum timeout length is %d seconds" msgstr "" -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -msgid "Display must have a 16 bit colorspace." +#: ports/espressif/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Descriptor.c +msgid "Value length != required fixed length" msgstr "" -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/epaperdisplay/EPaperDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -msgid "Display rotation must be in 90 degree increments" +#: ports/espressif/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Descriptor.c +msgid "Value length > max_length" +msgstr "" + +#: ports/espressif/common-hal/_bleio/Characteristic.c +#: ports/espressif/common-hal/_bleio/Service.c +#: ports/raspberrypi/common-hal/alarm/pin/PinAlarm.c +#: ports/raspberrypi/common-hal/usb_host_bulk/InStream.c +msgid "Too many %q" +msgstr "" + +#: ports/espressif/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Characteristic.c +#: ports/zephyr-cp/common-hal/_bleio/Characteristic.c +msgid "No CCCD for this Characteristic" +msgstr "" + +#: ports/espressif/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Characteristic.c +msgid "Can't set CCCD on local Characteristic" +msgstr "" + +#: ports/espressif/common-hal/_bleio/Connection.c +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/Characteristic.c +#: ports/zephyr-cp/common-hal/_bleio/Connection.c +#: ports/zephyr-cp/common-hal/_bleio/Descriptor.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +#: shared-bindings/_bleio/CharacteristicBuffer.c +msgid "Not connected" +msgstr "" + +#: ports/espressif/common-hal/_bleio/Connection.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/Connection.c +msgid "" +"Unspecified issue. The pairing request on the other device may have been " +"declined or ignored." +msgstr "" + +#: ports/espressif/common-hal/_bleio/Connection.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/Connection.c +#, c-format +msgid "Unknown security error: 0x%04x" +msgstr "" + +#: ports/espressif/common-hal/_bleio/Connection.c +msgid "No pairing in progress" +msgstr "" + +#: ports/espressif/common-hal/_bleio/Connection.c +#: ports/nordic/common-hal/_bleio/Connection.c +msgid "non-UUID found in service_uuids_whitelist" +msgstr "" + +#: ports/espressif/common-hal/_bleio/Descriptor.c +#: ports/nordic/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Descriptor.c +#, c-format +msgid "max_length must be 0-%d when fixed_length is %s" +msgstr "" + +#: ports/espressif/common-hal/_bleio/PacketBuffer.c +#: ports/nordic/common-hal/_bleio/PacketBuffer.c +#: ports/zephyr-cp/common-hal/_bleio/PacketBuffer.c +msgid "Writes not supported on Characteristic" +msgstr "" + +#: ports/espressif/common-hal/_bleio/PacketBuffer.c +#: ports/nordic/common-hal/_bleio/PacketBuffer.c +#: ports/zephyr-cp/common-hal/_bleio/PacketBuffer.c +msgid "Total data to write is larger than %q" +msgstr "" + +#: ports/espressif/common-hal/_bleio/__init__.c +msgid "Nimble out of memory" +msgstr "" + +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +msgid "Invalid BLE parameter" +msgstr "" + +#: ports/espressif/common-hal/_bleio/__init__.c +#: shared-module/audiofilewriter/AudioFileWriter.c +msgid "Already in progress" +msgstr "" + +#: ports/espressif/common-hal/_bleio/__init__.c +#, c-format +msgid "Unknown BLE error at %s:%d: 0x%04x" +msgstr "" + +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#, c-format +msgid "Unknown BLE error: 0x%04x" +msgstr "" + +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +msgid "%q not permitted" +msgstr "" + +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +msgid "Insufficient authentication" +msgstr "" + +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +msgid "Insufficient authorization" +msgstr "" + +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +msgid "Insufficient encryption" +msgstr "" + +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +#, c-format +msgid "Unknown gatt error: 0x%04x" +msgstr "" + +#: ports/espressif/common-hal/alarm/pin/PinAlarm.c +msgid "Cannot wake on pin edge. Only level." +msgstr "" + +#: ports/espressif/common-hal/alarm/pin/PinAlarm.c +msgid "Cannot pull on input-only pin." +msgstr "" + +#: ports/espressif/common-hal/alarm/pin/PinAlarm.c +msgid "Can only alarm on two low pins from deep sleep." +msgstr "" + +#: ports/espressif/common-hal/alarm/pin/PinAlarm.c +msgid "Can only alarm on one low pin while others alarm high from deep sleep." msgstr "" -#: main.c -msgid "Done" +#: ports/espressif/common-hal/alarm/pin/PinAlarm.c +msgid "Can only alarm on RTC IO from deep sleep." msgstr "" -#: shared-bindings/digitalio/DigitalInOut.c -msgid "Drive mode not used when direction is input." +#: ports/espressif/common-hal/alarm/time/TimeAlarm.c +#: ports/raspberrypi/common-hal/alarm/time/TimeAlarm.c +msgid "Only one alarm.time alarm can be set." msgstr "" -#: py/obj.c -msgid "During handling of the above exception, another exception occurred:" +#: ports/espressif/common-hal/alarm/touch/TouchAlarm.c +msgid "Only one %q can be set in deep sleep." msgstr "" -#: shared-bindings/aesio/aes.c -msgid "ECB only operates on 16 bytes at a time" +#: ports/espressif/common-hal/analogbufio/BufferedIn.c +msgid "%q must be array of type 'H'" msgstr "" -#: ports/espressif/common-hal/busio/SPI.c -#: ports/espressif/common-hal/canio/CAN.c -msgid "ESP-IDF memory allocation failed" +#: ports/espressif/common-hal/audiobusio/PDMIn.c +#: shared-bindings/audioi2sin/I2SIn.c shared-bindings/usb_host_audio/USBIn.c +msgid "%q must be 8, 16, 24, or 32" msgstr "" -#: extmod/modre.c -msgid "Error in regex" +#: ports/espressif/common-hal/audiobusio/__init__.c +#: ports/espressif/common-hal/audioi2sin/I2SIn.c +#: ports/espressif/common-hal/mii/Ethernet.c shared-bindings/emmcio/EMMC.c +msgid "Peripheral in use" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Error in safemode.py." +#: ports/espressif/common-hal/audioi2sin/I2SIn.c +#: ports/raspberrypi/common-hal/audioi2sin/I2SIn.c +msgid "%q must be 8 or 16" msgstr "" -#: shared-bindings/alarm/__init__.c -msgid "Expected a kind of %q" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "audio format not supported" msgstr "" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Extended advertisements with scan response not supported." +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to start async audio" msgstr "" -#: extmod/ulab/code/numpy/fft/fft_tools.c -msgid "FFT is defined for ndarrays only" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to create continuous channels: invalid arg" msgstr "" -#: extmod/ulab/code/numpy/fft/fft_tools.c -msgid "FFT is implemented for linear arrays only" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to create continuous channels: invalid state" msgstr "" -#: shared-bindings/ps2io/Ps2.c -msgid "Failed sending command." +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to create continuous channels: not found" msgstr "" -#: ports/nordic/sd_mutex.c -#, c-format -msgid "Failed to acquire mutex, err 0x%04x" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to create continuous channels: no mem" msgstr "" -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "Failed to add service TXT record" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to register continuous events callback" msgstr "" -#: shared-bindings/mdns/Server.c -msgid "" -"Failed to add service TXT record; non-string or bytes found in txt_records" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to enable continuous" msgstr "" -#: shared-module/rgbmatrix/RGBMatrix.c -msgid "Failed to allocate %q buffer" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Can't construct AudioOut because continuous channel already open" msgstr "" -#: ports/espressif/common-hal/wifi/__init__.c -msgid "Failed to allocate Wifi memory" +#: ports/espressif/common-hal/audioio/AudioOut.c +#: ports/espressif/common-hal/mipicsi/Camera.c +#: shared-module/videocore/VideoBuffer.c shared-module/videogif/GifDecoder.c +msgid "already playing" msgstr "" -#: ports/espressif/common-hal/wifi/ScannedNetworks.c -msgid "Failed to allocate wifi scan memory" +#: ports/espressif/common-hal/busio/I2C.c +#: ports/espressif/common-hal/i2ctarget/I2CTarget.c +#: ports/nordic/common-hal/busio/I2C.c ports/zephyr-cp/common-hal/busio/I2C.c +msgid "All I2C peripherals are in use" msgstr "" -#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c -msgid "Failed to buffer the sample" +#: ports/espressif/common-hal/busio/I2C.c +#: ports/espressif/common-hal/busio/SPI.c +msgid "Unable to create lock" msgstr "" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Failed to connect: internal error" +#: ports/espressif/common-hal/busio/SPI.c +msgid "SPI configuration failed" msgstr "" -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Failed to connect: timeout" +#: ports/espressif/common-hal/busio/SPI.c ports/nordic/common-hal/busio/SPI.c +#: ports/zephyr-cp/common-hal/async_spi/SPI.c +msgid "All SPI peripherals are in use" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to create continuous channels: invalid arg" +#: ports/espressif/common-hal/busio/SPI.c +#: ports/espressif/common-hal/canio/CAN.c +#: ports/espressif/common-hal/qspibus/QSPIBus.c +msgid "ESP-IDF memory allocation failed" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to create continuous channels: invalid state" +#: ports/espressif/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c +msgid "Cannot specify RTS or CTS in RS485 mode" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to create continuous channels: no mem" +#: ports/espressif/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c +msgid "RS485 inversion specified when not in RS485 mode" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to create continuous channels: not found" +#: ports/espressif/common-hal/canio/CAN.c +msgid "Baudrate not supported by peripheral" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to enable continuous" +#: ports/espressif/common-hal/canio/CAN.c +msgid "All CAN peripherals are in use" msgstr "" -#: shared-module/audiomp3/MP3Decoder.c -msgid "Failed to parse MP3 file" +#: ports/espressif/common-hal/canio/CAN.c +msgid "loopback + silent mode not supported by peripheral" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to register continuous events callback" +#: ports/espressif/common-hal/canio/CAN.c +#, c-format +msgid "twai_driver_install returned esp-idf error #%d" msgstr "" -#: ports/nordic/sd_mutex.c +#: ports/espressif/common-hal/canio/CAN.c #, c-format -msgid "Failed to release mutex, err 0x%04x" +msgid "twai_start returned esp-idf error #%d" msgstr "" -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "Failed to set hostname" +#: ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "ds_params has the wrong length" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to start async audio" +#: ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "" +"This key already committed to a different algorithm; call " +"load_digital_signature_key() again to use a different one" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Failed to write internal flash." +#: ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "" +"This key's ds_params were replaced by a later load_digital_signature_key() " +"call for the same key slot" msgstr "" -#: py/moderrno.c -msgid "File exists" +#: ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "ds_params is invalid for this key slot" msgstr "" -#: shared-module/os/getenv.c -msgid "File not found" +#: ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "Digital Signature peripheral not available on this chip" msgstr "" -#: ports/atmel-samd/common-hal/canio/Listener.c -#: ports/espressif/common-hal/canio/Listener.c -#: ports/mimxrt10xx/common-hal/canio/Listener.c -#: ports/stm/common-hal/canio/Listener.c -msgid "Filters too complex" +#: ports/espressif/common-hal/dotclockframebuffer/DotClockFramebuffer.c +msgid "Must provide 5/6/5 RGB pins" msgstr "" #: ports/espressif/common-hal/dualbank/__init__.c @@ -1074,239 +1663,244 @@ msgstr "" msgid "Firmware is too big" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "For L8 colorspace, input bitmap must have 8 bits per pixel" +#: ports/espressif/common-hal/espcamera/Camera.c py/objobject.c py/runtime.c +msgid "no such attribute" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "For RGB colorspaces, input bitmap must have 16 bits per pixel" +#: ports/espressif/common-hal/espcamera/Camera.c +msgid "invalid setting" msgstr "" -#: ports/cxd56/common-hal/camera/Camera.c -msgid "Format not supported" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "Generic Failure" msgstr "" -#: ports/mimxrt10xx/common-hal/microcontroller/Processor.c -msgid "" -"Frequency must be 24, 150, 396, 450, 528, 600, 720, 816, 912, 960 or 1008 Mhz" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "Out of memory" msgstr "" -#: shared-bindings/bitbangio/I2C.c shared-bindings/bitbangio/SPI.c -#: shared-bindings/busio/I2C.c shared-bindings/busio/SPI.c -msgid "Function requires lock" +#: ports/espressif/common-hal/espidf/__init__.c py/moderrno.c +msgid "Invalid argument" msgstr "" -#: ports/cxd56/common-hal/gnss/GNSS.c -msgid "GNSS init" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "Invalid size" msgstr "" #: ports/espressif/common-hal/espidf/__init__.c -msgid "Generic Failure" +msgid "Requested resource not found" msgstr "" +#: ports/espressif/common-hal/espidf/__init__.c +#: ports/espressif/common-hal/jpegio/JpegDecoder.c +#: ports/raspberrypi/common-hal/usb_host_bulk/InStream.c +#: shared-bindings/busdisplay/BusDisplay.c #: shared-bindings/framebufferio/FramebufferDisplay.c -#: shared-module/busdisplay/BusDisplay.c -#: shared-module/framebufferio/FramebufferDisplay.c -msgid "Group already used" -msgstr "" - -#: supervisor/shared/safe_mode.c -msgid "Hard fault: memory access or instruction error." +#: shared-bindings/picogame/Canvas.c shared-bindings/picogame/__init__.c +#: shared-module/jpegio/JpegDecoder.c shared-module/picogame/Display.c +msgid "Operation or feature not supported" msgstr "" -#: ports/mimxrt10xx/common-hal/busio/SPI.c -#: ports/mimxrt10xx/common-hal/busio/UART.c 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 "Hardware in use, try alternative pins" +#: ports/espressif/common-hal/espidf/__init__.c +#: ports/espressif/common-hal/qspibus/QSPIBus.c +#: shared-module/_airlift/__init__.c +msgid "Operation timed out" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Heap allocation when VM not running." +#: ports/espressif/common-hal/espidf/__init__.c +#: shared-module/_airlift/__init__.c +msgid "Received response was invalid" msgstr "" -#: extmod/vfs_posix_file.c py/objstringio.c -msgid "I/O operation on closed file" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "CRC or checksum was invalid" msgstr "" -#: ports/stm/common-hal/busio/I2C.c -msgid "I2C init error" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "Version was invalid" msgstr "" -#: ports/raspberrypi/common-hal/busio/I2C.c -#: ports/raspberrypi/common-hal/i2ctarget/I2CTarget.c -msgid "I2C peripheral in use" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "MAC address was invalid" msgstr "" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "In-buffer elements must be <= 4 bytes long" +#: ports/espressif/common-hal/espidf/__init__.c +#, c-format +msgid "%s error 0x%x" msgstr "" -#: shared-bindings/_pew/PewPew.c -msgid "Incorrect buffer size" +#: ports/espressif/common-hal/espulp/ULP.c +msgid "Program too long" msgstr "" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "Init program size invalid" +#: ports/espressif/common-hal/espulp/ULP.c +#: ports/espressif/common-hal/mipidsi/Bus.c +#: ports/espressif/common-hal/qspibus/QSPIBus.c +#: ports/mimxrt10xx/common-hal/audiobusio/__init__.c +#: ports/mimxrt10xx/common-hal/usb_host/Port.c +#: ports/raspberrypi/common-hal/picodvi/AudioOut.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#: ports/raspberrypi/common-hal/usb_host/Port.c +#: shared-bindings/digitalio/DigitalInOut.c shared-bindings/emmcio/EMMC.c +#: shared-bindings/i2cioexpander/IOPin.c shared-bindings/microcontroller/Pin.c +#: shared-module/_airlift/__init__.c +#: shared-module/epaperdisplay/EPaperDisplay.c +#: shared-module/max3421e/Max3421E.c shared-module/usb/core/Device.c +#: shared-module/usb_host_audio/USBIn.c +msgid "%q in use" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Initial set pin direction conflicts with initial out pin direction" +#: ports/espressif/common-hal/espulp/ULPAlarm.c +msgid "Only one %q can be set." msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Initial set pin state conflicts with initial out pin state" +#: ports/espressif/common-hal/i2ctarget/I2CTarget.c +#: ports/raspberrypi/common-hal/i2ctarget/I2CTarget.c +msgid "Only one address is allowed" msgstr "" -#: shared-bindings/bitops/__init__.c +#: ports/espressif/common-hal/max3421e/Max3421E.c +#: ports/raspberrypi/common-hal/wifi/__init__.c #, c-format -msgid "Input buffer length (%d) must be a multiple of the strand count (%d)" +msgid "Unknown error code %d" msgstr "" -#: ports/atmel-samd/common-hal/pulseio/PulseIn.c -msgid "Input taking too long" +#: ports/espressif/common-hal/mdns/Server.c +#: ports/raspberrypi/common-hal/mdns/Server.c +msgid "mDNS only works with built-in WiFi" msgstr "" -#: py/moderrno.c -msgid "Input/output error" +#: ports/espressif/common-hal/mdns/Server.c +#: ports/raspberrypi/common-hal/mdns/Server.c +msgid "mDNS already initialized" msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -#: ports/nordic/common-hal/_bleio/__init__.c -msgid "Insufficient authentication" +#: ports/espressif/common-hal/mdns/Server.c +#: ports/raspberrypi/common-hal/mdns/Server.c +msgid "Unable to start mDNS query" msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -#: ports/nordic/common-hal/_bleio/__init__.c -msgid "Insufficient encryption" +#: ports/espressif/common-hal/memorymap/AddressRange.c +#: ports/nordic/common-hal/memorymap/AddressRange.c +#: ports/raspberrypi/common-hal/memorymap/AddressRange.c +msgid "Address range not allowed" msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "Insufficient memory pool for the image" +#: ports/espressif/common-hal/mipicsi/Camera.c +#: shared-bindings/displayio/TileGrid.c shared-bindings/terminalio/Terminal.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-bindings/vectorio/VectorShape.c +msgid "unsupported %q type" msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "Insufficient stream input buffer" +#: ports/espressif/common-hal/mipicsi/Camera.c +msgid "output_format must be RGB565 or RGB888" msgstr "" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "Interface must be started" +#: ports/espressif/common-hal/mipicsi/Camera.c +msgid "ISP conversion not supported on this chip" msgstr "" -#: ports/atmel-samd/audio_dma.c ports/raspberrypi/audio_dma.c -msgid "Internal audio buffer too small" +#: ports/espressif/common-hal/mipidsi/Bus.c +msgid "%q is above %u" msgstr "" -#: ports/stm/common-hal/busio/UART.c -msgid "Internal define error" +#: ports/espressif/common-hal/mipidsi/Bus.c +msgid "%q is not reachable by the PHY" msgstr "" -#: shared-bindings/pwmio/PWMOut.c shared-module/os/getenv.c -msgid "Internal error" +#: ports/espressif/common-hal/nvm/ByteArray.c +msgid "NVS Error" msgstr "" -#: shared-module/rgbmatrix/RGBMatrix.c +#: ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c +#: ports/espressif/common-hal/sdioio/SDCard.c #, c-format -msgid "Internal error #%d" +msgid "Number of data_pins must be %d or %d, not %d" msgstr "" -#: ports/atmel-samd/common-hal/alarm/pin/PinAlarm.c -#: ports/atmel-samd/common-hal/countio/Counter.c -#: ports/atmel-samd/common-hal/frequencyio/FrequencyIn.c -#: ports/atmel-samd/common-hal/max3421e/Max3421E.c -#: ports/atmel-samd/common-hal/ps2io/Ps2.c -#: ports/atmel-samd/common-hal/pulseio/PulseIn.c -#: ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.c -#: ports/cxd56/common-hal/pulseio/PulseIn.c -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c -#: shared-bindings/pwmio/PWMOut.c -msgid "Internal resource(s) in use" +#: ports/espressif/common-hal/pulseio/PulseIn.c +msgid "pop from an empty PulseIn" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Internal watchdog timer expired." +#: ports/espressif/common-hal/qspibus/QSPIBus.c +#: ports/raspberrypi/common-hal/usb_host_bulk/InStream.c +#: shared-module/usb/core/Device.c +msgid "Could not allocate DMA capable buffer" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Interrupt error." +#: ports/espressif/common-hal/qspibus/QSPIBus.c shared-bindings/pwmio/PWMOut.c +#: supervisor/shared/settings.c +msgid "Internal error" msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "Interrupted by output function" +#: ports/espressif/common-hal/rclcpy/Node.c +msgid "ROS node failed to initialize" msgstr "" -#: ports/espressif/common-hal/_bleio/Service.c -#: ports/espressif/common-hal/espulp/ULP.c -#: ports/espressif/common-hal/microcontroller/Processor.c -#: ports/mimxrt10xx/common-hal/audiobusio/__init__.c -#: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c -#: ports/raspberrypi/bindings/picodvi/Framebuffer.c -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c py/argcheck.c -#: shared-bindings/digitalio/DigitalInOut.c -#: shared-bindings/epaperdisplay/EPaperDisplay.c shared-bindings/pwmio/PWMOut.c -#: shared-module/aurora_epaper/aurora_framebuffer.c -msgid "Invalid %q" +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "ROS topic failed to initialize" msgstr "" -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c -#: shared-module/aurora_epaper/aurora_framebuffer.c -msgid "Invalid %q and %q" +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "Could not publish to ROS topic" msgstr "" -#: ports/atmel-samd/common-hal/microcontroller/Pin.c -#: ports/espressif/common-hal/dotclockframebuffer/DotClockFramebuffer.c -#: ports/mimxrt10xx/common-hal/microcontroller/Pin.c -#: shared-bindings/microcontroller/Pin.c -msgid "Invalid %q pin" +#: ports/espressif/common-hal/rclcpy/__init__.c +#, c-format +msgid "Critical ROS failure during soft reboot, reset required: %d" msgstr "" -#: ports/stm/common-hal/analogio/AnalogIn.c -msgid "Invalid ADC Unit value" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS memory allocator failure" msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -#: ports/nordic/common-hal/_bleio/__init__.c -msgid "Invalid BLE parameter" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS internal setup failure" msgstr "" -#: shared-bindings/wifi/Radio.c -msgid "Invalid BSSID" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "Invalid ROS domain ID" msgstr "" -#: shared-bindings/wifi/Radio.c -msgid "Invalid MAC address" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS failed to initialize. Is agent connected?" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c py/moderrno.c -msgid "Invalid argument" +#: ports/espressif/common-hal/sdioio/SDCard.c +#: ports/raspberrypi/common-hal/sdioio/SDCard.c +#: ports/stm/common-hal/sdioio/SDCard.c +#, c-format +msgid "SDIO Init Error 0x%02x" msgstr "" -#: shared-module/displayio/Bitmap.c -msgid "Invalid bits per value" +#: ports/espressif/common-hal/socketpool/Socket.c +#: ports/zephyr-cp/common-hal/socketpool/Socket.c +msgid "Unsupported socket type" msgstr "" -#: shared-module/os/getenv.c -#, c-format -msgid "Invalid byte %.*s" +#: ports/espressif/common-hal/socketpool/Socket.c +#: ports/raspberrypi/common-hal/socketpool/Socket.c +msgid "Out of sockets" msgstr "" -#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c -#, c-format -msgid "Invalid data_pins[%d]" +#: ports/espressif/common-hal/socketpool/SocketPool.c +msgid "SocketPool can only be used with %q.%q or any %q.%q" msgstr "" -#: shared-module/msgpack/__init__.c -msgid "Invalid format" +#: ports/espressif/common-hal/watchdog/WatchDogTimer.c +msgid "%q must be <= %u" msgstr "" -#: shared-module/audiocore/WaveFile.c -msgid "Invalid format chunk size" +#: ports/espressif/common-hal/wifi/Monitor.c +msgid "monitor init failed" msgstr "" -#: shared-bindings/wifi/Radio.c -msgid "Invalid hex password" +#: ports/espressif/common-hal/wifi/Radio.c +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "Interface must be started" msgstr "" #: ports/espressif/common-hal/wifi/Radio.c @@ -1314,1350 +1908,1338 @@ msgstr "" msgid "Invalid multicast MAC address" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Invalid size" -msgstr "" - -#: shared-module/ssl/SSLSocket.c -msgid "Invalid socket for TLS" +#: ports/espressif/common-hal/wifi/Radio.c +#: ports/raspberrypi/common-hal/wifi/Radio.c +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "Already scanning for wifi networks" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -#: ports/nordic/common-hal/_bleio/__init__.c -msgid "Invalid state" +#: ports/espressif/common-hal/wifi/Radio.c +#: ports/espressif/common-hal/wifi/__init__.c +#: ports/raspberrypi/common-hal/wifi/Radio.c +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "WiFi is not enabled" msgstr "" -#: shared-module/os/getenv.c -msgid "Invalid unicode escape" +#: ports/espressif/common-hal/wifi/ScannedNetworks.c +msgid "Failed to allocate wifi scan memory" msgstr "" -#: shared-bindings/aesio/aes.c -msgid "Key must be 16, 24, or 32 bytes long" +#: ports/espressif/common-hal/wifi/__init__.c +msgid "Failed to allocate Wifi memory" msgstr "" -#: shared-module/os/getenv.c -msgid "Key not found" +#: ports/espressif/common-hal/wifi/__init__.c +#: ports/raspberrypi/common-hal/wifi/__init__.c +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "Only IPv4 addresses supported" msgstr "" -#: shared-module/is31fl3741/FrameBuffer.c -msgid "LED mappings must match display size" +#: ports/mimxrt10xx/common-hal/busio/SPI.c +#: ports/raspberrypi/bindings/wiznet/PIO_SPI.c shared-bindings/async_spi/SPI.c +#: shared-bindings/busio/SPI.c +msgid "Must provide MISO or MOSI pin" msgstr "" -#: py/compile.c -msgid "LHS of keyword arg must be an id" +#: ports/mimxrt10xx/common-hal/busio/SPI.c +#: ports/mimxrt10xx/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/canio/CAN.c 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 +#: shared-bindings/emmcio/EMMC.c +msgid "Hardware in use, try alternative pins" msgstr "" -#: shared-module/displayio/Group.c -msgid "Layer already in a group" +#: ports/mimxrt10xx/common-hal/canio/CAN.c +msgid "Unable to send CAN Message: all Tx message buffers are busy" msgstr "" -#: shared-module/displayio/Group.c -msgid "Layer must be a Group or TileGrid subclass" +#: ports/mimxrt10xx/common-hal/microcontroller/Processor.c +msgid "" +"Frequency must be 24, 150, 396, 450, 528, 600, 720, 816, 912, 960 or 1008 Mhz" msgstr "" -#: shared-bindings/audiocore/RawSample.c -msgid "Length of %q must be an even multiple of channel_count * type_size" +#: ports/nordic/boards/aramcon2_badge/mpconfigboard.h +msgid "You pressed the left button at start up." msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "MAC address was invalid" +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "timeout must be < 655.35 secs" msgstr "" -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/espressif/common-hal/_bleio/Descriptor.c -msgid "MITM security not supported" +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "non-zero timeout must be > 0.01" msgstr "" -#: shared-bindings/is31fl3741/IS31FL3741.c -msgid "Mapping must be a tuple" +#: ports/nordic/common-hal/_bleio/UUID.c +msgid "Unexpected nrfx uuid type" msgstr "" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Mismatched data size" +#: ports/nordic/common-hal/_bleio/__init__.c +msgid "Nordic system firmware out of memory" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Mismatched swap flag" +#: ports/nordic/common-hal/_bleio/__init__.c +#, c-format +msgid "Unknown system firmware error: %04x" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_in_pin. %q[%u] reads pin(s)" +#: ports/nordic/common-hal/alarm/pin/PinAlarm.c +msgid "Cannot wake on pin edge, only level" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_in_pin. %q[%u] shifts in from pin(s)" +#: ports/nordic/common-hal/audiobusio/I2SOut.c +msgid "Device in use" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_in_pin. %q[%u] waits based on pin" +#: ports/nordic/common-hal/audiobusio/PDMIn.c +#: ports/stm/common-hal/audiobusio/PDMIn.c +msgid "only sample_rate=16000 is supported" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_out_pin. %q[%u] shifts out to pin(s)" +#: ports/nordic/common-hal/audiobusio/PDMIn.c +#: ports/stm/common-hal/audiobusio/PDMIn.c +msgid "only bit_depth=16 is supported" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_out_pin. %q[%u] writes pin(s)" +#: ports/nordic/common-hal/busio/UART.c +#, c-format +msgid "error = 0x%08lX" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_set_pin. %q[%u] sets pin(s)" +#: ports/nordic/common-hal/busio/UART.c +msgid "Odd parity is not supported" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing jmp_pin. %q[%u] jumps on pin" +#: ports/nordic/common-hal/countio/Counter.c +#: ports/nordic/common-hal/pulseio/PulseIn.c +#: ports/nordic/common-hal/rotaryio/IncrementalEncoder.c +msgid "All channels in use" msgstr "" -#: shared-module/storage/__init__.c -msgid "Mount point directory missing" +#: ports/nordic/common-hal/microcontroller/Processor.c +msgid "Cannot get temperature" msgstr "" -#: ports/zephyr-cp/bindings/zephyr_serial/UART.c shared-bindings/busio/UART.c -#: shared-bindings/displayio/Group.c -msgid "Must be a %q subclass." +#: ports/nordic/common-hal/watchdog/WatchDogTimer.c +msgid "timeout duration exceeded the maximum supported value" msgstr "" -#: ports/espressif/common-hal/dotclockframebuffer/DotClockFramebuffer.c -msgid "Must provide 5/6/5 RGB pins" +#: ports/nordic/common-hal/watchdog/WatchDogTimer.c +msgid "%q cannot be changed once mode is set to %q" msgstr "" -#: ports/mimxrt10xx/common-hal/busio/SPI.c shared-bindings/busio/SPI.c -msgid "Must provide MISO or MOSI pin" +#: ports/nordic/common-hal/watchdog/WatchDogTimer.c +msgid "WatchDogTimer cannot be deinitialized once mode is set to RESET" msgstr "" -#: shared-bindings/rgbmatrix/RGBMatrix.c +#: ports/nordic/sd_mutex.c #, c-format -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/espressif/common-hal/nvm/ByteArray.c -msgid "NVS Error" -msgstr "" - -#: shared-bindings/socketpool/SocketPool.c -msgid "Name or service not known" -msgstr "" - -#: shared-bindings/displayio/TileGrid.c -msgid "New bitmap must be same size as old bitmap" +msgid "Failed to acquire mutex, err 0x%04x" msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -msgid "Nimble out of memory" +#: ports/nordic/sd_mutex.c +#, c-format +msgid "Failed to release mutex, err 0x%04x" msgstr "" -#: ports/atmel-samd/common-hal/busio/UART.c -#: ports/espressif/common-hal/busio/SPI.c -#: ports/espressif/common-hal/busio/UART.c -#: ports/mimxrt10xx/common-hal/busio/SPI.c -#: ports/mimxrt10xx/common-hal/busio/UART.c -#: ports/nordic/common-hal/busio/UART.c -#: ports/raspberrypi/common-hal/busio/UART.c ports/stm/common-hal/busio/SPI.c -#: ports/stm/common-hal/busio/UART.c shared-bindings/fourwire/FourWire.c -#: shared-bindings/i2cdisplaybus/I2CDisplayBus.c -#: shared-bindings/paralleldisplaybus/ParallelBus.c -#: shared-module/bitbangio/SPI.c -msgid "No %q pin" +#: ports/raspberrypi/audio_dma.c +msgid "Audio conversion not implemented" msgstr "" -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Characteristic.c -msgid "No CCCD for this Characteristic" +#: ports/raspberrypi/bindings/cyw43/__init__.c py/argcheck.c py/objexcept.c +#: shared-bindings/bitmapfilter/__init__.c shared-bindings/canio/CAN.c +#: shared-bindings/digitalio/Pull.c shared-bindings/picogame/Sprite.c +#: shared-bindings/supervisor/__init__.c shared-module/audiofilters/__init__.c +#: shared-module/displayio/legacy/__init__.c +#: shared-module/synthio/Synthesizer.c shared-module/videocore/VideoBuffer.c +msgid "%q must be of type %q or %q, not %q" msgstr "" -#: ports/atmel-samd/common-hal/analogio/AnalogOut.c -#: ports/stm/common-hal/analogio/AnalogOut.c -msgid "No DAC on chip" +#: ports/raspberrypi/bindings/picodvi/AudioOut.c +#: shared-bindings/audiobusio/I2SOut.c shared-bindings/audioio/AudioOut.c +#: shared-bindings/audiopwmio/PWMAudioOut.c shared-bindings/mcp4822/MCP4822.c +#: shared-bindings/usb_audio/USBMicrophone.c +msgid "Not playing" 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" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Program size invalid" msgstr "" -#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c -msgid "No DMA pacing timer found" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Init program size invalid" msgstr "" -#: shared-module/adafruit_bus_device/i2c_device/I2CDevice.c -#, c-format -msgid "No I2C device at address: 0x%x" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Buffer elements must be 4 bytes long or less" msgstr "" -#: supervisor/shared/web_workflow/web_workflow.c -msgid "No IP" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Mismatched data size" msgstr "" -#: ports/atmel-samd/common-hal/microcontroller/__init__.c -#: ports/cxd56/common-hal/microcontroller/__init__.c -#: ports/mimxrt10xx/common-hal/microcontroller/__init__.c -msgid "No bootloader present" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Out-buffer elements must be <= 4 bytes long" msgstr "" -#: shared-module/usb/core/Device.c -msgid "No configuration set" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "In-buffer elements must be <= 4 bytes long" msgstr "" -#: shared-bindings/_bleio/PacketBuffer.c -msgid "No connection: length cannot be determined" +#: ports/raspberrypi/bindings/wiznet/PIO_SPI.c shared-bindings/async_spi/SPI.c +#: 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 "" -#: shared-bindings/board/__init__.c -msgid "No default %q bus" +#: ports/raspberrypi/bindings/wiznet/PIO_SPI.c shared-bindings/async_spi/SPI.c +#: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c +msgid "buffer slices must be of equal length" msgstr "" -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c -#: ports/atmel-samd/common-hal/touchio/TouchIn.c -msgid "No free GCLKs" +#: ports/raspberrypi/common-hal/alarm/touch/TouchAlarm.c +#: ports/stm/common-hal/alarm/touch/TouchAlarm.c +msgid "Touch alarms not available" msgstr "" -#: shared-bindings/os/__init__.c -msgid "No hardware random available" +#: ports/raspberrypi/common-hal/async_spi/SPI.c shared-bindings/emmcio/EMMC.c +msgid "SPI peripheral in use" msgstr "" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audioi2sin/I2SIn.c #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "No in in program" +msgid "Cannot use GPIO0..15 together with GPIO32..47" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "No in or out in program" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audioi2sin/I2SIn.c +msgid "Bit clock and word select must be sequential GPIO pins" msgstr "" -#: py/objint.c shared-bindings/time/__init__.c -msgid "No long integer support" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/mcp4822/MCP4822.c +msgid "Too many channels in sample." msgstr "" -#: shared-bindings/wifi/Radio.c -msgid "No network with that ssid" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +#: ports/raspberrypi/common-hal/mcp4822/MCP4822.c +msgid "Audio source error" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "No out in program" +#: ports/raspberrypi/common-hal/audioi2sin/I2SIn.c +msgid "%q must be 16, 24, or 32" +msgstr "" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Pins must share PWM slice" +msgstr "" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "No DMA pacing timer found" msgstr "" -#: ports/atmel-samd/common-hal/busio/I2C.c -#: ports/espressif/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nordic/common-hal/busio/I2C.c #: ports/raspberrypi/common-hal/busio/I2C.c -msgid "No pull up found on SDA or SCL; check your wiring" +#: ports/raspberrypi/common-hal/i2ctarget/I2CTarget.c +msgid "I2C peripheral in use" msgstr "" -#: shared-module/touchio/TouchIn.c -msgid "No pulldown on pin; 1Mohm recommended" +#: ports/raspberrypi/common-hal/busio/UART.c +msgid "UART peripheral in use" msgstr "" -#: py/moderrno.c -msgid "No space left on device" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "Pin must be on PWM Channel B" msgstr "" -#: py/moderrno.c -msgid "No such device" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "RISE_AND_FALL not available on this chip" msgstr "" -#: py/moderrno.c -msgid "No such file/directory" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice already in use" msgstr "" -#: shared-module/rgbmatrix/RGBMatrix.c -msgid "No timer available" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice channel A already in use" msgstr "" -#: shared-module/usb/core/Device.c -msgid "No usb host port initialized" +#: ports/raspberrypi/common-hal/floppyio/__init__.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#: ports/raspberrypi/common-hal/usb_host/Port.c +msgid "All state machines in use" msgstr "" -#: ports/nordic/common-hal/_bleio/__init__.c -msgid "Nordic system firmware out of memory" +#: ports/raspberrypi/common-hal/floppyio/__init__.c +msgid "timeout waiting for flux" msgstr "" -#: shared-bindings/ipaddress/IPv4Address.c shared-bindings/ipaddress/__init__.c -msgid "Not a valid IP string" +#: ports/raspberrypi/common-hal/floppyio/__init__.c +#: shared-module/floppyio/__init__.c +msgid "timeout waiting for index pulse" msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -#: ports/nordic/common-hal/_bleio/__init__.c -#: shared-bindings/_bleio/CharacteristicBuffer.c -msgid "Not connected" +#: ports/raspberrypi/common-hal/imagecapture/ParallelImageCapture.c +msgid "Pins must be sequential" msgstr "" -#: shared-bindings/audiobusio/I2SOut.c shared-bindings/audioio/AudioOut.c -#: shared-bindings/audiopwmio/PWMAudioOut.c -msgid "Not playing" +#: ports/raspberrypi/common-hal/mcp4822/MCP4822.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c +#: shared-module/aurora_epaper/aurora_framebuffer.c +msgid "Invalid %q and %q" msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "Not supported JPEG standard" +#: ports/raspberrypi/common-hal/mdns/Server.c +msgid "Out of MDNS service slots" msgstr "" -#: ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/espressif/common-hal/sdioio/SDCard.c -#, c-format -msgid "Number of data_pins must be %d or %d, not %d" +#: ports/raspberrypi/common-hal/memorymap/AddressRange.c +msgid "Unable to access unaligned IO register" msgstr "" -#: shared-bindings/util.c -msgid "" -"Object has been deinitialized and can no longer be used. Create a new object." +#: ports/raspberrypi/common-hal/memorymap/AddressRange.c +msgid "Unable to write to read-only memory" msgstr "" -#: ports/nordic/common-hal/busio/UART.c -msgid "Odd parity is not supported" +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c +msgid "All timers for this pin are in use" msgstr "" -#: supervisor/shared/bluetooth/bluetooth.c -msgid "Off" +#: ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c +msgid "Pins must be sequential GPIO pins" msgstr "" -#: supervisor/shared/bluetooth/bluetooth.c -msgid "Ok" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Pin count too large" msgstr "" -#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c -#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c -#, c-format -msgid "Only 8 or 16 bit mono with %dx oversampling supported." +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing jmp_pin. %q[%u] jumps on pin" msgstr "" -#: ports/espressif/common-hal/wifi/__init__.c -#: ports/raspberrypi/common-hal/wifi/__init__.c -msgid "Only IPv4 addresses supported" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "%q[%u] uses extra pin" msgstr "" -#: ports/raspberrypi/common-hal/socketpool/Socket.c -msgid "Only IPv4 sockets supported" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_in_pin. %q[%u] waits based on pin" msgstr "" -#: shared-module/displayio/OnDiskBitmap.c -#, c-format -msgid "" -"Only Windows format, uncompressed BMP supported: given header size is %d" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "%q[%u] waits on input outside of count" msgstr "" -#: shared-bindings/_bleio/Adapter.c -msgid "Only connectable advertisements can be directed" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_in_pin. %q[%u] shifts in from pin(s)" msgstr "" -#: ports/stm/common-hal/alarm/pin/PinAlarm.c -msgid "Only edge detection is available on this hardware" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "%q[%u] shifts in more bits than pin count" msgstr "" -#: shared-bindings/ipaddress/__init__.c -msgid "Only int or string supported for ip" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_out_pin. %q[%u] shifts out to pin(s)" msgstr "" -#: ports/espressif/common-hal/alarm/touch/TouchAlarm.c -msgid "Only one %q can be set in deep sleep." +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "%q[%u] shifts out more bits than pin count" msgstr "" -#: ports/espressif/common-hal/espulp/ULPAlarm.c -msgid "Only one %q can be set." +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_set_pin. %q[%u] sets pin(s)" msgstr "" -#: ports/espressif/common-hal/i2ctarget/I2CTarget.c -#: ports/raspberrypi/common-hal/i2ctarget/I2CTarget.c -msgid "Only one address is allowed" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_out_pin. %q[%u] writes pin(s)" msgstr "" -#: ports/atmel-samd/common-hal/alarm/time/TimeAlarm.c -#: ports/nordic/common-hal/alarm/time/TimeAlarm.c -#: ports/stm/common-hal/alarm/time/TimeAlarm.c -msgid "Only one alarm.time alarm can be set" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_in_pin. %q[%u] reads pin(s)" msgstr "" -#: ports/espressif/common-hal/alarm/time/TimeAlarm.c -#: ports/raspberrypi/common-hal/alarm/time/TimeAlarm.c -msgid "Only one alarm.time alarm can be set." +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Program does IN without loading ISR" msgstr "" -#: shared-module/displayio/ColorConverter.c -msgid "Only one color can be transparent at a time" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Program does OUT without loading OSR" msgstr "" -#: py/moderrno.c -msgid "Operation not permitted" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin state conflicts with initial out pin state" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Operation or feature not supported" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin direction conflicts with initial out pin direction" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Operation timed out" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "pull masks conflict with direction masks" msgstr "" -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "Out of MDNS service slots" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No out in program" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Out of memory" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in in program" msgstr "" -#: ports/espressif/common-hal/socketpool/Socket.c -#: ports/raspberrypi/common-hal/socketpool/Socket.c -#: ports/zephyr-cp/common-hal/socketpool/Socket.c -msgid "Out of sockets" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in or out in program" +msgstr "" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Mismatched swap flag" +msgstr "" + +#: ports/raspberrypi/common-hal/sdioio/SDCard.c +#, c-format +msgid "Number of data_pins must be %d, not %d" msgstr "" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "Out-buffer elements must be <= 4 bytes long" +#: ports/raspberrypi/common-hal/sdioio/SDCard.c +msgid "Data pins must be consecutive" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "PWM restart" +#: ports/raspberrypi/common-hal/socketpool/Socket.c +msgid "Only IPv4 sockets supported" msgstr "" -#: ports/raspberrypi/common-hal/countio/Counter.c -msgid "PWM slice already in use" +#: ports/raspberrypi/common-hal/socketpool/SocketPool.c +msgid "SocketPool can only be used with wifi.radio" msgstr "" -#: ports/raspberrypi/common-hal/countio/Counter.c -msgid "PWM slice channel A already in use" +#: ports/raspberrypi/common-hal/usb_host/Port.c +msgid "All dma channels in use" msgstr "" -#: shared-bindings/spitarget/SPITarget.c -msgid "Packet buffers for an SPI transfer must have the same length." +#: ports/raspberrypi/common-hal/wifi/Monitor.c +msgid "wifi.Monitor not available" msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "Parameter error" +#: ports/raspberrypi/common-hal/wifi/Radio.c +msgid "%q is read-only for this board" msgstr "" -#: ports/espressif/common-hal/audiobusio/__init__.c -msgid "Peripheral in use" +#: ports/raspberrypi/common-hal/wifi/Radio.c +msgid "AP could not be started" msgstr "" -#: py/moderrno.c -msgid "Permission denied" +#: ports/stm/common-hal/alarm/pin/PinAlarm.c +msgid "Only edge detection is available on this hardware" msgstr "" #: ports/stm/common-hal/alarm/pin/PinAlarm.c -msgid "Pin cannot wake from Deep Sleep" +#: ports/stm/common-hal/pulseio/PulseIn.c +msgid "Pin interrupt already in use" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Pin count too large" +#: ports/stm/common-hal/alarm/pin/PinAlarm.c +msgid "Pin cannot wake from Deep Sleep" msgstr "" #: ports/stm/common-hal/alarm/pin/PinAlarm.c -#: ports/stm/common-hal/pulseio/PulseIn.c -msgid "Pin interrupt already in use" +msgid "Deep sleep pins must use a rising edge with pulldown" msgstr "" -#: shared-bindings/adafruit_bus_device/spi_device/SPIDevice.c -msgid "Pin is input only" +#: ports/stm/common-hal/analogio/AnalogIn.c +msgid "Invalid ADC Unit value" msgstr "" -#: ports/raspberrypi/common-hal/countio/Counter.c -msgid "Pin must be on PWM Channel B" +#: ports/stm/common-hal/analogio/AnalogOut.c +#: ports/stm/common-hal/audioio/AudioOut.c +msgid "DAC Device Init Error" msgstr "" -#: 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" +#: ports/stm/common-hal/analogio/AnalogOut.c +#: ports/stm/common-hal/audioio/AudioOut.c +msgid "DAC Channel Init Error" msgstr "" -#: ports/raspberrypi/common-hal/imagecapture/ParallelImageCapture.c -msgid "Pins must be sequential" +#: ports/stm/common-hal/audiobusio/PDMIn.c +msgid "only mono is supported" msgstr "" -#: ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c -msgid "Pins must be sequential GPIO pins" +#: ports/stm/common-hal/audiobusio/PDMIn.c +msgid "only oversample=64 is supported" msgstr "" -#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c -msgid "Pins must share PWM slice" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Another PWMAudioOut is already active" msgstr "" -#: shared-module/usb/core/Device.c -msgid "Pipe error" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +#, c-format +msgid "Buffer length %d too big. It must be less than %d" msgstr "" -#: py/builtinhelp.c -msgid "Plus any modules on the filesystem\n" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Failed to buffer the sample" msgstr "" -#: shared-module/vectorio/Polygon.c -msgid "Polygon needs at least 3 points" +#: ports/stm/common-hal/busio/I2C.c +msgid "I2C init error" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Power dipped. Make sure you are providing enough power." +#: ports/stm/common-hal/busio/SPI.c +msgid "SPI init error" msgstr "" -#: shared-bindings/_bleio/Adapter.c -msgid "Prefix buffer must be on the heap" +#: ports/stm/common-hal/busio/SPI.c +msgid "SPI re-init" msgstr "" -#: main.c -msgid "Press any key to enter the REPL. Use CTRL-D to reload.\n" +#: ports/stm/common-hal/busio/UART.c +msgid "Internal define error" msgstr "" -#: main.c -msgid "Pretending to deep sleep until alarm, CTRL-C or file write.\n" +#: ports/stm/common-hal/busio/UART.c +msgid "Could not start interrupt, RX busy" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Program does IN without loading ISR" +#: ports/stm/common-hal/busio/UART.c +msgid "UART write" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Program does OUT without loading OSR" +#: ports/stm/common-hal/busio/UART.c +msgid "UART de-init" msgstr "" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "Program size invalid" +#: ports/stm/common-hal/busio/UART.c +msgid "UART re-init" msgstr "" -#: ports/espressif/common-hal/espulp/ULP.c -msgid "Program too long" +#: ports/stm/common-hal/microcontroller/Processor.c +msgid "Temperature read timed out" msgstr "" -#: shared-bindings/digitalio/DigitalInOut.c -msgid "Pull not used when direction is output." +#: ports/stm/common-hal/microcontroller/Processor.c +msgid "Voltage read timed out" msgstr "" -#: ports/raspberrypi/common-hal/countio/Counter.c -msgid "RISE_AND_FALL not available on this chip" +#: ports/stm/common-hal/os/__init__.c +msgid "RNG Init Error" msgstr "" -#: shared-module/displayio/OnDiskBitmap.c -msgid "RLE-compressed BMP not supported" +#: ports/stm/common-hal/os/__init__.c +msgid "Random number generation error" msgstr "" #: ports/stm/common-hal/os/__init__.c msgid "RNG DeInit Error" msgstr "" -#: ports/stm/common-hal/os/__init__.c -msgid "RNG Init Error" +#: ports/stm/common-hal/pwmio/PWMOut.c +msgid "timer re-init" msgstr "" -#: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c -#: ports/nordic/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c -msgid "RS485" +#: ports/stm/common-hal/pwmio/PWMOut.c +msgid "channel re-init" msgstr "" -#: ports/espressif/common-hal/busio/UART.c -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "RS485 inversion specified when not in RS485 mode" +#: ports/stm/common-hal/pwmio/PWMOut.c +msgid "PWM restart" msgstr "" -#: shared-bindings/alarm/time/TimeAlarm.c shared-bindings/time/__init__.c -msgid "RTC is not supported on this board" +#: ports/stm/common-hal/sdioio/SDCard.c +#, c-format +msgid "MMC/SDIO Clock Error %x" msgstr "" -#: ports/stm/common-hal/os/__init__.c -msgid "Random number generation error" +#: ports/stm/common-hal/sdioio/SDCard.c +#, c-format +msgid "SDIO GetCardInfo Error %d" msgstr "" -#: shared-bindings/_bleio/__init__.c -#: shared-bindings/memorymonitor/AllocationSize.c -#: shared-bindings/pulseio/PulseIn.c shared-module/bitmaptools/__init__.c -#: shared-module/displayio/Bitmap.c shared-module/displayio/Group.c -msgid "Read-only" +#: ports/zephyr-cp/bindings/zephyr_display/Display.c +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/epaperdisplay/EPaperDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +#: shared-bindings/mipidsi/Display.c +msgid "Display rotation must be in 90 degree increments" msgstr "" -#: extmod/vfs_fat.c py/moderrno.c -msgid "Read-only filesystem" +#: ports/zephyr-cp/bindings/zephyr_display/Display.c +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/epaperdisplay/EPaperDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +msgid ".show(x) removed. Use .root_group = x" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Received response was invalid" +#: ports/zephyr-cp/bindings/zephyr_display/Display.c +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +msgid "Brightness not adjustable" msgstr "" -#: supervisor/shared/bluetooth/bluetooth.c -msgid "Reconnecting" +#: ports/zephyr-cp/bindings/zephyr_display/Display.c py/argcheck.c +#: shared-bindings/busdisplay/BusDisplay.c shared-bindings/displayio/Bitmap.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +#: shared-bindings/is31fl3741/FrameBuffer.c +#: shared-bindings/rgbmatrix/RGBMatrix.c +msgid "%q must be %d-%d" msgstr "" -#: shared-bindings/epaperdisplay/EPaperDisplay.c -msgid "Refresh too soon" +#: ports/zephyr-cp/bindings/zephyr_display/Display.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +#: shared-module/busdisplay/legacy/BusDisplay.c +#: shared-module/framebufferio/legacy/FramebufferDisplay.c +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "Group already used" msgstr "" -#: shared-bindings/canio/RemoteTransmissionRequest.c -msgid "RemoteTransmissionRequests limited to 8 bytes" +#: ports/zephyr-cp/common-hal/_bleio/Adapter.c +msgid "Invalid advertising data" msgstr "" -#: shared-bindings/aesio/aes.c -msgid "Requested AES mode is unsupported" +#: ports/zephyr-cp/common-hal/async_spi/SPI.c +#: ports/zephyr-cp/common-hal/audiobusio/I2SOut.c +#: ports/zephyr-cp/common-hal/busio/I2C.c +#: ports/zephyr-cp/common-hal/busio/UART.c +msgid "Use device tree to define %q devices" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Requested resource not found" +#: ports/zephyr-cp/common-hal/mii/Ethernet.c +msgid "cannot construct ethernet interfaces; use board.ETHERNET" msgstr "" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c -msgid "Right channel unsupported" +#: ports/zephyr-cp/common-hal/socketpool/SocketPool.c +msgid "SocketPool can only be used with %q.%q, %q.%q, or %q.%q" msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "Right format but not supported" +#: ports/zephyr-cp/common-hal/usb_hid/Device.c shared-module/usb_hid/Device.c +msgid "USB error" msgstr "" -#: main.c -msgid "Running in safe mode! Not running saved code.\n" +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "Failed to set hostname" msgstr "" -#: shared-module/sdcardio/SDCard.c -msgid "SD card CSD format not supported" +#: ports/zephyr-cp/common-hal/zephyr_display/legacy/Display.c +#: ports/zephyr-cp/common-hal/zephyr_display/lvgl/Display.c +#: shared-module/busdisplay/legacy/BusDisplay.c +#: shared-module/framebufferio/legacy/FramebufferDisplay.c +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "Below minimum frame rate" msgstr "" -#: ports/cxd56/common-hal/sdioio/SDCard.c -msgid "SDCard init" +#: py/argcheck.c +msgid "function doesn't take keyword arguments" msgstr "" -#: ports/stm/common-hal/sdioio/SDCard.c +#: py/argcheck.c py/bc.c py/objnamedtuple.c shared-bindings/_eve/__init__.c +#: shared-bindings/time/__init__.c #, c-format -msgid "SDIO GetCardInfo Error %d" +msgid "function takes %d positional arguments but %d were given" msgstr "" -#: ports/espressif/common-hal/sdioio/SDCard.c -#: ports/stm/common-hal/sdioio/SDCard.c +#: py/argcheck.c #, c-format -msgid "SDIO Init Error %x" +msgid "function missing %d required positional arguments" msgstr "" -#: ports/espressif/common-hal/busio/SPI.c -msgid "SPI configuration failed" +#: py/argcheck.c +#, c-format +msgid "function expected at most %d arguments, got %d" msgstr "" -#: ports/stm/common-hal/busio/SPI.c -msgid "SPI init error" +#: py/argcheck.c shared-bindings/wifi/Radio.c +msgid "'%q' argument required" msgstr "" -#: ports/raspberrypi/common-hal/busio/SPI.c -msgid "SPI peripheral in use" +#: py/argcheck.c +msgid "extra positional arguments given" msgstr "" -#: ports/stm/common-hal/busio/SPI.c -msgid "SPI re-init" +#: py/argcheck.c py/bc.c py/objnamedtuple.c +#: shared-bindings/traceback/__init__.c +msgid "unexpected keyword argument '%q'" msgstr "" -#: shared-bindings/is31fl3741/FrameBuffer.c -msgid "Scale dimensions must divide by 3" +#: py/argcheck.c +msgid "extra keyword arguments given" msgstr "" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Scan already in progress. Stop with stop_scan." +#: py/argcheck.c shared-bindings/_stage/__init__.c +#: shared-bindings/digitalio/DigitalInOut.c shared-bindings/picogame/__init__.c +msgid "argument num/types mismatch" msgstr "" -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c -msgid "Serializer in use" +#: py/argcheck.c +msgid "keyword argument(s) not implemented - use normal args instead" msgstr "" -#: shared-bindings/ssl/SSLContext.c -msgid "Server side context cannot have hostname" +#: py/argcheck.c +msgid "%q must be %d" msgstr "" -#: ports/cxd56/common-hal/camera/Camera.c -msgid "Size not supported" +#: py/argcheck.c +msgid "%q must be >= %d" msgstr "" -#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c -#: shared-bindings/nvm/ByteArray.c -msgid "Slice and value different lengths." +#: py/argcheck.c shared-bindings/gifio/GifWriter.c +#: shared-module/_airlift/__init__.c +msgid "%q must be <= %d" +msgstr "" + +#: py/argcheck.c py/runtime.c shared-bindings/bitmapfilter/__init__.c +#: shared-module/audiodelays/MultiTapDelay.c shared-module/synthio/Note.c +#: shared-module/synthio/__init__.c +msgid "%q must be of type %q, not %q" msgstr "" -#: 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" +#: py/argcheck.c +msgid "%q length must be %d-%d" msgstr "" -#: ports/espressif/common-hal/socketpool/SocketPool.c -#: ports/raspberrypi/common-hal/socketpool/SocketPool.c -#: ports/zephyr-cp/common-hal/socketpool/SocketPool.c -msgid "SocketPool can only be used with wifi.radio" +#: py/argcheck.c +msgid "%q length must be >= %d" msgstr "" -#: shared-bindings/aesio/aes.c -msgid "Source and destination buffers must be the same length" +#: py/argcheck.c shared-module/_airlift/__init__.c +msgid "%q length must be <= %d" msgstr "" -#: shared-bindings/paralleldisplaybus/ParallelBus.c -msgid "Specify exactly one of data0 or data_pins" +#: py/argcheck.c shared-bindings/usb_hid/Device.c +msgid "%q length must be %d" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Stack overflow. Increase stack size." +#: py/argcheck.c shared-module/audiofilters/__init__.c +msgid "%q in %q must be of type %q, not %q" msgstr "" -#: shared-bindings/alarm/time/TimeAlarm.c -msgid "Supply one of monotonic_time or epoch_time" +#: py/asmthumb.c +msgid "too many locals for native method" msgstr "" -#: shared-bindings/gnss/GNSS.c -msgid "System entry must be gnss.SatelliteSystem" +#: py/asmxtensa.c +msgid "ERROR: xtensa %q out of range" msgstr "" -#: ports/stm/common-hal/microcontroller/Processor.c -msgid "Temperature read timed out" +#: py/asmxtensa.c +msgid "ERROR: %q %q not word-aligned" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "The `microcontroller` module was used to boot into safe mode." +#: py/bc.c py/objnamedtuple.c +msgid "%q() takes %d positional arguments but %d were given" msgstr "" -#: py/obj.c -msgid "The above exception was the direct cause of the following exception:" +#: py/bc.c py/objnamedtuple.c +msgid "function got multiple values for argument '%q'" msgstr "" -#: shared-bindings/rgbmatrix/RGBMatrix.c -msgid "The length of rgb_pins must be 6, 12, 18, 24, or 30" +#: py/bc.c +msgid "unexpected keyword argument" msgstr "" -#: shared-module/audiocore/__init__.c -msgid "The sample's %q does not match" +#: py/bc.c +#, c-format +msgid "function missing required positional argument #%d" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Third-party firmware fatal error." +#: py/bc.c +msgid "function missing required keyword argument '%q'" msgstr "" -#: shared-module/imagecapture/ParallelImageCapture.c -msgid "This microcontroller does not support continuous capture." +#: py/bc.c +msgid "function missing keyword-only argument" msgstr "" -#: shared-module/paralleldisplaybus/ParallelBus.c -msgid "" -"This microcontroller only supports data0=, not data_pins=, because it " -"requires contiguous pins." +#: py/binary.c py/objarray.c +msgid "bad typecode" msgstr "" -#: shared-bindings/displayio/TileGrid.c -msgid "Tile height must exactly divide bitmap height" +#: py/binary.c +msgid "integer out of range" msgstr "" -#: shared-bindings/displayio/TileGrid.c shared-module/displayio/TileGrid.c -msgid "Tile index out of bounds" +#: py/builtinevex.c +msgid "bad compile mode" msgstr "" -#: shared-bindings/displayio/TileGrid.c -msgid "Tile width must exactly divide bitmap width" +#: py/builtinhelp.c +msgid "Plus any modules on the filesystem\n" msgstr "" -#: shared-bindings/alarm/time/TimeAlarm.c -msgid "Time is in the past." +#: py/builtinhelp.c +msgid "object " msgstr "" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -#, c-format -msgid "Timeout is too long: Maximum timeout length is %d seconds" +#: py/builtinhelp.c +msgid " is of type %q\n" msgstr "" -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -msgid "Too many channels in sample" +#: py/builtinhelp.c +#, c-format +msgid "" +"Welcome to Adafruit CircuitPython %s!\n" +"\n" +"Visit circuitpython.org for more information.\n" +"\n" +"To list built-in modules type `help(\"modules\")`.\n" msgstr "" -#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c -msgid "Too many channels in sample." +#: py/builtinimport.c +msgid "script compilation not supported" msgstr "" -#: ports/espressif/common-hal/_bleio/Characteristic.c -msgid "Too many descriptors" +#: py/builtinimport.c +msgid "can't perform relative import" msgstr "" -#: shared-module/displayio/__init__.c -msgid "Too many display busses; forgot displayio.release_displays() ?" +#: py/builtinimport.c +msgid "module not found" msgstr "" -#: shared-module/displayio/__init__.c -msgid "Too many displays" +#: py/builtinimport.c +msgid "no module named '%q'" msgstr "" -#: ports/espressif/common-hal/_bleio/PacketBuffer.c -#: ports/nordic/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than %q" +#: py/builtinimport.c +msgid "relative import" msgstr "" -#: ports/raspberrypi/common-hal/alarm/touch/TouchAlarm.c -#: ports/stm/common-hal/alarm/touch/TouchAlarm.c -msgid "Touch alarms not available" +#: py/compile.c +msgid "can't assign to expression" msgstr "" -#: py/obj.c -msgid "Traceback (most recent call last):\n" +#: py/compile.c +msgid "multiple *x in assignment" msgstr "" -#: ports/stm/common-hal/busio/UART.c -msgid "UART de-init" +#: py/compile.c +msgid "non-default argument follows default argument" msgstr "" -#: ports/cxd56/common-hal/busio/UART.c ports/espressif/common-hal/busio/UART.c -#: ports/stm/common-hal/busio/UART.c -msgid "UART init" +#: py/compile.c +msgid "invalid micropython decorator" msgstr "" -#: ports/raspberrypi/common-hal/busio/UART.c -msgid "UART peripheral in use" +#: py/compile.c +msgid "invalid arch" msgstr "" -#: ports/stm/common-hal/busio/UART.c -msgid "UART re-init" +#: py/compile.c +msgid "can't delete expression" msgstr "" -#: ports/stm/common-hal/busio/UART.c -msgid "UART write" +#: py/compile.c +msgid "'break'/'continue' outside loop" msgstr "" -#: main.c -msgid "UID:" +#: py/compile.c +msgid "'return' outside function" msgstr "" -#: shared-module/usb_hid/Device.c -msgid "USB busy" +#: py/compile.c +msgid "import * not at module level" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "USB devices need more endpoints than are available." +#: py/compile.c +msgid "identifier redefined as global" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "USB devices specify too many interface names." +#: py/compile.c +msgid "no binding for nonlocal found" msgstr "" -#: shared-module/usb_hid/Device.c -msgid "USB error" +#: py/compile.c +msgid "identifier redefined as nonlocal" msgstr "" -#: shared-bindings/_bleio/UUID.c -msgid "UUID integer value must be 0-0xffff" +#: py/compile.c +msgid "can't declare nonlocal in outer code" msgstr "" -#: shared-bindings/_bleio/UUID.c -msgid "UUID string not 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'" +#: py/compile.c +msgid "default 'except' must be last" msgstr "" -#: shared-bindings/_bleio/UUID.c -msgid "UUID value is not str, int or byte buffer" +#: py/compile.c +msgid "async for/with outside async function" msgstr "" -#: ports/raspberrypi/common-hal/memorymap/AddressRange.c -msgid "Unable to access unaligned IO register" +#: py/compile.c +msgid "*x must be assignment target" 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" +#: py/compile.c +msgid "super() can't find self" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Unable to allocate to the heap." +#: py/compile.c +msgid "* arg after **" msgstr "" -#: ports/espressif/common-hal/busio/I2C.c -msgid "Unable to create lock" +#: py/compile.c +msgid "* arg after kwarg" msgstr "" -#: shared-module/i2cdisplaybus/I2CDisplayBus.c -#: shared-module/is31fl3741/IS31FL3741.c -#, c-format -msgid "Unable to find I2C Display at %x" +#: py/compile.c +msgid "too many args" msgstr "" -#: py/parse.c -msgid "Unable to init parser" +#: py/compile.c +msgid "LHS of keyword arg must be an id" msgstr "" -#: shared-module/displayio/OnDiskBitmap.c -msgid "Unable to read color palette data" +#: py/compile.c +msgid "positional arg after **" msgstr "" -#: ports/mimxrt10xx/common-hal/canio/CAN.c -msgid "Unable to send CAN Message: all Tx message buffers are busy" +#: py/compile.c +msgid "positional arg after keyword arg" msgstr "" -#: ports/espressif/common-hal/mdns/Server.c -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "Unable to start mDNS query" +#: py/compile.c py/parse.c +msgid "invalid syntax" msgstr "" -#: shared-bindings/nvm/ByteArray.c -msgid "Unable to write to nvm." +#: py/compile.c +msgid "expecting key:value for dict" msgstr "" -#: ports/raspberrypi/common-hal/memorymap/AddressRange.c -msgid "Unable to write to read-only memory" +#: py/compile.c +msgid "expecting just a value for set" msgstr "" -#: shared-bindings/alarm/SleepMemory.c -msgid "Unable to write to sleep_memory." +#: py/compile.c +msgid "'yield' outside function" msgstr "" -#: ports/nordic/common-hal/_bleio/UUID.c -msgid "Unexpected nrfx uuid type" +#: py/compile.c +msgid "'yield from' inside async function" msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown BLE error at %s:%d: %d" +#: py/compile.c +msgid "'await' outside function" msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown BLE error: %d" +#: py/compile.c +msgid "unknown type '%q'" msgstr "" -#: ports/espressif/common-hal/max3421e/Max3421E.c -#: ports/raspberrypi/common-hal/wifi/__init__.c -#, c-format -msgid "Unknown error code %d" +#: py/compile.c +msgid "annotation must be an identifier" msgstr "" -#: shared-bindings/wifi/Radio.c -#, c-format -msgid "Unknown failure %d" +#: py/compile.c +msgid "argument name reused" msgstr "" -#: ports/nordic/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown gatt error: 0x%04x" +#: py/compile.c +msgid "inline assembler must be a function" msgstr "" -#: ports/atmel-samd/common-hal/alarm/pin/PinAlarm.c -#: supervisor/shared/safe_mode.c -msgid "Unknown reason." +#: py/compile.c +msgid "unknown type" msgstr "" -#: ports/nordic/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown security error: 0x%04x" +#: py/compile.c +msgid "return annotation must be an identifier" msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown system firmware error at %s:%d: %d" +#: py/compile.c +msgid "expecting an assembler instruction" msgstr "" -#: ports/nordic/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown system firmware error: %04x" +#: py/compile.c +msgid "'label' requires 1 argument" msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown system firmware error: %d" +#: py/compile.c +msgid "label redefined" msgstr "" -#: shared-bindings/adafruit_pixelbuf/PixelBuf.c -#: shared-module/_pixelmap/PixelMap.c -#, c-format -msgid "Unmatched number of items on RHS (expected %d, got %d)." +#: py/compile.c +msgid "'align' requires 1 argument" msgstr "" -#: ports/nordic/common-hal/_bleio/__init__.c -msgid "" -"Unspecified issue. Can be that the pairing prompt on the other device was " -"declined or ignored." +#: py/compile.c +msgid "'data' requires at least 2 arguments" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "Unsupported colorspace" +#: py/compile.c +msgid "'data' requires integer arguments" msgstr "" -#: shared-module/displayio/bus_core.c -msgid "Unsupported display bus type" +#: py/compile.c +msgid "cannot emit native code for this architecture" msgstr "" -#: shared-module/audiocore/WaveFile.c -msgid "Unsupported format" +#: py/emitbc.c +msgid "bytecode overflow" msgstr "" -#: shared-bindings/hashlib/__init__.c -msgid "Unsupported hash algorithm" +#: py/emitinlinerv32.c +msgid "can only have up to 4 parameters for RV32 assembly" msgstr "" -#: ports/espressif/common-hal/socketpool/Socket.c -#: ports/zephyr-cp/common-hal/socketpool/Socket.c -msgid "Unsupported socket type" +#: py/emitinlinerv32.c +msgid "parameters must be registers in sequence a0 to a3" msgstr "" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/espressif/common-hal/dualbank/__init__.c -msgid "Update failed" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: expecting %q" msgstr "" -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Descriptor.c -msgid "Value length != required fixed length" +#: py/emitinlinerv32.c +msgid "opcode '%q': expecting %d arguments" msgstr "" -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Descriptor.c -msgid "Value length > max_length" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: out of range" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Version was invalid" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: unknown register" msgstr "" -#: ports/stm/common-hal/microcontroller/Processor.c -msgid "Voltage read timed out" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: undefined label '%q'" msgstr "" -#: main.c -msgid "WARNING: Your code filename has two extensions\n" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: must not be zero" msgstr "" -#: ports/nordic/common-hal/watchdog/WatchDogTimer.c -msgid "WatchDogTimer cannot be deinitialized once mode is set to RESET" +#: py/emitinlinerv32.c +msgid "opcode '%q': registers must be different" msgstr "" -#: py/builtinhelp.c -#, c-format -msgid "" -"Welcome to Adafruit CircuitPython %s!\n" -"\n" -"Visit circuitpython.org for more information.\n" -"\n" -"To list built-in modules type `help(\"modules\")`.\n" +#: py/emitinlinerv32.c +msgid "opcode '%q': malformed register list" msgstr "" -#: supervisor/shared/web_workflow/web_workflow.c -msgid "Wi-Fi: " +#: py/emitinlinerv32.c +msgid "opcode '%q': invalid stack adjustment" msgstr "" -#: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "Wifi is not enabled" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: wrong register(s)" msgstr "" -#: main.c -msgid "Woken up by alarm.\n" +#: py/emitinlinerv32.c +msgid "invalid RV32 instruction '%q'" msgstr "" -#: ports/espressif/common-hal/_bleio/PacketBuffer.c -#: ports/nordic/common-hal/_bleio/PacketBuffer.c -msgid "Writes not supported on Characteristic" +#: py/emitinlinethumb.c +msgid "can only have up to 4 parameters to Thumb assembly" msgstr "" -#: 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/meowmeow/mpconfigboard.h -msgid "You pressed both buttons at start up." +#: py/emitinlinethumb.c +msgid "parameters must be registers in sequence r0 to r3" msgstr "" -#: ports/espressif/boards/m5stack_core_basic/mpconfigboard.h -#: ports/espressif/boards/m5stack_core_fire/mpconfigboard.h -#: ports/espressif/boards/m5stack_stick_c/mpconfigboard.h -#: ports/espressif/boards/m5stack_stick_c_plus/mpconfigboard.h -#: ports/espressif/boards/m5stack_stick_c_plus2/mpconfigboard.h -msgid "You pressed button A at start up." +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' expects at most r%d" msgstr "" -#: ports/espressif/boards/m5stack_m5paper/mpconfigboard.h -msgid "You pressed button DOWN at start up." +#: py/emitinlinethumb.c py/emitinlinextensa.c +#, c-format +msgid "'%s' expects a register" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "You pressed the BOOT button at start up" +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' expects a special register" msgstr "" -#: ports/espressif/boards/adafruit_feather_esp32c6_4mbflash_nopsram/mpconfigboard.h -#: ports/espressif/boards/adafruit_itsybitsy_esp32/mpconfigboard.h -#: ports/espressif/boards/waveshare_esp32_c6_lcd_1_47/mpconfigboard.h -msgid "You pressed the BOOT button at start up." +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' expects an FPU register" msgstr "" -#: ports/espressif/boards/adafruit_huzzah32_breakout/mpconfigboard.h -msgid "You pressed the GPIO0 button at start up." +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' expects {r0, r1, ...}" msgstr "" -#: ports/espressif/boards/espressif_esp32_lyrat/mpconfigboard.h -msgid "You pressed the Rec button at start up." +#: py/emitinlinethumb.c py/emitinlinextensa.c +#, c-format +msgid "'%s' expects an integer" msgstr "" -#: ports/espressif/boards/adafruit_feather_esp32_v2/mpconfigboard.h -msgid "You pressed the SW38 button at start up." +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' integer 0x%x doesn't fit in mask 0x%x" msgstr "" -#: ports/espressif/boards/hardkernel_odroid_go/mpconfigboard.h -#: ports/espressif/boards/vidi_x/mpconfigboard.h -msgid "You pressed the VOLUME button at start up." +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' expects an address of the form [a, b]" msgstr "" -#: ports/espressif/boards/m5stack_atom_echo/mpconfigboard.h -#: ports/espressif/boards/m5stack_atom_lite/mpconfigboard.h -#: ports/espressif/boards/m5stack_atom_matrix/mpconfigboard.h -#: ports/espressif/boards/m5stack_atom_u/mpconfigboard.h -msgid "You pressed the central button at start up." +#: py/emitinlinethumb.c py/emitinlinextensa.c +#, c-format +msgid "'%s' expects a label" msgstr "" -#: ports/nordic/boards/aramcon2_badge/mpconfigboard.h -msgid "You pressed the left button at start up." +#: py/emitinlinethumb.c py/emitinlinextensa.c +msgid "label '%q' not defined" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "You pressed the reset button during boot." +#: py/emitinlinethumb.c +#, c-format +msgid "unsupported Thumb instruction '%s' with %d arguments" msgstr "" -#: supervisor/shared/micropython.c -msgid "[truncated due to length]" +#: py/emitinlinethumb.c +msgid "branch not in range" msgstr "" -#: py/objtype.c -msgid "__init__() should return None" +#: py/emitinlinextensa.c +msgid "can only have up to 4 parameters to Xtensa assembly" msgstr "" -#: py/objtype.c -#, c-format -msgid "__init__() should return None, not '%s'" +#: py/emitinlinextensa.c +msgid "parameters must be registers in sequence a2 to a5" msgstr "" -#: py/objobject.c -msgid "__new__ arg must be a user-type" +#: py/emitinlinextensa.c +#, c-format +msgid "'%s' integer %d isn't within range %d..%d" msgstr "" -#: extmod/modbinascii.c extmod/modhashlib.c py/objarray.c -msgid "a bytes-like object is required" +#: py/emitinlinextensa.c +#, c-format +msgid "%d is not a multiple of %d" msgstr "" -#: shared-bindings/i2ctarget/I2CTarget.c -msgid "addresses is empty" +#: py/emitinlinextensa.c +#, c-format +msgid "unsupported Xtensa instruction '%s' with %d arguments" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "already playing" +#: py/emitnative.c +msgid "conversion to object" msgstr "" -#: py/compile.c -msgid "annotation must be an identifier" +#: py/emitnative.c +msgid "local '%q' used before type known" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "arange: cannot compute length" +#: py/emitnative.c +msgid "can't load from '%q'" msgstr "" -#: py/modbuiltins.c -msgid "arg is an empty sequence" +#: py/emitnative.c +msgid "can't load with '%q' index" msgstr "" -#: py/objobject.c -msgid "arg must be user-type" +#: py/emitnative.c +msgid "local '%q' has type '%q' but source is '%q'" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "argsort argument must be an ndarray" +#: py/emitnative.c +msgid "can't store '%q'" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "argsort is not implemented for flattened arrays" +#: py/emitnative.c +msgid "can't store to '%q'" msgstr "" -#: extmod/ulab/code/numpy/random/random.c -msgid "argument must be None, an integer or a tuple of integers" +#: py/emitnative.c +msgid "can't store with '%q' index" msgstr "" -#: py/compile.c -msgid "argument name reused" +#: py/emitnative.c +msgid "can't implicitly convert '%q' to 'bool'" msgstr "" -#: py/argcheck.c shared-bindings/_stage/__init__.c -#: shared-bindings/digitalio/DigitalInOut.c -msgid "argument num/types mismatch" +#: py/emitnative.c +msgid "'not' not implemented" msgstr "" -#: extmod/ulab/code/numpy/numerical.c extmod/ulab/code/numpy/transform.c -msgid "arguments must be ndarrays" +#: py/emitnative.c +msgid "can't do unary op of '%q'" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "array and index length must be equal" +#: py/emitnative.c +msgid "div/mod not implemented for uint" msgstr "" -#: extmod/ulab/code/numpy/io/io.c -msgid "array has too many dimensions" +#: py/emitnative.c +msgid "comparison of int and uint" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "array is too big" +#: py/emitnative.c +msgid "binary op %q not implemented" msgstr "" -#: py/objarray.c shared-bindings/alarm/SleepMemory.c -#: shared-bindings/memorymap/AddressRange.c shared-bindings/nvm/ByteArray.c -msgid "array/bytes required on right side" +#: py/emitnative.c +msgid "can't do binary op between '%q' and '%q'" msgstr "" -#: py/asmxtensa.c -msgid "asm overflow" +#: py/emitnative.c +msgid "casting" msgstr "" -#: py/compile.c -msgid "async for/with outside async function" +#: py/emitnative.c +msgid "return expected '%q' but got '%q'" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "attempt to get (arg)min/(arg)max of empty sequence" +#: py/emitnative.c +msgid "native raise" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "attempt to get argmin/argmax of an empty sequence" +#: py/emitnative.c +msgid "must raise an object" msgstr "" -#: py/objstr.c -msgid "attributes not supported" +#: py/emitnative.c +msgid "native yield" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "audio format not supported" +#: py/lexer.c +msgid "unicode name escapes" msgstr "" -#: extmod/ulab/code/ulab_tools.c -msgid "axis is out of bounds" +#: py/modbuiltins.c py/objstr.c +msgid "char not in range(0x110000)" msgstr "" -#: extmod/ulab/code/numpy/numerical.c extmod/ulab/code/ulab_tools.c -msgid "axis must be None, or an integer" +#: py/modbuiltins.c +msgid "chr() arg not in range(256)" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "axis too long" +#: py/modbuiltins.c +msgid "arg is an empty sequence" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "background value out of range of target" +#: py/modbuiltins.c +msgid "ord expects a character" msgstr "" -#: py/builtinevex.c -msgid "bad compile mode" +#: py/modbuiltins.c +#, c-format +msgid "ord() expected a character, but string of length %d found" msgstr "" -#: py/objstr.c -msgid "bad conversion specifier" +#: py/modbuiltins.c +msgid "3-arg pow() not supported" msgstr "" -#: py/objstr.c -msgid "bad format string" +#: py/modbuiltins.c +msgid "must use keyword argument for key function" msgstr "" -#: py/binary.c py/objarray.c -msgid "bad typecode" +#: py/moderrno.c +msgid "Operation not permitted" msgstr "" -#: py/emitnative.c -msgid "binary op %q not implemented" +#: py/moderrno.c +msgid "No such file/directory" msgstr "" -#: ports/espressif/common-hal/audiobusio/PDMIn.c -msgid "bit_depth must be 8, 16, 24, or 32." +#: py/moderrno.c +msgid "Input/output error" msgstr "" -#: shared-module/bitmapfilter/__init__.c -msgid "bitmap size and depth must match" +#: py/moderrno.c +msgid "Permission denied" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "bitmap sizes must match" +#: py/moderrno.c +msgid "File exists" msgstr "" -#: extmod/modrandom.c -msgid "bits must be 32 or less" +#: py/moderrno.c +msgid "No such device" msgstr "" -#: shared-bindings/audiodelays/Echo.c shared-bindings/audiodelays/PitchShift.c -#: shared-bindings/audiofilters/Distortion.c -#: shared-bindings/audiofilters/Filter.c shared-bindings/audiomixer/Mixer.c -msgid "bits_per_sample must be 8 or 16" +#: py/moderrno.c +msgid "No space left on device" msgstr "" -#: py/emitinlinethumb.c -msgid "branch not in range" +#: py/modmath.c shared-bindings/math/__init__.c +msgid "math domain error" msgstr "" -#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c -msgid "buffer is smaller than requested size" +#: py/modmath.c +msgid "negative factorial" msgstr "" -#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c -msgid "buffer size must be a multiple of element size" +#: py/modmicropython.c +msgid "schedule queue full" msgstr "" -#: shared-module/struct/__init__.c -msgid "buffer size must match format" +#: py/modstruct.c shared-bindings/picogame/Bitmap.c +#: shared-bindings/picogame/Canvas.c shared-bindings/picogame/Framebuffer.c +#: shared-module/picogame/__init__.c shared-module/struct/__init__.c +msgid "buffer too small" msgstr "" -#: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c -msgid "buffer slices must be of equal length" +#: py/modstruct.c +#, c-format +msgid "pack expected %d items for packing (got %d)" msgstr "" -#: py/modstruct.c shared-module/struct/__init__.c -msgid "buffer too small" +#: py/modthread.c +msgid "expecting a dict for keyword args" msgstr "" -#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c -msgid "buffer too small for requested bytes" +#: py/modweakref.c +msgid "not a heap object" msgstr "" -#: py/emitbc.c -msgid "bytecode overflow" +#: py/nativeglue.c +msgid "set unsupported" msgstr "" -#: py/objarray.c -msgid "bytes length not a multiple of item size" +#: py/nativeglue.c +msgid "slice unsupported" msgstr "" -#: py/objstr.c -msgid "bytes value out of range" +#: py/nativeglue.c +msgid "float unsupported" msgstr "" -#: ports/atmel-samd/bindings/samd/Clock.c -msgid "calibration is out of range" +#: py/obj.c shared-module/adafruit_pixelbuf/PixelBuf.c +msgid "can't convert %q to %q" msgstr "" -#: ports/atmel-samd/bindings/samd/Clock.c -msgid "calibration is read only" +#: py/obj.c +msgid "During handling of the above exception, another exception occurred:" msgstr "" -#: shared-module/vectorio/Circle.c shared-module/vectorio/Polygon.c -#: shared-module/vectorio/Rectangle.c -msgid "can only have one parent" +#: py/obj.c +msgid "The above exception was the direct cause of the following exception:" msgstr "" -#: py/emitinlinethumb.c -msgid "can only have up to 4 parameters to Thumb assembly" +#: py/obj.c +msgid " File \"%q\", line %d" msgstr "" -#: py/emitinlinextensa.c -msgid "can only have up to 4 parameters to Xtensa assembly" +#: py/obj.c +msgid " File \"%q\"" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "can only specify one unknown dimension" +#: py/obj.c +msgid ", in %q\n" msgstr "" -#: py/objtype.c -msgid "can't add special method to already-subclassed class" +#: py/obj.c +msgid "Traceback (most recent call last):\n" msgstr "" -#: py/compile.c -msgid "can't assign to expression" +#: py/obj.c +msgid "can't convert to float" msgstr "" -#: extmod/modasyncio.c -msgid "can't cancel self" +#: py/obj.c +#, c-format +msgid "can't convert %s to float" msgstr "" -#: py/obj.c shared-module/adafruit_pixelbuf/PixelBuf.c -msgid "can't convert %q to %q" +#: py/obj.c +msgid "can't convert to complex" msgstr "" #: py/obj.c @@ -2665,1482 +3247,1554 @@ msgstr "" msgid "can't convert %s to complex" msgstr "" +#: py/obj.c +msgid "expected tuple/list" +msgstr "" + #: py/obj.c #, c-format -msgid "can't convert %s to float" +msgid "object '%s' isn't a tuple or list" msgstr "" -#: py/objint.c py/runtime.c +#: py/obj.c +msgid "tuple/list has wrong length" +msgstr "" + +#: py/obj.c #, c-format -msgid "can't convert %s to int" +msgid "requested length %d but object has length %d" msgstr "" -#: py/objstr.c -msgid "can't convert '%q' object to %q implicitly" +#: py/obj.c +msgid "indices must be integers" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "can't convert complex to float" +#: py/obj.c +msgid "%q indices must be integers, not %s" msgstr "" #: py/obj.c -msgid "can't convert to complex" +msgid "object has no len" msgstr "" #: py/obj.c -msgid "can't convert to float" +#, c-format +msgid "object of type '%s' has no len()" msgstr "" -#: py/runtime.c -msgid "can't convert to int" +#: py/obj.c +msgid "object doesn't support item deletion" msgstr "" -#: py/objstr.c -msgid "can't convert to str implicitly" +#: py/obj.c +#, c-format +msgid "'%s' object doesn't support item deletion" msgstr "" -#: py/compile.c -msgid "can't declare nonlocal in outer code" +#: py/obj.c +msgid "object isn't subscriptable" msgstr "" -#: py/compile.c -msgid "can't delete expression" +#: py/obj.c +#, c-format +msgid "'%s' object isn't subscriptable" msgstr "" -#: py/emitnative.c -msgid "can't do binary op between '%q' and '%q'" +#: py/obj.c +msgid "object doesn't support item assignment" msgstr "" -#: py/emitnative.c -msgid "can't do unary op of '%q'" +#: py/obj.c +#, c-format +msgid "'%s' object doesn't support item assignment" msgstr "" -#: py/emitnative.c -msgid "can't implicitly convert '%q' to 'bool'" +#: py/obj.c +msgid "object with buffer protocol required" msgstr "" -#: py/runtime.c -msgid "can't import name %q" +#: py/objarray.c +msgid "bytes length not a multiple of item size" msgstr "" -#: py/emitnative.c -msgid "can't load from '%q'" +#: py/objarray.c py/objstr.c +msgid "string argument without an encoding" msgstr "" -#: py/emitnative.c -msgid "can't load with '%q' index" +#: py/objarray.c +msgid "memoryview: length is not a multiple of itemsize" msgstr "" -#: py/builtinimport.c -msgid "can't perform relative import" +#: py/objarray.c py/objstr.c +msgid "substring not found" msgstr "" -#: py/objgenerator.c -msgid "can't send non-None value to a just-started generator" +#: py/objarray.c py/objstr.c py/objstrunicode.c py/objtuple.c +#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c +#: shared-bindings/nvm/ByteArray.c +msgid "only slices with step=1 (aka None) are supported" msgstr "" -#: shared-module/sdcardio/SDCard.c -msgid "can't set 512 block size" +#: py/objarray.c +msgid "lhs and rhs should be compatible" msgstr "" -#: py/objexcept.c py/objnamedtuple.c -msgid "can't set attribute" +#: py/objarray.c shared-bindings/alarm/SleepMemory.c +#: shared-bindings/memorymap/AddressRange.c shared-bindings/nvm/ByteArray.c +msgid "array/bytes required on right side" msgstr "" -#: py/runtime.c -msgid "can't set attribute '%q'" +#: py/objarray.c +msgid "memoryview offset too large" msgstr "" -#: py/emitnative.c -msgid "can't store '%q'" +#: py/objcomplex.c +msgid "can't truncate-divide a complex number" msgstr "" -#: py/emitnative.c -msgid "can't store to '%q'" +#: py/objcomplex.c +msgid "complex divide by zero" msgstr "" -#: py/emitnative.c -msgid "can't store with '%q' index" +#: py/objcomplex.c +msgid "0.0 to a complex power" msgstr "" -#: py/objstr.c -msgid "" -"can't switch from automatic field numbering to manual field specification" +#: py/objdeque.c +msgid "full" msgstr "" -#: py/objstr.c -msgid "" -"can't switch from manual field specification to automatic field numbering" +#: py/objdeque.c +msgid "empty" +msgstr "" + +#: py/objdict.c +msgid "dict update sequence has wrong length" msgstr "" -#: py/objcomplex.c -msgid "can't truncate-divide a complex number" +#: py/objexcept.c py/objnamedtuple.c +msgid "can't set attribute" msgstr "" -#: extmod/modasyncio.c -msgid "can't wait" +#: py/objfloat.c py/parsenum.c +msgid "complex values not supported" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "cannot assign new shape" +#: py/objgenerator.c +msgid "generator already executing" msgstr "" -#: extmod/ulab/code/ndarray_operators.c -msgid "cannot cast output with casting rule" +#: py/objgenerator.c +msgid "can't send non-None value to a just-started generator" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "cannot convert complex to dtype" +#: py/objgenerator.c py/runtime.c +msgid "generator raised StopIteration" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "cannot convert complex type" +#: py/objgenerator.c +msgid "generator ignored GeneratorExit" msgstr "" -#: py/objtype.c -msgid "cannot create '%q' instances" +#: py/objint.c py/runtime.c +#, c-format +msgid "can't convert %s to int" msgstr "" -#: py/objtype.c -msgid "cannot create instance" +#: py/objint.c +msgid "float too big" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "cannot delete array elements" +#: py/objint.c shared-bindings/time/__init__.c +msgid "No long integer support" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "cannot reshape array" +#: py/objint.c py/sequence.c +msgid "small int overflow" msgstr "" -#: py/emitnative.c -msgid "casting" +#: py/objint.c shared-bindings/_bleio/Connection.c +#: shared-bindings/storage/__init__.c +msgid "%q=%q" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "channel re-init" +#: py/objint_impl.h +#, c-format +msgid "value would overflow a %d byte buffer" msgstr "" -#: shared-bindings/_stage/Text.c -msgid "chars buffer too small" +#: py/objint_impl.h +msgid "can't convert negative int to unsigned" msgstr "" -#: py/modbuiltins.c -msgid "chr() arg not in range(0x110000)" +#: py/objint_longlong.c py/parsenum.c +msgid "result overflows long long storage" msgstr "" -#: py/modbuiltins.c -msgid "chr() arg not in range(256)" +#: py/objint_longlong.c py/objint_mpz.c py/runtime.c +msgid "negative shift count" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "clip point must be (x,y) tuple" +#: py/objint_longlong.c py/objint_mpz.c py/runtime.c +msgid "negative power with no float support" msgstr "" -#: shared-bindings/msgpack/ExtType.c -msgid "code outside range 0~127" +#: py/objint_longlong.c py/objint_mpz.c +msgid "overflow converting long int to machine word" msgstr "" -#: shared-bindings/displayio/Palette.c -msgid "color buffer must be 3 bytes (RGB) or 4 bytes (RGB + pad byte)" +#: py/objint_mpz.c +msgid "pow() with 3 arguments requires integers" msgstr "" -#: shared-bindings/displayio/Palette.c -msgid "color buffer must be a buffer, tuple, list, or int" +#: py/objint_mpz.c +msgid "pow() 3rd argument cannot be 0" msgstr "" -#: shared-bindings/displayio/Palette.c -msgid "color buffer must be a bytearray or array of type 'b' or 'B'" +#: py/objobject.c +msgid "__new__ arg must be a user-type" msgstr "" -#: shared-bindings/displayio/Palette.c -msgid "color must be between 0x000000 and 0xffffff" +#: py/objobject.c +msgid "arg must be user-type" msgstr "" -#: py/emitnative.c -msgid "comparison of int and uint" +#: py/objrange.c py/objslice.c shared-bindings/random/__init__.c +msgid "%q step cannot be zero" msgstr "" -#: py/objcomplex.c -msgid "complex divide by zero" +#: py/objslice.c +msgid "Cannot subclass slice" msgstr "" -#: py/objfloat.c py/parsenum.c -msgid "complex values not supported" +#: py/objstr.c +msgid "unknown encoding: %q" msgstr "" -#: extmod/modzlib.c -msgid "compression header" +#: py/objstr.c +msgid "bytes value out of range" msgstr "" -#: py/emitnative.c -msgid "conversion to object" +#: py/objstr.c +msgid "join expects a list of str/bytes objects consistent with self object" msgstr "" -#: extmod/ulab/code/numpy/filter.c -msgid "convolve arguments must be linear arrays" +#: py/objstr.c +msgid "empty separator" msgstr "" -#: extmod/ulab/code/numpy/filter.c -msgid "convolve arguments must be ndarrays" +#: py/objstr.c +msgid "rsplit(None,n)" msgstr "" -#: extmod/ulab/code/numpy/filter.c -msgid "convolve arguments must not be empty" +#: py/objstr.c +msgid "bad format string" msgstr "" -#: extmod/ulab/code/numpy/io/io.c -msgid "corrupted file" +#: py/objstr.c +#, c-format +msgid "unmatched '%c' in format" msgstr "" -#: extmod/ulab/code/numpy/poly.c -msgid "could not invert Vandermonde matrix" +#: py/objstr.c +msgid "bad conversion specifier" msgstr "" -#: shared-module/sdcardio/SDCard.c -msgid "couldn't determine SD card version" +#: py/objstr.c +msgid "end of format while looking for conversion specifier" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "cross is defined for 1D arrays of length 3" +#: py/objstr.c +#, c-format +msgid "unknown conversion specifier %c" msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "data must be iterable" +#: py/objstr.c +msgid "expected ':' after format specifier" msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "data must be of equal length" +#: py/objstr.c +msgid "" +"can't switch from automatic field numbering to manual field specification" msgstr "" -#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c -#, c-format -msgid "data pin #%d in use" +#: py/objstr.c +msgid "%q index out of range" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "data type not understood" +#: py/objstr.c +msgid "attributes not supported" msgstr "" -#: py/parsenum.c -msgid "decimal numbers not supported" +#: py/objstr.c +msgid "" +"can't switch from manual field specification to automatic field numbering" msgstr "" -#: py/compile.c -msgid "default 'except' must be last" +#: py/objstr.c +msgid "invalid format specifier" msgstr "" -#: shared-bindings/msgpack/__init__.c -msgid "default is not a function" +#: py/objstr.c +msgid "sign not allowed in string format specifier" msgstr "" -#: shared-bindings/audiobusio/PDMIn.c -msgid "" -"destination buffer must be a bytearray or array of type 'B' for bit_depth = 8" +#: py/objstr.c +msgid "sign not allowed with integer format specifier 'c'" msgstr "" -#: shared-bindings/audiobusio/PDMIn.c -msgid "destination buffer must be an array of type 'H' for bit_depth = 16" +#: py/objstr.c +msgid "unknown format code '%c' for object of type '%q'" msgstr "" -#: py/objdict.c -msgid "dict update sequence has wrong length" +#: py/objstr.c +msgid "'=' alignment not allowed in string format specifier" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "diff argument must be an ndarray" +#: py/objstr.c +msgid "format needs a dict" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "differentiation order out of range" +#: py/objstr.c +msgid "incomplete format key" msgstr "" -#: extmod/ulab/code/numpy/transform.c -msgid "dimensions do not match" +#: py/objstr.c +msgid "incomplete format" msgstr "" -#: py/emitnative.c -msgid "div/mod not implemented for uint" +#: py/objstr.c +msgid "format string needs more arguments" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "divide by zero" +#: py/objstr.c +#, c-format +msgid "%%c needs int or char" msgstr "" -#: py/runtime.c -msgid "division by zero" +#: py/objstr.c +#, c-format +msgid "unsupported format character '%c' (0x%x) at index %d" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "dtype must be float, or complex" +#: py/objstr.c +msgid "format string didn't convert all arguments" msgstr "" -#: extmod/ulab/code/ndarray_operators.c -msgid "dtype of int32 is not supported" +#: py/objstr.c +msgid "non-hex digit" msgstr "" -#: py/objdeque.c -msgid "empty" +#: py/objstr.c +msgid "can't convert to str implicitly" msgstr "" -#: extmod/ulab/code/numpy/io/io.c -msgid "empty file" +#: py/objstr.c +msgid "can't convert '%q' object to %q implicitly" msgstr "" -#: extmod/modasyncio.c extmod/modheapq.c -msgid "empty heap" +#: py/objstrunicode.c +#, c-format +msgid "string indices must be integers, not %s" msgstr "" -#: py/objstr.c -msgid "empty separator" +#: py/objstrunicode.c +msgid "string index out of range" msgstr "" -#: shared-bindings/random/__init__.c -msgid "empty sequence" +#: py/objtemplate.c +msgid "expected str or Interpolation" msgstr "" -#: py/objstr.c -msgid "end of format while looking for conversion specifier" +#: py/objtype.c +msgid "Call super().__init__() before accessing native object." msgstr "" -#: shared-bindings/alarm/time/TimeAlarm.c -msgid "epoch_time not supported on this board" +#: py/objtype.c +msgid "__init__() should return None" msgstr "" -#: ports/nordic/common-hal/busio/UART.c +#: py/objtype.c #, c-format -msgid "error = 0x%08lX" +msgid "__init__() should return None, not '%s'" msgstr "" -#: py/runtime.c -msgid "exceptions must derive from BaseException" +#: py/objtype.c py/runtime.c +msgid "unreadable attribute" msgstr "" -#: py/objstr.c -msgid "expected ':' after format specifier" +#: py/objtype.c py/runtime.c +msgid "object not callable" msgstr "" -#: py/obj.c -msgid "expected tuple/list" +#: py/objtype.c py/runtime.c shared-module/atexit/__init__.c +msgid "'%q' object isn't callable" msgstr "" -#: py/modthread.c -msgid "expecting a dict for keyword args" +#: py/objtype.c +msgid "type takes 1 or 3 arguments" msgstr "" -#: py/compile.c -msgid "expecting an assembler instruction" +#: py/objtype.c +msgid "can't create instance" msgstr "" -#: py/compile.c -msgid "expecting just a value for set" +#: py/objtype.c +msgid "can't create '%q' instances" msgstr "" -#: py/compile.c -msgid "expecting key:value for dict" +#: py/objtype.c +msgid "can't add special method to already-subclassed class" msgstr "" -#: shared-bindings/msgpack/__init__.c -msgid "ext_hook is not a function" +#: py/objtype.c +msgid "type isn't an acceptable base type" msgstr "" -#: py/argcheck.c -msgid "extra keyword arguments given" +#: py/objtype.c +msgid "type '%q' isn't an acceptable base type" msgstr "" -#: py/argcheck.c -msgid "extra positional arguments given" +#: py/objtype.c +msgid "multiple inheritance not supported" msgstr "" -#: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/gifio/OnDiskGif.c -#: shared-bindings/synthio/__init__.c shared-module/gifio/GifWriter.c -msgid "file must be a file opened in byte mode" +#: py/objtype.c +msgid "multiple bases have instance lay-out conflict" msgstr "" -#: shared-bindings/traceback/__init__.c -msgid "file write is not available" +#: py/objtype.c +msgid "first argument to super() must be type" msgstr "" -#: shared-bindings/storage/__init__.c -msgid "filesystem must provide mount method" +#: py/objtype.c +msgid "issubclass() arg 2 must be a class or a tuple of classes" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "first argument must be a callable" +#: py/objtype.c +msgid "issubclass() arg 1 must be a class" msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "first argument must be a function" +#: py/parse.c +msgid "not a constant" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "first argument must be a tuple of ndarrays" +#: py/parse.c +msgid "Unable to init parser" msgstr "" -#: extmod/ulab/code/numpy/transform.c extmod/ulab/code/numpy/vector.c -msgid "first argument must be an ndarray" +#: py/parse.c +msgid "unexpected indent" msgstr "" -#: py/objtype.c -msgid "first argument to super() must be type" +#: py/parse.c +msgid "unindent doesn't match any outer indent level" msgstr "" -#: extmod/ulab/code/scipy/linalg/linalg.c -msgid "first two arguments must be ndarrays" +#: py/parse.c +msgid "malformed f-string" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "flattening order must be either 'C', or 'F'" +#: py/parsenum.c +msgid "invalid syntax for integer" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "flip argument must be an ndarray" +#: py/parsenum.c +#, c-format +msgid "invalid syntax for integer with base %d" msgstr "" -#: py/objint.c -msgid "float too big" +#: py/parsenum.c +msgid "invalid syntax for number" msgstr "" -#: py/nativeglue.c -msgid "float unsupported" +#: py/parsenum.c +msgid "decimal numbers not supported" msgstr "" -#: shared-bindings/_stage/Text.c -msgid "font must be 2048 bytes long" +#: py/persistentcode.c +msgid "incompatible .mpy file" msgstr "" -#: extmod/moddeflate.c -msgid "format" +#: py/persistentcode.c +msgid "MicroPython .mpy file; use CircuitPython mpy-cross" msgstr "" -#: py/objstr.c -msgid "format requires a dict" +#: py/persistentcode.c +msgid "native code in .mpy unsupported" msgstr "" -#: py/objdeque.c -msgid "full" +#: py/persistentcode.c +msgid "incompatible .mpy arch" msgstr "" -#: py/argcheck.c -msgid "function doesn't take keyword arguments" +#: py/persistentcode.c +msgid "function must be bytecode" msgstr "" -#: py/argcheck.c -#, c-format -msgid "function expected at most %d arguments, got %d" +#: py/proto.c shared-bindings/digitalio/DigitalInOutProtocol.c +msgid "'%q' object does not support '%q'" msgstr "" -#: py/bc.c py/objnamedtuple.c -msgid "function got multiple values for argument '%q'" +#: py/qstr.c +msgid "name too long" msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "function has the same sign at the ends of interval" +#: py/runtime.c +msgid "name not defined" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "function is defined for ndarrays only" +#: py/runtime.c +msgid "name '%q' isn't defined" msgstr "" -#: extmod/ulab/code/numpy/carray/carray.c -msgid "function is implemented for ndarrays only" +#: py/runtime.c +msgid "unsupported type for operator" msgstr "" -#: py/argcheck.c -#, c-format -msgid "function missing %d required positional arguments" +#: py/runtime.c +msgid "unsupported type for %q: '%s'" msgstr "" -#: py/bc.c -msgid "function missing keyword-only argument" +#: py/runtime.c +msgid "unsupported types for %q: '%q', '%q'" msgstr "" -#: py/bc.c -msgid "function missing required keyword argument '%q'" +#: py/runtime.c +msgid "wrong number of values to unpack" msgstr "" -#: py/bc.c +#: py/runtime.c #, c-format -msgid "function missing required positional argument #%d" +msgid "need more than %d values to unpack" msgstr "" -#: py/argcheck.c py/bc.c py/objnamedtuple.c shared-bindings/_eve/__init__.c -#: shared-bindings/time/__init__.c +#: py/runtime.c #, c-format -msgid "function takes %d positional arguments but %d were given" +msgid "too many values to unpack (expected %d)" msgstr "" -#: py/objgenerator.c -msgid "generator already executing" +#: py/runtime.c +msgid "type object '%q' has no attribute '%q'" msgstr "" -#: py/objgenerator.c -msgid "generator ignored GeneratorExit" +#: py/runtime.c +msgid "module '%q' has no attribute '%q'" msgstr "" -#: py/objgenerator.c py/runtime.c -msgid "generator raised StopIteration" +#: py/runtime.c +msgid "'%s' object has no attribute '%q'" msgstr "" -#: shared-bindings/_stage/Layer.c -msgid "graphic must be 2048 bytes long" +#: py/runtime.c +msgid "can't set attribute '%q'" msgstr "" -#: extmod/modhashlib.c -msgid "hash is final" +#: py/runtime.c +msgid "object not iterable" msgstr "" -#: extmod/modheapq.c -msgid "heap must be a list" +#: py/runtime.c +msgid "'%q' object isn't iterable" msgstr "" -#: py/compile.c -msgid "identifier redefined as global" +#: py/runtime.c +msgid "object not an iterator" msgstr "" -#: py/compile.c -msgid "identifier redefined as nonlocal" +#: py/runtime.c +msgid "'%q' object isn't an iterator" msgstr "" -#: py/compile.c -msgid "import * not at module level" +#: py/runtime.c +msgid "exceptions must derive from BaseException" msgstr "" -#: py/persistentcode.c -msgid "incompatible .mpy arch" +#: py/runtime.c +msgid "can't import name %q" msgstr "" -#: py/persistentcode.c -msgid "incompatible .mpy file" +#: py/runtime.c +msgid "memory allocation failed, heap is locked" msgstr "" -#: py/objstr.c -msgid "incomplete format" +#: py/runtime.c +#, c-format +msgid "memory allocation failed, allocating %u bytes" msgstr "" -#: py/objstr.c -msgid "incomplete format key" +#: py/runtime.c +msgid "can't convert to int" msgstr "" -#: extmod/modbinascii.c -msgid "incorrect padding" +#: py/runtime.c +msgid "division by zero" msgstr "" -#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/transform.c -msgid "index is out of bounds" +#: py/runtime.c +msgid "maximum recursion depth exceeded" msgstr "" -#: shared-bindings/_pixelmap/PixelMap.c -msgid "index must be tuple or int" +#: py/sequence.c shared-bindings/displayio/Group.c +msgid "object not in sequence" msgstr "" -#: extmod/ulab/code/numpy/numerical.c extmod/ulab/code/ulab_tools.c -#: ports/espressif/common-hal/pulseio/PulseIn.c -#: shared-bindings/bitmaptools/__init__.c -msgid "index out of range" +#: py/stream.c shared-bindings/getpass/__init__.c +msgid "stream operation not supported" msgstr "" -#: py/obj.c -msgid "indices must be integers" +#: py/vm.c +msgid "local variable referenced before assignment" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "indices must be integers, slices, or Boolean lists" +#: py/vm.c +msgid "no active exception to reraise" msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "initial values must be iterable" +#: py/vm.c +msgid "opcode" msgstr "" -#: shared-bindings/_bleio/Characteristic.c shared-bindings/_bleio/Descriptor.c -msgid "initial_value length is wrong" +#: shared-bindings/_bleio/Adapter.c +msgid "Cannot create a new Adapter; use _bleio.adapter;" msgstr "" -#: py/compile.c -msgid "inline assembler must be a function" +#: shared-bindings/_bleio/Adapter.c +msgid "Could not set address" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "input and output dimensions differ" +#: shared-bindings/_bleio/Adapter.c +#, c-format +msgid "interval must be in range %s-%s" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "input and output shapes differ" +#: shared-bindings/_bleio/Adapter.c +msgid "Cannot have scan responses for extended, connectable advertisements." msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "input argument must be an integer, a tuple, or a list" +#: shared-bindings/_bleio/Adapter.c +msgid "Only connectable advertisements can be directed" msgstr "" -#: extmod/ulab/code/numpy/fft/fft_tools.c -msgid "input array length must be power of 2" +#: shared-bindings/_bleio/Adapter.c +msgid "non-zero timeout must be >= interval" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "input arrays are not compatible" +#: shared-bindings/_bleio/Adapter.c +msgid "window must be <= interval" msgstr "" -#: extmod/ulab/code/numpy/poly.c -msgid "input data must be an iterable" +#: shared-bindings/_bleio/Adapter.c +msgid "Prefix buffer must be on the heap" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "input dtype must be float or complex" +#: shared-bindings/_bleio/CharacteristicBuffer.c +msgid "CharacteristicBuffer writing not provided" msgstr "" -#: extmod/ulab/code/numpy/poly.c -msgid "input is not iterable" +#: shared-bindings/_bleio/Connection.c +msgid "" +"Connection has been disconnected and can no longer be used. Create a new " +"connection." msgstr "" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "input matrix is asymmetric" +#: shared-bindings/_bleio/PacketBuffer.c +#, c-format +msgid "Buffer too short by %d bytes" msgstr "" -#: extmod/ulab/code/numpy/linalg/linalg.c -#: extmod/ulab/code/scipy/linalg/linalg.c -msgid "input matrix is singular" +#: shared-bindings/_bleio/PacketBuffer.c +msgid "No connection: length cannot be determined" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "input must be 1- or 2-d" +#: shared-bindings/_bleio/UUID.c +msgid "UUID string not 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'" msgstr "" -#: extmod/ulab/code/numpy/carray/carray.c -msgid "input must be a 1D ndarray" +#: shared-bindings/_bleio/UUID.c +msgid "UUID value is not str, int or byte buffer" msgstr "" -#: extmod/ulab/code/scipy/linalg/linalg.c extmod/ulab/code/user/user.c -msgid "input must be a dense ndarray" +#: shared-bindings/_bleio/UUID.c +msgid "not a 128-bit UUID" msgstr "" -#: extmod/ulab/code/user/user.c shared-bindings/_eve/__init__.c -msgid "input must be an ndarray" +#: shared-bindings/_bleio/__init__.c shared-bindings/emmcio/EMMC.c +#: shared-bindings/memorymonitor/AllocationSize.c +#: shared-bindings/pulseio/PulseIn.c shared-module/bitmaptools/__init__.c +#: shared-module/displayio/legacy/Bitmap.c +#: shared-module/displayio/legacy/Group.c shared-module/displayio/lvgl/Bitmap.c +#: shared-module/displayio/lvgl/Group.c +msgid "Read-only" msgstr "" -#: extmod/ulab/code/numpy/carray/carray.c -msgid "input must be an ndarray, or a scalar" +#: shared-bindings/_pew/PewPew.c +msgid "Incorrect buffer size" msgstr "" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "input must be one-dimensional" +#: shared-bindings/_pixelmap/PixelMap.c +msgid "nested index must be int" msgstr "" -#: extmod/ulab/code/ulab_tools.c -msgid "input must be square matrix" +#: shared-bindings/_pixelmap/PixelMap.c +msgid "index must be tuple or int" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "input must be tuple, list, range, or ndarray" +#: shared-bindings/_stage/Layer.c +msgid "map buffer too small" msgstr "" -#: extmod/ulab/code/numpy/poly.c -msgid "input vectors must be of equal length" +#: shared-bindings/_stage/Text.c +msgid "chars buffer too small" msgstr "" -#: extmod/ulab/code/numpy/approx.c -msgid "interp is defined for 1D iterables of equal length" +#: shared-bindings/adafruit_bus_device/spi_device/SPIDevice.c +msgid "Pin is input only" msgstr "" -#: shared-bindings/_bleio/Adapter.c +#: shared-bindings/adafruit_pixelbuf/PixelBuf.c +#: shared-module/_pixelmap/PixelMap.c #, c-format -msgid "interval must be in range %s-%s" +msgid "Unmatched number of items on RHS (expected %d, got %d)." msgstr "" -#: py/compile.c -msgid "invalid arch" +#: shared-bindings/aesio/aes.c +msgid "Key must be 16, 24, or 32 bytes long" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -#, c-format -msgid "invalid bits_per_pixel %d, must be, 1, 2, 4, 8, 16, 24, or 32" +#: shared-bindings/aesio/aes.c +msgid "Requested AES mode is unsupported" msgstr "" -#: shared-module/ssl/SSLSocket.c -msgid "invalid cert" +#: shared-bindings/aesio/aes.c +msgid "Source and destination buffers must be the same length" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -#, c-format -msgid "invalid element size %d for bits_per_pixel %d\n" +#: shared-bindings/aesio/aes.c +msgid "ECB only operates on 16 bytes at a time" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -#, c-format -msgid "invalid element_size %d, must be, 1, 2, or 4" +#: shared-bindings/aesio/aes.c +msgid "CBC blocks must be multiples of 16 bytes" msgstr "" -#: shared-bindings/traceback/__init__.c -msgid "invalid exception" +#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c +#: shared-bindings/nvm/ByteArray.c +msgid "Slice and value different lengths." msgstr "" -#: py/objstr.c -msgid "invalid format specifier" +#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c +#: shared-bindings/nvm/ByteArray.c +msgid "Array values should be single bytes." msgstr "" -#: shared-bindings/wifi/Radio.c -msgid "invalid hostname" +#: shared-bindings/alarm/SleepMemory.c +msgid "Unable to write to sleep_memory." msgstr "" -#: shared-module/ssl/SSLSocket.c -msgid "invalid key" +#: shared-bindings/alarm/__init__.c +msgid "Expected a kind of %q" msgstr "" -#: py/compile.c -msgid "invalid micropython decorator" +#: shared-bindings/alarm/time/TimeAlarm.c shared-bindings/time/__init__.c +msgid "RTC is not supported on this board" msgstr "" -#: ports/espressif/common-hal/espcamera/Camera.c -msgid "invalid setting" +#: shared-bindings/alarm/time/TimeAlarm.c +msgid "Supply one of monotonic_time or epoch_time" msgstr "" -#: shared-bindings/random/__init__.c -msgid "invalid step" +#: shared-bindings/alarm/time/TimeAlarm.c +msgid "epoch_time not supported on this board" msgstr "" -#: py/compile.c py/parse.c -msgid "invalid syntax" +#: shared-bindings/alarm/time/TimeAlarm.c +msgid "Time is in the past." msgstr "" -#: py/parsenum.c -msgid "invalid syntax for integer" +#: shared-bindings/analogbufio/BufferedIn.c +msgid "%q must be a bytearray or array of type 'H' or 'B'" msgstr "" -#: py/parsenum.c -#, c-format -msgid "invalid syntax for integer with base %d" +#: shared-bindings/audiobusio/PDMIn.c +msgid "%q must be multiple of 8." msgstr "" -#: py/parsenum.c -msgid "invalid syntax for number" +#: shared-bindings/audiobusio/PDMIn.c shared-bindings/audioi2sin/I2SIn.c +#: shared-bindings/usb_host_audio/USBIn.c +msgid "Cannot record to a file" msgstr "" -#: py/objtype.c -msgid "issubclass() arg 1 must be a class" +#: shared-bindings/audiobusio/PDMIn.c shared-bindings/audioi2sin/I2SIn.c +#: shared-bindings/usb_host_audio/USBIn.c +msgid "Destination capacity is smaller than destination_length." msgstr "" -#: py/objtype.c -msgid "issubclass() arg 2 must be a class or a tuple of classes" +#: shared-bindings/audiobusio/PDMIn.c +msgid "destination buffer must be an array of type 'H' for bit_depth = 16" msgstr "" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "iterations did not converge" +#: shared-bindings/audiobusio/PDMIn.c +msgid "" +"destination buffer must be a bytearray or array of type 'B' for bit_depth = 8" msgstr "" -#: py/objstr.c -msgid "join expects a list of str/bytes objects consistent with self object" +#: shared-bindings/audiocore/RawSample.c +msgid "%q must be a bytearray or array of type 'h', 'H', 'b', or 'B'" msgstr "" -#: py/argcheck.c -msgid "keyword argument(s) not implemented - use normal args instead" +#: shared-bindings/audiocore/RawSample.c +msgid "Length of %q must be an even multiple of channel_count * type_size" msgstr "" -#: py/emitinlinethumb.c py/emitinlinextensa.c -msgid "label '%q' not defined" +#: shared-bindings/audiodelays/Chorus.c shared-bindings/audiodelays/Echo.c +#: shared-bindings/audiodelays/Flanger.c +#: shared-bindings/audiodelays/GranularPitchShift.c +#: shared-bindings/audiodelays/MultiTapDelay.c +#: shared-bindings/audiodelays/PitchShift.c +#: shared-bindings/audiofilters/Distortion.c +#: shared-bindings/audiofilters/Filter.c shared-bindings/audiofilters/Phaser.c +#: shared-bindings/audiomixer/Mixer.c shared-module/audiotap/Tap.c +msgid "bits_per_sample must be 8 or 16" msgstr "" -#: py/compile.c -msgid "label redefined" +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "samples_signed must be true" msgstr "" -#: py/objarray.c -msgid "lhs and rhs should be compatible" +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "bits_per_sample must be 16" msgstr "" -#: py/emitnative.c -msgid "local '%q' has type '%q' but source is '%q'" +#: shared-bindings/audioi2sin/I2SIn.c shared-bindings/usb_host_audio/USBIn.c +#, c-format +msgid "invalid destination buffer, must be an array of type: %c" msgstr "" -#: py/emitnative.c -msgid "local '%q' used before type known" +#: shared-bindings/audioio/AudioOut.c shared-bindings/emmcio/EMMC.c +msgid "%q and %q must be different" msgstr "" -#: py/vm.c -msgid "local variable referenced before assignment" +#: shared-bindings/audiomp3/MP3Decoder.c shared-bindings/gifio/OnDiskGif.c +#: shared-bindings/synthio/__init__.c shared-module/gifio/GifWriter.c +msgid "file must be a file opened in byte mode" msgstr "" -#: ports/espressif/common-hal/canio/CAN.c -msgid "loopback + silent mode not supported by peripheral" +#: shared-bindings/bitmapfilter/__init__.c +msgid "" +"weights must be a sequence with an odd square number of elements (usually 9 " +"or 25)" msgstr "" -#: ports/espressif/common-hal/mdns/Server.c -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "mDNS already initialized" +#: shared-bindings/bitmapfilter/__init__.c +msgid "weights must be an object of type %q, %q, %q, or %q, not %q " msgstr "" -#: ports/espressif/common-hal/mdns/Server.c -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "mDNS only works with built-in WiFi" +#: shared-bindings/bitmaptools/__init__.c +msgid "clip point must be (x,y) tuple" msgstr "" -#: py/parse.c -msgid "malformed f-string" +#: shared-bindings/bitmaptools/__init__.c +msgid "source palette too large" msgstr "" -#: shared-bindings/_stage/Layer.c -msgid "map buffer too small" +#: shared-bindings/bitmaptools/__init__.c +msgid "Bitmap size and bits per value must match" msgstr "" -#: py/modmath.c shared-bindings/math/__init__.c -msgid "math domain error" +#: shared-bindings/bitmaptools/__init__.c +msgid "For L8 colorspace, input bitmap must have 8 bits per pixel" msgstr "" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "matrix is not positive definite" +#: shared-bindings/bitmaptools/__init__.c +msgid "For RGB colorspaces, input bitmap must have 16 bits per pixel" msgstr "" -#: ports/espressif/common-hal/_bleio/Descriptor.c -#: ports/nordic/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Descriptor.c -#, c-format -msgid "max_length must be 0-%d when fixed_length is %s" +#: shared-bindings/bitmaptools/__init__.c +msgid "Unsupported colorspace" msgstr "" -#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/random/random.c -msgid "maximum number of dimensions is " +#: shared-bindings/bitmaptools/__init__.c +msgid "Mask bitmap size must match the other bitmaps" msgstr "" -#: py/runtime.c -msgid "maximum recursion depth exceeded" +#: shared-bindings/bitmaptools/__init__.c +msgid "Mask bitmap must have 8 bits per pixel" msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "maxiter must be > 0" +#: shared-bindings/bitmaptools/__init__.c +msgid "out of range of target" msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "maxiter should be > 0" +#: shared-bindings/bitmaptools/__init__.c +msgid "value out of range of target" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "median argument must be an ndarray" +#: shared-bindings/bitmaptools/__init__.c +msgid "background value out of range of target" msgstr "" -#: py/runtime.c -#, c-format -msgid "memory allocation failed, allocating %u bytes" +#: shared-bindings/bitmaptools/__init__.c +msgid "Coordinate arrays types have different sizes" msgstr "" -#: py/runtime.c -msgid "memory allocation failed, heap is locked" +#: shared-bindings/bitmaptools/__init__.c +msgid "Coordinate arrays have different lengths" msgstr "" -#: py/objarray.c -msgid "memoryview offset too large" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element_size %d, must be, 1, 2, or 4" msgstr "" -#: py/objarray.c -msgid "memoryview: length is not a multiple of itemsize" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element size %d for bits_per_pixel %d\n" msgstr "" -#: extmod/modtime.c -msgid "mktime needs a tuple of length 8 or 9" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid bits_per_pixel %d, must be, 1, 2, 4, 8, 16, 24, or 32" msgstr "" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "mode must be complete, or reduced" +#: shared-bindings/bitmaptools/__init__.c +msgid "bitmap sizes must match" msgstr "" -#: py/builtinimport.c -msgid "module not found" +#: shared-bindings/bitmaptools/__init__.c +msgid "source_bitmap must have value_count of 2 or 65536" msgstr "" -#: ports/espressif/common-hal/wifi/Monitor.c -msgid "monitor init failed" +#: shared-bindings/bitmaptools/__init__.c +msgid "source_bitmap must have value_count of 65536" msgstr "" -#: extmod/ulab/code/numpy/poly.c -msgid "more degrees of freedom than data points" +#: shared-bindings/bitmaptools/__init__.c +msgid "source_bitmap must have value_count of 8" msgstr "" -#: py/compile.c -msgid "multiple *x in assignment" +#: shared-bindings/bitmaptools/__init__.c +msgid "unsupported colorspace for dither" msgstr "" -#: py/objtype.c -msgid "multiple bases have instance lay-out conflict" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Input buffer length (%d) must be a multiple of the strand count (%d)" msgstr "" -#: py/objtype.c -msgid "multiple inheritance not supported" +#: shared-bindings/board/__init__.c +msgid "No default %q bus" msgstr "" - -#: py/emitnative.c -msgid "must raise an object" + +#: shared-bindings/busdisplay/BusDisplay.c +msgid "%q must be 1 when %q is True" msgstr "" -#: py/modbuiltins.c -msgid "must use keyword argument for key function" +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +msgid "Display must have a 16 bit colorspace." msgstr "" -#: py/runtime.c -msgid "name '%q' is not defined" +#: shared-bindings/busio/UART.c shared-bindings/canio/CAN.c +msgid "tx and rx cannot both be None" msgstr "" -#: py/runtime.c -msgid "name not defined" +#: shared-bindings/busio/UART.c shared-bindings/displayio/Group.c +msgid "Must be a %q subclass." msgstr "" -#: py/qstr.c -msgid "name too long" +#: shared-bindings/canio/RemoteTransmissionRequest.c +msgid "RemoteTransmissionRequests limited to 8 bytes" msgstr "" -#: py/persistentcode.c -msgid "native code in .mpy unsupported" +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/ec/EllipticCurvePublicKey.c +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/padding/__init__.c +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "Only %q supported" msgstr "" -#: py/asmthumb.c -msgid "native method too big" +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/padding/__init__.c +msgid "label is not supported" msgstr "" -#: py/emitnative.c -msgid "native yield" +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/rsa/__init__.c +#: shared-bindings/hmac/__init__.c +msgid "key does not have the expected %q purpose" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "ndarray length overflows" +#: shared-bindings/digitalio/DigitalInOut.c +#: shared-bindings/i2cioexpander/IOPin.c +msgid "Cannot set value when direction is input." msgstr "" -#: py/runtime.c -#, c-format -msgid "need more than %d values to unpack" +#: shared-bindings/digitalio/DigitalInOut.c +#: shared-bindings/i2cioexpander/IOPin.c +msgid "Drive mode not used when direction is input." msgstr "" -#: py/modmath.c -msgid "negative factorial" +#: shared-bindings/digitalio/DigitalInOut.c +#: shared-bindings/i2cioexpander/IOPin.c +msgid "Pull not used when direction is output." msgstr "" -#: py/objint_longlong.c py/objint_mpz.c py/runtime.c -msgid "negative power with no float support" +#: shared-bindings/digitalio/DigitalInOutProtocol.c +msgid "%q object missing '%q' method" msgstr "" -#: py/objint_mpz.c py/runtime.c -msgid "negative shift count" +#: shared-bindings/digitalio/DigitalInOutProtocol.c +msgid "%q object missing '%q' attribute" msgstr "" -#: shared-bindings/_pixelmap/PixelMap.c -msgid "nested index must be int" +#: shared-bindings/digitalio/DigitalInOutProtocol.c +msgid "object does not support DigitalInOut protocol" msgstr "" -#: shared-module/sdcardio/SDCard.c -msgid "no SD card" +#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/memorymonitor/AllocationSize.c +#: shared-bindings/pulseio/PulseIn.c +msgid "Cannot delete values" msgstr "" -#: py/vm.c -msgid "no active exception to reraise" +#: 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 +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +msgid "Slices not supported" msgstr "" -#: py/compile.c -msgid "no binding for nonlocal found" +#: shared-bindings/displayio/Palette.c +msgid "color buffer must be a bytearray or array of type 'b' or 'B'" msgstr "" -#: shared-module/msgpack/__init__.c -msgid "no default packer" +#: shared-bindings/displayio/Palette.c +msgid "color buffer must be 3 bytes (RGB) or 4 bytes (RGB + pad byte)" msgstr "" -#: extmod/modrandom.c extmod/ulab/code/numpy/random/random.c -msgid "no default seed" +#: shared-bindings/displayio/Palette.c +msgid "color must be between 0x000000 and 0xffffff" msgstr "" -#: py/builtinimport.c -msgid "no module named '%q'" +#: shared-bindings/displayio/Palette.c +msgid "color buffer must be a buffer, tuple, list, or int" msgstr "" -#: shared-module/sdcardio/SDCard.c -msgid "no response from SD card" +#: shared-bindings/displayio/TileGrid.c +msgid "Tile width must exactly divide bitmap width" msgstr "" -#: ports/espressif/common-hal/espcamera/Camera.c py/objobject.c py/runtime.c -msgid "no such attribute" +#: shared-bindings/displayio/TileGrid.c +msgid "Tile height must exactly divide bitmap height" msgstr "" -#: ports/espressif/common-hal/_bleio/Connection.c -#: ports/nordic/common-hal/_bleio/Connection.c -msgid "non-UUID found in service_uuids_whitelist" +#: shared-bindings/displayio/TileGrid.c +msgid "New bitmap must be same size as old bitmap" msgstr "" -#: py/compile.c -msgid "non-default argument follows default argument" +#: shared-bindings/displayio/TileGrid.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-module/displayio/legacy/TileGrid.c +#: shared-module/displayio/lvgl/TileGrid.c +msgid "Tile index out of bounds" msgstr "" -#: py/objstr.c -msgid "non-hex digit found" +#: shared-bindings/dualbank/__init__.c +msgid "offset must be >= 0" msgstr "" -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "non-zero timeout must be > 0.01" +#: shared-bindings/emmcio/EMMC.c shared-bindings/i2cioexpander/IOExpander.c +msgid "address out of range" msgstr "" -#: shared-bindings/_bleio/Adapter.c -msgid "non-zero timeout must be >= interval" +#: shared-bindings/epaperdisplay/EPaperDisplay.c +msgid "Refresh too soon" msgstr "" -#: shared-bindings/_bleio/UUID.c -msgid "not a 128-bit UUID" +#: shared-bindings/framebufferio/FramebufferDisplay.c +msgid "Buffer is not a bytearray." msgstr "" -#: py/parse.c -msgid "not a constant" +#: shared-bindings/gnss/GNSS.c +msgid "System entry must be gnss.SatelliteSystem" msgstr "" -#: py/objstr.c -msgid "not all arguments converted during string formatting" +#: shared-bindings/hashlib/__init__.c shared-bindings/hmac/__init__.c +msgid "Unsupported hash algorithm" msgstr "" -#: py/objstr.c -msgid "not enough arguments for format string" +#: shared-bindings/i2cioexpander/IOExpander.c +msgid "num_pins must be 8 or 16" msgstr "" -#: extmod/ulab/code/numpy/carray/carray_tools.c -msgid "not implemented for complex dtype" +#: shared-bindings/i2ctarget/I2CTarget.c +msgid "addresses is empty" msgstr "" -#: extmod/ulab/code/numpy/bitwise.c -msgid "not supported for input types" +#: shared-bindings/ipaddress/IPv4Address.c shared-bindings/ipaddress/__init__.c +msgid "Not a valid IP string" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "number of points must be at least 2" +#: shared-bindings/ipaddress/IPv4Address.c +#, c-format +msgid "Address must be %d bytes long" msgstr "" -#: py/builtinhelp.c -msgid "object " +#: shared-bindings/ipaddress/__init__.c +msgid "Only int or string supported for ip" msgstr "" -#: py/obj.c -#, c-format -msgid "object '%s' isn't a tuple or list" +#: shared-bindings/is31fl3741/FrameBuffer.c +msgid "width must be greater than zero" msgstr "" -#: py/obj.c -msgid "object doesn't support item assignment" +#: shared-bindings/is31fl3741/FrameBuffer.c +msgid "Scale dimensions must divide by 3" msgstr "" -#: py/obj.c -msgid "object doesn't support item deletion" +#: shared-bindings/is31fl3741/FrameBuffer.c +msgid "LED mappings must match display size" msgstr "" -#: py/obj.c -msgid "object has no len" +#: shared-bindings/is31fl3741/IS31FL3741.c +msgid "Mapping must be a tuple" msgstr "" -#: py/obj.c -msgid "object isn't subscriptable" +#: shared-bindings/jpegio/JpegDecoder.c +msgid "%q must be of type %q, %q, or %q, not %q" msgstr "" -#: py/runtime.c -msgid "object not an iterator" +#: shared-bindings/mdns/Server.c +msgid "" +"Failed to add service TXT record; non-string or bytes found in txt_records" msgstr "" -#: py/objtype.c py/runtime.c -msgid "object not callable" +#: shared-bindings/memorymap/AddressRange.c +msgid "Address range wraps around" msgstr "" -#: py/sequence.c shared-bindings/displayio/Group.c -msgid "object not in sequence" +#: shared-bindings/microcontroller/Pin.c +msgid "%q contains duplicate pins" msgstr "" -#: py/runtime.c -msgid "object not iterable" +#: shared-bindings/microcontroller/Pin.c +msgid "%q and %q contain duplicate pins" msgstr "" -#: py/obj.c -#, c-format -msgid "object of type '%s' has no len()" +#: shared-bindings/mii/Ethernet.c shared-bindings/wifi/Radio.c +msgid "invalid hostname" msgstr "" -#: py/obj.c -msgid "object with buffer protocol required" +#: shared-bindings/msgpack/ExtType.c +msgid "code outside range 0~127" msgstr "" -#: py/objstr.c -msgid "odd-length string" +#: shared-bindings/msgpack/__init__.c +msgid "default is not a function" msgstr "" -#: supervisor/shared/web_workflow/web_workflow.c -msgid "off" +#: shared-bindings/msgpack/__init__.c +msgid "ext_hook is not a function" msgstr "" -#: extmod/ulab/code/utils/utils.c -msgid "offset is too large" +#: shared-bindings/nvm/ByteArray.c +msgid "Unable to write to nvm." msgstr "" -#: shared-bindings/dualbank/__init__.c -msgid "offset must be >= 0" +#: shared-bindings/os/__init__.c +msgid "No hardware random available" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "offset must be non-negative and no greater than buffer length" +#: shared-bindings/paralleldisplaybus/ParallelBus.c +msgid "Specify exactly one of data0 or data_pins" msgstr "" -#: ports/nordic/common-hal/audiobusio/PDMIn.c -#: ports/stm/common-hal/audiobusio/PDMIn.c -msgid "only bit_depth=16 is supported" +#: shared-bindings/picogame/Bitmap.c shared-module/msgpack/__init__.c +#: supervisor/shared/settings.c +msgid "Invalid format" msgstr "" -#: ports/stm/common-hal/audiobusio/PDMIn.c -msgid "only mono is supported" +#: shared-bindings/ps2io/Ps2.c +msgid "Failed sending command." msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "only ndarrays can be concatenated" +#: shared-bindings/pulseio/PulseOut.c +msgid "Array must contain halfwords (type 'H')" msgstr "" -#: ports/stm/common-hal/audiobusio/PDMIn.c -msgid "only oversample=64 is supported" +#: shared-bindings/pwmio/PWMOut.c +msgid "Conflicting settings for shared resource" msgstr "" -#: ports/nordic/common-hal/audiobusio/PDMIn.c -#: ports/stm/common-hal/audiobusio/PDMIn.c -msgid "only sample_rate=16000 is supported" +#: shared-bindings/random/__init__.c +msgid "stop not reachable from start" msgstr "" -#: py/objarray.c py/objstr.c py/objstrunicode.c py/objtuple.c -#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c -#: shared-bindings/nvm/ByteArray.c -msgid "only slices with step=1 (aka None) are supported" +#: shared-bindings/random/__init__.c +msgid "invalid step" msgstr "" -#: py/vm.c -msgid "opcode" +#: shared-bindings/random/__init__.c +msgid "empty sequence" msgstr "" -#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/bitwise.c -#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/numpy/vector.c -msgid "operands could not be broadcast together" +#: shared-bindings/rclcpy/Publisher.c +msgid "Publishers can only be created from a parent node" msgstr "" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "operation is defined for 2D arrays only" +#: shared-bindings/rgbmatrix/RGBMatrix.c +#, c-format +msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "operation is defined for ndarrays only" +#: 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 "" -#: extmod/ulab/code/ndarray.c -msgid "operation is implemented for 1D Boolean arrays only" +#: shared-bindings/socketpool/Socket.c +msgid "port must be >= 0" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "operation is not implemented on ndarrays" +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c +msgid "buffer too small for requested bytes" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "operation is not supported for given type" +#: shared-bindings/socketpool/SocketPool.c +msgid "Name or service not known" msgstr "" -#: extmod/ulab/code/ndarray_operators.c -msgid "operation not supported for the input types" +#: shared-bindings/spitarget/SPITarget.c +msgid "Packet buffers for an SPI transfer must have the same length." msgstr "" -#: py/modbuiltins.c -msgid "ord expects a character" +#: shared-bindings/ssl/SSLContext.c +msgid "Server side context cannot have hostname" msgstr "" -#: py/modbuiltins.c -#, c-format -msgid "ord() expected a character, but string of length %d found" +#: shared-bindings/storage/__init__.c shared-bindings/usb_audio/__init__.c +#: shared-bindings/usb_cdc/__init__.c shared-bindings/usb_hid/__init__.c +#: shared-bindings/usb_midi/__init__.c shared-bindings/usb_video/__init__.c +msgid "Cannot change USB devices now" msgstr "" -#: extmod/ulab/code/utils/utils.c -msgid "out array is too small" +#: shared-bindings/supervisor/__init__.c shared-module/lvfontio/OnDiskFont.c +msgid "File not found" msgstr "" -#: extmod/ulab/code/numpy/random/random.c -msgid "out has wrong type" +#: shared-bindings/time/__init__.c +msgid "timestamp out of range for platform time_t" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "out keyword is not supported for complex dtype" +#: shared-bindings/traceback/__init__.c +msgid "Supply both or neither of %q and %q" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "out keyword is not supported for function" +#: shared-bindings/traceback/__init__.c +msgid "file write is not available" msgstr "" -#: extmod/ulab/code/utils/utils.c -msgid "out must be a float dense array" +#: shared-bindings/traceback/__init__.c +msgid "invalid exception" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "out must be an ndarray" +#: shared-bindings/usb_audio/USBSpeaker.c +msgid "destination must be an array of type 'h'" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "out must be of float dtype" +#: shared-bindings/usb_audio/__init__.c +msgid "At least one of microphone and speaker must be enabled" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "out of range of target" +#: shared-bindings/usb_hid/Device.c +msgid "%q, %q, and %q must all be the same length" msgstr "" -#: extmod/ulab/code/numpy/random/random.c -msgid "output array has wrong type" +#: shared-bindings/util.c +msgid "" +"Object has been deinitialized and can no longer be used. Create a new object." msgstr "" -#: extmod/ulab/code/numpy/random/random.c -msgid "output array must be contiguous" +#: shared-bindings/warnings/__init__.c +msgid "%q must be a subclass of %q" msgstr "" -#: py/objint_mpz.c -msgid "overflow converting long int to machine word" +#: shared-bindings/wifi/Radio.c +msgid "Invalid hex password" msgstr "" -#: py/modstruct.c -#, c-format -msgid "pack expected %d items for packing (got %d)" +#: shared-bindings/wifi/Radio.c +msgid "Invalid MAC address" msgstr "" -#: shared-bindings/_stage/Layer.c shared-bindings/_stage/Text.c -msgid "palette must be 32 bytes long" +#: shared-bindings/wifi/Radio.c +msgid "AuthMode.OPEN is not used with password" msgstr "" -#: py/emitinlinextensa.c -msgid "parameters must be registers in sequence a2 to a5" +#: shared-bindings/wifi/Radio.c +msgid "Supply either %q or %q, not both" msgstr "" -#: py/emitinlinethumb.c -msgid "parameters must be registers in sequence r0 to r3" +#: shared-bindings/wifi/Radio.c +msgid "Invalid BSSID" msgstr "" -#: extmod/vfs_posix_file.c -msgid "poll on file not available on win32" +#: shared-bindings/wifi/Radio.c supervisor/shared/web_workflow/web_workflow.c +msgid "Authentication failure" msgstr "" -#: ports/espressif/common-hal/pulseio/PulseIn.c -msgid "pop from an empty PulseIn" +#: shared-bindings/wifi/Radio.c +msgid "No network with that ssid" msgstr "" -#: ports/atmel-samd/common-hal/pulseio/PulseIn.c -#: ports/cxd56/common-hal/pulseio/PulseIn.c -#: ports/nordic/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" +#: shared-bindings/wifi/Radio.c +#, c-format +msgid "Unknown failure %d" msgstr "" -#: shared-bindings/socketpool/Socket.c -msgid "port must be >= 0" +#: shared-module/adafruit_bus_device/i2c_device/I2CDevice.c +#, c-format +msgid "No I2C device at address: 0x%x" msgstr "" -#: py/compile.c -msgid "positional arg after **" +#: shared-module/audiocore/WaveFile.c +msgid "Invalid format chunk size" msgstr "" -#: py/compile.c -msgid "positional arg after keyword arg" +#: shared-module/audiocore/__init__.c shared-module/usb_audio/USBMicrophone.c +msgid "The sample's %q does not match" msgstr "" -#: py/objint_mpz.c -msgid "pow() 3rd argument cannot be 0" +#: shared-module/audiodelays/MultiTapDelay.c +msgid "%q in %q must be of type %q or %q, not %q" msgstr "" -#: py/objint_mpz.c -msgid "pow() with 3 arguments requires integers" +#: shared-module/audiofilewriter/AudioFileWriter.c +msgid "Only 8/16-bit mono/stereo is supported" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "pull masks conflict with direction masks" +#: shared-module/audiofilewriter/AudioFileWriter.c +msgid "buffer_size too small for source" msgstr "" -#: py/parse.c -msgid "raw f-strings are not supported" +#: shared-module/audiomp3/MP3Decoder.c +msgid "Couldn't allocate decoder" msgstr "" -#: extmod/ulab/code/numpy/fft/fft_tools.c -msgid "real and imaginary parts must be of equal length" +#: shared-module/audiomp3/MP3Decoder.c +msgid "Failed to parse MP3 file" msgstr "" -#: py/builtinimport.c -msgid "relative import" +#: shared-module/bitbangio/I2C.c shared-module/msgpack/__init__.c +msgid "%q too long" msgstr "" -#: py/obj.c -#, c-format -msgid "requested length %d but object has length %d" +#: shared-module/bitmapfilter/__init__.c +msgid "bitmap size and depth must match" msgstr "" -#: extmod/ulab/code/ndarray_operators.c -msgid "results cannot be cast to specified type" +#: shared-module/bitmapfilter/__init__.c +msgid "unsupported bitmap depth" msgstr "" -#: py/compile.c -msgid "return annotation must be an identifier" +#: shared-module/busdisplay/lvgl/BusDisplay.c +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "LVGL display create failed" msgstr "" -#: py/emitnative.c -msgid "return expected '%q' but got '%q'" +#: shared-module/busdisplay/lvgl/BusDisplay.c +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "LVGL buffer alloc failed" msgstr "" -#: shared-bindings/rgbmatrix/RGBMatrix.c -#, c-format -msgid "rgb_pins[%d] duplicates another pin assignment" +#: shared-module/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "OAEP requires this build to enable TLS 1.3 support" msgstr "" -#: shared-bindings/rgbmatrix/RGBMatrix.c -#, c-format -msgid "rgb_pins[%d] is not on the same port as clock" +#: shared-module/displayio/bus_core.c +msgid "Unsupported display bus type" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "roll argument must be an ndarray" +#: shared-module/displayio/legacy/Bitmap.c +#: shared-module/displayio/lvgl/Bitmap.c +msgid "Invalid bits per value" msgstr "" -#: py/objstr.c -msgid "rsplit(None,n)" +#: shared-module/displayio/legacy/ColorConverter.c +#: shared-module/displayio/lvgl/ColorConverter.c +msgid "Only one color can be transparent at a time" msgstr "" -#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c -#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c -msgid "sampling rate out of range" +#: shared-module/displayio/legacy/Group.c shared-module/displayio/lvgl/Group.c +msgid "Layer already in a group" msgstr "" -#: py/modmicropython.c -msgid "schedule queue full" +#: shared-module/displayio/legacy/Group.c +msgid "Layer must be a Group or TileGrid subclass" msgstr "" -#: py/builtinimport.c -msgid "script compilation not supported" +#: shared-module/displayio/legacy/OnDiskBitmap.c +#: shared-module/displayio/lvgl/OnDiskBitmap.c +#, c-format +msgid "" +"Only Windows format, uncompressed BMP supported: given header size is %d" msgstr "" -#: py/nativeglue.c -msgid "set unsupported" +#: shared-module/displayio/legacy/OnDiskBitmap.c +#: shared-module/displayio/lvgl/OnDiskBitmap.c +msgid "RLE-compressed BMP not supported" msgstr "" -#: extmod/ulab/code/numpy/random/random.c -msgid "shape must be None, and integer or a tuple of integers" +#: shared-module/displayio/legacy/OnDiskBitmap.c +#: shared-module/displayio/lvgl/OnDiskBitmap.c +msgid "Unable to read color palette data" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "shape must be integer or tuple of integers" +#: shared-module/displayio/legacy/__init__.c +msgid "Too many displays" msgstr "" -#: shared-module/msgpack/__init__.c -msgid "short read" +#: shared-module/displayio/legacy/__init__.c +msgid "Too many display buses; deinit() unused displays" msgstr "" -#: py/objstr.c -msgid "sign not allowed in string format specifier" +#: shared-module/displayio/lvgl/Group.c +msgid "Layer does not support scaling" msgstr "" -#: py/objstr.c -msgid "sign not allowed with integer format specifier 'c'" +#: shared-module/displayio/lvgl/Group.c +msgid "Layer must be a Group, TileGrid, vector shape or VideoBuffer" msgstr "" -#: extmod/ulab/code/ulab_tools.c -msgid "size is defined for ndarrays only" +#: shared-module/displayio/lvgl/TileGrid.c +msgid "LVGL displayio backend does not support flips/transpose yet" msgstr "" -#: extmod/ulab/code/numpy/random/random.c -msgid "size must match out.shape when used together" +#: shared-module/displayio/lvgl/TileGrid.c +msgid "OnDiskBitmap requires its own pixel_shader" msgstr "" -#: py/nativeglue.c -msgid "slice unsupported" +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "LVGL dirty row alloc failed" msgstr "" -#: py/objint.c py/sequence.c -msgid "small int overflow" +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +#: shared-module/videocore/VideoBuffer.c +#: shared-module/videocore/legacy/VideoBuffer.c +#: shared-module/videocore/lvgl/VideoBuffer.c +msgid "VideoBuffer can't stream into a rotated display" msgstr "" -#: main.c -msgid "soft reboot\n" +#: shared-module/gifio/GifWriter.c +msgid "unsupported colorspace for GifWriter" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "sort argument must be an ndarray" +#: shared-module/hmac/HMAC.c +msgid "key does not support this digest" msgstr "" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "sos array must be of shape (n_section, 6)" +#: shared-module/hmac/HMAC.c +msgid "HMAC of an empty message is not supported with a hardware key" msgstr "" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "sos[:, 3] should be all ones" +#: shared-module/i2cdisplaybus/I2CDisplayBus.c +#: shared-module/is31fl3741/IS31FL3741.c +#, c-format +msgid "Unable to find I2C Display at %x" msgstr "" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "sosfilt requires iterable arguments" +#: shared-module/i2cioexpander/IOExpander.c +msgid "Cannot deinitialize board IOExpander" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "source palette too large" +#: shared-module/imagecapture/ParallelImageCapture.c +msgid "This microcontroller does not support continuous capture." msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "source_bitmap must have value_count of 2 or 65536" +#: shared-module/jpegio/JpegDecoder.c +msgid "Interrupted by output function" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "source_bitmap must have value_count of 65536" +#: shared-module/jpegio/JpegDecoder.c +msgid "Device error or wrong termination of input stream" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "source_bitmap must have value_count of 8" +#: shared-module/jpegio/JpegDecoder.c +msgid "Insufficient memory pool for the image" msgstr "" -#: extmod/modre.c -msgid "splitting with sub-captures" +#: shared-module/jpegio/JpegDecoder.c +msgid "Insufficient stream input buffer" msgstr "" -#: py/objstr.c -msgid "start/end indices" +#: shared-module/jpegio/JpegDecoder.c +msgid "Parameter error" msgstr "" -#: shared-bindings/random/__init__.c -msgid "stop not reachable from start" +#: shared-module/jpegio/JpegDecoder.c +msgid "Data format error (may be broken data)" msgstr "" -#: py/stream.c shared-bindings/getpass/__init__.c -msgid "stream operation not supported" +#: shared-module/jpegio/JpegDecoder.c +msgid "Right format but not supported" msgstr "" -#: py/objarray.c py/objstr.c -msgid "string argument without an encoding" +#: shared-module/jpegio/JpegDecoder.c +msgid "Unsupported JPEG (may be progressive)" msgstr "" -#: py/objstrunicode.c -msgid "string index out of range" +#: shared-module/jpegio/JpegDecoder.c +msgid "%q() without %q()" msgstr "" -#: py/objstrunicode.c +#: shared-module/memorymonitor/AllocationAlarm.c #, c-format -msgid "string indices must be integers, not %s" +msgid "Attempt to allocate %d blocks" msgstr "" -#: py/objarray.c py/objstr.c -msgid "substring not found" +#: shared-module/msgpack/__init__.c +msgid "short read" msgstr "" -#: py/compile.c -msgid "super() can't find self" +#: shared-module/msgpack/__init__.c +msgid "no default packer" msgstr "" -#: extmod/modjson.c -msgid "syntax error in JSON" +#: shared-module/paralleldisplaybus/ParallelBus.c +msgid "" +"This microcontroller only supports data0=, not data_pins=, because it " +"requires contiguous pins." msgstr "" -#: extmod/modtime.c -msgid "ticks interval overflow" +#: shared-module/rgbmatrix/RGBMatrix.c +msgid "The length of rgb_pins must be 6, 12, 18, 24, or 30" msgstr "" -#: ports/nordic/common-hal/watchdog/WatchDogTimer.c -msgid "timeout duration exceeded the maximum supported value" +#: shared-module/rgbmatrix/RGBMatrix.c +#, c-format +msgid "rgb_pins[%d] is not on the same port as clock" msgstr "" -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "timeout must be < 655.35 secs" +#: shared-module/rgbmatrix/RGBMatrix.c +#, c-format +msgid "rgb_pins[%d] duplicates another pin assignment" msgstr "" -#: ports/raspberrypi/common-hal/floppyio/__init__.c -msgid "timeout waiting for flux" +#: shared-module/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 "" + +#: shared-module/rgbmatrix/RGBMatrix.c +msgid "No timer available" msgstr "" -#: ports/raspberrypi/common-hal/floppyio/__init__.c -#: shared-module/floppyio/__init__.c -msgid "timeout waiting for index pulse" +#: shared-module/rgbmatrix/RGBMatrix.c +#, c-format +msgid "Internal error #%d" msgstr "" #: shared-module/sdcardio/SDCard.c @@ -4151,274 +4805,271 @@ msgstr "" msgid "timeout waiting for v2 card" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "timer re-init" +#: shared-module/sdcardio/SDCard.c +msgid "no SD card" msgstr "" -#: shared-bindings/time/__init__.c -msgid "timestamp out of range for platform time_t" +#: shared-module/sdcardio/SDCard.c +msgid "couldn't determine SD card version" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "tobytes can be invoked for dense arrays only" +#: shared-module/sdcardio/SDCard.c +msgid "no response from SD card" msgstr "" -#: py/compile.c -msgid "too many args" +#: shared-module/sdcardio/SDCard.c +msgid "SD card CSD format not supported" msgstr "" -#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/create.c -msgid "too many dimensions" +#: shared-module/sdcardio/SDCard.c +msgid "can't set 512 block size" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "too many indices" +#: shared-module/ssl/SSLSocket.c +msgid "Invalid socket for TLS" msgstr "" -#: py/asmthumb.c -msgid "too many locals for native method" +#: shared-module/ssl/SSLSocket.c +msgid "invalid cert" msgstr "" -#: py/runtime.c -#, c-format -msgid "too many values to unpack (expected %d)" +#: shared-module/storage/__init__.c +msgid "File write in progress" msgstr "" -#: extmod/ulab/code/numpy/approx.c -msgid "trapz is defined for 1D arrays of equal length" +#: shared-module/storage/__init__.c +msgid "Mount point directory missing" msgstr "" -#: extmod/ulab/code/numpy/approx.c -msgid "trapz is defined for 1D iterables" +#: shared-module/storage/__init__.c +msgid "Cannot remount path when visible via USB." msgstr "" -#: py/obj.c -msgid "tuple/list has wrong length" +#: shared-module/struct/__init__.c +msgid "'S' and 'O' are not supported format types" msgstr "" -#: ports/espressif/common-hal/canio/CAN.c -#, c-format -msgid "twai_driver_install returned esp-idf error #%d" +#: shared-module/struct/__init__.c +msgid "buffer size must match format" msgstr "" -#: ports/espressif/common-hal/canio/CAN.c -#, c-format -msgid "twai_start returned esp-idf error #%d" +#: shared-module/synthio/__init__.c +msgid "%q must be array of type 'h'" msgstr "" -#: shared-bindings/busio/UART.c shared-bindings/canio/CAN.c -msgid "tx and rx cannot both be None" +#: shared-module/tilepalettemapper/TilePaletteMapper.c +msgid "TilePaletteMapper may only be bound to a TileGrid once" msgstr "" -#: py/objtype.c -msgid "type '%q' is not an acceptable base type" +#: shared-module/touchio/TouchIn.c +msgid "No pullup on pin; 1Mohm recommended" msgstr "" -#: py/objtype.c -msgid "type is not an acceptable base type" +#: shared-module/touchio/TouchIn.c +msgid "No pulldown on pin; 1Mohm recommended" msgstr "" -#: py/runtime.c -msgid "type object '%q' has no attribute '%q'" +#: shared-module/usb/core/Device.c +msgid "No usb host port initialized" msgstr "" -#: py/objtype.c -msgid "type takes 1 or 3 arguments" +#: shared-module/usb/core/Device.c +msgid "Pipe error" msgstr "" -#: py/objint_longlong.c -msgid "ulonglong too large" +#: shared-module/usb/core/Device.c +msgid "No configuration set" msgstr "" -#: py/parse.c -msgid "unexpected indent" +#: shared-module/usb_hid/Device.c +msgid "USB busy" msgstr "" -#: py/bc.c -msgid "unexpected keyword argument" +#: shared-module/vectorio/Circle.c shared-module/vectorio/Polygon.c +#: shared-module/vectorio/Rectangle.c +msgid "can only have one parent" msgstr "" -#: py/argcheck.c py/bc.c py/objnamedtuple.c -#: shared-bindings/traceback/__init__.c -msgid "unexpected keyword argument '%q'" +#: shared-module/vectorio/Polygon.c +msgid "Polygon needs at least 3 points" msgstr "" -#: py/lexer.c -msgid "unicode name escapes" +#: shared-module/videocore/VideoBuffer.c +msgid "framebuffer went away" msgstr "" -#: py/parse.c -msgid "unindent doesn't match any outer indent level" +#: shared-module/videocore/VideoBuffer.c +msgid "video doesn't fit in framebuffer" msgstr "" -#: py/objstr.c -#, c-format -msgid "unknown conversion specifier %c" +#: shared-module/videocore/VideoBuffer.c +msgid "framebuffer missing required functions" msgstr "" -#: py/objstr.c -msgid "unknown format code '%c' for object of type '%q'" +#: shared-module/videocore/VideoBuffer.c +msgid "video format must be byte aligned" msgstr "" -#: py/compile.c -msgid "unknown type" +#: shared-module/videocore/VideoBuffer.c +msgid "video format doesn't match framebuffer" msgstr "" -#: py/compile.c -msgid "unknown type '%q'" +#: shared-module/videocore/VideoBuffer.c +msgid "video source rejected the destination" msgstr "" -#: py/objstr.c -#, c-format -msgid "unmatched '%c' in format" +#: shared-module/videocore/VideoBuffer.c +msgid "video in a framebuffer must be at x == 0" msgstr "" -#: py/objtype.c py/runtime.c -msgid "unreadable attribute" +#: shared-module/videocore/VideoBuffer.c +msgid "video size changed since play; stop and play again" msgstr "" -#: shared-bindings/displayio/TileGrid.c shared-bindings/vectorio/VectorShape.c -msgid "unsupported %q type" +#: shared-module/videocore/VideoBuffer.c +msgid "VideoBuffer is playing into a different framebuffer" msgstr "" -#: py/emitinlinethumb.c -#, c-format -msgid "unsupported Thumb instruction '%s' with %d arguments" +#: shared-module/videocore/legacy/VideoBuffer.c +msgid "VideoBuffer does not support transforms" msgstr "" -#: py/emitinlinextensa.c -#, c-format -msgid "unsupported Xtensa instruction '%s' with %d arguments" +#: shared-module/videocore/lvgl/VideoBuffer.c +msgid "video format must be 16, 24 or 32 bits per pixel" msgstr "" -#: shared-module/bitmapfilter/__init__.c -msgid "unsupported bitmap depth" +#: supervisor/shared/bluetooth/bluetooth.c +msgid "Reconnecting" msgstr "" -#: shared-module/gifio/GifWriter.c -msgid "unsupported colorspace for GifWriter" +#: supervisor/shared/bluetooth/bluetooth.c +msgid "Ok" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "unsupported colorspace for dither" +#: supervisor/shared/bluetooth/bluetooth.c +msgid "Off" msgstr "" -#: py/objstr.c -#, c-format -msgid "unsupported format character '%c' (0x%x) at index %d" +#: supervisor/shared/micropython.c +msgid "[truncated due to length]" msgstr "" -#: py/runtime.c -msgid "unsupported type for %q: '%s'" +#: supervisor/shared/safe_mode.c +msgid "" +"\n" +"You are in safe mode because:\n" msgstr "" -#: py/runtime.c -msgid "unsupported type for operator" +#: supervisor/shared/safe_mode.c +msgid "Power dipped. Make sure you are providing enough power." msgstr "" -#: py/runtime.c -msgid "unsupported types for %q: '%q', '%q'" +#: supervisor/shared/safe_mode.c +msgid "You pressed the BOOT button at start up" msgstr "" -#: extmod/ulab/code/numpy/io/io.c -msgid "usecols is too high" +#: supervisor/shared/safe_mode.c +msgid "You pressed the reset button during boot." msgstr "" -#: extmod/ulab/code/numpy/io/io.c -msgid "usecols keyword must be specified" +#: supervisor/shared/safe_mode.c +msgid "CIRCUITPY drive could not be found or created." msgstr "" -#: py/objint.c -#, c-format -msgid "value must fit in %d byte(s)" +#: supervisor/shared/safe_mode.c +msgid "The `microcontroller` module was used to boot into safe mode." msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "value out of range of target" +#: supervisor/shared/safe_mode.c +msgid "Error in safemode.py." msgstr "" -#: extmod/moddeflate.c -msgid "wbits" +#: supervisor/shared/safe_mode.c +msgid "Stack overflow. Increase stack size." msgstr "" -#: shared-bindings/bitmapfilter/__init__.c -msgid "" -"weights must be a sequence with an odd square number of elements (usually 9 " -"or 25)" +#: supervisor/shared/safe_mode.c +msgid "USB devices need more endpoints than are available." msgstr "" -#: shared-bindings/bitmapfilter/__init__.c -msgid "weights must be an object of type %q, %q, %q, or %q, not %q " +#: supervisor/shared/safe_mode.c +msgid "USB devices specify too many interface names." msgstr "" -#: shared-bindings/is31fl3741/FrameBuffer.c -msgid "width must be greater than zero" +#: supervisor/shared/safe_mode.c +msgid "Boot device must be first (interface #0)." msgstr "" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/raspberrypi/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "wifi is not enabled" +#: supervisor/shared/safe_mode.c +msgid "Internal watchdog timer expired." msgstr "" -#: ports/raspberrypi/common-hal/wifi/Monitor.c -msgid "wifi.Monitor not available" +#: supervisor/shared/safe_mode.c +msgid "CircuitPython core code crashed hard. Whoops!\n" msgstr "" -#: shared-bindings/_bleio/Adapter.c -msgid "window must be <= interval" +#: supervisor/shared/safe_mode.c +msgid "Heap allocation when VM not running." msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "wrong axis index" +#: supervisor/shared/safe_mode.c +msgid "Failed to write internal flash." msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "wrong axis specified" +#: supervisor/shared/safe_mode.c +msgid "Hard fault: memory access or instruction error." msgstr "" -#: extmod/ulab/code/numpy/io/io.c -msgid "wrong dtype" +#: supervisor/shared/safe_mode.c +msgid "Interrupt error." msgstr "" -#: extmod/ulab/code/numpy/transform.c -msgid "wrong index type" +#: supervisor/shared/safe_mode.c +msgid "LVGL ran out of memory." msgstr "" -#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/numpy/create.c -#: extmod/ulab/code/numpy/io/io.c extmod/ulab/code/numpy/transform.c -#: extmod/ulab/code/numpy/vector.c -msgid "wrong input type" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." msgstr "" -#: extmod/ulab/code/numpy/transform.c -msgid "wrong length of condition array" +#: supervisor/shared/safe_mode.c +msgid "Unable to allocate to the heap." msgstr "" -#: extmod/ulab/code/numpy/transform.c -msgid "wrong length of index array" +#: supervisor/shared/safe_mode.c +msgid "Third-party firmware fatal error." msgstr "" -#: extmod/ulab/code/numpy/create.c py/objarray.c py/objstr.c -msgid "wrong number of arguments" +#: supervisor/shared/safe_mode.c +msgid "" +"\n" +"Please file an issue with your program at github.com/adafruit/circuitpython/" +"issues." msgstr "" -#: py/runtime.c -msgid "wrong number of values to unpack" +#: supervisor/shared/safe_mode.c +msgid "" +"\n" +"Press reset to exit safe mode.\n" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "wrong output type" +#: supervisor/shared/settings.c +#, c-format +msgid "An error occurred while retrieving '%s':\n" msgstr "" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "zi must be an ndarray" +#: supervisor/shared/settings.c +msgid "Invalid unicode escape" msgstr "" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "zi must be of float type" +#: supervisor/shared/web_workflow/web_workflow.c +msgid "Wi-Fi: " msgstr "" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "zi must be of shape (n_section, 2)" +#: supervisor/shared/web_workflow/web_workflow.c +msgid "off" +msgstr "" + +#: supervisor/shared/web_workflow/web_workflow.c +msgid "No IP" msgstr "" diff --git a/locale/cs.po b/locale/cs.po index ad0ad6ae4e2..83302421be8 100644 --- a/locale/cs.po +++ b/locale/cs.po @@ -6,3234 +6,3741 @@ 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: 2023-11-16 15:03+0000\n" -"Last-Translator: Scott Shawcroft \n" +"PO-Revision-Date: 2025-06-30 16:01+0000\n" +"Last-Translator: MAE \n" "Language-Team: LANGUAGE \n" "Language: cs\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Plural-Forms: nplurals=3; plural=(n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2;\n" -"X-Generator: Weblate 5.2\n" +"Plural-Forms: nplurals=3; plural=((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);\n" +"X-Generator: Weblate 5.13-dev\n" -#: main.c -msgid "" -"\n" -"Code done running.\n" +#: extmod/modasyncio.c extmod/modheapq.c +msgid "empty heap" msgstr "" -"\n" -"Běh programu byl dokončen.\n" -#: main.c -msgid "" -"\n" -"Code stopped by auto-reload. Reloading soon.\n" -msgstr "" -"\n" -"Kód byl zastaven kvůli automatickému načtení. K načtení dojde brzy.\n" +#: extmod/modasyncio.c +msgid "can't cancel self" +msgstr "nelze zrušit sám sebe" -#: supervisor/shared/safe_mode.c -msgid "" -"\n" -"Please file an issue with your program at github.com/adafruit/circuitpython/" -"issues." -msgstr "" -"\n" -"Prosím, založte issue s vaším programem na github.com/adafruit/circuitpython/" -"issues." +#: extmod/modasyncio.c +msgid "can't wait" +msgstr "nelze čekat" -#: supervisor/shared/safe_mode.c -msgid "" -"\n" -"Press reset to exit safe mode.\n" +#: extmod/modbinascii.c extmod/modhashlib.c py/objarray.c +msgid "a bytes-like object is required" msgstr "" -"\n" -"Stiskněte reset pro ukončení nouzového režimu.\n" -#: supervisor/shared/safe_mode.c -msgid "" -"\n" -"You are in safe mode because:\n" +#: extmod/modbinascii.c +msgid "incorrect padding" msgstr "" -"\n" -"Jste v bezpečnostním režimu z důvodu:\n" - -#: py/obj.c -msgid " File \"%q\"" -msgstr " Soubor \"%q\"" - -#: py/obj.c -msgid " File \"%q\", line %d" -msgstr " Soubor \"%q\", řádek %d" - -#: py/builtinhelp.c -msgid " is of type %q\n" -msgstr " je typu %q\n" -#: main.c -msgid " not found.\n" -msgstr " nenalezen\n" +#: extmod/moddeflate.c +msgid "format" +msgstr "" -#: main.c -msgid " output:\n" -msgstr " výstup:\n" +#: extmod/moddeflate.c +msgid "wbits" +msgstr "" -#: py/objstr.c -#, c-format -msgid "%%c requires int or char" -msgstr "%%c vyžaduje int nebo char" +#: extmod/modhashlib.c +msgid "hash is final" +msgstr "hash je konečný" -#: 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 adresní pin, %d rgb pin a %d dlaždice indikuje výšku %d, ne %d" +#: extmod/modheapq.c +msgid "heap must be a list" +msgstr "" -#: shared-bindings/microcontroller/Pin.c -msgid "%q and %q contain duplicate pins" -msgstr "%q a %q obsahují duplicitní piny" +#: extmod/modjson.c +msgid "syntax error in JSON" +msgstr "" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c -msgid "%q and %q must be different" -msgstr "%q a %q musí být rozdílné" +#: extmod/modrandom.c +msgid "bits must be 32 or less" +msgstr "počet bitů nesmí přesáhnout 32" -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -msgid "%q and %q must share a clock unit" +#: extmod/modrandom.c extmod/ulab/code/numpy/random/random.c +msgid "no default seed" msgstr "" -#: ports/nordic/common-hal/watchdog/WatchDogTimer.c -msgid "%q cannot be changed once mode is set to %q" +#: extmod/modre.c +msgid "splitting with sub-captures" msgstr "" -#: shared-bindings/microcontroller/Pin.c -msgid "%q contains duplicate pins" -msgstr "%q obsahuje duplicitní piny" +#: extmod/modre.c +msgid "regex too complex" +msgstr "" -#: ports/atmel-samd/common-hal/sdioio/SDCard.c -msgid "%q failure: %d" -msgstr "%q: selhání %d" +#: extmod/modre.c +msgid "Error in regex" +msgstr "Chyba v regulárním výrazu" -#: py/argcheck.c shared-module/audiofilters/Filter.c -msgid "%q in %q must be of type %q, not %q" -msgstr "%q v %q musí být typu %q, ne %q" +#: extmod/modtime.c +msgid "mktime needs a tuple of length 8 or 9" +msgstr "" -#: ports/espressif/common-hal/espulp/ULP.c -#: ports/mimxrt10xx/common-hal/audiobusio/__init__.c -#: ports/mimxrt10xx/common-hal/usb_host/Port.c -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -#: ports/raspberrypi/common-hal/usb_host/Port.c -#: shared-bindings/digitalio/DigitalInOut.c -#: shared-bindings/microcontroller/Pin.c shared-module/max3421e/Max3421E.c -msgid "%q in use" -msgstr "%q se právě používá" +#: extmod/modtime.c +msgid "ticks interval overflow" +msgstr "" -#: py/objstr.c -msgid "%q index out of range" -msgstr "Index %q je mimo rozsah" +#: extmod/modzlib.c +msgid "compression header" +msgstr "" -#: py/obj.c -msgid "%q indices must be integers, not %s" -msgstr "Indexy %q musí být celá čísla, nikoli %s" +#: extmod/ulab/code/ndarray.c +msgid "data type not understood" +msgstr "datový typ nebyl rozpoznán" -#: shared-module/bitbangio/SPI.c -msgid "%q init failed" -msgstr "Inicializace %q selhala" +#: extmod/ulab/code/ndarray.c +msgid "array is too big" +msgstr "pole je příliš velké" -#: ports/espressif/bindings/espnow/Peer.c shared-bindings/dualbank/__init__.c -msgid "%q is %q" -msgstr "%q je %q" +#: extmod/ulab/code/ndarray.c +msgid "ndarray length overflows" +msgstr "délka ndarray přetekla" -#: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "%q is read-only for this board" -msgstr "%q je pouze u této desky pouze pro čtení" +#: extmod/ulab/code/ndarray.c +msgid "maximum number of dimensions is " +msgstr "maximální počet dimenzí je " -#: py/argcheck.c shared-bindings/usb_hid/Device.c -msgid "%q length must be %d" -msgstr "Délka %q musí být %d" +#: extmod/ulab/code/ndarray.c +msgid "cannot convert complex type" +msgstr "nelze převést typ complex" -#: py/argcheck.c -msgid "%q length must be %d-%d" -msgstr "%q délka musí být %d-%d" +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/create.c +msgid "too many dimensions" +msgstr "příliš mnoho dimenzí" -#: py/argcheck.c -msgid "%q length must be <= %d" -msgstr "Délka %q musí být <= %d" +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/transform.c +msgid "index is out of bounds" +msgstr "" -#: py/argcheck.c -msgid "%q length must be >= %d" -msgstr "Délka %q musí být >= %d" +#: extmod/ulab/code/ndarray.c +msgid "indices must be integers, slices, or Boolean lists" +msgstr "" -#: py/modsys.c py/objmodule.c py/runtime.c -msgid "%q moved from %q to %q" +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/bitwise.c +#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/numpy/vector.c +msgid "operands could not be broadcast together" msgstr "" -#: py/argcheck.c -msgid "%q must be %d" -msgstr "%q musí být %d" +#: extmod/ulab/code/ndarray.c +msgid "array and index length must be equal" +msgstr "Pole a index musí mít stejnou délku" -#: py/argcheck.c shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/displayio/Bitmap.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -#: shared-bindings/is31fl3741/FrameBuffer.c -#: shared-bindings/rgbmatrix/RGBMatrix.c -msgid "%q must be %d-%d" -msgstr "%q musí být %d-%d" +#: extmod/ulab/code/ndarray.c +msgid "cannot convert complex to dtype" +msgstr "nelze převést complex na dtype" -#: shared-bindings/busdisplay/BusDisplay.c -msgid "%q must be 1 when %q is True" -msgstr "%q musí být 1, pokud %q je True" +#: extmod/ulab/code/ndarray.c +msgid "operation is implemented for 1D Boolean arrays only" +msgstr "operace je immplementována pouze pro 1D boolean pole" -#: py/argcheck.c shared-bindings/gifio/GifWriter.c -#: shared-module/gifio/OnDiskGif.c -msgid "%q must be <= %d" -msgstr "%q musí být <= %d" +#: extmod/ulab/code/ndarray.c +msgid "too many indices" +msgstr "" -#: ports/espressif/common-hal/watchdog/WatchDogTimer.c -msgid "%q must be <= %u" -msgstr "%q musí být <= %u" +#: extmod/ulab/code/ndarray.c +msgid "cannot delete array elements" +msgstr "nelze smazat prvky pole" -#: py/argcheck.c -msgid "%q must be >= %d" -msgstr "%q musí být >= %d" +#: extmod/ulab/code/ndarray.c +msgid "flattening order must be either 'C', or 'F'" +msgstr "" -#: shared-bindings/analogbufio/BufferedIn.c -msgid "%q must be a bytearray or array of type 'H' or 'B'" -msgstr "%q musí být bytearray nebo pole typu 'H' nebo 'B'" +#: extmod/ulab/code/ndarray.c +msgid "tobytes can be invoked for dense arrays only" +msgstr "" -#: shared-bindings/audiocore/RawSample.c -msgid "%q must be a bytearray or array of type 'h', 'H', 'b', or 'B'" -msgstr "%q musí být bytearray nebo pole typu 'h', 'H', 'b', nebo 'B'" +#: extmod/ulab/code/ndarray.c +msgid "operation is not supported for given type" +msgstr "" -#: shared-bindings/warnings/__init__.c -msgid "%q must be a subclass of %q" +#: extmod/ulab/code/ndarray.c +msgid "keyword argument must be tuple of integers" msgstr "" -#: ports/espressif/common-hal/analogbufio/BufferedIn.c -msgid "%q must be array of type 'H'" -msgstr "%q musí být pole typu 'H V" +#: extmod/ulab/code/ndarray.c +msgid "too many axes specified" +msgstr "" -#: shared-module/synthio/__init__.c -msgid "%q must be array of type 'h'" -msgstr "%q musí být pole typu 'h'" +#: extmod/ulab/code/ndarray.c +msgid "axis index out of bounds" +msgstr "" -#: shared-bindings/audiobusio/PDMIn.c -msgid "%q must be multiple of 8." +#: extmod/ulab/code/ndarray.c +msgid "repeated indices" msgstr "" -#: ports/raspberrypi/bindings/cyw43/__init__.c py/argcheck.c py/objexcept.c -#: shared-bindings/bitmapfilter/__init__.c shared-bindings/canio/CAN.c -#: shared-bindings/digitalio/Pull.c shared-bindings/supervisor/__init__.c -#: shared-module/audiofilters/Filter.c shared-module/displayio/__init__.c -#: shared-module/synthio/Biquad.c shared-module/synthio/Synthesizer.c -msgid "%q must be of type %q or %q, not %q" -msgstr "%q musí být typu %q nebo %q, ne %q" +#: extmod/ulab/code/ndarray.c +msgid "shape must be integer or tuple of integers" +msgstr "tvar musí být integer nebo tuple integerů" -#: shared-bindings/jpegio/JpegDecoder.c -msgid "%q must be of type %q, %q, or %q, not %q" +#: extmod/ulab/code/ndarray.c +msgid "can only specify one unknown dimension" msgstr "" -#: py/argcheck.c py/runtime.c shared-bindings/bitmapfilter/__init__.c -#: shared-module/synthio/__init__.c -msgid "%q must be of type %q, not %q" -msgstr "%q musí být typu %q, ne %q" - -#: ports/atmel-samd/common-hal/busio/UART.c -msgid "%q must be power of 2" -msgstr "%q musí být mocnina 2" +#: extmod/ulab/code/ndarray.c +msgid "cannot reshape array" +msgstr "nelze změnit rozměry pole" -#: shared-bindings/wifi/Monitor.c -msgid "%q out of bounds" -msgstr "%q je mimo hranice" +#: extmod/ulab/code/ndarray.c +msgid "cannot assign new shape" +msgstr "nelze přiřadit nový tvar" -#: ports/atmel-samd/common-hal/pulseio/PulseIn.c -#: ports/cxd56/common-hal/pulseio/PulseIn.c -#: ports/nordic/common-hal/pulseio/PulseIn.c -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -#: ports/stm/common-hal/pulseio/PulseIn.c py/argcheck.c -#: shared-bindings/canio/Match.c shared-bindings/time/__init__.c -msgid "%q out of range" -msgstr "%q je mimo rozsah" +#: extmod/ulab/code/ndarray.c +msgid "function is defined for ndarrays only" +msgstr "funkce je definována pouze pro ndarraye" -#: py/objmodule.c py/runtime.c -msgid "%q renamed %q" +#: extmod/ulab/code/ndarray_operators.c +msgid "operation not supported for the input types" msgstr "" -#: py/objrange.c py/objslice.c shared-bindings/random/__init__.c -msgid "%q step cannot be zero" -msgstr "%q krok nemůže být nula" - -#: shared-module/bitbangio/I2C.c -msgid "%q too long" +#: extmod/ulab/code/ndarray_operators.c +msgid "dtype of int32 is not supported" msgstr "" -#: py/bc.c py/objnamedtuple.c -msgid "%q() takes %d positional arguments but %d were given" -msgstr "%q() vyžaduje %d pozičních argumentů, ale pouze %d jich bylo zadáno" +#: extmod/ulab/code/ndarray_operators.c +msgid "cannot cast output with casting rule" +msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "%q() without %q()" +#: extmod/ulab/code/ndarray_operators.c +msgid "results cannot be cast to specified type" msgstr "" -#: shared-bindings/usb_hid/Device.c -msgid "%q, %q, and %q must all be the same length" -msgstr "%q, %q, a %q musí mít všechny shodnou délku" +#: extmod/ulab/code/numpy/approx.c +msgid "interp is defined for 1D iterables of equal length" +msgstr "" -#: py/objint.c shared-bindings/_bleio/Connection.c -#: shared-bindings/storage/__init__.c -msgid "%q=%q" -msgstr "%q=%q" +#: extmod/ulab/code/numpy/approx.c +msgid "trapz is defined for 1D iterables" +msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "%q[%u] shifts in more bits than pin count" -msgstr "%q[%u] posouvá dovnitř o více bitů než je počet pinů" +#: extmod/ulab/code/numpy/approx.c +msgid "trapz is defined for 1D arrays of equal length" +msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "%q[%u] shifts out more bits than pin count" -msgstr "%q[%u] posouvá ven o více bitů než je počet pinů" +#: extmod/ulab/code/numpy/bitwise.c +msgid "not supported for input types" +msgstr "není podporováno pro vstupní typy" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "%q[%u] uses extra pin" -msgstr "%q[%u] používá extra pin" +#: extmod/ulab/code/numpy/carray/carray.c +msgid "function is implemented for ndarrays only" +msgstr "funkce je implementována jen pro ndarraye" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "%q[%u] waits on input outside of count" -msgstr "%q[%u] čeká na vstup mimo rozsah" +#: extmod/ulab/code/numpy/carray/carray.c +msgid "input must be an ndarray, or a scalar" +msgstr "vstup musí být ndarray nebo scalar" -#: ports/espressif/common-hal/espidf/__init__.c -#, c-format -msgid "%s error 0x%x" -msgstr "%s chyba 0x%x" +#: extmod/ulab/code/numpy/carray/carray.c +msgid "input must be a 1D ndarray" +msgstr "vstup musí být 1D ndarray" -#: py/argcheck.c -msgid "'%q' argument required" -msgstr "Je vyžadován argument '%q'" +#: extmod/ulab/code/numpy/carray/carray_tools.c +msgid "not implemented for complex dtype" +msgstr "není implementováno pro komplexní dtype" -#: py/proto.c -msgid "'%q' object does not support '%q'" -msgstr "Objekt '%q' nepodporuje '%q'" +#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/user/user.c +#: shared-bindings/_eve/__init__.c +msgid "input must be an ndarray" +msgstr "vstup musí být ndarray" -#: py/runtime.c -msgid "'%q' object is not an iterator" -msgstr "Objekt '%q' není iterátor" +#: extmod/ulab/code/numpy/compare.c +msgid "object too deep for desired array" +msgstr "" -#: py/objtype.c py/runtime.c shared-module/atexit/__init__.c -msgid "'%q' object is not callable" -msgstr "Objekt '%q' nelze zavolat" +#: extmod/ulab/code/numpy/compare.c +msgid "cannot cast array data from dtype" +msgstr "" -#: py/runtime.c -msgid "'%q' object is not iterable" -msgstr "Objekt '%q' není iterovatelný" +#: extmod/ulab/code/numpy/compare.c +msgid "minlength must not be negative" +msgstr "" -#: py/emitinlinethumb.c py/emitinlinextensa.c -#, c-format -msgid "'%s' expects a label" -msgstr "'%s' očekává label" +#: extmod/ulab/code/numpy/compare.c +msgid "the weights and list don't have the same length" +msgstr "" -#: py/emitinlinethumb.c py/emitinlinextensa.c -#, c-format -msgid "'%s' expects a register" -msgstr "'%s' očekává registr" +#: extmod/ulab/code/numpy/compare.c +msgid "cannot cast weigths to float" +msgstr "" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects a special register" -msgstr "'%s' očekává speciální registr" +#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/numpy/create.c +#: extmod/ulab/code/numpy/io/io.c extmod/ulab/code/numpy/transform.c +#: extmod/ulab/code/numpy/vector.c +msgid "wrong input type" +msgstr "" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects an FPU register" -msgstr "'%s' očekává registr FPU" +#: extmod/ulab/code/numpy/create.c +msgid "input argument must be an integer, a tuple, or a list" +msgstr "vstupní argument musí být integer, tuple nebo list" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects an address of the form [a, b]" -msgstr "'%s' očekává adresu ve formátu [a, b]" +#: extmod/ulab/code/numpy/create.c py/objarray.c py/objstr.c +msgid "wrong number of arguments" +msgstr "" -#: py/emitinlinethumb.c py/emitinlinextensa.c -#, c-format -msgid "'%s' expects an integer" -msgstr "'%s' očekává integer (celé číslo)" +#: extmod/ulab/code/numpy/create.c py/objint_longlong.c py/objint_mpz.c +msgid "divide by zero" +msgstr "dělení nulou" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects at most r%d" -msgstr "'%s' očekává nanejvýš r%d" +#: extmod/ulab/code/numpy/create.c +msgid "arange: cannot compute length" +msgstr "" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects {r0, r1, ...}" -msgstr "'%s' očekává {r0, r1, ...}" +#: extmod/ulab/code/numpy/create.c +msgid "first argument must be a tuple of ndarrays" +msgstr "první argument musí být tuple nebo ndarray" -#: py/emitinlinextensa.c -#, c-format -msgid "'%s' integer %d isn't within range %d..%d" -msgstr "'%s' integer %d není v rozsahu %d..%d" +#: extmod/ulab/code/numpy/create.c +msgid "only ndarrays can be concatenated" +msgstr "pouze ndarraye mohou být spojeny" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' integer 0x%x doesn't fit in mask 0x%x" -msgstr "'%s' integer 0x%x nepatří do masky 0x%x" +#: extmod/ulab/code/numpy/create.c +msgid "wrong axis specified" +msgstr "" -#: py/obj.c -#, c-format -msgid "'%s' object doesn't support item assignment" -msgstr "'%s' objekt nepodporuje přiřazení položky" +#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c +msgid "input arrays are not compatible" +msgstr "vstupní pole nejsou kompatibilní" -#: py/obj.c -#, c-format -msgid "'%s' object doesn't support item deletion" -msgstr "'%s' objekt nepodporuje smazání položky" +#: extmod/ulab/code/numpy/create.c +msgid "input must be 1- or 2-d" +msgstr "vstup musí být 1- nebo 2-d" -#: py/runtime.c -msgid "'%s' object has no attribute '%q'" -msgstr "'%s' objekt nemá žádný atribut '%q'" +#: extmod/ulab/code/numpy/create.c +msgid "number of points must be at least 2" +msgstr "" -#: py/obj.c -#, c-format -msgid "'%s' object isn't subscriptable" -msgstr "'%s' objekt není vložitelný" +#: extmod/ulab/code/numpy/create.c +msgid "indexing should be 'xy' or 'ij'" +msgstr "" -#: py/objstr.c -msgid "'=' alignment not allowed in string format specifier" -msgstr "Specifikátor zarovnání '=' není ve formátovacím řetězci povolen" +#: extmod/ulab/code/numpy/create.c +msgid "indexing must be 'xy' or 'ij'" +msgstr "" -#: shared-module/struct/__init__.c -msgid "'S' and 'O' are not supported format types" -msgstr "'S' a 'O' nejsou podporované typy formátů" +#: extmod/ulab/code/numpy/create.c +msgid "too many input arrays" +msgstr "" -#: py/compile.c -msgid "'align' requires 1 argument" -msgstr "'align' vyžaduje 1 argument" +#: extmod/ulab/code/numpy/create.c extmod/ulab/code/numpy/numerical.c +#: extmod/ulab/code/numpy/transform.c +msgid "arguments must be ndarrays" +msgstr "" -#: py/compile.c -msgid "'await' outside function" -msgstr "'await' je volán mimo funkci" +#: extmod/ulab/code/numpy/create.c +msgid "arguments must be 1D arrays" +msgstr "" -#: py/compile.c -msgid "'break'/'continue' outside loop" +#: extmod/ulab/code/numpy/create.c +msgid "input is not an array" msgstr "" -#: py/compile.c -msgid "'data' requires at least 2 arguments" -msgstr "'data' vyžaduje nejméně 2 argumenty" +#: extmod/ulab/code/numpy/create.c extmod/ulab/code/numpy/numerical.c +#: ports/espressif/common-hal/pulseio/PulseIn.c +#: shared-bindings/bitmaptools/__init__.c +msgid "index out of range" +msgstr "" -#: py/compile.c -msgid "'data' requires integer arguments" -msgstr "'data' vyžaduje celočíselné argumenty" +#: extmod/ulab/code/numpy/create.c +msgid "mode should be raise, wrap or clip" +msgstr "" -#: py/compile.c -msgid "'label' requires 1 argument" -msgstr "'label' vyžaduje 1 argument" +#: extmod/ulab/code/numpy/create.c +msgid "index must not be negative" +msgstr "" -#: py/emitnative.c -msgid "'not' not implemented" +#: extmod/ulab/code/numpy/create.c +msgid "offset must be non-negative and no greater than buffer length" msgstr "" -#: py/compile.c -msgid "'return' outside function" -msgstr "'return' je volán mimo funkci" +#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c +msgid "buffer size must be a multiple of element size" +msgstr "velikost bufferu musí být násobkem velikosti elementu" -#: py/compile.c -msgid "'yield from' inside async function" -msgstr "'yield from' volán uvnitř funkce async" +#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c +msgid "buffer is smaller than requested size" +msgstr "buffer je menší než požadovaná velikost" -#: py/compile.c -msgid "'yield' outside function" -msgstr "'yield' je volán mimo funkci" +#: extmod/ulab/code/numpy/fft/fft_tools.c +msgid "FFT is defined for ndarrays only" +msgstr "FFT lze použít pouze pro ndarrays" -#: py/compile.c -msgid "* arg after **" -msgstr "* arg po **" +#: extmod/ulab/code/numpy/fft/fft_tools.c +msgid "FFT is implemented for linear arrays only" +msgstr "FFT je implementován pouze pro lineární pole" -#: py/compile.c -msgid "*x must be assignment target" -msgstr "∗x musí být cíl přiřazení" +#: extmod/ulab/code/numpy/fft/fft_tools.c extmod/ulab/code/utils/utils.c +msgid "input array length must be power of 2" +msgstr "" -#: py/obj.c -msgid ", in %q\n" -msgstr ", v% q\n" +#: extmod/ulab/code/numpy/fft/fft_tools.c +msgid "real and imaginary parts must be of equal length" +msgstr "" -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/epaperdisplay/EPaperDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -msgid ".show(x) removed. Use .root_group = x" +#: extmod/ulab/code/numpy/filter.c +msgid "convolve arguments must be ndarrays" msgstr "" -#: py/objcomplex.c -msgid "0.0 to a complex power" -msgstr "0.0 na komplexní mocninu" +#: extmod/ulab/code/numpy/filter.c +msgid "convolve arguments must be linear arrays" +msgstr "" -#: py/modbuiltins.c -msgid "3-arg pow() not supported" -msgstr "pow() nepodporuje 3 argumenty" +#: extmod/ulab/code/numpy/filter.c +msgid "convolve arguments must not be empty" +msgstr "" -#: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "AP could not be started" -msgstr "AP nemohl být spuštěn" +#: extmod/ulab/code/numpy/io/io.c +msgid "corrupted file" +msgstr "poškozený soubor" -#: shared-bindings/_bleio/Address.c shared-bindings/ipaddress/IPv4Address.c -#, c-format -msgid "Address must be %d bytes long" -msgstr "Adresa musí být %d bajtů dlouhá" +#: extmod/ulab/code/numpy/io/io.c +msgid "wrong dtype" +msgstr "špatný dtype" -#: ports/espressif/common-hal/memorymap/AddressRange.c -#: ports/nordic/common-hal/memorymap/AddressRange.c -#: ports/raspberrypi/common-hal/memorymap/AddressRange.c -msgid "Address range not allowed" -msgstr "Adresní rozsah není povolen" +#: extmod/ulab/code/numpy/io/io.c +msgid "usecols keyword must be specified" +msgstr "" -#: shared-bindings/memorymap/AddressRange.c -msgid "Address range wraps around" -msgstr "Adresní rozsah se překlápí přes maximální možnou adresu" +#: extmod/ulab/code/numpy/io/io.c +msgid "empty file" +msgstr "prázdný soubor" -#: ports/espressif/common-hal/canio/CAN.c -msgid "All CAN peripherals are in use" -msgstr "Všechny CAN periferie jsou používány" +#: extmod/ulab/code/numpy/io/io.c +msgid "usecols is too high" +msgstr "" -#: ports/espressif/common-hal/busio/I2C.c -#: ports/espressif/common-hal/i2ctarget/I2CTarget.c -#: ports/nordic/common-hal/busio/I2C.c -msgid "All I2C peripherals are in use" -msgstr "Všechny I2C periferie jsou používány" +#: extmod/ulab/code/numpy/io/io.c +msgid "array has too many dimensions" +msgstr "pole má příliš mnoho dimenzí" -#: ports/atmel-samd/common-hal/canio/Listener.c -#: ports/espressif/common-hal/canio/Listener.c -#: ports/stm/common-hal/canio/Listener.c -msgid "All RX FIFOs in use" -msgstr "Všechny RX FIFO jsou používány" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "input matrix is asymmetric" +msgstr "" -#: ports/espressif/common-hal/busio/SPI.c ports/nordic/common-hal/busio/SPI.c -msgid "All SPI peripherals are in use" -msgstr "Všechny SPI periferie jsou používány" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "matrix is not positive definite" +msgstr "" -#: ports/espressif/common-hal/busio/UART.c ports/nordic/common-hal/busio/UART.c -msgid "All UART peripherals are in use" -msgstr "Všechny UART periferie jsou používány" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "iterations did not converge" +msgstr "" -#: ports/nordic/common-hal/countio/Counter.c -#: ports/nordic/common-hal/pulseio/PulseIn.c -#: ports/nordic/common-hal/rotaryio/IncrementalEncoder.c -msgid "All channels in use" -msgstr "Všechny kanály jsou používány" +#: extmod/ulab/code/numpy/linalg/linalg.c +#: extmod/ulab/code/scipy/linalg/linalg.c +msgid "input matrix is singular" +msgstr "" -#: ports/raspberrypi/common-hal/usb_host/Port.c -msgid "All dma channels in use" -msgstr "Všechny DMA kanály jsou používány" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "operation is defined for ndarrays only" +msgstr "operace je definována pouze pro ndarray pole" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c -msgid "All event channels in use" -msgstr "Všechny kanály událostí jsou již používány" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "operation is defined for 2D arrays only" +msgstr "operace je definována pouze pro 2D pole" -#: ports/raspberrypi/common-hal/floppyio/__init__.c -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -#: ports/raspberrypi/common-hal/usb_host/Port.c -msgid "All state machines in use" -msgstr "Všechny stavové automaty jsou používány" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "mode must be complete, or reduced" +msgstr "" -#: ports/atmel-samd/audio_dma.c -msgid "All sync event channels in use" +#: extmod/ulab/code/numpy/numerical.c +msgid "attempt to get argmin/argmax of an empty sequence" msgstr "" -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c -msgid "All timers for this pin are in use" -msgstr "Všechny časovače pro tento pin jsou používány" +#: extmod/ulab/code/numpy/numerical.c +msgid "attempt to get (arg)min/(arg)max of empty sequence" +msgstr "pokus o získání (arg)min/(arg)max z prázdné sekvence" -#: ports/atmel-samd/common-hal/_pew/PewPew.c -#: ports/atmel-samd/common-hal/audioio/AudioOut.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/nordic/common-hal/audiopwmio/PWMAudioOut.c -#: ports/nordic/common-hal/pulseio/PulseIn.c -#: ports/nordic/peripherals/nrf/timers.c -#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c -msgid "All timers in use" -msgstr "Všechny časovače jsou používány" +#: extmod/ulab/code/numpy/numerical.c extmod/ulab/code/ulab_tools.c +msgid "axis must be None, or an integer" +msgstr "osa musí být None nebo integer" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Already advertising." -msgstr "Již propagujeme." +#: extmod/ulab/code/numpy/numerical.c +msgid "operation is not implemented on ndarrays" +msgstr "" -#: ports/atmel-samd/common-hal/canio/Listener.c -msgid "Already have all-matches listener" -msgstr "Již existuje posluchač pro všechny zprávy" +#: extmod/ulab/code/numpy/numerical.c +msgid "input must be tuple, list, range, or ndarray" +msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -msgid "Already in progress" +#: extmod/ulab/code/numpy/numerical.c +msgid "sort argument must be an ndarray" msgstr "" -#: ports/espressif/bindings/espnow/ESPNow.c -#: ports/espressif/common-hal/espulp/ULP.c -#: shared-module/memorymonitor/AllocationAlarm.c -#: shared-module/memorymonitor/AllocationSize.c -msgid "Already running" -msgstr "Již běží" +#: extmod/ulab/code/numpy/numerical.c +msgid "argsort argument must be an ndarray" +msgstr "" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/raspberrypi/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "Already scanning for wifi networks" -msgstr "Již skenuje wifi sítě" +#: extmod/ulab/code/numpy/numerical.c +msgid "argsort is not implemented for flattened arrays" +msgstr "argsort není implementován pro zploštěná pole" -#: shared-module/os/getenv.c -#, c-format -msgid "An error occurred while retrieving '%s':\n" -msgstr "Došlo k chybě při načítání '%s'\n" +#: extmod/ulab/code/numpy/numerical.c +msgid "axis too long" +msgstr "osa je příliš dlouhá" -#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c -msgid "Another PWMAudioOut is already active" -msgstr "Jiný PWMAudioOut je již aktivní" +#: extmod/ulab/code/numpy/numerical.c +msgid "cross is defined for 1D arrays of length 3" +msgstr "" -#: ports/atmel-samd/common-hal/pulseio/PulseOut.c -#: ports/cxd56/common-hal/pulseio/PulseOut.c -msgid "Another send is already active" -msgstr "Další odesílání je již aktivní" +#: extmod/ulab/code/numpy/numerical.c +msgid "diff argument must be an ndarray" +msgstr "" -#: shared-bindings/pulseio/PulseOut.c -msgid "Array must contain halfwords (type 'H')" -msgstr "Pole musí obsahovat poloviční slova (typ „H“)" +#: extmod/ulab/code/numpy/numerical.c +msgid "differentiation order out of range" +msgstr "" -#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c -#: shared-bindings/nvm/ByteArray.c -msgid "Array values should be single bytes." -msgstr "Hodnoty pole by měly být jednoduché bajty." +#: extmod/ulab/code/numpy/numerical.c +msgid "flip argument must be an ndarray" +msgstr "" -#: ports/atmel-samd/common-hal/spitarget/SPITarget.c -msgid "Async SPI transfer in progress on this bus, keep awaiting." +#: extmod/ulab/code/numpy/numerical.c +msgid "wrong axis index" msgstr "" -#: shared-module/memorymonitor/AllocationAlarm.c -#, c-format -msgid "Attempt to allocate %d blocks" -msgstr "Pokus o alokování %d bloků" +#: extmod/ulab/code/numpy/numerical.c +msgid "median argument must be an ndarray" +msgstr "" -#: ports/raspberrypi/audio_dma.c -msgid "Audio conversion not implemented" -msgstr "Konverze audia není implementována" +#: extmod/ulab/code/numpy/numerical.c +msgid "roll argument must be an ndarray" +msgstr "" -#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c -#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c -msgid "Audio source error" +#: extmod/ulab/code/numpy/poly.c +msgid "input data must be an iterable" msgstr "" -#: shared-bindings/wifi/Radio.c -msgid "AuthMode.OPEN is not used with password" -msgstr "AuthMode.OPEN nepoužívá heslo" +#: extmod/ulab/code/numpy/poly.c +msgid "more degrees of freedom than data points" +msgstr "" -#: shared-bindings/wifi/Radio.c supervisor/shared/web_workflow/web_workflow.c -msgid "Authentication failure" -msgstr "Autentizace selhala" - -#: main.c -msgid "Auto-reload is off.\n" -msgstr "Automatické načtení je vypnuto.\n" +#: extmod/ulab/code/numpy/poly.c +msgid "input vectors must be of equal length" +msgstr "" -#: main.c -msgid "" -"Auto-reload is on. Simply save files over USB to run them or enter REPL to " -"disable.\n" +#: extmod/ulab/code/numpy/poly.c +msgid "could not invert Vandermonde matrix" msgstr "" -"Automatické opětovné načtení je zapnuto. Jednoduše uložte soubory přes USB a " -"spusťte je, nebo vypněte REPL.\n" -#: ports/espressif/common-hal/canio/CAN.c -msgid "Baudrate not supported by peripheral" -msgstr "Baudrate není podporován periférií" +#: extmod/ulab/code/numpy/poly.c +msgid "input is not iterable" +msgstr "vstup není iterovatelný" -#: shared-module/busdisplay/BusDisplay.c -#: shared-module/framebufferio/FramebufferDisplay.c -msgid "Below minimum frame rate" -msgstr "Pod minimální obnovovací frekvencí" +#: extmod/ulab/code/numpy/random/random.c +msgid "argument must be None, an integer or a tuple of integers" +msgstr "" -#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c -msgid "Bit clock and word select must be sequential GPIO pins" +#: extmod/ulab/code/numpy/random/random.c +msgid "shape must be None, an integer or a tuple of integers" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "Bitmap size and bits per value must match" -msgstr "Velikost bitmapy a počet bitů na hodnotu se musí shodovat" +#: extmod/ulab/code/numpy/random/random.c extmod/ulab/code/ulab_tools.c +msgid "out has wrong type" +msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Boot device must be first (interface #0)." -msgstr "Bootovací zařízení musí být první (rozhraní #0)." +#: extmod/ulab/code/numpy/random/random.c +msgid "output array has wrong type" +msgstr "" -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Both RX and TX required for flow control" -msgstr "RX a TX jsou vyžadovány pro kontrolu toku" +#: extmod/ulab/code/numpy/random/random.c +msgid "size must match out.shape when used together" +msgstr "" -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -msgid "Brightness not adjustable" -msgstr "Jas není nastavitelný" +#: extmod/ulab/code/numpy/random/random.c extmod/ulab/code/ulab_tools.c +msgid "output array must be contiguous" +msgstr "" -#: shared-bindings/_bleio/UUID.c -#, c-format -msgid "Buffer + offset too small %d %d %d" -msgstr "Vyrovnávací paměť + offset je příliš malý %d %d %d" +#: extmod/ulab/code/numpy/transform.c +msgid "wrong length of condition array" +msgstr "" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "Buffer elements must be 4 bytes long or less" -msgstr "Prvky bufferu musí být 4 bajty dlouhé nebo méně" +#: extmod/ulab/code/numpy/transform.c extmod/ulab/code/numpy/vector.c +msgid "first argument must be an ndarray" +msgstr "" -#: shared-bindings/framebufferio/FramebufferDisplay.c -msgid "Buffer is not a bytearray." -msgstr "Buffer není bytearray." +#: extmod/ulab/code/numpy/transform.c +msgid "wrong index type" +msgstr "špatný typ indexu" -#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c -#, c-format -msgid "Buffer length %d too big. It must be less than %d" -msgstr "Délka vyrovnávací paměti %d je příliš velká. Musí být menší než %d" +#: extmod/ulab/code/numpy/transform.c +msgid "wrong length of index array" +msgstr "" -#: ports/atmel-samd/common-hal/sdioio/SDCard.c -#: ports/cxd56/common-hal/sdioio/SDCard.c -#: ports/espressif/common-hal/sdioio/SDCard.c -#: ports/stm/common-hal/sdioio/SDCard.c shared-bindings/floppyio/__init__.c -#: shared-module/sdcardio/SDCard.c -#, c-format -msgid "Buffer must be a multiple of %d bytes" +#: extmod/ulab/code/numpy/transform.c +msgid "dimensions do not match" +msgstr "dimenze nesouhlasí" + +#: extmod/ulab/code/numpy/vector.c extmod/ulab/code/utils/utils.c +msgid "out must be an ndarray" msgstr "" -#: shared-bindings/_bleio/PacketBuffer.c -#, c-format -msgid "Buffer too short by %d bytes" -msgstr "Buffer je příliš krátký o %d bajtů" +#: extmod/ulab/code/numpy/vector.c +msgid "out must be of float dtype" +msgstr "" -#: ports/cxd56/common-hal/camera/Camera.c -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -#: shared-bindings/struct/__init__.c shared-module/struct/__init__.c -msgid "Buffer too small" -msgstr "Buffer příliš malý" +#: extmod/ulab/code/numpy/vector.c +msgid "input and output dimensions differ" +msgstr "dimenze vstupu a výstupu se liší" -#: ports/atmel-samd/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/nordic/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/raspberrypi/common-hal/paralleldisplaybus/ParallelBus.c -#, c-format -msgid "Bus pin %d is already in use" -msgstr "Sběrnicový pin %d je již používán" +#: extmod/ulab/code/numpy/vector.c +msgid "input and output shapes differ" +msgstr "vstupní a výstupní tvar je růzmý" -#: shared-bindings/_bleio/UUID.c -msgid "Byte buffer must be 16 bytes." -msgstr "Buffer musí být dlouhý 16 bajtů." +#: extmod/ulab/code/numpy/vector.c +msgid "out keyword is not supported for function" +msgstr "" -#: shared-bindings/aesio/aes.c -msgid "CBC blocks must be multiples of 16 bytes" -msgstr "Bloky CBC musí být násobky 16 bajtů" +#: extmod/ulab/code/numpy/vector.c +msgid "out keyword is not supported for complex dtype" +msgstr "" -#: supervisor/shared/safe_mode.c -msgid "CIRCUITPY drive could not be found or created." -msgstr "Disk CIRCUITPY nelze nalézt nebo vytvořit." +#: extmod/ulab/code/numpy/vector.c +msgid "dtype must be float, or complex" +msgstr "dtype musí být float nebo complex" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "CRC or checksum was invalid" -msgstr "CRC nebo kontrolní součet byl neplatný" +#: extmod/ulab/code/numpy/vector.c +msgid "can't convert complex to float" +msgstr "nelze převést complex na float" -#: py/objtype.c -msgid "Call super().__init__() before accessing native object." -msgstr "Volání super().__init__() před přístupem k nativnímu objektu." +#: extmod/ulab/code/numpy/vector.c +msgid "input dtype must be float or complex" +msgstr "vstupní dtype musí být float nebo complex" -#: ports/cxd56/common-hal/camera/Camera.c -msgid "Camera init" -msgstr "Inizializace kamery" +#: extmod/ulab/code/numpy/vector.c extmod/ulab/code/scipy/integrate/integrate.c +msgid "first argument must be a callable" +msgstr "První argument musí být zavolatelný" -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Can only alarm on RTC IO from deep sleep." -msgstr "Alarm z IO RTC je možné generovat pouze z hlubokého spánku." +#: extmod/ulab/code/numpy/vector.c +msgid "wrong output type" +msgstr "" -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Can only alarm on one low pin while others alarm high from deep sleep." +#: extmod/ulab/code/scipy/integrate/integrate.c +#, c-format +msgid "can't convert arg %d from %s to float" msgstr "" -"Lze nastavit alarm na jednom pinu ve stavu low při hlubokém spánku, ostatní " -"musí být ve stavu high." -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Can only alarm on two low pins from deep sleep." +#: extmod/ulab/code/scipy/integrate/integrate.c +msgid "levels needs to be a positive integer" msgstr "" -"Lze nastavit alarm na maximálně dvou pinech ve stavu low při hlubokém spánku." -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Can't construct AudioOut because continuous channel already open" +#: extmod/ulab/code/scipy/integrate/integrate.c +msgid "steps needs to be a positive integer" msgstr "" -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Characteristic.c -msgid "Can't set CCCD on local Characteristic" -msgstr "Nelze nastavit CCCD na místní charakteristiku" +#: extmod/ulab/code/scipy/integrate/integrate.c +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "first argument must be a function" +msgstr "první argument musí být funkce" -#: shared-bindings/storage/__init__.c shared-bindings/usb_cdc/__init__.c -#: shared-bindings/usb_hid/__init__.c shared-bindings/usb_midi/__init__.c -#: shared-bindings/usb_video/__init__.c -msgid "Cannot change USB devices now" -msgstr "Nelze změnit USB zařízení" +#: extmod/ulab/code/scipy/integrate/integrate.c +msgid "order needs to be a positive integer" +msgstr "" -#: shared-bindings/_bleio/Adapter.c -msgid "Cannot create a new Adapter; use _bleio.adapter;" -msgstr "Není možné vytvořit nový adaptér; použití _bleio.adapter;" +#: extmod/ulab/code/scipy/linalg/linalg.c +msgid "first two arguments must be ndarrays" +msgstr "první dva argumenty musí být ndarray" -#: shared-bindings/displayio/Bitmap.c -#: shared-bindings/memorymonitor/AllocationSize.c -#: shared-bindings/pulseio/PulseIn.c -msgid "Cannot delete values" -msgstr "Nelze odstranit hodnoty" +#: extmod/ulab/code/scipy/linalg/linalg.c extmod/ulab/code/user/user.c +msgid "input must be a dense ndarray" +msgstr "vstup musí být hustý ndarray" -#: ports/atmel-samd/common-hal/digitalio/DigitalInOut.c -#: ports/mimxrt10xx/common-hal/digitalio/DigitalInOut.c -#: ports/nordic/common-hal/digitalio/DigitalInOut.c -#: ports/raspberrypi/common-hal/digitalio/DigitalInOut.c -msgid "Cannot get pull while in output mode" -msgstr "Nelze získat ve výstupním režimu" +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "function has the same sign at the ends of interval" +msgstr "" -#: ports/nordic/common-hal/microcontroller/Processor.c -msgid "Cannot get temperature" -msgstr "Nelze získat teplotu (°C)" +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "maxiter should be > 0" +msgstr "maxiter by měl být > 0" -#: shared-bindings/_bleio/Adapter.c -msgid "Cannot have scan responses for extended, connectable advertisements." -msgstr "" +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "maxiter must be > 0" +msgstr "maxiter musí být > 0" -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Cannot pull on input-only pin." -msgstr "Nelze aktivovat pull rezistor na pinu, který je pouze pro vstup." +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "data must be iterable" +msgstr "data musí být iterovatelná" -#: shared-bindings/audiobusio/PDMIn.c -msgid "Cannot record to a file" -msgstr "Nelze nahrávat do souboru" +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "initial values must be iterable" +msgstr "výchozí hodnoty musí být iterovatelné" -#: shared-module/storage/__init__.c -msgid "Cannot remount '/' when visible via USB." -msgstr "Není možné znovu připojit '/', pokud je viditelné pomocí USB." +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "data must be of equal length" +msgstr "data musí mít stejnou délku" -#: shared-bindings/digitalio/DigitalInOut.c -msgid "Cannot set value when direction is input." -msgstr "Nelze nastavit hodnotu, když směr je vstup." +#: extmod/ulab/code/scipy/signal/signal.c +msgid "sosfilt requires iterable arguments" +msgstr "" -#: ports/espressif/common-hal/busio/UART.c -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Cannot specify RTS or CTS in RS485 mode" -msgstr "Nelze určit RTS nebo CTS v režimu RS485" +#: extmod/ulab/code/scipy/signal/signal.c +msgid "input must be one-dimensional" +msgstr "vstup musí být jednorozměrný" -#: py/objslice.c -msgid "Cannot subclass slice" -msgstr "Nelze použít řez podtřídy" +#: extmod/ulab/code/scipy/signal/signal.c +msgid "zi must be an ndarray" +msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Cannot use GPIO0..15 together with GPIO32..47" +#: extmod/ulab/code/scipy/signal/signal.c +msgid "zi must be of shape (n_section, 2)" msgstr "" -#: ports/nordic/common-hal/alarm/pin/PinAlarm.c -msgid "Cannot wake on pin edge, only level" -msgstr "Nelze probudit hranou na pinu, pouze úrovní" +#: extmod/ulab/code/scipy/signal/signal.c +msgid "zi must be of float type" +msgstr "" -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Cannot wake on pin edge. Only level." -msgstr "Nelze probudit hranou na pinu. Pouze úrovní." - -#: shared-bindings/_bleio/CharacteristicBuffer.c -msgid "CharacteristicBuffer writing not provided" -msgstr "CharacteristicBuffer psaní není poskytováno" +#: extmod/ulab/code/scipy/signal/signal.c +msgid "sos array must be of shape (n_section, 6)" +msgstr "" -#: supervisor/shared/safe_mode.c -msgid "CircuitPython core code crashed hard. Whoops!\n" -msgstr "Jádro kódu CircuitPython tvrdě havarovalo. Jejda!\n" +#: extmod/ulab/code/scipy/signal/signal.c +msgid "sos[:, 3] should be all ones" +msgstr "" -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -msgid "Clock unit in use" -msgstr "Jednotka hodin je používána" +#: extmod/ulab/code/ulab_tools.c +msgid "axis is out of bounds" +msgstr "osa je mimo rozsah" -#: shared-bindings/_bleio/Connection.c -msgid "" -"Connection has been disconnected and can no longer be used. Create a new " -"connection." +#: extmod/ulab/code/ulab_tools.c +msgid "size is defined for ndarrays only" msgstr "" -"Připojení bylo odpojeno a nelze jej dále používat. Vytvořte nové připojení." - -#: shared-bindings/bitmaptools/__init__.c -msgid "Coordinate arrays have different lengths" -msgstr "Pole souřadnic mají různé délky" -#: shared-bindings/bitmaptools/__init__.c -msgid "Coordinate arrays types have different sizes" +#: extmod/ulab/code/ulab_tools.c +msgid "input must be square matrix" msgstr "" -#: shared-bindings/_bleio/Adapter.c -msgid "Could not set address" -msgstr "Není možné nastavit adresu" +#: extmod/ulab/code/ulab_tools.c +msgid "out array has wrong dtype" +msgstr "" -#: ports/stm/common-hal/busio/UART.c -msgid "Could not start interrupt, RX busy" -msgstr "Nelze začít přerušení, RX je zaneprázdněn" +#: extmod/ulab/code/ulab_tools.c +msgid "out array has wrong dimension" +msgstr "" -#: shared-module/audiomp3/MP3Decoder.c -msgid "Couldn't allocate decoder" -msgstr "Dekodér nelze přiřadit" +#: extmod/ulab/code/ulab_tools.c +msgid "out array has wrong shape" +msgstr "" -#: ports/stm/common-hal/analogio/AnalogOut.c -msgid "DAC Channel Init Error" -msgstr "Chyba inicializace kanálu DAC" +#: extmod/ulab/code/utils/utils.c +msgid "out must be a float dense array" +msgstr "" -#: ports/stm/common-hal/analogio/AnalogOut.c -msgid "DAC Device Init Error" -msgstr "Chyba inicializace zařízení DAC" +#: extmod/ulab/code/utils/utils.c +msgid "offset is too large" +msgstr "offset je příliš velký" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c -msgid "DAC already in use" -msgstr "DAC se již používá" +#: extmod/ulab/code/utils/utils.c +msgid "out array is too small" +msgstr "výstupní pole je příliš malé" -#: ports/atmel-samd/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/nordic/common-hal/paralleldisplaybus/ParallelBus.c -msgid "Data 0 pin must be byte aligned" -msgstr "Datový pin 0 musí být zarovnán na bajty" +#: extmod/ulab/code/utils/utils.c +msgid "spectrogram is defined for ndarrays only" +msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "Data format error (may be broken data)" +#: extmod/ulab/code/utils/utils.c +msgid "spectrogram is implemented for 1D arrays only" msgstr "" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Data not supported with directed advertising" -msgstr "Data nejsou podporována s cíleným oznamováním" +#: extmod/ulab/code/utils/utils.c +msgid "out array must be a 1D array of float type" +msgstr "" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Data too large for advertisement packet" -msgstr "Data jsou příliš velká pro propagovaný paket" +#: extmod/ulab/code/utils/utils.c +msgid "input and out arrays must have same length" +msgstr "" -#: ports/stm/common-hal/alarm/pin/PinAlarm.c -msgid "Deep sleep pins must use a rising edge with pulldown" +#: extmod/ulab/code/utils/utils.c +msgid "scratchpad must be an ndarray" msgstr "" -"Piny pro hluboký spánek musí používat náběžnou hranu s pulldown rezistorem" -#: shared-bindings/audiobusio/PDMIn.c -msgid "Destination capacity is smaller than destination_length." -msgstr "Cílová kapacita je menší než destination_length." +#: extmod/ulab/code/utils/utils.c +msgid "scratchpad must be a 1D dense float array" +msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "Device error or wrong termination of input stream" +#: extmod/ulab/code/utils/utils.c +msgid "scratchpad must be twice as long as input" msgstr "" -#: ports/nordic/common-hal/audiobusio/I2SOut.c -msgid "Device in use" -msgstr "Zařízení je používáno" +#: extmod/vfs_fat.c py/moderrno.c +msgid "Read-only filesystem" +msgstr "Filesystém pouze pro čtení" -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -msgid "Display must have a 16 bit colorspace." -msgstr "Displej musí mít 16bitový barevný prostor." +#: extmod/vfs_posix_file.c py/objstringio.c +msgid "I/O operation on closed file" +msgstr "I/O operace nad zavřeným souborem" -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/epaperdisplay/EPaperDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -msgid "Display rotation must be in 90 degree increments" -msgstr "Otočení displeje musí být po 90 stupních" +#: extmod/vfs_posix_file.c +msgid "poll on file not available on win32" +msgstr "" #: main.c msgid "Done" msgstr "Hotovo" -#: shared-bindings/digitalio/DigitalInOut.c -msgid "Drive mode not used when direction is input." +#: main.c +msgid " output:\n" +msgstr " výstup:\n" + +#: main.c +msgid "" +"Auto-reload is on. Simply save files over USB to run them or enter REPL to " +"disable.\n" msgstr "" +"Automatické opětovné načtení je zapnuto. Jednoduše uložte soubory přes USB a " +"spusťte je, nebo vypněte REPL.\n" -#: py/obj.c -msgid "During handling of the above exception, another exception occurred:" -msgstr "Při zpracování uvedené výjimky nastala další výjimka:" +#: main.c +msgid "Auto-reload is off.\n" +msgstr "Automatické načtení je vypnuto.\n" -#: shared-bindings/aesio/aes.c -msgid "ECB only operates on 16 bytes at a time" -msgstr "ECB operuje najednou pouze 16 bajtů" +#: main.c +msgid "Running in safe mode! Not running saved code.\n" +msgstr "Běh v nouzovém režimu! Uložený kód není zpracováván.\n" -#: ports/espressif/common-hal/busio/SPI.c -#: ports/espressif/common-hal/canio/CAN.c -msgid "ESP-IDF memory allocation failed" -msgstr "ESP-IDF alokace paměti selhala" +#: main.c +msgid " not found.\n" +msgstr " nenalezen\n" -#: extmod/modre.c -msgid "Error in regex" -msgstr "Chyba v regulárním výrazu" +#: main.c +msgid "WARNING: Your code filename has two extensions\n" +msgstr "UPOZORNĚNÍ: Název souboru vašeho kódu má dvě koncovky\n" -#: supervisor/shared/safe_mode.c -msgid "Error in safemode.py." -msgstr "Chyba v safemode.py." +#: main.c +msgid "" +"\n" +"Code stopped by auto-reload. Reloading soon.\n" +msgstr "" +"\n" +"Kód byl zastaven kvůli automatickému načtení. K načtení dojde brzy.\n" -#: shared-bindings/alarm/__init__.c -msgid "Expected a kind of %q" -msgstr "Očekáván typ %q" +#: main.c +msgid "" +"\n" +"Code done running.\n" +msgstr "" +"\n" +"Běh programu byl dokončen.\n" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Extended advertisements with scan response not supported." +#: main.c +msgid "Woken up by alarm.\n" +msgstr "Probuzen alarmem.\n" + +#: main.c +msgid "Press any key to enter the REPL. Use CTRL-D to reload.\n" msgstr "" +"Zmáčkněte jakoukoli klávesu pro spuštění REPLu. Použijte CTRL-D pro opětovné " +"načtení.\n" -#: extmod/ulab/code/numpy/fft/fft_tools.c -msgid "FFT is defined for ndarrays only" -msgstr "FFT lze použít pouze pro ndarrays" +#: main.c +msgid "Pretending to deep sleep until alarm, CTRL-C or file write.\n" +msgstr "Předstírám hluboký spánek do alarmu, CTRL-C nebo zápisu souboru.\n" -#: extmod/ulab/code/numpy/fft/fft_tools.c -msgid "FFT is implemented for linear arrays only" -msgstr "FFT je implementován pouze pro lineární pole" +#: main.c +msgid "UID:" +msgstr "UID:" -#: shared-bindings/ps2io/Ps2.c -msgid "Failed sending command." -msgstr "Nepodařilo se odeslat příkaz." +#: main.c +msgid "soft reboot\n" +msgstr "" -#: ports/nordic/sd_mutex.c -#, c-format -msgid "Failed to acquire mutex, err 0x%04x" -msgstr "Nepodařilo se získat mutex, err 0x%04x" +#: ports/analog/common-hal/busio/SPI.c ports/analog/common-hal/busio/UART.c +#: ports/cxd56/common-hal/busio/SPI.c ports/stm/common-hal/audioio/AudioOut.c +#: shared-bindings/digitalio/DigitalInOutProtocol.c +#: shared-module/displayio/bus_core.c shared-module/ssl/SSLContext.c +msgid "%q init failed" +msgstr "Inicializace %q selhala" -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "Failed to add service TXT record" +#: ports/analog/common-hal/busio/SPI.c +msgid "SPI needs MOSI, MISO, and SCK" msgstr "" -#: shared-bindings/mdns/Server.c -msgid "" -"Failed to add service TXT record; non-string or bytes found in txt_records" +#: ports/analog/common-hal/busio/SPI.c +#: ports/atmel-samd/common-hal/pulseio/PulseIn.c +#: ports/cxd56/common-hal/pulseio/PulseIn.c +#: ports/nordic/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#: ports/stm/common-hal/pulseio/PulseIn.c py/argcheck.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/canio/Match.c +#: shared-bindings/time/__init__.c +msgid "%q out of range" +msgstr "%q je mimo rozsah" + +#: ports/analog/common-hal/busio/SPI.c +#: ports/espressif/common-hal/espidf/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: shared-bindings/epaperdisplay/EPaperDisplay.c +msgid "Invalid state" +msgstr "Chybný stav" + +#: ports/analog/common-hal/busio/SPI.c +msgid "Failed to set SPI Clock Mode" +msgstr "" + +#: ports/analog/common-hal/busio/UART.c +#: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c +#: ports/nordic/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/zephyr-cp/common-hal/busio/UART.c +msgid "RS485" +msgstr "RS485" + +#: ports/analog/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c +msgid "UART needs TX & RX" msgstr "" +#: ports/analog/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c +msgid "Both RX and TX required for flow control" +msgstr "RX a TX jsou vyžadovány pro kontrolu toku" + +#: ports/analog/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/usb_host/Port.c #: shared-module/rgbmatrix/RGBMatrix.c msgid "Failed to allocate %q buffer" msgstr "Chyba alokace %q bufferu" -#: ports/espressif/common-hal/wifi/__init__.c -msgid "Failed to allocate Wifi memory" -msgstr "Chyba alokace paměti WiFi" +#: ports/analog/common-hal/busio/UART.c +msgid "UART read error" +msgstr "" -#: ports/espressif/common-hal/wifi/ScannedNetworks.c -msgid "Failed to allocate wifi scan memory" -msgstr "Nepodařilo se alokovat paměť pro wifi scan" +#: ports/analog/common-hal/busio/UART.c +msgid "UART transaction timeout" +msgstr "" -#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c -msgid "Failed to buffer the sample" -msgstr "Nepodařilo se nabufferovat sample" +#: ports/analog/common-hal/busio/UART.c ports/espressif/common-hal/busio/UART.c +#: ports/nordic/common-hal/busio/UART.c ports/zephyr-cp/common-hal/busio/UART.c +msgid "All UART peripherals are in use" +msgstr "Všechny UART periferie jsou používány" + +#: ports/analog/common-hal/busio/UART.c +#: ports/analog/peripherals/max32690/max32_i2c.c +#: ports/analog/peripherals/max32690/max32_spi.c +#: ports/analog/peripherals/max32690/max32_uart.c +#: ports/espressif/common-hal/_bleio/Service.c +#: ports/espressif/common-hal/espulp/ULP.c +#: ports/espressif/common-hal/jpegio/JpegDecoder.c +#: ports/espressif/common-hal/microcontroller/Processor.c +#: ports/espressif/common-hal/mipidsi/Display.c +#: ports/mimxrt10xx/common-hal/audiobusio/__init__.c +#: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c +#: ports/raspberrypi/bindings/picodvi/Framebuffer.c +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +#: ports/raspberrypi/common-hal/picodvi/AudioOut.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c +#: ports/raspberrypi/common-hal/usb_host_bulk/InStream.c py/argcheck.c +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/utils/__init__.c +#: shared-bindings/digitalio/DigitalInOut.c +#: shared-bindings/epaperdisplay/EPaperDisplay.c +#: shared-bindings/i2cioexpander/IOPin.c shared-bindings/mipidsi/Display.c +#: shared-bindings/pwmio/PWMOut.c shared-bindings/supervisor/__init__.c +#: shared-module/aurora_epaper/aurora_framebuffer.c +#: shared-module/cryptography/hazmat/primitives/asymmetric/ec/EllipticCurvePublicKey.c +#: shared-module/jpegio/JpegDecoder.c shared-module/lvfontio/OnDiskFont.c +msgid "Invalid %q" +msgstr "Špatný %s" + +#: ports/analog/common-hal/busio/UART.c +msgid "Timeout must be < 100 seconds" +msgstr "" + +#: ports/atmel-samd/audio_dma.c +msgid "All sync event channels in use" +msgstr "" + +#: ports/atmel-samd/audio_dma.c ports/raspberrypi/audio_dma.c +msgid "Internal audio buffer too small" +msgstr "Interní audio buffer je příliš malý" + +#: ports/atmel-samd/bindings/samd/Clock.c +msgid "calibration is read only" +msgstr "" + +#: ports/atmel-samd/bindings/samd/Clock.c +msgid "calibration is out of range" +msgstr "" + +#: 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/meowmeow/mpconfigboard.h +msgid "You pressed both buttons at start up." +msgstr "Při spuštění jsi stiskl obě tlačítka." + +#: ports/atmel-samd/common-hal/_pew/PewPew.c +#: ports/atmel-samd/common-hal/audioio/AudioOut.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/nordic/common-hal/audiopwmio/PWMAudioOut.c +#: ports/nordic/common-hal/pulseio/PulseIn.c +#: ports/nordic/peripherals/nrf/timers.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +#: ports/stm/common-hal/pulseio/PulseOut.c +msgid "All timers in use" +msgstr "Všechny časovače jsou používány" + +#: ports/atmel-samd/common-hal/alarm/pin/PinAlarm.c +#: ports/atmel-samd/common-hal/countio/Counter.c +#: ports/atmel-samd/common-hal/frequencyio/FrequencyIn.c +#: ports/atmel-samd/common-hal/max3421e/Max3421E.c +#: ports/atmel-samd/common-hal/ps2io/Ps2.c +#: ports/atmel-samd/common-hal/pulseio/PulseIn.c +#: ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.c +#: ports/cxd56/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c +#: ports/zephyr-cp/common-hal/async_spi/SPI.c +#: ports/zephyr-cp/common-hal/busio/I2C.c +#: ports/zephyr-cp/common-hal/busio/UART.c +msgid "Internal resource(s) in use" +msgstr "" + +#: ports/atmel-samd/common-hal/alarm/pin/PinAlarm.c +#: supervisor/shared/safe_mode.c +msgid "Unknown reason." +msgstr "Neznámý důvod." + +#: ports/atmel-samd/common-hal/alarm/time/TimeAlarm.c +#: ports/nordic/common-hal/alarm/time/TimeAlarm.c +#: ports/stm/common-hal/alarm/time/TimeAlarm.c +msgid "Only one alarm.time alarm can be set" +msgstr "Lze nastavit pouze jeden alarm typu alarm.time" + +#: ports/atmel-samd/common-hal/analogio/AnalogOut.c +#: ports/stm/common-hal/analogio/AnalogOut.c +#: ports/stm/common-hal/audioio/AudioOut.c +msgid "No DAC on chip" +msgstr "Žádný DAC na čipu" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +msgid "%q and %q must share a clock unit" +msgstr "" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +msgid "Serializer in use" +msgstr "" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +msgid "Clock unit in use" +msgstr "Jednotka hodin je používána" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/atmel-samd/common-hal/touchio/TouchIn.c +msgid "No free GCLKs" +msgstr "Žádné volné GCLK" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +msgid "Too many channels in sample" +msgstr "V samplu je příliš mnoho kanálů" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +#: ports/raspberrypi/common-hal/mcp4822/MCP4822.c +msgid "No DMA channel found" +msgstr "Nebyl nalezen žádný kanál DMA" + +#: 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 +#: ports/raspberrypi/common-hal/mcp4822/MCP4822.c +msgid "Unable to allocate buffers for signed conversion" +msgstr "" + +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c +#, c-format +msgid "Only 8 or 16 bit mono with %dx oversampling supported." +msgstr "" + +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c +msgid "sampling rate out of range" +msgstr "" + +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +msgid "DAC already in use" +msgstr "DAC se již používá" + +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +msgid "Right channel unsupported" +msgstr "Pravý kanál nepodporován" + +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +msgid "All event channels in use" +msgstr "Všechny kanály událostí jsou již používány" + +#: ports/atmel-samd/common-hal/busio/I2C.c +#: ports/espressif/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nordic/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 "SDA nebo SCL zřejmě nemá pull up; zkontroluj zapojení" + +#: ports/atmel-samd/common-hal/busio/UART.c +#: shared-bindings/usb_host_bulk/InStream.c +msgid "%q must be power of 2" +msgstr "%q musí být mocnina 2" + +#: ports/atmel-samd/common-hal/busio/UART.c +#: ports/espressif/common-hal/busio/SPI.c +#: ports/espressif/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/SPI.c +#: ports/mimxrt10xx/common-hal/busio/UART.c +#: ports/nordic/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c ports/stm/common-hal/busio/SPI.c +#: ports/stm/common-hal/busio/UART.c shared-bindings/fourwire/FourWire.c +#: shared-bindings/i2cdisplaybus/I2CDisplayBus.c +#: shared-bindings/paralleldisplaybus/ParallelBus.c +#: shared-bindings/qspibus/QSPIBus.c shared-module/bitbangio/SPI.c +msgid "No %q pin" +msgstr "Žádný %q pin" + +#: ports/atmel-samd/common-hal/canio/Listener.c +#: ports/espressif/common-hal/canio/Listener.c +#: ports/stm/common-hal/canio/Listener.c +msgid "All RX FIFOs in use" +msgstr "Všechny RX FIFO jsou používány" + +#: ports/atmel-samd/common-hal/canio/Listener.c +msgid "Already have all-matches listener" +msgstr "Již existuje posluchač pro všechny zprávy" + +#: ports/atmel-samd/common-hal/canio/Listener.c +#: ports/espressif/common-hal/canio/Listener.c +#: ports/mimxrt10xx/common-hal/canio/Listener.c +#: ports/stm/common-hal/canio/Listener.c +msgid "Filters too complex" +msgstr "Filtry jsou příliš komplexní" + +#: ports/atmel-samd/common-hal/digitalio/DigitalInOut.c +#: ports/mimxrt10xx/common-hal/digitalio/DigitalInOut.c +#: ports/nordic/common-hal/digitalio/DigitalInOut.c +#: ports/raspberrypi/common-hal/digitalio/DigitalInOut.c +msgid "Cannot get pull while in output mode" +msgstr "Nelze získat ve výstupním režimu" + +#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c +#, c-format +msgid "Invalid data_pins[%d]" +msgstr "Chybný data_pin[%d]" + +#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c +#, c-format +msgid "data pin #%d in use" +msgstr "datový pin #%d je používán" + +#: ports/atmel-samd/common-hal/microcontroller/Pin.c +#: ports/espressif/common-hal/dotclockframebuffer/DotClockFramebuffer.c +#: ports/mimxrt10xx/common-hal/microcontroller/Pin.c +#: shared-bindings/emmcio/EMMC.c shared-bindings/microcontroller/Pin.c +msgid "Invalid %q pin" +msgstr "Neplatný pin %q" + +#: ports/atmel-samd/common-hal/microcontroller/__init__.c +#: ports/cxd56/common-hal/microcontroller/__init__.c +#: ports/mimxrt10xx/common-hal/microcontroller/__init__.c +msgid "No bootloader present" +msgstr "" + +#: ports/atmel-samd/common-hal/paralleldisplaybus/ParallelBus.c +#: ports/nordic/common-hal/paralleldisplaybus/ParallelBus.c +msgid "Data 0 pin must be byte aligned" +msgstr "Datový pin 0 musí být zarovnán na bajty" + +#: ports/atmel-samd/common-hal/paralleldisplaybus/ParallelBus.c +#: ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c +#: ports/nordic/common-hal/paralleldisplaybus/ParallelBus.c +#: ports/raspberrypi/common-hal/paralleldisplaybus/ParallelBus.c +#, c-format +msgid "Bus pin %d is already in use" +msgstr "Sběrnicový pin %d je již používán" + +#: ports/atmel-samd/common-hal/pulseio/PulseIn.c +#: ports/cxd56/common-hal/pulseio/PulseIn.c +#: ports/nordic/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 z prázdného %q" + +#: ports/atmel-samd/common-hal/pulseio/PulseIn.c +msgid "Input taking too long" +msgstr "Vstup trval příliš dlouho" + +#: ports/atmel-samd/common-hal/pulseio/PulseOut.c +#: ports/cxd56/common-hal/pulseio/PulseOut.c +msgid "Another send is already active" +msgstr "Další odesílání je již aktivní" + +#: ports/atmel-samd/common-hal/sdioio/SDCard.c +#: ports/espressif/common-hal/mii/Ethernet.c +#: ports/espressif/common-hal/qspibus/QSPIBus.c shared-bindings/emmcio/EMMC.c +#: shared-bindings/socketpool/SocketPool.c +msgid "%q failure: %d" +msgstr "%q: selhání %d" + +#: ports/atmel-samd/common-hal/sdioio/SDCard.c +#: ports/cxd56/common-hal/sdioio/SDCard.c +#: ports/espressif/common-hal/sdioio/SDCard.c +#: ports/raspberrypi/common-hal/sdioio/SDCard.c +#: ports/stm/common-hal/sdioio/SDCard.c shared-bindings/audiocore/WaveFile.c +#: shared-bindings/emmcio/EMMC.c shared-bindings/floppyio/__init__.c +#: shared-bindings/picogame/Canvas.c shared-module/sdcardio/SDCard.c +#, c-format +msgid "Buffer must be a multiple of %d bytes" +msgstr "" + +#: ports/atmel-samd/common-hal/spitarget/SPITarget.c +msgid "Async SPI transfer in progress on this bus, keep awaiting." +msgstr "" + +#: ports/cxd56/common-hal/busio/UART.c ports/espressif/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c +msgid "UART init" +msgstr "Inicializace UART" + +#: ports/cxd56/common-hal/camera/Camera.c +msgid "Camera init" +msgstr "Inizializace kamery" + +#: ports/cxd56/common-hal/camera/Camera.c +msgid "Size not supported" +msgstr "Velikost není podporována" + +#: ports/cxd56/common-hal/camera/Camera.c +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +#: shared-bindings/struct/__init__.c shared-module/struct/__init__.c +#: shared-module/videocore/VideoBuffer.c +msgid "Buffer too small" +msgstr "Buffer příliš malý" + +#: ports/cxd56/common-hal/camera/Camera.c +#: ports/espressif/common-hal/jpegio/JpegDecoder.c +#: shared-module/audiocore/WaveFile.c +#: shared-module/busdisplay/lvgl/BusDisplay.c +#: shared-module/displayio/lvgl/TileGrid.c +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "Format not supported" +msgstr "Formát není podporován" + +#: ports/cxd56/common-hal/gnss/GNSS.c +msgid "GNSS init" +msgstr "Inicializace GNSS" + +#: ports/cxd56/common-hal/sdioio/SDCard.c +msgid "SDCard init" +msgstr "Inicializace SD karty" + +#: ports/espressif/bindings/espnow/ESPNow.c +#: ports/espressif/common-hal/espulp/ULP.c +#: ports/raspberrypi/common-hal/usb_host_bulk/InStream.c +#: shared-module/memorymonitor/AllocationAlarm.c +#: shared-module/memorymonitor/AllocationSize.c +msgid "Already running" +msgstr "Již běží" + +#: ports/espressif/bindings/espnow/Peer.c shared-bindings/dualbank/__init__.c +msgid "%q is %q" +msgstr "%q je %q" + +#: ports/espressif/boards/adafruit_feather_esp32_v2/mpconfigboard.h +msgid "You pressed the SW38 button at start up." +msgstr "Při spuštění jsi stiskl tlačítko SW38." + +#: ports/espressif/boards/adafruit_feather_esp32c6_4mbflash_nopsram/mpconfigboard.h +#: ports/espressif/boards/adafruit_itsybitsy_esp32/mpconfigboard.h +#: ports/espressif/boards/waveshare_esp32_c5_lcd_1_47/mpconfigboard.h +#: ports/espressif/boards/waveshare_esp32_c6_lcd_1_47/mpconfigboard.h +msgid "You pressed the BOOT button at start up." +msgstr "" + +#: ports/espressif/boards/adafruit_huzzah32_breakout/mpconfigboard.h +msgid "You pressed the GPIO0 button at start up." +msgstr "Při spuštění jsi stiskl tlačítko na pinu GPIO0." + +#: ports/espressif/boards/espressif_esp32_lyrat/mpconfigboard.h +msgid "You pressed the Rec button at start up." +msgstr "Při spuštění jsi stiskl tlačítko Rec." + +#: ports/espressif/boards/hardkernel_odroid_go/mpconfigboard.h +#: ports/espressif/boards/vidi_x/mpconfigboard.h +msgid "You pressed the VOLUME button at start up." +msgstr "Při spuštění jsi stiskl tlačítko VOLUME." + +#: ports/espressif/boards/m5stack_atom_echo/mpconfigboard.h +#: ports/espressif/boards/m5stack_atom_lite/mpconfigboard.h +#: ports/espressif/boards/m5stack_atom_matrix/mpconfigboard.h +#: ports/espressif/boards/m5stack_atom_u/mpconfigboard.h +msgid "You pressed the central button at start up." +msgstr "Při spuštění jsi stiskl středové tlačítko." + +#: ports/espressif/boards/m5stack_core_basic/mpconfigboard.h +#: ports/espressif/boards/m5stack_core_fire/mpconfigboard.h +#: ports/espressif/boards/m5stack_stick_c/mpconfigboard.h +#: ports/espressif/boards/m5stack_stick_c_plus/mpconfigboard.h +#: ports/espressif/boards/m5stack_stick_c_plus2/mpconfigboard.h +msgid "You pressed button A at start up." +msgstr "Při spuštění jsi stiskl tlačítko A." + +#: ports/espressif/boards/m5stack_m5paper/mpconfigboard.h +msgid "You pressed button DOWN at start up." +msgstr "Při spuštění jsi stiskl tlačítko DOWN." + +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/espressif/common-hal/dualbank/__init__.c +msgid "Update failed" +msgstr "" + +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "Scan already in progress. Stop with stop_scan." +msgstr "Scan již probíhá. Lze zastavit pomocí stop_scan." + +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +#: ports/zephyr-cp/common-hal/_bleio/Adapter.c +msgid "Failed to connect: timeout" +msgstr "Nepodařilo se připojit: časový limit" + +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +#: ports/zephyr-cp/common-hal/_bleio/Adapter.c +msgid "Failed to connect: internal error" +msgstr "Připojení se nezdařilo: interní chyba" + +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +#: ports/zephyr-cp/common-hal/_bleio/Adapter.c +msgid "Data too large for advertisement packet" +msgstr "Data jsou příliš velká pro propagovaný paket" + +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "Already advertising." +msgstr "Již propagujeme." + +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "Extended advertisements with scan response not supported." +msgstr "" + +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "Data not supported with directed advertising" +msgstr "Data nejsou podporována s cíleným oznamováním" + +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +#, c-format +msgid "Timeout is too long: Maximum timeout length is %d seconds" +msgstr "Časový limit je příliš dlouhý: maximální limit je %d vteřin" + +#: ports/espressif/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Descriptor.c +msgid "Value length != required fixed length" +msgstr "" + +#: ports/espressif/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Descriptor.c +msgid "Value length > max_length" +msgstr "" + +#: ports/espressif/common-hal/_bleio/Characteristic.c +#: ports/espressif/common-hal/_bleio/Service.c +#: ports/raspberrypi/common-hal/alarm/pin/PinAlarm.c +#: ports/raspberrypi/common-hal/usb_host_bulk/InStream.c +msgid "Too many %q" +msgstr "" + +#: ports/espressif/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Characteristic.c +#: ports/zephyr-cp/common-hal/_bleio/Characteristic.c +msgid "No CCCD for this Characteristic" +msgstr "Žádné CCCD pro tuto charakteristiku" + +#: ports/espressif/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Characteristic.c +msgid "Can't set CCCD on local Characteristic" +msgstr "Nelze nastavit CCCD na místní charakteristiku" + +#: ports/espressif/common-hal/_bleio/Connection.c +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/Characteristic.c +#: ports/zephyr-cp/common-hal/_bleio/Connection.c +#: ports/zephyr-cp/common-hal/_bleio/Descriptor.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +#: shared-bindings/_bleio/CharacteristicBuffer.c +msgid "Not connected" +msgstr "Nepřipojený" + +#: ports/espressif/common-hal/_bleio/Connection.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/Connection.c +msgid "" +"Unspecified issue. The pairing request on the other device may have been " +"declined or ignored." +msgstr "" + +#: ports/espressif/common-hal/_bleio/Connection.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/Connection.c +#, c-format +msgid "Unknown security error: 0x%04x" +msgstr "Neznámá bezpečnostní chyba: 0x%04x" + +#: ports/espressif/common-hal/_bleio/Connection.c +msgid "No pairing in progress" +msgstr "" + +#: ports/espressif/common-hal/_bleio/Connection.c +#: ports/nordic/common-hal/_bleio/Connection.c +msgid "non-UUID found in service_uuids_whitelist" +msgstr "" + +#: ports/espressif/common-hal/_bleio/Descriptor.c +#: ports/nordic/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Descriptor.c +#, c-format +msgid "max_length must be 0-%d when fixed_length is %s" +msgstr "" + +#: ports/espressif/common-hal/_bleio/PacketBuffer.c +#: ports/nordic/common-hal/_bleio/PacketBuffer.c +#: ports/zephyr-cp/common-hal/_bleio/PacketBuffer.c +msgid "Writes not supported on Characteristic" +msgstr "" + +#: ports/espressif/common-hal/_bleio/PacketBuffer.c +#: ports/nordic/common-hal/_bleio/PacketBuffer.c +#: ports/zephyr-cp/common-hal/_bleio/PacketBuffer.c +msgid "Total data to write is larger than %q" +msgstr "Velikost dat k zápisu je větší než %q" + +#: ports/espressif/common-hal/_bleio/__init__.c +msgid "Nimble out of memory" +msgstr "" + +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +msgid "Invalid BLE parameter" +msgstr "Chybný BLE parametr" + +#: ports/espressif/common-hal/_bleio/__init__.c +#: shared-module/audiofilewriter/AudioFileWriter.c +msgid "Already in progress" +msgstr "" + +#: ports/espressif/common-hal/_bleio/__init__.c +#, c-format +msgid "Unknown BLE error at %s:%d: 0x%04x" +msgstr "" + +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#, c-format +msgid "Unknown BLE error: 0x%04x" +msgstr "" + +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +msgid "%q not permitted" +msgstr "" + +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +msgid "Insufficient authentication" +msgstr "Nedostatečná autentizace" + +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +msgid "Insufficient authorization" +msgstr "" + +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +msgid "Insufficient encryption" +msgstr "Nedostatečné šifrování" + +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +#, c-format +msgid "Unknown gatt error: 0x%04x" +msgstr "" + +#: ports/espressif/common-hal/alarm/pin/PinAlarm.c +msgid "Cannot wake on pin edge. Only level." +msgstr "Nelze probudit hranou na pinu. Pouze úrovní." + +#: ports/espressif/common-hal/alarm/pin/PinAlarm.c +msgid "Cannot pull on input-only pin." +msgstr "Nelze aktivovat pull rezistor na pinu, který je pouze pro vstup." + +#: ports/espressif/common-hal/alarm/pin/PinAlarm.c +msgid "Can only alarm on two low pins from deep sleep." +msgstr "" +"Lze nastavit alarm na maximálně dvou pinech ve stavu low při hlubokém spánku." + +#: ports/espressif/common-hal/alarm/pin/PinAlarm.c +msgid "Can only alarm on one low pin while others alarm high from deep sleep." +msgstr "" +"Lze nastavit alarm na jednom pinu ve stavu low při hlubokém spánku, ostatní " +"musí být ve stavu high." + +#: ports/espressif/common-hal/alarm/pin/PinAlarm.c +msgid "Can only alarm on RTC IO from deep sleep." +msgstr "Alarm z IO RTC je možné generovat pouze z hlubokého spánku." -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Failed to connect: internal error" -msgstr "Připojení se nezdařilo: interní chyba" +#: ports/espressif/common-hal/alarm/time/TimeAlarm.c +#: ports/raspberrypi/common-hal/alarm/time/TimeAlarm.c +msgid "Only one alarm.time alarm can be set." +msgstr "Může být nastaven pouze jeden alarm typu alarm.time." -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Failed to connect: timeout" -msgstr "Nepodařilo se připojit: časový limit" +#: ports/espressif/common-hal/alarm/touch/TouchAlarm.c +msgid "Only one %q can be set in deep sleep." +msgstr "Pouze jeden %q lze nastavit v hlubokém spánku." + +#: ports/espressif/common-hal/analogbufio/BufferedIn.c +msgid "%q must be array of type 'H'" +msgstr "%q musí být pole typu 'H V" + +#: ports/espressif/common-hal/audiobusio/PDMIn.c +#: shared-bindings/audioi2sin/I2SIn.c shared-bindings/usb_host_audio/USBIn.c +msgid "%q must be 8, 16, 24, or 32" +msgstr "" + +#: ports/espressif/common-hal/audiobusio/__init__.c +#: ports/espressif/common-hal/audioi2sin/I2SIn.c +#: ports/espressif/common-hal/mii/Ethernet.c shared-bindings/emmcio/EMMC.c +msgid "Peripheral in use" +msgstr "Periférie je používána" + +#: ports/espressif/common-hal/audioi2sin/I2SIn.c +#: ports/raspberrypi/common-hal/audioi2sin/I2SIn.c +msgid "%q must be 8 or 16" +msgstr "" #: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to create continuous channels: invalid arg" +msgid "audio format not supported" msgstr "" #: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to create continuous channels: invalid state" +msgid "Failed to start async audio" msgstr "" #: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to create continuous channels: no mem" +msgid "Failed to create continuous channels: invalid arg" msgstr "" #: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to create continuous channels: not found" +msgid "Failed to create continuous channels: invalid state" msgstr "" #: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to enable continuous" +msgid "Failed to create continuous channels: not found" msgstr "" -#: shared-module/audiomp3/MP3Decoder.c -msgid "Failed to parse MP3 file" -msgstr "Soubor MP3 se nepodařilo analyzovat" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to create continuous channels: no mem" +msgstr "" #: ports/espressif/common-hal/audioio/AudioOut.c msgid "Failed to register continuous events callback" msgstr "" -#: ports/nordic/sd_mutex.c -#, c-format -msgid "Failed to release mutex, err 0x%04x" -msgstr "Nepodařilo se uvolnit mutex, err 0x%04x" - -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "Failed to set hostname" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to enable continuous" msgstr "" #: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to start async audio" +msgid "Can't construct AudioOut because continuous channel already open" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Failed to write internal flash." -msgstr "Nepodařilo se zapsat do interní paměti." - -#: py/moderrno.c -msgid "File exists" -msgstr "soubor existuje" - -#: shared-module/os/getenv.c -msgid "File not found" -msgstr "Soubor nenalezen" - -#: ports/atmel-samd/common-hal/canio/Listener.c -#: ports/espressif/common-hal/canio/Listener.c -#: ports/mimxrt10xx/common-hal/canio/Listener.c -#: ports/stm/common-hal/canio/Listener.c -msgid "Filters too complex" -msgstr "Filtry jsou příliš komplexní" +#: ports/espressif/common-hal/audioio/AudioOut.c +#: ports/espressif/common-hal/mipicsi/Camera.c +#: shared-module/videocore/VideoBuffer.c shared-module/videogif/GifDecoder.c +msgid "already playing" +msgstr "" -#: ports/espressif/common-hal/dualbank/__init__.c -msgid "Firmware is duplicate" -msgstr "Firmware je duplicitní" +#: ports/espressif/common-hal/busio/I2C.c +#: ports/espressif/common-hal/i2ctarget/I2CTarget.c +#: ports/nordic/common-hal/busio/I2C.c ports/zephyr-cp/common-hal/busio/I2C.c +msgid "All I2C peripherals are in use" +msgstr "Všechny I2C periferie jsou používány" -#: ports/espressif/common-hal/dualbank/__init__.c -msgid "Firmware is invalid" -msgstr "Firmware není validní" +#: ports/espressif/common-hal/busio/I2C.c +#: ports/espressif/common-hal/busio/SPI.c +msgid "Unable to create lock" +msgstr "Není možné vytvořit zámek" -#: ports/espressif/common-hal/dualbank/__init__.c -msgid "Firmware is too big" -msgstr "Firmware je příliš velký" +#: ports/espressif/common-hal/busio/SPI.c +msgid "SPI configuration failed" +msgstr "Konfigurace SPI selhala" -#: shared-bindings/bitmaptools/__init__.c -msgid "For L8 colorspace, input bitmap must have 8 bits per pixel" -msgstr "Pro barevný prostor L8 musí mít vstupní bitmapa 8 bitů na pixel" +#: ports/espressif/common-hal/busio/SPI.c ports/nordic/common-hal/busio/SPI.c +#: ports/zephyr-cp/common-hal/async_spi/SPI.c +msgid "All SPI peripherals are in use" +msgstr "Všechny SPI periferie jsou používány" -#: shared-bindings/bitmaptools/__init__.c -msgid "For RGB colorspaces, input bitmap must have 16 bits per pixel" -msgstr "Pro barevný prostor RGB musí mít vstupní bitmapa 16 bitů na pixel" +#: ports/espressif/common-hal/busio/SPI.c +#: ports/espressif/common-hal/canio/CAN.c +#: ports/espressif/common-hal/qspibus/QSPIBus.c +msgid "ESP-IDF memory allocation failed" +msgstr "ESP-IDF alokace paměti selhala" -#: ports/cxd56/common-hal/camera/Camera.c -msgid "Format not supported" -msgstr "Formát není podporován" +#: ports/espressif/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c +msgid "Cannot specify RTS or CTS in RS485 mode" +msgstr "Nelze určit RTS nebo CTS v režimu RS485" -#: ports/mimxrt10xx/common-hal/microcontroller/Processor.c -msgid "" -"Frequency must be 24, 150, 396, 450, 528, 600, 720, 816, 912, 960 or 1008 Mhz" +#: ports/espressif/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c +msgid "RS485 inversion specified when not in RS485 mode" msgstr "" -"Frekvence musí být 24, 150, 396, 450, 528, 600, 720, 816, 912, 960 nebo 1008 " -"Mhz" -#: 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 "Funkce vyžaduje zámek" +#: ports/espressif/common-hal/canio/CAN.c +msgid "Baudrate not supported by peripheral" +msgstr "Baudrate není podporován periférií" -#: ports/cxd56/common-hal/gnss/GNSS.c -msgid "GNSS init" -msgstr "Inicializace GNSS" +#: ports/espressif/common-hal/canio/CAN.c +msgid "All CAN peripherals are in use" +msgstr "Všechny CAN periferie jsou používány" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Generic Failure" -msgstr "Základní chyba" +#: ports/espressif/common-hal/canio/CAN.c +msgid "loopback + silent mode not supported by peripheral" +msgstr "" -#: shared-bindings/framebufferio/FramebufferDisplay.c -#: shared-module/busdisplay/BusDisplay.c -#: shared-module/framebufferio/FramebufferDisplay.c -msgid "Group already used" -msgstr "Skupina již byla použita" +#: ports/espressif/common-hal/canio/CAN.c +#, c-format +msgid "twai_driver_install returned esp-idf error #%d" +msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Hard fault: memory access or instruction error." -msgstr "Fatální chyba: přístup k paměti nebo chyba instrukce." +#: ports/espressif/common-hal/canio/CAN.c +#, c-format +msgid "twai_start returned esp-idf error #%d" +msgstr "" -#: ports/mimxrt10xx/common-hal/busio/SPI.c -#: ports/mimxrt10xx/common-hal/busio/UART.c 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 "Hardware in use, try alternative pins" -msgstr "Hardware je používán, zkuste alternativní piny" +#: ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "ds_params has the wrong length" +msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Heap allocation when VM not running." -msgstr "Alokace heapu při neběžícím VM." +#: ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "" +"This key already committed to a different algorithm; call " +"load_digital_signature_key() again to use a different one" +msgstr "" -#: extmod/vfs_posix_file.c py/objstringio.c -msgid "I/O operation on closed file" -msgstr "I/O operace nad zavřeným souborem" +#: ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "" +"This key's ds_params were replaced by a later load_digital_signature_key() " +"call for the same key slot" +msgstr "" -#: ports/stm/common-hal/busio/I2C.c -msgid "I2C init error" -msgstr "Chyba inicializace I2C" +#: ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "ds_params is invalid for this key slot" +msgstr "" -#: ports/raspberrypi/common-hal/busio/I2C.c -#: ports/raspberrypi/common-hal/i2ctarget/I2CTarget.c -msgid "I2C peripheral in use" -msgstr "Periférie I2C je používána" +#: ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "Digital Signature peripheral not available on this chip" +msgstr "" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "In-buffer elements must be <= 4 bytes long" -msgstr "Elementy v bufferu musí být <= 4 bajty" +#: ports/espressif/common-hal/dotclockframebuffer/DotClockFramebuffer.c +msgid "Must provide 5/6/5 RGB pins" +msgstr "Je třeba poskytnout 5/6/5 RGB piny" -#: shared-bindings/_pew/PewPew.c -msgid "Incorrect buffer size" -msgstr "Nesprávná velikost vyrovnávací paměti" +#: ports/espressif/common-hal/dualbank/__init__.c +msgid "Firmware is duplicate" +msgstr "Firmware je duplicitní" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "Init program size invalid" -msgstr "Velikost init programu není správná" +#: ports/espressif/common-hal/dualbank/__init__.c +msgid "Firmware is invalid" +msgstr "Firmware není validní" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Initial set pin direction conflicts with initial out pin direction" -msgstr "" +#: ports/espressif/common-hal/dualbank/__init__.c +msgid "Firmware is too big" +msgstr "Firmware je příliš velký" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Initial set pin state conflicts with initial out pin state" +#: ports/espressif/common-hal/espcamera/Camera.c py/objobject.c py/runtime.c +msgid "no such attribute" msgstr "" -#: shared-bindings/bitops/__init__.c -#, c-format -msgid "Input buffer length (%d) must be a multiple of the strand count (%d)" -msgstr "" +#: ports/espressif/common-hal/espcamera/Camera.c +msgid "invalid setting" +msgstr "neplatné nastavení" -#: ports/atmel-samd/common-hal/pulseio/PulseIn.c -msgid "Input taking too long" -msgstr "Vstup trval příliš dlouho" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "Generic Failure" +msgstr "Základní chyba" -#: py/moderrno.c -msgid "Input/output error" -msgstr "Chyba vstupu/výstupu" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "Out of memory" +msgstr "Došla paměť" -#: ports/espressif/common-hal/_bleio/__init__.c -#: ports/nordic/common-hal/_bleio/__init__.c -msgid "Insufficient authentication" -msgstr "Nedostatečná autentizace" +#: ports/espressif/common-hal/espidf/__init__.c py/moderrno.c +msgid "Invalid argument" +msgstr "Neplatný argument" -#: ports/espressif/common-hal/_bleio/__init__.c -#: ports/nordic/common-hal/_bleio/__init__.c -msgid "Insufficient encryption" -msgstr "Nedostatečné šifrování" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "Invalid size" +msgstr "Chybná velikost" -#: shared-module/jpegio/JpegDecoder.c -msgid "Insufficient memory pool for the image" -msgstr "" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "Requested resource not found" +msgstr "Požadovaný zdroj nebyl nalezen" -#: shared-module/jpegio/JpegDecoder.c -msgid "Insufficient stream input buffer" -msgstr "" +#: ports/espressif/common-hal/espidf/__init__.c +#: ports/espressif/common-hal/jpegio/JpegDecoder.c +#: ports/raspberrypi/common-hal/usb_host_bulk/InStream.c +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +#: shared-bindings/picogame/Canvas.c shared-bindings/picogame/__init__.c +#: shared-module/jpegio/JpegDecoder.c shared-module/picogame/Display.c +msgid "Operation or feature not supported" +msgstr "Operace nebo funkce není podporována" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "Interface must be started" -msgstr "Rozhraní musí být nastartováno" +#: ports/espressif/common-hal/espidf/__init__.c +#: ports/espressif/common-hal/qspibus/QSPIBus.c +#: shared-module/_airlift/__init__.c +msgid "Operation timed out" +msgstr "Časový limit operace vypršel" -#: ports/atmel-samd/audio_dma.c ports/raspberrypi/audio_dma.c -msgid "Internal audio buffer too small" -msgstr "Interní audio buffer je příliš malý" +#: ports/espressif/common-hal/espidf/__init__.c +#: shared-module/_airlift/__init__.c +msgid "Received response was invalid" +msgstr "Přijatá odpověď nebyla validní" -#: ports/stm/common-hal/busio/UART.c -msgid "Internal define error" -msgstr "" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "CRC or checksum was invalid" +msgstr "CRC nebo kontrolní součet byl neplatný" -#: shared-bindings/pwmio/PWMOut.c shared-module/os/getenv.c -msgid "Internal error" -msgstr "Interní chyba" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "Version was invalid" +msgstr "Verze byla neplatná" -#: shared-module/rgbmatrix/RGBMatrix.c +#: ports/espressif/common-hal/espidf/__init__.c +msgid "MAC address was invalid" +msgstr "MAC adresa byla chybná" + +#: ports/espressif/common-hal/espidf/__init__.c #, c-format -msgid "Internal error #%d" -msgstr "Vnitřní chyba #%d" +msgid "%s error 0x%x" +msgstr "%s chyba 0x%x" -#: ports/atmel-samd/common-hal/alarm/pin/PinAlarm.c -#: ports/atmel-samd/common-hal/countio/Counter.c -#: ports/atmel-samd/common-hal/frequencyio/FrequencyIn.c -#: ports/atmel-samd/common-hal/max3421e/Max3421E.c -#: ports/atmel-samd/common-hal/ps2io/Ps2.c -#: ports/atmel-samd/common-hal/pulseio/PulseIn.c -#: ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.c -#: ports/cxd56/common-hal/pulseio/PulseIn.c +#: ports/espressif/common-hal/espulp/ULP.c +msgid "Program too long" +msgstr "Program je příliš dlouhý" + +#: ports/espressif/common-hal/espulp/ULP.c +#: ports/espressif/common-hal/mipidsi/Bus.c +#: ports/espressif/common-hal/qspibus/QSPIBus.c +#: ports/mimxrt10xx/common-hal/audiobusio/__init__.c +#: ports/mimxrt10xx/common-hal/usb_host/Port.c +#: ports/raspberrypi/common-hal/picodvi/AudioOut.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c #: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c -#: shared-bindings/pwmio/PWMOut.c -msgid "Internal resource(s) in use" -msgstr "" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#: ports/raspberrypi/common-hal/usb_host/Port.c +#: shared-bindings/digitalio/DigitalInOut.c shared-bindings/emmcio/EMMC.c +#: shared-bindings/i2cioexpander/IOPin.c shared-bindings/microcontroller/Pin.c +#: shared-module/_airlift/__init__.c +#: shared-module/epaperdisplay/EPaperDisplay.c +#: shared-module/max3421e/Max3421E.c shared-module/usb/core/Device.c +#: shared-module/usb_host_audio/USBIn.c +msgid "%q in use" +msgstr "%q se právě používá" -#: supervisor/shared/safe_mode.c -msgid "Internal watchdog timer expired." -msgstr "Interní watchdog timer expiroval." +#: ports/espressif/common-hal/espulp/ULPAlarm.c +msgid "Only one %q can be set." +msgstr "Lze nastavit pouze jeden %q ." -#: supervisor/shared/safe_mode.c -msgid "Interrupt error." -msgstr "Chyba přerušení." +#: ports/espressif/common-hal/i2ctarget/I2CTarget.c +#: ports/raspberrypi/common-hal/i2ctarget/I2CTarget.c +msgid "Only one address is allowed" +msgstr "Je povolena pouze jedna adresa" -#: shared-module/jpegio/JpegDecoder.c -msgid "Interrupted by output function" -msgstr "" +#: ports/espressif/common-hal/max3421e/Max3421E.c +#: ports/raspberrypi/common-hal/wifi/__init__.c +#, c-format +msgid "Unknown error code %d" +msgstr "Neznámý chybový kód %d" -#: ports/espressif/common-hal/_bleio/Service.c -#: ports/espressif/common-hal/espulp/ULP.c -#: ports/espressif/common-hal/microcontroller/Processor.c -#: ports/mimxrt10xx/common-hal/audiobusio/__init__.c -#: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c -#: ports/raspberrypi/bindings/picodvi/Framebuffer.c -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c py/argcheck.c -#: shared-bindings/digitalio/DigitalInOut.c -#: shared-bindings/epaperdisplay/EPaperDisplay.c shared-bindings/pwmio/PWMOut.c -#: shared-module/aurora_epaper/aurora_framebuffer.c -msgid "Invalid %q" -msgstr "Špatný %s" +#: ports/espressif/common-hal/mdns/Server.c +#: ports/raspberrypi/common-hal/mdns/Server.c +msgid "mDNS only works with built-in WiFi" +msgstr "mDNS pracuje pouze s vestavěnou WiFi" -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c -#: shared-module/aurora_epaper/aurora_framebuffer.c -msgid "Invalid %q and %q" -msgstr "" +#: ports/espressif/common-hal/mdns/Server.c +#: ports/raspberrypi/common-hal/mdns/Server.c +msgid "mDNS already initialized" +msgstr "mDNS je již inicializováno" -#: ports/atmel-samd/common-hal/microcontroller/Pin.c -#: ports/espressif/common-hal/dotclockframebuffer/DotClockFramebuffer.c -#: ports/mimxrt10xx/common-hal/microcontroller/Pin.c -#: shared-bindings/microcontroller/Pin.c -msgid "Invalid %q pin" -msgstr "Neplatný pin %q" +#: ports/espressif/common-hal/mdns/Server.c +#: ports/raspberrypi/common-hal/mdns/Server.c +msgid "Unable to start mDNS query" +msgstr "Nepodařilo se začít mDNS dotaz" -#: ports/stm/common-hal/analogio/AnalogIn.c -msgid "Invalid ADC Unit value" -msgstr "Neplatná hodnota jednotky ADC" +#: ports/espressif/common-hal/memorymap/AddressRange.c +#: ports/nordic/common-hal/memorymap/AddressRange.c +#: ports/raspberrypi/common-hal/memorymap/AddressRange.c +msgid "Address range not allowed" +msgstr "Adresní rozsah není povolen" -#: ports/espressif/common-hal/_bleio/__init__.c -#: ports/nordic/common-hal/_bleio/__init__.c -msgid "Invalid BLE parameter" -msgstr "Chybný BLE parametr" +#: ports/espressif/common-hal/mipicsi/Camera.c +#: shared-bindings/displayio/TileGrid.c shared-bindings/terminalio/Terminal.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-bindings/vectorio/VectorShape.c +msgid "unsupported %q type" +msgstr "nepodporovaný typ% q" -#: shared-bindings/wifi/Radio.c -msgid "Invalid BSSID" -msgstr "Chybné BSSID" +#: ports/espressif/common-hal/mipicsi/Camera.c +msgid "output_format must be RGB565 or RGB888" +msgstr "" -#: shared-bindings/wifi/Radio.c -msgid "Invalid MAC address" -msgstr "Chybná MAC adresa" +#: ports/espressif/common-hal/mipicsi/Camera.c +msgid "ISP conversion not supported on this chip" +msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c py/moderrno.c -msgid "Invalid argument" -msgstr "Neplatný argument" +#: ports/espressif/common-hal/mipidsi/Bus.c +msgid "%q is above %u" +msgstr "" -#: shared-module/displayio/Bitmap.c -msgid "Invalid bits per value" +#: ports/espressif/common-hal/mipidsi/Bus.c +msgid "%q is not reachable by the PHY" msgstr "" -#: shared-module/os/getenv.c -#, c-format -msgid "Invalid byte %.*s" -msgstr "Špatný byte %.*s" +#: ports/espressif/common-hal/nvm/ByteArray.c +msgid "NVS Error" +msgstr "Chyba NVS" -#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c +#: ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c +#: ports/espressif/common-hal/sdioio/SDCard.c #, c-format -msgid "Invalid data_pins[%d]" -msgstr "Chybný data_pin[%d]" +msgid "Number of data_pins must be %d or %d, not %d" +msgstr "" -#: shared-module/msgpack/__init__.c -msgid "Invalid format" -msgstr "Špatný formát" +#: ports/espressif/common-hal/pulseio/PulseIn.c +msgid "pop from an empty PulseIn" +msgstr "" -#: shared-module/audiocore/WaveFile.c -msgid "Invalid format chunk size" -msgstr "Neplatná velikost bloku" +#: ports/espressif/common-hal/qspibus/QSPIBus.c +#: ports/raspberrypi/common-hal/usb_host_bulk/InStream.c +#: shared-module/usb/core/Device.c +msgid "Could not allocate DMA capable buffer" +msgstr "" -#: shared-bindings/wifi/Radio.c -msgid "Invalid hex password" -msgstr "Špatné heslo v hex" +#: ports/espressif/common-hal/qspibus/QSPIBus.c shared-bindings/pwmio/PWMOut.c +#: supervisor/shared/settings.c +msgid "Internal error" +msgstr "Interní chyba" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "Invalid multicast MAC address" -msgstr "Chybná multicastová MAC adresa" +#: ports/espressif/common-hal/rclcpy/Node.c +msgid "ROS node failed to initialize" +msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Invalid size" -msgstr "Chybná velikost" +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "ROS topic failed to initialize" +msgstr "" -#: shared-module/ssl/SSLSocket.c -msgid "Invalid socket for TLS" -msgstr "Chybný soket pro TLS" +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "Could not publish to ROS topic" +msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -#: ports/nordic/common-hal/_bleio/__init__.c -msgid "Invalid state" -msgstr "Chybný stav" +#: ports/espressif/common-hal/rclcpy/__init__.c +#, c-format +msgid "Critical ROS failure during soft reboot, reset required: %d" +msgstr "" -#: shared-module/os/getenv.c -msgid "Invalid unicode escape" -msgstr "Neplatná unicode escape sekvence" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS memory allocator failure" +msgstr "" -#: shared-bindings/aesio/aes.c -msgid "Key must be 16, 24, or 32 bytes long" -msgstr "Klíč musí být dlouhý 16, 24 nebo 32 bajtů" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS internal setup failure" +msgstr "" -#: shared-module/os/getenv.c -msgid "Key not found" -msgstr "Klíč nenalezen" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "Invalid ROS domain ID" +msgstr "" -#: shared-module/is31fl3741/FrameBuffer.c -msgid "LED mappings must match display size" -msgstr "Mapování LED musí korespondovat s velikostí displeje" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS failed to initialize. Is agent connected?" +msgstr "" -#: py/compile.c -msgid "LHS of keyword arg must be an id" +#: ports/espressif/common-hal/sdioio/SDCard.c +#: ports/raspberrypi/common-hal/sdioio/SDCard.c +#: ports/stm/common-hal/sdioio/SDCard.c +#, c-format +msgid "SDIO Init Error 0x%02x" msgstr "" -#: shared-module/displayio/Group.c -msgid "Layer already in a group" -msgstr "Vrstva již v groupě je" +#: ports/espressif/common-hal/socketpool/Socket.c +#: ports/zephyr-cp/common-hal/socketpool/Socket.c +msgid "Unsupported socket type" +msgstr "" -#: shared-module/displayio/Group.c -msgid "Layer must be a Group or TileGrid subclass" -msgstr "Vrstva musí být Group nebo TileGrid" +#: ports/espressif/common-hal/socketpool/Socket.c +#: ports/raspberrypi/common-hal/socketpool/Socket.c +msgid "Out of sockets" +msgstr "Došly sockety" -#: shared-bindings/audiocore/RawSample.c -msgid "Length of %q must be an even multiple of channel_count * type_size" +#: ports/espressif/common-hal/socketpool/SocketPool.c +msgid "SocketPool can only be used with %q.%q or any %q.%q" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "MAC address was invalid" -msgstr "MAC adresa byla chybná" +#: ports/espressif/common-hal/watchdog/WatchDogTimer.c +msgid "%q must be <= %u" +msgstr "%q musí být <= %u" -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/espressif/common-hal/_bleio/Descriptor.c -msgid "MITM security not supported" +#: ports/espressif/common-hal/wifi/Monitor.c +msgid "monitor init failed" msgstr "" -#: shared-bindings/is31fl3741/IS31FL3741.c -msgid "Mapping must be a tuple" -msgstr "" +#: ports/espressif/common-hal/wifi/Radio.c +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "Interface must be started" +msgstr "Rozhraní musí být nastartováno" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Mismatched data size" -msgstr "Nekorespondující velikost dat" +#: ports/espressif/common-hal/wifi/Radio.c +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "Invalid multicast MAC address" +msgstr "Chybná multicastová MAC adresa" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Mismatched swap flag" -msgstr "Nekorespondující swap flag" +#: ports/espressif/common-hal/wifi/Radio.c +#: ports/raspberrypi/common-hal/wifi/Radio.c +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "Already scanning for wifi networks" +msgstr "Již skenuje wifi sítě" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_in_pin. %q[%u] reads pin(s)" -msgstr "Chybí first_in_pin. %q[%u] čte z pinu(ů)" +#: ports/espressif/common-hal/wifi/Radio.c +#: ports/espressif/common-hal/wifi/__init__.c +#: ports/raspberrypi/common-hal/wifi/Radio.c +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "WiFi is not enabled" +msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_in_pin. %q[%u] shifts in from pin(s)" -msgstr "Chybí first_in_pin. %q[%u] posunuje z pinu(ů)" +#: ports/espressif/common-hal/wifi/ScannedNetworks.c +msgid "Failed to allocate wifi scan memory" +msgstr "Nepodařilo se alokovat paměť pro wifi scan" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_in_pin. %q[%u] waits based on pin" -msgstr "Chybí first_in_pin. %q[%u] čeká na základě pinu" +#: ports/espressif/common-hal/wifi/__init__.c +msgid "Failed to allocate Wifi memory" +msgstr "Chyba alokace paměti WiFi" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_out_pin. %q[%u] shifts out to pin(s)" -msgstr "Chybí first_out_pin. %q[%u] posunuje do pinu(ů)" +#: ports/espressif/common-hal/wifi/__init__.c +#: ports/raspberrypi/common-hal/wifi/__init__.c +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "Only IPv4 addresses supported" +msgstr "Pouze IPv4 adresy podporovány" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_out_pin. %q[%u] writes pin(s)" -msgstr "Chybí first_out_pin. %q[%u] zapisuje do pinu(ů)" +#: ports/mimxrt10xx/common-hal/busio/SPI.c +#: ports/raspberrypi/bindings/wiznet/PIO_SPI.c shared-bindings/async_spi/SPI.c +#: shared-bindings/busio/SPI.c +msgid "Must provide MISO or MOSI pin" +msgstr "Musí poskytnout pin MISO nebo MOSI" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_set_pin. %q[%u] sets pin(s)" -msgstr "Chybí first_set_pin. %q[%u] nastavuje pin(y)" +#: ports/mimxrt10xx/common-hal/busio/SPI.c +#: ports/mimxrt10xx/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/canio/CAN.c 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 +#: shared-bindings/emmcio/EMMC.c +msgid "Hardware in use, try alternative pins" +msgstr "Hardware je používán, zkuste alternativní piny" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing jmp_pin. %q[%u] jumps on pin" -msgstr "Chybí jmp_pin. %q[%u] skáče na pin" +#: ports/mimxrt10xx/common-hal/canio/CAN.c +msgid "Unable to send CAN Message: all Tx message buffers are busy" +msgstr "" -#: shared-module/storage/__init__.c -msgid "Mount point directory missing" +#: ports/mimxrt10xx/common-hal/microcontroller/Processor.c +msgid "" +"Frequency must be 24, 150, 396, 450, 528, 600, 720, 816, 912, 960 or 1008 Mhz" msgstr "" +"Frekvence musí být 24, 150, 396, 450, 528, 600, 720, 816, 912, 960 nebo 1008 " +"Mhz" -#: ports/zephyr-cp/bindings/zephyr_serial/UART.c shared-bindings/busio/UART.c -#: shared-bindings/displayio/Group.c -msgid "Must be a %q subclass." -msgstr "Musí být podtřída %q." +#: ports/nordic/boards/aramcon2_badge/mpconfigboard.h +msgid "You pressed the left button at start up." +msgstr "Při spuštění jsi stiskl tlačítko doleva." -#: ports/espressif/common-hal/dotclockframebuffer/DotClockFramebuffer.c -msgid "Must provide 5/6/5 RGB pins" -msgstr "Je třeba poskytnout 5/6/5 RGB piny" +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "timeout must be < 655.35 secs" +msgstr "timeout musí být < 655.35 s" -#: ports/mimxrt10xx/common-hal/busio/SPI.c shared-bindings/busio/SPI.c -msgid "Must provide MISO or MOSI pin" -msgstr "Musí poskytnout pin MISO nebo MOSI" +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "non-zero timeout must be > 0.01" +msgstr "nenulový timeout musí být > 0.01" -#: shared-bindings/rgbmatrix/RGBMatrix.c +#: ports/nordic/common-hal/_bleio/UUID.c +msgid "Unexpected nrfx uuid type" +msgstr "" + +#: ports/nordic/common-hal/_bleio/__init__.c +msgid "Nordic system firmware out of memory" +msgstr "Nordic system firmware - nedostatek paměti" + +#: ports/nordic/common-hal/_bleio/__init__.c #, c-format -msgid "Must use a multiple of 6 rgb pins, not %d" -msgstr "Je nutné použít několik kolíků 6 rgb, nikoli %d" +msgid "Unknown system firmware error: %04x" +msgstr "Neznámá chyba firmwaru: %04x" -#: supervisor/shared/safe_mode.c -msgid "NLR jump failed. Likely memory corruption." -msgstr "NLR skok selhal. Pravděpodobně poškozením paměti." +#: ports/nordic/common-hal/alarm/pin/PinAlarm.c +msgid "Cannot wake on pin edge, only level" +msgstr "Nelze probudit hranou na pinu, pouze úrovní" -#: ports/espressif/common-hal/nvm/ByteArray.c -msgid "NVS Error" -msgstr "Chyba NVS" +#: ports/nordic/common-hal/audiobusio/I2SOut.c +msgid "Device in use" +msgstr "Zařízení je používáno" -#: shared-bindings/socketpool/SocketPool.c -msgid "Name or service not known" -msgstr "Jméno nebo služba není známa" +#: ports/nordic/common-hal/audiobusio/PDMIn.c +#: ports/stm/common-hal/audiobusio/PDMIn.c +msgid "only sample_rate=16000 is supported" +msgstr "" -#: shared-bindings/displayio/TileGrid.c -msgid "New bitmap must be same size as old bitmap" -msgstr "Nová bitmapa musí mít stejnou velikost jako původní bitmapa" +#: ports/nordic/common-hal/audiobusio/PDMIn.c +#: ports/stm/common-hal/audiobusio/PDMIn.c +msgid "only bit_depth=16 is supported" +msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -msgid "Nimble out of memory" +#: ports/nordic/common-hal/busio/UART.c +#, c-format +msgid "error = 0x%08lX" msgstr "" -#: ports/atmel-samd/common-hal/busio/UART.c -#: ports/espressif/common-hal/busio/SPI.c -#: ports/espressif/common-hal/busio/UART.c -#: ports/mimxrt10xx/common-hal/busio/SPI.c -#: ports/mimxrt10xx/common-hal/busio/UART.c #: ports/nordic/common-hal/busio/UART.c -#: ports/raspberrypi/common-hal/busio/UART.c ports/stm/common-hal/busio/SPI.c -#: ports/stm/common-hal/busio/UART.c shared-bindings/fourwire/FourWire.c -#: shared-bindings/i2cdisplaybus/I2CDisplayBus.c -#: shared-bindings/paralleldisplaybus/ParallelBus.c -#: shared-module/bitbangio/SPI.c -msgid "No %q pin" -msgstr "Žádný %q pin" +msgid "Odd parity is not supported" +msgstr "" -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Characteristic.c -msgid "No CCCD for this Characteristic" -msgstr "Žádné CCCD pro tuto charakteristiku" +#: ports/nordic/common-hal/countio/Counter.c +#: ports/nordic/common-hal/pulseio/PulseIn.c +#: ports/nordic/common-hal/rotaryio/IncrementalEncoder.c +msgid "All channels in use" +msgstr "Všechny kanály jsou používány" -#: ports/atmel-samd/common-hal/analogio/AnalogOut.c -#: ports/stm/common-hal/analogio/AnalogOut.c -msgid "No DAC on chip" -msgstr "Žádný DAC na čipu" +#: ports/nordic/common-hal/microcontroller/Processor.c +msgid "Cannot get temperature" +msgstr "Nelze získat teplotu (°C)" -#: 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 "Nebyl nalezen žádný kanál DMA" +#: ports/nordic/common-hal/watchdog/WatchDogTimer.c +msgid "timeout duration exceeded the maximum supported value" +msgstr "timeout překročil maximální podporovanou hodnotu" -#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c -msgid "No DMA pacing timer found" +#: ports/nordic/common-hal/watchdog/WatchDogTimer.c +msgid "%q cannot be changed once mode is set to %q" msgstr "" -#: shared-module/adafruit_bus_device/i2c_device/I2CDevice.c +#: ports/nordic/common-hal/watchdog/WatchDogTimer.c +msgid "WatchDogTimer cannot be deinitialized once mode is set to RESET" +msgstr "WatchDogTimer nelze deaktivovat v režimu RESET" + +#: ports/nordic/sd_mutex.c #, c-format -msgid "No I2C device at address: 0x%x" -msgstr "Žádné I2C zařízení na adrese: 0x%x" +msgid "Failed to acquire mutex, err 0x%04x" +msgstr "Nepodařilo se získat mutex, err 0x%04x" -#: supervisor/shared/web_workflow/web_workflow.c -msgid "No IP" -msgstr "Není IP" +#: ports/nordic/sd_mutex.c +#, c-format +msgid "Failed to release mutex, err 0x%04x" +msgstr "Nepodařilo se uvolnit mutex, err 0x%04x" -#: ports/atmel-samd/common-hal/microcontroller/__init__.c -#: ports/cxd56/common-hal/microcontroller/__init__.c -#: ports/mimxrt10xx/common-hal/microcontroller/__init__.c -msgid "No bootloader present" -msgstr "" +#: ports/raspberrypi/audio_dma.c +msgid "Audio conversion not implemented" +msgstr "Konverze audia není implementována" -#: shared-module/usb/core/Device.c -msgid "No configuration set" -msgstr "Konfigurace není nastavena" +#: ports/raspberrypi/bindings/cyw43/__init__.c py/argcheck.c py/objexcept.c +#: shared-bindings/bitmapfilter/__init__.c shared-bindings/canio/CAN.c +#: shared-bindings/digitalio/Pull.c shared-bindings/picogame/Sprite.c +#: shared-bindings/supervisor/__init__.c shared-module/audiofilters/__init__.c +#: shared-module/displayio/legacy/__init__.c +#: shared-module/synthio/Synthesizer.c shared-module/videocore/VideoBuffer.c +msgid "%q must be of type %q or %q, not %q" +msgstr "%q musí být typu %q nebo %q, ne %q" -#: shared-bindings/_bleio/PacketBuffer.c -msgid "No connection: length cannot be determined" -msgstr "Žádné připojení: nelze určit délku" +#: ports/raspberrypi/bindings/picodvi/AudioOut.c +#: shared-bindings/audiobusio/I2SOut.c shared-bindings/audioio/AudioOut.c +#: shared-bindings/audiopwmio/PWMAudioOut.c shared-bindings/mcp4822/MCP4822.c +#: shared-bindings/usb_audio/USBMicrophone.c +msgid "Not playing" +msgstr "Nehraje" -#: shared-bindings/board/__init__.c -msgid "No default %q bus" -msgstr "Žádná výchozí sběrnice %q" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Program size invalid" +msgstr "Velikost programu je nesprávná" -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c -#: ports/atmel-samd/common-hal/touchio/TouchIn.c -msgid "No free GCLKs" -msgstr "Žádné volné GCLK" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Init program size invalid" +msgstr "Velikost init programu není správná" -#: shared-bindings/os/__init__.c -msgid "No hardware random available" -msgstr "" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Buffer elements must be 4 bytes long or less" +msgstr "Prvky bufferu musí být 4 bajty dlouhé nebo méně" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "No in in program" -msgstr "V programu není vstup" +msgid "Mismatched data size" +msgstr "Nekorespondující velikost dat" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "No in or out in program" -msgstr "V programu není vstup nebo výstup" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Out-buffer elements must be <= 4 bytes long" +msgstr "" -#: py/objint.c shared-bindings/time/__init__.c -msgid "No long integer support" -msgstr "Není podpora long integer" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "In-buffer elements must be <= 4 bytes long" +msgstr "Elementy v bufferu musí být <= 4 bajty" -#: shared-bindings/wifi/Radio.c -msgid "No network with that ssid" -msgstr "Žádná síť s takovým SSID" +#: ports/raspberrypi/bindings/wiznet/PIO_SPI.c shared-bindings/async_spi/SPI.c +#: 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 "Funkce vyžaduje zámek" + +#: ports/raspberrypi/bindings/wiznet/PIO_SPI.c shared-bindings/async_spi/SPI.c +#: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c +msgid "buffer slices must be of equal length" +msgstr "" + +#: ports/raspberrypi/common-hal/alarm/touch/TouchAlarm.c +#: ports/stm/common-hal/alarm/touch/TouchAlarm.c +msgid "Touch alarms not available" +msgstr "Touch alarmy nejsou dostupné" + +#: ports/raspberrypi/common-hal/async_spi/SPI.c shared-bindings/emmcio/EMMC.c +msgid "SPI peripheral in use" +msgstr "SPI periferie je používána" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audioi2sin/I2SIn.c #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "No out in program" -msgstr "V programu není výstup" +msgid "Cannot use GPIO0..15 together with GPIO32..47" +msgstr "" + +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audioi2sin/I2SIn.c +msgid "Bit clock and word select must be sequential GPIO pins" +msgstr "" + +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/mcp4822/MCP4822.c +msgid "Too many channels in sample." +msgstr "" -#: ports/atmel-samd/common-hal/busio/I2C.c -#: ports/espressif/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nordic/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 "SDA nebo SCL zřejmě nemá pull up; zkontroluj zapojení" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +#: ports/raspberrypi/common-hal/mcp4822/MCP4822.c +msgid "Audio source error" +msgstr "" -#: shared-module/touchio/TouchIn.c -msgid "No pulldown on pin; 1Mohm recommended" -msgstr "Žádný pulldown na pinu; doporučeno 1Mohm" +#: ports/raspberrypi/common-hal/audioi2sin/I2SIn.c +msgid "%q must be 16, 24, or 32" +msgstr "" -#: py/moderrno.c -msgid "No space left on device" -msgstr "Na zařízení nezůstal žádný prostor" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Pins must share PWM slice" +msgstr "" -#: py/moderrno.c -msgid "No such device" -msgstr "Žádné takové zařízení" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "No DMA pacing timer found" +msgstr "" -#: py/moderrno.c -msgid "No such file/directory" -msgstr "Žádný takový soubor / adresář" +#: ports/raspberrypi/common-hal/busio/I2C.c +#: ports/raspberrypi/common-hal/i2ctarget/I2CTarget.c +msgid "I2C peripheral in use" +msgstr "Periférie I2C je používána" -#: shared-module/rgbmatrix/RGBMatrix.c -msgid "No timer available" -msgstr "Není k dispozici žádný časovač" +#: ports/raspberrypi/common-hal/busio/UART.c +msgid "UART peripheral in use" +msgstr "UART periférie je používána" -#: shared-module/usb/core/Device.c -msgid "No usb host port initialized" -msgstr "Žádný USB host port není inicializován" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "Pin must be on PWM Channel B" +msgstr "Pin musí být na PWM kanálu B" -#: ports/nordic/common-hal/_bleio/__init__.c -msgid "Nordic system firmware out of memory" -msgstr "Nordic system firmware - nedostatek paměti" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "RISE_AND_FALL not available on this chip" +msgstr "RISE_AND_FALL není na tomto čipu k dispozici" -#: shared-bindings/ipaddress/IPv4Address.c shared-bindings/ipaddress/__init__.c -msgid "Not a valid IP string" -msgstr "Nevalidní IP string" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice already in use" +msgstr "PWM kanál je již využíván" -#: ports/espressif/common-hal/_bleio/__init__.c -#: ports/nordic/common-hal/_bleio/__init__.c -#: shared-bindings/_bleio/CharacteristicBuffer.c -msgid "Not connected" -msgstr "Nepřipojený" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice channel A already in use" +msgstr "PWM kanál A je již využíván" -#: shared-bindings/audiobusio/I2SOut.c shared-bindings/audioio/AudioOut.c -#: shared-bindings/audiopwmio/PWMAudioOut.c -msgid "Not playing" -msgstr "Nehraje" +#: ports/raspberrypi/common-hal/floppyio/__init__.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#: ports/raspberrypi/common-hal/usb_host/Port.c +msgid "All state machines in use" +msgstr "Všechny stavové automaty jsou používány" -#: shared-module/jpegio/JpegDecoder.c -msgid "Not supported JPEG standard" +#: ports/raspberrypi/common-hal/floppyio/__init__.c +msgid "timeout waiting for flux" msgstr "" -#: ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/espressif/common-hal/sdioio/SDCard.c -#, c-format -msgid "Number of data_pins must be %d or %d, not %d" +#: ports/raspberrypi/common-hal/floppyio/__init__.c +#: shared-module/floppyio/__init__.c +msgid "timeout waiting for index pulse" msgstr "" -#: shared-bindings/util.c -msgid "" -"Object has been deinitialized and can no longer be used. Create a new object." +#: ports/raspberrypi/common-hal/imagecapture/ParallelImageCapture.c +msgid "Pins must be sequential" msgstr "" -"Objekt byl deinicializován a nelze jej dále používat. Vytvořte nový objekt." -#: ports/nordic/common-hal/busio/UART.c -msgid "Odd parity is not supported" +#: ports/raspberrypi/common-hal/mcp4822/MCP4822.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c +#: shared-module/aurora_epaper/aurora_framebuffer.c +msgid "Invalid %q and %q" msgstr "" -#: supervisor/shared/bluetooth/bluetooth.c -msgid "Off" -msgstr "Vypnuto" - -#: supervisor/shared/bluetooth/bluetooth.c -msgid "Ok" -msgstr "Ok" +#: ports/raspberrypi/common-hal/mdns/Server.c +msgid "Out of MDNS service slots" +msgstr "Došly mDNS sloty" -#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c -#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c -#, c-format -msgid "Only 8 or 16 bit mono with %dx oversampling supported." -msgstr "" +#: ports/raspberrypi/common-hal/memorymap/AddressRange.c +msgid "Unable to access unaligned IO register" +msgstr "Nelze přistupovat k nezarovnanému IO registru" -#: ports/espressif/common-hal/wifi/__init__.c -#: ports/raspberrypi/common-hal/wifi/__init__.c -msgid "Only IPv4 addresses supported" -msgstr "Pouze IPv4 adresy podporovány" +#: ports/raspberrypi/common-hal/memorymap/AddressRange.c +msgid "Unable to write to read-only memory" +msgstr "Není možné zapisovat do paměti jen pro čtení" -#: ports/raspberrypi/common-hal/socketpool/Socket.c -msgid "Only IPv4 sockets supported" -msgstr "Pouze IPv4 sokety podporovány" +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c +msgid "All timers for this pin are in use" +msgstr "Všechny časovače pro tento pin jsou používány" -#: shared-module/displayio/OnDiskBitmap.c -#, c-format -msgid "" -"Only Windows format, uncompressed BMP supported: given header size is %d" +#: ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c +msgid "Pins must be sequential GPIO pins" msgstr "" -#: shared-bindings/_bleio/Adapter.c -msgid "Only connectable advertisements can be directed" -msgstr "" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Pin count too large" +msgstr "Počet pinů je příliš velký" -#: ports/stm/common-hal/alarm/pin/PinAlarm.c -msgid "Only edge detection is available on this hardware" -msgstr "Na tomto hardware je dostupná pouze detekce hrany" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing jmp_pin. %q[%u] jumps on pin" +msgstr "Chybí jmp_pin. %q[%u] skáče na pin" -#: shared-bindings/ipaddress/__init__.c -msgid "Only int or string supported for ip" -msgstr "Pro IP je podporován pouze int nebo string" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "%q[%u] uses extra pin" +msgstr "%q[%u] používá extra pin" -#: ports/espressif/common-hal/alarm/touch/TouchAlarm.c -msgid "Only one %q can be set in deep sleep." -msgstr "Pouze jeden %q lze nastavit v hlubokém spánku." +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_in_pin. %q[%u] waits based on pin" +msgstr "Chybí first_in_pin. %q[%u] čeká na základě pinu" -#: ports/espressif/common-hal/espulp/ULPAlarm.c -msgid "Only one %q can be set." -msgstr "Lze nastavit pouze jeden %q ." +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "%q[%u] waits on input outside of count" +msgstr "%q[%u] čeká na vstup mimo rozsah" -#: ports/espressif/common-hal/i2ctarget/I2CTarget.c -#: ports/raspberrypi/common-hal/i2ctarget/I2CTarget.c -msgid "Only one address is allowed" -msgstr "Je povolena pouze jedna adresa" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_in_pin. %q[%u] shifts in from pin(s)" +msgstr "Chybí first_in_pin. %q[%u] posunuje z pinu(ů)" -#: ports/atmel-samd/common-hal/alarm/time/TimeAlarm.c -#: ports/nordic/common-hal/alarm/time/TimeAlarm.c -#: ports/stm/common-hal/alarm/time/TimeAlarm.c -msgid "Only one alarm.time alarm can be set" -msgstr "Lze nastavit pouze jeden alarm typu alarm.time" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "%q[%u] shifts in more bits than pin count" +msgstr "%q[%u] posouvá dovnitř o více bitů než je počet pinů" -#: ports/espressif/common-hal/alarm/time/TimeAlarm.c -#: ports/raspberrypi/common-hal/alarm/time/TimeAlarm.c -msgid "Only one alarm.time alarm can be set." -msgstr "Může být nastaven pouze jeden alarm typu alarm.time." +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_out_pin. %q[%u] shifts out to pin(s)" +msgstr "Chybí first_out_pin. %q[%u] posunuje do pinu(ů)" -#: shared-module/displayio/ColorConverter.c -msgid "Only one color can be transparent at a time" -msgstr "Pouze jedna barva může být nastavena jako transparentní" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "%q[%u] shifts out more bits than pin count" +msgstr "%q[%u] posouvá ven o více bitů než je počet pinů" -#: py/moderrno.c -msgid "Operation not permitted" -msgstr "Operace není povolena" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_set_pin. %q[%u] sets pin(s)" +msgstr "Chybí first_set_pin. %q[%u] nastavuje pin(y)" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Operation or feature not supported" -msgstr "Operace nebo funkce není podporována" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_out_pin. %q[%u] writes pin(s)" +msgstr "Chybí first_out_pin. %q[%u] zapisuje do pinu(ů)" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Operation timed out" -msgstr "Časový limit operace vypršel" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_in_pin. %q[%u] reads pin(s)" +msgstr "Chybí first_in_pin. %q[%u] čte z pinu(ů)" -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "Out of MDNS service slots" -msgstr "Došly mDNS sloty" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Program does IN without loading ISR" +msgstr "Program provedl IN bez načtení ISR" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Out of memory" -msgstr "Došla paměť" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Program does OUT without loading OSR" +msgstr "Program provedl OUT bez načtení OSR" -#: ports/espressif/common-hal/socketpool/Socket.c -#: ports/raspberrypi/common-hal/socketpool/Socket.c -#: ports/zephyr-cp/common-hal/socketpool/Socket.c -msgid "Out of sockets" -msgstr "Došly sockety" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin state conflicts with initial out pin state" +msgstr "" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "Out-buffer elements must be <= 4 bytes long" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin direction conflicts with initial out pin direction" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "PWM restart" -msgstr "Restart PWM" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "pull masks conflict with direction masks" +msgstr "" -#: ports/raspberrypi/common-hal/countio/Counter.c -msgid "PWM slice already in use" -msgstr "PWM kanál je již využíván" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No out in program" +msgstr "V programu není výstup" -#: ports/raspberrypi/common-hal/countio/Counter.c -msgid "PWM slice channel A already in use" -msgstr "PWM kanál A je již využíván" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in in program" +msgstr "V programu není vstup" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in or out in program" +msgstr "V programu není vstup nebo výstup" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Mismatched swap flag" +msgstr "Nekorespondující swap flag" -#: shared-bindings/spitarget/SPITarget.c -msgid "Packet buffers for an SPI transfer must have the same length." +#: ports/raspberrypi/common-hal/sdioio/SDCard.c +#, c-format +msgid "Number of data_pins must be %d, not %d" msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "Parameter error" +#: ports/raspberrypi/common-hal/sdioio/SDCard.c +msgid "Data pins must be consecutive" msgstr "" -#: ports/espressif/common-hal/audiobusio/__init__.c -msgid "Peripheral in use" -msgstr "Periférie je používána" +#: ports/raspberrypi/common-hal/socketpool/Socket.c +msgid "Only IPv4 sockets supported" +msgstr "Pouze IPv4 sokety podporovány" -#: py/moderrno.c -msgid "Permission denied" -msgstr "Přístup odepřen" +#: ports/raspberrypi/common-hal/socketpool/SocketPool.c +msgid "SocketPool can only be used with wifi.radio" +msgstr "SocketPool je možné použít pouze s wifi.radio" -#: ports/stm/common-hal/alarm/pin/PinAlarm.c -msgid "Pin cannot wake from Deep Sleep" -msgstr "Z Deep Sleep nelze probudit pinem" +#: ports/raspberrypi/common-hal/usb_host/Port.c +msgid "All dma channels in use" +msgstr "Všechny DMA kanály jsou používány" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Pin count too large" -msgstr "Počet pinů je příliš velký" +#: ports/raspberrypi/common-hal/wifi/Monitor.c +msgid "wifi.Monitor not available" +msgstr "wifi.Monitor není dostupný" + +#: ports/raspberrypi/common-hal/wifi/Radio.c +msgid "%q is read-only for this board" +msgstr "%q je pouze u této desky pouze pro čtení" + +#: ports/raspberrypi/common-hal/wifi/Radio.c +msgid "AP could not be started" +msgstr "AP nemohl být spuštěn" + +#: ports/stm/common-hal/alarm/pin/PinAlarm.c +msgid "Only edge detection is available on this hardware" +msgstr "Na tomto hardware je dostupná pouze detekce hrany" #: ports/stm/common-hal/alarm/pin/PinAlarm.c #: ports/stm/common-hal/pulseio/PulseIn.c msgid "Pin interrupt already in use" msgstr "Přerušení od pinu je již používáno" -#: shared-bindings/adafruit_bus_device/spi_device/SPIDevice.c -msgid "Pin is input only" -msgstr "Pin je pouze vstupní" - -#: ports/raspberrypi/common-hal/countio/Counter.c -msgid "Pin must be on PWM Channel B" -msgstr "Pin musí být na PWM kanálu B" +#: ports/stm/common-hal/alarm/pin/PinAlarm.c +msgid "Pin cannot wake from Deep Sleep" +msgstr "Z Deep Sleep nelze probudit pinem" -#: 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" +#: ports/stm/common-hal/alarm/pin/PinAlarm.c +msgid "Deep sleep pins must use a rising edge with pulldown" msgstr "" +"Piny pro hluboký spánek musí používat náběžnou hranu s pulldown rezistorem" -#: ports/raspberrypi/common-hal/imagecapture/ParallelImageCapture.c -msgid "Pins must be sequential" -msgstr "" +#: ports/stm/common-hal/analogio/AnalogIn.c +msgid "Invalid ADC Unit value" +msgstr "Neplatná hodnota jednotky ADC" -#: ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c -msgid "Pins must be sequential GPIO pins" -msgstr "" +#: ports/stm/common-hal/analogio/AnalogOut.c +#: ports/stm/common-hal/audioio/AudioOut.c +msgid "DAC Device Init Error" +msgstr "Chyba inicializace zařízení DAC" -#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c -msgid "Pins must share PWM slice" -msgstr "" +#: ports/stm/common-hal/analogio/AnalogOut.c +#: ports/stm/common-hal/audioio/AudioOut.c +msgid "DAC Channel Init Error" +msgstr "Chyba inicializace kanálu DAC" -#: shared-module/usb/core/Device.c -msgid "Pipe error" -msgstr "" +#: ports/stm/common-hal/audiobusio/PDMIn.c +msgid "only mono is supported" +msgstr "je podporováno pouze mono" -#: py/builtinhelp.c -msgid "Plus any modules on the filesystem\n" -msgstr "Plus všechny moduly na filesystému\n" +#: ports/stm/common-hal/audiobusio/PDMIn.c +msgid "only oversample=64 is supported" +msgstr "je podporován pouze oversampling 64" -#: shared-module/vectorio/Polygon.c -msgid "Polygon needs at least 3 points" -msgstr "Polygon potřebuje nejméně 3 body" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Another PWMAudioOut is already active" +msgstr "Jiný PWMAudioOut je již aktivní" -#: supervisor/shared/safe_mode.c -msgid "Power dipped. Make sure you are providing enough power." -msgstr "Pokles napájení. Zkontroluj, zda je k dispozici dostatečné napájení." +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +#, c-format +msgid "Buffer length %d too big. It must be less than %d" +msgstr "Délka vyrovnávací paměti %d je příliš velká. Musí být menší než %d" -#: shared-bindings/_bleio/Adapter.c -msgid "Prefix buffer must be on the heap" -msgstr "" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Failed to buffer the sample" +msgstr "Nepodařilo se nabufferovat sample" -#: main.c -msgid "Press any key to enter the REPL. Use CTRL-D to reload.\n" -msgstr "" -"Zmáčkněte jakoukoli klávesu pro spuštění REPLu. Použijte CTRL-D pro opětovné " -"načtení.\n" +#: ports/stm/common-hal/busio/I2C.c +msgid "I2C init error" +msgstr "Chyba inicializace I2C" -#: main.c -msgid "Pretending to deep sleep until alarm, CTRL-C or file write.\n" -msgstr "Předstírám hluboký spánek do alarmu, CTRL-C nebo zápisu souboru.\n" +#: ports/stm/common-hal/busio/SPI.c +msgid "SPI init error" +msgstr "Chyba inicializace SPI" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Program does IN without loading ISR" -msgstr "Program provedl IN bez načtení ISR" +#: ports/stm/common-hal/busio/SPI.c +msgid "SPI re-init" +msgstr "Opětovná inicializace SPI" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Program does OUT without loading OSR" -msgstr "Program provedl OUT bez načtení OSR" +#: ports/stm/common-hal/busio/UART.c +msgid "Internal define error" +msgstr "" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "Program size invalid" -msgstr "Velikost programu je nesprávná" +#: ports/stm/common-hal/busio/UART.c +msgid "Could not start interrupt, RX busy" +msgstr "Nelze začít přerušení, RX je zaneprázdněn" -#: ports/espressif/common-hal/espulp/ULP.c -msgid "Program too long" -msgstr "Program je příliš dlouhý" +#: ports/stm/common-hal/busio/UART.c +msgid "UART write" +msgstr "Zápis na UART" -#: shared-bindings/digitalio/DigitalInOut.c -msgid "Pull not used when direction is output." -msgstr "" +#: ports/stm/common-hal/busio/UART.c +msgid "UART de-init" +msgstr "De-inicializace UART" -#: ports/raspberrypi/common-hal/countio/Counter.c -msgid "RISE_AND_FALL not available on this chip" -msgstr "RISE_AND_FALL není na tomto čipu k dispozici" +#: ports/stm/common-hal/busio/UART.c +msgid "UART re-init" +msgstr "Opětovná inicializace UART" -#: shared-module/displayio/OnDiskBitmap.c -msgid "RLE-compressed BMP not supported" -msgstr "" +#: ports/stm/common-hal/microcontroller/Processor.c +msgid "Temperature read timed out" +msgstr "Čas pro čtení teploty vypršel" -#: ports/stm/common-hal/os/__init__.c -msgid "RNG DeInit Error" -msgstr "" +#: ports/stm/common-hal/microcontroller/Processor.c +msgid "Voltage read timed out" +msgstr "Časový limit čtení napětí vypršel" #: ports/stm/common-hal/os/__init__.c msgid "RNG Init Error" msgstr "" -#: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c -#: ports/nordic/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c -msgid "RS485" -msgstr "RS485" - -#: ports/espressif/common-hal/busio/UART.c -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "RS485 inversion specified when not in RS485 mode" -msgstr "" - -#: shared-bindings/alarm/time/TimeAlarm.c shared-bindings/time/__init__.c -msgid "RTC is not supported on this board" -msgstr "RTC není na této desce podporován" - #: ports/stm/common-hal/os/__init__.c msgid "Random number generation error" msgstr "Chyba generování náhodných čísel" -#: shared-bindings/_bleio/__init__.c -#: shared-bindings/memorymonitor/AllocationSize.c -#: shared-bindings/pulseio/PulseIn.c shared-module/bitmaptools/__init__.c -#: shared-module/displayio/Bitmap.c shared-module/displayio/Group.c -msgid "Read-only" -msgstr "Pouze pro čtení" - -#: extmod/vfs_fat.c py/moderrno.c -msgid "Read-only filesystem" -msgstr "Filesystém pouze pro čtení" - -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Received response was invalid" -msgstr "Přijatá odpověď nebyla validní" - -#: supervisor/shared/bluetooth/bluetooth.c -msgid "Reconnecting" -msgstr "Opětovné připojování" - -#: shared-bindings/epaperdisplay/EPaperDisplay.c -msgid "Refresh too soon" -msgstr "Pokus o obnovení příliš brzo" - -#: shared-bindings/canio/RemoteTransmissionRequest.c -msgid "RemoteTransmissionRequests limited to 8 bytes" -msgstr "RemoteTransmissionRequests je limitován na 8 bajtů" +#: ports/stm/common-hal/os/__init__.c +msgid "RNG DeInit Error" +msgstr "" -#: shared-bindings/aesio/aes.c -msgid "Requested AES mode is unsupported" -msgstr "Požadovaný režim AES je nepodporovaný" +#: ports/stm/common-hal/pwmio/PWMOut.c +msgid "timer re-init" +msgstr "opětovný init timeru" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Requested resource not found" -msgstr "Požadovaný zdroj nebyl nalezen" +#: ports/stm/common-hal/pwmio/PWMOut.c +msgid "channel re-init" +msgstr "opětovná inicializace kanálu" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c -msgid "Right channel unsupported" -msgstr "Pravý kanál nepodporován" +#: ports/stm/common-hal/pwmio/PWMOut.c +msgid "PWM restart" +msgstr "Restart PWM" -#: shared-module/jpegio/JpegDecoder.c -msgid "Right format but not supported" +#: ports/stm/common-hal/sdioio/SDCard.c +#, c-format +msgid "MMC/SDIO Clock Error %x" msgstr "" -#: main.c -msgid "Running in safe mode! Not running saved code.\n" -msgstr "Běh v nouzovém režimu! Uložený kód není zpracováván.\n" +#: ports/stm/common-hal/sdioio/SDCard.c +#, c-format +msgid "SDIO GetCardInfo Error %d" +msgstr "SDIO GetCardInfo chyba %d" -#: shared-module/sdcardio/SDCard.c -msgid "SD card CSD format not supported" -msgstr "CSD formát SD karty není podporován" +#: ports/zephyr-cp/bindings/zephyr_display/Display.c +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/epaperdisplay/EPaperDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +#: shared-bindings/mipidsi/Display.c +msgid "Display rotation must be in 90 degree increments" +msgstr "Otočení displeje musí být po 90 stupních" + +#: ports/zephyr-cp/bindings/zephyr_display/Display.c +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/epaperdisplay/EPaperDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +msgid ".show(x) removed. Use .root_group = x" +msgstr "" -#: ports/cxd56/common-hal/sdioio/SDCard.c -msgid "SDCard init" -msgstr "Inicializace SD karty" +#: ports/zephyr-cp/bindings/zephyr_display/Display.c +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +msgid "Brightness not adjustable" +msgstr "Jas není nastavitelný" -#: ports/stm/common-hal/sdioio/SDCard.c -#, c-format -msgid "SDIO GetCardInfo Error %d" -msgstr "SDIO GetCardInfo chyba %d" +#: ports/zephyr-cp/bindings/zephyr_display/Display.c py/argcheck.c +#: shared-bindings/busdisplay/BusDisplay.c shared-bindings/displayio/Bitmap.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +#: shared-bindings/is31fl3741/FrameBuffer.c +#: shared-bindings/rgbmatrix/RGBMatrix.c +msgid "%q must be %d-%d" +msgstr "%q musí být %d-%d" -#: ports/espressif/common-hal/sdioio/SDCard.c -#: ports/stm/common-hal/sdioio/SDCard.c -#, c-format -msgid "SDIO Init Error %x" +#: ports/zephyr-cp/bindings/zephyr_display/Display.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +#: shared-module/busdisplay/legacy/BusDisplay.c +#: shared-module/framebufferio/legacy/FramebufferDisplay.c +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "Group already used" +msgstr "Skupina již byla použita" + +#: ports/zephyr-cp/common-hal/_bleio/Adapter.c +msgid "Invalid advertising data" msgstr "" -#: ports/espressif/common-hal/busio/SPI.c -msgid "SPI configuration failed" -msgstr "Konfigurace SPI selhala" +#: ports/zephyr-cp/common-hal/async_spi/SPI.c +#: ports/zephyr-cp/common-hal/audiobusio/I2SOut.c +#: ports/zephyr-cp/common-hal/busio/I2C.c +#: ports/zephyr-cp/common-hal/busio/UART.c +msgid "Use device tree to define %q devices" +msgstr "" -#: ports/stm/common-hal/busio/SPI.c -msgid "SPI init error" -msgstr "Chyba inicializace SPI" +#: ports/zephyr-cp/common-hal/mii/Ethernet.c +msgid "cannot construct ethernet interfaces; use board.ETHERNET" +msgstr "" -#: ports/raspberrypi/common-hal/busio/SPI.c -msgid "SPI peripheral in use" -msgstr "SPI periferie je používána" +#: ports/zephyr-cp/common-hal/socketpool/SocketPool.c +msgid "SocketPool can only be used with %q.%q, %q.%q, or %q.%q" +msgstr "" -#: ports/stm/common-hal/busio/SPI.c -msgid "SPI re-init" -msgstr "Opětovná inicializace SPI" +#: ports/zephyr-cp/common-hal/usb_hid/Device.c shared-module/usb_hid/Device.c +msgid "USB error" +msgstr "Chyba USB" -#: shared-bindings/is31fl3741/FrameBuffer.c -msgid "Scale dimensions must divide by 3" +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "Failed to set hostname" msgstr "" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Scan already in progress. Stop with stop_scan." -msgstr "Scan již probíhá. Lze zastavit pomocí stop_scan." +#: ports/zephyr-cp/common-hal/zephyr_display/legacy/Display.c +#: ports/zephyr-cp/common-hal/zephyr_display/lvgl/Display.c +#: shared-module/busdisplay/legacy/BusDisplay.c +#: shared-module/framebufferio/legacy/FramebufferDisplay.c +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "Below minimum frame rate" +msgstr "Pod minimální obnovovací frekvencí" -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c -msgid "Serializer in use" +#: py/argcheck.c +msgid "function doesn't take keyword arguments" msgstr "" -#: shared-bindings/ssl/SSLContext.c -msgid "Server side context cannot have hostname" +#: py/argcheck.c py/bc.c py/objnamedtuple.c shared-bindings/_eve/__init__.c +#: shared-bindings/time/__init__.c +#, c-format +msgid "function takes %d positional arguments but %d were given" msgstr "" -#: ports/cxd56/common-hal/camera/Camera.c -msgid "Size not supported" -msgstr "Velikost není podporována" +#: py/argcheck.c +#, c-format +msgid "function missing %d required positional arguments" +msgstr "funkci chybí %d povinné poziční argumenty" -#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c -#: shared-bindings/nvm/ByteArray.c -msgid "Slice and value different lengths." +#: py/argcheck.c +#, c-format +msgid "function expected at most %d arguments, got %d" msgstr "" -#: 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" +#: py/argcheck.c shared-bindings/wifi/Radio.c +msgid "'%q' argument required" +msgstr "Je vyžadován argument '%q'" + +#: py/argcheck.c +msgid "extra positional arguments given" msgstr "" -#: ports/espressif/common-hal/socketpool/SocketPool.c -#: ports/raspberrypi/common-hal/socketpool/SocketPool.c -#: ports/zephyr-cp/common-hal/socketpool/SocketPool.c -msgid "SocketPool can only be used with wifi.radio" -msgstr "SocketPool je možné použít pouze s wifi.radio" +#: py/argcheck.c py/bc.c py/objnamedtuple.c +#: shared-bindings/traceback/__init__.c +msgid "unexpected keyword argument '%q'" +msgstr "" -#: shared-bindings/aesio/aes.c -msgid "Source and destination buffers must be the same length" -msgstr "Zdrojové a cílové buffery musí být stejné délky" +#: py/argcheck.c +msgid "extra keyword arguments given" +msgstr "" -#: shared-bindings/paralleldisplaybus/ParallelBus.c -msgid "Specify exactly one of data0 or data_pins" -msgstr "Specifikuj přesně jeden z data0 nebo data_pins" +#: py/argcheck.c shared-bindings/_stage/__init__.c +#: shared-bindings/digitalio/DigitalInOut.c shared-bindings/picogame/__init__.c +msgid "argument num/types mismatch" +msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Stack overflow. Increase stack size." +#: py/argcheck.c +msgid "keyword argument(s) not implemented - use normal args instead" msgstr "" -#: shared-bindings/alarm/time/TimeAlarm.c -msgid "Supply one of monotonic_time or epoch_time" -msgstr "Musíš definovat monotonic_time nebo epoch_time" +#: py/argcheck.c +msgid "%q must be %d" +msgstr "%q musí být %d" -#: shared-bindings/gnss/GNSS.c -msgid "System entry must be gnss.SatelliteSystem" -msgstr "Parametr \"system\" musí být gnss.SatelliteSystem" +#: py/argcheck.c +msgid "%q must be >= %d" +msgstr "%q musí být >= %d" -#: ports/stm/common-hal/microcontroller/Processor.c -msgid "Temperature read timed out" -msgstr "Čas pro čtení teploty vypršel" +#: py/argcheck.c shared-bindings/gifio/GifWriter.c +#: shared-module/_airlift/__init__.c +msgid "%q must be <= %d" +msgstr "%q musí být <= %d" -#: supervisor/shared/safe_mode.c -msgid "The `microcontroller` module was used to boot into safe mode." -msgstr "Modul `microcontroller` byl použit pro spuštění do nouzového režimu." +#: py/argcheck.c py/runtime.c shared-bindings/bitmapfilter/__init__.c +#: shared-module/audiodelays/MultiTapDelay.c shared-module/synthio/Note.c +#: shared-module/synthio/__init__.c +msgid "%q must be of type %q, not %q" +msgstr "%q musí být typu %q, ne %q" -#: py/obj.c -msgid "The above exception was the direct cause of the following exception:" -msgstr "Výše uvedená výjimka byla přímá příčina následující výjimky:" +#: py/argcheck.c +msgid "%q length must be %d-%d" +msgstr "%q délka musí být %d-%d" -#: shared-bindings/rgbmatrix/RGBMatrix.c -msgid "The length of rgb_pins must be 6, 12, 18, 24, or 30" -msgstr "Počet prvků rgb_pin musí být 6, 12, 18, 24, nebo 30" +#: py/argcheck.c +msgid "%q length must be >= %d" +msgstr "Délka %q musí být >= %d" -#: shared-module/audiocore/__init__.c -msgid "The sample's %q does not match" -msgstr "" +#: py/argcheck.c shared-module/_airlift/__init__.c +msgid "%q length must be <= %d" +msgstr "Délka %q musí být <= %d" -#: supervisor/shared/safe_mode.c -msgid "Third-party firmware fatal error." -msgstr "Fatální chyby firmware třetí strany." +#: py/argcheck.c shared-bindings/usb_hid/Device.c +msgid "%q length must be %d" +msgstr "Délka %q musí být %d" -#: shared-module/imagecapture/ParallelImageCapture.c -msgid "This microcontroller does not support continuous capture." -msgstr "Tento mikrokontrolér nepodporuje kontinuální snímání." +#: py/argcheck.c shared-module/audiofilters/__init__.c +msgid "%q in %q must be of type %q, not %q" +msgstr "%q v %q musí být typu %q, ne %q" -#: shared-module/paralleldisplaybus/ParallelBus.c -msgid "" -"This microcontroller only supports data0=, not data_pins=, because it " -"requires contiguous pins." +#: py/asmthumb.c +msgid "too many locals for native method" msgstr "" -#: shared-bindings/displayio/TileGrid.c -msgid "Tile height must exactly divide bitmap height" +#: py/asmxtensa.c +msgid "ERROR: xtensa %q out of range" msgstr "" -#: shared-bindings/displayio/TileGrid.c shared-module/displayio/TileGrid.c -msgid "Tile index out of bounds" +#: py/asmxtensa.c +msgid "ERROR: %q %q not word-aligned" msgstr "" -#: shared-bindings/displayio/TileGrid.c -msgid "Tile width must exactly divide bitmap width" +#: py/bc.c py/objnamedtuple.c +msgid "%q() takes %d positional arguments but %d were given" +msgstr "%q() vyžaduje %d pozičních argumentů, ale pouze %d jich bylo zadáno" + +#: py/bc.c py/objnamedtuple.c +msgid "function got multiple values for argument '%q'" msgstr "" -#: shared-bindings/alarm/time/TimeAlarm.c -msgid "Time is in the past." -msgstr "Čas je v minulosti." +#: py/bc.c +msgid "unexpected keyword argument" +msgstr "" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c +#: py/bc.c #, c-format -msgid "Timeout is too long: Maximum timeout length is %d seconds" -msgstr "Časový limit je příliš dlouhý: maximální limit je %d vteřin" +msgid "function missing required positional argument #%d" +msgstr "funkci chybí požadovaný argument na pozici #%d" -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -msgid "Too many channels in sample" -msgstr "V samplu je příliš mnoho kanálů" +#: py/bc.c +msgid "function missing required keyword argument '%q'" +msgstr "funkci chybí argument specifikovaný klíčovým slovem" -#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c -msgid "Too many channels in sample." +#: py/bc.c +msgid "function missing keyword-only argument" +msgstr "funkci chybí argument pouze pro klíčové slovo" + +#: py/binary.c py/objarray.c +msgid "bad typecode" msgstr "" -#: ports/espressif/common-hal/_bleio/Characteristic.c -msgid "Too many descriptors" +#: py/binary.c +msgid "integer out of range" msgstr "" -#: shared-module/displayio/__init__.c -msgid "Too many display busses; forgot displayio.release_displays() ?" +#: py/builtinevex.c +msgid "bad compile mode" msgstr "" -"Příliš mnoho sběrnic displaye; nezapomněl si na displayio.release_displays()?" -#: shared-module/displayio/__init__.c -msgid "Too many displays" -msgstr "Příliš mnoho displejů" +#: py/builtinhelp.c +msgid "Plus any modules on the filesystem\n" +msgstr "Plus všechny moduly na filesystému\n" -#: ports/espressif/common-hal/_bleio/PacketBuffer.c -#: ports/nordic/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than %q" -msgstr "Velikost dat k zápisu je větší než %q" +#: py/builtinhelp.c +msgid "object " +msgstr "objekt " -#: ports/raspberrypi/common-hal/alarm/touch/TouchAlarm.c -#: ports/stm/common-hal/alarm/touch/TouchAlarm.c -msgid "Touch alarms not available" -msgstr "Touch alarmy nejsou dostupné" +#: py/builtinhelp.c +msgid " is of type %q\n" +msgstr " je typu %q\n" -#: py/obj.c -msgid "Traceback (most recent call last):\n" +#: py/builtinhelp.c +#, c-format +msgid "" +"Welcome to Adafruit CircuitPython %s!\n" +"\n" +"Visit circuitpython.org for more information.\n" +"\n" +"To list built-in modules type `help(\"modules\")`.\n" +msgstr "" +"Vítejte v Adafruit CircuitPython %s!\n" +"\n" +"Pro více informací navštivte circuitpython.org.\n" +"\n" +"Seznam vestavěných modulů můžete vypsat pomocí `help(\"modules\")`.\n" + +#: py/builtinimport.c +msgid "script compilation not supported" +msgstr "" + +#: py/builtinimport.c +msgid "can't perform relative import" +msgstr "nelze provést relativní import" + +#: py/builtinimport.c +msgid "module not found" msgstr "" -#: ports/stm/common-hal/busio/UART.c -msgid "UART de-init" -msgstr "De-inicializace UART" +#: py/builtinimport.c +msgid "no module named '%q'" +msgstr "" -#: ports/cxd56/common-hal/busio/UART.c ports/espressif/common-hal/busio/UART.c -#: ports/stm/common-hal/busio/UART.c -msgid "UART init" -msgstr "Inicializace UART" +#: py/builtinimport.c +msgid "relative import" +msgstr "" -#: ports/raspberrypi/common-hal/busio/UART.c -msgid "UART peripheral in use" -msgstr "UART periférie je používána" +#: py/compile.c +msgid "can't assign to expression" +msgstr "" -#: ports/stm/common-hal/busio/UART.c -msgid "UART re-init" -msgstr "Opětovná inicializace UART" +#: py/compile.c +msgid "multiple *x in assignment" +msgstr "" -#: ports/stm/common-hal/busio/UART.c -msgid "UART write" -msgstr "Zápis na UART" +#: py/compile.c +msgid "non-default argument follows default argument" +msgstr "" -#: main.c -msgid "UID:" -msgstr "UID:" +#: py/compile.c +msgid "invalid micropython decorator" +msgstr "" -#: shared-module/usb_hid/Device.c -msgid "USB busy" -msgstr "USB zaneprázdněno" +#: py/compile.c +msgid "invalid arch" +msgstr "" -#: supervisor/shared/safe_mode.c -msgid "USB devices need more endpoints than are available." -msgstr "USB zařízení potřebují více endpointů než je k dispozici." +#: py/compile.c +msgid "can't delete expression" +msgstr "" -#: supervisor/shared/safe_mode.c -msgid "USB devices specify too many interface names." -msgstr "USB zařízení používají příliš mnoho názvů rozhraní." +#: py/compile.c +msgid "'break'/'continue' outside loop" +msgstr "" -#: shared-module/usb_hid/Device.c -msgid "USB error" -msgstr "Chyba USB" +#: py/compile.c +msgid "'return' outside function" +msgstr "'return' je volán mimo funkci" -#: shared-bindings/_bleio/UUID.c -msgid "UUID integer value must be 0-0xffff" -msgstr "UUID integer musí být 0-0xffff" +#: py/compile.c +msgid "import * not at module level" +msgstr "" -#: shared-bindings/_bleio/UUID.c -msgid "UUID string not 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'" -msgstr "UUID řetězec neodpovídá 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'" +#: py/compile.c +msgid "identifier redefined as global" +msgstr "" -#: shared-bindings/_bleio/UUID.c -msgid "UUID value is not str, int or byte buffer" -msgstr "Hodnota UUID není str, int ani byte buffer" +#: py/compile.c +msgid "no binding for nonlocal found" +msgstr "" -#: ports/raspberrypi/common-hal/memorymap/AddressRange.c -msgid "Unable to access unaligned IO register" -msgstr "Nelze přistupovat k nezarovnanému IO registru" +#: py/compile.c +msgid "identifier redefined as nonlocal" +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" +#: py/compile.c +msgid "can't declare nonlocal in outer code" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Unable to allocate to the heap." +#: py/compile.c +msgid "default 'except' must be last" msgstr "" -#: ports/espressif/common-hal/busio/I2C.c -msgid "Unable to create lock" -msgstr "Není možné vytvořit zámek" +#: py/compile.c +msgid "async for/with outside async function" +msgstr "" -#: shared-module/i2cdisplaybus/I2CDisplayBus.c -#: shared-module/is31fl3741/IS31FL3741.c -#, c-format -msgid "Unable to find I2C Display at %x" -msgstr "I2C display nenalezen na %x" +#: py/compile.c +msgid "*x must be assignment target" +msgstr "∗x musí být cíl přiřazení" -#: py/parse.c -msgid "Unable to init parser" +#: py/compile.c +msgid "super() can't find self" msgstr "" -#: shared-module/displayio/OnDiskBitmap.c -msgid "Unable to read color palette data" -msgstr "Nelze číst data palety barev" +#: py/compile.c +msgid "* arg after **" +msgstr "* arg po **" -#: ports/mimxrt10xx/common-hal/canio/CAN.c -msgid "Unable to send CAN Message: all Tx message buffers are busy" +#: py/compile.c +msgid "* arg after kwarg" msgstr "" -#: ports/espressif/common-hal/mdns/Server.c -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "Unable to start mDNS query" -msgstr "Nepodařilo se začít mDNS dotaz" +#: py/compile.c +msgid "too many args" +msgstr "příliš mnoho argumentů" -#: shared-bindings/nvm/ByteArray.c -msgid "Unable to write to nvm." -msgstr "Není možné zapisovat do nvm." +#: py/compile.c +msgid "LHS of keyword arg must be an id" +msgstr "" -#: ports/raspberrypi/common-hal/memorymap/AddressRange.c -msgid "Unable to write to read-only memory" -msgstr "Není možné zapisovat do paměti jen pro čtení" +#: py/compile.c +msgid "positional arg after **" +msgstr "" -#: shared-bindings/alarm/SleepMemory.c -msgid "Unable to write to sleep_memory." -msgstr "Nelze zapsat do sleep_memory." +#: py/compile.c +msgid "positional arg after keyword arg" +msgstr "" -#: ports/nordic/common-hal/_bleio/UUID.c -msgid "Unexpected nrfx uuid type" +#: py/compile.c py/parse.c +msgid "invalid syntax" msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown BLE error at %s:%d: %d" -msgstr "Neznámá chyba BLE na %s:%d: %d" +#: py/compile.c +msgid "expecting key:value for dict" +msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown BLE error: %d" -msgstr "Neznámá chyba BLE: %d" +#: py/compile.c +msgid "expecting just a value for set" +msgstr "" -#: ports/espressif/common-hal/max3421e/Max3421E.c -#: ports/raspberrypi/common-hal/wifi/__init__.c -#, c-format -msgid "Unknown error code %d" -msgstr "Neznámý chybový kód %d" +#: py/compile.c +msgid "'yield' outside function" +msgstr "'yield' je volán mimo funkci" -#: shared-bindings/wifi/Radio.c -#, c-format -msgid "Unknown failure %d" -msgstr "Neznámé selhání %d" +#: py/compile.c +msgid "'yield from' inside async function" +msgstr "'yield from' volán uvnitř funkce async" -#: ports/nordic/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown gatt error: 0x%04x" -msgstr "" +#: py/compile.c +msgid "'await' outside function" +msgstr "'await' je volán mimo funkci" -#: ports/atmel-samd/common-hal/alarm/pin/PinAlarm.c -#: supervisor/shared/safe_mode.c -msgid "Unknown reason." -msgstr "Neznámý důvod." +#: py/compile.c +msgid "unknown type '%q'" +msgstr "neznámý typ '%q'" -#: ports/nordic/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown security error: 0x%04x" -msgstr "Neznámá bezpečnostní chyba: 0x%04x" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "anotace musí být identifikátor" -#: ports/espressif/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown system firmware error at %s:%d: %d" -msgstr "Neznámá chyba firmwaru na %s:%d: %d" +#: py/compile.c +msgid "argument name reused" +msgstr "jméno argumentu znovupoužito" -#: ports/nordic/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown system firmware error: %04x" -msgstr "Neznámá chyba firmwaru: %04x" +#: py/compile.c +msgid "inline assembler must be a function" +msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown system firmware error: %d" -msgstr "Neznámá chyba firmwaru: %d" +#: py/compile.c +msgid "unknown type" +msgstr "neznámý typ" -#: shared-bindings/adafruit_pixelbuf/PixelBuf.c -#: shared-module/_pixelmap/PixelMap.c -#, c-format -msgid "Unmatched number of items on RHS (expected %d, got %d)." +#: py/compile.c +msgid "return annotation must be an identifier" msgstr "" -#: ports/nordic/common-hal/_bleio/__init__.c -msgid "" -"Unspecified issue. Can be that the pairing prompt on the other device was " -"declined or ignored." +#: py/compile.c +msgid "expecting an assembler instruction" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "Unsupported colorspace" -msgstr "Nepodporovaný barevný prostor" +#: py/compile.c +msgid "'label' requires 1 argument" +msgstr "'label' vyžaduje 1 argument" -#: shared-module/displayio/bus_core.c -msgid "Unsupported display bus type" -msgstr "Nepodporovaná sběrnice dispalye" +#: py/compile.c +msgid "label redefined" +msgstr "" -#: shared-module/audiocore/WaveFile.c -msgid "Unsupported format" -msgstr "Nepodporovaný formát" +#: py/compile.c +msgid "'align' requires 1 argument" +msgstr "'align' vyžaduje 1 argument" -#: shared-bindings/hashlib/__init__.c -msgid "Unsupported hash algorithm" -msgstr "Nepodporovaný hash algoritmus" +#: py/compile.c +msgid "'data' requires at least 2 arguments" +msgstr "'data' vyžaduje nejméně 2 argumenty" + +#: py/compile.c +msgid "'data' requires integer arguments" +msgstr "'data' vyžaduje celočíselné argumenty" + +#: py/compile.c +msgid "cannot emit native code for this architecture" +msgstr "" + +#: py/emitbc.c +msgid "bytecode overflow" +msgstr "přetečení bytecode" -#: ports/espressif/common-hal/socketpool/Socket.c -#: ports/zephyr-cp/common-hal/socketpool/Socket.c -msgid "Unsupported socket type" +#: py/emitinlinerv32.c +msgid "can only have up to 4 parameters for RV32 assembly" msgstr "" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/espressif/common-hal/dualbank/__init__.c -msgid "Update failed" +#: py/emitinlinerv32.c +msgid "parameters must be registers in sequence a0 to a3" msgstr "" -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Descriptor.c -msgid "Value length != required fixed length" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: expecting %q" msgstr "" -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Descriptor.c -msgid "Value length > max_length" +#: py/emitinlinerv32.c +msgid "opcode '%q': expecting %d arguments" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Version was invalid" -msgstr "Verze byla neplatná" - -#: ports/stm/common-hal/microcontroller/Processor.c -msgid "Voltage read timed out" -msgstr "Časový limit čtení napětí vypršel" - -#: main.c -msgid "WARNING: Your code filename has two extensions\n" -msgstr "UPOZORNĚNÍ: Název souboru vašeho kódu má dvě koncovky\n" - -#: ports/nordic/common-hal/watchdog/WatchDogTimer.c -msgid "WatchDogTimer cannot be deinitialized once mode is set to RESET" -msgstr "WatchDogTimer nelze deaktivovat v režimu RESET" - -#: py/builtinhelp.c -#, c-format -msgid "" -"Welcome to Adafruit CircuitPython %s!\n" -"\n" -"Visit circuitpython.org for more information.\n" -"\n" -"To list built-in modules type `help(\"modules\")`.\n" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: out of range" msgstr "" -"Vítejte v Adafruit CircuitPython %s!\n" -"\n" -"Pro více informací navštivte circuitpython.org.\n" -"\n" -"Seznam vestavěných modulů můžete vypsat pomocí `help(\"modules\")`.\n" -#: supervisor/shared/web_workflow/web_workflow.c -msgid "Wi-Fi: " -msgstr "Wi-Fi: " +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: unknown register" +msgstr "" -#: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "Wifi is not enabled" -msgstr "Wifi není povoleno" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: undefined label '%q'" +msgstr "" -#: main.c -msgid "Woken up by alarm.\n" -msgstr "Probuzen alarmem.\n" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: must not be zero" +msgstr "" -#: ports/espressif/common-hal/_bleio/PacketBuffer.c -#: ports/nordic/common-hal/_bleio/PacketBuffer.c -msgid "Writes not supported on Characteristic" +#: py/emitinlinerv32.c +msgid "opcode '%q': registers must be different" msgstr "" -#: 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/meowmeow/mpconfigboard.h -msgid "You pressed both buttons at start up." -msgstr "Při spuštění jsi stiskl obě tlačítka." +#: py/emitinlinerv32.c +msgid "opcode '%q': malformed register list" +msgstr "" -#: ports/espressif/boards/m5stack_core_basic/mpconfigboard.h -#: ports/espressif/boards/m5stack_core_fire/mpconfigboard.h -#: ports/espressif/boards/m5stack_stick_c/mpconfigboard.h -#: ports/espressif/boards/m5stack_stick_c_plus/mpconfigboard.h -#: ports/espressif/boards/m5stack_stick_c_plus2/mpconfigboard.h -msgid "You pressed button A at start up." -msgstr "Při spuštění jsi stiskl tlačítko A." +#: py/emitinlinerv32.c +msgid "opcode '%q': invalid stack adjustment" +msgstr "" -#: ports/espressif/boards/m5stack_m5paper/mpconfigboard.h -msgid "You pressed button DOWN at start up." -msgstr "Při spuštění jsi stiskl tlačítko DOWN." +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: wrong register(s)" +msgstr "" -#: supervisor/shared/safe_mode.c -msgid "You pressed the BOOT button at start up" -msgstr "Při spuštění jsi stiskl tlačítko BOOT" +#: py/emitinlinerv32.c +msgid "invalid RV32 instruction '%q'" +msgstr "" -#: ports/espressif/boards/adafruit_feather_esp32c6_4mbflash_nopsram/mpconfigboard.h -#: ports/espressif/boards/adafruit_itsybitsy_esp32/mpconfigboard.h -#: ports/espressif/boards/waveshare_esp32_c6_lcd_1_47/mpconfigboard.h -msgid "You pressed the BOOT button at start up." +#: py/emitinlinethumb.c +msgid "can only have up to 4 parameters to Thumb assembly" msgstr "" -#: ports/espressif/boards/adafruit_huzzah32_breakout/mpconfigboard.h -msgid "You pressed the GPIO0 button at start up." -msgstr "Při spuštění jsi stiskl tlačítko na pinu GPIO0." +#: py/emitinlinethumb.c +msgid "parameters must be registers in sequence r0 to r3" +msgstr "" -#: ports/espressif/boards/espressif_esp32_lyrat/mpconfigboard.h -msgid "You pressed the Rec button at start up." -msgstr "Při spuštění jsi stiskl tlačítko Rec." +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' expects at most r%d" +msgstr "'%s' očekává nanejvýš r%d" -#: ports/espressif/boards/adafruit_feather_esp32_v2/mpconfigboard.h -msgid "You pressed the SW38 button at start up." -msgstr "Při spuštění jsi stiskl tlačítko SW38." +#: py/emitinlinethumb.c py/emitinlinextensa.c +#, c-format +msgid "'%s' expects a register" +msgstr "'%s' očekává registr" -#: ports/espressif/boards/hardkernel_odroid_go/mpconfigboard.h -#: ports/espressif/boards/vidi_x/mpconfigboard.h -msgid "You pressed the VOLUME button at start up." -msgstr "Při spuštění jsi stiskl tlačítko VOLUME." +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' expects a special register" +msgstr "'%s' očekává speciální registr" -#: ports/espressif/boards/m5stack_atom_echo/mpconfigboard.h -#: ports/espressif/boards/m5stack_atom_lite/mpconfigboard.h -#: ports/espressif/boards/m5stack_atom_matrix/mpconfigboard.h -#: ports/espressif/boards/m5stack_atom_u/mpconfigboard.h -msgid "You pressed the central button at start up." -msgstr "Při spuštění jsi stiskl středové tlačítko." +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' expects an FPU register" +msgstr "'%s' očekává registr FPU" -#: ports/nordic/boards/aramcon2_badge/mpconfigboard.h -msgid "You pressed the left button at start up." -msgstr "Při spuštění jsi stiskl tlačítko doleva." +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' expects {r0, r1, ...}" +msgstr "'%s' očekává {r0, r1, ...}" -#: supervisor/shared/safe_mode.c -msgid "You pressed the reset button during boot." -msgstr "Při spuštění jsi stiskl tlačítko reset." +#: py/emitinlinethumb.c py/emitinlinextensa.c +#, c-format +msgid "'%s' expects an integer" +msgstr "'%s' očekává integer (celé číslo)" -#: supervisor/shared/micropython.c -msgid "[truncated due to length]" -msgstr "[zkráceno kvůli délce]" +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' integer 0x%x doesn't fit in mask 0x%x" +msgstr "'%s' integer 0x%x nepatří do masky 0x%x" -#: py/objtype.c -msgid "__init__() should return None" -msgstr "" +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' expects an address of the form [a, b]" +msgstr "'%s' očekává adresu ve formátu [a, b]" -#: py/objtype.c +#: py/emitinlinethumb.c py/emitinlinextensa.c #, c-format -msgid "__init__() should return None, not '%s'" +msgid "'%s' expects a label" +msgstr "'%s' očekává label" + +#: py/emitinlinethumb.c py/emitinlinextensa.c +msgid "label '%q' not defined" msgstr "" -#: py/objobject.c -msgid "__new__ arg must be a user-type" +#: py/emitinlinethumb.c +#, c-format +msgid "unsupported Thumb instruction '%s' with %d arguments" msgstr "" -#: extmod/modbinascii.c extmod/modhashlib.c py/objarray.c -msgid "a bytes-like object is required" +#: py/emitinlinethumb.c +msgid "branch not in range" msgstr "" -#: shared-bindings/i2ctarget/I2CTarget.c -msgid "addresses is empty" +#: py/emitinlinextensa.c +msgid "can only have up to 4 parameters to Xtensa assembly" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "already playing" +#: py/emitinlinextensa.c +msgid "parameters must be registers in sequence a2 to a5" msgstr "" -#: py/compile.c -msgid "annotation must be an identifier" -msgstr "anotace musí být identifikátor" +#: py/emitinlinextensa.c +#, c-format +msgid "'%s' integer %d isn't within range %d..%d" +msgstr "'%s' integer %d není v rozsahu %d..%d" -#: extmod/ulab/code/numpy/create.c -msgid "arange: cannot compute length" +#: py/emitinlinextensa.c +#, c-format +msgid "%d is not a multiple of %d" msgstr "" -#: py/modbuiltins.c -msgid "arg is an empty sequence" +#: py/emitinlinextensa.c +#, c-format +msgid "unsupported Xtensa instruction '%s' with %d arguments" msgstr "" -#: py/objobject.c -msgid "arg must be user-type" +#: py/emitnative.c +msgid "conversion to object" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "argsort argument must be an ndarray" +#: py/emitnative.c +msgid "local '%q' used before type known" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "argsort is not implemented for flattened arrays" -msgstr "argsort není implementován pro zploštěná pole" - -#: extmod/ulab/code/numpy/random/random.c -msgid "argument must be None, an integer or a tuple of integers" +#: py/emitnative.c +msgid "can't load from '%q'" msgstr "" -#: py/compile.c -msgid "argument name reused" -msgstr "jméno argumentu znovupoužito" - -#: py/argcheck.c shared-bindings/_stage/__init__.c -#: shared-bindings/digitalio/DigitalInOut.c -msgid "argument num/types mismatch" +#: py/emitnative.c +msgid "can't load with '%q' index" msgstr "" -#: extmod/ulab/code/numpy/numerical.c extmod/ulab/code/numpy/transform.c -msgid "arguments must be ndarrays" +#: py/emitnative.c +msgid "local '%q' has type '%q' but source is '%q'" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "array and index length must be equal" -msgstr "Pole a index musí mít stejnou délku" - -#: extmod/ulab/code/numpy/io/io.c -msgid "array has too many dimensions" -msgstr "pole má příliš mnoho dimenzí" - -#: extmod/ulab/code/ndarray.c -msgid "array is too big" -msgstr "pole je příliš velké" - -#: py/objarray.c shared-bindings/alarm/SleepMemory.c -#: shared-bindings/memorymap/AddressRange.c shared-bindings/nvm/ByteArray.c -msgid "array/bytes required on right side" +#: py/emitnative.c +msgid "can't store '%q'" msgstr "" -#: py/asmxtensa.c -msgid "asm overflow" -msgstr "přetečení v asm" - -#: py/compile.c -msgid "async for/with outside async function" +#: py/emitnative.c +msgid "can't store to '%q'" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "attempt to get (arg)min/(arg)max of empty sequence" -msgstr "pokus o získání (arg)min/(arg)max z prázdné sekvence" +#: py/emitnative.c +msgid "can't store with '%q' index" +msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "attempt to get argmin/argmax of an empty sequence" +#: py/emitnative.c +msgid "can't implicitly convert '%q' to 'bool'" msgstr "" -#: py/objstr.c -msgid "attributes not supported" +#: py/emitnative.c +msgid "'not' not implemented" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "audio format not supported" +#: py/emitnative.c +msgid "can't do unary op of '%q'" msgstr "" -#: extmod/ulab/code/ulab_tools.c -msgid "axis is out of bounds" -msgstr "osa je mimo rozsah" - -#: extmod/ulab/code/numpy/numerical.c extmod/ulab/code/ulab_tools.c -msgid "axis must be None, or an integer" -msgstr "osa musí být None nebo integer" +#: py/emitnative.c +msgid "div/mod not implemented for uint" +msgstr "div/mod nejsou implementované pro uint" -#: extmod/ulab/code/numpy/numerical.c -msgid "axis too long" -msgstr "osa je příliš dlouhá" +#: py/emitnative.c +msgid "comparison of int and uint" +msgstr "porovnání int a uint" -#: shared-bindings/bitmaptools/__init__.c -msgid "background value out of range of target" +#: py/emitnative.c +msgid "binary op %q not implemented" msgstr "" -#: py/builtinevex.c -msgid "bad compile mode" +#: py/emitnative.c +msgid "can't do binary op between '%q' and '%q'" msgstr "" -#: py/objstr.c -msgid "bad conversion specifier" +#: py/emitnative.c +msgid "casting" msgstr "" -#: py/objstr.c -msgid "bad format string" +#: py/emitnative.c +msgid "return expected '%q' but got '%q'" msgstr "" -#: py/binary.c py/objarray.c -msgid "bad typecode" +#: py/emitnative.c +msgid "native raise" msgstr "" #: py/emitnative.c -msgid "binary op %q not implemented" +msgid "must raise an object" msgstr "" -#: ports/espressif/common-hal/audiobusio/PDMIn.c -msgid "bit_depth must be 8, 16, 24, or 32." +#: py/emitnative.c +msgid "native yield" msgstr "" -#: shared-module/bitmapfilter/__init__.c -msgid "bitmap size and depth must match" +#: py/lexer.c +msgid "unicode name escapes" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "bitmap sizes must match" -msgstr "velikosti bitmapy musí odpovídat" +#: py/modbuiltins.c py/objstr.c +msgid "char not in range(0x110000)" +msgstr "" -#: extmod/modrandom.c -msgid "bits must be 32 or less" -msgstr "počet bitů nesmí přesáhnout 32" +#: py/modbuiltins.c +msgid "chr() arg not in range(256)" +msgstr "" -#: shared-bindings/audiodelays/Echo.c shared-bindings/audiodelays/PitchShift.c -#: shared-bindings/audiofilters/Distortion.c -#: shared-bindings/audiofilters/Filter.c shared-bindings/audiomixer/Mixer.c -msgid "bits_per_sample must be 8 or 16" +#: py/modbuiltins.c +msgid "arg is an empty sequence" msgstr "" -#: py/emitinlinethumb.c -msgid "branch not in range" +#: py/modbuiltins.c +msgid "ord expects a character" msgstr "" -#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c -msgid "buffer is smaller than requested size" -msgstr "buffer je menší než požadovaná velikost" +#: py/modbuiltins.c +#, c-format +msgid "ord() expected a character, but string of length %d found" +msgstr "" -#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c -msgid "buffer size must be a multiple of element size" -msgstr "velikost bufferu musí být násobkem velikosti elementu" +#: py/modbuiltins.c +msgid "3-arg pow() not supported" +msgstr "pow() nepodporuje 3 argumenty" -#: shared-module/struct/__init__.c -msgid "buffer size must match format" +#: py/modbuiltins.c +msgid "must use keyword argument for key function" msgstr "" -#: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c -msgid "buffer slices must be of equal length" -msgstr "" +#: py/moderrno.c +msgid "Operation not permitted" +msgstr "Operace není povolena" -#: py/modstruct.c shared-module/struct/__init__.c -msgid "buffer too small" -msgstr "" +#: py/moderrno.c +msgid "No such file/directory" +msgstr "Žádný takový soubor / adresář" -#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c -msgid "buffer too small for requested bytes" -msgstr "buffer je příliš malý pro počet požadovaných bajtů" +#: py/moderrno.c +msgid "Input/output error" +msgstr "Chyba vstupu/výstupu" -#: py/emitbc.c -msgid "bytecode overflow" -msgstr "přetečení bytecode" +#: py/moderrno.c +msgid "Permission denied" +msgstr "Přístup odepřen" -#: py/objarray.c -msgid "bytes length not a multiple of item size" -msgstr "Počet bajtů není násobkem velikosti prvku" +#: py/moderrno.c +msgid "File exists" +msgstr "soubor existuje" -#: py/objstr.c -msgid "bytes value out of range" -msgstr "" +#: py/moderrno.c +msgid "No such device" +msgstr "Žádné takové zařízení" -#: ports/atmel-samd/bindings/samd/Clock.c -msgid "calibration is out of range" -msgstr "" +#: py/moderrno.c +msgid "No space left on device" +msgstr "Na zařízení nezůstal žádný prostor" -#: ports/atmel-samd/bindings/samd/Clock.c -msgid "calibration is read only" +#: py/modmath.c shared-bindings/math/__init__.c +msgid "math domain error" msgstr "" -#: shared-module/vectorio/Circle.c shared-module/vectorio/Polygon.c -#: shared-module/vectorio/Rectangle.c -msgid "can only have one parent" -msgstr "může mít pouze jednoho rodiče" +#: py/modmath.c +msgid "negative factorial" +msgstr "záporný faktoriál" -#: py/emitinlinethumb.c -msgid "can only have up to 4 parameters to Thumb assembly" +#: py/modmicropython.c +msgid "schedule queue full" msgstr "" -#: py/emitinlinextensa.c -msgid "can only have up to 4 parameters to Xtensa assembly" +#: py/modstruct.c shared-bindings/picogame/Bitmap.c +#: shared-bindings/picogame/Canvas.c shared-bindings/picogame/Framebuffer.c +#: shared-module/picogame/__init__.c shared-module/struct/__init__.c +msgid "buffer too small" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "can only specify one unknown dimension" +#: py/modstruct.c +#, c-format +msgid "pack expected %d items for packing (got %d)" msgstr "" -#: py/objtype.c -msgid "can't add special method to already-subclassed class" +#: py/modthread.c +msgid "expecting a dict for keyword args" msgstr "" -#: py/compile.c -msgid "can't assign to expression" +#: py/modweakref.c +msgid "not a heap object" msgstr "" -#: extmod/modasyncio.c -msgid "can't cancel self" -msgstr "nelze zrušit sám sebe" +#: py/nativeglue.c +msgid "set unsupported" +msgstr "set neoodporován" + +#: py/nativeglue.c +msgid "slice unsupported" +msgstr "" + +#: py/nativeglue.c +msgid "float unsupported" +msgstr "float není podporován" #: py/obj.c shared-module/adafruit_pixelbuf/PixelBuf.c msgid "can't convert %q to %q" msgstr "není možné převést %q na %q" #: py/obj.c -#, c-format -msgid "can't convert %s to complex" -msgstr "nelze převést %s na complex" +msgid "During handling of the above exception, another exception occurred:" +msgstr "Při zpracování uvedené výjimky nastala další výjimka:" #: py/obj.c -#, c-format -msgid "can't convert %s to float" -msgstr "nelze převést %s na float" +msgid "The above exception was the direct cause of the following exception:" +msgstr "Výše uvedená výjimka byla přímá příčina následující výjimky:" -#: py/objint.c py/runtime.c -#, c-format -msgid "can't convert %s to int" -msgstr "" +#: py/obj.c +msgid " File \"%q\", line %d" +msgstr " Soubor \"%q\", řádek %d" -#: py/objstr.c -msgid "can't convert '%q' object to %q implicitly" -msgstr "" +#: py/obj.c +msgid " File \"%q\"" +msgstr " Soubor \"%q\"" -#: extmod/ulab/code/numpy/vector.c -msgid "can't convert complex to float" -msgstr "nelze převést complex na float" +#: py/obj.c +msgid ", in %q\n" +msgstr ", v% q\n" #: py/obj.c -msgid "can't convert to complex" -msgstr "nelze převést na complex" +msgid "Traceback (most recent call last):\n" +msgstr "" #: py/obj.c msgid "can't convert to float" msgstr "nelze převést na float" -#: py/runtime.c -msgid "can't convert to int" -msgstr "nelze převést na int" +#: py/obj.c +#, c-format +msgid "can't convert %s to float" +msgstr "nelze převést %s na float" -#: py/objstr.c -msgid "can't convert to str implicitly" +#: py/obj.c +msgid "can't convert to complex" +msgstr "nelze převést na complex" + +#: py/obj.c +#, c-format +msgid "can't convert %s to complex" +msgstr "nelze převést %s na complex" + +#: py/obj.c +msgid "expected tuple/list" msgstr "" -#: py/compile.c -msgid "can't declare nonlocal in outer code" +#: py/obj.c +#, c-format +msgid "object '%s' isn't a tuple or list" +msgstr "objekt '%s' není tuple or nebo list" + +#: py/obj.c +msgid "tuple/list has wrong length" +msgstr "tuple/list má špatnou délku" + +#: py/obj.c +#, c-format +msgid "requested length %d but object has length %d" msgstr "" -#: py/compile.c -msgid "can't delete expression" +#: py/obj.c +msgid "indices must be integers" msgstr "" -#: py/emitnative.c -msgid "can't do binary op between '%q' and '%q'" +#: py/obj.c +msgid "%q indices must be integers, not %s" +msgstr "Indexy %q musí být celá čísla, nikoli %s" + +#: py/obj.c +msgid "object has no len" msgstr "" -#: py/emitnative.c -msgid "can't do unary op of '%q'" +#: py/obj.c +#, c-format +msgid "object of type '%s' has no len()" +msgstr "objekt typu '%s' nemá len()" + +#: py/obj.c +msgid "object doesn't support item deletion" msgstr "" -#: py/emitnative.c -msgid "can't implicitly convert '%q' to 'bool'" -msgstr "" +#: py/obj.c +#, c-format +msgid "'%s' object doesn't support item deletion" +msgstr "'%s' objekt nepodporuje smazání položky" -#: py/runtime.c -msgid "can't import name %q" +#: py/obj.c +msgid "object isn't subscriptable" msgstr "" -#: py/emitnative.c -msgid "can't load from '%q'" -msgstr "" +#: py/obj.c +#, c-format +msgid "'%s' object isn't subscriptable" +msgstr "'%s' objekt není vložitelný" -#: py/emitnative.c -msgid "can't load with '%q' index" +#: py/obj.c +msgid "object doesn't support item assignment" msgstr "" -#: py/builtinimport.c -msgid "can't perform relative import" -msgstr "nelze provést relativní import" +#: py/obj.c +#, c-format +msgid "'%s' object doesn't support item assignment" +msgstr "'%s' objekt nepodporuje přiřazení položky" -#: py/objgenerator.c -msgid "can't send non-None value to a just-started generator" +#: py/obj.c +msgid "object with buffer protocol required" msgstr "" -#: shared-module/sdcardio/SDCard.c -msgid "can't set 512 block size" -msgstr "nelze nastavit velikost bloku 512" +#: py/objarray.c +msgid "bytes length not a multiple of item size" +msgstr "Počet bajtů není násobkem velikosti prvku" -#: py/objexcept.c py/objnamedtuple.c -msgid "can't set attribute" +#: py/objarray.c py/objstr.c +msgid "string argument without an encoding" msgstr "" -#: py/runtime.c -msgid "can't set attribute '%q'" -msgstr "nelze nastavit atribut '%q'" +#: py/objarray.c +msgid "memoryview: length is not a multiple of itemsize" +msgstr "memoryview: délka není násobkem velikosti položky" -#: py/emitnative.c -msgid "can't store '%q'" +#: py/objarray.c py/objstr.c +msgid "substring not found" msgstr "" -#: py/emitnative.c -msgid "can't store to '%q'" +#: py/objarray.c py/objstr.c py/objstrunicode.c py/objtuple.c +#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c +#: shared-bindings/nvm/ByteArray.c +msgid "only slices with step=1 (aka None) are supported" msgstr "" -#: py/emitnative.c -msgid "can't store with '%q' index" +#: py/objarray.c +msgid "lhs and rhs should be compatible" msgstr "" -#: py/objstr.c -msgid "" -"can't switch from automatic field numbering to manual field specification" +#: py/objarray.c shared-bindings/alarm/SleepMemory.c +#: shared-bindings/memorymap/AddressRange.c shared-bindings/nvm/ByteArray.c +msgid "array/bytes required on right side" msgstr "" -#: py/objstr.c -msgid "" -"can't switch from manual field specification to automatic field numbering" +#: py/objarray.c +msgid "memoryview offset too large" msgstr "" #: py/objcomplex.c msgid "can't truncate-divide a complex number" msgstr "" -#: extmod/modasyncio.c -msgid "can't wait" -msgstr "nelze čekat" - -#: extmod/ulab/code/ndarray.c -msgid "cannot assign new shape" -msgstr "nelze přiřadit nový tvar" - -#: extmod/ulab/code/ndarray_operators.c -msgid "cannot cast output with casting rule" +#: py/objcomplex.c +msgid "complex divide by zero" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "cannot convert complex to dtype" -msgstr "nelze převést complex na dtype" - -#: extmod/ulab/code/ndarray.c -msgid "cannot convert complex type" -msgstr "nelze převést typ complex" +#: py/objcomplex.c +msgid "0.0 to a complex power" +msgstr "0.0 na komplexní mocninu" -#: py/objtype.c -msgid "cannot create '%q' instances" +#: py/objdeque.c +msgid "full" msgstr "" -#: py/objtype.c -msgid "cannot create instance" +#: py/objdeque.c +msgid "empty" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "cannot delete array elements" -msgstr "nelze smazat prvky pole" - -#: extmod/ulab/code/ndarray.c -msgid "cannot reshape array" -msgstr "nelze změnit rozměry pole" - -#: py/emitnative.c -msgid "casting" +#: py/objdict.c +msgid "dict update sequence has wrong length" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "channel re-init" -msgstr "opětovná inicializace kanálu" - -#: shared-bindings/_stage/Text.c -msgid "chars buffer too small" +#: py/objexcept.c py/objnamedtuple.c +msgid "can't set attribute" msgstr "" -#: py/modbuiltins.c -msgid "chr() arg not in range(0x110000)" +#: py/objfloat.c py/parsenum.c +msgid "complex values not supported" msgstr "" -#: py/modbuiltins.c -msgid "chr() arg not in range(256)" +#: py/objgenerator.c +msgid "generator already executing" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "clip point must be (x,y) tuple" +#: py/objgenerator.c +msgid "can't send non-None value to a just-started generator" msgstr "" -#: shared-bindings/msgpack/ExtType.c -msgid "code outside range 0~127" -msgstr "kód mimo rozsah 0~127" +#: py/objgenerator.c py/runtime.c +msgid "generator raised StopIteration" +msgstr "generátor způsobil StopIteration" -#: shared-bindings/displayio/Palette.c -msgid "color buffer must be 3 bytes (RGB) or 4 bytes (RGB + pad byte)" +#: py/objgenerator.c +msgid "generator ignored GeneratorExit" msgstr "" -#: shared-bindings/displayio/Palette.c -msgid "color buffer must be a buffer, tuple, list, or int" +#: py/objint.c py/runtime.c +#, c-format +msgid "can't convert %s to int" msgstr "" -#: shared-bindings/displayio/Palette.c -msgid "color buffer must be a bytearray or array of type 'b' or 'B'" +#: py/objint.c +msgid "float too big" msgstr "" -#: shared-bindings/displayio/Palette.c -msgid "color must be between 0x000000 and 0xffffff" +#: py/objint.c shared-bindings/time/__init__.c +msgid "No long integer support" +msgstr "Není podpora long integer" + +#: py/objint.c py/sequence.c +msgid "small int overflow" msgstr "" -#: py/emitnative.c -msgid "comparison of int and uint" -msgstr "porovnání int a uint" +#: py/objint.c shared-bindings/_bleio/Connection.c +#: shared-bindings/storage/__init__.c +msgid "%q=%q" +msgstr "%q=%q" -#: py/objcomplex.c -msgid "complex divide by zero" +#: py/objint_impl.h +#, c-format +msgid "value would overflow a %d byte buffer" msgstr "" -#: py/objfloat.c py/parsenum.c -msgid "complex values not supported" +#: py/objint_impl.h +msgid "can't convert negative int to unsigned" msgstr "" -#: extmod/modzlib.c -msgid "compression header" +#: py/objint_longlong.c py/parsenum.c +msgid "result overflows long long storage" msgstr "" -#: py/emitnative.c -msgid "conversion to object" +#: py/objint_longlong.c py/objint_mpz.c py/runtime.c +msgid "negative shift count" msgstr "" -#: extmod/ulab/code/numpy/filter.c -msgid "convolve arguments must be linear arrays" +#: py/objint_longlong.c py/objint_mpz.c py/runtime.c +msgid "negative power with no float support" msgstr "" -#: extmod/ulab/code/numpy/filter.c -msgid "convolve arguments must be ndarrays" +#: py/objint_longlong.c py/objint_mpz.c +msgid "overflow converting long int to machine word" msgstr "" -#: extmod/ulab/code/numpy/filter.c -msgid "convolve arguments must not be empty" +#: py/objint_mpz.c +msgid "pow() with 3 arguments requires integers" msgstr "" -#: extmod/ulab/code/numpy/io/io.c -msgid "corrupted file" -msgstr "poškozený soubor" - -#: extmod/ulab/code/numpy/poly.c -msgid "could not invert Vandermonde matrix" +#: py/objint_mpz.c +msgid "pow() 3rd argument cannot be 0" msgstr "" -#: shared-module/sdcardio/SDCard.c -msgid "couldn't determine SD card version" -msgstr "nelze zjistit verzi SD karty" - -#: extmod/ulab/code/numpy/numerical.c -msgid "cross is defined for 1D arrays of length 3" +#: py/objobject.c +msgid "__new__ arg must be a user-type" msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "data must be iterable" -msgstr "data musí být iterovatelná" - -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "data must be of equal length" -msgstr "data musí mít stejnou délku" +#: py/objobject.c +msgid "arg must be user-type" +msgstr "" -#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c -#, c-format -msgid "data pin #%d in use" -msgstr "datový pin #%d je používán" +#: py/objrange.c py/objslice.c shared-bindings/random/__init__.c +msgid "%q step cannot be zero" +msgstr "%q krok nemůže být nula" -#: extmod/ulab/code/ndarray.c -msgid "data type not understood" -msgstr "datový typ nebyl rozpoznán" +#: py/objslice.c +msgid "Cannot subclass slice" +msgstr "Nelze použít řez podtřídy" -#: py/parsenum.c -msgid "decimal numbers not supported" +#: py/objstr.c +msgid "unknown encoding: %q" msgstr "" -#: py/compile.c -msgid "default 'except' must be last" +#: py/objstr.c +msgid "bytes value out of range" msgstr "" -#: shared-bindings/msgpack/__init__.c -msgid "default is not a function" +#: py/objstr.c +msgid "join expects a list of str/bytes objects consistent with self object" msgstr "" -#: shared-bindings/audiobusio/PDMIn.c -msgid "" -"destination buffer must be a bytearray or array of type 'B' for bit_depth = 8" +#: py/objstr.c +msgid "empty separator" msgstr "" -#: shared-bindings/audiobusio/PDMIn.c -msgid "destination buffer must be an array of type 'H' for bit_depth = 16" +#: py/objstr.c +msgid "rsplit(None,n)" +msgstr "rsplit(None,n)" + +#: py/objstr.c +msgid "bad format string" msgstr "" -#: py/objdict.c -msgid "dict update sequence has wrong length" +#: py/objstr.c +#, c-format +msgid "unmatched '%c' in format" +msgstr "neshoduje se '%c' ve formátu" + +#: py/objstr.c +msgid "bad conversion specifier" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "diff argument must be an ndarray" +#: py/objstr.c +msgid "end of format while looking for conversion specifier" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "differentiation order out of range" +#: py/objstr.c +#, c-format +msgid "unknown conversion specifier %c" msgstr "" -#: extmod/ulab/code/numpy/transform.c -msgid "dimensions do not match" -msgstr "dimenze nesouhlasí" - -#: py/emitnative.c -msgid "div/mod not implemented for uint" -msgstr "div/mod nejsou implementované pro uint" - -#: extmod/ulab/code/numpy/create.c -msgid "divide by zero" -msgstr "dělení nulou" +#: py/objstr.c +msgid "expected ':' after format specifier" +msgstr "" -#: py/runtime.c -msgid "division by zero" +#: py/objstr.c +msgid "" +"can't switch from automatic field numbering to manual field specification" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "dtype must be float, or complex" -msgstr "dtype musí být float nebo complex" +#: py/objstr.c +msgid "%q index out of range" +msgstr "Index %q je mimo rozsah" -#: extmod/ulab/code/ndarray_operators.c -msgid "dtype of int32 is not supported" +#: py/objstr.c +msgid "attributes not supported" msgstr "" -#: py/objdeque.c -msgid "empty" +#: py/objstr.c +msgid "" +"can't switch from manual field specification to automatic field numbering" msgstr "" -#: extmod/ulab/code/numpy/io/io.c -msgid "empty file" -msgstr "prázdný soubor" - -#: extmod/modasyncio.c extmod/modheapq.c -msgid "empty heap" +#: py/objstr.c +msgid "invalid format specifier" msgstr "" #: py/objstr.c -msgid "empty separator" +msgid "sign not allowed in string format specifier" msgstr "" -#: shared-bindings/random/__init__.c -msgid "empty sequence" +#: py/objstr.c +msgid "sign not allowed with integer format specifier 'c'" msgstr "" #: py/objstr.c -msgid "end of format while looking for conversion specifier" +msgid "unknown format code '%c' for object of type '%q'" msgstr "" -#: shared-bindings/alarm/time/TimeAlarm.c -msgid "epoch_time not supported on this board" -msgstr "epoch_time není podporován na této desce" +#: py/objstr.c +msgid "'=' alignment not allowed in string format specifier" +msgstr "Specifikátor zarovnání '=' není ve formátovacím řetězci povolen" -#: ports/nordic/common-hal/busio/UART.c -#, c-format -msgid "error = 0x%08lX" +#: py/objstr.c +msgid "format needs a dict" msgstr "" -#: py/runtime.c -msgid "exceptions must derive from BaseException" +#: py/objstr.c +msgid "incomplete format key" msgstr "" #: py/objstr.c -msgid "expected ':' after format specifier" +msgid "incomplete format" msgstr "" -#: py/obj.c -msgid "expected tuple/list" +#: py/objstr.c +msgid "format string needs more arguments" msgstr "" -#: py/modthread.c -msgid "expecting a dict for keyword args" +#: py/objstr.c +#, c-format +msgid "%%c needs int or char" msgstr "" -#: py/compile.c -msgid "expecting an assembler instruction" +#: py/objstr.c +#, c-format +msgid "unsupported format character '%c' (0x%x) at index %d" msgstr "" -#: py/compile.c -msgid "expecting just a value for set" +#: py/objstr.c +msgid "format string didn't convert all arguments" msgstr "" -#: py/compile.c -msgid "expecting key:value for dict" +#: py/objstr.c +msgid "non-hex digit" msgstr "" -#: shared-bindings/msgpack/__init__.c -msgid "ext_hook is not a function" +#: py/objstr.c +msgid "can't convert to str implicitly" msgstr "" -#: py/argcheck.c -msgid "extra keyword arguments given" +#: py/objstr.c +msgid "can't convert '%q' object to %q implicitly" msgstr "" -#: py/argcheck.c -msgid "extra positional arguments given" +#: py/objstrunicode.c +#, c-format +msgid "string indices must be integers, not %s" msgstr "" -#: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/gifio/OnDiskGif.c -#: shared-bindings/synthio/__init__.c shared-module/gifio/GifWriter.c -msgid "file must be a file opened in byte mode" +#: py/objstrunicode.c +msgid "string index out of range" msgstr "" -#: shared-bindings/traceback/__init__.c -msgid "file write is not available" -msgstr "zápis do souboru není dostupný" - -#: shared-bindings/storage/__init__.c -msgid "filesystem must provide mount method" +#: py/objtemplate.c +msgid "expected str or Interpolation" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "first argument must be a callable" -msgstr "První argument musí být zavolatelný" - -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "first argument must be a function" -msgstr "první argument musí být funkce" - -#: extmod/ulab/code/numpy/create.c -msgid "first argument must be a tuple of ndarrays" -msgstr "první argument musí být tuple nebo ndarray" +#: py/objtype.c +msgid "Call super().__init__() before accessing native object." +msgstr "Volání super().__init__() před přístupem k nativnímu objektu." -#: extmod/ulab/code/numpy/transform.c extmod/ulab/code/numpy/vector.c -msgid "first argument must be an ndarray" +#: py/objtype.c +msgid "__init__() should return None" msgstr "" #: py/objtype.c -msgid "first argument to super() must be type" +#, c-format +msgid "__init__() should return None, not '%s'" msgstr "" -#: extmod/ulab/code/scipy/linalg/linalg.c -msgid "first two arguments must be ndarrays" -msgstr "první dva argumenty musí být ndarray" - -#: extmod/ulab/code/ndarray.c -msgid "flattening order must be either 'C', or 'F'" +#: py/objtype.c py/runtime.c +msgid "unreadable attribute" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "flip argument must be an ndarray" +#: py/objtype.c py/runtime.c +msgid "object not callable" msgstr "" -#: py/objint.c -msgid "float too big" +#: py/objtype.c py/runtime.c shared-module/atexit/__init__.c +msgid "'%q' object isn't callable" msgstr "" -#: py/nativeglue.c -msgid "float unsupported" -msgstr "float není podporován" - -#: shared-bindings/_stage/Text.c -msgid "font must be 2048 bytes long" +#: py/objtype.c +msgid "type takes 1 or 3 arguments" msgstr "" -#: extmod/moddeflate.c -msgid "format" +#: py/objtype.c +msgid "can't create instance" msgstr "" -#: py/objstr.c -msgid "format requires a dict" +#: py/objtype.c +msgid "can't create '%q' instances" msgstr "" -#: py/objdeque.c -msgid "full" +#: py/objtype.c +msgid "can't add special method to already-subclassed class" msgstr "" -#: py/argcheck.c -msgid "function doesn't take keyword arguments" +#: py/objtype.c +msgid "type isn't an acceptable base type" msgstr "" -#: py/argcheck.c -#, c-format -msgid "function expected at most %d arguments, got %d" +#: py/objtype.c +msgid "type '%q' isn't an acceptable base type" msgstr "" -#: py/bc.c py/objnamedtuple.c -msgid "function got multiple values for argument '%q'" +#: py/objtype.c +msgid "multiple inheritance not supported" msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "function has the same sign at the ends of interval" +#: py/objtype.c +msgid "multiple bases have instance lay-out conflict" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "function is defined for ndarrays only" -msgstr "funkce je definována pouze pro ndarraye" +#: py/objtype.c +msgid "first argument to super() must be type" +msgstr "" -#: extmod/ulab/code/numpy/carray/carray.c -msgid "function is implemented for ndarrays only" -msgstr "funkce je implementována jen pro ndarraye" +#: py/objtype.c +msgid "issubclass() arg 2 must be a class or a tuple of classes" +msgstr "" -#: py/argcheck.c -#, c-format -msgid "function missing %d required positional arguments" -msgstr "funkci chybí %d povinné poziční argumenty" +#: py/objtype.c +msgid "issubclass() arg 1 must be a class" +msgstr "" -#: py/bc.c -msgid "function missing keyword-only argument" -msgstr "funkci chybí argument pouze pro klíčové slovo" +#: py/parse.c +msgid "not a constant" +msgstr "není konstanta" -#: py/bc.c -msgid "function missing required keyword argument '%q'" -msgstr "funkci chybí argument specifikovaný klíčovým slovem" +#: py/parse.c +msgid "Unable to init parser" +msgstr "" -#: py/bc.c -#, c-format -msgid "function missing required positional argument #%d" -msgstr "funkci chybí požadovaný argument na pozici #%d" +#: py/parse.c +msgid "unexpected indent" +msgstr "neočekávané odsazení" -#: py/argcheck.c py/bc.c py/objnamedtuple.c shared-bindings/_eve/__init__.c -#: shared-bindings/time/__init__.c -#, c-format -msgid "function takes %d positional arguments but %d were given" +#: py/parse.c +msgid "unindent doesn't match any outer indent level" msgstr "" -#: py/objgenerator.c -msgid "generator already executing" +#: py/parse.c +msgid "malformed f-string" msgstr "" -#: py/objgenerator.c -msgid "generator ignored GeneratorExit" +#: py/parsenum.c +msgid "invalid syntax for integer" msgstr "" -#: py/objgenerator.c py/runtime.c -msgid "generator raised StopIteration" -msgstr "generátor způsobil StopIteration" - -#: shared-bindings/_stage/Layer.c -msgid "graphic must be 2048 bytes long" +#: py/parsenum.c +#, c-format +msgid "invalid syntax for integer with base %d" msgstr "" -#: extmod/modhashlib.c -msgid "hash is final" -msgstr "hash je konečný" +#: py/parsenum.c +msgid "invalid syntax for number" +msgstr "" -#: extmod/modheapq.c -msgid "heap must be a list" +#: py/parsenum.c +msgid "decimal numbers not supported" msgstr "" -#: py/compile.c -msgid "identifier redefined as global" -msgstr "" +#: py/persistentcode.c +msgid "incompatible .mpy file" +msgstr "nekompatibilní .mpy soubor" -#: py/compile.c -msgid "identifier redefined as nonlocal" +#: py/persistentcode.c +msgid "MicroPython .mpy file; use CircuitPython mpy-cross" msgstr "" -#: py/compile.c -msgid "import * not at module level" +#: py/persistentcode.c +msgid "native code in .mpy unsupported" msgstr "" #: py/persistentcode.c @@ -3241,937 +3748,1076 @@ msgid "incompatible .mpy arch" msgstr "nekopmatibilní architektura .mpy" #: py/persistentcode.c -msgid "incompatible .mpy file" -msgstr "nekompatibilní .mpy soubor" - -#: py/objstr.c -msgid "incomplete format" +msgid "function must be bytecode" msgstr "" -#: py/objstr.c -msgid "incomplete format key" +#: py/proto.c shared-bindings/digitalio/DigitalInOutProtocol.c +msgid "'%q' object does not support '%q'" +msgstr "Objekt '%q' nepodporuje '%q'" + +#: py/qstr.c +msgid "name too long" msgstr "" -#: extmod/modbinascii.c -msgid "incorrect padding" +#: py/runtime.c +msgid "name not defined" msgstr "" -#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/transform.c -msgid "index is out of bounds" +#: py/runtime.c +msgid "name '%q' isn't defined" msgstr "" -#: shared-bindings/_pixelmap/PixelMap.c -msgid "index must be tuple or int" -msgstr "index musí být tuple nebo int" +#: py/runtime.c +msgid "unsupported type for operator" +msgstr "" -#: extmod/ulab/code/numpy/numerical.c extmod/ulab/code/ulab_tools.c -#: ports/espressif/common-hal/pulseio/PulseIn.c -#: shared-bindings/bitmaptools/__init__.c -msgid "index out of range" +#: py/runtime.c +msgid "unsupported type for %q: '%s'" msgstr "" -#: py/obj.c -msgid "indices must be integers" +#: py/runtime.c +msgid "unsupported types for %q: '%q', '%q'" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "indices must be integers, slices, or Boolean lists" +#: py/runtime.c +msgid "wrong number of values to unpack" msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "initial values must be iterable" -msgstr "výchozí hodnoty musí být iterovatelné" +#: py/runtime.c +#, c-format +msgid "need more than %d values to unpack" +msgstr "" -#: shared-bindings/_bleio/Characteristic.c shared-bindings/_bleio/Descriptor.c -msgid "initial_value length is wrong" -msgstr "délka initial_value je chybná" +#: py/runtime.c +#, c-format +msgid "too many values to unpack (expected %d)" +msgstr "" -#: py/compile.c -msgid "inline assembler must be a function" +#: py/runtime.c +msgid "type object '%q' has no attribute '%q'" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "input and output dimensions differ" -msgstr "dimenze vstupu a výstupu se liší" +#: py/runtime.c +msgid "module '%q' has no attribute '%q'" +msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "input and output shapes differ" -msgstr "vstupní a výstupní tvar je růzmý" +#: py/runtime.c +msgid "'%s' object has no attribute '%q'" +msgstr "'%s' objekt nemá žádný atribut '%q'" -#: extmod/ulab/code/numpy/create.c -msgid "input argument must be an integer, a tuple, or a list" -msgstr "vstupní argument musí být integer, tuple nebo list" +#: py/runtime.c +msgid "can't set attribute '%q'" +msgstr "nelze nastavit atribut '%q'" -#: extmod/ulab/code/numpy/fft/fft_tools.c -msgid "input array length must be power of 2" +#: py/runtime.c +msgid "object not iterable" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "input arrays are not compatible" -msgstr "vstupní pole nejsou kompatibilní" +#: py/runtime.c +msgid "'%q' object isn't iterable" +msgstr "Objekt '%q' není iterovatelný" -#: extmod/ulab/code/numpy/poly.c -msgid "input data must be an iterable" +#: py/runtime.c +msgid "object not an iterator" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "input dtype must be float or complex" -msgstr "vstupní dtype musí být float nebo complex" - -#: extmod/ulab/code/numpy/poly.c -msgid "input is not iterable" -msgstr "vstup není iterovatelný" +#: py/runtime.c +msgid "'%q' object isn't an iterator" +msgstr "Objekt '%q' není iterátor" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "input matrix is asymmetric" +#: py/runtime.c +msgid "exceptions must derive from BaseException" msgstr "" -#: extmod/ulab/code/numpy/linalg/linalg.c -#: extmod/ulab/code/scipy/linalg/linalg.c -msgid "input matrix is singular" +#: py/runtime.c +msgid "can't import name %q" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "input must be 1- or 2-d" -msgstr "vstup musí být 1- nebo 2-d" - -#: extmod/ulab/code/numpy/carray/carray.c -msgid "input must be a 1D ndarray" -msgstr "vstup musí být 1D ndarray" +#: py/runtime.c +msgid "memory allocation failed, heap is locked" +msgstr "" -#: extmod/ulab/code/scipy/linalg/linalg.c extmod/ulab/code/user/user.c -msgid "input must be a dense ndarray" -msgstr "vstup musí být hustý ndarray" +#: py/runtime.c +#, c-format +msgid "memory allocation failed, allocating %u bytes" +msgstr "" -#: extmod/ulab/code/user/user.c shared-bindings/_eve/__init__.c -msgid "input must be an ndarray" -msgstr "vstup musí být ndarray" +#: py/runtime.c +msgid "can't convert to int" +msgstr "nelze převést na int" -#: extmod/ulab/code/numpy/carray/carray.c -msgid "input must be an ndarray, or a scalar" -msgstr "vstup musí být ndarray nebo scalar" +#: py/runtime.c +msgid "division by zero" +msgstr "" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "input must be one-dimensional" -msgstr "vstup musí být jednorozměrný" +#: py/runtime.c +msgid "maximum recursion depth exceeded" +msgstr "" -#: extmod/ulab/code/ulab_tools.c -msgid "input must be square matrix" +#: py/sequence.c shared-bindings/displayio/Group.c +msgid "object not in sequence" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "input must be tuple, list, range, or ndarray" +#: py/stream.c shared-bindings/getpass/__init__.c +msgid "stream operation not supported" msgstr "" -#: extmod/ulab/code/numpy/poly.c -msgid "input vectors must be of equal length" +#: py/vm.c +msgid "local variable referenced before assignment" msgstr "" -#: extmod/ulab/code/numpy/approx.c -msgid "interp is defined for 1D iterables of equal length" +#: py/vm.c +msgid "no active exception to reraise" msgstr "" +#: py/vm.c +msgid "opcode" +msgstr "opcode" + +#: shared-bindings/_bleio/Adapter.c +msgid "Cannot create a new Adapter; use _bleio.adapter;" +msgstr "Není možné vytvořit nový adaptér; použití _bleio.adapter;" + +#: shared-bindings/_bleio/Adapter.c +msgid "Could not set address" +msgstr "Není možné nastavit adresu" + #: shared-bindings/_bleio/Adapter.c #, c-format msgid "interval must be in range %s-%s" msgstr "" -#: py/compile.c -msgid "invalid arch" +#: shared-bindings/_bleio/Adapter.c +msgid "Cannot have scan responses for extended, connectable advertisements." msgstr "" -#: shared-bindings/bitmaptools/__init__.c -#, c-format -msgid "invalid bits_per_pixel %d, must be, 1, 2, 4, 8, 16, 24, or 32" -msgstr "chybné bits_per_pixel %d, musí být 1, 2, 4, 8, 16, 24, or 32" +#: shared-bindings/_bleio/Adapter.c +msgid "Only connectable advertisements can be directed" +msgstr "" -#: shared-module/ssl/SSLSocket.c -msgid "invalid cert" -msgstr "špatný certifikár" +#: shared-bindings/_bleio/Adapter.c +msgid "non-zero timeout must be >= interval" +msgstr "nenulový timeout musí být >= interval" -#: shared-bindings/bitmaptools/__init__.c -#, c-format -msgid "invalid element size %d for bits_per_pixel %d\n" +#: shared-bindings/_bleio/Adapter.c +msgid "window must be <= interval" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -#, c-format -msgid "invalid element_size %d, must be, 1, 2, or 4" -msgstr "chybná element_size %d, musí být 1, 2, nebo 4" +#: shared-bindings/_bleio/Adapter.c +msgid "Prefix buffer must be on the heap" +msgstr "" -#: shared-bindings/traceback/__init__.c -msgid "invalid exception" -msgstr "špatná výjimka" +#: shared-bindings/_bleio/CharacteristicBuffer.c +msgid "CharacteristicBuffer writing not provided" +msgstr "CharacteristicBuffer psaní není poskytováno" -#: py/objstr.c -msgid "invalid format specifier" +#: shared-bindings/_bleio/Connection.c +msgid "" +"Connection has been disconnected and can no longer be used. Create a new " +"connection." msgstr "" +"Připojení bylo odpojeno a nelze jej dále používat. Vytvořte nové připojení." -#: shared-bindings/wifi/Radio.c -msgid "invalid hostname" -msgstr "špatný hostname" +#: shared-bindings/_bleio/PacketBuffer.c +#, c-format +msgid "Buffer too short by %d bytes" +msgstr "Buffer je příliš krátký o %d bajtů" -#: shared-module/ssl/SSLSocket.c -msgid "invalid key" -msgstr "špatný klíč" +#: shared-bindings/_bleio/PacketBuffer.c +msgid "No connection: length cannot be determined" +msgstr "Žádné připojení: nelze určit délku" -#: py/compile.c -msgid "invalid micropython decorator" +#: shared-bindings/_bleio/UUID.c +msgid "UUID string not 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'" +msgstr "UUID řetězec neodpovídá 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'" + +#: shared-bindings/_bleio/UUID.c +msgid "UUID value is not str, int or byte buffer" +msgstr "Hodnota UUID není str, int ani byte buffer" + +#: shared-bindings/_bleio/UUID.c +msgid "not a 128-bit UUID" msgstr "" -#: ports/espressif/common-hal/espcamera/Camera.c -msgid "invalid setting" -msgstr "neplatné nastavení" +#: shared-bindings/_bleio/__init__.c shared-bindings/emmcio/EMMC.c +#: shared-bindings/memorymonitor/AllocationSize.c +#: shared-bindings/pulseio/PulseIn.c shared-module/bitmaptools/__init__.c +#: shared-module/displayio/legacy/Bitmap.c +#: shared-module/displayio/legacy/Group.c shared-module/displayio/lvgl/Bitmap.c +#: shared-module/displayio/lvgl/Group.c +msgid "Read-only" +msgstr "Pouze pro čtení" -#: shared-bindings/random/__init__.c -msgid "invalid step" +#: shared-bindings/_pew/PewPew.c +msgid "Incorrect buffer size" +msgstr "Nesprávná velikost vyrovnávací paměti" + +#: shared-bindings/_pixelmap/PixelMap.c +msgid "nested index must be int" msgstr "" -#: py/compile.c py/parse.c -msgid "invalid syntax" +#: shared-bindings/_pixelmap/PixelMap.c +msgid "index must be tuple or int" +msgstr "index musí být tuple nebo int" + +#: shared-bindings/_stage/Layer.c +msgid "map buffer too small" msgstr "" -#: py/parsenum.c -msgid "invalid syntax for integer" +#: shared-bindings/_stage/Text.c +msgid "chars buffer too small" msgstr "" -#: py/parsenum.c +#: shared-bindings/adafruit_bus_device/spi_device/SPIDevice.c +msgid "Pin is input only" +msgstr "Pin je pouze vstupní" + +#: shared-bindings/adafruit_pixelbuf/PixelBuf.c +#: shared-module/_pixelmap/PixelMap.c #, c-format -msgid "invalid syntax for integer with base %d" +msgid "Unmatched number of items on RHS (expected %d, got %d)." msgstr "" -#: py/parsenum.c -msgid "invalid syntax for number" -msgstr "" +#: shared-bindings/aesio/aes.c +msgid "Key must be 16, 24, or 32 bytes long" +msgstr "Klíč musí být dlouhý 16, 24 nebo 32 bajtů" -#: py/objtype.c -msgid "issubclass() arg 1 must be a class" -msgstr "" +#: shared-bindings/aesio/aes.c +msgid "Requested AES mode is unsupported" +msgstr "Požadovaný režim AES je nepodporovaný" -#: py/objtype.c -msgid "issubclass() arg 2 must be a class or a tuple of classes" -msgstr "" +#: shared-bindings/aesio/aes.c +msgid "Source and destination buffers must be the same length" +msgstr "Zdrojové a cílové buffery musí být stejné délky" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "iterations did not converge" -msgstr "" +#: shared-bindings/aesio/aes.c +msgid "ECB only operates on 16 bytes at a time" +msgstr "ECB operuje najednou pouze 16 bajtů" -#: py/objstr.c -msgid "join expects a list of str/bytes objects consistent with self object" -msgstr "" +#: shared-bindings/aesio/aes.c +msgid "CBC blocks must be multiples of 16 bytes" +msgstr "Bloky CBC musí být násobky 16 bajtů" -#: py/argcheck.c -msgid "keyword argument(s) not implemented - use normal args instead" +#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c +#: shared-bindings/nvm/ByteArray.c +msgid "Slice and value different lengths." msgstr "" -#: py/emitinlinethumb.c py/emitinlinextensa.c -msgid "label '%q' not defined" -msgstr "" +#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c +#: shared-bindings/nvm/ByteArray.c +msgid "Array values should be single bytes." +msgstr "Hodnoty pole by měly být jednoduché bajty." -#: py/compile.c -msgid "label redefined" -msgstr "" +#: shared-bindings/alarm/SleepMemory.c +msgid "Unable to write to sleep_memory." +msgstr "Nelze zapsat do sleep_memory." -#: py/objarray.c -msgid "lhs and rhs should be compatible" -msgstr "" +#: shared-bindings/alarm/__init__.c +msgid "Expected a kind of %q" +msgstr "Očekáván typ %q" -#: py/emitnative.c -msgid "local '%q' has type '%q' but source is '%q'" -msgstr "" +#: shared-bindings/alarm/time/TimeAlarm.c shared-bindings/time/__init__.c +msgid "RTC is not supported on this board" +msgstr "RTC není na této desce podporován" -#: py/emitnative.c -msgid "local '%q' used before type known" -msgstr "" +#: shared-bindings/alarm/time/TimeAlarm.c +msgid "Supply one of monotonic_time or epoch_time" +msgstr "Musíš definovat monotonic_time nebo epoch_time" -#: py/vm.c -msgid "local variable referenced before assignment" -msgstr "" +#: shared-bindings/alarm/time/TimeAlarm.c +msgid "epoch_time not supported on this board" +msgstr "epoch_time není podporován na této desce" -#: ports/espressif/common-hal/canio/CAN.c -msgid "loopback + silent mode not supported by peripheral" +#: shared-bindings/alarm/time/TimeAlarm.c +msgid "Time is in the past." +msgstr "Čas je v minulosti." + +#: shared-bindings/analogbufio/BufferedIn.c +msgid "%q must be a bytearray or array of type 'H' or 'B'" +msgstr "%q musí být bytearray nebo pole typu 'H' nebo 'B'" + +#: shared-bindings/audiobusio/PDMIn.c +msgid "%q must be multiple of 8." msgstr "" -#: ports/espressif/common-hal/mdns/Server.c -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "mDNS already initialized" -msgstr "mDNS je již inicializováno" +#: shared-bindings/audiobusio/PDMIn.c shared-bindings/audioi2sin/I2SIn.c +#: shared-bindings/usb_host_audio/USBIn.c +msgid "Cannot record to a file" +msgstr "Nelze nahrávat do souboru" -#: ports/espressif/common-hal/mdns/Server.c -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "mDNS only works with built-in WiFi" -msgstr "mDNS pracuje pouze s vestavěnou WiFi" +#: shared-bindings/audiobusio/PDMIn.c shared-bindings/audioi2sin/I2SIn.c +#: shared-bindings/usb_host_audio/USBIn.c +msgid "Destination capacity is smaller than destination_length." +msgstr "Cílová kapacita je menší než destination_length." -#: py/parse.c -msgid "malformed f-string" +#: shared-bindings/audiobusio/PDMIn.c +msgid "destination buffer must be an array of type 'H' for bit_depth = 16" msgstr "" -#: shared-bindings/_stage/Layer.c -msgid "map buffer too small" +#: shared-bindings/audiobusio/PDMIn.c +msgid "" +"destination buffer must be a bytearray or array of type 'B' for bit_depth = 8" msgstr "" -#: py/modmath.c shared-bindings/math/__init__.c -msgid "math domain error" -msgstr "" +#: shared-bindings/audiocore/RawSample.c +msgid "%q must be a bytearray or array of type 'h', 'H', 'b', or 'B'" +msgstr "%q musí být bytearray nebo pole typu 'h', 'H', 'b', nebo 'B'" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "matrix is not positive definite" +#: shared-bindings/audiocore/RawSample.c +msgid "Length of %q must be an even multiple of channel_count * type_size" msgstr "" -#: ports/espressif/common-hal/_bleio/Descriptor.c -#: ports/nordic/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Descriptor.c -#, c-format -msgid "max_length must be 0-%d when fixed_length is %s" +#: shared-bindings/audiodelays/Chorus.c shared-bindings/audiodelays/Echo.c +#: shared-bindings/audiodelays/Flanger.c +#: shared-bindings/audiodelays/GranularPitchShift.c +#: shared-bindings/audiodelays/MultiTapDelay.c +#: shared-bindings/audiodelays/PitchShift.c +#: shared-bindings/audiofilters/Distortion.c +#: shared-bindings/audiofilters/Filter.c shared-bindings/audiofilters/Phaser.c +#: shared-bindings/audiomixer/Mixer.c shared-module/audiotap/Tap.c +msgid "bits_per_sample must be 8 or 16" msgstr "" -#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/random/random.c -msgid "maximum number of dimensions is " -msgstr "maximální počet dimenzí je " +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "samples_signed must be true" +msgstr "" -#: py/runtime.c -msgid "maximum recursion depth exceeded" +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "bits_per_sample must be 16" msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "maxiter must be > 0" -msgstr "maxiter musí být > 0" +#: shared-bindings/audioi2sin/I2SIn.c shared-bindings/usb_host_audio/USBIn.c +#, c-format +msgid "invalid destination buffer, must be an array of type: %c" +msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "maxiter should be > 0" -msgstr "maxiter by měl být > 0" +#: shared-bindings/audioio/AudioOut.c shared-bindings/emmcio/EMMC.c +msgid "%q and %q must be different" +msgstr "%q a %q musí být rozdílné" -#: extmod/ulab/code/numpy/numerical.c -msgid "median argument must be an ndarray" +#: shared-bindings/audiomp3/MP3Decoder.c shared-bindings/gifio/OnDiskGif.c +#: shared-bindings/synthio/__init__.c shared-module/gifio/GifWriter.c +msgid "file must be a file opened in byte mode" msgstr "" -#: py/runtime.c -#, c-format -msgid "memory allocation failed, allocating %u bytes" +#: shared-bindings/bitmapfilter/__init__.c +msgid "" +"weights must be a sequence with an odd square number of elements (usually 9 " +"or 25)" msgstr "" -#: py/runtime.c -msgid "memory allocation failed, heap is locked" +#: shared-bindings/bitmapfilter/__init__.c +msgid "weights must be an object of type %q, %q, %q, or %q, not %q " msgstr "" -#: py/objarray.c -msgid "memoryview offset too large" +#: shared-bindings/bitmaptools/__init__.c +msgid "clip point must be (x,y) tuple" msgstr "" -#: py/objarray.c -msgid "memoryview: length is not a multiple of itemsize" -msgstr "memoryview: délka není násobkem velikosti položky" +#: shared-bindings/bitmaptools/__init__.c +msgid "source palette too large" +msgstr "zdrojová paleta je příliš velká" -#: extmod/modtime.c -msgid "mktime needs a tuple of length 8 or 9" -msgstr "" +#: shared-bindings/bitmaptools/__init__.c +msgid "Bitmap size and bits per value must match" +msgstr "Velikost bitmapy a počet bitů na hodnotu se musí shodovat" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "mode must be complete, or reduced" -msgstr "" +#: shared-bindings/bitmaptools/__init__.c +msgid "For L8 colorspace, input bitmap must have 8 bits per pixel" +msgstr "Pro barevný prostor L8 musí mít vstupní bitmapa 8 bitů na pixel" -#: py/builtinimport.c -msgid "module not found" -msgstr "" +#: shared-bindings/bitmaptools/__init__.c +msgid "For RGB colorspaces, input bitmap must have 16 bits per pixel" +msgstr "Pro barevný prostor RGB musí mít vstupní bitmapa 16 bitů na pixel" -#: ports/espressif/common-hal/wifi/Monitor.c -msgid "monitor init failed" -msgstr "" +#: shared-bindings/bitmaptools/__init__.c +msgid "Unsupported colorspace" +msgstr "Nepodporovaný barevný prostor" -#: extmod/ulab/code/numpy/poly.c -msgid "more degrees of freedom than data points" +#: shared-bindings/bitmaptools/__init__.c +msgid "Mask bitmap size must match the other bitmaps" msgstr "" -#: py/compile.c -msgid "multiple *x in assignment" +#: shared-bindings/bitmaptools/__init__.c +msgid "Mask bitmap must have 8 bits per pixel" msgstr "" -#: py/objtype.c -msgid "multiple bases have instance lay-out conflict" +#: shared-bindings/bitmaptools/__init__.c +msgid "out of range of target" msgstr "" -#: py/objtype.c -msgid "multiple inheritance not supported" +#: shared-bindings/bitmaptools/__init__.c +msgid "value out of range of target" msgstr "" -#: py/emitnative.c -msgid "must raise an object" +#: shared-bindings/bitmaptools/__init__.c +msgid "background value out of range of target" msgstr "" -#: py/modbuiltins.c -msgid "must use keyword argument for key function" +#: shared-bindings/bitmaptools/__init__.c +msgid "Coordinate arrays types have different sizes" msgstr "" -#: py/runtime.c -msgid "name '%q' is not defined" +#: shared-bindings/bitmaptools/__init__.c +msgid "Coordinate arrays have different lengths" +msgstr "Pole souřadnic mají různé délky" + +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element_size %d, must be, 1, 2, or 4" +msgstr "chybná element_size %d, musí být 1, 2, nebo 4" + +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element size %d for bits_per_pixel %d\n" msgstr "" -#: py/runtime.c -msgid "name not defined" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid bits_per_pixel %d, must be, 1, 2, 4, 8, 16, 24, or 32" +msgstr "chybné bits_per_pixel %d, musí být 1, 2, 4, 8, 16, 24, or 32" + +#: shared-bindings/bitmaptools/__init__.c +msgid "bitmap sizes must match" +msgstr "velikosti bitmapy musí odpovídat" + +#: shared-bindings/bitmaptools/__init__.c +msgid "source_bitmap must have value_count of 2 or 65536" msgstr "" -#: py/qstr.c -msgid "name too long" +#: shared-bindings/bitmaptools/__init__.c +msgid "source_bitmap must have value_count of 65536" msgstr "" -#: py/persistentcode.c -msgid "native code in .mpy unsupported" +#: shared-bindings/bitmaptools/__init__.c +msgid "source_bitmap must have value_count of 8" msgstr "" -#: py/asmthumb.c -msgid "native method too big" +#: shared-bindings/bitmaptools/__init__.c +msgid "unsupported colorspace for dither" msgstr "" -#: py/emitnative.c -msgid "native yield" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Input buffer length (%d) must be a multiple of the strand count (%d)" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "ndarray length overflows" -msgstr "délka ndarray přetekla" +#: shared-bindings/board/__init__.c +msgid "No default %q bus" +msgstr "Žádná výchozí sběrnice %q" -#: py/runtime.c -#, c-format -msgid "need more than %d values to unpack" +#: shared-bindings/busdisplay/BusDisplay.c +msgid "%q must be 1 when %q is True" +msgstr "%q musí být 1, pokud %q je True" + +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +msgid "Display must have a 16 bit colorspace." +msgstr "Displej musí mít 16bitový barevný prostor." + +#: shared-bindings/busio/UART.c shared-bindings/canio/CAN.c +msgid "tx and rx cannot both be None" msgstr "" -#: py/modmath.c -msgid "negative factorial" -msgstr "záporný faktoriál" +#: shared-bindings/busio/UART.c shared-bindings/displayio/Group.c +msgid "Must be a %q subclass." +msgstr "Musí být podtřída %q." -#: py/objint_longlong.c py/objint_mpz.c py/runtime.c -msgid "negative power with no float support" +#: shared-bindings/canio/RemoteTransmissionRequest.c +msgid "RemoteTransmissionRequests limited to 8 bytes" +msgstr "RemoteTransmissionRequests je limitován na 8 bajtů" + +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/ec/EllipticCurvePublicKey.c +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/padding/__init__.c +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "Only %q supported" msgstr "" -#: py/objint_mpz.c py/runtime.c -msgid "negative shift count" +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/padding/__init__.c +msgid "label is not supported" msgstr "" -#: shared-bindings/_pixelmap/PixelMap.c -msgid "nested index must be int" +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/rsa/__init__.c +#: shared-bindings/hmac/__init__.c +msgid "key does not have the expected %q purpose" msgstr "" -#: shared-module/sdcardio/SDCard.c -msgid "no SD card" -msgstr "není vložena SD karta" +#: shared-bindings/digitalio/DigitalInOut.c +#: shared-bindings/i2cioexpander/IOPin.c +msgid "Cannot set value when direction is input." +msgstr "Nelze nastavit hodnotu, když směr je vstup." -#: py/vm.c -msgid "no active exception to reraise" +#: shared-bindings/digitalio/DigitalInOut.c +#: shared-bindings/i2cioexpander/IOPin.c +msgid "Drive mode not used when direction is input." msgstr "" -#: py/compile.c -msgid "no binding for nonlocal found" +#: shared-bindings/digitalio/DigitalInOut.c +#: shared-bindings/i2cioexpander/IOPin.c +msgid "Pull not used when direction is output." msgstr "" -#: shared-module/msgpack/__init__.c -msgid "no default packer" +#: shared-bindings/digitalio/DigitalInOutProtocol.c +msgid "%q object missing '%q' method" msgstr "" -#: extmod/modrandom.c extmod/ulab/code/numpy/random/random.c -msgid "no default seed" +#: shared-bindings/digitalio/DigitalInOutProtocol.c +msgid "%q object missing '%q' attribute" msgstr "" -#: py/builtinimport.c -msgid "no module named '%q'" +#: shared-bindings/digitalio/DigitalInOutProtocol.c +msgid "object does not support DigitalInOut protocol" msgstr "" -#: shared-module/sdcardio/SDCard.c -msgid "no response from SD card" -msgstr "žádná odpověď z SD karty" +#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/memorymonitor/AllocationSize.c +#: shared-bindings/pulseio/PulseIn.c +msgid "Cannot delete values" +msgstr "Nelze odstranit hodnoty" -#: ports/espressif/common-hal/espcamera/Camera.c py/objobject.c py/runtime.c -msgid "no such attribute" +#: 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 +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +msgid "Slices not supported" msgstr "" -#: ports/espressif/common-hal/_bleio/Connection.c -#: ports/nordic/common-hal/_bleio/Connection.c -msgid "non-UUID found in service_uuids_whitelist" +#: shared-bindings/displayio/Palette.c +msgid "color buffer must be a bytearray or array of type 'b' or 'B'" msgstr "" -#: py/compile.c -msgid "non-default argument follows default argument" +#: shared-bindings/displayio/Palette.c +msgid "color buffer must be 3 bytes (RGB) or 4 bytes (RGB + pad byte)" msgstr "" -#: py/objstr.c -msgid "non-hex digit found" +#: shared-bindings/displayio/Palette.c +msgid "color must be between 0x000000 and 0xffffff" msgstr "" -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "non-zero timeout must be > 0.01" -msgstr "nenulový timeout musí být > 0.01" - -#: shared-bindings/_bleio/Adapter.c -msgid "non-zero timeout must be >= interval" -msgstr "nenulový timeout musí být >= interval" - -#: shared-bindings/_bleio/UUID.c -msgid "not a 128-bit UUID" +#: shared-bindings/displayio/Palette.c +msgid "color buffer must be a buffer, tuple, list, or int" msgstr "" -#: py/parse.c -msgid "not a constant" -msgstr "není konstanta" - -#: py/objstr.c -msgid "not all arguments converted during string formatting" +#: shared-bindings/displayio/TileGrid.c +msgid "Tile width must exactly divide bitmap width" msgstr "" -#: py/objstr.c -msgid "not enough arguments for format string" +#: shared-bindings/displayio/TileGrid.c +msgid "Tile height must exactly divide bitmap height" msgstr "" -#: extmod/ulab/code/numpy/carray/carray_tools.c -msgid "not implemented for complex dtype" -msgstr "není implementováno pro komplexní dtype" - -#: extmod/ulab/code/numpy/bitwise.c -msgid "not supported for input types" -msgstr "není podporováno pro vstupní typy" +#: shared-bindings/displayio/TileGrid.c +msgid "New bitmap must be same size as old bitmap" +msgstr "Nová bitmapa musí mít stejnou velikost jako původní bitmapa" -#: extmod/ulab/code/numpy/create.c -msgid "number of points must be at least 2" +#: shared-bindings/displayio/TileGrid.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-module/displayio/legacy/TileGrid.c +#: shared-module/displayio/lvgl/TileGrid.c +msgid "Tile index out of bounds" msgstr "" -#: py/builtinhelp.c -msgid "object " -msgstr "objekt " - -#: py/obj.c -#, c-format -msgid "object '%s' isn't a tuple or list" -msgstr "objekt '%s' není tuple or nebo list" +#: shared-bindings/dualbank/__init__.c +msgid "offset must be >= 0" +msgstr "offset musí být >= 0" -#: py/obj.c -msgid "object doesn't support item assignment" +#: shared-bindings/emmcio/EMMC.c shared-bindings/i2cioexpander/IOExpander.c +msgid "address out of range" msgstr "" -#: py/obj.c -msgid "object doesn't support item deletion" -msgstr "" +#: shared-bindings/epaperdisplay/EPaperDisplay.c +msgid "Refresh too soon" +msgstr "Pokus o obnovení příliš brzo" -#: py/obj.c -msgid "object has no len" -msgstr "" +#: shared-bindings/framebufferio/FramebufferDisplay.c +msgid "Buffer is not a bytearray." +msgstr "Buffer není bytearray." -#: py/obj.c -msgid "object isn't subscriptable" -msgstr "" +#: shared-bindings/gnss/GNSS.c +msgid "System entry must be gnss.SatelliteSystem" +msgstr "Parametr \"system\" musí být gnss.SatelliteSystem" -#: py/runtime.c -msgid "object not an iterator" -msgstr "" +#: shared-bindings/hashlib/__init__.c shared-bindings/hmac/__init__.c +msgid "Unsupported hash algorithm" +msgstr "Nepodporovaný hash algoritmus" -#: py/objtype.c py/runtime.c -msgid "object not callable" +#: shared-bindings/i2cioexpander/IOExpander.c +msgid "num_pins must be 8 or 16" msgstr "" -#: py/sequence.c shared-bindings/displayio/Group.c -msgid "object not in sequence" +#: shared-bindings/i2ctarget/I2CTarget.c +msgid "addresses is empty" msgstr "" -#: py/runtime.c -msgid "object not iterable" -msgstr "" +#: shared-bindings/ipaddress/IPv4Address.c shared-bindings/ipaddress/__init__.c +msgid "Not a valid IP string" +msgstr "Nevalidní IP string" -#: py/obj.c +#: shared-bindings/ipaddress/IPv4Address.c #, c-format -msgid "object of type '%s' has no len()" -msgstr "objekt typu '%s' nemá len()" +msgid "Address must be %d bytes long" +msgstr "Adresa musí být %d bajtů dlouhá" -#: py/obj.c -msgid "object with buffer protocol required" -msgstr "" +#: shared-bindings/ipaddress/__init__.c +msgid "Only int or string supported for ip" +msgstr "Pro IP je podporován pouze int nebo string" -#: py/objstr.c -msgid "odd-length string" +#: shared-bindings/is31fl3741/FrameBuffer.c +msgid "width must be greater than zero" msgstr "" -#: supervisor/shared/web_workflow/web_workflow.c -msgid "off" -msgstr "vypnuto" +#: shared-bindings/is31fl3741/FrameBuffer.c +msgid "Scale dimensions must divide by 3" +msgstr "" -#: extmod/ulab/code/utils/utils.c -msgid "offset is too large" -msgstr "offset je příliš velký" +#: shared-bindings/is31fl3741/FrameBuffer.c +msgid "LED mappings must match display size" +msgstr "Mapování LED musí korespondovat s velikostí displeje" -#: shared-bindings/dualbank/__init__.c -msgid "offset must be >= 0" -msgstr "offset musí být >= 0" +#: shared-bindings/is31fl3741/IS31FL3741.c +msgid "Mapping must be a tuple" +msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "offset must be non-negative and no greater than buffer length" +#: shared-bindings/jpegio/JpegDecoder.c +msgid "%q must be of type %q, %q, or %q, not %q" msgstr "" -#: ports/nordic/common-hal/audiobusio/PDMIn.c -#: ports/stm/common-hal/audiobusio/PDMIn.c -msgid "only bit_depth=16 is supported" +#: shared-bindings/mdns/Server.c +msgid "" +"Failed to add service TXT record; non-string or bytes found in txt_records" msgstr "" -#: ports/stm/common-hal/audiobusio/PDMIn.c -msgid "only mono is supported" -msgstr "je podporováno pouze mono" +#: shared-bindings/memorymap/AddressRange.c +msgid "Address range wraps around" +msgstr "Adresní rozsah se překlápí přes maximální možnou adresu" -#: extmod/ulab/code/numpy/create.c -msgid "only ndarrays can be concatenated" -msgstr "pouze ndarraye mohou být spojeny" +#: shared-bindings/microcontroller/Pin.c +msgid "%q contains duplicate pins" +msgstr "%q obsahuje duplicitní piny" -#: ports/stm/common-hal/audiobusio/PDMIn.c -msgid "only oversample=64 is supported" -msgstr "je podporován pouze oversampling 64" +#: shared-bindings/microcontroller/Pin.c +msgid "%q and %q contain duplicate pins" +msgstr "%q a %q obsahují duplicitní piny" -#: ports/nordic/common-hal/audiobusio/PDMIn.c -#: ports/stm/common-hal/audiobusio/PDMIn.c -msgid "only sample_rate=16000 is supported" +#: shared-bindings/mii/Ethernet.c shared-bindings/wifi/Radio.c +msgid "invalid hostname" +msgstr "špatný hostname" + +#: shared-bindings/msgpack/ExtType.c +msgid "code outside range 0~127" +msgstr "kód mimo rozsah 0~127" + +#: shared-bindings/msgpack/__init__.c +msgid "default is not a function" +msgstr "" + +#: shared-bindings/msgpack/__init__.c +msgid "ext_hook is not a function" msgstr "" -#: py/objarray.c py/objstr.c py/objstrunicode.c py/objtuple.c -#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c #: shared-bindings/nvm/ByteArray.c -msgid "only slices with step=1 (aka None) are supported" +msgid "Unable to write to nvm." +msgstr "Není možné zapisovat do nvm." + +#: shared-bindings/os/__init__.c +msgid "No hardware random available" msgstr "" -#: py/vm.c -msgid "opcode" -msgstr "opcode" +#: shared-bindings/paralleldisplaybus/ParallelBus.c +msgid "Specify exactly one of data0 or data_pins" +msgstr "Specifikuj přesně jeden z data0 nebo data_pins" -#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/bitwise.c -#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/numpy/vector.c -msgid "operands could not be broadcast together" -msgstr "" +#: shared-bindings/picogame/Bitmap.c shared-module/msgpack/__init__.c +#: supervisor/shared/settings.c +msgid "Invalid format" +msgstr "Špatný formát" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "operation is defined for 2D arrays only" -msgstr "operace je definována pouze pro 2D pole" +#: shared-bindings/ps2io/Ps2.c +msgid "Failed sending command." +msgstr "Nepodařilo se odeslat příkaz." -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "operation is defined for ndarrays only" -msgstr "operace je definována pouze pro ndarray pole" +#: shared-bindings/pulseio/PulseOut.c +msgid "Array must contain halfwords (type 'H')" +msgstr "Pole musí obsahovat poloviční slova (typ „H“)" -#: extmod/ulab/code/ndarray.c -msgid "operation is implemented for 1D Boolean arrays only" -msgstr "operace je immplementována pouze pro 1D boolean pole" +#: shared-bindings/pwmio/PWMOut.c +msgid "Conflicting settings for shared resource" +msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "operation is not implemented on ndarrays" +#: shared-bindings/random/__init__.c +msgid "stop not reachable from start" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "operation is not supported for given type" +#: shared-bindings/random/__init__.c +msgid "invalid step" msgstr "" -#: extmod/ulab/code/ndarray_operators.c -msgid "operation not supported for the input types" +#: shared-bindings/random/__init__.c +msgid "empty sequence" msgstr "" -#: py/modbuiltins.c -msgid "ord expects a character" +#: shared-bindings/rclcpy/Publisher.c +msgid "Publishers can only be created from a parent node" msgstr "" -#: py/modbuiltins.c +#: shared-bindings/rgbmatrix/RGBMatrix.c #, c-format -msgid "ord() expected a character, but string of length %d found" -msgstr "" +msgid "Must use a multiple of 6 rgb pins, not %d" +msgstr "Je nutné použít několik kolíků 6 rgb, nikoli %d" -#: extmod/ulab/code/utils/utils.c -msgid "out array is too small" -msgstr "výstupní pole je příliš malé" +#: 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 adresní pin, %d rgb pin a %d dlaždice indikuje výšku %d, ne %d" -#: extmod/ulab/code/numpy/random/random.c -msgid "out has wrong type" -msgstr "" +#: shared-bindings/socketpool/Socket.c +msgid "port must be >= 0" +msgstr "port musí být >= 0" -#: extmod/ulab/code/numpy/vector.c -msgid "out keyword is not supported for complex dtype" -msgstr "" +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c +msgid "buffer too small for requested bytes" +msgstr "buffer je příliš malý pro počet požadovaných bajtů" -#: extmod/ulab/code/numpy/vector.c -msgid "out keyword is not supported for function" -msgstr "" +#: shared-bindings/socketpool/SocketPool.c +msgid "Name or service not known" +msgstr "Jméno nebo služba není známa" -#: extmod/ulab/code/utils/utils.c -msgid "out must be a float dense array" +#: shared-bindings/spitarget/SPITarget.c +msgid "Packet buffers for an SPI transfer must have the same length." msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "out must be an ndarray" +#: shared-bindings/ssl/SSLContext.c +msgid "Server side context cannot have hostname" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "out must be of float dtype" -msgstr "" +#: shared-bindings/storage/__init__.c shared-bindings/usb_audio/__init__.c +#: shared-bindings/usb_cdc/__init__.c shared-bindings/usb_hid/__init__.c +#: shared-bindings/usb_midi/__init__.c shared-bindings/usb_video/__init__.c +msgid "Cannot change USB devices now" +msgstr "Nelze změnit USB zařízení" -#: shared-bindings/bitmaptools/__init__.c -msgid "out of range of target" -msgstr "" +#: shared-bindings/supervisor/__init__.c shared-module/lvfontio/OnDiskFont.c +msgid "File not found" +msgstr "Soubor nenalezen" -#: extmod/ulab/code/numpy/random/random.c -msgid "output array has wrong type" +#: shared-bindings/time/__init__.c +msgid "timestamp out of range for platform time_t" msgstr "" -#: extmod/ulab/code/numpy/random/random.c -msgid "output array must be contiguous" +#: shared-bindings/traceback/__init__.c +msgid "Supply both or neither of %q and %q" msgstr "" -#: py/objint_mpz.c -msgid "overflow converting long int to machine word" -msgstr "" +#: shared-bindings/traceback/__init__.c +msgid "file write is not available" +msgstr "zápis do souboru není dostupný" -#: py/modstruct.c -#, c-format -msgid "pack expected %d items for packing (got %d)" -msgstr "" +#: shared-bindings/traceback/__init__.c +msgid "invalid exception" +msgstr "špatná výjimka" -#: shared-bindings/_stage/Layer.c shared-bindings/_stage/Text.c -msgid "palette must be 32 bytes long" +#: shared-bindings/usb_audio/USBSpeaker.c +msgid "destination must be an array of type 'h'" msgstr "" -#: py/emitinlinextensa.c -msgid "parameters must be registers in sequence a2 to a5" +#: shared-bindings/usb_audio/__init__.c +msgid "At least one of microphone and speaker must be enabled" msgstr "" -#: py/emitinlinethumb.c -msgid "parameters must be registers in sequence r0 to r3" -msgstr "" +#: shared-bindings/usb_hid/Device.c +msgid "%q, %q, and %q must all be the same length" +msgstr "%q, %q, a %q musí mít všechny shodnou délku" -#: extmod/vfs_posix_file.c -msgid "poll on file not available on win32" +#: shared-bindings/util.c +msgid "" +"Object has been deinitialized and can no longer be used. Create a new object." msgstr "" +"Objekt byl deinicializován a nelze jej dále používat. Vytvořte nový objekt." -#: ports/espressif/common-hal/pulseio/PulseIn.c -msgid "pop from an empty PulseIn" +#: shared-bindings/warnings/__init__.c +msgid "%q must be a subclass of %q" msgstr "" -#: ports/atmel-samd/common-hal/pulseio/PulseIn.c -#: ports/cxd56/common-hal/pulseio/PulseIn.c -#: ports/nordic/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 z prázdného %q" +#: shared-bindings/wifi/Radio.c +msgid "Invalid hex password" +msgstr "Špatné heslo v hex" -#: shared-bindings/socketpool/Socket.c -msgid "port must be >= 0" -msgstr "port musí být >= 0" +#: shared-bindings/wifi/Radio.c +msgid "Invalid MAC address" +msgstr "Chybná MAC adresa" -#: py/compile.c -msgid "positional arg after **" -msgstr "" +#: shared-bindings/wifi/Radio.c +msgid "AuthMode.OPEN is not used with password" +msgstr "AuthMode.OPEN nepoužívá heslo" -#: py/compile.c -msgid "positional arg after keyword arg" +#: shared-bindings/wifi/Radio.c +msgid "Supply either %q or %q, not both" msgstr "" -#: py/objint_mpz.c -msgid "pow() 3rd argument cannot be 0" -msgstr "" +#: shared-bindings/wifi/Radio.c +msgid "Invalid BSSID" +msgstr "Chybné BSSID" -#: py/objint_mpz.c -msgid "pow() with 3 arguments requires integers" -msgstr "" +#: shared-bindings/wifi/Radio.c supervisor/shared/web_workflow/web_workflow.c +msgid "Authentication failure" +msgstr "Autentizace selhala" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "pull masks conflict with direction masks" -msgstr "" +#: shared-bindings/wifi/Radio.c +msgid "No network with that ssid" +msgstr "Žádná síť s takovým SSID" -#: py/parse.c -msgid "raw f-strings are not supported" -msgstr "surové f-stringy nesjou podporované" +#: shared-bindings/wifi/Radio.c +#, c-format +msgid "Unknown failure %d" +msgstr "Neznámé selhání %d" -#: extmod/ulab/code/numpy/fft/fft_tools.c -msgid "real and imaginary parts must be of equal length" +#: shared-module/adafruit_bus_device/i2c_device/I2CDevice.c +#, c-format +msgid "No I2C device at address: 0x%x" +msgstr "Žádné I2C zařízení na adrese: 0x%x" + +#: shared-module/audiocore/WaveFile.c +msgid "Invalid format chunk size" +msgstr "Neplatná velikost bloku" + +#: shared-module/audiocore/__init__.c shared-module/usb_audio/USBMicrophone.c +msgid "The sample's %q does not match" msgstr "" -#: py/builtinimport.c -msgid "relative import" +#: shared-module/audiodelays/MultiTapDelay.c +msgid "%q in %q must be of type %q or %q, not %q" msgstr "" -#: py/obj.c -#, c-format -msgid "requested length %d but object has length %d" +#: shared-module/audiofilewriter/AudioFileWriter.c +msgid "Only 8/16-bit mono/stereo is supported" msgstr "" -#: extmod/ulab/code/ndarray_operators.c -msgid "results cannot be cast to specified type" +#: shared-module/audiofilewriter/AudioFileWriter.c +msgid "buffer_size too small for source" msgstr "" -#: py/compile.c -msgid "return annotation must be an identifier" +#: shared-module/audiomp3/MP3Decoder.c +msgid "Couldn't allocate decoder" +msgstr "Dekodér nelze přiřadit" + +#: shared-module/audiomp3/MP3Decoder.c +msgid "Failed to parse MP3 file" +msgstr "Soubor MP3 se nepodařilo analyzovat" + +#: shared-module/bitbangio/I2C.c shared-module/msgpack/__init__.c +msgid "%q too long" msgstr "" -#: py/emitnative.c -msgid "return expected '%q' but got '%q'" +#: shared-module/bitmapfilter/__init__.c +msgid "bitmap size and depth must match" msgstr "" -#: shared-bindings/rgbmatrix/RGBMatrix.c -#, c-format -msgid "rgb_pins[%d] duplicates another pin assignment" +#: shared-module/bitmapfilter/__init__.c +msgid "unsupported bitmap depth" msgstr "" -#: shared-bindings/rgbmatrix/RGBMatrix.c -#, c-format -msgid "rgb_pins[%d] is not on the same port as clock" +#: shared-module/busdisplay/lvgl/BusDisplay.c +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "LVGL display create failed" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "roll argument must be an ndarray" +#: shared-module/busdisplay/lvgl/BusDisplay.c +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "LVGL buffer alloc failed" msgstr "" -#: py/objstr.c -msgid "rsplit(None,n)" +#: shared-module/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "OAEP requires this build to enable TLS 1.3 support" msgstr "" -#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c -#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c -msgid "sampling rate out of range" +#: shared-module/displayio/bus_core.c +msgid "Unsupported display bus type" +msgstr "Nepodporovaná sběrnice dispalye" + +#: shared-module/displayio/legacy/Bitmap.c +#: shared-module/displayio/lvgl/Bitmap.c +msgid "Invalid bits per value" msgstr "" -#: py/modmicropython.c -msgid "schedule queue full" +#: shared-module/displayio/legacy/ColorConverter.c +#: shared-module/displayio/lvgl/ColorConverter.c +msgid "Only one color can be transparent at a time" +msgstr "Pouze jedna barva může být nastavena jako transparentní" + +#: shared-module/displayio/legacy/Group.c shared-module/displayio/lvgl/Group.c +msgid "Layer already in a group" +msgstr "Vrstva již v groupě je" + +#: shared-module/displayio/legacy/Group.c +msgid "Layer must be a Group or TileGrid subclass" +msgstr "Vrstva musí být Group nebo TileGrid" + +#: shared-module/displayio/legacy/OnDiskBitmap.c +#: shared-module/displayio/lvgl/OnDiskBitmap.c +#, c-format +msgid "" +"Only Windows format, uncompressed BMP supported: given header size is %d" msgstr "" -#: py/builtinimport.c -msgid "script compilation not supported" +#: shared-module/displayio/legacy/OnDiskBitmap.c +#: shared-module/displayio/lvgl/OnDiskBitmap.c +msgid "RLE-compressed BMP not supported" msgstr "" -#: py/nativeglue.c -msgid "set unsupported" -msgstr "set neoodporován" - -#: extmod/ulab/code/numpy/random/random.c -msgid "shape must be None, and integer or a tuple of integers" -msgstr "" +#: shared-module/displayio/legacy/OnDiskBitmap.c +#: shared-module/displayio/lvgl/OnDiskBitmap.c +msgid "Unable to read color palette data" +msgstr "Nelze číst data palety barev" -#: extmod/ulab/code/ndarray.c -msgid "shape must be integer or tuple of integers" -msgstr "tvar musí být integer nebo tuple integerů" +#: shared-module/displayio/legacy/__init__.c +msgid "Too many displays" +msgstr "Příliš mnoho displejů" -#: shared-module/msgpack/__init__.c -msgid "short read" +#: shared-module/displayio/legacy/__init__.c +msgid "Too many display buses; deinit() unused displays" msgstr "" -#: py/objstr.c -msgid "sign not allowed in string format specifier" +#: shared-module/displayio/lvgl/Group.c +msgid "Layer does not support scaling" msgstr "" -#: py/objstr.c -msgid "sign not allowed with integer format specifier 'c'" +#: shared-module/displayio/lvgl/Group.c +msgid "Layer must be a Group, TileGrid, vector shape or VideoBuffer" msgstr "" -#: extmod/ulab/code/ulab_tools.c -msgid "size is defined for ndarrays only" +#: shared-module/displayio/lvgl/TileGrid.c +msgid "LVGL displayio backend does not support flips/transpose yet" msgstr "" -#: extmod/ulab/code/numpy/random/random.c -msgid "size must match out.shape when used together" +#: shared-module/displayio/lvgl/TileGrid.c +msgid "OnDiskBitmap requires its own pixel_shader" msgstr "" -#: py/nativeglue.c -msgid "slice unsupported" +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "LVGL dirty row alloc failed" msgstr "" -#: py/objint.c py/sequence.c -msgid "small int overflow" +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +#: shared-module/videocore/VideoBuffer.c +#: shared-module/videocore/legacy/VideoBuffer.c +#: shared-module/videocore/lvgl/VideoBuffer.c +msgid "VideoBuffer can't stream into a rotated display" msgstr "" -#: main.c -msgid "soft reboot\n" +#: shared-module/gifio/GifWriter.c +msgid "unsupported colorspace for GifWriter" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "sort argument must be an ndarray" +#: shared-module/hmac/HMAC.c +msgid "key does not support this digest" msgstr "" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "sos array must be of shape (n_section, 6)" +#: shared-module/hmac/HMAC.c +msgid "HMAC of an empty message is not supported with a hardware key" msgstr "" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "sos[:, 3] should be all ones" -msgstr "" +#: shared-module/i2cdisplaybus/I2CDisplayBus.c +#: shared-module/is31fl3741/IS31FL3741.c +#, c-format +msgid "Unable to find I2C Display at %x" +msgstr "I2C display nenalezen na %x" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "sosfilt requires iterable arguments" +#: shared-module/i2cioexpander/IOExpander.c +msgid "Cannot deinitialize board IOExpander" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "source palette too large" -msgstr "zdrojová paleta je příliš velká" +#: shared-module/imagecapture/ParallelImageCapture.c +msgid "This microcontroller does not support continuous capture." +msgstr "Tento mikrokontrolér nepodporuje kontinuální snímání." -#: shared-bindings/bitmaptools/__init__.c -msgid "source_bitmap must have value_count of 2 or 65536" +#: shared-module/jpegio/JpegDecoder.c +msgid "Interrupted by output function" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "source_bitmap must have value_count of 65536" +#: shared-module/jpegio/JpegDecoder.c +msgid "Device error or wrong termination of input stream" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "source_bitmap must have value_count of 8" +#: shared-module/jpegio/JpegDecoder.c +msgid "Insufficient memory pool for the image" msgstr "" -#: extmod/modre.c -msgid "splitting with sub-captures" +#: shared-module/jpegio/JpegDecoder.c +msgid "Insufficient stream input buffer" msgstr "" -#: py/objstr.c -msgid "start/end indices" +#: shared-module/jpegio/JpegDecoder.c +msgid "Parameter error" msgstr "" -#: shared-bindings/random/__init__.c -msgid "stop not reachable from start" +#: shared-module/jpegio/JpegDecoder.c +msgid "Data format error (may be broken data)" msgstr "" -#: py/stream.c shared-bindings/getpass/__init__.c -msgid "stream operation not supported" +#: shared-module/jpegio/JpegDecoder.c +msgid "Right format but not supported" msgstr "" -#: py/objarray.c py/objstr.c -msgid "string argument without an encoding" +#: shared-module/jpegio/JpegDecoder.c +msgid "Unsupported JPEG (may be progressive)" msgstr "" -#: py/objstrunicode.c -msgid "string index out of range" +#: shared-module/jpegio/JpegDecoder.c +msgid "%q() without %q()" msgstr "" -#: py/objstrunicode.c +#: shared-module/memorymonitor/AllocationAlarm.c #, c-format -msgid "string indices must be integers, not %s" -msgstr "" - -#: py/objarray.c py/objstr.c -msgid "substring not found" -msgstr "" +msgid "Attempt to allocate %d blocks" +msgstr "Pokus o alokování %d bloků" -#: py/compile.c -msgid "super() can't find self" +#: shared-module/msgpack/__init__.c +msgid "short read" msgstr "" -#: extmod/modjson.c -msgid "syntax error in JSON" +#: shared-module/msgpack/__init__.c +msgid "no default packer" msgstr "" -#: extmod/modtime.c -msgid "ticks interval overflow" +#: shared-module/paralleldisplaybus/ParallelBus.c +msgid "" +"This microcontroller only supports data0=, not data_pins=, because it " +"requires contiguous pins." msgstr "" -#: ports/nordic/common-hal/watchdog/WatchDogTimer.c -msgid "timeout duration exceeded the maximum supported value" -msgstr "timeout překročil maximální podporovanou hodnotu" +#: shared-module/rgbmatrix/RGBMatrix.c +msgid "The length of rgb_pins must be 6, 12, 18, 24, or 30" +msgstr "Počet prvků rgb_pin musí být 6, 12, 18, 24, nebo 30" -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "timeout must be < 655.35 secs" -msgstr "timeout musí být < 655.35 s" +#: shared-module/rgbmatrix/RGBMatrix.c +#, c-format +msgid "rgb_pins[%d] is not on the same port as clock" +msgstr "" -#: ports/raspberrypi/common-hal/floppyio/__init__.c -msgid "timeout waiting for flux" +#: shared-module/rgbmatrix/RGBMatrix.c +#, c-format +msgid "rgb_pins[%d] duplicates another pin assignment" msgstr "" -#: ports/raspberrypi/common-hal/floppyio/__init__.c -#: shared-module/floppyio/__init__.c -msgid "timeout waiting for index pulse" +#: shared-module/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 "" +#: shared-module/rgbmatrix/RGBMatrix.c +msgid "No timer available" +msgstr "Není k dispozici žádný časovač" + +#: shared-module/rgbmatrix/RGBMatrix.c +#, c-format +msgid "Internal error #%d" +msgstr "Vnitřní chyba #%d" + #: shared-module/sdcardio/SDCard.c msgid "timeout waiting for v1 card" msgstr "" @@ -4180,277 +4826,350 @@ msgstr "" msgid "timeout waiting for v2 card" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "timer re-init" -msgstr "opětovný init timeru" +#: shared-module/sdcardio/SDCard.c +msgid "no SD card" +msgstr "není vložena SD karta" -#: shared-bindings/time/__init__.c -msgid "timestamp out of range for platform time_t" -msgstr "" +#: shared-module/sdcardio/SDCard.c +msgid "couldn't determine SD card version" +msgstr "nelze zjistit verzi SD karty" -#: extmod/ulab/code/ndarray.c -msgid "tobytes can be invoked for dense arrays only" -msgstr "" +#: shared-module/sdcardio/SDCard.c +msgid "no response from SD card" +msgstr "žádná odpověď z SD karty" -#: py/compile.c -msgid "too many args" -msgstr "příliš mnoho argumentů" +#: shared-module/sdcardio/SDCard.c +msgid "SD card CSD format not supported" +msgstr "CSD formát SD karty není podporován" -#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/create.c -msgid "too many dimensions" -msgstr "příliš mnoho dimenzí" +#: shared-module/sdcardio/SDCard.c +msgid "can't set 512 block size" +msgstr "nelze nastavit velikost bloku 512" -#: extmod/ulab/code/ndarray.c -msgid "too many indices" -msgstr "" +#: shared-module/ssl/SSLSocket.c +msgid "Invalid socket for TLS" +msgstr "Chybný soket pro TLS" -#: py/asmthumb.c -msgid "too many locals for native method" -msgstr "" +#: shared-module/ssl/SSLSocket.c +msgid "invalid cert" +msgstr "špatný certifikár" -#: py/runtime.c -#, c-format -msgid "too many values to unpack (expected %d)" +#: shared-module/storage/__init__.c +msgid "File write in progress" msgstr "" -#: extmod/ulab/code/numpy/approx.c -msgid "trapz is defined for 1D arrays of equal length" +#: shared-module/storage/__init__.c +msgid "Mount point directory missing" msgstr "" -#: extmod/ulab/code/numpy/approx.c -msgid "trapz is defined for 1D iterables" +#: shared-module/storage/__init__.c +msgid "Cannot remount path when visible via USB." msgstr "" -#: py/obj.c -msgid "tuple/list has wrong length" -msgstr "tuple/list má špatnou délku" +#: shared-module/struct/__init__.c +msgid "'S' and 'O' are not supported format types" +msgstr "'S' a 'O' nejsou podporované typy formátů" -#: ports/espressif/common-hal/canio/CAN.c -#, c-format -msgid "twai_driver_install returned esp-idf error #%d" +#: shared-module/struct/__init__.c +msgid "buffer size must match format" msgstr "" -#: ports/espressif/common-hal/canio/CAN.c -#, c-format -msgid "twai_start returned esp-idf error #%d" +#: shared-module/synthio/__init__.c +msgid "%q must be array of type 'h'" +msgstr "%q musí být pole typu 'h'" + +#: shared-module/tilepalettemapper/TilePaletteMapper.c +msgid "TilePaletteMapper may only be bound to a TileGrid once" msgstr "" -#: shared-bindings/busio/UART.c shared-bindings/canio/CAN.c -msgid "tx and rx cannot both be None" +#: shared-module/touchio/TouchIn.c +msgid "No pullup on pin; 1Mohm recommended" msgstr "" -#: py/objtype.c -msgid "type '%q' is not an acceptable base type" +#: shared-module/touchio/TouchIn.c +msgid "No pulldown on pin; 1Mohm recommended" +msgstr "Žádný pulldown na pinu; doporučeno 1Mohm" + +#: shared-module/usb/core/Device.c +msgid "No usb host port initialized" +msgstr "Žádný USB host port není inicializován" + +#: shared-module/usb/core/Device.c +msgid "Pipe error" msgstr "" -#: py/objtype.c -msgid "type is not an acceptable base type" +#: shared-module/usb/core/Device.c +msgid "No configuration set" +msgstr "Konfigurace není nastavena" + +#: shared-module/usb_hid/Device.c +msgid "USB busy" +msgstr "USB zaneprázdněno" + +#: shared-module/vectorio/Circle.c shared-module/vectorio/Polygon.c +#: shared-module/vectorio/Rectangle.c +msgid "can only have one parent" +msgstr "může mít pouze jednoho rodiče" + +#: shared-module/vectorio/Polygon.c +msgid "Polygon needs at least 3 points" +msgstr "Polygon potřebuje nejméně 3 body" + +#: shared-module/videocore/VideoBuffer.c +msgid "framebuffer went away" msgstr "" -#: py/runtime.c -msgid "type object '%q' has no attribute '%q'" +#: shared-module/videocore/VideoBuffer.c +msgid "video doesn't fit in framebuffer" msgstr "" -#: py/objtype.c -msgid "type takes 1 or 3 arguments" +#: shared-module/videocore/VideoBuffer.c +msgid "framebuffer missing required functions" msgstr "" -#: py/objint_longlong.c -msgid "ulonglong too large" +#: shared-module/videocore/VideoBuffer.c +msgid "video format must be byte aligned" msgstr "" -#: py/parse.c -msgid "unexpected indent" -msgstr "neočekávané odsazení" +#: shared-module/videocore/VideoBuffer.c +msgid "video format doesn't match framebuffer" +msgstr "" -#: py/bc.c -msgid "unexpected keyword argument" +#: shared-module/videocore/VideoBuffer.c +msgid "video source rejected the destination" msgstr "" -#: py/argcheck.c py/bc.c py/objnamedtuple.c -#: shared-bindings/traceback/__init__.c -msgid "unexpected keyword argument '%q'" +#: shared-module/videocore/VideoBuffer.c +msgid "video in a framebuffer must be at x == 0" msgstr "" -#: py/lexer.c -msgid "unicode name escapes" +#: shared-module/videocore/VideoBuffer.c +msgid "video size changed since play; stop and play again" msgstr "" -#: py/parse.c -msgid "unindent doesn't match any outer indent level" +#: shared-module/videocore/VideoBuffer.c +msgid "VideoBuffer is playing into a different framebuffer" msgstr "" -#: py/objstr.c -#, c-format -msgid "unknown conversion specifier %c" +#: shared-module/videocore/legacy/VideoBuffer.c +msgid "VideoBuffer does not support transforms" msgstr "" -#: py/objstr.c -msgid "unknown format code '%c' for object of type '%q'" +#: shared-module/videocore/lvgl/VideoBuffer.c +msgid "video format must be 16, 24 or 32 bits per pixel" msgstr "" -#: py/compile.c -msgid "unknown type" -msgstr "neznámý typ" +#: supervisor/shared/bluetooth/bluetooth.c +msgid "Reconnecting" +msgstr "Opětovné připojování" -#: py/compile.c -msgid "unknown type '%q'" -msgstr "neznámý typ '%q'" +#: supervisor/shared/bluetooth/bluetooth.c +msgid "Ok" +msgstr "Ok" -#: py/objstr.c -#, c-format -msgid "unmatched '%c' in format" -msgstr "neshoduje se '%c' ve formátu" +#: supervisor/shared/bluetooth/bluetooth.c +msgid "Off" +msgstr "Vypnuto" -#: py/objtype.c py/runtime.c -msgid "unreadable attribute" +#: supervisor/shared/micropython.c +msgid "[truncated due to length]" +msgstr "[zkráceno kvůli délce]" + +#: supervisor/shared/safe_mode.c +msgid "" +"\n" +"You are in safe mode because:\n" msgstr "" +"\n" +"Jste v bezpečnostním režimu z důvodu:\n" -#: shared-bindings/displayio/TileGrid.c shared-bindings/vectorio/VectorShape.c -msgid "unsupported %q type" -msgstr "nepodporovaný typ% q" +#: supervisor/shared/safe_mode.c +msgid "Power dipped. Make sure you are providing enough power." +msgstr "Pokles napájení. Zkontroluj, zda je k dispozici dostatečné napájení." -#: py/emitinlinethumb.c -#, c-format -msgid "unsupported Thumb instruction '%s' with %d arguments" -msgstr "" +#: supervisor/shared/safe_mode.c +msgid "You pressed the BOOT button at start up" +msgstr "Při spuštění jsi stiskl tlačítko BOOT" -#: py/emitinlinextensa.c -#, c-format -msgid "unsupported Xtensa instruction '%s' with %d arguments" -msgstr "" +#: supervisor/shared/safe_mode.c +msgid "You pressed the reset button during boot." +msgstr "Při spuštění jsi stiskl tlačítko reset." -#: shared-module/bitmapfilter/__init__.c -msgid "unsupported bitmap depth" -msgstr "" +#: supervisor/shared/safe_mode.c +msgid "CIRCUITPY drive could not be found or created." +msgstr "Disk CIRCUITPY nelze nalézt nebo vytvořit." -#: shared-module/gifio/GifWriter.c -msgid "unsupported colorspace for GifWriter" -msgstr "" +#: supervisor/shared/safe_mode.c +msgid "The `microcontroller` module was used to boot into safe mode." +msgstr "Modul `microcontroller` byl použit pro spuštění do nouzového režimu." -#: shared-bindings/bitmaptools/__init__.c -msgid "unsupported colorspace for dither" -msgstr "" +#: supervisor/shared/safe_mode.c +msgid "Error in safemode.py." +msgstr "Chyba v safemode.py." -#: py/objstr.c -#, c-format -msgid "unsupported format character '%c' (0x%x) at index %d" +#: supervisor/shared/safe_mode.c +msgid "Stack overflow. Increase stack size." msgstr "" -#: py/runtime.c -msgid "unsupported type for %q: '%s'" -msgstr "" +#: supervisor/shared/safe_mode.c +msgid "USB devices need more endpoints than are available." +msgstr "USB zařízení potřebují více endpointů než je k dispozici." -#: py/runtime.c -msgid "unsupported type for operator" -msgstr "" +#: supervisor/shared/safe_mode.c +msgid "USB devices specify too many interface names." +msgstr "USB zařízení používají příliš mnoho názvů rozhraní." -#: py/runtime.c -msgid "unsupported types for %q: '%q', '%q'" -msgstr "" +#: supervisor/shared/safe_mode.c +msgid "Boot device must be first (interface #0)." +msgstr "Bootovací zařízení musí být první (rozhraní #0)." -#: extmod/ulab/code/numpy/io/io.c -msgid "usecols is too high" -msgstr "" +#: supervisor/shared/safe_mode.c +msgid "Internal watchdog timer expired." +msgstr "Interní watchdog timer expiroval." -#: extmod/ulab/code/numpy/io/io.c -msgid "usecols keyword must be specified" -msgstr "" +#: supervisor/shared/safe_mode.c +msgid "CircuitPython core code crashed hard. Whoops!\n" +msgstr "Jádro kódu CircuitPython tvrdě havarovalo. Jejda!\n" -#: py/objint.c -#, c-format -msgid "value must fit in %d byte(s)" -msgstr "" +#: supervisor/shared/safe_mode.c +msgid "Heap allocation when VM not running." +msgstr "Alokace heapu při neběžícím VM." -#: shared-bindings/bitmaptools/__init__.c -msgid "value out of range of target" +#: supervisor/shared/safe_mode.c +msgid "Failed to write internal flash." +msgstr "Nepodařilo se zapsat do interní paměti." + +#: supervisor/shared/safe_mode.c +msgid "Hard fault: memory access or instruction error." +msgstr "Fatální chyba: přístup k paměti nebo chyba instrukce." + +#: supervisor/shared/safe_mode.c +msgid "Interrupt error." +msgstr "Chyba přerušení." + +#: supervisor/shared/safe_mode.c +msgid "LVGL ran out of memory." msgstr "" -#: extmod/moddeflate.c -msgid "wbits" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "NLR skok selhal. Pravděpodobně poškozením paměti." + +#: supervisor/shared/safe_mode.c +msgid "Unable to allocate to the heap." msgstr "" -#: shared-bindings/bitmapfilter/__init__.c +#: supervisor/shared/safe_mode.c +msgid "Third-party firmware fatal error." +msgstr "Fatální chyby firmware třetí strany." + +#: supervisor/shared/safe_mode.c msgid "" -"weights must be a sequence with an odd square number of elements (usually 9 " -"or 25)" +"\n" +"Please file an issue with your program at github.com/adafruit/circuitpython/" +"issues." msgstr "" +"\n" +"Prosím, založte issue s vaším programem na github.com/adafruit/circuitpython/" +"issues." -#: shared-bindings/bitmapfilter/__init__.c -msgid "weights must be an object of type %q, %q, %q, or %q, not %q " +#: supervisor/shared/safe_mode.c +msgid "" +"\n" +"Press reset to exit safe mode.\n" msgstr "" +"\n" +"Stiskněte reset pro ukončení nouzového režimu.\n" -#: shared-bindings/is31fl3741/FrameBuffer.c -msgid "width must be greater than zero" -msgstr "" +#: supervisor/shared/settings.c +#, c-format +msgid "An error occurred while retrieving '%s':\n" +msgstr "Došlo k chybě při načítání '%s'\n" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/raspberrypi/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "wifi is not enabled" -msgstr "" +#: supervisor/shared/settings.c +msgid "Invalid unicode escape" +msgstr "Neplatná unicode escape sekvence" -#: ports/raspberrypi/common-hal/wifi/Monitor.c -msgid "wifi.Monitor not available" -msgstr "wifi.Monitor není dostupný" +#: supervisor/shared/web_workflow/web_workflow.c +msgid "Wi-Fi: " +msgstr "Wi-Fi: " -#: shared-bindings/_bleio/Adapter.c -msgid "window must be <= interval" -msgstr "" +#: supervisor/shared/web_workflow/web_workflow.c +msgid "off" +msgstr "vypnuto" -#: extmod/ulab/code/numpy/numerical.c -msgid "wrong axis index" -msgstr "" +#: supervisor/shared/web_workflow/web_workflow.c +msgid "No IP" +msgstr "Není IP" -#: extmod/ulab/code/numpy/create.c -msgid "wrong axis specified" -msgstr "" +#~ msgid "Too many display busses; forgot displayio.release_displays() ?" +#~ msgstr "" +#~ "Příliš mnoho sběrnic displaye; nezapomněl si na " +#~ "displayio.release_displays()?" -#: extmod/ulab/code/numpy/io/io.c -msgid "wrong dtype" -msgstr "špatný dtype" +#~ msgid "invalid key" +#~ msgstr "špatný klíč" -#: extmod/ulab/code/numpy/transform.c -msgid "wrong index type" -msgstr "špatný typ indexu" +#, c-format +#~ msgid "Unknown system firmware error at %s:%d: %d" +#~ msgstr "Neznámá chyba firmwaru na %s:%d: %d" -#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/numpy/create.c -#: extmod/ulab/code/numpy/io/io.c extmod/ulab/code/numpy/transform.c -#: extmod/ulab/code/numpy/vector.c -msgid "wrong input type" -msgstr "" +#, c-format +#~ msgid "Unknown system firmware error: %d" +#~ msgstr "Neznámá chyba firmwaru: %d" -#: extmod/ulab/code/numpy/transform.c -msgid "wrong length of condition array" -msgstr "" +#, c-format +#~ msgid "Unknown BLE error at %s:%d: %d" +#~ msgstr "Neznámá chyba BLE na %s:%d: %d" -#: extmod/ulab/code/numpy/transform.c -msgid "wrong length of index array" -msgstr "" +#, c-format +#~ msgid "Unknown BLE error: %d" +#~ msgstr "Neznámá chyba BLE: %d" -#: extmod/ulab/code/numpy/create.c py/objarray.c py/objstr.c -msgid "wrong number of arguments" -msgstr "" +#~ msgid "%q out of bounds" +#~ msgstr "%q je mimo hranice" -#: py/runtime.c -msgid "wrong number of values to unpack" -msgstr "" +#~ msgid "asm overflow" +#~ msgstr "přetečení v asm" -#: extmod/ulab/code/numpy/vector.c -msgid "wrong output type" -msgstr "" +#, c-format +#~ msgid "Buffer + offset too small %d %d %d" +#~ msgstr "Vyrovnávací paměť + offset je příliš malý %d %d %d" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "zi must be an ndarray" -msgstr "" +#~ msgid "Byte buffer must be 16 bytes." +#~ msgstr "Buffer musí být dlouhý 16 bajtů." -#: extmod/ulab/code/scipy/signal/signal.c -msgid "zi must be of float type" -msgstr "" +#~ msgid "UUID integer value must be 0-0xffff" +#~ msgstr "UUID integer musí být 0-0xffff" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "zi must be of shape (n_section, 2)" -msgstr "" +#~ msgid "initial_value length is wrong" +#~ msgstr "délka initial_value je chybná" + +#, c-format +#~ msgid "Invalid byte %.*s" +#~ msgstr "Špatný byte %.*s" + +#~ msgid "Key not found" +#~ msgstr "Klíč nenalezen" + +#, c-format +#~ msgid "%%c requires int or char" +#~ msgstr "%%c vyžaduje int nebo char" + +#~ msgid "'%q' object is not callable" +#~ msgstr "Objekt '%q' nelze zavolat" + +#~ msgid "raw f-strings are not supported" +#~ msgstr "surové f-stringy nesjou podporované" + +#~ msgid "Unsupported format" +#~ msgstr "Nepodporovaný formát" + +#~ msgid "Wifi is not enabled" +#~ msgstr "Wifi není povoleno" + +#~ msgid "Cannot remount '/' when visible via USB." +#~ msgstr "Není možné znovu připojit '/', pokud je viditelné pomocí USB." #~ msgid "Data chunk must follow fmt chunk" #~ msgstr "Datový blok musí následovat fmt blok" @@ -4665,7 +5384,7 @@ msgstr "" #~ msgid "'continue' outside loop" #~ msgstr "'continue' je volán mimo cyklus" -#~ msgid "'coroutine' object is not an iterator" +#~ msgid "'coroutine' object isn't an iterator" #~ msgstr "Objekt 'coroutine' není iterátor" #~ msgid "64 bit types" @@ -4725,8 +5444,8 @@ msgstr "" #~ msgstr "IV musí být dlouhé %d bajtů" #~ msgid "" -#~ "Incompatible .mpy file. Please update all .mpy files. See http://adafru." -#~ "it/mpy-update for more info." +#~ "Incompatible .mpy file. Please update all .mpy files. See http://" +#~ "adafru.it/mpy-update for more info." #~ msgstr "" #~ "Nekompatibilní soubor .mpy. Aktualizujte prosím všechny soubory .mpy. " #~ "Další informace naleznete na adrese http://adafru.it/mpy-update." diff --git a/locale/de_DE.po b/locale/de_DE.po index 749ba35fd3d..1ac8df55314 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: 2024-12-15 14:00+0000\n" -"Last-Translator: Exp3rt \n" +"PO-Revision-Date: 2025-06-29 13:01+0000\n" +"Last-Translator: MAE \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 5.9-rc\n" +"X-Generator: Weblate 5.13-dev\n" #: main.c msgid "" @@ -94,7 +94,7 @@ msgstr "" msgid "%q and %q contain duplicate pins" msgstr "%q und %q enthalten doppelte Pins" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: shared-bindings/audioio/AudioOut.c msgid "%q and %q must be different" msgstr "%q und %q müssen unterschiedlich sein" @@ -115,6 +115,10 @@ msgstr "%q enthält doppelte Pins" msgid "%q failure: %d" msgstr "%q Fehler: %d" +#: shared-module/audiodelays/MultiTapDelay.c +msgid "%q in %q must be of type %q or %q, not %q" +msgstr "%q in %q muss vom Typ %q oder %q sein, nicht %q" + #: py/argcheck.c shared-module/audiofilters/Filter.c msgid "%q in %q must be of type %q, not %q" msgstr "%q in %q muss von Typ %q sein, nicht %q" @@ -167,7 +171,7 @@ msgstr "%q länge muss kleiner oder gleich %d sein" msgid "%q length must be >= %d" msgstr "%q länge muss größer oder gleich %d sein" -#: py/modsys.c py/objmodule.c py/runtime.c +#: py/modsys.c py/runtime.c msgid "%q moved from %q to %q" msgstr "%q von %q nach %q versetzt" @@ -229,7 +233,7 @@ msgstr "%q muss ein Vielfaches von 8 sein." #: shared-bindings/bitmapfilter/__init__.c shared-bindings/canio/CAN.c #: shared-bindings/digitalio/Pull.c shared-bindings/supervisor/__init__.c #: shared-module/audiofilters/Filter.c shared-module/displayio/__init__.c -#: shared-module/synthio/Biquad.c shared-module/synthio/Synthesizer.c +#: shared-module/synthio/Synthesizer.c msgid "%q must be of type %q or %q, not %q" msgstr "%q muss von Typ %q oder %q sein, nicht %q" @@ -238,6 +242,7 @@ msgid "%q must be of type %q, %q, or %q, not %q" msgstr "%q muss vom Typ %q, %q oder %q sein, und nicht %q" #: py/argcheck.c py/runtime.c shared-bindings/bitmapfilter/__init__.c +#: shared-module/audiodelays/MultiTapDelay.c shared-module/synthio/Note.c #: shared-module/synthio/__init__.c msgid "%q must be of type %q, not %q" msgstr "%q muss von Typ %q sein, nicht %q" @@ -299,7 +304,7 @@ msgstr "%q[%u] schiebt mehr Bits raus als Pins vorhanden sind" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "%q[%u] uses extra pin" -msgstr "" +msgstr "%q[%u] verwendet zusätzlichen Pin" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "%q[%u] waits on input outside of count" @@ -319,7 +324,7 @@ msgid "'%q' object does not support '%q'" msgstr "'%q' Objekt unterstützt '%q' nicht" #: py/runtime.c -msgid "'%q' object is not an iterator" +msgid "'%q' object isn't an iterator" msgstr "'%q' Objekt ist kein Iterator" #: py/objtype.c py/runtime.c shared-module/atexit/__init__.c @@ -327,7 +332,7 @@ msgid "'%q' object is not callable" msgstr "'%q' Objekt ist kein callable" #: py/runtime.c -msgid "'%q' object is not iterable" +msgid "'%q' object isn't iterable" msgstr "'%q' Objekt ist nicht iterierbar" #: py/emitinlinethumb.c py/emitinlinextensa.c @@ -490,7 +495,7 @@ msgstr "Adressbereich nicht erlaubt" #: shared-bindings/memorymap/AddressRange.c msgid "Address range wraps around" -msgstr "" +msgstr "Der Adressbereich umfasst folgende Bereiche" #: ports/espressif/common-hal/canio/CAN.c msgid "All CAN peripherals are in use" @@ -568,7 +573,7 @@ msgstr "All-Matchers-Listener bereits vorhanden" #: ports/espressif/common-hal/_bleio/__init__.c msgid "Already in progress" -msgstr "" +msgstr "Bereits in Arbeit" #: ports/espressif/bindings/espnow/ESPNow.c #: ports/espressif/common-hal/espulp/ULP.c @@ -608,7 +613,7 @@ msgstr "Array-Werte sollten aus Einzelbytes bestehen." #: ports/atmel-samd/common-hal/spitarget/SPITarget.c msgid "Async SPI transfer in progress on this bus, keep awaiting." -msgstr "" +msgstr "Asynchroner SPI-Transfer auf diesem Bus im Gange, warten Sie weiter." #: shared-module/memorymonitor/AllocationAlarm.c #, c-format @@ -622,7 +627,7 @@ msgstr "Audio-Konvertierung nicht implementiert" #: ports/raspberrypi/common-hal/audiobusio/I2SOut.c #: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "Audio source error" -msgstr "" +msgstr "Audioquellenfehler" #: shared-bindings/wifi/Radio.c msgid "AuthMode.OPEN is not used with password" @@ -655,7 +660,7 @@ msgstr "Unterhalb der minimalen Frame Rate" #: ports/raspberrypi/common-hal/audiobusio/I2SOut.c msgid "Bit clock and word select must be sequential GPIO pins" -msgstr "" +msgstr "Bittakt und Wortauswahl müssen aufeinanderfolgende GPIO-Pins sein" #: shared-bindings/bitmaptools/__init__.c msgid "Bitmap size and bits per value must match" @@ -762,6 +767,8 @@ msgstr "Kann nur auf zwei Pins Alarm als low aus Deep Sleep auslösen." #: ports/espressif/common-hal/audioio/AudioOut.c msgid "Can't construct AudioOut because continuous channel already open" msgstr "" +"AudioOut kann nicht erstellt werden, da ein kontinuierlicher Kanal bereits " +"geöffnet ist" #: ports/espressif/common-hal/_bleio/Characteristic.c #: ports/nordic/common-hal/_bleio/Characteristic.c @@ -809,8 +816,9 @@ msgid "Cannot record to a file" msgstr "Aufnahme in eine Datei nicht möglich" #: shared-module/storage/__init__.c -msgid "Cannot remount '/' when visible via USB." -msgstr "'/' kann nicht wiedereingehängt werden, wenn per USB sichtbar." +msgid "Cannot remount path when visible via USB." +msgstr "" +"Der Pfad kann nicht neu gemountet werden, wenn er über USB sichtbar ist." #: shared-bindings/digitalio/DigitalInOut.c msgid "Cannot set value when direction is input." @@ -827,7 +835,7 @@ msgstr "Slice kann keine sub-klasse sein" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "Cannot use GPIO0..15 together with GPIO32..47" -msgstr "" +msgstr "GPIO0..15 kann nicht zusammen mit GPIO32..47 verwendet werden" #: ports/nordic/common-hal/alarm/pin/PinAlarm.c msgid "Cannot wake on pin edge, only level" @@ -865,6 +873,10 @@ msgstr "Koordinaten-Arrays haben unterschiedliche Längen" msgid "Coordinate arrays types have different sizes" msgstr "Typen der Koordinaten-Arrays haben unterschiedliche Längen" +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "Could not publish to ROS topic" +msgstr "Kann nicht im ROS-Thema veröffentlicht werden" + #: shared-bindings/_bleio/Adapter.c msgid "Could not set address" msgstr "Konnte Adresse nicht setzen" @@ -877,6 +889,11 @@ msgstr "Interrupt konnte nicht gestartet werden, RX beschäftigt" msgid "Couldn't allocate decoder" msgstr "Decoder konnte nicht zugeordnet werden" +#: ports/espressif/common-hal/rclcpy/__init__.c +#, c-format +msgid "Critical ROS failure during soft reboot, reset required: %d" +msgstr "Kritischer ROS-Fehler beim Soft-Reboot, Reset erforderlich: %d" + #: ports/stm/common-hal/analogio/AnalogOut.c msgid "DAC Channel Init Error" msgstr "DAC-Kanal-Initialisierungsfehler" @@ -995,12 +1012,14 @@ msgstr "Mutex konnte nicht akquiriert werden. Status: 0x%04x" #: ports/raspberrypi/common-hal/mdns/Server.c msgid "Failed to add service TXT record" -msgstr "" +msgstr "Fehler beim Hinzufügen des TXT-Diensteintrags" #: shared-bindings/mdns/Server.c msgid "" "Failed to add service TXT record; non-string or bytes found in txt_records" msgstr "" +"Fehler beim Hinzufügen des TXT-Diensteintrags; Nicht-Zeichenfolge oder Bytes " +"in txt_records gefunden" #: shared-module/rgbmatrix/RGBMatrix.c msgid "Failed to allocate %q buffer" @@ -1030,22 +1049,24 @@ msgstr "Verbindung nicht erfolgreich: timeout" #: ports/espressif/common-hal/audioio/AudioOut.c msgid "Failed to create continuous channels: invalid arg" msgstr "" +"Kontinuierliche Kanäle konnten nicht erstellt werden: ungültiges Argument" #: ports/espressif/common-hal/audioio/AudioOut.c msgid "Failed to create continuous channels: invalid state" msgstr "" +"Kontinuierliche Kanäle konnten nicht erstellt werden: ungültiger Status" #: ports/espressif/common-hal/audioio/AudioOut.c msgid "Failed to create continuous channels: no mem" -msgstr "" +msgstr "Kontinuierliche Kanäle konnten nicht erstellt werden: kein Speicher" #: ports/espressif/common-hal/audioio/AudioOut.c msgid "Failed to create continuous channels: not found" -msgstr "" +msgstr "Kontinuierliche Kanäle konnten nicht erstellt werden: nicht gefunden" #: ports/espressif/common-hal/audioio/AudioOut.c msgid "Failed to enable continuous" -msgstr "" +msgstr "Kontinuierliche Aktivierung fehlgeschlagen" #: shared-module/audiomp3/MP3Decoder.c msgid "Failed to parse MP3 file" @@ -1053,7 +1074,7 @@ msgstr "MP3-Datei konnte nicht analysiert werden" #: ports/espressif/common-hal/audioio/AudioOut.c msgid "Failed to register continuous events callback" -msgstr "" +msgstr "Rückruf für kontinuierliche Ereignisse konnte nicht registriert werden" #: ports/nordic/sd_mutex.c #, c-format @@ -1062,11 +1083,11 @@ msgstr "Mutex konnte nicht freigegeben werden. Status: 0x%04x" #: ports/zephyr-cp/common-hal/wifi/Radio.c msgid "Failed to set hostname" -msgstr "" +msgstr "Hostname konnte nicht gesetzt werden" #: ports/espressif/common-hal/audioio/AudioOut.c msgid "Failed to start async audio" -msgstr "" +msgstr "Start von asynchronem Audio fehlgeschlagen" #: supervisor/shared/safe_mode.c msgid "Failed to write internal flash." @@ -1076,6 +1097,7 @@ msgstr "Interner Flash konnte nicht geschrieben werden." msgid "File exists" msgstr "Datei existiert" +#: shared-bindings/supervisor/__init__.c shared-module/lvfontio/OnDiskFont.c #: shared-module/os/getenv.c msgid "File not found" msgstr "Datei nicht gefunden" @@ -1107,7 +1129,7 @@ msgstr "Für den L8-Farbraum muss die Eingabe-Bitmap 8 Bit pro Pixel aufweisen" msgid "For RGB colorspaces, input bitmap must have 16 bits per pixel" msgstr "Für RGB-Farbräume muss die Eingabe-Bitmap 16 Bit pro Pixel haben" -#: ports/cxd56/common-hal/camera/Camera.c +#: ports/cxd56/common-hal/camera/Camera.c shared-module/audiocore/WaveFile.c msgid "Format not supported" msgstr "Format nicht unterstützt" @@ -1218,7 +1240,7 @@ msgstr "Unzureichender Speicherpool für das Bild" #: shared-module/jpegio/JpegDecoder.c msgid "Insufficient stream input buffer" -msgstr "" +msgstr "Unzureichender Stream-Eingabepuffer" #: ports/espressif/common-hal/wifi/Radio.c #: ports/zephyr-cp/common-hal/wifi/Radio.c @@ -1277,7 +1299,9 @@ msgstr "Unterbrochen durch Ausgabefunktion" #: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c py/argcheck.c #: shared-bindings/digitalio/DigitalInOut.c #: shared-bindings/epaperdisplay/EPaperDisplay.c shared-bindings/pwmio/PWMOut.c +#: shared-bindings/supervisor/__init__.c #: shared-module/aurora_epaper/aurora_framebuffer.c +#: shared-module/lvfontio/OnDiskFont.c msgid "Invalid %q" msgstr "Ungültiger %q" @@ -1310,6 +1334,10 @@ msgstr "Ungültige BSSID" msgid "Invalid MAC address" msgstr "Ungültige MAC-Adresse" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "Invalid ROS domain ID" +msgstr "Ungültige ROS-Domain ID" + #: ports/espressif/common-hal/espidf/__init__.c py/moderrno.c msgid "Invalid argument" msgstr "Ungültiges Argument" @@ -1389,6 +1417,8 @@ msgstr "Ebene muss eine Gruppe oder eine TileGrid Subklasse sein" #: shared-bindings/audiocore/RawSample.c msgid "Length of %q must be an even multiple of channel_count * type_size" msgstr "" +"Die Länge von %q muss ein gerades Vielfaches von channel_count * type_size " +"sein" #: ports/espressif/common-hal/espidf/__init__.c msgid "MAC address was invalid" @@ -1399,6 +1429,11 @@ msgstr "MAC Adresse war ungültig" msgid "MITM security not supported" msgstr "MITM-Sicherheit wird nicht unterstützt" +#: ports/stm/common-hal/sdioio/SDCard.c +#, c-format +msgid "MMC/SDIO Clock Error %x" +msgstr "MMC/SDIO-Taktfehler %x" + #: shared-bindings/is31fl3741/IS31FL3741.c msgid "Mapping must be a tuple" msgstr "Zuordnung muss ein Tupel sein" @@ -1585,6 +1620,10 @@ msgstr "Kein Pull-up gefunden an SDA oder SCL; Verkabelung prüfen" msgid "No pulldown on pin; 1Mohm recommended" msgstr "Kein Pulldown-Widerstand am Pin; 1 MOhm wird vorgeschlagen" +#: shared-module/touchio/TouchIn.c +msgid "No pullup on pin; 1Mohm recommended" +msgstr "Kein Pullup-Widerstand am Pin; 1Mohm wird vorgeschlagen" + #: py/moderrno.c msgid "No space left on device" msgstr "Kein Speicherplatz mehr verfügbar auf dem Gerät" @@ -1632,7 +1671,7 @@ msgstr "Nicht unterstützter JPEG-Standard" #: ports/espressif/common-hal/sdioio/SDCard.c #, c-format msgid "Number of data_pins must be %d or %d, not %d" -msgstr "" +msgstr "Die Anzahl der data_pins muss %d oder %d sein, nicht %d" #: shared-bindings/util.c msgid "" @@ -1761,6 +1800,7 @@ msgstr "PWM-Stück-Kanal A wird bereits verwendet" #: shared-bindings/spitarget/SPITarget.c msgid "Packet buffers for an SPI transfer must have the same length." msgstr "" +"Die Paketpuffer für eine SPI-Übertragung müssen die gleiche Länge haben." #: shared-module/jpegio/JpegDecoder.c msgid "Parameter error" @@ -1867,6 +1907,10 @@ msgstr "Programm-Größe ist ungültig" msgid "Program too long" msgstr "Programm zu lang" +#: shared-bindings/rclcpy/Publisher.c +msgid "Publishers can only be created from a parent node" +msgstr "Herausgeber können nur aus einem übergeordneten Knoten erstellt werden" + #: shared-bindings/digitalio/DigitalInOut.c msgid "Pull not used when direction is output." msgstr "Pull wird nicht verwendet, wenn die Richtung output ist." @@ -1887,6 +1931,26 @@ msgstr "RNG DeInit-Fehler" msgid "RNG Init Error" msgstr "RNG-Init-Fehler" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS failed to initialize. Is agent connected?" +msgstr "ROS konnte nicht initialisiert werden. Ist der Agent verbunden?" + +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS internal setup failure" +msgstr "ROS interner Setup-Fehler" + +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS memory allocator failure" +msgstr "ROS-Speicherzuweisungsfehler" + +#: ports/espressif/common-hal/rclcpy/Node.c +msgid "ROS node failed to initialize" +msgstr "ROS-Knoten konnte nicht initialisiert werden" + +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "ROS topic failed to initialize" +msgstr "ROS-Thema konnte nicht initialisiert werden" + #: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c #: ports/nordic/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c msgid "RS485" @@ -1969,7 +2033,7 @@ msgstr "SDIO GetCardInfo-Fehler %d" #: ports/stm/common-hal/sdioio/SDCard.c #, c-format msgid "SDIO Init Error %x" -msgstr "" +msgstr "SDIO-Init-Fehler %x" #: ports/espressif/common-hal/busio/SPI.c msgid "SPI configuration failed" @@ -2018,6 +2082,7 @@ msgstr "Slice und Wert (value) haben unterschiedliche Längen." #: shared-bindings/displayio/TileGrid.c #: shared-bindings/memorymonitor/AllocationSize.c #: shared-bindings/pulseio/PulseIn.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c msgid "Slices not supported" msgstr "Slices werden nicht unterstützt" @@ -2068,7 +2133,7 @@ msgstr "Die Länge von rgb_pins muss 6, 12, 18, 24 oder 30 betragen" #: shared-module/audiocore/__init__.c msgid "The sample's %q does not match" -msgstr "" +msgstr "Der %q-Wert der Probe stimmt nicht überein" #: supervisor/shared/safe_mode.c msgid "Third-party firmware fatal error." @@ -2090,7 +2155,9 @@ msgstr "" msgid "Tile height must exactly divide bitmap height" msgstr "Die Kachelhöhe muss die Bitmaphöhe genau teilen" -#: shared-bindings/displayio/TileGrid.c shared-module/displayio/TileGrid.c +#: shared-bindings/displayio/TileGrid.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-module/displayio/TileGrid.c msgid "Tile index out of bounds" msgstr "Kachelindex außerhalb der Grenzen" @@ -2098,6 +2165,10 @@ msgstr "Kachelindex außerhalb der Grenzen" msgid "Tile width must exactly divide bitmap width" msgstr "Die Kachelbreite muss die Bitmap-Breite genau teilen" +#: shared-module/tilepalettemapper/TilePaletteMapper.c +msgid "TilePaletteMapper may only be bound to a TileGrid once" +msgstr "TilePaletteMapper darf nur einmal an ein TileGrid gebunden werden" + #: shared-bindings/alarm/time/TimeAlarm.c msgid "Time is in the past." msgstr "Zeit liegt in der Vergangenheit." @@ -2209,7 +2280,7 @@ msgstr "Konnte keine Buffer für Vorzeichenumwandlung allozieren" #: supervisor/shared/safe_mode.c msgid "Unable to allocate to the heap." -msgstr "" +msgstr "Die Zuweisung zum Heap ist nicht möglich." #: ports/espressif/common-hal/busio/I2C.c msgid "Unable to create lock" @@ -2232,6 +2303,8 @@ msgstr "Konnte Farbpalettendaten nicht lesen" #: ports/mimxrt10xx/common-hal/canio/CAN.c msgid "Unable to send CAN Message: all Tx message buffers are busy" msgstr "" +"CAN-Nachricht kann nicht gesendet werden: alle Sende-Nachrichtenpuffer sind " +"belegt" #: ports/espressif/common-hal/mdns/Server.c #: ports/raspberrypi/common-hal/mdns/Server.c @@ -2329,10 +2402,6 @@ msgstr "Nicht unterstützter Farbraum" msgid "Unsupported display bus type" msgstr "Nicht unterstützter display bus type" -#: shared-module/audiocore/WaveFile.c -msgid "Unsupported format" -msgstr "Nicht unterstütztes Format" - #: shared-bindings/hashlib/__init__.c msgid "Unsupported hash algorithm" msgstr "Hash Algorithmus wird nicht unterstützt" @@ -2340,7 +2409,7 @@ msgstr "Hash Algorithmus wird nicht unterstützt" #: ports/espressif/common-hal/socketpool/Socket.c #: ports/zephyr-cp/common-hal/socketpool/Socket.c msgid "Unsupported socket type" -msgstr "" +msgstr "Nicht unterstützter Sockeltyp" #: ports/espressif/common-hal/_bleio/Adapter.c #: ports/espressif/common-hal/dualbank/__init__.c @@ -2397,9 +2466,11 @@ msgstr "" msgid "Wi-Fi: " msgstr "Wi-Fi: " +#: ports/espressif/common-hal/wifi/Radio.c #: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "Wifi is not enabled" -msgstr "WLAN ist nicht aktiviert" +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "WiFi is not enabled" +msgstr "WiFi ist nicht aktiviert" #: main.c msgid "Woken up by alarm.\n" @@ -2498,7 +2569,7 @@ msgstr "addresses ist leer" #: ports/espressif/common-hal/audioio/AudioOut.c msgid "already playing" -msgstr "" +msgstr "spielt bereits" #: py/compile.c msgid "annotation must be an identifier" @@ -2527,6 +2598,7 @@ msgstr "argsort ist für flattened Arrays nicht implementiert" #: extmod/ulab/code/numpy/random/random.c msgid "argument must be None, an integer or a tuple of integers" msgstr "" +"Das Argument muss None, eine Ganzzahl oder ein Tupel von Ganzzahlen sein" #: py/compile.c msgid "argument name reused" @@ -2580,7 +2652,7 @@ msgstr "Attribute werden nicht unterstützt" #: ports/espressif/common-hal/audioio/AudioOut.c msgid "audio format not supported" -msgstr "" +msgstr "Audioformat wird nicht unterstützt" #: extmod/ulab/code/ulab_tools.c msgid "axis is out of bounds" @@ -2620,7 +2692,7 @@ msgstr "Der binäre Operator %q ist nicht implementiert" #: ports/espressif/common-hal/audiobusio/PDMIn.c msgid "bit_depth must be 8, 16, 24, or 32." -msgstr "" +msgstr "bit_depth muss 8, 16, 24 oder 32 sein." #: shared-module/bitmapfilter/__init__.c msgid "bitmap size and depth must match" @@ -2634,9 +2706,16 @@ msgstr "Bitmap-Größen müssen übereinstimmen" msgid "bits must be 32 or less" msgstr "bits müssen 32 oder kleiner sein" -#: shared-bindings/audiodelays/Echo.c shared-bindings/audiodelays/PitchShift.c +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "bits_per_sample must be 16" +msgstr "bits_per_sample muss 16 sein" + +#: shared-bindings/audiodelays/Chorus.c shared-bindings/audiodelays/Echo.c +#: shared-bindings/audiodelays/MultiTapDelay.c +#: shared-bindings/audiodelays/PitchShift.c #: shared-bindings/audiofilters/Distortion.c -#: shared-bindings/audiofilters/Filter.c shared-bindings/audiomixer/Mixer.c +#: shared-bindings/audiofilters/Filter.c shared-bindings/audiofilters/Phaser.c +#: shared-bindings/audiomixer/Mixer.c msgid "bits_per_sample must be 8 or 16" msgstr "Es müssen 8 oder 16 bits_per_sample sein" @@ -2844,7 +2923,7 @@ msgstr "" #: py/objcomplex.c msgid "can't truncate-divide a complex number" -msgstr "" +msgstr "kann eine komplexe Zahl nicht kürzen und dividieren" #: extmod/modasyncio.c msgid "can't wait" @@ -3188,7 +3267,7 @@ msgid "format" msgstr "Format" #: py/objstr.c -msgid "format requires a dict" +msgid "format needs a dict" msgstr "Format erfordert ein Wörterbuch (dict)" #: py/objdeque.c @@ -3655,7 +3734,7 @@ msgid "must use keyword argument for key function" msgstr "muss Schlüsselwortargument für key function verwenden" #: py/runtime.c -msgid "name '%q' is not defined" +msgid "name '%q' isn't defined" msgstr "Name '%q' ist nirgends definiert worden (Schreibweise kontrollieren)" #: py/runtime.c @@ -3936,7 +4015,7 @@ msgstr "Ausgabe-Array ist zu klein" #: extmod/ulab/code/numpy/random/random.c msgid "out has wrong type" -msgstr "" +msgstr "Ausgabe hat den falschen Typ" #: extmod/ulab/code/numpy/vector.c msgid "out keyword is not supported for complex dtype" @@ -3964,11 +4043,11 @@ msgstr "Außerhalb des Bereichs des Ziels" #: extmod/ulab/code/numpy/random/random.c msgid "output array has wrong type" -msgstr "" +msgstr "Ausgabe-Array hat einen falschen Typ" #: extmod/ulab/code/numpy/random/random.c msgid "output array must be contiguous" -msgstr "" +msgstr "Ausgabe-Array muss zusammenhängend sein" #: py/objint_mpz.c msgid "overflow converting long int to machine word" @@ -4079,6 +4158,10 @@ msgstr "Roll-Argument muss ein ndarray sein" msgid "rsplit(None,n)" msgstr "rsplit(None,n)" +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "samples_signed must be true" +msgstr "samples_signed muss wahr sein" + #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c #: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "sampling rate out of range" @@ -4098,7 +4181,7 @@ msgstr "nicht unterstützt" #: extmod/ulab/code/numpy/random/random.c msgid "shape must be None, and integer or a tuple of integers" -msgstr "" +msgstr "Form muss Keine, eine Ganzzahl oder ein Tupel von Ganzenahlen sein" #: extmod/ulab/code/ndarray.c msgid "shape must be integer or tuple of integers" @@ -4122,7 +4205,7 @@ msgstr "Größe ist nur für ndarrays definiert" #: extmod/ulab/code/numpy/random/random.c msgid "size must match out.shape when used together" -msgstr "" +msgstr "size muss bei gemeinsamer Verwendung mit out.shape übereinstimmen" #: py/nativeglue.c msgid "slice unsupported" @@ -4170,7 +4253,7 @@ msgstr "source_bitmap muss value_count von 8 haben" #: extmod/modre.c msgid "splitting with sub-captures" -msgstr "" +msgstr "Aufteilung mit Untererfassungen" #: py/objstr.c msgid "start/end indices" @@ -4211,7 +4294,7 @@ msgstr "Syntaxfehler in JSON" #: extmod/modtime.c msgid "ticks interval overflow" -msgstr "" +msgstr "Ticks Intervallüberlauf" #: ports/nordic/common-hal/watchdog/WatchDogTimer.c msgid "timeout duration exceeded the maximum supported value" @@ -4223,12 +4306,12 @@ msgstr "timeout muss kleiner als 655.35 Sekunden sein" #: ports/raspberrypi/common-hal/floppyio/__init__.c msgid "timeout waiting for flux" -msgstr "" +msgstr "Zeitüberschreitung beim Warten auf Fluss" #: ports/raspberrypi/common-hal/floppyio/__init__.c #: shared-module/floppyio/__init__.c msgid "timeout waiting for index pulse" -msgstr "" +msgstr "Zeitüberschreitung beim Warten auf Indeximpuls" #: shared-module/sdcardio/SDCard.c msgid "timeout waiting for v1 card" @@ -4298,11 +4381,11 @@ msgid "tx and rx cannot both be None" msgstr "tx und rx können nicht beide None sein" #: py/objtype.c -msgid "type '%q' is not an acceptable base type" +msgid "type '%q' isn't an acceptable base type" msgstr "Typ '%q' ist kein akzeptierter Basis-Typ" #: py/objtype.c -msgid "type is not an acceptable base type" +msgid "type isn't an acceptable base type" msgstr "Typ ist kein akzeptierter Basis-Typ" #: py/runtime.c @@ -4366,7 +4449,9 @@ msgstr "'%c' in Format konnte nicht zugeordnet werden" msgid "unreadable attribute" msgstr "nicht lesbares Attribut" -#: shared-bindings/displayio/TileGrid.c shared-bindings/vectorio/VectorShape.c +#: shared-bindings/displayio/TileGrid.c shared-bindings/terminalio/Terminal.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-bindings/vectorio/VectorShape.c msgid "unsupported %q type" msgstr "Nicht unterstützter %q-Typ" @@ -4446,12 +4531,6 @@ msgstr "Gewichte müssen ein Objekt des Typs %q, %q, %q, or %q, not %q sein " msgid "width must be greater than zero" msgstr "Breite muss größer als 0 sein" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/raspberrypi/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "wifi is not enabled" -msgstr "wifi ist nicht aktiviert" - #: ports/raspberrypi/common-hal/wifi/Monitor.c msgid "wifi.Monitor not available" msgstr "wifi.Monitor nicht verfügbar" @@ -4514,6 +4593,18 @@ msgstr "zi muss eine Gleitkommazahl sein" msgid "zi must be of shape (n_section, 2)" msgstr "zi muss die Form (n_section, 2) haben" +#~ msgid "Unsupported format" +#~ msgstr "Nicht unterstütztes Format" + +#~ msgid "Wifi is not enabled" +#~ msgstr "WLAN ist nicht aktiviert" + +#~ msgid "wifi is not enabled" +#~ msgstr "wifi ist nicht aktiviert" + +#~ msgid "Cannot remount '/' when visible via USB." +#~ msgstr "'/' kann nicht wiedereingehängt werden, wenn per USB sichtbar." + #~ msgid "%q must be a %q object, %q, or %q" #~ msgstr "%q muss ein %q Objekt, %q, oder %q sein" @@ -4851,13 +4942,13 @@ msgstr "zi muss die Form (n_section, 2) haben" #~ msgid "'%s' object does not support item deletion" #~ msgstr "'%s' Objekt unterstützt das Löschen von Elementen nicht" -#~ msgid "'%s' object is not an iterator" +#~ msgid "'%s' object isn't an iterator" #~ msgstr "'%s' Objekt ist kein Iterator" #~ msgid "'%s' object is not callable" #~ msgstr "'%s' object ist nicht aufrufbar" -#~ msgid "'%s' object is not iterable" +#~ msgid "'%s' object isn't iterable" #~ msgstr "'%s' Objekt nicht iterierbar" #~ msgid "'%s' object is not subscriptable" @@ -4876,7 +4967,7 @@ msgstr "zi muss die Form (n_section, 2) haben" #~ msgid "'continue' outside loop" #~ msgstr "'continue' außerhalb einer Schleife" -#~ msgid "'coroutine' object is not an iterator" +#~ msgid "'coroutine' object isn't an iterator" #~ msgstr "'coroutine' Objekt ist kein Iterator" #~ msgid "(x,y) integers required" @@ -6246,7 +6337,7 @@ msgstr "zi muss die Form (n_section, 2) haben" #~ msgid "frequency is read-only for this board" #~ msgstr "Frequenz ist für dieses Board schreibgeschützt" -#~ msgid "function does not take keyword arguments" +#~ msgid "function doesn't take keyword arguments" #~ msgstr "Funktion akzeptiert keine Schlüsselwort-Argumente" #~ msgid "function is implemented for scalars and ndarrays only" @@ -6360,7 +6451,7 @@ msgstr "zi muss die Form (n_section, 2) haben" #~ msgid "name must be a string" #~ msgstr "name muss ein String sein" -#~ msgid "name reused for argument" +#~ msgid "argument name reused" #~ msgstr "Name für Argumente wiederverwendet" #~ msgid "no available NIC" diff --git a/locale/el.po b/locale/el.po index 578a5f3eae2..4463f16a6f7 100644 --- a/locale/el.po +++ b/locale/el.po @@ -8,2348 +8,2684 @@ 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: 2023-12-04 01:08+0000\n" -"Last-Translator: Bill Sideris \n" +"PO-Revision-Date: 2025-06-29 13:02+0000\n" +"Last-Translator: MAE \n" "Language-Team: none\n" "Language: el\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 5.3-dev\n" +"X-Generator: Weblate 5.13-dev\n" -#: main.c -msgid "" -"\n" -"Code done running.\n" +#: extmod/modasyncio.c extmod/modheapq.c +msgid "empty heap" msgstr "" -"\n" -"Η εκτέλεση του κώδικα ολοκληρώθηκε.\n" -#: main.c -msgid "" -"\n" -"Code stopped by auto-reload. Reloading soon.\n" +#: extmod/modasyncio.c +msgid "can't cancel self" msgstr "" -"\n" -"Ο κώδικας σταμάτησε λόγω της αυτόματης επαναφόρτωσης. Η επαναφόρτωση θα " -"γίνει σύντομα.\n" -#: supervisor/shared/safe_mode.c -msgid "" -"\n" -"Please file an issue with your program at github.com/adafruit/circuitpython/" -"issues." +#: extmod/modasyncio.c +msgid "can't wait" msgstr "" -"\n" -"Παρακαλώ δημιουργήστε ένα πρόβλημα με το πρόγραμμά σας στο github.com/" -"adafruit/circuitpython/issues." -#: supervisor/shared/safe_mode.c -msgid "" -"\n" -"Press reset to exit safe mode.\n" +#: extmod/modbinascii.c extmod/modhashlib.c py/objarray.c +msgid "a bytes-like object is required" msgstr "" -"\n" -"Πατήστε reset για να βγείτε από την ασφαλή λειτουργία.\n" -#: supervisor/shared/safe_mode.c -msgid "" -"\n" -"You are in safe mode because:\n" +#: extmod/modbinascii.c +msgid "incorrect padding" msgstr "" -"\n" -"Είσαστε τε ασφαλή λειτουργία διότι:\n" - -#: py/obj.c -msgid " File \"%q\"" -msgstr " Αρχείο \"%q\"" - -#: py/obj.c -msgid " File \"%q\", line %d" -msgstr " Αρχείο \"%q\", γραμμή %d" -#: py/builtinhelp.c -msgid " is of type %q\n" -msgstr " είναι τύπου %q\n" +#: extmod/moddeflate.c +msgid "format" +msgstr "" -#: main.c -msgid " not found.\n" -msgstr " δεν βρέθηκε.\n" +#: extmod/moddeflate.c +msgid "wbits" +msgstr "" -#: main.c -msgid " output:\n" -msgstr " έξοδος:\n" +#: extmod/modhashlib.c +msgid "hash is final" +msgstr "" -#: py/objstr.c -#, c-format -msgid "%%c requires int or char" -msgstr "%%c απαιτεί ακέραιο ή χαρακτήρα" +#: extmod/modheapq.c +msgid "heap must be a list" +msgstr "" -#: shared-bindings/rgbmatrix/RGBMatrix.c -#, c-format -msgid "" -"%d address pins, %d rgb pins and %d tiles indicate a height of %d, not %d" +#: extmod/modjson.c +msgid "syntax error in JSON" msgstr "" -"%d pin διεύθυνσης, %d rgb ping και %d πλακίδια αναδεικνύουν ύψος %d, όχι %d" -#: shared-bindings/microcontroller/Pin.c -msgid "%q and %q contain duplicate pins" -msgstr "%q και %q περιέχουν διπλότυπα pins" +#: extmod/modrandom.c +msgid "bits must be 32 or less" +msgstr "" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c -msgid "%q and %q must be different" -msgstr "%q και %q πρεπει να είναι διαφορετικά" +#: extmod/modrandom.c extmod/ulab/code/numpy/random/random.c +msgid "no default seed" +msgstr "" -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -msgid "%q and %q must share a clock unit" +#: extmod/modre.c +msgid "splitting with sub-captures" msgstr "" -#: ports/nordic/common-hal/watchdog/WatchDogTimer.c -msgid "%q cannot be changed once mode is set to %q" +#: extmod/modre.c +msgid "regex too complex" msgstr "" -#: shared-bindings/microcontroller/Pin.c -msgid "%q contains duplicate pins" -msgstr "%q περιέχει διπλότυπα pins" +#: extmod/modre.c +msgid "Error in regex" +msgstr "Σφάλμα σε regex" -#: ports/atmel-samd/common-hal/sdioio/SDCard.c -msgid "%q failure: %d" -msgstr "%q αποτυχία: %d" +#: extmod/modtime.c +msgid "mktime needs a tuple of length 8 or 9" +msgstr "" -#: py/argcheck.c shared-module/audiofilters/Filter.c -msgid "%q in %q must be of type %q, not %q" -msgstr "%q στο %q πρέπει να είναι τύπου %q, όχι %q" +#: extmod/modtime.c +msgid "ticks interval overflow" +msgstr "" -#: ports/espressif/common-hal/espulp/ULP.c -#: ports/mimxrt10xx/common-hal/audiobusio/__init__.c -#: ports/mimxrt10xx/common-hal/usb_host/Port.c -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -#: ports/raspberrypi/common-hal/usb_host/Port.c -#: shared-bindings/digitalio/DigitalInOut.c -#: shared-bindings/microcontroller/Pin.c shared-module/max3421e/Max3421E.c -msgid "%q in use" -msgstr "%q είναι σε χρήση" +#: extmod/modzlib.c +msgid "compression header" +msgstr "" -#: py/objstr.c -msgid "%q index out of range" -msgstr "%q δείκτης εκτός εμβέλειας" +#: extmod/ulab/code/ndarray.c +msgid "data type not understood" +msgstr "" -#: py/obj.c -msgid "%q indices must be integers, not %s" -msgstr "%q δείκτες πρέπει να είναι ακέραιοι, όχι %s" +#: extmod/ulab/code/ndarray.c +msgid "array is too big" +msgstr "" -#: shared-module/bitbangio/SPI.c -msgid "%q init failed" -msgstr "%q εκκίνηση απέτυχε" +#: extmod/ulab/code/ndarray.c +msgid "ndarray length overflows" +msgstr "" -#: ports/espressif/bindings/espnow/Peer.c shared-bindings/dualbank/__init__.c -msgid "%q is %q" -msgstr "%q είναι %q" +#: extmod/ulab/code/ndarray.c +msgid "maximum number of dimensions is " +msgstr "" -#: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "%q is read-only for this board" -msgstr "%q είναι μόνο για ανάγνωση για αυτήν την πλακέτα" +#: extmod/ulab/code/ndarray.c +msgid "cannot convert complex type" +msgstr "" -#: py/argcheck.c shared-bindings/usb_hid/Device.c -msgid "%q length must be %d" -msgstr "%q μήκος πρέπει να είναι %d" +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/create.c +msgid "too many dimensions" +msgstr "" -#: py/argcheck.c -msgid "%q length must be %d-%d" -msgstr "%q μήκος πρέπει να είναι %d-%d" +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/transform.c +msgid "index is out of bounds" +msgstr "" -#: py/argcheck.c -msgid "%q length must be <= %d" -msgstr "%q μήκος πρέπει να είναι <= %d" +#: extmod/ulab/code/ndarray.c +msgid "indices must be integers, slices, or Boolean lists" +msgstr "" -#: py/argcheck.c -msgid "%q length must be >= %d" -msgstr "%q μήκος πρέπει να είναι >= %d" +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/bitwise.c +#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/numpy/vector.c +msgid "operands could not be broadcast together" +msgstr "" -#: py/modsys.c py/objmodule.c py/runtime.c -msgid "%q moved from %q to %q" -msgstr "%q μετακινήθηκε από το %q στο %q" +#: extmod/ulab/code/ndarray.c +msgid "array and index length must be equal" +msgstr "" -#: py/argcheck.c -msgid "%q must be %d" -msgstr "%q πρέπει να είναι %d" +#: extmod/ulab/code/ndarray.c +msgid "cannot convert complex to dtype" +msgstr "" -#: py/argcheck.c shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/displayio/Bitmap.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -#: shared-bindings/is31fl3741/FrameBuffer.c -#: shared-bindings/rgbmatrix/RGBMatrix.c -msgid "%q must be %d-%d" -msgstr "%q πρέπει να είναι %d-%d" +#: extmod/ulab/code/ndarray.c +msgid "operation is implemented for 1D Boolean arrays only" +msgstr "" -#: shared-bindings/busdisplay/BusDisplay.c -msgid "%q must be 1 when %q is True" -msgstr "%q πρέπει να είναι 1 όταν %q είναι True" +#: extmod/ulab/code/ndarray.c +msgid "too many indices" +msgstr "" -#: py/argcheck.c shared-bindings/gifio/GifWriter.c -#: shared-module/gifio/OnDiskGif.c -msgid "%q must be <= %d" -msgstr "%q πρέπει να είναι <= %d" +#: extmod/ulab/code/ndarray.c +msgid "cannot delete array elements" +msgstr "" -#: ports/espressif/common-hal/watchdog/WatchDogTimer.c -msgid "%q must be <= %u" -msgstr "%q πρέπει να είναι <= %u" +#: extmod/ulab/code/ndarray.c +msgid "flattening order must be either 'C', or 'F'" +msgstr "" -#: py/argcheck.c -msgid "%q must be >= %d" -msgstr "%q πρέπει να είναι >= %d" +#: extmod/ulab/code/ndarray.c +msgid "tobytes can be invoked for dense arrays only" +msgstr "" -#: shared-bindings/analogbufio/BufferedIn.c -msgid "%q must be a bytearray or array of type 'H' or 'B'" -msgstr "%q πρέπει να είναι bytearray ή array τύπου 'H' ή 'B'" +#: extmod/ulab/code/ndarray.c +msgid "operation is not supported for given type" +msgstr "" -#: shared-bindings/audiocore/RawSample.c -msgid "%q must be a bytearray or array of type 'h', 'H', 'b', or 'B'" -msgstr "%q πρέπει να είναι bytearray ή array τύπου 'h', 'H', 'b', ή 'B'" +#: extmod/ulab/code/ndarray.c +msgid "keyword argument must be tuple of integers" +msgstr "" -#: shared-bindings/warnings/__init__.c -msgid "%q must be a subclass of %q" -msgstr "%q πρέπει να είναι υποκλάση του %q" +#: extmod/ulab/code/ndarray.c +msgid "too many axes specified" +msgstr "" -#: ports/espressif/common-hal/analogbufio/BufferedIn.c -msgid "%q must be array of type 'H'" -msgstr "%q πρέπει να είναι πίνακας τύπου 'H'" +#: extmod/ulab/code/ndarray.c +msgid "axis index out of bounds" +msgstr "" -#: shared-module/synthio/__init__.c -msgid "%q must be array of type 'h'" -msgstr "%q πρέπει να είναι λίστα τύπου 'h'" +#: extmod/ulab/code/ndarray.c +msgid "repeated indices" +msgstr "" -#: shared-bindings/audiobusio/PDMIn.c -msgid "%q must be multiple of 8." +#: extmod/ulab/code/ndarray.c +msgid "shape must be integer or tuple of integers" msgstr "" -#: ports/raspberrypi/bindings/cyw43/__init__.c py/argcheck.c py/objexcept.c -#: shared-bindings/bitmapfilter/__init__.c shared-bindings/canio/CAN.c -#: shared-bindings/digitalio/Pull.c shared-bindings/supervisor/__init__.c -#: shared-module/audiofilters/Filter.c shared-module/displayio/__init__.c -#: shared-module/synthio/Biquad.c shared-module/synthio/Synthesizer.c -msgid "%q must be of type %q or %q, not %q" -msgstr "%q πρέπει να είναι τύπου %q ή %q, όχι %q" - -#: shared-bindings/jpegio/JpegDecoder.c -msgid "%q must be of type %q, %q, or %q, not %q" +#: extmod/ulab/code/ndarray.c +msgid "can only specify one unknown dimension" msgstr "" -#: py/argcheck.c py/runtime.c shared-bindings/bitmapfilter/__init__.c -#: shared-module/synthio/__init__.c -msgid "%q must be of type %q, not %q" -msgstr "%q πρέπει να είναι τύπου %q, όχι %q" - -#: ports/atmel-samd/common-hal/busio/UART.c -msgid "%q must be power of 2" -msgstr "%q πρέπει να είναι δύναμη του 2" +#: extmod/ulab/code/ndarray.c +msgid "cannot reshape array" +msgstr "" -#: shared-bindings/wifi/Monitor.c -msgid "%q out of bounds" -msgstr "%q εκτός ορίων" +#: extmod/ulab/code/ndarray.c +msgid "cannot assign new shape" +msgstr "" -#: ports/atmel-samd/common-hal/pulseio/PulseIn.c -#: ports/cxd56/common-hal/pulseio/PulseIn.c -#: ports/nordic/common-hal/pulseio/PulseIn.c -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -#: ports/stm/common-hal/pulseio/PulseIn.c py/argcheck.c -#: shared-bindings/canio/Match.c shared-bindings/time/__init__.c -msgid "%q out of range" -msgstr "%q εκτός εμβέλειας" +#: extmod/ulab/code/ndarray.c +msgid "function is defined for ndarrays only" +msgstr "" -#: py/objmodule.c py/runtime.c -msgid "%q renamed %q" -msgstr "%q μεταονομάστηκε σε %q" +#: extmod/ulab/code/ndarray_operators.c +msgid "operation not supported for the input types" +msgstr "" -#: py/objrange.c py/objslice.c shared-bindings/random/__init__.c -msgid "%q step cannot be zero" -msgstr "%q βήμα δεν μπορεί να είναι μηδέν" +#: extmod/ulab/code/ndarray_operators.c +msgid "dtype of int32 is not supported" +msgstr "" -#: shared-module/bitbangio/I2C.c -msgid "%q too long" +#: extmod/ulab/code/ndarray_operators.c +msgid "cannot cast output with casting rule" msgstr "" -#: py/bc.c py/objnamedtuple.c -msgid "%q() takes %d positional arguments but %d were given" -msgstr "%q() παίρνει %d ορίσματα θέσεως αλλά %d δόθηκαν" +#: extmod/ulab/code/ndarray_operators.c +msgid "results cannot be cast to specified type" +msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "%q() without %q()" +#: extmod/ulab/code/numpy/approx.c +msgid "interp is defined for 1D iterables of equal length" msgstr "" -#: shared-bindings/usb_hid/Device.c -msgid "%q, %q, and %q must all be the same length" -msgstr "%q, %q, και %q πρέπει να είναι όλα του ιδίου μήκους" +#: extmod/ulab/code/numpy/approx.c +msgid "trapz is defined for 1D iterables" +msgstr "" -#: py/objint.c shared-bindings/_bleio/Connection.c -#: shared-bindings/storage/__init__.c -msgid "%q=%q" -msgstr "%q=%q" +#: extmod/ulab/code/numpy/approx.c +msgid "trapz is defined for 1D arrays of equal length" +msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "%q[%u] shifts in more bits than pin count" -msgstr "%q[%u] μετατοπίζει σε περισσότερα bits από αριθμό pin" +#: extmod/ulab/code/numpy/bitwise.c +msgid "not supported for input types" +msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "%q[%u] shifts out more bits than pin count" -msgstr "%q[%u] μετατοπίζει από περισσότερα bits από αριθμό pin" +#: extmod/ulab/code/numpy/carray/carray.c +msgid "function is implemented for ndarrays only" +msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "%q[%u] uses extra pin" -msgstr "%q[%u] χρησιμοποιεί παραπάνω pin" +#: extmod/ulab/code/numpy/carray/carray.c +msgid "input must be an ndarray, or a scalar" +msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "%q[%u] waits on input outside of count" +#: extmod/ulab/code/numpy/carray/carray.c +msgid "input must be a 1D ndarray" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -#, c-format -msgid "%s error 0x%x" -msgstr "%s σφάλμα 0x%x" +#: extmod/ulab/code/numpy/carray/carray_tools.c +msgid "not implemented for complex dtype" +msgstr "" -#: py/argcheck.c -msgid "'%q' argument required" -msgstr "'%q' όρισμα απαιτείται" +#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/user/user.c +#: shared-bindings/_eve/__init__.c +msgid "input must be an ndarray" +msgstr "" -#: py/proto.c -msgid "'%q' object does not support '%q'" -msgstr "'%q' αντικείμενο δεν υποστηρίζει '%q'" +#: extmod/ulab/code/numpy/compare.c +msgid "object too deep for desired array" +msgstr "" -#: py/runtime.c -msgid "'%q' object is not an iterator" -msgstr "'%q' αντικείμενο δεν είναι επαναλήπτης" +#: extmod/ulab/code/numpy/compare.c +msgid "cannot cast array data from dtype" +msgstr "" -#: py/objtype.c py/runtime.c shared-module/atexit/__init__.c -msgid "'%q' object is not callable" -msgstr "'%q' αντικείμενο δεν καλείται" +#: extmod/ulab/code/numpy/compare.c +msgid "minlength must not be negative" +msgstr "" -#: py/runtime.c -msgid "'%q' object is not iterable" -msgstr "'%q' αντικείμενο δεν είναι επαναληπτικό" +#: extmod/ulab/code/numpy/compare.c +msgid "the weights and list don't have the same length" +msgstr "" -#: py/emitinlinethumb.c py/emitinlinextensa.c -#, c-format -msgid "'%s' expects a label" -msgstr "'%s' περιμένει μια ετικέτα" +#: extmod/ulab/code/numpy/compare.c +msgid "cannot cast weigths to float" +msgstr "" -#: py/emitinlinethumb.c py/emitinlinextensa.c -#, c-format -msgid "'%s' expects a register" -msgstr "'%s' περιμένει έναν καταχωρητή" +#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/numpy/create.c +#: extmod/ulab/code/numpy/io/io.c extmod/ulab/code/numpy/transform.c +#: extmod/ulab/code/numpy/vector.c +msgid "wrong input type" +msgstr "" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects a special register" -msgstr "'%s' περιμένει έναν ειδικό καταχωρητή" +#: extmod/ulab/code/numpy/create.c +msgid "input argument must be an integer, a tuple, or a list" +msgstr "" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects an FPU register" -msgstr "'%s' περιμένει έναν FPU καταχωρητή" +#: extmod/ulab/code/numpy/create.c py/objarray.c py/objstr.c +msgid "wrong number of arguments" +msgstr "" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects an address of the form [a, b]" -msgstr "'%s' περιμένει μια διεύθυνση της μορφής [a, b]" +#: extmod/ulab/code/numpy/create.c py/objint_longlong.c py/objint_mpz.c +msgid "divide by zero" +msgstr "" -#: py/emitinlinethumb.c py/emitinlinextensa.c -#, c-format -msgid "'%s' expects an integer" -msgstr "'%s' περιμένει έναν ακέραιο" +#: extmod/ulab/code/numpy/create.c +msgid "arange: cannot compute length" +msgstr "" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects at most r%d" -msgstr "'%s' περιμένει το πολύ r%d" +#: extmod/ulab/code/numpy/create.c +msgid "first argument must be a tuple of ndarrays" +msgstr "" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects {r0, r1, ...}" -msgstr "'%s' περιμένει {r0, r1, ...}" +#: extmod/ulab/code/numpy/create.c +msgid "only ndarrays can be concatenated" +msgstr "" -#: py/emitinlinextensa.c -#, c-format -msgid "'%s' integer %d isn't within range %d..%d" -msgstr "'%s' ακέραιος %d δεν είναι μέσα στο επιτρεπτό εύρος %d..%d" +#: extmod/ulab/code/numpy/create.c +msgid "wrong axis specified" +msgstr "" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' integer 0x%x doesn't fit in mask 0x%x" -msgstr "'%s' ακέραιος 0x%x δεν χωράει στην μάσκα 0x%x" +#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c +msgid "input arrays are not compatible" +msgstr "" -#: py/obj.c -#, c-format -msgid "'%s' object doesn't support item assignment" -msgstr "'%s' αντικείμενο δεν υποστηρίζει ορισμό πράγματος" +#: extmod/ulab/code/numpy/create.c +msgid "input must be 1- or 2-d" +msgstr "" -#: py/obj.c -#, c-format -msgid "'%s' object doesn't support item deletion" -msgstr "'%s' αντικείμενο δεν υποστηρίζει διαγραφή πράγματος" +#: extmod/ulab/code/numpy/create.c +msgid "number of points must be at least 2" +msgstr "" -#: py/runtime.c -msgid "'%s' object has no attribute '%q'" -msgstr "'%s' αντικείμενο δεν έχει γνώρισμα '%q'" +#: extmod/ulab/code/numpy/create.c +msgid "indexing should be 'xy' or 'ij'" +msgstr "" -#: py/obj.c -#, c-format -msgid "'%s' object isn't subscriptable" -msgstr "'%s' αντικείμενο δεν είναι subscriptable" +#: extmod/ulab/code/numpy/create.c +msgid "indexing must be 'xy' or 'ij'" +msgstr "" -#: py/objstr.c -msgid "'=' alignment not allowed in string format specifier" -msgstr "Ευθυγράμμιση του '=' δεν επιτρέπεται εντός προσδιοριστή string format" +#: extmod/ulab/code/numpy/create.c +msgid "too many input arrays" +msgstr "" -#: shared-module/struct/__init__.c -msgid "'S' and 'O' are not supported format types" -msgstr "'S' και 'O' δεν είναι υποστηριζόμενοι τύποι format" +#: extmod/ulab/code/numpy/create.c extmod/ulab/code/numpy/numerical.c +#: extmod/ulab/code/numpy/transform.c +msgid "arguments must be ndarrays" +msgstr "" -#: py/compile.c -msgid "'align' requires 1 argument" -msgstr "'align' απαιτεί τουλάχιστον ένα όρισμα" +#: extmod/ulab/code/numpy/create.c +msgid "arguments must be 1D arrays" +msgstr "" -#: py/compile.c -msgid "'await' outside function" -msgstr "'await' εκτός συνάρτησης" +#: extmod/ulab/code/numpy/create.c +msgid "input is not an array" +msgstr "" -#: py/compile.c -msgid "'break'/'continue' outside loop" -msgstr "'break'/'continue' εκτός επανάληψης" +#: extmod/ulab/code/numpy/create.c extmod/ulab/code/numpy/numerical.c +#: ports/espressif/common-hal/pulseio/PulseIn.c +#: shared-bindings/bitmaptools/__init__.c +msgid "index out of range" +msgstr "" -#: py/compile.c -msgid "'data' requires at least 2 arguments" -msgstr "'data' απαιτεί τουλάχιστον 2 παραμέτρους" +#: extmod/ulab/code/numpy/create.c +msgid "mode should be raise, wrap or clip" +msgstr "" -#: py/compile.c -msgid "'data' requires integer arguments" -msgstr "'data' απαιτεί ακέραιες παραμέτρους" +#: extmod/ulab/code/numpy/create.c +msgid "index must not be negative" +msgstr "" -#: py/compile.c -msgid "'label' requires 1 argument" -msgstr "'label' απαιτεί ένα όρισμα" +#: extmod/ulab/code/numpy/create.c +msgid "offset must be non-negative and no greater than buffer length" +msgstr "" -#: py/emitnative.c -msgid "'not' not implemented" +#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c +msgid "buffer size must be a multiple of element size" msgstr "" -#: py/compile.c -msgid "'return' outside function" -msgstr "'return' εκτός συνάρτησης" +#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c +msgid "buffer is smaller than requested size" +msgstr "" -#: py/compile.c -msgid "'yield from' inside async function" -msgstr "'yield from' εκτός ασύνχρονης συνάρτησης" +#: extmod/ulab/code/numpy/fft/fft_tools.c +msgid "FFT is defined for ndarrays only" +msgstr "" -#: py/compile.c -msgid "'yield' outside function" -msgstr "'yield' εκτός συνάρτησης" +#: extmod/ulab/code/numpy/fft/fft_tools.c +msgid "FFT is implemented for linear arrays only" +msgstr "" -#: py/compile.c -msgid "* arg after **" -msgstr "* όρισμα μετά **" +#: extmod/ulab/code/numpy/fft/fft_tools.c extmod/ulab/code/utils/utils.c +msgid "input array length must be power of 2" +msgstr "" -#: py/compile.c -msgid "*x must be assignment target" -msgstr "*x πρέπει να είναι στόχος ανάθεσης" +#: extmod/ulab/code/numpy/fft/fft_tools.c +msgid "real and imaginary parts must be of equal length" +msgstr "" -#: py/obj.c -msgid ", in %q\n" -msgstr ", στο %q\n" +#: extmod/ulab/code/numpy/filter.c +msgid "convolve arguments must be ndarrays" +msgstr "" -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/epaperdisplay/EPaperDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -msgid ".show(x) removed. Use .root_group = x" -msgstr ".show(x) αφαιρέθηκε. Χρησιμοποιήστε το .root_group = x" +#: extmod/ulab/code/numpy/filter.c +msgid "convolve arguments must be linear arrays" +msgstr "" -#: py/objcomplex.c -msgid "0.0 to a complex power" -msgstr "0.0 σε μία σύνθετη δύναμη" +#: extmod/ulab/code/numpy/filter.c +msgid "convolve arguments must not be empty" +msgstr "" -#: py/modbuiltins.c -msgid "3-arg pow() not supported" -msgstr "pow() με 3 παραμέτρους δεν υποστηρίζεται" +#: extmod/ulab/code/numpy/io/io.c +msgid "corrupted file" +msgstr "" -#: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "AP could not be started" -msgstr "AP δεν μπόρεσε να εκκινηθεί" +#: extmod/ulab/code/numpy/io/io.c +msgid "wrong dtype" +msgstr "" -#: shared-bindings/_bleio/Address.c shared-bindings/ipaddress/IPv4Address.c -#, c-format -msgid "Address must be %d bytes long" -msgstr "Η διεύθυνση πρέπει να είναι %d bytes μεγάλη" +#: extmod/ulab/code/numpy/io/io.c +msgid "usecols keyword must be specified" +msgstr "" -#: ports/espressif/common-hal/memorymap/AddressRange.c -#: ports/nordic/common-hal/memorymap/AddressRange.c -#: ports/raspberrypi/common-hal/memorymap/AddressRange.c -msgid "Address range not allowed" -msgstr "Εμβέλεια διευθύνσεων δεν επιτρέπεται" +#: extmod/ulab/code/numpy/io/io.c +msgid "empty file" +msgstr "" -#: shared-bindings/memorymap/AddressRange.c -msgid "Address range wraps around" +#: extmod/ulab/code/numpy/io/io.c +msgid "usecols is too high" msgstr "" -#: ports/espressif/common-hal/canio/CAN.c -msgid "All CAN peripherals are in use" -msgstr "Όλα τα περιφεριακά CAN είναι σε χρήση" +#: extmod/ulab/code/numpy/io/io.c +msgid "array has too many dimensions" +msgstr "" -#: ports/espressif/common-hal/busio/I2C.c -#: ports/espressif/common-hal/i2ctarget/I2CTarget.c -#: ports/nordic/common-hal/busio/I2C.c -msgid "All I2C peripherals are in use" -msgstr "Όλα τα I2C περιφεριακά ειναι σε χρήση" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "input matrix is asymmetric" +msgstr "" -#: ports/atmel-samd/common-hal/canio/Listener.c -#: ports/espressif/common-hal/canio/Listener.c -#: ports/stm/common-hal/canio/Listener.c -msgid "All RX FIFOs in use" -msgstr "Όλα τα RX FIFOs είναι σε χρήση" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "matrix is not positive definite" +msgstr "" -#: ports/espressif/common-hal/busio/SPI.c ports/nordic/common-hal/busio/SPI.c -msgid "All SPI peripherals are in use" -msgstr "Όλα τα SPI περιφεριακά είναι σε χρήση" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "iterations did not converge" +msgstr "" -#: ports/espressif/common-hal/busio/UART.c ports/nordic/common-hal/busio/UART.c -msgid "All UART peripherals are in use" -msgstr "Όλα τα UART περιφεριακά ειναι σε χρήση" +#: extmod/ulab/code/numpy/linalg/linalg.c +#: extmod/ulab/code/scipy/linalg/linalg.c +msgid "input matrix is singular" +msgstr "" -#: ports/nordic/common-hal/countio/Counter.c -#: ports/nordic/common-hal/pulseio/PulseIn.c -#: ports/nordic/common-hal/rotaryio/IncrementalEncoder.c -msgid "All channels in use" -msgstr "Όλα τα κανάλια είναι σε χρήση" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "operation is defined for ndarrays only" +msgstr "" -#: ports/raspberrypi/common-hal/usb_host/Port.c -msgid "All dma channels in use" -msgstr "Όλα τα κανάλια dma είναι σε χρήση" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "operation is defined for 2D arrays only" +msgstr "" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c -msgid "All event channels in use" -msgstr "Όλα τα κανάλια συμβάντων είναι σε χρήση" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "mode must be complete, or reduced" +msgstr "" -#: ports/raspberrypi/common-hal/floppyio/__init__.c -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -#: ports/raspberrypi/common-hal/usb_host/Port.c -msgid "All state machines in use" -msgstr "Όλες οι μηχανές κατάστασης είναι σε χρήση" +#: extmod/ulab/code/numpy/numerical.c +msgid "attempt to get argmin/argmax of an empty sequence" +msgstr "" -#: ports/atmel-samd/audio_dma.c -msgid "All sync event channels in use" -msgstr "Όλα τα κανάλια συμβάντων συγχρονισμού είναι σε χρήση" +#: extmod/ulab/code/numpy/numerical.c +msgid "attempt to get (arg)min/(arg)max of empty sequence" +msgstr "" -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c -msgid "All timers for this pin are in use" -msgstr "Όλοι οι χρονιστές για αυτό το pin χρησιμοποιούνται ήδη" +#: extmod/ulab/code/numpy/numerical.c extmod/ulab/code/ulab_tools.c +msgid "axis must be None, or an integer" +msgstr "" -#: ports/atmel-samd/common-hal/_pew/PewPew.c -#: ports/atmel-samd/common-hal/audioio/AudioOut.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/nordic/common-hal/audiopwmio/PWMAudioOut.c -#: ports/nordic/common-hal/pulseio/PulseIn.c -#: ports/nordic/peripherals/nrf/timers.c -#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c -msgid "All timers in use" -msgstr "Όλοι οι χρονιστές βρίσκονται σε χρήση" +#: extmod/ulab/code/numpy/numerical.c +msgid "operation is not implemented on ndarrays" +msgstr "" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Already advertising." -msgstr "Ήδη διαφημίζουμε." +#: extmod/ulab/code/numpy/numerical.c +msgid "input must be tuple, list, range, or ndarray" +msgstr "" -#: ports/atmel-samd/common-hal/canio/Listener.c -msgid "Already have all-matches listener" -msgstr "Ύπάρχει ήδη all-matches ακροατής" +#: extmod/ulab/code/numpy/numerical.c +msgid "sort argument must be an ndarray" +msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -msgid "Already in progress" +#: extmod/ulab/code/numpy/numerical.c +msgid "argsort argument must be an ndarray" msgstr "" -#: ports/espressif/bindings/espnow/ESPNow.c -#: ports/espressif/common-hal/espulp/ULP.c -#: shared-module/memorymonitor/AllocationAlarm.c -#: shared-module/memorymonitor/AllocationSize.c -msgid "Already running" -msgstr "Τρέχει ήδη" +#: extmod/ulab/code/numpy/numerical.c +msgid "argsort is not implemented for flattened arrays" +msgstr "" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/raspberrypi/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "Already scanning for wifi networks" -msgstr "Ήδη γίνεται σάρωση για δίκτυα wifi" +#: extmod/ulab/code/numpy/numerical.c +msgid "axis too long" +msgstr "" -#: shared-module/os/getenv.c -#, c-format -msgid "An error occurred while retrieving '%s':\n" -msgstr "Παρουσιάστηκε σφάλμα κατά την ανάκτηση '%s':\n" +#: extmod/ulab/code/numpy/numerical.c +msgid "cross is defined for 1D arrays of length 3" +msgstr "" -#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c -msgid "Another PWMAudioOut is already active" -msgstr "Και άλλο PWMAudioOut είναι σε χρήση" +#: extmod/ulab/code/numpy/numerical.c +msgid "diff argument must be an ndarray" +msgstr "" -#: ports/atmel-samd/common-hal/pulseio/PulseOut.c -#: ports/cxd56/common-hal/pulseio/PulseOut.c -msgid "Another send is already active" -msgstr "Άλλη αποστολή είναι ήδη ενεργή" +#: extmod/ulab/code/numpy/numerical.c +msgid "differentiation order out of range" +msgstr "" -#: shared-bindings/pulseio/PulseOut.c -msgid "Array must contain halfwords (type 'H')" -msgstr "H παράταξη πρέπει να περιέχει halfwords (τύπου 'H')" +#: extmod/ulab/code/numpy/numerical.c +msgid "flip argument must be an ndarray" +msgstr "" -#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c -#: shared-bindings/nvm/ByteArray.c -msgid "Array values should be single bytes." -msgstr "Η τιμές της παράταξη πρέπει να είναι μονά bytes." +#: extmod/ulab/code/numpy/numerical.c +msgid "wrong axis index" +msgstr "" -#: ports/atmel-samd/common-hal/spitarget/SPITarget.c -msgid "Async SPI transfer in progress on this bus, keep awaiting." +#: extmod/ulab/code/numpy/numerical.c +msgid "median argument must be an ndarray" msgstr "" -#: shared-module/memorymonitor/AllocationAlarm.c -#, c-format -msgid "Attempt to allocate %d blocks" -msgstr "Προσπάθεια να δεσμευτούν %d blocks" +#: extmod/ulab/code/numpy/numerical.c +msgid "roll argument must be an ndarray" +msgstr "" -#: ports/raspberrypi/audio_dma.c -msgid "Audio conversion not implemented" -msgstr "Η μετατροπή ήχου δεν υποστηρίζεται" +#: extmod/ulab/code/numpy/poly.c +msgid "input data must be an iterable" +msgstr "" -#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c -#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c -msgid "Audio source error" +#: extmod/ulab/code/numpy/poly.c +msgid "more degrees of freedom than data points" msgstr "" -#: shared-bindings/wifi/Radio.c -msgid "AuthMode.OPEN is not used with password" -msgstr "AuthMode.OPEN δεν μπορεί να χρησιμοποιηθεί με κωδικό" +#: extmod/ulab/code/numpy/poly.c +msgid "input vectors must be of equal length" +msgstr "" -#: shared-bindings/wifi/Radio.c supervisor/shared/web_workflow/web_workflow.c -msgid "Authentication failure" -msgstr "Αποτυχία αυθεντικοποίησης" +#: extmod/ulab/code/numpy/poly.c +msgid "could not invert Vandermonde matrix" +msgstr "" -#: main.c -msgid "Auto-reload is off.\n" -msgstr "Η αυτόματη επαναφόρτωση είναι απενεργοποιημένη.\n" +#: extmod/ulab/code/numpy/poly.c +msgid "input is not iterable" +msgstr "" -#: main.c -msgid "" -"Auto-reload is on. Simply save files over USB to run them or enter REPL to " -"disable.\n" +#: extmod/ulab/code/numpy/random/random.c +msgid "argument must be None, an integer or a tuple of integers" +msgstr "" + +#: extmod/ulab/code/numpy/random/random.c +msgid "shape must be None, an integer or a tuple of integers" +msgstr "" + +#: extmod/ulab/code/numpy/random/random.c extmod/ulab/code/ulab_tools.c +msgid "out has wrong type" +msgstr "" + +#: extmod/ulab/code/numpy/random/random.c +msgid "output array has wrong type" +msgstr "" + +#: extmod/ulab/code/numpy/random/random.c +msgid "size must match out.shape when used together" +msgstr "" + +#: extmod/ulab/code/numpy/random/random.c extmod/ulab/code/ulab_tools.c +msgid "output array must be contiguous" +msgstr "" + +#: extmod/ulab/code/numpy/transform.c +msgid "wrong length of condition array" +msgstr "" + +#: extmod/ulab/code/numpy/transform.c extmod/ulab/code/numpy/vector.c +msgid "first argument must be an ndarray" +msgstr "" + +#: extmod/ulab/code/numpy/transform.c +msgid "wrong index type" +msgstr "" + +#: extmod/ulab/code/numpy/transform.c +msgid "wrong length of index array" +msgstr "" + +#: extmod/ulab/code/numpy/transform.c +msgid "dimensions do not match" +msgstr "" + +#: extmod/ulab/code/numpy/vector.c extmod/ulab/code/utils/utils.c +msgid "out must be an ndarray" +msgstr "" + +#: extmod/ulab/code/numpy/vector.c +msgid "out must be of float dtype" +msgstr "" + +#: extmod/ulab/code/numpy/vector.c +msgid "input and output dimensions differ" +msgstr "" + +#: extmod/ulab/code/numpy/vector.c +msgid "input and output shapes differ" +msgstr "" + +#: extmod/ulab/code/numpy/vector.c +msgid "out keyword is not supported for function" +msgstr "" + +#: extmod/ulab/code/numpy/vector.c +msgid "out keyword is not supported for complex dtype" +msgstr "" + +#: extmod/ulab/code/numpy/vector.c +msgid "dtype must be float, or complex" +msgstr "" + +#: extmod/ulab/code/numpy/vector.c +msgid "can't convert complex to float" +msgstr "" + +#: extmod/ulab/code/numpy/vector.c +msgid "input dtype must be float or complex" +msgstr "" + +#: extmod/ulab/code/numpy/vector.c extmod/ulab/code/scipy/integrate/integrate.c +msgid "first argument must be a callable" +msgstr "" + +#: extmod/ulab/code/numpy/vector.c +msgid "wrong output type" +msgstr "" + +#: extmod/ulab/code/scipy/integrate/integrate.c +#, c-format +msgid "can't convert arg %d from %s to float" +msgstr "" + +#: extmod/ulab/code/scipy/integrate/integrate.c +msgid "levels needs to be a positive integer" +msgstr "" + +#: extmod/ulab/code/scipy/integrate/integrate.c +msgid "steps needs to be a positive integer" msgstr "" -"Η αυτόματη επαναφόρτωση είναι ενεργή. Αποθηκεύστε αρχεία μέσω USB για να " -"τρέξετε ή ανοίξτε το REPL για απενεργοποίηση.\n" -#: ports/espressif/common-hal/canio/CAN.c -msgid "Baudrate not supported by peripheral" -msgstr "Baudrate δεν υποστηρίζεται από την περιφεριακή συσκευή" +#: extmod/ulab/code/scipy/integrate/integrate.c +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "first argument must be a function" +msgstr "" -#: shared-module/busdisplay/BusDisplay.c -#: shared-module/framebufferio/FramebufferDisplay.c -msgid "Below minimum frame rate" -msgstr "Χαμηλότερο από το ελάχιστο frame rate" +#: extmod/ulab/code/scipy/integrate/integrate.c +msgid "order needs to be a positive integer" +msgstr "" -#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c -msgid "Bit clock and word select must be sequential GPIO pins" -msgstr "Ρολόι bit και ορισμού λέξης πρέπει να είναι διαδοχικά GPIO pins" +#: extmod/ulab/code/scipy/linalg/linalg.c +msgid "first two arguments must be ndarrays" +msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "Bitmap size and bits per value must match" -msgstr "Το μέγεθος του bitmap και τα bits ανα τιμή πρέπει να ταιριάζουν" +#: extmod/ulab/code/scipy/linalg/linalg.c extmod/ulab/code/user/user.c +msgid "input must be a dense ndarray" +msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Boot device must be first (interface #0)." -msgstr "Η συσκευή εκκίνησης πρέπει να επιλεχθεί πρώτα (διεπαφή #0)." +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "function has the same sign at the ends of interval" +msgstr "" -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Both RX and TX required for flow control" -msgstr "Και RX και TX απαιτούνται για έλεγχο flow" +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "maxiter should be > 0" +msgstr "" -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -msgid "Brightness not adjustable" -msgstr "H φωτεινότητα δεν μπορεί να προσαρμοστεί" +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "maxiter must be > 0" +msgstr "" -#: shared-bindings/_bleio/UUID.c -#, c-format -msgid "Buffer + offset too small %d %d %d" -msgstr "Buffer + offset είναι πολύ μικρά %d %d %d" +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "data must be iterable" +msgstr "" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "Buffer elements must be 4 bytes long or less" -msgstr "Στοιχεία του buffer πρέπει να είναι το πολύ 4 bytes" +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "initial values must be iterable" +msgstr "" -#: shared-bindings/framebufferio/FramebufferDisplay.c -msgid "Buffer is not a bytearray." -msgstr "Το buffer δεν είναι ένα bytearray." +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "data must be of equal length" +msgstr "" -#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c -#, c-format -msgid "Buffer length %d too big. It must be less than %d" -msgstr "Το μήκος buffer %d είναι πολύ μεγάλο. Πρέπει ν α είναι λιγότερο απο %d" +#: extmod/ulab/code/scipy/signal/signal.c +msgid "sosfilt requires iterable arguments" +msgstr "" -#: ports/atmel-samd/common-hal/sdioio/SDCard.c -#: ports/cxd56/common-hal/sdioio/SDCard.c -#: ports/espressif/common-hal/sdioio/SDCard.c -#: ports/stm/common-hal/sdioio/SDCard.c shared-bindings/floppyio/__init__.c -#: shared-module/sdcardio/SDCard.c -#, c-format -msgid "Buffer must be a multiple of %d bytes" +#: extmod/ulab/code/scipy/signal/signal.c +msgid "input must be one-dimensional" msgstr "" -#: shared-bindings/_bleio/PacketBuffer.c -#, c-format -msgid "Buffer too short by %d bytes" -msgstr "Buffer πολύ μικρό κατα %d bytes" +#: extmod/ulab/code/scipy/signal/signal.c +msgid "zi must be an ndarray" +msgstr "" -#: ports/cxd56/common-hal/camera/Camera.c -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -#: shared-bindings/struct/__init__.c shared-module/struct/__init__.c -msgid "Buffer too small" -msgstr "Buffer πολύ μικρός" +#: extmod/ulab/code/scipy/signal/signal.c +msgid "zi must be of shape (n_section, 2)" +msgstr "" -#: ports/atmel-samd/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/nordic/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/raspberrypi/common-hal/paralleldisplaybus/ParallelBus.c -#, c-format -msgid "Bus pin %d is already in use" -msgstr "Bus pin %d είναι ήδη σε χρήση" +#: extmod/ulab/code/scipy/signal/signal.c +msgid "zi must be of float type" +msgstr "" -#: shared-bindings/_bleio/UUID.c -msgid "Byte buffer must be 16 bytes." -msgstr "Byte buffer πρέπει να είναι 16 bytes." +#: extmod/ulab/code/scipy/signal/signal.c +msgid "sos array must be of shape (n_section, 6)" +msgstr "" -#: shared-bindings/aesio/aes.c -msgid "CBC blocks must be multiples of 16 bytes" -msgstr "CBC blocks πρέπει να είναι πολλαπλάσια του 16 bytes" +#: extmod/ulab/code/scipy/signal/signal.c +msgid "sos[:, 3] should be all ones" +msgstr "" -#: supervisor/shared/safe_mode.c -msgid "CIRCUITPY drive could not be found or created." -msgstr "Ο CIRCUITPY δίσκος δεν μπόρεσε να βρεθεί ή να δημιουργηθεί." +#: extmod/ulab/code/ulab_tools.c +msgid "axis is out of bounds" +msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "CRC or checksum was invalid" -msgstr "CRC ή checksum ήταν άκυρο" +#: extmod/ulab/code/ulab_tools.c +msgid "size is defined for ndarrays only" +msgstr "" -#: py/objtype.c -msgid "Call super().__init__() before accessing native object." -msgstr "Κλήση super().__init__() πρίν την πρόσβαση του τοπικού αντικειμένου." +#: extmod/ulab/code/ulab_tools.c +msgid "input must be square matrix" +msgstr "" -#: ports/cxd56/common-hal/camera/Camera.c -msgid "Camera init" -msgstr "Εκκίνηση κάμερας" +#: extmod/ulab/code/ulab_tools.c +msgid "out array has wrong dtype" +msgstr "" -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Can only alarm on RTC IO from deep sleep." -msgstr "Μόνο IO alarm ή RTC επιτρέπονται από βαθύ ύπνο." +#: extmod/ulab/code/ulab_tools.c +msgid "out array has wrong dimension" +msgstr "" -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Can only alarm on one low pin while others alarm high from deep sleep." +#: extmod/ulab/code/ulab_tools.c +msgid "out array has wrong shape" msgstr "" -"Μόνο ένα alarm από low pin ενώ τα άλλα alarm θα είναι απο high σε βαθύ ύπνο." -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Can only alarm on two low pins from deep sleep." -msgstr "Μπορεί να γίνει alarm μόνο σε δύο low pins σε βαθύ ύπνο." +#: extmod/ulab/code/utils/utils.c +msgid "out must be a float dense array" +msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Can't construct AudioOut because continuous channel already open" +#: extmod/ulab/code/utils/utils.c +msgid "offset is too large" msgstr "" -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Characteristic.c -msgid "Can't set CCCD on local Characteristic" -msgstr "Δεν μπορεί να οριστεί CCCD σε τοπικό Characteristic" +#: extmod/ulab/code/utils/utils.c +msgid "out array is too small" +msgstr "" -#: shared-bindings/storage/__init__.c shared-bindings/usb_cdc/__init__.c -#: shared-bindings/usb_hid/__init__.c shared-bindings/usb_midi/__init__.c -#: shared-bindings/usb_video/__init__.c -msgid "Cannot change USB devices now" -msgstr "Δεν μπορούν να αλλάξουν οι USB συσκευές τώρα" +#: extmod/ulab/code/utils/utils.c +msgid "spectrogram is defined for ndarrays only" +msgstr "" -#: shared-bindings/_bleio/Adapter.c -msgid "Cannot create a new Adapter; use _bleio.adapter;" +#: extmod/ulab/code/utils/utils.c +msgid "spectrogram is implemented for 1D arrays only" msgstr "" -"Δεν μπορεί να δημιουργηθεί νέο Adapter; χρησιμοποιείστε _bleio.adapter;" -#: shared-bindings/displayio/Bitmap.c -#: shared-bindings/memorymonitor/AllocationSize.c -#: shared-bindings/pulseio/PulseIn.c -msgid "Cannot delete values" -msgstr "Δεν μπορούν να διαγραφούν οι τιμές" +#: extmod/ulab/code/utils/utils.c +msgid "out array must be a 1D array of float type" +msgstr "" -#: ports/atmel-samd/common-hal/digitalio/DigitalInOut.c -#: ports/mimxrt10xx/common-hal/digitalio/DigitalInOut.c -#: ports/nordic/common-hal/digitalio/DigitalInOut.c -#: ports/raspberrypi/common-hal/digitalio/DigitalInOut.c -msgid "Cannot get pull while in output mode" -msgstr "Δεν γίνεται να διαβαστεί το pull όσο είναι σε output mode" +#: extmod/ulab/code/utils/utils.c +msgid "input and out arrays must have same length" +msgstr "" -#: ports/nordic/common-hal/microcontroller/Processor.c -msgid "Cannot get temperature" -msgstr "Δεν μπορεί να διαβαστεί η θερμοκρασία" +#: extmod/ulab/code/utils/utils.c +msgid "scratchpad must be an ndarray" +msgstr "" -#: shared-bindings/_bleio/Adapter.c -msgid "Cannot have scan responses for extended, connectable advertisements." +#: extmod/ulab/code/utils/utils.c +msgid "scratchpad must be a 1D dense float array" msgstr "" -"Δεν μπορούμε να έχουμε απαντήσεις scan για εκτεταμένες, συνδεόμενες " -"διαφημήσεις." -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Cannot pull on input-only pin." -msgstr "Δεν γίνεται pull σε pin μόνο για εισόδο." +#: extmod/ulab/code/utils/utils.c +msgid "scratchpad must be twice as long as input" +msgstr "" -#: shared-bindings/audiobusio/PDMIn.c -msgid "Cannot record to a file" -msgstr "Δεν μπορεί να γίνει καταγραφή σε αρχείο" +#: extmod/vfs_fat.c py/moderrno.c +msgid "Read-only filesystem" +msgstr "" -#: shared-module/storage/__init__.c -msgid "Cannot remount '/' when visible via USB." -msgstr "Δεν μπορεί να γίνει remount του '/' όταν είναι ορατό μέσω USB." +#: extmod/vfs_posix_file.c py/objstringio.c +msgid "I/O operation on closed file" +msgstr "" -#: shared-bindings/digitalio/DigitalInOut.c -msgid "Cannot set value when direction is input." -msgstr "Δεν μπορεί να οριστεί τιμή οταν η κατεύθυνση είναι input." +#: extmod/vfs_posix_file.c +msgid "poll on file not available on win32" +msgstr "" -#: ports/espressif/common-hal/busio/UART.c -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Cannot specify RTS or CTS in RS485 mode" -msgstr "Δεν μπορεί να οριστεί RTS ή CTS σε RS485 mode" +#: main.c +msgid "Done" +msgstr "Ολοκληρώθηκε" -#: py/objslice.c -msgid "Cannot subclass slice" -msgstr "Δεν γίνεται υποκατηγορία ενός slice" +#: main.c +msgid " output:\n" +msgstr " έξοδος:\n" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Cannot use GPIO0..15 together with GPIO32..47" +#: main.c +msgid "" +"Auto-reload is on. Simply save files over USB to run them or enter REPL to " +"disable.\n" msgstr "" +"Η αυτόματη επαναφόρτωση είναι ενεργή. Αποθηκεύστε αρχεία μέσω USB για να " +"τρέξετε ή ανοίξτε το REPL για απενεργοποίηση.\n" -#: ports/nordic/common-hal/alarm/pin/PinAlarm.c -msgid "Cannot wake on pin edge, only level" -msgstr "Δεν γίνεται αφύπνηση σε pin edge, αλλά μόνο σε level" +#: main.c +msgid "Auto-reload is off.\n" +msgstr "Η αυτόματη επαναφόρτωση είναι απενεργοποιημένη.\n" -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Cannot wake on pin edge. Only level." -msgstr "Δεν μπορεί να γίνει αφύπνηση σε pin edge. Μόνο level." +#: main.c +msgid "Running in safe mode! Not running saved code.\n" +msgstr "" -#: shared-bindings/_bleio/CharacteristicBuffer.c -msgid "CharacteristicBuffer writing not provided" -msgstr "Δεν υποστηρίζονται εγγραφές στο CharacteristicBuffer" +#: main.c +msgid " not found.\n" +msgstr " δεν βρέθηκε.\n" -#: supervisor/shared/safe_mode.c -msgid "CircuitPython core code crashed hard. Whoops!\n" -msgstr "Ο πυρήνας της CircuitPython κατέρευσε. Οουπς!\n" +#: main.c +msgid "WARNING: Your code filename has two extensions\n" +msgstr "" -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -msgid "Clock unit in use" -msgstr "Μονάδα ρολογιού ήδη σε χρήση" +#: main.c +msgid "" +"\n" +"Code stopped by auto-reload. Reloading soon.\n" +msgstr "" +"\n" +"Ο κώδικας σταμάτησε λόγω της αυτόματης επαναφόρτωσης. Η επαναφόρτωση θα " +"γίνει σύντομα.\n" -#: shared-bindings/_bleio/Connection.c +#: main.c msgid "" -"Connection has been disconnected and can no longer be used. Create a new " -"connection." +"\n" +"Code done running.\n" msgstr "" -"Έχει γίνει αποσύνδεση και αυτή η συνδεση δεν μπορεί να χρησιμοποιηθεί. " -"Δημιουργήστε μια νέα σύνδεση." +"\n" +"Η εκτέλεση του κώδικα ολοκληρώθηκε.\n" -#: shared-bindings/bitmaptools/__init__.c -msgid "Coordinate arrays have different lengths" +#: main.c +msgid "Woken up by alarm.\n" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "Coordinate arrays types have different sizes" +#: main.c +msgid "Press any key to enter the REPL. Use CTRL-D to reload.\n" msgstr "" +"Πατήστε οποιοδήποτε πλήκτρο για να μπείτε στο REPL. Πατήστε CTRL-D για " +"επαναφόρτωση.\n" -#: shared-bindings/_bleio/Adapter.c -msgid "Could not set address" -msgstr "Δεν μπόρεσε να ρυθμιστεί η διεύθυνση" +#: main.c +msgid "Pretending to deep sleep until alarm, CTRL-C or file write.\n" +msgstr "Προσποίηση βαθύ ύπνου μεχρι γεγονότος, CTRL-C ή εγγραφή αρχείου.\n" -#: ports/stm/common-hal/busio/UART.c -msgid "Could not start interrupt, RX busy" -msgstr "Δεν μπόρεσε να εκκινηθεί το interrupt, RX κατειλημμένο" +#: main.c +msgid "UID:" +msgstr "" -#: shared-module/audiomp3/MP3Decoder.c -msgid "Couldn't allocate decoder" -msgstr "Δεν μπόρεσε να δεσμευτεί decoder" +#: main.c +msgid "soft reboot\n" +msgstr "" -#: ports/stm/common-hal/analogio/AnalogOut.c -msgid "DAC Channel Init Error" -msgstr "Σφάλμα εκκίνησης καναλιού DAC" +#: ports/analog/common-hal/busio/SPI.c ports/analog/common-hal/busio/UART.c +#: ports/cxd56/common-hal/busio/SPI.c ports/stm/common-hal/audioio/AudioOut.c +#: shared-bindings/digitalio/DigitalInOutProtocol.c +#: shared-module/displayio/bus_core.c shared-module/ssl/SSLContext.c +msgid "%q init failed" +msgstr "%q εκκίνηση απέτυχε" -#: ports/stm/common-hal/analogio/AnalogOut.c -msgid "DAC Device Init Error" -msgstr "Σφάλμα εκκίνησης συσκευής DAC" +#: ports/analog/common-hal/busio/SPI.c +msgid "SPI needs MOSI, MISO, and SCK" +msgstr "" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c -msgid "DAC already in use" -msgstr "DAC είναι ήδη σε χρήση" +#: ports/analog/common-hal/busio/SPI.c +#: ports/atmel-samd/common-hal/pulseio/PulseIn.c +#: ports/cxd56/common-hal/pulseio/PulseIn.c +#: ports/nordic/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#: ports/stm/common-hal/pulseio/PulseIn.c py/argcheck.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/canio/Match.c +#: shared-bindings/time/__init__.c +msgid "%q out of range" +msgstr "%q εκτός εμβέλειας" -#: ports/atmel-samd/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/nordic/common-hal/paralleldisplaybus/ParallelBus.c -msgid "Data 0 pin must be byte aligned" -msgstr "Το Data 0 pin πρέπει να είναι byte aligned" +#: ports/analog/common-hal/busio/SPI.c +#: ports/espressif/common-hal/espidf/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: shared-bindings/epaperdisplay/EPaperDisplay.c +msgid "Invalid state" +msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "Data format error (may be broken data)" +#: ports/analog/common-hal/busio/SPI.c +msgid "Failed to set SPI Clock Mode" msgstr "" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Data not supported with directed advertising" -msgstr "Δεν υποστηρίζονται δεδομένα με κατευθυνόμενη διαφήμιση" +#: ports/analog/common-hal/busio/UART.c +#: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c +#: ports/nordic/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/zephyr-cp/common-hal/busio/UART.c +msgid "RS485" +msgstr "RS485" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Data too large for advertisement packet" -msgstr "Τα δεδομένα είναι πολύ μεγάλα για πακέτο διαφημίσεων" +#: ports/analog/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c +msgid "UART needs TX & RX" +msgstr "" -#: ports/stm/common-hal/alarm/pin/PinAlarm.c -msgid "Deep sleep pins must use a rising edge with pulldown" -msgstr "Τα pins βαθύ ύπνου πρέπει να χρησιμοποιούν rising edge με pulldown" +#: ports/analog/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c +msgid "Both RX and TX required for flow control" +msgstr "Και RX και TX απαιτούνται για έλεγχο flow" -#: shared-bindings/audiobusio/PDMIn.c -msgid "Destination capacity is smaller than destination_length." +#: ports/analog/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/usb_host/Port.c +#: shared-module/rgbmatrix/RGBMatrix.c +msgid "Failed to allocate %q buffer" msgstr "" -"Το μέγεθος προορισμού πρέπει να είναι μικρότερο από το destination_length." -#: shared-module/jpegio/JpegDecoder.c -msgid "Device error or wrong termination of input stream" +#: ports/analog/common-hal/busio/UART.c +msgid "UART read error" msgstr "" -#: ports/nordic/common-hal/audiobusio/I2SOut.c -msgid "Device in use" -msgstr "Συσκευή σε χρήση" +#: ports/analog/common-hal/busio/UART.c +msgid "UART transaction timeout" +msgstr "" -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -#, fuzzy -msgid "Display must have a 16 bit colorspace." -msgstr "Η οθόνη πρέπει να έχει 16 bit χρωματική ευκρίνεια." +#: ports/analog/common-hal/busio/UART.c ports/espressif/common-hal/busio/UART.c +#: ports/nordic/common-hal/busio/UART.c ports/zephyr-cp/common-hal/busio/UART.c +msgid "All UART peripherals are in use" +msgstr "Όλα τα UART περιφεριακά ειναι σε χρήση" -#: shared-bindings/busdisplay/BusDisplay.c +#: ports/analog/common-hal/busio/UART.c +#: ports/analog/peripherals/max32690/max32_i2c.c +#: ports/analog/peripherals/max32690/max32_spi.c +#: ports/analog/peripherals/max32690/max32_uart.c +#: ports/espressif/common-hal/_bleio/Service.c +#: ports/espressif/common-hal/espulp/ULP.c +#: ports/espressif/common-hal/jpegio/JpegDecoder.c +#: ports/espressif/common-hal/microcontroller/Processor.c +#: ports/espressif/common-hal/mipidsi/Display.c +#: ports/mimxrt10xx/common-hal/audiobusio/__init__.c +#: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c +#: ports/raspberrypi/bindings/picodvi/Framebuffer.c +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +#: ports/raspberrypi/common-hal/picodvi/AudioOut.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c +#: ports/raspberrypi/common-hal/usb_host_bulk/InStream.c py/argcheck.c +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/utils/__init__.c +#: shared-bindings/digitalio/DigitalInOut.c #: shared-bindings/epaperdisplay/EPaperDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -msgid "Display rotation must be in 90 degree increments" -msgstr "Η περιστροφή της οθόνη πρέπει να γίνεται σε βήματα 90 μοιρών" +#: shared-bindings/i2cioexpander/IOPin.c shared-bindings/mipidsi/Display.c +#: shared-bindings/pwmio/PWMOut.c shared-bindings/supervisor/__init__.c +#: shared-module/aurora_epaper/aurora_framebuffer.c +#: shared-module/cryptography/hazmat/primitives/asymmetric/ec/EllipticCurvePublicKey.c +#: shared-module/jpegio/JpegDecoder.c shared-module/lvfontio/OnDiskFont.c +msgid "Invalid %q" +msgstr "" -#: main.c -msgid "Done" -msgstr "Ολοκληρώθηκε" +#: ports/analog/common-hal/busio/UART.c +msgid "Timeout must be < 100 seconds" +msgstr "" -#: shared-bindings/digitalio/DigitalInOut.c -msgid "Drive mode not used when direction is input." -msgstr "Ο τρόπος οδήγησης δεν χρησιμοποιείται όταν η κατεύθυνση είναι είσοδος." +#: ports/atmel-samd/audio_dma.c +msgid "All sync event channels in use" +msgstr "Όλα τα κανάλια συμβάντων συγχρονισμού είναι σε χρήση" -#: py/obj.c -msgid "During handling of the above exception, another exception occurred:" +#: ports/atmel-samd/audio_dma.c ports/raspberrypi/audio_dma.c +msgid "Internal audio buffer too small" msgstr "" -"Κατά την αντιμετώπιση της παραπάνω εξαίρεσης, ακόμα μία εξαίρεση συνέβη:" -#: shared-bindings/aesio/aes.c -msgid "ECB only operates on 16 bytes at a time" -msgstr "ECB δουλεύει μόνο σε 16 bytes κάθε φορά" +#: ports/atmel-samd/bindings/samd/Clock.c +msgid "calibration is read only" +msgstr "" -#: ports/espressif/common-hal/busio/SPI.c -#: ports/espressif/common-hal/canio/CAN.c -msgid "ESP-IDF memory allocation failed" -msgstr "ESP-IDF δέσμευση μνήμης απέτυχε" +#: ports/atmel-samd/bindings/samd/Clock.c +msgid "calibration is out of range" +msgstr "" -#: extmod/modre.c -msgid "Error in regex" -msgstr "Σφάλμα σε regex" +#: 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/meowmeow/mpconfigboard.h +msgid "You pressed both buttons at start up." +msgstr "" + +#: ports/atmel-samd/common-hal/_pew/PewPew.c +#: ports/atmel-samd/common-hal/audioio/AudioOut.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/nordic/common-hal/audiopwmio/PWMAudioOut.c +#: ports/nordic/common-hal/pulseio/PulseIn.c +#: ports/nordic/peripherals/nrf/timers.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +#: ports/stm/common-hal/pulseio/PulseOut.c +msgid "All timers in use" +msgstr "Όλοι οι χρονιστές βρίσκονται σε χρήση" + +#: ports/atmel-samd/common-hal/alarm/pin/PinAlarm.c +#: ports/atmel-samd/common-hal/countio/Counter.c +#: ports/atmel-samd/common-hal/frequencyio/FrequencyIn.c +#: ports/atmel-samd/common-hal/max3421e/Max3421E.c +#: ports/atmel-samd/common-hal/ps2io/Ps2.c +#: ports/atmel-samd/common-hal/pulseio/PulseIn.c +#: ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.c +#: ports/cxd56/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c +#: ports/zephyr-cp/common-hal/async_spi/SPI.c +#: ports/zephyr-cp/common-hal/busio/I2C.c +#: ports/zephyr-cp/common-hal/busio/UART.c +msgid "Internal resource(s) in use" +msgstr "" +#: ports/atmel-samd/common-hal/alarm/pin/PinAlarm.c #: supervisor/shared/safe_mode.c -msgid "Error in safemode.py." -msgstr "Σφάλμα στο safemode.py." +msgid "Unknown reason." +msgstr "" -#: shared-bindings/alarm/__init__.c -msgid "Expected a kind of %q" +#: ports/atmel-samd/common-hal/alarm/time/TimeAlarm.c +#: ports/nordic/common-hal/alarm/time/TimeAlarm.c +#: ports/stm/common-hal/alarm/time/TimeAlarm.c +msgid "Only one alarm.time alarm can be set" msgstr "" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Extended advertisements with scan response not supported." +#: ports/atmel-samd/common-hal/analogio/AnalogOut.c +#: ports/stm/common-hal/analogio/AnalogOut.c +#: ports/stm/common-hal/audioio/AudioOut.c +msgid "No DAC on chip" msgstr "" -#: extmod/ulab/code/numpy/fft/fft_tools.c -msgid "FFT is defined for ndarrays only" +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +msgid "%q and %q must share a clock unit" msgstr "" -#: extmod/ulab/code/numpy/fft/fft_tools.c -msgid "FFT is implemented for linear arrays only" +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +msgid "Serializer in use" msgstr "" -#: shared-bindings/ps2io/Ps2.c -msgid "Failed sending command." +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +msgid "Clock unit in use" +msgstr "Μονάδα ρολογιού ήδη σε χρήση" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/atmel-samd/common-hal/touchio/TouchIn.c +msgid "No free GCLKs" msgstr "" -#: ports/nordic/sd_mutex.c -#, c-format -msgid "Failed to acquire mutex, err 0x%04x" +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +msgid "Too many channels in sample" msgstr "" -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "Failed to add service TXT record" +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +#: ports/raspberrypi/common-hal/mcp4822/MCP4822.c +msgid "No DMA channel found" msgstr "" -#: shared-bindings/mdns/Server.c -msgid "" -"Failed to add service TXT record; non-string or bytes found in txt_records" +#: 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 +#: ports/raspberrypi/common-hal/mcp4822/MCP4822.c +msgid "Unable to allocate buffers for signed conversion" msgstr "" -#: shared-module/rgbmatrix/RGBMatrix.c -msgid "Failed to allocate %q buffer" +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c +#, c-format +msgid "Only 8 or 16 bit mono with %dx oversampling supported." msgstr "" -#: ports/espressif/common-hal/wifi/__init__.c -msgid "Failed to allocate Wifi memory" +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c +msgid "sampling rate out of range" msgstr "" -#: ports/espressif/common-hal/wifi/ScannedNetworks.c -msgid "Failed to allocate wifi scan memory" -msgstr "" +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +msgid "DAC already in use" +msgstr "DAC είναι ήδη σε χρήση" -#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c -msgid "Failed to buffer the sample" +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +msgid "Right channel unsupported" msgstr "" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Failed to connect: internal error" -msgstr "" +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +msgid "All event channels in use" +msgstr "Όλα τα κανάλια συμβάντων είναι σε χρήση" -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Failed to connect: timeout" +#: ports/atmel-samd/common-hal/busio/I2C.c +#: ports/espressif/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nordic/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 "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to create continuous channels: invalid arg" -msgstr "" +#: ports/atmel-samd/common-hal/busio/UART.c +#: shared-bindings/usb_host_bulk/InStream.c +msgid "%q must be power of 2" +msgstr "%q πρέπει να είναι δύναμη του 2" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to create continuous channels: invalid state" +#: ports/atmel-samd/common-hal/busio/UART.c +#: ports/espressif/common-hal/busio/SPI.c +#: ports/espressif/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/SPI.c +#: ports/mimxrt10xx/common-hal/busio/UART.c +#: ports/nordic/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c ports/stm/common-hal/busio/SPI.c +#: ports/stm/common-hal/busio/UART.c shared-bindings/fourwire/FourWire.c +#: shared-bindings/i2cdisplaybus/I2CDisplayBus.c +#: shared-bindings/paralleldisplaybus/ParallelBus.c +#: shared-bindings/qspibus/QSPIBus.c shared-module/bitbangio/SPI.c +msgid "No %q pin" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to create continuous channels: no mem" -msgstr "" +#: ports/atmel-samd/common-hal/canio/Listener.c +#: ports/espressif/common-hal/canio/Listener.c +#: ports/stm/common-hal/canio/Listener.c +msgid "All RX FIFOs in use" +msgstr "Όλα τα RX FIFOs είναι σε χρήση" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to create continuous channels: not found" -msgstr "" +#: ports/atmel-samd/common-hal/canio/Listener.c +msgid "Already have all-matches listener" +msgstr "Ύπάρχει ήδη all-matches ακροατής" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to enable continuous" +#: ports/atmel-samd/common-hal/canio/Listener.c +#: ports/espressif/common-hal/canio/Listener.c +#: ports/mimxrt10xx/common-hal/canio/Listener.c +#: ports/stm/common-hal/canio/Listener.c +msgid "Filters too complex" msgstr "" -#: shared-module/audiomp3/MP3Decoder.c -msgid "Failed to parse MP3 file" -msgstr "" +#: ports/atmel-samd/common-hal/digitalio/DigitalInOut.c +#: ports/mimxrt10xx/common-hal/digitalio/DigitalInOut.c +#: ports/nordic/common-hal/digitalio/DigitalInOut.c +#: ports/raspberrypi/common-hal/digitalio/DigitalInOut.c +msgid "Cannot get pull while in output mode" +msgstr "Δεν γίνεται να διαβαστεί το pull όσο είναι σε output mode" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to register continuous events callback" +#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c +#, c-format +msgid "Invalid data_pins[%d]" msgstr "" -#: ports/nordic/sd_mutex.c +#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c #, c-format -msgid "Failed to release mutex, err 0x%04x" +msgid "data pin #%d in use" msgstr "" -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "Failed to set hostname" +#: ports/atmel-samd/common-hal/microcontroller/Pin.c +#: ports/espressif/common-hal/dotclockframebuffer/DotClockFramebuffer.c +#: ports/mimxrt10xx/common-hal/microcontroller/Pin.c +#: shared-bindings/emmcio/EMMC.c shared-bindings/microcontroller/Pin.c +msgid "Invalid %q pin" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to start async audio" +#: ports/atmel-samd/common-hal/microcontroller/__init__.c +#: ports/cxd56/common-hal/microcontroller/__init__.c +#: ports/mimxrt10xx/common-hal/microcontroller/__init__.c +msgid "No bootloader present" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Failed to write internal flash." -msgstr "" +#: ports/atmel-samd/common-hal/paralleldisplaybus/ParallelBus.c +#: ports/nordic/common-hal/paralleldisplaybus/ParallelBus.c +msgid "Data 0 pin must be byte aligned" +msgstr "Το Data 0 pin πρέπει να είναι byte aligned" -#: py/moderrno.c -msgid "File exists" -msgstr "" +#: ports/atmel-samd/common-hal/paralleldisplaybus/ParallelBus.c +#: ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c +#: ports/nordic/common-hal/paralleldisplaybus/ParallelBus.c +#: ports/raspberrypi/common-hal/paralleldisplaybus/ParallelBus.c +#, c-format +msgid "Bus pin %d is already in use" +msgstr "Bus pin %d είναι ήδη σε χρήση" -#: shared-module/os/getenv.c -msgid "File not found" +#: ports/atmel-samd/common-hal/pulseio/PulseIn.c +#: ports/cxd56/common-hal/pulseio/PulseIn.c +#: ports/nordic/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 "" -#: ports/atmel-samd/common-hal/canio/Listener.c -#: ports/espressif/common-hal/canio/Listener.c -#: ports/mimxrt10xx/common-hal/canio/Listener.c -#: ports/stm/common-hal/canio/Listener.c -msgid "Filters too complex" +#: ports/atmel-samd/common-hal/pulseio/PulseIn.c +msgid "Input taking too long" msgstr "" -#: ports/espressif/common-hal/dualbank/__init__.c -msgid "Firmware is duplicate" -msgstr "" +#: ports/atmel-samd/common-hal/pulseio/PulseOut.c +#: ports/cxd56/common-hal/pulseio/PulseOut.c +msgid "Another send is already active" +msgstr "Άλλη αποστολή είναι ήδη ενεργή" -#: ports/espressif/common-hal/dualbank/__init__.c -msgid "Firmware is invalid" +#: ports/atmel-samd/common-hal/sdioio/SDCard.c +#: ports/espressif/common-hal/mii/Ethernet.c +#: ports/espressif/common-hal/qspibus/QSPIBus.c shared-bindings/emmcio/EMMC.c +#: shared-bindings/socketpool/SocketPool.c +msgid "%q failure: %d" +msgstr "%q αποτυχία: %d" + +#: ports/atmel-samd/common-hal/sdioio/SDCard.c +#: ports/cxd56/common-hal/sdioio/SDCard.c +#: ports/espressif/common-hal/sdioio/SDCard.c +#: ports/raspberrypi/common-hal/sdioio/SDCard.c +#: ports/stm/common-hal/sdioio/SDCard.c shared-bindings/audiocore/WaveFile.c +#: shared-bindings/emmcio/EMMC.c shared-bindings/floppyio/__init__.c +#: shared-bindings/picogame/Canvas.c shared-module/sdcardio/SDCard.c +#, c-format +msgid "Buffer must be a multiple of %d bytes" msgstr "" -#: ports/espressif/common-hal/dualbank/__init__.c -msgid "Firmware is too big" +#: ports/atmel-samd/common-hal/spitarget/SPITarget.c +msgid "Async SPI transfer in progress on this bus, keep awaiting." msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "For L8 colorspace, input bitmap must have 8 bits per pixel" +#: ports/cxd56/common-hal/busio/UART.c ports/espressif/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c +msgid "UART init" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "For RGB colorspaces, input bitmap must have 16 bits per pixel" +#: ports/cxd56/common-hal/camera/Camera.c +msgid "Camera init" +msgstr "Εκκίνηση κάμερας" + +#: ports/cxd56/common-hal/camera/Camera.c +msgid "Size not supported" msgstr "" #: ports/cxd56/common-hal/camera/Camera.c +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +#: shared-bindings/struct/__init__.c shared-module/struct/__init__.c +#: shared-module/videocore/VideoBuffer.c +msgid "Buffer too small" +msgstr "Buffer πολύ μικρός" + +#: ports/cxd56/common-hal/camera/Camera.c +#: ports/espressif/common-hal/jpegio/JpegDecoder.c +#: shared-module/audiocore/WaveFile.c +#: shared-module/busdisplay/lvgl/BusDisplay.c +#: shared-module/displayio/lvgl/TileGrid.c +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c msgid "Format not supported" msgstr "" -#: ports/mimxrt10xx/common-hal/microcontroller/Processor.c -msgid "" -"Frequency must be 24, 150, 396, 450, 528, 600, 720, 816, 912, 960 or 1008 Mhz" +#: ports/cxd56/common-hal/gnss/GNSS.c +msgid "GNSS init" msgstr "" -#: shared-bindings/bitbangio/I2C.c shared-bindings/bitbangio/SPI.c -#: shared-bindings/busio/I2C.c shared-bindings/busio/SPI.c -msgid "Function requires lock" +#: ports/cxd56/common-hal/sdioio/SDCard.c +msgid "SDCard init" msgstr "" -#: ports/cxd56/common-hal/gnss/GNSS.c -msgid "GNSS init" +#: ports/espressif/bindings/espnow/ESPNow.c +#: ports/espressif/common-hal/espulp/ULP.c +#: ports/raspberrypi/common-hal/usb_host_bulk/InStream.c +#: shared-module/memorymonitor/AllocationAlarm.c +#: shared-module/memorymonitor/AllocationSize.c +msgid "Already running" +msgstr "Τρέχει ήδη" + +#: ports/espressif/bindings/espnow/Peer.c shared-bindings/dualbank/__init__.c +msgid "%q is %q" +msgstr "%q είναι %q" + +#: ports/espressif/boards/adafruit_feather_esp32_v2/mpconfigboard.h +msgid "You pressed the SW38 button at start up." msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Generic Failure" +#: ports/espressif/boards/adafruit_feather_esp32c6_4mbflash_nopsram/mpconfigboard.h +#: ports/espressif/boards/adafruit_itsybitsy_esp32/mpconfigboard.h +#: ports/espressif/boards/waveshare_esp32_c5_lcd_1_47/mpconfigboard.h +#: ports/espressif/boards/waveshare_esp32_c6_lcd_1_47/mpconfigboard.h +msgid "You pressed the BOOT button at start up." msgstr "" -#: shared-bindings/framebufferio/FramebufferDisplay.c -#: shared-module/busdisplay/BusDisplay.c -#: shared-module/framebufferio/FramebufferDisplay.c -msgid "Group already used" +#: ports/espressif/boards/adafruit_huzzah32_breakout/mpconfigboard.h +msgid "You pressed the GPIO0 button at start up." msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Hard fault: memory access or instruction error." +#: ports/espressif/boards/espressif_esp32_lyrat/mpconfigboard.h +msgid "You pressed the Rec button at start up." msgstr "" -#: ports/mimxrt10xx/common-hal/busio/SPI.c -#: ports/mimxrt10xx/common-hal/busio/UART.c 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 "Hardware in use, try alternative pins" +#: ports/espressif/boards/hardkernel_odroid_go/mpconfigboard.h +#: ports/espressif/boards/vidi_x/mpconfigboard.h +msgid "You pressed the VOLUME button at start up." msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Heap allocation when VM not running." +#: ports/espressif/boards/m5stack_atom_echo/mpconfigboard.h +#: ports/espressif/boards/m5stack_atom_lite/mpconfigboard.h +#: ports/espressif/boards/m5stack_atom_matrix/mpconfigboard.h +#: ports/espressif/boards/m5stack_atom_u/mpconfigboard.h +msgid "You pressed the central button at start up." msgstr "" -#: extmod/vfs_posix_file.c py/objstringio.c -msgid "I/O operation on closed file" +#: ports/espressif/boards/m5stack_core_basic/mpconfigboard.h +#: ports/espressif/boards/m5stack_core_fire/mpconfigboard.h +#: ports/espressif/boards/m5stack_stick_c/mpconfigboard.h +#: ports/espressif/boards/m5stack_stick_c_plus/mpconfigboard.h +#: ports/espressif/boards/m5stack_stick_c_plus2/mpconfigboard.h +msgid "You pressed button A at start up." msgstr "" -#: ports/stm/common-hal/busio/I2C.c -msgid "I2C init error" +#: ports/espressif/boards/m5stack_m5paper/mpconfigboard.h +msgid "You pressed button DOWN at start up." msgstr "" -#: ports/raspberrypi/common-hal/busio/I2C.c -#: ports/raspberrypi/common-hal/i2ctarget/I2CTarget.c -msgid "I2C peripheral in use" +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/espressif/common-hal/dualbank/__init__.c +msgid "Update failed" msgstr "" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "In-buffer elements must be <= 4 bytes long" +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "Scan already in progress. Stop with stop_scan." +msgstr "" + +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +#: ports/zephyr-cp/common-hal/_bleio/Adapter.c +msgid "Failed to connect: timeout" msgstr "" -#: shared-bindings/_pew/PewPew.c -msgid "Incorrect buffer size" +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +#: ports/zephyr-cp/common-hal/_bleio/Adapter.c +msgid "Failed to connect: internal error" msgstr "" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "Init program size invalid" +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +#: ports/zephyr-cp/common-hal/_bleio/Adapter.c +msgid "Data too large for advertisement packet" +msgstr "Τα δεδομένα είναι πολύ μεγάλα για πακέτο διαφημίσεων" + +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "Already advertising." +msgstr "Ήδη διαφημίζουμε." + +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "Extended advertisements with scan response not supported." msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Initial set pin direction conflicts with initial out pin direction" +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "Data not supported with directed advertising" +msgstr "Δεν υποστηρίζονται δεδομένα με κατευθυνόμενη διαφήμιση" + +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +#, c-format +msgid "Timeout is too long: Maximum timeout length is %d seconds" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Initial set pin state conflicts with initial out pin state" +#: ports/espressif/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Descriptor.c +msgid "Value length != required fixed length" msgstr "" -#: shared-bindings/bitops/__init__.c -#, c-format -msgid "Input buffer length (%d) must be a multiple of the strand count (%d)" +#: ports/espressif/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Descriptor.c +msgid "Value length > max_length" msgstr "" -#: ports/atmel-samd/common-hal/pulseio/PulseIn.c -msgid "Input taking too long" +#: ports/espressif/common-hal/_bleio/Characteristic.c +#: ports/espressif/common-hal/_bleio/Service.c +#: ports/raspberrypi/common-hal/alarm/pin/PinAlarm.c +#: ports/raspberrypi/common-hal/usb_host_bulk/InStream.c +msgid "Too many %q" msgstr "" -#: py/moderrno.c -msgid "Input/output error" +#: ports/espressif/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Characteristic.c +#: ports/zephyr-cp/common-hal/_bleio/Characteristic.c +msgid "No CCCD for this Characteristic" msgstr "" +#: ports/espressif/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Characteristic.c +msgid "Can't set CCCD on local Characteristic" +msgstr "Δεν μπορεί να οριστεί CCCD σε τοπικό Characteristic" + +#: ports/espressif/common-hal/_bleio/Connection.c #: ports/espressif/common-hal/_bleio/__init__.c #: ports/nordic/common-hal/_bleio/__init__.c -msgid "Insufficient authentication" +#: ports/zephyr-cp/common-hal/_bleio/Characteristic.c +#: ports/zephyr-cp/common-hal/_bleio/Connection.c +#: ports/zephyr-cp/common-hal/_bleio/Descriptor.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +#: shared-bindings/_bleio/CharacteristicBuffer.c +msgid "Not connected" msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/espressif/common-hal/_bleio/Connection.c #: ports/nordic/common-hal/_bleio/__init__.c -msgid "Insufficient encryption" +#: ports/zephyr-cp/common-hal/_bleio/Connection.c +msgid "" +"Unspecified issue. The pairing request on the other device may have been " +"declined or ignored." msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "Insufficient memory pool for the image" +#: ports/espressif/common-hal/_bleio/Connection.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/Connection.c +#, c-format +msgid "Unknown security error: 0x%04x" msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "Insufficient stream input buffer" +#: ports/espressif/common-hal/_bleio/Connection.c +msgid "No pairing in progress" msgstr "" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "Interface must be started" +#: ports/espressif/common-hal/_bleio/Connection.c +#: ports/nordic/common-hal/_bleio/Connection.c +msgid "non-UUID found in service_uuids_whitelist" msgstr "" -#: ports/atmel-samd/audio_dma.c ports/raspberrypi/audio_dma.c -msgid "Internal audio buffer too small" +#: ports/espressif/common-hal/_bleio/Descriptor.c +#: ports/nordic/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Descriptor.c +#, c-format +msgid "max_length must be 0-%d when fixed_length is %s" msgstr "" -#: ports/stm/common-hal/busio/UART.c -msgid "Internal define error" +#: ports/espressif/common-hal/_bleio/PacketBuffer.c +#: ports/nordic/common-hal/_bleio/PacketBuffer.c +#: ports/zephyr-cp/common-hal/_bleio/PacketBuffer.c +msgid "Writes not supported on Characteristic" msgstr "" -#: shared-bindings/pwmio/PWMOut.c shared-module/os/getenv.c -msgid "Internal error" +#: ports/espressif/common-hal/_bleio/PacketBuffer.c +#: ports/nordic/common-hal/_bleio/PacketBuffer.c +#: ports/zephyr-cp/common-hal/_bleio/PacketBuffer.c +msgid "Total data to write is larger than %q" msgstr "" -#: shared-module/rgbmatrix/RGBMatrix.c -#, c-format -msgid "Internal error #%d" +#: ports/espressif/common-hal/_bleio/__init__.c +msgid "Nimble out of memory" msgstr "" -#: ports/atmel-samd/common-hal/alarm/pin/PinAlarm.c -#: ports/atmel-samd/common-hal/countio/Counter.c -#: ports/atmel-samd/common-hal/frequencyio/FrequencyIn.c -#: ports/atmel-samd/common-hal/max3421e/Max3421E.c -#: ports/atmel-samd/common-hal/ps2io/Ps2.c -#: ports/atmel-samd/common-hal/pulseio/PulseIn.c -#: ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.c -#: ports/cxd56/common-hal/pulseio/PulseIn.c -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c -#: shared-bindings/pwmio/PWMOut.c -msgid "Internal resource(s) in use" +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +msgid "Invalid BLE parameter" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Internal watchdog timer expired." +#: ports/espressif/common-hal/_bleio/__init__.c +#: shared-module/audiofilewriter/AudioFileWriter.c +msgid "Already in progress" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Interrupt error." +#: ports/espressif/common-hal/_bleio/__init__.c +#, c-format +msgid "Unknown BLE error at %s:%d: 0x%04x" msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "Interrupted by output function" +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#, c-format +msgid "Unknown BLE error: 0x%04x" msgstr "" -#: ports/espressif/common-hal/_bleio/Service.c -#: ports/espressif/common-hal/espulp/ULP.c -#: ports/espressif/common-hal/microcontroller/Processor.c -#: ports/mimxrt10xx/common-hal/audiobusio/__init__.c -#: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c -#: ports/raspberrypi/bindings/picodvi/Framebuffer.c -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c py/argcheck.c -#: shared-bindings/digitalio/DigitalInOut.c -#: shared-bindings/epaperdisplay/EPaperDisplay.c shared-bindings/pwmio/PWMOut.c -#: shared-module/aurora_epaper/aurora_framebuffer.c -msgid "Invalid %q" +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +msgid "%q not permitted" msgstr "" -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c -#: shared-module/aurora_epaper/aurora_framebuffer.c -msgid "Invalid %q and %q" +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +msgid "Insufficient authentication" msgstr "" -#: ports/atmel-samd/common-hal/microcontroller/Pin.c -#: ports/espressif/common-hal/dotclockframebuffer/DotClockFramebuffer.c -#: ports/mimxrt10xx/common-hal/microcontroller/Pin.c -#: shared-bindings/microcontroller/Pin.c -msgid "Invalid %q pin" +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +msgid "Insufficient authorization" msgstr "" -#: ports/stm/common-hal/analogio/AnalogIn.c -msgid "Invalid ADC Unit value" +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +msgid "Insufficient encryption" msgstr "" #: ports/espressif/common-hal/_bleio/__init__.c #: ports/nordic/common-hal/_bleio/__init__.c -msgid "Invalid BLE parameter" +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +#, c-format +msgid "Unknown gatt error: 0x%04x" msgstr "" -#: shared-bindings/wifi/Radio.c -msgid "Invalid BSSID" -msgstr "" +#: ports/espressif/common-hal/alarm/pin/PinAlarm.c +msgid "Cannot wake on pin edge. Only level." +msgstr "Δεν μπορεί να γίνει αφύπνηση σε pin edge. Μόνο level." -#: shared-bindings/wifi/Radio.c -msgid "Invalid MAC address" -msgstr "" +#: ports/espressif/common-hal/alarm/pin/PinAlarm.c +msgid "Cannot pull on input-only pin." +msgstr "Δεν γίνεται pull σε pin μόνο για εισόδο." -#: ports/espressif/common-hal/espidf/__init__.c py/moderrno.c -msgid "Invalid argument" -msgstr "" +#: ports/espressif/common-hal/alarm/pin/PinAlarm.c +msgid "Can only alarm on two low pins from deep sleep." +msgstr "Μπορεί να γίνει alarm μόνο σε δύο low pins σε βαθύ ύπνο." -#: shared-module/displayio/Bitmap.c -msgid "Invalid bits per value" +#: ports/espressif/common-hal/alarm/pin/PinAlarm.c +msgid "Can only alarm on one low pin while others alarm high from deep sleep." msgstr "" +"Μόνο ένα alarm από low pin ενώ τα άλλα alarm θα είναι απο high σε βαθύ ύπνο." -#: shared-module/os/getenv.c -#, c-format -msgid "Invalid byte %.*s" +#: ports/espressif/common-hal/alarm/pin/PinAlarm.c +msgid "Can only alarm on RTC IO from deep sleep." +msgstr "Μόνο IO alarm ή RTC επιτρέπονται από βαθύ ύπνο." + +#: ports/espressif/common-hal/alarm/time/TimeAlarm.c +#: ports/raspberrypi/common-hal/alarm/time/TimeAlarm.c +msgid "Only one alarm.time alarm can be set." msgstr "" -#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c -#, c-format -msgid "Invalid data_pins[%d]" +#: ports/espressif/common-hal/alarm/touch/TouchAlarm.c +msgid "Only one %q can be set in deep sleep." msgstr "" -#: shared-module/msgpack/__init__.c -msgid "Invalid format" +#: ports/espressif/common-hal/analogbufio/BufferedIn.c +msgid "%q must be array of type 'H'" +msgstr "%q πρέπει να είναι πίνακας τύπου 'H'" + +#: ports/espressif/common-hal/audiobusio/PDMIn.c +#: shared-bindings/audioi2sin/I2SIn.c shared-bindings/usb_host_audio/USBIn.c +msgid "%q must be 8, 16, 24, or 32" msgstr "" -#: shared-module/audiocore/WaveFile.c -msgid "Invalid format chunk size" +#: ports/espressif/common-hal/audiobusio/__init__.c +#: ports/espressif/common-hal/audioi2sin/I2SIn.c +#: ports/espressif/common-hal/mii/Ethernet.c shared-bindings/emmcio/EMMC.c +msgid "Peripheral in use" msgstr "" -#: shared-bindings/wifi/Radio.c -msgid "Invalid hex password" +#: ports/espressif/common-hal/audioi2sin/I2SIn.c +#: ports/raspberrypi/common-hal/audioi2sin/I2SIn.c +msgid "%q must be 8 or 16" msgstr "" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "Invalid multicast MAC address" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "audio format not supported" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Invalid size" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to start async audio" msgstr "" -#: shared-module/ssl/SSLSocket.c -msgid "Invalid socket for TLS" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to create continuous channels: invalid arg" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -#: ports/nordic/common-hal/_bleio/__init__.c -msgid "Invalid state" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to create continuous channels: invalid state" msgstr "" -#: shared-module/os/getenv.c -msgid "Invalid unicode escape" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to create continuous channels: not found" msgstr "" -#: shared-bindings/aesio/aes.c -msgid "Key must be 16, 24, or 32 bytes long" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to create continuous channels: no mem" msgstr "" -#: shared-module/os/getenv.c -msgid "Key not found" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to register continuous events callback" msgstr "" -#: shared-module/is31fl3741/FrameBuffer.c -msgid "LED mappings must match display size" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to enable continuous" msgstr "" -#: py/compile.c -msgid "LHS of keyword arg must be an id" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Can't construct AudioOut because continuous channel already open" msgstr "" -#: shared-module/displayio/Group.c -msgid "Layer already in a group" +#: ports/espressif/common-hal/audioio/AudioOut.c +#: ports/espressif/common-hal/mipicsi/Camera.c +#: shared-module/videocore/VideoBuffer.c shared-module/videogif/GifDecoder.c +msgid "already playing" msgstr "" -#: shared-module/displayio/Group.c -msgid "Layer must be a Group or TileGrid subclass" +#: ports/espressif/common-hal/busio/I2C.c +#: ports/espressif/common-hal/i2ctarget/I2CTarget.c +#: ports/nordic/common-hal/busio/I2C.c ports/zephyr-cp/common-hal/busio/I2C.c +msgid "All I2C peripherals are in use" +msgstr "Όλα τα I2C περιφεριακά ειναι σε χρήση" + +#: ports/espressif/common-hal/busio/I2C.c +#: ports/espressif/common-hal/busio/SPI.c +msgid "Unable to create lock" msgstr "" -#: shared-bindings/audiocore/RawSample.c -msgid "Length of %q must be an even multiple of channel_count * type_size" +#: ports/espressif/common-hal/busio/SPI.c +msgid "SPI configuration failed" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "MAC address was invalid" -msgstr "" +#: ports/espressif/common-hal/busio/SPI.c ports/nordic/common-hal/busio/SPI.c +#: ports/zephyr-cp/common-hal/async_spi/SPI.c +msgid "All SPI peripherals are in use" +msgstr "Όλα τα SPI περιφεριακά είναι σε χρήση" -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/espressif/common-hal/_bleio/Descriptor.c -msgid "MITM security not supported" -msgstr "" +#: ports/espressif/common-hal/busio/SPI.c +#: ports/espressif/common-hal/canio/CAN.c +#: ports/espressif/common-hal/qspibus/QSPIBus.c +msgid "ESP-IDF memory allocation failed" +msgstr "ESP-IDF δέσμευση μνήμης απέτυχε" -#: shared-bindings/is31fl3741/IS31FL3741.c -msgid "Mapping must be a tuple" -msgstr "" +#: ports/espressif/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c +msgid "Cannot specify RTS or CTS in RS485 mode" +msgstr "Δεν μπορεί να οριστεί RTS ή CTS σε RS485 mode" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Mismatched data size" +#: ports/espressif/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c +msgid "RS485 inversion specified when not in RS485 mode" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Mismatched swap flag" -msgstr "" +#: ports/espressif/common-hal/canio/CAN.c +msgid "Baudrate not supported by peripheral" +msgstr "Baudrate δεν υποστηρίζεται από την περιφεριακή συσκευή" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_in_pin. %q[%u] reads pin(s)" -msgstr "" +#: ports/espressif/common-hal/canio/CAN.c +msgid "All CAN peripherals are in use" +msgstr "Όλα τα περιφεριακά CAN είναι σε χρήση" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_in_pin. %q[%u] shifts in from pin(s)" +#: ports/espressif/common-hal/canio/CAN.c +msgid "loopback + silent mode not supported by peripheral" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_in_pin. %q[%u] waits based on pin" +#: ports/espressif/common-hal/canio/CAN.c +#, c-format +msgid "twai_driver_install returned esp-idf error #%d" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_out_pin. %q[%u] shifts out to pin(s)" +#: ports/espressif/common-hal/canio/CAN.c +#, c-format +msgid "twai_start returned esp-idf error #%d" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_out_pin. %q[%u] writes pin(s)" +#: ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "ds_params has the wrong length" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_set_pin. %q[%u] sets pin(s)" +#: ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "" +"This key already committed to a different algorithm; call " +"load_digital_signature_key() again to use a different one" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing jmp_pin. %q[%u] jumps on pin" +#: ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "" +"This key's ds_params were replaced by a later load_digital_signature_key() " +"call for the same key slot" msgstr "" -#: shared-module/storage/__init__.c -msgid "Mount point directory missing" +#: ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "ds_params is invalid for this key slot" msgstr "" -#: ports/zephyr-cp/bindings/zephyr_serial/UART.c shared-bindings/busio/UART.c -#: shared-bindings/displayio/Group.c -msgid "Must be a %q subclass." +#: ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "Digital Signature peripheral not available on this chip" msgstr "" #: ports/espressif/common-hal/dotclockframebuffer/DotClockFramebuffer.c msgid "Must provide 5/6/5 RGB pins" msgstr "" -#: ports/mimxrt10xx/common-hal/busio/SPI.c shared-bindings/busio/SPI.c -msgid "Must provide MISO or MOSI pin" +#: ports/espressif/common-hal/dualbank/__init__.c +msgid "Firmware is duplicate" msgstr "" -#: shared-bindings/rgbmatrix/RGBMatrix.c -#, c-format -msgid "Must use a multiple of 6 rgb pins, not %d" +#: ports/espressif/common-hal/dualbank/__init__.c +msgid "Firmware is invalid" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "NLR jump failed. Likely memory corruption." +#: ports/espressif/common-hal/dualbank/__init__.c +msgid "Firmware is too big" msgstr "" -#: ports/espressif/common-hal/nvm/ByteArray.c -msgid "NVS Error" +#: ports/espressif/common-hal/espcamera/Camera.c py/objobject.c py/runtime.c +msgid "no such attribute" msgstr "" -#: shared-bindings/socketpool/SocketPool.c -msgid "Name or service not known" +#: ports/espressif/common-hal/espcamera/Camera.c +msgid "invalid setting" msgstr "" -#: shared-bindings/displayio/TileGrid.c -msgid "New bitmap must be same size as old bitmap" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "Generic Failure" msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -msgid "Nimble out of memory" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "Out of memory" msgstr "" -#: ports/atmel-samd/common-hal/busio/UART.c -#: ports/espressif/common-hal/busio/SPI.c -#: ports/espressif/common-hal/busio/UART.c -#: ports/mimxrt10xx/common-hal/busio/SPI.c -#: ports/mimxrt10xx/common-hal/busio/UART.c -#: ports/nordic/common-hal/busio/UART.c -#: ports/raspberrypi/common-hal/busio/UART.c ports/stm/common-hal/busio/SPI.c -#: ports/stm/common-hal/busio/UART.c shared-bindings/fourwire/FourWire.c -#: shared-bindings/i2cdisplaybus/I2CDisplayBus.c -#: shared-bindings/paralleldisplaybus/ParallelBus.c -#: shared-module/bitbangio/SPI.c -msgid "No %q pin" +#: ports/espressif/common-hal/espidf/__init__.c py/moderrno.c +msgid "Invalid argument" msgstr "" -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Characteristic.c -msgid "No CCCD for this Characteristic" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "Invalid size" msgstr "" -#: ports/atmel-samd/common-hal/analogio/AnalogOut.c -#: ports/stm/common-hal/analogio/AnalogOut.c -msgid "No DAC on chip" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "Requested resource not found" 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" +#: ports/espressif/common-hal/espidf/__init__.c +#: ports/espressif/common-hal/jpegio/JpegDecoder.c +#: ports/raspberrypi/common-hal/usb_host_bulk/InStream.c +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +#: shared-bindings/picogame/Canvas.c shared-bindings/picogame/__init__.c +#: shared-module/jpegio/JpegDecoder.c shared-module/picogame/Display.c +msgid "Operation or feature not supported" msgstr "" -#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c -msgid "No DMA pacing timer found" +#: ports/espressif/common-hal/espidf/__init__.c +#: ports/espressif/common-hal/qspibus/QSPIBus.c +#: shared-module/_airlift/__init__.c +msgid "Operation timed out" msgstr "" -#: shared-module/adafruit_bus_device/i2c_device/I2CDevice.c -#, c-format -msgid "No I2C device at address: 0x%x" +#: ports/espressif/common-hal/espidf/__init__.c +#: shared-module/_airlift/__init__.c +msgid "Received response was invalid" msgstr "" -#: supervisor/shared/web_workflow/web_workflow.c -msgid "No IP" -msgstr "" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "CRC or checksum was invalid" +msgstr "CRC ή checksum ήταν άκυρο" -#: ports/atmel-samd/common-hal/microcontroller/__init__.c -#: ports/cxd56/common-hal/microcontroller/__init__.c -#: ports/mimxrt10xx/common-hal/microcontroller/__init__.c -msgid "No bootloader present" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "Version was invalid" msgstr "" -#: shared-module/usb/core/Device.c -msgid "No configuration set" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "MAC address was invalid" msgstr "" -#: shared-bindings/_bleio/PacketBuffer.c -msgid "No connection: length cannot be determined" -msgstr "" +#: ports/espressif/common-hal/espidf/__init__.c +#, c-format +msgid "%s error 0x%x" +msgstr "%s σφάλμα 0x%x" -#: shared-bindings/board/__init__.c -msgid "No default %q bus" +#: ports/espressif/common-hal/espulp/ULP.c +msgid "Program too long" msgstr "" -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c -#: ports/atmel-samd/common-hal/touchio/TouchIn.c -msgid "No free GCLKs" +#: ports/espressif/common-hal/espulp/ULP.c +#: ports/espressif/common-hal/mipidsi/Bus.c +#: ports/espressif/common-hal/qspibus/QSPIBus.c +#: ports/mimxrt10xx/common-hal/audiobusio/__init__.c +#: ports/mimxrt10xx/common-hal/usb_host/Port.c +#: ports/raspberrypi/common-hal/picodvi/AudioOut.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#: ports/raspberrypi/common-hal/usb_host/Port.c +#: shared-bindings/digitalio/DigitalInOut.c shared-bindings/emmcio/EMMC.c +#: shared-bindings/i2cioexpander/IOPin.c shared-bindings/microcontroller/Pin.c +#: shared-module/_airlift/__init__.c +#: shared-module/epaperdisplay/EPaperDisplay.c +#: shared-module/max3421e/Max3421E.c shared-module/usb/core/Device.c +#: shared-module/usb_host_audio/USBIn.c +msgid "%q in use" +msgstr "%q είναι σε χρήση" + +#: ports/espressif/common-hal/espulp/ULPAlarm.c +msgid "Only one %q can be set." msgstr "" -#: shared-bindings/os/__init__.c -msgid "No hardware random available" +#: ports/espressif/common-hal/i2ctarget/I2CTarget.c +#: ports/raspberrypi/common-hal/i2ctarget/I2CTarget.c +msgid "Only one address is allowed" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "No in in program" +#: ports/espressif/common-hal/max3421e/Max3421E.c +#: ports/raspberrypi/common-hal/wifi/__init__.c +#, c-format +msgid "Unknown error code %d" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "No in or out in program" +#: ports/espressif/common-hal/mdns/Server.c +#: ports/raspberrypi/common-hal/mdns/Server.c +msgid "mDNS only works with built-in WiFi" msgstr "" -#: py/objint.c shared-bindings/time/__init__.c -msgid "No long integer support" +#: ports/espressif/common-hal/mdns/Server.c +#: ports/raspberrypi/common-hal/mdns/Server.c +msgid "mDNS already initialized" msgstr "" -#: shared-bindings/wifi/Radio.c -msgid "No network with that ssid" +#: ports/espressif/common-hal/mdns/Server.c +#: ports/raspberrypi/common-hal/mdns/Server.c +msgid "Unable to start mDNS query" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "No out in program" +#: ports/espressif/common-hal/memorymap/AddressRange.c +#: ports/nordic/common-hal/memorymap/AddressRange.c +#: ports/raspberrypi/common-hal/memorymap/AddressRange.c +msgid "Address range not allowed" +msgstr "Εμβέλεια διευθύνσεων δεν επιτρέπεται" + +#: ports/espressif/common-hal/mipicsi/Camera.c +#: shared-bindings/displayio/TileGrid.c shared-bindings/terminalio/Terminal.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-bindings/vectorio/VectorShape.c +msgid "unsupported %q type" msgstr "" -#: ports/atmel-samd/common-hal/busio/I2C.c -#: ports/espressif/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nordic/common-hal/busio/I2C.c -#: ports/raspberrypi/common-hal/busio/I2C.c -msgid "No pull up found on SDA or SCL; check your wiring" +#: ports/espressif/common-hal/mipicsi/Camera.c +msgid "output_format must be RGB565 or RGB888" msgstr "" -#: shared-module/touchio/TouchIn.c -msgid "No pulldown on pin; 1Mohm recommended" +#: ports/espressif/common-hal/mipicsi/Camera.c +msgid "ISP conversion not supported on this chip" msgstr "" -#: py/moderrno.c -msgid "No space left on device" +#: ports/espressif/common-hal/mipidsi/Bus.c +msgid "%q is above %u" msgstr "" -#: py/moderrno.c -msgid "No such device" +#: ports/espressif/common-hal/mipidsi/Bus.c +msgid "%q is not reachable by the PHY" msgstr "" -#: py/moderrno.c -msgid "No such file/directory" +#: ports/espressif/common-hal/nvm/ByteArray.c +msgid "NVS Error" msgstr "" -#: shared-module/rgbmatrix/RGBMatrix.c -msgid "No timer available" +#: ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c +#: ports/espressif/common-hal/sdioio/SDCard.c +#, c-format +msgid "Number of data_pins must be %d or %d, not %d" msgstr "" -#: shared-module/usb/core/Device.c -msgid "No usb host port initialized" +#: ports/espressif/common-hal/pulseio/PulseIn.c +msgid "pop from an empty PulseIn" msgstr "" -#: ports/nordic/common-hal/_bleio/__init__.c -msgid "Nordic system firmware out of memory" +#: ports/espressif/common-hal/qspibus/QSPIBus.c +#: ports/raspberrypi/common-hal/usb_host_bulk/InStream.c +#: shared-module/usb/core/Device.c +msgid "Could not allocate DMA capable buffer" msgstr "" -#: shared-bindings/ipaddress/IPv4Address.c shared-bindings/ipaddress/__init__.c -msgid "Not a valid IP string" +#: ports/espressif/common-hal/qspibus/QSPIBus.c shared-bindings/pwmio/PWMOut.c +#: supervisor/shared/settings.c +msgid "Internal error" msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -#: ports/nordic/common-hal/_bleio/__init__.c -#: shared-bindings/_bleio/CharacteristicBuffer.c -msgid "Not connected" +#: ports/espressif/common-hal/rclcpy/Node.c +msgid "ROS node failed to initialize" msgstr "" -#: shared-bindings/audiobusio/I2SOut.c shared-bindings/audioio/AudioOut.c -#: shared-bindings/audiopwmio/PWMAudioOut.c -msgid "Not playing" +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "ROS topic failed to initialize" msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "Not supported JPEG standard" +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "Could not publish to ROS topic" msgstr "" -#: ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/espressif/common-hal/sdioio/SDCard.c +#: ports/espressif/common-hal/rclcpy/__init__.c #, c-format -msgid "Number of data_pins must be %d or %d, not %d" +msgid "Critical ROS failure during soft reboot, reset required: %d" msgstr "" -#: shared-bindings/util.c -msgid "" -"Object has been deinitialized and can no longer be used. Create a new object." +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS memory allocator failure" msgstr "" -#: ports/nordic/common-hal/busio/UART.c -msgid "Odd parity is not supported" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS internal setup failure" msgstr "" -#: supervisor/shared/bluetooth/bluetooth.c -msgid "Off" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "Invalid ROS domain ID" msgstr "" -#: supervisor/shared/bluetooth/bluetooth.c -msgid "Ok" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS failed to initialize. Is agent connected?" msgstr "" -#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c -#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c +#: ports/espressif/common-hal/sdioio/SDCard.c +#: ports/raspberrypi/common-hal/sdioio/SDCard.c +#: ports/stm/common-hal/sdioio/SDCard.c #, c-format -msgid "Only 8 or 16 bit mono with %dx oversampling supported." +msgid "SDIO Init Error 0x%02x" msgstr "" -#: ports/espressif/common-hal/wifi/__init__.c -#: ports/raspberrypi/common-hal/wifi/__init__.c -msgid "Only IPv4 addresses supported" +#: ports/espressif/common-hal/socketpool/Socket.c +#: ports/zephyr-cp/common-hal/socketpool/Socket.c +msgid "Unsupported socket type" msgstr "" +#: ports/espressif/common-hal/socketpool/Socket.c #: ports/raspberrypi/common-hal/socketpool/Socket.c -msgid "Only IPv4 sockets supported" +msgid "Out of sockets" msgstr "" -#: shared-module/displayio/OnDiskBitmap.c -#, c-format -msgid "" -"Only Windows format, uncompressed BMP supported: given header size is %d" +#: ports/espressif/common-hal/socketpool/SocketPool.c +msgid "SocketPool can only be used with %q.%q or any %q.%q" msgstr "" -#: shared-bindings/_bleio/Adapter.c -msgid "Only connectable advertisements can be directed" -msgstr "" +#: ports/espressif/common-hal/watchdog/WatchDogTimer.c +msgid "%q must be <= %u" +msgstr "%q πρέπει να είναι <= %u" -#: ports/stm/common-hal/alarm/pin/PinAlarm.c -msgid "Only edge detection is available on this hardware" +#: ports/espressif/common-hal/wifi/Monitor.c +msgid "monitor init failed" msgstr "" -#: shared-bindings/ipaddress/__init__.c -msgid "Only int or string supported for ip" +#: ports/espressif/common-hal/wifi/Radio.c +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "Interface must be started" msgstr "" -#: ports/espressif/common-hal/alarm/touch/TouchAlarm.c -msgid "Only one %q can be set in deep sleep." +#: ports/espressif/common-hal/wifi/Radio.c +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "Invalid multicast MAC address" msgstr "" -#: ports/espressif/common-hal/espulp/ULPAlarm.c -msgid "Only one %q can be set." -msgstr "" +#: ports/espressif/common-hal/wifi/Radio.c +#: ports/raspberrypi/common-hal/wifi/Radio.c +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "Already scanning for wifi networks" +msgstr "Ήδη γίνεται σάρωση για δίκτυα wifi" -#: ports/espressif/common-hal/i2ctarget/I2CTarget.c -#: ports/raspberrypi/common-hal/i2ctarget/I2CTarget.c -msgid "Only one address is allowed" +#: ports/espressif/common-hal/wifi/Radio.c +#: ports/espressif/common-hal/wifi/__init__.c +#: ports/raspberrypi/common-hal/wifi/Radio.c +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "WiFi is not enabled" msgstr "" -#: ports/atmel-samd/common-hal/alarm/time/TimeAlarm.c -#: ports/nordic/common-hal/alarm/time/TimeAlarm.c -#: ports/stm/common-hal/alarm/time/TimeAlarm.c -msgid "Only one alarm.time alarm can be set" +#: ports/espressif/common-hal/wifi/ScannedNetworks.c +msgid "Failed to allocate wifi scan memory" msgstr "" -#: ports/espressif/common-hal/alarm/time/TimeAlarm.c -#: ports/raspberrypi/common-hal/alarm/time/TimeAlarm.c -msgid "Only one alarm.time alarm can be set." +#: ports/espressif/common-hal/wifi/__init__.c +msgid "Failed to allocate Wifi memory" msgstr "" -#: shared-module/displayio/ColorConverter.c -msgid "Only one color can be transparent at a time" +#: ports/espressif/common-hal/wifi/__init__.c +#: ports/raspberrypi/common-hal/wifi/__init__.c +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "Only IPv4 addresses supported" msgstr "" -#: py/moderrno.c -msgid "Operation not permitted" +#: ports/mimxrt10xx/common-hal/busio/SPI.c +#: ports/raspberrypi/bindings/wiznet/PIO_SPI.c shared-bindings/async_spi/SPI.c +#: shared-bindings/busio/SPI.c +msgid "Must provide MISO or MOSI pin" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Operation or feature not supported" +#: ports/mimxrt10xx/common-hal/busio/SPI.c +#: ports/mimxrt10xx/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/canio/CAN.c 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 +#: shared-bindings/emmcio/EMMC.c +msgid "Hardware in use, try alternative pins" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Operation timed out" +#: ports/mimxrt10xx/common-hal/canio/CAN.c +msgid "Unable to send CAN Message: all Tx message buffers are busy" msgstr "" -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "Out of MDNS service slots" +#: ports/mimxrt10xx/common-hal/microcontroller/Processor.c +msgid "" +"Frequency must be 24, 150, 396, 450, 528, 600, 720, 816, 912, 960 or 1008 Mhz" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Out of memory" +#: ports/nordic/boards/aramcon2_badge/mpconfigboard.h +msgid "You pressed the left button at start up." msgstr "" -#: ports/espressif/common-hal/socketpool/Socket.c -#: ports/raspberrypi/common-hal/socketpool/Socket.c -#: ports/zephyr-cp/common-hal/socketpool/Socket.c -msgid "Out of sockets" +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "timeout must be < 655.35 secs" msgstr "" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "Out-buffer elements must be <= 4 bytes long" +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "non-zero timeout must be > 0.01" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "PWM restart" +#: ports/nordic/common-hal/_bleio/UUID.c +msgid "Unexpected nrfx uuid type" msgstr "" -#: ports/raspberrypi/common-hal/countio/Counter.c -msgid "PWM slice already in use" +#: ports/nordic/common-hal/_bleio/__init__.c +msgid "Nordic system firmware out of memory" msgstr "" -#: ports/raspberrypi/common-hal/countio/Counter.c -msgid "PWM slice channel A already in use" +#: ports/nordic/common-hal/_bleio/__init__.c +#, c-format +msgid "Unknown system firmware error: %04x" msgstr "" -#: shared-bindings/spitarget/SPITarget.c -msgid "Packet buffers for an SPI transfer must have the same length." -msgstr "" +#: ports/nordic/common-hal/alarm/pin/PinAlarm.c +msgid "Cannot wake on pin edge, only level" +msgstr "Δεν γίνεται αφύπνηση σε pin edge, αλλά μόνο σε level" -#: shared-module/jpegio/JpegDecoder.c -msgid "Parameter error" +#: ports/nordic/common-hal/audiobusio/I2SOut.c +msgid "Device in use" +msgstr "Συσκευή σε χρήση" + +#: ports/nordic/common-hal/audiobusio/PDMIn.c +#: ports/stm/common-hal/audiobusio/PDMIn.c +msgid "only sample_rate=16000 is supported" msgstr "" -#: ports/espressif/common-hal/audiobusio/__init__.c -msgid "Peripheral in use" +#: ports/nordic/common-hal/audiobusio/PDMIn.c +#: ports/stm/common-hal/audiobusio/PDMIn.c +msgid "only bit_depth=16 is supported" msgstr "" -#: py/moderrno.c -msgid "Permission denied" +#: ports/nordic/common-hal/busio/UART.c +#, c-format +msgid "error = 0x%08lX" msgstr "" -#: ports/stm/common-hal/alarm/pin/PinAlarm.c -msgid "Pin cannot wake from Deep Sleep" +#: ports/nordic/common-hal/busio/UART.c +msgid "Odd parity is not supported" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Pin count too large" +#: ports/nordic/common-hal/countio/Counter.c +#: ports/nordic/common-hal/pulseio/PulseIn.c +#: ports/nordic/common-hal/rotaryio/IncrementalEncoder.c +msgid "All channels in use" +msgstr "Όλα τα κανάλια είναι σε χρήση" + +#: ports/nordic/common-hal/microcontroller/Processor.c +msgid "Cannot get temperature" +msgstr "Δεν μπορεί να διαβαστεί η θερμοκρασία" + +#: ports/nordic/common-hal/watchdog/WatchDogTimer.c +msgid "timeout duration exceeded the maximum supported value" msgstr "" -#: ports/stm/common-hal/alarm/pin/PinAlarm.c -#: ports/stm/common-hal/pulseio/PulseIn.c -msgid "Pin interrupt already in use" +#: ports/nordic/common-hal/watchdog/WatchDogTimer.c +msgid "%q cannot be changed once mode is set to %q" msgstr "" -#: shared-bindings/adafruit_bus_device/spi_device/SPIDevice.c -msgid "Pin is input only" +#: ports/nordic/common-hal/watchdog/WatchDogTimer.c +msgid "WatchDogTimer cannot be deinitialized once mode is set to RESET" msgstr "" -#: ports/raspberrypi/common-hal/countio/Counter.c -msgid "Pin must be on PWM Channel B" +#: ports/nordic/sd_mutex.c +#, c-format +msgid "Failed to acquire mutex, err 0x%04x" msgstr "" -#: shared-bindings/rgbmatrix/RGBMatrix.c +#: ports/nordic/sd_mutex.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" +msgid "Failed to release mutex, err 0x%04x" msgstr "" -#: ports/raspberrypi/common-hal/imagecapture/ParallelImageCapture.c -msgid "Pins must be sequential" +#: ports/raspberrypi/audio_dma.c +msgid "Audio conversion not implemented" +msgstr "Η μετατροπή ήχου δεν υποστηρίζεται" + +#: ports/raspberrypi/bindings/cyw43/__init__.c py/argcheck.c py/objexcept.c +#: shared-bindings/bitmapfilter/__init__.c shared-bindings/canio/CAN.c +#: shared-bindings/digitalio/Pull.c shared-bindings/picogame/Sprite.c +#: shared-bindings/supervisor/__init__.c shared-module/audiofilters/__init__.c +#: shared-module/displayio/legacy/__init__.c +#: shared-module/synthio/Synthesizer.c shared-module/videocore/VideoBuffer.c +msgid "%q must be of type %q or %q, not %q" +msgstr "%q πρέπει να είναι τύπου %q ή %q, όχι %q" + +#: ports/raspberrypi/bindings/picodvi/AudioOut.c +#: shared-bindings/audiobusio/I2SOut.c shared-bindings/audioio/AudioOut.c +#: shared-bindings/audiopwmio/PWMAudioOut.c shared-bindings/mcp4822/MCP4822.c +#: shared-bindings/usb_audio/USBMicrophone.c +msgid "Not playing" msgstr "" -#: ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c -msgid "Pins must be sequential GPIO pins" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Program size invalid" msgstr "" -#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c -msgid "Pins must share PWM slice" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Init program size invalid" msgstr "" -#: shared-module/usb/core/Device.c -msgid "Pipe error" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Buffer elements must be 4 bytes long or less" +msgstr "Στοιχεία του buffer πρέπει να είναι το πολύ 4 bytes" + +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Mismatched data size" msgstr "" -#: py/builtinhelp.c -msgid "Plus any modules on the filesystem\n" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Out-buffer elements must be <= 4 bytes long" msgstr "" -#: shared-module/vectorio/Polygon.c -msgid "Polygon needs at least 3 points" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "In-buffer elements must be <= 4 bytes long" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Power dipped. Make sure you are providing enough power." +#: ports/raspberrypi/bindings/wiznet/PIO_SPI.c shared-bindings/async_spi/SPI.c +#: 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 "" -#: shared-bindings/_bleio/Adapter.c -msgid "Prefix buffer must be on the heap" +#: ports/raspberrypi/bindings/wiznet/PIO_SPI.c shared-bindings/async_spi/SPI.c +#: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c +msgid "buffer slices must be of equal length" msgstr "" -#: main.c -msgid "Press any key to enter the REPL. Use CTRL-D to reload.\n" +#: ports/raspberrypi/common-hal/alarm/touch/TouchAlarm.c +#: ports/stm/common-hal/alarm/touch/TouchAlarm.c +msgid "Touch alarms not available" msgstr "" -"Πατήστε οποιοδήποτε πλήκτρο για να μπείτε στο REPL. Πατήστε CTRL-D για " -"επαναφόρτωση.\n" -#: main.c -msgid "Pretending to deep sleep until alarm, CTRL-C or file write.\n" -msgstr "Προσποίηση βαθύ ύπνου μεχρι γεγονότος, CTRL-C ή εγγραφή αρχείου.\n" +#: ports/raspberrypi/common-hal/async_spi/SPI.c shared-bindings/emmcio/EMMC.c +msgid "SPI peripheral in use" +msgstr "" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audioi2sin/I2SIn.c #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Program does IN without loading ISR" +msgid "Cannot use GPIO0..15 together with GPIO32..47" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Program does OUT without loading OSR" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audioi2sin/I2SIn.c +msgid "Bit clock and word select must be sequential GPIO pins" +msgstr "Ρολόι bit και ορισμού λέξης πρέπει να είναι διαδοχικά GPIO pins" + +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/mcp4822/MCP4822.c +msgid "Too many channels in sample." msgstr "" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "Program size invalid" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +#: ports/raspberrypi/common-hal/mcp4822/MCP4822.c +msgid "Audio source error" msgstr "" -#: ports/espressif/common-hal/espulp/ULP.c -msgid "Program too long" +#: ports/raspberrypi/common-hal/audioi2sin/I2SIn.c +msgid "%q must be 16, 24, or 32" msgstr "" -#: shared-bindings/digitalio/DigitalInOut.c -msgid "Pull not used when direction is output." +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Pins must share PWM slice" msgstr "" -#: ports/raspberrypi/common-hal/countio/Counter.c -msgid "RISE_AND_FALL not available on this chip" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "No DMA pacing timer found" msgstr "" -#: shared-module/displayio/OnDiskBitmap.c -msgid "RLE-compressed BMP not supported" +#: ports/raspberrypi/common-hal/busio/I2C.c +#: ports/raspberrypi/common-hal/i2ctarget/I2CTarget.c +msgid "I2C peripheral in use" msgstr "" -#: ports/stm/common-hal/os/__init__.c -msgid "RNG DeInit Error" +#: ports/raspberrypi/common-hal/busio/UART.c +msgid "UART peripheral in use" msgstr "" -#: ports/stm/common-hal/os/__init__.c -msgid "RNG Init Error" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "Pin must be on PWM Channel B" msgstr "" -#: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c -#: ports/nordic/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c -msgid "RS485" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "RISE_AND_FALL not available on this chip" msgstr "" -#: ports/espressif/common-hal/busio/UART.c -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "RS485 inversion specified when not in RS485 mode" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice already in use" msgstr "" -#: shared-bindings/alarm/time/TimeAlarm.c shared-bindings/time/__init__.c -msgid "RTC is not supported on this board" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice channel A already in use" msgstr "" -#: ports/stm/common-hal/os/__init__.c -msgid "Random number generation error" -msgstr "" +#: ports/raspberrypi/common-hal/floppyio/__init__.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#: ports/raspberrypi/common-hal/usb_host/Port.c +msgid "All state machines in use" +msgstr "Όλες οι μηχανές κατάστασης είναι σε χρήση" -#: shared-bindings/_bleio/__init__.c -#: shared-bindings/memorymonitor/AllocationSize.c -#: shared-bindings/pulseio/PulseIn.c shared-module/bitmaptools/__init__.c -#: shared-module/displayio/Bitmap.c shared-module/displayio/Group.c -msgid "Read-only" +#: ports/raspberrypi/common-hal/floppyio/__init__.c +msgid "timeout waiting for flux" msgstr "" -#: extmod/vfs_fat.c py/moderrno.c -msgid "Read-only filesystem" +#: ports/raspberrypi/common-hal/floppyio/__init__.c +#: shared-module/floppyio/__init__.c +msgid "timeout waiting for index pulse" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Received response was invalid" +#: ports/raspberrypi/common-hal/imagecapture/ParallelImageCapture.c +msgid "Pins must be sequential" msgstr "" -#: supervisor/shared/bluetooth/bluetooth.c -msgid "Reconnecting" +#: ports/raspberrypi/common-hal/mcp4822/MCP4822.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c +#: shared-module/aurora_epaper/aurora_framebuffer.c +msgid "Invalid %q and %q" msgstr "" -#: shared-bindings/epaperdisplay/EPaperDisplay.c -msgid "Refresh too soon" +#: ports/raspberrypi/common-hal/mdns/Server.c +msgid "Out of MDNS service slots" msgstr "" -#: shared-bindings/canio/RemoteTransmissionRequest.c -msgid "RemoteTransmissionRequests limited to 8 bytes" +#: ports/raspberrypi/common-hal/memorymap/AddressRange.c +msgid "Unable to access unaligned IO register" msgstr "" -#: shared-bindings/aesio/aes.c -msgid "Requested AES mode is unsupported" +#: ports/raspberrypi/common-hal/memorymap/AddressRange.c +msgid "Unable to write to read-only memory" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Requested resource not found" -msgstr "" +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c +msgid "All timers for this pin are in use" +msgstr "Όλοι οι χρονιστές για αυτό το pin χρησιμοποιούνται ήδη" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c -msgid "Right channel unsupported" +#: ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c +msgid "Pins must be sequential GPIO pins" msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "Right format but not supported" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Pin count too large" msgstr "" -#: main.c -msgid "Running in safe mode! Not running saved code.\n" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing jmp_pin. %q[%u] jumps on pin" msgstr "" -#: shared-module/sdcardio/SDCard.c -msgid "SD card CSD format not supported" -msgstr "" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "%q[%u] uses extra pin" +msgstr "%q[%u] χρησιμοποιεί παραπάνω pin" -#: ports/cxd56/common-hal/sdioio/SDCard.c -msgid "SDCard init" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_in_pin. %q[%u] waits based on pin" msgstr "" -#: ports/stm/common-hal/sdioio/SDCard.c -#, c-format -msgid "SDIO GetCardInfo Error %d" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "%q[%u] waits on input outside of count" msgstr "" -#: ports/espressif/common-hal/sdioio/SDCard.c -#: ports/stm/common-hal/sdioio/SDCard.c -#, c-format -msgid "SDIO Init Error %x" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_in_pin. %q[%u] shifts in from pin(s)" msgstr "" -#: ports/espressif/common-hal/busio/SPI.c -msgid "SPI configuration failed" -msgstr "" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "%q[%u] shifts in more bits than pin count" +msgstr "%q[%u] μετατοπίζει σε περισσότερα bits από αριθμό pin" -#: ports/stm/common-hal/busio/SPI.c -msgid "SPI init error" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_out_pin. %q[%u] shifts out to pin(s)" msgstr "" -#: ports/raspberrypi/common-hal/busio/SPI.c -msgid "SPI peripheral in use" -msgstr "" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "%q[%u] shifts out more bits than pin count" +msgstr "%q[%u] μετατοπίζει από περισσότερα bits από αριθμό pin" -#: ports/stm/common-hal/busio/SPI.c -msgid "SPI re-init" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_set_pin. %q[%u] sets pin(s)" msgstr "" -#: shared-bindings/is31fl3741/FrameBuffer.c -msgid "Scale dimensions must divide by 3" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_out_pin. %q[%u] writes pin(s)" msgstr "" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Scan already in progress. Stop with stop_scan." +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_in_pin. %q[%u] reads pin(s)" msgstr "" -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c -msgid "Serializer in use" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Program does IN without loading ISR" msgstr "" -#: shared-bindings/ssl/SSLContext.c -msgid "Server side context cannot have hostname" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Program does OUT without loading OSR" msgstr "" -#: ports/cxd56/common-hal/camera/Camera.c -msgid "Size not supported" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin state conflicts with initial out pin state" msgstr "" -#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c -#: shared-bindings/nvm/ByteArray.c -msgid "Slice and value different lengths." +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin direction conflicts with initial out pin direction" msgstr "" -#: 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" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "pull masks conflict with direction masks" msgstr "" -#: ports/espressif/common-hal/socketpool/SocketPool.c -#: ports/raspberrypi/common-hal/socketpool/SocketPool.c -#: ports/zephyr-cp/common-hal/socketpool/SocketPool.c -msgid "SocketPool can only be used with wifi.radio" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No out in program" msgstr "" -#: shared-bindings/aesio/aes.c -msgid "Source and destination buffers must be the same length" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in in program" msgstr "" -#: shared-bindings/paralleldisplaybus/ParallelBus.c -msgid "Specify exactly one of data0 or data_pins" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in or out in program" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Stack overflow. Increase stack size." +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Mismatched swap flag" msgstr "" -#: shared-bindings/alarm/time/TimeAlarm.c -msgid "Supply one of monotonic_time or epoch_time" +#: ports/raspberrypi/common-hal/sdioio/SDCard.c +#, c-format +msgid "Number of data_pins must be %d, not %d" msgstr "" -#: shared-bindings/gnss/GNSS.c -msgid "System entry must be gnss.SatelliteSystem" +#: ports/raspberrypi/common-hal/sdioio/SDCard.c +msgid "Data pins must be consecutive" msgstr "" -#: ports/stm/common-hal/microcontroller/Processor.c -msgid "Temperature read timed out" +#: ports/raspberrypi/common-hal/socketpool/Socket.c +msgid "Only IPv4 sockets supported" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "The `microcontroller` module was used to boot into safe mode." +#: ports/raspberrypi/common-hal/socketpool/SocketPool.c +msgid "SocketPool can only be used with wifi.radio" msgstr "" -#: py/obj.c -msgid "The above exception was the direct cause of the following exception:" -msgstr "" +#: ports/raspberrypi/common-hal/usb_host/Port.c +msgid "All dma channels in use" +msgstr "Όλα τα κανάλια dma είναι σε χρήση" -#: shared-bindings/rgbmatrix/RGBMatrix.c -msgid "The length of rgb_pins must be 6, 12, 18, 24, or 30" +#: ports/raspberrypi/common-hal/wifi/Monitor.c +msgid "wifi.Monitor not available" msgstr "" -#: shared-module/audiocore/__init__.c -msgid "The sample's %q does not match" -msgstr "" +#: ports/raspberrypi/common-hal/wifi/Radio.c +msgid "%q is read-only for this board" +msgstr "%q είναι μόνο για ανάγνωση για αυτήν την πλακέτα" -#: supervisor/shared/safe_mode.c -msgid "Third-party firmware fatal error." -msgstr "" +#: ports/raspberrypi/common-hal/wifi/Radio.c +msgid "AP could not be started" +msgstr "AP δεν μπόρεσε να εκκινηθεί" -#: shared-module/imagecapture/ParallelImageCapture.c -msgid "This microcontroller does not support continuous capture." +#: ports/stm/common-hal/alarm/pin/PinAlarm.c +msgid "Only edge detection is available on this hardware" msgstr "" -#: shared-module/paralleldisplaybus/ParallelBus.c -msgid "" -"This microcontroller only supports data0=, not data_pins=, because it " -"requires contiguous pins." +#: ports/stm/common-hal/alarm/pin/PinAlarm.c +#: ports/stm/common-hal/pulseio/PulseIn.c +msgid "Pin interrupt already in use" msgstr "" -#: shared-bindings/displayio/TileGrid.c -msgid "Tile height must exactly divide bitmap height" +#: ports/stm/common-hal/alarm/pin/PinAlarm.c +msgid "Pin cannot wake from Deep Sleep" msgstr "" -#: shared-bindings/displayio/TileGrid.c shared-module/displayio/TileGrid.c -msgid "Tile index out of bounds" -msgstr "" +#: ports/stm/common-hal/alarm/pin/PinAlarm.c +msgid "Deep sleep pins must use a rising edge with pulldown" +msgstr "Τα pins βαθύ ύπνου πρέπει να χρησιμοποιούν rising edge με pulldown" -#: shared-bindings/displayio/TileGrid.c -msgid "Tile width must exactly divide bitmap width" +#: ports/stm/common-hal/analogio/AnalogIn.c +msgid "Invalid ADC Unit value" msgstr "" -#: shared-bindings/alarm/time/TimeAlarm.c -msgid "Time is in the past." -msgstr "" +#: ports/stm/common-hal/analogio/AnalogOut.c +#: ports/stm/common-hal/audioio/AudioOut.c +msgid "DAC Device Init Error" +msgstr "Σφάλμα εκκίνησης συσκευής DAC" + +#: ports/stm/common-hal/analogio/AnalogOut.c +#: ports/stm/common-hal/audioio/AudioOut.c +msgid "DAC Channel Init Error" +msgstr "Σφάλμα εκκίνησης καναλιού DAC" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -#, c-format -msgid "Timeout is too long: Maximum timeout length is %d seconds" +#: ports/stm/common-hal/audiobusio/PDMIn.c +msgid "only mono is supported" msgstr "" -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -msgid "Too many channels in sample" +#: ports/stm/common-hal/audiobusio/PDMIn.c +msgid "only oversample=64 is supported" msgstr "" -#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c -msgid "Too many channels in sample." -msgstr "" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Another PWMAudioOut is already active" +msgstr "Και άλλο PWMAudioOut είναι σε χρήση" -#: ports/espressif/common-hal/_bleio/Characteristic.c -msgid "Too many descriptors" -msgstr "" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +#, c-format +msgid "Buffer length %d too big. It must be less than %d" +msgstr "Το μήκος buffer %d είναι πολύ μεγάλο. Πρέπει ν α είναι λιγότερο απο %d" -#: shared-module/displayio/__init__.c -msgid "Too many display busses; forgot displayio.release_displays() ?" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Failed to buffer the sample" msgstr "" -#: shared-module/displayio/__init__.c -msgid "Too many displays" +#: ports/stm/common-hal/busio/I2C.c +msgid "I2C init error" msgstr "" -#: ports/espressif/common-hal/_bleio/PacketBuffer.c -#: ports/nordic/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than %q" +#: ports/stm/common-hal/busio/SPI.c +msgid "SPI init error" msgstr "" -#: ports/raspberrypi/common-hal/alarm/touch/TouchAlarm.c -#: ports/stm/common-hal/alarm/touch/TouchAlarm.c -msgid "Touch alarms not available" +#: ports/stm/common-hal/busio/SPI.c +msgid "SPI re-init" msgstr "" -#: py/obj.c -msgid "Traceback (most recent call last):\n" +#: ports/stm/common-hal/busio/UART.c +msgid "Internal define error" msgstr "" #: ports/stm/common-hal/busio/UART.c -msgid "UART de-init" -msgstr "" +msgid "Could not start interrupt, RX busy" +msgstr "Δεν μπόρεσε να εκκινηθεί το interrupt, RX κατειλημμένο" -#: ports/cxd56/common-hal/busio/UART.c ports/espressif/common-hal/busio/UART.c #: ports/stm/common-hal/busio/UART.c -msgid "UART init" +msgid "UART write" msgstr "" -#: ports/raspberrypi/common-hal/busio/UART.c -msgid "UART peripheral in use" +#: ports/stm/common-hal/busio/UART.c +msgid "UART de-init" msgstr "" #: ports/stm/common-hal/busio/UART.c msgid "UART re-init" msgstr "" -#: ports/stm/common-hal/busio/UART.c -msgid "UART write" +#: ports/stm/common-hal/microcontroller/Processor.c +msgid "Temperature read timed out" msgstr "" -#: main.c -msgid "UID:" +#: ports/stm/common-hal/microcontroller/Processor.c +msgid "Voltage read timed out" msgstr "" -#: shared-module/usb_hid/Device.c -msgid "USB busy" +#: ports/stm/common-hal/os/__init__.c +msgid "RNG Init Error" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "USB devices need more endpoints than are available." +#: ports/stm/common-hal/os/__init__.c +msgid "Random number generation error" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "USB devices specify too many interface names." +#: ports/stm/common-hal/os/__init__.c +msgid "RNG DeInit Error" msgstr "" -#: shared-module/usb_hid/Device.c -msgid "USB error" +#: ports/stm/common-hal/pwmio/PWMOut.c +msgid "timer re-init" msgstr "" -#: shared-bindings/_bleio/UUID.c -msgid "UUID integer value must be 0-0xffff" +#: ports/stm/common-hal/pwmio/PWMOut.c +msgid "channel re-init" msgstr "" -#: shared-bindings/_bleio/UUID.c -msgid "UUID string not 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'" +#: ports/stm/common-hal/pwmio/PWMOut.c +msgid "PWM restart" msgstr "" -#: shared-bindings/_bleio/UUID.c -msgid "UUID value is not str, int or byte buffer" +#: ports/stm/common-hal/sdioio/SDCard.c +#, c-format +msgid "MMC/SDIO Clock Error %x" msgstr "" -#: ports/raspberrypi/common-hal/memorymap/AddressRange.c -msgid "Unable to access unaligned IO register" +#: ports/stm/common-hal/sdioio/SDCard.c +#, c-format +msgid "SDIO GetCardInfo Error %d" 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 "" +#: ports/zephyr-cp/bindings/zephyr_display/Display.c +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/epaperdisplay/EPaperDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +#: shared-bindings/mipidsi/Display.c +msgid "Display rotation must be in 90 degree increments" +msgstr "Η περιστροφή της οθόνη πρέπει να γίνεται σε βήματα 90 μοιρών" -#: supervisor/shared/safe_mode.c -msgid "Unable to allocate to the heap." -msgstr "" +#: ports/zephyr-cp/bindings/zephyr_display/Display.c +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/epaperdisplay/EPaperDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +msgid ".show(x) removed. Use .root_group = x" +msgstr ".show(x) αφαιρέθηκε. Χρησιμοποιήστε το .root_group = x" -#: ports/espressif/common-hal/busio/I2C.c -msgid "Unable to create lock" -msgstr "" +#: ports/zephyr-cp/bindings/zephyr_display/Display.c +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +msgid "Brightness not adjustable" +msgstr "H φωτεινότητα δεν μπορεί να προσαρμοστεί" -#: shared-module/i2cdisplaybus/I2CDisplayBus.c -#: shared-module/is31fl3741/IS31FL3741.c -#, c-format -msgid "Unable to find I2C Display at %x" -msgstr "" +#: ports/zephyr-cp/bindings/zephyr_display/Display.c py/argcheck.c +#: shared-bindings/busdisplay/BusDisplay.c shared-bindings/displayio/Bitmap.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +#: shared-bindings/is31fl3741/FrameBuffer.c +#: shared-bindings/rgbmatrix/RGBMatrix.c +msgid "%q must be %d-%d" +msgstr "%q πρέπει να είναι %d-%d" -#: py/parse.c -msgid "Unable to init parser" +#: ports/zephyr-cp/bindings/zephyr_display/Display.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +#: shared-module/busdisplay/legacy/BusDisplay.c +#: shared-module/framebufferio/legacy/FramebufferDisplay.c +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "Group already used" msgstr "" -#: shared-module/displayio/OnDiskBitmap.c -msgid "Unable to read color palette data" +#: ports/zephyr-cp/common-hal/_bleio/Adapter.c +msgid "Invalid advertising data" msgstr "" -#: ports/mimxrt10xx/common-hal/canio/CAN.c -msgid "Unable to send CAN Message: all Tx message buffers are busy" +#: ports/zephyr-cp/common-hal/async_spi/SPI.c +#: ports/zephyr-cp/common-hal/audiobusio/I2SOut.c +#: ports/zephyr-cp/common-hal/busio/I2C.c +#: ports/zephyr-cp/common-hal/busio/UART.c +msgid "Use device tree to define %q devices" msgstr "" -#: ports/espressif/common-hal/mdns/Server.c -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "Unable to start mDNS query" +#: ports/zephyr-cp/common-hal/mii/Ethernet.c +msgid "cannot construct ethernet interfaces; use board.ETHERNET" msgstr "" -#: shared-bindings/nvm/ByteArray.c -msgid "Unable to write to nvm." +#: ports/zephyr-cp/common-hal/socketpool/SocketPool.c +msgid "SocketPool can only be used with %q.%q, %q.%q, or %q.%q" msgstr "" -#: ports/raspberrypi/common-hal/memorymap/AddressRange.c -msgid "Unable to write to read-only memory" +#: ports/zephyr-cp/common-hal/usb_hid/Device.c shared-module/usb_hid/Device.c +msgid "USB error" msgstr "" -#: shared-bindings/alarm/SleepMemory.c -msgid "Unable to write to sleep_memory." +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "Failed to set hostname" msgstr "" -#: ports/nordic/common-hal/_bleio/UUID.c -msgid "Unexpected nrfx uuid type" -msgstr "" +#: ports/zephyr-cp/common-hal/zephyr_display/legacy/Display.c +#: ports/zephyr-cp/common-hal/zephyr_display/lvgl/Display.c +#: shared-module/busdisplay/legacy/BusDisplay.c +#: shared-module/framebufferio/legacy/FramebufferDisplay.c +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "Below minimum frame rate" +msgstr "Χαμηλότερο από το ελάχιστο frame rate" -#: ports/espressif/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown BLE error at %s:%d: %d" +#: py/argcheck.c +msgid "function doesn't take keyword arguments" msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c +#: py/argcheck.c py/bc.c py/objnamedtuple.c shared-bindings/_eve/__init__.c +#: shared-bindings/time/__init__.c #, c-format -msgid "Unknown BLE error: %d" +msgid "function takes %d positional arguments but %d were given" msgstr "" -#: ports/espressif/common-hal/max3421e/Max3421E.c -#: ports/raspberrypi/common-hal/wifi/__init__.c +#: py/argcheck.c #, c-format -msgid "Unknown error code %d" +msgid "function missing %d required positional arguments" msgstr "" -#: shared-bindings/wifi/Radio.c +#: py/argcheck.c #, c-format -msgid "Unknown failure %d" +msgid "function expected at most %d arguments, got %d" msgstr "" -#: ports/nordic/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown gatt error: 0x%04x" -msgstr "" +#: py/argcheck.c shared-bindings/wifi/Radio.c +msgid "'%q' argument required" +msgstr "'%q' όρισμα απαιτείται" -#: ports/atmel-samd/common-hal/alarm/pin/PinAlarm.c -#: supervisor/shared/safe_mode.c -msgid "Unknown reason." +#: py/argcheck.c +msgid "extra positional arguments given" msgstr "" -#: ports/nordic/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown security error: 0x%04x" +#: py/argcheck.c py/bc.c py/objnamedtuple.c +#: shared-bindings/traceback/__init__.c +msgid "unexpected keyword argument '%q'" msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown system firmware error at %s:%d: %d" +#: py/argcheck.c +msgid "extra keyword arguments given" msgstr "" -#: ports/nordic/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown system firmware error: %04x" +#: py/argcheck.c shared-bindings/_stage/__init__.c +#: shared-bindings/digitalio/DigitalInOut.c shared-bindings/picogame/__init__.c +msgid "argument num/types mismatch" msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown system firmware error: %d" +#: py/argcheck.c +msgid "keyword argument(s) not implemented - use normal args instead" msgstr "" -#: shared-bindings/adafruit_pixelbuf/PixelBuf.c -#: shared-module/_pixelmap/PixelMap.c -#, c-format -msgid "Unmatched number of items on RHS (expected %d, got %d)." -msgstr "" +#: py/argcheck.c +msgid "%q must be %d" +msgstr "%q πρέπει να είναι %d" -#: ports/nordic/common-hal/_bleio/__init__.c -msgid "" -"Unspecified issue. Can be that the pairing prompt on the other device was " -"declined or ignored." +#: py/argcheck.c +msgid "%q must be >= %d" +msgstr "%q πρέπει να είναι >= %d" + +#: py/argcheck.c shared-bindings/gifio/GifWriter.c +#: shared-module/_airlift/__init__.c +msgid "%q must be <= %d" +msgstr "%q πρέπει να είναι <= %d" + +#: py/argcheck.c py/runtime.c shared-bindings/bitmapfilter/__init__.c +#: shared-module/audiodelays/MultiTapDelay.c shared-module/synthio/Note.c +#: shared-module/synthio/__init__.c +msgid "%q must be of type %q, not %q" +msgstr "%q πρέπει να είναι τύπου %q, όχι %q" + +#: py/argcheck.c +msgid "%q length must be %d-%d" +msgstr "%q μήκος πρέπει να είναι %d-%d" + +#: py/argcheck.c +msgid "%q length must be >= %d" +msgstr "%q μήκος πρέπει να είναι >= %d" + +#: py/argcheck.c shared-module/_airlift/__init__.c +msgid "%q length must be <= %d" +msgstr "%q μήκος πρέπει να είναι <= %d" + +#: py/argcheck.c shared-bindings/usb_hid/Device.c +msgid "%q length must be %d" +msgstr "%q μήκος πρέπει να είναι %d" + +#: py/argcheck.c shared-module/audiofilters/__init__.c +msgid "%q in %q must be of type %q, not %q" +msgstr "%q στο %q πρέπει να είναι τύπου %q, όχι %q" + +#: py/asmthumb.c +msgid "too many locals for native method" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "Unsupported colorspace" +#: py/asmxtensa.c +msgid "ERROR: xtensa %q out of range" msgstr "" -#: shared-module/displayio/bus_core.c -msgid "Unsupported display bus type" +#: py/asmxtensa.c +msgid "ERROR: %q %q not word-aligned" msgstr "" -#: shared-module/audiocore/WaveFile.c -msgid "Unsupported format" +#: py/bc.c py/objnamedtuple.c +msgid "%q() takes %d positional arguments but %d were given" +msgstr "%q() παίρνει %d ορίσματα θέσεως αλλά %d δόθηκαν" + +#: py/bc.c py/objnamedtuple.c +msgid "function got multiple values for argument '%q'" msgstr "" -#: shared-bindings/hashlib/__init__.c -msgid "Unsupported hash algorithm" +#: py/bc.c +msgid "unexpected keyword argument" msgstr "" -#: ports/espressif/common-hal/socketpool/Socket.c -#: ports/zephyr-cp/common-hal/socketpool/Socket.c -msgid "Unsupported socket type" +#: py/bc.c +#, c-format +msgid "function missing required positional argument #%d" msgstr "" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/espressif/common-hal/dualbank/__init__.c -msgid "Update failed" +#: py/bc.c +msgid "function missing required keyword argument '%q'" msgstr "" -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Descriptor.c -msgid "Value length != required fixed length" +#: py/bc.c +msgid "function missing keyword-only argument" msgstr "" -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Descriptor.c -msgid "Value length > max_length" +#: py/binary.c py/objarray.c +msgid "bad typecode" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Version was invalid" +#: py/binary.c +msgid "integer out of range" msgstr "" -#: ports/stm/common-hal/microcontroller/Processor.c -msgid "Voltage read timed out" +#: py/builtinevex.c +msgid "bad compile mode" msgstr "" -#: main.c -msgid "WARNING: Your code filename has two extensions\n" +#: py/builtinhelp.c +msgid "Plus any modules on the filesystem\n" msgstr "" -#: ports/nordic/common-hal/watchdog/WatchDogTimer.c -msgid "WatchDogTimer cannot be deinitialized once mode is set to RESET" +#: py/builtinhelp.c +msgid "object " msgstr "" +#: py/builtinhelp.c +msgid " is of type %q\n" +msgstr " είναι τύπου %q\n" + #: py/builtinhelp.c #, c-format msgid "" @@ -2360,2097 +2696,2438 @@ msgid "" "To list built-in modules type `help(\"modules\")`.\n" msgstr "" -#: supervisor/shared/web_workflow/web_workflow.c -msgid "Wi-Fi: " +#: py/builtinimport.c +msgid "script compilation not supported" msgstr "" -#: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "Wifi is not enabled" +#: py/builtinimport.c +msgid "can't perform relative import" msgstr "" -#: main.c -msgid "Woken up by alarm.\n" +#: py/builtinimport.c +msgid "module not found" msgstr "" -#: ports/espressif/common-hal/_bleio/PacketBuffer.c -#: ports/nordic/common-hal/_bleio/PacketBuffer.c -msgid "Writes not supported on Characteristic" +#: py/builtinimport.c +msgid "no module named '%q'" msgstr "" -#: 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/meowmeow/mpconfigboard.h -msgid "You pressed both buttons at start up." +#: py/builtinimport.c +msgid "relative import" msgstr "" -#: ports/espressif/boards/m5stack_core_basic/mpconfigboard.h -#: ports/espressif/boards/m5stack_core_fire/mpconfigboard.h -#: ports/espressif/boards/m5stack_stick_c/mpconfigboard.h -#: ports/espressif/boards/m5stack_stick_c_plus/mpconfigboard.h -#: ports/espressif/boards/m5stack_stick_c_plus2/mpconfigboard.h -msgid "You pressed button A at start up." +#: py/compile.c +msgid "can't assign to expression" msgstr "" -#: ports/espressif/boards/m5stack_m5paper/mpconfigboard.h -msgid "You pressed button DOWN at start up." +#: py/compile.c +msgid "multiple *x in assignment" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "You pressed the BOOT button at start up" +#: py/compile.c +msgid "non-default argument follows default argument" msgstr "" -#: ports/espressif/boards/adafruit_feather_esp32c6_4mbflash_nopsram/mpconfigboard.h -#: ports/espressif/boards/adafruit_itsybitsy_esp32/mpconfigboard.h -#: ports/espressif/boards/waveshare_esp32_c6_lcd_1_47/mpconfigboard.h -msgid "You pressed the BOOT button at start up." +#: py/compile.c +msgid "invalid micropython decorator" msgstr "" -#: ports/espressif/boards/adafruit_huzzah32_breakout/mpconfigboard.h -msgid "You pressed the GPIO0 button at start up." +#: py/compile.c +msgid "invalid arch" msgstr "" -#: ports/espressif/boards/espressif_esp32_lyrat/mpconfigboard.h -msgid "You pressed the Rec button at start up." +#: py/compile.c +msgid "can't delete expression" msgstr "" -#: ports/espressif/boards/adafruit_feather_esp32_v2/mpconfigboard.h -msgid "You pressed the SW38 button at start up." -msgstr "" +#: py/compile.c +msgid "'break'/'continue' outside loop" +msgstr "'break'/'continue' εκτός επανάληψης" -#: ports/espressif/boards/hardkernel_odroid_go/mpconfigboard.h -#: ports/espressif/boards/vidi_x/mpconfigboard.h -msgid "You pressed the VOLUME button at start up." +#: py/compile.c +msgid "'return' outside function" +msgstr "'return' εκτός συνάρτησης" + +#: py/compile.c +msgid "import * not at module level" msgstr "" -#: ports/espressif/boards/m5stack_atom_echo/mpconfigboard.h -#: ports/espressif/boards/m5stack_atom_lite/mpconfigboard.h -#: ports/espressif/boards/m5stack_atom_matrix/mpconfigboard.h -#: ports/espressif/boards/m5stack_atom_u/mpconfigboard.h -msgid "You pressed the central button at start up." +#: py/compile.c +msgid "identifier redefined as global" msgstr "" -#: ports/nordic/boards/aramcon2_badge/mpconfigboard.h -msgid "You pressed the left button at start up." +#: py/compile.c +msgid "no binding for nonlocal found" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "You pressed the reset button during boot." +#: py/compile.c +msgid "identifier redefined as nonlocal" msgstr "" -#: supervisor/shared/micropython.c -msgid "[truncated due to length]" +#: py/compile.c +msgid "can't declare nonlocal in outer code" msgstr "" -#: py/objtype.c -msgid "__init__() should return None" +#: py/compile.c +msgid "default 'except' must be last" msgstr "" -#: py/objtype.c -#, c-format -msgid "__init__() should return None, not '%s'" +#: py/compile.c +msgid "async for/with outside async function" msgstr "" -#: py/objobject.c -msgid "__new__ arg must be a user-type" +#: py/compile.c +msgid "*x must be assignment target" +msgstr "*x πρέπει να είναι στόχος ανάθεσης" + +#: py/compile.c +msgid "super() can't find self" msgstr "" -#: extmod/modbinascii.c extmod/modhashlib.c py/objarray.c -msgid "a bytes-like object is required" +#: py/compile.c +msgid "* arg after **" +msgstr "* όρισμα μετά **" + +#: py/compile.c +msgid "* arg after kwarg" msgstr "" -#: shared-bindings/i2ctarget/I2CTarget.c -msgid "addresses is empty" +#: py/compile.c +msgid "too many args" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "already playing" +#: py/compile.c +msgid "LHS of keyword arg must be an id" msgstr "" #: py/compile.c -msgid "annotation must be an identifier" +msgid "positional arg after **" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "arange: cannot compute length" +#: py/compile.c +msgid "positional arg after keyword arg" msgstr "" -#: py/modbuiltins.c -msgid "arg is an empty sequence" +#: py/compile.c py/parse.c +msgid "invalid syntax" msgstr "" -#: py/objobject.c -msgid "arg must be user-type" +#: py/compile.c +msgid "expecting key:value for dict" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "argsort argument must be an ndarray" +#: py/compile.c +msgid "expecting just a value for set" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "argsort is not implemented for flattened arrays" +#: py/compile.c +msgid "'yield' outside function" +msgstr "'yield' εκτός συνάρτησης" + +#: py/compile.c +msgid "'yield from' inside async function" +msgstr "'yield from' εκτός ασύνχρονης συνάρτησης" + +#: py/compile.c +msgid "'await' outside function" +msgstr "'await' εκτός συνάρτησης" + +#: py/compile.c +msgid "unknown type '%q'" msgstr "" -#: extmod/ulab/code/numpy/random/random.c -msgid "argument must be None, an integer or a tuple of integers" +#: py/compile.c +msgid "annotation must be an identifier" msgstr "" #: py/compile.c msgid "argument name reused" msgstr "" -#: py/argcheck.c shared-bindings/_stage/__init__.c -#: shared-bindings/digitalio/DigitalInOut.c -msgid "argument num/types mismatch" +#: py/compile.c +msgid "inline assembler must be a function" msgstr "" -#: extmod/ulab/code/numpy/numerical.c extmod/ulab/code/numpy/transform.c -msgid "arguments must be ndarrays" +#: py/compile.c +msgid "unknown type" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "array and index length must be equal" +#: py/compile.c +msgid "return annotation must be an identifier" msgstr "" -#: extmod/ulab/code/numpy/io/io.c -msgid "array has too many dimensions" +#: py/compile.c +msgid "expecting an assembler instruction" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "array is too big" -msgstr "" +#: py/compile.c +msgid "'label' requires 1 argument" +msgstr "'label' απαιτεί ένα όρισμα" -#: py/objarray.c shared-bindings/alarm/SleepMemory.c -#: shared-bindings/memorymap/AddressRange.c shared-bindings/nvm/ByteArray.c -msgid "array/bytes required on right side" +#: py/compile.c +msgid "label redefined" msgstr "" -#: py/asmxtensa.c -msgid "asm overflow" -msgstr "" +#: py/compile.c +msgid "'align' requires 1 argument" +msgstr "'align' απαιτεί τουλάχιστον ένα όρισμα" #: py/compile.c -msgid "async for/with outside async function" -msgstr "" +msgid "'data' requires at least 2 arguments" +msgstr "'data' απαιτεί τουλάχιστον 2 παραμέτρους" -#: extmod/ulab/code/numpy/numerical.c -msgid "attempt to get (arg)min/(arg)max of empty sequence" +#: py/compile.c +msgid "'data' requires integer arguments" +msgstr "'data' απαιτεί ακέραιες παραμέτρους" + +#: py/compile.c +msgid "cannot emit native code for this architecture" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "attempt to get argmin/argmax of an empty sequence" +#: py/emitbc.c +msgid "bytecode overflow" +msgstr "" + +#: py/emitinlinerv32.c +msgid "can only have up to 4 parameters for RV32 assembly" msgstr "" -#: py/objstr.c -msgid "attributes not supported" +#: py/emitinlinerv32.c +msgid "parameters must be registers in sequence a0 to a3" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "audio format not supported" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: expecting %q" msgstr "" -#: extmod/ulab/code/ulab_tools.c -msgid "axis is out of bounds" +#: py/emitinlinerv32.c +msgid "opcode '%q': expecting %d arguments" msgstr "" -#: extmod/ulab/code/numpy/numerical.c extmod/ulab/code/ulab_tools.c -msgid "axis must be None, or an integer" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: out of range" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "axis too long" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: unknown register" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "background value out of range of target" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: undefined label '%q'" msgstr "" -#: py/builtinevex.c -msgid "bad compile mode" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: must not be zero" msgstr "" -#: py/objstr.c -msgid "bad conversion specifier" +#: py/emitinlinerv32.c +msgid "opcode '%q': registers must be different" msgstr "" -#: py/objstr.c -msgid "bad format string" +#: py/emitinlinerv32.c +msgid "opcode '%q': malformed register list" msgstr "" -#: py/binary.c py/objarray.c -msgid "bad typecode" +#: py/emitinlinerv32.c +msgid "opcode '%q': invalid stack adjustment" msgstr "" -#: py/emitnative.c -msgid "binary op %q not implemented" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: wrong register(s)" msgstr "" -#: ports/espressif/common-hal/audiobusio/PDMIn.c -msgid "bit_depth must be 8, 16, 24, or 32." +#: py/emitinlinerv32.c +msgid "invalid RV32 instruction '%q'" msgstr "" -#: shared-module/bitmapfilter/__init__.c -msgid "bitmap size and depth must match" +#: py/emitinlinethumb.c +msgid "can only have up to 4 parameters to Thumb assembly" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "bitmap sizes must match" +#: py/emitinlinethumb.c +msgid "parameters must be registers in sequence r0 to r3" msgstr "" -#: extmod/modrandom.c -msgid "bits must be 32 or less" +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' expects at most r%d" +msgstr "'%s' περιμένει το πολύ r%d" + +#: py/emitinlinethumb.c py/emitinlinextensa.c +#, c-format +msgid "'%s' expects a register" +msgstr "'%s' περιμένει έναν καταχωρητή" + +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' expects a special register" +msgstr "'%s' περιμένει έναν ειδικό καταχωρητή" + +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' expects an FPU register" +msgstr "'%s' περιμένει έναν FPU καταχωρητή" + +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' expects {r0, r1, ...}" +msgstr "'%s' περιμένει {r0, r1, ...}" + +#: py/emitinlinethumb.c py/emitinlinextensa.c +#, c-format +msgid "'%s' expects an integer" +msgstr "'%s' περιμένει έναν ακέραιο" + +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' integer 0x%x doesn't fit in mask 0x%x" +msgstr "'%s' ακέραιος 0x%x δεν χωράει στην μάσκα 0x%x" + +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' expects an address of the form [a, b]" +msgstr "'%s' περιμένει μια διεύθυνση της μορφής [a, b]" + +#: py/emitinlinethumb.c py/emitinlinextensa.c +#, c-format +msgid "'%s' expects a label" +msgstr "'%s' περιμένει μια ετικέτα" + +#: py/emitinlinethumb.c py/emitinlinextensa.c +msgid "label '%q' not defined" msgstr "" -#: shared-bindings/audiodelays/Echo.c shared-bindings/audiodelays/PitchShift.c -#: shared-bindings/audiofilters/Distortion.c -#: shared-bindings/audiofilters/Filter.c shared-bindings/audiomixer/Mixer.c -msgid "bits_per_sample must be 8 or 16" +#: py/emitinlinethumb.c +#, c-format +msgid "unsupported Thumb instruction '%s' with %d arguments" msgstr "" #: py/emitinlinethumb.c msgid "branch not in range" msgstr "" -#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c -msgid "buffer is smaller than requested size" +#: py/emitinlinextensa.c +msgid "can only have up to 4 parameters to Xtensa assembly" msgstr "" -#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c -msgid "buffer size must be a multiple of element size" +#: py/emitinlinextensa.c +msgid "parameters must be registers in sequence a2 to a5" msgstr "" -#: shared-module/struct/__init__.c -msgid "buffer size must match format" +#: py/emitinlinextensa.c +#, c-format +msgid "'%s' integer %d isn't within range %d..%d" +msgstr "'%s' ακέραιος %d δεν είναι μέσα στο επιτρεπτό εύρος %d..%d" + +#: py/emitinlinextensa.c +#, c-format +msgid "%d is not a multiple of %d" msgstr "" -#: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c -msgid "buffer slices must be of equal length" +#: py/emitinlinextensa.c +#, c-format +msgid "unsupported Xtensa instruction '%s' with %d arguments" msgstr "" -#: py/modstruct.c shared-module/struct/__init__.c -msgid "buffer too small" +#: py/emitnative.c +msgid "conversion to object" msgstr "" -#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c -msgid "buffer too small for requested bytes" +#: py/emitnative.c +msgid "local '%q' used before type known" msgstr "" -#: py/emitbc.c -msgid "bytecode overflow" +#: py/emitnative.c +msgid "can't load from '%q'" msgstr "" -#: py/objarray.c -msgid "bytes length not a multiple of item size" +#: py/emitnative.c +msgid "can't load with '%q' index" msgstr "" -#: py/objstr.c -msgid "bytes value out of range" +#: py/emitnative.c +msgid "local '%q' has type '%q' but source is '%q'" msgstr "" -#: ports/atmel-samd/bindings/samd/Clock.c -msgid "calibration is out of range" +#: py/emitnative.c +msgid "can't store '%q'" msgstr "" -#: ports/atmel-samd/bindings/samd/Clock.c -msgid "calibration is read only" +#: py/emitnative.c +msgid "can't store to '%q'" msgstr "" -#: shared-module/vectorio/Circle.c shared-module/vectorio/Polygon.c -#: shared-module/vectorio/Rectangle.c -msgid "can only have one parent" +#: py/emitnative.c +msgid "can't store with '%q' index" msgstr "" -#: py/emitinlinethumb.c -msgid "can only have up to 4 parameters to Thumb assembly" +#: py/emitnative.c +msgid "can't implicitly convert '%q' to 'bool'" msgstr "" -#: py/emitinlinextensa.c -msgid "can only have up to 4 parameters to Xtensa assembly" +#: py/emitnative.c +msgid "'not' not implemented" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "can only specify one unknown dimension" +#: py/emitnative.c +msgid "can't do unary op of '%q'" msgstr "" -#: py/objtype.c -msgid "can't add special method to already-subclassed class" +#: py/emitnative.c +msgid "div/mod not implemented for uint" msgstr "" -#: py/compile.c -msgid "can't assign to expression" +#: py/emitnative.c +msgid "comparison of int and uint" msgstr "" -#: extmod/modasyncio.c -msgid "can't cancel self" +#: py/emitnative.c +msgid "binary op %q not implemented" msgstr "" -#: py/obj.c shared-module/adafruit_pixelbuf/PixelBuf.c -msgid "can't convert %q to %q" +#: py/emitnative.c +msgid "can't do binary op between '%q' and '%q'" msgstr "" -#: py/obj.c -#, c-format -msgid "can't convert %s to complex" +#: py/emitnative.c +msgid "casting" msgstr "" -#: py/obj.c -#, c-format -msgid "can't convert %s to float" +#: py/emitnative.c +msgid "return expected '%q' but got '%q'" msgstr "" -#: py/objint.c py/runtime.c -#, c-format -msgid "can't convert %s to int" +#: py/emitnative.c +msgid "native raise" msgstr "" -#: py/objstr.c -msgid "can't convert '%q' object to %q implicitly" +#: py/emitnative.c +msgid "must raise an object" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "can't convert complex to float" +#: py/emitnative.c +msgid "native yield" msgstr "" -#: py/obj.c -msgid "can't convert to complex" +#: py/lexer.c +msgid "unicode name escapes" msgstr "" -#: py/obj.c -msgid "can't convert to float" +#: py/modbuiltins.c py/objstr.c +msgid "char not in range(0x110000)" msgstr "" -#: py/runtime.c -msgid "can't convert to int" +#: py/modbuiltins.c +msgid "chr() arg not in range(256)" msgstr "" -#: py/objstr.c -msgid "can't convert to str implicitly" +#: py/modbuiltins.c +msgid "arg is an empty sequence" msgstr "" -#: py/compile.c -msgid "can't declare nonlocal in outer code" +#: py/modbuiltins.c +msgid "ord expects a character" msgstr "" -#: py/compile.c -msgid "can't delete expression" +#: py/modbuiltins.c +#, c-format +msgid "ord() expected a character, but string of length %d found" msgstr "" -#: py/emitnative.c -msgid "can't do binary op between '%q' and '%q'" +#: py/modbuiltins.c +msgid "3-arg pow() not supported" +msgstr "pow() με 3 παραμέτρους δεν υποστηρίζεται" + +#: py/modbuiltins.c +msgid "must use keyword argument for key function" msgstr "" -#: py/emitnative.c -msgid "can't do unary op of '%q'" +#: py/moderrno.c +msgid "Operation not permitted" msgstr "" -#: py/emitnative.c -msgid "can't implicitly convert '%q' to 'bool'" +#: py/moderrno.c +msgid "No such file/directory" msgstr "" -#: py/runtime.c -msgid "can't import name %q" +#: py/moderrno.c +msgid "Input/output error" msgstr "" -#: py/emitnative.c -msgid "can't load from '%q'" +#: py/moderrno.c +msgid "Permission denied" msgstr "" -#: py/emitnative.c -msgid "can't load with '%q' index" +#: py/moderrno.c +msgid "File exists" msgstr "" -#: py/builtinimport.c -msgid "can't perform relative import" +#: py/moderrno.c +msgid "No such device" +msgstr "" + +#: py/moderrno.c +msgid "No space left on device" +msgstr "" + +#: py/modmath.c shared-bindings/math/__init__.c +msgid "math domain error" +msgstr "" + +#: py/modmath.c +msgid "negative factorial" msgstr "" -#: py/objgenerator.c -msgid "can't send non-None value to a just-started generator" +#: py/modmicropython.c +msgid "schedule queue full" msgstr "" -#: shared-module/sdcardio/SDCard.c -msgid "can't set 512 block size" +#: py/modstruct.c shared-bindings/picogame/Bitmap.c +#: shared-bindings/picogame/Canvas.c shared-bindings/picogame/Framebuffer.c +#: shared-module/picogame/__init__.c shared-module/struct/__init__.c +msgid "buffer too small" msgstr "" -#: py/objexcept.c py/objnamedtuple.c -msgid "can't set attribute" +#: py/modstruct.c +#, c-format +msgid "pack expected %d items for packing (got %d)" msgstr "" -#: py/runtime.c -msgid "can't set attribute '%q'" +#: py/modthread.c +msgid "expecting a dict for keyword args" msgstr "" -#: py/emitnative.c -msgid "can't store '%q'" +#: py/modweakref.c +msgid "not a heap object" msgstr "" -#: py/emitnative.c -msgid "can't store to '%q'" +#: py/nativeglue.c +msgid "set unsupported" msgstr "" -#: py/emitnative.c -msgid "can't store with '%q' index" +#: py/nativeglue.c +msgid "slice unsupported" msgstr "" -#: py/objstr.c -msgid "" -"can't switch from automatic field numbering to manual field specification" +#: py/nativeglue.c +msgid "float unsupported" msgstr "" -#: py/objstr.c -msgid "" -"can't switch from manual field specification to automatic field numbering" +#: py/obj.c shared-module/adafruit_pixelbuf/PixelBuf.c +msgid "can't convert %q to %q" msgstr "" -#: py/objcomplex.c -msgid "can't truncate-divide a complex number" +#: py/obj.c +msgid "During handling of the above exception, another exception occurred:" msgstr "" +"Κατά την αντιμετώπιση της παραπάνω εξαίρεσης, ακόμα μία εξαίρεση συνέβη:" -#: extmod/modasyncio.c -msgid "can't wait" +#: py/obj.c +msgid "The above exception was the direct cause of the following exception:" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "cannot assign new shape" -msgstr "" +#: py/obj.c +msgid " File \"%q\", line %d" +msgstr " Αρχείο \"%q\", γραμμή %d" -#: extmod/ulab/code/ndarray_operators.c -msgid "cannot cast output with casting rule" +#: py/obj.c +msgid " File \"%q\"" +msgstr " Αρχείο \"%q\"" + +#: py/obj.c +msgid ", in %q\n" +msgstr ", στο %q\n" + +#: py/obj.c +msgid "Traceback (most recent call last):\n" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "cannot convert complex to dtype" +#: py/obj.c +msgid "can't convert to float" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "cannot convert complex type" +#: py/obj.c +#, c-format +msgid "can't convert %s to float" msgstr "" -#: py/objtype.c -msgid "cannot create '%q' instances" +#: py/obj.c +msgid "can't convert to complex" msgstr "" -#: py/objtype.c -msgid "cannot create instance" +#: py/obj.c +#, c-format +msgid "can't convert %s to complex" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "cannot delete array elements" +#: py/obj.c +msgid "expected tuple/list" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "cannot reshape array" +#: py/obj.c +#, c-format +msgid "object '%s' isn't a tuple or list" msgstr "" -#: py/emitnative.c -msgid "casting" +#: py/obj.c +msgid "tuple/list has wrong length" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "channel re-init" +#: py/obj.c +#, c-format +msgid "requested length %d but object has length %d" msgstr "" -#: shared-bindings/_stage/Text.c -msgid "chars buffer too small" +#: py/obj.c +msgid "indices must be integers" msgstr "" -#: py/modbuiltins.c -msgid "chr() arg not in range(0x110000)" +#: py/obj.c +msgid "%q indices must be integers, not %s" +msgstr "%q δείκτες πρέπει να είναι ακέραιοι, όχι %s" + +#: py/obj.c +msgid "object has no len" msgstr "" -#: py/modbuiltins.c -msgid "chr() arg not in range(256)" +#: py/obj.c +#, c-format +msgid "object of type '%s' has no len()" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "clip point must be (x,y) tuple" +#: py/obj.c +msgid "object doesn't support item deletion" msgstr "" -#: shared-bindings/msgpack/ExtType.c -msgid "code outside range 0~127" +#: py/obj.c +#, c-format +msgid "'%s' object doesn't support item deletion" +msgstr "'%s' αντικείμενο δεν υποστηρίζει διαγραφή πράγματος" + +#: py/obj.c +msgid "object isn't subscriptable" msgstr "" -#: shared-bindings/displayio/Palette.c -msgid "color buffer must be 3 bytes (RGB) or 4 bytes (RGB + pad byte)" +#: py/obj.c +#, c-format +msgid "'%s' object isn't subscriptable" +msgstr "'%s' αντικείμενο δεν είναι subscriptable" + +#: py/obj.c +msgid "object doesn't support item assignment" msgstr "" -#: shared-bindings/displayio/Palette.c -msgid "color buffer must be a buffer, tuple, list, or int" +#: py/obj.c +#, c-format +msgid "'%s' object doesn't support item assignment" +msgstr "'%s' αντικείμενο δεν υποστηρίζει ορισμό πράγματος" + +#: py/obj.c +msgid "object with buffer protocol required" msgstr "" -#: shared-bindings/displayio/Palette.c -msgid "color buffer must be a bytearray or array of type 'b' or 'B'" +#: py/objarray.c +msgid "bytes length not a multiple of item size" msgstr "" -#: shared-bindings/displayio/Palette.c -msgid "color must be between 0x000000 and 0xffffff" +#: py/objarray.c py/objstr.c +msgid "string argument without an encoding" msgstr "" -#: py/emitnative.c -msgid "comparison of int and uint" +#: py/objarray.c +msgid "memoryview: length is not a multiple of itemsize" msgstr "" -#: py/objcomplex.c -msgid "complex divide by zero" +#: py/objarray.c py/objstr.c +msgid "substring not found" msgstr "" -#: py/objfloat.c py/parsenum.c -msgid "complex values not supported" +#: py/objarray.c py/objstr.c py/objstrunicode.c py/objtuple.c +#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c +#: shared-bindings/nvm/ByteArray.c +msgid "only slices with step=1 (aka None) are supported" msgstr "" -#: extmod/modzlib.c -msgid "compression header" +#: py/objarray.c +msgid "lhs and rhs should be compatible" msgstr "" -#: py/emitnative.c -msgid "conversion to object" +#: py/objarray.c shared-bindings/alarm/SleepMemory.c +#: shared-bindings/memorymap/AddressRange.c shared-bindings/nvm/ByteArray.c +msgid "array/bytes required on right side" msgstr "" -#: extmod/ulab/code/numpy/filter.c -msgid "convolve arguments must be linear arrays" +#: py/objarray.c +msgid "memoryview offset too large" msgstr "" -#: extmod/ulab/code/numpy/filter.c -msgid "convolve arguments must be ndarrays" +#: py/objcomplex.c +msgid "can't truncate-divide a complex number" msgstr "" -#: extmod/ulab/code/numpy/filter.c -msgid "convolve arguments must not be empty" +#: py/objcomplex.c +msgid "complex divide by zero" msgstr "" -#: extmod/ulab/code/numpy/io/io.c -msgid "corrupted file" +#: py/objcomplex.c +msgid "0.0 to a complex power" +msgstr "0.0 σε μία σύνθετη δύναμη" + +#: py/objdeque.c +msgid "full" msgstr "" -#: extmod/ulab/code/numpy/poly.c -msgid "could not invert Vandermonde matrix" +#: py/objdeque.c +msgid "empty" msgstr "" -#: shared-module/sdcardio/SDCard.c -msgid "couldn't determine SD card version" +#: py/objdict.c +msgid "dict update sequence has wrong length" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "cross is defined for 1D arrays of length 3" +#: py/objexcept.c py/objnamedtuple.c +msgid "can't set attribute" msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "data must be iterable" +#: py/objfloat.c py/parsenum.c +msgid "complex values not supported" msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "data must be of equal length" +#: py/objgenerator.c +msgid "generator already executing" msgstr "" -#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c -#, c-format -msgid "data pin #%d in use" +#: py/objgenerator.c +msgid "can't send non-None value to a just-started generator" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "data type not understood" +#: py/objgenerator.c py/runtime.c +msgid "generator raised StopIteration" msgstr "" -#: py/parsenum.c -msgid "decimal numbers not supported" +#: py/objgenerator.c +msgid "generator ignored GeneratorExit" msgstr "" -#: py/compile.c -msgid "default 'except' must be last" +#: py/objint.c py/runtime.c +#, c-format +msgid "can't convert %s to int" msgstr "" -#: shared-bindings/msgpack/__init__.c -msgid "default is not a function" +#: py/objint.c +msgid "float too big" msgstr "" -#: shared-bindings/audiobusio/PDMIn.c -msgid "" -"destination buffer must be a bytearray or array of type 'B' for bit_depth = 8" +#: py/objint.c shared-bindings/time/__init__.c +msgid "No long integer support" msgstr "" -#: shared-bindings/audiobusio/PDMIn.c -msgid "destination buffer must be an array of type 'H' for bit_depth = 16" +#: py/objint.c py/sequence.c +msgid "small int overflow" msgstr "" -#: py/objdict.c -msgid "dict update sequence has wrong length" +#: py/objint.c shared-bindings/_bleio/Connection.c +#: shared-bindings/storage/__init__.c +msgid "%q=%q" +msgstr "%q=%q" + +#: py/objint_impl.h +#, c-format +msgid "value would overflow a %d byte buffer" +msgstr "" + +#: py/objint_impl.h +msgid "can't convert negative int to unsigned" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "diff argument must be an ndarray" +#: py/objint_longlong.c py/parsenum.c +msgid "result overflows long long storage" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "differentiation order out of range" +#: py/objint_longlong.c py/objint_mpz.c py/runtime.c +msgid "negative shift count" msgstr "" -#: extmod/ulab/code/numpy/transform.c -msgid "dimensions do not match" +#: py/objint_longlong.c py/objint_mpz.c py/runtime.c +msgid "negative power with no float support" msgstr "" -#: py/emitnative.c -msgid "div/mod not implemented for uint" +#: py/objint_longlong.c py/objint_mpz.c +msgid "overflow converting long int to machine word" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "divide by zero" +#: py/objint_mpz.c +msgid "pow() with 3 arguments requires integers" msgstr "" -#: py/runtime.c -msgid "division by zero" +#: py/objint_mpz.c +msgid "pow() 3rd argument cannot be 0" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "dtype must be float, or complex" +#: py/objobject.c +msgid "__new__ arg must be a user-type" msgstr "" -#: extmod/ulab/code/ndarray_operators.c -msgid "dtype of int32 is not supported" +#: py/objobject.c +msgid "arg must be user-type" msgstr "" -#: py/objdeque.c -msgid "empty" +#: py/objrange.c py/objslice.c shared-bindings/random/__init__.c +msgid "%q step cannot be zero" +msgstr "%q βήμα δεν μπορεί να είναι μηδέν" + +#: py/objslice.c +msgid "Cannot subclass slice" +msgstr "Δεν γίνεται υποκατηγορία ενός slice" + +#: py/objstr.c +msgid "unknown encoding: %q" msgstr "" -#: extmod/ulab/code/numpy/io/io.c -msgid "empty file" +#: py/objstr.c +msgid "bytes value out of range" msgstr "" -#: extmod/modasyncio.c extmod/modheapq.c -msgid "empty heap" +#: py/objstr.c +msgid "join expects a list of str/bytes objects consistent with self object" msgstr "" #: py/objstr.c msgid "empty separator" msgstr "" -#: shared-bindings/random/__init__.c -msgid "empty sequence" +#: py/objstr.c +msgid "rsplit(None,n)" msgstr "" #: py/objstr.c -msgid "end of format while looking for conversion specifier" +msgid "bad format string" msgstr "" -#: shared-bindings/alarm/time/TimeAlarm.c -msgid "epoch_time not supported on this board" +#: py/objstr.c +#, c-format +msgid "unmatched '%c' in format" msgstr "" -#: ports/nordic/common-hal/busio/UART.c -#, c-format -msgid "error = 0x%08lX" +#: py/objstr.c +msgid "bad conversion specifier" msgstr "" -#: py/runtime.c -msgid "exceptions must derive from BaseException" +#: py/objstr.c +msgid "end of format while looking for conversion specifier" msgstr "" #: py/objstr.c -msgid "expected ':' after format specifier" +#, c-format +msgid "unknown conversion specifier %c" msgstr "" -#: py/obj.c -msgid "expected tuple/list" +#: py/objstr.c +msgid "expected ':' after format specifier" msgstr "" -#: py/modthread.c -msgid "expecting a dict for keyword args" +#: py/objstr.c +msgid "" +"can't switch from automatic field numbering to manual field specification" msgstr "" -#: py/compile.c -msgid "expecting an assembler instruction" +#: py/objstr.c +msgid "%q index out of range" +msgstr "%q δείκτης εκτός εμβέλειας" + +#: py/objstr.c +msgid "attributes not supported" msgstr "" -#: py/compile.c -msgid "expecting just a value for set" +#: py/objstr.c +msgid "" +"can't switch from manual field specification to automatic field numbering" msgstr "" -#: py/compile.c -msgid "expecting key:value for dict" +#: py/objstr.c +msgid "invalid format specifier" msgstr "" -#: shared-bindings/msgpack/__init__.c -msgid "ext_hook is not a function" +#: py/objstr.c +msgid "sign not allowed in string format specifier" msgstr "" -#: py/argcheck.c -msgid "extra keyword arguments given" +#: py/objstr.c +msgid "sign not allowed with integer format specifier 'c'" msgstr "" -#: py/argcheck.c -msgid "extra positional arguments given" +#: py/objstr.c +msgid "unknown format code '%c' for object of type '%q'" msgstr "" -#: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/gifio/OnDiskGif.c -#: shared-bindings/synthio/__init__.c shared-module/gifio/GifWriter.c -msgid "file must be a file opened in byte mode" +#: py/objstr.c +msgid "'=' alignment not allowed in string format specifier" +msgstr "Ευθυγράμμιση του '=' δεν επιτρέπεται εντός προσδιοριστή string format" + +#: py/objstr.c +msgid "format needs a dict" msgstr "" -#: shared-bindings/traceback/__init__.c -msgid "file write is not available" +#: py/objstr.c +msgid "incomplete format key" msgstr "" -#: shared-bindings/storage/__init__.c -msgid "filesystem must provide mount method" +#: py/objstr.c +msgid "incomplete format" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "first argument must be a callable" +#: py/objstr.c +msgid "format string needs more arguments" msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "first argument must be a function" +#: py/objstr.c +#, c-format +msgid "%%c needs int or char" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "first argument must be a tuple of ndarrays" +#: py/objstr.c +#, c-format +msgid "unsupported format character '%c' (0x%x) at index %d" msgstr "" -#: extmod/ulab/code/numpy/transform.c extmod/ulab/code/numpy/vector.c -msgid "first argument must be an ndarray" +#: py/objstr.c +msgid "format string didn't convert all arguments" msgstr "" -#: py/objtype.c -msgid "first argument to super() must be type" +#: py/objstr.c +msgid "non-hex digit" msgstr "" -#: extmod/ulab/code/scipy/linalg/linalg.c -msgid "first two arguments must be ndarrays" +#: py/objstr.c +msgid "can't convert to str implicitly" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "flattening order must be either 'C', or 'F'" +#: py/objstr.c +msgid "can't convert '%q' object to %q implicitly" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "flip argument must be an ndarray" +#: py/objstrunicode.c +#, c-format +msgid "string indices must be integers, not %s" msgstr "" -#: py/objint.c -msgid "float too big" +#: py/objstrunicode.c +msgid "string index out of range" msgstr "" -#: py/nativeglue.c -msgid "float unsupported" +#: py/objtemplate.c +msgid "expected str or Interpolation" msgstr "" -#: shared-bindings/_stage/Text.c -msgid "font must be 2048 bytes long" +#: py/objtype.c +msgid "Call super().__init__() before accessing native object." +msgstr "Κλήση super().__init__() πρίν την πρόσβαση του τοπικού αντικειμένου." + +#: py/objtype.c +msgid "__init__() should return None" msgstr "" -#: extmod/moddeflate.c -msgid "format" +#: py/objtype.c +#, c-format +msgid "__init__() should return None, not '%s'" msgstr "" -#: py/objstr.c -msgid "format requires a dict" +#: py/objtype.c py/runtime.c +msgid "unreadable attribute" msgstr "" -#: py/objdeque.c -msgid "full" +#: py/objtype.c py/runtime.c +msgid "object not callable" msgstr "" -#: py/argcheck.c -msgid "function doesn't take keyword arguments" +#: py/objtype.c py/runtime.c shared-module/atexit/__init__.c +msgid "'%q' object isn't callable" msgstr "" -#: py/argcheck.c -#, c-format -msgid "function expected at most %d arguments, got %d" +#: py/objtype.c +msgid "type takes 1 or 3 arguments" msgstr "" -#: py/bc.c py/objnamedtuple.c -msgid "function got multiple values for argument '%q'" +#: py/objtype.c +msgid "can't create instance" msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "function has the same sign at the ends of interval" +#: py/objtype.c +msgid "can't create '%q' instances" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "function is defined for ndarrays only" +#: py/objtype.c +msgid "can't add special method to already-subclassed class" msgstr "" -#: extmod/ulab/code/numpy/carray/carray.c -msgid "function is implemented for ndarrays only" +#: py/objtype.c +msgid "type isn't an acceptable base type" msgstr "" -#: py/argcheck.c -#, c-format -msgid "function missing %d required positional arguments" +#: py/objtype.c +msgid "type '%q' isn't an acceptable base type" msgstr "" -#: py/bc.c -msgid "function missing keyword-only argument" +#: py/objtype.c +msgid "multiple inheritance not supported" msgstr "" -#: py/bc.c -msgid "function missing required keyword argument '%q'" +#: py/objtype.c +msgid "multiple bases have instance lay-out conflict" msgstr "" -#: py/bc.c -#, c-format -msgid "function missing required positional argument #%d" +#: py/objtype.c +msgid "first argument to super() must be type" msgstr "" -#: py/argcheck.c py/bc.c py/objnamedtuple.c shared-bindings/_eve/__init__.c -#: shared-bindings/time/__init__.c -#, c-format -msgid "function takes %d positional arguments but %d were given" +#: py/objtype.c +msgid "issubclass() arg 2 must be a class or a tuple of classes" msgstr "" -#: py/objgenerator.c -msgid "generator already executing" +#: py/objtype.c +msgid "issubclass() arg 1 must be a class" msgstr "" -#: py/objgenerator.c -msgid "generator ignored GeneratorExit" +#: py/parse.c +msgid "not a constant" msgstr "" -#: py/objgenerator.c py/runtime.c -msgid "generator raised StopIteration" +#: py/parse.c +msgid "Unable to init parser" msgstr "" -#: shared-bindings/_stage/Layer.c -msgid "graphic must be 2048 bytes long" +#: py/parse.c +msgid "unexpected indent" msgstr "" -#: extmod/modhashlib.c -msgid "hash is final" +#: py/parse.c +msgid "unindent doesn't match any outer indent level" msgstr "" -#: extmod/modheapq.c -msgid "heap must be a list" +#: py/parse.c +msgid "malformed f-string" msgstr "" -#: py/compile.c -msgid "identifier redefined as global" +#: py/parsenum.c +msgid "invalid syntax for integer" msgstr "" -#: py/compile.c -msgid "identifier redefined as nonlocal" +#: py/parsenum.c +#, c-format +msgid "invalid syntax for integer with base %d" msgstr "" -#: py/compile.c -msgid "import * not at module level" +#: py/parsenum.c +msgid "invalid syntax for number" msgstr "" -#: py/persistentcode.c -msgid "incompatible .mpy arch" +#: py/parsenum.c +msgid "decimal numbers not supported" msgstr "" #: py/persistentcode.c msgid "incompatible .mpy file" msgstr "" -#: py/objstr.c -msgid "incomplete format" +#: py/persistentcode.c +msgid "MicroPython .mpy file; use CircuitPython mpy-cross" msgstr "" -#: py/objstr.c -msgid "incomplete format key" +#: py/persistentcode.c +msgid "native code in .mpy unsupported" msgstr "" -#: extmod/modbinascii.c -msgid "incorrect padding" +#: py/persistentcode.c +msgid "incompatible .mpy arch" msgstr "" -#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/transform.c -msgid "index is out of bounds" +#: py/persistentcode.c +msgid "function must be bytecode" msgstr "" -#: shared-bindings/_pixelmap/PixelMap.c -msgid "index must be tuple or int" -msgstr "" +#: py/proto.c shared-bindings/digitalio/DigitalInOutProtocol.c +msgid "'%q' object does not support '%q'" +msgstr "'%q' αντικείμενο δεν υποστηρίζει '%q'" -#: extmod/ulab/code/numpy/numerical.c extmod/ulab/code/ulab_tools.c -#: ports/espressif/common-hal/pulseio/PulseIn.c -#: shared-bindings/bitmaptools/__init__.c -msgid "index out of range" +#: py/qstr.c +msgid "name too long" msgstr "" -#: py/obj.c -msgid "indices must be integers" +#: py/runtime.c +msgid "name not defined" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "indices must be integers, slices, or Boolean lists" +#: py/runtime.c +msgid "name '%q' isn't defined" msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "initial values must be iterable" +#: py/runtime.c +msgid "unsupported type for operator" msgstr "" -#: shared-bindings/_bleio/Characteristic.c shared-bindings/_bleio/Descriptor.c -msgid "initial_value length is wrong" +#: py/runtime.c +msgid "unsupported type for %q: '%s'" msgstr "" -#: py/compile.c -msgid "inline assembler must be a function" +#: py/runtime.c +msgid "unsupported types for %q: '%q', '%q'" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "input and output dimensions differ" +#: py/runtime.c +msgid "wrong number of values to unpack" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "input and output shapes differ" +#: py/runtime.c +#, c-format +msgid "need more than %d values to unpack" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "input argument must be an integer, a tuple, or a list" +#: py/runtime.c +#, c-format +msgid "too many values to unpack (expected %d)" msgstr "" -#: extmod/ulab/code/numpy/fft/fft_tools.c -msgid "input array length must be power of 2" +#: py/runtime.c +msgid "type object '%q' has no attribute '%q'" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "input arrays are not compatible" +#: py/runtime.c +msgid "module '%q' has no attribute '%q'" msgstr "" -#: extmod/ulab/code/numpy/poly.c -msgid "input data must be an iterable" -msgstr "" +#: py/runtime.c +msgid "'%s' object has no attribute '%q'" +msgstr "'%s' αντικείμενο δεν έχει γνώρισμα '%q'" -#: extmod/ulab/code/numpy/vector.c -msgid "input dtype must be float or complex" +#: py/runtime.c +msgid "can't set attribute '%q'" msgstr "" -#: extmod/ulab/code/numpy/poly.c -msgid "input is not iterable" +#: py/runtime.c +msgid "object not iterable" msgstr "" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "input matrix is asymmetric" -msgstr "" +#: py/runtime.c +msgid "'%q' object isn't iterable" +msgstr "'%q' αντικείμενο δεν είναι επαναληπτικό" -#: extmod/ulab/code/numpy/linalg/linalg.c -#: extmod/ulab/code/scipy/linalg/linalg.c -msgid "input matrix is singular" +#: py/runtime.c +msgid "object not an iterator" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "input must be 1- or 2-d" -msgstr "" +#: py/runtime.c +msgid "'%q' object isn't an iterator" +msgstr "'%q' αντικείμενο δεν είναι επαναλήπτης" -#: extmod/ulab/code/numpy/carray/carray.c -msgid "input must be a 1D ndarray" +#: py/runtime.c +msgid "exceptions must derive from BaseException" msgstr "" -#: extmod/ulab/code/scipy/linalg/linalg.c extmod/ulab/code/user/user.c -msgid "input must be a dense ndarray" +#: py/runtime.c +msgid "can't import name %q" msgstr "" -#: extmod/ulab/code/user/user.c shared-bindings/_eve/__init__.c -msgid "input must be an ndarray" +#: py/runtime.c +msgid "memory allocation failed, heap is locked" msgstr "" -#: extmod/ulab/code/numpy/carray/carray.c -msgid "input must be an ndarray, or a scalar" +#: py/runtime.c +#, c-format +msgid "memory allocation failed, allocating %u bytes" msgstr "" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "input must be one-dimensional" +#: py/runtime.c +msgid "can't convert to int" msgstr "" -#: extmod/ulab/code/ulab_tools.c -msgid "input must be square matrix" +#: py/runtime.c +msgid "division by zero" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "input must be tuple, list, range, or ndarray" +#: py/runtime.c +msgid "maximum recursion depth exceeded" msgstr "" -#: extmod/ulab/code/numpy/poly.c -msgid "input vectors must be of equal length" +#: py/sequence.c shared-bindings/displayio/Group.c +msgid "object not in sequence" msgstr "" -#: extmod/ulab/code/numpy/approx.c -msgid "interp is defined for 1D iterables of equal length" +#: py/stream.c shared-bindings/getpass/__init__.c +msgid "stream operation not supported" msgstr "" -#: shared-bindings/_bleio/Adapter.c -#, c-format -msgid "interval must be in range %s-%s" +#: py/vm.c +msgid "local variable referenced before assignment" msgstr "" -#: py/compile.c -msgid "invalid arch" +#: py/vm.c +msgid "no active exception to reraise" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -#, c-format -msgid "invalid bits_per_pixel %d, must be, 1, 2, 4, 8, 16, 24, or 32" +#: py/vm.c +msgid "opcode" msgstr "" -#: shared-module/ssl/SSLSocket.c -msgid "invalid cert" +#: shared-bindings/_bleio/Adapter.c +msgid "Cannot create a new Adapter; use _bleio.adapter;" msgstr "" +"Δεν μπορεί να δημιουργηθεί νέο Adapter; χρησιμοποιείστε _bleio.adapter;" -#: shared-bindings/bitmaptools/__init__.c -#, c-format -msgid "invalid element size %d for bits_per_pixel %d\n" -msgstr "" +#: shared-bindings/_bleio/Adapter.c +msgid "Could not set address" +msgstr "Δεν μπόρεσε να ρυθμιστεί η διεύθυνση" -#: shared-bindings/bitmaptools/__init__.c +#: shared-bindings/_bleio/Adapter.c #, c-format -msgid "invalid element_size %d, must be, 1, 2, or 4" +msgid "interval must be in range %s-%s" msgstr "" -#: shared-bindings/traceback/__init__.c -msgid "invalid exception" +#: shared-bindings/_bleio/Adapter.c +msgid "Cannot have scan responses for extended, connectable advertisements." msgstr "" +"Δεν μπορούμε να έχουμε απαντήσεις scan για εκτεταμένες, συνδεόμενες " +"διαφημήσεις." -#: py/objstr.c -msgid "invalid format specifier" +#: shared-bindings/_bleio/Adapter.c +msgid "Only connectable advertisements can be directed" msgstr "" -#: shared-bindings/wifi/Radio.c -msgid "invalid hostname" +#: shared-bindings/_bleio/Adapter.c +msgid "non-zero timeout must be >= interval" msgstr "" -#: shared-module/ssl/SSLSocket.c -msgid "invalid key" +#: shared-bindings/_bleio/Adapter.c +msgid "window must be <= interval" msgstr "" -#: py/compile.c -msgid "invalid micropython decorator" +#: shared-bindings/_bleio/Adapter.c +msgid "Prefix buffer must be on the heap" msgstr "" -#: ports/espressif/common-hal/espcamera/Camera.c -msgid "invalid setting" +#: shared-bindings/_bleio/CharacteristicBuffer.c +msgid "CharacteristicBuffer writing not provided" +msgstr "Δεν υποστηρίζονται εγγραφές στο CharacteristicBuffer" + +#: shared-bindings/_bleio/Connection.c +msgid "" +"Connection has been disconnected and can no longer be used. Create a new " +"connection." msgstr "" +"Έχει γίνει αποσύνδεση και αυτή η συνδεση δεν μπορεί να χρησιμοποιηθεί. " +"Δημιουργήστε μια νέα σύνδεση." -#: shared-bindings/random/__init__.c -msgid "invalid step" +#: shared-bindings/_bleio/PacketBuffer.c +#, c-format +msgid "Buffer too short by %d bytes" +msgstr "Buffer πολύ μικρό κατα %d bytes" + +#: shared-bindings/_bleio/PacketBuffer.c +msgid "No connection: length cannot be determined" msgstr "" -#: py/compile.c py/parse.c -msgid "invalid syntax" +#: shared-bindings/_bleio/UUID.c +msgid "UUID string not 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'" msgstr "" -#: py/parsenum.c -msgid "invalid syntax for integer" +#: shared-bindings/_bleio/UUID.c +msgid "UUID value is not str, int or byte buffer" msgstr "" -#: py/parsenum.c -#, c-format -msgid "invalid syntax for integer with base %d" +#: shared-bindings/_bleio/UUID.c +msgid "not a 128-bit UUID" msgstr "" -#: py/parsenum.c -msgid "invalid syntax for number" +#: shared-bindings/_bleio/__init__.c shared-bindings/emmcio/EMMC.c +#: shared-bindings/memorymonitor/AllocationSize.c +#: shared-bindings/pulseio/PulseIn.c shared-module/bitmaptools/__init__.c +#: shared-module/displayio/legacy/Bitmap.c +#: shared-module/displayio/legacy/Group.c shared-module/displayio/lvgl/Bitmap.c +#: shared-module/displayio/lvgl/Group.c +msgid "Read-only" msgstr "" -#: py/objtype.c -msgid "issubclass() arg 1 must be a class" +#: shared-bindings/_pew/PewPew.c +msgid "Incorrect buffer size" msgstr "" -#: py/objtype.c -msgid "issubclass() arg 2 must be a class or a tuple of classes" +#: shared-bindings/_pixelmap/PixelMap.c +msgid "nested index must be int" msgstr "" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "iterations did not converge" +#: shared-bindings/_pixelmap/PixelMap.c +msgid "index must be tuple or int" msgstr "" -#: py/objstr.c -msgid "join expects a list of str/bytes objects consistent with self object" +#: shared-bindings/_stage/Layer.c +msgid "map buffer too small" msgstr "" -#: py/argcheck.c -msgid "keyword argument(s) not implemented - use normal args instead" +#: shared-bindings/_stage/Text.c +msgid "chars buffer too small" msgstr "" -#: py/emitinlinethumb.c py/emitinlinextensa.c -msgid "label '%q' not defined" +#: shared-bindings/adafruit_bus_device/spi_device/SPIDevice.c +msgid "Pin is input only" msgstr "" -#: py/compile.c -msgid "label redefined" +#: shared-bindings/adafruit_pixelbuf/PixelBuf.c +#: shared-module/_pixelmap/PixelMap.c +#, c-format +msgid "Unmatched number of items on RHS (expected %d, got %d)." msgstr "" -#: py/objarray.c -msgid "lhs and rhs should be compatible" +#: shared-bindings/aesio/aes.c +msgid "Key must be 16, 24, or 32 bytes long" msgstr "" -#: py/emitnative.c -msgid "local '%q' has type '%q' but source is '%q'" +#: shared-bindings/aesio/aes.c +msgid "Requested AES mode is unsupported" msgstr "" -#: py/emitnative.c -msgid "local '%q' used before type known" +#: shared-bindings/aesio/aes.c +msgid "Source and destination buffers must be the same length" msgstr "" -#: py/vm.c -msgid "local variable referenced before assignment" -msgstr "" +#: shared-bindings/aesio/aes.c +msgid "ECB only operates on 16 bytes at a time" +msgstr "ECB δουλεύει μόνο σε 16 bytes κάθε φορά" -#: ports/espressif/common-hal/canio/CAN.c -msgid "loopback + silent mode not supported by peripheral" -msgstr "" +#: shared-bindings/aesio/aes.c +msgid "CBC blocks must be multiples of 16 bytes" +msgstr "CBC blocks πρέπει να είναι πολλαπλάσια του 16 bytes" -#: ports/espressif/common-hal/mdns/Server.c -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "mDNS already initialized" +#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c +#: shared-bindings/nvm/ByteArray.c +msgid "Slice and value different lengths." msgstr "" -#: ports/espressif/common-hal/mdns/Server.c -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "mDNS only works with built-in WiFi" -msgstr "" +#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c +#: shared-bindings/nvm/ByteArray.c +msgid "Array values should be single bytes." +msgstr "Η τιμές της παράταξη πρέπει να είναι μονά bytes." -#: py/parse.c -msgid "malformed f-string" +#: shared-bindings/alarm/SleepMemory.c +msgid "Unable to write to sleep_memory." msgstr "" -#: shared-bindings/_stage/Layer.c -msgid "map buffer too small" +#: shared-bindings/alarm/__init__.c +msgid "Expected a kind of %q" msgstr "" -#: py/modmath.c shared-bindings/math/__init__.c -msgid "math domain error" +#: shared-bindings/alarm/time/TimeAlarm.c shared-bindings/time/__init__.c +msgid "RTC is not supported on this board" msgstr "" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "matrix is not positive definite" +#: shared-bindings/alarm/time/TimeAlarm.c +msgid "Supply one of monotonic_time or epoch_time" msgstr "" -#: ports/espressif/common-hal/_bleio/Descriptor.c -#: ports/nordic/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Descriptor.c -#, c-format -msgid "max_length must be 0-%d when fixed_length is %s" +#: shared-bindings/alarm/time/TimeAlarm.c +msgid "epoch_time not supported on this board" msgstr "" -#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/random/random.c -msgid "maximum number of dimensions is " +#: shared-bindings/alarm/time/TimeAlarm.c +msgid "Time is in the past." msgstr "" -#: py/runtime.c -msgid "maximum recursion depth exceeded" -msgstr "" +#: shared-bindings/analogbufio/BufferedIn.c +msgid "%q must be a bytearray or array of type 'H' or 'B'" +msgstr "%q πρέπει να είναι bytearray ή array τύπου 'H' ή 'B'" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "maxiter must be > 0" +#: shared-bindings/audiobusio/PDMIn.c +msgid "%q must be multiple of 8." msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "maxiter should be > 0" +#: shared-bindings/audiobusio/PDMIn.c shared-bindings/audioi2sin/I2SIn.c +#: shared-bindings/usb_host_audio/USBIn.c +msgid "Cannot record to a file" +msgstr "Δεν μπορεί να γίνει καταγραφή σε αρχείο" + +#: shared-bindings/audiobusio/PDMIn.c shared-bindings/audioi2sin/I2SIn.c +#: shared-bindings/usb_host_audio/USBIn.c +msgid "Destination capacity is smaller than destination_length." msgstr "" +"Το μέγεθος προορισμού πρέπει να είναι μικρότερο από το destination_length." -#: extmod/ulab/code/numpy/numerical.c -msgid "median argument must be an ndarray" +#: shared-bindings/audiobusio/PDMIn.c +msgid "destination buffer must be an array of type 'H' for bit_depth = 16" msgstr "" -#: py/runtime.c -#, c-format -msgid "memory allocation failed, allocating %u bytes" +#: shared-bindings/audiobusio/PDMIn.c +msgid "" +"destination buffer must be a bytearray or array of type 'B' for bit_depth = 8" msgstr "" -#: py/runtime.c -msgid "memory allocation failed, heap is locked" +#: shared-bindings/audiocore/RawSample.c +msgid "%q must be a bytearray or array of type 'h', 'H', 'b', or 'B'" +msgstr "%q πρέπει να είναι bytearray ή array τύπου 'h', 'H', 'b', ή 'B'" + +#: shared-bindings/audiocore/RawSample.c +msgid "Length of %q must be an even multiple of channel_count * type_size" msgstr "" -#: py/objarray.c -msgid "memoryview offset too large" +#: shared-bindings/audiodelays/Chorus.c shared-bindings/audiodelays/Echo.c +#: shared-bindings/audiodelays/Flanger.c +#: shared-bindings/audiodelays/GranularPitchShift.c +#: shared-bindings/audiodelays/MultiTapDelay.c +#: shared-bindings/audiodelays/PitchShift.c +#: shared-bindings/audiofilters/Distortion.c +#: shared-bindings/audiofilters/Filter.c shared-bindings/audiofilters/Phaser.c +#: shared-bindings/audiomixer/Mixer.c shared-module/audiotap/Tap.c +msgid "bits_per_sample must be 8 or 16" msgstr "" -#: py/objarray.c -msgid "memoryview: length is not a multiple of itemsize" +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "samples_signed must be true" msgstr "" -#: extmod/modtime.c -msgid "mktime needs a tuple of length 8 or 9" +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "bits_per_sample must be 16" msgstr "" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "mode must be complete, or reduced" +#: shared-bindings/audioi2sin/I2SIn.c shared-bindings/usb_host_audio/USBIn.c +#, c-format +msgid "invalid destination buffer, must be an array of type: %c" msgstr "" -#: py/builtinimport.c -msgid "module not found" +#: shared-bindings/audioio/AudioOut.c shared-bindings/emmcio/EMMC.c +msgid "%q and %q must be different" +msgstr "%q και %q πρεπει να είναι διαφορετικά" + +#: shared-bindings/audiomp3/MP3Decoder.c shared-bindings/gifio/OnDiskGif.c +#: shared-bindings/synthio/__init__.c shared-module/gifio/GifWriter.c +msgid "file must be a file opened in byte mode" msgstr "" -#: ports/espressif/common-hal/wifi/Monitor.c -msgid "monitor init failed" +#: shared-bindings/bitmapfilter/__init__.c +msgid "" +"weights must be a sequence with an odd square number of elements (usually 9 " +"or 25)" msgstr "" -#: extmod/ulab/code/numpy/poly.c -msgid "more degrees of freedom than data points" +#: shared-bindings/bitmapfilter/__init__.c +msgid "weights must be an object of type %q, %q, %q, or %q, not %q " msgstr "" -#: py/compile.c -msgid "multiple *x in assignment" +#: shared-bindings/bitmaptools/__init__.c +msgid "clip point must be (x,y) tuple" msgstr "" -#: py/objtype.c -msgid "multiple bases have instance lay-out conflict" +#: shared-bindings/bitmaptools/__init__.c +msgid "source palette too large" msgstr "" -#: py/objtype.c -msgid "multiple inheritance not supported" +#: shared-bindings/bitmaptools/__init__.c +msgid "Bitmap size and bits per value must match" +msgstr "Το μέγεθος του bitmap και τα bits ανα τιμή πρέπει να ταιριάζουν" + +#: shared-bindings/bitmaptools/__init__.c +msgid "For L8 colorspace, input bitmap must have 8 bits per pixel" msgstr "" -#: py/emitnative.c -msgid "must raise an object" +#: shared-bindings/bitmaptools/__init__.c +msgid "For RGB colorspaces, input bitmap must have 16 bits per pixel" msgstr "" -#: py/modbuiltins.c -msgid "must use keyword argument for key function" +#: shared-bindings/bitmaptools/__init__.c +msgid "Unsupported colorspace" msgstr "" -#: py/runtime.c -msgid "name '%q' is not defined" +#: shared-bindings/bitmaptools/__init__.c +msgid "Mask bitmap size must match the other bitmaps" msgstr "" -#: py/runtime.c -msgid "name not defined" +#: shared-bindings/bitmaptools/__init__.c +msgid "Mask bitmap must have 8 bits per pixel" msgstr "" -#: py/qstr.c -msgid "name too long" +#: shared-bindings/bitmaptools/__init__.c +msgid "out of range of target" msgstr "" -#: py/persistentcode.c -msgid "native code in .mpy unsupported" +#: shared-bindings/bitmaptools/__init__.c +msgid "value out of range of target" msgstr "" -#: py/asmthumb.c -msgid "native method too big" +#: shared-bindings/bitmaptools/__init__.c +msgid "background value out of range of target" msgstr "" -#: py/emitnative.c -msgid "native yield" +#: shared-bindings/bitmaptools/__init__.c +msgid "Coordinate arrays types have different sizes" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "ndarray length overflows" +#: shared-bindings/bitmaptools/__init__.c +msgid "Coordinate arrays have different lengths" msgstr "" -#: py/runtime.c +#: shared-bindings/bitmaptools/__init__.c #, c-format -msgid "need more than %d values to unpack" +msgid "invalid element_size %d, must be, 1, 2, or 4" msgstr "" -#: py/modmath.c -msgid "negative factorial" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element size %d for bits_per_pixel %d\n" msgstr "" -#: py/objint_longlong.c py/objint_mpz.c py/runtime.c -msgid "negative power with no float support" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid bits_per_pixel %d, must be, 1, 2, 4, 8, 16, 24, or 32" msgstr "" -#: py/objint_mpz.c py/runtime.c -msgid "negative shift count" +#: shared-bindings/bitmaptools/__init__.c +msgid "bitmap sizes must match" msgstr "" -#: shared-bindings/_pixelmap/PixelMap.c -msgid "nested index must be int" +#: shared-bindings/bitmaptools/__init__.c +msgid "source_bitmap must have value_count of 2 or 65536" msgstr "" -#: shared-module/sdcardio/SDCard.c -msgid "no SD card" +#: shared-bindings/bitmaptools/__init__.c +msgid "source_bitmap must have value_count of 65536" msgstr "" -#: py/vm.c -msgid "no active exception to reraise" +#: shared-bindings/bitmaptools/__init__.c +msgid "source_bitmap must have value_count of 8" msgstr "" -#: py/compile.c -msgid "no binding for nonlocal found" +#: shared-bindings/bitmaptools/__init__.c +msgid "unsupported colorspace for dither" msgstr "" -#: shared-module/msgpack/__init__.c -msgid "no default packer" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Input buffer length (%d) must be a multiple of the strand count (%d)" msgstr "" -#: extmod/modrandom.c extmod/ulab/code/numpy/random/random.c -msgid "no default seed" +#: shared-bindings/board/__init__.c +msgid "No default %q bus" msgstr "" -#: py/builtinimport.c -msgid "no module named '%q'" +#: shared-bindings/busdisplay/BusDisplay.c +msgid "%q must be 1 when %q is True" +msgstr "%q πρέπει να είναι 1 όταν %q είναι True" + +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +#, fuzzy +msgid "Display must have a 16 bit colorspace." +msgstr "Η οθόνη πρέπει να έχει 16 bit χρωματική ευκρίνεια." + +#: shared-bindings/busio/UART.c shared-bindings/canio/CAN.c +msgid "tx and rx cannot both be None" msgstr "" -#: shared-module/sdcardio/SDCard.c -msgid "no response from SD card" +#: shared-bindings/busio/UART.c shared-bindings/displayio/Group.c +msgid "Must be a %q subclass." msgstr "" -#: ports/espressif/common-hal/espcamera/Camera.c py/objobject.c py/runtime.c -msgid "no such attribute" +#: shared-bindings/canio/RemoteTransmissionRequest.c +msgid "RemoteTransmissionRequests limited to 8 bytes" msgstr "" -#: ports/espressif/common-hal/_bleio/Connection.c -#: ports/nordic/common-hal/_bleio/Connection.c -msgid "non-UUID found in service_uuids_whitelist" +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/ec/EllipticCurvePublicKey.c +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/padding/__init__.c +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "Only %q supported" msgstr "" -#: py/compile.c -msgid "non-default argument follows default argument" +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/padding/__init__.c +msgid "label is not supported" msgstr "" -#: py/objstr.c -msgid "non-hex digit found" +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/rsa/__init__.c +#: shared-bindings/hmac/__init__.c +msgid "key does not have the expected %q purpose" msgstr "" -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "non-zero timeout must be > 0.01" +#: shared-bindings/digitalio/DigitalInOut.c +#: shared-bindings/i2cioexpander/IOPin.c +msgid "Cannot set value when direction is input." +msgstr "Δεν μπορεί να οριστεί τιμή οταν η κατεύθυνση είναι input." + +#: shared-bindings/digitalio/DigitalInOut.c +#: shared-bindings/i2cioexpander/IOPin.c +msgid "Drive mode not used when direction is input." +msgstr "Ο τρόπος οδήγησης δεν χρησιμοποιείται όταν η κατεύθυνση είναι είσοδος." + +#: shared-bindings/digitalio/DigitalInOut.c +#: shared-bindings/i2cioexpander/IOPin.c +msgid "Pull not used when direction is output." msgstr "" -#: shared-bindings/_bleio/Adapter.c -msgid "non-zero timeout must be >= interval" +#: shared-bindings/digitalio/DigitalInOutProtocol.c +msgid "%q object missing '%q' method" msgstr "" -#: shared-bindings/_bleio/UUID.c -msgid "not a 128-bit UUID" +#: shared-bindings/digitalio/DigitalInOutProtocol.c +msgid "%q object missing '%q' attribute" msgstr "" -#: py/parse.c -msgid "not a constant" +#: shared-bindings/digitalio/DigitalInOutProtocol.c +msgid "object does not support DigitalInOut protocol" msgstr "" -#: py/objstr.c -msgid "not all arguments converted during string formatting" -msgstr "" +#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/memorymonitor/AllocationSize.c +#: shared-bindings/pulseio/PulseIn.c +msgid "Cannot delete values" +msgstr "Δεν μπορούν να διαγραφούν οι τιμές" -#: py/objstr.c -msgid "not enough arguments for format string" +#: 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 +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +msgid "Slices not supported" msgstr "" -#: extmod/ulab/code/numpy/carray/carray_tools.c -msgid "not implemented for complex dtype" +#: shared-bindings/displayio/Palette.c +msgid "color buffer must be a bytearray or array of type 'b' or 'B'" msgstr "" -#: extmod/ulab/code/numpy/bitwise.c -msgid "not supported for input types" +#: shared-bindings/displayio/Palette.c +msgid "color buffer must be 3 bytes (RGB) or 4 bytes (RGB + pad byte)" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "number of points must be at least 2" +#: shared-bindings/displayio/Palette.c +msgid "color must be between 0x000000 and 0xffffff" msgstr "" -#: py/builtinhelp.c -msgid "object " +#: shared-bindings/displayio/Palette.c +msgid "color buffer must be a buffer, tuple, list, or int" msgstr "" -#: py/obj.c -#, c-format -msgid "object '%s' isn't a tuple or list" +#: shared-bindings/displayio/TileGrid.c +msgid "Tile width must exactly divide bitmap width" msgstr "" -#: py/obj.c -msgid "object doesn't support item assignment" +#: shared-bindings/displayio/TileGrid.c +msgid "Tile height must exactly divide bitmap height" msgstr "" -#: py/obj.c -msgid "object doesn't support item deletion" +#: shared-bindings/displayio/TileGrid.c +msgid "New bitmap must be same size as old bitmap" msgstr "" -#: py/obj.c -msgid "object has no len" +#: shared-bindings/displayio/TileGrid.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-module/displayio/legacy/TileGrid.c +#: shared-module/displayio/lvgl/TileGrid.c +msgid "Tile index out of bounds" msgstr "" -#: py/obj.c -msgid "object isn't subscriptable" +#: shared-bindings/dualbank/__init__.c +msgid "offset must be >= 0" msgstr "" -#: py/runtime.c -msgid "object not an iterator" +#: shared-bindings/emmcio/EMMC.c shared-bindings/i2cioexpander/IOExpander.c +msgid "address out of range" msgstr "" -#: py/objtype.c py/runtime.c -msgid "object not callable" +#: shared-bindings/epaperdisplay/EPaperDisplay.c +msgid "Refresh too soon" msgstr "" -#: py/sequence.c shared-bindings/displayio/Group.c -msgid "object not in sequence" -msgstr "" +#: shared-bindings/framebufferio/FramebufferDisplay.c +msgid "Buffer is not a bytearray." +msgstr "Το buffer δεν είναι ένα bytearray." -#: py/runtime.c -msgid "object not iterable" +#: shared-bindings/gnss/GNSS.c +msgid "System entry must be gnss.SatelliteSystem" msgstr "" -#: py/obj.c -#, c-format -msgid "object of type '%s' has no len()" +#: shared-bindings/hashlib/__init__.c shared-bindings/hmac/__init__.c +msgid "Unsupported hash algorithm" msgstr "" -#: py/obj.c -msgid "object with buffer protocol required" +#: shared-bindings/i2cioexpander/IOExpander.c +msgid "num_pins must be 8 or 16" msgstr "" -#: py/objstr.c -msgid "odd-length string" +#: shared-bindings/i2ctarget/I2CTarget.c +msgid "addresses is empty" msgstr "" -#: supervisor/shared/web_workflow/web_workflow.c -msgid "off" +#: shared-bindings/ipaddress/IPv4Address.c shared-bindings/ipaddress/__init__.c +msgid "Not a valid IP string" msgstr "" -#: extmod/ulab/code/utils/utils.c -msgid "offset is too large" -msgstr "" +#: shared-bindings/ipaddress/IPv4Address.c +#, c-format +msgid "Address must be %d bytes long" +msgstr "Η διεύθυνση πρέπει να είναι %d bytes μεγάλη" -#: shared-bindings/dualbank/__init__.c -msgid "offset must be >= 0" +#: shared-bindings/ipaddress/__init__.c +msgid "Only int or string supported for ip" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "offset must be non-negative and no greater than buffer length" +#: shared-bindings/is31fl3741/FrameBuffer.c +msgid "width must be greater than zero" msgstr "" -#: ports/nordic/common-hal/audiobusio/PDMIn.c -#: ports/stm/common-hal/audiobusio/PDMIn.c -msgid "only bit_depth=16 is supported" +#: shared-bindings/is31fl3741/FrameBuffer.c +msgid "Scale dimensions must divide by 3" msgstr "" -#: ports/stm/common-hal/audiobusio/PDMIn.c -msgid "only mono is supported" +#: shared-bindings/is31fl3741/FrameBuffer.c +msgid "LED mappings must match display size" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "only ndarrays can be concatenated" +#: shared-bindings/is31fl3741/IS31FL3741.c +msgid "Mapping must be a tuple" msgstr "" -#: ports/stm/common-hal/audiobusio/PDMIn.c -msgid "only oversample=64 is supported" +#: shared-bindings/jpegio/JpegDecoder.c +msgid "%q must be of type %q, %q, or %q, not %q" msgstr "" -#: ports/nordic/common-hal/audiobusio/PDMIn.c -#: ports/stm/common-hal/audiobusio/PDMIn.c -msgid "only sample_rate=16000 is supported" +#: shared-bindings/mdns/Server.c +msgid "" +"Failed to add service TXT record; non-string or bytes found in txt_records" msgstr "" -#: py/objarray.c py/objstr.c py/objstrunicode.c py/objtuple.c -#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c -#: shared-bindings/nvm/ByteArray.c -msgid "only slices with step=1 (aka None) are supported" +#: shared-bindings/memorymap/AddressRange.c +msgid "Address range wraps around" msgstr "" -#: py/vm.c -msgid "opcode" -msgstr "" +#: shared-bindings/microcontroller/Pin.c +msgid "%q contains duplicate pins" +msgstr "%q περιέχει διπλότυπα pins" -#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/bitwise.c -#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/numpy/vector.c -msgid "operands could not be broadcast together" -msgstr "" +#: shared-bindings/microcontroller/Pin.c +msgid "%q and %q contain duplicate pins" +msgstr "%q και %q περιέχουν διπλότυπα pins" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "operation is defined for 2D arrays only" +#: shared-bindings/mii/Ethernet.c shared-bindings/wifi/Radio.c +msgid "invalid hostname" msgstr "" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "operation is defined for ndarrays only" +#: shared-bindings/msgpack/ExtType.c +msgid "code outside range 0~127" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "operation is implemented for 1D Boolean arrays only" +#: shared-bindings/msgpack/__init__.c +msgid "default is not a function" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "operation is not implemented on ndarrays" +#: shared-bindings/msgpack/__init__.c +msgid "ext_hook is not a function" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "operation is not supported for given type" +#: shared-bindings/nvm/ByteArray.c +msgid "Unable to write to nvm." msgstr "" -#: extmod/ulab/code/ndarray_operators.c -msgid "operation not supported for the input types" +#: shared-bindings/os/__init__.c +msgid "No hardware random available" msgstr "" -#: py/modbuiltins.c -msgid "ord expects a character" +#: shared-bindings/paralleldisplaybus/ParallelBus.c +msgid "Specify exactly one of data0 or data_pins" msgstr "" -#: py/modbuiltins.c -#, c-format -msgid "ord() expected a character, but string of length %d found" +#: shared-bindings/picogame/Bitmap.c shared-module/msgpack/__init__.c +#: supervisor/shared/settings.c +msgid "Invalid format" msgstr "" -#: extmod/ulab/code/utils/utils.c -msgid "out array is too small" +#: shared-bindings/ps2io/Ps2.c +msgid "Failed sending command." msgstr "" -#: extmod/ulab/code/numpy/random/random.c -msgid "out has wrong type" +#: shared-bindings/pulseio/PulseOut.c +msgid "Array must contain halfwords (type 'H')" +msgstr "H παράταξη πρέπει να περιέχει halfwords (τύπου 'H')" + +#: shared-bindings/pwmio/PWMOut.c +msgid "Conflicting settings for shared resource" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "out keyword is not supported for complex dtype" +#: shared-bindings/random/__init__.c +msgid "stop not reachable from start" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "out keyword is not supported for function" +#: shared-bindings/random/__init__.c +msgid "invalid step" msgstr "" -#: extmod/ulab/code/utils/utils.c -msgid "out must be a float dense array" +#: shared-bindings/random/__init__.c +msgid "empty sequence" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "out must be an ndarray" +#: shared-bindings/rclcpy/Publisher.c +msgid "Publishers can only be created from a parent node" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "out must be of float dtype" +#: shared-bindings/rgbmatrix/RGBMatrix.c +#, c-format +msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "out of range of target" +#: 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 pin διεύθυνσης, %d rgb ping και %d πλακίδια αναδεικνύουν ύψος %d, όχι %d" -#: extmod/ulab/code/numpy/random/random.c -msgid "output array has wrong type" +#: shared-bindings/socketpool/Socket.c +msgid "port must be >= 0" msgstr "" -#: extmod/ulab/code/numpy/random/random.c -msgid "output array must be contiguous" +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c +msgid "buffer too small for requested bytes" msgstr "" -#: py/objint_mpz.c -msgid "overflow converting long int to machine word" +#: shared-bindings/socketpool/SocketPool.c +msgid "Name or service not known" msgstr "" -#: py/modstruct.c -#, c-format -msgid "pack expected %d items for packing (got %d)" +#: shared-bindings/spitarget/SPITarget.c +msgid "Packet buffers for an SPI transfer must have the same length." msgstr "" -#: shared-bindings/_stage/Layer.c shared-bindings/_stage/Text.c -msgid "palette must be 32 bytes long" +#: shared-bindings/ssl/SSLContext.c +msgid "Server side context cannot have hostname" msgstr "" -#: py/emitinlinextensa.c -msgid "parameters must be registers in sequence a2 to a5" +#: shared-bindings/storage/__init__.c shared-bindings/usb_audio/__init__.c +#: shared-bindings/usb_cdc/__init__.c shared-bindings/usb_hid/__init__.c +#: shared-bindings/usb_midi/__init__.c shared-bindings/usb_video/__init__.c +msgid "Cannot change USB devices now" +msgstr "Δεν μπορούν να αλλάξουν οι USB συσκευές τώρα" + +#: shared-bindings/supervisor/__init__.c shared-module/lvfontio/OnDiskFont.c +msgid "File not found" msgstr "" -#: py/emitinlinethumb.c -msgid "parameters must be registers in sequence r0 to r3" +#: shared-bindings/time/__init__.c +msgid "timestamp out of range for platform time_t" msgstr "" -#: extmod/vfs_posix_file.c -msgid "poll on file not available on win32" +#: shared-bindings/traceback/__init__.c +msgid "Supply both or neither of %q and %q" msgstr "" -#: ports/espressif/common-hal/pulseio/PulseIn.c -msgid "pop from an empty PulseIn" +#: shared-bindings/traceback/__init__.c +msgid "file write is not available" msgstr "" -#: ports/atmel-samd/common-hal/pulseio/PulseIn.c -#: ports/cxd56/common-hal/pulseio/PulseIn.c -#: ports/nordic/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" +#: shared-bindings/traceback/__init__.c +msgid "invalid exception" msgstr "" -#: shared-bindings/socketpool/Socket.c -msgid "port must be >= 0" +#: shared-bindings/usb_audio/USBSpeaker.c +msgid "destination must be an array of type 'h'" msgstr "" -#: py/compile.c -msgid "positional arg after **" +#: shared-bindings/usb_audio/__init__.c +msgid "At least one of microphone and speaker must be enabled" msgstr "" -#: py/compile.c -msgid "positional arg after keyword arg" +#: shared-bindings/usb_hid/Device.c +msgid "%q, %q, and %q must all be the same length" +msgstr "%q, %q, και %q πρέπει να είναι όλα του ιδίου μήκους" + +#: shared-bindings/util.c +msgid "" +"Object has been deinitialized and can no longer be used. Create a new object." msgstr "" -#: py/objint_mpz.c -msgid "pow() 3rd argument cannot be 0" +#: shared-bindings/warnings/__init__.c +msgid "%q must be a subclass of %q" +msgstr "%q πρέπει να είναι υποκλάση του %q" + +#: shared-bindings/wifi/Radio.c +msgid "Invalid hex password" msgstr "" -#: py/objint_mpz.c -msgid "pow() with 3 arguments requires integers" +#: shared-bindings/wifi/Radio.c +msgid "Invalid MAC address" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "pull masks conflict with direction masks" +#: shared-bindings/wifi/Radio.c +msgid "AuthMode.OPEN is not used with password" +msgstr "AuthMode.OPEN δεν μπορεί να χρησιμοποιηθεί με κωδικό" + +#: shared-bindings/wifi/Radio.c +msgid "Supply either %q or %q, not both" msgstr "" -#: py/parse.c -msgid "raw f-strings are not supported" +#: shared-bindings/wifi/Radio.c +msgid "Invalid BSSID" msgstr "" -#: extmod/ulab/code/numpy/fft/fft_tools.c -msgid "real and imaginary parts must be of equal length" +#: shared-bindings/wifi/Radio.c supervisor/shared/web_workflow/web_workflow.c +msgid "Authentication failure" +msgstr "Αποτυχία αυθεντικοποίησης" + +#: shared-bindings/wifi/Radio.c +msgid "No network with that ssid" msgstr "" -#: py/builtinimport.c -msgid "relative import" +#: shared-bindings/wifi/Radio.c +#, c-format +msgid "Unknown failure %d" msgstr "" -#: py/obj.c +#: shared-module/adafruit_bus_device/i2c_device/I2CDevice.c #, c-format -msgid "requested length %d but object has length %d" +msgid "No I2C device at address: 0x%x" msgstr "" -#: extmod/ulab/code/ndarray_operators.c -msgid "results cannot be cast to specified type" +#: shared-module/audiocore/WaveFile.c +msgid "Invalid format chunk size" msgstr "" -#: py/compile.c -msgid "return annotation must be an identifier" +#: shared-module/audiocore/__init__.c shared-module/usb_audio/USBMicrophone.c +msgid "The sample's %q does not match" msgstr "" -#: py/emitnative.c -msgid "return expected '%q' but got '%q'" +#: shared-module/audiodelays/MultiTapDelay.c +msgid "%q in %q must be of type %q or %q, not %q" msgstr "" -#: shared-bindings/rgbmatrix/RGBMatrix.c -#, c-format -msgid "rgb_pins[%d] duplicates another pin assignment" +#: shared-module/audiofilewriter/AudioFileWriter.c +msgid "Only 8/16-bit mono/stereo is supported" msgstr "" -#: shared-bindings/rgbmatrix/RGBMatrix.c -#, c-format -msgid "rgb_pins[%d] is not on the same port as clock" +#: shared-module/audiofilewriter/AudioFileWriter.c +msgid "buffer_size too small for source" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "roll argument must be an ndarray" +#: shared-module/audiomp3/MP3Decoder.c +msgid "Couldn't allocate decoder" +msgstr "Δεν μπόρεσε να δεσμευτεί decoder" + +#: shared-module/audiomp3/MP3Decoder.c +msgid "Failed to parse MP3 file" msgstr "" -#: py/objstr.c -msgid "rsplit(None,n)" +#: shared-module/bitbangio/I2C.c shared-module/msgpack/__init__.c +msgid "%q too long" msgstr "" -#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c -#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c -msgid "sampling rate out of range" +#: shared-module/bitmapfilter/__init__.c +msgid "bitmap size and depth must match" msgstr "" -#: py/modmicropython.c -msgid "schedule queue full" +#: shared-module/bitmapfilter/__init__.c +msgid "unsupported bitmap depth" msgstr "" -#: py/builtinimport.c -msgid "script compilation not supported" +#: shared-module/busdisplay/lvgl/BusDisplay.c +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "LVGL display create failed" msgstr "" -#: py/nativeglue.c -msgid "set unsupported" +#: shared-module/busdisplay/lvgl/BusDisplay.c +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "LVGL buffer alloc failed" msgstr "" -#: extmod/ulab/code/numpy/random/random.c -msgid "shape must be None, and integer or a tuple of integers" +#: shared-module/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "OAEP requires this build to enable TLS 1.3 support" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "shape must be integer or tuple of integers" +#: shared-module/displayio/bus_core.c +msgid "Unsupported display bus type" msgstr "" -#: shared-module/msgpack/__init__.c -msgid "short read" +#: shared-module/displayio/legacy/Bitmap.c +#: shared-module/displayio/lvgl/Bitmap.c +msgid "Invalid bits per value" msgstr "" -#: py/objstr.c -msgid "sign not allowed in string format specifier" +#: shared-module/displayio/legacy/ColorConverter.c +#: shared-module/displayio/lvgl/ColorConverter.c +msgid "Only one color can be transparent at a time" msgstr "" -#: py/objstr.c -msgid "sign not allowed with integer format specifier 'c'" +#: shared-module/displayio/legacy/Group.c shared-module/displayio/lvgl/Group.c +msgid "Layer already in a group" msgstr "" -#: extmod/ulab/code/ulab_tools.c -msgid "size is defined for ndarrays only" +#: shared-module/displayio/legacy/Group.c +msgid "Layer must be a Group or TileGrid subclass" msgstr "" -#: extmod/ulab/code/numpy/random/random.c -msgid "size must match out.shape when used together" +#: shared-module/displayio/legacy/OnDiskBitmap.c +#: shared-module/displayio/lvgl/OnDiskBitmap.c +#, c-format +msgid "" +"Only Windows format, uncompressed BMP supported: given header size is %d" msgstr "" -#: py/nativeglue.c -msgid "slice unsupported" +#: shared-module/displayio/legacy/OnDiskBitmap.c +#: shared-module/displayio/lvgl/OnDiskBitmap.c +msgid "RLE-compressed BMP not supported" msgstr "" -#: py/objint.c py/sequence.c -msgid "small int overflow" +#: shared-module/displayio/legacy/OnDiskBitmap.c +#: shared-module/displayio/lvgl/OnDiskBitmap.c +msgid "Unable to read color palette data" msgstr "" -#: main.c -msgid "soft reboot\n" +#: shared-module/displayio/legacy/__init__.c +msgid "Too many displays" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "sort argument must be an ndarray" +#: shared-module/displayio/legacy/__init__.c +msgid "Too many display buses; deinit() unused displays" msgstr "" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "sos array must be of shape (n_section, 6)" +#: shared-module/displayio/lvgl/Group.c +msgid "Layer does not support scaling" msgstr "" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "sos[:, 3] should be all ones" +#: shared-module/displayio/lvgl/Group.c +msgid "Layer must be a Group, TileGrid, vector shape or VideoBuffer" msgstr "" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "sosfilt requires iterable arguments" +#: shared-module/displayio/lvgl/TileGrid.c +msgid "LVGL displayio backend does not support flips/transpose yet" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "source palette too large" +#: shared-module/displayio/lvgl/TileGrid.c +msgid "OnDiskBitmap requires its own pixel_shader" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "source_bitmap must have value_count of 2 or 65536" +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "LVGL dirty row alloc failed" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "source_bitmap must have value_count of 65536" +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +#: shared-module/videocore/VideoBuffer.c +#: shared-module/videocore/legacy/VideoBuffer.c +#: shared-module/videocore/lvgl/VideoBuffer.c +msgid "VideoBuffer can't stream into a rotated display" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "source_bitmap must have value_count of 8" +#: shared-module/gifio/GifWriter.c +msgid "unsupported colorspace for GifWriter" msgstr "" -#: extmod/modre.c -msgid "splitting with sub-captures" +#: shared-module/hmac/HMAC.c +msgid "key does not support this digest" msgstr "" -#: py/objstr.c -msgid "start/end indices" +#: shared-module/hmac/HMAC.c +msgid "HMAC of an empty message is not supported with a hardware key" msgstr "" -#: shared-bindings/random/__init__.c -msgid "stop not reachable from start" +#: shared-module/i2cdisplaybus/I2CDisplayBus.c +#: shared-module/is31fl3741/IS31FL3741.c +#, c-format +msgid "Unable to find I2C Display at %x" msgstr "" -#: py/stream.c shared-bindings/getpass/__init__.c -msgid "stream operation not supported" +#: shared-module/i2cioexpander/IOExpander.c +msgid "Cannot deinitialize board IOExpander" msgstr "" -#: py/objarray.c py/objstr.c -msgid "string argument without an encoding" +#: shared-module/imagecapture/ParallelImageCapture.c +msgid "This microcontroller does not support continuous capture." msgstr "" -#: py/objstrunicode.c -msgid "string index out of range" +#: shared-module/jpegio/JpegDecoder.c +msgid "Interrupted by output function" msgstr "" -#: py/objstrunicode.c -#, c-format -msgid "string indices must be integers, not %s" +#: shared-module/jpegio/JpegDecoder.c +msgid "Device error or wrong termination of input stream" msgstr "" -#: py/objarray.c py/objstr.c -msgid "substring not found" +#: shared-module/jpegio/JpegDecoder.c +msgid "Insufficient memory pool for the image" msgstr "" -#: py/compile.c -msgid "super() can't find self" +#: shared-module/jpegio/JpegDecoder.c +msgid "Insufficient stream input buffer" msgstr "" -#: extmod/modjson.c -msgid "syntax error in JSON" +#: shared-module/jpegio/JpegDecoder.c +msgid "Parameter error" msgstr "" -#: extmod/modtime.c -msgid "ticks interval overflow" +#: shared-module/jpegio/JpegDecoder.c +msgid "Data format error (may be broken data)" msgstr "" -#: ports/nordic/common-hal/watchdog/WatchDogTimer.c -msgid "timeout duration exceeded the maximum supported value" +#: shared-module/jpegio/JpegDecoder.c +msgid "Right format but not supported" msgstr "" -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "timeout must be < 655.35 secs" +#: shared-module/jpegio/JpegDecoder.c +msgid "Unsupported JPEG (may be progressive)" msgstr "" -#: ports/raspberrypi/common-hal/floppyio/__init__.c -msgid "timeout waiting for flux" +#: shared-module/jpegio/JpegDecoder.c +msgid "%q() without %q()" msgstr "" -#: ports/raspberrypi/common-hal/floppyio/__init__.c -#: shared-module/floppyio/__init__.c -msgid "timeout waiting for index pulse" +#: shared-module/memorymonitor/AllocationAlarm.c +#, c-format +msgid "Attempt to allocate %d blocks" +msgstr "Προσπάθεια να δεσμευτούν %d blocks" + +#: shared-module/msgpack/__init__.c +msgid "short read" msgstr "" -#: shared-module/sdcardio/SDCard.c -msgid "timeout waiting for v1 card" +#: shared-module/msgpack/__init__.c +msgid "no default packer" msgstr "" -#: shared-module/sdcardio/SDCard.c -msgid "timeout waiting for v2 card" +#: shared-module/paralleldisplaybus/ParallelBus.c +msgid "" +"This microcontroller only supports data0=, not data_pins=, because it " +"requires contiguous pins." msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "timer re-init" +#: shared-module/rgbmatrix/RGBMatrix.c +msgid "The length of rgb_pins must be 6, 12, 18, 24, or 30" msgstr "" -#: shared-bindings/time/__init__.c -msgid "timestamp out of range for platform time_t" +#: shared-module/rgbmatrix/RGBMatrix.c +#, c-format +msgid "rgb_pins[%d] is not on the same port as clock" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "tobytes can be invoked for dense arrays only" +#: shared-module/rgbmatrix/RGBMatrix.c +#, c-format +msgid "rgb_pins[%d] duplicates another pin assignment" msgstr "" -#: py/compile.c -msgid "too many args" +#: shared-module/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 "" -#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/create.c -msgid "too many dimensions" +#: shared-module/rgbmatrix/RGBMatrix.c +msgid "No timer available" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "too many indices" +#: shared-module/rgbmatrix/RGBMatrix.c +#, c-format +msgid "Internal error #%d" msgstr "" -#: py/asmthumb.c -msgid "too many locals for native method" +#: shared-module/sdcardio/SDCard.c +msgid "timeout waiting for v1 card" msgstr "" -#: py/runtime.c -#, c-format -msgid "too many values to unpack (expected %d)" +#: shared-module/sdcardio/SDCard.c +msgid "timeout waiting for v2 card" msgstr "" -#: extmod/ulab/code/numpy/approx.c -msgid "trapz is defined for 1D arrays of equal length" +#: shared-module/sdcardio/SDCard.c +msgid "no SD card" +msgstr "" + +#: shared-module/sdcardio/SDCard.c +msgid "couldn't determine SD card version" msgstr "" -#: extmod/ulab/code/numpy/approx.c -msgid "trapz is defined for 1D iterables" +#: shared-module/sdcardio/SDCard.c +msgid "no response from SD card" msgstr "" -#: py/obj.c -msgid "tuple/list has wrong length" +#: shared-module/sdcardio/SDCard.c +msgid "SD card CSD format not supported" msgstr "" -#: ports/espressif/common-hal/canio/CAN.c -#, c-format -msgid "twai_driver_install returned esp-idf error #%d" +#: shared-module/sdcardio/SDCard.c +msgid "can't set 512 block size" msgstr "" -#: ports/espressif/common-hal/canio/CAN.c -#, c-format -msgid "twai_start returned esp-idf error #%d" +#: shared-module/ssl/SSLSocket.c +msgid "Invalid socket for TLS" msgstr "" -#: shared-bindings/busio/UART.c shared-bindings/canio/CAN.c -msgid "tx and rx cannot both be None" +#: shared-module/ssl/SSLSocket.c +msgid "invalid cert" msgstr "" -#: py/objtype.c -msgid "type '%q' is not an acceptable base type" +#: shared-module/storage/__init__.c +msgid "File write in progress" msgstr "" -#: py/objtype.c -msgid "type is not an acceptable base type" +#: shared-module/storage/__init__.c +msgid "Mount point directory missing" msgstr "" -#: py/runtime.c -msgid "type object '%q' has no attribute '%q'" +#: shared-module/storage/__init__.c +msgid "Cannot remount path when visible via USB." msgstr "" -#: py/objtype.c -msgid "type takes 1 or 3 arguments" +#: shared-module/struct/__init__.c +msgid "'S' and 'O' are not supported format types" +msgstr "'S' και 'O' δεν είναι υποστηριζόμενοι τύποι format" + +#: shared-module/struct/__init__.c +msgid "buffer size must match format" msgstr "" -#: py/objint_longlong.c -msgid "ulonglong too large" +#: shared-module/synthio/__init__.c +msgid "%q must be array of type 'h'" +msgstr "%q πρέπει να είναι λίστα τύπου 'h'" + +#: shared-module/tilepalettemapper/TilePaletteMapper.c +msgid "TilePaletteMapper may only be bound to a TileGrid once" msgstr "" -#: py/parse.c -msgid "unexpected indent" +#: shared-module/touchio/TouchIn.c +msgid "No pullup on pin; 1Mohm recommended" msgstr "" -#: py/bc.c -msgid "unexpected keyword argument" +#: shared-module/touchio/TouchIn.c +msgid "No pulldown on pin; 1Mohm recommended" msgstr "" -#: py/argcheck.c py/bc.c py/objnamedtuple.c -#: shared-bindings/traceback/__init__.c -msgid "unexpected keyword argument '%q'" +#: shared-module/usb/core/Device.c +msgid "No usb host port initialized" msgstr "" -#: py/lexer.c -msgid "unicode name escapes" +#: shared-module/usb/core/Device.c +msgid "Pipe error" msgstr "" -#: py/parse.c -msgid "unindent doesn't match any outer indent level" +#: shared-module/usb/core/Device.c +msgid "No configuration set" msgstr "" -#: py/objstr.c -#, c-format -msgid "unknown conversion specifier %c" +#: shared-module/usb_hid/Device.c +msgid "USB busy" msgstr "" -#: py/objstr.c -msgid "unknown format code '%c' for object of type '%q'" +#: shared-module/vectorio/Circle.c shared-module/vectorio/Polygon.c +#: shared-module/vectorio/Rectangle.c +msgid "can only have one parent" msgstr "" -#: py/compile.c -msgid "unknown type" +#: shared-module/vectorio/Polygon.c +msgid "Polygon needs at least 3 points" msgstr "" -#: py/compile.c -msgid "unknown type '%q'" +#: shared-module/videocore/VideoBuffer.c +msgid "framebuffer went away" msgstr "" -#: py/objstr.c -#, c-format -msgid "unmatched '%c' in format" +#: shared-module/videocore/VideoBuffer.c +msgid "video doesn't fit in framebuffer" msgstr "" -#: py/objtype.c py/runtime.c -msgid "unreadable attribute" +#: shared-module/videocore/VideoBuffer.c +msgid "framebuffer missing required functions" msgstr "" -#: shared-bindings/displayio/TileGrid.c shared-bindings/vectorio/VectorShape.c -msgid "unsupported %q type" +#: shared-module/videocore/VideoBuffer.c +msgid "video format must be byte aligned" msgstr "" -#: py/emitinlinethumb.c -#, c-format -msgid "unsupported Thumb instruction '%s' with %d arguments" +#: shared-module/videocore/VideoBuffer.c +msgid "video format doesn't match framebuffer" msgstr "" -#: py/emitinlinextensa.c -#, c-format -msgid "unsupported Xtensa instruction '%s' with %d arguments" +#: shared-module/videocore/VideoBuffer.c +msgid "video source rejected the destination" msgstr "" -#: shared-module/bitmapfilter/__init__.c -msgid "unsupported bitmap depth" +#: shared-module/videocore/VideoBuffer.c +msgid "video in a framebuffer must be at x == 0" msgstr "" -#: shared-module/gifio/GifWriter.c -msgid "unsupported colorspace for GifWriter" +#: shared-module/videocore/VideoBuffer.c +msgid "video size changed since play; stop and play again" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "unsupported colorspace for dither" +#: shared-module/videocore/VideoBuffer.c +msgid "VideoBuffer is playing into a different framebuffer" msgstr "" -#: py/objstr.c -#, c-format -msgid "unsupported format character '%c' (0x%x) at index %d" +#: shared-module/videocore/legacy/VideoBuffer.c +msgid "VideoBuffer does not support transforms" msgstr "" -#: py/runtime.c -msgid "unsupported type for %q: '%s'" +#: shared-module/videocore/lvgl/VideoBuffer.c +msgid "video format must be 16, 24 or 32 bits per pixel" msgstr "" -#: py/runtime.c -msgid "unsupported type for operator" +#: supervisor/shared/bluetooth/bluetooth.c +msgid "Reconnecting" msgstr "" -#: py/runtime.c -msgid "unsupported types for %q: '%q', '%q'" +#: supervisor/shared/bluetooth/bluetooth.c +msgid "Ok" msgstr "" -#: extmod/ulab/code/numpy/io/io.c -msgid "usecols is too high" +#: supervisor/shared/bluetooth/bluetooth.c +msgid "Off" msgstr "" -#: extmod/ulab/code/numpy/io/io.c -msgid "usecols keyword must be specified" +#: supervisor/shared/micropython.c +msgid "[truncated due to length]" msgstr "" -#: py/objint.c -#, c-format -msgid "value must fit in %d byte(s)" +#: supervisor/shared/safe_mode.c +msgid "" +"\n" +"You are in safe mode because:\n" msgstr "" +"\n" +"Είσαστε τε ασφαλή λειτουργία διότι:\n" -#: shared-bindings/bitmaptools/__init__.c -msgid "value out of range of target" +#: supervisor/shared/safe_mode.c +msgid "Power dipped. Make sure you are providing enough power." msgstr "" -#: extmod/moddeflate.c -msgid "wbits" +#: supervisor/shared/safe_mode.c +msgid "You pressed the BOOT button at start up" msgstr "" -#: shared-bindings/bitmapfilter/__init__.c -msgid "" -"weights must be a sequence with an odd square number of elements (usually 9 " -"or 25)" +#: supervisor/shared/safe_mode.c +msgid "You pressed the reset button during boot." msgstr "" -#: shared-bindings/bitmapfilter/__init__.c -msgid "weights must be an object of type %q, %q, %q, or %q, not %q " +#: supervisor/shared/safe_mode.c +msgid "CIRCUITPY drive could not be found or created." +msgstr "Ο CIRCUITPY δίσκος δεν μπόρεσε να βρεθεί ή να δημιουργηθεί." + +#: supervisor/shared/safe_mode.c +msgid "The `microcontroller` module was used to boot into safe mode." msgstr "" -#: shared-bindings/is31fl3741/FrameBuffer.c -msgid "width must be greater than zero" +#: supervisor/shared/safe_mode.c +msgid "Error in safemode.py." +msgstr "Σφάλμα στο safemode.py." + +#: supervisor/shared/safe_mode.c +msgid "Stack overflow. Increase stack size." msgstr "" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/raspberrypi/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "wifi is not enabled" +#: supervisor/shared/safe_mode.c +msgid "USB devices need more endpoints than are available." msgstr "" -#: ports/raspberrypi/common-hal/wifi/Monitor.c -msgid "wifi.Monitor not available" +#: supervisor/shared/safe_mode.c +msgid "USB devices specify too many interface names." msgstr "" -#: shared-bindings/_bleio/Adapter.c -msgid "window must be <= interval" +#: supervisor/shared/safe_mode.c +msgid "Boot device must be first (interface #0)." +msgstr "Η συσκευή εκκίνησης πρέπει να επιλεχθεί πρώτα (διεπαφή #0)." + +#: supervisor/shared/safe_mode.c +msgid "Internal watchdog timer expired." msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "wrong axis index" +#: supervisor/shared/safe_mode.c +msgid "CircuitPython core code crashed hard. Whoops!\n" +msgstr "Ο πυρήνας της CircuitPython κατέρευσε. Οουπς!\n" + +#: supervisor/shared/safe_mode.c +msgid "Heap allocation when VM not running." msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "wrong axis specified" +#: supervisor/shared/safe_mode.c +msgid "Failed to write internal flash." msgstr "" -#: extmod/ulab/code/numpy/io/io.c -msgid "wrong dtype" +#: supervisor/shared/safe_mode.c +msgid "Hard fault: memory access or instruction error." msgstr "" -#: extmod/ulab/code/numpy/transform.c -msgid "wrong index type" +#: supervisor/shared/safe_mode.c +msgid "Interrupt error." msgstr "" -#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/numpy/create.c -#: extmod/ulab/code/numpy/io/io.c extmod/ulab/code/numpy/transform.c -#: extmod/ulab/code/numpy/vector.c -msgid "wrong input type" +#: supervisor/shared/safe_mode.c +msgid "LVGL ran out of memory." msgstr "" -#: extmod/ulab/code/numpy/transform.c -msgid "wrong length of condition array" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." msgstr "" -#: extmod/ulab/code/numpy/transform.c -msgid "wrong length of index array" +#: supervisor/shared/safe_mode.c +msgid "Unable to allocate to the heap." msgstr "" -#: extmod/ulab/code/numpy/create.c py/objarray.c py/objstr.c -msgid "wrong number of arguments" +#: supervisor/shared/safe_mode.c +msgid "Third-party firmware fatal error." msgstr "" -#: py/runtime.c -msgid "wrong number of values to unpack" +#: supervisor/shared/safe_mode.c +msgid "" +"\n" +"Please file an issue with your program at github.com/adafruit/circuitpython/" +"issues." msgstr "" +"\n" +"Παρακαλώ δημιουργήστε ένα πρόβλημα με το πρόγραμμά σας στο github.com/" +"adafruit/circuitpython/issues." -#: extmod/ulab/code/numpy/vector.c -msgid "wrong output type" +#: supervisor/shared/safe_mode.c +msgid "" +"\n" +"Press reset to exit safe mode.\n" msgstr "" +"\n" +"Πατήστε reset για να βγείτε από την ασφαλή λειτουργία.\n" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "zi must be an ndarray" +#: supervisor/shared/settings.c +#, c-format +msgid "An error occurred while retrieving '%s':\n" +msgstr "Παρουσιάστηκε σφάλμα κατά την ανάκτηση '%s':\n" + +#: supervisor/shared/settings.c +msgid "Invalid unicode escape" msgstr "" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "zi must be of float type" +#: supervisor/shared/web_workflow/web_workflow.c +msgid "Wi-Fi: " +msgstr "Wi-Fi: " + +#: supervisor/shared/web_workflow/web_workflow.c +msgid "off" msgstr "" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "zi must be of shape (n_section, 2)" +#: supervisor/shared/web_workflow/web_workflow.c +msgid "No IP" msgstr "" +#~ msgid "%q out of bounds" +#~ msgstr "%q εκτός ορίων" + +#~ msgid "%q renamed %q" +#~ msgstr "%q μεταονομάστηκε σε %q" + +#, c-format +#~ msgid "Buffer + offset too small %d %d %d" +#~ msgstr "Buffer + offset είναι πολύ μικρά %d %d %d" + +#~ msgid "Byte buffer must be 16 bytes." +#~ msgstr "Byte buffer πρέπει να είναι 16 bytes." + +#~ msgid "%q moved from %q to %q" +#~ msgstr "%q μετακινήθηκε από το %q στο %q" + +#, c-format +#~ msgid "%%c requires int or char" +#~ msgstr "%%c απαιτεί ακέραιο ή χαρακτήρα" + +#~ msgid "'%q' object is not callable" +#~ msgstr "'%q' αντικείμενο δεν καλείται" + +#~ msgid "Cannot remount '/' when visible via USB." +#~ msgstr "Δεν μπορεί να γίνει remount του '/' όταν είναι ορατό μέσω USB." + #~ msgid "Data chunk must follow fmt chunk" #~ msgstr "Το data chunk πρέπει να ακολουθεί το fmt chunk" @@ -4568,7 +5245,7 @@ msgstr "" #~ msgid "'continue' outside loop" #~ msgstr "'continue' εκτός επανάληψης" -#~ msgid "'coroutine' object is not an iterator" +#~ msgid "'coroutine' object isn't an iterator" #~ msgstr "" #~ "'coroutine' αντικείμενο δεν μπορεί να χρησιμοποιηθεί σαν επαναλήπτης" diff --git a/locale/en_GB.po b/locale/en_GB.po index 1165ac6d837..29380c91c80 100644 --- a/locale/en_GB.po +++ b/locale/en_GB.po @@ -7,7 +7,7 @@ msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" -"PO-Revision-Date: 2025-03-06 13:42+0000\n" +"PO-Revision-Date: 2026-04-30 11:09+0000\n" "Last-Translator: Andi Chandler \n" "Language-Team: none\n" "Language: en_GB\n" @@ -15,7 +15,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 5.10.3-dev\n" +"X-Generator: Weblate 5.17.1\n" #: main.c msgid "" @@ -95,7 +95,7 @@ msgstr "" msgid "%q and %q contain duplicate pins" msgstr "%q and %q contain duplicate pins" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: shared-bindings/audioio/AudioOut.c msgid "%q and %q must be different" msgstr "%q and %q must be different" @@ -115,6 +115,10 @@ msgstr "%q contains duplicate pins" msgid "%q failure: %d" msgstr "%q failure: %d" +#: shared-module/audiodelays/MultiTapDelay.c +msgid "%q in %q must be of type %q or %q, not %q" +msgstr "%q in %q must be of type %q or %q, not %q" + #: py/argcheck.c shared-module/audiofilters/Filter.c msgid "%q in %q must be of type %q, not %q" msgstr "%q in %q must be of type %q, not %q" @@ -167,7 +171,7 @@ msgstr "%q length must be <= %d" msgid "%q length must be >= %d" msgstr "%q length must be >= %d" -#: py/modsys.c py/objmodule.c py/runtime.c +#: py/modsys.c py/runtime.c msgid "%q moved from %q to %q" msgstr "%q moved from %q to %q" @@ -228,7 +232,7 @@ msgstr "%q must be multiple of 8." #: shared-bindings/bitmapfilter/__init__.c shared-bindings/canio/CAN.c #: shared-bindings/digitalio/Pull.c shared-bindings/supervisor/__init__.c #: shared-module/audiofilters/Filter.c shared-module/displayio/__init__.c -#: shared-module/synthio/Biquad.c shared-module/synthio/Synthesizer.c +#: shared-module/synthio/Synthesizer.c msgid "%q must be of type %q or %q, not %q" msgstr "%q must be of type %q or %q, not %q" @@ -237,6 +241,7 @@ msgid "%q must be of type %q, %q, or %q, not %q" msgstr "%q must be of type %q, %q, or %q, not %q" #: py/argcheck.c py/runtime.c shared-bindings/bitmapfilter/__init__.c +#: shared-module/audiodelays/MultiTapDelay.c shared-module/synthio/Note.c #: shared-module/synthio/__init__.c msgid "%q must be of type %q, not %q" msgstr "%q must be of type %q, not %q" @@ -317,16 +322,16 @@ msgid "'%q' object does not support '%q'" msgstr "'%q' object does not support '%q'" #: py/runtime.c -msgid "'%q' object is not an iterator" -msgstr "'%q' object is not an iterator" +msgid "'%q' object isn't an iterator" +msgstr "'%q' object isn't an iterator" #: py/objtype.c py/runtime.c shared-module/atexit/__init__.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" +msgid "'%q' object isn't iterable" +msgstr "'%q' object isn't iterable" #: py/emitinlinethumb.c py/emitinlinextensa.c #, c-format @@ -522,7 +527,7 @@ msgstr "All channels in use" #: ports/raspberrypi/common-hal/usb_host/Port.c msgid "All dma channels in use" -msgstr "All DMA channels in use" +msgstr "All dma channels in use" #: ports/atmel-samd/common-hal/audioio/AudioOut.c msgid "All event channels in use" @@ -804,8 +809,8 @@ msgid "Cannot record to a file" msgstr "Cannot record to a file" #: shared-module/storage/__init__.c -msgid "Cannot remount '/' when visible via USB." -msgstr "Cannot remount '/' when visible via USB." +msgid "Cannot remount path when visible via USB." +msgstr "Cannot remount path when visible via USB." #: shared-bindings/digitalio/DigitalInOut.c msgid "Cannot set value when direction is input." @@ -860,6 +865,10 @@ msgstr "Coordinate arrays have different lengths" msgid "Coordinate arrays types have different sizes" msgstr "Coordinate arrays types have different sizes" +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "Could not publish to ROS topic" +msgstr "Could not publish to ROS topic" + #: shared-bindings/_bleio/Adapter.c msgid "Could not set address" msgstr "Could not set address" @@ -872,6 +881,11 @@ msgstr "Could not start interrupt, RX busy" msgid "Couldn't allocate decoder" msgstr "Couldn't allocate decoder" +#: ports/espressif/common-hal/rclcpy/__init__.c +#, c-format +msgid "Critical ROS failure during soft reboot, reset required: %d" +msgstr "Critical ROS failure during soft reboot, reset required: %d" + #: ports/stm/common-hal/analogio/AnalogOut.c msgid "DAC Channel Init Error" msgstr "DAC channel init error" @@ -1069,6 +1083,7 @@ msgstr "Failed to write internal flash." msgid "File exists" msgstr "File exists" +#: shared-bindings/supervisor/__init__.c shared-module/lvfontio/OnDiskFont.c #: shared-module/os/getenv.c msgid "File not found" msgstr "File not found" @@ -1100,7 +1115,7 @@ msgstr "For L8 colourspace, input bitmap must have 8 bits per pixel" msgid "For RGB colorspaces, input bitmap must have 16 bits per pixel" msgstr "For RGB colourspaces, input bitmap must have 16 bits per pixel" -#: ports/cxd56/common-hal/camera/Camera.c +#: ports/cxd56/common-hal/camera/Camera.c shared-module/audiocore/WaveFile.c msgid "Format not supported" msgstr "Format not supported" @@ -1265,7 +1280,9 @@ msgstr "Interrupted by output function" #: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c py/argcheck.c #: shared-bindings/digitalio/DigitalInOut.c #: shared-bindings/epaperdisplay/EPaperDisplay.c shared-bindings/pwmio/PWMOut.c +#: shared-bindings/supervisor/__init__.c #: shared-module/aurora_epaper/aurora_framebuffer.c +#: shared-module/lvfontio/OnDiskFont.c msgid "Invalid %q" msgstr "Invalid %q" @@ -1298,6 +1315,10 @@ msgstr "Invalid BSSID" msgid "Invalid MAC address" msgstr "Invalid MAC address" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "Invalid ROS domain ID" +msgstr "Invalid ROS domain ID" + #: ports/espressif/common-hal/espidf/__init__.c py/moderrno.c msgid "Invalid argument" msgstr "Invalid argument" @@ -1387,6 +1408,11 @@ msgstr "MAC address was invalid" msgid "MITM security not supported" msgstr "MITM security is not supported" +#: ports/stm/common-hal/sdioio/SDCard.c +#, c-format +msgid "MMC/SDIO Clock Error %x" +msgstr "MMC/SDIO Clock Error %x" + #: shared-bindings/is31fl3741/IS31FL3741.c msgid "Mapping must be a tuple" msgstr "Mapping must be a tuple" @@ -1573,6 +1599,10 @@ msgstr "No pull up found on SDA or SCL; check your wiring" msgid "No pulldown on pin; 1Mohm recommended" msgstr "No pulldown on pin; 1Mohm recommended" +#: shared-module/touchio/TouchIn.c +msgid "No pullup on pin; 1Mohm recommended" +msgstr "No pullup on pin; 1Mohm recommended" + #: py/moderrno.c msgid "No space left on device" msgstr "No space left on device" @@ -1848,6 +1878,10 @@ msgstr "Program size invalid" msgid "Program too long" msgstr "Program too long" +#: shared-bindings/rclcpy/Publisher.c +msgid "Publishers can only be created from a parent node" +msgstr "Publishers can only be created from a parent node" + #: shared-bindings/digitalio/DigitalInOut.c msgid "Pull not used when direction is output." msgstr "Pull not used when direction is output." @@ -1868,6 +1902,26 @@ msgstr "RNG deinit Error" msgid "RNG Init Error" msgstr "RNG init Error" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS failed to initialize. Is agent connected?" +msgstr "ROS failed to initialise. Is agent connected?" + +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS internal setup failure" +msgstr "ROS internal setup failure" + +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS memory allocator failure" +msgstr "ROS memory allocator failure" + +#: ports/espressif/common-hal/rclcpy/Node.c +msgid "ROS node failed to initialize" +msgstr "ROS node failed to initialise" + +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "ROS topic failed to initialize" +msgstr "ROS topic failed to initialise" + #: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c #: ports/nordic/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c msgid "RS485" @@ -1999,6 +2053,7 @@ msgstr "Slice and value different lengths." #: shared-bindings/displayio/TileGrid.c #: shared-bindings/memorymonitor/AllocationSize.c #: shared-bindings/pulseio/PulseIn.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c msgid "Slices not supported" msgstr "Slices not supported" @@ -2068,7 +2123,9 @@ msgstr "" 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 +#: shared-bindings/displayio/TileGrid.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-module/displayio/TileGrid.c msgid "Tile index out of bounds" msgstr "Tile index out of bounds" @@ -2076,6 +2133,10 @@ msgstr "Tile index out of bounds" msgid "Tile width must exactly divide bitmap width" msgstr "Tile width must exactly divide bitmap width" +#: shared-module/tilepalettemapper/TilePaletteMapper.c +msgid "TilePaletteMapper may only be bound to a TileGrid once" +msgstr "TilePaletteMapper may only be bound to a TileGrid once" + #: shared-bindings/alarm/time/TimeAlarm.c msgid "Time is in the past." msgstr "Time is in the past." @@ -2304,10 +2365,6 @@ msgstr "Unsupported colourspace" msgid "Unsupported display bus type" msgstr "Unsupported display bus type" -#: shared-module/audiocore/WaveFile.c -msgid "Unsupported format" -msgstr "Unsupported format" - #: shared-bindings/hashlib/__init__.c msgid "Unsupported hash algorithm" msgstr "Unsupported hash algorithm" @@ -2369,9 +2426,11 @@ msgstr "" msgid "Wi-Fi: " msgstr "Wi-Fi: " +#: ports/espressif/common-hal/wifi/Radio.c #: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "Wifi is not enabled" -msgstr "Wifi is not enabled" +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "WiFi is not enabled" +msgstr "WiFi is not enabled" #: main.c msgid "Woken up by alarm.\n" @@ -2606,9 +2665,16 @@ msgstr "bitmap sizes must match" msgid "bits must be 32 or less" msgstr "bits must be 32 or less" -#: shared-bindings/audiodelays/Echo.c shared-bindings/audiodelays/PitchShift.c +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "bits_per_sample must be 16" +msgstr "bits_per_sample must be 16" + +#: shared-bindings/audiodelays/Chorus.c shared-bindings/audiodelays/Echo.c +#: shared-bindings/audiodelays/MultiTapDelay.c +#: shared-bindings/audiodelays/PitchShift.c #: shared-bindings/audiofilters/Distortion.c -#: shared-bindings/audiofilters/Filter.c shared-bindings/audiomixer/Mixer.c +#: shared-bindings/audiofilters/Filter.c shared-bindings/audiofilters/Phaser.c +#: shared-bindings/audiomixer/Mixer.c msgid "bits_per_sample must be 8 or 16" msgstr "bits_per_sample must be 8 or 16" @@ -3151,8 +3217,8 @@ msgid "format" msgstr "format" #: py/objstr.c -msgid "format requires a dict" -msgstr "format requires a dict" +msgid "format needs a dict" +msgstr "format needs a dict" #: py/objdeque.c msgid "full" @@ -3610,8 +3676,8 @@ 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" +msgid "name '%q' isn't defined" +msgstr "name '%q' isn't defined" #: py/runtime.c msgid "name not defined" @@ -4028,6 +4094,10 @@ msgstr "roll argument must be an ndarray" msgid "rsplit(None,n)" msgstr "rsplit(None,n)" +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "samples_signed must be true" +msgstr "samples_signed must be true" + #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c #: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "sampling rate out of range" @@ -4247,12 +4317,12 @@ 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" +msgid "type '%q' isn't an acceptable base type" +msgstr "type '%q' isn't an acceptable base type" #: py/objtype.c -msgid "type is not an acceptable base type" -msgstr "type is not an acceptable base type" +msgid "type isn't an acceptable base type" +msgstr "type isn't an acceptable base type" #: py/runtime.c msgid "type object '%q' has no attribute '%q'" @@ -4313,7 +4383,9 @@ msgstr "unmatched '%c' in format" msgid "unreadable attribute" msgstr "unreadable attribute" -#: shared-bindings/displayio/TileGrid.c shared-bindings/vectorio/VectorShape.c +#: shared-bindings/displayio/TileGrid.c shared-bindings/terminalio/Terminal.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-bindings/vectorio/VectorShape.c msgid "unsupported %q type" msgstr "unsupported %q type" @@ -4393,12 +4465,6 @@ msgstr "weights must be an object of type %q, %q, %q, or %q, not %q " msgid "width must be greater than zero" msgstr "width must be greater than zero" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/raspberrypi/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "wifi is not enabled" -msgstr "WiFi is not enabled" - #: ports/raspberrypi/common-hal/wifi/Monitor.c msgid "wifi.Monitor not available" msgstr "wifi.Monitor not available" @@ -4461,6 +4527,18 @@ msgstr "zi must be of float type" msgid "zi must be of shape (n_section, 2)" msgstr "zi must be of shape (n_section, 2)" +#~ msgid "Unsupported format" +#~ msgstr "Unsupported format" + +#~ msgid "Wifi is not enabled" +#~ msgstr "Wifi is not enabled" + +#~ msgid "wifi is not enabled" +#~ msgstr "WiFi is not enabled" + +#~ msgid "Cannot remount '/' when visible via USB." +#~ msgstr "Cannot remount '/' when visible via USB." + #~ msgid "%q must be a %q object, %q, or %q" #~ msgstr "%q must be a %q object, %q, or %q" @@ -4767,8 +4845,8 @@ msgstr "zi must be of shape (n_section, 2)" #~ msgid "'continue' outside loop" #~ msgstr "'continue' outside loop" -#~ msgid "'coroutine' object is not an iterator" -#~ msgstr "'coroutine' object is not an iterator" +#~ msgid "'coroutine' object isn't an iterator" +#~ msgstr "'coroutine' object isn't an iterator" #~ msgid "(x,y) integers required" #~ msgstr "(x,y) integers required" @@ -5638,8 +5716,8 @@ msgstr "zi must be of shape (n_section, 2)" #~ msgid "first argument must be an iterable" #~ msgstr "first argument must be an iterable" -#~ msgid "function does not take keyword arguments" -#~ msgstr "function does not take keyword arguments" +#~ msgid "function doesn't take keyword arguments" +#~ msgstr "function doesn't take keyword arguments" #~ msgid "incompatible native .mpy architecture" #~ msgstr "incompatible native .mpy architecture" @@ -5704,8 +5782,8 @@ msgstr "zi must be of shape (n_section, 2)" #~ msgid "maximum number of dimensions is 4" #~ msgstr "maximum number of dimensions is 4" -#~ msgid "name reused for argument" -#~ msgstr "name reused for argument" +#~ msgid "argument name reused" +#~ msgstr "argument name reused" #~ msgid "no available NIC" #~ msgstr "no available NIC" diff --git a/locale/en_US.po b/locale/en_US.po index e9344480c76..f621d0aa19a 100644 --- a/locale/en_US.po +++ b/locale/en_US.po @@ -274,7 +274,7 @@ msgid "'%q' object does not support '%q'" msgstr "" #: py/runtime.c -msgid "'%q' object is not an iterator" +msgid "'%q' object isn't an iterator" msgstr "" #: py/objtype.c py/runtime.c shared-module/atexit/__init__.c @@ -282,7 +282,7 @@ msgid "'%q' object is not callable" msgstr "" #: py/runtime.c -msgid "'%q' object is not iterable" +msgid "'%q' object isn't iterable" msgstr "" #: py/emitinlinethumb.c py/emitinlinextensa.c @@ -3068,7 +3068,7 @@ msgid "format" msgstr "" #: py/objstr.c -msgid "format requires a dict" +msgid "format needs a dict" msgstr "" #: py/objdeque.c @@ -3538,7 +3538,7 @@ msgid "must use keyword argument for key function" msgstr "" #: py/runtime.c -msgid "name '%q' is not defined" +msgid "name '%q' isn't defined" msgstr "" #: py/runtime.c @@ -4166,11 +4166,11 @@ msgid "tx and rx cannot both be None" msgstr "" #: py/objtype.c -msgid "type '%q' is not an acceptable base type" +msgid "type '%q' isn't an acceptable base type" msgstr "" #: py/objtype.c -msgid "type is not an acceptable base type" +msgid "type isn't an acceptable base type" msgstr "" #: py/runtime.c diff --git a/locale/en_x_pirate.po b/locale/en_x_pirate.po deleted file mode 100644 index f7b682d5626..00000000000 --- a/locale/en_x_pirate.po +++ /dev/null @@ -1,4425 +0,0 @@ -# SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) -# -# SPDX-License-Identifier: MIT -msgid "" -msgstr "" -"Project-Id-Version: \n" -"Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2020-06-25 11:44-0500\n" -"PO-Revision-Date: 2020-03-30 22:11+0000\n" -"Last-Translator: Tannewt \n" -"Language: en_x_pirate\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 3.11.3\n" - -#: main.c -msgid "" -"\n" -"Code done running.\n" -msgstr "" - -#: main.c -msgid "" -"\n" -"Code stopped by auto-reload. Reloading soon.\n" -msgstr "" - -#: supervisor/shared/safe_mode.c -msgid "" -"\n" -"Please file an issue with your program at github.com/adafruit/circuitpython/" -"issues." -msgstr "" - -#: supervisor/shared/safe_mode.c -msgid "" -"\n" -"Press reset to exit safe mode.\n" -msgstr "" - -#: supervisor/shared/safe_mode.c -msgid "" -"\n" -"You are in safe mode because:\n" -msgstr "" - -#: py/obj.c -msgid " File \"%q\"" -msgstr "" - -#: py/obj.c -msgid " File \"%q\", line %d" -msgstr "" - -#: py/builtinhelp.c -msgid " is of type %q\n" -msgstr "" - -#: main.c -msgid " not found.\n" -msgstr "" - -#: main.c -msgid " output:\n" -msgstr "" - -#: py/objstr.c -#, c-format -msgid "%%c requires int or char" -msgstr "" - -#: 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 "" - -#: shared-bindings/microcontroller/Pin.c -msgid "%q and %q contain duplicate pins" -msgstr "" - -#: ports/atmel-samd/common-hal/audioio/AudioOut.c -msgid "%q and %q must be different" -msgstr "" - -#: shared-bindings/microcontroller/Pin.c -msgid "%q contains duplicate pins" -msgstr "" - -#: ports/atmel-samd/common-hal/sdioio/SDCard.c -msgid "%q failure: %d" -msgstr "" - -#: py/argcheck.c -msgid "%q in %q must be of type %q, not %q" -msgstr "" - -#: ports/espressif/common-hal/espulp/ULP.c -#: ports/mimxrt10xx/common-hal/audiobusio/__init__.c -#: ports/mimxrt10xx/common-hal/usb_host/Port.c -#: ports/raspberrypi/common-hal/picodvi/Framebuffer.c -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -#: ports/raspberrypi/common-hal/usb_host/Port.c -#: shared-bindings/digitalio/DigitalInOut.c -#: shared-bindings/microcontroller/Pin.c -msgid "%q in use" -msgstr "" - -#: py/objstr.c -msgid "%q index out of range" -msgstr "" - -#: py/obj.c -msgid "%q indices must be integers, not %s" -msgstr "" - -#: shared-module/bitbangio/SPI.c -msgid "%q init failed" -msgstr "" - -#: ports/espressif/bindings/espnow/Peer.c shared-bindings/dualbank/__init__.c -msgid "%q is %q" -msgstr "" - -#: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "%q is read-only for this board" -msgstr "" - -#: py/argcheck.c shared-bindings/usb_hid/Device.c -msgid "%q length must be %d" -msgstr "" - -#: py/argcheck.c -msgid "%q length must be %d-%d" -msgstr "" - -#: py/argcheck.c -msgid "%q length must be <= %d" -msgstr "" - -#: py/argcheck.c -msgid "%q length must be >= %d" -msgstr "" - -#: py/objmodule.c py/runtime.c -msgid "%q moved from %q to %q" -msgstr "" - -#: py/argcheck.c -msgid "%q must be %d" -msgstr "" - -#: py/argcheck.c shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/displayio/Bitmap.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -#: shared-bindings/is31fl3741/FrameBuffer.c -#: shared-bindings/rgbmatrix/RGBMatrix.c -msgid "%q must be %d-%d" -msgstr "" - -#: shared-bindings/busdisplay/BusDisplay.c -msgid "%q must be 1 when %q is True" -msgstr "" - -#: py/argcheck.c shared-bindings/gifio/GifWriter.c -#: shared-module/gifio/OnDiskGif.c -msgid "%q must be <= %d" -msgstr "" - -#: ports/espressif/common-hal/watchdog/WatchDogTimer.c -msgid "%q must be <= %u" -msgstr "" - -#: py/argcheck.c -msgid "%q must be >= %d" -msgstr "" - -#: shared-bindings/analogbufio/BufferedIn.c -msgid "%q must be a bytearray or array of type 'H' or 'B'" -msgstr "" - -#: shared-bindings/audiocore/RawSample.c -msgid "%q must be a bytearray or array of type 'h', 'H', 'b', or 'B'" -msgstr "" - -#: shared-bindings/warnings/__init__.c -msgid "%q must be a subclass of %q" -msgstr "" - -#: ports/espressif/common-hal/analogbufio/BufferedIn.c -msgid "%q must be array of type 'H'" -msgstr "" - -#: shared-module/synthio/__init__.c -msgid "%q must be array of type 'h'" -msgstr "" - -#: ports/raspberrypi/bindings/cyw43/__init__.c py/argcheck.c py/objexcept.c -#: shared-bindings/canio/CAN.c shared-bindings/digitalio/Pull.c -#: shared-module/synthio/Synthesizer.c -msgid "%q must be of type %q or %q, not %q" -msgstr "" - -#: py/argcheck.c shared-module/synthio/__init__.c -msgid "%q must be of type %q, not %q" -msgstr "" - -#: ports/atmel-samd/common-hal/busio/UART.c -msgid "%q must be power of 2" -msgstr "" - -#: shared-bindings/wifi/Monitor.c -msgid "%q out of bounds" -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/rp2pio/StateMachine.c -#: ports/stm/common-hal/pulseio/PulseIn.c py/argcheck.c -#: shared-bindings/canio/Match.c -msgid "%q out of range" -msgstr "" - -#: py/objmodule.c py/runtime.c -msgid "%q renamed %q" -msgstr "" - -#: py/objrange.c py/objslice.c shared-bindings/random/__init__.c -msgid "%q step cannot be zero" -msgstr "" - -#: py/bc.c py/objnamedtuple.c -msgid "%q() takes %d positional arguments but %d were given" -msgstr "" - -#: shared-bindings/usb_hid/Device.c -msgid "%q, %q, and %q must all be the same length" -msgstr "" - -#: py/objint.c shared-bindings/storage/__init__.c -msgid "%q=%q" -msgstr "" - -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "%q[%u] shifts in more bits than pin count" -msgstr "" - -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "%q[%u] shifts out more bits than pin count" -msgstr "" - -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "%q[%u] uses extra pin" -msgstr "" - -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "%q[%u] waits on input outside of count" -msgstr "" - -#: ports/espressif/common-hal/espidf/__init__.c -#, c-format -msgid "%s error 0x%x" -msgstr "" - -#: py/argcheck.c -msgid "'%q' argument required" -msgstr "" - -#: py/proto.c -msgid "'%q' object does not support '%q'" -msgstr "" - -#: py/runtime.c -msgid "'%q' object is not an iterator" -msgstr "" - -#: py/objtype.c py/runtime.c shared-module/atexit/__init__.c -msgid "'%q' object is not callable" -msgstr "" - -#: py/runtime.c -msgid "'%q' object is not iterable" -msgstr "" - -#: py/emitinlinethumb.c py/emitinlinextensa.c -#, c-format -msgid "'%s' expects a label" -msgstr "" - -#: py/emitinlinethumb.c py/emitinlinextensa.c -#, c-format -msgid "'%s' expects a register" -msgstr "" - -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects a special register" -msgstr "" - -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects an FPU register" -msgstr "" - -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects an address of the form [a, b]" -msgstr "" - -#: py/emitinlinethumb.c py/emitinlinextensa.c -#, c-format -msgid "'%s' expects an integer" -msgstr "" - -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects at most r%d" -msgstr "" - -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects {r0, r1, ...}" -msgstr "" - -#: py/emitinlinextensa.c -#, c-format -msgid "'%s' integer %d isn't within range %d..%d" -msgstr "" - -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' integer 0x%x doesn't fit in mask 0x%x" -msgstr "" - -#: py/obj.c -#, c-format -msgid "'%s' object doesn't support item assignment" -msgstr "" - -#: py/obj.c -#, c-format -msgid "'%s' object doesn't support item deletion" -msgstr "" - -#: py/runtime.c -msgid "'%s' object has no attribute '%q'" -msgstr "" - -#: py/obj.c -#, c-format -msgid "'%s' object isn't subscriptable" -msgstr "" - -#: py/objstr.c -msgid "'=' alignment not allowed in string format specifier" -msgstr "" - -#: shared-module/struct/__init__.c -msgid "'S' and 'O' are not supported format types" -msgstr "" - -#: py/compile.c -msgid "'align' requires 1 argument" -msgstr "" - -#: py/compile.c -msgid "'await' outside function" -msgstr "" - -#: py/compile.c -msgid "'break'/'continue' outside loop" -msgstr "" - -#: py/compile.c -msgid "'data' requires at least 2 arguments" -msgstr "" - -#: py/compile.c -msgid "'data' requires integer arguments" -msgstr "" - -#: py/compile.c -msgid "'label' requires 1 argument" -msgstr "" - -#: py/compile.c -msgid "'return' outside function" -msgstr "" - -#: py/compile.c -msgid "'yield from' inside async function" -msgstr "" - -#: py/compile.c -msgid "'yield' outside function" -msgstr "" - -#: py/compile.c -msgid "* arg after **" -msgstr "" - -#: py/compile.c -msgid "*x must be assignment target" -msgstr "" - -#: py/obj.c -msgid ", in %q\n" -msgstr "" - -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/epaperdisplay/EPaperDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -msgid ".show(x) removed. Use .root_group = x" -msgstr "" - -#: py/objcomplex.c -msgid "0.0 to a complex power" -msgstr "" - -#: py/modbuiltins.c -msgid "3-arg pow() not supported" -msgstr "" - -#: ports/atmel-samd/common-hal/alarm/pin/PinAlarm.c -#: 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 "Avast! A hardware interrupt channel be used already" - -#: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "AP could not be started" -msgstr "" - -#: shared-bindings/_bleio/Address.c shared-bindings/ipaddress/IPv4Address.c -#, c-format -msgid "Address must be %d bytes long" -msgstr "" - -#: ports/espressif/common-hal/memorymap/AddressRange.c -#: ports/nrf/common-hal/memorymap/AddressRange.c -#: ports/raspberrypi/common-hal/memorymap/AddressRange.c -msgid "Address range not allowed" -msgstr "" - -#: shared-bindings/memorymap/AddressRange.c -msgid "Address range wraps around" -msgstr "" - -#: ports/espressif/common-hal/canio/CAN.c -msgid "All CAN peripherals are in use" -msgstr "" - -#: ports/espressif/common-hal/busio/I2C.c -#: ports/espressif/common-hal/i2ctarget/I2CTarget.c -#: ports/nrf/common-hal/busio/I2C.c -msgid "All I2C peripherals are in use" -msgstr "" - -#: ports/espressif/common-hal/countio/Counter.c -#: ports/espressif/common-hal/frequencyio/FrequencyIn.c -#: ports/espressif/common-hal/rotaryio/IncrementalEncoder.c -msgid "All PCNT units in use" -msgstr "" - -#: ports/atmel-samd/common-hal/canio/Listener.c -#: ports/espressif/common-hal/canio/Listener.c -#: ports/stm/common-hal/canio/Listener.c -msgid "All RX FIFOs in use" -msgstr "" - -#: ports/espressif/common-hal/busio/SPI.c ports/nrf/common-hal/busio/SPI.c -msgid "All SPI peripherals are in use" -msgstr "" - -#: ports/espressif/common-hal/busio/UART.c ports/nrf/common-hal/busio/UART.c -msgid "All UART peripherals are in use" -msgstr "" - -#: ports/nrf/common-hal/countio/Counter.c -#: ports/nrf/common-hal/pulseio/PulseIn.c -#: ports/nrf/common-hal/rotaryio/IncrementalEncoder.c -#: shared-bindings/pwmio/PWMOut.c -msgid "All channels in use" -msgstr "" - -#: ports/raspberrypi/common-hal/usb_host/Port.c -msgid "All dma channels in use" -msgstr "" - -#: ports/atmel-samd/common-hal/audioio/AudioOut.c -msgid "All event channels in use" -msgstr "" - -#: ports/raspberrypi/common-hal/picodvi/Framebuffer.c -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -#: ports/raspberrypi/common-hal/usb_host/Port.c -msgid "All state machines in use" -msgstr "" - -#: ports/atmel-samd/audio_dma.c -msgid "All sync event channels in use" -msgstr "" - -#: ports/raspberrypi/common-hal/picodvi/Framebuffer.c -#: shared-bindings/pwmio/PWMOut.c -msgid "All timers for this pin are in use" -msgstr "" - -#: 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/espressif/common-hal/frequencyio/FrequencyIn.c -#: ports/espressif/common-hal/neopixel_write/__init__.c -#: ports/espressif/common-hal/pulseio/PulseIn.c -#: ports/espressif/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 "" - -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nrf/common-hal/_bleio/Adapter.c -msgid "Already advertising." -msgstr "" - -#: ports/atmel-samd/common-hal/canio/Listener.c -msgid "Already have all-matches listener" -msgstr "" - -#: ports/espressif/bindings/espnow/ESPNow.c -#: ports/espressif/common-hal/espulp/ULP.c -#: shared-module/memorymonitor/AllocationAlarm.c -#: shared-module/memorymonitor/AllocationSize.c -msgid "Already running" -msgstr "" - -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "Already scanning for wifi networks" -msgstr "" - -#: shared-module/os/getenv.c -#, c-format -msgid "An error occurred while retrieving '%s':\n" -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" -msgstr "Belay that! thar be another active send" - -#: shared-bindings/pulseio/PulseOut.c -msgid "Array must contain halfwords (type 'H')" -msgstr "" - -#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c -#: shared-bindings/nvm/ByteArray.c -msgid "Array values should be single bytes." -msgstr "" - -#: shared-module/memorymonitor/AllocationAlarm.c -#, c-format -msgid "Attempt to allocate %d blocks" -msgstr "" - -#: ports/raspberrypi/audio_dma.c -msgid "Audio conversion not implemented" -msgstr "" - -#: shared-bindings/wifi/Radio.c -msgid "AuthMode.OPEN is not used with password" -msgstr "" - -#: shared-bindings/wifi/Radio.c supervisor/shared/web_workflow/web_workflow.c -msgid "Authentication failure" -msgstr "" - -#: main.c -msgid "Auto-reload is off.\n" -msgstr "Auto-reload be 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 be on. Put yer files on USB to weigh anchor, er' bring'er about " -"t' the REPL t' scuttle.\n" - -#: ports/espressif/common-hal/canio/CAN.c -msgid "Baudrate not supported by peripheral" -msgstr "" - -#: shared-module/busdisplay/BusDisplay.c -#: shared-module/framebufferio/FramebufferDisplay.c -msgid "Below minimum frame rate" -msgstr "" - -#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c -msgid "Bit clock and word select must be sequential GPIO pins" -msgstr "" - -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -msgid "Bit clock and word select must share a clock unit" -msgstr "" - -#: shared-bindings/audiobusio/PDMIn.c -msgid "Bit depth must be multiple of 8." -msgstr "" - -#: shared-bindings/bitmaptools/__init__.c -msgid "Bitmap size and bits per value must match" -msgstr "" - -#: supervisor/shared/safe_mode.c -msgid "Boot device must be first (interface #0)." -msgstr "" - -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Both RX and TX required for flow control" -msgstr "" - -#: ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.c -msgid "Both pins must support hardware interrupts" -msgstr "" - -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -msgid "Brightness not adjustable" -msgstr "" - -#: shared-bindings/_bleio/UUID.c -#, c-format -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-bindings/framebufferio/FramebufferDisplay.c -msgid "Buffer is not a bytearray." -msgstr "" - -#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c -#, c-format -msgid "Buffer length %d too big. It must be less than %d" -msgstr "" - -#: 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 "" - -#: ports/stm/common-hal/sdioio/SDCard.c shared-bindings/floppyio/__init__.c -msgid "Buffer must be a multiple of 512 bytes" -msgstr "" - -#: shared-bindings/_bleio/PacketBuffer.c -#, c-format -msgid "Buffer too short by %d bytes" -msgstr "" - -#: ports/cxd56/common-hal/camera/Camera.c -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -#: shared-bindings/struct/__init__.c shared-module/struct/__init__.c -msgid "Buffer too small" -msgstr "" - -#: ports/espressif/common-hal/imagecapture/ParallelImageCapture.c -msgid "Buffers must be same size" -msgstr "" - -#: ports/atmel-samd/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/nrf/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/raspberrypi/common-hal/paralleldisplaybus/ParallelBus.c -#, c-format -msgid "Bus pin %d is already in use" -msgstr "Belay that! Bus pin %d already be in use" - -#: shared-bindings/_bleio/UUID.c -msgid "Byte buffer must be 16 bytes." -msgstr "" - -#: shared-bindings/aesio/aes.c -msgid "CBC blocks must be multiples of 16 bytes" -msgstr "" - -#: supervisor/shared/safe_mode.c -msgid "CIRCUITPY drive could not be found or created." -msgstr "" - -#: ports/espressif/common-hal/espidf/__init__.c -msgid "CRC or checksum was invalid" -msgstr "" - -#: py/objtype.c -msgid "Call super().__init__() before accessing native object." -msgstr "" - -#: ports/cxd56/common-hal/camera/Camera.c -msgid "Camera init" -msgstr "" - -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Can only alarm on RTC IO from deep sleep." -msgstr "" - -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Can only alarm on one low pin while others alarm high from deep sleep." -msgstr "" - -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Can only alarm on two low pins from deep sleep." -msgstr "" - -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/nrf/common-hal/_bleio/Characteristic.c -msgid "Can't set CCCD on local Characteristic" -msgstr "" - -#: shared-bindings/storage/__init__.c shared-bindings/usb_cdc/__init__.c -#: shared-bindings/usb_hid/__init__.c shared-bindings/usb_midi/__init__.c -msgid "Cannot change USB devices now" -msgstr "" - -#: shared-bindings/_bleio/Adapter.c -msgid "Cannot create a new Adapter; use _bleio.adapter;" -msgstr "" - -#: shared-bindings/displayio/Bitmap.c -#: shared-bindings/memorymonitor/AllocationSize.c -#: shared-bindings/pulseio/PulseIn.c -msgid "Cannot delete values" -msgstr "" - -#: 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 "" - -#: ports/nrf/common-hal/microcontroller/Processor.c -msgid "Cannot get temperature" -msgstr "" - -#: shared-bindings/_bleio/Adapter.c -msgid "Cannot have scan responses for extended, connectable advertisements." -msgstr "" - -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Cannot pull on input-only pin." -msgstr "" - -#: shared-bindings/audiobusio/PDMIn.c -msgid "Cannot record to a file" -msgstr "" - -#: shared-module/storage/__init__.c -msgid "Cannot remount '/' when visible via USB." -msgstr "" - -#: 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 "" - -#: ports/espressif/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 "" - -#: ports/espressif/common-hal/busio/UART.c -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Cannot specify RTS or CTS in RS485 mode" -msgstr "" - -#: py/objslice.c -msgid "Cannot subclass slice" -msgstr "" - -#: shared-bindings/pwmio/PWMOut.c -msgid "Cannot vary frequency on a timer that is already in use" -msgstr "" - -#: ports/nrf/common-hal/alarm/pin/PinAlarm.c -msgid "Cannot wake on pin edge, only level" -msgstr "" - -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Cannot wake on pin edge. Only level." -msgstr "" - -#: shared-bindings/_bleio/CharacteristicBuffer.c -msgid "CharacteristicBuffer writing not provided" -msgstr "" - -#: supervisor/shared/safe_mode.c -msgid "CircuitPython core code crashed hard. Whoops!\n" -msgstr "" - -#: shared-module/bitbangio/I2C.c -msgid "Clock stretch too long" -msgstr "" - -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -msgid "Clock unit in use" -msgstr "" - -#: shared-bindings/_bleio/Connection.c -msgid "" -"Connection has been disconnected and can no longer be used. Create a new " -"connection." -msgstr "" - -#: shared-bindings/bitmaptools/__init__.c -msgid "Coordinate arrays have different lengths" -msgstr "" - -#: shared-bindings/bitmaptools/__init__.c -msgid "Coordinate arrays types have different sizes" -msgstr "" - -#: ports/espressif/common-hal/neopixel_write/__init__.c -msgid "Could not retrieve clock" -msgstr "" - -#: shared-bindings/_bleio/Adapter.c -msgid "Could not set address" -msgstr "" - -#: shared-bindings/pwmio/PWMOut.c -msgid "Could not start PWM" -msgstr "" - -#: ports/stm/common-hal/busio/UART.c -msgid "Could not start interrupt, RX busy" -msgstr "" - -#: shared-module/audiomp3/MP3Decoder.c -msgid "Couldn't allocate decoder" -msgstr "" - -#: ports/stm/common-hal/analogio/AnalogOut.c -msgid "DAC Channel Init Error" -msgstr "" - -#: ports/stm/common-hal/analogio/AnalogOut.c -msgid "DAC Device Init Error" -msgstr "" - -#: ports/atmel-samd/common-hal/audioio/AudioOut.c -msgid "DAC already in use" -msgstr "" - -#: ports/atmel-samd/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/nrf/common-hal/paralleldisplaybus/ParallelBus.c -msgid "Data 0 pin must be byte aligned" -msgstr "" - -#: shared-module/audiocore/WaveFile.c -msgid "Data chunk must follow fmt chunk" -msgstr "" - -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nrf/common-hal/_bleio/Adapter.c -msgid "Data not supported with directed advertising" -msgstr "" - -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nrf/common-hal/_bleio/Adapter.c -msgid "Data too large for advertisement packet" -msgstr "" - -#: ports/stm/common-hal/alarm/pin/PinAlarm.c -msgid "Deep sleep pins must use a rising edge with pulldown" -msgstr "" - -#: shared-bindings/audiobusio/PDMIn.c -msgid "Destination capacity is smaller than destination_length." -msgstr "" - -#: ports/nrf/common-hal/audiobusio/I2SOut.c -msgid "Device in use" -msgstr "" - -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -msgid "Display must have a 16 bit colorspace." -msgstr "" - -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/epaperdisplay/EPaperDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -msgid "Display rotation must be in 90 degree increments" -msgstr "" - -#: main.c -msgid "Done" -msgstr "" - -#: shared-bindings/digitalio/DigitalInOut.c -msgid "Drive mode not used when direction is input." -msgstr "" - -#: py/obj.c -msgid "During handling of the above exception, another exception occurred:" -msgstr "" - -#: shared-bindings/aesio/aes.c -msgid "ECB only operates on 16 bytes at a time" -msgstr "" - -#: ports/espressif/common-hal/busio/SPI.c -#: ports/espressif/common-hal/canio/CAN.c -msgid "ESP-IDF memory allocation failed" -msgstr "" - -#: 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 "Avast! EXTINT channel already in use" - -#: extmod/modre.c -msgid "Error in regex" -msgstr "" - -#: supervisor/shared/safe_mode.c -msgid "Error in safemode.py." -msgstr "" - -#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c -msgid "Error: Failure to bind" -msgstr "" - -#: shared-bindings/alarm/__init__.c -msgid "Expected a kind of %q" -msgstr "" - -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nrf/common-hal/_bleio/Adapter.c -msgid "Extended advertisements with scan response not supported." -msgstr "" - -#: extmod/ulab/code/numpy/fft/fft_tools.c -msgid "FFT is defined for ndarrays only" -msgstr "" - -#: extmod/ulab/code/numpy/fft/fft_tools.c -msgid "FFT is implemented for linear arrays only" -msgstr "" - -#: ports/espressif/common-hal/ssl/SSLSocket.c -msgid "Failed SSL handshake" -msgstr "" - -#: shared-bindings/ps2io/Ps2.c -msgid "Failed sending command." -msgstr "" - -#: ports/nrf/sd_mutex.c -#, c-format -msgid "Failed to acquire mutex, err 0x%04x" -msgstr "" - -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "Failed to add service TXT record" -msgstr "" - -#: shared-bindings/mdns/Server.c -msgid "" -"Failed to add service TXT record; non-string or bytes found in txt_records" -msgstr "" - -#: shared-module/rgbmatrix/RGBMatrix.c -msgid "Failed to allocate %q buffer" -msgstr "" - -#: ports/espressif/common-hal/wifi/__init__.c -msgid "Failed to allocate Wifi memory" -msgstr "" - -#: ports/espressif/common-hal/wifi/ScannedNetworks.c -msgid "Failed to allocate wifi scan memory" -msgstr "" - -#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c -msgid "Failed to buffer the sample" -msgstr "" - -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nrf/common-hal/_bleio/Adapter.c -msgid "Failed to connect: internal error" -msgstr "" - -#: ports/nrf/common-hal/_bleio/Adapter.c -msgid "Failed to connect: timeout" -msgstr "" - -#: shared-module/audiomp3/MP3Decoder.c -msgid "Failed to parse MP3 file" -msgstr "" - -#: ports/nrf/sd_mutex.c -#, c-format -msgid "Failed to release mutex, err 0x%04x" -msgstr "" - -#: supervisor/shared/safe_mode.c -msgid "Failed to write internal flash." -msgstr "" - -#: py/moderrno.c -msgid "File exists" -msgstr "" - -#: shared-module/os/getenv.c -msgid "File not found" -msgstr "" - -#: ports/atmel-samd/common-hal/canio/Listener.c -#: ports/espressif/common-hal/canio/Listener.c -#: ports/stm/common-hal/canio/Listener.c -msgid "Filters too complex" -msgstr "" - -#: ports/espressif/common-hal/dualbank/__init__.c -msgid "Firmware is duplicate" -msgstr "" - -#: ports/espressif/common-hal/dualbank/__init__.c -msgid "Firmware is invalid" -msgstr "" - -#: ports/espressif/common-hal/dualbank/__init__.c -msgid "Firmware is too big" -msgstr "" - -#: shared-bindings/bitmaptools/__init__.c -msgid "For L8 colorspace, input bitmap must have 8 bits per pixel" -msgstr "" - -#: shared-bindings/bitmaptools/__init__.c -msgid "For RGB colorspaces, input bitmap must have 16 bits per pixel" -msgstr "" - -#: ports/cxd56/common-hal/camera/Camera.c -msgid "Format not supported" -msgstr "" - -#: ports/mimxrt10xx/common-hal/microcontroller/Processor.c -msgid "" -"Frequency must be 24, 150, 396, 450, 528, 600, 720, 816, 912, 960 or 1008 Mhz" -msgstr "" - -#: shared-bindings/pwmio/PWMOut.c -msgid "Frequency must match existing PWMOut using this timer" -msgstr "" - -#: 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 "" - -#: ports/cxd56/common-hal/gnss/GNSS.c -msgid "GNSS init" -msgstr "" - -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Generic Failure" -msgstr "" - -#: shared-bindings/framebufferio/FramebufferDisplay.c -#: shared-module/busdisplay/BusDisplay.c -#: shared-module/framebufferio/FramebufferDisplay.c -msgid "Group already used" -msgstr "" - -#: ports/atmel-samd/common-hal/busio/SPI.c ports/cxd56/common-hal/busio/SPI.c -#: ports/espressif/common-hal/busio/SPI.c -#: ports/mimxrt10xx/common-hal/busio/SPI.c ports/nrf/common-hal/busio/SPI.c -#: ports/raspberrypi/common-hal/busio/SPI.c -msgid "Half duplex SPI is not implemented" -msgstr "" - -#: supervisor/shared/safe_mode.c -msgid "Hard fault: memory access or instruction error." -msgstr "" - -#: ports/mimxrt10xx/common-hal/busio/SPI.c -#: ports/mimxrt10xx/common-hal/busio/UART.c 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 "Hardware in use, try alternative pins" -msgstr "" - -#: supervisor/shared/safe_mode.c -msgid "Heap allocation when VM not running." -msgstr "" - -#: supervisor/shared/safe_mode.c -msgid "" -"Heap was corrupted because the stack was too small. Increase stack size." -msgstr "" - -#: extmod/vfs_posix_file.c py/objstringio.c -msgid "I/O operation on closed file" -msgstr "" - -#: ports/stm/common-hal/busio/I2C.c -msgid "I2C init error" -msgstr "" - -#: ports/raspberrypi/common-hal/busio/I2C.c -#: ports/raspberrypi/common-hal/i2ctarget/I2CTarget.c -msgid "I2C peripheral in use" -msgstr "" - -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "In-buffer elements must be <= 4 bytes long" -msgstr "" - -#: shared-bindings/_pew/PewPew.c -msgid "Incorrect buffer size" -msgstr "" - -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -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 "" - -#: 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 "" - -#: ports/espressif/common-hal/neopixel_write/__init__.c py/moderrno.c -msgid "Input/output error" -msgstr "" - -#: ports/nrf/common-hal/_bleio/__init__.c -msgid "Insufficient authentication" -msgstr "" - -#: ports/nrf/common-hal/_bleio/__init__.c -msgid "Insufficient encryption" -msgstr "" - -#: ports/espressif/common-hal/wifi/Radio.c -msgid "Interface must be started" -msgstr "" - -#: ports/atmel-samd/audio_dma.c ports/raspberrypi/audio_dma.c -msgid "Internal audio buffer too small" -msgstr "" - -#: ports/stm/common-hal/busio/UART.c -msgid "Internal define error" -msgstr "" - -#: ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c -#: shared-module/os/getenv.c -msgid "Internal error" -msgstr "" - -#: shared-module/rgbmatrix/RGBMatrix.c -#, c-format -msgid "Internal error #%d" -msgstr "" - -#: supervisor/shared/safe_mode.c -msgid "Internal watchdog timer expired." -msgstr "" - -#: supervisor/shared/safe_mode.c -msgid "Interrupt error." -msgstr "" - -#: ports/mimxrt10xx/common-hal/audiobusio/__init__.c -#: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c -#: ports/raspberrypi/bindings/picodvi/Framebuffer.c -#: ports/raspberrypi/common-hal/picodvi/Framebuffer.c py/argcheck.c -#: shared-bindings/digitalio/DigitalInOut.c -#: shared-bindings/epaperdisplay/EPaperDisplay.c -msgid "Invalid %q" -msgstr "" - -#: ports/atmel-samd/common-hal/microcontroller/Pin.c -#: ports/espressif/common-hal/dotclockframebuffer/DotClockFramebuffer.c -#: ports/mimxrt10xx/common-hal/microcontroller/Pin.c -#: shared-bindings/microcontroller/Pin.c -msgid "Invalid %q pin" -msgstr "Avast! %q pin be invalid" - -#: ports/stm/common-hal/analogio/AnalogIn.c -msgid "Invalid ADC Unit value" -msgstr "" - -#: ports/espressif/common-hal/_bleio/__init__.c -#: ports/nrf/common-hal/_bleio/__init__.c -msgid "Invalid BLE parameter" -msgstr "" - -#: shared-bindings/wifi/Radio.c -msgid "Invalid BSSID" -msgstr "" - -#: shared-bindings/wifi/Radio.c -msgid "Invalid MAC address" -msgstr "" - -#: ports/espressif/common-hal/espidf/__init__.c py/moderrno.c -msgid "Invalid argument" -msgstr "" - -#: shared-module/displayio/Bitmap.c -msgid "Invalid bits per value" -msgstr "" - -#: shared-module/os/getenv.c -#, c-format -msgid "Invalid byte %.*s" -msgstr "" - -#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c -#, c-format -msgid "Invalid data_pins[%d]" -msgstr "" - -#: shared-module/msgpack/__init__.c -msgid "Invalid format" -msgstr "" - -#: shared-module/audiocore/WaveFile.c -msgid "Invalid format chunk size" -msgstr "" - -#: shared-bindings/wifi/Radio.c -msgid "Invalid hex password" -msgstr "" - -#: ports/espressif/common-hal/wifi/Radio.c -msgid "Invalid multicast MAC address" -msgstr "" - -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Invalid size" -msgstr "" - -#: ports/espressif/common-hal/ssl/SSLContext.c -#: ports/raspberrypi/common-hal/ssl/SSLSocket.c -msgid "Invalid socket for TLS" -msgstr "" - -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Invalid state" -msgstr "" - -#: shared-module/os/getenv.c -msgid "Invalid unicode escape" -msgstr "" - -#: shared-bindings/aesio/aes.c -msgid "Key must be 16, 24, or 32 bytes long" -msgstr "" - -#: shared-module/os/getenv.c -msgid "Key not found" -msgstr "" - -#: shared-module/is31fl3741/FrameBuffer.c -msgid "LED mappings must match display size" -msgstr "" - -#: py/compile.c -msgid "LHS of keyword arg must be an id" -msgstr "" - -#: shared-module/displayio/Group.c -msgid "Layer already in a group" -msgstr "" - -#: shared-module/displayio/Group.c -msgid "Layer must be a Group or TileGrid subclass" -msgstr "" - -#: ports/espressif/common-hal/espidf/__init__.c -msgid "MAC address was invalid" -msgstr "" - -#: shared-bindings/is31fl3741/IS31FL3741.c -msgid "Mapping must be a tuple" -msgstr "" - -#: shared-bindings/audiobusio/PDMIn.c -msgid "Microphone startup delay must be in range 0.0 to 1.0" -msgstr "" - -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Mismatched data size" -msgstr "" - -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Mismatched swap flag" -msgstr "" - -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_in_pin. %q[%u] reads pin(s)" -msgstr "" - -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_in_pin. %q[%u] shifts in from pin(s)" -msgstr "" - -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_in_pin. %q[%u] waits based on pin" -msgstr "" - -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_out_pin. %q[%u] shifts out to pin(s)" -msgstr "" - -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_out_pin. %q[%u] writes pin(s)" -msgstr "" - -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_set_pin. %q[%u] sets pin(s)" -msgstr "" - -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing jmp_pin. %q[%u] jumps on pin" -msgstr "" - -#: shared-bindings/busio/UART.c shared-bindings/displayio/Group.c -msgid "Must be a %q subclass." -msgstr "" - -#: ports/espressif/common-hal/dotclockframebuffer/DotClockFramebuffer.c -msgid "Must provide 5/6/5 RGB pins" -msgstr "" - -#: ports/mimxrt10xx/common-hal/busio/SPI.c shared-bindings/busio/SPI.c -msgid "Must provide MISO or MOSI pin" -msgstr "" - -#: shared-bindings/rgbmatrix/RGBMatrix.c -#, c-format -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/espressif/common-hal/nvm/ByteArray.c -msgid "NVS Error" -msgstr "" - -#: shared-bindings/socketpool/SocketPool.c -msgid "Name or service not known" -msgstr "" - -#: py/qstr.c -msgid "Name too long" -msgstr "" - -#: shared-bindings/displayio/TileGrid.c -msgid "New bitmap must be same size as old bitmap" -msgstr "" - -#: ports/espressif/common-hal/_bleio/__init__.c -msgid "Nimble out of memory" -msgstr "" - -#: ports/atmel-samd/common-hal/busio/UART.c -#: ports/espressif/common-hal/busio/SPI.c -#: ports/espressif/common-hal/busio/UART.c -#: ports/mimxrt10xx/common-hal/busio/SPI.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/SPI.c -#: ports/stm/common-hal/busio/UART.c shared-bindings/fourwire/FourWire.c -#: shared-bindings/i2cdisplaybus/I2CDisplayBus.c -#: shared-bindings/paralleldisplaybus/ParallelBus.c -#: shared-module/bitbangio/SPI.c -msgid "No %q pin" -msgstr "" - -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/nrf/common-hal/_bleio/Characteristic.c -msgid "No CCCD for this Characteristic" -msgstr "" - -#: ports/atmel-samd/common-hal/analogio/AnalogOut.c -#: ports/stm/common-hal/analogio/AnalogOut.c -msgid "No DAC on chip" -msgstr "Shiver me timbers! There be no DAC on this 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 "" - -#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c -msgid "No DMA pacing timer found" -msgstr "" - -#: shared-module/adafruit_bus_device/i2c_device/I2CDevice.c -#, c-format -msgid "No I2C device at address: 0x%x" -msgstr "" - -#: supervisor/shared/web_workflow/web_workflow.c -msgid "No IP" -msgstr "" - -#: ports/atmel-samd/common-hal/frequencyio/FrequencyIn.c -msgid "No available clocks" -msgstr "" - -#: ports/espressif/common-hal/imagecapture/ParallelImageCapture.c -msgid "No capture in progress" -msgstr "" - -#: shared-module/usb/core/Device.c -msgid "No configuration set" -msgstr "" - -#: shared-bindings/_bleio/PacketBuffer.c -msgid "No connection: length cannot be determined" -msgstr "" - -#: shared-bindings/board/__init__.c -msgid "No default %q bus" -msgstr "" - -#: ports/atmel-samd/common-hal/touchio/TouchIn.c -msgid "No free GCLKs" -msgstr "" - -#: shared-bindings/os/__init__.c -msgid "No hardware random available" -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 "" - -#: py/objint.c shared-bindings/time/__init__.c -msgid "No long integer support" -msgstr "" - -#: shared-bindings/wifi/Radio.c -msgid "No network with that ssid" -msgstr "" - -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "No out in program" -msgstr "" - -#: ports/atmel-samd/common-hal/busio/I2C.c -#: ports/espressif/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 "" - -#: py/moderrno.c -msgid "No space left on device" -msgstr "" - -#: py/moderrno.c -msgid "No such device" -msgstr "" - -#: py/moderrno.c -msgid "No such file/directory" -msgstr "" - -#: shared-module/rgbmatrix/RGBMatrix.c -msgid "No timer available" -msgstr "" - -#: shared-module/usb/core/Device.c -msgid "No usb host port initialized" -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/espressif/common-hal/_bleio/__init__.c -#: ports/nrf/common-hal/_bleio/__init__.c -#: shared-bindings/_bleio/CharacteristicBuffer.c -msgid "Not connected" -msgstr "" - -#: shared-bindings/audiobusio/I2SOut.c shared-bindings/audioio/AudioOut.c -#: shared-bindings/audiopwmio/PWMAudioOut.c -msgid "Not playing" -msgstr "" - -#: ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c -#, c-format -msgid "Number of data_pins must be 8 or 16, not %d" -msgstr "" - -#: shared-bindings/util.c -msgid "" -"Object has been deinitialized and can no longer be used. Create a new object." -msgstr "" - -#: ports/nrf/common-hal/busio/UART.c -msgid "Odd parity is not supported" -msgstr "" - -#: supervisor/shared/bluetooth/bluetooth.c -msgid "Off" -msgstr "" - -#: supervisor/shared/bluetooth/bluetooth.c -msgid "Ok" -msgstr "" - -#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c -#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c -#, c-format -msgid "Only 8 or 16 bit mono with %dx oversampling supported." -msgstr "" - -#: ports/espressif/common-hal/wifi/__init__.c -#: ports/raspberrypi/common-hal/wifi/__init__.c -msgid "Only IPv4 addresses supported" -msgstr "" - -#: ports/espressif/common-hal/socketpool/Socket.c -#: ports/raspberrypi/common-hal/socketpool/Socket.c -msgid "Only IPv4 sockets supported" -msgstr "" - -#: shared-module/displayio/OnDiskBitmap.c -#, c-format -msgid "" -"Only Windows format, uncompressed BMP supported: given header size is %d" -msgstr "" - -#: shared-bindings/_bleio/Adapter.c -msgid "Only connectable advertisements can be directed" -msgstr "" - -#: ports/stm/common-hal/alarm/pin/PinAlarm.c -msgid "Only edge detection is available on this hardware" -msgstr "" - -#: shared-bindings/ipaddress/__init__.c -msgid "Only int or string supported for ip" -msgstr "" - -#: shared-module/displayio/OnDiskBitmap.c -#, c-format -msgid "" -"Only monochrome, indexed 4bpp or 8bpp, and 16bpp or greater BMPs supported: " -"%d bpp given" -msgstr "" - -#: ports/espressif/common-hal/alarm/touch/TouchAlarm.c -msgid "Only one %q can be set in deep sleep." -msgstr "" - -#: ports/espressif/common-hal/espulp/ULPAlarm.c -msgid "Only one %q can be set." -msgstr "" - -#: ports/espressif/common-hal/i2ctarget/I2CTarget.c -#: ports/raspberrypi/common-hal/i2ctarget/I2CTarget.c -msgid "Only one address is allowed" -msgstr "" - -#: ports/atmel-samd/common-hal/alarm/time/TimeAlarm.c -#: ports/nrf/common-hal/alarm/time/TimeAlarm.c -#: ports/stm/common-hal/alarm/time/TimeAlarm.c -msgid "Only one alarm.time alarm can be set" -msgstr "" - -#: ports/espressif/common-hal/alarm/time/TimeAlarm.c -#: ports/raspberrypi/common-hal/alarm/time/TimeAlarm.c -msgid "Only one alarm.time alarm can be set." -msgstr "" - -#: shared-module/displayio/ColorConverter.c -msgid "Only one color can be transparent at a time" -msgstr "" - -#: py/moderrno.c -msgid "Operation not permitted" -msgstr "" - -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Operation or feature not supported" -msgstr "" - -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Operation timed out" -msgstr "" - -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "Out of MDNS service slots" -msgstr "" - -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Out of memory" -msgstr "" - -#: ports/espressif/common-hal/socketpool/Socket.c -#: ports/raspberrypi/common-hal/socketpool/Socket.c -msgid "Out of sockets" -msgstr "" - -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "Out-buffer elements must be <= 4 bytes long" -msgstr "" - -#: shared-bindings/audiobusio/PDMIn.c -msgid "Oversample must be multiple of 8." -msgstr "" - -#: shared-bindings/pwmio/PWMOut.c -msgid "" -"PWM frequency not writable when variable_frequency is False on construction." -msgstr "" - -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "PWM restart" -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/espressif/common-hal/audiobusio/__init__.c -msgid "Peripheral in use" -msgstr "" - -#: py/moderrno.c -msgid "Permission denied" -msgstr "" - -#: ports/stm/common-hal/alarm/pin/PinAlarm.c -msgid "Pin cannot wake from Deep Sleep" -msgstr "" - -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Pin count too large" -msgstr "" - -#: ports/stm/common-hal/alarm/pin/PinAlarm.c -#: ports/stm/common-hal/pulseio/PulseIn.c -msgid "Pin interrupt already in use" -msgstr "" - -#: shared-bindings/adafruit_bus_device/spi_device/SPIDevice.c -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 "" - -#: 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 "" - -#: ports/raspberrypi/common-hal/imagecapture/ParallelImageCapture.c -msgid "Pins must be sequential" -msgstr "" - -#: ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c -msgid "Pins must be sequential GPIO pins" -msgstr "" - -#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c -msgid "Pins must share PWM slice" -msgstr "" - -#: shared-module/usb/core/Device.c -msgid "Pipe error" -msgstr "" - -#: py/builtinhelp.c -msgid "Plus any modules on the filesystem\n" -msgstr "" - -#: shared-module/vectorio/Polygon.c -msgid "Polygon needs at least 3 points" -msgstr "" - -#: supervisor/shared/safe_mode.c -msgid "Power dipped. Make sure you are providing enough power." -msgstr "" - -#: shared-bindings/_bleio/Adapter.c -msgid "Prefix buffer must be on the heap" -msgstr "" - -#: main.c -msgid "Press any key to enter the REPL. Use CTRL-D to reload.\n" -msgstr "" - -#: main.c -msgid "Pretending to deep sleep until alarm, CTRL-C or file write.\n" -msgstr "" - -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Program does IN without loading ISR" -msgstr "" - -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Program does OUT without loading OSR" -msgstr "" - -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "Program size invalid" -msgstr "" - -#: ports/espressif/common-hal/espulp/ULP.c -msgid "Program too long" -msgstr "" - -#: shared-bindings/digitalio/DigitalInOut.c -msgid "Pull not used when direction is output." -msgstr "" - -#: ports/raspberrypi/common-hal/countio/Counter.c -msgid "RISE_AND_FALL not available on this chip" -msgstr "" - -#: ports/stm/common-hal/os/__init__.c -msgid "RNG DeInit Error" -msgstr "" - -#: ports/stm/common-hal/os/__init__.c -msgid "RNG Init Error" -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 -msgid "RS485" -msgstr "" - -#: ports/espressif/common-hal/busio/UART.c -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "RS485 inversion specified when not in RS485 mode" -msgstr "" - -#: shared-bindings/alarm/time/TimeAlarm.c shared-bindings/time/__init__.c -msgid "RTC is not supported on this board" -msgstr "" - -#: ports/stm/common-hal/os/__init__.c -msgid "Random number generation error" -msgstr "" - -#: shared-bindings/_bleio/__init__.c -#: shared-bindings/memorymonitor/AllocationSize.c -#: shared-bindings/pulseio/PulseIn.c shared-module/bitmaptools/__init__.c -#: shared-module/displayio/Bitmap.c -msgid "Read-only" -msgstr "" - -#: extmod/vfs_fat.c py/moderrno.c -msgid "Read-only filesystem" -msgstr "" - -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Received response was invalid" -msgstr "" - -#: supervisor/shared/bluetooth/bluetooth.c -msgid "Reconnecting" -msgstr "" - -#: shared-bindings/epaperdisplay/EPaperDisplay.c -msgid "Refresh too soon" -msgstr "" - -#: shared-bindings/canio/RemoteTransmissionRequest.c -msgid "RemoteTransmissionRequests limited to 8 bytes" -msgstr "" - -#: shared-bindings/aesio/aes.c -msgid "Requested AES mode is unsupported" -msgstr "" - -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Requested resource not found" -msgstr "" - -#: ports/atmel-samd/common-hal/audioio/AudioOut.c -msgid "Right channel unsupported" -msgstr "" - -#: main.c -msgid "Running in safe mode! Not running saved code.\n" -msgstr "Runnin' in safe mode! Nay runnin' saved code.\n" - -#: shared-module/sdcardio/SDCard.c -msgid "SD card CSD format not supported" -msgstr "" - -#: ports/cxd56/common-hal/sdioio/SDCard.c -msgid "SDCard init" -msgstr "" - -#: ports/stm/common-hal/sdioio/SDCard.c -#, c-format -msgid "SDIO GetCardInfo Error %d" -msgstr "" - -#: ports/stm/common-hal/sdioio/SDCard.c -#, c-format -msgid "SDIO Init Error %d" -msgstr "" - -#: ports/espressif/common-hal/busio/SPI.c -msgid "SPI configuration failed" -msgstr "" - -#: ports/stm/common-hal/busio/SPI.c -msgid "SPI init error" -msgstr "" - -#: ports/raspberrypi/common-hal/busio/SPI.c -msgid "SPI peripheral in use" -msgstr "" - -#: ports/stm/common-hal/busio/SPI.c -msgid "SPI re-init" -msgstr "" - -#: shared-bindings/is31fl3741/FrameBuffer.c -msgid "Scale dimensions must divide by 3" -msgstr "" - -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nrf/common-hal/_bleio/Adapter.c -msgid "Scan already in progress. Stop with stop_scan." -msgstr "" - -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c -msgid "Serializer in use" -msgstr "" - -#: shared-bindings/ssl/SSLContext.c -msgid "Server side context cannot have hostname" -msgstr "" - -#: ports/cxd56/common-hal/camera/Camera.c -msgid "Size not supported" -msgstr "" - -#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c -#: shared-bindings/nvm/ByteArray.c -msgid "Slice and value different lengths." -msgstr "" - -#: 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 "" - -#: ports/espressif/common-hal/socketpool/SocketPool.c -#: ports/raspberrypi/common-hal/socketpool/SocketPool.c -msgid "SocketPool can only be used with wifi.radio" -msgstr "" - -#: shared-bindings/aesio/aes.c -msgid "Source and destination buffers must be the same length" -msgstr "" - -#: shared-bindings/paralleldisplaybus/ParallelBus.c -msgid "Specify exactly one of data0 or data_pins" -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/alarm/time/TimeAlarm.c -msgid "Supply one of monotonic_time or epoch_time" -msgstr "" - -#: shared-bindings/gnss/GNSS.c -msgid "System entry must be gnss.SatelliteSystem" -msgstr "" - -#: ports/stm/common-hal/microcontroller/Processor.c -msgid "Temperature read timed out" -msgstr "" - -#: supervisor/shared/safe_mode.c -msgid "The `microcontroller` module was used to boot into safe mode." -msgstr "" - -#: py/obj.c -msgid "The above exception was the direct cause of the following exception:" -msgstr "" - -#: shared-bindings/rgbmatrix/RGBMatrix.c -msgid "The length of rgb_pins must be 6, 12, 18, 24, or 30" -msgstr "" - -#: shared-module/audiomixer/MixerVoice.c -msgid "The sample's bits_per_sample does not match the mixer's" -msgstr "" - -#: shared-module/audiomixer/MixerVoice.c -msgid "The sample's channel count does not match the mixer's" -msgstr "" - -#: shared-module/audiomixer/MixerVoice.c -msgid "The sample's sample rate does not match the mixer's" -msgstr "" - -#: shared-module/audiomixer/MixerVoice.c -msgid "The sample's signedness does not match the mixer's" -msgstr "" - -#: supervisor/shared/safe_mode.c -msgid "Third-party firmware fatal error." -msgstr "" - -#: shared-module/imagecapture/ParallelImageCapture.c -msgid "This microcontroller does not support continuous capture." -msgstr "" - -#: shared-module/paralleldisplaybus/ParallelBus.c -msgid "" -"This microcontroller only supports data0=, not data_pins=, because it " -"requires contiguous pins." -msgstr "" - -#: shared-bindings/displayio/TileGrid.c -msgid "Tile height must exactly divide bitmap height" -msgstr "" - -#: shared-bindings/displayio/TileGrid.c shared-module/displayio/TileGrid.c -msgid "Tile index out of bounds" -msgstr "" - -#: shared-bindings/displayio/TileGrid.c -msgid "Tile width must exactly divide bitmap width" -msgstr "" - -#: shared-bindings/alarm/time/TimeAlarm.c -msgid "Time is in the past." -msgstr "" - -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nrf/common-hal/_bleio/Adapter.c -#, c-format -msgid "Timeout is too long: Maximum timeout length is %d seconds" -msgstr "" - -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -msgid "Too many channels in sample" -msgstr "" - -#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c -msgid "Too many channels in sample." -msgstr "" - -#: shared-module/displayio/__init__.c -msgid "Too many display busses; forgot displayio.release_displays() ?" -msgstr "" - -#: shared-module/displayio/__init__.c -msgid "Too many displays" -msgstr "" - -#: ports/espressif/common-hal/_bleio/PacketBuffer.c -#: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than %q" -msgstr "" - -#: ports/atmel-samd/common-hal/alarm/touch/TouchAlarm.c -#: ports/raspberrypi/common-hal/alarm/touch/TouchAlarm.c -#: ports/stm/common-hal/alarm/touch/TouchAlarm.c -msgid "Touch alarms not available" -msgstr "" - -#: py/obj.c -msgid "Traceback (most recent call last):\n" -msgstr "" - -#: shared-bindings/time/__init__.c -msgid "Tuple or struct_time argument required" -msgstr "" - -#: ports/stm/common-hal/busio/UART.c -msgid "UART de-init" -msgstr "" - -#: ports/cxd56/common-hal/busio/UART.c ports/espressif/common-hal/busio/UART.c -#: ports/stm/common-hal/busio/UART.c -msgid "UART init" -msgstr "" - -#: ports/raspberrypi/common-hal/busio/UART.c -msgid "UART peripheral in use" -msgstr "" - -#: ports/stm/common-hal/busio/UART.c -msgid "UART re-init" -msgstr "" - -#: ports/stm/common-hal/busio/UART.c -msgid "UART write" -msgstr "" - -#: main.c -msgid "UID:" -msgstr "" - -#: shared-module/usb_hid/Device.c -msgid "USB busy" -msgstr "" - -#: supervisor/shared/safe_mode.c -msgid "USB devices need more endpoints than are available." -msgstr "" - -#: supervisor/shared/safe_mode.c -msgid "USB devices specify too many interface names." -msgstr "" - -#: shared-module/usb_hid/Device.c -msgid "USB error" -msgstr "" - -#: shared-bindings/_bleio/UUID.c -msgid "UUID integer value must be 0-0xffff" -msgstr "" - -#: shared-bindings/_bleio/UUID.c -msgid "UUID string not 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'" -msgstr "" - -#: shared-bindings/_bleio/UUID.c -msgid "UUID value is not str, int or byte buffer" -msgstr "" - -#: ports/raspberrypi/common-hal/memorymap/AddressRange.c -msgid "Unable to access unaligned IO register" -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 "" - -#: supervisor/shared/safe_mode.c -msgid "Unable to allocate to the heap." -msgstr "" - -#: ports/espressif/common-hal/busio/I2C.c -msgid "Unable to create lock" -msgstr "" - -#: shared-module/i2cdisplaybus/I2CDisplayBus.c -#: shared-module/is31fl3741/IS31FL3741.c -#, c-format -msgid "Unable to find I2C Display at %x" -msgstr "" - -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c -msgid "Unable to find free GCLK" -msgstr "Arr! No free GCLK be in sight" - -#: py/parse.c -msgid "Unable to init parser" -msgstr "" - -#: shared-module/displayio/OnDiskBitmap.c -msgid "Unable to read color palette data" -msgstr "" - -#: ports/espressif/common-hal/mdns/Server.c -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "Unable to start mDNS query" -msgstr "" - -#: shared-bindings/nvm/ByteArray.c -msgid "Unable to write to nvm." -msgstr "" - -#: ports/raspberrypi/common-hal/memorymap/AddressRange.c -msgid "Unable to write to read-only memory" -msgstr "" - -#: shared-bindings/alarm/SleepMemory.c -msgid "Unable to write to sleep_memory." -msgstr "" - -#: ports/nrf/common-hal/_bleio/UUID.c -msgid "Unexpected nrfx uuid type" -msgstr "" - -#: ports/espressif/common-hal/ssl/SSLSocket.c -#, c-format -msgid "Unhandled ESP TLS error %d %d %x %d" -msgstr "" - -#: ports/espressif/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown BLE error at %s:%d: %d" -msgstr "" - -#: ports/espressif/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown BLE error: %d" -msgstr "" - -#: ports/raspberrypi/common-hal/wifi/__init__.c -#, c-format -msgid "Unknown error code %d" -msgstr "" - -#: shared-bindings/wifi/Radio.c -#, c-format -msgid "Unknown failure %d" -msgstr "" - -#: ports/nrf/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown gatt error: 0x%04x" -msgstr "" - -#: ports/atmel-samd/common-hal/alarm/pin/PinAlarm.c -#: supervisor/shared/safe_mode.c -msgid "Unknown reason." -msgstr "" - -#: ports/nrf/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown security error: 0x%04x" -msgstr "" - -#: ports/espressif/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown system firmware error at %s:%d: %d" -msgstr "" - -#: ports/nrf/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown system firmware error: %04x" -msgstr "" - -#: ports/espressif/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown system firmware error: %d" -msgstr "" - -#: shared-bindings/adafruit_pixelbuf/PixelBuf.c -#: shared-module/_pixelmap/PixelMap.c -#, c-format -msgid "Unmatched number of items on RHS (expected %d, got %d)." -msgstr "" - -#: 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 "" - -#: shared-bindings/bitmaptools/__init__.c -msgid "Unsupported colorspace" -msgstr "" - -#: shared-module/displayio/bus_core.c -msgid "Unsupported display bus type" -msgstr "" - -#: shared-module/audiocore/WaveFile.c -msgid "Unsupported format" -msgstr "" - -#: shared-bindings/hashlib/__init__.c -msgid "Unsupported hash algorithm" -msgstr "" - -#: ports/espressif/common-hal/dualbank/__init__.c -msgid "Update Failed" -msgstr "" - -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/espressif/common-hal/_bleio/Descriptor.c -#: ports/nrf/common-hal/_bleio/Characteristic.c -#: ports/nrf/common-hal/_bleio/Descriptor.c -msgid "Value length != required fixed length" -msgstr "" - -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/espressif/common-hal/_bleio/Descriptor.c -#: ports/nrf/common-hal/_bleio/Characteristic.c -#: ports/nrf/common-hal/_bleio/Descriptor.c -msgid "Value length > max_length" -msgstr "" - -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Version was invalid" -msgstr "" - -#: ports/stm/common-hal/microcontroller/Processor.c -msgid "Voltage read timed out" -msgstr "" - -#: main.c -msgid "WARNING: Your code filename has two extensions\n" -msgstr "Blimey! Yer code filename has two extensions\n" - -#: ports/nrf/common-hal/watchdog/WatchDogTimer.c -msgid "WatchDogTimer cannot be deinitialized once mode is set to RESET" -msgstr "" - -#: py/builtinhelp.c -#, c-format -msgid "" -"Welcome to Adafruit CircuitPython %s!\n" -"\n" -"Visit circuitpython.org for more information.\n" -"\n" -"To list built-in modules type `help(\"modules\")`.\n" -msgstr "" - -#: supervisor/shared/web_workflow/web_workflow.c -msgid "Wi-Fi: " -msgstr "" - -#: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "Wifi is not enabled" -msgstr "" - -#: main.c -msgid "Woken up by alarm.\n" -msgstr "" - -#: ports/espressif/common-hal/_bleio/PacketBuffer.c -#: ports/nrf/common-hal/_bleio/PacketBuffer.c -msgid "Writes not supported on Characteristic" -msgstr "" - -#: 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/meowmeow/mpconfigboard.h -msgid "You pressed both buttons at start up." -msgstr "" - -#: ports/espressif/boards/m5stack_core_basic/mpconfigboard.h -#: ports/espressif/boards/m5stack_core_fire/mpconfigboard.h -#: ports/espressif/boards/m5stack_stick_c/mpconfigboard.h -#: ports/espressif/boards/m5stack_stick_c_plus/mpconfigboard.h -msgid "You pressed button A at start up." -msgstr "" - -#: ports/espressif/boards/m5stack_m5paper/mpconfigboard.h -msgid "You pressed button DOWN at start up." -msgstr "" - -#: supervisor/shared/safe_mode.c -msgid "You pressed the BOOT button at start up" -msgstr "" - -#: ports/espressif/boards/adafruit_huzzah32_breakout/mpconfigboard.h -msgid "You pressed the GPIO0 button at start up." -msgstr "" - -#: ports/espressif/boards/espressif_esp32_lyrat/mpconfigboard.h -msgid "You pressed the Rec button at start up." -msgstr "" - -#: ports/espressif/boards/adafruit_feather_esp32_v2/mpconfigboard.h -msgid "You pressed the SW38 button at start up." -msgstr "" - -#: ports/espressif/boards/hardkernel_odroid_go/mpconfigboard.h -msgid "You pressed the VOLUME button at start up." -msgstr "" - -#: ports/espressif/boards/m5stack_atom_echo/mpconfigboard.h -#: ports/espressif/boards/m5stack_atom_lite/mpconfigboard.h -#: ports/espressif/boards/m5stack_atom_matrix/mpconfigboard.h -#: ports/espressif/boards/m5stack_atom_u/mpconfigboard.h -msgid "You pressed the central button at start up." -msgstr "" - -#: ports/nrf/boards/aramcon2_badge/mpconfigboard.h -msgid "You pressed the left button at start up." -msgstr "" - -#: supervisor/shared/safe_mode.c -msgid "You pressed the reset button during boot." -msgstr "" - -#: supervisor/shared/micropython.c -msgid "[truncated due to length]" -msgstr "" - -#: py/objtype.c -msgid "__init__() should return None" -msgstr "" - -#: py/objtype.c -#, c-format -msgid "__init__() should return None, not '%s'" -msgstr "" - -#: py/objobject.c -msgid "__new__ arg must be a user-type" -msgstr "" - -#: extmod/modbinascii.c extmod/modhashlib.c py/objarray.c -msgid "a bytes-like object is required" -msgstr "" - -#: shared-bindings/i2ctarget/I2CTarget.c -msgid "addresses is empty" -msgstr "" - -#: py/compile.c -msgid "annotation must be an identifier" -msgstr "" - -#: extmod/ulab/code/numpy/create.c -msgid "arange: cannot compute length" -msgstr "" - -#: py/modbuiltins.c -msgid "arg is an empty sequence" -msgstr "" - -#: py/objobject.c -msgid "arg must be user-type" -msgstr "" - -#: extmod/ulab/code/numpy/numerical.c -msgid "argsort argument must be an ndarray" -msgstr "" - -#: extmod/ulab/code/numpy/numerical.c -msgid "argsort is not implemented for flattened arrays" -msgstr "" - -#: py/runtime.c shared-bindings/supervisor/__init__.c -msgid "argument has wrong type" -msgstr "" - -#: py/compile.c -msgid "argument name reused" -msgstr "" - -#: py/argcheck.c shared-bindings/_stage/__init__.c -#: shared-bindings/digitalio/DigitalInOut.c -msgid "argument num/types mismatch" -msgstr "" - -#: py/runtime.c -msgid "argument should be a '%q' not a '%q'" -msgstr "" - -#: extmod/ulab/code/numpy/numerical.c extmod/ulab/code/numpy/transform.c -msgid "arguments must be ndarrays" -msgstr "" - -#: extmod/ulab/code/ndarray.c -msgid "array and index length must be equal" -msgstr "" - -#: extmod/ulab/code/numpy/io/io.c -msgid "array has too many dimensions" -msgstr "" - -#: extmod/ulab/code/ndarray.c -msgid "array is too big" -msgstr "" - -#: py/objarray.c shared-bindings/alarm/SleepMemory.c -#: shared-bindings/memorymap/AddressRange.c shared-bindings/nvm/ByteArray.c -msgid "array/bytes required on right side" -msgstr "" - -#: py/asmxtensa.c -msgid "asm overflow" -msgstr "" - -#: py/compile.c -msgid "async for/with outside async function" -msgstr "" - -#: extmod/ulab/code/numpy/numerical.c -msgid "attempt to get (arg)min/(arg)max of empty sequence" -msgstr "" - -#: extmod/ulab/code/numpy/numerical.c -msgid "attempt to get argmin/argmax of an empty sequence" -msgstr "" - -#: py/objstr.c -msgid "attributes not supported" -msgstr "" - -#: extmod/ulab/code/ulab_tools.c -msgid "axis is out of bounds" -msgstr "" - -#: extmod/ulab/code/numpy/numerical.c extmod/ulab/code/ulab_tools.c -msgid "axis must be None, or an integer" -msgstr "" - -#: extmod/ulab/code/numpy/numerical.c -msgid "axis too long" -msgstr "" - -#: shared-bindings/bitmaptools/__init__.c -msgid "background value out of range of target" -msgstr "" - -#: py/builtinevex.c -msgid "bad compile mode" -msgstr "" - -#: py/objstr.c -msgid "bad conversion specifier" -msgstr "" - -#: py/objstr.c -msgid "bad format string" -msgstr "" - -#: py/binary.c py/objarray.c -msgid "bad typecode" -msgstr "" - -#: py/emitnative.c -msgid "binary op %q not implemented" -msgstr "" - -#: shared-bindings/bitmaptools/__init__.c -msgid "bitmap sizes must match" -msgstr "" - -#: extmod/modrandom.c -msgid "bits must be 32 or less" -msgstr "" - -#: shared-bindings/audiomixer/Mixer.c -msgid "bits_per_sample must be 8 or 16" -msgstr "" - -#: py/emitinlinethumb.c -msgid "branch not in range" -msgstr "" - -#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c -msgid "buffer is smaller than requested size" -msgstr "" - -#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c -msgid "buffer size must be a multiple of element size" -msgstr "" - -#: shared-module/struct/__init__.c -msgid "buffer size must match format" -msgstr "" - -#: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c -msgid "buffer slices must be of equal length" -msgstr "" - -#: py/modstruct.c shared-module/struct/__init__.c -msgid "buffer too small" -msgstr "" - -#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c -msgid "buffer too small for requested bytes" -msgstr "" - -#: py/emitbc.c -msgid "bytecode overflow" -msgstr "" - -#: py/objarray.c -msgid "bytes length not a multiple of item size" -msgstr "" - -#: py/objstr.c -msgid "bytes value out of range" -msgstr "" - -#: ports/atmel-samd/bindings/samd/Clock.c -msgid "calibration is out of range" -msgstr "" - -#: ports/atmel-samd/bindings/samd/Clock.c -msgid "calibration is read only" -msgstr "" - -#: shared-module/vectorio/Circle.c shared-module/vectorio/Polygon.c -#: shared-module/vectorio/Rectangle.c -msgid "can only have one parent" -msgstr "" - -#: py/emitinlinethumb.c -msgid "can only have up to 4 parameters to Thumb assembly" -msgstr "" - -#: py/emitinlinextensa.c -msgid "can only have up to 4 parameters to Xtensa assembly" -msgstr "" - -#: extmod/ulab/code/ndarray.c -msgid "can only specify one unknown dimension" -msgstr "" - -#: py/objtype.c -msgid "can't add special method to already-subclassed class" -msgstr "" - -#: py/compile.c -msgid "can't assign to expression" -msgstr "" - -#: extmod/modasyncio.c -msgid "can't cancel self" -msgstr "" - -#: shared-module/adafruit_pixelbuf/PixelBuf.c -msgid "can't convert %q to %q" -msgstr "" - -#: py/obj.c -#, c-format -msgid "can't convert %s to complex" -msgstr "" - -#: py/obj.c -#, c-format -msgid "can't convert %s to float" -msgstr "" - -#: py/runtime.c -#, c-format -msgid "can't convert %s to int" -msgstr "" - -#: py/objstr.c -msgid "can't convert '%q' object to %q implicitly" -msgstr "" - -#: py/objint.c -msgid "can't convert NaN to int" -msgstr "" - -#: extmod/ulab/code/numpy/vector.c -msgid "can't convert complex to float" -msgstr "" - -#: py/objint.c -msgid "can't convert inf to int" -msgstr "" - -#: py/obj.c -msgid "can't convert to complex" -msgstr "" - -#: py/obj.c -msgid "can't convert to float" -msgstr "" - -#: py/runtime.c -msgid "can't convert to int" -msgstr "" - -#: py/objstr.c -msgid "can't convert to str implicitly" -msgstr "" - -#: py/compile.c -msgid "can't declare nonlocal in outer code" -msgstr "" - -#: py/compile.c -msgid "can't delete expression" -msgstr "" - -#: py/emitnative.c -msgid "can't do binary op between '%q' and '%q'" -msgstr "" - -#: py/emitnative.c -msgid "can't implicitly convert '%q' to 'bool'" -msgstr "" - -#: py/runtime.c -msgid "can't import name %q" -msgstr "" - -#: py/emitnative.c -msgid "can't load from '%q'" -msgstr "" - -#: py/emitnative.c -msgid "can't load with '%q' index" -msgstr "" - -#: py/builtinimport.c -msgid "can't perform relative import" -msgstr "" - -#: py/objgenerator.c -msgid "can't send non-None value to a just-started generator" -msgstr "" - -#: shared-module/sdcardio/SDCard.c -msgid "can't set 512 block size" -msgstr "" - -#: py/objexcept.c py/objnamedtuple.c -msgid "can't set attribute" -msgstr "" - -#: py/runtime.c -msgid "can't set attribute '%q'" -msgstr "" - -#: py/emitnative.c -msgid "can't store '%q'" -msgstr "" - -#: py/emitnative.c -msgid "can't store to '%q'" -msgstr "" - -#: py/emitnative.c -msgid "can't store with '%q' index" -msgstr "" - -#: py/objstr.c -msgid "" -"can't switch from automatic field numbering to manual field specification" -msgstr "" - -#: py/objstr.c -msgid "" -"can't switch from manual field specification to automatic field numbering" -msgstr "" - -#: py/objcomplex.c -msgid "can't truncate-divide a complex number" -msgstr "" - -#: extmod/moductypes.c -msgid "can't unambiguously get sizeof scalar" -msgstr "" - -#: extmod/modasyncio.c -msgid "can't wait" -msgstr "" - -#: extmod/ulab/code/ndarray.c -msgid "cannot assign new shape" -msgstr "" - -#: extmod/ulab/code/ndarray_operators.c -msgid "cannot cast output with casting rule" -msgstr "" - -#: extmod/ulab/code/ndarray.c -msgid "cannot convert complex to dtype" -msgstr "" - -#: extmod/ulab/code/ndarray.c -msgid "cannot convert complex type" -msgstr "" - -#: py/objtype.c -msgid "cannot create '%q' instances" -msgstr "" - -#: py/objtype.c -msgid "cannot create instance" -msgstr "" - -#: extmod/ulab/code/ndarray.c -msgid "cannot delete array elements" -msgstr "" - -#: extmod/ulab/code/ndarray.c -msgid "cannot reshape array" -msgstr "" - -#: py/emitnative.c -msgid "casting" -msgstr "" - -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "channel re-init" -msgstr "" - -#: shared-bindings/_stage/Text.c -msgid "chars buffer too small" -msgstr "" - -#: py/modbuiltins.c -msgid "chr() arg not in range(0x110000)" -msgstr "" - -#: py/modbuiltins.c -msgid "chr() arg not in range(256)" -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 "" - -#: shared-bindings/displayio/Palette.c -msgid "color buffer must be 3 bytes (RGB) or 4 bytes (RGB + pad byte)" -msgstr "" - -#: shared-bindings/displayio/Palette.c -msgid "color buffer must be a buffer, tuple, list, or int" -msgstr "" - -#: shared-bindings/displayio/Palette.c -msgid "color buffer must be a bytearray or array of type 'b' or 'B'" -msgstr "" - -#: shared-bindings/displayio/Palette.c -msgid "color must be between 0x000000 and 0xffffff" -msgstr "" - -#: py/emitnative.c -msgid "comparison of int and uint" -msgstr "" - -#: py/objcomplex.c -msgid "complex divide by zero" -msgstr "" - -#: py/objfloat.c py/parsenum.c -msgid "complex values not supported" -msgstr "" - -#: extmod/modzlib.c -msgid "compression header" -msgstr "" - -#: py/emitnative.c -msgid "conversion to object" -msgstr "" - -#: extmod/ulab/code/numpy/filter.c -msgid "convolve arguments must be linear arrays" -msgstr "" - -#: extmod/ulab/code/numpy/filter.c -msgid "convolve arguments must be ndarrays" -msgstr "" - -#: extmod/ulab/code/numpy/filter.c -msgid "convolve arguments must not be empty" -msgstr "" - -#: extmod/ulab/code/numpy/io/io.c -msgid "corrupted file" -msgstr "" - -#: extmod/ulab/code/numpy/poly.c -msgid "could not invert Vandermonde matrix" -msgstr "" - -#: shared-module/sdcardio/SDCard.c -msgid "couldn't determine SD card version" -msgstr "" - -#: extmod/ulab/code/numpy/numerical.c -msgid "cross is defined for 1D arrays of length 3" -msgstr "" - -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "data must be iterable" -msgstr "" - -#: 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 "" - -#: py/parsenum.c -msgid "decimal numbers not supported" -msgstr "" - -#: py/compile.c -msgid "default 'except' must be last" -msgstr "" - -#: shared-bindings/msgpack/__init__.c -msgid "default is not a function" -msgstr "" - -#: shared-bindings/audiobusio/PDMIn.c -msgid "" -"destination buffer must be a bytearray or array of type 'B' for bit_depth = 8" -msgstr "" - -#: shared-bindings/audiobusio/PDMIn.c -msgid "destination buffer must be an array of type 'H' for bit_depth = 16" -msgstr "" - -#: py/objdict.c -msgid "dict update sequence has wrong length" -msgstr "" - -#: extmod/ulab/code/numpy/numerical.c -msgid "diff argument must be an ndarray" -msgstr "" - -#: extmod/ulab/code/numpy/numerical.c -msgid "differentiation order out of range" -msgstr "" - -#: extmod/ulab/code/numpy/transform.c -msgid "dimensions do not match" -msgstr "" - -#: py/emitnative.c -msgid "div/mod not implemented for uint" -msgstr "" - -#: extmod/ulab/code/numpy/create.c -msgid "divide by zero" -msgstr "" - -#: py/runtime.c -msgid "division by zero" -msgstr "" - -#: extmod/ulab/code/numpy/vector.c -msgid "dtype must be float, or complex" -msgstr "" - -#: extmod/ulab/code/ndarray_operators.c -msgid "dtype of int32 is not supported" -msgstr "" - -#: py/objdeque.c -msgid "empty" -msgstr "" - -#: extmod/ulab/code/numpy/io/io.c -msgid "empty file" -msgstr "" - -#: extmod/modasyncio.c extmod/modheapq.c -msgid "empty heap" -msgstr "" - -#: py/objstr.c -msgid "empty separator" -msgstr "" - -#: shared-bindings/random/__init__.c -msgid "empty sequence" -msgstr "" - -#: py/objstr.c -msgid "end of format while looking for conversion specifier" -msgstr "" - -#: shared-bindings/alarm/time/TimeAlarm.c -msgid "epoch_time not supported on this board" -msgstr "" - -#: ports/nrf/common-hal/busio/UART.c -#, c-format -msgid "error = 0x%08lX" -msgstr "" - -#: py/runtime.c -msgid "exceptions must derive from BaseException" -msgstr "" - -#: py/objstr.c -msgid "expected ':' after format specifier" -msgstr "" - -#: py/obj.c -msgid "expected tuple/list" -msgstr "" - -#: py/modthread.c -msgid "expecting a dict for keyword args" -msgstr "" - -#: py/compile.c -msgid "expecting an assembler instruction" -msgstr "" - -#: py/compile.c -msgid "expecting just a value for set" -msgstr "" - -#: py/compile.c -msgid "expecting key:value for dict" -msgstr "" - -#: shared-bindings/msgpack/__init__.c -msgid "ext_hook is not a function" -msgstr "" - -#: py/argcheck.c -msgid "extra keyword arguments given" -msgstr "" - -#: py/argcheck.c -msgid "extra positional arguments given" -msgstr "" - -#: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/gifio/OnDiskGif.c -#: shared-bindings/synthio/__init__.c shared-module/gifio/GifWriter.c -msgid "file must be a file opened in byte mode" -msgstr "" - -#: shared-bindings/traceback/__init__.c -msgid "file write is not available" -msgstr "" - -#: shared-bindings/storage/__init__.c -msgid "filesystem must provide mount method" -msgstr "" - -#: extmod/ulab/code/numpy/vector.c -msgid "first argument must be a callable" -msgstr "" - -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "first argument must be a function" -msgstr "" - -#: extmod/ulab/code/numpy/create.c -msgid "first argument must be a tuple of ndarrays" -msgstr "" - -#: extmod/ulab/code/numpy/transform.c extmod/ulab/code/numpy/vector.c -msgid "first argument must be an ndarray" -msgstr "" - -#: py/objtype.c -msgid "first argument to super() must be type" -msgstr "" - -#: extmod/ulab/code/scipy/linalg/linalg.c -msgid "first two arguments must be ndarrays" -msgstr "" - -#: extmod/ulab/code/ndarray.c -msgid "flattening order must be either 'C', or 'F'" -msgstr "" - -#: extmod/ulab/code/numpy/numerical.c -msgid "flip argument must be an ndarray" -msgstr "" - -#: py/objint.c -msgid "float too big" -msgstr "" - -#: py/nativeglue.c -msgid "float unsupported" -msgstr "" - -#: shared-bindings/_stage/Text.c -msgid "font must be 2048 bytes long" -msgstr "" - -#: extmod/moddeflate.c -msgid "format" -msgstr "" - -#: py/objstr.c -msgid "format requires a dict" -msgstr "" - -#: py/objdeque.c -msgid "full" -msgstr "" - -#: 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 "" - -#: py/bc.c py/objnamedtuple.c -msgid "function got multiple values for argument '%q'" -msgstr "" - -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "function has the same sign at the ends of interval" -msgstr "" - -#: extmod/ulab/code/ndarray.c -msgid "function is defined for ndarrays only" -msgstr "" - -#: extmod/ulab/code/numpy/carray/carray.c -msgid "function is implemented for ndarrays only" -msgstr "" - -#: py/argcheck.c -#, c-format -msgid "function missing %d required positional arguments" -msgstr "" - -#: py/bc.c -msgid "function missing keyword-only argument" -msgstr "" - -#: py/bc.c -msgid "function missing required keyword argument '%q'" -msgstr "" - -#: py/bc.c -#, c-format -msgid "function missing required positional argument #%d" -msgstr "" - -#: 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 "" - -#: shared-bindings/time/__init__.c -msgid "function takes exactly 9 arguments" -msgstr "" - -#: py/objgenerator.c -msgid "generator already executing" -msgstr "" - -#: py/objgenerator.c -msgid "generator ignored GeneratorExit" -msgstr "" - -#: py/objgenerator.c py/runtime.c -msgid "generator raised StopIteration" -msgstr "" - -#: shared-bindings/_stage/Layer.c -msgid "graphic must be 2048 bytes long" -msgstr "" - -#: extmod/modhashlib.c -msgid "hash is final" -msgstr "" - -#: extmod/modheapq.c -msgid "heap must be a list" -msgstr "" - -#: py/compile.c -msgid "identifier redefined as global" -msgstr "" - -#: py/compile.c -msgid "identifier redefined as nonlocal" -msgstr "" - -#: py/compile.c -msgid "import * not at module level" -msgstr "" - -#: py/persistentcode.c -msgid "incompatible .mpy arch" -msgstr "" - -#: py/persistentcode.c -msgid "incompatible .mpy file" -msgstr "" - -#: py/objstr.c -msgid "incomplete format" -msgstr "" - -#: py/objstr.c -msgid "incomplete format key" -msgstr "" - -#: extmod/modbinascii.c -msgid "incorrect padding" -msgstr "" - -#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/transform.c -msgid "index is out of bounds" -msgstr "" - -#: shared-bindings/_pixelmap/PixelMap.c -msgid "index must be tuple or int" -msgstr "" - -#: extmod/ulab/code/numpy/numerical.c extmod/ulab/code/ulab_tools.c -#: ports/espressif/common-hal/pulseio/PulseIn.c -#: shared-bindings/bitmaptools/__init__.c -msgid "index out of range" -msgstr "" - -#: py/obj.c -msgid "indices must be integers" -msgstr "" - -#: extmod/ulab/code/ndarray.c -msgid "indices must be integers, slices, or Boolean lists" -msgstr "" - -#: ports/espressif/common-hal/busio/I2C.c -msgid "init I2C" -msgstr "" - -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "initial values must be iterable" -msgstr "" - -#: shared-bindings/_bleio/Characteristic.c shared-bindings/_bleio/Descriptor.c -msgid "initial_value length is wrong" -msgstr "" - -#: py/compile.c -msgid "inline assembler must be a function" -msgstr "" - -#: extmod/ulab/code/numpy/vector.c -msgid "input and output dimensions differ" -msgstr "" - -#: extmod/ulab/code/numpy/vector.c -msgid "input and output shapes differ" -msgstr "" - -#: extmod/ulab/code/numpy/create.c -msgid "input argument must be an integer, a tuple, or a list" -msgstr "" - -#: extmod/ulab/code/numpy/fft/fft_tools.c -msgid "input array length must be power of 2" -msgstr "" - -#: extmod/ulab/code/numpy/create.c -msgid "input arrays are not compatible" -msgstr "" - -#: extmod/ulab/code/numpy/poly.c -msgid "input data must be an iterable" -msgstr "" - -#: extmod/ulab/code/numpy/vector.c -msgid "input dtype must be float or complex" -msgstr "" - -#: extmod/ulab/code/numpy/poly.c -msgid "input is not iterable" -msgstr "" - -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "input matrix is asymmetric" -msgstr "" - -#: extmod/ulab/code/numpy/linalg/linalg.c -#: extmod/ulab/code/scipy/linalg/linalg.c -msgid "input matrix is singular" -msgstr "" - -#: extmod/ulab/code/numpy/create.c -msgid "input must be 1- or 2-d" -msgstr "" - -#: extmod/ulab/code/numpy/carray/carray.c -msgid "input must be a 1D ndarray" -msgstr "" - -#: extmod/ulab/code/scipy/linalg/linalg.c extmod/ulab/code/user/user.c -msgid "input must be a dense ndarray" -msgstr "" - -#: extmod/ulab/code/user/user.c -msgid "input must be an ndarray" -msgstr "" - -#: extmod/ulab/code/numpy/carray/carray.c -msgid "input must be an ndarray, or a scalar" -msgstr "" - -#: extmod/ulab/code/scipy/signal/signal.c -msgid "input must be one-dimensional" -msgstr "" - -#: extmod/ulab/code/ulab_tools.c -msgid "input must be square matrix" -msgstr "" - -#: extmod/ulab/code/numpy/numerical.c -msgid "input must be tuple, list, range, or ndarray" -msgstr "" - -#: extmod/ulab/code/numpy/poly.c -msgid "input vectors must be of equal length" -msgstr "" - -#: extmod/ulab/code/numpy/approx.c -msgid "interp is defined for 1D iterables of equal length" -msgstr "" - -#: shared-bindings/_bleio/Adapter.c -#, c-format -msgid "interval must be in range %s-%s" -msgstr "" - -#: py/compile.c -msgid "invalid arch" -msgstr "" - -#: shared-bindings/bitmaptools/__init__.c -#, c-format -msgid "invalid bits_per_pixel %d, must be, 1, 2, 4, 8, 16, 24, or 32" -msgstr "" - -#: ports/raspberrypi/common-hal/ssl/SSLSocket.c -msgid "invalid cert" -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 "" - -#: shared-bindings/traceback/__init__.c -msgid "invalid exception" -msgstr "" - -#: py/objstr.c -msgid "invalid format specifier" -msgstr "" - -#: shared-bindings/wifi/Radio.c -msgid "invalid hostname" -msgstr "" - -#: ports/raspberrypi/common-hal/ssl/SSLSocket.c -msgid "invalid key" -msgstr "" - -#: py/compile.c -msgid "invalid micropython decorator" -msgstr "" - -#: ports/espressif/common-hal/espcamera/Camera.c -msgid "invalid setting" -msgstr "" - -#: shared-bindings/random/__init__.c -msgid "invalid step" -msgstr "" - -#: py/compile.c py/parse.c -msgid "invalid syntax" -msgstr "" - -#: py/parsenum.c -msgid "invalid syntax for integer" -msgstr "" - -#: py/parsenum.c -#, c-format -msgid "invalid syntax for integer with base %d" -msgstr "" - -#: py/parsenum.c -msgid "invalid syntax for number" -msgstr "" - -#: py/objtype.c -msgid "issubclass() arg 1 must be a class" -msgstr "" - -#: py/objtype.c -msgid "issubclass() arg 2 must be a class or a tuple of classes" -msgstr "" - -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "iterations did not converge" -msgstr "" - -#: py/objstr.c -msgid "join expects a list of str/bytes objects consistent with self object" -msgstr "" - -#: py/argcheck.c -msgid "keyword argument(s) not implemented - use normal args instead" -msgstr "" - -#: py/emitinlinethumb.c py/emitinlinextensa.c -msgid "label '%q' not defined" -msgstr "" - -#: py/compile.c -msgid "label redefined" -msgstr "" - -#: shared-bindings/audiomixer/MixerVoice.c -msgid "level must be between 0 and 1" -msgstr "" - -#: py/objarray.c -msgid "lhs and rhs should be compatible" -msgstr "" - -#: py/emitnative.c -msgid "local '%q' has type '%q' but source is '%q'" -msgstr "" - -#: py/emitnative.c -msgid "local '%q' used before type known" -msgstr "" - -#: py/vm.c -msgid "local variable referenced before assignment" -msgstr "" - -#: ports/espressif/common-hal/canio/CAN.c -msgid "loopback + silent mode not supported by peripheral" -msgstr "" - -#: ports/espressif/common-hal/mdns/Server.c -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "mDNS already initialized" -msgstr "" - -#: ports/espressif/common-hal/mdns/Server.c -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "mDNS only works with built-in WiFi" -msgstr "" - -#: py/parse.c -msgid "malformed f-string" -msgstr "" - -#: shared-bindings/_stage/Layer.c -msgid "map buffer too small" -msgstr "" - -#: py/modmath.c shared-bindings/math/__init__.c -msgid "math domain error" -msgstr "" - -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "matrix is not positive definite" -msgstr "" - -#: ports/espressif/common-hal/_bleio/Descriptor.c -#: 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 "" - -#: extmod/ulab/code/ndarray.c -msgid "maximum number of dimensions is " -msgstr "" - -#: py/runtime.c -msgid "maximum recursion depth exceeded" -msgstr "" - -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "maxiter must be > 0" -msgstr "" - -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "maxiter should be > 0" -msgstr "" - -#: extmod/ulab/code/numpy/numerical.c -msgid "median argument must be an ndarray" -msgstr "" - -#: py/runtime.c -#, c-format -msgid "memory allocation failed, allocating %u bytes" -msgstr "" - -#: py/runtime.c -msgid "memory allocation failed, heap is locked" -msgstr "" - -#: py/objarray.c -msgid "memoryview offset too large" -msgstr "" - -#: py/objarray.c -msgid "memoryview: length is not a multiple of itemsize" -msgstr "" - -#: extmod/modtime.c -msgid "mktime needs a tuple of length 8 or 9" -msgstr "" - -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "mode must be complete, or reduced" -msgstr "" - -#: py/builtinimport.c -msgid "module not found" -msgstr "" - -#: ports/espressif/common-hal/wifi/Monitor.c -msgid "monitor init failed" -msgstr "" - -#: extmod/ulab/code/numpy/poly.c -msgid "more degrees of freedom than data points" -msgstr "" - -#: py/compile.c -msgid "multiple *x in assignment" -msgstr "" - -#: py/objtype.c -msgid "multiple bases have instance lay-out conflict" -msgstr "" - -#: py/objtype.c -msgid "multiple inheritance not supported" -msgstr "" - -#: py/emitnative.c -msgid "must raise an object" -msgstr "" - -#: py/modbuiltins.c -msgid "must use keyword argument for key function" -msgstr "" - -#: py/runtime.c -msgid "name '%q' is not defined" -msgstr "" - -#: py/runtime.c -msgid "name not defined" -msgstr "" - -#: py/persistentcode.c -msgid "native code in .mpy unsupported" -msgstr "" - -#: py/asmthumb.c -msgid "native method too big" -msgstr "" - -#: py/emitnative.c -msgid "native yield" -msgstr "" - -#: extmod/ulab/code/ndarray.c -msgid "ndarray length overflows" -msgstr "" - -#: py/runtime.c -#, c-format -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 "" - -#: py/objint_mpz.c py/runtime.c -msgid "negative shift count" -msgstr "" - -#: shared-bindings/_pixelmap/PixelMap.c -msgid "nested index must be int" -msgstr "" - -#: shared-module/sdcardio/SDCard.c -msgid "no SD card" -msgstr "" - -#: py/vm.c -msgid "no active exception to reraise" -msgstr "" - -#: py/compile.c -msgid "no binding for nonlocal found" -msgstr "" - -#: shared-module/msgpack/__init__.c -msgid "no default packer" -msgstr "" - -#: extmod/modrandom.c -msgid "no default seed" -msgstr "" - -#: py/builtinimport.c -msgid "no module named '%q'" -msgstr "" - -#: shared-module/sdcardio/SDCard.c -msgid "no response from SD card" -msgstr "" - -#: ports/espressif/common-hal/espcamera/Camera.c py/objobject.c py/runtime.c -msgid "no such attribute" -msgstr "" - -#: ports/espressif/common-hal/_bleio/Connection.c -#: ports/nrf/common-hal/_bleio/Connection.c -msgid "non-UUID found in service_uuids_whitelist" -msgstr "" - -#: py/compile.c -msgid "non-default argument follows default argument" -msgstr "" - -#: py/objstr.c -msgid "non-hex digit found" -msgstr "" - -#: ports/nrf/common-hal/_bleio/Adapter.c -msgid "non-zero timeout must be > 0.01" -msgstr "" - -#: shared-bindings/_bleio/Adapter.c -msgid "non-zero timeout must be >= interval" -msgstr "" - -#: shared-bindings/_bleio/UUID.c -msgid "not a 128-bit UUID" -msgstr "" - -#: py/parse.c -msgid "not a constant" -msgstr "" - -#: py/objstr.c -msgid "not all arguments converted during string formatting" -msgstr "" - -#: py/objstr.c -msgid "not enough arguments for format string" -msgstr "" - -#: extmod/ulab/code/numpy/carray/carray_tools.c -msgid "not implemented for complex dtype" -msgstr "" - -#: extmod/ulab/code/numpy/bitwise.c -msgid "not supported for input types" -msgstr "" - -#: extmod/ulab/code/numpy/create.c -msgid "number of points must be at least 2" -msgstr "" - -#: py/builtinhelp.c -msgid "object " -msgstr "" - -#: py/obj.c -#, c-format -msgid "object '%s' isn't a tuple or list" -msgstr "" - -#: py/obj.c -msgid "object doesn't support item assignment" -msgstr "" - -#: py/obj.c -msgid "object doesn't support item deletion" -msgstr "" - -#: py/obj.c -msgid "object has no len" -msgstr "" - -#: py/obj.c -msgid "object isn't subscriptable" -msgstr "" - -#: py/runtime.c -msgid "object not an iterator" -msgstr "" - -#: py/objtype.c py/runtime.c -msgid "object not callable" -msgstr "" - -#: py/sequence.c shared-bindings/displayio/Group.c -msgid "object not in sequence" -msgstr "" - -#: py/runtime.c -msgid "object not iterable" -msgstr "" - -#: py/obj.c -#, c-format -msgid "object of type '%s' has no len()" -msgstr "" - -#: py/obj.c -msgid "object with buffer protocol required" -msgstr "" - -#: py/objstr.c -msgid "odd-length string" -msgstr "" - -#: supervisor/shared/web_workflow/web_workflow.c -msgid "off" -msgstr "" - -#: extmod/ulab/code/utils/utils.c -msgid "offset is too large" -msgstr "" - -#: shared-bindings/dualbank/__init__.c -msgid "offset must be >= 0" -msgstr "" - -#: extmod/ulab/code/numpy/create.c -msgid "offset must be non-negative and no greater than buffer length" -msgstr "" - -#: ports/nrf/common-hal/audiobusio/PDMIn.c -#: ports/stm/common-hal/audiobusio/PDMIn.c -msgid "only bit_depth=16 is supported" -msgstr "" - -#: ports/stm/common-hal/audiobusio/PDMIn.c -msgid "only mono is supported" -msgstr "" - -#: extmod/ulab/code/numpy/create.c -msgid "only ndarrays can be concatenated" -msgstr "" - -#: ports/stm/common-hal/audiobusio/PDMIn.c -msgid "only oversample=64 is supported" -msgstr "" - -#: ports/nrf/common-hal/audiobusio/PDMIn.c -#: ports/stm/common-hal/audiobusio/PDMIn.c -msgid "only sample_rate=16000 is supported" -msgstr "" - -#: py/objarray.c py/objstr.c py/objstrunicode.c py/objtuple.c -#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c -#: shared-bindings/nvm/ByteArray.c -msgid "only slices with step=1 (aka None) are supported" -msgstr "" - -#: py/vm.c -msgid "opcode" -msgstr "" - -#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/bitwise.c -#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/numpy/vector.c -msgid "operands could not be broadcast together" -msgstr "" - -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "operation is defined for 2D arrays only" -msgstr "" - -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "operation is defined for ndarrays only" -msgstr "" - -#: extmod/ulab/code/ndarray.c -msgid "operation is implemented for 1D Boolean arrays only" -msgstr "" - -#: extmod/ulab/code/numpy/numerical.c -msgid "operation is not implemented on ndarrays" -msgstr "" - -#: extmod/ulab/code/ndarray.c -msgid "operation is not supported for given type" -msgstr "" - -#: extmod/ulab/code/ndarray_operators.c -msgid "operation not supported for the input types" -msgstr "" - -#: py/modbuiltins.c -msgid "ord expects a character" -msgstr "" - -#: py/modbuiltins.c -#, c-format -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/numpy/vector.c -msgid "out keyword is not supported for complex dtype" -msgstr "" - -#: extmod/ulab/code/numpy/vector.c -msgid "out keyword is not supported for function" -msgstr "" - -#: extmod/ulab/code/utils/utils.c -msgid "out must be a float dense array" -msgstr "" - -#: extmod/ulab/code/numpy/vector.c -msgid "out must be an ndarray" -msgstr "" - -#: extmod/ulab/code/numpy/vector.c -msgid "out must be of float dtype" -msgstr "" - -#: shared-bindings/bitmaptools/__init__.c -msgid "out of range of target" -msgstr "" - -#: py/objint_mpz.c -msgid "overflow converting long int to machine word" -msgstr "" - -#: py/modstruct.c -#, c-format -msgid "pack expected %d items for packing (got %d)" -msgstr "" - -#: shared-bindings/_stage/Layer.c shared-bindings/_stage/Text.c -msgid "palette must be 32 bytes long" -msgstr "" - -#: py/emitinlinextensa.c -msgid "parameters must be registers in sequence a2 to a5" -msgstr "" - -#: py/emitinlinethumb.c -msgid "parameters must be registers in sequence r0 to r3" -msgstr "" - -#: shared-bindings/bitmaptools/__init__.c -msgid "pixel coordinates out of bounds" -msgstr "" - -#: extmod/vfs_posix_file.c -msgid "poll on file not available on win32" -msgstr "" - -#: ports/espressif/common-hal/pulseio/PulseIn.c -msgid "pop from an empty PulseIn" -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/compile.c -msgid "positional arg after **" -msgstr "" - -#: py/compile.c -msgid "positional arg after keyword arg" -msgstr "" - -#: py/objint_mpz.c -msgid "pow() 3rd argument cannot be 0" -msgstr "" - -#: py/objint_mpz.c -msgid "pow() with 3 arguments requires integers" -msgstr "" - -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "pull masks conflict with direction masks" -msgstr "" - -#: py/parse.c -msgid "raw f-strings are not supported" -msgstr "" - -#: extmod/ulab/code/numpy/fft/fft_tools.c -msgid "real and imaginary parts must be of equal length" -msgstr "" - -#: py/builtinimport.c -msgid "relative import" -msgstr "" - -#: py/obj.c -#, c-format -msgid "requested length %d but object has length %d" -msgstr "" - -#: extmod/ulab/code/ndarray_operators.c -msgid "results cannot be cast to specified type" -msgstr "" - -#: py/compile.c -msgid "return annotation must be an identifier" -msgstr "" - -#: py/emitnative.c -msgid "return expected '%q' but got '%q'" -msgstr "" - -#: shared-bindings/rgbmatrix/RGBMatrix.c -#, c-format -msgid "rgb_pins[%d] duplicates another pin assignment" -msgstr "" - -#: shared-bindings/rgbmatrix/RGBMatrix.c -#, c-format -msgid "rgb_pins[%d] is not on the same port as clock" -msgstr "" - -#: extmod/ulab/code/numpy/numerical.c -msgid "roll argument must be an ndarray" -msgstr "" - -#: py/objstr.c -msgid "rsplit(None,n)" -msgstr "" - -#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c -#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c -msgid "sampling rate out of range" -msgstr "" - -#: py/modmicropython.c -msgid "schedule queue full" -msgstr "" - -#: py/builtinimport.c -msgid "script compilation not supported" -msgstr "" - -#: py/nativeglue.c -msgid "set unsupported" -msgstr "" - -#: extmod/ulab/code/ndarray.c -msgid "shape must be integer or tuple of integers" -msgstr "" - -#: shared-module/msgpack/__init__.c -msgid "short read" -msgstr "" - -#: py/objstr.c -msgid "sign not allowed in string format specifier" -msgstr "" - -#: py/objstr.c -msgid "sign not allowed with integer format specifier 'c'" -msgstr "" - -#: extmod/ulab/code/ulab_tools.c -msgid "size is defined for ndarrays only" -msgstr "" - -#: shared-bindings/time/__init__.c -msgid "sleep length must be non-negative" -msgstr "" - -#: py/nativeglue.c -msgid "slice unsupported" -msgstr "" - -#: py/objint.c py/sequence.c -msgid "small int overflow" -msgstr "" - -#: main.c -msgid "soft reboot\n" -msgstr "" - -#: extmod/ulab/code/numpy/numerical.c -msgid "sort argument must be an ndarray" -msgstr "" - -#: extmod/ulab/code/scipy/signal/signal.c -msgid "sos array must be of shape (n_section, 6)" -msgstr "" - -#: extmod/ulab/code/scipy/signal/signal.c -msgid "sos[:, 3] should be all ones" -msgstr "" - -#: extmod/ulab/code/scipy/signal/signal.c -msgid "sosfilt requires iterable arguments" -msgstr "" - -#: shared-bindings/bitmaptools/__init__.c -msgid "source palette too large" -msgstr "" - -#: shared-bindings/bitmaptools/__init__.c -msgid "source_bitmap must have value_count of 2 or 65536" -msgstr "" - -#: shared-bindings/bitmaptools/__init__.c -msgid "source_bitmap must have value_count of 65536" -msgstr "" - -#: shared-bindings/bitmaptools/__init__.c -msgid "source_bitmap must have value_count of 8" -msgstr "" - -#: extmod/modre.c -msgid "splitting with sub-captures" -msgstr "" - -#: py/objstr.c -msgid "start/end indices" -msgstr "" - -#: shared-bindings/random/__init__.c -msgid "stop not reachable from start" -msgstr "" - -#: py/stream.c shared-bindings/getpass/__init__.c -msgid "stream operation not supported" -msgstr "" - -#: py/objarray.c py/objstr.c -msgid "string argument without an encoding" -msgstr "" - -#: py/objstrunicode.c -msgid "string index out of range" -msgstr "" - -#: py/objstrunicode.c -#, c-format -msgid "string indices must be integers, not %s" -msgstr "" - -#: extmod/moductypes.c -msgid "struct: can't index" -msgstr "" - -#: extmod/moductypes.c -msgid "struct: index out of range" -msgstr "" - -#: extmod/moductypes.c -msgid "struct: no fields" -msgstr "" - -#: py/objarray.c py/objstr.c -msgid "substring not found" -msgstr "" - -#: py/compile.c -msgid "super() can't find self" -msgstr "" - -#: extmod/modjson.c -msgid "syntax error in JSON" -msgstr "" - -#: extmod/moductypes.c -msgid "syntax error in uctypes descriptor" -msgstr "" - -#: extmod/modtime.c -msgid "ticks interval overflow" -msgstr "" - -#: ports/nrf/common-hal/watchdog/WatchDogTimer.c -msgid "timeout duration exceeded the maximum supported value" -msgstr "" - -#: ports/nrf/common-hal/_bleio/Adapter.c -msgid "timeout must be < 655.35 secs" -msgstr "" - -#: shared-module/sdcardio/SDCard.c -msgid "timeout waiting for v1 card" -msgstr "" - -#: shared-module/sdcardio/SDCard.c -msgid "timeout waiting for v2 card" -msgstr "" - -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "timer re-init" -msgstr "" - -#: shared-bindings/time/__init__.c -msgid "timestamp out of range for platform time_t" -msgstr "" - -#: extmod/ulab/code/ndarray.c -msgid "tobytes can be invoked for dense arrays only" -msgstr "" - -#: py/compile.c -msgid "too many args" -msgstr "" - -#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/create.c -msgid "too many dimensions" -msgstr "" - -#: extmod/ulab/code/ndarray.c -msgid "too many indices" -msgstr "" - -#: py/asmthumb.c -msgid "too many locals for native method" -msgstr "" - -#: py/runtime.c -#, c-format -msgid "too many values to unpack (expected %d)" -msgstr "" - -#: extmod/ulab/code/numpy/approx.c -msgid "trapz is defined for 1D arrays of equal length" -msgstr "" - -#: extmod/ulab/code/numpy/approx.c -msgid "trapz is defined for 1D iterables" -msgstr "" - -#: py/obj.c -msgid "tuple/list has wrong length" -msgstr "" - -#: ports/espressif/common-hal/canio/CAN.c -#, c-format -msgid "twai_driver_install returned esp-idf error #%d" -msgstr "" - -#: ports/espressif/common-hal/canio/CAN.c -#, c-format -msgid "twai_start returned esp-idf error #%d" -msgstr "" - -#: shared-bindings/busio/UART.c shared-bindings/canio/CAN.c -msgid "tx and rx cannot both be None" -msgstr "" - -#: py/objtype.c -msgid "type '%q' is not an acceptable base type" -msgstr "" - -#: py/objtype.c -msgid "type is not an acceptable base type" -msgstr "" - -#: py/runtime.c -msgid "type object '%q' has no attribute '%q'" -msgstr "" - -#: py/objtype.c -msgid "type takes 1 or 3 arguments" -msgstr "" - -#: py/objint_longlong.c -msgid "ulonglong too large" -msgstr "" - -#: py/emitnative.c -msgid "unary op %q not implemented" -msgstr "" - -#: py/parse.c -msgid "unexpected indent" -msgstr "" - -#: py/bc.c -msgid "unexpected keyword argument" -msgstr "" - -#: py/argcheck.c py/bc.c py/objnamedtuple.c -#: shared-bindings/traceback/__init__.c -msgid "unexpected keyword argument '%q'" -msgstr "" - -#: py/lexer.c -msgid "unicode name escapes" -msgstr "" - -#: py/parse.c -msgid "unindent doesn't match any outer indent level" -msgstr "" - -#: py/objstr.c -#, c-format -msgid "unknown conversion specifier %c" -msgstr "" - -#: py/objstr.c -msgid "unknown format code '%c' for object of type '%q'" -msgstr "" - -#: py/compile.c -msgid "unknown type" -msgstr "" - -#: py/compile.c -msgid "unknown type '%q'" -msgstr "" - -#: py/objstr.c -#, c-format -msgid "unmatched '%c' in format" -msgstr "" - -#: py/objtype.c py/runtime.c -msgid "unreadable attribute" -msgstr "" - -#: shared-bindings/displayio/TileGrid.c shared-bindings/vectorio/VectorShape.c -msgid "unsupported %q type" -msgstr "" - -#: py/emitinlinethumb.c -#, c-format -msgid "unsupported Thumb instruction '%s' with %d arguments" -msgstr "" - -#: py/emitinlinextensa.c -#, c-format -msgid "unsupported Xtensa instruction '%s' with %d arguments" -msgstr "" - -#: shared-module/gifio/GifWriter.c -msgid "unsupported colorspace for GifWriter" -msgstr "" - -#: shared-bindings/bitmaptools/__init__.c -msgid "unsupported colorspace for dither" -msgstr "" - -#: py/objstr.c -#, c-format -msgid "unsupported format character '%c' (0x%x) at index %d" -msgstr "" - -#: py/runtime.c -msgid "unsupported type for %q: '%s'" -msgstr "" - -#: py/runtime.c -msgid "unsupported type for operator" -msgstr "" - -#: py/runtime.c -msgid "unsupported types for %q: '%q', '%q'" -msgstr "" - -#: extmod/ulab/code/numpy/io/io.c -msgid "usecols is too high" -msgstr "" - -#: extmod/ulab/code/numpy/io/io.c -msgid "usecols keyword must be specified" -msgstr "" - -#: py/objint.c -#, c-format -msgid "value must fit in %d byte(s)" -msgstr "" - -#: shared-bindings/bitmaptools/__init__.c -msgid "value out of range of target" -msgstr "" - -#: extmod/moddeflate.c -msgid "wbits" -msgstr "" - -#: shared-bindings/is31fl3741/FrameBuffer.c -msgid "width must be greater than zero" -msgstr "" - -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "wifi is not enabled" -msgstr "" - -#: ports/raspberrypi/common-hal/wifi/Monitor.c -msgid "wifi.Monitor not available" -msgstr "" - -#: shared-bindings/_bleio/Adapter.c -msgid "window must be <= interval" -msgstr "" - -#: extmod/ulab/code/numpy/numerical.c -msgid "wrong axis index" -msgstr "" - -#: extmod/ulab/code/numpy/create.c -msgid "wrong axis specified" -msgstr "" - -#: extmod/ulab/code/numpy/io/io.c -msgid "wrong dtype" -msgstr "" - -#: extmod/ulab/code/numpy/transform.c -msgid "wrong index type" -msgstr "" - -#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/numpy/create.c -#: extmod/ulab/code/numpy/io/io.c extmod/ulab/code/numpy/transform.c -#: extmod/ulab/code/numpy/vector.c -msgid "wrong input type" -msgstr "" - -#: extmod/ulab/code/numpy/transform.c -msgid "wrong length of condition array" -msgstr "" - -#: extmod/ulab/code/numpy/transform.c -msgid "wrong length of index array" -msgstr "" - -#: extmod/ulab/code/numpy/create.c py/objarray.c py/objstr.c -msgid "wrong number of arguments" -msgstr "" - -#: py/runtime.c -msgid "wrong number of values to unpack" -msgstr "" - -#: extmod/ulab/code/numpy/vector.c -msgid "wrong output type" -msgstr "" - -#: extmod/ulab/code/scipy/signal/signal.c -msgid "zi must be an ndarray" -msgstr "" - -#: extmod/ulab/code/scipy/signal/signal.c -msgid "zi must be of float type" -msgstr "" - -#: extmod/ulab/code/scipy/signal/signal.c -msgid "zi must be of shape (n_section, 2)" -msgstr "" - -#~ msgid "" -#~ "\n" -#~ "Code done running. Waiting for reload.\n" -#~ msgstr "" -#~ "\n" -#~ "Captin's orders are complete. Holdin' fast fer reload.\n" - -#~ msgid "" -#~ "\n" -#~ "Please file an issue with the contents of your CIRCUITPY drive at \n" -#~ "https://github.com/adafruit/circuitpython/issues\n" -#~ msgstr "" -#~ "\n" -#~ "Yar, there is a hole in the keel. Let the cap'n know at\n" -#~ "https://github.com/adafruit/circuitpython/issues\n" - -#~ msgid "All event channels " -#~ msgstr "Avast! All th' event channels " - -#~ msgid "All timers " -#~ msgstr "Heave-to! All th' timers be used" - -#~ msgid "Clock unit " -#~ msgstr "Blimey! Clock unit " - -#~ msgid "DAC already " -#~ msgstr "Blimey! DAC already under sail" - -#~ msgid "Invalid clock pin" -#~ msgstr "Avast! Clock pin be invalid" - -#~ msgid "Invalid pin for left channel" -#~ msgstr "Belay that! Invalid pin for port-side channel" - -#~ msgid "Invalid pin for right channel" -#~ msgstr "Belay that! Invalid pin for starboard-side channel" - -#~ msgid "Pin does not have ADC capabilities" -#~ msgstr "Belay that! Th' Pin be not ADC capable" - -#~ msgid "Running in safe mode! Auto-reload is off.\n" -#~ msgstr "Runnin' in safe mode! Auto-reload be off.\n" - -#~ msgid "bits must be 8" -#~ msgstr "pieces must be of 8" - -#~ msgid "buffers must be the same length" -#~ msgstr "yer buffers must be of the same length" - -#~ msgid "invalid I2C peripheral" -#~ msgstr "Belay that! I2C peripheral be invalid" - -#~ msgid "invalid SPI peripheral" -#~ msgstr "Arr! SPI peripheral be invalid" diff --git a/locale/es.po b/locale/es.po index c4bf81a6256..87589c2c28b 100644 --- a/locale/es.po +++ b/locale/es.po @@ -8,15 +8,15 @@ msgstr "" "Project-Id-Version: \n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2021-01-04 12:55-0600\n" -"PO-Revision-Date: 2025-02-09 17:02+0000\n" -"Last-Translator: karlos g liberal \n" +"PO-Revision-Date: 2026-05-06 18:11+0000\n" +"Last-Translator: Francisco Serrador \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 5.10-dev\n" +"X-Generator: Weblate 5.17.1\n" #: main.c msgid "" @@ -97,7 +97,7 @@ msgstr "" msgid "%q and %q contain duplicate pins" msgstr "%q y %q contienen pines duplicados" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: shared-bindings/audioio/AudioOut.c msgid "%q and %q must be different" msgstr "%q y %q deben ser diferentes" @@ -117,6 +117,10 @@ msgstr "%q contiene pines duplicados" msgid "%q failure: %d" msgstr "%q fallo: %d" +#: shared-module/audiodelays/MultiTapDelay.c +msgid "%q in %q must be of type %q or %q, not %q" +msgstr "%q en %q debe ser de tipo %q o %q, no %q" + #: py/argcheck.c shared-module/audiofilters/Filter.c msgid "%q in %q must be of type %q, not %q" msgstr "%q en %q debe ser del tipo %q, no %q" @@ -169,7 +173,7 @@ msgstr "%q longitud debe ser <= %d" msgid "%q length must be >= %d" msgstr "%q longitud debe ser >= %d" -#: py/modsys.c py/objmodule.c py/runtime.c +#: py/modsys.c py/runtime.c msgid "%q moved from %q to %q" msgstr "%q movido de %q a %q" @@ -230,7 +234,7 @@ msgstr "%q debe ser múltiplo de 8." #: shared-bindings/bitmapfilter/__init__.c shared-bindings/canio/CAN.c #: shared-bindings/digitalio/Pull.c shared-bindings/supervisor/__init__.c #: shared-module/audiofilters/Filter.c shared-module/displayio/__init__.c -#: shared-module/synthio/Biquad.c shared-module/synthio/Synthesizer.c +#: shared-module/synthio/Synthesizer.c msgid "%q must be of type %q or %q, not %q" msgstr "%q debe ser del tipo %q o %q, y no %q" @@ -239,6 +243,7 @@ msgid "%q must be of type %q, %q, or %q, not %q" msgstr "%q debe ser de tipo %q, %q, o %q, no %q" #: py/argcheck.c py/runtime.c shared-bindings/bitmapfilter/__init__.c +#: shared-module/audiodelays/MultiTapDelay.c shared-module/synthio/Note.c #: shared-module/synthio/__init__.c msgid "%q must be of type %q, not %q" msgstr "%q debe ser del tipo %q, y no %q" @@ -319,7 +324,7 @@ msgid "'%q' object does not support '%q'" msgstr "objeto '%q' no tiene capacidad '%q'" #: py/runtime.c -msgid "'%q' object is not an iterator" +msgid "'%q' object isn't an iterator" msgstr "objeto '%q' no es un iterador" #: py/objtype.c py/runtime.c shared-module/atexit/__init__.c @@ -327,7 +332,7 @@ msgid "'%q' object is not callable" msgstr "objeto '%q' no es llamable" #: py/runtime.c -msgid "'%q' object is not iterable" +msgid "'%q' object isn't iterable" msgstr "objeto '%q' no es iterable" #: py/emitinlinethumb.c py/emitinlinextensa.c @@ -611,6 +616,7 @@ msgstr "Valores del array deben ser bytes individuales." #: ports/atmel-samd/common-hal/spitarget/SPITarget.c msgid "Async SPI transfer in progress on this bus, keep awaiting." msgstr "" +"Transferencia SPI asíncrona en curso en este canal, manténgase esperando." #: shared-module/memorymonitor/AllocationAlarm.c #, c-format @@ -813,8 +819,8 @@ msgid "Cannot record to a file" msgstr "No se puede grabar en un archivo" #: shared-module/storage/__init__.c -msgid "Cannot remount '/' when visible via USB." -msgstr "No se puede remountar '/' cuanto se es visible vía USB." +msgid "Cannot remount path when visible via USB." +msgstr "No se puede volver a montar path mientras es visible a través de USB." #: shared-bindings/digitalio/DigitalInOut.c msgid "Cannot set value when direction is input." @@ -831,7 +837,7 @@ msgstr "No se puede manejar la partición en una subclase" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "Cannot use GPIO0..15 together with GPIO32..47" -msgstr "" +msgstr "No se puede utilizar GPIO0..15 junto con GPIO32..47" #: ports/nordic/common-hal/alarm/pin/PinAlarm.c msgid "Cannot wake on pin edge, only level" @@ -869,6 +875,10 @@ msgstr "Las matrices de coordenadas tienen diferentes longitudes" msgid "Coordinate arrays types have different sizes" msgstr "Las matrices de coordenadas tienen diferentes tamaños" +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "Could not publish to ROS topic" +msgstr "No se pudo publicar al tema ROS" + #: shared-bindings/_bleio/Adapter.c msgid "Could not set address" msgstr "No se puede definir la dirección" @@ -881,6 +891,11 @@ msgstr "No se pudo iniciar la interrupción, RX ocupado" msgid "Couldn't allocate decoder" msgstr "No se pudo encontrar el decodificador" +#: ports/espressif/common-hal/rclcpy/__init__.c +#, c-format +msgid "Critical ROS failure during soft reboot, reset required: %d" +msgstr "Fallo ROS critico durante reinicio suave, se requiere reiniciar: %d" + #: ports/stm/common-hal/analogio/AnalogOut.c msgid "DAC Channel Init Error" msgstr "Error de inicio del canal DAC" @@ -1049,7 +1064,7 @@ msgstr "Error al crear canales continuos: no encontrado" #: ports/espressif/common-hal/audioio/AudioOut.c msgid "Failed to enable continuous" -msgstr "" +msgstr "Ha fallado al habilitar continuo" #: shared-module/audiomp3/MP3Decoder.c msgid "Failed to parse MP3 file" @@ -1066,7 +1081,7 @@ msgstr "No se puede liberar el mutex, err 0x%04x" #: ports/zephyr-cp/common-hal/wifi/Radio.c msgid "Failed to set hostname" -msgstr "" +msgstr "Fallo al establecer el nombre de host" #: ports/espressif/common-hal/audioio/AudioOut.c msgid "Failed to start async audio" @@ -1080,6 +1095,7 @@ msgstr "Error al escribir el flash interno." msgid "File exists" msgstr "El archivo ya existe" +#: shared-bindings/supervisor/__init__.c shared-module/lvfontio/OnDiskFont.c #: shared-module/os/getenv.c msgid "File not found" msgstr "Archivo no encontrado" @@ -1114,7 +1130,7 @@ msgstr "" "Para espacios de colores RGB, el bitmap de entrada debe tener 16 bits por " "pixel" -#: ports/cxd56/common-hal/camera/Camera.c +#: ports/cxd56/common-hal/camera/Camera.c shared-module/audiocore/WaveFile.c msgid "Format not supported" msgstr "Sin capacidades para el formato" @@ -1287,7 +1303,9 @@ msgstr "Interrumpido por resultado de función" #: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c py/argcheck.c #: shared-bindings/digitalio/DigitalInOut.c #: shared-bindings/epaperdisplay/EPaperDisplay.c shared-bindings/pwmio/PWMOut.c +#: shared-bindings/supervisor/__init__.c #: shared-module/aurora_epaper/aurora_framebuffer.c +#: shared-module/lvfontio/OnDiskFont.c msgid "Invalid %q" msgstr "%q inválido" @@ -1320,6 +1338,10 @@ msgstr "BSSID inválido" msgid "Invalid MAC address" msgstr "Dirección MAC inválida" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "Invalid ROS domain ID" +msgstr "ID de dominio ROS invalido" + #: ports/espressif/common-hal/espidf/__init__.c py/moderrno.c msgid "Invalid argument" msgstr "Argumento inválido" @@ -1410,6 +1432,11 @@ msgstr "La dirección MAC es incorrecta" msgid "MITM security not supported" msgstr "Seguridad MITM no compatible" +#: ports/stm/common-hal/sdioio/SDCard.c +#, c-format +msgid "MMC/SDIO Clock Error %x" +msgstr "Error de Reloj MMC/SDIO %x" + #: shared-bindings/is31fl3741/IS31FL3741.c msgid "Mapping must be a tuple" msgstr "El mapping debe ser una dupla" @@ -1596,6 +1623,10 @@ msgstr "No se encontró pull up en SDA or SCL; verifique su cableado" msgid "No pulldown on pin; 1Mohm recommended" msgstr "No hay pulldown en el pin; 1Mohm recomendado" +#: shared-module/touchio/TouchIn.c +msgid "No pullup on pin; 1Mohm recommended" +msgstr "Sin pullup en el pin; 1Mohm recomendado" + #: py/moderrno.c msgid "No space left on device" msgstr "No queda espacio en el dispositivo" @@ -1772,6 +1803,7 @@ msgstr "Segmento del PWM canal A ya esta en uso" #: shared-bindings/spitarget/SPITarget.c msgid "Packet buffers for an SPI transfer must have the same length." msgstr "" +"Búferes de paquetes para transferencia SPI deben de ser de igual longitud." #: shared-module/jpegio/JpegDecoder.c msgid "Parameter error" @@ -1877,6 +1909,10 @@ msgstr "El tamaño del programa no es correcto" msgid "Program too long" msgstr "El programa es demasiado grande" +#: shared-bindings/rclcpy/Publisher.c +msgid "Publishers can only be created from a parent node" +msgstr "Las publicadores solo pueden ser creadas desde un nodo antecesor" + #: shared-bindings/digitalio/DigitalInOut.c msgid "Pull not used when direction is output." msgstr "Pull no se usa cuando la dirección es output." @@ -1897,6 +1933,26 @@ msgstr "Error de desinicialización de RNG" msgid "RNG Init Error" msgstr "Error de inicialización de RNG" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS failed to initialize. Is agent connected?" +msgstr "Fallo al inicializar ROS, El agente esta conectado?" + +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS internal setup failure" +msgstr "Fallo interno de instalación ROS" + +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS memory allocator failure" +msgstr "Fallo de asignación de memoria ROS" + +#: ports/espressif/common-hal/rclcpy/Node.c +msgid "ROS node failed to initialize" +msgstr "Fallo al inicializar nodo ROS" + +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "ROS topic failed to initialize" +msgstr "Fallo al inicializar Tema ROS" + #: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c #: ports/nordic/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c msgid "RS485" @@ -2029,6 +2085,7 @@ msgstr "Slice y value tienen tamaños diferentes." #: shared-bindings/displayio/TileGrid.c #: shared-bindings/memorymonitor/AllocationSize.c #: shared-bindings/pulseio/PulseIn.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c msgid "Slices not supported" msgstr "Rebanadas no soportadas" @@ -2099,7 +2156,9 @@ msgstr "" msgid "Tile height must exactly divide bitmap height" msgstr "La altura del Tile debe dividir exacto la altura del bitmap" -#: shared-bindings/displayio/TileGrid.c shared-module/displayio/TileGrid.c +#: shared-bindings/displayio/TileGrid.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-module/displayio/TileGrid.c msgid "Tile index out of bounds" msgstr "Índice de mosaico fuera de límites" @@ -2107,6 +2166,10 @@ msgstr "Índice de mosaico fuera de límites" msgid "Tile width must exactly divide bitmap width" msgstr "Ancho del Tile debe dividir exactamente el ancho de mapa de bits" +#: shared-module/tilepalettemapper/TilePaletteMapper.c +msgid "TilePaletteMapper may only be bound to a TileGrid once" +msgstr "TilePaletteMapper solo puede vincularse una vez a un TileGrid" + #: shared-bindings/alarm/time/TimeAlarm.c msgid "Time is in the past." msgstr "Tiempo suministrado esta en el pasado." @@ -2340,10 +2403,6 @@ msgstr "Espacio de color no sportado" msgid "Unsupported display bus type" msgstr "Sin capacidad de bus tipo display" -#: shared-module/audiocore/WaveFile.c -msgid "Unsupported format" -msgstr "Formato no soportado" - #: shared-bindings/hashlib/__init__.c msgid "Unsupported hash algorithm" msgstr "Algoritmo hash no soportado" @@ -2406,9 +2465,11 @@ msgstr "" msgid "Wi-Fi: " msgstr "Wi-Fi: " +#: ports/espressif/common-hal/wifi/Radio.c #: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "Wifi is not enabled" -msgstr "Wifi no esta activado" +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "WiFi is not enabled" +msgstr "WiFi no está habilitado" #: main.c msgid "Woken up by alarm.\n" @@ -2643,9 +2704,16 @@ msgstr "los tamaños de los bitmap deben coincidir" msgid "bits must be 32 or less" msgstr "los bits deben ser 32 o menos" -#: shared-bindings/audiodelays/Echo.c shared-bindings/audiodelays/PitchShift.c +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "bits_per_sample must be 16" +msgstr "bits_per_sample debe ser 16" + +#: shared-bindings/audiodelays/Chorus.c shared-bindings/audiodelays/Echo.c +#: shared-bindings/audiodelays/MultiTapDelay.c +#: shared-bindings/audiodelays/PitchShift.c #: shared-bindings/audiofilters/Distortion.c -#: shared-bindings/audiofilters/Filter.c shared-bindings/audiomixer/Mixer.c +#: shared-bindings/audiofilters/Filter.c shared-bindings/audiofilters/Phaser.c +#: shared-bindings/audiomixer/Mixer.c msgid "bits_per_sample must be 8 or 16" msgstr "bits_per_sample debe ser 8 ó 16" @@ -3192,7 +3260,7 @@ msgid "format" msgstr "formato" #: py/objstr.c -msgid "format requires a dict" +msgid "format needs a dict" msgstr "format requiere un dict" #: py/objdeque.c @@ -3655,7 +3723,7 @@ msgid "must use keyword argument for key function" msgstr "debe utilizar argumento de palabra clave para la función clave" #: py/runtime.c -msgid "name '%q' is not defined" +msgid "name '%q' isn't defined" msgstr "name '%q' no esta definido" #: py/runtime.c @@ -4074,6 +4142,10 @@ msgstr "argumento enrolado tiene que ser un ndarray" msgid "rsplit(None,n)" msgstr "rsplit(None,n)" +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "samples_signed must be true" +msgstr "samples_signed debe ser true" + #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c #: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "sampling rate out of range" @@ -4294,11 +4366,11 @@ msgid "tx and rx cannot both be None" msgstr "ambos tx y rx no pueden ser None" #: py/objtype.c -msgid "type '%q' is not an acceptable base type" +msgid "type '%q' isn't an acceptable base type" msgstr "type '%q' no es un tipo de base aceptable" #: py/objtype.c -msgid "type is not an acceptable base type" +msgid "type isn't an acceptable base type" msgstr "type no es un tipo de base aceptable" #: py/runtime.c @@ -4360,7 +4432,9 @@ msgstr "no coteja '%c' en formato" msgid "unreadable attribute" msgstr "atributo no legible" -#: shared-bindings/displayio/TileGrid.c shared-bindings/vectorio/VectorShape.c +#: shared-bindings/displayio/TileGrid.c shared-bindings/terminalio/Terminal.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-bindings/vectorio/VectorShape.c msgid "unsupported %q type" msgstr "tipo de %q no soportado" @@ -4440,12 +4514,6 @@ msgstr "los pesos deben ser un tipo de objetos %q, %q, %q, or %q, y no %q. " msgid "width must be greater than zero" msgstr "el ancho debe ser mayor que cero" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/raspberrypi/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "wifi is not enabled" -msgstr "wifi no esta habilitado" - #: ports/raspberrypi/common-hal/wifi/Monitor.c msgid "wifi.Monitor not available" msgstr "wifi.Monitor no esta disponible" @@ -4508,6 +4576,18 @@ msgstr "zi debe ser de tipo flotante" msgid "zi must be of shape (n_section, 2)" msgstr "zi debe ser una forma (n_section,2)" +#~ msgid "Unsupported format" +#~ msgstr "Formato no soportado" + +#~ msgid "Wifi is not enabled" +#~ msgstr "Wifi no esta activado" + +#~ msgid "wifi is not enabled" +#~ msgstr "wifi no esta habilitado" + +#~ msgid "Cannot remount '/' when visible via USB." +#~ msgstr "No se puede remountar '/' cuanto se es visible vía USB." + #~ msgid "%q must be a %q object, %q, or %q" #~ msgstr "%q tiene que ser un %q objeto, %q, o %q" @@ -4851,13 +4931,13 @@ msgstr "zi debe ser una forma (n_section,2)" #~ msgid "'%s' object does not support item deletion" #~ msgstr "objeto '%s' no soporta la eliminación de elementos" -#~ msgid "'%s' object is not an iterator" +#~ msgid "'%s' object isn't an iterator" #~ msgstr "objeto '%s' no es un iterator" #~ msgid "'%s' object is not callable" #~ msgstr "objeto '%s' no puede ser llamado" -#~ msgid "'%s' object is not iterable" +#~ msgid "'%s' object isn't iterable" #~ msgstr "objeto '%s' no es iterable" #~ msgid "'%s' object is not subscriptable" @@ -4875,7 +4955,7 @@ msgstr "zi debe ser una forma (n_section,2)" #~ msgid "'continue' outside loop" #~ msgstr "'continue' fuera de un bucle" -#~ msgid "'coroutine' object is not an iterator" +#~ msgid "'coroutine' object isn't an iterator" #~ msgstr "el objeto 'coroutine' no es un iterador" #~ msgid "64 bit types" @@ -6335,7 +6415,7 @@ msgstr "zi debe ser una forma (n_section,2)" #~ msgid "frequency can only be either 80Mhz or 160MHz" #~ msgstr "la frecuencia solo puede ser 80MHz ó 160MHz" -#~ msgid "function does not take keyword arguments" +#~ msgid "function doesn't take keyword arguments" #~ msgstr "la función no tiene argumentos por palabra clave" #~ msgid "function is implemented for scalars and ndarrays only" @@ -6459,7 +6539,7 @@ msgstr "zi debe ser una forma (n_section,2)" #~ msgid "name must be a string" #~ msgstr "name debe de ser un string" -#~ msgid "name reused for argument" +#~ msgid "argument name reused" #~ msgstr "name reusado para argumento" #~ msgid "no available NIC" diff --git a/locale/fil.po b/locale/fil.po index f95557569a1..27d949a0615 100644 --- a/locale/fil.po +++ b/locale/fil.po @@ -6,8 +6,8 @@ msgstr "" "Project-Id-Version: \n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2021-01-04 12:55-0600\n" -"PO-Revision-Date: 2024-10-06 01:15+0000\n" -"Last-Translator: Diamond Rivero \n" +"PO-Revision-Date: 2025-06-30 16:01+0000\n" +"Last-Translator: MAE \n" "Language-Team: fil\n" "Language: fil\n" "MIME-Version: 1.0\n" @@ -15,7 +15,7 @@ msgstr "" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=2; plural=n != 1 && n != 2 && n != 3 && (n % 10 == 4 " "|| n % 10 == 6 || n % 10 == 9);\n" -"X-Generator: Weblate 5.8-dev\n" +"X-Generator: Weblate 5.13-dev\n" #: main.c msgid "" @@ -85,7 +85,7 @@ msgstr "" msgid "%q and %q contain duplicate pins" msgstr "" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: shared-bindings/audioio/AudioOut.c msgid "%q and %q must be different" msgstr "" @@ -105,6 +105,10 @@ msgstr "" msgid "%q failure: %d" msgstr "" +#: shared-module/audiodelays/MultiTapDelay.c +msgid "%q in %q must be of type %q or %q, not %q" +msgstr "" + #: py/argcheck.c shared-module/audiofilters/Filter.c msgid "%q in %q must be of type %q, not %q" msgstr "" @@ -157,7 +161,7 @@ msgstr "" msgid "%q length must be >= %d" msgstr "" -#: py/modsys.c py/objmodule.c py/runtime.c +#: py/modsys.c py/runtime.c msgid "%q moved from %q to %q" msgstr "" @@ -218,7 +222,7 @@ msgstr "" #: shared-bindings/bitmapfilter/__init__.c shared-bindings/canio/CAN.c #: shared-bindings/digitalio/Pull.c shared-bindings/supervisor/__init__.c #: shared-module/audiofilters/Filter.c shared-module/displayio/__init__.c -#: shared-module/synthio/Biquad.c shared-module/synthio/Synthesizer.c +#: shared-module/synthio/Synthesizer.c msgid "%q must be of type %q or %q, not %q" msgstr "" @@ -227,6 +231,7 @@ msgid "%q must be of type %q, %q, or %q, not %q" msgstr "" #: py/argcheck.c py/runtime.c shared-bindings/bitmapfilter/__init__.c +#: shared-module/audiodelays/MultiTapDelay.c shared-module/synthio/Note.c #: shared-module/synthio/__init__.c msgid "%q must be of type %q, not %q" msgstr "" @@ -308,7 +313,7 @@ msgid "'%q' object does not support '%q'" msgstr "" #: py/runtime.c -msgid "'%q' object is not an iterator" +msgid "'%q' object isn't an iterator" msgstr "" #: py/objtype.c py/runtime.c shared-module/atexit/__init__.c @@ -316,7 +321,7 @@ msgid "'%q' object is not callable" msgstr "" #: py/runtime.c -msgid "'%q' object is not iterable" +msgid "'%q' object isn't iterable" msgstr "" #: py/emitinlinethumb.c py/emitinlinextensa.c @@ -467,9 +472,9 @@ msgid "AP could not be started" msgstr "" #: shared-bindings/_bleio/Address.c shared-bindings/ipaddress/IPv4Address.c -#, fuzzy, c-format +#, c-format msgid "Address must be %d bytes long" -msgstr "ang palette ay dapat 32 bytes ang haba" +msgstr "Dapat na %d bytes ang haba ng address" #: ports/espressif/common-hal/memorymap/AddressRange.c #: ports/nordic/common-hal/memorymap/AddressRange.c @@ -707,14 +712,13 @@ msgstr "" #: ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c #: ports/nordic/common-hal/paralleldisplaybus/ParallelBus.c #: ports/raspberrypi/common-hal/paralleldisplaybus/ParallelBus.c -#, fuzzy, c-format +#, c-format msgid "Bus pin %d is already in use" -msgstr "Ginagamit na ang DAC" +msgstr "Ginagamit na ang bus pin %d" #: shared-bindings/_bleio/UUID.c -#, fuzzy msgid "Byte buffer must be 16 bytes." -msgstr "buffer ay dapat bytes-like object" +msgstr "Ang byte buffer ay dapat na 16 byte." #: shared-bindings/aesio/aes.c msgid "CBC blocks must be multiples of 16 bytes" @@ -798,7 +802,7 @@ msgid "Cannot record to a file" msgstr "Hindi ma-record sa isang file" #: shared-module/storage/__init__.c -msgid "Cannot remount '/' when visible via USB." +msgid "Cannot remount path when visible via USB." msgstr "" #: shared-bindings/digitalio/DigitalInOut.c @@ -852,6 +856,10 @@ msgstr "" msgid "Coordinate arrays types have different sizes" msgstr "" +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "Could not publish to ROS topic" +msgstr "" + #: shared-bindings/_bleio/Adapter.c msgid "Could not set address" msgstr "" @@ -864,6 +872,11 @@ msgstr "" msgid "Couldn't allocate decoder" msgstr "" +#: ports/espressif/common-hal/rclcpy/__init__.c +#, c-format +msgid "Critical ROS failure during soft reboot, reset required: %d" +msgstr "" + #: ports/stm/common-hal/analogio/AnalogOut.c msgid "DAC Channel Init Error" msgstr "" @@ -976,9 +989,9 @@ msgid "Failed sending command." msgstr "" #: ports/nordic/sd_mutex.c -#, fuzzy, c-format +#, c-format msgid "Failed to acquire mutex, err 0x%04x" -msgstr "Nabigo sa pag kuha ng mutex, status: 0x%08lX" +msgstr "Nabigong makuha ang mutex, err 0x%04x" #: ports/raspberrypi/common-hal/mdns/Server.c msgid "Failed to add service TXT record" @@ -1043,9 +1056,9 @@ msgid "Failed to register continuous events callback" msgstr "" #: ports/nordic/sd_mutex.c -#, fuzzy, c-format +#, c-format msgid "Failed to release mutex, err 0x%04x" -msgstr "Nabigo sa pagrelease ng mutex, status: 0x%08lX" +msgstr "Nabigong ilabas ang mutex, err 0x%04x" #: ports/zephyr-cp/common-hal/wifi/Radio.c msgid "Failed to set hostname" @@ -1063,6 +1076,7 @@ msgstr "" msgid "File exists" msgstr "Mayroong file" +#: shared-bindings/supervisor/__init__.c shared-module/lvfontio/OnDiskFont.c #: shared-module/os/getenv.c msgid "File not found" msgstr "" @@ -1094,7 +1108,7 @@ msgstr "" msgid "For RGB colorspaces, input bitmap must have 16 bits per pixel" msgstr "" -#: ports/cxd56/common-hal/camera/Camera.c +#: ports/cxd56/common-hal/camera/Camera.c shared-module/audiocore/WaveFile.c msgid "Format not supported" msgstr "" @@ -1258,7 +1272,9 @@ msgstr "" #: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c py/argcheck.c #: shared-bindings/digitalio/DigitalInOut.c #: shared-bindings/epaperdisplay/EPaperDisplay.c shared-bindings/pwmio/PWMOut.c +#: shared-bindings/supervisor/__init__.c #: shared-module/aurora_epaper/aurora_framebuffer.c +#: shared-module/lvfontio/OnDiskFont.c msgid "Invalid %q" msgstr "" @@ -1291,6 +1307,10 @@ msgstr "" msgid "Invalid MAC address" msgstr "" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "Invalid ROS domain ID" +msgstr "" + #: ports/espressif/common-hal/espidf/__init__.c py/moderrno.c msgid "Invalid argument" msgstr "Maling argumento" @@ -1380,6 +1400,11 @@ msgstr "" msgid "MITM security not supported" msgstr "" +#: ports/stm/common-hal/sdioio/SDCard.c +#, c-format +msgid "MMC/SDIO Clock Error %x" +msgstr "" + #: shared-bindings/is31fl3741/IS31FL3741.c msgid "Mapping must be a tuple" msgstr "" @@ -1566,6 +1591,10 @@ msgstr "" msgid "No pulldown on pin; 1Mohm recommended" msgstr "" +#: shared-module/touchio/TouchIn.c +msgid "No pullup on pin; 1Mohm recommended" +msgstr "" + #: py/moderrno.c msgid "No space left on device" msgstr "" @@ -1841,6 +1870,10 @@ msgstr "" msgid "Program too long" msgstr "" +#: shared-bindings/rclcpy/Publisher.c +msgid "Publishers can only be created from a parent node" +msgstr "" + #: shared-bindings/digitalio/DigitalInOut.c msgid "Pull not used when direction is output." msgstr "Pull hindi ginagamit kapag ang direksyon ay output." @@ -1861,6 +1894,26 @@ msgstr "Error sa RNG DeInit" msgid "RNG Init Error" msgstr "Error sa RNG Init" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS failed to initialize. Is agent connected?" +msgstr "" + +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS internal setup failure" +msgstr "" + +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS memory allocator failure" +msgstr "" + +#: ports/espressif/common-hal/rclcpy/Node.c +msgid "ROS node failed to initialize" +msgstr "" + +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "ROS topic failed to initialize" +msgstr "" + #: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c #: ports/nordic/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c msgid "RS485" @@ -1992,6 +2045,7 @@ msgstr "Slice at value ay iba iba ang haba." #: shared-bindings/displayio/TileGrid.c #: shared-bindings/memorymonitor/AllocationSize.c #: shared-bindings/pulseio/PulseIn.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c msgid "Slices not supported" msgstr "Hindi suportado ang Slices" @@ -2059,7 +2113,9 @@ msgstr "" msgid "Tile height must exactly divide bitmap height" msgstr "" -#: shared-bindings/displayio/TileGrid.c shared-module/displayio/TileGrid.c +#: shared-bindings/displayio/TileGrid.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-module/displayio/TileGrid.c msgid "Tile index out of bounds" msgstr "" @@ -2067,6 +2123,10 @@ msgstr "" msgid "Tile width must exactly divide bitmap width" msgstr "" +#: shared-module/tilepalettemapper/TilePaletteMapper.c +msgid "TilePaletteMapper may only be bound to a TileGrid once" +msgstr "" + #: shared-bindings/alarm/time/TimeAlarm.c msgid "Time is in the past." msgstr "" @@ -2295,10 +2355,6 @@ msgstr "" msgid "Unsupported display bus type" msgstr "Hindi supportadong tipo ng bitmap" -#: shared-module/audiocore/WaveFile.c -msgid "Unsupported format" -msgstr "Hindi supportadong format" - #: shared-bindings/hashlib/__init__.c msgid "Unsupported hash algorithm" msgstr "" @@ -2353,10 +2409,12 @@ msgstr "" #: supervisor/shared/web_workflow/web_workflow.c msgid "Wi-Fi: " -msgstr "" +msgstr "Wi-Fi: " +#: ports/espressif/common-hal/wifi/Radio.c #: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "Wifi is not enabled" +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "WiFi is not enabled" msgstr "" #: main.c @@ -2592,9 +2650,16 @@ msgstr "" msgid "bits must be 32 or less" msgstr "" -#: shared-bindings/audiodelays/Echo.c shared-bindings/audiodelays/PitchShift.c +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "bits_per_sample must be 16" +msgstr "" + +#: shared-bindings/audiodelays/Chorus.c shared-bindings/audiodelays/Echo.c +#: shared-bindings/audiodelays/MultiTapDelay.c +#: shared-bindings/audiodelays/PitchShift.c #: shared-bindings/audiofilters/Distortion.c -#: shared-bindings/audiofilters/Filter.c shared-bindings/audiomixer/Mixer.c +#: shared-bindings/audiofilters/Filter.c shared-bindings/audiofilters/Phaser.c +#: shared-bindings/audiomixer/Mixer.c msgid "bits_per_sample must be 8 or 16" msgstr "bits_per_sample ay dapat 8 o 16" @@ -2689,7 +2754,7 @@ msgstr "hindi ma-convert %s sa complex" #: py/obj.c #, c-format msgid "can't convert %s to float" -msgstr "hindi ma-convert %s sa int" +msgstr "hindi ma-convert %s sa float" #: py/objint.c py/runtime.c #, c-format @@ -2840,7 +2905,7 @@ msgstr "" #: py/emitnative.c msgid "casting" -msgstr "casting" +msgstr "paghahagis" #: ports/stm/common-hal/pwmio/PWMOut.c msgid "channel re-init" @@ -3144,7 +3209,7 @@ msgid "format" msgstr "" #: py/objstr.c -msgid "format requires a dict" +msgid "format needs a dict" msgstr "kailangan ng format ng dict" #: py/objdeque.c @@ -3606,7 +3671,7 @@ msgid "must use keyword argument for key function" msgstr "dapat gumamit ng keyword argument para sa key function" #: py/runtime.c -msgid "name '%q' is not defined" +msgid "name '%q' isn't defined" msgstr "name '%q' ay hindi defined" #: py/runtime.c @@ -3987,7 +4052,7 @@ msgstr "" #: py/builtinimport.c msgid "relative import" -msgstr "relative import" +msgstr "kamag-anak na import" #: py/obj.c #, c-format @@ -4024,6 +4089,10 @@ msgstr "" msgid "rsplit(None,n)" msgstr "rsplit(None,n)" +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "samples_signed must be true" +msgstr "" + #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c #: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "sampling rate out of range" @@ -4075,7 +4144,7 @@ msgstr "" #: py/objint.c py/sequence.c msgid "small int overflow" -msgstr "small int overflow" +msgstr "maliit na int overflow" #: main.c msgid "soft reboot\n" @@ -4243,11 +4312,11 @@ msgid "tx and rx cannot both be None" msgstr "tx at rx hindi pwedeng parehas na None" #: py/objtype.c -msgid "type '%q' is not an acceptable base type" +msgid "type '%q' isn't an acceptable base type" msgstr "hindi maari ang type na '%q' para sa base type" #: py/objtype.c -msgid "type is not an acceptable base type" +msgid "type isn't an acceptable base type" msgstr "hindi puede ang type para sa base type" #: py/runtime.c @@ -4309,7 +4378,9 @@ msgstr "" msgid "unreadable attribute" msgstr "hindi mabasa ang attribute" -#: shared-bindings/displayio/TileGrid.c shared-bindings/vectorio/VectorShape.c +#: shared-bindings/displayio/TileGrid.c shared-bindings/terminalio/Terminal.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-bindings/vectorio/VectorShape.c msgid "unsupported %q type" msgstr "Hindi supportadong tipo ng %q" @@ -4387,12 +4458,6 @@ msgstr "" msgid "width must be greater than zero" msgstr "" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/raspberrypi/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "wifi is not enabled" -msgstr "" - #: ports/raspberrypi/common-hal/wifi/Monitor.c msgid "wifi.Monitor not available" msgstr "" @@ -4455,6 +4520,9 @@ msgstr "" msgid "zi must be of shape (n_section, 2)" msgstr "" +#~ msgid "Unsupported format" +#~ msgstr "Hindi supportadong format" + #~ msgid "Data chunk must follow fmt chunk" #~ msgstr "Dapat sunurin ng Data chunk ang fmt chunk" @@ -4564,13 +4632,13 @@ msgstr "" #~ msgid "'%s' object does not support item deletion" #~ msgstr "'%s' object ay hindi sumusuporta sa pagtanggal ng item" -#~ msgid "'%s' object is not an iterator" +#~ msgid "'%s' object isn't an iterator" #~ msgstr "'%s' object ay hindi iterator" #~ msgid "'%s' object is not callable" #~ msgstr "'%s' object hindi matatawag" -#~ msgid "'%s' object is not iterable" +#~ msgid "'%s' object isn't iterable" #~ msgstr "'%s' object ay hindi ma i-iterable" #~ msgid "'%s' object is not subscriptable" @@ -5241,7 +5309,7 @@ msgstr "" #~ msgid "frequency can only be either 80Mhz or 160MHz" #~ msgstr "ang frequency ay dapat 80Mhz or 160MHz lamang" -#~ msgid "function does not take keyword arguments" +#~ msgid "function doesn't take keyword arguments" #~ msgstr "ang function ay hindi kumukuha ng mga argumento ng keyword" #~ msgid "impossible baudrate" @@ -5311,7 +5379,7 @@ msgstr "" #~ msgid "name must be a string" #~ msgstr "ang keywords dapat strings" -#~ msgid "name reused for argument" +#~ msgid "argument name reused" #~ msgstr "name muling ginamit para sa argument" #~ msgid "no available NIC" diff --git a/locale/fr.po b/locale/fr.po index 6016af04146..f871c669f93 100644 --- a/locale/fr.po +++ b/locale/fr.po @@ -8,15 +8,15 @@ 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: 2025-02-19 11:46+0000\n" -"Last-Translator: Noel Gaetan \n" +"PO-Revision-Date: 2025-08-03 08:01+0000\n" +"Last-Translator: MAE \n" "Language-Team: \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 5.10.1-dev\n" +"X-Generator: Weblate 5.13-dev\n" #: main.c msgid "" @@ -49,7 +49,7 @@ msgid "" "Press reset to exit safe mode.\n" msgstr "" "\n" -"Pour quitter le mode sans échec, appuyez sur reset.\n" +"Appuyer sur reset pour sortir du mode sans échec.\n" #: supervisor/shared/safe_mode.c msgid "" @@ -57,7 +57,7 @@ msgid "" "You are in safe mode because:\n" msgstr "" "\n" -"Le mode sans échec est actif , car:\n" +"Le mode sans échec est actif pour cette raison:\n" #: py/obj.c msgid " File \"%q\"" @@ -96,7 +96,7 @@ msgstr "" msgid "%q and %q contain duplicate pins" msgstr "%q et %q contiennent des broches en double" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: shared-bindings/audioio/AudioOut.c msgid "%q and %q must be different" msgstr "%q et %q doivent être différents" @@ -116,6 +116,10 @@ msgstr "%q contient des broches en double" msgid "%q failure: %d" msgstr "Échec de %q : %d" +#: shared-module/audiodelays/MultiTapDelay.c +msgid "%q in %q must be of type %q or %q, not %q" +msgstr "%q dans %q doit être du type %q ou %q, pas %q" + #: py/argcheck.c shared-module/audiofilters/Filter.c msgid "%q in %q must be of type %q, not %q" msgstr "%q dans %q doit être de type %q, pas %q" @@ -168,7 +172,7 @@ msgstr "La longueur de %q doit être <= %d" msgid "%q length must be >= %d" msgstr "La longueur de %q doit être >= %d" -#: py/modsys.c py/objmodule.c py/runtime.c +#: py/modsys.c py/runtime.c msgid "%q moved from %q to %q" msgstr "% déplacé de %q à %q" @@ -229,7 +233,7 @@ msgstr "%q doit être un multiple de 8." #: shared-bindings/bitmapfilter/__init__.c shared-bindings/canio/CAN.c #: shared-bindings/digitalio/Pull.c shared-bindings/supervisor/__init__.c #: shared-module/audiofilters/Filter.c shared-module/displayio/__init__.c -#: shared-module/synthio/Biquad.c shared-module/synthio/Synthesizer.c +#: shared-module/synthio/Synthesizer.c msgid "%q must be of type %q or %q, not %q" msgstr "%q doit être de type %q ou %q, pas %q" @@ -238,6 +242,7 @@ msgid "%q must be of type %q, %q, or %q, not %q" msgstr "%q doit être de type %q, %q ou %q, pas %q" #: py/argcheck.c py/runtime.c shared-bindings/bitmapfilter/__init__.c +#: shared-module/audiodelays/MultiTapDelay.c shared-module/synthio/Note.c #: shared-module/synthio/__init__.c msgid "%q must be of type %q, not %q" msgstr "%q doit être de type %q, pas %q" @@ -320,7 +325,7 @@ msgid "'%q' object does not support '%q'" msgstr "l'objet '%q' ne supporte pas '%q'" #: py/runtime.c -msgid "'%q' object is not an iterator" +msgid "'%q' object isn't an iterator" msgstr "l'objet '%q' n'est pas un itérateur" #: py/objtype.c py/runtime.c shared-module/atexit/__init__.c @@ -328,7 +333,7 @@ msgid "'%q' object is not callable" msgstr "l'objet '%q' ne peut pas être appelé" #: py/runtime.c -msgid "'%q' object is not iterable" +msgid "'%q' object isn't iterable" msgstr "l'objet '%q' n'est pas itérable" #: py/emitinlinethumb.c py/emitinlinextensa.c @@ -817,10 +822,9 @@ msgid "Cannot record to a file" msgstr "Impossible d'enregistrer vers un fichier" #: shared-module/storage/__init__.c -msgid "Cannot remount '/' when visible via USB." +msgid "Cannot remount path when visible via USB." msgstr "" -"Ne peut démonter '/' la racine du système de fichier quand elle est déja vue " -"par le port USB." +"Impossible de remonter le chemin d'accès lorsqu'il est visible via USB." #: shared-bindings/digitalio/DigitalInOut.c msgid "Cannot set value when direction is input." @@ -877,6 +881,10 @@ msgstr "Les tableaux de coordonnées sont de longueur différentes" msgid "Coordinate arrays types have different sizes" msgstr "Les types des tableaux de coordonnées sont de longueur différentes" +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "Could not publish to ROS topic" +msgstr "Ne peut publier sur le Topic ROS" + #: shared-bindings/_bleio/Adapter.c msgid "Could not set address" msgstr "Ne peux définir l'adresse" @@ -889,6 +897,11 @@ msgstr "Ne peux lancer l'interruption, RX occupé" msgid "Couldn't allocate decoder" msgstr "Ne peux allouer le décodeur" +#: ports/espressif/common-hal/rclcpy/__init__.c +#, c-format +msgid "Critical ROS failure during soft reboot, reset required: %d" +msgstr "Erreur critique lors du reboot à chaud, reset requis: %d" + #: ports/stm/common-hal/analogio/AnalogOut.c msgid "DAC Channel Init Error" msgstr "Erreur init du canal DAC" @@ -1076,7 +1089,7 @@ msgstr "Écchec de liberaton du mutex, err 0x%04x" #: ports/zephyr-cp/common-hal/wifi/Radio.c msgid "Failed to set hostname" -msgstr "" +msgstr "hostname impossible à initialiser" #: ports/espressif/common-hal/audioio/AudioOut.c msgid "Failed to start async audio" @@ -1090,6 +1103,7 @@ msgstr "Échec de l'écriture vers flash interne." msgid "File exists" msgstr "Le fichier existe" +#: shared-bindings/supervisor/__init__.c shared-module/lvfontio/OnDiskFont.c #: shared-module/os/getenv.c msgid "File not found" msgstr "Fichier non trouvé" @@ -1123,7 +1137,7 @@ msgid "For RGB colorspaces, input bitmap must have 16 bits per pixel" msgstr "" "Pour l'espace de couleur RVB, l'image d'entrée doit avoir 16 bits par pixel" -#: ports/cxd56/common-hal/camera/Camera.c +#: ports/cxd56/common-hal/camera/Camera.c shared-module/audiocore/WaveFile.c msgid "Format not supported" msgstr "Format non supporté" @@ -1293,7 +1307,9 @@ msgstr "Interrompu par la fonction de sortie" #: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c py/argcheck.c #: shared-bindings/digitalio/DigitalInOut.c #: shared-bindings/epaperdisplay/EPaperDisplay.c shared-bindings/pwmio/PWMOut.c +#: shared-bindings/supervisor/__init__.c #: shared-module/aurora_epaper/aurora_framebuffer.c +#: shared-module/lvfontio/OnDiskFont.c msgid "Invalid %q" msgstr "%q invalide" @@ -1326,6 +1342,10 @@ msgstr "BSSID invalide" msgid "Invalid MAC address" msgstr "Adresse MAC invalide" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "Invalid ROS domain ID" +msgstr "ROS domain ID invalide" + #: ports/espressif/common-hal/espidf/__init__.c py/moderrno.c msgid "Invalid argument" msgstr "Paramètre invalide" @@ -1415,6 +1435,11 @@ msgstr "MAC Address invalide" msgid "MITM security not supported" msgstr "Sécurité MITM n'est pas supportée" +#: ports/stm/common-hal/sdioio/SDCard.c +#, c-format +msgid "MMC/SDIO Clock Error %x" +msgstr "Erreur d'horloge MMC/SDIO %x" + #: shared-bindings/is31fl3741/IS31FL3741.c msgid "Mapping must be a tuple" msgstr "Le mapping doit être un tuple" @@ -1609,6 +1634,10 @@ msgstr "Aucun pull up trouvé sur SDA ou SCL; vérifiez votre câblage" msgid "No pulldown on pin; 1Mohm recommended" msgstr "Pas de pulldown sur la broche ; 1Mohm requis" +#: shared-module/touchio/TouchIn.c +msgid "No pullup on pin; 1Mohm recommended" +msgstr "Pas de pullup sur la broche ; 1Mohm recommandé" + #: py/moderrno.c msgid "No space left on device" msgstr "Plus d'espace libre sur le dispositif" @@ -1826,8 +1855,7 @@ msgid "" "constructor" msgstr "" "Le brochage utilise %d octets par élément, ce qui dépasse le seuil de %d " -"octets. Si cela est inévitable, passez allow_inefficient=True au " -"constructeur." +"octets. Si cela est inévitable, passez allow_inefficient=True au constructeur" #: ports/raspberrypi/common-hal/imagecapture/ParallelImageCapture.c msgid "Pins must be sequential" @@ -1851,15 +1879,15 @@ msgstr "Plus tout autres modules présents sur le système de fichiers\n" #: shared-module/vectorio/Polygon.c msgid "Polygon needs at least 3 points" -msgstr "Polygon a besoin d'au moins 3 points" +msgstr "Un polygone a besoin d'au moins 3 points" #: supervisor/shared/safe_mode.c msgid "Power dipped. Make sure you are providing enough power." -msgstr "Chute de puissance.Apportez plus d'énergie." +msgstr "Chute de puissance. Assurez-vous de fournir assez de puissance." #: shared-bindings/_bleio/Adapter.c msgid "Prefix buffer must be on the heap" -msgstr "Le tampon de préfixe doit être sur la pile" +msgstr "Le tampon de préfixe doit être sur le tas" #: main.c msgid "Press any key to enter the REPL. Use CTRL-D to reload.\n" @@ -1889,9 +1917,14 @@ msgstr "Taille du programme invalide" msgid "Program too long" msgstr "Programme trop long" +#: shared-bindings/rclcpy/Publisher.c +msgid "Publishers can only be created from a parent node" +msgstr "Les Publishers ne peuvent être créés qu'à partir du nœud parent" + #: shared-bindings/digitalio/DigitalInOut.c msgid "Pull not used when direction is output." -msgstr "Le tirage 'pull' n'est pas utilisé quand la direction est 'output'." +msgstr "" +"L'attribut \"pull\" n'est pas utilisé quand la direction est \"output\"." #: ports/raspberrypi/common-hal/countio/Counter.c msgid "RISE_AND_FALL not available on this chip" @@ -1909,6 +1942,26 @@ msgstr "Erreur de désinitialisation du RNG" msgid "RNG Init Error" msgstr "Erreur d'initialisation du RNG" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS failed to initialize. Is agent connected?" +msgstr "L'agent est-il connecté? ROS échoue son initialisation" + +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS internal setup failure" +msgstr "ROS échec de configuration interne" + +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS memory allocator failure" +msgstr "Erreur d'allocation mémoire ROS" + +#: ports/espressif/common-hal/rclcpy/Node.c +msgid "ROS node failed to initialize" +msgstr "ROS node échoue a s'initialiser" + +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "ROS topic failed to initialize" +msgstr "Le topic ROS échoue à s'initialiser" + #: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c #: ports/nordic/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c msgid "RS485" @@ -1972,7 +2025,7 @@ msgstr "Format correct mais non supporté" #: main.c msgid "Running in safe mode! Not running saved code.\n" -msgstr "Mode sans- échec ! Le code sauvegardé n'est pas éxecuté.\n" +msgstr "Mode sans échec ! Le code sauvegardé n'est pas éxecuté.\n" #: shared-module/sdcardio/SDCard.c msgid "SD card CSD format not supported" @@ -2040,6 +2093,7 @@ msgstr "Tranche et valeur de tailles différentes." #: shared-bindings/displayio/TileGrid.c #: shared-bindings/memorymonitor/AllocationSize.c #: shared-bindings/pulseio/PulseIn.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c msgid "Slices not supported" msgstr "Tranches non supportées" @@ -2110,7 +2164,9 @@ msgstr "" msgid "Tile height must exactly divide bitmap height" msgstr "La hauteur de la tuile doit diviser exactement la hauteur de l'image" -#: shared-bindings/displayio/TileGrid.c shared-module/displayio/TileGrid.c +#: shared-bindings/displayio/TileGrid.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-module/displayio/TileGrid.c msgid "Tile index out of bounds" msgstr "Index des tuiles hors limites" @@ -2118,6 +2174,10 @@ msgstr "Index des tuiles hors limites" msgid "Tile width must exactly divide bitmap width" msgstr "La largeur de la tuile doit diviser exactement la largeur de l'image" +#: shared-module/tilepalettemapper/TilePaletteMapper.c +msgid "TilePaletteMapper may only be bound to a TileGrid once" +msgstr "TilePaletteMapper ne peut être lié à un TileGrid qu'une seule fois" + #: shared-bindings/alarm/time/TimeAlarm.c msgid "Time is in the past." msgstr "L'heure est dans le passé." @@ -2352,10 +2412,6 @@ msgstr "Espace de couleur non supporté" msgid "Unsupported display bus type" msgstr "Type de bus d'affichage non supporté" -#: shared-module/audiocore/WaveFile.c -msgid "Unsupported format" -msgstr "Format non pris en charge" - #: shared-bindings/hashlib/__init__.c msgid "Unsupported hash algorithm" msgstr "Algorithme de hachage non supporté" @@ -2417,8 +2473,10 @@ msgstr "" msgid "Wi-Fi: " msgstr "Wi-Fi : " +#: ports/espressif/common-hal/wifi/Radio.c #: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "Wifi is not enabled" +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "WiFi is not enabled" msgstr "Le WiFi n'est pas activé" #: main.c @@ -2655,11 +2713,18 @@ msgstr "les tailles des images doivent correspondre" msgid "bits must be 32 or less" msgstr "les bits doivent être 32 ou moins" -#: shared-bindings/audiodelays/Echo.c shared-bindings/audiodelays/PitchShift.c +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "bits_per_sample must be 16" +msgstr "bits_per_sample doit être de 16" + +#: shared-bindings/audiodelays/Chorus.c shared-bindings/audiodelays/Echo.c +#: shared-bindings/audiodelays/MultiTapDelay.c +#: shared-bindings/audiodelays/PitchShift.c #: shared-bindings/audiofilters/Distortion.c -#: shared-bindings/audiofilters/Filter.c shared-bindings/audiomixer/Mixer.c +#: shared-bindings/audiofilters/Filter.c shared-bindings/audiofilters/Phaser.c +#: shared-bindings/audiomixer/Mixer.c msgid "bits_per_sample must be 8 or 16" -msgstr "'bits_per_sample' doivent être 8 ou 16" +msgstr "bits_per_sample doivent être 8 ou 16" #: py/emitinlinethumb.c msgid "branch not in range" @@ -3211,7 +3276,7 @@ msgid "format" msgstr "format" #: py/objstr.c -msgid "format requires a dict" +msgid "format needs a dict" msgstr "le format requier un dict" #: py/objdeque.c @@ -3676,7 +3741,7 @@ msgid "must use keyword argument for key function" msgstr "doit utiliser un argument nommé pour une fonction key" #: py/runtime.c -msgid "name '%q' is not defined" +msgid "name '%q' isn't defined" msgstr "nom '%q' non défini" #: py/runtime.c @@ -3907,7 +3972,7 @@ msgstr "seules les tranches avec 'step=1' (cad None) sont supportées" #: py/vm.c msgid "opcode" -msgstr "opcode" +msgstr "" #: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/bitwise.c #: extmod/ulab/code/numpy/compare.c extmod/ulab/code/numpy/vector.c @@ -4097,6 +4162,10 @@ msgstr "paramêtre roll doit être un ndarray" msgid "rsplit(None,n)" msgstr "rsplit(None, n)" +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "samples_signed must be true" +msgstr "samples_signed doit être vrai" + #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c #: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "sampling rate out of range" @@ -4316,11 +4385,11 @@ msgid "tx and rx cannot both be None" msgstr "tx et rx ne peuvent être 'None' tous les deux" #: py/objtype.c -msgid "type '%q' is not an acceptable base type" +msgid "type '%q' isn't an acceptable base type" msgstr "le type '%q' n'est pas un type de base accepté" #: py/objtype.c -msgid "type is not an acceptable base type" +msgid "type isn't an acceptable base type" msgstr "le type n'est pas un type de base accepté" #: py/runtime.c @@ -4382,7 +4451,9 @@ msgstr "'%c' sans correspondance dans le format" msgid "unreadable attribute" msgstr "attribut illisible" -#: shared-bindings/displayio/TileGrid.c shared-bindings/vectorio/VectorShape.c +#: shared-bindings/displayio/TileGrid.c shared-bindings/terminalio/Terminal.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-bindings/vectorio/VectorShape.c msgid "unsupported %q type" msgstr "type %q non pris on charge" @@ -4462,12 +4533,6 @@ msgstr "le poids requier un objet de type %q, %q, %q ou %q, pas %q. " msgid "width must be greater than zero" msgstr "width doit être plus grand que zero" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/raspberrypi/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "wifi is not enabled" -msgstr "le WiFi est inactif" - #: ports/raspberrypi/common-hal/wifi/Monitor.c msgid "wifi.Monitor not available" msgstr "wifi.Monitor indisponible" @@ -4530,6 +4595,20 @@ msgstr "zi doit être de type float" msgid "zi must be of shape (n_section, 2)" msgstr "zi doit être de forme (n_section, 2)" +#~ msgid "Unsupported format" +#~ msgstr "Format non pris en charge" + +#~ msgid "Wifi is not enabled" +#~ msgstr "Le WiFi n'est pas activé" + +#~ msgid "wifi is not enabled" +#~ msgstr "le WiFi est inactif" + +#~ msgid "Cannot remount '/' when visible via USB." +#~ msgstr "" +#~ "Ne peut démonter '/' la racine du système de fichier quand elle est déja " +#~ "vue par le port USB." + #~ msgid "%q must be a %q object, %q, or %q" #~ msgstr "%q doit être un objet %q, %q ou %q" @@ -4879,13 +4958,13 @@ msgstr "zi doit être de forme (n_section, 2)" #~ msgid "'%s' object does not support item deletion" #~ msgstr "l'objet '%s' ne supporte pas la suppression d'éléments" -#~ msgid "'%s' object is not an iterator" +#~ msgid "'%s' object isn't an iterator" #~ msgstr "l'objet '%s' n'est pas un itérateur" #~ msgid "'%s' object is not callable" #~ msgstr "l'objet '%s' n'est pas appelable" -#~ msgid "'%s' object is not iterable" +#~ msgid "'%s' object isn't iterable" #~ msgstr "l'objet '%s' n'est pas itérable" #~ msgid "'%s' object is not subscriptable" @@ -4903,7 +4982,7 @@ msgstr "zi doit être de forme (n_section, 2)" #~ msgid "'continue' outside loop" #~ msgstr "'continue' dehors d'une boucle" -#~ msgid "'coroutine' object is not an iterator" +#~ msgid "'coroutine' object isn't an iterator" #~ msgstr "L'objet \"coroutine\" n'est pas un itérateur" #~ msgid "(x,y) integers required" @@ -6392,7 +6471,7 @@ msgstr "zi doit être de forme (n_section, 2)" #~ msgid "frequency is read-only for this board" #~ msgstr "la fréquence est en lecture seule pour cette carte" -#~ msgid "function does not take keyword arguments" +#~ msgid "function doesn't take keyword arguments" #~ msgstr "la fonction ne prend pas d'arguments nommés" #~ msgid "function is implemented for scalars and ndarrays only" @@ -6521,7 +6600,7 @@ msgstr "zi doit être de forme (n_section, 2)" #~ msgid "name must be a string" #~ msgstr "les noms doivent être des chaînes de caractère" -#~ msgid "name reused for argument" +#~ msgid "argument name reused" #~ msgstr "nom réutilisé comme paramètre" #~ msgid "no available NIC" diff --git a/locale/hi.po b/locale/hi.po index 90eeabf91b9..f8fc76621fe 100644 --- a/locale/hi.po +++ b/locale/hi.po @@ -8,1060 +8,1649 @@ 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: 2023-11-16 15:03+0000\n" -"Last-Translator: Anonymous \n" +"PO-Revision-Date: 2025-06-29 13:02+0000\n" +"Last-Translator: MAE \n" "Language-Team: none\n" "Language: hi\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 5.2\n" +"X-Generator: Weblate 5.13-dev\n" -#: main.c -msgid "" -"\n" -"Code done running.\n" +#: extmod/modasyncio.c extmod/modheapq.c +msgid "empty heap" msgstr "" -#: main.c -msgid "" -"\n" -"Code stopped by auto-reload. Reloading soon.\n" +#: extmod/modasyncio.c +msgid "can't cancel self" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "" -"\n" -"Please file an issue with your program at github.com/adafruit/circuitpython/" -"issues." +#: extmod/modasyncio.c +msgid "can't wait" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "" -"\n" -"Press reset to exit safe mode.\n" +#: extmod/modbinascii.c extmod/modhashlib.c py/objarray.c +msgid "a bytes-like object is required" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "" -"\n" -"You are in safe mode because:\n" +#: extmod/modbinascii.c +msgid "incorrect padding" msgstr "" -#: py/obj.c -msgid " File \"%q\"" +#: extmod/moddeflate.c +msgid "format" msgstr "" -#: py/obj.c -msgid " File \"%q\", line %d" +#: extmod/moddeflate.c +msgid "wbits" msgstr "" -#: py/builtinhelp.c -msgid " is of type %q\n" +#: extmod/modhashlib.c +msgid "hash is final" msgstr "" -#: main.c -msgid " not found.\n" +#: extmod/modheapq.c +msgid "heap must be a list" msgstr "" -#: main.c -msgid " output:\n" +#: extmod/modjson.c +msgid "syntax error in JSON" msgstr "" -#: py/objstr.c -#, c-format -msgid "%%c requires int or char" +#: extmod/modrandom.c +msgid "bits must be 32 or less" msgstr "" -#: shared-bindings/rgbmatrix/RGBMatrix.c -#, c-format -msgid "" -"%d address pins, %d rgb pins and %d tiles indicate a height of %d, not %d" +#: extmod/modrandom.c extmod/ulab/code/numpy/random/random.c +msgid "no default seed" msgstr "" -#: shared-bindings/microcontroller/Pin.c -msgid "%q and %q contain duplicate pins" +#: extmod/modre.c +msgid "splitting with sub-captures" msgstr "" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c -msgid "%q and %q must be different" +#: extmod/modre.c +msgid "regex too complex" msgstr "" -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -msgid "%q and %q must share a clock unit" +#: extmod/modre.c +msgid "Error in regex" msgstr "" -#: ports/nordic/common-hal/watchdog/WatchDogTimer.c -msgid "%q cannot be changed once mode is set to %q" +#: extmod/modtime.c +msgid "mktime needs a tuple of length 8 or 9" msgstr "" -#: shared-bindings/microcontroller/Pin.c -msgid "%q contains duplicate pins" +#: extmod/modtime.c +msgid "ticks interval overflow" msgstr "" -#: ports/atmel-samd/common-hal/sdioio/SDCard.c -msgid "%q failure: %d" +#: extmod/modzlib.c +msgid "compression header" msgstr "" -#: py/argcheck.c shared-module/audiofilters/Filter.c -msgid "%q in %q must be of type %q, not %q" +#: extmod/ulab/code/ndarray.c +msgid "data type not understood" msgstr "" -#: ports/espressif/common-hal/espulp/ULP.c -#: ports/mimxrt10xx/common-hal/audiobusio/__init__.c -#: ports/mimxrt10xx/common-hal/usb_host/Port.c -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -#: ports/raspberrypi/common-hal/usb_host/Port.c -#: shared-bindings/digitalio/DigitalInOut.c -#: shared-bindings/microcontroller/Pin.c shared-module/max3421e/Max3421E.c -msgid "%q in use" +#: extmod/ulab/code/ndarray.c +msgid "array is too big" msgstr "" -#: py/objstr.c -msgid "%q index out of range" +#: extmod/ulab/code/ndarray.c +msgid "ndarray length overflows" msgstr "" -#: py/obj.c -msgid "%q indices must be integers, not %s" +#: extmod/ulab/code/ndarray.c +msgid "maximum number of dimensions is " msgstr "" -#: shared-module/bitbangio/SPI.c -msgid "%q init failed" +#: extmod/ulab/code/ndarray.c +msgid "cannot convert complex type" msgstr "" -#: ports/espressif/bindings/espnow/Peer.c shared-bindings/dualbank/__init__.c -msgid "%q is %q" +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/create.c +msgid "too many dimensions" msgstr "" -#: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "%q is read-only for this board" +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/transform.c +msgid "index is out of bounds" msgstr "" -#: py/argcheck.c shared-bindings/usb_hid/Device.c -msgid "%q length must be %d" +#: extmod/ulab/code/ndarray.c +msgid "indices must be integers, slices, or Boolean lists" msgstr "" -#: py/argcheck.c -msgid "%q length must be %d-%d" +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/bitwise.c +#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/numpy/vector.c +msgid "operands could not be broadcast together" msgstr "" -#: py/argcheck.c -msgid "%q length must be <= %d" +#: extmod/ulab/code/ndarray.c +msgid "array and index length must be equal" msgstr "" -#: py/argcheck.c -msgid "%q length must be >= %d" +#: extmod/ulab/code/ndarray.c +msgid "cannot convert complex to dtype" msgstr "" -#: py/modsys.c py/objmodule.c py/runtime.c -msgid "%q moved from %q to %q" +#: extmod/ulab/code/ndarray.c +msgid "operation is implemented for 1D Boolean arrays only" msgstr "" -#: py/argcheck.c -msgid "%q must be %d" +#: extmod/ulab/code/ndarray.c +msgid "too many indices" msgstr "" -#: py/argcheck.c shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/displayio/Bitmap.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -#: shared-bindings/is31fl3741/FrameBuffer.c -#: shared-bindings/rgbmatrix/RGBMatrix.c -msgid "%q must be %d-%d" +#: extmod/ulab/code/ndarray.c +msgid "cannot delete array elements" msgstr "" -#: shared-bindings/busdisplay/BusDisplay.c -msgid "%q must be 1 when %q is True" +#: extmod/ulab/code/ndarray.c +msgid "flattening order must be either 'C', or 'F'" msgstr "" -#: py/argcheck.c shared-bindings/gifio/GifWriter.c -#: shared-module/gifio/OnDiskGif.c -msgid "%q must be <= %d" +#: extmod/ulab/code/ndarray.c +msgid "tobytes can be invoked for dense arrays only" msgstr "" -#: ports/espressif/common-hal/watchdog/WatchDogTimer.c -msgid "%q must be <= %u" +#: extmod/ulab/code/ndarray.c +msgid "operation is not supported for given type" msgstr "" -#: py/argcheck.c -msgid "%q must be >= %d" +#: extmod/ulab/code/ndarray.c +msgid "keyword argument must be tuple of integers" msgstr "" -#: shared-bindings/analogbufio/BufferedIn.c -msgid "%q must be a bytearray or array of type 'H' or 'B'" +#: extmod/ulab/code/ndarray.c +msgid "too many axes specified" msgstr "" -#: shared-bindings/audiocore/RawSample.c -msgid "%q must be a bytearray or array of type 'h', 'H', 'b', or 'B'" +#: extmod/ulab/code/ndarray.c +msgid "axis index out of bounds" msgstr "" -#: shared-bindings/warnings/__init__.c -msgid "%q must be a subclass of %q" +#: extmod/ulab/code/ndarray.c +msgid "repeated indices" msgstr "" -#: ports/espressif/common-hal/analogbufio/BufferedIn.c -msgid "%q must be array of type 'H'" +#: extmod/ulab/code/ndarray.c +msgid "shape must be integer or tuple of integers" msgstr "" -#: shared-module/synthio/__init__.c -msgid "%q must be array of type 'h'" +#: extmod/ulab/code/ndarray.c +msgid "can only specify one unknown dimension" msgstr "" -#: shared-bindings/audiobusio/PDMIn.c -msgid "%q must be multiple of 8." +#: extmod/ulab/code/ndarray.c +msgid "cannot reshape array" msgstr "" -#: ports/raspberrypi/bindings/cyw43/__init__.c py/argcheck.c py/objexcept.c -#: shared-bindings/bitmapfilter/__init__.c shared-bindings/canio/CAN.c -#: shared-bindings/digitalio/Pull.c shared-bindings/supervisor/__init__.c -#: shared-module/audiofilters/Filter.c shared-module/displayio/__init__.c -#: shared-module/synthio/Biquad.c shared-module/synthio/Synthesizer.c -msgid "%q must be of type %q or %q, not %q" +#: extmod/ulab/code/ndarray.c +msgid "cannot assign new shape" msgstr "" -#: shared-bindings/jpegio/JpegDecoder.c -msgid "%q must be of type %q, %q, or %q, not %q" +#: extmod/ulab/code/ndarray.c +msgid "function is defined for ndarrays only" msgstr "" -#: py/argcheck.c py/runtime.c shared-bindings/bitmapfilter/__init__.c -#: shared-module/synthio/__init__.c -msgid "%q must be of type %q, not %q" +#: extmod/ulab/code/ndarray_operators.c +msgid "operation not supported for the input types" msgstr "" -#: ports/atmel-samd/common-hal/busio/UART.c -msgid "%q must be power of 2" +#: extmod/ulab/code/ndarray_operators.c +msgid "dtype of int32 is not supported" msgstr "" -#: shared-bindings/wifi/Monitor.c -msgid "%q out of bounds" +#: extmod/ulab/code/ndarray_operators.c +msgid "cannot cast output with casting rule" msgstr "" -#: ports/atmel-samd/common-hal/pulseio/PulseIn.c -#: ports/cxd56/common-hal/pulseio/PulseIn.c -#: ports/nordic/common-hal/pulseio/PulseIn.c -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -#: ports/stm/common-hal/pulseio/PulseIn.c py/argcheck.c -#: shared-bindings/canio/Match.c shared-bindings/time/__init__.c -msgid "%q out of range" +#: extmod/ulab/code/ndarray_operators.c +msgid "results cannot be cast to specified type" msgstr "" -#: py/objmodule.c py/runtime.c -msgid "%q renamed %q" +#: extmod/ulab/code/numpy/approx.c +msgid "interp is defined for 1D iterables of equal length" msgstr "" -#: py/objrange.c py/objslice.c shared-bindings/random/__init__.c -msgid "%q step cannot be zero" +#: extmod/ulab/code/numpy/approx.c +msgid "trapz is defined for 1D iterables" msgstr "" -#: shared-module/bitbangio/I2C.c -msgid "%q too long" +#: extmod/ulab/code/numpy/approx.c +msgid "trapz is defined for 1D arrays of equal length" msgstr "" -#: py/bc.c py/objnamedtuple.c -msgid "%q() takes %d positional arguments but %d were given" +#: extmod/ulab/code/numpy/bitwise.c +msgid "not supported for input types" msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "%q() without %q()" +#: extmod/ulab/code/numpy/carray/carray.c +msgid "function is implemented for ndarrays only" msgstr "" -#: shared-bindings/usb_hid/Device.c -msgid "%q, %q, and %q must all be the same length" +#: extmod/ulab/code/numpy/carray/carray.c +msgid "input must be an ndarray, or a scalar" msgstr "" -#: py/objint.c shared-bindings/_bleio/Connection.c -#: shared-bindings/storage/__init__.c -msgid "%q=%q" +#: extmod/ulab/code/numpy/carray/carray.c +msgid "input must be a 1D ndarray" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "%q[%u] shifts in more bits than pin count" +#: extmod/ulab/code/numpy/carray/carray_tools.c +msgid "not implemented for complex dtype" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "%q[%u] shifts out more bits than pin count" +#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/user/user.c +#: shared-bindings/_eve/__init__.c +msgid "input must be an ndarray" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "%q[%u] uses extra pin" +#: extmod/ulab/code/numpy/compare.c +msgid "object too deep for desired array" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "%q[%u] waits on input outside of count" +#: extmod/ulab/code/numpy/compare.c +msgid "cannot cast array data from dtype" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -#, c-format -msgid "%s error 0x%x" +#: extmod/ulab/code/numpy/compare.c +msgid "minlength must not be negative" msgstr "" -#: py/argcheck.c -msgid "'%q' argument required" +#: extmod/ulab/code/numpy/compare.c +msgid "the weights and list don't have the same length" msgstr "" -#: py/proto.c -msgid "'%q' object does not support '%q'" +#: extmod/ulab/code/numpy/compare.c +msgid "cannot cast weigths to float" msgstr "" -#: py/runtime.c -msgid "'%q' object is not an iterator" -msgstr "" - -#: py/objtype.c py/runtime.c shared-module/atexit/__init__.c -msgid "'%q' object is not callable" +#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/numpy/create.c +#: extmod/ulab/code/numpy/io/io.c extmod/ulab/code/numpy/transform.c +#: extmod/ulab/code/numpy/vector.c +msgid "wrong input type" msgstr "" -#: py/runtime.c -msgid "'%q' object is not iterable" +#: extmod/ulab/code/numpy/create.c +msgid "input argument must be an integer, a tuple, or a list" msgstr "" -#: py/emitinlinethumb.c py/emitinlinextensa.c -#, c-format -msgid "'%s' expects a label" +#: extmod/ulab/code/numpy/create.c py/objarray.c py/objstr.c +msgid "wrong number of arguments" msgstr "" -#: py/emitinlinethumb.c py/emitinlinextensa.c -#, c-format -msgid "'%s' expects a register" +#: extmod/ulab/code/numpy/create.c py/objint_longlong.c py/objint_mpz.c +msgid "divide by zero" msgstr "" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects a special register" +#: extmod/ulab/code/numpy/create.c +msgid "arange: cannot compute length" msgstr "" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects an FPU register" +#: extmod/ulab/code/numpy/create.c +msgid "first argument must be a tuple of ndarrays" msgstr "" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects an address of the form [a, b]" +#: extmod/ulab/code/numpy/create.c +msgid "only ndarrays can be concatenated" msgstr "" -#: py/emitinlinethumb.c py/emitinlinextensa.c -#, c-format -msgid "'%s' expects an integer" +#: extmod/ulab/code/numpy/create.c +msgid "wrong axis specified" msgstr "" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects at most r%d" +#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c +msgid "input arrays are not compatible" msgstr "" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects {r0, r1, ...}" +#: extmod/ulab/code/numpy/create.c +msgid "input must be 1- or 2-d" msgstr "" -#: py/emitinlinextensa.c -#, c-format -msgid "'%s' integer %d isn't within range %d..%d" +#: extmod/ulab/code/numpy/create.c +msgid "number of points must be at least 2" msgstr "" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' integer 0x%x doesn't fit in mask 0x%x" +#: extmod/ulab/code/numpy/create.c +msgid "indexing should be 'xy' or 'ij'" msgstr "" -#: py/obj.c -#, c-format -msgid "'%s' object doesn't support item assignment" +#: extmod/ulab/code/numpy/create.c +msgid "indexing must be 'xy' or 'ij'" msgstr "" -#: py/obj.c -#, c-format -msgid "'%s' object doesn't support item deletion" +#: extmod/ulab/code/numpy/create.c +msgid "too many input arrays" msgstr "" -#: py/runtime.c -msgid "'%s' object has no attribute '%q'" +#: extmod/ulab/code/numpy/create.c extmod/ulab/code/numpy/numerical.c +#: extmod/ulab/code/numpy/transform.c +msgid "arguments must be ndarrays" msgstr "" -#: py/obj.c -#, c-format -msgid "'%s' object isn't subscriptable" +#: extmod/ulab/code/numpy/create.c +msgid "arguments must be 1D arrays" msgstr "" -#: py/objstr.c -msgid "'=' alignment not allowed in string format specifier" +#: extmod/ulab/code/numpy/create.c +msgid "input is not an array" msgstr "" -#: shared-module/struct/__init__.c -msgid "'S' and 'O' are not supported format types" +#: extmod/ulab/code/numpy/create.c extmod/ulab/code/numpy/numerical.c +#: ports/espressif/common-hal/pulseio/PulseIn.c +#: shared-bindings/bitmaptools/__init__.c +msgid "index out of range" msgstr "" -#: py/compile.c -msgid "'align' requires 1 argument" +#: extmod/ulab/code/numpy/create.c +msgid "mode should be raise, wrap or clip" msgstr "" -#: py/compile.c -msgid "'await' outside function" +#: extmod/ulab/code/numpy/create.c +msgid "index must not be negative" msgstr "" -#: py/compile.c -msgid "'break'/'continue' outside loop" +#: extmod/ulab/code/numpy/create.c +msgid "offset must be non-negative and no greater than buffer length" msgstr "" -#: py/compile.c -msgid "'data' requires at least 2 arguments" +#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c +msgid "buffer size must be a multiple of element size" msgstr "" -#: py/compile.c -msgid "'data' requires integer arguments" +#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c +msgid "buffer is smaller than requested size" msgstr "" -#: py/compile.c -msgid "'label' requires 1 argument" +#: extmod/ulab/code/numpy/fft/fft_tools.c +msgid "FFT is defined for ndarrays only" msgstr "" -#: py/emitnative.c -msgid "'not' not implemented" +#: extmod/ulab/code/numpy/fft/fft_tools.c +msgid "FFT is implemented for linear arrays only" msgstr "" -#: py/compile.c -msgid "'return' outside function" +#: extmod/ulab/code/numpy/fft/fft_tools.c extmod/ulab/code/utils/utils.c +msgid "input array length must be power of 2" msgstr "" -#: py/compile.c -msgid "'yield from' inside async function" +#: extmod/ulab/code/numpy/fft/fft_tools.c +msgid "real and imaginary parts must be of equal length" msgstr "" -#: py/compile.c -msgid "'yield' outside function" +#: extmod/ulab/code/numpy/filter.c +msgid "convolve arguments must be ndarrays" msgstr "" -#: py/compile.c -msgid "* arg after **" +#: extmod/ulab/code/numpy/filter.c +msgid "convolve arguments must be linear arrays" msgstr "" -#: py/compile.c -msgid "*x must be assignment target" +#: extmod/ulab/code/numpy/filter.c +msgid "convolve arguments must not be empty" msgstr "" -#: py/obj.c -msgid ", in %q\n" +#: extmod/ulab/code/numpy/io/io.c +msgid "corrupted file" msgstr "" -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/epaperdisplay/EPaperDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -msgid ".show(x) removed. Use .root_group = x" +#: extmod/ulab/code/numpy/io/io.c +msgid "wrong dtype" msgstr "" -#: py/objcomplex.c -msgid "0.0 to a complex power" +#: extmod/ulab/code/numpy/io/io.c +msgid "usecols keyword must be specified" msgstr "" -#: py/modbuiltins.c -msgid "3-arg pow() not supported" +#: extmod/ulab/code/numpy/io/io.c +msgid "empty file" msgstr "" -#: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "AP could not be started" +#: extmod/ulab/code/numpy/io/io.c +msgid "usecols is too high" msgstr "" -#: shared-bindings/_bleio/Address.c shared-bindings/ipaddress/IPv4Address.c -#, c-format -msgid "Address must be %d bytes long" +#: extmod/ulab/code/numpy/io/io.c +msgid "array has too many dimensions" msgstr "" -#: ports/espressif/common-hal/memorymap/AddressRange.c -#: ports/nordic/common-hal/memorymap/AddressRange.c -#: ports/raspberrypi/common-hal/memorymap/AddressRange.c -msgid "Address range not allowed" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "input matrix is asymmetric" msgstr "" -#: shared-bindings/memorymap/AddressRange.c -msgid "Address range wraps around" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "matrix is not positive definite" msgstr "" -#: ports/espressif/common-hal/canio/CAN.c -msgid "All CAN peripherals are in use" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "iterations did not converge" msgstr "" -#: ports/espressif/common-hal/busio/I2C.c -#: ports/espressif/common-hal/i2ctarget/I2CTarget.c -#: ports/nordic/common-hal/busio/I2C.c -msgid "All I2C peripherals are in use" +#: extmod/ulab/code/numpy/linalg/linalg.c +#: extmod/ulab/code/scipy/linalg/linalg.c +msgid "input matrix is singular" msgstr "" -#: ports/atmel-samd/common-hal/canio/Listener.c -#: ports/espressif/common-hal/canio/Listener.c -#: ports/stm/common-hal/canio/Listener.c -msgid "All RX FIFOs in use" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "operation is defined for ndarrays only" msgstr "" -#: ports/espressif/common-hal/busio/SPI.c ports/nordic/common-hal/busio/SPI.c -msgid "All SPI peripherals are in use" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "operation is defined for 2D arrays only" msgstr "" -#: ports/espressif/common-hal/busio/UART.c ports/nordic/common-hal/busio/UART.c -msgid "All UART peripherals are in use" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "mode must be complete, or reduced" msgstr "" -#: ports/nordic/common-hal/countio/Counter.c -#: ports/nordic/common-hal/pulseio/PulseIn.c -#: ports/nordic/common-hal/rotaryio/IncrementalEncoder.c -msgid "All channels in use" +#: extmod/ulab/code/numpy/numerical.c +msgid "attempt to get argmin/argmax of an empty sequence" msgstr "" -#: ports/raspberrypi/common-hal/usb_host/Port.c -msgid "All dma channels in use" +#: extmod/ulab/code/numpy/numerical.c +msgid "attempt to get (arg)min/(arg)max of empty sequence" msgstr "" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c -msgid "All event channels in use" +#: extmod/ulab/code/numpy/numerical.c extmod/ulab/code/ulab_tools.c +msgid "axis must be None, or an integer" msgstr "" -#: ports/raspberrypi/common-hal/floppyio/__init__.c -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -#: ports/raspberrypi/common-hal/usb_host/Port.c -msgid "All state machines in use" +#: extmod/ulab/code/numpy/numerical.c +msgid "operation is not implemented on ndarrays" msgstr "" -#: ports/atmel-samd/audio_dma.c -msgid "All sync event channels in use" +#: extmod/ulab/code/numpy/numerical.c +msgid "input must be tuple, list, range, or ndarray" msgstr "" -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c -msgid "All timers for this pin are in use" +#: extmod/ulab/code/numpy/numerical.c +msgid "sort argument must be an ndarray" msgstr "" -#: ports/atmel-samd/common-hal/_pew/PewPew.c -#: ports/atmel-samd/common-hal/audioio/AudioOut.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/nordic/common-hal/audiopwmio/PWMAudioOut.c -#: ports/nordic/common-hal/pulseio/PulseIn.c -#: ports/nordic/peripherals/nrf/timers.c -#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c -msgid "All timers in use" +#: extmod/ulab/code/numpy/numerical.c +msgid "argsort argument must be an ndarray" msgstr "" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Already advertising." +#: extmod/ulab/code/numpy/numerical.c +msgid "argsort is not implemented for flattened arrays" msgstr "" -#: ports/atmel-samd/common-hal/canio/Listener.c -msgid "Already have all-matches listener" +#: extmod/ulab/code/numpy/numerical.c +msgid "axis too long" msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -msgid "Already in progress" +#: extmod/ulab/code/numpy/numerical.c +msgid "cross is defined for 1D arrays of length 3" msgstr "" -#: ports/espressif/bindings/espnow/ESPNow.c -#: ports/espressif/common-hal/espulp/ULP.c -#: shared-module/memorymonitor/AllocationAlarm.c -#: shared-module/memorymonitor/AllocationSize.c -msgid "Already running" +#: extmod/ulab/code/numpy/numerical.c +msgid "diff argument must be an ndarray" msgstr "" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/raspberrypi/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "Already scanning for wifi networks" +#: extmod/ulab/code/numpy/numerical.c +msgid "differentiation order out of range" msgstr "" -#: shared-module/os/getenv.c -#, c-format -msgid "An error occurred while retrieving '%s':\n" +#: extmod/ulab/code/numpy/numerical.c +msgid "flip argument must be an ndarray" msgstr "" -#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c -msgid "Another PWMAudioOut is already active" +#: extmod/ulab/code/numpy/numerical.c +msgid "wrong axis index" msgstr "" -#: ports/atmel-samd/common-hal/pulseio/PulseOut.c -#: ports/cxd56/common-hal/pulseio/PulseOut.c -msgid "Another send is already active" +#: extmod/ulab/code/numpy/numerical.c +msgid "median argument must be an ndarray" msgstr "" -#: shared-bindings/pulseio/PulseOut.c -msgid "Array must contain halfwords (type 'H')" +#: extmod/ulab/code/numpy/numerical.c +msgid "roll argument must be an ndarray" msgstr "" -#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c -#: shared-bindings/nvm/ByteArray.c -msgid "Array values should be single bytes." +#: extmod/ulab/code/numpy/poly.c +msgid "input data must be an iterable" msgstr "" -#: ports/atmel-samd/common-hal/spitarget/SPITarget.c -msgid "Async SPI transfer in progress on this bus, keep awaiting." +#: extmod/ulab/code/numpy/poly.c +msgid "more degrees of freedom than data points" msgstr "" -#: shared-module/memorymonitor/AllocationAlarm.c -#, c-format -msgid "Attempt to allocate %d blocks" +#: extmod/ulab/code/numpy/poly.c +msgid "input vectors must be of equal length" msgstr "" -#: ports/raspberrypi/audio_dma.c -msgid "Audio conversion not implemented" +#: extmod/ulab/code/numpy/poly.c +msgid "could not invert Vandermonde matrix" msgstr "" -#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c -#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c -msgid "Audio source error" +#: extmod/ulab/code/numpy/poly.c +msgid "input is not iterable" msgstr "" -#: shared-bindings/wifi/Radio.c -msgid "AuthMode.OPEN is not used with password" +#: extmod/ulab/code/numpy/random/random.c +msgid "argument must be None, an integer or a tuple of integers" msgstr "" -#: shared-bindings/wifi/Radio.c supervisor/shared/web_workflow/web_workflow.c -msgid "Authentication failure" +#: extmod/ulab/code/numpy/random/random.c +msgid "shape must be None, an integer or a tuple of integers" msgstr "" -#: main.c -msgid "Auto-reload is off.\n" +#: extmod/ulab/code/numpy/random/random.c extmod/ulab/code/ulab_tools.c +msgid "out has wrong type" msgstr "" -#: main.c -msgid "" -"Auto-reload is on. Simply save files over USB to run them or enter REPL to " -"disable.\n" +#: extmod/ulab/code/numpy/random/random.c +msgid "output array has wrong type" msgstr "" -#: ports/espressif/common-hal/canio/CAN.c -msgid "Baudrate not supported by peripheral" +#: extmod/ulab/code/numpy/random/random.c +msgid "size must match out.shape when used together" msgstr "" -#: shared-module/busdisplay/BusDisplay.c -#: shared-module/framebufferio/FramebufferDisplay.c -msgid "Below minimum frame rate" +#: extmod/ulab/code/numpy/random/random.c extmod/ulab/code/ulab_tools.c +msgid "output array must be contiguous" msgstr "" -#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c -msgid "Bit clock and word select must be sequential GPIO pins" +#: extmod/ulab/code/numpy/transform.c +msgid "wrong length of condition array" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "Bitmap size and bits per value must match" +#: extmod/ulab/code/numpy/transform.c extmod/ulab/code/numpy/vector.c +msgid "first argument must be an ndarray" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Boot device must be first (interface #0)." +#: extmod/ulab/code/numpy/transform.c +msgid "wrong index type" msgstr "" -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Both RX and TX required for flow control" +#: extmod/ulab/code/numpy/transform.c +msgid "wrong length of index array" msgstr "" -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -msgid "Brightness not adjustable" +#: extmod/ulab/code/numpy/transform.c +msgid "dimensions do not match" msgstr "" -#: shared-bindings/_bleio/UUID.c -#, c-format -msgid "Buffer + offset too small %d %d %d" +#: extmod/ulab/code/numpy/vector.c extmod/ulab/code/utils/utils.c +msgid "out must be an ndarray" msgstr "" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "Buffer elements must be 4 bytes long or less" +#: extmod/ulab/code/numpy/vector.c +msgid "out must be of float dtype" msgstr "" -#: shared-bindings/framebufferio/FramebufferDisplay.c -msgid "Buffer is not a bytearray." +#: extmod/ulab/code/numpy/vector.c +msgid "input and output dimensions differ" msgstr "" -#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c -#, c-format -msgid "Buffer length %d too big. It must be less than %d" +#: extmod/ulab/code/numpy/vector.c +msgid "input and output shapes differ" msgstr "" -#: ports/atmel-samd/common-hal/sdioio/SDCard.c -#: ports/cxd56/common-hal/sdioio/SDCard.c -#: ports/espressif/common-hal/sdioio/SDCard.c -#: ports/stm/common-hal/sdioio/SDCard.c shared-bindings/floppyio/__init__.c -#: shared-module/sdcardio/SDCard.c -#, c-format -msgid "Buffer must be a multiple of %d bytes" +#: extmod/ulab/code/numpy/vector.c +msgid "out keyword is not supported for function" msgstr "" -#: shared-bindings/_bleio/PacketBuffer.c -#, c-format -msgid "Buffer too short by %d bytes" +#: extmod/ulab/code/numpy/vector.c +msgid "out keyword is not supported for complex dtype" msgstr "" -#: ports/cxd56/common-hal/camera/Camera.c -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -#: shared-bindings/struct/__init__.c shared-module/struct/__init__.c -msgid "Buffer too small" +#: extmod/ulab/code/numpy/vector.c +msgid "dtype must be float, or complex" msgstr "" -#: ports/atmel-samd/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/nordic/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/raspberrypi/common-hal/paralleldisplaybus/ParallelBus.c -#, c-format -msgid "Bus pin %d is already in use" +#: extmod/ulab/code/numpy/vector.c +msgid "can't convert complex to float" msgstr "" -#: shared-bindings/_bleio/UUID.c -msgid "Byte buffer must be 16 bytes." +#: extmod/ulab/code/numpy/vector.c +msgid "input dtype must be float or complex" msgstr "" -#: shared-bindings/aesio/aes.c -msgid "CBC blocks must be multiples of 16 bytes" +#: extmod/ulab/code/numpy/vector.c extmod/ulab/code/scipy/integrate/integrate.c +msgid "first argument must be a callable" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "CIRCUITPY drive could not be found or created." +#: extmod/ulab/code/numpy/vector.c +msgid "wrong output type" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "CRC or checksum was invalid" +#: extmod/ulab/code/scipy/integrate/integrate.c +#, c-format +msgid "can't convert arg %d from %s to float" msgstr "" -#: py/objtype.c -msgid "Call super().__init__() before accessing native object." +#: extmod/ulab/code/scipy/integrate/integrate.c +msgid "levels needs to be a positive integer" msgstr "" -#: ports/cxd56/common-hal/camera/Camera.c -msgid "Camera init" +#: extmod/ulab/code/scipy/integrate/integrate.c +msgid "steps needs to be a positive integer" msgstr "" -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Can only alarm on RTC IO from deep sleep." +#: extmod/ulab/code/scipy/integrate/integrate.c +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "first argument must be a function" msgstr "" -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Can only alarm on one low pin while others alarm high from deep sleep." +#: extmod/ulab/code/scipy/integrate/integrate.c +msgid "order needs to be a positive integer" msgstr "" -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Can only alarm on two low pins from deep sleep." +#: extmod/ulab/code/scipy/linalg/linalg.c +msgid "first two arguments must be ndarrays" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Can't construct AudioOut because continuous channel already open" +#: extmod/ulab/code/scipy/linalg/linalg.c extmod/ulab/code/user/user.c +msgid "input must be a dense ndarray" msgstr "" -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Characteristic.c -msgid "Can't set CCCD on local Characteristic" +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "function has the same sign at the ends of interval" msgstr "" -#: shared-bindings/storage/__init__.c shared-bindings/usb_cdc/__init__.c -#: shared-bindings/usb_hid/__init__.c shared-bindings/usb_midi/__init__.c -#: shared-bindings/usb_video/__init__.c -msgid "Cannot change USB devices now" +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "maxiter should be > 0" msgstr "" -#: shared-bindings/_bleio/Adapter.c -msgid "Cannot create a new Adapter; use _bleio.adapter;" +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "maxiter must be > 0" msgstr "" -#: shared-bindings/displayio/Bitmap.c -#: shared-bindings/memorymonitor/AllocationSize.c -#: shared-bindings/pulseio/PulseIn.c -msgid "Cannot delete values" +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "data must be iterable" msgstr "" -#: ports/atmel-samd/common-hal/digitalio/DigitalInOut.c -#: ports/mimxrt10xx/common-hal/digitalio/DigitalInOut.c -#: ports/nordic/common-hal/digitalio/DigitalInOut.c -#: ports/raspberrypi/common-hal/digitalio/DigitalInOut.c -msgid "Cannot get pull while in output mode" +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "initial values must be iterable" msgstr "" -#: ports/nordic/common-hal/microcontroller/Processor.c -msgid "Cannot get temperature" +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "data must be of equal length" msgstr "" -#: shared-bindings/_bleio/Adapter.c -msgid "Cannot have scan responses for extended, connectable advertisements." +#: extmod/ulab/code/scipy/signal/signal.c +msgid "sosfilt requires iterable arguments" msgstr "" -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Cannot pull on input-only pin." +#: extmod/ulab/code/scipy/signal/signal.c +msgid "input must be one-dimensional" msgstr "" -#: shared-bindings/audiobusio/PDMIn.c -msgid "Cannot record to a file" +#: extmod/ulab/code/scipy/signal/signal.c +msgid "zi must be an ndarray" msgstr "" -#: shared-module/storage/__init__.c -msgid "Cannot remount '/' when visible via USB." +#: extmod/ulab/code/scipy/signal/signal.c +msgid "zi must be of shape (n_section, 2)" msgstr "" -#: shared-bindings/digitalio/DigitalInOut.c -msgid "Cannot set value when direction is input." +#: extmod/ulab/code/scipy/signal/signal.c +msgid "zi must be of float type" msgstr "" -#: ports/espressif/common-hal/busio/UART.c -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Cannot specify RTS or CTS in RS485 mode" +#: extmod/ulab/code/scipy/signal/signal.c +msgid "sos array must be of shape (n_section, 6)" msgstr "" -#: py/objslice.c -msgid "Cannot subclass slice" +#: extmod/ulab/code/scipy/signal/signal.c +msgid "sos[:, 3] should be all ones" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Cannot use GPIO0..15 together with GPIO32..47" +#: extmod/ulab/code/ulab_tools.c +msgid "axis is out of bounds" msgstr "" -#: ports/nordic/common-hal/alarm/pin/PinAlarm.c -msgid "Cannot wake on pin edge, only level" +#: extmod/ulab/code/ulab_tools.c +msgid "size is defined for ndarrays only" msgstr "" -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Cannot wake on pin edge. Only level." +#: extmod/ulab/code/ulab_tools.c +msgid "input must be square matrix" msgstr "" -#: shared-bindings/_bleio/CharacteristicBuffer.c -msgid "CharacteristicBuffer writing not provided" +#: extmod/ulab/code/ulab_tools.c +msgid "out array has wrong dtype" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "CircuitPython core code crashed hard. Whoops!\n" +#: extmod/ulab/code/ulab_tools.c +msgid "out array has wrong dimension" msgstr "" -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -msgid "Clock unit in use" +#: extmod/ulab/code/ulab_tools.c +msgid "out array has wrong shape" msgstr "" -#: shared-bindings/_bleio/Connection.c -msgid "" -"Connection has been disconnected and can no longer be used. Create a new " -"connection." +#: extmod/ulab/code/utils/utils.c +msgid "out must be a float dense array" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "Coordinate arrays have different lengths" +#: extmod/ulab/code/utils/utils.c +msgid "offset is too large" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "Coordinate arrays types have different sizes" +#: extmod/ulab/code/utils/utils.c +msgid "out array is too small" msgstr "" -#: shared-bindings/_bleio/Adapter.c -msgid "Could not set address" +#: extmod/ulab/code/utils/utils.c +msgid "spectrogram is defined for ndarrays only" msgstr "" -#: ports/stm/common-hal/busio/UART.c -msgid "Could not start interrupt, RX busy" +#: extmod/ulab/code/utils/utils.c +msgid "spectrogram is implemented for 1D arrays only" msgstr "" -#: shared-module/audiomp3/MP3Decoder.c -msgid "Couldn't allocate decoder" +#: extmod/ulab/code/utils/utils.c +msgid "out array must be a 1D array of float type" msgstr "" -#: ports/stm/common-hal/analogio/AnalogOut.c -msgid "DAC Channel Init Error" +#: extmod/ulab/code/utils/utils.c +msgid "input and out arrays must have same length" +msgstr "" + +#: extmod/ulab/code/utils/utils.c +msgid "scratchpad must be an ndarray" +msgstr "" + +#: extmod/ulab/code/utils/utils.c +msgid "scratchpad must be a 1D dense float array" +msgstr "" + +#: extmod/ulab/code/utils/utils.c +msgid "scratchpad must be twice as long as input" +msgstr "" + +#: extmod/vfs_fat.c py/moderrno.c +msgid "Read-only filesystem" +msgstr "" + +#: extmod/vfs_posix_file.c py/objstringio.c +msgid "I/O operation on closed file" +msgstr "" + +#: extmod/vfs_posix_file.c +msgid "poll on file not available on win32" +msgstr "" + +#: main.c +msgid "Done" +msgstr "" + +#: main.c +msgid " output:\n" +msgstr "" + +#: main.c +msgid "" +"Auto-reload is on. Simply save files over USB to run them or enter REPL to " +"disable.\n" +msgstr "" + +#: main.c +msgid "Auto-reload is off.\n" +msgstr "" + +#: main.c +msgid "Running in safe mode! Not running saved code.\n" +msgstr "" + +#: main.c +msgid " not found.\n" +msgstr "" + +#: main.c +msgid "WARNING: Your code filename has two extensions\n" +msgstr "" + +#: main.c +msgid "" +"\n" +"Code stopped by auto-reload. Reloading soon.\n" +msgstr "" + +#: main.c +msgid "" +"\n" +"Code done running.\n" +msgstr "" + +#: main.c +msgid "Woken up by alarm.\n" +msgstr "" + +#: main.c +msgid "Press any key to enter the REPL. Use CTRL-D to reload.\n" +msgstr "" + +#: main.c +msgid "Pretending to deep sleep until alarm, CTRL-C or file write.\n" +msgstr "" + +#: main.c +msgid "UID:" +msgstr "UID:" + +#: main.c +msgid "soft reboot\n" +msgstr "" + +#: ports/analog/common-hal/busio/SPI.c ports/analog/common-hal/busio/UART.c +#: ports/cxd56/common-hal/busio/SPI.c ports/stm/common-hal/audioio/AudioOut.c +#: shared-bindings/digitalio/DigitalInOutProtocol.c +#: shared-module/displayio/bus_core.c shared-module/ssl/SSLContext.c +msgid "%q init failed" +msgstr "" + +#: ports/analog/common-hal/busio/SPI.c +msgid "SPI needs MOSI, MISO, and SCK" +msgstr "" + +#: ports/analog/common-hal/busio/SPI.c +#: ports/atmel-samd/common-hal/pulseio/PulseIn.c +#: ports/cxd56/common-hal/pulseio/PulseIn.c +#: ports/nordic/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#: ports/stm/common-hal/pulseio/PulseIn.c py/argcheck.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/canio/Match.c +#: shared-bindings/time/__init__.c +msgid "%q out of range" +msgstr "" + +#: ports/analog/common-hal/busio/SPI.c +#: ports/espressif/common-hal/espidf/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: shared-bindings/epaperdisplay/EPaperDisplay.c +msgid "Invalid state" +msgstr "" + +#: ports/analog/common-hal/busio/SPI.c +msgid "Failed to set SPI Clock Mode" +msgstr "" + +#: ports/analog/common-hal/busio/UART.c +#: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c +#: ports/nordic/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/zephyr-cp/common-hal/busio/UART.c +msgid "RS485" +msgstr "RS485" + +#: ports/analog/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c +msgid "UART needs TX & RX" +msgstr "" + +#: ports/analog/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c +msgid "Both RX and TX required for flow control" +msgstr "" + +#: ports/analog/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/usb_host/Port.c +#: shared-module/rgbmatrix/RGBMatrix.c +msgid "Failed to allocate %q buffer" +msgstr "" + +#: ports/analog/common-hal/busio/UART.c +msgid "UART read error" +msgstr "" + +#: ports/analog/common-hal/busio/UART.c +msgid "UART transaction timeout" +msgstr "" + +#: ports/analog/common-hal/busio/UART.c ports/espressif/common-hal/busio/UART.c +#: ports/nordic/common-hal/busio/UART.c ports/zephyr-cp/common-hal/busio/UART.c +msgid "All UART peripherals are in use" +msgstr "" + +#: ports/analog/common-hal/busio/UART.c +#: ports/analog/peripherals/max32690/max32_i2c.c +#: ports/analog/peripherals/max32690/max32_spi.c +#: ports/analog/peripherals/max32690/max32_uart.c +#: ports/espressif/common-hal/_bleio/Service.c +#: ports/espressif/common-hal/espulp/ULP.c +#: ports/espressif/common-hal/jpegio/JpegDecoder.c +#: ports/espressif/common-hal/microcontroller/Processor.c +#: ports/espressif/common-hal/mipidsi/Display.c +#: ports/mimxrt10xx/common-hal/audiobusio/__init__.c +#: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c +#: ports/raspberrypi/bindings/picodvi/Framebuffer.c +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +#: ports/raspberrypi/common-hal/picodvi/AudioOut.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c +#: ports/raspberrypi/common-hal/usb_host_bulk/InStream.c py/argcheck.c +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/utils/__init__.c +#: shared-bindings/digitalio/DigitalInOut.c +#: shared-bindings/epaperdisplay/EPaperDisplay.c +#: shared-bindings/i2cioexpander/IOPin.c shared-bindings/mipidsi/Display.c +#: shared-bindings/pwmio/PWMOut.c shared-bindings/supervisor/__init__.c +#: shared-module/aurora_epaper/aurora_framebuffer.c +#: shared-module/cryptography/hazmat/primitives/asymmetric/ec/EllipticCurvePublicKey.c +#: shared-module/jpegio/JpegDecoder.c shared-module/lvfontio/OnDiskFont.c +msgid "Invalid %q" +msgstr "" + +#: ports/analog/common-hal/busio/UART.c +msgid "Timeout must be < 100 seconds" +msgstr "" + +#: ports/atmel-samd/audio_dma.c +msgid "All sync event channels in use" +msgstr "" + +#: ports/atmel-samd/audio_dma.c ports/raspberrypi/audio_dma.c +msgid "Internal audio buffer too small" +msgstr "" + +#: ports/atmel-samd/bindings/samd/Clock.c +msgid "calibration is read only" +msgstr "" + +#: ports/atmel-samd/bindings/samd/Clock.c +msgid "calibration is out of range" +msgstr "" + +#: 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/meowmeow/mpconfigboard.h +msgid "You pressed both buttons at start up." +msgstr "" + +#: ports/atmel-samd/common-hal/_pew/PewPew.c +#: ports/atmel-samd/common-hal/audioio/AudioOut.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/nordic/common-hal/audiopwmio/PWMAudioOut.c +#: ports/nordic/common-hal/pulseio/PulseIn.c +#: ports/nordic/peripherals/nrf/timers.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +#: ports/stm/common-hal/pulseio/PulseOut.c +msgid "All timers in use" +msgstr "" + +#: ports/atmel-samd/common-hal/alarm/pin/PinAlarm.c +#: ports/atmel-samd/common-hal/countio/Counter.c +#: ports/atmel-samd/common-hal/frequencyio/FrequencyIn.c +#: ports/atmel-samd/common-hal/max3421e/Max3421E.c +#: ports/atmel-samd/common-hal/ps2io/Ps2.c +#: ports/atmel-samd/common-hal/pulseio/PulseIn.c +#: ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.c +#: ports/cxd56/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c +#: ports/zephyr-cp/common-hal/async_spi/SPI.c +#: ports/zephyr-cp/common-hal/busio/I2C.c +#: ports/zephyr-cp/common-hal/busio/UART.c +msgid "Internal resource(s) in use" +msgstr "" + +#: ports/atmel-samd/common-hal/alarm/pin/PinAlarm.c +#: supervisor/shared/safe_mode.c +msgid "Unknown reason." +msgstr "" + +#: ports/atmel-samd/common-hal/alarm/time/TimeAlarm.c +#: ports/nordic/common-hal/alarm/time/TimeAlarm.c +#: ports/stm/common-hal/alarm/time/TimeAlarm.c +msgid "Only one alarm.time alarm can be set" +msgstr "" + +#: ports/atmel-samd/common-hal/analogio/AnalogOut.c +#: ports/stm/common-hal/analogio/AnalogOut.c +#: ports/stm/common-hal/audioio/AudioOut.c +msgid "No DAC on chip" +msgstr "" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +msgid "%q and %q must share a clock unit" +msgstr "" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +msgid "Serializer in use" +msgstr "" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +msgid "Clock unit in use" +msgstr "" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/atmel-samd/common-hal/touchio/TouchIn.c +msgid "No free GCLKs" +msgstr "" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +msgid "Too many channels in sample" +msgstr "" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +#: ports/raspberrypi/common-hal/mcp4822/MCP4822.c +msgid "No DMA channel found" +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 +#: ports/raspberrypi/common-hal/mcp4822/MCP4822.c +msgid "Unable to allocate buffers for signed conversion" +msgstr "" + +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c +#, c-format +msgid "Only 8 or 16 bit mono with %dx oversampling supported." +msgstr "" + +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c +msgid "sampling rate out of range" +msgstr "" + +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +msgid "DAC already in use" +msgstr "" + +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +msgid "Right channel unsupported" +msgstr "" + +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +msgid "All event channels in use" +msgstr "" + +#: ports/atmel-samd/common-hal/busio/I2C.c +#: ports/espressif/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nordic/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 "" + +#: ports/atmel-samd/common-hal/busio/UART.c +#: shared-bindings/usb_host_bulk/InStream.c +msgid "%q must be power of 2" +msgstr "" + +#: ports/atmel-samd/common-hal/busio/UART.c +#: ports/espressif/common-hal/busio/SPI.c +#: ports/espressif/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/SPI.c +#: ports/mimxrt10xx/common-hal/busio/UART.c +#: ports/nordic/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c ports/stm/common-hal/busio/SPI.c +#: ports/stm/common-hal/busio/UART.c shared-bindings/fourwire/FourWire.c +#: shared-bindings/i2cdisplaybus/I2CDisplayBus.c +#: shared-bindings/paralleldisplaybus/ParallelBus.c +#: shared-bindings/qspibus/QSPIBus.c shared-module/bitbangio/SPI.c +msgid "No %q pin" +msgstr "" + +#: ports/atmel-samd/common-hal/canio/Listener.c +#: ports/espressif/common-hal/canio/Listener.c +#: ports/stm/common-hal/canio/Listener.c +msgid "All RX FIFOs in use" +msgstr "" + +#: ports/atmel-samd/common-hal/canio/Listener.c +msgid "Already have all-matches listener" +msgstr "" + +#: ports/atmel-samd/common-hal/canio/Listener.c +#: ports/espressif/common-hal/canio/Listener.c +#: ports/mimxrt10xx/common-hal/canio/Listener.c +#: ports/stm/common-hal/canio/Listener.c +msgid "Filters too complex" +msgstr "" + +#: ports/atmel-samd/common-hal/digitalio/DigitalInOut.c +#: ports/mimxrt10xx/common-hal/digitalio/DigitalInOut.c +#: ports/nordic/common-hal/digitalio/DigitalInOut.c +#: ports/raspberrypi/common-hal/digitalio/DigitalInOut.c +msgid "Cannot get pull while in output mode" +msgstr "" + +#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c +#, c-format +msgid "Invalid data_pins[%d]" +msgstr "" + +#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c +#, c-format +msgid "data pin #%d in use" +msgstr "" + +#: ports/atmel-samd/common-hal/microcontroller/Pin.c +#: ports/espressif/common-hal/dotclockframebuffer/DotClockFramebuffer.c +#: ports/mimxrt10xx/common-hal/microcontroller/Pin.c +#: shared-bindings/emmcio/EMMC.c shared-bindings/microcontroller/Pin.c +msgid "Invalid %q pin" +msgstr "" + +#: ports/atmel-samd/common-hal/microcontroller/__init__.c +#: ports/cxd56/common-hal/microcontroller/__init__.c +#: ports/mimxrt10xx/common-hal/microcontroller/__init__.c +msgid "No bootloader present" +msgstr "" + +#: ports/atmel-samd/common-hal/paralleldisplaybus/ParallelBus.c +#: ports/nordic/common-hal/paralleldisplaybus/ParallelBus.c +msgid "Data 0 pin must be byte aligned" +msgstr "" + +#: ports/atmel-samd/common-hal/paralleldisplaybus/ParallelBus.c +#: ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c +#: ports/nordic/common-hal/paralleldisplaybus/ParallelBus.c +#: ports/raspberrypi/common-hal/paralleldisplaybus/ParallelBus.c +#, c-format +msgid "Bus pin %d is already in use" +msgstr "" + +#: ports/atmel-samd/common-hal/pulseio/PulseIn.c +#: ports/cxd56/common-hal/pulseio/PulseIn.c +#: ports/nordic/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 "" + +#: ports/atmel-samd/common-hal/pulseio/PulseIn.c +msgid "Input taking too long" +msgstr "" + +#: ports/atmel-samd/common-hal/pulseio/PulseOut.c +#: ports/cxd56/common-hal/pulseio/PulseOut.c +msgid "Another send is already active" +msgstr "" + +#: ports/atmel-samd/common-hal/sdioio/SDCard.c +#: ports/espressif/common-hal/mii/Ethernet.c +#: ports/espressif/common-hal/qspibus/QSPIBus.c shared-bindings/emmcio/EMMC.c +#: shared-bindings/socketpool/SocketPool.c +msgid "%q failure: %d" msgstr "" -#: ports/stm/common-hal/analogio/AnalogOut.c -msgid "DAC Device Init Error" +#: ports/atmel-samd/common-hal/sdioio/SDCard.c +#: ports/cxd56/common-hal/sdioio/SDCard.c +#: ports/espressif/common-hal/sdioio/SDCard.c +#: ports/raspberrypi/common-hal/sdioio/SDCard.c +#: ports/stm/common-hal/sdioio/SDCard.c shared-bindings/audiocore/WaveFile.c +#: shared-bindings/emmcio/EMMC.c shared-bindings/floppyio/__init__.c +#: shared-bindings/picogame/Canvas.c shared-module/sdcardio/SDCard.c +#, c-format +msgid "Buffer must be a multiple of %d bytes" msgstr "" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c -msgid "DAC already in use" +#: ports/atmel-samd/common-hal/spitarget/SPITarget.c +msgid "Async SPI transfer in progress on this bus, keep awaiting." msgstr "" -#: ports/atmel-samd/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/nordic/common-hal/paralleldisplaybus/ParallelBus.c -msgid "Data 0 pin must be byte aligned" +#: ports/cxd56/common-hal/busio/UART.c ports/espressif/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c +msgid "UART init" msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "Data format error (may be broken data)" +#: ports/cxd56/common-hal/camera/Camera.c +msgid "Camera init" +msgstr "" + +#: ports/cxd56/common-hal/camera/Camera.c +msgid "Size not supported" +msgstr "" + +#: ports/cxd56/common-hal/camera/Camera.c +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +#: shared-bindings/struct/__init__.c shared-module/struct/__init__.c +#: shared-module/videocore/VideoBuffer.c +msgid "Buffer too small" +msgstr "" + +#: ports/cxd56/common-hal/camera/Camera.c +#: ports/espressif/common-hal/jpegio/JpegDecoder.c +#: shared-module/audiocore/WaveFile.c +#: shared-module/busdisplay/lvgl/BusDisplay.c +#: shared-module/displayio/lvgl/TileGrid.c +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "Format not supported" +msgstr "" + +#: ports/cxd56/common-hal/gnss/GNSS.c +msgid "GNSS init" +msgstr "" + +#: ports/cxd56/common-hal/sdioio/SDCard.c +msgid "SDCard init" +msgstr "" + +#: ports/espressif/bindings/espnow/ESPNow.c +#: ports/espressif/common-hal/espulp/ULP.c +#: ports/raspberrypi/common-hal/usb_host_bulk/InStream.c +#: shared-module/memorymonitor/AllocationAlarm.c +#: shared-module/memorymonitor/AllocationSize.c +msgid "Already running" +msgstr "" + +#: ports/espressif/bindings/espnow/Peer.c shared-bindings/dualbank/__init__.c +msgid "%q is %q" +msgstr "" + +#: ports/espressif/boards/adafruit_feather_esp32_v2/mpconfigboard.h +msgid "You pressed the SW38 button at start up." +msgstr "" + +#: ports/espressif/boards/adafruit_feather_esp32c6_4mbflash_nopsram/mpconfigboard.h +#: ports/espressif/boards/adafruit_itsybitsy_esp32/mpconfigboard.h +#: ports/espressif/boards/waveshare_esp32_c5_lcd_1_47/mpconfigboard.h +#: ports/espressif/boards/waveshare_esp32_c6_lcd_1_47/mpconfigboard.h +msgid "You pressed the BOOT button at start up." +msgstr "" + +#: ports/espressif/boards/adafruit_huzzah32_breakout/mpconfigboard.h +msgid "You pressed the GPIO0 button at start up." +msgstr "" + +#: ports/espressif/boards/espressif_esp32_lyrat/mpconfigboard.h +msgid "You pressed the Rec button at start up." +msgstr "" + +#: ports/espressif/boards/hardkernel_odroid_go/mpconfigboard.h +#: ports/espressif/boards/vidi_x/mpconfigboard.h +msgid "You pressed the VOLUME button at start up." +msgstr "" + +#: ports/espressif/boards/m5stack_atom_echo/mpconfigboard.h +#: ports/espressif/boards/m5stack_atom_lite/mpconfigboard.h +#: ports/espressif/boards/m5stack_atom_matrix/mpconfigboard.h +#: ports/espressif/boards/m5stack_atom_u/mpconfigboard.h +msgid "You pressed the central button at start up." +msgstr "" + +#: ports/espressif/boards/m5stack_core_basic/mpconfigboard.h +#: ports/espressif/boards/m5stack_core_fire/mpconfigboard.h +#: ports/espressif/boards/m5stack_stick_c/mpconfigboard.h +#: ports/espressif/boards/m5stack_stick_c_plus/mpconfigboard.h +#: ports/espressif/boards/m5stack_stick_c_plus2/mpconfigboard.h +msgid "You pressed button A at start up." +msgstr "" + +#: ports/espressif/boards/m5stack_m5paper/mpconfigboard.h +msgid "You pressed button DOWN at start up." +msgstr "" + +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/espressif/common-hal/dualbank/__init__.c +msgid "Update failed" msgstr "" #: ports/espressif/common-hal/_bleio/Adapter.c #: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Data not supported with directed advertising" +msgid "Scan already in progress. Stop with stop_scan." +msgstr "" + +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +#: ports/zephyr-cp/common-hal/_bleio/Adapter.c +msgid "Failed to connect: timeout" msgstr "" #: ports/espressif/common-hal/_bleio/Adapter.c #: ports/nordic/common-hal/_bleio/Adapter.c +#: ports/zephyr-cp/common-hal/_bleio/Adapter.c +msgid "Failed to connect: internal error" +msgstr "" + +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +#: ports/zephyr-cp/common-hal/_bleio/Adapter.c msgid "Data too large for advertisement packet" msgstr "" -#: ports/stm/common-hal/alarm/pin/PinAlarm.c -msgid "Deep sleep pins must use a rising edge with pulldown" +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "Already advertising." msgstr "" -#: shared-bindings/audiobusio/PDMIn.c -msgid "Destination capacity is smaller than destination_length." +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "Extended advertisements with scan response not supported." msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "Device error or wrong termination of input stream" +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "Data not supported with directed advertising" +msgstr "" + +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +#, c-format +msgid "Timeout is too long: Maximum timeout length is %d seconds" +msgstr "" + +#: ports/espressif/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Descriptor.c +msgid "Value length != required fixed length" +msgstr "" + +#: ports/espressif/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Descriptor.c +msgid "Value length > max_length" +msgstr "" + +#: ports/espressif/common-hal/_bleio/Characteristic.c +#: ports/espressif/common-hal/_bleio/Service.c +#: ports/raspberrypi/common-hal/alarm/pin/PinAlarm.c +#: ports/raspberrypi/common-hal/usb_host_bulk/InStream.c +msgid "Too many %q" +msgstr "" + +#: ports/espressif/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Characteristic.c +#: ports/zephyr-cp/common-hal/_bleio/Characteristic.c +msgid "No CCCD for this Characteristic" +msgstr "" + +#: ports/espressif/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Characteristic.c +msgid "Can't set CCCD on local Characteristic" +msgstr "" + +#: ports/espressif/common-hal/_bleio/Connection.c +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/Characteristic.c +#: ports/zephyr-cp/common-hal/_bleio/Connection.c +#: ports/zephyr-cp/common-hal/_bleio/Descriptor.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +#: shared-bindings/_bleio/CharacteristicBuffer.c +msgid "Not connected" +msgstr "" + +#: ports/espressif/common-hal/_bleio/Connection.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/Connection.c +msgid "" +"Unspecified issue. The pairing request on the other device may have been " +"declined or ignored." +msgstr "" + +#: ports/espressif/common-hal/_bleio/Connection.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/Connection.c +#, c-format +msgid "Unknown security error: 0x%04x" +msgstr "" + +#: ports/espressif/common-hal/_bleio/Connection.c +msgid "No pairing in progress" +msgstr "" + +#: ports/espressif/common-hal/_bleio/Connection.c +#: ports/nordic/common-hal/_bleio/Connection.c +msgid "non-UUID found in service_uuids_whitelist" +msgstr "" + +#: ports/espressif/common-hal/_bleio/Descriptor.c +#: ports/nordic/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Descriptor.c +#, c-format +msgid "max_length must be 0-%d when fixed_length is %s" +msgstr "" + +#: ports/espressif/common-hal/_bleio/PacketBuffer.c +#: ports/nordic/common-hal/_bleio/PacketBuffer.c +#: ports/zephyr-cp/common-hal/_bleio/PacketBuffer.c +msgid "Writes not supported on Characteristic" +msgstr "" + +#: ports/espressif/common-hal/_bleio/PacketBuffer.c +#: ports/nordic/common-hal/_bleio/PacketBuffer.c +#: ports/zephyr-cp/common-hal/_bleio/PacketBuffer.c +msgid "Total data to write is larger than %q" +msgstr "" + +#: ports/espressif/common-hal/_bleio/__init__.c +msgid "Nimble out of memory" +msgstr "" + +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +msgid "Invalid BLE parameter" +msgstr "" + +#: ports/espressif/common-hal/_bleio/__init__.c +#: shared-module/audiofilewriter/AudioFileWriter.c +msgid "Already in progress" +msgstr "" + +#: ports/espressif/common-hal/_bleio/__init__.c +#, c-format +msgid "Unknown BLE error at %s:%d: 0x%04x" +msgstr "" + +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#, c-format +msgid "Unknown BLE error: 0x%04x" +msgstr "" + +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +msgid "%q not permitted" +msgstr "" + +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +msgid "Insufficient authentication" +msgstr "" + +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +msgid "Insufficient authorization" +msgstr "" + +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +msgid "Insufficient encryption" +msgstr "" + +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +#, c-format +msgid "Unknown gatt error: 0x%04x" +msgstr "" + +#: ports/espressif/common-hal/alarm/pin/PinAlarm.c +msgid "Cannot wake on pin edge. Only level." msgstr "" -#: ports/nordic/common-hal/audiobusio/I2SOut.c -msgid "Device in use" +#: ports/espressif/common-hal/alarm/pin/PinAlarm.c +msgid "Cannot pull on input-only pin." msgstr "" -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -msgid "Display must have a 16 bit colorspace." +#: ports/espressif/common-hal/alarm/pin/PinAlarm.c +msgid "Can only alarm on two low pins from deep sleep." msgstr "" -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/epaperdisplay/EPaperDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -msgid "Display rotation must be in 90 degree increments" +#: ports/espressif/common-hal/alarm/pin/PinAlarm.c +msgid "Can only alarm on one low pin while others alarm high from deep sleep." msgstr "" -#: main.c -msgid "Done" +#: ports/espressif/common-hal/alarm/pin/PinAlarm.c +msgid "Can only alarm on RTC IO from deep sleep." msgstr "" -#: shared-bindings/digitalio/DigitalInOut.c -msgid "Drive mode not used when direction is input." +#: ports/espressif/common-hal/alarm/time/TimeAlarm.c +#: ports/raspberrypi/common-hal/alarm/time/TimeAlarm.c +msgid "Only one alarm.time alarm can be set." msgstr "" -#: py/obj.c -msgid "During handling of the above exception, another exception occurred:" +#: ports/espressif/common-hal/alarm/touch/TouchAlarm.c +msgid "Only one %q can be set in deep sleep." msgstr "" -#: shared-bindings/aesio/aes.c -msgid "ECB only operates on 16 bytes at a time" +#: ports/espressif/common-hal/analogbufio/BufferedIn.c +msgid "%q must be array of type 'H'" msgstr "" -#: ports/espressif/common-hal/busio/SPI.c -#: ports/espressif/common-hal/canio/CAN.c -msgid "ESP-IDF memory allocation failed" +#: ports/espressif/common-hal/audiobusio/PDMIn.c +#: shared-bindings/audioi2sin/I2SIn.c shared-bindings/usb_host_audio/USBIn.c +msgid "%q must be 8, 16, 24, or 32" msgstr "" -#: extmod/modre.c -msgid "Error in regex" +#: ports/espressif/common-hal/audiobusio/__init__.c +#: ports/espressif/common-hal/audioi2sin/I2SIn.c +#: ports/espressif/common-hal/mii/Ethernet.c shared-bindings/emmcio/EMMC.c +msgid "Peripheral in use" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Error in safemode.py." +#: ports/espressif/common-hal/audioi2sin/I2SIn.c +#: ports/raspberrypi/common-hal/audioi2sin/I2SIn.c +msgid "%q must be 8 or 16" msgstr "" -#: shared-bindings/alarm/__init__.c -msgid "Expected a kind of %q" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "audio format not supported" msgstr "" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Extended advertisements with scan response not supported." +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to start async audio" msgstr "" -#: extmod/ulab/code/numpy/fft/fft_tools.c -msgid "FFT is defined for ndarrays only" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to create continuous channels: invalid arg" msgstr "" -#: extmod/ulab/code/numpy/fft/fft_tools.c -msgid "FFT is implemented for linear arrays only" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to create continuous channels: invalid state" msgstr "" -#: shared-bindings/ps2io/Ps2.c -msgid "Failed sending command." +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to create continuous channels: not found" msgstr "" -#: ports/nordic/sd_mutex.c -#, c-format -msgid "Failed to acquire mutex, err 0x%04x" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to create continuous channels: no mem" msgstr "" -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "Failed to add service TXT record" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to register continuous events callback" msgstr "" -#: shared-bindings/mdns/Server.c -msgid "" -"Failed to add service TXT record; non-string or bytes found in txt_records" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to enable continuous" msgstr "" -#: shared-module/rgbmatrix/RGBMatrix.c -msgid "Failed to allocate %q buffer" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Can't construct AudioOut because continuous channel already open" msgstr "" -#: ports/espressif/common-hal/wifi/__init__.c -msgid "Failed to allocate Wifi memory" +#: ports/espressif/common-hal/audioio/AudioOut.c +#: ports/espressif/common-hal/mipicsi/Camera.c +#: shared-module/videocore/VideoBuffer.c shared-module/videogif/GifDecoder.c +msgid "already playing" msgstr "" -#: ports/espressif/common-hal/wifi/ScannedNetworks.c -msgid "Failed to allocate wifi scan memory" +#: ports/espressif/common-hal/busio/I2C.c +#: ports/espressif/common-hal/i2ctarget/I2CTarget.c +#: ports/nordic/common-hal/busio/I2C.c ports/zephyr-cp/common-hal/busio/I2C.c +msgid "All I2C peripherals are in use" msgstr "" -#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c -msgid "Failed to buffer the sample" +#: ports/espressif/common-hal/busio/I2C.c +#: ports/espressif/common-hal/busio/SPI.c +msgid "Unable to create lock" msgstr "" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Failed to connect: internal error" +#: ports/espressif/common-hal/busio/SPI.c +msgid "SPI configuration failed" msgstr "" -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Failed to connect: timeout" +#: ports/espressif/common-hal/busio/SPI.c ports/nordic/common-hal/busio/SPI.c +#: ports/zephyr-cp/common-hal/async_spi/SPI.c +msgid "All SPI peripherals are in use" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to create continuous channels: invalid arg" +#: ports/espressif/common-hal/busio/SPI.c +#: ports/espressif/common-hal/canio/CAN.c +#: ports/espressif/common-hal/qspibus/QSPIBus.c +msgid "ESP-IDF memory allocation failed" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to create continuous channels: invalid state" +#: ports/espressif/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c +msgid "Cannot specify RTS or CTS in RS485 mode" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to create continuous channels: no mem" +#: ports/espressif/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c +msgid "RS485 inversion specified when not in RS485 mode" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to create continuous channels: not found" +#: ports/espressif/common-hal/canio/CAN.c +msgid "Baudrate not supported by peripheral" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to enable continuous" +#: ports/espressif/common-hal/canio/CAN.c +msgid "All CAN peripherals are in use" msgstr "" -#: shared-module/audiomp3/MP3Decoder.c -msgid "Failed to parse MP3 file" +#: ports/espressif/common-hal/canio/CAN.c +msgid "loopback + silent mode not supported by peripheral" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to register continuous events callback" +#: ports/espressif/common-hal/canio/CAN.c +#, c-format +msgid "twai_driver_install returned esp-idf error #%d" msgstr "" -#: ports/nordic/sd_mutex.c +#: ports/espressif/common-hal/canio/CAN.c #, c-format -msgid "Failed to release mutex, err 0x%04x" +msgid "twai_start returned esp-idf error #%d" msgstr "" -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "Failed to set hostname" +#: ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "ds_params has the wrong length" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to start async audio" +#: ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "" +"This key already committed to a different algorithm; call " +"load_digital_signature_key() again to use a different one" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Failed to write internal flash." +#: ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "" +"This key's ds_params were replaced by a later load_digital_signature_key() " +"call for the same key slot" msgstr "" -#: py/moderrno.c -msgid "File exists" +#: ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "ds_params is invalid for this key slot" msgstr "" -#: shared-module/os/getenv.c -msgid "File not found" +#: ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "Digital Signature peripheral not available on this chip" msgstr "" -#: ports/atmel-samd/common-hal/canio/Listener.c -#: ports/espressif/common-hal/canio/Listener.c -#: ports/mimxrt10xx/common-hal/canio/Listener.c -#: ports/stm/common-hal/canio/Listener.c -msgid "Filters too complex" +#: ports/espressif/common-hal/dotclockframebuffer/DotClockFramebuffer.c +msgid "Must provide 5/6/5 RGB pins" msgstr "" #: ports/espressif/common-hal/dualbank/__init__.c @@ -1076,239 +1665,244 @@ msgstr "" msgid "Firmware is too big" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "For L8 colorspace, input bitmap must have 8 bits per pixel" +#: ports/espressif/common-hal/espcamera/Camera.c py/objobject.c py/runtime.c +msgid "no such attribute" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "For RGB colorspaces, input bitmap must have 16 bits per pixel" +#: ports/espressif/common-hal/espcamera/Camera.c +msgid "invalid setting" msgstr "" -#: ports/cxd56/common-hal/camera/Camera.c -msgid "Format not supported" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "Generic Failure" msgstr "" -#: ports/mimxrt10xx/common-hal/microcontroller/Processor.c -msgid "" -"Frequency must be 24, 150, 396, 450, 528, 600, 720, 816, 912, 960 or 1008 Mhz" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "Out of memory" msgstr "" -#: shared-bindings/bitbangio/I2C.c shared-bindings/bitbangio/SPI.c -#: shared-bindings/busio/I2C.c shared-bindings/busio/SPI.c -msgid "Function requires lock" +#: ports/espressif/common-hal/espidf/__init__.c py/moderrno.c +msgid "Invalid argument" msgstr "" -#: ports/cxd56/common-hal/gnss/GNSS.c -msgid "GNSS init" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "Invalid size" msgstr "" #: ports/espressif/common-hal/espidf/__init__.c -msgid "Generic Failure" +msgid "Requested resource not found" msgstr "" +#: ports/espressif/common-hal/espidf/__init__.c +#: ports/espressif/common-hal/jpegio/JpegDecoder.c +#: ports/raspberrypi/common-hal/usb_host_bulk/InStream.c +#: shared-bindings/busdisplay/BusDisplay.c #: shared-bindings/framebufferio/FramebufferDisplay.c -#: shared-module/busdisplay/BusDisplay.c -#: shared-module/framebufferio/FramebufferDisplay.c -msgid "Group already used" -msgstr "" - -#: supervisor/shared/safe_mode.c -msgid "Hard fault: memory access or instruction error." +#: shared-bindings/picogame/Canvas.c shared-bindings/picogame/__init__.c +#: shared-module/jpegio/JpegDecoder.c shared-module/picogame/Display.c +msgid "Operation or feature not supported" msgstr "" -#: ports/mimxrt10xx/common-hal/busio/SPI.c -#: ports/mimxrt10xx/common-hal/busio/UART.c 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 "Hardware in use, try alternative pins" +#: ports/espressif/common-hal/espidf/__init__.c +#: ports/espressif/common-hal/qspibus/QSPIBus.c +#: shared-module/_airlift/__init__.c +msgid "Operation timed out" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Heap allocation when VM not running." +#: ports/espressif/common-hal/espidf/__init__.c +#: shared-module/_airlift/__init__.c +msgid "Received response was invalid" msgstr "" -#: extmod/vfs_posix_file.c py/objstringio.c -msgid "I/O operation on closed file" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "CRC or checksum was invalid" msgstr "" -#: ports/stm/common-hal/busio/I2C.c -msgid "I2C init error" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "Version was invalid" msgstr "" -#: ports/raspberrypi/common-hal/busio/I2C.c -#: ports/raspberrypi/common-hal/i2ctarget/I2CTarget.c -msgid "I2C peripheral in use" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "MAC address was invalid" msgstr "" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "In-buffer elements must be <= 4 bytes long" +#: ports/espressif/common-hal/espidf/__init__.c +#, c-format +msgid "%s error 0x%x" msgstr "" -#: shared-bindings/_pew/PewPew.c -msgid "Incorrect buffer size" +#: ports/espressif/common-hal/espulp/ULP.c +msgid "Program too long" msgstr "" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "Init program size invalid" +#: ports/espressif/common-hal/espulp/ULP.c +#: ports/espressif/common-hal/mipidsi/Bus.c +#: ports/espressif/common-hal/qspibus/QSPIBus.c +#: ports/mimxrt10xx/common-hal/audiobusio/__init__.c +#: ports/mimxrt10xx/common-hal/usb_host/Port.c +#: ports/raspberrypi/common-hal/picodvi/AudioOut.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#: ports/raspberrypi/common-hal/usb_host/Port.c +#: shared-bindings/digitalio/DigitalInOut.c shared-bindings/emmcio/EMMC.c +#: shared-bindings/i2cioexpander/IOPin.c shared-bindings/microcontroller/Pin.c +#: shared-module/_airlift/__init__.c +#: shared-module/epaperdisplay/EPaperDisplay.c +#: shared-module/max3421e/Max3421E.c shared-module/usb/core/Device.c +#: shared-module/usb_host_audio/USBIn.c +msgid "%q in use" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Initial set pin direction conflicts with initial out pin direction" +#: ports/espressif/common-hal/espulp/ULPAlarm.c +msgid "Only one %q can be set." msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Initial set pin state conflicts with initial out pin state" +#: ports/espressif/common-hal/i2ctarget/I2CTarget.c +#: ports/raspberrypi/common-hal/i2ctarget/I2CTarget.c +msgid "Only one address is allowed" msgstr "" -#: shared-bindings/bitops/__init__.c +#: ports/espressif/common-hal/max3421e/Max3421E.c +#: ports/raspberrypi/common-hal/wifi/__init__.c #, c-format -msgid "Input buffer length (%d) must be a multiple of the strand count (%d)" +msgid "Unknown error code %d" msgstr "" -#: ports/atmel-samd/common-hal/pulseio/PulseIn.c -msgid "Input taking too long" +#: ports/espressif/common-hal/mdns/Server.c +#: ports/raspberrypi/common-hal/mdns/Server.c +msgid "mDNS only works with built-in WiFi" msgstr "" -#: py/moderrno.c -msgid "Input/output error" +#: ports/espressif/common-hal/mdns/Server.c +#: ports/raspberrypi/common-hal/mdns/Server.c +msgid "mDNS already initialized" msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -#: ports/nordic/common-hal/_bleio/__init__.c -msgid "Insufficient authentication" +#: ports/espressif/common-hal/mdns/Server.c +#: ports/raspberrypi/common-hal/mdns/Server.c +msgid "Unable to start mDNS query" msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -#: ports/nordic/common-hal/_bleio/__init__.c -msgid "Insufficient encryption" +#: ports/espressif/common-hal/memorymap/AddressRange.c +#: ports/nordic/common-hal/memorymap/AddressRange.c +#: ports/raspberrypi/common-hal/memorymap/AddressRange.c +msgid "Address range not allowed" msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "Insufficient memory pool for the image" +#: ports/espressif/common-hal/mipicsi/Camera.c +#: shared-bindings/displayio/TileGrid.c shared-bindings/terminalio/Terminal.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-bindings/vectorio/VectorShape.c +msgid "unsupported %q type" msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "Insufficient stream input buffer" +#: ports/espressif/common-hal/mipicsi/Camera.c +msgid "output_format must be RGB565 or RGB888" msgstr "" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "Interface must be started" +#: ports/espressif/common-hal/mipicsi/Camera.c +msgid "ISP conversion not supported on this chip" msgstr "" -#: ports/atmel-samd/audio_dma.c ports/raspberrypi/audio_dma.c -msgid "Internal audio buffer too small" +#: ports/espressif/common-hal/mipidsi/Bus.c +msgid "%q is above %u" msgstr "" -#: ports/stm/common-hal/busio/UART.c -msgid "Internal define error" +#: ports/espressif/common-hal/mipidsi/Bus.c +msgid "%q is not reachable by the PHY" msgstr "" -#: shared-bindings/pwmio/PWMOut.c shared-module/os/getenv.c -msgid "Internal error" +#: ports/espressif/common-hal/nvm/ByteArray.c +msgid "NVS Error" msgstr "" -#: shared-module/rgbmatrix/RGBMatrix.c +#: ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c +#: ports/espressif/common-hal/sdioio/SDCard.c #, c-format -msgid "Internal error #%d" +msgid "Number of data_pins must be %d or %d, not %d" msgstr "" -#: ports/atmel-samd/common-hal/alarm/pin/PinAlarm.c -#: ports/atmel-samd/common-hal/countio/Counter.c -#: ports/atmel-samd/common-hal/frequencyio/FrequencyIn.c -#: ports/atmel-samd/common-hal/max3421e/Max3421E.c -#: ports/atmel-samd/common-hal/ps2io/Ps2.c -#: ports/atmel-samd/common-hal/pulseio/PulseIn.c -#: ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.c -#: ports/cxd56/common-hal/pulseio/PulseIn.c -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c -#: shared-bindings/pwmio/PWMOut.c -msgid "Internal resource(s) in use" +#: ports/espressif/common-hal/pulseio/PulseIn.c +msgid "pop from an empty PulseIn" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Internal watchdog timer expired." +#: ports/espressif/common-hal/qspibus/QSPIBus.c +#: ports/raspberrypi/common-hal/usb_host_bulk/InStream.c +#: shared-module/usb/core/Device.c +msgid "Could not allocate DMA capable buffer" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Interrupt error." +#: ports/espressif/common-hal/qspibus/QSPIBus.c shared-bindings/pwmio/PWMOut.c +#: supervisor/shared/settings.c +msgid "Internal error" msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "Interrupted by output function" +#: ports/espressif/common-hal/rclcpy/Node.c +msgid "ROS node failed to initialize" msgstr "" -#: ports/espressif/common-hal/_bleio/Service.c -#: ports/espressif/common-hal/espulp/ULP.c -#: ports/espressif/common-hal/microcontroller/Processor.c -#: ports/mimxrt10xx/common-hal/audiobusio/__init__.c -#: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c -#: ports/raspberrypi/bindings/picodvi/Framebuffer.c -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c py/argcheck.c -#: shared-bindings/digitalio/DigitalInOut.c -#: shared-bindings/epaperdisplay/EPaperDisplay.c shared-bindings/pwmio/PWMOut.c -#: shared-module/aurora_epaper/aurora_framebuffer.c -msgid "Invalid %q" +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "ROS topic failed to initialize" msgstr "" -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c -#: shared-module/aurora_epaper/aurora_framebuffer.c -msgid "Invalid %q and %q" +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "Could not publish to ROS topic" msgstr "" -#: ports/atmel-samd/common-hal/microcontroller/Pin.c -#: ports/espressif/common-hal/dotclockframebuffer/DotClockFramebuffer.c -#: ports/mimxrt10xx/common-hal/microcontroller/Pin.c -#: shared-bindings/microcontroller/Pin.c -msgid "Invalid %q pin" +#: ports/espressif/common-hal/rclcpy/__init__.c +#, c-format +msgid "Critical ROS failure during soft reboot, reset required: %d" msgstr "" -#: ports/stm/common-hal/analogio/AnalogIn.c -msgid "Invalid ADC Unit value" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS memory allocator failure" msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -#: ports/nordic/common-hal/_bleio/__init__.c -msgid "Invalid BLE parameter" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS internal setup failure" msgstr "" -#: shared-bindings/wifi/Radio.c -msgid "Invalid BSSID" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "Invalid ROS domain ID" msgstr "" -#: shared-bindings/wifi/Radio.c -msgid "Invalid MAC address" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS failed to initialize. Is agent connected?" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c py/moderrno.c -msgid "Invalid argument" +#: ports/espressif/common-hal/sdioio/SDCard.c +#: ports/raspberrypi/common-hal/sdioio/SDCard.c +#: ports/stm/common-hal/sdioio/SDCard.c +#, c-format +msgid "SDIO Init Error 0x%02x" msgstr "" -#: shared-module/displayio/Bitmap.c -msgid "Invalid bits per value" +#: ports/espressif/common-hal/socketpool/Socket.c +#: ports/zephyr-cp/common-hal/socketpool/Socket.c +msgid "Unsupported socket type" msgstr "" -#: shared-module/os/getenv.c -#, c-format -msgid "Invalid byte %.*s" +#: ports/espressif/common-hal/socketpool/Socket.c +#: ports/raspberrypi/common-hal/socketpool/Socket.c +msgid "Out of sockets" msgstr "" -#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c -#, c-format -msgid "Invalid data_pins[%d]" +#: ports/espressif/common-hal/socketpool/SocketPool.c +msgid "SocketPool can only be used with %q.%q or any %q.%q" msgstr "" -#: shared-module/msgpack/__init__.c -msgid "Invalid format" +#: ports/espressif/common-hal/watchdog/WatchDogTimer.c +msgid "%q must be <= %u" msgstr "" -#: shared-module/audiocore/WaveFile.c -msgid "Invalid format chunk size" +#: ports/espressif/common-hal/wifi/Monitor.c +msgid "monitor init failed" msgstr "" -#: shared-bindings/wifi/Radio.c -msgid "Invalid hex password" +#: ports/espressif/common-hal/wifi/Radio.c +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "Interface must be started" msgstr "" #: ports/espressif/common-hal/wifi/Radio.c @@ -1316,1350 +1910,1338 @@ msgstr "" msgid "Invalid multicast MAC address" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Invalid size" +#: ports/espressif/common-hal/wifi/Radio.c +#: ports/raspberrypi/common-hal/wifi/Radio.c +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "Already scanning for wifi networks" msgstr "" -#: shared-module/ssl/SSLSocket.c -msgid "Invalid socket for TLS" +#: ports/espressif/common-hal/wifi/Radio.c +#: ports/espressif/common-hal/wifi/__init__.c +#: ports/raspberrypi/common-hal/wifi/Radio.c +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "WiFi is not enabled" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -#: ports/nordic/common-hal/_bleio/__init__.c -msgid "Invalid state" +#: ports/espressif/common-hal/wifi/ScannedNetworks.c +msgid "Failed to allocate wifi scan memory" msgstr "" -#: shared-module/os/getenv.c -msgid "Invalid unicode escape" +#: ports/espressif/common-hal/wifi/__init__.c +msgid "Failed to allocate Wifi memory" msgstr "" -#: shared-bindings/aesio/aes.c -msgid "Key must be 16, 24, or 32 bytes long" +#: ports/espressif/common-hal/wifi/__init__.c +#: ports/raspberrypi/common-hal/wifi/__init__.c +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "Only IPv4 addresses supported" msgstr "" -#: shared-module/os/getenv.c -msgid "Key not found" +#: ports/mimxrt10xx/common-hal/busio/SPI.c +#: ports/raspberrypi/bindings/wiznet/PIO_SPI.c shared-bindings/async_spi/SPI.c +#: shared-bindings/busio/SPI.c +msgid "Must provide MISO or MOSI pin" msgstr "" -#: shared-module/is31fl3741/FrameBuffer.c -msgid "LED mappings must match display size" +#: ports/mimxrt10xx/common-hal/busio/SPI.c +#: ports/mimxrt10xx/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/canio/CAN.c 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 +#: shared-bindings/emmcio/EMMC.c +msgid "Hardware in use, try alternative pins" msgstr "" -#: py/compile.c -msgid "LHS of keyword arg must be an id" +#: ports/mimxrt10xx/common-hal/canio/CAN.c +msgid "Unable to send CAN Message: all Tx message buffers are busy" msgstr "" -#: shared-module/displayio/Group.c -msgid "Layer already in a group" +#: ports/mimxrt10xx/common-hal/microcontroller/Processor.c +msgid "" +"Frequency must be 24, 150, 396, 450, 528, 600, 720, 816, 912, 960 or 1008 Mhz" msgstr "" -#: shared-module/displayio/Group.c -msgid "Layer must be a Group or TileGrid subclass" +#: ports/nordic/boards/aramcon2_badge/mpconfigboard.h +msgid "You pressed the left button at start up." msgstr "" -#: shared-bindings/audiocore/RawSample.c -msgid "Length of %q must be an even multiple of channel_count * type_size" +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "timeout must be < 655.35 secs" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "MAC address was invalid" +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "non-zero timeout must be > 0.01" msgstr "" -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/espressif/common-hal/_bleio/Descriptor.c -msgid "MITM security not supported" +#: ports/nordic/common-hal/_bleio/UUID.c +msgid "Unexpected nrfx uuid type" msgstr "" -#: shared-bindings/is31fl3741/IS31FL3741.c -msgid "Mapping must be a tuple" +#: ports/nordic/common-hal/_bleio/__init__.c +msgid "Nordic system firmware out of memory" msgstr "" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Mismatched data size" +#: ports/nordic/common-hal/_bleio/__init__.c +#, c-format +msgid "Unknown system firmware error: %04x" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Mismatched swap flag" +#: ports/nordic/common-hal/alarm/pin/PinAlarm.c +msgid "Cannot wake on pin edge, only level" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_in_pin. %q[%u] reads pin(s)" +#: ports/nordic/common-hal/audiobusio/I2SOut.c +msgid "Device in use" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_in_pin. %q[%u] shifts in from pin(s)" +#: ports/nordic/common-hal/audiobusio/PDMIn.c +#: ports/stm/common-hal/audiobusio/PDMIn.c +msgid "only sample_rate=16000 is supported" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_in_pin. %q[%u] waits based on pin" +#: ports/nordic/common-hal/audiobusio/PDMIn.c +#: ports/stm/common-hal/audiobusio/PDMIn.c +msgid "only bit_depth=16 is supported" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_out_pin. %q[%u] shifts out to pin(s)" +#: ports/nordic/common-hal/busio/UART.c +#, c-format +msgid "error = 0x%08lX" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_out_pin. %q[%u] writes pin(s)" +#: ports/nordic/common-hal/busio/UART.c +msgid "Odd parity is not supported" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_set_pin. %q[%u] sets pin(s)" +#: ports/nordic/common-hal/countio/Counter.c +#: ports/nordic/common-hal/pulseio/PulseIn.c +#: ports/nordic/common-hal/rotaryio/IncrementalEncoder.c +msgid "All channels in use" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing jmp_pin. %q[%u] jumps on pin" +#: ports/nordic/common-hal/microcontroller/Processor.c +msgid "Cannot get temperature" msgstr "" -#: shared-module/storage/__init__.c -msgid "Mount point directory missing" +#: ports/nordic/common-hal/watchdog/WatchDogTimer.c +msgid "timeout duration exceeded the maximum supported value" msgstr "" -#: ports/zephyr-cp/bindings/zephyr_serial/UART.c shared-bindings/busio/UART.c -#: shared-bindings/displayio/Group.c -msgid "Must be a %q subclass." +#: ports/nordic/common-hal/watchdog/WatchDogTimer.c +msgid "%q cannot be changed once mode is set to %q" msgstr "" -#: ports/espressif/common-hal/dotclockframebuffer/DotClockFramebuffer.c -msgid "Must provide 5/6/5 RGB pins" +#: ports/nordic/common-hal/watchdog/WatchDogTimer.c +msgid "WatchDogTimer cannot be deinitialized once mode is set to RESET" msgstr "" -#: ports/mimxrt10xx/common-hal/busio/SPI.c shared-bindings/busio/SPI.c -msgid "Must provide MISO or MOSI pin" +#: ports/nordic/sd_mutex.c +#, c-format +msgid "Failed to acquire mutex, err 0x%04x" msgstr "" -#: shared-bindings/rgbmatrix/RGBMatrix.c +#: ports/nordic/sd_mutex.c #, c-format -msgid "Must use a multiple of 6 rgb pins, not %d" +msgid "Failed to release mutex, err 0x%04x" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "NLR jump failed. Likely memory corruption." +#: ports/raspberrypi/audio_dma.c +msgid "Audio conversion not implemented" msgstr "" -#: ports/espressif/common-hal/nvm/ByteArray.c -msgid "NVS Error" +#: ports/raspberrypi/bindings/cyw43/__init__.c py/argcheck.c py/objexcept.c +#: shared-bindings/bitmapfilter/__init__.c shared-bindings/canio/CAN.c +#: shared-bindings/digitalio/Pull.c shared-bindings/picogame/Sprite.c +#: shared-bindings/supervisor/__init__.c shared-module/audiofilters/__init__.c +#: shared-module/displayio/legacy/__init__.c +#: shared-module/synthio/Synthesizer.c shared-module/videocore/VideoBuffer.c +msgid "%q must be of type %q or %q, not %q" msgstr "" -#: shared-bindings/socketpool/SocketPool.c -msgid "Name or service not known" +#: ports/raspberrypi/bindings/picodvi/AudioOut.c +#: shared-bindings/audiobusio/I2SOut.c shared-bindings/audioio/AudioOut.c +#: shared-bindings/audiopwmio/PWMAudioOut.c shared-bindings/mcp4822/MCP4822.c +#: shared-bindings/usb_audio/USBMicrophone.c +msgid "Not playing" msgstr "" - -#: shared-bindings/displayio/TileGrid.c -msgid "New bitmap must be same size as old bitmap" + +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Program size invalid" msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -msgid "Nimble out of memory" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Init program size invalid" msgstr "" -#: ports/atmel-samd/common-hal/busio/UART.c -#: ports/espressif/common-hal/busio/SPI.c -#: ports/espressif/common-hal/busio/UART.c -#: ports/mimxrt10xx/common-hal/busio/SPI.c -#: ports/mimxrt10xx/common-hal/busio/UART.c -#: ports/nordic/common-hal/busio/UART.c -#: ports/raspberrypi/common-hal/busio/UART.c ports/stm/common-hal/busio/SPI.c -#: ports/stm/common-hal/busio/UART.c shared-bindings/fourwire/FourWire.c -#: shared-bindings/i2cdisplaybus/I2CDisplayBus.c -#: shared-bindings/paralleldisplaybus/ParallelBus.c -#: shared-module/bitbangio/SPI.c -msgid "No %q pin" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Buffer elements must be 4 bytes long or less" msgstr "" -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Characteristic.c -msgid "No CCCD for this Characteristic" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Mismatched data size" msgstr "" -#: ports/atmel-samd/common-hal/analogio/AnalogOut.c -#: ports/stm/common-hal/analogio/AnalogOut.c -msgid "No DAC on chip" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Out-buffer elements must be <= 4 bytes long" 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" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "In-buffer elements must be <= 4 bytes long" msgstr "" -#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c -msgid "No DMA pacing timer found" +#: ports/raspberrypi/bindings/wiznet/PIO_SPI.c shared-bindings/async_spi/SPI.c +#: 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 "" -#: shared-module/adafruit_bus_device/i2c_device/I2CDevice.c -#, c-format -msgid "No I2C device at address: 0x%x" +#: ports/raspberrypi/bindings/wiznet/PIO_SPI.c shared-bindings/async_spi/SPI.c +#: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c +msgid "buffer slices must be of equal length" msgstr "" -#: supervisor/shared/web_workflow/web_workflow.c -msgid "No IP" +#: ports/raspberrypi/common-hal/alarm/touch/TouchAlarm.c +#: ports/stm/common-hal/alarm/touch/TouchAlarm.c +msgid "Touch alarms not available" msgstr "" -#: ports/atmel-samd/common-hal/microcontroller/__init__.c -#: ports/cxd56/common-hal/microcontroller/__init__.c -#: ports/mimxrt10xx/common-hal/microcontroller/__init__.c -msgid "No bootloader present" +#: ports/raspberrypi/common-hal/async_spi/SPI.c shared-bindings/emmcio/EMMC.c +msgid "SPI peripheral in use" msgstr "" -#: shared-module/usb/core/Device.c -msgid "No configuration set" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audioi2sin/I2SIn.c +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Cannot use GPIO0..15 together with GPIO32..47" msgstr "" -#: shared-bindings/_bleio/PacketBuffer.c -msgid "No connection: length cannot be determined" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audioi2sin/I2SIn.c +msgid "Bit clock and word select must be sequential GPIO pins" msgstr "" -#: shared-bindings/board/__init__.c -msgid "No default %q bus" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/mcp4822/MCP4822.c +msgid "Too many channels in sample." msgstr "" -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c -#: ports/atmel-samd/common-hal/touchio/TouchIn.c -msgid "No free GCLKs" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +#: ports/raspberrypi/common-hal/mcp4822/MCP4822.c +msgid "Audio source error" msgstr "" -#: shared-bindings/os/__init__.c -msgid "No hardware random available" +#: ports/raspberrypi/common-hal/audioi2sin/I2SIn.c +msgid "%q must be 16, 24, or 32" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "No in in program" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Pins must share PWM slice" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "No in or out in program" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "No DMA pacing timer found" msgstr "" -#: py/objint.c shared-bindings/time/__init__.c -msgid "No long integer support" +#: ports/raspberrypi/common-hal/busio/I2C.c +#: ports/raspberrypi/common-hal/i2ctarget/I2CTarget.c +msgid "I2C peripheral in use" msgstr "" -#: shared-bindings/wifi/Radio.c -msgid "No network with that ssid" +#: ports/raspberrypi/common-hal/busio/UART.c +msgid "UART peripheral in use" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "No out in program" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "Pin must be on PWM Channel B" msgstr "" -#: ports/atmel-samd/common-hal/busio/I2C.c -#: ports/espressif/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nordic/common-hal/busio/I2C.c -#: ports/raspberrypi/common-hal/busio/I2C.c -msgid "No pull up found on SDA or SCL; check your wiring" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "RISE_AND_FALL not available on this chip" msgstr "" -#: shared-module/touchio/TouchIn.c -msgid "No pulldown on pin; 1Mohm recommended" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice already in use" msgstr "" -#: py/moderrno.c -msgid "No space left on device" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice channel A already in use" msgstr "" -#: py/moderrno.c -msgid "No such device" +#: ports/raspberrypi/common-hal/floppyio/__init__.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#: ports/raspberrypi/common-hal/usb_host/Port.c +msgid "All state machines in use" msgstr "" -#: py/moderrno.c -msgid "No such file/directory" +#: ports/raspberrypi/common-hal/floppyio/__init__.c +msgid "timeout waiting for flux" msgstr "" -#: shared-module/rgbmatrix/RGBMatrix.c -msgid "No timer available" +#: ports/raspberrypi/common-hal/floppyio/__init__.c +#: shared-module/floppyio/__init__.c +msgid "timeout waiting for index pulse" msgstr "" -#: shared-module/usb/core/Device.c -msgid "No usb host port initialized" +#: ports/raspberrypi/common-hal/imagecapture/ParallelImageCapture.c +msgid "Pins must be sequential" msgstr "" -#: ports/nordic/common-hal/_bleio/__init__.c -msgid "Nordic system firmware out of memory" +#: ports/raspberrypi/common-hal/mcp4822/MCP4822.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c +#: shared-module/aurora_epaper/aurora_framebuffer.c +msgid "Invalid %q and %q" msgstr "" -#: shared-bindings/ipaddress/IPv4Address.c shared-bindings/ipaddress/__init__.c -msgid "Not a valid IP string" +#: ports/raspberrypi/common-hal/mdns/Server.c +msgid "Out of MDNS service slots" msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -#: ports/nordic/common-hal/_bleio/__init__.c -#: shared-bindings/_bleio/CharacteristicBuffer.c -msgid "Not connected" +#: ports/raspberrypi/common-hal/memorymap/AddressRange.c +msgid "Unable to access unaligned IO register" msgstr "" -#: shared-bindings/audiobusio/I2SOut.c shared-bindings/audioio/AudioOut.c -#: shared-bindings/audiopwmio/PWMAudioOut.c -msgid "Not playing" +#: ports/raspberrypi/common-hal/memorymap/AddressRange.c +msgid "Unable to write to read-only memory" msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "Not supported JPEG standard" +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c +msgid "All timers for this pin are in use" msgstr "" -#: ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/espressif/common-hal/sdioio/SDCard.c -#, c-format -msgid "Number of data_pins must be %d or %d, not %d" +#: ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c +msgid "Pins must be sequential GPIO pins" msgstr "" -#: shared-bindings/util.c -msgid "" -"Object has been deinitialized and can no longer be used. Create a new object." +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Pin count too large" msgstr "" -#: ports/nordic/common-hal/busio/UART.c -msgid "Odd parity is not supported" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing jmp_pin. %q[%u] jumps on pin" msgstr "" -#: supervisor/shared/bluetooth/bluetooth.c -msgid "Off" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "%q[%u] uses extra pin" msgstr "" -#: supervisor/shared/bluetooth/bluetooth.c -msgid "Ok" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_in_pin. %q[%u] waits based on pin" msgstr "" -#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c -#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c -#, c-format -msgid "Only 8 or 16 bit mono with %dx oversampling supported." +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "%q[%u] waits on input outside of count" msgstr "" -#: ports/espressif/common-hal/wifi/__init__.c -#: ports/raspberrypi/common-hal/wifi/__init__.c -msgid "Only IPv4 addresses supported" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_in_pin. %q[%u] shifts in from pin(s)" msgstr "" -#: ports/raspberrypi/common-hal/socketpool/Socket.c -msgid "Only IPv4 sockets supported" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "%q[%u] shifts in more bits than pin count" msgstr "" -#: shared-module/displayio/OnDiskBitmap.c -#, c-format -msgid "" -"Only Windows format, uncompressed BMP supported: given header size is %d" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_out_pin. %q[%u] shifts out to pin(s)" msgstr "" -#: shared-bindings/_bleio/Adapter.c -msgid "Only connectable advertisements can be directed" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "%q[%u] shifts out more bits than pin count" msgstr "" -#: ports/stm/common-hal/alarm/pin/PinAlarm.c -msgid "Only edge detection is available on this hardware" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_set_pin. %q[%u] sets pin(s)" msgstr "" -#: shared-bindings/ipaddress/__init__.c -msgid "Only int or string supported for ip" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_out_pin. %q[%u] writes pin(s)" msgstr "" -#: ports/espressif/common-hal/alarm/touch/TouchAlarm.c -msgid "Only one %q can be set in deep sleep." +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_in_pin. %q[%u] reads pin(s)" msgstr "" -#: ports/espressif/common-hal/espulp/ULPAlarm.c -msgid "Only one %q can be set." +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Program does IN without loading ISR" msgstr "" -#: ports/espressif/common-hal/i2ctarget/I2CTarget.c -#: ports/raspberrypi/common-hal/i2ctarget/I2CTarget.c -msgid "Only one address is allowed" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Program does OUT without loading OSR" msgstr "" -#: ports/atmel-samd/common-hal/alarm/time/TimeAlarm.c -#: ports/nordic/common-hal/alarm/time/TimeAlarm.c -#: ports/stm/common-hal/alarm/time/TimeAlarm.c -msgid "Only one alarm.time alarm can be set" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin state conflicts with initial out pin state" msgstr "" -#: ports/espressif/common-hal/alarm/time/TimeAlarm.c -#: ports/raspberrypi/common-hal/alarm/time/TimeAlarm.c -msgid "Only one alarm.time alarm can be set." +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin direction conflicts with initial out pin direction" msgstr "" -#: shared-module/displayio/ColorConverter.c -msgid "Only one color can be transparent at a time" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "pull masks conflict with direction masks" msgstr "" -#: py/moderrno.c -msgid "Operation not permitted" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No out in program" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Operation or feature not supported" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in in program" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Operation timed out" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in or out in program" msgstr "" -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "Out of MDNS service slots" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Mismatched swap flag" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Out of memory" +#: ports/raspberrypi/common-hal/sdioio/SDCard.c +#, c-format +msgid "Number of data_pins must be %d, not %d" msgstr "" -#: ports/espressif/common-hal/socketpool/Socket.c -#: ports/raspberrypi/common-hal/socketpool/Socket.c -#: ports/zephyr-cp/common-hal/socketpool/Socket.c -msgid "Out of sockets" +#: ports/raspberrypi/common-hal/sdioio/SDCard.c +msgid "Data pins must be consecutive" msgstr "" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "Out-buffer elements must be <= 4 bytes long" +#: ports/raspberrypi/common-hal/socketpool/Socket.c +msgid "Only IPv4 sockets supported" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "PWM restart" +#: ports/raspberrypi/common-hal/socketpool/SocketPool.c +msgid "SocketPool can only be used with wifi.radio" msgstr "" -#: ports/raspberrypi/common-hal/countio/Counter.c -msgid "PWM slice already in use" +#: ports/raspberrypi/common-hal/usb_host/Port.c +msgid "All dma channels in use" msgstr "" -#: ports/raspberrypi/common-hal/countio/Counter.c -msgid "PWM slice channel A already in use" +#: ports/raspberrypi/common-hal/wifi/Monitor.c +msgid "wifi.Monitor not available" msgstr "" -#: shared-bindings/spitarget/SPITarget.c -msgid "Packet buffers for an SPI transfer must have the same length." +#: ports/raspberrypi/common-hal/wifi/Radio.c +msgid "%q is read-only for this board" msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "Parameter error" +#: ports/raspberrypi/common-hal/wifi/Radio.c +msgid "AP could not be started" msgstr "" -#: ports/espressif/common-hal/audiobusio/__init__.c -msgid "Peripheral in use" +#: ports/stm/common-hal/alarm/pin/PinAlarm.c +msgid "Only edge detection is available on this hardware" msgstr "" -#: py/moderrno.c -msgid "Permission denied" +#: ports/stm/common-hal/alarm/pin/PinAlarm.c +#: ports/stm/common-hal/pulseio/PulseIn.c +msgid "Pin interrupt already in use" msgstr "" #: ports/stm/common-hal/alarm/pin/PinAlarm.c msgid "Pin cannot wake from Deep Sleep" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Pin count too large" -msgstr "" - #: ports/stm/common-hal/alarm/pin/PinAlarm.c -#: ports/stm/common-hal/pulseio/PulseIn.c -msgid "Pin interrupt already in use" +msgid "Deep sleep pins must use a rising edge with pulldown" msgstr "" -#: shared-bindings/adafruit_bus_device/spi_device/SPIDevice.c -msgid "Pin is input only" +#: ports/stm/common-hal/analogio/AnalogIn.c +msgid "Invalid ADC Unit value" msgstr "" -#: ports/raspberrypi/common-hal/countio/Counter.c -msgid "Pin must be on PWM Channel B" +#: ports/stm/common-hal/analogio/AnalogOut.c +#: ports/stm/common-hal/audioio/AudioOut.c +msgid "DAC Device Init Error" msgstr "" -#: 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" +#: ports/stm/common-hal/analogio/AnalogOut.c +#: ports/stm/common-hal/audioio/AudioOut.c +msgid "DAC Channel Init Error" msgstr "" -#: ports/raspberrypi/common-hal/imagecapture/ParallelImageCapture.c -msgid "Pins must be sequential" +#: ports/stm/common-hal/audiobusio/PDMIn.c +msgid "only mono is supported" msgstr "" -#: ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c -msgid "Pins must be sequential GPIO pins" +#: ports/stm/common-hal/audiobusio/PDMIn.c +msgid "only oversample=64 is supported" msgstr "" -#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c -msgid "Pins must share PWM slice" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Another PWMAudioOut is already active" msgstr "" -#: shared-module/usb/core/Device.c -msgid "Pipe error" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +#, c-format +msgid "Buffer length %d too big. It must be less than %d" msgstr "" -#: py/builtinhelp.c -msgid "Plus any modules on the filesystem\n" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Failed to buffer the sample" msgstr "" -#: shared-module/vectorio/Polygon.c -msgid "Polygon needs at least 3 points" +#: ports/stm/common-hal/busio/I2C.c +msgid "I2C init error" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Power dipped. Make sure you are providing enough power." +#: ports/stm/common-hal/busio/SPI.c +msgid "SPI init error" msgstr "" -#: shared-bindings/_bleio/Adapter.c -msgid "Prefix buffer must be on the heap" +#: ports/stm/common-hal/busio/SPI.c +msgid "SPI re-init" msgstr "" -#: main.c -msgid "Press any key to enter the REPL. Use CTRL-D to reload.\n" +#: ports/stm/common-hal/busio/UART.c +msgid "Internal define error" msgstr "" -#: main.c -msgid "Pretending to deep sleep until alarm, CTRL-C or file write.\n" +#: ports/stm/common-hal/busio/UART.c +msgid "Could not start interrupt, RX busy" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Program does IN without loading ISR" +#: ports/stm/common-hal/busio/UART.c +msgid "UART write" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Program does OUT without loading OSR" +#: ports/stm/common-hal/busio/UART.c +msgid "UART de-init" msgstr "" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "Program size invalid" +#: ports/stm/common-hal/busio/UART.c +msgid "UART re-init" msgstr "" -#: ports/espressif/common-hal/espulp/ULP.c -msgid "Program too long" +#: ports/stm/common-hal/microcontroller/Processor.c +msgid "Temperature read timed out" msgstr "" -#: shared-bindings/digitalio/DigitalInOut.c -msgid "Pull not used when direction is output." +#: ports/stm/common-hal/microcontroller/Processor.c +msgid "Voltage read timed out" msgstr "" -#: ports/raspberrypi/common-hal/countio/Counter.c -msgid "RISE_AND_FALL not available on this chip" +#: ports/stm/common-hal/os/__init__.c +msgid "RNG Init Error" msgstr "" -#: shared-module/displayio/OnDiskBitmap.c -msgid "RLE-compressed BMP not supported" +#: ports/stm/common-hal/os/__init__.c +msgid "Random number generation error" msgstr "" #: ports/stm/common-hal/os/__init__.c msgid "RNG DeInit Error" msgstr "" -#: ports/stm/common-hal/os/__init__.c -msgid "RNG Init Error" +#: ports/stm/common-hal/pwmio/PWMOut.c +msgid "timer re-init" msgstr "" -#: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c -#: ports/nordic/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c -msgid "RS485" +#: ports/stm/common-hal/pwmio/PWMOut.c +msgid "channel re-init" msgstr "" -#: ports/espressif/common-hal/busio/UART.c -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "RS485 inversion specified when not in RS485 mode" +#: ports/stm/common-hal/pwmio/PWMOut.c +msgid "PWM restart" msgstr "" -#: shared-bindings/alarm/time/TimeAlarm.c shared-bindings/time/__init__.c -msgid "RTC is not supported on this board" +#: ports/stm/common-hal/sdioio/SDCard.c +#, c-format +msgid "MMC/SDIO Clock Error %x" msgstr "" -#: ports/stm/common-hal/os/__init__.c -msgid "Random number generation error" +#: ports/stm/common-hal/sdioio/SDCard.c +#, c-format +msgid "SDIO GetCardInfo Error %d" msgstr "" -#: shared-bindings/_bleio/__init__.c -#: shared-bindings/memorymonitor/AllocationSize.c -#: shared-bindings/pulseio/PulseIn.c shared-module/bitmaptools/__init__.c -#: shared-module/displayio/Bitmap.c shared-module/displayio/Group.c -msgid "Read-only" +#: ports/zephyr-cp/bindings/zephyr_display/Display.c +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/epaperdisplay/EPaperDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +#: shared-bindings/mipidsi/Display.c +msgid "Display rotation must be in 90 degree increments" msgstr "" -#: extmod/vfs_fat.c py/moderrno.c -msgid "Read-only filesystem" +#: ports/zephyr-cp/bindings/zephyr_display/Display.c +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/epaperdisplay/EPaperDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +msgid ".show(x) removed. Use .root_group = x" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Received response was invalid" +#: ports/zephyr-cp/bindings/zephyr_display/Display.c +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +msgid "Brightness not adjustable" msgstr "" -#: supervisor/shared/bluetooth/bluetooth.c -msgid "Reconnecting" +#: ports/zephyr-cp/bindings/zephyr_display/Display.c py/argcheck.c +#: shared-bindings/busdisplay/BusDisplay.c shared-bindings/displayio/Bitmap.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +#: shared-bindings/is31fl3741/FrameBuffer.c +#: shared-bindings/rgbmatrix/RGBMatrix.c +msgid "%q must be %d-%d" msgstr "" -#: shared-bindings/epaperdisplay/EPaperDisplay.c -msgid "Refresh too soon" +#: ports/zephyr-cp/bindings/zephyr_display/Display.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +#: shared-module/busdisplay/legacy/BusDisplay.c +#: shared-module/framebufferio/legacy/FramebufferDisplay.c +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "Group already used" msgstr "" -#: shared-bindings/canio/RemoteTransmissionRequest.c -msgid "RemoteTransmissionRequests limited to 8 bytes" +#: ports/zephyr-cp/common-hal/_bleio/Adapter.c +msgid "Invalid advertising data" msgstr "" -#: shared-bindings/aesio/aes.c -msgid "Requested AES mode is unsupported" +#: ports/zephyr-cp/common-hal/async_spi/SPI.c +#: ports/zephyr-cp/common-hal/audiobusio/I2SOut.c +#: ports/zephyr-cp/common-hal/busio/I2C.c +#: ports/zephyr-cp/common-hal/busio/UART.c +msgid "Use device tree to define %q devices" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Requested resource not found" +#: ports/zephyr-cp/common-hal/mii/Ethernet.c +msgid "cannot construct ethernet interfaces; use board.ETHERNET" msgstr "" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c -msgid "Right channel unsupported" +#: ports/zephyr-cp/common-hal/socketpool/SocketPool.c +msgid "SocketPool can only be used with %q.%q, %q.%q, or %q.%q" msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "Right format but not supported" +#: ports/zephyr-cp/common-hal/usb_hid/Device.c shared-module/usb_hid/Device.c +msgid "USB error" msgstr "" -#: main.c -msgid "Running in safe mode! Not running saved code.\n" +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "Failed to set hostname" msgstr "" -#: shared-module/sdcardio/SDCard.c -msgid "SD card CSD format not supported" +#: ports/zephyr-cp/common-hal/zephyr_display/legacy/Display.c +#: ports/zephyr-cp/common-hal/zephyr_display/lvgl/Display.c +#: shared-module/busdisplay/legacy/BusDisplay.c +#: shared-module/framebufferio/legacy/FramebufferDisplay.c +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "Below minimum frame rate" msgstr "" -#: ports/cxd56/common-hal/sdioio/SDCard.c -msgid "SDCard init" +#: py/argcheck.c +msgid "function doesn't take keyword arguments" msgstr "" -#: ports/stm/common-hal/sdioio/SDCard.c +#: py/argcheck.c py/bc.c py/objnamedtuple.c shared-bindings/_eve/__init__.c +#: shared-bindings/time/__init__.c #, c-format -msgid "SDIO GetCardInfo Error %d" +msgid "function takes %d positional arguments but %d were given" msgstr "" -#: ports/espressif/common-hal/sdioio/SDCard.c -#: ports/stm/common-hal/sdioio/SDCard.c +#: py/argcheck.c #, c-format -msgid "SDIO Init Error %x" +msgid "function missing %d required positional arguments" msgstr "" -#: ports/espressif/common-hal/busio/SPI.c -msgid "SPI configuration failed" +#: py/argcheck.c +#, c-format +msgid "function expected at most %d arguments, got %d" msgstr "" -#: ports/stm/common-hal/busio/SPI.c -msgid "SPI init error" +#: py/argcheck.c shared-bindings/wifi/Radio.c +msgid "'%q' argument required" msgstr "" -#: ports/raspberrypi/common-hal/busio/SPI.c -msgid "SPI peripheral in use" +#: py/argcheck.c +msgid "extra positional arguments given" msgstr "" -#: ports/stm/common-hal/busio/SPI.c -msgid "SPI re-init" +#: py/argcheck.c py/bc.c py/objnamedtuple.c +#: shared-bindings/traceback/__init__.c +msgid "unexpected keyword argument '%q'" msgstr "" -#: shared-bindings/is31fl3741/FrameBuffer.c -msgid "Scale dimensions must divide by 3" +#: py/argcheck.c +msgid "extra keyword arguments given" msgstr "" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Scan already in progress. Stop with stop_scan." +#: py/argcheck.c shared-bindings/_stage/__init__.c +#: shared-bindings/digitalio/DigitalInOut.c shared-bindings/picogame/__init__.c +msgid "argument num/types mismatch" msgstr "" -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c -msgid "Serializer in use" +#: py/argcheck.c +msgid "keyword argument(s) not implemented - use normal args instead" msgstr "" -#: shared-bindings/ssl/SSLContext.c -msgid "Server side context cannot have hostname" +#: py/argcheck.c +msgid "%q must be %d" msgstr "" -#: ports/cxd56/common-hal/camera/Camera.c -msgid "Size not supported" +#: py/argcheck.c +msgid "%q must be >= %d" +msgstr "" + +#: py/argcheck.c shared-bindings/gifio/GifWriter.c +#: shared-module/_airlift/__init__.c +msgid "%q must be <= %d" msgstr "" -#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c -#: shared-bindings/nvm/ByteArray.c -msgid "Slice and value different lengths." +#: py/argcheck.c py/runtime.c shared-bindings/bitmapfilter/__init__.c +#: shared-module/audiodelays/MultiTapDelay.c shared-module/synthio/Note.c +#: shared-module/synthio/__init__.c +msgid "%q must be of type %q, not %q" msgstr "" -#: 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" +#: py/argcheck.c +msgid "%q length must be %d-%d" msgstr "" -#: ports/espressif/common-hal/socketpool/SocketPool.c -#: ports/raspberrypi/common-hal/socketpool/SocketPool.c -#: ports/zephyr-cp/common-hal/socketpool/SocketPool.c -msgid "SocketPool can only be used with wifi.radio" +#: py/argcheck.c +msgid "%q length must be >= %d" msgstr "" -#: shared-bindings/aesio/aes.c -msgid "Source and destination buffers must be the same length" +#: py/argcheck.c shared-module/_airlift/__init__.c +msgid "%q length must be <= %d" msgstr "" -#: shared-bindings/paralleldisplaybus/ParallelBus.c -msgid "Specify exactly one of data0 or data_pins" +#: py/argcheck.c shared-bindings/usb_hid/Device.c +msgid "%q length must be %d" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Stack overflow. Increase stack size." +#: py/argcheck.c shared-module/audiofilters/__init__.c +msgid "%q in %q must be of type %q, not %q" msgstr "" -#: shared-bindings/alarm/time/TimeAlarm.c -msgid "Supply one of monotonic_time or epoch_time" +#: py/asmthumb.c +msgid "too many locals for native method" msgstr "" -#: shared-bindings/gnss/GNSS.c -msgid "System entry must be gnss.SatelliteSystem" +#: py/asmxtensa.c +msgid "ERROR: xtensa %q out of range" msgstr "" -#: ports/stm/common-hal/microcontroller/Processor.c -msgid "Temperature read timed out" +#: py/asmxtensa.c +msgid "ERROR: %q %q not word-aligned" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "The `microcontroller` module was used to boot into safe mode." +#: py/bc.c py/objnamedtuple.c +msgid "%q() takes %d positional arguments but %d were given" msgstr "" -#: py/obj.c -msgid "The above exception was the direct cause of the following exception:" +#: py/bc.c py/objnamedtuple.c +msgid "function got multiple values for argument '%q'" msgstr "" -#: shared-bindings/rgbmatrix/RGBMatrix.c -msgid "The length of rgb_pins must be 6, 12, 18, 24, or 30" +#: py/bc.c +msgid "unexpected keyword argument" msgstr "" -#: shared-module/audiocore/__init__.c -msgid "The sample's %q does not match" +#: py/bc.c +#, c-format +msgid "function missing required positional argument #%d" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Third-party firmware fatal error." +#: py/bc.c +msgid "function missing required keyword argument '%q'" msgstr "" -#: shared-module/imagecapture/ParallelImageCapture.c -msgid "This microcontroller does not support continuous capture." +#: py/bc.c +msgid "function missing keyword-only argument" msgstr "" -#: shared-module/paralleldisplaybus/ParallelBus.c -msgid "" -"This microcontroller only supports data0=, not data_pins=, because it " -"requires contiguous pins." +#: py/binary.c py/objarray.c +msgid "bad typecode" msgstr "" -#: shared-bindings/displayio/TileGrid.c -msgid "Tile height must exactly divide bitmap height" +#: py/binary.c +msgid "integer out of range" msgstr "" -#: shared-bindings/displayio/TileGrid.c shared-module/displayio/TileGrid.c -msgid "Tile index out of bounds" +#: py/builtinevex.c +msgid "bad compile mode" msgstr "" -#: shared-bindings/displayio/TileGrid.c -msgid "Tile width must exactly divide bitmap width" +#: py/builtinhelp.c +msgid "Plus any modules on the filesystem\n" msgstr "" -#: shared-bindings/alarm/time/TimeAlarm.c -msgid "Time is in the past." +#: py/builtinhelp.c +msgid "object " msgstr "" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -#, c-format -msgid "Timeout is too long: Maximum timeout length is %d seconds" +#: py/builtinhelp.c +msgid " is of type %q\n" msgstr "" -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -msgid "Too many channels in sample" +#: py/builtinhelp.c +#, c-format +msgid "" +"Welcome to Adafruit CircuitPython %s!\n" +"\n" +"Visit circuitpython.org for more information.\n" +"\n" +"To list built-in modules type `help(\"modules\")`.\n" msgstr "" -#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c -msgid "Too many channels in sample." +#: py/builtinimport.c +msgid "script compilation not supported" msgstr "" -#: ports/espressif/common-hal/_bleio/Characteristic.c -msgid "Too many descriptors" +#: py/builtinimport.c +msgid "can't perform relative import" msgstr "" -#: shared-module/displayio/__init__.c -msgid "Too many display busses; forgot displayio.release_displays() ?" +#: py/builtinimport.c +msgid "module not found" msgstr "" -#: shared-module/displayio/__init__.c -msgid "Too many displays" +#: py/builtinimport.c +msgid "no module named '%q'" msgstr "" -#: ports/espressif/common-hal/_bleio/PacketBuffer.c -#: ports/nordic/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than %q" +#: py/builtinimport.c +msgid "relative import" msgstr "" -#: ports/raspberrypi/common-hal/alarm/touch/TouchAlarm.c -#: ports/stm/common-hal/alarm/touch/TouchAlarm.c -msgid "Touch alarms not available" +#: py/compile.c +msgid "can't assign to expression" msgstr "" -#: py/obj.c -msgid "Traceback (most recent call last):\n" +#: py/compile.c +msgid "multiple *x in assignment" msgstr "" -#: ports/stm/common-hal/busio/UART.c -msgid "UART de-init" +#: py/compile.c +msgid "non-default argument follows default argument" msgstr "" -#: ports/cxd56/common-hal/busio/UART.c ports/espressif/common-hal/busio/UART.c -#: ports/stm/common-hal/busio/UART.c -msgid "UART init" +#: py/compile.c +msgid "invalid micropython decorator" msgstr "" -#: ports/raspberrypi/common-hal/busio/UART.c -msgid "UART peripheral in use" +#: py/compile.c +msgid "invalid arch" msgstr "" -#: ports/stm/common-hal/busio/UART.c -msgid "UART re-init" +#: py/compile.c +msgid "can't delete expression" msgstr "" -#: ports/stm/common-hal/busio/UART.c -msgid "UART write" +#: py/compile.c +msgid "'break'/'continue' outside loop" msgstr "" -#: main.c -msgid "UID:" +#: py/compile.c +msgid "'return' outside function" msgstr "" -#: shared-module/usb_hid/Device.c -msgid "USB busy" +#: py/compile.c +msgid "import * not at module level" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "USB devices need more endpoints than are available." +#: py/compile.c +msgid "identifier redefined as global" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "USB devices specify too many interface names." +#: py/compile.c +msgid "no binding for nonlocal found" msgstr "" -#: shared-module/usb_hid/Device.c -msgid "USB error" +#: py/compile.c +msgid "identifier redefined as nonlocal" msgstr "" -#: shared-bindings/_bleio/UUID.c -msgid "UUID integer value must be 0-0xffff" +#: py/compile.c +msgid "can't declare nonlocal in outer code" msgstr "" -#: shared-bindings/_bleio/UUID.c -msgid "UUID string not 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'" +#: py/compile.c +msgid "default 'except' must be last" msgstr "" -#: shared-bindings/_bleio/UUID.c -msgid "UUID value is not str, int or byte buffer" +#: py/compile.c +msgid "async for/with outside async function" msgstr "" -#: ports/raspberrypi/common-hal/memorymap/AddressRange.c -msgid "Unable to access unaligned IO register" +#: py/compile.c +msgid "*x must be assignment target" 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" +#: py/compile.c +msgid "super() can't find self" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Unable to allocate to the heap." +#: py/compile.c +msgid "* arg after **" msgstr "" -#: ports/espressif/common-hal/busio/I2C.c -msgid "Unable to create lock" +#: py/compile.c +msgid "* arg after kwarg" msgstr "" -#: shared-module/i2cdisplaybus/I2CDisplayBus.c -#: shared-module/is31fl3741/IS31FL3741.c -#, c-format -msgid "Unable to find I2C Display at %x" +#: py/compile.c +msgid "too many args" msgstr "" -#: py/parse.c -msgid "Unable to init parser" +#: py/compile.c +msgid "LHS of keyword arg must be an id" msgstr "" -#: shared-module/displayio/OnDiskBitmap.c -msgid "Unable to read color palette data" +#: py/compile.c +msgid "positional arg after **" msgstr "" -#: ports/mimxrt10xx/common-hal/canio/CAN.c -msgid "Unable to send CAN Message: all Tx message buffers are busy" +#: py/compile.c +msgid "positional arg after keyword arg" msgstr "" -#: ports/espressif/common-hal/mdns/Server.c -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "Unable to start mDNS query" +#: py/compile.c py/parse.c +msgid "invalid syntax" msgstr "" -#: shared-bindings/nvm/ByteArray.c -msgid "Unable to write to nvm." +#: py/compile.c +msgid "expecting key:value for dict" msgstr "" -#: ports/raspberrypi/common-hal/memorymap/AddressRange.c -msgid "Unable to write to read-only memory" +#: py/compile.c +msgid "expecting just a value for set" msgstr "" -#: shared-bindings/alarm/SleepMemory.c -msgid "Unable to write to sleep_memory." +#: py/compile.c +msgid "'yield' outside function" msgstr "" -#: ports/nordic/common-hal/_bleio/UUID.c -msgid "Unexpected nrfx uuid type" +#: py/compile.c +msgid "'yield from' inside async function" msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown BLE error at %s:%d: %d" +#: py/compile.c +msgid "'await' outside function" msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown BLE error: %d" +#: py/compile.c +msgid "unknown type '%q'" msgstr "" -#: ports/espressif/common-hal/max3421e/Max3421E.c -#: ports/raspberrypi/common-hal/wifi/__init__.c -#, c-format -msgid "Unknown error code %d" +#: py/compile.c +msgid "annotation must be an identifier" msgstr "" -#: shared-bindings/wifi/Radio.c -#, c-format -msgid "Unknown failure %d" +#: py/compile.c +msgid "argument name reused" msgstr "" -#: ports/nordic/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown gatt error: 0x%04x" +#: py/compile.c +msgid "inline assembler must be a function" msgstr "" -#: ports/atmel-samd/common-hal/alarm/pin/PinAlarm.c -#: supervisor/shared/safe_mode.c -msgid "Unknown reason." +#: py/compile.c +msgid "unknown type" msgstr "" -#: ports/nordic/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown security error: 0x%04x" +#: py/compile.c +msgid "return annotation must be an identifier" msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown system firmware error at %s:%d: %d" +#: py/compile.c +msgid "expecting an assembler instruction" msgstr "" -#: ports/nordic/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown system firmware error: %04x" +#: py/compile.c +msgid "'label' requires 1 argument" msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown system firmware error: %d" +#: py/compile.c +msgid "label redefined" msgstr "" -#: shared-bindings/adafruit_pixelbuf/PixelBuf.c -#: shared-module/_pixelmap/PixelMap.c -#, c-format -msgid "Unmatched number of items on RHS (expected %d, got %d)." +#: py/compile.c +msgid "'align' requires 1 argument" msgstr "" -#: ports/nordic/common-hal/_bleio/__init__.c -msgid "" -"Unspecified issue. Can be that the pairing prompt on the other device was " -"declined or ignored." +#: py/compile.c +msgid "'data' requires at least 2 arguments" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "Unsupported colorspace" +#: py/compile.c +msgid "'data' requires integer arguments" msgstr "" -#: shared-module/displayio/bus_core.c -msgid "Unsupported display bus type" +#: py/compile.c +msgid "cannot emit native code for this architecture" msgstr "" -#: shared-module/audiocore/WaveFile.c -msgid "Unsupported format" +#: py/emitbc.c +msgid "bytecode overflow" msgstr "" -#: shared-bindings/hashlib/__init__.c -msgid "Unsupported hash algorithm" +#: py/emitinlinerv32.c +msgid "can only have up to 4 parameters for RV32 assembly" msgstr "" -#: ports/espressif/common-hal/socketpool/Socket.c -#: ports/zephyr-cp/common-hal/socketpool/Socket.c -msgid "Unsupported socket type" +#: py/emitinlinerv32.c +msgid "parameters must be registers in sequence a0 to a3" msgstr "" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/espressif/common-hal/dualbank/__init__.c -msgid "Update failed" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: expecting %q" msgstr "" -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Descriptor.c -msgid "Value length != required fixed length" +#: py/emitinlinerv32.c +msgid "opcode '%q': expecting %d arguments" msgstr "" -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Descriptor.c -msgid "Value length > max_length" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: out of range" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Version was invalid" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: unknown register" msgstr "" -#: ports/stm/common-hal/microcontroller/Processor.c -msgid "Voltage read timed out" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: undefined label '%q'" msgstr "" -#: main.c -msgid "WARNING: Your code filename has two extensions\n" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: must not be zero" msgstr "" -#: ports/nordic/common-hal/watchdog/WatchDogTimer.c -msgid "WatchDogTimer cannot be deinitialized once mode is set to RESET" +#: py/emitinlinerv32.c +msgid "opcode '%q': registers must be different" msgstr "" -#: py/builtinhelp.c -#, c-format -msgid "" -"Welcome to Adafruit CircuitPython %s!\n" -"\n" -"Visit circuitpython.org for more information.\n" -"\n" -"To list built-in modules type `help(\"modules\")`.\n" +#: py/emitinlinerv32.c +msgid "opcode '%q': malformed register list" msgstr "" -#: supervisor/shared/web_workflow/web_workflow.c -msgid "Wi-Fi: " +#: py/emitinlinerv32.c +msgid "opcode '%q': invalid stack adjustment" msgstr "" -#: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "Wifi is not enabled" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: wrong register(s)" msgstr "" -#: main.c -msgid "Woken up by alarm.\n" +#: py/emitinlinerv32.c +msgid "invalid RV32 instruction '%q'" msgstr "" -#: ports/espressif/common-hal/_bleio/PacketBuffer.c -#: ports/nordic/common-hal/_bleio/PacketBuffer.c -msgid "Writes not supported on Characteristic" +#: py/emitinlinethumb.c +msgid "can only have up to 4 parameters to Thumb assembly" msgstr "" -#: 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/meowmeow/mpconfigboard.h -msgid "You pressed both buttons at start up." +#: py/emitinlinethumb.c +msgid "parameters must be registers in sequence r0 to r3" msgstr "" -#: ports/espressif/boards/m5stack_core_basic/mpconfigboard.h -#: ports/espressif/boards/m5stack_core_fire/mpconfigboard.h -#: ports/espressif/boards/m5stack_stick_c/mpconfigboard.h -#: ports/espressif/boards/m5stack_stick_c_plus/mpconfigboard.h -#: ports/espressif/boards/m5stack_stick_c_plus2/mpconfigboard.h -msgid "You pressed button A at start up." +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' expects at most r%d" msgstr "" -#: ports/espressif/boards/m5stack_m5paper/mpconfigboard.h -msgid "You pressed button DOWN at start up." +#: py/emitinlinethumb.c py/emitinlinextensa.c +#, c-format +msgid "'%s' expects a register" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "You pressed the BOOT button at start up" +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' expects a special register" msgstr "" -#: ports/espressif/boards/adafruit_feather_esp32c6_4mbflash_nopsram/mpconfigboard.h -#: ports/espressif/boards/adafruit_itsybitsy_esp32/mpconfigboard.h -#: ports/espressif/boards/waveshare_esp32_c6_lcd_1_47/mpconfigboard.h -msgid "You pressed the BOOT button at start up." +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' expects an FPU register" msgstr "" -#: ports/espressif/boards/adafruit_huzzah32_breakout/mpconfigboard.h -msgid "You pressed the GPIO0 button at start up." +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' expects {r0, r1, ...}" msgstr "" -#: ports/espressif/boards/espressif_esp32_lyrat/mpconfigboard.h -msgid "You pressed the Rec button at start up." +#: py/emitinlinethumb.c py/emitinlinextensa.c +#, c-format +msgid "'%s' expects an integer" msgstr "" -#: ports/espressif/boards/adafruit_feather_esp32_v2/mpconfigboard.h -msgid "You pressed the SW38 button at start up." +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' integer 0x%x doesn't fit in mask 0x%x" msgstr "" -#: ports/espressif/boards/hardkernel_odroid_go/mpconfigboard.h -#: ports/espressif/boards/vidi_x/mpconfigboard.h -msgid "You pressed the VOLUME button at start up." +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' expects an address of the form [a, b]" msgstr "" -#: ports/espressif/boards/m5stack_atom_echo/mpconfigboard.h -#: ports/espressif/boards/m5stack_atom_lite/mpconfigboard.h -#: ports/espressif/boards/m5stack_atom_matrix/mpconfigboard.h -#: ports/espressif/boards/m5stack_atom_u/mpconfigboard.h -msgid "You pressed the central button at start up." +#: py/emitinlinethumb.c py/emitinlinextensa.c +#, c-format +msgid "'%s' expects a label" msgstr "" -#: ports/nordic/boards/aramcon2_badge/mpconfigboard.h -msgid "You pressed the left button at start up." +#: py/emitinlinethumb.c py/emitinlinextensa.c +msgid "label '%q' not defined" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "You pressed the reset button during boot." +#: py/emitinlinethumb.c +#, c-format +msgid "unsupported Thumb instruction '%s' with %d arguments" msgstr "" -#: supervisor/shared/micropython.c -msgid "[truncated due to length]" +#: py/emitinlinethumb.c +msgid "branch not in range" msgstr "" -#: py/objtype.c -msgid "__init__() should return None" +#: py/emitinlinextensa.c +msgid "can only have up to 4 parameters to Xtensa assembly" msgstr "" -#: py/objtype.c -#, c-format -msgid "__init__() should return None, not '%s'" +#: py/emitinlinextensa.c +msgid "parameters must be registers in sequence a2 to a5" msgstr "" -#: py/objobject.c -msgid "__new__ arg must be a user-type" +#: py/emitinlinextensa.c +#, c-format +msgid "'%s' integer %d isn't within range %d..%d" msgstr "" -#: extmod/modbinascii.c extmod/modhashlib.c py/objarray.c -msgid "a bytes-like object is required" +#: py/emitinlinextensa.c +#, c-format +msgid "%d is not a multiple of %d" msgstr "" -#: shared-bindings/i2ctarget/I2CTarget.c -msgid "addresses is empty" +#: py/emitinlinextensa.c +#, c-format +msgid "unsupported Xtensa instruction '%s' with %d arguments" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "already playing" +#: py/emitnative.c +msgid "conversion to object" msgstr "" -#: py/compile.c -msgid "annotation must be an identifier" +#: py/emitnative.c +msgid "local '%q' used before type known" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "arange: cannot compute length" +#: py/emitnative.c +msgid "can't load from '%q'" msgstr "" -#: py/modbuiltins.c -msgid "arg is an empty sequence" +#: py/emitnative.c +msgid "can't load with '%q' index" msgstr "" -#: py/objobject.c -msgid "arg must be user-type" +#: py/emitnative.c +msgid "local '%q' has type '%q' but source is '%q'" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "argsort argument must be an ndarray" +#: py/emitnative.c +msgid "can't store '%q'" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "argsort is not implemented for flattened arrays" +#: py/emitnative.c +msgid "can't store to '%q'" msgstr "" -#: extmod/ulab/code/numpy/random/random.c -msgid "argument must be None, an integer or a tuple of integers" +#: py/emitnative.c +msgid "can't store with '%q' index" msgstr "" -#: py/compile.c -msgid "argument name reused" +#: py/emitnative.c +msgid "can't implicitly convert '%q' to 'bool'" msgstr "" -#: py/argcheck.c shared-bindings/_stage/__init__.c -#: shared-bindings/digitalio/DigitalInOut.c -msgid "argument num/types mismatch" +#: py/emitnative.c +msgid "'not' not implemented" msgstr "" -#: extmod/ulab/code/numpy/numerical.c extmod/ulab/code/numpy/transform.c -msgid "arguments must be ndarrays" +#: py/emitnative.c +msgid "can't do unary op of '%q'" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "array and index length must be equal" +#: py/emitnative.c +msgid "div/mod not implemented for uint" msgstr "" -#: extmod/ulab/code/numpy/io/io.c -msgid "array has too many dimensions" +#: py/emitnative.c +msgid "comparison of int and uint" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "array is too big" +#: py/emitnative.c +msgid "binary op %q not implemented" msgstr "" -#: py/objarray.c shared-bindings/alarm/SleepMemory.c -#: shared-bindings/memorymap/AddressRange.c shared-bindings/nvm/ByteArray.c -msgid "array/bytes required on right side" +#: py/emitnative.c +msgid "can't do binary op between '%q' and '%q'" msgstr "" -#: py/asmxtensa.c -msgid "asm overflow" +#: py/emitnative.c +msgid "casting" msgstr "" -#: py/compile.c -msgid "async for/with outside async function" +#: py/emitnative.c +msgid "return expected '%q' but got '%q'" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "attempt to get (arg)min/(arg)max of empty sequence" +#: py/emitnative.c +msgid "native raise" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "attempt to get argmin/argmax of an empty sequence" +#: py/emitnative.c +msgid "must raise an object" msgstr "" -#: py/objstr.c -msgid "attributes not supported" +#: py/emitnative.c +msgid "native yield" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "audio format not supported" +#: py/lexer.c +msgid "unicode name escapes" msgstr "" -#: extmod/ulab/code/ulab_tools.c -msgid "axis is out of bounds" +#: py/modbuiltins.c py/objstr.c +msgid "char not in range(0x110000)" msgstr "" -#: extmod/ulab/code/numpy/numerical.c extmod/ulab/code/ulab_tools.c -msgid "axis must be None, or an integer" +#: py/modbuiltins.c +msgid "chr() arg not in range(256)" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "axis too long" +#: py/modbuiltins.c +msgid "arg is an empty sequence" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "background value out of range of target" +#: py/modbuiltins.c +msgid "ord expects a character" msgstr "" -#: py/builtinevex.c -msgid "bad compile mode" +#: py/modbuiltins.c +#, c-format +msgid "ord() expected a character, but string of length %d found" msgstr "" -#: py/objstr.c -msgid "bad conversion specifier" +#: py/modbuiltins.c +msgid "3-arg pow() not supported" msgstr "" -#: py/objstr.c -msgid "bad format string" +#: py/modbuiltins.c +msgid "must use keyword argument for key function" msgstr "" -#: py/binary.c py/objarray.c -msgid "bad typecode" +#: py/moderrno.c +msgid "Operation not permitted" msgstr "" -#: py/emitnative.c -msgid "binary op %q not implemented" +#: py/moderrno.c +msgid "No such file/directory" msgstr "" -#: ports/espressif/common-hal/audiobusio/PDMIn.c -msgid "bit_depth must be 8, 16, 24, or 32." +#: py/moderrno.c +msgid "Input/output error" msgstr "" -#: shared-module/bitmapfilter/__init__.c -msgid "bitmap size and depth must match" +#: py/moderrno.c +msgid "Permission denied" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "bitmap sizes must match" +#: py/moderrno.c +msgid "File exists" msgstr "" -#: extmod/modrandom.c -msgid "bits must be 32 or less" +#: py/moderrno.c +msgid "No such device" msgstr "" -#: shared-bindings/audiodelays/Echo.c shared-bindings/audiodelays/PitchShift.c -#: shared-bindings/audiofilters/Distortion.c -#: shared-bindings/audiofilters/Filter.c shared-bindings/audiomixer/Mixer.c -msgid "bits_per_sample must be 8 or 16" +#: py/moderrno.c +msgid "No space left on device" msgstr "" -#: py/emitinlinethumb.c -msgid "branch not in range" +#: py/modmath.c shared-bindings/math/__init__.c +msgid "math domain error" msgstr "" -#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c -msgid "buffer is smaller than requested size" +#: py/modmath.c +msgid "negative factorial" msgstr "" -#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c -msgid "buffer size must be a multiple of element size" +#: py/modmicropython.c +msgid "schedule queue full" msgstr "" -#: shared-module/struct/__init__.c -msgid "buffer size must match format" +#: py/modstruct.c shared-bindings/picogame/Bitmap.c +#: shared-bindings/picogame/Canvas.c shared-bindings/picogame/Framebuffer.c +#: shared-module/picogame/__init__.c shared-module/struct/__init__.c +msgid "buffer too small" msgstr "" -#: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c -msgid "buffer slices must be of equal length" +#: py/modstruct.c +#, c-format +msgid "pack expected %d items for packing (got %d)" msgstr "" -#: py/modstruct.c shared-module/struct/__init__.c -msgid "buffer too small" +#: py/modthread.c +msgid "expecting a dict for keyword args" msgstr "" -#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c -msgid "buffer too small for requested bytes" +#: py/modweakref.c +msgid "not a heap object" msgstr "" -#: py/emitbc.c -msgid "bytecode overflow" +#: py/nativeglue.c +msgid "set unsupported" msgstr "" -#: py/objarray.c -msgid "bytes length not a multiple of item size" +#: py/nativeglue.c +msgid "slice unsupported" msgstr "" -#: py/objstr.c -msgid "bytes value out of range" +#: py/nativeglue.c +msgid "float unsupported" msgstr "" -#: ports/atmel-samd/bindings/samd/Clock.c -msgid "calibration is out of range" +#: py/obj.c shared-module/adafruit_pixelbuf/PixelBuf.c +msgid "can't convert %q to %q" msgstr "" -#: ports/atmel-samd/bindings/samd/Clock.c -msgid "calibration is read only" +#: py/obj.c +msgid "During handling of the above exception, another exception occurred:" msgstr "" -#: shared-module/vectorio/Circle.c shared-module/vectorio/Polygon.c -#: shared-module/vectorio/Rectangle.c -msgid "can only have one parent" +#: py/obj.c +msgid "The above exception was the direct cause of the following exception:" msgstr "" -#: py/emitinlinethumb.c -msgid "can only have up to 4 parameters to Thumb assembly" +#: py/obj.c +msgid " File \"%q\", line %d" msgstr "" -#: py/emitinlinextensa.c -msgid "can only have up to 4 parameters to Xtensa assembly" +#: py/obj.c +msgid " File \"%q\"" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "can only specify one unknown dimension" +#: py/obj.c +msgid ", in %q\n" msgstr "" -#: py/objtype.c -msgid "can't add special method to already-subclassed class" +#: py/obj.c +msgid "Traceback (most recent call last):\n" msgstr "" -#: py/compile.c -msgid "can't assign to expression" +#: py/obj.c +msgid "can't convert to float" msgstr "" -#: extmod/modasyncio.c -msgid "can't cancel self" +#: py/obj.c +#, c-format +msgid "can't convert %s to float" msgstr "" -#: py/obj.c shared-module/adafruit_pixelbuf/PixelBuf.c -msgid "can't convert %q to %q" +#: py/obj.c +msgid "can't convert to complex" msgstr "" #: py/obj.c @@ -2668,1481 +3250,1553 @@ msgid "can't convert %s to complex" msgstr "" #: py/obj.c -#, c-format -msgid "can't convert %s to float" +msgid "expected tuple/list" msgstr "" -#: py/objint.c py/runtime.c +#: py/obj.c #, c-format -msgid "can't convert %s to int" +msgid "object '%s' isn't a tuple or list" msgstr "" -#: py/objstr.c -msgid "can't convert '%q' object to %q implicitly" +#: py/obj.c +msgid "tuple/list has wrong length" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "can't convert complex to float" +#: py/obj.c +#, c-format +msgid "requested length %d but object has length %d" msgstr "" #: py/obj.c -msgid "can't convert to complex" +msgid "indices must be integers" msgstr "" #: py/obj.c -msgid "can't convert to float" +msgid "%q indices must be integers, not %s" msgstr "" -#: py/runtime.c -msgid "can't convert to int" +#: py/obj.c +msgid "object has no len" msgstr "" -#: py/objstr.c -msgid "can't convert to str implicitly" +#: py/obj.c +#, c-format +msgid "object of type '%s' has no len()" msgstr "" -#: py/compile.c -msgid "can't declare nonlocal in outer code" +#: py/obj.c +msgid "object doesn't support item deletion" msgstr "" -#: py/compile.c -msgid "can't delete expression" +#: py/obj.c +#, c-format +msgid "'%s' object doesn't support item deletion" msgstr "" -#: py/emitnative.c -msgid "can't do binary op between '%q' and '%q'" +#: py/obj.c +msgid "object isn't subscriptable" msgstr "" -#: py/emitnative.c -msgid "can't do unary op of '%q'" +#: py/obj.c +#, c-format +msgid "'%s' object isn't subscriptable" msgstr "" -#: py/emitnative.c -msgid "can't implicitly convert '%q' to 'bool'" +#: py/obj.c +msgid "object doesn't support item assignment" msgstr "" -#: py/runtime.c -msgid "can't import name %q" +#: py/obj.c +#, c-format +msgid "'%s' object doesn't support item assignment" msgstr "" -#: py/emitnative.c -msgid "can't load from '%q'" +#: py/obj.c +msgid "object with buffer protocol required" msgstr "" -#: py/emitnative.c -msgid "can't load with '%q' index" +#: py/objarray.c +msgid "bytes length not a multiple of item size" msgstr "" -#: py/builtinimport.c -msgid "can't perform relative import" +#: py/objarray.c py/objstr.c +msgid "string argument without an encoding" msgstr "" -#: py/objgenerator.c -msgid "can't send non-None value to a just-started generator" +#: py/objarray.c +msgid "memoryview: length is not a multiple of itemsize" msgstr "" -#: shared-module/sdcardio/SDCard.c -msgid "can't set 512 block size" +#: py/objarray.c py/objstr.c +msgid "substring not found" msgstr "" -#: py/objexcept.c py/objnamedtuple.c -msgid "can't set attribute" +#: py/objarray.c py/objstr.c py/objstrunicode.c py/objtuple.c +#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c +#: shared-bindings/nvm/ByteArray.c +msgid "only slices with step=1 (aka None) are supported" msgstr "" -#: py/runtime.c -msgid "can't set attribute '%q'" +#: py/objarray.c +msgid "lhs and rhs should be compatible" msgstr "" -#: py/emitnative.c -msgid "can't store '%q'" +#: py/objarray.c shared-bindings/alarm/SleepMemory.c +#: shared-bindings/memorymap/AddressRange.c shared-bindings/nvm/ByteArray.c +msgid "array/bytes required on right side" msgstr "" -#: py/emitnative.c -msgid "can't store to '%q'" +#: py/objarray.c +msgid "memoryview offset too large" msgstr "" -#: py/emitnative.c -msgid "can't store with '%q' index" +#: py/objcomplex.c +msgid "can't truncate-divide a complex number" msgstr "" -#: py/objstr.c -msgid "" -"can't switch from automatic field numbering to manual field specification" +#: py/objcomplex.c +msgid "complex divide by zero" msgstr "" -#: py/objstr.c -msgid "" -"can't switch from manual field specification to automatic field numbering" +#: py/objcomplex.c +msgid "0.0 to a complex power" msgstr "" -#: py/objcomplex.c -msgid "can't truncate-divide a complex number" +#: py/objdeque.c +msgid "full" msgstr "" -#: extmod/modasyncio.c -msgid "can't wait" +#: py/objdeque.c +msgid "empty" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "cannot assign new shape" +#: py/objdict.c +msgid "dict update sequence has wrong length" msgstr "" -#: extmod/ulab/code/ndarray_operators.c -msgid "cannot cast output with casting rule" +#: py/objexcept.c py/objnamedtuple.c +msgid "can't set attribute" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "cannot convert complex to dtype" +#: py/objfloat.c py/parsenum.c +msgid "complex values not supported" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "cannot convert complex type" +#: py/objgenerator.c +msgid "generator already executing" msgstr "" -#: py/objtype.c -msgid "cannot create '%q' instances" +#: py/objgenerator.c +msgid "can't send non-None value to a just-started generator" msgstr "" -#: py/objtype.c -msgid "cannot create instance" +#: py/objgenerator.c py/runtime.c +msgid "generator raised StopIteration" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "cannot delete array elements" +#: py/objgenerator.c +msgid "generator ignored GeneratorExit" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "cannot reshape array" +#: py/objint.c py/runtime.c +#, c-format +msgid "can't convert %s to int" msgstr "" -#: py/emitnative.c -msgid "casting" +#: py/objint.c +msgid "float too big" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "channel re-init" +#: py/objint.c shared-bindings/time/__init__.c +msgid "No long integer support" msgstr "" -#: shared-bindings/_stage/Text.c -msgid "chars buffer too small" +#: py/objint.c py/sequence.c +msgid "small int overflow" msgstr "" -#: py/modbuiltins.c -msgid "chr() arg not in range(0x110000)" +#: py/objint.c shared-bindings/_bleio/Connection.c +#: shared-bindings/storage/__init__.c +msgid "%q=%q" msgstr "" -#: py/modbuiltins.c -msgid "chr() arg not in range(256)" +#: py/objint_impl.h +#, c-format +msgid "value would overflow a %d byte buffer" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "clip point must be (x,y) tuple" +#: py/objint_impl.h +msgid "can't convert negative int to unsigned" msgstr "" -#: shared-bindings/msgpack/ExtType.c -msgid "code outside range 0~127" +#: py/objint_longlong.c py/parsenum.c +msgid "result overflows long long storage" msgstr "" -#: shared-bindings/displayio/Palette.c -msgid "color buffer must be 3 bytes (RGB) or 4 bytes (RGB + pad byte)" +#: py/objint_longlong.c py/objint_mpz.c py/runtime.c +msgid "negative shift count" msgstr "" -#: shared-bindings/displayio/Palette.c -msgid "color buffer must be a buffer, tuple, list, or int" +#: py/objint_longlong.c py/objint_mpz.c py/runtime.c +msgid "negative power with no float support" msgstr "" -#: shared-bindings/displayio/Palette.c -msgid "color buffer must be a bytearray or array of type 'b' or 'B'" +#: py/objint_longlong.c py/objint_mpz.c +msgid "overflow converting long int to machine word" msgstr "" -#: shared-bindings/displayio/Palette.c -msgid "color must be between 0x000000 and 0xffffff" +#: py/objint_mpz.c +msgid "pow() with 3 arguments requires integers" msgstr "" -#: py/emitnative.c -msgid "comparison of int and uint" +#: py/objint_mpz.c +msgid "pow() 3rd argument cannot be 0" msgstr "" -#: py/objcomplex.c -msgid "complex divide by zero" +#: py/objobject.c +msgid "__new__ arg must be a user-type" msgstr "" -#: py/objfloat.c py/parsenum.c -msgid "complex values not supported" +#: py/objobject.c +msgid "arg must be user-type" msgstr "" -#: extmod/modzlib.c -msgid "compression header" +#: py/objrange.c py/objslice.c shared-bindings/random/__init__.c +msgid "%q step cannot be zero" msgstr "" -#: py/emitnative.c -msgid "conversion to object" +#: py/objslice.c +msgid "Cannot subclass slice" msgstr "" -#: extmod/ulab/code/numpy/filter.c -msgid "convolve arguments must be linear arrays" +#: py/objstr.c +msgid "unknown encoding: %q" msgstr "" -#: extmod/ulab/code/numpy/filter.c -msgid "convolve arguments must be ndarrays" +#: py/objstr.c +msgid "bytes value out of range" msgstr "" -#: extmod/ulab/code/numpy/filter.c -msgid "convolve arguments must not be empty" +#: py/objstr.c +msgid "join expects a list of str/bytes objects consistent with self object" msgstr "" -#: extmod/ulab/code/numpy/io/io.c -msgid "corrupted file" +#: py/objstr.c +msgid "empty separator" msgstr "" -#: extmod/ulab/code/numpy/poly.c -msgid "could not invert Vandermonde matrix" +#: py/objstr.c +msgid "rsplit(None,n)" msgstr "" -#: shared-module/sdcardio/SDCard.c -msgid "couldn't determine SD card version" +#: py/objstr.c +msgid "bad format string" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "cross is defined for 1D arrays of length 3" +#: py/objstr.c +#, c-format +msgid "unmatched '%c' in format" msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "data must be iterable" +#: py/objstr.c +msgid "bad conversion specifier" msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "data must be of equal length" +#: py/objstr.c +msgid "end of format while looking for conversion specifier" msgstr "" -#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c +#: py/objstr.c #, c-format -msgid "data pin #%d in use" +msgid "unknown conversion specifier %c" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "data type not understood" +#: py/objstr.c +msgid "expected ':' after format specifier" msgstr "" -#: py/parsenum.c -msgid "decimal numbers not supported" +#: py/objstr.c +msgid "" +"can't switch from automatic field numbering to manual field specification" msgstr "" -#: py/compile.c -msgid "default 'except' must be last" +#: py/objstr.c +msgid "%q index out of range" msgstr "" -#: shared-bindings/msgpack/__init__.c -msgid "default is not a function" +#: py/objstr.c +msgid "attributes not supported" msgstr "" -#: shared-bindings/audiobusio/PDMIn.c +#: py/objstr.c msgid "" -"destination buffer must be a bytearray or array of type 'B' for bit_depth = 8" +"can't switch from manual field specification to automatic field numbering" msgstr "" -#: shared-bindings/audiobusio/PDMIn.c -msgid "destination buffer must be an array of type 'H' for bit_depth = 16" +#: py/objstr.c +msgid "invalid format specifier" msgstr "" -#: py/objdict.c -msgid "dict update sequence has wrong length" +#: py/objstr.c +msgid "sign not allowed in string format specifier" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "diff argument must be an ndarray" +#: py/objstr.c +msgid "sign not allowed with integer format specifier 'c'" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "differentiation order out of range" +#: py/objstr.c +msgid "unknown format code '%c' for object of type '%q'" msgstr "" -#: extmod/ulab/code/numpy/transform.c -msgid "dimensions do not match" +#: py/objstr.c +msgid "'=' alignment not allowed in string format specifier" msgstr "" -#: py/emitnative.c -msgid "div/mod not implemented for uint" +#: py/objstr.c +msgid "format needs a dict" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "divide by zero" +#: py/objstr.c +msgid "incomplete format key" msgstr "" -#: py/runtime.c -msgid "division by zero" +#: py/objstr.c +msgid "incomplete format" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "dtype must be float, or complex" +#: py/objstr.c +msgid "format string needs more arguments" msgstr "" -#: extmod/ulab/code/ndarray_operators.c -msgid "dtype of int32 is not supported" +#: py/objstr.c +#, c-format +msgid "%%c needs int or char" msgstr "" -#: py/objdeque.c -msgid "empty" +#: py/objstr.c +#, c-format +msgid "unsupported format character '%c' (0x%x) at index %d" msgstr "" -#: extmod/ulab/code/numpy/io/io.c -msgid "empty file" +#: py/objstr.c +msgid "format string didn't convert all arguments" msgstr "" -#: extmod/modasyncio.c extmod/modheapq.c -msgid "empty heap" +#: py/objstr.c +msgid "non-hex digit" msgstr "" #: py/objstr.c -msgid "empty separator" +msgid "can't convert to str implicitly" msgstr "" -#: shared-bindings/random/__init__.c -msgid "empty sequence" +#: py/objstr.c +msgid "can't convert '%q' object to %q implicitly" msgstr "" -#: py/objstr.c -msgid "end of format while looking for conversion specifier" +#: py/objstrunicode.c +#, c-format +msgid "string indices must be integers, not %s" msgstr "" -#: shared-bindings/alarm/time/TimeAlarm.c -msgid "epoch_time not supported on this board" +#: py/objstrunicode.c +msgid "string index out of range" msgstr "" -#: ports/nordic/common-hal/busio/UART.c -#, c-format -msgid "error = 0x%08lX" +#: py/objtemplate.c +msgid "expected str or Interpolation" msgstr "" -#: py/runtime.c -msgid "exceptions must derive from BaseException" +#: py/objtype.c +msgid "Call super().__init__() before accessing native object." msgstr "" -#: py/objstr.c -msgid "expected ':' after format specifier" +#: py/objtype.c +msgid "__init__() should return None" msgstr "" -#: py/obj.c -msgid "expected tuple/list" +#: py/objtype.c +#, c-format +msgid "__init__() should return None, not '%s'" msgstr "" -#: py/modthread.c -msgid "expecting a dict for keyword args" +#: py/objtype.c py/runtime.c +msgid "unreadable attribute" msgstr "" -#: py/compile.c -msgid "expecting an assembler instruction" +#: py/objtype.c py/runtime.c +msgid "object not callable" msgstr "" -#: py/compile.c -msgid "expecting just a value for set" +#: py/objtype.c py/runtime.c shared-module/atexit/__init__.c +msgid "'%q' object isn't callable" msgstr "" -#: py/compile.c -msgid "expecting key:value for dict" +#: py/objtype.c +msgid "type takes 1 or 3 arguments" +msgstr "" + +#: py/objtype.c +msgid "can't create instance" +msgstr "" + +#: py/objtype.c +msgid "can't create '%q' instances" +msgstr "" + +#: py/objtype.c +msgid "can't add special method to already-subclassed class" msgstr "" -#: shared-bindings/msgpack/__init__.c -msgid "ext_hook is not a function" +#: py/objtype.c +msgid "type isn't an acceptable base type" msgstr "" -#: py/argcheck.c -msgid "extra keyword arguments given" +#: py/objtype.c +msgid "type '%q' isn't an acceptable base type" msgstr "" -#: py/argcheck.c -msgid "extra positional arguments given" +#: py/objtype.c +msgid "multiple inheritance not supported" msgstr "" -#: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/gifio/OnDiskGif.c -#: shared-bindings/synthio/__init__.c shared-module/gifio/GifWriter.c -msgid "file must be a file opened in byte mode" +#: py/objtype.c +msgid "multiple bases have instance lay-out conflict" msgstr "" -#: shared-bindings/traceback/__init__.c -msgid "file write is not available" +#: py/objtype.c +msgid "first argument to super() must be type" msgstr "" -#: shared-bindings/storage/__init__.c -msgid "filesystem must provide mount method" +#: py/objtype.c +msgid "issubclass() arg 2 must be a class or a tuple of classes" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "first argument must be a callable" +#: py/objtype.c +msgid "issubclass() arg 1 must be a class" msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "first argument must be a function" +#: py/parse.c +msgid "not a constant" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "first argument must be a tuple of ndarrays" +#: py/parse.c +msgid "Unable to init parser" msgstr "" -#: extmod/ulab/code/numpy/transform.c extmod/ulab/code/numpy/vector.c -msgid "first argument must be an ndarray" +#: py/parse.c +msgid "unexpected indent" msgstr "" -#: py/objtype.c -msgid "first argument to super() must be type" +#: py/parse.c +msgid "unindent doesn't match any outer indent level" msgstr "" -#: extmod/ulab/code/scipy/linalg/linalg.c -msgid "first two arguments must be ndarrays" +#: py/parse.c +msgid "malformed f-string" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "flattening order must be either 'C', or 'F'" +#: py/parsenum.c +msgid "invalid syntax for integer" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "flip argument must be an ndarray" +#: py/parsenum.c +#, c-format +msgid "invalid syntax for integer with base %d" msgstr "" -#: py/objint.c -msgid "float too big" +#: py/parsenum.c +msgid "invalid syntax for number" msgstr "" -#: py/nativeglue.c -msgid "float unsupported" +#: py/parsenum.c +msgid "decimal numbers not supported" msgstr "" -#: shared-bindings/_stage/Text.c -msgid "font must be 2048 bytes long" +#: py/persistentcode.c +msgid "incompatible .mpy file" msgstr "" -#: extmod/moddeflate.c -msgid "format" +#: py/persistentcode.c +msgid "MicroPython .mpy file; use CircuitPython mpy-cross" msgstr "" -#: py/objstr.c -msgid "format requires a dict" +#: py/persistentcode.c +msgid "native code in .mpy unsupported" msgstr "" -#: py/objdeque.c -msgid "full" +#: py/persistentcode.c +msgid "incompatible .mpy arch" msgstr "" -#: py/argcheck.c -msgid "function doesn't take keyword arguments" +#: py/persistentcode.c +msgid "function must be bytecode" msgstr "" -#: py/argcheck.c -#, c-format -msgid "function expected at most %d arguments, got %d" +#: py/proto.c shared-bindings/digitalio/DigitalInOutProtocol.c +msgid "'%q' object does not support '%q'" msgstr "" -#: py/bc.c py/objnamedtuple.c -msgid "function got multiple values for argument '%q'" +#: py/qstr.c +msgid "name too long" msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "function has the same sign at the ends of interval" +#: py/runtime.c +msgid "name not defined" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "function is defined for ndarrays only" +#: py/runtime.c +msgid "name '%q' isn't defined" msgstr "" -#: extmod/ulab/code/numpy/carray/carray.c -msgid "function is implemented for ndarrays only" +#: py/runtime.c +msgid "unsupported type for operator" msgstr "" -#: py/argcheck.c -#, c-format -msgid "function missing %d required positional arguments" +#: py/runtime.c +msgid "unsupported type for %q: '%s'" msgstr "" -#: py/bc.c -msgid "function missing keyword-only argument" +#: py/runtime.c +msgid "unsupported types for %q: '%q', '%q'" msgstr "" -#: py/bc.c -msgid "function missing required keyword argument '%q'" +#: py/runtime.c +msgid "wrong number of values to unpack" msgstr "" -#: py/bc.c +#: py/runtime.c #, c-format -msgid "function missing required positional argument #%d" +msgid "need more than %d values to unpack" msgstr "" -#: py/argcheck.c py/bc.c py/objnamedtuple.c shared-bindings/_eve/__init__.c -#: shared-bindings/time/__init__.c +#: py/runtime.c #, c-format -msgid "function takes %d positional arguments but %d were given" +msgid "too many values to unpack (expected %d)" msgstr "" -#: py/objgenerator.c -msgid "generator already executing" +#: py/runtime.c +msgid "type object '%q' has no attribute '%q'" msgstr "" -#: py/objgenerator.c -msgid "generator ignored GeneratorExit" +#: py/runtime.c +msgid "module '%q' has no attribute '%q'" msgstr "" -#: py/objgenerator.c py/runtime.c -msgid "generator raised StopIteration" +#: py/runtime.c +msgid "'%s' object has no attribute '%q'" msgstr "" -#: shared-bindings/_stage/Layer.c -msgid "graphic must be 2048 bytes long" +#: py/runtime.c +msgid "can't set attribute '%q'" msgstr "" -#: extmod/modhashlib.c -msgid "hash is final" +#: py/runtime.c +msgid "object not iterable" msgstr "" -#: extmod/modheapq.c -msgid "heap must be a list" +#: py/runtime.c +msgid "'%q' object isn't iterable" msgstr "" -#: py/compile.c -msgid "identifier redefined as global" +#: py/runtime.c +msgid "object not an iterator" msgstr "" -#: py/compile.c -msgid "identifier redefined as nonlocal" +#: py/runtime.c +msgid "'%q' object isn't an iterator" msgstr "" -#: py/compile.c -msgid "import * not at module level" +#: py/runtime.c +msgid "exceptions must derive from BaseException" msgstr "" -#: py/persistentcode.c -msgid "incompatible .mpy arch" +#: py/runtime.c +msgid "can't import name %q" msgstr "" -#: py/persistentcode.c -msgid "incompatible .mpy file" +#: py/runtime.c +msgid "memory allocation failed, heap is locked" msgstr "" -#: py/objstr.c -msgid "incomplete format" +#: py/runtime.c +#, c-format +msgid "memory allocation failed, allocating %u bytes" msgstr "" -#: py/objstr.c -msgid "incomplete format key" +#: py/runtime.c +msgid "can't convert to int" msgstr "" -#: extmod/modbinascii.c -msgid "incorrect padding" +#: py/runtime.c +msgid "division by zero" msgstr "" -#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/transform.c -msgid "index is out of bounds" +#: py/runtime.c +msgid "maximum recursion depth exceeded" msgstr "" -#: shared-bindings/_pixelmap/PixelMap.c -msgid "index must be tuple or int" +#: py/sequence.c shared-bindings/displayio/Group.c +msgid "object not in sequence" msgstr "" -#: extmod/ulab/code/numpy/numerical.c extmod/ulab/code/ulab_tools.c -#: ports/espressif/common-hal/pulseio/PulseIn.c -#: shared-bindings/bitmaptools/__init__.c -msgid "index out of range" +#: py/stream.c shared-bindings/getpass/__init__.c +msgid "stream operation not supported" msgstr "" -#: py/obj.c -msgid "indices must be integers" +#: py/vm.c +msgid "local variable referenced before assignment" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "indices must be integers, slices, or Boolean lists" +#: py/vm.c +msgid "no active exception to reraise" msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "initial values must be iterable" +#: py/vm.c +msgid "opcode" msgstr "" -#: shared-bindings/_bleio/Characteristic.c shared-bindings/_bleio/Descriptor.c -msgid "initial_value length is wrong" +#: shared-bindings/_bleio/Adapter.c +msgid "Cannot create a new Adapter; use _bleio.adapter;" msgstr "" -#: py/compile.c -msgid "inline assembler must be a function" +#: shared-bindings/_bleio/Adapter.c +msgid "Could not set address" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "input and output dimensions differ" +#: shared-bindings/_bleio/Adapter.c +#, c-format +msgid "interval must be in range %s-%s" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "input and output shapes differ" +#: shared-bindings/_bleio/Adapter.c +msgid "Cannot have scan responses for extended, connectable advertisements." msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "input argument must be an integer, a tuple, or a list" +#: shared-bindings/_bleio/Adapter.c +msgid "Only connectable advertisements can be directed" msgstr "" -#: extmod/ulab/code/numpy/fft/fft_tools.c -msgid "input array length must be power of 2" +#: shared-bindings/_bleio/Adapter.c +msgid "non-zero timeout must be >= interval" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "input arrays are not compatible" +#: shared-bindings/_bleio/Adapter.c +msgid "window must be <= interval" msgstr "" -#: extmod/ulab/code/numpy/poly.c -msgid "input data must be an iterable" +#: shared-bindings/_bleio/Adapter.c +msgid "Prefix buffer must be on the heap" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "input dtype must be float or complex" +#: shared-bindings/_bleio/CharacteristicBuffer.c +msgid "CharacteristicBuffer writing not provided" msgstr "" -#: extmod/ulab/code/numpy/poly.c -msgid "input is not iterable" +#: shared-bindings/_bleio/Connection.c +msgid "" +"Connection has been disconnected and can no longer be used. Create a new " +"connection." msgstr "" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "input matrix is asymmetric" +#: shared-bindings/_bleio/PacketBuffer.c +#, c-format +msgid "Buffer too short by %d bytes" msgstr "" -#: extmod/ulab/code/numpy/linalg/linalg.c -#: extmod/ulab/code/scipy/linalg/linalg.c -msgid "input matrix is singular" +#: shared-bindings/_bleio/PacketBuffer.c +msgid "No connection: length cannot be determined" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "input must be 1- or 2-d" +#: shared-bindings/_bleio/UUID.c +msgid "UUID string not 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'" msgstr "" -#: extmod/ulab/code/numpy/carray/carray.c -msgid "input must be a 1D ndarray" +#: shared-bindings/_bleio/UUID.c +msgid "UUID value is not str, int or byte buffer" msgstr "" -#: extmod/ulab/code/scipy/linalg/linalg.c extmod/ulab/code/user/user.c -msgid "input must be a dense ndarray" +#: shared-bindings/_bleio/UUID.c +msgid "not a 128-bit UUID" msgstr "" -#: extmod/ulab/code/user/user.c shared-bindings/_eve/__init__.c -msgid "input must be an ndarray" +#: shared-bindings/_bleio/__init__.c shared-bindings/emmcio/EMMC.c +#: shared-bindings/memorymonitor/AllocationSize.c +#: shared-bindings/pulseio/PulseIn.c shared-module/bitmaptools/__init__.c +#: shared-module/displayio/legacy/Bitmap.c +#: shared-module/displayio/legacy/Group.c shared-module/displayio/lvgl/Bitmap.c +#: shared-module/displayio/lvgl/Group.c +msgid "Read-only" msgstr "" -#: extmod/ulab/code/numpy/carray/carray.c -msgid "input must be an ndarray, or a scalar" +#: shared-bindings/_pew/PewPew.c +msgid "Incorrect buffer size" msgstr "" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "input must be one-dimensional" +#: shared-bindings/_pixelmap/PixelMap.c +msgid "nested index must be int" msgstr "" -#: extmod/ulab/code/ulab_tools.c -msgid "input must be square matrix" +#: shared-bindings/_pixelmap/PixelMap.c +msgid "index must be tuple or int" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "input must be tuple, list, range, or ndarray" +#: shared-bindings/_stage/Layer.c +msgid "map buffer too small" msgstr "" -#: extmod/ulab/code/numpy/poly.c -msgid "input vectors must be of equal length" +#: shared-bindings/_stage/Text.c +msgid "chars buffer too small" msgstr "" -#: extmod/ulab/code/numpy/approx.c -msgid "interp is defined for 1D iterables of equal length" +#: shared-bindings/adafruit_bus_device/spi_device/SPIDevice.c +msgid "Pin is input only" msgstr "" -#: shared-bindings/_bleio/Adapter.c +#: shared-bindings/adafruit_pixelbuf/PixelBuf.c +#: shared-module/_pixelmap/PixelMap.c #, c-format -msgid "interval must be in range %s-%s" +msgid "Unmatched number of items on RHS (expected %d, got %d)." msgstr "" -#: py/compile.c -msgid "invalid arch" +#: shared-bindings/aesio/aes.c +msgid "Key must be 16, 24, or 32 bytes long" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -#, c-format -msgid "invalid bits_per_pixel %d, must be, 1, 2, 4, 8, 16, 24, or 32" +#: shared-bindings/aesio/aes.c +msgid "Requested AES mode is unsupported" msgstr "" -#: shared-module/ssl/SSLSocket.c -msgid "invalid cert" +#: shared-bindings/aesio/aes.c +msgid "Source and destination buffers must be the same length" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -#, c-format -msgid "invalid element size %d for bits_per_pixel %d\n" +#: shared-bindings/aesio/aes.c +msgid "ECB only operates on 16 bytes at a time" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -#, c-format -msgid "invalid element_size %d, must be, 1, 2, or 4" +#: shared-bindings/aesio/aes.c +msgid "CBC blocks must be multiples of 16 bytes" msgstr "" -#: shared-bindings/traceback/__init__.c -msgid "invalid exception" +#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c +#: shared-bindings/nvm/ByteArray.c +msgid "Slice and value different lengths." msgstr "" -#: py/objstr.c -msgid "invalid format specifier" +#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c +#: shared-bindings/nvm/ByteArray.c +msgid "Array values should be single bytes." msgstr "" -#: shared-bindings/wifi/Radio.c -msgid "invalid hostname" +#: shared-bindings/alarm/SleepMemory.c +msgid "Unable to write to sleep_memory." msgstr "" -#: shared-module/ssl/SSLSocket.c -msgid "invalid key" +#: shared-bindings/alarm/__init__.c +msgid "Expected a kind of %q" msgstr "" -#: py/compile.c -msgid "invalid micropython decorator" +#: shared-bindings/alarm/time/TimeAlarm.c shared-bindings/time/__init__.c +msgid "RTC is not supported on this board" msgstr "" -#: ports/espressif/common-hal/espcamera/Camera.c -msgid "invalid setting" +#: shared-bindings/alarm/time/TimeAlarm.c +msgid "Supply one of monotonic_time or epoch_time" msgstr "" -#: shared-bindings/random/__init__.c -msgid "invalid step" +#: shared-bindings/alarm/time/TimeAlarm.c +msgid "epoch_time not supported on this board" msgstr "" -#: py/compile.c py/parse.c -msgid "invalid syntax" +#: shared-bindings/alarm/time/TimeAlarm.c +msgid "Time is in the past." msgstr "" -#: py/parsenum.c -msgid "invalid syntax for integer" +#: shared-bindings/analogbufio/BufferedIn.c +msgid "%q must be a bytearray or array of type 'H' or 'B'" msgstr "" -#: py/parsenum.c -#, c-format -msgid "invalid syntax for integer with base %d" +#: shared-bindings/audiobusio/PDMIn.c +msgid "%q must be multiple of 8." msgstr "" -#: py/parsenum.c -msgid "invalid syntax for number" +#: shared-bindings/audiobusio/PDMIn.c shared-bindings/audioi2sin/I2SIn.c +#: shared-bindings/usb_host_audio/USBIn.c +msgid "Cannot record to a file" msgstr "" -#: py/objtype.c -msgid "issubclass() arg 1 must be a class" +#: shared-bindings/audiobusio/PDMIn.c shared-bindings/audioi2sin/I2SIn.c +#: shared-bindings/usb_host_audio/USBIn.c +msgid "Destination capacity is smaller than destination_length." msgstr "" -#: py/objtype.c -msgid "issubclass() arg 2 must be a class or a tuple of classes" +#: shared-bindings/audiobusio/PDMIn.c +msgid "destination buffer must be an array of type 'H' for bit_depth = 16" msgstr "" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "iterations did not converge" +#: shared-bindings/audiobusio/PDMIn.c +msgid "" +"destination buffer must be a bytearray or array of type 'B' for bit_depth = 8" msgstr "" -#: py/objstr.c -msgid "join expects a list of str/bytes objects consistent with self object" +#: shared-bindings/audiocore/RawSample.c +msgid "%q must be a bytearray or array of type 'h', 'H', 'b', or 'B'" msgstr "" -#: py/argcheck.c -msgid "keyword argument(s) not implemented - use normal args instead" +#: shared-bindings/audiocore/RawSample.c +msgid "Length of %q must be an even multiple of channel_count * type_size" msgstr "" -#: py/emitinlinethumb.c py/emitinlinextensa.c -msgid "label '%q' not defined" +#: shared-bindings/audiodelays/Chorus.c shared-bindings/audiodelays/Echo.c +#: shared-bindings/audiodelays/Flanger.c +#: shared-bindings/audiodelays/GranularPitchShift.c +#: shared-bindings/audiodelays/MultiTapDelay.c +#: shared-bindings/audiodelays/PitchShift.c +#: shared-bindings/audiofilters/Distortion.c +#: shared-bindings/audiofilters/Filter.c shared-bindings/audiofilters/Phaser.c +#: shared-bindings/audiomixer/Mixer.c shared-module/audiotap/Tap.c +msgid "bits_per_sample must be 8 or 16" msgstr "" -#: py/compile.c -msgid "label redefined" +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "samples_signed must be true" msgstr "" -#: py/objarray.c -msgid "lhs and rhs should be compatible" +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "bits_per_sample must be 16" msgstr "" -#: py/emitnative.c -msgid "local '%q' has type '%q' but source is '%q'" +#: shared-bindings/audioi2sin/I2SIn.c shared-bindings/usb_host_audio/USBIn.c +#, c-format +msgid "invalid destination buffer, must be an array of type: %c" msgstr "" -#: py/emitnative.c -msgid "local '%q' used before type known" +#: shared-bindings/audioio/AudioOut.c shared-bindings/emmcio/EMMC.c +msgid "%q and %q must be different" msgstr "" -#: py/vm.c -msgid "local variable referenced before assignment" +#: shared-bindings/audiomp3/MP3Decoder.c shared-bindings/gifio/OnDiskGif.c +#: shared-bindings/synthio/__init__.c shared-module/gifio/GifWriter.c +msgid "file must be a file opened in byte mode" msgstr "" -#: ports/espressif/common-hal/canio/CAN.c -msgid "loopback + silent mode not supported by peripheral" +#: shared-bindings/bitmapfilter/__init__.c +msgid "" +"weights must be a sequence with an odd square number of elements (usually 9 " +"or 25)" msgstr "" -#: ports/espressif/common-hal/mdns/Server.c -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "mDNS already initialized" +#: shared-bindings/bitmapfilter/__init__.c +msgid "weights must be an object of type %q, %q, %q, or %q, not %q " msgstr "" -#: ports/espressif/common-hal/mdns/Server.c -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "mDNS only works with built-in WiFi" +#: shared-bindings/bitmaptools/__init__.c +msgid "clip point must be (x,y) tuple" msgstr "" -#: py/parse.c -msgid "malformed f-string" +#: shared-bindings/bitmaptools/__init__.c +msgid "source palette too large" msgstr "" -#: shared-bindings/_stage/Layer.c -msgid "map buffer too small" +#: shared-bindings/bitmaptools/__init__.c +msgid "Bitmap size and bits per value must match" msgstr "" -#: py/modmath.c shared-bindings/math/__init__.c -msgid "math domain error" +#: shared-bindings/bitmaptools/__init__.c +msgid "For L8 colorspace, input bitmap must have 8 bits per pixel" msgstr "" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "matrix is not positive definite" +#: shared-bindings/bitmaptools/__init__.c +msgid "For RGB colorspaces, input bitmap must have 16 bits per pixel" msgstr "" -#: ports/espressif/common-hal/_bleio/Descriptor.c -#: ports/nordic/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Descriptor.c -#, c-format -msgid "max_length must be 0-%d when fixed_length is %s" +#: shared-bindings/bitmaptools/__init__.c +msgid "Unsupported colorspace" msgstr "" -#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/random/random.c -msgid "maximum number of dimensions is " +#: shared-bindings/bitmaptools/__init__.c +msgid "Mask bitmap size must match the other bitmaps" msgstr "" -#: py/runtime.c -msgid "maximum recursion depth exceeded" +#: shared-bindings/bitmaptools/__init__.c +msgid "Mask bitmap must have 8 bits per pixel" msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "maxiter must be > 0" +#: shared-bindings/bitmaptools/__init__.c +msgid "out of range of target" msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "maxiter should be > 0" +#: shared-bindings/bitmaptools/__init__.c +msgid "value out of range of target" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "median argument must be an ndarray" +#: shared-bindings/bitmaptools/__init__.c +msgid "background value out of range of target" msgstr "" -#: py/runtime.c -#, c-format -msgid "memory allocation failed, allocating %u bytes" +#: shared-bindings/bitmaptools/__init__.c +msgid "Coordinate arrays types have different sizes" msgstr "" -#: py/runtime.c -msgid "memory allocation failed, heap is locked" +#: shared-bindings/bitmaptools/__init__.c +msgid "Coordinate arrays have different lengths" msgstr "" -#: py/objarray.c -msgid "memoryview offset too large" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element_size %d, must be, 1, 2, or 4" msgstr "" -#: py/objarray.c -msgid "memoryview: length is not a multiple of itemsize" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element size %d for bits_per_pixel %d\n" msgstr "" -#: extmod/modtime.c -msgid "mktime needs a tuple of length 8 or 9" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid bits_per_pixel %d, must be, 1, 2, 4, 8, 16, 24, or 32" msgstr "" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "mode must be complete, or reduced" +#: shared-bindings/bitmaptools/__init__.c +msgid "bitmap sizes must match" msgstr "" -#: py/builtinimport.c -msgid "module not found" +#: shared-bindings/bitmaptools/__init__.c +msgid "source_bitmap must have value_count of 2 or 65536" msgstr "" -#: ports/espressif/common-hal/wifi/Monitor.c -msgid "monitor init failed" +#: shared-bindings/bitmaptools/__init__.c +msgid "source_bitmap must have value_count of 65536" msgstr "" -#: extmod/ulab/code/numpy/poly.c -msgid "more degrees of freedom than data points" +#: shared-bindings/bitmaptools/__init__.c +msgid "source_bitmap must have value_count of 8" msgstr "" -#: py/compile.c -msgid "multiple *x in assignment" +#: shared-bindings/bitmaptools/__init__.c +msgid "unsupported colorspace for dither" msgstr "" -#: py/objtype.c -msgid "multiple bases have instance lay-out conflict" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Input buffer length (%d) must be a multiple of the strand count (%d)" msgstr "" -#: py/objtype.c -msgid "multiple inheritance not supported" +#: shared-bindings/board/__init__.c +msgid "No default %q bus" msgstr "" -#: py/emitnative.c -msgid "must raise an object" +#: shared-bindings/busdisplay/BusDisplay.c +msgid "%q must be 1 when %q is True" msgstr "" -#: py/modbuiltins.c -msgid "must use keyword argument for key function" +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +msgid "Display must have a 16 bit colorspace." msgstr "" -#: py/runtime.c -msgid "name '%q' is not defined" +#: shared-bindings/busio/UART.c shared-bindings/canio/CAN.c +msgid "tx and rx cannot both be None" msgstr "" -#: py/runtime.c -msgid "name not defined" +#: shared-bindings/busio/UART.c shared-bindings/displayio/Group.c +msgid "Must be a %q subclass." msgstr "" -#: py/qstr.c -msgid "name too long" +#: shared-bindings/canio/RemoteTransmissionRequest.c +msgid "RemoteTransmissionRequests limited to 8 bytes" msgstr "" -#: py/persistentcode.c -msgid "native code in .mpy unsupported" +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/ec/EllipticCurvePublicKey.c +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/padding/__init__.c +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "Only %q supported" msgstr "" -#: py/asmthumb.c -msgid "native method too big" +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/padding/__init__.c +msgid "label is not supported" msgstr "" -#: py/emitnative.c -msgid "native yield" +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/rsa/__init__.c +#: shared-bindings/hmac/__init__.c +msgid "key does not have the expected %q purpose" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "ndarray length overflows" +#: shared-bindings/digitalio/DigitalInOut.c +#: shared-bindings/i2cioexpander/IOPin.c +msgid "Cannot set value when direction is input." msgstr "" -#: py/runtime.c -#, c-format -msgid "need more than %d values to unpack" +#: shared-bindings/digitalio/DigitalInOut.c +#: shared-bindings/i2cioexpander/IOPin.c +msgid "Drive mode not used when direction is input." msgstr "" -#: py/modmath.c -msgid "negative factorial" +#: shared-bindings/digitalio/DigitalInOut.c +#: shared-bindings/i2cioexpander/IOPin.c +msgid "Pull not used when direction is output." msgstr "" -#: py/objint_longlong.c py/objint_mpz.c py/runtime.c -msgid "negative power with no float support" +#: shared-bindings/digitalio/DigitalInOutProtocol.c +msgid "%q object missing '%q' method" msgstr "" -#: py/objint_mpz.c py/runtime.c -msgid "negative shift count" +#: shared-bindings/digitalio/DigitalInOutProtocol.c +msgid "%q object missing '%q' attribute" msgstr "" -#: shared-bindings/_pixelmap/PixelMap.c -msgid "nested index must be int" +#: shared-bindings/digitalio/DigitalInOutProtocol.c +msgid "object does not support DigitalInOut protocol" msgstr "" -#: shared-module/sdcardio/SDCard.c -msgid "no SD card" +#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/memorymonitor/AllocationSize.c +#: shared-bindings/pulseio/PulseIn.c +msgid "Cannot delete values" msgstr "" -#: py/vm.c -msgid "no active exception to reraise" +#: 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 +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +msgid "Slices not supported" msgstr "" -#: py/compile.c -msgid "no binding for nonlocal found" +#: shared-bindings/displayio/Palette.c +msgid "color buffer must be a bytearray or array of type 'b' or 'B'" msgstr "" -#: shared-module/msgpack/__init__.c -msgid "no default packer" +#: shared-bindings/displayio/Palette.c +msgid "color buffer must be 3 bytes (RGB) or 4 bytes (RGB + pad byte)" msgstr "" -#: extmod/modrandom.c extmod/ulab/code/numpy/random/random.c -msgid "no default seed" +#: shared-bindings/displayio/Palette.c +msgid "color must be between 0x000000 and 0xffffff" msgstr "" -#: py/builtinimport.c -msgid "no module named '%q'" +#: shared-bindings/displayio/Palette.c +msgid "color buffer must be a buffer, tuple, list, or int" msgstr "" -#: shared-module/sdcardio/SDCard.c -msgid "no response from SD card" +#: shared-bindings/displayio/TileGrid.c +msgid "Tile width must exactly divide bitmap width" msgstr "" -#: ports/espressif/common-hal/espcamera/Camera.c py/objobject.c py/runtime.c -msgid "no such attribute" +#: shared-bindings/displayio/TileGrid.c +msgid "Tile height must exactly divide bitmap height" msgstr "" -#: ports/espressif/common-hal/_bleio/Connection.c -#: ports/nordic/common-hal/_bleio/Connection.c -msgid "non-UUID found in service_uuids_whitelist" +#: shared-bindings/displayio/TileGrid.c +msgid "New bitmap must be same size as old bitmap" msgstr "" -#: py/compile.c -msgid "non-default argument follows default argument" +#: shared-bindings/displayio/TileGrid.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-module/displayio/legacy/TileGrid.c +#: shared-module/displayio/lvgl/TileGrid.c +msgid "Tile index out of bounds" msgstr "" -#: py/objstr.c -msgid "non-hex digit found" +#: shared-bindings/dualbank/__init__.c +msgid "offset must be >= 0" msgstr "" -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "non-zero timeout must be > 0.01" +#: shared-bindings/emmcio/EMMC.c shared-bindings/i2cioexpander/IOExpander.c +msgid "address out of range" msgstr "" -#: shared-bindings/_bleio/Adapter.c -msgid "non-zero timeout must be >= interval" +#: shared-bindings/epaperdisplay/EPaperDisplay.c +msgid "Refresh too soon" msgstr "" -#: shared-bindings/_bleio/UUID.c -msgid "not a 128-bit UUID" +#: shared-bindings/framebufferio/FramebufferDisplay.c +msgid "Buffer is not a bytearray." msgstr "" -#: py/parse.c -msgid "not a constant" +#: shared-bindings/gnss/GNSS.c +msgid "System entry must be gnss.SatelliteSystem" msgstr "" -#: py/objstr.c -msgid "not all arguments converted during string formatting" +#: shared-bindings/hashlib/__init__.c shared-bindings/hmac/__init__.c +msgid "Unsupported hash algorithm" msgstr "" -#: py/objstr.c -msgid "not enough arguments for format string" +#: shared-bindings/i2cioexpander/IOExpander.c +msgid "num_pins must be 8 or 16" msgstr "" -#: extmod/ulab/code/numpy/carray/carray_tools.c -msgid "not implemented for complex dtype" +#: shared-bindings/i2ctarget/I2CTarget.c +msgid "addresses is empty" msgstr "" -#: extmod/ulab/code/numpy/bitwise.c -msgid "not supported for input types" +#: shared-bindings/ipaddress/IPv4Address.c shared-bindings/ipaddress/__init__.c +msgid "Not a valid IP string" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "number of points must be at least 2" +#: shared-bindings/ipaddress/IPv4Address.c +#, c-format +msgid "Address must be %d bytes long" msgstr "" -#: py/builtinhelp.c -msgid "object " +#: shared-bindings/ipaddress/__init__.c +msgid "Only int or string supported for ip" msgstr "" -#: py/obj.c -#, c-format -msgid "object '%s' isn't a tuple or list" +#: shared-bindings/is31fl3741/FrameBuffer.c +msgid "width must be greater than zero" msgstr "" -#: py/obj.c -msgid "object doesn't support item assignment" +#: shared-bindings/is31fl3741/FrameBuffer.c +msgid "Scale dimensions must divide by 3" msgstr "" -#: py/obj.c -msgid "object doesn't support item deletion" +#: shared-bindings/is31fl3741/FrameBuffer.c +msgid "LED mappings must match display size" msgstr "" -#: py/obj.c -msgid "object has no len" +#: shared-bindings/is31fl3741/IS31FL3741.c +msgid "Mapping must be a tuple" msgstr "" -#: py/obj.c -msgid "object isn't subscriptable" +#: shared-bindings/jpegio/JpegDecoder.c +msgid "%q must be of type %q, %q, or %q, not %q" msgstr "" -#: py/runtime.c -msgid "object not an iterator" +#: shared-bindings/mdns/Server.c +msgid "" +"Failed to add service TXT record; non-string or bytes found in txt_records" msgstr "" -#: py/objtype.c py/runtime.c -msgid "object not callable" +#: shared-bindings/memorymap/AddressRange.c +msgid "Address range wraps around" msgstr "" -#: py/sequence.c shared-bindings/displayio/Group.c -msgid "object not in sequence" +#: shared-bindings/microcontroller/Pin.c +msgid "%q contains duplicate pins" msgstr "" -#: py/runtime.c -msgid "object not iterable" +#: shared-bindings/microcontroller/Pin.c +msgid "%q and %q contain duplicate pins" msgstr "" -#: py/obj.c -#, c-format -msgid "object of type '%s' has no len()" +#: shared-bindings/mii/Ethernet.c shared-bindings/wifi/Radio.c +msgid "invalid hostname" msgstr "" -#: py/obj.c -msgid "object with buffer protocol required" +#: shared-bindings/msgpack/ExtType.c +msgid "code outside range 0~127" msgstr "" -#: py/objstr.c -msgid "odd-length string" +#: shared-bindings/msgpack/__init__.c +msgid "default is not a function" msgstr "" -#: supervisor/shared/web_workflow/web_workflow.c -msgid "off" +#: shared-bindings/msgpack/__init__.c +msgid "ext_hook is not a function" msgstr "" -#: extmod/ulab/code/utils/utils.c -msgid "offset is too large" +#: shared-bindings/nvm/ByteArray.c +msgid "Unable to write to nvm." msgstr "" -#: shared-bindings/dualbank/__init__.c -msgid "offset must be >= 0" +#: shared-bindings/os/__init__.c +msgid "No hardware random available" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "offset must be non-negative and no greater than buffer length" +#: shared-bindings/paralleldisplaybus/ParallelBus.c +msgid "Specify exactly one of data0 or data_pins" msgstr "" -#: ports/nordic/common-hal/audiobusio/PDMIn.c -#: ports/stm/common-hal/audiobusio/PDMIn.c -msgid "only bit_depth=16 is supported" +#: shared-bindings/picogame/Bitmap.c shared-module/msgpack/__init__.c +#: supervisor/shared/settings.c +msgid "Invalid format" msgstr "" -#: ports/stm/common-hal/audiobusio/PDMIn.c -msgid "only mono is supported" +#: shared-bindings/ps2io/Ps2.c +msgid "Failed sending command." msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "only ndarrays can be concatenated" +#: shared-bindings/pulseio/PulseOut.c +msgid "Array must contain halfwords (type 'H')" msgstr "" -#: ports/stm/common-hal/audiobusio/PDMIn.c -msgid "only oversample=64 is supported" +#: shared-bindings/pwmio/PWMOut.c +msgid "Conflicting settings for shared resource" msgstr "" -#: ports/nordic/common-hal/audiobusio/PDMIn.c -#: ports/stm/common-hal/audiobusio/PDMIn.c -msgid "only sample_rate=16000 is supported" +#: shared-bindings/random/__init__.c +msgid "stop not reachable from start" msgstr "" -#: py/objarray.c py/objstr.c py/objstrunicode.c py/objtuple.c -#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c -#: shared-bindings/nvm/ByteArray.c -msgid "only slices with step=1 (aka None) are supported" +#: shared-bindings/random/__init__.c +msgid "invalid step" msgstr "" -#: py/vm.c -msgid "opcode" +#: shared-bindings/random/__init__.c +msgid "empty sequence" msgstr "" -#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/bitwise.c -#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/numpy/vector.c -msgid "operands could not be broadcast together" +#: shared-bindings/rclcpy/Publisher.c +msgid "Publishers can only be created from a parent node" msgstr "" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "operation is defined for 2D arrays only" +#: shared-bindings/rgbmatrix/RGBMatrix.c +#, c-format +msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "operation is defined for ndarrays only" +#: 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 "" -#: extmod/ulab/code/ndarray.c -msgid "operation is implemented for 1D Boolean arrays only" +#: shared-bindings/socketpool/Socket.c +msgid "port must be >= 0" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "operation is not implemented on ndarrays" +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c +msgid "buffer too small for requested bytes" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "operation is not supported for given type" +#: shared-bindings/socketpool/SocketPool.c +msgid "Name or service not known" msgstr "" -#: extmod/ulab/code/ndarray_operators.c -msgid "operation not supported for the input types" +#: shared-bindings/spitarget/SPITarget.c +msgid "Packet buffers for an SPI transfer must have the same length." msgstr "" -#: py/modbuiltins.c -msgid "ord expects a character" +#: shared-bindings/ssl/SSLContext.c +msgid "Server side context cannot have hostname" msgstr "" -#: py/modbuiltins.c -#, c-format -msgid "ord() expected a character, but string of length %d found" +#: shared-bindings/storage/__init__.c shared-bindings/usb_audio/__init__.c +#: shared-bindings/usb_cdc/__init__.c shared-bindings/usb_hid/__init__.c +#: shared-bindings/usb_midi/__init__.c shared-bindings/usb_video/__init__.c +msgid "Cannot change USB devices now" msgstr "" -#: extmod/ulab/code/utils/utils.c -msgid "out array is too small" +#: shared-bindings/supervisor/__init__.c shared-module/lvfontio/OnDiskFont.c +msgid "File not found" msgstr "" -#: extmod/ulab/code/numpy/random/random.c -msgid "out has wrong type" +#: shared-bindings/time/__init__.c +msgid "timestamp out of range for platform time_t" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "out keyword is not supported for complex dtype" +#: shared-bindings/traceback/__init__.c +msgid "Supply both or neither of %q and %q" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "out keyword is not supported for function" +#: shared-bindings/traceback/__init__.c +msgid "file write is not available" msgstr "" -#: extmod/ulab/code/utils/utils.c -msgid "out must be a float dense array" +#: shared-bindings/traceback/__init__.c +msgid "invalid exception" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "out must be an ndarray" +#: shared-bindings/usb_audio/USBSpeaker.c +msgid "destination must be an array of type 'h'" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "out must be of float dtype" +#: shared-bindings/usb_audio/__init__.c +msgid "At least one of microphone and speaker must be enabled" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "out of range of target" +#: shared-bindings/usb_hid/Device.c +msgid "%q, %q, and %q must all be the same length" msgstr "" -#: extmod/ulab/code/numpy/random/random.c -msgid "output array has wrong type" +#: shared-bindings/util.c +msgid "" +"Object has been deinitialized and can no longer be used. Create a new object." msgstr "" -#: extmod/ulab/code/numpy/random/random.c -msgid "output array must be contiguous" +#: shared-bindings/warnings/__init__.c +msgid "%q must be a subclass of %q" msgstr "" -#: py/objint_mpz.c -msgid "overflow converting long int to machine word" +#: shared-bindings/wifi/Radio.c +msgid "Invalid hex password" msgstr "" -#: py/modstruct.c -#, c-format -msgid "pack expected %d items for packing (got %d)" +#: shared-bindings/wifi/Radio.c +msgid "Invalid MAC address" msgstr "" -#: shared-bindings/_stage/Layer.c shared-bindings/_stage/Text.c -msgid "palette must be 32 bytes long" +#: shared-bindings/wifi/Radio.c +msgid "AuthMode.OPEN is not used with password" msgstr "" -#: py/emitinlinextensa.c -msgid "parameters must be registers in sequence a2 to a5" +#: shared-bindings/wifi/Radio.c +msgid "Supply either %q or %q, not both" msgstr "" -#: py/emitinlinethumb.c -msgid "parameters must be registers in sequence r0 to r3" +#: shared-bindings/wifi/Radio.c +msgid "Invalid BSSID" msgstr "" -#: extmod/vfs_posix_file.c -msgid "poll on file not available on win32" +#: shared-bindings/wifi/Radio.c supervisor/shared/web_workflow/web_workflow.c +msgid "Authentication failure" msgstr "" -#: ports/espressif/common-hal/pulseio/PulseIn.c -msgid "pop from an empty PulseIn" +#: shared-bindings/wifi/Radio.c +msgid "No network with that ssid" msgstr "" -#: ports/atmel-samd/common-hal/pulseio/PulseIn.c -#: ports/cxd56/common-hal/pulseio/PulseIn.c -#: ports/nordic/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" +#: shared-bindings/wifi/Radio.c +#, c-format +msgid "Unknown failure %d" msgstr "" -#: shared-bindings/socketpool/Socket.c -msgid "port must be >= 0" +#: shared-module/adafruit_bus_device/i2c_device/I2CDevice.c +#, c-format +msgid "No I2C device at address: 0x%x" msgstr "" -#: py/compile.c -msgid "positional arg after **" +#: shared-module/audiocore/WaveFile.c +msgid "Invalid format chunk size" msgstr "" -#: py/compile.c -msgid "positional arg after keyword arg" +#: shared-module/audiocore/__init__.c shared-module/usb_audio/USBMicrophone.c +msgid "The sample's %q does not match" msgstr "" -#: py/objint_mpz.c -msgid "pow() 3rd argument cannot be 0" +#: shared-module/audiodelays/MultiTapDelay.c +msgid "%q in %q must be of type %q or %q, not %q" msgstr "" -#: py/objint_mpz.c -msgid "pow() with 3 arguments requires integers" +#: shared-module/audiofilewriter/AudioFileWriter.c +msgid "Only 8/16-bit mono/stereo is supported" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "pull masks conflict with direction masks" +#: shared-module/audiofilewriter/AudioFileWriter.c +msgid "buffer_size too small for source" msgstr "" -#: py/parse.c -msgid "raw f-strings are not supported" +#: shared-module/audiomp3/MP3Decoder.c +msgid "Couldn't allocate decoder" msgstr "" -#: extmod/ulab/code/numpy/fft/fft_tools.c -msgid "real and imaginary parts must be of equal length" +#: shared-module/audiomp3/MP3Decoder.c +msgid "Failed to parse MP3 file" msgstr "" -#: py/builtinimport.c -msgid "relative import" +#: shared-module/bitbangio/I2C.c shared-module/msgpack/__init__.c +msgid "%q too long" msgstr "" -#: py/obj.c -#, c-format -msgid "requested length %d but object has length %d" +#: shared-module/bitmapfilter/__init__.c +msgid "bitmap size and depth must match" msgstr "" -#: extmod/ulab/code/ndarray_operators.c -msgid "results cannot be cast to specified type" +#: shared-module/bitmapfilter/__init__.c +msgid "unsupported bitmap depth" msgstr "" -#: py/compile.c -msgid "return annotation must be an identifier" +#: shared-module/busdisplay/lvgl/BusDisplay.c +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "LVGL display create failed" msgstr "" -#: py/emitnative.c -msgid "return expected '%q' but got '%q'" +#: shared-module/busdisplay/lvgl/BusDisplay.c +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "LVGL buffer alloc failed" msgstr "" -#: shared-bindings/rgbmatrix/RGBMatrix.c -#, c-format -msgid "rgb_pins[%d] duplicates another pin assignment" +#: shared-module/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "OAEP requires this build to enable TLS 1.3 support" msgstr "" -#: shared-bindings/rgbmatrix/RGBMatrix.c -#, c-format -msgid "rgb_pins[%d] is not on the same port as clock" +#: shared-module/displayio/bus_core.c +msgid "Unsupported display bus type" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "roll argument must be an ndarray" +#: shared-module/displayio/legacy/Bitmap.c +#: shared-module/displayio/lvgl/Bitmap.c +msgid "Invalid bits per value" msgstr "" -#: py/objstr.c -msgid "rsplit(None,n)" +#: shared-module/displayio/legacy/ColorConverter.c +#: shared-module/displayio/lvgl/ColorConverter.c +msgid "Only one color can be transparent at a time" msgstr "" -#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c -#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c -msgid "sampling rate out of range" +#: shared-module/displayio/legacy/Group.c shared-module/displayio/lvgl/Group.c +msgid "Layer already in a group" msgstr "" -#: py/modmicropython.c -msgid "schedule queue full" +#: shared-module/displayio/legacy/Group.c +msgid "Layer must be a Group or TileGrid subclass" msgstr "" -#: py/builtinimport.c -msgid "script compilation not supported" +#: shared-module/displayio/legacy/OnDiskBitmap.c +#: shared-module/displayio/lvgl/OnDiskBitmap.c +#, c-format +msgid "" +"Only Windows format, uncompressed BMP supported: given header size is %d" msgstr "" -#: py/nativeglue.c -msgid "set unsupported" +#: shared-module/displayio/legacy/OnDiskBitmap.c +#: shared-module/displayio/lvgl/OnDiskBitmap.c +msgid "RLE-compressed BMP not supported" msgstr "" -#: extmod/ulab/code/numpy/random/random.c -msgid "shape must be None, and integer or a tuple of integers" +#: shared-module/displayio/legacy/OnDiskBitmap.c +#: shared-module/displayio/lvgl/OnDiskBitmap.c +msgid "Unable to read color palette data" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "shape must be integer or tuple of integers" +#: shared-module/displayio/legacy/__init__.c +msgid "Too many displays" msgstr "" -#: shared-module/msgpack/__init__.c -msgid "short read" +#: shared-module/displayio/legacy/__init__.c +msgid "Too many display buses; deinit() unused displays" msgstr "" -#: py/objstr.c -msgid "sign not allowed in string format specifier" +#: shared-module/displayio/lvgl/Group.c +msgid "Layer does not support scaling" msgstr "" -#: py/objstr.c -msgid "sign not allowed with integer format specifier 'c'" +#: shared-module/displayio/lvgl/Group.c +msgid "Layer must be a Group, TileGrid, vector shape or VideoBuffer" msgstr "" -#: extmod/ulab/code/ulab_tools.c -msgid "size is defined for ndarrays only" +#: shared-module/displayio/lvgl/TileGrid.c +msgid "LVGL displayio backend does not support flips/transpose yet" msgstr "" -#: extmod/ulab/code/numpy/random/random.c -msgid "size must match out.shape when used together" +#: shared-module/displayio/lvgl/TileGrid.c +msgid "OnDiskBitmap requires its own pixel_shader" msgstr "" -#: py/nativeglue.c -msgid "slice unsupported" +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "LVGL dirty row alloc failed" msgstr "" -#: py/objint.c py/sequence.c -msgid "small int overflow" +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +#: shared-module/videocore/VideoBuffer.c +#: shared-module/videocore/legacy/VideoBuffer.c +#: shared-module/videocore/lvgl/VideoBuffer.c +msgid "VideoBuffer can't stream into a rotated display" msgstr "" -#: main.c -msgid "soft reboot\n" +#: shared-module/gifio/GifWriter.c +msgid "unsupported colorspace for GifWriter" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "sort argument must be an ndarray" +#: shared-module/hmac/HMAC.c +msgid "key does not support this digest" msgstr "" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "sos array must be of shape (n_section, 6)" +#: shared-module/hmac/HMAC.c +msgid "HMAC of an empty message is not supported with a hardware key" msgstr "" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "sos[:, 3] should be all ones" +#: shared-module/i2cdisplaybus/I2CDisplayBus.c +#: shared-module/is31fl3741/IS31FL3741.c +#, c-format +msgid "Unable to find I2C Display at %x" msgstr "" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "sosfilt requires iterable arguments" +#: shared-module/i2cioexpander/IOExpander.c +msgid "Cannot deinitialize board IOExpander" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "source palette too large" +#: shared-module/imagecapture/ParallelImageCapture.c +msgid "This microcontroller does not support continuous capture." msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "source_bitmap must have value_count of 2 or 65536" +#: shared-module/jpegio/JpegDecoder.c +msgid "Interrupted by output function" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "source_bitmap must have value_count of 65536" +#: shared-module/jpegio/JpegDecoder.c +msgid "Device error or wrong termination of input stream" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "source_bitmap must have value_count of 8" +#: shared-module/jpegio/JpegDecoder.c +msgid "Insufficient memory pool for the image" msgstr "" -#: extmod/modre.c -msgid "splitting with sub-captures" +#: shared-module/jpegio/JpegDecoder.c +msgid "Insufficient stream input buffer" msgstr "" -#: py/objstr.c -msgid "start/end indices" +#: shared-module/jpegio/JpegDecoder.c +msgid "Parameter error" msgstr "" -#: shared-bindings/random/__init__.c -msgid "stop not reachable from start" +#: shared-module/jpegio/JpegDecoder.c +msgid "Data format error (may be broken data)" msgstr "" -#: py/stream.c shared-bindings/getpass/__init__.c -msgid "stream operation not supported" +#: shared-module/jpegio/JpegDecoder.c +msgid "Right format but not supported" msgstr "" -#: py/objarray.c py/objstr.c -msgid "string argument without an encoding" +#: shared-module/jpegio/JpegDecoder.c +msgid "Unsupported JPEG (may be progressive)" msgstr "" -#: py/objstrunicode.c -msgid "string index out of range" +#: shared-module/jpegio/JpegDecoder.c +msgid "%q() without %q()" msgstr "" -#: py/objstrunicode.c +#: shared-module/memorymonitor/AllocationAlarm.c #, c-format -msgid "string indices must be integers, not %s" +msgid "Attempt to allocate %d blocks" msgstr "" -#: py/objarray.c py/objstr.c -msgid "substring not found" +#: shared-module/msgpack/__init__.c +msgid "short read" msgstr "" -#: py/compile.c -msgid "super() can't find self" +#: shared-module/msgpack/__init__.c +msgid "no default packer" msgstr "" -#: extmod/modjson.c -msgid "syntax error in JSON" +#: shared-module/paralleldisplaybus/ParallelBus.c +msgid "" +"This microcontroller only supports data0=, not data_pins=, because it " +"requires contiguous pins." msgstr "" -#: extmod/modtime.c -msgid "ticks interval overflow" +#: shared-module/rgbmatrix/RGBMatrix.c +msgid "The length of rgb_pins must be 6, 12, 18, 24, or 30" msgstr "" -#: ports/nordic/common-hal/watchdog/WatchDogTimer.c -msgid "timeout duration exceeded the maximum supported value" +#: shared-module/rgbmatrix/RGBMatrix.c +#, c-format +msgid "rgb_pins[%d] is not on the same port as clock" msgstr "" -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "timeout must be < 655.35 secs" +#: shared-module/rgbmatrix/RGBMatrix.c +#, c-format +msgid "rgb_pins[%d] duplicates another pin assignment" msgstr "" -#: ports/raspberrypi/common-hal/floppyio/__init__.c -msgid "timeout waiting for flux" +#: shared-module/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 "" + +#: shared-module/rgbmatrix/RGBMatrix.c +msgid "No timer available" msgstr "" -#: ports/raspberrypi/common-hal/floppyio/__init__.c -#: shared-module/floppyio/__init__.c -msgid "timeout waiting for index pulse" +#: shared-module/rgbmatrix/RGBMatrix.c +#, c-format +msgid "Internal error #%d" msgstr "" #: shared-module/sdcardio/SDCard.c @@ -4153,274 +4807,271 @@ msgstr "" msgid "timeout waiting for v2 card" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "timer re-init" +#: shared-module/sdcardio/SDCard.c +msgid "no SD card" msgstr "" -#: shared-bindings/time/__init__.c -msgid "timestamp out of range for platform time_t" +#: shared-module/sdcardio/SDCard.c +msgid "couldn't determine SD card version" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "tobytes can be invoked for dense arrays only" +#: shared-module/sdcardio/SDCard.c +msgid "no response from SD card" msgstr "" -#: py/compile.c -msgid "too many args" +#: shared-module/sdcardio/SDCard.c +msgid "SD card CSD format not supported" msgstr "" -#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/create.c -msgid "too many dimensions" +#: shared-module/sdcardio/SDCard.c +msgid "can't set 512 block size" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "too many indices" +#: shared-module/ssl/SSLSocket.c +msgid "Invalid socket for TLS" msgstr "" -#: py/asmthumb.c -msgid "too many locals for native method" +#: shared-module/ssl/SSLSocket.c +msgid "invalid cert" msgstr "" -#: py/runtime.c -#, c-format -msgid "too many values to unpack (expected %d)" +#: shared-module/storage/__init__.c +msgid "File write in progress" msgstr "" -#: extmod/ulab/code/numpy/approx.c -msgid "trapz is defined for 1D arrays of equal length" +#: shared-module/storage/__init__.c +msgid "Mount point directory missing" msgstr "" -#: extmod/ulab/code/numpy/approx.c -msgid "trapz is defined for 1D iterables" +#: shared-module/storage/__init__.c +msgid "Cannot remount path when visible via USB." msgstr "" -#: py/obj.c -msgid "tuple/list has wrong length" +#: shared-module/struct/__init__.c +msgid "'S' and 'O' are not supported format types" msgstr "" -#: ports/espressif/common-hal/canio/CAN.c -#, c-format -msgid "twai_driver_install returned esp-idf error #%d" +#: shared-module/struct/__init__.c +msgid "buffer size must match format" msgstr "" -#: ports/espressif/common-hal/canio/CAN.c -#, c-format -msgid "twai_start returned esp-idf error #%d" +#: shared-module/synthio/__init__.c +msgid "%q must be array of type 'h'" msgstr "" -#: shared-bindings/busio/UART.c shared-bindings/canio/CAN.c -msgid "tx and rx cannot both be None" +#: shared-module/tilepalettemapper/TilePaletteMapper.c +msgid "TilePaletteMapper may only be bound to a TileGrid once" msgstr "" -#: py/objtype.c -msgid "type '%q' is not an acceptable base type" +#: shared-module/touchio/TouchIn.c +msgid "No pullup on pin; 1Mohm recommended" msgstr "" -#: py/objtype.c -msgid "type is not an acceptable base type" +#: shared-module/touchio/TouchIn.c +msgid "No pulldown on pin; 1Mohm recommended" msgstr "" -#: py/runtime.c -msgid "type object '%q' has no attribute '%q'" +#: shared-module/usb/core/Device.c +msgid "No usb host port initialized" msgstr "" -#: py/objtype.c -msgid "type takes 1 or 3 arguments" +#: shared-module/usb/core/Device.c +msgid "Pipe error" msgstr "" -#: py/objint_longlong.c -msgid "ulonglong too large" +#: shared-module/usb/core/Device.c +msgid "No configuration set" msgstr "" -#: py/parse.c -msgid "unexpected indent" +#: shared-module/usb_hid/Device.c +msgid "USB busy" msgstr "" -#: py/bc.c -msgid "unexpected keyword argument" +#: shared-module/vectorio/Circle.c shared-module/vectorio/Polygon.c +#: shared-module/vectorio/Rectangle.c +msgid "can only have one parent" msgstr "" -#: py/argcheck.c py/bc.c py/objnamedtuple.c -#: shared-bindings/traceback/__init__.c -msgid "unexpected keyword argument '%q'" +#: shared-module/vectorio/Polygon.c +msgid "Polygon needs at least 3 points" msgstr "" -#: py/lexer.c -msgid "unicode name escapes" +#: shared-module/videocore/VideoBuffer.c +msgid "framebuffer went away" msgstr "" -#: py/parse.c -msgid "unindent doesn't match any outer indent level" +#: shared-module/videocore/VideoBuffer.c +msgid "video doesn't fit in framebuffer" msgstr "" -#: py/objstr.c -#, c-format -msgid "unknown conversion specifier %c" +#: shared-module/videocore/VideoBuffer.c +msgid "framebuffer missing required functions" msgstr "" -#: py/objstr.c -msgid "unknown format code '%c' for object of type '%q'" +#: shared-module/videocore/VideoBuffer.c +msgid "video format must be byte aligned" msgstr "" -#: py/compile.c -msgid "unknown type" +#: shared-module/videocore/VideoBuffer.c +msgid "video format doesn't match framebuffer" msgstr "" -#: py/compile.c -msgid "unknown type '%q'" +#: shared-module/videocore/VideoBuffer.c +msgid "video source rejected the destination" msgstr "" -#: py/objstr.c -#, c-format -msgid "unmatched '%c' in format" +#: shared-module/videocore/VideoBuffer.c +msgid "video in a framebuffer must be at x == 0" msgstr "" -#: py/objtype.c py/runtime.c -msgid "unreadable attribute" +#: shared-module/videocore/VideoBuffer.c +msgid "video size changed since play; stop and play again" msgstr "" -#: shared-bindings/displayio/TileGrid.c shared-bindings/vectorio/VectorShape.c -msgid "unsupported %q type" +#: shared-module/videocore/VideoBuffer.c +msgid "VideoBuffer is playing into a different framebuffer" msgstr "" -#: py/emitinlinethumb.c -#, c-format -msgid "unsupported Thumb instruction '%s' with %d arguments" +#: shared-module/videocore/legacy/VideoBuffer.c +msgid "VideoBuffer does not support transforms" msgstr "" -#: py/emitinlinextensa.c -#, c-format -msgid "unsupported Xtensa instruction '%s' with %d arguments" +#: shared-module/videocore/lvgl/VideoBuffer.c +msgid "video format must be 16, 24 or 32 bits per pixel" msgstr "" -#: shared-module/bitmapfilter/__init__.c -msgid "unsupported bitmap depth" +#: supervisor/shared/bluetooth/bluetooth.c +msgid "Reconnecting" msgstr "" -#: shared-module/gifio/GifWriter.c -msgid "unsupported colorspace for GifWriter" +#: supervisor/shared/bluetooth/bluetooth.c +msgid "Ok" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "unsupported colorspace for dither" +#: supervisor/shared/bluetooth/bluetooth.c +msgid "Off" msgstr "" -#: py/objstr.c -#, c-format -msgid "unsupported format character '%c' (0x%x) at index %d" +#: supervisor/shared/micropython.c +msgid "[truncated due to length]" msgstr "" -#: py/runtime.c -msgid "unsupported type for %q: '%s'" +#: supervisor/shared/safe_mode.c +msgid "" +"\n" +"You are in safe mode because:\n" msgstr "" -#: py/runtime.c -msgid "unsupported type for operator" +#: supervisor/shared/safe_mode.c +msgid "Power dipped. Make sure you are providing enough power." msgstr "" -#: py/runtime.c -msgid "unsupported types for %q: '%q', '%q'" +#: supervisor/shared/safe_mode.c +msgid "You pressed the BOOT button at start up" msgstr "" -#: extmod/ulab/code/numpy/io/io.c -msgid "usecols is too high" +#: supervisor/shared/safe_mode.c +msgid "You pressed the reset button during boot." msgstr "" -#: extmod/ulab/code/numpy/io/io.c -msgid "usecols keyword must be specified" +#: supervisor/shared/safe_mode.c +msgid "CIRCUITPY drive could not be found or created." msgstr "" -#: py/objint.c -#, c-format -msgid "value must fit in %d byte(s)" +#: supervisor/shared/safe_mode.c +msgid "The `microcontroller` module was used to boot into safe mode." msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "value out of range of target" +#: supervisor/shared/safe_mode.c +msgid "Error in safemode.py." msgstr "" -#: extmod/moddeflate.c -msgid "wbits" +#: supervisor/shared/safe_mode.c +msgid "Stack overflow. Increase stack size." msgstr "" -#: shared-bindings/bitmapfilter/__init__.c -msgid "" -"weights must be a sequence with an odd square number of elements (usually 9 " -"or 25)" +#: supervisor/shared/safe_mode.c +msgid "USB devices need more endpoints than are available." msgstr "" -#: shared-bindings/bitmapfilter/__init__.c -msgid "weights must be an object of type %q, %q, %q, or %q, not %q " +#: supervisor/shared/safe_mode.c +msgid "USB devices specify too many interface names." msgstr "" -#: shared-bindings/is31fl3741/FrameBuffer.c -msgid "width must be greater than zero" +#: supervisor/shared/safe_mode.c +msgid "Boot device must be first (interface #0)." msgstr "" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/raspberrypi/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "wifi is not enabled" +#: supervisor/shared/safe_mode.c +msgid "Internal watchdog timer expired." msgstr "" -#: ports/raspberrypi/common-hal/wifi/Monitor.c -msgid "wifi.Monitor not available" +#: supervisor/shared/safe_mode.c +msgid "CircuitPython core code crashed hard. Whoops!\n" msgstr "" -#: shared-bindings/_bleio/Adapter.c -msgid "window must be <= interval" +#: supervisor/shared/safe_mode.c +msgid "Heap allocation when VM not running." msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "wrong axis index" +#: supervisor/shared/safe_mode.c +msgid "Failed to write internal flash." msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "wrong axis specified" +#: supervisor/shared/safe_mode.c +msgid "Hard fault: memory access or instruction error." msgstr "" -#: extmod/ulab/code/numpy/io/io.c -msgid "wrong dtype" +#: supervisor/shared/safe_mode.c +msgid "Interrupt error." msgstr "" -#: extmod/ulab/code/numpy/transform.c -msgid "wrong index type" +#: supervisor/shared/safe_mode.c +msgid "LVGL ran out of memory." msgstr "" -#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/numpy/create.c -#: extmod/ulab/code/numpy/io/io.c extmod/ulab/code/numpy/transform.c -#: extmod/ulab/code/numpy/vector.c -msgid "wrong input type" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." msgstr "" -#: extmod/ulab/code/numpy/transform.c -msgid "wrong length of condition array" +#: supervisor/shared/safe_mode.c +msgid "Unable to allocate to the heap." msgstr "" -#: extmod/ulab/code/numpy/transform.c -msgid "wrong length of index array" +#: supervisor/shared/safe_mode.c +msgid "Third-party firmware fatal error." msgstr "" -#: extmod/ulab/code/numpy/create.c py/objarray.c py/objstr.c -msgid "wrong number of arguments" +#: supervisor/shared/safe_mode.c +msgid "" +"\n" +"Please file an issue with your program at github.com/adafruit/circuitpython/" +"issues." msgstr "" -#: py/runtime.c -msgid "wrong number of values to unpack" +#: supervisor/shared/safe_mode.c +msgid "" +"\n" +"Press reset to exit safe mode.\n" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "wrong output type" +#: supervisor/shared/settings.c +#, c-format +msgid "An error occurred while retrieving '%s':\n" msgstr "" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "zi must be an ndarray" +#: supervisor/shared/settings.c +msgid "Invalid unicode escape" msgstr "" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "zi must be of float type" +#: supervisor/shared/web_workflow/web_workflow.c +msgid "Wi-Fi: " +msgstr "Wi-Fi: " + +#: supervisor/shared/web_workflow/web_workflow.c +msgid "off" msgstr "" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "zi must be of shape (n_section, 2)" +#: supervisor/shared/web_workflow/web_workflow.c +msgid "No IP" msgstr "" diff --git a/locale/it_IT.po b/locale/it_IT.po index 7b9c6cec633..87e7f0e343d 100644 --- a/locale/it_IT.po +++ b/locale/it_IT.po @@ -7,15 +7,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: 2023-12-06 22:06+0000\n" -"Last-Translator: deepserket \n" +"PO-Revision-Date: 2025-06-30 16:01+0000\n" +"Last-Translator: MAE \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 5.3-dev\n" +"X-Generator: Weblate 5.13-dev\n" #: main.c msgid "" @@ -86,7 +86,7 @@ msgstr "" msgid "%q and %q contain duplicate pins" msgstr "" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: shared-bindings/audioio/AudioOut.c msgid "%q and %q must be different" msgstr "" @@ -106,6 +106,10 @@ msgstr "" msgid "%q failure: %d" msgstr "%q fallito: %d" +#: shared-module/audiodelays/MultiTapDelay.c +msgid "%q in %q must be of type %q or %q, not %q" +msgstr "" + #: py/argcheck.c shared-module/audiofilters/Filter.c msgid "%q in %q must be of type %q, not %q" msgstr "" @@ -158,7 +162,7 @@ msgstr "" msgid "%q length must be >= %d" msgstr "" -#: py/modsys.c py/objmodule.c py/runtime.c +#: py/modsys.c py/runtime.c msgid "%q moved from %q to %q" msgstr "" @@ -219,7 +223,7 @@ msgstr "" #: shared-bindings/bitmapfilter/__init__.c shared-bindings/canio/CAN.c #: shared-bindings/digitalio/Pull.c shared-bindings/supervisor/__init__.c #: shared-module/audiofilters/Filter.c shared-module/displayio/__init__.c -#: shared-module/synthio/Biquad.c shared-module/synthio/Synthesizer.c +#: shared-module/synthio/Synthesizer.c msgid "%q must be of type %q or %q, not %q" msgstr "" @@ -228,6 +232,7 @@ msgid "%q must be of type %q, %q, or %q, not %q" msgstr "" #: py/argcheck.c py/runtime.c shared-bindings/bitmapfilter/__init__.c +#: shared-module/audiodelays/MultiTapDelay.c shared-module/synthio/Note.c #: shared-module/synthio/__init__.c msgid "%q must be of type %q, not %q" msgstr "" @@ -308,7 +313,7 @@ msgid "'%q' object does not support '%q'" msgstr "L'oggetto '%q' non supporta '%q'" #: py/runtime.c -msgid "'%q' object is not an iterator" +msgid "'%q' object isn't an iterator" msgstr "L'oggetto '%q' non è un iteratore" #: py/objtype.c py/runtime.c shared-module/atexit/__init__.c @@ -316,7 +321,7 @@ msgid "'%q' object is not callable" msgstr "L'oggetto '%q' non è richiamabile" #: py/runtime.c -msgid "'%q' object is not iterable" +msgid "'%q' object isn't iterable" msgstr "L'oggetto '%q' non è iterabile" #: py/emitinlinethumb.c py/emitinlinextensa.c @@ -797,12 +802,12 @@ msgid "Cannot record to a file" msgstr "Impossibile registrare in un file" #: shared-module/storage/__init__.c -msgid "Cannot remount '/' when visible via USB." +msgid "Cannot remount path when visible via USB." msgstr "" #: shared-bindings/digitalio/DigitalInOut.c msgid "Cannot set value when direction is input." -msgstr "non si può impostare un valore quando direzione è input" +msgstr "non si può impostare un valore quando direzione è input." #: ports/espressif/common-hal/busio/UART.c #: ports/mimxrt10xx/common-hal/busio/UART.c @@ -851,6 +856,10 @@ msgstr "" msgid "Coordinate arrays types have different sizes" msgstr "" +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "Could not publish to ROS topic" +msgstr "" + #: shared-bindings/_bleio/Adapter.c msgid "Could not set address" msgstr "" @@ -863,6 +872,11 @@ msgstr "" msgid "Couldn't allocate decoder" msgstr "" +#: ports/espressif/common-hal/rclcpy/__init__.c +#, c-format +msgid "Critical ROS failure during soft reboot, reset required: %d" +msgstr "" + #: ports/stm/common-hal/analogio/AnalogOut.c msgid "DAC Channel Init Error" msgstr "" @@ -892,9 +906,8 @@ msgstr "" #: ports/espressif/common-hal/_bleio/Adapter.c #: ports/nordic/common-hal/_bleio/Adapter.c -#, fuzzy msgid "Data too large for advertisement packet" -msgstr "Impossibile inserire dati nel pacchetto di advertisement." +msgstr "Impossibile inserire dati nel pacchetto di advertisement" #: ports/stm/common-hal/alarm/pin/PinAlarm.c msgid "Deep sleep pins must use a rising edge with pulldown" @@ -976,7 +989,7 @@ msgstr "" #: ports/nordic/sd_mutex.c #, c-format msgid "Failed to acquire mutex, err 0x%04x" -msgstr "Impossibile acquisire il mutex, err 0x%04x" +msgstr "Impossibile acquisire il mutex, err 0x%04x" #: ports/raspberrypi/common-hal/mdns/Server.c msgid "Failed to add service TXT record" @@ -1043,7 +1056,7 @@ msgstr "" #: ports/nordic/sd_mutex.c #, c-format msgid "Failed to release mutex, err 0x%04x" -msgstr "Impossibile rilasciare il mutex, err 0x%04x" +msgstr "Impossibile rilasciare il mutex, err 0x%04x" #: ports/zephyr-cp/common-hal/wifi/Radio.c msgid "Failed to set hostname" @@ -1061,6 +1074,7 @@ msgstr "" msgid "File exists" msgstr "File esistente" +#: shared-bindings/supervisor/__init__.c shared-module/lvfontio/OnDiskFont.c #: shared-module/os/getenv.c msgid "File not found" msgstr "" @@ -1092,7 +1106,7 @@ msgstr "" msgid "For RGB colorspaces, input bitmap must have 16 bits per pixel" msgstr "" -#: ports/cxd56/common-hal/camera/Camera.c +#: ports/cxd56/common-hal/camera/Camera.c shared-module/audiocore/WaveFile.c msgid "Format not supported" msgstr "" @@ -1256,7 +1270,9 @@ msgstr "" #: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c py/argcheck.c #: shared-bindings/digitalio/DigitalInOut.c #: shared-bindings/epaperdisplay/EPaperDisplay.c shared-bindings/pwmio/PWMOut.c +#: shared-bindings/supervisor/__init__.c #: shared-module/aurora_epaper/aurora_framebuffer.c +#: shared-module/lvfontio/OnDiskFont.c msgid "Invalid %q" msgstr "" @@ -1289,6 +1305,10 @@ msgstr "" msgid "Invalid MAC address" msgstr "" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "Invalid ROS domain ID" +msgstr "" + #: ports/espressif/common-hal/espidf/__init__.c py/moderrno.c msgid "Invalid argument" msgstr "Argomento non valido" @@ -1378,6 +1398,11 @@ msgstr "" msgid "MITM security not supported" msgstr "" +#: ports/stm/common-hal/sdioio/SDCard.c +#, c-format +msgid "MMC/SDIO Clock Error %x" +msgstr "" + #: shared-bindings/is31fl3741/IS31FL3741.c msgid "Mapping must be a tuple" msgstr "" @@ -1564,6 +1589,10 @@ msgstr "" msgid "No pulldown on pin; 1Mohm recommended" msgstr "" +#: shared-module/touchio/TouchIn.c +msgid "No pullup on pin; 1Mohm recommended" +msgstr "" + #: py/moderrno.c msgid "No space left on device" msgstr "Non che spazio sul dispositivo" @@ -1799,9 +1828,8 @@ msgid "Pipe error" msgstr "" #: py/builtinhelp.c -#, fuzzy msgid "Plus any modules on the filesystem\n" -msgstr "Imposssibile rimontare il filesystem" +msgstr "Imposssibile rimontare il filesystem\n" #: shared-module/vectorio/Polygon.c msgid "Polygon needs at least 3 points" @@ -1839,6 +1867,10 @@ msgstr "" msgid "Program too long" msgstr "" +#: shared-bindings/rclcpy/Publisher.c +msgid "Publishers can only be created from a parent node" +msgstr "" + #: shared-bindings/digitalio/DigitalInOut.c msgid "Pull not used when direction is output." msgstr "" @@ -1859,10 +1891,30 @@ msgstr "" msgid "RNG Init Error" msgstr "" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS failed to initialize. Is agent connected?" +msgstr "" + +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS internal setup failure" +msgstr "" + +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS memory allocator failure" +msgstr "" + +#: ports/espressif/common-hal/rclcpy/Node.c +msgid "ROS node failed to initialize" +msgstr "" + +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "ROS topic failed to initialize" +msgstr "" + #: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c #: ports/nordic/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c msgid "RS485" -msgstr "" +msgstr "RS485" #: ports/espressif/common-hal/busio/UART.c #: ports/mimxrt10xx/common-hal/busio/UART.c @@ -1990,6 +2042,7 @@ msgstr "" #: shared-bindings/displayio/TileGrid.c #: shared-bindings/memorymonitor/AllocationSize.c #: shared-bindings/pulseio/PulseIn.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c msgid "Slices not supported" msgstr "Slice non supportate" @@ -2057,7 +2110,9 @@ msgstr "" msgid "Tile height must exactly divide bitmap height" msgstr "" -#: shared-bindings/displayio/TileGrid.c shared-module/displayio/TileGrid.c +#: shared-bindings/displayio/TileGrid.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-module/displayio/TileGrid.c msgid "Tile index out of bounds" msgstr "" @@ -2065,6 +2120,10 @@ msgstr "" msgid "Tile width must exactly divide bitmap width" msgstr "" +#: shared-module/tilepalettemapper/TilePaletteMapper.c +msgid "TilePaletteMapper may only be bound to a TileGrid once" +msgstr "" + #: shared-bindings/alarm/time/TimeAlarm.c msgid "Time is in the past." msgstr "" @@ -2132,7 +2191,7 @@ msgstr "" #: main.c msgid "UID:" -msgstr "" +msgstr "UID:" #: shared-module/usb_hid/Device.c msgid "USB busy" @@ -2293,10 +2352,6 @@ msgstr "" msgid "Unsupported display bus type" msgstr "tipo di bitmap non supportato" -#: shared-module/audiocore/WaveFile.c -msgid "Unsupported format" -msgstr "Formato non supportato" - #: shared-bindings/hashlib/__init__.c msgid "Unsupported hash algorithm" msgstr "" @@ -2351,10 +2406,12 @@ msgstr "" #: supervisor/shared/web_workflow/web_workflow.c msgid "Wi-Fi: " -msgstr "" +msgstr "Wi-Fi: " +#: ports/espressif/common-hal/wifi/Radio.c #: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "Wifi is not enabled" +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "WiFi is not enabled" msgstr "" #: main.c @@ -2590,9 +2647,16 @@ msgstr "" msgid "bits must be 32 or less" msgstr "" -#: shared-bindings/audiodelays/Echo.c shared-bindings/audiodelays/PitchShift.c +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "bits_per_sample must be 16" +msgstr "" + +#: shared-bindings/audiodelays/Chorus.c shared-bindings/audiodelays/Echo.c +#: shared-bindings/audiodelays/MultiTapDelay.c +#: shared-bindings/audiodelays/PitchShift.c #: shared-bindings/audiofilters/Distortion.c -#: shared-bindings/audiofilters/Filter.c shared-bindings/audiomixer/Mixer.c +#: shared-bindings/audiofilters/Filter.c shared-bindings/audiofilters/Phaser.c +#: shared-bindings/audiomixer/Mixer.c #, fuzzy msgid "bits_per_sample must be 8 or 16" msgstr "i bit devono essere 7, 8 o 9" @@ -3141,7 +3205,7 @@ msgid "format" msgstr "" #: py/objstr.c -msgid "format requires a dict" +msgid "format needs a dict" msgstr "la formattazione richiede un dict" #: py/objdeque.c @@ -3604,7 +3668,7 @@ msgid "must use keyword argument for key function" msgstr "" #: py/runtime.c -msgid "name '%q' is not defined" +msgid "name '%q' isn't defined" msgstr "nome '%q'non definito" #: py/runtime.c @@ -4026,6 +4090,10 @@ msgstr "" msgid "rsplit(None,n)" msgstr "" +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "samples_signed must be true" +msgstr "" + #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c #: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "sampling rate out of range" @@ -4077,7 +4145,7 @@ msgstr "" #: py/objint.c py/sequence.c msgid "small int overflow" -msgstr "small int overflow" +msgstr "piccolo int overflow" #: main.c msgid "soft reboot\n" @@ -4245,11 +4313,11 @@ msgid "tx and rx cannot both be None" msgstr "tx e rx non possono essere entrambi None" #: py/objtype.c -msgid "type '%q' is not an acceptable base type" +msgid "type '%q' isn't an acceptable base type" msgstr "il tipo '%q' non è un tipo di base accettabile" #: py/objtype.c -msgid "type is not an acceptable base type" +msgid "type isn't an acceptable base type" msgstr "il tipo non è un tipo di base accettabile" #: py/runtime.c @@ -4311,7 +4379,9 @@ msgstr "" msgid "unreadable attribute" msgstr "attributo non leggibile" -#: shared-bindings/displayio/TileGrid.c shared-bindings/vectorio/VectorShape.c +#: shared-bindings/displayio/TileGrid.c shared-bindings/terminalio/Terminal.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-bindings/vectorio/VectorShape.c msgid "unsupported %q type" msgstr "tipo di %q non supportato" @@ -4389,12 +4459,6 @@ msgstr "" msgid "width must be greater than zero" msgstr "" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/raspberrypi/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "wifi is not enabled" -msgstr "" - #: ports/raspberrypi/common-hal/wifi/Monitor.c msgid "wifi.Monitor not available" msgstr "" @@ -4457,6 +4521,9 @@ msgstr "" msgid "zi must be of shape (n_section, 2)" msgstr "" +#~ msgid "Unsupported format" +#~ msgstr "Formato non supportato" + #~ msgid "Buffer length must be a multiple of 512" #~ msgstr "La lunghezza del buffer deve essere un multiplo di 512" @@ -4610,13 +4677,13 @@ msgstr "" #~ msgid "'%s' object does not support item deletion" #~ msgstr "oggeto '%s' non supporta eliminamento di item" -#~ msgid "'%s' object is not an iterator" +#~ msgid "'%s' object isn't an iterator" #~ msgstr "l'oggetto '%s' non è un iteratore" #~ msgid "'%s' object is not callable" #~ msgstr "oggeto '%s' non è chiamabile" -#~ msgid "'%s' object is not iterable" +#~ msgid "'%s' object isn't iterable" #~ msgstr "l'oggetto '%s' non è iterabile" #~ msgid "'%s' object is not subscriptable" @@ -4632,7 +4699,7 @@ msgstr "" #~ msgid "'continue' outside loop" #~ msgstr "'continue' fuori del ciclo" -#~ msgid "'coroutine' object is not an iterator" +#~ msgid "'coroutine' object isn't an iterator" #~ msgstr "L'oggetto 'coroutine' non è un iteratore" #~ msgid "64 bit types" @@ -5295,7 +5362,7 @@ msgstr "" #~ msgid "frequency can only be either 80Mhz or 160MHz" #~ msgstr "la frequenza può essere o 80Mhz o 160Mhz" -#~ msgid "function does not take keyword arguments" +#~ msgid "function doesn't take keyword arguments" #~ msgstr "la funzione non prende argomenti nominati" #~ msgid "impossible baudrate" @@ -5362,7 +5429,7 @@ msgstr "" #~ msgid "name must be a string" #~ msgstr "argomenti nominati devono essere stringhe" -#~ msgid "name reused for argument" +#~ msgid "argument name reused" #~ msgstr "nome riutilizzato come argomento" #, fuzzy diff --git a/locale/ja.po b/locale/ja.po index 4ff6dfd6b56..6e625e94a87 100644 --- a/locale/ja.po +++ b/locale/ja.po @@ -8,15 +8,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: 2024-01-22 14:03+0000\n" -"Last-Translator: Nemoto \n" +"PO-Revision-Date: 2025-06-30 16:01+0000\n" +"Last-Translator: MAE \n" "Language-Team: none\n" "Language: ja\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 5.4-dev\n" +"X-Generator: Weblate 5.13-dev\n" #: main.c msgid "" @@ -95,7 +95,7 @@ msgstr "%dアドレスピン、%dRGBピン、%dタイルは%dの高さを指示 msgid "%q and %q contain duplicate pins" msgstr "%q と %q に重複するピンがあります" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: shared-bindings/audioio/AudioOut.c msgid "%q and %q must be different" msgstr "%qと%qが必ず異なるのは必要" @@ -115,6 +115,10 @@ msgstr "%q に重複するピンがあります" msgid "%q failure: %d" msgstr "%q 失敗: %d" +#: shared-module/audiodelays/MultiTapDelay.c +msgid "%q in %q must be of type %q or %q, not %q" +msgstr "" + #: py/argcheck.c shared-module/audiofilters/Filter.c msgid "%q in %q must be of type %q, not %q" msgstr "%q 内の %q は %q 型である必要があり、 %q 型は使用できません" @@ -167,7 +171,7 @@ msgstr "%q の長さは <= %d である必要があります" msgid "%q length must be >= %d" msgstr "%q の長さは >= %d である必要があります" -#: py/modsys.c py/objmodule.c py/runtime.c +#: py/modsys.c py/runtime.c msgid "%q moved from %q to %q" msgstr "%q は %q から %q へ移動しました" @@ -223,13 +227,13 @@ msgstr "%q は 'h' 型の array である必要があります" #: shared-bindings/audiobusio/PDMIn.c msgid "%q must be multiple of 8." -msgstr "%q は 8 の倍数である必要があります" +msgstr "%q は 8 の倍数である必要があります." #: ports/raspberrypi/bindings/cyw43/__init__.c py/argcheck.c py/objexcept.c #: shared-bindings/bitmapfilter/__init__.c shared-bindings/canio/CAN.c #: shared-bindings/digitalio/Pull.c shared-bindings/supervisor/__init__.c #: shared-module/audiofilters/Filter.c shared-module/displayio/__init__.c -#: shared-module/synthio/Biquad.c shared-module/synthio/Synthesizer.c +#: shared-module/synthio/Synthesizer.c msgid "%q must be of type %q or %q, not %q" msgstr "%q は %q 型か %q 型である必要があります、 %q 型は使用できません" @@ -239,6 +243,7 @@ msgstr "" "%q は %q 型や %q 型または %q 型である必要があります、 %q 型は使用できません" #: py/argcheck.c py/runtime.c shared-bindings/bitmapfilter/__init__.c +#: shared-module/audiodelays/MultiTapDelay.c shared-module/synthio/Note.c #: shared-module/synthio/__init__.c msgid "%q must be of type %q, not %q" msgstr "%q は %q 型である必要があります、 %q 型は使用できません" @@ -319,7 +324,7 @@ msgid "'%q' object does not support '%q'" msgstr "'%q' オブジェクトは '%q' に対応していません" #: py/runtime.c -msgid "'%q' object is not an iterator" +msgid "'%q' object isn't an iterator" msgstr "オブジェクト'%q'はイテレータではありません" #: py/objtype.c py/runtime.c shared-module/atexit/__init__.c @@ -327,7 +332,7 @@ msgid "'%q' object is not callable" msgstr "オブジェクト'%q'は呼び出し可能ではありません" #: py/runtime.c -msgid "'%q' object is not iterable" +msgid "'%q' object isn't iterable" msgstr "オブジェクト'%q'はイテレート可能ではありません" #: py/emitinlinethumb.c py/emitinlinextensa.c @@ -808,7 +813,7 @@ msgid "Cannot record to a file" msgstr "ファイルへ記録できません" #: shared-module/storage/__init__.c -msgid "Cannot remount '/' when visible via USB." +msgid "Cannot remount path when visible via USB." msgstr "" #: shared-bindings/digitalio/DigitalInOut.c @@ -862,6 +867,10 @@ msgstr "" msgid "Coordinate arrays types have different sizes" msgstr "" +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "Could not publish to ROS topic" +msgstr "" + #: shared-bindings/_bleio/Adapter.c msgid "Could not set address" msgstr "アドレスをセットできません" @@ -874,6 +883,11 @@ msgstr "割り込みをスタートできません。RXビジー" msgid "Couldn't allocate decoder" msgstr "デコーダを確保できません" +#: ports/espressif/common-hal/rclcpy/__init__.c +#, c-format +msgid "Critical ROS failure during soft reboot, reset required: %d" +msgstr "" + #: ports/stm/common-hal/analogio/AnalogOut.c msgid "DAC Channel Init Error" msgstr "DACチャネル初期化エラー" @@ -1070,6 +1084,7 @@ msgstr "内部フラッシュ書き込みに失敗" msgid "File exists" msgstr "ファイルが存在します" +#: shared-bindings/supervisor/__init__.c shared-module/lvfontio/OnDiskFont.c #: shared-module/os/getenv.c msgid "File not found" msgstr "" @@ -1101,7 +1116,7 @@ msgstr "" msgid "For RGB colorspaces, input bitmap must have 16 bits per pixel" msgstr "" -#: ports/cxd56/common-hal/camera/Camera.c +#: ports/cxd56/common-hal/camera/Camera.c shared-module/audiocore/WaveFile.c msgid "Format not supported" msgstr "非対応の形式" @@ -1265,7 +1280,9 @@ msgstr "" #: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c py/argcheck.c #: shared-bindings/digitalio/DigitalInOut.c #: shared-bindings/epaperdisplay/EPaperDisplay.c shared-bindings/pwmio/PWMOut.c +#: shared-bindings/supervisor/__init__.c #: shared-module/aurora_epaper/aurora_framebuffer.c +#: shared-module/lvfontio/OnDiskFont.c msgid "Invalid %q" msgstr "不正な %q" @@ -1298,6 +1315,10 @@ msgstr "不正なBSSID" msgid "Invalid MAC address" msgstr "" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "Invalid ROS domain ID" +msgstr "" + #: ports/espressif/common-hal/espidf/__init__.c py/moderrno.c msgid "Invalid argument" msgstr "不正な引数" @@ -1387,6 +1408,11 @@ msgstr "" msgid "MITM security not supported" msgstr "" +#: ports/stm/common-hal/sdioio/SDCard.c +#, c-format +msgid "MMC/SDIO Clock Error %x" +msgstr "" + #: shared-bindings/is31fl3741/IS31FL3741.c msgid "Mapping must be a tuple" msgstr "" @@ -1573,6 +1599,10 @@ msgstr "" msgid "No pulldown on pin; 1Mohm recommended" msgstr "ピンにプルダウンがありません。1Mオーム推奨" +#: shared-module/touchio/TouchIn.c +msgid "No pullup on pin; 1Mohm recommended" +msgstr "" + #: py/moderrno.c msgid "No space left on device" msgstr "デバイスに空き容量が残っていません" @@ -1848,6 +1878,10 @@ msgstr "" msgid "Program too long" msgstr "" +#: shared-bindings/rclcpy/Publisher.c +msgid "Publishers can only be created from a parent node" +msgstr "" + #: shared-bindings/digitalio/DigitalInOut.c msgid "Pull not used when direction is output." msgstr "方向がoutputのときpullは使われません" @@ -1868,10 +1902,30 @@ msgstr "RNG解体エラー" msgid "RNG Init Error" msgstr "乱数生成器の初期化エラー" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS failed to initialize. Is agent connected?" +msgstr "" + +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS internal setup failure" +msgstr "" + +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS memory allocator failure" +msgstr "" + +#: ports/espressif/common-hal/rclcpy/Node.c +msgid "ROS node failed to initialize" +msgstr "" + +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "ROS topic failed to initialize" +msgstr "" + #: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c #: ports/nordic/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c msgid "RS485" -msgstr "" +msgstr "RS485" #: ports/espressif/common-hal/busio/UART.c #: ports/mimxrt10xx/common-hal/busio/UART.c @@ -1999,6 +2053,7 @@ msgstr "スライスと値の長さが一致しません" #: shared-bindings/displayio/TileGrid.c #: shared-bindings/memorymonitor/AllocationSize.c #: shared-bindings/pulseio/PulseIn.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c msgid "Slices not supported" msgstr "スライスは対応していません" @@ -2066,7 +2121,9 @@ msgstr "" msgid "Tile height must exactly divide bitmap height" msgstr "タイルの高さはビットマップの高さを割り切れる値でなければなりません" -#: shared-bindings/displayio/TileGrid.c shared-module/displayio/TileGrid.c +#: shared-bindings/displayio/TileGrid.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-module/displayio/TileGrid.c msgid "Tile index out of bounds" msgstr "タイルのインデクスが範囲外" @@ -2074,6 +2131,10 @@ msgstr "タイルのインデクスが範囲外" msgid "Tile width must exactly divide bitmap width" msgstr "タイルの幅はビットマップの幅を割り切れる値でなければなりません" +#: shared-module/tilepalettemapper/TilePaletteMapper.c +msgid "TilePaletteMapper may only be bound to a TileGrid once" +msgstr "" + #: shared-bindings/alarm/time/TimeAlarm.c msgid "Time is in the past." msgstr "" @@ -2301,10 +2362,6 @@ msgstr "" msgid "Unsupported display bus type" msgstr "" -#: shared-module/audiocore/WaveFile.c -msgid "Unsupported format" -msgstr "非対応の形式" - #: shared-bindings/hashlib/__init__.c msgid "Unsupported hash algorithm" msgstr "" @@ -2361,8 +2418,10 @@ msgstr "" msgid "Wi-Fi: " msgstr "" +#: ports/espressif/common-hal/wifi/Radio.c #: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "Wifi is not enabled" +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "WiFi is not enabled" msgstr "" #: main.c @@ -2598,9 +2657,16 @@ msgstr "" msgid "bits must be 32 or less" msgstr "" -#: shared-bindings/audiodelays/Echo.c shared-bindings/audiodelays/PitchShift.c +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "bits_per_sample must be 16" +msgstr "" + +#: shared-bindings/audiodelays/Chorus.c shared-bindings/audiodelays/Echo.c +#: shared-bindings/audiodelays/MultiTapDelay.c +#: shared-bindings/audiodelays/PitchShift.c #: shared-bindings/audiofilters/Distortion.c -#: shared-bindings/audiofilters/Filter.c shared-bindings/audiomixer/Mixer.c +#: shared-bindings/audiofilters/Filter.c shared-bindings/audiofilters/Phaser.c +#: shared-bindings/audiomixer/Mixer.c msgid "bits_per_sample must be 8 or 16" msgstr "bits_per_sampleは8または16でなければなりません" @@ -3144,7 +3210,7 @@ msgid "format" msgstr "" #: py/objstr.c -msgid "format requires a dict" +msgid "format needs a dict" msgstr "formatにはdictが必要" #: py/objdeque.c @@ -3604,7 +3670,7 @@ msgid "must use keyword argument for key function" msgstr "" #: py/runtime.c -msgid "name '%q' is not defined" +msgid "name '%q' isn't defined" msgstr "名前 '%q' は定義されていません" #: py/runtime.c @@ -4022,6 +4088,10 @@ msgstr "" msgid "rsplit(None,n)" msgstr "rsplit(None,n)" +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "samples_signed must be true" +msgstr "" + #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c #: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "sampling rate out of range" @@ -4241,11 +4311,11 @@ msgid "tx and rx cannot both be None" msgstr "txとrxを両方ともNoneにできません" #: py/objtype.c -msgid "type '%q' is not an acceptable base type" +msgid "type '%q' isn't an acceptable base type" msgstr "型'%q'はベース型として使えません" #: py/objtype.c -msgid "type is not an acceptable base type" +msgid "type isn't an acceptable base type" msgstr "この型はベース型にできません" #: py/runtime.c @@ -4307,7 +4377,9 @@ msgstr "" msgid "unreadable attribute" msgstr "読み込み不可能な属性" -#: shared-bindings/displayio/TileGrid.c shared-bindings/vectorio/VectorShape.c +#: shared-bindings/displayio/TileGrid.c shared-bindings/terminalio/Terminal.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-bindings/vectorio/VectorShape.c msgid "unsupported %q type" msgstr "非対応の型 %q" @@ -4385,12 +4457,6 @@ msgstr "" msgid "width must be greater than zero" msgstr "" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/raspberrypi/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "wifi is not enabled" -msgstr "" - #: ports/raspberrypi/common-hal/wifi/Monitor.c msgid "wifi.Monitor not available" msgstr "" @@ -4453,6 +4519,9 @@ msgstr "ziはfloat値でなければなりません" msgid "zi must be of shape (n_section, 2)" msgstr "" +#~ msgid "Unsupported format" +#~ msgstr "非対応の形式" + #~ msgid "Data chunk must follow fmt chunk" #~ msgstr "fmtチャンクの後にdataチャンクが続かなければなりません" @@ -4617,7 +4686,7 @@ msgstr "" #~ msgid "'continue' outside loop" #~ msgstr "ループ外でのcontinue" -#~ msgid "'coroutine' object is not an iterator" +#~ msgid "'coroutine' object isn't an iterator" #~ msgstr "'coroutine' オブジェクトはイテレータではありません" #~ msgid "Address type out of range" @@ -5217,7 +5286,7 @@ msgstr "" #~ msgid "n must be between 0, and 9" #~ msgstr "nは0から9まで" -#~ msgid "name reused for argument" +#~ msgid "argument name reused" #~ msgstr "引数で名前が再利用されています" #~ msgid "no available NIC" diff --git a/locale/ko.po b/locale/ko.po index ef0e72d8bb0..58aa0a59636 100644 --- a/locale/ko.po +++ b/locale/ko.po @@ -7,2399 +7,2719 @@ 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: 2023-12-23 14:56+0000\n" -"Last-Translator: 오수아 \n" +"PO-Revision-Date: 2025-06-30 16:01+0000\n" +"Last-Translator: MAE \n" "Language-Team: LANGUAGE \n" "Language: ko\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 5.4-dev\n" +"X-Generator: Weblate 5.13-dev\n" -#: main.c -msgid "" -"\n" -"Code done running.\n" +#: extmod/modasyncio.c extmod/modheapq.c +msgid "empty heap" msgstr "" -"\n" -"코드 실행 완료.\n" -#: main.c -msgid "" -"\n" -"Code stopped by auto-reload. Reloading soon.\n" +#: extmod/modasyncio.c +msgid "can't cancel self" msgstr "" -"\n" -"자동 업로드에 의해 코드가 중지되었습니다. 곧 다시 로드됩니다.\n" -#: supervisor/shared/safe_mode.c -msgid "" -"\n" -"Please file an issue with your program at github.com/adafruit/circuitpython/" -"issues." +#: extmod/modasyncio.c +msgid "can't wait" msgstr "" -"\n" -"github.com/adafruit/circuitpython/issues 에\n" -"프로그램 오류를 제출하세요." -#: supervisor/shared/safe_mode.c -msgid "" -"\n" -"Press reset to exit safe mode.\n" +#: extmod/modbinascii.c extmod/modhashlib.c py/objarray.c +msgid "a bytes-like object is required" msgstr "" -"\n" -"재설정을 눌러 안전 모드를 종료합니다.\n" -#: supervisor/shared/safe_mode.c -msgid "" -"\n" -"You are in safe mode because:\n" +#: extmod/modbinascii.c +msgid "incorrect padding" msgstr "" -"\n" -"안전 모드에 있는 이유는 다음과 같습니다:\n" - -#: py/obj.c -msgid " File \"%q\"" -msgstr " 파일 \"%q\"" -#: py/obj.c -msgid " File \"%q\", line %d" -msgstr " 파일 \"%q\", 라인 %d" +#: extmod/moddeflate.c +msgid "format" +msgstr "" -#: py/builtinhelp.c -msgid " is of type %q\n" -msgstr " %q 유형입니다\n" +#: extmod/moddeflate.c +msgid "wbits" +msgstr "" -#: main.c -msgid " not found.\n" -msgstr " 찾을 수 없습니다.\n" +#: extmod/modhashlib.c +msgid "hash is final" +msgstr "" -#: main.c -msgid " output:\n" -msgstr " 산출:\n" +#: extmod/modheapq.c +msgid "heap must be a list" +msgstr "" -#: py/objstr.c -#, c-format -msgid "%%c requires int or char" -msgstr "%%c 전수(int)또는 캐릭터(char)필요합니다" +#: extmod/modjson.c +msgid "syntax error in JSON" +msgstr "" -#: shared-bindings/rgbmatrix/RGBMatrix.c -#, c-format -msgid "" -"%d address pins, %d rgb pins and %d tiles indicate a height of %d, not %d" +#: extmod/modrandom.c +msgid "bits must be 32 or less" msgstr "" -"%d 주소 핀들, %d rgb 핀들과 %d 타일 들은 높이가 %d임을 나타낸다, %d가 아니라" -#: shared-bindings/microcontroller/Pin.c -msgid "%q and %q contain duplicate pins" -msgstr "%q 및 %q에 중복된 핀이 포함" +#: extmod/modrandom.c extmod/ulab/code/numpy/random/random.c +msgid "no default seed" +msgstr "" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c -msgid "%q and %q must be different" -msgstr "%q와 %q는 달라야 합니다" +#: extmod/modre.c +msgid "splitting with sub-captures" +msgstr "" -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -msgid "%q and %q must share a clock unit" +#: extmod/modre.c +msgid "regex too complex" msgstr "" -#: ports/nordic/common-hal/watchdog/WatchDogTimer.c -msgid "%q cannot be changed once mode is set to %q" +#: extmod/modre.c +msgid "Error in regex" +msgstr "Regex에 오류가 있습니다." + +#: extmod/modtime.c +msgid "mktime needs a tuple of length 8 or 9" msgstr "" -#: shared-bindings/microcontroller/Pin.c -msgid "%q contains duplicate pins" -msgstr "%q에 중복된 핀이 포함" +#: extmod/modtime.c +msgid "ticks interval overflow" +msgstr "" -#: ports/atmel-samd/common-hal/sdioio/SDCard.c -msgid "%q failure: %d" -msgstr "%q 실패: %d" +#: extmod/modzlib.c +msgid "compression header" +msgstr "" -#: py/argcheck.c shared-module/audiofilters/Filter.c -msgid "%q in %q must be of type %q, not %q" -msgstr "%q의 %q는 %q가 아니라 %q 유형이어야 합니다" +#: extmod/ulab/code/ndarray.c +msgid "data type not understood" +msgstr "" -#: ports/espressif/common-hal/espulp/ULP.c -#: ports/mimxrt10xx/common-hal/audiobusio/__init__.c -#: ports/mimxrt10xx/common-hal/usb_host/Port.c -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -#: ports/raspberrypi/common-hal/usb_host/Port.c -#: shared-bindings/digitalio/DigitalInOut.c -#: shared-bindings/microcontroller/Pin.c shared-module/max3421e/Max3421E.c -msgid "%q in use" -msgstr "%q 사용 중입니다" +#: extmod/ulab/code/ndarray.c +msgid "array is too big" +msgstr "" -#: py/objstr.c -msgid "%q index out of range" -msgstr "%q 인덱스 범위를 벗어났습니다" +#: extmod/ulab/code/ndarray.c +msgid "ndarray length overflows" +msgstr "" -#: py/obj.c -msgid "%q indices must be integers, not %s" -msgstr "%q 인덱스는 %s 가 아닌 정수 여야합니다" +#: extmod/ulab/code/ndarray.c +msgid "maximum number of dimensions is " +msgstr "" -#: shared-module/bitbangio/SPI.c -msgid "%q init failed" -msgstr "%q 초기화 실패" +#: extmod/ulab/code/ndarray.c +msgid "cannot convert complex type" +msgstr "" -#: ports/espressif/bindings/espnow/Peer.c shared-bindings/dualbank/__init__.c -msgid "%q is %q" -msgstr "%q는 %q입니다" +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/create.c +msgid "too many dimensions" +msgstr "" -#: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "%q is read-only for this board" -msgstr "%q는 이 보드에 대한 읽기 전용입니다" +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/transform.c +msgid "index is out of bounds" +msgstr "" -#: py/argcheck.c shared-bindings/usb_hid/Device.c -msgid "%q length must be %d" -msgstr "%q 길이는 %d이어야 합니다" +#: extmod/ulab/code/ndarray.c +msgid "indices must be integers, slices, or Boolean lists" +msgstr "" -#: py/argcheck.c -msgid "%q length must be %d-%d" -msgstr "%q 길이는 %d - %d이어야 합니다" +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/bitwise.c +#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/numpy/vector.c +msgid "operands could not be broadcast together" +msgstr "" -#: py/argcheck.c -msgid "%q length must be <= %d" -msgstr "%q 길이는 <= %d>여야 합니다" +#: extmod/ulab/code/ndarray.c +msgid "array and index length must be equal" +msgstr "" -#: py/argcheck.c -msgid "%q length must be >= %d" -msgstr "%q 길이는 >= %d이어야 합니다" +#: extmod/ulab/code/ndarray.c +msgid "cannot convert complex to dtype" +msgstr "" -#: py/modsys.c py/objmodule.c py/runtime.c -#, fuzzy -msgid "%q moved from %q to %q" -msgstr "%q가 %q에서 %q로 이동했습니다" +#: extmod/ulab/code/ndarray.c +msgid "operation is implemented for 1D Boolean arrays only" +msgstr "" -#: py/argcheck.c -msgid "%q must be %d" -msgstr "%q는 %d이어야 합니다" +#: extmod/ulab/code/ndarray.c +msgid "too many indices" +msgstr "" -#: py/argcheck.c shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/displayio/Bitmap.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -#: shared-bindings/is31fl3741/FrameBuffer.c -#: shared-bindings/rgbmatrix/RGBMatrix.c -msgid "%q must be %d-%d" -msgstr "%q는 %d-%d이어야 합니다" +#: extmod/ulab/code/ndarray.c +msgid "cannot delete array elements" +msgstr "" -#: shared-bindings/busdisplay/BusDisplay.c -msgid "%q must be 1 when %q is True" -msgstr "%q가 참일 때 %q는 1이어야 합니다" +#: extmod/ulab/code/ndarray.c +msgid "flattening order must be either 'C', or 'F'" +msgstr "" -#: py/argcheck.c shared-bindings/gifio/GifWriter.c -#: shared-module/gifio/OnDiskGif.c -#, fuzzy -msgid "%q must be <= %d" -msgstr "%q 는 <= %d 여야 합니다" +#: extmod/ulab/code/ndarray.c +msgid "tobytes can be invoked for dense arrays only" +msgstr "" -#: ports/espressif/common-hal/watchdog/WatchDogTimer.c -#, fuzzy -msgid "%q must be <= %u" -msgstr "%q 는 <= %u 여야 합니다" +#: extmod/ulab/code/ndarray.c +msgid "operation is not supported for given type" +msgstr "" -#: py/argcheck.c -#, fuzzy -msgid "%q must be >= %d" -msgstr "%q 는 >= %d 여야 합니다" +#: extmod/ulab/code/ndarray.c +msgid "keyword argument must be tuple of integers" +msgstr "" -#: shared-bindings/analogbufio/BufferedIn.c -msgid "%q must be a bytearray or array of type 'H' or 'B'" -msgstr "%q는 'H' 또는 'B' 타입의 바이트 배열 또는 배열이어야 합니다" +#: extmod/ulab/code/ndarray.c +msgid "too many axes specified" +msgstr "" -#: shared-bindings/audiocore/RawSample.c -msgid "%q must be a bytearray or array of type 'h', 'H', 'b', or 'B'" -msgstr "%q는 h, H, b 또는 B 유형의 바이트 배열 또는 배열이어야 합니다" +#: extmod/ulab/code/ndarray.c +msgid "axis index out of bounds" +msgstr "" -#: shared-bindings/warnings/__init__.c -msgid "%q must be a subclass of %q" -msgstr "%q는 %q의 하위 클래스여야 합니다" +#: extmod/ulab/code/ndarray.c +msgid "repeated indices" +msgstr "" -#: ports/espressif/common-hal/analogbufio/BufferedIn.c -#, fuzzy -msgid "%q must be array of type 'H'" -msgstr "%q는 'H' 유형의 배열이어야 합니다" +#: extmod/ulab/code/ndarray.c +msgid "shape must be integer or tuple of integers" +msgstr "" -#: shared-module/synthio/__init__.c -#, fuzzy -msgid "%q must be array of type 'h'" -msgstr "%q는 'h' 유형의 배열이어야 합니다" - -#: shared-bindings/audiobusio/PDMIn.c -msgid "%q must be multiple of 8." +#: extmod/ulab/code/ndarray.c +msgid "can only specify one unknown dimension" msgstr "" -#: ports/raspberrypi/bindings/cyw43/__init__.c py/argcheck.c py/objexcept.c -#: shared-bindings/bitmapfilter/__init__.c shared-bindings/canio/CAN.c -#: shared-bindings/digitalio/Pull.c shared-bindings/supervisor/__init__.c -#: shared-module/audiofilters/Filter.c shared-module/displayio/__init__.c -#: shared-module/synthio/Biquad.c shared-module/synthio/Synthesizer.c -msgid "%q must be of type %q or %q, not %q" -msgstr "%q는 %q가 아닌 %q 또는 %q 유형이어야 합니다" +#: extmod/ulab/code/ndarray.c +msgid "cannot reshape array" +msgstr "" -#: shared-bindings/jpegio/JpegDecoder.c -msgid "%q must be of type %q, %q, or %q, not %q" +#: extmod/ulab/code/ndarray.c +msgid "cannot assign new shape" msgstr "" -#: py/argcheck.c py/runtime.c shared-bindings/bitmapfilter/__init__.c -#: shared-module/synthio/__init__.c -msgid "%q must be of type %q, not %q" -msgstr "%q는 %q가 아니라 %q 유형이어야 합니다" +#: extmod/ulab/code/ndarray.c +msgid "function is defined for ndarrays only" +msgstr "" -#: ports/atmel-samd/common-hal/busio/UART.c -msgid "%q must be power of 2" -msgstr "%q는 2의 거듭제곱이어야 합니다" +#: extmod/ulab/code/ndarray_operators.c +msgid "operation not supported for the input types" +msgstr "" -#: shared-bindings/wifi/Monitor.c -#, fuzzy -msgid "%q out of bounds" -msgstr "%q가 경계를 벗어남" +#: extmod/ulab/code/ndarray_operators.c +msgid "dtype of int32 is not supported" +msgstr "" -#: ports/atmel-samd/common-hal/pulseio/PulseIn.c -#: ports/cxd56/common-hal/pulseio/PulseIn.c -#: ports/nordic/common-hal/pulseio/PulseIn.c -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -#: ports/stm/common-hal/pulseio/PulseIn.c py/argcheck.c -#: shared-bindings/canio/Match.c shared-bindings/time/__init__.c -#, fuzzy -msgid "%q out of range" -msgstr "%q가 범위를 벗어남" +#: extmod/ulab/code/ndarray_operators.c +msgid "cannot cast output with casting rule" +msgstr "" -#: py/objmodule.c py/runtime.c -msgid "%q renamed %q" -msgstr "%q가 %q로 이름이 변경되었습니다" +#: extmod/ulab/code/ndarray_operators.c +msgid "results cannot be cast to specified type" +msgstr "" -#: py/objrange.c py/objslice.c shared-bindings/random/__init__.c -#, fuzzy -msgid "%q step cannot be zero" -msgstr "%q 단계는 0일 수 없습니다" +#: extmod/ulab/code/numpy/approx.c +msgid "interp is defined for 1D iterables of equal length" +msgstr "" -#: shared-module/bitbangio/I2C.c -msgid "%q too long" +#: extmod/ulab/code/numpy/approx.c +msgid "trapz is defined for 1D iterables" msgstr "" -#: py/bc.c py/objnamedtuple.c -#, fuzzy -msgid "%q() takes %d positional arguments but %d were given" -msgstr "%q()는 %d 위치 인수를 사용하지만 %d이(가) 주어졌습니다" +#: extmod/ulab/code/numpy/approx.c +msgid "trapz is defined for 1D arrays of equal length" +msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "%q() without %q()" +#: extmod/ulab/code/numpy/bitwise.c +msgid "not supported for input types" msgstr "" -#: shared-bindings/usb_hid/Device.c -msgid "%q, %q, and %q must all be the same length" -msgstr "%q, %q 및 %q의 길이는 모두 같아야 합니다" +#: extmod/ulab/code/numpy/carray/carray.c +msgid "function is implemented for ndarrays only" +msgstr "" -#: py/objint.c shared-bindings/_bleio/Connection.c -#: shared-bindings/storage/__init__.c -msgid "%q=%q" -msgstr "%q=%q" +#: extmod/ulab/code/numpy/carray/carray.c +msgid "input must be an ndarray, or a scalar" +msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -#, fuzzy -msgid "%q[%u] shifts in more bits than pin count" -msgstr "%q[%u]가 핀 수보다 더 많은 비트로 이동했습니다" +#: extmod/ulab/code/numpy/carray/carray.c +msgid "input must be a 1D ndarray" +msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -#, fuzzy -msgid "%q[%u] shifts out more bits than pin count" -msgstr "%q[%u]이(가) 핀 수보다 많은 비트를 전송합니다" +#: extmod/ulab/code/numpy/carray/carray_tools.c +msgid "not implemented for complex dtype" +msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "%q[%u] uses extra pin" -msgstr "%q[%u]에서 추가 핀 사용" +#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/user/user.c +#: shared-bindings/_eve/__init__.c +msgid "input must be an ndarray" +msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "%q[%u] waits on input outside of count" -msgstr "%q[%u]이(가) 카운트 외부의 입력을 대기합니다" +#: extmod/ulab/code/numpy/compare.c +msgid "object too deep for desired array" +msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -#, fuzzy, c-format -msgid "%s error 0x%x" -msgstr "%s 오류 0x%x" +#: extmod/ulab/code/numpy/compare.c +msgid "cannot cast array data from dtype" +msgstr "" -#: py/argcheck.c -msgid "'%q' argument required" -msgstr "'%q' 인수가 필요합니다" +#: extmod/ulab/code/numpy/compare.c +msgid "minlength must not be negative" +msgstr "" -#: py/proto.c -msgid "'%q' object does not support '%q'" -msgstr "'%q' 개체가 '%q'를 지원하지 않습니다" +#: extmod/ulab/code/numpy/compare.c +msgid "the weights and list don't have the same length" +msgstr "" -#: py/runtime.c -msgid "'%q' object is not an iterator" -msgstr "'%q' 개체가 iterator가 아닙니다" +#: extmod/ulab/code/numpy/compare.c +msgid "cannot cast weigths to float" +msgstr "" -#: py/objtype.c py/runtime.c shared-module/atexit/__init__.c -msgid "'%q' object is not callable" -msgstr "'%q' 개체를 호출할 수 없습니다" +#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/numpy/create.c +#: extmod/ulab/code/numpy/io/io.c extmod/ulab/code/numpy/transform.c +#: extmod/ulab/code/numpy/vector.c +msgid "wrong input type" +msgstr "" -#: py/runtime.c -msgid "'%q' object is not iterable" -msgstr "'%q' 개체를 사용할 수 없습니다" +#: extmod/ulab/code/numpy/create.c +msgid "input argument must be an integer, a tuple, or a list" +msgstr "" -#: py/emitinlinethumb.c py/emitinlinextensa.c -#, c-format -msgid "'%s' expects a label" -msgstr "'%s' 에는 라벨이 필요합니다" +#: extmod/ulab/code/numpy/create.c py/objarray.c py/objstr.c +msgid "wrong number of arguments" +msgstr "" -#: py/emitinlinethumb.c py/emitinlinextensa.c -#, c-format -msgid "'%s' expects a register" -msgstr "'%s' 에는 레지스터가 필요합니다" +#: extmod/ulab/code/numpy/create.c py/objint_longlong.c py/objint_mpz.c +msgid "divide by zero" +msgstr "" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects a special register" -msgstr "'%s' 에는 특별한 레지스터가 필요합니다" +#: extmod/ulab/code/numpy/create.c +msgid "arange: cannot compute length" +msgstr "" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects an FPU register" -msgstr "'%s' 에는 FPU레지스터가 필요합니다" +#: extmod/ulab/code/numpy/create.c +msgid "first argument must be a tuple of ndarrays" +msgstr "" -#: py/emitinlinethumb.c -#, fuzzy, c-format -msgid "'%s' expects an address of the form [a, b]" -msgstr "'%s' 에는 [a, b] 형식의 주소가 필요합니다" +#: extmod/ulab/code/numpy/create.c +msgid "only ndarrays can be concatenated" +msgstr "" -#: py/emitinlinethumb.c py/emitinlinextensa.c -#, c-format -msgid "'%s' expects an integer" -msgstr "'%s' 는 정수 여야합니다" +#: extmod/ulab/code/numpy/create.c +msgid "wrong axis specified" +msgstr "" -#: py/emitinlinethumb.c -#, fuzzy, c-format -msgid "'%s' expects at most r%d" -msgstr "'%s'는 최대 r%d를 필요로 합니다" +#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c +msgid "input arrays are not compatible" +msgstr "" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects {r0, r1, ...}" -msgstr "'%s' {r0, r1, ...}은 을 기대합니다" +#: extmod/ulab/code/numpy/create.c +msgid "input must be 1- or 2-d" +msgstr "" -#: py/emitinlinextensa.c -#, fuzzy, c-format -msgid "'%s' integer %d isn't within range %d..%d" -msgstr "'%s' 정수 %d가 %d..%d 범위 내에 있지 않습니다" +#: extmod/ulab/code/numpy/create.c +msgid "number of points must be at least 2" +msgstr "" -#: py/emitinlinethumb.c -#, fuzzy, c-format -msgid "'%s' integer 0x%x doesn't fit in mask 0x%x" -msgstr "'%s' 정수 0x%x 이 마스크 0x%x에 맞지 않습니다" +#: extmod/ulab/code/numpy/create.c +msgid "indexing should be 'xy' or 'ij'" +msgstr "" -#: py/obj.c -#, fuzzy, c-format -msgid "'%s' object doesn't support item assignment" -msgstr "'%s' 개체가 항목 할당을 지원하지 않습니다" +#: extmod/ulab/code/numpy/create.c +msgid "indexing must be 'xy' or 'ij'" +msgstr "" -#: py/obj.c -#, fuzzy, c-format -msgid "'%s' object doesn't support item deletion" -msgstr "'%s' 개체가 항목 삭제를 지원하지 않습니다" +#: extmod/ulab/code/numpy/create.c +msgid "too many input arrays" +msgstr "" -#: py/runtime.c -#, fuzzy -msgid "'%s' object has no attribute '%q'" -msgstr "'%s' 개체에 '%q' 특성이 없습니다" +#: extmod/ulab/code/numpy/create.c extmod/ulab/code/numpy/numerical.c +#: extmod/ulab/code/numpy/transform.c +msgid "arguments must be ndarrays" +msgstr "" -#: py/obj.c -#, c-format -msgid "'%s' object isn't subscriptable" -msgstr "'%s' 개체를 subscriptable 할 수 없습니다" +#: extmod/ulab/code/numpy/create.c +msgid "arguments must be 1D arrays" +msgstr "" -#: py/objstr.c -#, fuzzy -msgid "'=' alignment not allowed in string format specifier" -msgstr "'=' 문자열 형식 지정자에서 정렬이 허용되지 않습니다" +#: extmod/ulab/code/numpy/create.c +msgid "input is not an array" +msgstr "" -#: shared-module/struct/__init__.c -msgid "'S' and 'O' are not supported format types" -msgstr "'S' 및 'O'는 지원되지 않는 형식 유형입니다" +#: extmod/ulab/code/numpy/create.c extmod/ulab/code/numpy/numerical.c +#: ports/espressif/common-hal/pulseio/PulseIn.c +#: shared-bindings/bitmaptools/__init__.c +msgid "index out of range" +msgstr "" -#: py/compile.c -msgid "'align' requires 1 argument" -msgstr "'align' 에는 1 개의 독립변수가 필요합니다" +#: extmod/ulab/code/numpy/create.c +msgid "mode should be raise, wrap or clip" +msgstr "" -#: py/compile.c -msgid "'await' outside function" -msgstr "'await' 는 펑크션 외부에 있습니다" +#: extmod/ulab/code/numpy/create.c +msgid "index must not be negative" +msgstr "" -#: py/compile.c -msgid "'break'/'continue' outside loop" -msgstr "'break'/'continue' 외부 루프" +#: extmod/ulab/code/numpy/create.c +msgid "offset must be non-negative and no greater than buffer length" +msgstr "" -#: py/compile.c -msgid "'data' requires at least 2 arguments" -msgstr "'data' 에는 >=2 개의 독립변수가 필요합니다" - -#: py/compile.c -#, fuzzy -msgid "'data' requires integer arguments" -msgstr "'data' 에는 정수 인수가 필요합니다" - -#: py/compile.c -msgid "'label' requires 1 argument" -msgstr "'label' 에는 1 개의 독립변수가 필요합니다" +#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c +msgid "buffer size must be a multiple of element size" +msgstr "" -#: py/emitnative.c -msgid "'not' not implemented" +#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c +msgid "buffer is smaller than requested size" msgstr "" -#: py/compile.c -msgid "'return' outside function" -msgstr "'return' 는 함수 외부에 존재합니다" +#: extmod/ulab/code/numpy/fft/fft_tools.c +msgid "FFT is defined for ndarrays only" +msgstr "FFT는 ndarrays에 대해서만 정의됩니다" -#: py/compile.c -#, fuzzy -msgid "'yield from' inside async function" -msgstr "비동기 함수 내 'yield from'" +#: extmod/ulab/code/numpy/fft/fft_tools.c +msgid "FFT is implemented for linear arrays only" +msgstr "FFT는 선형 배열에 대해서만 구현됩니다" -#: py/compile.c -msgid "'yield' outside function" -msgstr "'yield' 는 함수 외부에 존재합니다" +#: extmod/ulab/code/numpy/fft/fft_tools.c extmod/ulab/code/utils/utils.c +msgid "input array length must be power of 2" +msgstr "" -#: py/compile.c -#, fuzzy -msgid "* arg after **" -msgstr "* 인수 뒤에 **" +#: extmod/ulab/code/numpy/fft/fft_tools.c +msgid "real and imaginary parts must be of equal length" +msgstr "" -#: py/compile.c -#, fuzzy -msgid "*x must be assignment target" -msgstr "*x는 할당 대상이어야 합니다" +#: extmod/ulab/code/numpy/filter.c +msgid "convolve arguments must be ndarrays" +msgstr "" -#: py/obj.c -msgid ", in %q\n" -msgstr ", 에서 %q\n" +#: extmod/ulab/code/numpy/filter.c +msgid "convolve arguments must be linear arrays" +msgstr "" -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/epaperdisplay/EPaperDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -#, fuzzy -msgid ".show(x) removed. Use .root_group = x" -msgstr ".show(x)가 제거되었습니다. .root_group = x를 사용합니다" +#: extmod/ulab/code/numpy/filter.c +msgid "convolve arguments must not be empty" +msgstr "" -#: py/objcomplex.c -msgid "0.0 to a complex power" +#: extmod/ulab/code/numpy/io/io.c +msgid "corrupted file" msgstr "" -#: py/modbuiltins.c -msgid "3-arg pow() not supported" -msgstr "pow() 는 3개의 인수를 지원하지 않습니다" +#: extmod/ulab/code/numpy/io/io.c +msgid "wrong dtype" +msgstr "" -#: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "AP could not be started" -msgstr "AP를 시작할 수 없습니다" +#: extmod/ulab/code/numpy/io/io.c +msgid "usecols keyword must be specified" +msgstr "" -#: shared-bindings/_bleio/Address.c shared-bindings/ipaddress/IPv4Address.c -#, c-format -msgid "Address must be %d bytes long" -msgstr "주소 길이는 % d 바이트 여야합니다" +#: extmod/ulab/code/numpy/io/io.c +msgid "empty file" +msgstr "" -#: ports/espressif/common-hal/memorymap/AddressRange.c -#: ports/nordic/common-hal/memorymap/AddressRange.c -#: ports/raspberrypi/common-hal/memorymap/AddressRange.c -msgid "Address range not allowed" -msgstr "주소 범위가 허용되지 않습니다" +#: extmod/ulab/code/numpy/io/io.c +msgid "usecols is too high" +msgstr "" -#: shared-bindings/memorymap/AddressRange.c -msgid "Address range wraps around" +#: extmod/ulab/code/numpy/io/io.c +msgid "array has too many dimensions" msgstr "" -#: ports/espressif/common-hal/canio/CAN.c -#, fuzzy -msgid "All CAN peripherals are in use" -msgstr "모든 CAN 주변 기기가 사용 중입니다" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "input matrix is asymmetric" +msgstr "" -#: ports/espressif/common-hal/busio/I2C.c -#: ports/espressif/common-hal/i2ctarget/I2CTarget.c -#: ports/nordic/common-hal/busio/I2C.c -msgid "All I2C peripherals are in use" -msgstr "사용 중인 모든 I2C주변 기기" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "matrix is not positive definite" +msgstr "" -#: ports/atmel-samd/common-hal/canio/Listener.c -#: ports/espressif/common-hal/canio/Listener.c -#: ports/stm/common-hal/canio/Listener.c -#, fuzzy -msgid "All RX FIFOs in use" -msgstr "모든 RX FIFOs가 사용 중입니다" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "iterations did not converge" +msgstr "" -#: ports/espressif/common-hal/busio/SPI.c ports/nordic/common-hal/busio/SPI.c -msgid "All SPI peripherals are in use" -msgstr "사용중인 모든 SPI주변 기기" +#: extmod/ulab/code/numpy/linalg/linalg.c +#: extmod/ulab/code/scipy/linalg/linalg.c +msgid "input matrix is singular" +msgstr "" -#: ports/espressif/common-hal/busio/UART.c ports/nordic/common-hal/busio/UART.c -msgid "All UART peripherals are in use" -msgstr "사용중인 모든 UART주변 기기" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "operation is defined for ndarrays only" +msgstr "" -#: ports/nordic/common-hal/countio/Counter.c -#: ports/nordic/common-hal/pulseio/PulseIn.c -#: ports/nordic/common-hal/rotaryio/IncrementalEncoder.c -msgid "All channels in use" -msgstr "모든 채널이 사용중입니다" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "operation is defined for 2D arrays only" +msgstr "" -#: ports/raspberrypi/common-hal/usb_host/Port.c -msgid "All dma channels in use" -msgstr "모든 dma채널이 사용 중입니다" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "mode must be complete, or reduced" +msgstr "" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c -#, fuzzy -msgid "All event channels in use" -msgstr "모든 이벤트 채널이 사용 중입니다" +#: extmod/ulab/code/numpy/numerical.c +msgid "attempt to get argmin/argmax of an empty sequence" +msgstr "" -#: ports/raspberrypi/common-hal/floppyio/__init__.c -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -#: ports/raspberrypi/common-hal/usb_host/Port.c -#, fuzzy -msgid "All state machines in use" -msgstr "모든 상태 머신이 사용 중입니다" +#: extmod/ulab/code/numpy/numerical.c +msgid "attempt to get (arg)min/(arg)max of empty sequence" +msgstr "" -#: ports/atmel-samd/audio_dma.c -#, fuzzy -msgid "All sync event channels in use" -msgstr "모든 동기화 이벤트 채널이 사용 중입니다" +#: extmod/ulab/code/numpy/numerical.c extmod/ulab/code/ulab_tools.c +msgid "axis must be None, or an integer" +msgstr "" -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c -msgid "All timers for this pin are in use" -msgstr "핀의 모든 타이머가 사용 중입니다" +#: extmod/ulab/code/numpy/numerical.c +msgid "operation is not implemented on ndarrays" +msgstr "" -#: ports/atmel-samd/common-hal/_pew/PewPew.c -#: ports/atmel-samd/common-hal/audioio/AudioOut.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/nordic/common-hal/audiopwmio/PWMAudioOut.c -#: ports/nordic/common-hal/pulseio/PulseIn.c -#: ports/nordic/peripherals/nrf/timers.c -#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c -msgid "All timers in use" -msgstr "모든 타이머가 사용 중입니다" +#: extmod/ulab/code/numpy/numerical.c +msgid "input must be tuple, list, range, or ndarray" +msgstr "" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -#, fuzzy -msgid "Already advertising." -msgstr "이미 광고 중입니다." +#: extmod/ulab/code/numpy/numerical.c +msgid "sort argument must be an ndarray" +msgstr "" -#: ports/atmel-samd/common-hal/canio/Listener.c -#, fuzzy -msgid "Already have all-matches listener" -msgstr "이미 모든 일치 리스너가 있습니다" +#: extmod/ulab/code/numpy/numerical.c +msgid "argsort argument must be an ndarray" +msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -msgid "Already in progress" +#: extmod/ulab/code/numpy/numerical.c +msgid "argsort is not implemented for flattened arrays" msgstr "" -#: ports/espressif/bindings/espnow/ESPNow.c -#: ports/espressif/common-hal/espulp/ULP.c -#: shared-module/memorymonitor/AllocationAlarm.c -#: shared-module/memorymonitor/AllocationSize.c -msgid "Already running" -msgstr "이미 실행 중입니다" +#: extmod/ulab/code/numpy/numerical.c +msgid "axis too long" +msgstr "" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/raspberrypi/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -#, fuzzy -msgid "Already scanning for wifi networks" -msgstr "이미 wifi 네트워크를 찾고 있습니다" +#: extmod/ulab/code/numpy/numerical.c +msgid "cross is defined for 1D arrays of length 3" +msgstr "" -#: shared-module/os/getenv.c -#, c-format -msgid "An error occurred while retrieving '%s':\n" -msgstr "%s'을(를) 검색하는 동안 오류가 발생했습니다:\n" +#: extmod/ulab/code/numpy/numerical.c +msgid "diff argument must be an ndarray" +msgstr "" -#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c -#, fuzzy -msgid "Another PWMAudioOut is already active" -msgstr "다른 PWMaudioOut이 이미 활성화되어 있습니다" +#: extmod/ulab/code/numpy/numerical.c +msgid "differentiation order out of range" +msgstr "" -#: ports/atmel-samd/common-hal/pulseio/PulseOut.c -#: ports/cxd56/common-hal/pulseio/PulseOut.c -msgid "Another send is already active" -msgstr "다른 전송이 이미 활성화되었습니다" +#: extmod/ulab/code/numpy/numerical.c +msgid "flip argument must be an ndarray" +msgstr "" -#: shared-bindings/pulseio/PulseOut.c -msgid "Array must contain halfwords (type 'H')" -msgstr "배열은 하프워드(유형 'H')가 포함되어야 합니다" +#: extmod/ulab/code/numpy/numerical.c +msgid "wrong axis index" +msgstr "" -#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c -#: shared-bindings/nvm/ByteArray.c -#, fuzzy -msgid "Array values should be single bytes." -msgstr "배열 값은 1바이트 여야합니다." - -#: ports/atmel-samd/common-hal/spitarget/SPITarget.c -msgid "Async SPI transfer in progress on this bus, keep awaiting." +#: extmod/ulab/code/numpy/numerical.c +msgid "median argument must be an ndarray" msgstr "" -#: shared-module/memorymonitor/AllocationAlarm.c -#, c-format -msgid "Attempt to allocate %d blocks" -msgstr "%d 블록 할당 시도" +#: extmod/ulab/code/numpy/numerical.c +msgid "roll argument must be an ndarray" +msgstr "" -#: ports/raspberrypi/audio_dma.c -msgid "Audio conversion not implemented" -msgstr "오디오 변환이 구현되지 않음" +#: extmod/ulab/code/numpy/poly.c +msgid "input data must be an iterable" +msgstr "" -#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c -#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c -msgid "Audio source error" +#: extmod/ulab/code/numpy/poly.c +msgid "more degrees of freedom than data points" msgstr "" -#: shared-bindings/wifi/Radio.c -msgid "AuthMode.OPEN is not used with password" -msgstr "AuthMode.OPEN은 암호와 함께 사용되지 않습니다" +#: extmod/ulab/code/numpy/poly.c +msgid "input vectors must be of equal length" +msgstr "" -#: shared-bindings/wifi/Radio.c supervisor/shared/web_workflow/web_workflow.c -msgid "Authentication failure" -msgstr "인증 실패" +#: extmod/ulab/code/numpy/poly.c +msgid "could not invert Vandermonde matrix" +msgstr "" -#: main.c -msgid "Auto-reload is off.\n" -msgstr "자동 재 장전이 꺼져 있습니다\n" +#: extmod/ulab/code/numpy/poly.c +msgid "input is not iterable" +msgstr "" -#: main.c -msgid "" -"Auto-reload is on. Simply save files over USB to run them or enter REPL to " -"disable.\n" +#: extmod/ulab/code/numpy/random/random.c +msgid "argument must be None, an integer or a tuple of integers" msgstr "" -"자동 새로 고침이 켜져 있습니다. USB를 통해 파일을 저장하여 실행하십시오. 비활" -"성화하려면 REPL을 입력하십시오.\n" -#: ports/espressif/common-hal/canio/CAN.c -msgid "Baudrate not supported by peripheral" -msgstr "주변 기기에서 전송 속도가 지원되지 않습니다" +#: extmod/ulab/code/numpy/random/random.c +msgid "shape must be None, an integer or a tuple of integers" +msgstr "" -#: shared-module/busdisplay/BusDisplay.c -#: shared-module/framebufferio/FramebufferDisplay.c -msgid "Below minimum frame rate" -msgstr "최소 프레임 속도 미만" +#: extmod/ulab/code/numpy/random/random.c extmod/ulab/code/ulab_tools.c +msgid "out has wrong type" +msgstr "" -#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c -msgid "Bit clock and word select must be sequential GPIO pins" -msgstr "비트 클럭 및 워드 선택은 순차적 GPIO 핀이어야 합니다" +#: extmod/ulab/code/numpy/random/random.c +msgid "output array has wrong type" +msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "Bitmap size and bits per value must match" -msgstr "비트맵 크기와 값 당 비트가 일치해야 합니다" +#: extmod/ulab/code/numpy/random/random.c +msgid "size must match out.shape when used together" +msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Boot device must be first (interface #0)." -msgstr "부팅 장치는 첫 번째(인터페이스 #0)여야 합니다." +#: extmod/ulab/code/numpy/random/random.c extmod/ulab/code/ulab_tools.c +msgid "output array must be contiguous" +msgstr "" -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Both RX and TX required for flow control" -msgstr "플로우 제어에 RX와 TX가 모두 필요합니다" +#: extmod/ulab/code/numpy/transform.c +msgid "wrong length of condition array" +msgstr "" -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -msgid "Brightness not adjustable" -msgstr "밝기를 조절할 수 없습니다" +#: extmod/ulab/code/numpy/transform.c extmod/ulab/code/numpy/vector.c +msgid "first argument must be an ndarray" +msgstr "" -#: shared-bindings/_bleio/UUID.c -#, c-format -msgid "Buffer + offset too small %d %d %d" -msgstr "Buffer + offset이 너무 작습니다 %d %d %d" +#: extmod/ulab/code/numpy/transform.c +msgid "wrong index type" +msgstr "" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "Buffer elements must be 4 bytes long or less" -msgstr "버퍼 요소는 4바이트 이하여야 합니다" +#: extmod/ulab/code/numpy/transform.c +msgid "wrong length of index array" +msgstr "" -#: shared-bindings/framebufferio/FramebufferDisplay.c -msgid "Buffer is not a bytearray." -msgstr "버퍼는 바이트 배열이 아닙니다." +#: extmod/ulab/code/numpy/transform.c +msgid "dimensions do not match" +msgstr "" -#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c -#, c-format -msgid "Buffer length %d too big. It must be less than %d" -msgstr "버퍼 길이 %d가 너무 큽니다. 그것은 %d보다 작아야 합니다" +#: extmod/ulab/code/numpy/vector.c extmod/ulab/code/utils/utils.c +msgid "out must be an ndarray" +msgstr "" -#: ports/atmel-samd/common-hal/sdioio/SDCard.c -#: ports/cxd56/common-hal/sdioio/SDCard.c -#: ports/espressif/common-hal/sdioio/SDCard.c -#: ports/stm/common-hal/sdioio/SDCard.c shared-bindings/floppyio/__init__.c -#: shared-module/sdcardio/SDCard.c -#, c-format -msgid "Buffer must be a multiple of %d bytes" +#: extmod/ulab/code/numpy/vector.c +msgid "out must be of float dtype" msgstr "" -#: shared-bindings/_bleio/PacketBuffer.c -#, c-format -msgid "Buffer too short by %d bytes" -msgstr "버퍼가 %d 바이트로 너무 짧습니다" +#: extmod/ulab/code/numpy/vector.c +msgid "input and output dimensions differ" +msgstr "" -#: ports/cxd56/common-hal/camera/Camera.c -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -#: shared-bindings/struct/__init__.c shared-module/struct/__init__.c -msgid "Buffer too small" -msgstr "버퍼가 너무 작습니다" +#: extmod/ulab/code/numpy/vector.c +msgid "input and output shapes differ" +msgstr "" -#: ports/atmel-samd/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/nordic/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/raspberrypi/common-hal/paralleldisplaybus/ParallelBus.c -#, c-format -msgid "Bus pin %d is already in use" -msgstr "Bus 핀 %d은 이미 사용 중입니다" +#: extmod/ulab/code/numpy/vector.c +msgid "out keyword is not supported for function" +msgstr "" -#: shared-bindings/_bleio/UUID.c -msgid "Byte buffer must be 16 bytes." -msgstr "잘못된 크기의 버퍼. 16 바이트 여야합니다." +#: extmod/ulab/code/numpy/vector.c +msgid "out keyword is not supported for complex dtype" +msgstr "" -#: shared-bindings/aesio/aes.c -msgid "CBC blocks must be multiples of 16 bytes" -msgstr "CBC 블록은 16 바이트의 배수여야 합니다" +#: extmod/ulab/code/numpy/vector.c +msgid "dtype must be float, or complex" +msgstr "" -#: supervisor/shared/safe_mode.c -msgid "CIRCUITPY drive could not be found or created." -msgstr "CIRCUITPY 드라이브를 찾거나 만들 수 없습니다." +#: extmod/ulab/code/numpy/vector.c +msgid "can't convert complex to float" +msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "CRC or checksum was invalid" -msgstr "CRC 또는 checksum이 잘못되었습니다" +#: extmod/ulab/code/numpy/vector.c +msgid "input dtype must be float or complex" +msgstr "" -#: py/objtype.c -msgid "Call super().__init__() before accessing native object." -msgstr "네이티브 개체에 액세스하기 전에 super().__init__()를 호출하십시오." +#: extmod/ulab/code/numpy/vector.c extmod/ulab/code/scipy/integrate/integrate.c +msgid "first argument must be a callable" +msgstr "" -#: ports/cxd56/common-hal/camera/Camera.c -#, fuzzy -msgid "Camera init" -msgstr "카메라 초기화" +#: extmod/ulab/code/numpy/vector.c +msgid "wrong output type" +msgstr "" -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Can only alarm on RTC IO from deep sleep." +#: extmod/ulab/code/scipy/integrate/integrate.c +#, c-format +msgid "can't convert arg %d from %s to float" msgstr "" -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Can only alarm on one low pin while others alarm high from deep sleep." +#: extmod/ulab/code/scipy/integrate/integrate.c +msgid "levels needs to be a positive integer" msgstr "" -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Can only alarm on two low pins from deep sleep." +#: extmod/ulab/code/scipy/integrate/integrate.c +msgid "steps needs to be a positive integer" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Can't construct AudioOut because continuous channel already open" +#: extmod/ulab/code/scipy/integrate/integrate.c +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "first argument must be a function" msgstr "" -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Characteristic.c -msgid "Can't set CCCD on local Characteristic" -msgstr "로컬 특성에 CCCD를 설정할 수 없습니다" +#: extmod/ulab/code/scipy/integrate/integrate.c +msgid "order needs to be a positive integer" +msgstr "" -#: shared-bindings/storage/__init__.c shared-bindings/usb_cdc/__init__.c -#: shared-bindings/usb_hid/__init__.c shared-bindings/usb_midi/__init__.c -#: shared-bindings/usb_video/__init__.c -msgid "Cannot change USB devices now" -msgstr "현재 USB 디바이스를 변경할 수 없습니다" +#: extmod/ulab/code/scipy/linalg/linalg.c +msgid "first two arguments must be ndarrays" +msgstr "" -#: shared-bindings/_bleio/Adapter.c -msgid "Cannot create a new Adapter; use _bleio.adapter;" -msgstr "_bleio.adapter를 사용해서; 새로운 Adapter를 만들 수 없습니다;" +#: extmod/ulab/code/scipy/linalg/linalg.c extmod/ulab/code/user/user.c +msgid "input must be a dense ndarray" +msgstr "" -#: shared-bindings/displayio/Bitmap.c -#: shared-bindings/memorymonitor/AllocationSize.c -#: shared-bindings/pulseio/PulseIn.c -msgid "Cannot delete values" -msgstr "값을 삭제할 수 없습니다" +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "function has the same sign at the ends of interval" +msgstr "" -#: ports/atmel-samd/common-hal/digitalio/DigitalInOut.c -#: ports/mimxrt10xx/common-hal/digitalio/DigitalInOut.c -#: ports/nordic/common-hal/digitalio/DigitalInOut.c -#: ports/raspberrypi/common-hal/digitalio/DigitalInOut.c -msgid "Cannot get pull while in output mode" -msgstr "출력 모드에서는 끌어올 수 없습니다" +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "maxiter should be > 0" +msgstr "" -#: ports/nordic/common-hal/microcontroller/Processor.c -msgid "Cannot get temperature" -msgstr "온도 데이터를 수신 할 수 없습니다" +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "maxiter must be > 0" +msgstr "" -#: shared-bindings/_bleio/Adapter.c -msgid "Cannot have scan responses for extended, connectable advertisements." -msgstr "확장되고 연결 가능한 광고에 대한 검색 응답을 가질 수 없습니다." +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "data must be iterable" +msgstr "" -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Cannot pull on input-only pin." -msgstr "입력 전용 핀을 끌어올 수 없습니다." +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "initial values must be iterable" +msgstr "" -#: shared-bindings/audiobusio/PDMIn.c -msgid "Cannot record to a file" -msgstr "파일에 녹음 할 수 없습니다" +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "data must be of equal length" +msgstr "" -#: shared-module/storage/__init__.c -msgid "Cannot remount '/' when visible via USB." -msgstr "USB를 통해 표시될 때 '/'은 다시 마운트할 수 없습니다." +#: extmod/ulab/code/scipy/signal/signal.c +msgid "sosfilt requires iterable arguments" +msgstr "" -#: shared-bindings/digitalio/DigitalInOut.c -msgid "Cannot set value when direction is input." -msgstr "방향이 입력되면 값을 설정할 수 없습니다." - -#: ports/espressif/common-hal/busio/UART.c -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Cannot specify RTS or CTS in RS485 mode" -msgstr "RS485 모드에서는 RTS 또는 CTS를 지정할 수 없습니다" - -#: py/objslice.c -msgid "Cannot subclass slice" +#: extmod/ulab/code/scipy/signal/signal.c +msgid "input must be one-dimensional" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Cannot use GPIO0..15 together with GPIO32..47" +#: extmod/ulab/code/scipy/signal/signal.c +msgid "zi must be an ndarray" msgstr "" -#: ports/nordic/common-hal/alarm/pin/PinAlarm.c -#, fuzzy -msgid "Cannot wake on pin edge, only level" -msgstr "핀의 에지에서 깨울 수 없고, 레벨에서만 깨울 수 있습니다" - -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -#, fuzzy -msgid "Cannot wake on pin edge. Only level." -msgstr "핀의 에지에서는 깨울 수 없습니다. 레벨에서만 깨울 수 있습니다." +#: extmod/ulab/code/scipy/signal/signal.c +msgid "zi must be of shape (n_section, 2)" +msgstr "" -#: shared-bindings/_bleio/CharacteristicBuffer.c -msgid "CharacteristicBuffer writing not provided" -msgstr "CharacteristicBuffer 쓰기는 제공되지 않습니다" +#: extmod/ulab/code/scipy/signal/signal.c +msgid "zi must be of float type" +msgstr "" -#: supervisor/shared/safe_mode.c -msgid "CircuitPython core code crashed hard. Whoops!\n" -msgstr "CircuitPython 핵심 코드가 심하게 충돌했습니다. 앗!\n" +#: extmod/ulab/code/scipy/signal/signal.c +msgid "sos array must be of shape (n_section, 6)" +msgstr "" -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -msgid "Clock unit in use" -msgstr "시계 장치가 사용 중입니다" +#: extmod/ulab/code/scipy/signal/signal.c +msgid "sos[:, 3] should be all ones" +msgstr "" -#: shared-bindings/_bleio/Connection.c -msgid "" -"Connection has been disconnected and can no longer be used. Create a new " -"connection." -msgstr "연결이 끊어져 더 이상 사용할 수 없습니다. 새로운 연결을 만드십시오." +#: extmod/ulab/code/ulab_tools.c +msgid "axis is out of bounds" +msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "Coordinate arrays have different lengths" -msgstr "좌표 배열의 길이가 다릅니다" +#: extmod/ulab/code/ulab_tools.c +msgid "size is defined for ndarrays only" +msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "Coordinate arrays types have different sizes" -msgstr "좌표 배열 유형은 크기가 다릅니다" +#: extmod/ulab/code/ulab_tools.c +msgid "input must be square matrix" +msgstr "" -#: shared-bindings/_bleio/Adapter.c -msgid "Could not set address" -msgstr "주소를 설정할 수 없습니다" +#: extmod/ulab/code/ulab_tools.c +msgid "out array has wrong dtype" +msgstr "" -#: ports/stm/common-hal/busio/UART.c -msgid "Could not start interrupt, RX busy" -msgstr "인터럽트를 시작할 수 없습니다, RX가 사용 중입니다" +#: extmod/ulab/code/ulab_tools.c +msgid "out array has wrong dimension" +msgstr "" -#: shared-module/audiomp3/MP3Decoder.c -msgid "Couldn't allocate decoder" -msgstr "디코더를 할당할 수 없습니다" +#: extmod/ulab/code/ulab_tools.c +msgid "out array has wrong shape" +msgstr "" -#: ports/stm/common-hal/analogio/AnalogOut.c -msgid "DAC Channel Init Error" -msgstr "DAC 채널 초기화 오류" +#: extmod/ulab/code/utils/utils.c +msgid "out must be a float dense array" +msgstr "" -#: ports/stm/common-hal/analogio/AnalogOut.c -msgid "DAC Device Init Error" -msgstr "DAC 장치 초기화 오류" +#: extmod/ulab/code/utils/utils.c +msgid "offset is too large" +msgstr "" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c -msgid "DAC already in use" -msgstr "DAC가 현재 사용 중입니다" +#: extmod/ulab/code/utils/utils.c +msgid "out array is too small" +msgstr "" -#: ports/atmel-samd/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/nordic/common-hal/paralleldisplaybus/ParallelBus.c -msgid "Data 0 pin must be byte aligned" -msgstr "데이터 0 핀은 바이트 정렬되어야 합니다" +#: extmod/ulab/code/utils/utils.c +msgid "spectrogram is defined for ndarrays only" +msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "Data format error (may be broken data)" -msgstr "데이터 형식 오류(손상된 데이터일 수 있습니다)" +#: extmod/ulab/code/utils/utils.c +msgid "spectrogram is implemented for 1D arrays only" +msgstr "" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Data not supported with directed advertising" -msgstr "직접 광고에서는 데이터가 지원되지 않습니다" +#: extmod/ulab/code/utils/utils.c +msgid "out array must be a 1D array of float type" +msgstr "" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Data too large for advertisement packet" -msgstr "광고 (브로드 캐스트) 패킷에 대한 데이터가 너무 큽니다" +#: extmod/ulab/code/utils/utils.c +msgid "input and out arrays must have same length" +msgstr "" -#: ports/stm/common-hal/alarm/pin/PinAlarm.c -#, fuzzy -msgid "Deep sleep pins must use a rising edge with pulldown" -msgstr "딥 슬립 핀은 풀다운이 있는 상승 에지를 사용해야 합니다" +#: extmod/ulab/code/utils/utils.c +msgid "scratchpad must be an ndarray" +msgstr "" -#: shared-bindings/audiobusio/PDMIn.c -msgid "Destination capacity is smaller than destination_length." -msgstr "대상 용량이 destination_length보다 작습니다." +#: extmod/ulab/code/utils/utils.c +msgid "scratchpad must be a 1D dense float array" +msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "Device error or wrong termination of input stream" -msgstr "장치 오류 또는 입력 스트림의 잘못된 종료" +#: extmod/ulab/code/utils/utils.c +msgid "scratchpad must be twice as long as input" +msgstr "" -#: ports/nordic/common-hal/audiobusio/I2SOut.c -msgid "Device in use" -msgstr "사용 중인 장치" +#: extmod/vfs_fat.c py/moderrno.c +msgid "Read-only filesystem" +msgstr "읽기 전용 파일 시스템" -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -msgid "Display must have a 16 bit colorspace." -msgstr "디스플레이는 16 비트 색 공간을 가져야 합니다." +#: extmod/vfs_posix_file.c py/objstringio.c +msgid "I/O operation on closed file" +msgstr "닫힌 파일에서 I/O 작업" -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/epaperdisplay/EPaperDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -msgid "Display rotation must be in 90 degree increments" -msgstr "디스플레이 회전은 90도씩 증가해야 합니다" +#: extmod/vfs_posix_file.c +msgid "poll on file not available on win32" +msgstr "" #: main.c msgid "Done" msgstr "완료" -#: shared-bindings/digitalio/DigitalInOut.c -msgid "Drive mode not used when direction is input." -msgstr "방향을 입력할 때 드라이브 모드는 사용되지 않습니다." - -#: py/obj.c -msgid "During handling of the above exception, another exception occurred:" -msgstr "위 예외를 처리하는 동안, 또 다른 예외가 발생하였습니다:" +#: main.c +msgid " output:\n" +msgstr " 산출:\n" -#: shared-bindings/aesio/aes.c -msgid "ECB only operates on 16 bytes at a time" -msgstr "ECB는 한 번에 16 바이트에서만 작동합니다" +#: main.c +msgid "" +"Auto-reload is on. Simply save files over USB to run them or enter REPL to " +"disable.\n" +msgstr "" +"자동 새로 고침이 켜져 있습니다. USB를 통해 파일을 저장하여 실행하십시오. 비활" +"성화하려면 REPL을 입력하십시오.\n" -#: ports/espressif/common-hal/busio/SPI.c -#: ports/espressif/common-hal/canio/CAN.c -msgid "ESP-IDF memory allocation failed" -msgstr "ESP-IDF 메모리 할당에 실패하였습니다" +#: main.c +msgid "Auto-reload is off.\n" +msgstr "자동 재 장전이 꺼져 있습니다\n" -#: extmod/modre.c -msgid "Error in regex" -msgstr "Regex에 오류가 있습니다." +#: main.c +msgid "Running in safe mode! Not running saved code.\n" +msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Error in safemode.py." -msgstr "safemode.py에 오류가 있습니다." +#: main.c +msgid " not found.\n" +msgstr " 찾을 수 없습니다.\n" -#: shared-bindings/alarm/__init__.c -msgid "Expected a kind of %q" -msgstr "%q 유형이 필요합니다" +#: main.c +msgid "WARNING: Your code filename has two extensions\n" +msgstr "" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -#, fuzzy -msgid "Extended advertisements with scan response not supported." -msgstr "검색 응답이 있는 확장 광고는 지원되지 않습니다." +#: main.c +msgid "" +"\n" +"Code stopped by auto-reload. Reloading soon.\n" +msgstr "" +"\n" +"자동 업로드에 의해 코드가 중지되었습니다. 곧 다시 로드됩니다.\n" -#: extmod/ulab/code/numpy/fft/fft_tools.c -msgid "FFT is defined for ndarrays only" -msgstr "FFT는 ndarrays에 대해서만 정의됩니다" +#: main.c +msgid "" +"\n" +"Code done running.\n" +msgstr "" +"\n" +"코드 실행 완료.\n" -#: extmod/ulab/code/numpy/fft/fft_tools.c -msgid "FFT is implemented for linear arrays only" -msgstr "FFT는 선형 배열에 대해서만 구현됩니다" +#: main.c +msgid "Woken up by alarm.\n" +msgstr "" -#: shared-bindings/ps2io/Ps2.c -msgid "Failed sending command." -msgstr "명령을 보내는 것에 실패했습니다." +#: main.c +msgid "Press any key to enter the REPL. Use CTRL-D to reload.\n" +msgstr "아무 키나 눌러 REPL을 입력한다. 다시 로드할땐 CTRL-D를 사용한다.\n" -#: ports/nordic/sd_mutex.c -#, c-format -msgid "Failed to acquire mutex, err 0x%04x" -msgstr "뮤텍스 획득에 실패했습니다, 오류 0x%04x" +#: main.c +msgid "Pretending to deep sleep until alarm, CTRL-C or file write.\n" +msgstr "알람, CTRL-C 또는 파일을 작성하기 전까지 딥 슬립을 하는 척합니다\n" -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "Failed to add service TXT record" -msgstr "서비스 TXT 레코드를 추가하는 것에 실패했습니다" +#: main.c +msgid "UID:" +msgstr "UID:" -#: shared-bindings/mdns/Server.c -msgid "" -"Failed to add service TXT record; non-string or bytes found in txt_records" +#: main.c +msgid "soft reboot\n" msgstr "" -"서비스 TXT 레코드를 추가하는 것에 실패했습니다; txt_records에서 비문자열 또" -"는 바이트가 발견되었습니다" -#: shared-module/rgbmatrix/RGBMatrix.c +#: ports/analog/common-hal/busio/SPI.c ports/analog/common-hal/busio/UART.c +#: ports/cxd56/common-hal/busio/SPI.c ports/stm/common-hal/audioio/AudioOut.c +#: shared-bindings/digitalio/DigitalInOutProtocol.c +#: shared-module/displayio/bus_core.c shared-module/ssl/SSLContext.c +msgid "%q init failed" +msgstr "%q 초기화 실패" + +#: ports/analog/common-hal/busio/SPI.c +msgid "SPI needs MOSI, MISO, and SCK" +msgstr "" + +#: ports/analog/common-hal/busio/SPI.c +#: ports/atmel-samd/common-hal/pulseio/PulseIn.c +#: ports/cxd56/common-hal/pulseio/PulseIn.c +#: ports/nordic/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#: ports/stm/common-hal/pulseio/PulseIn.c py/argcheck.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/canio/Match.c +#: shared-bindings/time/__init__.c +#, fuzzy +msgid "%q out of range" +msgstr "%q가 범위를 벗어남" + +#: ports/analog/common-hal/busio/SPI.c +#: ports/espressif/common-hal/espidf/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: shared-bindings/epaperdisplay/EPaperDisplay.c +msgid "Invalid state" +msgstr "잘못된 상태" + +#: ports/analog/common-hal/busio/SPI.c +msgid "Failed to set SPI Clock Mode" +msgstr "" + +#: ports/analog/common-hal/busio/UART.c +#: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c +#: ports/nordic/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/zephyr-cp/common-hal/busio/UART.c +msgid "RS485" +msgstr "RS485" + +#: ports/analog/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c +msgid "UART needs TX & RX" +msgstr "" + +#: ports/analog/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c +msgid "Both RX and TX required for flow control" +msgstr "플로우 제어에 RX와 TX가 모두 필요합니다" + +#: ports/analog/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/usb_host/Port.c +#: shared-module/rgbmatrix/RGBMatrix.c msgid "Failed to allocate %q buffer" msgstr "%q 버퍼 할당에 실패했습니다" -#: ports/espressif/common-hal/wifi/__init__.c -msgid "Failed to allocate Wifi memory" -msgstr "Wifi 메모리 할당에 실패했습니다" +#: ports/analog/common-hal/busio/UART.c +msgid "UART read error" +msgstr "" -#: ports/espressif/common-hal/wifi/ScannedNetworks.c -msgid "Failed to allocate wifi scan memory" -msgstr "wifi 검색 메모리 할당에 실패했습니다" +#: ports/analog/common-hal/busio/UART.c +msgid "UART transaction timeout" +msgstr "" -#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c -msgid "Failed to buffer the sample" -msgstr "샘플 버퍼링에 실패했습니다" +#: ports/analog/common-hal/busio/UART.c ports/espressif/common-hal/busio/UART.c +#: ports/nordic/common-hal/busio/UART.c ports/zephyr-cp/common-hal/busio/UART.c +msgid "All UART peripherals are in use" +msgstr "사용중인 모든 UART주변 기기" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Failed to connect: internal error" -msgstr "연결에 실패했습니다: 내부 오류" +#: ports/analog/common-hal/busio/UART.c +#: ports/analog/peripherals/max32690/max32_i2c.c +#: ports/analog/peripherals/max32690/max32_spi.c +#: ports/analog/peripherals/max32690/max32_uart.c +#: ports/espressif/common-hal/_bleio/Service.c +#: ports/espressif/common-hal/espulp/ULP.c +#: ports/espressif/common-hal/jpegio/JpegDecoder.c +#: ports/espressif/common-hal/microcontroller/Processor.c +#: ports/espressif/common-hal/mipidsi/Display.c +#: ports/mimxrt10xx/common-hal/audiobusio/__init__.c +#: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c +#: ports/raspberrypi/bindings/picodvi/Framebuffer.c +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +#: ports/raspberrypi/common-hal/picodvi/AudioOut.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c +#: ports/raspberrypi/common-hal/usb_host_bulk/InStream.c py/argcheck.c +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/utils/__init__.c +#: shared-bindings/digitalio/DigitalInOut.c +#: shared-bindings/epaperdisplay/EPaperDisplay.c +#: shared-bindings/i2cioexpander/IOPin.c shared-bindings/mipidsi/Display.c +#: shared-bindings/pwmio/PWMOut.c shared-bindings/supervisor/__init__.c +#: shared-module/aurora_epaper/aurora_framebuffer.c +#: shared-module/cryptography/hazmat/primitives/asymmetric/ec/EllipticCurvePublicKey.c +#: shared-module/jpegio/JpegDecoder.c shared-module/lvfontio/OnDiskFont.c +msgid "Invalid %q" +msgstr "잘못된 %q" -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Failed to connect: timeout" -msgstr "연결에 실패했습니다: 시간 초과" +#: ports/analog/common-hal/busio/UART.c +msgid "Timeout must be < 100 seconds" +msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to create continuous channels: invalid arg" +#: ports/atmel-samd/audio_dma.c +#, fuzzy +msgid "All sync event channels in use" +msgstr "모든 동기화 이벤트 채널이 사용 중입니다" + +#: ports/atmel-samd/audio_dma.c ports/raspberrypi/audio_dma.c +msgid "Internal audio buffer too small" +msgstr "내부 오디오 버퍼가 너무 작습니다" + +#: ports/atmel-samd/bindings/samd/Clock.c +msgid "calibration is read only" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to create continuous channels: invalid state" +#: ports/atmel-samd/bindings/samd/Clock.c +msgid "calibration is out of range" +msgstr "" + +#: 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/meowmeow/mpconfigboard.h +msgid "You pressed both buttons at start up." +msgstr "" + +#: ports/atmel-samd/common-hal/_pew/PewPew.c +#: ports/atmel-samd/common-hal/audioio/AudioOut.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/nordic/common-hal/audiopwmio/PWMAudioOut.c +#: ports/nordic/common-hal/pulseio/PulseIn.c +#: ports/nordic/peripherals/nrf/timers.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +#: ports/stm/common-hal/pulseio/PulseOut.c +msgid "All timers in use" +msgstr "모든 타이머가 사용 중입니다" + +#: ports/atmel-samd/common-hal/alarm/pin/PinAlarm.c +#: ports/atmel-samd/common-hal/countio/Counter.c +#: ports/atmel-samd/common-hal/frequencyio/FrequencyIn.c +#: ports/atmel-samd/common-hal/max3421e/Max3421E.c +#: ports/atmel-samd/common-hal/ps2io/Ps2.c +#: ports/atmel-samd/common-hal/pulseio/PulseIn.c +#: ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.c +#: ports/cxd56/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c +#: ports/zephyr-cp/common-hal/async_spi/SPI.c +#: ports/zephyr-cp/common-hal/busio/I2C.c +#: ports/zephyr-cp/common-hal/busio/UART.c +msgid "Internal resource(s) in use" +msgstr "" + +#: ports/atmel-samd/common-hal/alarm/pin/PinAlarm.c +#: supervisor/shared/safe_mode.c +msgid "Unknown reason." msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to create continuous channels: no mem" -msgstr "" +#: ports/atmel-samd/common-hal/alarm/time/TimeAlarm.c +#: ports/nordic/common-hal/alarm/time/TimeAlarm.c +#: ports/stm/common-hal/alarm/time/TimeAlarm.c +msgid "Only one alarm.time alarm can be set" +msgstr "" + +#: ports/atmel-samd/common-hal/analogio/AnalogOut.c +#: ports/stm/common-hal/analogio/AnalogOut.c +#: ports/stm/common-hal/audioio/AudioOut.c +msgid "No DAC on chip" +msgstr "칩에 DAC가 없습니다" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +msgid "%q and %q must share a clock unit" +msgstr "" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +msgid "Serializer in use" +msgstr "" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +msgid "Clock unit in use" +msgstr "시계 장치가 사용 중입니다" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/atmel-samd/common-hal/touchio/TouchIn.c +msgid "No free GCLKs" +msgstr "무료 GCLKs가 없습니다" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +msgid "Too many channels in sample" +msgstr "" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +#: ports/raspberrypi/common-hal/mcp4822/MCP4822.c +msgid "No DMA channel found" +msgstr "DMA 채널을 찾을 수 없습니다" + +#: 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 +#: ports/raspberrypi/common-hal/mcp4822/MCP4822.c +msgid "Unable to allocate buffers for signed conversion" +msgstr "" + +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c +#, c-format +msgid "Only 8 or 16 bit mono with %dx oversampling supported." +msgstr "%dx 오버샘플링이 포함된 8 또는 16 비트 모노만 지원됩니다." + +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c +msgid "sampling rate out of range" +msgstr "" + +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +msgid "DAC already in use" +msgstr "DAC가 현재 사용 중입니다" + +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +msgid "Right channel unsupported" +msgstr "" + +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +#, fuzzy +msgid "All event channels in use" +msgstr "모든 이벤트 채널이 사용 중입니다" + +#: ports/atmel-samd/common-hal/busio/I2C.c +#: ports/espressif/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nordic/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 "SDA 또는 SCL에서 풀업을 찾을 수 없습니다; 케이블 연결을 확인하십시오" + +#: ports/atmel-samd/common-hal/busio/UART.c +#: shared-bindings/usb_host_bulk/InStream.c +msgid "%q must be power of 2" +msgstr "%q는 2의 거듭제곱이어야 합니다" + +#: ports/atmel-samd/common-hal/busio/UART.c +#: ports/espressif/common-hal/busio/SPI.c +#: ports/espressif/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/SPI.c +#: ports/mimxrt10xx/common-hal/busio/UART.c +#: ports/nordic/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c ports/stm/common-hal/busio/SPI.c +#: ports/stm/common-hal/busio/UART.c shared-bindings/fourwire/FourWire.c +#: shared-bindings/i2cdisplaybus/I2CDisplayBus.c +#: shared-bindings/paralleldisplaybus/ParallelBus.c +#: shared-bindings/qspibus/QSPIBus.c shared-module/bitbangio/SPI.c +msgid "No %q pin" +msgstr "%q 핀이 없습니다" + +#: ports/atmel-samd/common-hal/canio/Listener.c +#: ports/espressif/common-hal/canio/Listener.c +#: ports/stm/common-hal/canio/Listener.c +#, fuzzy +msgid "All RX FIFOs in use" +msgstr "모든 RX FIFOs가 사용 중입니다" + +#: ports/atmel-samd/common-hal/canio/Listener.c +#, fuzzy +msgid "Already have all-matches listener" +msgstr "이미 모든 일치 리스너가 있습니다" + +#: ports/atmel-samd/common-hal/canio/Listener.c +#: ports/espressif/common-hal/canio/Listener.c +#: ports/mimxrt10xx/common-hal/canio/Listener.c +#: ports/stm/common-hal/canio/Listener.c +msgid "Filters too complex" +msgstr "필터가 너무 복잡합니다" + +#: ports/atmel-samd/common-hal/digitalio/DigitalInOut.c +#: ports/mimxrt10xx/common-hal/digitalio/DigitalInOut.c +#: ports/nordic/common-hal/digitalio/DigitalInOut.c +#: ports/raspberrypi/common-hal/digitalio/DigitalInOut.c +msgid "Cannot get pull while in output mode" +msgstr "출력 모드에서는 끌어올 수 없습니다" + +#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c +#, c-format +msgid "Invalid data_pins[%d]" +msgstr "잘못된 data_pins[%d]" + +#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c +#, c-format +msgid "data pin #%d in use" +msgstr "" + +#: ports/atmel-samd/common-hal/microcontroller/Pin.c +#: ports/espressif/common-hal/dotclockframebuffer/DotClockFramebuffer.c +#: ports/mimxrt10xx/common-hal/microcontroller/Pin.c +#: shared-bindings/emmcio/EMMC.c shared-bindings/microcontroller/Pin.c +msgid "Invalid %q pin" +msgstr "잘못된 %q 핀" + +#: ports/atmel-samd/common-hal/microcontroller/__init__.c +#: ports/cxd56/common-hal/microcontroller/__init__.c +#: ports/mimxrt10xx/common-hal/microcontroller/__init__.c +msgid "No bootloader present" +msgstr "" + +#: ports/atmel-samd/common-hal/paralleldisplaybus/ParallelBus.c +#: ports/nordic/common-hal/paralleldisplaybus/ParallelBus.c +msgid "Data 0 pin must be byte aligned" +msgstr "데이터 0 핀은 바이트 정렬되어야 합니다" + +#: ports/atmel-samd/common-hal/paralleldisplaybus/ParallelBus.c +#: ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c +#: ports/nordic/common-hal/paralleldisplaybus/ParallelBus.c +#: ports/raspberrypi/common-hal/paralleldisplaybus/ParallelBus.c +#, c-format +msgid "Bus pin %d is already in use" +msgstr "Bus 핀 %d은 이미 사용 중입니다" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to create continuous channels: not found" +#: ports/atmel-samd/common-hal/pulseio/PulseIn.c +#: ports/cxd56/common-hal/pulseio/PulseIn.c +#: ports/nordic/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 "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to enable continuous" -msgstr "" +#: ports/atmel-samd/common-hal/pulseio/PulseIn.c +msgid "Input taking too long" +msgstr "입력이 너무 오래 걸린다" -#: shared-module/audiomp3/MP3Decoder.c -msgid "Failed to parse MP3 file" -msgstr "MP3 파일 분석에 실패했습니다" +#: ports/atmel-samd/common-hal/pulseio/PulseOut.c +#: ports/cxd56/common-hal/pulseio/PulseOut.c +msgid "Another send is already active" +msgstr "다른 전송이 이미 활성화되었습니다" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to register continuous events callback" -msgstr "" +#: ports/atmel-samd/common-hal/sdioio/SDCard.c +#: ports/espressif/common-hal/mii/Ethernet.c +#: ports/espressif/common-hal/qspibus/QSPIBus.c shared-bindings/emmcio/EMMC.c +#: shared-bindings/socketpool/SocketPool.c +msgid "%q failure: %d" +msgstr "%q 실패: %d" -#: ports/nordic/sd_mutex.c +#: ports/atmel-samd/common-hal/sdioio/SDCard.c +#: ports/cxd56/common-hal/sdioio/SDCard.c +#: ports/espressif/common-hal/sdioio/SDCard.c +#: ports/raspberrypi/common-hal/sdioio/SDCard.c +#: ports/stm/common-hal/sdioio/SDCard.c shared-bindings/audiocore/WaveFile.c +#: shared-bindings/emmcio/EMMC.c shared-bindings/floppyio/__init__.c +#: shared-bindings/picogame/Canvas.c shared-module/sdcardio/SDCard.c #, c-format -msgid "Failed to release mutex, err 0x%04x" -msgstr "뮤텍스 해제에 실패했습니다, 오류 0x%04x" +msgid "Buffer must be a multiple of %d bytes" +msgstr "" -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "Failed to set hostname" +#: ports/atmel-samd/common-hal/spitarget/SPITarget.c +msgid "Async SPI transfer in progress on this bus, keep awaiting." msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to start async audio" +#: ports/cxd56/common-hal/busio/UART.c ports/espressif/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c +msgid "UART init" msgstr "" -#: supervisor/shared/safe_mode.c +#: ports/cxd56/common-hal/camera/Camera.c #, fuzzy -msgid "Failed to write internal flash." -msgstr "내부 플래시를 쓰는 것에 실패했습니다." - -#: py/moderrno.c -msgid "File exists" -msgstr "파일이 있습니다" - -#: shared-module/os/getenv.c -msgid "File not found" -msgstr "파일을 찾을 수 없습니다" - -#: ports/atmel-samd/common-hal/canio/Listener.c -#: ports/espressif/common-hal/canio/Listener.c -#: ports/mimxrt10xx/common-hal/canio/Listener.c -#: ports/stm/common-hal/canio/Listener.c -msgid "Filters too complex" -msgstr "필터가 너무 복잡합니다" - -#: ports/espressif/common-hal/dualbank/__init__.c -msgid "Firmware is duplicate" -msgstr "펌웨어가 중복되었습니다" - -#: ports/espressif/common-hal/dualbank/__init__.c -msgid "Firmware is invalid" -msgstr "펌웨어가 잘못되었습니다" - -#: ports/espressif/common-hal/dualbank/__init__.c -msgid "Firmware is too big" -msgstr "펌웨어가 너무 큽니다" +msgid "Camera init" +msgstr "카메라 초기화" -#: shared-bindings/bitmaptools/__init__.c -msgid "For L8 colorspace, input bitmap must have 8 bits per pixel" -msgstr "L8 색상 공간의 경우, 입력 비트맵은 픽셀 당 8 비트를 가져야 합니다" +#: ports/cxd56/common-hal/camera/Camera.c +msgid "Size not supported" +msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "For RGB colorspaces, input bitmap must have 16 bits per pixel" -msgstr "RGB 색상 공간의 경우, 입력 비트맵은 픽셀 당 16 비트를 가져야 합니다" +#: ports/cxd56/common-hal/camera/Camera.c +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +#: shared-bindings/struct/__init__.c shared-module/struct/__init__.c +#: shared-module/videocore/VideoBuffer.c +msgid "Buffer too small" +msgstr "버퍼가 너무 작습니다" #: ports/cxd56/common-hal/camera/Camera.c +#: ports/espressif/common-hal/jpegio/JpegDecoder.c +#: shared-module/audiocore/WaveFile.c +#: shared-module/busdisplay/lvgl/BusDisplay.c +#: shared-module/displayio/lvgl/TileGrid.c +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c msgid "Format not supported" msgstr "지원되지 않는 형식입니다" -#: ports/mimxrt10xx/common-hal/microcontroller/Processor.c -msgid "" -"Frequency must be 24, 150, 396, 450, 528, 600, 720, 816, 912, 960 or 1008 Mhz" -msgstr "" -"주파수는 24, 150, 396, 450, 528, 600, 720, 816, 912, 960 또는 1008 Mhz 여야 " -"합니다" - -#: 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 "이 함수에는 잠금이 필요합니다" - #: ports/cxd56/common-hal/gnss/GNSS.c msgid "GNSS init" msgstr "GNSS 초기화" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Generic Failure" -msgstr "일반 오류" - -#: shared-bindings/framebufferio/FramebufferDisplay.c -#: shared-module/busdisplay/BusDisplay.c -#: shared-module/framebufferio/FramebufferDisplay.c -msgid "Group already used" -msgstr "이미 사용된 그룹" - -#: supervisor/shared/safe_mode.c -msgid "Hard fault: memory access or instruction error." -msgstr "치명적인 실수: 메모리 액세스 또는 명령 오류." - -#: ports/mimxrt10xx/common-hal/busio/SPI.c -#: ports/mimxrt10xx/common-hal/busio/UART.c 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 "Hardware in use, try alternative pins" -msgstr "하드웨어가 사용 중입니다, 대체 핀을 사용해보십시오" - -#: supervisor/shared/safe_mode.c -msgid "Heap allocation when VM not running." -msgstr "VM이 작동하지 않을 때 힙이 할당됩니다." - -#: extmod/vfs_posix_file.c py/objstringio.c -msgid "I/O operation on closed file" -msgstr "닫힌 파일에서 I/O 작업" +#: ports/cxd56/common-hal/sdioio/SDCard.c +msgid "SDCard init" +msgstr "" -#: ports/stm/common-hal/busio/I2C.c -msgid "I2C init error" -msgstr "I2C 초기화 오류" +#: ports/espressif/bindings/espnow/ESPNow.c +#: ports/espressif/common-hal/espulp/ULP.c +#: ports/raspberrypi/common-hal/usb_host_bulk/InStream.c +#: shared-module/memorymonitor/AllocationAlarm.c +#: shared-module/memorymonitor/AllocationSize.c +msgid "Already running" +msgstr "이미 실행 중입니다" -#: ports/raspberrypi/common-hal/busio/I2C.c -#: ports/raspberrypi/common-hal/i2ctarget/I2CTarget.c -msgid "I2C peripheral in use" -msgstr "I2C 주변 기기가 사용 중입니다" +#: ports/espressif/bindings/espnow/Peer.c shared-bindings/dualbank/__init__.c +msgid "%q is %q" +msgstr "%q는 %q입니다" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "In-buffer elements must be <= 4 bytes long" -msgstr "버퍼 내 요소 길이는 <= 4여야 합니다" +#: ports/espressif/boards/adafruit_feather_esp32_v2/mpconfigboard.h +msgid "You pressed the SW38 button at start up." +msgstr "" -#: shared-bindings/_pew/PewPew.c -msgid "Incorrect buffer size" -msgstr "잘못된 버퍼 크기" +#: ports/espressif/boards/adafruit_feather_esp32c6_4mbflash_nopsram/mpconfigboard.h +#: ports/espressif/boards/adafruit_itsybitsy_esp32/mpconfigboard.h +#: ports/espressif/boards/waveshare_esp32_c5_lcd_1_47/mpconfigboard.h +#: ports/espressif/boards/waveshare_esp32_c6_lcd_1_47/mpconfigboard.h +msgid "You pressed the BOOT button at start up." +msgstr "" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "Init program size invalid" -msgstr "초기화 프로그램의 크기가 잘못되었습니다" +#: ports/espressif/boards/adafruit_huzzah32_breakout/mpconfigboard.h +msgid "You pressed the GPIO0 button at start up." +msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Initial set pin direction conflicts with initial out pin direction" -msgstr "초기 설정한 핀의 방향이 초기 바깥쪽 핀의 방향과 충돌합니다" +#: ports/espressif/boards/espressif_esp32_lyrat/mpconfigboard.h +msgid "You pressed the Rec button at start up." +msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Initial set pin state conflicts with initial out pin state" -msgstr "초기 설정한 핀의 상태가 초기 바깥쪽 핀의 상태와 충돌합니다" +#: ports/espressif/boards/hardkernel_odroid_go/mpconfigboard.h +#: ports/espressif/boards/vidi_x/mpconfigboard.h +msgid "You pressed the VOLUME button at start up." +msgstr "" -#: shared-bindings/bitops/__init__.c -#, fuzzy, c-format -msgid "Input buffer length (%d) must be a multiple of the strand count (%d)" -msgstr "입력 버퍼 길이 (%d) 는 스트랜드 수 (%d)의 배수여야 한다" +#: ports/espressif/boards/m5stack_atom_echo/mpconfigboard.h +#: ports/espressif/boards/m5stack_atom_lite/mpconfigboard.h +#: ports/espressif/boards/m5stack_atom_matrix/mpconfigboard.h +#: ports/espressif/boards/m5stack_atom_u/mpconfigboard.h +msgid "You pressed the central button at start up." +msgstr "" -#: ports/atmel-samd/common-hal/pulseio/PulseIn.c -msgid "Input taking too long" -msgstr "입력이 너무 오래 걸린다" +#: ports/espressif/boards/m5stack_core_basic/mpconfigboard.h +#: ports/espressif/boards/m5stack_core_fire/mpconfigboard.h +#: ports/espressif/boards/m5stack_stick_c/mpconfigboard.h +#: ports/espressif/boards/m5stack_stick_c_plus/mpconfigboard.h +#: ports/espressif/boards/m5stack_stick_c_plus2/mpconfigboard.h +msgid "You pressed button A at start up." +msgstr "" -#: py/moderrno.c -msgid "Input/output error" -msgstr "입력/출력 오류" +#: ports/espressif/boards/m5stack_m5paper/mpconfigboard.h +msgid "You pressed button DOWN at start up." +msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -#: ports/nordic/common-hal/_bleio/__init__.c -msgid "Insufficient authentication" -msgstr "불충분한 인증" +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/espressif/common-hal/dualbank/__init__.c +msgid "Update failed" +msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -#: ports/nordic/common-hal/_bleio/__init__.c -msgid "Insufficient encryption" -msgstr "불충분한 암호화" +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "Scan already in progress. Stop with stop_scan." +msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "Insufficient memory pool for the image" -msgstr "이미지에 대한 메모리 풀이 부족합니다" +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +#: ports/zephyr-cp/common-hal/_bleio/Adapter.c +msgid "Failed to connect: timeout" +msgstr "연결에 실패했습니다: 시간 초과" -#: shared-module/jpegio/JpegDecoder.c -msgid "Insufficient stream input buffer" -msgstr "불충분한 스트림 입력 버퍼" +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +#: ports/zephyr-cp/common-hal/_bleio/Adapter.c +msgid "Failed to connect: internal error" +msgstr "연결에 실패했습니다: 내부 오류" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "Interface must be started" -msgstr "인터페이스를 시작해야 합니다" +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +#: ports/zephyr-cp/common-hal/_bleio/Adapter.c +msgid "Data too large for advertisement packet" +msgstr "광고 (브로드 캐스트) 패킷에 대한 데이터가 너무 큽니다" -#: ports/atmel-samd/audio_dma.c ports/raspberrypi/audio_dma.c -msgid "Internal audio buffer too small" -msgstr "내부 오디오 버퍼가 너무 작습니다" +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +#, fuzzy +msgid "Already advertising." +msgstr "이미 광고 중입니다." -#: ports/stm/common-hal/busio/UART.c -msgid "Internal define error" -msgstr "내부 정의 오류" +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +#, fuzzy +msgid "Extended advertisements with scan response not supported." +msgstr "검색 응답이 있는 확장 광고는 지원되지 않습니다." -#: shared-bindings/pwmio/PWMOut.c shared-module/os/getenv.c -msgid "Internal error" -msgstr "내부 오류" +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "Data not supported with directed advertising" +msgstr "직접 광고에서는 데이터가 지원되지 않습니다" -#: shared-module/rgbmatrix/RGBMatrix.c +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c #, c-format -msgid "Internal error #%d" -msgstr "내부 오류 #%d" - -#: ports/atmel-samd/common-hal/alarm/pin/PinAlarm.c -#: ports/atmel-samd/common-hal/countio/Counter.c -#: ports/atmel-samd/common-hal/frequencyio/FrequencyIn.c -#: ports/atmel-samd/common-hal/max3421e/Max3421E.c -#: ports/atmel-samd/common-hal/ps2io/Ps2.c -#: ports/atmel-samd/common-hal/pulseio/PulseIn.c -#: ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.c -#: ports/cxd56/common-hal/pulseio/PulseIn.c -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c -#: shared-bindings/pwmio/PWMOut.c -msgid "Internal resource(s) in use" +msgid "Timeout is too long: Maximum timeout length is %d seconds" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Internal watchdog timer expired." -msgstr "내부 감시 타이머가 만료되었습니다." - -#: supervisor/shared/safe_mode.c -msgid "Interrupt error." -msgstr "인터럽트 오류." +#: ports/espressif/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Descriptor.c +msgid "Value length != required fixed length" +msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "Interrupted by output function" -msgstr "출력 함수로 인해 종료되었다" +#: ports/espressif/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Descriptor.c +msgid "Value length > max_length" +msgstr "" +#: ports/espressif/common-hal/_bleio/Characteristic.c #: ports/espressif/common-hal/_bleio/Service.c -#: ports/espressif/common-hal/espulp/ULP.c -#: ports/espressif/common-hal/microcontroller/Processor.c -#: ports/mimxrt10xx/common-hal/audiobusio/__init__.c -#: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c -#: ports/raspberrypi/bindings/picodvi/Framebuffer.c -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c py/argcheck.c -#: shared-bindings/digitalio/DigitalInOut.c -#: shared-bindings/epaperdisplay/EPaperDisplay.c shared-bindings/pwmio/PWMOut.c -#: shared-module/aurora_epaper/aurora_framebuffer.c -msgid "Invalid %q" -msgstr "잘못된 %q" - -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c -#: shared-module/aurora_epaper/aurora_framebuffer.c -msgid "Invalid %q and %q" +#: ports/raspberrypi/common-hal/alarm/pin/PinAlarm.c +#: ports/raspberrypi/common-hal/usb_host_bulk/InStream.c +msgid "Too many %q" msgstr "" -#: ports/atmel-samd/common-hal/microcontroller/Pin.c -#: ports/espressif/common-hal/dotclockframebuffer/DotClockFramebuffer.c -#: ports/mimxrt10xx/common-hal/microcontroller/Pin.c -#: shared-bindings/microcontroller/Pin.c -msgid "Invalid %q pin" -msgstr "잘못된 %q 핀" +#: ports/espressif/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Characteristic.c +#: ports/zephyr-cp/common-hal/_bleio/Characteristic.c +msgid "No CCCD for this Characteristic" +msgstr "이 특성에 대한 CCCD가 없습니다" -#: ports/stm/common-hal/analogio/AnalogIn.c -msgid "Invalid ADC Unit value" -msgstr "잘못된 ADC 단위 값" +#: ports/espressif/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Characteristic.c +msgid "Can't set CCCD on local Characteristic" +msgstr "로컬 특성에 CCCD를 설정할 수 없습니다" +#: ports/espressif/common-hal/_bleio/Connection.c #: ports/espressif/common-hal/_bleio/__init__.c #: ports/nordic/common-hal/_bleio/__init__.c -msgid "Invalid BLE parameter" -msgstr "잘못된 BLE 파라미터" - -#: shared-bindings/wifi/Radio.c -msgid "Invalid BSSID" -msgstr "잘못된 BSSID" +#: ports/zephyr-cp/common-hal/_bleio/Characteristic.c +#: ports/zephyr-cp/common-hal/_bleio/Connection.c +#: ports/zephyr-cp/common-hal/_bleio/Descriptor.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +#: shared-bindings/_bleio/CharacteristicBuffer.c +msgid "Not connected" +msgstr "연결되지 않았습니다" -#: shared-bindings/wifi/Radio.c -msgid "Invalid MAC address" -msgstr "잘못된 MAC 주소" +#: ports/espressif/common-hal/_bleio/Connection.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/Connection.c +msgid "" +"Unspecified issue. The pairing request on the other device may have been " +"declined or ignored." +msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c py/moderrno.c -msgid "Invalid argument" -msgstr "잘못된 인수" +#: ports/espressif/common-hal/_bleio/Connection.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/Connection.c +#, c-format +msgid "Unknown security error: 0x%04x" +msgstr "" -#: shared-module/displayio/Bitmap.c -msgid "Invalid bits per value" -msgstr "값 당 잘못된 비트" +#: ports/espressif/common-hal/_bleio/Connection.c +msgid "No pairing in progress" +msgstr "" -#: shared-module/os/getenv.c -#, c-format -msgid "Invalid byte %.*s" -msgstr "잘못된 바이트 %.*s" +#: ports/espressif/common-hal/_bleio/Connection.c +#: ports/nordic/common-hal/_bleio/Connection.c +msgid "non-UUID found in service_uuids_whitelist" +msgstr "" -#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c +#: ports/espressif/common-hal/_bleio/Descriptor.c +#: ports/nordic/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Descriptor.c #, c-format -msgid "Invalid data_pins[%d]" -msgstr "잘못된 data_pins[%d]" +msgid "max_length must be 0-%d when fixed_length is %s" +msgstr "" -#: shared-module/msgpack/__init__.c -msgid "Invalid format" -msgstr "잘못된 형식" +#: ports/espressif/common-hal/_bleio/PacketBuffer.c +#: ports/nordic/common-hal/_bleio/PacketBuffer.c +#: ports/zephyr-cp/common-hal/_bleio/PacketBuffer.c +msgid "Writes not supported on Characteristic" +msgstr "" -#: shared-module/audiocore/WaveFile.c -msgid "Invalid format chunk size" -msgstr "형식 청크 크기가 잘못되었습니다" +#: ports/espressif/common-hal/_bleio/PacketBuffer.c +#: ports/nordic/common-hal/_bleio/PacketBuffer.c +#: ports/zephyr-cp/common-hal/_bleio/PacketBuffer.c +msgid "Total data to write is larger than %q" +msgstr "" -#: shared-bindings/wifi/Radio.c -msgid "Invalid hex password" -msgstr "잘못된 16진수 패스워드" +#: ports/espressif/common-hal/_bleio/__init__.c +#, fuzzy +msgid "Nimble out of memory" +msgstr "빠른 메모리 부족" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "Invalid multicast MAC address" -msgstr "잘못된 멀티캐스트 MAC 주소" +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +msgid "Invalid BLE parameter" +msgstr "잘못된 BLE 파라미터" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Invalid size" -msgstr "잘못된 크기" +#: ports/espressif/common-hal/_bleio/__init__.c +#: shared-module/audiofilewriter/AudioFileWriter.c +msgid "Already in progress" +msgstr "" -#: shared-module/ssl/SSLSocket.c -msgid "Invalid socket for TLS" -msgstr "TLS에 대한 잘못된 소켓" +#: ports/espressif/common-hal/_bleio/__init__.c +#, c-format +msgid "Unknown BLE error at %s:%d: 0x%04x" +msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c +#: ports/espressif/common-hal/_bleio/__init__.c #: ports/nordic/common-hal/_bleio/__init__.c -msgid "Invalid state" -msgstr "잘못된 상태" +#, c-format +msgid "Unknown BLE error: 0x%04x" +msgstr "" -#: shared-module/os/getenv.c -msgid "Invalid unicode escape" -msgstr "잘못된 유니코드 이스케이프" +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +msgid "%q not permitted" +msgstr "" -#: shared-bindings/aesio/aes.c -msgid "Key must be 16, 24, or 32 bytes long" -msgstr "키는 16, 24, 또는 32 바이트 길이여야 합니다" +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +msgid "Insufficient authentication" +msgstr "불충분한 인증" -#: shared-module/os/getenv.c -msgid "Key not found" -msgstr "키를 찾을 수 없습니다" +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +msgid "Insufficient authorization" +msgstr "" -#: shared-module/is31fl3741/FrameBuffer.c -msgid "LED mappings must match display size" -msgstr "LED 매핑은 디스플레이 크기와 일치해야 합니다" +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +msgid "Insufficient encryption" +msgstr "불충분한 암호화" -#: py/compile.c -msgid "LHS of keyword arg must be an id" -msgstr "키워드 인수의 LHS 는 id 여야 합니다" +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +#, c-format +msgid "Unknown gatt error: 0x%04x" +msgstr "" -#: shared-module/displayio/Group.c -msgid "Layer already in a group" -msgstr "레이어가 이미 그룹에 있습니다" +#: ports/espressif/common-hal/alarm/pin/PinAlarm.c +#, fuzzy +msgid "Cannot wake on pin edge. Only level." +msgstr "핀의 에지에서는 깨울 수 없습니다. 레벨에서만 깨울 수 있습니다." -#: shared-module/displayio/Group.c -msgid "Layer must be a Group or TileGrid subclass" -msgstr "레이어는 그룹 또는 TileGrid 하위 클래스 여야 합니다" +#: ports/espressif/common-hal/alarm/pin/PinAlarm.c +msgid "Cannot pull on input-only pin." +msgstr "입력 전용 핀을 끌어올 수 없습니다." -#: shared-bindings/audiocore/RawSample.c -msgid "Length of %q must be an even multiple of channel_count * type_size" +#: ports/espressif/common-hal/alarm/pin/PinAlarm.c +msgid "Can only alarm on two low pins from deep sleep." msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "MAC address was invalid" -msgstr "MAC 주소는 잘못되었습니다" - -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/espressif/common-hal/_bleio/Descriptor.c -msgid "MITM security not supported" +#: ports/espressif/common-hal/alarm/pin/PinAlarm.c +msgid "Can only alarm on one low pin while others alarm high from deep sleep." msgstr "" -#: shared-bindings/is31fl3741/IS31FL3741.c -msgid "Mapping must be a tuple" -msgstr "매핑은 투플이어야 합니다" +#: ports/espressif/common-hal/alarm/pin/PinAlarm.c +msgid "Can only alarm on RTC IO from deep sleep." +msgstr "" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Mismatched data size" -msgstr "일치하지 않는 데이터 크기" +#: ports/espressif/common-hal/alarm/time/TimeAlarm.c +#: ports/raspberrypi/common-hal/alarm/time/TimeAlarm.c +msgid "Only one alarm.time alarm can be set." +msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Mismatched swap flag" -msgstr "일치하지 않는 스왑 플래그" +#: ports/espressif/common-hal/alarm/touch/TouchAlarm.c +msgid "Only one %q can be set in deep sleep." +msgstr "딥 슬립에서는 하나의 %q만 설정할 수 있습니다." -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#: ports/espressif/common-hal/analogbufio/BufferedIn.c #, fuzzy -msgid "Missing first_in_pin. %q[%u] reads pin(s)" -msgstr "first_in_pin이 누락되어 있습니다. %q[%u]이 pin(s)을 읽습니다" +msgid "%q must be array of type 'H'" +msgstr "%q는 'H' 유형의 배열이어야 합니다" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_in_pin. %q[%u] shifts in from pin(s)" -msgstr "first_in_pin이 누락되었습니다. %q[%u]는 pin(s)에서 이동합니다" +#: ports/espressif/common-hal/audiobusio/PDMIn.c +#: shared-bindings/audioi2sin/I2SIn.c shared-bindings/usb_host_audio/USBIn.c +msgid "%q must be 8, 16, 24, or 32" +msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_in_pin. %q[%u] waits based on pin" -msgstr "first_in_pin이 누락되었습니다. %q[%u]는 핀에 따라 대기 중입니다" +#: ports/espressif/common-hal/audiobusio/__init__.c +#: ports/espressif/common-hal/audioi2sin/I2SIn.c +#: ports/espressif/common-hal/mii/Ethernet.c shared-bindings/emmcio/EMMC.c +#, fuzzy +msgid "Peripheral in use" +msgstr "주변 기기가 사용 중입니다" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_out_pin. %q[%u] shifts out to pin(s)" -msgstr "first_out_pin이 누락되었습니다. %q[%u]는 pin(s)으로 이동합니다" +#: ports/espressif/common-hal/audioi2sin/I2SIn.c +#: ports/raspberrypi/common-hal/audioi2sin/I2SIn.c +msgid "%q must be 8 or 16" +msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_out_pin. %q[%u] writes pin(s)" -msgstr "first_out_pin이 누락되었습니다. %q[%u]는 pin(s)에 씁니다" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "audio format not supported" +msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -#, fuzzy -msgid "Missing first_set_pin. %q[%u] sets pin(s)" -msgstr "first_set_pin이 누락되었습니다. %q[%u]는 pin(s)을 설정합니다" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to start async audio" +msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -#, fuzzy -msgid "Missing jmp_pin. %q[%u] jumps on pin" -msgstr "jmp_pin이 누락되었습니다. %q[%u] 핀으로 점프합니다" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to create continuous channels: invalid arg" +msgstr "" -#: shared-module/storage/__init__.c -msgid "Mount point directory missing" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to create continuous channels: invalid state" msgstr "" -#: ports/zephyr-cp/bindings/zephyr_serial/UART.c shared-bindings/busio/UART.c -#: shared-bindings/displayio/Group.c -msgid "Must be a %q subclass." -msgstr "%q의 하위클래스여야 합니다." +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to create continuous channels: not found" +msgstr "" -#: ports/espressif/common-hal/dotclockframebuffer/DotClockFramebuffer.c -msgid "Must provide 5/6/5 RGB pins" -msgstr "5/6/5 RGB 핀을 제공해야 합니다" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to create continuous channels: no mem" +msgstr "" -#: ports/mimxrt10xx/common-hal/busio/SPI.c shared-bindings/busio/SPI.c -msgid "Must provide MISO or MOSI pin" -msgstr "MISO 또는 MOSI 핀을 제공해야 합니다" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to register continuous events callback" +msgstr "" -#: shared-bindings/rgbmatrix/RGBMatrix.c -#, c-format -msgid "Must use a multiple of 6 rgb pins, not %d" -msgstr "%d이 아닌, 6 rgb 핀을 여러 개 사용해야 합니다" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to enable continuous" +msgstr "" -#: supervisor/shared/safe_mode.c -msgid "NLR jump failed. Likely memory corruption." -msgstr "NLR 는 점프에 실패했습니다. 아마도 메모리 손상일 것입니다." +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Can't construct AudioOut because continuous channel already open" +msgstr "" -#: ports/espressif/common-hal/nvm/ByteArray.c -msgid "NVS Error" -msgstr "NVS 오류" +#: ports/espressif/common-hal/audioio/AudioOut.c +#: ports/espressif/common-hal/mipicsi/Camera.c +#: shared-module/videocore/VideoBuffer.c shared-module/videogif/GifDecoder.c +msgid "already playing" +msgstr "" -#: shared-bindings/socketpool/SocketPool.c -msgid "Name or service not known" -msgstr "이름 또는 서비스를 알 수 없습니다" +#: ports/espressif/common-hal/busio/I2C.c +#: ports/espressif/common-hal/i2ctarget/I2CTarget.c +#: ports/nordic/common-hal/busio/I2C.c ports/zephyr-cp/common-hal/busio/I2C.c +msgid "All I2C peripherals are in use" +msgstr "사용 중인 모든 I2C주변 기기" -#: shared-bindings/displayio/TileGrid.c -msgid "New bitmap must be same size as old bitmap" -msgstr "새로운 비트맵은 원본 비트맵과 크기가 같아야 합니다" +#: ports/espressif/common-hal/busio/I2C.c +#: ports/espressif/common-hal/busio/SPI.c +msgid "Unable to create lock" +msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -#, fuzzy -msgid "Nimble out of memory" -msgstr "빠른 메모리 부족" +#: ports/espressif/common-hal/busio/SPI.c +msgid "SPI configuration failed" +msgstr "" + +#: ports/espressif/common-hal/busio/SPI.c ports/nordic/common-hal/busio/SPI.c +#: ports/zephyr-cp/common-hal/async_spi/SPI.c +msgid "All SPI peripherals are in use" +msgstr "사용중인 모든 SPI주변 기기" -#: ports/atmel-samd/common-hal/busio/UART.c #: ports/espressif/common-hal/busio/SPI.c +#: ports/espressif/common-hal/canio/CAN.c +#: ports/espressif/common-hal/qspibus/QSPIBus.c +msgid "ESP-IDF memory allocation failed" +msgstr "ESP-IDF 메모리 할당에 실패하였습니다" + #: ports/espressif/common-hal/busio/UART.c -#: ports/mimxrt10xx/common-hal/busio/SPI.c #: ports/mimxrt10xx/common-hal/busio/UART.c -#: ports/nordic/common-hal/busio/UART.c -#: ports/raspberrypi/common-hal/busio/UART.c ports/stm/common-hal/busio/SPI.c -#: ports/stm/common-hal/busio/UART.c shared-bindings/fourwire/FourWire.c -#: shared-bindings/i2cdisplaybus/I2CDisplayBus.c -#: shared-bindings/paralleldisplaybus/ParallelBus.c -#: shared-module/bitbangio/SPI.c -msgid "No %q pin" -msgstr "%q 핀이 없습니다" +msgid "Cannot specify RTS or CTS in RS485 mode" +msgstr "RS485 모드에서는 RTS 또는 CTS를 지정할 수 없습니다" -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Characteristic.c -msgid "No CCCD for this Characteristic" -msgstr "이 특성에 대한 CCCD가 없습니다" +#: ports/espressif/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c +msgid "RS485 inversion specified when not in RS485 mode" +msgstr "RS485 모드가 아닐 때 RS485 반전이 지정됩니다" -#: ports/atmel-samd/common-hal/analogio/AnalogOut.c -#: ports/stm/common-hal/analogio/AnalogOut.c -msgid "No DAC on chip" -msgstr "칩에 DAC가 없습니다" +#: ports/espressif/common-hal/canio/CAN.c +msgid "Baudrate not supported by peripheral" +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 "DMA 채널을 찾을 수 없습니다" +#: ports/espressif/common-hal/canio/CAN.c +#, fuzzy +msgid "All CAN peripherals are in use" +msgstr "모든 CAN 주변 기기가 사용 중입니다" -#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c -msgid "No DMA pacing timer found" -msgstr "DMA 간격 타이머를 찾을 수 없습니다" +#: ports/espressif/common-hal/canio/CAN.c +msgid "loopback + silent mode not supported by peripheral" +msgstr "" -#: shared-module/adafruit_bus_device/i2c_device/I2CDevice.c +#: ports/espressif/common-hal/canio/CAN.c #, c-format -msgid "No I2C device at address: 0x%x" -msgstr "주소에 I2C 장치가 없습니다: 0x%x" +msgid "twai_driver_install returned esp-idf error #%d" +msgstr "" -#: supervisor/shared/web_workflow/web_workflow.c -msgid "No IP" -msgstr "IP가 없습니다" +#: ports/espressif/common-hal/canio/CAN.c +#, c-format +msgid "twai_start returned esp-idf error #%d" +msgstr "" -#: ports/atmel-samd/common-hal/microcontroller/__init__.c -#: ports/cxd56/common-hal/microcontroller/__init__.c -#: ports/mimxrt10xx/common-hal/microcontroller/__init__.c -msgid "No bootloader present" +#: ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "ds_params has the wrong length" msgstr "" -#: shared-module/usb/core/Device.c -#, fuzzy -msgid "No configuration set" -msgstr "구성이 설정되어 있지 않습니다" +#: ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "" +"This key already committed to a different algorithm; call " +"load_digital_signature_key() again to use a different one" +msgstr "" -#: shared-bindings/_bleio/PacketBuffer.c -msgid "No connection: length cannot be determined" -msgstr "연결이 없습니다: 길이를 결정할 수 없습니다" +#: ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "" +"This key's ds_params were replaced by a later load_digital_signature_key() " +"call for the same key slot" +msgstr "" -#: shared-bindings/board/__init__.c -msgid "No default %q bus" -msgstr "기본 버스 %q가 없습니다" +#: ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "ds_params is invalid for this key slot" +msgstr "" -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c -#: ports/atmel-samd/common-hal/touchio/TouchIn.c -msgid "No free GCLKs" -msgstr "무료 GCLKs가 없습니다" +#: ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "Digital Signature peripheral not available on this chip" +msgstr "" -#: shared-bindings/os/__init__.c -msgid "No hardware random available" -msgstr "임의의 하드웨어를 사용할 수 없습니다" +#: ports/espressif/common-hal/dotclockframebuffer/DotClockFramebuffer.c +msgid "Must provide 5/6/5 RGB pins" +msgstr "5/6/5 RGB 핀을 제공해야 합니다" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -#, fuzzy -msgid "No in in program" -msgstr "프로그램에 입력이 없습니다" +#: ports/espressif/common-hal/dualbank/__init__.c +msgid "Firmware is duplicate" +msgstr "펌웨어가 중복되었습니다" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -#, fuzzy -msgid "No in or out in program" -msgstr "프로그램에 입력 또는 출력이 없습니다" +#: ports/espressif/common-hal/dualbank/__init__.c +msgid "Firmware is invalid" +msgstr "펌웨어가 잘못되었습니다" -#: py/objint.c shared-bindings/time/__init__.c -msgid "No long integer support" -msgstr "긴 정수 지원이 없습니다" +#: ports/espressif/common-hal/dualbank/__init__.c +msgid "Firmware is too big" +msgstr "펌웨어가 너무 큽니다" -#: shared-bindings/wifi/Radio.c -msgid "No network with that ssid" -msgstr "이 ssid를 사용하는 네트워크가 없습니다" +#: ports/espressif/common-hal/espcamera/Camera.c py/objobject.c py/runtime.c +msgid "no such attribute" +msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "No out in program" -msgstr "프로그램에 출력이 없습니다" +#: ports/espressif/common-hal/espcamera/Camera.c +msgid "invalid setting" +msgstr "" -#: ports/atmel-samd/common-hal/busio/I2C.c -#: ports/espressif/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nordic/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 "SDA 또는 SCL에서 풀업을 찾을 수 없습니다; 케이블 연결을 확인하십시오" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "Generic Failure" +msgstr "일반 오류" -#: shared-module/touchio/TouchIn.c -msgid "No pulldown on pin; 1Mohm recommended" -msgstr "핀에 풀다운이 없습니다; 1Mohm를 권장합니다" +#: ports/espressif/common-hal/espidf/__init__.c +#, fuzzy +msgid "Out of memory" +msgstr "메모리 부족" + +#: ports/espressif/common-hal/espidf/__init__.c py/moderrno.c +msgid "Invalid argument" +msgstr "잘못된 인수" + +#: ports/espressif/common-hal/espidf/__init__.c +msgid "Invalid size" +msgstr "잘못된 크기" + +#: ports/espressif/common-hal/espidf/__init__.c +msgid "Requested resource not found" +msgstr "" -#: py/moderrno.c -msgid "No space left on device" -msgstr "장치에 남은 공간이 없습니다" +#: ports/espressif/common-hal/espidf/__init__.c +#: ports/espressif/common-hal/jpegio/JpegDecoder.c +#: ports/raspberrypi/common-hal/usb_host_bulk/InStream.c +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +#: shared-bindings/picogame/Canvas.c shared-bindings/picogame/__init__.c +#: shared-module/jpegio/JpegDecoder.c shared-module/picogame/Display.c +msgid "Operation or feature not supported" +msgstr "작업 또는 기능이 지원되지 않습니다" -#: py/moderrno.c -msgid "No such device" -msgstr "해당 장치가 없습니다" +#: ports/espressif/common-hal/espidf/__init__.c +#: ports/espressif/common-hal/qspibus/QSPIBus.c +#: shared-module/_airlift/__init__.c +#, fuzzy +msgid "Operation timed out" +msgstr "작업 시간 초과되었습니다" -#: py/moderrno.c -msgid "No such file/directory" -msgstr "해당 파일/디렉토리가 없습니다" +#: ports/espressif/common-hal/espidf/__init__.c +#: shared-module/_airlift/__init__.c +msgid "Received response was invalid" +msgstr "수신된 응답이 잘못되었습니다" -#: shared-module/rgbmatrix/RGBMatrix.c -msgid "No timer available" -msgstr "사용 가능한 타이머가 없습니다" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "CRC or checksum was invalid" +msgstr "CRC 또는 checksum이 잘못되었습니다" -#: shared-module/usb/core/Device.c -msgid "No usb host port initialized" -msgstr "usb 호스트 포트가 초기화되지 않았습니다" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "Version was invalid" +msgstr "" -#: ports/nordic/common-hal/_bleio/__init__.c -msgid "Nordic system firmware out of memory" -msgstr "Nordic 시스템 펌웨어에 메모리가 부족합니다" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "MAC address was invalid" +msgstr "MAC 주소는 잘못되었습니다" -#: shared-bindings/ipaddress/IPv4Address.c shared-bindings/ipaddress/__init__.c -msgid "Not a valid IP string" -msgstr "유효한 IP 문자열이 아닙니다" +#: ports/espressif/common-hal/espidf/__init__.c +#, fuzzy, c-format +msgid "%s error 0x%x" +msgstr "%s 오류 0x%x" -#: ports/espressif/common-hal/_bleio/__init__.c -#: ports/nordic/common-hal/_bleio/__init__.c -#: shared-bindings/_bleio/CharacteristicBuffer.c -msgid "Not connected" -msgstr "연결되지 않았습니다" +#: ports/espressif/common-hal/espulp/ULP.c +msgid "Program too long" +msgstr "프로그램이 너무 깁니다" -#: shared-bindings/audiobusio/I2SOut.c shared-bindings/audioio/AudioOut.c -#: shared-bindings/audiopwmio/PWMAudioOut.c -msgid "Not playing" -msgstr "재생되지 않았습니다" +#: ports/espressif/common-hal/espulp/ULP.c +#: ports/espressif/common-hal/mipidsi/Bus.c +#: ports/espressif/common-hal/qspibus/QSPIBus.c +#: ports/mimxrt10xx/common-hal/audiobusio/__init__.c +#: ports/mimxrt10xx/common-hal/usb_host/Port.c +#: ports/raspberrypi/common-hal/picodvi/AudioOut.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#: ports/raspberrypi/common-hal/usb_host/Port.c +#: shared-bindings/digitalio/DigitalInOut.c shared-bindings/emmcio/EMMC.c +#: shared-bindings/i2cioexpander/IOPin.c shared-bindings/microcontroller/Pin.c +#: shared-module/_airlift/__init__.c +#: shared-module/epaperdisplay/EPaperDisplay.c +#: shared-module/max3421e/Max3421E.c shared-module/usb/core/Device.c +#: shared-module/usb_host_audio/USBIn.c +msgid "%q in use" +msgstr "%q 사용 중입니다" -#: shared-module/jpegio/JpegDecoder.c +#: ports/espressif/common-hal/espulp/ULPAlarm.c +msgid "Only one %q can be set." +msgstr "하나의 %q만 설정할 수 있습니다." + +#: ports/espressif/common-hal/i2ctarget/I2CTarget.c +#: ports/raspberrypi/common-hal/i2ctarget/I2CTarget.c #, fuzzy -msgid "Not supported JPEG standard" -msgstr "지원되지 않는 JPEG 표준" +msgid "Only one address is allowed" +msgstr "오직 하나의 주소만 허용됩니다" -#: ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/espressif/common-hal/sdioio/SDCard.c +#: ports/espressif/common-hal/max3421e/Max3421E.c +#: ports/raspberrypi/common-hal/wifi/__init__.c #, c-format -msgid "Number of data_pins must be %d or %d, not %d" +msgid "Unknown error code %d" msgstr "" -#: shared-bindings/util.c -msgid "" -"Object has been deinitialized and can no longer be used. Create a new object." +#: ports/espressif/common-hal/mdns/Server.c +#: ports/raspberrypi/common-hal/mdns/Server.c +msgid "mDNS only works with built-in WiFi" msgstr "" -"개체가 초기화 해제되어 더 이사 사용될 수 없습니다. 새로운 개체를 만드십시오." -#: ports/nordic/common-hal/busio/UART.c -msgid "Odd parity is not supported" -msgstr "홀수 패리티는 지원되지 않습니다" +#: ports/espressif/common-hal/mdns/Server.c +#: ports/raspberrypi/common-hal/mdns/Server.c +msgid "mDNS already initialized" +msgstr "" -#: supervisor/shared/bluetooth/bluetooth.c -msgid "Off" -msgstr "꺼짐 (연결 끊김)" +#: ports/espressif/common-hal/mdns/Server.c +#: ports/raspberrypi/common-hal/mdns/Server.c +msgid "Unable to start mDNS query" +msgstr "" -#: supervisor/shared/bluetooth/bluetooth.c -msgid "Ok" -msgstr "켜짐 (연결됨)" +#: ports/espressif/common-hal/memorymap/AddressRange.c +#: ports/nordic/common-hal/memorymap/AddressRange.c +#: ports/raspberrypi/common-hal/memorymap/AddressRange.c +msgid "Address range not allowed" +msgstr "주소 범위가 허용되지 않습니다" -#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c -#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c -#, c-format -msgid "Only 8 or 16 bit mono with %dx oversampling supported." -msgstr "%dx 오버샘플링이 포함된 8 또는 16 비트 모노만 지원됩니다." +#: ports/espressif/common-hal/mipicsi/Camera.c +#: shared-bindings/displayio/TileGrid.c shared-bindings/terminalio/Terminal.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-bindings/vectorio/VectorShape.c +msgid "unsupported %q type" +msgstr "" -#: ports/espressif/common-hal/wifi/__init__.c -#: ports/raspberrypi/common-hal/wifi/__init__.c -msgid "Only IPv4 addresses supported" -msgstr "IPv4 주소만 지원됩니다" +#: ports/espressif/common-hal/mipicsi/Camera.c +msgid "output_format must be RGB565 or RGB888" +msgstr "" -#: ports/raspberrypi/common-hal/socketpool/Socket.c -msgid "Only IPv4 sockets supported" -msgstr "IPv4 소켓만 지원됩니다" +#: ports/espressif/common-hal/mipicsi/Camera.c +msgid "ISP conversion not supported on this chip" +msgstr "" -#: shared-module/displayio/OnDiskBitmap.c -#, c-format -msgid "" -"Only Windows format, uncompressed BMP supported: given header size is %d" -msgstr "윈도우 형식, 비압축 BMP만 지원됩니다: 지정된 헤더 크기는 %d 입니다" +#: ports/espressif/common-hal/mipidsi/Bus.c +msgid "%q is above %u" +msgstr "" -#: shared-bindings/_bleio/Adapter.c -#, fuzzy -msgid "Only connectable advertisements can be directed" -msgstr "연결 가능한 광고만 지시할 수 있습니다" +#: ports/espressif/common-hal/mipidsi/Bus.c +msgid "%q is not reachable by the PHY" +msgstr "" -#: ports/stm/common-hal/alarm/pin/PinAlarm.c -msgid "Only edge detection is available on this hardware" -msgstr "이 하드웨어에서는 에지 감지만 가능합니다" +#: ports/espressif/common-hal/nvm/ByteArray.c +msgid "NVS Error" +msgstr "NVS 오류" -#: shared-bindings/ipaddress/__init__.c -msgid "Only int or string supported for ip" -msgstr "ip에는 정수 또는 문자열만 지원됩니다" +#: ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c +#: ports/espressif/common-hal/sdioio/SDCard.c +#, c-format +msgid "Number of data_pins must be %d or %d, not %d" +msgstr "" -#: ports/espressif/common-hal/alarm/touch/TouchAlarm.c -msgid "Only one %q can be set in deep sleep." -msgstr "딥 슬립에서는 하나의 %q만 설정할 수 있습니다." +#: ports/espressif/common-hal/pulseio/PulseIn.c +msgid "pop from an empty PulseIn" +msgstr "" -#: ports/espressif/common-hal/espulp/ULPAlarm.c -msgid "Only one %q can be set." -msgstr "하나의 %q만 설정할 수 있습니다." +#: ports/espressif/common-hal/qspibus/QSPIBus.c +#: ports/raspberrypi/common-hal/usb_host_bulk/InStream.c +#: shared-module/usb/core/Device.c +msgid "Could not allocate DMA capable buffer" +msgstr "" -#: ports/espressif/common-hal/i2ctarget/I2CTarget.c -#: ports/raspberrypi/common-hal/i2ctarget/I2CTarget.c -#, fuzzy -msgid "Only one address is allowed" -msgstr "오직 하나의 주소만 허용됩니다" +#: ports/espressif/common-hal/qspibus/QSPIBus.c shared-bindings/pwmio/PWMOut.c +#: supervisor/shared/settings.c +msgid "Internal error" +msgstr "내부 오류" -#: ports/atmel-samd/common-hal/alarm/time/TimeAlarm.c -#: ports/nordic/common-hal/alarm/time/TimeAlarm.c -#: ports/stm/common-hal/alarm/time/TimeAlarm.c -msgid "Only one alarm.time alarm can be set" +#: ports/espressif/common-hal/rclcpy/Node.c +msgid "ROS node failed to initialize" msgstr "" -#: ports/espressif/common-hal/alarm/time/TimeAlarm.c -#: ports/raspberrypi/common-hal/alarm/time/TimeAlarm.c -msgid "Only one alarm.time alarm can be set." +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "ROS topic failed to initialize" msgstr "" -#: shared-module/displayio/ColorConverter.c -#, fuzzy -msgid "Only one color can be transparent at a time" -msgstr "한 번에 한 가지 색상만 투명할 수 있습니다" +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "Could not publish to ROS topic" +msgstr "" -#: py/moderrno.c -#, fuzzy -msgid "Operation not permitted" -msgstr "작업이 허용되지 않습니다" +#: ports/espressif/common-hal/rclcpy/__init__.c +#, c-format +msgid "Critical ROS failure during soft reboot, reset required: %d" +msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Operation or feature not supported" -msgstr "작업 또는 기능이 지원되지 않습니다" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS memory allocator failure" +msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -#, fuzzy -msgid "Operation timed out" -msgstr "작업 시간 초과되었습니다" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS internal setup failure" +msgstr "" -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "Out of MDNS service slots" -msgstr "MDNS 서비스 슬롯 부족" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "Invalid ROS domain ID" +msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -#, fuzzy -msgid "Out of memory" -msgstr "메모리 부족" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS failed to initialize. Is agent connected?" +msgstr "" + +#: ports/espressif/common-hal/sdioio/SDCard.c +#: ports/raspberrypi/common-hal/sdioio/SDCard.c +#: ports/stm/common-hal/sdioio/SDCard.c +#, c-format +msgid "SDIO Init Error 0x%02x" +msgstr "" #: ports/espressif/common-hal/socketpool/Socket.c -#: ports/raspberrypi/common-hal/socketpool/Socket.c #: ports/zephyr-cp/common-hal/socketpool/Socket.c +msgid "Unsupported socket type" +msgstr "" + +#: ports/espressif/common-hal/socketpool/Socket.c +#: ports/raspberrypi/common-hal/socketpool/Socket.c msgid "Out of sockets" msgstr "소켓 부족" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "Out-buffer elements must be <= 4 bytes long" -msgstr "출력 버퍼 요소의 길이는 <= 4 바이트 여야 합니다" - -#: ports/stm/common-hal/pwmio/PWMOut.c -#, fuzzy -msgid "PWM restart" -msgstr "PWM 재시작" - -#: ports/raspberrypi/common-hal/countio/Counter.c -#, fuzzy -msgid "PWM slice already in use" -msgstr "PWM slice가 이미 사용 중입니다" +#: ports/espressif/common-hal/socketpool/SocketPool.c +msgid "SocketPool can only be used with %q.%q or any %q.%q" +msgstr "" -#: ports/raspberrypi/common-hal/countio/Counter.c +#: ports/espressif/common-hal/watchdog/WatchDogTimer.c #, fuzzy -msgid "PWM slice channel A already in use" -msgstr "PWM slice channel A가 이미 사용 중입니다" +msgid "%q must be <= %u" +msgstr "%q 는 <= %u 여야 합니다" -#: shared-bindings/spitarget/SPITarget.c -msgid "Packet buffers for an SPI transfer must have the same length." +#: ports/espressif/common-hal/wifi/Monitor.c +msgid "monitor init failed" msgstr "" -#: shared-module/jpegio/JpegDecoder.c -#, fuzzy -msgid "Parameter error" -msgstr "파라미터 오류" +#: ports/espressif/common-hal/wifi/Radio.c +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "Interface must be started" +msgstr "인터페이스를 시작해야 합니다" -#: ports/espressif/common-hal/audiobusio/__init__.c +#: ports/espressif/common-hal/wifi/Radio.c +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "Invalid multicast MAC address" +msgstr "잘못된 멀티캐스트 MAC 주소" + +#: ports/espressif/common-hal/wifi/Radio.c +#: ports/raspberrypi/common-hal/wifi/Radio.c +#: ports/zephyr-cp/common-hal/wifi/Radio.c #, fuzzy -msgid "Peripheral in use" -msgstr "주변 기기가 사용 중입니다" +msgid "Already scanning for wifi networks" +msgstr "이미 wifi 네트워크를 찾고 있습니다" -#: py/moderrno.c -msgid "Permission denied" -msgstr "권한이 거부 되었습니다" +#: ports/espressif/common-hal/wifi/Radio.c +#: ports/espressif/common-hal/wifi/__init__.c +#: ports/raspberrypi/common-hal/wifi/Radio.c +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "WiFi is not enabled" +msgstr "" -#: ports/stm/common-hal/alarm/pin/PinAlarm.c -msgid "Pin cannot wake from Deep Sleep" -msgstr "핀은 딥 슬립에서 깨어날 수 없습니다" +#: ports/espressif/common-hal/wifi/ScannedNetworks.c +msgid "Failed to allocate wifi scan memory" +msgstr "wifi 검색 메모리 할당에 실패했습니다" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -#, fuzzy -msgid "Pin count too large" -msgstr "핀 수 너무 큼" +#: ports/espressif/common-hal/wifi/__init__.c +msgid "Failed to allocate Wifi memory" +msgstr "Wifi 메모리 할당에 실패했습니다" -#: ports/stm/common-hal/alarm/pin/PinAlarm.c -#: ports/stm/common-hal/pulseio/PulseIn.c -msgid "Pin interrupt already in use" -msgstr "핀 인터럽트는 이미 사용 중입니다" +#: ports/espressif/common-hal/wifi/__init__.c +#: ports/raspberrypi/common-hal/wifi/__init__.c +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "Only IPv4 addresses supported" +msgstr "IPv4 주소만 지원됩니다" -#: shared-bindings/adafruit_bus_device/spi_device/SPIDevice.c -msgid "Pin is input only" -msgstr "핀은 입력 전용입니다" +#: ports/mimxrt10xx/common-hal/busio/SPI.c +#: ports/raspberrypi/bindings/wiznet/PIO_SPI.c shared-bindings/async_spi/SPI.c +#: shared-bindings/busio/SPI.c +msgid "Must provide MISO or MOSI pin" +msgstr "MISO 또는 MOSI 핀을 제공해야 합니다" -#: ports/raspberrypi/common-hal/countio/Counter.c -msgid "Pin must be on PWM Channel B" -msgstr "핀은 PWM 채널 B에 있어야 합니다" +#: ports/mimxrt10xx/common-hal/busio/SPI.c +#: ports/mimxrt10xx/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/canio/CAN.c 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 +#: shared-bindings/emmcio/EMMC.c +msgid "Hardware in use, try alternative pins" +msgstr "하드웨어가 사용 중입니다, 대체 핀을 사용해보십시오" -#: 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" +#: ports/mimxrt10xx/common-hal/canio/CAN.c +msgid "Unable to send CAN Message: all Tx message buffers are busy" msgstr "" -#: ports/raspberrypi/common-hal/imagecapture/ParallelImageCapture.c -msgid "Pins must be sequential" -msgstr "핀은 순차적이어야 합니다" +#: ports/mimxrt10xx/common-hal/microcontroller/Processor.c +msgid "" +"Frequency must be 24, 150, 396, 450, 528, 600, 720, 816, 912, 960 or 1008 Mhz" +msgstr "" +"주파수는 24, 150, 396, 450, 528, 600, 720, 816, 912, 960 또는 1008 Mhz 여야 " +"합니다" -#: ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c -msgid "Pins must be sequential GPIO pins" -msgstr "핀은 순차적인 GPIO 핀이어야 합니다" +#: ports/nordic/boards/aramcon2_badge/mpconfigboard.h +msgid "You pressed the left button at start up." +msgstr "" -#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c -msgid "Pins must share PWM slice" +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "timeout must be < 655.35 secs" msgstr "" -#: shared-module/usb/core/Device.c -msgid "Pipe error" -msgstr "파이프 오류" +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "non-zero timeout must be > 0.01" +msgstr "" -#: py/builtinhelp.c -msgid "Plus any modules on the filesystem\n" -msgstr "게다가 파일 시스템의 모든 모듈\n" +#: ports/nordic/common-hal/_bleio/UUID.c +msgid "Unexpected nrfx uuid type" +msgstr "" -#: shared-module/vectorio/Polygon.c -msgid "Polygon needs at least 3 points" -msgstr "다각형은 최소 3개의 점이 필요합니다" +#: ports/nordic/common-hal/_bleio/__init__.c +msgid "Nordic system firmware out of memory" +msgstr "Nordic 시스템 펌웨어에 메모리가 부족합니다" -#: supervisor/shared/safe_mode.c -msgid "Power dipped. Make sure you are providing enough power." -msgstr "전력이 내려갔습니다. 충분한 전력을 제공할 수 있는지 확인하십시오." +#: ports/nordic/common-hal/_bleio/__init__.c +#, c-format +msgid "Unknown system firmware error: %04x" +msgstr "" -#: shared-bindings/_bleio/Adapter.c +#: ports/nordic/common-hal/alarm/pin/PinAlarm.c #, fuzzy -msgid "Prefix buffer must be on the heap" -msgstr "앞의 버퍼는 힙에 있어야 합니다" +msgid "Cannot wake on pin edge, only level" +msgstr "핀의 에지에서 깨울 수 없고, 레벨에서만 깨울 수 있습니다" -#: main.c -msgid "Press any key to enter the REPL. Use CTRL-D to reload.\n" -msgstr "아무 키나 눌러 REPL을 입력한다. 다시 로드할땐 CTRL-D를 사용한다.\n" +#: ports/nordic/common-hal/audiobusio/I2SOut.c +msgid "Device in use" +msgstr "사용 중인 장치" -#: main.c -msgid "Pretending to deep sleep until alarm, CTRL-C or file write.\n" -msgstr "알람, CTRL-C 또는 파일을 작성하기 전까지 딥 슬립을 하는 척합니다\n" +#: ports/nordic/common-hal/audiobusio/PDMIn.c +#: ports/stm/common-hal/audiobusio/PDMIn.c +msgid "only sample_rate=16000 is supported" +msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Program does IN without loading ISR" -msgstr "프로그램이 ISR을 로드하지 않고 IN을 실행했습니다" +#: ports/nordic/common-hal/audiobusio/PDMIn.c +#: ports/stm/common-hal/audiobusio/PDMIn.c +msgid "only bit_depth=16 is supported" +msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Program does OUT without loading OSR" -msgstr "프로그램이 OSR을 로드하지 않고 OUT을 실행했습니다" +#: ports/nordic/common-hal/busio/UART.c +#, c-format +msgid "error = 0x%08lX" +msgstr "" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "Program size invalid" -msgstr "프로그램 크기가 잘못되었습니다" +#: ports/nordic/common-hal/busio/UART.c +msgid "Odd parity is not supported" +msgstr "홀수 패리티는 지원되지 않습니다" -#: ports/espressif/common-hal/espulp/ULP.c -msgid "Program too long" -msgstr "프로그램이 너무 깁니다" +#: ports/nordic/common-hal/countio/Counter.c +#: ports/nordic/common-hal/pulseio/PulseIn.c +#: ports/nordic/common-hal/rotaryio/IncrementalEncoder.c +msgid "All channels in use" +msgstr "모든 채널이 사용중입니다" -#: shared-bindings/digitalio/DigitalInOut.c -#, fuzzy -msgid "Pull not used when direction is output." -msgstr "방향이 출력 될 때 풀은 사용되지 않습니다" +#: ports/nordic/common-hal/microcontroller/Processor.c +msgid "Cannot get temperature" +msgstr "온도 데이터를 수신 할 수 없습니다" -#: ports/raspberrypi/common-hal/countio/Counter.c -msgid "RISE_AND_FALL not available on this chip" -msgstr "이 칩에서는 RISE_AND_FALL을 사용할 수 없습니다" +#: ports/nordic/common-hal/watchdog/WatchDogTimer.c +msgid "timeout duration exceeded the maximum supported value" +msgstr "" -#: shared-module/displayio/OnDiskBitmap.c -msgid "RLE-compressed BMP not supported" +#: ports/nordic/common-hal/watchdog/WatchDogTimer.c +msgid "%q cannot be changed once mode is set to %q" msgstr "" -#: ports/stm/common-hal/os/__init__.c -msgid "RNG DeInit Error" -msgstr "RNG DeInit 오류" +#: ports/nordic/common-hal/watchdog/WatchDogTimer.c +msgid "WatchDogTimer cannot be deinitialized once mode is set to RESET" +msgstr "" -#: ports/stm/common-hal/os/__init__.c -msgid "RNG Init Error" -msgstr "RNG 초기화 오류" +#: ports/nordic/sd_mutex.c +#, c-format +msgid "Failed to acquire mutex, err 0x%04x" +msgstr "뮤텍스 획득에 실패했습니다, 오류 0x%04x" -#: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c -#: ports/nordic/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c -msgid "RS485" -msgstr "RS485" +#: ports/nordic/sd_mutex.c +#, c-format +msgid "Failed to release mutex, err 0x%04x" +msgstr "뮤텍스 해제에 실패했습니다, 오류 0x%04x" -#: ports/espressif/common-hal/busio/UART.c -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "RS485 inversion specified when not in RS485 mode" -msgstr "RS485 모드가 아닐 때 RS485 반전이 지정됩니다" +#: ports/raspberrypi/audio_dma.c +msgid "Audio conversion not implemented" +msgstr "오디오 변환이 구현되지 않음" -#: shared-bindings/alarm/time/TimeAlarm.c shared-bindings/time/__init__.c -msgid "RTC is not supported on this board" -msgstr "이 보드에서는 PTC가 지원되지 않습니다" +#: ports/raspberrypi/bindings/cyw43/__init__.c py/argcheck.c py/objexcept.c +#: shared-bindings/bitmapfilter/__init__.c shared-bindings/canio/CAN.c +#: shared-bindings/digitalio/Pull.c shared-bindings/picogame/Sprite.c +#: shared-bindings/supervisor/__init__.c shared-module/audiofilters/__init__.c +#: shared-module/displayio/legacy/__init__.c +#: shared-module/synthio/Synthesizer.c shared-module/videocore/VideoBuffer.c +msgid "%q must be of type %q or %q, not %q" +msgstr "%q는 %q가 아닌 %q 또는 %q 유형이어야 합니다" -#: ports/stm/common-hal/os/__init__.c -msgid "Random number generation error" -msgstr "난수 생성 오류" +#: ports/raspberrypi/bindings/picodvi/AudioOut.c +#: shared-bindings/audiobusio/I2SOut.c shared-bindings/audioio/AudioOut.c +#: shared-bindings/audiopwmio/PWMAudioOut.c shared-bindings/mcp4822/MCP4822.c +#: shared-bindings/usb_audio/USBMicrophone.c +msgid "Not playing" +msgstr "재생되지 않았습니다" -#: shared-bindings/_bleio/__init__.c -#: shared-bindings/memorymonitor/AllocationSize.c -#: shared-bindings/pulseio/PulseIn.c shared-module/bitmaptools/__init__.c -#: shared-module/displayio/Bitmap.c shared-module/displayio/Group.c -msgid "Read-only" -msgstr "읽기 전용" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Program size invalid" +msgstr "프로그램 크기가 잘못되었습니다" -#: extmod/vfs_fat.c py/moderrno.c -msgid "Read-only filesystem" -msgstr "읽기 전용 파일 시스템" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Init program size invalid" +msgstr "초기화 프로그램의 크기가 잘못되었습니다" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Received response was invalid" -msgstr "수신된 응답이 잘못되었습니다" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Buffer elements must be 4 bytes long or less" +msgstr "버퍼 요소는 4바이트 이하여야 합니다" -#: supervisor/shared/bluetooth/bluetooth.c -msgid "Reconnecting" -msgstr "다시 연결하는 중입니다" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Mismatched data size" +msgstr "일치하지 않는 데이터 크기" -#: shared-bindings/epaperdisplay/EPaperDisplay.c -msgid "Refresh too soon" -msgstr "너무 빨리 새로고침하였습니다" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Out-buffer elements must be <= 4 bytes long" +msgstr "출력 버퍼 요소의 길이는 <= 4 바이트 여야 합니다" -#: shared-bindings/canio/RemoteTransmissionRequest.c -msgid "RemoteTransmissionRequests limited to 8 bytes" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "In-buffer elements must be <= 4 bytes long" +msgstr "버퍼 내 요소 길이는 <= 4여야 합니다" + +#: ports/raspberrypi/bindings/wiznet/PIO_SPI.c shared-bindings/async_spi/SPI.c +#: 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 "이 함수에는 잠금이 필요합니다" + +#: ports/raspberrypi/bindings/wiznet/PIO_SPI.c shared-bindings/async_spi/SPI.c +#: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c +msgid "buffer slices must be of equal length" +msgstr "" + +#: ports/raspberrypi/common-hal/alarm/touch/TouchAlarm.c +#: ports/stm/common-hal/alarm/touch/TouchAlarm.c +msgid "Touch alarms not available" msgstr "" -#: shared-bindings/aesio/aes.c -msgid "Requested AES mode is unsupported" +#: ports/raspberrypi/common-hal/async_spi/SPI.c shared-bindings/emmcio/EMMC.c +msgid "SPI peripheral in use" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Requested resource not found" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audioi2sin/I2SIn.c +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Cannot use GPIO0..15 together with GPIO32..47" msgstr "" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c -msgid "Right channel unsupported" -msgstr "" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audioi2sin/I2SIn.c +msgid "Bit clock and word select must be sequential GPIO pins" +msgstr "비트 클럭 및 워드 선택은 순차적 GPIO 핀이어야 합니다" -#: shared-module/jpegio/JpegDecoder.c -msgid "Right format but not supported" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/mcp4822/MCP4822.c +msgid "Too many channels in sample." msgstr "" -#: main.c -msgid "Running in safe mode! Not running saved code.\n" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +#: ports/raspberrypi/common-hal/mcp4822/MCP4822.c +msgid "Audio source error" msgstr "" -#: shared-module/sdcardio/SDCard.c -msgid "SD card CSD format not supported" +#: ports/raspberrypi/common-hal/audioi2sin/I2SIn.c +msgid "%q must be 16, 24, or 32" msgstr "" -#: ports/cxd56/common-hal/sdioio/SDCard.c -msgid "SDCard init" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Pins must share PWM slice" msgstr "" -#: ports/stm/common-hal/sdioio/SDCard.c -#, c-format -msgid "SDIO GetCardInfo Error %d" -msgstr "" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "No DMA pacing timer found" +msgstr "DMA 간격 타이머를 찾을 수 없습니다" -#: ports/espressif/common-hal/sdioio/SDCard.c -#: ports/stm/common-hal/sdioio/SDCard.c -#, c-format -msgid "SDIO Init Error %x" -msgstr "" +#: ports/raspberrypi/common-hal/busio/I2C.c +#: ports/raspberrypi/common-hal/i2ctarget/I2CTarget.c +msgid "I2C peripheral in use" +msgstr "I2C 주변 기기가 사용 중입니다" -#: ports/espressif/common-hal/busio/SPI.c -msgid "SPI configuration failed" +#: ports/raspberrypi/common-hal/busio/UART.c +msgid "UART peripheral in use" msgstr "" -#: ports/stm/common-hal/busio/SPI.c -msgid "SPI init error" -msgstr "" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "Pin must be on PWM Channel B" +msgstr "핀은 PWM 채널 B에 있어야 합니다" -#: ports/raspberrypi/common-hal/busio/SPI.c -msgid "SPI peripheral in use" -msgstr "" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "RISE_AND_FALL not available on this chip" +msgstr "이 칩에서는 RISE_AND_FALL을 사용할 수 없습니다" -#: ports/stm/common-hal/busio/SPI.c -msgid "SPI re-init" -msgstr "" +#: ports/raspberrypi/common-hal/countio/Counter.c +#, fuzzy +msgid "PWM slice already in use" +msgstr "PWM slice가 이미 사용 중입니다" -#: shared-bindings/is31fl3741/FrameBuffer.c -msgid "Scale dimensions must divide by 3" -msgstr "" +#: ports/raspberrypi/common-hal/countio/Counter.c +#, fuzzy +msgid "PWM slice channel A already in use" +msgstr "PWM slice channel A가 이미 사용 중입니다" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Scan already in progress. Stop with stop_scan." -msgstr "" +#: ports/raspberrypi/common-hal/floppyio/__init__.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#: ports/raspberrypi/common-hal/usb_host/Port.c +#, fuzzy +msgid "All state machines in use" +msgstr "모든 상태 머신이 사용 중입니다" -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c -msgid "Serializer in use" +#: ports/raspberrypi/common-hal/floppyio/__init__.c +msgid "timeout waiting for flux" msgstr "" -#: shared-bindings/ssl/SSLContext.c -msgid "Server side context cannot have hostname" +#: ports/raspberrypi/common-hal/floppyio/__init__.c +#: shared-module/floppyio/__init__.c +msgid "timeout waiting for index pulse" msgstr "" -#: ports/cxd56/common-hal/camera/Camera.c -msgid "Size not supported" -msgstr "" +#: ports/raspberrypi/common-hal/imagecapture/ParallelImageCapture.c +msgid "Pins must be sequential" +msgstr "핀은 순차적이어야 합니다" -#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c -#: shared-bindings/nvm/ByteArray.c -msgid "Slice and value different lengths." +#: ports/raspberrypi/common-hal/mcp4822/MCP4822.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c +#: shared-module/aurora_epaper/aurora_framebuffer.c +msgid "Invalid %q and %q" msgstr "" -#: 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 "" +#: ports/raspberrypi/common-hal/mdns/Server.c +msgid "Out of MDNS service slots" +msgstr "MDNS 서비스 슬롯 부족" -#: ports/espressif/common-hal/socketpool/SocketPool.c -#: ports/raspberrypi/common-hal/socketpool/SocketPool.c -#: ports/zephyr-cp/common-hal/socketpool/SocketPool.c -msgid "SocketPool can only be used with wifi.radio" +#: ports/raspberrypi/common-hal/memorymap/AddressRange.c +msgid "Unable to access unaligned IO register" msgstr "" -#: shared-bindings/aesio/aes.c -msgid "Source and destination buffers must be the same length" +#: ports/raspberrypi/common-hal/memorymap/AddressRange.c +msgid "Unable to write to read-only memory" msgstr "" -#: shared-bindings/paralleldisplaybus/ParallelBus.c -msgid "Specify exactly one of data0 or data_pins" -msgstr "" +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c +msgid "All timers for this pin are in use" +msgstr "핀의 모든 타이머가 사용 중입니다" -#: supervisor/shared/safe_mode.c -msgid "Stack overflow. Increase stack size." -msgstr "" +#: ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c +msgid "Pins must be sequential GPIO pins" +msgstr "핀은 순차적인 GPIO 핀이어야 합니다" -#: shared-bindings/alarm/time/TimeAlarm.c -msgid "Supply one of monotonic_time or epoch_time" -msgstr "" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#, fuzzy +msgid "Pin count too large" +msgstr "핀 수 너무 큼" -#: shared-bindings/gnss/GNSS.c -msgid "System entry must be gnss.SatelliteSystem" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#, fuzzy +msgid "Missing jmp_pin. %q[%u] jumps on pin" +msgstr "jmp_pin이 누락되었습니다. %q[%u] 핀으로 점프합니다" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "%q[%u] uses extra pin" +msgstr "%q[%u]에서 추가 핀 사용" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_in_pin. %q[%u] waits based on pin" +msgstr "first_in_pin이 누락되었습니다. %q[%u]는 핀에 따라 대기 중입니다" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "%q[%u] waits on input outside of count" +msgstr "%q[%u]이(가) 카운트 외부의 입력을 대기합니다" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_in_pin. %q[%u] shifts in from pin(s)" +msgstr "first_in_pin이 누락되었습니다. %q[%u]는 pin(s)에서 이동합니다" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#, fuzzy +msgid "%q[%u] shifts in more bits than pin count" +msgstr "%q[%u]가 핀 수보다 더 많은 비트로 이동했습니다" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_out_pin. %q[%u] shifts out to pin(s)" +msgstr "first_out_pin이 누락되었습니다. %q[%u]는 pin(s)으로 이동합니다" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#, fuzzy +msgid "%q[%u] shifts out more bits than pin count" +msgstr "%q[%u]이(가) 핀 수보다 많은 비트를 전송합니다" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#, fuzzy +msgid "Missing first_set_pin. %q[%u] sets pin(s)" +msgstr "first_set_pin이 누락되었습니다. %q[%u]는 pin(s)을 설정합니다" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_out_pin. %q[%u] writes pin(s)" +msgstr "first_out_pin이 누락되었습니다. %q[%u]는 pin(s)에 씁니다" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#, fuzzy +msgid "Missing first_in_pin. %q[%u] reads pin(s)" +msgstr "first_in_pin이 누락되어 있습니다. %q[%u]이 pin(s)을 읽습니다" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Program does IN without loading ISR" +msgstr "프로그램이 ISR을 로드하지 않고 IN을 실행했습니다" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Program does OUT without loading OSR" +msgstr "프로그램이 OSR을 로드하지 않고 OUT을 실행했습니다" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin state conflicts with initial out pin state" +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 "pull masks conflict with direction masks" msgstr "" -#: ports/stm/common-hal/microcontroller/Processor.c -msgid "Temperature read timed out" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No out in program" +msgstr "프로그램에 출력이 없습니다" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#, fuzzy +msgid "No in in program" +msgstr "프로그램에 입력이 없습니다" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#, fuzzy +msgid "No in or out in program" +msgstr "프로그램에 입력 또는 출력이 없습니다" + +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Mismatched swap flag" +msgstr "일치하지 않는 스왑 플래그" + +#: ports/raspberrypi/common-hal/sdioio/SDCard.c +#, c-format +msgid "Number of data_pins must be %d, not %d" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "The `microcontroller` module was used to boot into safe mode." +#: ports/raspberrypi/common-hal/sdioio/SDCard.c +msgid "Data pins must be consecutive" msgstr "" -#: py/obj.c -msgid "The above exception was the direct cause of the following exception:" +#: ports/raspberrypi/common-hal/socketpool/Socket.c +msgid "Only IPv4 sockets supported" +msgstr "IPv4 소켓만 지원됩니다" + +#: ports/raspberrypi/common-hal/socketpool/SocketPool.c +msgid "SocketPool can only be used with wifi.radio" msgstr "" -#: shared-bindings/rgbmatrix/RGBMatrix.c -msgid "The length of rgb_pins must be 6, 12, 18, 24, or 30" +#: ports/raspberrypi/common-hal/usb_host/Port.c +msgid "All dma channels in use" +msgstr "모든 dma채널이 사용 중입니다" + +#: ports/raspberrypi/common-hal/wifi/Monitor.c +msgid "wifi.Monitor not available" msgstr "" -#: shared-module/audiocore/__init__.c -msgid "The sample's %q does not match" -msgstr "" +#: ports/raspberrypi/common-hal/wifi/Radio.c +msgid "%q is read-only for this board" +msgstr "%q는 이 보드에 대한 읽기 전용입니다" + +#: ports/raspberrypi/common-hal/wifi/Radio.c +msgid "AP could not be started" +msgstr "AP를 시작할 수 없습니다" -#: supervisor/shared/safe_mode.c -msgid "Third-party firmware fatal error." -msgstr "" +#: ports/stm/common-hal/alarm/pin/PinAlarm.c +msgid "Only edge detection is available on this hardware" +msgstr "이 하드웨어에서는 에지 감지만 가능합니다" -#: shared-module/imagecapture/ParallelImageCapture.c -msgid "This microcontroller does not support continuous capture." -msgstr "" +#: ports/stm/common-hal/alarm/pin/PinAlarm.c +#: ports/stm/common-hal/pulseio/PulseIn.c +msgid "Pin interrupt already in use" +msgstr "핀 인터럽트는 이미 사용 중입니다" -#: shared-module/paralleldisplaybus/ParallelBus.c -msgid "" -"This microcontroller only supports data0=, not data_pins=, because it " -"requires contiguous pins." -msgstr "" +#: ports/stm/common-hal/alarm/pin/PinAlarm.c +msgid "Pin cannot wake from Deep Sleep" +msgstr "핀은 딥 슬립에서 깨어날 수 없습니다" -#: shared-bindings/displayio/TileGrid.c -msgid "Tile height must exactly divide bitmap height" -msgstr "" +#: ports/stm/common-hal/alarm/pin/PinAlarm.c +#, fuzzy +msgid "Deep sleep pins must use a rising edge with pulldown" +msgstr "딥 슬립 핀은 풀다운이 있는 상승 에지를 사용해야 합니다" -#: shared-bindings/displayio/TileGrid.c shared-module/displayio/TileGrid.c -msgid "Tile index out of bounds" -msgstr "" +#: ports/stm/common-hal/analogio/AnalogIn.c +msgid "Invalid ADC Unit value" +msgstr "잘못된 ADC 단위 값" -#: shared-bindings/displayio/TileGrid.c -msgid "Tile width must exactly divide bitmap width" -msgstr "" +#: ports/stm/common-hal/analogio/AnalogOut.c +#: ports/stm/common-hal/audioio/AudioOut.c +msgid "DAC Device Init Error" +msgstr "DAC 장치 초기화 오류" -#: shared-bindings/alarm/time/TimeAlarm.c -msgid "Time is in the past." -msgstr "" +#: ports/stm/common-hal/analogio/AnalogOut.c +#: ports/stm/common-hal/audioio/AudioOut.c +msgid "DAC Channel Init Error" +msgstr "DAC 채널 초기화 오류" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -#, c-format -msgid "Timeout is too long: Maximum timeout length is %d seconds" +#: ports/stm/common-hal/audiobusio/PDMIn.c +msgid "only mono is supported" msgstr "" -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -msgid "Too many channels in sample" +#: ports/stm/common-hal/audiobusio/PDMIn.c +msgid "only oversample=64 is supported" msgstr "" -#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c -msgid "Too many channels in sample." -msgstr "" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +#, fuzzy +msgid "Another PWMAudioOut is already active" +msgstr "다른 PWMaudioOut이 이미 활성화되어 있습니다" -#: ports/espressif/common-hal/_bleio/Characteristic.c -msgid "Too many descriptors" -msgstr "" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +#, c-format +msgid "Buffer length %d too big. It must be less than %d" +msgstr "버퍼 길이 %d가 너무 큽니다. 그것은 %d보다 작아야 합니다" -#: shared-module/displayio/__init__.c -msgid "Too many display busses; forgot displayio.release_displays() ?" -msgstr "" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Failed to buffer the sample" +msgstr "샘플 버퍼링에 실패했습니다" -#: shared-module/displayio/__init__.c -msgid "Too many displays" -msgstr "" +#: ports/stm/common-hal/busio/I2C.c +msgid "I2C init error" +msgstr "I2C 초기화 오류" -#: ports/espressif/common-hal/_bleio/PacketBuffer.c -#: ports/nordic/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than %q" +#: ports/stm/common-hal/busio/SPI.c +msgid "SPI init error" msgstr "" -#: ports/raspberrypi/common-hal/alarm/touch/TouchAlarm.c -#: ports/stm/common-hal/alarm/touch/TouchAlarm.c -msgid "Touch alarms not available" +#: ports/stm/common-hal/busio/SPI.c +msgid "SPI re-init" msgstr "" -#: py/obj.c -msgid "Traceback (most recent call last):\n" -msgstr "" +#: ports/stm/common-hal/busio/UART.c +msgid "Internal define error" +msgstr "내부 정의 오류" #: ports/stm/common-hal/busio/UART.c -msgid "UART de-init" -msgstr "" +msgid "Could not start interrupt, RX busy" +msgstr "인터럽트를 시작할 수 없습니다, RX가 사용 중입니다" -#: ports/cxd56/common-hal/busio/UART.c ports/espressif/common-hal/busio/UART.c #: ports/stm/common-hal/busio/UART.c -msgid "UART init" +msgid "UART write" msgstr "" -#: ports/raspberrypi/common-hal/busio/UART.c -msgid "UART peripheral in use" +#: ports/stm/common-hal/busio/UART.c +msgid "UART de-init" msgstr "" #: ports/stm/common-hal/busio/UART.c msgid "UART re-init" msgstr "" -#: ports/stm/common-hal/busio/UART.c -msgid "UART write" +#: ports/stm/common-hal/microcontroller/Processor.c +msgid "Temperature read timed out" msgstr "" -#: main.c -msgid "UID:" +#: ports/stm/common-hal/microcontroller/Processor.c +msgid "Voltage read timed out" msgstr "" -#: shared-module/usb_hid/Device.c -msgid "USB busy" -msgstr "" +#: ports/stm/common-hal/os/__init__.c +msgid "RNG Init Error" +msgstr "RNG 초기화 오류" -#: supervisor/shared/safe_mode.c -msgid "USB devices need more endpoints than are available." -msgstr "" +#: ports/stm/common-hal/os/__init__.c +msgid "Random number generation error" +msgstr "난수 생성 오류" -#: supervisor/shared/safe_mode.c -msgid "USB devices specify too many interface names." -msgstr "" +#: ports/stm/common-hal/os/__init__.c +msgid "RNG DeInit Error" +msgstr "RNG DeInit 오류" -#: shared-module/usb_hid/Device.c -msgid "USB error" +#: ports/stm/common-hal/pwmio/PWMOut.c +msgid "timer re-init" msgstr "" -#: shared-bindings/_bleio/UUID.c -msgid "UUID integer value must be 0-0xffff" +#: ports/stm/common-hal/pwmio/PWMOut.c +msgid "channel re-init" msgstr "" -#: shared-bindings/_bleio/UUID.c -msgid "UUID string not 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'" -msgstr "UUID문자열이 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'형식이 아닙니다" - -#: shared-bindings/_bleio/UUID.c -msgid "UUID value is not str, int or byte buffer" -msgstr "" -"UUID값이 문자열(str), 정수(int) 또는 바이트버퍼가(byte buffer) 아닙니다" +#: ports/stm/common-hal/pwmio/PWMOut.c +#, fuzzy +msgid "PWM restart" +msgstr "PWM 재시작" -#: ports/raspberrypi/common-hal/memorymap/AddressRange.c -msgid "Unable to access unaligned IO register" +#: ports/stm/common-hal/sdioio/SDCard.c +#, c-format +msgid "MMC/SDIO Clock Error %x" 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" +#: ports/stm/common-hal/sdioio/SDCard.c +#, c-format +msgid "SDIO GetCardInfo Error %d" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Unable to allocate to the heap." -msgstr "" +#: ports/zephyr-cp/bindings/zephyr_display/Display.c +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/epaperdisplay/EPaperDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +#: shared-bindings/mipidsi/Display.c +msgid "Display rotation must be in 90 degree increments" +msgstr "디스플레이 회전은 90도씩 증가해야 합니다" -#: ports/espressif/common-hal/busio/I2C.c -msgid "Unable to create lock" -msgstr "" +#: ports/zephyr-cp/bindings/zephyr_display/Display.c +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/epaperdisplay/EPaperDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +#, fuzzy +msgid ".show(x) removed. Use .root_group = x" +msgstr ".show(x)가 제거되었습니다. .root_group = x를 사용합니다" -#: shared-module/i2cdisplaybus/I2CDisplayBus.c -#: shared-module/is31fl3741/IS31FL3741.c -#, c-format -msgid "Unable to find I2C Display at %x" -msgstr "" +#: ports/zephyr-cp/bindings/zephyr_display/Display.c +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +msgid "Brightness not adjustable" +msgstr "밝기를 조절할 수 없습니다" -#: py/parse.c -msgid "Unable to init parser" -msgstr "파서를 초기화(init) 할 수 없습니다" +#: ports/zephyr-cp/bindings/zephyr_display/Display.c py/argcheck.c +#: shared-bindings/busdisplay/BusDisplay.c shared-bindings/displayio/Bitmap.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +#: shared-bindings/is31fl3741/FrameBuffer.c +#: shared-bindings/rgbmatrix/RGBMatrix.c +msgid "%q must be %d-%d" +msgstr "%q는 %d-%d이어야 합니다" -#: shared-module/displayio/OnDiskBitmap.c -msgid "Unable to read color palette data" -msgstr "" +#: ports/zephyr-cp/bindings/zephyr_display/Display.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +#: shared-module/busdisplay/legacy/BusDisplay.c +#: shared-module/framebufferio/legacy/FramebufferDisplay.c +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "Group already used" +msgstr "이미 사용된 그룹" -#: ports/mimxrt10xx/common-hal/canio/CAN.c -msgid "Unable to send CAN Message: all Tx message buffers are busy" +#: ports/zephyr-cp/common-hal/_bleio/Adapter.c +msgid "Invalid advertising data" msgstr "" -#: ports/espressif/common-hal/mdns/Server.c -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "Unable to start mDNS query" +#: ports/zephyr-cp/common-hal/async_spi/SPI.c +#: ports/zephyr-cp/common-hal/audiobusio/I2SOut.c +#: ports/zephyr-cp/common-hal/busio/I2C.c +#: ports/zephyr-cp/common-hal/busio/UART.c +msgid "Use device tree to define %q devices" msgstr "" -#: shared-bindings/nvm/ByteArray.c -msgid "Unable to write to nvm." +#: ports/zephyr-cp/common-hal/mii/Ethernet.c +msgid "cannot construct ethernet interfaces; use board.ETHERNET" msgstr "" -#: ports/raspberrypi/common-hal/memorymap/AddressRange.c -msgid "Unable to write to read-only memory" +#: ports/zephyr-cp/common-hal/socketpool/SocketPool.c +msgid "SocketPool can only be used with %q.%q, %q.%q, or %q.%q" msgstr "" -#: shared-bindings/alarm/SleepMemory.c -msgid "Unable to write to sleep_memory." +#: ports/zephyr-cp/common-hal/usb_hid/Device.c shared-module/usb_hid/Device.c +msgid "USB error" msgstr "" -#: ports/nordic/common-hal/_bleio/UUID.c -msgid "Unexpected nrfx uuid type" +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "Failed to set hostname" msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown BLE error at %s:%d: %d" -msgstr "" +#: ports/zephyr-cp/common-hal/zephyr_display/legacy/Display.c +#: ports/zephyr-cp/common-hal/zephyr_display/lvgl/Display.c +#: shared-module/busdisplay/legacy/BusDisplay.c +#: shared-module/framebufferio/legacy/FramebufferDisplay.c +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "Below minimum frame rate" +msgstr "최소 프레임 속도 미만" -#: ports/espressif/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown BLE error: %d" +#: py/argcheck.c +msgid "function doesn't take keyword arguments" msgstr "" -#: ports/espressif/common-hal/max3421e/Max3421E.c -#: ports/raspberrypi/common-hal/wifi/__init__.c +#: py/argcheck.c py/bc.c py/objnamedtuple.c shared-bindings/_eve/__init__.c +#: shared-bindings/time/__init__.c #, c-format -msgid "Unknown error code %d" +msgid "function takes %d positional arguments but %d were given" msgstr "" -#: shared-bindings/wifi/Radio.c +#: py/argcheck.c #, c-format -msgid "Unknown failure %d" +msgid "function missing %d required positional arguments" msgstr "" -#: ports/nordic/common-hal/_bleio/__init__.c +#: py/argcheck.c #, c-format -msgid "Unknown gatt error: 0x%04x" +msgid "function expected at most %d arguments, got %d" msgstr "" -#: ports/atmel-samd/common-hal/alarm/pin/PinAlarm.c -#: supervisor/shared/safe_mode.c -msgid "Unknown reason." -msgstr "" +#: py/argcheck.c shared-bindings/wifi/Radio.c +msgid "'%q' argument required" +msgstr "'%q' 인수가 필요합니다" -#: ports/nordic/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown security error: 0x%04x" +#: py/argcheck.c +msgid "extra positional arguments given" msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown system firmware error at %s:%d: %d" +#: py/argcheck.c py/bc.c py/objnamedtuple.c +#: shared-bindings/traceback/__init__.c +msgid "unexpected keyword argument '%q'" msgstr "" -#: ports/nordic/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown system firmware error: %04x" +#: py/argcheck.c +msgid "extra keyword arguments given" msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown system firmware error: %d" +#: py/argcheck.c shared-bindings/_stage/__init__.c +#: shared-bindings/digitalio/DigitalInOut.c shared-bindings/picogame/__init__.c +msgid "argument num/types mismatch" msgstr "" -#: shared-bindings/adafruit_pixelbuf/PixelBuf.c -#: shared-module/_pixelmap/PixelMap.c -#, c-format -msgid "Unmatched number of items on RHS (expected %d, got %d)." +#: py/argcheck.c +msgid "keyword argument(s) not implemented - use normal args instead" msgstr "" -#: ports/nordic/common-hal/_bleio/__init__.c -msgid "" -"Unspecified issue. Can be that the pairing prompt on the other device was " -"declined or ignored." -msgstr "" +#: py/argcheck.c +msgid "%q must be %d" +msgstr "%q는 %d이어야 합니다" -#: shared-bindings/bitmaptools/__init__.c -msgid "Unsupported colorspace" +#: py/argcheck.c +#, fuzzy +msgid "%q must be >= %d" +msgstr "%q 는 >= %d 여야 합니다" + +#: py/argcheck.c shared-bindings/gifio/GifWriter.c +#: shared-module/_airlift/__init__.c +#, fuzzy +msgid "%q must be <= %d" +msgstr "%q 는 <= %d 여야 합니다" + +#: py/argcheck.c py/runtime.c shared-bindings/bitmapfilter/__init__.c +#: shared-module/audiodelays/MultiTapDelay.c shared-module/synthio/Note.c +#: shared-module/synthio/__init__.c +msgid "%q must be of type %q, not %q" +msgstr "%q는 %q가 아니라 %q 유형이어야 합니다" + +#: py/argcheck.c +msgid "%q length must be %d-%d" +msgstr "%q 길이는 %d - %d이어야 합니다" + +#: py/argcheck.c +msgid "%q length must be >= %d" +msgstr "%q 길이는 >= %d이어야 합니다" + +#: py/argcheck.c shared-module/_airlift/__init__.c +msgid "%q length must be <= %d" +msgstr "%q 길이는 <= %d>여야 합니다" + +#: py/argcheck.c shared-bindings/usb_hid/Device.c +msgid "%q length must be %d" +msgstr "%q 길이는 %d이어야 합니다" + +#: py/argcheck.c shared-module/audiofilters/__init__.c +msgid "%q in %q must be of type %q, not %q" +msgstr "%q의 %q는 %q가 아니라 %q 유형이어야 합니다" + +#: py/asmthumb.c +msgid "too many locals for native method" msgstr "" -#: shared-module/displayio/bus_core.c -msgid "Unsupported display bus type" +#: py/asmxtensa.c +msgid "ERROR: xtensa %q out of range" msgstr "" -#: shared-module/audiocore/WaveFile.c -msgid "Unsupported format" +#: py/asmxtensa.c +msgid "ERROR: %q %q not word-aligned" msgstr "" -#: shared-bindings/hashlib/__init__.c -msgid "Unsupported hash algorithm" +#: py/bc.c py/objnamedtuple.c +#, fuzzy +msgid "%q() takes %d positional arguments but %d were given" +msgstr "%q()는 %d 위치 인수를 사용하지만 %d이(가) 주어졌습니다" + +#: py/bc.c py/objnamedtuple.c +msgid "function got multiple values for argument '%q'" msgstr "" -#: ports/espressif/common-hal/socketpool/Socket.c -#: ports/zephyr-cp/common-hal/socketpool/Socket.c -msgid "Unsupported socket type" +#: py/bc.c +msgid "unexpected keyword argument" msgstr "" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/espressif/common-hal/dualbank/__init__.c -msgid "Update failed" +#: py/bc.c +#, c-format +msgid "function missing required positional argument #%d" msgstr "" -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Descriptor.c -msgid "Value length != required fixed length" +#: py/bc.c +msgid "function missing required keyword argument '%q'" msgstr "" -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Descriptor.c -msgid "Value length > max_length" +#: py/bc.c +msgid "function missing keyword-only argument" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Version was invalid" +#: py/binary.c py/objarray.c +msgid "bad typecode" msgstr "" -#: ports/stm/common-hal/microcontroller/Processor.c -msgid "Voltage read timed out" +#: py/binary.c +msgid "integer out of range" msgstr "" -#: main.c -msgid "WARNING: Your code filename has two extensions\n" +#: py/builtinevex.c +msgid "bad compile mode" msgstr "" -#: ports/nordic/common-hal/watchdog/WatchDogTimer.c -msgid "WatchDogTimer cannot be deinitialized once mode is set to RESET" +#: py/builtinhelp.c +msgid "Plus any modules on the filesystem\n" +msgstr "게다가 파일 시스템의 모든 모듈\n" + +#: py/builtinhelp.c +msgid "object " msgstr "" +#: py/builtinhelp.c +msgid " is of type %q\n" +msgstr " %q 유형입니다\n" + #: py/builtinhelp.c #, c-format msgid "" @@ -2410,2096 +2730,2469 @@ msgid "" "To list built-in modules type `help(\"modules\")`.\n" msgstr "" -#: supervisor/shared/web_workflow/web_workflow.c -msgid "Wi-Fi: " -msgstr "" - -#: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "Wifi is not enabled" +#: py/builtinimport.c +msgid "script compilation not supported" msgstr "" -#: main.c -msgid "Woken up by alarm.\n" +#: py/builtinimport.c +msgid "can't perform relative import" msgstr "" -#: ports/espressif/common-hal/_bleio/PacketBuffer.c -#: ports/nordic/common-hal/_bleio/PacketBuffer.c -msgid "Writes not supported on Characteristic" +#: py/builtinimport.c +msgid "module not found" msgstr "" -#: 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/meowmeow/mpconfigboard.h -msgid "You pressed both buttons at start up." +#: py/builtinimport.c +msgid "no module named '%q'" msgstr "" -#: ports/espressif/boards/m5stack_core_basic/mpconfigboard.h -#: ports/espressif/boards/m5stack_core_fire/mpconfigboard.h -#: ports/espressif/boards/m5stack_stick_c/mpconfigboard.h -#: ports/espressif/boards/m5stack_stick_c_plus/mpconfigboard.h -#: ports/espressif/boards/m5stack_stick_c_plus2/mpconfigboard.h -msgid "You pressed button A at start up." +#: py/builtinimport.c +msgid "relative import" msgstr "" -#: ports/espressif/boards/m5stack_m5paper/mpconfigboard.h -msgid "You pressed button DOWN at start up." +#: py/compile.c +msgid "can't assign to expression" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "You pressed the BOOT button at start up" +#: py/compile.c +msgid "multiple *x in assignment" msgstr "" -#: ports/espressif/boards/adafruit_feather_esp32c6_4mbflash_nopsram/mpconfigboard.h -#: ports/espressif/boards/adafruit_itsybitsy_esp32/mpconfigboard.h -#: ports/espressif/boards/waveshare_esp32_c6_lcd_1_47/mpconfigboard.h -msgid "You pressed the BOOT button at start up." +#: py/compile.c +msgid "non-default argument follows default argument" msgstr "" -#: ports/espressif/boards/adafruit_huzzah32_breakout/mpconfigboard.h -msgid "You pressed the GPIO0 button at start up." +#: py/compile.c +msgid "invalid micropython decorator" msgstr "" -#: ports/espressif/boards/espressif_esp32_lyrat/mpconfigboard.h -msgid "You pressed the Rec button at start up." +#: py/compile.c +msgid "invalid arch" msgstr "" -#: ports/espressif/boards/adafruit_feather_esp32_v2/mpconfigboard.h -msgid "You pressed the SW38 button at start up." +#: py/compile.c +msgid "can't delete expression" msgstr "" -#: ports/espressif/boards/hardkernel_odroid_go/mpconfigboard.h -#: ports/espressif/boards/vidi_x/mpconfigboard.h -msgid "You pressed the VOLUME button at start up." -msgstr "" +#: py/compile.c +msgid "'break'/'continue' outside loop" +msgstr "'break'/'continue' 외부 루프" -#: ports/espressif/boards/m5stack_atom_echo/mpconfigboard.h -#: ports/espressif/boards/m5stack_atom_lite/mpconfigboard.h -#: ports/espressif/boards/m5stack_atom_matrix/mpconfigboard.h -#: ports/espressif/boards/m5stack_atom_u/mpconfigboard.h -msgid "You pressed the central button at start up." -msgstr "" +#: py/compile.c +msgid "'return' outside function" +msgstr "'return' 는 함수 외부에 존재합니다" -#: ports/nordic/boards/aramcon2_badge/mpconfigboard.h -msgid "You pressed the left button at start up." +#: py/compile.c +msgid "import * not at module level" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "You pressed the reset button during boot." +#: py/compile.c +msgid "identifier redefined as global" msgstr "" -#: supervisor/shared/micropython.c -msgid "[truncated due to length]" +#: py/compile.c +msgid "no binding for nonlocal found" msgstr "" -#: py/objtype.c -msgid "__init__() should return None" +#: py/compile.c +msgid "identifier redefined as nonlocal" msgstr "" -#: py/objtype.c -#, c-format -msgid "__init__() should return None, not '%s'" +#: py/compile.c +msgid "can't declare nonlocal in outer code" msgstr "" -#: py/objobject.c -msgid "__new__ arg must be a user-type" +#: py/compile.c +msgid "default 'except' must be last" msgstr "" -#: extmod/modbinascii.c extmod/modhashlib.c py/objarray.c -msgid "a bytes-like object is required" +#: py/compile.c +msgid "async for/with outside async function" msgstr "" -#: shared-bindings/i2ctarget/I2CTarget.c -msgid "addresses is empty" -msgstr "" +#: py/compile.c +#, fuzzy +msgid "*x must be assignment target" +msgstr "*x는 할당 대상이어야 합니다" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "already playing" +#: py/compile.c +msgid "super() can't find self" msgstr "" #: py/compile.c -msgid "annotation must be an identifier" -msgstr "" +#, fuzzy +msgid "* arg after **" +msgstr "* 인수 뒤에 **" -#: extmod/ulab/code/numpy/create.c -msgid "arange: cannot compute length" +#: py/compile.c +msgid "* arg after kwarg" msgstr "" -#: py/modbuiltins.c -msgid "arg is an empty sequence" +#: py/compile.c +msgid "too many args" msgstr "" -#: py/objobject.c -msgid "arg must be user-type" -msgstr "" +#: py/compile.c +msgid "LHS of keyword arg must be an id" +msgstr "키워드 인수의 LHS 는 id 여야 합니다" -#: extmod/ulab/code/numpy/numerical.c -msgid "argsort argument must be an ndarray" +#: py/compile.c +msgid "positional arg after **" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "argsort is not implemented for flattened arrays" +#: py/compile.c +msgid "positional arg after keyword arg" msgstr "" -#: extmod/ulab/code/numpy/random/random.c -msgid "argument must be None, an integer or a tuple of integers" -msgstr "" +#: py/compile.c py/parse.c +msgid "invalid syntax" +msgstr "구문(syntax)가 유효하지 않습니다" #: py/compile.c -msgid "argument name reused" +msgid "expecting key:value for dict" msgstr "" -#: py/argcheck.c shared-bindings/_stage/__init__.c -#: shared-bindings/digitalio/DigitalInOut.c -msgid "argument num/types mismatch" +#: py/compile.c +msgid "expecting just a value for set" msgstr "" -#: extmod/ulab/code/numpy/numerical.c extmod/ulab/code/numpy/transform.c -msgid "arguments must be ndarrays" -msgstr "" +#: py/compile.c +msgid "'yield' outside function" +msgstr "'yield' 는 함수 외부에 존재합니다" -#: extmod/ulab/code/ndarray.c -msgid "array and index length must be equal" -msgstr "" +#: py/compile.c +#, fuzzy +msgid "'yield from' inside async function" +msgstr "비동기 함수 내 'yield from'" -#: extmod/ulab/code/numpy/io/io.c -msgid "array has too many dimensions" -msgstr "" +#: py/compile.c +msgid "'await' outside function" +msgstr "'await' 는 펑크션 외부에 있습니다" -#: extmod/ulab/code/ndarray.c -msgid "array is too big" +#: py/compile.c +msgid "unknown type '%q'" msgstr "" -#: py/objarray.c shared-bindings/alarm/SleepMemory.c -#: shared-bindings/memorymap/AddressRange.c shared-bindings/nvm/ByteArray.c -msgid "array/bytes required on right side" +#: py/compile.c +msgid "annotation must be an identifier" msgstr "" -#: py/asmxtensa.c -msgid "asm overflow" +#: py/compile.c +msgid "argument name reused" msgstr "" #: py/compile.c -msgid "async for/with outside async function" +msgid "inline assembler must be a function" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "attempt to get (arg)min/(arg)max of empty sequence" +#: py/compile.c +msgid "unknown type" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "attempt to get argmin/argmax of an empty sequence" +#: py/compile.c +msgid "return annotation must be an identifier" msgstr "" -#: py/objstr.c -msgid "attributes not supported" +#: py/compile.c +msgid "expecting an assembler instruction" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "audio format not supported" -msgstr "" +#: py/compile.c +msgid "'label' requires 1 argument" +msgstr "'label' 에는 1 개의 독립변수가 필요합니다" -#: extmod/ulab/code/ulab_tools.c -msgid "axis is out of bounds" +#: py/compile.c +msgid "label redefined" msgstr "" -#: extmod/ulab/code/numpy/numerical.c extmod/ulab/code/ulab_tools.c -msgid "axis must be None, or an integer" -msgstr "" +#: py/compile.c +msgid "'align' requires 1 argument" +msgstr "'align' 에는 1 개의 독립변수가 필요합니다" -#: extmod/ulab/code/numpy/numerical.c -msgid "axis too long" -msgstr "" +#: py/compile.c +msgid "'data' requires at least 2 arguments" +msgstr "'data' 에는 >=2 개의 독립변수가 필요합니다" -#: shared-bindings/bitmaptools/__init__.c -msgid "background value out of range of target" -msgstr "" +#: py/compile.c +#, fuzzy +msgid "'data' requires integer arguments" +msgstr "'data' 에는 정수 인수가 필요합니다" -#: py/builtinevex.c -msgid "bad compile mode" +#: py/compile.c +msgid "cannot emit native code for this architecture" msgstr "" -#: py/objstr.c -msgid "bad conversion specifier" +#: py/emitbc.c +msgid "bytecode overflow" msgstr "" -#: py/objstr.c -msgid "bad format string" +#: py/emitinlinerv32.c +msgid "can only have up to 4 parameters for RV32 assembly" msgstr "" -#: py/binary.c py/objarray.c -msgid "bad typecode" +#: py/emitinlinerv32.c +msgid "parameters must be registers in sequence a0 to a3" msgstr "" -#: py/emitnative.c -msgid "binary op %q not implemented" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: expecting %q" msgstr "" -#: ports/espressif/common-hal/audiobusio/PDMIn.c -msgid "bit_depth must be 8, 16, 24, or 32." +#: py/emitinlinerv32.c +msgid "opcode '%q': expecting %d arguments" msgstr "" -#: shared-module/bitmapfilter/__init__.c -msgid "bitmap size and depth must match" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: out of range" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "bitmap sizes must match" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: unknown register" msgstr "" -#: extmod/modrandom.c -msgid "bits must be 32 or less" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: undefined label '%q'" msgstr "" -#: shared-bindings/audiodelays/Echo.c shared-bindings/audiodelays/PitchShift.c -#: shared-bindings/audiofilters/Distortion.c -#: shared-bindings/audiofilters/Filter.c shared-bindings/audiomixer/Mixer.c -msgid "bits_per_sample must be 8 or 16" -msgstr "bits_per_sample은 8 또는 16이어야합니다." - -#: py/emitinlinethumb.c -msgid "branch not in range" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: must not be zero" msgstr "" -#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c -msgid "buffer is smaller than requested size" +#: py/emitinlinerv32.c +msgid "opcode '%q': registers must be different" msgstr "" -#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c -msgid "buffer size must be a multiple of element size" +#: py/emitinlinerv32.c +msgid "opcode '%q': malformed register list" msgstr "" -#: shared-module/struct/__init__.c -msgid "buffer size must match format" +#: py/emitinlinerv32.c +msgid "opcode '%q': invalid stack adjustment" msgstr "" -#: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c -msgid "buffer slices must be of equal length" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: wrong register(s)" msgstr "" -#: py/modstruct.c shared-module/struct/__init__.c -msgid "buffer too small" +#: py/emitinlinerv32.c +msgid "invalid RV32 instruction '%q'" msgstr "" -#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c -msgid "buffer too small for requested bytes" +#: py/emitinlinethumb.c +msgid "can only have up to 4 parameters to Thumb assembly" msgstr "" -#: py/emitbc.c -msgid "bytecode overflow" +#: py/emitinlinethumb.c +msgid "parameters must be registers in sequence r0 to r3" msgstr "" -#: py/objarray.c -msgid "bytes length not a multiple of item size" -msgstr "" +#: py/emitinlinethumb.c +#, fuzzy, c-format +msgid "'%s' expects at most r%d" +msgstr "'%s'는 최대 r%d를 필요로 합니다" -#: py/objstr.c -msgid "bytes value out of range" -msgstr "" +#: py/emitinlinethumb.c py/emitinlinextensa.c +#, c-format +msgid "'%s' expects a register" +msgstr "'%s' 에는 레지스터가 필요합니다" -#: ports/atmel-samd/bindings/samd/Clock.c -msgid "calibration is out of range" -msgstr "" +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' expects a special register" +msgstr "'%s' 에는 특별한 레지스터가 필요합니다" -#: ports/atmel-samd/bindings/samd/Clock.c -msgid "calibration is read only" -msgstr "" +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' expects an FPU register" +msgstr "'%s' 에는 FPU레지스터가 필요합니다" -#: shared-module/vectorio/Circle.c shared-module/vectorio/Polygon.c -#: shared-module/vectorio/Rectangle.c -msgid "can only have one parent" -msgstr "" +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' expects {r0, r1, ...}" +msgstr "'%s' {r0, r1, ...}은 을 기대합니다" + +#: py/emitinlinethumb.c py/emitinlinextensa.c +#, c-format +msgid "'%s' expects an integer" +msgstr "'%s' 는 정수 여야합니다" #: py/emitinlinethumb.c -msgid "can only have up to 4 parameters to Thumb assembly" -msgstr "" +#, fuzzy, c-format +msgid "'%s' integer 0x%x doesn't fit in mask 0x%x" +msgstr "'%s' 정수 0x%x 이 마스크 0x%x에 맞지 않습니다" -#: py/emitinlinextensa.c -msgid "can only have up to 4 parameters to Xtensa assembly" -msgstr "" +#: py/emitinlinethumb.c +#, fuzzy, c-format +msgid "'%s' expects an address of the form [a, b]" +msgstr "'%s' 에는 [a, b] 형식의 주소가 필요합니다" -#: extmod/ulab/code/ndarray.c -msgid "can only specify one unknown dimension" +#: py/emitinlinethumb.c py/emitinlinextensa.c +#, c-format +msgid "'%s' expects a label" +msgstr "'%s' 에는 라벨이 필요합니다" + +#: py/emitinlinethumb.c py/emitinlinextensa.c +msgid "label '%q' not defined" msgstr "" -#: py/objtype.c -msgid "can't add special method to already-subclassed class" +#: py/emitinlinethumb.c +#, c-format +msgid "unsupported Thumb instruction '%s' with %d arguments" msgstr "" -#: py/compile.c -msgid "can't assign to expression" +#: py/emitinlinethumb.c +msgid "branch not in range" msgstr "" -#: extmod/modasyncio.c -msgid "can't cancel self" +#: py/emitinlinextensa.c +msgid "can only have up to 4 parameters to Xtensa assembly" msgstr "" -#: py/obj.c shared-module/adafruit_pixelbuf/PixelBuf.c -msgid "can't convert %q to %q" +#: py/emitinlinextensa.c +msgid "parameters must be registers in sequence a2 to a5" msgstr "" -#: py/obj.c +#: py/emitinlinextensa.c #, fuzzy, c-format -msgid "can't convert %s to complex" -msgstr "%s 를 복합어로 변환할 수 없습니다" +msgid "'%s' integer %d isn't within range %d..%d" +msgstr "'%s' 정수 %d가 %d..%d 범위 내에 있지 않습니다" -#: py/obj.c +#: py/emitinlinextensa.c #, c-format -msgid "can't convert %s to float" +msgid "%d is not a multiple of %d" msgstr "" -#: py/objint.c py/runtime.c +#: py/emitinlinextensa.c #, c-format -msgid "can't convert %s to int" -msgstr "" - -#: py/objstr.c -msgid "can't convert '%q' object to %q implicitly" -msgstr "" - -#: extmod/ulab/code/numpy/vector.c -msgid "can't convert complex to float" +msgid "unsupported Xtensa instruction '%s' with %d arguments" msgstr "" -#: py/obj.c -msgid "can't convert to complex" +#: py/emitnative.c +msgid "conversion to object" msgstr "" -#: py/obj.c -msgid "can't convert to float" +#: py/emitnative.c +msgid "local '%q' used before type known" msgstr "" -#: py/runtime.c -msgid "can't convert to int" +#: py/emitnative.c +msgid "can't load from '%q'" msgstr "" -#: py/objstr.c -msgid "can't convert to str implicitly" +#: py/emitnative.c +msgid "can't load with '%q' index" msgstr "" -#: py/compile.c -msgid "can't declare nonlocal in outer code" +#: py/emitnative.c +msgid "local '%q' has type '%q' but source is '%q'" msgstr "" - -#: py/compile.c -msgid "can't delete expression" + +#: py/emitnative.c +msgid "can't store '%q'" msgstr "" #: py/emitnative.c -msgid "can't do binary op between '%q' and '%q'" +msgid "can't store to '%q'" msgstr "" #: py/emitnative.c -msgid "can't do unary op of '%q'" +msgid "can't store with '%q' index" msgstr "" #: py/emitnative.c msgid "can't implicitly convert '%q' to 'bool'" msgstr "" -#: py/runtime.c -msgid "can't import name %q" +#: py/emitnative.c +msgid "'not' not implemented" msgstr "" #: py/emitnative.c -msgid "can't load from '%q'" +msgid "can't do unary op of '%q'" msgstr "" #: py/emitnative.c -msgid "can't load with '%q' index" +msgid "div/mod not implemented for uint" msgstr "" -#: py/builtinimport.c -msgid "can't perform relative import" +#: py/emitnative.c +msgid "comparison of int and uint" msgstr "" -#: py/objgenerator.c -msgid "can't send non-None value to a just-started generator" +#: py/emitnative.c +msgid "binary op %q not implemented" msgstr "" -#: shared-module/sdcardio/SDCard.c -msgid "can't set 512 block size" +#: py/emitnative.c +msgid "can't do binary op between '%q' and '%q'" msgstr "" -#: py/objexcept.c py/objnamedtuple.c -msgid "can't set attribute" +#: py/emitnative.c +msgid "casting" msgstr "" -#: py/runtime.c -msgid "can't set attribute '%q'" +#: py/emitnative.c +msgid "return expected '%q' but got '%q'" msgstr "" #: py/emitnative.c -msgid "can't store '%q'" +msgid "native raise" msgstr "" #: py/emitnative.c -msgid "can't store to '%q'" +msgid "must raise an object" msgstr "" #: py/emitnative.c -msgid "can't store with '%q' index" +msgid "native yield" msgstr "" -#: py/objstr.c -msgid "" -"can't switch from automatic field numbering to manual field specification" +#: py/lexer.c +msgid "unicode name escapes" msgstr "" -#: py/objstr.c -msgid "" -"can't switch from manual field specification to automatic field numbering" +#: py/modbuiltins.c py/objstr.c +msgid "char not in range(0x110000)" msgstr "" -#: py/objcomplex.c -msgid "can't truncate-divide a complex number" +#: py/modbuiltins.c +msgid "chr() arg not in range(256)" msgstr "" -#: extmod/modasyncio.c -msgid "can't wait" +#: py/modbuiltins.c +msgid "arg is an empty sequence" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "cannot assign new shape" +#: py/modbuiltins.c +msgid "ord expects a character" msgstr "" -#: extmod/ulab/code/ndarray_operators.c -msgid "cannot cast output with casting rule" +#: py/modbuiltins.c +#, c-format +msgid "ord() expected a character, but string of length %d found" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "cannot convert complex to dtype" +#: py/modbuiltins.c +msgid "3-arg pow() not supported" +msgstr "pow() 는 3개의 인수를 지원하지 않습니다" + +#: py/modbuiltins.c +msgid "must use keyword argument for key function" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "cannot convert complex type" +#: py/moderrno.c +#, fuzzy +msgid "Operation not permitted" +msgstr "작업이 허용되지 않습니다" + +#: py/moderrno.c +msgid "No such file/directory" +msgstr "해당 파일/디렉토리가 없습니다" + +#: py/moderrno.c +msgid "Input/output error" +msgstr "입력/출력 오류" + +#: py/moderrno.c +msgid "Permission denied" +msgstr "권한이 거부 되었습니다" + +#: py/moderrno.c +msgid "File exists" +msgstr "파일이 있습니다" + +#: py/moderrno.c +msgid "No such device" +msgstr "해당 장치가 없습니다" + +#: py/moderrno.c +msgid "No space left on device" +msgstr "장치에 남은 공간이 없습니다" + +#: py/modmath.c shared-bindings/math/__init__.c +msgid "math domain error" msgstr "" -#: py/objtype.c -msgid "cannot create '%q' instances" +#: py/modmath.c +msgid "negative factorial" msgstr "" -#: py/objtype.c -msgid "cannot create instance" +#: py/modmicropython.c +msgid "schedule queue full" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "cannot delete array elements" +#: py/modstruct.c shared-bindings/picogame/Bitmap.c +#: shared-bindings/picogame/Canvas.c shared-bindings/picogame/Framebuffer.c +#: shared-module/picogame/__init__.c shared-module/struct/__init__.c +msgid "buffer too small" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "cannot reshape array" +#: py/modstruct.c +#, c-format +msgid "pack expected %d items for packing (got %d)" msgstr "" -#: py/emitnative.c -msgid "casting" +#: py/modthread.c +msgid "expecting a dict for keyword args" +msgstr "사전(dict)이 예상되었습니다" + +#: py/modweakref.c +msgid "not a heap object" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "channel re-init" +#: py/nativeglue.c +msgid "set unsupported" msgstr "" -#: shared-bindings/_stage/Text.c -msgid "chars buffer too small" +#: py/nativeglue.c +msgid "slice unsupported" msgstr "" -#: py/modbuiltins.c -msgid "chr() arg not in range(0x110000)" +#: py/nativeglue.c +msgid "float unsupported" msgstr "" -#: py/modbuiltins.c -msgid "chr() arg not in range(256)" +#: py/obj.c shared-module/adafruit_pixelbuf/PixelBuf.c +msgid "can't convert %q to %q" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "clip point must be (x,y) tuple" +#: py/obj.c +msgid "During handling of the above exception, another exception occurred:" +msgstr "위 예외를 처리하는 동안, 또 다른 예외가 발생하였습니다:" + +#: py/obj.c +msgid "The above exception was the direct cause of the following exception:" msgstr "" -#: shared-bindings/msgpack/ExtType.c -msgid "code outside range 0~127" +#: py/obj.c +msgid " File \"%q\", line %d" +msgstr " 파일 \"%q\", 라인 %d" + +#: py/obj.c +msgid " File \"%q\"" +msgstr " 파일 \"%q\"" + +#: py/obj.c +msgid ", in %q\n" +msgstr ", 에서 %q\n" + +#: py/obj.c +msgid "Traceback (most recent call last):\n" msgstr "" -#: shared-bindings/displayio/Palette.c -msgid "color buffer must be 3 bytes (RGB) or 4 bytes (RGB + pad byte)" +#: py/obj.c +msgid "can't convert to float" msgstr "" -#: shared-bindings/displayio/Palette.c -msgid "color buffer must be a buffer, tuple, list, or int" +#: py/obj.c +#, c-format +msgid "can't convert %s to float" msgstr "" -#: shared-bindings/displayio/Palette.c -msgid "color buffer must be a bytearray or array of type 'b' or 'B'" +#: py/obj.c +msgid "can't convert to complex" msgstr "" -#: shared-bindings/displayio/Palette.c -msgid "color must be between 0x000000 and 0xffffff" +#: py/obj.c +#, fuzzy, c-format +msgid "can't convert %s to complex" +msgstr "%s 를 복합어로 변환할 수 없습니다" + +#: py/obj.c +msgid "expected tuple/list" +msgstr "튜플(tuple) 또는 리스트(list)이 예상되었습니다" + +#: py/obj.c +#, c-format +msgid "object '%s' isn't a tuple or list" msgstr "" -#: py/emitnative.c -msgid "comparison of int and uint" +#: py/obj.c +msgid "tuple/list has wrong length" msgstr "" -#: py/objcomplex.c -msgid "complex divide by zero" +#: py/obj.c +#, c-format +msgid "requested length %d but object has length %d" msgstr "" -#: py/objfloat.c py/parsenum.c -msgid "complex values not supported" +#: py/obj.c +msgid "indices must be integers" msgstr "" -#: extmod/modzlib.c -msgid "compression header" +#: py/obj.c +msgid "%q indices must be integers, not %s" +msgstr "%q 인덱스는 %s 가 아닌 정수 여야합니다" + +#: py/obj.c +msgid "object has no len" msgstr "" -#: py/emitnative.c -msgid "conversion to object" +#: py/obj.c +#, c-format +msgid "object of type '%s' has no len()" msgstr "" -#: extmod/ulab/code/numpy/filter.c -msgid "convolve arguments must be linear arrays" +#: py/obj.c +msgid "object doesn't support item deletion" msgstr "" -#: extmod/ulab/code/numpy/filter.c -msgid "convolve arguments must be ndarrays" +#: py/obj.c +#, fuzzy, c-format +msgid "'%s' object doesn't support item deletion" +msgstr "'%s' 개체가 항목 삭제를 지원하지 않습니다" + +#: py/obj.c +msgid "object isn't subscriptable" msgstr "" -#: extmod/ulab/code/numpy/filter.c -msgid "convolve arguments must not be empty" +#: py/obj.c +#, c-format +msgid "'%s' object isn't subscriptable" +msgstr "'%s' 개체를 subscriptable 할 수 없습니다" + +#: py/obj.c +msgid "object doesn't support item assignment" msgstr "" -#: extmod/ulab/code/numpy/io/io.c -msgid "corrupted file" +#: py/obj.c +#, fuzzy, c-format +msgid "'%s' object doesn't support item assignment" +msgstr "'%s' 개체가 항목 할당을 지원하지 않습니다" + +#: py/obj.c +msgid "object with buffer protocol required" msgstr "" -#: extmod/ulab/code/numpy/poly.c -msgid "could not invert Vandermonde matrix" +#: py/objarray.c +msgid "bytes length not a multiple of item size" +msgstr "" + +#: py/objarray.c py/objstr.c +msgid "string argument without an encoding" msgstr "" -#: shared-module/sdcardio/SDCard.c -msgid "couldn't determine SD card version" +#: py/objarray.c +msgid "memoryview: length is not a multiple of itemsize" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "cross is defined for 1D arrays of length 3" +#: py/objarray.c py/objstr.c +msgid "substring not found" msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "data must be iterable" +#: py/objarray.c py/objstr.c py/objstrunicode.c py/objtuple.c +#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c +#: shared-bindings/nvm/ByteArray.c +msgid "only slices with step=1 (aka None) are supported" msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "data must be of equal length" +#: py/objarray.c +msgid "lhs and rhs should be compatible" msgstr "" -#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c -#, c-format -msgid "data pin #%d in use" +#: py/objarray.c shared-bindings/alarm/SleepMemory.c +#: shared-bindings/memorymap/AddressRange.c shared-bindings/nvm/ByteArray.c +msgid "array/bytes required on right side" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "data type not understood" +#: py/objarray.c +msgid "memoryview offset too large" msgstr "" -#: py/parsenum.c -msgid "decimal numbers not supported" +#: py/objcomplex.c +msgid "can't truncate-divide a complex number" msgstr "" -#: py/compile.c -msgid "default 'except' must be last" +#: py/objcomplex.c +msgid "complex divide by zero" msgstr "" -#: shared-bindings/msgpack/__init__.c -msgid "default is not a function" +#: py/objcomplex.c +msgid "0.0 to a complex power" msgstr "" -#: shared-bindings/audiobusio/PDMIn.c -msgid "" -"destination buffer must be a bytearray or array of type 'B' for bit_depth = 8" -msgstr "" +#: py/objdeque.c +msgid "full" +msgstr "완전한(full)" -#: shared-bindings/audiobusio/PDMIn.c -msgid "destination buffer must be an array of type 'H' for bit_depth = 16" +#: py/objdeque.c +msgid "empty" msgstr "" #: py/objdict.c msgid "dict update sequence has wrong length" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "diff argument must be an ndarray" +#: py/objexcept.c py/objnamedtuple.c +msgid "can't set attribute" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "differentiation order out of range" +#: py/objfloat.c py/parsenum.c +msgid "complex values not supported" msgstr "" -#: extmod/ulab/code/numpy/transform.c -msgid "dimensions do not match" +#: py/objgenerator.c +msgid "generator already executing" msgstr "" -#: py/emitnative.c -msgid "div/mod not implemented for uint" +#: py/objgenerator.c +msgid "can't send non-None value to a just-started generator" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "divide by zero" +#: py/objgenerator.c py/runtime.c +msgid "generator raised StopIteration" msgstr "" -#: py/runtime.c -msgid "division by zero" +#: py/objgenerator.c +msgid "generator ignored GeneratorExit" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "dtype must be float, or complex" +#: py/objint.c py/runtime.c +#, c-format +msgid "can't convert %s to int" msgstr "" -#: extmod/ulab/code/ndarray_operators.c -msgid "dtype of int32 is not supported" -msgstr "" +#: py/objint.c +msgid "float too big" +msgstr "float이 너무 큽니다" -#: py/objdeque.c -msgid "empty" +#: py/objint.c shared-bindings/time/__init__.c +msgid "No long integer support" +msgstr "긴 정수 지원이 없습니다" + +#: py/objint.c py/sequence.c +msgid "small int overflow" msgstr "" -#: extmod/ulab/code/numpy/io/io.c -msgid "empty file" +#: py/objint.c shared-bindings/_bleio/Connection.c +#: shared-bindings/storage/__init__.c +msgid "%q=%q" +msgstr "%q=%q" + +#: py/objint_impl.h +#, c-format +msgid "value would overflow a %d byte buffer" msgstr "" -#: extmod/modasyncio.c extmod/modheapq.c -msgid "empty heap" +#: py/objint_impl.h +msgid "can't convert negative int to unsigned" msgstr "" -#: py/objstr.c -msgid "empty separator" +#: py/objint_longlong.c py/parsenum.c +msgid "result overflows long long storage" msgstr "" -#: shared-bindings/random/__init__.c -msgid "empty sequence" +#: py/objint_longlong.c py/objint_mpz.c py/runtime.c +msgid "negative shift count" msgstr "" -#: py/objstr.c -msgid "end of format while looking for conversion specifier" +#: py/objint_longlong.c py/objint_mpz.c py/runtime.c +msgid "negative power with no float support" msgstr "" -#: shared-bindings/alarm/time/TimeAlarm.c -msgid "epoch_time not supported on this board" +#: py/objint_longlong.c py/objint_mpz.c +msgid "overflow converting long int to machine word" msgstr "" -#: ports/nordic/common-hal/busio/UART.c -#, c-format -msgid "error = 0x%08lX" +#: py/objint_mpz.c +msgid "pow() with 3 arguments requires integers" msgstr "" -#: py/runtime.c -msgid "exceptions must derive from BaseException" +#: py/objint_mpz.c +msgid "pow() 3rd argument cannot be 0" msgstr "" -#: py/objstr.c -msgid "expected ':' after format specifier" -msgstr "':'이 예상되었습니다" +#: py/objobject.c +msgid "__new__ arg must be a user-type" +msgstr "" -#: py/obj.c -msgid "expected tuple/list" -msgstr "튜플(tuple) 또는 리스트(list)이 예상되었습니다" +#: py/objobject.c +msgid "arg must be user-type" +msgstr "" -#: py/modthread.c -msgid "expecting a dict for keyword args" -msgstr "사전(dict)이 예상되었습니다" +#: py/objrange.c py/objslice.c shared-bindings/random/__init__.c +#, fuzzy +msgid "%q step cannot be zero" +msgstr "%q 단계는 0일 수 없습니다" -#: py/compile.c -msgid "expecting an assembler instruction" +#: py/objslice.c +msgid "Cannot subclass slice" msgstr "" -#: py/compile.c -msgid "expecting just a value for set" +#: py/objstr.c +msgid "unknown encoding: %q" msgstr "" -#: py/compile.c -msgid "expecting key:value for dict" +#: py/objstr.c +msgid "bytes value out of range" msgstr "" -#: shared-bindings/msgpack/__init__.c -msgid "ext_hook is not a function" +#: py/objstr.c +msgid "join expects a list of str/bytes objects consistent with self object" msgstr "" -#: py/argcheck.c -msgid "extra keyword arguments given" +#: py/objstr.c +msgid "empty separator" msgstr "" -#: py/argcheck.c -msgid "extra positional arguments given" +#: py/objstr.c +msgid "rsplit(None,n)" msgstr "" -#: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/gifio/OnDiskGif.c -#: shared-bindings/synthio/__init__.c shared-module/gifio/GifWriter.c -msgid "file must be a file opened in byte mode" +#: py/objstr.c +msgid "bad format string" msgstr "" -#: shared-bindings/traceback/__init__.c -msgid "file write is not available" +#: py/objstr.c +#, c-format +msgid "unmatched '%c' in format" msgstr "" -#: shared-bindings/storage/__init__.c -msgid "filesystem must provide mount method" +#: py/objstr.c +msgid "bad conversion specifier" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "first argument must be a callable" +#: py/objstr.c +msgid "end of format while looking for conversion specifier" msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "first argument must be a function" +#: py/objstr.c +#, c-format +msgid "unknown conversion specifier %c" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "first argument must be a tuple of ndarrays" +#: py/objstr.c +msgid "expected ':' after format specifier" +msgstr "':'이 예상되었습니다" + +#: py/objstr.c +msgid "" +"can't switch from automatic field numbering to manual field specification" msgstr "" -#: extmod/ulab/code/numpy/transform.c extmod/ulab/code/numpy/vector.c -msgid "first argument must be an ndarray" +#: py/objstr.c +msgid "%q index out of range" +msgstr "%q 인덱스 범위를 벗어났습니다" + +#: py/objstr.c +msgid "attributes not supported" msgstr "" -#: py/objtype.c -msgid "first argument to super() must be type" +#: py/objstr.c +msgid "" +"can't switch from manual field specification to automatic field numbering" msgstr "" -#: extmod/ulab/code/scipy/linalg/linalg.c -msgid "first two arguments must be ndarrays" +#: py/objstr.c +msgid "invalid format specifier" +msgstr "형식 지정자(format specifier)가 유효하지 않습니다" + +#: py/objstr.c +msgid "sign not allowed in string format specifier" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "flattening order must be either 'C', or 'F'" +#: py/objstr.c +msgid "sign not allowed with integer format specifier 'c'" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "flip argument must be an ndarray" +#: py/objstr.c +msgid "unknown format code '%c' for object of type '%q'" msgstr "" -#: py/objint.c -msgid "float too big" -msgstr "float이 너무 큽니다" +#: py/objstr.c +#, fuzzy +msgid "'=' alignment not allowed in string format specifier" +msgstr "'=' 문자열 형식 지정자에서 정렬이 허용되지 않습니다" -#: py/nativeglue.c -msgid "float unsupported" +#: py/objstr.c +msgid "format needs a dict" msgstr "" -#: shared-bindings/_stage/Text.c -msgid "font must be 2048 bytes long" +#: py/objstr.c +msgid "incomplete format key" msgstr "" -#: extmod/moddeflate.c -msgid "format" +#: py/objstr.c +msgid "incomplete format" msgstr "" #: py/objstr.c -msgid "format requires a dict" +msgid "format string needs more arguments" msgstr "" -#: py/objdeque.c -msgid "full" -msgstr "완전한(full)" - -#: py/argcheck.c -msgid "function doesn't take keyword arguments" +#: py/objstr.c +#, c-format +msgid "%%c needs int or char" msgstr "" -#: py/argcheck.c +#: py/objstr.c #, c-format -msgid "function expected at most %d arguments, got %d" +msgid "unsupported format character '%c' (0x%x) at index %d" msgstr "" -#: py/bc.c py/objnamedtuple.c -msgid "function got multiple values for argument '%q'" +#: py/objstr.c +msgid "format string didn't convert all arguments" msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "function has the same sign at the ends of interval" +#: py/objstr.c +msgid "non-hex digit" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "function is defined for ndarrays only" +#: py/objstr.c +msgid "can't convert to str implicitly" msgstr "" -#: extmod/ulab/code/numpy/carray/carray.c -msgid "function is implemented for ndarrays only" +#: py/objstr.c +msgid "can't convert '%q' object to %q implicitly" msgstr "" -#: py/argcheck.c +#: py/objstrunicode.c #, c-format -msgid "function missing %d required positional arguments" +msgid "string indices must be integers, not %s" msgstr "" -#: py/bc.c -msgid "function missing keyword-only argument" +#: py/objstrunicode.c +msgid "string index out of range" msgstr "" -#: py/bc.c -msgid "function missing required keyword argument '%q'" +#: py/objtemplate.c +msgid "expected str or Interpolation" msgstr "" -#: py/bc.c -#, c-format -msgid "function missing required positional argument #%d" +#: py/objtype.c +msgid "Call super().__init__() before accessing native object." +msgstr "네이티브 개체에 액세스하기 전에 super().__init__()를 호출하십시오." + +#: py/objtype.c +msgid "__init__() should return None" msgstr "" -#: py/argcheck.c py/bc.c py/objnamedtuple.c shared-bindings/_eve/__init__.c -#: shared-bindings/time/__init__.c +#: py/objtype.c #, c-format -msgid "function takes %d positional arguments but %d were given" +msgid "__init__() should return None, not '%s'" msgstr "" -#: py/objgenerator.c -msgid "generator already executing" +#: py/objtype.c py/runtime.c +msgid "unreadable attribute" msgstr "" -#: py/objgenerator.c -msgid "generator ignored GeneratorExit" +#: py/objtype.c py/runtime.c +msgid "object not callable" msgstr "" -#: py/objgenerator.c py/runtime.c -msgid "generator raised StopIteration" +#: py/objtype.c py/runtime.c shared-module/atexit/__init__.c +msgid "'%q' object isn't callable" msgstr "" -#: shared-bindings/_stage/Layer.c -msgid "graphic must be 2048 bytes long" +#: py/objtype.c +msgid "type takes 1 or 3 arguments" msgstr "" -#: extmod/modhashlib.c -msgid "hash is final" +#: py/objtype.c +msgid "can't create instance" msgstr "" -#: extmod/modheapq.c -msgid "heap must be a list" +#: py/objtype.c +msgid "can't create '%q' instances" msgstr "" -#: py/compile.c -msgid "identifier redefined as global" +#: py/objtype.c +msgid "can't add special method to already-subclassed class" msgstr "" -#: py/compile.c -msgid "identifier redefined as nonlocal" +#: py/objtype.c +msgid "type isn't an acceptable base type" msgstr "" -#: py/compile.c -msgid "import * not at module level" +#: py/objtype.c +msgid "type '%q' isn't an acceptable base type" msgstr "" -#: py/persistentcode.c -msgid "incompatible .mpy arch" +#: py/objtype.c +msgid "multiple inheritance not supported" msgstr "" -#: py/persistentcode.c -msgid "incompatible .mpy file" +#: py/objtype.c +msgid "multiple bases have instance lay-out conflict" msgstr "" -#: py/objstr.c -msgid "incomplete format" +#: py/objtype.c +msgid "first argument to super() must be type" msgstr "" -#: py/objstr.c -msgid "incomplete format key" +#: py/objtype.c +msgid "issubclass() arg 2 must be a class or a tuple of classes" msgstr "" -#: extmod/modbinascii.c -msgid "incorrect padding" +#: py/objtype.c +msgid "issubclass() arg 1 must be a class" msgstr "" -#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/transform.c -msgid "index is out of bounds" +#: py/parse.c +msgid "not a constant" msgstr "" -#: shared-bindings/_pixelmap/PixelMap.c -msgid "index must be tuple or int" -msgstr "" +#: py/parse.c +msgid "Unable to init parser" +msgstr "파서를 초기화(init) 할 수 없습니다" -#: extmod/ulab/code/numpy/numerical.c extmod/ulab/code/ulab_tools.c -#: ports/espressif/common-hal/pulseio/PulseIn.c -#: shared-bindings/bitmaptools/__init__.c -msgid "index out of range" +#: py/parse.c +msgid "unexpected indent" msgstr "" -#: py/obj.c -msgid "indices must be integers" +#: py/parse.c +msgid "unindent doesn't match any outer indent level" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "indices must be integers, slices, or Boolean lists" +#: py/parse.c +msgid "malformed f-string" msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "initial values must be iterable" +#: py/parsenum.c +msgid "invalid syntax for integer" +msgstr "구문(syntax)가 정수가 유효하지 않습니다" + +#: py/parsenum.c +#, c-format +msgid "invalid syntax for integer with base %d" +msgstr "구문(syntax)가 정수가 유효하지 않습니다" + +#: py/parsenum.c +msgid "invalid syntax for number" +msgstr "숫자에 대한 구문(syntax)가 유효하지 않습니다" + +#: py/parsenum.c +msgid "decimal numbers not supported" msgstr "" -#: shared-bindings/_bleio/Characteristic.c shared-bindings/_bleio/Descriptor.c -msgid "initial_value length is wrong" +#: py/persistentcode.c +msgid "incompatible .mpy file" msgstr "" -#: py/compile.c -msgid "inline assembler must be a function" +#: py/persistentcode.c +msgid "MicroPython .mpy file; use CircuitPython mpy-cross" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "input and output dimensions differ" +#: py/persistentcode.c +msgid "native code in .mpy unsupported" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "input and output shapes differ" +#: py/persistentcode.c +msgid "incompatible .mpy arch" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "input argument must be an integer, a tuple, or a list" +#: py/persistentcode.c +msgid "function must be bytecode" msgstr "" -#: extmod/ulab/code/numpy/fft/fft_tools.c -msgid "input array length must be power of 2" +#: py/proto.c shared-bindings/digitalio/DigitalInOutProtocol.c +msgid "'%q' object does not support '%q'" +msgstr "'%q' 개체가 '%q'를 지원하지 않습니다" + +#: py/qstr.c +msgid "name too long" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "input arrays are not compatible" +#: py/runtime.c +msgid "name not defined" msgstr "" -#: extmod/ulab/code/numpy/poly.c -msgid "input data must be an iterable" +#: py/runtime.c +msgid "name '%q' isn't defined" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "input dtype must be float or complex" +#: py/runtime.c +msgid "unsupported type for operator" msgstr "" -#: extmod/ulab/code/numpy/poly.c -msgid "input is not iterable" +#: py/runtime.c +msgid "unsupported type for %q: '%s'" msgstr "" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "input matrix is asymmetric" +#: py/runtime.c +msgid "unsupported types for %q: '%q', '%q'" msgstr "" -#: extmod/ulab/code/numpy/linalg/linalg.c -#: extmod/ulab/code/scipy/linalg/linalg.c -msgid "input matrix is singular" +#: py/runtime.c +msgid "wrong number of values to unpack" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "input must be 1- or 2-d" +#: py/runtime.c +#, c-format +msgid "need more than %d values to unpack" msgstr "" -#: extmod/ulab/code/numpy/carray/carray.c -msgid "input must be a 1D ndarray" +#: py/runtime.c +#, c-format +msgid "too many values to unpack (expected %d)" msgstr "" -#: extmod/ulab/code/scipy/linalg/linalg.c extmod/ulab/code/user/user.c -msgid "input must be a dense ndarray" +#: py/runtime.c +msgid "type object '%q' has no attribute '%q'" msgstr "" -#: extmod/ulab/code/user/user.c shared-bindings/_eve/__init__.c -msgid "input must be an ndarray" +#: py/runtime.c +msgid "module '%q' has no attribute '%q'" msgstr "" -#: extmod/ulab/code/numpy/carray/carray.c -msgid "input must be an ndarray, or a scalar" +#: py/runtime.c +#, fuzzy +msgid "'%s' object has no attribute '%q'" +msgstr "'%s' 개체에 '%q' 특성이 없습니다" + +#: py/runtime.c +msgid "can't set attribute '%q'" msgstr "" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "input must be one-dimensional" +#: py/runtime.c +msgid "object not iterable" msgstr "" -#: extmod/ulab/code/ulab_tools.c -msgid "input must be square matrix" +#: py/runtime.c +msgid "'%q' object isn't iterable" +msgstr "'%q' 개체를 사용할 수 없습니다" + +#: py/runtime.c +msgid "object not an iterator" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "input must be tuple, list, range, or ndarray" +#: py/runtime.c +msgid "'%q' object isn't an iterator" +msgstr "'%q' 개체가 iterator가 아닙니다" + +#: py/runtime.c +msgid "exceptions must derive from BaseException" msgstr "" -#: extmod/ulab/code/numpy/poly.c -msgid "input vectors must be of equal length" +#: py/runtime.c +msgid "can't import name %q" msgstr "" -#: extmod/ulab/code/numpy/approx.c -msgid "interp is defined for 1D iterables of equal length" +#: py/runtime.c +msgid "memory allocation failed, heap is locked" msgstr "" -#: shared-bindings/_bleio/Adapter.c +#: py/runtime.c #, c-format -msgid "interval must be in range %s-%s" +msgid "memory allocation failed, allocating %u bytes" msgstr "" -#: py/compile.c -msgid "invalid arch" +#: py/runtime.c +msgid "can't convert to int" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -#, c-format -msgid "invalid bits_per_pixel %d, must be, 1, 2, 4, 8, 16, 24, or 32" +#: py/runtime.c +msgid "division by zero" msgstr "" -#: shared-module/ssl/SSLSocket.c -msgid "invalid cert" -msgstr "cert가 유효하지 않습니다" +#: py/runtime.c +msgid "maximum recursion depth exceeded" +msgstr "" -#: shared-bindings/bitmaptools/__init__.c -#, c-format -msgid "invalid element size %d for bits_per_pixel %d\n" +#: py/sequence.c shared-bindings/displayio/Group.c +msgid "object not in sequence" +msgstr "" + +#: py/stream.c shared-bindings/getpass/__init__.c +msgid "stream operation not supported" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -#, c-format -msgid "invalid element_size %d, must be, 1, 2, or 4" +#: py/vm.c +msgid "local variable referenced before assignment" msgstr "" -#: shared-bindings/traceback/__init__.c -msgid "invalid exception" +#: py/vm.c +msgid "no active exception to reraise" msgstr "" -#: py/objstr.c -msgid "invalid format specifier" -msgstr "형식 지정자(format specifier)가 유효하지 않습니다" +#: py/vm.c +msgid "opcode" +msgstr "" -#: shared-bindings/wifi/Radio.c -msgid "invalid hostname" +#: shared-bindings/_bleio/Adapter.c +msgid "Cannot create a new Adapter; use _bleio.adapter;" +msgstr "_bleio.adapter를 사용해서; 새로운 Adapter를 만들 수 없습니다;" + +#: shared-bindings/_bleio/Adapter.c +msgid "Could not set address" +msgstr "주소를 설정할 수 없습니다" + +#: shared-bindings/_bleio/Adapter.c +#, c-format +msgid "interval must be in range %s-%s" msgstr "" -#: shared-module/ssl/SSLSocket.c -msgid "invalid key" -msgstr "키가 유효하지 않습니다" +#: shared-bindings/_bleio/Adapter.c +msgid "Cannot have scan responses for extended, connectable advertisements." +msgstr "확장되고 연결 가능한 광고에 대한 검색 응답을 가질 수 없습니다." -#: py/compile.c -msgid "invalid micropython decorator" +#: shared-bindings/_bleio/Adapter.c +#, fuzzy +msgid "Only connectable advertisements can be directed" +msgstr "연결 가능한 광고만 지시할 수 있습니다" + +#: shared-bindings/_bleio/Adapter.c +msgid "non-zero timeout must be >= interval" msgstr "" -#: ports/espressif/common-hal/espcamera/Camera.c -msgid "invalid setting" +#: shared-bindings/_bleio/Adapter.c +msgid "window must be <= interval" msgstr "" -#: shared-bindings/random/__init__.c -msgid "invalid step" -msgstr "단계(step)가 유효하지 않습니다" +#: shared-bindings/_bleio/Adapter.c +#, fuzzy +msgid "Prefix buffer must be on the heap" +msgstr "앞의 버퍼는 힙에 있어야 합니다" -#: py/compile.c py/parse.c -msgid "invalid syntax" -msgstr "구문(syntax)가 유효하지 않습니다" +#: shared-bindings/_bleio/CharacteristicBuffer.c +msgid "CharacteristicBuffer writing not provided" +msgstr "CharacteristicBuffer 쓰기는 제공되지 않습니다" -#: py/parsenum.c -msgid "invalid syntax for integer" -msgstr "구문(syntax)가 정수가 유효하지 않습니다" +#: shared-bindings/_bleio/Connection.c +msgid "" +"Connection has been disconnected and can no longer be used. Create a new " +"connection." +msgstr "연결이 끊어져 더 이상 사용할 수 없습니다. 새로운 연결을 만드십시오." -#: py/parsenum.c +#: shared-bindings/_bleio/PacketBuffer.c #, c-format -msgid "invalid syntax for integer with base %d" -msgstr "구문(syntax)가 정수가 유효하지 않습니다" +msgid "Buffer too short by %d bytes" +msgstr "버퍼가 %d 바이트로 너무 짧습니다" -#: py/parsenum.c -msgid "invalid syntax for number" -msgstr "숫자에 대한 구문(syntax)가 유효하지 않습니다" +#: shared-bindings/_bleio/PacketBuffer.c +msgid "No connection: length cannot be determined" +msgstr "연결이 없습니다: 길이를 결정할 수 없습니다" -#: py/objtype.c -msgid "issubclass() arg 1 must be a class" -msgstr "" +#: shared-bindings/_bleio/UUID.c +msgid "UUID string not 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'" +msgstr "UUID문자열이 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'형식이 아닙니다" -#: py/objtype.c -msgid "issubclass() arg 2 must be a class or a tuple of classes" +#: shared-bindings/_bleio/UUID.c +msgid "UUID value is not str, int or byte buffer" msgstr "" +"UUID값이 문자열(str), 정수(int) 또는 바이트버퍼가(byte buffer) 아닙니다" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "iterations did not converge" +#: shared-bindings/_bleio/UUID.c +msgid "not a 128-bit UUID" msgstr "" -#: py/objstr.c -msgid "join expects a list of str/bytes objects consistent with self object" -msgstr "" +#: shared-bindings/_bleio/__init__.c shared-bindings/emmcio/EMMC.c +#: shared-bindings/memorymonitor/AllocationSize.c +#: shared-bindings/pulseio/PulseIn.c shared-module/bitmaptools/__init__.c +#: shared-module/displayio/legacy/Bitmap.c +#: shared-module/displayio/legacy/Group.c shared-module/displayio/lvgl/Bitmap.c +#: shared-module/displayio/lvgl/Group.c +msgid "Read-only" +msgstr "읽기 전용" -#: py/argcheck.c -msgid "keyword argument(s) not implemented - use normal args instead" -msgstr "" +#: shared-bindings/_pew/PewPew.c +msgid "Incorrect buffer size" +msgstr "잘못된 버퍼 크기" -#: py/emitinlinethumb.c py/emitinlinextensa.c -msgid "label '%q' not defined" +#: shared-bindings/_pixelmap/PixelMap.c +msgid "nested index must be int" msgstr "" -#: py/compile.c -msgid "label redefined" +#: shared-bindings/_pixelmap/PixelMap.c +msgid "index must be tuple or int" msgstr "" -#: py/objarray.c -msgid "lhs and rhs should be compatible" +#: shared-bindings/_stage/Layer.c +msgid "map buffer too small" msgstr "" -#: py/emitnative.c -msgid "local '%q' has type '%q' but source is '%q'" +#: shared-bindings/_stage/Text.c +msgid "chars buffer too small" msgstr "" -#: py/emitnative.c -msgid "local '%q' used before type known" -msgstr "" +#: shared-bindings/adafruit_bus_device/spi_device/SPIDevice.c +msgid "Pin is input only" +msgstr "핀은 입력 전용입니다" -#: py/vm.c -msgid "local variable referenced before assignment" +#: shared-bindings/adafruit_pixelbuf/PixelBuf.c +#: shared-module/_pixelmap/PixelMap.c +#, c-format +msgid "Unmatched number of items on RHS (expected %d, got %d)." msgstr "" -#: ports/espressif/common-hal/canio/CAN.c -msgid "loopback + silent mode not supported by peripheral" -msgstr "" +#: shared-bindings/aesio/aes.c +msgid "Key must be 16, 24, or 32 bytes long" +msgstr "키는 16, 24, 또는 32 바이트 길이여야 합니다" -#: ports/espressif/common-hal/mdns/Server.c -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "mDNS already initialized" +#: shared-bindings/aesio/aes.c +msgid "Requested AES mode is unsupported" msgstr "" -#: ports/espressif/common-hal/mdns/Server.c -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "mDNS only works with built-in WiFi" +#: shared-bindings/aesio/aes.c +msgid "Source and destination buffers must be the same length" msgstr "" -#: py/parse.c -msgid "malformed f-string" -msgstr "" +#: shared-bindings/aesio/aes.c +msgid "ECB only operates on 16 bytes at a time" +msgstr "ECB는 한 번에 16 바이트에서만 작동합니다" -#: shared-bindings/_stage/Layer.c -msgid "map buffer too small" -msgstr "" +#: shared-bindings/aesio/aes.c +msgid "CBC blocks must be multiples of 16 bytes" +msgstr "CBC 블록은 16 바이트의 배수여야 합니다" -#: py/modmath.c shared-bindings/math/__init__.c -msgid "math domain error" +#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c +#: shared-bindings/nvm/ByteArray.c +msgid "Slice and value different lengths." msgstr "" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "matrix is not positive definite" -msgstr "" +#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c +#: shared-bindings/nvm/ByteArray.c +#, fuzzy +msgid "Array values should be single bytes." +msgstr "배열 값은 1바이트 여야합니다." -#: ports/espressif/common-hal/_bleio/Descriptor.c -#: ports/nordic/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Descriptor.c -#, c-format -msgid "max_length must be 0-%d when fixed_length is %s" +#: shared-bindings/alarm/SleepMemory.c +msgid "Unable to write to sleep_memory." msgstr "" -#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/random/random.c -msgid "maximum number of dimensions is " +#: shared-bindings/alarm/__init__.c +msgid "Expected a kind of %q" +msgstr "%q 유형이 필요합니다" + +#: shared-bindings/alarm/time/TimeAlarm.c shared-bindings/time/__init__.c +msgid "RTC is not supported on this board" +msgstr "이 보드에서는 PTC가 지원되지 않습니다" + +#: shared-bindings/alarm/time/TimeAlarm.c +msgid "Supply one of monotonic_time or epoch_time" msgstr "" -#: py/runtime.c -msgid "maximum recursion depth exceeded" +#: shared-bindings/alarm/time/TimeAlarm.c +msgid "epoch_time not supported on this board" msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "maxiter must be > 0" +#: shared-bindings/alarm/time/TimeAlarm.c +msgid "Time is in the past." msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "maxiter should be > 0" +#: shared-bindings/analogbufio/BufferedIn.c +msgid "%q must be a bytearray or array of type 'H' or 'B'" +msgstr "%q는 'H' 또는 'B' 타입의 바이트 배열 또는 배열이어야 합니다" + +#: shared-bindings/audiobusio/PDMIn.c +msgid "%q must be multiple of 8." msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "median argument must be an ndarray" +#: shared-bindings/audiobusio/PDMIn.c shared-bindings/audioi2sin/I2SIn.c +#: shared-bindings/usb_host_audio/USBIn.c +msgid "Cannot record to a file" +msgstr "파일에 녹음 할 수 없습니다" + +#: shared-bindings/audiobusio/PDMIn.c shared-bindings/audioi2sin/I2SIn.c +#: shared-bindings/usb_host_audio/USBIn.c +msgid "Destination capacity is smaller than destination_length." +msgstr "대상 용량이 destination_length보다 작습니다." + +#: shared-bindings/audiobusio/PDMIn.c +msgid "destination buffer must be an array of type 'H' for bit_depth = 16" msgstr "" -#: py/runtime.c -#, c-format -msgid "memory allocation failed, allocating %u bytes" +#: shared-bindings/audiobusio/PDMIn.c +msgid "" +"destination buffer must be a bytearray or array of type 'B' for bit_depth = 8" msgstr "" -#: py/runtime.c -msgid "memory allocation failed, heap is locked" +#: shared-bindings/audiocore/RawSample.c +msgid "%q must be a bytearray or array of type 'h', 'H', 'b', or 'B'" +msgstr "%q는 h, H, b 또는 B 유형의 바이트 배열 또는 배열이어야 합니다" + +#: shared-bindings/audiocore/RawSample.c +msgid "Length of %q must be an even multiple of channel_count * type_size" msgstr "" -#: py/objarray.c -msgid "memoryview offset too large" +#: shared-bindings/audiodelays/Chorus.c shared-bindings/audiodelays/Echo.c +#: shared-bindings/audiodelays/Flanger.c +#: shared-bindings/audiodelays/GranularPitchShift.c +#: shared-bindings/audiodelays/MultiTapDelay.c +#: shared-bindings/audiodelays/PitchShift.c +#: shared-bindings/audiofilters/Distortion.c +#: shared-bindings/audiofilters/Filter.c shared-bindings/audiofilters/Phaser.c +#: shared-bindings/audiomixer/Mixer.c shared-module/audiotap/Tap.c +msgid "bits_per_sample must be 8 or 16" +msgstr "bits_per_sample은 8 또는 16이어야합니다" + +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "samples_signed must be true" msgstr "" -#: py/objarray.c -msgid "memoryview: length is not a multiple of itemsize" +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "bits_per_sample must be 16" msgstr "" -#: extmod/modtime.c -msgid "mktime needs a tuple of length 8 or 9" +#: shared-bindings/audioi2sin/I2SIn.c shared-bindings/usb_host_audio/USBIn.c +#, c-format +msgid "invalid destination buffer, must be an array of type: %c" msgstr "" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "mode must be complete, or reduced" +#: shared-bindings/audioio/AudioOut.c shared-bindings/emmcio/EMMC.c +msgid "%q and %q must be different" +msgstr "%q와 %q는 달라야 합니다" + +#: shared-bindings/audiomp3/MP3Decoder.c shared-bindings/gifio/OnDiskGif.c +#: shared-bindings/synthio/__init__.c shared-module/gifio/GifWriter.c +msgid "file must be a file opened in byte mode" msgstr "" -#: py/builtinimport.c -msgid "module not found" +#: shared-bindings/bitmapfilter/__init__.c +msgid "" +"weights must be a sequence with an odd square number of elements (usually 9 " +"or 25)" msgstr "" -#: ports/espressif/common-hal/wifi/Monitor.c -msgid "monitor init failed" +#: shared-bindings/bitmapfilter/__init__.c +msgid "weights must be an object of type %q, %q, %q, or %q, not %q " msgstr "" -#: extmod/ulab/code/numpy/poly.c -msgid "more degrees of freedom than data points" +#: shared-bindings/bitmaptools/__init__.c +msgid "clip point must be (x,y) tuple" msgstr "" -#: py/compile.c -msgid "multiple *x in assignment" +#: shared-bindings/bitmaptools/__init__.c +msgid "source palette too large" msgstr "" -#: py/objtype.c -msgid "multiple bases have instance lay-out conflict" -msgstr "" +#: shared-bindings/bitmaptools/__init__.c +msgid "Bitmap size and bits per value must match" +msgstr "비트맵 크기와 값 당 비트가 일치해야 합니다" -#: py/objtype.c -msgid "multiple inheritance not supported" -msgstr "" +#: shared-bindings/bitmaptools/__init__.c +msgid "For L8 colorspace, input bitmap must have 8 bits per pixel" +msgstr "L8 색상 공간의 경우, 입력 비트맵은 픽셀 당 8 비트를 가져야 합니다" -#: py/emitnative.c -msgid "must raise an object" -msgstr "" +#: shared-bindings/bitmaptools/__init__.c +msgid "For RGB colorspaces, input bitmap must have 16 bits per pixel" +msgstr "RGB 색상 공간의 경우, 입력 비트맵은 픽셀 당 16 비트를 가져야 합니다" -#: py/modbuiltins.c -msgid "must use keyword argument for key function" +#: shared-bindings/bitmaptools/__init__.c +msgid "Unsupported colorspace" msgstr "" -#: py/runtime.c -msgid "name '%q' is not defined" +#: shared-bindings/bitmaptools/__init__.c +msgid "Mask bitmap size must match the other bitmaps" msgstr "" -#: py/runtime.c -msgid "name not defined" +#: shared-bindings/bitmaptools/__init__.c +msgid "Mask bitmap must have 8 bits per pixel" msgstr "" -#: py/qstr.c -msgid "name too long" +#: shared-bindings/bitmaptools/__init__.c +msgid "out of range of target" msgstr "" -#: py/persistentcode.c -msgid "native code in .mpy unsupported" +#: shared-bindings/bitmaptools/__init__.c +msgid "value out of range of target" msgstr "" -#: py/asmthumb.c -msgid "native method too big" +#: shared-bindings/bitmaptools/__init__.c +msgid "background value out of range of target" msgstr "" -#: py/emitnative.c -msgid "native yield" -msgstr "" +#: shared-bindings/bitmaptools/__init__.c +msgid "Coordinate arrays types have different sizes" +msgstr "좌표 배열 유형은 크기가 다릅니다" -#: extmod/ulab/code/ndarray.c -msgid "ndarray length overflows" -msgstr "" +#: shared-bindings/bitmaptools/__init__.c +msgid "Coordinate arrays have different lengths" +msgstr "좌표 배열의 길이가 다릅니다" -#: py/runtime.c +#: shared-bindings/bitmaptools/__init__.c #, c-format -msgid "need more than %d values to unpack" +msgid "invalid element_size %d, must be, 1, 2, or 4" msgstr "" -#: py/modmath.c -msgid "negative factorial" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element size %d for bits_per_pixel %d\n" msgstr "" -#: py/objint_longlong.c py/objint_mpz.c py/runtime.c -msgid "negative power with no float support" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid bits_per_pixel %d, must be, 1, 2, 4, 8, 16, 24, or 32" msgstr "" -#: py/objint_mpz.c py/runtime.c -msgid "negative shift count" +#: shared-bindings/bitmaptools/__init__.c +msgid "bitmap sizes must match" msgstr "" -#: shared-bindings/_pixelmap/PixelMap.c -msgid "nested index must be int" +#: shared-bindings/bitmaptools/__init__.c +msgid "source_bitmap must have value_count of 2 or 65536" msgstr "" -#: shared-module/sdcardio/SDCard.c -msgid "no SD card" +#: shared-bindings/bitmaptools/__init__.c +msgid "source_bitmap must have value_count of 65536" msgstr "" -#: py/vm.c -msgid "no active exception to reraise" +#: shared-bindings/bitmaptools/__init__.c +msgid "source_bitmap must have value_count of 8" msgstr "" -#: py/compile.c -msgid "no binding for nonlocal found" +#: shared-bindings/bitmaptools/__init__.c +msgid "unsupported colorspace for dither" msgstr "" -#: shared-module/msgpack/__init__.c -msgid "no default packer" -msgstr "" +#: shared-bindings/bitops/__init__.c +#, fuzzy, c-format +msgid "Input buffer length (%d) must be a multiple of the strand count (%d)" +msgstr "입력 버퍼 길이 (%d) 는 스트랜드 수 (%d)의 배수여야 한다" -#: extmod/modrandom.c extmod/ulab/code/numpy/random/random.c -msgid "no default seed" -msgstr "" +#: shared-bindings/board/__init__.c +msgid "No default %q bus" +msgstr "기본 버스 %q가 없습니다" -#: py/builtinimport.c -msgid "no module named '%q'" -msgstr "" +#: shared-bindings/busdisplay/BusDisplay.c +msgid "%q must be 1 when %q is True" +msgstr "%q가 참일 때 %q는 1이어야 합니다" -#: shared-module/sdcardio/SDCard.c -msgid "no response from SD card" -msgstr "" +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +msgid "Display must have a 16 bit colorspace." +msgstr "디스플레이는 16 비트 색 공간을 가져야 합니다." -#: ports/espressif/common-hal/espcamera/Camera.c py/objobject.c py/runtime.c -msgid "no such attribute" +#: shared-bindings/busio/UART.c shared-bindings/canio/CAN.c +msgid "tx and rx cannot both be None" msgstr "" -#: ports/espressif/common-hal/_bleio/Connection.c -#: ports/nordic/common-hal/_bleio/Connection.c -msgid "non-UUID found in service_uuids_whitelist" -msgstr "" +#: shared-bindings/busio/UART.c shared-bindings/displayio/Group.c +msgid "Must be a %q subclass." +msgstr "%q의 하위클래스여야 합니다." -#: py/compile.c -msgid "non-default argument follows default argument" +#: shared-bindings/canio/RemoteTransmissionRequest.c +msgid "RemoteTransmissionRequests limited to 8 bytes" msgstr "" -#: py/objstr.c -msgid "non-hex digit found" +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/ec/EllipticCurvePublicKey.c +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/padding/__init__.c +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "Only %q supported" msgstr "" -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "non-zero timeout must be > 0.01" +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/padding/__init__.c +msgid "label is not supported" msgstr "" -#: shared-bindings/_bleio/Adapter.c -msgid "non-zero timeout must be >= interval" +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/rsa/__init__.c +#: shared-bindings/hmac/__init__.c +msgid "key does not have the expected %q purpose" msgstr "" -#: shared-bindings/_bleio/UUID.c -msgid "not a 128-bit UUID" +#: shared-bindings/digitalio/DigitalInOut.c +#: shared-bindings/i2cioexpander/IOPin.c +msgid "Cannot set value when direction is input." +msgstr "방향이 입력되면 값을 설정할 수 없습니다." + +#: shared-bindings/digitalio/DigitalInOut.c +#: shared-bindings/i2cioexpander/IOPin.c +msgid "Drive mode not used when direction is input." +msgstr "방향을 입력할 때 드라이브 모드는 사용되지 않습니다." + +#: shared-bindings/digitalio/DigitalInOut.c +#: shared-bindings/i2cioexpander/IOPin.c +#, fuzzy +msgid "Pull not used when direction is output." +msgstr "방향이 출력 될 때 풀은 사용되지 않습니다" + +#: shared-bindings/digitalio/DigitalInOutProtocol.c +msgid "%q object missing '%q' method" msgstr "" -#: py/parse.c -msgid "not a constant" +#: shared-bindings/digitalio/DigitalInOutProtocol.c +msgid "%q object missing '%q' attribute" msgstr "" -#: py/objstr.c -msgid "not all arguments converted during string formatting" +#: shared-bindings/digitalio/DigitalInOutProtocol.c +msgid "object does not support DigitalInOut protocol" msgstr "" -#: py/objstr.c -msgid "not enough arguments for format string" +#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/memorymonitor/AllocationSize.c +#: shared-bindings/pulseio/PulseIn.c +msgid "Cannot delete values" +msgstr "값을 삭제할 수 없습니다" + +#: 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 +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +msgid "Slices not supported" msgstr "" -#: extmod/ulab/code/numpy/carray/carray_tools.c -msgid "not implemented for complex dtype" +#: shared-bindings/displayio/Palette.c +msgid "color buffer must be a bytearray or array of type 'b' or 'B'" msgstr "" -#: extmod/ulab/code/numpy/bitwise.c -msgid "not supported for input types" +#: shared-bindings/displayio/Palette.c +msgid "color buffer must be 3 bytes (RGB) or 4 bytes (RGB + pad byte)" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "number of points must be at least 2" +#: shared-bindings/displayio/Palette.c +msgid "color must be between 0x000000 and 0xffffff" msgstr "" -#: py/builtinhelp.c -msgid "object " +#: shared-bindings/displayio/Palette.c +msgid "color buffer must be a buffer, tuple, list, or int" msgstr "" -#: py/obj.c -#, c-format -msgid "object '%s' isn't a tuple or list" +#: shared-bindings/displayio/TileGrid.c +msgid "Tile width must exactly divide bitmap width" msgstr "" -#: py/obj.c -msgid "object doesn't support item assignment" +#: shared-bindings/displayio/TileGrid.c +msgid "Tile height must exactly divide bitmap height" msgstr "" -#: py/obj.c -msgid "object doesn't support item deletion" +#: shared-bindings/displayio/TileGrid.c +msgid "New bitmap must be same size as old bitmap" +msgstr "새로운 비트맵은 원본 비트맵과 크기가 같아야 합니다" + +#: shared-bindings/displayio/TileGrid.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-module/displayio/legacy/TileGrid.c +#: shared-module/displayio/lvgl/TileGrid.c +msgid "Tile index out of bounds" msgstr "" -#: py/obj.c -msgid "object has no len" +#: shared-bindings/dualbank/__init__.c +msgid "offset must be >= 0" msgstr "" -#: py/obj.c -msgid "object isn't subscriptable" +#: shared-bindings/emmcio/EMMC.c shared-bindings/i2cioexpander/IOExpander.c +msgid "address out of range" msgstr "" -#: py/runtime.c -msgid "object not an iterator" +#: shared-bindings/epaperdisplay/EPaperDisplay.c +msgid "Refresh too soon" +msgstr "너무 빨리 새로고침하였습니다" + +#: shared-bindings/framebufferio/FramebufferDisplay.c +msgid "Buffer is not a bytearray." +msgstr "버퍼는 바이트 배열이 아닙니다." + +#: shared-bindings/gnss/GNSS.c +msgid "System entry must be gnss.SatelliteSystem" msgstr "" -#: py/objtype.c py/runtime.c -msgid "object not callable" +#: shared-bindings/hashlib/__init__.c shared-bindings/hmac/__init__.c +msgid "Unsupported hash algorithm" msgstr "" -#: py/sequence.c shared-bindings/displayio/Group.c -msgid "object not in sequence" +#: shared-bindings/i2cioexpander/IOExpander.c +msgid "num_pins must be 8 or 16" msgstr "" -#: py/runtime.c -msgid "object not iterable" +#: shared-bindings/i2ctarget/I2CTarget.c +msgid "addresses is empty" msgstr "" -#: py/obj.c +#: shared-bindings/ipaddress/IPv4Address.c shared-bindings/ipaddress/__init__.c +msgid "Not a valid IP string" +msgstr "유효한 IP 문자열이 아닙니다" + +#: shared-bindings/ipaddress/IPv4Address.c #, c-format -msgid "object of type '%s' has no len()" -msgstr "" +msgid "Address must be %d bytes long" +msgstr "주소 길이는 %d 바이트 여야합니다" -#: py/obj.c -msgid "object with buffer protocol required" +#: shared-bindings/ipaddress/__init__.c +msgid "Only int or string supported for ip" +msgstr "ip에는 정수 또는 문자열만 지원됩니다" + +#: shared-bindings/is31fl3741/FrameBuffer.c +msgid "width must be greater than zero" msgstr "" -#: py/objstr.c -msgid "odd-length string" +#: shared-bindings/is31fl3741/FrameBuffer.c +msgid "Scale dimensions must divide by 3" msgstr "" -#: supervisor/shared/web_workflow/web_workflow.c -msgid "off" +#: shared-bindings/is31fl3741/FrameBuffer.c +msgid "LED mappings must match display size" +msgstr "LED 매핑은 디스플레이 크기와 일치해야 합니다" + +#: shared-bindings/is31fl3741/IS31FL3741.c +msgid "Mapping must be a tuple" +msgstr "매핑은 투플이어야 합니다" + +#: shared-bindings/jpegio/JpegDecoder.c +msgid "%q must be of type %q, %q, or %q, not %q" msgstr "" -#: extmod/ulab/code/utils/utils.c -msgid "offset is too large" +#: shared-bindings/mdns/Server.c +msgid "" +"Failed to add service TXT record; non-string or bytes found in txt_records" msgstr "" +"서비스 TXT 레코드를 추가하는 것에 실패했습니다; txt_records에서 비문자열 또" +"는 바이트가 발견되었습니다" -#: shared-bindings/dualbank/__init__.c -msgid "offset must be >= 0" +#: shared-bindings/memorymap/AddressRange.c +msgid "Address range wraps around" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "offset must be non-negative and no greater than buffer length" -msgstr "" +#: shared-bindings/microcontroller/Pin.c +msgid "%q contains duplicate pins" +msgstr "%q에 중복된 핀이 포함" -#: ports/nordic/common-hal/audiobusio/PDMIn.c -#: ports/stm/common-hal/audiobusio/PDMIn.c -msgid "only bit_depth=16 is supported" -msgstr "" +#: shared-bindings/microcontroller/Pin.c +msgid "%q and %q contain duplicate pins" +msgstr "%q 및 %q에 중복된 핀이 포함" -#: ports/stm/common-hal/audiobusio/PDMIn.c -msgid "only mono is supported" +#: shared-bindings/mii/Ethernet.c shared-bindings/wifi/Radio.c +msgid "invalid hostname" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "only ndarrays can be concatenated" +#: shared-bindings/msgpack/ExtType.c +msgid "code outside range 0~127" msgstr "" -#: ports/stm/common-hal/audiobusio/PDMIn.c -msgid "only oversample=64 is supported" +#: shared-bindings/msgpack/__init__.c +msgid "default is not a function" msgstr "" -#: ports/nordic/common-hal/audiobusio/PDMIn.c -#: ports/stm/common-hal/audiobusio/PDMIn.c -msgid "only sample_rate=16000 is supported" +#: shared-bindings/msgpack/__init__.c +msgid "ext_hook is not a function" msgstr "" -#: py/objarray.c py/objstr.c py/objstrunicode.c py/objtuple.c -#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c #: shared-bindings/nvm/ByteArray.c -msgid "only slices with step=1 (aka None) are supported" +msgid "Unable to write to nvm." msgstr "" -#: py/vm.c -msgid "opcode" -msgstr "" +#: shared-bindings/os/__init__.c +msgid "No hardware random available" +msgstr "임의의 하드웨어를 사용할 수 없습니다" -#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/bitwise.c -#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/numpy/vector.c -msgid "operands could not be broadcast together" +#: shared-bindings/paralleldisplaybus/ParallelBus.c +msgid "Specify exactly one of data0 or data_pins" msgstr "" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "operation is defined for 2D arrays only" -msgstr "" +#: shared-bindings/picogame/Bitmap.c shared-module/msgpack/__init__.c +#: supervisor/shared/settings.c +msgid "Invalid format" +msgstr "잘못된 형식" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "operation is defined for ndarrays only" -msgstr "" +#: shared-bindings/ps2io/Ps2.c +msgid "Failed sending command." +msgstr "명령을 보내는 것에 실패했습니다." -#: extmod/ulab/code/ndarray.c -msgid "operation is implemented for 1D Boolean arrays only" -msgstr "" +#: shared-bindings/pulseio/PulseOut.c +msgid "Array must contain halfwords (type 'H')" +msgstr "배열은 하프워드(유형 'H')가 포함되어야 합니다" -#: extmod/ulab/code/numpy/numerical.c -msgid "operation is not implemented on ndarrays" +#: shared-bindings/pwmio/PWMOut.c +msgid "Conflicting settings for shared resource" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "operation is not supported for given type" +#: shared-bindings/random/__init__.c +msgid "stop not reachable from start" msgstr "" -#: extmod/ulab/code/ndarray_operators.c -msgid "operation not supported for the input types" +#: shared-bindings/random/__init__.c +msgid "invalid step" +msgstr "단계(step)가 유효하지 않습니다" + +#: shared-bindings/random/__init__.c +msgid "empty sequence" msgstr "" -#: py/modbuiltins.c -msgid "ord expects a character" +#: shared-bindings/rclcpy/Publisher.c +msgid "Publishers can only be created from a parent node" msgstr "" -#: py/modbuiltins.c +#: shared-bindings/rgbmatrix/RGBMatrix.c #, c-format -msgid "ord() expected a character, but string of length %d found" -msgstr "" +msgid "Must use a multiple of 6 rgb pins, not %d" +msgstr "%d이 아닌, 6 rgb 핀을 여러 개 사용해야 합니다" -#: extmod/ulab/code/utils/utils.c -msgid "out array is too small" +#: 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 주소 핀들, %d rgb 핀들과 %d 타일 들은 높이가 %d임을 나타낸다, %d가 아니라" -#: extmod/ulab/code/numpy/random/random.c -msgid "out has wrong type" +#: shared-bindings/socketpool/Socket.c +msgid "port must be >= 0" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "out keyword is not supported for complex dtype" +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c +msgid "buffer too small for requested bytes" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "out keyword is not supported for function" -msgstr "" +#: shared-bindings/socketpool/SocketPool.c +msgid "Name or service not known" +msgstr "이름 또는 서비스를 알 수 없습니다" -#: extmod/ulab/code/utils/utils.c -msgid "out must be a float dense array" +#: shared-bindings/spitarget/SPITarget.c +msgid "Packet buffers for an SPI transfer must have the same length." msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "out must be an ndarray" +#: shared-bindings/ssl/SSLContext.c +msgid "Server side context cannot have hostname" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "out must be of float dtype" -msgstr "" +#: shared-bindings/storage/__init__.c shared-bindings/usb_audio/__init__.c +#: shared-bindings/usb_cdc/__init__.c shared-bindings/usb_hid/__init__.c +#: shared-bindings/usb_midi/__init__.c shared-bindings/usb_video/__init__.c +msgid "Cannot change USB devices now" +msgstr "현재 USB 디바이스를 변경할 수 없습니다" -#: shared-bindings/bitmaptools/__init__.c -msgid "out of range of target" -msgstr "" +#: shared-bindings/supervisor/__init__.c shared-module/lvfontio/OnDiskFont.c +msgid "File not found" +msgstr "파일을 찾을 수 없습니다" -#: extmod/ulab/code/numpy/random/random.c -msgid "output array has wrong type" +#: shared-bindings/time/__init__.c +msgid "timestamp out of range for platform time_t" msgstr "" -#: extmod/ulab/code/numpy/random/random.c -msgid "output array must be contiguous" +#: shared-bindings/traceback/__init__.c +msgid "Supply both or neither of %q and %q" msgstr "" -#: py/objint_mpz.c -msgid "overflow converting long int to machine word" +#: shared-bindings/traceback/__init__.c +msgid "file write is not available" msgstr "" -#: py/modstruct.c -#, c-format -msgid "pack expected %d items for packing (got %d)" +#: shared-bindings/traceback/__init__.c +msgid "invalid exception" msgstr "" -#: shared-bindings/_stage/Layer.c shared-bindings/_stage/Text.c -msgid "palette must be 32 bytes long" +#: shared-bindings/usb_audio/USBSpeaker.c +msgid "destination must be an array of type 'h'" msgstr "" -#: py/emitinlinextensa.c -msgid "parameters must be registers in sequence a2 to a5" +#: shared-bindings/usb_audio/__init__.c +msgid "At least one of microphone and speaker must be enabled" msgstr "" -#: py/emitinlinethumb.c -msgid "parameters must be registers in sequence r0 to r3" -msgstr "" +#: shared-bindings/usb_hid/Device.c +msgid "%q, %q, and %q must all be the same length" +msgstr "%q, %q 및 %q의 길이는 모두 같아야 합니다" -#: extmod/vfs_posix_file.c -msgid "poll on file not available on win32" +#: shared-bindings/util.c +msgid "" +"Object has been deinitialized and can no longer be used. Create a new object." msgstr "" +"개체가 초기화 해제되어 더 이사 사용될 수 없습니다. 새로운 개체를 만드십시오." -#: ports/espressif/common-hal/pulseio/PulseIn.c -msgid "pop from an empty PulseIn" -msgstr "" +#: shared-bindings/warnings/__init__.c +msgid "%q must be a subclass of %q" +msgstr "%q는 %q의 하위 클래스여야 합니다" -#: ports/atmel-samd/common-hal/pulseio/PulseIn.c -#: ports/cxd56/common-hal/pulseio/PulseIn.c -#: ports/nordic/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/wifi/Radio.c +msgid "Invalid hex password" +msgstr "잘못된 16진수 패스워드" -#: shared-bindings/socketpool/Socket.c -msgid "port must be >= 0" -msgstr "" +#: shared-bindings/wifi/Radio.c +msgid "Invalid MAC address" +msgstr "잘못된 MAC 주소" -#: py/compile.c -msgid "positional arg after **" -msgstr "" +#: shared-bindings/wifi/Radio.c +msgid "AuthMode.OPEN is not used with password" +msgstr "AuthMode.OPEN은 암호와 함께 사용되지 않습니다" -#: py/compile.c -msgid "positional arg after keyword arg" +#: shared-bindings/wifi/Radio.c +msgid "Supply either %q or %q, not both" msgstr "" -#: py/objint_mpz.c -msgid "pow() 3rd argument cannot be 0" +#: shared-bindings/wifi/Radio.c +msgid "Invalid BSSID" +msgstr "잘못된 BSSID" + +#: shared-bindings/wifi/Radio.c supervisor/shared/web_workflow/web_workflow.c +msgid "Authentication failure" +msgstr "인증 실패" + +#: shared-bindings/wifi/Radio.c +msgid "No network with that ssid" +msgstr "이 ssid를 사용하는 네트워크가 없습니다" + +#: shared-bindings/wifi/Radio.c +#, c-format +msgid "Unknown failure %d" msgstr "" -#: py/objint_mpz.c -msgid "pow() with 3 arguments requires integers" +#: shared-module/adafruit_bus_device/i2c_device/I2CDevice.c +#, c-format +msgid "No I2C device at address: 0x%x" +msgstr "주소에 I2C 장치가 없습니다: 0x%x" + +#: shared-module/audiocore/WaveFile.c +msgid "Invalid format chunk size" +msgstr "형식 청크 크기가 잘못되었습니다" + +#: shared-module/audiocore/__init__.c shared-module/usb_audio/USBMicrophone.c +msgid "The sample's %q does not match" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "pull masks conflict with direction masks" +#: shared-module/audiodelays/MultiTapDelay.c +msgid "%q in %q must be of type %q or %q, not %q" msgstr "" -#: py/parse.c -msgid "raw f-strings are not supported" +#: shared-module/audiofilewriter/AudioFileWriter.c +msgid "Only 8/16-bit mono/stereo is supported" msgstr "" -#: extmod/ulab/code/numpy/fft/fft_tools.c -msgid "real and imaginary parts must be of equal length" +#: shared-module/audiofilewriter/AudioFileWriter.c +msgid "buffer_size too small for source" msgstr "" -#: py/builtinimport.c -msgid "relative import" +#: shared-module/audiomp3/MP3Decoder.c +msgid "Couldn't allocate decoder" +msgstr "디코더를 할당할 수 없습니다" + +#: shared-module/audiomp3/MP3Decoder.c +msgid "Failed to parse MP3 file" +msgstr "MP3 파일 분석에 실패했습니다" + +#: shared-module/bitbangio/I2C.c shared-module/msgpack/__init__.c +msgid "%q too long" msgstr "" -#: py/obj.c -#, c-format -msgid "requested length %d but object has length %d" +#: shared-module/bitmapfilter/__init__.c +msgid "bitmap size and depth must match" msgstr "" -#: extmod/ulab/code/ndarray_operators.c -msgid "results cannot be cast to specified type" +#: shared-module/bitmapfilter/__init__.c +msgid "unsupported bitmap depth" +msgstr "" + +#: shared-module/busdisplay/lvgl/BusDisplay.c +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "LVGL display create failed" msgstr "" -#: py/compile.c -msgid "return annotation must be an identifier" +#: shared-module/busdisplay/lvgl/BusDisplay.c +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "LVGL buffer alloc failed" msgstr "" -#: py/emitnative.c -msgid "return expected '%q' but got '%q'" +#: shared-module/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "OAEP requires this build to enable TLS 1.3 support" msgstr "" -#: shared-bindings/rgbmatrix/RGBMatrix.c -#, c-format -msgid "rgb_pins[%d] duplicates another pin assignment" +#: shared-module/displayio/bus_core.c +msgid "Unsupported display bus type" msgstr "" -#: shared-bindings/rgbmatrix/RGBMatrix.c +#: shared-module/displayio/legacy/Bitmap.c +#: shared-module/displayio/lvgl/Bitmap.c +msgid "Invalid bits per value" +msgstr "값 당 잘못된 비트" + +#: shared-module/displayio/legacy/ColorConverter.c +#: shared-module/displayio/lvgl/ColorConverter.c +#, fuzzy +msgid "Only one color can be transparent at a time" +msgstr "한 번에 한 가지 색상만 투명할 수 있습니다" + +#: shared-module/displayio/legacy/Group.c shared-module/displayio/lvgl/Group.c +msgid "Layer already in a group" +msgstr "레이어가 이미 그룹에 있습니다" + +#: shared-module/displayio/legacy/Group.c +msgid "Layer must be a Group or TileGrid subclass" +msgstr "레이어는 그룹 또는 TileGrid 하위 클래스 여야 합니다" + +#: shared-module/displayio/legacy/OnDiskBitmap.c +#: shared-module/displayio/lvgl/OnDiskBitmap.c #, c-format -msgid "rgb_pins[%d] is not on the same port as clock" -msgstr "" +msgid "" +"Only Windows format, uncompressed BMP supported: given header size is %d" +msgstr "윈도우 형식, 비압축 BMP만 지원됩니다: 지정된 헤더 크기는 %d 입니다" -#: extmod/ulab/code/numpy/numerical.c -msgid "roll argument must be an ndarray" +#: shared-module/displayio/legacy/OnDiskBitmap.c +#: shared-module/displayio/lvgl/OnDiskBitmap.c +msgid "RLE-compressed BMP not supported" msgstr "" -#: py/objstr.c -msgid "rsplit(None,n)" +#: shared-module/displayio/legacy/OnDiskBitmap.c +#: shared-module/displayio/lvgl/OnDiskBitmap.c +msgid "Unable to read color palette data" msgstr "" -#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c -#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c -msgid "sampling rate out of range" +#: shared-module/displayio/legacy/__init__.c +msgid "Too many displays" msgstr "" -#: py/modmicropython.c -msgid "schedule queue full" +#: shared-module/displayio/legacy/__init__.c +msgid "Too many display buses; deinit() unused displays" msgstr "" -#: py/builtinimport.c -msgid "script compilation not supported" +#: shared-module/displayio/lvgl/Group.c +msgid "Layer does not support scaling" msgstr "" -#: py/nativeglue.c -msgid "set unsupported" +#: shared-module/displayio/lvgl/Group.c +msgid "Layer must be a Group, TileGrid, vector shape or VideoBuffer" msgstr "" -#: extmod/ulab/code/numpy/random/random.c -msgid "shape must be None, and integer or a tuple of integers" +#: shared-module/displayio/lvgl/TileGrid.c +msgid "LVGL displayio backend does not support flips/transpose yet" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "shape must be integer or tuple of integers" +#: shared-module/displayio/lvgl/TileGrid.c +msgid "OnDiskBitmap requires its own pixel_shader" msgstr "" -#: shared-module/msgpack/__init__.c -msgid "short read" +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "LVGL dirty row alloc failed" msgstr "" -#: py/objstr.c -msgid "sign not allowed in string format specifier" +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +#: shared-module/videocore/VideoBuffer.c +#: shared-module/videocore/legacy/VideoBuffer.c +#: shared-module/videocore/lvgl/VideoBuffer.c +msgid "VideoBuffer can't stream into a rotated display" msgstr "" -#: py/objstr.c -msgid "sign not allowed with integer format specifier 'c'" +#: shared-module/gifio/GifWriter.c +msgid "unsupported colorspace for GifWriter" msgstr "" -#: extmod/ulab/code/ulab_tools.c -msgid "size is defined for ndarrays only" +#: shared-module/hmac/HMAC.c +msgid "key does not support this digest" msgstr "" -#: extmod/ulab/code/numpy/random/random.c -msgid "size must match out.shape when used together" +#: shared-module/hmac/HMAC.c +msgid "HMAC of an empty message is not supported with a hardware key" msgstr "" -#: py/nativeglue.c -msgid "slice unsupported" +#: shared-module/i2cdisplaybus/I2CDisplayBus.c +#: shared-module/is31fl3741/IS31FL3741.c +#, c-format +msgid "Unable to find I2C Display at %x" msgstr "" -#: py/objint.c py/sequence.c -msgid "small int overflow" +#: shared-module/i2cioexpander/IOExpander.c +msgid "Cannot deinitialize board IOExpander" msgstr "" -#: main.c -msgid "soft reboot\n" +#: shared-module/imagecapture/ParallelImageCapture.c +msgid "This microcontroller does not support continuous capture." msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "sort argument must be an ndarray" -msgstr "" +#: shared-module/jpegio/JpegDecoder.c +msgid "Interrupted by output function" +msgstr "출력 함수로 인해 종료되었다" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "sos array must be of shape (n_section, 6)" -msgstr "" +#: shared-module/jpegio/JpegDecoder.c +msgid "Device error or wrong termination of input stream" +msgstr "장치 오류 또는 입력 스트림의 잘못된 종료" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "sos[:, 3] should be all ones" -msgstr "" +#: shared-module/jpegio/JpegDecoder.c +msgid "Insufficient memory pool for the image" +msgstr "이미지에 대한 메모리 풀이 부족합니다" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "sosfilt requires iterable arguments" -msgstr "" +#: shared-module/jpegio/JpegDecoder.c +msgid "Insufficient stream input buffer" +msgstr "불충분한 스트림 입력 버퍼" -#: shared-bindings/bitmaptools/__init__.c -msgid "source palette too large" -msgstr "" +#: shared-module/jpegio/JpegDecoder.c +#, fuzzy +msgid "Parameter error" +msgstr "파라미터 오류" -#: shared-bindings/bitmaptools/__init__.c -msgid "source_bitmap must have value_count of 2 or 65536" -msgstr "" +#: shared-module/jpegio/JpegDecoder.c +msgid "Data format error (may be broken data)" +msgstr "데이터 형식 오류(손상된 데이터일 수 있습니다)" -#: shared-bindings/bitmaptools/__init__.c -msgid "source_bitmap must have value_count of 65536" +#: shared-module/jpegio/JpegDecoder.c +msgid "Right format but not supported" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "source_bitmap must have value_count of 8" +#: shared-module/jpegio/JpegDecoder.c +msgid "Unsupported JPEG (may be progressive)" msgstr "" -#: extmod/modre.c -msgid "splitting with sub-captures" +#: shared-module/jpegio/JpegDecoder.c +msgid "%q() without %q()" msgstr "" -#: py/objstr.c -msgid "start/end indices" -msgstr "" +#: shared-module/memorymonitor/AllocationAlarm.c +#, c-format +msgid "Attempt to allocate %d blocks" +msgstr "%d 블록 할당 시도" -#: shared-bindings/random/__init__.c -msgid "stop not reachable from start" +#: shared-module/msgpack/__init__.c +msgid "short read" msgstr "" -#: py/stream.c shared-bindings/getpass/__init__.c -msgid "stream operation not supported" +#: shared-module/msgpack/__init__.c +msgid "no default packer" msgstr "" -#: py/objarray.c py/objstr.c -msgid "string argument without an encoding" +#: shared-module/paralleldisplaybus/ParallelBus.c +msgid "" +"This microcontroller only supports data0=, not data_pins=, because it " +"requires contiguous pins." msgstr "" -#: py/objstrunicode.c -msgid "string index out of range" +#: shared-module/rgbmatrix/RGBMatrix.c +msgid "The length of rgb_pins must be 6, 12, 18, 24, or 30" msgstr "" -#: py/objstrunicode.c +#: shared-module/rgbmatrix/RGBMatrix.c #, c-format -msgid "string indices must be integers, not %s" +msgid "rgb_pins[%d] is not on the same port as clock" msgstr "" -#: py/objarray.c py/objstr.c -msgid "substring not found" +#: shared-module/rgbmatrix/RGBMatrix.c +#, c-format +msgid "rgb_pins[%d] duplicates another pin assignment" msgstr "" -#: py/compile.c -msgid "super() can't find self" +#: shared-module/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 "" -#: extmod/modjson.c -msgid "syntax error in JSON" -msgstr "" +#: shared-module/rgbmatrix/RGBMatrix.c +msgid "No timer available" +msgstr "사용 가능한 타이머가 없습니다" -#: extmod/modtime.c -msgid "ticks interval overflow" -msgstr "" +#: shared-module/rgbmatrix/RGBMatrix.c +#, c-format +msgid "Internal error #%d" +msgstr "내부 오류 #%d" -#: ports/nordic/common-hal/watchdog/WatchDogTimer.c -msgid "timeout duration exceeded the maximum supported value" +#: shared-module/sdcardio/SDCard.c +msgid "timeout waiting for v1 card" msgstr "" -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "timeout must be < 655.35 secs" +#: shared-module/sdcardio/SDCard.c +msgid "timeout waiting for v2 card" msgstr "" -#: ports/raspberrypi/common-hal/floppyio/__init__.c -msgid "timeout waiting for flux" +#: shared-module/sdcardio/SDCard.c +msgid "no SD card" msgstr "" -#: ports/raspberrypi/common-hal/floppyio/__init__.c -#: shared-module/floppyio/__init__.c -msgid "timeout waiting for index pulse" +#: shared-module/sdcardio/SDCard.c +msgid "couldn't determine SD card version" msgstr "" #: shared-module/sdcardio/SDCard.c -msgid "timeout waiting for v1 card" +msgid "no response from SD card" msgstr "" #: shared-module/sdcardio/SDCard.c -msgid "timeout waiting for v2 card" +msgid "SD card CSD format not supported" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "timer re-init" +#: shared-module/sdcardio/SDCard.c +msgid "can't set 512 block size" msgstr "" -#: shared-bindings/time/__init__.c -msgid "timestamp out of range for platform time_t" +#: shared-module/ssl/SSLSocket.c +msgid "Invalid socket for TLS" +msgstr "TLS에 대한 잘못된 소켓" + +#: shared-module/ssl/SSLSocket.c +msgid "invalid cert" +msgstr "cert가 유효하지 않습니다" + +#: shared-module/storage/__init__.c +msgid "File write in progress" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "tobytes can be invoked for dense arrays only" +#: shared-module/storage/__init__.c +msgid "Mount point directory missing" msgstr "" -#: py/compile.c -msgid "too many args" +#: shared-module/storage/__init__.c +msgid "Cannot remount path when visible via USB." msgstr "" -#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/create.c -msgid "too many dimensions" +#: shared-module/struct/__init__.c +msgid "'S' and 'O' are not supported format types" +msgstr "'S' 및 'O'는 지원되지 않는 형식 유형입니다" + +#: shared-module/struct/__init__.c +msgid "buffer size must match format" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "too many indices" +#: shared-module/synthio/__init__.c +#, fuzzy +msgid "%q must be array of type 'h'" +msgstr "%q는 'h' 유형의 배열이어야 합니다" + +#: shared-module/tilepalettemapper/TilePaletteMapper.c +msgid "TilePaletteMapper may only be bound to a TileGrid once" msgstr "" -#: py/asmthumb.c -msgid "too many locals for native method" +#: shared-module/touchio/TouchIn.c +msgid "No pullup on pin; 1Mohm recommended" msgstr "" -#: py/runtime.c -#, c-format -msgid "too many values to unpack (expected %d)" +#: shared-module/touchio/TouchIn.c +msgid "No pulldown on pin; 1Mohm recommended" +msgstr "핀에 풀다운이 없습니다; 1Mohm를 권장합니다" + +#: shared-module/usb/core/Device.c +msgid "No usb host port initialized" +msgstr "usb 호스트 포트가 초기화되지 않았습니다" + +#: shared-module/usb/core/Device.c +msgid "Pipe error" +msgstr "파이프 오류" + +#: shared-module/usb/core/Device.c +#, fuzzy +msgid "No configuration set" +msgstr "구성이 설정되어 있지 않습니다" + +#: shared-module/usb_hid/Device.c +msgid "USB busy" msgstr "" -#: extmod/ulab/code/numpy/approx.c -msgid "trapz is defined for 1D arrays of equal length" +#: shared-module/vectorio/Circle.c shared-module/vectorio/Polygon.c +#: shared-module/vectorio/Rectangle.c +msgid "can only have one parent" msgstr "" -#: extmod/ulab/code/numpy/approx.c -msgid "trapz is defined for 1D iterables" -msgstr "" +#: shared-module/vectorio/Polygon.c +msgid "Polygon needs at least 3 points" +msgstr "다각형은 최소 3개의 점이 필요합니다" -#: py/obj.c -msgid "tuple/list has wrong length" +#: shared-module/videocore/VideoBuffer.c +msgid "framebuffer went away" msgstr "" -#: ports/espressif/common-hal/canio/CAN.c -#, c-format -msgid "twai_driver_install returned esp-idf error #%d" +#: shared-module/videocore/VideoBuffer.c +msgid "video doesn't fit in framebuffer" msgstr "" -#: ports/espressif/common-hal/canio/CAN.c -#, c-format -msgid "twai_start returned esp-idf error #%d" +#: shared-module/videocore/VideoBuffer.c +msgid "framebuffer missing required functions" msgstr "" -#: shared-bindings/busio/UART.c shared-bindings/canio/CAN.c -msgid "tx and rx cannot both be None" +#: shared-module/videocore/VideoBuffer.c +msgid "video format must be byte aligned" msgstr "" -#: py/objtype.c -msgid "type '%q' is not an acceptable base type" +#: shared-module/videocore/VideoBuffer.c +msgid "video format doesn't match framebuffer" msgstr "" -#: py/objtype.c -msgid "type is not an acceptable base type" +#: shared-module/videocore/VideoBuffer.c +msgid "video source rejected the destination" msgstr "" -#: py/runtime.c -msgid "type object '%q' has no attribute '%q'" +#: shared-module/videocore/VideoBuffer.c +msgid "video in a framebuffer must be at x == 0" msgstr "" -#: py/objtype.c -msgid "type takes 1 or 3 arguments" +#: shared-module/videocore/VideoBuffer.c +msgid "video size changed since play; stop and play again" msgstr "" -#: py/objint_longlong.c -msgid "ulonglong too large" +#: shared-module/videocore/VideoBuffer.c +msgid "VideoBuffer is playing into a different framebuffer" msgstr "" -#: py/parse.c -msgid "unexpected indent" +#: shared-module/videocore/legacy/VideoBuffer.c +msgid "VideoBuffer does not support transforms" msgstr "" -#: py/bc.c -msgid "unexpected keyword argument" +#: shared-module/videocore/lvgl/VideoBuffer.c +msgid "video format must be 16, 24 or 32 bits per pixel" msgstr "" -#: py/argcheck.c py/bc.c py/objnamedtuple.c -#: shared-bindings/traceback/__init__.c -msgid "unexpected keyword argument '%q'" -msgstr "" +#: supervisor/shared/bluetooth/bluetooth.c +msgid "Reconnecting" +msgstr "다시 연결하는 중입니다" -#: py/lexer.c -msgid "unicode name escapes" -msgstr "" +#: supervisor/shared/bluetooth/bluetooth.c +msgid "Ok" +msgstr "켜짐 (연결됨)" -#: py/parse.c -msgid "unindent doesn't match any outer indent level" -msgstr "" +#: supervisor/shared/bluetooth/bluetooth.c +msgid "Off" +msgstr "꺼짐 (연결 끊김)" -#: py/objstr.c -#, c-format -msgid "unknown conversion specifier %c" +#: supervisor/shared/micropython.c +msgid "[truncated due to length]" msgstr "" -#: py/objstr.c -msgid "unknown format code '%c' for object of type '%q'" +#: supervisor/shared/safe_mode.c +msgid "" +"\n" +"You are in safe mode because:\n" msgstr "" +"\n" +"안전 모드에 있는 이유는 다음과 같습니다:\n" -#: py/compile.c -msgid "unknown type" -msgstr "" +#: supervisor/shared/safe_mode.c +msgid "Power dipped. Make sure you are providing enough power." +msgstr "전력이 내려갔습니다. 충분한 전력을 제공할 수 있는지 확인하십시오." -#: py/compile.c -msgid "unknown type '%q'" +#: supervisor/shared/safe_mode.c +msgid "You pressed the BOOT button at start up" msgstr "" -#: py/objstr.c -#, c-format -msgid "unmatched '%c' in format" +#: supervisor/shared/safe_mode.c +msgid "You pressed the reset button during boot." msgstr "" -#: py/objtype.c py/runtime.c -msgid "unreadable attribute" -msgstr "" +#: supervisor/shared/safe_mode.c +msgid "CIRCUITPY drive could not be found or created." +msgstr "CIRCUITPY 드라이브를 찾거나 만들 수 없습니다." -#: shared-bindings/displayio/TileGrid.c shared-bindings/vectorio/VectorShape.c -msgid "unsupported %q type" +#: supervisor/shared/safe_mode.c +msgid "The `microcontroller` module was used to boot into safe mode." msgstr "" -#: py/emitinlinethumb.c -#, c-format -msgid "unsupported Thumb instruction '%s' with %d arguments" -msgstr "" +#: supervisor/shared/safe_mode.c +msgid "Error in safemode.py." +msgstr "safemode.py에 오류가 있습니다." -#: py/emitinlinextensa.c -#, c-format -msgid "unsupported Xtensa instruction '%s' with %d arguments" +#: supervisor/shared/safe_mode.c +msgid "Stack overflow. Increase stack size." msgstr "" -#: shared-module/bitmapfilter/__init__.c -msgid "unsupported bitmap depth" +#: supervisor/shared/safe_mode.c +msgid "USB devices need more endpoints than are available." msgstr "" -#: shared-module/gifio/GifWriter.c -msgid "unsupported colorspace for GifWriter" +#: supervisor/shared/safe_mode.c +msgid "USB devices specify too many interface names." msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "unsupported colorspace for dither" -msgstr "" +#: supervisor/shared/safe_mode.c +msgid "Boot device must be first (interface #0)." +msgstr "부팅 장치는 첫 번째(인터페이스 #0)여야 합니다." -#: py/objstr.c -#, c-format -msgid "unsupported format character '%c' (0x%x) at index %d" -msgstr "" +#: supervisor/shared/safe_mode.c +msgid "Internal watchdog timer expired." +msgstr "내부 감시 타이머가 만료되었습니다." -#: py/runtime.c -msgid "unsupported type for %q: '%s'" -msgstr "" +#: supervisor/shared/safe_mode.c +msgid "CircuitPython core code crashed hard. Whoops!\n" +msgstr "CircuitPython 핵심 코드가 심하게 충돌했습니다. 앗!\n" -#: py/runtime.c -msgid "unsupported type for operator" -msgstr "" +#: supervisor/shared/safe_mode.c +msgid "Heap allocation when VM not running." +msgstr "VM이 작동하지 않을 때 힙이 할당됩니다." -#: py/runtime.c -msgid "unsupported types for %q: '%q', '%q'" -msgstr "" +#: supervisor/shared/safe_mode.c +#, fuzzy +msgid "Failed to write internal flash." +msgstr "내부 플래시를 쓰는 것에 실패했습니다." -#: extmod/ulab/code/numpy/io/io.c -msgid "usecols is too high" -msgstr "" +#: supervisor/shared/safe_mode.c +msgid "Hard fault: memory access or instruction error." +msgstr "치명적인 실수: 메모리 액세스 또는 명령 오류." -#: extmod/ulab/code/numpy/io/io.c -msgid "usecols keyword must be specified" -msgstr "" +#: supervisor/shared/safe_mode.c +msgid "Interrupt error." +msgstr "인터럽트 오류." -#: py/objint.c -#, c-format -msgid "value must fit in %d byte(s)" +#: supervisor/shared/safe_mode.c +msgid "LVGL ran out of memory." msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "value out of range of target" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "NLR 는 점프에 실패했습니다. 아마도 메모리 손상일 것입니다." + +#: supervisor/shared/safe_mode.c +msgid "Unable to allocate to the heap." msgstr "" -#: extmod/moddeflate.c -msgid "wbits" +#: supervisor/shared/safe_mode.c +msgid "Third-party firmware fatal error." msgstr "" -#: shared-bindings/bitmapfilter/__init__.c +#: supervisor/shared/safe_mode.c msgid "" -"weights must be a sequence with an odd square number of elements (usually 9 " -"or 25)" +"\n" +"Please file an issue with your program at github.com/adafruit/circuitpython/" +"issues." msgstr "" +"\n" +"github.com/adafruit/circuitpython/issues 에\n" +"프로그램 오류를 제출하세요." -#: shared-bindings/bitmapfilter/__init__.c -msgid "weights must be an object of type %q, %q, %q, or %q, not %q " +#: supervisor/shared/safe_mode.c +msgid "" +"\n" +"Press reset to exit safe mode.\n" msgstr "" +"\n" +"재설정을 눌러 안전 모드를 종료합니다.\n" -#: shared-bindings/is31fl3741/FrameBuffer.c -msgid "width must be greater than zero" -msgstr "" +#: supervisor/shared/settings.c +#, c-format +msgid "An error occurred while retrieving '%s':\n" +msgstr "%s'을(를) 검색하는 동안 오류가 발생했습니다:\n" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/raspberrypi/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "wifi is not enabled" -msgstr "" +#: supervisor/shared/settings.c +msgid "Invalid unicode escape" +msgstr "잘못된 유니코드 이스케이프" -#: ports/raspberrypi/common-hal/wifi/Monitor.c -msgid "wifi.Monitor not available" +#: supervisor/shared/web_workflow/web_workflow.c +msgid "Wi-Fi: " msgstr "" -#: shared-bindings/_bleio/Adapter.c -msgid "window must be <= interval" +#: supervisor/shared/web_workflow/web_workflow.c +msgid "off" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "wrong axis index" -msgstr "" +#: supervisor/shared/web_workflow/web_workflow.c +msgid "No IP" +msgstr "IP가 없습니다" -#: extmod/ulab/code/numpy/create.c -msgid "wrong axis specified" -msgstr "" +#~ msgid "Failed to add service TXT record" +#~ msgstr "서비스 TXT 레코드를 추가하는 것에 실패했습니다" -#: extmod/ulab/code/numpy/io/io.c -msgid "wrong dtype" -msgstr "" +#~ msgid "invalid key" +#~ msgstr "키가 유효하지 않습니다" -#: extmod/ulab/code/numpy/transform.c -msgid "wrong index type" -msgstr "" +#, fuzzy +#~ msgid "%q out of bounds" +#~ msgstr "%q가 경계를 벗어남" -#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/numpy/create.c -#: extmod/ulab/code/numpy/io/io.c extmod/ulab/code/numpy/transform.c -#: extmod/ulab/code/numpy/vector.c -msgid "wrong input type" -msgstr "" +#~ msgid "%q renamed %q" +#~ msgstr "%q가 %q로 이름이 변경되었습니다" -#: extmod/ulab/code/numpy/transform.c -msgid "wrong length of condition array" -msgstr "" +#, c-format +#~ msgid "Buffer + offset too small %d %d %d" +#~ msgstr "Buffer + offset이 너무 작습니다 %d %d %d" -#: extmod/ulab/code/numpy/transform.c -msgid "wrong length of index array" -msgstr "" +#~ msgid "Byte buffer must be 16 bytes." +#~ msgstr "잘못된 크기의 버퍼. 16 바이트 여야합니다." -#: extmod/ulab/code/numpy/create.c py/objarray.c py/objstr.c -msgid "wrong number of arguments" -msgstr "" +#, c-format +#~ msgid "Invalid byte %.*s" +#~ msgstr "잘못된 바이트 %.*s" -#: py/runtime.c -msgid "wrong number of values to unpack" -msgstr "" +#~ msgid "Key not found" +#~ msgstr "키를 찾을 수 없습니다" -#: extmod/ulab/code/numpy/vector.c -msgid "wrong output type" -msgstr "" +#, fuzzy +#~ msgid "Not supported JPEG standard" +#~ msgstr "지원되지 않는 JPEG 표준" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "zi must be an ndarray" -msgstr "" +#, fuzzy +#~ msgid "%q moved from %q to %q" +#~ msgstr "%q가 %q에서 %q로 이동했습니다" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "zi must be of float type" -msgstr "" +#, c-format +#~ msgid "%%c requires int or char" +#~ msgstr "%%c 전수(int)또는 캐릭터(char)필요합니다" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "zi must be of shape (n_section, 2)" -msgstr "" +#~ msgid "'%q' object is not callable" +#~ msgstr "'%q' 개체를 호출할 수 없습니다" + +#~ msgid "Cannot remount '/' when visible via USB." +#~ msgstr "USB를 통해 표시될 때 '/'은 다시 마운트할 수 없습니다." #~ msgid "Data chunk must follow fmt chunk" #~ msgstr "데이터 청크는 fmt 청크를 따라야 합니다" @@ -4626,13 +5319,13 @@ msgstr "" #~ msgid "'%s' object does not support item deletion" #~ msgstr "'%s' 은 삭제할 수 없습니다" -#~ msgid "'%s' object is not an iterator" +#~ msgid "'%s' object isn't an iterator" #~ msgstr "'%s' 은 수정할 수 없습니다" #~ msgid "'%s' object is not callable" #~ msgstr "'%s' 을 검색 할 수 없습니다" -#~ msgid "'%s' object is not iterable" +#~ msgid "'%s' object isn't iterable" #~ msgstr "'%s' 은 변경할 수 없습니다" #~ msgid "'break' outside loop" diff --git a/locale/nl.po b/locale/nl.po index ecdb4ba96b5..bafb415635e 100644 --- a/locale/nl.po +++ b/locale/nl.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: 2023-11-16 15:03+0000\n" -"Last-Translator: Jeff Epler \n" +"PO-Revision-Date: 2025-07-13 16:01+0000\n" +"Last-Translator: Mirthe Winter \n" "Language-Team: none\n" "Language: nl\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 5.2\n" +"X-Generator: Weblate 5.13-dev\n" #: main.c msgid "" @@ -49,7 +49,7 @@ msgstr "" #: py/obj.c msgid " File \"%q\"" -msgstr " Bestand" +msgstr " Bestand \"%q\"" #: py/obj.c msgid " File \"%q\", line %d" @@ -61,7 +61,7 @@ msgstr "" #: main.c msgid " not found.\n" -msgstr "" +msgstr " niet gevonden.\n" #: main.c msgid " output:\n" @@ -82,7 +82,7 @@ msgstr "" msgid "%q and %q contain duplicate pins" msgstr "" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: shared-bindings/audioio/AudioOut.c msgid "%q and %q must be different" msgstr "" @@ -102,6 +102,10 @@ msgstr "" msgid "%q failure: %d" msgstr "%q fout: %d" +#: shared-module/audiodelays/MultiTapDelay.c +msgid "%q in %q must be of type %q or %q, not %q" +msgstr "" + #: py/argcheck.c shared-module/audiofilters/Filter.c msgid "%q in %q must be of type %q, not %q" msgstr "" @@ -154,7 +158,7 @@ msgstr "" msgid "%q length must be >= %d" msgstr "" -#: py/modsys.c py/objmodule.c py/runtime.c +#: py/modsys.c py/runtime.c msgid "%q moved from %q to %q" msgstr "" @@ -215,7 +219,7 @@ msgstr "" #: shared-bindings/bitmapfilter/__init__.c shared-bindings/canio/CAN.c #: shared-bindings/digitalio/Pull.c shared-bindings/supervisor/__init__.c #: shared-module/audiofilters/Filter.c shared-module/displayio/__init__.c -#: shared-module/synthio/Biquad.c shared-module/synthio/Synthesizer.c +#: shared-module/synthio/Synthesizer.c msgid "%q must be of type %q or %q, not %q" msgstr "" @@ -224,6 +228,7 @@ msgid "%q must be of type %q, %q, or %q, not %q" msgstr "" #: py/argcheck.c py/runtime.c shared-bindings/bitmapfilter/__init__.c +#: shared-module/audiodelays/MultiTapDelay.c shared-module/synthio/Note.c #: shared-module/synthio/__init__.c msgid "%q must be of type %q, not %q" msgstr "" @@ -304,7 +309,7 @@ msgid "'%q' object does not support '%q'" msgstr "'%q' object ondersteunt geen '%q'" #: py/runtime.c -msgid "'%q' object is not an iterator" +msgid "'%q' object isn't an iterator" msgstr "'%q' object is geen iterator" #: py/objtype.c py/runtime.c shared-module/atexit/__init__.c @@ -312,7 +317,7 @@ msgid "'%q' object is not callable" msgstr "'%q' object is niet aanroepbaar" #: py/runtime.c -msgid "'%q' object is not iterable" +msgid "'%q' object isn't iterable" msgstr "'%q' object is niet itereerbaar" #: py/emitinlinethumb.c py/emitinlinextensa.c @@ -553,7 +558,7 @@ msgstr "Heeft al een luisteraar voor 'all-matches'" #: ports/espressif/common-hal/_bleio/__init__.c msgid "Already in progress" -msgstr "" +msgstr "Al in uitvoering" #: ports/espressif/bindings/espnow/ESPNow.c #: ports/espressif/common-hal/espulp/ULP.c @@ -607,7 +612,7 @@ msgstr "" #: ports/raspberrypi/common-hal/audiobusio/I2SOut.c #: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "Audio source error" -msgstr "" +msgstr "Audiobronfout" #: shared-bindings/wifi/Radio.c msgid "AuthMode.OPEN is not used with password" @@ -626,8 +631,8 @@ msgid "" "Auto-reload is on. Simply save files over USB to run them or enter REPL to " "disable.\n" msgstr "" -"Auto-herlaad staat aan. Sla bestanden simpelweg op over USB om uit te voeren " -"of start REPL om uit te schakelen.\n" +"Auto-herlaad staat aan. Sla bestanden simpelweg via USB op om ze uit te " +"voeren of start REPL om ze uit te schakelen.\n" #: ports/espressif/common-hal/canio/CAN.c msgid "Baudrate not supported by peripheral" @@ -696,7 +701,7 @@ msgstr "Buffer is %d bytes te klein" #: shared-bindings/framebufferio/FramebufferDisplay.c #: shared-bindings/struct/__init__.c shared-module/struct/__init__.c msgid "Buffer too small" -msgstr "" +msgstr "Buffer te klein" #: ports/atmel-samd/common-hal/paralleldisplaybus/ParallelBus.c #: ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c @@ -792,7 +797,7 @@ msgid "Cannot record to a file" msgstr "Kan niet opnemen naar een bestand" #: shared-module/storage/__init__.c -msgid "Cannot remount '/' when visible via USB." +msgid "Cannot remount path when visible via USB." msgstr "" #: shared-bindings/digitalio/DigitalInOut.c @@ -848,6 +853,10 @@ msgstr "" msgid "Coordinate arrays types have different sizes" msgstr "" +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "Could not publish to ROS topic" +msgstr "" + #: shared-bindings/_bleio/Adapter.c msgid "Could not set address" msgstr "Kan adres niet zetten" @@ -860,6 +869,11 @@ msgstr "Kan interrupt niet starten, RX is bezig" msgid "Couldn't allocate decoder" msgstr "Kan decoder niet alloceren" +#: ports/espressif/common-hal/rclcpy/__init__.c +#, c-format +msgid "Critical ROS failure during soft reboot, reset required: %d" +msgstr "" + #: ports/stm/common-hal/analogio/AnalogOut.c msgid "DAC Channel Init Error" msgstr "DAC kanaal Init Fout" @@ -920,7 +934,7 @@ msgstr "Beeldscherm rotatie moet in stappen van 90 graden" #: main.c msgid "Done" -msgstr "" +msgstr "Gedaan" #: shared-bindings/digitalio/DigitalInOut.c msgid "Drive mode not used when direction is input." @@ -1056,9 +1070,10 @@ msgstr "Schrijven naar interne flash mislukt." msgid "File exists" msgstr "Bestand bestaat" +#: shared-bindings/supervisor/__init__.c shared-module/lvfontio/OnDiskFont.c #: shared-module/os/getenv.c msgid "File not found" -msgstr "" +msgstr "Bestand niet gevonden" #: ports/atmel-samd/common-hal/canio/Listener.c #: ports/espressif/common-hal/canio/Listener.c @@ -1069,11 +1084,11 @@ msgstr "Filters zijn te complex" #: ports/espressif/common-hal/dualbank/__init__.c msgid "Firmware is duplicate" -msgstr "" +msgstr "Firmware is duplicaat" #: ports/espressif/common-hal/dualbank/__init__.c msgid "Firmware is invalid" -msgstr "" +msgstr "Firmware is ongeldig" #: ports/espressif/common-hal/dualbank/__init__.c msgid "Firmware is too big" @@ -1087,7 +1102,7 @@ msgstr "" msgid "For RGB colorspaces, input bitmap must have 16 bits per pixel" msgstr "" -#: ports/cxd56/common-hal/camera/Camera.c +#: ports/cxd56/common-hal/camera/Camera.c shared-module/audiocore/WaveFile.c msgid "Format not supported" msgstr "Formaat wordt niet ondersteund" @@ -1107,7 +1122,7 @@ msgstr "" #: ports/espressif/common-hal/espidf/__init__.c msgid "Generic Failure" -msgstr "" +msgstr "Generieke mislukking" #: shared-bindings/framebufferio/FramebufferDisplay.c #: shared-module/busdisplay/BusDisplay.c @@ -1209,7 +1224,7 @@ msgstr "Interne define fout" #: shared-bindings/pwmio/PWMOut.c shared-module/os/getenv.c msgid "Internal error" -msgstr "" +msgstr "Interne fout" #: shared-module/rgbmatrix/RGBMatrix.c #, c-format @@ -1235,7 +1250,7 @@ msgstr "" #: supervisor/shared/safe_mode.c msgid "Interrupt error." -msgstr "" +msgstr "Interruptfout." #: shared-module/jpegio/JpegDecoder.c msgid "Interrupted by output function" @@ -1251,7 +1266,9 @@ msgstr "" #: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c py/argcheck.c #: shared-bindings/digitalio/DigitalInOut.c #: shared-bindings/epaperdisplay/EPaperDisplay.c shared-bindings/pwmio/PWMOut.c +#: shared-bindings/supervisor/__init__.c #: shared-module/aurora_epaper/aurora_framebuffer.c +#: shared-module/lvfontio/OnDiskFont.c msgid "Invalid %q" msgstr "Ongeldige %q" @@ -1274,7 +1291,7 @@ msgstr "Ongeldige ADC Unit waarde" #: ports/espressif/common-hal/_bleio/__init__.c #: ports/nordic/common-hal/_bleio/__init__.c msgid "Invalid BLE parameter" -msgstr "" +msgstr "Ongeldige BLE-parameter" #: shared-bindings/wifi/Radio.c msgid "Invalid BSSID" @@ -1282,6 +1299,10 @@ msgstr "Ongeldig BSSID" #: shared-bindings/wifi/Radio.c msgid "Invalid MAC address" +msgstr "Ongeldig MAC-adres" + +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "Invalid ROS domain ID" msgstr "" #: ports/espressif/common-hal/espidf/__init__.c py/moderrno.c @@ -1304,7 +1325,7 @@ msgstr "" #: shared-module/msgpack/__init__.c msgid "Invalid format" -msgstr "" +msgstr "Ongeldig formaat" #: shared-module/audiocore/WaveFile.c msgid "Invalid format chunk size" @@ -1321,7 +1342,7 @@ msgstr "" #: ports/espressif/common-hal/espidf/__init__.c msgid "Invalid size" -msgstr "" +msgstr "Ongeldige grootte" #: shared-module/ssl/SSLSocket.c msgid "Invalid socket for TLS" @@ -1330,11 +1351,11 @@ msgstr "" #: ports/espressif/common-hal/espidf/__init__.c #: ports/nordic/common-hal/_bleio/__init__.c msgid "Invalid state" -msgstr "" +msgstr "Ongeldige staat" #: shared-module/os/getenv.c msgid "Invalid unicode escape" -msgstr "" +msgstr "Ongeldige unicode escape" #: shared-bindings/aesio/aes.c msgid "Key must be 16, 24, or 32 bytes long" @@ -1342,7 +1363,7 @@ msgstr "Sleutel moet 16, 24, of 32 bytes lang zijn" #: shared-module/os/getenv.c msgid "Key not found" -msgstr "" +msgstr "Sleutel niet gevonden" #: shared-module/is31fl3741/FrameBuffer.c msgid "LED mappings must match display size" @@ -1373,6 +1394,11 @@ msgstr "" msgid "MITM security not supported" msgstr "" +#: ports/stm/common-hal/sdioio/SDCard.c +#, c-format +msgid "MMC/SDIO Clock Error %x" +msgstr "" + #: shared-bindings/is31fl3741/IS31FL3741.c msgid "Mapping must be a tuple" msgstr "" @@ -1498,7 +1524,7 @@ msgstr "" #: supervisor/shared/web_workflow/web_workflow.c msgid "No IP" -msgstr "" +msgstr "Geen IP" #: ports/atmel-samd/common-hal/microcontroller/__init__.c #: ports/cxd56/common-hal/microcontroller/__init__.c @@ -1559,6 +1585,10 @@ msgstr "" msgid "No pulldown on pin; 1Mohm recommended" msgstr "Geen pulldown op pin; 1MOhm aangeraden" +#: shared-module/touchio/TouchIn.c +msgid "No pullup on pin; 1Mohm recommended" +msgstr "" + #: py/moderrno.c msgid "No space left on device" msgstr "Geen ruimte meer beschikbaar op apparaat" @@ -1815,7 +1845,7 @@ msgstr "Prefix buffer moet op de heap zijn" #: main.c msgid "Press any key to enter the REPL. Use CTRL-D to reload.\n" msgstr "" -"Druk een willekeurige toets om de REPL te starten. Gebruik CTRL+D om te " +"Druk op een willekeurige toets om de REPL te starten. Gebruik CTRL+D om te " "herstarten.\n" #: main.c @@ -1838,6 +1868,10 @@ msgstr "" msgid "Program too long" msgstr "" +#: shared-bindings/rclcpy/Publisher.c +msgid "Publishers can only be created from a parent node" +msgstr "" + #: shared-bindings/digitalio/DigitalInOut.c msgid "Pull not used when direction is output." msgstr "Pull niet gebruikt wanneer de richting output is." @@ -1858,10 +1892,30 @@ msgstr "RNG DeInit Fout" msgid "RNG Init Error" msgstr "RNG Init Fout" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS failed to initialize. Is agent connected?" +msgstr "" + +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS internal setup failure" +msgstr "" + +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS memory allocator failure" +msgstr "" + +#: ports/espressif/common-hal/rclcpy/Node.c +msgid "ROS node failed to initialize" +msgstr "" + +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "ROS topic failed to initialize" +msgstr "" + #: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c #: ports/nordic/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c msgid "RS485" -msgstr "" +msgstr "RS485" #: ports/espressif/common-hal/busio/UART.c #: ports/mimxrt10xx/common-hal/busio/UART.c @@ -1893,7 +1947,7 @@ msgstr "" #: supervisor/shared/bluetooth/bluetooth.c msgid "Reconnecting" -msgstr "" +msgstr "Opnieuw aansluiten" #: shared-bindings/epaperdisplay/EPaperDisplay.c msgid "Refresh too soon" @@ -1989,6 +2043,7 @@ msgstr "Slice en waarde hebben verschillende lengtes." #: shared-bindings/displayio/TileGrid.c #: shared-bindings/memorymonitor/AllocationSize.c #: shared-bindings/pulseio/PulseIn.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c msgid "Slices not supported" msgstr "Slices niet ondersteund" @@ -2056,7 +2111,9 @@ msgstr "" msgid "Tile height must exactly divide bitmap height" msgstr "Tile hoogte moet exact de bitmap hoogte verdelen" -#: shared-bindings/displayio/TileGrid.c shared-module/displayio/TileGrid.c +#: shared-bindings/displayio/TileGrid.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-module/displayio/TileGrid.c msgid "Tile index out of bounds" msgstr "Tile index buiten bereik" @@ -2064,6 +2121,10 @@ msgstr "Tile index buiten bereik" msgid "Tile width must exactly divide bitmap width" msgstr "Tile breedte moet exact de bitmap breedte verdelen" +#: shared-module/tilepalettemapper/TilePaletteMapper.c +msgid "TilePaletteMapper may only be bound to a TileGrid once" +msgstr "" + #: shared-bindings/alarm/time/TimeAlarm.c msgid "Time is in the past." msgstr "Tijdstip ligt in het verleden." @@ -2131,7 +2192,7 @@ msgstr "" #: main.c msgid "UID:" -msgstr "" +msgstr "UID:" #: shared-module/usb_hid/Device.c msgid "USB busy" @@ -2292,10 +2353,6 @@ msgstr "" msgid "Unsupported display bus type" msgstr "Niet-ondersteund beeldscherm bus type" -#: shared-module/audiocore/WaveFile.c -msgid "Unsupported format" -msgstr "Niet-ondersteunde format" - #: shared-bindings/hashlib/__init__.c msgid "Unsupported hash algorithm" msgstr "" @@ -2352,11 +2409,13 @@ msgstr "" #: supervisor/shared/web_workflow/web_workflow.c msgid "Wi-Fi: " -msgstr "" +msgstr "Wi-Fi: " +#: ports/espressif/common-hal/wifi/Radio.c #: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "Wifi is not enabled" -msgstr "" +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "WiFi is not enabled" +msgstr "WiFi is niet ingeschakeld" #: main.c msgid "Woken up by alarm.\n" @@ -2591,9 +2650,16 @@ msgstr "" msgid "bits must be 32 or less" msgstr "" -#: shared-bindings/audiodelays/Echo.c shared-bindings/audiodelays/PitchShift.c +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "bits_per_sample must be 16" +msgstr "" + +#: shared-bindings/audiodelays/Chorus.c shared-bindings/audiodelays/Echo.c +#: shared-bindings/audiodelays/MultiTapDelay.c +#: shared-bindings/audiodelays/PitchShift.c #: shared-bindings/audiofilters/Distortion.c -#: shared-bindings/audiofilters/Filter.c shared-bindings/audiomixer/Mixer.c +#: shared-bindings/audiofilters/Filter.c shared-bindings/audiofilters/Phaser.c +#: shared-bindings/audiomixer/Mixer.c msgid "bits_per_sample must be 8 or 16" msgstr "bits_per_sample moet 8 of 16 zijn" @@ -3136,7 +3202,7 @@ msgid "format" msgstr "" #: py/objstr.c -msgid "format requires a dict" +msgid "format needs a dict" msgstr "format vereist een dict" #: py/objdeque.c @@ -3261,7 +3327,7 @@ msgstr "" #: ports/espressif/common-hal/pulseio/PulseIn.c #: shared-bindings/bitmaptools/__init__.c msgid "index out of range" -msgstr "index is buiten bereik" +msgstr "index buiten bereik" #: py/obj.c msgid "indices must be integers" @@ -3598,7 +3664,7 @@ msgid "must use keyword argument for key function" msgstr "voor sleutelfunctie moet een trefwoordargument gebruikt worden" #: py/runtime.c -msgid "name '%q' is not defined" +msgid "name '%q' isn't defined" msgstr "naam '%q' is niet gedefinieerd" #: py/runtime.c @@ -4016,6 +4082,10 @@ msgstr "roll argument moet een ndarray zijn" msgid "rsplit(None,n)" msgstr "rsplit(None,n)" +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "samples_signed must be true" +msgstr "" + #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c #: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "sampling rate out of range" @@ -4235,11 +4305,11 @@ msgid "tx and rx cannot both be None" msgstr "tx en rx kunnen niet beiden None zijn" #: py/objtype.c -msgid "type '%q' is not an acceptable base type" +msgid "type '%q' isn't an acceptable base type" msgstr "type '%q' is geen aanvaardbaar basistype" #: py/objtype.c -msgid "type is not an acceptable base type" +msgid "type isn't an acceptable base type" msgstr "type is geen aanvaardbaar basistype" #: py/runtime.c @@ -4301,7 +4371,9 @@ msgstr "" msgid "unreadable attribute" msgstr "onleesbaar attribuut" -#: shared-bindings/displayio/TileGrid.c shared-bindings/vectorio/VectorShape.c +#: shared-bindings/displayio/TileGrid.c shared-bindings/terminalio/Terminal.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-bindings/vectorio/VectorShape.c msgid "unsupported %q type" msgstr "niet ondersteund %q type" @@ -4379,15 +4451,9 @@ msgstr "" msgid "width must be greater than zero" msgstr "breedte moet groter dan nul zijn" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/raspberrypi/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "wifi is not enabled" -msgstr "" - #: ports/raspberrypi/common-hal/wifi/Monitor.c msgid "wifi.Monitor not available" -msgstr "" +msgstr "wifi.monitor niet beschikbaar" #: shared-bindings/_bleio/Adapter.c msgid "window must be <= interval" @@ -4447,6 +4513,9 @@ msgstr "zi moet van type float zijn" msgid "zi must be of shape (n_section, 2)" msgstr "zi moet vorm (n_section, 2) hebben" +#~ msgid "Unsupported format" +#~ msgstr "Niet-ondersteunde format" + #~ msgid "Data chunk must follow fmt chunk" #~ msgstr "Data chunk moet gevolgd worden door fmt chunk" @@ -4672,13 +4741,13 @@ msgstr "zi moet vorm (n_section, 2) hebben" #~ msgid "'%s' object does not support item deletion" #~ msgstr "'%s' object ondersteunt item verwijdering niet" -#~ msgid "'%s' object is not an iterator" +#~ msgid "'%s' object isn't an iterator" #~ msgstr "'%s' object is geen iterator" #~ msgid "'%s' object is not callable" #~ msgstr "'%s' object is niet aanroepbaar" -#~ msgid "'%s' object is not iterable" +#~ msgid "'%s' object isn't iterable" #~ msgstr "'%s' object is niet itereerbaar" #~ msgid "'%s' object is not subscriptable" @@ -4696,7 +4765,7 @@ msgstr "zi moet vorm (n_section, 2) hebben" #~ msgid "'continue' outside loop" #~ msgstr "'continue' buiten de loop" -#~ msgid "'coroutine' object is not an iterator" +#~ msgid "'coroutine' object isn't an iterator" #~ msgstr "'coroutine' object is geen iterator" #~ msgid "ADC2 is being used by WiFi" @@ -5473,7 +5542,7 @@ msgstr "zi moet vorm (n_section, 2) hebben" #~ msgid "firstbit must be MSB" #~ msgstr "het eerste bit moet het MSB zijn" -#~ msgid "function does not take keyword arguments" +#~ msgid "function doesn't take keyword arguments" #~ msgstr "functie accepteert geen keyword argumenten" #~ msgid "function is implemented for scalars and ndarrays only" @@ -5551,7 +5620,7 @@ msgstr "zi moet vorm (n_section, 2) hebben" #~ msgid "n must be between 0, and 9" #~ msgstr "n moet tussen 0 en 9 liggen" -#~ msgid "name reused for argument" +#~ msgid "argument name reused" #~ msgstr "naam hergebruikt voor argument" #~ msgid "no available NIC" diff --git a/locale/pl.po b/locale/pl.po index 9906f441380..2e55f983e00 100644 --- a/locale/pl.po +++ b/locale/pl.po @@ -7,16 +7,16 @@ msgstr "" "Project-Id-Version: \n" "Report-Msgid-Bugs-To: \n" "POT-Creation-Date: 2021-01-04 12:55-0600\n" -"PO-Revision-Date: 2023-11-16 15:03+0000\n" -"Last-Translator: Szymon Jakubiak \n" +"PO-Revision-Date: 2025-08-06 18:01+0000\n" +"Last-Translator: MAE \n" "Language-Team: pl\n" "Language: pl\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" -"Plural-Forms: nplurals=3; plural=n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 " -"|| n%100>=20) ? 1 : 2;\n" -"X-Generator: Weblate 5.2\n" +"Plural-Forms: nplurals=3; plural=(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 " +"|| n%100>=20) ? 1 : 2);\n" +"X-Generator: Weblate 5.13-dev\n" #: main.c msgid "" @@ -31,6 +31,8 @@ msgid "" "\n" "Code stopped by auto-reload. Reloading soon.\n" msgstr "" +"\n" +"Wykonywanie zatrzymane przez auto-reload. Wkrótce nastąpi przeładowanie.\n" #: supervisor/shared/safe_mode.c msgid "" @@ -38,6 +40,9 @@ msgid "" "Please file an issue with your program at github.com/adafruit/circuitpython/" "issues." msgstr "" +"\n" +"Proszę dodaj problem z twoim programem na github.com/adafruit/circuitpython/" +"issues." #: supervisor/shared/safe_mode.c msgid "" @@ -85,22 +90,24 @@ msgstr "%%c wymaga int lub char" msgid "" "%d address pins, %d rgb pins and %d tiles indicate a height of %d, not %d" msgstr "" +"%d pinów adresowalnych, %d pinów rgb oraz %d płytek wskazują na wysokość %d, " +"nie %d" #: shared-bindings/microcontroller/Pin.c msgid "%q and %q contain duplicate pins" msgstr "%q oraz %q zawierają zduplikowane piny" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: shared-bindings/audioio/AudioOut.c msgid "%q and %q must be different" msgstr "%q and %q muszą być różne" #: ports/atmel-samd/common-hal/audiobusio/I2SOut.c msgid "%q and %q must share a clock unit" -msgstr "" +msgstr "%q i %q muszą współdzielić jednostkę zegara" #: ports/nordic/common-hal/watchdog/WatchDogTimer.c msgid "%q cannot be changed once mode is set to %q" -msgstr "" +msgstr "%q nie może zostać zmienione po ustawieniu trybu %q" #: shared-bindings/microcontroller/Pin.c msgid "%q contains duplicate pins" @@ -110,6 +117,10 @@ msgstr "%q zawiera zduplikowane piny" msgid "%q failure: %d" msgstr "%q niepowodzenie: %d" +#: shared-module/audiodelays/MultiTapDelay.c +msgid "%q in %q must be of type %q or %q, not %q" +msgstr "%q w %q musi być typu %q lub %q, nie %q" + #: py/argcheck.c shared-module/audiofilters/Filter.c msgid "%q in %q must be of type %q, not %q" msgstr "%q w %q musi być typu %q, a nie %q" @@ -156,19 +167,19 @@ msgstr "długość %q musi być w zakresie od %d do %d" #: py/argcheck.c msgid "%q length must be <= %d" -msgstr "" +msgstr "długość %q musi być <= %d" #: py/argcheck.c msgid "%q length must be >= %d" -msgstr "" +msgstr "długość %q musi być >= %d" -#: py/modsys.c py/objmodule.c py/runtime.c +#: py/modsys.c py/runtime.c msgid "%q moved from %q to %q" msgstr "" #: py/argcheck.c msgid "%q must be %d" -msgstr "" +msgstr "%q musi być %d" #: py/argcheck.c shared-bindings/busdisplay/BusDisplay.c #: shared-bindings/displayio/Bitmap.c @@ -176,16 +187,16 @@ msgstr "" #: shared-bindings/is31fl3741/FrameBuffer.c #: shared-bindings/rgbmatrix/RGBMatrix.c msgid "%q must be %d-%d" -msgstr "" +msgstr "%q musi być %d-%d" #: shared-bindings/busdisplay/BusDisplay.c msgid "%q must be 1 when %q is True" -msgstr "" +msgstr "%q musi wynosić 1, gdy %q jest True" #: py/argcheck.c shared-bindings/gifio/GifWriter.c #: shared-module/gifio/OnDiskGif.c msgid "%q must be <= %d" -msgstr "" +msgstr "%q musi być <= %d" #: ports/espressif/common-hal/watchdog/WatchDogTimer.c msgid "%q must be <= %u" @@ -193,7 +204,7 @@ msgstr "" #: py/argcheck.c msgid "%q must be >= %d" -msgstr "" +msgstr "%q musi być >= %d" #: shared-bindings/analogbufio/BufferedIn.c msgid "%q must be a bytearray or array of type 'H' or 'B'" @@ -223,7 +234,7 @@ msgstr "" #: shared-bindings/bitmapfilter/__init__.c shared-bindings/canio/CAN.c #: shared-bindings/digitalio/Pull.c shared-bindings/supervisor/__init__.c #: shared-module/audiofilters/Filter.c shared-module/displayio/__init__.c -#: shared-module/synthio/Biquad.c shared-module/synthio/Synthesizer.c +#: shared-module/synthio/Synthesizer.c msgid "%q must be of type %q or %q, not %q" msgstr "" @@ -232,6 +243,7 @@ msgid "%q must be of type %q, %q, or %q, not %q" msgstr "" #: py/argcheck.c py/runtime.c shared-bindings/bitmapfilter/__init__.c +#: shared-module/audiodelays/MultiTapDelay.c shared-module/synthio/Note.c #: shared-module/synthio/__init__.c msgid "%q must be of type %q, not %q" msgstr "%q musi być typu %q, a nie %q" @@ -312,7 +324,7 @@ msgid "'%q' object does not support '%q'" msgstr "Obiekt '%q' nie wspiera '%q'" #: py/runtime.c -msgid "'%q' object is not an iterator" +msgid "'%q' object isn't an iterator" msgstr "Obiekt '%q' nie jest iteratorem" #: py/objtype.c py/runtime.c shared-module/atexit/__init__.c @@ -320,7 +332,7 @@ msgid "'%q' object is not callable" msgstr "Obiekt '%q' nie jest wywoływalny" #: py/runtime.c -msgid "'%q' object is not iterable" +msgid "'%q' object isn't iterable" msgstr "Obiekt '%q' nie jest iterowalny" #: py/emitinlinethumb.c py/emitinlinextensa.c @@ -561,7 +573,7 @@ msgstr "" #: ports/espressif/common-hal/_bleio/__init__.c msgid "Already in progress" -msgstr "" +msgstr "Już trwa" #: ports/espressif/bindings/espnow/ESPNow.c #: ports/espressif/common-hal/espulp/ULP.c @@ -803,7 +815,7 @@ msgid "Cannot record to a file" msgstr "Nie można nagrać do pliku" #: shared-module/storage/__init__.c -msgid "Cannot remount '/' when visible via USB." +msgid "Cannot remount path when visible via USB." msgstr "" #: shared-bindings/digitalio/DigitalInOut.c @@ -859,6 +871,10 @@ msgstr "" msgid "Coordinate arrays types have different sizes" msgstr "" +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "Could not publish to ROS topic" +msgstr "" + #: shared-bindings/_bleio/Adapter.c msgid "Could not set address" msgstr "Nie można ustawić adresu" @@ -871,6 +887,11 @@ msgstr "Nie można rozpocząć przerwania, RX jest zajęty" msgid "Couldn't allocate decoder" msgstr "Nie udało się przydzielić dekodera" +#: ports/espressif/common-hal/rclcpy/__init__.c +#, c-format +msgid "Critical ROS failure during soft reboot, reset required: %d" +msgstr "" + #: ports/stm/common-hal/analogio/AnalogOut.c msgid "DAC Channel Init Error" msgstr "Błąd inicjalizacji kanału DAC" @@ -1069,6 +1090,7 @@ msgstr "Nie udało się zapisać wewnętrznej pamięci flash." msgid "File exists" msgstr "Plik istnieje" +#: shared-bindings/supervisor/__init__.c shared-module/lvfontio/OnDiskFont.c #: shared-module/os/getenv.c msgid "File not found" msgstr "Plik nie znaleziony" @@ -1104,7 +1126,7 @@ msgstr "" "W bitmapie wejściowej dla przestrzeni kolorów RGB piksel musi składać się z " "16 bitów" -#: ports/cxd56/common-hal/camera/Camera.c +#: ports/cxd56/common-hal/camera/Camera.c shared-module/audiocore/WaveFile.c msgid "Format not supported" msgstr "Nie wspierany format" @@ -1270,7 +1292,9 @@ msgstr "" #: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c py/argcheck.c #: shared-bindings/digitalio/DigitalInOut.c #: shared-bindings/epaperdisplay/EPaperDisplay.c shared-bindings/pwmio/PWMOut.c +#: shared-bindings/supervisor/__init__.c #: shared-module/aurora_epaper/aurora_framebuffer.c +#: shared-module/lvfontio/OnDiskFont.c msgid "Invalid %q" msgstr "Nieprawidłowe %q" @@ -1303,6 +1327,10 @@ msgstr "" msgid "Invalid MAC address" msgstr "" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "Invalid ROS domain ID" +msgstr "" + #: ports/espressif/common-hal/espidf/__init__.c py/moderrno.c msgid "Invalid argument" msgstr "Zły argument" @@ -1392,6 +1420,11 @@ msgstr "" msgid "MITM security not supported" msgstr "" +#: ports/stm/common-hal/sdioio/SDCard.c +#, c-format +msgid "MMC/SDIO Clock Error %x" +msgstr "" + #: shared-bindings/is31fl3741/IS31FL3741.c msgid "Mapping must be a tuple" msgstr "" @@ -1578,6 +1611,10 @@ msgstr "" msgid "No pulldown on pin; 1Mohm recommended" msgstr "Brak rozwijanego menu na pinezce; 1Mohm zalecane" +#: shared-module/touchio/TouchIn.c +msgid "No pullup on pin; 1Mohm recommended" +msgstr "" + #: py/moderrno.c msgid "No space left on device" msgstr "Brak miejsca" @@ -1737,7 +1774,7 @@ msgstr "" #: ports/stm/common-hal/pwmio/PWMOut.c msgid "PWM restart" -msgstr "" +msgstr "Ponowne uruchomienie PWM" #: ports/raspberrypi/common-hal/countio/Counter.c msgid "PWM slice already in use" @@ -1753,7 +1790,7 @@ msgstr "" #: shared-module/jpegio/JpegDecoder.c msgid "Parameter error" -msgstr "" +msgstr "Błąd parametru" #: ports/espressif/common-hal/audiobusio/__init__.c msgid "Peripheral in use" @@ -1850,6 +1887,10 @@ msgstr "" #: ports/espressif/common-hal/espulp/ULP.c msgid "Program too long" +msgstr "Program zbyt długi" + +#: shared-bindings/rclcpy/Publisher.c +msgid "Publishers can only be created from a parent node" msgstr "" #: shared-bindings/digitalio/DigitalInOut.c @@ -1872,10 +1913,30 @@ msgstr "Błąd RNG DeInit" msgid "RNG Init Error" msgstr "Błąd inicjalizacji RNG" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS failed to initialize. Is agent connected?" +msgstr "" + +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS internal setup failure" +msgstr "" + +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS memory allocator failure" +msgstr "" + +#: ports/espressif/common-hal/rclcpy/Node.c +msgid "ROS node failed to initialize" +msgstr "" + +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "ROS topic failed to initialize" +msgstr "" + #: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c #: ports/nordic/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c msgid "RS485" -msgstr "" +msgstr "RS485" #: ports/espressif/common-hal/busio/UART.c #: ports/mimxrt10xx/common-hal/busio/UART.c @@ -1907,7 +1968,7 @@ msgstr "Otrzymana odpowiedź była nieprawidłowa" #: supervisor/shared/bluetooth/bluetooth.c msgid "Reconnecting" -msgstr "" +msgstr "Ponowne połączenie" #: shared-bindings/epaperdisplay/EPaperDisplay.c msgid "Refresh too soon" @@ -1992,7 +2053,7 @@ msgstr "" #: ports/cxd56/common-hal/camera/Camera.c msgid "Size not supported" -msgstr "" +msgstr "Rozmiar nieobsługiwany" #: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c #: shared-bindings/nvm/ByteArray.c @@ -2003,6 +2064,7 @@ msgstr "Fragment i wartość są różnych długości." #: shared-bindings/displayio/TileGrid.c #: shared-bindings/memorymonitor/AllocationSize.c #: shared-bindings/pulseio/PulseIn.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c msgid "Slices not supported" msgstr "Fragmenty nieobsługiwane" @@ -2070,7 +2132,9 @@ msgstr "" msgid "Tile height must exactly divide bitmap height" msgstr "Wysokość bitmapy musi być wielokrotnością wysokości kafelka" -#: shared-bindings/displayio/TileGrid.c shared-module/displayio/TileGrid.c +#: shared-bindings/displayio/TileGrid.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-module/displayio/TileGrid.c msgid "Tile index out of bounds" msgstr "" @@ -2078,6 +2142,10 @@ msgstr "" msgid "Tile width must exactly divide bitmap width" msgstr "Szerokość bitmapy musi być wielokrotnością szerokości kafelka" +#: shared-module/tilepalettemapper/TilePaletteMapper.c +msgid "TilePaletteMapper may only be bound to a TileGrid once" +msgstr "" + #: shared-bindings/alarm/time/TimeAlarm.c msgid "Time is in the past." msgstr "" @@ -2116,7 +2184,7 @@ msgstr "" #: ports/raspberrypi/common-hal/alarm/touch/TouchAlarm.c #: ports/stm/common-hal/alarm/touch/TouchAlarm.c msgid "Touch alarms not available" -msgstr "" +msgstr "Alarmy dotykowe niedostępne" #: py/obj.c msgid "Traceback (most recent call last):\n" @@ -2145,7 +2213,7 @@ msgstr "" #: main.c msgid "UID:" -msgstr "" +msgstr "UID:" #: shared-module/usb_hid/Device.c msgid "USB busy" @@ -2161,7 +2229,7 @@ msgstr "" #: shared-module/usb_hid/Device.c msgid "USB error" -msgstr "" +msgstr "Błąd USB" #: shared-bindings/_bleio/UUID.c msgid "UUID integer value must be 0-0xffff" @@ -2227,7 +2295,7 @@ msgstr "" #: shared-bindings/alarm/SleepMemory.c msgid "Unable to write to sleep_memory." -msgstr "" +msgstr "Nie można zapisać do sleep_memory." #: ports/nordic/common-hal/_bleio/UUID.c msgid "Unexpected nrfx uuid type" @@ -2306,10 +2374,6 @@ msgstr "" msgid "Unsupported display bus type" msgstr "Zły typ magistrali wyświetlaczy" -#: shared-module/audiocore/WaveFile.c -msgid "Unsupported format" -msgstr "Zły format" - #: shared-bindings/hashlib/__init__.c msgid "Unsupported hash algorithm" msgstr "" @@ -2322,7 +2386,7 @@ msgstr "" #: ports/espressif/common-hal/_bleio/Adapter.c #: ports/espressif/common-hal/dualbank/__init__.c msgid "Update failed" -msgstr "" +msgstr "Aktualizacja nie powiodła się" #: ports/espressif/common-hal/_bleio/Characteristic.c #: ports/nordic/common-hal/_bleio/Characteristic.c @@ -2361,14 +2425,21 @@ msgid "" "\n" "To list built-in modules type `help(\"modules\")`.\n" msgstr "" +"Witamy w Adafruit CircuitPython %s!\n" +"\n" +"Odwiedź circuitpython.org po więcej informacji.\n" +"\n" +"Aby wyświetlić listę wbudowanych modułów wpisz `help(„modules”)`.\n" #: supervisor/shared/web_workflow/web_workflow.c msgid "Wi-Fi: " -msgstr "" +msgstr "Wi-Fi: " +#: ports/espressif/common-hal/wifi/Radio.c #: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "Wifi is not enabled" -msgstr "" +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "WiFi is not enabled" +msgstr "WiFi nie jest włączone" #: main.c msgid "Woken up by alarm.\n" @@ -2589,7 +2660,7 @@ msgstr "brak dwu-argumentowego operatora %q" #: ports/espressif/common-hal/audiobusio/PDMIn.c msgid "bit_depth must be 8, 16, 24, or 32." -msgstr "" +msgstr "bit_depth musi wynosić 8, 16, 24 lub 32." #: shared-module/bitmapfilter/__init__.c msgid "bitmap size and depth must match" @@ -2601,11 +2672,18 @@ msgstr "" #: extmod/modrandom.c msgid "bits must be 32 or less" -msgstr "" +msgstr "bitów musi wynosić 32 lub mniej" + +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "bits_per_sample must be 16" +msgstr "bits_per_sample musi wynosić 16" -#: shared-bindings/audiodelays/Echo.c shared-bindings/audiodelays/PitchShift.c +#: shared-bindings/audiodelays/Chorus.c shared-bindings/audiodelays/Echo.c +#: shared-bindings/audiodelays/MultiTapDelay.c +#: shared-bindings/audiodelays/PitchShift.c #: shared-bindings/audiofilters/Distortion.c -#: shared-bindings/audiofilters/Filter.c shared-bindings/audiomixer/Mixer.c +#: shared-bindings/audiofilters/Filter.c shared-bindings/audiofilters/Phaser.c +#: shared-bindings/audiomixer/Mixer.c msgid "bits_per_sample must be 8 or 16" msgstr "bits_per_sample musi być 8 lub 16" @@ -2809,7 +2887,7 @@ msgstr "" #: extmod/modasyncio.c msgid "can't wait" -msgstr "" +msgstr "nie mogę się doczekać" #: extmod/ulab/code/ndarray.c msgid "cannot assign new shape" @@ -2996,7 +3074,7 @@ msgstr "" #: extmod/ulab/code/numpy/create.c msgid "divide by zero" -msgstr "" +msgstr "dziel przez zero" #: py/runtime.c msgid "division by zero" @@ -3016,7 +3094,7 @@ msgstr "puste" #: extmod/ulab/code/numpy/io/io.c msgid "empty file" -msgstr "" +msgstr "puste plik" #: extmod/modasyncio.c extmod/modheapq.c msgid "empty heap" @@ -3135,7 +3213,7 @@ msgstr "float zbyt wielki" #: py/nativeglue.c msgid "float unsupported" -msgstr "" +msgstr "float nieobsługiwany" #: shared-bindings/_stage/Text.c msgid "font must be 2048 bytes long" @@ -3143,10 +3221,10 @@ msgstr "font musi mieć 2048 bajtów długości" #: extmod/moddeflate.c msgid "format" -msgstr "" +msgstr "format" #: py/objstr.c -msgid "format requires a dict" +msgid "format needs a dict" msgstr "format wymaga słownika" #: py/objdeque.c @@ -3244,7 +3322,7 @@ msgstr "" #: py/persistentcode.c msgid "incompatible .mpy file" -msgstr "" +msgstr "niekompatybilny plik .mpy" #: py/objstr.c msgid "incomplete format" @@ -3606,7 +3684,7 @@ msgid "must use keyword argument for key function" msgstr "funkcja key musi być podana jako argument nazwany" #: py/runtime.c -msgid "name '%q' is not defined" +msgid "name '%q' isn't defined" msgstr "nazwa '%q' niezdefiniowana" #: py/runtime.c @@ -3656,7 +3734,7 @@ msgstr "" #: shared-module/sdcardio/SDCard.c msgid "no SD card" -msgstr "" +msgstr "brak karty SD" #: py/vm.c msgid "no active exception to reraise" @@ -3737,7 +3815,7 @@ msgstr "liczba punktów musi wynosić co najmniej 2" #: py/builtinhelp.c msgid "object " -msgstr "" +msgstr "obiekt " #: py/obj.c #, c-format @@ -3791,7 +3869,7 @@ msgstr "łańcuch o nieparzystej długości" #: supervisor/shared/web_workflow/web_workflow.c msgid "off" -msgstr "" +msgstr "wył" #: extmod/ulab/code/utils/utils.c msgid "offset is too large" @@ -4024,6 +4102,10 @@ msgstr "" msgid "rsplit(None,n)" msgstr "rsplit(None,n)" +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "samples_signed must be true" +msgstr "" + #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c #: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "sampling rate out of range" @@ -4243,11 +4325,11 @@ msgid "tx and rx cannot both be None" msgstr "tx i rx nie mogą być oba None" #: py/objtype.c -msgid "type '%q' is not an acceptable base type" +msgid "type '%q' isn't an acceptable base type" msgstr "typ '%q' nie może być bazowy" #: py/objtype.c -msgid "type is not an acceptable base type" +msgid "type isn't an acceptable base type" msgstr "typ nie może być bazowy" #: py/runtime.c @@ -4309,7 +4391,9 @@ msgstr "" msgid "unreadable attribute" msgstr "nieczytelny atrybut" -#: shared-bindings/displayio/TileGrid.c shared-bindings/vectorio/VectorShape.c +#: shared-bindings/displayio/TileGrid.c shared-bindings/terminalio/Terminal.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-bindings/vectorio/VectorShape.c msgid "unsupported %q type" msgstr "zły typ %q" @@ -4387,12 +4471,6 @@ msgstr "" msgid "width must be greater than zero" msgstr "szerokość musi być większa niż zero" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/raspberrypi/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "wifi is not enabled" -msgstr "" - #: ports/raspberrypi/common-hal/wifi/Monitor.c msgid "wifi.Monitor not available" msgstr "" @@ -4455,6 +4533,9 @@ msgstr "" msgid "zi must be of shape (n_section, 2)" msgstr "" +#~ msgid "Unsupported format" +#~ msgstr "Zły format" + #~ msgid "Data chunk must follow fmt chunk" #~ msgstr "Fragment danych musi następować po fragmencie fmt" @@ -4652,13 +4733,13 @@ msgstr "" #~ msgid "'%s' object does not support item deletion" #~ msgstr "'%s' obiekt nie wspiera usuwania elementów" -#~ msgid "'%s' object is not an iterator" +#~ msgid "'%s' object isn't an iterator" #~ msgstr "'%s' obiekt nie jest iteratorem" #~ msgid "'%s' object is not callable" #~ msgstr "'%s' nie można wywoływać obiektu" -#~ msgid "'%s' object is not iterable" +#~ msgid "'%s' object isn't iterable" #~ msgstr "'%s' nie można iterować po obiekcie" #~ msgid "'%s' object is not subscriptable" @@ -5422,7 +5503,7 @@ msgstr "" #~ msgid "firstbit must be MSB" #~ msgstr "firstbit musi być MSB" -#~ msgid "function does not take keyword arguments" +#~ msgid "function doesn't take keyword arguments" #~ msgstr "funkcja nie bierze argumentów nazwanych" #~ msgid "int() arg 2 must be >= 2 and <= 36" @@ -5470,7 +5551,7 @@ msgstr "" #~ msgid "name must be a string" #~ msgstr "nazwa musi być łańcuchem" -#~ msgid "name reused for argument" +#~ msgid "argument name reused" #~ msgstr "nazwa użyta ponownie jako argument" #~ msgid "no available NIC" diff --git a/locale/pt_BR.po b/locale/pt_BR.po index 1c9d5545618..5bb98dc74c5 100644 --- a/locale/pt_BR.po +++ b/locale/pt_BR.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: 2025-03-09 18:40+0000\n" -"Last-Translator: Wellington Terumi Uemura \n" +"PO-Revision-Date: 2025-06-09 12:01+0000\n" +"Last-Translator: MAE \n" "Language-Team: \n" "Language: pt_BR\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 5.10.3-dev\n" +"X-Generator: Weblate 5.12-dev\n" #: main.c msgid "" @@ -95,7 +95,7 @@ msgstr "" msgid "%q and %q contain duplicate pins" msgstr "%q e %q contêm pinos duplicados" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: shared-bindings/audioio/AudioOut.c msgid "%q and %q must be different" msgstr "%q e %q devem ser diferentes" @@ -115,6 +115,10 @@ msgstr "%q contém pinos duplicados" msgid "%q failure: %d" msgstr "%q falha: %d" +#: shared-module/audiodelays/MultiTapDelay.c +msgid "%q in %q must be of type %q or %q, not %q" +msgstr "%q em %q deve ser do tipo %q ou %q, não %q" + #: py/argcheck.c shared-module/audiofilters/Filter.c msgid "%q in %q must be of type %q, not %q" msgstr "%q em %q deve ser do tipo %q e não %q" @@ -167,7 +171,7 @@ msgstr "o comprimento de %q deve ser <= %d" msgid "%q length must be >= %d" msgstr "o comprimento de %q deve ser >= %d" -#: py/modsys.c py/objmodule.c py/runtime.c +#: py/modsys.c py/runtime.c msgid "%q moved from %q to %q" msgstr "%q foi movido de %q para %q" @@ -228,7 +232,7 @@ msgstr "%q deve ser um múltiplo de 8." #: shared-bindings/bitmapfilter/__init__.c shared-bindings/canio/CAN.c #: shared-bindings/digitalio/Pull.c shared-bindings/supervisor/__init__.c #: shared-module/audiofilters/Filter.c shared-module/displayio/__init__.c -#: shared-module/synthio/Biquad.c shared-module/synthio/Synthesizer.c +#: shared-module/synthio/Synthesizer.c msgid "%q must be of type %q or %q, not %q" msgstr "%q deve ser do tipo %q ou %q e não %q" @@ -237,6 +241,7 @@ msgid "%q must be of type %q, %q, or %q, not %q" msgstr "%q deve ser do tipo %q, %q ou %q e não %q" #: py/argcheck.c py/runtime.c shared-bindings/bitmapfilter/__init__.c +#: shared-module/audiodelays/MultiTapDelay.c shared-module/synthio/Note.c #: shared-module/synthio/__init__.c msgid "%q must be of type %q, not %q" msgstr "%q deve ser do tipo %q e não %q" @@ -317,7 +322,7 @@ msgid "'%q' object does not support '%q'" msgstr "O objeto '%q' não suporta '%q'" #: py/runtime.c -msgid "'%q' object is not an iterator" +msgid "'%q' object isn't an iterator" msgstr "O objeto '%q' não é um iterador" #: py/objtype.c py/runtime.c shared-module/atexit/__init__.c @@ -325,7 +330,7 @@ msgid "'%q' object is not callable" msgstr "O objeto '%s' não é invocável" #: py/runtime.c -msgid "'%q' object is not iterable" +msgid "'%q' object isn't iterable" msgstr "O objeto '%q' não é iterável" #: py/emitinlinethumb.c py/emitinlinextensa.c @@ -814,8 +819,8 @@ msgid "Cannot record to a file" msgstr "Não é possível gravar em um arquivo" #: shared-module/storage/__init__.c -msgid "Cannot remount '/' when visible via USB." -msgstr "Não é possível montar '/' quando estiver visível pelo USB." +msgid "Cannot remount path when visible via USB." +msgstr "" #: shared-bindings/digitalio/DigitalInOut.c msgid "Cannot set value when direction is input." @@ -869,6 +874,10 @@ msgstr "As coordenadas das matrizes possuem comprimentos diferentes" msgid "Coordinate arrays types have different sizes" msgstr "Os tipos das coordenadas das matrizes possuem tamanhos diferentes" +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "Could not publish to ROS topic" +msgstr "" + #: shared-bindings/_bleio/Adapter.c msgid "Could not set address" msgstr "Não foi possível definir o endereço" @@ -881,6 +890,11 @@ msgstr "Não foi possível iniciar a interrupção, RX ocupado" msgid "Couldn't allocate decoder" msgstr "Não foi possível alocar o decodificador" +#: ports/espressif/common-hal/rclcpy/__init__.c +#, c-format +msgid "Critical ROS failure during soft reboot, reset required: %d" +msgstr "" + #: ports/stm/common-hal/analogio/AnalogOut.c msgid "DAC Channel Init Error" msgstr "Erro de Inicialização do Canal DAC" @@ -1080,6 +1094,7 @@ msgstr "Falha ao gravar o flash interno." msgid "File exists" msgstr "Arquivo já existe" +#: shared-bindings/supervisor/__init__.c shared-module/lvfontio/OnDiskFont.c #: shared-module/os/getenv.c msgid "File not found" msgstr "Arquivo não encontrado" @@ -1112,7 +1127,7 @@ msgid "For RGB colorspaces, input bitmap must have 16 bits per pixel" msgstr "" "Para espaços de cor RGB, o bitmap da entrada deve ter 16 bits por pixel" -#: ports/cxd56/common-hal/camera/Camera.c +#: ports/cxd56/common-hal/camera/Camera.c shared-module/audiocore/WaveFile.c msgid "Format not supported" msgstr "O formato não é suportado" @@ -1284,7 +1299,9 @@ msgstr "Interrompido pela função de saída" #: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c py/argcheck.c #: shared-bindings/digitalio/DigitalInOut.c #: shared-bindings/epaperdisplay/EPaperDisplay.c shared-bindings/pwmio/PWMOut.c +#: shared-bindings/supervisor/__init__.c #: shared-module/aurora_epaper/aurora_framebuffer.c +#: shared-module/lvfontio/OnDiskFont.c msgid "Invalid %q" msgstr "%q Inválido" @@ -1317,6 +1334,10 @@ msgstr "BSSID Inválido" msgid "Invalid MAC address" msgstr "Endereço MAC inválido" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "Invalid ROS domain ID" +msgstr "" + #: ports/espressif/common-hal/espidf/__init__.c py/moderrno.c msgid "Invalid argument" msgstr "Argumento inválido" @@ -1407,6 +1428,11 @@ msgstr "O endereço MAC era inválido" msgid "MITM security not supported" msgstr "Não há suporte para segurança MITM" +#: ports/stm/common-hal/sdioio/SDCard.c +#, c-format +msgid "MMC/SDIO Clock Error %x" +msgstr "Erro de relógio MMC/SDIO %x" + #: shared-bindings/is31fl3741/IS31FL3741.c msgid "Mapping must be a tuple" msgstr "O mapeamento deve ser uma tupla" @@ -1595,6 +1621,10 @@ msgstr "" msgid "No pulldown on pin; 1Mohm recommended" msgstr "Não há pulldown no pino; É recomendável utilizar um resistor de 1M ohm" +#: shared-module/touchio/TouchIn.c +msgid "No pullup on pin; 1Mohm recommended" +msgstr "" + #: py/moderrno.c msgid "No space left on device" msgstr "Não resta espaço no dispositivo" @@ -1880,6 +1910,10 @@ msgstr "O tamanho do programa é inválido" msgid "Program too long" msgstr "Programa muito longo" +#: shared-bindings/rclcpy/Publisher.c +msgid "Publishers can only be created from a parent node" +msgstr "" + #: shared-bindings/digitalio/DigitalInOut.c msgid "Pull not used when direction is output." msgstr "O Pull não foi usado quando a direção for gerada." @@ -1900,6 +1934,26 @@ msgstr "Erro DeInit RNG" msgid "RNG Init Error" msgstr "Houve um erro na inicialização do RNG" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS failed to initialize. Is agent connected?" +msgstr "" + +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS internal setup failure" +msgstr "" + +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS memory allocator failure" +msgstr "" + +#: ports/espressif/common-hal/rclcpy/Node.c +msgid "ROS node failed to initialize" +msgstr "" + +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "ROS topic failed to initialize" +msgstr "" + #: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c #: ports/nordic/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c msgid "RS485" @@ -2031,6 +2085,7 @@ msgstr "Fatie e avalie os diferentes comprimentos." #: shared-bindings/displayio/TileGrid.c #: shared-bindings/memorymonitor/AllocationSize.c #: shared-bindings/pulseio/PulseIn.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c msgid "Slices not supported" msgstr "Fatiamento não compatível" @@ -2101,7 +2156,9 @@ msgstr "" msgid "Tile height must exactly divide bitmap height" msgstr "A altura do bloco deve dividir exatamente com a altura do bitmap" -#: shared-bindings/displayio/TileGrid.c shared-module/displayio/TileGrid.c +#: shared-bindings/displayio/TileGrid.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-module/displayio/TileGrid.c msgid "Tile index out of bounds" msgstr "O índice do bloco está fora dos limites" @@ -2109,6 +2166,10 @@ msgstr "O índice do bloco está fora dos limites" msgid "Tile width must exactly divide bitmap width" msgstr "A largura do bloco deve dividir exatamente com a largura do bitmap" +#: shared-module/tilepalettemapper/TilePaletteMapper.c +msgid "TilePaletteMapper may only be bound to a TileGrid once" +msgstr "" + #: shared-bindings/alarm/time/TimeAlarm.c msgid "Time is in the past." msgstr "O tempo está no passado." @@ -2344,10 +2405,6 @@ msgstr "Espaço de cor não compatível" msgid "Unsupported display bus type" msgstr "Não há suporte para o tipo do display bus" -#: shared-module/audiocore/WaveFile.c -msgid "Unsupported format" -msgstr "Formato não suportado" - #: shared-bindings/hashlib/__init__.c msgid "Unsupported hash algorithm" msgstr "Sem compatibilidade com o algoritmo de hash" @@ -2411,9 +2468,11 @@ msgstr "" msgid "Wi-Fi: " msgstr "Wi-Fi: " +#: ports/espressif/common-hal/wifi/Radio.c #: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "Wifi is not enabled" -msgstr "O Wi-Fi não está ativado" +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "WiFi is not enabled" +msgstr "O WiFi não está habilitado" #: main.c msgid "Woken up by alarm.\n" @@ -2649,9 +2708,16 @@ msgstr "os tamanhos do bitmap devem coincidir" msgid "bits must be 32 or less" msgstr "bits deve ser 32 ou menos" -#: shared-bindings/audiodelays/Echo.c shared-bindings/audiodelays/PitchShift.c +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "bits_per_sample must be 16" +msgstr "bits_per_sample deve ser 16" + +#: shared-bindings/audiodelays/Chorus.c shared-bindings/audiodelays/Echo.c +#: shared-bindings/audiodelays/MultiTapDelay.c +#: shared-bindings/audiodelays/PitchShift.c #: shared-bindings/audiofilters/Distortion.c -#: shared-bindings/audiofilters/Filter.c shared-bindings/audiomixer/Mixer.c +#: shared-bindings/audiofilters/Filter.c shared-bindings/audiofilters/Phaser.c +#: shared-bindings/audiomixer/Mixer.c msgid "bits_per_sample must be 8 or 16" msgstr "bits_per_sample deve ser 8 ou 16" @@ -3200,7 +3266,7 @@ msgid "format" msgstr "formato" #: py/objstr.c -msgid "format requires a dict" +msgid "format needs a dict" msgstr "formato requer um dict" #: py/objdeque.c @@ -3665,7 +3731,7 @@ msgid "must use keyword argument for key function" msgstr "deve usar o argumento da palavra-chave para a função da chave" #: py/runtime.c -msgid "name '%q' is not defined" +msgid "name '%q' isn't defined" msgstr "o nome '%q' não está definido" #: py/runtime.c @@ -4088,6 +4154,10 @@ msgstr "argumento de enrolar deve ser um ndarray" msgid "rsplit(None,n)" msgstr "rsplit(Nenhum,n)" +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "samples_signed must be true" +msgstr "samples_signed deve ser verdadeiro" + #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c #: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "sampling rate out of range" @@ -4308,11 +4378,11 @@ msgid "tx and rx cannot both be None" msgstr "TX e RX não podem ser ambos" #: py/objtype.c -msgid "type '%q' is not an acceptable base type" +msgid "type '%q' isn't an acceptable base type" msgstr "o tipo '%q' não é um tipo base aceitável" #: py/objtype.c -msgid "type is not an acceptable base type" +msgid "type isn't an acceptable base type" msgstr "tipo não é um tipo base aceitável" #: py/runtime.c @@ -4374,7 +4444,9 @@ msgstr "'%c' sem correspondência no formato" msgid "unreadable attribute" msgstr "atributo ilegível" -#: shared-bindings/displayio/TileGrid.c shared-bindings/vectorio/VectorShape.c +#: shared-bindings/displayio/TileGrid.c shared-bindings/terminalio/Terminal.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-bindings/vectorio/VectorShape.c msgid "unsupported %q type" msgstr "tipo %q não suportado" @@ -4454,12 +4526,6 @@ msgstr "os pesos devem ser um objeto do tipo %q, %q, %q ou %q, e não %q " msgid "width must be greater than zero" msgstr "a largura deve ser maior que zero" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/raspberrypi/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "wifi is not enabled" -msgstr "o wifi não está ativo" - #: ports/raspberrypi/common-hal/wifi/Monitor.c msgid "wifi.Monitor not available" msgstr "O wifi.Monitor não está disponível" @@ -4522,6 +4588,18 @@ msgstr "zi deve ser de um tipo float" msgid "zi must be of shape (n_section, 2)" msgstr "zi deve estar na forma (n_section, 2)" +#~ msgid "Unsupported format" +#~ msgstr "Formato não suportado" + +#~ msgid "Wifi is not enabled" +#~ msgstr "O Wi-Fi não está ativado" + +#~ msgid "wifi is not enabled" +#~ msgstr "o wifi não está ativo" + +#~ msgid "Cannot remount '/' when visible via USB." +#~ msgstr "Não é possível montar '/' quando estiver visível pelo USB." + #~ msgid "%q must be a %q object, %q, or %q" #~ msgstr "%q deve ser um objeto %q, %q ou %q" @@ -4899,13 +4977,13 @@ msgstr "zi deve estar na forma (n_section, 2)" #~ msgid "'%s' object does not support item deletion" #~ msgstr "O objeto '%s' não é compatível com exclusão do item" -#~ msgid "'%s' object is not an iterator" +#~ msgid "'%s' object isn't an iterator" #~ msgstr "O objeto '%s' não é um iterador" #~ msgid "'%s' object is not callable" #~ msgstr "O objeto '%s' não é invocável" -#~ msgid "'%s' object is not iterable" +#~ msgid "'%s' object isn't iterable" #~ msgstr "O objeto '%s' não é iterável" #~ msgid "'%s' object is not subscriptable" @@ -4925,7 +5003,7 @@ msgstr "zi deve estar na forma (n_section, 2)" #~ msgid "'continue' outside loop" #~ msgstr "'continue' fora do loop" -#~ msgid "'coroutine' object is not an iterator" +#~ msgid "'coroutine' object isn't an iterator" #~ msgstr "O objeto 'corrotina' não é um iterador" #~ msgid "(x,y) integers required" @@ -6282,7 +6360,7 @@ msgstr "zi deve estar na forma (n_section, 2)" #~ msgid "frequency is read-only for this board" #~ msgstr "nesta placa, a frequência é de apenas leitura" -#~ msgid "function does not take keyword arguments" +#~ msgid "function doesn't take keyword arguments" #~ msgstr "função não aceita argumentos de palavras-chave" #~ msgid "function is implemented for scalars and ndarrays only" @@ -6411,7 +6489,7 @@ msgstr "zi deve estar na forma (n_section, 2)" #~ msgid "name must be a string" #~ msgstr "heap deve ser uma lista" -#~ msgid "name reused for argument" +#~ msgid "argument name reused" #~ msgstr "o nome foi reutilizado para o argumento" #~ msgid "no available NIC" diff --git a/locale/ru.po b/locale/ru.po index a2b18f900cc..01129f9b3c2 100644 --- a/locale/ru.po +++ b/locale/ru.po @@ -7,8 +7,8 @@ msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" -"PO-Revision-Date: 2025-01-13 14:00+0000\n" -"Last-Translator: gfbdrgng \n" +"PO-Revision-Date: 2025-06-30 16:01+0000\n" +"Last-Translator: MAE \n" "Language-Team: none\n" "Language: ru\n" "MIME-Version: 1.0\n" @@ -16,1082 +16,1660 @@ msgstr "" "Content-Transfer-Encoding: 8bit\n" "Plural-Forms: nplurals=3; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && " "n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);\n" -"X-Generator: Weblate 5.10-dev\n" +"X-Generator: Weblate 5.13-dev\n" -#: main.c -msgid "" -"\n" -"Code done running.\n" -msgstr "" -"\n" -"Программа закончила выполнение.\n" +#: extmod/modasyncio.c extmod/modheapq.c +msgid "empty heap" +msgstr "пустая куча" -#: main.c -msgid "" -"\n" -"Code stopped by auto-reload. Reloading soon.\n" -msgstr "" -"\n" -"Программа остановлена автоматической перезагрузкой. Скоро перезагрузка.\n" +#: extmod/modasyncio.c +msgid "can't cancel self" +msgstr "Не могу отменить себя" -#: supervisor/shared/safe_mode.c -msgid "" -"\n" -"Please file an issue with your program at github.com/adafruit/circuitpython/" -"issues." -msgstr "" -"\n" -"Пожалуйста подайте вопрос с вашей программой на github.com/adafruit/" -"circuitpython/issues." +#: extmod/modasyncio.c +msgid "can't wait" +msgstr "не может ждать" -#: supervisor/shared/safe_mode.c -msgid "" -"\n" -"Press reset to exit safe mode.\n" -msgstr "" -"\n" -"Нажмите на сброс чтобы выйти из безопасного режима.\n" +#: extmod/modbinascii.c extmod/modhashlib.c py/objarray.c +msgid "a bytes-like object is required" +msgstr "Требуется байтоподобный объект" -#: supervisor/shared/safe_mode.c -msgid "" -"\n" -"You are in safe mode because:\n" +#: extmod/modbinascii.c +msgid "incorrect padding" +msgstr "Неправильная набивка" + +#: extmod/moddeflate.c +msgid "format" +msgstr "формат" + +#: extmod/moddeflate.c +msgid "wbits" msgstr "" -"\n" -"Вы в безопасном режиме потому что:\n" -#: py/obj.c -msgid " File \"%q\"" -msgstr " Файл \"%q\"" +#: extmod/modhashlib.c +msgid "hash is final" +msgstr "хэш является окончательным" -#: py/obj.c -msgid " File \"%q\", line %d" -msgstr " Файл \"%q\", строка %d" +#: extmod/modheapq.c +msgid "heap must be a list" +msgstr "куча должна быть списком" -#: py/builtinhelp.c -msgid " is of type %q\n" -msgstr " имеет тип %q\n" +#: extmod/modjson.c +msgid "syntax error in JSON" +msgstr "синтаксис ошибка в JSON" -#: main.c -msgid " not found.\n" -msgstr " не найден.\n" +#: extmod/modrandom.c +msgid "bits must be 32 or less" +msgstr "биты должны быть 32 или менее" -#: main.c -msgid " output:\n" -msgstr " вывод:\n" +#: extmod/modrandom.c extmod/ulab/code/numpy/random/random.c +msgid "no default seed" +msgstr "Нет начального числа по умолчанию" -#: py/objstr.c -#, c-format -msgid "%%c requires int or char" -msgstr "%%c требует int или char" +#: extmod/modre.c +msgid "splitting with sub-captures" +msgstr "разделение с помощью подзахватов" -#: shared-bindings/rgbmatrix/RGBMatrix.c -#, c-format -msgid "" -"%d address pins, %d rgb pins and %d tiles indicate a height of %d, not %d" +#: extmod/modre.c +msgid "regex too complex" msgstr "" -"Адресные контакты %d, контакты rgb %d и плитки %d обозначают высоту %d, а не " -"%d" - -#: shared-bindings/microcontroller/Pin.c -msgid "%q and %q contain duplicate pins" -msgstr "%q и %q содержат пины дупликаты" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c -msgid "%q and %q must be different" -msgstr "%q и %q должны быть разными" +#: extmod/modre.c +msgid "Error in regex" +msgstr "Ошибка в регулярном выражении" -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -msgid "%q and %q must share a clock unit" -msgstr "%q и %q должны иметь общую единицу тактового генератора" +#: extmod/modtime.c +msgid "mktime needs a tuple of length 8 or 9" +msgstr "mktime нужен кортеж длины 8 или 9" -#: ports/nordic/common-hal/watchdog/WatchDogTimer.c -msgid "%q cannot be changed once mode is set to %q" -msgstr "%q не может быть изменен после установки режима на %q" +#: extmod/modtime.c +msgid "ticks interval overflow" +msgstr "переполнение интервала тиков" -#: shared-bindings/microcontroller/Pin.c -msgid "%q contains duplicate pins" -msgstr "%q содержит пины дупликаты" +#: extmod/modzlib.c +msgid "compression header" +msgstr "Заголовок сжатия" -#: ports/atmel-samd/common-hal/sdioio/SDCard.c -msgid "%q failure: %d" -msgstr "%q сбой: %d" +#: extmod/ulab/code/ndarray.c +msgid "data type not understood" +msgstr "Тип данных не понят" -#: py/argcheck.c shared-module/audiofilters/Filter.c -msgid "%q in %q must be of type %q, not %q" -msgstr "%q в %q должно быть типа %q, а не %q" +#: extmod/ulab/code/ndarray.c +msgid "array is too big" +msgstr "массив слишком велик" -#: ports/espressif/common-hal/espulp/ULP.c -#: ports/mimxrt10xx/common-hal/audiobusio/__init__.c -#: ports/mimxrt10xx/common-hal/usb_host/Port.c -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -#: ports/raspberrypi/common-hal/usb_host/Port.c -#: shared-bindings/digitalio/DigitalInOut.c -#: shared-bindings/microcontroller/Pin.c shared-module/max3421e/Max3421E.c -msgid "%q in use" -msgstr "%q используется" +#: extmod/ulab/code/ndarray.c +msgid "ndarray length overflows" +msgstr "Переполнение длины массива ndarray" -#: py/objstr.c -msgid "%q index out of range" -msgstr "Индекс %q вне диапазона" +#: extmod/ulab/code/ndarray.c +msgid "maximum number of dimensions is " +msgstr "Максимальное количество измерений составляет " -#: py/obj.c -msgid "%q indices must be integers, not %s" -msgstr "Индексы %q должны быть целыми числами, а не %s" +#: extmod/ulab/code/ndarray.c +msgid "cannot convert complex type" +msgstr "Не удается преобразовать сложный тип" -#: shared-module/bitbangio/SPI.c -msgid "%q init failed" -msgstr "Инициализация %q не удалась" +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/create.c +msgid "too many dimensions" +msgstr "Слишком много измерений" -#: ports/espressif/bindings/espnow/Peer.c shared-bindings/dualbank/__init__.c -msgid "%q is %q" -msgstr "%q является %q" +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/transform.c +msgid "index is out of bounds" +msgstr "индекс выходит из границ" -#: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "%q is read-only for this board" -msgstr "%q читается только для этой доски" +#: extmod/ulab/code/ndarray.c +msgid "indices must be integers, slices, or Boolean lists" +msgstr "индексы должны быть целыми числами, срезами или логическими списками" -#: py/argcheck.c shared-bindings/usb_hid/Device.c -msgid "%q length must be %d" -msgstr "Длинна %q должна быть %d" +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/bitwise.c +#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/numpy/vector.c +msgid "operands could not be broadcast together" +msgstr "Операнды не могут транслироваться вместе" -#: py/argcheck.c -msgid "%q length must be %d-%d" -msgstr "Длинна %q должна быть %d-%d" +#: extmod/ulab/code/ndarray.c +msgid "array and index length must be equal" +msgstr "Длина массива и индекса должна быть равна" -#: py/argcheck.c -msgid "%q length must be <= %d" -msgstr "Длинна %q должна быть <= %d" +#: extmod/ulab/code/ndarray.c +msgid "cannot convert complex to dtype" +msgstr "не может превратить комплекс в dtype" -#: py/argcheck.c -msgid "%q length must be >= %d" -msgstr "Длинна %q должна быть >= %d" +#: extmod/ulab/code/ndarray.c +msgid "operation is implemented for 1D Boolean arrays only" +msgstr "операция реализована только для 1D логических массивов" -#: py/modsys.c py/objmodule.c py/runtime.c -msgid "%q moved from %q to %q" -msgstr "%q переместился из %q в %q" +#: extmod/ulab/code/ndarray.c +msgid "too many indices" +msgstr "Слишком много индексов" -#: py/argcheck.c -msgid "%q must be %d" -msgstr "%q должно быть %d" +#: extmod/ulab/code/ndarray.c +msgid "cannot delete array elements" +msgstr "Не удается удалить элементы массива" -#: py/argcheck.c shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/displayio/Bitmap.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -#: shared-bindings/is31fl3741/FrameBuffer.c -#: shared-bindings/rgbmatrix/RGBMatrix.c -msgid "%q must be %d-%d" -msgstr "%q должно быть %d-%d" +#: extmod/ulab/code/ndarray.c +msgid "flattening order must be either 'C', or 'F'" +msgstr "порядок сглаживания должен быть либо 'C', либо 'F'" -#: shared-bindings/busdisplay/BusDisplay.c -msgid "%q must be 1 when %q is True" -msgstr "%q должен быть равен 1, если %q имеет значение True" +#: extmod/ulab/code/ndarray.c +msgid "tobytes can be invoked for dense arrays only" +msgstr "Тобайты могут быть вызваны только для плотных массивов" -#: py/argcheck.c shared-bindings/gifio/GifWriter.c -#: shared-module/gifio/OnDiskGif.c -msgid "%q must be <= %d" -msgstr "%q должно быть <= %d" +#: extmod/ulab/code/ndarray.c +msgid "operation is not supported for given type" +msgstr "Операция не поддерживается для данного типа" -#: ports/espressif/common-hal/watchdog/WatchDogTimer.c -msgid "%q must be <= %u" -msgstr "%q должно быть <= %u" +#: extmod/ulab/code/ndarray.c +msgid "keyword argument must be tuple of integers" +msgstr "" -#: py/argcheck.c -msgid "%q must be >= %d" -msgstr "%q должно быть >= %d" +#: extmod/ulab/code/ndarray.c +msgid "too many axes specified" +msgstr "" -#: shared-bindings/analogbufio/BufferedIn.c -msgid "%q must be a bytearray or array of type 'H' or 'B'" -msgstr "%q должен быть массивом байтов или массивом типа «H» или «B»" +#: extmod/ulab/code/ndarray.c +msgid "axis index out of bounds" +msgstr "" -#: shared-bindings/audiocore/RawSample.c -msgid "%q must be a bytearray or array of type 'h', 'H', 'b', or 'B'" -msgstr "%q должен быть массивом байтов или массивом типа «h», «H», «b» или «B»" +#: extmod/ulab/code/ndarray.c +msgid "repeated indices" +msgstr "" -#: shared-bindings/warnings/__init__.c -msgid "%q must be a subclass of %q" -msgstr "%q должен быть подклассом %q" - -#: ports/espressif/common-hal/analogbufio/BufferedIn.c -msgid "%q must be array of type 'H'" -msgstr "%q должен быть массивом типа 'H \"" +#: extmod/ulab/code/ndarray.c +msgid "shape must be integer or tuple of integers" +msgstr "фигура должна быть целым числом или кортежом целых чисел" -#: shared-module/synthio/__init__.c -msgid "%q must be array of type 'h'" -msgstr "%q должен быть массивом типа 'h \"" +#: extmod/ulab/code/ndarray.c +msgid "can only specify one unknown dimension" +msgstr "Можно указать только одно неизвестное измерение" -#: shared-bindings/audiobusio/PDMIn.c -msgid "%q must be multiple of 8." -msgstr "%q должно быть кратно 8." +#: extmod/ulab/code/ndarray.c +msgid "cannot reshape array" +msgstr "Не удается изменить форму массива" -#: ports/raspberrypi/bindings/cyw43/__init__.c py/argcheck.c py/objexcept.c -#: shared-bindings/bitmapfilter/__init__.c shared-bindings/canio/CAN.c -#: shared-bindings/digitalio/Pull.c shared-bindings/supervisor/__init__.c -#: shared-module/audiofilters/Filter.c shared-module/displayio/__init__.c -#: shared-module/synthio/Biquad.c shared-module/synthio/Synthesizer.c -msgid "%q must be of type %q or %q, not %q" -msgstr "%q должно быть типа%q или%q, а не%q" +#: extmod/ulab/code/ndarray.c +msgid "cannot assign new shape" +msgstr "Не удается назначить новую фигуру" -#: shared-bindings/jpegio/JpegDecoder.c -msgid "%q must be of type %q, %q, or %q, not %q" -msgstr "%q должен иметь тип %q, %q или %q, а не %q" +#: extmod/ulab/code/ndarray.c +msgid "function is defined for ndarrays only" +msgstr "Функция определяется только для массивов ndarrays" -#: py/argcheck.c py/runtime.c shared-bindings/bitmapfilter/__init__.c -#: shared-module/synthio/__init__.c -msgid "%q must be of type %q, not %q" -msgstr "%q должно быть типа %q, а не %q" +#: extmod/ulab/code/ndarray_operators.c +msgid "operation not supported for the input types" +msgstr "операция не поддерживается для типов ввода" -#: ports/atmel-samd/common-hal/busio/UART.c -msgid "%q must be power of 2" -msgstr "%q должен быть во 2-й степени" +#: extmod/ulab/code/ndarray_operators.c +msgid "dtype of int32 is not supported" +msgstr "dtype int32 не поддерживается" -#: shared-bindings/wifi/Monitor.c -msgid "%q out of bounds" -msgstr "%q за пределом" +#: extmod/ulab/code/ndarray_operators.c +msgid "cannot cast output with casting rule" +msgstr "Не удается привести выходные данные с помощью правила приведения" -#: ports/atmel-samd/common-hal/pulseio/PulseIn.c -#: ports/cxd56/common-hal/pulseio/PulseIn.c -#: ports/nordic/common-hal/pulseio/PulseIn.c -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -#: ports/stm/common-hal/pulseio/PulseIn.c py/argcheck.c -#: shared-bindings/canio/Match.c shared-bindings/time/__init__.c -msgid "%q out of range" -msgstr "%q вне диапазона" +#: extmod/ulab/code/ndarray_operators.c +msgid "results cannot be cast to specified type" +msgstr "Результаты не могут быть приведены к указанному типу" -#: py/objmodule.c py/runtime.c -msgid "%q renamed %q" -msgstr "%q переименован %q" +#: extmod/ulab/code/numpy/approx.c +msgid "interp is defined for 1D iterables of equal length" +msgstr "interp определен для 1D-итераций одинаковой длины" -#: py/objrange.c py/objslice.c shared-bindings/random/__init__.c -msgid "%q step cannot be zero" -msgstr "Шаг %q не может быть нулём" +#: extmod/ulab/code/numpy/approx.c +msgid "trapz is defined for 1D iterables" +msgstr "ловушка определена для одномерных 1D итераций" -#: shared-module/bitbangio/I2C.c -msgid "%q too long" -msgstr "%q слишком долго" +#: extmod/ulab/code/numpy/approx.c +msgid "trapz is defined for 1D arrays of equal length" +msgstr "ловушка определена для одномерных 1D массивов одинаковой длины" -#: py/bc.c py/objnamedtuple.c -msgid "%q() takes %d positional arguments but %d were given" -msgstr "%q() принимает %d позиционных аргументов, но было передано %d" +#: extmod/ulab/code/numpy/bitwise.c +msgid "not supported for input types" +msgstr "Не поддерживается для типов ввода" -#: shared-module/jpegio/JpegDecoder.c -msgid "%q() without %q()" -msgstr "%q() без %q()" +#: extmod/ulab/code/numpy/carray/carray.c +msgid "function is implemented for ndarrays only" +msgstr "Функция реализована только для массивов ndarrays" -#: shared-bindings/usb_hid/Device.c -msgid "%q, %q, and %q must all be the same length" -msgstr "%q, %q, и %q должны быть одной длинны" +#: extmod/ulab/code/numpy/carray/carray.c +msgid "input must be an ndarray, or a scalar" +msgstr "Ввод должен быть массивом ndarray или скаляр" -#: py/objint.c shared-bindings/_bleio/Connection.c -#: shared-bindings/storage/__init__.c -msgid "%q=%q" -msgstr "%q=%q" +#: extmod/ulab/code/numpy/carray/carray.c +msgid "input must be a 1D ndarray" +msgstr "Ввод должен быть 1D массивом ndarray" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "%q[%u] shifts in more bits than pin count" -msgstr "%q [%u] смещается в большем количестве чем количество пинов" +#: extmod/ulab/code/numpy/carray/carray_tools.c +msgid "not implemented for complex dtype" +msgstr "не реализовано для сложного типа d" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "%q[%u] shifts out more bits than pin count" -msgstr "%q[%u] смещает больше битов чем количество выводов" +#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/user/user.c +#: shared-bindings/_eve/__init__.c +msgid "input must be an ndarray" +msgstr "Ввод должен быть массивом ndarray" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "%q[%u] uses extra pin" -msgstr "%q[%u] использует дополнительный контакт" +#: extmod/ulab/code/numpy/compare.c +msgid "object too deep for desired array" +msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "%q[%u] waits on input outside of count" -msgstr "%q [%u] ожидает ввода за пределами графа" +#: extmod/ulab/code/numpy/compare.c +msgid "cannot cast array data from dtype" +msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -#, c-format -msgid "%s error 0x%x" -msgstr "%s ошибка 0x%x" +#: extmod/ulab/code/numpy/compare.c +msgid "minlength must not be negative" +msgstr "" -#: py/argcheck.c -msgid "'%q' argument required" -msgstr "Требуется аргумент '%q'" +#: extmod/ulab/code/numpy/compare.c +msgid "the weights and list don't have the same length" +msgstr "" -#: py/proto.c -msgid "'%q' object does not support '%q'" -msgstr "Объект '%q' не поддерживает '%q'" +#: extmod/ulab/code/numpy/compare.c +msgid "cannot cast weigths to float" +msgstr "" -#: py/runtime.c -msgid "'%q' object is not an iterator" -msgstr "Объект '%q' не является итератором" +#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/numpy/create.c +#: extmod/ulab/code/numpy/io/io.c extmod/ulab/code/numpy/transform.c +#: extmod/ulab/code/numpy/vector.c +msgid "wrong input type" +msgstr "Неправильный тип ввода" -#: py/objtype.c py/runtime.c shared-module/atexit/__init__.c -msgid "'%q' object is not callable" -msgstr "Объект '%q' не является вызываемым" +#: extmod/ulab/code/numpy/create.c +msgid "input argument must be an integer, a tuple, or a list" +msgstr "Входной аргумент должен быть целым числом, кортежом или списком" -#: py/runtime.c -msgid "'%q' object is not iterable" -msgstr "Объект '%q' не является итерируемым" +#: extmod/ulab/code/numpy/create.c py/objarray.c py/objstr.c +msgid "wrong number of arguments" +msgstr "неправильное количество аргументов" -#: py/emitinlinethumb.c py/emitinlinextensa.c -#, c-format -msgid "'%s' expects a label" -msgstr "'%s' ожидает метку" +#: extmod/ulab/code/numpy/create.c py/objint_longlong.c py/objint_mpz.c +msgid "divide by zero" +msgstr "Делим на ноль" -#: py/emitinlinethumb.c py/emitinlinextensa.c -#, c-format -msgid "'%s' expects a register" -msgstr "'%s' ожидает регистр" +#: extmod/ulab/code/numpy/create.c +msgid "arange: cannot compute length" +msgstr "arange: не удается вычислить длину" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects a special register" -msgstr "'%s' ожидает специальный регистр" +#: extmod/ulab/code/numpy/create.c +msgid "first argument must be a tuple of ndarrays" +msgstr "Первый аргумент должен быть кортежом массива ndarrays" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects an FPU register" -msgstr "'%s' ожидает регистр FPU" +#: extmod/ulab/code/numpy/create.c +msgid "only ndarrays can be concatenated" +msgstr "только массивы ndarrays могут быть объединены" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects an address of the form [a, b]" -msgstr "'%s' ожидает адрес в формате [a, b]" +#: extmod/ulab/code/numpy/create.c +msgid "wrong axis specified" +msgstr "Указана неправильная ось" -#: py/emitinlinethumb.c py/emitinlinextensa.c -#, c-format -msgid "'%s' expects an integer" -msgstr "'%s' ожидает целое число" +#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c +msgid "input arrays are not compatible" +msgstr "Входные массивы несовместимы" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects at most r%d" -msgstr "'%s' ожидает не более r%d" +#: extmod/ulab/code/numpy/create.c +msgid "input must be 1- or 2-d" +msgstr "Вход должен быть 1- или 2-D" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects {r0, r1, ...}" -msgstr "'%s' ожидает {r0, r1, ...}" +#: extmod/ulab/code/numpy/create.c +msgid "number of points must be at least 2" +msgstr "Количество баллов должно быть не менее 2" -#: py/emitinlinextensa.c -#, c-format -msgid "'%s' integer %d isn't within range %d..%d" -msgstr "'%s' целое число %d не находится в пределах диапазона %d..%d" +#: extmod/ulab/code/numpy/create.c +msgid "indexing should be 'xy' or 'ij'" +msgstr "" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' integer 0x%x doesn't fit in mask 0x%x" -msgstr "'%s' целое число 0x%x не помещается в маску 0x%x" +#: extmod/ulab/code/numpy/create.c +msgid "indexing must be 'xy' or 'ij'" +msgstr "" -#: py/obj.c -#, c-format -msgid "'%s' object doesn't support item assignment" -msgstr "Объект '%s' не поддерживает присвоение элементов" +#: extmod/ulab/code/numpy/create.c +msgid "too many input arrays" +msgstr "" -#: py/obj.c -#, c-format -msgid "'%s' object doesn't support item deletion" -msgstr "Объект '%s' не поддерживает удаление элементов" +#: extmod/ulab/code/numpy/create.c extmod/ulab/code/numpy/numerical.c +#: extmod/ulab/code/numpy/transform.c +msgid "arguments must be ndarrays" +msgstr "Аргументы должны быть массивами ndarrays" -#: py/runtime.c -msgid "'%s' object has no attribute '%q'" -msgstr "Объект '%s' не имеет атрибута '%q'" +#: extmod/ulab/code/numpy/create.c +msgid "arguments must be 1D arrays" +msgstr "" -#: py/obj.c -#, c-format -msgid "'%s' object isn't subscriptable" -msgstr "Объект '%s' не может быть подписан" +#: extmod/ulab/code/numpy/create.c +msgid "input is not an array" +msgstr "" -#: py/objstr.c -msgid "'=' alignment not allowed in string format specifier" -msgstr "Выравнивание '=' недопустимо в спецификаторе формата строки" +#: extmod/ulab/code/numpy/create.c extmod/ulab/code/numpy/numerical.c +#: ports/espressif/common-hal/pulseio/PulseIn.c +#: shared-bindings/bitmaptools/__init__.c +msgid "index out of range" +msgstr "индекс вне диапазона" -#: shared-module/struct/__init__.c -msgid "'S' and 'O' are not supported format types" -msgstr "'S' и 'O' не являются поддерживаемыми типами форматов" +#: extmod/ulab/code/numpy/create.c +msgid "mode should be raise, wrap or clip" +msgstr "" -#: py/compile.c -msgid "'align' requires 1 argument" -msgstr "«выравнивание» требует 1 аргумента" +#: extmod/ulab/code/numpy/create.c +msgid "index must not be negative" +msgstr "" -#: py/compile.c -msgid "'await' outside function" -msgstr "«ожидание» внешняя функция" +#: extmod/ulab/code/numpy/create.c +msgid "offset must be non-negative and no greater than buffer length" +msgstr "Смещение должно быть неотрицательным и не превышать длину буфера" -#: py/compile.c -msgid "'break'/'continue' outside loop" -msgstr "'прервать'/'продолжить' вне цикла" +#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c +msgid "buffer size must be a multiple of element size" +msgstr "Размер буфера должен быть кратен размеру элемента" -#: py/compile.c -msgid "'data' requires at least 2 arguments" -msgstr "«данные» требуют как минимум 2 аргумента" +#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c +msgid "buffer is smaller than requested size" +msgstr "Размер буфера меньше запрошенного" -#: py/compile.c -msgid "'data' requires integer arguments" -msgstr "«данные» требуют целочисленных аргументов" +#: extmod/ulab/code/numpy/fft/fft_tools.c +msgid "FFT is defined for ndarrays only" +msgstr "FFT определено только для массивов ndarrays" -#: py/compile.c -msgid "'label' requires 1 argument" -msgstr "«метка» требует 1 аргумент" +#: extmod/ulab/code/numpy/fft/fft_tools.c +msgid "FFT is implemented for linear arrays only" +msgstr "FFT реализовано только для линейных массивов" -#: py/emitnative.c -msgid "'not' not implemented" -msgstr "'не' не реализовано" +#: extmod/ulab/code/numpy/fft/fft_tools.c extmod/ulab/code/utils/utils.c +msgid "input array length must be power of 2" +msgstr "Длина входного массива должна быть равна степени 2" -#: py/compile.c -msgid "'return' outside function" -msgstr "«возврат» внешняя функция" +#: extmod/ulab/code/numpy/fft/fft_tools.c +msgid "real and imaginary parts must be of equal length" +msgstr "реальные и воображаемые части должны быть одинаковой длины" -#: py/compile.c -msgid "'yield from' inside async function" -msgstr "«выход из» внутри асинхронной функции" +#: extmod/ulab/code/numpy/filter.c +msgid "convolve arguments must be ndarrays" +msgstr "переплетение аргументов должно быть массивами ndarrays" -#: py/compile.c -msgid "'yield' outside function" -msgstr "внешняя функция \"выход\"" +#: extmod/ulab/code/numpy/filter.c +msgid "convolve arguments must be linear arrays" +msgstr "Аргументы свертки должны быть линейными массивами" -#: py/compile.c -msgid "* arg after **" -msgstr "* аргумент после **" +#: extmod/ulab/code/numpy/filter.c +msgid "convolve arguments must not be empty" +msgstr "аргументы свертки не должны быть пустыми" -#: py/compile.c -msgid "*x must be assignment target" -msgstr "*x должно быть целью назначения" +#: extmod/ulab/code/numpy/io/io.c +msgid "corrupted file" +msgstr "Поврежденный файл" -#: py/obj.c -msgid ", in %q\n" -msgstr ", в %q\n" +#: extmod/ulab/code/numpy/io/io.c +msgid "wrong dtype" +msgstr "Неправильный тип" -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/epaperdisplay/EPaperDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -msgid ".show(x) removed. Use .root_group = x" -msgstr ". Показать(x) удален. Используйте . корневую_группу = x" +#: extmod/ulab/code/numpy/io/io.c +msgid "usecols keyword must be specified" +msgstr "Ключевое слово usecols должно быть указано" -#: py/objcomplex.c -msgid "0.0 to a complex power" -msgstr "0.0 в комплексную степень" +#: extmod/ulab/code/numpy/io/io.c +msgid "empty file" +msgstr "пустой файл" -#: py/modbuiltins.c -msgid "3-arg pow() not supported" -msgstr "Pow() с 3 аргументами не поддерживается" +#: extmod/ulab/code/numpy/io/io.c +msgid "usecols is too high" +msgstr "Usecols слишком высок" -#: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "AP could not be started" -msgstr "AP не может быть запущен" +#: extmod/ulab/code/numpy/io/io.c +msgid "array has too many dimensions" +msgstr "Массив имеет слишком много измерений" -#: shared-bindings/_bleio/Address.c shared-bindings/ipaddress/IPv4Address.c -#, c-format -msgid "Address must be %d bytes long" -msgstr "Адрес должен быть длиной %d байт" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "input matrix is asymmetric" +msgstr "Входная матрица асимметрична" -#: ports/espressif/common-hal/memorymap/AddressRange.c -#: ports/nordic/common-hal/memorymap/AddressRange.c -#: ports/raspberrypi/common-hal/memorymap/AddressRange.c -msgid "Address range not allowed" -msgstr "Диапазон адресов не разрешен" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "matrix is not positive definite" +msgstr "матрица не является положительно определенной" -#: shared-bindings/memorymap/AddressRange.c -msgid "Address range wraps around" -msgstr "Обертывание диапазона адресов" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "iterations did not converge" +msgstr "итерации не сходятся" -#: ports/espressif/common-hal/canio/CAN.c -msgid "All CAN peripherals are in use" -msgstr "Все периферийные устройства CAN уже используются" +#: extmod/ulab/code/numpy/linalg/linalg.c +#: extmod/ulab/code/scipy/linalg/linalg.c +msgid "input matrix is singular" +msgstr "Входная матрица является сингулярной" -#: ports/espressif/common-hal/busio/I2C.c -#: ports/espressif/common-hal/i2ctarget/I2CTarget.c -#: ports/nordic/common-hal/busio/I2C.c -msgid "All I2C peripherals are in use" -msgstr "Все периферийные устройства I2C уже используются" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "operation is defined for ndarrays only" +msgstr "операция определена только для массивов ndarrays" -#: ports/atmel-samd/common-hal/canio/Listener.c -#: ports/espressif/common-hal/canio/Listener.c -#: ports/stm/common-hal/canio/Listener.c -msgid "All RX FIFOs in use" -msgstr "Все RX FIFO уже используются" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "operation is defined for 2D arrays only" +msgstr "операция определена только для 2D-массивов" -#: ports/espressif/common-hal/busio/SPI.c ports/nordic/common-hal/busio/SPI.c -msgid "All SPI peripherals are in use" -msgstr "Все периферийные устройства SPI уже используются" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "mode must be complete, or reduced" +msgstr "Режим должен быть завершенным или уменьшенным" -#: ports/espressif/common-hal/busio/UART.c ports/nordic/common-hal/busio/UART.c -msgid "All UART peripherals are in use" -msgstr "Все периферийные устройства UART уже используются" +#: extmod/ulab/code/numpy/numerical.c +msgid "attempt to get argmin/argmax of an empty sequence" +msgstr "" +"Попытка получить аргумент минимальный/аргумент максимальный пустой " +"последовательности" -#: ports/nordic/common-hal/countio/Counter.c -#: ports/nordic/common-hal/pulseio/PulseIn.c -#: ports/nordic/common-hal/rotaryio/IncrementalEncoder.c -msgid "All channels in use" -msgstr "Все каналы уже используются" +#: extmod/ulab/code/numpy/numerical.c +msgid "attempt to get (arg)min/(arg)max of empty sequence" +msgstr "" +"Попытка получить (аргумент)минимальный/(аргумент)максимальный пустой " +"последовательности" -#: ports/raspberrypi/common-hal/usb_host/Port.c -msgid "All dma channels in use" -msgstr "Все используемые каналы dma" +#: extmod/ulab/code/numpy/numerical.c extmod/ulab/code/ulab_tools.c +msgid "axis must be None, or an integer" +msgstr "ось должна быть None или целым числом" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c -msgid "All event channels in use" -msgstr "Все каналы событий уже используются" +#: extmod/ulab/code/numpy/numerical.c +msgid "operation is not implemented on ndarrays" +msgstr "операция не реализована на массивах ndarrays" -#: ports/raspberrypi/common-hal/floppyio/__init__.c -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -#: ports/raspberrypi/common-hal/usb_host/Port.c -msgid "All state machines in use" -msgstr "Все машины состояний уже используются" +#: extmod/ulab/code/numpy/numerical.c +msgid "input must be tuple, list, range, or ndarray" +msgstr "Ввод должен быть кортеж, список, диапазон или массивом ndarray" -#: ports/atmel-samd/audio_dma.c -msgid "All sync event channels in use" -msgstr "Все каналы событий синхронизации уже используются" +#: extmod/ulab/code/numpy/numerical.c +msgid "sort argument must be an ndarray" +msgstr "аргумент сортировки должен быть массивом ndarray" -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c -msgid "All timers for this pin are in use" -msgstr "Все таймеры для этого пина уже используются" +#: extmod/ulab/code/numpy/numerical.c +msgid "argsort argument must be an ndarray" +msgstr "аргумент сортировки должен быть аргументом массива ndarray" -#: ports/atmel-samd/common-hal/_pew/PewPew.c -#: ports/atmel-samd/common-hal/audioio/AudioOut.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/nordic/common-hal/audiopwmio/PWMAudioOut.c -#: ports/nordic/common-hal/pulseio/PulseIn.c -#: ports/nordic/peripherals/nrf/timers.c -#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c -msgid "All timers in use" -msgstr "Все таймеры уже используются" +#: extmod/ulab/code/numpy/numerical.c +msgid "argsort is not implemented for flattened arrays" +msgstr "сортировка arg не реализована для сглаженных массивов" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Already advertising." -msgstr "Уже реклама." +#: extmod/ulab/code/numpy/numerical.c +msgid "axis too long" +msgstr "Слишком длинная ось" -#: ports/atmel-samd/common-hal/canio/Listener.c -msgid "Already have all-matches listener" -msgstr "Уже есть универсальный слушатель" +#: extmod/ulab/code/numpy/numerical.c +msgid "cross is defined for 1D arrays of length 3" +msgstr "крест определяется для 1D массивов длины 3" -#: ports/espressif/common-hal/_bleio/__init__.c -msgid "Already in progress" -msgstr "Уже в процессе" +#: extmod/ulab/code/numpy/numerical.c +msgid "diff argument must be an ndarray" +msgstr "аргумент DIFF должен быть массивом ndarray" -#: ports/espressif/bindings/espnow/ESPNow.c -#: ports/espressif/common-hal/espulp/ULP.c -#: shared-module/memorymonitor/AllocationAlarm.c -#: shared-module/memorymonitor/AllocationSize.c -msgid "Already running" -msgstr "Уже запущен" +#: extmod/ulab/code/numpy/numerical.c +msgid "differentiation order out of range" +msgstr "Порядок дифференциации вне диапазона" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/raspberrypi/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "Already scanning for wifi networks" -msgstr "Поиск сетей wifi уже происходит" +#: extmod/ulab/code/numpy/numerical.c +msgid "flip argument must be an ndarray" +msgstr "Флип -аргумент должен быть массивом ndarray" -#: shared-module/os/getenv.c -#, c-format -msgid "An error occurred while retrieving '%s':\n" -msgstr "Произошла ошибка при получении '%s':\n" +#: extmod/ulab/code/numpy/numerical.c +msgid "wrong axis index" +msgstr "Неправильный индекс оси" -#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c -msgid "Another PWMAudioOut is already active" -msgstr "Другой аудиовыход PWM уже активен" +#: extmod/ulab/code/numpy/numerical.c +msgid "median argument must be an ndarray" +msgstr "Средний аргумент должен быть массивом ndarray" +#: extmod/ulab/code/numpy/numerical.c +msgid "roll argument must be an ndarray" +msgstr "аргумент roll должен быть массивом ndarray" + +#: extmod/ulab/code/numpy/poly.c +msgid "input data must be an iterable" +msgstr "Входные данные должны быть итерируемыми" + +#: extmod/ulab/code/numpy/poly.c +msgid "more degrees of freedom than data points" +msgstr "Больше степеней свободы чем точек данных" + +#: extmod/ulab/code/numpy/poly.c +msgid "input vectors must be of equal length" +msgstr "Входные векторы должны быть одинаковой длины" + +#: extmod/ulab/code/numpy/poly.c +msgid "could not invert Vandermonde matrix" +msgstr "не удалось инвертировать матрицу Вандермонда" + +#: extmod/ulab/code/numpy/poly.c +msgid "input is not iterable" +msgstr "Ввод не является итерируемым" + +#: extmod/ulab/code/numpy/random/random.c +msgid "argument must be None, an integer or a tuple of integers" +msgstr "аргумент должен быть None, целым числом или кортежем целых чисел" + +#: extmod/ulab/code/numpy/random/random.c +msgid "shape must be None, an integer or a tuple of integers" +msgstr "" + +#: extmod/ulab/code/numpy/random/random.c extmod/ulab/code/ulab_tools.c +msgid "out has wrong type" +msgstr "out имеет неправильный тип" + +#: extmod/ulab/code/numpy/random/random.c +msgid "output array has wrong type" +msgstr "Выходной массив имеет неправильный тип" + +#: extmod/ulab/code/numpy/random/random.c +msgid "size must match out.shape when used together" +msgstr "Размер должен соответствовать out.shape при совместном использовании" + +#: extmod/ulab/code/numpy/random/random.c extmod/ulab/code/ulab_tools.c +msgid "output array must be contiguous" +msgstr "выходной массив должен быть непрерывным" + +#: extmod/ulab/code/numpy/transform.c +msgid "wrong length of condition array" +msgstr "неправильная длина массива состояния" + +#: extmod/ulab/code/numpy/transform.c extmod/ulab/code/numpy/vector.c +msgid "first argument must be an ndarray" +msgstr "Первым аргументом должен быть массивом ndarray" + +#: extmod/ulab/code/numpy/transform.c +msgid "wrong index type" +msgstr "Неправильный тип индекса" + +#: extmod/ulab/code/numpy/transform.c +msgid "wrong length of index array" +msgstr "неправильная длина массива индексов" + +#: extmod/ulab/code/numpy/transform.c +msgid "dimensions do not match" +msgstr "Размеры не совпадают" + +#: extmod/ulab/code/numpy/vector.c extmod/ulab/code/utils/utils.c +msgid "out must be an ndarray" +msgstr "out должен быть массивом ndarray" + +#: extmod/ulab/code/numpy/vector.c +msgid "out must be of float dtype" +msgstr "Выход должен быть поплавкового типа" + +#: extmod/ulab/code/numpy/vector.c +msgid "input and output dimensions differ" +msgstr "Входные и выходные размеры различаются" + +#: extmod/ulab/code/numpy/vector.c +msgid "input and output shapes differ" +msgstr "Входные и выходные формы различаются" + +#: extmod/ulab/code/numpy/vector.c +msgid "out keyword is not supported for function" +msgstr "ключевое слово не поддерживается для функции" + +#: extmod/ulab/code/numpy/vector.c +msgid "out keyword is not supported for complex dtype" +msgstr "Ключевое слово out не поддерживается для сложного типа d" + +#: extmod/ulab/code/numpy/vector.c +msgid "dtype must be float, or complex" +msgstr "Тип d должен быть плавающим или сложным" + +#: extmod/ulab/code/numpy/vector.c +msgid "can't convert complex to float" +msgstr "Не может преобразовать сложный в плавающий" + +#: extmod/ulab/code/numpy/vector.c +msgid "input dtype must be float or complex" +msgstr "Входной тип dtype должен быть плавающим или сложным" + +#: extmod/ulab/code/numpy/vector.c extmod/ulab/code/scipy/integrate/integrate.c +msgid "first argument must be a callable" +msgstr "Первый аргумент должен быть вызываемым" + +#: extmod/ulab/code/numpy/vector.c +msgid "wrong output type" +msgstr "неверный тип вывода" + +#: extmod/ulab/code/scipy/integrate/integrate.c +#, c-format +msgid "can't convert arg %d from %s to float" +msgstr "" + +#: extmod/ulab/code/scipy/integrate/integrate.c +msgid "levels needs to be a positive integer" +msgstr "" + +#: extmod/ulab/code/scipy/integrate/integrate.c +msgid "steps needs to be a positive integer" +msgstr "" + +#: extmod/ulab/code/scipy/integrate/integrate.c +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "first argument must be a function" +msgstr "первый аргумент должен быть функцией" + +#: extmod/ulab/code/scipy/integrate/integrate.c +msgid "order needs to be a positive integer" +msgstr "" + +#: extmod/ulab/code/scipy/linalg/linalg.c +msgid "first two arguments must be ndarrays" +msgstr "Первые два аргумента должны быть массивами ndarrays" + +#: extmod/ulab/code/scipy/linalg/linalg.c extmod/ulab/code/user/user.c +msgid "input must be a dense ndarray" +msgstr "Ввод должен быть плотным массивом ndarray" + +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "function has the same sign at the ends of interval" +msgstr "функция имеет один и тот же знак в конце интервала" + +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "maxiter should be > 0" +msgstr "макситер должен быть > 0" + +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "maxiter must be > 0" +msgstr "maxiter должен быть > 0" + +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "data must be iterable" +msgstr "Данные должны быть итерируемыми" + +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "initial values must be iterable" +msgstr "Начальные значения должны быть итерируемыми" + +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "data must be of equal length" +msgstr "Данные должны быть одинаковой длины" + +#: extmod/ulab/code/scipy/signal/signal.c +msgid "sosfilt requires iterable arguments" +msgstr "sosфильтр требует повторяющихся аргументов" + +#: extmod/ulab/code/scipy/signal/signal.c +msgid "input must be one-dimensional" +msgstr "Входные данные должны быть одномерными" + +#: extmod/ulab/code/scipy/signal/signal.c +msgid "zi must be an ndarray" +msgstr "зи, должно быть, массивом ndarray" + +#: extmod/ulab/code/scipy/signal/signal.c +msgid "zi must be of shape (n_section, 2)" +msgstr "zi должен иметь форму (n_section, 2)" + +#: extmod/ulab/code/scipy/signal/signal.c +msgid "zi must be of float type" +msgstr "zi должно быть типа float" + +#: extmod/ulab/code/scipy/signal/signal.c +msgid "sos array must be of shape (n_section, 6)" +msgstr "Массив sos должен иметь форму (n_section, 6)" + +#: extmod/ulab/code/scipy/signal/signal.c +msgid "sos[:, 3] should be all ones" +msgstr "sos[:, 3] должны быть все единицы" + +#: extmod/ulab/code/ulab_tools.c +msgid "axis is out of bounds" +msgstr "Ось выходит за пределы" + +#: extmod/ulab/code/ulab_tools.c +msgid "size is defined for ndarrays only" +msgstr "размер определен только для массива ndarrays" + +#: extmod/ulab/code/ulab_tools.c +msgid "input must be square matrix" +msgstr "Входные данные должны быть квадратной матрицей" + +#: extmod/ulab/code/ulab_tools.c +msgid "out array has wrong dtype" +msgstr "" + +#: extmod/ulab/code/ulab_tools.c +msgid "out array has wrong dimension" +msgstr "" + +#: extmod/ulab/code/ulab_tools.c +msgid "out array has wrong shape" +msgstr "" + +#: extmod/ulab/code/utils/utils.c +msgid "out must be a float dense array" +msgstr "Out должен быть плотным массивом с плавающей запятой" + +#: extmod/ulab/code/utils/utils.c +msgid "offset is too large" +msgstr "Смещение слишком большое" + +#: extmod/ulab/code/utils/utils.c +msgid "out array is too small" +msgstr "Наш массив слишком мал" + +#: extmod/ulab/code/utils/utils.c +msgid "spectrogram is defined for ndarrays only" +msgstr "" + +#: extmod/ulab/code/utils/utils.c +msgid "spectrogram is implemented for 1D arrays only" +msgstr "" + +#: extmod/ulab/code/utils/utils.c +msgid "out array must be a 1D array of float type" +msgstr "" + +#: extmod/ulab/code/utils/utils.c +msgid "input and out arrays must have same length" +msgstr "" + +#: extmod/ulab/code/utils/utils.c +msgid "scratchpad must be an ndarray" +msgstr "" + +#: extmod/ulab/code/utils/utils.c +msgid "scratchpad must be a 1D dense float array" +msgstr "" + +#: extmod/ulab/code/utils/utils.c +msgid "scratchpad must be twice as long as input" +msgstr "" + +#: extmod/vfs_fat.c py/moderrno.c +msgid "Read-only filesystem" +msgstr "Файловая система только для чтения" + +#: extmod/vfs_posix_file.c py/objstringio.c +msgid "I/O operation on closed file" +msgstr "Операция ввода-вывода на закрытом файле" + +#: extmod/vfs_posix_file.c +msgid "poll on file not available on win32" +msgstr "Опрос в файле недоступен в Win32" + +#: main.c +msgid "Done" +msgstr "Выполнено" + +#: main.c +msgid " output:\n" +msgstr " вывод:\n" + +#: main.c +msgid "" +"Auto-reload is on. Simply save files over USB to run them or enter REPL to " +"disable.\n" +msgstr "" +"Автоматическая перезагрузка включена. Просто сохрани файл по USB или зайди в " +"REPL чтобы отключить.\n" + +#: main.c +msgid "Auto-reload is off.\n" +msgstr "Автоматическая перезагрузка отключена.\n" + +#: main.c +msgid "Running in safe mode! Not running saved code.\n" +msgstr "Работает в безопасном режиме! Сохраненный код не выполняется.\n" + +#: main.c +msgid " not found.\n" +msgstr " не найден.\n" + +#: main.c +msgid "WARNING: Your code filename has two extensions\n" +msgstr "ВНИМАНИЕ: Имя файла кода имеет два расширения\n" + +#: main.c +msgid "" +"\n" +"Code stopped by auto-reload. Reloading soon.\n" +msgstr "" +"\n" +"Программа остановлена автоматической перезагрузкой. Скоро перезагрузка.\n" + +#: main.c +msgid "" +"\n" +"Code done running.\n" +msgstr "" +"\n" +"Программа закончила выполнение.\n" + +#: main.c +msgid "Woken up by alarm.\n" +msgstr "Проснулся по тревоге.\n" + +#: main.c +msgid "Press any key to enter the REPL. Use CTRL-D to reload.\n" +msgstr "" +"Нажмите любую клавишу чтобы зайти в REPL. Используйте CTRL-D для " +"перезагрузки.\n" + +#: main.c +msgid "Pretending to deep sleep until alarm, CTRL-C or file write.\n" +msgstr "" +"Притворяюсь глубоким сном до сигнала тревоги, CTRL-C или записи файла.\n" + +#: main.c +msgid "UID:" +msgstr "UID:" + +#: main.c +msgid "soft reboot\n" +msgstr "Мягкая перезагрузка\n" + +#: ports/analog/common-hal/busio/SPI.c ports/analog/common-hal/busio/UART.c +#: ports/cxd56/common-hal/busio/SPI.c ports/stm/common-hal/audioio/AudioOut.c +#: shared-bindings/digitalio/DigitalInOutProtocol.c +#: shared-module/displayio/bus_core.c shared-module/ssl/SSLContext.c +msgid "%q init failed" +msgstr "Инициализация %q не удалась" + +#: ports/analog/common-hal/busio/SPI.c +msgid "SPI needs MOSI, MISO, and SCK" +msgstr "" + +#: ports/analog/common-hal/busio/SPI.c +#: ports/atmel-samd/common-hal/pulseio/PulseIn.c +#: ports/cxd56/common-hal/pulseio/PulseIn.c +#: ports/nordic/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#: ports/stm/common-hal/pulseio/PulseIn.c py/argcheck.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/canio/Match.c +#: shared-bindings/time/__init__.c +msgid "%q out of range" +msgstr "%q вне диапазона" + +#: ports/analog/common-hal/busio/SPI.c +#: ports/espressif/common-hal/espidf/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: shared-bindings/epaperdisplay/EPaperDisplay.c +msgid "Invalid state" +msgstr "Неверное состояние" + +#: ports/analog/common-hal/busio/SPI.c +msgid "Failed to set SPI Clock Mode" +msgstr "" + +#: ports/analog/common-hal/busio/UART.c +#: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c +#: ports/nordic/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/zephyr-cp/common-hal/busio/UART.c +msgid "RS485" +msgstr "RS485" + +#: ports/analog/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c +msgid "UART needs TX & RX" +msgstr "" + +#: ports/analog/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c +msgid "Both RX and TX required for flow control" +msgstr "Для управления потоком требуется как RX так и TX" + +#: ports/analog/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/usb_host/Port.c +#: shared-module/rgbmatrix/RGBMatrix.c +msgid "Failed to allocate %q buffer" +msgstr "Не удалось выделить буфер %q" + +#: ports/analog/common-hal/busio/UART.c +msgid "UART read error" +msgstr "" + +#: ports/analog/common-hal/busio/UART.c +msgid "UART transaction timeout" +msgstr "" + +#: ports/analog/common-hal/busio/UART.c ports/espressif/common-hal/busio/UART.c +#: ports/nordic/common-hal/busio/UART.c ports/zephyr-cp/common-hal/busio/UART.c +msgid "All UART peripherals are in use" +msgstr "Все периферийные устройства UART уже используются" + +#: ports/analog/common-hal/busio/UART.c +#: ports/analog/peripherals/max32690/max32_i2c.c +#: ports/analog/peripherals/max32690/max32_spi.c +#: ports/analog/peripherals/max32690/max32_uart.c +#: ports/espressif/common-hal/_bleio/Service.c +#: ports/espressif/common-hal/espulp/ULP.c +#: ports/espressif/common-hal/jpegio/JpegDecoder.c +#: ports/espressif/common-hal/microcontroller/Processor.c +#: ports/espressif/common-hal/mipidsi/Display.c +#: ports/mimxrt10xx/common-hal/audiobusio/__init__.c +#: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c +#: ports/raspberrypi/bindings/picodvi/Framebuffer.c +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +#: ports/raspberrypi/common-hal/picodvi/AudioOut.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c +#: ports/raspberrypi/common-hal/usb_host_bulk/InStream.c py/argcheck.c +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/utils/__init__.c +#: shared-bindings/digitalio/DigitalInOut.c +#: shared-bindings/epaperdisplay/EPaperDisplay.c +#: shared-bindings/i2cioexpander/IOPin.c shared-bindings/mipidsi/Display.c +#: shared-bindings/pwmio/PWMOut.c shared-bindings/supervisor/__init__.c +#: shared-module/aurora_epaper/aurora_framebuffer.c +#: shared-module/cryptography/hazmat/primitives/asymmetric/ec/EllipticCurvePublicKey.c +#: shared-module/jpegio/JpegDecoder.c shared-module/lvfontio/OnDiskFont.c +msgid "Invalid %q" +msgstr "Недопустимый %q" + +#: ports/analog/common-hal/busio/UART.c +msgid "Timeout must be < 100 seconds" +msgstr "" + +#: ports/atmel-samd/audio_dma.c +msgid "All sync event channels in use" +msgstr "Все каналы событий синхронизации уже используются" + +#: ports/atmel-samd/audio_dma.c ports/raspberrypi/audio_dma.c +msgid "Internal audio buffer too small" +msgstr "Внутренний звуковой буфер слишком мал" + +#: ports/atmel-samd/bindings/samd/Clock.c +msgid "calibration is read only" +msgstr "Калибровка доступна только для чтения" + +#: ports/atmel-samd/bindings/samd/Clock.c +msgid "calibration is out of range" +msgstr "Калибровка выходит за пределы допустимого диапазона" + +#: 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/meowmeow/mpconfigboard.h +msgid "You pressed both buttons at start up." +msgstr "Вы нажали обе кнопки при запуске." + +#: ports/atmel-samd/common-hal/_pew/PewPew.c +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/atmel-samd/common-hal/pulseio/PulseIn.c #: ports/atmel-samd/common-hal/pulseio/PulseOut.c #: ports/cxd56/common-hal/pulseio/PulseOut.c -msgid "Another send is already active" -msgstr "Другая передача уже активна" +#: ports/nordic/common-hal/audiopwmio/PWMAudioOut.c +#: ports/nordic/common-hal/pulseio/PulseIn.c +#: ports/nordic/peripherals/nrf/timers.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +#: ports/stm/common-hal/pulseio/PulseOut.c +msgid "All timers in use" +msgstr "Все таймеры уже используются" -#: shared-bindings/pulseio/PulseOut.c -msgid "Array must contain halfwords (type 'H')" -msgstr "Массив должен содержать полуслова (тип 'H')" +#: ports/atmel-samd/common-hal/alarm/pin/PinAlarm.c +#: ports/atmel-samd/common-hal/countio/Counter.c +#: ports/atmel-samd/common-hal/frequencyio/FrequencyIn.c +#: ports/atmel-samd/common-hal/max3421e/Max3421E.c +#: ports/atmel-samd/common-hal/ps2io/Ps2.c +#: ports/atmel-samd/common-hal/pulseio/PulseIn.c +#: ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.c +#: ports/cxd56/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c +#: ports/zephyr-cp/common-hal/async_spi/SPI.c +#: ports/zephyr-cp/common-hal/busio/I2C.c +#: ports/zephyr-cp/common-hal/busio/UART.c +msgid "Internal resource(s) in use" +msgstr "Используемые внутренние ресурсы" -#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c -#: shared-bindings/nvm/ByteArray.c -msgid "Array values should be single bytes." -msgstr "Значения массива должны быть однобайтовыми." +#: ports/atmel-samd/common-hal/alarm/pin/PinAlarm.c +#: supervisor/shared/safe_mode.c +msgid "Unknown reason." +msgstr "Причина неизвестна." -#: ports/atmel-samd/common-hal/spitarget/SPITarget.c -msgid "Async SPI transfer in progress on this bus, keep awaiting." -msgstr "" +#: ports/atmel-samd/common-hal/alarm/time/TimeAlarm.c +#: ports/nordic/common-hal/alarm/time/TimeAlarm.c +#: ports/stm/common-hal/alarm/time/TimeAlarm.c +msgid "Only one alarm.time alarm can be set" +msgstr "Можно установить только один будильник" -#: shared-module/memorymonitor/AllocationAlarm.c -#, c-format -msgid "Attempt to allocate %d blocks" -msgstr "Попытка выделения %d блоков" +#: ports/atmel-samd/common-hal/analogio/AnalogOut.c +#: ports/stm/common-hal/analogio/AnalogOut.c +#: ports/stm/common-hal/audioio/AudioOut.c +msgid "No DAC on chip" +msgstr "DAC отсутствует на чипе" -#: ports/raspberrypi/audio_dma.c -msgid "Audio conversion not implemented" -msgstr "Преобразование звука не реализовано" +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +msgid "%q and %q must share a clock unit" +msgstr "%q и %q должны иметь общую единицу тактового генератора" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +msgid "Serializer in use" +msgstr "Сериализатор используется" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +msgid "Clock unit in use" +msgstr "Источник тактирования уже используется" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/atmel-samd/common-hal/touchio/TouchIn.c +msgid "No free GCLKs" +msgstr "Свободные GCLK отсутствуют" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +msgid "Too many channels in sample" +msgstr "Слишком много каналов в выборке" +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/atmel-samd/common-hal/audioio/AudioOut.c #: ports/raspberrypi/common-hal/audiobusio/I2SOut.c #: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c -msgid "Audio source error" -msgstr "" - -#: shared-bindings/wifi/Radio.c -msgid "AuthMode.OPEN is not used with password" -msgstr "Режим авторизации.OPEN не используется с паролем" +#: ports/raspberrypi/common-hal/mcp4822/MCP4822.c +msgid "No DMA channel found" +msgstr "Канал DMA не найден" -#: shared-bindings/wifi/Radio.c supervisor/shared/web_workflow/web_workflow.c -msgid "Authentication failure" -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 +#: ports/raspberrypi/common-hal/mcp4822/MCP4822.c +msgid "Unable to allocate buffers for signed conversion" +msgstr "Не удается выделить буферы для подписанного преобразования" -#: main.c -msgid "Auto-reload is off.\n" -msgstr "Автоматическая перезагрузка отключена.\n" +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c +#, c-format +msgid "Only 8 or 16 bit mono with %dx oversampling supported." +msgstr "Поддерживается только 8 или 16-битное моно с передискретизацией %dx." -#: main.c -msgid "" -"Auto-reload is on. Simply save files over USB to run them or enter REPL to " -"disable.\n" -msgstr "" -"Автоматическая перезагрузка включена. Просто сохрани файл по USB или зайди в " -"REPL чтобы отключить.\n" +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c +msgid "sampling rate out of range" +msgstr "Частота дискретизации выходит за пределы допустимого диапазона" -#: ports/espressif/common-hal/canio/CAN.c -msgid "Baudrate not supported by peripheral" -msgstr "Скорость передачи данных не поддерживается периферийным устройством" +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +msgid "DAC already in use" +msgstr "DAC уже используется" -#: shared-module/busdisplay/BusDisplay.c -#: shared-module/framebufferio/FramebufferDisplay.c -msgid "Below minimum frame rate" -msgstr "Ниже минимальной частоты кадров" +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +msgid "Right channel unsupported" +msgstr "Правый канал не поддерживается" -#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c -msgid "Bit clock and word select must be sequential GPIO pins" -msgstr "Несколько часов и слов должны быть последовательными GPIO пинами" +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +msgid "All event channels in use" +msgstr "Все каналы событий уже используются" -#: shared-bindings/bitmaptools/__init__.c -msgid "Bitmap size and bits per value must match" -msgstr "" -"Размер растрового изображения и число битов на значение должны совпадать" +#: ports/atmel-samd/common-hal/busio/I2C.c +#: ports/espressif/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nordic/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 "На SDA или SCL не обнаружено подтягивания; проверь свою проводку" -#: supervisor/shared/safe_mode.c -msgid "Boot device must be first (interface #0)." -msgstr "Загрузочное устройство должно быть первым (интерфейс #0)." +#: ports/atmel-samd/common-hal/busio/UART.c +#: shared-bindings/usb_host_bulk/InStream.c +msgid "%q must be power of 2" +msgstr "%q должен быть во 2-й степени" +#: ports/atmel-samd/common-hal/busio/UART.c +#: ports/espressif/common-hal/busio/SPI.c +#: ports/espressif/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/SPI.c #: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Both RX and TX required for flow control" -msgstr "Для управления потоком требуется как RX так и TX" +#: ports/nordic/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c ports/stm/common-hal/busio/SPI.c +#: ports/stm/common-hal/busio/UART.c shared-bindings/fourwire/FourWire.c +#: shared-bindings/i2cdisplaybus/I2CDisplayBus.c +#: shared-bindings/paralleldisplaybus/ParallelBus.c +#: shared-bindings/qspibus/QSPIBus.c shared-module/bitbangio/SPI.c +msgid "No %q pin" +msgstr "Нет пина %q" -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -msgid "Brightness not adjustable" -msgstr "Яркость не регулируется" +#: ports/atmel-samd/common-hal/canio/Listener.c +#: ports/espressif/common-hal/canio/Listener.c +#: ports/stm/common-hal/canio/Listener.c +msgid "All RX FIFOs in use" +msgstr "Все RX FIFO уже используются" -#: shared-bindings/_bleio/UUID.c +#: ports/atmel-samd/common-hal/canio/Listener.c +msgid "Already have all-matches listener" +msgstr "Уже есть универсальный слушатель" + +#: ports/atmel-samd/common-hal/canio/Listener.c +#: ports/espressif/common-hal/canio/Listener.c +#: ports/mimxrt10xx/common-hal/canio/Listener.c +#: ports/stm/common-hal/canio/Listener.c +msgid "Filters too complex" +msgstr "Фильтры слишком сложные" + +#: ports/atmel-samd/common-hal/digitalio/DigitalInOut.c +#: ports/mimxrt10xx/common-hal/digitalio/DigitalInOut.c +#: ports/nordic/common-hal/digitalio/DigitalInOut.c +#: ports/raspberrypi/common-hal/digitalio/DigitalInOut.c +msgid "Cannot get pull while in output mode" +msgstr "Невозможно получить pull в режиме вывода" + +#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c #, c-format -msgid "Buffer + offset too small %d %d %d" -msgstr "Буфер + сдвиг слишком малы %d %d %d" +msgid "Invalid data_pins[%d]" +msgstr "Неверный data_pins[%d]" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "Buffer elements must be 4 bytes long or less" -msgstr "Элементы буфера должны иметь длину не более 4 байт" +#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c +#, c-format +msgid "data pin #%d in use" +msgstr "data-пин #%d уже используется" -#: shared-bindings/framebufferio/FramebufferDisplay.c -msgid "Buffer is not a bytearray." -msgstr "Буфер не является байтовым массивом." +#: ports/atmel-samd/common-hal/microcontroller/Pin.c +#: ports/espressif/common-hal/dotclockframebuffer/DotClockFramebuffer.c +#: ports/mimxrt10xx/common-hal/microcontroller/Pin.c +#: shared-bindings/emmcio/EMMC.c shared-bindings/microcontroller/Pin.c +msgid "Invalid %q pin" +msgstr "Недопустимый пин %q" -#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +#: ports/atmel-samd/common-hal/microcontroller/__init__.c +#: ports/cxd56/common-hal/microcontroller/__init__.c +#: ports/mimxrt10xx/common-hal/microcontroller/__init__.c +msgid "No bootloader present" +msgstr "Отсутствует загрузчик" + +#: ports/atmel-samd/common-hal/paralleldisplaybus/ParallelBus.c +#: ports/nordic/common-hal/paralleldisplaybus/ParallelBus.c +msgid "Data 0 pin must be byte aligned" +msgstr "Пин data 0 должен быть байтово выровнен" + +#: ports/atmel-samd/common-hal/paralleldisplaybus/ParallelBus.c +#: ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c +#: ports/nordic/common-hal/paralleldisplaybus/ParallelBus.c +#: ports/raspberrypi/common-hal/paralleldisplaybus/ParallelBus.c #, c-format -msgid "Buffer length %d too big. It must be less than %d" -msgstr "Размер буфера %d слишком большой. Он должен быть меньше чем %d" +msgid "Bus pin %d is already in use" +msgstr "Вывод шины %d уже используется" + +#: ports/atmel-samd/common-hal/pulseio/PulseIn.c +#: ports/cxd56/common-hal/pulseio/PulseIn.c +#: ports/nordic/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 "Всплывающее окно из пустого %q" + +#: ports/atmel-samd/common-hal/pulseio/PulseIn.c +msgid "Input taking too long" +msgstr "Ввод занимает слишком много времени" + +#: ports/atmel-samd/common-hal/pulseio/PulseOut.c +#: ports/cxd56/common-hal/pulseio/PulseOut.c +msgid "Another send is already active" +msgstr "Другая передача уже активна" + +#: ports/atmel-samd/common-hal/sdioio/SDCard.c +#: ports/espressif/common-hal/mii/Ethernet.c +#: ports/espressif/common-hal/qspibus/QSPIBus.c shared-bindings/emmcio/EMMC.c +#: shared-bindings/socketpool/SocketPool.c +msgid "%q failure: %d" +msgstr "%q сбой: %d" #: ports/atmel-samd/common-hal/sdioio/SDCard.c #: ports/cxd56/common-hal/sdioio/SDCard.c #: ports/espressif/common-hal/sdioio/SDCard.c -#: ports/stm/common-hal/sdioio/SDCard.c shared-bindings/floppyio/__init__.c -#: shared-module/sdcardio/SDCard.c +#: ports/raspberrypi/common-hal/sdioio/SDCard.c +#: ports/stm/common-hal/sdioio/SDCard.c shared-bindings/audiocore/WaveFile.c +#: shared-bindings/emmcio/EMMC.c shared-bindings/floppyio/__init__.c +#: shared-bindings/picogame/Canvas.c shared-module/sdcardio/SDCard.c #, c-format msgid "Buffer must be a multiple of %d bytes" msgstr "Буфер должен быть кратен %d байт" -#: shared-bindings/_bleio/PacketBuffer.c -#, c-format -msgid "Buffer too short by %d bytes" -msgstr "Буфер слишком короткий на %d байт" +#: ports/atmel-samd/common-hal/spitarget/SPITarget.c +msgid "Async SPI transfer in progress on this bus, keep awaiting." +msgstr "" + +#: ports/cxd56/common-hal/busio/UART.c ports/espressif/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c +msgid "UART init" +msgstr "Инициализация UART" + +#: ports/cxd56/common-hal/camera/Camera.c +msgid "Camera init" +msgstr "Иницализация камеры" + +#: ports/cxd56/common-hal/camera/Camera.c +msgid "Size not supported" +msgstr "Размер не поддерживается" #: ports/cxd56/common-hal/camera/Camera.c #: shared-bindings/busdisplay/BusDisplay.c #: shared-bindings/framebufferio/FramebufferDisplay.c #: shared-bindings/struct/__init__.c shared-module/struct/__init__.c +#: shared-module/videocore/VideoBuffer.c msgid "Buffer too small" msgstr "Слишком маленький буфер" -#: ports/atmel-samd/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/nordic/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/raspberrypi/common-hal/paralleldisplaybus/ParallelBus.c -#, c-format -msgid "Bus pin %d is already in use" -msgstr "Вывод шины %d уже используется" - -#: shared-bindings/_bleio/UUID.c -msgid "Byte buffer must be 16 bytes." -msgstr "Буфер байтов должен быть размером 16 байтам." +#: ports/cxd56/common-hal/camera/Camera.c +#: ports/espressif/common-hal/jpegio/JpegDecoder.c +#: shared-module/audiocore/WaveFile.c +#: shared-module/busdisplay/lvgl/BusDisplay.c +#: shared-module/displayio/lvgl/TileGrid.c +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "Format not supported" +msgstr "Формат не поддерживается" -#: shared-bindings/aesio/aes.c -msgid "CBC blocks must be multiples of 16 bytes" -msgstr "Блоки CBC должны быть кратны 16 байтам" +#: ports/cxd56/common-hal/gnss/GNSS.c +msgid "GNSS init" +msgstr "Инициализация GNSS" -#: supervisor/shared/safe_mode.c -msgid "CIRCUITPY drive could not be found or created." -msgstr "Диск CIRCUTPY не удалось найти или создать." +#: ports/cxd56/common-hal/sdioio/SDCard.c +msgid "SDCard init" +msgstr "Инициализация SD-карты" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "CRC or checksum was invalid" -msgstr "CRC или контрольная сумма неправильная" +#: ports/espressif/bindings/espnow/ESPNow.c +#: ports/espressif/common-hal/espulp/ULP.c +#: ports/raspberrypi/common-hal/usb_host_bulk/InStream.c +#: shared-module/memorymonitor/AllocationAlarm.c +#: shared-module/memorymonitor/AllocationSize.c +msgid "Already running" +msgstr "Уже запущен" -#: py/objtype.c -msgid "Call super().__init__() before accessing native object." -msgstr "Вызовите super().__init__() перед доступом к собственному объекту." +#: ports/espressif/bindings/espnow/Peer.c shared-bindings/dualbank/__init__.c +msgid "%q is %q" +msgstr "%q является %q" -#: ports/cxd56/common-hal/camera/Camera.c -msgid "Camera init" -msgstr "Иницализация камеры" +#: ports/espressif/boards/adafruit_feather_esp32_v2/mpconfigboard.h +msgid "You pressed the SW38 button at start up." +msgstr "Вы нажали кнопку SW38 при запуске." -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Can only alarm on RTC IO from deep sleep." -msgstr "Возможен только сигнал тревоги по RTC IO из глубокого сна." +#: ports/espressif/boards/adafruit_feather_esp32c6_4mbflash_nopsram/mpconfigboard.h +#: ports/espressif/boards/adafruit_itsybitsy_esp32/mpconfigboard.h +#: ports/espressif/boards/waveshare_esp32_c5_lcd_1_47/mpconfigboard.h +#: ports/espressif/boards/waveshare_esp32_c6_lcd_1_47/mpconfigboard.h +msgid "You pressed the BOOT button at start up." +msgstr "При запуске вы нажали кнопку BOOT." -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Can only alarm on one low pin while others alarm high from deep sleep." -msgstr "" -"Может сигнализировать только по одному низкому контакту в то время как " -"другие сигнализируют о высоком уровне после глубокого сна." +#: ports/espressif/boards/adafruit_huzzah32_breakout/mpconfigboard.h +msgid "You pressed the GPIO0 button at start up." +msgstr "Вы нажали кнопку GPIO0 при запуске." -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Can only alarm on two low pins from deep sleep." -msgstr "" -"Из глубокого сна может сигнализировать только по двум низким контактам." +#: ports/espressif/boards/espressif_esp32_lyrat/mpconfigboard.h +msgid "You pressed the Rec button at start up." +msgstr "Вы нажали кнопку «Запись» при запуске." -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Can't construct AudioOut because continuous channel already open" -msgstr "" +#: ports/espressif/boards/hardkernel_odroid_go/mpconfigboard.h +#: ports/espressif/boards/vidi_x/mpconfigboard.h +msgid "You pressed the VOLUME button at start up." +msgstr "Вы нажали кнопку ГРОМКОСТЬ при запуске." -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Characteristic.c -msgid "Can't set CCCD on local Characteristic" -msgstr "Невозможно установить CCCD для локальной характеристики" +#: ports/espressif/boards/m5stack_atom_echo/mpconfigboard.h +#: ports/espressif/boards/m5stack_atom_lite/mpconfigboard.h +#: ports/espressif/boards/m5stack_atom_matrix/mpconfigboard.h +#: ports/espressif/boards/m5stack_atom_u/mpconfigboard.h +msgid "You pressed the central button at start up." +msgstr "Вы нажали центральную кнопку при запуске." -#: shared-bindings/storage/__init__.c shared-bindings/usb_cdc/__init__.c -#: shared-bindings/usb_hid/__init__.c shared-bindings/usb_midi/__init__.c -#: shared-bindings/usb_video/__init__.c -msgid "Cannot change USB devices now" -msgstr "Невозможно изменить USB устройство сейчас" +#: ports/espressif/boards/m5stack_core_basic/mpconfigboard.h +#: ports/espressif/boards/m5stack_core_fire/mpconfigboard.h +#: ports/espressif/boards/m5stack_stick_c/mpconfigboard.h +#: ports/espressif/boards/m5stack_stick_c_plus/mpconfigboard.h +#: ports/espressif/boards/m5stack_stick_c_plus2/mpconfigboard.h +msgid "You pressed button A at start up." +msgstr "Вы нажали кнопку A при запуске." -#: shared-bindings/_bleio/Adapter.c -msgid "Cannot create a new Adapter; use _bleio.adapter;" -msgstr "Невозможно создать новый Adapter; используйте _bleio.adapter;" +#: ports/espressif/boards/m5stack_m5paper/mpconfigboard.h +msgid "You pressed button DOWN at start up." +msgstr "Вы нажали кнопку ВНИЗ при запуске." -#: shared-bindings/displayio/Bitmap.c -#: shared-bindings/memorymonitor/AllocationSize.c -#: shared-bindings/pulseio/PulseIn.c -msgid "Cannot delete values" -msgstr "Невозможно удалить значения" +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/espressif/common-hal/dualbank/__init__.c +msgid "Update failed" +msgstr "Обновление не удалось" -#: ports/atmel-samd/common-hal/digitalio/DigitalInOut.c -#: ports/mimxrt10xx/common-hal/digitalio/DigitalInOut.c -#: ports/nordic/common-hal/digitalio/DigitalInOut.c -#: ports/raspberrypi/common-hal/digitalio/DigitalInOut.c -msgid "Cannot get pull while in output mode" -msgstr "Невозможно получить pull в режиме вывода" +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "Scan already in progress. Stop with stop_scan." +msgstr "Сканирование уже выполняется. Остановитесь на stop_scan." -#: ports/nordic/common-hal/microcontroller/Processor.c -msgid "Cannot get temperature" -msgstr "Невозможно получить температуру" +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +#: ports/zephyr-cp/common-hal/_bleio/Adapter.c +msgid "Failed to connect: timeout" +msgstr "Не удалось подключиться: таймаут" -#: shared-bindings/_bleio/Adapter.c -msgid "Cannot have scan responses for extended, connectable advertisements." -msgstr "" -"Не может быть ответов на сканирование для расширенных подключаемых рекламных " -"объявлений." +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +#: ports/zephyr-cp/common-hal/_bleio/Adapter.c +msgid "Failed to connect: internal error" +msgstr "Не удалось подключиться: внутренняя ошибка" -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Cannot pull on input-only pin." -msgstr "Невозможно вытащить контакт только для ввода." +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +#: ports/zephyr-cp/common-hal/_bleio/Adapter.c +msgid "Data too large for advertisement packet" +msgstr "Данные слишком велики для пакета объявления" -#: shared-bindings/audiobusio/PDMIn.c -msgid "Cannot record to a file" -msgstr "Невозможно записать в файл" +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "Already advertising." +msgstr "Уже реклама." -#: shared-module/storage/__init__.c -msgid "Cannot remount '/' when visible via USB." -msgstr "Невозможно перемонтировать '/' пока он виден через USB." +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "Extended advertisements with scan response not supported." +msgstr "Расширенные объявления с ответом сканирования не поддерживаются." -#: shared-bindings/digitalio/DigitalInOut.c -msgid "Cannot set value when direction is input." -msgstr "Невозможно установить значение при вводе направления." +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "Data not supported with directed advertising" +msgstr "Данные не поддерживаются направленным объявлением" -#: ports/espressif/common-hal/busio/UART.c -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Cannot specify RTS or CTS in RS485 mode" -msgstr "Невозможно указать RTS или CTS в режиме RS485" +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +#, c-format +msgid "Timeout is too long: Maximum timeout length is %d seconds" +msgstr "Таймаут слишком длинный: максимальная длина таймаута %d секунд" -#: py/objslice.c -msgid "Cannot subclass slice" -msgstr "Невозможно создать подкласс среза" +#: ports/espressif/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Descriptor.c +msgid "Value length != required fixed length" +msgstr "Длина значения! = требуемая фиксированная длина" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Cannot use GPIO0..15 together with GPIO32..47" -msgstr "Невозможно использовать GPIO0..15 вместе с GPIO32..47" +#: ports/espressif/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Descriptor.c +msgid "Value length > max_length" +msgstr "Длина значения > максимальная_длина" -#: ports/nordic/common-hal/alarm/pin/PinAlarm.c -msgid "Cannot wake on pin edge, only level" +#: ports/espressif/common-hal/_bleio/Characteristic.c +#: ports/espressif/common-hal/_bleio/Service.c +#: ports/raspberrypi/common-hal/alarm/pin/PinAlarm.c +#: ports/raspberrypi/common-hal/usb_host_bulk/InStream.c +msgid "Too many %q" msgstr "" -"Невозможно проснуться по изменению логического уровня, только по уровню" -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Cannot wake on pin edge. Only level." -msgstr "Невозможно проснуться по спаду росту на пине. Только по уровню." +#: ports/espressif/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Characteristic.c +#: ports/zephyr-cp/common-hal/_bleio/Characteristic.c +msgid "No CCCD for this Characteristic" +msgstr "Для этой характеристики нет CCCD" + +#: ports/espressif/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Characteristic.c +msgid "Can't set CCCD on local Characteristic" +msgstr "Невозможно установить CCCD для локальной характеристики" +#: ports/espressif/common-hal/_bleio/Connection.c +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/Characteristic.c +#: ports/zephyr-cp/common-hal/_bleio/Connection.c +#: ports/zephyr-cp/common-hal/_bleio/Descriptor.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c #: shared-bindings/_bleio/CharacteristicBuffer.c -msgid "CharacteristicBuffer writing not provided" -msgstr "ХарактеристикаЗапись в буфер не предусмотрена" +msgid "Not connected" +msgstr "Не подключено" -#: supervisor/shared/safe_mode.c -msgid "CircuitPython core code crashed hard. Whoops!\n" -msgstr "Основной код CircuitPython сильно разбился. Упс!\n" +#: ports/espressif/common-hal/_bleio/Connection.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/Connection.c +msgid "" +"Unspecified issue. The pairing request on the other device may have been " +"declined or ignored." +msgstr "" -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -msgid "Clock unit in use" -msgstr "Источник тактирования уже используется" +#: ports/espressif/common-hal/_bleio/Connection.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/Connection.c +#, c-format +msgid "Unknown security error: 0x%04x" +msgstr "Неизвестная ошибка безопасности: 0x%04x" -#: shared-bindings/_bleio/Connection.c -msgid "" -"Connection has been disconnected and can no longer be used. Create a new " -"connection." +#: ports/espressif/common-hal/_bleio/Connection.c +msgid "No pairing in progress" msgstr "" -"Соединение было отключено и больше не может использоваться. Создайте новое " -"соединение." -#: shared-bindings/bitmaptools/__init__.c -msgid "Coordinate arrays have different lengths" -msgstr "Координатные массивы имеют разные длины" +#: ports/espressif/common-hal/_bleio/Connection.c +#: ports/nordic/common-hal/_bleio/Connection.c +msgid "non-UUID found in service_uuids_whitelist" +msgstr "не-UUID найден в сервисе_uuids_белый список" + +#: ports/espressif/common-hal/_bleio/Descriptor.c +#: ports/nordic/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Descriptor.c +#, c-format +msgid "max_length must be 0-%d when fixed_length is %s" +msgstr "максимальная_длина должна быть 0-%d когда фиксированная длина %s" + +#: ports/espressif/common-hal/_bleio/PacketBuffer.c +#: ports/nordic/common-hal/_bleio/PacketBuffer.c +#: ports/zephyr-cp/common-hal/_bleio/PacketBuffer.c +msgid "Writes not supported on Characteristic" +msgstr "Запись не поддерживается в Характеристика" -#: shared-bindings/bitmaptools/__init__.c -msgid "Coordinate arrays types have different sizes" -msgstr "Типы массивов координат имеют разные размеры" +#: ports/espressif/common-hal/_bleio/PacketBuffer.c +#: ports/nordic/common-hal/_bleio/PacketBuffer.c +#: ports/zephyr-cp/common-hal/_bleio/PacketBuffer.c +msgid "Total data to write is larger than %q" +msgstr "Общее количество данных для записи превышает %q" -#: shared-bindings/_bleio/Adapter.c -msgid "Could not set address" -msgstr "Не удалось задать адрес" +#: ports/espressif/common-hal/_bleio/__init__.c +msgid "Nimble out of memory" +msgstr "Изображение памяти" -#: ports/stm/common-hal/busio/UART.c -msgid "Could not start interrupt, RX busy" -msgstr "Не удалось запустить прерывание, RX занят" +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +msgid "Invalid BLE parameter" +msgstr "Недопустимый параметр BLE" -#: shared-module/audiomp3/MP3Decoder.c -msgid "Couldn't allocate decoder" -msgstr "Не удалось выделить место для декодера" +#: ports/espressif/common-hal/_bleio/__init__.c +#: shared-module/audiofilewriter/AudioFileWriter.c +msgid "Already in progress" +msgstr "Уже в процессе" -#: ports/stm/common-hal/analogio/AnalogOut.c -msgid "DAC Channel Init Error" -msgstr "Ошибка инициализации канала DAC" +#: ports/espressif/common-hal/_bleio/__init__.c +#, c-format +msgid "Unknown BLE error at %s:%d: 0x%04x" +msgstr "" -#: ports/stm/common-hal/analogio/AnalogOut.c -msgid "DAC Device Init Error" -msgstr "Ошибка инициализации устройства DAC" +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#, c-format +msgid "Unknown BLE error: 0x%04x" +msgstr "" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c -msgid "DAC already in use" -msgstr "DAC уже используется" +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +msgid "%q not permitted" +msgstr "" -#: ports/atmel-samd/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/nordic/common-hal/paralleldisplaybus/ParallelBus.c -msgid "Data 0 pin must be byte aligned" -msgstr "Пин data 0 должен быть байтово выровнен" +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +msgid "Insufficient authentication" +msgstr "Неполная аутентификация" -#: shared-module/jpegio/JpegDecoder.c -msgid "Data format error (may be broken data)" -msgstr "Ошибка формата данных (возможно, данные повреждены)" +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +msgid "Insufficient authorization" +msgstr "" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Data not supported with directed advertising" -msgstr "Данные не поддерживаются направленным объявлением" +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +msgid "Insufficient encryption" +msgstr "Недостаточное шифрование" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Data too large for advertisement packet" -msgstr "Данные слишком велики для пакета объявления" +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +#, c-format +msgid "Unknown gatt error: 0x%04x" +msgstr "Неизвестная ошибка gatt: 0x%04x" -#: ports/stm/common-hal/alarm/pin/PinAlarm.c -msgid "Deep sleep pins must use a rising edge with pulldown" -msgstr "" -"Выводы глубокого сна должны использовать сигнал по возрастанию с подтяжкой к " -"земле" +#: ports/espressif/common-hal/alarm/pin/PinAlarm.c +msgid "Cannot wake on pin edge. Only level." +msgstr "Невозможно проснуться по спаду росту на пине. Только по уровню." -#: shared-bindings/audiobusio/PDMIn.c -msgid "Destination capacity is smaller than destination_length." -msgstr "Емкость места назначения меньше длины места назначения." +#: ports/espressif/common-hal/alarm/pin/PinAlarm.c +msgid "Cannot pull on input-only pin." +msgstr "Невозможно вытащить контакт только для ввода." -#: shared-module/jpegio/JpegDecoder.c -msgid "Device error or wrong termination of input stream" -msgstr "Ошибка устройства или неправильное завершение входного потока" +#: ports/espressif/common-hal/alarm/pin/PinAlarm.c +msgid "Can only alarm on two low pins from deep sleep." +msgstr "" +"Из глубокого сна может сигнализировать только по двум низким контактам." -#: ports/nordic/common-hal/audiobusio/I2SOut.c -msgid "Device in use" -msgstr "Устройство используется" +#: ports/espressif/common-hal/alarm/pin/PinAlarm.c +msgid "Can only alarm on one low pin while others alarm high from deep sleep." +msgstr "" +"Может сигнализировать только по одному низкому контакту в то время как " +"другие сигнализируют о высоком уровне после глубокого сна." -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -msgid "Display must have a 16 bit colorspace." -msgstr "Дисплей должен иметь 16 битное цветовое пространство." +#: ports/espressif/common-hal/alarm/pin/PinAlarm.c +msgid "Can only alarm on RTC IO from deep sleep." +msgstr "Возможен только сигнал тревоги по RTC IO из глубокого сна." -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/epaperdisplay/EPaperDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -msgid "Display rotation must be in 90 degree increments" -msgstr "Поворот дисплея должен осуществляться с шагом 90 градусов" +#: ports/espressif/common-hal/alarm/time/TimeAlarm.c +#: ports/raspberrypi/common-hal/alarm/time/TimeAlarm.c +msgid "Only one alarm.time alarm can be set." +msgstr "Можно установить только один будильник alarm.time." -#: main.c -msgid "Done" -msgstr "Выполнено" +#: ports/espressif/common-hal/alarm/touch/TouchAlarm.c +msgid "Only one %q can be set in deep sleep." +msgstr "Только один %q может быть переведен в режим глубокого сна." -#: shared-bindings/digitalio/DigitalInOut.c -msgid "Drive mode not used when direction is input." -msgstr "Режим движения не используется при вводе направления." +#: ports/espressif/common-hal/analogbufio/BufferedIn.c +msgid "%q must be array of type 'H'" +msgstr "%q должен быть массивом типа 'H \"" -#: py/obj.c -msgid "During handling of the above exception, another exception occurred:" +#: ports/espressif/common-hal/audiobusio/PDMIn.c +#: shared-bindings/audioi2sin/I2SIn.c shared-bindings/usb_host_audio/USBIn.c +msgid "%q must be 8, 16, 24, or 32" msgstr "" -"При обращении с вышеуказанным исключением произошло еще одно исключение:" - -#: shared-bindings/aesio/aes.c -msgid "ECB only operates on 16 bytes at a time" -msgstr "ECB работает только с 16 байтами за раз" -#: ports/espressif/common-hal/busio/SPI.c -#: ports/espressif/common-hal/canio/CAN.c -msgid "ESP-IDF memory allocation failed" -msgstr "Ошибка выделения памяти ESP-IDF" +#: ports/espressif/common-hal/audiobusio/__init__.c +#: ports/espressif/common-hal/audioi2sin/I2SIn.c +#: ports/espressif/common-hal/mii/Ethernet.c shared-bindings/emmcio/EMMC.c +msgid "Peripheral in use" +msgstr "Периферийные устройства в использовании" -#: extmod/modre.c -msgid "Error in regex" -msgstr "Ошибка в регулярном выражении" +#: ports/espressif/common-hal/audioi2sin/I2SIn.c +#: ports/raspberrypi/common-hal/audioi2sin/I2SIn.c +msgid "%q must be 8 or 16" +msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Error in safemode.py." -msgstr "Ошибка в сейфе. py." +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "audio format not supported" +msgstr "" -#: shared-bindings/alarm/__init__.c -msgid "Expected a kind of %q" -msgstr "Ожидаемый вид %q" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to start async audio" +msgstr "" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Extended advertisements with scan response not supported." -msgstr "Расширенные объявления с ответом сканирования не поддерживаются." +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to create continuous channels: invalid arg" +msgstr "" -#: extmod/ulab/code/numpy/fft/fft_tools.c -msgid "FFT is defined for ndarrays only" -msgstr "FFT определено только для массивов ndarrays" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to create continuous channels: invalid state" +msgstr "" -#: extmod/ulab/code/numpy/fft/fft_tools.c -msgid "FFT is implemented for linear arrays only" -msgstr "FFT реализовано только для линейных массивов" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to create continuous channels: not found" +msgstr "" -#: shared-bindings/ps2io/Ps2.c -msgid "Failed sending command." -msgstr "Не удалось отправить команду." +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to create continuous channels: no mem" +msgstr "" -#: ports/nordic/sd_mutex.c -#, c-format -msgid "Failed to acquire mutex, err 0x%04x" -msgstr "Не удалось получить mutex, ошибка 0x%04x" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to register continuous events callback" +msgstr "" -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "Failed to add service TXT record" -msgstr "Не удалось добавить служебную запись TXT" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to enable continuous" +msgstr "" -#: shared-bindings/mdns/Server.c -msgid "" -"Failed to add service TXT record; non-string or bytes found in txt_records" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Can't construct AudioOut because continuous channel already open" msgstr "" -"Не удалось добавить служебную TXT-запись; в txt_records обнаружена нестрока " -"или байт" -#: shared-module/rgbmatrix/RGBMatrix.c -msgid "Failed to allocate %q buffer" -msgstr "Не удалось выделить буфер %q" +#: ports/espressif/common-hal/audioio/AudioOut.c +#: ports/espressif/common-hal/mipicsi/Camera.c +#: shared-module/videocore/VideoBuffer.c shared-module/videogif/GifDecoder.c +msgid "already playing" +msgstr "" -#: ports/espressif/common-hal/wifi/__init__.c -msgid "Failed to allocate Wifi memory" -msgstr "Не удалось выделить память Wifi" +#: ports/espressif/common-hal/busio/I2C.c +#: ports/espressif/common-hal/i2ctarget/I2CTarget.c +#: ports/nordic/common-hal/busio/I2C.c ports/zephyr-cp/common-hal/busio/I2C.c +msgid "All I2C peripherals are in use" +msgstr "Все периферийные устройства I2C уже используются" -#: ports/espressif/common-hal/wifi/ScannedNetworks.c -msgid "Failed to allocate wifi scan memory" -msgstr "Не удалось выделить память для сканирования wifi" +#: ports/espressif/common-hal/busio/I2C.c +#: ports/espressif/common-hal/busio/SPI.c +msgid "Unable to create lock" +msgstr "Не удается создать блокировку" -#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c -msgid "Failed to buffer the sample" -msgstr "Не удалось выполнить буферизацию образца" +#: ports/espressif/common-hal/busio/SPI.c +msgid "SPI configuration failed" +msgstr "Сбой конфигурации SPI" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Failed to connect: internal error" -msgstr "Не удалось подключиться: внутренняя ошибка" +#: ports/espressif/common-hal/busio/SPI.c ports/nordic/common-hal/busio/SPI.c +#: ports/zephyr-cp/common-hal/async_spi/SPI.c +msgid "All SPI peripherals are in use" +msgstr "Все периферийные устройства SPI уже используются" -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Failed to connect: timeout" -msgstr "Не удалось подключиться: таймаут" +#: ports/espressif/common-hal/busio/SPI.c +#: ports/espressif/common-hal/canio/CAN.c +#: ports/espressif/common-hal/qspibus/QSPIBus.c +msgid "ESP-IDF memory allocation failed" +msgstr "Ошибка выделения памяти ESP-IDF" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to create continuous channels: invalid arg" -msgstr "" +#: ports/espressif/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c +msgid "Cannot specify RTS or CTS in RS485 mode" +msgstr "Невозможно указать RTS или CTS в режиме RS485" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to create continuous channels: invalid state" -msgstr "" +#: ports/espressif/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c +msgid "RS485 inversion specified when not in RS485 mode" +msgstr "Инверсия RS485 указана, когда она не находится в режиме RS485" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to create continuous channels: no mem" -msgstr "" +#: ports/espressif/common-hal/canio/CAN.c +msgid "Baudrate not supported by peripheral" +msgstr "Скорость передачи данных не поддерживается периферийным устройством" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to create continuous channels: not found" -msgstr "" +#: ports/espressif/common-hal/canio/CAN.c +msgid "All CAN peripherals are in use" +msgstr "Все периферийные устройства CAN уже используются" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to enable continuous" +#: ports/espressif/common-hal/canio/CAN.c +msgid "loopback + silent mode not supported by peripheral" msgstr "" +"Замыкание на себя + бесшумный режим, не поддерживаемый периферийными " +"устройствами" -#: shared-module/audiomp3/MP3Decoder.c -msgid "Failed to parse MP3 file" -msgstr "Не удалось распарсить файл MP3" - -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to register continuous events callback" -msgstr "" +#: ports/espressif/common-hal/canio/CAN.c +#, c-format +msgid "twai_driver_install returned esp-idf error #%d" +msgstr "twai_driver_install вернул ошибку esp-idf #%d" -#: ports/nordic/sd_mutex.c +#: ports/espressif/common-hal/canio/CAN.c #, c-format -msgid "Failed to release mutex, err 0x%04x" -msgstr "Не удалось освободить mutex, ошибка 0x%04x" +msgid "twai_start returned esp-idf error #%d" +msgstr "twai_start вернул ошибку esp-idf #%d" -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "Failed to set hostname" +#: ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "ds_params has the wrong length" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to start async audio" +#: ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "" +"This key already committed to a different algorithm; call " +"load_digital_signature_key() again to use a different one" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Failed to write internal flash." -msgstr "Не удалось записать внутреннюю флэш-память." +#: ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "" +"This key's ds_params were replaced by a later load_digital_signature_key() " +"call for the same key slot" +msgstr "" -#: py/moderrno.c -msgid "File exists" -msgstr "Файл существует" +#: ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "ds_params is invalid for this key slot" +msgstr "" -#: shared-module/os/getenv.c -msgid "File not found" -msgstr "Файл не найден" +#: ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "Digital Signature peripheral not available on this chip" +msgstr "" -#: ports/atmel-samd/common-hal/canio/Listener.c -#: ports/espressif/common-hal/canio/Listener.c -#: ports/mimxrt10xx/common-hal/canio/Listener.c -#: ports/stm/common-hal/canio/Listener.c -msgid "Filters too complex" -msgstr "Фильтры слишком сложные" +#: ports/espressif/common-hal/dotclockframebuffer/DotClockFramebuffer.c +msgid "Must provide 5/6/5 RGB pins" +msgstr "Должен иметь 5/6/5 контактов RGB" #: ports/espressif/common-hal/dualbank/__init__.c msgid "Firmware is duplicate" @@ -1105,1738 +1683,1883 @@ msgstr "Недопустимая прошивка" msgid "Firmware is too big" msgstr "Прошивка слишком большая" -#: shared-bindings/bitmaptools/__init__.c -msgid "For L8 colorspace, input bitmap must have 8 bits per pixel" -msgstr "" -"Для цветового пространства L8 входное растровое изображение должно иметь 8 " -"бит на пиксель" +#: ports/espressif/common-hal/espcamera/Camera.c py/objobject.c py/runtime.c +msgid "no such attribute" +msgstr "нет такого атрибута" -#: shared-bindings/bitmaptools/__init__.c -msgid "For RGB colorspaces, input bitmap must have 16 bits per pixel" -msgstr "" -"Для цветовых пространств RGB входное растровое изображение должно иметь 16 " -"бит на пиксель" +#: ports/espressif/common-hal/espcamera/Camera.c +msgid "invalid setting" +msgstr "Недопустимый параметр" -#: ports/cxd56/common-hal/camera/Camera.c -msgid "Format not supported" -msgstr "Формат не поддерживается" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "Generic Failure" +msgstr "Общий сбой" -#: ports/mimxrt10xx/common-hal/microcontroller/Processor.c -msgid "" -"Frequency must be 24, 150, 396, 450, 528, 600, 720, 816, 912, 960 or 1008 Mhz" -msgstr "" -"Частота должна быть 24, 150, 396, 450, 528, 600, 720, 816, 912, 960 или 1008 " -"МГц" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "Out of memory" +msgstr "Не хватает памяти" -#: 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 "Функция требует блокировки" +#: ports/espressif/common-hal/espidf/__init__.c py/moderrno.c +msgid "Invalid argument" +msgstr "Недопустимый аргумент" -#: ports/cxd56/common-hal/gnss/GNSS.c -msgid "GNSS init" -msgstr "Инициализация GNSS" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "Invalid size" +msgstr "Неверный размер" #: ports/espressif/common-hal/espidf/__init__.c -msgid "Generic Failure" -msgstr "Общий сбой" +msgid "Requested resource not found" +msgstr "Запрошенный ресурс не найден" +#: ports/espressif/common-hal/espidf/__init__.c +#: ports/espressif/common-hal/jpegio/JpegDecoder.c +#: ports/raspberrypi/common-hal/usb_host_bulk/InStream.c +#: shared-bindings/busdisplay/BusDisplay.c #: shared-bindings/framebufferio/FramebufferDisplay.c -#: shared-module/busdisplay/BusDisplay.c -#: shared-module/framebufferio/FramebufferDisplay.c -msgid "Group already used" -msgstr "Группа уже используется" +#: shared-bindings/picogame/Canvas.c shared-bindings/picogame/__init__.c +#: shared-module/jpegio/JpegDecoder.c shared-module/picogame/Display.c +msgid "Operation or feature not supported" +msgstr "Операция или функция, не поддерживаемые" -#: supervisor/shared/safe_mode.c -msgid "Hard fault: memory access or instruction error." -msgstr "Жесткая ошибка: доступ к памяти или ошибка инструкции." +#: ports/espressif/common-hal/espidf/__init__.c +#: ports/espressif/common-hal/qspibus/QSPIBus.c +#: shared-module/_airlift/__init__.c +msgid "Operation timed out" +msgstr "Истекло время ожидания операции" -#: ports/mimxrt10xx/common-hal/busio/SPI.c -#: ports/mimxrt10xx/common-hal/busio/UART.c 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 "Hardware in use, try alternative pins" -msgstr "Оборудование используется, попробуйте использовать другие пины" +#: ports/espressif/common-hal/espidf/__init__.c +#: shared-module/_airlift/__init__.c +msgid "Received response was invalid" +msgstr "Полученный ответ недействителен" -#: supervisor/shared/safe_mode.c -msgid "Heap allocation when VM not running." -msgstr "Выделение кучи, когда виртуальная машина не запущена." +#: ports/espressif/common-hal/espidf/__init__.c +msgid "CRC or checksum was invalid" +msgstr "CRC или контрольная сумма неправильная" -#: extmod/vfs_posix_file.c py/objstringio.c -msgid "I/O operation on closed file" -msgstr "Операция ввода-вывода на закрытом файле" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "Version was invalid" +msgstr "Версия была недействительной" -#: ports/stm/common-hal/busio/I2C.c -msgid "I2C init error" -msgstr "Ошибка инициализации I2C" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "MAC address was invalid" +msgstr "MAC адрес был недействительным" -#: ports/raspberrypi/common-hal/busio/I2C.c +#: ports/espressif/common-hal/espidf/__init__.c +#, c-format +msgid "%s error 0x%x" +msgstr "%s ошибка 0x%x" + +#: ports/espressif/common-hal/espulp/ULP.c +msgid "Program too long" +msgstr "Слишком длинная программа" + +#: ports/espressif/common-hal/espulp/ULP.c +#: ports/espressif/common-hal/mipidsi/Bus.c +#: ports/espressif/common-hal/qspibus/QSPIBus.c +#: ports/mimxrt10xx/common-hal/audiobusio/__init__.c +#: ports/mimxrt10xx/common-hal/usb_host/Port.c +#: ports/raspberrypi/common-hal/picodvi/AudioOut.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#: ports/raspberrypi/common-hal/usb_host/Port.c +#: shared-bindings/digitalio/DigitalInOut.c shared-bindings/emmcio/EMMC.c +#: shared-bindings/i2cioexpander/IOPin.c shared-bindings/microcontroller/Pin.c +#: shared-module/_airlift/__init__.c +#: shared-module/epaperdisplay/EPaperDisplay.c +#: shared-module/max3421e/Max3421E.c shared-module/usb/core/Device.c +#: shared-module/usb_host_audio/USBIn.c +msgid "%q in use" +msgstr "%q используется" + +#: ports/espressif/common-hal/espulp/ULPAlarm.c +msgid "Only one %q can be set." +msgstr "Можно установить только один %q." + +#: ports/espressif/common-hal/i2ctarget/I2CTarget.c #: ports/raspberrypi/common-hal/i2ctarget/I2CTarget.c -msgid "I2C peripheral in use" -msgstr "Периферийное устройство I2C уже используется" +msgid "Only one address is allowed" +msgstr "Разрешен только один адрес" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "In-buffer elements must be <= 4 bytes long" -msgstr "Элементы буфера должны быть длиной <= 4 байта" +#: ports/espressif/common-hal/max3421e/Max3421E.c +#: ports/raspberrypi/common-hal/wifi/__init__.c +#, c-format +msgid "Unknown error code %d" +msgstr "Неизвестный код ошибки %d" -#: shared-bindings/_pew/PewPew.c -msgid "Incorrect buffer size" -msgstr "Неправильный размер буфера" +#: ports/espressif/common-hal/mdns/Server.c +#: ports/raspberrypi/common-hal/mdns/Server.c +msgid "mDNS only works with built-in WiFi" +msgstr "mDNS работает только со встроенным WiFi" + +#: ports/espressif/common-hal/mdns/Server.c +#: ports/raspberrypi/common-hal/mdns/Server.c +msgid "mDNS already initialized" +msgstr "mDNS уже инициализирован" + +#: ports/espressif/common-hal/mdns/Server.c +#: ports/raspberrypi/common-hal/mdns/Server.c +msgid "Unable to start mDNS query" +msgstr "Не удается запустить запрос mDNS" + +#: ports/espressif/common-hal/memorymap/AddressRange.c +#: ports/nordic/common-hal/memorymap/AddressRange.c +#: ports/raspberrypi/common-hal/memorymap/AddressRange.c +msgid "Address range not allowed" +msgstr "Диапазон адресов не разрешен" + +#: ports/espressif/common-hal/mipicsi/Camera.c +#: shared-bindings/displayio/TileGrid.c shared-bindings/terminalio/Terminal.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-bindings/vectorio/VectorShape.c +msgid "unsupported %q type" +msgstr "Неподдерживаемый тип %Q" + +#: ports/espressif/common-hal/mipicsi/Camera.c +msgid "output_format must be RGB565 or RGB888" +msgstr "" + +#: ports/espressif/common-hal/mipicsi/Camera.c +msgid "ISP conversion not supported on this chip" +msgstr "" + +#: ports/espressif/common-hal/mipidsi/Bus.c +msgid "%q is above %u" +msgstr "" + +#: ports/espressif/common-hal/mipidsi/Bus.c +msgid "%q is not reachable by the PHY" +msgstr "" + +#: ports/espressif/common-hal/nvm/ByteArray.c +msgid "NVS Error" +msgstr "Ошибка NVS" + +#: ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c +#: ports/espressif/common-hal/sdioio/SDCard.c +#, c-format +msgid "Number of data_pins must be %d or %d, not %d" +msgstr "Количество выводов_данных должно быть %d или %d, а не %d" + +#: ports/espressif/common-hal/pulseio/PulseIn.c +msgid "pop from an empty PulseIn" +msgstr "вытолкнуть из пустого импульсного входа" + +#: ports/espressif/common-hal/qspibus/QSPIBus.c +#: ports/raspberrypi/common-hal/usb_host_bulk/InStream.c +#: shared-module/usb/core/Device.c +msgid "Could not allocate DMA capable buffer" +msgstr "" + +#: ports/espressif/common-hal/qspibus/QSPIBus.c shared-bindings/pwmio/PWMOut.c +#: supervisor/shared/settings.c +msgid "Internal error" +msgstr "Внутренняя ошибка" + +#: ports/espressif/common-hal/rclcpy/Node.c +msgid "ROS node failed to initialize" +msgstr "" + +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "ROS topic failed to initialize" +msgstr "" + +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "Could not publish to ROS topic" +msgstr "" + +#: ports/espressif/common-hal/rclcpy/__init__.c +#, c-format +msgid "Critical ROS failure during soft reboot, reset required: %d" +msgstr "" + +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS memory allocator failure" +msgstr "" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "Init program size invalid" -msgstr "Неверный размер программы инициализации" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS internal setup failure" +msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Initial set pin direction conflicts with initial out pin direction" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "Invalid ROS domain ID" msgstr "" -"Исходное установленное направление штифта конфликтует с исходным " -"направлением вывода" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Initial set pin state conflicts with initial out pin state" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS failed to initialize. Is agent connected?" msgstr "" -"Исходное установленное состояние контакта конфликтует с исходным состоянием " -"выхода" -#: shared-bindings/bitops/__init__.c +#: ports/espressif/common-hal/sdioio/SDCard.c +#: ports/raspberrypi/common-hal/sdioio/SDCard.c +#: ports/stm/common-hal/sdioio/SDCard.c #, c-format -msgid "Input buffer length (%d) must be a multiple of the strand count (%d)" -msgstr "Длина входного буфера (%d) должна быть кратна количеству цепочек (%d)" - -#: ports/atmel-samd/common-hal/pulseio/PulseIn.c -msgid "Input taking too long" -msgstr "Ввод занимает слишком много времени" +msgid "SDIO Init Error 0x%02x" +msgstr "" -#: py/moderrno.c -msgid "Input/output error" -msgstr "Ошибка ввода/вывода" +#: ports/espressif/common-hal/socketpool/Socket.c +#: ports/zephyr-cp/common-hal/socketpool/Socket.c +msgid "Unsupported socket type" +msgstr "Неподдерживаемый тип сокета" -#: ports/espressif/common-hal/_bleio/__init__.c -#: ports/nordic/common-hal/_bleio/__init__.c -msgid "Insufficient authentication" -msgstr "Неполная аутентификация" +#: ports/espressif/common-hal/socketpool/Socket.c +#: ports/raspberrypi/common-hal/socketpool/Socket.c +msgid "Out of sockets" +msgstr "Вне розеток" -#: ports/espressif/common-hal/_bleio/__init__.c -#: ports/nordic/common-hal/_bleio/__init__.c -msgid "Insufficient encryption" -msgstr "Недостаточное шифрование" +#: ports/espressif/common-hal/socketpool/SocketPool.c +msgid "SocketPool can only be used with %q.%q or any %q.%q" +msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "Insufficient memory pool for the image" -msgstr "Недостаточный объем памяти для изображения" +#: ports/espressif/common-hal/watchdog/WatchDogTimer.c +msgid "%q must be <= %u" +msgstr "%q должно быть <= %u" -#: shared-module/jpegio/JpegDecoder.c -msgid "Insufficient stream input buffer" -msgstr "Недостаточный буфер ввода потока" +#: ports/espressif/common-hal/wifi/Monitor.c +msgid "monitor init failed" +msgstr "Сбой инициализации монитора" #: ports/espressif/common-hal/wifi/Radio.c #: ports/zephyr-cp/common-hal/wifi/Radio.c msgid "Interface must be started" msgstr "Интерфейс должен быть запущен" -#: ports/atmel-samd/audio_dma.c ports/raspberrypi/audio_dma.c -msgid "Internal audio buffer too small" -msgstr "Внутренний звуковой буфер слишком мал" +#: ports/espressif/common-hal/wifi/Radio.c +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "Invalid multicast MAC address" +msgstr "Неверный MAC-адрес многоадресной рассылки" -#: ports/stm/common-hal/busio/UART.c -msgid "Internal define error" -msgstr "Внутренняя ошибка определения" +#: ports/espressif/common-hal/wifi/Radio.c +#: ports/raspberrypi/common-hal/wifi/Radio.c +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "Already scanning for wifi networks" +msgstr "Поиск сетей wifi уже происходит" -#: shared-bindings/pwmio/PWMOut.c shared-module/os/getenv.c -msgid "Internal error" -msgstr "Внутренняя ошибка" +#: ports/espressif/common-hal/wifi/Radio.c +#: ports/espressif/common-hal/wifi/__init__.c +#: ports/raspberrypi/common-hal/wifi/Radio.c +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "WiFi is not enabled" +msgstr "" -#: shared-module/rgbmatrix/RGBMatrix.c -#, c-format -msgid "Internal error #%d" -msgstr "Внутренняя ошибка #%d" +#: ports/espressif/common-hal/wifi/ScannedNetworks.c +msgid "Failed to allocate wifi scan memory" +msgstr "Не удалось выделить память для сканирования wifi" -#: ports/atmel-samd/common-hal/alarm/pin/PinAlarm.c -#: ports/atmel-samd/common-hal/countio/Counter.c -#: ports/atmel-samd/common-hal/frequencyio/FrequencyIn.c -#: ports/atmel-samd/common-hal/max3421e/Max3421E.c -#: ports/atmel-samd/common-hal/ps2io/Ps2.c -#: ports/atmel-samd/common-hal/pulseio/PulseIn.c -#: ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.c -#: ports/cxd56/common-hal/pulseio/PulseIn.c -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c -#: shared-bindings/pwmio/PWMOut.c -msgid "Internal resource(s) in use" -msgstr "Используемые внутренние ресурсы" +#: ports/espressif/common-hal/wifi/__init__.c +msgid "Failed to allocate Wifi memory" +msgstr "Не удалось выделить память Wifi" -#: supervisor/shared/safe_mode.c -msgid "Internal watchdog timer expired." -msgstr "Внутренний сторожевой таймер истек." +#: ports/espressif/common-hal/wifi/__init__.c +#: ports/raspberrypi/common-hal/wifi/__init__.c +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "Only IPv4 addresses supported" +msgstr "Поддерживаются только адреса IPv4" -#: supervisor/shared/safe_mode.c -msgid "Interrupt error." -msgstr "Прерванная ошибка." +#: ports/mimxrt10xx/common-hal/busio/SPI.c +#: ports/raspberrypi/bindings/wiznet/PIO_SPI.c shared-bindings/async_spi/SPI.c +#: shared-bindings/busio/SPI.c +msgid "Must provide MISO or MOSI pin" +msgstr "Пин MISO или MOSI должен быть предоставлен" -#: shared-module/jpegio/JpegDecoder.c -msgid "Interrupted by output function" -msgstr "Прерывается функцией выхода" +#: ports/mimxrt10xx/common-hal/busio/SPI.c +#: ports/mimxrt10xx/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/canio/CAN.c 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 +#: shared-bindings/emmcio/EMMC.c +msgid "Hardware in use, try alternative pins" +msgstr "Оборудование используется, попробуйте использовать другие пины" -#: ports/espressif/common-hal/_bleio/Service.c -#: ports/espressif/common-hal/espulp/ULP.c -#: ports/espressif/common-hal/microcontroller/Processor.c -#: ports/mimxrt10xx/common-hal/audiobusio/__init__.c -#: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c -#: ports/raspberrypi/bindings/picodvi/Framebuffer.c -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c py/argcheck.c -#: shared-bindings/digitalio/DigitalInOut.c -#: shared-bindings/epaperdisplay/EPaperDisplay.c shared-bindings/pwmio/PWMOut.c -#: shared-module/aurora_epaper/aurora_framebuffer.c -msgid "Invalid %q" -msgstr "Недопустимый %q" +#: ports/mimxrt10xx/common-hal/canio/CAN.c +msgid "Unable to send CAN Message: all Tx message buffers are busy" +msgstr "" -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c -#: shared-module/aurora_epaper/aurora_framebuffer.c -msgid "Invalid %q and %q" -msgstr "Недопустимые %q и %q" +#: ports/mimxrt10xx/common-hal/microcontroller/Processor.c +msgid "" +"Frequency must be 24, 150, 396, 450, 528, 600, 720, 816, 912, 960 or 1008 Mhz" +msgstr "" +"Частота должна быть 24, 150, 396, 450, 528, 600, 720, 816, 912, 960 или 1008 " +"МГц" -#: ports/atmel-samd/common-hal/microcontroller/Pin.c -#: ports/espressif/common-hal/dotclockframebuffer/DotClockFramebuffer.c -#: ports/mimxrt10xx/common-hal/microcontroller/Pin.c -#: shared-bindings/microcontroller/Pin.c -msgid "Invalid %q pin" -msgstr "Недопустимый пин %q" +#: ports/nordic/boards/aramcon2_badge/mpconfigboard.h +msgid "You pressed the left button at start up." +msgstr "Вы нажали левую кнопку при запуске." -#: ports/stm/common-hal/analogio/AnalogIn.c -msgid "Invalid ADC Unit value" -msgstr "Недопустимое значение единицы ADC" +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "timeout must be < 655.35 secs" +msgstr "таймаут должен быть < 655.35 сек" + +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "non-zero timeout must be > 0.01" +msgstr "Ненулевое время ожидания должно быть > 0,01" + +#: ports/nordic/common-hal/_bleio/UUID.c +msgid "Unexpected nrfx uuid type" +msgstr "Неожиданный тип nrfx uuid" -#: ports/espressif/common-hal/_bleio/__init__.c #: ports/nordic/common-hal/_bleio/__init__.c -msgid "Invalid BLE parameter" -msgstr "Недопустимый параметр BLE" +msgid "Nordic system firmware out of memory" +msgstr "Скандинавская система прошивки из памяти" -#: shared-bindings/wifi/Radio.c -msgid "Invalid BSSID" -msgstr "Неверный BSSID" +#: ports/nordic/common-hal/_bleio/__init__.c +#, c-format +msgid "Unknown system firmware error: %04x" +msgstr "Неизвестная системная ошибка прошивки: %04x" -#: shared-bindings/wifi/Radio.c -msgid "Invalid MAC address" -msgstr "Неверный MAC-адрес" +#: ports/nordic/common-hal/alarm/pin/PinAlarm.c +msgid "Cannot wake on pin edge, only level" +msgstr "" +"Невозможно проснуться по изменению логического уровня, только по уровню" -#: ports/espressif/common-hal/espidf/__init__.c py/moderrno.c -msgid "Invalid argument" -msgstr "Недопустимый аргумент" +#: ports/nordic/common-hal/audiobusio/I2SOut.c +msgid "Device in use" +msgstr "Устройство используется" -#: shared-module/displayio/Bitmap.c -msgid "Invalid bits per value" -msgstr "Недопустимое бит-на-значение" +#: ports/nordic/common-hal/audiobusio/PDMIn.c +#: ports/stm/common-hal/audiobusio/PDMIn.c +msgid "only sample_rate=16000 is supported" +msgstr "только образец_рейт=16000 поддерживается" -#: shared-module/os/getenv.c +#: ports/nordic/common-hal/audiobusio/PDMIn.c +#: ports/stm/common-hal/audiobusio/PDMIn.c +msgid "only bit_depth=16 is supported" +msgstr "поддерживается только бит_глубина=16" + +#: ports/nordic/common-hal/busio/UART.c #, c-format -msgid "Invalid byte %.*s" -msgstr "Неверный байт %.*s" +msgid "error = 0x%08lX" +msgstr "ошибка = 0x%08lX" -#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c +#: ports/nordic/common-hal/busio/UART.c +msgid "Odd parity is not supported" +msgstr "Нечетная четность не поддерживается" + +#: ports/nordic/common-hal/countio/Counter.c +#: ports/nordic/common-hal/pulseio/PulseIn.c +#: ports/nordic/common-hal/rotaryio/IncrementalEncoder.c +msgid "All channels in use" +msgstr "Все каналы уже используются" + +#: ports/nordic/common-hal/microcontroller/Processor.c +msgid "Cannot get temperature" +msgstr "Невозможно получить температуру" + +#: ports/nordic/common-hal/watchdog/WatchDogTimer.c +msgid "timeout duration exceeded the maximum supported value" +msgstr "" +"Продолжительность таймаута превысила максимальное поддерживаемое значение" + +#: ports/nordic/common-hal/watchdog/WatchDogTimer.c +msgid "%q cannot be changed once mode is set to %q" +msgstr "%q не может быть изменен после установки режима на %q" + +#: ports/nordic/common-hal/watchdog/WatchDogTimer.c +msgid "WatchDogTimer cannot be deinitialized once mode is set to RESET" +msgstr "" +"Сторожевой таймер не может быть деинициализирован, если установлен режим " +"RESET" + +#: ports/nordic/sd_mutex.c #, c-format -msgid "Invalid data_pins[%d]" -msgstr "Неверный data_pins[%d]" +msgid "Failed to acquire mutex, err 0x%04x" +msgstr "Не удалось получить mutex, ошибка 0x%04x" -#: shared-module/msgpack/__init__.c -msgid "Invalid format" -msgstr "Недопустимый формат" +#: ports/nordic/sd_mutex.c +#, c-format +msgid "Failed to release mutex, err 0x%04x" +msgstr "Не удалось освободить mutex, ошибка 0x%04x" -#: shared-module/audiocore/WaveFile.c -msgid "Invalid format chunk size" -msgstr "Неверный размер блока формата" +#: ports/raspberrypi/audio_dma.c +msgid "Audio conversion not implemented" +msgstr "Преобразование звука не реализовано" -#: shared-bindings/wifi/Radio.c -msgid "Invalid hex password" -msgstr "Неверный шестнадцатеричный пароль" +#: ports/raspberrypi/bindings/cyw43/__init__.c py/argcheck.c py/objexcept.c +#: shared-bindings/bitmapfilter/__init__.c shared-bindings/canio/CAN.c +#: shared-bindings/digitalio/Pull.c shared-bindings/picogame/Sprite.c +#: shared-bindings/supervisor/__init__.c shared-module/audiofilters/__init__.c +#: shared-module/displayio/legacy/__init__.c +#: shared-module/synthio/Synthesizer.c shared-module/videocore/VideoBuffer.c +msgid "%q must be of type %q or %q, not %q" +msgstr "%q должно быть типа%q или%q, а не%q" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "Invalid multicast MAC address" -msgstr "Неверный MAC-адрес многоадресной рассылки" +#: ports/raspberrypi/bindings/picodvi/AudioOut.c +#: shared-bindings/audiobusio/I2SOut.c shared-bindings/audioio/AudioOut.c +#: shared-bindings/audiopwmio/PWMAudioOut.c shared-bindings/mcp4822/MCP4822.c +#: shared-bindings/usb_audio/USBMicrophone.c +msgid "Not playing" +msgstr "Не воспроизводится (Not playing)" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Invalid size" -msgstr "Неверный размер" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Program size invalid" +msgstr "Недопустимый размер программы" -#: shared-module/ssl/SSLSocket.c -msgid "Invalid socket for TLS" -msgstr "Неверный сокет для TLS" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Init program size invalid" +msgstr "Неверный размер программы инициализации" -#: ports/espressif/common-hal/espidf/__init__.c -#: ports/nordic/common-hal/_bleio/__init__.c -msgid "Invalid state" -msgstr "Неверное состояние" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Buffer elements must be 4 bytes long or less" +msgstr "Элементы буфера должны иметь длину не более 4 байт" -#: shared-module/os/getenv.c -msgid "Invalid unicode escape" -msgstr "Недопустимое экранирование Юникода" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Mismatched data size" +msgstr "Размер данных различается" -#: shared-bindings/aesio/aes.c -msgid "Key must be 16, 24, or 32 bytes long" -msgstr "Ключ должен быть длинной 16, 24 или 32 байта" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Out-buffer elements must be <= 4 bytes long" +msgstr "Элементы вне буфера должны иметь длину <= 4 байта" -#: shared-module/os/getenv.c -msgid "Key not found" -msgstr "Ключ не найден" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "In-buffer elements must be <= 4 bytes long" +msgstr "Элементы буфера должны быть длиной <= 4 байта" -#: shared-module/is31fl3741/FrameBuffer.c -msgid "LED mappings must match display size" -msgstr "Светодиодные сопоставления должны соответствовать размеру дисплея" +#: ports/raspberrypi/bindings/wiznet/PIO_SPI.c shared-bindings/async_spi/SPI.c +#: 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 "Функция требует блокировки" -#: py/compile.c -msgid "LHS of keyword arg must be an id" -msgstr "LHS ключевого слова arg должен быть идентификатором(id)" +#: ports/raspberrypi/bindings/wiznet/PIO_SPI.c shared-bindings/async_spi/SPI.c +#: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c +msgid "buffer slices must be of equal length" +msgstr "Буферные фрагменты должны быть одинаковой длины" -#: shared-module/displayio/Group.c -msgid "Layer already in a group" -msgstr "Слой уже в группе (Group)" +#: ports/raspberrypi/common-hal/alarm/touch/TouchAlarm.c +#: ports/stm/common-hal/alarm/touch/TouchAlarm.c +msgid "Touch alarms not available" +msgstr "Сенсорные сигналы недоступны" -#: shared-module/displayio/Group.c -msgid "Layer must be a Group or TileGrid subclass" -msgstr "Слой должен быть группой (Group) или субклассом TileGrid" +#: ports/raspberrypi/common-hal/async_spi/SPI.c shared-bindings/emmcio/EMMC.c +msgid "SPI peripheral in use" +msgstr "Используемое периферийное устройство SPI" -#: shared-bindings/audiocore/RawSample.c -msgid "Length of %q must be an even multiple of channel_count * type_size" -msgstr "Длина %q должна быть четной, кратной количеству каналов * размер_типа" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audioi2sin/I2SIn.c +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Cannot use GPIO0..15 together with GPIO32..47" +msgstr "Невозможно использовать GPIO0..15 вместе с GPIO32..47" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "MAC address was invalid" -msgstr "MAC адрес был недействительным" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audioi2sin/I2SIn.c +msgid "Bit clock and word select must be sequential GPIO pins" +msgstr "Несколько часов и слов должны быть последовательными GPIO пинами" -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/espressif/common-hal/_bleio/Descriptor.c -msgid "MITM security not supported" -msgstr "Защита от MITM не поддерживается" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/mcp4822/MCP4822.c +msgid "Too many channels in sample." +msgstr "Слишком много каналов в выборке." -#: shared-bindings/is31fl3741/IS31FL3741.c -msgid "Mapping must be a tuple" -msgstr "Сопоставление должно быть кортежом" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +#: ports/raspberrypi/common-hal/mcp4822/MCP4822.c +msgid "Audio source error" +msgstr "" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Mismatched data size" -msgstr "Размер данных различается" +#: ports/raspberrypi/common-hal/audioi2sin/I2SIn.c +msgid "%q must be 16, 24, or 32" +msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Mismatched swap flag" -msgstr "Несоответствующий флаг подкачки" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Pins must share PWM slice" +msgstr "Пины должны иметь общий срез PWM" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_in_pin. %q[%u] reads pin(s)" -msgstr "Отсутствует first_in_pin. %q[%u] читает выводы" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "No DMA pacing timer found" +msgstr "Таймер стимуляции DMA не найден" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_in_pin. %q[%u] shifts in from pin(s)" -msgstr "Отсутствует first_in_pin. %q[%u] смещается от контакта (контактов)" +#: ports/raspberrypi/common-hal/busio/I2C.c +#: ports/raspberrypi/common-hal/i2ctarget/I2CTarget.c +msgid "I2C peripheral in use" +msgstr "Периферийное устройство I2C уже используется" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_in_pin. %q[%u] waits based on pin" -msgstr "Отсутствует first_in_pin. Инструкция %d ожидает на основе пина" +#: ports/raspberrypi/common-hal/busio/UART.c +msgid "UART peripheral in use" +msgstr "Используемое периферийное устройство UART" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_out_pin. %q[%u] shifts out to pin(s)" -msgstr "Отсутствует first_out_pin. %q[%u] переключается на контакты" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "Pin must be on PWM Channel B" +msgstr "Пин должен быть на канале ШИМ B" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_out_pin. %q[%u] writes pin(s)" -msgstr "Отсутствует first_out_pin. %q[%u] записывает выводы" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "RISE_AND_FALL not available on this chip" +msgstr "RISE_AND_FALL недоступен на этом чипе" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_set_pin. %q[%u] sets pin(s)" -msgstr "Отсутствует first_set_pin. %q[%u] устанавливает контакты" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice already in use" +msgstr "PWM уже используется" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing jmp_pin. %q[%u] jumps on pin" -msgstr "Не хватает jmp_pin.%q [%u] прыгает на пин" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "PWM slice channel A already in use" +msgstr "PWM канал среза A уже используется" -#: shared-module/storage/__init__.c -msgid "Mount point directory missing" -msgstr "Отсутствует каталог точки монтирования" +#: ports/raspberrypi/common-hal/floppyio/__init__.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#: ports/raspberrypi/common-hal/usb_host/Port.c +msgid "All state machines in use" +msgstr "Все машины состояний уже используются" -#: ports/zephyr-cp/bindings/zephyr_serial/UART.c shared-bindings/busio/UART.c -#: shared-bindings/displayio/Group.c -msgid "Must be a %q subclass." -msgstr "Должен быть субклассом %q." +#: ports/raspberrypi/common-hal/floppyio/__init__.c +msgid "timeout waiting for flux" +msgstr "таймаут ожидания потока" -#: ports/espressif/common-hal/dotclockframebuffer/DotClockFramebuffer.c -msgid "Must provide 5/6/5 RGB pins" -msgstr "Должен иметь 5/6/5 контактов RGB" +#: ports/raspberrypi/common-hal/floppyio/__init__.c +#: shared-module/floppyio/__init__.c +msgid "timeout waiting for index pulse" +msgstr "таймаут ожидания индексного импульса" -#: ports/mimxrt10xx/common-hal/busio/SPI.c shared-bindings/busio/SPI.c -msgid "Must provide MISO or MOSI pin" -msgstr "Пин MISO или MOSI должен быть предоставлен" +#: ports/raspberrypi/common-hal/imagecapture/ParallelImageCapture.c +msgid "Pins must be sequential" +msgstr "Пины должны быть последовательными" -#: shared-bindings/rgbmatrix/RGBMatrix.c -#, c-format -msgid "Must use a multiple of 6 rgb pins, not %d" -msgstr "Количество используемых rgb-пинов должно быть кратно 6, а не %d" +#: ports/raspberrypi/common-hal/mcp4822/MCP4822.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c +#: shared-module/aurora_epaper/aurora_framebuffer.c +msgid "Invalid %q and %q" +msgstr "Недопустимые %q и %q" -#: supervisor/shared/safe_mode.c -msgid "NLR jump failed. Likely memory corruption." -msgstr "Прыжок NLR не удался. Вероятно повреждение памяти." +#: ports/raspberrypi/common-hal/mdns/Server.c +msgid "Out of MDNS service slots" +msgstr "Отсутствуют сервисные слоты MDNS" -#: ports/espressif/common-hal/nvm/ByteArray.c -msgid "NVS Error" -msgstr "Ошибка NVS" +#: ports/raspberrypi/common-hal/memorymap/AddressRange.c +msgid "Unable to access unaligned IO register" +msgstr "Невозможно получить доступ к невыровненному регистру ввода-вывода" -#: shared-bindings/socketpool/SocketPool.c -msgid "Name or service not known" -msgstr "Имя или услуга не известны" +#: ports/raspberrypi/common-hal/memorymap/AddressRange.c +msgid "Unable to write to read-only memory" +msgstr "Невозможно записать в постоянную память" -#: shared-bindings/displayio/TileGrid.c -msgid "New bitmap must be same size as old bitmap" -msgstr "" -"Новое растровое изображение должно быть того же размера, что и старое " -"растровое изображение" +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c +msgid "All timers for this pin are in use" +msgstr "Все таймеры для этого пина уже используются" -#: ports/espressif/common-hal/_bleio/__init__.c -msgid "Nimble out of memory" -msgstr "Изображение памяти" +#: ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c +msgid "Pins must be sequential GPIO pins" +msgstr "Пины должны быть последовательными выводами GPIO" -#: ports/atmel-samd/common-hal/busio/UART.c -#: ports/espressif/common-hal/busio/SPI.c -#: ports/espressif/common-hal/busio/UART.c -#: ports/mimxrt10xx/common-hal/busio/SPI.c -#: ports/mimxrt10xx/common-hal/busio/UART.c -#: ports/nordic/common-hal/busio/UART.c -#: ports/raspberrypi/common-hal/busio/UART.c ports/stm/common-hal/busio/SPI.c -#: ports/stm/common-hal/busio/UART.c shared-bindings/fourwire/FourWire.c -#: shared-bindings/i2cdisplaybus/I2CDisplayBus.c -#: shared-bindings/paralleldisplaybus/ParallelBus.c -#: shared-module/bitbangio/SPI.c -msgid "No %q pin" -msgstr "Нет пина %q" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Pin count too large" +msgstr "Слишком большое количество пинов" -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Characteristic.c -msgid "No CCCD for this Characteristic" -msgstr "Для этой характеристики нет CCCD" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing jmp_pin. %q[%u] jumps on pin" +msgstr "Не хватает jmp_pin.%q [%u] прыгает на пин" -#: ports/atmel-samd/common-hal/analogio/AnalogOut.c -#: ports/stm/common-hal/analogio/AnalogOut.c -msgid "No DAC on chip" -msgstr "DAC отсутствует на чипе" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "%q[%u] uses extra pin" +msgstr "%q[%u] использует дополнительный контакт" -#: 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/rp2pio/StateMachine.c +msgid "Missing first_in_pin. %q[%u] waits based on pin" +msgstr "Отсутствует first_in_pin. Инструкция %d ожидает на основе пина" -#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c -msgid "No DMA pacing timer found" -msgstr "Таймер стимуляции DMA не найден" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "%q[%u] waits on input outside of count" +msgstr "%q [%u] ожидает ввода за пределами графа" -#: shared-module/adafruit_bus_device/i2c_device/I2CDevice.c -#, c-format -msgid "No I2C device at address: 0x%x" -msgstr "Нет устройства I2C по адресу: %x" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_in_pin. %q[%u] shifts in from pin(s)" +msgstr "Отсутствует first_in_pin. %q[%u] смещается от контакта (контактов)" -#: supervisor/shared/web_workflow/web_workflow.c -msgid "No IP" -msgstr "Нет IP" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "%q[%u] shifts in more bits than pin count" +msgstr "%q [%u] смещается в большем количестве чем количество пинов" -#: ports/atmel-samd/common-hal/microcontroller/__init__.c -#: ports/cxd56/common-hal/microcontroller/__init__.c -#: ports/mimxrt10xx/common-hal/microcontroller/__init__.c -msgid "No bootloader present" -msgstr "Отсутствует загрузчик" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_out_pin. %q[%u] shifts out to pin(s)" +msgstr "Отсутствует first_out_pin. %q[%u] переключается на контакты" -#: shared-module/usb/core/Device.c -msgid "No configuration set" -msgstr "Нет конфигураций" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "%q[%u] shifts out more bits than pin count" +msgstr "%q[%u] смещает больше битов чем количество выводов" -#: shared-bindings/_bleio/PacketBuffer.c -msgid "No connection: length cannot be determined" -msgstr "Нет соединения: длина не может быть определена" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_set_pin. %q[%u] sets pin(s)" +msgstr "Отсутствует first_set_pin. %q[%u] устанавливает контакты" -#: shared-bindings/board/__init__.c -msgid "No default %q bus" -msgstr "Нет шины %q по умолчанию" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_out_pin. %q[%u] writes pin(s)" +msgstr "Отсутствует first_out_pin. %q[%u] записывает выводы" -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c -#: ports/atmel-samd/common-hal/touchio/TouchIn.c -msgid "No free GCLKs" -msgstr "Свободные GCLK отсутствуют" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_in_pin. %q[%u] reads pin(s)" +msgstr "Отсутствует first_in_pin. %q[%u] читает выводы" -#: shared-bindings/os/__init__.c -msgid "No hardware random available" -msgstr "Отсутствует аппаратный генератор случайных чисел" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Program does IN without loading ISR" +msgstr "Программа выполняет IN без загрузки ISR" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "No in in program" -msgstr "Нет в программе" +msgid "Program does OUT without loading OSR" +msgstr "Программа выполняет ВЫХОД без загрузки OSR" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "No in or out in program" -msgstr "В программе отсутствует ввод или вывод" +msgid "Initial set pin state conflicts with initial out pin state" +msgstr "" +"Исходное установленное состояние контакта конфликтует с исходным состоянием " +"выхода" -#: py/objint.c shared-bindings/time/__init__.c -msgid "No long integer support" -msgstr "Нет поддержки длинных целых чисел (long integer)" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin direction conflicts with initial out pin direction" +msgstr "" +"Исходное установленное направление штифта конфликтует с исходным " +"направлением вывода" -#: shared-bindings/wifi/Radio.c -msgid "No network with that ssid" -msgstr "Нет сети с этим ssid" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "pull masks conflict with direction masks" +msgstr "Маски вытягивания конфликтуют с масками направления" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "No out in program" msgstr "В программе отсутствует вывод" -#: ports/atmel-samd/common-hal/busio/I2C.c -#: ports/espressif/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nordic/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 "На SDA или SCL не обнаружено подтягивания; проверь свою проводку" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in in program" +msgstr "Нет в программе" -#: shared-module/touchio/TouchIn.c -msgid "No pulldown on pin; 1Mohm recommended" -msgstr "Отсутствует подтяжка к земле на пине; Рекомендуется 1 Мегаом" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in or out in program" +msgstr "В программе отсутствует ввод или вывод" -#: py/moderrno.c -msgid "No space left on device" -msgstr "На устройстве не осталось свободного места" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Mismatched swap flag" +msgstr "Несоответствующий флаг подкачки" -#: py/moderrno.c -msgid "No such device" -msgstr "Нет такого устройства" +#: ports/raspberrypi/common-hal/sdioio/SDCard.c +#, c-format +msgid "Number of data_pins must be %d, not %d" +msgstr "" -#: py/moderrno.c -msgid "No such file/directory" -msgstr "Файл/директория не существует" +#: ports/raspberrypi/common-hal/sdioio/SDCard.c +msgid "Data pins must be consecutive" +msgstr "" -#: shared-module/rgbmatrix/RGBMatrix.c -msgid "No timer available" -msgstr "Нет доступного таймера" +#: ports/raspberrypi/common-hal/socketpool/Socket.c +msgid "Only IPv4 sockets supported" +msgstr "Поддерживаются только сокеты IPv4" -#: shared-module/usb/core/Device.c -msgid "No usb host port initialized" -msgstr "Порт USB-хоста не инициализирован" +#: ports/raspberrypi/common-hal/socketpool/SocketPool.c +msgid "SocketPool can only be used with wifi.radio" +msgstr "SocketPool можно использовать только с wifi.radio" -#: ports/nordic/common-hal/_bleio/__init__.c -msgid "Nordic system firmware out of memory" -msgstr "Скандинавская система прошивки из памяти" +#: ports/raspberrypi/common-hal/usb_host/Port.c +msgid "All dma channels in use" +msgstr "Все используемые каналы dma" -#: shared-bindings/ipaddress/IPv4Address.c shared-bindings/ipaddress/__init__.c -msgid "Not a valid IP string" -msgstr "Недействительная строка IP" +#: ports/raspberrypi/common-hal/wifi/Monitor.c +msgid "wifi.Monitor not available" +msgstr "Wi-Fi. Монитор недоступен" -#: ports/espressif/common-hal/_bleio/__init__.c -#: ports/nordic/common-hal/_bleio/__init__.c -#: shared-bindings/_bleio/CharacteristicBuffer.c -msgid "Not connected" -msgstr "Не подключено" +#: ports/raspberrypi/common-hal/wifi/Radio.c +msgid "%q is read-only for this board" +msgstr "%q читается только для этой доски" -#: shared-bindings/audiobusio/I2SOut.c shared-bindings/audioio/AudioOut.c -#: shared-bindings/audiopwmio/PWMAudioOut.c -msgid "Not playing" -msgstr "Не воспроизводится (Not playing)" +#: ports/raspberrypi/common-hal/wifi/Radio.c +msgid "AP could not be started" +msgstr "AP не может быть запущен" -#: shared-module/jpegio/JpegDecoder.c -msgid "Not supported JPEG standard" -msgstr "Не поддерживается Стандарт JPEG" +#: ports/stm/common-hal/alarm/pin/PinAlarm.c +msgid "Only edge detection is available on this hardware" +msgstr "На этом аппаратном обеспечении доступно только обнаружение края" -#: ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/espressif/common-hal/sdioio/SDCard.c -#, c-format -msgid "Number of data_pins must be %d or %d, not %d" -msgstr "Количество выводов_данных должно быть %d или %d, а не %d" +#: ports/stm/common-hal/alarm/pin/PinAlarm.c +#: ports/stm/common-hal/pulseio/PulseIn.c +msgid "Pin interrupt already in use" +msgstr "Прерывание пина уже используется" -#: shared-bindings/util.c -msgid "" -"Object has been deinitialized and can no longer be used. Create a new object." +#: ports/stm/common-hal/alarm/pin/PinAlarm.c +msgid "Pin cannot wake from Deep Sleep" +msgstr "Пин не может вывести из глубокого сна" + +#: ports/stm/common-hal/alarm/pin/PinAlarm.c +msgid "Deep sleep pins must use a rising edge with pulldown" msgstr "" -"Объект был деинициализирован и больше не может быть использован. Создайте " -"новый объект." +"Выводы глубокого сна должны использовать сигнал по возрастанию с подтяжкой к " +"земле" -#: ports/nordic/common-hal/busio/UART.c -msgid "Odd parity is not supported" -msgstr "Нечетная четность не поддерживается" +#: ports/stm/common-hal/analogio/AnalogIn.c +msgid "Invalid ADC Unit value" +msgstr "Недопустимое значение единицы ADC" -#: supervisor/shared/bluetooth/bluetooth.c -msgid "Off" -msgstr "Выключено" +#: ports/stm/common-hal/analogio/AnalogOut.c +#: ports/stm/common-hal/audioio/AudioOut.c +msgid "DAC Device Init Error" +msgstr "Ошибка инициализации устройства DAC" -#: supervisor/shared/bluetooth/bluetooth.c -msgid "Ok" -msgstr "Да" +#: ports/stm/common-hal/analogio/AnalogOut.c +#: ports/stm/common-hal/audioio/AudioOut.c +msgid "DAC Channel Init Error" +msgstr "Ошибка инициализации канала DAC" -#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c -#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c -#, c-format -msgid "Only 8 or 16 bit mono with %dx oversampling supported." -msgstr "Поддерживается только 8 или 16-битное моно с передискретизацией %dx." +#: ports/stm/common-hal/audiobusio/PDMIn.c +msgid "only mono is supported" +msgstr "Поддерживается только моно" -#: ports/espressif/common-hal/wifi/__init__.c -#: ports/raspberrypi/common-hal/wifi/__init__.c -msgid "Only IPv4 addresses supported" -msgstr "Поддерживаются только адреса IPv4" +#: ports/stm/common-hal/audiobusio/PDMIn.c +msgid "only oversample=64 is supported" +msgstr "поддерживается только выборка = 64" -#: ports/raspberrypi/common-hal/socketpool/Socket.c -msgid "Only IPv4 sockets supported" -msgstr "Поддерживаются только сокеты IPv4" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Another PWMAudioOut is already active" +msgstr "Другой аудиовыход PWM уже активен" -#: shared-module/displayio/OnDiskBitmap.c +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c #, c-format -msgid "" -"Only Windows format, uncompressed BMP supported: given header size is %d" -msgstr "" -"Поддерживается только формат Windows, несжатый BMP: заданный размер " -"заголовка - %d" +msgid "Buffer length %d too big. It must be less than %d" +msgstr "Размер буфера %d слишком большой. Он должен быть меньше чем %d" -#: shared-bindings/_bleio/Adapter.c -msgid "Only connectable advertisements can be directed" -msgstr "Только подключаемые объявления могут быть направлены" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Failed to buffer the sample" +msgstr "Не удалось выполнить буферизацию образца" -#: ports/stm/common-hal/alarm/pin/PinAlarm.c -msgid "Only edge detection is available on this hardware" -msgstr "На этом аппаратном обеспечении доступно только обнаружение края" +#: ports/stm/common-hal/busio/I2C.c +msgid "I2C init error" +msgstr "Ошибка инициализации I2C" -#: shared-bindings/ipaddress/__init__.c -msgid "Only int or string supported for ip" -msgstr "Для IP поддерживаются только int или строка" +#: ports/stm/common-hal/busio/SPI.c +msgid "SPI init error" +msgstr "Ошибка инициализации SPI" -#: ports/espressif/common-hal/alarm/touch/TouchAlarm.c -msgid "Only one %q can be set in deep sleep." -msgstr "Только один %q может быть переведен в режим глубокого сна." +#: ports/stm/common-hal/busio/SPI.c +msgid "SPI re-init" +msgstr "Повторная инициализация SPI" -#: ports/espressif/common-hal/espulp/ULPAlarm.c -msgid "Only one %q can be set." -msgstr "Можно установить только один %q." +#: ports/stm/common-hal/busio/UART.c +msgid "Internal define error" +msgstr "Внутренняя ошибка определения" -#: ports/espressif/common-hal/i2ctarget/I2CTarget.c -#: ports/raspberrypi/common-hal/i2ctarget/I2CTarget.c -msgid "Only one address is allowed" -msgstr "Разрешен только один адрес" +#: ports/stm/common-hal/busio/UART.c +msgid "Could not start interrupt, RX busy" +msgstr "Не удалось запустить прерывание, RX занят" -#: ports/atmel-samd/common-hal/alarm/time/TimeAlarm.c -#: ports/nordic/common-hal/alarm/time/TimeAlarm.c -#: ports/stm/common-hal/alarm/time/TimeAlarm.c -msgid "Only one alarm.time alarm can be set" -msgstr "Можно установить только один будильник" +#: ports/stm/common-hal/busio/UART.c +msgid "UART write" +msgstr "Запись UART" -#: ports/espressif/common-hal/alarm/time/TimeAlarm.c -#: ports/raspberrypi/common-hal/alarm/time/TimeAlarm.c -msgid "Only one alarm.time alarm can be set." -msgstr "Можно установить только один будильник alarm.time." +#: ports/stm/common-hal/busio/UART.c +msgid "UART de-init" +msgstr "Деинициализация UART" -#: shared-module/displayio/ColorConverter.c -msgid "Only one color can be transparent at a time" -msgstr "Только один цвет может быть прозрачным одновременно" +#: ports/stm/common-hal/busio/UART.c +msgid "UART re-init" +msgstr "Повторная инициализация UART" -#: py/moderrno.c -msgid "Operation not permitted" -msgstr "Операция не разрешена" +#: ports/stm/common-hal/microcontroller/Processor.c +msgid "Temperature read timed out" +msgstr "Истекло время ожидания считывания температуры" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Operation or feature not supported" -msgstr "Операция или функция, не поддерживаемые" +#: ports/stm/common-hal/microcontroller/Processor.c +msgid "Voltage read timed out" +msgstr "Истекло время ожидания считывания напряжения" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Operation timed out" -msgstr "Истекло время ожидания операции" +#: ports/stm/common-hal/os/__init__.c +msgid "RNG Init Error" +msgstr "Ошибка инициализации RNG" -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "Out of MDNS service slots" -msgstr "Отсутствуют сервисные слоты MDNS" +#: ports/stm/common-hal/os/__init__.c +msgid "Random number generation error" +msgstr "Ошибка генерации случайных чисел" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Out of memory" -msgstr "Не хватает памяти" +#: ports/stm/common-hal/os/__init__.c +msgid "RNG DeInit Error" +msgstr "Ошибка деинициализации генератора случайных чисел" -#: ports/espressif/common-hal/socketpool/Socket.c -#: ports/raspberrypi/common-hal/socketpool/Socket.c -#: ports/zephyr-cp/common-hal/socketpool/Socket.c -msgid "Out of sockets" -msgstr "Вне розеток" +#: ports/stm/common-hal/pwmio/PWMOut.c +msgid "timer re-init" +msgstr "Повторное инициализация таймера" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "Out-buffer elements must be <= 4 bytes long" -msgstr "Элементы вне буфера должны иметь длину <= 4 байта" +#: ports/stm/common-hal/pwmio/PWMOut.c +msgid "channel re-init" +msgstr "Реинициализация канала" #: ports/stm/common-hal/pwmio/PWMOut.c msgid "PWM restart" msgstr "PWM перезагрузка" -#: ports/raspberrypi/common-hal/countio/Counter.c -msgid "PWM slice already in use" -msgstr "PWM уже используется" - -#: ports/raspberrypi/common-hal/countio/Counter.c -msgid "PWM slice channel A already in use" -msgstr "PWM канал среза A уже используется" - -#: shared-bindings/spitarget/SPITarget.c -msgid "Packet buffers for an SPI transfer must have the same length." +#: ports/stm/common-hal/sdioio/SDCard.c +#, c-format +msgid "MMC/SDIO Clock Error %x" msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "Parameter error" -msgstr "Ошибка параметра" - -#: ports/espressif/common-hal/audiobusio/__init__.c -msgid "Peripheral in use" -msgstr "Периферийные устройства в использовании" +#: ports/stm/common-hal/sdioio/SDCard.c +#, c-format +msgid "SDIO GetCardInfo Error %d" +msgstr "Ошибка получения информации о карте SDIO %d" -#: py/moderrno.c -msgid "Permission denied" -msgstr "Отказано в разрешении" +#: ports/zephyr-cp/bindings/zephyr_display/Display.c +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/epaperdisplay/EPaperDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +#: shared-bindings/mipidsi/Display.c +msgid "Display rotation must be in 90 degree increments" +msgstr "Поворот дисплея должен осуществляться с шагом 90 градусов" -#: ports/stm/common-hal/alarm/pin/PinAlarm.c -msgid "Pin cannot wake from Deep Sleep" -msgstr "Пин не может вывести из глубокого сна" +#: ports/zephyr-cp/bindings/zephyr_display/Display.c +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/epaperdisplay/EPaperDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +msgid ".show(x) removed. Use .root_group = x" +msgstr ". Показать(x) удален. Используйте . корневую_группу = x" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Pin count too large" -msgstr "Слишком большое количество пинов" +#: ports/zephyr-cp/bindings/zephyr_display/Display.c +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +msgid "Brightness not adjustable" +msgstr "Яркость не регулируется" -#: ports/stm/common-hal/alarm/pin/PinAlarm.c -#: ports/stm/common-hal/pulseio/PulseIn.c -msgid "Pin interrupt already in use" -msgstr "Прерывание пина уже используется" +#: ports/zephyr-cp/bindings/zephyr_display/Display.c py/argcheck.c +#: shared-bindings/busdisplay/BusDisplay.c shared-bindings/displayio/Bitmap.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +#: shared-bindings/is31fl3741/FrameBuffer.c +#: shared-bindings/rgbmatrix/RGBMatrix.c +msgid "%q must be %d-%d" +msgstr "%q должно быть %d-%d" -#: shared-bindings/adafruit_bus_device/spi_device/SPIDevice.c -msgid "Pin is input only" -msgstr "Пин является только входом" +#: ports/zephyr-cp/bindings/zephyr_display/Display.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +#: shared-module/busdisplay/legacy/BusDisplay.c +#: shared-module/framebufferio/legacy/FramebufferDisplay.c +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "Group already used" +msgstr "Группа уже используется" -#: ports/raspberrypi/common-hal/countio/Counter.c -msgid "Pin must be on PWM Channel B" -msgstr "Пин должен быть на канале ШИМ B" +#: ports/zephyr-cp/common-hal/_bleio/Adapter.c +msgid "Invalid advertising data" +msgstr "" -#: 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" +#: ports/zephyr-cp/common-hal/async_spi/SPI.c +#: ports/zephyr-cp/common-hal/audiobusio/I2SOut.c +#: ports/zephyr-cp/common-hal/busio/I2C.c +#: ports/zephyr-cp/common-hal/busio/UART.c +msgid "Use device tree to define %q devices" msgstr "" -"Распиновка использует %d байт на элемент, что превышает идеальное %d байт. " -"Если этого нельзя избежать, передайте конструктору allow_inefficient=True" -#: ports/raspberrypi/common-hal/imagecapture/ParallelImageCapture.c -msgid "Pins must be sequential" -msgstr "Пины должны быть последовательными" +#: ports/zephyr-cp/common-hal/mii/Ethernet.c +msgid "cannot construct ethernet interfaces; use board.ETHERNET" +msgstr "" -#: ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c -msgid "Pins must be sequential GPIO pins" -msgstr "Пины должны быть последовательными выводами GPIO" +#: ports/zephyr-cp/common-hal/socketpool/SocketPool.c +msgid "SocketPool can only be used with %q.%q, %q.%q, or %q.%q" +msgstr "" -#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c -msgid "Pins must share PWM slice" -msgstr "Пины должны иметь общий срез PWM" +#: ports/zephyr-cp/common-hal/usb_hid/Device.c shared-module/usb_hid/Device.c +msgid "USB error" +msgstr "Ошибка USB" -#: shared-module/usb/core/Device.c -msgid "Pipe error" -msgstr "Ошибка трубопровода" +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "Failed to set hostname" +msgstr "" -#: py/builtinhelp.c -msgid "Plus any modules on the filesystem\n" -msgstr "Плюс любые модули в файловой системе\n" +#: ports/zephyr-cp/common-hal/zephyr_display/legacy/Display.c +#: ports/zephyr-cp/common-hal/zephyr_display/lvgl/Display.c +#: shared-module/busdisplay/legacy/BusDisplay.c +#: shared-module/framebufferio/legacy/FramebufferDisplay.c +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "Below minimum frame rate" +msgstr "Ниже минимальной частоты кадров" -#: shared-module/vectorio/Polygon.c -msgid "Polygon needs at least 3 points" -msgstr "Полигону необходимо как минимум 3 точки" +#: py/argcheck.c +msgid "function doesn't take keyword arguments" +msgstr "функция не принимает аргументы ключевых слов" -#: supervisor/shared/safe_mode.c -msgid "Power dipped. Make sure you are providing enough power." -msgstr "" -"Мощность просела. Убедитесь, что вы обеспечиваете достаточную мощность." +#: py/argcheck.c py/bc.c py/objnamedtuple.c shared-bindings/_eve/__init__.c +#: shared-bindings/time/__init__.c +#, c-format +msgid "function takes %d positional arguments but %d were given" +msgstr "функция принимает %d позиционные аргументы, но %d были заданы" -#: shared-bindings/_bleio/Adapter.c -msgid "Prefix buffer must be on the heap" -msgstr "Буфер префикса должен находиться в куче" +#: py/argcheck.c +#, c-format +msgid "function missing %d required positional arguments" +msgstr "Функция отсутствует %d обязательные позиционные аргументы" -#: main.c -msgid "Press any key to enter the REPL. Use CTRL-D to reload.\n" -msgstr "" -"Нажмите любую клавишу чтобы зайти в REPL. Используйте CTRL-D для " -"перезагрузки.\n" +#: py/argcheck.c +#, c-format +msgid "function expected at most %d arguments, got %d" +msgstr "функция, ожидаемая в большинстве %d аргументов, получила %d" -#: main.c -msgid "Pretending to deep sleep until alarm, CTRL-C or file write.\n" -msgstr "" -"Притворяюсь глубоким сном до сигнала тревоги, CTRL-C или записи файла.\n" +#: py/argcheck.c shared-bindings/wifi/Radio.c +msgid "'%q' argument required" +msgstr "Требуется аргумент '%q'" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Program does IN without loading ISR" -msgstr "Программа выполняет IN без загрузки ISR" +#: py/argcheck.c +msgid "extra positional arguments given" +msgstr "Приведены дополнительные позиционные аргументы" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Program does OUT without loading OSR" -msgstr "Программа выполняет ВЫХОД без загрузки OSR" +#: py/argcheck.c py/bc.c py/objnamedtuple.c +#: shared-bindings/traceback/__init__.c +msgid "unexpected keyword argument '%q'" +msgstr "неожиданный аргумент ключевого слова '%q'" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "Program size invalid" -msgstr "Недопустимый размер программы" +#: py/argcheck.c +msgid "extra keyword arguments given" +msgstr "Приведены дополнительные аргументы ключевых слов" -#: ports/espressif/common-hal/espulp/ULP.c -msgid "Program too long" -msgstr "Слишком длинная программа" +#: py/argcheck.c shared-bindings/_stage/__init__.c +#: shared-bindings/digitalio/DigitalInOut.c shared-bindings/picogame/__init__.c +msgid "argument num/types mismatch" +msgstr "Аргумент Несоответствие числа/типов" -#: shared-bindings/digitalio/DigitalInOut.c -msgid "Pull not used when direction is output." -msgstr "Тяга не используется, когда выводится направление." +#: py/argcheck.c +msgid "keyword argument(s) not implemented - use normal args instead" +msgstr "" +"Аргумент(ы) ключевого слова не реализован - используйте вместо него обычные " +"аргументы" -#: ports/raspberrypi/common-hal/countio/Counter.c -msgid "RISE_AND_FALL not available on this chip" -msgstr "RISE_AND_FALL недоступен на этом чипе" +#: py/argcheck.c +msgid "%q must be %d" +msgstr "%q должно быть %d" -#: shared-module/displayio/OnDiskBitmap.c -msgid "RLE-compressed BMP not supported" -msgstr "RLE-сжатый BMP не поддерживается" +#: py/argcheck.c +msgid "%q must be >= %d" +msgstr "%q должно быть >= %d" -#: ports/stm/common-hal/os/__init__.c -msgid "RNG DeInit Error" -msgstr "Ошибка деинициализации генератора случайных чисел" +#: py/argcheck.c shared-bindings/gifio/GifWriter.c +#: shared-module/_airlift/__init__.c +msgid "%q must be <= %d" +msgstr "%q должно быть <= %d" -#: ports/stm/common-hal/os/__init__.c -msgid "RNG Init Error" -msgstr "Ошибка инициализации RNG" +#: py/argcheck.c py/runtime.c shared-bindings/bitmapfilter/__init__.c +#: shared-module/audiodelays/MultiTapDelay.c shared-module/synthio/Note.c +#: shared-module/synthio/__init__.c +msgid "%q must be of type %q, not %q" +msgstr "%q должно быть типа %q, а не %q" -#: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c -#: ports/nordic/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c -msgid "RS485" -msgstr "RS485" +#: py/argcheck.c +msgid "%q length must be %d-%d" +msgstr "Длинна %q должна быть %d-%d" -#: ports/espressif/common-hal/busio/UART.c -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "RS485 inversion specified when not in RS485 mode" -msgstr "Инверсия RS485 указана, когда она не находится в режиме RS485" +#: py/argcheck.c +msgid "%q length must be >= %d" +msgstr "Длинна %q должна быть >= %d" -#: shared-bindings/alarm/time/TimeAlarm.c shared-bindings/time/__init__.c -msgid "RTC is not supported on this board" -msgstr "RTC не поддерживается на этой плате" +#: py/argcheck.c shared-module/_airlift/__init__.c +msgid "%q length must be <= %d" +msgstr "Длинна %q должна быть <= %d" -#: ports/stm/common-hal/os/__init__.c -msgid "Random number generation error" -msgstr "Ошибка генерации случайных чисел" +#: py/argcheck.c shared-bindings/usb_hid/Device.c +msgid "%q length must be %d" +msgstr "Длинна %q должна быть %d" -#: shared-bindings/_bleio/__init__.c -#: shared-bindings/memorymonitor/AllocationSize.c -#: shared-bindings/pulseio/PulseIn.c shared-module/bitmaptools/__init__.c -#: shared-module/displayio/Bitmap.c shared-module/displayio/Group.c -msgid "Read-only" -msgstr "Только для чтения" +#: py/argcheck.c shared-module/audiofilters/__init__.c +msgid "%q in %q must be of type %q, not %q" +msgstr "%q в %q должно быть типа %q, а не %q" -#: extmod/vfs_fat.c py/moderrno.c -msgid "Read-only filesystem" -msgstr "Файловая система только для чтения" +#: py/asmthumb.c +msgid "too many locals for native method" +msgstr "Слишком много местных жителей для нативного метода" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Received response was invalid" -msgstr "Полученный ответ недействителен" +#: py/asmxtensa.c +msgid "ERROR: xtensa %q out of range" +msgstr "" -#: supervisor/shared/bluetooth/bluetooth.c -msgid "Reconnecting" -msgstr "Повторное соединение" +#: py/asmxtensa.c +msgid "ERROR: %q %q not word-aligned" +msgstr "" -#: shared-bindings/epaperdisplay/EPaperDisplay.c -msgid "Refresh too soon" -msgstr "Слишком раннее обновление" +#: py/bc.c py/objnamedtuple.c +msgid "%q() takes %d positional arguments but %d were given" +msgstr "%q() принимает %d позиционных аргументов, но было передано %d" -#: shared-bindings/canio/RemoteTransmissionRequest.c -msgid "RemoteTransmissionRequests limited to 8 bytes" -msgstr "Запросы на удаленную передачу ограничены 8 байтами" +#: py/bc.c py/objnamedtuple.c +msgid "function got multiple values for argument '%q'" +msgstr "функция имеет несколько значений для аргументации%q \"" -#: shared-bindings/aesio/aes.c -msgid "Requested AES mode is unsupported" -msgstr "Запрошенный режим AES не поддерживается" +#: py/bc.c +msgid "unexpected keyword argument" +msgstr "Неожиданный аргумент ключевого слова" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Requested resource not found" -msgstr "Запрошенный ресурс не найден" +#: py/bc.c +#, c-format +msgid "function missing required positional argument #%d" +msgstr "В функции отсутствует обязательный позиционный аргумент #%d" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c -msgid "Right channel unsupported" -msgstr "Правый канал не поддерживается" +#: py/bc.c +msgid "function missing required keyword argument '%q'" +msgstr "В функции отсутствует обязательный аргумент ключевого слова '%q'" -#: shared-module/jpegio/JpegDecoder.c -msgid "Right format but not supported" -msgstr "Правильный формат, но не поддерживается" +#: py/bc.c +msgid "function missing keyword-only argument" +msgstr "функция отсутствует аргумент только по ключевому слову" -#: main.c -msgid "Running in safe mode! Not running saved code.\n" -msgstr "Работает в безопасном режиме! Сохраненный код не выполняется.\n" +#: py/binary.c py/objarray.c +msgid "bad typecode" +msgstr "Неверный шрифт" -#: shared-module/sdcardio/SDCard.c -msgid "SD card CSD format not supported" -msgstr "Формат CSD SD-карты не поддерживается" +#: py/binary.c +msgid "integer out of range" +msgstr "" -#: ports/cxd56/common-hal/sdioio/SDCard.c -msgid "SDCard init" -msgstr "Инициализация SD-карты" +#: py/builtinevex.c +msgid "bad compile mode" +msgstr "Неверный режим компиляции" -#: ports/stm/common-hal/sdioio/SDCard.c -#, c-format -msgid "SDIO GetCardInfo Error %d" -msgstr "Ошибка получения информации о карте SDIO %d" +#: py/builtinhelp.c +msgid "Plus any modules on the filesystem\n" +msgstr "Плюс любые модули в файловой системе\n" -#: ports/espressif/common-hal/sdioio/SDCard.c -#: ports/stm/common-hal/sdioio/SDCard.c -#, c-format -msgid "SDIO Init Error %x" -msgstr "Ошибка инициализации SDIO %x" +#: py/builtinhelp.c +msgid "object " +msgstr "объект " -#: ports/espressif/common-hal/busio/SPI.c -msgid "SPI configuration failed" -msgstr "Сбой конфигурации SPI" +#: py/builtinhelp.c +msgid " is of type %q\n" +msgstr " имеет тип %q\n" -#: ports/stm/common-hal/busio/SPI.c -msgid "SPI init error" -msgstr "Ошибка инициализации SPI" +#: py/builtinhelp.c +#, c-format +msgid "" +"Welcome to Adafruit CircuitPython %s!\n" +"\n" +"Visit circuitpython.org for more information.\n" +"\n" +"To list built-in modules type `help(\"modules\")`.\n" +msgstr "" +"Добро пожаловать в Adafruit CircuitPython %s! \n" +"\n" +"Посетите circuitpython.org для получения дополнительной информации. \n" +"\n" +"Чтобы получить список встроенных модулей, введите 'help(\"modules\")'.\n" -#: ports/raspberrypi/common-hal/busio/SPI.c -msgid "SPI peripheral in use" -msgstr "Используемое периферийное устройство SPI" +#: py/builtinimport.c +msgid "script compilation not supported" +msgstr "Компиляция скриптов не поддерживается" -#: ports/stm/common-hal/busio/SPI.c -msgid "SPI re-init" -msgstr "Повторная инициализация SPI" +#: py/builtinimport.c +msgid "can't perform relative import" +msgstr "Не удается выполнить относительный импорт" -#: shared-bindings/is31fl3741/FrameBuffer.c -msgid "Scale dimensions must divide by 3" -msgstr "Размеры шкалы необходимо разделить на 3" +#: py/builtinimport.c +msgid "module not found" +msgstr "модуль не найден" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Scan already in progress. Stop with stop_scan." -msgstr "Сканирование уже выполняется. Остановитесь на stop_scan." +#: py/builtinimport.c +msgid "no module named '%q'" +msgstr "Нет модуля с именем '%Q'" -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c -msgid "Serializer in use" -msgstr "Сериализатор используется" +#: py/builtinimport.c +msgid "relative import" +msgstr "Относительный импорт" -#: shared-bindings/ssl/SSLContext.c -msgid "Server side context cannot have hostname" -msgstr "Контекст на стороне сервера не может иметь имя хоста" +#: py/compile.c +msgid "can't assign to expression" +msgstr "Не удается назначить выражение" -#: ports/cxd56/common-hal/camera/Camera.c -msgid "Size not supported" -msgstr "Размер не поддерживается" +#: py/compile.c +msgid "multiple *x in assignment" +msgstr "Несколько *x в назначении" -#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c -#: shared-bindings/nvm/ByteArray.c -msgid "Slice and value different lengths." -msgstr "Нарежьте и оцените разную длину." +#: py/compile.c +msgid "non-default argument follows default argument" +msgstr "" +"Аргумент отличный от аргумента по умолчанию следует за аргументом по " +"умолчанию" -#: 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 "Фрагменты не поддерживаются" +#: py/compile.c +msgid "invalid micropython decorator" +msgstr "неверный декоратор микропитона" -#: ports/espressif/common-hal/socketpool/SocketPool.c -#: ports/raspberrypi/common-hal/socketpool/SocketPool.c -#: ports/zephyr-cp/common-hal/socketpool/SocketPool.c -msgid "SocketPool can only be used with wifi.radio" -msgstr "SocketPool можно использовать только с wifi.radio" +#: py/compile.c +msgid "invalid arch" +msgstr "недействительная арка" -#: shared-bindings/aesio/aes.c -msgid "Source and destination buffers must be the same length" -msgstr "Исходный и конечный буферы должны иметь одинаковую длину" +#: py/compile.c +msgid "can't delete expression" +msgstr "Не удается удалить выражение" -#: shared-bindings/paralleldisplaybus/ParallelBus.c -msgid "Specify exactly one of data0 or data_pins" -msgstr "Укажите точно один из data0 или data_pins" +#: py/compile.c +msgid "'break'/'continue' outside loop" +msgstr "'прервать'/'продолжить' вне цикла" -#: supervisor/shared/safe_mode.c -msgid "Stack overflow. Increase stack size." -msgstr "Переполнение стека. Увеличьте размер стека." +#: py/compile.c +msgid "'return' outside function" +msgstr "«возврат» внешняя функция" -#: shared-bindings/alarm/time/TimeAlarm.c -msgid "Supply one of monotonic_time or epoch_time" -msgstr "Поставьте один из monotonic_time или epoch_time" +#: py/compile.c +msgid "import * not at module level" +msgstr "Импорт * не на уровне модуля" -#: shared-bindings/gnss/GNSS.c -msgid "System entry must be gnss.SatelliteSystem" -msgstr "Системная запись должна быть gnss. Спутниковая система" +#: py/compile.c +msgid "identifier redefined as global" +msgstr "идентификатор переопределен как глобальный" -#: ports/stm/common-hal/microcontroller/Processor.c -msgid "Temperature read timed out" -msgstr "Истекло время ожидания считывания температуры" +#: py/compile.c +msgid "no binding for nonlocal found" +msgstr "Привязка для нелокальных не найдена" -#: supervisor/shared/safe_mode.c -msgid "The `microcontroller` module was used to boot into safe mode." -msgstr "" -"Модуль «микроконтроллер» использовался для загрузки в безопасном режиме." +#: py/compile.c +msgid "identifier redefined as nonlocal" +msgstr "идентификатор переопределен как нелокальный" -#: py/obj.c -msgid "The above exception was the direct cause of the following exception:" -msgstr "" -"Вышеупомянутое исключение было непосредственной причиной следующего " -"исключения:" +#: py/compile.c +msgid "can't declare nonlocal in outer code" +msgstr "не может объявить нелокальный во внешнем коде" -#: shared-bindings/rgbmatrix/RGBMatrix.c -msgid "The length of rgb_pins must be 6, 12, 18, 24, or 30" -msgstr "Длина rgb_pins должна быть 6, 12, 18, 24 или 30" +#: py/compile.c +msgid "default 'except' must be last" +msgstr "по умолчанию \"за исключением\" должно быть последним" -#: shared-module/audiocore/__init__.c -msgid "The sample's %q does not match" -msgstr "%q образца не совпадает" +#: py/compile.c +msgid "async for/with outside async function" +msgstr "async для/вместе с внешней async-функцией" -#: supervisor/shared/safe_mode.c -msgid "Third-party firmware fatal error." -msgstr "Неустранимая ошибка прошивки стороннего производителя." +#: py/compile.c +msgid "*x must be assignment target" +msgstr "*x должно быть целью назначения" -#: shared-module/imagecapture/ParallelImageCapture.c -msgid "This microcontroller does not support continuous capture." -msgstr "Этот микроконтроллер не поддерживает непрерывный захват." +#: py/compile.c +msgid "super() can't find self" +msgstr "super() не может найти себя" -#: shared-module/paralleldisplaybus/ParallelBus.c -msgid "" -"This microcontroller only supports data0=, not data_pins=, because it " -"requires contiguous pins." -msgstr "" -"Этот микроконтроллер поддерживает только data0=, а не data_pins=, поскольку " -"для него требуются смежные выводы." +#: py/compile.c +msgid "* arg after **" +msgstr "* аргумент после **" -#: shared-bindings/displayio/TileGrid.c -msgid "Tile height must exactly divide bitmap height" -msgstr "Высота плитки должна точно делить высоту растрового изображения" +#: py/compile.c +msgid "* arg after kwarg" +msgstr "" -#: shared-bindings/displayio/TileGrid.c shared-module/displayio/TileGrid.c -msgid "Tile index out of bounds" -msgstr "Выход индекса плитки за пределы" +#: py/compile.c +msgid "too many args" +msgstr "слишком много аргументов" -#: shared-bindings/displayio/TileGrid.c -msgid "Tile width must exactly divide bitmap width" -msgstr "Ширина плитки должна точно делить ширину растрового изображения" +#: py/compile.c +msgid "LHS of keyword arg must be an id" +msgstr "LHS ключевого слова arg должен быть идентификатором(id)" -#: shared-bindings/alarm/time/TimeAlarm.c -msgid "Time is in the past." -msgstr "Время в прошлом." +#: py/compile.c +msgid "positional arg after **" +msgstr "позиционный аргумент после **" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -#, c-format -msgid "Timeout is too long: Maximum timeout length is %d seconds" -msgstr "Таймаут слишком длинный: максимальная длина таймаута %d секунд" +#: py/compile.c +msgid "positional arg after keyword arg" +msgstr "позиционный аргумент после ключевого слова аргумента" -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -msgid "Too many channels in sample" -msgstr "Слишком много каналов в выборке" +#: py/compile.c py/parse.c +msgid "invalid syntax" +msgstr "недействительный синтаксис" -#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c -msgid "Too many channels in sample." -msgstr "Слишком много каналов в выборке." +#: py/compile.c +msgid "expecting key:value for dict" +msgstr "ожидание ключа: значение для дикта" -#: ports/espressif/common-hal/_bleio/Characteristic.c -msgid "Too many descriptors" -msgstr "Слишком много дескрипторов" +#: py/compile.c +msgid "expecting just a value for set" +msgstr "ожидание только значения для набора" -#: shared-module/displayio/__init__.c -msgid "Too many display busses; forgot displayio.release_displays() ?" -msgstr "Слишком много шин дисплея; забыл displayio.release_displays()?" +#: py/compile.c +msgid "'yield' outside function" +msgstr "внешняя функция \"выход\"" -#: shared-module/displayio/__init__.c -msgid "Too many displays" -msgstr "Слишком много дисплеев" +#: py/compile.c +msgid "'yield from' inside async function" +msgstr "«выход из» внутри асинхронной функции" -#: ports/espressif/common-hal/_bleio/PacketBuffer.c -#: ports/nordic/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than %q" -msgstr "Общее количество данных для записи превышает %q" +#: py/compile.c +msgid "'await' outside function" +msgstr "«ожидание» внешняя функция" -#: ports/raspberrypi/common-hal/alarm/touch/TouchAlarm.c -#: ports/stm/common-hal/alarm/touch/TouchAlarm.c -msgid "Touch alarms not available" -msgstr "Сенсорные сигналы недоступны" +#: py/compile.c +msgid "unknown type '%q'" +msgstr "Неизвестный тип '%q'" -#: py/obj.c -msgid "Traceback (most recent call last):\n" -msgstr "Трассировка (последний вызов):\n" +#: py/compile.c +msgid "annotation must be an identifier" +msgstr "Аннотация должна быть идентификатором" -#: ports/stm/common-hal/busio/UART.c -msgid "UART de-init" -msgstr "Деинициализация UART" +#: py/compile.c +msgid "argument name reused" +msgstr "Повторное использование имени аргумента" -#: ports/cxd56/common-hal/busio/UART.c ports/espressif/common-hal/busio/UART.c -#: ports/stm/common-hal/busio/UART.c -msgid "UART init" -msgstr "Инициализация UART" +#: py/compile.c +msgid "inline assembler must be a function" +msgstr "Встроенный ассемблер должен быть функцией" -#: ports/raspberrypi/common-hal/busio/UART.c -msgid "UART peripheral in use" -msgstr "Используемое периферийное устройство UART" +#: py/compile.c +msgid "unknown type" +msgstr "Неизвестный тип" -#: ports/stm/common-hal/busio/UART.c -msgid "UART re-init" -msgstr "Повторная инициализация UART" +#: py/compile.c +msgid "return annotation must be an identifier" +msgstr "Возвращаемая аннотация должна быть идентификатором" -#: ports/stm/common-hal/busio/UART.c -msgid "UART write" -msgstr "Запись UART" +#: py/compile.c +msgid "expecting an assembler instruction" +msgstr "Ожидание инструкции ассемблера" -#: main.c -msgid "UID:" -msgstr "UID:" +#: py/compile.c +msgid "'label' requires 1 argument" +msgstr "«метка» требует 1 аргумент" -#: shared-module/usb_hid/Device.c -msgid "USB busy" -msgstr "USB занят" +#: py/compile.c +msgid "label redefined" +msgstr "Метка переопределена" -#: supervisor/shared/safe_mode.c -msgid "USB devices need more endpoints than are available." -msgstr "USB-устройствам требуется больше конечных точек, чем доступно." +#: py/compile.c +msgid "'align' requires 1 argument" +msgstr "«выравнивание» требует 1 аргумента" -#: supervisor/shared/safe_mode.c -msgid "USB devices specify too many interface names." -msgstr "USB-устройства указывают слишком много имен интерфейсов." +#: py/compile.c +msgid "'data' requires at least 2 arguments" +msgstr "«данные» требуют как минимум 2 аргумента" -#: shared-module/usb_hid/Device.c -msgid "USB error" -msgstr "Ошибка USB" +#: py/compile.c +msgid "'data' requires integer arguments" +msgstr "«данные» требуют целочисленных аргументов" -#: shared-bindings/_bleio/UUID.c -msgid "UUID integer value must be 0-0xffff" -msgstr "Целое значение UUID должно быть равно 0-0xffff" +#: py/compile.c +msgid "cannot emit native code for this architecture" +msgstr "" -#: shared-bindings/_bleio/UUID.c -msgid "UUID string not 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'" -msgstr "UUID строка не 'xxxxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxxxxxxxxxx \"" +#: py/emitbc.c +msgid "bytecode overflow" +msgstr "Переполнение байт-кода" -#: shared-bindings/_bleio/UUID.c -msgid "UUID value is not str, int or byte buffer" -msgstr "Значение UUID не является строковым, целым или байтовым буфером" +#: py/emitinlinerv32.c +msgid "can only have up to 4 parameters for RV32 assembly" +msgstr "" -#: ports/raspberrypi/common-hal/memorymap/AddressRange.c -msgid "Unable to access unaligned IO register" -msgstr "Невозможно получить доступ к невыровненному регистру ввода-вывода" +#: py/emitinlinerv32.c +msgid "parameters must be registers in sequence a0 to a3" +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 "Не удается выделить буферы для подписанного преобразования" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: expecting %q" +msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Unable to allocate to the heap." -msgstr "Невозможно выделить место в куче." +#: py/emitinlinerv32.c +msgid "opcode '%q': expecting %d arguments" +msgstr "" -#: ports/espressif/common-hal/busio/I2C.c -msgid "Unable to create lock" -msgstr "Не удается создать блокировку" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: out of range" +msgstr "" -#: shared-module/i2cdisplaybus/I2CDisplayBus.c -#: shared-module/is31fl3741/IS31FL3741.c -#, c-format -msgid "Unable to find I2C Display at %x" -msgstr "Не удается найти дисплей I2C в %x" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: unknown register" +msgstr "" -#: py/parse.c -msgid "Unable to init parser" -msgstr "Не удается инициировать синтаксический анализатор" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: undefined label '%q'" +msgstr "" -#: shared-module/displayio/OnDiskBitmap.c -msgid "Unable to read color palette data" -msgstr "Не удается прочитать данные цветовой палитры" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: must not be zero" +msgstr "" -#: ports/mimxrt10xx/common-hal/canio/CAN.c -msgid "Unable to send CAN Message: all Tx message buffers are busy" +#: py/emitinlinerv32.c +msgid "opcode '%q': registers must be different" msgstr "" -#: ports/espressif/common-hal/mdns/Server.c -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "Unable to start mDNS query" -msgstr "Не удается запустить запрос mDNS" +#: py/emitinlinerv32.c +msgid "opcode '%q': malformed register list" +msgstr "" -#: shared-bindings/nvm/ByteArray.c -msgid "Unable to write to nvm." -msgstr "Невозможно выполнить запись в nvm." +#: py/emitinlinerv32.c +msgid "opcode '%q': invalid stack adjustment" +msgstr "" -#: ports/raspberrypi/common-hal/memorymap/AddressRange.c -msgid "Unable to write to read-only memory" -msgstr "Невозможно записать в постоянную память" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: wrong register(s)" +msgstr "" -#: shared-bindings/alarm/SleepMemory.c -msgid "Unable to write to sleep_memory." -msgstr "Невозможно записать в Sleep_memory." +#: py/emitinlinerv32.c +msgid "invalid RV32 instruction '%q'" +msgstr "" -#: ports/nordic/common-hal/_bleio/UUID.c -msgid "Unexpected nrfx uuid type" -msgstr "Неожиданный тип nrfx uuid" +#: py/emitinlinethumb.c +msgid "can only have up to 4 parameters to Thumb assembly" +msgstr "может иметь только до 4 параметров для сборки большого пальца" -#: ports/espressif/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown BLE error at %s:%d: %d" -msgstr "Неизвестная ошибка BLE в %s:%d: %d" +#: py/emitinlinethumb.c +msgid "parameters must be registers in sequence r0 to r3" +msgstr "Параметры должны быть регистрами в последовательности от r0 до r3" -#: ports/espressif/common-hal/_bleio/__init__.c +#: py/emitinlinethumb.c #, c-format -msgid "Unknown BLE error: %d" -msgstr "Неизвестная ошибка BLE: %d" +msgid "'%s' expects at most r%d" +msgstr "'%s' ожидает не более r%d" -#: ports/espressif/common-hal/max3421e/Max3421E.c -#: ports/raspberrypi/common-hal/wifi/__init__.c +#: py/emitinlinethumb.c py/emitinlinextensa.c #, c-format -msgid "Unknown error code %d" -msgstr "Неизвестный код ошибки %d" +msgid "'%s' expects a register" +msgstr "'%s' ожидает регистр" -#: shared-bindings/wifi/Radio.c +#: py/emitinlinethumb.c #, c-format -msgid "Unknown failure %d" -msgstr "Неизвестный сбой %d" +msgid "'%s' expects a special register" +msgstr "'%s' ожидает специальный регистр" -#: ports/nordic/common-hal/_bleio/__init__.c +#: py/emitinlinethumb.c #, c-format -msgid "Unknown gatt error: 0x%04x" -msgstr "Неизвестная ошибка gatt: 0x%04x" - -#: ports/atmel-samd/common-hal/alarm/pin/PinAlarm.c -#: supervisor/shared/safe_mode.c -msgid "Unknown reason." -msgstr "Причина неизвестна." +msgid "'%s' expects an FPU register" +msgstr "'%s' ожидает регистр FPU" -#: ports/nordic/common-hal/_bleio/__init__.c +#: py/emitinlinethumb.c #, c-format -msgid "Unknown security error: 0x%04x" -msgstr "Неизвестная ошибка безопасности: 0x%04x" +msgid "'%s' expects {r0, r1, ...}" +msgstr "'%s' ожидает {r0, r1, ...}" -#: ports/espressif/common-hal/_bleio/__init__.c +#: py/emitinlinethumb.c py/emitinlinextensa.c #, c-format -msgid "Unknown system firmware error at %s:%d: %d" -msgstr "Неизвестная системная ошибка прошивки на %s:%d: %d" +msgid "'%s' expects an integer" +msgstr "'%s' ожидает целое число" -#: ports/nordic/common-hal/_bleio/__init__.c +#: py/emitinlinethumb.c #, c-format -msgid "Unknown system firmware error: %04x" -msgstr "Неизвестная системная ошибка прошивки: %04x" +msgid "'%s' integer 0x%x doesn't fit in mask 0x%x" +msgstr "'%s' целое число 0x%x не помещается в маску 0x%x" -#: ports/espressif/common-hal/_bleio/__init__.c +#: py/emitinlinethumb.c #, c-format -msgid "Unknown system firmware error: %d" -msgstr "Неизвестная ошибка прошивки системы: %d" +msgid "'%s' expects an address of the form [a, b]" +msgstr "'%s' ожидает адрес в формате [a, b]" -#: shared-bindings/adafruit_pixelbuf/PixelBuf.c -#: shared-module/_pixelmap/PixelMap.c +#: py/emitinlinethumb.c py/emitinlinextensa.c #, c-format -msgid "Unmatched number of items on RHS (expected %d, got %d)." -msgstr "" -"Непревзойденное количество элементов на RHS (ожидалось %d, получено %d)." +msgid "'%s' expects a label" +msgstr "'%s' ожидает метку" -#: ports/nordic/common-hal/_bleio/__init__.c -msgid "" -"Unspecified issue. Can be that the pairing prompt on the other device was " -"declined or ignored." -msgstr "" -"Неуказанная проблема. Возможно, запрос на сопряжение на другом устройстве " -"был отклонен или проигнорирован." +#: py/emitinlinethumb.c py/emitinlinextensa.c +msgid "label '%q' not defined" +msgstr "Метка '%q' не определена" -#: shared-bindings/bitmaptools/__init__.c -msgid "Unsupported colorspace" -msgstr "Неподдерживаемое цветовое пространство" +#: py/emitinlinethumb.c +#, c-format +msgid "unsupported Thumb instruction '%s' with %d arguments" +msgstr "неподдерживаемая инструкция Thumb '%s' с аргументами %d" -#: shared-module/displayio/bus_core.c -msgid "Unsupported display bus type" -msgstr "Неподдерживаемый тип шины дисплея" +#: py/emitinlinethumb.c +msgid "branch not in range" +msgstr "Ветвь не в пределах досягаемости" -#: shared-module/audiocore/WaveFile.c -msgid "Unsupported format" -msgstr "Неподдерживаемый формат" +#: py/emitinlinextensa.c +msgid "can only have up to 4 parameters to Xtensa assembly" +msgstr "может иметь только до 4 параметров для сборки Xtensa" -#: shared-bindings/hashlib/__init__.c -msgid "Unsupported hash algorithm" -msgstr "Неподдерживаемый алгоритм хеширования" +#: py/emitinlinextensa.c +msgid "parameters must be registers in sequence a2 to a5" +msgstr "Параметры должны быть регистрами в последовательности от a2 до a5" -#: ports/espressif/common-hal/socketpool/Socket.c -#: ports/zephyr-cp/common-hal/socketpool/Socket.c -msgid "Unsupported socket type" -msgstr "Неподдерживаемый тип сокета" +#: py/emitinlinextensa.c +#, c-format +msgid "'%s' integer %d isn't within range %d..%d" +msgstr "'%s' целое число %d не находится в пределах диапазона %d..%d" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/espressif/common-hal/dualbank/__init__.c -msgid "Update failed" -msgstr "Обновление не удалось" +#: py/emitinlinextensa.c +#, c-format +msgid "%d is not a multiple of %d" +msgstr "" -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Descriptor.c -msgid "Value length != required fixed length" -msgstr "Длина значения! = требуемая фиксированная длина" +#: py/emitinlinextensa.c +#, c-format +msgid "unsupported Xtensa instruction '%s' with %d arguments" +msgstr "неподдерживаемая инструкция Xtensa '%s' с аргументами %d" -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Descriptor.c -msgid "Value length > max_length" -msgstr "Длина значения > максимальная_длина" +#: py/emitnative.c +msgid "conversion to object" +msgstr "Преобразование в объект" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Version was invalid" -msgstr "Версия была недействительной" +#: py/emitnative.c +msgid "local '%q' used before type known" +msgstr "местный '%q' используется перед типом" -#: ports/stm/common-hal/microcontroller/Processor.c -msgid "Voltage read timed out" -msgstr "Истекло время ожидания считывания напряжения" +#: py/emitnative.c +msgid "can't load from '%q'" +msgstr "Не удается загрузить из '%q'" -#: main.c -msgid "WARNING: Your code filename has two extensions\n" -msgstr "ВНИМАНИЕ: Имя файла кода имеет два расширения\n" +#: py/emitnative.c +msgid "can't load with '%q' index" +msgstr "Не удается загрузить с индексом '%q'" -#: ports/nordic/common-hal/watchdog/WatchDogTimer.c -msgid "WatchDogTimer cannot be deinitialized once mode is set to RESET" -msgstr "" -"Сторожевой таймер не может быть деинициализирован, если установлен режим " -"RESET" +#: py/emitnative.c +msgid "local '%q' has type '%q' but source is '%q'" +msgstr "Локальный '%q' имеет тип '%q', но источник '%q'" -#: py/builtinhelp.c -#, c-format -msgid "" -"Welcome to Adafruit CircuitPython %s!\n" -"\n" -"Visit circuitpython.org for more information.\n" -"\n" -"To list built-in modules type `help(\"modules\")`.\n" -msgstr "" -"Добро пожаловать в Adafruit CircuitPython %s! \n" -"\n" -"Посетите circuitpython.org для получения дополнительной информации. \n" -"\n" -"Чтобы получить список встроенных модулей, введите 'help(\"modules\")'.\n" +#: py/emitnative.c +msgid "can't store '%q'" +msgstr "Не удается сохранить '%q'" -#: supervisor/shared/web_workflow/web_workflow.c -msgid "Wi-Fi: " -msgstr "Wi-Fi: " +#: py/emitnative.c +msgid "can't store to '%q'" +msgstr "невозможно сохранить в «%q»" -#: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "Wifi is not enabled" -msgstr "Wifi не включен" +#: py/emitnative.c +msgid "can't store with '%q' index" +msgstr "не может хранить с индексом%q" -#: main.c -msgid "Woken up by alarm.\n" -msgstr "Проснулся по тревоге.\n" +#: py/emitnative.c +msgid "can't implicitly convert '%q' to 'bool'" +msgstr "не может неявно преобразовать '%q' в 'bool'" -#: ports/espressif/common-hal/_bleio/PacketBuffer.c -#: ports/nordic/common-hal/_bleio/PacketBuffer.c -msgid "Writes not supported on Characteristic" -msgstr "Запись не поддерживается в Характеристика" +#: py/emitnative.c +msgid "'not' not implemented" +msgstr "'не' не реализовано" -#: 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/meowmeow/mpconfigboard.h -msgid "You pressed both buttons at start up." -msgstr "Вы нажали обе кнопки при запуске." +#: py/emitnative.c +msgid "can't do unary op of '%q'" +msgstr "Невозможно выполнить унарную операцию '%q'" -#: ports/espressif/boards/m5stack_core_basic/mpconfigboard.h -#: ports/espressif/boards/m5stack_core_fire/mpconfigboard.h -#: ports/espressif/boards/m5stack_stick_c/mpconfigboard.h -#: ports/espressif/boards/m5stack_stick_c_plus/mpconfigboard.h -#: ports/espressif/boards/m5stack_stick_c_plus2/mpconfigboard.h -msgid "You pressed button A at start up." -msgstr "Вы нажали кнопку A при запуске." +#: py/emitnative.c +msgid "div/mod not implemented for uint" +msgstr "div/mod не реализован для uint" -#: ports/espressif/boards/m5stack_m5paper/mpconfigboard.h -msgid "You pressed button DOWN at start up." -msgstr "Вы нажали кнопку ВНИЗ при запуске." +#: py/emitnative.c +msgid "comparison of int and uint" +msgstr "сравнение int и uint" -#: supervisor/shared/safe_mode.c -msgid "You pressed the BOOT button at start up" -msgstr "Вы нажали кнопку BOOT при запуске" +#: py/emitnative.c +msgid "binary op %q not implemented" +msgstr "двоичная операция %q не реализована" -#: ports/espressif/boards/adafruit_feather_esp32c6_4mbflash_nopsram/mpconfigboard.h -#: ports/espressif/boards/adafruit_itsybitsy_esp32/mpconfigboard.h -#: ports/espressif/boards/waveshare_esp32_c6_lcd_1_47/mpconfigboard.h -msgid "You pressed the BOOT button at start up." -msgstr "При запуске вы нажали кнопку BOOT." +#: py/emitnative.c +msgid "can't do binary op between '%q' and '%q'" +msgstr "Не могу выполнить двоичную операцию между '%q' и '%q'" -#: ports/espressif/boards/adafruit_huzzah32_breakout/mpconfigboard.h -msgid "You pressed the GPIO0 button at start up." -msgstr "Вы нажали кнопку GPIO0 при запуске." +#: py/emitnative.c +msgid "casting" +msgstr "кастинг" -#: ports/espressif/boards/espressif_esp32_lyrat/mpconfigboard.h -msgid "You pressed the Rec button at start up." -msgstr "Вы нажали кнопку «Запись» при запуске." +#: py/emitnative.c +msgid "return expected '%q' but got '%q'" +msgstr "Возврат ожидался '%q', но получил '%q'" -#: ports/espressif/boards/adafruit_feather_esp32_v2/mpconfigboard.h -msgid "You pressed the SW38 button at start up." -msgstr "Вы нажали кнопку SW38 при запуске." +#: py/emitnative.c +msgid "native raise" +msgstr "" -#: ports/espressif/boards/hardkernel_odroid_go/mpconfigboard.h -#: ports/espressif/boards/vidi_x/mpconfigboard.h -msgid "You pressed the VOLUME button at start up." -msgstr "Вы нажали кнопку ГРОМКОСТЬ при запуске." +#: py/emitnative.c +msgid "must raise an object" +msgstr "должен поднять объект" -#: ports/espressif/boards/m5stack_atom_echo/mpconfigboard.h -#: ports/espressif/boards/m5stack_atom_lite/mpconfigboard.h -#: ports/espressif/boards/m5stack_atom_matrix/mpconfigboard.h -#: ports/espressif/boards/m5stack_atom_u/mpconfigboard.h -msgid "You pressed the central button at start up." -msgstr "Вы нажали центральную кнопку при запуске." +#: py/emitnative.c +msgid "native yield" +msgstr "родной урожай" -#: ports/nordic/boards/aramcon2_badge/mpconfigboard.h -msgid "You pressed the left button at start up." -msgstr "Вы нажали левую кнопку при запуске." +#: py/lexer.c +msgid "unicode name escapes" +msgstr "Экранирование имен в Юникоде" -#: supervisor/shared/safe_mode.c -msgid "You pressed the reset button during boot." -msgstr "Вы нажали кнопку сброса во время загрузки." +#: py/modbuiltins.c py/objstr.c +msgid "char not in range(0x110000)" +msgstr "" + +#: py/modbuiltins.c +msgid "chr() arg not in range(256)" +msgstr "chr() аргумент вне диапазона (256)" -#: supervisor/shared/micropython.c -msgid "[truncated due to length]" -msgstr "[отрезается по длине]" +#: py/modbuiltins.c +msgid "arg is an empty sequence" +msgstr "arg - пустая последовательность" -#: py/objtype.c -msgid "__init__() should return None" -msgstr "__init__() должен возвращать значение None" +#: py/modbuiltins.c +msgid "ord expects a character" +msgstr "Орд ожидает персонажа" -#: py/objtype.c +#: py/modbuiltins.c #, c-format -msgid "__init__() should return None, not '%s'" -msgstr "__init__() должна возвращать Нет, а не \"%s\"" +msgid "ord() expected a character, but string of length %d found" +msgstr "ord() ожидал символ, но строка длины %d найдена" -#: py/objobject.c -msgid "__new__ arg must be a user-type" -msgstr "__new__ arg должен быть пользовательского типа" +#: py/modbuiltins.c +msgid "3-arg pow() not supported" +msgstr "Pow() с 3 аргументами не поддерживается" -#: extmod/modbinascii.c extmod/modhashlib.c py/objarray.c -msgid "a bytes-like object is required" -msgstr "Требуется байтоподобный объект" +#: py/modbuiltins.c +msgid "must use keyword argument for key function" +msgstr "Необходимо использовать аргумент ключевого слова для ключевой функции" -#: shared-bindings/i2ctarget/I2CTarget.c -msgid "addresses is empty" -msgstr "адреса пусты" +#: py/moderrno.c +msgid "Operation not permitted" +msgstr "Операция не разрешена" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "already playing" -msgstr "" +#: py/moderrno.c +msgid "No such file/directory" +msgstr "Файл/директория не существует" -#: py/compile.c -msgid "annotation must be an identifier" -msgstr "Аннотация должна быть идентификатором" +#: py/moderrno.c +msgid "Input/output error" +msgstr "Ошибка ввода/вывода" -#: extmod/ulab/code/numpy/create.c -msgid "arange: cannot compute length" -msgstr "arange: не удается вычислить длину" +#: py/moderrno.c +msgid "Permission denied" +msgstr "Отказано в разрешении" -#: py/modbuiltins.c -msgid "arg is an empty sequence" -msgstr "arg - пустая последовательность" +#: py/moderrno.c +msgid "File exists" +msgstr "Файл существует" -#: py/objobject.c -msgid "arg must be user-type" -msgstr "arg должен быть пользовательского типа" +#: py/moderrno.c +msgid "No such device" +msgstr "Нет такого устройства" -#: extmod/ulab/code/numpy/numerical.c -msgid "argsort argument must be an ndarray" -msgstr "аргумент сортировки должен быть аргументом массива ndarray" +#: py/moderrno.c +msgid "No space left on device" +msgstr "На устройстве не осталось свободного места" -#: extmod/ulab/code/numpy/numerical.c -msgid "argsort is not implemented for flattened arrays" -msgstr "сортировка arg не реализована для сглаженных массивов" +#: py/modmath.c shared-bindings/math/__init__.c +msgid "math domain error" +msgstr "Ошибка математической области" -#: extmod/ulab/code/numpy/random/random.c -msgid "argument must be None, an integer or a tuple of integers" -msgstr "аргумент должен быть None, целым числом или кортежем целых чисел" +#: py/modmath.c +msgid "negative factorial" +msgstr "отрицательный факториал" -#: py/compile.c -msgid "argument name reused" -msgstr "Повторное использование имени аргумента" +#: py/modmicropython.c +msgid "schedule queue full" +msgstr "Расписание Очередь заполнена" -#: py/argcheck.c shared-bindings/_stage/__init__.c -#: shared-bindings/digitalio/DigitalInOut.c -msgid "argument num/types mismatch" -msgstr "Аргумент Несоответствие числа/типов" +#: py/modstruct.c shared-bindings/picogame/Bitmap.c +#: shared-bindings/picogame/Canvas.c shared-bindings/picogame/Framebuffer.c +#: shared-module/picogame/__init__.c shared-module/struct/__init__.c +msgid "buffer too small" +msgstr "буфер слишком мал" -#: extmod/ulab/code/numpy/numerical.c extmod/ulab/code/numpy/transform.c -msgid "arguments must be ndarrays" -msgstr "Аргументы должны быть массивами ndarrays" +#: py/modstruct.c +#, c-format +msgid "pack expected %d items for packing (got %d)" +msgstr "Упаковка ожидаемых %d товаров для упаковки (получил %d)" -#: extmod/ulab/code/ndarray.c -msgid "array and index length must be equal" -msgstr "Длина массива и индекса должна быть равна" +#: py/modthread.c +msgid "expecting a dict for keyword args" +msgstr "ожидание определения аргументов ключевых слов" -#: extmod/ulab/code/numpy/io/io.c -msgid "array has too many dimensions" -msgstr "Массив имеет слишком много измерений" +#: py/modweakref.c +msgid "not a heap object" +msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "array is too big" -msgstr "массив слишком велик" +#: py/nativeglue.c +msgid "set unsupported" +msgstr "Установить не поддерживается" -#: py/objarray.c shared-bindings/alarm/SleepMemory.c -#: shared-bindings/memorymap/AddressRange.c shared-bindings/nvm/ByteArray.c -msgid "array/bytes required on right side" -msgstr "массив/байты, необходимые справа" +#: py/nativeglue.c +msgid "slice unsupported" +msgstr "Фрагмент не поддерживается" -#: py/asmxtensa.c -msgid "asm overflow" -msgstr "Переполнение ASM" +#: py/nativeglue.c +msgid "float unsupported" +msgstr "Плавающий без поддержки" -#: py/compile.c -msgid "async for/with outside async function" -msgstr "async для/вместе с внешней async-функцией" +#: py/obj.c shared-module/adafruit_pixelbuf/PixelBuf.c +msgid "can't convert %q to %q" +msgstr "Не удается преобразовать %q в %q" -#: extmod/ulab/code/numpy/numerical.c -msgid "attempt to get (arg)min/(arg)max of empty sequence" +#: py/obj.c +msgid "During handling of the above exception, another exception occurred:" msgstr "" -"Попытка получить (аргумент)минимальный/(аргумент)максимальный пустой " -"последовательности" +"При обращении с вышеуказанным исключением произошло еще одно исключение:" -#: extmod/ulab/code/numpy/numerical.c -msgid "attempt to get argmin/argmax of an empty sequence" +#: py/obj.c +msgid "The above exception was the direct cause of the following exception:" msgstr "" -"Попытка получить аргумент минимальный/аргумент максимальный пустой " -"последовательности" +"Вышеупомянутое исключение было непосредственной причиной следующего " +"исключения:" -#: py/objstr.c -msgid "attributes not supported" -msgstr "Атрибуты не поддерживаются" +#: py/obj.c +msgid " File \"%q\", line %d" +msgstr " Файл \"%q\", строка %d" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "audio format not supported" -msgstr "" +#: py/obj.c +msgid " File \"%q\"" +msgstr " Файл \"%q\"" -#: extmod/ulab/code/ulab_tools.c -msgid "axis is out of bounds" -msgstr "Ось выходит за пределы" +#: py/obj.c +msgid ", in %q\n" +msgstr ", в %q\n" -#: extmod/ulab/code/numpy/numerical.c extmod/ulab/code/ulab_tools.c -msgid "axis must be None, or an integer" -msgstr "ось должна быть None или целым числом" +#: py/obj.c +msgid "Traceback (most recent call last):\n" +msgstr "Трассировка (последний вызов):\n" -#: extmod/ulab/code/numpy/numerical.c -msgid "axis too long" -msgstr "Слишком длинная ось" +#: py/obj.c +msgid "can't convert to float" +msgstr "Не удается преобразовать в float" -#: shared-bindings/bitmaptools/__init__.c -msgid "background value out of range of target" -msgstr "Фоновое значение вне диапазона цели" +#: py/obj.c +#, c-format +msgid "can't convert %s to float" +msgstr "не могу преобразовать %s в число с плавающей запятой" -#: py/builtinevex.c -msgid "bad compile mode" -msgstr "Неверный режим компиляции" +#: py/obj.c +msgid "can't convert to complex" +msgstr "не может быть преобразован в сложный" -#: py/objstr.c -msgid "bad conversion specifier" -msgstr "Неверный спецификатор преобразования" +#: py/obj.c +#, c-format +msgid "can't convert %s to complex" +msgstr "не может преобразовать %s в сложный" -#: py/objstr.c -msgid "bad format string" -msgstr "Строка неверного формата" +#: py/obj.c +msgid "expected tuple/list" +msgstr "Ожидаемый кортеж/список" -#: py/binary.c py/objarray.c -msgid "bad typecode" -msgstr "Неверный шрифт" +#: py/obj.c +#, c-format +msgid "object '%s' isn't a tuple or list" +msgstr "Объект \"%s\" не является кортежом или списком" -#: py/emitnative.c -msgid "binary op %q not implemented" -msgstr "двоичная операция %q не реализована" +#: py/obj.c +msgid "tuple/list has wrong length" +msgstr "Кортеж/список имеет неправильную длину" -#: ports/espressif/common-hal/audiobusio/PDMIn.c -msgid "bit_depth must be 8, 16, 24, or 32." -msgstr "Глубина_бита должна быть равна 8, 16, 24 или 32." +#: py/obj.c +#, c-format +msgid "requested length %d but object has length %d" +msgstr "запрашиваемая длина %d, но объект имеет длину %d" -#: shared-module/bitmapfilter/__init__.c -msgid "bitmap size and depth must match" -msgstr "Размер и глубина растрового изображения должны совпадать" +#: py/obj.c +msgid "indices must be integers" +msgstr "индексы должны быть целыми числами" -#: shared-bindings/bitmaptools/__init__.c -msgid "bitmap sizes must match" -msgstr "Размеры растровых изображений должны совпадать" +#: py/obj.c +msgid "%q indices must be integers, not %s" +msgstr "Индексы %q должны быть целыми числами, а не %s" + +#: py/obj.c +msgid "object has no len" +msgstr "Объект не имеет объектива" + +#: py/obj.c +#, c-format +msgid "object of type '%s' has no len()" +msgstr "объект типа «%s» не имеет len()" + +#: py/obj.c +msgid "object doesn't support item deletion" +msgstr "Объект не поддерживает удаление элементов" + +#: py/obj.c +#, c-format +msgid "'%s' object doesn't support item deletion" +msgstr "Объект '%s' не поддерживает удаление элементов" -#: extmod/modrandom.c -msgid "bits must be 32 or less" -msgstr "биты должны быть 32 или менее" +#: py/obj.c +msgid "object isn't subscriptable" +msgstr "Объект не имеет индекса" -#: shared-bindings/audiodelays/Echo.c shared-bindings/audiodelays/PitchShift.c -#: shared-bindings/audiofilters/Distortion.c -#: shared-bindings/audiofilters/Filter.c shared-bindings/audiomixer/Mixer.c -msgid "bits_per_sample must be 8 or 16" -msgstr "bits_per_sample должно быть 8 или 16" +#: py/obj.c +#, c-format +msgid "'%s' object isn't subscriptable" +msgstr "Объект '%s' не может быть подписан" -#: py/emitinlinethumb.c -msgid "branch not in range" -msgstr "Ветвь не в пределах досягаемости" +#: py/obj.c +msgid "object doesn't support item assignment" +msgstr "Объект не поддерживает назначение элементов" -#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c -msgid "buffer is smaller than requested size" -msgstr "Размер буфера меньше запрошенного" +#: py/obj.c +#, c-format +msgid "'%s' object doesn't support item assignment" +msgstr "Объект '%s' не поддерживает присвоение элементов" -#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c -msgid "buffer size must be a multiple of element size" -msgstr "Размер буфера должен быть кратен размеру элемента" +#: py/obj.c +msgid "object with buffer protocol required" +msgstr "Объект с обязательным буферным протоколом" -#: shared-module/struct/__init__.c -msgid "buffer size must match format" -msgstr "Размер буфера должен соответствовать формату" +#: py/objarray.c +msgid "bytes length not a multiple of item size" +msgstr "длина байтов, не кратная размеру элемента" -#: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c -msgid "buffer slices must be of equal length" -msgstr "Буферные фрагменты должны быть одинаковой длины" +#: py/objarray.c py/objstr.c +msgid "string argument without an encoding" +msgstr "строковый аргумент без кодировки" -#: py/modstruct.c shared-module/struct/__init__.c -msgid "buffer too small" -msgstr "буфер слишком мал" +#: py/objarray.c +msgid "memoryview: length is not a multiple of itemsize" +msgstr "вид памяти: длина не является множеством элементов" -#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c -msgid "buffer too small for requested bytes" -msgstr "Слишком маленький буфер для запрашиваемых байтов" +#: py/objarray.c py/objstr.c +msgid "substring not found" +msgstr "Подстрока не найдена" -#: py/emitbc.c -msgid "bytecode overflow" -msgstr "Переполнение байт-кода" +#: py/objarray.c py/objstr.c py/objstrunicode.c py/objtuple.c +#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c +#: shared-bindings/nvm/ByteArray.c +msgid "only slices with step=1 (aka None) are supported" +msgstr "поддерживаются только срезы с шагом = 1 (так как нет)" #: py/objarray.c -msgid "bytes length not a multiple of item size" -msgstr "длина байтов, не кратная размеру элемента" +msgid "lhs and rhs should be compatible" +msgstr "lhs и rhs должны быть совместимыми" -#: py/objstr.c -msgid "bytes value out of range" -msgstr "Значение байтов вне диапазона" +#: py/objarray.c shared-bindings/alarm/SleepMemory.c +#: shared-bindings/memorymap/AddressRange.c shared-bindings/nvm/ByteArray.c +msgid "array/bytes required on right side" +msgstr "массив/байты, необходимые справа" -#: ports/atmel-samd/bindings/samd/Clock.c -msgid "calibration is out of range" -msgstr "Калибровка выходит за пределы допустимого диапазона" +#: py/objarray.c +msgid "memoryview offset too large" +msgstr "Слишком большое смещение просмотра памяти" -#: ports/atmel-samd/bindings/samd/Clock.c -msgid "calibration is read only" -msgstr "Калибровка доступна только для чтения" +#: py/objcomplex.c +msgid "can't truncate-divide a complex number" +msgstr "нельзя усекать и делить комплексное число" -#: shared-module/vectorio/Circle.c shared-module/vectorio/Polygon.c -#: shared-module/vectorio/Rectangle.c -msgid "can only have one parent" -msgstr "может иметь только одного родителя" +#: py/objcomplex.c +msgid "complex divide by zero" +msgstr "комплексное деление на ноль" -#: py/emitinlinethumb.c -msgid "can only have up to 4 parameters to Thumb assembly" -msgstr "может иметь только до 4 параметров для сборки большого пальца" +#: py/objcomplex.c +msgid "0.0 to a complex power" +msgstr "0.0 в комплексную степень" -#: py/emitinlinextensa.c -msgid "can only have up to 4 parameters to Xtensa assembly" -msgstr "может иметь только до 4 параметров для сборки Xtensa" +#: py/objdeque.c +msgid "full" +msgstr "полный" -#: extmod/ulab/code/ndarray.c -msgid "can only specify one unknown dimension" -msgstr "Можно указать только одно неизвестное измерение" +#: py/objdeque.c +msgid "empty" +msgstr "пусто" -#: py/objtype.c -msgid "can't add special method to already-subclassed class" -msgstr "" -"Не удается добавить специальный метод к уже имеющемуся подклассу классу" +#: py/objdict.c +msgid "dict update sequence has wrong length" +msgstr "последовательность обновления дикта имеет неправильную длину" -#: py/compile.c -msgid "can't assign to expression" -msgstr "Не удается назначить выражение" +#: py/objexcept.c py/objnamedtuple.c +msgid "can't set attribute" +msgstr "Не удается установить атрибут" -#: extmod/modasyncio.c -msgid "can't cancel self" -msgstr "Не могу отменить себя" +#: py/objfloat.c py/parsenum.c +msgid "complex values not supported" +msgstr "Комплексные значения не поддерживаются" -#: py/obj.c shared-module/adafruit_pixelbuf/PixelBuf.c -msgid "can't convert %q to %q" -msgstr "Не удается преобразовать %q в %q" +#: py/objgenerator.c +msgid "generator already executing" +msgstr "генератор уже работает" -#: py/obj.c -#, c-format -msgid "can't convert %s to complex" -msgstr "не может преобразовать %s в сложный" +#: py/objgenerator.c +msgid "can't send non-None value to a just-started generator" +msgstr "" +"не может отправить значение, отличное от None, только что запущенному " +"генератору" -#: py/obj.c -#, c-format -msgid "can't convert %s to float" -msgstr "не могу преобразовать %s в число с плавающей запятой" +#: py/objgenerator.c py/runtime.c +msgid "generator raised StopIteration" +msgstr "генератор поднят Остановить итерацию" + +#: py/objgenerator.c +msgid "generator ignored GeneratorExit" +msgstr "генератор проигнорировал Выход" #: py/objint.c py/runtime.c #, c-format msgid "can't convert %s to int" msgstr "Невозможно преобразовать %s в int" -#: py/objstr.c -msgid "can't convert '%q' object to %q implicitly" -msgstr "не может конвертировать «%q» в% q косвенно" +#: py/objint.c +msgid "float too big" +msgstr "Поплавок слишком большой" -#: extmod/ulab/code/numpy/vector.c -msgid "can't convert complex to float" -msgstr "Не может преобразовать сложный в плавающий" +#: py/objint.c shared-bindings/time/__init__.c +msgid "No long integer support" +msgstr "Нет поддержки длинных целых чисел (long integer)" -#: py/obj.c -msgid "can't convert to complex" -msgstr "не может быть преобразован в сложный" +#: py/objint.c py/sequence.c +msgid "small int overflow" +msgstr "Маленькое переполнение int" -#: py/obj.c -msgid "can't convert to float" -msgstr "Не удается преобразовать в float" +#: py/objint.c shared-bindings/_bleio/Connection.c +#: shared-bindings/storage/__init__.c +msgid "%q=%q" +msgstr "%q=%q" -#: py/runtime.c -msgid "can't convert to int" -msgstr "Не удается преобразовать в int" +#: py/objint_impl.h +#, c-format +msgid "value would overflow a %d byte buffer" +msgstr "" -#: py/objstr.c -msgid "can't convert to str implicitly" -msgstr "не может превратиться в полосу неявно" +#: py/objint_impl.h +msgid "can't convert negative int to unsigned" +msgstr "" -#: py/compile.c -msgid "can't declare nonlocal in outer code" -msgstr "не может объявить нелокальный во внешнем коде" +#: py/objint_longlong.c py/parsenum.c +msgid "result overflows long long storage" +msgstr "" -#: py/compile.c -msgid "can't delete expression" -msgstr "Не удается удалить выражение" +#: py/objint_longlong.c py/objint_mpz.c py/runtime.c +msgid "negative shift count" +msgstr "Количество отрицательных сдвигов" -#: py/emitnative.c -msgid "can't do binary op between '%q' and '%q'" -msgstr "Не могу выполнить двоичную операцию между '%q' и '%q'" +#: py/objint_longlong.c py/objint_mpz.c py/runtime.c +msgid "negative power with no float support" +msgstr "Отрицательная мощность без поплавковой опоры" -#: py/emitnative.c -msgid "can't do unary op of '%q'" -msgstr "Невозможно выполнить унарную операцию '%q'" +#: py/objint_longlong.c py/objint_mpz.c +msgid "overflow converting long int to machine word" +msgstr "переполнение преобразование длинного целого в машинное слово" -#: py/emitnative.c -msgid "can't implicitly convert '%q' to 'bool'" -msgstr "не может неявно преобразовать '%q' в 'bool'" +#: py/objint_mpz.c +msgid "pow() with 3 arguments requires integers" +msgstr "pow() с 3 аргументами требует целых чисел" -#: py/runtime.c -msgid "can't import name %q" -msgstr "Невозможно импортировать имя %q" +#: py/objint_mpz.c +msgid "pow() 3rd argument cannot be 0" +msgstr "3-й аргумент pow() не может быть равен 0" -#: py/emitnative.c -msgid "can't load from '%q'" -msgstr "Не удается загрузить из '%q'" +#: py/objobject.c +msgid "__new__ arg must be a user-type" +msgstr "__new__ arg должен быть пользовательского типа" -#: py/emitnative.c -msgid "can't load with '%q' index" -msgstr "Не удается загрузить с индексом '%q'" +#: py/objobject.c +msgid "arg must be user-type" +msgstr "arg должен быть пользовательского типа" -#: py/builtinimport.c -msgid "can't perform relative import" -msgstr "Не удается выполнить относительный импорт" +#: py/objrange.c py/objslice.c shared-bindings/random/__init__.c +msgid "%q step cannot be zero" +msgstr "Шаг %q не может быть нулём" -#: py/objgenerator.c -msgid "can't send non-None value to a just-started generator" +#: py/objslice.c +msgid "Cannot subclass slice" +msgstr "Невозможно создать подкласс среза" + +#: py/objstr.c +msgid "unknown encoding: %q" +msgstr "" + +#: py/objstr.c +msgid "bytes value out of range" +msgstr "Значение байтов вне диапазона" + +#: py/objstr.c +msgid "join expects a list of str/bytes objects consistent with self object" msgstr "" -"не может отправить значение, отличное от None, только что запущенному " -"генератору" +"присоединяйтесь к ожидающему список стр/байт объектов, совместимых с " +"самообъектом" -#: shared-module/sdcardio/SDCard.c -msgid "can't set 512 block size" -msgstr "Не удается установить размер блока 512" +#: py/objstr.c +msgid "empty separator" +msgstr "пустой сепаратор" -#: py/objexcept.c py/objnamedtuple.c -msgid "can't set attribute" -msgstr "Не удается установить атрибут" +#: py/objstr.c +msgid "rsplit(None,n)" +msgstr "rsplit(Нет;n)" -#: py/runtime.c -msgid "can't set attribute '%q'" -msgstr "Не удается установить атрибут '%q'" +#: py/objstr.c +msgid "bad format string" +msgstr "Строка неверного формата" -#: py/emitnative.c -msgid "can't store '%q'" -msgstr "Не удается сохранить '%q'" +#: py/objstr.c +#, c-format +msgid "unmatched '%c' in format" +msgstr "Несовпадающий '%c' в формате" -#: py/emitnative.c -msgid "can't store to '%q'" -msgstr "невозможно сохранить в «%q»" +#: py/objstr.c +msgid "bad conversion specifier" +msgstr "Неверный спецификатор преобразования" -#: py/emitnative.c -msgid "can't store with '%q' index" -msgstr "не может хранить с индексом%q" +#: py/objstr.c +msgid "end of format while looking for conversion specifier" +msgstr "конец формата при поиске спецификатора преобразования" + +#: py/objstr.c +#, c-format +msgid "unknown conversion specifier %c" +msgstr "Неизвестный спецификатор преобразования %c" + +#: py/objstr.c +msgid "expected ':' after format specifier" +msgstr "Ожидаемый ':' после спецификатора формата" #: py/objstr.c msgid "" @@ -2845,603 +3568,650 @@ msgstr "" "Не удается переключиться с автоматической нумерации полей на ручную " "спецификацию полей" +#: py/objstr.c +msgid "%q index out of range" +msgstr "Индекс %q вне диапазона" + +#: py/objstr.c +msgid "attributes not supported" +msgstr "Атрибуты не поддерживаются" + #: py/objstr.c msgid "" "can't switch from manual field specification to automatic field numbering" msgstr "не может переключаться с ручного поля на автоматическую нумерацию поля" -#: py/objcomplex.c -msgid "can't truncate-divide a complex number" -msgstr "нельзя усекать и делить комплексное число" +#: py/objstr.c +msgid "invalid format specifier" +msgstr "Недопустимый спецификатор формата" -#: extmod/modasyncio.c -msgid "can't wait" -msgstr "не может ждать" +#: py/objstr.c +msgid "sign not allowed in string format specifier" +msgstr "Знак не разрешен в спецификаторе строкового формата" -#: extmod/ulab/code/ndarray.c -msgid "cannot assign new shape" -msgstr "Не удается назначить новую фигуру" +#: py/objstr.c +msgid "sign not allowed with integer format specifier 'c'" +msgstr "Знак не разрешен со спецификатором целочисленного формата 'c'" -#: extmod/ulab/code/ndarray_operators.c -msgid "cannot cast output with casting rule" -msgstr "Не удается привести выходные данные с помощью правила приведения" +#: py/objstr.c +msgid "unknown format code '%c' for object of type '%q'" +msgstr "Неизвестный код формата '%c' для объекта типа '%q'" -#: extmod/ulab/code/ndarray.c -msgid "cannot convert complex to dtype" -msgstr "не может превратить комплекс в dtype" +#: py/objstr.c +msgid "'=' alignment not allowed in string format specifier" +msgstr "Выравнивание '=' недопустимо в спецификаторе формата строки" -#: extmod/ulab/code/ndarray.c -msgid "cannot convert complex type" -msgstr "Не удается преобразовать сложный тип" +#: py/objstr.c +msgid "format needs a dict" +msgstr "Формат требует диктата" -#: py/objtype.c -msgid "cannot create '%q' instances" -msgstr "Не удается создать экземпляры '%q'" +#: py/objstr.c +msgid "incomplete format key" +msgstr "Неполный ключ форматирования" -#: py/objtype.c -msgid "cannot create instance" -msgstr "Не удается создать экземпляр" +#: py/objstr.c +msgid "incomplete format" +msgstr "Неполный формат" -#: extmod/ulab/code/ndarray.c -msgid "cannot delete array elements" -msgstr "Не удается удалить элементы массива" +#: py/objstr.c +msgid "format string needs more arguments" +msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "cannot reshape array" -msgstr "Не удается изменить форму массива" +#: py/objstr.c +#, c-format +msgid "%%c needs int or char" +msgstr "" -#: py/emitnative.c -msgid "casting" -msgstr "кастинг" +#: py/objstr.c +#, c-format +msgid "unsupported format character '%c' (0x%x) at index %d" +msgstr "Неподдерживаемый символ формата '%c' (0x%x) при индексе %d" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "channel re-init" -msgstr "Реинициализация канала" +#: py/objstr.c +msgid "format string didn't convert all arguments" +msgstr "" -#: shared-bindings/_stage/Text.c -msgid "chars buffer too small" -msgstr "Слишком маленький буфер символов" +#: py/objstr.c +msgid "non-hex digit" +msgstr "" -#: py/modbuiltins.c -msgid "chr() arg not in range(0x110000)" -msgstr "chr() аргумент вне диапазона (0x110000)" +#: py/objstr.c +msgid "can't convert to str implicitly" +msgstr "не может превратиться в полосу неявно" -#: py/modbuiltins.c -msgid "chr() arg not in range(256)" -msgstr "chr() аргумент вне диапазона (256)" +#: py/objstr.c +msgid "can't convert '%q' object to %q implicitly" +msgstr "не может конвертировать «%q» в% q косвенно" -#: shared-bindings/bitmaptools/__init__.c -msgid "clip point must be (x,y) tuple" -msgstr "Точка клипа должна быть кортежом (x,y)" +#: py/objstrunicode.c +#, c-format +msgid "string indices must be integers, not %s" +msgstr "Индексы строк должны быть целыми числами, а не %s" -#: shared-bindings/msgpack/ExtType.c -msgid "code outside range 0~127" -msgstr "код вне диапазона 0~127" +#: py/objstrunicode.c +msgid "string index out of range" +msgstr "индекс строки выходит за пределы диапазона" -#: shared-bindings/displayio/Palette.c -msgid "color buffer must be 3 bytes (RGB) or 4 bytes (RGB + pad byte)" +#: py/objtemplate.c +msgid "expected str or Interpolation" msgstr "" -"Цветовой буфер должен иметь размер 3 байта (RGB) или 4 байта (RGB + байт " -"заполнения)" -#: shared-bindings/displayio/Palette.c -msgid "color buffer must be a buffer, tuple, list, or int" -msgstr "Цветовой буфер должен быть буфером, кортежом, списком или целым числом" +#: py/objtype.c +msgid "Call super().__init__() before accessing native object." +msgstr "Вызовите super().__init__() перед доступом к собственному объекту." -#: shared-bindings/displayio/Palette.c -msgid "color buffer must be a bytearray or array of type 'b' or 'B'" +#: py/objtype.c +msgid "__init__() should return None" +msgstr "__init__() должен возвращать значение None" + +#: py/objtype.c +#, c-format +msgid "__init__() should return None, not '%s'" +msgstr "__init__() должна возвращать Нет, а не \"%s\"" + +#: py/objtype.c py/runtime.c +msgid "unreadable attribute" +msgstr "Нечитаемый атрибут" + +#: py/objtype.c py/runtime.c +msgid "object not callable" +msgstr "Объект не вызывается" + +#: py/objtype.c py/runtime.c shared-module/atexit/__init__.c +msgid "'%q' object isn't callable" msgstr "" -"цветовой буфер должен быть байтом массива или массивом типа \"b\" или \"B\"" -#: shared-bindings/displayio/Palette.c -msgid "color must be between 0x000000 and 0xffffff" -msgstr "Цвет должен быть от 0x000000 до 0xffffff" +#: py/objtype.c +msgid "type takes 1 or 3 arguments" +msgstr "тип занимает 1 или 3 аргумента" -#: py/emitnative.c -msgid "comparison of int and uint" -msgstr "сравнение int и uint" +#: py/objtype.c +msgid "can't create instance" +msgstr "" -#: py/objcomplex.c -msgid "complex divide by zero" -msgstr "комплексное деление на ноль" +#: py/objtype.c +msgid "can't create '%q' instances" +msgstr "" -#: py/objfloat.c py/parsenum.c -msgid "complex values not supported" -msgstr "Комплексные значения не поддерживаются" +#: py/objtype.c +msgid "can't add special method to already-subclassed class" +msgstr "" +"Не удается добавить специальный метод к уже имеющемуся подклассу классу" -#: extmod/modzlib.c -msgid "compression header" -msgstr "Заголовок сжатия" +#: py/objtype.c +msgid "type isn't an acceptable base type" +msgstr "Тип не является приемлемым базовым типом" -#: py/emitnative.c -msgid "conversion to object" -msgstr "Преобразование в объект" +#: py/objtype.c +msgid "type '%q' isn't an acceptable base type" +msgstr "Тип '%Q' не является допустимым базовым типом" -#: extmod/ulab/code/numpy/filter.c -msgid "convolve arguments must be linear arrays" -msgstr "Аргументы свертки должны быть линейными массивами" +#: py/objtype.c +msgid "multiple inheritance not supported" +msgstr "Множественное наследование не поддерживается" -#: extmod/ulab/code/numpy/filter.c -msgid "convolve arguments must be ndarrays" -msgstr "переплетение аргументов должно быть массивами ndarrays" +#: py/objtype.c +msgid "multiple bases have instance lay-out conflict" +msgstr "Несколько баз имеют конфликт расположения экземпляров" -#: extmod/ulab/code/numpy/filter.c -msgid "convolve arguments must not be empty" -msgstr "аргументы свертки не должны быть пустыми" +#: py/objtype.c +msgid "first argument to super() must be type" +msgstr "первый аргумент супер() должен быть типом" -#: extmod/ulab/code/numpy/io/io.c -msgid "corrupted file" -msgstr "Поврежденный файл" +#: py/objtype.c +msgid "issubclass() arg 2 must be a class or a tuple of classes" +msgstr "issubclass() arg 2 должен быть классом или кортежом классов" -#: extmod/ulab/code/numpy/poly.c -msgid "could not invert Vandermonde matrix" -msgstr "не удалось инвертировать матрицу Вандермонда" +#: py/objtype.c +msgid "issubclass() arg 1 must be a class" +msgstr "issubclass() arg 1 должен быть классом" -#: shared-module/sdcardio/SDCard.c -msgid "couldn't determine SD card version" -msgstr "Не удалось определить версию SD карты" +#: py/parse.c +msgid "not a constant" +msgstr "не константа" + +#: py/parse.c +msgid "Unable to init parser" +msgstr "Не удается инициировать синтаксический анализатор" -#: extmod/ulab/code/numpy/numerical.c -msgid "cross is defined for 1D arrays of length 3" -msgstr "крест определяется для 1D массивов длины 3" +#: py/parse.c +msgid "unexpected indent" +msgstr "Неожиданный отступ" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "data must be iterable" -msgstr "Данные должны быть итерируемыми" +#: py/parse.c +msgid "unindent doesn't match any outer indent level" +msgstr "Отступ не совпадает ни с одним уровнем внешнего отступа" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "data must be of equal length" -msgstr "Данные должны быть одинаковой длины" +#: py/parse.c +msgid "malformed f-string" +msgstr "Неправильно сформированная F-строка" -#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c +#: py/parsenum.c +msgid "invalid syntax for integer" +msgstr "недействительный синтаксис для целых чисел" + +#: py/parsenum.c #, c-format -msgid "data pin #%d in use" -msgstr "data-пин #%d уже используется" +msgid "invalid syntax for integer with base %d" +msgstr "недействительный синтаксис для целых чисел с основанием %d" -#: extmod/ulab/code/ndarray.c -msgid "data type not understood" -msgstr "Тип данных не понят" +#: py/parsenum.c +msgid "invalid syntax for number" +msgstr "недействительный синтаксис для номера" #: py/parsenum.c msgid "decimal numbers not supported" msgstr "Десятичные числа не поддерживаются" -#: py/compile.c -msgid "default 'except' must be last" -msgstr "по умолчанию \"за исключением\" должно быть последним" - -#: shared-bindings/msgpack/__init__.c -msgid "default is not a function" -msgstr "По умолчанию не является функцией" - -#: shared-bindings/audiobusio/PDMIn.c -msgid "" -"destination buffer must be a bytearray or array of type 'B' for bit_depth = 8" -msgstr "" -"буфер назначения должен быть байтоммассива или массивом типа \"B\" для " -"бит_глубины = 8" +#: py/persistentcode.c +msgid "incompatible .mpy file" +msgstr "несовместимый файл .mpy" -#: shared-bindings/audiobusio/PDMIn.c -msgid "destination buffer must be an array of type 'H' for bit_depth = 16" +#: py/persistentcode.c +msgid "MicroPython .mpy file; use CircuitPython mpy-cross" msgstr "" -"буфер назначения должен быть массивом типа «H» для битовой_глубины = 16" - -#: py/objdict.c -msgid "dict update sequence has wrong length" -msgstr "последовательность обновления дикта имеет неправильную длину" -#: extmod/ulab/code/numpy/numerical.c -msgid "diff argument must be an ndarray" -msgstr "аргумент DIFF должен быть массивом ndarray" +#: py/persistentcode.c +msgid "native code in .mpy unsupported" +msgstr "Нативный код в .mpy не поддерживается" -#: extmod/ulab/code/numpy/numerical.c -msgid "differentiation order out of range" -msgstr "Порядок дифференциации вне диапазона" +#: py/persistentcode.c +msgid "incompatible .mpy arch" +msgstr "несовместимые .mpy арка" -#: extmod/ulab/code/numpy/transform.c -msgid "dimensions do not match" -msgstr "Размеры не совпадают" +#: py/persistentcode.c +msgid "function must be bytecode" +msgstr "" -#: py/emitnative.c -msgid "div/mod not implemented for uint" -msgstr "div/mod не реализован для uint" +#: py/proto.c shared-bindings/digitalio/DigitalInOutProtocol.c +msgid "'%q' object does not support '%q'" +msgstr "Объект '%q' не поддерживает '%q'" -#: extmod/ulab/code/numpy/create.c -msgid "divide by zero" -msgstr "Делим на ноль" +#: py/qstr.c +msgid "name too long" +msgstr "слишком длинное имя" #: py/runtime.c -msgid "division by zero" -msgstr "Деление на ноль" - -#: extmod/ulab/code/numpy/vector.c -msgid "dtype must be float, or complex" -msgstr "Тип d должен быть плавающим или сложным" +msgid "name not defined" +msgstr "Имя не определено" -#: extmod/ulab/code/ndarray_operators.c -msgid "dtype of int32 is not supported" -msgstr "dtype int32 не поддерживается" +#: py/runtime.c +msgid "name '%q' isn't defined" +msgstr "Имя '%q' не определено" -#: py/objdeque.c -msgid "empty" -msgstr "пусто" +#: py/runtime.c +msgid "unsupported type for operator" +msgstr "Неподдерживаемый тип для оператора" -#: extmod/ulab/code/numpy/io/io.c -msgid "empty file" -msgstr "пустой файл" +#: py/runtime.c +msgid "unsupported type for %q: '%s'" +msgstr "неподдерживаемый тип для %q: '%s'" -#: extmod/modasyncio.c extmod/modheapq.c -msgid "empty heap" -msgstr "пустая куча" +#: py/runtime.c +msgid "unsupported types for %q: '%q', '%q'" +msgstr "Неподдерживаемые типы для %q: '%q', '%q'" -#: py/objstr.c -msgid "empty separator" -msgstr "пустой сепаратор" +#: py/runtime.c +msgid "wrong number of values to unpack" +msgstr "Неправильное количество значений для распаковки" -#: shared-bindings/random/__init__.c -msgid "empty sequence" -msgstr "пустая последовательность" +#: py/runtime.c +#, c-format +msgid "need more than %d values to unpack" +msgstr "Для распаковки требуется более значений %d" -#: py/objstr.c -msgid "end of format while looking for conversion specifier" -msgstr "конец формата при поиске спецификатора преобразования" +#: py/runtime.c +#, c-format +msgid "too many values to unpack (expected %d)" +msgstr "Слишком много значений для распаковки (ожидаемый %d)" -#: shared-bindings/alarm/time/TimeAlarm.c -msgid "epoch_time not supported on this board" -msgstr "epoch_time не поддерживается на этой плате" +#: py/runtime.c +msgid "type object '%q' has no attribute '%q'" +msgstr "тип объекта '%q' не имеет атрибута '%q \"" -#: ports/nordic/common-hal/busio/UART.c -#, c-format -msgid "error = 0x%08lX" -msgstr "ошибка = 0x%08lX" +#: py/runtime.c +msgid "module '%q' has no attribute '%q'" +msgstr "" #: py/runtime.c -msgid "exceptions must derive from BaseException" -msgstr "исключения должны быть производными от базового исключения" +msgid "'%s' object has no attribute '%q'" +msgstr "Объект '%s' не имеет атрибута '%q'" -#: py/objstr.c -msgid "expected ':' after format specifier" -msgstr "Ожидаемый ':' после спецификатора формата" +#: py/runtime.c +msgid "can't set attribute '%q'" +msgstr "Не удается установить атрибут '%q'" -#: py/obj.c -msgid "expected tuple/list" -msgstr "Ожидаемый кортеж/список" +#: py/runtime.c +msgid "object not iterable" +msgstr "Объект не итерируемый" -#: py/modthread.c -msgid "expecting a dict for keyword args" -msgstr "ожидание определения аргументов ключевых слов" +#: py/runtime.c +msgid "'%q' object isn't iterable" +msgstr "Объект '%q' не является итерируемым" -#: py/compile.c -msgid "expecting an assembler instruction" -msgstr "Ожидание инструкции ассемблера" +#: py/runtime.c +msgid "object not an iterator" +msgstr "объект не итератор" -#: py/compile.c -msgid "expecting just a value for set" -msgstr "ожидание только значения для набора" +#: py/runtime.c +msgid "'%q' object isn't an iterator" +msgstr "Объект '%q' не является итератором" -#: py/compile.c -msgid "expecting key:value for dict" -msgstr "ожидание ключа: значение для дикта" +#: py/runtime.c +msgid "exceptions must derive from BaseException" +msgstr "исключения должны быть производными от базового исключения" -#: shared-bindings/msgpack/__init__.c -msgid "ext_hook is not a function" -msgstr "ext_hook не является функцией" +#: py/runtime.c +msgid "can't import name %q" +msgstr "Невозможно импортировать имя %q" -#: py/argcheck.c -msgid "extra keyword arguments given" -msgstr "Приведены дополнительные аргументы ключевых слов" +#: py/runtime.c +msgid "memory allocation failed, heap is locked" +msgstr "Не удалось выделить память, куча заблокирована" -#: py/argcheck.c -msgid "extra positional arguments given" -msgstr "Приведены дополнительные позиционные аргументы" +#: py/runtime.c +#, c-format +msgid "memory allocation failed, allocating %u bytes" +msgstr "Сбой выделения памяти, выделение %u байт" -#: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/gifio/OnDiskGif.c -#: shared-bindings/synthio/__init__.c shared-module/gifio/GifWriter.c -msgid "file must be a file opened in byte mode" -msgstr "Файл должен быть файлом, открытым в байтовом режиме" +#: py/runtime.c +msgid "can't convert to int" +msgstr "Не удается преобразовать в int" -#: shared-bindings/traceback/__init__.c -msgid "file write is not available" -msgstr "Запись файлов недоступна" +#: py/runtime.c +msgid "division by zero" +msgstr "Деление на ноль" -#: shared-bindings/storage/__init__.c -msgid "filesystem must provide mount method" -msgstr "Файловая система должна предусматривать метод монтирования" +#: py/runtime.c +msgid "maximum recursion depth exceeded" +msgstr "Превышена максимальная глубина рекурсии" -#: extmod/ulab/code/numpy/vector.c -msgid "first argument must be a callable" -msgstr "Первый аргумент должен быть вызываемым" +#: py/sequence.c shared-bindings/displayio/Group.c +msgid "object not in sequence" +msgstr "объект не в последовательности" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "first argument must be a function" -msgstr "первый аргумент должен быть функцией" +#: py/stream.c shared-bindings/getpass/__init__.c +msgid "stream operation not supported" +msgstr "Потоковая операция не поддерживается" -#: extmod/ulab/code/numpy/create.c -msgid "first argument must be a tuple of ndarrays" -msgstr "Первый аргумент должен быть кортежом массива ndarrays" +#: py/vm.c +msgid "local variable referenced before assignment" +msgstr "локальная переменная, на которую ссылается перед присвоением" -#: extmod/ulab/code/numpy/transform.c extmod/ulab/code/numpy/vector.c -msgid "first argument must be an ndarray" -msgstr "Первым аргументом должен быть массивом ndarray" +#: py/vm.c +msgid "no active exception to reraise" +msgstr "Нет активного исключения для повторного создания" -#: py/objtype.c -msgid "first argument to super() must be type" -msgstr "первый аргумент супер() должен быть типом" +#: py/vm.c +msgid "opcode" +msgstr "код операции" -#: extmod/ulab/code/scipy/linalg/linalg.c -msgid "first two arguments must be ndarrays" -msgstr "Первые два аргумента должны быть массивами ndarrays" +#: shared-bindings/_bleio/Adapter.c +msgid "Cannot create a new Adapter; use _bleio.adapter;" +msgstr "Невозможно создать новый Adapter; используйте _bleio.adapter;" -#: extmod/ulab/code/ndarray.c -msgid "flattening order must be either 'C', or 'F'" -msgstr "порядок сглаживания должен быть либо 'C', либо 'F'" +#: shared-bindings/_bleio/Adapter.c +msgid "Could not set address" +msgstr "Не удалось задать адрес" -#: extmod/ulab/code/numpy/numerical.c -msgid "flip argument must be an ndarray" -msgstr "Флип -аргумент должен быть массивом ndarray" +#: shared-bindings/_bleio/Adapter.c +#, c-format +msgid "interval must be in range %s-%s" +msgstr "Интервал должен находиться в диапазоне %s-%s" -#: py/objint.c -msgid "float too big" -msgstr "Поплавок слишком большой" +#: shared-bindings/_bleio/Adapter.c +msgid "Cannot have scan responses for extended, connectable advertisements." +msgstr "" +"Не может быть ответов на сканирование для расширенных подключаемых рекламных " +"объявлений." -#: py/nativeglue.c -msgid "float unsupported" -msgstr "Плавающий без поддержки" +#: shared-bindings/_bleio/Adapter.c +msgid "Only connectable advertisements can be directed" +msgstr "Только подключаемые объявления могут быть направлены" -#: shared-bindings/_stage/Text.c -msgid "font must be 2048 bytes long" -msgstr "Длина шрифта должна составлять 2048 байт" +#: shared-bindings/_bleio/Adapter.c +msgid "non-zero timeout must be >= interval" +msgstr "Ненулевое время ожидания должно быть >= интервал" -#: extmod/moddeflate.c -msgid "format" -msgstr "формат" +#: shared-bindings/_bleio/Adapter.c +msgid "window must be <= interval" +msgstr "окно должно быть <= интервал" -#: py/objstr.c -msgid "format requires a dict" -msgstr "Формат требует диктата" +#: shared-bindings/_bleio/Adapter.c +msgid "Prefix buffer must be on the heap" +msgstr "Буфер префикса должен находиться в куче" -#: py/objdeque.c -msgid "full" -msgstr "полный" +#: shared-bindings/_bleio/CharacteristicBuffer.c +msgid "CharacteristicBuffer writing not provided" +msgstr "ХарактеристикаЗапись в буфер не предусмотрена" -#: py/argcheck.c -msgid "function doesn't take keyword arguments" -msgstr "функция не принимает аргументы ключевых слов" +#: shared-bindings/_bleio/Connection.c +msgid "" +"Connection has been disconnected and can no longer be used. Create a new " +"connection." +msgstr "" +"Соединение было отключено и больше не может использоваться. Создайте новое " +"соединение." -#: py/argcheck.c +#: shared-bindings/_bleio/PacketBuffer.c #, c-format -msgid "function expected at most %d arguments, got %d" -msgstr "функция, ожидаемая в большинстве %d аргументов, получила %d" +msgid "Buffer too short by %d bytes" +msgstr "Буфер слишком короткий на %d байт" -#: py/bc.c py/objnamedtuple.c -msgid "function got multiple values for argument '%q'" -msgstr "функция имеет несколько значений для аргументации%q \"" +#: shared-bindings/_bleio/PacketBuffer.c +msgid "No connection: length cannot be determined" +msgstr "Нет соединения: длина не может быть определена" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "function has the same sign at the ends of interval" -msgstr "функция имеет один и тот же знак в конце интервала" +#: shared-bindings/_bleio/UUID.c +msgid "UUID string not 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'" +msgstr "UUID строка не 'xxxxxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxxxxxxxxxx \"" -#: extmod/ulab/code/ndarray.c -msgid "function is defined for ndarrays only" -msgstr "Функция определяется только для массивов ndarrays" +#: shared-bindings/_bleio/UUID.c +msgid "UUID value is not str, int or byte buffer" +msgstr "Значение UUID не является строковым, целым или байтовым буфером" -#: extmod/ulab/code/numpy/carray/carray.c -msgid "function is implemented for ndarrays only" -msgstr "Функция реализована только для массивов ndarrays" +#: shared-bindings/_bleio/UUID.c +msgid "not a 128-bit UUID" +msgstr "не 128-битный UUID" -#: py/argcheck.c -#, c-format -msgid "function missing %d required positional arguments" -msgstr "Функция отсутствует %d обязательные позиционные аргументы" +#: shared-bindings/_bleio/__init__.c shared-bindings/emmcio/EMMC.c +#: shared-bindings/memorymonitor/AllocationSize.c +#: shared-bindings/pulseio/PulseIn.c shared-module/bitmaptools/__init__.c +#: shared-module/displayio/legacy/Bitmap.c +#: shared-module/displayio/legacy/Group.c shared-module/displayio/lvgl/Bitmap.c +#: shared-module/displayio/lvgl/Group.c +msgid "Read-only" +msgstr "Только для чтения" -#: py/bc.c -msgid "function missing keyword-only argument" -msgstr "функция отсутствует аргумент только по ключевому слову" +#: shared-bindings/_pew/PewPew.c +msgid "Incorrect buffer size" +msgstr "Неправильный размер буфера" -#: py/bc.c -msgid "function missing required keyword argument '%q'" -msgstr "В функции отсутствует обязательный аргумент ключевого слова '%q'" +#: shared-bindings/_pixelmap/PixelMap.c +msgid "nested index must be int" +msgstr "вложенный индекс должен быть int" -#: py/bc.c -#, c-format -msgid "function missing required positional argument #%d" -msgstr "В функции отсутствует обязательный позиционный аргумент #%d" +#: shared-bindings/_pixelmap/PixelMap.c +msgid "index must be tuple or int" +msgstr "Индекс должен быть кортежом или целым кортежом" -#: py/argcheck.c py/bc.c py/objnamedtuple.c shared-bindings/_eve/__init__.c -#: shared-bindings/time/__init__.c -#, c-format -msgid "function takes %d positional arguments but %d were given" -msgstr "функция принимает %d позиционные аргументы, но %d были заданы" +#: shared-bindings/_stage/Layer.c +msgid "map buffer too small" +msgstr "Слишком маленький буфер карты" -#: py/objgenerator.c -msgid "generator already executing" -msgstr "генератор уже работает" +#: shared-bindings/_stage/Text.c +msgid "chars buffer too small" +msgstr "Слишком маленький буфер символов" -#: py/objgenerator.c -msgid "generator ignored GeneratorExit" -msgstr "генератор проигнорировал Выход" +#: shared-bindings/adafruit_bus_device/spi_device/SPIDevice.c +msgid "Pin is input only" +msgstr "Пин является только входом" -#: py/objgenerator.c py/runtime.c -msgid "generator raised StopIteration" -msgstr "генератор поднят Остановить итерацию" +#: shared-bindings/adafruit_pixelbuf/PixelBuf.c +#: shared-module/_pixelmap/PixelMap.c +#, c-format +msgid "Unmatched number of items on RHS (expected %d, got %d)." +msgstr "" +"Непревзойденное количество элементов на RHS (ожидалось %d, получено %d)." -#: shared-bindings/_stage/Layer.c -msgid "graphic must be 2048 bytes long" -msgstr "Длина рисунка должна составлять 2048 байт" +#: shared-bindings/aesio/aes.c +msgid "Key must be 16, 24, or 32 bytes long" +msgstr "Ключ должен быть длинной 16, 24 или 32 байта" -#: extmod/modhashlib.c -msgid "hash is final" -msgstr "хэш является окончательным" +#: shared-bindings/aesio/aes.c +msgid "Requested AES mode is unsupported" +msgstr "Запрошенный режим AES не поддерживается" -#: extmod/modheapq.c -msgid "heap must be a list" -msgstr "куча должна быть списком" +#: shared-bindings/aesio/aes.c +msgid "Source and destination buffers must be the same length" +msgstr "Исходный и конечный буферы должны иметь одинаковую длину" -#: py/compile.c -msgid "identifier redefined as global" -msgstr "идентификатор переопределен как глобальный" +#: shared-bindings/aesio/aes.c +msgid "ECB only operates on 16 bytes at a time" +msgstr "ECB работает только с 16 байтами за раз" -#: py/compile.c -msgid "identifier redefined as nonlocal" -msgstr "идентификатор переопределен как нелокальный" +#: shared-bindings/aesio/aes.c +msgid "CBC blocks must be multiples of 16 bytes" +msgstr "Блоки CBC должны быть кратны 16 байтам" -#: py/compile.c -msgid "import * not at module level" -msgstr "Импорт * не на уровне модуля" +#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c +#: shared-bindings/nvm/ByteArray.c +msgid "Slice and value different lengths." +msgstr "Нарежьте и оцените разную длину." -#: py/persistentcode.c -msgid "incompatible .mpy arch" -msgstr "несовместимые .mpy арка" +#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c +#: shared-bindings/nvm/ByteArray.c +msgid "Array values should be single bytes." +msgstr "Значения массива должны быть однобайтовыми." -#: py/persistentcode.c -msgid "incompatible .mpy file" -msgstr "несовместимый файл .mpy" +#: shared-bindings/alarm/SleepMemory.c +msgid "Unable to write to sleep_memory." +msgstr "Невозможно записать в Sleep_memory." -#: py/objstr.c -msgid "incomplete format" -msgstr "Неполный формат" +#: shared-bindings/alarm/__init__.c +msgid "Expected a kind of %q" +msgstr "Ожидаемый вид %q" -#: py/objstr.c -msgid "incomplete format key" -msgstr "Неполный ключ форматирования" +#: shared-bindings/alarm/time/TimeAlarm.c shared-bindings/time/__init__.c +msgid "RTC is not supported on this board" +msgstr "RTC не поддерживается на этой плате" -#: extmod/modbinascii.c -msgid "incorrect padding" -msgstr "Неправильная набивка" +#: shared-bindings/alarm/time/TimeAlarm.c +msgid "Supply one of monotonic_time or epoch_time" +msgstr "Поставьте один из monotonic_time или epoch_time" -#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/transform.c -msgid "index is out of bounds" -msgstr "индекс выходит из границ" +#: shared-bindings/alarm/time/TimeAlarm.c +msgid "epoch_time not supported on this board" +msgstr "epoch_time не поддерживается на этой плате" -#: shared-bindings/_pixelmap/PixelMap.c -msgid "index must be tuple or int" -msgstr "Индекс должен быть кортежом или целым кортежом" +#: shared-bindings/alarm/time/TimeAlarm.c +msgid "Time is in the past." +msgstr "Время в прошлом." -#: extmod/ulab/code/numpy/numerical.c extmod/ulab/code/ulab_tools.c -#: ports/espressif/common-hal/pulseio/PulseIn.c -#: shared-bindings/bitmaptools/__init__.c -msgid "index out of range" -msgstr "индекс вне диапазона" +#: shared-bindings/analogbufio/BufferedIn.c +msgid "%q must be a bytearray or array of type 'H' or 'B'" +msgstr "%q должен быть массивом байтов или массивом типа «H» или «B»" -#: py/obj.c -msgid "indices must be integers" -msgstr "индексы должны быть целыми числами" +#: shared-bindings/audiobusio/PDMIn.c +msgid "%q must be multiple of 8." +msgstr "%q должно быть кратно 8." -#: extmod/ulab/code/ndarray.c -msgid "indices must be integers, slices, or Boolean lists" -msgstr "индексы должны быть целыми числами, срезами или логическими списками" +#: shared-bindings/audiobusio/PDMIn.c shared-bindings/audioi2sin/I2SIn.c +#: shared-bindings/usb_host_audio/USBIn.c +msgid "Cannot record to a file" +msgstr "Невозможно записать в файл" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "initial values must be iterable" -msgstr "Начальные значения должны быть итерируемыми" +#: shared-bindings/audiobusio/PDMIn.c shared-bindings/audioi2sin/I2SIn.c +#: shared-bindings/usb_host_audio/USBIn.c +msgid "Destination capacity is smaller than destination_length." +msgstr "Емкость места назначения меньше длины места назначения." + +#: shared-bindings/audiobusio/PDMIn.c +msgid "destination buffer must be an array of type 'H' for bit_depth = 16" +msgstr "" +"буфер назначения должен быть массивом типа «H» для битовой_глубины = 16" -#: shared-bindings/_bleio/Characteristic.c shared-bindings/_bleio/Descriptor.c -msgid "initial_value length is wrong" -msgstr "длина первоначального_значения ошибочна" +#: shared-bindings/audiobusio/PDMIn.c +msgid "" +"destination buffer must be a bytearray or array of type 'B' for bit_depth = 8" +msgstr "" +"буфер назначения должен быть байтоммассива или массивом типа \"B\" для " +"бит_глубины = 8" -#: py/compile.c -msgid "inline assembler must be a function" -msgstr "Встроенный ассемблер должен быть функцией" +#: shared-bindings/audiocore/RawSample.c +msgid "%q must be a bytearray or array of type 'h', 'H', 'b', or 'B'" +msgstr "%q должен быть массивом байтов или массивом типа «h», «H», «b» или «B»" -#: extmod/ulab/code/numpy/vector.c -msgid "input and output dimensions differ" -msgstr "Входные и выходные размеры различаются" +#: shared-bindings/audiocore/RawSample.c +msgid "Length of %q must be an even multiple of channel_count * type_size" +msgstr "Длина %q должна быть четной, кратной количеству каналов * размер_типа" -#: extmod/ulab/code/numpy/vector.c -msgid "input and output shapes differ" -msgstr "Входные и выходные формы различаются" +#: shared-bindings/audiodelays/Chorus.c shared-bindings/audiodelays/Echo.c +#: shared-bindings/audiodelays/Flanger.c +#: shared-bindings/audiodelays/GranularPitchShift.c +#: shared-bindings/audiodelays/MultiTapDelay.c +#: shared-bindings/audiodelays/PitchShift.c +#: shared-bindings/audiofilters/Distortion.c +#: shared-bindings/audiofilters/Filter.c shared-bindings/audiofilters/Phaser.c +#: shared-bindings/audiomixer/Mixer.c shared-module/audiotap/Tap.c +msgid "bits_per_sample must be 8 or 16" +msgstr "bits_per_sample должно быть 8 или 16" -#: extmod/ulab/code/numpy/create.c -msgid "input argument must be an integer, a tuple, or a list" -msgstr "Входной аргумент должен быть целым числом, кортежом или списком" +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "samples_signed must be true" +msgstr "" -#: extmod/ulab/code/numpy/fft/fft_tools.c -msgid "input array length must be power of 2" -msgstr "Длина входного массива должна быть равна степени 2" +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "bits_per_sample must be 16" +msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "input arrays are not compatible" -msgstr "Входные массивы несовместимы" +#: shared-bindings/audioi2sin/I2SIn.c shared-bindings/usb_host_audio/USBIn.c +#, c-format +msgid "invalid destination buffer, must be an array of type: %c" +msgstr "" -#: extmod/ulab/code/numpy/poly.c -msgid "input data must be an iterable" -msgstr "Входные данные должны быть итерируемыми" +#: shared-bindings/audioio/AudioOut.c shared-bindings/emmcio/EMMC.c +msgid "%q and %q must be different" +msgstr "%q и %q должны быть разными" -#: extmod/ulab/code/numpy/vector.c -msgid "input dtype must be float or complex" -msgstr "Входной тип dtype должен быть плавающим или сложным" +#: shared-bindings/audiomp3/MP3Decoder.c shared-bindings/gifio/OnDiskGif.c +#: shared-bindings/synthio/__init__.c shared-module/gifio/GifWriter.c +msgid "file must be a file opened in byte mode" +msgstr "Файл должен быть файлом, открытым в байтовом режиме" -#: extmod/ulab/code/numpy/poly.c -msgid "input is not iterable" -msgstr "Ввод не является итерируемым" +#: shared-bindings/bitmapfilter/__init__.c +msgid "" +"weights must be a sequence with an odd square number of elements (usually 9 " +"or 25)" +msgstr "" +"Весом должна быть последовательность с нечетным квадратным числом элементов " +"(обычно 9 или 25)" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "input matrix is asymmetric" -msgstr "Входная матрица асимметрична" +#: shared-bindings/bitmapfilter/__init__.c +msgid "weights must be an object of type %q, %q, %q, or %q, not %q " +msgstr "Веса должны быть объектом типа %q, %q, %q или %q, а не %q " -#: extmod/ulab/code/numpy/linalg/linalg.c -#: extmod/ulab/code/scipy/linalg/linalg.c -msgid "input matrix is singular" -msgstr "Входная матрица является сингулярной" +#: shared-bindings/bitmaptools/__init__.c +msgid "clip point must be (x,y) tuple" +msgstr "Точка клипа должна быть кортежом (x,y)" -#: extmod/ulab/code/numpy/create.c -msgid "input must be 1- or 2-d" -msgstr "Вход должен быть 1- или 2-D" +#: shared-bindings/bitmaptools/__init__.c +msgid "source palette too large" +msgstr "Исходная палитра слишком велика" -#: extmod/ulab/code/numpy/carray/carray.c -msgid "input must be a 1D ndarray" -msgstr "Ввод должен быть 1D массивом ndarray" +#: shared-bindings/bitmaptools/__init__.c +msgid "Bitmap size and bits per value must match" +msgstr "" +"Размер растрового изображения и число битов на значение должны совпадать" -#: extmod/ulab/code/scipy/linalg/linalg.c extmod/ulab/code/user/user.c -msgid "input must be a dense ndarray" -msgstr "Ввод должен быть плотным массивом ndarray" +#: shared-bindings/bitmaptools/__init__.c +msgid "For L8 colorspace, input bitmap must have 8 bits per pixel" +msgstr "" +"Для цветового пространства L8 входное растровое изображение должно иметь 8 " +"бит на пиксель" -#: extmod/ulab/code/user/user.c shared-bindings/_eve/__init__.c -msgid "input must be an ndarray" -msgstr "Ввод должен быть массивом ndarray" +#: shared-bindings/bitmaptools/__init__.c +msgid "For RGB colorspaces, input bitmap must have 16 bits per pixel" +msgstr "" +"Для цветовых пространств RGB входное растровое изображение должно иметь 16 " +"бит на пиксель" -#: extmod/ulab/code/numpy/carray/carray.c -msgid "input must be an ndarray, or a scalar" -msgstr "Ввод должен быть массивом ndarray или скаляр" +#: shared-bindings/bitmaptools/__init__.c +msgid "Unsupported colorspace" +msgstr "Неподдерживаемое цветовое пространство" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "input must be one-dimensional" -msgstr "Входные данные должны быть одномерными" +#: shared-bindings/bitmaptools/__init__.c +msgid "Mask bitmap size must match the other bitmaps" +msgstr "" -#: extmod/ulab/code/ulab_tools.c -msgid "input must be square matrix" -msgstr "Входные данные должны быть квадратной матрицей" +#: shared-bindings/bitmaptools/__init__.c +msgid "Mask bitmap must have 8 bits per pixel" +msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "input must be tuple, list, range, or ndarray" -msgstr "Ввод должен быть кортеж, список, диапазон или массивом ndarray" +#: shared-bindings/bitmaptools/__init__.c +msgid "out of range of target" +msgstr "вне досягаемости цели" -#: extmod/ulab/code/numpy/poly.c -msgid "input vectors must be of equal length" -msgstr "Входные векторы должны быть одинаковой длины" +#: shared-bindings/bitmaptools/__init__.c +msgid "value out of range of target" +msgstr "Величина выходящая за пределы диапазона цели" -#: extmod/ulab/code/numpy/approx.c -msgid "interp is defined for 1D iterables of equal length" -msgstr "interp определен для 1D-итераций одинаковой длины" +#: shared-bindings/bitmaptools/__init__.c +msgid "background value out of range of target" +msgstr "Фоновое значение вне диапазона цели" -#: shared-bindings/_bleio/Adapter.c -#, c-format -msgid "interval must be in range %s-%s" -msgstr "Интервал должен находиться в диапазоне %s-%s" +#: shared-bindings/bitmaptools/__init__.c +msgid "Coordinate arrays types have different sizes" +msgstr "Типы массивов координат имеют разные размеры" -#: py/compile.c -msgid "invalid arch" -msgstr "недействительная арка" +#: shared-bindings/bitmaptools/__init__.c +msgid "Coordinate arrays have different lengths" +msgstr "Координатные массивы имеют разные длины" #: shared-bindings/bitmaptools/__init__.c #, c-format -msgid "invalid bits_per_pixel %d, must be, 1, 2, 4, 8, 16, 24, or 32" -msgstr "неверный бит_на_пиксель %d, должно быть 1, 2, 4, 8, 16, 24 или 32" - -#: shared-module/ssl/SSLSocket.c -msgid "invalid cert" -msgstr "Неверный сертификат" +msgid "invalid element_size %d, must be, 1, 2, or 4" +msgstr "аннулированный элемент_размер %d, должен быть, 1, 2 или 4" #: shared-bindings/bitmaptools/__init__.c #, c-format @@ -3450,1074 +4220,1103 @@ msgstr "недопустимый размер элемента %d для бит #: shared-bindings/bitmaptools/__init__.c #, c-format -msgid "invalid element_size %d, must be, 1, 2, or 4" -msgstr "аннулированный элемент_размер %d, должен быть, 1, 2 или 4" - -#: shared-bindings/traceback/__init__.c -msgid "invalid exception" -msgstr "Недопустимое исключение" - -#: py/objstr.c -msgid "invalid format specifier" -msgstr "Недопустимый спецификатор формата" +msgid "invalid bits_per_pixel %d, must be, 1, 2, 4, 8, 16, 24, or 32" +msgstr "неверный бит_на_пиксель %d, должно быть 1, 2, 4, 8, 16, 24 или 32" -#: shared-bindings/wifi/Radio.c -msgid "invalid hostname" -msgstr "Недопустимое имя хоста" +#: shared-bindings/bitmaptools/__init__.c +msgid "bitmap sizes must match" +msgstr "Размеры растровых изображений должны совпадать" -#: shared-module/ssl/SSLSocket.c -msgid "invalid key" -msgstr "Неверный ключ" +#: shared-bindings/bitmaptools/__init__.c +msgid "source_bitmap must have value_count of 2 or 65536" +msgstr "source_bitmap должен иметь значение_счет 2 или 65536" -#: py/compile.c -msgid "invalid micropython decorator" -msgstr "неверный декоратор микропитона" +#: shared-bindings/bitmaptools/__init__.c +msgid "source_bitmap must have value_count of 65536" +msgstr "source_bitmap должен иметь значение_счет 65536" -#: ports/espressif/common-hal/espcamera/Camera.c -msgid "invalid setting" -msgstr "Недопустимый параметр" +#: shared-bindings/bitmaptools/__init__.c +msgid "source_bitmap must have value_count of 8" +msgstr "source_bitmap должен иметь значение_счет 8" -#: shared-bindings/random/__init__.c -msgid "invalid step" -msgstr "недействительный шаг" +#: shared-bindings/bitmaptools/__init__.c +msgid "unsupported colorspace for dither" +msgstr "Неподдерживаемое цветовое пространство для дизеринга" -#: py/compile.c py/parse.c -msgid "invalid syntax" -msgstr "недействительный синтаксис" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Input buffer length (%d) must be a multiple of the strand count (%d)" +msgstr "Длина входного буфера (%d) должна быть кратна количеству цепочек (%d)" -#: py/parsenum.c -msgid "invalid syntax for integer" -msgstr "недействительный синтаксис для целых чисел" +#: shared-bindings/board/__init__.c +msgid "No default %q bus" +msgstr "Нет шины %q по умолчанию" -#: py/parsenum.c -#, c-format -msgid "invalid syntax for integer with base %d" -msgstr "недействительный синтаксис для целых чисел с основанием %d" +#: shared-bindings/busdisplay/BusDisplay.c +msgid "%q must be 1 when %q is True" +msgstr "%q должен быть равен 1, если %q имеет значение True" -#: py/parsenum.c -msgid "invalid syntax for number" -msgstr "недействительный синтаксис для номера" +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +msgid "Display must have a 16 bit colorspace." +msgstr "Дисплей должен иметь 16 битное цветовое пространство." -#: py/objtype.c -msgid "issubclass() arg 1 must be a class" -msgstr "issubclass() arg 1 должен быть классом" +#: shared-bindings/busio/UART.c shared-bindings/canio/CAN.c +msgid "tx and rx cannot both be None" +msgstr "tx и rx не могут быть одновременно None" -#: py/objtype.c -msgid "issubclass() arg 2 must be a class or a tuple of classes" -msgstr "issubclass() arg 2 должен быть классом или кортежом классов" +#: shared-bindings/busio/UART.c shared-bindings/displayio/Group.c +msgid "Must be a %q subclass." +msgstr "Должен быть субклассом %q." -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "iterations did not converge" -msgstr "итерации не сходятся" +#: shared-bindings/canio/RemoteTransmissionRequest.c +msgid "RemoteTransmissionRequests limited to 8 bytes" +msgstr "Запросы на удаленную передачу ограничены 8 байтами" -#: py/objstr.c -msgid "join expects a list of str/bytes objects consistent with self object" +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/ec/EllipticCurvePublicKey.c +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/padding/__init__.c +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "Only %q supported" msgstr "" -"присоединяйтесь к ожидающему список стр/байт объектов, совместимых с " -"самообъектом" -#: py/argcheck.c -msgid "keyword argument(s) not implemented - use normal args instead" +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/padding/__init__.c +msgid "label is not supported" msgstr "" -"Аргумент(ы) ключевого слова не реализован - используйте вместо него обычные " -"аргументы" - -#: py/emitinlinethumb.c py/emitinlinextensa.c -msgid "label '%q' not defined" -msgstr "Метка '%q' не определена" -#: py/compile.c -msgid "label redefined" -msgstr "Метка переопределена" +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/rsa/__init__.c +#: shared-bindings/hmac/__init__.c +msgid "key does not have the expected %q purpose" +msgstr "" -#: py/objarray.c -msgid "lhs and rhs should be compatible" -msgstr "lhs и rhs должны быть совместимыми" +#: shared-bindings/digitalio/DigitalInOut.c +#: shared-bindings/i2cioexpander/IOPin.c +msgid "Cannot set value when direction is input." +msgstr "Невозможно установить значение при вводе направления." -#: py/emitnative.c -msgid "local '%q' has type '%q' but source is '%q'" -msgstr "Локальный '%q' имеет тип '%q', но источник '%q'" +#: shared-bindings/digitalio/DigitalInOut.c +#: shared-bindings/i2cioexpander/IOPin.c +msgid "Drive mode not used when direction is input." +msgstr "Режим движения не используется при вводе направления." -#: py/emitnative.c -msgid "local '%q' used before type known" -msgstr "местный '%q' используется перед типом" +#: shared-bindings/digitalio/DigitalInOut.c +#: shared-bindings/i2cioexpander/IOPin.c +msgid "Pull not used when direction is output." +msgstr "Тяга не используется, когда выводится направление." -#: py/vm.c -msgid "local variable referenced before assignment" -msgstr "локальная переменная, на которую ссылается перед присвоением" +#: shared-bindings/digitalio/DigitalInOutProtocol.c +msgid "%q object missing '%q' method" +msgstr "" -#: ports/espressif/common-hal/canio/CAN.c -msgid "loopback + silent mode not supported by peripheral" +#: shared-bindings/digitalio/DigitalInOutProtocol.c +msgid "%q object missing '%q' attribute" msgstr "" -"Замыкание на себя + бесшумный режим, не поддерживаемый периферийными " -"устройствами" -#: ports/espressif/common-hal/mdns/Server.c -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "mDNS already initialized" -msgstr "mDNS уже инициализирован" +#: shared-bindings/digitalio/DigitalInOutProtocol.c +msgid "object does not support DigitalInOut protocol" +msgstr "" -#: ports/espressif/common-hal/mdns/Server.c -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "mDNS only works with built-in WiFi" -msgstr "mDNS работает только со встроенным WiFi" +#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/memorymonitor/AllocationSize.c +#: shared-bindings/pulseio/PulseIn.c +msgid "Cannot delete values" +msgstr "Невозможно удалить значения" -#: py/parse.c -msgid "malformed f-string" -msgstr "Неправильно сформированная F-строка" +#: 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 +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +msgid "Slices not supported" +msgstr "Фрагменты не поддерживаются" -#: shared-bindings/_stage/Layer.c -msgid "map buffer too small" -msgstr "Слишком маленький буфер карты" +#: shared-bindings/displayio/Palette.c +msgid "color buffer must be a bytearray or array of type 'b' or 'B'" +msgstr "" +"цветовой буфер должен быть байтом массива или массивом типа \"b\" или \"B\"" -#: py/modmath.c shared-bindings/math/__init__.c -msgid "math domain error" -msgstr "Ошибка математической области" +#: shared-bindings/displayio/Palette.c +msgid "color buffer must be 3 bytes (RGB) or 4 bytes (RGB + pad byte)" +msgstr "" +"Цветовой буфер должен иметь размер 3 байта (RGB) или 4 байта (RGB + байт " +"заполнения)" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "matrix is not positive definite" -msgstr "матрица не является положительно определенной" +#: shared-bindings/displayio/Palette.c +msgid "color must be between 0x000000 and 0xffffff" +msgstr "Цвет должен быть от 0x000000 до 0xffffff" -#: ports/espressif/common-hal/_bleio/Descriptor.c -#: ports/nordic/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Descriptor.c -#, c-format -msgid "max_length must be 0-%d when fixed_length is %s" -msgstr "максимальная_длина должна быть 0-%d когда фиксированная длина %s" +#: shared-bindings/displayio/Palette.c +msgid "color buffer must be a buffer, tuple, list, or int" +msgstr "Цветовой буфер должен быть буфером, кортежом, списком или целым числом" -#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/random/random.c -msgid "maximum number of dimensions is " -msgstr "Максимальное количество измерений составляет " +#: shared-bindings/displayio/TileGrid.c +msgid "Tile width must exactly divide bitmap width" +msgstr "Ширина плитки должна точно делить ширину растрового изображения" -#: py/runtime.c -msgid "maximum recursion depth exceeded" -msgstr "Превышена максимальная глубина рекурсии" +#: shared-bindings/displayio/TileGrid.c +msgid "Tile height must exactly divide bitmap height" +msgstr "Высота плитки должна точно делить высоту растрового изображения" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "maxiter must be > 0" -msgstr "maxiter должен быть > 0" +#: shared-bindings/displayio/TileGrid.c +msgid "New bitmap must be same size as old bitmap" +msgstr "" +"Новое растровое изображение должно быть того же размера, что и старое " +"растровое изображение" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "maxiter should be > 0" -msgstr "макситер должен быть > 0" +#: shared-bindings/displayio/TileGrid.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-module/displayio/legacy/TileGrid.c +#: shared-module/displayio/lvgl/TileGrid.c +msgid "Tile index out of bounds" +msgstr "Выход индекса плитки за пределы" -#: extmod/ulab/code/numpy/numerical.c -msgid "median argument must be an ndarray" -msgstr "Средний аргумент должен быть массивом ndarray" +#: shared-bindings/dualbank/__init__.c +msgid "offset must be >= 0" +msgstr "Смещение должно быть >= 0" -#: py/runtime.c -#, c-format -msgid "memory allocation failed, allocating %u bytes" -msgstr "Сбой выделения памяти, выделение %u байт" +#: shared-bindings/emmcio/EMMC.c shared-bindings/i2cioexpander/IOExpander.c +msgid "address out of range" +msgstr "" -#: py/runtime.c -msgid "memory allocation failed, heap is locked" -msgstr "Не удалось выделить память, куча заблокирована" +#: shared-bindings/epaperdisplay/EPaperDisplay.c +msgid "Refresh too soon" +msgstr "Слишком раннее обновление" -#: py/objarray.c -msgid "memoryview offset too large" -msgstr "Слишком большое смещение просмотра памяти" +#: shared-bindings/framebufferio/FramebufferDisplay.c +msgid "Buffer is not a bytearray." +msgstr "Буфер не является байтовым массивом." -#: py/objarray.c -msgid "memoryview: length is not a multiple of itemsize" -msgstr "вид памяти: длина не является множеством элементов" +#: shared-bindings/gnss/GNSS.c +msgid "System entry must be gnss.SatelliteSystem" +msgstr "Системная запись должна быть gnss. Спутниковая система" -#: extmod/modtime.c -msgid "mktime needs a tuple of length 8 or 9" -msgstr "mktime нужен кортеж длины 8 или 9" +#: shared-bindings/hashlib/__init__.c shared-bindings/hmac/__init__.c +msgid "Unsupported hash algorithm" +msgstr "Неподдерживаемый алгоритм хеширования" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "mode must be complete, or reduced" -msgstr "Режим должен быть завершенным или уменьшенным" +#: shared-bindings/i2cioexpander/IOExpander.c +msgid "num_pins must be 8 or 16" +msgstr "" -#: py/builtinimport.c -msgid "module not found" -msgstr "модуль не найден" +#: shared-bindings/i2ctarget/I2CTarget.c +msgid "addresses is empty" +msgstr "адреса пусты" -#: ports/espressif/common-hal/wifi/Monitor.c -msgid "monitor init failed" -msgstr "Сбой инициализации монитора" +#: shared-bindings/ipaddress/IPv4Address.c shared-bindings/ipaddress/__init__.c +msgid "Not a valid IP string" +msgstr "Недействительная строка IP" -#: extmod/ulab/code/numpy/poly.c -msgid "more degrees of freedom than data points" -msgstr "Больше степеней свободы чем точек данных" +#: shared-bindings/ipaddress/IPv4Address.c +#, c-format +msgid "Address must be %d bytes long" +msgstr "Адрес должен быть длиной %d байт" -#: py/compile.c -msgid "multiple *x in assignment" -msgstr "Несколько *x в назначении" +#: shared-bindings/ipaddress/__init__.c +msgid "Only int or string supported for ip" +msgstr "Для IP поддерживаются только int или строка" -#: py/objtype.c -msgid "multiple bases have instance lay-out conflict" -msgstr "Несколько баз имеют конфликт расположения экземпляров" +#: shared-bindings/is31fl3741/FrameBuffer.c +msgid "width must be greater than zero" +msgstr "ширина должна быть больше нуля" -#: py/objtype.c -msgid "multiple inheritance not supported" -msgstr "Множественное наследование не поддерживается" +#: shared-bindings/is31fl3741/FrameBuffer.c +msgid "Scale dimensions must divide by 3" +msgstr "Размеры шкалы необходимо разделить на 3" -#: py/emitnative.c -msgid "must raise an object" -msgstr "должен поднять объект" +#: shared-bindings/is31fl3741/FrameBuffer.c +msgid "LED mappings must match display size" +msgstr "Светодиодные сопоставления должны соответствовать размеру дисплея" -#: py/modbuiltins.c -msgid "must use keyword argument for key function" -msgstr "Необходимо использовать аргумент ключевого слова для ключевой функции" +#: shared-bindings/is31fl3741/IS31FL3741.c +msgid "Mapping must be a tuple" +msgstr "Сопоставление должно быть кортежом" -#: py/runtime.c -msgid "name '%q' is not defined" -msgstr "Имя '%q' не определено" +#: shared-bindings/jpegio/JpegDecoder.c +msgid "%q must be of type %q, %q, or %q, not %q" +msgstr "%q должен иметь тип %q, %q или %q, а не %q" -#: py/runtime.c -msgid "name not defined" -msgstr "Имя не определено" +#: shared-bindings/mdns/Server.c +msgid "" +"Failed to add service TXT record; non-string or bytes found in txt_records" +msgstr "" +"Не удалось добавить служебную TXT-запись; в txt_records обнаружена нестрока " +"или байт" -#: py/qstr.c -msgid "name too long" -msgstr "слишком длинное имя" +#: shared-bindings/memorymap/AddressRange.c +msgid "Address range wraps around" +msgstr "Обертывание диапазона адресов" -#: py/persistentcode.c -msgid "native code in .mpy unsupported" -msgstr "Нативный код в .mpy не поддерживается" +#: shared-bindings/microcontroller/Pin.c +msgid "%q contains duplicate pins" +msgstr "%q содержит пины дупликаты" -#: py/asmthumb.c -msgid "native method too big" -msgstr "родной метод слишком большой" +#: shared-bindings/microcontroller/Pin.c +msgid "%q and %q contain duplicate pins" +msgstr "%q и %q содержат пины дупликаты" -#: py/emitnative.c -msgid "native yield" -msgstr "родной урожай" +#: shared-bindings/mii/Ethernet.c shared-bindings/wifi/Radio.c +msgid "invalid hostname" +msgstr "Недопустимое имя хоста" -#: extmod/ulab/code/ndarray.c -msgid "ndarray length overflows" -msgstr "Переполнение длины массива ndarray" +#: shared-bindings/msgpack/ExtType.c +msgid "code outside range 0~127" +msgstr "код вне диапазона 0~127" -#: py/runtime.c -#, c-format -msgid "need more than %d values to unpack" -msgstr "Для распаковки требуется более значений %d" +#: shared-bindings/msgpack/__init__.c +msgid "default is not a function" +msgstr "По умолчанию не является функцией" -#: py/modmath.c -msgid "negative factorial" -msgstr "отрицательный факториал" +#: shared-bindings/msgpack/__init__.c +msgid "ext_hook is not a function" +msgstr "ext_hook не является функцией" -#: py/objint_longlong.c py/objint_mpz.c py/runtime.c -msgid "negative power with no float support" -msgstr "Отрицательная мощность без поплавковой опоры" +#: shared-bindings/nvm/ByteArray.c +msgid "Unable to write to nvm." +msgstr "Невозможно выполнить запись в nvm." -#: py/objint_mpz.c py/runtime.c -msgid "negative shift count" -msgstr "Количество отрицательных сдвигов" +#: shared-bindings/os/__init__.c +msgid "No hardware random available" +msgstr "Отсутствует аппаратный генератор случайных чисел" -#: shared-bindings/_pixelmap/PixelMap.c -msgid "nested index must be int" -msgstr "вложенный индекс должен быть int" +#: shared-bindings/paralleldisplaybus/ParallelBus.c +msgid "Specify exactly one of data0 or data_pins" +msgstr "Укажите точно один из data0 или data_pins" -#: shared-module/sdcardio/SDCard.c -msgid "no SD card" -msgstr "нет SD карты" +#: shared-bindings/picogame/Bitmap.c shared-module/msgpack/__init__.c +#: supervisor/shared/settings.c +msgid "Invalid format" +msgstr "Недопустимый формат" -#: py/vm.c -msgid "no active exception to reraise" -msgstr "Нет активного исключения для повторного создания" +#: shared-bindings/ps2io/Ps2.c +msgid "Failed sending command." +msgstr "Не удалось отправить команду." -#: py/compile.c -msgid "no binding for nonlocal found" -msgstr "Привязка для нелокальных не найдена" +#: shared-bindings/pulseio/PulseOut.c +msgid "Array must contain halfwords (type 'H')" +msgstr "Массив должен содержать полуслова (тип 'H')" -#: shared-module/msgpack/__init__.c -msgid "no default packer" -msgstr "Нет упаковщика по умолчанию" +#: shared-bindings/pwmio/PWMOut.c +msgid "Conflicting settings for shared resource" +msgstr "" -#: extmod/modrandom.c extmod/ulab/code/numpy/random/random.c -msgid "no default seed" -msgstr "Нет начального числа по умолчанию" +#: shared-bindings/random/__init__.c +msgid "stop not reachable from start" +msgstr "Остановка недоступна с начального запуска" -#: py/builtinimport.c -msgid "no module named '%q'" -msgstr "Нет модуля с именем '%Q'" +#: shared-bindings/random/__init__.c +msgid "invalid step" +msgstr "недействительный шаг" -#: shared-module/sdcardio/SDCard.c -msgid "no response from SD card" -msgstr "нет ответа с SD карты" +#: shared-bindings/random/__init__.c +msgid "empty sequence" +msgstr "пустая последовательность" -#: ports/espressif/common-hal/espcamera/Camera.c py/objobject.c py/runtime.c -msgid "no such attribute" -msgstr "нет такого атрибута" +#: shared-bindings/rclcpy/Publisher.c +msgid "Publishers can only be created from a parent node" +msgstr "" -#: ports/espressif/common-hal/_bleio/Connection.c -#: ports/nordic/common-hal/_bleio/Connection.c -msgid "non-UUID found in service_uuids_whitelist" -msgstr "не-UUID найден в сервисе_uuids_белый список" +#: shared-bindings/rgbmatrix/RGBMatrix.c +#, c-format +msgid "Must use a multiple of 6 rgb pins, not %d" +msgstr "Количество используемых rgb-пинов должно быть кратно 6, а не %d" -#: py/compile.c -msgid "non-default argument follows default argument" +#: 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, контакты rgb %d и плитки %d обозначают высоту %d, а не " +"%d" -#: py/objstr.c -msgid "non-hex digit found" -msgstr "Ненайдена шестнадцатеричная цифра" +#: shared-bindings/socketpool/Socket.c +msgid "port must be >= 0" +msgstr "порт должен быть >= 0" -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "non-zero timeout must be > 0.01" -msgstr "Ненулевое время ожидания должно быть > 0,01" +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c +msgid "buffer too small for requested bytes" +msgstr "Слишком маленький буфер для запрашиваемых байтов" -#: shared-bindings/_bleio/Adapter.c -msgid "non-zero timeout must be >= interval" -msgstr "Ненулевое время ожидания должно быть >= интервал" +#: shared-bindings/socketpool/SocketPool.c +msgid "Name or service not known" +msgstr "Имя или услуга не известны" -#: shared-bindings/_bleio/UUID.c -msgid "not a 128-bit UUID" -msgstr "не 128-битный UUID" +#: shared-bindings/spitarget/SPITarget.c +msgid "Packet buffers for an SPI transfer must have the same length." +msgstr "" -#: py/parse.c -msgid "not a constant" -msgstr "не константа" +#: shared-bindings/ssl/SSLContext.c +msgid "Server side context cannot have hostname" +msgstr "Контекст на стороне сервера не может иметь имя хоста" -#: py/objstr.c -msgid "not all arguments converted during string formatting" -msgstr "Не все аргументы преобразуются при форматировании строки" +#: shared-bindings/storage/__init__.c shared-bindings/usb_audio/__init__.c +#: shared-bindings/usb_cdc/__init__.c shared-bindings/usb_hid/__init__.c +#: shared-bindings/usb_midi/__init__.c shared-bindings/usb_video/__init__.c +msgid "Cannot change USB devices now" +msgstr "Невозможно изменить USB устройство сейчас" -#: py/objstr.c -msgid "not enough arguments for format string" -msgstr "Недостаточно аргументов для строки форматирования" +#: shared-bindings/supervisor/__init__.c shared-module/lvfontio/OnDiskFont.c +msgid "File not found" +msgstr "Файл не найден" -#: extmod/ulab/code/numpy/carray/carray_tools.c -msgid "not implemented for complex dtype" -msgstr "не реализовано для сложного типа d" +#: shared-bindings/time/__init__.c +msgid "timestamp out of range for platform time_t" +msgstr "" +"Временная метка выходит за пределы допустимого диапазона для платформы time_t" -#: extmod/ulab/code/numpy/bitwise.c -msgid "not supported for input types" -msgstr "Не поддерживается для типов ввода" +#: shared-bindings/traceback/__init__.c +msgid "Supply both or neither of %q and %q" +msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "number of points must be at least 2" -msgstr "Количество баллов должно быть не менее 2" +#: shared-bindings/traceback/__init__.c +msgid "file write is not available" +msgstr "Запись файлов недоступна" -#: py/builtinhelp.c -msgid "object " -msgstr "объект " +#: shared-bindings/traceback/__init__.c +msgid "invalid exception" +msgstr "Недопустимое исключение" -#: py/obj.c -#, c-format -msgid "object '%s' isn't a tuple or list" -msgstr "Объект \"%s\" не является кортежом или списком" +#: shared-bindings/usb_audio/USBSpeaker.c +msgid "destination must be an array of type 'h'" +msgstr "" -#: py/obj.c -msgid "object doesn't support item assignment" -msgstr "Объект не поддерживает назначение элементов" +#: shared-bindings/usb_audio/__init__.c +msgid "At least one of microphone and speaker must be enabled" +msgstr "" -#: py/obj.c -msgid "object doesn't support item deletion" -msgstr "Объект не поддерживает удаление элементов" +#: shared-bindings/usb_hid/Device.c +msgid "%q, %q, and %q must all be the same length" +msgstr "%q, %q, и %q должны быть одной длинны" -#: py/obj.c -msgid "object has no len" -msgstr "Объект не имеет объектива" +#: shared-bindings/util.c +msgid "" +"Object has been deinitialized and can no longer be used. Create a new object." +msgstr "" +"Объект был деинициализирован и больше не может быть использован. Создайте " +"новый объект." -#: py/obj.c -msgid "object isn't subscriptable" -msgstr "Объект не имеет индекса" +#: shared-bindings/warnings/__init__.c +msgid "%q must be a subclass of %q" +msgstr "%q должен быть подклассом %q" -#: py/runtime.c -msgid "object not an iterator" -msgstr "объект не итератор" +#: shared-bindings/wifi/Radio.c +msgid "Invalid hex password" +msgstr "Неверный шестнадцатеричный пароль" -#: py/objtype.c py/runtime.c -msgid "object not callable" -msgstr "Объект не вызывается" +#: shared-bindings/wifi/Radio.c +msgid "Invalid MAC address" +msgstr "Неверный MAC-адрес" -#: py/sequence.c shared-bindings/displayio/Group.c -msgid "object not in sequence" -msgstr "объект не в последовательности" +#: shared-bindings/wifi/Radio.c +msgid "AuthMode.OPEN is not used with password" +msgstr "Режим авторизации.OPEN не используется с паролем" -#: py/runtime.c -msgid "object not iterable" -msgstr "Объект не итерируемый" +#: shared-bindings/wifi/Radio.c +msgid "Supply either %q or %q, not both" +msgstr "" -#: py/obj.c -#, c-format -msgid "object of type '%s' has no len()" -msgstr "объект типа «%s» не имеет len()" +#: shared-bindings/wifi/Radio.c +msgid "Invalid BSSID" +msgstr "Неверный BSSID" -#: py/obj.c -msgid "object with buffer protocol required" -msgstr "Объект с обязательным буферным протоколом" +#: shared-bindings/wifi/Radio.c supervisor/shared/web_workflow/web_workflow.c +msgid "Authentication failure" +msgstr "Ошибка аутентификации" -#: py/objstr.c -msgid "odd-length string" -msgstr "Строка нечетной длины" +#: shared-bindings/wifi/Radio.c +msgid "No network with that ssid" +msgstr "Нет сети с этим ssid" -#: supervisor/shared/web_workflow/web_workflow.c -msgid "off" -msgstr "выключить" +#: shared-bindings/wifi/Radio.c +#, c-format +msgid "Unknown failure %d" +msgstr "Неизвестный сбой %d" -#: extmod/ulab/code/utils/utils.c -msgid "offset is too large" -msgstr "Смещение слишком большое" +#: shared-module/adafruit_bus_device/i2c_device/I2CDevice.c +#, c-format +msgid "No I2C device at address: 0x%x" +msgstr "Нет устройства I2C по адресу: %x" -#: shared-bindings/dualbank/__init__.c -msgid "offset must be >= 0" -msgstr "Смещение должно быть >= 0" +#: shared-module/audiocore/WaveFile.c +msgid "Invalid format chunk size" +msgstr "Неверный размер блока формата" -#: extmod/ulab/code/numpy/create.c -msgid "offset must be non-negative and no greater than buffer length" -msgstr "Смещение должно быть неотрицательным и не превышать длину буфера" +#: shared-module/audiocore/__init__.c shared-module/usb_audio/USBMicrophone.c +msgid "The sample's %q does not match" +msgstr "%q образца не совпадает" -#: ports/nordic/common-hal/audiobusio/PDMIn.c -#: ports/stm/common-hal/audiobusio/PDMIn.c -msgid "only bit_depth=16 is supported" -msgstr "поддерживается только бит_глубина=16" +#: shared-module/audiodelays/MultiTapDelay.c +msgid "%q in %q must be of type %q or %q, not %q" +msgstr "" -#: ports/stm/common-hal/audiobusio/PDMIn.c -msgid "only mono is supported" -msgstr "Поддерживается только моно" +#: shared-module/audiofilewriter/AudioFileWriter.c +msgid "Only 8/16-bit mono/stereo is supported" +msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "only ndarrays can be concatenated" -msgstr "только массивы ndarrays могут быть объединены" +#: shared-module/audiofilewriter/AudioFileWriter.c +msgid "buffer_size too small for source" +msgstr "" -#: ports/stm/common-hal/audiobusio/PDMIn.c -msgid "only oversample=64 is supported" -msgstr "поддерживается только выборка = 64" +#: shared-module/audiomp3/MP3Decoder.c +msgid "Couldn't allocate decoder" +msgstr "Не удалось выделить место для декодера" -#: ports/nordic/common-hal/audiobusio/PDMIn.c -#: ports/stm/common-hal/audiobusio/PDMIn.c -msgid "only sample_rate=16000 is supported" -msgstr "только образец_рейт=16000 поддерживается" +#: shared-module/audiomp3/MP3Decoder.c +msgid "Failed to parse MP3 file" +msgstr "Не удалось распарсить файл MP3" -#: py/objarray.c py/objstr.c py/objstrunicode.c py/objtuple.c -#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c -#: shared-bindings/nvm/ByteArray.c -msgid "only slices with step=1 (aka None) are supported" -msgstr "поддерживаются только срезы с шагом = 1 (так как нет)" +#: shared-module/bitbangio/I2C.c shared-module/msgpack/__init__.c +msgid "%q too long" +msgstr "%q слишком долго" -#: py/vm.c -msgid "opcode" -msgstr "код операции" +#: shared-module/bitmapfilter/__init__.c +msgid "bitmap size and depth must match" +msgstr "Размер и глубина растрового изображения должны совпадать" + +#: shared-module/bitmapfilter/__init__.c +msgid "unsupported bitmap depth" +msgstr "неподдерживаемая глубина растрового изображения" -#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/bitwise.c -#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/numpy/vector.c -msgid "operands could not be broadcast together" -msgstr "Операнды не могут транслироваться вместе" +#: shared-module/busdisplay/lvgl/BusDisplay.c +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "LVGL display create failed" +msgstr "" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "operation is defined for 2D arrays only" -msgstr "операция определена только для 2D-массивов" +#: shared-module/busdisplay/lvgl/BusDisplay.c +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "LVGL buffer alloc failed" +msgstr "" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "operation is defined for ndarrays only" -msgstr "операция определена только для массивов ndarrays" +#: shared-module/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "OAEP requires this build to enable TLS 1.3 support" +msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "operation is implemented for 1D Boolean arrays only" -msgstr "операция реализована только для 1D логических массивов" +#: shared-module/displayio/bus_core.c +msgid "Unsupported display bus type" +msgstr "Неподдерживаемый тип шины дисплея" -#: extmod/ulab/code/numpy/numerical.c -msgid "operation is not implemented on ndarrays" -msgstr "операция не реализована на массивах ndarrays" +#: shared-module/displayio/legacy/Bitmap.c +#: shared-module/displayio/lvgl/Bitmap.c +msgid "Invalid bits per value" +msgstr "Недопустимое бит-на-значение" -#: extmod/ulab/code/ndarray.c -msgid "operation is not supported for given type" -msgstr "Операция не поддерживается для данного типа" +#: shared-module/displayio/legacy/ColorConverter.c +#: shared-module/displayio/lvgl/ColorConverter.c +msgid "Only one color can be transparent at a time" +msgstr "Только один цвет может быть прозрачным одновременно" -#: extmod/ulab/code/ndarray_operators.c -msgid "operation not supported for the input types" -msgstr "операция не поддерживается для типов ввода" +#: shared-module/displayio/legacy/Group.c shared-module/displayio/lvgl/Group.c +msgid "Layer already in a group" +msgstr "Слой уже в группе (Group)" -#: py/modbuiltins.c -msgid "ord expects a character" -msgstr "Орд ожидает персонажа" +#: shared-module/displayio/legacy/Group.c +msgid "Layer must be a Group or TileGrid subclass" +msgstr "Слой должен быть группой (Group) или субклассом TileGrid" -#: py/modbuiltins.c +#: shared-module/displayio/legacy/OnDiskBitmap.c +#: shared-module/displayio/lvgl/OnDiskBitmap.c #, c-format -msgid "ord() expected a character, but string of length %d found" -msgstr "ord() ожидал символ, но строка длины %d найдена" +msgid "" +"Only Windows format, uncompressed BMP supported: given header size is %d" +msgstr "" +"Поддерживается только формат Windows, несжатый BMP: заданный размер " +"заголовка - %d" -#: extmod/ulab/code/utils/utils.c -msgid "out array is too small" -msgstr "Наш массив слишком мал" +#: shared-module/displayio/legacy/OnDiskBitmap.c +#: shared-module/displayio/lvgl/OnDiskBitmap.c +msgid "RLE-compressed BMP not supported" +msgstr "RLE-сжатый BMP не поддерживается" -#: extmod/ulab/code/numpy/random/random.c -msgid "out has wrong type" -msgstr "out имеет неправильный тип" +#: shared-module/displayio/legacy/OnDiskBitmap.c +#: shared-module/displayio/lvgl/OnDiskBitmap.c +msgid "Unable to read color palette data" +msgstr "Не удается прочитать данные цветовой палитры" -#: extmod/ulab/code/numpy/vector.c -msgid "out keyword is not supported for complex dtype" -msgstr "Ключевое слово out не поддерживается для сложного типа d" +#: shared-module/displayio/legacy/__init__.c +msgid "Too many displays" +msgstr "Слишком много дисплеев" -#: extmod/ulab/code/numpy/vector.c -msgid "out keyword is not supported for function" -msgstr "ключевое слово не поддерживается для функции" +#: shared-module/displayio/legacy/__init__.c +msgid "Too many display buses; deinit() unused displays" +msgstr "" -#: extmod/ulab/code/utils/utils.c -msgid "out must be a float dense array" -msgstr "Out должен быть плотным массивом с плавающей запятой" +#: shared-module/displayio/lvgl/Group.c +msgid "Layer does not support scaling" +msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "out must be an ndarray" -msgstr "out должен быть массивом ndarray" +#: shared-module/displayio/lvgl/Group.c +msgid "Layer must be a Group, TileGrid, vector shape or VideoBuffer" +msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "out must be of float dtype" -msgstr "Выход должен быть поплавкового типа" +#: shared-module/displayio/lvgl/TileGrid.c +msgid "LVGL displayio backend does not support flips/transpose yet" +msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "out of range of target" -msgstr "вне досягаемости цели" +#: shared-module/displayio/lvgl/TileGrid.c +msgid "OnDiskBitmap requires its own pixel_shader" +msgstr "" -#: extmod/ulab/code/numpy/random/random.c -msgid "output array has wrong type" -msgstr "Выходной массив имеет неправильный тип" +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "LVGL dirty row alloc failed" +msgstr "" -#: extmod/ulab/code/numpy/random/random.c -msgid "output array must be contiguous" -msgstr "выходной массив должен быть непрерывным" +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +#: shared-module/videocore/VideoBuffer.c +#: shared-module/videocore/legacy/VideoBuffer.c +#: shared-module/videocore/lvgl/VideoBuffer.c +msgid "VideoBuffer can't stream into a rotated display" +msgstr "" -#: py/objint_mpz.c -msgid "overflow converting long int to machine word" -msgstr "переполнение преобразование длинного целого в машинное слово" +#: shared-module/gifio/GifWriter.c +msgid "unsupported colorspace for GifWriter" +msgstr "неподдерживаемое цветовое пространство для GifWriter" -#: py/modstruct.c -#, c-format -msgid "pack expected %d items for packing (got %d)" -msgstr "Упаковка ожидаемых %d товаров для упаковки (получил %d)" +#: shared-module/hmac/HMAC.c +msgid "key does not support this digest" +msgstr "" -#: shared-bindings/_stage/Layer.c shared-bindings/_stage/Text.c -msgid "palette must be 32 bytes long" -msgstr "Длина палитры должна составлять 32 байта" +#: shared-module/hmac/HMAC.c +msgid "HMAC of an empty message is not supported with a hardware key" +msgstr "" -#: py/emitinlinextensa.c -msgid "parameters must be registers in sequence a2 to a5" -msgstr "Параметры должны быть регистрами в последовательности от a2 до a5" +#: shared-module/i2cdisplaybus/I2CDisplayBus.c +#: shared-module/is31fl3741/IS31FL3741.c +#, c-format +msgid "Unable to find I2C Display at %x" +msgstr "Не удается найти дисплей I2C в %x" -#: py/emitinlinethumb.c -msgid "parameters must be registers in sequence r0 to r3" -msgstr "Параметры должны быть регистрами в последовательности от r0 до r3" +#: shared-module/i2cioexpander/IOExpander.c +msgid "Cannot deinitialize board IOExpander" +msgstr "" -#: extmod/vfs_posix_file.c -msgid "poll on file not available on win32" -msgstr "Опрос в файле недоступен в Win32" +#: shared-module/imagecapture/ParallelImageCapture.c +msgid "This microcontroller does not support continuous capture." +msgstr "Этот микроконтроллер не поддерживает непрерывный захват." -#: ports/espressif/common-hal/pulseio/PulseIn.c -msgid "pop from an empty PulseIn" -msgstr "вытолкнуть из пустого импульсного входа" +#: shared-module/jpegio/JpegDecoder.c +msgid "Interrupted by output function" +msgstr "Прерывается функцией выхода" -#: ports/atmel-samd/common-hal/pulseio/PulseIn.c -#: ports/cxd56/common-hal/pulseio/PulseIn.c -#: ports/nordic/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 "Всплывающее окно из пустого %q" +#: shared-module/jpegio/JpegDecoder.c +msgid "Device error or wrong termination of input stream" +msgstr "Ошибка устройства или неправильное завершение входного потока" -#: shared-bindings/socketpool/Socket.c -msgid "port must be >= 0" -msgstr "порт должен быть >= 0" +#: shared-module/jpegio/JpegDecoder.c +msgid "Insufficient memory pool for the image" +msgstr "Недостаточный объем памяти для изображения" -#: py/compile.c -msgid "positional arg after **" -msgstr "позиционный аргумент после **" +#: shared-module/jpegio/JpegDecoder.c +msgid "Insufficient stream input buffer" +msgstr "Недостаточный буфер ввода потока" -#: py/compile.c -msgid "positional arg after keyword arg" -msgstr "позиционный аргумент после ключевого слова аргумента" +#: shared-module/jpegio/JpegDecoder.c +msgid "Parameter error" +msgstr "Ошибка параметра" -#: py/objint_mpz.c -msgid "pow() 3rd argument cannot be 0" -msgstr "3-й аргумент pow() не может быть равен 0" +#: shared-module/jpegio/JpegDecoder.c +msgid "Data format error (may be broken data)" +msgstr "Ошибка формата данных (возможно, данные повреждены)" -#: py/objint_mpz.c -msgid "pow() with 3 arguments requires integers" -msgstr "pow() с 3 аргументами требует целых чисел" +#: shared-module/jpegio/JpegDecoder.c +msgid "Right format but not supported" +msgstr "Правильный формат, но не поддерживается" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "pull masks conflict with direction masks" -msgstr "Маски вытягивания конфликтуют с масками направления" +#: shared-module/jpegio/JpegDecoder.c +msgid "Unsupported JPEG (may be progressive)" +msgstr "" -#: py/parse.c -msgid "raw f-strings are not supported" -msgstr "Необработанные F-строки не поддерживаются" +#: shared-module/jpegio/JpegDecoder.c +msgid "%q() without %q()" +msgstr "%q() без %q()" -#: extmod/ulab/code/numpy/fft/fft_tools.c -msgid "real and imaginary parts must be of equal length" -msgstr "реальные и воображаемые части должны быть одинаковой длины" +#: shared-module/memorymonitor/AllocationAlarm.c +#, c-format +msgid "Attempt to allocate %d blocks" +msgstr "Попытка выделения %d блоков" -#: py/builtinimport.c -msgid "relative import" -msgstr "Относительный импорт" +#: shared-module/msgpack/__init__.c +msgid "short read" +msgstr "короткое чтение" -#: py/obj.c -#, c-format -msgid "requested length %d but object has length %d" -msgstr "запрашиваемая длина %d, но объект имеет длину %d" +#: shared-module/msgpack/__init__.c +msgid "no default packer" +msgstr "Нет упаковщика по умолчанию" -#: extmod/ulab/code/ndarray_operators.c -msgid "results cannot be cast to specified type" -msgstr "Результаты не могут быть приведены к указанному типу" +#: shared-module/paralleldisplaybus/ParallelBus.c +msgid "" +"This microcontroller only supports data0=, not data_pins=, because it " +"requires contiguous pins." +msgstr "" +"Этот микроконтроллер поддерживает только data0=, а не data_pins=, поскольку " +"для него требуются смежные выводы." -#: py/compile.c -msgid "return annotation must be an identifier" -msgstr "Возвращаемая аннотация должна быть идентификатором" +#: shared-module/rgbmatrix/RGBMatrix.c +msgid "The length of rgb_pins must be 6, 12, 18, 24, or 30" +msgstr "Длина rgb_pins должна быть 6, 12, 18, 24 или 30" -#: py/emitnative.c -msgid "return expected '%q' but got '%q'" -msgstr "Возврат ожидался '%q', но получил '%q'" +#: shared-module/rgbmatrix/RGBMatrix.c +#, c-format +msgid "rgb_pins[%d] is not on the same port as clock" +msgstr "rgb_pins[%d] не находится на том же порту что и часы" -#: shared-bindings/rgbmatrix/RGBMatrix.c +#: shared-module/rgbmatrix/RGBMatrix.c #, c-format msgid "rgb_pins[%d] duplicates another pin assignment" msgstr "rgb_pins[%d] дублирует другое назначение пинов" -#: shared-bindings/rgbmatrix/RGBMatrix.c -#, c-format -msgid "rgb_pins[%d] is not on the same port as clock" -msgstr "rgb_pins[%d] не находится на том же порту что и часы" +#: shared-module/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 "" +"Распиновка использует %d байт на элемент, что превышает идеальное %d байт. " +"Если этого нельзя избежать, передайте конструктору allow_inefficient=True" + +#: shared-module/rgbmatrix/RGBMatrix.c +msgid "No timer available" +msgstr "Нет доступного таймера" + +#: shared-module/rgbmatrix/RGBMatrix.c +#, c-format +msgid "Internal error #%d" +msgstr "Внутренняя ошибка #%d" + +#: shared-module/sdcardio/SDCard.c +msgid "timeout waiting for v1 card" +msgstr "Таймаут в ожидании карты v1" + +#: shared-module/sdcardio/SDCard.c +msgid "timeout waiting for v2 card" +msgstr "Таймаут ожидания карты v2" + +#: shared-module/sdcardio/SDCard.c +msgid "no SD card" +msgstr "нет SD карты" + +#: shared-module/sdcardio/SDCard.c +msgid "couldn't determine SD card version" +msgstr "Не удалось определить версию SD карты" + +#: shared-module/sdcardio/SDCard.c +msgid "no response from SD card" +msgstr "нет ответа с SD карты" -#: extmod/ulab/code/numpy/numerical.c -msgid "roll argument must be an ndarray" -msgstr "аргумент roll должен быть массивом ndarray" +#: shared-module/sdcardio/SDCard.c +msgid "SD card CSD format not supported" +msgstr "Формат CSD SD-карты не поддерживается" -#: py/objstr.c -msgid "rsplit(None,n)" -msgstr "rsplit(Нет;n)" +#: shared-module/sdcardio/SDCard.c +msgid "can't set 512 block size" +msgstr "Не удается установить размер блока 512" -#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c -#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c -msgid "sampling rate out of range" -msgstr "Частота дискретизации выходит за пределы допустимого диапазона" +#: shared-module/ssl/SSLSocket.c +msgid "Invalid socket for TLS" +msgstr "Неверный сокет для TLS" -#: py/modmicropython.c -msgid "schedule queue full" -msgstr "Расписание Очередь заполнена" +#: shared-module/ssl/SSLSocket.c +msgid "invalid cert" +msgstr "Неверный сертификат" -#: py/builtinimport.c -msgid "script compilation not supported" -msgstr "Компиляция скриптов не поддерживается" +#: shared-module/storage/__init__.c +msgid "File write in progress" +msgstr "" -#: py/nativeglue.c -msgid "set unsupported" -msgstr "Установить не поддерживается" +#: shared-module/storage/__init__.c +msgid "Mount point directory missing" +msgstr "Отсутствует каталог точки монтирования" -#: extmod/ulab/code/numpy/random/random.c -msgid "shape must be None, and integer or a tuple of integers" -msgstr "форма должна быть None, целым числом или кортежем целых чисел" +#: shared-module/storage/__init__.c +msgid "Cannot remount path when visible via USB." +msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "shape must be integer or tuple of integers" -msgstr "фигура должна быть целым числом или кортежом целых чисел" +#: shared-module/struct/__init__.c +msgid "'S' and 'O' are not supported format types" +msgstr "'S' и 'O' не являются поддерживаемыми типами форматов" -#: shared-module/msgpack/__init__.c -msgid "short read" -msgstr "короткое чтение" +#: shared-module/struct/__init__.c +msgid "buffer size must match format" +msgstr "Размер буфера должен соответствовать формату" -#: py/objstr.c -msgid "sign not allowed in string format specifier" -msgstr "Знак не разрешен в спецификаторе строкового формата" +#: shared-module/synthio/__init__.c +msgid "%q must be array of type 'h'" +msgstr "%q должен быть массивом типа 'h \"" -#: py/objstr.c -msgid "sign not allowed with integer format specifier 'c'" -msgstr "Знак не разрешен со спецификатором целочисленного формата 'c'" +#: shared-module/tilepalettemapper/TilePaletteMapper.c +msgid "TilePaletteMapper may only be bound to a TileGrid once" +msgstr "" -#: extmod/ulab/code/ulab_tools.c -msgid "size is defined for ndarrays only" -msgstr "размер определен только для массива ndarrays" +#: shared-module/touchio/TouchIn.c +msgid "No pullup on pin; 1Mohm recommended" +msgstr "" -#: extmod/ulab/code/numpy/random/random.c -msgid "size must match out.shape when used together" -msgstr "Размер должен соответствовать out.shape при совместном использовании" +#: shared-module/touchio/TouchIn.c +msgid "No pulldown on pin; 1Mohm recommended" +msgstr "Отсутствует подтяжка к земле на пине; Рекомендуется 1 Мегаом" -#: py/nativeglue.c -msgid "slice unsupported" -msgstr "Фрагмент не поддерживается" +#: shared-module/usb/core/Device.c +msgid "No usb host port initialized" +msgstr "Порт USB-хоста не инициализирован" -#: py/objint.c py/sequence.c -msgid "small int overflow" -msgstr "Маленькое переполнение int" +#: shared-module/usb/core/Device.c +msgid "Pipe error" +msgstr "Ошибка трубопровода" -#: main.c -msgid "soft reboot\n" -msgstr "Мягкая перезагрузка\n" +#: shared-module/usb/core/Device.c +msgid "No configuration set" +msgstr "Нет конфигураций" -#: extmod/ulab/code/numpy/numerical.c -msgid "sort argument must be an ndarray" -msgstr "аргумент сортировки должен быть массивом ndarray" +#: shared-module/usb_hid/Device.c +msgid "USB busy" +msgstr "USB занят" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "sos array must be of shape (n_section, 6)" -msgstr "Массив sos должен иметь форму (n_section, 6)" +#: shared-module/vectorio/Circle.c shared-module/vectorio/Polygon.c +#: shared-module/vectorio/Rectangle.c +msgid "can only have one parent" +msgstr "может иметь только одного родителя" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "sos[:, 3] should be all ones" -msgstr "sos[:, 3] должны быть все единицы" +#: shared-module/vectorio/Polygon.c +msgid "Polygon needs at least 3 points" +msgstr "Полигону необходимо как минимум 3 точки" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "sosfilt requires iterable arguments" -msgstr "sosфильтр требует повторяющихся аргументов" +#: shared-module/videocore/VideoBuffer.c +msgid "framebuffer went away" +msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "source palette too large" -msgstr "Исходная палитра слишком велика" +#: shared-module/videocore/VideoBuffer.c +msgid "video doesn't fit in framebuffer" +msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "source_bitmap must have value_count of 2 or 65536" -msgstr "source_bitmap должен иметь значение_счет 2 или 65536" +#: shared-module/videocore/VideoBuffer.c +msgid "framebuffer missing required functions" +msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "source_bitmap must have value_count of 65536" -msgstr "source_bitmap должен иметь значение_счет 65536" +#: shared-module/videocore/VideoBuffer.c +msgid "video format must be byte aligned" +msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "source_bitmap must have value_count of 8" -msgstr "source_bitmap должен иметь значение_счет 8" +#: shared-module/videocore/VideoBuffer.c +msgid "video format doesn't match framebuffer" +msgstr "" -#: extmod/modre.c -msgid "splitting with sub-captures" -msgstr "разделение с помощью подзахватов" +#: shared-module/videocore/VideoBuffer.c +msgid "video source rejected the destination" +msgstr "" -#: py/objstr.c -msgid "start/end indices" -msgstr "Начальные/конечные индексы" +#: shared-module/videocore/VideoBuffer.c +msgid "video in a framebuffer must be at x == 0" +msgstr "" -#: shared-bindings/random/__init__.c -msgid "stop not reachable from start" -msgstr "Остановка недоступна с начального запуска" +#: shared-module/videocore/VideoBuffer.c +msgid "video size changed since play; stop and play again" +msgstr "" -#: py/stream.c shared-bindings/getpass/__init__.c -msgid "stream operation not supported" -msgstr "Потоковая операция не поддерживается" +#: shared-module/videocore/VideoBuffer.c +msgid "VideoBuffer is playing into a different framebuffer" +msgstr "" -#: py/objarray.c py/objstr.c -msgid "string argument without an encoding" -msgstr "строковый аргумент без кодировки" +#: shared-module/videocore/legacy/VideoBuffer.c +msgid "VideoBuffer does not support transforms" +msgstr "" -#: py/objstrunicode.c -msgid "string index out of range" -msgstr "индекс строки выходит за пределы диапазона" +#: shared-module/videocore/lvgl/VideoBuffer.c +msgid "video format must be 16, 24 or 32 bits per pixel" +msgstr "" -#: py/objstrunicode.c -#, c-format -msgid "string indices must be integers, not %s" -msgstr "Индексы строк должны быть целыми числами, а не %s" +#: supervisor/shared/bluetooth/bluetooth.c +msgid "Reconnecting" +msgstr "Повторное соединение" -#: py/objarray.c py/objstr.c -msgid "substring not found" -msgstr "Подстрока не найдена" +#: supervisor/shared/bluetooth/bluetooth.c +msgid "Ok" +msgstr "Да" -#: py/compile.c -msgid "super() can't find self" -msgstr "super() не может найти себя" +#: supervisor/shared/bluetooth/bluetooth.c +msgid "Off" +msgstr "Выключено" -#: extmod/modjson.c -msgid "syntax error in JSON" -msgstr "синтаксис ошибка в JSON" +#: supervisor/shared/micropython.c +msgid "[truncated due to length]" +msgstr "[отрезается по длине]" -#: extmod/modtime.c -msgid "ticks interval overflow" -msgstr "переполнение интервала тиков" +#: supervisor/shared/safe_mode.c +msgid "" +"\n" +"You are in safe mode because:\n" +msgstr "" +"\n" +"Вы в безопасном режиме потому что:\n" -#: ports/nordic/common-hal/watchdog/WatchDogTimer.c -msgid "timeout duration exceeded the maximum supported value" +#: supervisor/shared/safe_mode.c +msgid "Power dipped. Make sure you are providing enough power." msgstr "" -"Продолжительность таймаута превысила максимальное поддерживаемое значение" +"Мощность просела. Убедитесь, что вы обеспечиваете достаточную мощность." -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "timeout must be < 655.35 secs" -msgstr "таймаут должен быть < 655.35 сек" +#: supervisor/shared/safe_mode.c +msgid "You pressed the BOOT button at start up" +msgstr "Вы нажали кнопку BOOT при запуске" -#: ports/raspberrypi/common-hal/floppyio/__init__.c -msgid "timeout waiting for flux" -msgstr "таймаут ожидания потока" +#: supervisor/shared/safe_mode.c +msgid "You pressed the reset button during boot." +msgstr "Вы нажали кнопку сброса во время загрузки." -#: ports/raspberrypi/common-hal/floppyio/__init__.c -#: shared-module/floppyio/__init__.c -msgid "timeout waiting for index pulse" -msgstr "таймаут ожидания индексного импульса" +#: supervisor/shared/safe_mode.c +msgid "CIRCUITPY drive could not be found or created." +msgstr "Диск CIRCUTPY не удалось найти или создать." -#: shared-module/sdcardio/SDCard.c -msgid "timeout waiting for v1 card" -msgstr "Таймаут в ожидании карты v1" +#: supervisor/shared/safe_mode.c +msgid "The `microcontroller` module was used to boot into safe mode." +msgstr "" +"Модуль «микроконтроллер» использовался для загрузки в безопасном режиме." -#: shared-module/sdcardio/SDCard.c -msgid "timeout waiting for v2 card" -msgstr "Таймаут ожидания карты v2" +#: supervisor/shared/safe_mode.c +msgid "Error in safemode.py." +msgstr "Ошибка в сейфе. py." -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "timer re-init" -msgstr "Повторное инициализация таймера" +#: supervisor/shared/safe_mode.c +msgid "Stack overflow. Increase stack size." +msgstr "Переполнение стека. Увеличьте размер стека." -#: shared-bindings/time/__init__.c -msgid "timestamp out of range for platform time_t" -msgstr "" -"Временная метка выходит за пределы допустимого диапазона для платформы time_t" +#: supervisor/shared/safe_mode.c +msgid "USB devices need more endpoints than are available." +msgstr "USB-устройствам требуется больше конечных точек, чем доступно." -#: extmod/ulab/code/ndarray.c -msgid "tobytes can be invoked for dense arrays only" -msgstr "Тобайты могут быть вызваны только для плотных массивов" +#: supervisor/shared/safe_mode.c +msgid "USB devices specify too many interface names." +msgstr "USB-устройства указывают слишком много имен интерфейсов." + +#: supervisor/shared/safe_mode.c +msgid "Boot device must be first (interface #0)." +msgstr "Загрузочное устройство должно быть первым (интерфейс #0)." -#: py/compile.c -msgid "too many args" -msgstr "слишком много аргументов" +#: supervisor/shared/safe_mode.c +msgid "Internal watchdog timer expired." +msgstr "Внутренний сторожевой таймер истек." -#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/create.c -msgid "too many dimensions" -msgstr "Слишком много измерений" +#: supervisor/shared/safe_mode.c +msgid "CircuitPython core code crashed hard. Whoops!\n" +msgstr "Основной код CircuitPython сильно разбился. Упс!\n" -#: extmod/ulab/code/ndarray.c -msgid "too many indices" -msgstr "Слишком много индексов" +#: supervisor/shared/safe_mode.c +msgid "Heap allocation when VM not running." +msgstr "Выделение кучи, когда виртуальная машина не запущена." -#: py/asmthumb.c -msgid "too many locals for native method" -msgstr "Слишком много местных жителей для нативного метода" +#: supervisor/shared/safe_mode.c +msgid "Failed to write internal flash." +msgstr "Не удалось записать внутреннюю флэш-память." -#: py/runtime.c -#, c-format -msgid "too many values to unpack (expected %d)" -msgstr "Слишком много значений для распаковки (ожидаемый %d)" +#: supervisor/shared/safe_mode.c +msgid "Hard fault: memory access or instruction error." +msgstr "Жесткая ошибка: доступ к памяти или ошибка инструкции." -#: extmod/ulab/code/numpy/approx.c -msgid "trapz is defined for 1D arrays of equal length" -msgstr "ловушка определена для одномерных 1D массивов одинаковой длины" +#: supervisor/shared/safe_mode.c +msgid "Interrupt error." +msgstr "Прерванная ошибка." -#: extmod/ulab/code/numpy/approx.c -msgid "trapz is defined for 1D iterables" -msgstr "ловушка определена для одномерных 1D итераций" +#: supervisor/shared/safe_mode.c +msgid "LVGL ran out of memory." +msgstr "" -#: py/obj.c -msgid "tuple/list has wrong length" -msgstr "Кортеж/список имеет неправильную длину" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." +msgstr "Прыжок NLR не удался. Вероятно повреждение памяти." -#: ports/espressif/common-hal/canio/CAN.c -#, c-format -msgid "twai_driver_install returned esp-idf error #%d" -msgstr "twai_driver_install вернул ошибку esp-idf #%d" +#: supervisor/shared/safe_mode.c +msgid "Unable to allocate to the heap." +msgstr "Невозможно выделить место в куче." -#: ports/espressif/common-hal/canio/CAN.c -#, c-format -msgid "twai_start returned esp-idf error #%d" -msgstr "twai_start вернул ошибку esp-idf #%d" +#: supervisor/shared/safe_mode.c +msgid "Third-party firmware fatal error." +msgstr "Неустранимая ошибка прошивки стороннего производителя." -#: shared-bindings/busio/UART.c shared-bindings/canio/CAN.c -msgid "tx and rx cannot both be None" -msgstr "tx и rx не могут быть одновременно None" +#: supervisor/shared/safe_mode.c +msgid "" +"\n" +"Please file an issue with your program at github.com/adafruit/circuitpython/" +"issues." +msgstr "" +"\n" +"Пожалуйста подайте вопрос с вашей программой на github.com/adafruit/" +"circuitpython/issues." -#: py/objtype.c -msgid "type '%q' is not an acceptable base type" -msgstr "Тип '%Q' не является допустимым базовым типом" +#: supervisor/shared/safe_mode.c +msgid "" +"\n" +"Press reset to exit safe mode.\n" +msgstr "" +"\n" +"Нажмите на сброс чтобы выйти из безопасного режима.\n" -#: py/objtype.c -msgid "type is not an acceptable base type" -msgstr "Тип не является приемлемым базовым типом" +#: supervisor/shared/settings.c +#, c-format +msgid "An error occurred while retrieving '%s':\n" +msgstr "Произошла ошибка при получении '%s':\n" -#: py/runtime.c -msgid "type object '%q' has no attribute '%q'" -msgstr "тип объекта '%q' не имеет атрибута '%q \"" +#: supervisor/shared/settings.c +msgid "Invalid unicode escape" +msgstr "Недопустимое экранирование Юникода" -#: py/objtype.c -msgid "type takes 1 or 3 arguments" -msgstr "тип занимает 1 или 3 аргумента" +#: supervisor/shared/web_workflow/web_workflow.c +msgid "Wi-Fi: " +msgstr "Wi-Fi: " -#: py/objint_longlong.c -msgid "ulonglong too large" -msgstr "голова длинная слишком большая" +#: supervisor/shared/web_workflow/web_workflow.c +msgid "off" +msgstr "выключить" -#: py/parse.c -msgid "unexpected indent" -msgstr "Неожиданный отступ" +#: supervisor/shared/web_workflow/web_workflow.c +msgid "No IP" +msgstr "Нет IP" -#: py/bc.c -msgid "unexpected keyword argument" -msgstr "Неожиданный аргумент ключевого слова" +#~ msgid "Too many display busses; forgot displayio.release_displays() ?" +#~ msgstr "Слишком много шин дисплея; забыл displayio.release_displays()?" -#: py/argcheck.c py/bc.c py/objnamedtuple.c -#: shared-bindings/traceback/__init__.c -msgid "unexpected keyword argument '%q'" -msgstr "неожиданный аргумент ключевого слова '%q'" +#~ msgid "Failed to add service TXT record" +#~ msgstr "Не удалось добавить служебную запись TXT" -#: py/lexer.c -msgid "unicode name escapes" -msgstr "Экранирование имен в Юникоде" +#~ msgid "invalid key" +#~ msgstr "Неверный ключ" -#: py/parse.c -msgid "unindent doesn't match any outer indent level" -msgstr "Отступ не совпадает ни с одним уровнем внешнего отступа" +#, c-format +#~ msgid "Unknown system firmware error at %s:%d: %d" +#~ msgstr "Неизвестная системная ошибка прошивки на %s:%d: %d" -#: py/objstr.c #, c-format -msgid "unknown conversion specifier %c" -msgstr "Неизвестный спецификатор преобразования %c" +#~ msgid "Unknown system firmware error: %d" +#~ msgstr "Неизвестная ошибка прошивки системы: %d" -#: py/objstr.c -msgid "unknown format code '%c' for object of type '%q'" -msgstr "Неизвестный код формата '%c' для объекта типа '%q'" +#, c-format +#~ msgid "Unknown BLE error at %s:%d: %d" +#~ msgstr "Неизвестная ошибка BLE в %s:%d: %d" -#: py/compile.c -msgid "unknown type" -msgstr "Неизвестный тип" +#, c-format +#~ msgid "Unknown BLE error: %d" +#~ msgstr "Неизвестная ошибка BLE: %d" -#: py/compile.c -msgid "unknown type '%q'" -msgstr "Неизвестный тип '%q'" +#~ msgid "shape must be None, and integer or a tuple of integers" +#~ msgstr "форма должна быть None, целым числом или кортежем целых чисел" -#: py/objstr.c -#, c-format -msgid "unmatched '%c' in format" -msgstr "Несовпадающий '%c' в формате" +#~ msgid "MITM security not supported" +#~ msgstr "Защита от MITM не поддерживается" -#: py/objtype.c py/runtime.c -msgid "unreadable attribute" -msgstr "Нечитаемый атрибут" +#~ msgid "%q out of bounds" +#~ msgstr "%q за пределом" -#: shared-bindings/displayio/TileGrid.c shared-bindings/vectorio/VectorShape.c -msgid "unsupported %q type" -msgstr "Неподдерживаемый тип %Q" +#~ msgid "chr() arg not in range(0x110000)" +#~ msgstr "chr() аргумент вне диапазона (0x110000)" -#: py/emitinlinethumb.c #, c-format -msgid "unsupported Thumb instruction '%s' with %d arguments" -msgstr "неподдерживаемая инструкция Thumb '%s' с аргументами %d" +#~ msgid "value must fit in %d byte(s)" +#~ msgstr "Значение должно совпадать с байтами %d" + +#~ msgid "Too many descriptors" +#~ msgstr "Слишком много дескрипторов" + +#~ msgid "" +#~ "Unspecified issue. Can be that the pairing prompt on the other device was " +#~ "declined or ignored." +#~ msgstr "" +#~ "Неуказанная проблема. Возможно, запрос на сопряжение на другом устройстве " +#~ "был отклонен или проигнорирован." -#: py/emitinlinextensa.c #, c-format -msgid "unsupported Xtensa instruction '%s' with %d arguments" -msgstr "неподдерживаемая инструкция Xtensa '%s' с аргументами %d" +#~ msgid "SDIO Init Error %x" +#~ msgstr "Ошибка инициализации SDIO %x" -#: shared-module/bitmapfilter/__init__.c -msgid "unsupported bitmap depth" -msgstr "неподдерживаемая глубина растрового изображения" +#~ msgid "bit_depth must be 8, 16, 24, or 32." +#~ msgstr "Глубина_бита должна быть равна 8, 16, 24 или 32." -#: shared-module/gifio/GifWriter.c -msgid "unsupported colorspace for GifWriter" -msgstr "неподдерживаемое цветовое пространство для GifWriter" +#~ msgid "%q renamed %q" +#~ msgstr "%q переименован %q" -#: shared-bindings/bitmaptools/__init__.c -msgid "unsupported colorspace for dither" -msgstr "Неподдерживаемое цветовое пространство для дизеринга" +#~ msgid "asm overflow" +#~ msgstr "Переполнение ASM" -#: py/objstr.c -#, c-format -msgid "unsupported format character '%c' (0x%x) at index %d" -msgstr "Неподдерживаемый символ формата '%c' (0x%x) при индексе %d" +#~ msgid "cannot create instance" +#~ msgstr "Не удается создать экземпляр" -#: py/runtime.c -msgid "unsupported type for %q: '%s'" -msgstr "неподдерживаемый тип для %q: '%s'" +#~ msgid "native method too big" +#~ msgstr "родной метод слишком большой" -#: py/runtime.c -msgid "unsupported type for operator" -msgstr "Неподдерживаемый тип для оператора" +#~ msgid "ulonglong too large" +#~ msgstr "голова длинная слишком большая" -#: py/runtime.c -msgid "unsupported types for %q: '%q', '%q'" -msgstr "Неподдерживаемые типы для %q: '%q', '%q'" +#~ msgid "font must be 2048 bytes long" +#~ msgstr "Длина шрифта должна составлять 2048 байт" -#: extmod/ulab/code/numpy/io/io.c -msgid "usecols is too high" -msgstr "Usecols слишком высок" +#~ msgid "graphic must be 2048 bytes long" +#~ msgstr "Длина рисунка должна составлять 2048 байт" -#: extmod/ulab/code/numpy/io/io.c -msgid "usecols keyword must be specified" -msgstr "Ключевое слово usecols должно быть указано" +#~ msgid "palette must be 32 bytes long" +#~ msgstr "Длина палитры должна составлять 32 байта" -#: py/objint.c #, c-format -msgid "value must fit in %d byte(s)" -msgstr "Значение должно совпадать с байтами %d" +#~ msgid "Buffer + offset too small %d %d %d" +#~ msgstr "Буфер + сдвиг слишком малы %d %d %d" -#: shared-bindings/bitmaptools/__init__.c -msgid "value out of range of target" -msgstr "Величина выходящая за пределы диапазона цели" +#~ msgid "Byte buffer must be 16 bytes." +#~ msgstr "Буфер байтов должен быть размером 16 байтам." -#: extmod/moddeflate.c -#, fuzzy -msgid "wbits" -msgstr "wbits" +#~ msgid "UUID integer value must be 0-0xffff" +#~ msgstr "Целое значение UUID должно быть равно 0-0xffff" -#: shared-bindings/bitmapfilter/__init__.c -msgid "" -"weights must be a sequence with an odd square number of elements (usually 9 " -"or 25)" -msgstr "" -"Весом должна быть последовательность с нечетным квадратным числом элементов " -"(обычно 9 или 25)" +#~ msgid "initial_value length is wrong" +#~ msgstr "длина первоначального_значения ошибочна" -#: shared-bindings/bitmapfilter/__init__.c -msgid "weights must be an object of type %q, %q, %q, or %q, not %q " -msgstr "Веса должны быть объектом типа %q, %q, %q или %q, а не %q " +#, c-format +#~ msgid "Invalid byte %.*s" +#~ msgstr "Неверный байт %.*s" -#: shared-bindings/is31fl3741/FrameBuffer.c -msgid "width must be greater than zero" -msgstr "ширина должна быть больше нуля" +#~ msgid "Key not found" +#~ msgstr "Ключ не найден" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/raspberrypi/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "wifi is not enabled" -msgstr "Wi-Fi не включен" +#~ msgid "Not supported JPEG standard" +#~ msgstr "Не поддерживается Стандарт JPEG" -#: ports/raspberrypi/common-hal/wifi/Monitor.c -msgid "wifi.Monitor not available" -msgstr "Wi-Fi. Монитор недоступен" +#~ msgid "%q moved from %q to %q" +#~ msgstr "%q переместился из %q в %q" -#: shared-bindings/_bleio/Adapter.c -msgid "window must be <= interval" -msgstr "окно должно быть <= интервал" +#~ msgid "filesystem must provide mount method" +#~ msgstr "Файловая система должна предусматривать метод монтирования" -#: extmod/ulab/code/numpy/numerical.c -msgid "wrong axis index" -msgstr "Неправильный индекс оси" +#~ msgid "start/end indices" +#~ msgstr "Начальные/конечные индексы" -#: extmod/ulab/code/numpy/create.c -msgid "wrong axis specified" -msgstr "Указана неправильная ось" +#, c-format +#~ msgid "%%c requires int or char" +#~ msgstr "%%c требует int или char" -#: extmod/ulab/code/numpy/io/io.c -msgid "wrong dtype" -msgstr "Неправильный тип" +#~ msgid "'%q' object is not callable" +#~ msgstr "Объект '%q' не является вызываемым" -#: extmod/ulab/code/numpy/transform.c -msgid "wrong index type" -msgstr "Неправильный тип индекса" +#~ msgid "cannot create '%q' instances" +#~ msgstr "Не удается создать экземпляры '%q'" -#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/numpy/create.c -#: extmod/ulab/code/numpy/io/io.c extmod/ulab/code/numpy/transform.c -#: extmod/ulab/code/numpy/vector.c -msgid "wrong input type" -msgstr "Неправильный тип ввода" +#~ msgid "non-hex digit found" +#~ msgstr "Ненайдена шестнадцатеричная цифра" -#: extmod/ulab/code/numpy/transform.c -msgid "wrong length of condition array" -msgstr "неправильная длина массива состояния" +#~ msgid "not all arguments converted during string formatting" +#~ msgstr "Не все аргументы преобразуются при форматировании строки" -#: extmod/ulab/code/numpy/transform.c -msgid "wrong length of index array" -msgstr "неправильная длина массива индексов" +#~ msgid "not enough arguments for format string" +#~ msgstr "Недостаточно аргументов для строки форматирования" -#: extmod/ulab/code/numpy/create.c py/objarray.c py/objstr.c -msgid "wrong number of arguments" -msgstr "неправильное количество аргументов" +#~ msgid "odd-length string" +#~ msgstr "Строка нечетной длины" -#: py/runtime.c -msgid "wrong number of values to unpack" -msgstr "Неправильное количество значений для распаковки" +#~ msgid "raw f-strings are not supported" +#~ msgstr "Необработанные F-строки не поддерживаются" -#: extmod/ulab/code/numpy/vector.c -msgid "wrong output type" -msgstr "неверный тип вывода" +#~ msgid "Unsupported format" +#~ msgstr "Неподдерживаемый формат" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "zi must be an ndarray" -msgstr "зи, должно быть, массивом ndarray" +#~ msgid "Wifi is not enabled" +#~ msgstr "Wifi не включен" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "zi must be of float type" -msgstr "zi должно быть типа float" +#~ msgid "wifi is not enabled" +#~ msgstr "Wi-Fi не включен" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "zi must be of shape (n_section, 2)" -msgstr "zi должен иметь форму (n_section, 2)" +#~ msgid "Cannot remount '/' when visible via USB." +#~ msgstr "Невозможно перемонтировать '/' пока он виден через USB." #~ msgid "%q must be a %q object, %q, or %q" #~ msgstr "%q должен быть объектом %q, %q или %q" @@ -4783,7 +5582,7 @@ msgstr "zi должен иметь форму (n_section, 2)" #~ msgid "'continue' outside loop" #~ msgstr "«продолжить» вне цикла" -#~ msgid "'coroutine' object is not an iterator" +#~ msgid "'coroutine' object isn't an iterator" #~ msgstr "Объект 'coroutine' не является итератором" #~ msgid "(x,y) integers required" @@ -4978,8 +5777,8 @@ msgstr "zi должен иметь форму (n_section, 2)" #~ msgstr "IV должен быть длиной %d байт" #~ msgid "" -#~ "Incompatible .mpy file. Please update all .mpy files. See http://adafru." -#~ "it/mpy-update for more info." +#~ "Incompatible .mpy file. Please update all .mpy files. See http://" +#~ "adafru.it/mpy-update for more info." #~ msgstr "" #~ "Несовместимый файл .mpy. Пожалуйста, обновите все файлы .mpy. См. http://" #~ "adafru.it/mpy-update для получения дополнительной информации." diff --git a/locale/sv.po b/locale/sv.po index 0dd1bfabf88..cfdbaa3064b 100644 --- a/locale/sv.po +++ b/locale/sv.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: 2024-01-15 16:06+0000\n" -"Last-Translator: Jonny Bergdahl \n" +"PO-Revision-Date: 2025-06-15 23:04+0000\n" +"Last-Translator: Jonny Bergdahl \n" "Language-Team: LANGUAGE \n" "Language: sv\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 5.4-dev\n" +"X-Generator: Weblate 5.12-dev\n" #: main.c msgid "" @@ -94,7 +94,7 @@ msgstr "" msgid "%q and %q contain duplicate pins" msgstr "%q och %q innehåller duplicerade pinnar" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: shared-bindings/audioio/AudioOut.c msgid "%q and %q must be different" msgstr "%q och %q måste vara olika" @@ -104,7 +104,7 @@ msgstr "%q och %q måste dela klockenhet" #: ports/nordic/common-hal/watchdog/WatchDogTimer.c msgid "%q cannot be changed once mode is set to %q" -msgstr "" +msgstr "%q kan inte ändras efter att läge satts till %q" #: shared-bindings/microcontroller/Pin.c msgid "%q contains duplicate pins" @@ -114,6 +114,10 @@ msgstr "%q innehåller dubblettstift" msgid "%q failure: %d" msgstr "%q-fel: %d" +#: shared-module/audiodelays/MultiTapDelay.c +msgid "%q in %q must be of type %q or %q, not %q" +msgstr "%q in %1 måste vara av typ %q eller %q, inte %q" + #: py/argcheck.c shared-module/audiofilters/Filter.c msgid "%q in %q must be of type %q, not %q" msgstr "%q i %q måste vara av typen %q, inte %q" @@ -166,7 +170,7 @@ msgstr "längden på %q måste vara <= %d" msgid "%q length must be >= %d" msgstr "längden på %q måste vara >= %d" -#: py/modsys.c py/objmodule.c py/runtime.c +#: py/modsys.c py/runtime.c msgid "%q moved from %q to %q" msgstr "%q flyttad från %q till %q" @@ -229,7 +233,7 @@ msgstr "%q måste vara en multipel av 8." #: shared-bindings/bitmapfilter/__init__.c shared-bindings/canio/CAN.c #: shared-bindings/digitalio/Pull.c shared-bindings/supervisor/__init__.c #: shared-module/audiofilters/Filter.c shared-module/displayio/__init__.c -#: shared-module/synthio/Biquad.c shared-module/synthio/Synthesizer.c +#: shared-module/synthio/Synthesizer.c msgid "%q must be of type %q or %q, not %q" msgstr "%q måste vara av typen %q eller %q, inte %q" @@ -238,6 +242,7 @@ msgid "%q must be of type %q, %q, or %q, not %q" msgstr "%q måste vara av typen %q, %q, eller %q, inte %q" #: py/argcheck.c py/runtime.c shared-bindings/bitmapfilter/__init__.c +#: shared-module/audiodelays/MultiTapDelay.c shared-module/synthio/Note.c #: shared-module/synthio/__init__.c msgid "%q must be of type %q, not %q" msgstr "%q måste vara av typen %q, inte %q" @@ -318,7 +323,7 @@ msgid "'%q' object does not support '%q'" msgstr "Objektet '%q' stöder inte '%q'" #: py/runtime.c -msgid "'%q' object is not an iterator" +msgid "'%q' object isn't an iterator" msgstr "Objektet '%q' är inte en iterator" #: py/objtype.c py/runtime.c shared-module/atexit/__init__.c @@ -326,13 +331,13 @@ msgid "'%q' object is not callable" msgstr "Objektet '%q' kan inte anropas" #: py/runtime.c -msgid "'%q' object is not iterable" +msgid "'%q' object isn't iterable" msgstr "Objektet '%q' är inte itererbart" #: py/emitinlinethumb.c py/emitinlinextensa.c #, c-format msgid "'%s' expects a label" -msgstr "'%s' förväntar sig en label" +msgstr "'%s' förväntar sig en etikett" #: py/emitinlinethumb.c py/emitinlinextensa.c #, c-format @@ -432,7 +437,7 @@ msgstr "'label' kräver 1 argument" #: py/emitnative.c msgid "'not' not implemented" -msgstr "" +msgstr "'not' är inte implementerat" #: py/compile.c msgid "'return' outside function" @@ -456,7 +461,7 @@ msgstr "*x måste vara mål för tilldelning" #: py/obj.c msgid ", in %q\n" -msgstr ", i %q\n" +msgstr ", i%q\n" #: shared-bindings/busdisplay/BusDisplay.c #: shared-bindings/epaperdisplay/EPaperDisplay.c @@ -567,7 +572,7 @@ msgstr "Har redan lyssnare för all-matchningar" #: ports/espressif/common-hal/_bleio/__init__.c msgid "Already in progress" -msgstr "" +msgstr "Pågår redan" #: ports/espressif/bindings/espnow/ESPNow.c #: ports/espressif/common-hal/espulp/ULP.c @@ -607,7 +612,7 @@ msgstr "Matrisvärden ska bestå av enstaka bytes." #: ports/atmel-samd/common-hal/spitarget/SPITarget.c msgid "Async SPI transfer in progress on this bus, keep awaiting." -msgstr "" +msgstr "Async SPI-överföring pågår på denna buss, forsätter vänta." #: shared-module/memorymonitor/AllocationAlarm.c #, c-format @@ -621,7 +626,7 @@ msgstr "Ljudkonvertering inte implementerad" #: ports/raspberrypi/common-hal/audiobusio/I2SOut.c #: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c msgid "Audio source error" -msgstr "" +msgstr "Fel på ljudkälla" #: shared-bindings/wifi/Radio.c msgid "AuthMode.OPEN is not used with password" @@ -640,8 +645,8 @@ msgid "" "Auto-reload is on. Simply save files over USB to run them or enter REPL to " "disable.\n" msgstr "" -"Autoladdning är på. Spara filer via USB för att köra dem eller ange REPL för " -"att inaktivera.\n" +"Autoladdning är på. Spara filer via USB för att köra dem eller gå till REPL " +"för att inaktivera.\n" #: ports/espressif/common-hal/canio/CAN.c msgid "Baudrate not supported by peripheral" @@ -698,7 +703,7 @@ msgstr "Buffertlängd %d för stor. Den måste vara mindre än %d" #: shared-module/sdcardio/SDCard.c #, c-format msgid "Buffer must be a multiple of %d bytes" -msgstr "" +msgstr "Buffer måste vara multipel av %d byte" #: shared-bindings/_bleio/PacketBuffer.c #, c-format @@ -759,7 +764,7 @@ msgstr "Kan bara larma från djup sömn på två låga pinnar." #: ports/espressif/common-hal/audioio/AudioOut.c msgid "Can't construct AudioOut because continuous channel already open" -msgstr "" +msgstr "Kan inte skapa AudioOut eftersom kontinuerlig kanal redan är öppen" #: ports/espressif/common-hal/_bleio/Characteristic.c #: ports/nordic/common-hal/_bleio/Characteristic.c @@ -807,8 +812,8 @@ msgid "Cannot record to a file" msgstr "Det går inte att spela in till en fil" #: shared-module/storage/__init__.c -msgid "Cannot remount '/' when visible via USB." -msgstr "Det går inte att montera om '/' när den är synlig via USB." +msgid "Cannot remount path when visible via USB." +msgstr "Kan inte montera sökväg när den är åtkomlig via USB." #: shared-bindings/digitalio/DigitalInOut.c msgid "Cannot set value when direction is input." @@ -825,7 +830,7 @@ msgstr "Det går inte att subklassa slice" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "Cannot use GPIO0..15 together with GPIO32..47" -msgstr "" +msgstr "Kan inte använda GPIO0..15 tillsammans med GPIO32..47" #: ports/nordic/common-hal/alarm/pin/PinAlarm.c msgid "Cannot wake on pin edge, only level" @@ -863,6 +868,10 @@ msgstr "Arrayer för koordinater har olika längd" msgid "Coordinate arrays types have different sizes" msgstr "Arrayer för koordinater har olika storlek" +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "Could not publish to ROS topic" +msgstr "Kan inte publicera till ROS topic" + #: shared-bindings/_bleio/Adapter.c msgid "Could not set address" msgstr "Kan inte ange adress" @@ -875,6 +884,11 @@ msgstr "Det gick inte att starta avbrott, RX upptagen" msgid "Couldn't allocate decoder" msgstr "Det gick inte att allokera avkodaren" +#: ports/espressif/common-hal/rclcpy/__init__.c +#, c-format +msgid "Critical ROS failure during soft reboot, reset required: %d" +msgstr "Kritiskt ROS-fel vid mjuk omstart, reset krävs: %d" + #: ports/stm/common-hal/analogio/AnalogOut.c msgid "DAC Channel Init Error" msgstr "Initieringsfel för DAC-kanal" @@ -1027,23 +1041,23 @@ msgstr "Det gick inte att ansluta: timeout" #: ports/espressif/common-hal/audioio/AudioOut.c msgid "Failed to create continuous channels: invalid arg" -msgstr "" +msgstr "Kan inte skapa kontinuerliga kanaler: ogiltigt argument" #: ports/espressif/common-hal/audioio/AudioOut.c msgid "Failed to create continuous channels: invalid state" -msgstr "" +msgstr "Det gick inte att skapa kontinuerliga kanaler: ogiltigt läge" #: ports/espressif/common-hal/audioio/AudioOut.c msgid "Failed to create continuous channels: no mem" -msgstr "" +msgstr "Det gick inte att skapa kontinuerliga kanaler: Inget minne" #: ports/espressif/common-hal/audioio/AudioOut.c msgid "Failed to create continuous channels: not found" -msgstr "" +msgstr "Det gick inte att skapa kontinuerliga kanaler: inte funnen" #: ports/espressif/common-hal/audioio/AudioOut.c msgid "Failed to enable continuous" -msgstr "" +msgstr "Kan inte skapa kontinuerlig" #: shared-module/audiomp3/MP3Decoder.c msgid "Failed to parse MP3 file" @@ -1051,7 +1065,7 @@ msgstr "Det gick inte att tolka MP3-filen" #: ports/espressif/common-hal/audioio/AudioOut.c msgid "Failed to register continuous events callback" -msgstr "" +msgstr "Kan inte registrera kontinuerlig händelsers callback" #: ports/nordic/sd_mutex.c #, c-format @@ -1060,11 +1074,11 @@ msgstr "Det gick inte att frigöra mutex, fel 0x%04x" #: ports/zephyr-cp/common-hal/wifi/Radio.c msgid "Failed to set hostname" -msgstr "" +msgstr "Kan inte sätta värdnamn" #: ports/espressif/common-hal/audioio/AudioOut.c msgid "Failed to start async audio" -msgstr "" +msgstr "Kan inte starta async audio" #: supervisor/shared/safe_mode.c msgid "Failed to write internal flash." @@ -1074,6 +1088,7 @@ msgstr "Det gick inte att skriva till intern flash." msgid "File exists" msgstr "Filen finns redan" +#: shared-bindings/supervisor/__init__.c shared-module/lvfontio/OnDiskFont.c #: shared-module/os/getenv.c msgid "File not found" msgstr "Filen hittades inte" @@ -1105,7 +1120,7 @@ msgstr "För L8-färgrymden måste indatabitmappen ha 8 bitar per pixel" msgid "For RGB colorspaces, input bitmap must have 16 bits per pixel" msgstr "För RGB-färgrymder måste indatabitmappen ha 16 bitar per pixel" -#: ports/cxd56/common-hal/camera/Camera.c +#: ports/cxd56/common-hal/camera/Camera.c shared-module/audiocore/WaveFile.c msgid "Format not supported" msgstr "Format stöds inte" @@ -1249,7 +1264,7 @@ msgstr "Internt fel #%d" #: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c #: shared-bindings/pwmio/PWMOut.c msgid "Internal resource(s) in use" -msgstr "" +msgstr "Intern(a) resurs(er) används redan" #: supervisor/shared/safe_mode.c msgid "Internal watchdog timer expired." @@ -1273,14 +1288,16 @@ msgstr "Avbruten av utgångsfunktion" #: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c py/argcheck.c #: shared-bindings/digitalio/DigitalInOut.c #: shared-bindings/epaperdisplay/EPaperDisplay.c shared-bindings/pwmio/PWMOut.c +#: shared-bindings/supervisor/__init__.c #: shared-module/aurora_epaper/aurora_framebuffer.c +#: shared-module/lvfontio/OnDiskFont.c msgid "Invalid %q" msgstr "Ogiltig %q" #: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c #: shared-module/aurora_epaper/aurora_framebuffer.c msgid "Invalid %q and %q" -msgstr "" +msgstr "Ogiltig %q och %q" #: ports/atmel-samd/common-hal/microcontroller/Pin.c #: ports/espressif/common-hal/dotclockframebuffer/DotClockFramebuffer.c @@ -1306,6 +1323,10 @@ msgstr "Ogiltig BSSID" msgid "Invalid MAC address" msgstr "Ogiltig MAC-adress" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "Invalid ROS domain ID" +msgstr "Ogiltigt ROS domän-id" + #: ports/espressif/common-hal/espidf/__init__.c py/moderrno.c msgid "Invalid argument" msgstr "Ogiltigt argument" @@ -1384,7 +1405,7 @@ msgstr "Layer måste vara en underklass av Group eller TileGrid" #: shared-bindings/audiocore/RawSample.c msgid "Length of %q must be an even multiple of channel_count * type_size" -msgstr "" +msgstr "Längden på %q måste vara en jämn multipel av channel_count * type_size" #: ports/espressif/common-hal/espidf/__init__.c msgid "MAC address was invalid" @@ -1393,7 +1414,12 @@ msgstr "MAC-adressen var ogiltig" #: ports/espressif/common-hal/_bleio/Characteristic.c #: ports/espressif/common-hal/_bleio/Descriptor.c msgid "MITM security not supported" -msgstr "" +msgstr "MITM-säkerhet stöds inte" + +#: ports/stm/common-hal/sdioio/SDCard.c +#, c-format +msgid "MMC/SDIO Clock Error %x" +msgstr "Fel på MMC/SDIO-klocka: %x" #: shared-bindings/is31fl3741/IS31FL3741.c msgid "Mapping must be a tuple" @@ -1438,7 +1464,7 @@ msgstr "Saknad jmp_pin. %q[%u] hoppar på pin" #: shared-module/storage/__init__.c msgid "Mount point directory missing" -msgstr "" +msgstr "Katalog för monteringspunkt saknas" #: ports/zephyr-cp/bindings/zephyr_serial/UART.c shared-bindings/busio/UART.c #: shared-bindings/displayio/Group.c @@ -1526,7 +1552,7 @@ msgstr "Ingen IP" #: ports/cxd56/common-hal/microcontroller/__init__.c #: ports/mimxrt10xx/common-hal/microcontroller/__init__.c msgid "No bootloader present" -msgstr "" +msgstr "Bootloader saknas" #: shared-module/usb/core/Device.c msgid "No configuration set" @@ -1581,6 +1607,10 @@ msgstr "Ingen pull-up hittades på SDA eller SCL; kontrollera inkopplingen" msgid "No pulldown on pin; 1Mohm recommended" msgstr "Ingen pulldown på pinnen; 1Mohm rekommenderas" +#: shared-module/touchio/TouchIn.c +msgid "No pullup on pin; 1Mohm recommended" +msgstr "Pullup saknas på pinne; 1MOhm rekommenderas" + #: py/moderrno.c msgid "No space left on device" msgstr "Inget utrymme kvar på enheten" @@ -1628,7 +1658,7 @@ msgstr "JPEG-standard stöds ej" #: ports/espressif/common-hal/sdioio/SDCard.c #, c-format msgid "Number of data_pins must be %d or %d, not %d" -msgstr "" +msgstr "Antal för data_pins måste vara %d eller %d, inte %d" #: shared-bindings/util.c msgid "" @@ -1755,7 +1785,7 @@ msgstr "PWM-segmentkanal A används redan" #: shared-bindings/spitarget/SPITarget.c msgid "Packet buffers for an SPI transfer must have the same length." -msgstr "" +msgstr "Paketbuffertar för en SPI-överföring måste ha samma längd." #: shared-module/jpegio/JpegDecoder.c msgid "Parameter error" @@ -1859,6 +1889,10 @@ msgstr "Programstorlek ogiltig" msgid "Program too long" msgstr "Programmet är för långt" +#: shared-bindings/rclcpy/Publisher.c +msgid "Publishers can only be created from a parent node" +msgstr "Publicerare kan bara skapas from föräldranod" + #: shared-bindings/digitalio/DigitalInOut.c msgid "Pull not used when direction is output." msgstr "Pull används inte när riktningen är output." @@ -1879,6 +1913,26 @@ msgstr "RNG DeInit-fel" msgid "RNG Init Error" msgstr "RNG Init-fel" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS failed to initialize. Is agent connected?" +msgstr "Fel vid ROS initialisering, är agent ansluten?" + +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS internal setup failure" +msgstr "Fel vid ROS intern inställning" + +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS memory allocator failure" +msgstr "Fel vid ROS minnesallokering" + +#: ports/espressif/common-hal/rclcpy/Node.c +msgid "ROS node failed to initialize" +msgstr "Fel vid ROS-nods initialisering" + +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "ROS topic failed to initialize" +msgstr "Fel vid initialisering av ROS topic" + #: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c #: ports/nordic/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c msgid "RS485" @@ -1961,7 +2015,7 @@ msgstr "SDIO GetCardInfo-fel %d" #: ports/stm/common-hal/sdioio/SDCard.c #, c-format msgid "SDIO Init Error %x" -msgstr "" +msgstr "SDIO Init Fel %x" #: ports/espressif/common-hal/busio/SPI.c msgid "SPI configuration failed" @@ -2010,6 +2064,7 @@ msgstr "Slice och värde har olika längd." #: shared-bindings/displayio/TileGrid.c #: shared-bindings/memorymonitor/AllocationSize.c #: shared-bindings/pulseio/PulseIn.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c msgid "Slices not supported" msgstr "Slice stöds inte" @@ -2029,7 +2084,7 @@ msgstr "Ange en av data0 eller data_pins" #: supervisor/shared/safe_mode.c msgid "Stack overflow. Increase stack size." -msgstr "" +msgstr "Stack overflow. Öka stackstorleken." #: shared-bindings/alarm/time/TimeAlarm.c msgid "Supply one of monotonic_time or epoch_time" @@ -2057,7 +2112,7 @@ msgstr "Längden på rgb_pins vara 6, 12, 18, 24 eller 30" #: shared-module/audiocore/__init__.c msgid "The sample's %q does not match" -msgstr "" +msgstr "Prov %q matchar inte" #: supervisor/shared/safe_mode.c msgid "Third-party firmware fatal error." @@ -2079,7 +2134,9 @@ msgstr "" msgid "Tile height must exactly divide bitmap height" msgstr "Tile-höjden måste vara jämnt delbar med höjd på bitmap" -#: shared-bindings/displayio/TileGrid.c shared-module/displayio/TileGrid.c +#: shared-bindings/displayio/TileGrid.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-module/displayio/TileGrid.c msgid "Tile index out of bounds" msgstr "Tile-index utanför gräns" @@ -2087,6 +2144,10 @@ msgstr "Tile-index utanför gräns" msgid "Tile width must exactly divide bitmap width" msgstr "Tile-bredd måste vara jämnt delbar med bredd på bitmap" +#: shared-module/tilepalettemapper/TilePaletteMapper.c +msgid "TilePaletteMapper may only be bound to a TileGrid once" +msgstr "TilePaletteMapper får bara bindas till ett TileGrid en gång" + #: shared-bindings/alarm/time/TimeAlarm.c msgid "Time is in the past." msgstr "Tid har passerats." @@ -2107,7 +2168,7 @@ msgstr "För många kanaler i sampling." #: ports/espressif/common-hal/_bleio/Characteristic.c msgid "Too many descriptors" -msgstr "" +msgstr "För många beskrivningar" #: shared-module/displayio/__init__.c msgid "Too many display busses; forgot displayio.release_displays() ?" @@ -2133,7 +2194,7 @@ msgstr "Traceback (senaste anrop):\n" #: ports/stm/common-hal/busio/UART.c msgid "UART de-init" -msgstr "UART omstart" +msgstr "Avinitiering av UART" #: ports/cxd56/common-hal/busio/UART.c ports/espressif/common-hal/busio/UART.c #: ports/stm/common-hal/busio/UART.c @@ -2220,6 +2281,7 @@ msgstr "Det går inte att läsa färgpalettdata" #: ports/mimxrt10xx/common-hal/canio/CAN.c msgid "Unable to send CAN Message: all Tx message buffers are busy" msgstr "" +"Kan inte skicka CAN-meddelande: alla Tx-meddelandebuffertar är upptagna" #: ports/espressif/common-hal/mdns/Server.c #: ports/raspberrypi/common-hal/mdns/Server.c @@ -2315,10 +2377,6 @@ msgstr "Färgrymd stöds inte" msgid "Unsupported display bus type" msgstr "Busstyp för display stöds inte" -#: shared-module/audiocore/WaveFile.c -msgid "Unsupported format" -msgstr "Format stöds inte" - #: shared-bindings/hashlib/__init__.c msgid "Unsupported hash algorithm" msgstr "Hash-algoritmen stöds inte" @@ -2326,12 +2384,12 @@ msgstr "Hash-algoritmen stöds inte" #: ports/espressif/common-hal/socketpool/Socket.c #: ports/zephyr-cp/common-hal/socketpool/Socket.c msgid "Unsupported socket type" -msgstr "" +msgstr "Sockettyp stöds ej" #: ports/espressif/common-hal/_bleio/Adapter.c #: ports/espressif/common-hal/dualbank/__init__.c msgid "Update failed" -msgstr "" +msgstr "Uppdatering misslyckades" #: ports/espressif/common-hal/_bleio/Characteristic.c #: ports/nordic/common-hal/_bleio/Characteristic.c @@ -2380,8 +2438,10 @@ msgstr "" msgid "Wi-Fi: " msgstr "Wi-Fi: " +#: ports/espressif/common-hal/wifi/Radio.c #: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "Wifi is not enabled" +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "WiFi is not enabled" msgstr "WiFi är inte aktiverat" #: main.c @@ -2420,7 +2480,7 @@ msgstr "Du tryckte ner BOOT-knappen vid start" #: ports/espressif/boards/adafruit_itsybitsy_esp32/mpconfigboard.h #: ports/espressif/boards/waveshare_esp32_c6_lcd_1_47/mpconfigboard.h msgid "You pressed the BOOT button at start up." -msgstr "" +msgstr "Du tryckte på BOOT-knappen vid start." #: ports/espressif/boards/adafruit_huzzah32_breakout/mpconfigboard.h msgid "You pressed the GPIO0 button at start up." @@ -2481,7 +2541,7 @@ msgstr "adresserna är tomma" #: ports/espressif/common-hal/audioio/AudioOut.c msgid "already playing" -msgstr "" +msgstr "spelas redan" #: py/compile.c msgid "annotation must be an identifier" @@ -2509,7 +2569,7 @@ msgstr "argsort är inte implementerad för tillplattade matriser" #: extmod/ulab/code/numpy/random/random.c msgid "argument must be None, an integer or a tuple of integers" -msgstr "" +msgstr "argument måste vara None, en integer eller en tuple av heltal" #: py/compile.c msgid "argument name reused" @@ -2563,7 +2623,7 @@ msgstr "Attribut stöds ej" #: ports/espressif/common-hal/audioio/AudioOut.c msgid "audio format not supported" -msgstr "" +msgstr "audioformatet stöds inte" #: extmod/ulab/code/ulab_tools.c msgid "axis is out of bounds" @@ -2603,11 +2663,11 @@ msgstr "binär op %q är inte implementerad" #: ports/espressif/common-hal/audiobusio/PDMIn.c msgid "bit_depth must be 8, 16, 24, or 32." -msgstr "" +msgstr "bit_depth måste vara 8, 16, 24, or 32." #: shared-module/bitmapfilter/__init__.c msgid "bitmap size and depth must match" -msgstr "" +msgstr "bitmaps size och depth måste matcha" #: shared-bindings/bitmaptools/__init__.c msgid "bitmap sizes must match" @@ -2617,9 +2677,16 @@ msgstr "bitmappsstorlekar måste matcha" msgid "bits must be 32 or less" msgstr "bits måste vara 32 eller färre" -#: shared-bindings/audiodelays/Echo.c shared-bindings/audiodelays/PitchShift.c +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "bits_per_sample must be 16" +msgstr "bits_per_sample måste vara 16" + +#: shared-bindings/audiodelays/Chorus.c shared-bindings/audiodelays/Echo.c +#: shared-bindings/audiodelays/MultiTapDelay.c +#: shared-bindings/audiodelays/PitchShift.c #: shared-bindings/audiofilters/Distortion.c -#: shared-bindings/audiofilters/Filter.c shared-bindings/audiomixer/Mixer.c +#: shared-bindings/audiofilters/Filter.c shared-bindings/audiofilters/Phaser.c +#: shared-bindings/audiomixer/Mixer.c msgid "bits_per_sample must be 8 or 16" msgstr "bits_per_sample måste vara 8 eller 16" @@ -2757,7 +2824,7 @@ msgstr "kan inte göra binära op mellan '%q' och '%q'" #: py/emitnative.c msgid "can't do unary op of '%q'" -msgstr "" +msgstr "kan inte göra unary operation av '%q'" #: py/emitnative.c msgid "can't implicitly convert '%q' to 'bool'" @@ -3164,7 +3231,7 @@ msgid "format" msgstr "format" #: py/objstr.c -msgid "format requires a dict" +msgid "format needs a dict" msgstr "formatet kräver en dict" #: py/objdeque.c @@ -3625,7 +3692,7 @@ msgid "must use keyword argument for key function" msgstr "måste använda nyckelordsargument för nyckelfunktion" #: py/runtime.c -msgid "name '%q' is not defined" +msgid "name '%q' isn't defined" msgstr "namnet '%q' är inte definierat" #: py/runtime.c @@ -3634,7 +3701,7 @@ msgstr "namn inte definierat" #: py/qstr.c msgid "name too long" -msgstr "" +msgstr "namn för långt" #: py/persistentcode.c msgid "native code in .mpy unsupported" @@ -3900,7 +3967,7 @@ msgstr "matrisen för out är för liten" #: extmod/ulab/code/numpy/random/random.c msgid "out has wrong type" -msgstr "" +msgstr "out har fel typ" #: extmod/ulab/code/numpy/vector.c msgid "out keyword is not supported for complex dtype" @@ -3928,11 +3995,11 @@ msgstr "utanför räckvidd för target" #: extmod/ulab/code/numpy/random/random.c msgid "output array has wrong type" -msgstr "" +msgstr "output array har fel typ" #: extmod/ulab/code/numpy/random/random.c msgid "output array must be contiguous" -msgstr "" +msgstr "output array måste vara kontinuerlig" #: py/objint_mpz.c msgid "overflow converting long int to machine word" @@ -4043,6 +4110,10 @@ msgstr "argumentet roll måste vara en ndarray" msgid "rsplit(None,n)" msgstr "rsplit(None,n)" +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "samples_signed must be true" +msgstr "samples_signed måste vara sann" + #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c #: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "sampling rate out of range" @@ -4050,7 +4121,7 @@ msgstr "samplingsfrekvens utanför räckvidden" #: py/modmicropython.c msgid "schedule queue full" -msgstr "schemakön full" +msgstr "schemakö full" #: py/builtinimport.c msgid "script compilation not supported" @@ -4062,7 +4133,7 @@ msgstr "set stöds inte" #: extmod/ulab/code/numpy/random/random.c msgid "shape must be None, and integer or a tuple of integers" -msgstr "" +msgstr "shape måste vara None, integer eller en tuple av integers" #: extmod/ulab/code/ndarray.c msgid "shape must be integer or tuple of integers" @@ -4086,7 +4157,7 @@ msgstr "storlek är enbart definierad ndarrays" #: extmod/ulab/code/numpy/random/random.c msgid "size must match out.shape when used together" -msgstr "" +msgstr "size måste matcha out.shape när dom används tillsammans" #: py/nativeglue.c msgid "slice unsupported" @@ -4187,12 +4258,12 @@ msgstr "timeout måste vara < 655,35 sekunder" #: ports/raspberrypi/common-hal/floppyio/__init__.c msgid "timeout waiting for flux" -msgstr "" +msgstr "tidsgräns överskriden vid väntan på flux" #: ports/raspberrypi/common-hal/floppyio/__init__.c #: shared-module/floppyio/__init__.c msgid "timeout waiting for index pulse" -msgstr "" +msgstr "Tidsgräns överskriden vid väntan på indexpuls" #: shared-module/sdcardio/SDCard.c msgid "timeout waiting for v1 card" @@ -4262,11 +4333,11 @@ msgid "tx and rx cannot both be None" msgstr "tx och rx kan inte båda vara None" #: py/objtype.c -msgid "type '%q' is not an acceptable base type" +msgid "type '%q' isn't an acceptable base type" msgstr "typ '%q' är inte en acceptabel bastyp" #: py/objtype.c -msgid "type is not an acceptable base type" +msgid "type isn't an acceptable base type" msgstr "typ är inte en acceptabel bastyp" #: py/runtime.c @@ -4328,7 +4399,9 @@ msgstr "Omatchad '%c' i format" msgid "unreadable attribute" msgstr "attribut kan inte läsas" -#: shared-bindings/displayio/TileGrid.c shared-bindings/vectorio/VectorShape.c +#: shared-bindings/displayio/TileGrid.c shared-bindings/terminalio/Terminal.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-bindings/vectorio/VectorShape.c msgid "unsupported %q type" msgstr "typ %q stöds inte" @@ -4344,7 +4417,7 @@ msgstr "Xtensa-instruktion '%s' med %d argument stöds inte" #: shared-module/bitmapfilter/__init__.c msgid "unsupported bitmap depth" -msgstr "" +msgstr "Bitmapps­djupet stöds inte" #: shared-module/gifio/GifWriter.c msgid "unsupported colorspace for GifWriter" @@ -4397,21 +4470,17 @@ msgid "" "weights must be a sequence with an odd square number of elements (usually 9 " "or 25)" msgstr "" +"vikterna måste vara en sekvens med ett udda kvadrattal antal element " +"(vanligtvis 9 eller 25)" #: shared-bindings/bitmapfilter/__init__.c msgid "weights must be an object of type %q, %q, %q, or %q, not %q " -msgstr "" +msgstr "Vikter måste vara ett objekt av typen %q, %q, %q eller %q, inte %q " #: shared-bindings/is31fl3741/FrameBuffer.c msgid "width must be greater than zero" msgstr "width måste vara större än noll" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/raspberrypi/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "wifi is not enabled" -msgstr "WiFi är inte aktiverat" - #: ports/raspberrypi/common-hal/wifi/Monitor.c msgid "wifi.Monitor not available" msgstr "wifi.Monitor är inte tillgänglig" @@ -4474,6 +4543,18 @@ msgstr "zi måste vara av typ float" msgid "zi must be of shape (n_section, 2)" msgstr "zi måste vara i formen (n_section, 2)" +#~ msgid "Unsupported format" +#~ msgstr "Format stöds inte" + +#~ msgid "Wifi is not enabled" +#~ msgstr "WiFi är inte aktiverat" + +#~ msgid "wifi is not enabled" +#~ msgstr "WiFi är inte aktiverat" + +#~ msgid "Cannot remount '/' when visible via USB." +#~ msgstr "Det går inte att montera om '/' när den är synlig via USB." + #~ msgid "Data chunk must follow fmt chunk" #~ msgstr "Datasegmentet måste följa fmt-segmentet" @@ -4842,13 +4923,13 @@ msgstr "zi måste vara i formen (n_section, 2)" #~ msgid "'%s' object does not support item deletion" #~ msgstr "Objektet '%s' stöder inte borttagning av objekt" -#~ msgid "'%s' object is not an iterator" +#~ msgid "'%s' object isn't an iterator" #~ msgstr "Objektet '%s' är inte en iterator" #~ msgid "'%s' object is not callable" #~ msgstr "Objektet '%s' kan inte anropas" -#~ msgid "'%s' object is not iterable" +#~ msgid "'%s' object isn't iterable" #~ msgstr "Objektet '%s' är inte itererable" #~ msgid "'%s' object is not subscriptable" @@ -4866,7 +4947,7 @@ msgstr "zi måste vara i formen (n_section, 2)" #~ msgid "'continue' outside loop" #~ msgstr "'continue' utanför loop" -#~ msgid "'coroutine' object is not an iterator" +#~ msgid "'coroutine' object isn't an iterator" #~ msgstr "objektet 'coroutine\" är inte en iterator" #~ msgid "(x,y) integers required" @@ -5969,7 +6050,7 @@ msgstr "zi måste vara i formen (n_section, 2)" #~ msgid "frequency is read-only for this board" #~ msgstr "frekvens är skrivskyddad för detta kort" -#~ msgid "function does not take keyword arguments" +#~ msgid "function doesn't take keyword arguments" #~ msgstr "funktionen tar inte nyckelordsargument" #~ msgid "function is implemented for scalars and ndarrays only" @@ -6069,7 +6150,7 @@ msgstr "zi måste vara i formen (n_section, 2)" #~ msgid "n must be between 0, and 9" #~ msgstr "n måste vara mellan 0 och 9" -#~ msgid "name reused for argument" +#~ msgid "argument name reused" #~ msgstr "namn återanvänt för argument" #~ msgid "no available NIC" diff --git a/locale/tr.po b/locale/tr.po index 7e19fade99d..e5bbf3b6c91 100644 --- a/locale/tr.po +++ b/locale/tr.po @@ -7,1733 +7,2174 @@ msgid "" msgstr "" "Project-Id-Version: PACKAGE VERSION\n" "Report-Msgid-Bugs-To: \n" -"PO-Revision-Date: 2024-07-03 19:09+0000\n" -"Last-Translator: Hacı \n" +"PO-Revision-Date: 2026-07-08 15:01+0000\n" +"Last-Translator: H B \n" "Language-Team: none\n" "Language: tr\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 5.7-dev\n" +"X-Generator: Weblate 2026.7.1.dev0\n" -#: main.c -msgid "" -"\n" -"Code done running.\n" +#: extmod/modasyncio.c extmod/modheapq.c +msgid "empty heap" msgstr "" -"\n" -"Program çalıştırıldı.\n" -#: main.c -msgid "" -"\n" -"Code stopped by auto-reload. Reloading soon.\n" +#: extmod/modasyncio.c +msgid "can't cancel self" msgstr "" -"\n" -"Program otomatik yeniden yükleme tarafından durduruldu. Birazdan tekrar " -"yüklenecek.\n" -#: supervisor/shared/safe_mode.c -msgid "" -"\n" -"Please file an issue with your program at github.com/adafruit/circuitpython/" -"issues." +#: extmod/modasyncio.c +msgid "can't wait" msgstr "" -"\n" -"Lütfen programınızla ilgili bir sorunu github.com/adafruit/circuitpython/" -"issues adresinden bildirin." -#: supervisor/shared/safe_mode.c -msgid "" -"\n" -"Press reset to exit safe mode.\n" +#: extmod/modbinascii.c extmod/modhashlib.c py/objarray.c +msgid "a bytes-like object is required" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "" -"\n" -"You are in safe mode because:\n" +#: extmod/modbinascii.c +msgid "incorrect padding" msgstr "" -"\n" -"Güvenli moddasın çünkü:\n" - -#: py/obj.c -msgid " File \"%q\"" -msgstr " \"%q\" dosyası" - -#: py/obj.c -msgid " File \"%q\", line %d" -msgstr " \"%q\" dosyası, %d numaralı satır" - -#: py/builtinhelp.c -msgid " is of type %q\n" -msgstr " nesnesi, %q tipindedir\n" -#: main.c -msgid " not found.\n" -msgstr " bulunamadı.\n" +#: extmod/moddeflate.c +msgid "format" +msgstr "" -#: main.c -msgid " output:\n" -msgstr " çıktı:\n" +#: extmod/moddeflate.c +msgid "wbits" +msgstr "" -#: py/objstr.c -#, c-format -msgid "%%c requires int or char" -msgstr "%%c int veya char tipine ihtiyaç duyar" +#: extmod/modhashlib.c +msgid "hash is final" +msgstr "" -#: shared-bindings/rgbmatrix/RGBMatrix.c -#, c-format -msgid "" -"%d address pins, %d rgb pins and %d tiles indicate a height of %d, not %d" +#: extmod/modheapq.c +msgid "heap must be a list" msgstr "" -"%d adres pinleri, %d RGB pinleri ve %d döşemeleri %d'nin yüksekliği " -"gösterir, %d'nin değil" -#: shared-bindings/microcontroller/Pin.c -msgid "%q and %q contain duplicate pins" -msgstr "%q ve %q yinelenen pinler içeriyor" +#: extmod/modjson.c +msgid "syntax error in JSON" +msgstr "" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c -msgid "%q and %q must be different" -msgstr "%q ve %q farklı olmalılar" +#: extmod/modrandom.c +msgid "bits must be 32 or less" +msgstr "" -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -msgid "%q and %q must share a clock unit" +#: extmod/modrandom.c extmod/ulab/code/numpy/random/random.c +msgid "no default seed" msgstr "" -#: ports/nordic/common-hal/watchdog/WatchDogTimer.c -msgid "%q cannot be changed once mode is set to %q" -msgstr "Mod %q olarak ayarlandıktan sonra %q değiştirilemez" +#: extmod/modre.c +msgid "splitting with sub-captures" +msgstr "" -#: shared-bindings/microcontroller/Pin.c -msgid "%q contains duplicate pins" -msgstr "%q yinelenen pinler içeriyor" +#: extmod/modre.c +msgid "regex too complex" +msgstr "" -#: ports/atmel-samd/common-hal/sdioio/SDCard.c -msgid "%q failure: %d" -msgstr "%q hata: %d" +#: extmod/modre.c +msgid "Error in regex" +msgstr "regex'te hata" -#: py/argcheck.c shared-module/audiofilters/Filter.c -msgid "%q in %q must be of type %q, not %q" +#: extmod/modtime.c +msgid "mktime needs a tuple of length 8 or 9" msgstr "" -#: ports/espressif/common-hal/espulp/ULP.c -#: ports/mimxrt10xx/common-hal/audiobusio/__init__.c -#: ports/mimxrt10xx/common-hal/usb_host/Port.c -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -#: ports/raspberrypi/common-hal/usb_host/Port.c -#: shared-bindings/digitalio/DigitalInOut.c -#: shared-bindings/microcontroller/Pin.c shared-module/max3421e/Max3421E.c -msgid "%q in use" -msgstr "%q kullanımda" +#: extmod/modtime.c +msgid "ticks interval overflow" +msgstr "" -#: py/objstr.c -msgid "%q index out of range" -msgstr "%q indeksi aralık dışında" +#: extmod/modzlib.c +msgid "compression header" +msgstr "" -#: py/obj.c -msgid "%q indices must be integers, not %s" -msgstr "%q indeksleri integer olmalı, %s değil" +#: extmod/ulab/code/ndarray.c +msgid "data type not understood" +msgstr "" -#: shared-module/bitbangio/SPI.c -msgid "%q init failed" -msgstr "%q init başarısız oldu" +#: extmod/ulab/code/ndarray.c +msgid "array is too big" +msgstr "" -#: ports/espressif/bindings/espnow/Peer.c shared-bindings/dualbank/__init__.c -msgid "%q is %q" -msgstr "%q %q dir" +#: extmod/ulab/code/ndarray.c +msgid "ndarray length overflows" +msgstr "" -#: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "%q is read-only for this board" +#: extmod/ulab/code/ndarray.c +msgid "maximum number of dimensions is " msgstr "" -#: py/argcheck.c shared-bindings/usb_hid/Device.c -msgid "%q length must be %d" -msgstr "%q boyutu %d olmalıdır" +#: extmod/ulab/code/ndarray.c +msgid "cannot convert complex type" +msgstr "" -#: py/argcheck.c -msgid "%q length must be %d-%d" -msgstr "%q boyutları %d-%d olmalıdır" +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/create.c +msgid "too many dimensions" +msgstr "" -#: py/argcheck.c -msgid "%q length must be <= %d" -msgstr "%q boyutu <= %d olmalıdır" +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/transform.c +msgid "index is out of bounds" +msgstr "" -#: py/argcheck.c -msgid "%q length must be >= %d" -msgstr "%q boyutu >= %d olmalıdır" +#: extmod/ulab/code/ndarray.c +msgid "indices must be integers, slices, or Boolean lists" +msgstr "" -#: py/modsys.c py/objmodule.c py/runtime.c -msgid "%q moved from %q to %q" +#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/bitwise.c +#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/numpy/vector.c +msgid "operands could not be broadcast together" msgstr "" -#: py/argcheck.c -msgid "%q must be %d" -msgstr "%q, %d olmalıdır" +#: extmod/ulab/code/ndarray.c +msgid "array and index length must be equal" +msgstr "" -#: py/argcheck.c shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/displayio/Bitmap.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -#: shared-bindings/is31fl3741/FrameBuffer.c -#: shared-bindings/rgbmatrix/RGBMatrix.c -msgid "%q must be %d-%d" -msgstr "%q, %d-%d olmalıdır" +#: extmod/ulab/code/ndarray.c +msgid "cannot convert complex to dtype" +msgstr "" -#: shared-bindings/busdisplay/BusDisplay.c -msgid "%q must be 1 when %q is True" -msgstr "%q 1 olmalı, %q True olduğu zaman" +#: extmod/ulab/code/ndarray.c +msgid "operation is implemented for 1D Boolean arrays only" +msgstr "" -#: py/argcheck.c shared-bindings/gifio/GifWriter.c -#: shared-module/gifio/OnDiskGif.c -msgid "%q must be <= %d" -msgstr "%q <= %d olmalıdır" +#: extmod/ulab/code/ndarray.c +msgid "too many indices" +msgstr "" -#: ports/espressif/common-hal/watchdog/WatchDogTimer.c -msgid "%q must be <= %u" +#: extmod/ulab/code/ndarray.c +msgid "cannot delete array elements" msgstr "" -#: py/argcheck.c -msgid "%q must be >= %d" -msgstr "%q >= %d olmalıdır" +#: extmod/ulab/code/ndarray.c +msgid "flattening order must be either 'C', or 'F'" +msgstr "" -#: shared-bindings/analogbufio/BufferedIn.c -msgid "%q must be a bytearray or array of type 'H' or 'B'" -msgstr "%q 'H' ya da 'B' tipi bir bytearray ya da array olmalıdır" +#: extmod/ulab/code/ndarray.c +msgid "tobytes can be invoked for dense arrays only" +msgstr "" -#: shared-bindings/audiocore/RawSample.c -msgid "%q must be a bytearray or array of type 'h', 'H', 'b', or 'B'" -msgstr "%q 'h', 'H', 'b' ya da 'B' tipi bir bytearray ya da array olmalı" +#: extmod/ulab/code/ndarray.c +msgid "operation is not supported for given type" +msgstr "" -#: shared-bindings/warnings/__init__.c -msgid "%q must be a subclass of %q" +#: extmod/ulab/code/ndarray.c +msgid "keyword argument must be tuple of integers" msgstr "" -#: ports/espressif/common-hal/analogbufio/BufferedIn.c -msgid "%q must be array of type 'H'" +#: extmod/ulab/code/ndarray.c +msgid "too many axes specified" msgstr "" -#: shared-module/synthio/__init__.c -msgid "%q must be array of type 'h'" +#: extmod/ulab/code/ndarray.c +msgid "axis index out of bounds" msgstr "" -#: shared-bindings/audiobusio/PDMIn.c -msgid "%q must be multiple of 8." +#: extmod/ulab/code/ndarray.c +msgid "repeated indices" msgstr "" -#: ports/raspberrypi/bindings/cyw43/__init__.c py/argcheck.c py/objexcept.c -#: shared-bindings/bitmapfilter/__init__.c shared-bindings/canio/CAN.c -#: shared-bindings/digitalio/Pull.c shared-bindings/supervisor/__init__.c -#: shared-module/audiofilters/Filter.c shared-module/displayio/__init__.c -#: shared-module/synthio/Biquad.c shared-module/synthio/Synthesizer.c -msgid "%q must be of type %q or %q, not %q" +#: extmod/ulab/code/ndarray.c +msgid "shape must be integer or tuple of integers" msgstr "" -#: shared-bindings/jpegio/JpegDecoder.c -msgid "%q must be of type %q, %q, or %q, not %q" +#: extmod/ulab/code/ndarray.c +msgid "can only specify one unknown dimension" msgstr "" -#: py/argcheck.c py/runtime.c shared-bindings/bitmapfilter/__init__.c -#: shared-module/synthio/__init__.c -msgid "%q must be of type %q, not %q" +#: extmod/ulab/code/ndarray.c +msgid "cannot reshape array" msgstr "" -#: ports/atmel-samd/common-hal/busio/UART.c -msgid "%q must be power of 2" -msgstr "%q, 2'nin kuvveti olmalıdır" - -#: shared-bindings/wifi/Monitor.c -msgid "%q out of bounds" -msgstr "%q sınırların dışında" +#: extmod/ulab/code/ndarray.c +msgid "cannot assign new shape" +msgstr "" -#: ports/atmel-samd/common-hal/pulseio/PulseIn.c -#: ports/cxd56/common-hal/pulseio/PulseIn.c -#: ports/nordic/common-hal/pulseio/PulseIn.c -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -#: ports/stm/common-hal/pulseio/PulseIn.c py/argcheck.c -#: shared-bindings/canio/Match.c shared-bindings/time/__init__.c -msgid "%q out of range" -msgstr "%q aralık dışında" +#: extmod/ulab/code/ndarray.c +msgid "function is defined for ndarrays only" +msgstr "" -#: py/objmodule.c py/runtime.c -msgid "%q renamed %q" +#: extmod/ulab/code/ndarray_operators.c +msgid "operation not supported for the input types" msgstr "" -#: py/objrange.c py/objslice.c shared-bindings/random/__init__.c -msgid "%q step cannot be zero" -msgstr "%q sıfır olamaz" +#: extmod/ulab/code/ndarray_operators.c +msgid "dtype of int32 is not supported" +msgstr "" -#: shared-module/bitbangio/I2C.c -msgid "%q too long" -msgstr "%q çok uzun" +#: extmod/ulab/code/ndarray_operators.c +msgid "cannot cast output with casting rule" +msgstr "" -#: py/bc.c py/objnamedtuple.c -msgid "%q() takes %d positional arguments but %d were given" -msgstr "%q(), %d konumsal argümanını alır ancak %d verildi" +#: extmod/ulab/code/ndarray_operators.c +msgid "results cannot be cast to specified type" +msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "%q() without %q()" +#: extmod/ulab/code/numpy/approx.c +msgid "interp is defined for 1D iterables of equal length" msgstr "" -#: shared-bindings/usb_hid/Device.c -msgid "%q, %q, and %q must all be the same length" -msgstr "%q, %q ve %q aynı uzunlukta olmalıdır" +#: extmod/ulab/code/numpy/approx.c +msgid "trapz is defined for 1D iterables" +msgstr "" -#: py/objint.c shared-bindings/_bleio/Connection.c -#: shared-bindings/storage/__init__.c -msgid "%q=%q" -msgstr "%q=%q" +#: extmod/ulab/code/numpy/approx.c +msgid "trapz is defined for 1D arrays of equal length" +msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "%q[%u] shifts in more bits than pin count" +#: extmod/ulab/code/numpy/bitwise.c +msgid "not supported for input types" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "%q[%u] shifts out more bits than pin count" +#: extmod/ulab/code/numpy/carray/carray.c +msgid "function is implemented for ndarrays only" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "%q[%u] uses extra pin" +#: extmod/ulab/code/numpy/carray/carray.c +msgid "input must be an ndarray, or a scalar" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "%q[%u] waits on input outside of count" +#: extmod/ulab/code/numpy/carray/carray.c +msgid "input must be a 1D ndarray" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -#, c-format -msgid "%s error 0x%x" -msgstr "%s hatası 0x%x" +#: extmod/ulab/code/numpy/carray/carray_tools.c +msgid "not implemented for complex dtype" +msgstr "" -#: py/argcheck.c -msgid "'%q' argument required" -msgstr "'%q' argümanı gerekli" +#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/user/user.c +#: shared-bindings/_eve/__init__.c +msgid "input must be an ndarray" +msgstr "" -#: py/proto.c -msgid "'%q' object does not support '%q'" -msgstr "'%q' nesnesi '%q' öğesini desteklemiyor" +#: extmod/ulab/code/numpy/compare.c +msgid "object too deep for desired array" +msgstr "" -#: py/runtime.c -msgid "'%q' object is not an iterator" -msgstr "'%q' nesnesi bir iteratör değildir" +#: extmod/ulab/code/numpy/compare.c +msgid "cannot cast array data from dtype" +msgstr "" -#: py/objtype.c py/runtime.c shared-module/atexit/__init__.c -msgid "'%q' object is not callable" -msgstr "'%q' nesnesi çağrılabilir değil" +#: extmod/ulab/code/numpy/compare.c +msgid "minlength must not be negative" +msgstr "" -#: py/runtime.c -msgid "'%q' object is not iterable" -msgstr "'%q' nesnesi iterable değildir" +#: extmod/ulab/code/numpy/compare.c +msgid "the weights and list don't have the same length" +msgstr "" -#: py/emitinlinethumb.c py/emitinlinextensa.c -#, c-format -msgid "'%s' expects a label" -msgstr "'%s' bir etiket bekliyor" +#: extmod/ulab/code/numpy/compare.c +msgid "cannot cast weigths to float" +msgstr "" -#: py/emitinlinethumb.c py/emitinlinextensa.c -#, c-format -msgid "'%s' expects a register" -msgstr "'%s' bir yazmaç bekliyor" +#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/numpy/create.c +#: extmod/ulab/code/numpy/io/io.c extmod/ulab/code/numpy/transform.c +#: extmod/ulab/code/numpy/vector.c +msgid "wrong input type" +msgstr "" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects a special register" -msgstr "'%s' özel bir yazmaç bekliyor" +#: extmod/ulab/code/numpy/create.c +msgid "input argument must be an integer, a tuple, or a list" +msgstr "" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects an FPU register" -msgstr "'%s' bir FPU yazmacı bekliyor" +#: extmod/ulab/code/numpy/create.c py/objarray.c py/objstr.c +msgid "wrong number of arguments" +msgstr "" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects an address of the form [a, b]" -msgstr "'%s', [a, b] biçiminde bir adres bekliyor" +#: extmod/ulab/code/numpy/create.c py/objint_longlong.c py/objint_mpz.c +msgid "divide by zero" +msgstr "" -#: py/emitinlinethumb.c py/emitinlinextensa.c -#, c-format -msgid "'%s' expects an integer" -msgstr "'%s' bir integer bekliyor" +#: extmod/ulab/code/numpy/create.c +msgid "arange: cannot compute length" +msgstr "" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects at most r%d" -msgstr "'%s' en fazla r%d bekler" +#: extmod/ulab/code/numpy/create.c +msgid "first argument must be a tuple of ndarrays" +msgstr "" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' expects {r0, r1, ...}" -msgstr "'%s' {r0, r1, ...} bekliyor" +#: extmod/ulab/code/numpy/create.c +msgid "only ndarrays can be concatenated" +msgstr "" -#: py/emitinlinextensa.c -#, c-format -msgid "'%s' integer %d isn't within range %d..%d" -msgstr "'%s' integer %d, %d..%d aralığında değil" +#: extmod/ulab/code/numpy/create.c +msgid "wrong axis specified" +msgstr "" -#: py/emitinlinethumb.c -#, c-format -msgid "'%s' integer 0x%x doesn't fit in mask 0x%x" -msgstr "'%s' integer 0x%x, 0x%x maskesine uymuyor" +#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c +msgid "input arrays are not compatible" +msgstr "" -#: py/obj.c -#, c-format -msgid "'%s' object doesn't support item assignment" -msgstr "'%s' nesnesi, öğe atamasını desteklemiyor" +#: extmod/ulab/code/numpy/create.c +msgid "input must be 1- or 2-d" +msgstr "" -#: py/obj.c -#, c-format -msgid "'%s' object doesn't support item deletion" -msgstr "'%s' nesnesi, öğe silmeyi desteklemiyor" +#: extmod/ulab/code/numpy/create.c +msgid "number of points must be at least 2" +msgstr "" -#: py/runtime.c -msgid "'%s' object has no attribute '%q'" -msgstr "'%s' nesnesinin '%q' özelliği yok" +#: extmod/ulab/code/numpy/create.c +msgid "indexing should be 'xy' or 'ij'" +msgstr "" -#: py/obj.c -#, c-format -msgid "'%s' object isn't subscriptable" -msgstr "'%s' nesnesi subscriptable özelliğe sahip değil" +#: extmod/ulab/code/numpy/create.c +msgid "indexing must be 'xy' or 'ij'" +msgstr "" -#: py/objstr.c -msgid "'=' alignment not allowed in string format specifier" -msgstr "'=' hizalamasına string biçiminde izin verilmez" +#: extmod/ulab/code/numpy/create.c +msgid "too many input arrays" +msgstr "" -#: shared-module/struct/__init__.c -msgid "'S' and 'O' are not supported format types" -msgstr "'S' ve 'O' desteklenen biçim türlerinden değildir" +#: extmod/ulab/code/numpy/create.c extmod/ulab/code/numpy/numerical.c +#: extmod/ulab/code/numpy/transform.c +msgid "arguments must be ndarrays" +msgstr "" -#: py/compile.c -msgid "'align' requires 1 argument" -msgstr "'align' 1 argümana ihtiyaç duyar" +#: extmod/ulab/code/numpy/create.c +msgid "arguments must be 1D arrays" +msgstr "" -#: py/compile.c -msgid "'await' outside function" -msgstr "fonksiyon dışında 'await'" +#: extmod/ulab/code/numpy/create.c +msgid "input is not an array" +msgstr "" -#: py/compile.c -msgid "'break'/'continue' outside loop" -msgstr "Döngü dışında 'break'/'continue'" +#: extmod/ulab/code/numpy/create.c extmod/ulab/code/numpy/numerical.c +#: ports/espressif/common-hal/pulseio/PulseIn.c +#: shared-bindings/bitmaptools/__init__.c +msgid "index out of range" +msgstr "" -#: py/compile.c -msgid "'data' requires at least 2 arguments" -msgstr "'data' en az 2 argümana ihtiyaç duyar" +#: extmod/ulab/code/numpy/create.c +msgid "mode should be raise, wrap or clip" +msgstr "" -#: py/compile.c -msgid "'data' requires integer arguments" -msgstr "'data' integer tipinde argümanlara ihtiyaç duyar" +#: extmod/ulab/code/numpy/create.c +msgid "index must not be negative" +msgstr "" -#: py/compile.c -msgid "'label' requires 1 argument" -msgstr "'label' 1 argümana ihtiyaç duyar" +#: extmod/ulab/code/numpy/create.c +msgid "offset must be non-negative and no greater than buffer length" +msgstr "" -#: py/emitnative.c -msgid "'not' not implemented" +#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c +msgid "buffer size must be a multiple of element size" msgstr "" -#: py/compile.c -msgid "'return' outside function" -msgstr "fonksiyon dışında 'return'" +#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c +msgid "buffer is smaller than requested size" +msgstr "" -#: py/compile.c -msgid "'yield from' inside async function" -msgstr "asenkron fonksiyon içinde 'yield from'" +#: extmod/ulab/code/numpy/fft/fft_tools.c +msgid "FFT is defined for ndarrays only" +msgstr "FFT sadece ndarrays'te tanımlandı" -#: py/compile.c -msgid "'yield' outside function" -msgstr "fonksiyon dışında 'yield'" +#: extmod/ulab/code/numpy/fft/fft_tools.c +msgid "FFT is implemented for linear arrays only" +msgstr "FFT yalnızca doğrusal diziler için uygulanır" -#: py/compile.c -msgid "* arg after **" +#: extmod/ulab/code/numpy/fft/fft_tools.c extmod/ulab/code/utils/utils.c +msgid "input array length must be power of 2" msgstr "" -#: py/compile.c -msgid "*x must be assignment target" -msgstr "*x atama hedefi olmalıdır" +#: extmod/ulab/code/numpy/fft/fft_tools.c +msgid "real and imaginary parts must be of equal length" +msgstr "" -#: py/obj.c -msgid ", in %q\n" -msgstr ", içinde %q\n" +#: extmod/ulab/code/numpy/filter.c +msgid "convolve arguments must be ndarrays" +msgstr "" -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/epaperdisplay/EPaperDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -msgid ".show(x) removed. Use .root_group = x" +#: extmod/ulab/code/numpy/filter.c +msgid "convolve arguments must be linear arrays" msgstr "" -#: py/objcomplex.c -msgid "0.0 to a complex power" -msgstr "0.0'dan bir karmaşık güce" +#: extmod/ulab/code/numpy/filter.c +msgid "convolve arguments must not be empty" +msgstr "" -#: py/modbuiltins.c -msgid "3-arg pow() not supported" -msgstr "3-argümanlı pow() desteklenmemektedir" +#: extmod/ulab/code/numpy/io/io.c +msgid "corrupted file" +msgstr "" -#: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "AP could not be started" +#: extmod/ulab/code/numpy/io/io.c +msgid "wrong dtype" msgstr "" -#: shared-bindings/_bleio/Address.c shared-bindings/ipaddress/IPv4Address.c -#, c-format -msgid "Address must be %d bytes long" -msgstr "Adres %d byte uzunluğunda olmalıdır" +#: extmod/ulab/code/numpy/io/io.c +msgid "usecols keyword must be specified" +msgstr "" -#: ports/espressif/common-hal/memorymap/AddressRange.c -#: ports/nordic/common-hal/memorymap/AddressRange.c -#: ports/raspberrypi/common-hal/memorymap/AddressRange.c -msgid "Address range not allowed" +#: extmod/ulab/code/numpy/io/io.c +msgid "empty file" msgstr "" -#: shared-bindings/memorymap/AddressRange.c -msgid "Address range wraps around" +#: extmod/ulab/code/numpy/io/io.c +msgid "usecols is too high" msgstr "" -#: ports/espressif/common-hal/canio/CAN.c -msgid "All CAN peripherals are in use" -msgstr "Tüm CAN çevre birimleri kullanımda" +#: extmod/ulab/code/numpy/io/io.c +msgid "array has too many dimensions" +msgstr "" -#: ports/espressif/common-hal/busio/I2C.c -#: ports/espressif/common-hal/i2ctarget/I2CTarget.c -#: ports/nordic/common-hal/busio/I2C.c -msgid "All I2C peripherals are in use" -msgstr "Tüm I2C çevre birimleri kullanımda" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "input matrix is asymmetric" +msgstr "" -#: ports/atmel-samd/common-hal/canio/Listener.c -#: ports/espressif/common-hal/canio/Listener.c -#: ports/stm/common-hal/canio/Listener.c -msgid "All RX FIFOs in use" -msgstr "Tüm RX FIFO'ları kullanımda" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "matrix is not positive definite" +msgstr "" -#: ports/espressif/common-hal/busio/SPI.c ports/nordic/common-hal/busio/SPI.c -msgid "All SPI peripherals are in use" -msgstr "Tüm SPI çevre birimleri kullanımda" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "iterations did not converge" +msgstr "" -#: ports/espressif/common-hal/busio/UART.c ports/nordic/common-hal/busio/UART.c -msgid "All UART peripherals are in use" -msgstr "Tüm UART çevre birimleri kullanımda" +#: extmod/ulab/code/numpy/linalg/linalg.c +#: extmod/ulab/code/scipy/linalg/linalg.c +msgid "input matrix is singular" +msgstr "" -#: ports/nordic/common-hal/countio/Counter.c -#: ports/nordic/common-hal/pulseio/PulseIn.c -#: ports/nordic/common-hal/rotaryio/IncrementalEncoder.c -msgid "All channels in use" -msgstr "Tüm kanallar kullanımda" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "operation is defined for ndarrays only" +msgstr "" -#: ports/raspberrypi/common-hal/usb_host/Port.c -msgid "All dma channels in use" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "operation is defined for 2D arrays only" msgstr "" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c -msgid "All event channels in use" -msgstr "Tüm olay kanalları kullanımda" +#: extmod/ulab/code/numpy/linalg/linalg.c +msgid "mode must be complete, or reduced" +msgstr "" -#: ports/raspberrypi/common-hal/floppyio/__init__.c -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -#: ports/raspberrypi/common-hal/usb_host/Port.c -msgid "All state machines in use" -msgstr "Tüm durum makineleri kullanımda" +#: extmod/ulab/code/numpy/numerical.c +msgid "attempt to get argmin/argmax of an empty sequence" +msgstr "" -#: ports/atmel-samd/audio_dma.c -msgid "All sync event channels in use" -msgstr "Tüm asenkron olay kanalları kullanımda" +#: extmod/ulab/code/numpy/numerical.c +msgid "attempt to get (arg)min/(arg)max of empty sequence" +msgstr "" -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c -msgid "All timers for this pin are in use" -msgstr "Bu pin için tüm zamanlayıcılar kullanımda" +#: extmod/ulab/code/numpy/numerical.c extmod/ulab/code/ulab_tools.c +msgid "axis must be None, or an integer" +msgstr "" -#: ports/atmel-samd/common-hal/_pew/PewPew.c -#: ports/atmel-samd/common-hal/audioio/AudioOut.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/nordic/common-hal/audiopwmio/PWMAudioOut.c -#: ports/nordic/common-hal/pulseio/PulseIn.c -#: ports/nordic/peripherals/nrf/timers.c -#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c -msgid "All timers in use" -msgstr "Tüm zamanlayıcılar kullanımda" +#: extmod/ulab/code/numpy/numerical.c +msgid "operation is not implemented on ndarrays" +msgstr "" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Already advertising." -msgstr "Halihazırda duyuruluyor." +#: extmod/ulab/code/numpy/numerical.c +msgid "input must be tuple, list, range, or ndarray" +msgstr "" -#: ports/atmel-samd/common-hal/canio/Listener.c -msgid "Already have all-matches listener" -msgstr "Tüm eşleşmelerle eşleşen dinleyiciniz var" +#: extmod/ulab/code/numpy/numerical.c +msgid "sort argument must be an ndarray" +msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -msgid "Already in progress" +#: extmod/ulab/code/numpy/numerical.c +msgid "argsort argument must be an ndarray" msgstr "" -#: ports/espressif/bindings/espnow/ESPNow.c -#: ports/espressif/common-hal/espulp/ULP.c -#: shared-module/memorymonitor/AllocationAlarm.c -#: shared-module/memorymonitor/AllocationSize.c -msgid "Already running" -msgstr "Halihazırda çalışıyor" +#: extmod/ulab/code/numpy/numerical.c +msgid "argsort is not implemented for flattened arrays" +msgstr "" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/raspberrypi/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "Already scanning for wifi networks" -msgstr "Halihazırda wifi ağları için tarama yapılıyor" +#: extmod/ulab/code/numpy/numerical.c +msgid "axis too long" +msgstr "" -#: shared-module/os/getenv.c -#, c-format -msgid "An error occurred while retrieving '%s':\n" +#: extmod/ulab/code/numpy/numerical.c +msgid "cross is defined for 1D arrays of length 3" msgstr "" -#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c -msgid "Another PWMAudioOut is already active" -msgstr "Başka bir PWMAudioOut zaten aktif durumda" +#: extmod/ulab/code/numpy/numerical.c +msgid "diff argument must be an ndarray" +msgstr "" -#: ports/atmel-samd/common-hal/pulseio/PulseOut.c -#: ports/cxd56/common-hal/pulseio/PulseOut.c -msgid "Another send is already active" -msgstr "Başka bir gönderme zaten aktif" +#: extmod/ulab/code/numpy/numerical.c +msgid "differentiation order out of range" +msgstr "" -#: shared-bindings/pulseio/PulseOut.c -msgid "Array must contain halfwords (type 'H')" -msgstr "Dizi yarımsözcüklere sahip olmalıdır (tip 'H')" +#: extmod/ulab/code/numpy/numerical.c +msgid "flip argument must be an ndarray" +msgstr "" -#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c -#: shared-bindings/nvm/ByteArray.c -msgid "Array values should be single bytes." -msgstr "Dizi değerleri tekil bytelar olmalıdır." +#: extmod/ulab/code/numpy/numerical.c +msgid "wrong axis index" +msgstr "" -#: ports/atmel-samd/common-hal/spitarget/SPITarget.c -msgid "Async SPI transfer in progress on this bus, keep awaiting." +#: extmod/ulab/code/numpy/numerical.c +msgid "median argument must be an ndarray" msgstr "" -#: shared-module/memorymonitor/AllocationAlarm.c -#, c-format -msgid "Attempt to allocate %d blocks" -msgstr "%d bloğun ayrılması girişimi" +#: extmod/ulab/code/numpy/numerical.c +msgid "roll argument must be an ndarray" +msgstr "" -#: ports/raspberrypi/audio_dma.c -msgid "Audio conversion not implemented" -msgstr "Ses dönüşümü implemente edilmedi" +#: extmod/ulab/code/numpy/poly.c +msgid "input data must be an iterable" +msgstr "" -#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c -#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c -msgid "Audio source error" +#: extmod/ulab/code/numpy/poly.c +msgid "more degrees of freedom than data points" msgstr "" -#: shared-bindings/wifi/Radio.c -msgid "AuthMode.OPEN is not used with password" -msgstr "AuthMode.OPEN bir şifre ile kullanılmadı" +#: extmod/ulab/code/numpy/poly.c +msgid "input vectors must be of equal length" +msgstr "" -#: shared-bindings/wifi/Radio.c supervisor/shared/web_workflow/web_workflow.c -msgid "Authentication failure" -msgstr "Kimlik doğrulama hatası" +#: extmod/ulab/code/numpy/poly.c +msgid "could not invert Vandermonde matrix" +msgstr "" -#: main.c -msgid "Auto-reload is off.\n" -msgstr "Otomatik yeniden yükleme devre dışı.\n" +#: extmod/ulab/code/numpy/poly.c +msgid "input is not iterable" +msgstr "" -#: main.c -msgid "" -"Auto-reload is on. Simply save files over USB to run them or enter REPL to " -"disable.\n" +#: extmod/ulab/code/numpy/random/random.c +msgid "argument must be None, an integer or a tuple of integers" msgstr "" -"Otomatik yeniden yükleme aktif. Dosyaları çalıştırmak için USB aracılığı ile " -"kaydedin ya da deaktif etmek için REPL moda girin.\n" -#: ports/espressif/common-hal/canio/CAN.c -msgid "Baudrate not supported by peripheral" -msgstr "Baudhızı, çevre birimi tarafından desteklenmiyor" +#: extmod/ulab/code/numpy/random/random.c +msgid "shape must be None, an integer or a tuple of integers" +msgstr "" -#: shared-module/busdisplay/BusDisplay.c -#: shared-module/framebufferio/FramebufferDisplay.c -msgid "Below minimum frame rate" -msgstr "Minimum kare hızından altında" +#: extmod/ulab/code/numpy/random/random.c extmod/ulab/code/ulab_tools.c +msgid "out has wrong type" +msgstr "" -#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c -msgid "Bit clock and word select must be sequential GPIO pins" +#: extmod/ulab/code/numpy/random/random.c +msgid "output array has wrong type" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "Bitmap size and bits per value must match" -msgstr "Bitmap boyutu ve bit başına değer uyuşmalı" - -#: supervisor/shared/safe_mode.c -msgid "Boot device must be first (interface #0)." +#: extmod/ulab/code/numpy/random/random.c +msgid "size must match out.shape when used together" msgstr "" -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Both RX and TX required for flow control" -msgstr "Hem RX hem de TX akış kontrolü için gerekli" - -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -msgid "Brightness not adjustable" -msgstr "Parlaklık ayarlanabilir değil" - -#: shared-bindings/_bleio/UUID.c -#, c-format -msgid "Buffer + offset too small %d %d %d" -msgstr "Buffer + offset çok küçük %d %d %d" - -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "Buffer elements must be 4 bytes long or less" -msgstr "Buffer elementleri 4 bit olmak zorunda" +#: extmod/ulab/code/numpy/random/random.c extmod/ulab/code/ulab_tools.c +msgid "output array must be contiguous" +msgstr "" -#: shared-bindings/framebufferio/FramebufferDisplay.c -msgid "Buffer is not a bytearray." -msgstr "Buffer bir bytearray değil." +#: extmod/ulab/code/numpy/transform.c +msgid "wrong length of condition array" +msgstr "" -#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c -#, c-format -msgid "Buffer length %d too big. It must be less than %d" -msgstr "Mevcut arabellek boyutu %d çok büyük. En fazla %d kadar olmalı" +#: extmod/ulab/code/numpy/transform.c extmod/ulab/code/numpy/vector.c +msgid "first argument must be an ndarray" +msgstr "" -#: ports/atmel-samd/common-hal/sdioio/SDCard.c -#: ports/cxd56/common-hal/sdioio/SDCard.c -#: ports/espressif/common-hal/sdioio/SDCard.c -#: ports/stm/common-hal/sdioio/SDCard.c shared-bindings/floppyio/__init__.c -#: shared-module/sdcardio/SDCard.c -#, c-format -msgid "Buffer must be a multiple of %d bytes" +#: extmod/ulab/code/numpy/transform.c +msgid "wrong index type" msgstr "" -#: shared-bindings/_bleio/PacketBuffer.c -#, c-format -msgid "Buffer too short by %d bytes" -msgstr "Buffer bitten %d daha az" +#: extmod/ulab/code/numpy/transform.c +msgid "wrong length of index array" +msgstr "" -#: ports/cxd56/common-hal/camera/Camera.c -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -#: shared-bindings/struct/__init__.c shared-module/struct/__init__.c -msgid "Buffer too small" +#: extmod/ulab/code/numpy/transform.c +msgid "dimensions do not match" msgstr "" -#: ports/atmel-samd/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/nordic/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/raspberrypi/common-hal/paralleldisplaybus/ParallelBus.c -#, c-format -msgid "Bus pin %d is already in use" -msgstr "Veriyolu pini %d kullanımda" +#: extmod/ulab/code/numpy/vector.c extmod/ulab/code/utils/utils.c +msgid "out must be an ndarray" +msgstr "" -#: shared-bindings/_bleio/UUID.c -msgid "Byte buffer must be 16 bytes." -msgstr "Bit buffer'ı 16bit olmalı." +#: extmod/ulab/code/numpy/vector.c +msgid "out must be of float dtype" +msgstr "" -#: shared-bindings/aesio/aes.c -msgid "CBC blocks must be multiples of 16 bytes" -msgstr "CBC blokları 16 baytın katları şeklinde olmalı" +#: extmod/ulab/code/numpy/vector.c +msgid "input and output dimensions differ" +msgstr "" -#: supervisor/shared/safe_mode.c -msgid "CIRCUITPY drive could not be found or created." -msgstr "CIRCUITPY sürücüsü bulunamadı veya oluşturulamadı." +#: extmod/ulab/code/numpy/vector.c +msgid "input and output shapes differ" +msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "CRC or checksum was invalid" -msgstr "CRC yada checksum geçersiz" +#: extmod/ulab/code/numpy/vector.c +msgid "out keyword is not supported for function" +msgstr "" -#: py/objtype.c -msgid "Call super().__init__() before accessing native object." -msgstr "Yerel nesneye erişmeden önce super().__init__() fonksiyonunu çağırın." +#: extmod/ulab/code/numpy/vector.c +msgid "out keyword is not supported for complex dtype" +msgstr "" -#: ports/cxd56/common-hal/camera/Camera.c -msgid "Camera init" +#: extmod/ulab/code/numpy/vector.c +msgid "dtype must be float, or complex" msgstr "" -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Can only alarm on RTC IO from deep sleep." +#: extmod/ulab/code/numpy/vector.c +msgid "can't convert complex to float" msgstr "" -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Can only alarm on one low pin while others alarm high from deep sleep." +#: extmod/ulab/code/numpy/vector.c +msgid "input dtype must be float or complex" msgstr "" -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Can only alarm on two low pins from deep sleep." +#: extmod/ulab/code/numpy/vector.c extmod/ulab/code/scipy/integrate/integrate.c +msgid "first argument must be a callable" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Can't construct AudioOut because continuous channel already open" +#: extmod/ulab/code/numpy/vector.c +msgid "wrong output type" msgstr "" -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Characteristic.c -msgid "Can't set CCCD on local Characteristic" +#: extmod/ulab/code/scipy/integrate/integrate.c +#, c-format +msgid "can't convert arg %d from %s to float" msgstr "" -#: shared-bindings/storage/__init__.c shared-bindings/usb_cdc/__init__.c -#: shared-bindings/usb_hid/__init__.c shared-bindings/usb_midi/__init__.c -#: shared-bindings/usb_video/__init__.c -msgid "Cannot change USB devices now" -msgstr "USB aygıtları şu an değiştirilemez" +#: extmod/ulab/code/scipy/integrate/integrate.c +msgid "levels needs to be a positive integer" +msgstr "" -#: shared-bindings/_bleio/Adapter.c -msgid "Cannot create a new Adapter; use _bleio.adapter;" -msgstr "yeni Adaptör oluşturulamadı, _bleio.adapter kullanın" +#: extmod/ulab/code/scipy/integrate/integrate.c +msgid "steps needs to be a positive integer" +msgstr "" -#: shared-bindings/displayio/Bitmap.c -#: shared-bindings/memorymonitor/AllocationSize.c -#: shared-bindings/pulseio/PulseIn.c -msgid "Cannot delete values" -msgstr "Değerler silinemez" +#: extmod/ulab/code/scipy/integrate/integrate.c +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "first argument must be a function" +msgstr "" -#: ports/atmel-samd/common-hal/digitalio/DigitalInOut.c -#: ports/mimxrt10xx/common-hal/digitalio/DigitalInOut.c -#: ports/nordic/common-hal/digitalio/DigitalInOut.c -#: ports/raspberrypi/common-hal/digitalio/DigitalInOut.c -msgid "Cannot get pull while in output mode" -msgstr "Çıkış modundayken çekme alınamıyor" +#: extmod/ulab/code/scipy/integrate/integrate.c +msgid "order needs to be a positive integer" +msgstr "" -#: ports/nordic/common-hal/microcontroller/Processor.c -msgid "Cannot get temperature" -msgstr "Isı okunamadı" +#: extmod/ulab/code/scipy/linalg/linalg.c +msgid "first two arguments must be ndarrays" +msgstr "" -#: shared-bindings/_bleio/Adapter.c -#, fuzzy -msgid "Cannot have scan responses for extended, connectable advertisements." -msgstr "Genişletilmiş, bağlanabilir reklamlar için tarama yanıtları yapılamaz." +#: extmod/ulab/code/scipy/linalg/linalg.c extmod/ulab/code/user/user.c +msgid "input must be a dense ndarray" +msgstr "" -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Cannot pull on input-only pin." +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "function has the same sign at the ends of interval" msgstr "" -#: shared-bindings/audiobusio/PDMIn.c -msgid "Cannot record to a file" -msgstr "Dosyaya kayıt yapılamıyor" +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "maxiter should be > 0" +msgstr "" -#: shared-module/storage/__init__.c -msgid "Cannot remount '/' when visible via USB." -msgstr "'/' USB ile görünür olduğunda, yeniden bağlanamaz." +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "maxiter must be > 0" +msgstr "" -#: shared-bindings/digitalio/DigitalInOut.c -msgid "Cannot set value when direction is input." -msgstr "Yön, giriş olduğunda değer ayarlanamıyor." +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "data must be iterable" +msgstr "" -#: ports/espressif/common-hal/busio/UART.c -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "Cannot specify RTS or CTS in RS485 mode" -msgstr "RS485 modunda RTS veya CTS belirtilemez" +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "initial values must be iterable" +msgstr "" -#: py/objslice.c -msgid "Cannot subclass slice" +#: extmod/ulab/code/scipy/optimize/optimize.c +msgid "data must be of equal length" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Cannot use GPIO0..15 together with GPIO32..47" +#: extmod/ulab/code/scipy/signal/signal.c +msgid "sosfilt requires iterable arguments" msgstr "" -#: ports/nordic/common-hal/alarm/pin/PinAlarm.c -msgid "Cannot wake on pin edge, only level" +#: extmod/ulab/code/scipy/signal/signal.c +msgid "input must be one-dimensional" msgstr "" -#: ports/espressif/common-hal/alarm/pin/PinAlarm.c -msgid "Cannot wake on pin edge. Only level." +#: extmod/ulab/code/scipy/signal/signal.c +msgid "zi must be an ndarray" msgstr "" -#: shared-bindings/_bleio/CharacteristicBuffer.c -msgid "CharacteristicBuffer writing not provided" -msgstr "CharacteristicBuffer yazılmı sağlanmadı" +#: extmod/ulab/code/scipy/signal/signal.c +msgid "zi must be of shape (n_section, 2)" +msgstr "" -#: supervisor/shared/safe_mode.c -msgid "CircuitPython core code crashed hard. Whoops!\n" -msgstr "CircuitPython kor kodu patladı. Haydaaa!\n" +#: extmod/ulab/code/scipy/signal/signal.c +msgid "zi must be of float type" +msgstr "" -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -msgid "Clock unit in use" -msgstr "Saat ünitesi kullanımda" +#: extmod/ulab/code/scipy/signal/signal.c +msgid "sos array must be of shape (n_section, 6)" +msgstr "" -#: shared-bindings/_bleio/Connection.c -msgid "" -"Connection has been disconnected and can no longer be used. Create a new " -"connection." -msgstr "Bağlantı koparıldı ve tekrar kullanılamaz. Yeni bir bağlantı kurun." +#: extmod/ulab/code/scipy/signal/signal.c +msgid "sos[:, 3] should be all ones" +msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "Coordinate arrays have different lengths" +#: extmod/ulab/code/ulab_tools.c +msgid "axis is out of bounds" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "Coordinate arrays types have different sizes" +#: extmod/ulab/code/ulab_tools.c +msgid "size is defined for ndarrays only" msgstr "" -#: shared-bindings/_bleio/Adapter.c -msgid "Could not set address" -msgstr "Adres ayarlanamadı" +#: extmod/ulab/code/ulab_tools.c +msgid "input must be square matrix" +msgstr "" -#: ports/stm/common-hal/busio/UART.c -msgid "Could not start interrupt, RX busy" -msgstr "Kesinti başlatılamadı, RX kullanımda" +#: extmod/ulab/code/ulab_tools.c +msgid "out array has wrong dtype" +msgstr "" -#: shared-module/audiomp3/MP3Decoder.c -msgid "Couldn't allocate decoder" +#: extmod/ulab/code/ulab_tools.c +msgid "out array has wrong dimension" msgstr "" -#: ports/stm/common-hal/analogio/AnalogOut.c -msgid "DAC Channel Init Error" +#: extmod/ulab/code/ulab_tools.c +msgid "out array has wrong shape" msgstr "" -#: ports/stm/common-hal/analogio/AnalogOut.c -msgid "DAC Device Init Error" +#: extmod/ulab/code/utils/utils.c +msgid "out must be a float dense array" +msgstr "" + +#: extmod/ulab/code/utils/utils.c +msgid "offset is too large" +msgstr "" + +#: extmod/ulab/code/utils/utils.c +msgid "out array is too small" +msgstr "" + +#: extmod/ulab/code/utils/utils.c +msgid "spectrogram is defined for ndarrays only" +msgstr "" + +#: extmod/ulab/code/utils/utils.c +msgid "spectrogram is implemented for 1D arrays only" +msgstr "" + +#: extmod/ulab/code/utils/utils.c +msgid "out array must be a 1D array of float type" +msgstr "" + +#: extmod/ulab/code/utils/utils.c +msgid "input and out arrays must have same length" +msgstr "" + +#: extmod/ulab/code/utils/utils.c +msgid "scratchpad must be an ndarray" +msgstr "" + +#: extmod/ulab/code/utils/utils.c +msgid "scratchpad must be a 1D dense float array" +msgstr "" + +#: extmod/ulab/code/utils/utils.c +msgid "scratchpad must be twice as long as input" +msgstr "" + +#: extmod/vfs_fat.c py/moderrno.c +msgid "Read-only filesystem" +msgstr "" + +#: extmod/vfs_posix_file.c py/objstringio.c +msgid "I/O operation on closed file" +msgstr "Kapalı dosyada I/O işlemi" + +#: extmod/vfs_posix_file.c +msgid "poll on file not available on win32" +msgstr "" + +#: main.c +msgid "Done" +msgstr "Tamamlandı" + +#: main.c +msgid " output:\n" +msgstr " çıktı:\n" + +#: main.c +msgid "" +"Auto-reload is on. Simply save files over USB to run them or enter REPL to " +"disable.\n" +msgstr "" +"Otomatik yeniden yükleme aktif. Dosyaları çalıştırmak için USB aracılığı ile " +"kaydedin ya da deaktif etmek için REPL moda girin.\n" + +#: main.c +msgid "Auto-reload is off.\n" +msgstr "Otomatik yeniden yükleme devre dışı.\n" + +#: main.c +msgid "Running in safe mode! Not running saved code.\n" +msgstr "" + +#: main.c +msgid " not found.\n" +msgstr " bulunamadı.\n" + +#: main.c +msgid "WARNING: Your code filename has two extensions\n" +msgstr "" + +#: main.c +msgid "" +"\n" +"Code stopped by auto-reload. Reloading soon.\n" +msgstr "" +"\n" +"Program otomatik yeniden yükleme tarafından durduruldu. Birazdan tekrar " +"yüklenecek.\n" + +#: main.c +msgid "" +"\n" +"Code done running.\n" +msgstr "" +"\n" +"Program çalıştırıldı.\n" + +#: main.c +msgid "Woken up by alarm.\n" +msgstr "" + +#: main.c +msgid "Press any key to enter the REPL. Use CTRL-D to reload.\n" +msgstr "" +"REPL moda girmek için herhangi bir tuşa basınız. Programı yeniden yüklemek " +"için CTRL+D tuş kombinasyonunu kullanabilirsiniz.\n" + +#: main.c +msgid "Pretending to deep sleep until alarm, CTRL-C or file write.\n" +msgstr "" +"Alarma, CTRL-C'ye veya dosya yazana kadar derin uyku moduna geçiliyor.\n" + +#: main.c +msgid "UID:" +msgstr "UID:" + +#: main.c +msgid "soft reboot\n" +msgstr "" + +#: ports/analog/common-hal/busio/SPI.c ports/analog/common-hal/busio/UART.c +#: ports/cxd56/common-hal/busio/SPI.c ports/stm/common-hal/audioio/AudioOut.c +#: shared-bindings/digitalio/DigitalInOutProtocol.c +#: shared-module/displayio/bus_core.c shared-module/ssl/SSLContext.c +msgid "%q init failed" +msgstr "%q init başarısız oldu" + +#: ports/analog/common-hal/busio/SPI.c +msgid "SPI needs MOSI, MISO, and SCK" +msgstr "" + +#: ports/analog/common-hal/busio/SPI.c +#: ports/atmel-samd/common-hal/pulseio/PulseIn.c +#: ports/cxd56/common-hal/pulseio/PulseIn.c +#: ports/nordic/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#: ports/stm/common-hal/pulseio/PulseIn.c py/argcheck.c +#: shared-bindings/bitmaptools/__init__.c shared-bindings/canio/Match.c +#: shared-bindings/time/__init__.c +msgid "%q out of range" +msgstr "%q aralık dışında" + +#: ports/analog/common-hal/busio/SPI.c +#: ports/espressif/common-hal/espidf/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: shared-bindings/epaperdisplay/EPaperDisplay.c +msgid "Invalid state" +msgstr "Geçersiz durum" + +#: ports/analog/common-hal/busio/SPI.c +msgid "Failed to set SPI Clock Mode" +msgstr "" + +#: ports/analog/common-hal/busio/UART.c +#: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c +#: ports/nordic/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c +#: ports/zephyr-cp/common-hal/busio/UART.c +msgid "RS485" +msgstr "RS485" + +#: ports/analog/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c +msgid "UART needs TX & RX" +msgstr "" + +#: ports/analog/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c +msgid "Both RX and TX required for flow control" +msgstr "Hem RX hem de TX akış kontrolü için gerekli" + +#: ports/analog/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/usb_host/Port.c +#: shared-module/rgbmatrix/RGBMatrix.c +msgid "Failed to allocate %q buffer" +msgstr "" + +#: ports/analog/common-hal/busio/UART.c +msgid "UART read error" +msgstr "" + +#: ports/analog/common-hal/busio/UART.c +msgid "UART transaction timeout" +msgstr "" + +#: ports/analog/common-hal/busio/UART.c ports/espressif/common-hal/busio/UART.c +#: ports/nordic/common-hal/busio/UART.c ports/zephyr-cp/common-hal/busio/UART.c +msgid "All UART peripherals are in use" +msgstr "Tüm UART çevre birimleri kullanımda" + +#: ports/analog/common-hal/busio/UART.c +#: ports/analog/peripherals/max32690/max32_i2c.c +#: ports/analog/peripherals/max32690/max32_spi.c +#: ports/analog/peripherals/max32690/max32_uart.c +#: ports/espressif/common-hal/_bleio/Service.c +#: ports/espressif/common-hal/espulp/ULP.c +#: ports/espressif/common-hal/jpegio/JpegDecoder.c +#: ports/espressif/common-hal/microcontroller/Processor.c +#: ports/espressif/common-hal/mipidsi/Display.c +#: ports/mimxrt10xx/common-hal/audiobusio/__init__.c +#: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c +#: ports/raspberrypi/bindings/picodvi/Framebuffer.c +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +#: ports/raspberrypi/common-hal/picodvi/AudioOut.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c +#: ports/raspberrypi/common-hal/usb_host_bulk/InStream.c py/argcheck.c +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/utils/__init__.c +#: shared-bindings/digitalio/DigitalInOut.c +#: shared-bindings/epaperdisplay/EPaperDisplay.c +#: shared-bindings/i2cioexpander/IOPin.c shared-bindings/mipidsi/Display.c +#: shared-bindings/pwmio/PWMOut.c shared-bindings/supervisor/__init__.c +#: shared-module/aurora_epaper/aurora_framebuffer.c +#: shared-module/cryptography/hazmat/primitives/asymmetric/ec/EllipticCurvePublicKey.c +#: shared-module/jpegio/JpegDecoder.c shared-module/lvfontio/OnDiskFont.c +msgid "Invalid %q" +msgstr "Geçersiz %q" + +#: ports/analog/common-hal/busio/UART.c +msgid "Timeout must be < 100 seconds" +msgstr "" + +#: ports/atmel-samd/audio_dma.c +msgid "All sync event channels in use" +msgstr "Tüm asenkron olay kanalları kullanımda" + +#: ports/atmel-samd/audio_dma.c ports/raspberrypi/audio_dma.c +msgid "Internal audio buffer too small" +msgstr "Dahili ses arabelleği çok küçük" + +#: ports/atmel-samd/bindings/samd/Clock.c +msgid "calibration is read only" +msgstr "" + +#: ports/atmel-samd/bindings/samd/Clock.c +msgid "calibration is out of range" +msgstr "" + +#: 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/meowmeow/mpconfigboard.h +msgid "You pressed both buttons at start up." +msgstr "" + +#: ports/atmel-samd/common-hal/_pew/PewPew.c +#: ports/atmel-samd/common-hal/audioio/AudioOut.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/nordic/common-hal/audiopwmio/PWMAudioOut.c +#: ports/nordic/common-hal/pulseio/PulseIn.c +#: ports/nordic/peripherals/nrf/timers.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +#: ports/stm/common-hal/pulseio/PulseOut.c +msgid "All timers in use" +msgstr "Tüm zamanlayıcılar kullanımda" + +#: ports/atmel-samd/common-hal/alarm/pin/PinAlarm.c +#: ports/atmel-samd/common-hal/countio/Counter.c +#: ports/atmel-samd/common-hal/frequencyio/FrequencyIn.c +#: ports/atmel-samd/common-hal/max3421e/Max3421E.c +#: ports/atmel-samd/common-hal/ps2io/Ps2.c +#: ports/atmel-samd/common-hal/pulseio/PulseIn.c +#: ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.c +#: ports/cxd56/common-hal/pulseio/PulseIn.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c +#: ports/zephyr-cp/common-hal/async_spi/SPI.c +#: ports/zephyr-cp/common-hal/busio/I2C.c +#: ports/zephyr-cp/common-hal/busio/UART.c +msgid "Internal resource(s) in use" +msgstr "" + +#: ports/atmel-samd/common-hal/alarm/pin/PinAlarm.c +#: supervisor/shared/safe_mode.c +msgid "Unknown reason." +msgstr "" + +#: ports/atmel-samd/common-hal/alarm/time/TimeAlarm.c +#: ports/nordic/common-hal/alarm/time/TimeAlarm.c +#: ports/stm/common-hal/alarm/time/TimeAlarm.c +msgid "Only one alarm.time alarm can be set" +msgstr "" + +#: ports/atmel-samd/common-hal/analogio/AnalogOut.c +#: ports/stm/common-hal/analogio/AnalogOut.c +#: ports/stm/common-hal/audioio/AudioOut.c +msgid "No DAC on chip" +msgstr "" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +msgid "%q and %q must share a clock unit" +msgstr "%q ve %q bir saat birimi paylaşmalıdır" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +msgid "Serializer in use" +msgstr "" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +msgid "Clock unit in use" +msgstr "Saat ünitesi kullanımda" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/atmel-samd/common-hal/touchio/TouchIn.c +msgid "No free GCLKs" +msgstr "" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +msgid "Too many channels in sample" +msgstr "" + +#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +#: ports/raspberrypi/common-hal/mcp4822/MCP4822.c +msgid "No DMA channel found" +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 +#: ports/raspberrypi/common-hal/mcp4822/MCP4822.c +msgid "Unable to allocate buffers for signed conversion" +msgstr "" + +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c +#, c-format +msgid "Only 8 or 16 bit mono with %dx oversampling supported." +msgstr "" + +#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c +#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c +msgid "sampling rate out of range" msgstr "" #: ports/atmel-samd/common-hal/audioio/AudioOut.c msgid "DAC already in use" msgstr "DAC zaten kullanımda" +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +msgid "Right channel unsupported" +msgstr "" + +#: ports/atmel-samd/common-hal/audioio/AudioOut.c +msgid "All event channels in use" +msgstr "Tüm olay kanalları kullanımda" + +#: ports/atmel-samd/common-hal/busio/I2C.c +#: ports/espressif/common-hal/busio/I2C.c +#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nordic/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 "" + +#: ports/atmel-samd/common-hal/busio/UART.c +#: shared-bindings/usb_host_bulk/InStream.c +msgid "%q must be power of 2" +msgstr "%q, 2'nin kuvveti olmalıdır" + +#: ports/atmel-samd/common-hal/busio/UART.c +#: ports/espressif/common-hal/busio/SPI.c +#: ports/espressif/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/SPI.c +#: ports/mimxrt10xx/common-hal/busio/UART.c +#: ports/nordic/common-hal/busio/UART.c +#: ports/raspberrypi/common-hal/busio/UART.c ports/stm/common-hal/busio/SPI.c +#: ports/stm/common-hal/busio/UART.c shared-bindings/fourwire/FourWire.c +#: shared-bindings/i2cdisplaybus/I2CDisplayBus.c +#: shared-bindings/paralleldisplaybus/ParallelBus.c +#: shared-bindings/qspibus/QSPIBus.c shared-module/bitbangio/SPI.c +msgid "No %q pin" +msgstr "%q pini yok" + +#: ports/atmel-samd/common-hal/canio/Listener.c +#: ports/espressif/common-hal/canio/Listener.c +#: ports/stm/common-hal/canio/Listener.c +msgid "All RX FIFOs in use" +msgstr "Tüm RX FIFO'ları kullanımda" + +#: ports/atmel-samd/common-hal/canio/Listener.c +msgid "Already have all-matches listener" +msgstr "Tüm eşleşmelerle eşleşen dinleyiciniz var" + +#: ports/atmel-samd/common-hal/canio/Listener.c +#: ports/espressif/common-hal/canio/Listener.c +#: ports/mimxrt10xx/common-hal/canio/Listener.c +#: ports/stm/common-hal/canio/Listener.c +msgid "Filters too complex" +msgstr "Filtreler çok karmaşık" + +#: ports/atmel-samd/common-hal/digitalio/DigitalInOut.c +#: ports/mimxrt10xx/common-hal/digitalio/DigitalInOut.c +#: ports/nordic/common-hal/digitalio/DigitalInOut.c +#: ports/raspberrypi/common-hal/digitalio/DigitalInOut.c +msgid "Cannot get pull while in output mode" +msgstr "Çıkış modundayken çekme alınamıyor" + +#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c +#, c-format +msgid "Invalid data_pins[%d]" +msgstr "Geçersiz veri_pini [%d]" + +#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c +#, c-format +msgid "data pin #%d in use" +msgstr "" + +#: ports/atmel-samd/common-hal/microcontroller/Pin.c +#: ports/espressif/common-hal/dotclockframebuffer/DotClockFramebuffer.c +#: ports/mimxrt10xx/common-hal/microcontroller/Pin.c +#: shared-bindings/emmcio/EMMC.c shared-bindings/microcontroller/Pin.c +msgid "Invalid %q pin" +msgstr "Geersi %q pin" + +#: ports/atmel-samd/common-hal/microcontroller/__init__.c +#: ports/cxd56/common-hal/microcontroller/__init__.c +#: ports/mimxrt10xx/common-hal/microcontroller/__init__.c +msgid "No bootloader present" +msgstr "" + #: ports/atmel-samd/common-hal/paralleldisplaybus/ParallelBus.c #: ports/nordic/common-hal/paralleldisplaybus/ParallelBus.c msgid "Data 0 pin must be byte aligned" msgstr "Data 0 pini bite hizalı olmalı" -#: shared-module/jpegio/JpegDecoder.c -msgid "Data format error (may be broken data)" -msgstr "" +#: ports/atmel-samd/common-hal/paralleldisplaybus/ParallelBus.c +#: ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c +#: ports/nordic/common-hal/paralleldisplaybus/ParallelBus.c +#: ports/raspberrypi/common-hal/paralleldisplaybus/ParallelBus.c +#, c-format +msgid "Bus pin %d is already in use" +msgstr "Veriyolu pini %d kullanımda" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Data not supported with directed advertising" +#: ports/atmel-samd/common-hal/pulseio/PulseIn.c +#: ports/cxd56/common-hal/pulseio/PulseIn.c +#: ports/nordic/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 "" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Data too large for advertisement packet" +#: ports/atmel-samd/common-hal/pulseio/PulseIn.c +msgid "Input taking too long" +msgstr "Giriş çok uzun sürüyor" + +#: ports/atmel-samd/common-hal/pulseio/PulseOut.c +#: ports/cxd56/common-hal/pulseio/PulseOut.c +msgid "Another send is already active" +msgstr "Başka bir gönderme zaten aktif" + +#: ports/atmel-samd/common-hal/sdioio/SDCard.c +#: ports/espressif/common-hal/mii/Ethernet.c +#: ports/espressif/common-hal/qspibus/QSPIBus.c shared-bindings/emmcio/EMMC.c +#: shared-bindings/socketpool/SocketPool.c +msgid "%q failure: %d" +msgstr "%q hata: %d" + +#: ports/atmel-samd/common-hal/sdioio/SDCard.c +#: ports/cxd56/common-hal/sdioio/SDCard.c +#: ports/espressif/common-hal/sdioio/SDCard.c +#: ports/raspberrypi/common-hal/sdioio/SDCard.c +#: ports/stm/common-hal/sdioio/SDCard.c shared-bindings/audiocore/WaveFile.c +#: shared-bindings/emmcio/EMMC.c shared-bindings/floppyio/__init__.c +#: shared-bindings/picogame/Canvas.c shared-module/sdcardio/SDCard.c +#, c-format +msgid "Buffer must be a multiple of %d bytes" +msgstr "Tampon, %d baytların katı olmalıdır" + +#: ports/atmel-samd/common-hal/spitarget/SPITarget.c +msgid "Async SPI transfer in progress on this bus, keep awaiting." msgstr "" +"Bu veri yolunda asenkron SPI transferi devam ediyor, beklemeye devam edin." -#: ports/stm/common-hal/alarm/pin/PinAlarm.c -msgid "Deep sleep pins must use a rising edge with pulldown" +#: ports/cxd56/common-hal/busio/UART.c ports/espressif/common-hal/busio/UART.c +#: ports/stm/common-hal/busio/UART.c +msgid "UART init" msgstr "" -#: shared-bindings/audiobusio/PDMIn.c -msgid "Destination capacity is smaller than destination_length." -msgstr "Hedef kapasitesi, hedef_uzunluğundan daha küçük." +#: ports/cxd56/common-hal/camera/Camera.c +msgid "Camera init" +msgstr "Kamerayı başlat" -#: shared-module/jpegio/JpegDecoder.c -msgid "Device error or wrong termination of input stream" +#: ports/cxd56/common-hal/camera/Camera.c +msgid "Size not supported" msgstr "" -#: ports/nordic/common-hal/audiobusio/I2SOut.c -msgid "Device in use" -msgstr "Cihaz kullanımda" - +#: ports/cxd56/common-hal/camera/Camera.c #: shared-bindings/busdisplay/BusDisplay.c #: shared-bindings/framebufferio/FramebufferDisplay.c -msgid "Display must have a 16 bit colorspace." -msgstr "Ekran 16 bitlik bir renk uzayına sahip olmalıdır." +#: shared-bindings/struct/__init__.c shared-module/struct/__init__.c +#: shared-module/videocore/VideoBuffer.c +msgid "Buffer too small" +msgstr "Tampon çok küçük" -#: shared-bindings/busdisplay/BusDisplay.c -#: shared-bindings/epaperdisplay/EPaperDisplay.c -#: shared-bindings/framebufferio/FramebufferDisplay.c -msgid "Display rotation must be in 90 degree increments" -msgstr "Ekran dönüşü 90 derecelik artışlarla olmalıdır" +#: ports/cxd56/common-hal/camera/Camera.c +#: ports/espressif/common-hal/jpegio/JpegDecoder.c +#: shared-module/audiocore/WaveFile.c +#: shared-module/busdisplay/lvgl/BusDisplay.c +#: shared-module/displayio/lvgl/TileGrid.c +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "Format not supported" +msgstr "Format desteklenmiyor" -#: main.c -msgid "Done" -msgstr "Tamamlandı" +#: ports/cxd56/common-hal/gnss/GNSS.c +msgid "GNSS init" +msgstr "GNSS init" -#: shared-bindings/digitalio/DigitalInOut.c -msgid "Drive mode not used when direction is input." -msgstr "Yön, giriş olduğunda sürüş modu kullanılmaz." +#: ports/cxd56/common-hal/sdioio/SDCard.c +msgid "SDCard init" +msgstr "" -#: py/obj.c -msgid "During handling of the above exception, another exception occurred:" -msgstr "Yukarıdaki hatanın işlenmesi sırasında başka bir hata oluştu:" +#: ports/espressif/bindings/espnow/ESPNow.c +#: ports/espressif/common-hal/espulp/ULP.c +#: ports/raspberrypi/common-hal/usb_host_bulk/InStream.c +#: shared-module/memorymonitor/AllocationAlarm.c +#: shared-module/memorymonitor/AllocationSize.c +msgid "Already running" +msgstr "Halihazırda çalışıyor" -#: shared-bindings/aesio/aes.c -msgid "ECB only operates on 16 bytes at a time" -msgstr "ECB aynı anda yalnızca 16 baytla çalışır" +#: ports/espressif/bindings/espnow/Peer.c shared-bindings/dualbank/__init__.c +msgid "%q is %q" +msgstr "%q %q dir" -#: ports/espressif/common-hal/busio/SPI.c -#: ports/espressif/common-hal/canio/CAN.c -msgid "ESP-IDF memory allocation failed" +#: ports/espressif/boards/adafruit_feather_esp32_v2/mpconfigboard.h +msgid "You pressed the SW38 button at start up." +msgstr "" + +#: ports/espressif/boards/adafruit_feather_esp32c6_4mbflash_nopsram/mpconfigboard.h +#: ports/espressif/boards/adafruit_itsybitsy_esp32/mpconfigboard.h +#: ports/espressif/boards/waveshare_esp32_c5_lcd_1_47/mpconfigboard.h +#: ports/espressif/boards/waveshare_esp32_c6_lcd_1_47/mpconfigboard.h +msgid "You pressed the BOOT button at start up." +msgstr "" + +#: ports/espressif/boards/adafruit_huzzah32_breakout/mpconfigboard.h +msgid "You pressed the GPIO0 button at start up." +msgstr "" + +#: ports/espressif/boards/espressif_esp32_lyrat/mpconfigboard.h +msgid "You pressed the Rec button at start up." +msgstr "" + +#: ports/espressif/boards/hardkernel_odroid_go/mpconfigboard.h +#: ports/espressif/boards/vidi_x/mpconfigboard.h +msgid "You pressed the VOLUME button at start up." +msgstr "" + +#: ports/espressif/boards/m5stack_atom_echo/mpconfigboard.h +#: ports/espressif/boards/m5stack_atom_lite/mpconfigboard.h +#: ports/espressif/boards/m5stack_atom_matrix/mpconfigboard.h +#: ports/espressif/boards/m5stack_atom_u/mpconfigboard.h +msgid "You pressed the central button at start up." +msgstr "" + +#: ports/espressif/boards/m5stack_core_basic/mpconfigboard.h +#: ports/espressif/boards/m5stack_core_fire/mpconfigboard.h +#: ports/espressif/boards/m5stack_stick_c/mpconfigboard.h +#: ports/espressif/boards/m5stack_stick_c_plus/mpconfigboard.h +#: ports/espressif/boards/m5stack_stick_c_plus2/mpconfigboard.h +msgid "You pressed button A at start up." msgstr "" -#: extmod/modre.c -msgid "Error in regex" -msgstr "regex'te hata" - -#: supervisor/shared/safe_mode.c -msgid "Error in safemode.py." +#: ports/espressif/boards/m5stack_m5paper/mpconfigboard.h +msgid "You pressed button DOWN at start up." msgstr "" -#: shared-bindings/alarm/__init__.c -msgid "Expected a kind of %q" +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/espressif/common-hal/dualbank/__init__.c +msgid "Update failed" msgstr "" #: ports/espressif/common-hal/_bleio/Adapter.c #: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Extended advertisements with scan response not supported." +msgid "Scan already in progress. Stop with stop_scan." msgstr "" -#: extmod/ulab/code/numpy/fft/fft_tools.c -msgid "FFT is defined for ndarrays only" -msgstr "FFT sadece ndarrays'te tanımlandı" +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +#: ports/zephyr-cp/common-hal/_bleio/Adapter.c +msgid "Failed to connect: timeout" +msgstr "Bağlantı kurulamadı: timeout" -#: extmod/ulab/code/numpy/fft/fft_tools.c -msgid "FFT is implemented for linear arrays only" -msgstr "FFT yalnızca doğrusal diziler için uygulanır" +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +#: ports/zephyr-cp/common-hal/_bleio/Adapter.c +msgid "Failed to connect: internal error" +msgstr "Bağlantı kurulamadı: internal error" -#: shared-bindings/ps2io/Ps2.c -msgid "Failed sending command." -msgstr "Komut gönderilemedi." +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +#: ports/zephyr-cp/common-hal/_bleio/Adapter.c +msgid "Data too large for advertisement packet" +msgstr "Veri, reklam paketi için çok büyük" -#: ports/nordic/sd_mutex.c -#, c-format -msgid "Failed to acquire mutex, err 0x%04x" -msgstr "Muteks alınamadı, err 0x%04x" +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "Already advertising." +msgstr "Halihazırda duyuruluyor." -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "Failed to add service TXT record" +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "Extended advertisements with scan response not supported." msgstr "" -#: shared-bindings/mdns/Server.c -msgid "" -"Failed to add service TXT record; non-string or bytes found in txt_records" -msgstr "" +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "Data not supported with directed advertising" +msgstr "Veri, hedefli reklamcılıkla desteklenmemektedir" -#: shared-module/rgbmatrix/RGBMatrix.c -msgid "Failed to allocate %q buffer" +#: ports/espressif/common-hal/_bleio/Adapter.c +#: ports/nordic/common-hal/_bleio/Adapter.c +#, c-format +msgid "Timeout is too long: Maximum timeout length is %d seconds" msgstr "" -#: ports/espressif/common-hal/wifi/__init__.c -msgid "Failed to allocate Wifi memory" +#: ports/espressif/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Descriptor.c +msgid "Value length != required fixed length" msgstr "" -#: ports/espressif/common-hal/wifi/ScannedNetworks.c -msgid "Failed to allocate wifi scan memory" +#: ports/espressif/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Descriptor.c +msgid "Value length > max_length" msgstr "" -#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c -msgid "Failed to buffer the sample" +#: ports/espressif/common-hal/_bleio/Characteristic.c +#: ports/espressif/common-hal/_bleio/Service.c +#: ports/raspberrypi/common-hal/alarm/pin/PinAlarm.c +#: ports/raspberrypi/common-hal/usb_host_bulk/InStream.c +msgid "Too many %q" msgstr "" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Failed to connect: internal error" -msgstr "Bağlantı kurulamadı: internal error" +#: ports/espressif/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Characteristic.c +#: ports/zephyr-cp/common-hal/_bleio/Characteristic.c +msgid "No CCCD for this Characteristic" +msgstr "" -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Failed to connect: timeout" -msgstr "Bağlantı kurulamadı: timeout" +#: ports/espressif/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Characteristic.c +msgid "Can't set CCCD on local Characteristic" +msgstr "Yerel Karakteristikte CCCD ayarlanamaz" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to create continuous channels: invalid arg" +#: ports/espressif/common-hal/_bleio/Connection.c +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/Characteristic.c +#: ports/zephyr-cp/common-hal/_bleio/Connection.c +#: ports/zephyr-cp/common-hal/_bleio/Descriptor.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +#: shared-bindings/_bleio/CharacteristicBuffer.c +msgid "Not connected" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to create continuous channels: invalid state" +#: ports/espressif/common-hal/_bleio/Connection.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/Connection.c +msgid "" +"Unspecified issue. The pairing request on the other device may have been " +"declined or ignored." msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to create continuous channels: no mem" +#: ports/espressif/common-hal/_bleio/Connection.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/Connection.c +#, c-format +msgid "Unknown security error: 0x%04x" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to create continuous channels: not found" +#: ports/espressif/common-hal/_bleio/Connection.c +msgid "No pairing in progress" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to enable continuous" +#: ports/espressif/common-hal/_bleio/Connection.c +#: ports/nordic/common-hal/_bleio/Connection.c +msgid "non-UUID found in service_uuids_whitelist" msgstr "" -#: shared-module/audiomp3/MP3Decoder.c -msgid "Failed to parse MP3 file" -msgstr "MP3 dosyası ayrıştırılamadı" - -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to register continuous events callback" +#: ports/espressif/common-hal/_bleio/Descriptor.c +#: ports/nordic/common-hal/_bleio/Characteristic.c +#: ports/nordic/common-hal/_bleio/Descriptor.c +#, c-format +msgid "max_length must be 0-%d when fixed_length is %s" msgstr "" -#: ports/nordic/sd_mutex.c -#, c-format -msgid "Failed to release mutex, err 0x%04x" -msgstr "Muteks serbest bırakılamadı, err 0x%04x" +#: ports/espressif/common-hal/_bleio/PacketBuffer.c +#: ports/nordic/common-hal/_bleio/PacketBuffer.c +#: ports/zephyr-cp/common-hal/_bleio/PacketBuffer.c +msgid "Writes not supported on Characteristic" +msgstr "" -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "Failed to set hostname" +#: ports/espressif/common-hal/_bleio/PacketBuffer.c +#: ports/nordic/common-hal/_bleio/PacketBuffer.c +#: ports/zephyr-cp/common-hal/_bleio/PacketBuffer.c +msgid "Total data to write is larger than %q" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "Failed to start async audio" +#: ports/espressif/common-hal/_bleio/__init__.c +msgid "Nimble out of memory" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Failed to write internal flash." -msgstr "Dahili flaş yazılamadı." +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +msgid "Invalid BLE parameter" +msgstr "Geçersiz BLE parametresi" -#: py/moderrno.c -msgid "File exists" -msgstr "Dosya var" +#: ports/espressif/common-hal/_bleio/__init__.c +#: shared-module/audiofilewriter/AudioFileWriter.c +msgid "Already in progress" +msgstr "Zaten işlemde" -#: shared-module/os/getenv.c -msgid "File not found" +#: ports/espressif/common-hal/_bleio/__init__.c +#, c-format +msgid "Unknown BLE error at %s:%d: 0x%04x" msgstr "" -#: ports/atmel-samd/common-hal/canio/Listener.c -#: ports/espressif/common-hal/canio/Listener.c -#: ports/mimxrt10xx/common-hal/canio/Listener.c -#: ports/stm/common-hal/canio/Listener.c -msgid "Filters too complex" -msgstr "Filtreler çok karmaşık" - -#: ports/espressif/common-hal/dualbank/__init__.c -msgid "Firmware is duplicate" +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#, c-format +msgid "Unknown BLE error: 0x%04x" msgstr "" -#: ports/espressif/common-hal/dualbank/__init__.c -msgid "Firmware is invalid" -msgstr "Yazılım geçersiz" +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +msgid "%q not permitted" +msgstr "" -#: ports/espressif/common-hal/dualbank/__init__.c -msgid "Firmware is too big" -msgstr "Yazılım çok büyük" +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +msgid "Insufficient authentication" +msgstr "Yetersiz kimlik doğrulama" -#: shared-bindings/bitmaptools/__init__.c -msgid "For L8 colorspace, input bitmap must have 8 bits per pixel" +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +msgid "Insufficient authorization" msgstr "" -"L8 renk uzayı için, giriş bitmap'i piksel başına 8 bayta sahip olmalıdır" -#: shared-bindings/bitmaptools/__init__.c -msgid "For RGB colorspaces, input bitmap must have 16 bits per pixel" -msgstr "" -"RGB renk uzayı için, giriş bitmap'i piksel başına 16 bayta sahip olmalıdır" +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +msgid "Insufficient encryption" +msgstr "Yetersiz şifreleme" -#: ports/cxd56/common-hal/camera/Camera.c -msgid "Format not supported" -msgstr "Format desteklenmiyor" +#: ports/espressif/common-hal/_bleio/__init__.c +#: ports/nordic/common-hal/_bleio/__init__.c +#: ports/zephyr-cp/common-hal/_bleio/__init__.c +#, c-format +msgid "Unknown gatt error: 0x%04x" +msgstr "" -#: ports/mimxrt10xx/common-hal/microcontroller/Processor.c -msgid "" -"Frequency must be 24, 150, 396, 450, 528, 600, 720, 816, 912, 960 or 1008 Mhz" +#: ports/espressif/common-hal/alarm/pin/PinAlarm.c +msgid "Cannot wake on pin edge. Only level." msgstr "" -"Frekans 24, 150, 396, 450, 528, 600, 720, 816, 912, 960 ya da 1008 Mhz " -"olmalıdır" -#: 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 "Fonksiyon kilit gerektirir" +#: ports/espressif/common-hal/alarm/pin/PinAlarm.c +msgid "Cannot pull on input-only pin." +msgstr "Sadece giriş olan pinde pull ayarlanamaz." -#: ports/cxd56/common-hal/gnss/GNSS.c -msgid "GNSS init" -msgstr "GNSS init" +#: ports/espressif/common-hal/alarm/pin/PinAlarm.c +msgid "Can only alarm on two low pins from deep sleep." +msgstr "Derin uykudan uyanırken yalnızca iki düşük pinde alarm tetiklenebilir." -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Generic Failure" +#: ports/espressif/common-hal/alarm/pin/PinAlarm.c +msgid "Can only alarm on one low pin while others alarm high from deep sleep." msgstr "" +"Derin uykudan uyanırken, diğerleri yüksek seviyede alarm verecek şekilde " +"ayarlanmışken sadece tek bir düşük pinde alarm tetiklenebilir." -#: shared-bindings/framebufferio/FramebufferDisplay.c -#: shared-module/busdisplay/BusDisplay.c -#: shared-module/framebufferio/FramebufferDisplay.c -msgid "Group already used" -msgstr "Grup zaten kullanılıyor" +#: ports/espressif/common-hal/alarm/pin/PinAlarm.c +msgid "Can only alarm on RTC IO from deep sleep." +msgstr "Sadece alarm RTC IO'yu uyandırabilir." -#: supervisor/shared/safe_mode.c -msgid "Hard fault: memory access or instruction error." +#: ports/espressif/common-hal/alarm/time/TimeAlarm.c +#: ports/raspberrypi/common-hal/alarm/time/TimeAlarm.c +msgid "Only one alarm.time alarm can be set." msgstr "" -#: ports/mimxrt10xx/common-hal/busio/SPI.c -#: ports/mimxrt10xx/common-hal/busio/UART.c 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 "Hardware in use, try alternative pins" -msgstr "Donanım kullanımda, alternatif pinleri deneyin" +#: ports/espressif/common-hal/alarm/touch/TouchAlarm.c +msgid "Only one %q can be set in deep sleep." +msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Heap allocation when VM not running." +#: ports/espressif/common-hal/analogbufio/BufferedIn.c +msgid "%q must be array of type 'H'" +msgstr "%q, 'H' dizisi türünde olmalıdır" + +#: ports/espressif/common-hal/audiobusio/PDMIn.c +#: shared-bindings/audioi2sin/I2SIn.c shared-bindings/usb_host_audio/USBIn.c +msgid "%q must be 8, 16, 24, or 32" +msgstr "%q 8, 16, 24 veya 32 olmalıdır" + +#: ports/espressif/common-hal/audiobusio/__init__.c +#: ports/espressif/common-hal/audioi2sin/I2SIn.c +#: ports/espressif/common-hal/mii/Ethernet.c shared-bindings/emmcio/EMMC.c +msgid "Peripheral in use" msgstr "" -#: extmod/vfs_posix_file.c py/objstringio.c -msgid "I/O operation on closed file" -msgstr "Kapalı dosyada I/O işlemi" +#: ports/espressif/common-hal/audioi2sin/I2SIn.c +#: ports/raspberrypi/common-hal/audioi2sin/I2SIn.c +msgid "%q must be 8 or 16" +msgstr "%q 8 veya 16 olmalıdır" -#: ports/stm/common-hal/busio/I2C.c -msgid "I2C init error" -msgstr "I2C init hatası" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "audio format not supported" +msgstr "" -#: ports/raspberrypi/common-hal/busio/I2C.c -#: ports/raspberrypi/common-hal/i2ctarget/I2CTarget.c -msgid "I2C peripheral in use" -msgstr "I2C çevre cihazı kullanımda" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to start async audio" +msgstr "" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "In-buffer elements must be <= 4 bytes long" -msgstr "Buffer öğeleri <=4 bayt uzunluğunda olmalı" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to create continuous channels: invalid arg" +msgstr "" -#: shared-bindings/_pew/PewPew.c -msgid "Incorrect buffer size" -msgstr "Yanlış buffer size" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to create continuous channels: invalid state" +msgstr "" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "Init program size invalid" -msgstr "Init program boyutu geçersiz" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to create continuous channels: not found" +msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Initial set pin direction conflicts with initial out pin direction" -msgstr "İlk pin yönü, ilk çıkış pin yönüyle çakışıyor" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to create continuous channels: no mem" +msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Initial set pin state conflicts with initial out pin state" -msgstr "İlk pinin durumu, ilk çıkış pininin durumu ile çakışıyor" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to register continuous events callback" +msgstr "" -#: shared-bindings/bitops/__init__.c -#, c-format -msgid "Input buffer length (%d) must be a multiple of the strand count (%d)" -msgstr "Giriş buffer uzunluğu (%d) strand sayımının (%d) katı olmalıdır" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Failed to enable continuous" +msgstr "" -#: ports/atmel-samd/common-hal/pulseio/PulseIn.c -msgid "Input taking too long" -msgstr "Giriş çok uzun sürüyor" +#: ports/espressif/common-hal/audioio/AudioOut.c +msgid "Can't construct AudioOut because continuous channel already open" +msgstr "AudioOut oluşturulamıyor çünkü kesintisiz kanal zaten açık" -#: py/moderrno.c -msgid "Input/output error" -msgstr "Giriş/çıkış hatası" +#: ports/espressif/common-hal/audioio/AudioOut.c +#: ports/espressif/common-hal/mipicsi/Camera.c +#: shared-module/videocore/VideoBuffer.c shared-module/videogif/GifDecoder.c +msgid "already playing" +msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -#: ports/nordic/common-hal/_bleio/__init__.c -msgid "Insufficient authentication" -msgstr "Yetersiz kimlik doğrulama" +#: ports/espressif/common-hal/busio/I2C.c +#: ports/espressif/common-hal/i2ctarget/I2CTarget.c +#: ports/nordic/common-hal/busio/I2C.c ports/zephyr-cp/common-hal/busio/I2C.c +msgid "All I2C peripherals are in use" +msgstr "Tüm I2C çevre birimleri kullanımda" -#: ports/espressif/common-hal/_bleio/__init__.c -#: ports/nordic/common-hal/_bleio/__init__.c -msgid "Insufficient encryption" -msgstr "Yetersiz şifreleme" +#: ports/espressif/common-hal/busio/I2C.c +#: ports/espressif/common-hal/busio/SPI.c +msgid "Unable to create lock" +msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "Insufficient memory pool for the image" +#: ports/espressif/common-hal/busio/SPI.c +msgid "SPI configuration failed" msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "Insufficient stream input buffer" +#: ports/espressif/common-hal/busio/SPI.c ports/nordic/common-hal/busio/SPI.c +#: ports/zephyr-cp/common-hal/async_spi/SPI.c +msgid "All SPI peripherals are in use" +msgstr "Tüm SPI çevre birimleri kullanımda" + +#: ports/espressif/common-hal/busio/SPI.c +#: ports/espressif/common-hal/canio/CAN.c +#: ports/espressif/common-hal/qspibus/QSPIBus.c +msgid "ESP-IDF memory allocation failed" msgstr "" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "Interface must be started" -msgstr "Arayüz başlatılmalıdır" +#: ports/espressif/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c +msgid "Cannot specify RTS or CTS in RS485 mode" +msgstr "RS485 modunda RTS veya CTS belirtilemez" -#: ports/atmel-samd/audio_dma.c ports/raspberrypi/audio_dma.c -msgid "Internal audio buffer too small" -msgstr "Dahili ses arabelleği çok küçük" +#: ports/espressif/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/busio/UART.c +msgid "RS485 inversion specified when not in RS485 mode" +msgstr "" -#: ports/stm/common-hal/busio/UART.c -msgid "Internal define error" -msgstr "Dahili tanımlama hatası" +#: ports/espressif/common-hal/canio/CAN.c +msgid "Baudrate not supported by peripheral" +msgstr "Baudhızı, çevre birimi tarafından desteklenmiyor" -#: shared-bindings/pwmio/PWMOut.c shared-module/os/getenv.c -msgid "Internal error" -msgstr "Dahili hata" +#: ports/espressif/common-hal/canio/CAN.c +msgid "All CAN peripherals are in use" +msgstr "Tüm CAN çevre birimleri kullanımda" -#: shared-module/rgbmatrix/RGBMatrix.c +#: ports/espressif/common-hal/canio/CAN.c +msgid "loopback + silent mode not supported by peripheral" +msgstr "" + +#: ports/espressif/common-hal/canio/CAN.c #, c-format -msgid "Internal error #%d" -msgstr "Dahili hata #%d" +msgid "twai_driver_install returned esp-idf error #%d" +msgstr "" -#: ports/atmel-samd/common-hal/alarm/pin/PinAlarm.c -#: ports/atmel-samd/common-hal/countio/Counter.c -#: ports/atmel-samd/common-hal/frequencyio/FrequencyIn.c -#: ports/atmel-samd/common-hal/max3421e/Max3421E.c -#: ports/atmel-samd/common-hal/ps2io/Ps2.c -#: ports/atmel-samd/common-hal/pulseio/PulseIn.c -#: ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.c -#: ports/cxd56/common-hal/pulseio/PulseIn.c -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c -#: shared-bindings/pwmio/PWMOut.c -msgid "Internal resource(s) in use" +#: ports/espressif/common-hal/canio/CAN.c +#, c-format +msgid "twai_start returned esp-idf error #%d" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Internal watchdog timer expired." -msgstr "Dahili bekçi zamanlayıcısının süresi doldu." +#: ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "ds_params has the wrong length" +msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Interrupt error." +#: ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "" +"This key already committed to a different algorithm; call " +"load_digital_signature_key() again to use a different one" msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "Interrupted by output function" +#: ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "" +"This key's ds_params were replaced by a later load_digital_signature_key() " +"call for the same key slot" msgstr "" -#: ports/espressif/common-hal/_bleio/Service.c -#: ports/espressif/common-hal/espulp/ULP.c -#: ports/espressif/common-hal/microcontroller/Processor.c -#: ports/mimxrt10xx/common-hal/audiobusio/__init__.c -#: ports/mimxrt10xx/common-hal/pwmio/PWMOut.c -#: ports/raspberrypi/bindings/picodvi/Framebuffer.c -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c py/argcheck.c -#: shared-bindings/digitalio/DigitalInOut.c -#: shared-bindings/epaperdisplay/EPaperDisplay.c shared-bindings/pwmio/PWMOut.c -#: shared-module/aurora_epaper/aurora_framebuffer.c -msgid "Invalid %q" -msgstr "Geçersiz %q" +#: ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "ds_params is invalid for this key slot" +msgstr "" -#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c -#: shared-module/aurora_epaper/aurora_framebuffer.c -msgid "Invalid %q and %q" +#: ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "Digital Signature peripheral not available on this chip" msgstr "" -#: ports/atmel-samd/common-hal/microcontroller/Pin.c #: ports/espressif/common-hal/dotclockframebuffer/DotClockFramebuffer.c -#: ports/mimxrt10xx/common-hal/microcontroller/Pin.c -#: shared-bindings/microcontroller/Pin.c -msgid "Invalid %q pin" -msgstr "Geersi %q pin" - -#: ports/stm/common-hal/analogio/AnalogIn.c -msgid "Invalid ADC Unit value" -msgstr "Geçersiz ADC Ünite değeri" - -#: ports/espressif/common-hal/_bleio/__init__.c -#: ports/nordic/common-hal/_bleio/__init__.c -msgid "Invalid BLE parameter" -msgstr "Geçersiz BLE parametresi" - -#: shared-bindings/wifi/Radio.c -msgid "Invalid BSSID" -msgstr "Geçersiz BSSID" +msgid "Must provide 5/6/5 RGB pins" +msgstr "" -#: shared-bindings/wifi/Radio.c -msgid "Invalid MAC address" -msgstr "Geçersiz MAC adresi" +#: ports/espressif/common-hal/dualbank/__init__.c +msgid "Firmware is duplicate" +msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c py/moderrno.c -msgid "Invalid argument" -msgstr "Geçersiz argüman" +#: ports/espressif/common-hal/dualbank/__init__.c +msgid "Firmware is invalid" +msgstr "Yazılım geçersiz" -#: shared-module/displayio/Bitmap.c -#, fuzzy -msgid "Invalid bits per value" -msgstr "Geçersiz bit başına değer" +#: ports/espressif/common-hal/dualbank/__init__.c +msgid "Firmware is too big" +msgstr "Yazılım çok büyük" -#: shared-module/os/getenv.c -#, c-format -msgid "Invalid byte %.*s" +#: ports/espressif/common-hal/espcamera/Camera.c py/objobject.c py/runtime.c +msgid "no such attribute" msgstr "" -#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c -#, c-format -msgid "Invalid data_pins[%d]" -msgstr "Geçersiz veri_pini [%d]" - -#: shared-module/msgpack/__init__.c -msgid "Invalid format" +#: ports/espressif/common-hal/espcamera/Camera.c +msgid "invalid setting" msgstr "" -#: shared-module/audiocore/WaveFile.c -msgid "Invalid format chunk size" -msgstr "Geçersiz biçim yığın boyutu" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "Generic Failure" +msgstr "" -#: shared-bindings/wifi/Radio.c -msgid "Invalid hex password" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "Out of memory" msgstr "" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "Invalid multicast MAC address" -msgstr "Geçersiz multicast MAC adresi" +#: ports/espressif/common-hal/espidf/__init__.c py/moderrno.c +msgid "Invalid argument" +msgstr "Geçersiz argüman" #: ports/espressif/common-hal/espidf/__init__.c msgid "Invalid size" msgstr "Geçersiz boyut" -#: shared-module/ssl/SSLSocket.c -msgid "Invalid socket for TLS" -msgstr "TLS için geçersiz soket" - #: ports/espressif/common-hal/espidf/__init__.c -#: ports/nordic/common-hal/_bleio/__init__.c -msgid "Invalid state" -msgstr "Geçersiz durum" - -#: shared-module/os/getenv.c -msgid "Invalid unicode escape" +msgid "Requested resource not found" msgstr "" -#: shared-bindings/aesio/aes.c -msgid "Key must be 16, 24, or 32 bytes long" -msgstr "Anahtar 16, 24 veya 32 bayt uzunluğunda olmalıdır" - -#: shared-module/os/getenv.c -msgid "Key not found" +#: ports/espressif/common-hal/espidf/__init__.c +#: ports/espressif/common-hal/jpegio/JpegDecoder.c +#: ports/raspberrypi/common-hal/usb_host_bulk/InStream.c +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +#: shared-bindings/picogame/Canvas.c shared-bindings/picogame/__init__.c +#: shared-module/jpegio/JpegDecoder.c shared-module/picogame/Display.c +msgid "Operation or feature not supported" msgstr "" -#: shared-module/is31fl3741/FrameBuffer.c -msgid "LED mappings must match display size" -msgstr "LED eşlemeleri ekran boyutuyla eşleşmelidir" - -#: py/compile.c -msgid "LHS of keyword arg must be an id" +#: ports/espressif/common-hal/espidf/__init__.c +#: ports/espressif/common-hal/qspibus/QSPIBus.c +#: shared-module/_airlift/__init__.c +msgid "Operation timed out" msgstr "" -#: shared-module/displayio/Group.c -msgid "Layer already in a group" -msgstr "Katman zaten bir grupta" +#: ports/espressif/common-hal/espidf/__init__.c +#: shared-module/_airlift/__init__.c +msgid "Received response was invalid" +msgstr "" -#: shared-module/displayio/Group.c -msgid "Layer must be a Group or TileGrid subclass" -msgstr "Katman, bir Grup ya da TileGrid alt sınıfı olmalıdır" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "CRC or checksum was invalid" +msgstr "CRC yada checksum geçersiz" -#: shared-bindings/audiocore/RawSample.c -msgid "Length of %q must be an even multiple of channel_count * type_size" +#: ports/espressif/common-hal/espidf/__init__.c +msgid "Version was invalid" msgstr "" #: ports/espressif/common-hal/espidf/__init__.c msgid "MAC address was invalid" msgstr "MAC adresi geçersiz" -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/espressif/common-hal/_bleio/Descriptor.c -msgid "MITM security not supported" -msgstr "" - -#: shared-bindings/is31fl3741/IS31FL3741.c -msgid "Mapping must be a tuple" -msgstr "Map tuple olmalıdır" - -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Mismatched data size" -msgstr "" +#: ports/espressif/common-hal/espidf/__init__.c +#, c-format +msgid "%s error 0x%x" +msgstr "%s hatası 0x%x" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Mismatched swap flag" +#: ports/espressif/common-hal/espulp/ULP.c +msgid "Program too long" msgstr "" +#: ports/espressif/common-hal/espulp/ULP.c +#: ports/espressif/common-hal/mipidsi/Bus.c +#: ports/espressif/common-hal/qspibus/QSPIBus.c +#: ports/mimxrt10xx/common-hal/audiobusio/__init__.c +#: ports/mimxrt10xx/common-hal/usb_host/Port.c +#: ports/raspberrypi/common-hal/picodvi/AudioOut.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_in_pin. %q[%u] reads pin(s)" -msgstr "" +#: ports/raspberrypi/common-hal/usb_host/Port.c +#: shared-bindings/digitalio/DigitalInOut.c shared-bindings/emmcio/EMMC.c +#: shared-bindings/i2cioexpander/IOPin.c shared-bindings/microcontroller/Pin.c +#: shared-module/_airlift/__init__.c +#: shared-module/epaperdisplay/EPaperDisplay.c +#: shared-module/max3421e/Max3421E.c shared-module/usb/core/Device.c +#: shared-module/usb_host_audio/USBIn.c +msgid "%q in use" +msgstr "%q kullanımda" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_in_pin. %q[%u] shifts in from pin(s)" +#: ports/espressif/common-hal/espulp/ULPAlarm.c +msgid "Only one %q can be set." msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_in_pin. %q[%u] waits based on pin" +#: ports/espressif/common-hal/i2ctarget/I2CTarget.c +#: ports/raspberrypi/common-hal/i2ctarget/I2CTarget.c +msgid "Only one address is allowed" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_out_pin. %q[%u] shifts out to pin(s)" +#: ports/espressif/common-hal/max3421e/Max3421E.c +#: ports/raspberrypi/common-hal/wifi/__init__.c +#, c-format +msgid "Unknown error code %d" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_out_pin. %q[%u] writes pin(s)" +#: ports/espressif/common-hal/mdns/Server.c +#: ports/raspberrypi/common-hal/mdns/Server.c +msgid "mDNS only works with built-in WiFi" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing first_set_pin. %q[%u] sets pin(s)" +#: ports/espressif/common-hal/mdns/Server.c +#: ports/raspberrypi/common-hal/mdns/Server.c +msgid "mDNS already initialized" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Missing jmp_pin. %q[%u] jumps on pin" +#: ports/espressif/common-hal/mdns/Server.c +#: ports/raspberrypi/common-hal/mdns/Server.c +msgid "Unable to start mDNS query" msgstr "" -#: shared-module/storage/__init__.c -msgid "Mount point directory missing" +#: ports/espressif/common-hal/memorymap/AddressRange.c +#: ports/nordic/common-hal/memorymap/AddressRange.c +#: ports/raspberrypi/common-hal/memorymap/AddressRange.c +msgid "Address range not allowed" msgstr "" -#: ports/zephyr-cp/bindings/zephyr_serial/UART.c shared-bindings/busio/UART.c -#: shared-bindings/displayio/Group.c -msgid "Must be a %q subclass." +#: ports/espressif/common-hal/mipicsi/Camera.c +#: shared-bindings/displayio/TileGrid.c shared-bindings/terminalio/Terminal.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-bindings/vectorio/VectorShape.c +msgid "unsupported %q type" msgstr "" -#: ports/espressif/common-hal/dotclockframebuffer/DotClockFramebuffer.c -msgid "Must provide 5/6/5 RGB pins" +#: ports/espressif/common-hal/mipicsi/Camera.c +msgid "output_format must be RGB565 or RGB888" msgstr "" -#: ports/mimxrt10xx/common-hal/busio/SPI.c shared-bindings/busio/SPI.c -msgid "Must provide MISO or MOSI pin" +#: ports/espressif/common-hal/mipicsi/Camera.c +msgid "ISP conversion not supported on this chip" msgstr "" -#: shared-bindings/rgbmatrix/RGBMatrix.c -#, c-format -msgid "Must use a multiple of 6 rgb pins, not %d" +#: ports/espressif/common-hal/mipidsi/Bus.c +msgid "%q is above %u" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "NLR jump failed. Likely memory corruption." +#: ports/espressif/common-hal/mipidsi/Bus.c +msgid "%q is not reachable by the PHY" msgstr "" #: ports/espressif/common-hal/nvm/ByteArray.c msgid "NVS Error" msgstr "NVS hatası" -#: shared-bindings/socketpool/SocketPool.c -msgid "Name or service not known" -msgstr "" - -#: shared-bindings/displayio/TileGrid.c -msgid "New bitmap must be same size as old bitmap" +#: ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c +#: ports/espressif/common-hal/sdioio/SDCard.c +#, c-format +msgid "Number of data_pins must be %d or %d, not %d" msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -msgid "Nimble out of memory" +#: ports/espressif/common-hal/pulseio/PulseIn.c +msgid "pop from an empty PulseIn" msgstr "" -#: ports/atmel-samd/common-hal/busio/UART.c -#: ports/espressif/common-hal/busio/SPI.c -#: ports/espressif/common-hal/busio/UART.c -#: ports/mimxrt10xx/common-hal/busio/SPI.c -#: ports/mimxrt10xx/common-hal/busio/UART.c -#: ports/nordic/common-hal/busio/UART.c -#: ports/raspberrypi/common-hal/busio/UART.c ports/stm/common-hal/busio/SPI.c -#: ports/stm/common-hal/busio/UART.c shared-bindings/fourwire/FourWire.c -#: shared-bindings/i2cdisplaybus/I2CDisplayBus.c -#: shared-bindings/paralleldisplaybus/ParallelBus.c -#: shared-module/bitbangio/SPI.c -msgid "No %q pin" -msgstr "%q pini yok" +#: ports/espressif/common-hal/qspibus/QSPIBus.c +#: ports/raspberrypi/common-hal/usb_host_bulk/InStream.c +#: shared-module/usb/core/Device.c +msgid "Could not allocate DMA capable buffer" +msgstr "DMA yetenekli tampon tahsis edilemedi" -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Characteristic.c -msgid "No CCCD for this Characteristic" -msgstr "" +#: ports/espressif/common-hal/qspibus/QSPIBus.c shared-bindings/pwmio/PWMOut.c +#: supervisor/shared/settings.c +msgid "Internal error" +msgstr "Dahili hata" -#: ports/atmel-samd/common-hal/analogio/AnalogOut.c -#: ports/stm/common-hal/analogio/AnalogOut.c -msgid "No DAC on chip" +#: ports/espressif/common-hal/rclcpy/Node.c +msgid "ROS node failed to initialize" 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" +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "ROS topic failed to initialize" msgstr "" -#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c -msgid "No DMA pacing timer found" -msgstr "" +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "Could not publish to ROS topic" +msgstr "ROS konusuna yayımlanamadı" -#: shared-module/adafruit_bus_device/i2c_device/I2CDevice.c +#: ports/espressif/common-hal/rclcpy/__init__.c #, c-format -msgid "No I2C device at address: 0x%x" +msgid "Critical ROS failure during soft reboot, reset required: %d" msgstr "" +"Yazılımsal yeniden başlatma sırasında kritik ROS hatası, sıfırlama " +"gerekiyor: %d" -#: supervisor/shared/web_workflow/web_workflow.c -msgid "No IP" -msgstr "IP yok" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS memory allocator failure" +msgstr "" -#: ports/atmel-samd/common-hal/microcontroller/__init__.c -#: ports/cxd56/common-hal/microcontroller/__init__.c -#: ports/mimxrt10xx/common-hal/microcontroller/__init__.c -msgid "No bootloader present" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS internal setup failure" msgstr "" -#: shared-module/usb/core/Device.c -msgid "No configuration set" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "Invalid ROS domain ID" msgstr "" -#: shared-bindings/_bleio/PacketBuffer.c -msgid "No connection: length cannot be determined" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS failed to initialize. Is agent connected?" msgstr "" -#: shared-bindings/board/__init__.c -msgid "No default %q bus" +#: ports/espressif/common-hal/sdioio/SDCard.c +#: ports/raspberrypi/common-hal/sdioio/SDCard.c +#: ports/stm/common-hal/sdioio/SDCard.c +#, c-format +msgid "SDIO Init Error 0x%02x" msgstr "" -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c -#: ports/atmel-samd/common-hal/touchio/TouchIn.c -msgid "No free GCLKs" +#: ports/espressif/common-hal/socketpool/Socket.c +#: ports/zephyr-cp/common-hal/socketpool/Socket.c +msgid "Unsupported socket type" msgstr "" -#: shared-bindings/os/__init__.c -msgid "No hardware random available" +#: ports/espressif/common-hal/socketpool/Socket.c +#: ports/raspberrypi/common-hal/socketpool/Socket.c +msgid "Out of sockets" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "No in in program" +#: ports/espressif/common-hal/socketpool/SocketPool.c +msgid "SocketPool can only be used with %q.%q or any %q.%q" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "No in or out in program" +#: ports/espressif/common-hal/watchdog/WatchDogTimer.c +msgid "%q must be <= %u" +msgstr "%q, %u değerinden küçük veya eşit olmalıdır" + +#: ports/espressif/common-hal/wifi/Monitor.c +msgid "monitor init failed" msgstr "" -#: py/objint.c shared-bindings/time/__init__.c -msgid "No long integer support" +#: ports/espressif/common-hal/wifi/Radio.c +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "Interface must be started" +msgstr "Arayüz başlatılmalıdır" + +#: ports/espressif/common-hal/wifi/Radio.c +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "Invalid multicast MAC address" +msgstr "Geçersiz multicast MAC adresi" + +#: ports/espressif/common-hal/wifi/Radio.c +#: ports/raspberrypi/common-hal/wifi/Radio.c +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "Already scanning for wifi networks" +msgstr "Halihazırda wifi ağları için tarama yapılıyor" + +#: ports/espressif/common-hal/wifi/Radio.c +#: ports/espressif/common-hal/wifi/__init__.c +#: ports/raspberrypi/common-hal/wifi/Radio.c +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "WiFi is not enabled" msgstr "" -#: shared-bindings/wifi/Radio.c -msgid "No network with that ssid" +#: ports/espressif/common-hal/wifi/ScannedNetworks.c +msgid "Failed to allocate wifi scan memory" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "No out in program" +#: ports/espressif/common-hal/wifi/__init__.c +msgid "Failed to allocate Wifi memory" msgstr "" -#: ports/atmel-samd/common-hal/busio/I2C.c -#: ports/espressif/common-hal/busio/I2C.c -#: ports/mimxrt10xx/common-hal/busio/I2C.c ports/nordic/common-hal/busio/I2C.c -#: ports/raspberrypi/common-hal/busio/I2C.c -msgid "No pull up found on SDA or SCL; check your wiring" +#: ports/espressif/common-hal/wifi/__init__.c +#: ports/raspberrypi/common-hal/wifi/__init__.c +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "Only IPv4 addresses supported" msgstr "" -#: shared-module/touchio/TouchIn.c -msgid "No pulldown on pin; 1Mohm recommended" +#: ports/mimxrt10xx/common-hal/busio/SPI.c +#: ports/raspberrypi/bindings/wiznet/PIO_SPI.c shared-bindings/async_spi/SPI.c +#: shared-bindings/busio/SPI.c +msgid "Must provide MISO or MOSI pin" msgstr "" -#: py/moderrno.c -msgid "No space left on device" +#: ports/mimxrt10xx/common-hal/busio/SPI.c +#: ports/mimxrt10xx/common-hal/busio/UART.c +#: ports/mimxrt10xx/common-hal/canio/CAN.c 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 +#: shared-bindings/emmcio/EMMC.c +msgid "Hardware in use, try alternative pins" +msgstr "Donanım kullanımda, alternatif pinleri deneyin" + +#: ports/mimxrt10xx/common-hal/canio/CAN.c +msgid "Unable to send CAN Message: all Tx message buffers are busy" msgstr "" -#: py/moderrno.c -msgid "No such device" +#: ports/mimxrt10xx/common-hal/microcontroller/Processor.c +msgid "" +"Frequency must be 24, 150, 396, 450, 528, 600, 720, 816, 912, 960 or 1008 Mhz" msgstr "" +"Frekans 24, 150, 396, 450, 528, 600, 720, 816, 912, 960 ya da 1008 Mhz " +"olmalıdır" -#: py/moderrno.c -msgid "No such file/directory" +#: ports/nordic/boards/aramcon2_badge/mpconfigboard.h +msgid "You pressed the left button at start up." msgstr "" -#: shared-module/rgbmatrix/RGBMatrix.c -msgid "No timer available" +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "timeout must be < 655.35 secs" msgstr "" -#: shared-module/usb/core/Device.c -msgid "No usb host port initialized" +#: ports/nordic/common-hal/_bleio/Adapter.c +msgid "non-zero timeout must be > 0.01" +msgstr "" + +#: ports/nordic/common-hal/_bleio/UUID.c +msgid "Unexpected nrfx uuid type" msgstr "" #: ports/nordic/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/espressif/common-hal/_bleio/__init__.c #: ports/nordic/common-hal/_bleio/__init__.c -#: shared-bindings/_bleio/CharacteristicBuffer.c -msgid "Not connected" +#, c-format +msgid "Unknown system firmware error: %04x" msgstr "" -#: shared-bindings/audiobusio/I2SOut.c shared-bindings/audioio/AudioOut.c -#: shared-bindings/audiopwmio/PWMAudioOut.c -msgid "Not playing" -msgstr "" +#: ports/nordic/common-hal/alarm/pin/PinAlarm.c +msgid "Cannot wake on pin edge, only level" +msgstr "Pin kenarı ile uyandırılamaz, yalnızca seviye ile uyanabilir" -#: shared-module/jpegio/JpegDecoder.c -msgid "Not supported JPEG standard" +#: ports/nordic/common-hal/audiobusio/I2SOut.c +msgid "Device in use" +msgstr "Cihaz kullanımda" + +#: ports/nordic/common-hal/audiobusio/PDMIn.c +#: ports/stm/common-hal/audiobusio/PDMIn.c +msgid "only sample_rate=16000 is supported" msgstr "" -#: ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c -#: ports/espressif/common-hal/sdioio/SDCard.c -#, c-format -msgid "Number of data_pins must be %d or %d, not %d" +#: ports/nordic/common-hal/audiobusio/PDMIn.c +#: ports/stm/common-hal/audiobusio/PDMIn.c +msgid "only bit_depth=16 is supported" msgstr "" -#: shared-bindings/util.c -msgid "" -"Object has been deinitialized and can no longer be used. Create a new object." +#: ports/nordic/common-hal/busio/UART.c +#, c-format +msgid "error = 0x%08lX" msgstr "" #: ports/nordic/common-hal/busio/UART.c msgid "Odd parity is not supported" msgstr "" -#: supervisor/shared/bluetooth/bluetooth.c -msgid "Off" -msgstr "" +#: ports/nordic/common-hal/countio/Counter.c +#: ports/nordic/common-hal/pulseio/PulseIn.c +#: ports/nordic/common-hal/rotaryio/IncrementalEncoder.c +msgid "All channels in use" +msgstr "Tüm kanallar kullanımda" -#: supervisor/shared/bluetooth/bluetooth.c -msgid "Ok" -msgstr "" +#: ports/nordic/common-hal/microcontroller/Processor.c +msgid "Cannot get temperature" +msgstr "Isı okunamadı" -#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c -#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c -#, c-format -msgid "Only 8 or 16 bit mono with %dx oversampling supported." +#: ports/nordic/common-hal/watchdog/WatchDogTimer.c +msgid "timeout duration exceeded the maximum supported value" msgstr "" -#: ports/espressif/common-hal/wifi/__init__.c -#: ports/raspberrypi/common-hal/wifi/__init__.c -msgid "Only IPv4 addresses supported" -msgstr "" +#: ports/nordic/common-hal/watchdog/WatchDogTimer.c +msgid "%q cannot be changed once mode is set to %q" +msgstr "Mod %q olarak ayarlandıktan sonra %q değiştirilemez" -#: ports/raspberrypi/common-hal/socketpool/Socket.c -msgid "Only IPv4 sockets supported" +#: ports/nordic/common-hal/watchdog/WatchDogTimer.c +msgid "WatchDogTimer cannot be deinitialized once mode is set to RESET" msgstr "" -#: shared-module/displayio/OnDiskBitmap.c +#: ports/nordic/sd_mutex.c #, c-format -msgid "" -"Only Windows format, uncompressed BMP supported: given header size is %d" -msgstr "" +msgid "Failed to acquire mutex, err 0x%04x" +msgstr "Muteks alınamadı, err 0x%04x" -#: shared-bindings/_bleio/Adapter.c -msgid "Only connectable advertisements can be directed" -msgstr "" +#: ports/nordic/sd_mutex.c +#, c-format +msgid "Failed to release mutex, err 0x%04x" +msgstr "Muteks serbest bırakılamadı, err 0x%04x" -#: ports/stm/common-hal/alarm/pin/PinAlarm.c -msgid "Only edge detection is available on this hardware" -msgstr "" +#: ports/raspberrypi/audio_dma.c +msgid "Audio conversion not implemented" +msgstr "Ses dönüşümü implemente edilmedi" -#: shared-bindings/ipaddress/__init__.c -msgid "Only int or string supported for ip" -msgstr "" +#: ports/raspberrypi/bindings/cyw43/__init__.c py/argcheck.c py/objexcept.c +#: shared-bindings/bitmapfilter/__init__.c shared-bindings/canio/CAN.c +#: shared-bindings/digitalio/Pull.c shared-bindings/picogame/Sprite.c +#: shared-bindings/supervisor/__init__.c shared-module/audiofilters/__init__.c +#: shared-module/displayio/legacy/__init__.c +#: shared-module/synthio/Synthesizer.c shared-module/videocore/VideoBuffer.c +msgid "%q must be of type %q or %q, not %q" +msgstr "%q; %q veya %q tipi olmalıdır, %q değil" -#: ports/espressif/common-hal/alarm/touch/TouchAlarm.c -msgid "Only one %q can be set in deep sleep." +#: ports/raspberrypi/bindings/picodvi/AudioOut.c +#: shared-bindings/audiobusio/I2SOut.c shared-bindings/audioio/AudioOut.c +#: shared-bindings/audiopwmio/PWMAudioOut.c shared-bindings/mcp4822/MCP4822.c +#: shared-bindings/usb_audio/USBMicrophone.c +msgid "Not playing" msgstr "" -#: ports/espressif/common-hal/espulp/ULPAlarm.c -msgid "Only one %q can be set." +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Program size invalid" msgstr "" -#: ports/espressif/common-hal/i2ctarget/I2CTarget.c -#: ports/raspberrypi/common-hal/i2ctarget/I2CTarget.c -msgid "Only one address is allowed" -msgstr "" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Init program size invalid" +msgstr "Init program boyutu geçersiz" -#: ports/atmel-samd/common-hal/alarm/time/TimeAlarm.c -#: ports/nordic/common-hal/alarm/time/TimeAlarm.c -#: ports/stm/common-hal/alarm/time/TimeAlarm.c -msgid "Only one alarm.time alarm can be set" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Buffer elements must be 4 bytes long or less" +msgstr "Buffer elementleri 4 bit olmak zorunda" + +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Mismatched data size" msgstr "" -#: ports/espressif/common-hal/alarm/time/TimeAlarm.c -#: ports/raspberrypi/common-hal/alarm/time/TimeAlarm.c -msgid "Only one alarm.time alarm can be set." +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "Out-buffer elements must be <= 4 bytes long" msgstr "" -#: shared-module/displayio/ColorConverter.c -msgid "Only one color can be transparent at a time" +#: ports/raspberrypi/bindings/rp2pio/StateMachine.c +msgid "In-buffer elements must be <= 4 bytes long" +msgstr "Buffer öğeleri <=4 bayt uzunluğunda olmalı" + +#: ports/raspberrypi/bindings/wiznet/PIO_SPI.c shared-bindings/async_spi/SPI.c +#: 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 "Fonksiyon kilit gerektirir" + +#: ports/raspberrypi/bindings/wiznet/PIO_SPI.c shared-bindings/async_spi/SPI.c +#: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c +msgid "buffer slices must be of equal length" msgstr "" -#: py/moderrno.c -msgid "Operation not permitted" +#: ports/raspberrypi/common-hal/alarm/touch/TouchAlarm.c +#: ports/stm/common-hal/alarm/touch/TouchAlarm.c +msgid "Touch alarms not available" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Operation or feature not supported" +#: ports/raspberrypi/common-hal/async_spi/SPI.c shared-bindings/emmcio/EMMC.c +msgid "SPI peripheral in use" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Operation timed out" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audioi2sin/I2SIn.c +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Cannot use GPIO0..15 together with GPIO32..47" +msgstr "GPIO0..15, GPIO32..47 ile birlikte kullanılamaz" + +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audioi2sin/I2SIn.c +msgid "Bit clock and word select must be sequential GPIO pins" +msgstr "Bit saati ve kelime seçimi ardışık GPIO pinleri olmalı" + +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/mcp4822/MCP4822.c +msgid "Too many channels in sample." msgstr "" -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "Out of MDNS service slots" +#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +#: ports/raspberrypi/common-hal/mcp4822/MCP4822.c +msgid "Audio source error" +msgstr "Ses kaynağı hatası" + +#: ports/raspberrypi/common-hal/audioi2sin/I2SIn.c +msgid "%q must be 16, 24, or 32" +msgstr "%q 16,24 veya 32 olmalıdır" + +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "Pins must share PWM slice" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Out of memory" +#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +msgid "No DMA pacing timer found" msgstr "" -#: ports/espressif/common-hal/socketpool/Socket.c -#: ports/raspberrypi/common-hal/socketpool/Socket.c -#: ports/zephyr-cp/common-hal/socketpool/Socket.c -msgid "Out of sockets" +#: ports/raspberrypi/common-hal/busio/I2C.c +#: ports/raspberrypi/common-hal/i2ctarget/I2CTarget.c +msgid "I2C peripheral in use" +msgstr "I2C çevre cihazı kullanımda" + +#: ports/raspberrypi/common-hal/busio/UART.c +msgid "UART peripheral in use" msgstr "" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "Out-buffer elements must be <= 4 bytes long" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "Pin must be on PWM Channel B" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "PWM restart" +#: ports/raspberrypi/common-hal/countio/Counter.c +msgid "RISE_AND_FALL not available on this chip" msgstr "" #: ports/raspberrypi/common-hal/countio/Counter.c @@ -1744,93 +2185,99 @@ msgstr "" msgid "PWM slice channel A already in use" msgstr "" -#: shared-bindings/spitarget/SPITarget.c -msgid "Packet buffers for an SPI transfer must have the same length." +#: ports/raspberrypi/common-hal/floppyio/__init__.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +#: ports/raspberrypi/common-hal/usb_host/Port.c +msgid "All state machines in use" +msgstr "Tüm durum makineleri kullanımda" + +#: ports/raspberrypi/common-hal/floppyio/__init__.c +msgid "timeout waiting for flux" msgstr "" -#: shared-module/jpegio/JpegDecoder.c -msgid "Parameter error" +#: ports/raspberrypi/common-hal/floppyio/__init__.c +#: shared-module/floppyio/__init__.c +msgid "timeout waiting for index pulse" msgstr "" -#: ports/espressif/common-hal/audiobusio/__init__.c -msgid "Peripheral in use" +#: ports/raspberrypi/common-hal/imagecapture/ParallelImageCapture.c +msgid "Pins must be sequential" msgstr "" -#: py/moderrno.c -msgid "Permission denied" +#: ports/raspberrypi/common-hal/mcp4822/MCP4822.c +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c +#: shared-module/aurora_epaper/aurora_framebuffer.c +msgid "Invalid %q and %q" msgstr "" -#: ports/stm/common-hal/alarm/pin/PinAlarm.c -msgid "Pin cannot wake from Deep Sleep" +#: ports/raspberrypi/common-hal/mdns/Server.c +msgid "Out of MDNS service slots" msgstr "" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "Pin count too large" +#: ports/raspberrypi/common-hal/memorymap/AddressRange.c +msgid "Unable to access unaligned IO register" msgstr "" -#: ports/stm/common-hal/alarm/pin/PinAlarm.c -#: ports/stm/common-hal/pulseio/PulseIn.c -msgid "Pin interrupt already in use" +#: ports/raspberrypi/common-hal/memorymap/AddressRange.c +msgid "Unable to write to read-only memory" msgstr "" -#: shared-bindings/adafruit_bus_device/spi_device/SPIDevice.c -msgid "Pin is input only" +#: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c +msgid "All timers for this pin are in use" +msgstr "Bu pin için tüm zamanlayıcılar kullanımda" + +#: ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c +msgid "Pins must be sequential GPIO pins" msgstr "" -#: ports/raspberrypi/common-hal/countio/Counter.c -msgid "Pin must be on PWM Channel B" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Pin count too large" msgstr "" -#: 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" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing jmp_pin. %q[%u] jumps on pin" msgstr "" -#: ports/raspberrypi/common-hal/imagecapture/ParallelImageCapture.c -msgid "Pins must be sequential" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "%q[%u] uses extra pin" msgstr "" -#: ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c -msgid "Pins must be sequential GPIO pins" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_in_pin. %q[%u] waits based on pin" msgstr "" -#: ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c -msgid "Pins must share PWM slice" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "%q[%u] waits on input outside of count" msgstr "" -#: shared-module/usb/core/Device.c -msgid "Pipe error" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_in_pin. %q[%u] shifts in from pin(s)" msgstr "" -#: py/builtinhelp.c -msgid "Plus any modules on the filesystem\n" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "%q[%u] shifts in more bits than pin count" msgstr "" -#: shared-module/vectorio/Polygon.c -msgid "Polygon needs at least 3 points" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_out_pin. %q[%u] shifts out to pin(s)" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Power dipped. Make sure you are providing enough power." +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "%q[%u] shifts out more bits than pin count" msgstr "" -#: shared-bindings/_bleio/Adapter.c -msgid "Prefix buffer must be on the heap" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_set_pin. %q[%u] sets pin(s)" msgstr "" -#: main.c -msgid "Press any key to enter the REPL. Use CTRL-D to reload.\n" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_out_pin. %q[%u] writes pin(s)" msgstr "" -"REPL moda girmek için herhangi bir tuşa basınız. Programı yeniden yüklemek " -"için CTRL+D tuş kombinasyonunu kullanabilirsiniz.\n" -#: main.c -msgid "Pretending to deep sleep until alarm, CTRL-C or file write.\n" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Missing first_in_pin. %q[%u] reads pin(s)" msgstr "" -"Alarma, CTRL-C'ye veya dosya yazana kadar derin uyku moduna geçiliyor.\n" #: ports/raspberrypi/common-hal/rp2pio/StateMachine.c msgid "Program does IN without loading ISR" @@ -1840,2612 +2287,2844 @@ msgstr "" msgid "Program does OUT without loading OSR" msgstr "" -#: ports/raspberrypi/bindings/rp2pio/StateMachine.c -msgid "Program size invalid" -msgstr "" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin state conflicts with initial out pin state" +msgstr "İlk pinin durumu, ilk çıkış pininin durumu ile çakışıyor" -#: ports/espressif/common-hal/espulp/ULP.c -msgid "Program too long" -msgstr "" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Initial set pin direction conflicts with initial out pin direction" +msgstr "İlk pin yönü, ilk çıkış pin yönüyle çakışıyor" -#: shared-bindings/digitalio/DigitalInOut.c -msgid "Pull not used when direction is output." +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "pull masks conflict with direction masks" msgstr "" -#: ports/raspberrypi/common-hal/countio/Counter.c -msgid "RISE_AND_FALL not available on this chip" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No out in program" msgstr "" -#: shared-module/displayio/OnDiskBitmap.c -msgid "RLE-compressed BMP not supported" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in in program" msgstr "" -#: ports/stm/common-hal/os/__init__.c -msgid "RNG DeInit Error" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "No in or out in program" msgstr "" -#: ports/stm/common-hal/os/__init__.c -msgid "RNG Init Error" +#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c +msgid "Mismatched swap flag" msgstr "" -#: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c -#: ports/nordic/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c -msgid "RS485" +#: ports/raspberrypi/common-hal/sdioio/SDCard.c +#, c-format +msgid "Number of data_pins must be %d, not %d" msgstr "" -#: ports/espressif/common-hal/busio/UART.c -#: ports/mimxrt10xx/common-hal/busio/UART.c -msgid "RS485 inversion specified when not in RS485 mode" +#: ports/raspberrypi/common-hal/sdioio/SDCard.c +msgid "Data pins must be consecutive" msgstr "" -#: shared-bindings/alarm/time/TimeAlarm.c shared-bindings/time/__init__.c -msgid "RTC is not supported on this board" +#: ports/raspberrypi/common-hal/socketpool/Socket.c +msgid "Only IPv4 sockets supported" msgstr "" -#: ports/stm/common-hal/os/__init__.c -msgid "Random number generation error" +#: ports/raspberrypi/common-hal/socketpool/SocketPool.c +msgid "SocketPool can only be used with wifi.radio" msgstr "" -#: shared-bindings/_bleio/__init__.c -#: shared-bindings/memorymonitor/AllocationSize.c -#: shared-bindings/pulseio/PulseIn.c shared-module/bitmaptools/__init__.c -#: shared-module/displayio/Bitmap.c shared-module/displayio/Group.c -msgid "Read-only" -msgstr "" +#: ports/raspberrypi/common-hal/usb_host/Port.c +msgid "All dma channels in use" +msgstr "Kullanımdaki tüm dma kanalları" -#: extmod/vfs_fat.c py/moderrno.c -msgid "Read-only filesystem" +#: ports/raspberrypi/common-hal/wifi/Monitor.c +msgid "wifi.Monitor not available" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Received response was invalid" -msgstr "" +#: ports/raspberrypi/common-hal/wifi/Radio.c +msgid "%q is read-only for this board" +msgstr "%q bu kart için salt okunur" -#: supervisor/shared/bluetooth/bluetooth.c -msgid "Reconnecting" +#: ports/raspberrypi/common-hal/wifi/Radio.c +msgid "AP could not be started" msgstr "" -#: shared-bindings/epaperdisplay/EPaperDisplay.c -msgid "Refresh too soon" +#: ports/stm/common-hal/alarm/pin/PinAlarm.c +msgid "Only edge detection is available on this hardware" msgstr "" -#: shared-bindings/canio/RemoteTransmissionRequest.c -msgid "RemoteTransmissionRequests limited to 8 bytes" +#: ports/stm/common-hal/alarm/pin/PinAlarm.c +#: ports/stm/common-hal/pulseio/PulseIn.c +msgid "Pin interrupt already in use" msgstr "" -#: shared-bindings/aesio/aes.c -msgid "Requested AES mode is unsupported" +#: ports/stm/common-hal/alarm/pin/PinAlarm.c +msgid "Pin cannot wake from Deep Sleep" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Requested resource not found" +#: ports/stm/common-hal/alarm/pin/PinAlarm.c +msgid "Deep sleep pins must use a rising edge with pulldown" msgstr "" +"Derin uyku pinleri, aşağı çekme direnci ile yükselen kenar kullanmalıdır" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c -msgid "Right channel unsupported" -msgstr "" +#: ports/stm/common-hal/analogio/AnalogIn.c +msgid "Invalid ADC Unit value" +msgstr "Geçersiz ADC Ünite değeri" -#: shared-module/jpegio/JpegDecoder.c -msgid "Right format but not supported" -msgstr "" +#: ports/stm/common-hal/analogio/AnalogOut.c +#: ports/stm/common-hal/audioio/AudioOut.c +msgid "DAC Device Init Error" +msgstr "DAC cihazı başlatma hatası" -#: main.c -msgid "Running in safe mode! Not running saved code.\n" -msgstr "" +#: ports/stm/common-hal/analogio/AnalogOut.c +#: ports/stm/common-hal/audioio/AudioOut.c +msgid "DAC Channel Init Error" +msgstr "DAC kanalı başlatma hatası" -#: shared-module/sdcardio/SDCard.c -msgid "SD card CSD format not supported" +#: ports/stm/common-hal/audiobusio/PDMIn.c +msgid "only mono is supported" msgstr "" -#: ports/cxd56/common-hal/sdioio/SDCard.c -msgid "SDCard init" +#: ports/stm/common-hal/audiobusio/PDMIn.c +msgid "only oversample=64 is supported" msgstr "" -#: ports/stm/common-hal/sdioio/SDCard.c -#, c-format -msgid "SDIO GetCardInfo Error %d" -msgstr "" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Another PWMAudioOut is already active" +msgstr "Başka bir PWMAudioOut zaten aktif durumda" -#: ports/espressif/common-hal/sdioio/SDCard.c -#: ports/stm/common-hal/sdioio/SDCard.c +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c #, c-format -msgid "SDIO Init Error %x" -msgstr "" +msgid "Buffer length %d too big. It must be less than %d" +msgstr "Mevcut arabellek boyutu %d çok büyük. En fazla %d kadar olmalı" -#: ports/espressif/common-hal/busio/SPI.c -msgid "SPI configuration failed" +#: ports/stm/common-hal/audiopwmio/PWMAudioOut.c +msgid "Failed to buffer the sample" msgstr "" +#: ports/stm/common-hal/busio/I2C.c +msgid "I2C init error" +msgstr "I2C init hatası" + #: ports/stm/common-hal/busio/SPI.c msgid "SPI init error" msgstr "" -#: ports/raspberrypi/common-hal/busio/SPI.c -msgid "SPI peripheral in use" -msgstr "" - #: ports/stm/common-hal/busio/SPI.c msgid "SPI re-init" msgstr "" -#: shared-bindings/is31fl3741/FrameBuffer.c -msgid "Scale dimensions must divide by 3" -msgstr "" +#: ports/stm/common-hal/busio/UART.c +msgid "Internal define error" +msgstr "Dahili tanımlama hatası" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "Scan already in progress. Stop with stop_scan." +#: ports/stm/common-hal/busio/UART.c +msgid "Could not start interrupt, RX busy" +msgstr "Kesinti başlatılamadı, RX kullanımda" + +#: ports/stm/common-hal/busio/UART.c +msgid "UART write" msgstr "" -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c -msgid "Serializer in use" +#: ports/stm/common-hal/busio/UART.c +msgid "UART de-init" msgstr "" -#: shared-bindings/ssl/SSLContext.c -msgid "Server side context cannot have hostname" +#: ports/stm/common-hal/busio/UART.c +msgid "UART re-init" msgstr "" -#: ports/cxd56/common-hal/camera/Camera.c -msgid "Size not supported" +#: ports/stm/common-hal/microcontroller/Processor.c +msgid "Temperature read timed out" msgstr "" -#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c -#: shared-bindings/nvm/ByteArray.c -msgid "Slice and value different lengths." +#: ports/stm/common-hal/microcontroller/Processor.c +msgid "Voltage read timed out" msgstr "" -#: 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" +#: ports/stm/common-hal/os/__init__.c +msgid "RNG Init Error" msgstr "" -#: ports/espressif/common-hal/socketpool/SocketPool.c -#: ports/raspberrypi/common-hal/socketpool/SocketPool.c -#: ports/zephyr-cp/common-hal/socketpool/SocketPool.c -msgid "SocketPool can only be used with wifi.radio" +#: ports/stm/common-hal/os/__init__.c +msgid "Random number generation error" msgstr "" -#: shared-bindings/aesio/aes.c -msgid "Source and destination buffers must be the same length" +#: ports/stm/common-hal/os/__init__.c +msgid "RNG DeInit Error" msgstr "" -#: shared-bindings/paralleldisplaybus/ParallelBus.c -msgid "Specify exactly one of data0 or data_pins" +#: ports/stm/common-hal/pwmio/PWMOut.c +msgid "timer re-init" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Stack overflow. Increase stack size." +#: ports/stm/common-hal/pwmio/PWMOut.c +msgid "channel re-init" msgstr "" -#: shared-bindings/alarm/time/TimeAlarm.c -msgid "Supply one of monotonic_time or epoch_time" +#: ports/stm/common-hal/pwmio/PWMOut.c +msgid "PWM restart" msgstr "" -#: shared-bindings/gnss/GNSS.c -msgid "System entry must be gnss.SatelliteSystem" +#: ports/stm/common-hal/sdioio/SDCard.c +#, c-format +msgid "MMC/SDIO Clock Error %x" msgstr "" -#: ports/stm/common-hal/microcontroller/Processor.c -msgid "Temperature read timed out" +#: ports/stm/common-hal/sdioio/SDCard.c +#, c-format +msgid "SDIO GetCardInfo Error %d" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "The `microcontroller` module was used to boot into safe mode." +#: ports/zephyr-cp/bindings/zephyr_display/Display.c +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/epaperdisplay/EPaperDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +#: shared-bindings/mipidsi/Display.c +msgid "Display rotation must be in 90 degree increments" +msgstr "Ekran dönüşü 90 derecelik artışlarla olmalıdır" + +#: ports/zephyr-cp/bindings/zephyr_display/Display.c +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/epaperdisplay/EPaperDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +msgid ".show(x) removed. Use .root_group = x" msgstr "" -#: py/obj.c -msgid "The above exception was the direct cause of the following exception:" -msgstr "" +#: ports/zephyr-cp/bindings/zephyr_display/Display.c +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +msgid "Brightness not adjustable" +msgstr "Parlaklık ayarlanabilir değil" + +#: ports/zephyr-cp/bindings/zephyr_display/Display.c py/argcheck.c +#: shared-bindings/busdisplay/BusDisplay.c shared-bindings/displayio/Bitmap.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +#: shared-bindings/is31fl3741/FrameBuffer.c +#: shared-bindings/rgbmatrix/RGBMatrix.c +msgid "%q must be %d-%d" +msgstr "%q, %d-%d olmalıdır" + +#: ports/zephyr-cp/bindings/zephyr_display/Display.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +#: shared-module/busdisplay/legacy/BusDisplay.c +#: shared-module/framebufferio/legacy/FramebufferDisplay.c +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "Group already used" +msgstr "Grup zaten kullanılıyor" -#: shared-bindings/rgbmatrix/RGBMatrix.c -msgid "The length of rgb_pins must be 6, 12, 18, 24, or 30" +#: ports/zephyr-cp/common-hal/_bleio/Adapter.c +msgid "Invalid advertising data" msgstr "" -#: shared-module/audiocore/__init__.c -msgid "The sample's %q does not match" +#: ports/zephyr-cp/common-hal/async_spi/SPI.c +#: ports/zephyr-cp/common-hal/audiobusio/I2SOut.c +#: ports/zephyr-cp/common-hal/busio/I2C.c +#: ports/zephyr-cp/common-hal/busio/UART.c +msgid "Use device tree to define %q devices" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Third-party firmware fatal error." +#: ports/zephyr-cp/common-hal/mii/Ethernet.c +msgid "cannot construct ethernet interfaces; use board.ETHERNET" msgstr "" -#: shared-module/imagecapture/ParallelImageCapture.c -msgid "This microcontroller does not support continuous capture." +#: ports/zephyr-cp/common-hal/socketpool/SocketPool.c +msgid "SocketPool can only be used with %q.%q, %q.%q, or %q.%q" msgstr "" -#: shared-module/paralleldisplaybus/ParallelBus.c -msgid "" -"This microcontroller only supports data0=, not data_pins=, because it " -"requires contiguous pins." +#: ports/zephyr-cp/common-hal/usb_hid/Device.c shared-module/usb_hid/Device.c +msgid "USB error" msgstr "" -#: shared-bindings/displayio/TileGrid.c -msgid "Tile height must exactly divide bitmap height" +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "Failed to set hostname" msgstr "" -#: shared-bindings/displayio/TileGrid.c shared-module/displayio/TileGrid.c -msgid "Tile index out of bounds" -msgstr "" +#: ports/zephyr-cp/common-hal/zephyr_display/legacy/Display.c +#: ports/zephyr-cp/common-hal/zephyr_display/lvgl/Display.c +#: shared-module/busdisplay/legacy/BusDisplay.c +#: shared-module/framebufferio/legacy/FramebufferDisplay.c +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "Below minimum frame rate" +msgstr "Minimum kare hızından altında" -#: shared-bindings/displayio/TileGrid.c -msgid "Tile width must exactly divide bitmap width" +#: py/argcheck.c +msgid "function doesn't take keyword arguments" msgstr "" -#: shared-bindings/alarm/time/TimeAlarm.c -msgid "Time is in the past." +#: py/argcheck.c py/bc.c py/objnamedtuple.c shared-bindings/_eve/__init__.c +#: shared-bindings/time/__init__.c +#, c-format +msgid "function takes %d positional arguments but %d were given" msgstr "" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/nordic/common-hal/_bleio/Adapter.c +#: py/argcheck.c #, c-format -msgid "Timeout is too long: Maximum timeout length is %d seconds" +msgid "function missing %d required positional arguments" msgstr "" -#: ports/atmel-samd/common-hal/audiobusio/I2SOut.c -msgid "Too many channels in sample" +#: py/argcheck.c +#, c-format +msgid "function expected at most %d arguments, got %d" msgstr "" -#: ports/raspberrypi/common-hal/audiobusio/I2SOut.c -msgid "Too many channels in sample." -msgstr "" +#: py/argcheck.c shared-bindings/wifi/Radio.c +msgid "'%q' argument required" +msgstr "'%q' argümanı gerekli" -#: ports/espressif/common-hal/_bleio/Characteristic.c -msgid "Too many descriptors" +#: py/argcheck.c +msgid "extra positional arguments given" msgstr "" -#: shared-module/displayio/__init__.c -msgid "Too many display busses; forgot displayio.release_displays() ?" +#: py/argcheck.c py/bc.c py/objnamedtuple.c +#: shared-bindings/traceback/__init__.c +msgid "unexpected keyword argument '%q'" msgstr "" -#: shared-module/displayio/__init__.c -msgid "Too many displays" +#: py/argcheck.c +msgid "extra keyword arguments given" msgstr "" -#: ports/espressif/common-hal/_bleio/PacketBuffer.c -#: ports/nordic/common-hal/_bleio/PacketBuffer.c -msgid "Total data to write is larger than %q" +#: py/argcheck.c shared-bindings/_stage/__init__.c +#: shared-bindings/digitalio/DigitalInOut.c shared-bindings/picogame/__init__.c +msgid "argument num/types mismatch" msgstr "" -#: ports/raspberrypi/common-hal/alarm/touch/TouchAlarm.c -#: ports/stm/common-hal/alarm/touch/TouchAlarm.c -msgid "Touch alarms not available" +#: py/argcheck.c +msgid "keyword argument(s) not implemented - use normal args instead" msgstr "" -#: py/obj.c -msgid "Traceback (most recent call last):\n" -msgstr "" +#: py/argcheck.c +msgid "%q must be %d" +msgstr "%q, %d olmalıdır" -#: ports/stm/common-hal/busio/UART.c -msgid "UART de-init" -msgstr "" +#: py/argcheck.c +msgid "%q must be >= %d" +msgstr "%q >= %d olmalıdır" -#: ports/cxd56/common-hal/busio/UART.c ports/espressif/common-hal/busio/UART.c -#: ports/stm/common-hal/busio/UART.c -msgid "UART init" -msgstr "" +#: py/argcheck.c shared-bindings/gifio/GifWriter.c +#: shared-module/_airlift/__init__.c +msgid "%q must be <= %d" +msgstr "%q <= %d olmalıdır" -#: ports/raspberrypi/common-hal/busio/UART.c -msgid "UART peripheral in use" -msgstr "" +#: py/argcheck.c py/runtime.c shared-bindings/bitmapfilter/__init__.c +#: shared-module/audiodelays/MultiTapDelay.c shared-module/synthio/Note.c +#: shared-module/synthio/__init__.c +msgid "%q must be of type %q, not %q" +msgstr "%q; %q tipi olmalıdır, %q değil" -#: ports/stm/common-hal/busio/UART.c -msgid "UART re-init" -msgstr "" +#: py/argcheck.c +msgid "%q length must be %d-%d" +msgstr "%q boyutları %d-%d olmalıdır" -#: ports/stm/common-hal/busio/UART.c -msgid "UART write" -msgstr "" +#: py/argcheck.c +msgid "%q length must be >= %d" +msgstr "%q boyutu >= %d olmalıdır" -#: main.c -msgid "UID:" -msgstr "" +#: py/argcheck.c shared-module/_airlift/__init__.c +msgid "%q length must be <= %d" +msgstr "%q boyutu <= %d olmalıdır" -#: shared-module/usb_hid/Device.c -msgid "USB busy" -msgstr "" +#: py/argcheck.c shared-bindings/usb_hid/Device.c +msgid "%q length must be %d" +msgstr "%q boyutu %d olmalıdır" -#: supervisor/shared/safe_mode.c -msgid "USB devices need more endpoints than are available." -msgstr "" +#: py/argcheck.c shared-module/audiofilters/__init__.c +msgid "%q in %q must be of type %q, not %q" +msgstr "%q'nün içindeki %q, %q tipi olmalıdır, %q değil" -#: supervisor/shared/safe_mode.c -msgid "USB devices specify too many interface names." +#: py/asmthumb.c +msgid "too many locals for native method" msgstr "" -#: shared-module/usb_hid/Device.c -msgid "USB error" +#: py/asmxtensa.c +msgid "ERROR: xtensa %q out of range" msgstr "" -#: shared-bindings/_bleio/UUID.c -msgid "UUID integer value must be 0-0xffff" +#: py/asmxtensa.c +msgid "ERROR: %q %q not word-aligned" msgstr "" -#: shared-bindings/_bleio/UUID.c -msgid "UUID string not 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'" +#: py/bc.c py/objnamedtuple.c +msgid "%q() takes %d positional arguments but %d were given" +msgstr "%q(), %d konumsal argümanını alır ancak %d verildi" + +#: py/bc.c py/objnamedtuple.c +msgid "function got multiple values for argument '%q'" msgstr "" -#: shared-bindings/_bleio/UUID.c -msgid "UUID value is not str, int or byte buffer" +#: py/bc.c +msgid "unexpected keyword argument" msgstr "" -#: ports/raspberrypi/common-hal/memorymap/AddressRange.c -msgid "Unable to access unaligned IO register" +#: py/bc.c +#, c-format +msgid "function missing required positional argument #%d" 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" +#: py/bc.c +msgid "function missing required keyword argument '%q'" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "Unable to allocate to the heap." +#: py/bc.c +msgid "function missing keyword-only argument" msgstr "" -#: ports/espressif/common-hal/busio/I2C.c -msgid "Unable to create lock" +#: py/binary.c py/objarray.c +msgid "bad typecode" msgstr "" -#: shared-module/i2cdisplaybus/I2CDisplayBus.c -#: shared-module/is31fl3741/IS31FL3741.c -#, c-format -msgid "Unable to find I2C Display at %x" +#: py/binary.c +msgid "integer out of range" msgstr "" -#: py/parse.c -msgid "Unable to init parser" +#: py/builtinevex.c +msgid "bad compile mode" msgstr "" -#: shared-module/displayio/OnDiskBitmap.c -msgid "Unable to read color palette data" +#: py/builtinhelp.c +msgid "Plus any modules on the filesystem\n" msgstr "" -#: ports/mimxrt10xx/common-hal/canio/CAN.c -msgid "Unable to send CAN Message: all Tx message buffers are busy" +#: py/builtinhelp.c +msgid "object " msgstr "" -#: ports/espressif/common-hal/mdns/Server.c -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "Unable to start mDNS query" +#: py/builtinhelp.c +msgid " is of type %q\n" +msgstr " nesnesi, %q tipindedir\n" + +#: py/builtinhelp.c +#, c-format +msgid "" +"Welcome to Adafruit CircuitPython %s!\n" +"\n" +"Visit circuitpython.org for more information.\n" +"\n" +"To list built-in modules type `help(\"modules\")`.\n" msgstr "" -#: shared-bindings/nvm/ByteArray.c -msgid "Unable to write to nvm." +#: py/builtinimport.c +msgid "script compilation not supported" msgstr "" -#: ports/raspberrypi/common-hal/memorymap/AddressRange.c -msgid "Unable to write to read-only memory" +#: py/builtinimport.c +msgid "can't perform relative import" msgstr "" -#: shared-bindings/alarm/SleepMemory.c -msgid "Unable to write to sleep_memory." +#: py/builtinimport.c +msgid "module not found" msgstr "" -#: ports/nordic/common-hal/_bleio/UUID.c -msgid "Unexpected nrfx uuid type" +#: py/builtinimport.c +msgid "no module named '%q'" msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown BLE error at %s:%d: %d" +#: py/builtinimport.c +msgid "relative import" msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown BLE error: %d" +#: py/compile.c +msgid "can't assign to expression" msgstr "" -#: ports/espressif/common-hal/max3421e/Max3421E.c -#: ports/raspberrypi/common-hal/wifi/__init__.c -#, c-format -msgid "Unknown error code %d" +#: py/compile.c +msgid "multiple *x in assignment" msgstr "" -#: shared-bindings/wifi/Radio.c -#, c-format -msgid "Unknown failure %d" +#: py/compile.c +msgid "non-default argument follows default argument" msgstr "" -#: ports/nordic/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown gatt error: 0x%04x" +#: py/compile.c +msgid "invalid micropython decorator" msgstr "" -#: ports/atmel-samd/common-hal/alarm/pin/PinAlarm.c -#: supervisor/shared/safe_mode.c -msgid "Unknown reason." +#: py/compile.c +msgid "invalid arch" msgstr "" -#: ports/nordic/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown security error: 0x%04x" +#: py/compile.c +msgid "can't delete expression" msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown system firmware error at %s:%d: %d" +#: py/compile.c +msgid "'break'/'continue' outside loop" +msgstr "Döngü dışında 'break'/'continue'" + +#: py/compile.c +msgid "'return' outside function" +msgstr "fonksiyon dışında 'return'" + +#: py/compile.c +msgid "import * not at module level" msgstr "" -#: ports/nordic/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown system firmware error: %04x" +#: py/compile.c +msgid "identifier redefined as global" msgstr "" -#: ports/espressif/common-hal/_bleio/__init__.c -#, c-format -msgid "Unknown system firmware error: %d" +#: py/compile.c +msgid "no binding for nonlocal found" msgstr "" -#: shared-bindings/adafruit_pixelbuf/PixelBuf.c -#: shared-module/_pixelmap/PixelMap.c -#, c-format -msgid "Unmatched number of items on RHS (expected %d, got %d)." +#: py/compile.c +msgid "identifier redefined as nonlocal" msgstr "" -#: ports/nordic/common-hal/_bleio/__init__.c -msgid "" -"Unspecified issue. Can be that the pairing prompt on the other device was " -"declined or ignored." +#: py/compile.c +msgid "can't declare nonlocal in outer code" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "Unsupported colorspace" +#: py/compile.c +msgid "default 'except' must be last" msgstr "" -#: shared-module/displayio/bus_core.c -msgid "Unsupported display bus type" +#: py/compile.c +msgid "async for/with outside async function" msgstr "" -#: shared-module/audiocore/WaveFile.c -msgid "Unsupported format" -msgstr "" +#: py/compile.c +msgid "*x must be assignment target" +msgstr "*x atama hedefi olmalıdır" -#: shared-bindings/hashlib/__init__.c -msgid "Unsupported hash algorithm" +#: py/compile.c +msgid "super() can't find self" msgstr "" -#: ports/espressif/common-hal/socketpool/Socket.c -#: ports/zephyr-cp/common-hal/socketpool/Socket.c -msgid "Unsupported socket type" +#: py/compile.c +msgid "* arg after **" msgstr "" -#: ports/espressif/common-hal/_bleio/Adapter.c -#: ports/espressif/common-hal/dualbank/__init__.c -msgid "Update failed" +#: py/compile.c +msgid "* arg after kwarg" msgstr "" -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Descriptor.c -msgid "Value length != required fixed length" +#: py/compile.c +msgid "too many args" msgstr "" -#: ports/espressif/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Descriptor.c -msgid "Value length > max_length" +#: py/compile.c +msgid "LHS of keyword arg must be an id" msgstr "" -#: ports/espressif/common-hal/espidf/__init__.c -msgid "Version was invalid" +#: py/compile.c +msgid "positional arg after **" msgstr "" -#: ports/stm/common-hal/microcontroller/Processor.c -msgid "Voltage read timed out" +#: py/compile.c +msgid "positional arg after keyword arg" msgstr "" -#: main.c -msgid "WARNING: Your code filename has two extensions\n" +#: py/compile.c py/parse.c +msgid "invalid syntax" msgstr "" -#: ports/nordic/common-hal/watchdog/WatchDogTimer.c -msgid "WatchDogTimer cannot be deinitialized once mode is set to RESET" +#: py/compile.c +msgid "expecting key:value for dict" msgstr "" -#: py/builtinhelp.c -#, c-format -msgid "" -"Welcome to Adafruit CircuitPython %s!\n" -"\n" -"Visit circuitpython.org for more information.\n" -"\n" -"To list built-in modules type `help(\"modules\")`.\n" +#: py/compile.c +msgid "expecting just a value for set" msgstr "" -#: supervisor/shared/web_workflow/web_workflow.c -msgid "Wi-Fi: " -msgstr "" +#: py/compile.c +msgid "'yield' outside function" +msgstr "fonksiyon dışında 'yield'" -#: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "Wifi is not enabled" -msgstr "" +#: py/compile.c +msgid "'yield from' inside async function" +msgstr "asenkron fonksiyon içinde 'yield from'" -#: main.c -msgid "Woken up by alarm.\n" -msgstr "" +#: py/compile.c +msgid "'await' outside function" +msgstr "fonksiyon dışında 'await'" -#: ports/espressif/common-hal/_bleio/PacketBuffer.c -#: ports/nordic/common-hal/_bleio/PacketBuffer.c -msgid "Writes not supported on Characteristic" +#: py/compile.c +msgid "unknown type '%q'" msgstr "" -#: 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/meowmeow/mpconfigboard.h -msgid "You pressed both buttons at start up." +#: py/compile.c +msgid "annotation must be an identifier" msgstr "" -#: ports/espressif/boards/m5stack_core_basic/mpconfigboard.h -#: ports/espressif/boards/m5stack_core_fire/mpconfigboard.h -#: ports/espressif/boards/m5stack_stick_c/mpconfigboard.h -#: ports/espressif/boards/m5stack_stick_c_plus/mpconfigboard.h -#: ports/espressif/boards/m5stack_stick_c_plus2/mpconfigboard.h -msgid "You pressed button A at start up." +#: py/compile.c +msgid "argument name reused" msgstr "" -#: ports/espressif/boards/m5stack_m5paper/mpconfigboard.h -msgid "You pressed button DOWN at start up." +#: py/compile.c +msgid "inline assembler must be a function" msgstr "" -#: supervisor/shared/safe_mode.c -msgid "You pressed the BOOT button at start up" +#: py/compile.c +msgid "unknown type" msgstr "" -#: ports/espressif/boards/adafruit_feather_esp32c6_4mbflash_nopsram/mpconfigboard.h -#: ports/espressif/boards/adafruit_itsybitsy_esp32/mpconfigboard.h -#: ports/espressif/boards/waveshare_esp32_c6_lcd_1_47/mpconfigboard.h -msgid "You pressed the BOOT button at start up." +#: py/compile.c +msgid "return annotation must be an identifier" msgstr "" -#: ports/espressif/boards/adafruit_huzzah32_breakout/mpconfigboard.h -msgid "You pressed the GPIO0 button at start up." +#: py/compile.c +msgid "expecting an assembler instruction" msgstr "" -#: ports/espressif/boards/espressif_esp32_lyrat/mpconfigboard.h -msgid "You pressed the Rec button at start up." -msgstr "" +#: py/compile.c +msgid "'label' requires 1 argument" +msgstr "'label' 1 argümana ihtiyaç duyar" -#: ports/espressif/boards/adafruit_feather_esp32_v2/mpconfigboard.h -msgid "You pressed the SW38 button at start up." +#: py/compile.c +msgid "label redefined" msgstr "" -#: ports/espressif/boards/hardkernel_odroid_go/mpconfigboard.h -#: ports/espressif/boards/vidi_x/mpconfigboard.h -msgid "You pressed the VOLUME button at start up." -msgstr "" +#: py/compile.c +msgid "'align' requires 1 argument" +msgstr "'align' 1 argümana ihtiyaç duyar" -#: ports/espressif/boards/m5stack_atom_echo/mpconfigboard.h -#: ports/espressif/boards/m5stack_atom_lite/mpconfigboard.h -#: ports/espressif/boards/m5stack_atom_matrix/mpconfigboard.h -#: ports/espressif/boards/m5stack_atom_u/mpconfigboard.h -msgid "You pressed the central button at start up." -msgstr "" +#: py/compile.c +msgid "'data' requires at least 2 arguments" +msgstr "'data' en az 2 argümana ihtiyaç duyar" -#: ports/nordic/boards/aramcon2_badge/mpconfigboard.h -msgid "You pressed the left button at start up." -msgstr "" +#: py/compile.c +msgid "'data' requires integer arguments" +msgstr "'data' integer tipinde argümanlara ihtiyaç duyar" -#: supervisor/shared/safe_mode.c -msgid "You pressed the reset button during boot." +#: py/compile.c +msgid "cannot emit native code for this architecture" msgstr "" -#: supervisor/shared/micropython.c -msgid "[truncated due to length]" +#: py/emitbc.c +msgid "bytecode overflow" msgstr "" -#: py/objtype.c -msgid "__init__() should return None" +#: py/emitinlinerv32.c +msgid "can only have up to 4 parameters for RV32 assembly" msgstr "" -#: py/objtype.c -#, c-format -msgid "__init__() should return None, not '%s'" +#: py/emitinlinerv32.c +msgid "parameters must be registers in sequence a0 to a3" msgstr "" -#: py/objobject.c -msgid "__new__ arg must be a user-type" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: expecting %q" msgstr "" -#: extmod/modbinascii.c extmod/modhashlib.c py/objarray.c -msgid "a bytes-like object is required" +#: py/emitinlinerv32.c +msgid "opcode '%q': expecting %d arguments" msgstr "" -#: shared-bindings/i2ctarget/I2CTarget.c -msgid "addresses is empty" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: out of range" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "already playing" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: unknown register" msgstr "" -#: py/compile.c -msgid "annotation must be an identifier" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: undefined label '%q'" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "arange: cannot compute length" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: must not be zero" msgstr "" -#: py/modbuiltins.c -msgid "arg is an empty sequence" +#: py/emitinlinerv32.c +msgid "opcode '%q': registers must be different" msgstr "" -#: py/objobject.c -msgid "arg must be user-type" +#: py/emitinlinerv32.c +msgid "opcode '%q': malformed register list" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "argsort argument must be an ndarray" +#: py/emitinlinerv32.c +msgid "opcode '%q': invalid stack adjustment" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "argsort is not implemented for flattened arrays" +#: py/emitinlinerv32.c +msgid "opcode '%q' argument %d: wrong register(s)" msgstr "" -#: extmod/ulab/code/numpy/random/random.c -msgid "argument must be None, an integer or a tuple of integers" +#: py/emitinlinerv32.c +msgid "invalid RV32 instruction '%q'" msgstr "" -#: py/compile.c -msgid "argument name reused" +#: py/emitinlinethumb.c +msgid "can only have up to 4 parameters to Thumb assembly" msgstr "" -#: py/argcheck.c shared-bindings/_stage/__init__.c -#: shared-bindings/digitalio/DigitalInOut.c -msgid "argument num/types mismatch" +#: py/emitinlinethumb.c +msgid "parameters must be registers in sequence r0 to r3" msgstr "" -#: extmod/ulab/code/numpy/numerical.c extmod/ulab/code/numpy/transform.c -msgid "arguments must be ndarrays" -msgstr "" +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' expects at most r%d" +msgstr "'%s' en fazla r%d bekler" -#: extmod/ulab/code/ndarray.c -msgid "array and index length must be equal" -msgstr "" +#: py/emitinlinethumb.c py/emitinlinextensa.c +#, c-format +msgid "'%s' expects a register" +msgstr "'%s' bir yazmaç bekliyor" -#: extmod/ulab/code/numpy/io/io.c -msgid "array has too many dimensions" -msgstr "" +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' expects a special register" +msgstr "'%s' özel bir yazmaç bekliyor" -#: extmod/ulab/code/ndarray.c -msgid "array is too big" -msgstr "" +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' expects an FPU register" +msgstr "'%s' bir FPU yazmacı bekliyor" -#: py/objarray.c shared-bindings/alarm/SleepMemory.c -#: shared-bindings/memorymap/AddressRange.c shared-bindings/nvm/ByteArray.c -msgid "array/bytes required on right side" -msgstr "" +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' expects {r0, r1, ...}" +msgstr "'%s' {r0, r1, ...} bekliyor" + +#: py/emitinlinethumb.c py/emitinlinextensa.c +#, c-format +msgid "'%s' expects an integer" +msgstr "'%s' bir integer bekliyor" + +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' integer 0x%x doesn't fit in mask 0x%x" +msgstr "'%s' integer 0x%x, 0x%x maskesine uymuyor" -#: py/asmxtensa.c -msgid "asm overflow" -msgstr "" +#: py/emitinlinethumb.c +#, c-format +msgid "'%s' expects an address of the form [a, b]" +msgstr "'%s', [a, b] biçiminde bir adres bekliyor" -#: py/compile.c -msgid "async for/with outside async function" -msgstr "" +#: py/emitinlinethumb.c py/emitinlinextensa.c +#, c-format +msgid "'%s' expects a label" +msgstr "'%s' bir etiket bekliyor" -#: extmod/ulab/code/numpy/numerical.c -msgid "attempt to get (arg)min/(arg)max of empty sequence" +#: py/emitinlinethumb.c py/emitinlinextensa.c +msgid "label '%q' not defined" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "attempt to get argmin/argmax of an empty sequence" +#: py/emitinlinethumb.c +#, c-format +msgid "unsupported Thumb instruction '%s' with %d arguments" msgstr "" -#: py/objstr.c -msgid "attributes not supported" +#: py/emitinlinethumb.c +msgid "branch not in range" msgstr "" -#: ports/espressif/common-hal/audioio/AudioOut.c -msgid "audio format not supported" +#: py/emitinlinextensa.c +msgid "can only have up to 4 parameters to Xtensa assembly" msgstr "" -#: extmod/ulab/code/ulab_tools.c -msgid "axis is out of bounds" +#: py/emitinlinextensa.c +msgid "parameters must be registers in sequence a2 to a5" msgstr "" -#: extmod/ulab/code/numpy/numerical.c extmod/ulab/code/ulab_tools.c -msgid "axis must be None, or an integer" -msgstr "" +#: py/emitinlinextensa.c +#, c-format +msgid "'%s' integer %d isn't within range %d..%d" +msgstr "'%s' integer %d, %d..%d aralığında değil" -#: extmod/ulab/code/numpy/numerical.c -msgid "axis too long" -msgstr "" +#: py/emitinlinextensa.c +#, c-format +msgid "%d is not a multiple of %d" +msgstr "%d %d'nin katı değil" -#: shared-bindings/bitmaptools/__init__.c -msgid "background value out of range of target" +#: py/emitinlinextensa.c +#, c-format +msgid "unsupported Xtensa instruction '%s' with %d arguments" msgstr "" -#: py/builtinevex.c -msgid "bad compile mode" +#: py/emitnative.c +msgid "conversion to object" msgstr "" -#: py/objstr.c -msgid "bad conversion specifier" +#: py/emitnative.c +msgid "local '%q' used before type known" msgstr "" -#: py/objstr.c -msgid "bad format string" +#: py/emitnative.c +msgid "can't load from '%q'" msgstr "" -#: py/binary.c py/objarray.c -msgid "bad typecode" +#: py/emitnative.c +msgid "can't load with '%q' index" msgstr "" #: py/emitnative.c -msgid "binary op %q not implemented" +msgid "local '%q' has type '%q' but source is '%q'" msgstr "" -#: ports/espressif/common-hal/audiobusio/PDMIn.c -msgid "bit_depth must be 8, 16, 24, or 32." +#: py/emitnative.c +msgid "can't store '%q'" msgstr "" -#: shared-module/bitmapfilter/__init__.c -msgid "bitmap size and depth must match" +#: py/emitnative.c +msgid "can't store to '%q'" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "bitmap sizes must match" +#: py/emitnative.c +msgid "can't store with '%q' index" msgstr "" -#: extmod/modrandom.c -msgid "bits must be 32 or less" +#: py/emitnative.c +msgid "can't implicitly convert '%q' to 'bool'" msgstr "" -#: shared-bindings/audiodelays/Echo.c shared-bindings/audiodelays/PitchShift.c -#: shared-bindings/audiofilters/Distortion.c -#: shared-bindings/audiofilters/Filter.c shared-bindings/audiomixer/Mixer.c -msgid "bits_per_sample must be 8 or 16" +#: py/emitnative.c +msgid "'not' not implemented" msgstr "" -#: py/emitinlinethumb.c -msgid "branch not in range" +#: py/emitnative.c +msgid "can't do unary op of '%q'" msgstr "" -#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c -msgid "buffer is smaller than requested size" +#: py/emitnative.c +msgid "div/mod not implemented for uint" msgstr "" -#: extmod/ulab/code/numpy/create.c extmod/ulab/code/utils/utils.c -msgid "buffer size must be a multiple of element size" +#: py/emitnative.c +msgid "comparison of int and uint" msgstr "" -#: shared-module/struct/__init__.c -msgid "buffer size must match format" +#: py/emitnative.c +msgid "binary op %q not implemented" msgstr "" -#: shared-bindings/bitbangio/SPI.c shared-bindings/busio/SPI.c -msgid "buffer slices must be of equal length" +#: py/emitnative.c +msgid "can't do binary op between '%q' and '%q'" msgstr "" -#: py/modstruct.c shared-module/struct/__init__.c -msgid "buffer too small" +#: py/emitnative.c +msgid "casting" msgstr "" -#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c -msgid "buffer too small for requested bytes" +#: py/emitnative.c +msgid "return expected '%q' but got '%q'" msgstr "" -#: py/emitbc.c -msgid "bytecode overflow" +#: py/emitnative.c +msgid "native raise" msgstr "" -#: py/objarray.c -msgid "bytes length not a multiple of item size" +#: py/emitnative.c +msgid "must raise an object" msgstr "" -#: py/objstr.c -msgid "bytes value out of range" +#: py/emitnative.c +msgid "native yield" msgstr "" -#: ports/atmel-samd/bindings/samd/Clock.c -msgid "calibration is out of range" +#: py/lexer.c +msgid "unicode name escapes" msgstr "" -#: ports/atmel-samd/bindings/samd/Clock.c -msgid "calibration is read only" +#: py/modbuiltins.c py/objstr.c +msgid "char not in range(0x110000)" msgstr "" -#: shared-module/vectorio/Circle.c shared-module/vectorio/Polygon.c -#: shared-module/vectorio/Rectangle.c -msgid "can only have one parent" +#: py/modbuiltins.c +msgid "chr() arg not in range(256)" msgstr "" -#: py/emitinlinethumb.c -msgid "can only have up to 4 parameters to Thumb assembly" +#: py/modbuiltins.c +msgid "arg is an empty sequence" msgstr "" -#: py/emitinlinextensa.c -msgid "can only have up to 4 parameters to Xtensa assembly" +#: py/modbuiltins.c +msgid "ord expects a character" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "can only specify one unknown dimension" +#: py/modbuiltins.c +#, c-format +msgid "ord() expected a character, but string of length %d found" msgstr "" -#: py/objtype.c -msgid "can't add special method to already-subclassed class" -msgstr "" +#: py/modbuiltins.c +msgid "3-arg pow() not supported" +msgstr "3-argümanlı pow() desteklenmemektedir" -#: py/compile.c -msgid "can't assign to expression" +#: py/modbuiltins.c +msgid "must use keyword argument for key function" msgstr "" -#: extmod/modasyncio.c -msgid "can't cancel self" +#: py/moderrno.c +msgid "Operation not permitted" msgstr "" -#: py/obj.c shared-module/adafruit_pixelbuf/PixelBuf.c -msgid "can't convert %q to %q" +#: py/moderrno.c +msgid "No such file/directory" msgstr "" -#: py/obj.c -#, c-format -msgid "can't convert %s to complex" -msgstr "" +#: py/moderrno.c +msgid "Input/output error" +msgstr "Giriş/çıkış hatası" -#: py/obj.c -#, c-format -msgid "can't convert %s to float" +#: py/moderrno.c +msgid "Permission denied" msgstr "" -#: py/objint.c py/runtime.c -#, c-format -msgid "can't convert %s to int" -msgstr "" +#: py/moderrno.c +msgid "File exists" +msgstr "Dosya var" -#: py/objstr.c -msgid "can't convert '%q' object to %q implicitly" +#: py/moderrno.c +msgid "No such device" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "can't convert complex to float" +#: py/moderrno.c +msgid "No space left on device" msgstr "" -#: py/obj.c -msgid "can't convert to complex" +#: py/modmath.c shared-bindings/math/__init__.c +msgid "math domain error" msgstr "" -#: py/obj.c -msgid "can't convert to float" +#: py/modmath.c +msgid "negative factorial" msgstr "" -#: py/runtime.c -msgid "can't convert to int" +#: py/modmicropython.c +msgid "schedule queue full" msgstr "" -#: py/objstr.c -msgid "can't convert to str implicitly" +#: py/modstruct.c shared-bindings/picogame/Bitmap.c +#: shared-bindings/picogame/Canvas.c shared-bindings/picogame/Framebuffer.c +#: shared-module/picogame/__init__.c shared-module/struct/__init__.c +msgid "buffer too small" msgstr "" -#: py/compile.c -msgid "can't declare nonlocal in outer code" +#: py/modstruct.c +#, c-format +msgid "pack expected %d items for packing (got %d)" msgstr "" -#: py/compile.c -msgid "can't delete expression" +#: py/modthread.c +msgid "expecting a dict for keyword args" msgstr "" -#: py/emitnative.c -msgid "can't do binary op between '%q' and '%q'" +#: py/modweakref.c +msgid "not a heap object" msgstr "" -#: py/emitnative.c -msgid "can't do unary op of '%q'" +#: py/nativeglue.c +msgid "set unsupported" msgstr "" -#: py/emitnative.c -msgid "can't implicitly convert '%q' to 'bool'" +#: py/nativeglue.c +msgid "slice unsupported" msgstr "" -#: py/runtime.c -msgid "can't import name %q" +#: py/nativeglue.c +msgid "float unsupported" msgstr "" -#: py/emitnative.c -msgid "can't load from '%q'" +#: py/obj.c shared-module/adafruit_pixelbuf/PixelBuf.c +msgid "can't convert %q to %q" msgstr "" -#: py/emitnative.c -msgid "can't load with '%q' index" -msgstr "" +#: py/obj.c +msgid "During handling of the above exception, another exception occurred:" +msgstr "Yukarıdaki hatanın işlenmesi sırasında başka bir hata oluştu:" -#: py/builtinimport.c -msgid "can't perform relative import" +#: py/obj.c +msgid "The above exception was the direct cause of the following exception:" msgstr "" -#: py/objgenerator.c -msgid "can't send non-None value to a just-started generator" -msgstr "" +#: py/obj.c +msgid " File \"%q\", line %d" +msgstr " \"%q\" dosyası, %d numaralı satır" -#: shared-module/sdcardio/SDCard.c -msgid "can't set 512 block size" -msgstr "" +#: py/obj.c +msgid " File \"%q\"" +msgstr " \"%q\" dosyası" -#: py/objexcept.c py/objnamedtuple.c -msgid "can't set attribute" -msgstr "" +#: py/obj.c +msgid ", in %q\n" +msgstr ", içinde %q\n" -#: py/runtime.c -msgid "can't set attribute '%q'" +#: py/obj.c +msgid "Traceback (most recent call last):\n" msgstr "" -#: py/emitnative.c -msgid "can't store '%q'" +#: py/obj.c +msgid "can't convert to float" msgstr "" -#: py/emitnative.c -msgid "can't store to '%q'" +#: py/obj.c +#, c-format +msgid "can't convert %s to float" msgstr "" -#: py/emitnative.c -msgid "can't store with '%q' index" +#: py/obj.c +msgid "can't convert to complex" msgstr "" -#: py/objstr.c -msgid "" -"can't switch from automatic field numbering to manual field specification" +#: py/obj.c +#, c-format +msgid "can't convert %s to complex" msgstr "" -#: py/objstr.c -msgid "" -"can't switch from manual field specification to automatic field numbering" +#: py/obj.c +msgid "expected tuple/list" msgstr "" -#: py/objcomplex.c -msgid "can't truncate-divide a complex number" +#: py/obj.c +#, c-format +msgid "object '%s' isn't a tuple or list" msgstr "" -#: extmod/modasyncio.c -msgid "can't wait" +#: py/obj.c +msgid "tuple/list has wrong length" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "cannot assign new shape" +#: py/obj.c +#, c-format +msgid "requested length %d but object has length %d" msgstr "" -#: extmod/ulab/code/ndarray_operators.c -msgid "cannot cast output with casting rule" +#: py/obj.c +msgid "indices must be integers" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "cannot convert complex to dtype" -msgstr "" +#: py/obj.c +msgid "%q indices must be integers, not %s" +msgstr "%q indeksleri integer olmalı, %s değil" -#: extmod/ulab/code/ndarray.c -msgid "cannot convert complex type" +#: py/obj.c +msgid "object has no len" msgstr "" -#: py/objtype.c -msgid "cannot create '%q' instances" +#: py/obj.c +#, c-format +msgid "object of type '%s' has no len()" msgstr "" -#: py/objtype.c -msgid "cannot create instance" +#: py/obj.c +msgid "object doesn't support item deletion" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "cannot delete array elements" -msgstr "" +#: py/obj.c +#, c-format +msgid "'%s' object doesn't support item deletion" +msgstr "'%s' nesnesi, öğe silmeyi desteklemiyor" -#: extmod/ulab/code/ndarray.c -msgid "cannot reshape array" +#: py/obj.c +msgid "object isn't subscriptable" msgstr "" -#: py/emitnative.c -msgid "casting" -msgstr "" +#: py/obj.c +#, c-format +msgid "'%s' object isn't subscriptable" +msgstr "'%s' nesnesi subscriptable özelliğe sahip değil" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "channel re-init" +#: py/obj.c +msgid "object doesn't support item assignment" msgstr "" -#: shared-bindings/_stage/Text.c -msgid "chars buffer too small" -msgstr "" +#: py/obj.c +#, c-format +msgid "'%s' object doesn't support item assignment" +msgstr "'%s' nesnesi, öğe atamasını desteklemiyor" -#: py/modbuiltins.c -msgid "chr() arg not in range(0x110000)" +#: py/obj.c +msgid "object with buffer protocol required" msgstr "" -#: py/modbuiltins.c -msgid "chr() arg not in range(256)" +#: py/objarray.c +msgid "bytes length not a multiple of item size" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "clip point must be (x,y) tuple" +#: py/objarray.c py/objstr.c +msgid "string argument without an encoding" msgstr "" -#: shared-bindings/msgpack/ExtType.c -msgid "code outside range 0~127" +#: py/objarray.c +msgid "memoryview: length is not a multiple of itemsize" msgstr "" -#: shared-bindings/displayio/Palette.c -msgid "color buffer must be 3 bytes (RGB) or 4 bytes (RGB + pad byte)" +#: py/objarray.c py/objstr.c +msgid "substring not found" msgstr "" -#: shared-bindings/displayio/Palette.c -msgid "color buffer must be a buffer, tuple, list, or int" +#: py/objarray.c py/objstr.c py/objstrunicode.c py/objtuple.c +#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c +#: shared-bindings/nvm/ByteArray.c +msgid "only slices with step=1 (aka None) are supported" msgstr "" -#: shared-bindings/displayio/Palette.c -msgid "color buffer must be a bytearray or array of type 'b' or 'B'" +#: py/objarray.c +msgid "lhs and rhs should be compatible" msgstr "" -#: shared-bindings/displayio/Palette.c -msgid "color must be between 0x000000 and 0xffffff" +#: py/objarray.c shared-bindings/alarm/SleepMemory.c +#: shared-bindings/memorymap/AddressRange.c shared-bindings/nvm/ByteArray.c +msgid "array/bytes required on right side" msgstr "" -#: py/emitnative.c -msgid "comparison of int and uint" +#: py/objarray.c +msgid "memoryview offset too large" msgstr "" #: py/objcomplex.c -msgid "complex divide by zero" -msgstr "" - -#: py/objfloat.c py/parsenum.c -msgid "complex values not supported" +msgid "can't truncate-divide a complex number" msgstr "" -#: extmod/modzlib.c -msgid "compression header" +#: py/objcomplex.c +msgid "complex divide by zero" msgstr "" -#: py/emitnative.c -msgid "conversion to object" -msgstr "" +#: py/objcomplex.c +msgid "0.0 to a complex power" +msgstr "0.0'dan bir karmaşık güce" -#: extmod/ulab/code/numpy/filter.c -msgid "convolve arguments must be linear arrays" +#: py/objdeque.c +msgid "full" msgstr "" -#: extmod/ulab/code/numpy/filter.c -msgid "convolve arguments must be ndarrays" +#: py/objdeque.c +msgid "empty" msgstr "" -#: extmod/ulab/code/numpy/filter.c -msgid "convolve arguments must not be empty" +#: py/objdict.c +msgid "dict update sequence has wrong length" msgstr "" -#: extmod/ulab/code/numpy/io/io.c -msgid "corrupted file" +#: py/objexcept.c py/objnamedtuple.c +msgid "can't set attribute" msgstr "" -#: extmod/ulab/code/numpy/poly.c -msgid "could not invert Vandermonde matrix" +#: py/objfloat.c py/parsenum.c +msgid "complex values not supported" msgstr "" -#: shared-module/sdcardio/SDCard.c -msgid "couldn't determine SD card version" +#: py/objgenerator.c +msgid "generator already executing" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "cross is defined for 1D arrays of length 3" +#: py/objgenerator.c +msgid "can't send non-None value to a just-started generator" msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "data must be iterable" +#: py/objgenerator.c py/runtime.c +msgid "generator raised StopIteration" msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "data must be of equal length" +#: py/objgenerator.c +msgid "generator ignored GeneratorExit" msgstr "" -#: ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c +#: py/objint.c py/runtime.c #, c-format -msgid "data pin #%d in use" -msgstr "" - -#: extmod/ulab/code/ndarray.c -msgid "data type not understood" +msgid "can't convert %s to int" msgstr "" -#: py/parsenum.c -msgid "decimal numbers not supported" +#: py/objint.c +msgid "float too big" msgstr "" -#: py/compile.c -msgid "default 'except' must be last" +#: py/objint.c shared-bindings/time/__init__.c +msgid "No long integer support" msgstr "" -#: shared-bindings/msgpack/__init__.c -msgid "default is not a function" +#: py/objint.c py/sequence.c +msgid "small int overflow" msgstr "" -#: shared-bindings/audiobusio/PDMIn.c -msgid "" -"destination buffer must be a bytearray or array of type 'B' for bit_depth = 8" -msgstr "" +#: py/objint.c shared-bindings/_bleio/Connection.c +#: shared-bindings/storage/__init__.c +msgid "%q=%q" +msgstr "%q=%q" -#: shared-bindings/audiobusio/PDMIn.c -msgid "destination buffer must be an array of type 'H' for bit_depth = 16" +#: py/objint_impl.h +#, c-format +msgid "value would overflow a %d byte buffer" msgstr "" -#: py/objdict.c -msgid "dict update sequence has wrong length" +#: py/objint_impl.h +msgid "can't convert negative int to unsigned" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "diff argument must be an ndarray" +#: py/objint_longlong.c py/parsenum.c +msgid "result overflows long long storage" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "differentiation order out of range" +#: py/objint_longlong.c py/objint_mpz.c py/runtime.c +msgid "negative shift count" msgstr "" -#: extmod/ulab/code/numpy/transform.c -msgid "dimensions do not match" +#: py/objint_longlong.c py/objint_mpz.c py/runtime.c +msgid "negative power with no float support" msgstr "" -#: py/emitnative.c -msgid "div/mod not implemented for uint" +#: py/objint_longlong.c py/objint_mpz.c +msgid "overflow converting long int to machine word" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "divide by zero" +#: py/objint_mpz.c +msgid "pow() with 3 arguments requires integers" msgstr "" -#: py/runtime.c -msgid "division by zero" +#: py/objint_mpz.c +msgid "pow() 3rd argument cannot be 0" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "dtype must be float, or complex" +#: py/objobject.c +msgid "__new__ arg must be a user-type" msgstr "" -#: extmod/ulab/code/ndarray_operators.c -msgid "dtype of int32 is not supported" +#: py/objobject.c +msgid "arg must be user-type" msgstr "" -#: py/objdeque.c -msgid "empty" +#: py/objrange.c py/objslice.c shared-bindings/random/__init__.c +msgid "%q step cannot be zero" +msgstr "%q sıfır olamaz" + +#: py/objslice.c +msgid "Cannot subclass slice" +msgstr "Alt sınıf kesilemez" + +#: py/objstr.c +msgid "unknown encoding: %q" msgstr "" -#: extmod/ulab/code/numpy/io/io.c -msgid "empty file" +#: py/objstr.c +msgid "bytes value out of range" msgstr "" -#: extmod/modasyncio.c extmod/modheapq.c -msgid "empty heap" +#: py/objstr.c +msgid "join expects a list of str/bytes objects consistent with self object" msgstr "" #: py/objstr.c msgid "empty separator" msgstr "" -#: shared-bindings/random/__init__.c -msgid "empty sequence" +#: py/objstr.c +msgid "rsplit(None,n)" +msgstr "rsplit(None,n)" + +#: py/objstr.c +msgid "bad format string" msgstr "" #: py/objstr.c -msgid "end of format while looking for conversion specifier" +#, c-format +msgid "unmatched '%c' in format" msgstr "" -#: shared-bindings/alarm/time/TimeAlarm.c -msgid "epoch_time not supported on this board" +#: py/objstr.c +msgid "bad conversion specifier" msgstr "" -#: ports/nordic/common-hal/busio/UART.c -#, c-format -msgid "error = 0x%08lX" +#: py/objstr.c +msgid "end of format while looking for conversion specifier" msgstr "" -#: py/runtime.c -msgid "exceptions must derive from BaseException" +#: py/objstr.c +#, c-format +msgid "unknown conversion specifier %c" msgstr "" #: py/objstr.c msgid "expected ':' after format specifier" msgstr "" -#: py/obj.c -msgid "expected tuple/list" +#: py/objstr.c +msgid "" +"can't switch from automatic field numbering to manual field specification" msgstr "" -#: py/modthread.c -msgid "expecting a dict for keyword args" -msgstr "" +#: py/objstr.c +msgid "%q index out of range" +msgstr "%q indeksi aralık dışında" -#: py/compile.c -msgid "expecting an assembler instruction" +#: py/objstr.c +msgid "attributes not supported" msgstr "" -#: py/compile.c -msgid "expecting just a value for set" +#: py/objstr.c +msgid "" +"can't switch from manual field specification to automatic field numbering" msgstr "" -#: py/compile.c -msgid "expecting key:value for dict" +#: py/objstr.c +msgid "invalid format specifier" msgstr "" -#: shared-bindings/msgpack/__init__.c -msgid "ext_hook is not a function" +#: py/objstr.c +msgid "sign not allowed in string format specifier" msgstr "" -#: py/argcheck.c -msgid "extra keyword arguments given" +#: py/objstr.c +msgid "sign not allowed with integer format specifier 'c'" msgstr "" -#: py/argcheck.c -msgid "extra positional arguments given" +#: py/objstr.c +msgid "unknown format code '%c' for object of type '%q'" msgstr "" -#: shared-bindings/audiocore/WaveFile.c shared-bindings/audiomp3/MP3Decoder.c -#: shared-bindings/displayio/OnDiskBitmap.c shared-bindings/gifio/OnDiskGif.c -#: shared-bindings/synthio/__init__.c shared-module/gifio/GifWriter.c -msgid "file must be a file opened in byte mode" -msgstr "" +#: py/objstr.c +msgid "'=' alignment not allowed in string format specifier" +msgstr "'=' hizalamasına string biçiminde izin verilmez" -#: shared-bindings/traceback/__init__.c -msgid "file write is not available" +#: py/objstr.c +msgid "format needs a dict" msgstr "" -#: shared-bindings/storage/__init__.c -msgid "filesystem must provide mount method" +#: py/objstr.c +msgid "incomplete format key" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "first argument must be a callable" +#: py/objstr.c +msgid "incomplete format" msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "first argument must be a function" +#: py/objstr.c +msgid "format string needs more arguments" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "first argument must be a tuple of ndarrays" +#: py/objstr.c +#, c-format +msgid "%%c needs int or char" +msgstr "%%c int ya da char gerektirir" + +#: py/objstr.c +#, c-format +msgid "unsupported format character '%c' (0x%x) at index %d" msgstr "" -#: extmod/ulab/code/numpy/transform.c extmod/ulab/code/numpy/vector.c -msgid "first argument must be an ndarray" +#: py/objstr.c +msgid "format string didn't convert all arguments" msgstr "" -#: py/objtype.c -msgid "first argument to super() must be type" +#: py/objstr.c +msgid "non-hex digit" msgstr "" -#: extmod/ulab/code/scipy/linalg/linalg.c -msgid "first two arguments must be ndarrays" +#: py/objstr.c +msgid "can't convert to str implicitly" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "flattening order must be either 'C', or 'F'" +#: py/objstr.c +msgid "can't convert '%q' object to %q implicitly" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "flip argument must be an ndarray" +#: py/objstrunicode.c +#, c-format +msgid "string indices must be integers, not %s" msgstr "" -#: py/objint.c -msgid "float too big" +#: py/objstrunicode.c +msgid "string index out of range" msgstr "" -#: py/nativeglue.c -msgid "float unsupported" +#: py/objtemplate.c +msgid "expected str or Interpolation" msgstr "" -#: shared-bindings/_stage/Text.c -msgid "font must be 2048 bytes long" +#: py/objtype.c +msgid "Call super().__init__() before accessing native object." +msgstr "Yerel nesneye erişmeden önce super().__init__() fonksiyonunu çağırın." + +#: py/objtype.c +msgid "__init__() should return None" msgstr "" -#: extmod/moddeflate.c -msgid "format" +#: py/objtype.c +#, c-format +msgid "__init__() should return None, not '%s'" msgstr "" -#: py/objstr.c -msgid "format requires a dict" +#: py/objtype.c py/runtime.c +msgid "unreadable attribute" msgstr "" -#: py/objdeque.c -msgid "full" +#: py/objtype.c py/runtime.c +msgid "object not callable" msgstr "" -#: py/argcheck.c -msgid "function doesn't take keyword arguments" +#: py/objtype.c py/runtime.c shared-module/atexit/__init__.c +msgid "'%q' object isn't callable" msgstr "" -#: py/argcheck.c -#, c-format -msgid "function expected at most %d arguments, got %d" +#: py/objtype.c +msgid "type takes 1 or 3 arguments" msgstr "" -#: py/bc.c py/objnamedtuple.c -msgid "function got multiple values for argument '%q'" +#: py/objtype.c +msgid "can't create instance" msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "function has the same sign at the ends of interval" +#: py/objtype.c +msgid "can't create '%q' instances" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "function is defined for ndarrays only" +#: py/objtype.c +msgid "can't add special method to already-subclassed class" msgstr "" -#: extmod/ulab/code/numpy/carray/carray.c -msgid "function is implemented for ndarrays only" +#: py/objtype.c +msgid "type isn't an acceptable base type" msgstr "" -#: py/argcheck.c -#, c-format -msgid "function missing %d required positional arguments" +#: py/objtype.c +msgid "type '%q' isn't an acceptable base type" msgstr "" -#: py/bc.c -msgid "function missing keyword-only argument" +#: py/objtype.c +msgid "multiple inheritance not supported" msgstr "" -#: py/bc.c -msgid "function missing required keyword argument '%q'" +#: py/objtype.c +msgid "multiple bases have instance lay-out conflict" msgstr "" -#: py/bc.c -#, c-format -msgid "function missing required positional argument #%d" +#: py/objtype.c +msgid "first argument to super() must be type" msgstr "" -#: py/argcheck.c py/bc.c py/objnamedtuple.c shared-bindings/_eve/__init__.c -#: shared-bindings/time/__init__.c -#, c-format -msgid "function takes %d positional arguments but %d were given" +#: py/objtype.c +msgid "issubclass() arg 2 must be a class or a tuple of classes" msgstr "" -#: py/objgenerator.c -msgid "generator already executing" +#: py/objtype.c +msgid "issubclass() arg 1 must be a class" msgstr "" -#: py/objgenerator.c -msgid "generator ignored GeneratorExit" +#: py/parse.c +msgid "not a constant" msgstr "" -#: py/objgenerator.c py/runtime.c -msgid "generator raised StopIteration" +#: py/parse.c +msgid "Unable to init parser" msgstr "" -#: shared-bindings/_stage/Layer.c -msgid "graphic must be 2048 bytes long" +#: py/parse.c +msgid "unexpected indent" msgstr "" -#: extmod/modhashlib.c -msgid "hash is final" +#: py/parse.c +msgid "unindent doesn't match any outer indent level" msgstr "" -#: extmod/modheapq.c -msgid "heap must be a list" +#: py/parse.c +msgid "malformed f-string" msgstr "" -#: py/compile.c -msgid "identifier redefined as global" +#: py/parsenum.c +msgid "invalid syntax for integer" msgstr "" -#: py/compile.c -msgid "identifier redefined as nonlocal" +#: py/parsenum.c +#, c-format +msgid "invalid syntax for integer with base %d" msgstr "" -#: py/compile.c -msgid "import * not at module level" +#: py/parsenum.c +msgid "invalid syntax for number" msgstr "" -#: py/persistentcode.c -msgid "incompatible .mpy arch" +#: py/parsenum.c +msgid "decimal numbers not supported" msgstr "" #: py/persistentcode.c msgid "incompatible .mpy file" msgstr "" -#: py/objstr.c -msgid "incomplete format" +#: py/persistentcode.c +msgid "MicroPython .mpy file; use CircuitPython mpy-cross" msgstr "" -#: py/objstr.c -msgid "incomplete format key" +#: py/persistentcode.c +msgid "native code in .mpy unsupported" msgstr "" -#: extmod/modbinascii.c -msgid "incorrect padding" +#: py/persistentcode.c +msgid "incompatible .mpy arch" msgstr "" -#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/transform.c -msgid "index is out of bounds" +#: py/persistentcode.c +msgid "function must be bytecode" msgstr "" -#: shared-bindings/_pixelmap/PixelMap.c -msgid "index must be tuple or int" -msgstr "" +#: py/proto.c shared-bindings/digitalio/DigitalInOutProtocol.c +msgid "'%q' object does not support '%q'" +msgstr "'%q' nesnesi '%q' öğesini desteklemiyor" -#: extmod/ulab/code/numpy/numerical.c extmod/ulab/code/ulab_tools.c -#: ports/espressif/common-hal/pulseio/PulseIn.c -#: shared-bindings/bitmaptools/__init__.c -msgid "index out of range" +#: py/qstr.c +msgid "name too long" msgstr "" -#: py/obj.c -msgid "indices must be integers" +#: py/runtime.c +msgid "name not defined" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "indices must be integers, slices, or Boolean lists" +#: py/runtime.c +msgid "name '%q' isn't defined" msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "initial values must be iterable" +#: py/runtime.c +msgid "unsupported type for operator" msgstr "" -#: shared-bindings/_bleio/Characteristic.c shared-bindings/_bleio/Descriptor.c -msgid "initial_value length is wrong" +#: py/runtime.c +msgid "unsupported type for %q: '%s'" msgstr "" -#: py/compile.c -msgid "inline assembler must be a function" +#: py/runtime.c +msgid "unsupported types for %q: '%q', '%q'" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "input and output dimensions differ" +#: py/runtime.c +msgid "wrong number of values to unpack" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "input and output shapes differ" +#: py/runtime.c +#, c-format +msgid "need more than %d values to unpack" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "input argument must be an integer, a tuple, or a list" +#: py/runtime.c +#, c-format +msgid "too many values to unpack (expected %d)" msgstr "" -#: extmod/ulab/code/numpy/fft/fft_tools.c -msgid "input array length must be power of 2" +#: py/runtime.c +msgid "type object '%q' has no attribute '%q'" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "input arrays are not compatible" +#: py/runtime.c +msgid "module '%q' has no attribute '%q'" msgstr "" -#: extmod/ulab/code/numpy/poly.c -msgid "input data must be an iterable" +#: py/runtime.c +msgid "'%s' object has no attribute '%q'" +msgstr "'%s' nesnesinin '%q' özelliği yok" + +#: py/runtime.c +msgid "can't set attribute '%q'" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "input dtype must be float or complex" +#: py/runtime.c +msgid "object not iterable" msgstr "" -#: extmod/ulab/code/numpy/poly.c -msgid "input is not iterable" +#: py/runtime.c +msgid "'%q' object isn't iterable" +msgstr "'%q' nesnesi iterable değildir" + +#: py/runtime.c +msgid "object not an iterator" msgstr "" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "input matrix is asymmetric" +#: py/runtime.c +msgid "'%q' object isn't an iterator" +msgstr "'%q' nesnesi bir iteratör değildir" + +#: py/runtime.c +msgid "exceptions must derive from BaseException" msgstr "" -#: extmod/ulab/code/numpy/linalg/linalg.c -#: extmod/ulab/code/scipy/linalg/linalg.c -msgid "input matrix is singular" +#: py/runtime.c +msgid "can't import name %q" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "input must be 1- or 2-d" +#: py/runtime.c +msgid "memory allocation failed, heap is locked" msgstr "" -#: extmod/ulab/code/numpy/carray/carray.c -msgid "input must be a 1D ndarray" +#: py/runtime.c +#, c-format +msgid "memory allocation failed, allocating %u bytes" msgstr "" -#: extmod/ulab/code/scipy/linalg/linalg.c extmod/ulab/code/user/user.c -msgid "input must be a dense ndarray" +#: py/runtime.c +msgid "can't convert to int" msgstr "" -#: extmod/ulab/code/user/user.c shared-bindings/_eve/__init__.c -msgid "input must be an ndarray" +#: py/runtime.c +msgid "division by zero" msgstr "" -#: extmod/ulab/code/numpy/carray/carray.c -msgid "input must be an ndarray, or a scalar" +#: py/runtime.c +msgid "maximum recursion depth exceeded" msgstr "" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "input must be one-dimensional" +#: py/sequence.c shared-bindings/displayio/Group.c +msgid "object not in sequence" msgstr "" -#: extmod/ulab/code/ulab_tools.c -msgid "input must be square matrix" +#: py/stream.c shared-bindings/getpass/__init__.c +msgid "stream operation not supported" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "input must be tuple, list, range, or ndarray" +#: py/vm.c +msgid "local variable referenced before assignment" msgstr "" -#: extmod/ulab/code/numpy/poly.c -msgid "input vectors must be of equal length" +#: py/vm.c +msgid "no active exception to reraise" msgstr "" -#: extmod/ulab/code/numpy/approx.c -msgid "interp is defined for 1D iterables of equal length" +#: py/vm.c +msgid "opcode" msgstr "" +#: shared-bindings/_bleio/Adapter.c +msgid "Cannot create a new Adapter; use _bleio.adapter;" +msgstr "yeni Adaptör oluşturulamadı; _bleio.adapter kullanın;" + +#: shared-bindings/_bleio/Adapter.c +msgid "Could not set address" +msgstr "Adres ayarlanamadı" + #: shared-bindings/_bleio/Adapter.c #, c-format msgid "interval must be in range %s-%s" msgstr "" -#: py/compile.c -msgid "invalid arch" -msgstr "" +#: shared-bindings/_bleio/Adapter.c +#, fuzzy +msgid "Cannot have scan responses for extended, connectable advertisements." +msgstr "Genişletilmiş, bağlanabilir reklamlar için tarama yanıtları yapılamaz." -#: shared-bindings/bitmaptools/__init__.c -#, c-format -msgid "invalid bits_per_pixel %d, must be, 1, 2, 4, 8, 16, 24, or 32" +#: shared-bindings/_bleio/Adapter.c +msgid "Only connectable advertisements can be directed" msgstr "" -#: shared-module/ssl/SSLSocket.c -msgid "invalid cert" +#: shared-bindings/_bleio/Adapter.c +msgid "non-zero timeout must be >= interval" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -#, c-format -msgid "invalid element size %d for bits_per_pixel %d\n" +#: shared-bindings/_bleio/Adapter.c +msgid "window must be <= interval" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -#, c-format -msgid "invalid element_size %d, must be, 1, 2, or 4" +#: shared-bindings/_bleio/Adapter.c +msgid "Prefix buffer must be on the heap" msgstr "" -#: shared-bindings/traceback/__init__.c -msgid "invalid exception" -msgstr "" +#: shared-bindings/_bleio/CharacteristicBuffer.c +msgid "CharacteristicBuffer writing not provided" +msgstr "CharacteristicBuffer yazılmı sağlanmadı" -#: py/objstr.c -msgid "invalid format specifier" -msgstr "" +#: shared-bindings/_bleio/Connection.c +msgid "" +"Connection has been disconnected and can no longer be used. Create a new " +"connection." +msgstr "Bağlantı koparıldı ve tekrar kullanılamaz. Yeni bir bağlantı kurun." -#: shared-bindings/wifi/Radio.c -msgid "invalid hostname" -msgstr "" +#: shared-bindings/_bleio/PacketBuffer.c +#, c-format +msgid "Buffer too short by %d bytes" +msgstr "Buffer bitten %d daha az" -#: shared-module/ssl/SSLSocket.c -msgid "invalid key" +#: shared-bindings/_bleio/PacketBuffer.c +msgid "No connection: length cannot be determined" msgstr "" -#: py/compile.c -msgid "invalid micropython decorator" +#: shared-bindings/_bleio/UUID.c +msgid "UUID string not 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'" msgstr "" -#: ports/espressif/common-hal/espcamera/Camera.c -msgid "invalid setting" +#: shared-bindings/_bleio/UUID.c +msgid "UUID value is not str, int or byte buffer" msgstr "" -#: shared-bindings/random/__init__.c -msgid "invalid step" +#: shared-bindings/_bleio/UUID.c +msgid "not a 128-bit UUID" msgstr "" -#: py/compile.c py/parse.c -msgid "invalid syntax" +#: shared-bindings/_bleio/__init__.c shared-bindings/emmcio/EMMC.c +#: shared-bindings/memorymonitor/AllocationSize.c +#: shared-bindings/pulseio/PulseIn.c shared-module/bitmaptools/__init__.c +#: shared-module/displayio/legacy/Bitmap.c +#: shared-module/displayio/legacy/Group.c shared-module/displayio/lvgl/Bitmap.c +#: shared-module/displayio/lvgl/Group.c +msgid "Read-only" msgstr "" -#: py/parsenum.c -msgid "invalid syntax for integer" -msgstr "" +#: shared-bindings/_pew/PewPew.c +msgid "Incorrect buffer size" +msgstr "Yanlış buffer size" -#: py/parsenum.c -#, c-format -msgid "invalid syntax for integer with base %d" +#: shared-bindings/_pixelmap/PixelMap.c +msgid "nested index must be int" msgstr "" -#: py/parsenum.c -msgid "invalid syntax for number" +#: shared-bindings/_pixelmap/PixelMap.c +msgid "index must be tuple or int" msgstr "" -#: py/objtype.c -msgid "issubclass() arg 1 must be a class" +#: shared-bindings/_stage/Layer.c +msgid "map buffer too small" msgstr "" -#: py/objtype.c -msgid "issubclass() arg 2 must be a class or a tuple of classes" +#: shared-bindings/_stage/Text.c +msgid "chars buffer too small" msgstr "" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "iterations did not converge" +#: shared-bindings/adafruit_bus_device/spi_device/SPIDevice.c +msgid "Pin is input only" msgstr "" -#: py/objstr.c -msgid "join expects a list of str/bytes objects consistent with self object" +#: shared-bindings/adafruit_pixelbuf/PixelBuf.c +#: shared-module/_pixelmap/PixelMap.c +#, c-format +msgid "Unmatched number of items on RHS (expected %d, got %d)." msgstr "" -#: py/argcheck.c -msgid "keyword argument(s) not implemented - use normal args instead" -msgstr "" +#: shared-bindings/aesio/aes.c +msgid "Key must be 16, 24, or 32 bytes long" +msgstr "Anahtar 16, 24 veya 32 bayt uzunluğunda olmalıdır" -#: py/emitinlinethumb.c py/emitinlinextensa.c -msgid "label '%q' not defined" +#: shared-bindings/aesio/aes.c +msgid "Requested AES mode is unsupported" msgstr "" -#: py/compile.c -msgid "label redefined" +#: shared-bindings/aesio/aes.c +msgid "Source and destination buffers must be the same length" msgstr "" -#: py/objarray.c -msgid "lhs and rhs should be compatible" -msgstr "" +#: shared-bindings/aesio/aes.c +msgid "ECB only operates on 16 bytes at a time" +msgstr "ECB aynı anda yalnızca 16 baytla çalışır" -#: py/emitnative.c -msgid "local '%q' has type '%q' but source is '%q'" +#: shared-bindings/aesio/aes.c +msgid "CBC blocks must be multiples of 16 bytes" +msgstr "CBC blokları 16 baytın katları şeklinde olmalı" + +#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c +#: shared-bindings/nvm/ByteArray.c +msgid "Slice and value different lengths." msgstr "" -#: py/emitnative.c -msgid "local '%q' used before type known" +#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c +#: shared-bindings/nvm/ByteArray.c +msgid "Array values should be single bytes." +msgstr "Dizi değerleri tekil bytelar olmalıdır." + +#: shared-bindings/alarm/SleepMemory.c +msgid "Unable to write to sleep_memory." msgstr "" -#: py/vm.c -msgid "local variable referenced before assignment" +#: shared-bindings/alarm/__init__.c +msgid "Expected a kind of %q" msgstr "" -#: ports/espressif/common-hal/canio/CAN.c -msgid "loopback + silent mode not supported by peripheral" +#: shared-bindings/alarm/time/TimeAlarm.c shared-bindings/time/__init__.c +msgid "RTC is not supported on this board" msgstr "" -#: ports/espressif/common-hal/mdns/Server.c -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "mDNS already initialized" +#: shared-bindings/alarm/time/TimeAlarm.c +msgid "Supply one of monotonic_time or epoch_time" msgstr "" -#: ports/espressif/common-hal/mdns/Server.c -#: ports/raspberrypi/common-hal/mdns/Server.c -msgid "mDNS only works with built-in WiFi" +#: shared-bindings/alarm/time/TimeAlarm.c +msgid "epoch_time not supported on this board" msgstr "" -#: py/parse.c -msgid "malformed f-string" +#: shared-bindings/alarm/time/TimeAlarm.c +msgid "Time is in the past." msgstr "" -#: shared-bindings/_stage/Layer.c -msgid "map buffer too small" -msgstr "" +#: shared-bindings/analogbufio/BufferedIn.c +msgid "%q must be a bytearray or array of type 'H' or 'B'" +msgstr "%q 'H' ya da 'B' tipi bir bytearray ya da array olmalıdır" -#: py/modmath.c shared-bindings/math/__init__.c -msgid "math domain error" -msgstr "" +#: shared-bindings/audiobusio/PDMIn.c +msgid "%q must be multiple of 8." +msgstr "%q 8'in katı olmalıdır." -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "matrix is not positive definite" -msgstr "" +#: shared-bindings/audiobusio/PDMIn.c shared-bindings/audioi2sin/I2SIn.c +#: shared-bindings/usb_host_audio/USBIn.c +msgid "Cannot record to a file" +msgstr "Dosyaya kayıt yapılamıyor" -#: ports/espressif/common-hal/_bleio/Descriptor.c -#: ports/nordic/common-hal/_bleio/Characteristic.c -#: ports/nordic/common-hal/_bleio/Descriptor.c -#, c-format -msgid "max_length must be 0-%d when fixed_length is %s" -msgstr "" +#: shared-bindings/audiobusio/PDMIn.c shared-bindings/audioi2sin/I2SIn.c +#: shared-bindings/usb_host_audio/USBIn.c +msgid "Destination capacity is smaller than destination_length." +msgstr "Hedef kapasitesi, hedef_uzunluğundan daha küçük." -#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/random/random.c -msgid "maximum number of dimensions is " +#: shared-bindings/audiobusio/PDMIn.c +msgid "destination buffer must be an array of type 'H' for bit_depth = 16" msgstr "" -#: py/runtime.c -msgid "maximum recursion depth exceeded" +#: shared-bindings/audiobusio/PDMIn.c +msgid "" +"destination buffer must be a bytearray or array of type 'B' for bit_depth = 8" msgstr "" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "maxiter must be > 0" -msgstr "" +#: shared-bindings/audiocore/RawSample.c +msgid "%q must be a bytearray or array of type 'h', 'H', 'b', or 'B'" +msgstr "%q 'h', 'H', 'b' ya da 'B' tipi bir bytearray ya da array olmalı" -#: extmod/ulab/code/scipy/optimize/optimize.c -msgid "maxiter should be > 0" +#: shared-bindings/audiocore/RawSample.c +msgid "Length of %q must be an even multiple of channel_count * type_size" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "median argument must be an ndarray" +#: shared-bindings/audiodelays/Chorus.c shared-bindings/audiodelays/Echo.c +#: shared-bindings/audiodelays/Flanger.c +#: shared-bindings/audiodelays/GranularPitchShift.c +#: shared-bindings/audiodelays/MultiTapDelay.c +#: shared-bindings/audiodelays/PitchShift.c +#: shared-bindings/audiofilters/Distortion.c +#: shared-bindings/audiofilters/Filter.c shared-bindings/audiofilters/Phaser.c +#: shared-bindings/audiomixer/Mixer.c shared-module/audiotap/Tap.c +msgid "bits_per_sample must be 8 or 16" msgstr "" -#: py/runtime.c -#, c-format -msgid "memory allocation failed, allocating %u bytes" +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "samples_signed must be true" msgstr "" -#: py/runtime.c -msgid "memory allocation failed, heap is locked" +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "bits_per_sample must be 16" msgstr "" -#: py/objarray.c -msgid "memoryview offset too large" +#: shared-bindings/audioi2sin/I2SIn.c shared-bindings/usb_host_audio/USBIn.c +#, c-format +msgid "invalid destination buffer, must be an array of type: %c" msgstr "" -#: py/objarray.c -msgid "memoryview: length is not a multiple of itemsize" -msgstr "" +#: shared-bindings/audioio/AudioOut.c shared-bindings/emmcio/EMMC.c +msgid "%q and %q must be different" +msgstr "%q ve %q farklı olmalılar" -#: extmod/modtime.c -msgid "mktime needs a tuple of length 8 or 9" +#: shared-bindings/audiomp3/MP3Decoder.c shared-bindings/gifio/OnDiskGif.c +#: shared-bindings/synthio/__init__.c shared-module/gifio/GifWriter.c +msgid "file must be a file opened in byte mode" msgstr "" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "mode must be complete, or reduced" +#: shared-bindings/bitmapfilter/__init__.c +msgid "" +"weights must be a sequence with an odd square number of elements (usually 9 " +"or 25)" msgstr "" -#: py/builtinimport.c -msgid "module not found" +#: shared-bindings/bitmapfilter/__init__.c +msgid "weights must be an object of type %q, %q, %q, or %q, not %q " msgstr "" -#: ports/espressif/common-hal/wifi/Monitor.c -msgid "monitor init failed" +#: shared-bindings/bitmaptools/__init__.c +msgid "clip point must be (x,y) tuple" msgstr "" -#: extmod/ulab/code/numpy/poly.c -msgid "more degrees of freedom than data points" +#: shared-bindings/bitmaptools/__init__.c +msgid "source palette too large" msgstr "" -#: py/compile.c -msgid "multiple *x in assignment" -msgstr "" +#: shared-bindings/bitmaptools/__init__.c +msgid "Bitmap size and bits per value must match" +msgstr "Bitmap boyutu ve bit başına değer uyuşmalı" -#: py/objtype.c -msgid "multiple bases have instance lay-out conflict" +#: shared-bindings/bitmaptools/__init__.c +msgid "For L8 colorspace, input bitmap must have 8 bits per pixel" msgstr "" +"L8 renk uzayı için, giriş bitmap'i piksel başına 8 bayta sahip olmalıdır" -#: py/objtype.c -msgid "multiple inheritance not supported" +#: shared-bindings/bitmaptools/__init__.c +msgid "For RGB colorspaces, input bitmap must have 16 bits per pixel" msgstr "" +"RGB renk uzayı için, giriş bitmap'i piksel başına 16 bayta sahip olmalıdır" -#: py/emitnative.c -msgid "must raise an object" +#: shared-bindings/bitmaptools/__init__.c +msgid "Unsupported colorspace" msgstr "" -#: py/modbuiltins.c -msgid "must use keyword argument for key function" +#: shared-bindings/bitmaptools/__init__.c +msgid "Mask bitmap size must match the other bitmaps" msgstr "" -#: py/runtime.c -msgid "name '%q' is not defined" +#: shared-bindings/bitmaptools/__init__.c +msgid "Mask bitmap must have 8 bits per pixel" msgstr "" -#: py/runtime.c -msgid "name not defined" +#: shared-bindings/bitmaptools/__init__.c +msgid "out of range of target" msgstr "" -#: py/qstr.c -msgid "name too long" +#: shared-bindings/bitmaptools/__init__.c +msgid "value out of range of target" msgstr "" -#: py/persistentcode.c -msgid "native code in .mpy unsupported" +#: shared-bindings/bitmaptools/__init__.c +msgid "background value out of range of target" msgstr "" -#: py/asmthumb.c -msgid "native method too big" -msgstr "" +#: shared-bindings/bitmaptools/__init__.c +msgid "Coordinate arrays types have different sizes" +msgstr "Kordinat dizilerinin türlerifarklı boyutlara sahip" -#: py/emitnative.c -msgid "native yield" -msgstr "" +#: shared-bindings/bitmaptools/__init__.c +msgid "Coordinate arrays have different lengths" +msgstr "Kordinat dizilerinin uzunlukları farklı" -#: extmod/ulab/code/ndarray.c -msgid "ndarray length overflows" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid element_size %d, must be, 1, 2, or 4" msgstr "" -#: py/runtime.c +#: shared-bindings/bitmaptools/__init__.c #, c-format -msgid "need more than %d values to unpack" +msgid "invalid element size %d for bits_per_pixel %d\n" msgstr "" -#: py/modmath.c -msgid "negative factorial" +#: shared-bindings/bitmaptools/__init__.c +#, c-format +msgid "invalid bits_per_pixel %d, must be, 1, 2, 4, 8, 16, 24, or 32" msgstr "" -#: py/objint_longlong.c py/objint_mpz.c py/runtime.c -msgid "negative power with no float support" +#: shared-bindings/bitmaptools/__init__.c +msgid "bitmap sizes must match" msgstr "" -#: py/objint_mpz.c py/runtime.c -msgid "negative shift count" +#: shared-bindings/bitmaptools/__init__.c +msgid "source_bitmap must have value_count of 2 or 65536" msgstr "" -#: shared-bindings/_pixelmap/PixelMap.c -msgid "nested index must be int" +#: shared-bindings/bitmaptools/__init__.c +msgid "source_bitmap must have value_count of 65536" msgstr "" -#: shared-module/sdcardio/SDCard.c -msgid "no SD card" +#: shared-bindings/bitmaptools/__init__.c +msgid "source_bitmap must have value_count of 8" msgstr "" -#: py/vm.c -msgid "no active exception to reraise" +#: shared-bindings/bitmaptools/__init__.c +msgid "unsupported colorspace for dither" msgstr "" -#: py/compile.c -msgid "no binding for nonlocal found" -msgstr "" +#: shared-bindings/bitops/__init__.c +#, c-format +msgid "Input buffer length (%d) must be a multiple of the strand count (%d)" +msgstr "Giriş buffer uzunluğu (%d) strand sayımının (%d) katı olmalıdır" -#: shared-module/msgpack/__init__.c -msgid "no default packer" +#: shared-bindings/board/__init__.c +msgid "No default %q bus" msgstr "" -#: extmod/modrandom.c extmod/ulab/code/numpy/random/random.c -msgid "no default seed" +#: shared-bindings/busdisplay/BusDisplay.c +msgid "%q must be 1 when %q is True" +msgstr "%q 1 olmalı, %q True olduğu zaman" + +#: shared-bindings/busdisplay/BusDisplay.c +#: shared-bindings/framebufferio/FramebufferDisplay.c +msgid "Display must have a 16 bit colorspace." +msgstr "Ekran 16 bitlik bir renk uzayına sahip olmalıdır." + +#: shared-bindings/busio/UART.c shared-bindings/canio/CAN.c +msgid "tx and rx cannot both be None" msgstr "" -#: py/builtinimport.c -msgid "no module named '%q'" +#: shared-bindings/busio/UART.c shared-bindings/displayio/Group.c +msgid "Must be a %q subclass." msgstr "" -#: shared-module/sdcardio/SDCard.c -msgid "no response from SD card" +#: shared-bindings/canio/RemoteTransmissionRequest.c +msgid "RemoteTransmissionRequests limited to 8 bytes" msgstr "" -#: ports/espressif/common-hal/espcamera/Camera.c py/objobject.c py/runtime.c -msgid "no such attribute" +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/ec/EllipticCurvePublicKey.c +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/padding/__init__.c +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "Only %q supported" msgstr "" -#: ports/espressif/common-hal/_bleio/Connection.c -#: ports/nordic/common-hal/_bleio/Connection.c -msgid "non-UUID found in service_uuids_whitelist" +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/padding/__init__.c +msgid "label is not supported" msgstr "" -#: py/compile.c -msgid "non-default argument follows default argument" +#: shared-bindings/cryptography/hazmat/primitives/asymmetric/rsa/__init__.c +#: shared-bindings/hmac/__init__.c +msgid "key does not have the expected %q purpose" msgstr "" -#: py/objstr.c -msgid "non-hex digit found" +#: shared-bindings/digitalio/DigitalInOut.c +#: shared-bindings/i2cioexpander/IOPin.c +msgid "Cannot set value when direction is input." +msgstr "Yön, giriş olduğunda değer ayarlanamıyor." + +#: shared-bindings/digitalio/DigitalInOut.c +#: shared-bindings/i2cioexpander/IOPin.c +msgid "Drive mode not used when direction is input." +msgstr "Yön, giriş olduğunda sürüş modu kullanılmaz." + +#: shared-bindings/digitalio/DigitalInOut.c +#: shared-bindings/i2cioexpander/IOPin.c +msgid "Pull not used when direction is output." msgstr "" -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "non-zero timeout must be > 0.01" +#: shared-bindings/digitalio/DigitalInOutProtocol.c +msgid "%q object missing '%q' method" +msgstr "%q nesnesinde '%q' metodu eksik" + +#: shared-bindings/digitalio/DigitalInOutProtocol.c +msgid "%q object missing '%q' attribute" +msgstr "%q nesnesinde '%q' niteliği eksik" + +#: shared-bindings/digitalio/DigitalInOutProtocol.c +msgid "object does not support DigitalInOut protocol" msgstr "" -#: shared-bindings/_bleio/Adapter.c -msgid "non-zero timeout must be >= interval" +#: shared-bindings/displayio/Bitmap.c +#: shared-bindings/memorymonitor/AllocationSize.c +#: shared-bindings/pulseio/PulseIn.c +msgid "Cannot delete values" +msgstr "Değerler silinemez" + +#: 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 +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +msgid "Slices not supported" msgstr "" -#: shared-bindings/_bleio/UUID.c -msgid "not a 128-bit UUID" +#: shared-bindings/displayio/Palette.c +msgid "color buffer must be a bytearray or array of type 'b' or 'B'" msgstr "" -#: py/parse.c -msgid "not a constant" +#: shared-bindings/displayio/Palette.c +msgid "color buffer must be 3 bytes (RGB) or 4 bytes (RGB + pad byte)" msgstr "" -#: py/objstr.c -msgid "not all arguments converted during string formatting" +#: shared-bindings/displayio/Palette.c +msgid "color must be between 0x000000 and 0xffffff" msgstr "" -#: py/objstr.c -msgid "not enough arguments for format string" +#: shared-bindings/displayio/Palette.c +msgid "color buffer must be a buffer, tuple, list, or int" msgstr "" -#: extmod/ulab/code/numpy/carray/carray_tools.c -msgid "not implemented for complex dtype" +#: shared-bindings/displayio/TileGrid.c +msgid "Tile width must exactly divide bitmap width" msgstr "" -#: extmod/ulab/code/numpy/bitwise.c -msgid "not supported for input types" +#: shared-bindings/displayio/TileGrid.c +msgid "Tile height must exactly divide bitmap height" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "number of points must be at least 2" +#: shared-bindings/displayio/TileGrid.c +msgid "New bitmap must be same size as old bitmap" msgstr "" -#: py/builtinhelp.c -msgid "object " +#: shared-bindings/displayio/TileGrid.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-module/displayio/legacy/TileGrid.c +#: shared-module/displayio/lvgl/TileGrid.c +msgid "Tile index out of bounds" msgstr "" -#: py/obj.c -#, c-format -msgid "object '%s' isn't a tuple or list" +#: shared-bindings/dualbank/__init__.c +msgid "offset must be >= 0" msgstr "" -#: py/obj.c -msgid "object doesn't support item assignment" +#: shared-bindings/emmcio/EMMC.c shared-bindings/i2cioexpander/IOExpander.c +msgid "address out of range" msgstr "" -#: py/obj.c -msgid "object doesn't support item deletion" +#: shared-bindings/epaperdisplay/EPaperDisplay.c +msgid "Refresh too soon" msgstr "" -#: py/obj.c -msgid "object has no len" -msgstr "" +#: shared-bindings/framebufferio/FramebufferDisplay.c +msgid "Buffer is not a bytearray." +msgstr "Buffer bir bytearray değil." -#: py/obj.c -msgid "object isn't subscriptable" +#: shared-bindings/gnss/GNSS.c +msgid "System entry must be gnss.SatelliteSystem" msgstr "" -#: py/runtime.c -msgid "object not an iterator" +#: shared-bindings/hashlib/__init__.c shared-bindings/hmac/__init__.c +msgid "Unsupported hash algorithm" msgstr "" -#: py/objtype.c py/runtime.c -msgid "object not callable" +#: shared-bindings/i2cioexpander/IOExpander.c +msgid "num_pins must be 8 or 16" msgstr "" -#: py/sequence.c shared-bindings/displayio/Group.c -msgid "object not in sequence" +#: shared-bindings/i2ctarget/I2CTarget.c +msgid "addresses is empty" msgstr "" -#: py/runtime.c -msgid "object not iterable" +#: shared-bindings/ipaddress/IPv4Address.c shared-bindings/ipaddress/__init__.c +msgid "Not a valid IP string" msgstr "" -#: py/obj.c +#: shared-bindings/ipaddress/IPv4Address.c #, c-format -msgid "object of type '%s' has no len()" -msgstr "" +msgid "Address must be %d bytes long" +msgstr "Adres %d byte uzunluğunda olmalıdır" -#: py/obj.c -msgid "object with buffer protocol required" +#: shared-bindings/ipaddress/__init__.c +msgid "Only int or string supported for ip" msgstr "" -#: py/objstr.c -msgid "odd-length string" +#: shared-bindings/is31fl3741/FrameBuffer.c +msgid "width must be greater than zero" msgstr "" -#: supervisor/shared/web_workflow/web_workflow.c -msgid "off" +#: shared-bindings/is31fl3741/FrameBuffer.c +msgid "Scale dimensions must divide by 3" msgstr "" -#: extmod/ulab/code/utils/utils.c -msgid "offset is too large" -msgstr "" +#: shared-bindings/is31fl3741/FrameBuffer.c +msgid "LED mappings must match display size" +msgstr "LED eşlemeleri ekran boyutuyla eşleşmelidir" -#: shared-bindings/dualbank/__init__.c -msgid "offset must be >= 0" -msgstr "" +#: shared-bindings/is31fl3741/IS31FL3741.c +msgid "Mapping must be a tuple" +msgstr "Map tuple olmalıdır" -#: extmod/ulab/code/numpy/create.c -msgid "offset must be non-negative and no greater than buffer length" -msgstr "" +#: shared-bindings/jpegio/JpegDecoder.c +msgid "%q must be of type %q, %q, or %q, not %q" +msgstr "%q; %q, %q veya %q tipi olmalıdır, %q değil" -#: ports/nordic/common-hal/audiobusio/PDMIn.c -#: ports/stm/common-hal/audiobusio/PDMIn.c -msgid "only bit_depth=16 is supported" +#: shared-bindings/mdns/Server.c +msgid "" +"Failed to add service TXT record; non-string or bytes found in txt_records" msgstr "" -#: ports/stm/common-hal/audiobusio/PDMIn.c -msgid "only mono is supported" +#: shared-bindings/memorymap/AddressRange.c +msgid "Address range wraps around" +msgstr "Adres aralığı başa döner" + +#: shared-bindings/microcontroller/Pin.c +msgid "%q contains duplicate pins" +msgstr "%q yinelenen pinler içeriyor" + +#: shared-bindings/microcontroller/Pin.c +msgid "%q and %q contain duplicate pins" +msgstr "%q ve %q yinelenen pinler içeriyor" + +#: shared-bindings/mii/Ethernet.c shared-bindings/wifi/Radio.c +msgid "invalid hostname" msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "only ndarrays can be concatenated" +#: shared-bindings/msgpack/ExtType.c +msgid "code outside range 0~127" msgstr "" -#: ports/stm/common-hal/audiobusio/PDMIn.c -msgid "only oversample=64 is supported" +#: shared-bindings/msgpack/__init__.c +msgid "default is not a function" msgstr "" -#: ports/nordic/common-hal/audiobusio/PDMIn.c -#: ports/stm/common-hal/audiobusio/PDMIn.c -msgid "only sample_rate=16000 is supported" +#: shared-bindings/msgpack/__init__.c +msgid "ext_hook is not a function" msgstr "" -#: py/objarray.c py/objstr.c py/objstrunicode.c py/objtuple.c -#: shared-bindings/alarm/SleepMemory.c shared-bindings/memorymap/AddressRange.c #: shared-bindings/nvm/ByteArray.c -msgid "only slices with step=1 (aka None) are supported" +msgid "Unable to write to nvm." msgstr "" -#: py/vm.c -msgid "opcode" +#: shared-bindings/os/__init__.c +msgid "No hardware random available" msgstr "" -#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/bitwise.c -#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/numpy/vector.c -msgid "operands could not be broadcast together" +#: shared-bindings/paralleldisplaybus/ParallelBus.c +msgid "Specify exactly one of data0 or data_pins" msgstr "" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "operation is defined for 2D arrays only" +#: shared-bindings/picogame/Bitmap.c shared-module/msgpack/__init__.c +#: supervisor/shared/settings.c +msgid "Invalid format" msgstr "" -#: extmod/ulab/code/numpy/linalg/linalg.c -msgid "operation is defined for ndarrays only" +#: shared-bindings/ps2io/Ps2.c +msgid "Failed sending command." +msgstr "Komut gönderilemedi." + +#: shared-bindings/pulseio/PulseOut.c +msgid "Array must contain halfwords (type 'H')" +msgstr "Dizi yarımsözcüklere sahip olmalıdır (tip 'H')" + +#: shared-bindings/pwmio/PWMOut.c +msgid "Conflicting settings for shared resource" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "operation is implemented for 1D Boolean arrays only" +#: shared-bindings/random/__init__.c +msgid "stop not reachable from start" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "operation is not implemented on ndarrays" +#: shared-bindings/random/__init__.c +msgid "invalid step" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "operation is not supported for given type" +#: shared-bindings/random/__init__.c +msgid "empty sequence" msgstr "" -#: extmod/ulab/code/ndarray_operators.c -msgid "operation not supported for the input types" +#: shared-bindings/rclcpy/Publisher.c +msgid "Publishers can only be created from a parent node" msgstr "" -#: py/modbuiltins.c -msgid "ord expects a character" +#: shared-bindings/rgbmatrix/RGBMatrix.c +#, c-format +msgid "Must use a multiple of 6 rgb pins, not %d" msgstr "" -#: py/modbuiltins.c +#: shared-bindings/rgbmatrix/RGBMatrix.c #, c-format -msgid "ord() expected a character, but string of length %d found" +msgid "" +"%d address pins, %d rgb pins and %d tiles indicate a height of %d, not %d" msgstr "" +"%d adres pinleri, %d RGB pinleri ve %d döşemeleri %d'nin yüksekliği " +"gösterir, %d'nin değil" -#: extmod/ulab/code/utils/utils.c -msgid "out array is too small" +#: shared-bindings/socketpool/Socket.c +msgid "port must be >= 0" msgstr "" -#: extmod/ulab/code/numpy/random/random.c -msgid "out has wrong type" +#: shared-bindings/socketpool/Socket.c shared-bindings/ssl/SSLSocket.c +msgid "buffer too small for requested bytes" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "out keyword is not supported for complex dtype" +#: shared-bindings/socketpool/SocketPool.c +msgid "Name or service not known" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "out keyword is not supported for function" +#: shared-bindings/spitarget/SPITarget.c +msgid "Packet buffers for an SPI transfer must have the same length." msgstr "" -#: extmod/ulab/code/utils/utils.c -msgid "out must be a float dense array" +#: shared-bindings/ssl/SSLContext.c +msgid "Server side context cannot have hostname" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "out must be an ndarray" +#: shared-bindings/storage/__init__.c shared-bindings/usb_audio/__init__.c +#: shared-bindings/usb_cdc/__init__.c shared-bindings/usb_hid/__init__.c +#: shared-bindings/usb_midi/__init__.c shared-bindings/usb_video/__init__.c +msgid "Cannot change USB devices now" +msgstr "USB aygıtları şu an değiştirilemez" + +#: shared-bindings/supervisor/__init__.c shared-module/lvfontio/OnDiskFont.c +msgid "File not found" msgstr "" -#: extmod/ulab/code/numpy/vector.c -msgid "out must be of float dtype" +#: shared-bindings/time/__init__.c +msgid "timestamp out of range for platform time_t" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "out of range of target" +#: shared-bindings/traceback/__init__.c +msgid "Supply both or neither of %q and %q" msgstr "" -#: extmod/ulab/code/numpy/random/random.c -msgid "output array has wrong type" +#: shared-bindings/traceback/__init__.c +msgid "file write is not available" msgstr "" -#: extmod/ulab/code/numpy/random/random.c -msgid "output array must be contiguous" +#: shared-bindings/traceback/__init__.c +msgid "invalid exception" msgstr "" -#: py/objint_mpz.c -msgid "overflow converting long int to machine word" +#: shared-bindings/usb_audio/USBSpeaker.c +msgid "destination must be an array of type 'h'" msgstr "" -#: py/modstruct.c -#, c-format -msgid "pack expected %d items for packing (got %d)" +#: shared-bindings/usb_audio/__init__.c +msgid "At least one of microphone and speaker must be enabled" +msgstr "Mikrofon veya hoparlörden en az biri etkinleştirilmiş olmalı" + +#: shared-bindings/usb_hid/Device.c +msgid "%q, %q, and %q must all be the same length" +msgstr "%q, %q ve %q aynı uzunlukta olmalıdır" + +#: shared-bindings/util.c +msgid "" +"Object has been deinitialized and can no longer be used. Create a new object." msgstr "" -#: shared-bindings/_stage/Layer.c shared-bindings/_stage/Text.c -msgid "palette must be 32 bytes long" +#: shared-bindings/warnings/__init__.c +msgid "%q must be a subclass of %q" +msgstr "%q, %q'nün alt türü olmalıdır" + +#: shared-bindings/wifi/Radio.c +msgid "Invalid hex password" msgstr "" -#: py/emitinlinextensa.c -msgid "parameters must be registers in sequence a2 to a5" +#: shared-bindings/wifi/Radio.c +msgid "Invalid MAC address" +msgstr "Geçersiz MAC adresi" + +#: shared-bindings/wifi/Radio.c +msgid "AuthMode.OPEN is not used with password" +msgstr "AuthMode.OPEN bir şifre ile kullanılmadı" + +#: shared-bindings/wifi/Radio.c +msgid "Supply either %q or %q, not both" +msgstr "" + +#: shared-bindings/wifi/Radio.c +msgid "Invalid BSSID" +msgstr "Geçersiz BSSID" + +#: shared-bindings/wifi/Radio.c supervisor/shared/web_workflow/web_workflow.c +msgid "Authentication failure" +msgstr "Kimlik doğrulama hatası" + +#: shared-bindings/wifi/Radio.c +msgid "No network with that ssid" msgstr "" -#: py/emitinlinethumb.c -msgid "parameters must be registers in sequence r0 to r3" +#: shared-bindings/wifi/Radio.c +#, c-format +msgid "Unknown failure %d" msgstr "" -#: extmod/vfs_posix_file.c -msgid "poll on file not available on win32" +#: shared-module/adafruit_bus_device/i2c_device/I2CDevice.c +#, c-format +msgid "No I2C device at address: 0x%x" msgstr "" -#: ports/espressif/common-hal/pulseio/PulseIn.c -msgid "pop from an empty PulseIn" -msgstr "" +#: shared-module/audiocore/WaveFile.c +msgid "Invalid format chunk size" +msgstr "Geçersiz biçim yığın boyutu" -#: ports/atmel-samd/common-hal/pulseio/PulseIn.c -#: ports/cxd56/common-hal/pulseio/PulseIn.c -#: ports/nordic/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" +#: shared-module/audiocore/__init__.c shared-module/usb_audio/USBMicrophone.c +msgid "The sample's %q does not match" msgstr "" -#: shared-bindings/socketpool/Socket.c -msgid "port must be >= 0" -msgstr "" +#: shared-module/audiodelays/MultiTapDelay.c +msgid "%q in %q must be of type %q or %q, not %q" +msgstr "%q'nün içindeki %q, %q veya %q tipi olmalıdır, %q değil" -#: py/compile.c -msgid "positional arg after **" +#: shared-module/audiofilewriter/AudioFileWriter.c +msgid "Only 8/16-bit mono/stereo is supported" msgstr "" -#: py/compile.c -msgid "positional arg after keyword arg" +#: shared-module/audiofilewriter/AudioFileWriter.c +msgid "buffer_size too small for source" msgstr "" -#: py/objint_mpz.c -msgid "pow() 3rd argument cannot be 0" -msgstr "" +#: shared-module/audiomp3/MP3Decoder.c +msgid "Couldn't allocate decoder" +msgstr "Deşifre edici tahsis edilemedi" -#: py/objint_mpz.c -msgid "pow() with 3 arguments requires integers" -msgstr "" +#: shared-module/audiomp3/MP3Decoder.c +msgid "Failed to parse MP3 file" +msgstr "MP3 dosyası ayrıştırılamadı" -#: ports/raspberrypi/common-hal/rp2pio/StateMachine.c -msgid "pull masks conflict with direction masks" -msgstr "" +#: shared-module/bitbangio/I2C.c shared-module/msgpack/__init__.c +msgid "%q too long" +msgstr "%q çok uzun" -#: py/parse.c -msgid "raw f-strings are not supported" +#: shared-module/bitmapfilter/__init__.c +msgid "bitmap size and depth must match" msgstr "" -#: extmod/ulab/code/numpy/fft/fft_tools.c -msgid "real and imaginary parts must be of equal length" +#: shared-module/bitmapfilter/__init__.c +msgid "unsupported bitmap depth" msgstr "" -#: py/builtinimport.c -msgid "relative import" +#: shared-module/busdisplay/lvgl/BusDisplay.c +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "LVGL display create failed" msgstr "" -#: py/obj.c -#, c-format -msgid "requested length %d but object has length %d" +#: shared-module/busdisplay/lvgl/BusDisplay.c +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "LVGL buffer alloc failed" msgstr "" -#: extmod/ulab/code/ndarray_operators.c -msgid "results cannot be cast to specified type" +#: shared-module/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c +msgid "OAEP requires this build to enable TLS 1.3 support" msgstr "" -#: py/compile.c -msgid "return annotation must be an identifier" +#: shared-module/displayio/bus_core.c +msgid "Unsupported display bus type" msgstr "" -#: py/emitnative.c -msgid "return expected '%q' but got '%q'" -msgstr "" +#: shared-module/displayio/legacy/Bitmap.c +#: shared-module/displayio/lvgl/Bitmap.c +#, fuzzy +msgid "Invalid bits per value" +msgstr "Geçersiz bit başına değer" -#: shared-bindings/rgbmatrix/RGBMatrix.c -#, c-format -msgid "rgb_pins[%d] duplicates another pin assignment" +#: shared-module/displayio/legacy/ColorConverter.c +#: shared-module/displayio/lvgl/ColorConverter.c +msgid "Only one color can be transparent at a time" msgstr "" -#: shared-bindings/rgbmatrix/RGBMatrix.c +#: shared-module/displayio/legacy/Group.c shared-module/displayio/lvgl/Group.c +msgid "Layer already in a group" +msgstr "Katman zaten bir grupta" + +#: shared-module/displayio/legacy/Group.c +msgid "Layer must be a Group or TileGrid subclass" +msgstr "Katman, bir Grup ya da TileGrid alt sınıfı olmalıdır" + +#: shared-module/displayio/legacy/OnDiskBitmap.c +#: shared-module/displayio/lvgl/OnDiskBitmap.c #, c-format -msgid "rgb_pins[%d] is not on the same port as clock" +msgid "" +"Only Windows format, uncompressed BMP supported: given header size is %d" msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "roll argument must be an ndarray" +#: shared-module/displayio/legacy/OnDiskBitmap.c +#: shared-module/displayio/lvgl/OnDiskBitmap.c +msgid "RLE-compressed BMP not supported" msgstr "" -#: py/objstr.c -msgid "rsplit(None,n)" +#: shared-module/displayio/legacy/OnDiskBitmap.c +#: shared-module/displayio/lvgl/OnDiskBitmap.c +msgid "Unable to read color palette data" msgstr "" -#: ports/atmel-samd/common-hal/audiobusio/PDMIn.c -#: ports/raspberrypi/common-hal/audiobusio/PDMIn.c -msgid "sampling rate out of range" +#: shared-module/displayio/legacy/__init__.c +msgid "Too many displays" msgstr "" -#: py/modmicropython.c -msgid "schedule queue full" +#: shared-module/displayio/legacy/__init__.c +msgid "Too many display buses; deinit() unused displays" msgstr "" -#: py/builtinimport.c -msgid "script compilation not supported" +#: shared-module/displayio/lvgl/Group.c +msgid "Layer does not support scaling" msgstr "" -#: py/nativeglue.c -msgid "set unsupported" +#: shared-module/displayio/lvgl/Group.c +msgid "Layer must be a Group, TileGrid, vector shape or VideoBuffer" msgstr "" -#: extmod/ulab/code/numpy/random/random.c -msgid "shape must be None, and integer or a tuple of integers" +#: shared-module/displayio/lvgl/TileGrid.c +msgid "LVGL displayio backend does not support flips/transpose yet" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "shape must be integer or tuple of integers" +#: shared-module/displayio/lvgl/TileGrid.c +msgid "OnDiskBitmap requires its own pixel_shader" msgstr "" -#: shared-module/msgpack/__init__.c -msgid "short read" +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +msgid "LVGL dirty row alloc failed" msgstr "" -#: py/objstr.c -msgid "sign not allowed in string format specifier" +#: shared-module/framebufferio/lvgl/FramebufferDisplay.c +#: shared-module/videocore/VideoBuffer.c +#: shared-module/videocore/legacy/VideoBuffer.c +#: shared-module/videocore/lvgl/VideoBuffer.c +msgid "VideoBuffer can't stream into a rotated display" msgstr "" -#: py/objstr.c -msgid "sign not allowed with integer format specifier 'c'" +#: shared-module/gifio/GifWriter.c +msgid "unsupported colorspace for GifWriter" msgstr "" -#: extmod/ulab/code/ulab_tools.c -msgid "size is defined for ndarrays only" +#: shared-module/hmac/HMAC.c +msgid "key does not support this digest" msgstr "" -#: extmod/ulab/code/numpy/random/random.c -msgid "size must match out.shape when used together" +#: shared-module/hmac/HMAC.c +msgid "HMAC of an empty message is not supported with a hardware key" msgstr "" -#: py/nativeglue.c -msgid "slice unsupported" +#: shared-module/i2cdisplaybus/I2CDisplayBus.c +#: shared-module/is31fl3741/IS31FL3741.c +#, c-format +msgid "Unable to find I2C Display at %x" msgstr "" -#: py/objint.c py/sequence.c -msgid "small int overflow" -msgstr "" +#: shared-module/i2cioexpander/IOExpander.c +msgid "Cannot deinitialize board IOExpander" +msgstr "Kart IOExpander'ı devreden çıkarılamıyor" -#: main.c -msgid "soft reboot\n" +#: shared-module/imagecapture/ParallelImageCapture.c +msgid "This microcontroller does not support continuous capture." msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "sort argument must be an ndarray" +#: shared-module/jpegio/JpegDecoder.c +msgid "Interrupted by output function" msgstr "" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "sos array must be of shape (n_section, 6)" +#: shared-module/jpegio/JpegDecoder.c +msgid "Device error or wrong termination of input stream" msgstr "" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "sos[:, 3] should be all ones" +#: shared-module/jpegio/JpegDecoder.c +msgid "Insufficient memory pool for the image" msgstr "" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "sosfilt requires iterable arguments" +#: shared-module/jpegio/JpegDecoder.c +msgid "Insufficient stream input buffer" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "source palette too large" +#: shared-module/jpegio/JpegDecoder.c +msgid "Parameter error" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "source_bitmap must have value_count of 2 or 65536" -msgstr "" +#: shared-module/jpegio/JpegDecoder.c +msgid "Data format error (may be broken data)" +msgstr "Veri formatı hatası (bozuk veri olabilir)" -#: shared-bindings/bitmaptools/__init__.c -msgid "source_bitmap must have value_count of 65536" +#: shared-module/jpegio/JpegDecoder.c +msgid "Right format but not supported" msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "source_bitmap must have value_count of 8" +#: shared-module/jpegio/JpegDecoder.c +msgid "Unsupported JPEG (may be progressive)" msgstr "" -#: extmod/modre.c -msgid "splitting with sub-captures" +#: shared-module/jpegio/JpegDecoder.c +msgid "%q() without %q()" msgstr "" -#: py/objstr.c -msgid "start/end indices" -msgstr "" +#: shared-module/memorymonitor/AllocationAlarm.c +#, c-format +msgid "Attempt to allocate %d blocks" +msgstr "%d bloğun ayrılması girişimi" -#: shared-bindings/random/__init__.c -msgid "stop not reachable from start" +#: shared-module/msgpack/__init__.c +msgid "short read" msgstr "" -#: py/stream.c shared-bindings/getpass/__init__.c -msgid "stream operation not supported" +#: shared-module/msgpack/__init__.c +msgid "no default packer" msgstr "" -#: py/objarray.c py/objstr.c -msgid "string argument without an encoding" +#: shared-module/paralleldisplaybus/ParallelBus.c +msgid "" +"This microcontroller only supports data0=, not data_pins=, because it " +"requires contiguous pins." msgstr "" -#: py/objstrunicode.c -msgid "string index out of range" +#: shared-module/rgbmatrix/RGBMatrix.c +msgid "The length of rgb_pins must be 6, 12, 18, 24, or 30" msgstr "" -#: py/objstrunicode.c +#: shared-module/rgbmatrix/RGBMatrix.c #, c-format -msgid "string indices must be integers, not %s" -msgstr "" - -#: py/objarray.c py/objstr.c -msgid "substring not found" +msgid "rgb_pins[%d] is not on the same port as clock" msgstr "" -#: py/compile.c -msgid "super() can't find self" +#: shared-module/rgbmatrix/RGBMatrix.c +#, c-format +msgid "rgb_pins[%d] duplicates another pin assignment" msgstr "" -#: extmod/modjson.c -msgid "syntax error in JSON" +#: shared-module/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 "" -#: extmod/modtime.c -msgid "ticks interval overflow" +#: shared-module/rgbmatrix/RGBMatrix.c +msgid "No timer available" msgstr "" -#: ports/nordic/common-hal/watchdog/WatchDogTimer.c -msgid "timeout duration exceeded the maximum supported value" -msgstr "" +#: shared-module/rgbmatrix/RGBMatrix.c +#, c-format +msgid "Internal error #%d" +msgstr "Dahili hata #%d" -#: ports/nordic/common-hal/_bleio/Adapter.c -msgid "timeout must be < 655.35 secs" +#: shared-module/sdcardio/SDCard.c +msgid "timeout waiting for v1 card" msgstr "" -#: ports/raspberrypi/common-hal/floppyio/__init__.c -msgid "timeout waiting for flux" +#: shared-module/sdcardio/SDCard.c +msgid "timeout waiting for v2 card" msgstr "" -#: ports/raspberrypi/common-hal/floppyio/__init__.c -#: shared-module/floppyio/__init__.c -msgid "timeout waiting for index pulse" +#: shared-module/sdcardio/SDCard.c +msgid "no SD card" msgstr "" #: shared-module/sdcardio/SDCard.c -msgid "timeout waiting for v1 card" +msgid "couldn't determine SD card version" msgstr "" #: shared-module/sdcardio/SDCard.c -msgid "timeout waiting for v2 card" +msgid "no response from SD card" msgstr "" -#: ports/stm/common-hal/pwmio/PWMOut.c -msgid "timer re-init" +#: shared-module/sdcardio/SDCard.c +msgid "SD card CSD format not supported" msgstr "" -#: shared-bindings/time/__init__.c -msgid "timestamp out of range for platform time_t" +#: shared-module/sdcardio/SDCard.c +msgid "can't set 512 block size" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "tobytes can be invoked for dense arrays only" -msgstr "" +#: shared-module/ssl/SSLSocket.c +msgid "Invalid socket for TLS" +msgstr "TLS için geçersiz soket" -#: py/compile.c -msgid "too many args" +#: shared-module/ssl/SSLSocket.c +msgid "invalid cert" msgstr "" -#: extmod/ulab/code/ndarray.c extmod/ulab/code/numpy/create.c -msgid "too many dimensions" +#: shared-module/storage/__init__.c +msgid "File write in progress" msgstr "" -#: extmod/ulab/code/ndarray.c -msgid "too many indices" +#: shared-module/storage/__init__.c +msgid "Mount point directory missing" msgstr "" -#: py/asmthumb.c -msgid "too many locals for native method" -msgstr "" +#: shared-module/storage/__init__.c +msgid "Cannot remount path when visible via USB." +msgstr "USB üzerinden görünür durumdayken yol yeniden bağlanamaz." -#: py/runtime.c -#, c-format -msgid "too many values to unpack (expected %d)" -msgstr "" +#: shared-module/struct/__init__.c +msgid "'S' and 'O' are not supported format types" +msgstr "'S' ve 'O' desteklenen biçim türlerinden değildir" -#: extmod/ulab/code/numpy/approx.c -msgid "trapz is defined for 1D arrays of equal length" +#: shared-module/struct/__init__.c +msgid "buffer size must match format" msgstr "" -#: extmod/ulab/code/numpy/approx.c -msgid "trapz is defined for 1D iterables" -msgstr "" +#: shared-module/synthio/__init__.c +msgid "%q must be array of type 'h'" +msgstr "%q, 'h' dizisi türünde olmalıdır" -#: py/obj.c -msgid "tuple/list has wrong length" +#: shared-module/tilepalettemapper/TilePaletteMapper.c +msgid "TilePaletteMapper may only be bound to a TileGrid once" msgstr "" -#: ports/espressif/common-hal/canio/CAN.c -#, c-format -msgid "twai_driver_install returned esp-idf error #%d" +#: shared-module/touchio/TouchIn.c +msgid "No pullup on pin; 1Mohm recommended" msgstr "" -#: ports/espressif/common-hal/canio/CAN.c -#, c-format -msgid "twai_start returned esp-idf error #%d" +#: shared-module/touchio/TouchIn.c +msgid "No pulldown on pin; 1Mohm recommended" msgstr "" -#: shared-bindings/busio/UART.c shared-bindings/canio/CAN.c -msgid "tx and rx cannot both be None" +#: shared-module/usb/core/Device.c +msgid "No usb host port initialized" msgstr "" -#: py/objtype.c -msgid "type '%q' is not an acceptable base type" +#: shared-module/usb/core/Device.c +msgid "Pipe error" msgstr "" -#: py/objtype.c -msgid "type is not an acceptable base type" +#: shared-module/usb/core/Device.c +msgid "No configuration set" msgstr "" -#: py/runtime.c -msgid "type object '%q' has no attribute '%q'" +#: shared-module/usb_hid/Device.c +msgid "USB busy" msgstr "" -#: py/objtype.c -msgid "type takes 1 or 3 arguments" +#: shared-module/vectorio/Circle.c shared-module/vectorio/Polygon.c +#: shared-module/vectorio/Rectangle.c +msgid "can only have one parent" msgstr "" -#: py/objint_longlong.c -msgid "ulonglong too large" +#: shared-module/vectorio/Polygon.c +msgid "Polygon needs at least 3 points" msgstr "" -#: py/parse.c -msgid "unexpected indent" +#: shared-module/videocore/VideoBuffer.c +msgid "framebuffer went away" msgstr "" -#: py/bc.c -msgid "unexpected keyword argument" +#: shared-module/videocore/VideoBuffer.c +msgid "video doesn't fit in framebuffer" msgstr "" -#: py/argcheck.c py/bc.c py/objnamedtuple.c -#: shared-bindings/traceback/__init__.c -msgid "unexpected keyword argument '%q'" +#: shared-module/videocore/VideoBuffer.c +msgid "framebuffer missing required functions" msgstr "" -#: py/lexer.c -msgid "unicode name escapes" +#: shared-module/videocore/VideoBuffer.c +msgid "video format must be byte aligned" msgstr "" -#: py/parse.c -msgid "unindent doesn't match any outer indent level" +#: shared-module/videocore/VideoBuffer.c +msgid "video format doesn't match framebuffer" msgstr "" -#: py/objstr.c -#, c-format -msgid "unknown conversion specifier %c" +#: shared-module/videocore/VideoBuffer.c +msgid "video source rejected the destination" msgstr "" -#: py/objstr.c -msgid "unknown format code '%c' for object of type '%q'" +#: shared-module/videocore/VideoBuffer.c +msgid "video in a framebuffer must be at x == 0" msgstr "" -#: py/compile.c -msgid "unknown type" +#: shared-module/videocore/VideoBuffer.c +msgid "video size changed since play; stop and play again" msgstr "" -#: py/compile.c -msgid "unknown type '%q'" +#: shared-module/videocore/VideoBuffer.c +msgid "VideoBuffer is playing into a different framebuffer" msgstr "" -#: py/objstr.c -#, c-format -msgid "unmatched '%c' in format" +#: shared-module/videocore/legacy/VideoBuffer.c +msgid "VideoBuffer does not support transforms" msgstr "" -#: py/objtype.c py/runtime.c -msgid "unreadable attribute" +#: shared-module/videocore/lvgl/VideoBuffer.c +msgid "video format must be 16, 24 or 32 bits per pixel" msgstr "" -#: shared-bindings/displayio/TileGrid.c shared-bindings/vectorio/VectorShape.c -msgid "unsupported %q type" +#: supervisor/shared/bluetooth/bluetooth.c +msgid "Reconnecting" msgstr "" -#: py/emitinlinethumb.c -#, c-format -msgid "unsupported Thumb instruction '%s' with %d arguments" +#: supervisor/shared/bluetooth/bluetooth.c +msgid "Ok" msgstr "" -#: py/emitinlinextensa.c -#, c-format -msgid "unsupported Xtensa instruction '%s' with %d arguments" +#: supervisor/shared/bluetooth/bluetooth.c +msgid "Off" msgstr "" -#: shared-module/bitmapfilter/__init__.c -msgid "unsupported bitmap depth" +#: supervisor/shared/micropython.c +msgid "[truncated due to length]" msgstr "" -#: shared-module/gifio/GifWriter.c -msgid "unsupported colorspace for GifWriter" +#: supervisor/shared/safe_mode.c +msgid "" +"\n" +"You are in safe mode because:\n" msgstr "" +"\n" +"Güvenli moddasın çünkü:\n" -#: shared-bindings/bitmaptools/__init__.c -msgid "unsupported colorspace for dither" +#: supervisor/shared/safe_mode.c +msgid "Power dipped. Make sure you are providing enough power." msgstr "" -#: py/objstr.c -#, c-format -msgid "unsupported format character '%c' (0x%x) at index %d" +#: supervisor/shared/safe_mode.c +msgid "You pressed the BOOT button at start up" msgstr "" -#: py/runtime.c -msgid "unsupported type for %q: '%s'" +#: supervisor/shared/safe_mode.c +msgid "You pressed the reset button during boot." msgstr "" -#: py/runtime.c -msgid "unsupported type for operator" -msgstr "" +#: supervisor/shared/safe_mode.c +msgid "CIRCUITPY drive could not be found or created." +msgstr "CIRCUITPY sürücüsü bulunamadı veya oluşturulamadı." -#: py/runtime.c -msgid "unsupported types for %q: '%q', '%q'" +#: supervisor/shared/safe_mode.c +msgid "The `microcontroller` module was used to boot into safe mode." msgstr "" -#: extmod/ulab/code/numpy/io/io.c -msgid "usecols is too high" +#: supervisor/shared/safe_mode.c +msgid "Error in safemode.py." msgstr "" -#: extmod/ulab/code/numpy/io/io.c -msgid "usecols keyword must be specified" +#: supervisor/shared/safe_mode.c +msgid "Stack overflow. Increase stack size." msgstr "" -#: py/objint.c -#, c-format -msgid "value must fit in %d byte(s)" +#: supervisor/shared/safe_mode.c +msgid "USB devices need more endpoints than are available." msgstr "" -#: shared-bindings/bitmaptools/__init__.c -msgid "value out of range of target" +#: supervisor/shared/safe_mode.c +msgid "USB devices specify too many interface names." msgstr "" -#: extmod/moddeflate.c -msgid "wbits" -msgstr "" +#: supervisor/shared/safe_mode.c +msgid "Boot device must be first (interface #0)." +msgstr "Önyükleme cihazı birinci olmalı (arayüz #0)." -#: shared-bindings/bitmapfilter/__init__.c -msgid "" -"weights must be a sequence with an odd square number of elements (usually 9 " -"or 25)" -msgstr "" +#: supervisor/shared/safe_mode.c +msgid "Internal watchdog timer expired." +msgstr "Dahili bekçi zamanlayıcısının süresi doldu." -#: shared-bindings/bitmapfilter/__init__.c -msgid "weights must be an object of type %q, %q, %q, or %q, not %q " -msgstr "" +#: supervisor/shared/safe_mode.c +msgid "CircuitPython core code crashed hard. Whoops!\n" +msgstr "CircuitPython kor kodu patladı. Haydaaa!\n" -#: shared-bindings/is31fl3741/FrameBuffer.c -msgid "width must be greater than zero" +#: supervisor/shared/safe_mode.c +msgid "Heap allocation when VM not running." msgstr "" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/raspberrypi/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "wifi is not enabled" -msgstr "" +#: supervisor/shared/safe_mode.c +msgid "Failed to write internal flash." +msgstr "Dahili flaş yazılamadı." -#: ports/raspberrypi/common-hal/wifi/Monitor.c -msgid "wifi.Monitor not available" +#: supervisor/shared/safe_mode.c +msgid "Hard fault: memory access or instruction error." msgstr "" -#: shared-bindings/_bleio/Adapter.c -msgid "window must be <= interval" +#: supervisor/shared/safe_mode.c +msgid "Interrupt error." msgstr "" -#: extmod/ulab/code/numpy/numerical.c -msgid "wrong axis index" +#: supervisor/shared/safe_mode.c +msgid "LVGL ran out of memory." msgstr "" -#: extmod/ulab/code/numpy/create.c -msgid "wrong axis specified" +#: supervisor/shared/safe_mode.c +msgid "NLR jump failed. Likely memory corruption." msgstr "" -#: extmod/ulab/code/numpy/io/io.c -msgid "wrong dtype" +#: supervisor/shared/safe_mode.c +msgid "Unable to allocate to the heap." msgstr "" -#: extmod/ulab/code/numpy/transform.c -msgid "wrong index type" +#: supervisor/shared/safe_mode.c +msgid "Third-party firmware fatal error." msgstr "" -#: extmod/ulab/code/numpy/compare.c extmod/ulab/code/numpy/create.c -#: extmod/ulab/code/numpy/io/io.c extmod/ulab/code/numpy/transform.c -#: extmod/ulab/code/numpy/vector.c -msgid "wrong input type" +#: supervisor/shared/safe_mode.c +msgid "" +"\n" +"Please file an issue with your program at github.com/adafruit/circuitpython/" +"issues." msgstr "" +"\n" +"Lütfen programınızla ilgili bir sorunu github.com/adafruit/circuitpython/" +"issues adresinden bildirin." -#: extmod/ulab/code/numpy/transform.c -msgid "wrong length of condition array" +#: supervisor/shared/safe_mode.c +msgid "" +"\n" +"Press reset to exit safe mode.\n" msgstr "" +"\n" +"Güvenli moddan çıkmak için reset'e basın\n" -#: extmod/ulab/code/numpy/transform.c -msgid "wrong length of index array" -msgstr "" +#: supervisor/shared/settings.c +#, c-format +msgid "An error occurred while retrieving '%s':\n" +msgstr "'%s' alınırken hata yaşandı:\n" -#: extmod/ulab/code/numpy/create.c py/objarray.c py/objstr.c -msgid "wrong number of arguments" +#: supervisor/shared/settings.c +msgid "Invalid unicode escape" msgstr "" -#: py/runtime.c -msgid "wrong number of values to unpack" -msgstr "" +#: supervisor/shared/web_workflow/web_workflow.c +msgid "Wi-Fi: " +msgstr "Wi-Fi: " -#: extmod/ulab/code/numpy/vector.c -msgid "wrong output type" +#: supervisor/shared/web_workflow/web_workflow.c +msgid "off" msgstr "" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "zi must be an ndarray" -msgstr "" +#: supervisor/shared/web_workflow/web_workflow.c +msgid "No IP" +msgstr "IP yok" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "zi must be of float type" -msgstr "" +#~ msgid "%q out of bounds" +#~ msgstr "%q sınırların dışında" -#: extmod/ulab/code/scipy/signal/signal.c -msgid "zi must be of shape (n_section, 2)" -msgstr "" +#, c-format +#~ msgid "Buffer + offset too small %d %d %d" +#~ msgstr "Buffer + offset çok küçük %d %d %d" + +#~ msgid "Byte buffer must be 16 bytes." +#~ msgstr "Bit buffer'ı 16bit olmalı." + +#, c-format +#~ msgid "%%c requires int or char" +#~ msgstr "%%c int veya char tipine ihtiyaç duyar" + +#~ msgid "'%q' object is not callable" +#~ msgstr "'%q' nesnesi çağrılabilir değil" + +#~ msgid "Cannot remount '/' when visible via USB." +#~ msgstr "'/' USB ile görünür olduğunda, yeniden bağlanamaz." #~ msgid "Data chunk must follow fmt chunk" #~ msgstr "Veri öbeği, fmt yığınını takip etmelidir" @@ -4578,7 +5257,7 @@ msgstr "" #~ msgid "'continue' outside loop" #~ msgstr "döngü dışında 'continue'" -#~ msgid "'coroutine' object is not an iterator" +#~ msgid "'coroutine' object isn't an iterator" #~ msgstr "'coroutine' nesnesi bir iteratör değildir" #~ msgid "(x,y) integers required" @@ -4676,8 +5355,8 @@ msgstr "" #~ msgstr "IV %d bayt uzunluğunda olmalı" #~ msgid "" -#~ "Incompatible .mpy file. Please update all .mpy files. See http://adafru." -#~ "it/mpy-update for more info." +#~ "Incompatible .mpy file. Please update all .mpy files. See http://" +#~ "adafru.it/mpy-update for more info." #~ msgstr "" #~ "Uyumsuz .mpy dosyası. Lütfen tüm .mpy dosyalarını güncelleyin. Daha fazla " #~ "bilgi için http://adafru.it/mpy-update ." diff --git a/locale/zh_Latn_pinyin.po b/locale/zh_Latn_pinyin.po index be8705c3aa9..f3f9483cc4c 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: 2025-02-24 05:02+0000\n" +"PO-Revision-Date: 2025-07-15 00:01+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 5.10.1-dev\n" +"X-Generator: Weblate 5.13-dev\n" #: main.c msgid "" @@ -96,7 +96,7 @@ msgstr "" msgid "%q and %q contain duplicate pins" msgstr "%q hé %q bāo hán chóng fù yǐn jiǎo" -#: ports/atmel-samd/common-hal/audioio/AudioOut.c +#: shared-bindings/audioio/AudioOut.c msgid "%q and %q must be different" msgstr "%q hé %q bìxū bùtóng" @@ -116,6 +116,10 @@ msgstr "%q bāo hán chóng fù de yǐn jiǎo" msgid "%q failure: %d" msgstr "%q Shībài: %d" +#: shared-module/audiodelays/MultiTapDelay.c +msgid "%q in %q must be of type %q or %q, not %q" +msgstr "%q zhōngde %q bìxū shì %q huò %q lèixíng, érbùshì %q" + #: py/argcheck.c shared-module/audiofilters/Filter.c msgid "%q in %q must be of type %q, not %q" msgstr "%q zhōng de %q bì xū shì %q lèi xíng, ér bù shì %q" @@ -168,7 +172,7 @@ msgstr "%q chángdù bìxū <= %d" msgid "%q length must be >= %d" msgstr "%q chángdù bìxū >= %d" -#: py/modsys.c py/objmodule.c py/runtime.c +#: py/modsys.c py/runtime.c msgid "%q moved from %q to %q" msgstr "%q cóng %q yídòngdào %q" @@ -230,7 +234,7 @@ msgstr "%q bìxū shì 8 debèishù." #: shared-bindings/bitmapfilter/__init__.c shared-bindings/canio/CAN.c #: shared-bindings/digitalio/Pull.c shared-bindings/supervisor/__init__.c #: shared-module/audiofilters/Filter.c shared-module/displayio/__init__.c -#: shared-module/synthio/Biquad.c shared-module/synthio/Synthesizer.c +#: shared-module/synthio/Synthesizer.c msgid "%q must be of type %q or %q, not %q" msgstr "%q de lèi xíng bì xū shì %q huò %q, ér bù shì %q" @@ -239,6 +243,7 @@ msgid "%q must be of type %q, %q, or %q, not %q" msgstr "%q bìxūshì %q, %q huò %q lèixíng, érbùshì %q" #: py/argcheck.c py/runtime.c shared-bindings/bitmapfilter/__init__.c +#: shared-module/audiodelays/MultiTapDelay.c shared-module/synthio/Note.c #: shared-module/synthio/__init__.c msgid "%q must be of type %q, not %q" msgstr "%q de lèi xíng bì xū shì %q, ér bù shì %q" @@ -319,7 +324,7 @@ msgid "'%q' object does not support '%q'" msgstr "'%q' duì xiàng bù zhī chí '%q'" #: py/runtime.c -msgid "'%q' object is not an iterator" +msgid "'%q' object isn't an iterator" msgstr "%q' duìxiàng bùshì yígè diédàiqì" #: py/objtype.c py/runtime.c shared-module/atexit/__init__.c @@ -327,7 +332,7 @@ msgid "'%q' object is not callable" msgstr "%q' duìxiàng bù kě bèi diàoyòng" #: py/runtime.c -msgid "'%q' object is not iterable" +msgid "'%q' object isn't iterable" msgstr "%q' duìxiàng bù kě yòngyú diédài" #: py/emitinlinethumb.c py/emitinlinextensa.c @@ -809,8 +814,8 @@ msgid "Cannot record to a file" msgstr "Wúfǎ jìlù dào wénjiàn" #: shared-module/storage/__init__.c -msgid "Cannot remount '/' when visible via USB." -msgstr "tōngguò USB kějiàn shí wúfǎ chóngxīn ānzhuāng '/'." +msgid "Cannot remount path when visible via USB." +msgstr "tōngguò USB kějiàn shí wúfǎ chóngxīn guàzǎi lùjìng." #: shared-bindings/digitalio/DigitalInOut.c msgid "Cannot set value when direction is input." @@ -863,6 +868,10 @@ msgstr "zuòbiāo shùzǔ jùyǒu bùtóng de chángdù" msgid "Coordinate arrays types have different sizes" msgstr "zuòbiāo shùzǔ lèixíng jùyǒu bùtóng de dàxiǎo" +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "Could not publish to ROS topic" +msgstr "wúfǎ fābù dào ROS zhǔtí" + #: shared-bindings/_bleio/Adapter.c msgid "Could not set address" msgstr "wúfǎ shèzhì dìzhǐ" @@ -875,6 +884,11 @@ msgstr "Wúfǎ qǐdòng zhōngduàn,RX máng" msgid "Couldn't allocate decoder" msgstr "wúfǎ fēnpèi jiěmǎ qì" +#: ports/espressif/common-hal/rclcpy/__init__.c +#, c-format +msgid "Critical ROS failure during soft reboot, reset required: %d" +msgstr "ruǎn chóngqǐ qījiān fāshēng guānjiàn de ROS gùzhàng, xūyàozhòngzhì: %d" + #: ports/stm/common-hal/analogio/AnalogOut.c msgid "DAC Channel Init Error" msgstr "DAC tōngdào chūshǐhuà cuòwù" @@ -1061,7 +1075,7 @@ msgstr "Wúfǎ shìfàng mutex, err 0x%04x" #: ports/zephyr-cp/common-hal/wifi/Radio.c msgid "Failed to set hostname" -msgstr "" +msgstr "wúfǎ shèzhì zhǔjīmíng" #: ports/espressif/common-hal/audioio/AudioOut.c msgid "Failed to start async audio" @@ -1075,6 +1089,7 @@ msgstr "Wúfǎ xiě rù nèibù shǎncún." msgid "File exists" msgstr "Wénjiàn cúnzài" +#: shared-bindings/supervisor/__init__.c shared-module/lvfontio/OnDiskFont.c #: shared-module/os/getenv.c msgid "File not found" msgstr "zhǎo bú dào wén jiàn" @@ -1109,7 +1124,7 @@ msgstr "" "zài GRB sè yù zhōng, měi gè shū rù de xiàng sù bì xū shì 16 wèi (16 bit) shù " "jù" -#: ports/cxd56/common-hal/camera/Camera.c +#: ports/cxd56/common-hal/camera/Camera.c shared-module/audiocore/WaveFile.c msgid "Format not supported" msgstr "Bù zhīyuán géshì" @@ -1279,7 +1294,9 @@ msgstr "bèi shūchū gōngnéng zhōngduàn" #: ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c py/argcheck.c #: shared-bindings/digitalio/DigitalInOut.c #: shared-bindings/epaperdisplay/EPaperDisplay.c shared-bindings/pwmio/PWMOut.c +#: shared-bindings/supervisor/__init__.c #: shared-module/aurora_epaper/aurora_framebuffer.c +#: shared-module/lvfontio/OnDiskFont.c msgid "Invalid %q" msgstr "wú xiào %q" @@ -1312,6 +1329,10 @@ msgstr "Wúxiào de BSSID" msgid "Invalid MAC address" msgstr "wú xiào de MAC dì zhǐ" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "Invalid ROS domain ID" +msgstr "wúxiàode ROS yù ID" + #: ports/espressif/common-hal/espidf/__init__.c py/moderrno.c msgid "Invalid argument" msgstr "Wúxiào de cānshù" @@ -1401,6 +1422,11 @@ msgstr "MAC dì zhǐ wú xiào" msgid "MITM security not supported" msgstr "bù zhīchí MITM ānquánxìng" +#: ports/stm/common-hal/sdioio/SDCard.c +#, c-format +msgid "MMC/SDIO Clock Error %x" +msgstr "MMC/SDIO shízhōngcuòwù %x" + #: shared-bindings/is31fl3741/IS31FL3741.c msgid "Mapping must be a tuple" msgstr "yìng shè bì xū shì yuán zǔ" @@ -1587,6 +1613,10 @@ msgstr "zài SDA huò SCL shàng wèi zhǎo dào shàng lā; jiǎn chá nín de msgid "No pulldown on pin; 1Mohm recommended" msgstr "Yǐn jiǎo shàng méiyǒu xiàlā; 1Mohm tuījiàn" +#: shared-module/touchio/TouchIn.c +msgid "No pullup on pin; 1Mohm recommended" +msgstr "Yǐn jiǎo shàng wú shàng lā diànzǔ; jiànyì shǐyòng 1Mohm" + #: py/moderrno.c msgid "No space left on device" msgstr "Shèbèi shàng méiyǒu kònggé" @@ -1866,6 +1896,10 @@ msgstr "chéng xù dà xiǎo wú xiào" msgid "Program too long" msgstr "chéng xù tài cháng" +#: shared-bindings/rclcpy/Publisher.c +msgid "Publishers can only be created from a parent node" +msgstr "chūbǎnshāng zhǐ néngcóng fù jiédiǎn chuàngjiàn" + #: shared-bindings/digitalio/DigitalInOut.c msgid "Pull not used when direction is output." msgstr "Fāngxiàng shūchū shí Pull méiyǒu shǐyòng." @@ -1886,6 +1920,26 @@ msgstr "RNG qǔxiāo chūshǐhuà cuòwù" msgid "RNG Init Error" msgstr "RNG chūshǐhuà cuòwù" +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS failed to initialize. Is agent connected?" +msgstr "ROS chūshǐhuàshībài. dàilǐ yǐ liánjiē ma?" + +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS internal setup failure" +msgstr "ROS nèibù shèzhì shībài" + +#: ports/espressif/common-hal/rclcpy/__init__.c +msgid "ROS memory allocator failure" +msgstr "ROS nèicún fēnpèiqì shībài" + +#: ports/espressif/common-hal/rclcpy/Node.c +msgid "ROS node failed to initialize" +msgstr "ROS jiédiǎn chūshǐhuà shībài" + +#: ports/espressif/common-hal/rclcpy/Publisher.c +msgid "ROS topic failed to initialize" +msgstr "ROS zhǔtí chūshǐhuà shībài" + #: ports/atmel-samd/common-hal/busio/UART.c ports/cxd56/common-hal/busio/UART.c #: ports/nordic/common-hal/busio/UART.c ports/stm/common-hal/busio/UART.c msgid "RS485" @@ -2017,6 +2071,7 @@ msgstr "Qiēpiàn hé zhí bùtóng chángdù." #: shared-bindings/displayio/TileGrid.c #: shared-bindings/memorymonitor/AllocationSize.c #: shared-bindings/pulseio/PulseIn.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c msgid "Slices not supported" msgstr "Qiēpiàn bù shòu zhīchí" @@ -2086,7 +2141,9 @@ msgstr "" msgid "Tile height must exactly divide bitmap height" msgstr "Píng pū gāodù bìxū huàfēn wèi tú gāodù" -#: shared-bindings/displayio/TileGrid.c shared-module/displayio/TileGrid.c +#: shared-bindings/displayio/TileGrid.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-module/displayio/TileGrid.c msgid "Tile index out of bounds" msgstr "Píng pū zhǐshù chāochū fànwéi" @@ -2094,6 +2151,10 @@ msgstr "Píng pū zhǐshù chāochū fànwéi" msgid "Tile width must exactly divide bitmap width" msgstr "Píng pū kuāndù bìxū huàfēn wèi tú kuāndù" +#: shared-module/tilepalettemapper/TilePaletteMapper.c +msgid "TilePaletteMapper may only be bound to a TileGrid once" +msgstr "TilePaletteMapper zhǐnéng bǎngdìng dào yígè TileGrid shàngyícì" + #: shared-bindings/alarm/time/TimeAlarm.c msgid "Time is in the past." msgstr "shí jiān yǐ jīng guò qù." @@ -2322,10 +2383,6 @@ msgstr "bú zhī chí de sè cǎi kōng jiān" msgid "Unsupported display bus type" msgstr "Bù zhīchí de gōnggòng qìchē lèixíng" -#: shared-module/audiocore/WaveFile.c -msgid "Unsupported format" -msgstr "Bù zhīchí de géshì" - #: shared-bindings/hashlib/__init__.c msgid "Unsupported hash algorithm" msgstr "bù zhīchí de hā xī suànfǎ" @@ -2387,9 +2444,11 @@ msgstr "" msgid "Wi-Fi: " msgstr "Wi-Fi: " +#: ports/espressif/common-hal/wifi/Radio.c #: ports/raspberrypi/common-hal/wifi/Radio.c -msgid "Wifi is not enabled" -msgstr "wú xiàn wǎng luò wèi qǐ yòng" +#: ports/zephyr-cp/common-hal/wifi/Radio.c +msgid "WiFi is not enabled" +msgstr "WiFi wèi qǐyòng" #: main.c msgid "Woken up by alarm.\n" @@ -2624,9 +2683,16 @@ msgstr "wèi tú dà xiǎo bì xū pǐ pèi" msgid "bits must be 32 or less" msgstr "wèi bì xū shì 32 huò gèng shǎo" -#: shared-bindings/audiodelays/Echo.c shared-bindings/audiodelays/PitchShift.c +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "bits_per_sample must be 16" +msgstr "bits_per_sample bìxū wèi 16" + +#: shared-bindings/audiodelays/Chorus.c shared-bindings/audiodelays/Echo.c +#: shared-bindings/audiodelays/MultiTapDelay.c +#: shared-bindings/audiodelays/PitchShift.c #: shared-bindings/audiofilters/Distortion.c -#: shared-bindings/audiofilters/Filter.c shared-bindings/audiomixer/Mixer.c +#: shared-bindings/audiofilters/Filter.c shared-bindings/audiofilters/Phaser.c +#: shared-bindings/audiomixer/Mixer.c msgid "bits_per_sample must be 8 or 16" msgstr "měi jiàn yàngběn bìxū wèi 8 huò 16" @@ -3172,7 +3238,7 @@ msgid "format" msgstr "Géshì" #: py/objstr.c -msgid "format requires a dict" +msgid "format needs a dict" msgstr "géshì yāoqiú yīgè yǔjù" #: py/objdeque.c @@ -3632,7 +3698,7 @@ msgid "must use keyword argument for key function" msgstr "bìxū shǐyòng guānjiàn cí cānshù" #: py/runtime.c -msgid "name '%q' is not defined" +msgid "name '%q' isn't defined" msgstr "míngchēng '%q' wèi dìngyì" #: py/runtime.c @@ -4050,6 +4116,10 @@ msgstr "gǔn dòng cān shù bì xū shì ndarray" msgid "rsplit(None,n)" msgstr "Rchāifēn(wú,N)" +#: shared-bindings/audiofreeverb/Freeverb.c +msgid "samples_signed must be true" +msgstr "samples_signed bìxū wéi zhēn" + #: ports/atmel-samd/common-hal/audiobusio/PDMIn.c #: ports/raspberrypi/common-hal/audiobusio/PDMIn.c msgid "sampling rate out of range" @@ -4272,11 +4342,11 @@ msgid "tx and rx cannot both be None" msgstr "tx hé rx bùnéng dōu shì wú" #: py/objtype.c -msgid "type '%q' is not an acceptable base type" +msgid "type '%q' isn't an acceptable base type" msgstr "lèixíng '%q' bùshì kě jiēshòu de jīchǔ lèixíng" #: py/objtype.c -msgid "type is not an acceptable base type" +msgid "type isn't an acceptable base type" msgstr "lèixíng bùshì kě jiēshòu de jīchǔ lèixíng" #: py/runtime.c @@ -4338,7 +4408,9 @@ msgstr "gé shì bù pǐ pèi de '%c'" msgid "unreadable attribute" msgstr "bùkě dú shǔxìng" -#: shared-bindings/displayio/TileGrid.c shared-bindings/vectorio/VectorShape.c +#: shared-bindings/displayio/TileGrid.c shared-bindings/terminalio/Terminal.c +#: shared-bindings/tilepalettemapper/TilePaletteMapper.c +#: shared-bindings/vectorio/VectorShape.c msgid "unsupported %q type" msgstr "bù zhīchí %q lèixíng" @@ -4419,12 +4491,6 @@ msgstr "" msgid "width must be greater than zero" msgstr "kuāndù bìxū dàyú líng" -#: ports/espressif/common-hal/wifi/Radio.c -#: ports/raspberrypi/common-hal/wifi/Radio.c -#: ports/zephyr-cp/common-hal/wifi/Radio.c -msgid "wifi is not enabled" -msgstr "wèi qǐ yòng WIFI" - #: ports/raspberrypi/common-hal/wifi/Monitor.c msgid "wifi.Monitor not available" msgstr "wú xiàn wǎng luò xiǎn shì qì bù kě yòng" @@ -4487,6 +4553,18 @@ msgstr "zi bìxū wèi fú diǎn xíng" msgid "zi must be of shape (n_section, 2)" msgstr "zi bìxū jùyǒu xíngzhuàng (n_section,2)" +#~ msgid "Unsupported format" +#~ msgstr "Bù zhīchí de géshì" + +#~ msgid "Wifi is not enabled" +#~ msgstr "wú xiàn wǎng luò wèi qǐ yòng" + +#~ msgid "wifi is not enabled" +#~ msgstr "wèi qǐ yòng WIFI" + +#~ msgid "Cannot remount '/' when visible via USB." +#~ msgstr "tōngguò USB kějiàn shí wúfǎ chóngxīn ānzhuāng '/'." + #~ msgid "%q must be a %q object, %q, or %q" #~ msgstr "%q bìxū shì %q duìxiàng, %q huò %q" @@ -4848,13 +4926,13 @@ msgstr "zi bìxū jùyǒu xíngzhuàng (n_section,2)" #~ msgid "'%s' object does not support item deletion" #~ msgstr "'%s' duìxiàng bù zhīchí shānchú xiàngmù" -#~ msgid "'%s' object is not an iterator" +#~ msgid "'%s' object isn't an iterator" #~ msgstr "'%s' duìxiàng bùshì yīgè diédài qì" #~ msgid "'%s' object is not callable" #~ msgstr "'%s' duìxiàng wúfǎ diàoyòng" -#~ msgid "'%s' object is not iterable" +#~ msgid "'%s' object isn't iterable" #~ msgstr "'%s' duìxiàng bùnéng diédài" #~ msgid "'%s' object is not subscriptable" @@ -4870,7 +4948,7 @@ msgstr "zi bìxū jùyǒu xíngzhuàng (n_section,2)" #~ msgid "'continue' outside loop" #~ msgstr "'continue' wèiyú xúnhuán zhīwài" -#~ msgid "'coroutine' object is not an iterator" +#~ msgid "'coroutine' object isn't an iterator" #~ msgstr "'coroutine' duìxiàng búshì yígè diédàiqì" #~ msgid "(x,y) integers required" @@ -6218,7 +6296,7 @@ msgstr "zi bìxū jùyǒu xíngzhuàng (n_section,2)" #~ msgid "frequency is read-only for this board" #~ msgstr "cǐ zhǔ bǎn de pín lǜ wéi zhǐ dú" -#~ msgid "function does not take keyword arguments" +#~ msgid "function doesn't take keyword arguments" #~ msgstr "hánshù méiyǒu guānjiàn cí cānshù" #~ msgid "function is implemented for scalars and ndarrays only" @@ -6320,7 +6398,7 @@ msgstr "zi bìxū jùyǒu xíngzhuàng (n_section,2)" #~ msgid "name must be a string" #~ msgstr "míngchēng bìxū shì yīgè zìfú chuàn" -#~ msgid "name reused for argument" +#~ msgid "argument name reused" #~ msgstr "cān shǔ míngchēng bèi chóngxīn shǐyòng" #~ msgid "no available NIC" diff --git a/main.c b/main.c index 0ea389635f4..93b433c13ea 100644 --- a/main.c +++ b/main.c @@ -15,12 +15,14 @@ #include "py/compile.h" #include "py/frozenmod.h" #include "py/mphal.h" +#include "py/persistentcode.h" #include "py/runtime.h" #include "py/repl.h" #include "py/gc.h" #include "py/stackctrl.h" #include "shared/readline/readline.h" +#include "shared/runtime/gchelper.h" #include "shared/runtime/pyexec.h" #include "background.h" @@ -42,6 +44,7 @@ #include "supervisor/shared/external_flash/external_flash.h" #include "shared-bindings/microcontroller/__init__.h" +#include "shared-bindings/microcontroller/Pin.h" #include "shared-bindings/microcontroller/Processor.h" #include "shared-bindings/supervisor/__init__.h" #include "shared-bindings/supervisor/Runtime.h" @@ -65,10 +68,6 @@ #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" #include "shared-bindings/displayio/__init__.h" @@ -78,14 +77,34 @@ #include "shared-bindings/epaperdisplay/EPaperDisplay.h" #endif -#if CIRCUITPY_KEYPAD -#include "shared-module/keypad/__init__.h" +#if CIRCUITPY_PICOGAME_RGB444 +#include "shared-module/picogame/__init__.h" +#endif + +#if CIRCUITPY_STORAGE_MAP_FILE +#include "shared-bindings/storage/__init__.h" +#endif + +#if CIRCUITPY_AUDIOFILEWRITER +#include "shared-module/audiofilewriter/AudioFileWriter.h" +#endif + +#if CIRCUITPY_USB_HOST_AUDIO +#include "shared-module/usb_host_audio/USBIn.h" +#endif + +#if CIRCUITPY_VIDEOGIF +#include "shared-module/videogif/GifDecoder.h" #endif #if CIRCUITPY_MEMORYMONITOR #include "shared-module/memorymonitor/__init__.h" #endif +#if CIRCUITPY_AIRLIFT +#include "shared-module/_airlift/transport.h" +#endif + #if CIRCUITPY_SOCKETPOOL #include "shared-bindings/socketpool/__init__.h" #endif @@ -111,35 +130,30 @@ uint8_t value_out = 0; #endif -#if MICROPY_ENABLE_PYSTACK && CIRCUITPY_OS_GETENV -#include "shared-module/os/__init__.h" +#if CIRCUITPY_SETTINGS_TOML +#include "supervisor/shared/settings.h" #endif -static void reset_devices(void) { - #if CIRCUITPY_BLEIO_HCI - bleio_reset(); - #endif -} - static uint8_t *_heap; static uint8_t *_pystack; +static volatile bool _vm_is_running = false; static const char line_clear[] = "\x1b[2K\x1b[0G"; #if MICROPY_ENABLE_PYSTACK || MICROPY_ENABLE_GC static uint8_t *_allocate_memory(safe_mode_t safe_mode, const char *env_key, size_t default_size, size_t *final_size) { *final_size = default_size; - #if CIRCUITPY_OS_GETENV + #if CIRCUITPY_SETTINGS_TOML if (safe_mode == SAFE_MODE_NONE) { mp_int_t size; - if (common_hal_os_getenv_int(env_key, &size) == GETENV_OK && size > 0) { + if (settings_get_int(env_key, &size) == SETTINGS_OK && size > 0) { *final_size = size; } } #endif uint8_t *ptr = port_malloc(*final_size, false); - #if CIRCUITPY_OS_GETENV + #if CIRCUITPY_SETTINGS_TOML if (ptr == NULL) { // Fallback to the build size. ptr = port_malloc(default_size, false); @@ -193,6 +207,7 @@ static void start_mp(safe_mode_t safe_mode) { _heap = _allocate_memory(safe_mode, "CIRCUITPY_HEAP_START_SIZE", CIRCUITPY_HEAP_START_SIZE, &heap_size); gc_init(_heap, _heap + heap_size); #endif + background_callback_heap_ready(); mp_init(); mp_obj_list_init((mp_obj_list_t *)mp_sys_path, 0); mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR_)); // current dir (or base dir of the script) @@ -203,20 +218,36 @@ static void start_mp(safe_mode_t safe_mode) { mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR__slash_lib)); mp_obj_list_init((mp_obj_list_t *)mp_sys_argv, 0); + + // Always return to root + common_hal_os_chdir("/"); + + _vm_is_running = true; } static void stop_mp(void) { + _vm_is_running = false; #if MICROPY_VFS - mp_vfs_mount_t *vfs = MP_STATE_VM(vfs_mount_table); // Unmount all heap allocated vfs mounts. - while (gc_nbytes(vfs) > 0) { - vfs = vfs->next; - } - MP_STATE_VM(vfs_mount_table) = vfs; - // The last vfs is CIRCUITPY and the root directory. - while (vfs->next != NULL) { - vfs = vfs->next; + mp_vfs_mount_t *vfs = MP_STATE_VM(vfs_mount_table); + if (vfs != NULL) { + do { + if (gc_ptr_on_heap(vfs)) { + // mp_vfs_umount will splice out an unmounted vfs from the vfs_mount_table linked list. + mp_vfs_umount(vfs->obj); + // Start over at the beginning of the list since the first entry may have been removed. + vfs = MP_STATE_VM(vfs_mount_table); + continue; + } + vfs = vfs->next; + } while (vfs != NULL); + + // The last vfs is CIRCUITPY and the root directory. + vfs = MP_STATE_VM(vfs_mount_table); + while (vfs->next != NULL) { + vfs = vfs->next; + } } MP_STATE_VM(vfs_cur) = vfs; #endif @@ -232,6 +263,7 @@ static void stop_mp(void) { qstr_reset(); gc_deinit(); + port_gc_deinit(); port_free(_heap); _heap = NULL; @@ -250,9 +282,10 @@ void supervisor_execution_status(void) { mp_obj_exception_t *exception = MP_OBJ_TO_PTR(_exec_result.exception); if (_current_executing_filename != NULL) { serial_write(_current_executing_filename); - } else if ((_exec_result.return_code & PYEXEC_EXCEPTION) != 0 && - _exec_result.exception_line > 0 && - exception != NULL) { + } else if ( + (_exec_result.return_code == PYEXEC_UNHANDLED_EXCEPTION) && + (_exec_result.exception_line > 0) && + exception != NULL) { mp_printf(&mp_plat_print, "%d@%s %q", _exec_result.exception_line, _exec_result.exception_filename, exception->base.type->name); } else { serial_write_compressed(MP_ERROR_TEXT("Done")); @@ -318,6 +351,9 @@ static void count_strn(void *data, const char *str, size_t len) { } static void cleanup_after_vm(mp_obj_t exception) { + // Do any port cleanup needed before anything else, including releasing board buses. + reset_port_early(); + // Get the traceback of any exception from this run off the heap. // MP_OBJ_SENTINEL means "this run does not contribute to traceback storage, don't touch it" // MP_OBJ_NULL (=0) means "this run completed successfully, clear any stored traceback" @@ -348,13 +384,20 @@ static void cleanup_after_vm(mp_obj_t exception) { } } - // Reset port-independent devices, like CIRCUITPY_BLEIO_HCI. - reset_devices(); - #if CIRCUITPY_ATEXIT atexit_reset(); #endif + // Restore the panel's pixel format while the display bus is still alive. + #if CIRCUITPY_PICOGAME_RGB444 + picogame_reset(); + #endif + + // Stop GIF playback before the displays and their framebuffers go away. + #if CIRCUITPY_VIDEOGIF + videogif_reset(); + #endif + // Turn off the display and flush the filesystem before the heap disappears. #if CIRCUITPY_DISPLAYIO reset_displays(); @@ -364,17 +407,21 @@ static void cleanup_after_vm(mp_obj_t exception) { memorymonitor_reset(); #endif - // Disable user related BLE state that uses the micropython heap. + // Disable user related BLE state that uses the VM heap. Leave BLE workflow running if it's in use. #if CIRCUITPY_BLEIO bleio_user_reset(); #endif - #if CIRCUITPY_CANIO - common_hal_canio_reset(); + #if CIRCUITPY_STORAGE_MAP_FILE + storage_map_file_reset(); #endif - #if CIRCUITPY_KEYPAD - keypad_reset(); + #if CIRCUITPY_AUDIOFILEWRITER + audiofilewriter_reset(); + #endif + + #if CIRCUITPY_USB_HOST_AUDIO + usb_host_audio_reset(); #endif // Close user-initiated sockets. @@ -382,13 +429,16 @@ static void cleanup_after_vm(mp_obj_t exception) { socketpool_user_reset(); #endif + // Close sockets that user code left open on the ESP32 co-processor. + #if CIRCUITPY_AIRLIFT + airlift_user_reset(); + #endif + // Turn off user initiated WiFi connections. #if CIRCUITPY_WIFI wifi_user_reset(); #endif - // reset_board_buses() first because it may release pins from the never_reset state, so that - // reset_port() can reset them. #if CIRCUITPY_BOARD reset_board_buses(); #endif @@ -397,6 +447,8 @@ static void cleanup_after_vm(mp_obj_t exception) { // Free the heap last because other modules may reference heap memory and need to shut down. filesystem_flush(); + + // Runs finalisers while shutting down the heap. stop_mp(); // Let the workflows know we've reset in case they want to restart. @@ -417,17 +469,6 @@ static void print_code_py_status_message(safe_mode_t safe_mode) { } static bool __attribute__((noinline)) run_code_py(safe_mode_t safe_mode, bool *simulate_reset) { - bool serial_connected_at_start = serial_connected(); - bool printed_safe_mode_message = false; - #if CIRCUITPY_AUTORELOAD_DELAY_MS > 0 - if (serial_connected_at_start) { - serial_write("\r\n"); - print_code_py_status_message(safe_mode); - print_safe_mode_message(safe_mode); - printed_safe_mode_message = true; - } - #endif - bool skip_repl = false; bool skip_wait = false; bool found_main = false; @@ -462,9 +503,12 @@ static bool __attribute__((noinline)) run_code_py(safe_mode_t safe_mode, bool *s next_code_configuration->options &= ~SUPERVISOR_NEXT_CODE_OPT_NEWLY_SET; next_code_options = next_code_configuration->options; if (next_code_configuration->filename[0] != '\0') { + if (next_code_configuration->working_directory != NULL) { + common_hal_os_chdir(next_code_configuration->working_directory); + } // This is where the user's python code is actually executed: const char *const filenames[] = { next_code_configuration->filename }; - found_main = maybe_run_list(filenames, MP_ARRAY_SIZE(filenames)); + found_main = maybe_run_list(filenames, 1); if (!found_main) { serial_write(next_code_configuration->filename); serial_write_compressed(MP_ERROR_TEXT(" not found.\n")); @@ -498,6 +542,7 @@ static bool __attribute__((noinline)) run_code_py(safe_mode_t safe_mode, bool *s // Finished executing python code. Cleanup includes filesystem flush and a board reset. + _vm_is_running = false; cleanup_after_vm(_exec_result.exception); _exec_result.exception = NULL; @@ -557,7 +602,7 @@ static bool __attribute__((noinline)) run_code_py(safe_mode_t safe_mode, bool *s blink_count = 0; } else #endif - if (_exec_result.return_code != PYEXEC_EXCEPTION) { + if (_exec_result.return_code != PYEXEC_UNHANDLED_EXCEPTION) { if (safe_mode == SAFE_MODE_NONE) { color = ALL_DONE; blink_count = ALL_DONE_BLINKS; @@ -575,10 +620,11 @@ static bool __attribute__((noinline)) run_code_py(safe_mode_t safe_mode, bool *s size_t total_time = blink_time + LED_SLEEP_TIME_MS; #endif - // This loop is waits after code completes. It waits for fake sleeps to - // finish, user input or autoreloads. + // This loop is run after code completes. It waits for fake sleeps to + // finish, waits for user input, or waits for an autoreload. #if CIRCUITPY_ALARM bool fake_sleeping = false; + bool keep_display_in_fake_sleep = false; #endif while (!skip_wait) { RUN_BACKGROUND_TASKS; @@ -623,20 +669,18 @@ static bool __attribute__((noinline)) run_code_py(safe_mode_t safe_mode, bool *s // If messages haven't been printed yet, print them if (!printed_press_any_key && serial_connected() && !autoreload_pending()) { - if (!serial_connected_at_start) { - print_code_py_status_message(safe_mode); - } - - if (!printed_safe_mode_message) { - print_safe_mode_message(safe_mode); - printed_safe_mode_message = true; - } + print_code_py_status_message(safe_mode); + print_safe_mode_message(safe_mode); serial_write("\r\n"); serial_write_compressed(MP_ERROR_TEXT("Press any key to enter the REPL. Use CTRL-D to reload.\n")); + if (safe_mode != SAFE_MODE_NONE) { + // Reset the port again in safe mode. It doesn't usually do much but + // the Zephyr native_sim tests use it for tracking test completion. + reset_port(); + } printed_press_any_key = true; } if (!serial_connected()) { - serial_connected_at_start = false; printed_press_any_key = false; } @@ -644,7 +688,7 @@ static bool __attribute__((noinline)) run_code_py(safe_mode_t safe_mode, bool *s #if CIRCUITPY_ALARM if (_exec_result.return_code & PYEXEC_DEEP_SLEEP) { const bool awoke_from_true_deep_sleep = - common_hal_mcu_processor_get_reset_reason() == RESET_REASON_DEEP_SLEEP_ALARM; + common_hal_mcu_processor_get_reset_reason() == MCU_RESET_REASON_DEEP_SLEEP_ALARM; if (fake_sleeping) { // This waits until a pretend deep sleep alarm occurs. They are set @@ -662,15 +706,24 @@ static bool __attribute__((noinline)) run_code_py(safe_mode_t safe_mode, bool *s else if (awoke_from_true_deep_sleep || port_get_raw_ticks(NULL) > CIRCUITPY_WORKFLOW_CONNECTION_SLEEP_DELAY * 1024) { // OK to start sleeping, real or fake. + const bool true_deep_sleep = awoke_from_true_deep_sleep || !supervisor_workflow_active(); #if CIRCUITPY_DISPLAYIO - common_hal_displayio_release_displays(); + // A fake sleep doesn't run boot.py again, so keep a display set as + // supervisor.runtime.display. Also leave the board as a reload does, because + // board_init() can't make its own display if the kept one fills the slots. + keep_display_in_fake_sleep = !true_deep_sleep && common_hal_displayio_primary_display_set_by_user(); + if (!keep_display_in_fake_sleep) { + common_hal_displayio_release_displays(); + } #endif status_led_deinit(); deinit_rxtx_leds(); - board_deinit(); + if (!keep_display_in_fake_sleep) { + board_deinit(); + } // Continue with true deep sleep even if workflow is available. - if (awoke_from_true_deep_sleep || !supervisor_workflow_active()) { + if (true_deep_sleep) { // Enter true deep sleep. When we wake up we'll be back at the // top of main(), not in this loop. common_hal_alarm_enter_deep_sleep(); @@ -754,8 +807,10 @@ static bool __attribute__((noinline)) run_code_py(safe_mode_t safe_mode, bool *s // Done waiting, start the board back up. - // We delay resetting BLE until after the wait in case we're transferring - // more files over. + // Resetting BLE is delayed until here, after the wait, in case files were being + // transferred over the BLE workflow during the wait. The reset restarts the BLE + // stack, dropping the workflow connection, only if user code created GATT + // services; otherwise it is a no-op and the connection continues. #if CIRCUITPY_BLEIO bleio_reset(); #endif @@ -775,9 +830,15 @@ static bool __attribute__((noinline)) run_code_py(safe_mode_t safe_mode, bool *s #if CIRCUITPY_ALARM if (fake_sleeping) { - board_init(); - #if CIRCUITPY_DISPLAYIO - common_hal_displayio_auto_primary_display(); + if (!keep_display_in_fake_sleep) { + board_init(); + #if CIRCUITPY_DISPLAYIO + common_hal_displayio_auto_primary_display(); + #endif + } + // Undo any preserve_dios. + #if CIRCUITPY_ALARM_PRESERVE_DIOS + common_hal_alarm_clear_pin_preservations(); #endif // Pretend that the next run is the first run, as if we were reset. *simulate_reset = true; @@ -848,8 +909,19 @@ static void __attribute__ ((noinline)) run_boot_py(safe_mode_t safe_mode) { boot_output = &boot_text; #endif + // Get the base filesystem. + supervisor_vfs_t *vfs_root = filesystem_circuitpy(); + fs_user_mount_t *vfs = vfs_root == NULL ? NULL : &vfs_root->fat; + + // Allow boot.py access to CIRCUITPY, and allow writes to boot_out.txt. + // We can't use the regular flags for this, because they might get modified inside boot.py. + filesystem_set_ignore_write_protection(vfs, true); + // Write version info mp_printf(&mp_plat_print, "%s\nBoard ID:%s\n", MICROPY_FULL_VERSION_INFO, CIRCUITPY_BOARD_ID); + #if MICROPY_PERSISTENT_CODE_LOAD_NATIVE + mp_printf(&mp_plat_print, "%q:%s\n", MP_QSTR_architecture, MPY_FEATURE_ARCH_NAME); + #endif #if CIRCUITPY_MICROCONTROLLER && COMMON_HAL_MCU_PROCESSOR_UID_LENGTH > 0 uint8_t raw_id[COMMON_HAL_MCU_PROCESSOR_UID_LENGTH]; common_hal_mcu_processor_get_uid(raw_id); @@ -866,24 +938,22 @@ static void __attribute__ ((noinline)) run_boot_py(safe_mode_t safe_mode) { #ifdef CIRCUITPY_BOOT_OUTPUT_FILE - // Get the base filesystem. - fs_user_mount_t *vfs = filesystem_circuitpy(); - FATFS *fs = &vfs->fatfs; - boot_output = NULL; #if CIRCUITPY_STATUS_BAR supervisor_status_bar_resume(); #endif bool write_boot_output = true; - FIL boot_output_file; - if (f_open(fs, &boot_output_file, CIRCUITPY_BOOT_OUTPUT_FILE, FA_READ) == FR_OK) { + supervisor_vfs_file_t boot_output_file; + if (supervisor_vfs_open_file(vfs_root, CIRCUITPY_BOOT_OUTPUT_FILE, SUPERVISOR_FS_OPEN_READ, 0, + &boot_output_file) == SUPERVISOR_FS_OK) { char *file_contents = m_new(char, boot_text.alloc); - UINT chars_read; - if (f_read(&boot_output_file, file_contents, 1 + boot_text.len, &chars_read) == FR_OK) { + size_t chars_read; + if (supervisor_vfs_read_file(&boot_output_file, file_contents, 1 + boot_text.len, &chars_read) == + SUPERVISOR_FS_OK) { write_boot_output = (chars_read != boot_text.len) || (memcmp(boot_text.buf, file_contents, chars_read) != 0); } - // no need to f_close the file + supervisor_vfs_close_file(&boot_output_file); } if (write_boot_output) { @@ -891,24 +961,23 @@ static void __attribute__ ((noinline)) run_boot_py(safe_mode_t safe_mode) { // in case power is momentary or will fail shortly due to, say a low, battery. mp_hal_delay_ms(1000); - // USB isn't up, so we can write the file. - // operating at the oofatfs (f_open) layer means the usb concurrent write permission - // is not even checked! - f_open(fs, &boot_output_file, CIRCUITPY_BOOT_OUTPUT_FILE, FA_WRITE | FA_CREATE_ALWAYS); - UINT chars_written; - f_write(&boot_output_file, boot_text.buf, boot_text.len, &chars_written); - f_close(&boot_output_file); - filesystem_flush(); + if (supervisor_vfs_open_file(vfs_root, CIRCUITPY_BOOT_OUTPUT_FILE, + SUPERVISOR_FS_OPEN_WRITE | SUPERVISOR_FS_OPEN_CREATE | SUPERVISOR_FS_OPEN_TRUNCATE, 0, + &boot_output_file) == SUPERVISOR_FS_OK) { + size_t chars_written; + supervisor_vfs_write_file(&boot_output_file, boot_text.buf, boot_text.len, &chars_written); + supervisor_vfs_close_file(&boot_output_file); + filesystem_flush(); + } } #endif - } - port_post_boot_py(true); + // Back to regular filesystem protections. + filesystem_set_ignore_write_protection(vfs, false); + } cleanup_after_vm(_exec_result.exception); _exec_result.exception = NULL; - - port_post_boot_py(false); } static int run_repl(safe_mode_t safe_mode) { @@ -965,8 +1034,9 @@ static int run_repl(safe_mode_t safe_mode) { #endif cleanup_after_vm(MP_OBJ_SENTINEL); - // Also reset bleio. The above call omits it in case workflows should continue. In this case, - // we're switching straight to another VM so we want to reset. + // Also reset bleio, which cleanup_after_vm() above omits so workflows can + // continue between VMs. As in run_code_py(), this restarts the BLE stack only if + // user code created GATT services. #if CIRCUITPY_BLEIO bleio_reset(); #endif @@ -994,6 +1064,7 @@ int __attribute__((used)) main(void) { port_heap_init(); + // Turn on RX and TX LEDs if we have them. init_rxtx_leds(); @@ -1008,18 +1079,12 @@ int __attribute__((used)) main(void) { serial_early_init(); mp_hal_stdout_tx_str(line_clear); - // Wait briefly to give a reset window where we'll enter safe mode after the reset. - if (get_safe_mode() == SAFE_MODE_NONE) { - set_safe_mode(wait_for_safe_mode_reset()); - } - stack_init(); #if CIRCUITPY_STATUS_BAR supervisor_status_bar_init(); #endif - #if !INTERNAL_FLASH_FILESYSTEM // Set up anything that might need to get done before we try to use SPI flash // This is needed for some boards where flash relies on GPIO setup to work @@ -1036,6 +1101,17 @@ int __attribute__((used)) main(void) { set_safe_mode(SAFE_MODE_NO_CIRCUITPY); } + #if CIRCUITPY_STORAGE_MAP_FILE + storage_map_file_init(); + #endif + + // Wait briefly to give a reset window where we'll enter safe mode after the reset. + // Do this after mounting the filesystem because settings.toml can contain + // CIRCUITPY_SAFE_MODE_DELAY to change the default delay. + if (get_safe_mode() == SAFE_MODE_NONE) { + set_safe_mode(wait_for_safe_mode_reset()); + } + #if CIRCUITPY_BLEIO // Early init so that a reset press can cause BLE public advertising. Need the filesystem to // read settings.toml. @@ -1053,10 +1129,14 @@ int __attribute__((used)) main(void) { // Reset everything and prep MicroPython to run boot.py. reset_port(); - // Port-independent devices, like CIRCUITPY_BLEIO_HCI. - reset_devices(); reset_board(); + #if CIRCUITPY_USB_KEYBOARD_WORKFLOW + // board_init() or boot.py may start a USB host port, and from then on + // TinyUSB's callbacks use the keyboard's lock and buffer. + usb_keyboard_init(); + #endif + // displays init after filesystem, since they could share the flash SPI board_init(); @@ -1109,9 +1189,6 @@ int __attribute__((used)) main(void) { } simulate_reset = false; - // Always return to root before trying to run files. - common_hal_os_chdir("/"); - if (pyexec_mode_kind == PYEXEC_MODE_FRIENDLY_REPL) { // If code.py did a fake deep sleep, pretend that we // are running code.py for the first time after a hard @@ -1120,7 +1197,7 @@ int __attribute__((used)) main(void) { } else { skip_repl = false; } - } else if (exit_code != 0) { + } else if (exit_code != PYEXEC_NORMAL_EXIT) { break; } @@ -1136,8 +1213,7 @@ int __attribute__((used)) main(void) { void gc_collect(void) { gc_collect_start(); - mp_uint_t regs[10]; - mp_uint_t sp = cpu_get_regs_and_sp(regs); + gc_helper_collect_regs_and_stack(); // This collects root pointers from the VFS mount table. Some of them may // have lost their references in the VM even though they are mounted. @@ -1171,28 +1247,25 @@ void gc_collect(void) { common_hal_wifi_gc_collect(); #endif - // This naively collects all object references from an approximate stack - // range. - gc_collect_root((void **)sp, ((mp_uint_t)port_stack_get_top() - sp) / sizeof(mp_uint_t)); gc_collect_end(); } -// Ports may provide an implementation of this function if it is needed -MP_WEAK void port_gc_collect() { -} - size_t gc_get_max_new_split(void) { return port_heap_get_largest_free_size(); } -void NORETURN nlr_jump_fail(void *val) { +void MP_NORETURN nlr_jump_fail(void *val) { reset_into_safe_mode(SAFE_MODE_NLR_JUMP_FAIL); while (true) { } } +bool vm_is_running(void) { + return _vm_is_running; +} + #ifndef NDEBUG -static void NORETURN __fatal_error(const char *msg) { +static void MP_NORETURN __fatal_error(const char *msg) { #if CIRCUITPY_DEBUG == 0 reset_into_safe_mode(SAFE_MODE_HARD_FAULT); #endif diff --git a/mpy-cross/Makefile b/mpy-cross/Makefile index 9962e9bcbb2..bd9e0fb1f54 100644 --- a/mpy-cross/Makefile +++ b/mpy-cross/Makefile @@ -25,6 +25,12 @@ CFLAGS += -fdata-sections -ffunction-sections -fno-asynchronous-unwind-tables # CIRCUITPY-CHANGE CFLAGS += -DCIRCUITPY +# Build a static executable. +# Useful for builds that must run on multiple operating system versions. Used for published mpy-cross versions. +ifdef STATIC_BUILD +CFLAGS += -static -static-libgcc -static-libstdc++ +endif + # Debugging/Optimization ifdef DEBUG CFLAGS += -g @@ -47,6 +53,10 @@ LDFLAGS_ARCH = -Wl,-Map=$@.map,--cref -Wl,--gc-sections endif LDFLAGS += $(LDFLAGS_MOD) $(LDFLAGS_ARCH) -lm $(LDFLAGS_EXTRA) +ifdef STATIC_BUILD +LDFLAGS += -static -static-libgcc -static-libstdc++ +endif + # source files # CIRCUITPY-CHANGE: extra files SRC_C = \ diff --git a/mpy-cross/main.c b/mpy-cross/main.c index 611da764687..7d829e79e68 100644 --- a/mpy-cross/main.c +++ b/mpy-cross/main.c @@ -24,6 +24,7 @@ * THE SOFTWARE. */ +#include #include #include #include @@ -34,16 +35,25 @@ #include "py/persistentcode.h" #include "py/runtime.h" #include "py/gc.h" -#include "py/stackctrl.h" +#include "py/parsenumbase.h" #include "genhdr/mpversion.h" #ifdef _WIN32 // CIRCUITPY-CHANGE #include "fmode.h" #endif +#if MICROPY_EMIT_NATIVE && MICROPY_EMIT_RV32 +#include "py/asmrv32.h" + +static asm_rv32_backend_options_t rv32_options = { 0 }; +#endif + // Command line options, with their defaults static uint emit_opt = MP_EMIT_OPT_NONE; -mp_uint_t mp_verbose_flag = 0; + +#if MICROPY_ENABLE_SOURCE_LINE +static bool include_source_lines = true; +#endif // Heap size of GC heap (if enabled) // Make it larger on a 64 bit machine, because pointers are larger. @@ -55,7 +65,7 @@ static void stdout_print_strn(void *env, const char *str, size_t len) { (void)dummy; } -static const mp_print_t mp_stdout_print = {NULL, stdout_print_strn}; +const mp_print_t mp_stdout_print = {NULL, stdout_print_strn}; static void stderr_print_strn(void *env, const char *str, size_t len) { (void)env; @@ -82,13 +92,20 @@ static int compile_and_save(const char *file, const char *output_file, const cha source_name = qstr_from_str(source_file); } - #if MICROPY_PY___FILE__ + #if MICROPY_MODULE___FILE__ mp_store_global(MP_QSTR___file__, MP_OBJ_NEW_QSTR(source_name)); #endif mp_parse_tree_t parse_tree = mp_parse(lex, MP_PARSE_FILE_INPUT); mp_compiled_module_t cm; cm.context = m_new_obj(mp_module_context_t); + cm.arch_flags = 0; + #if MICROPY_EMIT_NATIVE && MICROPY_EMIT_RV32 + if (mp_dynamic_compiler.native_arch == MP_NATIVE_ARCH_RV32IMC && mp_dynamic_compiler.backend_options != NULL) { + cm.arch_flags = ((asm_rv32_backend_options_t *)mp_dynamic_compiler.backend_options)->allowed_extensions; + } + #endif + mp_compile_to_raw_code(&parse_tree, source_name, false, &cm); if ((output_file != NULL && strcmp(output_file, "-") == 0) || @@ -130,7 +147,11 @@ static int usage(char **argv) { "\n" "Target specific options:\n" "-msmall-int-bits=number : set the maximum bits used to encode a small-int\n" - "-march= : set architecture for native emitter; x86, x64, armv6, armv6m, armv7m, armv7em, armv7emsp, armv7emdp, xtensa, xtensawin\n" + "-march= : set architecture for native emitter;\n" + " x86, x64, armv6, armv6m, armv7m, armv7em, armv7emsp,\n" + " armv7emdp, xtensa, xtensawin, rv32imc, rv64imc, host, debug\n" + "-march-flags= : set architecture-specific flags (can be either a dec/hex/bin value or a comma-separated flags string)\n" + " supported flags for rv32imc: zba, zcmp\n" "\n" "Implementation specific options:\n", argv[0] ); @@ -147,6 +168,12 @@ static int usage(char **argv) { " heapsize= -- set the heap size for the GC (default %ld)\n" , heap_size); impl_opts_cnt++; + #if MICROPY_ENABLE_SOURCE_LINE + printf( + " source-lines -- include source line numbers (default)\n" + " no-source-lines -- exclude source line numbers\n"); + impl_opts_cnt += 2; + #endif if (impl_opts_cnt == 0) { printf(" (none)\n"); @@ -171,6 +198,14 @@ static void pre_process_options(int argc, char **argv) { } else if (strcmp(argv[a + 1], "emit=viper") == 0) { emit_opt = MP_EMIT_OPT_VIPER; #endif + #if MICROPY_ENABLE_SOURCE_LINE + } else if (strcmp(argv[a + 1], "source-lines") == 0) { + // Allow excluding source lines for debug builds. + include_source_lines = true; + } else if (strcmp(argv[a + 1], "no-source-lines") == 0) { + // Allow excluding source lines for debug builds. + include_source_lines = false; + #endif } else if (strncmp(argv[a + 1], "heapsize=", sizeof("heapsize=") - 1) == 0) { char *end; heap_size = strtol(argv[a + 1] + sizeof("heapsize=") - 1, &end, 0); @@ -211,9 +246,57 @@ static char *backslash_to_forwardslash(char *path) { return path; } -MP_NOINLINE int main_(int argc, char **argv) { - mp_stack_set_limit(40000 * (sizeof(void *) / 4)); +// This will need to be reworked in case mpy-cross needs to set more bits than +// what `unsigned long` can fit. +static bool parse_integer(const char *value, unsigned long *integer) { + assert(value && "Attempting to parse a NULL string"); + assert(integer && "Attempting to store into a NULL integer buffer"); + + size_t value_length = strlen(value); + int base = 0; + size_t skip = mp_parse_num_base(value, value_length, &base); + // These can trip strtoul up. + if (base < 2 || value_length == skip || value[skip] == '+') { + return false; + } + errno = 0; + char *end = NULL; + *integer = strtoul(value + skip, &end, base); + if (end != (value + value_length) || errno != 0) { + return false; + } + return true; +} +#if MICROPY_EMIT_NATIVE && MICROPY_EMIT_RV32 +static bool parse_rv32_flags_string(const char *source, unsigned long *flags) { + assert(source && "Flag arguments string is NULL."); + assert(flags && "Collected flags pointer is NULL."); + + const char *current = source; + const char *end = source + strlen(source); + unsigned long collected_flags = 0; + while (current < end) { + const char *separator = strchr(current, ','); + if (separator == NULL) { + separator = end; + } + ptrdiff_t length = separator - current; + if (length == (sizeof("zba") - 1) && memcmp(current, "zba", length) == 0) { + collected_flags |= RV32_EXT_ZBA; + } else if (length == (sizeof("zcmp") - 1) && memcmp(current, "zcmp", length) == 0) { + collected_flags |= RV32_EXT_ZCMP; + } else { + return false; + } + current = separator + 1; + } + *flags = collected_flags; + return collected_flags != 0; +} +#endif + +MP_NOINLINE int main_(int argc, char **argv) { pre_process_options(argc, argv); char *heap = malloc(heap_size); @@ -236,11 +319,16 @@ MP_NOINLINE int main_(int argc, char **argv) { // don't support native emitter unless -march is specified mp_dynamic_compiler.native_arch = MP_NATIVE_ARCH_NONE; mp_dynamic_compiler.nlr_buf_num_regs = 0; + mp_dynamic_compiler.backend_options = NULL; + #if MICROPY_ENABLE_SOURCE_LINE + mp_dynamic_compiler.include_source_lines = include_source_lines; + #endif const char *input_file = NULL; const char *output_file = NULL; const char *source_file = NULL; bool option_parsing_active = true; + const char *arch_flags = NULL; // parse main options for (int a = 1; a < argc; a++) { @@ -253,7 +341,7 @@ MP_NOINLINE int main_(int argc, char **argv) { "; mpy-cross emitting mpy v" MP_STRINGIFY(MPY_VERSION) "." MP_STRINGIFY(MPY_SUB_VERSION) "\n"); return 0; } else if (strcmp(argv[a], "-v") == 0) { - mp_verbose_flag++; + // This verbose option doesn't currently do anything. } else if (strncmp(argv[a], "-O", 2) == 0) { if (unichar_isdigit(argv[a][2])) { MP_STATE_VM(mp_optimise_value) = argv[a][2] & 0xf; @@ -314,6 +402,15 @@ MP_NOINLINE int main_(int argc, char **argv) { } else if (strcmp(arch, "xtensawin") == 0) { mp_dynamic_compiler.native_arch = MP_NATIVE_ARCH_XTENSAWIN; mp_dynamic_compiler.nlr_buf_num_regs = MICROPY_NLR_NUM_REGS_XTENSAWIN; + } else if (strcmp(arch, "rv32imc") == 0) { + mp_dynamic_compiler.native_arch = MP_NATIVE_ARCH_RV32IMC; + mp_dynamic_compiler.nlr_buf_num_regs = MICROPY_NLR_NUM_REGS_RV32I; + } else if (strcmp(arch, "rv64imc") == 0) { + mp_dynamic_compiler.native_arch = MP_NATIVE_ARCH_RV64IMC; + mp_dynamic_compiler.nlr_buf_num_regs = MICROPY_NLR_NUM_REGS_RV64I; + } else if (strcmp(arch, "debug") == 0) { + mp_dynamic_compiler.native_arch = MP_NATIVE_ARCH_DEBUG; + mp_dynamic_compiler.nlr_buf_num_regs = 0; } else if (strcmp(arch, "host") == 0) { #if defined(__i386__) || defined(_M_IX86) mp_dynamic_compiler.native_arch = MP_NATIVE_ARCH_X86; @@ -324,6 +421,9 @@ MP_NOINLINE int main_(int argc, char **argv) { #elif defined(__arm__) && !defined(__thumb2__) mp_dynamic_compiler.native_arch = MP_NATIVE_ARCH_ARMV6; mp_dynamic_compiler.nlr_buf_num_regs = MICROPY_NLR_NUM_REGS_ARM_THUMB_FP; + #elif defined(__riscv) && (__riscv_xlen == 64) + mp_dynamic_compiler.native_arch = MP_NATIVE_ARCH_RV64IMC; + mp_dynamic_compiler.nlr_buf_num_regs = MICROPY_NLR_NUM_REGS_RV64I; #else mp_printf(&mp_stderr_print, "unable to determine host architecture for -march=host\n"); exit(1); @@ -331,6 +431,8 @@ MP_NOINLINE int main_(int argc, char **argv) { } else { return usage(argv); } + } else if (strncmp(argv[a], "-march-flags=", sizeof("-march-flags=") - 1) == 0) { + arch_flags = argv[a] + sizeof("-march-flags=") - 1; } else if (strcmp(argv[a], "--") == 0) { option_parsing_active = false; } else { @@ -345,6 +447,35 @@ MP_NOINLINE int main_(int argc, char **argv) { } } + if (arch_flags && mp_dynamic_compiler.native_arch != MP_NATIVE_ARCH_NONE) { + bool processed = false; + #if MICROPY_EMIT_NATIVE && MICROPY_EMIT_RV32 + if (mp_dynamic_compiler.native_arch == MP_NATIVE_ARCH_RV32IMC) { + mp_dynamic_compiler.backend_options = (void *)&rv32_options; + unsigned long raw_flags = 0; + if (parse_integer(arch_flags, &raw_flags) || parse_rv32_flags_string(arch_flags, &raw_flags)) { + if ((raw_flags & ~((unsigned long)RV32_EXT_ALL)) == 0) { + rv32_options.allowed_extensions = (uint8_t)raw_flags; + processed = true; + } + } + } + #endif + if (!processed) { + mp_printf(&mp_stderr_print, "unrecognised arch flags\n"); + exit(1); + } + } + + #if MICROPY_EMIT_NATIVE + if ((MP_STATE_VM(default_emit_opt) == MP_EMIT_OPT_NATIVE_PYTHON + || MP_STATE_VM(default_emit_opt) == MP_EMIT_OPT_VIPER) + && mp_dynamic_compiler.native_arch == MP_NATIVE_ARCH_NONE) { + mp_printf(&mp_stderr_print, "arch not specified\n"); + exit(1); + } + #endif + if (input_file == NULL) { mp_printf(&mp_stderr_print, "no input file\n"); exit(1); @@ -352,19 +483,13 @@ MP_NOINLINE int main_(int argc, char **argv) { int ret = compile_and_save(input_file, output_file, source_file); - #if MICROPY_PY_MICROPYTHON_MEM_INFO - if (mp_verbose_flag) { - mp_micropython_mem_info(0, NULL); - } - #endif - mp_deinit(); return ret & 0xff; } int main(int argc, char **argv) { - mp_stack_ctrl_init(); + mp_cstack_init_with_sp_here(40000 * (sizeof(void *) / 4)); return main_(argc, argv); } diff --git a/mpy-cross/mpconfigport.h b/mpy-cross/mpconfigport.h index bdd10efdaea..3f8e54d878b 100644 --- a/mpy-cross/mpconfigport.h +++ b/mpy-cross/mpconfigport.h @@ -32,6 +32,7 @@ #define MICROPY_ALLOC_PATH_MAX (PATH_MAX) #define MICROPY_PERSISTENT_CODE_LOAD (0) +#define MICROPY_PERSISTENT_CODE_LOAD_NATIVE (0) #define MICROPY_PERSISTENT_CODE_SAVE (1) #ifndef MICROPY_PERSISTENT_CODE_SAVE_FILE @@ -50,11 +51,16 @@ #define MICROPY_EMIT_XTENSA (1) #define MICROPY_EMIT_INLINE_XTENSA (1) #define MICROPY_EMIT_XTENSAWIN (1) +#define MICROPY_EMIT_RV32 (1) +#define MICROPY_EMIT_INLINE_RV32 (1) +#define MICROPY_EMIT_NATIVE_DEBUG (1) +#define MICROPY_EMIT_NATIVE_DEBUG_PRINTER (&mp_stdout_print) #define MICROPY_DYNAMIC_COMPILER (1) #define MICROPY_COMP_CONST_FOLDING (1) #define MICROPY_COMP_MODULE_CONST (1) #define MICROPY_COMP_CONST (1) +#define MICROPY_COMP_CONST_FLOAT (1) #define MICROPY_COMP_DOUBLE_TUPLE_ASSIGN (1) #define MICROPY_COMP_TRIPLE_TUPLE_ASSIGN (1) #define MICROPY_COMP_RETURN_IF_EXPR (1) @@ -79,18 +85,24 @@ #define MICROPY_USE_INTERNAL_PRINTF (0) #define MICROPY_PY_FSTRINGS (1) +#define MICROPY_PY_TSTRINGS (1) #define MICROPY_PY_BUILTINS_STR_UNICODE (1) -#if !(defined(MICROPY_GCREGS_SETJMP) || defined(__x86_64__) || defined(__i386__) || defined(__thumb2__) || defined(__thumb__) || defined(__arm__)) -// Fall back to setjmp() implementation for discovery of GC pointers in registers. -#define MICROPY_GCREGS_SETJMP (1) +// Fall back to setjmp() implementation for discovery of GC pointers in registers +// if running on intel-based macOS, or on architectures for which there is no +// specialised GC pointer discovery mechanism. +#if (defined(__APPLE__) && defined(__MACH__) && (defined(__i386__) || defined(__x86_64__))) || \ + (!(defined(MICROPY_GCREGS_SETJMP) || defined(__x86_64__) || defined(__i386__) || \ + defined(__thumb2__) || defined(__thumb__) || defined(__arm__))) +#define MICROPY_GCREGS_SETJMP (1) #endif -#define MICROPY_PY___FILE__ (0) +#define MICROPY_MODULE___FILE__ (0) #define MICROPY_PY_ARRAY (0) #define MICROPY_PY_ATTRTUPLE (0) #define MICROPY_PY_COLLECTIONS (0) -#define MICROPY_PY_MATH (0) +#define MICROPY_PY_MATH (MICROPY_COMP_CONST_FLOAT) +#define MICROPY_PY_MATH_CONSTANTS (MICROPY_COMP_CONST_FLOAT) #define MICROPY_PY_CMATH (0) #define MICROPY_PY_GC (0) #define MICROPY_PY_IO (0) @@ -98,23 +110,6 @@ // type definitions for the specific machine -#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) -#include -typedef __int64 mp_int_t; -typedef unsigned __int64 mp_uint_t; -#elif defined(_MSC_VER) && defined(_WIN64) -typedef __int64 mp_int_t; -typedef unsigned __int64 mp_uint_t; -#else -// These are definitions for machines where sizeof(int) == sizeof(void*), -// regardless for actual size. -typedef int mp_int_t; // must be pointer size -typedef unsigned int mp_uint_t; // must be pointer size -#endif - // Cannot include , as it may lead to symbol name clashes #if _FILE_OFFSET_BITS == 64 && !defined(__LP64__) typedef long long mp_off_t; @@ -139,7 +134,7 @@ typedef long mp_off_t; #ifdef _MSC_VER #define MP_ENDIANNESS_LITTLE (1) -#define NORETURN __declspec(noreturn) +#define MP_NORETURN __declspec(noreturn) #define MP_NOINLINE __declspec(noinline) #define MP_ALWAYSINLINE __forceinline #define MP_LIKELY(x) (x) @@ -169,3 +164,5 @@ typedef int ssize_t; typedef mp_off_t off_t; #endif + +extern const struct _mp_print_t mp_stdout_print; diff --git a/mpy-cross/mpy_cross/__init__.py b/mpy-cross/mpy_cross/__init__.py index 5020033e8c8..6d7002a3b89 100644 --- a/mpy-cross/mpy_cross/__init__.py +++ b/mpy-cross/mpy_cross/__init__.py @@ -25,7 +25,6 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. -from __future__ import print_function import os import re import stat @@ -43,6 +42,8 @@ "NATIVE_ARCH_ARMV7EMDP": "armv7emdp", "NATIVE_ARCH_XTENSA": "xtensa", "NATIVE_ARCH_XTENSAWIN": "xtensawin", + "NATIVE_ARCH_RV32IMC": "rv32imc", + "NATIVE_ARCH_RV64IMC": "rv64imc", } globals().update(NATIVE_ARCHS) diff --git a/mpy-cross/mpy_cross/__main__.py b/mpy-cross/mpy_cross/__main__.py index 2b6b81c3333..fe78a9e077e 100644 --- a/mpy-cross/mpy_cross/__main__.py +++ b/mpy-cross/mpy_cross/__main__.py @@ -25,7 +25,6 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. -from __future__ import print_function import argparse import sys diff --git a/ports/analog/Makefile b/ports/analog/Makefile index c31bb6dea19..fd1c9b8f5c5 100644 --- a/ports/analog/Makefile +++ b/ports/analog/Makefile @@ -2,15 +2,17 @@ # # SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries # SPDX-FileCopyrightText: Copyright (c) 2024 Brandon Hurst, Analog Devices, Inc. +# SPDX-FileCopyrightText: Copyright (c) 2025 Peggy Zhu, Analog Devices, Inc. # # SPDX-License-Identifier: MIT +BOARD ?= apard32690 +CROSS_COMPILE = arm-none-eabi- + # Includes mpconfigboard.mk & mpconfigport.mk, # along with numerous other shared environment makefiles. include ../../py/circuitpy_mkenv.mk -CROSS_COMPILE = arm-none-eabi- - # MCU_SERIES e.g. "max32" # MCU_VARIANT e.g. "max32690" # defined in mpconfigboard.mk @@ -19,6 +21,7 @@ MCU_SERIES_UPPER := $(shell echo $(MCU_SERIES) | tr '[:lower:]' '[:upper:]') MCU_VARIANT_LOWER := $(shell echo $(MCU_VARIANT) | tr '[:upper:]' '[:lower:]') MCU_VARIANT_UPPER := $(shell echo $(MCU_VARIANT) | tr '[:lower:]' '[:upper:]') + # ******************************************************************************* #### MSDK INCLUDES #### # Necessary for msdk makefiles @@ -58,6 +61,7 @@ DIE_TYPE=me18 endif PERIPH_SRC = $(ADI_PERIPH)/Source +PERIPH_INC = $(ADI_PERIPH)/Include/$(MCU_VARIANT_UPPER) INC += -I. INC += -I../.. @@ -74,7 +78,7 @@ INC += \ -I$(TOP)/lib/cmsis/inc \ -I$(CMSIS_ROOT)/Include \ -I$(CMSIS_ROOT)/Device/Maxim/$(MCU_VARIANT_UPPER)/Include \ - -I$(ADI_PERIPH)/Include/$(MCU_VARIANT_UPPER) \ + -I$(PERIPH_INC) \ -I$(PERIPH_SRC)/SYS \ -I$(PERIPH_SRC)/CTB \ -I$(PERIPH_SRC)/DMA \ @@ -83,7 +87,10 @@ INC += \ -I$(PERIPH_SRC)/ICC \ -I$(PERIPH_SRC)/TMR \ -I$(PERIPH_SRC)/RTC \ - -I$(PERIPH_SRC)/UART + -I$(PERIPH_SRC)/UART \ + -I$(PERIPH_SRC)/TRNG \ + -I$(PERIPH_SRC)/I2C \ + -I$(PERIPH_SRC)/SPI INC += -I$(CMSIS_ROOT)/Device/Maxim/$(MCU_VARIANT_UPPER)/Source/GCC @@ -116,13 +123,22 @@ SRC_MAX32 += \ $(PERIPH_SRC)/TMR/tmr_$(DIE_TYPE).c \ $(PERIPH_SRC)/UART/uart_common.c \ $(PERIPH_SRC)/UART/uart_$(DIE_TYPE).c \ - $(PERIPH_SRC)/UART/uart_revb.c + $(PERIPH_SRC)/UART/uart_revb.c \ + $(PERIPH_SRC)/TRNG/trng_revb.c \ + $(PERIPH_SRC)/TRNG/trng_$(DIE_TYPE).c \ + $(PERIPH_SRC)/I2C/i2c_$(DIE_TYPE).c \ + $(PERIPH_SRC)/I2C/i2c_reva.c \ + $(PERIPH_SRC)/SPI/spi_$(DIE_TYPE).c \ + $(PERIPH_SRC)/SPI/spi_reva1.c SRC_C += $(SRC_MAX32) \ boards/$(BOARD)/board.c \ boards/$(BOARD)/pins.c \ peripherals/$(MCU_VARIANT_LOWER)/pins.c \ - peripherals/$(MCU_VARIANT_LOWER)/gpios.c + peripherals/$(MCU_VARIANT_LOWER)/gpios.c \ + peripherals/$(MCU_VARIANT_LOWER)/max32_uart.c \ + peripherals/$(MCU_VARIANT_LOWER)/max32_i2c.c \ + peripherals/$(MCU_VARIANT_LOWER)/max32_spi.c # ******************************************************************************* ### Compiler & Linker Flags ### @@ -138,8 +154,10 @@ LINKERFILE = linking/$(MCU_VARIANT_LOWER)_cktpy.ld LDFLAGS += -nostartfiles -specs=nano.specs endif -SRC_S += supervisor/cpu.s \ - $(STARTUPFILE) +SRC_S += $(STARTUPFILE) +SRC_S += shared/runtime/gchelper_thumb2.s + +SRC_C += shared/runtime/gchelper_native.c # Needed to compile some MAX32 headers CFLAGS += -D$(MCU_VARIANT_UPPER) \ @@ -228,19 +246,6 @@ endif # QSTR sources are provided for the initial build step, which generates # Python constants to represent C data which gets passed into the GC. -SRC_COMMON_HAL_EXPANDED = $(addprefix shared-bindings/, $(SRC_COMMON_HAL)) \ - $(addprefix shared-bindings/, $(SRC_BINDINGS_ENUMS)) \ - $(addprefix common-hal/, $(SRC_COMMON_HAL)) - -SRC_SHARED_MODULE_EXPANDED = $(addprefix shared-bindings/, $(SRC_SHARED_MODULE)) \ - $(addprefix shared-module/, $(SRC_SHARED_MODULE)) \ - $(addprefix shared-module/, $(SRC_SHARED_MODULE_INTERNAL)) - -# There are duplicates between SRC_COMMON_HAL_EXPANDED and SRC_SHARED_MODULE_EXPANDED, -# because a few modules have files both in common-hal/ and shared-module/. -# Doing a $(sort ...) removes duplicates as part of sorting. -SRC_COMMON_HAL_SHARED_MODULE_EXPANDED = $(sort $(SRC_COMMON_HAL_EXPANDED) $(SRC_SHARED_MODULE_EXPANDED)) - # OBJ includes OBJ += $(PY_O) $(SUPERVISOR_O) $(addprefix $(BUILD)/, $(SRC_C:.c=.o)) OBJ += $(addprefix $(BUILD)/, $(SRC_COMMON_HAL_SHARED_MODULE_EXPANDED:.c=.o)) @@ -275,11 +280,16 @@ flash-msdk: -f interface/cmsis-dap.cfg -f target/$(MCU_VARIANT_LOWER).cfg \ -c "program $(BUILD)/firmware.elf verify; init; reset; exit" +flash-openocd-jlink: + $(OPENOCD) -s $(OPENOCD_SCRIPTS) \ + -f interface/jlink.cfg -f target/$(MCU_VARIANT_LOWER).cfg \ + -c "program $(BUILD)/firmware.elf verify; init; reset; exit" + # flash target using JLink JLINK_DEVICE = $(MCU_VARIANT_LOWER) JLINKEXE ?= JLink.exe -JLINKEXE += -if SWD -device ${JLINK_DEVICE} -speed 10000 +JLINKEXE += -if SWD -device ${JLINK_DEVICE} -speed 4000 COMMAND_FILE := tools/flash_max32.jlink flash-jlink: $(BUILD)/firmware.bin @@ -289,7 +299,7 @@ $(BUILD)/firmware.elf: $(OBJ) $(STEPECHO) "LINK $@" $(Q)echo $^ > $(BUILD)/firmware.objs $(Q)$(CC) -o $@ $(LDFLAGS) @$(BUILD)/firmware.objs -Wl,--print-memory-usage -Wl,--start-group $(LIBS) -Wl,--end-group - $(Q)$(SIZE) $@ | $(PYTHON) $(TOP)/tools/build_memory_info.py $(LINKERFILE) $(BUILD) + $(Q)$(PYTHON) $(TOP)/tools/build_memory_info.py $@.map $(BUILD) --elf $@ $(BUILD)/firmware.hex: $(BUILD)/firmware.elf $(STEPECHO) "Create $@" diff --git a/ports/analog/background.c b/ports/analog/background.c index ffad007ffa5..ad840c6dcda 100644 --- a/ports/analog/background.c +++ b/ports/analog/background.c @@ -19,19 +19,13 @@ extern const mxc_gpio_cfg_t led_pin[]; extern const int num_leds; /** NOTE: ALL "ticks" refer to a 1/1024 s period */ -static int status_led_ticks = 0; +static int status_ticks = 0; // This function is where port-specific background // tasks should be performed // Execute port specific actions during background tick. Only if ticks are enabled. void port_background_tick(void) { - status_led_ticks++; - - // Set an LED approx. 1/s - if (status_led_ticks > 1024) { - MXC_GPIO_OutToggle(led_pin[2].port, led_pin[2].mask); - status_led_ticks = 0; - } + status_ticks++; } // Execute port specific actions during background tasks. This is before the diff --git a/ports/analog/boards/apard32690/mpconfigboard.mk b/ports/analog/boards/apard32690/mpconfigboard.mk index 7cc54ccfc6d..0e62f25f3f8 100644 --- a/ports/analog/boards/apard32690/mpconfigboard.mk +++ b/ports/analog/boards/apard32690/mpconfigboard.mk @@ -19,7 +19,6 @@ USB_VID=0x0456 USB_PID=0x003C USB_MANUFACTURER="Analog Devices, Inc." USB_PRODUCT="MAX32690 APARD" -USB_HIGHSPEED=1 # NOTE: MAX32 devices do not support IN/OUT pairs on the same EP USB_NUM_ENDPOINT_PAIRS=12 diff --git a/ports/analog/boards/max32690evkit/mpconfigboard.mk b/ports/analog/boards/max32690evkit/mpconfigboard.mk index 61413216d81..a97bc9ddacd 100644 --- a/ports/analog/boards/max32690evkit/mpconfigboard.mk +++ b/ports/analog/boards/max32690evkit/mpconfigboard.mk @@ -19,7 +19,6 @@ USB_VID=0x0456 USB_PID=0x003D USB_MANUFACTURER="Analog Devices, Inc." USB_PRODUCT="MAX32690 EvKit" -USB_HIGHSPEED=1 # NOTE: MAX32 devices do not support IN/OUT pairs on the same EP USB_NUM_ENDPOINT_PAIRS=12 diff --git a/ports/analog/common-hal/busio/I2C.c b/ports/analog/common-hal/busio/I2C.c new file mode 100644 index 00000000000..2e9a43dacb6 --- /dev/null +++ b/ports/analog/common-hal/busio/I2C.c @@ -0,0 +1,250 @@ +/* + * This file is part of Adafruit for EFR32 project + * + * The MIT License (MIT) + * + * Copyright 2023 Silicon Laboratories Inc. www.silabs.com + * + * 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/busio/I2C.h" +#include "py/mperrno.h" +#include "py/runtime.h" +#include "shared-bindings/microcontroller/__init__.h" +#include "shared-bindings/microcontroller/Pin.h" + +#include "max32_port.h" + +#define I2C_PRIORITY 1 + +// Set each bit to indicate an active I2c +static uint8_t i2c_active = 0; +static volatile int i2c_err; + +// I2C struct for configuring GPIO pins +extern const mxc_gpio_cfg_t i2c_maps[NUM_I2C]; + +// Construct I2C protocol, this function init i2c peripheral +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) { + // Check for NULL Pointers && valid I2C settings + assert(self); + + /* NOTE: The validate_obj_is_free_pin() calls in shared-bindings/busio/I2C.c + will ensure that scl and sda are both pins and cannot be null + ref: https://github.com/adafruit/circuitpython/pull/10413 + */ + + // Assign I2C ID based on pins + int i2c_id = pinsToI2c(sda, scl); + if (i2c_id == -1) { + return; + } else { + self->i2c_id = i2c_id; + self->i2c_regs = MXC_I2C_GET_I2C(i2c_id); + } + + // Check for valid I2C controller + assert((self->i2c_id >= 0) && (self->i2c_id < NUM_I2C)); + assert(!(i2c_active & (1 << self->i2c_id))); + + // Attach I2C pins + self->sda = sda; + self->scl = scl; + common_hal_mcu_pin_claim(self->sda); + common_hal_mcu_pin_claim(self->scl); + + // Clear all flags + MXC_I2C_ClearFlags(self->i2c_regs, 0xFFFFFF, 0xFFFFFF); + + // Init as master, no slave address + MXC_I2C_Shutdown(self->i2c_regs); + MXC_I2C_Init(self->i2c_regs, 1, 0); + + // Set frequency arg (CircuitPython shared-bindings validate) + MXC_I2C_SetFrequency(self->i2c_regs, frequency); + + // Indicate to this module that the I2C is active + i2c_active |= (1 << self->i2c_id); + + // Set the timeout to a default value + if (timeout > 100) { + self->timeout = 1; + } else { + self->timeout = timeout; + } + + return; +} + +// Check I2C status, deinited or not +bool common_hal_busio_i2c_deinited(busio_i2c_obj_t *self) { + return self->sda == NULL; +} + +// Deinit i2c obj, reset I2C pin +void common_hal_busio_i2c_deinit(busio_i2c_obj_t *self) { + MXC_I2C_Shutdown(self->i2c_regs); + + common_hal_reset_pin(self->sda); + common_hal_reset_pin(self->scl); + + self->sda = NULL; + self->scl = NULL; +} + +// Probe device in I2C bus +bool common_hal_busio_i2c_probe(busio_i2c_obj_t *self, uint8_t addr) { + uint32_t int_fl0; + bool ret = 0; + + // If not in Master mode, error out (can happen in some error conditions) + if (!(self->i2c_regs->ctrl & MXC_F_I2C_CTRL_MST_MODE)) { + return false; + } + + // Clear FIFOs & all interrupt flags + MXC_I2C_ClearRXFIFO(self->i2c_regs); + MXC_I2C_ClearTXFIFO(self->i2c_regs); + MXC_I2C_ClearFlags(self->i2c_regs, 0xFFFFFF, 0xFFFFFF); + + // Pre-load target address into transmit FIFO + addr = (addr << 1); + self->i2c_regs->fifo = addr; + + // Set start bit & wait for it to clear + MXC_I2C_Start(self->i2c_regs); + + // wait for ACK/NACK + while (!(self->i2c_regs->intfl0 & MXC_F_I2C_INTFL0_ADDR_ACK) && + !(self->i2c_regs->intfl0 & MXC_F_I2C_INTFL0_ADDR_NACK_ERR)) { + } + + // Save interrupt flags for ACK/NACK checking + int_fl0 = self->i2c_regs->intfl0; + + // Set / Wait for stop + MXC_I2C_Stop(self->i2c_regs); + + // Wait for controller not busy, then clear flags + while (self->i2c_regs->status & MXC_F_I2C_STATUS_BUSY) { + ; + } + MXC_I2C_ClearFlags(self->i2c_regs, 0xFFFFFF, 0xFFFFFF); + + if (int_fl0 & MXC_F_I2C_INTFL0_ADDR_ACK) { + ret = true; + } else { + ret = false; + } + return ret; +} + +// Lock I2C bus +bool common_hal_busio_i2c_try_lock(busio_i2c_obj_t *self) { + + if (self->i2c_regs->status & MXC_F_I2C_STATUS_BUSY) { + return false; + } else { + self->has_lock = true; + return true; + } +} + +// Check I2C lock status +bool common_hal_busio_i2c_has_lock(busio_i2c_obj_t *self) { + return self->has_lock; +} + +// Unlock I2C bus +void common_hal_busio_i2c_unlock(busio_i2c_obj_t *self) { + self->has_lock = false; +} + +// Write data to the device selected by address +mp_negative_errno_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, + const uint8_t *data, size_t len) { + + int ret; + mxc_i2c_req_t wr_req = { + .addr = addr, + .i2c = self->i2c_regs, + .tx_buf = (uint8_t *)data, + .tx_len = len, + .rx_buf = NULL, + .rx_len = 0, + .callback = NULL + }; + ret = MXC_I2C_MasterTransaction(&wr_req); + if (ret) { + return -MP_EIO; + } + + return 0; +} + +// Read into buffer from the device selected by address +mp_negative_errno_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, + uint16_t addr, + uint8_t *data, size_t len) { + + int ret; + mxc_i2c_req_t rd_req = { + .addr = addr, + .i2c = self->i2c_regs, + .tx_buf = NULL, + .tx_len = 0, + .rx_buf = data, + .rx_len = len, + .callback = NULL + }; + ret = MXC_I2C_MasterTransaction(&rd_req); + if (ret) { + // Return I/O error + return -MP_EIO; + } + + return 0; +} + +// Write the bytes from out_data to the device selected by address +mp_negative_errno_t common_hal_busio_i2c_write_read(busio_i2c_obj_t *self, uint16_t addr, + uint8_t *out_data, size_t out_len, + uint8_t *in_data, size_t in_len) { + + int ret; + mxc_i2c_req_t wr_rd_req = { + .addr = addr, + .i2c = self->i2c_regs, + .tx_buf = out_data, + .tx_len = out_len, + .rx_buf = in_data, + .rx_len = in_len, + .callback = NULL + }; + ret = MXC_I2C_MasterTransaction(&wr_rd_req); + if (ret) { + return -MP_EIO; + } + + return 0; +} diff --git a/ports/analog/common-hal/busio/I2C.h b/ports/analog/common-hal/busio/I2C.h new file mode 100644 index 00000000000..55c230ee2f9 --- /dev/null +++ b/ports/analog/common-hal/busio/I2C.h @@ -0,0 +1,28 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Brandon Hurst, Analog Devices, Inc. +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "common-hal/microcontroller/Pin.h" +#include "py/obj.h" + +// HAL-specific +#include "i2c.h" +#include "gpio.h" + +// Define a struct for what BUSIO.I2C should carry +typedef struct { + mp_obj_base_t base; + + int i2c_id; + mxc_i2c_regs_t *i2c_regs; + const mcu_pin_obj_t *scl; + const mcu_pin_obj_t *sda; + const int frequency; + + uint32_t timeout; + bool has_lock; +} busio_i2c_obj_t; diff --git a/ports/analog/common-hal/busio/SPI.c b/ports/analog/common-hal/busio/SPI.c new file mode 100644 index 00000000000..e74df040f48 --- /dev/null +++ b/ports/analog/common-hal/busio/SPI.c @@ -0,0 +1,335 @@ +/* + * This file is part of Adafruit for EFR32 project + * + * The MIT License (MIT) + * + * Copyright 2023 Silicon Laboratories Inc. www.silabs.com + * + * 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/busio/SPI.h" +#include "py/mperrno.h" +#include "py/runtime.h" +#include "shared-bindings/microcontroller/__init__.h" +#include "supervisor/board.h" +#include "shared-bindings/microcontroller/Pin.h" + +#include "max32_port.h" +#include "spi_reva1.h" + +// Note that any bugs introduced in this file can cause crashes +// at startupfor chips using external SPI flash. + +#define SPI_PRIORITY 1 + +typedef enum { + SPI_FREE = 0, + SPI_BUSY, +} spi_status_t; + +// Set each bit to indicate an active SPI +static uint8_t spi_active = 0; +static spi_status_t spi_status[NUM_SPI]; +static volatile int spi_err; + +// Construct SPI protocol, this function init SPI peripheral +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, + bool half_duplex) { + int err = 0; + + // Check for NULL Pointer + assert(self); + + // Ensure the object starts in its deinit state. + common_hal_busio_spi_mark_deinit(self); + + // Assign SPI ID based on pins + int spi_id = pinsToSpi(mosi, miso, sck); + if (spi_id == -1) { + return; + } else { + self->spi_id = spi_id; + self->spi_regs = MXC_SPI_GET_SPI(spi_id); + } + + // Other pins default to true + mxc_spi_pins_t spi_pins = { + .clock = TRUE, + .mosi = TRUE, + .miso = TRUE, + .ss0 = FALSE, + .ss1 = FALSE, + .ss2 = FALSE, + .vddioh = true, + .drvstr = MXC_GPIO_DRVSTR_0 + }; + + assert((self->spi_id >= 0) && (self->spi_id < NUM_SPI)); + + // Init SPI controller + if ((mosi != NULL) && (miso != NULL) && (sck != NULL)) { + // spi, mastermode, quadModeUsed, numSubs, ssPolarity, frequency + err = MXC_SPI_Init(self->spi_regs, MXC_SPI_TYPE_CONTROLLER, MXC_SPI_INTERFACE_STANDARD, + 1, 0x01, 1000000, spi_pins); + MXC_GPIO_SetVSSEL(MXC_GPIO_GET_GPIO(sck->port), MXC_GPIO_VSSEL_VDDIOH, (sck->mask | miso->mask | mosi->mask | MXC_GPIO_PIN_0)); + if (err) { + // NOTE: Reuse existing messages from locales/circuitpython.pot to save space + mp_raise_RuntimeError_varg(MP_ERROR_TEXT("%q init failed"), MP_QSTR_SPI); + } + } else { + mp_raise_NotImplementedError(MP_ERROR_TEXT("SPI needs MOSI, MISO, and SCK")); + } + + // Attach SPI pins + self->mosi = mosi; + self->miso = miso; + self->sck = sck; + common_hal_mcu_pin_claim(self->mosi); + common_hal_mcu_pin_claim(self->miso); + common_hal_mcu_pin_claim(self->sck); + + // Indicate to this module that the SPI is active + spi_active |= (1 << self->spi_id); + + return; +} + +// Check SPI status, deinited or not +bool common_hal_busio_spi_deinited(busio_spi_obj_t *self) { + return self->sck == NULL; +} + +void common_hal_busio_spi_mark_deinit(busio_spi_obj_t *self) { + self->sck = NULL; +} + +// Deinit SPI obj +void common_hal_busio_spi_deinit(busio_spi_obj_t *self) { + + MXC_SPI_Shutdown(self->spi_regs); + common_hal_reset_pin(self->mosi); + common_hal_reset_pin(self->miso); + common_hal_reset_pin(self->sck); + common_hal_reset_pin(self->nss); + + self->mosi = NULL; + self->miso = NULL; + self->nss = NULL; + + common_hal_busio_spi_mark_deinit(self); +} + +// Configures the SPI bus. The SPI object must be locked. +bool common_hal_busio_spi_configure(busio_spi_obj_t *self, + uint32_t baudrate, + uint8_t polarity, + uint8_t phase, + uint8_t bits) { + + mxc_spi_clkmode_t clk_mode; + int ret; + + self->polarity = polarity; + self->phase = phase; + self->bits = bits; + + switch ((polarity << 1) | (phase)) { + case 0b00: + clk_mode = MXC_SPI_CLKMODE_0; + break; + case 0b01: + clk_mode = MXC_SPI_CLKMODE_1; + break; + case 0b10: + clk_mode = MXC_SPI_CLKMODE_2; + break; + case 0b11: + clk_mode = MXC_SPI_CLKMODE_3; + break; + default: + // should not be reachable; validated in shared-bindings/busio/SPI.c + return false; + } + + ret = MXC_SPI_SetFrequency(self->spi_regs, baudrate); + if (ret) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("%q out of range"), MP_QSTR_baudrate); + return false; + } + + // MXC_SPI_SetFrequency() floors the clock divisor, so the actual rate can be + // HIGHER than requested. Treat baudrate as a ceiling: if the hardware + // overshoots, bisect downward on the requested target for the highest rate + // that does not exceed baudrate. MXC_SPI_GetFrequency() reports the actual + // configured rate, so we don't depend on the divisor internals. + uint32_t actual = MXC_SPI_GetFrequency(self->spi_regs); + if (actual > baudrate) { + uint32_t lo = 1; // f(lo) <= baudrate + uint32_t hi = baudrate; // f(hi) > baudrate (just measured) + while (hi - lo > 1) { + uint32_t mid = lo + (hi - lo) / 2; + MXC_SPI_SetFrequency(self->spi_regs, mid); + if (MXC_SPI_GetFrequency(self->spi_regs) <= baudrate) { + lo = mid; + } else { + hi = mid; + } + } + MXC_SPI_SetFrequency(self->spi_regs, lo); + actual = MXC_SPI_GetFrequency(self->spi_regs); + } + self->baudrate = actual; + ret = MXC_SPI_SetDataSize(self->spi_regs, bits); + if (ret == E_BAD_PARAM) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("%q out of range"), MP_QSTR_bits); + return false; + } else if (ret == E_BAD_STATE) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Invalid state")); + } + ret = MXC_SPI_SetMode(self->spi_regs, clk_mode); + if (ret) { + mp_raise_ValueError(MP_ERROR_TEXT("Failed to set SPI Clock Mode")); + return false; + } + return true; +} + +// Lock SPI bus +bool common_hal_busio_spi_try_lock(busio_spi_obj_t *self) { + if (spi_status[self->spi_id] != SPI_BUSY) { + self->has_lock = true; + return true; + } else { + return false; + } +} + +// Check SPI lock status +bool common_hal_busio_spi_has_lock(busio_spi_obj_t *self) { + return self->has_lock; +} + +// Unlock SPI bus +void common_hal_busio_spi_unlock(busio_spi_obj_t *self) { + self->has_lock = false; +} + +// Write the data contained in buffer +bool common_hal_busio_spi_write(busio_spi_obj_t *self, + const uint8_t *data, + size_t len) { + int ret = 0; + + mxc_spi_req_t wr_req = { + .spi = self->spi_regs, + .ssIdx = 0, + .txCnt = 0, + .rxCnt = 0, + .txData = (uint8_t *)data, + .txLen = len, + .rxData = NULL, + .rxLen = 0, + .ssDeassert = 1, + .completeCB = NULL, + .txDummyValue = 0xFF, + }; + ret = MXC_SPI_MasterTransaction(&wr_req); + if (ret) { + return false; + } else { + return true; + } +} + +// Read data into buffer +bool common_hal_busio_spi_read(busio_spi_obj_t *self, + uint8_t *data, size_t len, + uint8_t write_value) { + + int ret = 0; + + mxc_spi_req_t rd_req = { + .spi = self->spi_regs, + .ssIdx = 0, + .txCnt = 0, + .rxCnt = 0, + .txData = NULL, + .txLen = len, + .rxData = data, + .rxLen = len, + .ssDeassert = 1, + .completeCB = NULL, + .txDummyValue = write_value, + }; + ret = MXC_SPI_MasterTransaction(&rd_req); + if (ret) { + return false; + } else { + return true; + } +} + +// Write out the data in data_out +// while simultaneously reading data into data_in +bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, + const uint8_t *data_out, + uint8_t *data_in, + size_t len) { + + int ret = 0; + + mxc_spi_req_t rd_req = { + .spi = self->spi_regs, + .ssIdx = 0, + .txCnt = 0, + .rxCnt = 0, + .txData = (uint8_t *)data_out, + .txLen = len, + .rxData = data_in, + .rxLen = len, + .ssDeassert = 1, + .completeCB = NULL, + .txDummyValue = 0xFF, + }; + ret = MXC_SPI_MasterTransaction(&rd_req); + if (ret) { + return false; + } else { + return true; + } +} + +// Get SPI baudrate +uint32_t common_hal_busio_spi_get_frequency(busio_spi_obj_t *self) { + return self->baudrate; +} + +// Get SPI phase +uint8_t common_hal_busio_spi_get_phase(busio_spi_obj_t *self) { + return self->phase; +} + +// Get SPI polarity +uint8_t common_hal_busio_spi_get_polarity(busio_spi_obj_t *self) { + return self->polarity; +} diff --git a/ports/analog/common-hal/busio/SPI.h b/ports/analog/common-hal/busio/SPI.h new file mode 100644 index 00000000000..d10601876fb --- /dev/null +++ b/ports/analog/common-hal/busio/SPI.h @@ -0,0 +1,41 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Brandon Hurst, Analog Devices, Inc. +// +// SPDX-License-Identifier: MIT + +#ifndef MICROPY_INCLUDED_MAX32_COMMON_HAL_BUSIO_SPI_H +#define MICROPY_INCLUDED_MAX32_COMMON_HAL_BUSIO_SPI_H + +#include "common-hal/microcontroller/Pin.h" +#include "py/obj.h" + +// HAL-specific +#include "spi.h" + +// Define a struct for what BUSIO.SPI should carry +typedef struct { + mp_obj_base_t base; + + // Spi regs & pins + int spi_id; + mxc_spi_regs_t *spi_regs; + const mcu_pin_obj_t *sck; + const mcu_pin_obj_t *mosi; + const mcu_pin_obj_t *miso; + const mcu_pin_obj_t *nss; + + // Configuration + uint32_t baudrate; + uint16_t prescaler; + uint8_t polarity; + uint8_t phase; + uint8_t bits; + + // Synch data + bool has_lock; +} busio_spi_obj_t; + +void spi_reset(void); + +#endif // MICROPY_INCLUDED_MAX32_COMMON_HAL_BUSIO_SPI_H diff --git a/ports/analog/common-hal/busio/UART.c b/ports/analog/common-hal/busio/UART.c new file mode 100644 index 00000000000..ced5ad3d518 --- /dev/null +++ b/ports/analog/common-hal/busio/UART.c @@ -0,0 +1,449 @@ +/* + * This file is part of Adafruit for EFR32 project + * + * The MIT License (MIT) + * + * Copyright 2023 Silicon Laboratories Inc. www.silabs.com + * + * 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_BUSIO_UART + +#include "mpconfigport.h" +#include "supervisor/shared/tick.h" + +#include "shared-bindings/microcontroller/__init__.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/busio/UART.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared/readline/readline.h" +#include "shared/runtime/interrupt_char.h" + +#include "py/gc.h" +#include "py/ringbuf.h" +#include "py/mperrno.h" +#include "py/mpprint.h" +#include "py/runtime.h" + +#include "max32_port.h" +#include "UART.h" +#include "nvic_table.h" + +// UART IRQ Priority +#define UART_PRIORITY 1 + +typedef enum { + UART_9600 = 9600, + UART_14400 = 14400, + UART_19200 = 19200, + UART_38400 = 38400, + UART_57600 = 57600, + UART_115200 = 115200, + UART_230400 = 230400, + UART_460800 = 460800, + UART_921600 = 921600, +} uart_valid_baudrates; + +typedef enum { + UART_FREE = 0, + UART_BUSY, +} uart_status_t; + +static uint32_t timeout_ms = 0; + +// Set each bit to indicate an active UART +// will be checked by ISR Handler for which ones to call +static uint8_t uarts_active = 0; +static uart_status_t uart_status[NUM_UARTS]; +static volatile int uart_err; +static busio_uart_obj_t *context; + +static bool isValidBaudrate(uint32_t baudrate) { + switch (baudrate) { + case UART_9600: + return true; + break; + case UART_14400: + return true; + break; + case UART_19200: + return true; + break; + case UART_38400: + return true; + break; + case UART_57600: + return true; + break; + case UART_115200: + return true; + break; + case UART_230400: + return true; + break; + case UART_460800: + return true; + break; + case UART_921600: + return true; + break; + default: + return false; + break; + } +} + +static mxc_uart_parity_t convertParity(busio_uart_parity_t busio_parity) { + switch (busio_parity) { + case BUSIO_UART_PARITY_NONE: + return MXC_UART_PARITY_DISABLE; + case BUSIO_UART_PARITY_EVEN: + return MXC_UART_PARITY_EVEN_0; + case BUSIO_UART_PARITY_ODD: + return MXC_UART_PARITY_ODD_0; + default: + // not reachable due to validation in shared-bindings/busio/SPI.c + return MXC_UART_PARITY_DISABLE; + } +} + +void uart_isr(void) { + for (int i = 0; i < NUM_UARTS; i++) { + if (uarts_active & (1 << i)) { + MXC_UART_AsyncHandler(MXC_UART_GET_UART(i)); + } + } +} + +// Callback gets called when AsyncRequest is COMPLETE +// (e.g. txLen == txCnt) +static volatile void uartCallback(mxc_uart_req_t *req, int error) { + uart_status[MXC_UART_GET_IDX(req->uart)] = UART_FREE; + uart_err = error; + + MXC_SYS_Crit_Enter(); + ringbuf_put_n(&context->ringbuf, req->rxData, req->rxLen); + MXC_SYS_Crit_Exit(); +} + +// Construct an underlying UART object. +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) { + int err, temp; + + // Check for NULL Pointers && valid UART settings + assert(self); + + // Assign UART ID based on pins + temp = pinsToUart(tx, rx); + if (temp == -1) { + // Error will be indicated by pinsToUart(tx, rx) function + return; + } else { + self->uart_id = temp; + self->uart_regs = MXC_UART_GET_UART(temp); + } + assert((self->uart_id >= 0) && (self->uart_id < NUM_UARTS)); + + // Check for size of ringbuffer, desire powers of 2 + // At least use 1 byte if no size is given + assert((receiver_buffer_size & (receiver_buffer_size - 1)) == 0); + if (receiver_buffer_size == 0) { + receiver_buffer_size += 1; + } + + // Indicate RS485 not implemented + if ((rs485_dir != NULL) || (rs485_invert)) { + mp_raise_NotImplementedError(MP_ERROR_TEXT("RS485")); + } + + if ((rx != NULL) && (tx != NULL)) { + err = MXC_UART_Init(self->uart_regs, baudrate, MXC_UART_IBRO_CLK); + if (err != E_NO_ERROR) { + mp_raise_RuntimeError_varg(MP_ERROR_TEXT("%q init failed"), MP_QSTR_UART); + } + + // attach & configure pins + self->tx_pin = tx; + self->rx_pin = rx; + common_hal_mcu_pin_claim(self->tx_pin); + common_hal_mcu_pin_claim(self->rx_pin); + } else { + mp_raise_NotImplementedError(MP_ERROR_TEXT("UART needs TX & RX")); + } + + if ((cts) && (rts)) { + MXC_UART_SetFlowCtrl(self->uart_regs, MXC_UART_FLOW_EN, 8); + self->cts_pin = cts; + self->rts_pin = rts; + common_hal_mcu_pin_claim(self->cts_pin); + common_hal_mcu_pin_claim(self->rts_pin); + } else if (cts || rts) { + mp_raise_ValueError(MP_ERROR_TEXT("Both RX and TX required for flow control")); + } + + // Set stop bits & data size + assert((stop == 1) || (stop == 2)); + mp_arg_validate_int(bits, 8, MP_QSTR_bits); + MXC_UART_SetDataSize(self->uart_regs, bits); + MXC_UART_SetStopBits(self->uart_regs, stop); + + // Set parity + MXC_UART_SetParity(self->uart_regs, convertParity(parity)); + + // attach UART parameters + self->stop_bits = stop; // must be 1 or 2 + self->bits = bits; + self->parity = parity; + self->baudrate = baudrate; + self->error = E_NO_ERROR; + + // Indicate to this module that the UART is active + uarts_active |= (1 << self->uart_id); + + // Set the timeout to a default value + if (((timeout < 0.0) || (timeout > 100.0))) { + self->timeout = 1.0; + } else { + self->timeout = timeout; + } + + // Initialize ringbuffer + if (receiver_buffer == NULL) { + if (!ringbuf_alloc(&self->ringbuf, receiver_buffer_size)) { + m_malloc_fail(receiver_buffer_size); + mp_raise_RuntimeError_varg(MP_ERROR_TEXT("Failed to allocate %q buffer"), + MP_QSTR_UART); + } + } else { + if (!(ringbuf_init(&self->ringbuf, receiver_buffer, receiver_buffer_size))) { + mp_raise_RuntimeError_varg(MP_ERROR_TEXT("Failed to allocate %q buffer"), + MP_QSTR_UART); + } + } + + context = self; + + // Setup UART interrupt + NVIC_ClearPendingIRQ(MXC_UART_GET_IRQ(self->uart_id)); + NVIC_DisableIRQ(MXC_UART_GET_IRQ(self->uart_id)); + NVIC_SetPriority(MXC_UART_GET_IRQ(self->uart_id), UART_PRIORITY); + NVIC_SetVector(MXC_UART_GET_IRQ(self->uart_id), (uint32_t)uart_isr); + + NVIC_EnableIRQ(MXC_UART_GET_IRQ(self->uart_id)); + + return; +} + +void common_hal_busio_uart_deinit(busio_uart_obj_t *self) { + assert(self); + + if (!common_hal_busio_uart_deinited(self)) { + // First disable the ISR to avoid pre-emption + NVIC_DisableIRQ(MXC_UART_GET_IRQ(self->uart_id)); + + // Shutdown the UART Controller + MXC_UART_Shutdown(self->uart_regs); + self->error = E_UNINITIALIZED; + + assert(self->rx_pin && self->tx_pin); + reset_pin_number(self->rx_pin->port, self->rx_pin->mask); + reset_pin_number(self->tx_pin->port, self->tx_pin->mask); + + if (self->cts_pin && self->rts_pin) { + reset_pin_number(self->cts_pin->port, self->cts_pin->mask); + reset_pin_number(self->rts_pin->port, self->rts_pin->mask); + } + + self->tx_pin = NULL; + self->rx_pin = NULL; + self->cts_pin = NULL; + self->rts_pin = NULL; + + ringbuf_deinit(&self->ringbuf); + + // Indicate to this module that the UART is not active + uarts_active &= ~(1 << self->uart_id); + } +} + +bool common_hal_busio_uart_deinited(busio_uart_obj_t *self) { + if (uarts_active & (1 << self->uart_id)) { + return false; + } else { + return true; + }; +} + +// Read characters. len is in characters. +size_t common_hal_busio_uart_read(busio_uart_obj_t *self, + uint8_t *data, size_t len, int *errcode) { + int err; + uint32_t start_time = 0; + static size_t bytes_remaining; + + // Setup globals & status tracking + uart_err = E_NO_ERROR; + uarts_active |= (1 << self->uart_id); + uart_status[self->uart_id] = UART_BUSY; + bytes_remaining = len; + + mxc_uart_req_t uart_rd_req; + uart_rd_req.rxCnt = 0; + uart_rd_req.txCnt = 0; + uart_rd_req.rxData = data; + uart_rd_req.txData = NULL; + uart_rd_req.rxLen = bytes_remaining; + uart_rd_req.txLen = 0; + uart_rd_req.uart = self->uart_regs; + uart_rd_req.callback = (void *)uartCallback; + + // Initiate the read transaction + start_time = supervisor_ticks_ms64(); + err = MXC_UART_TransactionAsync(&uart_rd_req); + if (err != E_NO_ERROR) { + *errcode = err; + MXC_UART_AbortAsync(self->uart_regs); + NVIC_DisableIRQ(MXC_UART_GET_IRQ(self->uart_id)); + mp_raise_RuntimeError_varg(MP_ERROR_TEXT("UART read error")); + } + + // Wait for transaction completion or timeout + while ((uart_status[self->uart_id] != UART_FREE) && + (supervisor_ticks_ms64() - start_time < (self->timeout * 1000))) { + } + + // If the timeout gets hit, abort and error out + if (uart_status[self->uart_id] != UART_FREE) { + MXC_UART_AbortAsync(self->uart_regs); + NVIC_DisableIRQ(MXC_UART_GET_IRQ(self->uart_id)); + mp_raise_RuntimeError(MP_ERROR_TEXT("UART transaction timeout")); + } + // Check for errors from the callback + else if (uart_err != E_NO_ERROR) { + mp_raise_RuntimeError(MP_ERROR_TEXT("UART read error")); + MXC_UART_AbortAsync(self->uart_regs); + } + + // Copy the data from the ringbuf (or return error) + MXC_SYS_Crit_Enter(); + err = ringbuf_get_n(&context->ringbuf, data, len); + MXC_SYS_Crit_Exit(); + + return err; +} + +// Write characters. len is in characters NOT bytes! +// This function blocks until the timeout finishes +size_t common_hal_busio_uart_write(busio_uart_obj_t *self, + const uint8_t *data, size_t len, int *errcode) { + int err; + static size_t bytes_remaining; + + // Setup globals & status tracking + uart_err = E_NO_ERROR; + uarts_active |= (1 << self->uart_id); + uart_status[self->uart_id] = UART_BUSY; + bytes_remaining = len; + + mxc_uart_req_t uart_wr_req = {}; + + // Setup transaction + uart_wr_req.rxCnt = 0; + uart_wr_req.txCnt = 0; + uart_wr_req.rxData = NULL; + uart_wr_req.txData = data; + uart_wr_req.txLen = bytes_remaining; + uart_wr_req.rxLen = 0; + uart_wr_req.uart = self->uart_regs; + uart_wr_req.callback = (void *)uartCallback; + + // Start the transaction + err = MXC_UART_TransactionAsync(&uart_wr_req); + if (err != E_NO_ERROR) { + *errcode = err; + MXC_UART_AbortAsync(self->uart_regs); + NVIC_DisableIRQ(MXC_UART_GET_IRQ(self->uart_id)); + mp_raise_ValueError(MP_ERROR_TEXT("All UART peripherals are in use")); + } + + // Wait for transaction completion + while (uart_status[self->uart_id] != UART_FREE) { + // Call the handler and abort if errors + uart_err = MXC_UART_AsyncHandler(self->uart_regs); + if (uart_err != E_NO_ERROR) { + MXC_UART_AbortAsync(self->uart_regs); + } + } + // Check for errors from the callback + if (uart_err != E_NO_ERROR) { + MXC_UART_AbortAsync(self->uart_regs); + } + + return len; +} + +uint32_t common_hal_busio_uart_get_baudrate(busio_uart_obj_t *self) { + return self->baudrate; +} + +// Validate baudrate +void common_hal_busio_uart_set_baudrate(busio_uart_obj_t *self, uint32_t baudrate) { + if (isValidBaudrate(baudrate)) { + self->baudrate = baudrate; + } else { + mp_raise_ValueError_varg(MP_ERROR_TEXT("Invalid %q"), MP_QSTR_baudrate); + } +} + +mp_float_t common_hal_busio_uart_get_timeout(busio_uart_obj_t *self) { + return self->timeout; +} + +void common_hal_busio_uart_set_timeout(busio_uart_obj_t *self, mp_float_t timeout) { + if (timeout > 100.0) { + mp_raise_ValueError(MP_ERROR_TEXT("Timeout must be < 100 seconds")); + } + + timeout_ms = 1000 * (uint32_t)timeout; + self->timeout = (uint32_t)timeout; + + return; +} + +uint32_t common_hal_busio_uart_rx_characters_available(busio_uart_obj_t *self) { + return ringbuf_num_filled(&self->ringbuf); +} + +void common_hal_busio_uart_clear_rx_buffer(busio_uart_obj_t *self) { + MXC_UART_ClearRXFIFO(self->uart_regs); + ringbuf_clear(&self->ringbuf); +} + +bool common_hal_busio_uart_ready_to_tx(busio_uart_obj_t *self) { + return !(MXC_UART_GetStatus(self->uart_regs) & (MXC_F_UART_STATUS_TX_BUSY)); +} + +#endif // CIRCUITPY_BUSIO_UART diff --git a/ports/analog/common-hal/busio/UART.h b/ports/analog/common-hal/busio/UART.h new file mode 100644 index 00000000000..51ec83a007f --- /dev/null +++ b/ports/analog/common-hal/busio/UART.h @@ -0,0 +1,39 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Brandon Hurst, Analog Devices, Inc. +// +// SPDX-License-Identifier: MIT + +#ifndef MICROPY_INCLUDED_MAX32_COMMON_HAL_BUSIO_UART_H +#define MICROPY_INCLUDED_MAX32_COMMON_HAL_BUSIO_UART_H + +#include "common-hal/microcontroller/Pin.h" +#include "py/obj.h" +#include "py/ringbuf.h" + +#include "max32_port.h" + +// Define a struct for what BUSIO.UART should contain +typedef struct { + mp_obj_base_t base; + int error; + float timeout; + + int uart_id; + int uart_map; + mxc_uart_regs_t *uart_regs; + ringbuf_t ringbuf; + bool parity; + uint8_t bits; + uint8_t stop_bits; + uint32_t baudrate; + + 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; +} busio_uart_obj_t; + +void uart_reset(void); + +#endif // MICROPY_INCLUDED_MAX32_COMMON_HAL_BUSIO_UART_H diff --git a/ports/analog/common-hal/busio/__init__.c b/ports/analog/common-hal/busio/__init__.c new file mode 100644 index 00000000000..ff05be051bb --- /dev/null +++ b/ports/analog/common-hal/busio/__init__.c @@ -0,0 +1,5 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Brandon Hurst, Analog Devices, Inc. +// +// SPDX-License-Identifier: MIT diff --git a/ports/analog/common-hal/digitalio/DigitalInOut.c b/ports/analog/common-hal/digitalio/DigitalInOut.c index 7d4048d77e7..e00347b38ce 100644 --- a/ports/analog/common-hal/digitalio/DigitalInOut.c +++ b/ports/analog/common-hal/digitalio/DigitalInOut.c @@ -14,11 +14,6 @@ extern mxc_gpio_regs_t *gpio_ports[NUM_GPIO_PORTS]; -void common_hal_digitalio_digitalinout_never_reset( - digitalio_digitalinout_obj_t *self) { - common_hal_never_reset_pin(self->pin); -} - bool common_hal_digitalio_digitalinout_deinited(digitalio_digitalinout_obj_t *self) { return self->pin == NULL; } @@ -107,7 +102,7 @@ digitalio_direction_t common_hal_digitalio_digitalinout_get_direction( if (self->pin->port < 4) { // Check that I/O mode is enabled and we don't have in AND out on at the same time - MP_STATIC_ASSERT(!((port->en0 & mask) && (port->inen & mask) && (port->outen & mask))); + MP_STATIC_ASSERT_NONCONSTEXPR(!((port->en0 & mask) && (port->inen & mask) && (port->outen & mask))); if ((port->en0 & mask) && (port->outen & mask)) { return DIRECTION_OUTPUT; diff --git a/ports/analog/common-hal/microcontroller/Pin.c b/ports/analog/common-hal/microcontroller/Pin.c index 4545aa039c2..1e35ebe0a6f 100644 --- a/ports/analog/common-hal/microcontroller/Pin.c +++ b/ports/analog/common-hal/microcontroller/Pin.c @@ -19,25 +19,11 @@ static uint32_t claimed_pins[NUM_GPIO_PORTS]; // defined in board.c extern mxc_gpio_regs_t *gpio_ports[NUM_GPIO_PORTS]; -static uint32_t never_reset_pins[NUM_GPIO_PORTS]; - #define INVALID_PIN 0xFF // id for invalid pin -void reset_all_pins(void) { - // reset all pins except for never_reset_pins - for (int i = 0; i < NUM_GPIO_PORTS; i++) { - for (int j = 0; j < 32; j++) { - if (!(never_reset_pins[i] & (1 << j))) { - reset_pin_number(i, j); - } - } - // set claimed pins to never_reset pins - claimed_pins[i] = never_reset_pins[i]; - } -} void reset_pin_number(uint8_t pin_port, uint8_t pin_pad) { - if (pin_port == INVALID_PIN || pin_port > NUM_GPIO_PORTS) { + if ((pin_port == INVALID_PIN) || (pin_port > NUM_GPIO_PORTS)) { return; } @@ -84,15 +70,6 @@ bool common_hal_mcu_pin_is_free(const mcu_pin_obj_t *pin) { return !(claimed_pins[pin->port] & (pin->mask)); } -void common_hal_never_reset_pin(const mcu_pin_obj_t *pin) { - if ((pin != NULL) && (pin->mask != INVALID_PIN)) { - never_reset_pins[pin->port] |= (1 << pin->mask); - - // any never reset pin must also be claimed - claimed_pins[pin->port] |= (1 << pin->mask); - } -} - void common_hal_reset_pin(const mcu_pin_obj_t *pin) { if (pin == NULL) { return; diff --git a/ports/analog/common-hal/microcontroller/Pin.h b/ports/analog/common-hal/microcontroller/Pin.h index 169586e7e90..18f3700cf5d 100644 --- a/ports/analog/common-hal/microcontroller/Pin.h +++ b/ports/analog/common-hal/microcontroller/Pin.h @@ -10,7 +10,10 @@ #include "peripherals/pins.h" -void reset_all_pins(void); +void common_hal_reset_pin(const mcu_pin_obj_t *pin); // 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_port, uint8_t pin_pad); + +uint8_t common_hal_mcu_pin_number(const mcu_pin_obj_t *pin); +void common_hal_mcu_pin_claim(const mcu_pin_obj_t *pin); diff --git a/ports/analog/common-hal/microcontroller/Processor.c b/ports/analog/common-hal/microcontroller/Processor.c index 87d8047ff2c..3695ecdf671 100644 --- a/ports/analog/common-hal/microcontroller/Processor.c +++ b/ports/analog/common-hal/microcontroller/Processor.c @@ -42,5 +42,5 @@ mcu_reset_reason_t common_hal_mcu_processor_get_reset_reason(void) { #if CIRCUITPY_ALARM // TODO: (low prior.) add reset reason in alarm / deepsleep cases (should require alarm peripheral API in "peripherals") #endif - return RESET_REASON_UNKNOWN; + return MCU_RESET_REASON_UNKNOWN; } diff --git a/ports/analog/common-hal/os/__init__.c b/ports/analog/common-hal/os/__init__.c index 7b607cf6b3c..508b40798e2 100644 --- a/ports/analog/common-hal/os/__init__.c +++ b/ports/analog/common-hal/os/__init__.c @@ -2,6 +2,7 @@ // // SPDX-FileCopyrightText: Copyright (c) 2017 Scott Shawcroft for Adafruit Industries // SPDX-FileCopyrightText: Copyright (c) 2019 Lucian Copeland for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2025 Peggy Zhu, Analog Devices, Inc. // // SPDX-License-Identifier: MIT @@ -15,9 +16,14 @@ // #include "peripherals/periph.h" +// true random number generator, TRNG +#include "trng.h" + bool common_hal_os_urandom(uint8_t *buffer, uint32_t length) { #if (HAS_TRNG) - // todo (low prior): implement + // get a random number of "length" number of bytes + MXC_TRNG_Random(buffer, length); + return true; #else #endif return false; diff --git a/ports/analog/common-hal/rtc/RTC.c b/ports/analog/common-hal/rtc/RTC.c new file mode 100644 index 00000000000..c9d2258c1ec --- /dev/null +++ b/ports/analog/common-hal/rtc/RTC.c @@ -0,0 +1,42 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Nick Moore for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2019 Artur Pacholec +// SPDX-FileCopyrightText: Copyright (c) 2025 Peggy Zhu, Analog Devices, Inc. +// +// SPDX-License-Identifier: MIT + +#include + +#include "py/obj.h" +#include "py/runtime.h" +#include "shared/timeutils/timeutils.h" +#include "supervisor/port.h" + +// This is the time in seconds since 2000 that the RTC was started. +// TODO: Change the offset to ticks so that it can be a subsecond adjustment. +static uint32_t rtc_offset = 0; + +void common_hal_rtc_get_time(timeutils_struct_time_t *tm) { + uint64_t ticks_s = port_get_raw_ticks(NULL) / 1024; + timeutils_seconds_since_2000_to_struct_time(rtc_offset + ticks_s, tm); +} + +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 = epoch_s - ticks_s; +} + +// the calibration function will be implemented in near future +// the RTC oscillator on my MAX32690-APARD is only off by 0.001 second +// the inaccuracy is still tolerable +int common_hal_rtc_get_calibration(void) { + return 0; +} + +void common_hal_rtc_set_calibration(int calibration) { + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_calibration); +} diff --git a/ports/analog/common-hal/rtc/RTC.h b/ports/analog/common-hal/rtc/RTC.h new file mode 100644 index 00000000000..f68897c19fb --- /dev/null +++ b/ports/analog/common-hal/rtc/RTC.h @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018 Noralf Trønnes +// SPDX-FileCopyrightText: Copyright (c) 2019 Artur Pacholec +// SPDX-FileCopyrightText: Copyright (c) 2025 Peggy Zhu, Analog Devices, Inc. +// +// SPDX-License-Identifier: MIT + +#pragma once diff --git a/ports/analog/common-hal/rtc/__init__.c b/ports/analog/common-hal/rtc/__init__.c new file mode 100644 index 00000000000..ddf788bb0b5 --- /dev/null +++ b/ports/analog/common-hal/rtc/__init__.c @@ -0,0 +1,6 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Adafruit Industries LLC +// SPDX-FileCopyrightText: Copyright (c) 2025 Peggy Zhu, Analog Devices, Inc. +// +// SPDX-License-Identifier: MIT diff --git a/ports/analog/linking/max32690_cktpy.ld b/ports/analog/linking/max32690_cktpy.ld index 9b32121a135..e802a8f9612 100644 --- a/ports/analog/linking/max32690_cktpy.ld +++ b/ports/analog/linking/max32690_cktpy.ld @@ -41,6 +41,12 @@ SECTIONS { .text : { . = ALIGN(4); + __property_getter_start = .; + *(.property_getter) + __property_getter_end = .; + __property_getset_start = .; + *(.property_getset) + __property_getset_end = .; _text = .; /* ISR Vector beginning of .text */ @@ -183,4 +189,9 @@ SECTIONS { /* Check if data + heap + stack exceeds RAM limit */ ASSERT(__StackLimit >= _ebss, "region RAM overflowed with stack") + + ASSERT((__property_getter_end - __property_getter_start) % 8 == 0, + "the .property_getter section must hold whole 8-byte objects") + ASSERT((__property_getset_end - __property_getset_start) % 12 == 0, + "the .property_getset section must hold whole 12-byte objects") } diff --git a/ports/analog/max32_port.h b/ports/analog/max32_port.h index 5d92fcfe6d3..89830e96b0a 100644 --- a/ports/analog/max32_port.h +++ b/ports/analog/max32_port.h @@ -22,29 +22,34 @@ #include "system_max32690.h" #include "max32690.h" +// UART Ports & pins +#include "peripherals/max32690/max32_uart.h" +#include "peripherals/max32690/max32_i2c.h" +#include "peripherals/max32690/max32_spi.h" + /** START: GPIO4 Handling specific to MAX32690 */ -#define GPIO4_PIN_MASK 0x00000003 -#define GPIO4_RESET_MASK 0xFFFFFF77 -#define GPIO4_OUTEN_MASK(mask) \ + #define GPIO4_PIN_MASK 0x00000003 + #define GPIO4_RESET_MASK 0xFFFFFF77 + #define GPIO4_OUTEN_MASK(mask) \ (((mask & (1 << 0)) << MXC_F_MCR_GPIO4_CTRL_P40_OE_POS) | \ ((mask & (1 << 1)) << (MXC_F_MCR_GPIO4_CTRL_P41_OE_POS - 1))) -#define GPIO4_PULLDIS_MASK(mask) \ + #define GPIO4_PULLDIS_MASK(mask) \ (((mask & (1 << 0)) << MXC_F_MCR_GPIO4_CTRL_P40_PE_POS) | \ ((mask & (1 << 1)) << (MXC_F_MCR_GPIO4_CTRL_P41_PE_POS - 1))) -#define GPIO4_DATAOUT_MASK(mask) \ + #define GPIO4_DATAOUT_MASK(mask) \ (((mask & (1 << 0)) << MXC_F_MCR_GPIO4_CTRL_P40_DO_POS) | \ ((mask & (1 << 1)) << (MXC_F_MCR_GPIO4_CTRL_P41_DO_POS - 1))) -#define GPIO4_DATAOUT_GET_MASK(mask) \ + #define GPIO4_DATAOUT_GET_MASK(mask) \ ((((MXC_MCR->gpio4_ctrl & MXC_F_MCR_GPIO4_CTRL_P40_DO) >> MXC_F_MCR_GPIO4_CTRL_P40_DO_POS) | \ ((MXC_MCR->gpio4_ctrl & MXC_F_MCR_GPIO4_CTRL_P41_DO) >> \ (MXC_F_MCR_GPIO4_CTRL_P41_DO_POS - 1))) & \ mask) -#define GPIO4_DATAIN_MASK(mask) \ + #define GPIO4_DATAIN_MASK(mask) \ ((((MXC_MCR->gpio4_ctrl & MXC_F_MCR_GPIO4_CTRL_P40_IN) >> MXC_F_MCR_GPIO4_CTRL_P40_IN_POS) | \ ((MXC_MCR->gpio4_ctrl & MXC_F_MCR_GPIO4_CTRL_P41_IN) >> \ (MXC_F_MCR_GPIO4_CTRL_P41_IN_POS - 1))) & \ mask) -#define GPIO4_AFEN_MASK(mask) \ + #define GPIO4_AFEN_MASK(mask) \ (((mask & (1 << 0)) << MXC_F_MCR_OUTEN_PDOWN_OUT_EN_POS) | \ ((mask & (1 << 1)) >> (MXC_F_MCR_OUTEN_SQWOUT_EN_POS + 1))) /** END: GPIO4 Handling specific to MAX32690 */ diff --git a/ports/analog/mpconfigport.h b/ports/analog/mpconfigport.h index c4b3ee031ca..3296661fca7 100644 --- a/ports/analog/mpconfigport.h +++ b/ports/analog/mpconfigport.h @@ -12,6 +12,8 @@ // 24KiB stack #define CIRCUITPY_DEFAULT_STACK_SIZE 0x6000 +#define CIRCUITPY_USB_DEVICE_HIGH_SPEED (1) + // Also includes mpconfigboard.h #include "py/circuitpy_mpconfig.h" diff --git a/ports/analog/mpconfigport.mk b/ports/analog/mpconfigport.mk index 1729a284a3f..63521a27467 100644 --- a/ports/analog/mpconfigport.mk +++ b/ports/analog/mpconfigport.mk @@ -2,9 +2,13 @@ # # SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries # SPDX-FileCopyrightText: Copyright (c) 2024 Brandon Hurst, Analog Devices, Inc. +# SPDX-FileCopyrightText: Copyright (c) 2025 Peggy Zhu, Analog Devices, Inc. # # SPDX-License-Identifier: MIT +# Properties get a dedicated linker section here, so they can drop the unused slots. +CIRCUITPY_OPTIMIZE_PROPERTY_FLASH_SIZE ?= 1 + CHIP_FAMILY ?= max32 # Necessary to build CircuitPython @@ -21,9 +25,8 @@ INTERNAL_FLASH_FILESYSTEM = 1 #################################################################################### # These modules are implemented in ports//common-hal: -# Plan to implement -CIRCUITPY_BUSIO ?= 0 -CIRCUITPY_RTC ?= 0 +CIRCUITPY_BUSIO ?= 1 +CIRCUITPY_RTC ?= 1 # Other modules (may or may not implement): CIRCUITPY_ANALOGIO ?= 0 @@ -51,7 +54,7 @@ CIRCUITPY_BITBANGIO ?= 1 # Requires Microcontroller CIRCUITPY_TOUCHIO ?= 1 # Requires OS -CIRCUITPY_RANDOM ?= 0 +CIRCUITPY_RANDOM ?= 1 # Requires busio.UART CIRCUITPY_CONSOLE_UART ?= 0 # Does nothing without I2C diff --git a/ports/analog/peripherals/max32690/gpios.h b/ports/analog/peripherals/max32690/gpios.h index 4677bf8f33d..fe912277282 100644 --- a/ports/analog/peripherals/max32690/gpios.h +++ b/ports/analog/peripherals/max32690/gpios.h @@ -4,6 +4,8 @@ // // SPDX-License-Identifier: MIT +#pragma once + #include "py/obj.h" #include "py/mphal.h" diff --git a/ports/analog/peripherals/max32690/max32_i2c.c b/ports/analog/peripherals/max32690/max32_i2c.c new file mode 100644 index 00000000000..4b9ec8b4db2 --- /dev/null +++ b/ports/analog/peripherals/max32690/max32_i2c.c @@ -0,0 +1,75 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Brandon Hurst, Analog Devices, Inc. +// +// SPDX-License-Identifier: MIT + +#include "peripherals/pins.h" + +#include "common-hal/busio/I2C.h" +#include "max32_i2c.h" +#include "max32690.h" + +#include "py/runtime.h" +#include "py/mperrno.h" + + +/* Note: The MAX32690 assigns the same alternate function to multiple sets + * of pins. The drivers will enable both sets so that either can be used. + * Users should ensure the unused set is left unconnected. + * + * See MAX32690 Rev A2 Errata #16: + * https://www.analog.com/media/en/technical-documentation/data-sheets/max32690_a2_errata_rev2.pdf + * + * Additionally, note that the TQFN package does not expose some of the duplicate pins. For this package, + * enabling the un-routed GPIOs has been shown to cause initialization issues with the I2C block. + * To work around this, "MAX32690GTK_PACKAGE_TQFN" can be defined by the build system. The recommend place + * to do it is in the "board.mk" file of the BSP. This will prevent the inaccessible pins from being configured. + */ + +const mxc_gpio_cfg_t i2c_maps[NUM_I2C] = { + // I2C0 + { MXC_GPIO2, (MXC_GPIO_PIN_7 | MXC_GPIO_PIN_8), MXC_GPIO_FUNC_ALT1, + MXC_GPIO_PAD_NONE, MXC_GPIO_VSSEL_VDDIO, MXC_GPIO_DRVSTR_0 }, + // I2C1 + { MXC_GPIO0, (MXC_GPIO_PIN_11 | MXC_GPIO_PIN_12), MXC_GPIO_FUNC_ALT1, + MXC_GPIO_PAD_NONE, MXC_GPIO_VSSEL_VDDIO, MXC_GPIO_DRVSTR_0 }, + // I2C2 + { MXC_GPIO1, (MXC_GPIO_PIN_7 | MXC_GPIO_PIN_8), MXC_GPIO_FUNC_ALT3, + MXC_GPIO_PAD_NONE, MXC_GPIO_VSSEL_VDDIOH, MXC_GPIO_DRVSTR_0 }, +}; +#ifndef MAX32690GTK_PACKAGE_TQFN +const mxc_gpio_cfg_t i2c_maps_extra[NUM_I2C] = { + // I2C0A + { MXC_GPIO0, (MXC_GPIO_PIN_30 | MXC_GPIO_PIN_31), MXC_GPIO_FUNC_ALT1, + MXC_GPIO_PAD_PULL_UP, MXC_GPIO_VSSEL_VDDIOH, MXC_GPIO_DRVSTR_0 }, + // I2C1A + { MXC_GPIO2, (MXC_GPIO_PIN_17 | MXC_GPIO_PIN_18), MXC_GPIO_FUNC_ALT1, + MXC_GPIO_PAD_PULL_UP, MXC_GPIO_VSSEL_VDDIOH, MXC_GPIO_DRVSTR_0 }, + // I2C2C + { MXC_GPIO0, (MXC_GPIO_PIN_13 | MXC_GPIO_PIN_14), MXC_GPIO_FUNC_ALT3, + MXC_GPIO_PAD_NONE, MXC_GPIO_VSSEL_VDDIO, MXC_GPIO_DRVSTR_0 }, +}; +#endif + +int pinsToI2c(const mcu_pin_obj_t *sda, const mcu_pin_obj_t *scl) { + for (int i = 0; i < NUM_I2C; i++) { + if ((i2c_maps[i].port == (MXC_GPIO_GET_GPIO(sda->port))) + && (i2c_maps[i].mask == ((sda->mask) | (scl->mask)))) { + return i; + } + } + + // Additional for loop to cover alternate potential I2C maps + #ifndef MAX32690GTK_PACKAGE_TQFN + for (int i = 0; i < NUM_I2C; i++) { + if ((i2c_maps_extra[i].port == (MXC_GPIO_GET_GPIO(sda->port))) + && (i2c_maps_extra[i].mask == ((sda->mask) | (scl->mask)))) { + return i; + } + } + #endif + + mp_raise_ValueError_varg(MP_ERROR_TEXT("Invalid %q"), MP_QSTR_pins); + return -1; +} diff --git a/ports/analog/peripherals/max32690/max32_i2c.h b/ports/analog/peripherals/max32690/max32_i2c.h new file mode 100644 index 00000000000..b64cfd308dc --- /dev/null +++ b/ports/analog/peripherals/max32690/max32_i2c.h @@ -0,0 +1,16 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Brandon Hurst, Analog Devices, Inc. +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "i2c_regs.h" +#include "mxc_sys.h" +#include "i2c.h" +#include "peripherals/pins.h" + +#define NUM_I2C 3 + +int pinsToI2c(const mcu_pin_obj_t *sda, const mcu_pin_obj_t *scl); diff --git a/ports/analog/peripherals/max32690/max32_spi.c b/ports/analog/peripherals/max32690/max32_spi.c new file mode 100644 index 00000000000..c78fd64dbd7 --- /dev/null +++ b/ports/analog/peripherals/max32690/max32_spi.c @@ -0,0 +1,44 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Brandon Hurst, Analog Devices, Inc. +// +// SPDX-License-Identifier: MIT + +#include "peripherals/pins.h" + +#include "common-hal/busio/SPI.h" +#include "max32_spi.h" +#include "max32690.h" + +#include "py/runtime.h" +#include "py/mperrno.h" + +const mxc_gpio_cfg_t spi_maps[NUM_SPI] = { + // SPI0 + { MXC_GPIO2, (MXC_GPIO_PIN_27 | MXC_GPIO_PIN_28 | MXC_GPIO_PIN_29), + MXC_GPIO_FUNC_ALT2, MXC_GPIO_PAD_NONE, MXC_GPIO_VSSEL_VDDIO, MXC_GPIO_DRVSTR_0 }, + // SPI1 + { MXC_GPIO1, (MXC_GPIO_PIN_26 | MXC_GPIO_PIN_28 | MXC_GPIO_PIN_29), + MXC_GPIO_FUNC_ALT1, MXC_GPIO_PAD_NONE, MXC_GPIO_VSSEL_VDDIO, MXC_GPIO_DRVSTR_0 }, + // SPI2 + { MXC_GPIO2, (MXC_GPIO_PIN_2 | MXC_GPIO_PIN_3 | MXC_GPIO_PIN_4), + MXC_GPIO_FUNC_ALT1, MXC_GPIO_PAD_NONE, MXC_GPIO_VSSEL_VDDIO, MXC_GPIO_DRVSTR_0 }, + // SPI3 + { MXC_GPIO0, (MXC_GPIO_PIN_16 | MXC_GPIO_PIN_20 | MXC_GPIO_PIN_21), + MXC_GPIO_FUNC_ALT1, MXC_GPIO_PAD_NONE, MXC_GPIO_VSSEL_VDDIO, MXC_GPIO_DRVSTR_0 }, + // SPI4 + { MXC_GPIO1, (MXC_GPIO_PIN_1 | MXC_GPIO_PIN_2 | MXC_GPIO_PIN_3), + MXC_GPIO_FUNC_ALT1, MXC_GPIO_PAD_NONE, MXC_GPIO_VSSEL_VDDIO, MXC_GPIO_DRVSTR_0 }, +}; + +int pinsToSpi(const mcu_pin_obj_t *mosi, const mcu_pin_obj_t *miso, + const mcu_pin_obj_t *sck) { + for (int i = 0; i < NUM_SPI; i++) { + if ((spi_maps[i].port == (MXC_GPIO_GET_GPIO(mosi->port))) + && (spi_maps[i].mask == ((mosi->mask) | (miso->mask) | (sck->mask)))) { + return i; + } + } + mp_raise_ValueError_varg(MP_ERROR_TEXT("Invalid %q"), MP_QSTR_pins); + return -1; +} diff --git a/ports/analog/peripherals/max32690/max32_spi.h b/ports/analog/peripherals/max32690/max32_spi.h new file mode 100644 index 00000000000..76bb48a59a7 --- /dev/null +++ b/ports/analog/peripherals/max32690/max32_spi.h @@ -0,0 +1,17 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Brandon Hurst, Analog Devices, Inc. +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "spi_regs.h" +#include "mxc_sys.h" +#include "spi.h" +#include "peripherals/pins.h" + +#define NUM_SPI 5 + +int pinsToSpi(const mcu_pin_obj_t *mosi, const mcu_pin_obj_t *miso, + const mcu_pin_obj_t *sck); diff --git a/ports/analog/peripherals/max32690/max32_uart.c b/ports/analog/peripherals/max32690/max32_uart.c new file mode 100644 index 00000000000..7d377087974 --- /dev/null +++ b/ports/analog/peripherals/max32690/max32_uart.c @@ -0,0 +1,36 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Brandon Hurst, Analog Devices, Inc. +// +// SPDX-License-Identifier: MIT + +#include "peripherals/pins.h" + +#include "common-hal/busio/UART.h" +#include "max32_uart.h" +#include "max32690.h" + +#include "py/runtime.h" +#include "py/mperrno.h" + +const mxc_gpio_cfg_t uart_maps[NUM_UARTS] = { + { MXC_GPIO2, (MXC_GPIO_PIN_11 | MXC_GPIO_PIN_12), MXC_GPIO_FUNC_ALT1, + MXC_GPIO_PAD_WEAK_PULL_UP, MXC_GPIO_VSSEL_VDDIO, MXC_GPIO_DRVSTR_0 }, + { MXC_GPIO2, (MXC_GPIO_PIN_14 | MXC_GPIO_PIN_16), MXC_GPIO_FUNC_ALT1, + MXC_GPIO_PAD_WEAK_PULL_UP, MXC_GPIO_VSSEL_VDDIO, MXC_GPIO_DRVSTR_0 }, + { MXC_GPIO1, (MXC_GPIO_PIN_9 | MXC_GPIO_PIN_10), MXC_GPIO_FUNC_ALT1, + MXC_GPIO_PAD_WEAK_PULL_UP, MXC_GPIO_VSSEL_VDDIO, MXC_GPIO_DRVSTR_0 }, + { MXC_GPIO3, (MXC_GPIO_PIN_0 | MXC_GPIO_PIN_1), MXC_GPIO_FUNC_ALT2, + MXC_GPIO_PAD_WEAK_PULL_UP, MXC_GPIO_VSSEL_VDDIO, MXC_GPIO_DRVSTR_0 } +}; + +int pinsToUart(const mcu_pin_obj_t *rx, const mcu_pin_obj_t *tx) { + for (int i = 0; i < NUM_UARTS; i++) { + if ((uart_maps[i].port == (MXC_GPIO_GET_GPIO(tx->port))) + && (uart_maps[i].mask == ((tx->mask) | (rx->mask)))) { + return i; + } + } + mp_raise_ValueError_varg(MP_ERROR_TEXT("Invalid %q"), MP_QSTR_pins); + return -1; +} diff --git a/ports/analog/peripherals/max32690/max32_uart.h b/ports/analog/peripherals/max32690/max32_uart.h new file mode 100644 index 00000000000..f03b500a3c5 --- /dev/null +++ b/ports/analog/peripherals/max32690/max32_uart.h @@ -0,0 +1,16 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Brandon Hurst, Analog Devices, Inc. +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "uart_regs.h" +#include "mxc_sys.h" +#include "uart.h" +#include "peripherals/pins.h" + +#define NUM_UARTS 4 + +int pinsToUart(const mcu_pin_obj_t *rx, const mcu_pin_obj_t *tx); diff --git a/ports/analog/supervisor/cpu.s b/ports/analog/supervisor/cpu.s deleted file mode 100644 index 7cb8291045f..00000000000 --- a/ports/analog/supervisor/cpu.s +++ /dev/null @@ -1,34 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2017 Scott Shawcroft for Adafruit Industries -// SPDX-FileCopyrightText: Copyright (c) 2024 Brandon Hurst, Analog Devices, Inc -// -// SPDX-License-Identifier: MIT - -.syntax unified -.cpu cortex-m4 -.thumb -.text -.align 2 - -@ uint cpu_get_regs_and_sp(r0=uint regs[10]) -.global cpu_get_regs_and_sp -.thumb -.thumb_func -.type cpu_get_regs_and_sp, %function -cpu_get_regs_and_sp: -@ store registers into given array -str r4, [r0], #4 -str r5, [r0], #4 -str r6, [r0], #4 -str r7, [r0], #4 -str r8, [r0], #4 -str r9, [r0], #4 -str r10, [r0], #4 -str r11, [r0], #4 -str r12, [r0], #4 -str r13, [r0], #4 - -@ return the sp -mov r0, sp -bx lr diff --git a/ports/analog/supervisor/port.c b/ports/analog/supervisor/port.c index ad003c12ed9..e95deaba2a8 100644 --- a/ports/analog/supervisor/port.c +++ b/ports/analog/supervisor/port.c @@ -39,11 +39,15 @@ // Sys includes #include "max32_port.h" +#include "nvic_table.h" // Timers #include "mxc_delay.h" #include "rtc.h" +// true random number generator, TRNG +#include "trng.h" + // msec to RTC subsec ticks (4 kHz) /* Converts a time in milleseconds to equivalent RSSA register value */ #define MSEC_TO_SS_ALARM(x) (0 - ((x * 4096) / 1000)) @@ -63,18 +67,27 @@ static uint32_t subsec, sec = 0; static uint32_t tick_flag = 0; // defined by cmsis core files -extern void NVIC_SystemReset(void) NORETURN; +extern void NVIC_SystemReset(void) MP_NORETURN; volatile uint32_t system_ticks = 0; void SysTick_Handler(void) { system_ticks++; + + MXC_DelayHandler(); } safe_mode_t port_init(void) { int err = E_NO_ERROR; + // Set Vector Table to RAM & configure ARM core to use RAM-based ISRs + // This allows definition of ISRs with custom names + // + // Useful for mapping ISRs with names not related to a specific IRQn. + // Source: https://arm-software.github.io/CMSIS_5/Core/html/using_VTOR_pg.html + NVIC_SetRAM(); + // 1ms tick timer SysTick_Config(SystemCoreClock / 1000); NVIC_EnableIRQ(SysTick_IRQn); @@ -112,9 +125,18 @@ safe_mode_t port_init(void) { } ; + // enable TRNG (true random number generator) + #if CIRCUITPY_RANDOM + MXC_TRNG_Init(); + #endif + return SAFE_MODE_NONE; } +void TRNG_IRQHandler(void) { + MXC_TRNG_Handler(); +} + void RTC_IRQHandler(void) { // Read flags to clear int flags = MXC_RTC_GetFlags(); @@ -144,7 +166,6 @@ void reset_cpu(void) { // Reset MCU state void reset_port(void) { - reset_all_pins(); } // Reset to the bootloader diff --git a/ports/analog/supervisor/usb.c b/ports/analog/supervisor/usb.c index 1624359ab51..c971b4dab2c 100644 --- a/ports/analog/supervisor/usb.c +++ b/ports/analog/supervisor/usb.c @@ -19,7 +19,6 @@ void init_usb_hardware(void) { // USB GPIOs are non-configurable on MAX32 devices - // No need to add them to the never_reset list for mcu/Pin API. // 1 ms SysTick initialized in board.c diff --git a/ports/analog/tools/debug-dap.gdb b/ports/analog/tools/debug-dap.gdb new file mode 100644 index 00000000000..d0aa7e2b13f --- /dev/null +++ b/ports/analog/tools/debug-dap.gdb @@ -0,0 +1,3 @@ +target remote :3333 +break main +continue diff --git a/ports/analog/tools/debug-dap.sh b/ports/analog/tools/debug-dap.sh new file mode 100644 index 00000000000..df2964fcb12 --- /dev/null +++ b/ports/analog/tools/debug-dap.sh @@ -0,0 +1,23 @@ +#!/bin/bash + +# Primer on taking cmd line args in Linux shell scripts +# $0 is the script itself +# $1 $2 $3 are arg1, arg2, arg3, etc + +# Export OCD Path +### USER ACTION: Replace with your path to OpenOCD ### +OCD_PATH="~/MaximSDK/Tools/OpenOCD" + +# Call openocd to setup the debug server, storing the PID for OpenOCD +sh -c "openocd -s $OCD_PATH/scripts -f interface/cmsis-dap.cfg -f target/$1.cfg -c \"init; reset halt\" " & + +# Allow enough time for OCD server to set up +# + wait for the sleep to finish +sleep 3 & +wait $! + +# spawn the gdb process and store the gdb_pid +gdb-multiarch build-apard32690/firmware.elf -x "tools/debug-dap.gdb" + +# when gdb exits, kill all openocd processes +killall openocd diff --git a/ports/analog/tools/flash_max32.jlink b/ports/analog/tools/flash_max32.jlink index 4c9cbacb96f..0453f4cb077 100644 --- a/ports/analog/tools/flash_max32.jlink +++ b/ports/analog/tools/flash_max32.jlink @@ -1,6 +1,7 @@ -si 1 +selectinterface swd erase -loadbin build-APARD/firmware.bin 0x10000000 -r -g +loadbin build-apard32690/firmware.bin 0x10000000 +reset +halt +go exit diff --git a/ports/atmel-samd/Makefile b/ports/atmel-samd/Makefile index 0c4eb386130..e681bcd6b8c 100644 --- a/ports/atmel-samd/Makefile +++ b/ports/atmel-samd/Makefile @@ -95,6 +95,8 @@ else ifeq ($(CHIP_FAMILY), samd21) # max-inline-insns-auto increases the size of SAMD51 builds. CFLAGS += -finline-limit=45 --param max-inline-insns-auto=110 + else ifeq ($(HAS_1MB_FLASH),0) + CFLAGS += -finline-limit=45 endif endif @@ -107,7 +109,7 @@ else endif endif -CFLAGS += $(INC) -Wall -Werror -std=gnu11 -nostdlib -fshort-enums $(BASE_CFLAGS) $(CFLAGS_MOD) $(COPT) -Werror=missing-prototypes +CFLAGS += $(INC) -Wall -Werror -std=gnu11 -nostdlib -fshort-enums $(BASE_CFLAGS) $(CFLAGS_MOD) $(COPT) -Werror=missing-prototypes -Werror=old-style-definition ifeq ($(CHIP_FAMILY), samd21) CFLAGS += \ @@ -117,7 +119,7 @@ CFLAGS += \ -msoft-float \ -mfloat-abi=soft \ -DSAMD21 -LIBS := libs/libgcc-12.1.0-Os-v6-m-nofp.a -lc +LIBS := libs/libgcc-14.2.0-Os-v6-m-nofp.a -lc else LIBS := -lgcc -lc endif @@ -169,7 +171,7 @@ LIBS += -lm endif ifeq ($(CHIP_FAMILY), samd21) -LDFLAGS += -mthumb -mcpu=cortex-m0plus -Lasf/thirdparty/CMSIS/Lib/GCC/ +LDFLAGS += -mthumb -mcpu=cortex-m0plus -Lasf/thirdparty/CMSIS/Lib/GCC/ # codespell:ignore thirdparty BOOTLOADER_SIZE := 0x2000 else ifeq ($(CHIP_FAMILY), samd51) LDFLAGS += -mthumb -mcpu=cortex-m4 @@ -266,6 +268,7 @@ SRC_PERIPHERALS := \ peripherals/samd/$(PERIPHERALS_CHIP_FAMILY)/pins.c \ peripherals/samd/$(PERIPHERALS_CHIP_FAMILY)/sercom.c \ peripherals/samd/$(PERIPHERALS_CHIP_FAMILY)/timers.c \ + peripherals/samd/adc.c \ peripherals/samd/clocks.c \ peripherals/samd/dma.c \ peripherals/samd/events.c \ @@ -284,6 +287,7 @@ SRC_C += \ lib/tinyusb/src/portable/microchip/samd/dcd_samd.c \ mphalport.c \ reset.c \ + shared/runtime/gchelper_native.c \ timer_handler.c \ $(SRC_PERIPHERALS) \ @@ -308,20 +312,12 @@ ifeq ($(CIRCUITPY_AUDIOBUSIO),1) SRC_C += peripherals/samd/i2s.c peripherals/samd/$(PERIPHERALS_CHIP_FAMILY)/i2s.c endif -SRC_COMMON_HAL_EXPANDED = $(addprefix shared-bindings/, $(SRC_COMMON_HAL)) \ - $(addprefix shared-bindings/, $(SRC_BINDINGS_ENUMS)) \ - $(addprefix common-hal/, $(SRC_COMMON_HAL)) - -SRC_SHARED_MODULE_EXPANDED = $(addprefix shared-bindings/, $(SRC_SHARED_MODULE)) \ - $(addprefix shared-module/, $(SRC_SHARED_MODULE)) \ - $(addprefix shared-module/, $(SRC_SHARED_MODULE_INTERNAL)) - -# There may be duplicates between SRC_COMMON_HAL_EXPANDED and SRC_SHARED_MODULE_EXPANDED, -# because a few modules have files both in common-hal/ and shared-module/. -# Doing a $(sort ...) removes duplicates as part of sorting. -SRC_COMMON_HAL_SHARED_MODULE_EXPANDED = $(sort $(SRC_COMMON_HAL_EXPANDED) $(SRC_SHARED_MODULE_EXPANDED)) - -SRC_S = supervisor/$(CHIP_FAMILY)_cpu.s +ifeq ($(CHIP_FAMILY), samd21) +SRC_S += shared/runtime/gchelper_thumb1.s +SRC_S += libgcc_thumb1.s +else +SRC_S += shared/runtime/gchelper_thumb2.s +endif OBJ = $(PY_O) $(SUPERVISOR_O) $(addprefix $(BUILD)/, $(SRC_C:.c=.o)) OBJ += $(addprefix $(BUILD)/, $(SRC_ASF:.c=.o)) @@ -343,7 +339,7 @@ OBJ_EXTRA_ORDER_DEPS += $(HEADER_BUILD)/candata.h $(HEADER_BUILD)/candata.h: tools/mkcandata.py | $(HEADER_BUILD) $(Q)$(PYTHON) $< > $@ -SRC_QSTR += $(SRC_C) $(SRC_SUPERVISOR) $(SRC_COMMON_HAL_EXPANDED) $(SRC_SHARED_MODULE_EXPANDED) $(SRC_CIRCUITPY_COMMON) +SRC_QSTR += $(SRC_C) $(SRC_SUPERVISOR) $(SRC_COMMON_HAL_SHARED_MODULE_EXPANDED) $(SRC_CIRCUITPY_COMMON) # Sources that only hold QSTRs after pre-processing. SRC_QSTR_PREPROCESSOR += peripherals/samd/$(PERIPHERALS_CHIP_FAMILY)/clocks.c @@ -356,7 +352,7 @@ $(BUILD)/firmware.elf: $(OBJ) $(GENERATED_LD_FILE) $(STEPECHO) "LINK $@" $(Q)echo $(OBJ) > $(BUILD)/firmware.objs $(Q)$(CC) -o $@ $(LDFLAGS) @$(BUILD)/firmware.objs -Wl,--print-memory-usage -Wl,--start-group $(LIBS) -Wl,--end-group - $(Q)$(SIZE) $@ | $(PYTHON) $(TOP)/tools/build_memory_info.py $(GENERATED_LD_FILE) $(BUILD) + $(Q)$(PYTHON) $(TOP)/tools/build_memory_info.py $@.map $(BUILD) --elf $@ endif $(BUILD)/firmware.bin: $(BUILD)/firmware.elf 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 5979d1ee997..157db0d3f7f 100644 --- a/ports/atmel-samd/asf4_conf/samd21/hpl_sercom_config.h +++ b/ports/atmel-samd/asf4_conf/samd21/hpl_sercom_config.h @@ -431,7 +431,7 @@ // <0x2=>8x arithmetic // <0x3=>8x fractional // <0x3=>3x -// How many over-sampling bits used when samling data state +// How many over-sampling bits used when sampling data state // usart_arch_sampr #ifndef CONF_SERCOM_2_USART_SAMPR #define CONF_SERCOM_2_USART_SAMPR 0x0 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 e05560e6358..6dd21277b78 100644 --- a/ports/atmel-samd/asf4_conf/samd51/hpl_sercom_config.h +++ b/ports/atmel-samd/asf4_conf/samd51/hpl_sercom_config.h @@ -431,7 +431,7 @@ // <0x2=>8x arithmetic // <0x3=>8x fractional // <0x3=>3x -// How many over-sampling bits used when samling data state +// How many over-sampling bits used when sampling data state // usart_arch_sampr #ifndef CONF_SERCOM_2_USART_SAMPR #define CONF_SERCOM_2_USART_SAMPR 0x0 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 e05560e6358..6dd21277b78 100644 --- a/ports/atmel-samd/asf4_conf/same51/hpl_sercom_config.h +++ b/ports/atmel-samd/asf4_conf/same51/hpl_sercom_config.h @@ -431,7 +431,7 @@ // <0x2=>8x arithmetic // <0x3=>8x fractional // <0x3=>3x -// How many over-sampling bits used when samling data state +// How many over-sampling bits used when sampling data state // usart_arch_sampr #ifndef CONF_SERCOM_2_USART_SAMPR #define CONF_SERCOM_2_USART_SAMPR 0x0 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 e05560e6358..6dd21277b78 100644 --- a/ports/atmel-samd/asf4_conf/same54/hpl_sercom_config.h +++ b/ports/atmel-samd/asf4_conf/same54/hpl_sercom_config.h @@ -431,7 +431,7 @@ // <0x2=>8x arithmetic // <0x3=>8x fractional // <0x3=>3x -// How many over-sampling bits used when samling data state +// How many over-sampling bits used when sampling data state // usart_arch_sampr #ifndef CONF_SERCOM_2_USART_SAMPR #define CONF_SERCOM_2_USART_SAMPR 0x0 diff --git a/ports/atmel-samd/audio_dma.c b/ports/atmel-samd/audio_dma.c index d5f841f371d..e5c46d887bf 100644 --- a/ports/atmel-samd/audio_dma.c +++ b/ports/atmel-samd/audio_dma.c @@ -30,7 +30,7 @@ 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]; -uint8_t find_sync_event_channel_raise() { +uint8_t find_sync_event_channel_raise(void) { uint8_t event_channel = find_sync_event_channel(); if (event_channel >= EVSYS_SYNCH_NUM) { mp_raise_RuntimeError(MP_ERROR_TEXT("All sync event channels in use")); @@ -39,14 +39,14 @@ uint8_t find_sync_event_channel_raise() { } void audio_dma_disable_channel(uint8_t channel) { - if (channel >= AUDIO_DMA_CHANNEL_COUNT) { + if (channel == NO_DMA_CHANNEL) { return; } dma_disable_channel(channel); } void audio_dma_enable_channel(uint8_t channel) { - if (channel >= AUDIO_DMA_CHANNEL_COUNT) { + if (channel == NO_DMA_CHANNEL) { return; } dma_enable_channel(channel); @@ -163,19 +163,18 @@ static void setup_audio_descriptor(DmacDescriptor *descriptor, uint8_t beat_size } // Playback should be shutdown before calling this. -audio_dma_result audio_dma_setup_playback(audio_dma_t *dma, +// The body of audio_dma_setup_playback(), run once dma_channel is allocated. +// It can raise: m_realloc(), find_sync_event_channel_raise() and +// audio_dma_load_next_block() all do. +static audio_dma_result setup_playback(audio_dma_t *dma, mp_obj_t sample, bool loop, bool single_channel_output, uint8_t audio_channel, bool output_signed, uint32_t output_register_address, - uint8_t dma_trigger_source) { - uint8_t dma_channel = dma_allocate_channel(true); - if (dma_channel >= AUDIO_DMA_CHANNEL_COUNT) { - return AUDIO_DMA_DMA_BUSY; - } - + uint8_t dma_trigger_source, + uint8_t dma_channel) { dma->sample = sample; dma->loop = loop; dma->single_channel_output = single_channel_output; @@ -296,16 +295,55 @@ audio_dma_result audio_dma_setup_playback(audio_dma_t *dma, return AUDIO_DMA_OK; } +audio_dma_result audio_dma_setup_playback(audio_dma_t *dma, + mp_obj_t sample, + bool loop, + bool single_channel_output, + uint8_t audio_channel, + bool output_signed, + uint32_t output_register_address, + uint8_t dma_trigger_source) { + uint8_t dma_channel = dma_allocate_audio_channel(); + if (dma_channel == NO_DMA_CHANNEL) { + return AUDIO_DMA_DMA_BUSY; + } + dma->dma_channel = dma_channel; + dma->event_channel = 0xff; + + // If setup fails or raises, free the DMA channel and anything else it + // took. Nothing else will: there's no bulk audio DMA reset at VM end, and + // the caller's deinit() only stops playback that started. + audio_dma_result result; + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + result = setup_playback(dma, sample, loop, single_channel_output, audio_channel, + output_signed, output_register_address, dma_trigger_source, dma_channel); + nlr_pop(); + } else { + audio_dma_stop(dma); + nlr_jump(nlr.ret_val); + } + if (result != AUDIO_DMA_OK) { + audio_dma_stop(dma); + } + return result; +} + void audio_dma_stop(audio_dma_t *dma) { uint8_t channel = dma->dma_channel; - if (channel < AUDIO_DMA_CHANNEL_COUNT) { + if (channel != NO_DMA_CHANNEL) { audio_dma_disable_channel(channel); - disable_event_channel(dma->event_channel); + // 0xff means no event channel (single buffer). SAMD51's + // disable_event_channel() would index past the channel registers. + if (dma->event_channel != 0xff) { + disable_event_channel(dma->event_channel); + dma->event_channel = 0xff; + } MP_STATE_PORT(playing_audio)[channel] = NULL; audio_dma_state[channel] = NULL; dma_free_channel(dma->dma_channel); } - dma->dma_channel = AUDIO_DMA_CHANNEL_COUNT; + dma->dma_channel = NO_DMA_CHANNEL; dma->playing_in_progress = false; } @@ -318,7 +356,7 @@ void audio_dma_resume(audio_dma_t *dma) { } bool audio_dma_get_paused(audio_dma_t *dma) { - if (dma->dma_channel >= AUDIO_DMA_CHANNEL_COUNT) { + if (dma->dma_channel == NO_DMA_CHANNEL) { return false; } uint32_t status = dma_transfer_status(dma->dma_channel); @@ -327,23 +365,22 @@ bool audio_dma_get_paused(audio_dma_t *dma) { } void audio_dma_init(audio_dma_t *dma) { - dma->dma_channel = AUDIO_DMA_CHANNEL_COUNT; -} - -void audio_dma_reset(void) { - for (uint8_t i = 0; i < AUDIO_DMA_CHANNEL_COUNT; i++) { - audio_dma_state[i] = NULL; - audio_dma_pending[i] = false; - dma_free_channel(i); - dma_descriptor(i)->BTCTRL.bit.VALID = false; - MP_STATE_PORT(playing_audio)[i] = NULL; - } + dma->dma_channel = NO_DMA_CHANNEL; } bool audio_dma_get_playing(audio_dma_t *dma) { - if (dma->dma_channel >= AUDIO_DMA_CHANNEL_COUNT) { + if (dma->dma_channel == NO_DMA_CHANNEL) { return false; } + // A single buffer played once ends with its one descriptor and no further block to load, + // so nothing else notices the end: stop once the channel reports the transfer done. + if (dma->single_buffer && !dma->loop) { + uint32_t status = dma_transfer_status(dma->dma_channel); + if ((status & (DMAC_CHINTFLAG_TCMPL | DMAC_CHINTFLAG_TERR)) != 0) { + audio_dma_stop(dma); + return false; + } + } return dma->playing_in_progress; } diff --git a/ports/atmel-samd/audio_dma.h b/ports/atmel-samd/audio_dma.h index 7b42a7b6114..286b7c9011c 100644 --- a/ports/atmel-samd/audio_dma.h +++ b/ports/atmel-samd/audio_dma.h @@ -42,7 +42,6 @@ typedef enum { } audio_dma_result; void audio_dma_init(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. diff --git a/ports/atmel-samd/background.c b/ports/atmel-samd/background.c index 2410f0fddb7..3d25bd340b1 100644 --- a/ports/atmel-samd/background.c +++ b/ports/atmel-samd/background.c @@ -14,7 +14,7 @@ #include "supervisor/shared/stack.h" #include "supervisor/port.h" -#ifdef CIRCUITPY_DISPLAYIO +#if CIRCUITPY_DISPLAYIO #include "shared-module/displayio/__init__.h" #endif diff --git a/ports/atmel-samd/boards/adafruit_pixel_trinkey_m0/mpconfigboard.mk b/ports/atmel-samd/boards/adafruit_pixel_trinkey_m0/mpconfigboard.mk index 32db497b010..24df3a1fbe1 100644 --- a/ports/atmel-samd/boards/adafruit_pixel_trinkey_m0/mpconfigboard.mk +++ b/ports/atmel-samd/boards/adafruit_pixel_trinkey_m0/mpconfigboard.mk @@ -19,6 +19,7 @@ CIRCUITPY_PWMIO = 1 CIRCUITPY_ROTARYIO = 0 CIRCUITPY_RTC = 0 CIRCUITPY_TOUCHIO = 0 +CIRCUITPY_USB_MIDI = 0 CIRCUITPY_PIXELBUF = 1 diff --git a/ports/atmel-samd/boards/adafruit_trrs_trinkey_m0/mpconfigboard.h b/ports/atmel-samd/boards/adafruit_trrs_trinkey_m0/mpconfigboard.h index 8e53129679f..7b206ddaf54 100644 --- a/ports/atmel-samd/boards/adafruit_trrs_trinkey_m0/mpconfigboard.h +++ b/ports/atmel-samd/boards/adafruit_trrs_trinkey_m0/mpconfigboard.h @@ -40,3 +40,6 @@ // no PA29 #define IGNORE_PIN_PA30 1 #define IGNORE_PIN_PA31 1 + +// A couple Learn examples do `array.array('d', ...)` so enable it. +#define MICROPY_PY_DOUBLE_TYPECODE 1 diff --git a/ports/atmel-samd/boards/aloriumtech_evo_m51/board.c b/ports/atmel-samd/boards/aloriumtech_evo_m51/board.c index eece51baa54..8f64430ba06 100644 --- a/ports/atmel-samd/boards/aloriumtech_evo_m51/board.c +++ b/ports/atmel-samd/boards/aloriumtech_evo_m51/board.c @@ -13,7 +13,6 @@ #include "common-hal/microcontroller/Pin.h" void board_init(void) { - never_reset_pin_number(PIN_PB20); 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 diff --git a/ports/atmel-samd/boards/bradanlanestudio_coin_m0/mpconfigboard.mk b/ports/atmel-samd/boards/bradanlanestudio_coin_m0/mpconfigboard.mk index 33165c8cfc5..9a2cdcd668e 100644 --- a/ports/atmel-samd/boards/bradanlanestudio_coin_m0/mpconfigboard.mk +++ b/ports/atmel-samd/boards/bradanlanestudio_coin_m0/mpconfigboard.mk @@ -18,7 +18,7 @@ CHIP_FAMILY = samd21 SPI_FLASH_FILESYSTEM = 1 EXTERNAL_FLASH_DEVICES = "W25Q32JVxQ" -LONGINT_IMPL = NONE +LONGINT_IMPL = MPZ # the M0 Coin has limited functionality and many modules can be eliminated @@ -26,7 +26,7 @@ LONGINT_IMPL = NONE # Disable modules that are unusable on this special-purpose board. -CIRCUITPY_FULL_BUILD = 0 +CIRCUITPY_FULL_BUILD = 1 CIRCUITPY_AUDIOIO = 1 CIRCUITPY_DISPLAYIO = 0 @@ -38,7 +38,8 @@ CIRCUITPY_ROTARYIO = 0 CIRCUITPY_RTC = 0 CIRCUITPY_USB_HID = 1 CIRCUITPY_USB_MIDI = 0 - +CIRCUITPY_NEOPIXEL_WRITE = 1 +CIRCUITPY_PIXELBUF = 1 # Include these Python libraries in firmware. FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_HID diff --git a/ports/atmel-samd/boards/circuitbrains_basic_m0/mpconfigboard.mk b/ports/atmel-samd/boards/circuitbrains_basic_m0/mpconfigboard.mk index c647039bc8a..121becc472d 100755 --- a/ports/atmel-samd/boards/circuitbrains_basic_m0/mpconfigboard.mk +++ b/ports/atmel-samd/boards/circuitbrains_basic_m0/mpconfigboard.mk @@ -10,4 +10,6 @@ SPI_FLASH_FILESYSTEM = 1 EXTERNAL_FLASH_DEVICES = "W25Q32JVxQ" LONGINT_IMPL = MPZ -CIRCUITPY_JPEGIO = 0 +CIRCUITPY_CODEOP = 0 +CIRCUITPY_ERRNO = 0 +CIRCUITPY_RAINBOWIO = 0 diff --git a/ports/atmel-samd/boards/circuitbrains_deluxe_m4/mpconfigboard.mk b/ports/atmel-samd/boards/circuitbrains_deluxe_m4/mpconfigboard.mk index b3cb3d73015..32793c20d2f 100755 --- a/ports/atmel-samd/boards/circuitbrains_deluxe_m4/mpconfigboard.mk +++ b/ports/atmel-samd/boards/circuitbrains_deluxe_m4/mpconfigboard.mk @@ -10,8 +10,10 @@ QSPI_FLASH_FILESYSTEM = 1 EXTERNAL_FLASH_DEVICES = "W25Q64JVxQ, S25FL064L" LONGINT_IMPL = MPZ +CIRCUITPY_I2CTARGET = 0 CIRCUITPY_PS2IO = 1 CIRCUITPY_JPEGIO = 0 +CIRCUITPY_MSGPACK = 0 CIRCUITPY_SPITARGET = 0 CIRCUITPY_SYNTHIO = 0 CIRCUITPY_TILEPALETTEMAPPER = 0 diff --git a/ports/atmel-samd/boards/circuitplayground_express/board.c b/ports/atmel-samd/boards/circuitplayground_express/board.c index cc5d8355624..1b1874702c1 100644 --- a/ports/atmel-samd/boards/circuitplayground_express/board.c +++ b/ports/atmel-samd/boards/circuitplayground_express/board.c @@ -28,6 +28,12 @@ bool board_requests_safe_mode(void) { return safe_mode; } +void board_init(void) { + // PA30 (SPEAKER_ENABLE) turns on the speaker amplifier. + // Default to low (off). + reset_pin_number(PIN_PA30); +} + void reset_board(void) { board_reset_user_neopixels(&pin_PB23, 10); } diff --git a/ports/atmel-samd/boards/circuitplayground_express_crickit/board.c b/ports/atmel-samd/boards/circuitplayground_express_crickit/board.c index 5a3e55395f5..fc5a031bbe4 100644 --- a/ports/atmel-samd/boards/circuitplayground_express_crickit/board.c +++ b/ports/atmel-samd/boards/circuitplayground_express_crickit/board.c @@ -28,6 +28,12 @@ bool board_requests_safe_mode(void) { return safe_mode; } +void board_init(void) { + // PA30 (SPEAKER_ENABLE) turns on the speaker amplifier. + // Default to low (off). + reset_pin_number(PIN_PA30); +} + void reset_board(void) { board_reset_user_neopixels(&pin_PB23, 10); } diff --git a/ports/atmel-samd/boards/circuitplayground_express_displayio/board.c b/ports/atmel-samd/boards/circuitplayground_express_displayio/board.c index 5a3e55395f5..fc5a031bbe4 100644 --- a/ports/atmel-samd/boards/circuitplayground_express_displayio/board.c +++ b/ports/atmel-samd/boards/circuitplayground_express_displayio/board.c @@ -28,6 +28,12 @@ bool board_requests_safe_mode(void) { return safe_mode; } +void board_init(void) { + // PA30 (SPEAKER_ENABLE) turns on the speaker amplifier. + // Default to low (off). + reset_pin_number(PIN_PA30); +} + void reset_board(void) { board_reset_user_neopixels(&pin_PB23, 10); } diff --git a/ports/atmel-samd/boards/datalore_ip_m4/mpconfigboard.mk b/ports/atmel-samd/boards/datalore_ip_m4/mpconfigboard.mk index f6c07e7aaaf..14744513bbc 100644 --- a/ports/atmel-samd/boards/datalore_ip_m4/mpconfigboard.mk +++ b/ports/atmel-samd/boards/datalore_ip_m4/mpconfigboard.mk @@ -9,7 +9,10 @@ CHIP_FAMILY = samd51 QSPI_FLASH_FILESYSTEM = 1 EXTERNAL_FLASH_DEVICES = "GD25Q16C, W25Q16JVxQ, W25Q16JVxM" LONGINT_IMPL = MPZ -CIRCUITPY_SYNTHIO = 0 + +CIRCUITPY_I2CTARGET = 0 CIRCUITPY_JPEGIO = 0 +CIRCUITPY_MSGPACK = 0 CIRCUITPY_SPITARGET = 0 +CIRCUITPY_SYNTHIO = 0 CIRCUITPY_TILEPALETTEMAPPER = 0 diff --git a/ports/atmel-samd/boards/feather_m0_express/mpconfigboard.mk b/ports/atmel-samd/boards/feather_m0_express/mpconfigboard.mk index 00418114841..1152fb4acc4 100644 --- a/ports/atmel-samd/boards/feather_m0_express/mpconfigboard.mk +++ b/ports/atmel-samd/boards/feather_m0_express/mpconfigboard.mk @@ -10,4 +10,6 @@ SPI_FLASH_FILESYSTEM = 1 EXTERNAL_FLASH_DEVICES = "S25FL216K, GD25Q16C, W25Q16JVxQ" LONGINT_IMPL = MPZ +CIRCUITPY_CODEOP = 0 +CIRCUITPY_ERRNO = 0 CIRCUITPY_RAINBOWIO = 0 diff --git a/ports/atmel-samd/boards/feather_m0_supersized/mpconfigboard.h b/ports/atmel-samd/boards/feather_m0_supersized/mpconfigboard.h index be48cb81055..8fdf20f186b 100644 --- a/ports/atmel-samd/boards/feather_m0_supersized/mpconfigboard.h +++ b/ports/atmel-samd/boards/feather_m0_supersized/mpconfigboard.h @@ -20,6 +20,8 @@ #define SPI_FLASH_SCK_PIN &pin_PA09 #define SPI_FLASH_CS_PIN &pin_PA13 +#define BOARD_HAS_CRYSTAL 1 + #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 811336885b8..dd58e8d1ce5 100644 --- a/ports/atmel-samd/boards/feather_m0_supersized/mpconfigboard.mk +++ b/ports/atmel-samd/boards/feather_m0_supersized/mpconfigboard.mk @@ -9,3 +9,7 @@ CHIP_FAMILY = samd21 SPI_FLASH_FILESYSTEM = 1 EXTERNAL_FLASH_DEVICES = "S25FL064L" LONGINT_IMPL = MPZ + +CIRCUITPY_CODEOP = 0 +CIRCUITPY_ERRNO = 0 +CIRCUITPY_RAINBOWIO = 0 diff --git a/ports/atmel-samd/boards/feather_m4_can/mpconfigboard.mk b/ports/atmel-samd/boards/feather_m4_can/mpconfigboard.mk index ce2f5116cf7..206716c6879 100644 --- a/ports/atmel-samd/boards/feather_m4_can/mpconfigboard.mk +++ b/ports/atmel-samd/boards/feather_m4_can/mpconfigboard.mk @@ -14,9 +14,12 @@ CIRCUITPY__EVE = 1 CIRCUITPY_BITMAPFILTER = 0 CIRCUITPY_CANIO = 1 CIRCUITPY_FLOPPYIO = 0 -CIRCUITPY_SYNTHIO = 0 CIRCUITPY_GIFIO = 0 +CIRCUITPY_I2CTARGET = 0 CIRCUITPY_JPEGIO = 0 +CIRCUITPY_PS2IO = 0 +CIRCUITPY_SYNTHIO = 0 +CIRCUITPY_VECTORIO = 0 CIRCUITPY_LTO_PARTITION = one diff --git a/ports/atmel-samd/boards/feather_m4_express/mpconfigboard.mk b/ports/atmel-samd/boards/feather_m4_express/mpconfigboard.mk index 4958581056e..f780ea4aa3d 100644 --- a/ports/atmel-samd/boards/feather_m4_express/mpconfigboard.mk +++ b/ports/atmel-samd/boards/feather_m4_express/mpconfigboard.mk @@ -14,6 +14,7 @@ CIRCUITPY__EVE = 1 CIRCUITPY_CODEOP = 0 CIRCUITPY_FLOPPYIO = 0 CIRCUITPY_JPEGIO = 0 +CIRCUITPY_MSGPACK = 0 CIRCUITPY_SYNTHIO = 0 CIRCUITPY_VECTORIO = 0 diff --git a/ports/atmel-samd/boards/hallowing_m0_express/board.c b/ports/atmel-samd/boards/hallowing_m0_express/board.c index 637129a0e9d..304d842ccaa 100644 --- a/ports/atmel-samd/boards/hallowing_m0_express/board.c +++ b/ports/atmel-samd/boards/hallowing_m0_express/board.c @@ -28,7 +28,7 @@ uint8_t display_init_sequence[] = { 0xc3, 2, 0x8a, 0x2a, 0xc4, 2, 0x8a, 0xee, 0xc5, 1, 0x0e, // _VMCTR1 VCOMH = 4V, VOML = -1.1V - 0x2a, 0, // _INVOFF + 0x20, 0, // _INVOFF 0x36, 1, 0x18, // _MADCTL bottom to top refresh // 1 clk cycle nonoverlap, 2 cycle gate rise, 3 cycle osc equalie, // fix on VTL @@ -51,12 +51,11 @@ void board_init(void) { fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; bus->base.type = &fourwire_fourwire_type; busio_spi_obj_t *spi = common_hal_board_create_spi(0); - common_hal_busio_spi_never_reset(spi); common_hal_fourwire_fourwire_construct(bus, spi, - &pin_PA28, // Command or data - &pin_PA01, // Chip select - &pin_PA27, // Reset + MP_OBJ_FROM_PTR(&pin_PA28), // Command or data + MP_OBJ_FROM_PTR(&pin_PA01), // Chip select + MP_OBJ_FROM_PTR(&pin_PA27), // Reset 12000000, // Baudrate 0, // Polarity 0); // Phase diff --git a/ports/atmel-samd/boards/hallowing_m4_express/board.c b/ports/atmel-samd/boards/hallowing_m4_express/board.c index bfef5fbcd75..1713f845b38 100644 --- a/ports/atmel-samd/boards/hallowing_m4_express/board.c +++ b/ports/atmel-samd/boards/hallowing_m4_express/board.c @@ -30,14 +30,13 @@ void board_init(void) { fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_PA01, &pin_PA00, NULL, false); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_PB31, // TFT_DC Command or data - &pin_PA27, // TFT_CS Chip select - &pin_PB30, // TFT_RST Reset + MP_OBJ_FROM_PTR(&pin_PB31), // TFT_DC Command or data + MP_OBJ_FROM_PTR(&pin_PA27), // TFT_CS Chip select + MP_OBJ_FROM_PTR(&pin_PB30), // TFT_RST Reset 60000000, // Baudrate 0, // Polarity 0); // Phase diff --git a/ports/atmel-samd/boards/hallowing_m4_express/mpconfigboard.mk b/ports/atmel-samd/boards/hallowing_m4_express/mpconfigboard.mk index 3a0eeb3f213..5a3ee93444a 100644 --- a/ports/atmel-samd/boards/hallowing_m4_express/mpconfigboard.mk +++ b/ports/atmel-samd/boards/hallowing_m4_express/mpconfigboard.mk @@ -11,6 +11,14 @@ EXTERNAL_FLASH_DEVICES = "GD25Q64C,W25Q64JVxQ" LONGINT_IMPL = MPZ CIRCUITPY_AESIO = 0 -CIRCUITPY_JPEGIO = 0 -CIRCUITPY_SYNTHIO = 0 -CIRCUITPY_TILEPALETTEMAPPER = 0 +CIRCUITPY_CODEOP = 0 +CIRCUITPY_EPAPERDISPLAY = 0 +CIRCUITPY_FLOPPYIO = 0 +CIRCUITPY_FRAMEBUFFERIO = 0 +CIRCUITPY_I2CDISPLAYBUS = 0 +CIRCUITPY_I2CTARGET = 0 +CIRCUITPY_MSGPACK = 0 +CIRCUITPY_PARALLELDISPLAYBUS = 0 +CIRCUITPY_RGBMATRIX = 0 +CIRCUITPY_SHARPDISPLAY = 0 +CIRCUITPY_SPITARGET = 0 diff --git a/ports/atmel-samd/boards/huntercat_nfc/mpconfigboard.mk b/ports/atmel-samd/boards/huntercat_nfc/mpconfigboard.mk index 5e9a1372b45..4da89f10cb8 100644 --- a/ports/atmel-samd/boards/huntercat_nfc/mpconfigboard.mk +++ b/ports/atmel-samd/boards/huntercat_nfc/mpconfigboard.mk @@ -9,3 +9,24 @@ CHIP_FAMILY = samd21 SPI_FLASH_FILESYSTEM = 1 EXTERNAL_FLASH_DEVICES = "W25Q16JVxQ" LONGINT_IMPL = MPZ + +CIRCUITPY_CODEOP = 0 + +# No display or display connector. +CIRCUITPY_DISPLAYIO = 0 +CIRCUITPY_PARALLELDISPLAYBUS = 0 + +# No audio input, output, amplifier, microphone, or codec. +CIRCUITPY_AUDIOBUSIO = 0 +CIRCUITPY_AUDIOIO = 0 + +# Discrete LEDs only, not NeoPixels. +CIRCUITPY_RAINBOWIO = 0 +CIRCUITPY_NEOPIXEL_WRITE = 0 +CIRCUITPY_PIXELBUF = 0 + +# No corresponding built-in peripherals. +CIRCUITPY_ONEWIREIO = 0 +CIRCUITPY_PULSEIO = 0 +CIRCUITPY_ROTARYIO = 0 +CIRCUITPY_TOUCHIO = 0 diff --git a/ports/atmel-samd/boards/itsybitsy_m0_express/mpconfigboard.mk b/ports/atmel-samd/boards/itsybitsy_m0_express/mpconfigboard.mk index 6dce23e506d..727c07adaba 100644 --- a/ports/atmel-samd/boards/itsybitsy_m0_express/mpconfigboard.mk +++ b/ports/atmel-samd/boards/itsybitsy_m0_express/mpconfigboard.mk @@ -12,4 +12,7 @@ LONGINT_IMPL = MPZ CIRCUITPY_BITBANG_APA102 = 1 +CIRCUITPY_CODEOP = 0 +CIRCUITPY_ERRNO = 0 CIRCUITPY_PULSEIO = 0 +CIRCUITPY_RAINBOWIO = 0 diff --git a/ports/atmel-samd/boards/itsybitsy_m4_express/mpconfigboard.mk b/ports/atmel-samd/boards/itsybitsy_m4_express/mpconfigboard.mk index 27bf8c165da..be22cb94fae 100644 --- a/ports/atmel-samd/boards/itsybitsy_m4_express/mpconfigboard.mk +++ b/ports/atmel-samd/boards/itsybitsy_m4_express/mpconfigboard.mk @@ -10,11 +10,13 @@ QSPI_FLASH_FILESYSTEM = 1 EXTERNAL_FLASH_DEVICES = "GD25Q16C,W25Q16JVxQ" LONGINT_IMPL = MPZ +CIRCUITPY__EVE = 1 CIRCUITPY_CODEOP = 0 CIRCUITPY_FLOPPYIO = 0 -CIRCUITPY_GIFIO = 0 CIRCUITPY_JPEGIO = 0 -CIRCUITPY_TILEPALETTEMAPPER = 0 +CIRCUITPY_MSGPACK = 0 +CIRCUITPY_SYNTHIO = 0 +CIRCUITPY_VECTORIO = 0 CIRCUITPY_BITBANG_APA102 = 1 diff --git a/ports/atmel-samd/boards/kicksat-sprite/mpconfigboard.mk b/ports/atmel-samd/boards/kicksat-sprite/mpconfigboard.mk index ebe9403c34d..b20242a4361 100644 --- a/ports/atmel-samd/boards/kicksat-sprite/mpconfigboard.mk +++ b/ports/atmel-samd/boards/kicksat-sprite/mpconfigboard.mk @@ -18,11 +18,13 @@ CIRCUITPY_AUDIOMIXER = 0 CIRCUITPY_AUDIOMP3 = 0 CIRCUITPY_BLEIO_HCI = 0 CIRCUITPY_DISPLAYIO = 0 +CIRCUITPY_ERRNO = 0 CIRCUITPY_FLOPPYIO = 0 CIRCUITPY_FRAMEBUFFERIO = 0 CIRCUITPY_PIXELMAP = 0 CIRCUITPY_GETPASS = 0 CIRCUITPY_KEYPAD = 0 +CIRCUITPY_LOAD_NATIVE = 0 CIRCUITPY_MSGPACK = 0 CIRCUITPY_PIXELBUF = 0 CIRCUITPY_PS2IO = 0 diff --git a/ports/atmel-samd/boards/metro_m0_express/mpconfigboard.mk b/ports/atmel-samd/boards/metro_m0_express/mpconfigboard.mk index d758d6878fb..85bac53dc76 100644 --- a/ports/atmel-samd/boards/metro_m0_express/mpconfigboard.mk +++ b/ports/atmel-samd/boards/metro_m0_express/mpconfigboard.mk @@ -10,5 +10,7 @@ SPI_FLASH_FILESYSTEM = 1 EXTERNAL_FLASH_DEVICES = "S25FL216K, GD25Q16C, W25Q16JVxQ" LONGINT_IMPL = MPZ +CIRCUITPY_AUDIOBUSIO_PDMIN = 0 CIRCUITPY_CODEOP = 0 +CIRCUITPY_ERRNO = 0 CIRCUITPY_RAINBOWIO = 0 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 69cd5b0e286..cb7e690c6c0 100644 --- a/ports/atmel-samd/boards/metro_m4_airlift_lite/mpconfigboard.mk +++ b/ports/atmel-samd/boards/metro_m4_airlift_lite/mpconfigboard.mk @@ -11,9 +11,13 @@ EXTERNAL_FLASH_DEVICES = "S25FL116K, S25FL216K, GD25Q16C, W25Q16JVxQ" LONGINT_IMPL = MPZ CIRCUITPY__EVE = 0 +CIRCUITPY_CODEOP = 0 CIRCUITPY_FLOPPYIO = 0 CIRCUITPY_JPEGIO = 0 +CIRCUITPY_MSGPACK = 0 CIRCUITPY_SYNTHIO = 0 +CIRCUITPY_VECTORIO = 0 + # We don't have room for the fonts for terminalio for certain languages, # so turn off terminalio, and if it's off and displayio is on, diff --git a/ports/atmel-samd/boards/metro_m4_express/mpconfigboard.mk b/ports/atmel-samd/boards/metro_m4_express/mpconfigboard.mk index 55a307ed4e3..d5aef01a037 100644 --- a/ports/atmel-samd/boards/metro_m4_express/mpconfigboard.mk +++ b/ports/atmel-samd/boards/metro_m4_express/mpconfigboard.mk @@ -14,6 +14,7 @@ CIRCUITPY__EVE = 1 CIRCUITPY_CODEOP = 0 CIRCUITPY_FLOPPYIO = 0 CIRCUITPY_JPEGIO = 0 +CIRCUITPY_MSGPACK = 0 CIRCUITPY_SYNTHIO = 0 CIRCUITPY_VECTORIO = 0 diff --git a/ports/atmel-samd/boards/microchip_curiosity_circuitpython/board.c b/ports/atmel-samd/boards/microchip_curiosity_circuitpython/board.c new file mode 100644 index 00000000000..b44a1ae51e0 --- /dev/null +++ b/ports/atmel-samd/boards/microchip_curiosity_circuitpython/board.c @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2017 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/atmel-samd/boards/microchip_curiosity_circuitpython/mpconfigboard.h b/ports/atmel-samd/boards/microchip_curiosity_circuitpython/mpconfigboard.h new file mode 100644 index 00000000000..4416d8517d2 --- /dev/null +++ b/ports/atmel-samd/boards/microchip_curiosity_circuitpython/mpconfigboard.h @@ -0,0 +1,33 @@ + +#pragma once + +#define MICROPY_HW_BOARD_NAME "Microchip Curiosity CircuitPython" +#define MICROPY_HW_MCU_NAME "same51j20" +#define CIRCUITPY_MCU_FAMILY samd51 + +#define MICROPY_HW_LED_STATUS (&pin_PB23) +#define MICROPY_HW_NEOPIXEL (&pin_PB22) + +#define BOARD_HAS_CRYSTAL 1 + +// USB is always used internally so skip the pin objects for it. +#define IGNORE_PIN_PA24 1 +#define IGNORE_PIN_PA25 1 + +#define DEFAULT_I2C_BUS_SCL (&pin_PB30) +#define DEFAULT_I2C_BUS_SDA (&pin_PB31) + +#define CIRCUITPY_BOARD_SPI (3) +// These correspond to the CIRCUITPY_BOARD_BUS_SINGLETON definitions in pins.c +#define CIRCUITPY_BOARD_SPI_PIN { \ + {.clock = &pin_PB03, .mosi = &pin_PB02, .miso = &pin_PB00}, /*board.SPI()*/ \ + {.clock = &pin_PA05, .mosi = &pin_PA04, .miso = NULL}, /*board.LCD_SPI()*/ \ + {.clock = &pin_PA17, .mosi = &pin_PA16, .miso = &pin_PA18}, /*board.SD_SPI()*/ \ +} + +#define DEFAULT_CAN_BUS_TX (&pin_PB12) +#define DEFAULT_CAN_BUS_RX (&pin_PB13) +#define DEFAULT_CAN_BUS_STDBY (&pin_PB17) + +#define DEFAULT_UART_BUS_RX (&pin_PA23) +#define DEFAULT_UART_BUS_TX (&pin_PA22) diff --git a/ports/atmel-samd/boards/microchip_curiosity_circuitpython/mpconfigboard.mk b/ports/atmel-samd/boards/microchip_curiosity_circuitpython/mpconfigboard.mk new file mode 100644 index 00000000000..985eb4c6a44 --- /dev/null +++ b/ports/atmel-samd/boards/microchip_curiosity_circuitpython/mpconfigboard.mk @@ -0,0 +1,14 @@ +USB_VID = 0x04D8 +USB_PID = 0xE52B +USB_PRODUCT = "Microchip Curiosity CircuitPython" +USB_MANUFACTURER = "Microchip Technology Inc" + +CHIP_VARIANT = SAME51J20A +CHIP_FAMILY = same51 + +QSPI_FLASH_FILESYSTEM = 1 +EXTERNAL_FLASH_DEVICES = "SST26VF016B,SST26VF032B,SST26VF064B" +LONGINT_IMPL = MPZ + +CIRCUITPY__EVE = 1 +CIRCUITPY_CANIO = 1 diff --git a/ports/atmel-samd/boards/microchip_curiosity_circuitpython/pins.c b/ports/atmel-samd/boards/microchip_curiosity_circuitpython/pins.c new file mode 100644 index 00000000000..49c7f7565e2 --- /dev/null +++ b/ports/atmel-samd/boards/microchip_curiosity_circuitpython/pins.c @@ -0,0 +1,91 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2017 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +// The singleton for board.SPI() is already defined. +// board.LCD_SPI() +CIRCUITPY_BOARD_BUS_SINGLETON(lcd_spi, spi, 1) +// board.SD_SPI() +CIRCUITPY_BOARD_BUS_SINGLETON(sd_spi, spi, 2) + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_PA15) }, + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_PA20) }, + { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_PA21) }, + { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_PA27) }, + { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_PB14) }, + { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_PB15) }, + { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_PB16) }, + + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_PB23) }, + { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_PB23) }, + + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_PB22) }, + + { MP_ROM_QSTR(MP_QSTR_VREF), MP_ROM_PTR(&pin_PA03) }, + + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_PB04) }, + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_PB05) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_PB06) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_PB07) }, + { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_PB08) }, + { MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_PB09) }, + + { MP_ROM_QSTR(MP_QSTR_DAC), MP_ROM_PTR(&pin_PA02) }, + + { MP_ROM_QSTR(MP_QSTR_CAP1), MP_ROM_PTR(&pin_PB09) }, + + { MP_ROM_QSTR(MP_QSTR_LCD_CS), MP_ROM_PTR(&pin_PA07) }, + { MP_ROM_QSTR(MP_QSTR_LCD_MOSI), MP_ROM_PTR(&pin_PA04) }, + { MP_ROM_QSTR(MP_QSTR_LCD_SCK), MP_ROM_PTR(&pin_PA05) }, + { MP_ROM_QSTR(MP_QSTR_LCD_BL), MP_ROM_PTR(&pin_PA06) }, + + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_PB30) }, + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_PB31) }, + + { MP_ROM_QSTR(MP_QSTR_BLE_TX), MP_ROM_PTR(&pin_PA12) }, + { MP_ROM_QSTR(MP_QSTR_BLE_RX), MP_ROM_PTR(&pin_PA13) }, + { MP_ROM_QSTR(MP_QSTR_BLE_CLR), MP_ROM_PTR(&pin_PA14) }, + + { MP_ROM_QSTR(MP_QSTR_SD_MOSI), MP_ROM_PTR(&pin_PA16) }, + { MP_ROM_QSTR(MP_QSTR_SD_MISO), MP_ROM_PTR(&pin_PA18) }, + { MP_ROM_QSTR(MP_QSTR_SD_SCK), MP_ROM_PTR(&pin_PA17) }, + { MP_ROM_QSTR(MP_QSTR_SD_CS), MP_ROM_PTR(&pin_PA19) }, + + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_PB00) }, + { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_PB00) }, + { MP_ROM_QSTR(MP_QSTR_IMU_INT), MP_ROM_PTR(&pin_PB00) }, + + { MP_ROM_QSTR(MP_QSTR_CS), MP_ROM_PTR(&pin_PB01) }, + { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_PB01) }, + { MP_ROM_QSTR(MP_QSTR_IMU_ADDR), MP_ROM_PTR(&pin_PB01) }, + + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_PB02) }, + { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_PB02) }, + + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_PB03) }, + { MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_PB03) }, + + { MP_ROM_QSTR(MP_QSTR_DEBUG_TX), MP_ROM_PTR(&pin_PA22) }, + { MP_ROM_QSTR(MP_QSTR_DEBUG_RX), MP_ROM_PTR(&pin_PA23) }, + + { MP_OBJ_NEW_QSTR(MP_QSTR_CAN_RX), MP_ROM_PTR(&pin_PB13) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_CAN_TX), MP_ROM_PTR(&pin_PB12) }, + + { MP_OBJ_NEW_QSTR(MP_QSTR_CAN_STDBY), MP_ROM_PTR(&pin_PB17) }, + { MP_ROM_QSTR(MP_QSTR_D7), MP_ROM_PTR(&pin_PB17) }, + + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, + { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj) }, + + { MP_ROM_QSTR(MP_QSTR_SPI), MP_ROM_PTR(&board_spi_obj) }, + { MP_ROM_QSTR(MP_QSTR_LCD_SPI), MP_ROM_PTR(&board_lcd_spi_obj) }, + { MP_ROM_QSTR(MP_QSTR_SD_SPI), MP_ROM_PTR(&board_sd_spi_obj) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/atmel-samd/boards/mini_sam_m4/mpconfigboard.mk b/ports/atmel-samd/boards/mini_sam_m4/mpconfigboard.mk index 73c56fb5fba..8fae53c0101 100644 --- a/ports/atmel-samd/boards/mini_sam_m4/mpconfigboard.mk +++ b/ports/atmel-samd/boards/mini_sam_m4/mpconfigboard.mk @@ -10,9 +10,13 @@ QSPI_FLASH_FILESYSTEM = 1 EXTERNAL_FLASH_DEVICES = "W25Q16JVxM, W25Q16JVxQ" LONGINT_IMPL = MPZ +CIRCUITPY__EVE = 1 +CIRCUITPY_CODEOP = 0 CIRCUITPY_FLOPPYIO = 0 CIRCUITPY_JPEGIO = 0 +CIRCUITPY_MSGPACK = 0 CIRCUITPY_SYNTHIO = 0 +CIRCUITPY_VECTORIO = 0 CIRCUITPY_BITBANG_APA102 = 1 diff --git a/ports/atmel-samd/boards/monster_m4sk/board.c b/ports/atmel-samd/boards/monster_m4sk/board.c index 1d4fd69b7f7..1c1640da9b5 100644 --- a/ports/atmel-samd/boards/monster_m4sk/board.c +++ b/ports/atmel-samd/boards/monster_m4sk/board.c @@ -30,14 +30,13 @@ void board_init(void) { fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_PA13, &pin_PA12, NULL, false); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_PA07, // TFT_DC Command or data - &pin_PA06, // TFT_CS Chip select - &pin_PA04, // TFT_RST Reset + MP_OBJ_FROM_PTR(&pin_PA07), // TFT_DC Command or data + MP_OBJ_FROM_PTR(&pin_PA06), // TFT_CS Chip select + MP_OBJ_FROM_PTR(&pin_PA04), // TFT_RST Reset 60000000, // Baudrate 0, // Polarity 0); // Phase diff --git a/ports/atmel-samd/boards/openbook_m4/board.c b/ports/atmel-samd/boards/openbook_m4/board.c index 032ebe9f628..010679af6ee 100644 --- a/ports/atmel-samd/boards/openbook_m4/board.c +++ b/ports/atmel-samd/boards/openbook_m4/board.c @@ -39,54 +39,37 @@ void board_init(void) { fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_PB13, &pin_PB15, NULL, false); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_PB05, // EPD_DC Command or data - &pin_PB07, // EPD_CS Chip select - &pin_PA00, // EPD_RST Reset + MP_OBJ_FROM_PTR(&pin_PB05), // EPD_DC Command or data + MP_OBJ_FROM_PTR(&pin_PB07), // EPD_CS Chip select + MP_OBJ_FROM_PTR(&pin_PA00), // EPD_RST Reset 1000000, // Baudrate 0, // Polarity 0); // Phase epaperdisplay_epaperdisplay_obj_t *display = &allocate_display()->epaper_display; display->base.type = &epaperdisplay_epaperdisplay_type; - common_hal_epaperdisplay_epaperdisplay_construct(display, - bus, - start_sequence, - sizeof(start_sequence), - 0, // start up time - stop_sequence, - sizeof(stop_sequence), - 300, // width - 400, // height - 300, // RAM width - 400, // RAM height - 0, // colstart - 0, // rowstart - 270, // rotation - NO_COMMAND, // set_column_window_command - NO_COMMAND, // set_row_window_command - NO_COMMAND, // set_current_column_command - NO_COMMAND, // set_current_row_command - 0x13, // write_black_ram_command - false, // black_bits_inverted - NO_COMMAND, // write_color_ram_command (can add this for grayscale eventually) - false, // color_bits_inverted - 0x000000, // highlight_color - refresh_sequence, // refresh_display_sequence - sizeof(refresh_sequence), - 40, // refresh_time - &pin_PA01, // busy_pin - false, // busy_state - 5, // seconds_per_frame - false, // chip_select (don't always toggle chip select) - false, // grayscale - false, // acep - false, // two_byte_sequence_length - false); // address_little_endian + epaperdisplay_construct_args_t args = EPAPERDISPLAY_CONSTRUCT_ARGS_DEFAULTS; + args.bus = bus; + args.start_sequence = start_sequence; + args.start_sequence_len = sizeof(start_sequence); + args.stop_sequence = stop_sequence; + args.stop_sequence_len = sizeof(stop_sequence); + args.width = 300; + args.height = 400; + args.ram_width = 300; + args.ram_height = 400; + args.rotation = 270; + args.write_black_ram_command = 0x13; + args.refresh_sequence = refresh_sequence; + args.refresh_sequence_len = sizeof(refresh_sequence); + args.refresh_time = 40.0; + args.busy_pin = &pin_PA01; + args.seconds_per_frame = 5.0; + common_hal_epaperdisplay_epaperdisplay_construct(display, &args); } // Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/atmel-samd/boards/openbook_m4/mpconfigboard.mk b/ports/atmel-samd/boards/openbook_m4/mpconfigboard.mk index 20e9cda0eb4..aae02a95325 100644 --- a/ports/atmel-samd/boards/openbook_m4/mpconfigboard.mk +++ b/ports/atmel-samd/boards/openbook_m4/mpconfigboard.mk @@ -10,9 +10,11 @@ QSPI_FLASH_FILESYSTEM = 1 EXTERNAL_FLASH_DEVICES = GD25Q16C LONGINT_IMPL = MPZ +CIRCUITPY_FLOPPYIO = 0 +CIRCUITPY_I2CTARGET = 0 +CIRCUITPY_JPEGIO = 0 CIRCUITPY_KEYPAD = 1 +CIRCUITPY_MSGPACK = 0 CIRCUITPY_SYNTHIO = 0 -CIRCUITPY_JPEGIO = 0 -CIRCUITPY_FLOPPYIO = 0 CIRCUITPY_TERMINALIO_VT100 = 0 CIRCUITPY_TILEPALETTEMAPPER = 0 diff --git a/ports/atmel-samd/boards/pewpew_lcd/board.c b/ports/atmel-samd/boards/pewpew_lcd/board.c index 6a10132e11d..1cd74867366 100644 --- a/ports/atmel-samd/boards/pewpew_lcd/board.c +++ b/ports/atmel-samd/boards/pewpew_lcd/board.c @@ -28,7 +28,7 @@ uint8_t display_init_sequence[] = { 0xc3, 2, 0x8a, 0x2a, 0xc4, 2, 0x8a, 0xee, 0xc5, 1, 0x0e, // _VMCTR1 VCOMH = 4V, VOML = -1.1V - 0x2a, 0, // _INVOFF + 0x20, 0, // _INVOFF 0x36, 1, 0xa0, // _MADCTL // 1 clk cycle nonoverlap, 2 cycle gate rise, 3 cycle osc equalie, // fix on VTL @@ -49,14 +49,13 @@ void board_init(void) { fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_PA23, &pin_PA22, NULL, false); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_PA19, // TFT_DC Command or data - &pin_PA17, // TFT_CS Chip select - &pin_PA18, // TFT_RST Reset + MP_OBJ_FROM_PTR(&pin_PA19), // TFT_DC Command or data + MP_OBJ_FROM_PTR(&pin_PA17), // TFT_CS Chip select + MP_OBJ_FROM_PTR(&pin_PA18), // TFT_RST Reset 60000000, // Baudrate 0, // Polarity 0); // Phase diff --git a/ports/atmel-samd/boards/pewpew_lcd/mpconfigboard.mk b/ports/atmel-samd/boards/pewpew_lcd/mpconfigboard.mk index c734323a6ab..58047f2506e 100644 --- a/ports/atmel-samd/boards/pewpew_lcd/mpconfigboard.mk +++ b/ports/atmel-samd/boards/pewpew_lcd/mpconfigboard.mk @@ -41,7 +41,8 @@ CIRCUITPY_BITBANG_APA102 = 0 CIRCUITPY_BITBANGIO = 0 CIRCUITPY_BITMAPFILTER = 0 CIRCUITPY_BITMAPTOOLS = 0 -CIRCUITPY_BLEIO = 0 +CIRCUITPY_BLEIO_HCI = 0 +CIRCUITPY_BLEIO_NATIVE = 0 CIRCUITPY_BUSDEVICE = 0 CIRCUITPY_FRAMEBUFFERIO = 0 CIRCUITPY_FREQUENCYIO = 0 diff --git a/ports/atmel-samd/boards/pewpew_m4/board.c b/ports/atmel-samd/boards/pewpew_m4/board.c index 2007d755c69..2514f8523a4 100644 --- a/ports/atmel-samd/boards/pewpew_m4/board.c +++ b/ports/atmel-samd/boards/pewpew_m4/board.c @@ -57,7 +57,7 @@ uint8_t display_init_sequence[] = { 0xc3, 2, 0x8a, 0x2a, 0xc4, 2, 0x8a, 0xee, 0xc5, 1, 0x0e, // _VMCTR1 VCOMH = 4V, VOML = -1.1V - 0x2a, 0, // _INVOFF + 0x20, 0, // _INVOFF 0x36, 1, 0xa0, // _MADCTL // 1 clk cycle nonoverlap, 2 cycle gate rise, 3 cycle osc equalie, // fix on VTL @@ -78,14 +78,13 @@ void board_init(void) { fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_PA13, &pin_PA15, NULL, false); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_PA16, // TFT_DC Command or data - &pin_PA11, // TFT_CS Chip select - &pin_PA17, // TFT_RST Reset + MP_OBJ_FROM_PTR(&pin_PA16), // TFT_DC Command or data + MP_OBJ_FROM_PTR(&pin_PA11), // TFT_CS Chip select + MP_OBJ_FROM_PTR(&pin_PA17), // TFT_RST Reset 60000000, // Baudrate 0, // Polarity 0); // Phase diff --git a/ports/atmel-samd/boards/pewpew_m4/mpconfigboard.mk b/ports/atmel-samd/boards/pewpew_m4/mpconfigboard.mk index 0f239fae93a..9874cc51667 100644 --- a/ports/atmel-samd/boards/pewpew_m4/mpconfigboard.mk +++ b/ports/atmel-samd/boards/pewpew_m4/mpconfigboard.mk @@ -39,6 +39,7 @@ CIRCUITPY_BUSDEVICE = 0 CIRCUITPY_BITMAPFILTER = 0 CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_GIFIO = 0 +CIRCUITPY_LOAD_NATIVE = 0 CIRCUITPY_WATCHDOG = 0 CIRCUITPY_AUDIOIO = 1 diff --git a/ports/atmel-samd/boards/pybadge/board.c b/ports/atmel-samd/boards/pybadge/board.c index 545918374e2..6d1a2ec391a 100644 --- a/ports/atmel-samd/boards/pybadge/board.c +++ b/ports/atmel-samd/boards/pybadge/board.c @@ -28,7 +28,7 @@ uint8_t display_init_sequence[] = { 0xc3, 2, 0x8a, 0x2a, 0xc4, 2, 0x8a, 0xee, 0xc5, 1, 0x0e, // _VMCTR1 VCOMH = 4V, VOML = -1.1V - 0x2a, 0, // _INVOFF + 0x20, 0, // _INVOFF 0x36, 1, 0b10100000, // _MADCTL for rotation 0 // 1 clk cycle nonoverlap, 2 cycle gate rise, 3 cycle osc equalie, // fix on VTL @@ -51,14 +51,13 @@ void board_init(void) { fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_PB13, &pin_PB15, NULL, false); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_PB05, // TFT_DC Command or data - &pin_PB07, // TFT_CS Chip select - &pin_PA00, // TFT_RST Reset + MP_OBJ_FROM_PTR(&pin_PB05), // TFT_DC Command or data + MP_OBJ_FROM_PTR(&pin_PB07), // TFT_CS Chip select + MP_OBJ_FROM_PTR(&pin_PA00), // TFT_RST Reset 60000000, // Baudrate 0, // Polarity 0); // Phase diff --git a/ports/atmel-samd/boards/pybadge/mpconfigboard.mk b/ports/atmel-samd/boards/pybadge/mpconfigboard.mk index 70571b6c77d..9e62d1a342a 100644 --- a/ports/atmel-samd/boards/pybadge/mpconfigboard.mk +++ b/ports/atmel-samd/boards/pybadge/mpconfigboard.mk @@ -14,6 +14,7 @@ CIRCUITPY_AESIO = 0 CIRCUITPY_FLOPPYIO = 0 CIRCUITPY_FRAMEBUFFERIO = 0 CIRCUITPY_GIFIO = 0 +CIRCUITPY_EPAPERDISPLAY = 0 CIRCUITPY_I2CDISPLAYBUS = 0 CIRCUITPY_JPEGIO = 0 CIRCUITPY_KEYPAD = 1 @@ -21,6 +22,17 @@ CIRCUITPY_PARALLELDISPLAYBUS= 0 CIRCUITPY_SPITARGET = 0 CIRCUITPY_STAGE = 1 +CIRCUITPY_PICOGAME = 1 +CIRCUITPY_PICOGAME_RGB444 = 1 + +# Not enough room for picogame and these; all are only reachable through the Feather header. +CIRCUITPY_BLEIO_HCI = 0 +CIRCUITPY_FREQUENCYIO = 0 +CIRCUITPY_I2CTARGET = 0 +CIRCUITPY_PS2IO = 0 +CIRCUITPY_PULSEIO = 0 +CIRCUITPY_SDCARDIO = 0 + FROZEN_MPY_DIRS += $(TOP)/frozen/circuitpython-stage/pybadge # We don't have room for the fonts for terminalio for certain languages, diff --git a/ports/atmel-samd/boards/pycubed/board.c b/ports/atmel-samd/boards/pycubed/board.c index 7589900314a..942a7729b87 100644 --- a/ports/atmel-samd/boards/pycubed/board.c +++ b/ports/atmel-samd/boards/pycubed/board.c @@ -13,7 +13,6 @@ void board_init(void) { pwmio_pwmout_obj_t pwm; common_hal_pwmio_pwmout_construct(&pwm, &pin_PA23, 4096, 2, false); - common_hal_pwmio_pwmout_never_reset(&pwm); } // Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/atmel-samd/boards/pycubed/mpconfigboard.mk b/ports/atmel-samd/boards/pycubed/mpconfigboard.mk index 347462919f8..08d867c6e1c 100644 --- a/ports/atmel-samd/boards/pycubed/mpconfigboard.mk +++ b/ports/atmel-samd/boards/pycubed/mpconfigboard.mk @@ -27,8 +27,8 @@ CIRCUITPY_FRAMEBUFFERIO = 0 CIRCUITPY_KEYPAD = 0 CIRCUITPY_RGBMATRIX = 0 CIRCUITPY_PS2IO = 0 -CIRCUITPY_BLEIO_HCI=0 -CIRCUITPY_BLEIO=0 +CIRCUITPY_BLEIO_HCI = 0 +CIRCUITPY_BLEIO_NATIVE = 0 FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_Register diff --git a/ports/atmel-samd/boards/pycubed_mram/board.c b/ports/atmel-samd/boards/pycubed_mram/board.c index 7589900314a..942a7729b87 100644 --- a/ports/atmel-samd/boards/pycubed_mram/board.c +++ b/ports/atmel-samd/boards/pycubed_mram/board.c @@ -13,7 +13,6 @@ void board_init(void) { pwmio_pwmout_obj_t pwm; common_hal_pwmio_pwmout_construct(&pwm, &pin_PA23, 4096, 2, false); - common_hal_pwmio_pwmout_never_reset(&pwm); } // Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/atmel-samd/boards/pycubed_mram/mpconfigboard.mk b/ports/atmel-samd/boards/pycubed_mram/mpconfigboard.mk index ac8af21dcb6..52129f0b187 100644 --- a/ports/atmel-samd/boards/pycubed_mram/mpconfigboard.mk +++ b/ports/atmel-samd/boards/pycubed_mram/mpconfigboard.mk @@ -27,8 +27,8 @@ CIRCUITPY_FRAMEBUFFERIO = 0 CIRCUITPY_KEYPAD = 0 CIRCUITPY_RGBMATRIX = 0 CIRCUITPY_PS2IO = 0 -CIRCUITPY_BLEIO_HCI=0 -CIRCUITPY_BLEIO=0 +CIRCUITPY_BLEIO_HCI = 0 +CIRCUITPY_BLEIO_NATIVE = 0 FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_Register diff --git a/ports/atmel-samd/boards/pycubed_mram_v05/board.c b/ports/atmel-samd/boards/pycubed_mram_v05/board.c index 7589900314a..942a7729b87 100644 --- a/ports/atmel-samd/boards/pycubed_mram_v05/board.c +++ b/ports/atmel-samd/boards/pycubed_mram_v05/board.c @@ -13,7 +13,6 @@ void board_init(void) { pwmio_pwmout_obj_t pwm; common_hal_pwmio_pwmout_construct(&pwm, &pin_PA23, 4096, 2, false); - common_hal_pwmio_pwmout_never_reset(&pwm); } // Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/atmel-samd/boards/pycubed_mram_v05/mpconfigboard.mk b/ports/atmel-samd/boards/pycubed_mram_v05/mpconfigboard.mk index ac8af21dcb6..52129f0b187 100644 --- a/ports/atmel-samd/boards/pycubed_mram_v05/mpconfigboard.mk +++ b/ports/atmel-samd/boards/pycubed_mram_v05/mpconfigboard.mk @@ -27,8 +27,8 @@ CIRCUITPY_FRAMEBUFFERIO = 0 CIRCUITPY_KEYPAD = 0 CIRCUITPY_RGBMATRIX = 0 CIRCUITPY_PS2IO = 0 -CIRCUITPY_BLEIO_HCI=0 -CIRCUITPY_BLEIO=0 +CIRCUITPY_BLEIO_HCI = 0 +CIRCUITPY_BLEIO_NATIVE = 0 FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_Register diff --git a/ports/atmel-samd/boards/pycubed_v05/board.c b/ports/atmel-samd/boards/pycubed_v05/board.c index 7589900314a..942a7729b87 100644 --- a/ports/atmel-samd/boards/pycubed_v05/board.c +++ b/ports/atmel-samd/boards/pycubed_v05/board.c @@ -13,7 +13,6 @@ void board_init(void) { pwmio_pwmout_obj_t pwm; common_hal_pwmio_pwmout_construct(&pwm, &pin_PA23, 4096, 2, false); - common_hal_pwmio_pwmout_never_reset(&pwm); } // Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/atmel-samd/boards/pycubed_v05/mpconfigboard.mk b/ports/atmel-samd/boards/pycubed_v05/mpconfigboard.mk index 923ab2eaaef..43d3b9f1f83 100644 --- a/ports/atmel-samd/boards/pycubed_v05/mpconfigboard.mk +++ b/ports/atmel-samd/boards/pycubed_v05/mpconfigboard.mk @@ -28,8 +28,8 @@ CIRCUITPY_FRAMEBUFFERIO = 0 CIRCUITPY_KEYPAD = 0 CIRCUITPY_RGBMATRIX = 0 CIRCUITPY_PS2IO = 0 -CIRCUITPY_BLEIO_HCI=0 -CIRCUITPY_BLEIO=0 +CIRCUITPY_BLEIO_HCI = 0 +CIRCUITPY_BLEIO_NATIVE = 0 FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_Register diff --git a/ports/atmel-samd/boards/pygamer/board.c b/ports/atmel-samd/boards/pygamer/board.c index 53275ac686a..012d6571c02 100644 --- a/ports/atmel-samd/boards/pygamer/board.c +++ b/ports/atmel-samd/boards/pygamer/board.c @@ -29,7 +29,7 @@ uint8_t display_init_sequence[] = { 0xc3, 2, 0x8a, 0x2a, 0xc4, 2, 0x8a, 0xee, 0xc5, 1, 0x0e, // _VMCTR1 VCOMH = 4V, VOML = -1.1V - 0x2a, 0, // _INVOFF + 0x20, 0, // _INVOFF 0x36, 1, 0b10100000, // _MADCTL for rotation 0 // 1 clk cycle nonoverlap, 2 cycle gate rise, 3 cycle osc equalie, // fix on VTL @@ -52,14 +52,13 @@ void board_init(void) { fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_PB13, &pin_PB15, NULL, false); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_PB05, // TFT_DC Command or data - &pin_PB12, // TFT_CS Chip select - &pin_PA00, // TFT_RST Reset + MP_OBJ_FROM_PTR(&pin_PB05), // TFT_DC Command or data + MP_OBJ_FROM_PTR(&pin_PB12), // TFT_CS Chip select + MP_OBJ_FROM_PTR(&pin_PA00), // TFT_RST Reset 60000000, // Baudrate 0, // Polarity 0); // Phase diff --git a/ports/atmel-samd/boards/pygamer/mpconfigboard.mk b/ports/atmel-samd/boards/pygamer/mpconfigboard.mk index 19fa4f19b9d..0c6f16f8b63 100644 --- a/ports/atmel-samd/boards/pygamer/mpconfigboard.mk +++ b/ports/atmel-samd/boards/pygamer/mpconfigboard.mk @@ -12,6 +12,7 @@ LONGINT_IMPL = MPZ CIRCUITPY_AESIO = 0 CIRCUITPY_FLOPPYIO = 0 +CIRCUITPY_EPAPERDISPLAY = 0 CIRCUITPY_FRAMEBUFFERIO = 0 CIRCUITPY_GIFIO = 0 CIRCUITPY_I2CDISPLAYBUS = 0 diff --git a/ports/atmel-samd/boards/pyportal/mpconfigboard.h b/ports/atmel-samd/boards/pyportal/mpconfigboard.h index b84bc793170..b2cde230c46 100644 --- a/ports/atmel-samd/boards/pyportal/mpconfigboard.h +++ b/ports/atmel-samd/boards/pyportal/mpconfigboard.h @@ -27,3 +27,9 @@ // USB is always used internally so skip the pin objects for it. #define IGNORE_PIN_PA24 1 #define IGNORE_PIN_PA25 1 + +// The ESP32 running nina-fw, on board.SPI(). +#define CIRCUITPY_AIRLIFT_CS (&pin_PB14) +#define CIRCUITPY_AIRLIFT_BUSY (&pin_PB16) +#define CIRCUITPY_AIRLIFT_RESET (&pin_PB17) +#define CIRCUITPY_AIRLIFT_GPIO0 (&pin_PB15) diff --git a/ports/atmel-samd/boards/pyportal/mpconfigboard.mk b/ports/atmel-samd/boards/pyportal/mpconfigboard.mk index a056b452e08..fd7b34e8416 100644 --- a/ports/atmel-samd/boards/pyportal/mpconfigboard.mk +++ b/ports/atmel-samd/boards/pyportal/mpconfigboard.mk @@ -18,3 +18,12 @@ FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_ESP32SPI FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_Display_Text FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_FakeRequests + +# The ESP32 co-processor, shared by the core and ESP32SPI. The core uses it +# for web workflow. The flags are set one by one, because CIRCUITPY_NETWORK +# would also turn on ssl, ipaddress and so on. +CIRCUITPY_AIRLIFT = 1 +CIRCUITPY_SOCKETPOOL = 1 +CIRCUITPY_WEB_WORKFLOW = 1 +CIRCUITPY_MDNS = 0 +CIRCUITPY_SSL = 0 diff --git a/ports/atmel-samd/boards/pyruler/pins.c b/ports/atmel-samd/boards/pyruler/pins.c index 5eff2a9b514..ea9ea70b204 100644 --- a/ports/atmel-samd/boards/pyruler/pins.c +++ b/ports/atmel-samd/boards/pyruler/pins.c @@ -10,7 +10,7 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_PA08) }, - { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_PA08) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_PA08) }, { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_PA08) }, { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_PA02) }, @@ -38,7 +38,7 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_PA09) }, { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_PA06) }, - { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_PA06) }, + { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_PA06) }, { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_PA06) }, { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_PA06) }, diff --git a/ports/atmel-samd/boards/qtpy_m0_haxpress/mpconfigboard.mk b/ports/atmel-samd/boards/qtpy_m0_haxpress/mpconfigboard.mk index 1aca9134674..49ef93b62b4 100644 --- a/ports/atmel-samd/boards/qtpy_m0_haxpress/mpconfigboard.mk +++ b/ports/atmel-samd/boards/qtpy_m0_haxpress/mpconfigboard.mk @@ -9,3 +9,7 @@ CHIP_FAMILY = samd21 LONGINT_IMPL = MPZ SPI_FLASH_FILESYSTEM = 1 EXTERNAL_FLASH_DEVICES = "GD25Q16C,W25Q16JVxQ,W25Q32FV" + +CIRCUITPY_CODEOP = 0 +CIRCUITPY_ERRNO = 0 +CIRCUITPY_RAINBOWIO = 0 diff --git a/ports/atmel-samd/boards/seeeduino_wio_terminal/board.c b/ports/atmel-samd/boards/seeeduino_wio_terminal/board.c index d3d1ae3a956..81261ab8056 100644 --- a/ports/atmel-samd/boards/seeeduino_wio_terminal/board.c +++ b/ports/atmel-samd/boards/seeeduino_wio_terminal/board.c @@ -47,14 +47,13 @@ void board_init(void) { fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_PB20, &pin_PB19, NULL, false); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_PC06, // TFT_DC Command or data - &pin_PB21, // TFT_CS Chip select - &pin_PC07, // TFT_RST Reset + MP_OBJ_FROM_PTR(&pin_PC06), // TFT_DC Command or data + MP_OBJ_FROM_PTR(&pin_PB21), // TFT_CS Chip select + MP_OBJ_FROM_PTR(&pin_PC07), // TFT_RST Reset 60000000, // Baudrate 0, // Polarity 0); // Phase @@ -104,9 +103,6 @@ void board_init(void) { 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); // reset pin after fake deep sleep reset_pin_number(pin_PA18.number); diff --git a/ports/atmel-samd/boards/seeeduino_wio_terminal/mpconfigboard.mk b/ports/atmel-samd/boards/seeeduino_wio_terminal/mpconfigboard.mk index dd8afd51f6e..4ade6a14831 100644 --- a/ports/atmel-samd/boards/seeeduino_wio_terminal/mpconfigboard.mk +++ b/ports/atmel-samd/boards/seeeduino_wio_terminal/mpconfigboard.mk @@ -9,6 +9,14 @@ CHIP_FAMILY = samd51 QSPI_FLASH_FILESYSTEM = 1 EXTERNAL_FLASH_DEVICES = "W25Q32JVxQ" LONGINT_IMPL = MPZ + +CIRCUITPY__EVE = 1 +CIRCUITPY_CODEOP = 0 CIRCUITPY_FLOPPYIO = 0 -CIRCUITPY_FRAMEBUFFERIO = 0 +CIRCUITPY_JPEGIO = 0 +CIRCUITPY_MSGPACK = 0 +CIRCUITPY_PARALLELDISPLAYBUS = 0 +CIRCUITPY_RGBMATRIX = 0 +CIRCUITPY_SHARPDISPLAY = 0 CIRCUITPY_SYNTHIO = 0 +CIRCUITPY_VECTORIO = 0 diff --git a/ports/atmel-samd/boards/silicognition-m4-shim/mpconfigboard.mk b/ports/atmel-samd/boards/silicognition-m4-shim/mpconfigboard.mk index 214099ccc16..a8b0677e759 100644 --- a/ports/atmel-samd/boards/silicognition-m4-shim/mpconfigboard.mk +++ b/ports/atmel-samd/boards/silicognition-m4-shim/mpconfigboard.mk @@ -10,7 +10,9 @@ QSPI_FLASH_FILESYSTEM = 1 EXTERNAL_FLASH_DEVICES = GD25Q16C LONGINT_IMPL = MPZ +CIRCUITPY_I2CTARGET = 0 CIRCUITPY_JPEGIO = 0 +CIRCUITPY_MSGPACK = 0 CIRCUITPY_SPITARGET = 0 CIRCUITPY_SYNTHIO = 0 CIRCUITPY_TILEPALETTEMAPPER = 0 diff --git a/ports/atmel-samd/boards/snekboard/mpconfigboard.mk b/ports/atmel-samd/boards/snekboard/mpconfigboard.mk index d19e606319b..08342eead1d 100644 --- a/ports/atmel-samd/boards/snekboard/mpconfigboard.mk +++ b/ports/atmel-samd/boards/snekboard/mpconfigboard.mk @@ -9,3 +9,7 @@ CHIP_FAMILY = samd21 SPI_FLASH_FILESYSTEM = 1 EXTERNAL_FLASH_DEVICES = "W25Q16JVxQ" LONGINT_IMPL = MPZ + +CIRCUITPY_CODEOP = 0 +CIRCUITPY_ERRNO = 0 +CIRCUITPY_RAINBOWIO = 0 diff --git a/ports/atmel-samd/boards/sparkfun_redboard_turbo/mpconfigboard.mk b/ports/atmel-samd/boards/sparkfun_redboard_turbo/mpconfigboard.mk index 64049e8d598..3b5e1c49108 100755 --- a/ports/atmel-samd/boards/sparkfun_redboard_turbo/mpconfigboard.mk +++ b/ports/atmel-samd/boards/sparkfun_redboard_turbo/mpconfigboard.mk @@ -10,5 +10,7 @@ SPI_FLASH_FILESYSTEM = 1 EXTERNAL_FLASH_DEVICES = "W25Q32FV" LONGINT_IMPL = MPZ +CIRCUITPY_AUDIOBUSIO_PDMIN = 0 CIRCUITPY_CODEOP = 0 +CIRCUITPY_ERRNO = 0 CIRCUITPY_RAINBOWIO = 0 diff --git a/ports/atmel-samd/boards/sparkfun_samd51_micromod/board.c b/ports/atmel-samd/boards/sparkfun_samd51_micromod/board.c index a8153347def..14dc8873c73 100644 --- a/ports/atmel-samd/boards/sparkfun_samd51_micromod/board.c +++ b/ports/atmel-samd/boards/sparkfun_samd51_micromod/board.c @@ -12,8 +12,6 @@ void external_flash_setup(void) { // Do not reset the external flash write-protect and hold pins high - never_reset_pin_number(PIN_PB22); - never_reset_pin_number(PIN_PB23); // note: using output instead of input+pullups because the pullups are a little weak // Set the WP pin high diff --git a/ports/atmel-samd/boards/trinket_m0_haxpress/mpconfigboard.mk b/ports/atmel-samd/boards/trinket_m0_haxpress/mpconfigboard.mk index 29b5865d419..fb62ff22980 100644 --- a/ports/atmel-samd/boards/trinket_m0_haxpress/mpconfigboard.mk +++ b/ports/atmel-samd/boards/trinket_m0_haxpress/mpconfigboard.mk @@ -11,3 +11,5 @@ EXTERNAL_FLASH_DEVICES = W25Q32BV LONGINT_IMPL = MPZ CIRCUITPY_CODEOP = 0 +CIRCUITPY_PARALLELDISPLAYBUS = 0 +CIRCUITPY_RAINBOWIO = 0 diff --git a/ports/atmel-samd/boards/uartlogger2/mpconfigboard.mk b/ports/atmel-samd/boards/uartlogger2/mpconfigboard.mk index 82d7f0f43ba..226478328fd 100644 --- a/ports/atmel-samd/boards/uartlogger2/mpconfigboard.mk +++ b/ports/atmel-samd/boards/uartlogger2/mpconfigboard.mk @@ -9,8 +9,11 @@ CHIP_FAMILY = samd51 QSPI_FLASH_FILESYSTEM = 1 EXTERNAL_FLASH_DEVICES = "W25Q32JVxQ" LONGINT_IMPL = MPZ + +CIRCUITPY_I2CTARGET = 0 CIRCUITPY_SPITARGET = 0 CIRCUITPY_SYNTHIO = 0 CIRCUITPY_JPEGIO = 0 CIRCUITPY_TERMINALIO_VT100 = 0 CIRCUITPY_TILEPALETTEMAPPER = 0 +CIRCUITPY_EPAPERDISPLAY = 0 diff --git a/ports/atmel-samd/boards/uchip/board.c b/ports/atmel-samd/boards/uchip/board.c index 667e08c676f..45077e0dbaa 100644 --- a/ports/atmel-samd/boards/uchip/board.c +++ b/ports/atmel-samd/boards/uchip/board.c @@ -13,13 +13,9 @@ void board_init(void) { // BOOST_ENABLE - never_reset_pin_number(PIN_PA14); // VEXT_SELECT - never_reset_pin_number(PIN_PA15); // USB_DETECT - never_reset_pin_number(PIN_PA28); // USB_HOST_EN - never_reset_pin_number(PIN_PA27); } // Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/atmel-samd/boards/ugame10/board.c b/ports/atmel-samd/boards/ugame10/board.c index bbf3839c516..fc2725afd8f 100644 --- a/ports/atmel-samd/boards/ugame10/board.c +++ b/ports/atmel-samd/boards/ugame10/board.c @@ -28,7 +28,7 @@ uint8_t display_init_sequence[] = { 0xc3, 2, 0x8a, 0x2a, 0xc4, 2, 0x8a, 0xee, 0xc5, 1, 0x0e, // _VMCTR1 VCOMH = 4V, VOML = -1.1V - 0x2a, 0, // _INVOFF + 0x20, 0, // _INVOFF 0x36, 1, 0xa8, // _MADCTL bottom to top refresh // 1 clk cycle nonoverlap, 2 cycle gate rise, 3 cycle osc equalie, // fix on VTL @@ -53,9 +53,9 @@ void board_init(void) { busio_spi_obj_t *spi = common_hal_board_create_spi(0); common_hal_fourwire_fourwire_construct(bus, spi, - &pin_PA09, // Command or data - &pin_PA08, // Chip select - NULL, // Reset + MP_OBJ_FROM_PTR(&pin_PA09), // Command or data + MP_OBJ_FROM_PTR(&pin_PA08), // Chip select + mp_const_none, // Reset 24000000, // Baudrate 0, // Polarity 0); // Phase 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 d23ce47f58f..e2f0ab66145 100644 --- a/ports/atmel-samd/boards/winterbloom_big_honking_button/mpconfigboard.mk +++ b/ports/atmel-samd/boards/winterbloom_big_honking_button/mpconfigboard.mk @@ -21,7 +21,8 @@ CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_FRAMEBUFFERIO = 0 CIRCUITPY_FREQUENCYIO = 0 CIRCUITPY_AUDIOBUSIO = 0 -CIRCUITPY_BLEIO = 0 +CIRCUITPY_BLEIO_HCI = 0 +CIRCUITPY_BLEIO_NATIVE = 0 CIRCUITPY_DISPLAYIO = 0 CIRCUITPY_KEYPAD = 0 CIRCUITPY_I2CTARGET = 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 9b8c6b64e99..daae1f6b762 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 @@ -14,7 +14,6 @@ static mp_obj_t _bhb_read_adc(void); static mp_obj_t _bhb_init_adc(void) { claim_pin(&pin_PB08); - common_hal_never_reset_pin(&pin_PB08); /* Enable the APB clock for the ADC. */ PM->APBCMASK.reg |= PM_APBCMASK_ADC; diff --git a/ports/atmel-samd/common-hal/_pew/PewPew.c b/ports/atmel-samd/common-hal/_pew/PewPew.c index 84ff7bc16c7..2a3a4a06dc3 100644 --- a/ports/atmel-samd/common-hal/_pew/PewPew.c +++ b/ports/atmel-samd/common-hal/_pew/PewPew.c @@ -38,7 +38,7 @@ void pewpew_interrupt_handler(uint8_t index) { tc->COUNT16.INTFLAG.reg = TC_INTFLAG_MC0; } -void pew_init() { +void pew_init(void) { pew_obj_t *pew = MP_STATE_VM(pew_singleton); common_hal_digitalio_digitalinout_switch_to_input(pew->buttons, PULL_UP); @@ -97,14 +97,24 @@ void pew_init() { } } -void pew_reset(void) { - if (pewpew_tc_index != 0xff) { - tc_reset(tc_insts[pewpew_tc_index]); - pewpew_tc_index = 0xff; +void pew_deinit(void) { + if (pewpew_tc_index == 0xff) { + return; } + Tc *tc = tc_insts[pewpew_tc_index]; + tc->COUNT16.INTENCLR.reg = TC_INTENCLR_MC0; + tc_disable_interrupts(pewpew_tc_index); + tc_reset(tc); + set_timer_handler(true, pewpew_tc_index, TC_HANDLER_NO_INTERRUPT); + turn_off_clocks(TIMER_TYPE_TC, pewpew_tc_index); + pewpew_tc_index = 0xff; +} + +void pew_reset(void) { + pew_deinit(); MP_STATE_VM(pew_singleton) = NULL; } -uint16_t pew_get_ticks() { +uint16_t pew_get_ticks(void) { return pewpew_ticks; } diff --git a/ports/atmel-samd/common-hal/_pew/PewPew.h b/ports/atmel-samd/common-hal/_pew/PewPew.h index c3d1b52f297..7be95d53f83 100644 --- a/ports/atmel-samd/common-hal/_pew/PewPew.h +++ b/ports/atmel-samd/common-hal/_pew/PewPew.h @@ -21,6 +21,7 @@ typedef struct { } pew_obj_t; void pew_init(void); -void pewpew_interrupt_handler(uint8_t index); +void pew_deinit(void); void pew_reset(void); +void pewpew_interrupt_handler(uint8_t index); uint16_t pew_get_ticks(void); diff --git a/ports/atmel-samd/common-hal/alarm/__init__.c b/ports/atmel-samd/common-hal/alarm/__init__.c index 483aa1a9679..153647f4e89 100644 --- a/ports/atmel-samd/common-hal/alarm/__init__.c +++ b/ports/atmel-samd/common-hal/alarm/__init__.c @@ -127,13 +127,10 @@ mp_obj_t common_hal_alarm_light_sleep_until_alarms(size_t n_alarms, const mp_obj } void common_hal_alarm_set_deep_sleep_alarms(size_t n_alarms, const mp_obj_t *alarms, size_t n_dios, digitalio_digitalinout_obj_t **preserve_dios) { - if (n_dios > 0) { - mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_preserve_dios); - } _setup_sleep_alarms(true, n_alarms, alarms); } -void NORETURN common_hal_alarm_enter_deep_sleep(void) { +void MP_NORETURN common_hal_alarm_enter_deep_sleep(void) { alarm_pin_pinalarm_prepare_for_deep_sleep(); alarm_time_timealarm_prepare_for_deep_sleep(); // port_disable_tick(); // TODO: Required for SAMD? diff --git a/ports/atmel-samd/common-hal/alarm/touch/TouchAlarm.c b/ports/atmel-samd/common-hal/alarm/touch/TouchAlarm.c index 44396fa8e8a..de98b7ec85a 100644 --- a/ports/atmel-samd/common-hal/alarm/touch/TouchAlarm.c +++ b/ports/atmel-samd/common-hal/alarm/touch/TouchAlarm.c @@ -7,6 +7,6 @@ #include "shared-bindings/alarm/touch/TouchAlarm.h" #include "shared-bindings/microcontroller/__init__.h" -void common_hal_alarm_touch_touchalarm_construct(alarm_touch_touchalarm_obj_t *self, const mcu_pin_obj_t *pin) { +MP_NORETURN void common_hal_alarm_touch_touchalarm_construct(alarm_touch_touchalarm_obj_t *self, const mcu_pin_obj_t *pin) { mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_TouchAlarm); } diff --git a/ports/atmel-samd/common-hal/analogio/AnalogIn.c b/ports/atmel-samd/common-hal/analogio/AnalogIn.c index c633cf44b67..2e9b38b8060 100644 --- a/ports/atmel-samd/common-hal/analogio/AnalogIn.c +++ b/ports/atmel-samd/common-hal/analogio/AnalogIn.c @@ -64,43 +64,23 @@ void common_hal_analogio_analogin_deinit(analogio_analogin_obj_t *self) { self->pin = NULL; } -void analogin_reset() { -} - 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. struct adc_sync_descriptor adc; - samd_peripherals_adc_setup(&adc, self->instance); - // Full scale is 3.3V (VDDANA) = 65535. // On SAMD21, INTVCC1 is 0.5*VDDANA. On SAMD51, INTVCC1 is 1*VDDANA. // So on SAMD21 only, divide the input by 2, so full scale will match 0.5*VDDANA. - adc_sync_set_reference(&adc, ADC_REFCTRL_REFSEL_INTVCC1_Val); #ifdef SAMD21 - adc_sync_set_channel_gain(&adc, self->channel, ADC_INPUTCTRL_GAIN_DIV2_Val); + const uint8_t gain = ADC_INPUTCTRL_GAIN_DIV2_Val; + #else + const uint8_t gain = 0; // ignored #endif - - adc_sync_set_resolution(&adc, ADC_CTRLB_RESSEL_12BIT_Val); - - adc_sync_enable_channel(&adc, self->channel); - - // We need to set the inputs because the above channel enable only enables the ADC. - adc_sync_set_inputs(&adc, self->channel, ADC_INPUTCTRL_MUXNEG_GND_Val, self->channel); - - // Read twice and discard first result, as recommended in section 14 of - // http://www.atmel.com/images/Atmel-42645-ADC-Configurations-with-Examples_ApplicationNote_AT11481.pdf - // "Discard the first conversion result whenever there is a change in ADC configuration - // like voltage reference / ADC channel change" - // 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); - + samd_peripherals_adc_start(&adc, self->instance, ADC_REFCTRL_REFSEL_INTVCC1_Val, gain, self->channel); + uint16_t value = samd_peripherals_adc_read(&adc); adc_sync_deinit(&adc); // Stretch 12-bit ADC reading to 16-bit range return (value << 4) | (value >> 8); diff --git a/ports/atmel-samd/common-hal/analogio/AnalogIn.h b/ports/atmel-samd/common-hal/analogio/AnalogIn.h index 5d97ddcc156..4573fc1c647 100644 --- a/ports/atmel-samd/common-hal/analogio/AnalogIn.h +++ b/ports/atmel-samd/common-hal/analogio/AnalogIn.h @@ -16,5 +16,3 @@ typedef struct { Adc *instance; uint8_t channel; } analogio_analogin_obj_t; - -void analogin_reset(void); diff --git a/ports/atmel-samd/common-hal/analogio/AnalogOut.c b/ports/atmel-samd/common-hal/analogio/AnalogOut.c index e9c817501f9..ede58a2acc1 100644 --- a/ports/atmel-samd/common-hal/analogio/AnalogOut.c +++ b/ports/atmel-samd/common-hal/analogio/AnalogOut.c @@ -16,6 +16,7 @@ #include "atmel_start_pins.h" #include "hal/include/hal_dac_sync.h" +#include "samd/clocks.h" #include "hpl/gclk/hpl_gclk_base.h" #include "peripheral_clk_config.h" @@ -28,11 +29,20 @@ (defined(SAM_D5X_E5X) && defined(PIN_PA05) && !defined(IGNORE_PIN_PA05)) \ ) +#if HAVE_ANALOGOUT +// Mark the object deinited: deinited() is true and deinit() does nothing. +static void mark_deinit(analogio_analogout_obj_t *self) { + self->pin = NULL; +} +#endif + void common_hal_analogio_analogout_construct(analogio_analogout_obj_t *self, const mcu_pin_obj_t *pin) { #if !HAVE_ANALOGOUT mp_raise_NotImplementedError(MP_ERROR_TEXT("No DAC on chip")); #else + // Ensure the object starts in its deinit state. + mark_deinit(self); uint8_t channel; switch (pin->number) { @@ -54,7 +64,6 @@ void common_hal_analogio_analogout_construct(analogio_analogout_obj_t *self, } self->channel = channel; - self->pin = pin; #ifdef SAM_D5X_E5X hri_mclk_set_APBDMASK_DAC_bit(MCLK); @@ -87,6 +96,9 @@ void common_hal_analogio_analogout_construct(analogio_analogout_obj_t *self, mp_raise_OSError(MP_EIO); return; } + // Set the pin only after the last raise: until then the object reads as + // deinited, so its finaliser does nothing. + self->pin = pin; claim_pin(pin); gpio_set_pin_function(pin->number, GPIO_PIN_FUNCTION_B); @@ -99,7 +111,7 @@ bool common_hal_analogio_analogout_deinited(analogio_analogout_obj_t *self) { #if !HAVE_ANALOGOUT return false; #else - return self->deinited; + return self->pin == NULL; #endif } @@ -110,18 +122,22 @@ void common_hal_analogio_analogout_deinit(analogio_analogout_obj_t *self) { } dac_sync_disable_channel(&self->descriptor, self->channel); reset_pin_number(self->pin->number); - self->pin = NULL; + mark_deinit(self); // Only deinit the DAC on the SAMD51 if both outputs are free. #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); + // Turn off the DAC clocks to save power. + disconnect_gclk_from_peripheral(CONF_GCLK_DAC_SRC, DAC_GCLK_ID); + #ifdef SAMD21 + _pm_disable_bus_clock(PM_BUS_APBC, DAC); + #endif #ifdef SAM_D5X_E5X + hri_mclk_clear_APBDMASK_DAC_bit(MCLK); } #endif - self->deinited = true; - // TODO(tannewt): Turn off the DAC clocks to save power. #endif } @@ -133,17 +149,3 @@ void common_hal_analogio_analogout_set_value(analogio_analogout_obj_t *self, dac_sync_write(&self->descriptor, self->channel, &value, 1); #endif } - -void analogout_reset(void) { - #if HAVE_ANALOGOUT - #ifdef SAMD21 - while (DAC->STATUS.reg & DAC_STATUS_SYNCBUSY) { - } - #endif - #ifdef SAM_D5X_E5X - while (DAC->SYNCBUSY.reg & DAC_SYNCBUSY_SWRST) { - } - #endif - DAC->CTRLA.reg |= DAC_CTRLA_SWRST; - #endif -} diff --git a/ports/atmel-samd/common-hal/analogio/AnalogOut.h b/ports/atmel-samd/common-hal/analogio/AnalogOut.h index 7260444d26e..953489c3a9a 100644 --- a/ports/atmel-samd/common-hal/analogio/AnalogOut.h +++ b/ports/atmel-samd/common-hal/analogio/AnalogOut.h @@ -17,7 +17,4 @@ typedef struct { const mcu_pin_obj_t *pin; struct dac_sync_descriptor descriptor; uint8_t channel; - bool deinited; } analogio_analogout_obj_t; - -void analogout_reset(void); diff --git a/ports/atmel-samd/common-hal/audiobusio/I2SOut.c b/ports/atmel-samd/common-hal/audiobusio/I2SOut.c index 178db2f07d0..5d1b021fb85 100644 --- a/ports/atmel-samd/common-hal/audiobusio/I2SOut.c +++ b/ports/atmel-samd/common-hal/audiobusio/I2SOut.c @@ -9,6 +9,51 @@ #include "mpconfigport.h" +#include "i2s_shared.h" +#include "samd/clocks.h" + +#ifdef SAMD21 +#include "hpl/pm/hpl_pm_base.h" +#endif + +// Shared I2S reference count. See i2s_shared.h. +static uint8_t i2s_user_count = 0; + +void i2s_acquire(void) { + i2s_user_count++; +} + +void i2s_release(void) { + i2s_user_count--; + if (i2s_user_count == 0) { + // Fully power the I2S peripheral down; undo what turn_on_i2s() did. + // Disable it first, so the next user finds ENABLE == 0 and resets it, + // instead of starting from the last user's configuration. + // The I2S can't disable without a clock on its clock units: the + // ENABLE sync never finishes. Its users have disconnected theirs, so + // connect one for now: the 2MHz GCLK5 on SAMD51, GCLK0 on SAMD21. + #ifdef SAM_D5X_E5X + const uint8_t sync_gclk = 5; + #else + const uint8_t sync_gclk = 0; + #endif + connect_gclk_to_peripheral(sync_gclk, I2S_GCLK_ID_0); + connect_gclk_to_peripheral(sync_gclk, I2S_GCLK_ID_1); + if (I2S->CTRLA.bit.ENABLE == 1) { + I2S->CTRLA.bit.ENABLE = 0; + while (I2S->SYNCBUSY.bit.ENABLE == 1) { + } + } + disconnect_gclk_from_peripheral(sync_gclk, I2S_GCLK_ID_0); + disconnect_gclk_from_peripheral(sync_gclk, I2S_GCLK_ID_1); + #ifdef SAM_D5X_E5X + MCLK->APBDMASK.reg &= ~MCLK_APBDMASK_I2S; + #else + _pm_disable_bus_clock(PM_BUS_APBC, I2S); + #endif + } +} + // Some boards don't implement I2SOut, so suppress any routines from here. #if CIRCUITPY_AUDIOBUSIO_I2SOUT @@ -34,6 +79,7 @@ #include "samd/dma.h" #include "samd/events.h" #include "samd/i2s.h" +#include "i2s_shared.h" #include "samd/pins.h" #include "samd/timers.h" @@ -47,37 +93,14 @@ #define SERCTRL(name) I2S_TXCTRL_##name #endif -void i2sout_reset(void) { - // Make sure the I2S peripheral is running so we can see if the resources we need are free. - #ifdef SAM_D5X_E5X - // Connect the clock units to the 2MHz clock. It can't disable without it. - connect_gclk_to_peripheral(5, I2S_GCLK_ID_0); - connect_gclk_to_peripheral(5, I2S_GCLK_ID_1); - #endif - if (I2S->CTRLA.bit.ENABLE == 1) { - I2S->CTRLA.bit.ENABLE = 0; - while (I2S->SYNCBUSY.bit.ENABLE == 1) { - } - } - - // Make sure the I2S peripheral is running so we can see if the resources we need are free. - #ifdef SAM_D5X_E5X - // Connect the clock units to the 2MHz clock by default. They can't reset without it. - disconnect_gclk_from_peripheral(5, I2S_GCLK_ID_0); - disconnect_gclk_from_peripheral(5, I2S_GCLK_ID_1); - - hri_mclk_clear_APBDMASK_I2S_bit(MCLK); - #endif - - #ifdef SAMD21 - _pm_disable_bus_clock(PM_BUS_APBC, I2S); - #endif -} - // 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, const mcu_pin_obj_t *main_clock, bool left_justified) { + const mcu_pin_obj_t *data, const mcu_pin_obj_t *main_clock, bool left_justified, + bool external_clock) { + if (external_clock) { + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_external_clock); + } if (main_clock != NULL) { mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_main_clock); } @@ -147,8 +170,9 @@ void common_hal_audiobusio_i2sout_construct(audiobusio_i2sout_obj_t *self, self->clock_unit = ws_clock_unit; self->serializer = serializer; + // Check the shared I2S peripheral before refcounting it, so a raise here + // doesn't leak the reference. turn_on_i2s(); - if (I2S->CTRLA.bit.ENABLE == 0) { I2S->CTRLA.bit.SWRST = 1; while (I2S->CTRLA.bit.SWRST == 1) { @@ -165,6 +189,9 @@ void common_hal_audiobusio_i2sout_construct(audiobusio_i2sout_obj_t *self, } #endif } + i2s_acquire(); + + self->gclk = 0xff; #ifdef SAM_D5X_E5X #define GPIO_I2S_FUNCTION GPIO_PIN_FUNCTION_J @@ -199,18 +226,35 @@ void common_hal_audiobusio_i2sout_deinit(audiobusio_i2sout_obj_t *self) { return; } + // Stop the DMA channel, serializer and clock unit, and release the GCLK. + // A GCLK is held from play() until stop(). Don't touch the serializer or + // clock unit otherwise: their enable bits sync on that GCLK, so with it + // disconnected the SYNCBUSY wait never ends. + if (self->gclk != 0xff) { + common_hal_audiobusio_i2sout_stop(self); + } + reset_pin_number(self->bit_clock->number); self->bit_clock = NULL; reset_pin_number(self->word_select->number); self->word_select = NULL; reset_pin_number(self->data->number); + self->data = NULL; + + // Fully power the I2S peripheral down if we were its last user. + i2s_release(); } 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)) { + // Stop if playing, or if a GCLK is still held from a play() that raised + // after taking it. Otherwise this play() would overwrite self->gclk and leak it. + if (common_hal_audiobusio_i2sout_get_playing(self) || self->gclk != 0xff) { common_hal_audiobusio_i2sout_stop(self); } + + audiosample_check(sample); + #ifdef SAMD21 if ((I2S->CTRLA.vec.CKEN & (1 << self->clock_unit)) == 1) { mp_raise_RuntimeError(MP_ERROR_TEXT("Clock unit in use")); @@ -225,7 +269,6 @@ void common_hal_audiobusio_i2sout_play(audiobusio_i2sout_obj_t *self, if (gclk > GCLK_GEN_NUM) { mp_raise_RuntimeError(MP_ERROR_TEXT("No free GCLKs")); } - self->gclk = gclk; uint32_t clkctrl = I2S_CLKCTRL_MCKSEL_GCLK | I2S_CLKCTRL_NBSLOTS(1) | @@ -270,6 +313,8 @@ void common_hal_audiobusio_i2sout_play(audiobusio_i2sout_obj_t *self, #endif // The DFLL is always a 48MHz clock + // Hold the GCLK only once it's running: deinit() calls stop() while one is held. + self->gclk = gclk; enable_clock_generator(self->gclk, CLOCK_48MHZ, divisor); connect_gclk_to_peripheral(self->gclk, I2S_GCLK_ID_0 + self->clock_unit); @@ -360,12 +405,17 @@ void common_hal_audiobusio_i2sout_stop(audiobusio_i2sout_obj_t *self) { } } #endif - disconnect_gclk_from_peripheral(self->gclk, I2S_GCLK_ID_0 + self->clock_unit); - disable_clock_generator(self->gclk); + // Release the GCLK once and forget it, so a later stop() or deinit() + // doesn't disable a generator that another object now owns. + if (self->gclk != 0xff) { + disconnect_gclk_from_peripheral(self->gclk, I2S_GCLK_ID_0 + self->clock_unit); + disable_clock_generator(self->gclk); + self->gclk = 0xff; - #ifdef SAM_D5X_E5X - connect_gclk_to_peripheral(5, I2S_GCLK_ID_0 + self->clock_unit); - #endif + #ifdef SAM_D5X_E5X + connect_gclk_to_peripheral(5, I2S_GCLK_ID_0 + self->clock_unit); + #endif + } self->playing = false; } diff --git a/ports/atmel-samd/common-hal/audiobusio/I2SOut.h b/ports/atmel-samd/common-hal/audiobusio/I2SOut.h index 617221adf21..5afb432fa95 100644 --- a/ports/atmel-samd/common-hal/audiobusio/I2SOut.h +++ b/ports/atmel-samd/common-hal/audiobusio/I2SOut.h @@ -28,6 +28,5 @@ typedef struct { audio_dma_t dma; } audiobusio_i2sout_obj_t; -void i2sout_reset(void); #endif // CIRCUITPY_AUDIOBUSIO_I2SOUT diff --git a/ports/atmel-samd/common-hal/audiobusio/PDMIn.c b/ports/atmel-samd/common-hal/audiobusio/PDMIn.c index a1a67d04082..1fd055938ee 100644 --- a/ports/atmel-samd/common-hal/audiobusio/PDMIn.c +++ b/ports/atmel-samd/common-hal/audiobusio/PDMIn.c @@ -4,6 +4,8 @@ // // SPDX-License-Identifier: MIT +#if CIRCUITPY_AUDIOBUSIO_PDMIN + #include #include #include @@ -22,6 +24,7 @@ #include "hal/include/hal_gpio.h" #include "hal/utils/include/utils.h" +#include "i2s_shared.h" #include "samd/clocks.h" #include "samd/events.h" #include "samd/i2s.h" @@ -47,7 +50,8 @@ // Set by interrupt handler when DMA block has finished transferring. static volatile bool pdmin_dma_block_done; // Event channel used to trigger interrupt. Set to invalid value EVSYS_SYNCH_NUM when not in use. -static uint8_t pdmin_event_channel; +// EVSYS_SYNCH_NUM means none. pdmin_reset() used to set this at every VM start. +static uint8_t pdmin_event_channel = EVSYS_SYNCH_NUM; void pdmin_evsys_handler(void) { if (pdmin_event_channel < EVSYS_SYNCH_NUM && event_interrupt_active(pdmin_event_channel)) { @@ -55,21 +59,13 @@ void pdmin_evsys_handler(void) { } } -void pdmin_reset(void) { - pdmin_dma_block_done = false; - pdmin_event_channel = EVSYS_SYNCH_NUM; - - while (I2S->SYNCBUSY.reg & I2S_SYNCBUSY_ENABLE) { - } - I2S->INTENCLR.reg = I2S_INTENCLR_MASK; - I2S->INTFLAG.reg = I2S_INTFLAG_MASK; - I2S->CTRLA.reg &= ~I2S_SYNCBUSY_ENABLE; - while (I2S->SYNCBUSY.reg & I2S_SYNCBUSY_ENABLE) { - } - I2S->CTRLA.reg = I2S_CTRLA_SWRST; +// Caller validates that pins are free. +// Mark the object deinited: deinited() is true and deinit() does nothing. +static void mark_deinit(audiobusio_pdmin_obj_t *self) { + self->clock_pin = NULL; + self->data_pin = NULL; } -// 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, @@ -77,7 +73,10 @@ void common_hal_audiobusio_pdmin_construct(audiobusio_pdmin_obj_t *self, uint8_t bit_depth, bool mono, uint8_t oversample) { - self->clock_pin = clock_pin; // PA10, PA20 -> SCK0, PB11 -> SCK1 + // Ensure the object starts in its deinit state. + mark_deinit(self); + + // PA10, PA20 -> SCK0, PB11 -> SCK1 #ifdef SAMD21 if (clock_pin == &pin_PA10 #if defined(PIN_PA20) && !defined(IGNORE_PIN_PA20) @@ -105,7 +104,7 @@ void common_hal_audiobusio_pdmin_construct(audiobusio_pdmin_obj_t *self, raise_ValueError_invalid_pin_name(MP_QSTR_clock); } - self->data_pin = data_pin; // PA07, PA19 -> SD0, PA08, PB16 -> SD1 + // PA07, PA19 -> SD0, PA08, PB16 -> SD1 #ifdef SAMD21 if (false @@ -140,6 +139,19 @@ void common_hal_audiobusio_pdmin_construct(audiobusio_pdmin_obj_t *self, mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("Only 8 or 16 bit mono with %dx oversampling supported."), OVERSAMPLING); } + uint32_t clock_divisor = (uint32_t)roundf(48000000.0f / sample_rate / oversample); + float mic_clock_freq = 48000000.0f / clock_divisor; + self->sample_rate = mic_clock_freq / oversample; + if (mic_clock_freq < MIN_MIC_CLOCK || clock_divisor == 0) { + mp_raise_ValueError(MP_ERROR_TEXT("sampling rate out of range")); + } + // Find a free GCLK to generate the MCLK signal. + uint8_t gclk = find_free_gclk(clock_divisor); + if (gclk > GCLK_GEN_NUM) { + mp_raise_RuntimeError(MP_ERROR_TEXT("No free GCLKs")); + } + self->gclk = gclk; + turn_on_i2s(); if (I2S->CTRLA.bit.ENABLE == 0) { @@ -158,6 +170,7 @@ void common_hal_audiobusio_pdmin_construct(audiobusio_pdmin_obj_t *self, } #endif } + i2s_acquire(); #ifdef SAM_D5X_E5X #define GPIO_I2S_FUNCTION GPIO_PIN_FUNCTION_J #endif @@ -165,18 +178,6 @@ void common_hal_audiobusio_pdmin_construct(audiobusio_pdmin_obj_t *self, #define GPIO_I2S_FUNCTION GPIO_PIN_FUNCTION_G #endif - uint32_t clock_divisor = (uint32_t)roundf(48000000.0f / sample_rate / oversample); - float mic_clock_freq = 48000000.0f / clock_divisor; - self->sample_rate = mic_clock_freq / oversample; - if (mic_clock_freq < MIN_MIC_CLOCK || clock_divisor == 0) { - mp_raise_ValueError(MP_ERROR_TEXT("sampling rate out of range")); - } - // Find a free GCLK to generate the MCLK signal. - uint8_t gclk = find_free_gclk(clock_divisor); - if (gclk > GCLK_GEN_NUM) { - mp_raise_RuntimeError(MP_ERROR_TEXT("No free GCLKs")); - } - self->gclk = gclk; enable_clock_generator(self->gclk, CLOCK_48MHZ, clock_divisor); connect_gclk_to_peripheral(self->gclk, I2S_GCLK_ID_0 + self->clock_unit); @@ -216,8 +217,13 @@ void common_hal_audiobusio_pdmin_construct(audiobusio_pdmin_obj_t *self, claim_pin(clock_pin); claim_pin(data_pin); - gpio_set_pin_function(self->clock_pin->number, GPIO_I2S_FUNCTION); - gpio_set_pin_function(self->data_pin->number, GPIO_I2S_FUNCTION); + gpio_set_pin_function(clock_pin->number, GPIO_I2S_FUNCTION); + gpio_set_pin_function(data_pin->number, GPIO_I2S_FUNCTION); + + // Set the pins last: until then the object reads as deinited, so its + // finaliser does nothing if the constructor raised. + self->clock_pin = clock_pin; + self->data_pin = data_pin; self->bytes_per_sample = oversample >> 3; self->bit_depth = bit_depth; @@ -235,15 +241,15 @@ void common_hal_audiobusio_pdmin_deinit(audiobusio_pdmin_obj_t *self) { i2s_set_serializer_enable(self->serializer, false); i2s_set_clock_unit_enable(self->clock_unit, false); - i2s_set_enable(false); - disconnect_gclk_from_peripheral(self->gclk, I2S_GCLK_ID_0 + self->clock_unit); disable_clock_generator(self->gclk); reset_pin_number(self->clock_pin->number); reset_pin_number(self->data_pin->number); - self->clock_pin = NULL; - self->data_pin = NULL; + mark_deinit(self); + + // Fully power the I2S peripheral down if we were its last user. + i2s_release(); } uint8_t common_hal_audiobusio_pdmin_get_bit_depth(audiobusio_pdmin_obj_t *self) { @@ -364,8 +370,14 @@ 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 = dma_allocate_channel(true); - pdmin_event_channel = find_sync_event_channel_raise(); + // Find the event channel first: it raises if there isn't one, and the DMA + // channel would leak if it were already allocated. + uint8_t event_channel = find_sync_event_channel_raise(); + uint8_t dma_channel = dma_allocate_audio_channel(); + if (dma_channel == NO_DMA_CHANNEL) { + mp_raise_RuntimeError(MP_ERROR_TEXT("No DMA channel found")); + } + pdmin_event_channel = event_channel; pdmin_dma_block_done = false; // We allocate two buffers on the stack to use for double buffering. @@ -482,3 +494,5 @@ uint32_t common_hal_audiobusio_pdmin_record_to_buffer(audiobusio_pdmin_obj_t *se return values_output; } + +#endif // CIRCUITPY_AUDIOBUSIO_PDMIN diff --git a/ports/atmel-samd/common-hal/audiobusio/PDMIn.h b/ports/atmel-samd/common-hal/audiobusio/PDMIn.h index 4d2904e1075..2d37776f336 100644 --- a/ports/atmel-samd/common-hal/audiobusio/PDMIn.h +++ b/ports/atmel-samd/common-hal/audiobusio/PDMIn.h @@ -23,8 +23,6 @@ typedef struct { uint8_t gclk; } audiobusio_pdmin_obj_t; -void pdmin_reset(void); - void pdmin_evsys_handler(void); void pdmin_background(void); diff --git a/ports/atmel-samd/common-hal/audiobusio/i2s_shared.h b/ports/atmel-samd/common-hal/audiobusio/i2s_shared.h new file mode 100644 index 00000000000..089e6d4abb4 --- /dev/null +++ b/ports/atmel-samd/common-hal/audiobusio/i2s_shared.h @@ -0,0 +1,17 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-License-Identifier: MIT + +// Shared reference counting for the single I2S peripheral, used by both +// audiobusio I2SOut and PDMIn. The implementations are in I2SOut.c, outside +// its CIRCUITPY_AUDIOBUSIO_I2SOUT guard, so they exist on boards with PDMIn +// but no I2SOut. + +#pragma once + +// Turn the I2S peripheral's clocks on (idempotent; call once per user). +void i2s_acquire(void); + +// Drop one reference and fully power the I2S peripheral down if this was the +// last user. +void i2s_release(void); diff --git a/ports/atmel-samd/common-hal/audioio/AudioOut.c b/ports/atmel-samd/common-hal/audioio/AudioOut.c index f7af5e292a7..33010990147 100644 --- a/ports/atmel-samd/common-hal/audioio/AudioOut.c +++ b/ports/atmel-samd/common-hal/audioio/AudioOut.c @@ -32,6 +32,7 @@ #include "samd/events.h" #include "samd/pins.h" #include "samd/timers.h" +#include "samd/clocks.h" #ifdef SAMD21 static void ramp_value(uint16_t start, uint16_t end) { @@ -120,6 +121,11 @@ void common_hal_audioio_audioout_construct(audioio_audioout_obj_t *self, self->left_channel = left_channel; audio_dma_init(&self->left_dma); + // Initialized to an invalid value so deinit() can tell whether the timer + // (and its event channel) were ever allocated. + self->tc_index = 0xff; + self->tc_to_dac_event_channel = 0xff; + #ifdef SAM_D5X_E5X hri_mclk_set_APBDMASK_DAC_bit(MCLK); #endif @@ -289,19 +295,43 @@ void common_hal_audioio_audioout_deinit(audioio_audioout_obj_t *self) { DAC->CTRLA.reg |= DAC_CTRLA_SWRST; - // TODO(tannewt): Turn off the DAC clocks to save power. - DAC->CTRLA.bit.ENABLE = 0; - disable_event_channel(self->tc_to_dac_event_channel); + if (self->tc_to_dac_event_channel != 0xff) { + disable_event_channel(self->tc_to_dac_event_channel); + disable_event_user(EVSYS_ID_USER_DAC_START); + #ifdef SAM_D5X_E5X + disable_event_user(EVSYS_ID_USER_DAC_START_1); + #endif + self->tc_to_dac_event_channel = 0xff; + } - tc_set_enable(tc_insts[self->tc_index], false); + if (self->tc_index != 0xff) { + Tc *t = tc_insts[self->tc_index]; + tc_set_enable(t, false); + tc_reset(t); + set_timer_handler(true, self->tc_index, TC_HANDLER_NO_INTERRUPT); + turn_off_clocks(TIMER_TYPE_TC, self->tc_index); + self->tc_index = 0xff; + } + + // Turn off the DAC clocks to save power. The construct re-enables them. + disconnect_gclk_from_peripheral(CONF_GCLK_DAC_SRC, DAC_GCLK_ID); + #ifdef SAMD21 + _pm_disable_bus_clock(PM_BUS_APBC, DAC); + #endif + #ifdef SAM_D5X_E5X + hri_mclk_clear_APBDMASK_DAC_bit(MCLK); + #endif reset_pin_number(self->left_channel->number); self->left_channel = NULL; #ifdef SAM_D5X_E5X - reset_pin_number(self->right_channel->number); - self->right_channel = NULL; + // right_channel is NULL for mono. + if (self->right_channel != NULL) { + reset_pin_number(self->right_channel->number); + self->right_channel = NULL; + } #endif } @@ -331,6 +361,9 @@ void common_hal_audioio_audioout_play(audioio_audioout_obj_t *self, if (common_hal_audioio_audioout_get_playing(self)) { common_hal_audioio_audioout_stop(self); } + + audiosample_check(sample); + audio_dma_result result = AUDIO_DMA_OK; uint32_t sample_rate = audiosample_get_sample_rate(sample); #ifdef SAMD21 diff --git a/ports/atmel-samd/common-hal/busio/I2C.c b/ports/atmel-samd/common-hal/busio/I2C.c index e13b5410ae3..4495498e62f 100644 --- a/ports/atmel-samd/common-hal/busio/I2C.c +++ b/ports/atmel-samd/common-hal/busio/I2C.c @@ -55,6 +55,14 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, // Ensure the object starts in its deinit state. common_hal_busio_i2c_mark_deinit(self); + // Check the frequency before setting anything up, so there's nothing to undo. + // The maximum frequency divisor gives a clock rate of around 48MHz/2/255 + // but set_baudrate does not diagnose this problem. (This is not the + // exact cutoff, but no frequency well under 100kHz is available) + if (frequency < 95000) { + mp_arg_error_invalid(MP_QSTR_frequency); + } + Sercom *sercom = samd_i2c_get_sercom(scl, sda, &sercom_index, &sda_pinmux, &scl_pinmux); if (sercom == NULL) { raise_ValueError_invalid_pins(); @@ -97,20 +105,20 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, mp_raise_OSError(MP_EIO); } - // clkrate is always 0. baud_rate is in kHz. - // Frequency must be set before the I2C device is enabled. - // The maximum frequency divisor gives a clock rate of around 48MHz/2/255 - // but set_baudrate does not diagnose this problem. (This is not the - // exact cutoff, but no frequency well under 100kHz is available) - if ((frequency < 95000) || - (i2c_m_sync_set_baudrate(&self->i2c_desc, 0, frequency / 1000) != ERR_NONE)) { - common_hal_busio_i2c_deinit(self); + // clkrate is always 0. baud_rate is in kHz. + if (i2c_m_sync_set_baudrate(&self->i2c_desc, 0, frequency / 1000) != ERR_NONE) { + // The object is still marked deinited, so deinit() would do nothing. + i2c_m_sync_deinit(&self->i2c_desc); + reset_pin_number(sda->number); + reset_pin_number(scl->number); mp_arg_error_invalid(MP_QSTR_frequency); } if (i2c_m_sync_enable(&self->i2c_desc) != ERR_NONE) { - common_hal_busio_i2c_deinit(self); + i2c_m_sync_deinit(&self->i2c_desc); + reset_pin_number(sda->number); + reset_pin_number(scl->number); mp_raise_OSError(MP_EIO); } @@ -118,9 +126,6 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, self->scl_pin = scl->number; claim_pin(sda); claim_pin(scl); - - // Prevent bulk sercom reset from resetting us. The finalizer will instead. - never_reset_sercom(self->i2c_desc.device.hw); } bool common_hal_busio_i2c_deinited(busio_i2c_obj_t *self) { @@ -175,7 +180,7 @@ void common_hal_busio_i2c_unlock(busio_i2c_obj_t *self) { self->has_lock = false; } -static uint8_t _common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, +static mp_negative_errno_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) { uint16_t attempts = ATTEMPTS; @@ -196,17 +201,17 @@ static uint8_t _common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, if (status == I2C_OK) { return 0; } else if (status == I2C_ERR_BAD_ADDRESS) { - return MP_ENODEV; + return -MP_ENODEV; } - return MP_EIO; + return -MP_EIO; } -uint8_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, +mp_negative_errno_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, const uint8_t *data, size_t len) { return _common_hal_busio_i2c_write(self, addr, data, len, true); } -uint8_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t addr, +mp_negative_errno_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t addr, uint8_t *data, size_t len) { uint16_t attempts = ATTEMPTS; @@ -227,22 +232,17 @@ uint8_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t addr, if (status == ERR_NONE) { return 0; } else if (status == I2C_ERR_BAD_ADDRESS) { - return MP_ENODEV; + return -MP_ENODEV; } - return MP_EIO; + return -MP_EIO; } -uint8_t common_hal_busio_i2c_write_read(busio_i2c_obj_t *self, uint16_t addr, +mp_negative_errno_t common_hal_busio_i2c_write_read(busio_i2c_obj_t *self, uint16_t addr, uint8_t *out_data, size_t out_len, uint8_t *in_data, size_t in_len) { - uint8_t result = _common_hal_busio_i2c_write(self, addr, out_data, out_len, false); + mp_negative_errno_t result = _common_hal_busio_i2c_write(self, addr, out_data, out_len, false); if (result != 0) { return result; } return common_hal_busio_i2c_read(self, addr, in_data, in_len); } - -void common_hal_busio_i2c_never_reset(busio_i2c_obj_t *self) { - never_reset_pin_number(self->scl_pin); - never_reset_pin_number(self->sda_pin); -} diff --git a/ports/atmel-samd/common-hal/busio/SPI.c b/ports/atmel-samd/common-hal/busio/SPI.c index 5d7633be7f8..eb0a045cc4c 100644 --- a/ports/atmel-samd/common-hal/busio/SPI.c +++ b/ports/atmel-samd/common-hal/busio/SPI.c @@ -21,11 +21,13 @@ #include "samd/dma.h" #include "samd/sercom.h" -void setup_pin(const mcu_pin_obj_t *pin, uint32_t pinmux); 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, bool half_duplex) { + // Ensure the object starts in its deinit state. + common_hal_busio_spi_mark_deinit(self); + Sercom *sercom = NULL; uint8_t sercom_index; uint32_t clock_pinmux = 0; @@ -42,9 +44,6 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_half_duplex); } - // Ensure the object starts in its deinit state. - self->clock_pin = NO_PIN; - // Special case for SAMR21 boards. (feather_radiofruit_zigbee) #if defined(PIN_PC19F_SERCOM4_PAD0) if (miso == &pin_PC19) { @@ -128,9 +127,17 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, // Pads must be set after spi_m_sync_init(), which uses default values from // the prototypical SERCOM. - hri_sercomspi_write_CTRLA_MODE_bf(sercom, 3); - hri_sercomspi_write_CTRLA_DOPO_bf(sercom, dopo); - hri_sercomspi_write_CTRLA_DIPO_bf(sercom, miso_pad); + // Set to SPI host mode and choose pads. + // Set all the fields at once to save code space. + hri_sercomspi_wait_for_sync(sercom, SERCOM_SPI_SYNCBUSY_MASK); + sercom->SPI.CTRLA.reg = + (sercom->SPI.CTRLA.reg & + ~(SERCOM_SPI_CTRLA_MODE_Msk | + SERCOM_SPI_CTRLA_DOPO_Msk | + SERCOM_SPI_CTRLA_DIPO_Msk)) | + (SERCOM_SPI_CTRLA_MODE(3) | + SERCOM_SPI_CTRLA_DOPO(dopo) | + SERCOM_SPI_CTRLA_DIPO(miso_pad)); // Always start at 250khz which is what SD cards need. They are sensitive to // SPI bus noise before they are put into SPI mode. @@ -141,50 +148,52 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, mp_raise_OSError(MP_EIO); } - setup_pin(clock, clock_pinmux); - self->clock_pin = clock->number; + // Use strong drive strength for SPI outputs. + self->clock_pin = sercom_setup_pin(clock, clock_pinmux, GPIO_DIRECTION_OUT, true); + #if CIRCUITPY_BUSIO_SPI_ASYNC + self->async_active = false; + #endif if (mosi_none) { self->MOSI_pin = NO_PIN; } else { - setup_pin(mosi, mosi_pinmux); - self->MOSI_pin = mosi->number; + self->MOSI_pin = sercom_setup_pin(mosi, mosi_pinmux, GPIO_DIRECTION_OUT, true); } if (miso_none) { self->MISO_pin = NO_PIN; } else { - setup_pin(miso, miso_pinmux); - self->MISO_pin = miso->number; + self->MISO_pin = sercom_setup_pin(miso, miso_pinmux, GPIO_DIRECTION_IN, false); } spi_m_sync_enable(&self->spi_desc); } -void common_hal_busio_spi_never_reset(busio_spi_obj_t *self) { - never_reset_sercom(self->spi_desc.dev.prvt); - - never_reset_pin_number(self->clock_pin); - never_reset_pin_number(self->MOSI_pin); - never_reset_pin_number(self->MISO_pin); -} bool common_hal_busio_spi_deinited(busio_spi_obj_t *self) { return self->clock_pin == NO_PIN; } +void common_hal_busio_spi_mark_deinit(busio_spi_obj_t *self) { + self->clock_pin = NO_PIN; +} + void common_hal_busio_spi_deinit(busio_spi_obj_t *self) { if (common_hal_busio_spi_deinited(self)) { return; } - allow_reset_sercom(self->spi_desc.dev.prvt); + #if CIRCUITPY_BUSIO_SPI_ASYNC + common_hal_busio_spi_end(self); + #endif spi_m_sync_disable(&self->spi_desc); spi_m_sync_deinit(&self->spi_desc); reset_pin_number(self->clock_pin); reset_pin_number(self->MOSI_pin); reset_pin_number(self->MISO_pin); - self->clock_pin = NO_PIN; + + // This smashes self->clock_pin, so don't do it before resetting the pin above. + common_hal_busio_spi_mark_deinit(self); } bool common_hal_busio_spi_configure(busio_spi_obj_t *self, @@ -204,10 +213,18 @@ bool common_hal_busio_spi_configure(busio_spi_obj_t *self, spi_m_sync_disable(&self->spi_desc); hri_sercomspi_wait_for_sync(hw, SERCOM_SPI_SYNCBUSY_MASK); - hri_sercomspi_write_CTRLA_CPHA_bit(hw, phase); - hri_sercomspi_write_CTRLA_CPOL_bit(hw, polarity); - hri_sercomspi_write_CTRLB_CHSIZE_bf(hw, bits - 8); - hri_sercomspi_write_BAUD_BAUD_bf(hw, baud_reg_value); + // Set all the fields of each register at once to save code space. + SercomSpi *spi = &((Sercom *)hw)->SPI; + spi->CTRLA.reg = + (spi->CTRLA.reg & + ~(SERCOM_SPI_CTRLA_CPHA | + SERCOM_SPI_CTRLA_CPOL)) | + ((phase ? SERCOM_SPI_CTRLA_CPHA : 0) | + (polarity ? SERCOM_SPI_CTRLA_CPOL : 0)); + spi->CTRLB.reg = + (spi->CTRLB.reg & ~SERCOM_SPI_CTRLB_CHSIZE_Msk) | + SERCOM_SPI_CTRLB_CHSIZE(bits - 8); + spi->BAUD.reg = baud_reg_value; hri_sercomspi_wait_for_sync(hw, SERCOM_SPI_SYNCBUSY_MASK); spi_m_sync_enable(&self->spi_desc); @@ -268,6 +285,40 @@ bool common_hal_busio_spi_write(busio_spi_obj_t *self, return status >= 0; // Status is number of chars read or an error code < 0. } +#if CIRCUITPY_BUSIO_SPI_ASYNC +void common_hal_busio_spi_write_start(busio_spi_obj_t *self, const uint8_t *data, size_t len, + circuitpy_async_flag_t *done) { + common_hal_busio_spi_end(self); + CIRCUITPY_ASYNC_FLAG_INIT(done); + self->async_done = done; + // One descriptor holds at most 65535 beats; longer writes and short ones go the normal way. + if (len >= 32 && len <= 65535) { + Sercom *sercom = self->spi_desc.dev.prvt; + shared_dma_transfer_start(&self->async_xfer, sercom, data, &sercom->SPI.DATA.reg, + NULL, NULL, len, 0); + if (self->async_xfer.failure == 0) { + self->async_active = true; + return; + } + } + common_hal_busio_spi_write(self, data, len); + CIRCUITPY_ASYNC_FLAG_SET(done); +} + +void common_hal_busio_spi_end(busio_spi_obj_t *self) { + if (!self->async_active) { + return; + } + // finished() also clears the RX overflow a TX-only transfer leaves on the SERCOM. + // No background tasks here: the caller holds the bus, and one of them may want it. + while (!shared_dma_transfer_finished(&self->async_xfer)) { + } + shared_dma_transfer_close(&self->async_xfer); + self->async_active = false; + CIRCUITPY_ASYNC_FLAG_SET(self->async_done); +} +#endif + bool common_hal_busio_spi_read(busio_spi_obj_t *self, uint8_t *data, size_t len, uint8_t write_value) { if (len == 0) { @@ -317,11 +368,3 @@ uint8_t common_hal_busio_spi_get_polarity(busio_spi_obj_t *self) { void *hw = self->spi_desc.dev.prvt; return hri_sercomspi_get_CTRLA_CPOL_bit(hw); } - -void setup_pin(const mcu_pin_obj_t *pin, uint32_t pinmux) { - gpio_set_pin_direction(pin->number, GPIO_DIRECTION_OUT); - gpio_set_pin_pull_mode(pin->number, GPIO_PULL_OFF); - gpio_set_pin_function(pin->number, pinmux); - claim_pin(pin); - hri_port_set_PINCFG_DRVSTR_bit(PORT, (enum gpio_port)GPIO_PORT(pin->number), GPIO_PIN(pin->number)); -} diff --git a/ports/atmel-samd/common-hal/busio/SPI.h b/ports/atmel-samd/common-hal/busio/SPI.h index ed8bc220a34..57acd5581df 100644 --- a/ports/atmel-samd/common-hal/busio/SPI.h +++ b/ports/atmel-samd/common-hal/busio/SPI.h @@ -6,11 +6,16 @@ #pragma once +#include "py/mpconfig.h" +#if CIRCUITPY_BUSIO_SPI_ASYNC +#include "peripherals/samd/dma.h" +#endif #include "common-hal/microcontroller/Pin.h" #include "hal/include/hal_spi_m_sync.h" #include "py/obj.h" +#include "supervisor/shared/async_flag.h" typedef struct { mp_obj_base_t base; @@ -19,4 +24,9 @@ typedef struct { uint8_t clock_pin; uint8_t MOSI_pin; uint8_t MISO_pin; + #if CIRCUITPY_BUSIO_SPI_ASYNC + bool async_active; // a write_start DMA transfer may still be running + dma_transfer_t async_xfer; + circuitpy_async_flag_t *async_done; + #endif } busio_spi_obj_t; diff --git a/ports/atmel-samd/common-hal/busio/UART.c b/ports/atmel-samd/common-hal/busio/UART.c index 31b644bea9a..c2f3fc71143 100644 --- a/ports/atmel-samd/common-hal/busio/UART.c +++ b/ports/atmel-samd/common-hal/busio/UART.c @@ -37,6 +37,14 @@ static void usart_async_rxc_callback(const struct usart_async_descriptor *const // Nothing needs to be done by us. } +// Mark the object deinited: deinited() is true and deinit() does nothing. +static void mark_deinit(busio_uart_obj_t *self) { + self->rx_pin = NO_PIN; + self->tx_pin = NO_PIN; + self->rts_pin = NO_PIN; + self->cts_pin = NO_PIN; +} + // shared-bindings validates that the tx and rx are not both missing, // and that the pins are distinct. void common_hal_busio_uart_construct(busio_uart_obj_t *self, @@ -56,11 +64,8 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, uint32_t rts_pinmux = 0; uint32_t cts_pinmux = 0; - // Set state so the object is deinited to start. - self->rx_pin = NO_PIN; - self->tx_pin = NO_PIN; - self->rts_pin = NO_PIN; - self->cts_pin = NO_PIN; + // Ensure the object starts in its deinit state. + mark_deinit(self); if ((rs485_dir != NULL) || (rs485_invert)) { mp_raise_NotImplementedError(MP_ERROR_TEXT("RS485")); @@ -284,64 +289,24 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, 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; + self->tx_pin = sercom_setup_pin(tx, tx_pinmux, GPIO_DIRECTION_OUT, false); } 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; + self->rx_pin = sercom_setup_pin(rx, rx_pinmux, GPIO_DIRECTION_IN, false); } if (have_rts) { - gpio_set_pin_direction(rts->number, GPIO_DIRECTION_OUT); - gpio_set_pin_pull_mode(rts->number, GPIO_PULL_OFF); - gpio_set_pin_function(rts->number, rts_pinmux); - self->rts_pin = rts->number; - claim_pin(rts); - } else { - self->rts_pin = NO_PIN; + self->rts_pin = sercom_setup_pin(rts, rts_pinmux, GPIO_DIRECTION_OUT, false); } if (have_cts) { - gpio_set_pin_direction(cts->number, GPIO_DIRECTION_IN); - gpio_set_pin_pull_mode(cts->number, GPIO_PULL_OFF); - gpio_set_pin_function(cts->number, cts_pinmux); - self->cts_pin = cts->number; - claim_pin(cts); - } else { - self->cts_pin = NO_PIN; + self->cts_pin = sercom_setup_pin(cts, cts_pinmux, GPIO_DIRECTION_IN, false); } usart_async_enable(usart_desc_p); } -void common_hal_busio_uart_never_reset(busio_uart_obj_t *self) { - for (size_t i = 0; i < MP_ARRAY_SIZE(sercom_insts); i++) { - const Sercom *sercom = sercom_insts[i]; - Sercom *hw = (Sercom *)(self->usart_desc.device.hw); - - // Reserve pins for active UART only - if (sercom == hw) { - never_reset_sercom(hw); - never_reset_pin_number(self->rx_pin); - never_reset_pin_number(self->tx_pin); - never_reset_pin_number(self->rts_pin); - never_reset_pin_number(self->cts_pin); - } - } - return; -} bool common_hal_busio_uart_deinited(busio_uart_obj_t *self) { return self->rx_pin == NO_PIN && self->tx_pin == NO_PIN; @@ -359,10 +324,7 @@ void common_hal_busio_uart_deinit(busio_uart_obj_t *self) { reset_pin_number(self->tx_pin); reset_pin_number(self->rts_pin); reset_pin_number(self->cts_pin); - self->rx_pin = NO_PIN; - self->tx_pin = NO_PIN; - self->rts_pin = NO_PIN; - self->cts_pin = NO_PIN; + mark_deinit(self); } // Read characters. diff --git a/ports/atmel-samd/common-hal/busio/__init__.c b/ports/atmel-samd/common-hal/busio/__init__.c index 0017aa662a2..1aa046c0d89 100644 --- a/ports/atmel-samd/common-hal/busio/__init__.c +++ b/ports/atmel-samd/common-hal/busio/__init__.c @@ -6,39 +6,16 @@ #include "samd/sercom.h" #include "common-hal/busio/__init__.h" +#include "shared-bindings/microcontroller/Pin.h" -static bool never_reset_sercoms[SERCOM_INST_NUM]; - -void never_reset_sercom(Sercom *sercom) { - // Reset all SERCOMs except the ones being used by on-board devices. - Sercom *sercom_instances[SERCOM_INST_NUM] = SERCOM_INSTS; - for (int i = 0; i < SERCOM_INST_NUM; i++) { - if (sercom_instances[i] == sercom) { - never_reset_sercoms[i] = true; - break; - } - } -} - -void allow_reset_sercom(Sercom *sercom) { - // Reset all SERCOMs except the ones being used by on-board devices. - Sercom *sercom_instances[SERCOM_INST_NUM] = SERCOM_INSTS; - for (int i = 0; i < SERCOM_INST_NUM; i++) { - if (sercom_instances[i] == sercom) { - never_reset_sercoms[i] = false; - break; - } - } -} - -void reset_sercoms(void) { - // Reset all SERCOMs except the ones being used by on-board devices. - Sercom *sercom_instances[SERCOM_INST_NUM] = SERCOM_INSTS; - for (int i = 0; i < SERCOM_INST_NUM; i++) { - if (never_reset_sercoms[i]) { - continue; - } - // SWRST is same for all modes of SERCOMs. - sercom_instances[i]->SPI.CTRLA.bit.SWRST = 1; +uint8_t sercom_setup_pin(const mcu_pin_obj_t *pin, uint32_t pinmux, enum gpio_direction direction, + bool strong_drive) { + gpio_set_pin_direction(pin->number, direction); + gpio_set_pin_pull_mode(pin->number, GPIO_PULL_OFF); + gpio_set_pin_function(pin->number, pinmux); + if (strong_drive) { + hri_port_set_PINCFG_DRVSTR_bit(PORT, (enum gpio_port)GPIO_PORT(pin->number), GPIO_PIN(pin->number)); } + claim_pin(pin); + return pin->number; } diff --git a/ports/atmel-samd/common-hal/busio/__init__.h b/ports/atmel-samd/common-hal/busio/__init__.h index a87e38cb7ba..82335f18925 100644 --- a/ports/atmel-samd/common-hal/busio/__init__.h +++ b/ports/atmel-samd/common-hal/busio/__init__.h @@ -6,6 +6,10 @@ #pragma once -void reset_sercoms(void); -void allow_reset_sercom(Sercom *sercom); -void never_reset_sercom(Sercom *sercom); +#include "common-hal/microcontroller/Pin.h" +#include "hal/include/hal_gpio.h" + +// Connect pin to its SERCOM with no pull, optionally with strong drive, and claim it. +// Returns the pin number. +uint8_t sercom_setup_pin(const mcu_pin_obj_t *pin, uint32_t pinmux, enum gpio_direction direction, + bool strong_drive); diff --git a/ports/atmel-samd/common-hal/canio/CAN.c b/ports/atmel-samd/common-hal/canio/CAN.c index 3321d0abdbc..c207e39fca5 100644 --- a/ports/atmel-samd/common-hal/canio/CAN.c +++ b/ports/atmel-samd/common-hal/canio/CAN.c @@ -27,7 +27,17 @@ static canio_can_obj_t *can_objs[MP_ARRAY_SIZE(can_insts)]; // This must be placed in the first 64kB of RAM static COMPILER_SECTION(".canram") canio_can_state_t can_state[MP_ARRAY_SIZE(can_insts)]; +// Mark the object deinited: deinited() is true and deinit() does nothing. +static void mark_deinit(canio_can_obj_t *self) { + self->hw = NULL; + self->tx_pin_number = COMMON_HAL_MCU_NO_PIN; + self->rx_pin_number = COMMON_HAL_MCU_NO_PIN; +} + void common_hal_canio_can_construct(canio_can_obj_t *self, const mcu_pin_obj_t *tx, const mcu_pin_obj_t *rx, int baudrate, bool loopback, bool silent) { + // Ensure the object starts in its deinit state. + mark_deinit(self); + mcu_pin_function_t *tx_function = mcu_find_pin_function(can_tx, tx, -1, MP_QSTR_tx); int instance = tx_function->instance; @@ -48,11 +58,11 @@ void common_hal_canio_can_construct(canio_can_obj_t *self, const mcu_pin_obj_t * gpio_set_pin_direction(tx_function->pin, GPIO_DIRECTION_OUT); gpio_set_pin_function(tx_function->pin, tx_function->function); - common_hal_never_reset_pin(tx_function->obj); + claim_pin(tx_function->obj); gpio_set_pin_direction(rx_function->pin, GPIO_DIRECTION_IN); gpio_set_pin_function(rx_function->pin, rx_function->function); - common_hal_never_reset_pin(rx_function->obj); + claim_pin(rx_function->obj); self->tx_pin_number = tx ? common_hal_mcu_pin_number(tx) : COMMON_HAL_MCU_NO_PIN; self->rx_pin_number = rx ? common_hal_mcu_pin_number(rx) : COMMON_HAL_MCU_NO_PIN; @@ -62,6 +72,18 @@ void common_hal_canio_can_construct(canio_can_obj_t *self, const mcu_pin_obj_t * self->loopback = loopback; self->silent = silent; + // Turn the CAN clocks on before touching its registers. deinit() turns + // them off, so CCCR.INIT would never read back as set without them. + if (instance == 0) { + hri_mclk_set_AHBMASK_CAN0_bit(MCLK); + hri_gclk_write_PCHCTRL_reg(GCLK, CAN0_GCLK_ID, CONF_GCLK_CAN0_SRC | (1 << GCLK_PCHCTRL_CHEN_Pos)); + #ifdef CAN1_GCLK_ID + } else if (instance == 1) { + hri_mclk_set_AHBMASK_CAN1_bit(MCLK); + hri_gclk_write_PCHCTRL_reg(GCLK, CAN1_GCLK_ID, CONF_GCLK_CAN1_SRC | (1 << GCLK_PCHCTRL_CHEN_Pos)); + #endif + } + // Allow configuration change hri_can_set_CCCR_INIT_bit(self->hw); while (hri_can_get_CCCR_INIT_bit(self->hw) == 0) { @@ -69,18 +91,12 @@ void common_hal_canio_can_construct(canio_can_obj_t *self, const mcu_pin_obj_t * hri_can_set_CCCR_CCE_bit(self->hw); if (instance == 0) { - hri_mclk_set_AHBMASK_CAN0_bit(MCLK); - hri_gclk_write_PCHCTRL_reg(GCLK, CAN0_GCLK_ID, CONF_GCLK_CAN0_SRC | (1 << GCLK_PCHCTRL_CHEN_Pos)); - NVIC_DisableIRQ(CAN0_IRQn); NVIC_ClearPendingIRQ(CAN0_IRQn); NVIC_EnableIRQ(CAN0_IRQn); hri_can_write_ILE_reg(self->hw, CAN_ILE_EINT0); #ifdef CAN1_GCLK_ID } else if (instance == 1) { - hri_mclk_set_AHBMASK_CAN1_bit(MCLK); - hri_gclk_write_PCHCTRL_reg(GCLK, CAN1_GCLK_ID, CONF_GCLK_CAN1_SRC | (1 << GCLK_PCHCTRL_CHEN_Pos)); - NVIC_DisableIRQ(CAN1_IRQn); NVIC_ClearPendingIRQ(CAN1_IRQn); NVIC_EnableIRQ(CAN1_IRQn); @@ -343,7 +359,38 @@ void common_hal_canio_can_check_for_deinit(canio_can_obj_t *self) { void common_hal_canio_can_deinit(canio_can_obj_t *self) { if (self->hw) { hri_can_set_CCCR_INIT_bit(self->hw); - self->hw = 0; + while (hri_can_get_CCCR_INIT_bit(self->hw) == 0) { + } + + // Find which hardware instance we are so we can release its clocks + // and IRQ. + size_t instance = MP_ARRAY_SIZE(can_insts); + for (size_t i = 0; i < MP_ARRAY_SIZE(can_insts); i++) { + if (can_insts[i] == self->hw) { + instance = i; + break; + } + } + if (instance < MP_ARRAY_SIZE(can_insts)) { + // Clear this instance's message RAM, including its RX filters, so + // the next CAN on it doesn't inherit them. + memset(&can_state[instance], 0, sizeof(can_state[instance])); + if (instance == 0) { + NVIC_DisableIRQ(CAN0_IRQn); + NVIC_ClearPendingIRQ(CAN0_IRQn); + hri_gclk_write_PCHCTRL_reg(GCLK, CAN0_GCLK_ID, 0); + hri_mclk_clear_AHBMASK_CAN0_bit(MCLK); + #ifdef CAN1_GCLK_ID + } else if (instance == 1) { + NVIC_DisableIRQ(CAN1_IRQn); + NVIC_ClearPendingIRQ(CAN1_IRQn); + hri_gclk_write_PCHCTRL_reg(GCLK, CAN1_GCLK_ID, 0); + hri_mclk_clear_AHBMASK_CAN1_bit(MCLK); + #endif + } + can_objs[instance] = NULL; + } + self->hw = NULL; } if (self->rx_pin_number != COMMON_HAL_MCU_NO_PIN) { reset_pin_number(self->rx_pin_number); @@ -355,22 +402,6 @@ void common_hal_canio_can_deinit(canio_can_obj_t *self) { } } -void common_hal_canio_reset(void) { - memset(can_state, 0, sizeof(can_state)); - - for (size_t i = 0; i < MP_ARRAY_SIZE(can_insts); i++) { - hri_can_set_CCCR_INIT_bit(can_insts[i]); - } - - for (size_t i = 0; i < MP_ARRAY_SIZE(can_objs); i++) { - if (can_objs[i]) { - common_hal_canio_can_deinit(can_objs[i]); - can_objs[i] = NULL; - } - } -} - - static void can_handler(int i) { canio_can_obj_t *self = can_objs[i]; (void)self; diff --git a/ports/atmel-samd/common-hal/canio/Listener.c b/ports/atmel-samd/common-hal/canio/Listener.c index 23f7710d6cb..3f52fbd8db1 100644 --- a/ports/atmel-samd/common-hal/canio/Listener.c +++ b/ports/atmel-samd/common-hal/canio/Listener.c @@ -14,6 +14,7 @@ #include "common-hal/canio/__init__.h" #include "common-hal/canio/Listener.h" +#include "shared-bindings/canio/CAN.h" #include "shared-bindings/canio/Listener.h" #include "shared-bindings/util.h" #include "supervisor/shared/tick.h" @@ -108,7 +109,7 @@ static void clear_filters(canio_listener_obj_t *self) { } } for (size_t i = 0; i < MP_ARRAY_SIZE(can->state->standard_rx_filter); i++) { - int val = CAN_SIDFE_0_SFEC_STF1M_Val + fifo; + int val = CAN_SIDFE_0_SFEC_STF0M_Val + fifo; if (can->state->standard_rx_filter[i].SIDFE_0.bit.SFEC == val) { can->state->standard_rx_filter[i].SIDFE_0.bit.SFEC = CAN_SIDFE_0_SFEC_DISABLE_Val; } @@ -273,27 +274,22 @@ static void set_filters(canio_listener_obj_t *self, size_t nmatch, canio_match_o void common_hal_canio_listener_construct(canio_listener_obj_t *self, canio_can_obj_t *can, size_t nmatch, canio_match_obj_t **matches, float timeout) { + // Pick a FIFO, but claim it only after the checks below. deinit() frees + // it only once self->can is set, so a raise here would leak it. + int fifo_idx; if (!can->fifo0_in_use) { - self->fifo_idx = 0; - self->fifo = can->state->rx0_fifo; - self->hw = (canio_rxfifo_reg_t *)&can->hw->RXF0C; - can->hw->IR.reg = CAN_IR_RF0N | CAN_IR_RF0W | CAN_IR_RF0F | CAN_IR_RF0L; - can->fifo0_in_use = true; + fifo_idx = 0; } else if (!can->fifo1_in_use) { - self->fifo_idx = 1; - self->fifo = can->state->rx1_fifo; - self->hw = (canio_rxfifo_reg_t *)&can->hw->RXF1C; - can->fifo1_in_use = true; - can->hw->IR.reg = CAN_IR_RF1N | CAN_IR_RF1W | CAN_IR_RF1F | CAN_IR_RF1L; + fifo_idx = 1; } else { mp_raise_ValueError(MP_ERROR_TEXT("All RX FIFOs in use")); } if (!nmatch) { - if (can->hw->GFC.bit.ANFS == CAN_GFC_ANFS_RXF1_Val - self->fifo_idx) { + if (can->hw->GFC.bit.ANFS == CAN_GFC_ANFS_RXF1_Val - fifo_idx) { mp_raise_ValueError(MP_ERROR_TEXT("Already have all-matches listener")); } - if (can->hw->GFC.bit.ANFE == CAN_GFC_ANFE_RXF1_Val - self->fifo_idx) { + if (can->hw->GFC.bit.ANFE == CAN_GFC_ANFE_RXF1_Val - fifo_idx) { mp_raise_ValueError(MP_ERROR_TEXT("Already have all-matches listener")); } } @@ -306,7 +302,19 @@ void common_hal_canio_listener_construct(canio_listener_obj_t *self, canio_can_o mp_raise_ValueError(MP_ERROR_TEXT("Filters too complex")); } - // Nothing can fail now so it's safe to assign self->can + // Nothing can fail now so it's safe to claim the FIFO and assign self->can + self->fifo_idx = fifo_idx; + if (fifo_idx == 0) { + self->fifo = can->state->rx0_fifo; + self->hw = (canio_rxfifo_reg_t *)&can->hw->RXF0C; + can->hw->IR.reg = CAN_IR_RF0N | CAN_IR_RF0W | CAN_IR_RF0F | CAN_IR_RF0L; + can->fifo0_in_use = true; + } else { + self->fifo = can->state->rx1_fifo; + self->hw = (canio_rxfifo_reg_t *)&can->hw->RXF1C; + can->hw->IR.reg = CAN_IR_RF1N | CAN_IR_RF1W | CAN_IR_RF1F | CAN_IR_RF1L; + can->fifo1_in_use = true; + } self->can = can; set_filters(self, nmatch, matches); common_hal_canio_listener_set_timeout(self, timeout); @@ -365,7 +373,10 @@ mp_obj_t common_hal_canio_listener_receive(canio_listener_obj_t *self) { } void common_hal_canio_listener_deinit(canio_listener_obj_t *self) { - if (self->can) { + // If the CAN was deinited first, for example when finalisers run in either + // order at VM end, its hw is NULL and its clocks are off: skip the + // hardware. CAN's deinit() has already cleared its filters. + if (self->can && !common_hal_canio_can_deinited(self->can)) { clear_filters(self); if (self->fifo_idx == 0) { self->can->fifo0_in_use = false; diff --git a/ports/atmel-samd/common-hal/countio/Counter.c b/ports/atmel-samd/common-hal/countio/Counter.c index d9766339cad..e8842764f6a 100644 --- a/ports/atmel-samd/common-hal/countio/Counter.c +++ b/ports/atmel-samd/common-hal/countio/Counter.c @@ -15,8 +15,16 @@ #include "samd/external_interrupts.h" #include "py/runtime.h" +// Mark the object deinited: deinited() is true and deinit() does nothing. +static void mark_deinit(countio_counter_obj_t *self) { + self->pin = NO_PIN; +} + void common_hal_countio_counter_construct(countio_counter_obj_t *self, const mcu_pin_obj_t *pin, countio_edge_t edge, digitalio_pull_t pull) { + // Ensure the object starts in its deinit state. + mark_deinit(self); + if (!pin->has_extint) { raise_ValueError_invalid_pin(); } @@ -87,7 +95,7 @@ void common_hal_countio_counter_deinit(countio_counter_obj_t *self) { reset_pin_number(self->pin); - self->pin = NO_PIN; + mark_deinit(self); } diff --git a/ports/atmel-samd/common-hal/digitalio/DigitalInOut.c b/ports/atmel-samd/common-hal/digitalio/DigitalInOut.c index 89902259a23..adda3efe876 100644 --- a/ports/atmel-samd/common-hal/digitalio/DigitalInOut.c +++ b/ports/atmel-samd/common-hal/digitalio/DigitalInOut.c @@ -28,10 +28,6 @@ digitalinout_result_t common_hal_digitalio_digitalinout_construct( return DIGITALINOUT_OK; } -void common_hal_digitalio_digitalinout_never_reset( - digitalio_digitalinout_obj_t *self) { - never_reset_pin_number(self->pin->number); -} bool common_hal_digitalio_digitalinout_deinited(digitalio_digitalinout_obj_t *self) { return self->pin == NULL; diff --git a/ports/atmel-samd/common-hal/frequencyio/FrequencyIn.c b/ports/atmel-samd/common-hal/frequencyio/FrequencyIn.c index 405e043bf69..0d8e289a73a 100644 --- a/ports/atmel-samd/common-hal/frequencyio/FrequencyIn.c +++ b/ports/atmel-samd/common-hal/frequencyio/FrequencyIn.c @@ -34,32 +34,18 @@ #endif static frequencyio_frequencyin_obj_t *active_frequencyins[TC_INST_NUM]; -volatile uint8_t reference_tc; +// 0xff means none. frequencyin_reset() used to set these at every VM start; +// now they start that way, and deinit() resets them when the last FrequencyIn is freed. +volatile uint8_t reference_tc = 0xff; #ifdef SAM_D5X_E5X -static uint8_t dpll_gclk; +static uint8_t dpll_gclk = 0xff; #if !BOARD_HAS_CRYSTAL -static uint8_t osculp32k_gclk; +static uint8_t osculp32k_gclk = 0xff; #endif #endif -void frequencyin_reset(void) { - for (uint8_t i = 0; i < TC_INST_NUM; i++) { - active_frequencyins[i] = NULL; - } - - reference_tc = 0xff; - #ifdef SAM_D5X_E5X - dpll_gclk = 0xff; - - #if !BOARD_HAS_CRYSTAL - osculp32k_gclk = 0xff; - #endif - - #endif -} - static void frequencyin_emergency_cancel_capture(uint8_t index) { frequencyio_frequencyin_obj_t* self = active_frequencyins[index]; @@ -259,7 +245,14 @@ static void frequencyin_samd51_stop_dpll(void) { } #endif +// Mark the object deinited: deinited() is true and deinit() does nothing. +static void mark_deinit(frequencyio_frequencyin_obj_t *self) { + self->pin = NO_PIN; +} + void common_hal_frequencyio_frequencyin_construct(frequencyio_frequencyin_obj_t* self, const mcu_pin_obj_t* pin, const uint16_t capture_period) { + // Ensure the object starts in its deinit state. + mark_deinit(self); if (!pin->has_extint) { raise_ValueError_invalid_pin(); @@ -284,6 +277,16 @@ void common_hal_frequencyio_frequencyin_construct(frequencyio_frequencyin_obj_t* } Tc *tc = tc_insts[timer_index]; + #ifdef SAM_D5X_E5X + // Start the DPLL before setting any state, so this raise leaves the + // object deinited. deinit() can't undo a partial setup: it would disable + // event channel 0 and toggle this channel's EXTINTEO bit on. + frequencyin_samd51_start_dpll(); + if (dpll_gclk == 0xff && !clock_get_enabled(0, GCLK_SOURCE_DPLL1)) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Internal resource(s) in use")); + } + #endif + self->tc_index = timer_index; self->pin = pin->number; self->channel = pin->extint_channel; @@ -302,16 +305,11 @@ void common_hal_frequencyio_frequencyin_construct(frequencyio_frequencyin_obj_t* // SAMD21: We use GCLK0 generated from DFLL running at 48mhz // SAMD51: We use a GCLK generated from DPLL1 running at <100mhz #ifdef SAMD21 - set_timer_handler(timer_index, 0, TC_HANDLER_NO_INTERRUPT); + set_timer_handler(true, timer_index, TC_HANDLER_NO_INTERRUPT); turn_on_clocks(true, timer_index, 0); #endif #ifdef SAM_D5X_E5X - frequencyin_samd51_start_dpll(); - if (dpll_gclk == 0xff && !clock_get_enabled(0, GCLK_SOURCE_DPLL1)) { - common_hal_frequencyio_frequencyin_deinit(self); - mp_raise_RuntimeError(MP_ERROR_TEXT("Internal resource(s) in use")); - } - set_timer_handler(timer_index, dpll_gclk, TC_HANDLER_NO_INTERRUPT); + set_timer_handler(true, timer_index, TC_HANDLER_NO_INTERRUPT); turn_on_clocks(true, timer_index, dpll_gclk); #endif @@ -371,6 +369,7 @@ void common_hal_frequencyio_frequencyin_construct(frequencyio_frequencyin_obj_t* NVIC_EnableIRQ(self->TC_IRQ); gpio_set_pin_function(pin->number, GPIO_PIN_FUNCTION_A); + claim_pin(pin); tc_set_enable(tc, true); @@ -429,7 +428,7 @@ void common_hal_frequencyio_frequencyin_deinit(frequencyio_frequencyin_obj_t* se active_frequencyins[self->tc_index] = NULL; self->tc_index = 0xff; - self->pin = NO_PIN; + mark_deinit(self); bool check_active = false; for (uint8_t i = 0; i < TC_INST_NUM; i++) { diff --git a/ports/atmel-samd/common-hal/frequencyio/FrequencyIn.h b/ports/atmel-samd/common-hal/frequencyio/FrequencyIn.h index 8fd28b29c99..b43b101862c 100644 --- a/ports/atmel-samd/common-hal/frequencyio/FrequencyIn.h +++ b/ports/atmel-samd/common-hal/frequencyio/FrequencyIn.h @@ -25,4 +25,3 @@ typedef struct { } frequencyio_frequencyin_obj_t; void frequencyin_interrupt_handler(uint8_t index); -void frequencyin_reset(void); diff --git a/ports/atmel-samd/common-hal/i2ctarget/I2CTarget.c b/ports/atmel-samd/common-hal/i2ctarget/I2CTarget.c index f838b576e43..c22d63a3dcc 100644 --- a/ports/atmel-samd/common-hal/i2ctarget/I2CTarget.c +++ b/ports/atmel-samd/common-hal/i2ctarget/I2CTarget.c @@ -16,9 +16,18 @@ #include "hal/include/hal_gpio.h" #include "peripherals/samd/sercom.h" +// Mark the object deinited: deinited() is true and deinit() does nothing. +static void mark_deinit(i2ctarget_i2c_target_obj_t *self) { + self->sda_pin = NO_PIN; + self->scl_pin = NO_PIN; +} + void common_hal_i2ctarget_i2c_target_construct(i2ctarget_i2c_target_obj_t *self, const mcu_pin_obj_t *scl, const mcu_pin_obj_t *sda, uint8_t *addresses, unsigned int num_addresses, bool smbus) { + // Ensure the object starts in its deinit state. + mark_deinit(self); + uint8_t sercom_index; uint32_t sda_pinmux, scl_pinmux; Sercom *sercom = samd_i2c_get_sercom(scl, sda, &sercom_index, &sda_pinmux, &scl_pinmux); @@ -93,8 +102,7 @@ void common_hal_i2ctarget_i2c_target_deinit(i2ctarget_i2c_target_obj_t *self) { reset_pin_number(self->sda_pin); reset_pin_number(self->scl_pin); - self->sda_pin = NO_PIN; - self->scl_pin = NO_PIN; + mark_deinit(self); } static int i2c_target_check_error(i2ctarget_i2c_target_obj_t *self, bool raise) { diff --git a/ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c b/ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c index a6d8fef0f39..a34f8497e13 100644 --- a/ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c +++ b/ports/atmel-samd/common-hal/imagecapture/ParallelImageCapture.c @@ -30,14 +30,14 @@ #define PIN_PCC_CLK (PIN_PA14) void common_hal_imagecapture_parallelimagecapture_construct(imagecapture_parallelimagecapture_obj_t *self, - const uint8_t data_pins[], + const mcu_pin_obj_t **data_pins, uint8_t data_count, const mcu_pin_obj_t *data_clock, const mcu_pin_obj_t *vertical_sync, const mcu_pin_obj_t *horizontal_reference) { for (int i = 0; i < data_count; i++) { - if (data_pins[i] != PIN_PCC_D0 + i) { + if (common_hal_mcu_pin_number(data_pins[i]) != PIN_PCC_D0 + i) { mp_raise_ValueError_varg(MP_ERROR_TEXT("Invalid data_pins[%d]"), i); } } @@ -56,7 +56,7 @@ void common_hal_imagecapture_parallelimagecapture_construct(imagecapture_paralle } // technically, 0 was validated as free already but check again for (int i = 0; i < data_count; i++) { - if (!pin_number_is_free(data_pins[i])) { + if (!pin_number_is_free(common_hal_mcu_pin_number(data_pins[i]))) { mp_raise_ValueError_varg(MP_ERROR_TEXT("data pin #%d in use"), i); } } @@ -81,24 +81,24 @@ void common_hal_imagecapture_parallelimagecapture_construct(imagecapture_paralle 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); + 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); + 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); + claim_pin_number(PIN_PCC_DEN2); } for (int i = 0; i < data_count; i++) { gpio_set_pin_direction(PIN_PCC_D0 + i, GPIO_DIRECTION_IN); gpio_set_pin_pull_mode(PIN_PCC_D0 + i, GPIO_PULL_OFF); gpio_set_pin_function(PIN_PCC_D0 + i, GPIO_PIN_FUNCTION_PCC); - // claim_pin_number(PIN_PCC_D0+i); + claim_pin_number(PIN_PCC_D0 + i); } } @@ -112,6 +112,14 @@ void common_hal_imagecapture_parallelimagecapture_deinit(imagecapture_parallelim for (int i = 0; i < self->data_count; i++) { reset_pin_number(PIN_PCC_D0 + i); } + self->vertical_sync = NO_PIN; + self->horizontal_reference = NO_PIN; + + // Disable and power down the PCC peripheral. + PCC->MR.bit.PCEN = 0; + PCC->IDR.reg = 0b1111; + MCLK->APBDMASK.bit.PCC_ = 0; + self->data_count = 0; } @@ -135,7 +143,8 @@ void common_hal_imagecapture_parallelimagecapture_singleshot_capture(imagecaptur mp_buffer_info_t bufinfo; mp_get_buffer_raise(buffer, &bufinfo, MP_BUFFER_RW); - uint8_t dma_channel = dma_allocate_channel(true); + // Allocate a permanent channel (not really audio). + uint8_t dma_channel = dma_allocate_audio_channel(); uint32_t *dest = bufinfo.buf; size_t count = bufinfo.len / 4; // PCC receives 4 bytes (2 pixels) at a time diff --git a/ports/atmel-samd/common-hal/max3421e/Max3421E.c b/ports/atmel-samd/common-hal/max3421e/Max3421E.c index bcf6bd2b31c..21dc142f197 100644 --- a/ports/atmel-samd/common-hal/max3421e/Max3421E.c +++ b/ports/atmel-samd/common-hal/max3421e/Max3421E.c @@ -44,7 +44,6 @@ void common_hal_max3421e_max3421e_deinit_irq(max3421e_max3421e_obj_t *self) { const mcu_pin_obj_t *pin = self->irq.pin; set_eic_handler(pin->extint_channel, EIC_HANDLER_NO_INTERRUPT); turn_off_eic_channel(pin->extint_channel); - reset_pin_number(pin->extint_channel); } // Enable or disable the irq interrupt. diff --git a/ports/atmel-samd/common-hal/microcontroller/Pin.c b/ports/atmel-samd/common-hal/microcontroller/Pin.c index bbf3957818e..c60e671a89d 100644 --- a/ports/atmel-samd/common-hal/microcontroller/Pin.c +++ b/ports/atmel-samd/common-hal/microcontroller/Pin.c @@ -13,10 +13,6 @@ #include "samd/pins.h" -#ifdef SPEAKER_ENABLE_PIN -bool speaker_enable_in_use; -#endif - #define PORT_COUNT (PORT_BITS / 32 + 1) #ifdef SAM_D5X_E5X @@ -26,67 +22,14 @@ bool speaker_enable_in_use; #define SWD_MUX GPIO_PIN_FUNCTION_G #endif -static uint32_t never_reset_pins[PORT_COUNT]; - -void reset_all_pins(void) { - uint32_t pin_mask[PORT_COUNT] = PORT_OUT_IMPLEMENTED; - - // Do not full reset USB lines. - #if CIRCUITPY_USB_DEVICE - pin_mask[0] &= ~(PORT_PA24 | PORT_PA25); - #endif - - // Do not reset SWD when a debugger is present. - if (DSU->STATUSB.bit.DBGPRES == 1) { - pin_mask[0] &= ~(PORT_PA30 | PORT_PA31); - } - - for (uint32_t i = 0; i < PORT_COUNT; i++) { - pin_mask[i] &= ~never_reset_pins[i]; - } - - gpio_set_port_direction(GPIO_PORTA, pin_mask[0], GPIO_DIRECTION_OFF); - gpio_set_port_direction(GPIO_PORTB, pin_mask[1], GPIO_DIRECTION_OFF); - #if PORT_BITS > 64 - gpio_set_port_direction(GPIO_PORTC, pin_mask[2], GPIO_DIRECTION_OFF); - #endif - #if PORT_BITS > 96 - gpio_set_port_direction(GPIO_PORTD, pin_mask[3], GPIO_DIRECTION_OFF); - #endif - - // Configure SWD. SWDIO will be automatically switched on PA31 when a signal is input on - // SWCLK. - #ifdef SAM_D5X_E5X - gpio_set_pin_function(PIN_PA30, MUX_PA30H_CM4_SWCLK); - #endif - #ifdef SAMD21 - gpio_set_pin_function(PIN_PA30, GPIO_PIN_FUNCTION_G); - gpio_set_pin_function(PIN_PA31, GPIO_PIN_FUNCTION_G); - #endif - - // After configuring SWD because it may be shared. - #ifdef SPEAKER_ENABLE_PIN - speaker_enable_in_use = false; - gpio_set_pin_function(SPEAKER_ENABLE_PIN->number, GPIO_PIN_FUNCTION_OFF); - gpio_set_pin_direction(SPEAKER_ENABLE_PIN->number, GPIO_DIRECTION_OUT); - gpio_set_pin_level(SPEAKER_ENABLE_PIN->number, false); - #endif -} - -void never_reset_pin_number(uint8_t pin_number) { - if (pin_number >= PORT_BITS) { - return; - } - - never_reset_pins[GPIO_PORT(pin_number)] |= 1 << GPIO_PIN(pin_number); -} +static uint32_t claimed_pins[PORT_COUNT]; void reset_pin_number(uint8_t pin_number) { if (pin_number >= PORT_BITS) { return; } - never_reset_pins[GPIO_PORT(pin_number)] &= ~(1 << GPIO_PIN(pin_number)); + claimed_pins[GPIO_PORT(pin_number)] &= ~(1 << GPIO_PIN(pin_number)); if (pin_number == PIN_PA30 #ifdef SAM_D5X_E5X @@ -103,7 +46,6 @@ void reset_pin_number(uint8_t pin_number) { #ifdef SPEAKER_ENABLE_PIN if (pin_number == SPEAKER_ENABLE_PIN->number) { - speaker_enable_in_use = false; gpio_set_pin_function(pin_number, GPIO_PIN_FUNCTION_OFF); gpio_set_pin_direction(SPEAKER_ENABLE_PIN->number, GPIO_DIRECTION_OUT); gpio_set_pin_level(SPEAKER_ENABLE_PIN->number, false); @@ -111,56 +53,33 @@ void reset_pin_number(uint8_t pin_number) { #endif } -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) { - if (pin == NULL) { +void claim_pin_number(uint8_t pin_number) { + if (pin_number >= PORT_BITS) { return; } - reset_pin_number(pin->number); + + claimed_pins[GPIO_PORT(pin_number)] |= 1 << GPIO_PIN(pin_number); } void claim_pin(const mcu_pin_obj_t* pin) { - #ifdef SPEAKER_ENABLE_PIN - if (pin == SPEAKER_ENABLE_PIN) { - speaker_enable_in_use = true; - } - #endif + claim_pin_number(pin->number); } bool pin_number_is_free(uint8_t pin_number) { - PortGroup *const port = &PORT->Group[(enum gpio_port)GPIO_PORT(pin_number)]; - uint8_t pin_index = GPIO_PIN(pin_number); - volatile PORT_PINCFG_Type *state = &port->PINCFG[pin_index]; - volatile PORT_PMUX_Type *pmux = &port->PMUX[pin_index / 2]; - - if (pin_number == PIN_PA30 || pin_number == PIN_PA31) { - if (DSU->STATUSB.bit.DBGPRES == 1) { - return false; - } - if (pin_number == PIN_PA30 - #ifdef SAMD21 - || pin_number == PIN_PA31 - #endif - ) - { - return state->bit.PMUXEN == 1 && ((pmux->reg >> (4 * pin_index % 2)) & 0xf) == SWD_MUX; - } + if (pin_number >= PORT_BITS) { + return false; } - return state->bit.PMUXEN == 0 && state->bit.INEN == 0 && - state->bit.PULLEN == 0 && (port->DIR.reg & (1 << pin_index)) == 0; + // SWD pins are in use while a debugger is attached. + if ((pin_number == PIN_PA30 || pin_number == PIN_PA31) && DSU->STATUSB.bit.DBGPRES == 1) { + return false; + } + + return (claimed_pins[GPIO_PORT(pin_number)] & (1 << GPIO_PIN(pin_number))) == 0; } bool common_hal_mcu_pin_is_free(const mcu_pin_obj_t* pin) { - #ifdef SPEAKER_ENABLE_PIN - if (pin == SPEAKER_ENABLE_PIN) { - return !speaker_enable_in_use; - } - #endif - return pin_number_is_free(pin->number); } @@ -168,10 +87,6 @@ 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) { - return claim_pin(pin); -} - void common_hal_mcu_pin_reset_number(uint8_t pin_no) { reset_pin_number(pin_no); } diff --git a/ports/atmel-samd/common-hal/microcontroller/Pin.h b/ports/atmel-samd/common-hal/microcontroller/Pin.h index cce9d84ef33..cc97a5a1775 100644 --- a/ports/atmel-samd/common-hal/microcontroller/Pin.h +++ b/ports/atmel-samd/common-hal/microcontroller/Pin.h @@ -10,14 +10,18 @@ #include "peripherals/samd/pins.h" -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_number); -void never_reset_pin_number(uint8_t pin_number); +// Pins are claimed in a table, not detected from their hardware configuration, so code +// that configures a pin directly must claim it. void claim_pin(const mcu_pin_obj_t *pin); +void claim_pin_number(uint8_t pin_number); +// Returns true when the pin is not claimed, and is not an SWD pin while a debugger is attached. bool pin_number_is_free(uint8_t pin_number); +uint8_t common_hal_mcu_pin_number(const mcu_pin_obj_t *pin); + typedef struct { const mcu_pin_obj_t *obj; uint8_t instance; diff --git a/ports/atmel-samd/common-hal/microcontroller/Processor.c b/ports/atmel-samd/common-hal/microcontroller/Processor.c index 95ecde815e6..7d36d0f7ab1 100644 --- a/ports/atmel-samd/common-hal/microcontroller/Processor.c +++ b/ports/atmel-samd/common-hal/microcontroller/Processor.c @@ -60,7 +60,6 @@ // channel argument (ignored in calls below) #define IGNORED_CHANNEL 0 - // Extract the production calibration data information from NVM (adapted from ASF sample), // then calculate the temperature // @@ -170,23 +169,12 @@ float common_hal_mcu_processor_get_temperature(void) { struct adc_sync_descriptor adc; static Adc *adc_insts[] = ADC_INSTS; - samd_peripherals_adc_setup(&adc, adc_insts[0]); #ifdef SAMD21 // The parameters chosen here are from the temperature example in: // http://www.atmel.com/images/Atmel-42645-ADC-Configurations-with-Examples_ApplicationNote_AT11481.pdf - // That note also recommends in general: - // "Discard the first conversion result whenever there is a change - // in ADC configuration like voltage reference / ADC channel change." - - adc_sync_set_resolution(&adc, ADC_CTRLB_RESSEL_12BIT_Val); - adc_sync_set_reference(&adc, ADC_REFCTRL_REFSEL_INT1V_Val); - // Channel arg is ignored. - adc_sync_enable_channel(&adc, IGNORED_CHANNEL); - adc_sync_set_inputs(&adc, - ADC_INPUTCTRL_MUXPOS_TEMP_Val, // pos_input - ADC_INPUTCTRL_MUXNEG_GND_Val, // neg_input - IGNORED_CHANNEL); // channel (ignored) + samd_peripherals_adc_start(&adc, adc_insts[0], ADC_REFCTRL_REFSEL_INT1V_Val, ADC_INPUTCTRL_GAIN_1X_Val, + ADC_INPUTCTRL_MUXPOS_TEMP_Val); hri_adc_write_CTRLB_PRESCALER_bf(adc.device.hw, ADC_CTRLB_PRESCALER_DIV32_Val); hri_adc_write_SAMPCTRL_SAMPLEN_bf(adc.device.hw, ADC_TEMP_SAMPLE_LENGTH); @@ -197,57 +185,33 @@ float common_hal_mcu_processor_get_temperature(void) { hri_adc_write_AVGCTRL_SAMPLENUM_bf(adc.device.hw, ADC_AVGCTRL_SAMPLENUM_4_Val); hri_adc_write_AVGCTRL_ADJRES_bf(adc.device.hw, 2); - volatile uint16_t value; - - // Read twice and discard first result, as recommended in section 14 of - // http://www.atmel.com/images/Atmel-42645-ADC-Configurations-with-Examples_ApplicationNote_AT11481.pdf - // "Discard the first conversion result whenever there is a change in ADC configuration - // like voltage reference / ADC channel change" - // Empirical observation shows the first reading is quite different than subsequent ones. - - // Channel arg is ignored. - adc_sync_read_channel(&adc, IGNORED_CHANNEL, ((uint8_t *)&value), 2); - adc_sync_read_channel(&adc, IGNORED_CHANNEL, ((uint8_t *)&value), 2); + uint16_t value = samd_peripherals_adc_read(&adc); adc_sync_deinit(&adc); return calculate_temperature(value); #endif // SAMD21 #ifdef SAM_D5X_E5X - adc_sync_set_resolution(&adc, ADC_CTRLB_RESSEL_12BIT_Val); - // Using INTVCC0 as the reference voltage. - // INTVCC1 seems to read a little high. - // INTREF doesn't work: ADC hangs BUSY. It's supposed to work, but does not. - // The SAME54 example from Atmel START implicitly uses INTREF. - adc_sync_set_reference(&adc, ADC_REFCTRL_REFSEL_INTVCC0_Val); - hri_supc_set_VREF_ONDEMAND_bit(SUPC); // Enable temperature sensor. hri_supc_set_VREF_TSEN_bit(SUPC); hri_supc_set_VREF_VREFOE_bit(SUPC); - // Channel arg is ignored. - adc_sync_enable_channel(&adc, IGNORED_CHANNEL); - adc_sync_set_inputs(&adc, - ADC_INPUTCTRL_MUXPOS_PTAT_Val, // pos_input - ADC_INPUTCTRL_MUXNEG_GND_Val, // neg_input - IGNORED_CHANNEL); // channel (ignored) + // Using INTVCC0 as the reference voltage. + // INTVCC1 seems to read a little high. + // INTREF doesn't work: ADC hangs BUSY. It's supposed to work, but does not. + // The SAME54 example from Atmel START implicitly uses INTREF. + samd_peripherals_adc_start(&adc, adc_insts[0], ADC_REFCTRL_REFSEL_INTVCC0_Val, 0, ADC_INPUTCTRL_MUXPOS_PTAT_Val); // Read both temperature sensors. - volatile uint16_t ptat; - volatile uint16_t ctat; - - // Read twice for stability (necessary?). - adc_sync_read_channel(&adc, IGNORED_CHANNEL, ((uint8_t *)&ptat), 2); - adc_sync_read_channel(&adc, IGNORED_CHANNEL, ((uint8_t *)&ptat), 2); + uint16_t ptat = samd_peripherals_adc_read(&adc); adc_sync_set_inputs(&adc, ADC_INPUTCTRL_MUXPOS_CTAT_Val, // pos_input ADC_INPUTCTRL_MUXNEG_GND_Val, // neg_input IGNORED_CHANNEL); // channel (ignored) - adc_sync_read_channel(&adc, IGNORED_CHANNEL, ((uint8_t *)&ctat), 2); - adc_sync_read_channel(&adc, IGNORED_CHANNEL, ((uint8_t *)&ctat), 2); + uint16_t ctat = samd_peripherals_adc_read(&adc); // Turn off temp sensor. hri_supc_clear_VREF_TSEN_bit(SUPC); @@ -261,10 +225,9 @@ float common_hal_mcu_processor_get_voltage(void) { struct adc_sync_descriptor adc; static Adc *adc_insts[] = ADC_INSTS; - samd_peripherals_adc_setup(&adc, adc_insts[0]); #ifdef SAMD21 - adc_sync_set_reference(&adc, ADC_REFCTRL_REFSEL_INT1V_Val); + const uint8_t reference = ADC_REFCTRL_REFSEL_INT1V_Val; #endif #ifdef SAM_D5X_E5X @@ -272,33 +235,18 @@ float common_hal_mcu_processor_get_voltage(void) { hri_supc_set_VREF_SEL_bf(SUPC, SUPC_VREF_SEL_1V0_Val); hri_supc_set_VREF_VREFOE_bit(SUPC); - adc_sync_set_reference(&adc, ADC_REFCTRL_REFSEL_INTREF_Val); - // On some processor samples, the ADC will hang trying to read the voltage. A simple // delay after setting the SUPC bits seems to fix things. This appears to be due to VREFOE // startup time. There is no synchronization bit to check. // See https://community.atmel.com/forum/samd51-using-intref-adc-voltage-reference mp_hal_delay_ms(1); - #endif - - adc_sync_set_resolution(&adc, ADC_CTRLB_RESSEL_12BIT_Val); - // Channel arg is ignored. - adc_sync_set_inputs(&adc, - ADC_INPUTCTRL_MUXPOS_SCALEDIOVCC_Val, // IOVCC/4 (nominal 3.3V/4) - ADC_INPUTCTRL_MUXNEG_GND_Val, // neg_input - IGNORED_CHANNEL); // channel (ignored). - adc_sync_enable_channel(&adc, IGNORED_CHANNEL); - volatile uint16_t reading; + const uint8_t reference = ADC_REFCTRL_REFSEL_INTREF_Val; + #endif - // Channel arg is ignored. - // Read twice and discard first result, as recommended in section 14 of - // http://www.atmel.com/images/Atmel-42645-ADC-Configurations-with-Examples_ApplicationNote_AT11481.pdf - // "Discard the first conversion result whenever there is a change in ADC configuration - // like voltage reference / ADC channel change" - // Empirical observation shows the first reading is quite different than subsequent ones. - adc_sync_read_channel(&adc, IGNORED_CHANNEL, ((uint8_t *)&reading), 2); - adc_sync_read_channel(&adc, IGNORED_CHANNEL, ((uint8_t *)&reading), 2); + // IOVCC/4 (nominal 3.3V/4). The gain argument is ignored on SAMD51. + samd_peripherals_adc_start(&adc, adc_insts[0], reference, 0, ADC_INPUTCTRL_MUXPOS_SCALEDIOVCC_Val); + uint16_t reading = samd_peripherals_adc_read(&adc); adc_sync_deinit(&adc); // Multiply by 4 to compensate for SCALEDIOVCC division by 4. @@ -328,5 +276,5 @@ void common_hal_mcu_processor_get_uid(uint8_t raw_id[]) { } mcu_reset_reason_t common_hal_mcu_processor_get_reset_reason(void) { - return RESET_REASON_UNKNOWN; + return MCU_RESET_REASON_UNKNOWN; } diff --git a/ports/atmel-samd/common-hal/paralleldisplaybus/ParallelBus.c b/ports/atmel-samd/common-hal/paralleldisplaybus/ParallelBus.c index 6f56753d29a..69f0ce0ff3d 100644 --- a/ports/atmel-samd/common-hal/paralleldisplaybus/ParallelBus.c +++ b/ports/atmel-samd/common-hal/paralleldisplaybus/ParallelBus.c @@ -35,6 +35,9 @@ void common_hal_paralleldisplaybus_parallelbus_construct(paralleldisplaybus_para wrconfig |= 0xff << (data_pin % 32); } g->WRCONFIG.reg = wrconfig; + for (uint8_t i = 0; i < 8; i++) { + claim_pin_number(data_pin + i); + } self->bus = ((uint8_t *)&g->OUT.reg) + (data0->number % 32 / 8); self->command.base.type = &digitalio_digitalinout_type; @@ -54,7 +57,6 @@ void common_hal_paralleldisplaybus_parallelbus_construct(paralleldisplaybus_para 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); - never_reset_pin_number(read->number); } self->data0_pin = data_pin; @@ -66,28 +68,35 @@ void common_hal_paralleldisplaybus_parallelbus_construct(paralleldisplaybus_para 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_paralleldisplaybus_parallelbus_reset(self); } - never_reset_pin_number(command->number); - never_reset_pin_number(chip_select->number); - never_reset_pin_number(write->number); for (uint8_t i = 0; i < 8; i++) { - never_reset_pin_number(data_pin + i); } } void common_hal_paralleldisplaybus_parallelbus_deinit(paralleldisplaybus_parallelbus_obj_t *self) { + // The bus lives in a supervisor-allocated slot and may be deinited when it + // was never constructed, so guard on the always-present command pin. + if (self->command.base.type == NULL || self->command.base.type == &mp_type_NoneType) { + return; + } + for (uint8_t i = 0; i < 8; i++) { reset_pin_number(self->data0_pin + i); } + self->data0_pin = NO_PIN; - reset_pin_number(self->command.pin->number); - reset_pin_number(self->chip_select.pin->number); - reset_pin_number(self->write.pin->number); - reset_pin_number(self->read.pin->number); - reset_pin_number(self->reset.pin->number); + common_hal_digitalio_digitalinout_deinit(&self->command); + common_hal_digitalio_digitalinout_deinit(&self->chip_select); + common_hal_digitalio_digitalinout_deinit(&self->write); + if (self->read.base.type == &digitalio_digitalinout_type) { + common_hal_digitalio_digitalinout_deinit(&self->read); + } + if (self->reset.base.type == &digitalio_digitalinout_type) { + common_hal_digitalio_digitalinout_deinit(&self->reset); + } + self->command.base.type = &mp_type_NoneType; } bool common_hal_paralleldisplaybus_parallelbus_reset(mp_obj_t obj) { diff --git a/ports/atmel-samd/common-hal/ps2io/Ps2.c b/ports/atmel-samd/common-hal/ps2io/Ps2.c index 006833c3d63..7bb072368b9 100644 --- a/ports/atmel-samd/common-hal/ps2io/Ps2.c +++ b/ports/atmel-samd/common-hal/ps2io/Ps2.c @@ -222,8 +222,17 @@ void ps2_interrupt_handler(uint8_t channel) { } } +// Mark the object deinited: deinited() is true and deinit() does nothing. +static void mark_deinit(ps2io_ps2_obj_t *self) { + self->clock_pin = NO_PIN; + self->data_pin = NO_PIN; +} + void common_hal_ps2io_ps2_construct(ps2io_ps2_obj_t *self, const mcu_pin_obj_t *data_pin, const mcu_pin_obj_t *clock_pin) { + // Ensure the object starts in its deinit state. + mark_deinit(self); + if (!clock_pin->has_extint) { mp_arg_error_invalid(MP_QSTR_clock_pin); } @@ -231,12 +240,12 @@ void common_hal_ps2io_ps2_construct(ps2io_ps2_obj_t *self, mp_raise_RuntimeError(MP_ERROR_TEXT("Internal resource(s) in use")); } - clk_hi(self); - data_hi(self); - self->channel = clock_pin->extint_channel; self->clock_pin = clock_pin->number; self->data_pin = data_pin->number; + // These configure the pins in self, so call them only once they're set. + clk_hi(self); + data_hi(self); self->state = STATE_IDLE; self->bufcount = 0; self->bufposr = 0; @@ -274,8 +283,7 @@ void common_hal_ps2io_ps2_deinit(ps2io_ps2_obj_t *self) { turn_off_eic_channel(self->channel); reset_pin_number(self->clock_pin); reset_pin_number(self->data_pin); - self->clock_pin = NO_PIN; - self->data_pin = NO_PIN; + mark_deinit(self); } uint16_t common_hal_ps2io_ps2_get_len(ps2io_ps2_obj_t *self) { diff --git a/ports/atmel-samd/common-hal/pulseio/PulseIn.c b/ports/atmel-samd/common-hal/pulseio/PulseIn.c index 705f8ceeb8b..3ef8ddb4f92 100644 --- a/ports/atmel-samd/common-hal/pulseio/PulseIn.c +++ b/ports/atmel-samd/common-hal/pulseio/PulseIn.c @@ -121,8 +121,16 @@ void pulsein_interrupt_handler(uint8_t channel) { common_hal_mcu_enable_interrupts(); } +// Mark the object deinited: deinited() is true and deinit() does nothing. +static void mark_deinit(pulseio_pulsein_obj_t *self) { + self->pin = NO_PIN; +} + void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t *self, const mcu_pin_obj_t *pin, uint16_t maxlen, bool idle_state) { + // Ensure the object starts in its deinit state. + mark_deinit(self); + if (!pin->has_extint) { raise_ValueError_invalid_pin(); } @@ -130,12 +138,11 @@ void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t *self, mp_raise_RuntimeError(MP_ERROR_TEXT("Internal resource(s) in use")); } - self->buffer = (uint16_t *)m_malloc(maxlen * sizeof(uint16_t)); + self->buffer = (uint16_t *)m_malloc_without_collect(maxlen * sizeof(uint16_t)); if (self->buffer == NULL) { m_malloc_fail(maxlen * sizeof(uint16_t)); } self->channel = pin->extint_channel; - self->pin = pin->number; self->maxlen = maxlen; self->idle_state = idle_state; self->start = 0; @@ -194,6 +201,9 @@ void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t *self, overflow_count = 0; } refcount++; + // Set the pin only after the last raise: until then the object reads as + // deinited, so its finaliser doesn't drop a refcount it never took. + self->pin = pin->number; self->last_overflow = overflow_count; self->last_count = 0; @@ -234,10 +244,15 @@ void common_hal_pulseio_pulsein_deinit(pulseio_pulsein_obj_t *self) { refcount--; if (refcount == 0) { - tc_reset(tc_insts[pulsein_tc_index]); + Tc *tc = tc_insts[pulsein_tc_index]; + tc->COUNT16.INTENCLR.reg = TC_INTENCLR_OVF; + tc_disable_interrupts(pulsein_tc_index); + tc_reset(tc); + set_timer_handler(true, pulsein_tc_index, TC_HANDLER_NO_INTERRUPT); + turn_off_clocks(TIMER_TYPE_TC, pulsein_tc_index); pulsein_tc_index = 0xff; } - self->pin = NO_PIN; + mark_deinit(self); } void common_hal_pulseio_pulsein_pause(pulseio_pulsein_obj_t *self) { diff --git a/ports/atmel-samd/common-hal/pulseio/PulseOut.c b/ports/atmel-samd/common-hal/pulseio/PulseOut.c index a345405533a..f1913cb365f 100644 --- a/ports/atmel-samd/common-hal/pulseio/PulseOut.c +++ b/ports/atmel-samd/common-hal/pulseio/PulseOut.c @@ -95,6 +95,9 @@ void common_hal_pulseio_pulseout_construct(pulseio_pulseout_obj_t *self, } } if (tc == NULL) { + // deinited() checks the PWMOut, so release it before raising. + // Otherwise the finaliser would run deinit() on this half-built object. + common_hal_pwmio_pwmout_deinit(&self->pwmout); mp_raise_RuntimeError(MP_ERROR_TEXT("All timers in use")); } @@ -159,7 +162,12 @@ void common_hal_pulseio_pulseout_deinit(pulseio_pulseout_obj_t *self) { refcount--; if (refcount == 0) { - tc_reset(tc_insts[pulseout_tc_index]); + Tc *tc = tc_insts[pulseout_tc_index]; + tc->COUNT16.INTENCLR.reg = TC_INTENCLR_MC0; + tc_disable_interrupts(pulseout_tc_index); + tc_reset(tc); + set_timer_handler(true, pulseout_tc_index, TC_HANDLER_NO_INTERRUPT); + turn_off_clocks(TIMER_TYPE_TC, pulseout_tc_index); pulseout_tc_index = 0xff; } self->pin = NO_PIN; diff --git a/ports/atmel-samd/common-hal/pwmio/PWMOut.c b/ports/atmel-samd/common-hal/pwmio/PWMOut.c index 71d6f38d502..e91381f210d 100644 --- a/ports/atmel-samd/common-hal/pwmio/PWMOut.c +++ b/ports/atmel-samd/common-hal/pwmio/PWMOut.c @@ -31,17 +31,10 @@ 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 SAM_D5X_E5X -uint8_t tcc_channels[5]; // Set by pwmout_reset() to {0xc0, 0xf0, 0xf8, 0xfc, 0xfc} initially. -#endif +// A variable-frequency PWMOut claims all of them (0xff). +uint8_t tcc_channels[TCC_INST_NUM]; -void common_hal_pwmio_pwmout_never_reset(pwmio_pwmout_obj_t *self) { - never_reset_pin_number(self->pin->number); -} 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 @@ -55,6 +48,22 @@ static bool channel_ok(const pin_timer_t *t) { t->is_tc; } +// Find the divisor that gets the highest resolution: the smallest prescaler for which +// the period fits in the timer. Sets *top to the period. +static uint8_t compute_divisor(const pin_timer_t *t, uint32_t system_clock, uint32_t frequency, + uint32_t *top) { + // TCC resolution varies so look it up. + uint8_t resolution = t->is_tc ? 16 : tcc_sizes[t->index]; + uint8_t divisor; + for (divisor = 0; divisor < 8; divisor++) { + *top = (system_clock / prescaler[divisor] / frequency) - 1; + if (*top < (1u << resolution)) { + break; + } + } + return divisor; +} + pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t *self, const mcu_pin_obj_t *pin, uint16_t duty, @@ -141,22 +150,8 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t *self, return PWMOUT_INTERNAL_RESOURCES_IN_USE; } - uint8_t resolution = 0; - if (timer->is_tc) { - resolution = 16; - } else { - // TCC resolution varies so look it up. - resolution = tcc_sizes[timer->index]; - } - // First determine the divisor that gets us the highest resolution. uint32_t top; - uint8_t divisor; - for (divisor = 0; divisor < 8; divisor++) { - top = (system_clock / prescaler[divisor] / frequency) - 1; - if (top < (1u << resolution)) { - break; - } - } + uint8_t divisor = compute_divisor(timer, system_clock, frequency, &top); set_timer_handler(timer->is_tc, timer->index, TC_HANDLER_NO_INTERRUPT); // We use the zeroeth clock on either port to go full speed. @@ -207,6 +202,7 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t *self, self->pin = pin; gpio_set_pin_function(pin->number, GPIO_PIN_FUNCTION_E + mux_position); + claim_pin(pin); common_hal_pwmio_pwmout_set_duty_cycle(self, duty); return PWMOUT_OK; @@ -226,10 +222,13 @@ void common_hal_pwmio_pwmout_deinit(pwmio_pwmout_obj_t *self) { tc_set_enable(tc, false); tc->COUNT16.CTRLA.bit.SWRST = true; tc_wait_for_sync(tc); + turn_off_clocks(TIMER_TYPE_TC, t->index); } else { tcc_refcount[t->index]--; tcc_channels[t->index] &= ~(1 << tcc_channel(t)); if (tcc_refcount[t->index] == 0) { + // A variable-frequency PWMOut claimed every channel, not just its own. + tcc_channels[t->index] = 0; target_tcc_frequencies[t->index] = 0; Tcc *tcc = tcc_insts[t->index]; tcc_set_enable(tcc, false); @@ -237,6 +236,7 @@ void common_hal_pwmio_pwmout_deinit(pwmio_pwmout_obj_t *self) { while (tcc->SYNCBUSY.bit.SWRST != 0) { /* Wait for sync */ } + turn_off_clocks(TIMER_TYPE_TCC, t->index); } } reset_pin_number(self->pin->number); @@ -333,21 +333,8 @@ void common_hal_pwmio_pwmout_set_frequency(pwmio_pwmout_obj_t *self, mp_arg_error_invalid(MP_QSTR_frequency); } const pin_timer_t *t = self->timer; - uint8_t resolution; - if (t->is_tc) { - resolution = 16; - } else { - // TCC resolution varies so look it up. - resolution = tcc_sizes[t->index]; - } 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; - } - } + uint8_t new_divisor = compute_divisor(t, system_clock, frequency, &new_top); if (t->is_tc) { Tc *tc = tc_insts[t->index]; uint8_t old_divisor = tc->COUNT16.CTRLA.bit.PRESCALER; diff --git a/ports/atmel-samd/common-hal/rgbmatrix/RGBMatrix.c b/ports/atmel-samd/common-hal/rgbmatrix/RGBMatrix.c index c0b6386b4be..98c0880a12e 100644 --- a/ports/atmel-samd/common-hal/rgbmatrix/RGBMatrix.c +++ b/ports/atmel-samd/common-hal/rgbmatrix/RGBMatrix.c @@ -20,7 +20,7 @@ void *common_hal_rgbmatrix_timer_allocate(rgbmatrix_rgbmatrix_obj_t *self) { } static uint8_t tc_index_from_ptr(void *ptr) { - for (uint8_t i = TC_INST_NUM; i > 0; i--) { + for (uint8_t i = 0; i < TC_INST_NUM; i++) { if (tc_insts[i] == ptr) { return i; } @@ -53,4 +53,5 @@ void common_hal_rgbmatrix_timer_free(void *ptr) { } tc_set_enable(ptr, false); tc_reset(ptr); + turn_off_clocks(TIMER_TYPE_TC, timer_index); } diff --git a/ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.c b/ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.c index c6cd4605784..a8c87d82ed2 100644 --- a/ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.c +++ b/ports/atmel-samd/common-hal/rotaryio/IncrementalEncoder.c @@ -17,6 +17,10 @@ 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) { + + // Ensure object starts in its deinit state. + common_hal_rotaryio_incrementalencoder_mark_deinit(self); + if (!pin_a->has_extint) { raise_ValueError_invalid_pin_name(MP_QSTR_pin_a); } @@ -83,10 +87,13 @@ void common_hal_rotaryio_incrementalencoder_deinit(rotaryio_incrementalencoder_o turn_off_eic_channel(self->eic_channel_b); reset_pin_number(self->pin_a); - self->pin_a = NO_PIN; - reset_pin_number(self->pin_b); - self->pin_b = NO_PIN; + + common_hal_rotaryio_incrementalencoder_mark_deinit(self); +} + +void common_hal_rotaryio_incrementalencoder_mark_deinit(rotaryio_incrementalencoder_obj_t *self) { + self->pin_a = NO_PIN; } void incrementalencoder_interrupt_handler(uint8_t channel) { diff --git a/ports/atmel-samd/common-hal/sdioio/SDCard.c b/ports/atmel-samd/common-hal/sdioio/SDCard.c index 8ff1a391bb2..002b74622a4 100644 --- a/ports/atmel-samd/common-hal/sdioio/SDCard.c +++ b/ports/atmel-samd/common-hal/sdioio/SDCard.c @@ -9,6 +9,7 @@ #include "py/runtime.h" #include "common-hal/microcontroller/Pin.h" +#include "extmod/vfs.h" #include "shared-bindings/sdioio/SDCard.h" #include "shared-bindings/microcontroller/Pin.h" #include "shared-bindings/microcontroller/__init__.h" @@ -36,9 +37,22 @@ static Sdhc *sdhc_insts[] = SDHC_INSTS; +// Mark the object deinited: deinited() is true and deinit() does nothing. +static void mark_deinit(sdioio_sdcard_obj_t *self) { + self->command_pin = COMMON_HAL_MCU_NO_PIN; + self->clock_pin = COMMON_HAL_MCU_NO_PIN; + self->data_pins[0] = COMMON_HAL_MCU_NO_PIN; + self->data_pins[1] = COMMON_HAL_MCU_NO_PIN; + self->data_pins[2] = COMMON_HAL_MCU_NO_PIN; + self->data_pins[3] = COMMON_HAL_MCU_NO_PIN; +} + 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, const mcu_pin_obj_t **data, uint32_t frequency) { + // Ensure the object starts in its deinit state. + mark_deinit(self); + /* SD breakout as assembled ("*" = minimum viable set) @@ -61,6 +75,7 @@ CLK PA21 PCC_D? (D32) BROWN mcu_pin_function_t *functions[6] = {}; functions[0] = mcu_find_pin_function(sdio_cmd, command, -1, MP_QSTR_command); int instance = functions[0]->instance; + self->instance = instance; functions[1] = mcu_find_pin_function(sdio_ck, clock, instance, MP_QSTR_clock); functions[2] = mcu_find_pin_function(sdio_dat0, data[0], instance, MP_QSTR_data0); if (num_data == 4) { @@ -83,7 +98,8 @@ CLK PA21 PCC_D? (D32) BROWN } for (size_t i = 0; i < MP_ARRAY_SIZE(functions); i++) { - if (!functions[i]->obj) { + // With one data pin, functions[3] to functions[5] are NULL. + if (!functions[i]) { break; } @@ -93,6 +109,7 @@ CLK PA21 PCC_D? (D32) BROWN gpio_set_pin_pull_mode(functions[i]->pin, (i == 1 || i == 5) ? GPIO_PULL_OFF : GPIO_PULL_UP); gpio_set_pin_function(functions[i]->pin, GPIO_PIN_FUNCTION_SDIO); + claim_pin(functions[i]->obj); } self->num_data = num_data; @@ -122,12 +139,9 @@ CLK PA21 PCC_D? (D32) BROWN } if (result != SD_MMC_OK) { - for (size_t i = 0; i < MP_ARRAY_SIZE(functions); i++) { - if (!functions[i]->obj) { - break; - } - reset_pin_number(functions[i]->obj->number); - } + // Everything deinit() undoes is set up by now: it powers the SDHC down, + // releases the pins and marks the object deinited. + common_hal_sdioio_sdcard_deinit(self); mp_raise_OSError_msg_varg(MP_ERROR_TEXT("%q failure: %d"), MP_QSTR_sd_mmc_check, (int)result); } // sd_mmc_get_capacity() is in KiB, but our "capacity" is in 512-byte blocks @@ -170,43 +184,85 @@ static void debug_print_state(sdioio_sdcard_obj_t *self, const char *what, sd_mm #endif } -int common_hal_sdioio_sdcard_writeblocks(sdioio_sdcard_obj_t *self, uint32_t start_block, mp_buffer_info_t *bufinfo) { - check_for_deinit(self); - check_whole_block(bufinfo); +mp_negative_errno_t sdioio_sdcard_writeblocks(mp_obj_t self_in, uint8_t *buf, + uint32_t start_block, uint32_t num_blocks) { + sdioio_sdcard_obj_t *self = MP_OBJ_TO_PTR(self_in); wait_write_complete(self); self->state_programming = true; - sd_mmc_err_t r = sd_mmc_init_write_blocks(0, start_block, bufinfo->len / 512); + sd_mmc_err_t r = sd_mmc_init_write_blocks(0, start_block, num_blocks); if (r != SD_MMC_OK) { debug_print_state(self, "sd_mmc_init_write_blocks", r); - return -EIO; + return -MP_EIO; } - r = sd_mmc_start_write_blocks(bufinfo->buf, bufinfo->len / 512); + r = sd_mmc_start_write_blocks(buf, num_blocks); if (r != SD_MMC_OK) { debug_print_state(self, "sd_mmc_start_write_blocks", r); - return -EIO; + return -MP_EIO; } - // debug_print_state(self, "after writeblocks OK"); return 0; } -int common_hal_sdioio_sdcard_readblocks(sdioio_sdcard_obj_t *self, uint32_t start_block, mp_buffer_info_t *bufinfo) { +mp_negative_errno_t common_hal_sdioio_sdcard_writeblocks(sdioio_sdcard_obj_t *self, uint32_t start_block, mp_buffer_info_t *bufinfo) { check_for_deinit(self); check_whole_block(bufinfo); + + uint32_t num_blocks = bufinfo->len / 512; + return sdioio_sdcard_writeblocks(MP_OBJ_FROM_PTR(self), bufinfo->buf, + start_block, num_blocks); +} + +mp_negative_errno_t sdioio_sdcard_readblocks(mp_obj_t self_in, uint8_t *buf, + uint32_t start_block, uint32_t num_blocks) { + sdioio_sdcard_obj_t *self = MP_OBJ_TO_PTR(self_in); wait_write_complete(self); - sd_mmc_err_t r = sd_mmc_init_read_blocks(0, start_block, bufinfo->len / 512); + sd_mmc_err_t r = sd_mmc_init_read_blocks(0, start_block, num_blocks); if (r != SD_MMC_OK) { debug_print_state(self, "sd_mmc_init_read_blocks", r); - return -EIO; + return -MP_EIO; } - r = sd_mmc_start_read_blocks(bufinfo->buf, bufinfo->len / 512); + r = sd_mmc_start_read_blocks(buf, num_blocks); if (r != SD_MMC_OK) { debug_print_state(self, "sd_mmc_start_read_blocks", r); - return -EIO; + return -MP_EIO; } sd_mmc_wait_end_of_write_blocks(0); return 0; } +mp_negative_errno_t common_hal_sdioio_sdcard_readblocks(sdioio_sdcard_obj_t *self, uint32_t start_block, mp_buffer_info_t *bufinfo) { + check_for_deinit(self); + check_whole_block(bufinfo); + + uint32_t num_blocks = bufinfo->len / 512; + return sdioio_sdcard_readblocks(MP_OBJ_FROM_PTR(self), bufinfo->buf, + start_block, num_blocks); +} + +// Native function for VFS blockdev layer +bool sdioio_sdcard_ioctl(mp_obj_t self_in, size_t cmd, size_t arg, + mp_int_t *out_value) { + sdioio_sdcard_obj_t *self = MP_OBJ_TO_PTR(self_in); + *out_value = 0; + + switch (cmd) { + case MP_BLOCKDEV_IOCTL_DEINIT: + case MP_BLOCKDEV_IOCTL_SYNC: + // SDIO operations are synchronous, no action needed + return true; + + case MP_BLOCKDEV_IOCTL_BLOCK_COUNT: + *out_value = common_hal_sdioio_sdcard_get_count(self); + return true; + + case MP_BLOCKDEV_IOCTL_BLOCK_SIZE: + *out_value = 512; // SD cards use 512-byte sectors + return true; + + default: + return false; // Unsupported command + } +} + bool common_hal_sdioio_sdcard_configure(sdioio_sdcard_obj_t *self, uint32_t frequency, uint8_t bits) { check_for_deinit(self); return true; @@ -217,6 +273,13 @@ bool common_hal_sdioio_sdcard_deinited(sdioio_sdcard_obj_t *self) { } void common_hal_sdioio_sdcard_deinit(sdioio_sdcard_obj_t *self) { + if (common_hal_sdioio_sdcard_deinited(self)) { + return; + } + + wait_write_complete(self); + mci_sync_deinit(&self->IO_BUS); + reset_pin_number(self->command_pin); reset_pin_number(self->clock_pin); reset_pin_number(self->data_pins[0]); @@ -224,13 +287,18 @@ void common_hal_sdioio_sdcard_deinit(sdioio_sdcard_obj_t *self) { reset_pin_number(self->data_pins[2]); reset_pin_number(self->data_pins[3]); - self->command_pin = COMMON_HAL_MCU_NO_PIN; - self->clock_pin = COMMON_HAL_MCU_NO_PIN; - self->data_pins[0] = COMMON_HAL_MCU_NO_PIN; - self->data_pins[1] = COMMON_HAL_MCU_NO_PIN; - self->data_pins[2] = COMMON_HAL_MCU_NO_PIN; - self->data_pins[3] = COMMON_HAL_MCU_NO_PIN; -} + // Power down the SDHC peripheral. + if (self->instance == 0) { + hri_gclk_write_PCHCTRL_reg(GCLK, SDHC0_GCLK_ID, 0); + hri_gclk_write_PCHCTRL_reg(GCLK, SDHC0_GCLK_ID_SLOW, 0); + hri_mclk_clear_AHBMASK_SDHC0_bit(MCLK); + #ifdef SDHC1_GCLK_ID + } else { + hri_gclk_write_PCHCTRL_reg(GCLK, SDHC1_GCLK_ID, 0); + hri_gclk_write_PCHCTRL_reg(GCLK, SDHC1_GCLK_ID_SLOW, 0); + hri_mclk_clear_AHBMASK_SDHC1_bit(MCLK); + #endif + } -void common_hal_sdioio_sdcard_never_reset(sdioio_sdcard_obj_t *self) { + mark_deinit(self); } diff --git a/ports/atmel-samd/common-hal/sdioio/SDCard.h b/ports/atmel-samd/common-hal/sdioio/SDCard.h index 8b8c2fd39f8..c86e12426ec 100644 --- a/ports/atmel-samd/common-hal/sdioio/SDCard.h +++ b/ports/atmel-samd/common-hal/sdioio/SDCard.h @@ -14,6 +14,7 @@ typedef struct { uint32_t frequency; uint32_t capacity; uint8_t num_data : 3, state_programming : 1, has_lock : 1; + uint8_t instance; uint8_t command_pin; uint8_t clock_pin; uint8_t data_pins[4]; diff --git a/ports/atmel-samd/common-hal/socketpool/Socket.c b/ports/atmel-samd/common-hal/socketpool/Socket.c new file mode 100644 index 00000000000..b954dad158c --- /dev/null +++ b/ports/atmel-samd/common-hal/socketpool/Socket.c @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// shared-module/_airlift/socketpool.c implements socketpool on this port. diff --git a/ports/atmel-samd/common-hal/socketpool/Socket.h b/ports/atmel-samd/common-hal/socketpool/Socket.h new file mode 100644 index 00000000000..466015dc61e --- /dev/null +++ b/ports/atmel-samd/common-hal/socketpool/Socket.h @@ -0,0 +1,10 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// The sockets live on the ESP32 co-processor (nina-fw). +#include "shared-module/_airlift/socketpool.h" diff --git a/ports/atmel-samd/common-hal/socketpool/SocketPool.c b/ports/atmel-samd/common-hal/socketpool/SocketPool.c new file mode 100644 index 00000000000..b954dad158c --- /dev/null +++ b/ports/atmel-samd/common-hal/socketpool/SocketPool.c @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// shared-module/_airlift/socketpool.c implements socketpool on this port. diff --git a/ports/atmel-samd/common-hal/socketpool/SocketPool.h b/ports/atmel-samd/common-hal/socketpool/SocketPool.h new file mode 100644 index 00000000000..466015dc61e --- /dev/null +++ b/ports/atmel-samd/common-hal/socketpool/SocketPool.h @@ -0,0 +1,10 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// The sockets live on the ESP32 co-processor (nina-fw). +#include "shared-module/_airlift/socketpool.h" diff --git a/ports/atmel-samd/common-hal/socketpool/__init__.c b/ports/atmel-samd/common-hal/socketpool/__init__.c new file mode 100644 index 00000000000..b954dad158c --- /dev/null +++ b/ports/atmel-samd/common-hal/socketpool/__init__.c @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// shared-module/_airlift/socketpool.c implements socketpool on this port. diff --git a/ports/atmel-samd/common-hal/spitarget/SPITarget.c b/ports/atmel-samd/common-hal/spitarget/SPITarget.c index b9062911cc3..f6c54638d7c 100644 --- a/ports/atmel-samd/common-hal/spitarget/SPITarget.c +++ b/ports/atmel-samd/common-hal/spitarget/SPITarget.c @@ -15,6 +15,14 @@ #include "hpl_sercom_config.h" #include "samd/sercom.h" +// Mark the object deinited: deinited() is true and deinit() does nothing. +static void mark_deinit(spitarget_spi_target_obj_t *self) { + self->clock_pin = NO_PIN; + self->MOSI_pin = NO_PIN; + self->MISO_pin = NO_PIN; + self->SS_pin = NO_PIN; +} + void common_hal_spitarget_spi_target_construct(spitarget_spi_target_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 *ss) { @@ -30,7 +38,7 @@ void common_hal_spitarget_spi_target_construct(spitarget_spi_target_obj_t *self, uint8_t dopo = 255; // Ensure the object starts in its deinit state. - self->clock_pin = NO_PIN; + mark_deinit(self); // Special case for SAMR21 boards. (feather_radiofruit_zigbee) #if defined(PIN_PC19F_SERCOM4_PAD0) @@ -168,15 +176,16 @@ void common_hal_spitarget_spi_target_deinit(spitarget_spi_target_obj_t *self) { if (common_hal_spitarget_spi_target_deinited(self)) { return; } - allow_reset_sercom(self->spi_desc.dev.prvt); - + // Stop and free the DMA channels of a transfer still in progress, for + // example one interrupted by ctrl-C. Does nothing if none is running. + common_hal_spitarget_spi_target_transfer_close(self); spi_m_sync_disable(&self->spi_desc); spi_m_sync_deinit(&self->spi_desc); reset_pin_number(self->clock_pin); reset_pin_number(self->MOSI_pin); reset_pin_number(self->MISO_pin); reset_pin_number(self->SS_pin); - self->clock_pin = NO_PIN; + mark_deinit(self); } void common_hal_spitarget_spi_target_transfer_start(spitarget_spi_target_obj_t *self, @@ -192,7 +201,7 @@ void common_hal_spitarget_spi_target_transfer_start(spitarget_spi_target_obj_t * self->miso_packet = miso_packet; Sercom *sercom = self->spi_desc.dev.prvt; - self->running_dma = shared_dma_transfer_start(sercom, miso_packet, &sercom->SPI.DATA.reg, &sercom->SPI.DATA.reg, mosi_packet, len, 0); + shared_dma_transfer_start(&self->running_dma, sercom, miso_packet, &sercom->SPI.DATA.reg, &sercom->SPI.DATA.reg, mosi_packet, len, 0); // There is an issue where if an unexpected SPI transfer is received before the user calls "end" for the in-progress, expected // transfer, the SERCOM has an error and gets confused. This can be detected from INTFLAG.ERROR. I think the code in @@ -200,7 +209,7 @@ void common_hal_spitarget_spi_target_transfer_start(spitarget_spi_target_obj_t * // s->SPI.DATA.reg) is supposed to fix this, but experimentation seems to show that it does not in fact fix anything. Anyways, if // the ERROR bit is set, let's just reset the peripheral and then setup the transfer again -- that seems to work. if (hri_sercomspi_get_INTFLAG_ERROR_bit(sercom)) { - shared_dma_transfer_close(self->running_dma); + shared_dma_transfer_close(&self->running_dma); // disable the sercom spi_m_sync_disable(&self->spi_desc); @@ -223,19 +232,19 @@ void common_hal_spitarget_spi_target_transfer_start(spitarget_spi_target_obj_t * spi_m_sync_enable(&self->spi_desc); hri_sercomspi_wait_for_sync(sercom, SERCOM_SPI_SYNCBUSY_MASK); - self->running_dma = shared_dma_transfer_start(sercom, miso_packet, &sercom->SPI.DATA.reg, &sercom->SPI.DATA.reg, mosi_packet, len, 0); + shared_dma_transfer_start(&self->running_dma, sercom, miso_packet, &sercom->SPI.DATA.reg, &sercom->SPI.DATA.reg, mosi_packet, len, 0); } } bool common_hal_spitarget_spi_target_transfer_is_finished(spitarget_spi_target_obj_t *self) { - return self->running_dma.failure == 1 || shared_dma_transfer_finished(self->running_dma); + return self->running_dma.failure == 1 || shared_dma_transfer_finished(&self->running_dma); } int common_hal_spitarget_spi_target_transfer_close(spitarget_spi_target_obj_t *self) { if (self->running_dma.failure == 1) { return 0; } - int res = shared_dma_transfer_close(self->running_dma); + int res = shared_dma_transfer_close(&self->running_dma); self->running_dma.failure = 1; self->mosi_packet = NULL; diff --git a/ports/atmel-samd/common-hal/spitarget/SPITarget.h b/ports/atmel-samd/common-hal/spitarget/SPITarget.h index 50f2bcb3309..9fff23c1743 100644 --- a/ports/atmel-samd/common-hal/spitarget/SPITarget.h +++ b/ports/atmel-samd/common-hal/spitarget/SPITarget.h @@ -18,7 +18,7 @@ typedef struct { uint8_t *mosi_packet; const uint8_t *miso_packet; - dma_descr_t running_dma; + dma_transfer_t running_dma; } spitarget_spi_target_obj_t; #endif // MICROPY_INCLUDED_ATMEL_SAMD_COMMON_HAL_BUSIO_SPI_TARGET_H diff --git a/ports/atmel-samd/common-hal/touchio/TouchIn.c b/ports/atmel-samd/common-hal/touchio/TouchIn.c index 05c3f3ee923..6f550aed85e 100644 --- a/ports/atmel-samd/common-hal/touchio/TouchIn.c +++ b/ports/atmel-samd/common-hal/touchio/TouchIn.c @@ -12,8 +12,11 @@ #include "py/binary.h" #include "py/mphal.h" #include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/digitalio/Pull.h" #include "shared-bindings/touchio/TouchIn.h" +#include "common-hal/touchio/TouchIn.h" + // Native touchio only exists for SAMD21 #ifdef SAMD21 @@ -24,7 +27,13 @@ #include "adafruit_ptc.h" -bool touch_enabled = false; +// The PTC is shared by all TouchIn objects, so it is refcounted. The first +// object turns on the PTC and its clocks; the last one to deinit turns them +// all off again. +static uint8_t touchin_refcount = 0; +static uint8_t touchin_gclk = 0xff; + +static void touchin_reset(void); static uint16_t get_raw_reading(touchio_touchin_obj_t *self) { adafruit_ptc_start_conversion(PTC, &self->config); @@ -37,20 +46,29 @@ static uint16_t get_raw_reading(touchio_touchin_obj_t *self) { return adafruit_ptc_get_conversion_result(PTC); } +// Mark the object deinited: deinited() is true and deinit() does nothing. +static void mark_deinit(touchio_touchin_obj_t *self) { + self->config.pin = NO_PIN; +} + void common_hal_touchio_touchin_construct(touchio_touchin_obj_t *self, - const mcu_pin_obj_t *pin) { + const mcu_pin_obj_t *pin, const digitalio_pull_t pull) { + // Ensure the object starts in its deinit state. + mark_deinit(self); + if (!pin->has_touch) { raise_ValueError_invalid_pin(); } - claim_pin(pin); - // Turn on the PTC if its not in use. We won't turn it off until reset. + // Turn on the PTC if its not in use. We won't turn it off until the last + // TouchIn object is deinited. if (((Ptc *)PTC)->CTRLA.bit.ENABLE == 0) { // We run the PTC at 8mhz so divide the 48mhz clock by 6. uint8_t gclk = find_free_gclk(6); if (gclk > GCLK_GEN_NUM) { mp_raise_RuntimeError(MP_ERROR_TEXT("No free GCLKs")); } + touchin_gclk = gclk; enable_clock_generator(gclk, CLOCK_48MHZ, 6); /* Setup and enable generic clock source for PTC module. */ @@ -59,12 +77,17 @@ void common_hal_touchio_touchin_construct(touchio_touchin_obj_t *self, _pm_enable_bus_clock(PM_BUS_APBC, PTC); } + // Claim the pin only after the last raise, so a failed construct doesn't leak it. + claim_pin(pin); + adafruit_ptc_get_config_default(&self->config); self->config.pin = pin->number; self->config.yline = pin->touch_y_line; adafruit_ptc_init(PTC, &self->config); + touchin_refcount++; + // Initial values for pins will vary, depending on what peripherals the pins // share on-chip. // @@ -80,17 +103,32 @@ bool common_hal_touchio_touchin_deinited(touchio_touchin_obj_t *self) { } void common_hal_touchio_touchin_deinit(touchio_touchin_obj_t *self) { - // TODO(tannewt): Reset the PTC. if (common_hal_touchio_touchin_deinited(self)) { return; } - // We leave the clocks running because they may be in use by others. reset_pin_number(self->config.pin); - self->config.pin = NO_PIN; + mark_deinit(self); + + touchin_refcount--; + if (touchin_refcount > 0) { + // Other TouchIn objects still use the PTC and its clock. + return; + } + + touchin_reset(); + + if (touchin_gclk != 0xff) { + disconnect_gclk_from_peripheral(touchin_gclk, PTC_GCLK_ID); + disable_clock_generator(touchin_gclk); + touchin_gclk = 0xff; + } + _pm_disable_bus_clock(PM_BUS_APBC, PTC); } -void touchin_reset() { +// Reset and power down the PTC entirely. The caller must ensure no other +// TouchIn objects are still using it. +static void touchin_reset(void) { Ptc *ptc = ((Ptc *)PTC); if (ptc->CTRLA.bit.ENABLE == 1) { ptc->CTRLA.bit.ENABLE = 0; diff --git a/ports/atmel-samd/common-hal/touchio/TouchIn.h b/ports/atmel-samd/common-hal/touchio/TouchIn.h index 6029320e5ba..60efbeb3bfd 100644 --- a/ports/atmel-samd/common-hal/touchio/TouchIn.h +++ b/ports/atmel-samd/common-hal/touchio/TouchIn.h @@ -22,6 +22,4 @@ typedef struct { uint16_t threshold; } touchio_touchin_obj_t; -void touchin_reset(void); - #endif // SAMD21 diff --git a/ports/atmel-samd/common-hal/watchdog/WatchDogTimer.c b/ports/atmel-samd/common-hal/watchdog/WatchDogTimer.c index a11f995d8b4..d79b2425477 100644 --- a/ports/atmel-samd/common-hal/watchdog/WatchDogTimer.c +++ b/ports/atmel-samd/common-hal/watchdog/WatchDogTimer.c @@ -52,7 +52,7 @@ void common_hal_watchdog_feed(watchdog_watchdogtimer_obj_t *self) { WDT->CLEAR.reg = WDT_CLEAR_CLEAR_KEY; } -void common_hal_watchdog_deinit(watchdog_watchdogtimer_obj_t *self) { +void common_hal_watchdog_reset(watchdog_watchdogtimer_obj_t *self) { if (self->mode == WATCHDOGMODE_NONE) { return; } @@ -84,7 +84,7 @@ void common_hal_watchdog_set_mode(watchdog_watchdogtimer_obj_t *self, watchdog_w switch (new_mode) { case WATCHDOGMODE_NONE: - common_hal_watchdog_deinit(self); + common_hal_watchdog_reset(self); break; case WATCHDOGMODE_RAISE: mp_raise_NotImplementedError(NULL); diff --git a/ports/atmel-samd/libgcc_thumb1.s b/ports/atmel-samd/libgcc_thumb1.s new file mode 100644 index 00000000000..3ed26543210 --- /dev/null +++ b/ports/atmel-samd/libgcc_thumb1.s @@ -0,0 +1,113 @@ +@ Thin replacements for libgcc soft-float and bit helpers on Cortex-M0+. Each builds on a +@ libgcc routine the firmware links anyway, so the larger archive member is never pulled in. +@ Results are bit-identical to libgcc's, including NaN handling. + + .syntax unified + .cpu cortex-m0plus + .thumb + +@ float __aeabi_fsub(float a, float b): a + (-b). A NaN b keeps its sign, as in libgcc. + .section .text.__aeabi_fsub,"ax",%progbits + .global __aeabi_fsub + .type __aeabi_fsub, %function + .thumb_func +__aeabi_fsub: + lsls r2, r1, #1 + ldr r3, =0xff000000 + cmp r2, r3 + bhi 1f + movs r2, #1 + lsls r2, r2, #31 + eors r1, r2 +1: + ldr r2, =__aeabi_fadd + bx r2 + .size __aeabi_fsub, . - __aeabi_fsub + .ltorg + +@ int __aeabi_fcmp{eq,lt,le,gt,ge}(float a, float b), all from __lesf2, which returns +@ -1, 0 or 1 when ordered and 2 when either operand is NaN. + .section .text.__aeabi_fcmp,"ax",%progbits + .global __aeabi_fcmpgt + .type __aeabi_fcmpgt, %function + .thumb_func +__aeabi_fcmpgt: + mov r2, r0 + mov r0, r1 + mov r1, r2 + .global __aeabi_fcmplt + .type __aeabi_fcmplt, %function + .thumb_func +__aeabi_fcmplt: + push {r4, lr} + bl __lesf2 + lsrs r0, r0, #31 + pop {r4, pc} + + .global __aeabi_fcmpge + .type __aeabi_fcmpge, %function + .thumb_func +__aeabi_fcmpge: + mov r2, r0 + mov r0, r1 + mov r1, r2 + .global __aeabi_fcmple + .type __aeabi_fcmple, %function + .thumb_func +__aeabi_fcmple: + push {r4, lr} + bl __lesf2 + subs r0, r0, #1 + lsrs r0, r0, #31 + pop {r4, pc} + + .global __aeabi_fcmpeq + .type __aeabi_fcmpeq, %function + .thumb_func +__aeabi_fcmpeq: + push {r4, lr} + bl __lesf2 + negs r1, r0 + adcs r0, r1 + pop {r4, pc} + .size __aeabi_fcmpgt, . - __aeabi_fcmpgt + +@ float __aeabi_i2f(int x): the unsigned conversion of |x|, with the sign set for x < 0. +@ -INT_MIN is 0x80000000 as unsigned, so INT_MIN converts exactly. + .section .text.__aeabi_i2f,"ax",%progbits + .global __aeabi_i2f + .type __aeabi_i2f, %function + .thumb_func +__aeabi_i2f: + cmp r0, #0 + bge 1f + push {r4, lr} + negs r0, r0 + bl __aeabi_ui2f + movs r1, #1 + lsls r1, r1, #31 + orrs r0, r1 + pop {r4, pc} +1: + ldr r1, =__aeabi_ui2f + bx r1 + .size __aeabi_i2f, . - __aeabi_i2f + .ltorg + +@ int __ffssi2(int x): 1 + index of the lowest set bit, 0 for x == 0. + .section .text.__ffssi2,"ax",%progbits + .global __ffssi2 + .type __ffssi2, %function + .thumb_func +__ffssi2: + negs r1, r0 + ands r0, r1 + beq 1f + push {r4, lr} + bl __clzsi2 + movs r1, #32 + subs r0, r1, r0 + pop {r4, pc} +1: + bx lr + .size __ffssi2, . - __ffssi2 diff --git a/ports/atmel-samd/libs/libgcc-12.1.0-Os-v6-m-nofp.a b/ports/atmel-samd/libs/libgcc-12.1.0-Os-v6-m-nofp.a deleted file mode 100644 index 56692d5d056..00000000000 Binary files a/ports/atmel-samd/libs/libgcc-12.1.0-Os-v6-m-nofp.a and /dev/null differ diff --git a/ports/atmel-samd/libs/libgcc-14.2.0-Os-v6-m-nofp.a b/ports/atmel-samd/libs/libgcc-14.2.0-Os-v6-m-nofp.a new file mode 100644 index 00000000000..6a708c1ffaa Binary files /dev/null and b/ports/atmel-samd/libs/libgcc-14.2.0-Os-v6-m-nofp.a differ diff --git a/ports/atmel-samd/mpconfigport.h b/ports/atmel-samd/mpconfigport.h index eca28dbd9be..715b0c4266f 100644 --- a/ports/atmel-samd/mpconfigport.h +++ b/ports/atmel-samd/mpconfigport.h @@ -27,6 +27,7 @@ #define MICROPY_PY_REVERSE_SPECIAL_METHODS (0) #define MICROPY_PY_COLLECTIONS_DEQUE (0) #define MICROPY_PY_COLLECTIONS_ORDEREDDICT (0) +// docs/library/errno.rst lists these names. Update it if this list changes. #define MICROPY_PY_ERRNO_LIST \ X(EPERM) \ X(ENOENT) \ @@ -51,6 +52,8 @@ // See https://github.com/micropython/micropython/pull/11353 #define MICROPY_NLR_THUMB_USE_LONG_JUMP (1) +// Don't store qstr hashes and do string compares instead. +#define MICROPY_QSTR_BYTES_IN_HASH (0) #endif // SAMD21 @@ -64,6 +67,8 @@ #define CIRCUITPY_MCU_FAMILY samd51 #ifdef SAMD51 #define MICROPY_PY_SYS_PLATFORM "MicroChip SAMD51" +#elif defined(SAME51) +#define MICROPY_PY_SYS_PLATFORM "MicroChip SAME51" #elif defined(SAME54) #define MICROPY_PY_SYS_PLATFORM "MicroChip SAME54" #endif @@ -100,6 +105,11 @@ #define CIRCUITPY_DEFAULT_STACK_SIZE 3584 #endif +#ifndef CIRCUITPY_PYSTACK_SIZE +// Default for most boards is 2048 starting with CircuitPython 10, but on SAMD21, keep it at previous lower value. +#define CIRCUITPY_PYSTACK_SIZE 1536 +#endif + #ifndef SAMD21_BOD33_LEVEL // Set brownout detection to ~2.7V. Default from factory is 1.7V, // which is too low for proper operation of external SPI flash chips diff --git a/ports/atmel-samd/mpconfigport.mk b/ports/atmel-samd/mpconfigport.mk index 15013b2d831..05545b5f019 100644 --- a/ports/atmel-samd/mpconfigport.mk +++ b/ports/atmel-samd/mpconfigport.mk @@ -12,6 +12,9 @@ CIRCUITPY_OPTIMIZE_PROPERTY_FLASH_SIZE ?= 1 CIRCUITPY_LTO = 1 CIRCUITPY_KEYPAD_DEMUX ?= 0 +CIRCUITPY_LVFONTIO ?= 0 + +CIRCUITPY_DIGITALINOUT_PROTOCOL = 0 ###################################################################### # Put samd21-only choices here. @@ -36,6 +39,7 @@ CIRCUITPY_BUILTINS_POW3 ?= 0 CIRCUITPY_BUSDEVICE ?= 0 CIRCUITPY_COMPUTED_GOTO_SAVE_SPACE ?= 1 CIRCUITPY_COUNTIO ?= 0 +CIRCUITPY_EPAPERDISPLAY_FAST ?= 0 # Not enough RAM for framebuffers CIRCUITPY_FRAMEBUFFERIO ?= 0 CIRCUITPY_FREQUENCYIO ?= 0 @@ -45,10 +49,10 @@ CIRCUITPY_I2CTARGET ?= 0 CIRCUITPY_JSON ?= 0 CIRCUITPY_KEYPAD ?= 0 CIRCUITPY_MSGPACK ?= 0 -CIRCUITPY_OS_GETENV ?= 0 CIRCUITPY_PIXELMAP ?= 0 CIRCUITPY_RE ?= 0 CIRCUITPY_SDCARDIO ?= 0 +CIRCUITPY_SETTINGS_TOML ?= 0 CIRCUITPY_SPITARGET ?= 0 CIRCUITPY_SYNTHIO ?= 0 CIRCUITPY_TOUCHIO_USE_NATIVE ?= 1 @@ -92,11 +96,15 @@ endif # samd21 ###################################################################### ###################################################################### -# Put samd51-only choices here. +# Put samx5x-only choices here. + +ifneq ($(filter $(CHIP_FAMILY),samd51 same51 same54),) +CIRCUITPY_BUSIO_SPI_ASYNC ?= 1 -ifeq ($(CHIP_FAMILY),samd51) +# The 24 KB stack has room for a larger display refresh buffer. +CIRCUITPY_DISPLAY_AREA_BUFFER_SIZE ?= 2048 -# No native touchio on SAMD51. +# No native touchio on SAMx5x. CIRCUITPY_TOUCHIO_USE_NATIVE = 0 ifeq ($(CIRCUITPY_FULL_BUILD),0) @@ -116,15 +124,25 @@ endif CIRCUITPY_ALARM ?= 1 # Not enough room for both bitmaptools and bitmapfilter on most boards. CIRCUITPY_BITMAPFILTER ?= 0 +# Fast e-paper only fits on chips with 1MB flash. +ifeq ($(HAS_1MB_FLASH),0) +CIRCUITPY_EPAPERDISPLAY_FAST ?= 0 +endif CIRCUITPY_FLOPPYIO ?= $(CIRCUITPY_FULL_BUILD) CIRCUITPY_FRAMEBUFFERIO ?= $(CIRCUITPY_FULL_BUILD) +CIRCUITPY_LOAD_NATIVE ?= 1 CIRCUITPY_MAX3421E ?= $(HAS_1MB_FLASH) CIRCUITPY_PS2IO ?= 1 CIRCUITPY_RGBMATRIX ?= $(CIRCUITPY_FRAMEBUFFERIO) CIRCUITPY_SAMD ?= 1 CIRCUITPY_SPITARGET ?= 1 CIRCUITPY_SYNTHIO_MAX_CHANNELS = 12 +# Trade some speed for flash only where flash is tight. +ifeq ($(HAS_1MB_FLASH),0) +CIRCUITPY_COMPUTED_GOTO_SAVE_SPACE ?= 1 +CIRCUITPY_LTO_PARTITION ?= one CIRCUITPY_ULAB_OPTIMIZE_SIZE ?= 1 +endif CIRCUITPY_WATCHDOG ?= 1 ifeq ($(CHIP_VARIANT),SAMD51G19A) @@ -132,32 +150,7 @@ ifeq ($(CHIP_VARIANT),SAMD51G19A) CIRCUITPY_AUDIOBUSIO = 0 endif -endif # samd51 -###################################################################### - -###################################################################### -# Put same51-only choices here. - -ifeq ($(CHIP_FAMILY),same51) - -# No native touchio on SAME51. -CIRCUITPY_TOUCHIO_USE_NATIVE = 0 - -ifeq ($(CIRCUITPY_FULL_BUILD),0) -CIRCUITPY_LTO_PARTITION ?= one -endif - -# The ?='s allow overriding in mpconfigboard.mk. - -CIRCUITPY_ALARM ?= 1 -CIRCUITPY_PS2IO ?= 1 -CIRCUITPY_SAMD ?= 1 -CIRCUITPY_FLOPPYIO ?= $(CIRCUITPY_FULL_BUILD) -CIRCUITPY_FRAMEBUFFERIO ?= $(CIRCUITPY_FULL_BUILD) -CIRCUITPY_RGBMATRIX ?= $(CIRCUITPY_FRAMEBUFFERIO) -CIRCUITPY_ULAB_OPTIMIZE_SIZE ?= 1 - -endif # same51 +endif # samx5x ###################################################################### CIRCUITPY_BUILD_EXTENSIONS ?= uf2 diff --git a/ports/atmel-samd/peripherals b/ports/atmel-samd/peripherals index d3210221bbd..b577f2ddd3b 160000 --- a/ports/atmel-samd/peripherals +++ b/ports/atmel-samd/peripherals @@ -1 +1 @@ -Subproject commit d3210221bbd018ae9d0183ea4640c42cf4bce672 +Subproject commit b577f2ddd3b476abf8777caec15c3383881eb282 diff --git a/ports/atmel-samd/reset.c b/ports/atmel-samd/reset.c index 9cacd4ab951..816e23e3251 100644 --- a/ports/atmel-samd/reset.c +++ b/ports/atmel-samd/reset.c @@ -9,7 +9,7 @@ #include "reset.h" #include "supervisor/filesystem.h" -void NVIC_SystemReset(void) NORETURN; +void NVIC_SystemReset(void) MP_NORETURN; void reset(void) { filesystem_flush(); diff --git a/ports/atmel-samd/reset.h b/ports/atmel-samd/reset.h index c74d25fa01e..248d43779fd 100644 --- a/ports/atmel-samd/reset.h +++ b/ports/atmel-samd/reset.h @@ -16,6 +16,6 @@ extern uint32_t _bootloader_dbl_tap; -void reset_to_bootloader(void) NORETURN; -void reset(void) NORETURN; +void reset_to_bootloader(void) MP_NORETURN; +void reset(void) MP_NORETURN; bool bootloader_available(void); diff --git a/ports/atmel-samd/sd_mmc/sd_mmc.c b/ports/atmel-samd/sd_mmc/sd_mmc.c index 60b4d9f8985..6724e88f42a 100644 --- a/ports/atmel-samd/sd_mmc/sd_mmc.c +++ b/ports/atmel-samd/sd_mmc/sd_mmc.c @@ -160,9 +160,9 @@ static struct sd_mmc_card sd_mmc_cards[CONF_SD_MMC_MEM_CNT]; /** HAL driver instance */ static void *sd_mmc_hal; -/** Index of current slot configurated */ +/** Index of current slot configured */ static uint8_t sd_mmc_slot_sel; -/** Pointer on current slot configurated */ +/** Pointer on current slot configured */ static struct sd_mmc_card *sd_mmc_card; /** Number of block to read or write on the current transfer */ static uint16_t sd_mmc_nb_block_to_tranfer = 0; @@ -238,7 +238,7 @@ static bool mmc_mci_op_cond(void) { uint32_t retry, resp; /* - * Timeout 1s = 400KHz / ((6+6)*8) cylces = 4200 retry + * Timeout 1s = 400KHz / ((6+6)*8) cycles = 4200 retry * 6 = cmd byte size * 6 = response byte size */ @@ -277,7 +277,7 @@ static bool sd_mci_op_cond(uint8_t v2) { uint32_t arg, retry, resp; /* - * Timeout 1s = 400KHz / ((6+6+6+6)*8) cylces = 2100 retry + * Timeout 1s = 400KHz / ((6+6+6+6)*8) cycles = 2100 retry * 6 = cmd byte size * 6 = response byte size * 6 = cmd byte size @@ -339,7 +339,7 @@ static bool sdio_op_cond(void) { /* * Wait card ready - * Timeout 1s = 400KHz / ((6+4)*8) cylces = 5000 retry + * Timeout 1s = 400KHz / ((6+4)*8) cycles = 5000 retry * 6 = cmd byte size * 4(SPI) 6(MCI) = response byte size */ @@ -1292,13 +1292,13 @@ static bool sd_mmc_mci_install_mmc(void) { void sd_mmc_init(void *hal, sd_mmc_detect_t *card_detects, sd_mmc_detect_t *wp_detects) { /* GPIO will be used to detect card and write protect. - * The related clocks and pinmux must be configurated in good + * The related clocks and pinmux must be configured in good * condition. */ for (uint8_t slot = 0; slot < CONF_SD_MMC_MEM_CNT; slot++) { sd_mmc_cards[slot].state = SD_MMC_CARD_STATE_NO_CARD; } - sd_mmc_slot_sel = 0xFF; /* No slot configurated */ + sd_mmc_slot_sel = 0xFF; /* No slot configured */ sd_mmc_hal = hal; _cd = card_detects; _wp = wp_detects; diff --git a/ports/atmel-samd/sd_mmc/sd_mmc.h b/ports/atmel-samd/sd_mmc/sd_mmc.h index cdc98e7108e..7b70a631164 100644 --- a/ports/atmel-samd/sd_mmc/sd_mmc.h +++ b/ports/atmel-samd/sd_mmc/sd_mmc.h @@ -113,7 +113,7 @@ typedef struct sd_mmc_detect { uint16_t val; /**< Detection value */ } sd_mmc_detect_t; -/** This SD MMC stack uses the maximum block size autorized (512 bytes) */ +/** This SD MMC stack uses the maximum block size authorized (512 bytes) */ #define SD_MMC_BLOCK_SIZE 512 /** diff --git a/ports/atmel-samd/supervisor/port.c b/ports/atmel-samd/supervisor/port.c index 8f5115789da..b0c3175ff40 100644 --- a/ports/atmel-samd/supervisor/port.c +++ b/ports/atmel-samd/supervisor/port.c @@ -360,43 +360,18 @@ safe_mode_t port_init(void) { } void reset_port(void) { - #if CIRCUITPY_BUSIO - reset_sercoms(); - #endif - - #if CIRCUITPY_AUDIOIO - audio_dma_reset(); - #endif - - #if CIRCUITPY_AUDIOBUSIO - pdmin_reset(); - #endif - - #if CIRCUITPY_AUDIOBUSIO_I2SOUT - i2sout_reset(); - #endif - - #if CIRCUITPY_FREQUENCYIO - frequencyin_reset(); - #endif - - #if CIRCUITPY_TOUCHIO && CIRCUITPY_TOUCHIO_USE_NATIVE - touchin_reset(); - #endif - - eic_reset(); - - #if CIRCUITPY_ANALOGIO - analogin_reset(); - analogout_reset(); - #endif + // Peripherals are torn down by the deinit() of their Python objects, which + // runs via __del__ when the VM's heap is collected. There is no port-level + // bulk reset. #if CIRCUITPY_WATCHDOG watchdog_reset(); #endif - reset_gclks(); - + // Stop PewPew before the heap is swept. + // + // Its timer interrupt drives pins through DigitalInOut objects on the heap, + // and gc_sweep_all() may finalize them before the PewPew object. #if CIRCUITPY_PEW pew_reset(); #endif @@ -411,8 +386,6 @@ void reset_port(void) { reset_ticks(); } - reset_all_pins(); - // Output clocks for debugging. // not supported by SAMD51G; uncomment for SAMD51J or update for 51G // #ifdef SAM_D5X_E5X @@ -553,7 +526,7 @@ static void evsyshandler_common(void) { audio_dma_evsys_handler(); #endif - #if CIRCUITPY_AUDIOBUSIO + #if CIRCUITPY_AUDIOBUSIO_PDMIN pdmin_evsys_handler(); #endif } @@ -686,7 +659,7 @@ void port_idle_until_interrupt(void) { /** * \brief Default interrupt handler for unused IRQs. */ -__attribute__((used)) void HardFault_Handler(void) { +__attribute__((used)) MP_NORETURN 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. diff --git a/ports/atmel-samd/supervisor/qspi_flash.c b/ports/atmel-samd/supervisor/qspi_flash.c index 956d71044f8..1bdedd4ecf2 100644 --- a/ports/atmel-samd/supervisor/qspi_flash.c +++ b/ports/atmel-samd/supervisor/qspi_flash.c @@ -233,7 +233,7 @@ void spi_flash_init(void) { gpio_set_pin_direction(pins[i], GPIO_DIRECTION_IN); gpio_set_pin_pull_mode(pins[i], GPIO_PULL_OFF); gpio_set_pin_function(pins[i], GPIO_PIN_FUNCTION_H); - never_reset_pin_number(pins[i]); + claim_pin_number(pins[i]); } } diff --git a/ports/atmel-samd/supervisor/samd21_cpu.s b/ports/atmel-samd/supervisor/samd21_cpu.s deleted file mode 100755 index 741bb21358a..00000000000 --- a/ports/atmel-samd/supervisor/samd21_cpu.s +++ /dev/null @@ -1,35 +0,0 @@ -.syntax unified -.cpu cortex-m0 -.thumb -.text -.align 2 - -@ uint cpu_get_regs_and_sp(r0=uint regs[10]) -.global cpu_get_regs_and_sp -.thumb -.thumb_func -.type cpu_get_regs_and_sp, %function -cpu_get_regs_and_sp: -@ store registers into given array -str r4, [r0, #0] -str r5, [r0, #4] -str r6, [r0, #8] -str r7, [r0, #12] -push {r1} -mov r1, r8 -str r1, [r0, #16] -mov r1, r9 -str r1, [r0, #20] -mov r1, r10 -str r1, [r0, #24] -mov r1, r11 -str r1, [r0, #28] -mov r1, r12 -str r1, [r0, #32] -mov r1, r13 -str r1, [r0, #36] -pop {r1} - -@ return the sp -mov r0, sp -bx lr diff --git a/ports/atmel-samd/supervisor/samd51_cpu.s b/ports/atmel-samd/supervisor/samd51_cpu.s deleted file mode 100755 index 9e6807a5e2e..00000000000 --- a/ports/atmel-samd/supervisor/samd51_cpu.s +++ /dev/null @@ -1,27 +0,0 @@ -.syntax unified -.cpu cortex-m4 -.thumb -.text -.align 2 - -@ uint cpu_get_regs_and_sp(r0=uint regs[10]) -.global cpu_get_regs_and_sp -.thumb -.thumb_func -.type cpu_get_regs_and_sp, %function -cpu_get_regs_and_sp: -@ store registers into given array -str r4, [r0], #4 -str r5, [r0], #4 -str r6, [r0], #4 -str r7, [r0], #4 -str r8, [r0], #4 -str r9, [r0], #4 -str r10, [r0], #4 -str r11, [r0], #4 -str r12, [r0], #4 -str r13, [r0], #4 - -@ return the sp -mov r0, sp -bx lr diff --git a/ports/atmel-samd/supervisor/same51_cpu.s b/ports/atmel-samd/supervisor/same51_cpu.s deleted file mode 100755 index 9e6807a5e2e..00000000000 --- a/ports/atmel-samd/supervisor/same51_cpu.s +++ /dev/null @@ -1,27 +0,0 @@ -.syntax unified -.cpu cortex-m4 -.thumb -.text -.align 2 - -@ uint cpu_get_regs_and_sp(r0=uint regs[10]) -.global cpu_get_regs_and_sp -.thumb -.thumb_func -.type cpu_get_regs_and_sp, %function -cpu_get_regs_and_sp: -@ store registers into given array -str r4, [r0], #4 -str r5, [r0], #4 -str r6, [r0], #4 -str r7, [r0], #4 -str r8, [r0], #4 -str r9, [r0], #4 -str r10, [r0], #4 -str r11, [r0], #4 -str r12, [r0], #4 -str r13, [r0], #4 - -@ return the sp -mov r0, sp -bx lr diff --git a/ports/atmel-samd/supervisor/same54_cpu.s b/ports/atmel-samd/supervisor/same54_cpu.s deleted file mode 100755 index 9e6807a5e2e..00000000000 --- a/ports/atmel-samd/supervisor/same54_cpu.s +++ /dev/null @@ -1,27 +0,0 @@ -.syntax unified -.cpu cortex-m4 -.thumb -.text -.align 2 - -@ uint cpu_get_regs_and_sp(r0=uint regs[10]) -.global cpu_get_regs_and_sp -.thumb -.thumb_func -.type cpu_get_regs_and_sp, %function -cpu_get_regs_and_sp: -@ store registers into given array -str r4, [r0], #4 -str r5, [r0], #4 -str r6, [r0], #4 -str r7, [r0], #4 -str r8, [r0], #4 -str r9, [r0], #4 -str r10, [r0], #4 -str r11, [r0], #4 -str r12, [r0], #4 -str r13, [r0], #4 - -@ return the sp -mov r0, sp -bx lr diff --git a/ports/atmel-samd/supervisor/usb.c b/ports/atmel-samd/supervisor/usb.c index 88392f57d69..1bda5beff4b 100644 --- a/ports/atmel-samd/supervisor/usb.c +++ b/ports/atmel-samd/supervisor/usb.c @@ -5,6 +5,7 @@ // SPDX-License-Identifier: MIT #include "atmel_start_pins.h" +#include "common-hal/microcontroller/Pin.h" #include "hpl/pm/hpl_pm_base.h" #include "hpl/gclk/hpl_gclk_base.h" #include "hal_gpio.h" @@ -39,6 +40,8 @@ void init_usb_hardware(void) { gpio_set_pin_function(PIN_PA24, PINMUX_PA24H_USB_DM); gpio_set_pin_function(PIN_PA25, PINMUX_PA25H_USB_DP); #endif + claim_pin_number(PIN_PA24); + claim_pin_number(PIN_PA25); } #ifdef SAMD21 diff --git a/ports/atmel-samd/timer_handler.c b/ports/atmel-samd/timer_handler.c index 55e5818e725..89e2500965b 100644 --- a/ports/atmel-samd/timer_handler.c +++ b/ports/atmel-samd/timer_handler.c @@ -9,6 +9,9 @@ #include "timer_handler.h" +#include "samd/clocks.h" +#include "samd/timers.h" + #include "common-hal/pulseio/PulseIn.h" #include "common-hal/pulseio/PulseOut.h" #include "common-hal/_pew/PewPew.h" @@ -18,6 +21,86 @@ extern void _PM_IRQ_HANDLER(void); static uint8_t tc_handler[TC_INST_NUM]; +// Find the APB mask register and bit that clock a timer. turn_on_clocks() sets this bit. +static volatile uint32_t *apb_mask(timer_type_t timer_type, uint8_t index, uint32_t *bit) { + #ifdef SAM_D5X_E5X + if (timer_type == TIMER_TYPE_TC) { + switch (index) { + case 0: + *bit = MCLK_APBAMASK_TC0; + return &MCLK->APBAMASK.reg; + case 1: + *bit = MCLK_APBAMASK_TC1; + return &MCLK->APBAMASK.reg; + case 2: + *bit = MCLK_APBBMASK_TC2; + return &MCLK->APBBMASK.reg; + case 3: + *bit = MCLK_APBBMASK_TC3; + return &MCLK->APBBMASK.reg; + case 4: + *bit = MCLK_APBCMASK_TC4; + return &MCLK->APBCMASK.reg; + case 5: + *bit = MCLK_APBCMASK_TC5; + return &MCLK->APBCMASK.reg; + case 6: + *bit = MCLK_APBDMASK_TC6; + return &MCLK->APBDMASK.reg; + default: + *bit = MCLK_APBDMASK_TC7; + return &MCLK->APBDMASK.reg; + } + } + switch (index) { + case 0: + *bit = MCLK_APBBMASK_TCC0; + return &MCLK->APBBMASK.reg; + case 1: + *bit = MCLK_APBBMASK_TCC1; + return &MCLK->APBBMASK.reg; + case 2: + *bit = MCLK_APBCMASK_TCC2; + return &MCLK->APBCMASK.reg; + case 3: + *bit = MCLK_APBCMASK_TCC3; + return &MCLK->APBCMASK.reg; + default: + *bit = MCLK_APBDMASK_TCC4; + return &MCLK->APBDMASK.reg; + } + #else + // TCC0 is APBC slot 8. TC3, which is TC index 0, is slot 11. + *bit = 1 << (8 + index + (timer_type == TIMER_TYPE_TC ? 3 : 0)); + return &PM->APBCMASK.reg; + #endif +} + +static bool apb_clock_enabled(timer_type_t timer_type, uint8_t index) { + uint32_t bit; + return (*apb_mask(timer_type, index, &bit) & bit) != 0; +} + +void turn_off_clocks(timer_type_t timer_type, uint8_t index) { + uint32_t bit; + *apb_mask(timer_type, index, &bit) &= ~bit; + + // Most timers share a GCLK peripheral channel with one other timer. Leave the channel on while + // any timer on it still has its APB clock. + uint8_t gclk_id = timer_type == TIMER_TYPE_TC ? tc_gclk_ids[index] : tcc_gclk_ids[index]; + for (uint8_t i = 0; i < TC_INST_NUM; i++) { + if (tc_gclk_ids[i] == gclk_id && apb_clock_enabled(TIMER_TYPE_TC, i)) { + return; + } + } + for (uint8_t i = 0; i < TCC_INST_NUM; i++) { + if (tcc_gclk_ids[i] == gclk_id && apb_clock_enabled(TIMER_TYPE_TCC, i)) { + return; + } + } + disconnect_gclk_from_peripheral(0, gclk_id); +} + void set_timer_handler(bool is_tc, uint8_t index, uint8_t timer_handler) { if (is_tc) { tc_handler[index] = timer_handler; diff --git a/ports/atmel-samd/timer_handler.h b/ports/atmel-samd/timer_handler.h index d8eb121eb27..7529d84736a 100644 --- a/ports/atmel-samd/timer_handler.h +++ b/ports/atmel-samd/timer_handler.h @@ -12,5 +12,16 @@ #define TC_HANDLER_RGBMATRIX 0x4 #define TC_HANDLER_PULSEIN 0x5 +typedef enum { + TIMER_TYPE_TC, + TIMER_TYPE_TCC, +} timer_type_t; + void set_timer_handler(bool is_tc, uint8_t index, uint8_t timer_handler); void shared_timer_handler(bool is_tc, uint8_t index); + +// Undo turn_on_clocks() from peripherals/samd for a timer that is no longer in use. Always turns +// off the timer's APB clock. Turns off its GCLK peripheral channel only if no other timer sharing +// that channel still has its APB clock on. Call it after the timer's software reset has synced, +// which needs the GCLK. +void turn_off_clocks(timer_type_t timer_type, uint8_t index); diff --git a/ports/broadcom/Makefile b/ports/broadcom/Makefile deleted file mode 100644 index d49ac82189d..00000000000 --- a/ports/broadcom/Makefile +++ /dev/null @@ -1,169 +0,0 @@ -# This file is part of the CircuitPython project: https://circuitpython.org -# -# SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries -# -# SPDX-License-Identifier: MIT - -include ../../py/circuitpy_mkenv.mk - -ifeq ($(CHIP_VARIANT), "bcm2711") -CFLAGS += -mcpu=cortex-a72 -DBCM_VERSION=2711 -CROSS_COMPILE = aarch64-none-elf- -SUFFIX = 8 -else ifeq ($(CHIP_VARIANT), "bcm2837") -CFLAGS += -mcpu=cortex-a53 -DBCM_VERSION=2837 -CROSS_COMPILE = aarch64-none-elf- -SUFFIX = 8 -else ifeq ($(CHIP_VARIANT), "bcm2835") -CFLAGS += -mcpu=arm1176jzf-s -DBCM_VERSION=2835 -CROSS_COMPILE = arm-none-eabi- -SUFFIX = -# TODO add 32-bit support for Cortex-A7 in 2836 -endif - -INC += -I. \ - -I../.. \ - -I../../lib/mp-readline \ - -I../../lib/timeutils \ - -I../../lib/sdmmc/include \ - -Iboards/$(BOARD) \ - -Iboards/ \ - -Iperipherals/ \ - -I../../lib/tinyusb/src \ - -I../../supervisor/shared/usb \ - -I$(BUILD) - - -SRC_C += bindings/videocore/__init__.c \ - bindings/videocore/Framebuffer.c \ - boards/$(BOARD)/board.c \ - boards/$(BOARD)/pins.c \ - background.c \ - common-hal/videocore/Framebuffer.c \ - mphalport.c \ - lib/sdmmc/sdmmc_cmd.c \ - lib/sdmmc/sdmmc_common.c \ - lib/sdmmc/sdmmc_init.c \ - lib/sdmmc/sdmmc_io.c \ - lib/sdmmc/sdmmc_mmc.c \ - lib/sdmmc/sdmmc_sd.c \ - lib/tinyusb/src/portable/synopsys/dwc2/dcd_dwc2.c \ - lib/tinyusb/src/portable/synopsys/dwc2/dwc2_common.c \ - peripherals/broadcom/caches.c \ - peripherals/broadcom/gen/interrupt_handlers.c \ - peripherals/broadcom/gen/pins.c \ - peripherals/broadcom/gpio.c \ - peripherals/broadcom/interrupts.c \ - peripherals/broadcom/mmu.c \ - peripherals/broadcom/vcmailbox.c - -SRC_S = peripherals/broadcom/boot$(SUFFIX).s - -SRC_COMMON_HAL_EXPANDED = $(addprefix shared-bindings/, $(SRC_COMMON_HAL)) \ - $(addprefix shared-bindings/, $(SRC_BINDINGS_ENUMS)) \ - $(addprefix common-hal/, $(SRC_COMMON_HAL)) - -SRC_SHARED_MODULE_EXPANDED = $(addprefix shared-bindings/, $(SRC_SHARED_MODULE)) \ - $(addprefix shared-module/, $(SRC_SHARED_MODULE)) \ - $(addprefix shared-module/, $(SRC_SHARED_MODULE_INTERNAL)) - -# There may be duplicates between SRC_COMMON_HAL_EXPANDED and SRC_SHARED_MODULE_EXPANDED, -# because a few modules have files both in common-hal/ and shared-modules/. -# Doing a $(sort ...) removes duplicates as part of sorting. -SRC_COMMON_HAL_SHARED_MODULE_EXPANDED = $(sort $(SRC_COMMON_HAL_EXPANDED) $(SRC_SHARED_MODULE_EXPANDED)) - -OBJ = $(PY_O) $(SUPERVISOR_O) $(addprefix $(BUILD)/, $(SRC_C:.c=.o)) -OBJ += $(addprefix $(BUILD)/, $(SRC_COMMON_HAL_SHARED_MODULE_EXPANDED:.c=.o)) - ifeq ($(INTERNAL_LIBM),1) -OBJ += $(addprefix $(BUILD)/, $(SRC_LIBM:.c=.o)) -endif -OBJ += $(addprefix $(BUILD)/, $(SRC_CIRCUITPY_COMMON:.c=.o)) -OBJ += $(addprefix $(BUILD)/, $(SRC_S:.s=.o)) -OBJ += $(addprefix $(BUILD)/, $(SRC_MOD:.c=.o)) - -# BCM CLFAGS -CFLAGS += -nostartfiles -DMICROPY_HW_MCU_NAME="\"$(CHIP_VARIANT)\"" - - -OPTIMIZATION_FLAGS ?= -O3 -CFLAGS += $(OPTIMIZATION_FLAGS) - -# TinyUSB defines -CFLAGS += -DCFG_TUSB_MCU=OPT_MCU_BCM2711 -DCFG_TUD_MIDI_RX_BUFSIZE=512 \ - -DCFG_TUD_CDC_RX_BUFSIZE=640 -DCFG_TUD_MIDI_TX_BUFSIZE=512 \ - -DCFG_TUD_CDC_TX_BUFSIZE=512 -DCFG_TUD_MSC_BUFSIZE=1024 - -#Debugging/Optimization -ifeq ($(DEBUG), 1) - CFLAGS += -ggdb3 -Og - # No LTO because we may place some functions in RAM instead of flash. -else - CFLAGS += -DNDEBUG -ggdb3 - - # No LTO because we may place some functions in RAM instead of flash. - - ifdef CFLAGS_BOARD - CFLAGS += $(CFLAGS_BOARD) - endif -endif - - -CFLAGS += $(INC) -Wall -Werror -std=gnu11 $(BASE_CFLAGS) $(CFLAGS_MOD) $(COPT) $(DISABLE_WARNINGS) - -$(BUILD)/lib/tlsf/tlsf.o: CFLAGS += -Wno-cast-align - -SRC_QSTR += $(SRC_C) $(SRC_SUPERVISOR) $(SRC_COMMON_HAL_EXPANDED) $(SRC_SHARED_MODULE_EXPANDED) $(SRC_CIRCUITPY_COMMON) - -LDFLAGS += $(CFLAGS) -T peripherals/broadcom/link$(SUFFIX).ld -Wl,--gc-sections -Wl,-Map=$@.map # -Wl,--cref - -# Use toolchain libm if we're not using our own. -ifndef INTERNAL_LIBM -LIBS += -lm -endif - -all: $(BUILD)/firmware.kernel$(SUFFIX).img $(BUILD)/firmware.disk.img.zip - -$(BUILD)/lib/tlsf/tlsf.o: CFLAGS += -Wno-pointer-to-int-cast -Wno-int-to-pointer-cast - -%.o: %.c - $(CC) $(CFLAGS) -c $< -o $@ - -ifeq ($(VALID_BOARD),) -$(BUILD)/kernel$(SUFFIX).elf: invalid-board -else -$(BUILD)/kernel$(SUFFIX).elf: $(OBJ) - $(STEPECHO) "LINK $@" - $(Q)echo $(OBJ) > $(BUILD)/firmware.objs - $(Q)$(CC) -o $@ $(LDFLAGS) @$(BUILD)/firmware.objs -Wl,--print-memory-usage -Wl,--start-group $(LIBS) -Wl,--end-group -endif - -$(BUILD)/kernel$(SUFFIX).img: $(BUILD)/kernel$(SUFFIX).elf - $(STEPECHO) "Create $@" - $(OBJCOPY) -O binary $(BUILD)/kernel$(SUFFIX).elf $@ - -$(BUILD)/firmware.kernel$(SUFFIX).img: $(BUILD)/kernel$(SUFFIX).img - $(STEPECHO) "Create $@" - $(CP) $^ $@ - -$(BUILD)/firmware.disk.img.zip: $(BUILD)/kernel$(SUFFIX).img - $(STEPECHO) "Create $@" - $(Q)dd if=/dev/zero of=$(BUILD)/circuitpython-disk.img bs=1 count=0 seek=256M - $(Q)parted -s $(BUILD)/circuitpython-disk.img mktable msdos - $(Q)parted -s $(BUILD)/circuitpython-disk.img mkpart primary fat32 0% 100% - $(Q)mkfs.fat -F 32 -n BOOT --offset=2048 $(BUILD)/circuitpython-disk.img - - $(Q)mcopy -i $(BUILD)/circuitpython-disk.img@@1M config.txt firmware/bootcode.bin firmware/fixup* firmware/start* firmware/*.dtb :: - $(Q)mcopy -i $(BUILD)/circuitpython-disk.img@@1M $(BUILD)/kernel$(SUFFIX).img :: - $(Q)zip $@ $(BUILD)/circuitpython-disk.img - $(Q)rm $(BUILD)/circuitpython-disk.img - -.PHONY: $(BUILD)/rpiboot rpiboot -rpiboot: $(BUILD)/rpiboot -$(BUILD)/rpiboot: $(BUILD)/kernel$(SUFFIX).img - mkdir -vp $@ - cp -vf $(BUILD)/kernel$(SUFFIX).img $@/ - cp -vfr config.txt firmware/bootcode.bin firmware/fixup* firmware/start* firmware/*.dtb $@/ - #sed -i -e "s/BOOT_UART=0/BOOT_UART=1/" $@/bootcode.bin $@/bootcode.bin - echo uart_2ndstage=1 >> $@/config.txt - -include $(TOP)/py/mkrules.mk diff --git a/ports/broadcom/README.rst b/ports/broadcom/README.rst deleted file mode 100644 index 10ff81711bd..00000000000 --- a/ports/broadcom/README.rst +++ /dev/null @@ -1,5 +0,0 @@ -Broadcom -================== - -This port supports running CircuitPython bare-metal on Raspberry Pi single board -computers that utilize Broadcom system-on-chips. diff --git a/ports/broadcom/background.c b/ports/broadcom/background.c deleted file mode 100644 index 5bb961eea59..00000000000 --- a/ports/broadcom/background.c +++ /dev/null @@ -1,20 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT -#include "background.h" - -#include "py/runtime.h" -#include "supervisor/port.h" - -void port_start_background_tick(void) { -} -void port_finish_background_tick(void) { -} - -void port_background_tick(void) { -} - -void port_background_task(void) { -} diff --git a/ports/broadcom/background.h b/ports/broadcom/background.h deleted file mode 100644 index fe71149ab4b..00000000000 --- a/ports/broadcom/background.h +++ /dev/null @@ -1,9 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#pragma once - -#include diff --git a/ports/broadcom/bindings/videocore/Framebuffer.c b/ports/broadcom/bindings/videocore/Framebuffer.c deleted file mode 100644 index 66135baa7fe..00000000000 --- a/ports/broadcom/bindings/videocore/Framebuffer.c +++ /dev/null @@ -1,163 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "py/obj.h" -#include "py/objproperty.h" -#include "py/runtime.h" -#include "py/objarray.h" - -#include "bindings/videocore/Framebuffer.h" -#include "shared-bindings/util.h" -#include "shared-module/displayio/__init__.h" -#include "shared-module/framebufferio/__init__.h" -#include "shared-module/framebufferio/FramebufferDisplay.h" - -//| class Framebuffer: -//| """A VideoCore managed frame buffer.""" -//| -//| def __init__(self, width: int, height: int) -> None: -//| """Create a Framebuffer object with the given dimensions. Memory is -//| allocated outside of the heap in GPU memory. -//| -//| The framebuffer is in "ARGB8888" format. -//| -//| A Framebuffer is often used in conjunction with a -//| `framebufferio.FramebufferDisplay`.""" -//| - -static mp_obj_t videocore_framebuffer_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { - enum { ARG_width, ARG_height, }; - static const mp_arg_t allowed_args[] = { - { MP_QSTR_width, MP_ARG_INT | MP_ARG_REQUIRED }, - { MP_QSTR_height, MP_ARG_INT | MP_ARG_REQUIRED }, - }; - mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; - mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); - - videocore_framebuffer_obj_t *self = &allocate_display_bus_or_raise()->videocore; - self->base.type = &videocore_framebuffer_type; - - mp_uint_t width = (mp_uint_t)mp_arg_validate_int_min(args[ARG_width].u_int, 0, MP_QSTR_width); - mp_uint_t height = (mp_uint_t)mp_arg_validate_int_min(args[ARG_height].u_int, 0, MP_QSTR_height); - common_hal_videocore_framebuffer_construct(self, width, height); - - return MP_OBJ_FROM_PTR(self); -} - -//| def deinit(self) -> None: -//| """Free the resources (pins, timers, etc.) associated with this -//| rgbmatrix instance. After deinitialization, no further operations -//| may be performed.""" -//| ... -//| -static mp_obj_t videocore_framebuffer_deinit(mp_obj_t self_in) { - videocore_framebuffer_obj_t *self = (videocore_framebuffer_obj_t *)self_in; - common_hal_videocore_framebuffer_deinit(self); - return mp_const_none; -} - -static MP_DEFINE_CONST_FUN_OBJ_1(videocore_framebuffer_deinit_obj, videocore_framebuffer_deinit); - -static void check_for_deinit(videocore_framebuffer_obj_t *self) { - if (common_hal_videocore_framebuffer_deinited(self)) { - raise_deinited_error(); - } -} - -//| width: int -//| """The width of the display, in pixels""" -static mp_obj_t videocore_framebuffer_get_width(mp_obj_t self_in) { - videocore_framebuffer_obj_t *self = (videocore_framebuffer_obj_t *)self_in; - check_for_deinit(self); - return MP_OBJ_NEW_SMALL_INT(common_hal_videocore_framebuffer_get_width(self)); -} -MP_DEFINE_CONST_FUN_OBJ_1(videocore_framebuffer_get_width_obj, videocore_framebuffer_get_width); -MP_PROPERTY_GETTER(videocore_framebuffer_width_obj, - (mp_obj_t)&videocore_framebuffer_get_width_obj); - -//| height: int -//| """The height of the display, in pixels""" -//| -//| -static mp_obj_t videocore_framebuffer_get_height(mp_obj_t self_in) { - videocore_framebuffer_obj_t *self = (videocore_framebuffer_obj_t *)self_in; - check_for_deinit(self); - return MP_OBJ_NEW_SMALL_INT(common_hal_videocore_framebuffer_get_height(self)); -} -MP_DEFINE_CONST_FUN_OBJ_1(videocore_framebuffer_get_height_obj, videocore_framebuffer_get_height); - -MP_PROPERTY_GETTER(videocore_framebuffer_height_obj, - (mp_obj_t)&videocore_framebuffer_get_height_obj); - -static const mp_rom_map_elem_t videocore_framebuffer_locals_dict_table[] = { - { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&videocore_framebuffer_deinit_obj) }, - - { MP_ROM_QSTR(MP_QSTR_width), MP_ROM_PTR(&videocore_framebuffer_width_obj) }, - { MP_ROM_QSTR(MP_QSTR_height), MP_ROM_PTR(&videocore_framebuffer_height_obj) }, -}; -static MP_DEFINE_CONST_DICT(videocore_framebuffer_locals_dict, videocore_framebuffer_locals_dict_table); - -static void videocore_framebuffer_get_bufinfo(mp_obj_t self_in, mp_buffer_info_t *bufinfo) { - common_hal_videocore_framebuffer_get_buffer(self_in, bufinfo, 0); -} - -// These versions exist so that the prototype matches the protocol, -// avoiding a type cast that can hide errors -static void videocore_framebuffer_swapbuffers(mp_obj_t self_in, uint8_t *dirty_row_bitmap) { - (void)dirty_row_bitmap; - common_hal_videocore_framebuffer_refresh(self_in); -} - -static void videocore_framebuffer_deinit_proto(mp_obj_t self_in) { - common_hal_videocore_framebuffer_deinit(self_in); -} - -static int videocore_framebuffer_get_width_proto(mp_obj_t self_in) { - return common_hal_videocore_framebuffer_get_width(self_in); -} - -static int videocore_framebuffer_get_height_proto(mp_obj_t self_in) { - return common_hal_videocore_framebuffer_get_height(self_in); -} - -static int videocore_framebuffer_get_color_depth_proto(mp_obj_t self_in) { - return 32; -} - -static int videocore_framebuffer_get_bytes_per_cell_proto(mp_obj_t self_in) { - return 1; -} - -static int videocore_framebuffer_get_native_frames_per_second_proto(mp_obj_t self_in) { - return 30; -} - -static int videocore_framebuffer_get_row_stride_proto(mp_obj_t self_in) { - return common_hal_videocore_framebuffer_get_row_stride(self_in); -} - -static const framebuffer_p_t videocore_framebuffer_proto = { - MP_PROTO_IMPLEMENT(MP_QSTR_protocol_framebuffer) - .get_bufinfo = videocore_framebuffer_get_bufinfo, - .get_width = videocore_framebuffer_get_width_proto, - .get_height = videocore_framebuffer_get_height_proto, - .get_color_depth = videocore_framebuffer_get_color_depth_proto, - .get_row_stride = videocore_framebuffer_get_row_stride_proto, - .get_bytes_per_cell = videocore_framebuffer_get_bytes_per_cell_proto, - .get_native_frames_per_second = videocore_framebuffer_get_native_frames_per_second_proto, - .swapbuffers = videocore_framebuffer_swapbuffers, - .deinit = videocore_framebuffer_deinit_proto, -}; - -MP_DEFINE_CONST_OBJ_TYPE( - videocore_framebuffer_type, - MP_QSTR_Framebuffer, - MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, - locals_dict, (mp_obj_dict_t *)&videocore_framebuffer_locals_dict, - make_new, videocore_framebuffer_make_new, - buffer, common_hal_videocore_framebuffer_get_buffer, - protocol, &videocore_framebuffer_proto - ); diff --git a/ports/broadcom/bindings/videocore/Framebuffer.h b/ports/broadcom/bindings/videocore/Framebuffer.h deleted file mode 100644 index cb6c04a67bc..00000000000 --- a/ports/broadcom/bindings/videocore/Framebuffer.h +++ /dev/null @@ -1,20 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2020 Jeff Epler for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#pragma once - -#include "common-hal/videocore/Framebuffer.h" - -extern const mp_obj_type_t videocore_framebuffer_type; - -void common_hal_videocore_framebuffer_construct(videocore_framebuffer_obj_t *self, mp_uint_t width, mp_uint_t height); -void common_hal_videocore_framebuffer_deinit(videocore_framebuffer_obj_t *self); -bool common_hal_videocore_framebuffer_deinited(videocore_framebuffer_obj_t *self); -void common_hal_videocore_framebuffer_refresh(videocore_framebuffer_obj_t *self); -int common_hal_videocore_framebuffer_get_width(videocore_framebuffer_obj_t *self); -int common_hal_videocore_framebuffer_get_height(videocore_framebuffer_obj_t *self); -int common_hal_videocore_framebuffer_get_row_stride(videocore_framebuffer_obj_t *self); -mp_int_t common_hal_videocore_framebuffer_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags); diff --git a/ports/broadcom/bindings/videocore/__init__.c b/ports/broadcom/bindings/videocore/__init__.c deleted file mode 100644 index 3c83ba2ac78..00000000000 --- a/ports/broadcom/bindings/videocore/__init__.c +++ /dev/null @@ -1,28 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include - -#include "py/obj.h" -#include "py/runtime.h" - -#include "bindings/videocore/Framebuffer.h" - -//| """Low-level routines for interacting with the Broadcom VideoCore GPU""" - -static const mp_rom_map_elem_t videocore_module_globals_table[] = { - { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_videocore) }, - { MP_ROM_QSTR(MP_QSTR_Framebuffer), MP_ROM_PTR(&videocore_framebuffer_type) }, -}; - -static MP_DEFINE_CONST_DICT(videocore_module_globals, videocore_module_globals_table); - -const mp_obj_module_t videocore_module = { - .base = { &mp_type_module }, - .globals = (mp_obj_dict_t *)&videocore_module_globals, -}; - -MP_REGISTER_MODULE(MP_QSTR_videocore, videocore_module); diff --git a/ports/broadcom/boards/diodes_delight_piunora/board.c b/ports/broadcom/boards/diodes_delight_piunora/board.c deleted file mode 100644 index 612d93776df..00000000000 --- a/ports/broadcom/boards/diodes_delight_piunora/board.c +++ /dev/null @@ -1,28 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "supervisor/board.h" -#include "mpconfigboard.h" - -#include "bindings/videocore/Framebuffer.h" -#include "shared-module/displayio/__init__.h" -#include "shared-bindings/framebufferio/FramebufferDisplay.h" - -void board_init(void) { - videocore_framebuffer_obj_t *fb = &allocate_display_bus()->videocore; - fb->base.type = &videocore_framebuffer_type; - common_hal_videocore_framebuffer_construct(fb, 640, 480); - - framebufferio_framebufferdisplay_obj_t *display = &allocate_display()->framebuffer_display; - display->base.type = &framebufferio_framebufferdisplay_type; - common_hal_framebufferio_framebufferdisplay_construct( - display, - MP_OBJ_FROM_PTR(fb), - 0, - true); -} - -// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/broadcom/boards/diodes_delight_piunora/mpconfigboard.h b/ports/broadcom/boards/diodes_delight_piunora/mpconfigboard.h deleted file mode 100644 index 298a94316ad..00000000000 --- a/ports/broadcom/boards/diodes_delight_piunora/mpconfigboard.h +++ /dev/null @@ -1,17 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#pragma once - -#define MICROPY_HW_BOARD_NAME "Diodes Delight Piunora" - -#define DEFAULT_I2C_BUS_SCL (&pin_GPIO3) -#define DEFAULT_I2C_BUS_SDA (&pin_GPIO2) - -#define MICROPY_HW_NEOPIXEL (&pin_GPIO12) - -#define CIRCUITPY_CONSOLE_UART_TX (&pin_GPIO4) -#define CIRCUITPY_CONSOLE_UART_RX (&pin_GPIO5) diff --git a/ports/broadcom/boards/diodes_delight_piunora/mpconfigboard.mk b/ports/broadcom/boards/diodes_delight_piunora/mpconfigboard.mk deleted file mode 100644 index d05bb160282..00000000000 --- a/ports/broadcom/boards/diodes_delight_piunora/mpconfigboard.mk +++ /dev/null @@ -1,6 +0,0 @@ -USB_VID = 0x1209 -USB_PID = 0xD10D -USB_PRODUCT = "Piunora" -USB_MANUFACTURER = "Diodes Delight" - -CHIP_VARIANT = "bcm2711" diff --git a/ports/broadcom/boards/diodes_delight_piunora/pins.c b/ports/broadcom/boards/diodes_delight_piunora/pins.c deleted file mode 100644 index 27bbe93e1ee..00000000000 --- a/ports/broadcom/boards/diodes_delight_piunora/pins.c +++ /dev/null @@ -1,77 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "shared-bindings/board/__init__.h" - -#include "shared-module/displayio/__init__.h" - -static const mp_rom_map_elem_t board_global_dict_table[] = { - CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS - - { MP_ROM_QSTR(MP_QSTR_GPIO5), MP_ROM_PTR(&pin_GPIO5) }, - { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_GPIO5) }, - { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO5) }, - - { MP_ROM_QSTR(MP_QSTR_GPIO4), MP_ROM_PTR(&pin_GPIO4) }, - { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO4) }, - { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO4) }, - - { MP_ROM_QSTR(MP_QSTR_GPIO18), MP_ROM_PTR(&pin_GPIO18) }, - { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_GPIO18) }, - - { MP_ROM_QSTR(MP_QSTR_GPIO19), MP_ROM_PTR(&pin_GPIO19) }, - { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_GPIO19) }, - - { MP_ROM_QSTR(MP_QSTR_GPIO20), MP_ROM_PTR(&pin_GPIO20) }, - { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_GPIO20) }, - - { MP_ROM_QSTR(MP_QSTR_GPIO21), MP_ROM_PTR(&pin_GPIO21) }, - { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_GPIO21) }, - - { MP_ROM_QSTR(MP_QSTR_GPIO22), MP_ROM_PTR(&pin_GPIO22) }, - { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_GPIO22) }, - { MP_ROM_QSTR(MP_QSTR_SDA6), MP_ROM_PTR(&pin_GPIO22) }, - - { MP_ROM_QSTR(MP_QSTR_GPIO23), MP_ROM_PTR(&pin_GPIO23) }, - { MP_ROM_QSTR(MP_QSTR_D7), MP_ROM_PTR(&pin_GPIO23) }, - { MP_ROM_QSTR(MP_QSTR_SCL6), MP_ROM_PTR(&pin_GPIO23) }, - - { MP_ROM_QSTR(MP_QSTR_GPIO6), MP_ROM_PTR(&pin_GPIO6) }, - { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_GPIO6) }, - { MP_ROM_QSTR(MP_QSTR_SDA4), MP_ROM_PTR(&pin_GPIO6) }, - - { MP_ROM_QSTR(MP_QSTR_GPIO7), MP_ROM_PTR(&pin_GPIO7) }, - { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_GPIO7) }, - { MP_ROM_QSTR(MP_QSTR_SCL4), MP_ROM_PTR(&pin_GPIO7) }, - { MP_ROM_QSTR(MP_QSTR_SPI0_CE1), MP_ROM_PTR(&pin_GPIO7) }, - - { MP_ROM_QSTR(MP_QSTR_GPIO8), MP_ROM_PTR(&pin_GPIO8) }, - { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_GPIO8) }, - { MP_ROM_QSTR(MP_QSTR_SPI0_CE0), MP_ROM_PTR(&pin_GPIO8) }, - - { MP_ROM_QSTR(MP_QSTR_GPIO10), MP_ROM_PTR(&pin_GPIO10) }, - { MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_GPIO10) }, - { MP_ROM_QSTR(MP_QSTR_SPI0_MOSI), MP_ROM_PTR(&pin_GPIO10) }, - - { MP_ROM_QSTR(MP_QSTR_GPIO9), MP_ROM_PTR(&pin_GPIO9) }, - { MP_ROM_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_GPIO9) }, - { MP_ROM_QSTR(MP_QSTR_SPI0_MISO), MP_ROM_PTR(&pin_GPIO9) }, - - { MP_ROM_QSTR(MP_QSTR_GPIO11), MP_ROM_PTR(&pin_GPIO11) }, - { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_GPIO11) }, - { MP_ROM_QSTR(MP_QSTR_SPI0_SCLK), MP_ROM_PTR(&pin_GPIO11) }, - - { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO2) }, - { MP_ROM_QSTR(MP_QSTR_SDA1), MP_ROM_PTR(&pin_GPIO2) }, - { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO3) }, - - { MP_ROM_QSTR(MP_QSTR_GPIO12), MP_ROM_PTR(&pin_GPIO12) }, - { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO12) }, - - { 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/broadcom/boards/raspberrypi_cm4/board.c b/ports/broadcom/boards/raspberrypi_cm4/board.c deleted file mode 100644 index 612d93776df..00000000000 --- a/ports/broadcom/boards/raspberrypi_cm4/board.c +++ /dev/null @@ -1,28 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "supervisor/board.h" -#include "mpconfigboard.h" - -#include "bindings/videocore/Framebuffer.h" -#include "shared-module/displayio/__init__.h" -#include "shared-bindings/framebufferio/FramebufferDisplay.h" - -void board_init(void) { - videocore_framebuffer_obj_t *fb = &allocate_display_bus()->videocore; - fb->base.type = &videocore_framebuffer_type; - common_hal_videocore_framebuffer_construct(fb, 640, 480); - - framebufferio_framebufferdisplay_obj_t *display = &allocate_display()->framebuffer_display; - display->base.type = &framebufferio_framebufferdisplay_type; - common_hal_framebufferio_framebufferdisplay_construct( - display, - MP_OBJ_FROM_PTR(fb), - 0, - true); -} - -// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/broadcom/boards/raspberrypi_cm4/mpconfigboard.h b/ports/broadcom/boards/raspberrypi_cm4/mpconfigboard.h deleted file mode 100644 index 23b99342fac..00000000000 --- a/ports/broadcom/boards/raspberrypi_cm4/mpconfigboard.h +++ /dev/null @@ -1,9 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#pragma once - -#define MICROPY_HW_BOARD_NAME "Raspberry Pi Compute Module 4" diff --git a/ports/broadcom/boards/raspberrypi_cm4/mpconfigboard.mk b/ports/broadcom/boards/raspberrypi_cm4/mpconfigboard.mk deleted file mode 100644 index ee54efe84be..00000000000 --- a/ports/broadcom/boards/raspberrypi_cm4/mpconfigboard.mk +++ /dev/null @@ -1,6 +0,0 @@ -USB_VID = 0x2E8A -USB_PID = 0x1014 -USB_PRODUCT = "Compute Module 4" -USB_MANUFACTURER = "Raspberry Pi" - -CHIP_VARIANT = "bcm2711" diff --git a/ports/broadcom/boards/raspberrypi_cm4/pins.c b/ports/broadcom/boards/raspberrypi_cm4/pins.c deleted file mode 100644 index 83f781eea97..00000000000 --- a/ports/broadcom/boards/raspberrypi_cm4/pins.c +++ /dev/null @@ -1,54 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "shared-bindings/board/__init__.h" - -#include "shared-module/displayio/__init__.h" - -static const mp_rom_map_elem_t board_global_dict_table[] = { - CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS - - // These match the names used in the CM4 datasheet - { MP_ROM_QSTR(MP_QSTR_ID_SD), MP_ROM_PTR(&pin_GPIO0) }, - { MP_ROM_QSTR(MP_QSTR_ID_SC), MP_ROM_PTR(&pin_GPIO1) }, - { MP_ROM_QSTR(MP_QSTR_GPIO2), MP_ROM_PTR(&pin_GPIO2) }, - { MP_ROM_QSTR(MP_QSTR_GPIO3), MP_ROM_PTR(&pin_GPIO3) }, - { MP_ROM_QSTR(MP_QSTR_GPIO4), MP_ROM_PTR(&pin_GPIO4) }, - { MP_ROM_QSTR(MP_QSTR_GPIO5), MP_ROM_PTR(&pin_GPIO5) }, - { MP_ROM_QSTR(MP_QSTR_GPIO6), MP_ROM_PTR(&pin_GPIO6) }, - { MP_ROM_QSTR(MP_QSTR_GPIO7), MP_ROM_PTR(&pin_GPIO7) }, - { MP_ROM_QSTR(MP_QSTR_GPIO8), MP_ROM_PTR(&pin_GPIO8) }, - { MP_ROM_QSTR(MP_QSTR_GPIO9), MP_ROM_PTR(&pin_GPIO9) }, - - { MP_ROM_QSTR(MP_QSTR_GPIO10), MP_ROM_PTR(&pin_GPIO10) }, - { MP_ROM_QSTR(MP_QSTR_GPIO11), MP_ROM_PTR(&pin_GPIO11) }, - { MP_ROM_QSTR(MP_QSTR_GPIO12), MP_ROM_PTR(&pin_GPIO12) }, - { MP_ROM_QSTR(MP_QSTR_GPIO13), MP_ROM_PTR(&pin_GPIO13) }, - { MP_ROM_QSTR(MP_QSTR_GPIO14), MP_ROM_PTR(&pin_GPIO14) }, - { MP_ROM_QSTR(MP_QSTR_GPIO15), MP_ROM_PTR(&pin_GPIO15) }, - - { MP_ROM_QSTR(MP_QSTR_GPIO16), MP_ROM_PTR(&pin_GPIO16) }, - { MP_ROM_QSTR(MP_QSTR_GPIO17), MP_ROM_PTR(&pin_GPIO17) }, - { MP_ROM_QSTR(MP_QSTR_GPIO18), MP_ROM_PTR(&pin_GPIO18) }, - { MP_ROM_QSTR(MP_QSTR_GPIO19), MP_ROM_PTR(&pin_GPIO19) }, - { MP_ROM_QSTR(MP_QSTR_GPIO20), MP_ROM_PTR(&pin_GPIO20) }, - { MP_ROM_QSTR(MP_QSTR_GPIO21), MP_ROM_PTR(&pin_GPIO21) }, - { MP_ROM_QSTR(MP_QSTR_GPIO22), MP_ROM_PTR(&pin_GPIO22) }, - { MP_ROM_QSTR(MP_QSTR_GPIO23), MP_ROM_PTR(&pin_GPIO23) }, - { MP_ROM_QSTR(MP_QSTR_GPIO24), MP_ROM_PTR(&pin_GPIO24) }, - { MP_ROM_QSTR(MP_QSTR_GPIO25), MP_ROM_PTR(&pin_GPIO25) }, - { MP_ROM_QSTR(MP_QSTR_GPIO26), MP_ROM_PTR(&pin_GPIO26) }, - { MP_ROM_QSTR(MP_QSTR_GPIO27), MP_ROM_PTR(&pin_GPIO27) }, - - { MP_ROM_QSTR(MP_QSTR_LED_nACT), MP_ROM_PTR(&pin_GPIO42) }, - { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO42) }, - - { MP_ROM_QSTR(MP_QSTR_SDA0), MP_ROM_PTR(&pin_GPIO44) }, - { MP_ROM_QSTR(MP_QSTR_SCL0), MP_ROM_PTR(&pin_GPIO45) }, - - { 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/broadcom/boards/raspberrypi_cm4io/board.c b/ports/broadcom/boards/raspberrypi_cm4io/board.c deleted file mode 100644 index 612d93776df..00000000000 --- a/ports/broadcom/boards/raspberrypi_cm4io/board.c +++ /dev/null @@ -1,28 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "supervisor/board.h" -#include "mpconfigboard.h" - -#include "bindings/videocore/Framebuffer.h" -#include "shared-module/displayio/__init__.h" -#include "shared-bindings/framebufferio/FramebufferDisplay.h" - -void board_init(void) { - videocore_framebuffer_obj_t *fb = &allocate_display_bus()->videocore; - fb->base.type = &videocore_framebuffer_type; - common_hal_videocore_framebuffer_construct(fb, 640, 480); - - framebufferio_framebufferdisplay_obj_t *display = &allocate_display()->framebuffer_display; - display->base.type = &framebufferio_framebufferdisplay_type; - common_hal_framebufferio_framebufferdisplay_construct( - display, - MP_OBJ_FROM_PTR(fb), - 0, - true); -} - -// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/broadcom/boards/raspberrypi_cm4io/mpconfigboard.h b/ports/broadcom/boards/raspberrypi_cm4io/mpconfigboard.h deleted file mode 100644 index 2c02fabd9ec..00000000000 --- a/ports/broadcom/boards/raspberrypi_cm4io/mpconfigboard.h +++ /dev/null @@ -1,17 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#pragma once - -#define MICROPY_HW_BOARD_NAME "Raspberry Pi Compute Module 4 IO Board" - -#define DEFAULT_I2C_BUS_SCL (&pin_GPIO3) -#define DEFAULT_I2C_BUS_SDA (&pin_GPIO2) - -#define MICROPY_HW_LED_STATUS (&pin_GPIO42) - -#define CIRCUITPY_CONSOLE_UART_TX (&pin_GPIO14) -#define CIRCUITPY_CONSOLE_UART_RX (&pin_GPIO15) diff --git a/ports/broadcom/boards/raspberrypi_cm4io/mpconfigboard.mk b/ports/broadcom/boards/raspberrypi_cm4io/mpconfigboard.mk deleted file mode 100644 index d021462bc6b..00000000000 --- a/ports/broadcom/boards/raspberrypi_cm4io/mpconfigboard.mk +++ /dev/null @@ -1,6 +0,0 @@ -USB_VID = 0x2E8A -USB_PID = 0x1012 -USB_PRODUCT = "Compute Module 4 IO Board" -USB_MANUFACTURER = "Raspberry Pi" - -CHIP_VARIANT = "bcm2711" diff --git a/ports/broadcom/boards/raspberrypi_cm4io/pins.c b/ports/broadcom/boards/raspberrypi_cm4io/pins.c deleted file mode 100644 index d9666eafda3..00000000000 --- a/ports/broadcom/boards/raspberrypi_cm4io/pins.c +++ /dev/null @@ -1,71 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "shared-bindings/board/__init__.h" - -#include "shared-module/displayio/__init__.h" - -static const mp_rom_map_elem_t board_global_dict_table[] = { - CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS - - // These match the names used in Blinka - { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_GPIO0) }, - { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO1) }, - - { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_GPIO2) }, - { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO2) }, - { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_GPIO3) }, - { MP_ROM_QSTR(MP_QSTR_SCL), 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_CE1), MP_ROM_PTR(&pin_GPIO7) }, - { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_GPIO8) }, - { MP_ROM_QSTR(MP_QSTR_CE0), MP_ROM_PTR(&pin_GPIO8) }, - { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_GPIO9) }, - { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO9) }, - { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_GPIO10) }, - { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO10) }, - { MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_GPIO11) }, - { MP_ROM_QSTR(MP_QSTR_SCLK), MP_ROM_PTR(&pin_GPIO11) }, - { MP_ROM_QSTR(MP_QSTR_SCK), 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_D14), MP_ROM_PTR(&pin_GPIO14) }, - { MP_ROM_QSTR(MP_QSTR_TXD), MP_ROM_PTR(&pin_GPIO14) }, - { MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_GPIO15) }, - { MP_ROM_QSTR(MP_QSTR_RXD), MP_ROM_PTR(&pin_GPIO15) }, - { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO14) }, - { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO15) }, - - { MP_ROM_QSTR(MP_QSTR_D16), MP_ROM_PTR(&pin_GPIO16) }, - { MP_ROM_QSTR(MP_QSTR_D17), MP_ROM_PTR(&pin_GPIO17) }, - { MP_ROM_QSTR(MP_QSTR_D18), MP_ROM_PTR(&pin_GPIO18) }, - { MP_ROM_QSTR(MP_QSTR_D19), MP_ROM_PTR(&pin_GPIO19) }, - { MP_ROM_QSTR(MP_QSTR_MISO_1), MP_ROM_PTR(&pin_GPIO19) }, - { MP_ROM_QSTR(MP_QSTR_D20), MP_ROM_PTR(&pin_GPIO20) }, - { MP_ROM_QSTR(MP_QSTR_MOSI_1), MP_ROM_PTR(&pin_GPIO20) }, - { MP_ROM_QSTR(MP_QSTR_D21), MP_ROM_PTR(&pin_GPIO21) }, - { MP_ROM_QSTR(MP_QSTR_SCLK_1), MP_ROM_PTR(&pin_GPIO21) }, - { MP_ROM_QSTR(MP_QSTR_SCK_1), MP_ROM_PTR(&pin_GPIO21) }, - { MP_ROM_QSTR(MP_QSTR_D22), MP_ROM_PTR(&pin_GPIO22) }, - { MP_ROM_QSTR(MP_QSTR_D23), MP_ROM_PTR(&pin_GPIO23) }, - { 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_D26), MP_ROM_PTR(&pin_GPIO26) }, - { MP_ROM_QSTR(MP_QSTR_D27), MP_ROM_PTR(&pin_GPIO27) }, - - { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO42) }, - - { 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/broadcom/boards/raspberrypi_pi4b/board.c b/ports/broadcom/boards/raspberrypi_pi4b/board.c deleted file mode 100644 index 612d93776df..00000000000 --- a/ports/broadcom/boards/raspberrypi_pi4b/board.c +++ /dev/null @@ -1,28 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "supervisor/board.h" -#include "mpconfigboard.h" - -#include "bindings/videocore/Framebuffer.h" -#include "shared-module/displayio/__init__.h" -#include "shared-bindings/framebufferio/FramebufferDisplay.h" - -void board_init(void) { - videocore_framebuffer_obj_t *fb = &allocate_display_bus()->videocore; - fb->base.type = &videocore_framebuffer_type; - common_hal_videocore_framebuffer_construct(fb, 640, 480); - - framebufferio_framebufferdisplay_obj_t *display = &allocate_display()->framebuffer_display; - display->base.type = &framebufferio_framebufferdisplay_type; - common_hal_framebufferio_framebufferdisplay_construct( - display, - MP_OBJ_FROM_PTR(fb), - 0, - true); -} - -// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/broadcom/boards/raspberrypi_pi4b/mpconfigboard.h b/ports/broadcom/boards/raspberrypi_pi4b/mpconfigboard.h deleted file mode 100644 index 45eeff3b59b..00000000000 --- a/ports/broadcom/boards/raspberrypi_pi4b/mpconfigboard.h +++ /dev/null @@ -1,17 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#pragma once - -#define MICROPY_HW_BOARD_NAME "Raspberry Pi 4B" - -#define DEFAULT_I2C_BUS_SCL (&pin_GPIO3) -#define DEFAULT_I2C_BUS_SDA (&pin_GPIO2) - -#define MICROPY_HW_LED_STATUS (&pin_GPIO42) - -#define CIRCUITPY_CONSOLE_UART_TX (&pin_GPIO14) -#define CIRCUITPY_CONSOLE_UART_RX (&pin_GPIO15) diff --git a/ports/broadcom/boards/raspberrypi_pi4b/mpconfigboard.mk b/ports/broadcom/boards/raspberrypi_pi4b/mpconfigboard.mk deleted file mode 100644 index 2c808931da5..00000000000 --- a/ports/broadcom/boards/raspberrypi_pi4b/mpconfigboard.mk +++ /dev/null @@ -1,6 +0,0 @@ -USB_VID = 0x2E8A -USB_PID = 0x1013 -USB_PRODUCT = "Raspberry Pi 4B" -USB_MANUFACTURER = "Raspberry Pi" - -CHIP_VARIANT = "bcm2711" diff --git a/ports/broadcom/boards/raspberrypi_pi4b/pins.c b/ports/broadcom/boards/raspberrypi_pi4b/pins.c deleted file mode 100644 index d9666eafda3..00000000000 --- a/ports/broadcom/boards/raspberrypi_pi4b/pins.c +++ /dev/null @@ -1,71 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "shared-bindings/board/__init__.h" - -#include "shared-module/displayio/__init__.h" - -static const mp_rom_map_elem_t board_global_dict_table[] = { - CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS - - // These match the names used in Blinka - { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_GPIO0) }, - { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO1) }, - - { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_GPIO2) }, - { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO2) }, - { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_GPIO3) }, - { MP_ROM_QSTR(MP_QSTR_SCL), 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_CE1), MP_ROM_PTR(&pin_GPIO7) }, - { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_GPIO8) }, - { MP_ROM_QSTR(MP_QSTR_CE0), MP_ROM_PTR(&pin_GPIO8) }, - { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_GPIO9) }, - { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO9) }, - { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_GPIO10) }, - { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO10) }, - { MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_GPIO11) }, - { MP_ROM_QSTR(MP_QSTR_SCLK), MP_ROM_PTR(&pin_GPIO11) }, - { MP_ROM_QSTR(MP_QSTR_SCK), 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_D14), MP_ROM_PTR(&pin_GPIO14) }, - { MP_ROM_QSTR(MP_QSTR_TXD), MP_ROM_PTR(&pin_GPIO14) }, - { MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_GPIO15) }, - { MP_ROM_QSTR(MP_QSTR_RXD), MP_ROM_PTR(&pin_GPIO15) }, - { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO14) }, - { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO15) }, - - { MP_ROM_QSTR(MP_QSTR_D16), MP_ROM_PTR(&pin_GPIO16) }, - { MP_ROM_QSTR(MP_QSTR_D17), MP_ROM_PTR(&pin_GPIO17) }, - { MP_ROM_QSTR(MP_QSTR_D18), MP_ROM_PTR(&pin_GPIO18) }, - { MP_ROM_QSTR(MP_QSTR_D19), MP_ROM_PTR(&pin_GPIO19) }, - { MP_ROM_QSTR(MP_QSTR_MISO_1), MP_ROM_PTR(&pin_GPIO19) }, - { MP_ROM_QSTR(MP_QSTR_D20), MP_ROM_PTR(&pin_GPIO20) }, - { MP_ROM_QSTR(MP_QSTR_MOSI_1), MP_ROM_PTR(&pin_GPIO20) }, - { MP_ROM_QSTR(MP_QSTR_D21), MP_ROM_PTR(&pin_GPIO21) }, - { MP_ROM_QSTR(MP_QSTR_SCLK_1), MP_ROM_PTR(&pin_GPIO21) }, - { MP_ROM_QSTR(MP_QSTR_SCK_1), MP_ROM_PTR(&pin_GPIO21) }, - { MP_ROM_QSTR(MP_QSTR_D22), MP_ROM_PTR(&pin_GPIO22) }, - { MP_ROM_QSTR(MP_QSTR_D23), MP_ROM_PTR(&pin_GPIO23) }, - { 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_D26), MP_ROM_PTR(&pin_GPIO26) }, - { MP_ROM_QSTR(MP_QSTR_D27), MP_ROM_PTR(&pin_GPIO27) }, - - { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO42) }, - - { 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/broadcom/boards/raspberrypi_zero/board.c b/ports/broadcom/boards/raspberrypi_zero/board.c deleted file mode 100644 index 612d93776df..00000000000 --- a/ports/broadcom/boards/raspberrypi_zero/board.c +++ /dev/null @@ -1,28 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "supervisor/board.h" -#include "mpconfigboard.h" - -#include "bindings/videocore/Framebuffer.h" -#include "shared-module/displayio/__init__.h" -#include "shared-bindings/framebufferio/FramebufferDisplay.h" - -void board_init(void) { - videocore_framebuffer_obj_t *fb = &allocate_display_bus()->videocore; - fb->base.type = &videocore_framebuffer_type; - common_hal_videocore_framebuffer_construct(fb, 640, 480); - - framebufferio_framebufferdisplay_obj_t *display = &allocate_display()->framebuffer_display; - display->base.type = &framebufferio_framebufferdisplay_type; - common_hal_framebufferio_framebufferdisplay_construct( - display, - MP_OBJ_FROM_PTR(fb), - 0, - true); -} - -// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/broadcom/boards/raspberrypi_zero/mpconfigboard.h b/ports/broadcom/boards/raspberrypi_zero/mpconfigboard.h deleted file mode 100644 index 64da629317e..00000000000 --- a/ports/broadcom/boards/raspberrypi_zero/mpconfigboard.h +++ /dev/null @@ -1,17 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#pragma once - -#define MICROPY_HW_BOARD_NAME "Raspberry Pi Zero" - -#define DEFAULT_I2C_BUS_SCL (&pin_GPIO3) -#define DEFAULT_I2C_BUS_SDA (&pin_GPIO2) - -#define MICROPY_HW_LED_STATUS (&pin_GPIO47) - -#define CIRCUITPY_CONSOLE_UART_TX (&pin_GPIO14) -#define CIRCUITPY_CONSOLE_UART_RX (&pin_GPIO15) diff --git a/ports/broadcom/boards/raspberrypi_zero/mpconfigboard.mk b/ports/broadcom/boards/raspberrypi_zero/mpconfigboard.mk deleted file mode 100644 index b6adb5d6bb8..00000000000 --- a/ports/broadcom/boards/raspberrypi_zero/mpconfigboard.mk +++ /dev/null @@ -1,8 +0,0 @@ -USB_VID = 0x2E8A -USB_PID = 0x100E -USB_PRODUCT = "Zero" -USB_MANUFACTURER = "Raspberry Pi" - -CHIP_VARIANT = "bcm2835" - -CIRCUITPY_BUILD_EXTENSIONS = disk.img.zip,kernel.img diff --git a/ports/broadcom/boards/raspberrypi_zero/pins.c b/ports/broadcom/boards/raspberrypi_zero/pins.c deleted file mode 100644 index 4b3cf228135..00000000000 --- a/ports/broadcom/boards/raspberrypi_zero/pins.c +++ /dev/null @@ -1,68 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "shared-bindings/board/__init__.h" - -#include "shared-module/displayio/__init__.h" - -static const mp_rom_map_elem_t board_global_dict_table[] = { - CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS - // These match the names used in Blinka - { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_GPIO0) }, - { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO1) }, - - { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_GPIO2) }, - { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO2) }, - { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_GPIO3) }, - { MP_ROM_QSTR(MP_QSTR_SCL), 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_CE1), MP_ROM_PTR(&pin_GPIO7) }, - { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_GPIO8) }, - { MP_ROM_QSTR(MP_QSTR_CE0), MP_ROM_PTR(&pin_GPIO8) }, - { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_GPIO9) }, - { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO9) }, - { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_GPIO10) }, - { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO10) }, - { MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_GPIO11) }, - { MP_ROM_QSTR(MP_QSTR_SCLK), MP_ROM_PTR(&pin_GPIO11) }, - { MP_ROM_QSTR(MP_QSTR_SCK), 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_D14), MP_ROM_PTR(&pin_GPIO14) }, - { MP_ROM_QSTR(MP_QSTR_TXD), MP_ROM_PTR(&pin_GPIO14) }, - { MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_GPIO15) }, - { MP_ROM_QSTR(MP_QSTR_RXD), MP_ROM_PTR(&pin_GPIO15) }, - { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO14) }, - { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO15) }, - - { MP_ROM_QSTR(MP_QSTR_D16), MP_ROM_PTR(&pin_GPIO16) }, - { MP_ROM_QSTR(MP_QSTR_D17), MP_ROM_PTR(&pin_GPIO17) }, - { MP_ROM_QSTR(MP_QSTR_D18), MP_ROM_PTR(&pin_GPIO18) }, - { MP_ROM_QSTR(MP_QSTR_D19), MP_ROM_PTR(&pin_GPIO19) }, - { MP_ROM_QSTR(MP_QSTR_MISO_1), MP_ROM_PTR(&pin_GPIO19) }, - { MP_ROM_QSTR(MP_QSTR_D20), MP_ROM_PTR(&pin_GPIO20) }, - { MP_ROM_QSTR(MP_QSTR_MOSI_1), MP_ROM_PTR(&pin_GPIO20) }, - { MP_ROM_QSTR(MP_QSTR_D21), MP_ROM_PTR(&pin_GPIO21) }, - { MP_ROM_QSTR(MP_QSTR_SCLK_1), MP_ROM_PTR(&pin_GPIO21) }, - { MP_ROM_QSTR(MP_QSTR_SCK_1), MP_ROM_PTR(&pin_GPIO21) }, - { MP_ROM_QSTR(MP_QSTR_D22), MP_ROM_PTR(&pin_GPIO22) }, - { MP_ROM_QSTR(MP_QSTR_D23), MP_ROM_PTR(&pin_GPIO23) }, - { 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_D26), MP_ROM_PTR(&pin_GPIO26) }, - { MP_ROM_QSTR(MP_QSTR_D27), MP_ROM_PTR(&pin_GPIO27) }, - - { 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/broadcom/boards/raspberrypi_zero2w/board.c b/ports/broadcom/boards/raspberrypi_zero2w/board.c deleted file mode 100644 index 612d93776df..00000000000 --- a/ports/broadcom/boards/raspberrypi_zero2w/board.c +++ /dev/null @@ -1,28 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "supervisor/board.h" -#include "mpconfigboard.h" - -#include "bindings/videocore/Framebuffer.h" -#include "shared-module/displayio/__init__.h" -#include "shared-bindings/framebufferio/FramebufferDisplay.h" - -void board_init(void) { - videocore_framebuffer_obj_t *fb = &allocate_display_bus()->videocore; - fb->base.type = &videocore_framebuffer_type; - common_hal_videocore_framebuffer_construct(fb, 640, 480); - - framebufferio_framebufferdisplay_obj_t *display = &allocate_display()->framebuffer_display; - display->base.type = &framebufferio_framebufferdisplay_type; - common_hal_framebufferio_framebufferdisplay_construct( - display, - MP_OBJ_FROM_PTR(fb), - 0, - true); -} - -// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/broadcom/boards/raspberrypi_zero2w/mpconfigboard.h b/ports/broadcom/boards/raspberrypi_zero2w/mpconfigboard.h deleted file mode 100644 index 4168832fb82..00000000000 --- a/ports/broadcom/boards/raspberrypi_zero2w/mpconfigboard.h +++ /dev/null @@ -1,17 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#pragma once - -#define MICROPY_HW_BOARD_NAME "Raspberry Pi Zero 2W" - -#define DEFAULT_I2C_BUS_SCL (&pin_GPIO3) -#define DEFAULT_I2C_BUS_SDA (&pin_GPIO2) - -#define MICROPY_HW_LED_STATUS (&pin_GPIO29) - -#define CIRCUITPY_CONSOLE_UART_TX (&pin_GPIO14) -#define CIRCUITPY_CONSOLE_UART_RX (&pin_GPIO15) diff --git a/ports/broadcom/boards/raspberrypi_zero2w/mpconfigboard.mk b/ports/broadcom/boards/raspberrypi_zero2w/mpconfigboard.mk deleted file mode 100644 index 1479cb3b8c4..00000000000 --- a/ports/broadcom/boards/raspberrypi_zero2w/mpconfigboard.mk +++ /dev/null @@ -1,6 +0,0 @@ -USB_VID = 0x2E8A -USB_PID = 0x1015 -USB_PRODUCT = "Raspberry Pi Zero 2W" -USB_MANUFACTURER = "Raspberry Pi" - -CHIP_VARIANT = "bcm2837" diff --git a/ports/broadcom/boards/raspberrypi_zero2w/pins.c b/ports/broadcom/boards/raspberrypi_zero2w/pins.c deleted file mode 100644 index 1d8f247487e..00000000000 --- a/ports/broadcom/boards/raspberrypi_zero2w/pins.c +++ /dev/null @@ -1,69 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "shared-bindings/board/__init__.h" - -#include "shared-module/displayio/__init__.h" - -static const mp_rom_map_elem_t board_global_dict_table[] = { - CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS - // These match the names used in Blinka - { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_GPIO0) }, - { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO1) }, - - { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_GPIO2) }, - { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO2) }, - { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_GPIO3) }, - { MP_ROM_QSTR(MP_QSTR_SCL), 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_CE1), MP_ROM_PTR(&pin_GPIO7) }, - { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_GPIO8) }, - { MP_ROM_QSTR(MP_QSTR_CE0), MP_ROM_PTR(&pin_GPIO8) }, - { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_GPIO9) }, - { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO9) }, - { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_GPIO10) }, - { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO10) }, - { MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_GPIO11) }, - { MP_ROM_QSTR(MP_QSTR_SCLK), MP_ROM_PTR(&pin_GPIO11) }, - { MP_ROM_QSTR(MP_QSTR_SCK), 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_D14), MP_ROM_PTR(&pin_GPIO14) }, - { MP_ROM_QSTR(MP_QSTR_TXD), MP_ROM_PTR(&pin_GPIO14) }, - { MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_GPIO15) }, - { MP_ROM_QSTR(MP_QSTR_RXD), MP_ROM_PTR(&pin_GPIO15) }, - { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO14) }, - { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO15) }, - - { MP_ROM_QSTR(MP_QSTR_D16), MP_ROM_PTR(&pin_GPIO16) }, - { MP_ROM_QSTR(MP_QSTR_D17), MP_ROM_PTR(&pin_GPIO17) }, - { MP_ROM_QSTR(MP_QSTR_D18), MP_ROM_PTR(&pin_GPIO18) }, - { MP_ROM_QSTR(MP_QSTR_D19), MP_ROM_PTR(&pin_GPIO19) }, - { MP_ROM_QSTR(MP_QSTR_MISO_1), MP_ROM_PTR(&pin_GPIO19) }, - { MP_ROM_QSTR(MP_QSTR_D20), MP_ROM_PTR(&pin_GPIO20) }, - { MP_ROM_QSTR(MP_QSTR_MOSI_1), MP_ROM_PTR(&pin_GPIO20) }, - { MP_ROM_QSTR(MP_QSTR_D21), MP_ROM_PTR(&pin_GPIO21) }, - { MP_ROM_QSTR(MP_QSTR_SCLK_1), MP_ROM_PTR(&pin_GPIO21) }, - { MP_ROM_QSTR(MP_QSTR_SCK_1), MP_ROM_PTR(&pin_GPIO21) }, - { MP_ROM_QSTR(MP_QSTR_D22), MP_ROM_PTR(&pin_GPIO22) }, - { MP_ROM_QSTR(MP_QSTR_D23), MP_ROM_PTR(&pin_GPIO23) }, - { 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_D26), MP_ROM_PTR(&pin_GPIO26) }, - { MP_ROM_QSTR(MP_QSTR_D27), MP_ROM_PTR(&pin_GPIO27) }, - { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO29) }, - - { 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/broadcom/boards/raspberrypi_zero_w/board.c b/ports/broadcom/boards/raspberrypi_zero_w/board.c deleted file mode 100644 index 612d93776df..00000000000 --- a/ports/broadcom/boards/raspberrypi_zero_w/board.c +++ /dev/null @@ -1,28 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "supervisor/board.h" -#include "mpconfigboard.h" - -#include "bindings/videocore/Framebuffer.h" -#include "shared-module/displayio/__init__.h" -#include "shared-bindings/framebufferio/FramebufferDisplay.h" - -void board_init(void) { - videocore_framebuffer_obj_t *fb = &allocate_display_bus()->videocore; - fb->base.type = &videocore_framebuffer_type; - common_hal_videocore_framebuffer_construct(fb, 640, 480); - - framebufferio_framebufferdisplay_obj_t *display = &allocate_display()->framebuffer_display; - display->base.type = &framebufferio_framebufferdisplay_type; - common_hal_framebufferio_framebufferdisplay_construct( - display, - MP_OBJ_FROM_PTR(fb), - 0, - true); -} - -// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/broadcom/boards/raspberrypi_zero_w/mpconfigboard.h b/ports/broadcom/boards/raspberrypi_zero_w/mpconfigboard.h deleted file mode 100644 index 526a152011e..00000000000 --- a/ports/broadcom/boards/raspberrypi_zero_w/mpconfigboard.h +++ /dev/null @@ -1,17 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#pragma once - -#define MICROPY_HW_BOARD_NAME "Raspberry Pi Zero W" - -#define DEFAULT_I2C_BUS_SCL (&pin_GPIO3) -#define DEFAULT_I2C_BUS_SDA (&pin_GPIO2) - -#define MICROPY_HW_LED_STATUS (&pin_GPIO47) - -#define CIRCUITPY_CONSOLE_UART_TX (&pin_GPIO14) -#define CIRCUITPY_CONSOLE_UART_RX (&pin_GPIO15) diff --git a/ports/broadcom/boards/raspberrypi_zero_w/mpconfigboard.mk b/ports/broadcom/boards/raspberrypi_zero_w/mpconfigboard.mk deleted file mode 100644 index cd55f73ee84..00000000000 --- a/ports/broadcom/boards/raspberrypi_zero_w/mpconfigboard.mk +++ /dev/null @@ -1,8 +0,0 @@ -USB_VID = 0x2E8A -USB_PID = 0x101E -USB_PRODUCT = "Zero W" -USB_MANUFACTURER = "Raspberry Pi" - -CHIP_VARIANT = "bcm2835" - -CIRCUITPY_BUILD_EXTENSIONS = disk.img.zip,kernel.img diff --git a/ports/broadcom/boards/raspberrypi_zero_w/pins.c b/ports/broadcom/boards/raspberrypi_zero_w/pins.c deleted file mode 100644 index 4b3cf228135..00000000000 --- a/ports/broadcom/boards/raspberrypi_zero_w/pins.c +++ /dev/null @@ -1,68 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "shared-bindings/board/__init__.h" - -#include "shared-module/displayio/__init__.h" - -static const mp_rom_map_elem_t board_global_dict_table[] = { - CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS - // These match the names used in Blinka - { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_GPIO0) }, - { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO1) }, - - { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_GPIO2) }, - { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO2) }, - { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_GPIO3) }, - { MP_ROM_QSTR(MP_QSTR_SCL), 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_CE1), MP_ROM_PTR(&pin_GPIO7) }, - { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_GPIO8) }, - { MP_ROM_QSTR(MP_QSTR_CE0), MP_ROM_PTR(&pin_GPIO8) }, - { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_GPIO9) }, - { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO9) }, - { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_GPIO10) }, - { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO10) }, - { MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_GPIO11) }, - { MP_ROM_QSTR(MP_QSTR_SCLK), MP_ROM_PTR(&pin_GPIO11) }, - { MP_ROM_QSTR(MP_QSTR_SCK), 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_D14), MP_ROM_PTR(&pin_GPIO14) }, - { MP_ROM_QSTR(MP_QSTR_TXD), MP_ROM_PTR(&pin_GPIO14) }, - { MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_GPIO15) }, - { MP_ROM_QSTR(MP_QSTR_RXD), MP_ROM_PTR(&pin_GPIO15) }, - { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO14) }, - { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO15) }, - - { MP_ROM_QSTR(MP_QSTR_D16), MP_ROM_PTR(&pin_GPIO16) }, - { MP_ROM_QSTR(MP_QSTR_D17), MP_ROM_PTR(&pin_GPIO17) }, - { MP_ROM_QSTR(MP_QSTR_D18), MP_ROM_PTR(&pin_GPIO18) }, - { MP_ROM_QSTR(MP_QSTR_D19), MP_ROM_PTR(&pin_GPIO19) }, - { MP_ROM_QSTR(MP_QSTR_MISO_1), MP_ROM_PTR(&pin_GPIO19) }, - { MP_ROM_QSTR(MP_QSTR_D20), MP_ROM_PTR(&pin_GPIO20) }, - { MP_ROM_QSTR(MP_QSTR_MOSI_1), MP_ROM_PTR(&pin_GPIO20) }, - { MP_ROM_QSTR(MP_QSTR_D21), MP_ROM_PTR(&pin_GPIO21) }, - { MP_ROM_QSTR(MP_QSTR_SCLK_1), MP_ROM_PTR(&pin_GPIO21) }, - { MP_ROM_QSTR(MP_QSTR_SCK_1), MP_ROM_PTR(&pin_GPIO21) }, - { MP_ROM_QSTR(MP_QSTR_D22), MP_ROM_PTR(&pin_GPIO22) }, - { MP_ROM_QSTR(MP_QSTR_D23), MP_ROM_PTR(&pin_GPIO23) }, - { 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_D26), MP_ROM_PTR(&pin_GPIO26) }, - { MP_ROM_QSTR(MP_QSTR_D27), MP_ROM_PTR(&pin_GPIO27) }, - - { 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/broadcom/broadcom_peripherals_config.h b/ports/broadcom/broadcom_peripherals_config.h deleted file mode 100644 index 64d35affea3..00000000000 --- a/ports/broadcom/broadcom_peripherals_config.h +++ /dev/null @@ -1,14 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#pragma once - -#include "py/obj.h" - -extern const mp_obj_type_t mcu_pin_type; - -#define PIN_PREFIX_VALUES { &mcu_pin_type }, -#define PIN_PREFIX_FIELDS mp_obj_base_t base; diff --git a/ports/broadcom/common-hal/board/__init__.c b/ports/broadcom/common-hal/board/__init__.c deleted file mode 100644 index bbb34aa3454..00000000000 --- a/ports/broadcom/common-hal/board/__init__.c +++ /dev/null @@ -1,14 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include - -#include "py/runtime.h" -#include "py/mphal.h" -#include "common-hal/microcontroller/Pin.h" - -// Pins aren't actually defined here. They are in the board specific directory -// such as boards/arduino_zero/pins.c. diff --git a/ports/broadcom/common-hal/busio/I2C.c b/ports/broadcom/common-hal/busio/I2C.c deleted file mode 100644 index 6a77cec08af..00000000000 --- a/ports/broadcom/common-hal/busio/I2C.c +++ /dev/null @@ -1,260 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#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 "shared-bindings/microcontroller/Pin.h" - -#include "peripherals/broadcom/cpu.h" -#include "peripherals/broadcom/vcmailbox.h" - -#if BCM_VERSION == 2711 -#define NUM_I2C (8) -static BSC0_Type *i2c[NUM_I2C] = {BSC0, BSC1, NULL, BSC3, BSC4, BSC5, BSC6, NULL}; -#else -#define NUM_I2C (3) -static BSC0_Type *i2c[NUM_I2C] = {BSC0, BSC1, NULL}; -#endif - -static bool never_reset_i2c[NUM_I2C]; -static bool i2c_in_use[NUM_I2C]; - -void reset_i2c(void) { - // BSC2 is dedicated to the first HDMI output. - never_reset_i2c[2] = true; - i2c_in_use[2] = true; - #if BCM_VERSION == 2711 - // BSC7 is dedicated to the second HDMI output. - never_reset_i2c[7] = true; - i2c_in_use[7] = true; - #endif - for (size_t i = 0; i < NUM_I2C; i++) { - if (never_reset_i2c[i]) { - continue; - } - i2c_in_use[i] = false; - i2c[i]->C_b.I2CEN = false; - COMPLETE_MEMORY_READS; - } -} - -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) { - - // Ensure the object starts in its deinit state. - common_hal_busio_i2c_mark_deinit(self); - - size_t instance_index = NUM_I2C; - uint8_t scl_alt = 0; - uint8_t sda_alt = 0; - - for (scl_alt = 0; scl_alt < 6; scl_alt++) { - if (scl->functions[scl_alt].type != PIN_FUNCTION_I2C || - i2c_in_use[scl->functions[scl_alt].index] || - scl->functions[scl_alt].function != I2C_FUNCTION_SCL) { - continue; - } - for (sda_alt = 0; sda_alt < 6; sda_alt++) { - if (sda->functions[sda_alt].type != PIN_FUNCTION_I2C || - scl->functions[scl_alt].index != sda->functions[sda_alt].index || - sda->functions[sda_alt].function != I2C_FUNCTION_SDA) { - continue; - } - instance_index = scl->functions[scl_alt].index; - break; - } - if (instance_index != NUM_I2C) { - break; - } - } - if (instance_index == NUM_I2C) { - raise_ValueError_invalid_pins(); - } - i2c_in_use[instance_index] = true; - self->index = instance_index; - self->peripheral = i2c[self->index]; - self->sda_pin = sda; - self->scl_pin = scl; - - uint32_t source_clock = vcmailbox_get_clock_rate(VCMAILBOX_CLOCK_CORE); - uint16_t clock_divider = source_clock / frequency; - self->peripheral->DIV_b.CDIV = clock_divider; - - gpio_set_function(sda->number, FSEL_VALUES[sda_alt]); - gpio_set_function(scl->number, FSEL_VALUES[scl_alt]); -} - -bool common_hal_busio_i2c_deinited(busio_i2c_obj_t *self) { - return self->sda_pin == NULL; -} - -void common_hal_busio_i2c_mark_deinit(busio_i2c_obj_t *self) { - self->sda_pin = NULL; -} - -void common_hal_busio_i2c_deinit(busio_i2c_obj_t *self) { - if (common_hal_busio_i2c_deinited(self)) { - return; - } - i2c_in_use[self->index] = false; - - common_hal_reset_pin(self->sda_pin); - common_hal_reset_pin(self->scl_pin); - common_hal_busio_i2c_mark_deinit(self); -} - -bool common_hal_busio_i2c_probe(busio_i2c_obj_t *self, uint8_t addr) { - uint8_t result = common_hal_busio_i2c_write(self, addr, NULL, 0); - return result == 0; -} - -bool common_hal_busio_i2c_try_lock(busio_i2c_obj_t *self) { - if (common_hal_busio_i2c_deinited(self)) { - return false; - } - bool grabbed_lock = false; - if (!self->has_lock) { - grabbed_lock = true; - self->has_lock = true; - } - return grabbed_lock; -} - -bool common_hal_busio_i2c_has_lock(busio_i2c_obj_t *self) { - return self->has_lock; -} - -void common_hal_busio_i2c_unlock(busio_i2c_obj_t *self) { - self->has_lock = false; -} - -// Discussion of I2C implementation is here: https://github.com/raspberrypi/linux/issues/254 - -static 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) { - COMPLETE_MEMORY_READS; - self->peripheral->S_b.DONE = true; - self->peripheral->A_b.ADDR = addr; - size_t loop_len = len; - // Prevent the stop bit by transmitting everything but the last byte. Doing - // so is left up to the subsequent read. - if (!transmit_stop_bit) { - loop_len -= 1; - } - self->peripheral->DLEN_b.DLEN = len; - self->peripheral->C = BSC0_C_ST_Msk | BSC0_C_I2CEN_Msk; - // Wait for the transaction to start. - while (self->peripheral->S_b.TA == 0) { - RUN_BACKGROUND_TASKS; - } - for (size_t i = 0; i < loop_len; i++) { - if (self->peripheral->S_b.ERR) { - break; - } - self->peripheral->FIFO_b.DATA = data[i]; - // Wait for the FIFO to empty enough that we can write more data. - while (self->peripheral->S_b.TXE == 0) { - RUN_BACKGROUND_TASKS; - } - } - // Wait for the FIFO to empty completely, not DONE, because we may not complete the - // transaction with a write. - while (self->peripheral->S_b.ERR == 0 && - ((!transmit_stop_bit && self->peripheral->S_b.TXE == 0) || - (transmit_stop_bit && self->peripheral->S_b.TA == 1))) { - RUN_BACKGROUND_TASKS; - } - self->finish_write = false; - if (self->peripheral->S_b.ERR) { - // Wait for the transfer to finish. - while (self->peripheral->S_b.TA == 1) { - RUN_BACKGROUND_TASKS; - } - // Clear the flag by writing it and wait for it to clear. - self->peripheral->S_b.ERR = true; - while (self->peripheral->S_b.ERR == 1) { - RUN_BACKGROUND_TASKS; - } - return MP_ENODEV; - } - - if (loop_len < len) { - self->finish_write = true; - self->last_write_data = data[len - 1]; - } - return 0; -} - -uint8_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, - const uint8_t *data, size_t len) { - return _common_hal_busio_i2c_write(self, addr, data, len, true); -} - -uint8_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t addr, - uint8_t *data, size_t len) { - COMPLETE_MEMORY_READS; - self->peripheral->A_b.ADDR = addr; - if (self->finish_write) { - self->finish_write = false; - if (self->peripheral->S_b.ERR == 1) { - return MP_ENODEV; - } - self->peripheral->FIFO_b.DATA = self->last_write_data; - } else { - self->peripheral->S_b.DONE = true; - } - self->peripheral->DLEN_b.DLEN = len; - self->peripheral->C = BSC0_C_READ_Msk | BSC0_C_ST_Msk | BSC0_C_I2CEN_Msk; - // Wait for the transaction to start. - while (self->peripheral->S_b.TA == 0) { - RUN_BACKGROUND_TASKS; - } - for (size_t i = 0; i < len; i++) { - if (self->peripheral->S_b.ERR) { - break; - } - // Wait for the FIFO to have enough data that we can read it. RXR is low - // once the transaction is done so we check the done bit too. - while (!self->peripheral->S_b.RXR && !self->peripheral->S_b.DONE) { - RUN_BACKGROUND_TASKS; - } - data[i] = self->peripheral->FIFO_b.DATA; - } - // Wait for the transaction to finish. - while (!self->peripheral->S_b.DONE && !self->peripheral->S_b.ERR) { - RUN_BACKGROUND_TASKS; - } - if (self->peripheral->S_b.ERR) { - self->peripheral->S_b.ERR = true; - while (self->peripheral->S_b.ERR == 1) { - RUN_BACKGROUND_TASKS; - } - return MP_ENODEV; - } - - return 0; -} - -uint8_t common_hal_busio_i2c_write_read(busio_i2c_obj_t *self, uint16_t addr, - uint8_t *out_data, size_t out_len, uint8_t *in_data, size_t in_len) { - uint8_t result = _common_hal_busio_i2c_write(self, addr, out_data, out_len, false); - if (result != 0) { - return result; - } - - return common_hal_busio_i2c_read(self, addr, in_data, in_len); -} - -void common_hal_busio_i2c_never_reset(busio_i2c_obj_t *self) { - never_reset_i2c[self->index] = true; - - common_hal_never_reset_pin(self->scl_pin); - common_hal_never_reset_pin(self->sda_pin); -} diff --git a/ports/broadcom/common-hal/busio/I2C.h b/ports/broadcom/common-hal/busio/I2C.h deleted file mode 100644 index 11416c0203f..00000000000 --- a/ports/broadcom/common-hal/busio/I2C.h +++ /dev/null @@ -1,27 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#pragma once - -#include "common-hal/microcontroller/Pin.h" - -#include "py/obj.h" - -#include "peripherals/broadcom/defines.h" -#include "peripherals/broadcom/gpio.h" - -typedef struct { - mp_obj_base_t base; - const mcu_pin_obj_t *scl_pin; - const mcu_pin_obj_t *sda_pin; - BSC0_Type *peripheral; - uint8_t index; - bool has_lock; - bool finish_write; - uint8_t last_write_data; -} busio_i2c_obj_t; - -void reset_i2c(void); diff --git a/ports/broadcom/common-hal/busio/SPI.c b/ports/broadcom/common-hal/busio/SPI.c deleted file mode 100644 index 2396a9b921e..00000000000 --- a/ports/broadcom/common-hal/busio/SPI.c +++ /dev/null @@ -1,331 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "shared-bindings/busio/SPI.h" - -#include "shared/runtime/interrupt_char.h" -#include "py/mperrno.h" -#include "py/runtime.h" - -#include "supervisor/board.h" -#include "common-hal/microcontroller/Pin.h" -#include "shared-bindings/microcontroller/Pin.h" - -#include "peripherals/broadcom/cpu.h" -#include "peripherals/broadcom/defines.h" -#include "peripherals/broadcom/gpio.h" -#include "peripherals/broadcom/pins.h" -#include "peripherals/broadcom/vcmailbox.h" - -#if BCM_VERSION == 2711 -#define NUM_SPI (7) -static SPI0_Type *spi[NUM_SPI] = {SPI0, NULL, NULL, SPI3, SPI4, SPI5, SPI6}; -static SPI1_Type *aux_spi[NUM_SPI] = {NULL, SPI1, SPI2, NULL, NULL, NULL, NULL}; -#else -#define NUM_SPI (3) -static SPI0_Type *spi[NUM_SPI] = {SPI0, NULL, NULL}; -static SPI1_Type *aux_spi[NUM_SPI] = {NULL, SPI1, SPI2}; -#endif - -static bool never_reset_spi[NUM_SPI]; -static bool spi_in_use[NUM_SPI]; - -void reset_spi(void) { - for (size_t i = 0; i < NUM_SPI; i++) { - if (never_reset_spi[i]) { - continue; - } - - if (i == 1 || i == 2) { - if (i == 1) { - AUX->ENABLES_b.SPI_1 = false; - } else { - AUX->ENABLES_b.SPI_2 = false; - } - aux_spi[i]->CNTL0 = 0; - } else { - // Set CS back to default. All 0 except read enable. - spi[i]->CS = SPI0_CS_REN_Msk; - } - - spi_in_use[i] = false; - } -} - -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, bool half_duplex) { - size_t instance_index = NUM_SPI; - BP_Function_Enum clock_alt = 0; - BP_Function_Enum mosi_alt = 0; - BP_Function_Enum miso_alt = 0; - - if (half_duplex) { - mp_raise_NotImplementedError(MP_ERROR_TEXT("Half duplex SPI is not implemented")); - } - - // BCM_VERSION != 2711 have 3 SPI but as listed in peripherals/gen/pins.c two are on - // index 0, once one index 0 SPI is found the other will throw an invalid_pins error. - for (size_t i = 0; i < NUM_SPI; i++) { - if (spi_in_use[i]) { - continue; - } - if (!pin_find_alt(clock, PIN_FUNCTION_SPI, i, SPI_FUNCTION_SCLK, &clock_alt)) { - continue; - } - if (mosi != NULL && !pin_find_alt(mosi, PIN_FUNCTION_SPI, i, SPI_FUNCTION_MOSI, &mosi_alt)) { - continue; - } - if (miso != NULL && !pin_find_alt(miso, PIN_FUNCTION_SPI, i, SPI_FUNCTION_MISO, &miso_alt)) { - continue; - } - instance_index = i; - break; - } - if (instance_index == NUM_SPI) { - raise_ValueError_invalid_pins(); - } - - self->clock = clock; - self->MOSI = mosi; - self->MISO = miso; - self->index = instance_index; - spi_in_use[instance_index] = true; - - - if (instance_index == 1) { - AUX->ENABLES_b.SPI_1 = true; - } else if (instance_index == 2) { - AUX->ENABLES_b.SPI_2 = true; - } - - common_hal_busio_spi_configure(self, 250000, 0, 0, 8); - - COMPLETE_MEMORY_READS; - gpio_set_pull(clock->number, BP_PULL_NONE); - gpio_set_function(clock->number, clock_alt); - if (mosi != NULL) { - gpio_set_pull(mosi->number, BP_PULL_NONE); - gpio_set_function(mosi->number, mosi_alt); - } - if (miso != NULL) { - gpio_set_pull(miso->number, BP_PULL_NONE); - gpio_set_function(miso->number, miso_alt); - } -} - -void common_hal_busio_spi_never_reset(busio_spi_obj_t *self) { - never_reset_spi[self->index] = true; - - common_hal_never_reset_pin(self->clock); - common_hal_never_reset_pin(self->MOSI); - common_hal_never_reset_pin(self->MISO); -} - -bool common_hal_busio_spi_deinited(busio_spi_obj_t *self) { - return self->clock == NULL; -} - -void common_hal_busio_spi_deinit(busio_spi_obj_t *self) { - if (common_hal_busio_spi_deinited(self)) { - return; - } - never_reset_spi[self->index] = false; - - common_hal_reset_pin(self->clock); - common_hal_reset_pin(self->MOSI); - common_hal_reset_pin(self->MISO); - self->clock = NULL; - spi_in_use[self->index] = false; - - if (self->index == 1 || - self->index == 2) { - aux_spi[self->index]->CNTL0_b.ENABLE = false; - if (self->index == 1) { - AUX->ENABLES_b.SPI_1 = false; - } else if (self->index == 2) { - AUX->ENABLES_b.SPI_2 = false; - } - } -} - -bool common_hal_busio_spi_configure(busio_spi_obj_t *self, - uint32_t baudrate, uint8_t polarity, uint8_t phase, uint8_t bits) { - if (baudrate == self->target_frequency && - polarity == self->polarity && - phase == self->phase && - bits == self->bits) { - return true; - } - - if (self->index == 1 || self->index == 2) { - SPI1_Type *p = aux_spi[self->index]; - uint32_t source_clock = vcmailbox_get_clock_rate(VCMAILBOX_CLOCK_CORE); - uint16_t clock_divider = source_clock / baudrate; - if (source_clock % baudrate > 0) { - clock_divider += 2; - } - - p->CNTL0 = (clock_divider / 2 - 1) << SPI1_CNTL0_SPEED_Pos | - SPI1_CNTL0_ENABLE_Msk | - SPI1_CNTL0_MSB_FIRST_Msk | - (polarity == 1? SPI1_CNTL0_INVERT_CLK_Msk : 0) | - (phase == polarity? SPI1_CNTL0_IN_RISING_Msk : SPI1_CNTL0_OUT_RISING_Msk) | - 8 << SPI1_CNTL0_SHIFT_LENGTH_Pos; - p->CNTL1 = SPI1_CNTL1_MSB_FIRST_Msk; - self->real_frequency = source_clock / clock_divider; - } else { - SPI0_Type *p = spi[self->index]; - p->CS = polarity << SPI0_CS_CPOL_Pos | - phase << SPI0_CS_CPHA_Pos; - uint32_t source_clock = vcmailbox_get_clock_rate(VCMAILBOX_CLOCK_CORE); - uint16_t clock_divider = source_clock / baudrate; - if (source_clock % baudrate > 0) { - clock_divider += 2; - } - - p->CLK = clock_divider; - self->real_frequency = source_clock / clock_divider; - } - - self->polarity = polarity; - self->phase = phase; - self->bits = bits; - self->target_frequency = baudrate; - - return true; -} - -bool common_hal_busio_spi_try_lock(busio_spi_obj_t *self) { - if (common_hal_busio_spi_deinited(self)) { - return false; - } - bool grabbed_lock = false; - if (!self->has_lock) { - grabbed_lock = true; - self->has_lock = true; - } - return grabbed_lock; -} - -bool common_hal_busio_spi_has_lock(busio_spi_obj_t *self) { - return self->has_lock; -} - -void common_hal_busio_spi_unlock(busio_spi_obj_t *self) { - self->has_lock = false; -} - -static void _spi_transfer(SPI0_Type *p, - const uint8_t *data_out, size_t out_len, - uint8_t *data_in, size_t in_len) { - size_t len = MAX(out_len, in_len); - COMPLETE_MEMORY_READS; - p->DLEN = len; - p->CS |= SPI0_CS_TA_Msk | SPI0_CS_CLEAR_Msk; - size_t in = 0; - size_t out = 0; - while (in < len) { - while (out < len && p->CS_b.TXD == 1) { - if (out_len == 1) { - p->FIFO = data_out[0]; - } else { - p->FIFO = data_out[out]; - } - out++; - } - // Wait for data to read (also means data has been sent.) - while (p->CS_b.RXD == 0) { - RUN_BACKGROUND_TASKS; - } - while (p->CS_b.RXD == 1) { - uint8_t data = p->FIFO; - if (data_in != NULL) { - data_in[in] = data; - } else { - (void)data; - } - in++; - } - } - p->CS_b.TA = false; - COMPLETE_MEMORY_READS; -} - -static void _aux_spi_transfer(SPI1_Type *p, - const uint8_t *data_out, size_t out_len, - uint8_t *data_in, size_t in_len) { - size_t len = MAX(out_len, in_len); - p->CNTL0 |= SPI1_CNTL0_CLEAR_FIFOS_Msk; - p->CNTL0 &= ~SPI1_CNTL0_CLEAR_FIFOS_Msk; - size_t in = 0; - size_t out = 0; - while (in < len) { - while (out < len && p->STAT_b.TX_FULL == 0) { - if (out_len == 1) { - p->TXHOLD0 = data_out[0] << 24; - } else { - p->TXHOLD0 = data_out[out] << 24; - } - out++; - } - // Wait for data to read (also means data has been sent.) - while (p->STAT_b.RX_EMPTY == 1) { - RUN_BACKGROUND_TASKS; - } - while (p->STAT_b.RX_EMPTY == 0) { - uint8_t data = p->TXHOLD0; - if (data_in != NULL) { - data_in[in] = data; - } else { - (void)data; - } - in++; - } - } -} - -bool common_hal_busio_spi_write(busio_spi_obj_t *self, - const uint8_t *data, size_t len) { - if (self->index == 1 || self->index == 2) { - _aux_spi_transfer(aux_spi[self->index], data, len, NULL, 0); - } else { - _spi_transfer(spi[self->index], data, len, NULL, 0); - } - return true; -} - -bool common_hal_busio_spi_read(busio_spi_obj_t *self, - uint8_t *data, size_t len, uint8_t write_value) { - if (self->index == 1 || self->index == 2) { - _aux_spi_transfer(aux_spi[self->index], &write_value, 1, data, len); - } else { - _spi_transfer(spi[self->index], &write_value, 1, data, len); - } - return true; -} - -bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, - const uint8_t *data_out, uint8_t *data_in, size_t len) { - if (self->index == 1 || self->index == 2) { - _aux_spi_transfer(aux_spi[self->index], data_out, len, data_in, len); - } else { - _spi_transfer(spi[self->index], data_out, len, data_in, len); - } - return true; -} - -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) { - return self->phase; -} - -uint8_t common_hal_busio_spi_get_polarity(busio_spi_obj_t *self) { - return self->polarity; -} diff --git a/ports/broadcom/common-hal/busio/SPI.h b/ports/broadcom/common-hal/busio/SPI.h deleted file mode 100644 index aec91263677..00000000000 --- a/ports/broadcom/common-hal/busio/SPI.h +++ /dev/null @@ -1,27 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#pragma once - -#include "common-hal/microcontroller/Pin.h" - -#include "py/obj.h" - -typedef struct { - mp_obj_base_t base; - bool has_lock; - 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; - uint8_t phase; - uint8_t bits; - uint8_t index; -} busio_spi_obj_t; - -void reset_spi(void); diff --git a/ports/broadcom/common-hal/busio/UART.c b/ports/broadcom/common-hal/busio/UART.c deleted file mode 100644 index 55c890475eb..00000000000 --- a/ports/broadcom/common-hal/busio/UART.c +++ /dev/null @@ -1,489 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 microDev -// -// SPDX-License-Identifier: MIT - -#include "shared-bindings/busio/UART.h" - -#include "py/stream.h" -#include "py/mperrno.h" -#include "py/runtime.h" -#include "supervisor/shared/tick.h" -#include "shared/runtime/interrupt_char.h" -#include "shared-bindings/microcontroller/Pin.h" - -#include "peripherals/broadcom/cpu.h" -#include "peripherals/broadcom/defines.h" -#include "peripherals/broadcom/gpio.h" -#include "peripherals/broadcom/interrupts.h" -#include "peripherals/broadcom/vcmailbox.h" - -#define NO_PIN 0xff - -// UART1 is a different peripheral than the rest so it is hardcoded below. -#if BCM_VERSION == 2711 -#define NUM_UART (6) -static ARM_UART_PL011_Type *uart[NUM_UART] = {UART0, NULL, UART2, UART3, UART4, UART5}; -#else -#define NUM_UART (2) -static ARM_UART_PL011_Type *uart[NUM_UART] = {UART0, NULL}; -#endif - -typedef enum { - STATUS_FREE = 0, - STATUS_BUSY, - STATUS_NEVER_RESET -} uart_status_t; - -static uart_status_t uart_status[NUM_UART]; -static busio_uart_obj_t *active_uart[NUM_UART]; - -void reset_uart(void) { - bool any_pl011_active = false; - for (uint8_t num = 0; num < NUM_UART; num++) { - if (uart_status[num] == STATUS_BUSY) { - if (num == 1) { - UART1->IER_b.DATA_READY = false; - UART1->CNTL = 0; - COMPLETE_MEMORY_READS; - AUX->ENABLES_b.UART_1 = false; - } else { - ARM_UART_PL011_Type *pl011 = uart[num]; - pl011->CR = 0; - } - active_uart[num] = NULL; - uart_status[num] = STATUS_FREE; - } else { - any_pl011_active = any_pl011_active || (num != 1 && uart_status[num] == STATUS_NEVER_RESET); - } - } - if (!any_pl011_active) { - BP_DisableIRQ(UART_IRQn); - } - COMPLETE_MEMORY_READS; - if (AUX->ENABLES == 0) { - BP_DisableIRQ(AUX_IRQn); - } -} - -static void fetch_all_from_fifo(busio_uart_obj_t *self) { - if (self->uart_id == 1) { - while (UART1->STAT_b.DATA_READY && ringbuf_num_empty(&self->ringbuf) > 0) { - int c = UART1->IO_b.DATA; - if (self->sigint_enabled && c == mp_interrupt_char) { - mp_sched_keyboard_interrupt(); - continue; - } - ringbuf_put(&self->ringbuf, c); - } - } else { - ARM_UART_PL011_Type *pl011 = uart[self->uart_id]; - while (!pl011->FR_b.RXFE && ringbuf_num_empty(&self->ringbuf) > 0) { - int c = pl011->DR_b.DATA; - if (self->sigint_enabled && c == mp_interrupt_char) { - mp_sched_keyboard_interrupt(); - continue; - } - ringbuf_put(&self->ringbuf, c); - } - } -} - -void UART1_IRQHandler(void) { - fetch_all_from_fifo(active_uart[1]); - // We couldn't read all pending data (overrun) so clear the FIFO so that the interrupt - // can finish. - if (UART1->STAT_b.DATA_READY) { - UART1->IIR_b.DATA_READY = 1; - } -} - -void pl011_IRQHandler(uint8_t index) { - fetch_all_from_fifo(active_uart[index]); - // Clear the interrupt in case we weren't able to clear it by emptying the - // FIFO. (This won't clear the FIFO.) - ARM_UART_PL011_Type *pl011 = uart[index]; - pl011->ICR = ARM_UART_PL011_ICR_RXIC_Msk; -} - -void UART0_IRQHandler(void) { - pl011_IRQHandler(0); -} - -#if BCM_VERSION == 2711 -void UART2_IRQHandler(void) { - pl011_IRQHandler(2); -} -void UART3_IRQHandler(void) { - pl011_IRQHandler(3); -} -void UART4_IRQHandler(void) { - pl011_IRQHandler(4); -} -void UART5_IRQHandler(void) { - pl011_IRQHandler(5); -} -#endif - -void common_hal_busio_uart_never_reset(busio_uart_obj_t *self) { - uart_status[self->uart_id] = STATUS_NEVER_RESET; - common_hal_never_reset_pin(self->tx_pin); - common_hal_never_reset_pin(self->rx_pin); - common_hal_never_reset_pin(self->cts_pin); - common_hal_never_reset_pin(self->rts_pin); -} - -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) { - - mp_arg_validate_int_max(bits, 8, MP_QSTR_bits); - mp_arg_validate_int_min(receiver_buffer_size, 1, MP_QSTR_receiver_buffer_size); - - if ((rs485_dir != NULL) || (rs485_invert)) { - mp_raise_NotImplementedError(MP_ERROR_TEXT("RS485 Not yet supported on this device")); - } - - size_t instance_index = NUM_UART; - BP_Function_Enum tx_alt = 0; - BP_Function_Enum rx_alt = 0; - BP_Function_Enum rts_alt = 0; - BP_Function_Enum cts_alt = 0; - for (size_t i = 0; i < NUM_UART; i++) { - if (uart_status[i] != STATUS_FREE) { - continue; - } - if (tx != NULL) { - if (!pin_find_alt(tx, PIN_FUNCTION_UART, i, UART_FUNCTION_TXD, &tx_alt)) { - continue; - } - if (rts != NULL && !pin_find_alt(rts, PIN_FUNCTION_UART, i, UART_FUNCTION_RTS, &rts_alt)) { - continue; - } - } - if (rx != NULL) { - if (!pin_find_alt(rx, PIN_FUNCTION_UART, i, UART_FUNCTION_RXD, &rx_alt)) { - continue; - } - if (cts != NULL && !pin_find_alt(cts, PIN_FUNCTION_UART, i, UART_FUNCTION_CTS, &cts_alt)) { - continue; - } - } - instance_index = i; - break; - } - if (instance_index == NUM_UART) { - raise_ValueError_invalid_pins(); - } - - self->rx_pin = rx; - self->tx_pin = tx; - self->rts_pin = rts; - self->cts_pin = cts; - self->sigint_enabled = sigint_enabled; - - if (rx != NULL) { - // Use the provided buffer when given. - if (receiver_buffer != NULL) { - ringbuf_init(&self->ringbuf, receiver_buffer, receiver_buffer_size); - } else { - if (!ringbuf_alloc(&self->ringbuf, receiver_buffer_size)) { - m_malloc_fail(receiver_buffer_size); - } - } - } - - active_uart[self->uart_id] = self; - - ARM_UART_PL011_Type *pl011 = uart[self->uart_id]; - - if (self->uart_id == 1) { - AUX->ENABLES_b.UART_1 = true; - - UART1->IER = 0; - UART1->CNTL = 0; - if (bits == 8) { - UART1->LCR_b.DATA_SIZE = UART1_LCR_DATA_SIZE_MODE_8BIT; - } else if (bits == 7) { - UART1->LCR_b.DATA_SIZE = UART1_LCR_DATA_SIZE_MODE_7BIT; - } - UART1->MCR = 0; - UART1->IER = 0; - - // Clear interrupts - UART1->IIR = 0xff; - common_hal_busio_uart_set_baudrate(self, baudrate); - if (tx != NULL) { - UART1->CNTL |= UART1_CNTL_TX_ENABLE_Msk; - } - if (rx != NULL) { - UART1->CNTL |= UART1_CNTL_RX_ENABLE_Msk; - } - } else { - // Ensure the UART is disabled as we configure it. - pl011->CR_b.UARTEN = false; - pl011->IMSC = 0; - pl011->ICR = 0x3ff; - - common_hal_busio_uart_set_baudrate(self, baudrate); - - uint32_t line_control = ARM_UART_PL011_LCR_H_FEN_Msk; - line_control |= (bits - 5) << ARM_UART_PL011_LCR_H_WLEN_Pos; - if (stop == 2) { - line_control |= ARM_UART_PL011_LCR_H_STP2_Msk; - } - if (parity != BUSIO_UART_PARITY_NONE) { - line_control |= ARM_UART_PL011_LCR_H_PEN_Msk; - } - if (parity == BUSIO_UART_PARITY_EVEN) { - line_control |= ARM_UART_PL011_LCR_H_EPS_Msk; - } - pl011->LCR_H = line_control; - - uint32_t control = ARM_UART_PL011_CR_UARTEN_Msk; - if (tx != NULL) { - control |= ARM_UART_PL011_CR_TXE_Msk; - } - if (rx != NULL) { - control |= ARM_UART_PL011_CR_RXE_Msk; - } - if (cts != NULL) { - control |= ARM_UART_PL011_CR_CTSEN_Msk; - } - if (rts != NULL) { - control |= ARM_UART_PL011_CR_RTSEN_Msk; - } - pl011->CR = control; - } - - // Setup the pins after waiting for UART stuff - COMPLETE_MEMORY_READS; - if (tx != NULL) { - gpio_set_pull(tx->number, BP_PULL_NONE); - gpio_set_function(tx->number, tx_alt); - } - if (rx != NULL) { - gpio_set_pull(rx->number, BP_PULL_NONE); - gpio_set_function(rx->number, rx_alt); - } - if (rts != NULL) { - gpio_set_pull(rts->number, BP_PULL_NONE); - gpio_set_function(rts->number, rts_alt); - } - if (cts != NULL) { - gpio_set_pull(cts->number, BP_PULL_NONE); - gpio_set_function(cts->number, cts_alt); - } - - // Turn on interrupts - COMPLETE_MEMORY_READS; - if (self->uart_id == 1) { - UART1->IER_b.DATA_READY = true; - // Never disable this in case the SPIs are used. They can each be - // disabled at the peripheral itself. - BP_EnableIRQ(AUX_IRQn); - } else { - pl011->IMSC_b.RXIM = true; - // Never disable this in case the other PL011 UARTs are used. - BP_EnableIRQ(UART_IRQn); - } -} - -bool common_hal_busio_uart_deinited(busio_uart_obj_t *self) { - 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 (self->uart_id == 1) { - UART1->IER_b.DATA_READY = false; - UART1->CNTL = 0; - AUX->ENABLES_b.UART_1 = false; - } else { - ARM_UART_PL011_Type *pl011 = uart[self->uart_id]; - pl011->CR = 0; - } - active_uart[self->uart_id] = NULL; - ringbuf_deinit(&self->ringbuf); - uart_status[self->uart_id] = STATUS_FREE; - common_hal_reset_pin(self->tx_pin); - common_hal_reset_pin(self->rx_pin); - common_hal_reset_pin(self->cts_pin); - common_hal_reset_pin(self->rts_pin); - self->tx_pin = NULL; - self->rx_pin = NULL; - self->cts_pin = NULL; - self->rts_pin = NULL; -} - -// 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 == NULL) { - mp_raise_ValueError_varg(MP_ERROR_TEXT("No %q pin"), MP_QSTR_tx); - } - - COMPLETE_MEMORY_READS; - ARM_UART_PL011_Type *pl011 = uart[self->uart_id]; - for (size_t i = 0; i < len; i++) { - if (self->uart_id == 1) { - // Wait for the FIFO to have space. - while (!UART1->STAT_b.TX_READY) { - RUN_BACKGROUND_TASKS; - } - UART1->IO = data[i]; - } else { - while (pl011->FR_b.TXFF) { - RUN_BACKGROUND_TASKS; - } - pl011->DR_b.DATA = data[i]; - } - } - // Wait for the data to be shifted out - if (self->uart_id == 1) { - while (!UART1->STAT_b.TX_DONE) { - RUN_BACKGROUND_TASKS; - } - } else { - while (pl011->FR_b.BUSY) { - RUN_BACKGROUND_TASKS; - } - } - COMPLETE_MEMORY_READS; - return len; -} - -static void disable_interrupt(busio_uart_obj_t *self) { - if (self->uart_id == 1) { - UART1->IER_b.DATA_READY = false; - } -} - -static void enable_interrupt(busio_uart_obj_t *self) { - if (self->uart_id == 1) { - UART1->IER_b.DATA_READY = true; - } -} - -// Read characters. -size_t common_hal_busio_uart_read(busio_uart_obj_t *self, uint8_t *data, size_t len, int *errcode) { - if (self->rx_pin == NULL) { - mp_raise_ValueError_varg(MP_ERROR_TEXT("No %q pin"), MP_QSTR_rx); - } - - if (len == 0) { - // Nothing to read. - return 0; - } - COMPLETE_MEMORY_READS; - - // Prevent conflict with uart irq. - disable_interrupt(self); - - // 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)) { - fetch_all_from_fifo(self); - size_t additional_read = ringbuf_get_n(&self->ringbuf, data + total_read, len); - len -= additional_read; - total_read += additional_read; - if (additional_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; - } - } - } - - // 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. - fetch_all_from_fifo(self); - - // Re-enable irq. - enable_interrupt(self); - - COMPLETE_MEMORY_READS; - if (total_read == 0) { - *errcode = EAGAIN; - return MP_STREAM_ERROR; - } - - return total_read; -} - -uint32_t common_hal_busio_uart_get_baudrate(busio_uart_obj_t *self) { - return self->baudrate; -} - -void common_hal_busio_uart_set_baudrate(busio_uart_obj_t *self, uint32_t baudrate) { - if (self->uart_id == 1) { - uint32_t source_clock = vcmailbox_get_clock_rate(VCMAILBOX_CLOCK_CORE); - UART1->BAUD = ((source_clock / (baudrate * 8)) - 1); - } else { - ARM_UART_PL011_Type *pl011 = uart[self->uart_id]; - bool reenable = false; - if (pl011->CR_b.UARTEN) { - pl011->CR_b.UARTEN = false; - reenable = true; - } - uint32_t source_clock = vcmailbox_get_clock_rate_measured(VCMAILBOX_CLOCK_UART); - uint32_t divisor = 16 * baudrate; - pl011->IBRD = source_clock / divisor; - // The fractional divisor is 64ths. - uint32_t remainder = source_clock % divisor; - uint32_t per_tick = (divisor / 64) + 1; - uint32_t adjust = 0; - if (remainder % per_tick > 0) { - adjust = 1; - } - pl011->FBRD = remainder / per_tick + adjust; - if (reenable) { - pl011->CR_b.UARTEN = true; - } - } - self->baudrate = baudrate; -} - -mp_float_t common_hal_busio_uart_get_timeout(busio_uart_obj_t *self) { - return (mp_float_t)(self->timeout_ms / 1000.0L); -} - -void common_hal_busio_uart_set_timeout(busio_uart_obj_t *self, mp_float_t timeout) { - self->timeout_ms = timeout * 1000; -} - -uint32_t common_hal_busio_uart_rx_characters_available(busio_uart_obj_t *self) { - fetch_all_from_fifo(self); - return ringbuf_num_filled(&self->ringbuf); -} - -void common_hal_busio_uart_clear_rx_buffer(busio_uart_obj_t *self) { - ringbuf_clear(&self->ringbuf); -} - -bool common_hal_busio_uart_ready_to_tx(busio_uart_obj_t *self) { - if (self->tx_pin == NULL) { - return false; - } - if (self->uart_id == 1) { - return UART1->STAT_b.TX_READY; - } - return !uart[self->uart_id]->FR_b.TXFF; -} diff --git a/ports/broadcom/common-hal/busio/UART.h b/ports/broadcom/common-hal/busio/UART.h deleted file mode 100644 index 866e64c4855..00000000000 --- a/ports/broadcom/common-hal/busio/UART.h +++ /dev/null @@ -1,25 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 microDev -// -// SPDX-License-Identifier: MIT - -#pragma once - -#include "py/obj.h" -#include "py/ringbuf.h" - -typedef struct { - mp_obj_base_t base; - const mcu_pin_obj_t *tx_pin; - const mcu_pin_obj_t *rx_pin; - const mcu_pin_obj_t *cts_pin; - const mcu_pin_obj_t *rts_pin; - uint32_t baudrate; - uint32_t timeout_ms; - ringbuf_t ringbuf; - bool sigint_enabled; - uint8_t uart_id; -} busio_uart_obj_t; - -extern void reset_uart(void); diff --git a/ports/broadcom/common-hal/busio/__init__.c b/ports/broadcom/common-hal/busio/__init__.c deleted file mode 100644 index b726684324a..00000000000 --- a/ports/broadcom/common-hal/busio/__init__.c +++ /dev/null @@ -1,7 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2024 Adafruit Industries LLC -// -// SPDX-License-Identifier: MIT - -// No busio module functions. diff --git a/ports/broadcom/common-hal/digitalio/DigitalInOut.c b/ports/broadcom/common-hal/digitalio/DigitalInOut.c deleted file mode 100644 index b2b0aae404b..00000000000 --- a/ports/broadcom/common-hal/digitalio/DigitalInOut.c +++ /dev/null @@ -1,144 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include -#include - -#include "py/runtime.h" -#include "py/mphal.h" - -#include "common-hal/microcontroller/Pin.h" -#include "shared-bindings/digitalio/DigitalInOut.h" - -#include "peripherals/broadcom/gpio.h" - -digitalinout_result_t common_hal_digitalio_digitalinout_construct( - digitalio_digitalinout_obj_t *self, const mcu_pin_obj_t *pin) { - claim_pin(pin); - self->pin = pin; - self->output = false; - self->open_drain = false; - - return DIGITALINOUT_OK; -} - -void common_hal_digitalio_digitalinout_never_reset( - digitalio_digitalinout_obj_t *self) { - never_reset_pin_number(self->pin->number); -} - -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) { - if (common_hal_digitalio_digitalinout_deinited(self)) { - return; - } - reset_pin_number(self->pin->number); - self->pin = NULL; -} - -digitalinout_result_t common_hal_digitalio_digitalinout_switch_to_input( - 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); - return DIGITALINOUT_OK; -} - -digitalinout_result_t common_hal_digitalio_digitalinout_switch_to_output( - digitalio_digitalinout_obj_t *self, bool value, - digitalio_drive_mode_t drive_mode) { - const uint8_t pin = self->pin->number; - gpio_set_pull(pin, PULL_NONE); - - self->output = true; - 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) { - return self->output ? DIRECTION_OUTPUT : DIRECTION_INPUT; -} - -void common_hal_digitalio_digitalinout_set_value( - digitalio_digitalinout_obj_t *self, bool value) { - const uint8_t pin = self->pin->number; - if (self->open_drain && value) { - // If true and open-drain, set the direction -before- setting - // the pin value, to to avoid a high glitch on the pin before - // switching from output to input for open-drain. - gpio_set_function(pin, GPIO_FUNCTION_INPUT); - gpio_set_value(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_set_value(pin, value); - gpio_set_function(pin, GPIO_FUNCTION_OUTPUT); - } -} - -bool common_hal_digitalio_digitalinout_get_value( - digitalio_digitalinout_obj_t *self) { - return gpio_get_value(self->pin->number); -} - -digitalinout_result_t common_hal_digitalio_digitalinout_set_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; - // True is implemented differently between modes so reset the value to make - // sure it's correct for the new mode. - if (value) { - common_hal_digitalio_digitalinout_set_value(self, value); - } - return DIGITALINOUT_OK; -} - -digitalio_drive_mode_t common_hal_digitalio_digitalinout_get_drive_mode( - digitalio_digitalinout_obj_t *self) { - if (self->open_drain) { - return DRIVE_MODE_OPEN_DRAIN; - } else { - return DRIVE_MODE_PUSH_PULL; - } -} - -digitalinout_result_t common_hal_digitalio_digitalinout_set_pull( - digitalio_digitalinout_obj_t *self, digitalio_pull_t pull) { - const uint8_t pin = self->pin->number; - BP_PULL_Enum bp_pull = BP_PULL_NONE; - if (pull == PULL_UP) { - bp_pull = BP_PULL_UP; - } else if (pull == PULL_DOWN) { - bp_pull = BP_PULL_DOWN; - } - gpio_set_pull(pin, bp_pull); - return DIGITALINOUT_OK; -} - -digitalio_pull_t common_hal_digitalio_digitalinout_get_pull( - digitalio_digitalinout_obj_t *self) { - uint32_t pin = self->pin->number; - if (self->output) { - mp_raise_AttributeError(MP_ERROR_TEXT("Cannot get pull while in output mode")); - return PULL_NONE; - } else { - if (gpio_get_pull(pin) == BP_PULL_UP) { - return PULL_UP; - } else if (gpio_get_pull(pin) == BP_PULL_DOWN) { - return PULL_DOWN; - } - } - return PULL_NONE; -} diff --git a/ports/broadcom/common-hal/digitalio/DigitalInOut.h b/ports/broadcom/common-hal/digitalio/DigitalInOut.h deleted file mode 100644 index 69520a92bff..00000000000 --- a/ports/broadcom/common-hal/digitalio/DigitalInOut.h +++ /dev/null @@ -1,17 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#pragma once - -#include "common-hal/microcontroller/Pin.h" -#include "py/obj.h" - -typedef struct { - mp_obj_base_t base; - const mcu_pin_obj_t *pin; - bool output; - bool open_drain; -} digitalio_digitalinout_obj_t; diff --git a/ports/broadcom/common-hal/digitalio/__init__.c b/ports/broadcom/common-hal/digitalio/__init__.c deleted file mode 100644 index fa222ed01f0..00000000000 --- a/ports/broadcom/common-hal/digitalio/__init__.c +++ /dev/null @@ -1,7 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2024 Adafruit Industries LLC -// -// SPDX-License-Identifier: MIT - -// No digitalio module functions. diff --git a/ports/broadcom/common-hal/microcontroller/Pin.c b/ports/broadcom/common-hal/microcontroller/Pin.c deleted file mode 100644 index be5c0ff6210..00000000000 --- a/ports/broadcom/common-hal/microcontroller/Pin.c +++ /dev/null @@ -1,89 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "shared-bindings/microcontroller/Pin.h" - -#include "peripherals/broadcom/gpio.h" - -static bool pin_in_use[BCM_PIN_COUNT]; -static bool never_reset_pin[BCM_PIN_COUNT]; - -void reset_all_pins(void) { - for (size_t i = 0; i < BCM_PIN_COUNT; i++) { - if (never_reset_pin[i]) { - continue; - } - reset_pin_number(i); - } -} - -void never_reset_pin_number(uint8_t pin_number) { - never_reset_pin[pin_number] = true; -} - -void reset_pin_number(uint8_t pin_number) { - pin_in_use[pin_number] = false; - never_reset_pin[pin_number] = false; - // Reset JTAG pins back to JTAG. - BP_PULL_Enum pull = BP_PULL_NONE; - if (22 <= pin_number && pin_number <= 27) { - gpio_set_function(pin_number, GPIO_FUNCTION_ALT4); - } else { - gpio_set_function(pin_number, GPIO_FUNCTION_INPUT); - } - // Set the pull to match the datasheet. - if (pin_number < 9 || - (33 < pin_number && pin_number < 37) || - pin_number > 45) { - pull = BP_PULL_UP; - } else if (pin_number != 28 && - pin_number != 29 && - pin_number != 44 && - pin_number != 45) { - // Most pins are pulled low so we only exclude the four pins that aren't - // pulled at all. This will also set the JTAG pins 22-27 - pull = BP_PULL_DOWN; - } - gpio_set_pull(pin_number, pull); -} - -void common_hal_never_reset_pin(const mcu_pin_obj_t *pin) { - if (pin == NULL) { - return; - } - never_reset_pin_number(pin->number); -} - -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) { - pin_in_use[pin->number] = true; -} - -bool pin_number_is_free(uint8_t pin_number) { - return !pin_in_use[pin_number]; -} - -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) { - return pin->number; -} - -void common_hal_mcu_pin_claim(const mcu_pin_obj_t *pin) { - return claim_pin(pin); -} - -void common_hal_mcu_pin_reset_number(uint8_t pin_no) { - reset_pin_number(pin_no); -} diff --git a/ports/broadcom/common-hal/microcontroller/Pin.h b/ports/broadcom/common-hal/microcontroller/Pin.h deleted file mode 100644 index 4e0e2e2e659..00000000000 --- a/ports/broadcom/common-hal/microcontroller/Pin.h +++ /dev/null @@ -1,22 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#pragma once - -#include -#include - -#include - -#include "peripherals/broadcom/pins.h" - -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_number); -void never_reset_pin_number(uint8_t pin_number); -void claim_pin(const mcu_pin_obj_t *pin); -bool pin_number_is_free(uint8_t pin_number); diff --git a/ports/broadcom/common-hal/microcontroller/Processor.c b/ports/broadcom/common-hal/microcontroller/Processor.c deleted file mode 100644 index 4956604f9b6..00000000000 --- a/ports/broadcom/common-hal/microcontroller/Processor.c +++ /dev/null @@ -1,35 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "shared-bindings/microcontroller/Processor.h" - -#include - -#include "peripherals/broadcom/vcmailbox.h" - -float common_hal_mcu_processor_get_temperature(void) { - uint32_t temp = vcmailbox_get_temperature(); - return temp / 1000.0f; -} - -float common_hal_mcu_processor_get_voltage(void) { - return NAN; -} - -uint32_t common_hal_mcu_processor_get_frequency(void) { - return vcmailbox_get_clock_rate_measured(VCMAILBOX_CLOCK_ARM); -} - -void common_hal_mcu_processor_get_uid(uint8_t raw_id[]) { - uint64_t serial = vcmailbox_get_serial_number(); - for (size_t i = 0; i < sizeof(uint64_t); i++) { - raw_id[i] = (serial >> (64 - ((i + 1) * 8))) & 0xff; - } -} - -mcu_reset_reason_t common_hal_mcu_processor_get_reset_reason(void) { - return RESET_REASON_UNKNOWN; -} diff --git a/ports/broadcom/common-hal/microcontroller/Processor.h b/ports/broadcom/common-hal/microcontroller/Processor.h deleted file mode 100644 index 0c9088f1881..00000000000 --- a/ports/broadcom/common-hal/microcontroller/Processor.h +++ /dev/null @@ -1,16 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#pragma once - -#include "py/obj.h" - -typedef struct { - mp_obj_base_t base; - // Stores no state currently. -} mcu_processor_obj_t; - -#define COMMON_HAL_MCU_PROCESSOR_UID_LENGTH 8 diff --git a/ports/broadcom/common-hal/microcontroller/__init__.c b/ports/broadcom/common-hal/microcontroller/__init__.c deleted file mode 100644 index b0ed1fcb9ec..00000000000 --- a/ports/broadcom/common-hal/microcontroller/__init__.c +++ /dev/null @@ -1,178 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "shared-bindings/microcontroller/__init__.h" - -#include "shared-bindings/microcontroller/Pin.h" -#include "shared-bindings/microcontroller/Processor.h" -#include "common-hal/microcontroller/__init__.h" -#include "peripherals/broadcom/defines.h" -#include "peripherals/broadcom/interrupts.h" - -#include "mphalport.h" - -void common_hal_mcu_delay_us(uint32_t delay) { - mp_hal_delay_us(delay); -} - -volatile uint32_t nesting_count = 0; -void common_hal_mcu_disable_interrupts(void) { - BP_DisableIRQs(); - nesting_count++; -} - -void common_hal_mcu_enable_interrupts(void) { - if (nesting_count == 0) { - // reset_into_safe_mode(SAFE_MODE_INTERRUPT_ERROR); - } - nesting_count--; - if (nesting_count > 0) { - return; - } - BP_EnableIRQs(); -} - -void common_hal_mcu_on_next_reset(mcu_runmode_t runmode) { -} - -void common_hal_mcu_reset(void) { -} - -// The singleton microcontroller.Processor object, bound to microcontroller.cpu -// It currently only has properties, and no state. -#if CIRCUITPY_PROCESSOR_COUNT > 1 -static const mcu_processor_obj_t processor0 = { - .base = { - .type = &mcu_processor_type, - }, -}; - -static const mcu_processor_obj_t processor1 = { - .base = { - .type = &mcu_processor_type, - }, -}; - -static const mcu_processor_obj_t processor2 = { - .base = { - .type = &mcu_processor_type, - }, -}; - -static const mcu_processor_obj_t processor3 = { - .base = { - .type = &mcu_processor_type, - }, -}; - -const mp_rom_obj_tuple_t common_hal_multi_processor_obj = { - {&mp_type_tuple}, - CIRCUITPY_PROCESSOR_COUNT, - { - MP_ROM_PTR(&processor0), - MP_ROM_PTR(&processor1), - MP_ROM_PTR(&processor2), - MP_ROM_PTR(&processor3) - } -}; -#endif - -const mcu_processor_obj_t common_hal_mcu_processor_obj = { - .base = { - .type = &mcu_processor_type, - }, -}; - -#if CIRCUITPY_NVM && CIRCUITPY_INTERNAL_NVM_SIZE > 0 -// The singleton nvm.ByteArray object. -const nvm_bytearray_obj_t common_hal_mcu_nvm_obj = { - .base = { - .type = &nvm_bytearray_type, - }, - .len = CIRCUITPY_INTERNAL_NVM_SIZE, - .start_address = (uint8_t *)(CIRCUITPY_INTERNAL_NVM_START_ADDR) -}; -#endif - -#if CIRCUITPY_WATCHDOG -// The singleton watchdog.WatchDogTimer object. -watchdog_watchdogtimer_obj_t common_hal_mcu_watchdogtimer_obj = { - .base = { - .type = &watchdog_watchdogtimer_type, - }, - .timeout = 0.0f, - .mode = WATCHDOGMODE_NONE, -}; -#endif - -// This maps MCU pin names to pin objects. -#define PIN(num) { MP_ROM_QSTR(MP_QSTR_GPIO##num), MP_ROM_PTR(&pin_GPIO##num) }, -const mp_rom_map_elem_t mcu_pin_global_dict_table[TOTAL_GPIO_COUNT] = { - PIN(0) - PIN(1) - PIN(2) - PIN(3) - PIN(4) - PIN(5) - PIN(6) - PIN(7) - PIN(8) - PIN(9) - PIN(10) - PIN(11) - PIN(12) - PIN(13) - PIN(14) - PIN(15) - PIN(16) - PIN(17) - PIN(18) - PIN(19) - PIN(20) - PIN(21) - PIN(22) - PIN(23) - PIN(24) - PIN(25) - PIN(26) - PIN(27) - PIN(28) - PIN(29) - - PIN(30) - PIN(31) - PIN(32) - PIN(33) - PIN(34) - PIN(35) - PIN(36) - PIN(37) - PIN(38) - PIN(39) - - PIN(40) - PIN(41) - PIN(42) - PIN(43) - PIN(44) - PIN(45) - PIN(46) - PIN(47) - PIN(48) - PIN(49) - - PIN(50) - PIN(51) - PIN(52) - PIN(53) - #if BCM_VERSION == 2711 - PIN(54) - PIN(55) - PIN(56) - PIN(57) - #endif -}; -MP_DEFINE_CONST_DICT(mcu_pin_globals, mcu_pin_global_dict_table); diff --git a/ports/broadcom/common-hal/microcontroller/__init__.h b/ports/broadcom/common-hal/microcontroller/__init__.h deleted file mode 100644 index 217a3de3c7a..00000000000 --- a/ports/broadcom/common-hal/microcontroller/__init__.h +++ /dev/null @@ -1,9 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#pragma once - -#define TOTAL_GPIO_COUNT 58 diff --git a/ports/broadcom/common-hal/neopixel_write/__init__.c b/ports/broadcom/common-hal/neopixel_write/__init__.c deleted file mode 100644 index 175caf54041..00000000000 --- a/ports/broadcom/common-hal/neopixel_write/__init__.c +++ /dev/null @@ -1,165 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "shared-bindings/neopixel_write/__init__.h" - -#include "py/runtime.h" - -#include "shared-bindings/microcontroller/__init__.h" -#include "shared-bindings/digitalio/DigitalInOut.h" -#include "shared-bindings/time/__init__.h" - -#include "peripherals/broadcom/cpu.h" - -#include "supervisor/port.h" - -uint64_t next_start_raw_ticks = 0; - -// NeoPixels are 800khz bit streams. Zeroes are 1/3 duty cycle (~416ns) and ones -// are 2/3 duty cycle (~833ns). - -void common_hal_neopixel_write(const digitalio_digitalinout_obj_t *digitalinout, - uint8_t *pixels, uint32_t num_bytes) { - // Wait to make sure we don't append onto the last transmission. This should only be a tick or - // two. - int icnt; - while ((port_get_raw_ticks(NULL) < next_start_raw_ticks) && - (next_start_raw_ticks - port_get_raw_ticks(NULL) < 100)) { - RUN_BACKGROUND_TASKS; - } - - BP_Function_Enum alt_function = GPIO_FUNCTION_OUTPUT; - uint8_t index = 0; - uint8_t channel = 0; - bool found = false; - for (size_t i = 0; i < NUM_ALT_FUNC; i++) { - const pin_function_t *f = &digitalinout->pin->functions[i]; - if (f->type == PIN_FUNCTION_PWM) { - index = f->index; - channel = f->function; - alt_function = FSEL_VALUES[i]; - found = true; - break; - } - } - if (!found) { - mp_raise_ValueError(MP_ERROR_TEXT("NeoPixel not supported on pin")); - return; - } - - // Turn on the PWM clock. The speed is NeoPixel specific. - if (CM_PWM->CS_b.BUSY == 0) { - uint32_t source_clock; - #if BCM_VERSION == 2711 - source_clock = 54000000; - #else - source_clock = 19200000; - #endif - // Three clocks per 800khz bit to get the 1/3 or 2/3 timing. - uint32_t target_clock = 3 * 800000; - uint32_t int_div = source_clock / target_clock; - - CM_PWM->DIV = CM_PCM_DIV_PASSWD_PASSWD << CM_PCM_DIV_PASSWD_Pos | - (int_div) << CM_PCM_DIV_DIVI_Pos; - - CM_PWM->CS = CM_PCM_CS_PASSWD_PASSWD << CM_PCM_CS_PASSWD_Pos | - CM_PCM_CS_SRC_XOSC << CM_PCM_CS_SRC_Pos; - - // Set enable after setting the source to ensure it is stable. - CM_PWM->CS = CM_PCM_CS_PASSWD_PASSWD << CM_PCM_CS_PASSWD_Pos | - CM_PCM_CS_SRC_XOSC << CM_PCM_CS_SRC_Pos | - CM_PCM_CS_ENAB_Msk; - - // Wait for the clock to start up. - COMPLETE_MEMORY_READS; - icnt = 0; - while ((CM_PWM->CS_b.BUSY == 0) && (icnt++ < 1000)) { - } - } - - PWM0_Type *pwm = PWM0; - #if BCM_VERSION == 2711 - if (index == 1) { - pwm = PWM1; - } - #else - (void)index; - #endif - - pwm->RNG1 = 24; - pwm->RNG2 = 24; - COMPLETE_MEMORY_READS; - pwm->CTL = PWM0_CTL_CLRF1_Msk; - COMPLETE_MEMORY_READS; - - // Even though we're only transmitting one channel, we enable both. Without - // the second channel enabled, the output is repeated forever. - pwm->CTL = - PWM0_CTL_USEF2_Msk | - PWM0_CTL_MODE2_Msk | - PWM0_CTL_USEF1_Msk | - PWM0_CTL_MODE1_Msk; - - COMPLETE_MEMORY_READS; - pwm->CTL |= PWM0_CTL_PWEN1_Msk | PWM0_CTL_PWEN2_Msk; - - gpio_set_function(digitalinout->pin->number, alt_function); - - for (size_t i = 0; i < num_bytes; i++) { - uint32_t expanded = 0; - for (size_t j = 0; j < 8; j++) { - expanded = expanded >> 3; - if ((pixels[i] & (1 << j)) != 0) { - expanded |= 0xc0000000; - } else { - expanded |= 0x80000000; - } - } - if (channel == 1) { - icnt = 0; - while ((pwm->STA_b.FULL1 == 1) && (icnt++ < 150)) { - RUN_BACKGROUND_TASKS; - } - // Dummy value for the first channel. - pwm->FIF1 = 0x000000; - } - icnt = 0; - while ((pwm->STA_b.FULL1 == 1) && (icnt++ < 150)) { - RUN_BACKGROUND_TASKS; - } - pwm->FIF1 = expanded; - if (channel == 0) { - icnt = 0; - while ((pwm->STA_b.FULL1 == 1) && (icnt++ < 150)) { - RUN_BACKGROUND_TASKS; - } - // Dummy value for the second channel. - pwm->FIF1 = 0x000000; - } - } - - icnt = 0; - while ((pwm->STA_b.EMPT1 == 0) && (icnt++ < 2500)) { - RUN_BACKGROUND_TASKS; - } - // Wait for transmission to start. - icnt = 0; - while (((pwm->STA_b.STA1 == 0) && (pwm->STA_b.STA2 == 0)) && (icnt++ < 150)) { - RUN_BACKGROUND_TASKS; - } - // Wait for transmission to complete. - icnt = 0; - while (((pwm->STA_b.STA1 == 1) || (pwm->STA_b.STA2 == 1)) && (icnt++ < 150)) { - RUN_BACKGROUND_TASKS; - } - // Shouldn't be anything left in queue but clear it so the clock doesn't crash if there is - pwm->CTL = PWM0_CTL_CLRF1_Msk; - - gpio_set_function(digitalinout->pin->number, GPIO_FUNCTION_OUTPUT); - - // Update the next start. - next_start_raw_ticks = port_get_raw_ticks(NULL) + 1; -} diff --git a/ports/broadcom/common-hal/os/__init__.c b/ports/broadcom/common-hal/os/__init__.c deleted file mode 100644 index c1c50234451..00000000000 --- a/ports/broadcom/common-hal/os/__init__.c +++ /dev/null @@ -1,15 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2017 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "genhdr/mpversion.h" -#include "py/mpconfig.h" -#include "py/objstr.h" -#include "py/objtuple.h" -#include "py/qstr.h" - -bool common_hal_os_urandom(uint8_t *buffer, uint32_t length) { - return false; -} diff --git a/ports/broadcom/common-hal/rtc/RTC.c b/ports/broadcom/common-hal/rtc/RTC.c deleted file mode 100644 index c7092edd3fe..00000000000 --- a/ports/broadcom/common-hal/rtc/RTC.c +++ /dev/null @@ -1,38 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2019 Nick Moore for Adafruit Industries -// SPDX-FileCopyrightText: Copyright (c) 2019 Artur Pacholec -// -// SPDX-License-Identifier: MIT - -#include - -#include "py/obj.h" -#include "py/runtime.h" -#include "shared/timeutils/timeutils.h" -#include "supervisor/port.h" - -// This is the time in seconds since 2000 that the RTC was started. -// TODO: Change the offset to ticks so that it can be a subsecond adjustment. -static uint32_t rtc_offset = 0; - -void common_hal_rtc_get_time(timeutils_struct_time_t *tm) { - uint64_t ticks_s = port_get_raw_ticks(NULL) / 1024; - timeutils_seconds_since_2000_to_struct_time(rtc_offset + ticks_s, tm); -} - -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 = epoch_s - ticks_s; -} - -int common_hal_rtc_get_calibration(void) { - return 0; -} - -void common_hal_rtc_set_calibration(int calibration) { - mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_calibration); -} diff --git a/ports/broadcom/common-hal/rtc/RTC.h b/ports/broadcom/common-hal/rtc/RTC.h deleted file mode 100644 index 9f310488793..00000000000 --- a/ports/broadcom/common-hal/rtc/RTC.h +++ /dev/null @@ -1,10 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2018 Noralf Trønnes -// SPDX-FileCopyrightText: Copyright (c) 2019 Artur Pacholec -// -// SPDX-License-Identifier: MIT - -#pragma once - -extern void rtc_reset(void); diff --git a/ports/broadcom/common-hal/rtc/__init__.c b/ports/broadcom/common-hal/rtc/__init__.c deleted file mode 100644 index 72d32ef2b2c..00000000000 --- a/ports/broadcom/common-hal/rtc/__init__.c +++ /dev/null @@ -1,5 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2024 Adafruit Industries LLC -// -// SPDX-License-Identifier: MIT diff --git a/ports/broadcom/common-hal/sdioio/SDCard.c b/ports/broadcom/common-hal/sdioio/SDCard.c deleted file mode 100644 index f87d40cd8dc..00000000000 --- a/ports/broadcom/common-hal/sdioio/SDCard.c +++ /dev/null @@ -1,380 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2020 Jeff Epler for Adafruit Industries -// -// SPDX-License-Identifier: MIT -#include - -#include "mphalport.h" - -#include "py/mperrno.h" -#include "py/runtime.h" - -#include "common-hal/microcontroller/Pin.h" -#include "shared-bindings/sdioio/SDCard.h" -#include "shared-bindings/microcontroller/Pin.h" -#include "shared-bindings/microcontroller/__init__.h" -#include "supervisor/port.h" - -#include "peripherals/broadcom/cpu.h" -#include "peripherals/broadcom/defines.h" -#include "peripherals/broadcom/gpio.h" - -#include "lib/sdmmc/include/sdmmc_cmd.h" - -void osal_task_delay(uint32_t msec) { - mp_hal_delay_ms(msec); -} - -/*!< Host function to initialize the driver */ -static sdmmc_err_t _init(void) { - return SDMMC_OK; -} - -/*!< host function to set bus width */ -static sdmmc_err_t _set_bus_width(int slot, size_t width) { - if (width == 4) { - EMMC->CONTROL0_b.HCTL_DWIDTH = true; - } else if (width == 8) { - EMMC->CONTROL0_b.HCTL_8BIT = true; - } - return SDMMC_OK; -} - -/*!< host function to get the maximum bus width of a particular slot */ -static size_t _get_bus_width(int slot) { - return 4; -} - -/*!< host function to set card clock frequency */ -static sdmmc_err_t _set_card_clk(int slot, uint32_t freq_khz) { - uint32_t base_clock = 125000000; - uint32_t frequency = freq_khz * 1000; - uint64_t start_ticks = port_get_raw_ticks(NULL); - while ((EMMC->STATUS_b.CMD_INHIBIT || EMMC->STATUS_b.DAT_INHIBIT) && (port_get_raw_ticks(NULL) - start_ticks) < 1024) { - } - if (EMMC->STATUS_b.CMD_INHIBIT || EMMC->STATUS_b.DAT_INHIBIT) { - return SDMMC_ERR_TIMEOUT; - } - - EMMC->CONTROL1_b.CLK_EN = false; - - uint32_t divisor = base_clock / frequency; - // + 1 to ensure we round the frequency down. - if (base_clock % frequency > 0) { - divisor += 1; - } - // Only even divisors are supported - uint32_t register_value = divisor / 2; - if (divisor % 2 == 1) { - register_value += 1; - } - - // The divisor is stored with bits swapped. - EMMC->CONTROL1_b.CLK_FREQ8 = divisor & 0xff; - EMMC->CONTROL1_b.CLK_FREQ_MS2 = (divisor >> 8) & 0x3; - - EMMC->CONTROL1_b.CLK_EN = true; - start_ticks = port_get_raw_ticks(NULL); - while (!EMMC->CONTROL1_b.CLK_STABLE && (port_get_raw_ticks(NULL) - start_ticks) < 1024) { - } - if (!EMMC->CONTROL1_b.CLK_STABLE) { - return SDMMC_ERR_TIMEOUT; - } - return SDMMC_OK; -} - -/*!< host function to do a transaction */ -static sdmmc_err_t _do_transaction(int slot, sdmmc_command_t *cmdinfo) { - if (EMMC->STATUS_b.CMD_INHIBIT) { - return SDMMC_ERR_BUSY; - } - - // Clear interrupts and then send the command - EMMC->INTERRUPT = 0xffffffff; - EMMC->ARG1 = cmdinfo->arg; - - uint32_t cmd_flags = 0; - bool read = (cmdinfo->flags & SCF_CMD_READ) != 0; - if (SCF_CMD(cmdinfo->flags) == SCF_CMD_ADTC || - SCF_CMD(cmdinfo->flags) == (SCF_CMD_ADTC | SCF_CMD_READ)) { - if (EMMC->STATUS_b.DAT_INHIBIT) { - return SDMMC_ERR_BUSY; - } - cmd_flags = Arasan_EMMC_Distributor_CMDTM_TM_BLKCNT_EN_Msk | Arasan_EMMC_Distributor_CMDTM_CMD_ISDATA_Msk; - if (cmdinfo->datalen > cmdinfo->blklen) { - cmd_flags |= Arasan_EMMC_Distributor_CMDTM_TM_MULTI_BLOCK_Msk; - if ((cmdinfo->flags & SCF_AUTO_STOP) != 0) { - cmd_flags |= 1 << Arasan_EMMC_Distributor_CMDTM_TM_AUTO_CMD_EN_Pos; - } - } - if (read) { - cmd_flags |= Arasan_EMMC_Distributor_CMDTM_TM_DAT_DIR_Msk; - } - EMMC->BLKSIZECNT = (cmdinfo->datalen / cmdinfo->blklen) << Arasan_EMMC_Distributor_BLKSIZECNT_BLKCNT_Pos | - cmdinfo->blklen << Arasan_EMMC_Distributor_BLKSIZECNT_BLKSIZE_Pos; - } - - uint32_t response_type = EMMC_CMDTM_CMD_RSPNS_TYPE_RESPONSE_48BITS; - uint32_t crc = 0; - if ((cmdinfo->flags & SCF_RSP_CRC) != 0) { - crc |= Arasan_EMMC_Distributor_CMDTM_CMD_CRCCHK_EN_Msk; - } - if ((cmdinfo->flags & SCF_RSP_IDX) != 0) { - crc |= Arasan_EMMC_Distributor_CMDTM_CMD_IXCHK_EN_Msk; - } - if ((cmdinfo->flags & SCF_RSP_136) != 0) { - response_type = EMMC_CMDTM_CMD_RSPNS_TYPE_RESPONSE_136BITS; - } else if ((cmdinfo->flags & SCF_RSP_BSY) != 0) { - response_type = EMMC_CMDTM_CMD_RSPNS_TYPE_RESPONSE_48BITS_USING_BUSY; - } else if ((cmdinfo->flags & SCF_RSP_PRESENT) == 0) { - response_type = EMMC_CMDTM_CMD_RSPNS_TYPE_RESPONSE_NONE; - } - uint32_t full_cmd = cmd_flags | crc | - cmdinfo->opcode << Arasan_EMMC_Distributor_CMDTM_CMD_INDEX_Pos | - response_type << Arasan_EMMC_Distributor_CMDTM_CMD_RSPNS_TYPE_Pos; - EMMC->CMDTM = full_cmd; - - // Wait for an interrupt to indicate completion of the command. - uint64_t start_ticks = port_get_raw_ticks(NULL); - while (EMMC->INTERRUPT == 0 && (port_get_raw_ticks(NULL) - start_ticks) < (size_t)cmdinfo->timeout_ms) { - } - if (!EMMC->INTERRUPT_b.CMD_DONE) { - cmdinfo->response[0] = 0; - // Reset the command circuit - EMMC->CONTROL1_b.SRST_CMD = true; - // Wait for the bit to clear - start_ticks = port_get_raw_ticks(NULL); - while (EMMC->CONTROL1_b.SRST_CMD && (port_get_raw_ticks(NULL) - start_ticks) < (size_t)cmdinfo->timeout_ms) { - } - return SDMMC_ERR_TIMEOUT; - } else { - EMMC->INTERRUPT = Arasan_EMMC_Distributor_INTERRUPT_CMD_DONE_Msk; - } - - // Transfer the data. - // TODO: Use DMA - if (cmd_flags != 0) { - if (read) { - for (size_t i = 0; i < cmdinfo->datalen / sizeof(uint32_t); i++) { - start_ticks = port_get_raw_ticks(NULL); - while (!EMMC->INTERRUPT_b.READ_RDY && (port_get_raw_ticks(NULL) - start_ticks) < (size_t)cmdinfo->timeout_ms) { - } - if (!EMMC->INTERRUPT_b.READ_RDY) { - return SDMMC_ERR_TIMEOUT; - } - ((uint32_t *)cmdinfo->data)[i] = EMMC->DATA; - } - } else { - for (size_t i = 0; i < cmdinfo->datalen / sizeof(uint32_t); i++) { - start_ticks = port_get_raw_ticks(NULL); - while (!EMMC->INTERRUPT_b.WRITE_RDY && (port_get_raw_ticks(NULL) - start_ticks) < (size_t)cmdinfo->timeout_ms) { - } - if (!EMMC->INTERRUPT_b.WRITE_RDY) { - return SDMMC_ERR_TIMEOUT; - } - EMMC->DATA = ((uint32_t *)cmdinfo->data)[i]; - } - } - uint32_t data_done_mask = Arasan_EMMC_Distributor_INTERRUPT_ERR_Msk | Arasan_EMMC_Distributor_INTERRUPT_DATA_DONE_Msk; - start_ticks = port_get_raw_ticks(NULL); - while ((EMMC->INTERRUPT & data_done_mask) == 0 && (port_get_raw_ticks(NULL) - start_ticks) < (size_t)cmdinfo->timeout_ms) { - } - if (!EMMC->INTERRUPT_b.DATA_DONE) { - cmdinfo->response[0] = 0; - // Reset the command circuit - EMMC->CONTROL1_b.SRST_DATA = true; - // Wait for the bit to clear - start_ticks = port_get_raw_ticks(NULL); - while (EMMC->CONTROL1_b.SRST_DATA && (port_get_raw_ticks(NULL) - start_ticks) < (size_t)cmdinfo->timeout_ms) { - } - return SDMMC_ERR_TIMEOUT; - } - } - - cmdinfo->response[0] = EMMC->RESP0; - if (response_type == EMMC_CMDTM_CMD_RSPNS_TYPE_RESPONSE_136BITS) { - // Rotate one more byte for some reason. - cmdinfo->response[3] = EMMC->RESP3 << 8 | ((EMMC->RESP2 >> 24) & 0xff); - cmdinfo->response[2] = EMMC->RESP2 << 8 | ((EMMC->RESP1 >> 24) & 0xff); - cmdinfo->response[1] = EMMC->RESP1 << 8 | ((EMMC->RESP0 >> 24) & 0xff); - cmdinfo->response[0] <<= 8; - } - return SDMMC_OK; -} - -/*!< host function to deinitialize the driver, called with the `slot` */ -static sdmmc_err_t _deinit(int slot) { - return SDMMC_OK; -} - -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, const mcu_pin_obj_t **data, uint32_t frequency) { - - if (clock != NULL) { - gpio_set_function(clock->number, GPIO_GPFSEL4_FSEL48_SD1_CLK); - gpio_set_pull(clock->number, BP_PULL_NONE); - self->clock_pin = clock->number; - gpio_set_function(command->number, GPIO_GPFSEL4_FSEL49_SD1_CMD); - gpio_set_pull(command->number, BP_PULL_UP); - self->command_pin = command->number; - gpio_set_function(data[0]->number, GPIO_GPFSEL5_FSEL50_SD1_DAT0); - gpio_set_pull(data[0]->number, BP_PULL_UP); - self->data_pins[0] = data[0]->number; - gpio_set_function(data[1]->number, GPIO_GPFSEL5_FSEL51_SD1_DAT1); - gpio_set_pull(data[1]->number, BP_PULL_UP); - self->data_pins[1] = data[1]->number; - gpio_set_function(data[2]->number, GPIO_GPFSEL5_FSEL52_SD1_DAT2); - gpio_set_pull(data[2]->number, BP_PULL_UP); - self->data_pins[2] = data[2]->number; - gpio_set_function(data[3]->number, GPIO_GPFSEL5_FSEL53_SD1_DAT3); - gpio_set_pull(data[3]->number, BP_PULL_UP); - self->data_pins[3] = data[3]->number; - } else { - // Switch the sdcard to use the old arasan interface. - GPIO->EXTRA_MUX_b.SDIO = GPIO_EXTRA_MUX_SDIO_ARASAN; - } - - COMPLETE_MEMORY_READS; - - self->host_info = (sdmmc_host_t) { - .flags = SDMMC_HOST_FLAG_1BIT | SDMMC_HOST_FLAG_4BIT | SDMMC_HOST_FLAG_DEINIT_ARG, - .slot = 0, - .max_freq_khz = SDMMC_FREQ_HIGHSPEED, - .io_voltage = 3.3f, - .command_timeout_ms = 0, - .init = _init, - .set_bus_width = _set_bus_width, - .get_bus_width = _get_bus_width, - .set_bus_ddr_mode = NULL, - .set_card_clk = _set_card_clk, - .do_transaction = _do_transaction, - .deinit_p = _deinit, - }; - - // Reset the peripheral. - EMMC->CONTROL0 = 0; - EMMC->CONTROL1_b.SRST_HC = true; - // Wait for the bit to clear - while (EMMC->CONTROL1_b.SRST_HC) { - - } - // Set max timeout - EMMC->CONTROL1 |= Arasan_EMMC_Distributor_CONTROL1_CLK_INTLEN_Msk | (0xe << Arasan_EMMC_Distributor_CONTROL1_DATA_TOUNIT_Pos); - - EMMC->IRPT_MASK = 0xffffffff; - - // Start clocking the card. - _set_card_clk(0, 400); - - sdmmc_err_t err = SDMMC_ERR_INVALID_RESPONSE; - size_t tries = 3; - while (err == SDMMC_ERR_INVALID_RESPONSE && tries > 0) { - err = sdmmc_card_init(&self->host_info, &self->card_info); - if (err != SDMMC_OK) { - mp_printf(&mp_plat_print, "SD card init failed %d\n", err); - } else if (tries < 3) { - mp_printf(&mp_plat_print, "SD card init success\n"); - } - tries--; - } - - self->init = err == SDMMC_OK; - - self->capacity = self->card_info.csd.capacity; - COMPLETE_MEMORY_READS; -} - -uint32_t common_hal_sdioio_sdcard_get_count(sdioio_sdcard_obj_t *self) { - return self->capacity; -} - -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) { - return self->num_data; -} - -static void check_whole_block(mp_buffer_info_t *bufinfo) { - if (bufinfo->len % 512) { - mp_raise_ValueError(MP_ERROR_TEXT("Buffer length must be a multiple of 512")); - } -} - -int common_hal_sdioio_sdcard_writeblocks(sdioio_sdcard_obj_t *self, uint32_t start_block, mp_buffer_info_t *bufinfo) { - if (!self->init) { - return -EIO; - } - check_whole_block(bufinfo); - self->state_programming = true; - - COMPLETE_MEMORY_READS; - sdmmc_err_t error = sdmmc_write_sectors(&self->card_info, bufinfo->buf, - start_block, bufinfo->len / 512); - COMPLETE_MEMORY_READS; - - if (error != SDMMC_OK) { - mp_printf(&mp_plat_print, "write sectors result %d\n", error); - return -EIO; - } - - return 0; -} - -int common_hal_sdioio_sdcard_readblocks(sdioio_sdcard_obj_t *self, uint32_t start_block, mp_buffer_info_t *bufinfo) { - if (!self->init) { - return -EIO; - } - check_whole_block(bufinfo); - COMPLETE_MEMORY_READS; - sdmmc_err_t error = sdmmc_read_sectors(&self->card_info, bufinfo->buf, - start_block, bufinfo->len / 512); - COMPLETE_MEMORY_READS; - - if (error != SDMMC_OK) { - mp_printf(&mp_plat_print, "read sectors result %d when reading block %d for %d\n", error, start_block, bufinfo->len / 512); - return -EIO; - } - - return 0; -} - -bool common_hal_sdioio_sdcard_configure(sdioio_sdcard_obj_t *self, uint32_t frequency, uint8_t bits) { - if (!self->init) { - return false; - } - return true; -} - -bool common_hal_sdioio_sdcard_deinited(sdioio_sdcard_obj_t *self) { - return self->command_pin == COMMON_HAL_MCU_NO_PIN; -} - -void common_hal_sdioio_sdcard_deinit(sdioio_sdcard_obj_t *self) { - reset_pin_number(self->command_pin); - reset_pin_number(self->clock_pin); - reset_pin_number(self->data_pins[0]); - reset_pin_number(self->data_pins[1]); - reset_pin_number(self->data_pins[2]); - reset_pin_number(self->data_pins[3]); - - self->command_pin = COMMON_HAL_MCU_NO_PIN; - self->clock_pin = COMMON_HAL_MCU_NO_PIN; - self->data_pins[0] = COMMON_HAL_MCU_NO_PIN; - self->data_pins[1] = COMMON_HAL_MCU_NO_PIN; - self->data_pins[2] = COMMON_HAL_MCU_NO_PIN; - self->data_pins[3] = COMMON_HAL_MCU_NO_PIN; - self->init = false; -} - -void common_hal_sdioio_sdcard_never_reset(sdioio_sdcard_obj_t *self) { - never_reset_pin_number(self->command_pin); - never_reset_pin_number(self->clock_pin); - never_reset_pin_number(self->data_pins[0]); - never_reset_pin_number(self->data_pins[1]); - never_reset_pin_number(self->data_pins[2]); - never_reset_pin_number(self->data_pins[3]); -} diff --git a/ports/broadcom/common-hal/sdioio/SDCard.h b/ports/broadcom/common-hal/sdioio/SDCard.h deleted file mode 100644 index e63f8db99f2..00000000000 --- a/ports/broadcom/common-hal/sdioio/SDCard.h +++ /dev/null @@ -1,24 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2016 Scott Shawcroft -// -// SPDX-License-Identifier: MIT - -#pragma once - -#include "lib/sdmmc/include/sdmmc_types.h" - -typedef struct { - mp_obj_base_t base; - sdmmc_host_t host_info; - sdmmc_card_t card_info; - uint32_t frequency; - uint32_t capacity; - uint8_t num_data; - bool state_programming; - bool has_lock; - bool init; - uint8_t command_pin; - uint8_t clock_pin; - uint8_t data_pins[4]; -} sdioio_sdcard_obj_t; diff --git a/ports/broadcom/common-hal/sdioio/__init__.c b/ports/broadcom/common-hal/sdioio/__init__.c deleted file mode 100644 index 72d32ef2b2c..00000000000 --- a/ports/broadcom/common-hal/sdioio/__init__.c +++ /dev/null @@ -1,5 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2024 Adafruit Industries LLC -// -// SPDX-License-Identifier: MIT diff --git a/ports/broadcom/common-hal/sdioio/__init__.h b/ports/broadcom/common-hal/sdioio/__init__.h deleted file mode 100644 index c9069db9fd7..00000000000 --- a/ports/broadcom/common-hal/sdioio/__init__.h +++ /dev/null @@ -1,7 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2024 Adafruit Industries LLC -// -// SPDX-License-Identifier: MIT - -#pragma once diff --git a/ports/broadcom/common-hal/videocore/Framebuffer.c b/ports/broadcom/common-hal/videocore/Framebuffer.c deleted file mode 100644 index 26672d95f4d..00000000000 --- a/ports/broadcom/common-hal/videocore/Framebuffer.c +++ /dev/null @@ -1,80 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2024 Adafruit Industries LLC -// -// SPDX-License-Identifier: MIT - - -#include "bindings/videocore/Framebuffer.h" - -#include "py/gc.h" -#include "py/runtime.h" - -#include "peripherals/broadcom/caches.h" -#include "peripherals/broadcom/vcmailbox.h" - -void common_hal_videocore_framebuffer_construct(videocore_framebuffer_obj_t *self, - mp_uint_t width, mp_uint_t height) { - // These will be modified on success to indicate actual values. - uint32_t virtual_width = width; - uint32_t virtual_height = height; - uint32_t physical_width = width; - // TODO: Make the FB twice as tall if double buffering. - uint32_t physical_height = height; - uint32_t pitch = 0; - uint32_t bits_per_pixel = 0; - self->framebuffer = vcmailbox_get_framebuffer(&virtual_width, - &virtual_height, - &physical_width, - &physical_height, - &pitch, - &bits_per_pixel); - if (self->framebuffer == NULL) { - if (gc_alloc_possible()) { - mp_raise_ValueError(MP_ERROR_TEXT("no fb")); - } else { - mp_printf(&mp_plat_print, "no fb\n"); - } - self->width = 0; - self->height = 0; - return; - } - self->width = virtual_width; - self->height = virtual_height; - self->pitch = pitch; -} - -void common_hal_videocore_framebuffer_deinit(videocore_framebuffer_obj_t *self) { - if (vcmailbox_release_framebuffer()) { - self->framebuffer = NULL; - } - self->base.type = &mp_type_NoneType; -} - -bool common_hal_videocore_framebuffer_deinited(videocore_framebuffer_obj_t *self) { - return self->framebuffer == NULL; -} - -void common_hal_videocore_framebuffer_refresh(videocore_framebuffer_obj_t *self) { - data_clean(self->framebuffer, sizeof(uint32_t) * self->width * self->height); -} - -int common_hal_videocore_framebuffer_get_width(videocore_framebuffer_obj_t *self) { - return self->width; -} - -int common_hal_videocore_framebuffer_get_height(videocore_framebuffer_obj_t *self) { - return self->height; -} - -mp_int_t common_hal_videocore_framebuffer_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags) { - videocore_framebuffer_obj_t *self = (videocore_framebuffer_obj_t *)self_in; - bufinfo->buf = self->framebuffer; - bufinfo->typecode = 'L'; - bufinfo->len = self->pitch * self->height * sizeof(uint32_t); - return 0; -} - -int common_hal_videocore_framebuffer_get_row_stride(videocore_framebuffer_obj_t *self) { - return self->pitch; -} diff --git a/ports/broadcom/common-hal/videocore/Framebuffer.h b/ports/broadcom/common-hal/videocore/Framebuffer.h deleted file mode 100644 index 939204efbcd..00000000000 --- a/ports/broadcom/common-hal/videocore/Framebuffer.h +++ /dev/null @@ -1,18 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Jeff Epler for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#pragma once - -#include "py/obj.h" - -typedef struct { - mp_obj_base_t base; - uint32_t *framebuffer; - mp_uint_t width; - mp_uint_t height; - uint32_t pitch; - bool doublebuffer; -} videocore_framebuffer_obj_t; diff --git a/ports/broadcom/config.txt b/ports/broadcom/config.txt deleted file mode 100644 index 1c12196b980..00000000000 --- a/ports/broadcom/config.txt +++ /dev/null @@ -1,10 +0,0 @@ - -# dtparam=audio=on -# dtoverlay=dwc2 -# core_freq_min=500 -gpio=22-27=np -enable_jtag_gpio=1 -# hdmi_group=1 -# hdmi_mode=16 -gpu_mem=16 -kernel_address=0x100000 diff --git a/ports/broadcom/firmware b/ports/broadcom/firmware deleted file mode 160000 index bf96d0eda59..00000000000 --- a/ports/broadcom/firmware +++ /dev/null @@ -1 +0,0 @@ -Subproject commit bf96d0eda5952595d717fedb797aeb168483e9fa diff --git a/ports/broadcom/mpconfigport.h b/ports/broadcom/mpconfigport.h deleted file mode 100644 index 8b749ca0310..00000000000 --- a/ports/broadcom/mpconfigport.h +++ /dev/null @@ -1,36 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#pragma once - -// Definitions that control circuitpy_mpconfig.h: - -//////////////////////////////////////////////////////////////////////////////////////////////////// - - -#define CIRCUITPY_MCU_FAMILY broadcom -#define MICROPY_PY_SYS_PLATFORM "BROADCOM" - -#if BCM_VERSION == 2837 || BCM_VERSION == 2711 -#define MICROPY_OBJ_REPR (MICROPY_OBJ_REPR_A) -#elif BCM_VERSION == 2835 -#define MICROPY_OBJ_REPR (MICROPY_OBJ_REPR_C) -#endif -#define CIRCUITPY_DEFAULT_STACK_SIZE (0x10000) -#define CIRCUITPY_DISPLAY_AREA_BUFFER_SIZE (1920) -#define CIRCUITPY_PROCESSOR_COUNT (4) - -#define MICROPY_FATFS_EXFAT (1) -#define MICROPY_FATFS_MKFS_FAT32 (1) - -//////////////////////////////////////////////////////////////////////////////////////////////////// - -// This also includes mpconfigboard.h. -#include "py/circuitpy_mpconfig.h" - -// Definitions that can be overridden by mpconfigboard.h: - -//////////////////////////////////////////////////////////////////////////////////////////////////// diff --git a/ports/broadcom/mpconfigport.mk b/ports/broadcom/mpconfigport.mk deleted file mode 100644 index b4b3e2ebf81..00000000000 --- a/ports/broadcom/mpconfigport.mk +++ /dev/null @@ -1,33 +0,0 @@ -# All broadcom ports have longints. -LONGINT_IMPL = MPZ - -CIRCUITPY_FULL_BUILD = 1 - -# Modules in FULL_BUILD that we don't support. -CIRCUITPY_ANALOGIO = 0 -CIRCUITPY_AUDIOBUSIO = 0 -CIRCUITPY_AUDIOIO = 0 -CIRCUITPY_COUNTIO = 0 -CIRCUITPY_FREQUENCYIO = 0 -CIRCUITPY_I2CTARGET = 0 -CIRCUITPY_NVM = 0 -CIRCUITPY_PARALLELDISPLAYBUS = 0 -CIRCUITPY_PULSEIO = 0 -CIRCUITPY_PWMIO = 0 -CIRCUITPY_ROTARYIO = 0 - -CIRCUITPY_SDIOIO = 1 -CIRCUITPY_VIDEOCORE = 1 - -INTERNAL_FLASH_FILESYSTEM = 1 - -USB_NUM_ENDPOINT_PAIRS = 8 -USB_HIGHSPEED = 1 - -CIRCUITPY_BUILD_EXTENSIONS ?= disk.img.zip,kernel8.img - -ifeq ($(CHIP_VARIANT), "bcm2711") -CIRCUITPY_MIN_GCC_VERSION ?= 10 -else ifeq ($(CHIP_VARIANT), "bcm2837") -CIRCUITPY_MIN_GCC_VERSION ?= 10 -endif diff --git a/ports/broadcom/mphalport.c b/ports/broadcom/mphalport.c deleted file mode 100644 index 32718511f05..00000000000 --- a/ports/broadcom/mphalport.c +++ /dev/null @@ -1,63 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2024 Adafruit Industries LLC -// -// SPDX-License-Identifier: MIT - -#include - -#include -#include "py/mpconfig.h" -#include "py/obj.h" -#include "shared-bindings/microcontroller/__init__.h" -#include "mphalport.h" - -#include "peripherals/broadcom/defines.h" - -void mp_hal_delay_us(mp_uint_t delay) { - uint32_t end = SYSTMR->CLO + delay; - // Wait if end is before current time because it must have wrapped. - while (end < SYSTMR->CLO) { - } - while (SYSTMR->CLO < end) { - } -} - -void mp_hal_disable_all_interrupts(void) { - common_hal_mcu_disable_interrupts(); -} - -void mp_hal_enable_all_interrupts(void) { - common_hal_mcu_enable_interrupts(); -} - -mp_uint_t cpu_get_regs_and_sp(mp_uint_t *regs) { - size_t sp = 0; - #if defined(__ARM_ARCH) && (__ARM_ARCH >= 8) - __asm__ ("mov %[out], sp" : [out] "=r" (sp)); - __asm__ ("mov %[out], x19" : [out] "=r" (regs[0])); - __asm__ ("mov %[out], x20" : [out] "=r" (regs[1])); - __asm__ ("mov %[out], x21" : [out] "=r" (regs[2])); - __asm__ ("mov %[out], x22" : [out] "=r" (regs[3])); - __asm__ ("mov %[out], x23" : [out] "=r" (regs[4])); - __asm__ ("mov %[out], x24" : [out] "=r" (regs[5])); - __asm__ ("mov %[out], x25" : [out] "=r" (regs[6])); - __asm__ ("mov %[out], x26" : [out] "=r" (regs[7])); - __asm__ ("mov %[out], x27" : [out] "=r" (regs[8])); - __asm__ ("mov %[out], x28" : [out] "=r" (regs[9])); - #else - __asm__ ("mov %[out], sp" : [out] "=r" (sp)); - __asm__ ("mov %[out], r4" : [out] "=r" (regs[0])); - __asm__ ("mov %[out], r5" : [out] "=r" (regs[1])); - __asm__ ("mov %[out], r6" : [out] "=r" (regs[2])); - __asm__ ("mov %[out], r7" : [out] "=r" (regs[3])); - __asm__ ("mov %[out], r8" : [out] "=r" (regs[4])); - __asm__ ("mov %[out], r9" : [out] "=r" (regs[5])); - __asm__ ("mov %[out], r10" : [out] "=r" (regs[6])); - __asm__ ("mov %[out], r11" : [out] "=r" (regs[7])); - __asm__ ("mov %[out], r12" : [out] "=r" (regs[8])); - __asm__ ("mov %[out], r13" : [out] "=r" (regs[9])); - #endif - - return sp; -} diff --git a/ports/broadcom/mphalport.h b/ports/broadcom/mphalport.h deleted file mode 100644 index d42915aa8bd..00000000000 --- a/ports/broadcom/mphalport.h +++ /dev/null @@ -1,28 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2022 Scott Shawcroft -// -// SPDX-License-Identifier: MIT - -#pragma once - -#include -#include "py/obj.h" - - -#include "supervisor/shared/tick.h" - -void mp_hal_delay_ms(mp_uint_t ms); -void mp_hal_delay_us(mp_uint_t us); - -#define mp_hal_ticks_ms() ((mp_uint_t)supervisor_ticks_ms32()) - -void mp_hal_set_interrupt_char(int c); -int mp_hal_stdin_rx_chr(void); -mp_uint_t mp_hal_stdout_tx_strn(const char *str, size_t len); - -#ifdef MICROPY_HW_USBHOST -#include "usbkbd.h" - -void usbkbd_setup(); -#endif diff --git a/ports/broadcom/peripherals b/ports/broadcom/peripherals deleted file mode 160000 index ec1043800fc..00000000000 --- a/ports/broadcom/peripherals +++ /dev/null @@ -1 +0,0 @@ -Subproject commit ec1043800fc987f7067fc07615193439843695d6 diff --git a/ports/broadcom/qstrdefsport.h b/ports/broadcom/qstrdefsport.h deleted file mode 100644 index 79d7f33276e..00000000000 --- a/ports/broadcom/qstrdefsport.h +++ /dev/null @@ -1,16 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2014 Damien P. George -// -// SPDX-License-Identifier: MIT - -// Do not use #pragma once in this file; it will cause a warning during qstr generation. - -// qstrs specific to this port, only needed if they aren't auto-generated - -// Prevent uncrustify from modifying these lines. -// *FORMAT-OFF* - -// Entries for sys.path -Q(/sd) -Q(/sd/lib) diff --git a/ports/broadcom/supervisor/internal_flash.c b/ports/broadcom/supervisor/internal_flash.c deleted file mode 100644 index 2e75154ea35..00000000000 --- a/ports/broadcom/supervisor/internal_flash.c +++ /dev/null @@ -1,160 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "supervisor/flash.h" -#include "supervisor/internal_flash.h" - -#include - -#include "shared-bindings/digitalio/DigitalInOut.h" -#include "shared-bindings/sdioio/SDCard.h" - -static sdioio_sdcard_obj_t sd; - -static uint32_t first_lba = 0; -static uint32_t sector_count = 0; - -static bool inited = false; - -void supervisor_flash_init(void) { - if (inited) { - return; - } - inited = true; - - #if BCM_VERSION != 2711 - const mcu_pin_obj_t *data_pins[4] = { - &pin_GPIO50, - &pin_GPIO51, - &pin_GPIO52, - &pin_GPIO53, - }; - common_hal_sdioio_sdcard_construct(&sd, - &pin_GPIO48, &pin_GPIO49, - 4, data_pins, 8000000); - #else - common_hal_sdioio_sdcard_construct(&sd, - NULL, NULL, - 0, NULL, 8000000); - #endif - common_hal_sdioio_sdcard_never_reset(&sd); - - uint32_t buffer[512 / sizeof(uint32_t)]; - mp_buffer_info_t bufinfo; - bufinfo.len = 512; - bufinfo.buf = buffer; - common_hal_sdioio_sdcard_readblocks(&sd, 0, &bufinfo); - size_t partition_count = 0; - size_t first_free_sector = 0; - for (size_t i = 0; i < 4; i++) { - uint32_t part_first_lba = 0; - uint32_t part_sector_count = 0; - for (size_t j = 0; j < 16; j++) { - size_t offset = 446 + i * 16 + j; - uint8_t value = ((uint8_t *)buffer)[offset]; - // Little endian - if (j >= 8 && j < 12) { - part_first_lba |= value << (8 * (j - 8)); - } else if (j >= 12) { - part_sector_count |= value << (8 * (j - 12)); - } - } - if (part_sector_count > 0) { - partition_count += 1; - first_free_sector = part_first_lba + part_sector_count; - } - // If the second partition exists, then use it (possibly after reformatting it.) - if (i == 1 && part_sector_count > 0 && part_first_lba > 0) { - sector_count = part_sector_count; - first_lba = part_first_lba; - } else if (i > 1 && part_sector_count > 0) { - sector_count = 0; - } - } - - // Special case where most of the card is unused and the first and only - // partition is likely the CP boot partition. (It is 255MB starting at 1MB) - size_t sectors_per_mb = 2048; - if (partition_count == 1 && first_free_sector == 256 * sectors_per_mb) { - size_t total_sectors = common_hal_sdioio_sdcard_get_count(&sd); - // Align to a MB - total_sectors = total_sectors - (total_sectors % sectors_per_mb); - // Don't use the last MB because the imager erases it. GPT tables put a - // backup there sometimes. - total_sectors -= sectors_per_mb; - size_t new_sector_count = total_sectors - first_free_sector; - - // Modify the MBR - size_t offset = 446 + 1 * 16; - uint8_t *part = ((uint8_t *)buffer) + offset; - part[0] = 0; // not boot - part[1] = 0xff; // Old unused CHS sizing - part[2] = 0xff; - part[3] = 0xff; - uint8_t type = 0x0C; // FAT32 with LBA - if (new_sector_count >= 0x4000000) { - type = 0x07; // Exfat when 32GB+ - } - part[4] = type; - part[5] = 0xff; // Old unused CHS sizing - part[6] = 0xff; - part[7] = 0xff; - part[8] = first_free_sector & 0xff; - part[9] = (first_free_sector >> 8) & 0xff; - part[10] = (first_free_sector >> 16) & 0xff; - part[11] = (first_free_sector >> 24) & 0xff; - part[12] = new_sector_count & 0xff; - part[13] = (new_sector_count >> 8) & 0xff; - part[14] = (new_sector_count >> 16) & 0xff; - part[15] = (new_sector_count >> 24) & 0xff; - - // Write back the modified MBR with the new partition. CircuitPython can - // detect a previously formatted FAT filesystem later if only the MBR and - // BOOT partition was updated. - if (common_hal_sdioio_sdcard_writeblocks(&sd, 0, &bufinfo) == 0) { - sector_count = new_sector_count; - first_lba = first_free_sector; - } - } -} - -uint32_t supervisor_flash_get_block_size(void) { - return 512; -} - -uint32_t supervisor_flash_get_block_count(void) { - return sector_count; -} - -void port_internal_flash_flush(void) { -} - -mp_uint_t supervisor_flash_read_blocks(uint8_t *dest, uint32_t block, uint32_t num_blocks) { - mp_buffer_info_t bufinfo; - bufinfo.len = 512; - for (size_t i = 0; i < num_blocks; i++) { - bufinfo.buf = dest + 512 * i; - if (common_hal_sdioio_sdcard_readblocks(&sd, first_lba + block + i, &bufinfo) != 0) { - return 1; // error - } - } - return 0; // success -} - -mp_uint_t supervisor_flash_write_blocks(const uint8_t *src, uint32_t block, uint32_t num_blocks) { - mp_buffer_info_t bufinfo; - bufinfo.len = 512; - for (size_t i = 0; i < num_blocks; i++) { - bufinfo.buf = (uint8_t *)src + 512 * i; - if (common_hal_sdioio_sdcard_writeblocks(&sd, first_lba + block + i, &bufinfo) != 0) { - return 1; // error - } - } - return 0; // success -} - -void supervisor_flash_release_cache(void) { -} diff --git a/ports/broadcom/supervisor/internal_flash.h b/ports/broadcom/supervisor/internal_flash.h deleted file mode 100644 index 94b1f0bc973..00000000000 --- a/ports/broadcom/supervisor/internal_flash.h +++ /dev/null @@ -1,10 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT -#pragma once - -#include - -#include "mpconfigport.h" diff --git a/ports/broadcom/supervisor/port.c b/ports/broadcom/supervisor/port.c deleted file mode 100644 index 33b20b7c864..00000000000 --- a/ports/broadcom/supervisor/port.c +++ /dev/null @@ -1,178 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include -#include - -#include "supervisor/board.h" -#include "supervisor/port.h" - -#include "genhdr/mpversion.h" - -#include "common-hal/rtc/RTC.h" -#include "common-hal/busio/I2C.h" -#include "common-hal/busio/SPI.h" -#include "common-hal/busio/UART.h" - -#include "peripherals/broadcom/caches.h" -#include "peripherals/broadcom/cpu.h" -#include "peripherals/broadcom/defines.h" -#include "peripherals/broadcom/interrupts.h" -#include "peripherals/broadcom/mmu.h" - -#include "shared-bindings/microcontroller/__init__.h" - -#include "supervisor/shared/safe_mode.h" -#include "supervisor/shared/stack.h" -#include "supervisor/shared/tick.h" - -#include "peripherals/broadcom/vcmailbox.h" - -// #include "tusb.h" - -extern volatile bool mp_msc_enabled; - -static uint32_t board_revision; - -safe_mode_t port_init(void) { - board_revision = vcmailbox_get_board_revision(); - setup_mmu_flat_map(); - - init_caches(); - - // Set brown out. - - // 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); - - // Check brownout. - - if (board_requests_safe_mode()) { - return SAFE_MODE_USER; - } - - return SAFE_MODE_NONE; -} - -void reset_port(void) { - #if CIRCUITPY_BUSIO - reset_i2c(); - reset_spi(); - reset_uart(); - #endif - - #if CIRCUITPY_PWMIO - pwmout_reset(); - #endif - - #if CIRCUITPY_RTC - 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_usb_boot(0, 0); - while (true) { - } -} - -void reset_cpu(void) { - // Don't actually reset because we can't store the safe mode info. - // PM->WDOG = 1 << PM_WDOG_TIME_Pos | PM_WDOG_PASSWD_PASSWD << PM_WDOG_PASSWD_Pos; - // PM->RSTC = PM_RSTC_WRCFG_FULL_RESET << PM_RSTC_WRCFG_Pos | PM_RSTC_PASSWD_PASSWD << PM_RSTC_PASSWD_Pos; - while (true) { - } -} - -// From the linker script -extern uint32_t __bss_end; -extern uint32_t _ld_ram_end; -uint32_t *port_stack_get_limit(void) { - return (uint32_t *)0x4; -} - -uint32_t *port_stack_get_top(void) { - return (uint32_t *)0x100000; -} - -uint32_t *port_heap_get_bottom(void) { - return &__bss_end; -} - -uint32_t *port_heap_get_top(void) { - // 32M heap - return (uint32_t *)(((size_t)&__bss_end) + 32 * 1024 * 1024); -} - -void port_set_saved_word(uint32_t value) { - // NOTE: This doesn't survive pressing the reset button (aka toggling RUN). - __bss_end = value; - data_clean_and_invalidate(&__bss_end, sizeof(uint32_t)); -} - -uint32_t port_get_saved_word(void) { - return __bss_end; -} - -uint64_t port_get_raw_ticks(uint8_t *subticks) { - COMPLETE_MEMORY_READS; - uint64_t hi = SYSTMR->CHI; - uint64_t lo = SYSTMR->CLO; - if (hi != SYSTMR->CHI) { - hi = SYSTMR->CHI; - lo = SYSTMR->CLO; - } - COMPLETE_MEMORY_READS; - uint64_t microseconds = hi << 32 | lo; - return 1024 * (microseconds / 1000000) + (microseconds % 1000000) / 977; -} - -void TIMER_1_IRQHandler(void) { - SYSTMR->C1 += 977; - SYSTMR->CS_b.M1 = 1; - supervisor_tick(); -} - -// Enable 1/1024 second tick. -void port_enable_tick(void) { - COMPLETE_MEMORY_READS; - SYSTMR->CS_b.M1 = 1; - SYSTMR->C1 = SYSTMR->CLO + 977; - BP_EnableIRQ(TIMER_1_IRQn); -} - -// Disable 1/1024 second tick. -void port_disable_tick(void) { - BP_DisableIRQ(TIMER_1_IRQn); -} - -void port_interrupt_after_ticks(uint32_t ticks) { -} - -void port_idle_until_interrupt(void) { - common_hal_mcu_disable_interrupts(); -// if (!tud_task_event_ready()) { -// // asm volatile ("dsb 0xF":::"memory"); -// // __wfi(); -// } - common_hal_mcu_enable_interrupts(); -} diff --git a/ports/broadcom/supervisor/usb.c b/ports/broadcom/supervisor/usb.c deleted file mode 100644 index 166ed4e3e2e..00000000000 --- a/ports/broadcom/supervisor/usb.c +++ /dev/null @@ -1,28 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2017, 2018 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "lib/tinyusb/src/device/usbd.h" -#include "py/runtime.h" -#include "supervisor/background_callback.h" -#include "supervisor/usb.h" - -#include "peripherals/broadcom/interrupts.h" -#include "peripherals/broadcom/vcmailbox.h" - -uint32_t SystemCoreClock = 700 * 1000 * 1000; - -void USB_IRQHandler(void) { - usb_irq_handler(0); -} - -void init_usb_hardware(void) { - vcmailbox_set_power_state(VCMAILBOX_DEVICE_USB_HCD, true); - - BP_SetPriority(USB_IRQn, 0x00); - BP_ClearPendingIRQ(USB_IRQn); - BP_EnableIRQ(USB_IRQn); - BP_EnableIRQs(); -} diff --git a/ports/cxd56/Makefile b/ports/cxd56/Makefile index 30abb8bb47f..88c39210220 100644 --- a/ports/cxd56/Makefile +++ b/ports/cxd56/Makefile @@ -74,7 +74,7 @@ CFLAGS += \ -fdata-sections \ -Wall \ -OPTIMIZATION_FLAGS ?= -O2 -fno-inline-functions +OPTIMIZATION_FLAGS ?= -O2 # option to override compiler optimization level, set in boards/$(BOARD)/mpconfigboard.mk CFLAGS += $(OPTIMIZATION_FLAGS) @@ -110,15 +110,9 @@ LDFLAGS = \ 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)) \ - $(addprefix common-hal/, $(SRC_COMMON_HAL)) +SRC_S = shared/runtime/gchelper_thumb2.s -SRC_SHARED_MODULE_EXPANDED = $(addprefix shared-bindings/, $(SRC_SHARED_MODULE)) \ - $(addprefix shared-module/, $(SRC_SHARED_MODULE)) \ - $(addprefix shared-module/, $(SRC_SHARED_MODULE_INTERNAL)) - -SRC_S = supervisor/cpu.s +SRC_C += shared/runtime/gchelper_native.c SRC_C += \ background.c \ @@ -129,8 +123,7 @@ SRC_C += \ OBJ = $(PY_O) $(SUPERVISOR_O) $(addprefix $(BUILD)/, $(SRC_C:.c=.o)) OBJ += $(addprefix $(BUILD)/, $(SRC_S:.s=.o)) -OBJ += $(addprefix $(BUILD)/, $(SRC_COMMON_HAL_EXPANDED:.c=.o)) -OBJ += $(addprefix $(BUILD)/, $(SRC_SHARED_MODULE_EXPANDED:.c=.o)) +OBJ += $(addprefix $(BUILD)/, $(SRC_COMMON_HAL_SHARED_MODULE_EXPANDED:.c=.o)) ifeq ($(INTERNAL_LIBM),1) OBJ += $(addprefix $(BUILD)/, $(SRC_LIBM:.c=.o)) endif @@ -138,7 +131,7 @@ OBJ += $(addprefix $(BUILD)/, $(SRC_CIRCUITPY_COMMON:.c=.o)) OBJ += $(addprefix $(BUILD)/, $(SRC_MOD:.c=.o)) # List of sources for qstr extraction -SRC_QSTR += $(SRC_C) $(SRC_SUPERVISOR) $(SRC_COMMON_HAL_EXPANDED) $(SRC_SHARED_MODULE_EXPANDED) $(SRC_CIRCUITPY_COMMON) +SRC_QSTR += $(SRC_C) $(SRC_SUPERVISOR) $(SRC_COMMON_HAL_SHARED_MODULE_EXPANDED) $(SRC_CIRCUITPY_COMMON) # Sources that only hold QSTRs after pre-processing. SRC_QSTR_PREPROCESSOR += diff --git a/ports/cxd56/common-hal/analogio/AnalogIn.c b/ports/cxd56/common-hal/analogio/AnalogIn.c index b124f1bac80..b90104ea10b 100644 --- a/ports/cxd56/common-hal/analogio/AnalogIn.c +++ b/ports/cxd56/common-hal/analogio/AnalogIn.c @@ -20,18 +20,27 @@ typedef struct { const char *devpath; const mcu_pin_obj_t *pin; int fd; + // The ADC pins aren't claimed, so more than one AnalogIn can use a device. + // Close it when the last one is deinited. + uint8_t num_users; } analogin_dev_t; static analogin_dev_t analogin_dev[] = { - {"/dev/lpadc0", &pin_LPADC0, -1}, - {"/dev/lpadc1", &pin_LPADC1, -1}, - {"/dev/lpadc2", &pin_LPADC2, -1}, - {"/dev/lpadc3", &pin_LPADC3, -1}, - {"/dev/hpadc0", &pin_HPADC0, -1}, - {"/dev/hpadc1", &pin_HPADC1, -1}, + {"/dev/lpadc0", &pin_LPADC0, -1, 0}, + {"/dev/lpadc1", &pin_LPADC1, -1, 0}, + {"/dev/lpadc2", &pin_LPADC2, -1, 0}, + {"/dev/lpadc3", &pin_LPADC3, -1, 0}, + {"/dev/hpadc0", &pin_HPADC0, -1, 0}, + {"/dev/hpadc1", &pin_HPADC1, -1, 0}, }; +static void mark_deinit(analogio_analogin_obj_t *self) { + self->pin = NULL; +} + void common_hal_analogio_analogin_construct(analogio_analogin_obj_t *self, const mcu_pin_obj_t *pin) { + mark_deinit(self); + if (!pin->analog) { raise_ValueError_invalid_pin(); } @@ -65,6 +74,7 @@ void common_hal_analogio_analogin_construct(analogio_analogin_obj_t *self, const // start ADC ioctl(analogin_dev[self->number].fd, ANIOC_CXD56_START, 0); + analogin_dev[self->number].num_users++; self->pin = pin; } @@ -73,16 +83,20 @@ void common_hal_analogio_analogin_deinit(analogio_analogin_obj_t *self) { return; } - // stop ADC - ioctl(analogin_dev[self->number].fd, ANIOC_CXD56_STOP, 0); - close(analogin_dev[self->number].fd); - analogin_dev[self->number].fd = -1; + analogin_dev[self->number].num_users--; + if (analogin_dev[self->number].num_users == 0) { + // stop ADC + ioctl(analogin_dev[self->number].fd, ANIOC_CXD56_STOP, 0); + close(analogin_dev[self->number].fd); + analogin_dev[self->number].fd = -1; + } - self->pin = NULL; + mark_deinit(self); } +// Per object: the device's fd may now belong to a newer AnalogIn. bool common_hal_analogio_analogin_deinited(analogio_analogin_obj_t *self) { - return analogin_dev[self->number].fd < 0; + return self->pin == NULL; } uint16_t common_hal_analogio_analogin_get_value(analogio_analogin_obj_t *self) { @@ -108,14 +122,3 @@ float common_hal_analogio_analogin_get_reference_voltage(analogio_analogin_obj_t return voltage; } - -void analogin_reset(void) { - for (int i = 0; i < MP_ARRAY_SIZE(analogin_dev); i++) { - if (analogin_dev[i].fd >= 0) { - // stop ADC - ioctl(analogin_dev[i].fd, ANIOC_CXD56_STOP, 0); - close(analogin_dev[i].fd); - analogin_dev[i].fd = -1; - } - } -} diff --git a/ports/cxd56/common-hal/analogio/AnalogIn.h b/ports/cxd56/common-hal/analogio/AnalogIn.h index affc7f805e8..da36b6818ff 100644 --- a/ports/cxd56/common-hal/analogio/AnalogIn.h +++ b/ports/cxd56/common-hal/analogio/AnalogIn.h @@ -15,5 +15,3 @@ typedef struct { const mcu_pin_obj_t *pin; int8_t number; } analogio_analogin_obj_t; - -void analogin_reset(void); diff --git a/ports/cxd56/common-hal/busio/I2C.c b/ports/cxd56/common-hal/busio/I2C.c index fb33c242a03..b16c1d0aa10 100644 --- a/ports/cxd56/common-hal/busio/I2C.c +++ b/ports/cxd56/common-hal/busio/I2C.c @@ -17,7 +17,6 @@ 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) { - // Ensure the object starts in its deinit state. common_hal_busio_i2c_mark_deinit(self); if (frequency != I2C_SPEED_STANDARD && frequency != I2C_SPEED_FAST) { @@ -44,7 +43,6 @@ void common_hal_busio_i2c_deinit(busio_i2c_obj_t *self) { } cxd56_i2cbus_uninitialize(self->i2c_dev); - self->i2c_dev = NULL; reset_pin_number(self->scl_pin->number); reset_pin_number(self->sda_pin->number); @@ -91,7 +89,7 @@ bool common_hal_busio_i2c_probe(busio_i2c_obj_t *self, uint8_t addr) { return I2C_TRANSFER(self->i2c_dev, &msg, 1) < 0 ? false : true; } -static uint8_t _common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t address, const uint8_t *data, size_t len, bool stop) { +static mp_negative_errno_t _common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t address, const uint8_t *data, size_t len, bool stop) { struct i2c_msg_s msg; msg.frequency = self->frequency; @@ -102,12 +100,12 @@ static uint8_t _common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addre return -I2C_TRANSFER(self->i2c_dev, &msg, 1); } -uint8_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, +mp_negative_errno_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, const uint8_t *data, size_t len) { return _common_hal_busio_i2c_write(self, addr, data, len, true); } -uint8_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t address, uint8_t *data, size_t len) { +mp_negative_errno_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t address, uint8_t *data, size_t len) { struct i2c_msg_s msg; msg.frequency = self->frequency; @@ -118,17 +116,12 @@ uint8_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t address, uint8 return -I2C_TRANSFER(self->i2c_dev, &msg, 1); } -uint8_t common_hal_busio_i2c_write_read(busio_i2c_obj_t *self, uint16_t addr, +mp_negative_errno_t common_hal_busio_i2c_write_read(busio_i2c_obj_t *self, uint16_t addr, uint8_t *out_data, size_t out_len, uint8_t *in_data, size_t in_len) { - uint8_t result = _common_hal_busio_i2c_write(self, addr, out_data, out_len, false); + mp_negative_errno_t result = _common_hal_busio_i2c_write(self, addr, out_data, out_len, false); if (result != 0) { return result; } return common_hal_busio_i2c_read(self, addr, in_data, in_len); } - -void common_hal_busio_i2c_never_reset(busio_i2c_obj_t *self) { - never_reset_pin_number(self->scl_pin->number); - never_reset_pin_number(self->sda_pin->number); -} diff --git a/ports/cxd56/common-hal/busio/SPI.c b/ports/cxd56/common-hal/busio/SPI.c index 8eedb624201..53466a4ed80 100644 --- a/ports/cxd56/common-hal/busio/SPI.c +++ b/ports/cxd56/common-hal/busio/SPI.c @@ -19,6 +19,8 @@ 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, bool half_duplex) { int port = -1; + common_hal_busio_spi_mark_deinit(self); + if (half_duplex) { mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_half_duplex); } @@ -39,14 +41,24 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, const mcu_pin_obj_t * raise_ValueError_invalid_pins(); } + struct spi_dev_s *spi_dev = cxd56_spibus_initialize(port); + if (spi_dev == NULL) { + mp_raise_RuntimeError_varg(MP_ERROR_TEXT("%q init failed"), MP_QSTR_SPI); + } + + // MOSI or MISO may be None. claim_pin(clock); - claim_pin(mosi); - claim_pin(miso); + if (mosi != NULL) { + claim_pin(mosi); + } + if (miso != NULL) { + claim_pin(miso); + } self->clock_pin = clock; self->mosi_pin = mosi; self->miso_pin = miso; - self->spi_dev = cxd56_spibus_initialize(port); + self->spi_dev = spi_dev; } void common_hal_busio_spi_deinit(busio_spi_obj_t *self) { @@ -54,22 +66,49 @@ void common_hal_busio_spi_deinit(busio_spi_obj_t *self) { return; } - self->spi_dev = NULL; + common_hal_busio_spi_mark_deinit(self); reset_pin_number(self->clock_pin->number); - reset_pin_number(self->mosi_pin->number); - reset_pin_number(self->miso_pin->number); + if (self->mosi_pin != NULL) { + reset_pin_number(self->mosi_pin->number); + } + if (self->miso_pin != NULL) { + reset_pin_number(self->miso_pin->number); + } } bool common_hal_busio_spi_deinited(busio_spi_obj_t *self) { return self->spi_dev == NULL; } +void common_hal_busio_spi_mark_deinit(busio_spi_obj_t *self) { + self->spi_dev = NULL; +} + bool common_hal_busio_spi_configure(busio_spi_obj_t *self, uint32_t baudrate, uint8_t polarity, uint8_t phase, uint8_t bits) { uint8_t mode; - self->frequency = baudrate; - SPI_SETFREQUENCY(self->spi_dev, baudrate); + // SPI_SETFREQUENCY() picks the nearest available frequency and returns it, + // which can be HIGHER than requested (it overshoots at low frequencies). + // Treat baudrate as a ceiling: if the driver overshoots, bisect downward on + // the requested target for the highest available frequency that does not + // exceed baudrate. The driver returns the actual frequency each call, so we + // don't depend on its divisor internals. + uint32_t actual = SPI_SETFREQUENCY(self->spi_dev, baudrate); + if (actual > baudrate) { + uint32_t lo = 1; // f(lo) <= baudrate + uint32_t hi = baudrate; // f(hi) > baudrate (just measured) + while (hi - lo > 1) { + uint32_t mid = lo + (hi - lo) / 2; + if (SPI_SETFREQUENCY(self->spi_dev, mid) <= baudrate) { + lo = mid; + } else { + hi = mid; + } + } + actual = SPI_SETFREQUENCY(self->spi_dev, lo); + } + self->frequency = actual; if (polarity == 0) { if (phase == 0) { @@ -145,9 +184,3 @@ uint8_t common_hal_busio_spi_get_phase(busio_spi_obj_t *self) { uint8_t common_hal_busio_spi_get_polarity(busio_spi_obj_t *self) { return self->polarity; } - -void common_hal_busio_spi_never_reset(busio_spi_obj_t *self) { - never_reset_pin_number(self->clock_pin->number); - never_reset_pin_number(self->mosi_pin->number); - never_reset_pin_number(self->miso_pin->number); -} diff --git a/ports/cxd56/common-hal/busio/UART.c b/ports/cxd56/common-hal/busio/UART.c index 0b6a5dbd622..f425858ec5b 100644 --- a/ports/cxd56/common-hal/busio/UART.c +++ b/ports/cxd56/common-hal/busio/UART.c @@ -33,6 +33,10 @@ static busio_uart_dev_t busio_uart_dev[] = { {"/dev/ttyS2", &pin_UART2_TXD, &pin_UART2_RXD, -1}, }; +static void mark_deinit(busio_uart_obj_t *self) { + self->tx_pin = NULL; +} + 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, @@ -45,6 +49,8 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, char tmp; struct termios tio; + mark_deinit(self); + if ((rts != NULL) || (cts != NULL) || (rs485_dir != NULL) || (rs485_invert)) { mp_raise_NotImplementedError(MP_ERROR_TEXT("RS485")); } @@ -53,6 +59,11 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, mp_arg_validate_int(parity, BUSIO_UART_PARITY_NONE, MP_QSTR_parity); mp_arg_validate_int(stop, 1, MP_QSTR_stop); + // The one UART needs both TX and RX. + if (tx == NULL || rx == NULL) { + mp_raise_NotImplementedError(MP_ERROR_TEXT("UART needs TX & RX")); + } + self->number = -1; for (int i = 0; i < MP_ARRAY_SIZE(busio_uart_dev); i++) { @@ -106,10 +117,12 @@ void common_hal_busio_uart_deinit(busio_uart_obj_t *self) { reset_pin_number(self->tx_pin->number); reset_pin_number(self->rx_pin->number); + mark_deinit(self); } +// Per object: the device's fd may now belong to a newer UART. bool common_hal_busio_uart_deinited(busio_uart_obj_t *self) { - return busio_uart_dev[self->number].fd < 0; + return self->tx_pin == NULL; } size_t common_hal_busio_uart_read(busio_uart_obj_t *self, uint8_t *data, size_t len, int *errcode) { @@ -186,12 +199,3 @@ bool common_hal_busio_uart_ready_to_tx(busio_uart_obj_t *self) { ioctl(busio_uart_dev[self->number].fd, TCFLSH, (long unsigned int)NULL); return true; } - -void busio_uart_reset(void) { - for (int i = 0; i < MP_ARRAY_SIZE(busio_uart_dev); i++) { - if (busio_uart_dev[i].fd >= 0) { - close(busio_uart_dev[i].fd); - busio_uart_dev[i].fd = -1; - } - } -} diff --git a/ports/cxd56/common-hal/busio/UART.h b/ports/cxd56/common-hal/busio/UART.h index e642de75257..e861abc1809 100644 --- a/ports/cxd56/common-hal/busio/UART.h +++ b/ports/cxd56/common-hal/busio/UART.h @@ -18,5 +18,3 @@ typedef struct { uint32_t baudrate; uint32_t timeout_us; } busio_uart_obj_t; - -void busio_uart_reset(void); diff --git a/ports/cxd56/common-hal/camera/Camera.c b/ports/cxd56/common-hal/camera/Camera.c index c3c935a168d..56e7fd649d3 100644 --- a/ports/cxd56/common-hal/camera/Camera.c +++ b/ports/cxd56/common-hal/camera/Camera.c @@ -21,6 +21,8 @@ typedef struct { } camera_dev_t; static camera_dev_t camera_dev = {"/dev/video", -1}; +// Camera objects share the device. Close it when the last one is deinited. +static uint8_t camera_users = 0; typedef struct { uint16_t width; @@ -44,7 +46,7 @@ static const image_size_t isx019_image_size_table[] = { { VIDEO_HSIZE_QUADVGA, VIDEO_VSIZE_QUADVGA }, }; -static const char *get_imgsensor_name() { +static const char *get_imgsensor_name(void) { static struct v4l2_capability cap; ioctl(camera_dev.fd, VIDIOC_QUERYCAP, (unsigned long)&cap); @@ -113,7 +115,7 @@ static void camera_start_streaming(enum v4l2_buf_type type) { ioctl(camera_dev.fd, VIDIOC_STREAMON, (unsigned long)&type); } -static void camera_start_preview() { +static void camera_start_preview(void) { camera_set_format(V4L2_BUF_TYPE_VIDEO_CAPTURE, V4L2_PIX_FMT_UYVY, VIDEO_HSIZE_QVGA, VIDEO_VSIZE_QVGA); v4l2_buffer_t buf; @@ -126,13 +128,20 @@ static void camera_start_preview() { camera_start_streaming(V4L2_BUF_TYPE_VIDEO_CAPTURE); } +static void mark_deinit(camera_obj_t *self) { + self->active = false; +} + void common_hal_camera_construct(camera_obj_t *self) { + mark_deinit(self); + if (camera_dev.fd < 0) { if (video_initialize(camera_dev.devpath) < 0) { mp_raise_RuntimeError(MP_ERROR_TEXT("Camera init")); } camera_dev.fd = open(camera_dev.devpath, 0); if (camera_dev.fd < 0) { + video_uninitialize(); mp_raise_RuntimeError(MP_ERROR_TEXT("Camera init")); } } @@ -142,12 +151,20 @@ void common_hal_camera_construct(camera_obj_t *self) { camera_start_streaming(V4L2_BUF_TYPE_STILL_CAPTURE); sleep(1); + + camera_users++; + self->active = true; } void common_hal_camera_deinit(camera_obj_t *self) { if (common_hal_camera_deinited(self)) { return; } + mark_deinit(self); + camera_users--; + if (camera_users > 0) { + return; + } video_uninitialize(); @@ -156,7 +173,7 @@ void common_hal_camera_deinit(camera_obj_t *self) { } bool common_hal_camera_deinited(camera_obj_t *self) { - return camera_dev.fd < 0; + return !self->active; } size_t common_hal_camera_take_picture(camera_obj_t *self, uint8_t *buffer, size_t len, uint16_t width, uint16_t height, camera_imageformat_t format) { diff --git a/ports/cxd56/common-hal/camera/Camera.h b/ports/cxd56/common-hal/camera/Camera.h index c79fa29079c..d7d9f762c9f 100644 --- a/ports/cxd56/common-hal/camera/Camera.h +++ b/ports/cxd56/common-hal/camera/Camera.h @@ -10,4 +10,6 @@ typedef struct { mp_obj_base_t base; + // False on a zeroed object, so a failed construct reads as deinited. + bool active; } camera_obj_t; diff --git a/ports/cxd56/common-hal/digitalio/DigitalInOut.c b/ports/cxd56/common-hal/digitalio/DigitalInOut.c index 6936fe4f8cd..4c178877c53 100644 --- a/ports/cxd56/common-hal/digitalio/DigitalInOut.c +++ b/ports/cxd56/common-hal/digitalio/DigitalInOut.c @@ -11,7 +11,13 @@ #include "shared-bindings/digitalio/DigitalInOut.h" #include "shared-bindings/microcontroller/Pin.h" +static void mark_deinit(digitalio_digitalinout_obj_t *self) { + self->pin = NULL; +} + digitalinout_result_t common_hal_digitalio_digitalinout_construct(digitalio_digitalinout_obj_t *self, const mcu_pin_obj_t *pin) { + mark_deinit(self); + if (pin->analog) { raise_ValueError_invalid_pin(); } @@ -37,7 +43,7 @@ void common_hal_digitalio_digitalinout_deinit(digitalio_digitalinout_obj_t *self board_gpio_config(self->pin->number, 0, false, true, PIN_FLOAT); reset_pin_number(self->pin->number); - self->pin = NULL; + mark_deinit(self); } bool common_hal_digitalio_digitalinout_deinited(digitalio_digitalinout_obj_t *self) { @@ -115,7 +121,3 @@ digitalinout_result_t common_hal_digitalio_digitalinout_set_pull(digitalio_digit digitalio_pull_t common_hal_digitalio_digitalinout_get_pull(digitalio_digitalinout_obj_t *self) { return self->pull; } - -void common_hal_digitalio_digitalinout_never_reset(digitalio_digitalinout_obj_t *self) { - never_reset_pin_number(self->pin->number); -} diff --git a/ports/cxd56/common-hal/gnss/GNSS.c b/ports/cxd56/common-hal/gnss/GNSS.c index c3320234935..7980591e045 100644 --- a/ports/cxd56/common-hal/gnss/GNSS.c +++ b/ports/cxd56/common-hal/gnss/GNSS.c @@ -19,6 +19,8 @@ typedef struct { } gnss_dev_t; static gnss_dev_t gnss_dev = {"/dev/gps", -1}; +// GNSS objects share the device. Close it when the last one is deinited. +static uint8_t gnss_users = 0; static gnss_positionfix_t fix_to_positionfix_type(uint8_t fix) { switch (fix) { @@ -32,7 +34,13 @@ static gnss_positionfix_t fix_to_positionfix_type(uint8_t fix) { } } +static void mark_deinit(gnss_obj_t *self) { + self->active = false; +} + void common_hal_gnss_construct(gnss_obj_t *self, unsigned long selection) { + mark_deinit(self); + if (gnss_dev.fd < 0) { gnss_dev.fd = open(gnss_dev.devpath, O_RDONLY); if (gnss_dev.fd < 0) { @@ -59,19 +67,28 @@ void common_hal_gnss_construct(gnss_obj_t *self, unsigned long selection) { ioctl(gnss_dev.fd, CXD56_GNSS_IOCTL_SELECT_SATELLITE_SYSTEM, sel); ioctl(gnss_dev.fd, CXD56_GNSS_IOCTL_START, CXD56_GNSS_STMOD_COLD); + + gnss_users++; + self->active = true; } void common_hal_gnss_deinit(gnss_obj_t *self) { if (common_hal_gnss_deinited(self)) { return; } + mark_deinit(self); + gnss_users--; + if (gnss_users > 0) { + return; + } + ioctl(gnss_dev.fd, CXD56_GNSS_IOCTL_STOP, 0); close(gnss_dev.fd); gnss_dev.fd = -1; } bool common_hal_gnss_deinited(gnss_obj_t *self) { - return gnss_dev.fd < 0; + return !self->active; } void common_hal_gnss_update(gnss_obj_t *self) { diff --git a/ports/cxd56/common-hal/gnss/GNSS.h b/ports/cxd56/common-hal/gnss/GNSS.h index a974d747c95..bf7e0e2d201 100644 --- a/ports/cxd56/common-hal/gnss/GNSS.h +++ b/ports/cxd56/common-hal/gnss/GNSS.h @@ -12,6 +12,8 @@ typedef struct { mp_obj_base_t base; + // False on a zeroed object, so a failed construct reads as deinited. + bool active; unsigned long satellite_system; uint8_t fix; double latitude; diff --git a/ports/cxd56/common-hal/microcontroller/Pin.c b/ports/cxd56/common-hal/microcontroller/Pin.c index 0f9d6b1f3bd..9ffb04e774b 100644 --- a/ports/cxd56/common-hal/microcontroller/Pin.c +++ b/ports/cxd56/common-hal/microcontroller/Pin.c @@ -15,7 +15,6 @@ typedef struct { const mcu_pin_obj_t *pin; - bool reset; bool free; } pin_status_t; @@ -66,39 +65,39 @@ const mcu_pin_obj_t pin_HPADC0 = PIN(4, true); const mcu_pin_obj_t pin_HPADC1 = PIN(5, true); static pin_status_t pins[] = { - { &pin_UART2_RXD, true, true }, - { &pin_UART2_TXD, true, true }, - { &pin_HIF_IRQ_OUT, true, true }, - { &pin_PWM3, true, true }, - { &pin_SPI2_MOSI, true, true }, - { &pin_PWM1, true, true }, - { &pin_PWM0, true, true }, - { &pin_SPI3_CS1_X, true, true }, - { &pin_SPI2_MISO, true, true }, - { &pin_PWM2, true, true }, - { &pin_SPI4_CS_X, true, true }, - { &pin_SPI4_MOSI, true, true }, - { &pin_SPI4_MISO, true, true }, - { &pin_SPI4_SCK, true, true }, - { &pin_I2C0_BDT, true, true }, - { &pin_I2C0_BCK, true, true }, - { &pin_EMMC_DATA0, true, true }, - { &pin_EMMC_DATA1, true, true }, - { &pin_I2S0_DATA_OUT, true, true }, - { &pin_I2S0_DATA_IN, true, true }, - { &pin_EMMC_DATA2, true, true }, - { &pin_EMMC_DATA3, true, true }, - { &pin_SEN_IRQ_IN, true, true }, - { &pin_EMMC_CLK, true, true }, - { &pin_EMMC_CMD, true, true }, - { &pin_I2S0_LRCK, true, true }, - { &pin_I2S0_BCK, true, true }, - { &pin_UART2_CTS, true, true }, - { &pin_UART2_RTS, true, true }, - { &pin_I2S1_BCK, true, true }, - { &pin_I2S1_LRCK, true, true }, - { &pin_I2S1_DATA_IN, true, true }, - { &pin_I2S1_DATA_OUT, true, true }, + { &pin_UART2_RXD, true }, + { &pin_UART2_TXD, true }, + { &pin_HIF_IRQ_OUT, true }, + { &pin_PWM3, true }, + { &pin_SPI2_MOSI, true }, + { &pin_PWM1, true }, + { &pin_PWM0, true }, + { &pin_SPI3_CS1_X, true }, + { &pin_SPI2_MISO, true }, + { &pin_PWM2, true }, + { &pin_SPI4_CS_X, true }, + { &pin_SPI4_MOSI, true }, + { &pin_SPI4_MISO, true }, + { &pin_SPI4_SCK, true }, + { &pin_I2C0_BDT, true }, + { &pin_I2C0_BCK, true }, + { &pin_EMMC_DATA0, true }, + { &pin_EMMC_DATA1, true }, + { &pin_I2S0_DATA_OUT, true }, + { &pin_I2S0_DATA_IN, true }, + { &pin_EMMC_DATA2, true }, + { &pin_EMMC_DATA3, true }, + { &pin_SEN_IRQ_IN, true }, + { &pin_EMMC_CLK, true }, + { &pin_EMMC_CMD, true }, + { &pin_I2S0_LRCK, true }, + { &pin_I2S0_BCK, true }, + { &pin_UART2_CTS, true }, + { &pin_UART2_RTS, true }, + { &pin_I2S1_BCK, true }, + { &pin_I2S1_LRCK, true }, + { &pin_I2S1_DATA_IN, true }, + { &pin_I2S1_DATA_OUT, true }, }; bool common_hal_mcu_pin_is_free(const mcu_pin_obj_t *pin) { @@ -111,14 +110,6 @@ bool common_hal_mcu_pin_is_free(const mcu_pin_obj_t *pin) { return true; } -void never_reset_pin_number(uint8_t pin_number) { - for (int i = 0; i < MP_ARRAY_SIZE(pins); i++) { - if (pins[i].pin->number == pin_number) { - pins[i].reset = false; - } - } -} - void reset_pin_number(uint8_t pin_number) { for (int i = 0; i < MP_ARRAY_SIZE(pins); i++) { if (pins[i].pin->number == pin_number) { @@ -127,17 +118,6 @@ void reset_pin_number(uint8_t pin_number) { } } -void reset_all_pins(void) { - for (int i = 0; i < MP_ARRAY_SIZE(pins); i++) { - if (!pins[i].free && pins[i].reset) { - board_gpio_write(pins[i].pin->number, -1); - board_gpio_config(pins[i].pin->number, 0, false, true, PIN_FLOAT); - board_gpio_int(pins[i].pin->number, false); - board_gpio_intconfig(pins[i].pin->number, 0, false, NULL); - pins[i].free = true; - } - } -} void claim_pin(const mcu_pin_obj_t *pin) { for (int i = 0; i < MP_ARRAY_SIZE(pins); i++) { diff --git a/ports/cxd56/common-hal/microcontroller/Pin.h b/ports/cxd56/common-hal/microcontroller/Pin.h index 8c27abe76f2..94c01d2b7ad 100644 --- a/ports/cxd56/common-hal/microcontroller/Pin.h +++ b/ports/cxd56/common-hal/microcontroller/Pin.h @@ -69,7 +69,5 @@ extern const mcu_pin_obj_t pin_LPADC3; extern const mcu_pin_obj_t pin_HPADC0; 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); diff --git a/ports/cxd56/common-hal/microcontroller/Processor.c b/ports/cxd56/common-hal/microcontroller/Processor.c index 6b9d20afa04..a3e2a44a3e4 100644 --- a/ports/cxd56/common-hal/microcontroller/Processor.c +++ b/ports/cxd56/common-hal/microcontroller/Processor.c @@ -30,5 +30,5 @@ void common_hal_mcu_processor_get_uid(uint8_t raw_id[]) { } mcu_reset_reason_t common_hal_mcu_processor_get_reset_reason(void) { - return RESET_REASON_UNKNOWN; + return MCU_RESET_REASON_UNKNOWN; } diff --git a/ports/cxd56/common-hal/microcontroller/__init__.c b/ports/cxd56/common-hal/microcontroller/__init__.c index fa872f2807b..f7ac0c174ae 100644 --- a/ports/cxd56/common-hal/microcontroller/__init__.c +++ b/ports/cxd56/common-hal/microcontroller/__init__.c @@ -61,6 +61,8 @@ void common_hal_mcu_on_next_reset(mcu_runmode_t runmode) { void common_hal_mcu_reset(void) { filesystem_flush(); boardctl(BOARDIOC_RESET, 0); + // boardctl is noreturn in this case. + __builtin_unreachable(); } static const mp_rom_map_elem_t mcu_pin_globals_table[] = { diff --git a/ports/cxd56/common-hal/os/__init__.c b/ports/cxd56/common-hal/os/__init__.c index e1024108b07..902228f1db0 100644 --- a/ports/cxd56/common-hal/os/__init__.c +++ b/ports/cxd56/common-hal/os/__init__.c @@ -10,17 +10,7 @@ #include "py/objstr.h" #include "py/objtuple.h" +// No HW TRNG. bool common_hal_os_urandom(uint8_t *buffer, mp_uint_t length) { - uint32_t i = 0; - - while (i < length) { - uint32_t new_random = rand(); - for (int j = 0; j < 4 && i < length; j++) { - buffer[i] = new_random & 0xff; - i++; - new_random >>= 8; - } - } - - return true; + return false; } diff --git a/ports/cxd56/common-hal/pulseio/PulseIn.c b/ports/cxd56/common-hal/pulseio/PulseIn.c index f0063d3f0d8..7961ef14f8d 100644 --- a/ports/cxd56/common-hal/pulseio/PulseIn.c +++ b/ports/cxd56/common-hal/pulseio/PulseIn.c @@ -63,9 +63,15 @@ static int pulsein_interrupt_handler(int irq, FAR void *context, FAR void *arg) return 0; } +static void mark_deinit(pulseio_pulsein_obj_t *self) { + self->pin = NULL; +} + 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)); + mark_deinit(self); + + self->buffer = (uint16_t *)m_malloc_without_collect(maxlen * sizeof(uint16_t)); if (self->buffer == NULL) { m_malloc_fail(maxlen * sizeof(uint16_t)); } @@ -80,6 +86,8 @@ void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t *self, int irq = pulsein_set_config(self, true); if (irq < 0) { + // The pin is set for pulsein_set_config() but not claimed yet. + mark_deinit(self); mp_raise_RuntimeError(MP_ERROR_TEXT("Internal resource(s) in use")); } else { pulsein_objects[irq - CXD56_IRQ_EXDEVICE_0] = self; @@ -99,7 +107,7 @@ void common_hal_pulseio_pulsein_deinit(pulseio_pulsein_obj_t *self) { board_gpio_intconfig(self->pin->number, 0, false, NULL); reset_pin_number(self->pin->number); - self->pin = NULL; + mark_deinit(self); } bool common_hal_pulseio_pulsein_deinited(pulseio_pulsein_obj_t *self) { diff --git a/ports/cxd56/common-hal/pulseio/PulseOut.c b/ports/cxd56/common-hal/pulseio/PulseOut.c index a3023cc8973..f3275abf8a9 100644 --- a/ports/cxd56/common-hal/pulseio/PulseOut.c +++ b/ports/cxd56/common-hal/pulseio/PulseOut.c @@ -17,6 +17,8 @@ static uint16_t *pulse_buffer = NULL; static uint16_t pulse_index = 0; static uint16_t pulse_length; static int pulse_fd = -1; +// PulseOuts share the timer. Close it when the last one is deinited. +static uint8_t pulse_users = 0; static bool pulseout_timer_handler(uint32_t *next_interval_us, void *arg) { uint8_t pwm_num = (uint8_t)(int)arg; @@ -53,9 +55,12 @@ void common_hal_pulseio_pulseout_construct(pulseio_pulseout_obj_t *self, } if (pulse_fd < 0) { + // Don't leave the PWMOut claimed. + common_hal_pwmio_pwmout_deinit(&self->pwmout); mp_raise_RuntimeError(MP_ERROR_TEXT("All timers in use")); } + pulse_users++; self->pwm_num = self->pwmout.number; } @@ -64,17 +69,20 @@ void common_hal_pulseio_pulseout_deinit(pulseio_pulseout_obj_t *self) { return; } - ioctl(pulse_fd, TCIOC_STOP, 0); - close(pulse_fd); - pulse_fd = -1; - common_hal_pwmio_pwmout_deinit(&self->pwmout); - pulse_buffer = NULL; + pulse_users--; + if (pulse_users == 0) { + ioctl(pulse_fd, TCIOC_STOP, 0); + close(pulse_fd); + pulse_fd = -1; + pulse_buffer = NULL; + } } +// Per object: the timer is shared with any other PulseOuts. bool common_hal_pulseio_pulseout_deinited(pulseio_pulseout_obj_t *self) { - return pulse_fd < 0; + return common_hal_pwmio_pwmout_deinited(&self->pwmout); } void common_hal_pulseio_pulseout_send(pulseio_pulseout_obj_t *self, uint16_t *pulses, uint16_t len) { diff --git a/ports/cxd56/common-hal/pwmio/PWMOut.c b/ports/cxd56/common-hal/pwmio/PWMOut.c index f754858f306..ec40d2d4660 100644 --- a/ports/cxd56/common-hal/pwmio/PWMOut.c +++ b/ports/cxd56/common-hal/pwmio/PWMOut.c @@ -16,19 +16,23 @@ typedef struct { const char *devpath; const mcu_pin_obj_t *pin; int fd; - bool reset; } pwmout_dev_t; static pwmout_dev_t pwmout_dev[] = { - {"/dev/pwm0", &pin_PWM0, -1, true}, - {"/dev/pwm1", &pin_PWM1, -1, true}, - {"/dev/pwm2", &pin_PWM2, -1, true}, - {"/dev/pwm3", &pin_PWM3, -1, true} + {"/dev/pwm0", &pin_PWM0, -1}, + {"/dev/pwm1", &pin_PWM1, -1}, + {"/dev/pwm2", &pin_PWM2, -1}, + {"/dev/pwm3", &pin_PWM3, -1} }; +static void mark_deinit(pwmio_pwmout_obj_t *self) { + self->pin = NULL; +} + 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) { + mark_deinit(self); self->number = -1; for (int i = 0; i < MP_ARRAY_SIZE(pwmout_dev); i++) { @@ -54,6 +58,8 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t *self, self->variable_frequency = variable_frequency; if (ioctl(pwmout_dev[self->number].fd, PWMIOC_SETCHARACTERISTICS, (unsigned long)((uintptr_t)&self->info)) < 0) { + close(pwmout_dev[self->number].fd); + pwmout_dev[self->number].fd = -1; mp_arg_error_invalid(MP_QSTR_frequency); } ioctl(pwmout_dev[self->number].fd, PWMIOC_START, 0); @@ -70,18 +76,17 @@ void common_hal_pwmio_pwmout_deinit(pwmio_pwmout_obj_t *self) { return; } - pwmout_dev[self->number].reset = true; - ioctl(pwmout_dev[self->number].fd, PWMIOC_STOP, 0); close(pwmout_dev[self->number].fd); pwmout_dev[self->number].fd = -1; reset_pin_number(self->pin->number); - self->pin = NULL; + mark_deinit(self); } +// Per object: the device's fd may now belong to a newer PWMOut. bool common_hal_pwmio_pwmout_deinited(pwmio_pwmout_obj_t *self) { - return pwmout_dev[self->number].fd < 0; + return self->pin == NULL; } void common_hal_pwmio_pwmout_set_duty_cycle(pwmio_pwmout_obj_t *self, uint16_t duty) { @@ -110,12 +115,6 @@ bool common_hal_pwmio_pwmout_get_variable_frequency(pwmio_pwmout_obj_t *self) { return self->variable_frequency; } -void common_hal_pwmio_pwmout_never_reset(pwmio_pwmout_obj_t *self) { - never_reset_pin_number(self->pin->number); - - pwmout_dev[self->number].reset = false; -} - void pwmout_start(uint8_t pwm_num) { ioctl(pwmout_dev[pwm_num].fd, PWMIOC_START, 0); } diff --git a/ports/cxd56/common-hal/sdioio/SDCard.c b/ports/cxd56/common-hal/sdioio/SDCard.c index aa1d1371770..3fa4dd0c1be 100644 --- a/ports/cxd56/common-hal/sdioio/SDCard.c +++ b/ports/cxd56/common-hal/sdioio/SDCard.c @@ -8,6 +8,7 @@ #include #include +#include "extmod/vfs.h" #include "py/mperrno.h" #include "py/runtime.h" @@ -17,30 +18,39 @@ #define DATA_PINS_NUM 4 +static void mark_deinit(sdioio_sdcard_obj_t *self) { + self->inode = NULL; +} + 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, const mcu_pin_obj_t **data, uint32_t frequency) { struct geometry geo; + mark_deinit(self); + if (clock->number != PIN_SDIO_CLK || command->number != PIN_SDIO_CMD) { raise_ValueError_invalid_pins(); } - uint8_t data_pins_num = 0; + // Only 4-bit mode on the four SDIO data pins, in order. + static const uint8_t data_pin_numbers[DATA_PINS_NUM] = { + PIN_SDIO_DATA0, PIN_SDIO_DATA1, PIN_SDIO_DATA2, PIN_SDIO_DATA3, + }; + if (num_data != DATA_PINS_NUM) { + raise_ValueError_invalid_pins(); + } for (uint8_t i = 0; i < DATA_PINS_NUM; i++) { - if (data[i]->number != PIN_SDIO_DATA0 || data[i]->number != PIN_SDIO_DATA1 || - data[i]->number != PIN_SDIO_DATA2 || data[i]->number != PIN_SDIO_DATA3) { - data_pins_num++; + if (data[i]->number != data_pin_numbers[i]) { + raise_ValueError_invalid_pins(); } } - if (data_pins_num != DATA_PINS_NUM) { - raise_ValueError_invalid_pins(); - } - - if (open_blockdriver("/dev/mmcsd0", 0, &self->inode) < 0) { + struct inode *inode; + if (open_blockdriver("/dev/mmcsd0", 0, &inode) < 0) { mp_raise_RuntimeError(MP_ERROR_TEXT("SDCard init")); } + self->inode = inode; self->inode->u.i_bops->geometry(self->inode, &geo); @@ -59,8 +69,11 @@ void common_hal_sdioio_sdcard_construct(sdioio_sdcard_obj_t *self, } void common_hal_sdioio_sdcard_deinit(sdioio_sdcard_obj_t *self) { + if (common_hal_sdioio_sdcard_deinited(self)) { + return; + } close_blockdriver(self->inode); - self->inode = NULL; + mark_deinit(self); reset_pin_number(self->clock_pin->number); reset_pin_number(self->command_pin->number); @@ -95,28 +108,71 @@ 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) { +// Native function for VFS blockdev layer +mp_negative_errno_t sdioio_sdcard_readblocks(mp_obj_t self_in, uint8_t *buf, + uint32_t start_block, uint32_t num_blocks) { + sdioio_sdcard_obj_t *self = MP_OBJ_TO_PTR(self_in); + int result = self->inode->u.i_bops->read(self->inode, buf, start_block, num_blocks); + if (result < 0) { + return -MP_EIO; + } + return 0; +} + +mp_negative_errno_t 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(); } check_whole_block(bufinfo); - return self->inode->u.i_bops->read(self->inode, bufinfo->buf, start_block, bufinfo->len / 512); + uint32_t num_blocks = bufinfo->len / 512; + return sdioio_sdcard_readblocks(MP_OBJ_FROM_PTR(self), bufinfo->buf, + start_block, num_blocks); +} + +// Native function for VFS blockdev layer +mp_negative_errno_t sdioio_sdcard_writeblocks(mp_obj_t self_in, uint8_t *buf, + uint32_t start_block, uint32_t num_blocks) { + sdioio_sdcard_obj_t *self = MP_OBJ_TO_PTR(self_in); + int result = self->inode->u.i_bops->write(self->inode, buf, start_block, num_blocks); + if (result < 0) { + return -MP_EIO; + } + return 0; } -int common_hal_sdioio_sdcard_writeblocks(sdioio_sdcard_obj_t *self, uint32_t start_block, mp_buffer_info_t *bufinfo) { +mp_negative_errno_t 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); + uint32_t num_blocks = bufinfo->len / 512; + return sdioio_sdcard_writeblocks(MP_OBJ_FROM_PTR(self), bufinfo->buf, + start_block, num_blocks); } -void common_hal_sdioio_sdcard_never_reset(sdioio_sdcard_obj_t *self) { - never_reset_pin_number(self->clock_pin->number); - never_reset_pin_number(self->command_pin->number); - for (uint8_t i = 0; i < DATA_PINS_NUM; i++) { - never_reset_pin_number(self->data_pins[i]->number); +// Native function for VFS blockdev layer +bool sdioio_sdcard_ioctl(mp_obj_t self_in, size_t cmd, size_t arg, + mp_int_t *out_value) { + sdioio_sdcard_obj_t *self = MP_OBJ_TO_PTR(self_in); + *out_value = 0; + + switch (cmd) { + case MP_BLOCKDEV_IOCTL_DEINIT: + case MP_BLOCKDEV_IOCTL_SYNC: + // SDIO operations are synchronous, no action needed + return true; + + case MP_BLOCKDEV_IOCTL_BLOCK_COUNT: + *out_value = common_hal_sdioio_sdcard_get_count(self); + return true; + + case MP_BLOCKDEV_IOCTL_BLOCK_SIZE: + *out_value = 512; // SD cards use 512-byte sectors + return true; + + default: + return false; // Unsupported command } } diff --git a/ports/cxd56/mkspk/clefia.c b/ports/cxd56/mkspk/clefia.c index e946ee5348a..d36f638fa0b 100644 --- a/ports/cxd56/mkspk/clefia.c +++ b/ports/cxd56/mkspk/clefia.c @@ -466,16 +466,16 @@ 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) { - unsigned char rin[16]; + unsigned char r_in[16]; unsigned char rout[16]; - bytecpy(rin, pt, 16); + bytecpy(r_in, pt, 16); - bytexor(rin + 4, rin + 4, rk + 0, 4); /* initial key whitening */ - bytexor(rin + 12, rin + 12, rk + 4, 4); + bytexor(r_in + 4, r_in + 4, rk + 0, 4); /* initial key whitening */ + bytexor(r_in + 12, r_in + 12, rk + 4, 4); rk += 8; - clefiagfn4(rout, rin, rk, r); /* GFN_{4,r} */ + clefiagfn4(rout, r_in, rk, r); /* GFN_{4,r} */ bytecpy(ct, rout, 16); bytexor(ct + 4, ct + 4, rk + r * 8 + 0, 4); /* final key whitening */ diff --git a/ports/cxd56/mpconfigport.h b/ports/cxd56/mpconfigport.h index 3bcb2528687..ec606a76547 100644 --- a/ports/cxd56/mpconfigport.h +++ b/ports/cxd56/mpconfigport.h @@ -8,6 +8,9 @@ #define MICROPY_PY_SYS_PLATFORM "CXD56" +// SD card socket on board is configured for sdioio, which is not supported for automatic USB presentation. +#define CIRCUITPY_SDCARD_USB (0) + // 64kiB stack #define CIRCUITPY_DEFAULT_STACK_SIZE (0x10000) @@ -20,6 +23,8 @@ #define USB_MSC_EP_NUM_OUT (5) #define USB_MSC_EP_NUM_IN (4) +#define CIRCUITPY_USB_DEVICE_HIGH_SPEED (1) + #include "py/circuitpy_mpconfig.h" #define MICROPY_BYTES_PER_GC_BLOCK (32) diff --git a/ports/cxd56/mpconfigport.mk b/ports/cxd56/mpconfigport.mk index cb54233a07e..ebfaa91f251 100644 --- a/ports/cxd56/mpconfigport.mk +++ b/ports/cxd56/mpconfigport.mk @@ -1,5 +1,3 @@ -USB_HIGHSPEED = 1 - # Number of USB endpoint pairs. USB_NUM_ENDPOINT_PAIRS = 6 diff --git a/ports/cxd56/supervisor/cpu.s b/ports/cxd56/supervisor/cpu.s deleted file mode 100755 index 9e6807a5e2e..00000000000 --- a/ports/cxd56/supervisor/cpu.s +++ /dev/null @@ -1,27 +0,0 @@ -.syntax unified -.cpu cortex-m4 -.thumb -.text -.align 2 - -@ uint cpu_get_regs_and_sp(r0=uint regs[10]) -.global cpu_get_regs_and_sp -.thumb -.thumb_func -.type cpu_get_regs_and_sp, %function -cpu_get_regs_and_sp: -@ store registers into given array -str r4, [r0], #4 -str r5, [r0], #4 -str r6, [r0], #4 -str r7, [r0], #4 -str r8, [r0], #4 -str r9, [r0], #4 -str r10, [r0], #4 -str r11, [r0], #4 -str r12, [r0], #4 -str r13, [r0], #4 - -@ return the sp -mov r0, sp -bx lr diff --git a/ports/cxd56/supervisor/port.c b/ports/cxd56/supervisor/port.c index 237013ff2bd..b1d1887fdd8 100644 --- a/ports/cxd56/supervisor/port.c +++ b/ports/cxd56/supervisor/port.c @@ -23,7 +23,6 @@ #include "common-hal/microcontroller/Pin.h" #include "common-hal/analogio/AnalogIn.h" -#include "common-hal/busio/UART.h" #define SPRESENSE_MEM_ALIGN (32) @@ -57,17 +56,9 @@ void reset_cpu(void) { } void reset_port(void) { - #if CIRCUITPY_ANALOGIO - analogin_reset(); - #endif - #if CIRCUITPY_BUSIO - busio_uart_reset(); - #endif #if CIRCUITPY_RTC rtc_reset(); #endif - - reset_all_pins(); } void reset_to_bootloader(void) { @@ -124,7 +115,9 @@ void board_timerhook(void) { uint64_t port_get_raw_ticks(uint8_t *subticks) { uint64_t count = cxd56_rtc_count(); - *subticks = count % 32; + if (subticks != NULL) { + *subticks = count % 32; + } return count / 32; } diff --git a/ports/espressif/AGENTS.md b/ports/espressif/AGENTS.md new file mode 100644 index 00000000000..2e39b1ba086 --- /dev/null +++ b/ports/espressif/AGENTS.md @@ -0,0 +1 @@ +Source esp-idf/export.sh before running make. diff --git a/ports/espressif/CMakeLists.txt b/ports/espressif/CMakeLists.txt index 387a18dac09..c644a966446 100644 --- a/ports/espressif/CMakeLists.txt +++ b/ports/espressif/CMakeLists.txt @@ -5,10 +5,32 @@ cmake_minimum_required(VERSION 3.16) set(ENV{IDF_PATH} ${CMAKE_SOURCE_DIR}/esp-idf) # The component list here determines what options we get in menuconfig and what the ninja file can build. -set(COMPONENTS bt driver esp_driver_dac esp_driver_gpio esp_driver_gptimer esp_driver_i2c esp_driver_i2s esp_driver_ledc esp_driver_pcnt esp_driver_rmt esp_driver_spi esp_driver_tsens esp_driver_uart esp-tls esp_adc_cal esp_event esp_netif esp_psram esp_wifi esptool_py freertos log lwip main mbedtls mdns soc ulp usb wpa_supplicant esp-camera esp_lcd vfs esp_vfs_console sdmmc) +# Keep this split into separate set()/list() calls so additions merge easily. +# Core components +set(COMPONENTS bt driver esptool_py freertos log main mbedtls pthread soc) +# Peripheral drivers +list(APPEND COMPONENTS esp_driver_dac esp_driver_gpio esp_driver_gptimer esp_driver_i2c esp_driver_i2s esp_driver_jpeg esp_driver_ledc esp_driver_pcnt esp_driver_ppa esp_driver_rmt esp_driver_sdmmc esp_driver_spi esp_driver_touch_sens esp_driver_tsens esp_driver_uart) +# Networking +list(APPEND COMPONENTS esp_eth esp-tls esp_event esp_netif esp_wifi lwip mdns wpa_supplicant) +# Misc +list(APPEND COMPONENTS esp_adc esp_adc_cal esp_psram esp_security ulp vfs esp_vfs_console esp_stdio sdmmc usb) +# Display and camera +list(APPEND COMPONENTS esp-camera esp_lcd) + +if(CIRCUITPY_MIPICSI) + list(APPEND COMPONENTS esp_driver_cam esp_hal_cam) +endif() + set(EXTRA_COMPONENT_DIRS "esp-protocols/components/mdns" "esp-camera") +set(EXTRA_COMPONENT_DIRS "${EXTRA_COMPONENT_DIRS}" "${CMAKE_SOURCE_DIR}/../../lib/lvgl") + +if(CIRCUITPY_ESP_HOSTED) + list(APPEND EXTRA_COMPONENT_DIRS "esp-hosted") + list(APPEND COMPONENTS esp-hosted) +endif() include($ENV{IDF_PATH}/tools/cmake/project.cmake) +set(ENV{ESP_IDF_VERSION} "${IDF_VERSION_MAJOR}.${IDF_VERSION_MINOR}") project(circuitpython) idf_build_set_property(__OUTPUT_SDKCONFIG 0) diff --git a/ports/espressif/Makefile b/ports/espressif/Makefile index ff64a3b03cf..c972a835326 100644 --- a/ports/espressif/Makefile +++ b/ports/espressif/Makefile @@ -6,8 +6,13 @@ include ../../py/circuitpy_mkenv.mk +# Keep dependency selection identical during automatic CMake reconfiguration. +export IDF_COMPONENT_MANAGER = 0 + ifeq ($(IDF_TARGET),esp32s3) BT_IDF_TARGET = esp32c3 +else ifeq ($(IDF_TARGET),esp32c61) +BT_IDF_TARGET = esp32c6 else BT_IDF_TARGET = $(IDF_TARGET) endif @@ -17,6 +22,10 @@ endif ####################################### INC += \ + -I../../lib/lvgl \ + -I../../lib/lvgl/include \ + -I../../lib/lvgl/src \ + -I./lvgl \ -I.\ -I./boards \ -I./boards/$(BOARD) \ @@ -45,44 +54,54 @@ INC += \ -isystem esp-idf/components/bt/host/nimble/nimble/porting/nimble/include \ -isystem esp-idf/components/bt/host/nimble/nimble/porting/npl/freertos/include \ -isystem esp-idf/components/bt/host/nimble/port/include \ - -isystem esp-idf/components/driver/touch_sensor/include \ - -isystem esp-idf/components/driver/touch_sensor/$(IDF_TARGET)/include \ + -isystem esp-idf/components/bt/porting/include \ + -isystem esp-idf/components/bt/porting/npl/freertos/include \ + -isystem esp-idf/components/bt/porting/transport/include \ + -isystem esp-idf/components/esp_driver_touch_sens/include \ -isystem esp-idf/components/driver/twai/include \ + -isystem esp-idf/components/driver/i2c/include \ -isystem esp-idf/components/efuse/include \ -isystem esp-idf/components/efuse/$(IDF_TARGET)/include \ - -isystem esp-idf/components/$(IDF_TARGET)/include \ -isystem esp-idf/components/esp_adc/include \ -isystem esp-idf/components/esp_adc/$(IDF_TARGET)/include \ -isystem esp-idf/components/esp_app_format/include \ -isystem esp-idf/components/esp_bootloader_format/include \ -isystem esp-idf/components/esp_common/include \ - -isystem esp-idf/components/esp_driver_deprecated \ -isystem esp-idf/components/esp_driver_dac/include \ -isystem esp-idf/components/esp_driver_gpio/include \ -isystem esp-idf/components/esp_driver_gptimer/include \ -isystem esp-idf/components/esp_driver_i2c/include \ -isystem esp-idf/components/esp_driver_i2s/include \ - -isystem esp-idf/components/esp_driver_$(IDF_TARGET)/include \ + -isystem esp-idf/components/esp_driver_jpeg/include \ -isystem esp-idf/components/esp_driver_ledc/include \ + -isystem esp-idf/components/esp_driver_parlio/include \ -isystem esp-idf/components/esp_driver_pcnt/include \ + -isystem esp-idf/components/esp_driver_ppa/include \ -isystem esp-idf/components/esp_driver_rmt/include \ -isystem esp-idf/components/esp_driver_sdio/include \ -isystem esp-idf/components/esp_driver_sdmmc/include \ + -isystem esp-idf/components/esp_driver_sdmmc/legacy/include \ + -isystem esp-idf/components/esp_driver_dma/include \ -isystem esp-idf/components/esp_driver_spi/include \ -isystem esp-idf/components/esp_driver_tsens/include \ -isystem esp-idf/components/esp_driver_uart/include \ -isystem esp-idf/components/esp_event/include \ - -isystem esp-idf/components/esp_hw_support/dma/include \ -isystem esp-idf/components/esp_hw_support/include \ -isystem esp-idf/components/esp_hw_support/include/soc \ -isystem esp-idf/components/esp_hw_support/port/$(IDF_TARGET)/private_include \ + -isystem esp-idf/components/esp_hw_support/etm/include \ -isystem esp-idf/components/esp_mm/include \ + -isystem esp-idf/components/esp_eth/include \ -isystem esp-idf/components/esp_netif/include \ + -isystem esp-idf/components/esp_blockdev/include \ -isystem esp-idf/components/esp_partition/include \ -isystem esp-idf/components/esp_pm/include \ -isystem esp-idf/components/esp_psram/include \ -isystem esp-idf/components/esp_ringbuf/include \ -isystem esp-idf/components/esp_rom/include \ + -isystem esp-idf/components/esp_rom/$(IDF_TARGET)/include \ + -isystem esp-idf/components/esp_rom/$(IDF_TARGET)/include/$(IDF_TARGET) \ + -isystem esp-idf/components/esp_security/include \ -isystem esp-idf/components/esp_system/include \ -isystem esp-idf/components/esp_timer/include \ -isystem esp-idf/components/esp_wifi/include \ @@ -99,6 +118,48 @@ INC += \ -isystem esp-idf/components/hal/include \ -isystem esp-idf/components/hal/$(IDF_TARGET)/include \ -isystem esp-idf/components/hal/platform_port/include \ + -isystem esp-idf/components/esp_hal_gpio/include \ + -isystem esp-idf/components/esp_hal_gpio/$(IDF_TARGET)/include \ + -isystem esp-idf/components/esp_hal_ppa/include \ + -isystem esp-idf/components/esp_hal_ppa/$(IDF_TARGET)/include \ + -isystem esp-idf/components/esp_hal_timg/include \ + -isystem esp-idf/components/esp_hal_ana_conv/include \ + -isystem esp-idf/components/esp_hal_touch_sens/include \ + -isystem esp-idf/components/esp_hal_uart/include \ + -isystem esp-idf/components/esp_hal_gpspi/include \ + -isystem esp-idf/components/esp_hal_i2c/include \ + -isystem esp-idf/components/esp_hal_i2s/include \ + -isystem esp-idf/components/esp_hal_i2s/$(IDF_TARGET)/include \ + -isystem esp-idf/components/esp_hal_jpeg/include \ + -isystem esp-idf/components/esp_hal_jpeg/$(IDF_TARGET)/include \ + -isystem esp-idf/components/esp_hal_ledc/include \ + -isystem esp-idf/components/esp_hal_ledc/$(IDF_TARGET)/include \ + -isystem esp-idf/components/esp_hal_pcnt/include \ + -isystem esp-idf/components/esp_hal_rmt/include \ + -isystem esp-idf/components/esp_hal_rmt/$(IDF_TARGET)/include \ + -isystem esp-idf/components/esp_hal_twai/include \ + -isystem esp-idf/components/esp_hal_twai/$(IDF_TARGET)/include \ + -isystem esp-idf/components/esp_hal_timg/$(IDF_TARGET)/include \ + -isystem esp-idf/components/esp_hal_gpspi/$(IDF_TARGET)/include \ + -isystem esp-idf/components/esp_hal_dma/include \ + -isystem esp-idf/components/esp_hal_dma/$(IDF_TARGET)/include \ + -isystem esp-idf/components/esp_hal_emac/include \ + -isystem esp-idf/components/esp_hal_emac/$(IDF_TARGET)/include \ + -isystem esp-idf/components/esp_hal_lcd/include \ + -isystem esp-idf/components/esp_hal_lcd/$(IDF_TARGET)/include \ + -isystem esp-idf/components/esp_hal_sd/include \ + -isystem esp-idf/components/esp_hal_sd/$(IDF_TARGET)/include \ + -isystem esp-idf/components/esp_hal_usb/include \ + -isystem esp-idf/components/esp_hal_usb/$(IDF_TARGET)/include \ + -isystem esp-idf/components/esp_hal_parlio/include \ + -isystem esp-idf/components/esp_hal_pmu/include \ + -isystem esp-idf/components/esp_hal_pmu/$(IDF_TARGET)/include \ + -isystem esp-idf/components/esp_hal_wdt/include \ + -isystem esp-idf/components/esp_hal_wdt/$(IDF_TARGET)/include \ + -isystem esp-idf/components/esp_hal_security/include \ + -isystem esp-idf/components/esp_hal_regi2c/include \ + -isystem esp-idf/components/esp_hal_regi2c/$(IDF_TARGET)/include \ + -isystem esp-idf/components/esp_hal_systimer/include \ -isystem esp-idf/components/heap/include \ -isystem esp-idf/components/log/include \ -isystem esp-idf/components/lwip/include \ @@ -106,21 +167,21 @@ INC += \ -isystem esp-idf/components/lwip/port/include \ -isystem esp-idf/components/lwip/port/esp32xx/include \ -isystem esp-idf/components/lwip/port/freertos/include \ - -isystem esp-idf/components/mbedtls/esp_crt_bundle/include \ -isystem esp-idf/components/mbedtls/mbedtls/include \ + -isystem esp-idf/components/mbedtls/mbedtls/tf-psa-crypto/include \ + -isystem esp-idf/components/mbedtls/mbedtls/tf-psa-crypto/drivers/builtin/include \ -isystem esp-idf/components/mbedtls/port/include \ - -isystem esp-idf/components/newlib/platform_include \ + -isystem esp-idf/components/mbedtls/port/psa_driver/include \ + -isystem esp-idf/components/esp_libc/platform_include \ -isystem esp-idf/components/nvs_flash/include \ - -isystem esp-idf/components/sdio/include \ -isystem esp-idf/components/sdmmc/include \ -isystem esp-idf/components/soc/include \ -isystem esp-idf/components/soc/$(IDF_TARGET)/include \ + -isystem esp-idf/components/soc/$(IDF_TARGET)/register \ -isystem esp-idf/components/spi_flash/include \ - -isystem esp-idf/components/usb/include \ -isystem esp-idf/components/ulp/ulp_fsm/include \ -isystem esp-idf/components/ulp/ulp_riscv/include \ -isystem esp-idf/components/ulp/ulp_common/include \ - -isystem esp-idf/components/ulp/ulp_common/include/$(IDF_TARGET) \ -isystem esp-idf/components/$(IDF_TARGET_ARCH)/include \ -isystem esp-idf/components/$(IDF_TARGET_ARCH)/$(IDF_TARGET)/include \ -isystem esp-protocols/components/mdns/include @@ -129,9 +190,12 @@ CFLAGS += \ -DHAVE_CONFIG_H \ -DESP_PLATFORM=1 \ -DMBEDTLS_CONFIG_FILE=\"mbedtls/esp_config.h\" \ + -DMBEDTLS_DECLARE_PRIVATE_IDENTIFIERS \ -DMBEDTLS_PADLOCK_FILE=\"ports/espressif/esp-idf/components/mbedtls/mbedtls/library/padlock.h\" \ -DUNITY_INCLUDE_CONFIG_H -DWITH_POSIX \ - -DMP3DEC_GENERIC + -DMP3DEC_GENERIC \ + -DSOC_MMU_PAGE_SIZE=CONFIG_MMU_PAGE_SIZE \ + -DSOC_XTAL_FREQ_MHZ=CONFIG_XTAL_FREQ # Make our canary value match FreeRTOS's # This define is in FreeRTOS as tskSTACK_FILL_BYTE 0xa5U which we expand out to a full word. @@ -145,6 +209,8 @@ CFLAGS += -DSTACK_CANARY_VALUE=0xa5a5a5a5 REGISTRATION_FUNCTIONS = \ -u ld_include_highint_hdl \ -u __cxx_fatal_exception \ + -u __cxx_init_dummy \ + -u __cxa_guard_dummy \ -u esp_app_desc \ -u esp_timer_init_include_func \ -u uart_vfs_include_dev_init \ @@ -152,13 +218,75 @@ REGISTRATION_FUNCTIONS = \ -u __ubsan_include \ -u esp_system_include_startup_funcs \ -u esp_efuse_startup_include_func \ - -u newlib_include_heap_impl \ - -u newlib_include_syscalls_impl \ - -u newlib_include_pthread_impl \ - -u newlib_include_assert_impl \ - -u newlib_include_init_funcs \ + -u esp_libc_include_heap_impl \ + -u esp_libc_include_reent_syscalls_impl \ + -u esp_libc_include_syscalls_impl \ + -u esp_libc_include_pthread_impl \ + -u esp_libc_include_assert_impl \ + -u esp_libc_include_getentropy_impl \ + -u esp_libc_include_init_funcs \ + -u esp_libc_init_funcs \ -u include_esp_phy_override \ - -u vfs_include_syscalls_impl + -u vfs_include_syscalls_impl \ + -u esp_vfs_include_nullfs_register \ + -u usb_serial_jtag_vfs_include_dev_init \ + -u usb_serial_jtag_connection_monitor_include \ + -u esp_flash_spi_init_include_func \ + -u pthread_include_pthread_impl \ + -u pthread_include_pthread_cond_var_impl \ + -u pthread_include_pthread_local_storage_impl \ + -u pthread_include_pthread_rwlock_impl \ + -u pthread_include_pthread_semaphore_impl \ + -u esp_security_init_include_impl \ + -u mbedtls_psa_crypto_init_include_impl + +# Video DMA destinations come from the Python heap (user bytearrays), and +# the cache line is 64 bytes on the P4, so make GC blocks 64 bytes as well. +# supervisor/port.c aligns the PSRAM heap areas to the same value. +ifeq ($(IDF_TARGET),esp32p4) +CFLAGS += -DMICROPY_BYTES_PER_GC_BLOCK=64 +endif + +# RISC-V picolibc ships optimized memcpy/memset/etc. that need forcing +# (gated by CONFIG_LIBC_OPTIMIZED_MISALIGNED_ACCESS in IDF's esp_libc CMake). +ifeq ($(IDF_TARGET_ARCH),riscv) +REGISTRATION_FUNCTIONS += \ + -u esp_libc_include_memcpy_impl \ + -u esp_libc_include_memmove_impl \ + -u esp_libc_include_memcmp_impl \ + -u esp_libc_include_memset_impl \ + -u esp_libc_include_strcpy_impl \ + -u esp_libc_include_strncpy_impl \ + -u esp_libc_include_strcmp_impl \ + -u esp_libc_include_strncmp_impl +endif + +# Chips with PAU + TOP power-down (SOC_PAU_SUPPORTED && SOC_PM_SUPPORT_TOP_PD): +# C5, C6, C61, H2, H21, H4, P4. These pull in sleep_gpio + system-peripheral +# retention, and the SW-driven RISC-V CPU register save/restore path. +ifneq ($(filter $(IDF_TARGET),esp32c5 esp32c6 esp32c61 esp32h2 esp32h21 esp32h4 esp32p4 esp32s31),) +REGISTRATION_FUNCTIONS += \ + -u esp_sleep_gpio_include \ + -u sleep_system_peripheral_dummy \ + -u rv_core_critical_regs_save \ + -u rv_core_critical_regs_restore +endif + +# RISC-V chips with a hardware FPU (H4, P4, S31) need FPU register save/restore +# alongside the CPU retention path. +ifneq ($(filter $(IDF_TARGET),esp32h4 esp32p4 esp32s31),) +REGISTRATION_FUNCTIONS += \ + -u rv_core_fpu_save \ + -u rv_core_fpu_restore +endif + +ifneq ($(CIRCUITPY_WIFI),0) +ifeq ($(filter $(IDF_TARGET),esp32s2 esp32p4),) +ifneq ($(CIRCUITPY_ESP_HOSTED),1) +REGISTRATION_FUNCTIONS += -u esp_coex_init_include_func +endif +endif +endif #Debugging/Optimization @@ -171,12 +299,12 @@ ifeq ($(DEBUG), 1) OPTIMIZATION_FLAGS ?= -Og CFLAGS += -DDEBUG endif - # You may want to enable these flags to make setting breakpoints easier. - # CFLAGS += -fno-inline -fno-ipa-sra +# You may want to enable these flags to make setting breakpoints easier. +# CFLAGS += -fno-inline -fno-ipa-sra else CFLAGS += -DNDEBUG - # RISC-V is larger than xtensa - # Use -Os for RISC-V when it overflows +# RISC-V is larger than xtensa +# Use -Os for RISC-V when it overflows ifeq ($(IDF_TARGET_ARCH),riscv) OPTIMIZATION_FLAGS ?= -Os else @@ -187,48 +315,69 @@ endif # option to override compiler optimization level, set in boards/$(BOARD)/mpconfigboard.mk CFLAGS += $(OPTIMIZATION_FLAGS) -CFLAGS += $(INC) -Werror -Wall -std=gnu11 -Wl,--gc-sections $(BASE_CFLAGS) $(C_DEFS) $(CFLAGS_MOD) $(COPT) -Werror=missing-prototypes +# Default ROM symbol maps; per-chip blocks below may override. +IDF_TARGET_ROM_LD ?= $(IDF_TARGET).rom.ld +# Floating-point/libgcc ROM map. IDF picks between libgcc and rvfp based on +# CONFIG_COMPILER_FLOAT_LIB_FROM_GCCLIB (rvfp xor libgcc, never both). Default +# to libgcc; targets that ship the rvfp variant in ROM (P4 in particular) +# override this. +IDF_TARGET_ROM_FLOAT_LD ?= $(IDF_TARGET).rom.libgcc.ld -# Most current ESPs have nano versions of newlib in ROM so we use them. -ifneq ($(IDF_TARGET),esp32c6) - CFLAGS += --specs=nano.specs - LDFLAGS += -T$(IDF_TARGET).rom.newlib-nano.ld -else - LDFLAGS += -T$(IDF_TARGET).rom.newlib-normal.ld -endif +CFLAGS += $(INC) -Werror -Wall -std=gnu11 -Wl,--gc-sections $(BASE_CFLAGS) $(C_DEFS) $(CFLAGS_MOD) $(COPT) -Werror=missing-prototypes -Werror=old-style-definition -Wno-error=cpp -Wno-cpp + +# ESP-IDF v6.0 uses picolibc instead of newlib. +CFLAGS += --specs=picolibc.specs ifeq ($(IDF_TARGET_ARCH),xtensa) # Remove the last two flags once TinyUSB is updated with the `#include ` instead of # `#include "xtensa/xtensa_api.h"`. -CFLAGS += -mlongcalls -isystem esp-idf/components/xtensa/deprecated_include/ -Wno-error=cpp + CFLAGS += -mlongcalls -fno-builtin-memcpy -fno-builtin-memset -fno-builtin-bzero + CFLAGS += -isystem esp-idf/components/xtensa/deprecated_include/ +ifeq ($(IDF_TARGET),esp32) + CFLAGS += -Wno-frame-address +endif + CFLAGS += -DMICROPY_GCREGS_SETJMP=1 + +# Wrap longjmp with a patched version that protects register window update with a critical section + LDFLAGS += -Wl,--wrap=longjmp + + SRC_C += shared/runtime/gchelper_generic.c else ifeq ($(IDF_TARGET_ARCH),riscv) -ifeq ($(IDF_TARGET),esp32p4) -CFLAGS += -march=rv32imafc_zicsr_zifencei_xesppie -mabi=ilp32f -else -CFLAGS += -march=rv32imac_zicsr_zifencei -endif + ifneq ($(filter $(IDF_TARGET),esp32p4 esp32s31),) + CFLAGS += -march=rv32imafc_zicsr_zifencei_zaamo_zalrsc -mabi=ilp32f + else ifeq ($(IDF_TARGET),$(filter $(IDF_TARGET),esp32c2 esp32c3)) + CFLAGS += -march=rv32imc_zicsr_zifencei + else + CFLAGS += -march=rv32imac_zicsr_zifencei_zaamo_zalrsc + endif -LDFLAGS += \ - -Lesp-idf/components/riscv/ld \ - -Trom.api.ld + LDFLAGS += \ + -Lesp-idf/components/riscv/ld \ + -Trom.api.ld + + SRC_C += shared/runtime/gchelper_native.c + SRC_S = shared/runtime/gchelper_rv32i.s endif -$(BUILD)/lib/tlsf/tlsf.o: CFLAGS += -Wno-cast-align -LDFLAGS += $(CFLAGS) -Wl,-nostdlib -Wl,-Map=$@.map -Wl,-cref -Wl,--undefined=uxTopUsedPriority +LDFLAGS += $(CFLAGS) -nostartfiles -Wl,-nostdlib -Wl,-Map=$@.map -Wl,-cref -Wl,--undefined=uxTopUsedPriority LDFLAGS += \ -L$(BUILD)/esp-idf/esp-idf/esp_system/ld \ -Lesp-idf/components/esp_rom/$(IDF_TARGET)/ld \ -Lesp-idf/components/soc/$(IDF_TARGET)/ld \ + -Lesp-idf/components/esp_hal_wdt/$(IDF_TARGET) \ + -Lesp-idf/components/esp_hal_systimer/$(IDF_TARGET) \ + -Lesp-idf/components/heap/port/$(IDF_TARGET)/ld \ + -Lesp-idf/components/esp_hal_regi2c/$(IDF_TARGET) \ -Tmemory.ld \ -Tsections.ld \ -T$(IDF_TARGET).peripherals.ld \ - -T$(IDF_TARGET).rom.ld \ + -T$(IDF_TARGET_ROM_LD) \ -T$(IDF_TARGET).rom.api.ld \ - -T$(IDF_TARGET).rom.libgcc.ld \ + -T$(IDF_TARGET_ROM_FLOAT_LD) \ -Wl,-Bstatic \ -Wl,--no-warn-mismatch \ -Wl,--build-id=none \ @@ -236,95 +385,257 @@ LDFLAGS += \ ifeq ($(IDF_TARGET),esp32) LDFLAGS += \ - -Tesp32.rom.newlib-data.ld \ - -Tesp32.rom.newlib-funcs.ld \ - -Tesp32.rom.newlib-time.ld \ - -Tesp32.rom.spiflash_legacy.ld + -Tesp32.rom.libc-funcs.ld + +CFLAGS += -isystem esp-idf/components/esp_driver_touch_sens/hw_ver1/include CHIP_COMPONENTS = \ - esp_driver_dac + esp_driver_dac \ + esp_driver_touch_sens \ + esp_hal_emac \ + esp_hal_i2s \ + esp_hal_lcd \ + esp_hal_pcnt \ + esp_hal_pmu \ + esp_hal_rmt \ + esp_hal_touch_sens \ + esp_hal_twai else ifeq ($(IDF_TARGET),esp32c2) LDFLAGS += \ -Tesp32c2.rom.ble.ld \ -Tesp32c2.rom.heap.ld \ - -Tesp32c2.rom.newlib.ld \ + -Tesp32c2.rom.libc.ld \ -Tesp32c2.rom.version.ld \ - -Tesp32c2.rom.systimer.ld \ - -Tesp32c2.rom.wdt.ld - -CFLAGS += -DSOC_XTAL_FREQ_MHZ=CONFIG_XTAL_FREQ + -Trom.systimer.ld \ + -Trom.wdt.ld CHIP_COMPONENTS = \ - esp_driver_tsens + esp_driver_tsens \ + esp_hal_dma \ + esp_hal_pmu else ifeq ($(IDF_TARGET),esp32c3) +# esp32c2 has none of: esp_hal_i2s esp_hal_lcd esp_hal_pcnt esp_hal_touch_sens esp_hal_twai LDFLAGS += \ - -Tesp32c3.rom.newlib.ld \ - -Tesp32c3.rom.newlib-time.ld \ + -Tesp32c3.rom.libc.ld \ -Tesp32c3.rom.version.ld \ + -Tesp32c3.rom.eco3_bt_funcs.ld \ -Tesp32c3.rom.eco3.ld \ -Tesp32c3.rom.bt_funcs.ld CHIP_COMPONENTS = \ - esp_driver_tsens + esp_driver_tsens \ + esp_driver_usb_serial_jtag \ + esp_hal_dma \ + esp_hal_i2s \ + esp_hal_pmu \ + esp_hal_rmt \ + esp_hal_twai \ + esp_hal_usb + +else ifeq ($(IDF_TARGET),esp32c5) +LDFLAGS += \ + -Tesp32c5.rom.phy.ld \ + -Tesp32c5.rom.pp.ld \ + -Tesp32c5.rom.net80211.ld \ + -Tesp32c5.rom.libc.ld \ + -Tesp32c5.rom.version.ld \ + -Tesp32c5.rom.coexist.ld \ + -Tesp32c5.rom.heap.ld \ + -Trom.systimer.ld \ + -Trom.wdt.ld + +CHIP_COMPONENTS = \ + esp_driver_tsens \ + esp_driver_usb_serial_jtag \ + esp_hal_dma \ + esp_hal_i2s \ + esp_hal_pcnt \ + esp_hal_pmu \ + esp_hal_rmt \ + esp_hal_twai \ + esp_hal_usb else ifeq ($(IDF_TARGET),esp32c6) LDFLAGS += \ -Tesp32c6.rom.phy.ld \ -Tesp32c6.rom.pp.ld \ -Tesp32c6.rom.net80211.ld \ - -Tesp32c6.rom.newlib.ld \ + -Tesp32c6.rom.libc.ld \ -Tesp32c6.rom.coexist.ld \ -Tesp32c6.rom.heap.ld \ - -Tesp32c6.rom.systimer.ld \ - -Tesp32c6.rom.wdt.ld + -Trom.systimer.ld \ + -Trom.wdt.ld CHIP_COMPONENTS = \ - esp_driver_tsens + esp_driver_tsens \ + esp_driver_usb_serial_jtag \ + esp_hal_dma \ + esp_hal_i2s \ + esp_hal_pcnt \ + esp_hal_pmu \ + esp_hal_rmt \ + esp_hal_twai \ + esp_hal_usb + +else ifeq ($(IDF_TARGET),esp32c61) +LDFLAGS += \ + -Tesp32c61.rom.phy.ld \ + -Tesp32c61.rom.pp.ld \ + -Tesp32c61.rom.net80211.ld \ + -Tesp32c61.rom.libc.ld \ + -Tesp32c61.rom.version.ld \ + -Tesp32c61.rom.coexist.ld \ + -Tesp32c61.rom.heap.ld \ + -Trom.systimer.ld \ + -Trom.wdt.ld + + +CHIP_COMPONENTS = \ + esp_driver_tsens \ + esp_driver_usb_serial_jtag \ + esp_hal_dma \ + esp_hal_i2s \ + esp_hal_pmu \ + esp_hal_usb else ifeq ($(IDF_TARGET),esp32p4) +CIRCUITPY_ESP32P4_REV ?= 1 +CFLAGS += \ + -isystem esp-idf/components/soc/esp32p4/register/hw_ver$(CIRCUITPY_ESP32P4_REV) \ + -isystem esp-idf/components/esp_hw_support/ldo/include \ + -isystem esp-idf/components/esp_driver_touch_sens/hw_ver3/include + +# JPEG engine DMA writes into GC blocks, so make them one 64-byte cache line. +CFLAGS += -DMICROPY_BYTES_PER_GC_BLOCK=64 + +ifeq ($(CIRCUITPY_ESP32P4_REV),3) +IDF_TARGET_ROM_FLOAT_LD = esp32p4.rom.rvfp.ld +LDFLAGS += \ + -Trom.systimer.ld \ + -Tesp32p4.rom.libc.ld \ + -Tesp32p4.rom.version.ld \ + -Trom.wdt.ld +else +IDF_TARGET_ROM_LD = esp32p4.rom.eco0_4.ld +IDF_TARGET_ROM_FLOAT_LD = esp32p4.rom.eco0_4.rvfp.ld LDFLAGS += \ - -Tesp32p4.rom.newlib.ld \ - -Tesp32p4.rom.systimer.ld \ - -Tesp32p4.rom.wdt.ld + -Trom.systimer.ld \ + -Tesp32p4.rom.eco0_4.libc.ld \ + -Tesp32p4.rom.version.ld \ + -Trom.wdt.ld +endif + +CHIP_COMPONENTS = \ + esp_driver_cam \ + esp_driver_isp \ + esp_driver_touch_sens \ + esp_driver_tsens \ + esp_driver_usb_serial_jtag \ + esp_hal_cam \ + esp_hal_dma \ + esp_hal_emac \ + esp_hal_i2s \ + esp_hal_lcd \ + esp_hal_pcnt \ + esp_hal_pmu \ + esp_hal_rmt \ + esp_hal_touch_sens \ + esp_hal_twai \ + esp_hal_usb + +else ifeq ($(IDF_TARGET),esp32s31) +CFLAGS += -isystem esp-idf/components/esp_hw_support/ldo/include + +# JPEG engine DMA writes into GC blocks, so make them one 64-byte cache line. +CFLAGS += -DMICROPY_BYTES_PER_GC_BLOCK=64 + +IDF_TARGET_ROM_FLOAT_LD = esp32s31.rom.rvfp.ld +LDFLAGS += \ + -Tesp32s31.rom.heap.ld \ + -Trom.systimer.ld \ + -Tesp32s31.rom.libc.ld \ + -Tesp32s31.rom.version.ld \ + -Trom.wdt.ld CHIP_COMPONENTS = \ - esp_driver_tsens + esp_driver_tsens \ + esp_driver_usb_serial_jtag \ + esp_hal_dma \ + esp_hal_i2s \ + esp_hal_lcd \ + esp_hal_pcnt \ + esp_hal_pmu \ + esp_hal_rmt \ + esp_hal_touch_sens \ + esp_hal_twai \ + esp_hal_usb else ifeq ($(IDF_TARGET),esp32h2) LDFLAGS += \ -Tesp32h2.rom.heap.ld \ - -Tesp32h2.rom.newlib.ld \ - -Tesp32h2.rom.systimer.ld \ - -Tesp32h2.rom.wdt.ld + -Tesp32h2.rom.libc.ld \ + -Trom.systimer.ld \ + -Trom.wdt.ld CHIP_COMPONENTS = \ - esp_driver_tsens + esp_driver_tsens \ + esp_driver_usb_serial_jtag \ + esp_hal_dma \ + esp_hal_i2s \ + esp_hal_pcnt \ + esp_hal_pmu \ + esp_hal_rmt \ + esp_hal_twai \ + esp_hal_usb else ifeq ($(IDF_TARGET),esp32s2) +CFLAGS += -isystem esp-idf/components/esp_driver_touch_sens/hw_ver2/include + LDFLAGS += \ - -Tesp32s2.rom.newlib-data.ld \ - -Tesp32s2.rom.newlib-funcs.ld \ - -Tesp32s2.rom.newlib-time.ld \ + -Tesp32s2.rom.libc-funcs.ld \ -Tesp32s2.rom.spiflash_legacy.ld CHIP_COMPONENTS = \ esp_driver_dac \ - esp_driver_tsens + esp_driver_touch_sens \ + esp_driver_tsens \ + esp_hal_dma \ + esp_hal_i2s \ + esp_hal_lcd \ + esp_hal_pcnt \ + esp_hal_pmu \ + esp_hal_rmt \ + esp_hal_touch_sens \ + esp_hal_twai \ + esp_hal_usb else ifeq ($(IDF_TARGET),esp32s3) +CFLAGS += -isystem esp-idf/components/esp_driver_touch_sens/hw_ver2/include + LDFLAGS += \ - -Tesp32s3.rom.newlib.ld \ + -Tesp32s3.rom.libc.ld \ -Tesp32s3.rom.version.ld \ - -Tesp32s3.rom.systimer.ld \ - -Tesp32s3.rom.wdt.ld \ - -Tesp32s3.rom.bt_funcs.ld + -Trom.systimer.ld \ + -Tesp32s3.rom.bt_funcs.ld \ + -Trom.wdt.ld CHIP_COMPONENTS = \ - esp_driver_tsens + esp_driver_touch_sens \ + esp_driver_tsens \ + esp_driver_usb_serial_jtag \ + esp_hal_dma \ + esp_hal_i2s \ + esp_hal_lcd \ + esp_hal_pcnt \ + esp_hal_pmu \ + esp_hal_rmt \ + esp_hal_touch_sens \ + esp_hal_twai \ + esp_hal_usb endif @@ -343,10 +654,16 @@ else ifeq ($(IDF_TARGET),esp32c2) CFLAGS += -DCFG_TUSB_MCU=OPT_MCU_ESP32C2 else ifeq ($(IDF_TARGET),esp32c3) CFLAGS += -DCFG_TUSB_MCU=OPT_MCU_ESP32C3 +else ifeq ($(IDF_TARGET),esp32c5) +CFLAGS += -DCFG_TUSB_MCU=OPT_MCU_ESP32C5 else ifeq ($(IDF_TARGET),esp32c6) CFLAGS += -DCFG_TUSB_MCU=OPT_MCU_ESP32C6 +else ifeq ($(IDF_TARGET),esp32c61) +CFLAGS += -DCFG_TUSB_MCU=OPT_MCU_ESP32C61 else ifeq ($(IDF_TARGET),esp32p4) CFLAGS += -DCFG_TUSB_MCU=OPT_MCU_ESP32P4 +else ifeq ($(IDF_TARGET),esp32s31) +CFLAGS += -DCFG_TUSB_MCU=OPT_MCU_ESP32S31 else ifeq ($(IDF_TARGET),esp32h2) CFLAGS += -DCFG_TUSB_MCU=OPT_MCU_ESP32H2 else ifeq ($(IDF_TARGET),esp32s2) @@ -360,12 +677,31 @@ CFLAGS += \ -DCFG_TUD_TASK_QUEUE_SZ=32 endif ifeq ($(CIRCUITPY_USB_DEVICE),1) +ifeq ($(IDF_TARGET),esp32s2) +# Make more room in internal RAM on the S2. +CFLAGS += \ + -DCFG_TUD_CDC_RX_BUFSIZE=128 \ + -DCFG_TUD_CDC_TX_BUFSIZE=128 \ + -DCFG_TUD_MSC_BUFSIZE=1024 +else CFLAGS += \ -DCFG_TUD_CDC_RX_BUFSIZE=1024 \ -DCFG_TUD_CDC_TX_BUFSIZE=1024 \ - -DCFG_TUD_MSC_BUFSIZE=4096 \ + -DCFG_TUD_MSC_BUFSIZE=4096 +endif +ifeq ($(CIRCUITPY_USB_DEVICE_HIGH_SPEED),1) +# At high speed the MIDI endpoint is a 512-byte bulk endpoint. The MIDI driver +# refuses to arm the endpoint unless the stream FIFO can hold a full packet, so +# the buffers must be at least as big as the endpoint's max packet size. +CFLAGS += \ + -DCFG_TUD_MIDI_RX_BUFSIZE=512 \ + -DCFG_TUD_MIDI_TX_BUFSIZE=512 +else +CFLAGS += \ -DCFG_TUD_MIDI_RX_BUFSIZE=128 \ - -DCFG_TUD_MIDI_TX_BUFSIZE=128 \ + -DCFG_TUD_MIDI_TX_BUFSIZE=128 +endif +CFLAGS += \ -DCFG_TUD_VENDOR_RX_BUFSIZE=128 \ -DCFG_TUD_VENDOR_TX_BUFSIZE=128 endif @@ -374,8 +710,19 @@ endif # source ###################################### +ifeq ($(CIRCUITPY_DISPLAYIO_LVGL),1) +# Compile LVGL as part of CircuitPython's build rather than as an ESP-IDF component so +# that it uses the port's lv_conf.h. The library and the display code must agree on the +# LVGL configuration or struct layouts will differ. +LVGL_SRC = $(patsubst $(TOP)/%,%,$(shell find $(TOP)/lib/lvgl/src -name '*.c')) +SRC_MOD += $(LVGL_SRC) +# LVGL isn't warning-clean under CircuitPython's strict warning flags. +$(addprefix $(BUILD)/, $(LVGL_SRC:.c=.o)): CFLAGS += -w +endif + SRC_C += \ background.c \ + supervisor/lvgl_port.c \ mphalport.c \ boards/$(BOARD)/board.c \ boards/$(BOARD)/pins.c \ @@ -383,7 +730,15 @@ SRC_C += \ peripherals/$(IDF_TARGET)/pins.c ifeq ($(CIRCUITPY_SSL),1) +# The same root certificate bundle and lookup code as the other ports, not ESP-IDF's. +# A board short of flash can set CIRCUITPY_SSL_ROOTS to roots-filtered.pem. +# The generated bundle holds a hash of each root's subject name, not the name itself; +# the format is described in lib/mbedtls_config/crt_bundle.c. +CIRCUITPY_SSL_ROOTS ?= $(TOP)/lib/certificates/data/roots-full.pem SRC_C += lib/mbedtls_config/crt_bundle.c +$(BUILD)/x509_crt_bundle.S: $(CIRCUITPY_SSL_ROOTS) $(TOP)/tools/gen_crt_bundle.py + $(Q)$(PYTHON) $(TOP)/tools/gen_crt_bundle.py -i $< -o $@ --asm +OBJ_CRT_BUNDLE := $(BUILD)/x509_crt_bundle.o endif SRC_C += $(wildcard common-hal/espidf/*.c) @@ -397,16 +752,26 @@ SRC_C += peripherals/touch.c endif ifneq ($(CIRCUITPY_USB_DEVICE),0) -SRC_C += \ - lib/tinyusb/src/portable/synopsys/dwc2/dcd_dwc2.c \ - lib/tinyusb/src/portable/synopsys/dwc2/dwc2_common.c +SRC_C += lib/tinyusb/src/portable/synopsys/dwc2/dcd_dwc2.c +endif + +ifeq ($(CIRCUITPY_USB_HOST),1) +SRC_C += lib/tinyusb/src/portable/synopsys/dwc2/hcd_dwc2.c +endif + +ifneq ($(filter 1,$(CIRCUITPY_USB_DEVICE) $(CIRCUITPY_USB_HOST)),) +SRC_C += lib/tinyusb/src/portable/synopsys/dwc2/dwc2_common.c endif ifneq ($(CIRCUITPY_AUDIOBUSIO),0) CHIP_COMPONENTS += esp_driver_i2s endif -ifneq ($(CIRCUITPY_BLEIO),0) +ifneq ($(CIRCUITPY_AUDIOI2SIN),0) +CHIP_COMPONENTS += esp_driver_i2s +endif + +ifneq ($(CIRCUITPY_BLEIO_NATIVE),0) SRC_C += common-hal/_bleio/ble_events.c endif @@ -417,6 +782,21 @@ CFLAGS += \ -isystem esp-idf/components/esp_lcd/rgb/include endif +ifneq ($(CIRCUITPY_MIPIDSI),0) +CFLAGS += \ + -isystem esp-idf/components/esp_lcd/include \ + -isystem esp-idf/components/esp_lcd/interface \ + -isystem esp-idf/components/esp_lcd/dsi/include +endif + +ifneq ($(CIRCUITPY_MIPICSI),0) +CFLAGS += \ + -isystem esp-idf/components/esp_driver_cam/include \ + -isystem esp-idf/components/esp_driver_cam/csi/include \ + -isystem esp-idf/components/esp_driver_isp/include \ + -isystem esp-idf/components/esp_hal_cam/include +endif + ifneq ($(CIRCUITPY_ESPCAMERA),0) SRC_CAMERA := \ $(wildcard common-hal/espcamera/*.c) \ @@ -426,6 +806,55 @@ CFLAGS += -isystem esp-camera/driver/include CFLAGS += -isystem esp-camera/conversions/include endif +ifneq ($(CIRCUITPY_RCLCPY),0) +CFLAGS += -isystem microros-lib/include +CFLAGS += -isystem microros-lib/include/rcl +CFLAGS += -isystem microros-lib/include/statistics_msgs +CFLAGS += -isystem microros-lib/include/composition_interfaces +CFLAGS += -isystem microros-lib/include/example_interfaces +CFLAGS += -isystem microros-lib/include/rmw_microxrcedds_c +CFLAGS += -isystem microros-lib/include/test_msgs +CFLAGS += -isystem microros-lib/include/std_msgs +CFLAGS += -isystem microros-lib/include/rcutils +CFLAGS += -isystem microros-lib/include/lifecycle_msgs +CFLAGS += -isystem microros-lib/include/rosidl_typesupport_interface +CFLAGS += -isystem microros-lib/include/service_msgs +CFLAGS += -isystem microros-lib/include/visualization_msgs +CFLAGS += -isystem microros-lib/include/rosidl_dynamic_typesupport +CFLAGS += -isystem microros-lib/include/stereo_msgs +CFLAGS += -isystem microros-lib/include/ucdr +CFLAGS += -isystem microros-lib/include/rosidl_typesupport_c +CFLAGS += -isystem microros-lib/include/std_srvs +CFLAGS += -isystem microros-lib/include/rcl_lifecycle +CFLAGS += -isystem microros-lib/include/action_msgs +CFLAGS += -isystem microros-lib/include/micro_ros_utilities +CFLAGS += -isystem microros-lib/include/rcl_action +CFLAGS += -isystem microros-lib/include/rcl_logging_interface +CFLAGS += -isystem microros-lib/include/type_description_interfaces +CFLAGS += -isystem microros-lib/include/nav_msgs +CFLAGS += -isystem microros-lib/include/actionlib_msgs +CFLAGS += -isystem microros-lib/include/rmw +CFLAGS += -isystem microros-lib/include/rclc_parameter +CFLAGS += -isystem microros-lib/include/geometry_msgs +CFLAGS += -isystem microros-lib/include/sensor_msgs +CFLAGS += -isystem microros-lib/include/trajectory_msgs +CFLAGS += -isystem microros-lib/include/shape_msgs +CFLAGS += -isystem microros-lib/include/rosidl_runtime_c +CFLAGS += -isystem microros-lib/include/rclc +CFLAGS += -isystem microros-lib/include/rosgraph_msgs +CFLAGS += -isystem microros-lib/include/rclc_lifecycle +CFLAGS += -isystem microros-lib/include/rcl_interfaces +CFLAGS += -isystem microros-lib/include/diagnostic_msgs +CFLAGS += -isystem microros-lib/include/micro_ros_msgs +CFLAGS += -isystem microros-lib/include/rosidl_typesupport_introspection_c +CFLAGS += -isystem microros-lib/include/uxr +CFLAGS += -isystem microros-lib/include/unique_identifier_msgs +CFLAGS += -isystem microros-lib/include/rosidl_typesupport_microxrcedds_c +CFLAGS += -isystem microros-lib/include/builtin_interfaces +CFLAGS += -isystem microros-lib/include/tracetools +CFLAGS += -isystem microros-lib/include/rmw_microros +endif + ifneq ($(CIRCUITPY_ESPIDF),0) SRC_ESPIDF := \ $(wildcard common-hal/espidf/*.c) \ @@ -447,6 +876,21 @@ SRC_ULP := \ SRC_C += $(SRC_ULP) endif +ifneq ($(CIRCUITPY_JPEGIO_HW),0) +SRC_C += common-hal/jpegio/JpegDecoder.c +CHIP_COMPONENTS += esp_driver_jpeg esp_hal_jpeg +endif + +ifneq ($(CIRCUITPY_JPEGIO_FAST),0) +ifneq ($(VALID_BOARD),) +ifneq ($(IDF_TARGET),esp32s3) +$(error CIRCUITPY_JPEGIO_FAST is only supported on the ESP32-S3) +endif +endif +SRC_C += common-hal/jpegio/JpegDecoderFast.c +CFLAGS += -isystem esp-adf-libs/esp_new_jpeg/include +endif + ifneq ($(CIRCUITPY_NEOPIXEL_WRITE),0) CHIP_COMPONENTS += esp_driver_rmt endif @@ -471,37 +915,29 @@ ifneq ($(CIRCUITPY_FREQUENCYIO),0) CHIP_COMPONENTS += esp_driver_pcnt endif -SRC_COMMON_HAL_EXPANDED = \ - $(addprefix shared-bindings/, $(SRC_COMMON_HAL)) \ - $(addprefix shared-bindings/, $(SRC_BINDINGS_ENUMS)) \ - $(addprefix common-hal/, $(SRC_COMMON_HAL)) - -SRC_SHARED_MODULE_EXPANDED = \ - $(addprefix shared-bindings/, $(SRC_SHARED_MODULE)) \ - $(addprefix shared-module/, $(SRC_SHARED_MODULE)) \ - $(addprefix shared-module/, $(SRC_SHARED_MODULE_INTERNAL)) - ifneq ($(FROZEN_MPY_DIR),) FROZEN_MPY_PY_FILES := $(shell find -L $(FROZEN_MPY_DIR) -type f -name '*.py') FROZEN_MPY_MPY_FILES := $(addprefix $(BUILD)/,$(FROZEN_MPY_PY_FILES:.py=.mpy)) endif OBJ += $(PY_O) $(SUPERVISOR_O) $(addprefix $(BUILD)/, $(SRC_C:.c=.o)) -OBJ += $(addprefix $(BUILD)/, $(SRC_COMMON_HAL_EXPANDED:.c=.o)) -OBJ += $(addprefix $(BUILD)/, $(SRC_SHARED_MODULE_EXPANDED:.c=.o)) +OBJ += $(addprefix $(BUILD)/, $(SRC_COMMON_HAL_SHARED_MODULE_EXPANDED:.c=.o)) ifeq ($(INTERNAL_LIBM),1) OBJ += $(addprefix $(BUILD)/, $(SRC_LIBM:.c=.o)) endif OBJ += $(addprefix $(BUILD)/, $(SRC_CIRCUITPY_COMMON:.c=.o)) OBJ += $(addprefix $(BUILD)/, $(SRC_MOD:.c=.o)) +OBJ += $(addprefix $(BUILD)/, $(SRC_S:.s=.o)) +OBJ += $(OBJ_CRT_BUNDLE) $(BUILD)/$(FATFS_DIR)/ff.o: COPT += -Os $(filter $(PY_BUILD)/../extmod/vfs_fat_%.o, $(PY_O)): COPT += -Os $(BUILD)/lib/protomatter/src/core.o: CFLAGS += -DESP32 -# List of sources for qstr extraction -SRC_QSTR += $(SRC_C) $(SRC_SUPERVISOR) $(SRC_MOD) $(SRC_COMMON_HAL_EXPANDED) $(SRC_SHARED_MODULE_EXPANDED) $(SRC_CIRCUITPY_COMMON) +# List of sources for qstr extraction. LVGL sources contain no qstrs and aren't +# -Wundef clean, so skip preprocessing them. +SRC_QSTR += $(SRC_C) $(SRC_SUPERVISOR) $(filter-out lib/lvgl/%, $(SRC_MOD)) $(SRC_COMMON_HAL_SHARED_MODULE_EXPANDED) $(SRC_CIRCUITPY_COMMON) # IDF build commands IDF_PATH = $(realpath ./esp-idf) @@ -511,25 +947,17 @@ $(BUILD)/esp-idf: TARGET_SDKCONFIG = esp-idf-config/sdkconfig-$(IDF_TARGET).defaults - -ifeq ($(CIRCUITPY_ESP_FLASH_SIZE), 2MB) - FLASH_SIZE_SDKCONFIG ?= esp-idf-config/sdkconfig-flash-$(CIRCUITPY_ESP_FLASH_SIZE)-no-ota-no-uf2.defaults -else +# Choose the correct partition layout, based on UF2 or not, flash size, etc. UF2_BOOTLOADER ?= $(CIRCUITPY_USB_DEVICE) -ifeq ($(UF2_BOOTLOADER), 1) - FLASH_SIZE_SDKCONFIG ?= esp-idf-config/sdkconfig-flash-$(CIRCUITPY_ESP_FLASH_SIZE).defaults -else -ifeq ($(CIRCUITPY_ESP_FLASH_SIZE), 4MB) - ifeq ($(CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT), 1) - FLASH_SIZE_SDKCONFIG ?= esp-idf-config/sdkconfig-flash-$(CIRCUITPY_ESP_FLASH_SIZE)-no-uf2.defaults - else - FLASH_SIZE_SDKCONFIG ?= esp-idf-config/sdkconfig-flash-$(CIRCUITPY_ESP_FLASH_SIZE)-no-ota-no-uf2.defaults - endif -else - FLASH_SIZE_SDKCONFIG ?= esp-idf-config/sdkconfig-flash-$(CIRCUITPY_ESP_FLASH_SIZE)-no-uf2.defaults -endif -endif -endif + +# The sdkconfig file naming rules are shared with tools/update_sdkconfig.py. +# Keep them in tools/flash_layout.py so that they cannot drift. +FLASH_SIZE_SDKCONFIG ?= $(if $(VALID_BOARD),$(shell $(PYTHON) tools/flash_layout.py \ + --family "$(IDF_TARGET)" \ + --flash-size "$(CIRCUITPY_ESP_FLASH_SIZE)" \ + $(if $(filter 1,$(UF2_BOOTLOADER)),--uf2) \ + $(if $(filter 1,$(CIRCUITPY_4MB_FLASH_LARGE_USER_FS_LAYOUT)),--large-user-fs))) + FLASH_MODE_SDKCONFIG ?= esp-idf-config/sdkconfig-flash-$(CIRCUITPY_ESP_FLASH_MODE).defaults FLASH_SPEED_SDKCONFIG ?= esp-idf-config/sdkconfig-flash-$(CIRCUITPY_ESP_FLASH_FREQ).defaults @@ -546,20 +974,37 @@ else DEBUG_SDKCONFIG = esp-idf-config/sdkconfig-opt.defaults endif -SDKCONFIGS := esp-idf-config/sdkconfig.defaults;$(DEBUG_SDKCONFIG);$(FLASH_SIZE_SDKCONFIG);$(FLASH_MODE_SDKCONFIG);$(FLASH_SPEED_SDKCONFIG);$(PSRAM_SDKCONFIG);$(PSRAM_SIZE_SDKCONFIG);$(PSRAM_MODE_SDKCONFIG);$(PSRAM_SPEED_SDKCONFIG);$(TARGET_SDKCONFIG);boards/$(BOARD)/sdkconfig -ifneq ($(CIRCUITPY_BLEIO),0) - SDKCONFIGS := esp-idf-config/sdkconfig-ble.defaults;$(SDKCONFIGS) +ifeq ($(ENABLE_JTAG), 1) + CFLAGS += -DENABLE_JTAG=1 +endif + +ifneq ($(CIRCUITPY_BLEIO_NATIVE),0) + BLE_SDKCONFIG := ;esp-idf-config/sdkconfig-ble.defaults +endif + +# Loaded native code executes from RAM, which memory protection forbids. +ifneq (,$(filter 1,$(CIRCUITPY_ENABLE_MPY_NATIVE) $(CIRCUITPY_LOAD_NATIVE))) + NATIVE_SDKCONFIG := ;esp-idf-config/sdkconfig-native.defaults endif + +ifeq ($(CIRCUITPY_HARDWAREKEY),1) + HARDWAREKEY_SDKCONFIG := ;esp-idf-config/sdkconfig-hardwarekey.defaults +endif + +SDKCONFIGS := esp-idf-config/sdkconfig.defaults;$(DEBUG_SDKCONFIG);$(FLASH_SIZE_SDKCONFIG);$(FLASH_MODE_SDKCONFIG);$(FLASH_SPEED_SDKCONFIG);$(PSRAM_SDKCONFIG);$(PSRAM_SIZE_SDKCONFIG);$(PSRAM_MODE_SDKCONFIG);$(PSRAM_SPEED_SDKCONFIG);$(BLE_SDKCONFIG)$(NATIVE_SDKCONFIG)$(HARDWAREKEY_SDKCONFIG);$(TARGET_SDKCONFIG);boards/$(BOARD)/sdkconfig + # create the config headers .PHONY: do-sdkconfig do-sdkconfig: $(BUILD)/esp-idf/config/sdkconfig.h QSTR_GLOBAL_REQUIREMENTS += $(BUILD)/esp-idf/config/sdkconfig.h $(BUILD)/esp-idf/config/sdkconfig.h: boards/$(BOARD)/sdkconfig boards/$(BOARD)/mpconfigboard.mk CMakeLists.txt | $(BUILD)/esp-idf - $(STEPECHO) "LINK $@" - $(Q)env IDF_PATH=$(IDF_PATH) cmake -S . -B $(BUILD)/esp-idf -DSDKCONFIG=$(BUILD)/esp-idf/sdkconfig -DSDKCONFIG_DEFAULTS="$(SDKCONFIGS)" -DCMAKE_TOOLCHAIN_FILE=$(IDF_PATH)/tools/cmake/toolchain-$(IDF_TARGET).cmake -DIDF_TARGET=$(IDF_TARGET) -GNinja + $(STEPECHO) "Create $@" + $(Q)env IDF_PATH=$(IDF_PATH) IDF_COMPONENT_MANAGER=0 cmake -S . -B $(BUILD)/esp-idf -DSDKCONFIG=$(BUILD)/esp-idf/sdkconfig -DSDKCONFIG_DEFAULTS="$(SDKCONFIGS)" -DCMAKE_TOOLCHAIN_FILE=$(IDF_PATH)/tools/cmake/toolchain-$(IDF_TARGET).cmake -DIDF_TARGET=$(IDF_TARGET) -DCIRCUITPY_ESP_HOSTED=$(CIRCUITPY_ESP_HOSTED) -DCIRCUITPY_MIPICSI=$(CIRCUITPY_MIPICSI) -GNinja $(Q)$(PYTHON) tools/check-sdkconfig.py \ CIRCUITPY_DUALBANK=$(CIRCUITPY_DUALBANK) \ CIRCUITPY_STORAGE_EXTEND=$(CIRCUITPY_STORAGE_EXTEND) \ + CIRCUITPY_ENABLE_MPY_NATIVE=$(CIRCUITPY_ENABLE_MPY_NATIVE) \ + CIRCUITPY_LOAD_NATIVE=$(CIRCUITPY_LOAD_NATIVE) \ $@ # build a lib @@ -592,34 +1037,111 @@ BINARY_WIFI_BLOBS = libcore.a libespnow.a libnet80211.a libpp.a libsmartconfig.a ifneq ($(IDF_TARGET),esp32p4) BINARY_BLOBS = esp-idf/components/esp_phy/lib/$(IDF_TARGET)/libphy.a endif +ifneq ($(CIRCUITPY_ESP_HOSTED),1) ifneq ($(CIRCUITPY_WIFI),0) - BINARY_BLOBS += esp-idf/components/esp_coex/lib/$(IDF_TARGET)/libcoexist.a $(addprefix esp-idf/components/esp_wifi/lib/$(IDF_TARGET)/, $(BINARY_WIFI_BLOBS)) + BINARY_BLOBS += $(addprefix esp-idf/components/esp_wifi/lib/$(IDF_TARGET)/, $(BINARY_WIFI_BLOBS)) + BINARY_BLOBS += esp-idf/components/esp_coex/lib/$(IDF_TARGET)/libcoexist.a ifneq ($(IDF_TARGET),esp32c2) BINARY_BLOBS += $(addprefix esp-idf/components/esp_wifi/lib/$(IDF_TARGET)/, libmesh.a libwapi.a) endif endif +endif + ifeq ($(IDF_TARGET),esp32) BINARY_BLOBS += esp-idf/components/esp_phy/lib/$(IDF_TARGET)/librtc.a endif -ESP_IDF_COMPONENTS_LINK = $(IDF_TARGET_ARCH) $(CHIP_COMPONENTS) app_update bootloader_support driver esp_driver_gpio esp_driver_gptimer esp_driver_i2c esp_driver_ledc esp_driver_spi esp_driver_uart efuse esp_adc esp_app_format esp_common esp_event esp_hw_support esp_mm esp_partition esp_pm esp_ringbuf esp_rom esp_system esp_timer freertos hal heap log newlib nvs_flash pthread soc spi_flash vfs esp_vfs_console +# CONFIG_COMPILER_CXX_EXCEPTIONS is off, so IDF's cxx component replaces these +# with stubs that abort, and C++ code such as nvs_flash does not link libgcc's +# unwinder. Same list as esp-idf/components/cxx/CMakeLists.txt. +CXX_EXCEPTION_WRAPS = \ + __register_frame_info_bases \ + __register_frame_info \ + __register_frame \ + __register_frame_info_table_bases \ + __register_frame_info_table \ + __register_frame_table \ + __deregister_frame_info_bases \ + __deregister_frame_info \ + _Unwind_Find_FDE \ + _Unwind_GetGR \ + _Unwind_GetCFA \ + _Unwind_GetIP \ + _Unwind_GetIPInfo \ + _Unwind_GetRegionStart \ + _Unwind_GetDataRelBase \ + _Unwind_GetTextRelBase \ + _Unwind_SetIP \ + _Unwind_SetGR \ + _Unwind_GetLanguageSpecificData \ + _Unwind_FindEnclosingFunction \ + _Unwind_Resume \ + _Unwind_RaiseException \ + _Unwind_DeleteException \ + _Unwind_ForcedUnwind \ + _Unwind_Resume_or_Rethrow \ + _Unwind_Backtrace \ + __cxa_call_unexpected \ + __gxx_personality_v0 \ + __cxa_throw \ + __cxa_allocate_exception +LDFLAGS += $(foreach f,$(CXX_EXCEPTION_WRAPS),-Wl,--wrap=$(f)) + +ESP_IDF_COMPONENTS_LINK = $(IDF_TARGET_ARCH) $(CHIP_COMPONENTS) app_update bootloader_support driver esp_driver_dma esp_driver_gpio esp_driver_gptimer esp_driver_i2c esp_driver_ledc esp_driver_spi esp_driver_uart efuse esp_adc esp_app_format esp_common esp_event esp_gdbstub esp_hal_ana_conv esp_hal_clock esp_hal_gpio esp_hal_gpspi esp_hal_i2c esp_hal_ledc esp_hal_mspi esp_hal_security esp_hal_timg esp_hal_uart esp_hal_wdt esp_hw_support esp_mm esp_partition esp_pm esp_ringbuf esp_rom esp_system esp_timer freertos hal heap log esp_libc nvs_flash nvs_sec_provider pthread soc spi_flash vfs esp_stdio cxx +ifneq ($(IDF_TARGET),esp32) +ESP_IDF_COMPONENTS_LINK += esp_hal_systimer +endif +# These chips have regi2c in ROM. The rest link the esp_hal_regi2c implementation. +ifneq ($(filter $(IDF_TARGET),esp32 esp32c2 esp32c3 esp32s3),) +LDFLAGS += -Trom.regi2c.ld +else +ESP_IDF_COMPONENTS_LINK += esp_hal_regi2c +endif +# Only targets with EMAC support (per SOC_EMAC_SUPPORTED in soc_caps.h) build +# libesp_hal_emac.a; those targets list it in their CHIP_COMPONENTS above. The +# component is interface-only elsewhere, so it must not appear in the list of +# components to link. ifneq ($(CIRCUITPY_WIFI),0) - ESP_IDF_COMPONENTS_LINK += esp_coex esp_netif esp-tls esp_wifi lwip mbedtls mdns wpa_supplicant esp_phy + ESP_IDF_COMPONENTS_LINK += esp_netif esp_security esp-tls esp_wifi lwip mbedtls mdns +ifneq ($(CIRCUITPY_ESP_HOSTED),1) +ESP_IDF_COMPONENTS_LINK += esp_coex esp_phy wpa_supplicant +endif +endif +ifeq ($(CIRCUITPY_ESP_HOSTED),1) +# ESP-IDF v6.1+ has remote Wi-Fi support built into esp_wifi, so no separate +# esp_wifi_remote component is needed. +INC := -isystem esp-hosted/host/api/include -isystem esp-hosted/host $(INC) +ESP_IDF_COMPONENTS_LINK += esp-hosted esp_http_client http_parser console +REGISTRATION_FUNCTIONS += -u esp_hosted_init endif -ifneq ($(CIRCUITPY_BLEIO),0) +# mdns registers handlers on ETH_EVENT, which is defined by esp_eth. On EMAC-capable +# targets, esp_eth's compiled EMAC sources reference the esp_hal_emac symbols; that +# library comes via CHIP_COMPONENTS. +ifneq ($(CIRCUITPY_MDNS),0) + ESP_IDF_COMPONENTS_LINK += esp_eth +endif +ifneq ($(CIRCUITPY_MII),0) + ESP_IDF_COMPONENTS_LINK += esp_eth + ifeq ($(CIRCUITPY_WIFI),0) + ESP_IDF_COMPONENTS_LINK += esp_netif lwip mbedtls + endif +endif +ifneq ($(CIRCUITPY_BLEIO_NATIVE),0) BLE_IMPL_esp32 := esp32 BLE_IMPL_esp32s3 := esp32c3 BLE_IMPL_esp32c2 := libble BLE_IMPL_esp32c3 := esp32c3 + BLE_IMPL_esp32c5 := libble BLE_IMPL_esp32c6 := libble + BLE_IMPL_esp32c61 := libble BLE_IMPL_esp32h2 := libble BLE_IMPL = $(BLE_IMPL_$(IDF_TARGET)) - ESP_IDF_COMPONENTS_LINK += bt esp_phy + ESP_IDF_COMPONENTS_LINK += bt esp_phy esp_security ifeq ($(BLE_IMPL),esp32) - # BLE will hang the ESP32 and trigger an interrupt watchdog without this undefined symbol at - # link because a weak version of the interrupt that BLE uses will be linked incorrectly. +# BLE will hang the ESP32 and trigger an interrupt watchdog without this undefined symbol at +# link because a weak version of the interrupt that BLE uses will be linked incorrectly. REGISTRATION_FUNCTIONS += -u ld_include_hli_vectors_bt BINARY_BLOBS += esp-idf/components/bt/controller/lib_esp32/$(IDF_TARGET)/libbtdm_app.a endif @@ -631,36 +1153,55 @@ ifneq ($(CIRCUITPY_BLEIO),0) ifeq ($(BLE_IMPL),libble) BINARY_BLOBS += esp-idf/components/esp_phy/lib/$(IDF_TARGET)/libbtbb.a - ifeq ($(IDF_TARGET),esp32c6) - BINARY_BLOBS += esp-idf/components/bt/controller/lib_$(IDF_TARGET)/$(IDF_TARGET)-bt-lib/$(IDF_TARGET)/libble_app.a - else - BINARY_BLOBS += esp-idf/components/bt/controller/lib_$(IDF_TARGET)/$(IDF_TARGET)-bt-lib/libble_app.a - endif + # Shared lib first, else the per-chip one. + BLE_LIB_DIR = esp-idf/components/bt/controller/lib_$(BT_IDF_TARGET)/$(BT_IDF_TARGET)-bt-lib + BINARY_BLOBS += $(firstword $(wildcard $(BLE_LIB_DIR)/libble_app.a) $(BLE_LIB_DIR)/$(IDF_TARGET)/libble_app.a) endif endif +ifneq ($(filter $(IDF_TARGET),esp32p4 esp32s31),) + ESP_IDF_COMPONENTS_LINK += esp_security +endif ifneq ($(CIRCUITPY_ESPULP),0) ESP_IDF_COMPONENTS_LINK += ulp endif ifneq ($(CIRCUITPY_ESP_PSRAM_SIZE),0) ESP_IDF_COMPONENTS_LINK += esp_psram endif +# The LVGL PPA draw unit uses the P4/S31 Pixel Processing Accelerator. +ifneq ($(CIRCUITPY_DISPLAYIO_LVGL),0) + ESP_IDF_COMPONENTS_LINK += esp_driver_ppa esp_hal_ppa +endif ifneq ($(CIRCUITPY_DOTCLOCKFRAMEBUFFER),0) ESP_IDF_COMPONENTS_LINK += esp_lcd endif +ifneq ($(CIRCUITPY_MIPIDSI),0) + ESP_IDF_COMPONENTS_LINK += esp_lcd +endif +ifneq ($(CIRCUITPY_MIPICSI),0) + ESP_IDF_COMPONENTS_LINK += esp_driver_cam esp_driver_isp esp_hal_cam +endif ifneq ($(CIRCUITPY_PARALLELDISPLAYBUS),0) ESP_IDF_COMPONENTS_LINK += esp_lcd endif -ifneq ($(CIRCUITPY_USB_DEVICE),0) - ESP_IDF_COMPONENTS_LINK += usb +ifneq ($(CIRCUITPY_QSPIBUS),0) + ESP_IDF_COMPONENTS_LINK += esp_lcd endif ifneq ($(CIRCUITPY_SDIOIO),0) - ESP_IDF_COMPONENTS_LINK += sdmmc esp_driver_sdmmc + ESP_IDF_COMPONENTS_LINK += sdmmc esp_driver_sdmmc esp_driver_sd_intf esp_hal_sd endif ESP_IDF_COMPONENTS_EXPANDED = $(foreach component, $(ESP_IDF_COMPONENTS_LINK), $(BUILD)/esp-idf/esp-idf/$(component)/lib$(component).a) MBEDTLS_COMPONENTS_LINK = crypto tls x509 MBEDTLS_COMPONENTS_LINK_EXPANDED = $(foreach component, $(MBEDTLS_COMPONENTS_LINK), $(BUILD)/esp-idf/esp-idf/mbedtls/mbedtls/library/libmbed$(component).a) +MBEDTLS_COMPONENTS_LINK_EXPANDED += $(BUILD)/esp-idf/esp-idf/mbedtls/mbedtls/library/libtfpsacrypto.a +MBEDTLS_COMPONENTS_LINK_EXPANDED += $(BUILD)/esp-idf/esp-idf/mbedtls/mbedtls/tf-psa-crypto/drivers/builtin/libmbed-builtin.a +MBEDTLS_COMPONENTS_LINK_EXPANDED += $(BUILD)/esp-idf/esp-idf/mbedtls/mbedtls/tf-psa-crypto/drivers/everest/libeverest.a +MBEDTLS_COMPONENTS_LINK_EXPANDED += $(BUILD)/esp-idf/esp-idf/mbedtls/mbedtls/tf-psa-crypto/drivers/p256-m/libp256-m.a +MBEDTLS_COMPONENTS_LINK_EXPANDED += $(BUILD)/esp-idf/esp-idf/mbedtls/mbedtls/tf-psa-crypto/extras/libextras.a +MBEDTLS_COMPONENTS_LINK_EXPANDED += $(BUILD)/esp-idf/esp-idf/mbedtls/mbedtls/tf-psa-crypto/platform/libplatform.a +MBEDTLS_COMPONENTS_LINK_EXPANDED += $(BUILD)/esp-idf/esp-idf/mbedtls/mbedtls/tf-psa-crypto/utilities/libutilities.a +MBEDTLS_COMPONENTS_LINK_EXPANDED += $(BUILD)/esp-idf/esp-idf/mbedtls/libmbedtls.a ifeq ($(IDF_TARGET_ARCH),xtensa) BINARY_BLOBS += esp-idf/components/xtensa/$(IDF_TARGET)/libxt_hal.a @@ -672,6 +1213,23 @@ ESP_IDF_COMPONENTS_EXPANDED += $(BUILD)/esp-idf/esp-idf/esp-camera/libesp-camera #$(error $(ESP_IDF_COMPONENTS_EXPANDED)) endif +# esp_new_jpeg is a prebuilt library from Espressif's esp-adf-libs. +ifneq ($(CIRCUITPY_JPEGIO_FAST),0) +BINARY_BLOBS += esp-adf-libs/esp_new_jpeg/lib/esp32s3/libesp_new_jpeg.a +endif + +ifneq ($(CIRCUITPY_RCLCPY),0) + ifeq ($(IDF_TARGET),esp32) + BINARY_BLOBS += microros-lib/esp32/libmicroros.a + else ifeq ($(IDF_TARGET),esp32s2) + BINARY_BLOBS+= microros-lib/esp32s2/libmicroros.a + else ifeq ($(IDF_TARGET),esp32s3) + BINARY_BLOBS += microros-lib/esp32s3/libmicroros.a + else + $(error Unsupported Espressif target for Micro-ROS: $(IDF_TARGET).) + endif +endif + ifneq ($(VALID_BOARD),) # From esp-idf/components/bootloader/Kconfig.projbuild # BOOTLOADER_OFFSET is determined by chip type, based on the ROM bootloader, and is not changeable. @@ -683,10 +1241,16 @@ else ifeq ($(IDF_TARGET),esp32c2) BOOTLOADER_OFFSET = 0x0 else ifeq ($(IDF_TARGET),esp32c3) BOOTLOADER_OFFSET = 0x0 +else ifeq ($(IDF_TARGET),esp32c5) +BOOTLOADER_OFFSET = 0x2000 else ifeq ($(IDF_TARGET),esp32c6) BOOTLOADER_OFFSET = 0x0 +else ifeq ($(IDF_TARGET),esp32c61) +BOOTLOADER_OFFSET = 0x0 else ifeq ($(IDF_TARGET),esp32p4) BOOTLOADER_OFFSET = 0x2000 +else ifeq ($(IDF_TARGET),esp32s31) +BOOTLOADER_OFFSET = 0x2000 else ifeq ($(IDF_TARGET),esp32s3) BOOTLOADER_OFFSET = 0x0 else ifeq ($(IDF_TARGET),esp32s2) @@ -698,7 +1262,7 @@ endif IDF_CMAKE_TARGETS = \ bootloader/bootloader.bin \ - esp-idf/esp_system/__ldgen_output_sections.ld \ + __ldgen_output_sections.ld \ $(foreach component, $(ESP_IDF_COMPONENTS_LINK), esp-idf/$(component)/lib$(component).a) PARTITION_TABLE_OFFSET = 0x8000 @@ -723,9 +1287,9 @@ else ESPTOOLPY_FLASHFREQ = $(CIRCUITPY_ESP_FLASH_FREQ) endif -FLASH_FLAGS = --flash_mode $(ESPTOOLPY_FLASHMODE) --flash_freq $(ESPTOOLPY_FLASHFREQ) --flash_size $(CIRCUITPY_ESP_FLASH_SIZE) +FLASH_FLAGS = --flash-mode $(ESPTOOLPY_FLASHMODE) --flash-freq $(ESPTOOLPY_FLASHFREQ) --flash-size $(CIRCUITPY_ESP_FLASH_SIZE) -ESPTOOL_FLAGS ?= --before=default_reset --after=no_reset --baud 921600 +ESPTOOL_FLAGS ?= --before=default-reset --after=no-reset --baud 921600 ifeq ($(UF2_BOOTLOADER),1) all: $(BUILD)/firmware.bin $(BUILD)/firmware.uf2 @@ -745,7 +1309,7 @@ $(BUILD)/firmware.elf: $(OBJ) | esp-idf-stamp $(IDF_CMAKE_TARGETS) $(BUILD)/circuitpython-firmware.bin: $(BUILD)/firmware.elf | tools/build_memory_info.py $(STEPECHO) "Create $@" - $(Q)esptool.py --chip $(IDF_TARGET) elf2image $(FLASH_FLAGS) --elf-sha256-offset 0xb0 -o $@ $^ + $(Q)esptool --chip $(IDF_TARGET) elf2image $(FLASH_FLAGS) --elf-sha256-offset 0xb0 -o $@ $^ $(Q)$(PYTHON) tools/build_memory_info.py $< $(BUILD)/esp-idf/sdkconfig $@ $(BUILD) ifeq ($(VALID_BOARD),) @@ -757,17 +1321,18 @@ endif UF2_FAMILY_ID_esp32s2 = 0xbfdd4eee UF2_FAMILY_ID_esp32s3 = 0xc47e5767 -UF2_FAMILY_ID_esp32p4 = 0x540ddf62 +UF2_FAMILY_ID_esp32p4 = 0x3d308e94 +UF2_FAMILY_ID_esp32s31 = 0x3101f7c1 $(BUILD)/firmware.uf2: $(BUILD)/circuitpython-firmware.bin $(STEPECHO) "Create $@" $(Q)$(PYTHON) $(TOP)/tools/uf2/utils/uf2conv.py -f $(UF2_FAMILY_ID_$(IDF_TARGET)) -b 0x0000 -c -o $@ $^ flash: $(BUILD)/firmware.bin - esptool.py --chip $(IDF_TARGET) -p $(PORT) $(ESPTOOL_FLAGS) write_flash $(FLASH_FLAGS) 0x0000 $^ + esptool --chip $(IDF_TARGET) -p $(PORT) $(ESPTOOL_FLAGS) write-flash $(FLASH_FLAGS) 0x0000 $^ flash-circuitpython-only: $(BUILD)/circuitpython-firmware.bin - esptool.py --chip $(IDF_TARGET) -p $(PORT) $(ESPTOOL_FLAGS) write_flash $(FLASH_FLAGS) $(FIRMWARE_OFFSET) $^ + esptool --chip $(IDF_TARGET) -p $(PORT) $(ESPTOOL_FLAGS) write-flash $(FLASH_FLAGS) $(FIRMWARE_OFFSET) $^ monitor: $(BUILD)/firmware.elf cp $< build/circuitpython.elf diff --git a/ports/espressif/README.rst b/ports/espressif/README.rst index 63174fd1670..5af91591f7e 100644 --- a/ports/espressif/README.rst +++ b/ports/espressif/README.rst @@ -41,7 +41,7 @@ Connecting to the ESP32-C3 **USB Connection:** -On ESP32-C3 REV3 chips, a USB Serial/JTAG Controller is available. Note: This USB connection cannot be used for a ``CIRCUITPY`` drive. +On ESP32-C3 REV3 chips, a USB Serial/JTAG Controller is available. Note: This USB connection cannot be used for a **CIRCUITPY** drive. Depending on the board you have, the USB port may or may not be connected to native USB. @@ -222,4 +222,3 @@ And follow the Espressif GDB tutorial `instructions for connecting `_ +//| +//| **Limitations:** Currently, setting ``phy_rate`` does nothing. The rate is always 1 Mbps. //| """ //| ... //| @@ -59,8 +61,8 @@ static mp_obj_t espnow_make_new(const mp_obj_type_t *type, size_t n_args, size_t mp_raise_RuntimeError(MP_ERROR_TEXT("Already running")); } - // Allocate a new object - self = mp_obj_malloc(espnow_obj_t, &espnow_type); + // Allocate a new object. The finaliser deinits it if user code doesn't. + self = mp_obj_malloc_with_finaliser(espnow_obj_t, &espnow_type); // Construct the object common_hal_espnow_construct(self, args[ARG_buffer_size].u_int, args[ARG_phy_rate].u_int); @@ -76,8 +78,14 @@ static mp_obj_t espnow_make_new(const mp_obj_type_t *type, size_t n_args, size_t //| static mp_obj_t espnow_deinit(mp_obj_t self_in) { espnow_obj_t *self = MP_OBJ_TO_PTR(self_in); - espnow_check_for_deinit(self); - common_hal_espnow_deinit(self); + if (!common_hal_espnow_deinited(self)) { + common_hal_espnow_deinit(self); + } + // Root pointers are not cleared between VM runs, so don't leave one pointing + // into the old heap. Leave it alone if it already points to a newer ESPNow. + if (MP_STATE_PORT(espnow_singleton) == self) { + MP_STATE_PORT(espnow_singleton) = NULL; + } return mp_const_none; } static MP_DEFINE_CONST_FUN_OBJ_1(espnow_deinit_obj, espnow_deinit); @@ -231,6 +239,8 @@ MP_PROPERTY_GETTER(espnow_buffer_size_obj, //| phy_rate: int //| """The ESP-NOW physical layer rate. //| `wifi_phy_rate_t `_ +//| +//| **Limitations:** Currently, setting ``phy_rate`` does nothing. The rate is always 1 Mbps. //| """ //| static mp_obj_t espnow_get_phy_rate(const mp_obj_t self_in) { @@ -272,6 +282,7 @@ static const mp_rom_map_elem_t espnow_locals_dict_table[] = { // Deinit the object { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&espnow_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&espnow_deinit_obj) }, // Send messages { MP_ROM_QSTR(MP_QSTR_send), MP_ROM_PTR(&espnow_send_obj) }, diff --git a/ports/espressif/bindings/espnow/__init__.h b/ports/espressif/bindings/espnow/__init__.h index a27f5a5ce44..d66bea92b6d 100644 --- a/ports/espressif/bindings/espnow/__init__.h +++ b/ports/espressif/bindings/espnow/__init__.h @@ -5,5 +5,3 @@ // SPDX-License-Identifier: MIT #pragma once - -void espnow_reset(void); diff --git a/ports/espressif/bindings/espulp/ULP.c b/ports/espressif/bindings/espulp/ULP.c index 294678cb1da..04432f546c2 100644 --- a/ports/espressif/bindings/espulp/ULP.c +++ b/ports/espressif/bindings/espulp/ULP.c @@ -20,6 +20,10 @@ //| Raises an exception if another ULP has been instantiated. This //| ensures that is is only used by one piece of code at a time. //| +//| A program started with `run()` keeps running after the VM ends, +//| including during deep sleep, so that it can wake the board with a +//| `ULPAlarm`. Call `halt()` or `deinit()` to stop it. +//| //| :param Architecture arch: The ulp arch. //| """ //| ... @@ -185,6 +189,8 @@ MP_PROPERTY_GETTER(espulp_ulp_arch_obj, static const mp_rom_map_elem_t espulp_ulp_locals_table[] = { { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&espulp_ulp_deinit_obj) }, + // No __del__, and the object has no finaliser: a running ULP program must + // outlive the VM, for example to wake from deep sleep with a ULPAlarm. { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, { MP_ROM_QSTR(MP_QSTR_set_wakeup_period), MP_ROM_PTR(&espulp_ulp_set_wakeup_period_obj) }, diff --git a/ports/espressif/bindings/espulp/__init__.h b/ports/espressif/bindings/espulp/__init__.h index 9212ac83322..7b00972d06a 100644 --- a/ports/espressif/bindings/espulp/__init__.h +++ b/ports/espressif/bindings/espulp/__init__.h @@ -8,6 +8,4 @@ #include "shared-bindings/microcontroller/Pin.h" -void espulp_reset(void); - mp_int_t common_hal_espulp_get_rtc_gpio_number(const mcu_pin_obj_t *pin); diff --git a/ports/espressif/boards/01space_lcd042_esp32c3/board.c b/ports/espressif/boards/01space_lcd042_esp32c3/board.c index c675636bb55..f66ba1eecc1 100644 --- a/ports/espressif/boards/01space_lcd042_esp32c3/board.c +++ b/ports/espressif/boards/01space_lcd042_esp32c3/board.c @@ -37,7 +37,6 @@ void board_init(void) { // What we would do if it wasn't the shared board I2C: (for reference) // busio_i2c_obj_t *i2c = &allocate_display_bus()->i2cdisplay_bus.inline_bus; // common_hal_busio_i2c_construct(i2c, &pin_GPIO23, &pin_GPIO22, 100000, 0); - // common_hal_busio_i2c_never_reset(i2c); i2cdisplaybus_i2cdisplaybus_obj_t *bus = &allocate_display_bus()->i2cdisplay_bus; bus->base.type = &i2cdisplaybus_i2cdisplaybus_type; diff --git a/ports/espressif/boards/01space_lcd042_esp32c3/mpconfigboard.mk b/ports/espressif/boards/01space_lcd042_esp32c3/mpconfigboard.mk index f0067c0d22b..ad0e985cd6f 100644 --- a/ports/espressif/boards/01space_lcd042_esp32c3/mpconfigboard.mk +++ b/ports/espressif/boards/01space_lcd042_esp32c3/mpconfigboard.mk @@ -7,6 +7,4 @@ CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 - CIRCUITPY_ESP_USB_SERIAL_JTAG = 1 diff --git a/ports/espressif/boards/adafruit_esp32s3_camera/board.c b/ports/espressif/boards/adafruit_esp32s3_camera/board.c index e0c357f04c8..d8b0832d3d0 100644 --- a/ports/espressif/boards/adafruit_esp32s3_camera/board.c +++ b/ports/espressif/boards/adafruit_esp32s3_camera/board.c @@ -37,9 +37,9 @@ void board_init(void) { bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_GPIO40, // TFT_DC Command or data - &pin_GPIO39, // TFT_CS Chip select - &pin_GPIO38, // TFT_RESET Reset + MP_OBJ_FROM_PTR(&pin_GPIO40), // TFT_DC Command or data + MP_OBJ_FROM_PTR(&pin_GPIO39), // TFT_CS Chip select + MP_OBJ_FROM_PTR(&pin_GPIO38), // TFT_RESET Reset 40000000, // Baudrate 0, // Polarity 0); // Phase diff --git a/ports/espressif/boards/adafruit_esp32s3_camera/mpconfigboard.h b/ports/espressif/boards/adafruit_esp32s3_camera/mpconfigboard.h index 25d08535dd6..771a3275fb4 100644 --- a/ports/espressif/boards/adafruit_esp32s3_camera/mpconfigboard.h +++ b/ports/espressif/boards/adafruit_esp32s3_camera/mpconfigboard.h @@ -20,3 +20,7 @@ #define DEFAULT_SPI_BUS_MISO (&pin_GPIO37) #define DOUBLE_TAP_PIN (&pin_GPIO42) + +// Turn off presenting SD card to USB by default. Changes settings.toml default for this setting. +// Workaround for https://github.com/adafruit/circuitpython/issues/11109. +#define CIRCUITPY_SDCARD_USB (false) diff --git a/ports/espressif/boards/adafruit_esp32s3_camera/mpconfigboard.mk b/ports/espressif/boards/adafruit_esp32s3_camera/mpconfigboard.mk index 9f8acf042f6..1eda3497585 100644 --- a/ports/espressif/boards/adafruit_esp32s3_camera/mpconfigboard.mk +++ b/ports/espressif/boards/adafruit_esp32s3_camera/mpconfigboard.mk @@ -13,13 +13,13 @@ CIRCUITPY_ESP_PSRAM_SIZE = 2MB CIRCUITPY_ESP_PSRAM_MODE = qio CIRCUITPY_ESP_PSRAM_FREQ = 80m -# No OTA partition: larger firmware partition -FLASH_SIZE_SDKCONFIG = esp-idf-config/sdkconfig-flash-$(CIRCUITPY_ESP_FLASH_SIZE)-no-ota.defaults +CIRCUITPY_ESPCAMERA = 1 CIRCUITPY_AUDIOBUSIO = 0 +CIRCUITPY_AUDIOI2SIN = 0 +CIRCUITPY_AUDIOPWMIO = 0 CIRCUITPY_CANIO = 0 CIRCUITPY_DUALBANK = 0 -CIRCUITPY_ESPCAMERA = 1 CIRCUITPY_FRAMEBUFFERIO = 0 CIRCUITPY_KEYPAD = 0 CIRCUITPY_ONEWIREIO = 0 diff --git a/ports/espressif/boards/adafruit_feather_esp32_v2/board.c b/ports/espressif/boards/adafruit_feather_esp32_v2/board.c index 071ac252727..4ab33d9328b 100644 --- a/ports/espressif/boards/adafruit_feather_esp32_v2/board.c +++ b/ports/espressif/boards/adafruit_feather_esp32_v2/board.c @@ -20,4 +20,10 @@ bool espressif_board_reset_pin_number(gpio_num_t pin_number) { return false; } +void board_init(void) { + // GPIO2 (NEOPIXEL_I2C_POWER) powers the NeoPixel and the STEMMA QT + // connector. Default to high (on). + espressif_board_reset_pin_number(2); +} + // Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/adafruit_feather_esp32c6_4mbflash_nopsram/board.c b/ports/espressif/boards/adafruit_feather_esp32c6_4mbflash_nopsram/board.c index 77a197d3f73..71e6ca32bf6 100644 --- a/ports/espressif/boards/adafruit_feather_esp32c6_4mbflash_nopsram/board.c +++ b/ports/espressif/boards/adafruit_feather_esp32c6_4mbflash_nopsram/board.c @@ -19,4 +19,11 @@ bool espressif_board_reset_pin_number(gpio_num_t pin_number) { return false; } +void board_init(void) { + // GPIO20 (NEOPIXEL_I2C_POWER) powers the NeoPixel and the STEMMA QT + // connector. Default to high (on). After a chip reset the pin is an input + // with no pull-up, which leaves them unpowered. + espressif_board_reset_pin_number(20); +} + // Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/adafruit_feather_esp32c6_4mbflash_nopsram/mpconfigboard.mk b/ports/espressif/boards/adafruit_feather_esp32c6_4mbflash_nopsram/mpconfigboard.mk index f39b1594eda..28821ed7b48 100644 --- a/ports/espressif/boards/adafruit_feather_esp32c6_4mbflash_nopsram/mpconfigboard.mk +++ b/ports/espressif/boards/adafruit_feather_esp32c6_4mbflash_nopsram/mpconfigboard.mk @@ -6,3 +6,6 @@ IDF_TARGET = esp32c6 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB + +# Board was originally defined with a 2MB firmware, almost 2MB user filesystem. Leave it that way. +CIRCUITPY_4MB_FLASH_LARGE_USER_FS_LAYOUT = 1 diff --git a/ports/espressif/boards/adafruit_feather_esp32s2_reverse_tft/board.c b/ports/espressif/boards/adafruit_feather_esp32s2_reverse_tft/board.c index e554be121db..6a79bbbadae 100644 --- a/ports/espressif/boards/adafruit_feather_esp32s2_reverse_tft/board.c +++ b/ports/espressif/boards/adafruit_feather_esp32s2_reverse_tft/board.c @@ -50,6 +50,10 @@ uint8_t display_init_sequence[] = { void board_init(void) { + // GPIO7 (TFT_I2C_POWER) powers the display and the STEMMA QT connector. + // Default to high (on). + espressif_board_reset_pin_number(7); + busio_spi_obj_t *spi = common_hal_board_create_spi(0); fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; bus->base.type = &fourwire_fourwire_type; @@ -57,9 +61,9 @@ void board_init(void) { common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO40, // DC - &pin_GPIO42, // CS - &pin_GPIO41, // RST + MP_OBJ_FROM_PTR(&pin_GPIO40), // DC + MP_OBJ_FROM_PTR(&pin_GPIO42), // CS + MP_OBJ_FROM_PTR(&pin_GPIO41), // RST 40000000, // baudrate 0, // polarity 0 // phase diff --git a/ports/espressif/boards/adafruit_feather_esp32s2_reverse_tft/mpconfigboard.h b/ports/espressif/boards/adafruit_feather_esp32s2_reverse_tft/mpconfigboard.h index 42b51434edf..f2ec187abde 100644 --- a/ports/espressif/boards/adafruit_feather_esp32s2_reverse_tft/mpconfigboard.h +++ b/ports/espressif/boards/adafruit_feather_esp32s2_reverse_tft/mpconfigboard.h @@ -23,7 +23,7 @@ #define DEFAULT_SPI_BUS_MOSI (&pin_GPIO35) #define DEFAULT_SPI_BUS_MISO (&pin_GPIO37) -#define DEFAULT_UART_BUS_RX (&pin_GPIO34) -#define DEFAULT_UART_BUS_TX (&pin_GPIO35) +#define DEFAULT_UART_BUS_RX (&pin_GPIO38) +#define DEFAULT_UART_BUS_TX (&pin_GPIO39) #define DOUBLE_TAP_PIN (&pin_GPIO34) diff --git a/ports/espressif/boards/adafruit_feather_esp32s2_reverse_tft/mpconfigboard.mk b/ports/espressif/boards/adafruit_feather_esp32s2_reverse_tft/mpconfigboard.mk index 06a1bf706d3..a0be8c7a5ca 100644 --- a/ports/espressif/boards/adafruit_feather_esp32s2_reverse_tft/mpconfigboard.mk +++ b/ports/espressif/boards/adafruit_feather_esp32s2_reverse_tft/mpconfigboard.mk @@ -13,3 +13,6 @@ CIRCUITPY_ESP_FLASH_SIZE = 4MB CIRCUITPY_ESP_PSRAM_SIZE = 2MB CIRCUITPY_ESP_PSRAM_MODE = qio CIRCUITPY_ESP_PSRAM_FREQ = 80m + +# Already have a display. +CIRCUITPY_PARALLELDISPLAYBUS = 0 diff --git a/ports/espressif/boards/adafruit_feather_esp32s2_reverse_tft/sdkconfig b/ports/espressif/boards/adafruit_feather_esp32s2_reverse_tft/sdkconfig index e69de29bb2d..e9628662160 100644 --- a/ports/espressif/boards/adafruit_feather_esp32s2_reverse_tft/sdkconfig +++ b/ports/espressif/boards/adafruit_feather_esp32s2_reverse_tft/sdkconfig @@ -0,0 +1,14 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Component config +# +# +# LWIP +# +# end of LWIP + +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/boards/adafruit_feather_esp32s2_tft/board.c b/ports/espressif/boards/adafruit_feather_esp32s2_tft/board.c index 1ebb357aed5..9b363204ae2 100644 --- a/ports/espressif/boards/adafruit_feather_esp32s2_tft/board.c +++ b/ports/espressif/boards/adafruit_feather_esp32s2_tft/board.c @@ -50,6 +50,10 @@ uint8_t display_init_sequence[] = { void board_init(void) { + // GPIO21 (TFT_I2C_POWER) powers the display and the STEMMA QT connector. + // Default to high (on). + espressif_board_reset_pin_number(21); + busio_spi_obj_t *spi = common_hal_board_create_spi(0); fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; bus->base.type = &fourwire_fourwire_type; @@ -57,9 +61,9 @@ void board_init(void) { common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO39, // DC - &pin_GPIO7, // CS - &pin_GPIO40, // RST + MP_OBJ_FROM_PTR(&pin_GPIO39), // DC + MP_OBJ_FROM_PTR(&pin_GPIO7), // CS + MP_OBJ_FROM_PTR(&pin_GPIO40), // RST 40000000, // baudrate 0, // polarity 0 // phase diff --git a/ports/espressif/boards/adafruit_feather_esp32s3_4mbflash_2mbpsram/mpconfigboard.mk b/ports/espressif/boards/adafruit_feather_esp32s3_4mbflash_2mbpsram/mpconfigboard.mk index 68abfe8cca7..6fafa82485a 100644 --- a/ports/espressif/boards/adafruit_feather_esp32s3_4mbflash_2mbpsram/mpconfigboard.mk +++ b/ports/espressif/boards/adafruit_feather_esp32s3_4mbflash_2mbpsram/mpconfigboard.mk @@ -12,7 +12,3 @@ CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_PSRAM_SIZE = 2MB CIRCUITPY_ESP_PSRAM_MODE = qio CIRCUITPY_ESP_PSRAM_FREQ = 80m - -OPTIMIZATION_FLAGS = -Os -CIRCUITPY_ESPCAMERA = 0 -CIRCUITPY_PARALLELDISPLAYBUS = 0 diff --git a/ports/espressif/boards/adafruit_feather_esp32s3_nopsram/mpconfigboard.mk b/ports/espressif/boards/adafruit_feather_esp32s3_nopsram/mpconfigboard.mk index bf0dc3f320f..cdf1657d8be 100644 --- a/ports/espressif/boards/adafruit_feather_esp32s3_nopsram/mpconfigboard.mk +++ b/ports/espressif/boards/adafruit_feather_esp32s3_nopsram/mpconfigboard.mk @@ -8,4 +8,3 @@ IDF_TARGET = esp32s3 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 8MB -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/adafruit_feather_esp32s3_reverse_tft/board.c b/ports/espressif/boards/adafruit_feather_esp32s3_reverse_tft/board.c index e554be121db..6a79bbbadae 100644 --- a/ports/espressif/boards/adafruit_feather_esp32s3_reverse_tft/board.c +++ b/ports/espressif/boards/adafruit_feather_esp32s3_reverse_tft/board.c @@ -50,6 +50,10 @@ uint8_t display_init_sequence[] = { void board_init(void) { + // GPIO7 (TFT_I2C_POWER) powers the display and the STEMMA QT connector. + // Default to high (on). + espressif_board_reset_pin_number(7); + busio_spi_obj_t *spi = common_hal_board_create_spi(0); fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; bus->base.type = &fourwire_fourwire_type; @@ -57,9 +61,9 @@ void board_init(void) { common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO40, // DC - &pin_GPIO42, // CS - &pin_GPIO41, // RST + MP_OBJ_FROM_PTR(&pin_GPIO40), // DC + MP_OBJ_FROM_PTR(&pin_GPIO42), // CS + MP_OBJ_FROM_PTR(&pin_GPIO41), // RST 40000000, // baudrate 0, // polarity 0 // phase diff --git a/ports/espressif/boards/adafruit_feather_esp32s3_reverse_tft/mpconfigboard.h b/ports/espressif/boards/adafruit_feather_esp32s3_reverse_tft/mpconfigboard.h index c11780faf41..5053a1b2b58 100644 --- a/ports/espressif/boards/adafruit_feather_esp32s3_reverse_tft/mpconfigboard.h +++ b/ports/espressif/boards/adafruit_feather_esp32s3_reverse_tft/mpconfigboard.h @@ -23,7 +23,7 @@ #define DEFAULT_SPI_BUS_MOSI (&pin_GPIO35) #define DEFAULT_SPI_BUS_MISO (&pin_GPIO37) -#define DEFAULT_UART_BUS_RX (&pin_GPIO34) -#define DEFAULT_UART_BUS_TX (&pin_GPIO35) +#define DEFAULT_UART_BUS_RX (&pin_GPIO38) +#define DEFAULT_UART_BUS_TX (&pin_GPIO39) #define DOUBLE_TAP_PIN (&pin_GPIO34) diff --git a/ports/espressif/boards/adafruit_feather_esp32s3_reverse_tft/mpconfigboard.mk b/ports/espressif/boards/adafruit_feather_esp32s3_reverse_tft/mpconfigboard.mk index 0aebfea1713..a82ae6d4f04 100644 --- a/ports/espressif/boards/adafruit_feather_esp32s3_reverse_tft/mpconfigboard.mk +++ b/ports/espressif/boards/adafruit_feather_esp32s3_reverse_tft/mpconfigboard.mk @@ -14,5 +14,5 @@ CIRCUITPY_ESP_PSRAM_SIZE = 2MB CIRCUITPY_ESP_PSRAM_MODE = qio CIRCUITPY_ESP_PSRAM_FREQ = 80m -CIRCUITPY_ESPCAMERA = 0 +# Already have a display. CIRCUITPY_PARALLELDISPLAYBUS = 0 diff --git a/ports/espressif/boards/adafruit_feather_esp32s3_tft/board.c b/ports/espressif/boards/adafruit_feather_esp32s3_tft/board.c index e3569d864e7..269af4e67fa 100644 --- a/ports/espressif/boards/adafruit_feather_esp32s3_tft/board.c +++ b/ports/espressif/boards/adafruit_feather_esp32s3_tft/board.c @@ -50,6 +50,10 @@ uint8_t display_init_sequence[] = { void board_init(void) { + // GPIO21 (TFT_I2C_POWER) powers the display and the STEMMA QT connector. + // Default to high (on). + espressif_board_reset_pin_number(21); + busio_spi_obj_t *spi = common_hal_board_create_spi(0); fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; bus->base.type = &fourwire_fourwire_type; @@ -57,9 +61,9 @@ void board_init(void) { common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO39, // DC - &pin_GPIO7, // CS - &pin_GPIO40, // RST + MP_OBJ_FROM_PTR(&pin_GPIO39), // DC + MP_OBJ_FROM_PTR(&pin_GPIO7), // CS + MP_OBJ_FROM_PTR(&pin_GPIO40), // RST 40000000, // baudrate 0, // polarity 0 // phase diff --git a/ports/espressif/boards/adafruit_feather_esp32s3_tft/mpconfigboard.mk b/ports/espressif/boards/adafruit_feather_esp32s3_tft/mpconfigboard.mk index c7d6c33a3fd..71ef6d222a2 100644 --- a/ports/espressif/boards/adafruit_feather_esp32s3_tft/mpconfigboard.mk +++ b/ports/espressif/boards/adafruit_feather_esp32s3_tft/mpconfigboard.mk @@ -10,9 +10,9 @@ CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB -CIRCUITPY_ESPCAMERA = 0 -CIRCUITPY_PARALLELDISPLAYBUS = 0 - CIRCUITPY_ESP_PSRAM_SIZE = 2MB CIRCUITPY_ESP_PSRAM_MODE = qio CIRCUITPY_ESP_PSRAM_FREQ = 80m + +# Already have a display. +CIRCUITPY_PARALLELDISPLAYBUS = 0 diff --git a/ports/espressif/boards/adafruit_feather_huzzah32/mpconfigboard.mk b/ports/espressif/boards/adafruit_feather_huzzah32/mpconfigboard.mk index 2715f5ca306..f948521eb6d 100644 --- a/ports/espressif/boards/adafruit_feather_huzzah32/mpconfigboard.mk +++ b/ports/espressif/boards/adafruit_feather_huzzah32/mpconfigboard.mk @@ -6,6 +6,3 @@ IDF_TARGET = esp32 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB - -CIRCUITPY_BLEIO = 0 -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/adafruit_funhouse/board.c b/ports/espressif/boards/adafruit_funhouse/board.c index 061a6abf0d8..5ced72da2aa 100644 --- a/ports/espressif/boards/adafruit_funhouse/board.c +++ b/ports/espressif/boards/adafruit_funhouse/board.c @@ -32,14 +32,13 @@ void board_init(void) { fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_GPIO36, &pin_GPIO35, NULL, false); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_GPIO39, // TFT_DC Command or data - &pin_GPIO40, // TFT_CS Chip select - &pin_GPIO41, // TFT_RESET Reset + MP_OBJ_FROM_PTR(&pin_GPIO39), // TFT_DC Command or data + MP_OBJ_FROM_PTR(&pin_GPIO40), // TFT_CS Chip select + MP_OBJ_FROM_PTR(&pin_GPIO41), // TFT_RESET Reset 5000000, // Baudrate 0, // Polarity 0); // Phase diff --git a/ports/espressif/boards/adafruit_funhouse/mpconfigboard.mk b/ports/espressif/boards/adafruit_funhouse/mpconfigboard.mk index e956964776c..43045b4cd98 100644 --- a/ports/espressif/boards/adafruit_funhouse/mpconfigboard.mk +++ b/ports/espressif/boards/adafruit_funhouse/mpconfigboard.mk @@ -9,6 +9,11 @@ CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB +CIRCUITPY_ESP_PSRAM_SIZE = 2MB +CIRCUITPY_ESP_PSRAM_MODE = qio +CIRCUITPY_ESP_PSRAM_FREQ = 80m + +# Specialized board. CIRCUITPY_ESPCAMERA = 0 CIRCUITPY_MAX3421E = 0 CIRCUITPY_PS2IO = 0 @@ -21,7 +26,3 @@ CIRCUITPY_FRAMEBUFFERIO = 0 # Include these Python libraries in firmware. FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel - -CIRCUITPY_ESP_PSRAM_SIZE = 2MB -CIRCUITPY_ESP_PSRAM_MODE = qio -CIRCUITPY_ESP_PSRAM_FREQ = 80m diff --git a/ports/espressif/boards/adafruit_huzzah32_breakout/mpconfigboard.mk b/ports/espressif/boards/adafruit_huzzah32_breakout/mpconfigboard.mk index 24909715b97..9b816b2ba28 100644 --- a/ports/espressif/boards/adafruit_huzzah32_breakout/mpconfigboard.mk +++ b/ports/espressif/boards/adafruit_huzzah32_breakout/mpconfigboard.mk @@ -6,7 +6,3 @@ IDF_TARGET = esp32 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB - -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 - -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/adafruit_itsybitsy_esp32/board.c b/ports/espressif/boards/adafruit_itsybitsy_esp32/board.c index 6474622a682..38dd403f106 100644 --- a/ports/espressif/boards/adafruit_itsybitsy_esp32/board.c +++ b/ports/espressif/boards/adafruit_itsybitsy_esp32/board.c @@ -19,4 +19,9 @@ bool espressif_board_reset_pin_number(gpio_num_t pin_number) { return false; } +void board_init(void) { + // GPIO2 (NEOPIXEL_POWER) powers the NeoPixel. Default to high (on). + espressif_board_reset_pin_number(2); +} + // Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/adafruit_magtag_2.9_grayscale/board.c b/ports/espressif/boards/adafruit_magtag_2.9_grayscale/board.c index 321a5a1f2c7..cab5ee4bac1 100644 --- a/ports/espressif/boards/adafruit_magtag_2.9_grayscale/board.c +++ b/ports/espressif/boards/adafruit_magtag_2.9_grayscale/board.c @@ -7,9 +7,11 @@ #include "supervisor/board.h" #include "mpconfigboard.h" +#include "driver/gpio.h" #include "shared-bindings/busio/SPI.h" #include "shared-bindings/fourwire/FourWire.h" #include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/microcontroller/__init__.h" #include "shared-module/displayio/__init__.h" #include "supervisor/shared/board.h" @@ -21,7 +23,7 @@ static const char *TAG = "board"; // This is an ILO373 control chip. The display is a 2.9" grayscale EInk. -const uint8_t display_start_sequence[] = { +const uint8_t il0373_display_start_sequence[] = { 0x01, 5, 0x03, 0x00, 0x2b, 0x2b, 0x13, // power setting 0x06, 3, 0x17, 0x17, 0x17, // booster soft start 0x04, DELAY, 200, // power on and wait 200 ms @@ -83,66 +85,278 @@ const uint8_t display_start_sequence[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; -const uint8_t display_stop_sequence[] = { +const uint8_t il0373_display_stop_sequence[] = { 0x50, 0x01, 0x17, // CDI Setting 0x82, 0x01, 0x00, // VCM DC to -0.1V 0x02, 0x00 // Power off }; -const uint8_t refresh_sequence[] = { +const uint8_t il0373_display_refresh_sequence[] = { 0x12, 0x00 }; + +// This is an SSD1680 control chip. The display is a 2.9" grayscale EInk. +const uint8_t ssd1680_display_start_sequence[] = { + 0x12, DELAY, 0x00, 0x14, // soft reset and wait 20ms + 0x11, 0x00, 0x01, 0x03, // Ram data entry mode + 0x3c, 0x00, 0x01, 0x03, // border color + 0x2c, 0x00, 0x01, 0x28, // Set vcom voltage + 0x03, 0x00, 0x01, 0x17, // Set gate voltage + 0x04, 0x00, 0x03, 0x41, 0xae, 0x32, // Set source voltage + 0x4e, 0x00, 0x01, 0x01, // ram x count + 0x4f, 0x00, 0x02, 0x00, 0x00, // ram y count + 0x01, 0x00, 0x03, 0x27, 0x01, 0x00, // set display size + 0x32, 0x00, 0x99, // Update waveforms + 0x2a, 0x60, 0x15, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // VS L0 + 0x20, 0x60, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // VS L1 + 0x28, 0x60, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // VS L2 + 0x00, 0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // VS L3 + 0x00, 0x90, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // VS L4 + 0x00, 0x02, 0x00, 0x05, 0x14, 0x00, 0x00, // TP, SR, RP of Group0 + 0x1E, 0x1E, 0x00, 0x00, 0x00, 0x00, 0x01, // TP, SR, RP of Group1 + 0x00, 0x02, 0x00, 0x05, 0x14, 0x00, 0x00, // TP, SR, RP of Group2 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // TP, SR, RP of Group3 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // TP, SR, RP of Group4 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // TP, SR, RP of Group5 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // TP, SR, RP of Group6 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // TP, SR, RP of Group7 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // TP, SR, RP of Group8 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // TP, SR, RP of Group9 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // TP, SR, RP of Group10 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // TP, SR, RP of Group11 + 0x24, 0x22, 0x22, 0x22, 0x23, 0x32, 0x00, 0x00, 0x00, // FR, XON + 0x22, 0x00, 0x01, 0xc7 // display update mode +}; + +// FPC-7519rev.b panels (User ID byte 0x44 or 0xca) need colstart=8 and tuned VCOM + LUT. +// LUT: Good Display reference (GxEPD2_4G / GDEM029T94) with VS rows reversed (L0↔L3, L1↔L2). +// Reason: CircuitPython maps luma 0→L0 and luma 255→L3. On this panel VSH1(0x40) drives WHITE and +// VSL(0x20) drives BLACK, so L0 must carry the black-driving waveform and L3 the white-driving +// waveform — opposite from GxEPD2_4G's Arduino convention (where index 0 = white constant). +// VS=0x48 = VSH1/GND/VSL/GND alternating for DC balance. +// VCOM=0x24 empirically tuned for FPC-7519rev.b contrast. Both 0x44 and 0xca share this sequence. +const uint8_t ssd1680_fpc7519_display_start_sequence[] = { + 0x12, DELAY, 0x00, 0x14, // soft reset and wait 20ms + 0x11, 0x00, 0x01, 0x03, // Ram data entry mode + 0x3c, 0x00, 0x01, 0x03, // border color + 0x2c, 0x00, 0x01, 0x24, // Set vcom voltage (0x24 tuned for FPC-7519rev.b contrast) + 0x03, 0x00, 0x01, 0x17, // Set gate voltage + 0x04, 0x00, 0x03, 0x41, 0xae, 0x32, // Set source voltage + 0x4e, 0x00, 0x01, 0x01, // ram x count + 0x4f, 0x00, 0x02, 0x00, 0x00, // ram y count + 0x01, 0x00, 0x03, 0x27, 0x01, 0x00, // set display size + 0x32, 0x00, 0x99, // Update waveforms (153 bytes follow) + // VS rows: only L0↔L3 are swapped relative to GxEPD2_4G; L1 and L2 stay in place. + // Reason: CircuitPython luma maps 0→L0, 64-127→L2, 128-191→L1, 255→L3. + // GxEPD2 uses L0=white-driver, L3=black-driver (opposite of CircuitPython for extremes). + // GxEPD2 L1=lighter-gray, L2=darker-gray; CircuitPython L1=mid-bright, L2=mid-dark — same ordering. + // So: swap only L0↔L3 (polarity); L1 and L2 keep their GxEPD2 positions (gradient preserved). + // 0x48 = VSH1/GND/VSL/GND alternating — better DC balance than 0x60 (VSH1/VSL/GND/GND) + 0x20, 0x48, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // VS L0 (darkest/black) ← GxEPD2 L3 + 0x08, 0x48, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // VS L1 (mid-light) ← GxEPD2 L1 (luma 128-191 → lighter) + 0x02, 0x48, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // VS L2 (mid-dark) ← GxEPD2 L2 (luma 64-127 → darker) + 0x40, 0x48, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // VS L3 (lightest/white) ← GxEPD2 L0 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // VS L4 VCOM + // Timing groups — Good Display reference timing + 0x0A, 0x19, 0x00, 0x03, 0x08, 0x00, 0x00, // Group0: 10+25 / 3+8 frames activation + 0x14, 0x01, 0x00, 0x14, 0x01, 0x00, 0x03, // Group1: 20+1 / 20+1 frames, RP=3 repeats + 0x0A, 0x03, 0x00, 0x08, 0x19, 0x00, 0x00, // Group2: 10+3 / 8+25 frames (mirror of G0) + 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, // Group3: 1 frame settle + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Group4 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Group5 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Group6 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Group7 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Group8 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Group9 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Group10 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Group11 + 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, // XON + 0x22, 0x00, 0x01, 0xc7 // display update mode +}; + +const uint8_t ssd1680_display_stop_sequence[] = { + 0x10, DELAY, 0x01, 0x01, 0x64 +}; + +const uint8_t ssd1680_display_refresh_sequence[] = { + 0x20, 0x00, 0x00 +}; + + +typedef enum { + DISPLAY_IL0373, + DISPLAY_SSD1680_COLSTART_0, + DISPLAY_SSD1680_COLSTART_8, // FPC-7519rev.b (User ID 0x44 or 0xca) +} display_type_t; + +static display_type_t detect_display_type(void) { + // Bitbang 4-wire SPI with a bidirectional data line to read the first byte of register 0x2e, + // which is the 10-byte USER ID. + // NOTE: the SSD1680 drives its response back on the MOSI/DATA line (GPIO35) in half-duplex + // mode, NOT on the separate MISO line (GPIO37). Read with GPIO35 switched to input. + // On the IL0373 it will return 0xff because it's not a valid register. + // With SSD1680, we have seen two types: + // 1. The first batch of displays, labeled "FPC-A005 20.06.15 TRX", which needs colstart=0. + // These have 10 bytes of zeros in the User ID. + // 2. Later panels, labeled "FPC-7519rev.b", which need colstart=8 and a tuned LUT/VCOM. + // Two controller variants exist within this panel generation: + // User ID [0x44, 0x0, 0x4, 0x0, 0x25, 0x0, 0x1, 0x78, 0x2b, 0xe] + // User ID [0xca, 0xfe, 0x0, 0x16, 0x80, 0x0, 0x75, 0x1, 0x0, 0x98] + // Both carry the same ribbon label and show the same display characteristics. + // So let's distinguish just by the first byte. + digitalio_digitalinout_obj_t data; + digitalio_digitalinout_obj_t clock; + digitalio_digitalinout_obj_t chip_select; + digitalio_digitalinout_obj_t data_command; + digitalio_digitalinout_obj_t reset; + data.base.type = &digitalio_digitalinout_type; + clock.base.type = &digitalio_digitalinout_type; + chip_select.base.type = &digitalio_digitalinout_type; + data_command.base.type = &digitalio_digitalinout_type; + reset.base.type = &digitalio_digitalinout_type; + + common_hal_digitalio_digitalinout_construct(&data, &pin_GPIO35); + common_hal_digitalio_digitalinout_construct(&clock, &pin_GPIO36); + common_hal_digitalio_digitalinout_construct(&chip_select, &pin_GPIO8); + common_hal_digitalio_digitalinout_construct(&data_command, &pin_GPIO7); + common_hal_digitalio_digitalinout_construct(&reset, &pin_GPIO6); + + // Set CS and DC low + common_hal_digitalio_digitalinout_switch_to_output(&chip_select, false, DRIVE_MODE_PUSH_PULL); + common_hal_digitalio_digitalinout_switch_to_output(&data_command, false, DRIVE_MODE_PUSH_PULL); + common_hal_digitalio_digitalinout_switch_to_output(&data, false, DRIVE_MODE_PUSH_PULL); + common_hal_digitalio_digitalinout_switch_to_output(&clock, false, DRIVE_MODE_PUSH_PULL); + + // Pulse RESET low to wake SSD1680 from deep sleep (entered via stop_sequence on prior run). + // SSD1680 ignores all SPI commands while in deep sleep; only a hardware reset exits it. + common_hal_digitalio_digitalinout_switch_to_output(&reset, false, DRIVE_MODE_PUSH_PULL); + common_hal_mcu_delay_us(200); + common_hal_digitalio_digitalinout_set_value(&reset, true); + common_hal_mcu_delay_us(10000); // 10ms for controller to come out of reset + + uint8_t status_read = 0x2e; // SSD1680 User ID register. Not a valid register on IL0373. + for (int i = 0; i < 8; i++) { + common_hal_digitalio_digitalinout_set_value(&data, (status_read & (1 << (7 - i))) != 0); + common_hal_digitalio_digitalinout_set_value(&clock, true); + common_hal_digitalio_digitalinout_set_value(&clock, false); + } + + // Set DC high for data and switch to input with pull-up in case the SSD1680 doesn't send any + // data back (as it should.) + common_hal_digitalio_digitalinout_switch_to_input(&data, PULL_UP); + common_hal_digitalio_digitalinout_set_value(&data_command, true); + uint8_t status = 0; + for (int bit = 0; bit < 8; bit++) { + status <<= 1; + if (common_hal_digitalio_digitalinout_get_value(&data)) { + status |= 1; + } + common_hal_digitalio_digitalinout_set_value(&clock, true); + common_hal_digitalio_digitalinout_set_value(&clock, false); + } + + // Set CS high + common_hal_digitalio_digitalinout_set_value(&chip_select, true); + + common_hal_digitalio_digitalinout_deinit(&data); + common_hal_digitalio_digitalinout_deinit(&clock); + common_hal_digitalio_digitalinout_deinit(&chip_select); + common_hal_digitalio_digitalinout_deinit(&data_command); + common_hal_digitalio_digitalinout_deinit(&reset); + + switch (status) { + case 0xff: + return DISPLAY_IL0373; + case 0x00: + return DISPLAY_SSD1680_COLSTART_0; + default: // unknown SSD1680 variant — assume newer panel needs colstart=8 + case 0x44: + case 0xca: + return DISPLAY_SSD1680_COLSTART_8; + } +} + void board_init(void) { + // GPIO16 (SPEAKER_ENABLE) has an external pull-down that keeps the speaker + // off. Default to no internal pull, so as not to fight it. + espressif_board_reset_pin_number(16); + + display_type_t display_type = detect_display_type(); + fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_GPIO36, &pin_GPIO35, NULL, false); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_GPIO7, // EPD_DC Command or data - &pin_GPIO8, // EPD_CS Chip select - &pin_GPIO6, // EPD_RST Reset + MP_OBJ_FROM_PTR(&pin_GPIO7), // EPD_DC Command or data + MP_OBJ_FROM_PTR(&pin_GPIO8), // EPD_CS Chip select + MP_OBJ_FROM_PTR(&pin_GPIO6), // EPD_RST Reset 4000000, // Baudrate 0, // Polarity 0); // Phase epaperdisplay_epaperdisplay_obj_t *display = &allocate_display()->epaper_display; display->base.type = &epaperdisplay_epaperdisplay_type; - common_hal_epaperdisplay_epaperdisplay_construct( - display, - bus, - display_start_sequence, sizeof(display_start_sequence), - 0, // start up time - display_stop_sequence, sizeof(display_stop_sequence), - 296, // width - 128, // height - 160, // ram_width - 296, // ram_height - 0, // colstart - 0, // rowstart - 270, // rotation - NO_COMMAND, // set_column_window_command - NO_COMMAND, // set_row_window_command - NO_COMMAND, // set_current_column_command - NO_COMMAND, // set_current_row_command - 0x10, // write_black_ram_command - false, // black_bits_inverted - 0x13, // write_color_ram_command - false, // color_bits_inverted - 0x000000, // highlight_color - refresh_sequence, sizeof(refresh_sequence), - 1.0, // refresh_time - &pin_GPIO5, // busy_pin - false, // busy_state - 5.0, // seconds_per_frame - false, // always_toggle_chip_select - true, // grayscale - false, // acep - false, // two_byte_sequence_length - false); // address_little_endian + + if (display_type == DISPLAY_IL0373) { + epaperdisplay_construct_args_t args = EPAPERDISPLAY_CONSTRUCT_ARGS_DEFAULTS; + args.bus = bus; + args.start_sequence = il0373_display_start_sequence; + args.start_sequence_len = sizeof(il0373_display_start_sequence); + args.stop_sequence = il0373_display_stop_sequence; + args.stop_sequence_len = sizeof(il0373_display_stop_sequence); + args.width = 296; + args.height = 128; + args.ram_width = 160; + args.ram_height = 296; + args.rotation = 270; + args.write_black_ram_command = 0x10; + args.write_color_ram_command = 0x13; + args.refresh_sequence = il0373_display_refresh_sequence; + args.refresh_sequence_len = sizeof(il0373_display_refresh_sequence); + args.refresh_time = 1.0; + args.busy_pin = &pin_GPIO5; + args.seconds_per_frame = 5.0; + args.grayscale = true; + common_hal_epaperdisplay_epaperdisplay_construct(display, &args); + } else { + epaperdisplay_construct_args_t args = EPAPERDISPLAY_CONSTRUCT_ARGS_DEFAULTS; + args.bus = bus; + if (display_type == DISPLAY_SSD1680_COLSTART_8) { + args.colstart = 8; + args.start_sequence = ssd1680_fpc7519_display_start_sequence; + args.start_sequence_len = sizeof(ssd1680_fpc7519_display_start_sequence); + } else { + args.start_sequence = ssd1680_display_start_sequence; + args.start_sequence_len = sizeof(ssd1680_display_start_sequence); + } + args.stop_sequence = ssd1680_display_stop_sequence; + args.stop_sequence_len = sizeof(ssd1680_display_stop_sequence); + args.width = 296; + args.height = 128; + args.ram_width = 250; + args.ram_height = 296; + args.rotation = 270; + args.set_column_window_command = 0x44; + args.set_row_window_command = 0x45; + args.set_current_column_command = 0x4e; + args.set_current_row_command = 0x4f; + args.write_black_ram_command = 0x24; + args.write_color_ram_command = 0x26; + args.refresh_sequence = ssd1680_display_refresh_sequence; + args.refresh_sequence_len = sizeof(ssd1680_display_refresh_sequence); + args.refresh_time = 1.0; + args.busy_pin = &pin_GPIO5; + args.busy_state = true; + args.seconds_per_frame = 5.0; + args.grayscale = true; + args.two_byte_sequence_length = true; + args.address_little_endian = true; + common_hal_epaperdisplay_epaperdisplay_construct(display, &args); + } } bool espressif_board_reset_pin_number(gpio_num_t pin_number) { diff --git a/ports/espressif/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.mk b/ports/espressif/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.mk index 01b9ec73e9c..582eb32eaef 100644 --- a/ports/espressif/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.mk +++ b/ports/espressif/boards/adafruit_magtag_2.9_grayscale/mpconfigboard.mk @@ -9,7 +9,11 @@ CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB -CIRCUITPY_ESPCAMERA = 0 +CIRCUITPY_ESP_PSRAM_SIZE = 2MB +CIRCUITPY_ESP_PSRAM_MODE = qio +CIRCUITPY_ESP_PSRAM_FREQ = 80m + +CIRCUITPY_PARALLELDISPLAYBUS = 0 # Include these Python libraries in firmware. FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_ConnectionManager @@ -19,7 +23,3 @@ FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_Requests FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_Display_Text FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_LIS3DH - -CIRCUITPY_ESP_PSRAM_SIZE = 2MB -CIRCUITPY_ESP_PSRAM_MODE = qio -CIRCUITPY_ESP_PSRAM_FREQ = 80m diff --git a/ports/espressif/boards/adafruit_matrixportal_s3/mpconfigboard.mk b/ports/espressif/boards/adafruit_matrixportal_s3/mpconfigboard.mk index 51a03b34610..e213980ccdf 100644 --- a/ports/espressif/boards/adafruit_matrixportal_s3/mpconfigboard.mk +++ b/ports/espressif/boards/adafruit_matrixportal_s3/mpconfigboard.mk @@ -13,7 +13,6 @@ CIRCUITPY_ESP_PSRAM_SIZE = 2MB CIRCUITPY_ESP_PSRAM_MODE = qio CIRCUITPY_ESP_PSRAM_FREQ = 80m -CIRCUITPY_ESPCAMERA = 0 - # Not enough pins. +CIRCUITPY_ESPCAMERA = 0 CIRCUITPY_PARALLELDISPLAYBUS = 0 diff --git a/ports/espressif/boards/adafruit_metro_esp32p4/board.c b/ports/espressif/boards/adafruit_metro_esp32p4/board.c new file mode 100644 index 00000000000..85e13ed334d --- /dev/null +++ b/ports/espressif/boards/adafruit_metro_esp32p4/board.c @@ -0,0 +1,24 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Limor Fried for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" +#include "esp_ldo_regulator.h" + +static esp_ldo_channel_handle_t io_ldo; + +void board_init(void) { + // Keep the rail acquired across simulated deep-sleep wakes. + if (io_ldo != NULL) { + return; + } + + // The SD card and C6 control pins (GPIO39-48) require the VO4 3.3 V rail. + const esp_ldo_channel_config_t config = { + .chan_id = 4, + .voltage_mv = 3300, + }; + ESP_ERROR_CHECK(esp_ldo_acquire_channel(&config, &io_ldo)); +} diff --git a/ports/espressif/boards/adafruit_metro_esp32p4/mpconfigboard.h b/ports/espressif/boards/adafruit_metro_esp32p4/mpconfigboard.h new file mode 100644 index 00000000000..ac80ec50f38 --- /dev/null +++ b/ports/espressif/boards/adafruit_metro_esp32p4/mpconfigboard.h @@ -0,0 +1,29 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Limor Fried for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#define MICROPY_HW_BOARD_NAME "Adafruit Metro ESP32-P4" +#define MICROPY_HW_MCU_NAME "ESP32P4" + +#define MICROPY_HW_NEOPIXEL (&pin_GPIO23) +#define CIRCUITPY_BOOT_BUTTON (&pin_GPIO35) + +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO32) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO33) + +#define DEFAULT_SPI_BUS_SCK (&pin_GPIO15) +#define DEFAULT_SPI_BUS_MOSI (&pin_GPIO16) +#define DEFAULT_SPI_BUS_MISO (&pin_GPIO17) + +#define DEFAULT_UART_BUS_RX (&pin_GPIO0) +#define DEFAULT_UART_BUS_TX (&pin_GPIO1) + +// USB-C shares GPIO24/25 with the ROM USB Serial/JTAG downloader. +#define CIRCUITPY_ESP32P4_SWAP_LSFS (1) + +// USB-A is connected to the dedicated high-speed PHY. +#define CIRCUITPY_USB_HOST_INSTANCE 1 diff --git a/ports/espressif/boards/adafruit_metro_esp32p4/mpconfigboard.mk b/ports/espressif/boards/adafruit_metro_esp32p4/mpconfigboard.mk new file mode 100644 index 00000000000..bfce2e41c35 --- /dev/null +++ b/ports/espressif/boards/adafruit_metro_esp32p4/mpconfigboard.mk @@ -0,0 +1,26 @@ +USB_VID = 0x239A +USB_PID = 0x817C +USB_PRODUCT = "Adafruit Metro ESP32-P4" +USB_MANUFACTURER = "Adafruit" + +IDF_TARGET = esp32p4 + +CIRCUITPY_USB_DEVICE_INSTANCE = FULL_SPEED_INSTANCE + +CIRCUITPY_AUDIOFILEWRITER = 1 +CIRCUITPY_USB_HOST = 1 +CIRCUITPY_USB_HOST_AUDIO = 1 +CIRCUITPY_ESP_HOSTED = 1 + +CIRCUITPY_ESP_FLASH_SIZE = 16MB +CIRCUITPY_ESP_FLASH_MODE = dio +CIRCUITPY_ESP_FLASH_FREQ = 80m + +CIRCUITPY_ESP_PSRAM_SIZE = 16MB +CIRCUITPY_ESP_PSRAM_MODE = hpi +CIRCUITPY_ESP_PSRAM_FREQ = 200m + +# Some USB MIDI devices, such as the M-Vave FM-1, have configuration descriptors +# over the 288-byte default. TinyUSB skips enumerating any device whose +# descriptor doesn't fit here. +CFLAGS += -DCFG_TUH_ENUMERATION_BUFSIZE=512 diff --git a/ports/espressif/boards/adafruit_metro_esp32p4/pins.c b/ports/espressif/boards/adafruit_metro_esp32p4/pins.c new file mode 100644 index 00000000000..ee2679ae1f0 --- /dev/null +++ b/ports/espressif/boards/adafruit_metro_esp32p4/pins.c @@ -0,0 +1,81 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Limor Fried for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_GPIO49) }, + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO50) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO51) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO52) }, + { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_GPIO53) }, + { MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_GPIO54) }, + + { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO1) }, + { 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_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_SCK), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO32) }, + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO33) }, + + { MP_ROM_QSTR(MP_QSTR_BUTTON), MP_ROM_PTR(&pin_GPIO35) }, + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_VOLTAGE_MONITOR), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_USB_HOST_DP), MP_ROM_PTR(&pin_USB_HS_DP) }, + { MP_ROM_QSTR(MP_QSTR_USB_HOST_DM), MP_ROM_PTR(&pin_USB_HS_DM) }, + { MP_ROM_QSTR(MP_QSTR_USB_HOST_POWER), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_DEBUG_TX), MP_ROM_PTR(&pin_GPIO37) }, + { MP_ROM_QSTR(MP_QSTR_DEBUG_RX), MP_ROM_PTR(&pin_GPIO38) }, + + { MP_ROM_QSTR(MP_QSTR_SD_CLK), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_SD_CMD), MP_ROM_PTR(&pin_GPIO44) }, + { MP_ROM_QSTR(MP_QSTR_SD_DATA0), MP_ROM_PTR(&pin_GPIO39) }, + { MP_ROM_QSTR(MP_QSTR_SD_DATA1), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_SD_DATA2), MP_ROM_PTR(&pin_GPIO41) }, + { MP_ROM_QSTR(MP_QSTR_SD_DATA3), MP_ROM_PTR(&pin_GPIO42) }, + { MP_ROM_QSTR(MP_QSTR_SD_CD), MP_ROM_PTR(&pin_GPIO45) }, + + { MP_ROM_QSTR(MP_QSTR_C6_RX), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_C6_TX), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_C6_BOOT), MP_ROM_PTR(&pin_GPIO46) }, + { MP_ROM_QSTR(MP_QSTR_C6_RESET), MP_ROM_PTR(&pin_GPIO47) }, + { MP_ROM_QSTR(MP_QSTR_C6_WAKE), MP_ROM_PTR(&pin_GPIO48) }, + { MP_ROM_QSTR(MP_QSTR_C6_SDIO_CLK), MP_ROM_PTR(&pin_GPIO34) }, + { MP_ROM_QSTR(MP_QSTR_C6_SDIO_CMD), MP_ROM_PTR(&pin_GPIO36) }, + { MP_ROM_QSTR(MP_QSTR_C6_SDIO_DATA0), MP_ROM_PTR(&pin_GPIO31) }, + { MP_ROM_QSTR(MP_QSTR_C6_SDIO_DATA1), MP_ROM_PTR(&pin_GPIO30) }, + { MP_ROM_QSTR(MP_QSTR_C6_SDIO_DATA2), MP_ROM_PTR(&pin_GPIO29) }, + { MP_ROM_QSTR(MP_QSTR_C6_SDIO_DATA3), MP_ROM_PTR(&pin_GPIO28) }, + + { MP_ROM_QSTR(MP_QSTR_CAMERA_RESET), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_LCD_BACKLIGHT), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_LCD_RESET), MP_ROM_PTR(&pin_GPIO20) }, + + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, + { MP_ROM_QSTR(MP_QSTR_STEMMA_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_module_globals_table); diff --git a/ports/espressif/boards/adafruit_metro_esp32p4/sdkconfig b/ports/espressif/boards/adafruit_metro_esp32p4/sdkconfig new file mode 100644 index 00000000000..a30634b1e0d --- /dev/null +++ b/ports/espressif/boards/adafruit_metro_esp32p4/sdkconfig @@ -0,0 +1,25 @@ +CONFIG_ESP32P4_SELECTS_REV_LESS_V3=y +CONFIG_ESP32P4_REV_MIN_1=y +CONFIG_ESP_WIFI_REMOTE_ENABLED=y +CONFIG_ESP_WIFI_REMOTE_LIBRARY_HOSTED=y +CONFIG_SLAVE_IDF_TARGET_ESP32C6=y +CONFIG_ESP_HOSTED_ENABLED=y +CONFIG_ESP_HOSTED_CP_TARGET_ESP32C6=y +CONFIG_ESP_HOSTED_P4_DEV_BOARD_NONE=y +CONFIG_ESP_HOSTED_SDIO_HOST_INTERFACE=y +CONFIG_ESP_HOSTED_SDIO_SLOT_1=y +CONFIG_ESP_HOSTED_SDIO_4_BIT_BUS=y +CONFIG_ESP_HOSTED_PRIV_SDIO_PIN_CLK_SLOT_1=34 +CONFIG_ESP_HOSTED_PRIV_SDIO_PIN_CMD_SLOT_1=36 +CONFIG_ESP_HOSTED_PRIV_SDIO_PIN_D0_SLOT_1=31 +CONFIG_ESP_HOSTED_PRIV_SDIO_PIN_D1_4BIT_BUS_SLOT_1=30 +CONFIG_ESP_HOSTED_PRIV_SDIO_PIN_D2_4BIT_BUS_SLOT_1=29 +CONFIG_ESP_HOSTED_PRIV_SDIO_PIN_D3_4BIT_BUS_SLOT_1=28 +CONFIG_ESP_HOSTED_SDIO_GPIO_RESET_SLAVE=47 +CONFIG_ESP_HOSTED_SDIO_CLOCK_FREQ_KHZ=40000 + +# CONFIG_WIFI_RMT_NVS_ENABLED is not set + +# CONFIG_ESP_WIFI_NVS_ENABLED is not set + +# CONFIG_ESP32_WIFI_NVS_ENABLED is not set diff --git a/ports/espressif/boards/adafruit_mini_sparkle_motion/mpconfigboard.mk b/ports/espressif/boards/adafruit_mini_sparkle_motion/mpconfigboard.mk index 6e31ba69a5b..25c857fc597 100644 --- a/ports/espressif/boards/adafruit_mini_sparkle_motion/mpconfigboard.mk +++ b/ports/espressif/boards/adafruit_mini_sparkle_motion/mpconfigboard.mk @@ -7,5 +7,6 @@ CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB -CIRCUITPY_BLEIO = 0 +# Few pins. CIRCUITPY_ESPCAMERA = 0 +CIRCUITPY_PARALLELDISPLAYBUS = 0 diff --git a/ports/espressif/boards/adafruit_p4gpio/board.c b/ports/espressif/boards/adafruit_p4gpio/board.c new file mode 100644 index 00000000000..8287c3ea247 --- /dev/null +++ b/ports/espressif/boards/adafruit_p4gpio/board.c @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/adafruit_p4gpio/mpconfigboard.h b/ports/espressif/boards/adafruit_p4gpio/mpconfigboard.h new file mode 100644 index 00000000000..cd6213909ff --- /dev/null +++ b/ports/espressif/boards/adafruit_p4gpio/mpconfigboard.h @@ -0,0 +1,22 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Micropython setup + +#define MICROPY_HW_BOARD_NAME "Adafruit P4 GPIO" +#define MICROPY_HW_MCU_NAME "ESP32P4" + +#define MICROPY_HW_NEOPIXEL (&pin_GPIO52) + +#define CIRCUITPY_BOOT_BUTTON (&pin_GPIO35) + +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO54) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO53) + +// FS USB on GPIO24/25 routed to J2. +#define CIRCUITPY_USB_HOST_INSTANCE 0 diff --git a/ports/espressif/boards/adafruit_p4gpio/mpconfigboard.mk b/ports/espressif/boards/adafruit_p4gpio/mpconfigboard.mk new file mode 100644 index 00000000000..88f496eeca1 --- /dev/null +++ b/ports/espressif/boards/adafruit_p4gpio/mpconfigboard.mk @@ -0,0 +1,16 @@ +USB_VID = 0x239A +USB_PID = 0x8174 +USB_PRODUCT = "Adafruit P4 GPIO" +USB_MANUFACTURER = "Adafruit" + +IDF_TARGET = esp32p4 + +CIRCUITPY_USB_DEVICE_INSTANCE = HIGH_SPEED_INSTANCE + +CIRCUITPY_ESP_FLASH_SIZE = 16MB +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m + +CIRCUITPY_ESP_PSRAM_SIZE = 32MB +CIRCUITPY_ESP_PSRAM_MODE = hpi +CIRCUITPY_ESP_PSRAM_FREQ = 200m diff --git a/ports/espressif/boards/adafruit_p4gpio/pins.c b/ports/espressif/boards/adafruit_p4gpio/pins.c new file mode 100644 index 00000000000..77ed1f89513 --- /dev/null +++ b/ports/espressif/boards/adafruit_p4gpio/pins.c @@ -0,0 +1,85 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + // Header J8 (B1) + { MP_ROM_QSTR(MP_QSTR_B1_0), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_B1_1), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_B1_2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_B1_3), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_B1_4), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_B1_5), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_B1_6), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_B1_7), MP_ROM_PTR(&pin_GPIO7) }, + + // Header J7 (B2) + { MP_ROM_QSTR(MP_QSTR_B2_0), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_B2_1), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_B2_2), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_B2_3), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_B2_4), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_B2_5), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_B2_6), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_B2_7), MP_ROM_PTR(&pin_GPIO15) }, + + // Header J6 (B3) + { MP_ROM_QSTR(MP_QSTR_B3_0), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_B3_1), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_B3_2), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_B3_3), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_B3_4), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_B3_5), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_B3_6), MP_ROM_PTR(&pin_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_B3_7), MP_ROM_PTR(&pin_GPIO23) }, + + // Header J3 (T3) + { MP_ROM_QSTR(MP_QSTR_T3_0), MP_ROM_PTR(&pin_GPIO33) }, + { MP_ROM_QSTR(MP_QSTR_T3_1), MP_ROM_PTR(&pin_GPIO32) }, + { MP_ROM_QSTR(MP_QSTR_T3_2), MP_ROM_PTR(&pin_GPIO31) }, + { MP_ROM_QSTR(MP_QSTR_T3_3), MP_ROM_PTR(&pin_GPIO30) }, + { MP_ROM_QSTR(MP_QSTR_T3_4), MP_ROM_PTR(&pin_GPIO29) }, + { MP_ROM_QSTR(MP_QSTR_T3_5), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_T3_6), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_T3_7), MP_ROM_PTR(&pin_GPIO26) }, + + // Header J4 (T2) + { MP_ROM_QSTR(MP_QSTR_T2_0), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_T2_1), MP_ROM_PTR(&pin_GPIO42) }, + { MP_ROM_QSTR(MP_QSTR_T2_2), MP_ROM_PTR(&pin_GPIO41) }, + { MP_ROM_QSTR(MP_QSTR_T2_3), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_T2_4), MP_ROM_PTR(&pin_GPIO39) }, + { MP_ROM_QSTR(MP_QSTR_T2_5), MP_ROM_PTR(&pin_GPIO38) }, + { MP_ROM_QSTR(MP_QSTR_T2_6), MP_ROM_PTR(&pin_GPIO37) }, + { MP_ROM_QSTR(MP_QSTR_T2_7), MP_ROM_PTR(&pin_GPIO34) }, + + // Header J5 (T1) + { MP_ROM_QSTR(MP_QSTR_T1_0), MP_ROM_PTR(&pin_GPIO51) }, + { MP_ROM_QSTR(MP_QSTR_T1_1), MP_ROM_PTR(&pin_GPIO50) }, + { MP_ROM_QSTR(MP_QSTR_T1_2), MP_ROM_PTR(&pin_GPIO49) }, + { MP_ROM_QSTR(MP_QSTR_T1_3), MP_ROM_PTR(&pin_GPIO48) }, + { MP_ROM_QSTR(MP_QSTR_T1_4), MP_ROM_PTR(&pin_GPIO47) }, + { MP_ROM_QSTR(MP_QSTR_T1_5), MP_ROM_PTR(&pin_GPIO46) }, + { MP_ROM_QSTR(MP_QSTR_T1_6), MP_ROM_PTR(&pin_GPIO45) }, + { MP_ROM_QSTR(MP_QSTR_T1_7), MP_ROM_PTR(&pin_GPIO44) }, + + // Boot button (also exposed on J9/J10 pin 2) + { MP_ROM_QSTR(MP_QSTR_BOOT), MP_ROM_PTR(&pin_GPIO35) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON), MP_ROM_PTR(&pin_GPIO35) }, + + // NeoPixel + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO52) }, + + // StemmaQT / Qwiic I2C (J11) + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO53) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO54) }, + + { 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/espressif/boards/adafruit_p4gpio/sdkconfig b/ports/espressif/boards/adafruit_p4gpio/sdkconfig new file mode 100644 index 00000000000..681e52bf82c --- /dev/null +++ b/ports/espressif/boards/adafruit_p4gpio/sdkconfig @@ -0,0 +1,70 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Bootloader config +# +# +# Log +# +# +# Format +# +# CONFIG_BOOTLOADER_LOG_COLORS is not set +# end of Format + +# end of Log + +# default: +CONFIG_BOOTLOADER_CPU_CLK_FREQ_MHZ=90 +# +# Serial Flash Configurations +# +# CONFIG_BOOTLOADER_FLASH_XMC_SUPPORT is not set +# end of Serial Flash Configurations + +# end of Bootloader config + +# +# Component config +# +# +# Bluetooth +# +# CONFIG_BT_ENABLED is not set +# end of Bluetooth + +# +# Hardware Settings +# +# +# Chip revision +# +CONFIG_ESP32P4_SELECTS_REV_LESS_V3=y +CONFIG_ESP32P4_REV_MIN_100=y +# default: +CONFIG_ESP32P4_REV_MIN_FULL=100 +# default: +CONFIG_ESP_REV_MIN_FULL=100 +# default: +CONFIG_ESP32P4_REV_MAX_FULL=199 +# default: +CONFIG_ESP_REV_MAX_FULL=199 +# end of Chip revision + +# end of Hardware Settings + +# +# ESP System Settings +# +# default: +CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_360=y +# default: +# CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_400 is not set +# default: +CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ=360 +# end of ESP System Settings + +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/boards/adafruit_qtpy_esp32_pico/mpconfigboard.h b/ports/espressif/boards/adafruit_qtpy_esp32_pico/mpconfigboard.h index 799a53c5c78..a0bc2b9f374 100644 --- a/ports/espressif/boards/adafruit_qtpy_esp32_pico/mpconfigboard.h +++ b/ports/espressif/boards/adafruit_qtpy_esp32_pico/mpconfigboard.h @@ -26,3 +26,6 @@ // UART pins attached to the USB-serial converter chip #define CIRCUITPY_CONSOLE_UART_TX (&pin_GPIO1) #define CIRCUITPY_CONSOLE_UART_RX (&pin_GPIO3) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/adafruit_qtpy_esp32c3/mpconfigboard.mk b/ports/espressif/boards/adafruit_qtpy_esp32c3/mpconfigboard.mk index 4063a639522..a17418eff19 100644 --- a/ports/espressif/boards/adafruit_qtpy_esp32c3/mpconfigboard.mk +++ b/ports/espressif/boards/adafruit_qtpy_esp32c3/mpconfigboard.mk @@ -7,9 +7,8 @@ CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 - CIRCUITPY_ESP_USB_SERIAL_JTAG = 1 # Not enough pins. CIRCUITPY_PARALLELDISPLAYBUS = 0 +CIRCUITPY_RGBMATRIX = 0 diff --git a/ports/espressif/boards/adafruit_qtpy_esp32s2/mpconfigboard.h b/ports/espressif/boards/adafruit_qtpy_esp32s2/mpconfigboard.h index c59dbfc81c9..a0c73d0bcdf 100644 --- a/ports/espressif/boards/adafruit_qtpy_esp32s2/mpconfigboard.h +++ b/ports/espressif/boards/adafruit_qtpy_esp32s2/mpconfigboard.h @@ -25,3 +25,6 @@ #define CIRCUITPY_BOARD_UART_PIN {{.tx = &pin_GPIO5, .rx = &pin_GPIO16}} #define DOUBLE_TAP_PIN (&pin_GPIO10) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/adafruit_qtpy_esp32s3_4mbflash_2mbpsram/mpconfigboard.h b/ports/espressif/boards/adafruit_qtpy_esp32s3_4mbflash_2mbpsram/mpconfigboard.h index ad97ab057fb..9760bbfeb44 100644 --- a/ports/espressif/boards/adafruit_qtpy_esp32s3_4mbflash_2mbpsram/mpconfigboard.h +++ b/ports/espressif/boards/adafruit_qtpy_esp32s3_4mbflash_2mbpsram/mpconfigboard.h @@ -25,3 +25,6 @@ #define CIRCUITPY_BOARD_UART_PIN {{.tx = &pin_GPIO5, .rx = &pin_GPIO16}} #define DOUBLE_TAP_PIN (&pin_GPIO10) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/adafruit_qtpy_esp32s3_4mbflash_2mbpsram/mpconfigboard.mk b/ports/espressif/boards/adafruit_qtpy_esp32s3_4mbflash_2mbpsram/mpconfigboard.mk index afc6e335c1a..09571a63a59 100644 --- a/ports/espressif/boards/adafruit_qtpy_esp32s3_4mbflash_2mbpsram/mpconfigboard.mk +++ b/ports/espressif/boards/adafruit_qtpy_esp32s3_4mbflash_2mbpsram/mpconfigboard.mk @@ -13,6 +13,6 @@ CIRCUITPY_ESP_PSRAM_SIZE = 2MB CIRCUITPY_ESP_PSRAM_MODE = qio CIRCUITPY_ESP_PSRAM_FREQ = 80m -CIRCUITPY_ESPCAMERA = 0 # Not enough pins. +CIRCUITPY_ESPCAMERA = 0 CIRCUITPY_PARALLELDISPLAYBUS = 0 diff --git a/ports/espressif/boards/adafruit_qtpy_esp32s3_nopsram/mpconfigboard.h b/ports/espressif/boards/adafruit_qtpy_esp32s3_nopsram/mpconfigboard.h index fcdefda3b40..6073bd47d0e 100644 --- a/ports/espressif/boards/adafruit_qtpy_esp32s3_nopsram/mpconfigboard.h +++ b/ports/espressif/boards/adafruit_qtpy_esp32s3_nopsram/mpconfigboard.h @@ -25,3 +25,6 @@ #define CIRCUITPY_BOARD_UART_PIN {{.tx = &pin_GPIO5, .rx = &pin_GPIO16}} #define DOUBLE_TAP_PIN (&pin_GPIO10) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/adafruit_qtpy_esp32s3_nopsram/mpconfigboard.mk b/ports/espressif/boards/adafruit_qtpy_esp32s3_nopsram/mpconfigboard.mk index 43ac269cd09..053b15647c1 100644 --- a/ports/espressif/boards/adafruit_qtpy_esp32s3_nopsram/mpconfigboard.mk +++ b/ports/espressif/boards/adafruit_qtpy_esp32s3_nopsram/mpconfigboard.mk @@ -10,7 +10,5 @@ CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 8MB -CIRCUITPY_ESPCAMERA = 0 - -# Not enough pins. +# Few pins. CIRCUITPY_PARALLELDISPLAYBUS = 0 diff --git a/ports/espressif/boards/adafruit_qualia_s3_rgb666/sdkconfig b/ports/espressif/boards/adafruit_qualia_s3_rgb666/sdkconfig index e9628662160..6bd9c5a4cb9 100644 --- a/ports/espressif/boards/adafruit_qualia_s3_rgb666/sdkconfig +++ b/ports/espressif/boards/adafruit_qualia_s3_rgb666/sdkconfig @@ -12,3 +12,6 @@ # end of Component config # end of Espressif IoT Development Framework Configuration +# Keep the RGB bounce-buffer refill cache available during flash writes when +# settings.toml disables persistent flash-file mappings. +CONFIG_SPIRAM_XIP_FROM_PSRAM=y diff --git a/ports/espressif/boards/adafruit_sparkle_motion/mpconfigboard.mk b/ports/espressif/boards/adafruit_sparkle_motion/mpconfigboard.mk index cf7cfd40a49..2765a63cef6 100644 --- a/ports/espressif/boards/adafruit_sparkle_motion/mpconfigboard.mk +++ b/ports/espressif/boards/adafruit_sparkle_motion/mpconfigboard.mk @@ -7,5 +7,6 @@ CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB -CIRCUITPY_BLEIO = 0 +# Very few pins. CIRCUITPY_ESPCAMERA = 0 +CIRCUITPY_PARALLELDISPLAYBUS = 0 diff --git a/ports/espressif/boards/adafruit_sparkle_motion/pins.c b/ports/espressif/boards/adafruit_sparkle_motion/pins.c index d78c1e1c4c7..f22cb50608d 100644 --- a/ports/espressif/boards/adafruit_sparkle_motion/pins.c +++ b/ports/espressif/boards/adafruit_sparkle_motion/pins.c @@ -46,6 +46,10 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_SIG4), MP_ROM_PTR(&pin_GPIO23) }, { MP_ROM_QSTR(MP_QSTR_D23), MP_ROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_D25), MP_ROM_PTR(&pin_GPIO25) }, + { MP_ROM_QSTR(MP_QSTR_D26), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_D33), MP_ROM_PTR(&pin_GPIO33) }, + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO9) }, { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_GPIO9) }, diff --git a/ports/espressif/boards/adafruit_sparkle_motion_stick/board.c b/ports/espressif/boards/adafruit_sparkle_motion_stick/board.c new file mode 100644 index 00000000000..a3a9eec0471 --- /dev/null +++ b/ports/espressif/boards/adafruit_sparkle_motion_stick/board.c @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/adafruit_sparkle_motion_stick/mpconfigboard.h b/ports/espressif/boards/adafruit_sparkle_motion_stick/mpconfigboard.h new file mode 100644 index 00000000000..fdc289fb845 --- /dev/null +++ b/ports/espressif/boards/adafruit_sparkle_motion_stick/mpconfigboard.h @@ -0,0 +1,19 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2022 Dan Halbert for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Micropython setup + +#define MICROPY_HW_BOARD_NAME "Adafruit Sparkle Motion Stick" +#define MICROPY_HW_MCU_NAME "ESP32" + +#define MICROPY_HW_LED_STATUS (&pin_GPIO4) +#define MICROPY_HW_NEOPIXEL (&pin_GPIO18) + +// UART pins attached to the USB-serial converter chip +#define CIRCUITPY_CONSOLE_UART_TX (&pin_GPIO1) +#define CIRCUITPY_CONSOLE_UART_RX (&pin_GPIO3) diff --git a/ports/espressif/boards/adafruit_sparkle_motion_stick/mpconfigboard.mk b/ports/espressif/boards/adafruit_sparkle_motion_stick/mpconfigboard.mk new file mode 100644 index 00000000000..d1bfe2f9742 --- /dev/null +++ b/ports/espressif/boards/adafruit_sparkle_motion_stick/mpconfigboard.mk @@ -0,0 +1,8 @@ +CIRCUITPY_CREATOR_ID = 0x0000239A +CIRCUITPY_CREATION_ID = 0x00320008 + +IDF_TARGET = esp32 + +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m +CIRCUITPY_ESP_FLASH_SIZE = 4MB diff --git a/ports/espressif/boards/adafruit_sparkle_motion_stick/pins.c b/ports/espressif/boards/adafruit_sparkle_motion_stick/pins.c new file mode 100644 index 00000000000..a5fdadac1e0 --- /dev/null +++ b/ports/espressif/boards/adafruit_sparkle_motion_stick/pins.c @@ -0,0 +1,32 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { MP_ROM_QSTR(MP_QSTR_BOOT), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_GPIO0) }, + + { MP_ROM_QSTR(MP_QSTR_IR), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_GPIO10) }, + { 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_D14), MP_ROM_PTR(&pin_GPIO14) }, + + { MP_ROM_QSTR(MP_QSTR_D21), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_D22), MP_ROM_PTR(&pin_GPIO22) }, + + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_D18), MP_ROM_PTR(&pin_GPIO18) }, + + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_GPIO4) }, + +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/tests/extmod/ssl_poll.py.exp b/ports/espressif/boards/adafruit_sparkle_motion_stick/sdkconfig similarity index 100% rename from tests/extmod/ssl_poll.py.exp rename to ports/espressif/boards/adafruit_sparkle_motion_stick/sdkconfig diff --git a/ports/espressif/boards/ai-thinker-esp32-cam/board.c b/ports/espressif/boards/ai-thinker-esp32-cam/board.c index 2e5c0c370ca..d1e28a2bc6a 100755 --- a/ports/espressif/boards/ai-thinker-esp32-cam/board.c +++ b/ports/espressif/boards/ai-thinker-esp32-cam/board.c @@ -11,6 +11,10 @@ #include "driver/gpio.h" void board_init(void) { + // GPIO4 (FLASHLIGHT) drives a very bright LED. Default to pulled down + // (off). + espressif_board_reset_pin_number(4); + reset_board(); } diff --git a/ports/espressif/boards/ai_thinker_esp32-c3s-2m/board.c b/ports/espressif/boards/ai_thinker_esp32-c3s-2m/board.c index 78e4a10b917..0709921bd54 100644 --- a/ports/espressif/boards/ai_thinker_esp32-c3s-2m/board.c +++ b/ports/espressif/boards/ai_thinker_esp32-c3s-2m/board.c @@ -12,6 +12,19 @@ #include "soc/usb_serial_jtag_struct.h" void board_init(void) { + // These pins drive LEDs. Default to pulled down (off): + // GPIO3 LED_RED + // GPIO4 LED_GREEN + // GPIO5 LED_BLUE + // GPIO18 LED_YELLOW + // GPIO19 LED_WHITE + static const gpio_num_t pins_to_reset[] = { + 3, 4, 5, 18, 19, + }; + for (size_t i = 0; i < MP_ARRAY_SIZE(pins_to_reset); i++) { + espressif_board_reset_pin_number(pins_to_reset[i]); + } + // This board has LEDs connected to the USB pins USB_SERIAL_JTAG.conf0.usb_pad_enable = 0; USB_SERIAL_JTAG.conf0.dp_pullup = 0; diff --git a/ports/espressif/boards/ai_thinker_esp32-c3s-2m/mpconfigboard.mk b/ports/espressif/boards/ai_thinker_esp32-c3s-2m/mpconfigboard.mk index 515b6da5c07..0bcb9df8196 100644 --- a/ports/espressif/boards/ai_thinker_esp32-c3s-2m/mpconfigboard.mk +++ b/ports/espressif/boards/ai_thinker_esp32-c3s-2m/mpconfigboard.mk @@ -9,4 +9,14 @@ CIRCUITPY_ESP_FLASH_SIZE = 2MB CIRCUITPY_DUALBANK = 0 +CIRCUITPY_SSL_ROOTS = $(TOP)/lib/certificates/data/roots-filtered.pem + +CIRCUITPY_AESIO = 0 +CIRCUITPY_CANIO = 0 +CIRCUITPY_GETPASS = 0 +CIRCUITPY_JPEGIO = 0 +CIRCUITPY_MSGPACK = 0 +CIRCUITPY_PS2IO = 0 +CIRCUITPY_ZLIB = 0 + CIRCUITPY_ESP_USB_SERIAL_JTAG = 0 diff --git a/ports/espressif/boards/ai_thinker_esp32-c3s-2m/sdkconfig b/ports/espressif/boards/ai_thinker_esp32-c3s-2m/sdkconfig index e9628662160..5fd531f274a 100644 --- a/ports/espressif/boards/ai_thinker_esp32-c3s-2m/sdkconfig +++ b/ports/espressif/boards/ai_thinker_esp32-c3s-2m/sdkconfig @@ -9,6 +9,18 @@ # # end of LWIP +# +# Wireless Coexistence +# +# CONFIG_ESP_COEX_SW_COEXIST_ENABLE is not set +# end of Wireless Coexistence + +# +# LibC +# +# CONFIG_LIBC_OPTIMIZED_MISALIGNED_ACCESS is not set +# end of LibC + # end of Component config # end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/boards/ai_thinker_esp32-c3s/board.c b/ports/espressif/boards/ai_thinker_esp32-c3s/board.c index 78e4a10b917..0709921bd54 100644 --- a/ports/espressif/boards/ai_thinker_esp32-c3s/board.c +++ b/ports/espressif/boards/ai_thinker_esp32-c3s/board.c @@ -12,6 +12,19 @@ #include "soc/usb_serial_jtag_struct.h" void board_init(void) { + // These pins drive LEDs. Default to pulled down (off): + // GPIO3 LED_RED + // GPIO4 LED_GREEN + // GPIO5 LED_BLUE + // GPIO18 LED_YELLOW + // GPIO19 LED_WHITE + static const gpio_num_t pins_to_reset[] = { + 3, 4, 5, 18, 19, + }; + for (size_t i = 0; i < MP_ARRAY_SIZE(pins_to_reset); i++) { + espressif_board_reset_pin_number(pins_to_reset[i]); + } + // This board has LEDs connected to the USB pins USB_SERIAL_JTAG.conf0.usb_pad_enable = 0; USB_SERIAL_JTAG.conf0.dp_pullup = 0; diff --git a/ports/espressif/boards/ai_thinker_esp32-c3s/mpconfigboard.mk b/ports/espressif/boards/ai_thinker_esp32-c3s/mpconfigboard.mk index f907853f238..9bcaa3473a2 100644 --- a/ports/espressif/boards/ai_thinker_esp32-c3s/mpconfigboard.mk +++ b/ports/espressif/boards/ai_thinker_esp32-c3s/mpconfigboard.mk @@ -7,6 +7,4 @@ CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 - CIRCUITPY_ESP_USB_SERIAL_JTAG = 0 diff --git a/ports/espressif/boards/arduino_nano_esp32s3/board.c b/ports/espressif/boards/arduino_nano_esp32s3/board.c index 9e3399f8bf7..7615ae6d45e 100644 --- a/ports/espressif/boards/arduino_nano_esp32s3/board.c +++ b/ports/espressif/boards/arduino_nano_esp32s3/board.c @@ -10,7 +10,7 @@ #include "driver/gpio.h" bool espressif_board_reset_pin_number(gpio_num_t pin_number) { - if (pin_number == 13) { + if (pin_number == 48) { // Set D13 LED to input when not in use gpio_config_t cfg = { .pin_bit_mask = BIT64(pin_number), @@ -26,4 +26,10 @@ bool espressif_board_reset_pin_number(gpio_num_t pin_number) { return false; } +void board_init(void) { + // GPIO48 (LED) drives the D13 LED. Default to an input with a pull-down + // (off). + espressif_board_reset_pin_number(48); +} + // Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/arduino_nano_esp32s3/mpconfigboard.h b/ports/espressif/boards/arduino_nano_esp32s3/mpconfigboard.h index 6518da3566f..04cc8baeead 100644 --- a/ports/espressif/boards/arduino_nano_esp32s3/mpconfigboard.h +++ b/ports/espressif/boards/arduino_nano_esp32s3/mpconfigboard.h @@ -17,7 +17,7 @@ #define CIRCUITPY_RGB_STATUS_G (&pin_GPIO0) #define CIRCUITPY_RGB_STATUS_B (&pin_GPIO45) -#define MICROPY_HW_LED_STATUS (&pin_GPIO13) +#define MICROPY_HW_LED_STATUS (&pin_GPIO48) #if QSPI_FLASH_FILESYSTEM #define MICROPY_QSPI_DATA0 (&pin_GPIO32) diff --git a/ports/espressif/boards/arduino_nano_esp32s3/mpconfigboard.mk b/ports/espressif/boards/arduino_nano_esp32s3/mpconfigboard.mk index 3abf3d9afcb..4974b7a9c89 100644 --- a/ports/espressif/boards/arduino_nano_esp32s3/mpconfigboard.mk +++ b/ports/espressif/boards/arduino_nano_esp32s3/mpconfigboard.mk @@ -21,5 +21,3 @@ CIRCUITPY_ESP_PSRAM_FREQ = 80m INTERNAL_FLASH_FILESYSTEM = 0 QSPI_FLASH_FILESYSTEM = 1 EXTERNAL_FLASH_DEVICES = GD25WQ128E - -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/arduino_nano_esp32s3_inverted_statusled/board.c b/ports/espressif/boards/arduino_nano_esp32s3_inverted_statusled/board.c index 9e3399f8bf7..7615ae6d45e 100644 --- a/ports/espressif/boards/arduino_nano_esp32s3_inverted_statusled/board.c +++ b/ports/espressif/boards/arduino_nano_esp32s3_inverted_statusled/board.c @@ -10,7 +10,7 @@ #include "driver/gpio.h" bool espressif_board_reset_pin_number(gpio_num_t pin_number) { - if (pin_number == 13) { + if (pin_number == 48) { // Set D13 LED to input when not in use gpio_config_t cfg = { .pin_bit_mask = BIT64(pin_number), @@ -26,4 +26,10 @@ bool espressif_board_reset_pin_number(gpio_num_t pin_number) { return false; } +void board_init(void) { + // GPIO48 (LED) drives the D13 LED. Default to an input with a pull-down + // (off). + espressif_board_reset_pin_number(48); +} + // Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/arduino_nano_esp32s3_inverted_statusled/mpconfigboard.h b/ports/espressif/boards/arduino_nano_esp32s3_inverted_statusled/mpconfigboard.h index da20e04a973..24b3a0f9fcf 100644 --- a/ports/espressif/boards/arduino_nano_esp32s3_inverted_statusled/mpconfigboard.h +++ b/ports/espressif/boards/arduino_nano_esp32s3_inverted_statusled/mpconfigboard.h @@ -17,7 +17,7 @@ #define CIRCUITPY_RGB_STATUS_G (&pin_GPIO45) #define CIRCUITPY_RGB_STATUS_B (&pin_GPIO0) -#define MICROPY_HW_LED_STATUS (&pin_GPIO13) +#define MICROPY_HW_LED_STATUS (&pin_GPIO48) #if QSPI_FLASH_FILESYSTEM #define MICROPY_QSPI_DATA0 (&pin_GPIO32) diff --git a/ports/espressif/boards/arduino_nano_esp32s3_inverted_statusled/mpconfigboard.mk b/ports/espressif/boards/arduino_nano_esp32s3_inverted_statusled/mpconfigboard.mk index 3abf3d9afcb..4974b7a9c89 100644 --- a/ports/espressif/boards/arduino_nano_esp32s3_inverted_statusled/mpconfigboard.mk +++ b/ports/espressif/boards/arduino_nano_esp32s3_inverted_statusled/mpconfigboard.mk @@ -21,5 +21,3 @@ CIRCUITPY_ESP_PSRAM_FREQ = 80m INTERNAL_FLASH_FILESYSTEM = 0 QSPI_FLASH_FILESYSTEM = 1 EXTERNAL_FLASH_DEVICES = GD25WQ128E - -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/artisense_rd00/board.c b/ports/espressif/boards/artisense_rd00/board.c index 779dfb861e0..d4790658205 100644 --- a/ports/espressif/boards/artisense_rd00/board.c +++ b/ports/espressif/boards/artisense_rd00/board.c @@ -5,11 +5,5 @@ // SPDX-License-Identifier: MIT #include "supervisor/board.h" -#include "mpconfigboard.h" -#include "shared-bindings/microcontroller/Pin.h" -void board_init(void) { - // Crystal - common_hal_never_reset_pin(&pin_GPIO15); - common_hal_never_reset_pin(&pin_GPIO16); -} +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/atmegazero_esp32s2/mpconfigboard.h b/ports/espressif/boards/atmegazero_esp32s2/mpconfigboard.h index 8f20dc5bfe2..31dba37970c 100644 --- a/ports/espressif/boards/atmegazero_esp32s2/mpconfigboard.h +++ b/ports/espressif/boards/atmegazero_esp32s2/mpconfigboard.h @@ -22,3 +22,6 @@ #define DEFAULT_UART_BUS_TX (&pin_GPIO43) #define MICROPY_HW_NEOPIXEL (&pin_GPIO40) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/atmegazero_esp32s2/mpconfigboard.mk b/ports/espressif/boards/atmegazero_esp32s2/mpconfigboard.mk index d0628afa6b6..0d9fdd6ca11 100644 --- a/ports/espressif/boards/atmegazero_esp32s2/mpconfigboard.mk +++ b/ports/espressif/boards/atmegazero_esp32s2/mpconfigboard.mk @@ -12,3 +12,9 @@ CIRCUITPY_ESP_FLASH_SIZE = 16MB CIRCUITPY_ESP_PSRAM_SIZE = 8MB CIRCUITPY_ESP_PSRAM_MODE = qio CIRCUITPY_ESP_PSRAM_FREQ = 80m + +# Out of internal RAM with audiopwmio +CIRCUITPY_AUDIOPWMIO = 0 + +# Fast e-paper doesn't fit in internal RAM. +CIRCUITPY_EPAPERDISPLAY_FAST = 0 diff --git a/ports/espressif/boards/barduino/mpconfigboard.mk b/ports/espressif/boards/barduino/mpconfigboard.mk index fed67ab635b..61c5feea811 100644 --- a/ports/espressif/boards/barduino/mpconfigboard.mk +++ b/ports/espressif/boards/barduino/mpconfigboard.mk @@ -8,4 +8,3 @@ IDF_TARGET = esp32s3 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 8MB -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/beetle-esp32-c3/mpconfigboard.mk b/ports/espressif/boards/beetle-esp32-c3/mpconfigboard.mk index a03e6c32eb2..dfd6a665f3b 100644 --- a/ports/espressif/boards/beetle-esp32-c3/mpconfigboard.mk +++ b/ports/espressif/boards/beetle-esp32-c3/mpconfigboard.mk @@ -1,4 +1,4 @@ -# TODO +# A better directory name for this board would be dfrobot_beetle_esp32_c3. CIRCUITPY_CREATOR_ID = 0x10101010 CIRCUITPY_CREATION_ID = 0x00C30001 @@ -8,6 +8,4 @@ CIRCUITPY_ESP_FLASH_MODE=qio CIRCUITPY_ESP_FLASH_FREQ=80m CIRCUITPY_ESP_FLASH_SIZE=4MB -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 - CIRCUITPY_ESP_USB_SERIAL_JTAG = 1 diff --git a/ports/espressif/boards/bpi_bit_s2/mpconfigboard.mk b/ports/espressif/boards/bpi_bit_s2/mpconfigboard.mk index e9dd3da71f4..a9bb35b51f7 100644 --- a/ports/espressif/boards/bpi_bit_s2/mpconfigboard.mk +++ b/ports/espressif/boards/bpi_bit_s2/mpconfigboard.mk @@ -9,9 +9,9 @@ CIRCUITPY_ESP_FLASH_MODE=dio CIRCUITPY_ESP_FLASH_FREQ=40m CIRCUITPY_ESP_FLASH_SIZE=4MB -# Include these Python libraries in firmware. -FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel - CIRCUITPY_ESP_PSRAM_SIZE = 2MB CIRCUITPY_ESP_PSRAM_MODE = qio CIRCUITPY_ESP_PSRAM_FREQ = 80m + +# Include these Python libraries in firmware. +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel diff --git a/ports/espressif/boards/cezerio_dev_ESP32C6/mpconfigboard.h b/ports/espressif/boards/cezerio_dev_ESP32C6/mpconfigboard.h index 44171d1dc4d..65832e3cc9c 100644 --- a/ports/espressif/boards/cezerio_dev_ESP32C6/mpconfigboard.h +++ b/ports/espressif/boards/cezerio_dev_ESP32C6/mpconfigboard.h @@ -25,3 +25,6 @@ // For entering safe mode, use BOOT button #define CIRCUITPY_BOOT_BUTTON (&pin_GPIO9) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/cezerio_dev_ESP32C6/mpconfigboard.mk b/ports/espressif/boards/cezerio_dev_ESP32C6/mpconfigboard.mk index 3acd161c340..fe93c7a849a 100644 --- a/ports/espressif/boards/cezerio_dev_ESP32C6/mpconfigboard.mk +++ b/ports/espressif/boards/cezerio_dev_ESP32C6/mpconfigboard.mk @@ -6,3 +6,6 @@ IDF_TARGET = esp32c6 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB + +# Board was originally defined with a 2MB firmware, almost 2MB user filesystem. Leave it that way. +CIRCUITPY_4MB_FLASH_LARGE_USER_FS_LAYOUT = 1 diff --git a/ports/espressif/boards/circuitart_zero_s3/mpconfigboard.h b/ports/espressif/boards/circuitart_zero_s3/mpconfigboard.h index 973e6118393..973e2f5bac2 100644 --- a/ports/espressif/boards/circuitart_zero_s3/mpconfigboard.h +++ b/ports/espressif/boards/circuitart_zero_s3/mpconfigboard.h @@ -32,3 +32,6 @@ #define DEFAULT_TFT_CS (&pin_GPIO39) #define DEFAULT_TFT_DC (&pin_GPIO5) #define DEFAULT_TFT_RST (&pin_GPIO40) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/columbia-dsl-sensor/mpconfigboard.mk b/ports/espressif/boards/columbia-dsl-sensor/mpconfigboard.mk index 9d11052ee5c..f37fe88a4fc 100644 --- a/ports/espressif/boards/columbia-dsl-sensor/mpconfigboard.mk +++ b/ports/espressif/boards/columbia-dsl-sensor/mpconfigboard.mk @@ -12,5 +12,3 @@ CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_PSRAM_SIZE = 2MB CIRCUITPY_ESP_PSRAM_MODE = qio CIRCUITPY_ESP_PSRAM_FREQ = 80m - -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/crcibernetica-ideaboard/mpconfigboard.mk b/ports/espressif/boards/crcibernetica-ideaboard/mpconfigboard.mk index 3e7e54c9a63..861ae00b0f5 100644 --- a/ports/espressif/boards/crcibernetica-ideaboard/mpconfigboard.mk +++ b/ports/espressif/boards/crcibernetica-ideaboard/mpconfigboard.mk @@ -7,9 +7,6 @@ CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 8MB -CIRCUITPY_BLEIO = 0 -CIRCUITPY_ESPCAMERA = 0 - # Include these Python libraries in firmware FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_ConnectionManager FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_Requests diff --git a/ports/espressif/boards/crumpspace_crumps2/mpconfigboard.mk b/ports/espressif/boards/crumpspace_crumps2/mpconfigboard.mk index 86fefedfb95..707687b5cf3 100644 --- a/ports/espressif/boards/crumpspace_crumps2/mpconfigboard.mk +++ b/ports/espressif/boards/crumpspace_crumps2/mpconfigboard.mk @@ -9,11 +9,11 @@ CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB +CIRCUITPY_ESP_PSRAM_SIZE = 2MB +CIRCUITPY_ESP_PSRAM_MODE = qio +CIRCUITPY_ESP_PSRAM_FREQ = 80m + CIRCUITPY_BITBANG_APA102 = 1 # Include these Python libraries in firmware. # FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_DotStar - -CIRCUITPY_ESP_PSRAM_SIZE = 2MB -CIRCUITPY_ESP_PSRAM_MODE = qio -CIRCUITPY_ESP_PSRAM_FREQ = 80m diff --git a/ports/espressif/boards/cytron_maker_feather_aiot_s3/board.c b/ports/espressif/boards/cytron_maker_feather_aiot_s3/board.c index 72d95a8768b..0fd667b493c 100644 --- a/ports/espressif/boards/cytron_maker_feather_aiot_s3/board.c +++ b/ports/espressif/boards/cytron_maker_feather_aiot_s3/board.c @@ -11,6 +11,17 @@ #include "common-hal/microcontroller/Pin.h" void board_init(void) { + // Most of these pins drive active-high LEDs. Default to pulled down (off). + // + // GPIO13 (VOLTAGE_MONITOR) measures the battery voltage. Default to no + // pull. + static const gpio_num_t pins_to_reset[] = { + 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 21, 38, 39, 40, 41, 42, 47, 48, + }; + for (size_t i = 0; i < MP_ARRAY_SIZE(pins_to_reset); i++) { + espressif_board_reset_pin_number(pins_to_reset[i]); + } + reset_board(); } diff --git a/ports/espressif/boards/deneyap_kart/mpconfigboard.mk b/ports/espressif/boards/deneyap_kart/mpconfigboard.mk index df54649ec52..69d81074fa7 100644 --- a/ports/espressif/boards/deneyap_kart/mpconfigboard.mk +++ b/ports/espressif/boards/deneyap_kart/mpconfigboard.mk @@ -10,5 +10,3 @@ CIRCUITPY_ESP_FLASH_SIZE = 4MB CIRCUITPY_ESP_PSRAM_SIZE = 8MB CIRCUITPY_ESP_PSRAM_MODE = qio CIRCUITPY_ESP_PSRAM_FREQ = 80m - -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 diff --git a/ports/espressif/boards/deneyap_kart_1a/mpconfigboard.mk b/ports/espressif/boards/deneyap_kart_1a/mpconfigboard.mk index 17dfe4fe768..b1b6c9eab4b 100644 --- a/ports/espressif/boards/deneyap_kart_1a/mpconfigboard.mk +++ b/ports/espressif/boards/deneyap_kart_1a/mpconfigboard.mk @@ -10,5 +10,3 @@ CIRCUITPY_ESP_FLASH_SIZE = 4MB CIRCUITPY_ESP_PSRAM_SIZE = 8MB CIRCUITPY_ESP_PSRAM_MODE = qio CIRCUITPY_ESP_PSRAM_FREQ = 80m - -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 diff --git a/ports/espressif/boards/deneyap_kart_1a_v2/mpconfigboard.mk b/ports/espressif/boards/deneyap_kart_1a_v2/mpconfigboard.mk index cb994090192..5a2fd709a5e 100644 --- a/ports/espressif/boards/deneyap_kart_1a_v2/mpconfigboard.mk +++ b/ports/espressif/boards/deneyap_kart_1a_v2/mpconfigboard.mk @@ -13,10 +13,3 @@ CIRCUITPY_ESP_FLASH_SIZE = 4MB CIRCUITPY_ESP_PSRAM_SIZE = 8MB CIRCUITPY_ESP_PSRAM_MODE = opi CIRCUITPY_ESP_PSRAM_FREQ = 80m - -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 - -CIRCUITPY_ESPCAMERA = 0 -CIRCUITPY_BITMAPFILTER = 0 -CIRCUITPY_CODEOP = 0 -CIRCUITPY_PARALLELDISPLAYBUS = 0 diff --git a/ports/espressif/boards/deneyap_kart_g/mpconfigboard.mk b/ports/espressif/boards/deneyap_kart_g/mpconfigboard.mk index 8aaea636b84..46e0fbb3e23 100644 --- a/ports/espressif/boards/deneyap_kart_g/mpconfigboard.mk +++ b/ports/espressif/boards/deneyap_kart_g/mpconfigboard.mk @@ -7,6 +7,4 @@ CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 - CIRCUITPY_ESP_USB_SERIAL_JTAG = 1 diff --git a/ports/espressif/boards/deneyap_mini/mpconfigboard.mk b/ports/espressif/boards/deneyap_mini/mpconfigboard.mk index 007b7ebc82a..8f6257ff02b 100644 --- a/ports/espressif/boards/deneyap_mini/mpconfigboard.mk +++ b/ports/espressif/boards/deneyap_mini/mpconfigboard.mk @@ -9,7 +9,3 @@ IDF_TARGET = esp32s2 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB - -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 - -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/deneyap_mini_v2/mpconfigboard.mk b/ports/espressif/boards/deneyap_mini_v2/mpconfigboard.mk index 457d4b93161..9712e8437f7 100644 --- a/ports/espressif/boards/deneyap_mini_v2/mpconfigboard.mk +++ b/ports/espressif/boards/deneyap_mini_v2/mpconfigboard.mk @@ -13,5 +13,3 @@ CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_PSRAM_SIZE = 2MB CIRCUITPY_ESP_PSRAM_MODE = qio CIRCUITPY_ESP_PSRAM_FREQ = 80m - -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 diff --git a/ports/espressif/boards/deshipu_ugame_s3/board.c b/ports/espressif/boards/deshipu_ugame_s3/board.c new file mode 100644 index 00000000000..599db3b8436 --- /dev/null +++ b/ports/espressif/boards/deshipu_ugame_s3/board.c @@ -0,0 +1,122 @@ +/* + * 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/fourwire/FourWire.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-module/displayio/__init__.h" +#include "shared-module/displayio/mipi_constants.h" +#include "shared-bindings/board/__init__.h" + +#include "esp_log.h" +#include "esp_err.h" + +fourwire_fourwire_obj_t board_display_obj; + +#define DELAY 0x80 + +uint8_t display_init_sequence[] = { + 0x01, 0 | DELAY, 0x80, // Software reset then delay 0x80 (128ms) + 0xEF, 3, 0x03, 0x80, 0x02, + 0xCF, 3, 0x00, 0xC1, 0x30, + 0xED, 4, 0x64, 0x03, 0x12, 0x81, + 0xE8, 3, 0x85, 0x00, 0x78, + 0xCB, 5, 0x39, 0x2C, 0x00, 0x34, 0x02, + 0xF7, 1, 0x20, + 0xEA, 2, 0x00, 0x00, + 0xc0, 1, 0x23, // Power control VRH[5:0] + 0xc1, 1, 0x10, // Power control SAP[2:0];BT[3:0] + 0xc5, 2, 0x3e, 0x28, // VCM control + 0xc7, 1, 0x86, // VCM control2 + 0x37, 1, 0x00, // Vertical scroll zero + 0x3a, 1, 0x55, // COLMOD: Pixel Format Set + 0xb1, 2, 0x00, 0x18, // Frame Rate Control (In Normal Mode/Full Colors) + 0xb6, 3, 0x08, 0x82, 0x27, // Display Function Control + 0xF2, 1, 0x00, // 3Gamma Function Disable + 0x26, 1, 0x01, // Gamma curve selected + 0xe0, 15, 0x0F, 0x31, 0x2B, 0x0C, 0x0E, 0x08, 0x4E, 0xF1, 0x37, 0x07, 0x10, 0x03, 0x0E, 0x09, 0x00, // Set Gamma + 0xe1, 15, 0x00, 0x0E, 0x14, 0x03, 0x11, 0x07, 0x31, 0xC1, 0x48, 0x08, 0x0F, 0x0C, 0x31, 0x36, 0x0F, // Set Gamma + 0x11, 0 | DELAY, 0x78, // Exit Sleep then delay 0x78 (120ms) + 0x29, 0 | DELAY, 0x78, // Display on then delay 0x78 (120ms) + 0x36, 1, 0x38, +}; + + +void board_init(void) { + fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; + busio_spi_obj_t *spi = &bus->inline_bus; + common_hal_busio_spi_construct(spi, &pin_GPIO12, &pin_GPIO11, NULL, false); + + bus->base.type = &fourwire_fourwire_type; + common_hal_fourwire_fourwire_construct(bus, + spi, + MP_OBJ_FROM_PTR(&pin_GPIO9), // TFT_DC Command or data + MP_OBJ_FROM_PTR(&pin_GPIO10), // TFT_CS Chip select + MP_OBJ_FROM_PTR(&pin_GPIO13), // TFT_RESET Reset + 48000000L, // Baudrate + 0, // Polarity + 0); // Phase + + busdisplay_busdisplay_obj_t *display = &allocate_display()->display; + display->base.type = &busdisplay_busdisplay_type; + common_hal_busdisplay_busdisplay_construct( + display, + bus, + 320, // Width (after rotation) + 240, // Height (after rotation) + 0, // column start + 0, // row start + 0, // 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 + display_init_sequence, + sizeof(display_init_sequence), + &pin_GPIO21, // backlight pin + NO_BRIGHTNESS_COMMAND, + 1.0f, // brightness + false, // single_byte_bounds + false, // data_as_commands + true, // auto_refresh + 20, // native_frames_per_second + true, // backlight_on_high + false, // not SH1107 + 50000); // backlight pwm frequency +} + +void board_deinit(void) { +} + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/deshipu_ugame_s3/mpconfigboard.h b/ports/espressif/boards/deshipu_ugame_s3/mpconfigboard.h new file mode 100644 index 00000000000..da7c3b4e8a4 --- /dev/null +++ b/ports/espressif/boards/deshipu_ugame_s3/mpconfigboard.h @@ -0,0 +1,28 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2023 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. + */ + +#define MICROPY_HW_BOARD_NAME "uGame S3" +#define MICROPY_HW_MCU_NAME "ESP32S3" diff --git a/ports/espressif/boards/deshipu_ugame_s3/mpconfigboard.mk b/ports/espressif/boards/deshipu_ugame_s3/mpconfigboard.mk new file mode 100644 index 00000000000..36a0ce040c5 --- /dev/null +++ b/ports/espressif/boards/deshipu_ugame_s3/mpconfigboard.mk @@ -0,0 +1,27 @@ +USB_VID = 0x1209 +USB_PID = 0xD187 +USB_PRODUCT = "uGameS3" +USB_MANUFACTURER = "deshipu" + +IDF_TARGET = esp32s3 + +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m +CIRCUITPY_ESP_FLASH_SIZE = 16MB + +CIRCUITPY_ESP_PSRAM_SIZE = 8MB +CIRCUITPY_ESP_PSRAM_MODE = opi +CIRCUITPY_ESP_PSRAM_FREQ = 80m + +CIRCUITPY_STAGE = 1 +CIRCUITPY_KEYPAD = 1 + +CIRCUITPY_CANIO = 0 +CIRCUITPY_DUALBANK = 0 +CIRCUITPY_ESPCAMERA = 0 +CIRCUITPY_FRAMEBUFFERIO = 0 +CIRCUITPY_PARALLELDISPLAYBUS = 0 +CIRCUITPY_RGBMATRIX = 0 +CIRCUITPY_ROTARYIO = 0 + +FROZEN_MPY_DIRS += $(TOP)/frozen/circuitpython-stage/ugame_s3 diff --git a/ports/espressif/boards/deshipu_ugame_s3/pins.c b/ports/espressif/boards/deshipu_ugame_s3/pins.c new file mode 100644 index 00000000000..54bd5dcdb4f --- /dev/null +++ b/ports/espressif/boards/deshipu_ugame_s3/pins.c @@ -0,0 +1,43 @@ +#include "py/objtuple.h" +#include "shared-bindings/board/__init__.h" +#include "shared-module/displayio/__init__.h" + + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { MP_ROM_QSTR(MP_QSTR_P1), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_P2), MP_ROM_PTR(&pin_GPIO44) }, + { MP_ROM_QSTR(MP_QSTR_P3), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_P4), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_P5), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_P6), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_P7), MP_ROM_PTR(&pin_GPIO7) }, + + { MP_ROM_QSTR(MP_QSTR_BUTTON_LEFT), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON_UP), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON_RIGHT), MP_ROM_PTR(&pin_GPIO42) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON_DOWN), MP_ROM_PTR(&pin_GPIO41) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON_X), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON_O), MP_ROM_PTR(&pin_GPIO48) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON_Z), MP_ROM_PTR(&pin_GPIO47) }, + + { MP_ROM_QSTR(MP_QSTR_LIGHT), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_BATTERY), MP_ROM_PTR(&pin_GPIO8) }, + + + { MP_ROM_QSTR(MP_QSTR_AUDIO_BCLK), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_AUDIO_LRCLK), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_AUDIO_DATA), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_AUDIO_GAIN), MP_ROM_PTR(&pin_GPIO18) }, + + { MP_ROM_QSTR(MP_QSTR_TFT_RESET), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_TFT_CS), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_TFT_DC), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_TFT_BACKLIGHT), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_TFT_SCK), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_TFT_MOSI), MP_ROM_PTR(&pin_GPIO11) }, + + { 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/espressif/boards/deshipu_ugame_s3/sdkconfig b/ports/espressif/boards/deshipu_ugame_s3/sdkconfig new file mode 100644 index 00000000000..1bddb7a89fb --- /dev/null +++ b/ports/espressif/boards/deshipu_ugame_s3/sdkconfig @@ -0,0 +1,22 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Component config +# +# +# LWIP +# +CONFIG_LWIP_LOCAL_HOSTNAME="espressif-esp32s3" +# end of LWIP + +# +# Camera configuration +# +# CONFIG_OV7725_SUPPORT is not set +# CONFIG_OV3660_SUPPORT is not set +# end of Camera configuration + +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/boards/doit_esp32_devkit_v1/mpconfigboard.mk b/ports/espressif/boards/doit_esp32_devkit_v1/mpconfigboard.mk index 9f657c6552d..01db9cff090 100644 --- a/ports/espressif/boards/doit_esp32_devkit_v1/mpconfigboard.mk +++ b/ports/espressif/boards/doit_esp32_devkit_v1/mpconfigboard.mk @@ -6,6 +6,3 @@ IDF_TARGET = esp32 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB -CIRCUITPY_ESPCAMERA = 0 - -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 diff --git a/ports/espressif/boards/elecrow_crowpanel_2_13_epaper/board.c b/ports/espressif/boards/elecrow_crowpanel_2_13_epaper/board.c new file mode 100644 index 00000000000..5d671943eec --- /dev/null +++ b/ports/espressif/boards/elecrow_crowpanel_2_13_epaper/board.c @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Cade Roux +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/elecrow_crowpanel_2_13_epaper/mpconfigboard.h b/ports/espressif/boards/elecrow_crowpanel_2_13_epaper/mpconfigboard.h new file mode 100644 index 00000000000..522eb31031e --- /dev/null +++ b/ports/espressif/boards/elecrow_crowpanel_2_13_epaper/mpconfigboard.h @@ -0,0 +1,26 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Cade Roux +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Micropython setup + +#define MICROPY_HW_BOARD_NAME "CrowPanel 2.13 EPaper" +#define MICROPY_HW_MCU_NAME "ESP32S3" +#define MICROPY_HW_LED_STATUS (&pin_GPIO19) +#define CIRCUITPY_BOOT_BUTTON (&pin_GPIO0) + +#define CIRCUITPY_BOARD_SPI (1) +#define CIRCUITPY_BOARD_SPI_PIN { \ + {.clock = &pin_GPIO12, .mosi = &pin_GPIO11}, /*EPD*/ \ +} + +// UART pins attached to the USB-serial converter chip +#define DEFAULT_UART_BUS_RX (&pin_GPIO44) +#define DEFAULT_UART_BUS_TX (&pin_GPIO43) + +#define CIRCUITPY_CONSOLE_UART_TX DEFAULT_UART_BUS_TX +#define CIRCUITPY_CONSOLE_UART_RX DEFAULT_UART_BUS_RX diff --git a/ports/espressif/boards/elecrow_crowpanel_2_13_epaper/mpconfigboard.mk b/ports/espressif/boards/elecrow_crowpanel_2_13_epaper/mpconfigboard.mk new file mode 100644 index 00000000000..3aaebe15f96 --- /dev/null +++ b/ports/espressif/boards/elecrow_crowpanel_2_13_epaper/mpconfigboard.mk @@ -0,0 +1,17 @@ +CIRCUITPY_CREATOR_ID = 0x1C350000 +CIRCUITPY_CREATION_ID = 0x00000003 + +# This board doesn't have USB by default, it +# instead uses a CH340K USB-to-Serial chip +CIRCUITPY_USB_DEVICE = 0 +CIRCUITPY_ESP_USB_SERIAL_JTAG = 0 + +IDF_TARGET = esp32s3 + +CIRCUITPY_ESP_FLASH_SIZE = 8MB +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m + +CIRCUITPY_ESP_PSRAM_SIZE = 8MB +CIRCUITPY_ESP_PSRAM_MODE = opi +CIRCUITPY_ESP_PSRAM_FREQ = 80m diff --git a/ports/espressif/boards/elecrow_crowpanel_2_13_epaper/pins.c b/ports/espressif/boards/elecrow_crowpanel_2_13_epaper/pins.c new file mode 100644 index 00000000000..2d70555628e --- /dev/null +++ b/ports/espressif/boards/elecrow_crowpanel_2_13_epaper/pins.c @@ -0,0 +1,50 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Cade Roux +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +CIRCUITPY_BOARD_BUS_SINGLETON(epd_spi, spi, 0) + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + // Buttons + { MP_ROM_QSTR(MP_QSTR_BUTTON_BOOT), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON_EXIT), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON_MENU), MP_ROM_PTR(&pin_GPIO2) }, + + // Rocker Switch + { MP_ROM_QSTR(MP_QSTR_ROCKER_DOWN), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_ROCKER_CLICK), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_ROCKER_UP), MP_ROM_PTR(&pin_GPIO6) }, + + // LED + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO19) }, + + // Device Control (Pins that, when activated, enable devices) + { MP_ROM_QSTR(MP_QSTR_EPD_ENABLE), MP_ROM_PTR(&pin_GPIO7) }, + + // EPD + { MP_ROM_QSTR(MP_QSTR_EPD_BUSY), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_EPD_RES), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_EPD_DC), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_EPD_CS), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_EPD_CLK), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_EPD_MOSI), MP_ROM_PTR(&pin_GPIO11) }, + + // User accessible GPIO + { MP_ROM_QSTR(MP_QSTR_IO40), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_IO41), MP_ROM_PTR(&pin_GPIO41) }, + + // UART + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO44) }, + + // Objects + { MP_ROM_QSTR(MP_QSTR_EPD_SPI), MP_ROM_PTR(&board_epd_spi_obj) }, + { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/espressif/boards/elecrow_crowpanel_2_13_epaper/sdkconfig b/ports/espressif/boards/elecrow_crowpanel_2_13_epaper/sdkconfig new file mode 100644 index 00000000000..e9628662160 --- /dev/null +++ b/ports/espressif/boards/elecrow_crowpanel_2_13_epaper/sdkconfig @@ -0,0 +1,14 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Component config +# +# +# LWIP +# +# end of LWIP + +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/boards/elecrow_crowpanel_3.5/board.c b/ports/espressif/boards/elecrow_crowpanel_3.5/board.c new file mode 100755 index 00000000000..e1be66c7c51 --- /dev/null +++ b/ports/espressif/boards/elecrow_crowpanel_3.5/board.c @@ -0,0 +1,99 @@ +#include "supervisor/board.h" +#include "mpconfigboard.h" +#include "shared-bindings/busio/SPI.h" +#include "shared-bindings/fourwire/FourWire.h" +#include "shared-module/displayio/__init__.h" +#include "shared-module/displayio/mipi_constants.h" + +#include "common-hal/microcontroller/Pin.h" + +// reference: lv_micropython ili9XXX.py +// reference: ILI9488 datasheet + +#define DELAY_FLAG 0x80 + +#define COLORMODE_BGR 0b00001000 +#define ROTATION_Y_FLIP 0b10000000 +#define ROTATION_X_FLIP 0b01000000 +#define ROTATION_MV 0b00100000 + +// DBI type C (SPI) only has 3bit and 18bit format support, 3bit = 2 pixels per byte, 18bit = one color per byte +#define COLORFORMAT_3BIT 0b00000001 +#define COLORFORMAT_16BIT 0b00000101 +#define COLORFORMAT_18BIT 0b00000110 +#define COLORFORMAT_24BIT 0b00000111 + +static uint8_t display_init_sequence[] = { + 0x01, DELAY_FLAG | 0, 200, // Software Reset + 0x11, DELAY_FLAG | 0, 120, // Exit Sleep Mode + 0xE0, 15, 0x00, 0x03, 0x09, 0x08, 0x16, 0x0A, 0x3F, 0x78, 0x4C, 0x09, 0x0A, 0x08, 0x16, 0x1A, 0x0F, // Positive Gamma Control + 0xE1, 15, 0x00, 0x16, 0x19, 0x03, 0x0F, 0x05, 0x32, 0x45, 0x46, 0x04, 0x0E, 0x0D, 0x35, 0x37, 0x0F, // Negative Gamma Control + 0xC0, 2, 0x17, 0x15, // Power Control 1 + 0xC1, 1, 0x41, // Power Control 2 + 0xC2, 1, 0x44, // Power Control 3 / Normal Mode + 0xC5, 3, 0x00, 0x12, 0x80, // VCOM Control + 0x36, 1, ROTATION_Y_FLIP, // Colormode & Rotation + 0x3A, 1, COLORFORMAT_18BIT, // Interface pixel format + 0xB0, 1, 0x00, // Interface mode control + 0xB1, 1, 0xA0, // Frame Rate Control + 0xB4, 1, 0x02, // Display Inversion Control + 0xB6, 2, 0x02, 0x02, // Display Function Control + 0xE9, 1, 0x00, // Set Image Function + 0x53, 1, 0x28, // CTRL Display Value + 0x51, 1, 0x7F, // Display Brightness + 0xF7, 4, 0xA9, 0x51, 0x2C, 0x02, // Adjust Control 3 + 0x29, DELAY_FLAG | 0, 25 // Display ON +}; + +void board_init(void) { + fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; + busio_spi_obj_t *spi = &bus->inline_bus; + common_hal_busio_spi_construct(spi, &pin_GPIO14, &pin_GPIO13, NULL, false); + + bus->base.type = &fourwire_fourwire_type; + common_hal_fourwire_fourwire_construct(bus, + spi, + MP_OBJ_FROM_PTR(&pin_GPIO2), // TFT_DC Command or data + MP_OBJ_FROM_PTR(&pin_GPIO15), // TFT_CS Chip select + mp_const_none, // TFT_RST Reset + 20000000, // Baudrate + 0, // Polarity + 0); // Phase + + busdisplay_busdisplay_obj_t *display = &allocate_display()->display; + display->base.type = &busdisplay_busdisplay_type; + common_hal_busdisplay_busdisplay_construct(display, + bus, + 320, // Width (after rotation) + 480, // Height (after rotation) + 0, // column start + 0, // row start + 0, // rotation + 24, // Color depth + false, // grayscale + false, // pixels in byte share 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 + display_init_sequence, + sizeof(display_init_sequence), + &pin_GPIO27, // backlight pin + 0x51, // cmd to write brightness + 0.5f, // brightness + false, // single_byte_bounds + false, // data_as_commands + true, // auto_refresh + 60, // native_frames_per_second + true, // backlight_on_high + false, // SH1107_addressing + 50000); // backlight pwm frequency +} + +void board_deinit(void) { + common_hal_displayio_release_displays(); +} + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/elecrow_crowpanel_3.5/mpconfigboard.h b/ports/espressif/boards/elecrow_crowpanel_3.5/mpconfigboard.h new file mode 100644 index 00000000000..9c080fd3223 --- /dev/null +++ b/ports/espressif/boards/elecrow_crowpanel_3.5/mpconfigboard.h @@ -0,0 +1,41 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2024 Chris Drake, independently providing these changes. + * + * 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. + */ + +#define MICROPY_HW_BOARD_NAME "Elecrow CrowPanel" +#define MICROPY_HW_MCU_NAME "ESP32" + +#define CIRCUITPY_BOARD_I2C (1) +#define CIRCUITPY_BOARD_I2C_PIN {{.scl = &pin_GPIO22, .sda = &pin_GPIO21}} + +#define CIRCUITPY_BOARD_SPI (2) +#define CIRCUITPY_BOARD_SPI_PIN {{.clock = &pin_GPIO18, .mosi = &pin_GPIO23, .miso = &pin_GPIO19}, /* SD */ \ + {.clock = &pin_GPIO14, .mosi = &pin_GPIO13, .miso = &pin_GPIO12} /* LCD & touch */ } + +// UART pins attached to the USB-serial converter chip +#define CIRCUITPY_CONSOLE_UART_TX (&pin_GPIO1) +#define CIRCUITPY_CONSOLE_UART_RX (&pin_GPIO3) + +#define CIRCUITPY_I2C_ALLOW_INTERNAL_PULL_UP (1) diff --git a/ports/espressif/boards/elecrow_crowpanel_3.5/mpconfigboard.mk b/ports/espressif/boards/elecrow_crowpanel_3.5/mpconfigboard.mk new file mode 100755 index 00000000000..f92068909fb --- /dev/null +++ b/ports/espressif/boards/elecrow_crowpanel_3.5/mpconfigboard.mk @@ -0,0 +1,17 @@ +CIRCUITPY_CREATOR_ID = 0xDD500000 +CIRCUITPY_CREATION_ID = 0x00320000 + +IDF_TARGET = esp32 + +# This board doesn't have USB by default, it +# instead uses a CH340C USB-to-Serial chip +CIRCUITPY_USB_DEVICE = 0 +CIRCUITPY_ESP_USB_SERIAL_JTAG = 0 + +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m +CIRCUITPY_ESP_FLASH_SIZE = 4MB + +CIRCUITPY_ESP_PSRAM_SIZE = 8MB +CIRCUITPY_ESP_PSRAM_MODE = qio +CIRCUITPY_ESP_PSRAM_FREQ = 80m diff --git a/ports/espressif/boards/elecrow_crowpanel_3.5/pins.c b/ports/espressif/boards/elecrow_crowpanel_3.5/pins.c new file mode 100755 index 00000000000..147db0a346d --- /dev/null +++ b/ports/espressif/boards/elecrow_crowpanel_3.5/pins.c @@ -0,0 +1,72 @@ +#include "py/objtuple.h" +#include "shared-bindings/board/__init__.h" +#include "shared-module/displayio/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO22) }, + { 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) }, + + // TFT and Touch Panel share the same SPI bus + { MP_ROM_QSTR(MP_QSTR_TFT_MISO), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_TFT_MOSI), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_TFT_CLK), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_TFT_CS), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_TFT_DC), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_TFT_BACKLIGHT), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_TP_CS), MP_ROM_PTR(&pin_GPIO33) }, + { MP_ROM_QSTR(MP_QSTR_TP_IRQ), MP_ROM_PTR(&pin_GPIO36) }, + + // Version 2.2 hardware (Sep 2024) swaps MISO & touch CS pins + { MP_ROM_QSTR(MP_QSTR_TFT_MISO_ALT), MP_ROM_PTR(&pin_GPIO33) }, + { MP_ROM_QSTR(MP_QSTR_TP_CS_ALT), MP_ROM_PTR(&pin_GPIO12) }, + + // SD card SPI bus + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_SD_CS), MP_ROM_PTR(&pin_GPIO5) }, + + { MP_ROM_QSTR(MP_QSTR_GPIO1), MP_ROM_PTR(&pin_GPIO25) }, + { MP_ROM_QSTR(MP_QSTR_GPIO2), MP_ROM_PTR(&pin_GPIO32) }, + + { MP_ROM_QSTR(MP_QSTR_SPEAK), MP_ROM_PTR(&pin_GPIO26) }, + + { 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_IO18), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_IO19), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_IO21), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_IO22), MP_ROM_PTR(&pin_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_IO23), MP_ROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_IO25), MP_ROM_PTR(&pin_GPIO25) }, + { MP_ROM_QSTR(MP_QSTR_IO26), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_IO27), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_IO32), MP_ROM_PTR(&pin_GPIO32) }, + { 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_IO39), MP_ROM_PTR(&pin_GPIO39) }, + + { 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/espressif/boards/elecrow_crowpanel_3.5/sdkconfig b/ports/espressif/boards/elecrow_crowpanel_3.5/sdkconfig new file mode 100755 index 00000000000..a571ec9cacb --- /dev/null +++ b/ports/espressif/boards/elecrow_crowpanel_3.5/sdkconfig @@ -0,0 +1,9 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# +# Component config +# +# +# Hardware Settings diff --git a/ports/espressif/boards/elecrow_crowpanel_4_2_epaper/board.c b/ports/espressif/boards/elecrow_crowpanel_4_2_epaper/board.c index 4567e2c5956..38219e0c5e7 100644 --- a/ports/espressif/boards/elecrow_crowpanel_4_2_epaper/board.c +++ b/ports/espressif/boards/elecrow_crowpanel_4_2_epaper/board.c @@ -44,60 +44,47 @@ void board_init(void) { epd_enable_pin_obj.base.type = &digitalio_digitalinout_type; common_hal_digitalio_digitalinout_construct(&epd_enable_pin_obj, &pin_GPIO7); common_hal_digitalio_digitalinout_switch_to_output(&epd_enable_pin_obj, true, DRIVE_MODE_PUSH_PULL); - common_hal_digitalio_digitalinout_never_reset(&epd_enable_pin_obj); // Set up the SPI object used to control the display fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_GPIO12, &pin_GPIO11, NULL, false); - common_hal_busio_spi_never_reset(spi); // Set up the DisplayIO pin object bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_GPIO46, // EPD_DC Command or data - &pin_GPIO45, // EPD_CS Chip select - &pin_GPIO47, // EPD_RST Reset + MP_OBJ_FROM_PTR(&pin_GPIO46), // EPD_DC Command or data + MP_OBJ_FROM_PTR(&pin_GPIO45), // EPD_CS Chip select + MP_OBJ_FROM_PTR(&pin_GPIO47), // EPD_RST Reset 1000000, // Baudrate 0, // Polarity 0); // Phase -// Set up the DisplayIO epaper object + // Set up the DisplayIO epaper object epaperdisplay_epaperdisplay_obj_t *display = &allocate_display()->epaper_display; display->base.type = &epaperdisplay_epaperdisplay_type; - common_hal_epaperdisplay_epaperdisplay_construct( - display, - bus, - display_start_sequence, sizeof(display_start_sequence), - 1, // start up time - display_stop_sequence, sizeof(display_stop_sequence), - 400, // width - 300, // height - 400, // ram_width - 300, // ram_height - 0, // colstart - 0, // rowstart - 0, // rotation - NO_COMMAND, // set_column_window_command - NO_COMMAND, // set_row_window_command - NO_COMMAND, // set_current_column_command - NO_COMMAND, // set_current_row_command - 0x24, // write_black_ram_command - false, // black_bits_inverted - 0x26, // write_color_ram_command - false, // color_bits_inverted - 0x000000, // highlight_color - refresh_sequence, sizeof(refresh_sequence), // refresh_display_command - 1.0, // refresh_time - &pin_GPIO48, // busy_pin - true, // busy_state - 2.0, // seconds_per_frame - false, // always_toggle_chip_select - false, // grayscale - false, // acep - false, // two_byte_sequence_length - false); // address_little_endian + + epaperdisplay_construct_args_t args = EPAPERDISPLAY_CONSTRUCT_ARGS_DEFAULTS; + args.bus = bus; + args.start_sequence = display_start_sequence; + args.start_sequence_len = sizeof(display_start_sequence); + args.start_up_time = 1.0; + args.stop_sequence = display_stop_sequence; + args.stop_sequence_len = sizeof(display_stop_sequence); + args.width = 400; + args.height = 300; + args.ram_width = 400; + args.ram_height = 300; + args.write_black_ram_command = 0x24; + args.write_color_ram_command = 0x26; + args.refresh_sequence = refresh_sequence; + args.refresh_sequence_len = sizeof(refresh_sequence); + args.refresh_time = 1.0; + args.busy_pin = &pin_GPIO48; + args.busy_state = true; + args.seconds_per_frame = 2.0; + common_hal_epaperdisplay_epaperdisplay_construct(display, &args); } void board_deinit(void) { diff --git a/ports/espressif/boards/elecrow_crowpanel_4_2_epaper/mpconfigboard.mk b/ports/espressif/boards/elecrow_crowpanel_4_2_epaper/mpconfigboard.mk index 5b6e293439c..3f14971607b 100644 --- a/ports/espressif/boards/elecrow_crowpanel_4_2_epaper/mpconfigboard.mk +++ b/ports/espressif/boards/elecrow_crowpanel_4_2_epaper/mpconfigboard.mk @@ -15,5 +15,3 @@ CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_PSRAM_SIZE = 8MB CIRCUITPY_ESP_PSRAM_MODE = opi CIRCUITPY_ESP_PSRAM_FREQ = 80m - -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/electroniccats_bastwifi/mpconfigboard.mk b/ports/espressif/boards/electroniccats_bastwifi/mpconfigboard.mk index dc73ae08f55..6234a6b60cc 100644 --- a/ports/espressif/boards/electroniccats_bastwifi/mpconfigboard.mk +++ b/ports/espressif/boards/electroniccats_bastwifi/mpconfigboard.mk @@ -5,9 +5,6 @@ USB_MANUFACTURER = "ElectronicCats" IDF_TARGET = esp32s2 -CIRCUITPY_NEOPIXEL_WRITE = 0 - CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/elio_eliobot_s3/board.c b/ports/espressif/boards/elio_eliobot_s3/board.c new file mode 100644 index 00000000000..895f4397351 --- /dev/null +++ b/ports/espressif/boards/elio_eliobot_s3/board.c @@ -0,0 +1,39 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Romain Boutrois +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" +#include "mpconfigboard.h" +#include "shared-bindings/microcontroller/Pin.h" + +#include "py/mpstate.h" +#include "supervisor/filesystem.h" + +void board_init(void) { + mp_import_stat_t stat_b = mp_import_stat("boot.py"); + if (stat_b != MP_IMPORT_STAT_FILE) { + supervisor_vfs_t *fs_mount = filesystem_circuitpy(); + supervisor_vfs_file_t fs; + // Default boot.py: CIRCUITPY is read-only over USB so children can't + // break the robot's files from the drive, while code sent over the + // serial REPL or BLE (Eliobot's web editor) can still write them. + const byte buffer[] = + "import storage\n" + "\n" + "# Eliobot default: the USB drive is read-only, and code sent by\n" + "# the Elioblocs editor can write files. To edit files from the drive\n" + "# instead, comment out the next line.\n" + "storage.remount(\"/\", False)\n"; + if (supervisor_vfs_open_file(fs_mount, "/boot.py", + SUPERVISOR_FS_OPEN_WRITE | SUPERVISOR_FS_OPEN_CREATE | + SUPERVISOR_FS_OPEN_TRUNCATE, 0, &fs) == SUPERVISOR_FS_OK) { + size_t char_written = 0; + supervisor_vfs_write_file(&fs, buffer, sizeof(buffer) - 1, &char_written); + supervisor_vfs_close_file(&fs); + } + } +} + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/elio_eliobot_s3/mpconfigboard.h b/ports/espressif/boards/elio_eliobot_s3/mpconfigboard.h new file mode 100644 index 00000000000..7919df48932 --- /dev/null +++ b/ports/espressif/boards/elio_eliobot_s3/mpconfigboard.h @@ -0,0 +1,27 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Romain Boutrois +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Micropython setup + +#define MICROPY_HW_BOARD_NAME "Eliobot" +#define MICROPY_HW_MCU_NAME "ESP32S3" +#define CIRCUITPY_DRIVE_LABEL "ELIOBOT" + +// Current boards have one status NeoPixel; the next revision chains eight. +#define MICROPY_HW_NEOPIXEL (&pin_GPIO1) +#define MICROPY_HW_NEOPIXEL_COUNT (8) + +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO9) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO8) + +#define DEFAULT_SPI_BUS_SCK (&pin_GPIO39) +#define DEFAULT_SPI_BUS_MOSI (&pin_GPIO40) +#define DEFAULT_SPI_BUS_MISO (&pin_GPIO41) + +#define DEFAULT_UART_BUS_RX (&pin_GPIO44) +#define DEFAULT_UART_BUS_TX (&pin_GPIO43) diff --git a/ports/espressif/boards/elio_eliobot_s3/mpconfigboard.mk b/ports/espressif/boards/elio_eliobot_s3/mpconfigboard.mk new file mode 100644 index 00000000000..405b8e872df --- /dev/null +++ b/ports/espressif/boards/elio_eliobot_s3/mpconfigboard.mk @@ -0,0 +1,27 @@ +USB_VID = 0x303a +USB_PID = 0x8384 +USB_PRODUCT = "Eliobot" +USB_MANUFACTURER = "ELIO" +USB_INTERFACE_NAME = "Eliobot" + +IDF_TARGET = esp32s3 + +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m +CIRCUITPY_ESP_FLASH_SIZE = 4MB + +CIRCUITPY_ESP_PSRAM_SIZE = 2MB +CIRCUITPY_ESP_PSRAM_MODE = qio +CIRCUITPY_ESP_PSRAM_FREQ = 80m + +CIRCUITPY_ESPCAMERA = 0 +CIRCUITPY_BITMAPFILTER = 0 +CIRCUITPY_CODEOP = 0 +CIRCUITPY_PARALLELDISPLAYBUS = 0 + + +# Include these Python libraries in firmware. +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_HTTPServer +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_IRRemote +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_BLE diff --git a/ports/espressif/boards/elio_eliobot_s3/pins.c b/ports/espressif/boards/elio_eliobot_s3/pins.c new file mode 100644 index 00000000000..79f6e83aa61 --- /dev/null +++ b/ports/espressif/boards/elio_eliobot_s3/pins.c @@ -0,0 +1,134 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Romain Boutrois +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { MP_ROM_QSTR(MP_QSTR_IO0), MP_ROM_PTR(&pin_GPIO0) }, + + // GPIO1 : NeoPixel (WS2812B) + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO1) }, + + // GPIO2 : Eyes LED connector (J3) + { MP_ROM_QSTR(MP_QSTR_IO2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_EYES), MP_ROM_PTR(&pin_GPIO2) }, + + // GPIO3 : Battery voltage sense (ADC, 1:2 divider) + { MP_ROM_QSTR(MP_QSTR_IO3), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_BATTERY), 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) }, + + // GPIO4-7 : IR obstacle sensor outputs (TSSP77038) + { MP_ROM_QSTR(MP_QSTR_IO4), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_IR_OUT_1), MP_ROM_PTR(&pin_GPIO4) }, + + { MP_ROM_QSTR(MP_QSTR_IO5), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_IR_OUT_2), MP_ROM_PTR(&pin_GPIO5) }, + + { MP_ROM_QSTR(MP_QSTR_IO6), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_IR_OUT_3), MP_ROM_PTR(&pin_GPIO6) }, + + { MP_ROM_QSTR(MP_QSTR_IO7), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_IR_OUT_4), MP_ROM_PTR(&pin_GPIO7) }, + + // GPIO8-9 : I2C bus + { MP_ROM_QSTR(MP_QSTR_IO8), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO8) }, + + { MP_ROM_QSTR(MP_QSTR_IO9), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO9) }, + + // GPIO10-14 : Line sensors (J1) + { MP_ROM_QSTR(MP_QSTR_IO10), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_LINE_1), MP_ROM_PTR(&pin_GPIO10) }, + + { MP_ROM_QSTR(MP_QSTR_IO11), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_LINE_2), MP_ROM_PTR(&pin_GPIO11) }, + + { MP_ROM_QSTR(MP_QSTR_IO12), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_LINE_3), MP_ROM_PTR(&pin_GPIO12) }, + + { MP_ROM_QSTR(MP_QSTR_IO13), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_LINE_4), MP_ROM_PTR(&pin_GPIO13) }, + + { MP_ROM_QSTR(MP_QSTR_IO14), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_LINE_5), MP_ROM_PTR(&pin_GPIO14) }, + + // GPIO15-16 : free (no 32 kHz crystal fitted) + { MP_ROM_QSTR(MP_QSTR_IO15), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_IO16), MP_ROM_PTR(&pin_GPIO16) }, + + // GPIO17 : Buzzer + { MP_ROM_QSTR(MP_QSTR_IO17), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_BUZZER), MP_ROM_PTR(&pin_GPIO17) }, + + // GPIO18 : Line sensor LED enable + { MP_ROM_QSTR(MP_QSTR_IO18), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_LINE_LED), MP_ROM_PTR(&pin_GPIO18) }, + + // GPIO19 : USB_D- + // GPIO20 : USB_D+ + + // GPIO21 : VBUS sense (5V present, 1:2 divider) + { MP_ROM_QSTR(MP_QSTR_VBUS), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_VBUS_SENSE), MP_ROM_PTR(&pin_GPIO21) }, + + // GPIO26-32 : internal flash/PSRAM SPI — not available as GPIO + + // GPIO33 : Line sensor command output (J1) + { MP_ROM_QSTR(MP_QSTR_IO33), MP_ROM_PTR(&pin_GPIO33) }, + { MP_ROM_QSTR(MP_QSTR_LINE_CMD), MP_ROM_PTR(&pin_GPIO33) }, + + // GPIO34 : IR obstacle sensor 38kHz modulation output + { MP_ROM_QSTR(MP_QSTR_IO34), MP_ROM_PTR(&pin_GPIO34) }, + { MP_ROM_QSTR(MP_QSTR_IR_CMD), MP_ROM_PTR(&pin_GPIO34) }, + + // GPIO35-38 : Motor driver (DRV8833) + { MP_ROM_QSTR(MP_QSTR_IO35), MP_ROM_PTR(&pin_GPIO35) }, + { MP_ROM_QSTR(MP_QSTR_BIN2), MP_ROM_PTR(&pin_GPIO35) }, + + { MP_ROM_QSTR(MP_QSTR_IO36), MP_ROM_PTR(&pin_GPIO36) }, + { MP_ROM_QSTR(MP_QSTR_AIN1), MP_ROM_PTR(&pin_GPIO36) }, + + { MP_ROM_QSTR(MP_QSTR_IO37), MP_ROM_PTR(&pin_GPIO37) }, + { MP_ROM_QSTR(MP_QSTR_BIN1), MP_ROM_PTR(&pin_GPIO37) }, + + { MP_ROM_QSTR(MP_QSTR_IO38), MP_ROM_PTR(&pin_GPIO38) }, + { MP_ROM_QSTR(MP_QSTR_AIN2), MP_ROM_PTR(&pin_GPIO38) }, + + // GPIO39-41 : SPI header (J8) via JTAG pins MTCK/MTDO/MTDI + { MP_ROM_QSTR(MP_QSTR_IO39), MP_ROM_PTR(&pin_GPIO39) }, + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_GPIO39) }, + + { MP_ROM_QSTR(MP_QSTR_IO40), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO40) }, + + { MP_ROM_QSTR(MP_QSTR_IO41), MP_ROM_PTR(&pin_GPIO41) }, + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO41) }, + + { MP_ROM_QSTR(MP_QSTR_IO42), MP_ROM_PTR(&pin_GPIO42) }, + + // GPIO43-44 : UART (U0TXD / U0RXD) + { MP_ROM_QSTR(MP_QSTR_IO43), 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_RX), MP_ROM_PTR(&pin_GPIO44) }, + + // GPIO45 : SPI chip select (J8) + { MP_ROM_QSTR(MP_QSTR_IO45), MP_ROM_PTR(&pin_GPIO45) }, + { MP_ROM_QSTR(MP_QSTR_SS), MP_ROM_PTR(&pin_GPIO45) }, + + { MP_ROM_QSTR(MP_QSTR_IO46), MP_ROM_PTR(&pin_GPIO46) }, + + { 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_module_globals_table); diff --git a/ports/espressif/boards/elio_eliobot_s3/sdkconfig b/ports/espressif/boards/elio_eliobot_s3/sdkconfig new file mode 100644 index 00000000000..253a3984eb1 --- /dev/null +++ b/ports/espressif/boards/elio_eliobot_s3/sdkconfig @@ -0,0 +1,16 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Component config +# +# +# LWIP +# +CONFIG_LWIP_LOCAL_HOSTNAME="ELIOBOT" + +# end of LWIP + +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/boards/es3ink/board.c b/ports/espressif/boards/es3ink/board.c index 1ecda1cd7f6..a3a9eec0471 100644 --- a/ports/espressif/boards/es3ink/board.c +++ b/ports/espressif/boards/es3ink/board.c @@ -5,15 +5,5 @@ // SPDX-License-Identifier: MIT #include "supervisor/board.h" -#include "mpconfigboard.h" -#include "shared-bindings/microcontroller/Pin.h" - -void board_init(void) { - // Debug UART - #ifdef DEBUG - common_hal_never_reset_pin(&pin_GPIO43); - common_hal_never_reset_pin(&pin_GPIO44); - #endif /* DEBUG */ -} // Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/espressif_esp32_devkitc_v4_wroom_32e/mpconfigboard.mk b/ports/espressif/boards/espressif_esp32_devkitc_v4_wroom_32e/mpconfigboard.mk index 766196f9b30..aa34430a34c 100644 --- a/ports/espressif/boards/espressif_esp32_devkitc_v4_wroom_32e/mpconfigboard.mk +++ b/ports/espressif/boards/espressif_esp32_devkitc_v4_wroom_32e/mpconfigboard.mk @@ -6,7 +6,3 @@ IDF_TARGET = esp32 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB - -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 - -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/espressif_esp32_devkitc_v4_wrover/mpconfigboard.mk b/ports/espressif/boards/espressif_esp32_devkitc_v4_wrover/mpconfigboard.mk index 6ff7d4e519b..848c55d54c1 100644 --- a/ports/espressif/boards/espressif_esp32_devkitc_v4_wrover/mpconfigboard.mk +++ b/ports/espressif/boards/espressif_esp32_devkitc_v4_wrover/mpconfigboard.mk @@ -7,8 +7,6 @@ CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 8MB -CIRCUITPY_ESPCAMERA = 0 - CIRCUITPY_ESP_PSRAM_SIZE = 8MB CIRCUITPY_ESP_PSRAM_MODE = qio CIRCUITPY_ESP_PSRAM_FREQ = 40m diff --git a/ports/espressif/boards/espressif_esp32_eye/board.c b/ports/espressif/boards/espressif_esp32_eye/board.c index 28471788e7d..d64648785e2 100644 --- a/ports/espressif/boards/espressif_esp32_eye/board.c +++ b/ports/espressif/boards/espressif_esp32_eye/board.c @@ -11,6 +11,11 @@ #include "common-hal/microcontroller/Pin.h" void board_init(void) { + // GPIO21 (LED_RED) and GPIO22 (LED_WHITE) drive LEDs. Default to pulled + // down (off). + espressif_board_reset_pin_number(21); + espressif_board_reset_pin_number(22); + reset_board(); } diff --git a/ports/espressif/boards/espressif_esp32_eye/mpconfigboard.mk b/ports/espressif/boards/espressif_esp32_eye/mpconfigboard.mk index 92d855842ff..1980ff38ccd 100644 --- a/ports/espressif/boards/espressif_esp32_eye/mpconfigboard.mk +++ b/ports/espressif/boards/espressif_esp32_eye/mpconfigboard.mk @@ -13,12 +13,5 @@ CIRCUITPY_ESP_PSRAM_SIZE = 8MB CIRCUITPY_ESP_PSRAM_MODE = qio CIRCUITPY_ESP_PSRAM_FREQ = 40m -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 - CIRCUITPY_CANIO = 0 CIRCUITPY_NEOPIXEL_WRITE = 0 -CIRCUITPY_PIXELBUF = 0 -CIRCUITPY_PS2IO = 0 -CIRCUITPY_ROTARYIO = 0 -CIRCUITPY_TOUCHIO = 0 -CIRCUITPY_KEYPAD = 0 diff --git a/ports/espressif/boards/espressif_esp32_lyrat/mpconfigboard.mk b/ports/espressif/boards/espressif_esp32_lyrat/mpconfigboard.mk index 4865e855023..664c24c358f 100644 --- a/ports/espressif/boards/espressif_esp32_lyrat/mpconfigboard.mk +++ b/ports/espressif/boards/espressif_esp32_lyrat/mpconfigboard.mk @@ -10,7 +10,3 @@ CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_PSRAM_SIZE = 4MB CIRCUITPY_ESP_PSRAM_MODE = qio CIRCUITPY_ESP_PSRAM_FREQ = 40m - -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 - -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/espressif_esp32c3_devkitm_1_n4/mpconfigboard.mk b/ports/espressif/boards/espressif_esp32c3_devkitm_1_n4/mpconfigboard.mk index 5b4f4b7ead6..1bbb997a710 100644 --- a/ports/espressif/boards/espressif_esp32c3_devkitm_1_n4/mpconfigboard.mk +++ b/ports/espressif/boards/espressif_esp32c3_devkitm_1_n4/mpconfigboard.mk @@ -7,6 +7,4 @@ CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 - CIRCUITPY_ESP_USB_SERIAL_JTAG = 0 diff --git a/ports/espressif/boards/espressif_esp32c3_lyra_v2/board.c b/ports/espressif/boards/espressif_esp32c3_lyra_v2/board.c new file mode 100644 index 00000000000..b3b20cfe2d3 --- /dev/null +++ b/ports/espressif/boards/espressif_esp32c3_lyra_v2/board.c @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 microDev +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/espressif_esp32c3_lyra_v2/mpconfigboard.h b/ports/espressif/boards/espressif_esp32c3_lyra_v2/mpconfigboard.h new file mode 100644 index 00000000000..d38d4f4d09f --- /dev/null +++ b/ports/espressif/boards/espressif_esp32c3_lyra_v2/mpconfigboard.h @@ -0,0 +1,23 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 microDev +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Board setup +#define MICROPY_HW_BOARD_NAME "ESP32-C3-Lyra-V2" +#define MICROPY_HW_MCU_NAME "ESP32-C3N4" + +// Status LED +#define MICROPY_HW_NEOPIXEL (&pin_GPIO10) +#define MICROPY_HW_NEOPIXEL_COUNT (1) + +// Default bus pins +#define DEFAULT_UART_BUS_RX (&pin_GPIO20) +#define DEFAULT_UART_BUS_TX (&pin_GPIO21) + +// Serial over UART +#define CIRCUITPY_CONSOLE_UART_RX DEFAULT_UART_BUS_RX +#define CIRCUITPY_CONSOLE_UART_TX DEFAULT_UART_BUS_TX diff --git a/ports/espressif/boards/espressif_esp32c3_lyra_v2/mpconfigboard.mk b/ports/espressif/boards/espressif_esp32c3_lyra_v2/mpconfigboard.mk new file mode 100644 index 00000000000..4b23a76ba6a --- /dev/null +++ b/ports/espressif/boards/espressif_esp32c3_lyra_v2/mpconfigboard.mk @@ -0,0 +1,10 @@ +CIRCUITPY_CREATOR_ID = 0x000C303A +CIRCUITPY_CREATION_ID = 0x00C3A000 + +IDF_TARGET = esp32c3 + +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m +CIRCUITPY_ESP_FLASH_SIZE = 4MB + +CIRCUITPY_ESP_USB_SERIAL_JTAG = 0 diff --git a/ports/espressif/boards/espressif_esp32c3_lyra_v2/pins.c b/ports/espressif/boards/espressif_esp32c3_lyra_v2/pins.c new file mode 100644 index 00000000000..5f7c3d084dd --- /dev/null +++ b/ports/espressif/boards/espressif_esp32c3_lyra_v2/pins.c @@ -0,0 +1,41 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 microDev +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { 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_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_RX), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO21) }, + + { MP_ROM_QSTR(MP_QSTR_MTMS), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_MTDI), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_MTCK), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_MTDO), MP_ROM_PTR(&pin_GPIO7) }, + + { MP_ROM_QSTR(MP_QSTR_BUTTON), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO10) }, + + { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/tests/feature_check/async_check.py.exp b/ports/espressif/boards/espressif_esp32c3_lyra_v2/sdkconfig similarity index 100% rename from tests/feature_check/async_check.py.exp rename to ports/espressif/boards/espressif_esp32c3_lyra_v2/sdkconfig diff --git a/ports/espressif/boards/espressif_esp32c5_devkitc_1_n8r8/board.c b/ports/espressif/boards/espressif_esp32c5_devkitc_1_n8r8/board.c new file mode 100644 index 00000000000..a3a9eec0471 --- /dev/null +++ b/ports/espressif/boards/espressif_esp32c5_devkitc_1_n8r8/board.c @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/espressif_esp32c5_devkitc_1_n8r8/mpconfigboard.h b/ports/espressif/boards/espressif_esp32c5_devkitc_1_n8r8/mpconfigboard.h new file mode 100644 index 00000000000..ca05bf78b6a --- /dev/null +++ b/ports/espressif/boards/espressif_esp32c5_devkitc_1_n8r8/mpconfigboard.h @@ -0,0 +1,17 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Micropython setup + +#define MICROPY_HW_BOARD_NAME "ESP32-C5-DevKitC-1-N8R8" +#define MICROPY_HW_MCU_NAME "ESP32C5" + +#define MICROPY_HW_NEOPIXEL (&pin_GPIO27) + +#define DEFAULT_UART_BUS_RX (&pin_GPIO12) +#define DEFAULT_UART_BUS_TX (&pin_GPIO11) diff --git a/ports/espressif/boards/espressif_esp32c5_devkitc_1_n8r8/mpconfigboard.mk b/ports/espressif/boards/espressif_esp32c5_devkitc_1_n8r8/mpconfigboard.mk new file mode 100644 index 00000000000..0da008596e3 --- /dev/null +++ b/ports/espressif/boards/espressif_esp32c5_devkitc_1_n8r8/mpconfigboard.mk @@ -0,0 +1,12 @@ +CIRCUITPY_CREATOR_ID = 0x000C303A +CIRCUITPY_CREATION_ID = 0x00C50001 + +IDF_TARGET = esp32c5 + +CIRCUITPY_ESP_FLASH_MODE = dio +CIRCUITPY_ESP_FLASH_FREQ = 80m +CIRCUITPY_ESP_FLASH_SIZE = 8MB + +CIRCUITPY_ESP_PSRAM_SIZE = 8MB +CIRCUITPY_ESP_PSRAM_MODE = qio +CIRCUITPY_ESP_PSRAM_FREQ = 40m diff --git a/ports/espressif/boards/espressif_esp32c5_devkitc_1_n8r8/pins.c b/ports/espressif/boards/espressif_esp32c5_devkitc_1_n8r8/pins.c new file mode 100644 index 00000000000..dc4a478a592 --- /dev/null +++ b/ports/espressif/boards/espressif_esp32c5_devkitc_1_n8r8/pins.c @@ -0,0 +1,40 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { 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_IO13), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_IO14), MP_ROM_PTR(&pin_GPIO14) }, + + { MP_ROM_QSTR(MP_QSTR_IO23), MP_ROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_IO24), MP_ROM_PTR(&pin_GPIO24) }, + { MP_ROM_QSTR(MP_QSTR_IO25), MP_ROM_PTR(&pin_GPIO25) }, + { MP_ROM_QSTR(MP_QSTR_IO26), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_IO27), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_IO28), MP_ROM_PTR(&pin_GPIO28) }, + + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO27) }, + + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO12) }, + + { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/espressif/boards/espressif_esp32c5_devkitc_1_n8r8/sdkconfig b/ports/espressif/boards/espressif_esp32c5_devkitc_1_n8r8/sdkconfig new file mode 100644 index 00000000000..e9628662160 --- /dev/null +++ b/ports/espressif/boards/espressif_esp32c5_devkitc_1_n8r8/sdkconfig @@ -0,0 +1,14 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Component config +# +# +# LWIP +# +# end of LWIP + +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/boards/espressif_esp32c61_devkitc_1_n8r2/board.c b/ports/espressif/boards/espressif_esp32c61_devkitc_1_n8r2/board.c new file mode 100644 index 00000000000..a3a9eec0471 --- /dev/null +++ b/ports/espressif/boards/espressif_esp32c61_devkitc_1_n8r2/board.c @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/espressif_esp32c61_devkitc_1_n8r2/mpconfigboard.h b/ports/espressif/boards/espressif_esp32c61_devkitc_1_n8r2/mpconfigboard.h new file mode 100644 index 00000000000..d901bfb37ba --- /dev/null +++ b/ports/espressif/boards/espressif_esp32c61_devkitc_1_n8r2/mpconfigboard.h @@ -0,0 +1,15 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Micropython setup + +#define MICROPY_HW_BOARD_NAME "ESP32-C61-DevKitC-1-N8R2" +#define MICROPY_HW_MCU_NAME "ESP32C61" + +#define DEFAULT_UART_BUS_RX (&pin_GPIO10) +#define DEFAULT_UART_BUS_TX (&pin_GPIO11) diff --git a/ports/espressif/boards/espressif_esp32c61_devkitc_1_n8r2/mpconfigboard.mk b/ports/espressif/boards/espressif_esp32c61_devkitc_1_n8r2/mpconfigboard.mk new file mode 100644 index 00000000000..1092a874a68 --- /dev/null +++ b/ports/espressif/boards/espressif_esp32c61_devkitc_1_n8r2/mpconfigboard.mk @@ -0,0 +1,13 @@ +CIRCUITPY_CREATOR_ID = 0x000C303A +CIRCUITPY_CREATION_ID = 0x00C61001 + +IDF_TARGET = esp32c61 +IDF_TARGET_ARCH = riscv + +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m +CIRCUITPY_ESP_FLASH_SIZE = 8MB + +CIRCUITPY_ESP_PSRAM_SIZE = 2MB +CIRCUITPY_ESP_PSRAM_MODE = qio +CIRCUITPY_ESP_PSRAM_FREQ = 80m diff --git a/ports/espressif/boards/espressif_esp32c61_devkitc_1_n8r2/pins.c b/ports/espressif/boards/espressif_esp32c61_devkitc_1_n8r2/pins.c new file mode 100644 index 00000000000..901e5216657 --- /dev/null +++ b/ports/espressif/boards/espressif_esp32c61_devkitc_1_n8r2/pins.c @@ -0,0 +1,48 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { 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_IO22), MP_ROM_PTR(&pin_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_IO23), MP_ROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_IO24), MP_ROM_PTR(&pin_GPIO24) }, + { MP_ROM_QSTR(MP_QSTR_IO25), MP_ROM_PTR(&pin_GPIO25) }, + { MP_ROM_QSTR(MP_QSTR_IO26), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_IO27), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_IO28), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_IO29), MP_ROM_PTR(&pin_GPIO29) }, + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO8) }, + + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO10) }, + + { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/espressif/boards/espressif_esp32c61_devkitc_1_n8r2/sdkconfig b/ports/espressif/boards/espressif_esp32c61_devkitc_1_n8r2/sdkconfig new file mode 100644 index 00000000000..e9628662160 --- /dev/null +++ b/ports/espressif/boards/espressif_esp32c61_devkitc_1_n8r2/sdkconfig @@ -0,0 +1,14 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Component config +# +# +# LWIP +# +# end of LWIP + +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/boards/espressif_esp32c6_devkitm_1_n4/mpconfigboard.mk b/ports/espressif/boards/espressif_esp32c6_devkitm_1_n4/mpconfigboard.mk index 9685a7e62c5..75e097afa84 100644 --- a/ports/espressif/boards/espressif_esp32c6_devkitm_1_n4/mpconfigboard.mk +++ b/ports/espressif/boards/espressif_esp32c6_devkitm_1_n4/mpconfigboard.mk @@ -6,7 +6,3 @@ IDF_TARGET = esp32c6 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB - -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 - -CIRCUITPY_AUDIOMP3 = 0 diff --git a/ports/espressif/boards/espressif_esp32h2_devkitm_1_n4/mpconfigboard.mk b/ports/espressif/boards/espressif_esp32h2_devkitm_1_n4/mpconfigboard.mk index 82eb611bdf3..d1458fecec5 100644 --- a/ports/espressif/boards/espressif_esp32h2_devkitm_1_n4/mpconfigboard.mk +++ b/ports/espressif/boards/espressif_esp32h2_devkitm_1_n4/mpconfigboard.mk @@ -6,3 +6,6 @@ IDF_TARGET = esp32h2 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 48m CIRCUITPY_ESP_FLASH_SIZE = 4MB + +# Board was originally defined with a 2MB firmware, almost 2MB user filesystem. Leave it that way. +CIRCUITPY_4MB_FLASH_LARGE_USER_FS_LAYOUT = 1 diff --git a/ports/espressif/boards/espressif_esp32p4_function_ev/board.c b/ports/espressif/boards/espressif_esp32p4_function_ev/board.c index a3a9eec0471..2afd10bfbd8 100644 --- a/ports/espressif/boards/espressif_esp32p4_function_ev/board.c +++ b/ports/espressif/boards/espressif_esp32p4_function_ev/board.c @@ -1,9 +1,34 @@ // This file is part of the CircuitPython project: https://circuitpython.org // -// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries // // SPDX-License-Identifier: MIT #include "supervisor/board.h" +#if CIRCUITPY_MII +#include "common-hal/mii/__init__.h" +#include "shared-bindings/mii/MDIO.h" +#include "shared-bindings/mii/Ethernet.h" +#include "shared-bindings/mii/RMII.h" +#include "shared-bindings/microcontroller/Pin.h" + +// The board owns its ethernet instance and the MDIO + RMII bus wiring. +mii_mdio_obj_t board_mdio_obj; +mii_rmii_obj_t board_rmii_obj; +mii_ethernet_obj_t board_ethernet_obj; + +void board_init(void) { + common_hal_mii_mdio_construct(&board_mdio_obj, + &pin_GPIO31, &pin_GPIO52); // MDC, MDIO + common_hal_mii_rmii_construct(&board_rmii_obj, &board_mdio_obj, 1, + &pin_GPIO29, &pin_GPIO30, &pin_GPIO28, // RXD0, RXD1, RX_DV + &pin_GPIO34, &pin_GPIO35, &pin_GPIO49, // TXD0, TXD1, TX_EN + &pin_GPIO50, // REFCLK + &pin_GPIO51); // PHY reset (active low) + common_hal_mii_ethernet_construct(&board_ethernet_obj, &board_rmii_obj); + mii_set_default_instance(&board_ethernet_obj); +} +#endif + // Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/espressif_esp32p4_function_ev/mpconfigboard.h b/ports/espressif/boards/espressif_esp32p4_function_ev/mpconfigboard.h index 646fb62e562..25c9bf8f549 100644 --- a/ports/espressif/boards/espressif_esp32p4_function_ev/mpconfigboard.h +++ b/ports/espressif/boards/espressif_esp32p4_function_ev/mpconfigboard.h @@ -1,6 +1,6 @@ // This file is part of the CircuitPython project: https://circuitpython.org // -// SPDX-FileCopyrightText: Copyright (c) 2019 Scott Shawcroft for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries // // SPDX-License-Identifier: MIT @@ -16,5 +16,7 @@ #define DEFAULT_UART_BUS_RX (&pin_GPIO38) #define DEFAULT_UART_BUS_TX (&pin_GPIO37) -// Use the second USB device (numbered 0 and 1) -#define CIRCUITPY_USB_DEVICE_INSTANCE 1 +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO8) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO7) + +#define CIRCUITPY_USB_HOST_INSTANCE 0 diff --git a/ports/espressif/boards/espressif_esp32p4_function_ev/mpconfigboard.mk b/ports/espressif/boards/espressif_esp32p4_function_ev/mpconfigboard.mk index 247a1371192..3c5ba5ffc0e 100644 --- a/ports/espressif/boards/espressif_esp32p4_function_ev/mpconfigboard.mk +++ b/ports/espressif/boards/espressif_esp32p4_function_ev/mpconfigboard.mk @@ -5,6 +5,8 @@ USB_MANUFACTURER = "Espressif" IDF_TARGET = esp32p4 +CIRCUITPY_USB_DEVICE_INSTANCE = HIGH_SPEED_INSTANCE + CIRCUITPY_ESP_FLASH_SIZE = 16MB CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m @@ -12,3 +14,10 @@ CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_PSRAM_SIZE = 32MB CIRCUITPY_ESP_PSRAM_MODE = hpi CIRCUITPY_ESP_PSRAM_FREQ = 200m + +CIRCUITPY_MII = 1 +CIRCUITPY_SSL = 1 +CIRCUITPY_USB_VIDEO = 1 + +# mdns on Espressif requires the wifi-based ESP-IDF mdns component +CIRCUITPY_MDNS = 0 diff --git a/ports/espressif/boards/espressif_esp32p4_function_ev/pins.c b/ports/espressif/boards/espressif_esp32p4_function_ev/pins.c index 3bb64f434d0..fe77142d78c 100644 --- a/ports/espressif/boards/espressif_esp32p4_function_ev/pins.c +++ b/ports/espressif/boards/espressif_esp32p4_function_ev/pins.c @@ -1,55 +1,102 @@ // This file is part of the CircuitPython project: https://circuitpython.org // -// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries // // SPDX-License-Identifier: MIT #include "shared-bindings/board/__init__.h" +#if CIRCUITPY_MII +#include "common-hal/mii/Ethernet.h" + +extern mii_ethernet_obj_t board_ethernet_obj; +extern mii_rmii_obj_t board_rmii_obj; +#endif + static const mp_rom_map_elem_t board_module_globals_table[] = { CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS - { 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) }, + // Header Block J1 + { MP_ROM_QSTR(MP_QSTR_I2C_SDA), MP_ROM_PTR(&pin_GPIO7) }, { MP_ROM_QSTR(MP_QSTR_IO7), MP_ROM_PTR(&pin_GPIO7) }, + + { MP_ROM_QSTR(MP_QSTR_I2C_SCL), MP_ROM_PTR(&pin_GPIO8) }, { 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_IO35), MP_ROM_PTR(&pin_GPIO35) }, - { MP_ROM_QSTR(MP_QSTR_IO36), MP_ROM_PTR(&pin_GPIO36) }, + + { MP_ROM_QSTR(MP_QSTR_IO23), MP_ROM_PTR(&pin_GPIO23) }, + + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO37) }, { MP_ROM_QSTR(MP_QSTR_IO37), MP_ROM_PTR(&pin_GPIO37) }, + + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO38) }, { 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_IO43), MP_ROM_PTR(&pin_GPIO43) }, - { 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_IO21), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_IO22), MP_ROM_PTR(&pin_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_IO20), MP_ROM_PTR(&pin_GPIO20) }, + + { MP_ROM_QSTR(MP_QSTR_C6_WAKEUP), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_IO6), MP_ROM_PTR(&pin_GPIO6) }, + + { MP_ROM_QSTR(MP_QSTR_IO5), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_IO4), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_IO3), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_IO2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_IO36), MP_ROM_PTR(&pin_GPIO36) }, + + { MP_ROM_QSTR(MP_QSTR_IO32), MP_ROM_PTR(&pin_GPIO32) }, + { MP_ROM_QSTR(MP_QSTR_IO24), MP_ROM_PTR(&pin_GPIO24) }, + { MP_ROM_QSTR(MP_QSTR_IO25), MP_ROM_PTR(&pin_GPIO25) }, + + { MP_ROM_QSTR(MP_QSTR_IO33), MP_ROM_PTR(&pin_GPIO33) }, + { MP_ROM_QSTR(MP_QSTR_IO26), MP_ROM_PTR(&pin_GPIO26) }, + + { MP_ROM_QSTR(MP_QSTR_C6_EN), MP_ROM_PTR(&pin_GPIO54) }, + { MP_ROM_QSTR(MP_QSTR_IO54), MP_ROM_PTR(&pin_GPIO54) }, + + { MP_ROM_QSTR(MP_QSTR_IO48), MP_ROM_PTR(&pin_GPIO48) }, + + { MP_ROM_QSTR(MP_QSTR_PA_CTRL), MP_ROM_PTR(&pin_GPIO53) }, + { MP_ROM_QSTR(MP_QSTR_IO53), MP_ROM_PTR(&pin_GPIO53) }, + { MP_ROM_QSTR(MP_QSTR_IO46), MP_ROM_PTR(&pin_GPIO46) }, { MP_ROM_QSTR(MP_QSTR_IO47), MP_ROM_PTR(&pin_GPIO47) }, - { MP_ROM_QSTR(MP_QSTR_IO48), MP_ROM_PTR(&pin_GPIO48) }, - { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO48) }, + { MP_ROM_QSTR(MP_QSTR_IO27), MP_ROM_PTR(&pin_GPIO27) }, + + // I2S + { MP_ROM_QSTR(MP_QSTR_I2S_DSDIN), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_I2S_LRCK), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_I2S_ASDOUT), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_I2S_SCLK), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_I2S_MCLK), MP_ROM_PTR(&pin_GPIO13) }, - { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO43) }, - { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO44) }, + // Ethernet + { MP_ROM_QSTR(MP_QSTR_RMII_RXDV), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_RMII_RXD0), MP_ROM_PTR(&pin_GPIO29) }, + { MP_ROM_QSTR(MP_QSTR_RMII_RXD1), MP_ROM_PTR(&pin_GPIO30) }, + { MP_ROM_QSTR(MP_QSTR_MDC), MP_ROM_PTR(&pin_GPIO31) }, + { MP_ROM_QSTR(MP_QSTR_RMII_TXD0), MP_ROM_PTR(&pin_GPIO34) }, + { MP_ROM_QSTR(MP_QSTR_RMII_TXD1), MP_ROM_PTR(&pin_GPIO35) }, + { MP_ROM_QSTR(MP_QSTR_RMII_TXEN), MP_ROM_PTR(&pin_GPIO49) }, + { MP_ROM_QSTR(MP_QSTR_RMII_CLK), MP_ROM_PTR(&pin_GPIO50) }, + { MP_ROM_QSTR(MP_QSTR_PHY_RSTN), MP_ROM_PTR(&pin_GPIO51) }, + { MP_ROM_QSTR(MP_QSTR_MDIO), MP_ROM_PTR(&pin_GPIO52) }, + // SD Card + { MP_ROM_QSTR(MP_QSTR_SD_DATA0), MP_ROM_PTR(&pin_GPIO39) }, + { MP_ROM_QSTR(MP_QSTR_SD_DATA1), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_SD_DATA2), MP_ROM_PTR(&pin_GPIO41) }, + { MP_ROM_QSTR(MP_QSTR_SD_DATA3), MP_ROM_PTR(&pin_GPIO42) }, + { MP_ROM_QSTR(MP_QSTR_SD_CLK), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_SD_CMD), MP_ROM_PTR(&pin_GPIO44) }, + { MP_ROM_QSTR(MP_QSTR_SD_PWRN), MP_ROM_PTR(&pin_GPIO45) }, + + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj) }, + + #if CIRCUITPY_MII + { MP_ROM_QSTR(MP_QSTR_ETHERNET), MP_ROM_PTR(&board_ethernet_obj) }, + { MP_ROM_QSTR(MP_QSTR_RMII), MP_ROM_PTR(&board_rmii_obj) }, + #endif }; MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/espressif/boards/espressif_esp32p4_function_ev/sdkconfig b/ports/espressif/boards/espressif_esp32p4_function_ev/sdkconfig index e69de29bb2d..8ad98a7b081 100644 --- a/ports/espressif/boards/espressif_esp32p4_function_ev/sdkconfig +++ b/ports/espressif/boards/espressif_esp32p4_function_ev/sdkconfig @@ -0,0 +1,27 @@ +# +# Espressif IoT Development Framework Configuration +# +# Bootloader +# +CONFIG_BOOTLOADER_LOG_LEVEL_WARN=y +CONFIG_BOOTLOADER_LOG_LEVEL=2 +# end of Bootloader + +# This board ships with pre-v3 (eco2) silicon: link the 2nd stage bootloader +# into the lower memory layout used by revisions 0.x and 1.x. +CONFIG_ESP32P4_SELECTS_REV_LESS_V3=y +# This board's silicon is rev v1.3; match the working BSP-demo build (REV_MIN +# v1.0) so IDF compiles the same errata/clock handling as the reference stack. +CONFIG_ESP32P4_REV_MIN_100=y +CONFIG_ETH_USE_ESP32_EMAC=y + +# ESP-STDIO: send the ESP-IDF console to the USB-Serial-JTAG port so bootloader +# logs are visible on the board's serial connector. +# +CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG=y +CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG_ENABLED=y +CONFIG_ESP_CONSOLE_UART_NUM=-1 +CONFIG_ESP_CONSOLE_ROM_SERIAL_PORT_NUM=6 +# end of ESP-STDIO + +# CONFIG_ESP_SYSTEM_MEMPROT is not set diff --git a/ports/espressif/boards/espressif_esp32p4x_function_ev/board.c b/ports/espressif/boards/espressif_esp32p4x_function_ev/board.c new file mode 100644 index 00000000000..158837c6350 --- /dev/null +++ b/ports/espressif/boards/espressif_esp32p4x_function_ev/board.c @@ -0,0 +1,34 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" + +#if CIRCUITPY_MII +#include "common-hal/mii/__init__.h" +#include "shared-bindings/mii/MDIO.h" +#include "shared-bindings/mii/Ethernet.h" +#include "shared-bindings/mii/RMII.h" +#include "shared-bindings/microcontroller/Pin.h" + +// The board owns its ethernet instance and the MDIO + RMII bus wiring. +mii_mdio_obj_t board_mdio_obj; +mii_rmii_obj_t board_rmii_obj; +mii_ethernet_obj_t board_ethernet_obj; + +void board_init(void) { + common_hal_mii_mdio_construct(&board_mdio_obj, + &pin_GPIO31, &pin_GPIO52); // MDC, MDIO + common_hal_mii_rmii_construct(&board_rmii_obj, &board_mdio_obj, 1, + &pin_GPIO29, &pin_GPIO30, &pin_GPIO28, // RXD0, RXD1, RX_DV + &pin_GPIO34, &pin_GPIO35, &pin_GPIO49, // TXD0, TXD1, TX_EN + &pin_GPIO50, // REFCLK + &pin_GPIO51); // PHY reset (active low) + common_hal_mii_ethernet_construct(&board_ethernet_obj, &board_rmii_obj); + mii_set_default_instance(&board_ethernet_obj); +} +#endif + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/espressif_esp32p4x_function_ev/mpconfigboard.h b/ports/espressif/boards/espressif_esp32p4x_function_ev/mpconfigboard.h new file mode 100644 index 00000000000..0fb522851b0 --- /dev/null +++ b/ports/espressif/boards/espressif_esp32p4x_function_ev/mpconfigboard.h @@ -0,0 +1,22 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Micropython setup + +#define MICROPY_HW_BOARD_NAME "ESP32-P4X-Function-EV" +#define MICROPY_HW_MCU_NAME "ESP32P4" + +#define CIRCUITPY_BOOT_BUTTON (&pin_GPIO0) + +#define DEFAULT_UART_BUS_RX (&pin_GPIO38) +#define DEFAULT_UART_BUS_TX (&pin_GPIO37) + +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO8) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO7) + +#define CIRCUITPY_USB_HOST_INSTANCE 0 diff --git a/ports/espressif/boards/espressif_esp32p4x_function_ev/mpconfigboard.mk b/ports/espressif/boards/espressif_esp32p4x_function_ev/mpconfigboard.mk new file mode 100644 index 00000000000..1cd76342f06 --- /dev/null +++ b/ports/espressif/boards/espressif_esp32p4x_function_ev/mpconfigboard.mk @@ -0,0 +1,24 @@ +USB_VID = 0x303A +USB_PID = 0x7014 +USB_PRODUCT = "ESP32-P4X-Function-EV" +USB_MANUFACTURER = "Espressif" + +IDF_TARGET = esp32p4 + +CIRCUITPY_USB_DEVICE_INSTANCE = HIGH_SPEED_INSTANCE + +CIRCUITPY_ESP_FLASH_SIZE = 16MB +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m + +CIRCUITPY_ESP_PSRAM_SIZE = 32MB +CIRCUITPY_ESP_PSRAM_MODE = hpi +CIRCUITPY_ESP_PSRAM_FREQ = 200m + +CIRCUITPY_ESP32P4_REV = 3 + +CIRCUITPY_MII = 1 +CIRCUITPY_SSL = 1 + +# mdns on Espressif requires the wifi-based ESP-IDF mdns component +CIRCUITPY_MDNS = 0 diff --git a/ports/espressif/boards/espressif_esp32p4x_function_ev/pins.c b/ports/espressif/boards/espressif_esp32p4x_function_ev/pins.c new file mode 100644 index 00000000000..fe77142d78c --- /dev/null +++ b/ports/espressif/boards/espressif_esp32p4x_function_ev/pins.c @@ -0,0 +1,102 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +#if CIRCUITPY_MII +#include "common-hal/mii/Ethernet.h" + +extern mii_ethernet_obj_t board_ethernet_obj; +extern mii_rmii_obj_t board_rmii_obj; +#endif + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + // Header Block J1 + { MP_ROM_QSTR(MP_QSTR_I2C_SDA), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_IO7), MP_ROM_PTR(&pin_GPIO7) }, + + { MP_ROM_QSTR(MP_QSTR_I2C_SCL), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_IO8), MP_ROM_PTR(&pin_GPIO8) }, + + { MP_ROM_QSTR(MP_QSTR_IO23), MP_ROM_PTR(&pin_GPIO23) }, + + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO37) }, + { MP_ROM_QSTR(MP_QSTR_IO37), MP_ROM_PTR(&pin_GPIO37) }, + + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO38) }, + { MP_ROM_QSTR(MP_QSTR_IO38), MP_ROM_PTR(&pin_GPIO38) }, + + { MP_ROM_QSTR(MP_QSTR_IO21), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_IO22), MP_ROM_PTR(&pin_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_IO20), MP_ROM_PTR(&pin_GPIO20) }, + + { MP_ROM_QSTR(MP_QSTR_C6_WAKEUP), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_IO6), MP_ROM_PTR(&pin_GPIO6) }, + + { MP_ROM_QSTR(MP_QSTR_IO5), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_IO4), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_IO3), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_IO2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_IO36), MP_ROM_PTR(&pin_GPIO36) }, + + { MP_ROM_QSTR(MP_QSTR_IO32), MP_ROM_PTR(&pin_GPIO32) }, + { MP_ROM_QSTR(MP_QSTR_IO24), MP_ROM_PTR(&pin_GPIO24) }, + { MP_ROM_QSTR(MP_QSTR_IO25), MP_ROM_PTR(&pin_GPIO25) }, + + { MP_ROM_QSTR(MP_QSTR_IO33), MP_ROM_PTR(&pin_GPIO33) }, + { MP_ROM_QSTR(MP_QSTR_IO26), MP_ROM_PTR(&pin_GPIO26) }, + + { MP_ROM_QSTR(MP_QSTR_C6_EN), MP_ROM_PTR(&pin_GPIO54) }, + { MP_ROM_QSTR(MP_QSTR_IO54), MP_ROM_PTR(&pin_GPIO54) }, + + { MP_ROM_QSTR(MP_QSTR_IO48), MP_ROM_PTR(&pin_GPIO48) }, + + { MP_ROM_QSTR(MP_QSTR_PA_CTRL), MP_ROM_PTR(&pin_GPIO53) }, + { MP_ROM_QSTR(MP_QSTR_IO53), MP_ROM_PTR(&pin_GPIO53) }, + + { MP_ROM_QSTR(MP_QSTR_IO46), MP_ROM_PTR(&pin_GPIO46) }, + { MP_ROM_QSTR(MP_QSTR_IO47), MP_ROM_PTR(&pin_GPIO47) }, + { MP_ROM_QSTR(MP_QSTR_IO27), MP_ROM_PTR(&pin_GPIO27) }, + + // I2S + { MP_ROM_QSTR(MP_QSTR_I2S_DSDIN), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_I2S_LRCK), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_I2S_ASDOUT), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_I2S_SCLK), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_I2S_MCLK), MP_ROM_PTR(&pin_GPIO13) }, + + // Ethernet + { MP_ROM_QSTR(MP_QSTR_RMII_RXDV), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_RMII_RXD0), MP_ROM_PTR(&pin_GPIO29) }, + { MP_ROM_QSTR(MP_QSTR_RMII_RXD1), MP_ROM_PTR(&pin_GPIO30) }, + { MP_ROM_QSTR(MP_QSTR_MDC), MP_ROM_PTR(&pin_GPIO31) }, + { MP_ROM_QSTR(MP_QSTR_RMII_TXD0), MP_ROM_PTR(&pin_GPIO34) }, + { MP_ROM_QSTR(MP_QSTR_RMII_TXD1), MP_ROM_PTR(&pin_GPIO35) }, + { MP_ROM_QSTR(MP_QSTR_RMII_TXEN), MP_ROM_PTR(&pin_GPIO49) }, + { MP_ROM_QSTR(MP_QSTR_RMII_CLK), MP_ROM_PTR(&pin_GPIO50) }, + { MP_ROM_QSTR(MP_QSTR_PHY_RSTN), MP_ROM_PTR(&pin_GPIO51) }, + { MP_ROM_QSTR(MP_QSTR_MDIO), MP_ROM_PTR(&pin_GPIO52) }, + + // SD Card + { MP_ROM_QSTR(MP_QSTR_SD_DATA0), MP_ROM_PTR(&pin_GPIO39) }, + { MP_ROM_QSTR(MP_QSTR_SD_DATA1), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_SD_DATA2), MP_ROM_PTR(&pin_GPIO41) }, + { MP_ROM_QSTR(MP_QSTR_SD_DATA3), MP_ROM_PTR(&pin_GPIO42) }, + { MP_ROM_QSTR(MP_QSTR_SD_CLK), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_SD_CMD), MP_ROM_PTR(&pin_GPIO44) }, + { MP_ROM_QSTR(MP_QSTR_SD_PWRN), MP_ROM_PTR(&pin_GPIO45) }, + + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, + { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj) }, + + #if CIRCUITPY_MII + { MP_ROM_QSTR(MP_QSTR_ETHERNET), MP_ROM_PTR(&board_ethernet_obj) }, + { MP_ROM_QSTR(MP_QSTR_RMII), MP_ROM_PTR(&board_rmii_obj) }, + #endif +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/espressif/boards/espressif_esp32p4x_function_ev/sdkconfig b/ports/espressif/boards/espressif_esp32p4x_function_ev/sdkconfig new file mode 100644 index 00000000000..3ca4ff5782e --- /dev/null +++ b/ports/espressif/boards/espressif_esp32p4x_function_ev/sdkconfig @@ -0,0 +1,69 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Bootloader config +# +# +# Log +# +CONFIG_BOOTLOADER_LOG_LEVEL_WARN=y +# CONFIG_BOOTLOADER_LOG_LEVEL_INFO is not set +# default: +CONFIG_BOOTLOADER_LOG_LEVEL=2 +# +# Format +# +# CONFIG_BOOTLOADER_LOG_COLORS is not set +# end of Format + +# end of Log + +# end of Bootloader config + +# +# Component config +# +# +# Bluetooth +# +# CONFIG_BT_ENABLED is not set +# end of Bluetooth + +# +# Hardware Settings +# +# +# Chip revision +# +# CONFIG_ESP32P4_REV_MIN_300 is not set +CONFIG_ESP32P4_REV_MIN_301=y +# default: +CONFIG_ESP32P4_REV_MIN_FULL=301 +# default: +CONFIG_ESP_REV_MIN_FULL=301 +# end of Chip revision + +# default: +CONFIG_P4_REV3_MSPI_CRASH_AFTER_POWER_UP_WORKAROUND=y +# default: +CONFIG_P4_REV3_MSPI_WORKAROUND_SIZE=0x100 +# end of Hardware Settings + +# +# ESP-STDIO +# +# CONFIG_ESP_CONSOLE_UART_DEFAULT is not set +CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG=y +# default: +CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG_ENABLED=y +# default: +CONFIG_ESP_CONSOLE_UART_NUM=-1 +# default: +CONFIG_ESP_CONSOLE_ROM_SERIAL_PORT_NUM=6 +# end of ESP-STDIO + +# end of Component config + +# end of Espressif IoT Development Framework Configuration +CONFIG_ETH_USE_ESP32_EMAC=y diff --git a/ports/espressif/boards/espressif_esp32s2_devkitc_1_n4/mpconfigboard.mk b/ports/espressif/boards/espressif_esp32s2_devkitc_1_n4/mpconfigboard.mk index 37f0450490c..271e0fd8d95 100644 --- a/ports/espressif/boards/espressif_esp32s2_devkitc_1_n4/mpconfigboard.mk +++ b/ports/espressif/boards/espressif_esp32s2_devkitc_1_n4/mpconfigboard.mk @@ -8,4 +8,3 @@ IDF_TARGET = esp32s2 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/espressif_esp32s2_devkitc_1_n8r2/mpconfigboard.mk b/ports/espressif/boards/espressif_esp32s2_devkitc_1_n8r2/mpconfigboard.mk index 4475b249b63..45becf7efd8 100644 --- a/ports/espressif/boards/espressif_esp32s2_devkitc_1_n8r2/mpconfigboard.mk +++ b/ports/espressif/boards/espressif_esp32s2_devkitc_1_n8r2/mpconfigboard.mk @@ -12,3 +12,5 @@ CIRCUITPY_ESP_FLASH_SIZE=8MB CIRCUITPY_ESP_PSRAM_SIZE = 2MB CIRCUITPY_ESP_PSRAM_MODE = qio CIRCUITPY_ESP_PSRAM_FREQ = 80m + +CIRCUITPY_MAX3421E = 0 diff --git a/ports/espressif/boards/espressif_esp32s31_korvo_1/board.c b/ports/espressif/boards/espressif_esp32s31_korvo_1/board.c new file mode 100644 index 00000000000..3f5352b5a24 --- /dev/null +++ b/ports/espressif/boards/espressif_esp32s31_korvo_1/board.c @@ -0,0 +1,74 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" +#include "mpconfigboard.h" +#include "common-hal/dotclockframebuffer/DotClockFramebuffer.h" +#include "shared-bindings/dotclockframebuffer/DotClockFramebuffer.h" +#include "shared-bindings/framebufferio/FramebufferDisplay.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-module/displayio/__init__.h" + +// The 4.3 inch 800x480 RGB panel on the LCD connector (ESP32-S3-LCD-EV-Board SUB3, +// ST7262E43). It needs no init commands, only the RGB timing below. + +// LCD data lines DB0-DB15, least significant bit first within each color. +static const mcu_pin_obj_t *blue_pins[] = { + &pin_GPIO8, &pin_GPIO9, &pin_GPIO10, &pin_GPIO11, &pin_GPIO12 +}; +static const mcu_pin_obj_t *green_pins[] = { + &pin_GPIO13, &pin_GPIO14, &pin_GPIO15, &pin_GPIO16, &pin_GPIO17, &pin_GPIO18 +}; +static const mcu_pin_obj_t *red_pins[] = { + &pin_GPIO19, &pin_GPIO33, &pin_GPIO34, &pin_GPIO35, &pin_GPIO36 +}; + +// Display enable on the LCD connector. +#define LCD_DISP_PIN (38) + +void board_init(void) { + config_pin_as_output_with_level(LCD_DISP_PIN, true); + + dotclockframebuffer_framebuffer_obj_t *framebuffer = &allocate_display_bus_or_raise()->dotclock; + framebuffer->base.type = &dotclockframebuffer_framebuffer_type; + + common_hal_dotclockframebuffer_framebuffer_construct( + framebuffer, + /* de */ &pin_GPIO43, + /* vsync */ &pin_GPIO45, + /* hsync */ &pin_GPIO44, + /* dclk */ &pin_GPIO40, + /* data */ red_pins, MP_ARRAY_SIZE(red_pins), green_pins, MP_ARRAY_SIZE(green_pins), blue_pins, MP_ARRAY_SIZE(blue_pins), + /* frequency */ 18000000, + /* width x height */ 800, 480, + /* horizontal: pulse, back & front porch, idle */ 40, 40, 48, false, + /* vertical: pulse, back & front porch, idle */ 23, 32, 13, false, + /* de_idle_high */ false, + /* pclk_active_high */ false, + /* pclk_idle_high */ false, + /* overscan_left */ 0 + ); + + framebufferio_framebufferdisplay_obj_t *display = &allocate_display_or_raise()->framebuffer_display; + display->base.type = &framebufferio_framebufferdisplay_type; + common_hal_framebufferio_framebufferdisplay_construct( + display, + framebuffer, + 0, + true + ); +} + +bool espressif_board_reset_pin_number(gpio_num_t pin_number) { + // Keep the display enabled across resets. + if (pin_number == LCD_DISP_PIN) { + config_pin_as_output_with_level(pin_number, true); + return true; + } + return false; +} + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/espressif_esp32s31_korvo_1/mpconfigboard.h b/ports/espressif/boards/espressif_esp32s31_korvo_1/mpconfigboard.h new file mode 100644 index 00000000000..6122b58da95 --- /dev/null +++ b/ports/espressif/boards/espressif_esp32s31_korvo_1/mpconfigboard.h @@ -0,0 +1,21 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Micropython setup + +#define MICROPY_HW_BOARD_NAME "ESP32-S31-Korvo-1" +#define MICROPY_HW_MCU_NAME "ESP32S31" + +// UART0 is wired to the onboard CP2102N USB-serial converter. +#define CIRCUITPY_CONSOLE_UART_TX (&pin_GPIO58) +#define CIRCUITPY_CONSOLE_UART_RX (&pin_GPIO59) + +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO1) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO0) + +#define CIRCUITPY_USB_HOST_INSTANCE 0 diff --git a/ports/espressif/boards/espressif_esp32s31_korvo_1/mpconfigboard.mk b/ports/espressif/boards/espressif_esp32s31_korvo_1/mpconfigboard.mk new file mode 100644 index 00000000000..942154942d8 --- /dev/null +++ b/ports/espressif/boards/espressif_esp32s31_korvo_1/mpconfigboard.mk @@ -0,0 +1,19 @@ +CIRCUITPY_CREATOR_ID = 0x000C303A +CIRCUITPY_CREATION_ID = 0x00531001 + +IDF_TARGET = esp32s31 + +CIRCUITPY_ESP_FLASH_SIZE = 16MB +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m + +CIRCUITPY_ESP_PSRAM_SIZE = 16MB +CIRCUITPY_ESP_PSRAM_MODE = opi +CIRCUITPY_ESP_PSRAM_FREQ = 200m + +# The chip's only USB port goes to a USB-A host jack. +CIRCUITPY_USB_DEVICE = 0 +CIRCUITPY_USB_HOST = 1 + +# 4.3 inch 800x480 RGB panel on the LCD connector +CIRCUITPY_DOTCLOCKFRAMEBUFFER = 1 diff --git a/ports/espressif/boards/espressif_esp32s31_korvo_1/pins.c b/ports/espressif/boards/espressif_esp32s31_korvo_1/pins.c new file mode 100644 index 00000000000..fc881013c44 --- /dev/null +++ b/ports/espressif/boards/espressif_esp32s31_korvo_1/pins.c @@ -0,0 +1,31 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" +#include "shared-module/displayio/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, + + { MP_ROM_QSTR(MP_QSTR_BOOT), MP_ROM_PTR(&pin_GPIO61) }, + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO37) }, + + // UART0, wired to the onboard CP2102N. + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO58) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO59) }, + + // USB-A host jack. + { MP_ROM_QSTR(MP_QSTR_USB_HOST_DATA_PLUS), MP_ROM_PTR(&pin_USB_HS_DP) }, + { MP_ROM_QSTR(MP_QSTR_USB_HOST_DATA_MINUS), MP_ROM_PTR(&pin_USB_HS_DM) }, + + // 800x480 RGB panel on the LCD connector. + { 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/tests/feature_check/bytearray.py.exp b/ports/espressif/boards/espressif_esp32s31_korvo_1/sdkconfig similarity index 100% rename from tests/feature_check/bytearray.py.exp rename to ports/espressif/boards/espressif_esp32s31_korvo_1/sdkconfig diff --git a/ports/espressif/boards/espressif_esp32s3_box/board.c b/ports/espressif/boards/espressif_esp32s3_box/board.c index 54edb47bac3..86ba94e67b9 100644 --- a/ports/espressif/boards/espressif_esp32s3_box/board.c +++ b/ports/espressif/boards/espressif_esp32s3_box/board.c @@ -26,14 +26,13 @@ void board_init(void) { fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_GPIO7, &pin_GPIO6, NULL, false); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_GPIO4, // TFT_DC Command or data - &pin_GPIO5, // TFT_CS Chip select - &pin_GPIO48, // TFT_RST Reset + MP_OBJ_FROM_PTR(&pin_GPIO4), // TFT_DC Command or data + MP_OBJ_FROM_PTR(&pin_GPIO5), // TFT_CS Chip select + MP_OBJ_FROM_PTR(&pin_GPIO48), // TFT_RST Reset 60000000, // Baudrate 0, // Polarity 0); // Phase diff --git a/ports/espressif/boards/espressif_esp32s3_box/mpconfigboard.mk b/ports/espressif/boards/espressif_esp32s3_box/mpconfigboard.mk index 765f9968a99..6c117b1f67e 100644 --- a/ports/espressif/boards/espressif_esp32s3_box/mpconfigboard.mk +++ b/ports/espressif/boards/espressif_esp32s3_box/mpconfigboard.mk @@ -12,5 +12,3 @@ CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_PSRAM_SIZE = 8MB CIRCUITPY_ESP_PSRAM_MODE = opi CIRCUITPY_ESP_PSRAM_FREQ = 80m - -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/espressif_esp32s3_box_3/board.c b/ports/espressif/boards/espressif_esp32s3_box_3/board.c new file mode 100644 index 00000000000..73dce39f294 --- /dev/null +++ b/ports/espressif/boards/espressif_esp32s3_box_3/board.c @@ -0,0 +1,95 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// SPDX-FileCopyrightText: Copyright (c) 2026 Moises Trovo +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" +#include "mpconfigboard.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "common-hal/microcontroller/Pin.h" +#include "py/mphal.h" +#include "driver/gpio.h" + +#include "shared-bindings/busio/SPI.h" +#include "shared-bindings/fourwire/FourWire.h" +#include "shared-module/displayio/__init__.h" +#include "shared-module/displayio/mipi_constants.h" + +// esp-bsp bsp/esp-box-3/esp-box-3.c vendor_specific_init[], with SWRESET +// prepended and MADCTL set to 0xC8 for CircuitPython's landscape orientation. +// The BSP's own 0x08 is portrait; it also calls +// esp_lcd_panel_mirror(panel, true, true), which CircuitPython folds into +// MADCTL. If the image is ever mirrored or rotated, 0x36 is the knob. +uint8_t display_init_sequence[] = { + 0x01, 0x80, 0x96, // SWRESET, delay 150ms + 0xC8, 0x03, 0xFF, 0x93, 0x42, // vendor unlock + 0xC0, 0x02, 0x0E, 0x0E, // power control + 0xC5, 0x01, 0xD0, // VCOM + 0xC1, 0x01, 0x02, + 0xB4, 0x01, 0x02, + 0xE0, 0x0F, 0x00, 0x03, 0x08, 0x06, 0x13, 0x09, 0x39, 0x39, 0x48, 0x02, 0x0A, 0x08, 0x17, 0x17, 0x0F, // positive gamma + 0xE1, 0x0F, 0x00, 0x28, 0x29, 0x01, 0x0D, 0x03, 0x3F, 0x33, 0x52, 0x04, 0x0F, 0x0E, 0x37, 0x38, 0x0F, // negative gamma + 0xB1, 0x02, 0x00, 0x1B, + 0x36, 0x01, 0xC8, // MADCTL: landscape, BGR + 0x3A, 0x01, 0x55, // COLMOD: 16bpp + 0xB7, 0x01, 0x06, + 0x11, 0x80, 0x78, // SLPOUT, delay 120ms + 0x29, 0x80, 0x78, // DISPON, delay 120ms +}; + +void board_init(void) { + // The panel reset (GPIO48, shared with the touch controller) is ACTIVE + // HIGH. FourWire assumes active low and leaves the pin high, which holds + // this panel in reset forever with no error. So assert it here, release + // it low, and hand FourWire reset = None. + config_pin_as_output_with_level(GPIO_NUM_48, true); + mp_hal_delay_ms(10); + config_pin_as_output_with_level(GPIO_NUM_48, false); + mp_hal_delay_ms(120); + + fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; + busio_spi_obj_t *spi = &bus->inline_bus; + common_hal_busio_spi_construct(spi, &pin_GPIO7, &pin_GPIO6, NULL, false); + + bus->base.type = &fourwire_fourwire_type; + common_hal_fourwire_fourwire_construct(bus, + spi, + MP_OBJ_FROM_PTR(&pin_GPIO4), // LCD_DC + MP_OBJ_FROM_PTR(&pin_GPIO5), // LCD_CS + mp_const_none, // reset managed above, opposite polarity + 40000000, // Baudrate. BSP uses 40MHz; 24MHz is the fallback. + 0, // Polarity + 0); // Phase + + busdisplay_busdisplay_obj_t *display = &allocate_display()->display; + display->base.type = &busdisplay_busdisplay_type; + common_hal_busdisplay_busdisplay_construct(display, + bus, + 320, // Width + 240, // Height + 0, // column start + 0, // row start + 0, // 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 + display_init_sequence, + sizeof(display_init_sequence), + &pin_GPIO47, // backlight pin + NO_BRIGHTNESS_COMMAND, + 1.0f, // brightness + false, // single_byte_bounds + false, // data_as_commands + true, // auto_refresh + 60, // native_frames_per_second + true, // backlight_on_high + false, // SH1107_addressing + 50000); // backlight pwm frequency +} + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/espressif_esp32s3_box_3/mpconfigboard.h b/ports/espressif/boards/espressif_esp32s3_box_3/mpconfigboard.h new file mode 100644 index 00000000000..9ded82db172 --- /dev/null +++ b/ports/espressif/boards/espressif_esp32s3_box_3/mpconfigboard.h @@ -0,0 +1,10 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// SPDX-FileCopyrightText: Copyright (c) 2026 Moises Trovo +// SPDX-License-Identifier: MIT + +#pragma once + +// Micropython setup + +#define MICROPY_HW_BOARD_NAME "ESP32-S3-Box-3" +#define MICROPY_HW_MCU_NAME "ESP32S3" diff --git a/ports/espressif/boards/espressif_esp32s3_box_3/mpconfigboard.mk b/ports/espressif/boards/espressif_esp32s3_box_3/mpconfigboard.mk new file mode 100644 index 00000000000..dbbee619732 --- /dev/null +++ b/ports/espressif/boards/espressif_esp32s3_box_3/mpconfigboard.mk @@ -0,0 +1,14 @@ +USB_VID = 0x303A +USB_PID = 0x7015 +USB_PRODUCT = "ESP32-S3-Box-3" +USB_MANUFACTURER = "Espressif" + +IDF_TARGET = esp32s3 + +CIRCUITPY_ESP_FLASH_SIZE = 16MB +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m + +CIRCUITPY_ESP_PSRAM_SIZE = 16MB +CIRCUITPY_ESP_PSRAM_MODE = opi +CIRCUITPY_ESP_PSRAM_FREQ = 80m diff --git a/ports/espressif/boards/espressif_esp32s3_box_3/pins.c b/ports/espressif/boards/espressif_esp32s3_box_3/pins.c new file mode 100644 index 00000000000..ce1230f17d5 --- /dev/null +++ b/ports/espressif/boards/espressif_esp32s3_box_3/pins.c @@ -0,0 +1,61 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// SPDX-FileCopyrightText: Copyright (c) 2026 Moises Trovo +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" +#include "shared-module/displayio/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + // PMOD connector 1 (dock). IO2/IO6 are the USB D+/D- pair (GPIO20/GPIO19) + // and are not aliased. + { MP_ROM_QSTR(MP_QSTR_G42), MP_ROM_PTR(&pin_GPIO42) }, + { MP_ROM_QSTR(MP_QSTR_G39), MP_ROM_PTR(&pin_GPIO39) }, + { MP_ROM_QSTR(MP_QSTR_G40), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_G21), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_G38), MP_ROM_PTR(&pin_GPIO38) }, + { MP_ROM_QSTR(MP_QSTR_G41), MP_ROM_PTR(&pin_GPIO41) }, + + // PMOD connector 2 (dock) + { MP_ROM_QSTR(MP_QSTR_G13), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_G9), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_G12), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_G44), MP_ROM_PTR(&pin_GPIO44) }, + { MP_ROM_QSTR(MP_QSTR_G10), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_G14), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_G11), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_G43), MP_ROM_PTR(&pin_GPIO43) }, + + // LCD & touch + { MP_ROM_QSTR(MP_QSTR_LCD_DC), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_LCD_CS), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_LCD_MOSI), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_LCD_SCK), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_LCD_RST), MP_ROM_PTR(&pin_GPIO48) }, + { MP_ROM_QSTR(MP_QSTR_LCD_BACKLIGHT), MP_ROM_PTR(&pin_GPIO47) }, + { MP_ROM_QSTR(MP_QSTR_CTP_INT), MP_ROM_PTR(&pin_GPIO3) }, + + // Audio + { MP_ROM_QSTR(MP_QSTR_I2S_MCLK), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_I2S_SCLK), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_I2S_LRCK), MP_ROM_PTR(&pin_GPIO45) }, + { MP_ROM_QSTR(MP_QSTR_I2S_CODEC_DSDIN), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_I2S_ADC_SDOUT), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_PA_CTRL), MP_ROM_PTR(&pin_GPIO46) }, + { MP_ROM_QSTR(MP_QSTR_MUTE_STATUS), MP_ROM_PTR(&pin_GPIO1) }, + + // Internal I2C bus (codec, touch, IMU, AHT30) + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO18) }, + + // Dock I2C bus + { MP_ROM_QSTR(MP_QSTR_SCL2), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_SDA2), MP_ROM_PTR(&pin_GPIO41) }, + + // Boot button, also usable as a software button + { MP_ROM_QSTR(MP_QSTR_BOOT), MP_ROM_PTR(&pin_GPIO0) }, + + { 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/espressif/boards/espressif_esp32s3_box_3/sdkconfig b/ports/espressif/boards/espressif_esp32s3_box_3/sdkconfig new file mode 100644 index 00000000000..e9628662160 --- /dev/null +++ b/ports/espressif/boards/espressif_esp32s3_box_3/sdkconfig @@ -0,0 +1,14 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Component config +# +# +# LWIP +# +# end of LWIP + +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/boards/espressif_esp32s3_box_lite/board.c b/ports/espressif/boards/espressif_esp32s3_box_lite/board.c index e675c0f915b..0a732220337 100644 --- a/ports/espressif/boards/espressif_esp32s3_box_lite/board.c +++ b/ports/espressif/boards/espressif_esp32s3_box_lite/board.c @@ -27,14 +27,13 @@ void board_init(void) { fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_GPIO7, &pin_GPIO6, NULL, false); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_GPIO4, // TFT_DC Command or data - &pin_GPIO5, // TFT_CS Chip select - &pin_GPIO48, // TFT_RST Reset + MP_OBJ_FROM_PTR(&pin_GPIO4), // TFT_DC Command or data + MP_OBJ_FROM_PTR(&pin_GPIO5), // TFT_CS Chip select + MP_OBJ_FROM_PTR(&pin_GPIO48), // TFT_RST Reset 60000000, // Baudrate 0, // Polarity 0); // Phase diff --git a/ports/espressif/boards/espressif_esp32s3_box_lite/mpconfigboard.mk b/ports/espressif/boards/espressif_esp32s3_box_lite/mpconfigboard.mk index fe83e2e34dd..e54f55fd642 100644 --- a/ports/espressif/boards/espressif_esp32s3_box_lite/mpconfigboard.mk +++ b/ports/espressif/boards/espressif_esp32s3_box_lite/mpconfigboard.mk @@ -12,5 +12,3 @@ CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_PSRAM_SIZE = 8MB CIRCUITPY_ESP_PSRAM_MODE = opi CIRCUITPY_ESP_PSRAM_FREQ = 80m - -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/espressif_esp32s3_devkitc_1_n16/mpconfigboard.mk b/ports/espressif/boards/espressif_esp32s3_devkitc_1_n16/mpconfigboard.mk index 0a7925420f7..d182a144992 100644 --- a/ports/espressif/boards/espressif_esp32s3_devkitc_1_n16/mpconfigboard.mk +++ b/ports/espressif/boards/espressif_esp32s3_devkitc_1_n16/mpconfigboard.mk @@ -8,4 +8,3 @@ IDF_TARGET = esp32s3 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 16MB -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/espressif_esp32s3_devkitc_1_n32r16/board.c b/ports/espressif/boards/espressif_esp32s3_devkitc_1_n32r16/board.c new file mode 100644 index 00000000000..a3a9eec0471 --- /dev/null +++ b/ports/espressif/boards/espressif_esp32s3_devkitc_1_n32r16/board.c @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/espressif_esp32s3_devkitc_1_n32r16/mpconfigboard.h b/ports/espressif/boards/espressif_esp32s3_devkitc_1_n32r16/mpconfigboard.h new file mode 100644 index 00000000000..9df0ebcdb40 --- /dev/null +++ b/ports/espressif/boards/espressif_esp32s3_devkitc_1_n32r16/mpconfigboard.h @@ -0,0 +1,21 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Micropython setup + +#define MICROPY_HW_BOARD_NAME "ESP32-S3-DevKitC-1-N32R16" +#define MICROPY_HW_MCU_NAME "ESP32S3" + +#define MICROPY_HW_NEOPIXEL (&pin_GPIO38) + +#define CIRCUITPY_BOOT_BUTTON (&pin_GPIO0) + +#define DEFAULT_UART_BUS_RX (&pin_GPIO44) +#define DEFAULT_UART_BUS_TX (&pin_GPIO43) + +#define AUTORESET_DELAY_MS 500 diff --git a/ports/espressif/boards/espressif_esp32s3_devkitc_1_n32r16/mpconfigboard.mk b/ports/espressif/boards/espressif_esp32s3_devkitc_1_n32r16/mpconfigboard.mk new file mode 100644 index 00000000000..15fcf8697fc --- /dev/null +++ b/ports/espressif/boards/espressif_esp32s3_devkitc_1_n32r16/mpconfigboard.mk @@ -0,0 +1,14 @@ +USB_VID = 0x303A +USB_PID = 0x7003 +USB_PRODUCT = "ESP32-S3-DevKitC-1-N32R16" +USB_MANUFACTURER = "Espressif" + +IDF_TARGET = esp32s3 + +CIRCUITPY_ESP_FLASH_SIZE = 32MB +CIRCUITPY_ESP_FLASH_MODE = opi +CIRCUITPY_ESP_FLASH_FREQ = 80m + +CIRCUITPY_ESP_PSRAM_SIZE = 16MB +CIRCUITPY_ESP_PSRAM_MODE = opi +CIRCUITPY_ESP_PSRAM_FREQ = 80m diff --git a/ports/espressif/boards/espressif_esp32s3_devkitc_1_n32r16/pins.c b/ports/espressif/boards/espressif_esp32s3_devkitc_1_n32r16/pins.c new file mode 100644 index 00000000000..e77a3813e94 --- /dev/null +++ b/ports/espressif/boards/espressif_esp32s3_devkitc_1_n32r16/pins.c @@ -0,0 +1,55 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { 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_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_IO43), MP_ROM_PTR(&pin_GPIO43) }, + { 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_IO47), MP_ROM_PTR(&pin_GPIO47) }, + { MP_ROM_QSTR(MP_QSTR_IO48), MP_ROM_PTR(&pin_GPIO48) }, + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO38) }, + + { 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_UART), MP_ROM_PTR(&board_uart_obj) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/espressif/boards/espressif_esp32s3_devkitc_1_n32r16/sdkconfig b/ports/espressif/boards/espressif_esp32s3_devkitc_1_n32r16/sdkconfig new file mode 100644 index 00000000000..e9628662160 --- /dev/null +++ b/ports/espressif/boards/espressif_esp32s3_devkitc_1_n32r16/sdkconfig @@ -0,0 +1,14 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Component config +# +# +# LWIP +# +# end of LWIP + +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/boards/espressif_esp32s3_devkitc_1_n32r8_v1_1/board.c b/ports/espressif/boards/espressif_esp32s3_devkitc_1_n32r8_v1_1/board.c new file mode 100644 index 00000000000..a3a9eec0471 --- /dev/null +++ b/ports/espressif/boards/espressif_esp32s3_devkitc_1_n32r8_v1_1/board.c @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/espressif_esp32s3_devkitc_1_n32r8_v1_1/mpconfigboard.h b/ports/espressif/boards/espressif_esp32s3_devkitc_1_n32r8_v1_1/mpconfigboard.h new file mode 100644 index 00000000000..363a3baeafe --- /dev/null +++ b/ports/espressif/boards/espressif_esp32s3_devkitc_1_n32r8_v1_1/mpconfigboard.h @@ -0,0 +1,21 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Micropython setup + +#define MICROPY_HW_BOARD_NAME "ESP32-S3-DevKitC-1-N32R8 v1.1" +#define MICROPY_HW_MCU_NAME "ESP32S3" + +#define MICROPY_HW_NEOPIXEL (&pin_GPIO38) + +#define CIRCUITPY_BOOT_BUTTON (&pin_GPIO0) + +#define DEFAULT_UART_BUS_RX (&pin_GPIO44) +#define DEFAULT_UART_BUS_TX (&pin_GPIO43) + +#define AUTORESET_DELAY_MS 500 diff --git a/ports/espressif/boards/espressif_esp32s3_devkitc_1_n32r8_v1_1/mpconfigboard.mk b/ports/espressif/boards/espressif_esp32s3_devkitc_1_n32r8_v1_1/mpconfigboard.mk new file mode 100644 index 00000000000..af74f6a407f --- /dev/null +++ b/ports/espressif/boards/espressif_esp32s3_devkitc_1_n32r8_v1_1/mpconfigboard.mk @@ -0,0 +1,14 @@ +USB_VID = 0x303A +USB_PID = 0x7003 +USB_PRODUCT = "ESP32-S3-DevKitC-1-N32R8 v1.1" +USB_MANUFACTURER = "Espressif" + +IDF_TARGET = esp32s3 + +CIRCUITPY_ESP_FLASH_SIZE = 32MB +CIRCUITPY_ESP_FLASH_MODE = opi +CIRCUITPY_ESP_FLASH_FREQ = 80m + +CIRCUITPY_ESP_PSRAM_SIZE = 8MB +CIRCUITPY_ESP_PSRAM_MODE = opi +CIRCUITPY_ESP_PSRAM_FREQ = 80m diff --git a/ports/espressif/boards/espressif_esp32s3_devkitc_1_n32r8_v1_1/pins.c b/ports/espressif/boards/espressif_esp32s3_devkitc_1_n32r8_v1_1/pins.c new file mode 100644 index 00000000000..e77a3813e94 --- /dev/null +++ b/ports/espressif/boards/espressif_esp32s3_devkitc_1_n32r8_v1_1/pins.c @@ -0,0 +1,55 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { 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_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_IO43), MP_ROM_PTR(&pin_GPIO43) }, + { 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_IO47), MP_ROM_PTR(&pin_GPIO47) }, + { MP_ROM_QSTR(MP_QSTR_IO48), MP_ROM_PTR(&pin_GPIO48) }, + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO38) }, + + { 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_UART), MP_ROM_PTR(&board_uart_obj) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/espressif/boards/espressif_esp32s3_devkitc_1_n32r8_v1_1/sdkconfig b/ports/espressif/boards/espressif_esp32s3_devkitc_1_n32r8_v1_1/sdkconfig new file mode 100644 index 00000000000..e9628662160 --- /dev/null +++ b/ports/espressif/boards/espressif_esp32s3_devkitc_1_n32r8_v1_1/sdkconfig @@ -0,0 +1,14 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Component config +# +# +# LWIP +# +# end of LWIP + +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/boards/espressif_esp32s3_devkitc_1_n8/mpconfigboard.mk b/ports/espressif/boards/espressif_esp32s3_devkitc_1_n8/mpconfigboard.mk index bd2cd4c0a33..ea5597d3702 100644 --- a/ports/espressif/boards/espressif_esp32s3_devkitc_1_n8/mpconfigboard.mk +++ b/ports/espressif/boards/espressif_esp32s3_devkitc_1_n8/mpconfigboard.mk @@ -8,4 +8,3 @@ IDF_TARGET = esp32s3 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 8MB -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/espressif_esp32s3_devkitc_1_n8r2_ros/board.c b/ports/espressif/boards/espressif_esp32s3_devkitc_1_n8r2_ros/board.c new file mode 100644 index 00000000000..a3a9eec0471 --- /dev/null +++ b/ports/espressif/boards/espressif_esp32s3_devkitc_1_n8r2_ros/board.c @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/espressif_esp32s3_devkitc_1_n8r2_ros/mpconfigboard.h b/ports/espressif/boards/espressif_esp32s3_devkitc_1_n8r2_ros/mpconfigboard.h new file mode 100644 index 00000000000..02fe72fe4a7 --- /dev/null +++ b/ports/espressif/boards/espressif_esp32s3_devkitc_1_n8r2_ros/mpconfigboard.h @@ -0,0 +1,16 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Micropython setup +#define MICROPY_HW_BOARD_NAME "ESP32-S3-DevKitC-1-N8R2 (ROS version)" +#define MICROPY_HW_MCU_NAME "ESP32S3" + +#define MICROPY_HW_NEOPIXEL (&pin_GPIO48) + +#define DEFAULT_UART_BUS_RX (&pin_GPIO44) +#define DEFAULT_UART_BUS_TX (&pin_GPIO43) diff --git a/ports/espressif/boards/espressif_esp32s3_devkitc_1_n8r2_ros/mpconfigboard.mk b/ports/espressif/boards/espressif_esp32s3_devkitc_1_n8r2_ros/mpconfigboard.mk new file mode 100644 index 00000000000..b6ae3cf73b4 --- /dev/null +++ b/ports/espressif/boards/espressif_esp32s3_devkitc_1_n8r2_ros/mpconfigboard.mk @@ -0,0 +1,16 @@ +USB_VID = 0x303A +USB_PID = 0x7003 +USB_PRODUCT = "ESP32-S3-DevKitC-1-N8R2 CPY/ROS" +USB_MANUFACTURER = "Espressif" + +IDF_TARGET = esp32s3 + +CIRCUITPY_ESP_FLASH_SIZE = 8MB +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m + +CIRCUITPY_ESP_PSRAM_SIZE = 2MB +CIRCUITPY_ESP_PSRAM_MODE = qio +CIRCUITPY_ESP_PSRAM_FREQ = 80m + +CIRCUITPY_RCLCPY = 0 diff --git a/ports/espressif/boards/espressif_esp32s3_devkitc_1_n8r2_ros/pins.c b/ports/espressif/boards/espressif_esp32s3_devkitc_1_n8r2_ros/pins.c new file mode 100644 index 00000000000..3bb64f434d0 --- /dev/null +++ b/ports/espressif/boards/espressif_esp32s3_devkitc_1_n8r2_ros/pins.c @@ -0,0 +1,55 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { 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_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_IO43), MP_ROM_PTR(&pin_GPIO43) }, + { 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_IO47), MP_ROM_PTR(&pin_GPIO47) }, + { MP_ROM_QSTR(MP_QSTR_IO48), MP_ROM_PTR(&pin_GPIO48) }, + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO48) }, + + { 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_UART), MP_ROM_PTR(&board_uart_obj) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/espressif/boards/espressif_esp32s3_devkitc_1_n8r2_ros/sdkconfig b/ports/espressif/boards/espressif_esp32s3_devkitc_1_n8r2_ros/sdkconfig new file mode 100644 index 00000000000..e9628662160 --- /dev/null +++ b/ports/espressif/boards/espressif_esp32s3_devkitc_1_n8r2_ros/sdkconfig @@ -0,0 +1,14 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Component config +# +# +# LWIP +# +# end of LWIP + +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/boards/espressif_esp32s3_devkitc_1_n8r8_hacktablet/board.c b/ports/espressif/boards/espressif_esp32s3_devkitc_1_n8r8_hacktablet/board.c index f8435df23f7..3fe525eb712 100644 --- a/ports/espressif/boards/espressif_esp32s3_devkitc_1_n8r8_hacktablet/board.c +++ b/ports/espressif/boards/espressif_esp32s3_devkitc_1_n8r8_hacktablet/board.c @@ -41,7 +41,6 @@ static void display_init(void) { // Turn on backlight // gpio_set_direction(2, GPIO_MODE_DEF_OUTPUT); // gpio_set_level(2, true); - common_hal_never_reset_pin(&pin_GPIO39); dotclockframebuffer_framebuffer_obj_t *framebuffer = &allocate_display_bus_or_raise()->dotclock; framebuffer->base.type = &dotclockframebuffer_framebuffer_type; diff --git a/ports/espressif/boards/espressif_esp32s3_devkitm_1_n8/mpconfigboard.mk b/ports/espressif/boards/espressif_esp32s3_devkitm_1_n8/mpconfigboard.mk index fdbd686e090..5a410afaa06 100644 --- a/ports/espressif/boards/espressif_esp32s3_devkitm_1_n8/mpconfigboard.mk +++ b/ports/espressif/boards/espressif_esp32s3_devkitm_1_n8/mpconfigboard.mk @@ -8,4 +8,3 @@ IDF_TARGET = esp32s3 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 8MB -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/espressif_esp32s3_eye/board.c b/ports/espressif/boards/espressif_esp32s3_eye/board.c index c48c9428cf4..43445b034e4 100644 --- a/ports/espressif/boards/espressif_esp32s3_eye/board.c +++ b/ports/espressif/boards/espressif_esp32s3_eye/board.c @@ -56,9 +56,9 @@ void board_init(void) { common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO43, // DC - &pin_GPIO44, // CS - NULL, // no reset pin + MP_OBJ_FROM_PTR(&pin_GPIO43), // DC + MP_OBJ_FROM_PTR(&pin_GPIO44), // CS + mp_const_none, // no reset pin 40000000, // baudrate 0, // polarity 0 // phase diff --git a/ports/espressif/boards/espressif_esp32s3_usb_otg_n8/board.c b/ports/espressif/boards/espressif_esp32s3_usb_otg_n8/board.c index 94d08bb56c8..3604c806735 100644 --- a/ports/espressif/boards/espressif_esp32s3_usb_otg_n8/board.c +++ b/ports/espressif/boards/espressif_esp32s3_usb_otg_n8/board.c @@ -7,6 +7,7 @@ #include "supervisor/board.h" #include "mpconfigboard.h" #include "shared-bindings/microcontroller/Pin.h" +#include "driver/gpio.h" #include "shared-bindings/busio/SPI.h" #include "shared-bindings/fourwire/FourWire.h" @@ -51,17 +52,28 @@ uint8_t display_init_sequence[] = { }; void board_init(void) { + // Default these pins to pulled down: + // GPIO13 BOOST_EN boost converter off + // GPIO15 LED_GREEN LED off + // GPIO16 LED_YELLOW LED off + // GPIO18 USB_SEL low + static const gpio_num_t pins_to_reset[] = { + 13, 15, 16, 18, + }; + for (size_t i = 0; i < MP_ARRAY_SIZE(pins_to_reset); i++) { + espressif_board_reset_pin_number(pins_to_reset[i]); + } + fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_GPIO6, &pin_GPIO7, NULL, false); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_GPIO4, // TFT_DC Command or data - &pin_GPIO5, // TFT_CS Chip select - &pin_GPIO8, // TFT_RST Reset + MP_OBJ_FROM_PTR(&pin_GPIO4), // TFT_DC Command or data + MP_OBJ_FROM_PTR(&pin_GPIO5), // TFT_CS Chip select + MP_OBJ_FROM_PTR(&pin_GPIO8), // TFT_RST Reset 60000000, // Baudrate 0, // Polarity 0); // Phase diff --git a/ports/espressif/boards/espressif_esp32s3_usb_otg_n8/mpconfigboard.mk b/ports/espressif/boards/espressif_esp32s3_usb_otg_n8/mpconfigboard.mk index 947b689fafe..b0abc221418 100644 --- a/ports/espressif/boards/espressif_esp32s3_usb_otg_n8/mpconfigboard.mk +++ b/ports/espressif/boards/espressif_esp32s3_usb_otg_n8/mpconfigboard.mk @@ -8,4 +8,3 @@ IDF_TARGET = esp32s3 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 8MB -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/espressif_esp8684_devkitc_02_n4/mpconfigboard.mk b/ports/espressif/boards/espressif_esp8684_devkitc_02_n4/mpconfigboard.mk index 0925e8de64d..3631493c267 100644 --- a/ports/espressif/boards/espressif_esp8684_devkitc_02_n4/mpconfigboard.mk +++ b/ports/espressif/boards/espressif_esp8684_devkitc_02_n4/mpconfigboard.mk @@ -6,3 +6,6 @@ IDF_TARGET = esp32c2 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 60m CIRCUITPY_ESP_FLASH_SIZE = 4MB + +# Board was originally defined with a 2MB firmware, almost 2MB user filesystem. Leave it that way. +CIRCUITPY_4MB_FLASH_LARGE_USER_FS_LAYOUT = 1 diff --git a/ports/espressif/boards/espressif_hmi_devkit_1/board.c b/ports/espressif/boards/espressif_hmi_devkit_1/board.c index ec73bf118fc..a3a9eec0471 100644 --- a/ports/espressif/boards/espressif_hmi_devkit_1/board.c +++ b/ports/espressif/boards/espressif_hmi_devkit_1/board.c @@ -5,13 +5,5 @@ // SPDX-License-Identifier: MIT #include "supervisor/board.h" -#include "mpconfigboard.h" -#include "shared-bindings/microcontroller/Pin.h" - -void board_init(void) { - // Debug UART - common_hal_never_reset_pin(&pin_GPIO43); - common_hal_never_reset_pin(&pin_GPIO44); -} // Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/espressif_saola_1_wroom/mpconfigboard.mk b/ports/espressif/boards/espressif_saola_1_wroom/mpconfigboard.mk index d00bf432c97..cb766aa2312 100644 --- a/ports/espressif/boards/espressif_saola_1_wroom/mpconfigboard.mk +++ b/ports/espressif/boards/espressif_saola_1_wroom/mpconfigboard.mk @@ -8,4 +8,3 @@ IDF_TARGET = esp32s2 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/franzininho_wifi_wroom/mpconfigboard.mk b/ports/espressif/boards/franzininho_wifi_wroom/mpconfigboard.mk index 1cc62cb69d4..7b4f1e9d1d2 100644 --- a/ports/espressif/boards/franzininho_wifi_wroom/mpconfigboard.mk +++ b/ports/espressif/boards/franzininho_wifi_wroom/mpconfigboard.mk @@ -8,4 +8,3 @@ IDF_TARGET = esp32s2 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/freenove_esp32_display_3_5/board.c b/ports/espressif/boards/freenove_esp32_display_3_5/board.c new file mode 100644 index 00000000000..aa14c059a80 --- /dev/null +++ b/ports/espressif/boards/freenove_esp32_display_3_5/board.c @@ -0,0 +1,95 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Brian Nelson +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" +#include "mpconfigboard.h" + +#include "shared-bindings/busio/SPI.h" +#include "shared-bindings/fourwire/FourWire.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-module/displayio/__init__.h" +#include "shared-module/displayio/mipi_constants.h" +#include "supervisor/shared/settings.h" + +// ST7796 init sequence from Freenove's TFT_eSPI setup, landscape (MADCTL MV | BGR) +static uint8_t display_init_sequence[] = { + 0x01, 0x80, 0x78, // Software reset, delay 120 ms + 0x11, 0x80, 0x78, // Sleep out, delay 120 ms + 0xF0, 0x01, 0xC3, // Enable extension command 2 part I + 0xF0, 0x01, 0x96, // Enable extension command 2 part II + 0x36, 0x01, 0x28, // Memory data access control: row/column exchange, BGR + 0x3A, 0x01, 0x55, // 16 bits per pixel + 0xB4, 0x01, 0x01, // 1-dot inversion + 0xB6, 0x03, 0x80, 0x02, 0x3B, // Display function control + 0xE8, 0x08, 0x40, 0x8A, 0x00, 0x00, 0x29, 0x19, 0xA5, 0x33, // Display output control adjust + 0xC1, 0x01, 0x06, // Power control 2 + 0xC2, 0x01, 0xA7, // Power control 3 + 0xC5, 0x81, 0x18, 0x78, // VCOM control, delay 120 ms + 0xE0, 0x0E, 0xF0, 0x09, 0x0B, 0x06, 0x04, 0x15, 0x2F, 0x54, 0x42, 0x3C, 0x17, 0x14, 0x18, 0x1B, // Positive gamma + 0xE1, 0x8E, 0xE0, 0x09, 0x0B, 0x06, 0x04, 0x03, 0x2B, 0x43, 0x42, 0x3B, 0x16, 0x14, 0x17, 0x1B, 0x78, // Negative gamma, delay 120 ms + 0xF0, 0x01, 0x3C, // Disable extension command 2 part I + 0xF0, 0x81, 0x69, 0x78, // Disable extension command 2 part II, delay 120 ms + 0x29, 0x00, // Display on +}; + +static void display_init(void) { + fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; + busio_spi_obj_t *spi = &bus->inline_bus; + mp_int_t rotation; + + common_hal_busio_spi_construct(spi, &pin_GPIO14, &pin_GPIO13, &pin_GPIO12, false); + + bus->base.type = &fourwire_fourwire_type; + common_hal_fourwire_fourwire_construct(bus, + spi, + MP_OBJ_FROM_PTR(&pin_GPIO2), // LCD_DC + MP_OBJ_FROM_PTR(&pin_GPIO15), // LCD_CS + mp_const_none, // Reset is tied to the ESP32 reset + 26666666, // Baudrate: ESP32 SPI through the GPIO matrix tops out at 26.67 MHz + 0, // Polarity + 0); // Phase + + busdisplay_busdisplay_obj_t *display = &allocate_display()->display; + display->base.type = &busdisplay_busdisplay_type; + if (settings_get_int("CIRCUITPY_DISPLAY_ROTATION", &rotation) != SETTINGS_OK) { + rotation = 0; + } + + common_hal_busdisplay_busdisplay_construct(display, + bus, + 480, // Width + 320, // Height + 0, // column start + 0, // row start + rotation, // 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 + display_init_sequence, + sizeof(display_init_sequence), + &pin_GPIO27, // backlight pin + NO_BRIGHTNESS_COMMAND, + 1.0f, // brightness + false, // single_byte_bounds + false, // data_as_commands + true, // auto_refresh + 60, // native_frames_per_second + true, // backlight_on_high + false, // SH1107_addressing + 50000); // backlight pwm frequency +} + +void board_init(void) { + display_init(); +} + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/freenove_esp32_display_3_5/mpconfigboard.h b/ports/espressif/boards/freenove_esp32_display_3_5/mpconfigboard.h new file mode 100644 index 00000000000..412bf2b0e15 --- /dev/null +++ b/ports/espressif/boards/freenove_esp32_display_3_5/mpconfigboard.h @@ -0,0 +1,29 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Brian Nelson +// +// SPDX-License-Identifier: MIT + +#pragma once + +#define MICROPY_HW_BOARD_NAME "Freenove ESP32 Display 3.5 inch" +#define MICROPY_HW_MCU_NAME "ESP32" + +// Blue element of the common-anode RGB LED +#define MICROPY_HW_LED_STATUS (&pin_GPIO17) +#define MICROPY_HW_LED_STATUS_INVERTED (1) + +#define CIRCUITPY_BOOT_BUTTON (&pin_GPIO0) + +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO32) +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO25) + +#define CIRCUITPY_BOARD_SPI (2) +#define CIRCUITPY_BOARD_SPI_PIN { \ + {.clock = &pin_GPIO18, .mosi = &pin_GPIO23, .miso = &pin_GPIO19}, /* SD card and SPI header */ \ + {.clock = &pin_GPIO14, .mosi = &pin_GPIO13, .miso = &pin_GPIO12}, /* LCD and touch */ \ +} + +// UART pins attached to the CH340C USB-to-serial converter +#define CIRCUITPY_CONSOLE_UART_TX (&pin_GPIO1) +#define CIRCUITPY_CONSOLE_UART_RX (&pin_GPIO3) diff --git a/ports/espressif/boards/freenove_esp32_display_3_5/mpconfigboard.mk b/ports/espressif/boards/freenove_esp32_display_3_5/mpconfigboard.mk new file mode 100644 index 00000000000..d7ab69e1e51 --- /dev/null +++ b/ports/espressif/boards/freenove_esp32_display_3_5/mpconfigboard.mk @@ -0,0 +1,8 @@ +CIRCUITPY_CREATOR_ID = 0x1C330000 +CIRCUITPY_CREATION_ID = 0x01030035 + +IDF_TARGET = esp32 + +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m +CIRCUITPY_ESP_FLASH_SIZE = 4MB diff --git a/ports/espressif/boards/freenove_esp32_display_3_5/pins.c b/ports/espressif/boards/freenove_esp32_display_3_5/pins.c new file mode 100644 index 00000000000..47e36ce49be --- /dev/null +++ b/ports/espressif/boards/freenove_esp32_display_3_5/pins.c @@ -0,0 +1,72 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Brian Nelson +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" +#include "shared-module/displayio/__init__.h" + +CIRCUITPY_BOARD_BUS_SINGLETON(lcd_spi, spi, 1) + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + // BOOT button + { MP_ROM_QSTR(MP_QSTR_BUTTON), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_BOOT), MP_ROM_PTR(&pin_GPIO0) }, + + // RGB LED, common anode (drive low to light) + { MP_ROM_QSTR(MP_QSTR_LED_RED), MP_ROM_PTR(&pin_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_LED_GREEN), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_LED_BLUE), MP_ROM_PTR(&pin_GPIO17) }, + + // ST7796 display, HSPI + { MP_ROM_QSTR(MP_QSTR_LCD_SCK), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_LCD_MOSI), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_LCD_MISO), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_LCD_CS), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_LCD_DC), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_LCD_BACKLIGHT), MP_ROM_PTR(&pin_GPIO27) }, + + // XPT2046 resistive touch controller, shares the LCD SPI bus + { MP_ROM_QSTR(MP_QSTR_TOUCH_CS), MP_ROM_PTR(&pin_GPIO33) }, + { MP_ROM_QSTR(MP_QSTR_TOUCH_IRQ), MP_ROM_PTR(&pin_GPIO36) }, + + // microSD card slot, VSPI + { MP_ROM_QSTR(MP_QSTR_SD_CLK), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_SD_MOSI), MP_ROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_SD_MISO), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_SD_CS), MP_ROM_PTR(&pin_GPIO5) }, + + // SPI header, shares the SD card bus + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_CS), MP_ROM_PTR(&pin_GPIO21) }, + + // I2C header + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO32) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO25) }, + + // UART header, shared with the USB serial console + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO3) }, + + // Input header (input-only pins) + { MP_ROM_QSTR(MP_QSTR_IO35), MP_ROM_PTR(&pin_GPIO35) }, + { MP_ROM_QSTR(MP_QSTR_IO39), MP_ROM_PTR(&pin_GPIO39) }, + + // Speaker: DAC output into the amplifier, and the amplifier shutdown (low = on) + { MP_ROM_QSTR(MP_QSTR_SPEAKER), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_SPEAKER_ENABLE_INVERTED), MP_ROM_PTR(&pin_GPIO4) }, + + // Battery voltage through a 1:2 divider + { MP_ROM_QSTR(MP_QSTR_BATTERY), MP_ROM_PTR(&pin_GPIO34) }, + + { 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_LCD_SPI), MP_ROM_PTR(&board_lcd_spi_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/tests/feature_check/byteorder.py.exp b/ports/espressif/boards/freenove_esp32_display_3_5/sdkconfig similarity index 100% rename from tests/feature_check/byteorder.py.exp rename to ports/espressif/boards/freenove_esp32_display_3_5/sdkconfig diff --git a/ports/espressif/boards/generic_esp32s3_supermini/board.c b/ports/espressif/boards/generic_esp32s3_supermini/board.c new file mode 100644 index 00000000000..9f1dc29f4fb --- /dev/null +++ b/ports/espressif/boards/generic_esp32s3_supermini/board.c @@ -0,0 +1,26 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include + +#include "supervisor/board.h" +#include "supervisor/shared/settings.h" +#include "supervisor/shared/status_leds.h" + +void board_init(void) { + #if CIRCUITPY_SETTINGS_TOML + // Clones of this board differ in ways the chip can't report. + // CIRCUITPY_BOARD_VARIANT in settings.toml picks one: + // "rgb_led": status NeoPixel takes R,G,B + char variant[16]; + if (settings_get_str("CIRCUITPY_BOARD_VARIANT", variant, sizeof(variant)) == SETTINGS_OK && + strcmp(variant, "rgb_led") == 0) { + status_led_set_neopixel_order(STATUS_NEOPIXEL_ORDER_RGB); + } + #endif +} + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/generic_esp32s3_supermini/mpconfigboard.h b/ports/espressif/boards/generic_esp32s3_supermini/mpconfigboard.h new file mode 100644 index 00000000000..d891284de25 --- /dev/null +++ b/ports/espressif/boards/generic_esp32s3_supermini/mpconfigboard.h @@ -0,0 +1,20 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Micropython setup + +#define MICROPY_HW_BOARD_NAME "Generic ESP32S3 Supermini" +#define MICROPY_HW_MCU_NAME "ESP32S3" + +#define MICROPY_HW_NEOPIXEL (&pin_GPIO48) + +#define DEFAULT_UART_BUS_RX (&pin_GPIO44) +#define DEFAULT_UART_BUS_TX (&pin_GPIO43) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/generic_esp32s3_supermini/mpconfigboard.mk b/ports/espressif/boards/generic_esp32s3_supermini/mpconfigboard.mk new file mode 100644 index 00000000000..b584c433e9f --- /dev/null +++ b/ports/espressif/boards/generic_esp32s3_supermini/mpconfigboard.mk @@ -0,0 +1,17 @@ +USB_VID = 0x303a +USB_PID = 0x8247 +USB_PRODUCT = "Generic ESP32-S3-Supermini" +USB_MANUFACTURER = "GENERIC" + +IDF_TARGET = esp32s3 + +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m +CIRCUITPY_ESP_FLASH_SIZE = 4MB + +CIRCUITPY_ESP_PSRAM_MODE = qio +CIRCUITPY_ESP_PSRAM_FREQ = 80m +CIRCUITPY_ESP_PSRAM_SIZE = 2MB + +# Include these Python libraries in firmware. +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel diff --git a/ports/espressif/boards/generic_esp32s3_supermini/pins.c b/ports/espressif/boards/generic_esp32s3_supermini/pins.c new file mode 100644 index 00000000000..c39aa400815 --- /dev/null +++ b/ports/espressif/boards/generic_esp32s3_supermini/pins.c @@ -0,0 +1,156 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + // BOOT button + { MP_ROM_QSTR(MP_QSTR_BUTTON), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_IO0), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_GPIO0) }, + + // Top side of the board - left column (top to bottom) + { MP_ROM_QSTR(MP_QSTR_IO43), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_D43), 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_D44), MP_ROM_PTR(&pin_GPIO44) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO44) }, + + { MP_ROM_QSTR(MP_QSTR_IO1), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO1) }, + + { MP_ROM_QSTR(MP_QSTR_IO2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_GPIO2) }, + + { MP_ROM_QSTR(MP_QSTR_IO3), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_GPIO3) }, + + { MP_ROM_QSTR(MP_QSTR_IO4), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_GPIO4) }, + + { MP_ROM_QSTR(MP_QSTR_IO5), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_GPIO5) }, + + { MP_ROM_QSTR(MP_QSTR_IO6), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_GPIO6) }, + + { MP_ROM_QSTR(MP_QSTR_IO7), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_A6), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_D7), MP_ROM_PTR(&pin_GPIO7) }, + + // Top side of the board - right column (bottom to top) + { MP_ROM_QSTR(MP_QSTR_IO8), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_A7), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_GPIO8) }, + + { MP_ROM_QSTR(MP_QSTR_IO9), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_A8), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_GPIO9) }, + + { MP_ROM_QSTR(MP_QSTR_IO10), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_A9), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_GPIO10) }, + + { MP_ROM_QSTR(MP_QSTR_IO11), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_A10), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_GPIO11) }, + + { MP_ROM_QSTR(MP_QSTR_IO12), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_A11), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_GPIO12) }, + + { MP_ROM_QSTR(MP_QSTR_IO13), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_A12), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_GPIO13) }, + + // Top side of the board - right column (top to bottom) + // Remaining three pins 5V, GND, 3v3 + + // Bottom pins (flat pads) left column (bottom to top) + { MP_ROM_QSTR(MP_QSTR_IO14), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_A13), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_D14), MP_ROM_PTR(&pin_GPIO14) }, + + { MP_ROM_QSTR(MP_QSTR_IO15), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_A14), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_GPIO15) }, + + { MP_ROM_QSTR(MP_QSTR_IO16), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_A15), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_D16), MP_ROM_PTR(&pin_GPIO16) }, + + { MP_ROM_QSTR(MP_QSTR_IO17), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_A16), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_D17), MP_ROM_PTR(&pin_GPIO17) }, + + { MP_ROM_QSTR(MP_QSTR_IO18), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_A17), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_D18), MP_ROM_PTR(&pin_GPIO18) }, + + // Remaining pins are digital only + { MP_ROM_QSTR(MP_QSTR_IO21), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_D21), MP_ROM_PTR(&pin_GPIO21) }, + + { MP_ROM_QSTR(MP_QSTR_IO33), MP_ROM_PTR(&pin_GPIO33) }, + { MP_ROM_QSTR(MP_QSTR_D33), MP_ROM_PTR(&pin_GPIO33) }, + + { MP_ROM_QSTR(MP_QSTR_IO34), MP_ROM_PTR(&pin_GPIO34) }, + { MP_ROM_QSTR(MP_QSTR_D34), MP_ROM_PTR(&pin_GPIO34) }, + + { MP_ROM_QSTR(MP_QSTR_IO35), MP_ROM_PTR(&pin_GPIO35) }, + { MP_ROM_QSTR(MP_QSTR_D35), MP_ROM_PTR(&pin_GPIO35) }, + + { MP_ROM_QSTR(MP_QSTR_IO36), MP_ROM_PTR(&pin_GPIO36) }, + { MP_ROM_QSTR(MP_QSTR_D36), MP_ROM_PTR(&pin_GPIO36) }, + + { MP_ROM_QSTR(MP_QSTR_IO37), MP_ROM_PTR(&pin_GPIO37) }, + { MP_ROM_QSTR(MP_QSTR_D37), MP_ROM_PTR(&pin_GPIO37) }, + + { MP_ROM_QSTR(MP_QSTR_IO38), MP_ROM_PTR(&pin_GPIO38) }, + { MP_ROM_QSTR(MP_QSTR_D38), MP_ROM_PTR(&pin_GPIO38) }, + + + // Bottom pins (flat pads) right column (bottom to top) + { MP_ROM_QSTR(MP_QSTR_IO39), MP_ROM_PTR(&pin_GPIO39) }, + { MP_ROM_QSTR(MP_QSTR_D39), MP_ROM_PTR(&pin_GPIO39) }, + + { MP_ROM_QSTR(MP_QSTR_IO40), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_D40), MP_ROM_PTR(&pin_GPIO40) }, + + { MP_ROM_QSTR(MP_QSTR_IO41), MP_ROM_PTR(&pin_GPIO41) }, + { MP_ROM_QSTR(MP_QSTR_D41), MP_ROM_PTR(&pin_GPIO41) }, + + { MP_ROM_QSTR(MP_QSTR_IO42), MP_ROM_PTR(&pin_GPIO42) }, + { MP_ROM_QSTR(MP_QSTR_D42), MP_ROM_PTR(&pin_GPIO42) }, + + { MP_ROM_QSTR(MP_QSTR_IO45), MP_ROM_PTR(&pin_GPIO45) }, + { MP_ROM_QSTR(MP_QSTR_D45), MP_ROM_PTR(&pin_GPIO45) }, + + { MP_ROM_QSTR(MP_QSTR_IO46), MP_ROM_PTR(&pin_GPIO46) }, + { MP_ROM_QSTR(MP_QSTR_D46), MP_ROM_PTR(&pin_GPIO46) }, + + { MP_ROM_QSTR(MP_QSTR_IO47), MP_ROM_PTR(&pin_GPIO47) }, + { MP_ROM_QSTR(MP_QSTR_D47), MP_ROM_PTR(&pin_GPIO47) }, + + // Neopixel + { MP_ROM_QSTR(MP_QSTR_IO48), MP_ROM_PTR(&pin_GPIO48) }, + { MP_ROM_QSTR(MP_QSTR_D48), MP_ROM_PTR(&pin_GPIO48) }, + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO48) }, + + // UART - using TX RX on silkscreen + { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj) } +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/espressif/boards/generic_esp32s3_supermini/sdkconfig b/ports/espressif/boards/generic_esp32s3_supermini/sdkconfig new file mode 100644 index 00000000000..e9628662160 --- /dev/null +++ b/ports/espressif/boards/generic_esp32s3_supermini/sdkconfig @@ -0,0 +1,14 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Component config +# +# +# LWIP +# +# end of LWIP + +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/boards/gravitech_cucumber_m/mpconfigboard.mk b/ports/espressif/boards/gravitech_cucumber_m/mpconfigboard.mk index a06ac482090..a77626e5104 100644 --- a/ports/espressif/boards/gravitech_cucumber_m/mpconfigboard.mk +++ b/ports/espressif/boards/gravitech_cucumber_m/mpconfigboard.mk @@ -8,4 +8,3 @@ IDF_TARGET = esp32s2 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/gravitech_cucumber_ms/mpconfigboard.mk b/ports/espressif/boards/gravitech_cucumber_ms/mpconfigboard.mk index 1cdf6273bee..f593b77cfff 100644 --- a/ports/espressif/boards/gravitech_cucumber_ms/mpconfigboard.mk +++ b/ports/espressif/boards/gravitech_cucumber_ms/mpconfigboard.mk @@ -8,4 +8,3 @@ IDF_TARGET = esp32s2 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/hardkernel_odroid_go/board.c b/ports/espressif/boards/hardkernel_odroid_go/board.c index 647fcd740eb..f2e1b29bb6d 100644 --- a/ports/espressif/boards/hardkernel_odroid_go/board.c +++ b/ports/espressif/boards/hardkernel_odroid_go/board.c @@ -6,6 +6,7 @@ #include "supervisor/board.h" #include "mpconfigboard.h" +#include "driver/gpio.h" #include "shared-bindings/busio/SPI.h" #include "shared-bindings/fourwire/FourWire.h" #include "shared-module/displayio/__init__.h" @@ -43,17 +44,19 @@ uint8_t display_init_sequence[] = { }; void board_init(void) { + // GPIO2 (LED) drives an LED. Default to pulled down (off). + espressif_board_reset_pin_number(2); + fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_GPIO18, &pin_GPIO23, NULL, false); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_GPIO21, // TFT_DC Command or data - &pin_GPIO5, // TFT_CS Chip select - NULL, // TFT_RST Reset + MP_OBJ_FROM_PTR(&pin_GPIO21), // TFT_DC Command or data + MP_OBJ_FROM_PTR(&pin_GPIO5), // TFT_CS Chip select + mp_const_none, // TFT_RST Reset 40000000, // Baudrate 0, // Polarity 0); // Phase diff --git a/ports/espressif/boards/heltec_esp32s3_wifi_lora_v3/board.c b/ports/espressif/boards/heltec_esp32s3_wifi_lora_v3/board.c index 317fb0d88a1..0960047c0a7 100644 --- a/ports/espressif/boards/heltec_esp32s3_wifi_lora_v3/board.c +++ b/ports/espressif/boards/heltec_esp32s3_wifi_lora_v3/board.c @@ -34,11 +34,10 @@ uint8_t display_init_sequence[] = { // SSD1306 digitalio_digitalinout_obj_t display_on; static void display_init(void) { - // Need to bring GPIO21 high or the screen doesn't get power + // Need to bring GPIO36 high or the screen doesn't get power // & the board can't see the i2c bus at all. - common_hal_digitalio_digitalinout_construct(&display_on, &pin_GPIO21); - common_hal_digitalio_digitalinout_switch_to_output(&display_on, true, DRIVE_MODE_PUSH_PULL); - common_hal_digitalio_digitalinout_never_reset(&display_on); + common_hal_digitalio_digitalinout_construct(&display_on, &pin_GPIO36); + common_hal_digitalio_digitalinout_switch_to_output(&display_on, false, DRIVE_MODE_PUSH_PULL); busio_i2c_obj_t *i2c = common_hal_board_create_i2c(0); @@ -48,7 +47,7 @@ static void display_init(void) { bus, i2c, 0x3c, - NULL + &pin_GPIO21 // broken-out on V3 ); busdisplay_busdisplay_obj_t *display = &allocate_display()->display; diff --git a/ports/espressif/boards/heltec_esp32s3_wifi_lora_v3/mpconfigboard.mk b/ports/espressif/boards/heltec_esp32s3_wifi_lora_v3/mpconfigboard.mk index 383961a8327..d5cbac7ea59 100644 --- a/ports/espressif/boards/heltec_esp32s3_wifi_lora_v3/mpconfigboard.mk +++ b/ports/espressif/boards/heltec_esp32s3_wifi_lora_v3/mpconfigboard.mk @@ -20,9 +20,5 @@ CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 8MB -CIRCUITPY_ESPCAMERA = 0 - -CIRCUITPY_DISPLAYIO = 1 - FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_Display_Shapes FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_Display_Text diff --git a/ports/espressif/boards/heltec_vision_master_e290/board.c b/ports/espressif/boards/heltec_vision_master_e290/board.c index cc8afe226be..178141b4737 100644 --- a/ports/espressif/boards/heltec_vision_master_e290/board.c +++ b/ports/espressif/boards/heltec_vision_master_e290/board.c @@ -42,60 +42,54 @@ void board_init(void) { vext_pin_obj.base.type = &digitalio_digitalinout_type; common_hal_digitalio_digitalinout_construct(&vext_pin_obj, &pin_GPIO18); common_hal_digitalio_digitalinout_switch_to_output(&vext_pin_obj, true, DRIVE_MODE_PUSH_PULL); - common_hal_digitalio_digitalinout_never_reset(&vext_pin_obj); // Set up the SPI object used to control the display fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_GPIO2, &pin_GPIO1, NULL, false); - common_hal_busio_spi_never_reset(spi); // Set up the DisplayIO pin object bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_GPIO4, // EPD_DC Command or data - &pin_GPIO3, // EPD_CS Chip select - &pin_GPIO5, // EPD_RST Reset + MP_OBJ_FROM_PTR(&pin_GPIO4), // EPD_DC Command or data + MP_OBJ_FROM_PTR(&pin_GPIO3), // EPD_CS Chip select + MP_OBJ_FROM_PTR(&pin_GPIO5), // EPD_RST Reset 1000000, // Baudrate 0, // Polarity 0); // Phase -// Set up the DisplayIO epaper object + // Set up the DisplayIO epaper object epaperdisplay_epaperdisplay_obj_t *display = &allocate_display()->epaper_display; display->base.type = &epaperdisplay_epaperdisplay_type; - common_hal_epaperdisplay_epaperdisplay_construct( - display, - bus, - display_start_sequence, sizeof(display_start_sequence), - 0, // start up time - display_stop_sequence, sizeof(display_stop_sequence), - 296, // width - 128, // height - 250, // ram_width - 296, // ram_height - 8, // colstart - 0, // rowstart - 90, // rotation - 0x44, // set_column_window_command - 0x45, // set_row_window_command - 0x4E, // set_current_column_command - 0x4F, // set_current_row_command - 0x24, // write_black_ram_command - false, // black_bits_inverted - 0x26, // write_color_ram_command - false, // color_bits_inverted - 0xFF0000, // highlight_color - refresh_sequence, sizeof(refresh_sequence), // refresh_display_command - 1.0, // refresh_time - &pin_GPIO6, // busy_pin - true, // busy_state - 2.0, // seconds_per_frame - false, // always_toggle_chip_select - false, // grayscale - false, // acep - false, // two_byte_sequence_length - true); // address_little_endian + + epaperdisplay_construct_args_t args = EPAPERDISPLAY_CONSTRUCT_ARGS_DEFAULTS; + args.bus = bus; + args.start_sequence = display_start_sequence; + args.start_sequence_len = sizeof(display_start_sequence); + args.stop_sequence = display_stop_sequence; + args.stop_sequence_len = sizeof(display_stop_sequence); + args.width = 296; + args.height = 128; + args.ram_width = 250; + args.ram_height = 296; + args.colstart = 8; + args.rotation = 90; + args.set_column_window_command = 0x44; + args.set_row_window_command = 0x45; + args.set_current_column_command = 0x4E; + args.set_current_row_command = 0x4F; + args.write_black_ram_command = 0x24; + args.write_color_ram_command = 0x26; + args.highlight_color = 0xFF0000; + args.refresh_sequence = refresh_sequence; + args.refresh_sequence_len = sizeof(refresh_sequence); + args.refresh_time = 1.0; + args.busy_pin = &pin_GPIO6; + args.busy_state = true; + args.seconds_per_frame = 2.0; + args.address_little_endian = true; + common_hal_epaperdisplay_epaperdisplay_construct(display, &args); } void board_deinit(void) { diff --git a/ports/espressif/boards/heltec_vision_master_e290/mpconfigboard.mk b/ports/espressif/boards/heltec_vision_master_e290/mpconfigboard.mk index 38b34592fc2..e5ab355fee9 100644 --- a/ports/espressif/boards/heltec_vision_master_e290/mpconfigboard.mk +++ b/ports/espressif/boards/heltec_vision_master_e290/mpconfigboard.mk @@ -12,5 +12,3 @@ CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_PSRAM_SIZE = 8MB CIRCUITPY_ESP_PSRAM_MODE = opi CIRCUITPY_ESP_PSRAM_FREQ = 80m - -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/heltec_wireless_paper/board.c b/ports/espressif/boards/heltec_wireless_paper/board.c index 2807f2d1a20..dfdf1d04f9d 100644 --- a/ports/espressif/boards/heltec_wireless_paper/board.c +++ b/ports/espressif/boards/heltec_wireless_paper/board.c @@ -82,60 +82,46 @@ void board_init(void) { vext_pin_obj.base.type = &digitalio_digitalinout_type; common_hal_digitalio_digitalinout_construct(&vext_pin_obj, &pin_GPIO45); common_hal_digitalio_digitalinout_switch_to_output(&vext_pin_obj, false, DRIVE_MODE_PUSH_PULL); - common_hal_digitalio_digitalinout_never_reset(&vext_pin_obj); // Set up the SPI object used to control the display fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_GPIO3, &pin_GPIO2, NULL, false); - common_hal_busio_spi_never_reset(spi); // Set up the DisplayIO pin object bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_GPIO5, // EPD_DC Command or data - &pin_GPIO4, // EPD_CS Chip select - &pin_GPIO6, // EPD_RST Reset + MP_OBJ_FROM_PTR(&pin_GPIO5), // EPD_DC Command or data + MP_OBJ_FROM_PTR(&pin_GPIO4), // EPD_CS Chip select + MP_OBJ_FROM_PTR(&pin_GPIO6), // EPD_RST Reset 1000000, // Baudrate 0, // Polarity 0); // Phase -// Set up the DisplayIO epaper object + // Set up the DisplayIO epaper object epaperdisplay_epaperdisplay_obj_t *display = &allocate_display()->epaper_display; display->base.type = &epaperdisplay_epaperdisplay_type; - common_hal_epaperdisplay_epaperdisplay_construct( - display, - bus, - display_start_sequence, sizeof(display_start_sequence), - 0, // start up time - display_stop_sequence, sizeof(display_stop_sequence), - 250, // width - 122, // height - 128, // ram_width - 296, // ram_height - 0, // colstart - 0, // rowstart - 270, // rotation - NO_COMMAND, // set_column_window_command - NO_COMMAND, // set_row_window_command - NO_COMMAND, // set_current_column_command - NO_COMMAND, // set_current_row_command - 0x13, // write_black_ram_command - false, // black_bits_inverted - 0x10, // write_color_ram_command - false, // color_bits_inverted - 0x000000, // highlight_color - refresh_sequence, sizeof(refresh_sequence), // refresh_display_command - 1.0, // refresh_time - &pin_GPIO7, // busy_pin - false, // busy_state - 2.0, // seconds_per_frame - false, // always_toggle_chip_select - false, // grayscale - false, // acep - false, // two_byte_sequence_length - false); // address_little_endian + + epaperdisplay_construct_args_t args = EPAPERDISPLAY_CONSTRUCT_ARGS_DEFAULTS; + args.bus = bus; + args.start_sequence = display_start_sequence; + args.start_sequence_len = sizeof(display_start_sequence); + args.stop_sequence = display_stop_sequence; + args.stop_sequence_len = sizeof(display_stop_sequence); + args.width = 250; + args.height = 122; + args.ram_width = 128; + args.ram_height = 296; + args.rotation = 270; + args.write_black_ram_command = 0x13; + args.write_color_ram_command = 0x10; + args.refresh_sequence = refresh_sequence; + args.refresh_sequence_len = sizeof(refresh_sequence); + args.refresh_time = 1.0; + args.busy_pin = &pin_GPIO7; + args.seconds_per_frame = 2.0; + common_hal_epaperdisplay_epaperdisplay_construct(display, &args); } void board_deinit(void) { diff --git a/ports/espressif/boards/heltec_wireless_paper/mpconfigboard.mk b/ports/espressif/boards/heltec_wireless_paper/mpconfigboard.mk index d949cb01a85..35a9ac1402e 100644 --- a/ports/espressif/boards/heltec_wireless_paper/mpconfigboard.mk +++ b/ports/espressif/boards/heltec_wireless_paper/mpconfigboard.mk @@ -19,7 +19,3 @@ CIRCUITPY_ESP_USB_SERIAL_JTAG = 0 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 8MB - -CIRCUITPY_ESPCAMERA = 0 - -CIRCUITPY_DISPLAYIO = 1 diff --git a/ports/espressif/boards/hexky_s2/board.c b/ports/espressif/boards/hexky_s2/board.c index c1e1801fed6..57425168a86 100644 --- a/ports/espressif/boards/hexky_s2/board.c +++ b/ports/espressif/boards/hexky_s2/board.c @@ -57,9 +57,9 @@ void board_init(void) { common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO34, // DC - &pin_GPIO33, // CS - &pin_GPIO41, // RST + MP_OBJ_FROM_PTR(&pin_GPIO34), // DC + MP_OBJ_FROM_PTR(&pin_GPIO33), // CS + MP_OBJ_FROM_PTR(&pin_GPIO41), // RST 40000000, // baudrate 0, // polarity 0 // phase @@ -99,16 +99,6 @@ void board_init(void) { ); } -bool espressif_board_reset_pin_number(gpio_num_t pin_number) { - // Override the I2C/TFT power pin reset to prevent resetting the display. - if (pin_number == 21) { - // Turn on TFT and I2C - config_pin_as_output_with_level(pin_number, true); - return true; - } - return false; -} - // Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. // TODO: Should we turn off the display when asleep, in board_deinit()? diff --git a/ports/espressif/boards/hexky_s2/mpconfigboard.mk b/ports/espressif/boards/hexky_s2/mpconfigboard.mk index 94d98aa8654..825d8721333 100644 --- a/ports/espressif/boards/hexky_s2/mpconfigboard.mk +++ b/ports/espressif/boards/hexky_s2/mpconfigboard.mk @@ -10,8 +10,8 @@ CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB -FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel - CIRCUITPY_ESP_PSRAM_SIZE = 2MB CIRCUITPY_ESP_PSRAM_MODE = qio CIRCUITPY_ESP_PSRAM_FREQ = 80m + +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel diff --git a/ports/espressif/boards/hiibot_iots2/board.c b/ports/espressif/boards/hiibot_iots2/board.c index e9941cbc368..1ee15b6ed03 100644 --- a/ports/espressif/boards/hiibot_iots2/board.c +++ b/ports/espressif/boards/hiibot_iots2/board.c @@ -55,16 +55,14 @@ static void display_init(void) { NULL, // MISO not connected false); // Not half-duplex - common_hal_busio_spi_never_reset(spi); - bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO35, // DC - &pin_GPIO36, // CS - NULL, // NO RST ? + MP_OBJ_FROM_PTR(&pin_GPIO35), // DC + MP_OBJ_FROM_PTR(&pin_GPIO36), // CS + mp_const_none, // NO RST ? 40000000, // baudrate 0, // polarity 0 // phase diff --git a/ports/espressif/boards/hiibot_iots2/mpconfigboard.mk b/ports/espressif/boards/hiibot_iots2/mpconfigboard.mk index 743acf85a45..f6d04202bb2 100644 --- a/ports/espressif/boards/hiibot_iots2/mpconfigboard.mk +++ b/ports/espressif/boards/hiibot_iots2/mpconfigboard.mk @@ -8,8 +8,9 @@ IDF_TARGET = esp32s2 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 8MB -#CIRCUITPY_ESP_FLASH_SIZE = 4MB CIRCUITPY_ESP_PSRAM_SIZE = 8MB CIRCUITPY_ESP_PSRAM_MODE = qio CIRCUITPY_ESP_PSRAM_FREQ = 80m + +CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/ikea_alpstuga_esp32_s3/board.c b/ports/espressif/boards/ikea_alpstuga_esp32_s3/board.c new file mode 100644 index 00000000000..6d735a9b031 --- /dev/null +++ b/ports/espressif/boards/ikea_alpstuga_esp32_s3/board.c @@ -0,0 +1,12 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" +#include "mpconfigboard.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "driver/gpio.h" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/ikea_alpstuga_esp32_s3/mpconfigboard.h b/ports/espressif/boards/ikea_alpstuga_esp32_s3/mpconfigboard.h new file mode 100644 index 00000000000..9a826047351 --- /dev/null +++ b/ports/espressif/boards/ikea_alpstuga_esp32_s3/mpconfigboard.h @@ -0,0 +1,21 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Micropython setup + +#define MICROPY_HW_BOARD_NAME "Ikea Alpstuga Drop-In ESP32S3 4MB Flash 2MB PSRAM" +#define MICROPY_HW_MCU_NAME "ESP32S3" + +#define MICROPY_HW_NEOPIXEL (&pin_GPIO33) + +#define MICROPY_HW_LED_STATUS (&pin_GPIO9) + +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO4) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO3) + +#define DOUBLE_TAP_PIN (&pin_GPIO34) diff --git a/ports/espressif/boards/ikea_alpstuga_esp32_s3/mpconfigboard.mk b/ports/espressif/boards/ikea_alpstuga_esp32_s3/mpconfigboard.mk new file mode 100644 index 00000000000..fbfb0f1ed3f --- /dev/null +++ b/ports/espressif/boards/ikea_alpstuga_esp32_s3/mpconfigboard.mk @@ -0,0 +1,14 @@ +USB_VID = 0x239A +USB_PID = 0x8178 +USB_PRODUCT = "Ikea Alpstuga Drop-In ESP32S3 4MB Flash 2MB PSRAM" +USB_MANUFACTURER = "Adafruit" + +IDF_TARGET = esp32s3 + +CIRCUITPY_ESP_FLASH_SIZE = 4MB +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m + +CIRCUITPY_ESP_PSRAM_SIZE = 2MB +CIRCUITPY_ESP_PSRAM_MODE = qio +CIRCUITPY_ESP_PSRAM_FREQ = 80m diff --git a/ports/espressif/boards/ikea_alpstuga_esp32_s3/pins.c b/ports/espressif/boards/ikea_alpstuga_esp32_s3/pins.c new file mode 100644 index 00000000000..20991f032bd --- /dev/null +++ b/ports/espressif/boards/ikea_alpstuga_esp32_s3/pins.c @@ -0,0 +1,38 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { MP_ROM_QSTR(MP_QSTR_BUTTON), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_BOOT0), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_GPIO0) }, + + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_GPIO3) }, + + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_GPIO4) }, + + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_GPIO9) }, + + { MP_ROM_QSTR(MP_QSTR_BUTTON_1), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_GPIO5) }, + + { MP_ROM_QSTR(MP_QSTR_BUTTON_2), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_GPIO6) }, + + { MP_ROM_QSTR(MP_QSTR_BUTTON_3), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_GPIO8) }, + + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO33) }, + + { 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/espressif/boards/ikea_alpstuga_esp32_s3/sdkconfig b/ports/espressif/boards/ikea_alpstuga_esp32_s3/sdkconfig new file mode 100644 index 00000000000..e9628662160 --- /dev/null +++ b/ports/espressif/boards/ikea_alpstuga_esp32_s3/sdkconfig @@ -0,0 +1,14 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Component config +# +# +# LWIP +# +# end of LWIP + +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/boards/lilygo_tdeck/board.c b/ports/espressif/boards/lilygo_tdeck/board.c index 91a2f6d2ad7..fdcc799a52e 100644 --- a/ports/espressif/boards/lilygo_tdeck/board.c +++ b/ports/espressif/boards/lilygo_tdeck/board.c @@ -26,15 +26,18 @@ uint8_t display_init_sequence[] = { }; void board_init(void) { + // GPIO10 (POWER_ON) switches on power to the display. Default to high (on). + espressif_board_reset_pin_number(10); + busio_spi_obj_t *spi = common_hal_board_create_spi(0); fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO11, // TFT_DC Command or data - &pin_GPIO12, // TFT_CS Chip select - NULL, // TFT_RST Reset + MP_OBJ_FROM_PTR(&pin_GPIO11), // TFT_DC Command or data + MP_OBJ_FROM_PTR(&pin_GPIO12), // TFT_CS Chip select + mp_const_none, // TFT_RST Reset 60000000, // Baudrate 0, // Polarity 0); // Phase diff --git a/ports/espressif/boards/lilygo_tdeck/mpconfigboard.mk b/ports/espressif/boards/lilygo_tdeck/mpconfigboard.mk index 369fba4e1a0..fc30e96c793 100644 --- a/ports/espressif/boards/lilygo_tdeck/mpconfigboard.mk +++ b/ports/espressif/boards/lilygo_tdeck/mpconfigboard.mk @@ -13,6 +13,7 @@ CIRCUITPY_ESP_PSRAM_SIZE = 8MB CIRCUITPY_ESP_PSRAM_MODE = opi CIRCUITPY_ESP_PSRAM_FREQ = 80m +# Few pins. CIRCUITPY_ESPCAMERA = 0 CIRCUITPY_MAX3421E = 0 CIRCUITPY_PS2IO = 0 diff --git a/ports/espressif/boards/lilygo_tdisplay_s3/board.c b/ports/espressif/boards/lilygo_tdisplay_s3/board.c index fe62edf1ed8..a02dab7173d 100644 --- a/ports/espressif/boards/lilygo_tdisplay_s3/board.c +++ b/ports/espressif/boards/lilygo_tdisplay_s3/board.c @@ -6,6 +6,7 @@ #include "supervisor/board.h" #include "mpconfigboard.h" +#include "driver/gpio.h" #include "shared-bindings/microcontroller/Pin.h" #include "shared-module/displayio/__init__.h" #include "shared-module/displayio/mipi_constants.h" diff --git a/ports/espressif/boards/lilygo_tdisplay_s3_pro/board.c b/ports/espressif/boards/lilygo_tdisplay_s3_pro/board.c index ede20df200f..054589af4bd 100644 --- a/ports/espressif/boards/lilygo_tdisplay_s3_pro/board.c +++ b/ports/espressif/boards/lilygo_tdisplay_s3_pro/board.c @@ -28,15 +28,19 @@ uint8_t display_init_sequence[] = { }; void board_init(void) { + // GPIO38 (FLASHLIGHT) drives a very bright LED. Default to pulled down + // (off). + espressif_board_reset_pin_number(38); + busio_spi_obj_t *spi = common_hal_board_create_spi(0); fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO9, // TFT_DC Command or data - &pin_GPIO39, // TFT_CS Chip select - &pin_GPIO47, // TFT_RST Reset + MP_OBJ_FROM_PTR(&pin_GPIO9), // TFT_DC Command or data + MP_OBJ_FROM_PTR(&pin_GPIO39), // TFT_CS Chip select + MP_OBJ_FROM_PTR(&pin_GPIO47), // TFT_RST Reset 40000000, // Baudrate 0, // Polarity 0); // Phase diff --git a/ports/espressif/boards/lilygo_tdongle_s3/board.c b/ports/espressif/boards/lilygo_tdongle_s3/board.c index 8907dc7fe98..8929ed234f0 100644 --- a/ports/espressif/boards/lilygo_tdongle_s3/board.c +++ b/ports/espressif/boards/lilygo_tdongle_s3/board.c @@ -53,16 +53,14 @@ static void display_init(void) { NULL, // MISO not connected false); // Not half-duplex - common_hal_busio_spi_never_reset(spi); - bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO2, // DC - &pin_GPIO4, // CS - &pin_GPIO1, // RST + MP_OBJ_FROM_PTR(&pin_GPIO2), // DC + MP_OBJ_FROM_PTR(&pin_GPIO4), // CS + MP_OBJ_FROM_PTR(&pin_GPIO1), // RST 10000000, // baudrate 0, // polarity 0 // phase @@ -97,7 +95,7 @@ static void display_init(void) { false, // data_as_commands true, // auto_refresh 60, // native_frames_per_second - true, // backlight_on_high + false, // backlight_on_high false, // SH1107_addressing 50000 // backlight pwm frequency ); diff --git a/ports/espressif/boards/lilygo_tdongle_s3/mpconfigboard.h b/ports/espressif/boards/lilygo_tdongle_s3/mpconfigboard.h index fe5525ef056..a987bac317b 100644 --- a/ports/espressif/boards/lilygo_tdongle_s3/mpconfigboard.h +++ b/ports/espressif/boards/lilygo_tdongle_s3/mpconfigboard.h @@ -11,5 +11,11 @@ #define MICROPY_HW_BOARD_NAME "LILYGO T-Dongle S3" #define MICROPY_HW_MCU_NAME "ESP32S3" -#define DEFAULT_UART_BUS_RX (&pin_GPIO44) -#define DEFAULT_UART_BUS_TX (&pin_GPIO43) +#define MICROPY_HW_APA102_MOSI (&pin_GPIO40) +#define MICROPY_HW_APA102_SCK (&pin_GPIO39) + +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO44) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO43) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/lilygo_tdongle_s3/mpconfigboard.mk b/ports/espressif/boards/lilygo_tdongle_s3/mpconfigboard.mk index 13fde7e1ec1..bc883366b5d 100644 --- a/ports/espressif/boards/lilygo_tdongle_s3/mpconfigboard.mk +++ b/ports/espressif/boards/lilygo_tdongle_s3/mpconfigboard.mk @@ -9,6 +9,5 @@ CIRCUITPY_ESP_FLASH_SIZE = 16MB CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m -CIRCUITPY_ESP_PSRAM_SIZE = 8MB -CIRCUITPY_ESP_PSRAM_MODE = opi -CIRCUITPY_ESP_PSRAM_FREQ = 80m +# Few pins. +CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/lilygo_tembed_esp32s3/board.c b/ports/espressif/boards/lilygo_tembed_esp32s3/board.c index 698e6980ece..8d921b65177 100644 --- a/ports/espressif/boards/lilygo_tembed_esp32s3/board.c +++ b/ports/espressif/boards/lilygo_tembed_esp32s3/board.c @@ -27,14 +27,13 @@ void board_init(void) { fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_GPIO12, &pin_GPIO11, NULL, false); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_GPIO13, // TFT_DC Command or data - &pin_GPIO10, // TFT_CS Chip select - &pin_GPIO9, // TFT_RST Reset + MP_OBJ_FROM_PTR(&pin_GPIO13), // TFT_DC Command or data + MP_OBJ_FROM_PTR(&pin_GPIO10), // TFT_CS Chip select + MP_OBJ_FROM_PTR(&pin_GPIO9), // TFT_RST Reset 60000000, // Baudrate 0, // Polarity 0); // Phase diff --git a/ports/espressif/boards/lilygo_tqt_pro_nopsram/board.c b/ports/espressif/boards/lilygo_tqt_pro_nopsram/board.c index c7e711aee66..fe72222a22c 100644 --- a/ports/espressif/boards/lilygo_tqt_pro_nopsram/board.c +++ b/ports/espressif/boards/lilygo_tqt_pro_nopsram/board.c @@ -57,9 +57,9 @@ void board_init(void) { common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO6, // DC - &pin_GPIO5, // CS - &pin_GPIO1, // RST + MP_OBJ_FROM_PTR(&pin_GPIO6), // DC + MP_OBJ_FROM_PTR(&pin_GPIO5), // CS + MP_OBJ_FROM_PTR(&pin_GPIO1), // RST 40000000, // baudrate 0, // polarity 0 // phase diff --git a/ports/espressif/boards/lilygo_tqt_pro_nopsram/mpconfigboard.mk b/ports/espressif/boards/lilygo_tqt_pro_nopsram/mpconfigboard.mk index 6592aaff4a4..5c7ff943cb3 100644 --- a/ports/espressif/boards/lilygo_tqt_pro_nopsram/mpconfigboard.mk +++ b/ports/espressif/boards/lilygo_tqt_pro_nopsram/mpconfigboard.mk @@ -9,6 +9,6 @@ CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 8MB -CIRCUITPY_ESPCAMERA = 0 # Not enough pins. +CIRCUITPY_ESPCAMERA = 0 CIRCUITPY_PARALLELDISPLAYBUS = 0 diff --git a/ports/espressif/boards/lilygo_tqt_pro_psram/board.c b/ports/espressif/boards/lilygo_tqt_pro_psram/board.c index c7e711aee66..fe72222a22c 100644 --- a/ports/espressif/boards/lilygo_tqt_pro_psram/board.c +++ b/ports/espressif/boards/lilygo_tqt_pro_psram/board.c @@ -57,9 +57,9 @@ void board_init(void) { common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO6, // DC - &pin_GPIO5, // CS - &pin_GPIO1, // RST + MP_OBJ_FROM_PTR(&pin_GPIO6), // DC + MP_OBJ_FROM_PTR(&pin_GPIO5), // CS + MP_OBJ_FROM_PTR(&pin_GPIO1), // RST 40000000, // baudrate 0, // polarity 0 // phase diff --git a/ports/espressif/boards/lilygo_tqt_pro_psram/mpconfigboard.mk b/ports/espressif/boards/lilygo_tqt_pro_psram/mpconfigboard.mk index f8d9e102e78..2006f98fbd7 100644 --- a/ports/espressif/boards/lilygo_tqt_pro_psram/mpconfigboard.mk +++ b/ports/espressif/boards/lilygo_tqt_pro_psram/mpconfigboard.mk @@ -13,6 +13,6 @@ CIRCUITPY_ESP_PSRAM_SIZE = 2MB CIRCUITPY_ESP_PSRAM_MODE = qio CIRCUITPY_ESP_PSRAM_FREQ = 80m -CIRCUITPY_ESPCAMERA = 0 # Not enough pins. +CIRCUITPY_ESPCAMERA = 0 CIRCUITPY_PARALLELDISPLAYBUS = 0 diff --git a/ports/espressif/boards/lilygo_ttgo_t-01c3/mpconfigboard.mk b/ports/espressif/boards/lilygo_ttgo_t-01c3/mpconfigboard.mk index 0fd65d99d6e..8550c526def 100644 --- a/ports/espressif/boards/lilygo_ttgo_t-01c3/mpconfigboard.mk +++ b/ports/espressif/boards/lilygo_ttgo_t-01c3/mpconfigboard.mk @@ -8,3 +8,6 @@ CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB CIRCUITPY_ESP_USB_SERIAL_JTAG = 0 + +# Board was originally defined with a 2MB firmware, almost 2MB user filesystem. Leave it that way. +CIRCUITPY_4MB_FLASH_LARGE_USER_FS_LAYOUT = 1 diff --git a/ports/espressif/boards/lilygo_ttgo_t-oi-plus/mpconfigboard.h b/ports/espressif/boards/lilygo_ttgo_t-oi-plus/mpconfigboard.h index 247e58d916d..382f6e3f598 100644 --- a/ports/espressif/boards/lilygo_ttgo_t-oi-plus/mpconfigboard.h +++ b/ports/espressif/boards/lilygo_ttgo_t-oi-plus/mpconfigboard.h @@ -16,3 +16,6 @@ #define CIRCUITPY_CONSOLE_UART_RX DEFAULT_UART_BUS_RX #define CIRCUITPY_CONSOLE_UART_TX DEFAULT_UART_BUS_TX + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/lilygo_ttgo_t-oi-plus/mpconfigboard.mk b/ports/espressif/boards/lilygo_ttgo_t-oi-plus/mpconfigboard.mk index d7eba6ea262..35ac1d44c62 100644 --- a/ports/espressif/boards/lilygo_ttgo_t-oi-plus/mpconfigboard.mk +++ b/ports/espressif/boards/lilygo_ttgo_t-oi-plus/mpconfigboard.mk @@ -7,6 +7,4 @@ CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 - CIRCUITPY_ESP_USB_SERIAL_JTAG = 0 diff --git a/ports/espressif/boards/lilygo_ttgo_t8_esp32_s2_wroom/mpconfigboard.mk b/ports/espressif/boards/lilygo_ttgo_t8_esp32_s2_wroom/mpconfigboard.mk index 0fbcf5c62bf..8cacf57efdf 100644 --- a/ports/espressif/boards/lilygo_ttgo_t8_esp32_s2_wroom/mpconfigboard.mk +++ b/ports/espressif/boards/lilygo_ttgo_t8_esp32_s2_wroom/mpconfigboard.mk @@ -8,4 +8,3 @@ IDF_TARGET = esp32s2 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/lilygo_ttgo_t8_s2_st7789/board.c b/ports/espressif/boards/lilygo_ttgo_t8_s2_st7789/board.c index 2b77e24b91e..64f60d5c799 100644 --- a/ports/espressif/boards/lilygo_ttgo_t8_s2_st7789/board.c +++ b/ports/espressif/boards/lilygo_ttgo_t8_s2_st7789/board.c @@ -55,16 +55,14 @@ static void display_init(void) { NULL, // MISO not connected false); // Not half-duplex - common_hal_busio_spi_never_reset(spi); - bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO37, // DC - &pin_GPIO34, // CS - &pin_GPIO38, // RST + MP_OBJ_FROM_PTR(&pin_GPIO37), // DC + MP_OBJ_FROM_PTR(&pin_GPIO34), // CS + MP_OBJ_FROM_PTR(&pin_GPIO38), // RST 40000000, // baudrate 0, // polarity 0 // phase diff --git a/ports/espressif/boards/lilygo_ttgo_tdisplay_esp32_16m/board.c b/ports/espressif/boards/lilygo_ttgo_tdisplay_esp32_16m/board.c index 97574398ca2..18869f28110 100644 --- a/ports/espressif/boards/lilygo_ttgo_tdisplay_esp32_16m/board.c +++ b/ports/espressif/boards/lilygo_ttgo_tdisplay_esp32_16m/board.c @@ -35,16 +35,14 @@ static void display_init(void) { NULL, // MISO not connected false); // Not half-duplex - common_hal_busio_spi_never_reset(spi); - bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO16, // DC - &pin_GPIO5, // CS - &pin_GPIO23, // RST + MP_OBJ_FROM_PTR(&pin_GPIO16), // DC + MP_OBJ_FROM_PTR(&pin_GPIO5), // CS + MP_OBJ_FROM_PTR(&pin_GPIO23), // RST 24000000, // baudrate (default from the driver) // 40000000, 0, // polarity diff --git a/ports/espressif/boards/lilygo_ttgo_tdisplay_esp32_16m/mpconfigboard.mk b/ports/espressif/boards/lilygo_ttgo_tdisplay_esp32_16m/mpconfigboard.mk index dd177ec1c90..e76ffaba310 100644 --- a/ports/espressif/boards/lilygo_ttgo_tdisplay_esp32_16m/mpconfigboard.mk +++ b/ports/espressif/boards/lilygo_ttgo_tdisplay_esp32_16m/mpconfigboard.mk @@ -6,5 +6,3 @@ IDF_TARGET = esp32 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 16MB - -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/lilygo_ttgo_tdisplay_esp32_4m/board.c b/ports/espressif/boards/lilygo_ttgo_tdisplay_esp32_4m/board.c index 2d3cb64d455..e38cf5d6ade 100644 --- a/ports/espressif/boards/lilygo_ttgo_tdisplay_esp32_4m/board.c +++ b/ports/espressif/boards/lilygo_ttgo_tdisplay_esp32_4m/board.c @@ -34,16 +34,14 @@ static void display_init(void) { NULL, // MISO not connected false); // Not half-duplex - common_hal_busio_spi_never_reset(spi); - bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO16, // DC - &pin_GPIO5, // CS - &pin_GPIO23, // RST + MP_OBJ_FROM_PTR(&pin_GPIO16), // DC + MP_OBJ_FROM_PTR(&pin_GPIO5), // CS + MP_OBJ_FROM_PTR(&pin_GPIO23), // RST 24000000, // baudrate (default from the driver) // 40000000, 0, // polarity diff --git a/ports/espressif/boards/lilygo_ttgo_tdisplay_esp32_4m/mpconfigboard.mk b/ports/espressif/boards/lilygo_ttgo_tdisplay_esp32_4m/mpconfigboard.mk index af1bd8b1789..8e89a6a2b3a 100644 --- a/ports/espressif/boards/lilygo_ttgo_tdisplay_esp32_4m/mpconfigboard.mk +++ b/ports/espressif/boards/lilygo_ttgo_tdisplay_esp32_4m/mpconfigboard.mk @@ -6,7 +6,3 @@ IDF_TARGET = esp32 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB - -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 - -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/lilygo_twatch_2020_v3/board.c b/ports/espressif/boards/lilygo_twatch_2020_v3/board.c index 266515c2338..74d54de99c0 100644 --- a/ports/espressif/boards/lilygo_twatch_2020_v3/board.c +++ b/ports/espressif/boards/lilygo_twatch_2020_v3/board.c @@ -39,16 +39,14 @@ static void display_init(void) { false // Not half-duplex ); - common_hal_busio_spi_never_reset(spi); - bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO27, // DC - &pin_GPIO5, // CS - NULL, // RST + MP_OBJ_FROM_PTR(&pin_GPIO27), // DC + MP_OBJ_FROM_PTR(&pin_GPIO5), // CS + mp_const_none, // RST 24000000, // baudrate 0, // polarity 0 // phase @@ -123,6 +121,9 @@ static void backlight_init(void) { */ void board_init(void) { + // MOTOR_PIN drives the vibration motor. Default to low (off). + espressif_board_reset_pin_number(MOTOR_PIN); + // Display display_init(); // backlight_init(); diff --git a/ports/espressif/boards/lilygo_twatch_s3/board.c b/ports/espressif/boards/lilygo_twatch_s3/board.c index 51f5933d177..a9fd3db46e7 100644 --- a/ports/espressif/boards/lilygo_twatch_s3/board.c +++ b/ports/espressif/boards/lilygo_twatch_s3/board.c @@ -108,9 +108,9 @@ void board_init(void) { common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO38, // DC - &pin_GPIO12, // CS - NULL, // RST + MP_OBJ_FROM_PTR(&pin_GPIO38), // DC + MP_OBJ_FROM_PTR(&pin_GPIO12), // CS + mp_const_none, // RST 40000000, // baudrate 0, // polarity 0 // phase diff --git a/ports/espressif/boards/lilygo_twatch_s3/mpconfigboard.mk b/ports/espressif/boards/lilygo_twatch_s3/mpconfigboard.mk index 5d63032d5bf..1d3154c1826 100644 --- a/ports/espressif/boards/lilygo_twatch_s3/mpconfigboard.mk +++ b/ports/espressif/boards/lilygo_twatch_s3/mpconfigboard.mk @@ -10,6 +10,11 @@ CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 16MB +CIRCUITPY_ESP_PSRAM_SIZE = 8MB +CIRCUITPY_ESP_PSRAM_MODE = opi +CIRCUITPY_ESP_PSRAM_FREQ = 80m + +# Specialized board. CIRCUITPY_ESPCAMERA = 0 CIRCUITPY_PARALLELDISPLAYBUS = 0 CIRCUITPY_MAX3421E = 0 @@ -19,10 +24,6 @@ CIRCUITPY_PS2IO = 0 CIRCUITPY_RGBMATRIX = 0 CIRCUITPY_ROTARYIO = 0 -CIRCUITPY_ESP_PSRAM_SIZE = 8MB -CIRCUITPY_ESP_PSRAM_MODE = opi -CIRCUITPY_ESP_PSRAM_FREQ = 80m - # Include these Python libraries in firmware. FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_FocalTouch FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_IRRemote diff --git a/ports/espressif/boards/lolin_c3_mini/mpconfigboard.mk b/ports/espressif/boards/lolin_c3_mini/mpconfigboard.mk index 36dc38883ff..99c910e6d24 100644 --- a/ports/espressif/boards/lolin_c3_mini/mpconfigboard.mk +++ b/ports/espressif/boards/lolin_c3_mini/mpconfigboard.mk @@ -7,6 +7,4 @@ CIRCUITPY_ESP_FLASH_MODE=qio CIRCUITPY_ESP_FLASH_FREQ=80m CIRCUITPY_ESP_FLASH_SIZE=4MB -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 - CIRCUITPY_ESP_USB_SERIAL_JTAG = 1 diff --git a/ports/espressif/boards/lolin_c3_pico/mpconfigboard.h b/ports/espressif/boards/lolin_c3_pico/mpconfigboard.h index 24800307223..6ee4cd4cf95 100644 --- a/ports/espressif/boards/lolin_c3_pico/mpconfigboard.h +++ b/ports/espressif/boards/lolin_c3_pico/mpconfigboard.h @@ -26,3 +26,6 @@ #define CIRCUITPY_BOARD_UART (1) #define CIRCUITPY_BOARD_UART_PIN {{.tx = &pin_GPIO21, .rx = &pin_GPIO20}} + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/lolin_c3_pico/mpconfigboard.mk b/ports/espressif/boards/lolin_c3_pico/mpconfigboard.mk index 25027d4c97b..6778550a2d1 100644 --- a/ports/espressif/boards/lolin_c3_pico/mpconfigboard.mk +++ b/ports/espressif/boards/lolin_c3_pico/mpconfigboard.mk @@ -7,12 +7,7 @@ CIRCUITPY_ESP_FLASH_MODE=qio CIRCUITPY_ESP_FLASH_FREQ=80m CIRCUITPY_ESP_FLASH_SIZE=4MB -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 - CIRCUITPY_ESP_USB_SERIAL_JTAG = 1 -# Not enough flash -CIRCUITPY_SOCKETPOOL_IPV6 = 0 - # Include these Python libraries in firmware. FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel diff --git a/ports/espressif/boards/lolin_c3_pico/sdkconfig b/ports/espressif/boards/lolin_c3_pico/sdkconfig index 3d0800e10d9..e9628662160 100644 --- a/ports/espressif/boards/lolin_c3_pico/sdkconfig +++ b/ports/espressif/boards/lolin_c3_pico/sdkconfig @@ -7,7 +7,6 @@ # # LWIP # -# CONFIG_LWIP_IPV6 is not set # end of LWIP # end of Component config diff --git a/ports/espressif/boards/lolin_s3/mpconfigboard.mk b/ports/espressif/boards/lolin_s3/mpconfigboard.mk index fbcdece670b..a86dd6578bd 100644 --- a/ports/espressif/boards/lolin_s3/mpconfigboard.mk +++ b/ports/espressif/boards/lolin_s3/mpconfigboard.mk @@ -12,5 +12,3 @@ CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_PSRAM_SIZE = 8MB CIRCUITPY_ESP_PSRAM_MODE = opi CIRCUITPY_ESP_PSRAM_FREQ = 80m - -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/lolin_s3_mini/mpconfigboard.mk b/ports/espressif/boards/lolin_s3_mini/mpconfigboard.mk index f58218d5e6b..fff6cae6d33 100644 --- a/ports/espressif/boards/lolin_s3_mini/mpconfigboard.mk +++ b/ports/espressif/boards/lolin_s3_mini/mpconfigboard.mk @@ -13,10 +13,5 @@ CIRCUITPY_ESP_PSRAM_SIZE = 2MB CIRCUITPY_ESP_PSRAM_MODE = qio CIRCUITPY_ESP_PSRAM_FREQ = 80m -CIRCUITPY_ESPCAMERA = 0 -CIRCUITPY_BITMAPFILTER = 0 -CIRCUITPY_CODEOP = 0 -CIRCUITPY_PARALLELDISPLAYBUS = 0 - # Include these Python libraries in firmware. FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel diff --git a/ports/espressif/boards/lolin_s3_mini_pro/board.c b/ports/espressif/boards/lolin_s3_mini_pro/board.c index cd5a083dbdb..564218e9016 100644 --- a/ports/espressif/boards/lolin_s3_mini_pro/board.c +++ b/ports/espressif/boards/lolin_s3_mini_pro/board.c @@ -33,15 +33,14 @@ void board_init(void) { // busio_spi_obj_t *spi = common_hal_board_create_spi(0); busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_GPIO40, &pin_GPIO38, NULL, false); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO36, // DC - &pin_GPIO35, // CS - &pin_GPIO34, // RST + MP_OBJ_FROM_PTR(&pin_GPIO36), // DC + MP_OBJ_FROM_PTR(&pin_GPIO35), // CS + MP_OBJ_FROM_PTR(&pin_GPIO34), // RST 40000000, // baudrate 0, // polarity 0 // phase diff --git a/ports/espressif/boards/lolin_s3_mini_pro/mpconfigboard.h b/ports/espressif/boards/lolin_s3_mini_pro/mpconfigboard.h index 2fe5f4205da..bdbea2d18cb 100644 --- a/ports/espressif/boards/lolin_s3_mini_pro/mpconfigboard.h +++ b/ports/espressif/boards/lolin_s3_mini_pro/mpconfigboard.h @@ -22,3 +22,6 @@ #define DEFAULT_UART_BUS_RX (&pin_GPIO44) #define DEFAULT_UART_BUS_TX (&pin_GPIO43) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/lolin_s3_mini_pro/mpconfigboard.mk b/ports/espressif/boards/lolin_s3_mini_pro/mpconfigboard.mk index 26d7e176a35..f08c733e43a 100644 --- a/ports/espressif/boards/lolin_s3_mini_pro/mpconfigboard.mk +++ b/ports/espressif/boards/lolin_s3_mini_pro/mpconfigboard.mk @@ -13,10 +13,5 @@ CIRCUITPY_ESP_PSRAM_SIZE = 2MB CIRCUITPY_ESP_PSRAM_MODE = qio CIRCUITPY_ESP_PSRAM_FREQ = 80m -CIRCUITPY_ESPCAMERA = 0 -CIRCUITPY_BITMAPFILTER = 0 -CIRCUITPY_CODEOP = 0 -CIRCUITPY_PARALLELDISPLAYBUS = 0 - # Include these Python libraries in firmware. FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel diff --git a/ports/espressif/boards/lolin_s3_pro/mpconfigboard.mk b/ports/espressif/boards/lolin_s3_pro/mpconfigboard.mk index 9df3f3580cd..f20732df49c 100755 --- a/ports/espressif/boards/lolin_s3_pro/mpconfigboard.mk +++ b/ports/espressif/boards/lolin_s3_pro/mpconfigboard.mk @@ -12,5 +12,3 @@ CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_PSRAM_SIZE = 8MB CIRCUITPY_ESP_PSRAM_MODE = opi CIRCUITPY_ESP_PSRAM_FREQ = 80m - -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/luatos_core_esp32c3/mpconfigboard.mk b/ports/espressif/boards/luatos_core_esp32c3/mpconfigboard.mk index ea3c7a44621..03f5171a310 100644 --- a/ports/espressif/boards/luatos_core_esp32c3/mpconfigboard.mk +++ b/ports/espressif/boards/luatos_core_esp32c3/mpconfigboard.mk @@ -7,6 +7,4 @@ CIRCUITPY_ESP_FLASH_MODE=dio CIRCUITPY_ESP_FLASH_FREQ=80m CIRCUITPY_ESP_FLASH_SIZE=4MB -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 - CIRCUITPY_ESP_USB_SERIAL_JTAG = 1 diff --git a/ports/espressif/boards/luatos_core_esp32c3_ch343/mpconfigboard.mk b/ports/espressif/boards/luatos_core_esp32c3_ch343/mpconfigboard.mk index bb793f0f262..9e777889c0f 100644 --- a/ports/espressif/boards/luatos_core_esp32c3_ch343/mpconfigboard.mk +++ b/ports/espressif/boards/luatos_core_esp32c3_ch343/mpconfigboard.mk @@ -7,6 +7,4 @@ CIRCUITPY_ESP_FLASH_MODE=dio CIRCUITPY_ESP_FLASH_FREQ=80m CIRCUITPY_ESP_FLASH_SIZE=4MB -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 - CIRCUITPY_ESP_USB_SERIAL_JTAG = 0 diff --git a/ports/espressif/boards/m5stack_atom_echo/mpconfigboard.mk b/ports/espressif/boards/m5stack_atom_echo/mpconfigboard.mk index a40381f8a34..c896ed0c8a4 100644 --- a/ports/espressif/boards/m5stack_atom_echo/mpconfigboard.mk +++ b/ports/espressif/boards/m5stack_atom_echo/mpconfigboard.mk @@ -6,7 +6,3 @@ IDF_TARGET = esp32 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB - -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 - -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/m5stack_atom_lite/mpconfigboard.mk b/ports/espressif/boards/m5stack_atom_lite/mpconfigboard.mk index 215fd976df3..5ca1db04f3b 100644 --- a/ports/espressif/boards/m5stack_atom_lite/mpconfigboard.mk +++ b/ports/espressif/boards/m5stack_atom_lite/mpconfigboard.mk @@ -6,7 +6,3 @@ IDF_TARGET = esp32 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB - -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 - -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/m5stack_atom_matrix/mpconfigboard.mk b/ports/espressif/boards/m5stack_atom_matrix/mpconfigboard.mk index 081750d143f..ace0e7f02cf 100644 --- a/ports/espressif/boards/m5stack_atom_matrix/mpconfigboard.mk +++ b/ports/espressif/boards/m5stack_atom_matrix/mpconfigboard.mk @@ -6,7 +6,3 @@ IDF_TARGET = esp32 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB - -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 - -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/m5stack_atom_u/mpconfigboard.mk b/ports/espressif/boards/m5stack_atom_u/mpconfigboard.mk index abcd5f8724d..0f8ab59f744 100644 --- a/ports/espressif/boards/m5stack_atom_u/mpconfigboard.mk +++ b/ports/espressif/boards/m5stack_atom_u/mpconfigboard.mk @@ -6,7 +6,3 @@ IDF_TARGET = esp32 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB - -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 - -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/m5stack_atoms3/board.c b/ports/espressif/boards/m5stack_atoms3/board.c index df620976b61..98f4188c694 100644 --- a/ports/espressif/boards/m5stack_atoms3/board.c +++ b/ports/espressif/boards/m5stack_atoms3/board.c @@ -33,15 +33,14 @@ void board_init(void) { // busio_spi_obj_t *spi = common_hal_board_create_spi(0); busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_GPIO17, &pin_GPIO21, NULL, false); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO33, // DC - &pin_GPIO15, // CS - &pin_GPIO34, // RST + MP_OBJ_FROM_PTR(&pin_GPIO33), // DC + MP_OBJ_FROM_PTR(&pin_GPIO15), // CS + MP_OBJ_FROM_PTR(&pin_GPIO34), // RST 40000000, // baudrate 0, // polarity 0 // phase diff --git a/ports/espressif/boards/m5stack_atoms3/mpconfigboard.mk b/ports/espressif/boards/m5stack_atoms3/mpconfigboard.mk index 9bc53033a1f..7738713aa53 100644 --- a/ports/espressif/boards/m5stack_atoms3/mpconfigboard.mk +++ b/ports/espressif/boards/m5stack_atoms3/mpconfigboard.mk @@ -8,4 +8,6 @@ IDF_TARGET = esp32s3 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 8MB + +# Few pins. CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/m5stack_atoms3_lite/mpconfigboard.mk b/ports/espressif/boards/m5stack_atoms3_lite/mpconfigboard.mk index 8bb5ab76d85..736fb3222b5 100644 --- a/ports/espressif/boards/m5stack_atoms3_lite/mpconfigboard.mk +++ b/ports/espressif/boards/m5stack_atoms3_lite/mpconfigboard.mk @@ -8,4 +8,6 @@ IDF_TARGET = esp32s3 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 8MB + +# Few pins. CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/m5stack_atoms3r/board.c b/ports/espressif/boards/m5stack_atoms3r/board.c new file mode 100644 index 00000000000..8591047ff96 --- /dev/null +++ b/ports/espressif/boards/m5stack_atoms3r/board.c @@ -0,0 +1,120 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Cade Roux +// +// SPDX-License-Identifier: MIT + +#include "py/mphal.h" +#include "supervisor/board.h" +#include "mpconfigboard.h" +#include "shared-bindings/busio/I2C.h" +#include "shared-bindings/busio/SPI.h" +#include "shared-bindings/fourwire/FourWire.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-module/displayio/__init__.h" +#include "shared-module/displayio/mipi_constants.h" +#include "shared-bindings/board/__init__.h" + +#define DELAY 0x80 + +// The panel is an ST7735S (M5Stack's M5GFX, Panel_ST7735S and board_M5AtomS3R), mounted upside down: MADCTL MY|MX|BGR, +// and the 128 x 128 picture sits 2 columns and 3 rows into the controller's memory. (Units made before May 2026 have a +// GC9107 instead, which this sequence doesn't drive.) +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, // FRMCTR2 + 0xB3, 6, 0x01, 0x2C, 0x2D, 0x01, 0x2C, 0x2D, // FRMCTR3 + 0xB4, 1, 0x07, // INVCTR + 0xC0, 3, 0xA2, 0x02, 0x84, // PWCTR1 + 0xC1, 1, 0xC5, // PWCTR2 + 0xC2, 2, 0x0A, 0x00, // PWCTR3 + 0xC3, 2, 0x8A, 0x2A, // PWCTR4 + 0xC4, 2, 0x8A, 0xEE, // PWCTR5 + 0xC5, 1, 0x0E, // VMCTR1 + 0xE0, 16, 0x02, 0x1C, 0x07, 0x12, 0x37, 0x32, 0x29, 0x2D, 0x29, 0x25, 0x2B, 0x39, 0x00, 0x01, 0x03, 0x10, // GMCTRP1 + 0xE1, 16, 0x03, 0x1D, 0x07, 0x06, 0x2E, 0x2C, 0x29, 0x2D, 0x2E, 0x2E, 0x37, 0x3F, 0x00, 0x00, 0x02, 0x10, // GMCTRN1 + 0x3A, 1, 0x05, // COLMOD: 16 bits a pixel + 0x36, 1, 0xC8, // MADCTL: MY | MX | BGR + 0x21, 0, // INVON + 0x13, 0 | DELAY, 10, // NORON + 0x29, 0 | DELAY, 100, // DISPON +}; + +// The backlight is the white channel of an LP5562 LED driver on the internal bus (GPIO0 SCL, GPIO45 SDA), not a pin +// (M5GFX: Light_M5StackAtomS3R). Enable it, run it on its internal clock with every LED under I2C control, and set the +// white channel's PWM. The bus is released afterwards, so board.I2C() can open it again. +#define LP5562_ADDRESS 0x30 +#define LP5562_BRIGHTNESS 0xA0 + +static void backlight_on(void) { + busio_i2c_obj_t i2c; + common_hal_busio_i2c_construct(&i2c, &pin_GPIO0, &pin_GPIO45, 100000, 255); + const uint8_t writes[][2] = { + {0x00, 0x40}, // ENABLE: chip enable + {0x08, 0x01}, // CONFIG: internal clock + {0x70, 0x00}, // LED_MAP: every LED from its I2C PWM register + {0x0E, LP5562_BRIGHTNESS}, // W_PWM + }; + for (size_t i = 0; i < MP_ARRAY_SIZE(writes); i++) { + common_hal_busio_i2c_write(&i2c, LP5562_ADDRESS, writes[i], 2); + mp_hal_delay_ms(1); + } + common_hal_busio_i2c_deinit(&i2c); +} + +void board_init(void) { + backlight_on(); + + fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; + busio_spi_obj_t *spi = &bus->inline_bus; + common_hal_busio_spi_construct(spi, &pin_GPIO15, &pin_GPIO21, NULL, false); + bus->base.type = &fourwire_fourwire_type; + + common_hal_fourwire_fourwire_construct( + bus, + spi, + MP_OBJ_FROM_PTR(&pin_GPIO42), // DC + MP_OBJ_FROM_PTR(&pin_GPIO14), // CS + MP_OBJ_FROM_PTR(&pin_GPIO48), // RST + 40000000, // baudrate + 0, // polarity + 0 // phase + ); + busdisplay_busdisplay_obj_t *display = &allocate_display()->display; + display->base.type = &busdisplay_busdisplay_type; + + common_hal_busdisplay_busdisplay_construct( + display, + bus, + 128, // width (after rotation) + 128, // height (after rotation) + 2, // column start + 3, // row start + 0, // 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 + display_init_sequence, + sizeof(display_init_sequence), + NULL, // backlight pin: the LP5562 (backlight_on above) + NO_BRIGHTNESS_COMMAND, + 1.0f, // brightness + false, // single_byte_bounds + false, // data_as_commands + true, // auto_refresh + 60, // native_frames_per_second + true, // backlight_on_high + false, // SH1107_addressing + 50000 // backlight pwm frequency + ); +} + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/m5stack_atoms3r/mpconfigboard.h b/ports/espressif/boards/m5stack_atoms3r/mpconfigboard.h new file mode 100644 index 00000000000..bb256ba467b --- /dev/null +++ b/ports/espressif/boards/m5stack_atoms3r/mpconfigboard.h @@ -0,0 +1,19 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Cade Roux +// +// SPDX-License-Identifier: MIT + +#pragma once + +#define MICROPY_HW_BOARD_NAME "M5Stack AtomS3R" +#define MICROPY_HW_MCU_NAME "ESP32S3" + +// board.I2C(): the internal bus (LP5562 backlight driver at 0x30, BMI270 IMU at 0x68). +// board.PORTA_I2C(): the Grove port. +#define CIRCUITPY_BOARD_I2C (2) +#define CIRCUITPY_BOARD_I2C_PIN {{.scl = &pin_GPIO0, .sda = &pin_GPIO45}, \ + {.scl = &pin_GPIO1, .sda = &pin_GPIO2}} + +#define DEFAULT_SPI_BUS_SCK (&pin_GPIO15) +#define DEFAULT_SPI_BUS_MOSI (&pin_GPIO21) diff --git a/ports/espressif/boards/m5stack_atoms3r/mpconfigboard.mk b/ports/espressif/boards/m5stack_atoms3r/mpconfigboard.mk new file mode 100644 index 00000000000..bb10e2d5aa2 --- /dev/null +++ b/ports/espressif/boards/m5stack_atoms3r/mpconfigboard.mk @@ -0,0 +1,20 @@ +USB_VID = 0x303A +USB_PID = 0x83EA +USB_PRODUCT = "AtomS3R" +USB_MANUFACTURER = "M5Stack" + +IDF_TARGET = esp32s3 + +CIRCUITPY_ESP_FLASH_SIZE = 8MB +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m + +CIRCUITPY_ESP_PSRAM_SIZE = 8MB +CIRCUITPY_ESP_PSRAM_MODE = opi +CIRCUITPY_ESP_PSRAM_FREQ = 80m + +# The internal I2C bus (the LP5562 backlight driver, the BMI270) is on GPIO0 / GPIO45, and 45 is a strapping pin. +CIRCUITPY_I2C_ALLOW_STRAPPING_PINS = 1 + +# Few pins. +CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/m5stack_atoms3r/pins.c b/ports/espressif/boards/m5stack_atoms3r/pins.c new file mode 100644 index 00000000000..6a8463c47b6 --- /dev/null +++ b/ports/espressif/boards/m5stack_atoms3r/pins.c @@ -0,0 +1,55 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Cade Roux +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" +#include "shared-module/displayio/__init__.h" + +CIRCUITPY_BOARD_BUS_SINGLETON(porta_i2c, i2c, 1) + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + // Grove (PORT.CUSTOM) + { MP_ROM_QSTR(MP_QSTR_PORTA_SCL), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_PORTA_SDA), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_GPIO2) }, + + // The bottom header + { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_A6), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_D7), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_A7), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_D38), MP_ROM_PTR(&pin_GPIO38) }, + { MP_ROM_QSTR(MP_QSTR_D39), MP_ROM_PTR(&pin_GPIO39) }, + + // The internal bus: the LP5562 (backlight) and the BMI270 (IMU) + { MP_ROM_QSTR(MP_QSTR_SYS_SCL), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_SYS_SDA), MP_ROM_PTR(&pin_GPIO45) }, + + // The display (ST7735S) + { MP_ROM_QSTR(MP_QSTR_LCD_MOSI), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_LCD_CLK), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_LCD_DC), MP_ROM_PTR(&pin_GPIO42) }, + { MP_ROM_QSTR(MP_QSTR_LCD_RST), MP_ROM_PTR(&pin_GPIO48) }, + { MP_ROM_QSTR(MP_QSTR_LCD_CS), MP_ROM_PTR(&pin_GPIO14) }, + + { MP_ROM_QSTR(MP_QSTR_BUTTON), MP_ROM_PTR(&pin_GPIO41) }, + { MP_ROM_QSTR(MP_QSTR_BTN), MP_ROM_PTR(&pin_GPIO41) }, + { MP_ROM_QSTR(MP_QSTR_IR_LED), MP_ROM_PTR(&pin_GPIO47) }, + + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, + { MP_ROM_QSTR(MP_QSTR_PORTA_I2C), MP_ROM_PTR(&board_porta_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_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/espressif/boards/m5stack_atoms3r/sdkconfig b/ports/espressif/boards/m5stack_atoms3r/sdkconfig new file mode 100644 index 00000000000..e9628662160 --- /dev/null +++ b/ports/espressif/boards/m5stack_atoms3r/sdkconfig @@ -0,0 +1,14 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Component config +# +# +# LWIP +# +# end of LWIP + +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/boards/m5stack_atoms3u/mpconfigboard.mk b/ports/espressif/boards/m5stack_atoms3u/mpconfigboard.mk index dc65fefc4bf..e68f4efdc65 100644 --- a/ports/espressif/boards/m5stack_atoms3u/mpconfigboard.mk +++ b/ports/espressif/boards/m5stack_atoms3u/mpconfigboard.mk @@ -8,4 +8,3 @@ IDF_TARGET = esp32s3 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 8MB -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/m5stack_cardputer/board.c b/ports/espressif/boards/m5stack_cardputer/board.c index 6fdc2f8ea5c..00630cd36d2 100644 --- a/ports/espressif/boards/m5stack_cardputer/board.c +++ b/ports/espressif/boards/m5stack_cardputer/board.c @@ -50,9 +50,9 @@ void board_init(void) { common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO34, // DC - &pin_GPIO37, // CS - &pin_GPIO33, // RST + MP_OBJ_FROM_PTR(&pin_GPIO34), // DC + MP_OBJ_FROM_PTR(&pin_GPIO37), // CS + MP_OBJ_FROM_PTR(&pin_GPIO33), // RST 40000000, // baudrate 0, // polarity 0 // phase diff --git a/ports/espressif/boards/m5stack_cardputer/mpconfigboard.mk b/ports/espressif/boards/m5stack_cardputer/mpconfigboard.mk index 6e9aaa76420..bc30ae3afd5 100644 --- a/ports/espressif/boards/m5stack_cardputer/mpconfigboard.mk +++ b/ports/espressif/boards/m5stack_cardputer/mpconfigboard.mk @@ -8,9 +8,9 @@ IDF_TARGET = esp32s3 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 8MB -CIRCUITPY_ESPCAMERA = 0 -CIRCUITPY_GIFIO = 1 +# Very few pins. +CIRCUITPY_ESPCAMERA = 0 CIRCUITPY_MAX3421E = 0 -SRC_C += boards/$(BOARD)/cardputer_keyboard.c +SRC_C += module/cardputer_keyboard.c diff --git a/ports/espressif/boards/m5stack_cardputer_ros/board.c b/ports/espressif/boards/m5stack_cardputer_ros/board.c new file mode 100644 index 00000000000..00630cd36d2 --- /dev/null +++ b/ports/espressif/boards/m5stack_cardputer_ros/board.c @@ -0,0 +1,95 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "mpconfigboard.h" +#include "supervisor/board.h" +#include "supervisor/shared/serial.h" +#include "shared-bindings/busio/SPI.h" +#include "shared-bindings/fourwire/FourWire.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-module/displayio/__init__.h" +#include "shared-module/displayio/mipi_constants.h" +#include "shared-bindings/board/__init__.h" +#include "py/runtime.h" +#include "py/ringbuf.h" +#include "shared/runtime/interrupt_char.h" + + +#define DELAY 0x80 + +uint8_t display_init_sequence[] = { + // SWRESET and Delay 140ms + 0x01, 0 | DELAY, 140, + // SLPOUT and Delay 10ms + 0x11, 0 | DELAY, 10, + // COLMOD 65k colors and 16 bit 5-6-5 + 0x3A, 1, 0x55, + // INVON Iiversion on + 0x21, 0, + // NORON normal operation (full update) + 0x13, 0, + // MADCTL columns RTL, page/column reverse order + 0x36, 1, 0x60, + // RAMCTRL color word little endian + 0xB0, 2, 0x00, 0xF8, + // DIPON display on + 0x29, 0, +}; + + +// Overrides the weakly linked function from supervisor/shared/board.c +void board_init(void) { + busio_spi_obj_t *spi = common_hal_board_create_spi(0); + fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; + bus->base.type = &fourwire_fourwire_type; + + // see here for inspiration: https://github.com/m5stack/M5GFX/blob/33d7d3135e816a86a008fae8ab3757938cee95d2/src/M5GFX.cpp#L1350 + common_hal_fourwire_fourwire_construct( + bus, + spi, + MP_OBJ_FROM_PTR(&pin_GPIO34), // DC + MP_OBJ_FROM_PTR(&pin_GPIO37), // CS + MP_OBJ_FROM_PTR(&pin_GPIO33), // RST + 40000000, // baudrate + 0, // polarity + 0 // phase + ); + busdisplay_busdisplay_obj_t *display = &allocate_display()->display; + display->base.type = &busdisplay_busdisplay_type; + + common_hal_busdisplay_busdisplay_construct( + display, + bus, + 240, // width (after rotation) + 135, // height (after rotation) + 40, // column start + 53, // row start + 0, // 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 + false, // 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 + display_init_sequence, + sizeof(display_init_sequence), + &pin_GPIO38, // backlight pin + NO_BRIGHTNESS_COMMAND, + 1.0f, // brightness + false, // single_byte_bounds + false, // data_as_commands + true, // auto_refresh + 60, // native_frames_per_second + true, // backlight_on_high + false, // SH1107_addressing + 350 // backlight pwm frequency + ); +} + +// TODO: Should we turn off the display when asleep, in board_deinit() ? diff --git a/ports/espressif/boards/m5stack_cardputer_ros/mpconfigboard.h b/ports/espressif/boards/m5stack_cardputer_ros/mpconfigboard.h new file mode 100644 index 00000000000..4b62c7d76e6 --- /dev/null +++ b/ports/espressif/boards/m5stack_cardputer_ros/mpconfigboard.h @@ -0,0 +1,19 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Micropython setup + +#define MICROPY_HW_BOARD_NAME "M5Stack Cardputer (ROS version)" +#define MICROPY_HW_MCU_NAME "ESP32S3" + +#define MICROPY_HW_NEOPIXEL (&pin_GPIO21) +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO1) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO2) +#define CIRCUITPY_BOARD_SPI (2) +#define CIRCUITPY_BOARD_SPI_PIN {{.clock = &pin_GPIO36, .mosi = &pin_GPIO35}, \ + {.clock = &pin_GPIO40, .mosi = &pin_GPIO14, .miso = &pin_GPIO39}} diff --git a/ports/espressif/boards/m5stack_cardputer_ros/mpconfigboard.mk b/ports/espressif/boards/m5stack_cardputer_ros/mpconfigboard.mk new file mode 100644 index 00000000000..98d2ad502dd --- /dev/null +++ b/ports/espressif/boards/m5stack_cardputer_ros/mpconfigboard.mk @@ -0,0 +1,18 @@ +USB_VID = 0x303A +USB_PID = 0x81DA +USB_PRODUCT = "M5Stack Cardputer - Circuitpython/ROS" +USB_MANUFACTURER = "M5STACK" + +IDF_TARGET = esp32s3 + +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m +CIRCUITPY_ESP_FLASH_SIZE = 8MB + +CIRCUITPY_RCLCPY = 0 + +# Very few pins. +CIRCUITPY_ESPCAMERA = 0 +CIRCUITPY_MAX3421E = 0 + +SRC_C += module/cardputer_keyboard.c diff --git a/ports/espressif/boards/m5stack_cardputer_ros/pins.c b/ports/espressif/boards/m5stack_cardputer_ros/pins.c new file mode 100644 index 00000000000..ba309e0dcbf --- /dev/null +++ b/ports/espressif/boards/m5stack_cardputer_ros/pins.c @@ -0,0 +1,86 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +#include "shared-module/displayio/__init__.h" +CIRCUITPY_BOARD_BUS_SINGLETON(sd_spi, spi, 1) +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + // Port A + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_PORTA1), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_G1), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_PORTA2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_G2), MP_ROM_PTR(&pin_GPIO2) }, + + // Keyboard + { MP_ROM_QSTR(MP_QSTR_KB_COL_0), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_KB_COL_1), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_KB_COL_2), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_KB_COL_3), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_KB_COL_4), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_KB_COL_5), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_KB_COL_6), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_KB_A_0), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_KB_A_1), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_KB_A_2), MP_ROM_PTR(&pin_GPIO11) }, + + // Neopixel + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO21) }, + + // Speaker + { MP_ROM_QSTR(MP_QSTR_I2S_BIT_CLOCK), MP_ROM_PTR(&pin_GPIO41) }, + { MP_ROM_QSTR(MP_QSTR_I2S_DATA), MP_ROM_PTR(&pin_GPIO42) }, + { MP_ROM_QSTR(MP_QSTR_I2S_WORD_SELECT), MP_ROM_PTR(&pin_GPIO43) }, + + // Mic + { MP_ROM_QSTR(MP_QSTR_MIC_DATA), MP_ROM_PTR(&pin_GPIO46) }, + { MP_ROM_QSTR(MP_QSTR_MIC_CLK), MP_ROM_PTR(&pin_GPIO43) }, + + // IR + { MP_ROM_QSTR(MP_QSTR_IR_TX), MP_ROM_PTR(&pin_GPIO44) }, + + // SD + { MP_ROM_QSTR(MP_QSTR_SD_MOSI), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_SD_SCK), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_SD_MISO), MP_ROM_PTR(&pin_GPIO39) }, + { MP_ROM_QSTR(MP_QSTR_SD_CS), MP_ROM_PTR(&pin_GPIO12) }, + + + // Display + { MP_ROM_QSTR(MP_QSTR_TFT_RST), MP_ROM_PTR(&pin_GPIO33) }, + { MP_ROM_QSTR(MP_QSTR_TFT_RESET), MP_ROM_PTR(&pin_GPIO33) }, + { MP_ROM_QSTR(MP_QSTR_TFT_DC), MP_ROM_PTR(&pin_GPIO34) }, + { MP_ROM_QSTR(MP_QSTR_TFT_RS), MP_ROM_PTR(&pin_GPIO34) }, + { MP_ROM_QSTR(MP_QSTR_TFT_MOSI), MP_ROM_PTR(&pin_GPIO35) }, + { MP_ROM_QSTR(MP_QSTR_TFT_DATA), MP_ROM_PTR(&pin_GPIO35) }, + { MP_ROM_QSTR(MP_QSTR_TFT_SCK), MP_ROM_PTR(&pin_GPIO36) }, + { MP_ROM_QSTR(MP_QSTR_TFT_CS), MP_ROM_PTR(&pin_GPIO37) }, + { MP_ROM_QSTR(MP_QSTR_TFT_BACKLIGHT), MP_ROM_PTR(&pin_GPIO38) }, + { MP_ROM_QSTR(MP_QSTR_TFT_BL), MP_ROM_PTR(&pin_GPIO38) }, + + // Button + { MP_ROM_QSTR(MP_QSTR_BUTTON), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_BOOT0), MP_ROM_PTR(&pin_GPIO0) }, + + // Battery + { MP_ROM_QSTR(MP_QSTR_BAT_ADC), MP_ROM_PTR(&pin_GPIO10) }, + + // Other + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, + { MP_ROM_QSTR(MP_QSTR_PORTA_I2C), MP_ROM_PTR(&board_i2c_obj) }, + { MP_ROM_QSTR(MP_QSTR_TFT_SPI), MP_ROM_PTR(&board_spi_obj) }, + { MP_ROM_QSTR(MP_QSTR_SD_SPI), MP_ROM_PTR(&board_sd_spi_obj) }, + + // Display object + { 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/espressif/boards/m5stack_cardputer_ros/sdkconfig b/ports/espressif/boards/m5stack_cardputer_ros/sdkconfig new file mode 100644 index 00000000000..e9628662160 --- /dev/null +++ b/ports/espressif/boards/m5stack_cardputer_ros/sdkconfig @@ -0,0 +1,14 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Component config +# +# +# LWIP +# +# end of LWIP + +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/boards/m5stack_core2/board.c b/ports/espressif/boards/m5stack_core2/board.c index 9d5c2bd650a..2e13c06c44f 100644 --- a/ports/espressif/boards/m5stack_core2/board.c +++ b/ports/espressif/boards/m5stack_core2/board.c @@ -318,9 +318,9 @@ static bool display_init(void) { common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO15, // DC - &pin_GPIO5, // CS - NULL, // RST + MP_OBJ_FROM_PTR(&pin_GPIO15), // DC + MP_OBJ_FROM_PTR(&pin_GPIO5), // CS + mp_const_none, // RST 32000000, // baudrate 0, // polarity 0 // phase diff --git a/ports/espressif/boards/m5stack_core_basic/board.c b/ports/espressif/boards/m5stack_core_basic/board.c index 4ae128817a1..e0f38c6da38 100644 --- a/ports/espressif/boards/m5stack_core_basic/board.c +++ b/ports/espressif/boards/m5stack_core_basic/board.c @@ -35,6 +35,10 @@ uint8_t display_init_sequence[] = { }; void board_init(void) { + // GPIO25 (SPEAKER) drives the speaker. Default to low, to keep noise off + // it. + espressif_board_reset_pin_number(25); + busio_spi_obj_t *spi = common_hal_board_create_spi(0); fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; bus->base.type = &fourwire_fourwire_type; @@ -42,9 +46,9 @@ void board_init(void) { common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO27, // DC - &pin_GPIO14, // CS - &pin_GPIO33, // RST + MP_OBJ_FROM_PTR(&pin_GPIO27), // DC + MP_OBJ_FROM_PTR(&pin_GPIO14), // CS + MP_OBJ_FROM_PTR(&pin_GPIO33), // RST 40000000, // baudrate 0, // polarity 0 // phase diff --git a/ports/espressif/boards/m5stack_core_basic/mpconfigboard.mk b/ports/espressif/boards/m5stack_core_basic/mpconfigboard.mk index dedcde81e63..964f61a04f4 100644 --- a/ports/espressif/boards/m5stack_core_basic/mpconfigboard.mk +++ b/ports/espressif/boards/m5stack_core_basic/mpconfigboard.mk @@ -6,4 +6,3 @@ IDF_TARGET = esp32 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 16MB -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/m5stack_core_fire/board.c b/ports/espressif/boards/m5stack_core_fire/board.c index 4ae128817a1..e0f38c6da38 100644 --- a/ports/espressif/boards/m5stack_core_fire/board.c +++ b/ports/espressif/boards/m5stack_core_fire/board.c @@ -35,6 +35,10 @@ uint8_t display_init_sequence[] = { }; void board_init(void) { + // GPIO25 (SPEAKER) drives the speaker. Default to low, to keep noise off + // it. + espressif_board_reset_pin_number(25); + busio_spi_obj_t *spi = common_hal_board_create_spi(0); fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; bus->base.type = &fourwire_fourwire_type; @@ -42,9 +46,9 @@ void board_init(void) { common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO27, // DC - &pin_GPIO14, // CS - &pin_GPIO33, // RST + MP_OBJ_FROM_PTR(&pin_GPIO27), // DC + MP_OBJ_FROM_PTR(&pin_GPIO14), // CS + MP_OBJ_FROM_PTR(&pin_GPIO33), // RST 40000000, // baudrate 0, // polarity 0 // phase diff --git a/ports/espressif/boards/m5stack_core_fire/mpconfigboard.mk b/ports/espressif/boards/m5stack_core_fire/mpconfigboard.mk index 591c596bbcf..e62fd3d4e57 100644 --- a/ports/espressif/boards/m5stack_core_fire/mpconfigboard.mk +++ b/ports/espressif/boards/m5stack_core_fire/mpconfigboard.mk @@ -10,5 +10,3 @@ CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_PSRAM_SIZE = 8MB CIRCUITPY_ESP_PSRAM_MODE = qio CIRCUITPY_ESP_PSRAM_FREQ = 80m - -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/m5stack_cores3/board.c b/ports/espressif/boards/m5stack_cores3/board.c index f49d6349997..ed93c914b4f 100644 --- a/ports/espressif/boards/m5stack_cores3/board.c +++ b/ports/espressif/boards/m5stack_cores3/board.c @@ -38,16 +38,17 @@ uint8_t display_init_sequence[] = { }; static bool display_init(void) { - busio_spi_obj_t *spi = common_hal_board_create_spi(0); fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; + busio_spi_obj_t *spi = &bus->inline_bus; + common_hal_busio_spi_construct(spi, &pin_GPIO36, &pin_GPIO37, NULL, false); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO35, // DC - &pin_GPIO3, // CS - NULL, // RST + MP_OBJ_FROM_PTR(&pin_GPIO35), // DC + MP_OBJ_FROM_PTR(&pin_GPIO3), // CS + mp_const_none, // RST 40000000, // baudrate 0, // polarity 0 // phase diff --git a/ports/espressif/boards/m5stack_cores3/mpconfigboard.h b/ports/espressif/boards/m5stack_cores3/mpconfigboard.h index 9af6ccf2fb4..0e5e136e3ea 100644 --- a/ports/espressif/boards/m5stack_cores3/mpconfigboard.h +++ b/ports/espressif/boards/m5stack_cores3/mpconfigboard.h @@ -15,9 +15,5 @@ #define CIRCUITPY_BOARD_I2C_PIN {{.scl = &pin_GPIO11, .sda = &pin_GPIO12}, \ {.scl = &pin_GPIO1, .sda = &pin_GPIO2}} -#define DEFAULT_SPI_BUS_SCK (&pin_GPIO36) -#define DEFAULT_SPI_BUS_MOSI (&pin_GPIO37) -#define DEFAULT_SPI_BUS_MISO (&pin_GPIO35) - #define DEFAULT_UART_BUS_RX (&pin_GPIO18) #define DEFAULT_UART_BUS_TX (&pin_GPIO17) diff --git a/ports/espressif/boards/m5stack_cores3/pins.c b/ports/espressif/boards/m5stack_cores3/pins.c index 2ebb225277d..11357d79a72 100644 --- a/ports/espressif/boards/m5stack_cores3/pins.c +++ b/ports/espressif/boards/m5stack_cores3/pins.c @@ -28,42 +28,57 @@ CIRCUITPY_BOARD_BUS_SINGLETON(porta_i2c, i2c, 1) static const mp_rom_map_elem_t board_module_globals_table[] = { CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS - // M5 Bus (except I2S & PORT B) - { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO37) }, - { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO35) }, - { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_GPIO36) }, + // M5 Bus (except I2S) + // The SPI bus MISO is also used for the TFT D/C signal, so it is not available for general use + // therefore the SPI bus is not listed on the M5 Bus { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO44) }, { MP_ROM_QSTR(MP_QSTR_D44), MP_ROM_PTR(&pin_GPIO44) }, + { MP_ROM_QSTR(MP_QSTR_PORTC_RX), MP_ROM_PTR(&pin_GPIO18) }, { MP_ROM_QSTR(MP_QSTR_D18), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_A18), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO12) }, - { MP_ROM_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_PORTA_SDA), MP_ROM_PTR(&pin_GPIO2) }, { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_GPIO2) }, { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_GPIO6) }, { MP_ROM_QSTR(MP_QSTR_A6), MP_ROM_PTR(&pin_GPIO6) }, - { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_GPIO6) }, + + { MP_ROM_QSTR(MP_QSTR_PORTB_IN), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_A8), MP_ROM_PTR(&pin_GPIO8) }, + + { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_GPIO5) }, + + { MP_ROM_QSTR(MP_QSTR_PORTB_OUT), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_A9), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO43) }, { MP_ROM_QSTR(MP_QSTR_D43), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_PORTC_TX), MP_ROM_PTR(&pin_GPIO17) }, { MP_ROM_QSTR(MP_QSTR_D17), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_A17), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_PORTA_SCL), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_D7), MP_ROM_PTR(&pin_GPIO7) }, { MP_ROM_QSTR(MP_QSTR_A7), MP_ROM_PTR(&pin_GPIO7) }, - // Port B - { MP_ROM_QSTR(MP_QSTR_PORTB_IN), MP_ROM_PTR(&pin_GPIO8) }, - { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_GPIO8) }, - { MP_ROM_QSTR(MP_QSTR_PORTB_OUT), MP_ROM_PTR(&pin_GPIO9) }, - { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_GPIO9) }, - // I2S { MP_ROM_QSTR(MP_QSTR_I2S_BIT_CLOCK), MP_ROM_PTR(&pin_GPIO34) }, { MP_ROM_QSTR(MP_QSTR_I2S_WORD_SELECT), MP_ROM_PTR(&pin_GPIO33) }, - { MP_ROM_QSTR(MP_QSTR_IS2_DATA), MP_ROM_PTR(&pin_GPIO13) }, - { MP_ROM_QSTR(MP_QSTR_IS2_MASTER_CLOCK), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_I2S_DATA_OUT), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_I2S_DATA_IN), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_I2S_MASTER_CLOCK), MP_ROM_PTR(&pin_GPIO0) }, // Camera { MP_ROM_QSTR(MP_QSTR_CAMERA_DATA), MP_ROM_PTR(&camera_data_tuple) }, @@ -82,6 +97,8 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_CAMERA_XCLK), MP_ROM_PTR(&pin_GPIO2) }, // Display + { MP_ROM_QSTR(MP_QSTR_TFT_MOSI), MP_ROM_PTR(&pin_GPIO37) }, + { MP_ROM_QSTR(MP_QSTR_TFT_SCK), MP_ROM_PTR(&pin_GPIO36) }, { MP_ROM_QSTR(MP_QSTR_TFT_CS), MP_ROM_PTR(&pin_GPIO3) }, { MP_ROM_QSTR(MP_QSTR_TFT_DC), MP_ROM_PTR(&pin_GPIO35) }, @@ -92,7 +109,6 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, { MP_ROM_QSTR(MP_QSTR_PORTA_I2C), MP_ROM_PTR(&board_porta_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_DISPLAY), MP_ROM_PTR(&displays[0].display)} diff --git a/ports/espressif/boards/m5stack_cores3_se/board.c b/ports/espressif/boards/m5stack_cores3_se/board.c new file mode 100644 index 00000000000..08ddfeebd85 --- /dev/null +++ b/ports/espressif/boards/m5stack_cores3_se/board.c @@ -0,0 +1,225 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" +#include "mpconfigboard.h" +#include "shared-bindings/busio/SPI.h" +#include "shared-bindings/busio/I2C.h" +#include "shared-bindings/fourwire/FourWire.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-module/displayio/__init__.h" +#include "shared-module/displayio/mipi_constants.h" +#include "shared-bindings/board/__init__.h" +#include "common-hal/microcontroller/Pin.h" + + +#define DELAY 0x80 +#define AXP2101_I2C_ADDRESS 0x34 +#define AW9523B_I2C_ADDRESS 0x58 + +uint8_t display_init_sequence[] = { + 0x01, DELAY, 0x80, // Software reset then delay 0x80 (128ms) + 0xC8, 0x03, 0xFF, 0x93, 0x42, // Turn on the external command + 0xC0, 0x02, 0x12, 0x12, // Power Control 1 + 0xC1, 0x01, 0x03, // Power Control 2 + 0xC5, 0x01, 0xF2, // VCOM Control 1 + 0xB0, 0x01, 0xE0, // RGB Interface SYNC Mode + 0xF6, 0x03, 0x01, 0x00, 0x00, // Interface control + 0XE0, 0x0F, 0x00, 0x0C, 0x11, 0x04, 0x11, 0x08, 0x37, 0x89, 0x4C, 0x06, 0x0C, 0x0A, 0x2E, 0x34, 0x0F, // Positive Gamma Correction + 0xE1, 0x0F, 0x00, 0x0B, 0x11, 0x05, 0x13, 0x09, 0x33, 0x67, 0x48, 0x07, 0x0E, 0x0B, 0x2E, 0x33, 0x0F, // Negative Gamma Correction + 0xB6, 0x04, 0x08, 0x82, 0x1D, 0x04, // Display Function Control + 0x3A, 0x01, 0x55, // COLMOD: Pixel Format Set 16 bit + 0x21, 0x00, // Display inversion ON + 0x36, 0x01, 0x08, // Memory Access Control: RGB order + 0x11, DELAY, 0x78, // Exit Sleep then delay 0x78 (120ms) + 0x29, DELAY, 0x78, // Display on then delay 0x78 (120ms) +}; + +static bool display_init(void) { + fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; + busio_spi_obj_t *spi = &bus->inline_bus; + common_hal_busio_spi_construct(spi, &pin_GPIO36, &pin_GPIO37, NULL, false); + bus->base.type = &fourwire_fourwire_type; + + common_hal_fourwire_fourwire_construct( + bus, + spi, + MP_OBJ_FROM_PTR(&pin_GPIO35), // DC + MP_OBJ_FROM_PTR(&pin_GPIO3), // CS + mp_const_none, // RST + 40000000, // baudrate + 0, // polarity + 0 // phase + ); + busdisplay_busdisplay_obj_t *display = &allocate_display()->display; + display->base.type = &busdisplay_busdisplay_type; + + common_hal_busdisplay_busdisplay_construct( + display, + bus, + 320, // width (after rotation) + 240, // height (after rotation) + 0, // column start + 0, // row start + 0, // 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 + display_init_sequence, + sizeof(display_init_sequence), + NULL, // backlight pin + NO_BRIGHTNESS_COMMAND, + 1.0f, // brightness + false, // single_byte_bounds + false, // data_as_commands + true, // auto_refresh + 61, // native_frames_per_second + true, // backlight_on_high + false, // SH1107_addressing + 50000 // backlight pwm frequency + ); + + return true; +} + +static bool axp2101_init(busio_i2c_obj_t *i2c) { + int rc; + uint8_t write_buf[2]; + + // 0x90 = 0b1011_0011 // LDOS ON/OFF control 0 + // Compared to CoreS3: ALDO2 (bit 2) and ALDO3 (bit 3) disabled (no ES7210/camera) + write_buf[0] = 0x90; + write_buf[1] = 0b10110011; + rc = common_hal_busio_i2c_write(i2c, AXP2101_I2C_ADDRESS, write_buf, sizeof(write_buf)); + if (rc != 0) { + return false; + } + + // 0x92, 0x0D // ALDO1 set to 1.8v for AW88298 + write_buf[0] = 0x92; + write_buf[1] = 0x0D; + rc = common_hal_busio_i2c_write(i2c, AXP2101_I2C_ADDRESS, write_buf, sizeof(write_buf)); + if (rc != 0) { + return false; + } + + // 0x95, 0x1C // ALDO4 set to 3.3v for TF card slot + write_buf[0] = 0x95; + write_buf[1] = 0x1C; + rc = common_hal_busio_i2c_write(i2c, AXP2101_I2C_ADDRESS, write_buf, sizeof(write_buf)); + if (rc != 0) { + return false; + } + + // 0x99, 0x18 // DLDO1 set to 2.9v for TFT backlight + write_buf[0] = 0x99; + write_buf[1] = 0x18; + rc = common_hal_busio_i2c_write(i2c, AXP2101_I2C_ADDRESS, write_buf, sizeof(write_buf)); + if (rc != 0) { + return false; + } + + // 0x27, 0x00 // PowerKey Hold=1sec / PowerOff=4sec + write_buf[0] = 0x27; + write_buf[1] = 0x00; + rc = common_hal_busio_i2c_write(i2c, AXP2101_I2C_ADDRESS, write_buf, sizeof(write_buf)); + if (rc != 0) { + return false; + } + + // 0x69, 0x11 // CHGLED setting + write_buf[0] = 0x69; + write_buf[1] = 0x11; + rc = common_hal_busio_i2c_write(i2c, AXP2101_I2C_ADDRESS, write_buf, sizeof(write_buf)); + if (rc != 0) { + return false; + } + + // 0x10, 0x30 // PMU common config + write_buf[0] = 0x10; + write_buf[1] = 0x30; + rc = common_hal_busio_i2c_write(i2c, AXP2101_I2C_ADDRESS, write_buf, sizeof(write_buf)); + if (rc != 0) { + return false; + } + + return true; +} + +static bool aw9523b_init(busio_i2c_obj_t *i2c) { + int rc; + uint8_t write_buf[2]; + + // 0x02 = 0b0000_0111 // AW_RST, BUD_OUT_EN, TOUCH_RST + write_buf[0] = 0x02; + write_buf[1] = 0b00000111; + rc = common_hal_busio_i2c_write(i2c, AW9523B_I2C_ADDRESS, write_buf, sizeof(write_buf)); + if (rc != 0) { + return false; + } + + // 0x03 = 0b1000_0011 // BOOST_EN, CAM_RST, LCD_RST + write_buf[0] = 0x03; + write_buf[1] = 0b10000011; + rc = common_hal_busio_i2c_write(i2c, AW9523B_I2C_ADDRESS, write_buf, sizeof(write_buf)); + if (rc != 0) { + return false; + } + + // 0x04 = 0b0001_1000 // Set TF_SW, ES_INT as input + write_buf[0] = 0x04; + write_buf[1] = 0b00011000; + rc = common_hal_busio_i2c_write(i2c, AW9523B_I2C_ADDRESS, write_buf, sizeof(write_buf)); + if (rc != 0) { + return false; + } + + // 0x05 = 0b0000_1100 // Set AW_INT, TOUCH_INT as input + write_buf[0] = 0x05; + write_buf[1] = 0b00001100; + rc = common_hal_busio_i2c_write(i2c, AW9523B_I2C_ADDRESS, write_buf, sizeof(write_buf)); + if (rc != 0) { + return false; + } + + // 0x11 = 0b0001_0000 // Set P0 outputs in push pull mode + write_buf[0] = 0x11; + write_buf[1] = 0b00010000; + rc = common_hal_busio_i2c_write(i2c, AW9523B_I2C_ADDRESS, write_buf, sizeof(write_buf)); + if (rc != 0) { + return false; + } + + return true; +} + +void board_init(void) { + // Deselect SD card on shared SPI bus before display init (see #10536) + config_pin_as_output_with_level(GPIO_NUM_4, true); + + busio_i2c_obj_t *internal_i2c = common_hal_board_create_i2c(0); + + if (!axp2101_init(internal_i2c)) { + mp_printf(&mp_plat_print, "could not initialize AXP2101"); + return; + } + + if (!aw9523b_init(internal_i2c)) { + mp_printf(&mp_plat_print, "could not initialize AW9523B"); + return; + } + + if (!display_init()) { + mp_printf(&mp_plat_print, "could not initialize the display"); + return; + } +} diff --git a/ports/espressif/boards/m5stack_cores3_se/mpconfigboard.h b/ports/espressif/boards/m5stack_cores3_se/mpconfigboard.h new file mode 100644 index 00000000000..edfcbb3c91b --- /dev/null +++ b/ports/espressif/boards/m5stack_cores3_se/mpconfigboard.h @@ -0,0 +1,21 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Micropython setup + +#define MICROPY_HW_BOARD_NAME "M5Stack CoreS3 SE" +#define MICROPY_HW_MCU_NAME "ESP32S3" + +#define MICROPY_HW_NEOPIXEL (&pin_GPIO5) + +#define CIRCUITPY_BOARD_I2C (2) +#define CIRCUITPY_BOARD_I2C_PIN {{.scl = &pin_GPIO11, .sda = &pin_GPIO12}, \ + {.scl = &pin_GPIO1, .sda = &pin_GPIO2}} + +#define DEFAULT_UART_BUS_RX (&pin_GPIO18) +#define DEFAULT_UART_BUS_TX (&pin_GPIO17) diff --git a/ports/espressif/boards/m5stack_cores3_se/mpconfigboard.mk b/ports/espressif/boards/m5stack_cores3_se/mpconfigboard.mk new file mode 100644 index 00000000000..2413c43cebe --- /dev/null +++ b/ports/espressif/boards/m5stack_cores3_se/mpconfigboard.mk @@ -0,0 +1,27 @@ +USB_VID = 0x303A +USB_PID = 0x8348 + +USB_PRODUCT = "M5Stack CoreS3 SE" +USB_MANUFACTURER = "M5Stack" + +IDF_TARGET = esp32s3 + +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m +CIRCUITPY_ESP_FLASH_SIZE = 16MB + +CIRCUITPY_ESP_PSRAM_SIZE = 8MB +CIRCUITPY_ESP_PSRAM_MODE = qio +CIRCUITPY_ESP_PSRAM_FREQ = 80m + +CIRCUITPY_PARALLELDISPLAYBUS = 0 + +OPTIMIZATION_FLAGS = -Os + +# Include these Python libraries in firmware. +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_ConnectionManager +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_Display_Shapes +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_Display_Text +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_FakeRequests +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_Requests diff --git a/ports/espressif/boards/m5stack_cores3_se/pins.c b/ports/espressif/boards/m5stack_cores3_se/pins.c new file mode 100644 index 00000000000..f003b74e122 --- /dev/null +++ b/ports/espressif/boards/m5stack_cores3_se/pins.c @@ -0,0 +1,86 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" +#include "shared-module/displayio/__init__.h" + +CIRCUITPY_BOARD_BUS_SINGLETON(porta_i2c, i2c, 1) + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + // M5 Bus (except I2S) + // The SPI bus MISO is also used for the TFT D/C signal, so it is not available for general use + // therefore the SPI bus is not listed on the M5 Bus + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO44) }, + { MP_ROM_QSTR(MP_QSTR_D44), MP_ROM_PTR(&pin_GPIO44) }, + + { MP_ROM_QSTR(MP_QSTR_PORTC_RX), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_D18), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_A18), MP_ROM_PTR(&pin_GPIO18) }, + + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO12) }, + + { MP_ROM_QSTR(MP_QSTR_PORTA_SDA), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO2) }, + + { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_A6), MP_ROM_PTR(&pin_GPIO6) }, + + { MP_ROM_QSTR(MP_QSTR_PORTB_IN), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_A8), MP_ROM_PTR(&pin_GPIO8) }, + + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_GPIO5) }, + + { MP_ROM_QSTR(MP_QSTR_PORTB_OUT), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_A9), MP_ROM_PTR(&pin_GPIO9) }, + + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_D43), MP_ROM_PTR(&pin_GPIO43) }, + + { MP_ROM_QSTR(MP_QSTR_PORTC_TX), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_D17), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_A17), MP_ROM_PTR(&pin_GPIO17) }, + + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO11) }, + + { MP_ROM_QSTR(MP_QSTR_PORTA_SCL), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO1) }, + + { MP_ROM_QSTR(MP_QSTR_IR), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_D7), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_A7), MP_ROM_PTR(&pin_GPIO7) }, + + // I2S + { MP_ROM_QSTR(MP_QSTR_I2S_BIT_CLOCK), MP_ROM_PTR(&pin_GPIO34) }, + { MP_ROM_QSTR(MP_QSTR_I2S_WORD_SELECT), MP_ROM_PTR(&pin_GPIO33) }, + { MP_ROM_QSTR(MP_QSTR_I2S_DATA_OUT), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_I2S_DATA_IN), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_I2S_MASTER_CLOCK), MP_ROM_PTR(&pin_GPIO0) }, + + // Display + { MP_ROM_QSTR(MP_QSTR_TFT_MOSI), MP_ROM_PTR(&pin_GPIO37) }, + { MP_ROM_QSTR(MP_QSTR_TFT_SCK), MP_ROM_PTR(&pin_GPIO36) }, + { MP_ROM_QSTR(MP_QSTR_TFT_CS), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_TFT_DC), MP_ROM_PTR(&pin_GPIO35) }, + + // Misc + { MP_ROM_QSTR(MP_QSTR_I2C_INTERRUPT), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_SDCARD_CS), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_BOOT0), MP_ROM_PTR(&pin_GPIO0) }, + + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, + { MP_ROM_QSTR(MP_QSTR_PORTA_I2C), MP_ROM_PTR(&board_porta_i2c_obj) }, + { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_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/espressif/boards/m5stack_cores3_se/sdkconfig b/ports/espressif/boards/m5stack_cores3_se/sdkconfig new file mode 100644 index 00000000000..e9628662160 --- /dev/null +++ b/ports/espressif/boards/m5stack_cores3_se/sdkconfig @@ -0,0 +1,14 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Component config +# +# +# LWIP +# +# end of LWIP + +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/boards/m5stack_dial/board.c b/ports/espressif/boards/m5stack_dial/board.c index 4e7cf4b0240..b37a58fc007 100644 --- a/ports/espressif/boards/m5stack_dial/board.c +++ b/ports/espressif/boards/m5stack_dial/board.c @@ -42,6 +42,10 @@ uint8_t display_init_sequence[] = { }; void board_init(void) { + // GPIO46 (POWER_HOLD) keeps the board on when it runs from the battery. + // Default to high (on). + espressif_board_reset_pin_number(46); + busio_spi_obj_t *spi = common_hal_board_create_spi(0); fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; bus->base.type = &fourwire_fourwire_type; @@ -49,9 +53,9 @@ void board_init(void) { common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO4, // DC - &pin_GPIO7, // CS - &pin_GPIO8, // RST + MP_OBJ_FROM_PTR(&pin_GPIO4), // DC + MP_OBJ_FROM_PTR(&pin_GPIO7), // CS + MP_OBJ_FROM_PTR(&pin_GPIO8), // RST 40000000, // baudrate 0, // polarity 0 // phase diff --git a/ports/espressif/boards/m5stack_dial/mpconfigboard.mk b/ports/espressif/boards/m5stack_dial/mpconfigboard.mk index cfdb0f16905..b87b5e6f925 100644 --- a/ports/espressif/boards/m5stack_dial/mpconfigboard.mk +++ b/ports/espressif/boards/m5stack_dial/mpconfigboard.mk @@ -10,7 +10,6 @@ CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 8MB +# Very few pins. CIRCUITPY_ESPCAMERA = 0 CIRCUITPY_PARALLELDISPLAYBUS = 0 - -OPTIMIZATION_FLAGS = -Os diff --git a/ports/espressif/boards/m5stack_dinmeter/board.c b/ports/espressif/boards/m5stack_dinmeter/board.c new file mode 100644 index 00000000000..ce91de1051b --- /dev/null +++ b/ports/espressif/boards/m5stack_dinmeter/board.c @@ -0,0 +1,111 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "mpconfigboard.h" +#include "supervisor/board.h" +#include "supervisor/shared/serial.h" +#include "shared-bindings/busio/SPI.h" +#include "shared-bindings/fourwire/FourWire.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-module/displayio/__init__.h" +#include "shared-module/displayio/mipi_constants.h" +#include "shared-bindings/board/__init__.h" +#include "py/runtime.h" +#include "py/ringbuf.h" +#include "shared/runtime/interrupt_char.h" + + +uint8_t display_init_sequence[] = { + 0x01, 0x80, 0x96, // SWRESET and Delay 150ms + 0x11, 0x80, 0xff, // SLPOUT and Delay + 0xb1, 0x03, 0x01, 0x2C, 0x2D, // _FRMCTR1 + 0xb2, 0x03, 0x01, 0x2C, 0x2D, // _FRMCTR2 + 0xb3, 0x06, 0x01, 0x2C, 0x2D, 0x01, 0x2C, 0x2D, // _FRMCTR3 + 0xb4, 0x01, 0x07, // _INVCTR line inversion + 0xc0, 0x03, 0xa2, 0x02, 0x84, // _PWCTR1 GVDD = 4.7V, 1.0uA + 0xc1, 0x01, 0xc5, // _PWCTR2 VGH=14.7V, VGL=-7.35V + 0xc2, 0x02, 0x0a, 0x00, // _PWCTR3 Opamp current small, Boost frequency + 0xc3, 0x02, 0x8a, 0x2a, + 0xc4, 0x02, 0x8a, 0xee, + 0xc5, 0x01, 0x0e, // _VMCTR1 VCOMH = 4V, VOML = -1.1V + 0x36, 0x01, 0xc8, // MADCTL Rotate display + 0x21, 0x00, // _INVON + 0x3a, 0x01, 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, 0x80, 0x0a, // _NORON + 0x29, 0x80, 0x64 // _DISPON +}; + + +// Overrides the weakly linked function from supervisor/shared/board.c +void board_init(void) { + // GPIO46 (POWER_HOLD) keeps the board on when it runs from the battery. + // Default to high (on). + espressif_board_reset_pin_number(46); + + busio_spi_obj_t *spi = common_hal_board_create_spi(0); + fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; + bus->base.type = &fourwire_fourwire_type; + + // see here for inspiration: https://github.com/m5stack/M5GFX/blob/33d7d3135e816a86a008fae8ab3757938cee95d2/src/M5GFX.cpp#L1350 + common_hal_fourwire_fourwire_construct( + bus, + spi, + MP_OBJ_FROM_PTR(&pin_GPIO4), // DC + MP_OBJ_FROM_PTR(&pin_GPIO7), // CS + MP_OBJ_FROM_PTR(&pin_GPIO8), // RST + 40000000, // baudrate + 0, // polarity + 0 // phase + ); + busdisplay_busdisplay_obj_t *display = &allocate_display()->display; + display->base.type = &busdisplay_busdisplay_type; + + common_hal_busdisplay_busdisplay_construct( + display, + bus, + 240, // width (after rotation) + 135, // height (after rotation) + 40, // column start + 52, // row start + 0, // 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 + display_init_sequence, + sizeof(display_init_sequence), + &pin_GPIO9, // backlight pin + NO_BRIGHTNESS_COMMAND, + 1.0f, // brightness + false, // single_byte_bounds + false, // data_as_commands + true, // auto_refresh + 80, // native_frames_per_second + true, // backlight_on_high + false, // SH1107_addressing + 50000 // backlight pwm frequency + ); +} + + +bool espressif_board_reset_pin_number(gpio_num_t pin_number) { + // Hold pin must be set high to avoid a power off when battery powered + if (pin_number == 46) { + // Turn on hold output + config_pin_as_output_with_level(pin_number, true); + return true; + } + return false; +} + +// TODO: Should we turn off the display when asleep, in board_deinit() ? diff --git a/ports/espressif/boards/m5stack_dinmeter/mpconfigboard.h b/ports/espressif/boards/m5stack_dinmeter/mpconfigboard.h new file mode 100644 index 00000000000..2d69e61ea95 --- /dev/null +++ b/ports/espressif/boards/m5stack_dinmeter/mpconfigboard.h @@ -0,0 +1,22 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 CDarius +// SPDX-FileCopyrightText: Copyright (c) 2025 juergenpabel +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Micropython setup + +#define MICROPY_HW_BOARD_NAME "M5Stack DinMeter" +#define MICROPY_HW_MCU_NAME "ESP32S3" + +#define CIRCUITPY_BOARD_I2C (2) +#define CIRCUITPY_BOARD_I2C_PIN {{.scl = &pin_GPIO12, .sda = &pin_GPIO11}, \ + {.scl = &pin_GPIO15, .sda = &pin_GPIO13}} + +#define CIRCUITPY_BOARD_SPI (1) +#define CIRCUITPY_BOARD_SPI_PIN {{.clock = &pin_GPIO6, .mosi = &pin_GPIO5}} + +#define CIRCUITPY_I2C_ALLOW_INTERNAL_PULL_UP (1) diff --git a/ports/espressif/boards/m5stack_dinmeter/mpconfigboard.mk b/ports/espressif/boards/m5stack_dinmeter/mpconfigboard.mk new file mode 100644 index 00000000000..81a23af1fe4 --- /dev/null +++ b/ports/espressif/boards/m5stack_dinmeter/mpconfigboard.mk @@ -0,0 +1,15 @@ +USB_VID = 0x303A +USB_PID = 0x830B + +USB_PRODUCT = "DinMeter" +USB_MANUFACTURER = "M5Stack" + +IDF_TARGET = esp32s3 + +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m +CIRCUITPY_ESP_FLASH_SIZE = 8MB + +# Very few pins. +CIRCUITPY_ESPCAMERA = 0 +CIRCUITPY_PARALLELDISPLAYBUS = 0 diff --git a/ports/espressif/boards/m5stack_dinmeter/pins.c b/ports/espressif/boards/m5stack_dinmeter/pins.c new file mode 100644 index 00000000000..f75e05e848b --- /dev/null +++ b/ports/espressif/boards/m5stack_dinmeter/pins.c @@ -0,0 +1,61 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2025 Juergen Pabel +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +#include "shared-module/displayio/__init__.h" + +CIRCUITPY_BOARD_BUS_SINGLETON(porta_i2c, i2c, 1) + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + // Port A + { MP_ROM_QSTR(MP_QSTR_PORTA_SCL), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_PORTA_SDA), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_GPIO13) }, + + // Port B + { MP_ROM_QSTR(MP_QSTR_PORTB_IN), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_PORTB_OUT), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO2) }, + + // Encoder + { MP_ROM_QSTR(MP_QSTR_ENC_A), MP_ROM_PTR(&pin_GPIO41) }, + { MP_ROM_QSTR(MP_QSTR_ENC_B), MP_ROM_PTR(&pin_GPIO40) }, + + // Button + { MP_ROM_QSTR(MP_QSTR_BUTTON), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_BOOT0), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_GPIO0) }, + + // Misc + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_SPEAKER), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_KNOB_BUTTON), MP_ROM_PTR(&pin_GPIO42) }, + { MP_ROM_QSTR(MP_QSTR_POWER_HOLD), MP_ROM_PTR(&pin_GPIO46) }, + + // Display + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_TFT_CS), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_TFT_DC), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_TFT_RESET), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_TFT_BACKLIGHT), MP_ROM_PTR(&pin_GPIO9) }, + + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, + { MP_ROM_QSTR(MP_QSTR_PORTA_I2C), MP_ROM_PTR(&board_porta_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_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/espressif/boards/m5stack_dinmeter/sdkconfig b/ports/espressif/boards/m5stack_dinmeter/sdkconfig new file mode 100644 index 00000000000..e9628662160 --- /dev/null +++ b/ports/espressif/boards/m5stack_dinmeter/sdkconfig @@ -0,0 +1,14 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Component config +# +# +# LWIP +# +# end of LWIP + +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/boards/m5stack_m5paper/board.c b/ports/espressif/boards/m5stack_m5paper/board.c index fbf66fa5ccd..16bd4084707 100644 --- a/ports/espressif/boards/m5stack_m5paper/board.c +++ b/ports/espressif/boards/m5stack_m5paper/board.c @@ -27,7 +27,6 @@ void board_init(void) { // // Set up the SPI object used to control the display // busio_spi_obj_t *spi = common_hal_board_create_spi(0); - // common_hal_busio_spi_never_reset(spi); // // Set up the DisplayIO pin object // fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; @@ -74,6 +73,7 @@ void board_init(void) { // false, // always_toggle_chip_select // false, // grayscale // true, // acep + // false, // spectra6 // false, // two_byte_sequence_length // false // address_little_endian // ); diff --git a/ports/espressif/boards/m5stack_m5paper/mpconfigboard.mk b/ports/espressif/boards/m5stack_m5paper/mpconfigboard.mk index bacf270a663..bbc07263273 100644 --- a/ports/espressif/boards/m5stack_m5paper/mpconfigboard.mk +++ b/ports/espressif/boards/m5stack_m5paper/mpconfigboard.mk @@ -10,5 +10,3 @@ CIRCUITPY_ESP_FLASH_SIZE = 16MB CIRCUITPY_ESP_PSRAM_SIZE = 8MB CIRCUITPY_ESP_PSRAM_MODE = qio CIRCUITPY_ESP_PSRAM_FREQ = 80m - -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/m5stack_stamp_c3/mpconfigboard.mk b/ports/espressif/boards/m5stack_stamp_c3/mpconfigboard.mk index 2c856c6fc00..2f3b62f90fa 100644 --- a/ports/espressif/boards/m5stack_stamp_c3/mpconfigboard.mk +++ b/ports/espressif/boards/m5stack_stamp_c3/mpconfigboard.mk @@ -7,6 +7,4 @@ CIRCUITPY_ESP_FLASH_MODE=qio CIRCUITPY_ESP_FLASH_FREQ=80m CIRCUITPY_ESP_FLASH_SIZE=4MB -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 - CIRCUITPY_ESP_USB_SERIAL_JTAG = 0 diff --git a/ports/espressif/boards/m5stack_stamp_s3/mpconfigboard.mk b/ports/espressif/boards/m5stack_stamp_s3/mpconfigboard.mk index b27fbb3dc2c..d2f1bc3c471 100644 --- a/ports/espressif/boards/m5stack_stamp_s3/mpconfigboard.mk +++ b/ports/espressif/boards/m5stack_stamp_s3/mpconfigboard.mk @@ -8,7 +8,6 @@ IDF_TARGET = esp32s3 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 8MB -CIRCUITPY_ESPCAMERA = 0 # Include these Python libraries in firmware. FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel diff --git a/ports/espressif/boards/m5stack_stick_c/board.c b/ports/espressif/boards/m5stack_stick_c/board.c index 641d2d1db7e..639db155745 100644 --- a/ports/espressif/boards/m5stack_stick_c/board.c +++ b/ports/espressif/boards/m5stack_stick_c/board.c @@ -147,16 +147,15 @@ static bool display_init(void) { fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_GPIO13, &pin_GPIO15, NULL, false); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO23, // DC - &pin_GPIO5, // CS - &pin_GPIO18, // RST + MP_OBJ_FROM_PTR(&pin_GPIO23), // DC + MP_OBJ_FROM_PTR(&pin_GPIO5), // CS + MP_OBJ_FROM_PTR(&pin_GPIO18), // RST 10000000, // baudrate 0, // polarity 0 // phase @@ -200,6 +199,10 @@ static bool display_init(void) { } void board_init(void) { + // GPIO9 (IR_LED) drives the IR LED, which is on when the pin is low. + // Default to high (off), to save power. + espressif_board_reset_pin_number(9); + busio_i2c_obj_t *internal_i2c = common_hal_board_create_i2c(0); if (!pmic_init(internal_i2c)) { diff --git a/ports/espressif/boards/m5stack_stick_c/mpconfigboard.mk b/ports/espressif/boards/m5stack_stick_c/mpconfigboard.mk index ce94e71dff2..7f8b24c8081 100644 --- a/ports/espressif/boards/m5stack_stick_c/mpconfigboard.mk +++ b/ports/espressif/boards/m5stack_stick_c/mpconfigboard.mk @@ -6,8 +6,5 @@ IDF_TARGET = esp32 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB -CIRCUITPY_ESPCAMERA = 0 - -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 SRC_C += pmic/axp192/axp192.c diff --git a/ports/espressif/boards/m5stack_stick_c_plus/board.c b/ports/espressif/boards/m5stack_stick_c_plus/board.c index eec6a208260..d3caa86a94b 100644 --- a/ports/espressif/boards/m5stack_stick_c_plus/board.c +++ b/ports/espressif/boards/m5stack_stick_c_plus/board.c @@ -147,16 +147,15 @@ static bool display_init(void) { fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_GPIO13, &pin_GPIO15, NULL, false); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO23, // DC - &pin_GPIO5, // CS - &pin_GPIO18, // RST + MP_OBJ_FROM_PTR(&pin_GPIO23), // DC + MP_OBJ_FROM_PTR(&pin_GPIO5), // CS + MP_OBJ_FROM_PTR(&pin_GPIO18), // RST 10000000, // baudrate 0, // polarity 0 // phase @@ -200,6 +199,10 @@ static bool display_init(void) { } void board_init(void) { + // GPIO9 (IR_LED) drives the IR LED, which is on when the pin is low. + // Default to high (off), to save power. + espressif_board_reset_pin_number(9); + busio_i2c_obj_t *internal_i2c = common_hal_board_create_i2c(0); if (!pmic_init(internal_i2c)) { diff --git a/ports/espressif/boards/m5stack_stick_c_plus/mpconfigboard.mk b/ports/espressif/boards/m5stack_stick_c_plus/mpconfigboard.mk index bee1fc7e781..8960a568feb 100644 --- a/ports/espressif/boards/m5stack_stick_c_plus/mpconfigboard.mk +++ b/ports/espressif/boards/m5stack_stick_c_plus/mpconfigboard.mk @@ -6,8 +6,5 @@ IDF_TARGET = esp32 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB -CIRCUITPY_ESPCAMERA = 0 - -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 SRC_C += pmic/axp192/axp192.c diff --git a/ports/espressif/boards/m5stack_stick_c_plus2/board.c b/ports/espressif/boards/m5stack_stick_c_plus2/board.c index a50e38df09e..bc61008e1a1 100644 --- a/ports/espressif/boards/m5stack_stick_c_plus2/board.c +++ b/ports/espressif/boards/m5stack_stick_c_plus2/board.c @@ -43,16 +43,15 @@ static void display_init(void) { fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_GPIO13, &pin_GPIO15, NULL, false); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO14, // DC - &pin_GPIO5, // CS - &pin_GPIO12, // RST + MP_OBJ_FROM_PTR(&pin_GPIO14), // DC + MP_OBJ_FROM_PTR(&pin_GPIO5), // CS + MP_OBJ_FROM_PTR(&pin_GPIO12), // RST 10000000, // baudrate 0, // polarity 0 // phase diff --git a/ports/espressif/boards/m5stack_tab5/board.c b/ports/espressif/boards/m5stack_tab5/board.c new file mode 100644 index 00000000000..413009c05c0 --- /dev/null +++ b/ports/espressif/boards/m5stack_tab5/board.c @@ -0,0 +1,456 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" +#include "mpconfigboard.h" +#include "shared-bindings/board/__init__.h" +#include "shared-bindings/busio/I2C.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/mipidsi/Bus.h" +#include "shared-bindings/mipidsi/Display.h" +#include "shared-bindings/framebufferio/FramebufferDisplay.h" +#include "shared-module/displayio/__init__.h" +#include "shared-module/framebufferio/__init__.h" +#include "shared-module/framebufferio/FramebufferDisplay.h" +#include "ports/espressif/common-hal/microcontroller/Pin.h" + +// Statically allocate the MIPI DSI bus (only one DSI bus on ESP32-P4) +static mipidsi_bus_obj_t board_mipidsi_bus; + +// ILI9881C initialization sequence +static const uint8_t ili9881c_init_sequence[] = { + 0xff, 0x03, 0x98, 0x81, 0x00, + 0x01, 0x80, 0x78, // software reset + // CMD_Page 1 + 0xff, 0x03, 0x98, 0x81, 0x01, + 0xb7, 0x01, 0x03, // set 2 lane + // CMD Page 0 + 0xff, 0x03, 0x98, 0x81, 0x00, + 0x11, 0x80, 0x0a, // out of sleep + 0x36, 0x01, 0x00, // madctl + 0x3a, 0x01, 0x55, // colmod + // CMD_Page 3 + 0xff, 0x03, 0x98, 0x81, 0x03, + 0x01, 0x01, 0x00, + 0x02, 0x01, 0x00, + 0x03, 0x01, 0x73, + 0x04, 0x01, 0x00, + 0x05, 0x01, 0x00, + 0x06, 0x01, 0x08, + 0x07, 0x01, 0x00, + 0x08, 0x01, 0x00, + 0x09, 0x01, 0x1b, + 0x0a, 0x01, 0x01, + 0x0b, 0x01, 0x01, + 0x0c, 0x01, 0x0d, + 0x0d, 0x01, 0x01, + 0x0e, 0x01, 0x01, + 0x0f, 0x01, 0x26, + 0x10, 0x01, 0x26, + 0x11, 0x01, 0x00, + 0x12, 0x01, 0x00, + 0x13, 0x01, 0x02, + 0x14, 0x01, 0x00, + 0x15, 0x01, 0x00, + 0x16, 0x01, 0x00, + 0x17, 0x01, 0x00, + 0x18, 0x01, 0x00, + 0x19, 0x01, 0x00, + 0x1a, 0x01, 0x00, + 0x1b, 0x01, 0x00, + 0x1c, 0x01, 0x00, + 0x1d, 0x01, 0x00, + 0x1e, 0x01, 0x40, + 0x1f, 0x01, 0x00, + 0x20, 0x01, 0x06, + 0x21, 0x01, 0x01, + 0x22, 0x01, 0x00, + 0x23, 0x01, 0x00, + 0x24, 0x01, 0x00, + 0x25, 0x01, 0x00, + 0x26, 0x01, 0x00, + 0x27, 0x01, 0x00, + 0x28, 0x01, 0x33, + 0x29, 0x01, 0x03, + 0x2a, 0x01, 0x00, + 0x2b, 0x01, 0x00, + 0x2c, 0x01, 0x00, + 0x2d, 0x01, 0x00, + 0x2e, 0x01, 0x00, + 0x2f, 0x01, 0x00, + 0x30, 0x01, 0x00, + 0x31, 0x01, 0x00, + 0x32, 0x01, 0x00, + 0x33, 0x01, 0x00, + 0x34, 0x01, 0x00, + 0x35, 0x01, 0x00, + 0x36, 0x01, 0x00, + 0x37, 0x01, 0x00, + 0x38, 0x01, 0x00, + 0x39, 0x01, 0x00, + 0x3a, 0x01, 0x00, + 0x3b, 0x01, 0x00, + 0x3c, 0x01, 0x00, + 0x3d, 0x01, 0x00, + 0x3e, 0x01, 0x00, + 0x3f, 0x01, 0x00, + 0x40, 0x01, 0x00, + 0x41, 0x01, 0x00, + 0x42, 0x01, 0x00, + 0x43, 0x01, 0x00, + 0x44, 0x01, 0x00, + 0x50, 0x01, 0x01, + 0x51, 0x01, 0x23, + 0x52, 0x01, 0x45, + 0x53, 0x01, 0x67, + 0x54, 0x01, 0x89, + 0x55, 0x01, 0xab, + 0x56, 0x01, 0x01, + 0x57, 0x01, 0x23, + 0x58, 0x01, 0x45, + 0x59, 0x01, 0x67, + 0x5a, 0x01, 0x89, + 0x5b, 0x01, 0xab, + 0x5c, 0x01, 0xcd, + 0x5d, 0x01, 0xef, + 0x5e, 0x01, 0x11, + 0x5f, 0x01, 0x02, + 0x60, 0x01, 0x00, + 0x61, 0x01, 0x07, + 0x62, 0x01, 0x06, + 0x63, 0x01, 0x0e, + 0x64, 0x01, 0x0f, + 0x65, 0x01, 0x0c, + 0x66, 0x01, 0x0d, + 0x67, 0x01, 0x02, + 0x68, 0x01, 0x02, + 0x69, 0x01, 0x02, + 0x6a, 0x01, 0x02, + 0x6b, 0x01, 0x02, + 0x6c, 0x01, 0x02, + 0x6d, 0x01, 0x02, + 0x6e, 0x01, 0x02, + 0x6f, 0x01, 0x02, + 0x70, 0x01, 0x02, + 0x71, 0x01, 0x02, + 0x72, 0x01, 0x02, + 0x73, 0x01, 0x05, + 0x74, 0x01, 0x01, + 0x75, 0x01, 0x02, + 0x76, 0x01, 0x00, + 0x77, 0x01, 0x07, + 0x78, 0x01, 0x06, + 0x79, 0x01, 0x0e, + 0x7a, 0x01, 0x0f, + 0x7b, 0x01, 0x0c, + 0x7c, 0x01, 0x0d, + 0x7d, 0x01, 0x02, + 0x7e, 0x01, 0x02, + 0x7f, 0x01, 0x02, + 0x80, 0x01, 0x02, + 0x81, 0x01, 0x02, + 0x82, 0x01, 0x02, + 0x83, 0x01, 0x02, + 0x84, 0x01, 0x02, + 0x85, 0x01, 0x02, + 0x86, 0x01, 0x02, + 0x87, 0x01, 0x02, + 0x88, 0x01, 0x02, + 0x89, 0x01, 0x05, + 0x8a, 0x01, 0x01, + // CMD_Page 4 + 0xff, 0x03, 0x98, 0x81, 0x04, + 0x38, 0x01, 0x01, + 0x39, 0x01, 0x00, + 0x6c, 0x01, 0x15, + 0x6e, 0x01, 0x1a, + 0x6f, 0x01, 0x25, + 0x3a, 0x01, 0xa4, + 0x8d, 0x01, 0x20, + 0x87, 0x01, 0xba, + 0x3b, 0x01, 0x98, + // CMD_Page 1 + 0xff, 0x03, 0x98, 0x81, 0x01, + 0x22, 0x01, 0x0a, + 0x31, 0x01, 0x00, + 0x50, 0x01, 0x6b, + 0x51, 0x01, 0x66, + 0x53, 0x01, 0x73, + 0x55, 0x01, 0x8b, + 0x60, 0x01, 0x1b, + 0x61, 0x01, 0x01, + 0x62, 0x01, 0x0c, + 0x63, 0x01, 0x00, + // Gamma P + 0xa0, 0x01, 0x00, + 0xa1, 0x01, 0x15, + 0xa2, 0x01, 0x1f, + 0xa3, 0x01, 0x13, + 0xa4, 0x01, 0x11, + 0xa5, 0x01, 0x21, + 0xa6, 0x01, 0x17, + 0xa7, 0x01, 0x1b, + 0xa8, 0x01, 0x6b, + 0xa9, 0x01, 0x1e, + 0xaa, 0x01, 0x2b, + 0xab, 0x01, 0x5d, + 0xac, 0x01, 0x19, + 0xad, 0x01, 0x14, + 0xae, 0x01, 0x4b, + 0xaf, 0x01, 0x1d, + 0xb0, 0x01, 0x27, + 0xb1, 0x01, 0x49, + 0xb2, 0x01, 0x5d, + 0xb3, 0x01, 0x39, + // Gamma N + 0xc0, 0x01, 0x00, + 0xc1, 0x01, 0x01, + 0xc2, 0x01, 0x0c, + 0xc3, 0x01, 0x11, + 0xc4, 0x01, 0x15, + 0xc5, 0x01, 0x28, + 0xc6, 0x01, 0x1b, + 0xc7, 0x01, 0x1c, + 0xc8, 0x01, 0x62, + 0xc9, 0x01, 0x1c, + 0xca, 0x01, 0x29, + 0xcb, 0x01, 0x60, + 0xcc, 0x01, 0x16, + 0xcd, 0x01, 0x17, + 0xce, 0x01, 0x4a, + 0xcf, 0x01, 0x23, + 0xd0, 0x01, 0x24, + 0xd1, 0x01, 0x4f, + 0xd2, 0x01, 0x5f, + 0xd3, 0x01, 0x39, + // CMD_Page 0 + 0xff, 0x03, 0x98, 0x81, 0x00, + 0x35, 0x00, + 0xfe, 0x00, + 0x29, 0x00, +}; + +// ST7123 initialization sequence from M5Stack's Tab5 BSP: +// https://github.com/m5stack/M5Tab5-UserDemo/blob/main/platforms/tab5/components/m5stack_tab5/m5stack_tab5.c +static const uint8_t st7123_init_sequence[] = { + 0x60, 0x03, 0x71, 0x23, 0xa2, + 0x60, 0x03, 0x71, 0x23, 0xa3, + 0x60, 0x03, 0x71, 0x23, 0xa4, + 0xa4, 0x01, 0x31, + 0xd7, 0x06, 0x10, 0x0a, 0x10, 0x2a, 0x80, 0x80, + 0x90, 0x07, 0x71, 0x23, 0x5a, 0x20, 0x24, 0x09, 0x09, + 0xa3, 0x27, + 0x80, 0x01, 0x88, 0x30, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x46, 0x00, 0x00, 0x1e, 0x5c, 0x1e, 0x80, 0x00, 0x4f, 0x05, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x46, 0x00, 0x00, 0x1e, 0x5c, + 0x1e, 0x80, 0x00, 0x6f, 0x58, 0x00, 0x00, 0x00, 0xff, + 0xa6, 0x37, + 0x03, 0x00, 0x24, 0x55, 0x36, 0x00, 0x39, 0x00, 0x6e, 0x6e, + 0x91, 0xff, 0x00, 0x24, 0x55, 0x38, 0x00, 0x37, 0x00, 0x6e, + 0x6e, 0x91, 0xff, 0x00, 0x24, 0x11, 0x00, 0x00, 0x00, 0x00, + 0x6e, 0x6e, 0x91, 0xff, 0x00, 0xec, 0x11, 0x00, 0x03, 0x00, + 0x03, 0x6e, 0x6e, 0xff, 0xff, 0x00, 0x08, 0x80, 0x08, 0x80, + 0x06, 0x00, 0x00, 0x00, 0x00, + 0xa7, 0x3c, + 0x19, 0x19, 0x80, 0x64, 0x40, 0x07, 0x16, 0x40, 0x00, 0x44, + 0x03, 0x6e, 0x6e, 0x91, 0xff, 0x08, 0x80, 0x64, 0x40, 0x25, + 0x34, 0x40, 0x00, 0x02, 0x01, 0x6e, 0x6e, 0x91, 0xff, 0x08, + 0x80, 0x64, 0x40, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x6e, + 0x6e, 0x91, 0xff, 0x08, 0x80, 0x64, 0x40, 0x00, 0x00, 0x00, + 0x00, 0x20, 0x00, 0x6e, 0x6e, 0x84, 0xff, 0x08, 0x80, 0x44, + 0xac, 0x2c, + 0x03, 0x19, 0x19, 0x18, 0x18, 0x06, 0x13, 0x13, 0x11, 0x11, + 0x08, 0x08, 0x0a, 0x0a, 0x1c, 0x1c, 0x07, 0x07, 0x00, 0x00, + 0x02, 0x02, 0x01, 0x19, 0x19, 0x18, 0x18, 0x06, 0x12, 0x12, + 0x10, 0x10, 0x09, 0x09, 0x0b, 0x0b, 0x1c, 0x1c, 0x07, 0x07, + 0x03, 0x03, 0x01, 0x01, + 0xad, 0x19, + 0xf0, 0x00, 0x46, 0x00, 0x03, 0x50, 0x50, 0xff, 0xff, 0xf0, + 0x40, 0x06, 0x01, 0x07, 0x42, 0x42, 0xff, 0xff, 0x01, 0x00, + 0x00, 0xff, 0xff, 0xff, 0xff, + 0xae, 0x07, 0xfe, 0x3f, 0x3f, 0xfe, 0x3f, 0x3f, 0x00, + 0xb2, 0x11, + 0x15, 0x19, 0x05, 0x23, 0x49, 0xaf, 0x03, 0x2e, 0x5c, + 0xd2, 0xff, 0x10, 0x20, 0xfd, 0x20, 0xc0, 0x00, + 0xe8, 0x0e, + 0x20, 0x6f, 0x04, 0x97, 0x97, 0x3e, 0x04, 0xdc, + 0xdc, 0x3e, 0x06, 0xfa, 0x26, 0x3e, + 0x75, 0x02, 0x03, 0x04, + 0xe7, 0x24, + 0x3b, 0x00, 0x00, 0x7c, 0xa1, 0x8c, 0x20, 0x1a, 0xf0, 0xb1, + 0x50, 0x00, 0x50, 0xb1, 0x50, 0xb1, 0x50, 0xd8, 0x00, 0x55, + 0x00, 0xb1, 0x00, 0x45, 0xc9, 0x6a, 0xff, 0x5a, 0xd8, 0x18, + 0x88, 0x15, 0xb1, 0x01, 0x01, 0x77, + 0xea, 0x08, 0x13, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x2c, + 0xb0, 0x07, 0x22, 0x43, 0x11, 0x61, 0x25, 0x43, 0x43, + 0xb7, 0x04, 0x00, 0x00, 0x73, 0x73, + 0xbf, 0x02, 0xa6, 0xaa, + 0xa9, 0x0a, 0x00, 0x00, 0x73, 0xff, 0x00, 0x00, 0x03, 0x00, 0x00, 0x03, + 0xc8, 0x25, + 0x00, 0x00, 0x10, 0x1f, 0x36, 0x00, 0x5d, 0x04, 0x9d, 0x05, + 0x10, 0xf2, 0x06, 0x60, 0x03, 0x11, 0xad, 0x00, 0xef, 0x01, + 0x22, 0x2e, 0x0e, 0x74, 0x08, 0x32, 0xdc, 0x09, 0x33, 0x0f, + 0xf3, 0x77, 0x0d, 0xb0, 0xdc, 0x03, 0xff, + 0xc9, 0x25, + 0x00, 0x00, 0x10, 0x1f, 0x36, 0x00, 0x5d, 0x04, 0x9d, 0x05, + 0x10, 0xf2, 0x06, 0x60, 0x03, 0x11, 0xad, 0x00, 0xef, 0x01, + 0x22, 0x2e, 0x0e, 0x74, 0x08, 0x32, 0xdc, 0x09, 0x33, 0x0f, + 0xf3, 0x77, 0x0d, 0xb0, 0xdc, 0x03, 0xff, + 0x36, 0x01, 0x00, + 0x11, 0x81, 0x00, 100, + 0x29, 0x01, 0x00, + 0x35, 0x81, 0x00, 100, +}; + +// I2C addresses +#define GOODIX_TOUCH_ADDRESS 0x14 +#define ST7123_ADDRESS 0x55 +#define I2C_DEV_ADDR_PI4IOE1 0x43 + +// PI4IOE GPIO expander registers +#define PI4IO_REG_CHIP_RESET 0x01 +#define PI4IO_REG_IO_DIR 0x03 +#define PI4IO_REG_OUT_SET 0x05 +#define PI4IO_REG_OUT_H_IM 0x07 +#define PI4IO_REG_PULL_SEL 0x0D +#define PI4IO_REG_PULL_EN 0x0B + +void board_init(void) { + // Initialize I2C for GPIO expander and display detection + busio_i2c_obj_t *i2c = common_hal_board_create_i2c(0); + + // Initialize PI4IOE GPIO expander to control LCD reset + uint8_t write_buf[2]; + + common_hal_busio_i2c_try_lock(i2c); + + // Chip reset + write_buf[0] = PI4IO_REG_CHIP_RESET; + write_buf[1] = 0xFF; + common_hal_busio_i2c_write(i2c, I2C_DEV_ADDR_PI4IOE1, write_buf, 2); + + // LCD_RST is a 1.8V signal without an external pull-up. Do not drive it + // high with the expander's 3.3V push-pull output; use an input pull-up. + // Set pull select + write_buf[0] = PI4IO_REG_PULL_SEL; + write_buf[1] = 0b01111111; + common_hal_busio_i2c_write(i2c, I2C_DEV_ADDR_PI4IOE1, write_buf, 2); + + // Enable pull resistors + write_buf[0] = PI4IO_REG_PULL_EN; + write_buf[1] = 0b01111111; + common_hal_busio_i2c_write(i2c, I2C_DEV_ADDR_PI4IOE1, write_buf, 2); + + // Keep LCD_RST (P4) latched low, along with the other active-low resets. + write_buf[0] = PI4IO_REG_OUT_SET; + write_buf[1] = 0b01100110; + common_hal_busio_i2c_write(i2c, I2C_DEV_ADDR_PI4IOE1, write_buf, 2); + + // Set output high-impedance mode + write_buf[0] = PI4IO_REG_OUT_H_IM; + write_buf[1] = 0b00000000; + common_hal_busio_i2c_write(i2c, I2C_DEV_ADDR_PI4IOE1, write_buf, 2); + + // Assert LCD_RST by making P4 an output whose latch is low. + write_buf[0] = PI4IO_REG_IO_DIR; + write_buf[1] = 0b01111111; + common_hal_busio_i2c_write(i2c, I2C_DEV_ADDR_PI4IOE1, write_buf, 2); + mp_hal_delay_ms(10); + + // Release LCD_RST by switching P4 to an input with its pull-up enabled. + write_buf[0] = PI4IO_REG_IO_DIR; + write_buf[1] = 0b01101111; + common_hal_busio_i2c_write(i2c, I2C_DEV_ADDR_PI4IOE1, write_buf, 2); + mp_hal_delay_ms(50); + + // Probe I2C bus to detect which display is present + bool has_goodix = common_hal_busio_i2c_probe(i2c, GOODIX_TOUCH_ADDRESS); + bool has_st7123 = common_hal_busio_i2c_probe(i2c, ST7123_ADDRESS); + + common_hal_busio_i2c_unlock(i2c); + + // Configure display parameters based on detected hardware + uint32_t minimum_bus_frequency; + uint32_t pixel_clock_frequency; + const uint8_t *init_sequence; + size_t init_sequence_len; + uint32_t hsync_pulse_width, hsync_back_porch, hsync_front_porch; + uint32_t vsync_pulse_width, vsync_back_porch, vsync_front_porch; + + if (has_goodix) { + // ILI9881C display with Goodix touch + minimum_bus_frequency = 730000000; + pixel_clock_frequency = 60000000; + init_sequence = ili9881c_init_sequence; + init_sequence_len = sizeof(ili9881c_init_sequence); + hsync_pulse_width = 40; + hsync_back_porch = 140; + hsync_front_porch = 40; + vsync_pulse_width = 4; + vsync_back_porch = 20; + vsync_front_porch = 20; + } else if (has_st7123) { + // ST7123 display + minimum_bus_frequency = 965000000; + pixel_clock_frequency = 70000000; + init_sequence = st7123_init_sequence; + init_sequence_len = sizeof(st7123_init_sequence); + hsync_pulse_width = 2; + hsync_back_porch = 40; + hsync_front_porch = 40; + vsync_pulse_width = 2; + vsync_back_porch = 8; + vsync_front_porch = 220; + } else { + return; + } + + // Initialize the statically allocated MIPI DSI bus + board_mipidsi_bus.base.type = &mipidsi_bus_type; + common_hal_mipidsi_bus_construct(&board_mipidsi_bus, minimum_bus_frequency, 2); // 2 lanes + + // Allocate display bus for the display object + primary_display_bus_t *display_bus_obj = allocate_display_bus_or_raise(); + mipidsi_display_obj_t *display = &display_bus_obj->mipidsi; + display->base.type = &mipidsi_display_type; + + common_hal_mipidsi_display_construct( + display, + &board_mipidsi_bus, // Use statically allocated bus + init_sequence, + init_sequence_len, + 0, // virtual_channel + 720, // width + 1280, // height + 0, // rotation + 16, // color_depth + &pin_GPIO22, // backlight_pin (LCD_BL) + 0.1f, // brightness + 60, // native_frames_per_second + true, // backlight_on_high + hsync_pulse_width, + hsync_back_porch, + hsync_front_porch, + vsync_pulse_width, + vsync_back_porch, + vsync_front_porch, + pixel_clock_frequency, + true // low_power_blanking + ); + + // Create framebuffer display + framebufferio_framebufferdisplay_obj_t *fb_display = &allocate_display()->framebuffer_display; + fb_display->base.type = &framebufferio_framebufferdisplay_type; + + common_hal_framebufferio_framebufferdisplay_construct( + fb_display, + MP_OBJ_FROM_PTR(display), + 0, // rotation + true // auto_refresh + ); +} + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/m5stack_tab5/mpconfigboard.h b/ports/espressif/boards/m5stack_tab5/mpconfigboard.h new file mode 100644 index 00000000000..7047025f47a --- /dev/null +++ b/ports/espressif/boards/m5stack_tab5/mpconfigboard.h @@ -0,0 +1,27 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Micropython setup + +#define MICROPY_HW_BOARD_NAME "M5Stack Tab5" +#define MICROPY_HW_MCU_NAME "ESP32P4" + +// I2C bus for touch, IMU, RTC, power monitor, and GPIO expanders +#define CIRCUITPY_BOARD_I2C (1) +#define CIRCUITPY_BOARD_I2C_PIN {{.scl = &pin_GPIO32, .sda = &pin_GPIO31}} + +// UART +#define DEFAULT_UART_BUS_RX (&pin_GPIO38) +#define DEFAULT_UART_BUS_TX (&pin_GPIO37) + +// SPI on M5-Bus +#define DEFAULT_SPI_BUS_SCK (&pin_GPIO5) +#define DEFAULT_SPI_BUS_MOSI (&pin_GPIO18) +#define DEFAULT_SPI_BUS_MISO (&pin_GPIO19) + +#define CIRCUITPY_ESP32P4_SWAP_LSFS (1) diff --git a/ports/espressif/boards/m5stack_tab5/mpconfigboard.mk b/ports/espressif/boards/m5stack_tab5/mpconfigboard.mk new file mode 100644 index 00000000000..04cc84b7fc5 --- /dev/null +++ b/ports/espressif/boards/m5stack_tab5/mpconfigboard.mk @@ -0,0 +1,16 @@ +USB_VID = 0x303A +USB_PID = 0x832B +USB_PRODUCT = "M5Stack Tab5" +USB_MANUFACTURER = "M5Stack" + +IDF_TARGET = esp32p4 + +CIRCUITPY_USB_DEVICE_INSTANCE = FULL_SPEED_INSTANCE + +CIRCUITPY_ESP_FLASH_SIZE = 16MB +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m + +CIRCUITPY_ESP_PSRAM_SIZE = 32MB +CIRCUITPY_ESP_PSRAM_MODE = hpi +CIRCUITPY_ESP_PSRAM_FREQ = 200m diff --git a/ports/espressif/boards/m5stack_tab5/pins.c b/ports/espressif/boards/m5stack_tab5/pins.c new file mode 100644 index 00000000000..e486b2d0b1a --- /dev/null +++ b/ports/espressif/boards/m5stack_tab5/pins.c @@ -0,0 +1,132 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +#include "shared-module/displayio/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + // M5-Bus and general GPIO + { MP_ROM_QSTR(MP_QSTR_G2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_G3), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_G4), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_G6), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_G7), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_G16), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_G17), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_G35), MP_ROM_PTR(&pin_GPIO35) }, + { MP_ROM_QSTR(MP_QSTR_G45), MP_ROM_PTR(&pin_GPIO45) }, + { MP_ROM_QSTR(MP_QSTR_G47), MP_ROM_PTR(&pin_GPIO47) }, + { MP_ROM_QSTR(MP_QSTR_G48), MP_ROM_PTR(&pin_GPIO48) }, + { MP_ROM_QSTR(MP_QSTR_G51), MP_ROM_PTR(&pin_GPIO51) }, + { MP_ROM_QSTR(MP_QSTR_G52), MP_ROM_PTR(&pin_GPIO52) }, + + // SPI (on M5-Bus) + { MP_ROM_QSTR(MP_QSTR_G5), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_G18), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_G19), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO19) }, + + // UART (on M5-Bus) + { MP_ROM_QSTR(MP_QSTR_G37), MP_ROM_PTR(&pin_GPIO37) }, + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO37) }, + { MP_ROM_QSTR(MP_QSTR_TXD0), MP_ROM_PTR(&pin_GPIO37) }, + { MP_ROM_QSTR(MP_QSTR_G38), MP_ROM_PTR(&pin_GPIO38) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO38) }, + { MP_ROM_QSTR(MP_QSTR_RXD0), MP_ROM_PTR(&pin_GPIO38) }, + + // I2C (Touch, IMU, RTC, Power Monitor, GPIO Expanders) + { MP_ROM_QSTR(MP_QSTR_G31), MP_ROM_PTR(&pin_GPIO31) }, + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO31) }, + { MP_ROM_QSTR(MP_QSTR_G32), MP_ROM_PTR(&pin_GPIO32) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO32) }, + + // Touch Panel + { MP_ROM_QSTR(MP_QSTR_G23), MP_ROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_TP_INT), MP_ROM_PTR(&pin_GPIO23) }, + + // LCD + { MP_ROM_QSTR(MP_QSTR_G22), MP_ROM_PTR(&pin_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_LCD_BL), MP_ROM_PTR(&pin_GPIO22) }, + + // Audio ES8388/ES7210 + { MP_ROM_QSTR(MP_QSTR_G26), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_I2S_DSDIN), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_G27), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_I2S_SCLK), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_G28), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_I2S_ASDOUT), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_G29), MP_ROM_PTR(&pin_GPIO29) }, + { MP_ROM_QSTR(MP_QSTR_I2S_LRCK), MP_ROM_PTR(&pin_GPIO29) }, + { MP_ROM_QSTR(MP_QSTR_G30), MP_ROM_PTR(&pin_GPIO30) }, + { MP_ROM_QSTR(MP_QSTR_I2S_MCLK), MP_ROM_PTR(&pin_GPIO30) }, + + // Camera + { MP_ROM_QSTR(MP_QSTR_G36), MP_ROM_PTR(&pin_GPIO36) }, + { MP_ROM_QSTR(MP_QSTR_CAM_MCLK), MP_ROM_PTR(&pin_GPIO36) }, + + // microSD Card (SDIO mode) + { MP_ROM_QSTR(MP_QSTR_G39), MP_ROM_PTR(&pin_GPIO39) }, + { MP_ROM_QSTR(MP_QSTR_SD_DAT0), MP_ROM_PTR(&pin_GPIO39) }, + { MP_ROM_QSTR(MP_QSTR_SD_MISO), MP_ROM_PTR(&pin_GPIO39) }, + { MP_ROM_QSTR(MP_QSTR_G40), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_SD_DAT1), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_G41), MP_ROM_PTR(&pin_GPIO41) }, + { MP_ROM_QSTR(MP_QSTR_SD_DAT2), MP_ROM_PTR(&pin_GPIO41) }, + { MP_ROM_QSTR(MP_QSTR_G42), MP_ROM_PTR(&pin_GPIO42) }, + { MP_ROM_QSTR(MP_QSTR_SD_DAT3), MP_ROM_PTR(&pin_GPIO42) }, + { MP_ROM_QSTR(MP_QSTR_SD_CS), MP_ROM_PTR(&pin_GPIO42) }, + { MP_ROM_QSTR(MP_QSTR_G43), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_SD_CLK), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_SD_SCK), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_G44), MP_ROM_PTR(&pin_GPIO44) }, + { MP_ROM_QSTR(MP_QSTR_SD_CMD), MP_ROM_PTR(&pin_GPIO44) }, + { MP_ROM_QSTR(MP_QSTR_SD_MOSI), MP_ROM_PTR(&pin_GPIO44) }, + + // RS485 + { MP_ROM_QSTR(MP_QSTR_G20), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_RS485_TX), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_G21), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_RS485_RX), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_G34), MP_ROM_PTR(&pin_GPIO34) }, + { MP_ROM_QSTR(MP_QSTR_RS485_DIR), MP_ROM_PTR(&pin_GPIO34) }, + + // HY2.0-4P PORT.A + { MP_ROM_QSTR(MP_QSTR_G53), MP_ROM_PTR(&pin_GPIO53) }, + { MP_ROM_QSTR(MP_QSTR_PORTA_Y), MP_ROM_PTR(&pin_GPIO53) }, + { MP_ROM_QSTR(MP_QSTR_G54), MP_ROM_PTR(&pin_GPIO54) }, + { MP_ROM_QSTR(MP_QSTR_PORTA_W), MP_ROM_PTR(&pin_GPIO54) }, + + // ESP32-C6 SDIO interface + { MP_ROM_QSTR(MP_QSTR_G8), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_C6_SDIO2_D3), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_G9), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_C6_SDIO2_D2), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_G10), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_C6_SDIO2_D1), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_G11), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_C6_SDIO2_D0), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_G12), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_C6_SDIO2_CK), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_G13), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_C6_SDIO2_CMD), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_G14), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_C6_IO2), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_G15), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_C6_RESET), MP_ROM_PTR(&pin_GPIO15) }, + + // I2C and SPI 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_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/espressif/boards/m5stack_tab5/sdkconfig b/ports/espressif/boards/m5stack_tab5/sdkconfig new file mode 100644 index 00000000000..3bce8cc0c13 --- /dev/null +++ b/ports/espressif/boards/m5stack_tab5/sdkconfig @@ -0,0 +1,2 @@ +CONFIG_ESP32P4_SELECTS_REV_LESS_V3=y +CONFIG_ESP32P4_REV_MIN_100=y diff --git a/ports/espressif/boards/m5stack_timer_camera_x/board.c b/ports/espressif/boards/m5stack_timer_camera_x/board.c index 004aaa09281..299996d6f44 100755 --- a/ports/espressif/boards/m5stack_timer_camera_x/board.c +++ b/ports/espressif/boards/m5stack_timer_camera_x/board.c @@ -24,4 +24,10 @@ bool espressif_board_reset_pin_number(gpio_num_t pin_number) { return false; } +void board_init(void) { + // GPIO33 (BAT_HOLD) keeps the board on when USB is disconnected or the + // power button is released. Default to high (on). + espressif_board_reset_pin_number(33); +} + // Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/m5stack_timer_camera_x/mpconfigboard.mk b/ports/espressif/boards/m5stack_timer_camera_x/mpconfigboard.mk index 4fcacd94d3d..e17f5061d9e 100644 --- a/ports/espressif/boards/m5stack_timer_camera_x/mpconfigboard.mk +++ b/ports/espressif/boards/m5stack_timer_camera_x/mpconfigboard.mk @@ -10,5 +10,3 @@ CIRCUITPY_ESP_FLASH_SIZE = 4MB CIRCUITPY_ESP_PSRAM_SIZE = 8MB CIRCUITPY_ESP_PSRAM_MODE = opi CIRCUITPY_ESP_PSRAM_FREQ = 80m - -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 diff --git a/ports/espressif/boards/magiclick_s3_n4r2/mpconfigboard.mk b/ports/espressif/boards/magiclick_s3_n4r2/mpconfigboard.mk index 6c2159c6478..fe2eb2c7a76 100644 --- a/ports/espressif/boards/magiclick_s3_n4r2/mpconfigboard.mk +++ b/ports/espressif/boards/magiclick_s3_n4r2/mpconfigboard.mk @@ -14,5 +14,6 @@ CIRCUITPY_ESP_PSRAM_MODE = qio CIRCUITPY_ESP_PSRAM_FREQ = 80m CIRCUITPY_ESP_PSRAM_SIZE = 2MB +# No pins. CIRCUITPY_ESPCAMERA = 0 CIRCUITPY_DISPLAYIO = 1 diff --git a/ports/espressif/boards/maker_badge/mpconfigboard.mk b/ports/espressif/boards/maker_badge/mpconfigboard.mk index 979ae581e3d..13229c02dbf 100644 --- a/ports/espressif/boards/maker_badge/mpconfigboard.mk +++ b/ports/espressif/boards/maker_badge/mpconfigboard.mk @@ -3,14 +3,12 @@ USB_PID = 0x2030 USB_PRODUCT = "Maker badge" USB_MANUFACTURER = "Czech maker" -CIRCUITPY_ESPCAMERA = 0 +IDF_TARGET = esp32s2 CIRCUITPY_ESP_FLASH_MODE=dio CIRCUITPY_ESP_FLASH_FREQ=40m CIRCUITPY_ESP_FLASH_SIZE=4MB -IDF_TARGET = esp32s2 - FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_ConnectionManager FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_Requests FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel diff --git a/ports/espressif/boards/makerfabs_tft7/board.c b/ports/espressif/boards/makerfabs_tft7/board.c index dd0ffa26528..a994cfef381 100644 --- a/ports/espressif/boards/makerfabs_tft7/board.c +++ b/ports/espressif/boards/makerfabs_tft7/board.c @@ -6,13 +6,14 @@ #include "supervisor/board.h" #include "mpconfigboard.h" + #include "shared-bindings/board/__init__.h" #include "shared-bindings/dotclockframebuffer/DotClockFramebuffer.h" #include "shared-bindings/dotclockframebuffer/__init__.h" #include "shared-bindings/framebufferio/FramebufferDisplay.h" #include "shared-bindings/microcontroller/Pin.h" #include "shared-module/displayio/__init__.h" -#include "shared-module/os/__init__.h" +#include "supervisor/shared/settings.h" static const mcu_pin_obj_t *blue_pins[] = { &pin_GPIO8, @@ -40,14 +41,14 @@ static const mcu_pin_obj_t *red_pins[] = { static void display_init(void) { mp_int_t height = 0, width = 0, frequency = 0; - os_getenv_err_t result; + settings_err_t result; - result = common_hal_os_getenv_int("CIRCUITPY_DISPLAY_WIDTH", &width); - if (result == GETENV_OK && width == 800) { + result = settings_get_int("CIRCUITPY_DISPLAY_WIDTH", &width); + if (result == SETTINGS_OK && width == 800) { width = 800; height = 480; frequency = 6500000; - } else if (result == GETENV_OK && width == 1024) { + } else if (result == SETTINGS_OK && width == 1024) { width = 1024; height = 600; frequency = 10000000; diff --git a/ports/espressif/boards/makergo_esp32c3_supermini/mpconfigboard.mk b/ports/espressif/boards/makergo_esp32c3_supermini/mpconfigboard.mk index 37c27203af3..d82f62df377 100644 --- a/ports/espressif/boards/makergo_esp32c3_supermini/mpconfigboard.mk +++ b/ports/espressif/boards/makergo_esp32c3_supermini/mpconfigboard.mk @@ -7,6 +7,4 @@ CIRCUITPY_ESP_FLASH_MODE=dio CIRCUITPY_ESP_FLASH_FREQ=80m CIRCUITPY_ESP_FLASH_SIZE=4MB -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 - CIRCUITPY_ESP_USB_SERIAL_JTAG = 1 diff --git a/ports/espressif/boards/makergo_esp32c6_supermini/board.c b/ports/espressif/boards/makergo_esp32c6_supermini/board.c index 8cb7168e0da..5bcb2ee4693 100644 --- a/ports/espressif/boards/makergo_esp32c6_supermini/board.c +++ b/ports/espressif/boards/makergo_esp32c6_supermini/board.c @@ -19,4 +19,10 @@ bool espressif_board_reset_pin_number(gpio_num_t pin_number) { return false; } +void board_init(void) { + // GPIO15 (LED) drives an LED used as a power indicator. Default to high + // (on). + espressif_board_reset_pin_number(15); +} + // Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/makergo_esp32c6_supermini/mpconfigboard.h b/ports/espressif/boards/makergo_esp32c6_supermini/mpconfigboard.h index ed8dec14f0a..0d17aef1109 100644 --- a/ports/espressif/boards/makergo_esp32c6_supermini/mpconfigboard.h +++ b/ports/espressif/boards/makergo_esp32c6_supermini/mpconfigboard.h @@ -17,3 +17,6 @@ // Default bus pins #define DEFAULT_UART_BUS_TX (&pin_GPIO17) #define DEFAULT_UART_BUS_RX (&pin_GPIO16) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/makergo_esp32c6_supermini/mpconfigboard.mk b/ports/espressif/boards/makergo_esp32c6_supermini/mpconfigboard.mk index 54078559d7b..ca425c01593 100644 --- a/ports/espressif/boards/makergo_esp32c6_supermini/mpconfigboard.mk +++ b/ports/espressif/boards/makergo_esp32c6_supermini/mpconfigboard.mk @@ -6,3 +6,6 @@ IDF_TARGET = esp32c6 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB + +# Board was originally defined with a 2MB firmware, almost 2MB user filesystem. Leave it that way. +CIRCUITPY_4MB_FLASH_LARGE_USER_FS_LAYOUT = 1 diff --git a/ports/espressif/boards/microdev_micro_c3/mpconfigboard.mk b/ports/espressif/boards/microdev_micro_c3/mpconfigboard.mk index b2ea6005db5..79821f7c0e5 100644 --- a/ports/espressif/boards/microdev_micro_c3/mpconfigboard.mk +++ b/ports/espressif/boards/microdev_micro_c3/mpconfigboard.mk @@ -7,6 +7,4 @@ CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 - CIRCUITPY_ESP_USB_SERIAL_JTAG = 1 diff --git a/ports/espressif/boards/microdev_micro_s2/mpconfigboard.h b/ports/espressif/boards/microdev_micro_s2/mpconfigboard.h index b7b327b23d3..db2d353f998 100644 --- a/ports/espressif/boards/microdev_micro_s2/mpconfigboard.h +++ b/ports/espressif/boards/microdev_micro_s2/mpconfigboard.h @@ -25,3 +25,6 @@ #define DEFAULT_UART_BUS_TX (&pin_GPIO43) #define DEFAULT_UART_BUS_RX (&pin_GPIO44) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/microdev_micro_s2/mpconfigboard.mk b/ports/espressif/boards/microdev_micro_s2/mpconfigboard.mk index c090c69aac7..fe5ea4a7da1 100644 --- a/ports/espressif/boards/microdev_micro_s2/mpconfigboard.mk +++ b/ports/espressif/boards/microdev_micro_s2/mpconfigboard.mk @@ -12,3 +12,9 @@ CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_PSRAM_SIZE = 8MB CIRCUITPY_ESP_PSRAM_MODE = qio CIRCUITPY_ESP_PSRAM_FREQ = 80m + +# Out of internal RAM with audiopwmio +CIRCUITPY_AUDIOPWMIO = 0 + +# Fast e-paper doesn't fit in internal RAM. +CIRCUITPY_EPAPERDISPLAY_FAST = 0 diff --git a/ports/espressif/boards/mixgo_ce_serial/board.c b/ports/espressif/boards/mixgo_ce_serial/board.c index e83f3b69679..e0d9f9530f2 100644 --- a/ports/espressif/boards/mixgo_ce_serial/board.c +++ b/ports/espressif/boards/mixgo_ce_serial/board.c @@ -16,8 +16,8 @@ void board_init(void) { mp_import_stat_t stat_b = mp_import_stat("boot.py"); if (stat_b != MP_IMPORT_STAT_FILE) { - fs_user_mount_t *fs_mount = filesystem_circuitpy(); - FATFS *fatfs = &fs_mount->fatfs; + supervisor_vfs_t *fs_mount = filesystem_circuitpy(); + FATFS *fatfs = &fs_mount->fat.fatfs; FIL fs; UINT char_written = 0; const byte buffer[] = "#Serial port upload mode\nimport storage\nstorage.remount(\"/\", False)\nstorage.disable_usb_drive()\n"; diff --git a/ports/espressif/boards/mixgo_ce_serial/mpconfigboard.mk b/ports/espressif/boards/mixgo_ce_serial/mpconfigboard.mk index 1d370fd30e7..9b96aa31c9e 100644 --- a/ports/espressif/boards/mixgo_ce_serial/mpconfigboard.mk +++ b/ports/espressif/boards/mixgo_ce_serial/mpconfigboard.mk @@ -9,12 +9,6 @@ CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB -CIRCUITPY_AESIO = 0 -CIRCUITPY_AUDIOBUSIO = 0 -CIRCUITPY_CANIO = 0 -CIRCUITPY_CODEOP = 0 -CIRCUITPY_ESPCAMERA = 0 - FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_ConnectionManager FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_Requests FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel diff --git a/ports/espressif/boards/mixgo_ce_udisk/mpconfigboard.mk b/ports/espressif/boards/mixgo_ce_udisk/mpconfigboard.mk index 691da625e03..d6447ee7134 100644 --- a/ports/espressif/boards/mixgo_ce_udisk/mpconfigboard.mk +++ b/ports/espressif/boards/mixgo_ce_udisk/mpconfigboard.mk @@ -9,10 +9,6 @@ CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB -CIRCUITPY_AESIO = 0 -CIRCUITPY_CODEOP = 0 -CIRCUITPY_ESPCAMERA = 0 - FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_ConnectionManager FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_Requests FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel diff --git a/ports/espressif/boards/morpheans_morphesp-240/board.c b/ports/espressif/boards/morpheans_morphesp-240/board.c index 5b1c3f82bbb..ad096439f26 100644 --- a/ports/espressif/boards/morpheans_morphesp-240/board.c +++ b/ports/espressif/boards/morpheans_morphesp-240/board.c @@ -131,16 +131,14 @@ void board_init(void) { NULL, // MISO not connected false); // Not half-duplex - common_hal_busio_spi_never_reset(spi); - bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO14, // DC - &pin_GPIO10, // CS - &pin_GPIO9, // RST + MP_OBJ_FROM_PTR(&pin_GPIO14), // DC + MP_OBJ_FROM_PTR(&pin_GPIO10), // CS + MP_OBJ_FROM_PTR(&pin_GPIO9), // RST 40000000, // baudrate 0, // polarity 0 // phase diff --git a/ports/espressif/boards/morpheans_morphesp-240/mpconfigboard.mk b/ports/espressif/boards/morpheans_morphesp-240/mpconfigboard.mk index 8a6b359d238..5c806cb69b2 100644 --- a/ports/espressif/boards/morpheans_morphesp-240/mpconfigboard.mk +++ b/ports/espressif/boards/morpheans_morphesp-240/mpconfigboard.mk @@ -8,4 +8,3 @@ IDF_TARGET = esp32s2 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/muselab_nanoesp32_s2_wroom/mpconfigboard.mk b/ports/espressif/boards/muselab_nanoesp32_s2_wroom/mpconfigboard.mk index bb3c0ea4d82..b2540a8c3b8 100644 --- a/ports/espressif/boards/muselab_nanoesp32_s2_wroom/mpconfigboard.mk +++ b/ports/espressif/boards/muselab_nanoesp32_s2_wroom/mpconfigboard.mk @@ -8,4 +8,3 @@ IDF_TARGET = esp32s2 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/nhbsystems_jl401_4mbflash_2mbpsram/board.c b/ports/espressif/boards/nhbsystems_jl401_4mbflash_2mbpsram/board.c new file mode 100755 index 00000000000..e2517f8640a --- /dev/null +++ b/ports/espressif/boards/nhbsystems_jl401_4mbflash_2mbpsram/board.c @@ -0,0 +1,26 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" +#include "mpconfigboard.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "driver/gpio.h" + +void board_init(void) { + reset_board(); +} + +void reset_board(void) { + // Turn on I2C power by default. + gpio_set_direction(14, GPIO_MODE_DEF_OUTPUT); + gpio_set_level(14, true); + + // Turn on SD power by default + gpio_set_direction(3, GPIO_MODE_DEF_OUTPUT); + gpio_set_level(3, true); +} + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/nhbsystems_jl401_4mbflash_2mbpsram/mpconfigboard.h b/ports/espressif/boards/nhbsystems_jl401_4mbflash_2mbpsram/mpconfigboard.h new file mode 100755 index 00000000000..c3181ea9431 --- /dev/null +++ b/ports/espressif/boards/nhbsystems_jl401_4mbflash_2mbpsram/mpconfigboard.h @@ -0,0 +1,36 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Micropython setup + +#define MICROPY_HW_BOARD_NAME "NHB Systems JL401-S3 4MB Flash 2MB PSRAM" +#define MICROPY_HW_MCU_NAME "ESP32S3" + +#define MICROPY_HW_NEOPIXEL (&pin_GPIO1) +#define CIRCUITPY_STATUS_LED_POWER (&pin_GPIO2) + +// #define MICROPY_HW_LED_STATUS (&pin_GPIO13) + +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO48) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO47) + +#define DEFAULT_SPI_BUS_SCK (&pin_GPIO12) +#define DEFAULT_SPI_BUS_MOSI (&pin_GPIO11) +#define DEFAULT_SPI_BUS_MISO (&pin_GPIO13) + +#define DEFAULT_UART_BUS_RX (&pin_GPIO18) +#define DEFAULT_UART_BUS_TX (&pin_GPIO17) + +#define DOUBLE_TAP_PIN (&pin_GPIO38) + +#define DEFAULT_SD_SCK (&pin_GPIO12) +#define DEFAULT_SD_MOSI (&pin_GPIO11) +#define DEFAULT_SD_MISO (&pin_GPIO13) +#define DEFAULT_SD_CS (&pin_GPIO10) +#define DEFAULT_SD_CARD_DETECT (&pin_GPIO9) +#define DEFAULT_SD_CARD_INSERTED true diff --git a/ports/espressif/boards/nhbsystems_jl401_4mbflash_2mbpsram/mpconfigboard.mk b/ports/espressif/boards/nhbsystems_jl401_4mbflash_2mbpsram/mpconfigboard.mk new file mode 100755 index 00000000000..fdc981fdccc --- /dev/null +++ b/ports/espressif/boards/nhbsystems_jl401_4mbflash_2mbpsram/mpconfigboard.mk @@ -0,0 +1,14 @@ +USB_VID = 0x303A +USB_PID = 0x834A +USB_PRODUCT = "NHB Systems JL401-S3 4MB Flash 2MB PSRAM" +USB_MANUFACTURER = "NHB Systems" + +IDF_TARGET = esp32s3 + +CIRCUITPY_ESP_FLASH_SIZE = 4MB +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m + +CIRCUITPY_ESP_PSRAM_SIZE = 2MB +CIRCUITPY_ESP_PSRAM_MODE = qio +CIRCUITPY_ESP_PSRAM_FREQ = 80m diff --git a/ports/espressif/boards/nhbsystems_jl401_4mbflash_2mbpsram/pins.c b/ports/espressif/boards/nhbsystems_jl401_4mbflash_2mbpsram/pins.c new file mode 100644 index 00000000000..111659bee61 --- /dev/null +++ b/ports/espressif/boards/nhbsystems_jl401_4mbflash_2mbpsram/pins.c @@ -0,0 +1,89 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { MP_ROM_QSTR(MP_QSTR_BUTTON), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_BOOT0), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_GPIO0) }, + + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL_POWER), MP_ROM_PTR(&pin_GPIO2) }, + + { MP_ROM_QSTR(MP_QSTR_SD_PWR), MP_ROM_PTR(&pin_GPIO3)}, + { 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_A5), MP_ROM_PTR(&pin_GPIO8) }, + { 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_LED), MP_ROM_PTR(&pin_GPIO13) }, + // { MP_ROM_QSTR(MP_QSTR_L), MP_ROM_PTR(&pin_GPIO13) }, + + { MP_ROM_QSTR(MP_QSTR_I2C_POWER), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_D14), MP_ROM_PTR(&pin_GPIO14) }, + + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_GPIO15) }, + + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_D16), MP_ROM_PTR(&pin_GPIO16) }, + + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_D17), MP_ROM_PTR(&pin_GPIO17) }, + + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_D18), MP_ROM_PTR(&pin_GPIO18) }, + + { MP_ROM_QSTR(MP_QSTR_D21), MP_ROM_PTR(&pin_GPIO21) }, + + { MP_OBJ_NEW_QSTR(MP_QSTR_SD_CS), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_GPIO10) }, + + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_GPIO11) }, + + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_GPIO12) }, + + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_GPIO13) }, + + // D33 to D36 used for AD7124 SPI + { MP_ROM_QSTR(MP_QSTR_D33), MP_ROM_PTR(&pin_GPIO33) }, + { MP_ROM_QSTR(MP_QSTR_D34), MP_ROM_PTR(&pin_GPIO34) }, + { MP_ROM_QSTR(MP_QSTR_D35), MP_ROM_PTR(&pin_GPIO35) }, + { MP_ROM_QSTR(MP_QSTR_D36), MP_ROM_PTR(&pin_GPIO36) }, + + { MP_ROM_QSTR(MP_QSTR_D37), MP_ROM_PTR(&pin_GPIO37) }, + // { MP_ROM_QSTR(MP_QSTR_D38), MP_ROM_PTR(&pin_GPIO38) }, + { MP_ROM_QSTR(MP_QSTR_D39), MP_ROM_PTR(&pin_GPIO39) }, + + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_D43), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO44) }, + { MP_ROM_QSTR(MP_QSTR_D44), MP_ROM_PTR(&pin_GPIO44) }, + + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO47) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO48) }, + + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, + { MP_ROM_QSTR(MP_QSTR_STEMMA_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_module_globals_table); diff --git a/ports/espressif/boards/nhbsystems_jl401_4mbflash_2mbpsram/sdkconfig b/ports/espressif/boards/nhbsystems_jl401_4mbflash_2mbpsram/sdkconfig new file mode 100755 index 00000000000..e9628662160 --- /dev/null +++ b/ports/espressif/boards/nhbsystems_jl401_4mbflash_2mbpsram/sdkconfig @@ -0,0 +1,14 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Component config +# +# +# LWIP +# +# end of LWIP + +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/boards/nodemcu_esp32c2/mpconfigboard.mk b/ports/espressif/boards/nodemcu_esp32c2/mpconfigboard.mk index dd90b325b6d..249dd80bebd 100644 --- a/ports/espressif/boards/nodemcu_esp32c2/mpconfigboard.mk +++ b/ports/espressif/boards/nodemcu_esp32c2/mpconfigboard.mk @@ -6,3 +6,6 @@ IDF_TARGET = esp32c2 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 60m CIRCUITPY_ESP_FLASH_SIZE = 4MB + +# Board was originally defined with a 2MB firmware, almost 2MB user filesystem. Leave it that way. +CIRCUITPY_4MB_FLASH_LARGE_USER_FS_LAYOUT = 1 diff --git a/ports/espressif/boards/oxocard_artwork/board.c b/ports/espressif/boards/oxocard_artwork/board.c index 600bc0c5943..8fbf7d46730 100644 --- a/ports/espressif/boards/oxocard_artwork/board.c +++ b/ports/espressif/boards/oxocard_artwork/board.c @@ -36,16 +36,14 @@ static void display_init(void) { &pin_GPIO12, // MISO false); // Not half-duplex - common_hal_busio_spi_never_reset(spi); - bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO27, // DC - &pin_GPIO15, // CS - &pin_GPIO4, // RST + MP_OBJ_FROM_PTR(&pin_GPIO27), // DC + MP_OBJ_FROM_PTR(&pin_GPIO15), // CS + MP_OBJ_FROM_PTR(&pin_GPIO4), // RST 24000000, // baudrate 0, // polarity 0 // phase @@ -60,7 +58,7 @@ static void display_init(void) { 240, // width (after rotation) 240, // height (after rotation) 0, // column start - 80, // row start + 0, // row start 0, // rotation 16, // color depth false, // grayscale diff --git a/ports/espressif/boards/oxocard_artwork/mpconfigboard.mk b/ports/espressif/boards/oxocard_artwork/mpconfigboard.mk index a7dfe8b8e33..61367774a21 100644 --- a/ports/espressif/boards/oxocard_artwork/mpconfigboard.mk +++ b/ports/espressif/boards/oxocard_artwork/mpconfigboard.mk @@ -10,5 +10,3 @@ CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_PSRAM_SIZE = 2MB CIRCUITPY_ESP_PSRAM_MODE = qio CIRCUITPY_ESP_PSRAM_FREQ = 80m - -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/oxocard_connect/board.c b/ports/espressif/boards/oxocard_connect/board.c index 89be45c8226..a0ef3cdec68 100644 --- a/ports/espressif/boards/oxocard_connect/board.c +++ b/ports/espressif/boards/oxocard_connect/board.c @@ -37,16 +37,14 @@ static void display_init(void) { &pin_GPIO12, // MISO false); // Not half-duplex - common_hal_busio_spi_never_reset(spi); - bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO27, // DC - &pin_GPIO15, // CS - &pin_GPIO4, // RST + MP_OBJ_FROM_PTR(&pin_GPIO27), // DC + MP_OBJ_FROM_PTR(&pin_GPIO15), // CS + MP_OBJ_FROM_PTR(&pin_GPIO4), // RST 24000000, // baudrate 0, // polarity 0 // phase diff --git a/ports/espressif/boards/oxocard_connect/mpconfigboard.mk b/ports/espressif/boards/oxocard_connect/mpconfigboard.mk index 49b8a4f4c87..ea00787921d 100644 --- a/ports/espressif/boards/oxocard_connect/mpconfigboard.mk +++ b/ports/espressif/boards/oxocard_connect/mpconfigboard.mk @@ -10,5 +10,3 @@ CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_PSRAM_SIZE = 2MB CIRCUITPY_ESP_PSRAM_MODE = qio CIRCUITPY_ESP_PSRAM_FREQ = 80m - -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/oxocard_galaxy/board.c b/ports/espressif/boards/oxocard_galaxy/board.c index 600bc0c5943..8fbf7d46730 100644 --- a/ports/espressif/boards/oxocard_galaxy/board.c +++ b/ports/espressif/boards/oxocard_galaxy/board.c @@ -36,16 +36,14 @@ static void display_init(void) { &pin_GPIO12, // MISO false); // Not half-duplex - common_hal_busio_spi_never_reset(spi); - bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO27, // DC - &pin_GPIO15, // CS - &pin_GPIO4, // RST + MP_OBJ_FROM_PTR(&pin_GPIO27), // DC + MP_OBJ_FROM_PTR(&pin_GPIO15), // CS + MP_OBJ_FROM_PTR(&pin_GPIO4), // RST 24000000, // baudrate 0, // polarity 0 // phase @@ -60,7 +58,7 @@ static void display_init(void) { 240, // width (after rotation) 240, // height (after rotation) 0, // column start - 80, // row start + 0, // row start 0, // rotation 16, // color depth false, // grayscale diff --git a/ports/espressif/boards/oxocard_galaxy/mpconfigboard.mk b/ports/espressif/boards/oxocard_galaxy/mpconfigboard.mk index 915d7cc5862..e4786df383c 100644 --- a/ports/espressif/boards/oxocard_galaxy/mpconfigboard.mk +++ b/ports/espressif/boards/oxocard_galaxy/mpconfigboard.mk @@ -10,5 +10,3 @@ CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_PSRAM_SIZE = 2MB CIRCUITPY_ESP_PSRAM_MODE = qio CIRCUITPY_ESP_PSRAM_FREQ = 80m - -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/oxocard_science/board.c b/ports/espressif/boards/oxocard_science/board.c index 600bc0c5943..8fbf7d46730 100644 --- a/ports/espressif/boards/oxocard_science/board.c +++ b/ports/espressif/boards/oxocard_science/board.c @@ -36,16 +36,14 @@ static void display_init(void) { &pin_GPIO12, // MISO false); // Not half-duplex - common_hal_busio_spi_never_reset(spi); - bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO27, // DC - &pin_GPIO15, // CS - &pin_GPIO4, // RST + MP_OBJ_FROM_PTR(&pin_GPIO27), // DC + MP_OBJ_FROM_PTR(&pin_GPIO15), // CS + MP_OBJ_FROM_PTR(&pin_GPIO4), // RST 24000000, // baudrate 0, // polarity 0 // phase @@ -60,7 +58,7 @@ static void display_init(void) { 240, // width (after rotation) 240, // height (after rotation) 0, // column start - 80, // row start + 0, // row start 0, // rotation 16, // color depth false, // grayscale diff --git a/ports/espressif/boards/oxocard_science/mpconfigboard.mk b/ports/espressif/boards/oxocard_science/mpconfigboard.mk index d31be7d7992..9d89108f392 100644 --- a/ports/espressif/boards/oxocard_science/mpconfigboard.mk +++ b/ports/espressif/boards/oxocard_science/mpconfigboard.mk @@ -10,5 +10,3 @@ CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_PSRAM_SIZE = 2MB CIRCUITPY_ESP_PSRAM_MODE = qio CIRCUITPY_ESP_PSRAM_FREQ = 80m - -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/pcbcupid_glyph_c3/board.c b/ports/espressif/boards/pcbcupid_glyph_c3/board.c new file mode 100644 index 00000000000..8bc15c17551 --- /dev/null +++ b/ports/espressif/boards/pcbcupid_glyph_c3/board.c @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 PCBCupid +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/pcbcupid_glyph_c3/mpconfigboard.h b/ports/espressif/boards/pcbcupid_glyph_c3/mpconfigboard.h new file mode 100644 index 00000000000..064559a4dc8 --- /dev/null +++ b/ports/espressif/boards/pcbcupid_glyph_c3/mpconfigboard.h @@ -0,0 +1,19 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 PCBCupid +// +// SPDX-License-Identifier: MIT +#pragma once + +#define MICROPY_HW_BOARD_NAME "PCBCupid GLYPH C3" +#define MICROPY_HW_MCU_NAME "ESP32-C3" + +#define MICROPY_HW_LED_STATUS (&pin_GPIO1) + +#define DEFAULT_UART_BUS_TX (&pin_GPIO21) +#define DEFAULT_UART_BUS_RX (&pin_GPIO20) + +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO5) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO4) + +#define DEFAULT_SPI_BUS_SCK (&pin_GPIO10) +#define DEFAULT_SPI_BUS_MOSI (&pin_GPIO6) +#define DEFAULT_SPI_BUS_MISO (&pin_GPIO7) diff --git a/ports/espressif/boards/pcbcupid_glyph_c3/mpconfigboard.mk b/ports/espressif/boards/pcbcupid_glyph_c3/mpconfigboard.mk new file mode 100644 index 00000000000..dea0619ee7e --- /dev/null +++ b/ports/espressif/boards/pcbcupid_glyph_c3/mpconfigboard.mk @@ -0,0 +1,10 @@ +CIRCUITPY_CREATOR_ID = 0x20241402 +CIRCUITPY_CREATION_ID = 0x00C30001 + +IDF_TARGET = esp32c3 + +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m +CIRCUITPY_ESP_FLASH_SIZE = 4MB + +CIRCUITPY_ESP_USB_SERIAL_JTAG = 1 diff --git a/ports/espressif/boards/pcbcupid_glyph_c3/pins.c b/ports/espressif/boards/pcbcupid_glyph_c3/pins.c new file mode 100644 index 00000000000..2d15da17bd9 --- /dev/null +++ b/ports/espressif/boards/pcbcupid_glyph_c3/pins.c @@ -0,0 +1,36 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 PCBCupid +// +// SPDX-License-Identifier: MIT +#include "shared-bindings/board/__init__.h" +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + { 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_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_RX), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO21) }, + { 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_MOSI), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_MTMS), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_MTDI), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_MTCK), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_MTDO), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/espressif/boards/pcbcupid_glyph_c3/sdkconfig b/ports/espressif/boards/pcbcupid_glyph_c3/sdkconfig new file mode 100644 index 00000000000..e9628662160 --- /dev/null +++ b/ports/espressif/boards/pcbcupid_glyph_c3/sdkconfig @@ -0,0 +1,14 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Component config +# +# +# LWIP +# +# end of LWIP + +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/boards/pcbcupid_glyph_c6/board.c b/ports/espressif/boards/pcbcupid_glyph_c6/board.c new file mode 100644 index 00000000000..3c254a05417 --- /dev/null +++ b/ports/espressif/boards/pcbcupid_glyph_c6/board.c @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 PCBCupid +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/pcbcupid_glyph_c6/mpconfigboard.h b/ports/espressif/boards/pcbcupid_glyph_c6/mpconfigboard.h new file mode 100644 index 00000000000..6c83a0f4ecb --- /dev/null +++ b/ports/espressif/boards/pcbcupid_glyph_c6/mpconfigboard.h @@ -0,0 +1,18 @@ +#pragma once + +#define MICROPY_HW_BOARD_NAME "Pcbcupid GLYPH C6" +#define MICROPY_HW_MCU_NAME "ESP32-C6" + +#define MICROPY_HW_LED_STATUS (&pin_GPIO14) + +#define DEFAULT_UART_BUS_TX (&pin_GPIO16) +#define DEFAULT_UART_BUS_RX (&pin_GPIO17) + +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO5) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO4) + +#define DEFAULT_SPI_BUS_SCK (&pin_GPIO21) +#define DEFAULT_SPI_BUS_MOSI (&pin_GPIO22) +#define DEFAULT_SPI_BUS_MISO (&pin_GPIO23) + +#define CIRCUITPY_BOOT_BUTTON (&pin_GPIO9) diff --git a/ports/espressif/boards/pcbcupid_glyph_c6/mpconfigboard.mk b/ports/espressif/boards/pcbcupid_glyph_c6/mpconfigboard.mk new file mode 100644 index 00000000000..8c2e6d74453 --- /dev/null +++ b/ports/espressif/boards/pcbcupid_glyph_c6/mpconfigboard.mk @@ -0,0 +1,10 @@ +CIRCUITPY_CREATOR_ID = 0x20241402 +CIRCUITPY_CREATION_ID = 0x00C60001 + +IDF_TARGET = esp32c6 + +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m +CIRCUITPY_ESP_FLASH_SIZE = 4MB + +CIRCUITPY_ESP_USB_SERIAL_JTAG = 1 diff --git a/ports/espressif/boards/pcbcupid_glyph_c6/pins.c b/ports/espressif/boards/pcbcupid_glyph_c6/pins.c new file mode 100644 index 00000000000..c2a4db30854 --- /dev/null +++ b/ports/espressif/boards/pcbcupid_glyph_c6/pins.c @@ -0,0 +1,56 @@ +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { MP_ROM_QSTR(MP_QSTR_BOOT), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO14) }, + + { 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_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_IO22), MP_ROM_PTR(&pin_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_IO23), MP_ROM_PTR(&pin_GPIO23) }, + + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO3) }, + + { 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_D14), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_D18), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_D19), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_D20), MP_ROM_PTR(&pin_GPIO20) }, + + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO4) }, + + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO23) }, + + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/espressif/boards/pcbcupid_glyph_c6/sdkconfig b/ports/espressif/boards/pcbcupid_glyph_c6/sdkconfig new file mode 100644 index 00000000000..e9628662160 --- /dev/null +++ b/ports/espressif/boards/pcbcupid_glyph_c6/sdkconfig @@ -0,0 +1,14 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Component config +# +# +# LWIP +# +# end of LWIP + +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/boards/pcbcupid_glyph_h2/board.c b/ports/espressif/boards/pcbcupid_glyph_h2/board.c new file mode 100644 index 00000000000..4e6bc405957 --- /dev/null +++ b/ports/espressif/boards/pcbcupid_glyph_h2/board.c @@ -0,0 +1,7 @@ +// SPDX-FileCopyrightText: Copyright (c) 2024 PCBCupid +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/pcbcupid_glyph_h2/mpconfigboard.h b/ports/espressif/boards/pcbcupid_glyph_h2/mpconfigboard.h new file mode 100644 index 00000000000..0060381696e --- /dev/null +++ b/ports/espressif/boards/pcbcupid_glyph_h2/mpconfigboard.h @@ -0,0 +1,20 @@ +// SPDX-FileCopyrightText: Copyright (c) 2024 PCBCupid +// +// SPDX-License-Identifier: MIT + +#pragma once + +#define MICROPY_HW_BOARD_NAME "Pcbcupid GLYPH H2" +#define MICROPY_HW_MCU_NAME "ESP32H2" + +#define MICROPY_HW_LED_STATUS (&pin_GPIO0) + +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO5) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO4) + +#define DEFAULT_SPI_BUS_SCK (&pin_GPIO11) +#define DEFAULT_SPI_BUS_MOSI (&pin_GPIO22) +#define DEFAULT_SPI_BUS_MISO (&pin_GPIO25) + +#define DEFAULT_UART_BUS_RX (&pin_GPIO23) +#define DEFAULT_UART_BUS_TX (&pin_GPIO24) diff --git a/ports/espressif/boards/pcbcupid_glyph_h2/mpconfigboard.mk b/ports/espressif/boards/pcbcupid_glyph_h2/mpconfigboard.mk new file mode 100644 index 00000000000..4acde24d6f6 --- /dev/null +++ b/ports/espressif/boards/pcbcupid_glyph_h2/mpconfigboard.mk @@ -0,0 +1,11 @@ +CIRCUITPY_CREATOR_ID = 0x20241402 +CIRCUITPY_CREATION_ID = 0x00110001 + +IDF_TARGET = esp32h2 + +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 48m +CIRCUITPY_ESP_FLASH_SIZE = 4MB +CIRCUITPY_4MB_FLASH_LARGE_USER_FS_LAYOUT = 1 + +CIRCUITPY_ESP_USB_SERIAL_JTAG = 1 diff --git a/ports/espressif/boards/pcbcupid_glyph_h2/pins.c b/ports/espressif/boards/pcbcupid_glyph_h2/pins.c new file mode 100644 index 00000000000..550ba4e3101 --- /dev/null +++ b/ports/espressif/boards/pcbcupid_glyph_h2/pins.c @@ -0,0 +1,62 @@ +// SPDX-FileCopyrightText: Copyright (c) 2024 PCBCupid +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { MP_ROM_QSTR(MP_QSTR_BOOT), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO0) }, + + + { 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_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_IO22), MP_ROM_PTR(&pin_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_IO23), MP_ROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_IO24), MP_ROM_PTR(&pin_GPIO24) }, + { MP_ROM_QSTR(MP_QSTR_IO25), MP_ROM_PTR(&pin_GPIO25) }, + { MP_ROM_QSTR(MP_QSTR_IO26), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_IO27), MP_ROM_PTR(&pin_GPIO27) }, + + + { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_GPIO0) }, + { 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_D10), MP_ROM_PTR(&pin_GPIO10) }, + { 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_D14), MP_ROM_PTR(&pin_GPIO14) }, + + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_A3), 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_MOSI), MP_ROM_PTR(&pin_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO25) }, + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO24) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO23) }, + + + { MP_ROM_QSTR(MP_QSTR_MTMS), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_MTDO), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_MTCK), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_MTDI), MP_ROM_PTR(&pin_GPIO5) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/tests/feature_check/complex.py.exp b/ports/espressif/boards/pcbcupid_glyph_h2/sdkconfig similarity index 100% rename from tests/feature_check/complex.py.exp rename to ports/espressif/boards/pcbcupid_glyph_h2/sdkconfig diff --git a/ports/espressif/boards/pcbcupid_glyph_s3/board.c b/ports/espressif/boards/pcbcupid_glyph_s3/board.c new file mode 100644 index 00000000000..27b058c946f --- /dev/null +++ b/ports/espressif/boards/pcbcupid_glyph_s3/board.c @@ -0,0 +1,10 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 PCBCupid +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" + +void board_init(void) { +} diff --git a/ports/espressif/boards/pcbcupid_glyph_s3/mpconfigboard.h b/ports/espressif/boards/pcbcupid_glyph_s3/mpconfigboard.h new file mode 100644 index 00000000000..bc17cb65dfc --- /dev/null +++ b/ports/espressif/boards/pcbcupid_glyph_s3/mpconfigboard.h @@ -0,0 +1,22 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 PCBCupid +// +// SPDX-License-Identifier: MIT + +#pragma once + +#define MICROPY_HW_BOARD_NAME "PCBCupid GLYPH S3" +#define MICROPY_HW_MCU_NAME "ESP32S3" + +#define MICROPY_HW_LED_STATUS (&pin_GPIO21) + +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO5) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO4) + +#define DEFAULT_SPI_BUS_SCK (&pin_GPIO35) +#define DEFAULT_SPI_BUS_MOSI (&pin_GPIO36) +#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/espressif/boards/pcbcupid_glyph_s3/mpconfigboard.mk b/ports/espressif/boards/pcbcupid_glyph_s3/mpconfigboard.mk new file mode 100644 index 00000000000..9228197411f --- /dev/null +++ b/ports/espressif/boards/pcbcupid_glyph_s3/mpconfigboard.mk @@ -0,0 +1,10 @@ +USB_VID = 0x303A +USB_PID = 0x8373 +USB_PRODUCT = "GLYPH S3" +USB_MANUFACTURER = "PCBCupid" + +IDF_TARGET = esp32s3 + +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m +CIRCUITPY_ESP_FLASH_SIZE = 8MB diff --git a/ports/espressif/boards/pcbcupid_glyph_s3/pins.c b/ports/espressif/boards/pcbcupid_glyph_s3/pins.c new file mode 100644 index 00000000000..5b962f2f74d --- /dev/null +++ b/ports/espressif/boards/pcbcupid_glyph_s3/pins.c @@ -0,0 +1,59 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 PCBCupid +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO1) }, + + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_GPIO2) }, + + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_GPIO4) }, + + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_GPIO5) }, + + { MP_ROM_QSTR(MP_QSTR_A6), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_GPIO6) }, + + { MP_ROM_QSTR(MP_QSTR_A7), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_D7), MP_ROM_PTR(&pin_GPIO7) }, + + { MP_ROM_QSTR(MP_QSTR_A8), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_GPIO8) }, + + { MP_ROM_QSTR(MP_QSTR_A9), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_GPIO9) }, + + { MP_ROM_QSTR(MP_QSTR_A10), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_GPIO10) }, + + { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_D14), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_D16), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_D17), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_D18), MP_ROM_PTR(&pin_GPIO18) }, + + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO21) }, + + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_GPIO35) }, + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO36) }, + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO37) }, + + { 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_module_globals_table); diff --git a/tests/feature_check/const.py.exp b/ports/espressif/boards/pcbcupid_glyph_s3/sdkconfig similarity index 100% rename from tests/feature_check/const.py.exp rename to ports/espressif/boards/pcbcupid_glyph_s3/sdkconfig diff --git a/ports/espressif/boards/prokyber_ai_on_the_edge_cam/board.c b/ports/espressif/boards/prokyber_ai_on_the_edge_cam/board.c new file mode 100644 index 00000000000..a3a9eec0471 --- /dev/null +++ b/ports/espressif/boards/prokyber_ai_on_the_edge_cam/board.c @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/prokyber_ai_on_the_edge_cam/mpconfigboard.h b/ports/espressif/boards/prokyber_ai_on_the_edge_cam/mpconfigboard.h new file mode 100644 index 00000000000..2114fecf373 --- /dev/null +++ b/ports/espressif/boards/prokyber_ai_on_the_edge_cam/mpconfigboard.h @@ -0,0 +1,22 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Micropython setup + +#define MICROPY_HW_BOARD_NAME "Prokyber Ai-On-The-Edge-Cam" +#define MICROPY_HW_MCU_NAME "ESP32S3" + +#define MICROPY_HW_NEOPIXEL (&pin_GPIO12) + +#define MICROPY_HW_LED_STATUS (&pin_GPIO48) + +#define DEFAULT_UART_BUS_RX (&pin_GPIO44) +#define DEFAULT_UART_BUS_TX (&pin_GPIO43) + +#define CIRCUITPY_BOARD_I2C (1) +#define CIRCUITPY_BOARD_I2C_PIN {{.scl = &pin_GPIO5, .sda = &pin_GPIO4}} diff --git a/ports/espressif/boards/prokyber_ai_on_the_edge_cam/mpconfigboard.mk b/ports/espressif/boards/prokyber_ai_on_the_edge_cam/mpconfigboard.mk new file mode 100644 index 00000000000..82419bb8074 --- /dev/null +++ b/ports/espressif/boards/prokyber_ai_on_the_edge_cam/mpconfigboard.mk @@ -0,0 +1,14 @@ +USB_VID = 0x1209 +USB_PID = 0xDABB +USB_PRODUCT = "AI-ON-THE-EDGE-CAM" +USB_MANUFACTURER = "Prokyber" + +IDF_TARGET = esp32s3 + +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m +CIRCUITPY_ESP_FLASH_SIZE = 16MB + +CIRCUITPY_ESP_PSRAM_MODE = opi +CIRCUITPY_ESP_PSRAM_FREQ = 80m +CIRCUITPY_ESP_PSRAM_SIZE = 8MB diff --git a/ports/espressif/boards/prokyber_ai_on_the_edge_cam/pins.c b/ports/espressif/boards/prokyber_ai_on_the_edge_cam/pins.c new file mode 100644 index 00000000000..68dc40781a4 --- /dev/null +++ b/ports/espressif/boards/prokyber_ai_on_the_edge_cam/pins.c @@ -0,0 +1,106 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "py/objtuple.h" +#include "shared-bindings/board/__init__.h" + +static const mp_rom_obj_tuple_t camera_data_tuple = { + {&mp_type_tuple}, + 8, + { + MP_ROM_PTR(&pin_GPIO11), + MP_ROM_PTR(&pin_GPIO9), + MP_ROM_PTR(&pin_GPIO8), + MP_ROM_PTR(&pin_GPIO10), + MP_ROM_PTR(&pin_GPIO47), + MP_ROM_PTR(&pin_GPIO18), + MP_ROM_PTR(&pin_GPIO17), + MP_ROM_PTR(&pin_GPIO16), + } +}; + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { MP_ROM_QSTR(MP_QSTR_IO0), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_IO2), MP_ROM_PTR(&pin_GPIO2) }, + + { MP_ROM_QSTR(MP_QSTR_IO46), MP_ROM_PTR(&pin_GPIO46) }, + { MP_ROM_QSTR(MP_QSTR_PER_EN), MP_ROM_PTR(&pin_GPIO46) }, + + // SD + { MP_ROM_QSTR(MP_QSTR_SD_CS), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_IO3), MP_ROM_PTR(&pin_GPIO3) }, + + { MP_ROM_QSTR(MP_QSTR_SD_MISO), MP_ROM_PTR(&pin_GPIO41) }, + { MP_ROM_QSTR(MP_QSTR_IO41), MP_ROM_PTR(&pin_GPIO41) }, + + { MP_ROM_QSTR(MP_QSTR_SD_MOSI), MP_ROM_PTR(&pin_GPIO42) }, + { MP_ROM_QSTR(MP_QSTR_IO42), MP_ROM_PTR(&pin_GPIO42) }, + + { MP_ROM_QSTR(MP_QSTR_SD_CLK), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_IO40), MP_ROM_PTR(&pin_GPIO40) }, + + // Ethernet + { MP_ROM_QSTR(MP_QSTR_ETH_RST), MP_ROM_PTR(&pin_GPIO45) }, + { MP_ROM_QSTR(MP_QSTR_IO45), MP_ROM_PTR(&pin_GPIO45) }, + + { MP_ROM_QSTR(MP_QSTR_ETH_INT), MP_ROM_PTR(&pin_GPIO38) }, + { MP_ROM_QSTR(MP_QSTR_IO38), MP_ROM_PTR(&pin_GPIO38) }, + + { MP_ROM_QSTR(MP_QSTR_ETH_MOSI), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_IO1), MP_ROM_PTR(&pin_GPIO1) }, + + { MP_ROM_QSTR(MP_QSTR_ETH_MISO), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_IO14), MP_ROM_PTR(&pin_GPIO14) }, + + { MP_ROM_QSTR(MP_QSTR_ETH_CLK), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_IO21), MP_ROM_PTR(&pin_GPIO21) }, + + { MP_ROM_QSTR(MP_QSTR_ETH_CS), MP_ROM_PTR(&pin_GPIO39) }, + { MP_ROM_QSTR(MP_QSTR_IO39), MP_ROM_PTR(&pin_GPIO39) }, + + // LEDs + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_IO12), MP_ROM_PTR(&pin_GPIO12) }, + + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO48) }, + { MP_ROM_QSTR(MP_QSTR_IO48), MP_ROM_PTR(&pin_GPIO48) }, + + // UART + { 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) }, + + // I2C + { 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_CAMERA_DATA), MP_ROM_PTR(&camera_data_tuple) }, + + { MP_ROM_QSTR(MP_QSTR_CAMERA_VSYNC), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_CAMERA_HREF), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_CAMERA_DATA9), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_CAMERA_XCLK), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_CAMERA_DATA8), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_CAMERA_DATA7), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_CAMERA_PCLK), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_CAMERA_DATA6), MP_ROM_PTR(&pin_GPIO47) }, + { MP_ROM_QSTR(MP_QSTR_CAMERA_DATA2), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_CAMERA_DATA5), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_CAMERA_DATA3), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_CAMERA_DATA4), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_CAMERA_SIOD), MP_ROM_PTR(&pin_GPIO4) }, // SDA + { MP_ROM_QSTR(MP_QSTR_CAMERA_SIOC), MP_ROM_PTR(&pin_GPIO5) }, // SCL + + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, + { MP_ROM_QSTR(MP_QSTR_STEMMA_I2C), MP_ROM_PTR(&board_i2c_obj) }, + { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj) }, + { MP_ROM_QSTR(MP_QSTR_SPI), MP_ROM_PTR(&board_spi_obj) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/espressif/boards/prokyber_ai_on_the_edge_cam/sdkconfig b/ports/espressif/boards/prokyber_ai_on_the_edge_cam/sdkconfig new file mode 100644 index 00000000000..ac1c5357176 --- /dev/null +++ b/ports/espressif/boards/prokyber_ai_on_the_edge_cam/sdkconfig @@ -0,0 +1,14 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Component config +# +# +# LWIP +# +# end of LWIP +CONFIG_OV2640_SUPPORT=y +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/boards/red-s2-wroom/mpconfigboard.mk b/ports/espressif/boards/red-s2-wroom/mpconfigboard.mk index e12fb443f6d..33a83f954a7 100644 --- a/ports/espressif/boards/red-s2-wroom/mpconfigboard.mk +++ b/ports/espressif/boards/red-s2-wroom/mpconfigboard.mk @@ -8,4 +8,3 @@ IDF_TARGET = esp32s2 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/seeed_xiao_esp32_s3_sense/mpconfigboard.h b/ports/espressif/boards/seeed_xiao_esp32_s3_sense/mpconfigboard.h index c05b6a93a10..d7f24b255d6 100644 --- a/ports/espressif/boards/seeed_xiao_esp32_s3_sense/mpconfigboard.h +++ b/ports/espressif/boards/seeed_xiao_esp32_s3_sense/mpconfigboard.h @@ -12,9 +12,9 @@ #define DEFAULT_UART_BUS_RX (&pin_GPIO44) #define DEFAULT_UART_BUS_TX (&pin_GPIO43) -#define DEFAULT_SPI_BUS_SCK (&pin_GPIO7) -#define DEFAULT_SPI_BUS_MOSI (&pin_GPIO9) -#define DEFAULT_SPI_BUS_MISO (&pin_GPIO8) +#define DEFAULT_SPI_BUS_SCK (&pin_GPIO7) +#define DEFAULT_SPI_BUS_MOSI (&pin_GPIO9) +#define DEFAULT_SPI_BUS_MISO (&pin_GPIO8) -#define DEFAULT_I2C_BUS_SCL (&pin_GPIO6) -#define DEFAULT_I2C_BUS_SDA (&pin_GPIO5) +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO6) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO5) diff --git a/ports/espressif/boards/seeed_xiao_esp32_s3_sense/pins.c b/ports/espressif/boards/seeed_xiao_esp32_s3_sense/pins.c index aa3a6f7b7f5..fbb6014685c 100644 --- a/ports/espressif/boards/seeed_xiao_esp32_s3_sense/pins.c +++ b/ports/espressif/boards/seeed_xiao_esp32_s3_sense/pins.c @@ -31,49 +31,92 @@ static const mp_rom_obj_tuple_t camera_data_tuple = { static const mp_rom_map_elem_t board_module_globals_table[] = { CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS - { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_GPIO1) }, - { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO2) }, - { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO3) }, - { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO4) }, - { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_GPIO5) }, - { MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_GPIO6) }, { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_D7), MP_ROM_PTR(&pin_GPIO44) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO44) }, + { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_GPIO9) }, - { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO21) }, - { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO5) }, - { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO6) }, - { 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_MOSI), MP_ROM_PTR(&pin_GPIO9) }, - { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO8) }, - { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_GPIO7) }, + + { MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_GPIO38) }, + { MP_ROM_QSTR(MP_QSTR_I2S_SD), MP_ROM_PTR(&pin_GPIO38) }, + { MP_ROM_QSTR(MP_QSTR_CAM_VSYNC), MP_ROM_PTR(&pin_GPIO38) }, + + { MP_ROM_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_GPIO39) }, + { MP_ROM_QSTR(MP_QSTR_I2S_SCK), MP_ROM_PTR(&pin_GPIO39) }, + { MP_ROM_QSTR(MP_QSTR_MTCK), MP_ROM_PTR(&pin_GPIO39) }, + { MP_ROM_QSTR(MP_QSTR_CAM_SCL), MP_ROM_PTR(&pin_GPIO39) }, + + { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_I2S_WS), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_MTDO), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_CAM_SDA), MP_ROM_PTR(&pin_GPIO40) }, + + { MP_ROM_QSTR(MP_QSTR_D14), MP_ROM_PTR(&pin_GPIO41) }, + { MP_ROM_QSTR(MP_QSTR_MTDI), MP_ROM_PTR(&pin_GPIO41) }, + { MP_ROM_QSTR(MP_QSTR_MIC_DATA), MP_ROM_PTR(&pin_GPIO41) }, + { MP_ROM_QSTR(MP_QSTR_RX_1), MP_ROM_PTR(&pin_GPIO41) }, + + { MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_GPIO42) }, + { MP_ROM_QSTR(MP_QSTR_MTMS), MP_ROM_PTR(&pin_GPIO42) }, + { MP_ROM_QSTR(MP_QSTR_MIC_CLK), MP_ROM_PTR(&pin_GPIO42) }, + { MP_ROM_QSTR(MP_QSTR_TX_1), MP_ROM_PTR(&pin_GPIO42) }, + + { MP_ROM_QSTR(MP_QSTR_D16), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_ADC), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_CAM_XCLK), MP_ROM_PTR(&pin_GPIO10) }, + + { MP_ROM_QSTR(MP_QSTR_D17), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_SCK_1), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_CAM_PCLK), MP_ROM_PTR(&pin_GPIO13) }, + + { MP_ROM_QSTR(MP_QSTR_D18), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_MISO_1), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_CAM_D5), MP_ROM_PTR(&pin_GPIO12) }, + + { MP_ROM_QSTR(MP_QSTR_D19), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_MOSI_1), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_CAM_D6), MP_ROM_PTR(&pin_GPIO11) }, + + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO21) }, { MP_ROM_QSTR(MP_QSTR_SDCS), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_CAM_DATA), MP_ROM_PTR(&camera_data_tuple) }, { MP_ROM_QSTR(MP_QSTR_CAM_D0), MP_ROM_PTR(&pin_GPIO15) }, { MP_ROM_QSTR(MP_QSTR_CAM_D1), MP_ROM_PTR(&pin_GPIO17) }, { MP_ROM_QSTR(MP_QSTR_CAM_D2), MP_ROM_PTR(&pin_GPIO18) }, { MP_ROM_QSTR(MP_QSTR_CAM_D3), MP_ROM_PTR(&pin_GPIO16) }, { MP_ROM_QSTR(MP_QSTR_CAM_D4), MP_ROM_PTR(&pin_GPIO14) }, - { MP_ROM_QSTR(MP_QSTR_CAM_D5), MP_ROM_PTR(&pin_GPIO12) }, - { MP_ROM_QSTR(MP_QSTR_CAM_D6), MP_ROM_PTR(&pin_GPIO11) }, { MP_ROM_QSTR(MP_QSTR_CAM_D7), MP_ROM_PTR(&pin_GPIO48) }, - { MP_ROM_QSTR(MP_QSTR_CAM_XCLK), MP_ROM_PTR(&pin_GPIO10) }, { MP_ROM_QSTR(MP_QSTR_CAM_HREF), MP_ROM_PTR(&pin_GPIO47) }, - { MP_ROM_QSTR(MP_QSTR_CAM_PCLK), MP_ROM_PTR(&pin_GPIO13) }, - { MP_ROM_QSTR(MP_QSTR_CAM_VSYNC), MP_ROM_PTR(&pin_GPIO38) }, - { MP_ROM_QSTR(MP_QSTR_CAM_SCL), MP_ROM_PTR(&pin_GPIO39) }, - { MP_ROM_QSTR(MP_QSTR_CAM_SDA), MP_ROM_PTR(&pin_GPIO40) }, - { MP_ROM_QSTR(MP_QSTR_MIC_DATA), MP_ROM_PTR(&pin_GPIO41) }, - { MP_ROM_QSTR(MP_QSTR_MIC_CLK), MP_ROM_PTR(&pin_GPIO42) }, { 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/espressif/boards/seeed_xiao_esp32_s3_sense/sdkconfig b/ports/espressif/boards/seeed_xiao_esp32_s3_sense/sdkconfig index 919f4d9f345..2d98e822542 100644 --- a/ports/espressif/boards/seeed_xiao_esp32_s3_sense/sdkconfig +++ b/ports/espressif/boards/seeed_xiao_esp32_s3_sense/sdkconfig @@ -5,15 +5,13 @@ # Component config # # -# LWIP # -# end of LWIP # Camera configuration # -CONFIG_OV2640_SUPPORT=y # CONFIG_OV7725_SUPPORT is not set -# CONFIG_OV3660_SUPPORT is not set +CONFIG_OV2640_SUPPORT=y # end of Camera configuration + # end of Component config # end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/boards/seeed_xiao_esp32_s3_trmnl_diy_kit/board.c b/ports/espressif/boards/seeed_xiao_esp32_s3_trmnl_diy_kit/board.c new file mode 100644 index 00000000000..fea7fe2c300 --- /dev/null +++ b/ports/espressif/boards/seeed_xiao_esp32_s3_trmnl_diy_kit/board.c @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "mpconfigboard.h" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/seeed_xiao_esp32_s3_trmnl_diy_kit/mpconfigboard.h b/ports/espressif/boards/seeed_xiao_esp32_s3_trmnl_diy_kit/mpconfigboard.h new file mode 100644 index 00000000000..79deafd6125 --- /dev/null +++ b/ports/espressif/boards/seeed_xiao_esp32_s3_trmnl_diy_kit/mpconfigboard.h @@ -0,0 +1,24 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Bernhard Bablok +// +// SPDX-License-Identifier: MIT + +// Micropython setup + +#define MICROPY_HW_BOARD_NAME "Seeed Xiao ESP32-S3 Trmnl DIY Kit" +#define MICROPY_HW_MCU_NAME "ESP32S3" + +#define MICROPY_HW_LED_STATUS (&pin_GPIO21) + +// the unpopulated NFC-header also provides UART +#define CIRCUITPY_BOARD_UART (1) +#define CIRCUITPY_BOARD_UART_PIN {{.rx = &pin_GPIO41, .tx = &pin_GPIO42}} + +// SPI0 is used by the display connector +// SPI1 is used by a two secondary flash chips (one unpopulated) +#define CIRCUITPY_BOARD_SPI (2) +#define CIRCUITPY_BOARD_SPI_PIN \ + {{.clock = &pin_GPIO7, .mosi = &pin_GPIO9}, \ + {.clock = &pin_GPIO13, .mosi = &pin_GPIO11, .miso = &pin_GPIO12} \ + } diff --git a/ports/espressif/boards/seeed_xiao_esp32_s3_trmnl_diy_kit/mpconfigboard.mk b/ports/espressif/boards/seeed_xiao_esp32_s3_trmnl_diy_kit/mpconfigboard.mk new file mode 100644 index 00000000000..dc0e64f765a --- /dev/null +++ b/ports/espressif/boards/seeed_xiao_esp32_s3_trmnl_diy_kit/mpconfigboard.mk @@ -0,0 +1,33 @@ +USB_VID = 0x2886 +USB_PID = 0x0300 + +USB_PRODUCT = "Seeed Xiao ESP32-S3 Trmnl DIY Kit" +USB_MANUFACTURER = "Seeed Studio" + +IDF_TARGET = esp32s3 + +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_SIZE = 16MB +CIRCUITPY_ESP_FLASH_FREQ = 80m + +CIRCUITPY_ESP_PSRAM_MODE = opi +CIRCUITPY_ESP_PSRAM_SIZE = 8MB +CIRCUITPY_ESP_PSRAM_FREQ = 80m + +CIRCUITPY_FREQUENCYIO = 0 +CIRCUITPY_RAINBOWIO = 0 +CIRCUITPY__EVE = 0 +CIRCUITPY_PS2IO = 0 +CIRCUITPY_CANIO = 0 +CIRCUITPY_MAX3421E = 0 +CIRCUITPY_ESPCAMERA = 0 +CIRCUITPY_PARALLELDISPLAYBUS = 0 +CIRCUITPY_COUNTIO = 0 +CIRCUITPY_NEOPIXEL_WRITE = 0 +CIRCUITPY_ROTARYIO = 0 + +CIRCUITPY_AUDIOCORE = 0 +CIRCUITPY_AUDIOBUSIO = 0 +CIRCUITPY_AUDIOBUSIO_PDMIN = 0 +CIRCUITPY_AUDIOI2SIN = 0 +CIRCUITPY_AUDIOPWMIO = 0 diff --git a/ports/espressif/boards/seeed_xiao_esp32_s3_trmnl_diy_kit/pins.c b/ports/espressif/boards/seeed_xiao_esp32_s3_trmnl_diy_kit/pins.c new file mode 100644 index 00000000000..422f16b787b --- /dev/null +++ b/ports/espressif/boards/seeed_xiao_esp32_s3_trmnl_diy_kit/pins.c @@ -0,0 +1,47 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { MP_ROM_QSTR(MP_QSTR_BAT_ADC), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_BTN1), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_BTN2), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_EDP_BUSY), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_BTN3), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_ADC_EN), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_SPI0_CLK), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_SPI0_MOSI), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_EDP_DC), MP_ROM_PTR(&pin_GPIO10) }, + + // connected to two additional flash chips (one unpopulated) + { MP_ROM_QSTR(MP_QSTR_SPI1_MOSI), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_SPI1_MISO), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_SPI1_CLK), MP_ROM_PTR(&pin_GPIO13) }, + + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO21) }, + + { MP_ROM_QSTR(MP_QSTR_EDP_RES), MP_ROM_PTR(&pin_GPIO38) }, + + // connected to two additional flash chips (CS0 unpopulated) + { MP_ROM_QSTR(MP_QSTR_SPI1_CS0), MP_ROM_PTR(&pin_GPIO39) }, + { MP_ROM_QSTR(MP_QSTR_SPI1_CS1), MP_ROM_PTR(&pin_GPIO40) }, + + { MP_ROM_QSTR(MP_QSTR_D14), MP_ROM_PTR(&pin_GPIO41) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO41) }, + + { MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_GPIO42) }, + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO42) }, + + { MP_ROM_QSTR(MP_QSTR_PWR_EN), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_SPI0_CS), MP_ROM_PTR(&pin_GPIO44) }, + + { 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_module_globals_table); diff --git a/ports/espressif/boards/seeed_xiao_esp32_s3_trmnl_diy_kit/sdkconfig b/ports/espressif/boards/seeed_xiao_esp32_s3_trmnl_diy_kit/sdkconfig new file mode 100644 index 00000000000..ce6696bf50f --- /dev/null +++ b/ports/espressif/boards/seeed_xiao_esp32_s3_trmnl_diy_kit/sdkconfig @@ -0,0 +1,11 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Component config +# +# +# +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/boards/seeed_xiao_esp32c3/mpconfigboard.mk b/ports/espressif/boards/seeed_xiao_esp32c3/mpconfigboard.mk index b71a41ef6e3..c5b266ca744 100644 --- a/ports/espressif/boards/seeed_xiao_esp32c3/mpconfigboard.mk +++ b/ports/espressif/boards/seeed_xiao_esp32c3/mpconfigboard.mk @@ -7,6 +7,4 @@ CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 - CIRCUITPY_ESP_USB_SERIAL_JTAG = 1 diff --git a/ports/espressif/boards/seeed_xiao_esp32c6/board.c b/ports/espressif/boards/seeed_xiao_esp32c6/board.c index 7a013bc9d0b..7993adaf934 100644 --- a/ports/espressif/boards/seeed_xiao_esp32c6/board.c +++ b/ports/espressif/boards/seeed_xiao_esp32c6/board.c @@ -25,19 +25,5 @@ */ #include "supervisor/board.h" -#include "mpconfigboard.h" -#include "shared-bindings/microcontroller/Pin.h" -#include "driver/gpio.h" -#include "common-hal/microcontroller/Pin.h" - -bool espressif_board_reset_pin_number(gpio_num_t pin_number) { - if (pin_number == 16) { - // Turn on I2C power by default. - config_pin_as_output_with_level(pin_number, true); - return true; - } - - return false; -} // Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/seeed_xiao_esp32c6/mpconfigboard.h b/ports/espressif/boards/seeed_xiao_esp32c6/mpconfigboard.h index 6f803cd9c96..6918056cf86 100644 --- a/ports/espressif/boards/seeed_xiao_esp32c6/mpconfigboard.h +++ b/ports/espressif/boards/seeed_xiao_esp32c6/mpconfigboard.h @@ -17,3 +17,6 @@ // For entering safe mode, use BOOT button #define CIRCUITPY_BOOT_BUTTON (&pin_GPIO9) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/seeed_xiao_esp32c6/mpconfigboard.mk b/ports/espressif/boards/seeed_xiao_esp32c6/mpconfigboard.mk index 9d95fe94449..ce6763afbcc 100644 --- a/ports/espressif/boards/seeed_xiao_esp32c6/mpconfigboard.mk +++ b/ports/espressif/boards/seeed_xiao_esp32c6/mpconfigboard.mk @@ -6,3 +6,6 @@ IDF_TARGET = esp32c6 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB + +# Board was originally defined with a 2MB firmware, almost 2MB user filesystem. Leave it that way. +CIRCUITPY_4MB_FLASH_LARGE_USER_FS_LAYOUT = 1 diff --git a/ports/espressif/boards/seeed_xiao_esp32c6/pins.c b/ports/espressif/boards/seeed_xiao_esp32c6/pins.c index b7aeb90d2b1..1b62b37065e 100644 --- a/ports/espressif/boards/seeed_xiao_esp32c6/pins.c +++ b/ports/espressif/boards/seeed_xiao_esp32c6/pins.c @@ -47,6 +47,9 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_MTCK), MP_ROM_PTR(&pin_GPIO6) }, { MP_ROM_QSTR(MP_QSTR_LP_I2C_SDA), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_LED_INVERTED), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_MTDO), MP_ROM_PTR(&pin_GPIO7) }, { MP_ROM_QSTR(MP_QSTR_LP_I2C_SCL), MP_ROM_PTR(&pin_GPIO7) }, diff --git a/ports/espressif/boards/sensebox_mcu_esp32s2/mpconfigboard.mk b/ports/espressif/boards/sensebox_mcu_esp32s2/mpconfigboard.mk index a8c32ae88df..6b97c870cc0 100644 --- a/ports/espressif/boards/sensebox_mcu_esp32s2/mpconfigboard.mk +++ b/ports/espressif/boards/sensebox_mcu_esp32s2/mpconfigboard.mk @@ -1,7 +1,7 @@ USB_VID = 0x303A USB_PID = 0x81B9 USB_PRODUCT = "senseBox MCU-S2 ESP32S2" -USB_MANUFACTURER = "Espressif" +USB_MANUFACTURER = "senseBox" IDF_TARGET = esp32s2 @@ -9,8 +9,6 @@ CIRCUITPY_ESP_FLASH_SIZE = 4MB CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m -CIRCUITPY_ESPCAMERA = 0 - CIRCUITPY_REQUIRE_I2C_PULLUPS = 0 CIRCUITPY_I2C_ALLOW_STRAPPING_PINS = 1 diff --git a/ports/espressif/boards/sensebox_mcu_eye_esp32s3/board.c b/ports/espressif/boards/sensebox_mcu_eye_esp32s3/board.c new file mode 100644 index 00000000000..fea7fe2c300 --- /dev/null +++ b/ports/espressif/boards/sensebox_mcu_eye_esp32s3/board.c @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "mpconfigboard.h" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/sensebox_mcu_eye_esp32s3/mpconfigboard.h b/ports/espressif/boards/sensebox_mcu_eye_esp32s3/mpconfigboard.h new file mode 100644 index 00000000000..300154fe344 --- /dev/null +++ b/ports/espressif/boards/sensebox_mcu_eye_esp32s3/mpconfigboard.h @@ -0,0 +1,18 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// Micropython setup + +#define MICROPY_HW_BOARD_NAME "senseBox MCU Eye ESP32S3" +#define MICROPY_HW_MCU_NAME "ESP32S3" + +#define MICROPY_HW_NEOPIXEL (&pin_GPIO45) + +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO1) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO2) + +#define DEFAULT_UART_BUS_RX (&pin_GPIO44) +#define DEFAULT_UART_BUS_TX (&pin_GPIO43) diff --git a/ports/espressif/boards/sensebox_mcu_eye_esp32s3/mpconfigboard.mk b/ports/espressif/boards/sensebox_mcu_eye_esp32s3/mpconfigboard.mk new file mode 100644 index 00000000000..be3c65746c8 --- /dev/null +++ b/ports/espressif/boards/sensebox_mcu_eye_esp32s3/mpconfigboard.mk @@ -0,0 +1,21 @@ +USB_VID = 0x303A +USB_PID = 0x82D2 + +USB_PRODUCT = "senseBox-eye ESP32S3" +USB_MANUFACTURER = "senseBox" + +IDF_TARGET = esp32s3 + +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_SIZE = 16MB +CIRCUITPY_ESP_FLASH_FREQ = 80m + +CIRCUITPY_ESP_PSRAM_MODE = opi +CIRCUITPY_ESP_PSRAM_SIZE = 8MB +CIRCUITPY_ESP_PSRAM_FREQ = 80m + +CIRCUITPY_ESPCAMERA = 1 +CIRCUITPY_AUDIOBUSIO = 1 + +# Include these Python libraries in firmware. +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel diff --git a/ports/espressif/boards/sensebox_mcu_eye_esp32s3/pins.c b/ports/espressif/boards/sensebox_mcu_eye_esp32s3/pins.c new file mode 100644 index 00000000000..71b984f7ff5 --- /dev/null +++ b/ports/espressif/boards/sensebox_mcu_eye_esp32s3/pins.c @@ -0,0 +1,82 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "py/objtuple.h" +#include "shared-bindings/board/__init__.h" +#include "shared-module/displayio/__init__.h" + +CIRCUITPY_BOARD_BUS_SINGLETON(sscb_i2c, i2c, 2) + +static const mp_rom_obj_tuple_t camera_data_tuple = { + // The order matters. + // They must be ordered from low to high (CAM_D0, CAM_D1...CAM_D7). + + // Do not include any of the control pins in here. + {&mp_type_tuple}, + 8, + { + MP_ROM_PTR(&pin_GPIO11), + MP_ROM_PTR(&pin_GPIO9), + MP_ROM_PTR(&pin_GPIO8), + MP_ROM_PTR(&pin_GPIO10), + MP_ROM_PTR(&pin_GPIO12), + MP_ROM_PTR(&pin_GPIO18), + MP_ROM_PTR(&pin_GPIO17), + MP_ROM_PTR(&pin_GPIO16), + } +}; + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + { MP_ROM_QSTR(MP_QSTR_BUTTON), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_BOOT0), MP_ROM_PTR(&pin_GPIO0) }, + {MP_ROM_QSTR(MP_QSTR_BUTTON_SW), MP_ROM_PTR(&pin_GPIO21) }, + + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_GPIO2) }, + + { MP_ROM_QSTR(MP_QSTR_A14), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_D14), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_A48), MP_ROM_PTR(&pin_GPIO48) }, + { MP_ROM_QSTR(MP_QSTR_D48), MP_ROM_PTR(&pin_GPIO48) }, + + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO45) }, + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO45) }, + + { 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_UART_ENABLE), MP_ROM_PTR(&pin_GPIO26) }, + + { MP_ROM_QSTR(MP_QSTR_CAM_DATA), MP_ROM_PTR(&camera_data_tuple) }, + { MP_ROM_QSTR(MP_QSTR_CAM_D0), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_CAM_D1), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_CAM_D2), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_CAM_D3), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_CAM_D4), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_CAM_D5), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_CAM_D6), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_CAM_D7), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_CAM_XCLK), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_CAM_HREF), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_CAM_PCLK), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_CAM_VSYNC), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_CAM_SCL), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_CAM_SDA), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_PWDN), MP_ROM_PTR(&pin_GPIO46) }, + + { MP_ROM_QSTR(MP_QSTR_SD_CS), MP_ROM_PTR(&pin_GPIO41) }, + { MP_ROM_QSTR(MP_QSTR_SD_MOSI), MP_ROM_PTR(&pin_GPIO38) }, + { MP_ROM_QSTR(MP_QSTR_SD_SCLK), MP_ROM_PTR(&pin_GPIO39) }, + { MP_ROM_QSTR(MP_QSTR_SD_MISO), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_SD_ENABLE), MP_ROM_PTR(&pin_GPIO3) }, + + { 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_module_globals_table); diff --git a/ports/espressif/boards/sensebox_mcu_eye_esp32s3/sdkconfig b/ports/espressif/boards/sensebox_mcu_eye_esp32s3/sdkconfig new file mode 100644 index 00000000000..919f4d9f345 --- /dev/null +++ b/ports/espressif/boards/sensebox_mcu_eye_esp32s3/sdkconfig @@ -0,0 +1,19 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Component config +# +# +# LWIP +# +# end of LWIP +# Camera configuration +# +CONFIG_OV2640_SUPPORT=y +# CONFIG_OV7725_SUPPORT is not set +# CONFIG_OV3660_SUPPORT is not set +# end of Camera configuration +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/boards/smartbeedesigns_bee_data_logger/mpconfigboard.mk b/ports/espressif/boards/smartbeedesigns_bee_data_logger/mpconfigboard.mk index 6ded5c4e198..6465252ac46 100644 --- a/ports/espressif/boards/smartbeedesigns_bee_data_logger/mpconfigboard.mk +++ b/ports/espressif/boards/smartbeedesigns_bee_data_logger/mpconfigboard.mk @@ -9,10 +9,8 @@ CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 8MB - FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_Register FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_BusDevice FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_DS3231 FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_SD -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/smartbeedesigns_bee_motion_s3/mpconfigboard.mk b/ports/espressif/boards/smartbeedesigns_bee_motion_s3/mpconfigboard.mk index 72ad30af2e0..5bfa7340d56 100644 --- a/ports/espressif/boards/smartbeedesigns_bee_motion_s3/mpconfigboard.mk +++ b/ports/espressif/boards/smartbeedesigns_bee_motion_s3/mpconfigboard.mk @@ -9,6 +9,4 @@ CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 8MB - FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/smartbeedesigns_bee_s3/mpconfigboard.mk b/ports/espressif/boards/smartbeedesigns_bee_s3/mpconfigboard.mk index 095924385b7..fc11e4bd21c 100644 --- a/ports/espressif/boards/smartbeedesigns_bee_s3/mpconfigboard.mk +++ b/ports/espressif/boards/smartbeedesigns_bee_s3/mpconfigboard.mk @@ -9,6 +9,4 @@ CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 8MB - FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/solderparty_esp32p4_stamp_xl/sdkconfig b/ports/espressif/boards/solderparty_esp32p4_stamp_xl/sdkconfig index e69de29bb2d..3bce8cc0c13 100644 --- a/ports/espressif/boards/solderparty_esp32p4_stamp_xl/sdkconfig +++ b/ports/espressif/boards/solderparty_esp32p4_stamp_xl/sdkconfig @@ -0,0 +1,2 @@ +CONFIG_ESP32P4_SELECTS_REV_LESS_V3=y +CONFIG_ESP32P4_REV_MIN_100=y diff --git a/ports/espressif/boards/spotpear_esp32c3_lcd_1_44/board.c b/ports/espressif/boards/spotpear_esp32c3_lcd_1_44/board.c index 89bcbf6b8dd..7b6e26ebe39 100644 --- a/ports/espressif/boards/spotpear_esp32c3_lcd_1_44/board.c +++ b/ports/espressif/boards/spotpear_esp32c3_lcd_1_44/board.c @@ -35,16 +35,15 @@ static bool display_init(void) { fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_GPIO3, &pin_GPIO4, NULL, false); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO0, // DC - &pin_GPIO2, // CS - &pin_GPIO5, // RST + MP_OBJ_FROM_PTR(&pin_GPIO0), // DC + MP_OBJ_FROM_PTR(&pin_GPIO2), // CS + MP_OBJ_FROM_PTR(&pin_GPIO5), // RST 10000000, // baudrate 0, // polarity 0 // phase diff --git a/ports/espressif/boards/spotpear_esp32c3_lcd_1_44/mpconfigboard.mk b/ports/espressif/boards/spotpear_esp32c3_lcd_1_44/mpconfigboard.mk index 87fc8a72f3e..c876b7c7a4e 100644 --- a/ports/espressif/boards/spotpear_esp32c3_lcd_1_44/mpconfigboard.mk +++ b/ports/espressif/boards/spotpear_esp32c3_lcd_1_44/mpconfigboard.mk @@ -8,4 +8,3 @@ CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB CIRCUITPY_ESP_USB_SERIAL_JTAG = 1 -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 diff --git a/ports/espressif/boards/spotpear_esp32c3_lcd_1_69/board.c b/ports/espressif/boards/spotpear_esp32c3_lcd_1_69/board.c index 6299402e8e0..cb9f0e857bb 100644 --- a/ports/espressif/boards/spotpear_esp32c3_lcd_1_69/board.c +++ b/ports/espressif/boards/spotpear_esp32c3_lcd_1_69/board.c @@ -33,15 +33,14 @@ void board_init(void) { fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_GPIO5, &pin_GPIO6, NULL, false); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO2, // DC - &pin_GPIO3, // CS - &pin_GPIO10, // RST + MP_OBJ_FROM_PTR(&pin_GPIO2), // DC + MP_OBJ_FROM_PTR(&pin_GPIO3), // CS + MP_OBJ_FROM_PTR(&pin_GPIO10), // RST 40000000, // baudrate 0, // polarity 0 // phase diff --git a/ports/espressif/boards/sqfmi_watchy/board.c b/ports/espressif/boards/sqfmi_watchy/board.c index 25a7be4613c..4722be98303 100644 --- a/ports/espressif/boards/sqfmi_watchy/board.c +++ b/ports/espressif/boards/sqfmi_watchy/board.c @@ -135,24 +135,17 @@ const uint8_t refresh_sequence[] = { void board_init(void) { - // Debug UART - #ifdef DEBUG - common_hal_never_reset_pin(&pin_GPIO43); - common_hal_never_reset_pin(&pin_GPIO44); - #endif /* DEBUG */ - fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_GPIO18, &pin_GPIO23, NULL, false); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO10, // EPD_DC Command or data - &pin_GPIO5, // EPD_CS Chip select - &pin_GPIO9, // EPD_RST Reset + MP_OBJ_FROM_PTR(&pin_GPIO10), // EPD_DC Command or data + MP_OBJ_FROM_PTR(&pin_GPIO5), // EPD_CS Chip select + MP_OBJ_FROM_PTR(&pin_GPIO9), // EPD_RST Reset 2000000, // Baudrate 0, // Polarity 0 // Phase @@ -160,39 +153,33 @@ void board_init(void) { epaperdisplay_epaperdisplay_obj_t *display = &allocate_display()->epaper_display; display->base.type = &epaperdisplay_epaperdisplay_type; - common_hal_epaperdisplay_epaperdisplay_construct( - display, - bus, - display_start_sequence, sizeof(display_start_sequence), - (double)0.01, // start up time - display_stop_sequence, sizeof(display_stop_sequence), - 200, // width - 200, // height - 200, // ram_width - 296, // ram_height - 0, // colstart - 0, // rowstart - 0, // rotation - 0x44, // set_column_window_command - 0x45, // set_row_window_command - 0x4E, // set_current_column_command - 0x4F, // set_current_row_command - 0x24, // write_black_ram_command - true, // black_bits_inverted - 0x26, // write_color_ram_command - false, // color_bits_inverted - 0x000000, // highlight_color - refresh_sequence, sizeof(refresh_sequence), - (double)1.0, // refresh_time - &pin_GPIO19, // busy_pin - true, // busy_state - (double)5.0, // seconds_per_frame - false, // always_toggle_chip_select - false, // grayscale - false, // acep - false, // two_byte_sequence_length - true // address_little_endian - ); + + epaperdisplay_construct_args_t args = EPAPERDISPLAY_CONSTRUCT_ARGS_DEFAULTS; + args.bus = bus; + args.start_sequence = display_start_sequence; + args.start_sequence_len = sizeof(display_start_sequence); + args.start_up_time = 0.01; + args.stop_sequence = display_stop_sequence; + args.stop_sequence_len = sizeof(display_stop_sequence); + args.width = 200; + args.height = 200; + args.ram_width = 200; + args.ram_height = 296; + args.set_column_window_command = 0x44; + args.set_row_window_command = 0x45; + args.set_current_column_command = 0x4E; + args.set_current_row_command = 0x4F; + args.write_black_ram_command = 0x24; + args.black_bits_inverted = true; + args.write_color_ram_command = 0x26; + args.refresh_sequence = refresh_sequence; + args.refresh_sequence_len = sizeof(refresh_sequence); + args.refresh_time = 1.0; + args.busy_pin = &pin_GPIO19; + args.busy_state = true; + args.seconds_per_frame = 5.0; + args.address_little_endian = true; + common_hal_epaperdisplay_epaperdisplay_construct(display, &args); } bool board_requests_safe_mode(void) { diff --git a/ports/espressif/boards/sqfmi_watchy/mpconfigboard.mk b/ports/espressif/boards/sqfmi_watchy/mpconfigboard.mk index 520894ea70a..b1c8c64f8ba 100644 --- a/ports/espressif/boards/sqfmi_watchy/mpconfigboard.mk +++ b/ports/espressif/boards/sqfmi_watchy/mpconfigboard.mk @@ -1,13 +1,8 @@ CIRCUITPY_CREATOR_ID = 0x4496E3F4 CIRCUITPY_CREATION_ID = 0x00320024 - -CIRCUITPY_ESPCAMERA = 0 +IDF_TARGET = esp32 CIRCUITPY_ESP_FLASH_MODE=dio CIRCUITPY_ESP_FLASH_FREQ=40m CIRCUITPY_ESP_FLASH_SIZE=4MB - -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 - -IDF_TARGET = esp32 diff --git a/ports/espressif/boards/sunton_esp32_2424S012/board.c b/ports/espressif/boards/sunton_esp32_2424S012/board.c index c313ded8637..e3ccac05581 100644 --- a/ports/espressif/boards/sunton_esp32_2424S012/board.c +++ b/ports/espressif/boards/sunton_esp32_2424S012/board.c @@ -100,14 +100,13 @@ static void display_init(void) { NULL, // MISO not connected false // Not half-duplex ); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO2, // DC - &pin_GPIO10, // CS - NULL, // RST + MP_OBJ_FROM_PTR(&pin_GPIO2), // DC + MP_OBJ_FROM_PTR(&pin_GPIO10), // CS + mp_const_none, // RST 80000000, // baudrate 0, // polarity 0 // phase diff --git a/ports/espressif/boards/sunton_esp32_2424S012/mpconfigboard.mk b/ports/espressif/boards/sunton_esp32_2424S012/mpconfigboard.mk index 2a84d801bc3..716a01084c1 100644 --- a/ports/espressif/boards/sunton_esp32_2424S012/mpconfigboard.mk +++ b/ports/espressif/boards/sunton_esp32_2424S012/mpconfigboard.mk @@ -7,6 +7,4 @@ CIRCUITPY_ESP_FLASH_MODE=qio CIRCUITPY_ESP_FLASH_FREQ=80m CIRCUITPY_ESP_FLASH_SIZE=4MB -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 - CIRCUITPY_ESP_USB_SERIAL_JTAG = 1 diff --git a/ports/espressif/boards/sunton_esp32_2432S024C/board.c b/ports/espressif/boards/sunton_esp32_2432S024C/board.c index 8b4201d88e8..8ef5cd98529 100644 --- a/ports/espressif/boards/sunton_esp32_2432S024C/board.c +++ b/ports/espressif/boards/sunton_esp32_2432S024C/board.c @@ -6,13 +6,14 @@ #include "supervisor/board.h" #include "mpconfigboard.h" + +#include "common-hal/microcontroller/Pin.h" +#include "driver/gpio.h" #include "shared-bindings/board/__init__.h" #include "shared-bindings/microcontroller/Pin.h" #include "shared-module/displayio/__init__.h" #include "shared-module/displayio/mipi_constants.h" -#include "driver/gpio.h" -#include "common-hal/microcontroller/Pin.h" -#include "shared-module/os/__init__.h" +#include "supervisor/shared/settings.h" uint8_t display_init_sequence[] = { 0x01, 0x80, 0x80, // # Software reset then delay 0x80 (128ms) @@ -45,22 +46,21 @@ static void display_init(void) { busio_spi_obj_t *spi = &bus->inline_bus; mp_int_t rotation; common_hal_busio_spi_construct(spi, &pin_GPIO14, &pin_GPIO13, &pin_GPIO12, false); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_GPIO2, // TFT_DC Command or data - &pin_GPIO15, // TFT_CS Chip select - NULL, // TFT_RST Reset + MP_OBJ_FROM_PTR(&pin_GPIO2), // TFT_DC Command or data + MP_OBJ_FROM_PTR(&pin_GPIO15), // TFT_CS Chip select + mp_const_none, // TFT_RST Reset 6000000, // Baudrate 0, // Polarity 0); // Phase busdisplay_busdisplay_obj_t *display = &allocate_display()->display; display->base.type = &busdisplay_busdisplay_type; - os_getenv_err_t result = common_hal_os_getenv_int("CIRCUITPY_DISPLAY_ROTATION", &rotation); - if (result != GETENV_OK) { + settings_err_t result = settings_get_int("CIRCUITPY_DISPLAY_ROTATION", &rotation); + if (result != SETTINGS_OK) { rotation = 0; } @@ -95,6 +95,10 @@ static void display_init(void) { } void board_init(void) { + // GPIO26 (SPEAKER) drives the speaker. Default to low, to keep noise off + // it. + espressif_board_reset_pin_number(26); + display_init(); } diff --git a/ports/espressif/boards/sunton_esp32_2432S024C/mpconfigboard.mk b/ports/espressif/boards/sunton_esp32_2432S024C/mpconfigboard.mk index 0b988886cb6..fcb3e98458e 100644 --- a/ports/espressif/boards/sunton_esp32_2432S024C/mpconfigboard.mk +++ b/ports/espressif/boards/sunton_esp32_2432S024C/mpconfigboard.mk @@ -6,9 +6,3 @@ IDF_TARGET = esp32 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB - -CIRCUITPY_ESPCAMERA = 0 - -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 - -CIRCUITPY_BUILD_EXTENSIONS = bin diff --git a/ports/espressif/boards/sunton_esp32_2432S024C/pins.c b/ports/espressif/boards/sunton_esp32_2432S024C/pins.c index a69f3150e92..6544017cd99 100644 --- a/ports/espressif/boards/sunton_esp32_2432S024C/pins.c +++ b/ports/espressif/boards/sunton_esp32_2432S024C/pins.c @@ -46,7 +46,7 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_SD_SCK), MP_ROM_PTR(&pin_GPIO18) }, { MP_ROM_QSTR(MP_QSTR_SD_CS), MP_ROM_PTR(&pin_GPIO5) }, - // ILI9341 dsplay (spi) + // ILI9341 display (spi) { MP_ROM_QSTR(MP_QSTR_LCD_MOSI), MP_ROM_PTR(&pin_GPIO13) }, { MP_ROM_QSTR(MP_QSTR_LCD_MISO), MP_ROM_PTR(&pin_GPIO12) }, { MP_ROM_QSTR(MP_QSTR_LCD_SCK), MP_ROM_PTR(&pin_GPIO14) }, diff --git a/ports/espressif/boards/sunton_esp32_2432S028/board.c b/ports/espressif/boards/sunton_esp32_2432S028/board.c index b249c45dd8f..4816f212249 100644 --- a/ports/espressif/boards/sunton_esp32_2432S028/board.c +++ b/ports/espressif/boards/sunton_esp32_2432S028/board.c @@ -6,13 +6,14 @@ #include "supervisor/board.h" #include "mpconfigboard.h" + +#include "common-hal/microcontroller/Pin.h" +#include "driver/gpio.h" #include "shared-bindings/board/__init__.h" #include "shared-bindings/microcontroller/Pin.h" #include "shared-module/displayio/__init__.h" #include "shared-module/displayio/mipi_constants.h" -#include "driver/gpio.h" -#include "common-hal/microcontroller/Pin.h" -#include "shared-module/os/__init__.h" +#include "supervisor/shared/settings.h" uint8_t display_init_sequence[] = { 0x01, 0x80, 0x80, // # Software reset then delay 0x80 (128ms) @@ -45,22 +46,21 @@ static void display_init(void) { busio_spi_obj_t *spi = &bus->inline_bus; mp_int_t rotation; common_hal_busio_spi_construct(spi, &pin_GPIO14, &pin_GPIO13, &pin_GPIO12, false); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_GPIO2, // TFT_DC Command or data - &pin_GPIO15, // TFT_CS Chip select - NULL, // TFT_RST Reset + MP_OBJ_FROM_PTR(&pin_GPIO2), // TFT_DC Command or data + MP_OBJ_FROM_PTR(&pin_GPIO15), // TFT_CS Chip select + mp_const_none, // TFT_RST Reset 6000000, // Baudrate 0, // Polarity 0); // Phase busdisplay_busdisplay_obj_t *display = &allocate_display()->display; display->base.type = &busdisplay_busdisplay_type; - os_getenv_err_t result = common_hal_os_getenv_int("CIRCUITPY_DISPLAY_ROTATION", &rotation); - if (result != GETENV_OK) { + settings_err_t result = settings_get_int("CIRCUITPY_DISPLAY_ROTATION", &rotation); + if (result != SETTINGS_OK) { rotation = 0; } @@ -95,6 +95,10 @@ static void display_init(void) { } void board_init(void) { + // GPIO26 (SPEAKER) drives the speaker. Default to low, to keep noise off + // it. + espressif_board_reset_pin_number(26); + display_init(); } diff --git a/ports/espressif/boards/sunton_esp32_2432S028/mpconfigboard.mk b/ports/espressif/boards/sunton_esp32_2432S028/mpconfigboard.mk index 444c80227ab..d4c4fb94c71 100644 --- a/ports/espressif/boards/sunton_esp32_2432S028/mpconfigboard.mk +++ b/ports/espressif/boards/sunton_esp32_2432S028/mpconfigboard.mk @@ -6,7 +6,3 @@ IDF_TARGET = esp32 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB - -CIRCUITPY_ESPCAMERA = 0 - -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 diff --git a/ports/espressif/boards/sunton_esp32_2432S028/pins.c b/ports/espressif/boards/sunton_esp32_2432S028/pins.c index b852ab11e04..7791c1685eb 100644 --- a/ports/espressif/boards/sunton_esp32_2432S028/pins.c +++ b/ports/espressif/boards/sunton_esp32_2432S028/pins.c @@ -45,7 +45,7 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_SD_SCK), MP_ROM_PTR(&pin_GPIO18) }, { MP_ROM_QSTR(MP_QSTR_SD_CS), MP_ROM_PTR(&pin_GPIO5) }, - // ILI9341 dsplay (spi) + // ILI9341 display (spi) { MP_ROM_QSTR(MP_QSTR_LCD_MOSI), MP_ROM_PTR(&pin_GPIO13) }, { MP_ROM_QSTR(MP_QSTR_LCD_MISO), MP_ROM_PTR(&pin_GPIO12) }, { MP_ROM_QSTR(MP_QSTR_LCD_SCK), MP_ROM_PTR(&pin_GPIO14) }, diff --git a/ports/espressif/boards/sunton_esp32_2432S032C/board.c b/ports/espressif/boards/sunton_esp32_2432S032C/board.c index b2160e0aa4f..d0b20c55d79 100644 --- a/ports/espressif/boards/sunton_esp32_2432S032C/board.c +++ b/ports/espressif/boards/sunton_esp32_2432S032C/board.c @@ -43,9 +43,9 @@ static void display_init(void) { common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO2, // TFT_DC - &pin_GPIO15, // TFT_CS - NULL, // TFT_RST + MP_OBJ_FROM_PTR(&pin_GPIO2), // TFT_DC + MP_OBJ_FROM_PTR(&pin_GPIO15), // TFT_CS + mp_const_none, // TFT_RST 26600000, // Baudrate 0, // Polarity 0 // Phase @@ -85,6 +85,10 @@ static void display_init(void) { } void board_init(void) { + // GPIO26 (SPEAKER) drives the speaker. Default to low, to keep noise off + // it. + espressif_board_reset_pin_number(26); + display_init(); } diff --git a/ports/espressif/boards/sunton_esp32_2432S032C/mpconfigboard.mk b/ports/espressif/boards/sunton_esp32_2432S032C/mpconfigboard.mk index 15e3b102c9b..f36374a456a 100644 --- a/ports/espressif/boards/sunton_esp32_2432S032C/mpconfigboard.mk +++ b/ports/espressif/boards/sunton_esp32_2432S032C/mpconfigboard.mk @@ -6,5 +6,3 @@ IDF_TARGET = esp32 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 40m CIRCUITPY_ESP_FLASH_SIZE = 4MB - -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/sunton_esp32_8048S050/board.c b/ports/espressif/boards/sunton_esp32_8048S050/board.c index e01f857bfd9..0d3d8f7e8f3 100644 --- a/ports/espressif/boards/sunton_esp32_8048S050/board.c +++ b/ports/espressif/boards/sunton_esp32_8048S050/board.c @@ -6,13 +6,15 @@ #include "supervisor/board.h" #include "mpconfigboard.h" + +#include "driver/gpio.h" #include "shared-bindings/board/__init__.h" #include "shared-bindings/dotclockframebuffer/DotClockFramebuffer.h" #include "shared-bindings/dotclockframebuffer/__init__.h" #include "shared-bindings/framebufferio/FramebufferDisplay.h" #include "shared-bindings/microcontroller/Pin.h" #include "shared-module/displayio/__init__.h" -#include "shared-module/os/__init__.h" +#include "supervisor/shared/settings.h" static const mcu_pin_obj_t *blue_pins[] = { &pin_GPIO8, @@ -43,12 +45,11 @@ static void display_init(void) { // Turn on backlight gpio_set_direction(2, GPIO_MODE_DEF_OUTPUT); gpio_set_level(2, true); - common_hal_never_reset_pin(&pin_GPIO2); dotclockframebuffer_framebuffer_obj_t *framebuffer = &allocate_display_bus_or_raise()->dotclock; framebuffer->base.type = &dotclockframebuffer_framebuffer_type; - os_getenv_err_t result = common_hal_os_getenv_int("CIRCUITPY_DISPLAY_FREQUENCY", &frequency); - if (result != GETENV_OK) { + settings_err_t result = settings_get_int("CIRCUITPY_DISPLAY_FREQUENCY", &frequency); + if (result != SETTINGS_OK) { frequency = 12500000; } diff --git a/ports/espressif/boards/sunton_esp32_8048S070/board.c b/ports/espressif/boards/sunton_esp32_8048S070/board.c index ecc9b7c1236..50b7cebc1db 100644 --- a/ports/espressif/boards/sunton_esp32_8048S070/board.c +++ b/ports/espressif/boards/sunton_esp32_8048S070/board.c @@ -6,6 +6,7 @@ #include "supervisor/board.h" #include "mpconfigboard.h" +#include "driver/gpio.h" #include "shared-bindings/board/__init__.h" #include "shared-bindings/dotclockframebuffer/DotClockFramebuffer.h" #include "shared-bindings/dotclockframebuffer/__init__.h" @@ -41,7 +42,6 @@ static void display_init(void) { // Turn on backlight gpio_set_direction(2, GPIO_MODE_DEF_OUTPUT); gpio_set_level(2, true); - common_hal_never_reset_pin(&pin_GPIO2); dotclockframebuffer_framebuffer_obj_t *framebuffer = &allocate_display_bus_or_raise()->dotclock; framebuffer->base.type = &dotclockframebuffer_framebuffer_type; diff --git a/ports/espressif/boards/targett_module_clip_wroom/board.c b/ports/espressif/boards/targett_module_clip_wroom/board.c index a08886fda1d..a3a9eec0471 100644 --- a/ports/espressif/boards/targett_module_clip_wroom/board.c +++ b/ports/espressif/boards/targett_module_clip_wroom/board.c @@ -5,13 +5,5 @@ // SPDX-License-Identifier: MIT #include "supervisor/board.h" -#include "mpconfigboard.h" -#include "shared-bindings/microcontroller/Pin.h" - -void board_init(void) { - // Crystal - common_hal_never_reset_pin(&pin_GPIO15); - common_hal_never_reset_pin(&pin_GPIO16); -} // Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/targett_module_clip_wroom/mpconfigboard.mk b/ports/espressif/boards/targett_module_clip_wroom/mpconfigboard.mk index 2e0e84456cb..f273085b192 100644 --- a/ports/espressif/boards/targett_module_clip_wroom/mpconfigboard.mk +++ b/ports/espressif/boards/targett_module_clip_wroom/mpconfigboard.mk @@ -8,5 +8,3 @@ IDF_TARGET = esp32s2 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB - -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/targett_module_clip_wrover/board.c b/ports/espressif/boards/targett_module_clip_wrover/board.c index a08886fda1d..a3a9eec0471 100644 --- a/ports/espressif/boards/targett_module_clip_wrover/board.c +++ b/ports/espressif/boards/targett_module_clip_wrover/board.c @@ -5,13 +5,5 @@ // SPDX-License-Identifier: MIT #include "supervisor/board.h" -#include "mpconfigboard.h" -#include "shared-bindings/microcontroller/Pin.h" - -void board_init(void) { - // Crystal - common_hal_never_reset_pin(&pin_GPIO15); - common_hal_never_reset_pin(&pin_GPIO16); -} // Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/thepihut_baguette_s3/board.c b/ports/espressif/boards/thepihut_baguette_s3/board.c new file mode 100644 index 00000000000..7329702be16 --- /dev/null +++ b/ports/espressif/boards/thepihut_baguette_s3/board.c @@ -0,0 +1,20 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 ThePiHut +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" +#include "mpconfigboard.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "driver/gpio.h" + +void board_init(void) { + reset_board(); +} + +void reset_board(void) { + // Board-specific initialization +} + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/thepihut_baguette_s3/mpconfigboard.h b/ports/espressif/boards/thepihut_baguette_s3/mpconfigboard.h new file mode 100644 index 00000000000..87763707983 --- /dev/null +++ b/ports/espressif/boards/thepihut_baguette_s3/mpconfigboard.h @@ -0,0 +1,29 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 ThePiHut +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Board setup +#define MICROPY_HW_BOARD_NAME "ThePiHut Baguette S3" +#define MICROPY_HW_MCU_NAME "ESP32-S3-MINI-1-N8" + +// Status LED (GPIO8) +#define MICROPY_HW_NEOPIXEL (&pin_GPIO8) + +// I2C (Qwiic connector) +#define CIRCUITPY_BOARD_I2C (1) +#define CIRCUITPY_BOARD_I2C_PIN {{.scl = &pin_GPIO48, .sda = &pin_GPIO47}} + +// SPI bus wired to the on-board SD card slot (exposed as board.SD_SPI) +#define CIRCUITPY_BOARD_SPI (1) +#define CIRCUITPY_BOARD_SPI_PIN {{.clock = &pin_GPIO9, .mosi = &pin_GPIO10, .miso = &pin_GPIO11}} + +// UART +#define CIRCUITPY_BOARD_UART (1) +#define CIRCUITPY_BOARD_UART_PIN {{.tx = &pin_GPIO43, .rx = &pin_GPIO44}} + +// For entering safe mode +#define CIRCUITPY_BOOT_BUTTON (&pin_GPIO0) diff --git a/ports/espressif/boards/thepihut_baguette_s3/mpconfigboard.mk b/ports/espressif/boards/thepihut_baguette_s3/mpconfigboard.mk new file mode 100644 index 00000000000..22d0b2f5b1f --- /dev/null +++ b/ports/espressif/boards/thepihut_baguette_s3/mpconfigboard.mk @@ -0,0 +1,16 @@ +CIRCUITPY_CREATOR_ID = 0x20122012 +CIRCUITPY_CREATION_ID = 0x00C90101 + +USB_VID = 0x303A +USB_PID = 0x83E0 +USB_MANUFACTURER = "ThePiHut" +USB_PRODUCT = "Baguette S3" + +IDF_TARGET = esp32s3 + +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m +CIRCUITPY_ESP_FLASH_SIZE = 8MB + +# Include these Python libraries in firmware +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel diff --git a/ports/espressif/boards/thepihut_baguette_s3/pins.c b/ports/espressif/boards/thepihut_baguette_s3/pins.c new file mode 100644 index 00000000000..ad6ec92a491 --- /dev/null +++ b/ports/espressif/boards/thepihut_baguette_s3/pins.c @@ -0,0 +1,148 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 ThePiHut +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +CIRCUITPY_BOARD_BUS_SINGLETON(sd_spi, spi, 0) + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + // 30-pin header. Pins 1-3 are GND, VCC-USB and +3.3V. + // The first name for each pin matches the label printed on the board. + // Dxx names are kept as aliases. + + // Header pin 4 + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO44) }, + { MP_ROM_QSTR(MP_QSTR_D44), MP_ROM_PTR(&pin_GPIO44) }, + + // Header pin 5 + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_D43), MP_ROM_PTR(&pin_GPIO43) }, + + // Header pin 6 + { MP_ROM_QSTR(MP_QSTR_IO48), MP_ROM_PTR(&pin_GPIO48) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO48) }, + { MP_ROM_QSTR(MP_QSTR_D48), MP_ROM_PTR(&pin_GPIO48) }, + + // Header pin 7 + { MP_ROM_QSTR(MP_QSTR_IO47), MP_ROM_PTR(&pin_GPIO47) }, + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO47) }, + { MP_ROM_QSTR(MP_QSTR_D47), MP_ROM_PTR(&pin_GPIO47) }, + + // Header pin 8 + { MP_ROM_QSTR(MP_QSTR_IO2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_GPIO2) }, + + // Header pin 9 + { MP_ROM_QSTR(MP_QSTR_IO3), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_GPIO3) }, + + // Header pin 10 + { MP_ROM_QSTR(MP_QSTR_IO4), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_GPIO4) }, + + // Header pin 11 + { MP_ROM_QSTR(MP_QSTR_IO5), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_GPIO5) }, + + // Header pin 12 + { MP_ROM_QSTR(MP_QSTR_IO6), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_GPIO6) }, + + // Header pin 13 + { MP_ROM_QSTR(MP_QSTR_IO12), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_GPIO12) }, + + // Header pin 14 + { MP_ROM_QSTR(MP_QSTR_IO13), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_GPIO13) }, + + // Header pin 15 + { MP_ROM_QSTR(MP_QSTR_IO14), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_D14), MP_ROM_PTR(&pin_GPIO14) }, + + // Header pin 16 + { MP_ROM_QSTR(MP_QSTR_IO15), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_GPIO15) }, + + // Header pin 17 + { MP_ROM_QSTR(MP_QSTR_IO16), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_D16), MP_ROM_PTR(&pin_GPIO16) }, + + // Header pin 18 + { MP_ROM_QSTR(MP_QSTR_IO17), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_D17), MP_ROM_PTR(&pin_GPIO17) }, + + // Header pin 19 + { MP_ROM_QSTR(MP_QSTR_IO18), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_D18), MP_ROM_PTR(&pin_GPIO18) }, + + // Header pin 20 + { MP_ROM_QSTR(MP_QSTR_IO21), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_D21), MP_ROM_PTR(&pin_GPIO21) }, + + // Header pin 21 + { MP_ROM_QSTR(MP_QSTR_IO33), MP_ROM_PTR(&pin_GPIO33) }, + { MP_ROM_QSTR(MP_QSTR_D33), MP_ROM_PTR(&pin_GPIO33) }, + + // Header pin 22 + { MP_ROM_QSTR(MP_QSTR_IO34), MP_ROM_PTR(&pin_GPIO34) }, + { MP_ROM_QSTR(MP_QSTR_D34), MP_ROM_PTR(&pin_GPIO34) }, + + // Header pin 23 + { MP_ROM_QSTR(MP_QSTR_IO35), MP_ROM_PTR(&pin_GPIO35) }, + { MP_ROM_QSTR(MP_QSTR_D35), MP_ROM_PTR(&pin_GPIO35) }, + + // Header pin 24 + { MP_ROM_QSTR(MP_QSTR_IO36), MP_ROM_PTR(&pin_GPIO36) }, + { MP_ROM_QSTR(MP_QSTR_D36), MP_ROM_PTR(&pin_GPIO36) }, + + // Header pin 25 + { MP_ROM_QSTR(MP_QSTR_IO37), MP_ROM_PTR(&pin_GPIO37) }, + { MP_ROM_QSTR(MP_QSTR_D37), MP_ROM_PTR(&pin_GPIO37) }, + + // Header pin 26 + { MP_ROM_QSTR(MP_QSTR_IO38), MP_ROM_PTR(&pin_GPIO38) }, + { MP_ROM_QSTR(MP_QSTR_D38), MP_ROM_PTR(&pin_GPIO38) }, + + // Header pin 27 + { MP_ROM_QSTR(MP_QSTR_IO39), MP_ROM_PTR(&pin_GPIO39) }, + { MP_ROM_QSTR(MP_QSTR_D39), MP_ROM_PTR(&pin_GPIO39) }, + + // Header pin 28 + { MP_ROM_QSTR(MP_QSTR_IO40), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_D40), MP_ROM_PTR(&pin_GPIO40) }, + + // Header pin 29 + { MP_ROM_QSTR(MP_QSTR_IO41), MP_ROM_PTR(&pin_GPIO41) }, + { MP_ROM_QSTR(MP_QSTR_D41), MP_ROM_PTR(&pin_GPIO41) }, + + // Header pin 30 + { MP_ROM_QSTR(MP_QSTR_IO42), MP_ROM_PTR(&pin_GPIO42) }, + { MP_ROM_QSTR(MP_QSTR_D42), MP_ROM_PTR(&pin_GPIO42) }, + + // SD card slot (internal, not on the header) + { MP_ROM_QSTR(MP_QSTR_SD_CS), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_SD_SCK), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_SD_MOSI), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_SD_MISO), MP_ROM_PTR(&pin_GPIO11) }, + + // Button (internal, GPIO0) + { MP_ROM_QSTR(MP_QSTR_BUTTON), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_BOOT), MP_ROM_PTR(&pin_GPIO0) }, + + // RGB LED (internal, GPIO8) + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO8) }, + + // Buses + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, + { MP_ROM_QSTR(MP_QSTR_STEMMA_I2C), MP_ROM_PTR(&board_i2c_obj) }, + { MP_ROM_QSTR(MP_QSTR_SD_SPI), MP_ROM_PTR(&board_sd_spi_obj) }, + { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/espressif/boards/thepihut_baguette_s3/sdkconfig b/ports/espressif/boards/thepihut_baguette_s3/sdkconfig new file mode 100644 index 00000000000..e9628662160 --- /dev/null +++ b/ports/espressif/boards/thepihut_baguette_s3/sdkconfig @@ -0,0 +1,14 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Component config +# +# +# LWIP +# +# end of LWIP + +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/boards/thingpulse_pendrive_s3/mpconfigboard.mk b/ports/espressif/boards/thingpulse_pendrive_s3/mpconfigboard.mk index 66f5a4aba70..cb273b7a45d 100644 --- a/ports/espressif/boards/thingpulse_pendrive_s3/mpconfigboard.mk +++ b/ports/espressif/boards/thingpulse_pendrive_s3/mpconfigboard.mk @@ -13,7 +13,8 @@ CIRCUITPY_ESP_PSRAM_SIZE = 2MB CIRCUITPY_ESP_PSRAM_MODE = qio CIRCUITPY_ESP_PSRAM_FREQ = 80m +# No pins. CIRCUITPY_ESPCAMERA = 0 -CIRCUITPY_DISPLAYIO = 1 +CIRCUITPY_PARALLELDISPLAYBUS = 0 FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel diff --git a/ports/espressif/boards/ttgo_t8_v1_7/mpconfigboard.mk b/ports/espressif/boards/ttgo_t8_v1_7/mpconfigboard.mk index eb9259cdf0e..aa9f2e1c1b3 100644 --- a/ports/espressif/boards/ttgo_t8_v1_7/mpconfigboard.mk +++ b/ports/espressif/boards/ttgo_t8_v1_7/mpconfigboard.mk @@ -10,5 +10,3 @@ CIRCUITPY_ESP_FLASH_SIZE = 4MB CIRCUITPY_ESP_PSRAM_SIZE = 4MB CIRCUITPY_ESP_PSRAM_MODE = qio CIRCUITPY_ESP_PSRAM_FREQ = 80m - -CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/unexpectedmaker_bling/mpconfigboard.h b/ports/espressif/boards/unexpectedmaker_bling/mpconfigboard.h index 671f714daea..f9aad2c4ba3 100644 --- a/ports/espressif/boards/unexpectedmaker_bling/mpconfigboard.h +++ b/ports/espressif/boards/unexpectedmaker_bling/mpconfigboard.h @@ -25,3 +25,6 @@ #define DEFAULT_UART_BUS_TX (&pin_GPIO43) #define DOUBLE_TAP_PIN (&pin_GPIO47) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/unexpectedmaker_blizzard_s3/mpconfigboard.h b/ports/espressif/boards/unexpectedmaker_blizzard_s3/mpconfigboard.h index dd677dad7b9..86275b0d784 100644 --- a/ports/espressif/boards/unexpectedmaker_blizzard_s3/mpconfigboard.h +++ b/ports/espressif/boards/unexpectedmaker_blizzard_s3/mpconfigboard.h @@ -25,3 +25,6 @@ #define DEFAULT_UART_BUS_TX (&pin_GPIO43) #define DOUBLE_TAP_PIN (&pin_GPIO47) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/unexpectedmaker_edges3d/board.c b/ports/espressif/boards/unexpectedmaker_edges3d/board.c new file mode 100644 index 00000000000..a3a9eec0471 --- /dev/null +++ b/ports/espressif/boards/unexpectedmaker_edges3d/board.c @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/unexpectedmaker_edges3d/mpconfigboard.h b/ports/espressif/boards/unexpectedmaker_edges3d/mpconfigboard.h new file mode 100644 index 00000000000..16c5949bb84 --- /dev/null +++ b/ports/espressif/boards/unexpectedmaker_edges3d/mpconfigboard.h @@ -0,0 +1,22 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Scott Shawcroft for Adafruit +// Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Micropython setup + +#define MICROPY_HW_BOARD_NAME "EdgeS3[D]" +#define MICROPY_HW_MCU_NAME "ESP32S3" + +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO9) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO8) + +#define DEFAULT_UART_BUS_RX (&pin_GPIO44) +#define DEFAULT_UART_BUS_TX (&pin_GPIO43) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/unexpectedmaker_edges3d/mpconfigboard.mk b/ports/espressif/boards/unexpectedmaker_edges3d/mpconfigboard.mk new file mode 100644 index 00000000000..e471a2b37b8 --- /dev/null +++ b/ports/espressif/boards/unexpectedmaker_edges3d/mpconfigboard.mk @@ -0,0 +1,16 @@ +USB_VID = 0x303A +USB_PID = 0x82DD +USB_PRODUCT = "EdgeS3[D]" +USB_MANUFACTURER = "UnexpectedMaker" + +IDF_TARGET = esp32s3 + +CIRCUITPY_ESP_FLASH_SIZE = 8MB +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m + +CIRCUITPY_ESP_PSRAM_SIZE = 2MB +CIRCUITPY_ESP_PSRAM_MODE = qio +CIRCUITPY_ESP_PSRAM_FREQ = 80m + +CIRCUITPY_STAGE = 1 diff --git a/ports/espressif/boards/unexpectedmaker_edges3d/pins.c b/ports/espressif/boards/unexpectedmaker_edges3d/pins.c new file mode 100644 index 00000000000..046e7b23ce4 --- /dev/null +++ b/ports/espressif/boards/unexpectedmaker_edges3d/pins.c @@ -0,0 +1,128 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit +// Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { MP_ROM_QSTR(MP_QSTR_IO0), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_GPIO0) }, + + { MP_ROM_QSTR(MP_QSTR_IO1), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO1) }, + + { MP_ROM_QSTR(MP_QSTR_IO2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_GPIO2) }, + + { MP_ROM_QSTR(MP_QSTR_IO3), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_GPIO3) }, + + { MP_ROM_QSTR(MP_QSTR_IO4), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_GPIO4) }, + + { MP_ROM_QSTR(MP_QSTR_IO5), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_GPIO5) }, + + { MP_ROM_QSTR(MP_QSTR_IO7), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_A6), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_D7), MP_ROM_PTR(&pin_GPIO7) }, + + { 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_A7), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_D8), 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_A8), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_GPIO9) }, + + { MP_ROM_QSTR(MP_QSTR_IO10), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_A9), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_GPIO10) }, + + { MP_ROM_QSTR(MP_QSTR_IO11), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_A10), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_GPIO11) }, + + { MP_ROM_QSTR(MP_QSTR_IO12), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_A11), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_GPIO12) }, + + { MP_ROM_QSTR(MP_QSTR_IO13), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_A12), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_GPIO13) }, + + { MP_ROM_QSTR(MP_QSTR_IO14), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_A13), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_D14), MP_ROM_PTR(&pin_GPIO14) }, + + { MP_ROM_QSTR(MP_QSTR_IO15), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_A14), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_GPIO15) }, + + { MP_ROM_QSTR(MP_QSTR_IO16), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_A15), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_D16), MP_ROM_PTR(&pin_GPIO16) }, + + { MP_ROM_QSTR(MP_QSTR_IO17), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_A16), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_D17), MP_ROM_PTR(&pin_GPIO17) }, + + { MP_ROM_QSTR(MP_QSTR_IO18), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_A17), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_D18), MP_ROM_PTR(&pin_GPIO18) }, + + { MP_ROM_QSTR(MP_QSTR_IO21), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_D21), MP_ROM_PTR(&pin_GPIO21) }, + + { MP_ROM_QSTR(MP_QSTR_IO39), MP_ROM_PTR(&pin_GPIO39) }, + { MP_ROM_QSTR(MP_QSTR_D39), MP_ROM_PTR(&pin_GPIO39) }, + { MP_ROM_QSTR(MP_QSTR_MTCK), MP_ROM_PTR(&pin_GPIO39) }, + + { MP_ROM_QSTR(MP_QSTR_IO40), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_D40), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_MTDO), MP_ROM_PTR(&pin_GPIO40) }, + + { MP_ROM_QSTR(MP_QSTR_IO41), MP_ROM_PTR(&pin_GPIO41) }, + { MP_ROM_QSTR(MP_QSTR_D41), MP_ROM_PTR(&pin_GPIO41) }, + { MP_ROM_QSTR(MP_QSTR_MTDI), MP_ROM_PTR(&pin_GPIO41) }, + + { MP_ROM_QSTR(MP_QSTR_IO42), MP_ROM_PTR(&pin_GPIO42) }, + { MP_ROM_QSTR(MP_QSTR_D42), MP_ROM_PTR(&pin_GPIO42) }, + { MP_ROM_QSTR(MP_QSTR_MTMS), MP_ROM_PTR(&pin_GPIO42) }, + + { MP_ROM_QSTR(MP_QSTR_IO43), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_D43), 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_D44), MP_ROM_PTR(&pin_GPIO44) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO44) }, + + { MP_ROM_QSTR(MP_QSTR_IO45), MP_ROM_PTR(&pin_GPIO45) }, + { MP_ROM_QSTR(MP_QSTR_D45), MP_ROM_PTR(&pin_GPIO45) }, + + { MP_ROM_QSTR(MP_QSTR_IO46), MP_ROM_PTR(&pin_GPIO46) }, + { MP_ROM_QSTR(MP_QSTR_D46), MP_ROM_PTR(&pin_GPIO46) }, + + // MAX17048 fuel gauge interrupt + { MP_ROM_QSTR(MP_QSTR_FG_INT), MP_ROM_PTR(&pin_GPIO6) }, + + // RF antenna switch + { MP_ROM_QSTR(MP_QSTR_ANT_SWITCH), MP_ROM_PTR(&pin_GPIO38) }, + + { 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_module_globals_table); diff --git a/ports/espressif/boards/unexpectedmaker_edges3d/sdkconfig b/ports/espressif/boards/unexpectedmaker_edges3d/sdkconfig new file mode 100644 index 00000000000..e9628662160 --- /dev/null +++ b/ports/espressif/boards/unexpectedmaker_edges3d/sdkconfig @@ -0,0 +1,14 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Component config +# +# +# LWIP +# +# end of LWIP + +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/boards/unexpectedmaker_feathers2/mpconfigboard.h b/ports/espressif/boards/unexpectedmaker_feathers2/mpconfigboard.h index d8349cdb58b..1df282a3326 100644 --- a/ports/espressif/boards/unexpectedmaker_feathers2/mpconfigboard.h +++ b/ports/espressif/boards/unexpectedmaker_feathers2/mpconfigboard.h @@ -25,3 +25,6 @@ #define DEFAULT_UART_BUS_RX (&pin_GPIO44) #define DEFAULT_UART_BUS_TX (&pin_GPIO43) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/unexpectedmaker_feathers2/mpconfigboard.mk b/ports/espressif/boards/unexpectedmaker_feathers2/mpconfigboard.mk index f3a6e36ef25..58f053f36c8 100644 --- a/ports/espressif/boards/unexpectedmaker_feathers2/mpconfigboard.mk +++ b/ports/espressif/boards/unexpectedmaker_feathers2/mpconfigboard.mk @@ -17,3 +17,10 @@ CIRCUITPY_BITBANG_APA102 = 1 # Include these Python libraries in firmware. # FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_DotStar + +# Fast e-paper does not fit in internal RAM. +CIRCUITPY_EPAPERDISPLAY_FAST = 0 + +# The ESP32-S2 shares its 152KB SRAM between IRAM and DRAM. -O2 overflows +# dram0_0_seg, so use the same optimization level as the smaller-flash boards. +OPTIMIZATION_FLAGS ?= -Os diff --git a/ports/espressif/boards/unexpectedmaker_feathers2_neo/mpconfigboard.h b/ports/espressif/boards/unexpectedmaker_feathers2_neo/mpconfigboard.h index 1dd6b79a9b9..5141c6d7793 100644 --- a/ports/espressif/boards/unexpectedmaker_feathers2_neo/mpconfigboard.h +++ b/ports/espressif/boards/unexpectedmaker_feathers2_neo/mpconfigboard.h @@ -25,3 +25,6 @@ #define DEFAULT_UART_BUS_RX (&pin_GPIO44) #define DEFAULT_UART_BUS_TX (&pin_GPIO43) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/unexpectedmaker_feathers2_prerelease/mpconfigboard.h b/ports/espressif/boards/unexpectedmaker_feathers2_prerelease/mpconfigboard.h index 1d6c9035ac6..c2f9197fad8 100644 --- a/ports/espressif/boards/unexpectedmaker_feathers2_prerelease/mpconfigboard.h +++ b/ports/espressif/boards/unexpectedmaker_feathers2_prerelease/mpconfigboard.h @@ -25,3 +25,6 @@ #define DEFAULT_UART_BUS_RX (&pin_GPIO44) #define DEFAULT_UART_BUS_TX (&pin_GPIO43) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/unexpectedmaker_feathers2_prerelease/mpconfigboard.mk b/ports/espressif/boards/unexpectedmaker_feathers2_prerelease/mpconfigboard.mk index f3a6e36ef25..58f053f36c8 100644 --- a/ports/espressif/boards/unexpectedmaker_feathers2_prerelease/mpconfigboard.mk +++ b/ports/espressif/boards/unexpectedmaker_feathers2_prerelease/mpconfigboard.mk @@ -17,3 +17,10 @@ CIRCUITPY_BITBANG_APA102 = 1 # Include these Python libraries in firmware. # FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_DotStar + +# Fast e-paper does not fit in internal RAM. +CIRCUITPY_EPAPERDISPLAY_FAST = 0 + +# The ESP32-S2 shares its 152KB SRAM between IRAM and DRAM. -O2 overflows +# dram0_0_seg, so use the same optimization level as the smaller-flash boards. +OPTIMIZATION_FLAGS ?= -Os diff --git a/ports/espressif/boards/unexpectedmaker_feathers3/mpconfigboard.h b/ports/espressif/boards/unexpectedmaker_feathers3/mpconfigboard.h index 53157a1ff11..dc48fe3f40f 100644 --- a/ports/espressif/boards/unexpectedmaker_feathers3/mpconfigboard.h +++ b/ports/espressif/boards/unexpectedmaker_feathers3/mpconfigboard.h @@ -28,3 +28,6 @@ #define DEFAULT_UART_BUS_TX (&pin_GPIO43) #define DOUBLE_TAP_PIN (&pin_GPIO47) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/unexpectedmaker_feathers3_neo/mpconfigboard.h b/ports/espressif/boards/unexpectedmaker_feathers3_neo/mpconfigboard.h index 037190d9aa8..18f2513e6af 100644 --- a/ports/espressif/boards/unexpectedmaker_feathers3_neo/mpconfigboard.h +++ b/ports/espressif/boards/unexpectedmaker_feathers3_neo/mpconfigboard.h @@ -27,3 +27,6 @@ #define DEFAULT_UART_BUS_TX (&pin_GPIO43) // #define DOUBLE_TAP_PIN (&pin_GPIO47) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/unexpectedmaker_feathers3d/board.c b/ports/espressif/boards/unexpectedmaker_feathers3d/board.c new file mode 100644 index 00000000000..a3a9eec0471 --- /dev/null +++ b/ports/espressif/boards/unexpectedmaker_feathers3d/board.c @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/unexpectedmaker_feathers3d/mpconfigboard.h b/ports/espressif/boards/unexpectedmaker_feathers3d/mpconfigboard.h new file mode 100644 index 00000000000..f068ad3ac48 --- /dev/null +++ b/ports/espressif/boards/unexpectedmaker_feathers3d/mpconfigboard.h @@ -0,0 +1,33 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Micropython setup + +#define MICROPY_HW_BOARD_NAME "FeatherS3[D]" +#define MICROPY_HW_MCU_NAME "ESP32S3" + +#define MICROPY_HW_NEOPIXEL (&pin_GPIO40) +#define CIRCUITPY_STATUS_LED_POWER (&pin_GPIO39) + +#define MICROPY_HW_LED_STATUS (&pin_GPIO13) + +#define CIRCUITPY_BOARD_I2C (2) +#define CIRCUITPY_BOARD_I2C_PIN {{.scl = &pin_GPIO9, .sda = &pin_GPIO8}, \ + {.scl = &pin_GPIO15, .sda = &pin_GPIO16}} + +#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 DOUBLE_TAP_PIN (&pin_GPIO47) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/unexpectedmaker_feathers3d/mpconfigboard.mk b/ports/espressif/boards/unexpectedmaker_feathers3d/mpconfigboard.mk new file mode 100644 index 00000000000..920895add05 --- /dev/null +++ b/ports/espressif/boards/unexpectedmaker_feathers3d/mpconfigboard.mk @@ -0,0 +1,19 @@ +USB_VID = 0x303A +USB_PID = 0x80D7 +USB_PRODUCT = "FeatherS3[D]" +USB_MANUFACTURER = "UnexpectedMaker" + +IDF_TARGET = esp32s3 + +CIRCUITPY_ESP_FLASH_SIZE = 16MB +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m + +CIRCUITPY_ESP_PSRAM_SIZE = 8MB +CIRCUITPY_ESP_PSRAM_MODE = qio +CIRCUITPY_ESP_PSRAM_FREQ = 80m + +#CIRCUITPY_BITBANG_NEOPIXEL = 1 + +# Include these Python libraries in firmware. +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel diff --git a/ports/espressif/boards/unexpectedmaker_feathers3d/pins.c b/ports/espressif/boards/unexpectedmaker_feathers3d/pins.c new file mode 100644 index 00000000000..31521bf45f0 --- /dev/null +++ b/ports/espressif/boards/unexpectedmaker_feathers3d/pins.c @@ -0,0 +1,144 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +CIRCUITPY_BOARD_BUS_SINGLETON(stemma_i2c, i2c, 1) + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { 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_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_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_IO12), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_D17), MP_ROM_PTR(&pin_GPIO12) }, + + { 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_IO36), MP_ROM_PTR(&pin_GPIO36) }, + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_GPIO36) }, + { MP_ROM_QSTR(MP_QSTR_D25), MP_ROM_PTR(&pin_GPIO36) }, + + { 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_D24), MP_ROM_PTR(&pin_GPIO35) }, + + { MP_ROM_QSTR(MP_QSTR_IO37), MP_ROM_PTR(&pin_GPIO37) }, + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO37) }, + { MP_ROM_QSTR(MP_QSTR_D23), MP_ROM_PTR(&pin_GPIO37) }, + + { 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) }, + + { 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_IO42), MP_ROM_PTR(&pin_GPIO42) }, + // { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_GPIO42) }, + + { 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_A11), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_D21), 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_A12), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_D22), MP_ROM_PTR(&pin_GPIO9) }, + + { MP_ROM_QSTR(MP_QSTR_IO33), MP_ROM_PTR(&pin_GPIO33) }, + { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_GPIO33) }, + + { MP_ROM_QSTR(MP_QSTR_IO38), MP_ROM_PTR(&pin_GPIO38) }, + { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_GPIO38) }, + + { MP_ROM_QSTR(MP_QSTR_IO1), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_A6), MP_ROM_PTR(&pin_GPIO1) }, + + { MP_ROM_QSTR(MP_QSTR_IO3), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_A7), MP_ROM_PTR(&pin_GPIO3) }, + + { MP_ROM_QSTR(MP_QSTR_IO7), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_A8), MP_ROM_PTR(&pin_GPIO7) }, + + { MP_ROM_QSTR(MP_QSTR_IO10), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_A9), MP_ROM_PTR(&pin_GPIO10) }, + + { MP_ROM_QSTR(MP_QSTR_IO11), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_A10), MP_ROM_PTR(&pin_GPIO11) }, + + // Blue LED + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO13) }, + + // STEMMA QT Vertical Connector I2C IO + { MP_ROM_QSTR(MP_QSTR_IO15), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_SCL2), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_IO16), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_SDA2), MP_ROM_PTR(&pin_GPIO16) }, + + // MAX17048 fuel gauge interrupt + { MP_ROM_QSTR(MP_QSTR_FG_INT), MP_ROM_PTR(&pin_GPIO2) }, + + // 5V present sense pin + { MP_ROM_QSTR(MP_QSTR_VBUS), MP_ROM_PTR(&pin_GPIO34) }, + { MP_ROM_QSTR(MP_QSTR_VBUS_SENSE), MP_ROM_PTR(&pin_GPIO34) }, + + // Neopixel pins + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL_POWER), MP_ROM_PTR(&pin_GPIO39) }, + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO40) }, + + // Ambient Light Sensor + { MP_ROM_QSTR(MP_QSTR_IO4), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_AMB), MP_ROM_PTR(&pin_GPIO4) }, + + // Second LDO Enable control + { MP_ROM_QSTR(MP_QSTR_LDO2), MP_ROM_PTR(&pin_GPIO39) }, + { MP_ROM_QSTR(MP_QSTR_IO39), MP_ROM_PTR(&pin_GPIO39) }, + + // RF antenna switch + { MP_ROM_QSTR(MP_QSTR_ANT_SWITCH), MP_ROM_PTR(&pin_GPIO41) }, + + // I2C + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, + { MP_ROM_QSTR(MP_QSTR_STEMMA_I2C), MP_ROM_PTR(&board_i2c_obj) }, + { MP_ROM_QSTR(MP_QSTR_STEMMA_VERTICAL_I2C), MP_ROM_PTR(&board_stemma_i2c_obj) }, + { MP_ROM_QSTR(MP_QSTR_STEMMA_I2C2), MP_ROM_PTR(&board_stemma_i2c_obj) }, + { MP_ROM_QSTR(MP_QSTR_I2C2), MP_ROM_PTR(&board_stemma_i2c_obj) }, + + // SPI + { MP_ROM_QSTR(MP_QSTR_SPI), MP_ROM_PTR(&board_spi_obj) }, + + // UART + { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/espressif/boards/unexpectedmaker_feathers3d/sdkconfig b/ports/espressif/boards/unexpectedmaker_feathers3d/sdkconfig new file mode 100644 index 00000000000..e9628662160 --- /dev/null +++ b/ports/espressif/boards/unexpectedmaker_feathers3d/sdkconfig @@ -0,0 +1,14 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Component config +# +# +# LWIP +# +# end of LWIP + +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/boards/unexpectedmaker_nanos3/mpconfigboard.h b/ports/espressif/boards/unexpectedmaker_nanos3/mpconfigboard.h index 022d6f3373e..f59ce34fb6a 100644 --- a/ports/espressif/boards/unexpectedmaker_nanos3/mpconfigboard.h +++ b/ports/espressif/boards/unexpectedmaker_nanos3/mpconfigboard.h @@ -23,3 +23,6 @@ #define DEFAULT_UART_BUS_RX (&pin_GPIO44) #define DEFAULT_UART_BUS_TX (&pin_GPIO43) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/unexpectedmaker_omgs3/mpconfigboard.h b/ports/espressif/boards/unexpectedmaker_omgs3/mpconfigboard.h index 5fd666524c7..5ec5945cdfe 100644 --- a/ports/espressif/boards/unexpectedmaker_omgs3/mpconfigboard.h +++ b/ports/espressif/boards/unexpectedmaker_omgs3/mpconfigboard.h @@ -24,3 +24,6 @@ #define DEFAULT_UART_BUS_RX (&pin_GPIO44) #define DEFAULT_UART_BUS_TX (&pin_GPIO43) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/unexpectedmaker_pros3/mpconfigboard.h b/ports/espressif/boards/unexpectedmaker_pros3/mpconfigboard.h index bec68c88cb1..dfef3399844 100644 --- a/ports/espressif/boards/unexpectedmaker_pros3/mpconfigboard.h +++ b/ports/espressif/boards/unexpectedmaker_pros3/mpconfigboard.h @@ -25,3 +25,6 @@ #define DEFAULT_UART_BUS_TX (&pin_GPIO43) #define DOUBLE_TAP_PIN (&pin_GPIO47) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/unexpectedmaker_pros3d/board.c b/ports/espressif/boards/unexpectedmaker_pros3d/board.c new file mode 100644 index 00000000000..a3a9eec0471 --- /dev/null +++ b/ports/espressif/boards/unexpectedmaker_pros3d/board.c @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/unexpectedmaker_pros3d/mpconfigboard.h b/ports/espressif/boards/unexpectedmaker_pros3d/mpconfigboard.h new file mode 100644 index 00000000000..471f851db3f --- /dev/null +++ b/ports/espressif/boards/unexpectedmaker_pros3d/mpconfigboard.h @@ -0,0 +1,30 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Micropython setup + +#define MICROPY_HW_BOARD_NAME "ProS3[D]" +#define MICROPY_HW_MCU_NAME "ESP32S3" + +#define MICROPY_HW_NEOPIXEL (&pin_GPIO18) +#define CIRCUITPY_STATUS_LED_POWER (&pin_GPIO17) + +#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 DOUBLE_TAP_PIN (&pin_GPIO47) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/unexpectedmaker_pros3d/mpconfigboard.mk b/ports/espressif/boards/unexpectedmaker_pros3d/mpconfigboard.mk new file mode 100644 index 00000000000..7b3b656cf55 --- /dev/null +++ b/ports/espressif/boards/unexpectedmaker_pros3d/mpconfigboard.mk @@ -0,0 +1,19 @@ +USB_VID = 0x303A +USB_PID = 0x80D4 +USB_PRODUCT = "ProS3[D]" +USB_MANUFACTURER = "UnexpectedMaker" + +IDF_TARGET = esp32s3 + +CIRCUITPY_ESP_FLASH_SIZE = 16MB +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m + +CIRCUITPY_ESP_PSRAM_SIZE = 8MB +CIRCUITPY_ESP_PSRAM_MODE = qio +CIRCUITPY_ESP_PSRAM_FREQ = 80m + +# CIRCUITPY_BITBANG_NEOPIXEL = 1 + +# Include these Python libraries in firmware. +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel diff --git a/ports/espressif/boards/unexpectedmaker_pros3d/pins.c b/ports/espressif/boards/unexpectedmaker_pros3d/pins.c new file mode 100644 index 00000000000..44f61e5984f --- /dev/null +++ b/ports/espressif/boards/unexpectedmaker_pros3d/pins.c @@ -0,0 +1,144 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { MP_ROM_QSTR(MP_QSTR_IO0), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_GPIO0) }, + + { MP_ROM_QSTR(MP_QSTR_IO1), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO1) }, + + { MP_ROM_QSTR(MP_QSTR_IO2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_GPIO2) }, + + { MP_ROM_QSTR(MP_QSTR_IO3), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_GPIO3) }, + + { MP_ROM_QSTR(MP_QSTR_IO4), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_GPIO4) }, + + { MP_ROM_QSTR(MP_QSTR_IO5), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_GPIO5) }, + + { MP_ROM_QSTR(MP_QSTR_IO6), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_GPIO6) }, + + { MP_ROM_QSTR(MP_QSTR_IO7), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_A6), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_D7), MP_ROM_PTR(&pin_GPIO7) }, + + { 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_A7), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_D8), 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_A8), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_GPIO9) }, + + + { MP_ROM_QSTR(MP_QSTR_IO12), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_A11), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_GPIO12) }, + + { MP_ROM_QSTR(MP_QSTR_IO13), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_A12), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_GPIO13) }, + + { MP_ROM_QSTR(MP_QSTR_IO14), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_A13), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_D14), MP_ROM_PTR(&pin_GPIO14) }, + + { MP_ROM_QSTR(MP_QSTR_IO15), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_A14), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_GPIO15) }, + + { MP_ROM_QSTR(MP_QSTR_IO16), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_A15), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_D16), MP_ROM_PTR(&pin_GPIO16) }, + + { MP_ROM_QSTR(MP_QSTR_IO21), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_D21), MP_ROM_PTR(&pin_GPIO21) }, + + { MP_ROM_QSTR(MP_QSTR_IO34), MP_ROM_PTR(&pin_GPIO34) }, + { MP_ROM_QSTR(MP_QSTR_D34), MP_ROM_PTR(&pin_GPIO34) }, + + { 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_MO), MP_ROM_PTR(&pin_GPIO35) }, + { MP_ROM_QSTR(MP_QSTR_SDO), MP_ROM_PTR(&pin_GPIO35) }, + { MP_ROM_QSTR(MP_QSTR_D35), MP_ROM_PTR(&pin_GPIO35) }, + + { MP_ROM_QSTR(MP_QSTR_IO37), MP_ROM_PTR(&pin_GPIO37) }, + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO37) }, + { MP_ROM_QSTR(MP_QSTR_MI), MP_ROM_PTR(&pin_GPIO37) }, + { MP_ROM_QSTR(MP_QSTR_SDI), MP_ROM_PTR(&pin_GPIO37) }, + { MP_ROM_QSTR(MP_QSTR_D37), MP_ROM_PTR(&pin_GPIO37) }, + + { MP_ROM_QSTR(MP_QSTR_IO36), MP_ROM_PTR(&pin_GPIO36) }, + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_GPIO36) }, + { MP_ROM_QSTR(MP_QSTR_D36), MP_ROM_PTR(&pin_GPIO36) }, + + { MP_ROM_QSTR(MP_QSTR_IO38), MP_ROM_PTR(&pin_GPIO38) }, + { MP_ROM_QSTR(MP_QSTR_D38), MP_ROM_PTR(&pin_GPIO38) }, + + { MP_ROM_QSTR(MP_QSTR_IO39), MP_ROM_PTR(&pin_GPIO39) }, + { MP_ROM_QSTR(MP_QSTR_MTCK), MP_ROM_PTR(&pin_GPIO39) }, + { MP_ROM_QSTR(MP_QSTR_D39), MP_ROM_PTR(&pin_GPIO39) }, + + { MP_ROM_QSTR(MP_QSTR_IO40), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_MTDO), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_D40), MP_ROM_PTR(&pin_GPIO40) }, + + { MP_ROM_QSTR(MP_QSTR_IO41), MP_ROM_PTR(&pin_GPIO41) }, + { MP_ROM_QSTR(MP_QSTR_MTDI), MP_ROM_PTR(&pin_GPIO41) }, + { MP_ROM_QSTR(MP_QSTR_D41), MP_ROM_PTR(&pin_GPIO41) }, + + { MP_ROM_QSTR(MP_QSTR_IO42), MP_ROM_PTR(&pin_GPIO42) }, + { MP_ROM_QSTR(MP_QSTR_MTMS), MP_ROM_PTR(&pin_GPIO42) }, + { MP_ROM_QSTR(MP_QSTR_D42), MP_ROM_PTR(&pin_GPIO42) }, + + { MP_ROM_QSTR(MP_QSTR_IO43), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_D43), 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_D44), MP_ROM_PTR(&pin_GPIO44) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO44) }, + + // MAX17048 fuel gauge interrupt + { MP_ROM_QSTR(MP_QSTR_FG_INT), MP_ROM_PTR(&pin_GPIO10) }, + + // RF antenna switch + { MP_ROM_QSTR(MP_QSTR_ANT_SWITCH), MP_ROM_PTR(&pin_GPIO11) }, + + // 5V present sense pin + { MP_ROM_QSTR(MP_QSTR_VBUS), MP_ROM_PTR(&pin_GPIO33) }, + { MP_ROM_QSTR(MP_QSTR_VBUS_SENSE), MP_ROM_PTR(&pin_GPIO33) }, + + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL_POWER), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO18) }, + + { MP_ROM_QSTR(MP_QSTR_LDO2), MP_ROM_PTR(&pin_GPIO17) }, // Second LDO Enable control + { MP_ROM_QSTR(MP_QSTR_IO17), MP_ROM_PTR(&pin_GPIO17) }, // Second LDO Enable control + + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, + { MP_ROM_QSTR(MP_QSTR_STEMMA_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_module_globals_table); diff --git a/ports/espressif/boards/unexpectedmaker_pros3d/sdkconfig b/ports/espressif/boards/unexpectedmaker_pros3d/sdkconfig new file mode 100644 index 00000000000..e9628662160 --- /dev/null +++ b/ports/espressif/boards/unexpectedmaker_pros3d/sdkconfig @@ -0,0 +1,14 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Component config +# +# +# LWIP +# +# end of LWIP + +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/boards/unexpectedmaker_rgbtouch_mini/mpconfigboard.h b/ports/espressif/boards/unexpectedmaker_rgbtouch_mini/mpconfigboard.h index 2cf95fa9a6d..b0bbcd2d457 100644 --- a/ports/espressif/boards/unexpectedmaker_rgbtouch_mini/mpconfigboard.h +++ b/ports/espressif/boards/unexpectedmaker_rgbtouch_mini/mpconfigboard.h @@ -17,3 +17,6 @@ #define DEFAULT_I2C_BUS_SCL (&pin_GPIO9) #define DEFAULT_I2C_BUS_SDA (&pin_GPIO8) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/unexpectedmaker_tinyc6/mpconfigboard.h b/ports/espressif/boards/unexpectedmaker_tinyc6/mpconfigboard.h index 3e4995437d5..6f7e84c5c75 100644 --- a/ports/espressif/boards/unexpectedmaker_tinyc6/mpconfigboard.h +++ b/ports/espressif/boards/unexpectedmaker_tinyc6/mpconfigboard.h @@ -23,3 +23,6 @@ #define DEFAULT_UART_BUS_RX (&pin_GPIO17) #define DEFAULT_UART_BUS_TX (&pin_GPIO16) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/unexpectedmaker_tinyc6d/board.c b/ports/espressif/boards/unexpectedmaker_tinyc6d/board.c new file mode 100644 index 00000000000..a3a9eec0471 --- /dev/null +++ b/ports/espressif/boards/unexpectedmaker_tinyc6d/board.c @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/unexpectedmaker_tinyc6d/mpconfigboard.h b/ports/espressif/boards/unexpectedmaker_tinyc6d/mpconfigboard.h new file mode 100644 index 00000000000..57001db2aa2 --- /dev/null +++ b/ports/espressif/boards/unexpectedmaker_tinyc6d/mpconfigboard.h @@ -0,0 +1,28 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Micropython setup + +#define MICROPY_HW_BOARD_NAME "TinyC6[D]" +#define MICROPY_HW_MCU_NAME "ESP32C6" + +#define MICROPY_HW_NEOPIXEL (&pin_GPIO23) +#define CIRCUITPY_STATUS_LED_POWER (&pin_GPIO22) + +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO7) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO6) + +#define DEFAULT_SPI_BUS_SCK (&pin_GPIO19) +#define DEFAULT_SPI_BUS_MOSI (&pin_GPIO21) +#define DEFAULT_SPI_BUS_MISO (&pin_GPIO20) + +#define DEFAULT_UART_BUS_RX (&pin_GPIO17) +#define DEFAULT_UART_BUS_TX (&pin_GPIO16) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/unexpectedmaker_tinyc6d/mpconfigboard.mk b/ports/espressif/boards/unexpectedmaker_tinyc6d/mpconfigboard.mk new file mode 100644 index 00000000000..eecc1dd19fa --- /dev/null +++ b/ports/espressif/boards/unexpectedmaker_tinyc6d/mpconfigboard.mk @@ -0,0 +1,11 @@ +CIRCUITPY_CREATOR_ID = 0xB0B00000 +CIRCUITPY_CREATION_ID = 0x00C60002 + +IDF_TARGET = esp32c6 + +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m +CIRCUITPY_ESP_FLASH_SIZE = 8MB + +# Include these Python libraries in firmware. +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel diff --git a/ports/espressif/boards/unexpectedmaker_tinyc6d/pins.c b/ports/espressif/boards/unexpectedmaker_tinyc6d/pins.c new file mode 100644 index 00000000000..8f9bd1316de --- /dev/null +++ b/ports/espressif/boards/unexpectedmaker_tinyc6d/pins.c @@ -0,0 +1,93 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { MP_ROM_QSTR(MP_QSTR_IO0), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_GPIO0) }, + + { MP_ROM_QSTR(MP_QSTR_IO1), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO1) }, + + { MP_ROM_QSTR(MP_QSTR_IO2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_GPIO2) }, + + { MP_ROM_QSTR(MP_QSTR_IO3), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_GPIO3) }, + + { MP_ROM_QSTR(MP_QSTR_IO6), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_A6), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO6) }, + + { MP_ROM_QSTR(MP_QSTR_IO7), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_D7), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO7) }, + + { MP_ROM_QSTR(MP_QSTR_IO8), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_GPIO8) }, + + { MP_ROM_QSTR(MP_QSTR_IO9), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_GPIO9) }, + + { MP_ROM_QSTR(MP_QSTR_IO10), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_GPIO10) }, + + { MP_ROM_QSTR(MP_QSTR_IO11), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_GPIO11) }, + + { MP_ROM_QSTR(MP_QSTR_IO15), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_GPIO15) }, + + { MP_ROM_QSTR(MP_QSTR_IO16), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_D16), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO16) }, + + { MP_ROM_QSTR(MP_QSTR_IO17), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_D17), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO17) }, + + { MP_ROM_QSTR(MP_QSTR_IO18), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_D18), MP_ROM_PTR(&pin_GPIO18) }, + + { MP_ROM_QSTR(MP_QSTR_IO19), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_D19), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_GPIO19) }, + + { MP_ROM_QSTR(MP_QSTR_IO20), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_D20), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_MI), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_SDI), MP_ROM_PTR(&pin_GPIO20) }, + + { MP_ROM_QSTR(MP_QSTR_IO21), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_D21), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_MO), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_SDO), MP_ROM_PTR(&pin_GPIO21) }, + + // MAX17048 fuel gauge interrupt + { MP_ROM_QSTR(MP_QSTR_FG_INT), MP_ROM_PTR(&pin_GPIO4) }, + + // 5V present sense pin + { MP_ROM_QSTR(MP_QSTR_VBUS), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_VBUS_SENSE), MP_ROM_PTR(&pin_GPIO5) }, + + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL_POWER), MP_ROM_PTR(&pin_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), 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_module_globals_table); diff --git a/ports/espressif/boards/unexpectedmaker_tinyc6d/sdkconfig b/ports/espressif/boards/unexpectedmaker_tinyc6d/sdkconfig new file mode 100644 index 00000000000..e9628662160 --- /dev/null +++ b/ports/espressif/boards/unexpectedmaker_tinyc6d/sdkconfig @@ -0,0 +1,14 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Component config +# +# +# LWIP +# +# end of LWIP + +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/boards/unexpectedmaker_tinypico/mpconfigboard.h b/ports/espressif/boards/unexpectedmaker_tinypico/mpconfigboard.h index c03aa8d7fbc..6300506e9e1 100644 --- a/ports/espressif/boards/unexpectedmaker_tinypico/mpconfigboard.h +++ b/ports/espressif/boards/unexpectedmaker_tinypico/mpconfigboard.h @@ -18,3 +18,6 @@ // UART pins attached to the USB-serial converter chip #define CIRCUITPY_CONSOLE_UART_TX (&pin_GPIO1) #define CIRCUITPY_CONSOLE_UART_RX (&pin_GPIO3) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/unexpectedmaker_tinypico/mpconfigboard.mk b/ports/espressif/boards/unexpectedmaker_tinypico/mpconfigboard.mk index 4086abba11e..80acff0ca49 100644 --- a/ports/espressif/boards/unexpectedmaker_tinypico/mpconfigboard.mk +++ b/ports/espressif/boards/unexpectedmaker_tinypico/mpconfigboard.mk @@ -10,5 +10,3 @@ CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_PSRAM_SIZE = 8MB CIRCUITPY_ESP_PSRAM_MODE = qio CIRCUITPY_ESP_PSRAM_FREQ = 80m - -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 diff --git a/ports/espressif/boards/unexpectedmaker_tinypico_nano/mpconfigboard.h b/ports/espressif/boards/unexpectedmaker_tinypico_nano/mpconfigboard.h index 2ab781f1a2e..6b01e2c2e13 100644 --- a/ports/espressif/boards/unexpectedmaker_tinypico_nano/mpconfigboard.h +++ b/ports/espressif/boards/unexpectedmaker_tinypico_nano/mpconfigboard.h @@ -18,3 +18,6 @@ // UART pins attached to the USB-serial converter chip #define CIRCUITPY_CONSOLE_UART_TX (&pin_GPIO1) #define CIRCUITPY_CONSOLE_UART_RX (&pin_GPIO3) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/unexpectedmaker_tinypico_nano/mpconfigboard.mk b/ports/espressif/boards/unexpectedmaker_tinypico_nano/mpconfigboard.mk index 550e0d4a76c..c919aff8aef 100644 --- a/ports/espressif/boards/unexpectedmaker_tinypico_nano/mpconfigboard.mk +++ b/ports/espressif/boards/unexpectedmaker_tinypico_nano/mpconfigboard.mk @@ -10,5 +10,3 @@ CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_PSRAM_SIZE = 8MB CIRCUITPY_ESP_PSRAM_MODE = qio CIRCUITPY_ESP_PSRAM_FREQ = 80m - -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 diff --git a/ports/espressif/boards/unexpectedmaker_tinypicod/board.c b/ports/espressif/boards/unexpectedmaker_tinypicod/board.c new file mode 100644 index 00000000000..5cc6974759b --- /dev/null +++ b/ports/espressif/boards/unexpectedmaker_tinypicod/board.c @@ -0,0 +1,31 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" +#include "mpconfigboard.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "driver/gpio.h" +#include "common-hal/microcontroller/Pin.h" + +void board_init(void) { + reset_board(); +} + +bool board_requests_safe_mode(void) { + return false; +} + +void reset_board(void) { + // Turn on APA102 power by default + gpio_set_direction(13, GPIO_MODE_DEF_OUTPUT); + gpio_set_level(13, true); +} + +void board_deinit(void) { + // Turn off APA102 power + gpio_set_direction(13, GPIO_MODE_DEF_OUTPUT); + gpio_set_level(13, false); +} diff --git a/ports/espressif/boards/unexpectedmaker_tinypicod/mpconfigboard.h b/ports/espressif/boards/unexpectedmaker_tinypicod/mpconfigboard.h new file mode 100644 index 00000000000..89d3ac7f0c2 --- /dev/null +++ b/ports/espressif/boards/unexpectedmaker_tinypicod/mpconfigboard.h @@ -0,0 +1,26 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2022 Dan Halbert for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#define MICROPY_HW_BOARD_NAME "TinyPICO[D]" +#define MICROPY_HW_MCU_NAME "ESP32-PICO-D4" + +#define MICROPY_HW_NEOPIXEL (&pin_GPIO2) +#define CIRCUITPY_STATUS_LED_POWER (&pin_GPIO13) + +#define CIRCUITPY_BOARD_I2C (1) +#define CIRCUITPY_BOARD_I2C_PIN {{.scl = &pin_GPIO22, .sda = &pin_GPIO21}} + +#define CIRCUITPY_BOARD_SPI (1) +#define CIRCUITPY_BOARD_SPI_PIN {{.clock = &pin_GPIO18, .mosi = &pin_GPIO23, .miso = &pin_GPIO19}} + +// UART pins attached to the USB-serial converter chip +#define CIRCUITPY_CONSOLE_UART_TX (&pin_GPIO1) +#define CIRCUITPY_CONSOLE_UART_RX (&pin_GPIO3) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/unexpectedmaker_tinypicod/mpconfigboard.mk b/ports/espressif/boards/unexpectedmaker_tinypicod/mpconfigboard.mk new file mode 100644 index 00000000000..c75c2c02e1c --- /dev/null +++ b/ports/espressif/boards/unexpectedmaker_tinypicod/mpconfigboard.mk @@ -0,0 +1,15 @@ +CIRCUITPY_CREATOR_ID = 0xB0B00000 +CIRCUITPY_CREATION_ID = 0x00000003 + +IDF_TARGET = esp32 + +CIRCUITPY_ESP_FLASH_SIZE = 4MB +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m + +CIRCUITPY_ESP_PSRAM_SIZE = 8MB +CIRCUITPY_ESP_PSRAM_MODE = qio +CIRCUITPY_ESP_PSRAM_FREQ = 80m + +# Include these Python libraries in firmware. +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel diff --git a/ports/espressif/boards/unexpectedmaker_tinypicod/pins.c b/ports/espressif/boards/unexpectedmaker_tinypicod/pins.c new file mode 100644 index 00000000000..59b7df15194 --- /dev/null +++ b/ports/espressif/boards/unexpectedmaker_tinypicod/pins.c @@ -0,0 +1,89 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { MP_ROM_QSTR(MP_QSTR_IO4), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_GPIO4) }, + + { MP_ROM_QSTR(MP_QSTR_IO14), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_D14), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_A14), MP_ROM_PTR(&pin_GPIO14) }, + + { MP_ROM_QSTR(MP_QSTR_IO15), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_A15), MP_ROM_PTR(&pin_GPIO15) }, + + { MP_ROM_QSTR(MP_QSTR_IO27), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_D27), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_A27), MP_ROM_PTR(&pin_GPIO27) }, + + { MP_ROM_QSTR(MP_QSTR_IO26), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_D26), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_A26), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_DAC2), MP_ROM_PTR(&pin_GPIO26) }, + + { MP_ROM_QSTR(MP_QSTR_IO25), MP_ROM_PTR(&pin_GPIO25) }, + { MP_ROM_QSTR(MP_QSTR_D25), MP_ROM_PTR(&pin_GPIO25) }, + { MP_ROM_QSTR(MP_QSTR_A25), MP_ROM_PTR(&pin_GPIO25) }, + { MP_ROM_QSTR(MP_QSTR_DAC1), MP_ROM_PTR(&pin_GPIO25) }, + + { MP_ROM_QSTR(MP_QSTR_IO23), MP_ROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_SDO), MP_ROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_D23), MP_ROM_PTR(&pin_GPIO23) }, + + { MP_ROM_QSTR(MP_QSTR_IO19), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_SDI), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_D19), MP_ROM_PTR(&pin_GPIO19) }, + + { MP_ROM_QSTR(MP_QSTR_IO18), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_D18), MP_ROM_PTR(&pin_GPIO18) }, + + { MP_ROM_QSTR(MP_QSTR_IO5), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_GPIO5) }, + + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_IO22), MP_ROM_PTR(&pin_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_D22), MP_ROM_PTR(&pin_GPIO22) }, + + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_IO21), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_D21), MP_ROM_PTR(&pin_GPIO21) }, + + { MP_ROM_QSTR(MP_QSTR_IO32), MP_ROM_PTR(&pin_GPIO32) }, + { MP_ROM_QSTR(MP_QSTR_D32), MP_ROM_PTR(&pin_GPIO32) }, + { MP_ROM_QSTR(MP_QSTR_A32), MP_ROM_PTR(&pin_GPIO32) }, + + { MP_ROM_QSTR(MP_QSTR_IO33), MP_ROM_PTR(&pin_GPIO33) }, + { MP_ROM_QSTR(MP_QSTR_D33), MP_ROM_PTR(&pin_GPIO33) }, + { MP_ROM_QSTR(MP_QSTR_A33), MP_ROM_PTR(&pin_GPIO33) }, + + // MAX17048 fuel gauge interrupt + { MP_ROM_QSTR(MP_QSTR_FG_INT), MP_ROM_PTR(&pin_GPIO35) }, + + // 5V present sense pin + { MP_ROM_QSTR(MP_QSTR_VBUS), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_VBUS_SENSE), MP_ROM_PTR(&pin_GPIO9) }, + + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL_POWER), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO2) }, + + // RF antenna switch + { MP_ROM_QSTR(MP_QSTR_ANT_SWITCH), MP_ROM_PTR(&pin_GPIO12) }, + + { 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_module_globals_table); diff --git a/tests/feature_check/coverage.py.exp b/ports/espressif/boards/unexpectedmaker_tinypicod/sdkconfig similarity index 100% rename from tests/feature_check/coverage.py.exp rename to ports/espressif/boards/unexpectedmaker_tinypicod/sdkconfig diff --git a/ports/espressif/boards/unexpectedmaker_tinys2/mpconfigboard.h b/ports/espressif/boards/unexpectedmaker_tinys2/mpconfigboard.h index d7c87bfdba2..07c453cb7bc 100644 --- a/ports/espressif/boards/unexpectedmaker_tinys2/mpconfigboard.h +++ b/ports/espressif/boards/unexpectedmaker_tinys2/mpconfigboard.h @@ -23,3 +23,6 @@ #define DEFAULT_UART_BUS_RX (&pin_GPIO44) #define DEFAULT_UART_BUS_TX (&pin_GPIO43) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/unexpectedmaker_tinys3/mpconfigboard.h b/ports/espressif/boards/unexpectedmaker_tinys3/mpconfigboard.h index 2556e714d67..066dd00386c 100644 --- a/ports/espressif/boards/unexpectedmaker_tinys3/mpconfigboard.h +++ b/ports/espressif/boards/unexpectedmaker_tinys3/mpconfigboard.h @@ -25,3 +25,6 @@ #define DEFAULT_UART_BUS_TX (&pin_GPIO43) #define DOUBLE_TAP_PIN (&pin_GPIO47) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/unexpectedmaker_tinys3d/board.c b/ports/espressif/boards/unexpectedmaker_tinys3d/board.c new file mode 100644 index 00000000000..a3a9eec0471 --- /dev/null +++ b/ports/espressif/boards/unexpectedmaker_tinys3d/board.c @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/unexpectedmaker_tinys3d/mpconfigboard.h b/ports/espressif/boards/unexpectedmaker_tinys3d/mpconfigboard.h new file mode 100644 index 00000000000..825daeb4195 --- /dev/null +++ b/ports/espressif/boards/unexpectedmaker_tinys3d/mpconfigboard.h @@ -0,0 +1,30 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Micropython setup + +#define MICROPY_HW_BOARD_NAME "TinyS3[D]" +#define MICROPY_HW_MCU_NAME "ESP32S3" + +#define MICROPY_HW_NEOPIXEL (&pin_GPIO18) +#define CIRCUITPY_STATUS_LED_POWER (&pin_GPIO17) + +#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 DOUBLE_TAP_PIN (&pin_GPIO47) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/unexpectedmaker_tinys3d/mpconfigboard.mk b/ports/espressif/boards/unexpectedmaker_tinys3d/mpconfigboard.mk new file mode 100644 index 00000000000..3643ac512e4 --- /dev/null +++ b/ports/espressif/boards/unexpectedmaker_tinys3d/mpconfigboard.mk @@ -0,0 +1,21 @@ +USB_VID = 0x303A +USB_PID = 0x80D1 +USB_PRODUCT = "TinyS3[D]" +USB_MANUFACTURER = "UnexpectedMaker" + +IDF_TARGET = esp32s3 + +CIRCUITPY_ESP_FLASH_SIZE = 8MB +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m + +CIRCUITPY_ESP_PSRAM_SIZE = 8MB +CIRCUITPY_ESP_PSRAM_MODE = qio +CIRCUITPY_ESP_PSRAM_FREQ = 80m + +# CIRCUITPY_BITBANG_NEOPIXEL = 1 + +CIRCUITPY_STAGE = 1 + +# Include these Python libraries in firmware. +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel diff --git a/ports/espressif/boards/unexpectedmaker_tinys3d/pins.c b/ports/espressif/boards/unexpectedmaker_tinys3d/pins.c new file mode 100644 index 00000000000..3b325a2898e --- /dev/null +++ b/ports/espressif/boards/unexpectedmaker_tinys3d/pins.c @@ -0,0 +1,100 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { MP_ROM_QSTR(MP_QSTR_IO0), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_GPIO0) }, + + { MP_ROM_QSTR(MP_QSTR_IO1), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO1) }, + + { MP_ROM_QSTR(MP_QSTR_IO2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_GPIO2) }, + + { MP_ROM_QSTR(MP_QSTR_IO3), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_GPIO3) }, + + { MP_ROM_QSTR(MP_QSTR_IO4), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_GPIO4) }, + + { MP_ROM_QSTR(MP_QSTR_IO5), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_GPIO5) }, + + { MP_ROM_QSTR(MP_QSTR_IO6), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_GPIO6) }, + + { MP_ROM_QSTR(MP_QSTR_IO7), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_A6), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_D7), MP_ROM_PTR(&pin_GPIO7) }, + + { 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_A7), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_D8), 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_A8), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_GPIO9) }, + + { MP_ROM_QSTR(MP_QSTR_IO21), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_D21), MP_ROM_PTR(&pin_GPIO21) }, + + { MP_ROM_QSTR(MP_QSTR_IO34), MP_ROM_PTR(&pin_GPIO34) }, + { MP_ROM_QSTR(MP_QSTR_D34), MP_ROM_PTR(&pin_GPIO34) }, + + { 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_MO), MP_ROM_PTR(&pin_GPIO35) }, + { MP_ROM_QSTR(MP_QSTR_SDO), MP_ROM_PTR(&pin_GPIO35) }, + { MP_ROM_QSTR(MP_QSTR_D35), MP_ROM_PTR(&pin_GPIO35) }, + + { MP_ROM_QSTR(MP_QSTR_IO37), MP_ROM_PTR(&pin_GPIO37) }, + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO37) }, + { MP_ROM_QSTR(MP_QSTR_MI), MP_ROM_PTR(&pin_GPIO37) }, + { MP_ROM_QSTR(MP_QSTR_SDI), MP_ROM_PTR(&pin_GPIO37) }, + { MP_ROM_QSTR(MP_QSTR_D37), MP_ROM_PTR(&pin_GPIO37) }, + + { MP_ROM_QSTR(MP_QSTR_IO36), MP_ROM_PTR(&pin_GPIO36) }, + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_GPIO36) }, + { MP_ROM_QSTR(MP_QSTR_D36), MP_ROM_PTR(&pin_GPIO36) }, + + { MP_ROM_QSTR(MP_QSTR_IO43), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_D43), 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_D44), MP_ROM_PTR(&pin_GPIO44) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO44) }, + + // MAX17048 fuel gauge interrupt + { MP_ROM_QSTR(MP_QSTR_FG_INT), MP_ROM_PTR(&pin_GPIO10) }, + + // RF antenna switch + { MP_ROM_QSTR(MP_QSTR_ANT_SWITCH), MP_ROM_PTR(&pin_GPIO38) }, + + // 5V present sense pin + { MP_ROM_QSTR(MP_QSTR_VBUS), MP_ROM_PTR(&pin_GPIO33) }, + { MP_ROM_QSTR(MP_QSTR_VBUS_SENSE), MP_ROM_PTR(&pin_GPIO33) }, + + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL_POWER), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO18) }, + + { 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_module_globals_table); diff --git a/ports/espressif/boards/unexpectedmaker_tinys3d/sdkconfig b/ports/espressif/boards/unexpectedmaker_tinys3d/sdkconfig new file mode 100644 index 00000000000..e9628662160 --- /dev/null +++ b/ports/espressif/boards/unexpectedmaker_tinys3d/sdkconfig @@ -0,0 +1,14 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Component config +# +# +# LWIP +# +# end of LWIP + +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/boards/unexpectedmaker_tinywatch_s3/board.c b/ports/espressif/boards/unexpectedmaker_tinywatch_s3/board.c index f4edc3e227e..2c9265348e6 100644 --- a/ports/espressif/boards/unexpectedmaker_tinywatch_s3/board.c +++ b/ports/espressif/boards/unexpectedmaker_tinywatch_s3/board.c @@ -24,4 +24,10 @@ bool espressif_board_reset_pin_number(gpio_num_t pin_number) { return false; } +void board_init(void) { + // GPIO21 (USER_PWR_SHUTDOWN) cuts power when high. Default to pulled down + // (power stays on). + espressif_board_reset_pin_number(21); +} + // Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/unexpectedmaker_tinywatch_s3/mpconfigboard.h b/ports/espressif/boards/unexpectedmaker_tinywatch_s3/mpconfigboard.h index 6f0181c4acb..309c2e2e702 100644 --- a/ports/espressif/boards/unexpectedmaker_tinywatch_s3/mpconfigboard.h +++ b/ports/espressif/boards/unexpectedmaker_tinywatch_s3/mpconfigboard.h @@ -21,3 +21,6 @@ #define DEFAULT_UART_BUS_RX (&pin_GPIO44) #define DEFAULT_UART_BUS_TX (&pin_GPIO43) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/vidi_x/board.c b/ports/espressif/boards/vidi_x/board.c index e53dfd82ad9..a57ebc9e3b4 100644 --- a/ports/espressif/boards/vidi_x/board.c +++ b/ports/espressif/boards/vidi_x/board.c @@ -6,6 +6,7 @@ #include "supervisor/board.h" #include "mpconfigboard.h" +#include "driver/gpio.h" #include "shared-bindings/busio/SPI.h" #include "shared-bindings/fourwire/FourWire.h" #include "shared-module/displayio/__init__.h" @@ -43,17 +44,19 @@ uint8_t display_init_sequence[] = { }; void board_init(void) { + // GPIO2 (STATUS) drives an LED. Default to pulled down (off). + espressif_board_reset_pin_number(2); + fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_GPIO18, &pin_GPIO23, NULL, false); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_GPIO21, // TFT_DC Command or data - &pin_GPIO5, // TFT_CS Chip select - NULL, // TFT_RST Reset + MP_OBJ_FROM_PTR(&pin_GPIO21), // TFT_DC Command or data + MP_OBJ_FROM_PTR(&pin_GPIO5), // TFT_CS Chip select + mp_const_none, // TFT_RST Reset 40000000, // Baudrate 0, // Polarity 0); // Phase diff --git a/ports/espressif/boards/waveshare_esp32_c5_lcd_1_47/board.c b/ports/espressif/boards/waveshare_esp32_c5_lcd_1_47/board.c new file mode 100644 index 00000000000..0a3f930efbe --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_c5_lcd_1_47/board.c @@ -0,0 +1,100 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Benjamin Shockley +// SPDX-FileCopyrightText: Copyright (c) 2026 David Glaude +// +// SPDX-License-Identifier: MIT +// +// Modified from waveshare_esp32_c6_lcd_1_47 to support waveshare_esp32_c5_lcd_1_47 + +#include "supervisor/board.h" +#include "mpconfigboard.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/busio/SPI.h" +#include "shared-bindings/fourwire/FourWire.h" +#include "shared-bindings/busdisplay/BusDisplay.h" +#include "shared-module/displayio/__init__.h" +#include "shared-module/displayio/mipi_constants.h" +#include "shared-bindings/board/__init__.h" + +#define DELAY 0x80 + +// Driver: ST7789V3, Panel: LBS147TC-IF15 (172x320 RGB) +uint8_t display_init_sequence[] = { + 0x01, 0 | DELAY, 120, + 0x11, 0 | DELAY, 120, + 0x13, 0, + 0x36, 1, 0x00, + 0x3A, 1 | DELAY, 0x05, 10, + 0xB2, 5, 0x0C, 0x0C, 0x00, 0x33, 0x33, + 0xB7, 1, 0x35, + 0xBB, 1, 0x20, + 0xC0, 1, 0x2C, + 0xC2, 2, 0x01, 0xFF, + 0xC3, 1, 0x13, + 0xC4, 1, 0x20, + 0xC6, 1, 0x0F, + 0xD0, 2, 0xA4, 0xA1, + 0xE0, 14, 0xF0, 0x00, 0x04, 0x04, 0x04, 0x05, 0x29, 0x33, 0x3E, 0x38, 0x12, 0x12, 0x28, 0x30, + 0xE1, 14, 0xF0, 0x07, 0x0A, 0x0D, 0x0B, 0x07, 0x28, 0x33, 0x3E, 0x36, 0x14, 0x14, 0x29, 0x32, + 0x21, 0, + 0x29, 0 | DELAY, 255, +}; + +static void display_init(void) { + busio_spi_obj_t *spi = common_hal_board_create_spi(0); + fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; + bus->base.type = &fourwire_fourwire_type; + + common_hal_fourwire_fourwire_construct( + bus, + spi, + MP_OBJ_FROM_PTR(&pin_GPIO24), // LCD_DC + MP_OBJ_FROM_PTR(&pin_GPIO23), // LCD_CS + MP_OBJ_FROM_PTR(&pin_GPIO26), // LCD_RST + 40000000, // Baudrate (40 MHz) + 0, // Polarity + 0 // Phase + ); + + busdisplay_busdisplay_obj_t *display = &allocate_display()->display; + display->base.type = &busdisplay_busdisplay_type; + + common_hal_busdisplay_busdisplay_construct( + display, + bus, + 172, // Native width + 320, // Native height + 34, // Column start offset + 0, // Row start offset + 0, // Native rotation: 0 (portrait) + 16, // Color depth + false, // Grayscale + false, // Pixels in byte share row + 1, // Bytes per cell + false, // Reverse pixels in byte + true, // Reverse pixels in word + MIPI_COMMAND_SET_COLUMN_ADDRESS, + MIPI_COMMAND_SET_PAGE_ADDRESS, + MIPI_COMMAND_WRITE_MEMORY_START, + display_init_sequence, + sizeof(display_init_sequence), + &pin_GPIO10, // Backlight pin (LCD_BL) + NO_BRIGHTNESS_COMMAND, + 1.0f, // Brightness + false, // Single byte bounds + false, // Data as commands + true, // Auto refresh + 60, // Native FPS + true, // Backlight active high + false, // SH1107 addressing + 50000 // Backlight PWM frequency + ); + + // Switch to landscape: swaps width/height to 320x172 and recalculates RAM offsets + common_hal_busdisplay_busdisplay_set_rotation(display, 270); +} + +void board_init(void) { + display_init(); +} diff --git a/ports/espressif/boards/waveshare_esp32_c5_lcd_1_47/mpconfigboard.h b/ports/espressif/boards/waveshare_esp32_c5_lcd_1_47/mpconfigboard.h new file mode 100644 index 00000000000..11fba7dbe78 --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_c5_lcd_1_47/mpconfigboard.h @@ -0,0 +1,34 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Benjamin Shockley +// SPDX-FileCopyrightText: Copyright (c) 2026 David Glaude +// +// SPDX-License-Identifier: MIT +// +// Modified from waveshare_esp32_c6_lcd_1_47 to support waveshare_esp32_c5_lcd_1_47 + +#pragma once + +// Micropython setup + +#define MICROPY_HW_BOARD_NAME "Waveshare ESP32-C5 LCD 1.47" +#define MICROPY_HW_MCU_NAME "ESP32-C5" + +// For entering safe mode, use BOOT button +#define CIRCUITPY_BOOT_BUTTON (&pin_GPIO28) + +// Waveshare onboard NeoPixel on GPIO8 +#define CIRCUITPY_STATUS_LED_POWER (&pin_GPIO8) +#define MICROPY_HW_NEOPIXEL (&pin_GPIO8) +#define MICROPY_HW_NEOPIXEL_COUNT (1) + +// Default SPI bus definitions (shared between LCD and TF card) +#define DEFAULT_SPI_BUS_SCK (&pin_GPIO7) +#define DEFAULT_SPI_BUS_MOSI (&pin_GPIO6) +#define DEFAULT_SPI_BUS_MISO (&pin_GPIO5) + +// Explanation of how a user got into safe mode +#define BOARD_USER_SAFE_MODE_ACTION MP_ERROR_TEXT("You pressed the BOOT button at start up.") + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/waveshare_esp32_c5_lcd_1_47/mpconfigboard.mk b/ports/espressif/boards/waveshare_esp32_c5_lcd_1_47/mpconfigboard.mk new file mode 100644 index 00000000000..5a7b1521245 --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_c5_lcd_1_47/mpconfigboard.mk @@ -0,0 +1,16 @@ +USB_PRODUCT = "Waveshare ESP32-C5 LCD 1.47" +USB_MANUFACTURER = "Waveshare" + +CIRCUITPY_CREATOR_ID = 0x000C303A +CIRCUITPY_CREATION_ID = 0x00C50002 + +IDF_TARGET = esp32c5 + +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m +CIRCUITPY_ESP_FLASH_SIZE = 4MB + +CIRCUITPY_NEOPIXEL_WRITE = 1 +CIRCUITPY_BUSDISPLAY = 1 +CIRCUITPY_FOURWIRE = 1 +CIRCUITPY_4MB_FLASH_LARGE_USER_FS_LAYOUT = 1 diff --git a/ports/espressif/boards/waveshare_esp32_c5_lcd_1_47/pins.c b/ports/espressif/boards/waveshare_esp32_c5_lcd_1_47/pins.c new file mode 100644 index 00000000000..15f67bca223 --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_c5_lcd_1_47/pins.c @@ -0,0 +1,62 @@ +#include "shared-bindings/board/__init__.h" +#include "shared-module/displayio/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + // Boot / User button + { MP_ROM_QSTR(MP_QSTR_BUTTON), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_BOOT0), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_IO28), MP_ROM_PTR(&pin_GPIO28) }, + + // General purpose exposed GPIOs + { MP_ROM_QSTR(MP_QSTR_IO0), MP_ROM_PTR(&pin_GPIO0) }, + + // Status RGB LED + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_IO8), MP_ROM_PTR(&pin_GPIO8) }, + + // Primary SPI bus lines + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO5) }, + + // LCD Dedicated Aliases + { MP_ROM_QSTR(MP_QSTR_LCD_CLK), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_LCD_DIN), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_LCD_MOSI), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_LCD_CS), MP_ROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_LCD_DC), MP_ROM_PTR(&pin_GPIO24) }, + { MP_ROM_QSTR(MP_QSTR_LCD_RST), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_LCD_BL), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_BACKLIGHT), MP_ROM_PTR(&pin_GPIO10) }, + + // MicroSD (TF Card) Dedicated Aliases + { MP_ROM_QSTR(MP_QSTR_SD_CS), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_SD_CLK), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_SD_MOSI), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_SD_MISO), MP_ROM_PTR(&pin_GPIO5) }, + + // General purpose exposed GPIOs + { 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_IO9), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_IO10), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_IO23), MP_ROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_IO24), MP_ROM_PTR(&pin_GPIO24) }, + { MP_ROM_QSTR(MP_QSTR_IO25), MP_ROM_PTR(&pin_GPIO25) }, + { MP_ROM_QSTR(MP_QSTR_IO26), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_IO27), MP_ROM_PTR(&pin_GPIO27) }, + + // Shared SPI bus singleton + { MP_ROM_QSTR(MP_QSTR_SPI), MP_ROM_PTR(&board_spi_obj) }, + + // Built-in Display + { MP_ROM_QSTR(MP_QSTR_DISPLAY), MP_ROM_PTR(&displays[0].display) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/espressif/boards/waveshare_esp32_c5_lcd_1_47/sdkconfig b/ports/espressif/boards/waveshare_esp32_c5_lcd_1_47/sdkconfig new file mode 100644 index 00000000000..b8cf0e97b5a --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_c5_lcd_1_47/sdkconfig @@ -0,0 +1 @@ +# Everything is default or implied by mpconfigboard.mk diff --git a/ports/espressif/boards/waveshare_esp32_c6_lcd_1_47/board.c b/ports/espressif/boards/waveshare_esp32_c6_lcd_1_47/board.c index 7dd0e0c0fa2..e56c096e403 100644 --- a/ports/espressif/boards/waveshare_esp32_c6_lcd_1_47/board.c +++ b/ports/espressif/boards/waveshare_esp32_c6_lcd_1_47/board.c @@ -48,9 +48,9 @@ static void display_init(void) { common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO15, // DC - &pin_GPIO14, // CS - &pin_GPIO21, // RST + MP_OBJ_FROM_PTR(&pin_GPIO15), // DC + MP_OBJ_FROM_PTR(&pin_GPIO14), // CS + MP_OBJ_FROM_PTR(&pin_GPIO21), // RST 80000000, // baudrate 0, // polarity 0 // phase diff --git a/ports/espressif/boards/waveshare_esp32_c6_lcd_1_47/mpconfigboard.h b/ports/espressif/boards/waveshare_esp32_c6_lcd_1_47/mpconfigboard.h index 78a0d9b5221..5f80b124e9b 100644 --- a/ports/espressif/boards/waveshare_esp32_c6_lcd_1_47/mpconfigboard.h +++ b/ports/espressif/boards/waveshare_esp32_c6_lcd_1_47/mpconfigboard.h @@ -12,6 +12,7 @@ #define MICROPY_HW_MCU_NAME "ESP32-C6FH4" #define MICROPY_HW_NEOPIXEL (&pin_GPIO8) +#define MICROPY_HW_NEOPIXEL_ORDER (STATUS_NEOPIXEL_ORDER_RGB) // I2C #define CIRCUITPY_BOARD_I2C (1) @@ -30,3 +31,6 @@ // Explanation of how a user got into safe mode #define BOARD_USER_SAFE_MODE_ACTION MP_ERROR_TEXT("You pressed the BOOT button at start up.") + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/waveshare_esp32_c6_lcd_1_47/mpconfigboard.mk b/ports/espressif/boards/waveshare_esp32_c6_lcd_1_47/mpconfigboard.mk index 0d0930984eb..e838f8ad2e5 100644 --- a/ports/espressif/boards/waveshare_esp32_c6_lcd_1_47/mpconfigboard.mk +++ b/ports/espressif/boards/waveshare_esp32_c6_lcd_1_47/mpconfigboard.mk @@ -6,3 +6,6 @@ IDF_TARGET = esp32c6 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB + +# Board was originally defined with a 2MB firmware, almost 2MB user filesystem. Leave it that way. +CIRCUITPY_4MB_FLASH_LARGE_USER_FS_LAYOUT = 1 diff --git a/ports/espressif/boards/waveshare_esp32_s2_pico_lcd/board.c b/ports/espressif/boards/waveshare_esp32_s2_pico_lcd/board.c index cb6fb310338..88b2be56395 100644 --- a/ports/espressif/boards/waveshare_esp32_s2_pico_lcd/board.c +++ b/ports/espressif/boards/waveshare_esp32_s2_pico_lcd/board.c @@ -54,16 +54,14 @@ static void display_init(void) { NULL, // MISO not connected false); // Not half-duplex - common_hal_busio_spi_never_reset(spi); - bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO18, // DC - &pin_GPIO9, // CS - &pin_GPIO21, // RST + MP_OBJ_FROM_PTR(&pin_GPIO18), // DC + MP_OBJ_FROM_PTR(&pin_GPIO9), // CS + MP_OBJ_FROM_PTR(&pin_GPIO21), // RST 40000000, // baudrate 0, // polarity 0 // phase diff --git a/ports/espressif/boards/waveshare_esp32_s2_pico_lcd/mpconfigboard.h b/ports/espressif/boards/waveshare_esp32_s2_pico_lcd/mpconfigboard.h index c74499cf80a..638eb0390d8 100644 --- a/ports/espressif/boards/waveshare_esp32_s2_pico_lcd/mpconfigboard.h +++ b/ports/espressif/boards/waveshare_esp32_s2_pico_lcd/mpconfigboard.h @@ -20,3 +20,6 @@ #define DEFAULT_UART_BUS_RX (&pin_GPIO44) #define DEFAULT_UART_BUS_TX (&pin_GPIO43) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/waveshare_esp32_s3_amoled_175/board.c b/ports/espressif/boards/waveshare_esp32_s3_amoled_175/board.c new file mode 100644 index 00000000000..a5940ac41ac --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_amoled_175/board.c @@ -0,0 +1,79 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Hassan Naeem +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" +#include "mpconfigboard.h" +#include "shared-bindings/qspibus/QSPIBus.h" +#include "shared-bindings/busdisplay/BusDisplay.h" +#include "shared-module/displayio/__init__.h" +#include "shared-module/displayio/mipi_constants.h" + +// CO5300 start-up, as in Waveshare's ESP-IDF BSP for this board. +static uint8_t display_init_sequence[] = { + 0xFE, 0x01, 0x20, // Page 0x20 + 0x19, 0x01, 0x10, // Vendor command + 0x1C, 0x01, 0xA0, // Vendor command + 0xFE, 0x01, 0x00, // Back to the user command page + 0xC4, 0x01, 0x80, // QSPI interface + 0x3A, 0x01, 0x55, // COLMOD: 16-bit RGB565 + 0x35, 0x01, 0x00, // Tearing effect line on + 0x53, 0x01, 0x20, // Brightness control on + 0x51, 0x01, 0xFF, // Brightness + 0x63, 0x01, 0xFF, // High brightness mode level + 0x11, 0x80, 0xFF, // Sleep out + 500ms + 0x29, 0x80, 0x0A, // Display on + 10ms +}; + +void board_init(void) { + qspibus_qspibus_obj_t *bus = &allocate_display_bus_or_raise()->qspi_bus; + bus->base.type = &qspibus_qspibus_type; + + common_hal_qspibus_qspibus_construct(bus, + CIRCUITPY_LCD_CLK, + CIRCUITPY_LCD_D0, + CIRCUITPY_LCD_D1, + CIRCUITPY_LCD_D2, + CIRCUITPY_LCD_D3, + CIRCUITPY_LCD_CS, + NULL, // dcx: QSPI encodes commands + CIRCUITPY_LCD_RESET, + 40000000); + + // The 466x466 panel's first visible column is 6. + busdisplay_busdisplay_obj_t *display = &allocate_display_or_raise()->display; + display->base.type = &busdisplay_busdisplay_type; + + common_hal_busdisplay_busdisplay_construct(display, + bus, + 466, // width + 466, // height + 6, // colstart + 0, // rowstart + 0, // rotation + 16, // color_depth + false, // grayscale + false, // pixels_in_byte_share_row + 1, // bytes_per_cell + false, // reverse_pixels_in_byte + true, // reverse_bytes_in_word: the CO5300 takes RGB565 high byte first + MIPI_COMMAND_SET_COLUMN_ADDRESS, + MIPI_COMMAND_SET_PAGE_ADDRESS, + MIPI_COMMAND_WRITE_MEMORY_START, + display_init_sequence, + sizeof(display_init_sequence), + NULL, // no backlight pin on an AMOLED + 0x51, // brightness_command + 1.0f, // brightness + false, // single_byte_bounds + false, // data_as_commands + true, // auto_refresh + 60, // native_frames_per_second + true, // backlight_on_high + false, // SH1107_addressing + 50000); // backlight_pwm_frequency +} + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/waveshare_esp32_s3_amoled_175/mpconfigboard.h b/ports/espressif/boards/waveshare_esp32_s3_amoled_175/mpconfigboard.h new file mode 100644 index 00000000000..e308ed48608 --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_amoled_175/mpconfigboard.h @@ -0,0 +1,28 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Hassan Naeem +// +// SPDX-License-Identifier: MIT + +#pragma once + +#define MICROPY_HW_BOARD_NAME "Waveshare ESP32-S3-Touch-AMOLED-1.75" +#define MICROPY_HW_MCU_NAME "ESP32S3" + +// Touch (CST9217), PMU (AXP2101), codecs (ES8311, ES7210), IMU (QMI8658), RTC (PCF85063) +#define CIRCUITPY_BOARD_I2C (1) +#define CIRCUITPY_BOARD_I2C_PIN {{.scl = &pin_GPIO14, .sda = &pin_GPIO15}} + +#define CIRCUITPY_BOARD_DISPLAY (1) +#define CIRCUITPY_LCD_CS (&pin_GPIO12) +#define CIRCUITPY_LCD_CLK (&pin_GPIO38) +#define CIRCUITPY_LCD_D0 (&pin_GPIO4) +#define CIRCUITPY_LCD_D1 (&pin_GPIO5) +#define CIRCUITPY_LCD_D2 (&pin_GPIO6) +#define CIRCUITPY_LCD_D3 (&pin_GPIO7) +#define CIRCUITPY_LCD_RESET (&pin_GPIO39) + +#define CIRCUITPY_BOARD_SPI (0) + +#define DEFAULT_UART_BUS_RX (&pin_GPIO44) +#define DEFAULT_UART_BUS_TX (&pin_GPIO43) diff --git a/ports/espressif/boards/waveshare_esp32_s3_amoled_175/mpconfigboard.mk b/ports/espressif/boards/waveshare_esp32_s3_amoled_175/mpconfigboard.mk new file mode 100644 index 00000000000..aa63ea1003f --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_amoled_175/mpconfigboard.mk @@ -0,0 +1,36 @@ +# This file is part of the CircuitPython project: https://circuitpython.org +# SPDX-FileCopyrightText: Copyright (c) 2026 Hassan Naeem +# SPDX-License-Identifier: MIT + +USB_VID = 0x303A +USB_PID = 0x828E +USB_MANUFACTURER = "Waveshare" +USB_PRODUCT = "ESP32-S3-Touch-AMOLED-1.75" + +IDF_TARGET = esp32s3 + +# 16MB quad flash +CIRCUITPY_ESP_FLASH_SIZE = 16MB +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m + +# 8MB octal PSRAM +CIRCUITPY_ESP_PSRAM_SIZE = 8MB +CIRCUITPY_ESP_PSRAM_MODE = opi +CIRCUITPY_ESP_PSRAM_FREQ = 80m + +OPTIMIZATION_FLAGS = -Os + +# QSPI bus for the CO5300 AMOLED panel +CIRCUITPY_QSPIBUS = 1 +CIRCUITPY_PARALLELDISPLAYBUS = 0 + +CIRCUITPY_ESPCAMERA = 0 + +# Touch is the CST9217 on I2C, not the ESP32-S3's capacitive pins +CIRCUITPY_TOUCHIO = 0 + +# microSD slot, 1-bit SDMMC +CIRCUITPY_SDIOIO = 1 + +CIRCUITPY_DISPLAY_AREA_BUFFER_SIZE = 8192 diff --git a/ports/espressif/boards/waveshare_esp32_s3_amoled_175/pins.c b/ports/espressif/boards/waveshare_esp32_s3_amoled_175/pins.c new file mode 100644 index 00000000000..155ea38599b --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_amoled_175/pins.c @@ -0,0 +1,69 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Hassan Naeem +// +// SPDX-License-Identifier: MIT + +#include "py/obj.h" +#include "py/mphal.h" +#include "shared-bindings/board/__init__.h" +#include "shared-module/displayio/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + // BOOT button. PWR is read through the AXP2101 PMU. + { MP_ROM_QSTR(MP_QSTR_BOOT), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON), MP_ROM_PTR(&pin_GPIO0) }, + + // I2C: CST9217 touch (0x5A), AXP2101 PMU (0x34), ES8311 (0x18), + // ES7210 (0x40), QMI8658 IMU (0x6B), PCF85063 RTC (0x51) + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, + + // Touch + { MP_ROM_QSTR(MP_QSTR_TP_INT), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_TP_RESET), MP_ROM_PTR(&pin_GPIO40) }, + + // IMU + { MP_ROM_QSTR(MP_QSTR_IMU_INT2), MP_ROM_PTR(&pin_GPIO21) }, + + // Audio: I2S to the ES8311 (speaker) and from the ES7210 (microphones) + { MP_ROM_QSTR(MP_QSTR_I2S_MCLK), MP_ROM_PTR(&pin_GPIO42) }, + { MP_ROM_QSTR(MP_QSTR_I2S_BCLK), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_I2S_WS), MP_ROM_PTR(&pin_GPIO45) }, + { MP_ROM_QSTR(MP_QSTR_I2S_DOUT), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_I2S_DIN), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_PA_CTRL), MP_ROM_PTR(&pin_GPIO46) }, + + // QSPI display (CO5300) + { MP_ROM_QSTR(MP_QSTR_LCD_CS), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_LCD_CLK), MP_ROM_PTR(&pin_GPIO38) }, + { MP_ROM_QSTR(MP_QSTR_LCD_D0), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_LCD_D1), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_LCD_D2), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_LCD_D3), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_LCD_RESET), MP_ROM_PTR(&pin_GPIO39) }, + { MP_ROM_QSTR(MP_QSTR_LCD_TE), MP_ROM_PTR(&pin_GPIO13) }, + + // UART + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO44) }, + + // microSD: SDMMC (CLK, CMD, D0), or SPI with SD_CS + { MP_ROM_QSTR(MP_QSTR_SDIO_CLK), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_SDIO_CMD), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_SDIO_D0), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_SD_SCK), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_SD_MOSI), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_SD_MISO), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_SD_CS), MP_ROM_PTR(&pin_GPIO41) }, + + // Header pins, marked for an optional GPS module + { 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_DISPLAY), MP_ROM_PTR(&displays[0].display) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/espressif/boards/waveshare_esp32_s3_amoled_175/sdkconfig b/ports/espressif/boards/waveshare_esp32_s3_amoled_175/sdkconfig new file mode 100644 index 00000000000..f95cb2a8fd3 --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_amoled_175/sdkconfig @@ -0,0 +1,3 @@ +# +# Configuration file for the Waveshare ESP32-S3 Touch AMOLED 1.75 +# diff --git a/ports/espressif/boards/waveshare_esp32_s3_amoled_175c/board.c b/ports/espressif/boards/waveshare_esp32_s3_amoled_175c/board.c new file mode 100644 index 00000000000..a5940ac41ac --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_amoled_175c/board.c @@ -0,0 +1,79 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Hassan Naeem +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" +#include "mpconfigboard.h" +#include "shared-bindings/qspibus/QSPIBus.h" +#include "shared-bindings/busdisplay/BusDisplay.h" +#include "shared-module/displayio/__init__.h" +#include "shared-module/displayio/mipi_constants.h" + +// CO5300 start-up, as in Waveshare's ESP-IDF BSP for this board. +static uint8_t display_init_sequence[] = { + 0xFE, 0x01, 0x20, // Page 0x20 + 0x19, 0x01, 0x10, // Vendor command + 0x1C, 0x01, 0xA0, // Vendor command + 0xFE, 0x01, 0x00, // Back to the user command page + 0xC4, 0x01, 0x80, // QSPI interface + 0x3A, 0x01, 0x55, // COLMOD: 16-bit RGB565 + 0x35, 0x01, 0x00, // Tearing effect line on + 0x53, 0x01, 0x20, // Brightness control on + 0x51, 0x01, 0xFF, // Brightness + 0x63, 0x01, 0xFF, // High brightness mode level + 0x11, 0x80, 0xFF, // Sleep out + 500ms + 0x29, 0x80, 0x0A, // Display on + 10ms +}; + +void board_init(void) { + qspibus_qspibus_obj_t *bus = &allocate_display_bus_or_raise()->qspi_bus; + bus->base.type = &qspibus_qspibus_type; + + common_hal_qspibus_qspibus_construct(bus, + CIRCUITPY_LCD_CLK, + CIRCUITPY_LCD_D0, + CIRCUITPY_LCD_D1, + CIRCUITPY_LCD_D2, + CIRCUITPY_LCD_D3, + CIRCUITPY_LCD_CS, + NULL, // dcx: QSPI encodes commands + CIRCUITPY_LCD_RESET, + 40000000); + + // The 466x466 panel's first visible column is 6. + busdisplay_busdisplay_obj_t *display = &allocate_display_or_raise()->display; + display->base.type = &busdisplay_busdisplay_type; + + common_hal_busdisplay_busdisplay_construct(display, + bus, + 466, // width + 466, // height + 6, // colstart + 0, // rowstart + 0, // rotation + 16, // color_depth + false, // grayscale + false, // pixels_in_byte_share_row + 1, // bytes_per_cell + false, // reverse_pixels_in_byte + true, // reverse_bytes_in_word: the CO5300 takes RGB565 high byte first + MIPI_COMMAND_SET_COLUMN_ADDRESS, + MIPI_COMMAND_SET_PAGE_ADDRESS, + MIPI_COMMAND_WRITE_MEMORY_START, + display_init_sequence, + sizeof(display_init_sequence), + NULL, // no backlight pin on an AMOLED + 0x51, // brightness_command + 1.0f, // brightness + false, // single_byte_bounds + false, // data_as_commands + true, // auto_refresh + 60, // native_frames_per_second + true, // backlight_on_high + false, // SH1107_addressing + 50000); // backlight_pwm_frequency +} + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/waveshare_esp32_s3_amoled_175c/mpconfigboard.h b/ports/espressif/boards/waveshare_esp32_s3_amoled_175c/mpconfigboard.h new file mode 100644 index 00000000000..003719711c2 --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_amoled_175c/mpconfigboard.h @@ -0,0 +1,28 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Hassan Naeem +// +// SPDX-License-Identifier: MIT + +#pragma once + +#define MICROPY_HW_BOARD_NAME "Waveshare ESP32-S3-Touch-AMOLED-1.75C" +#define MICROPY_HW_MCU_NAME "ESP32S3" + +// Touch (CST9217), PMU (AXP2101), codecs (ES8311, ES7210) and IMU (QMI8658) +#define CIRCUITPY_BOARD_I2C (1) +#define CIRCUITPY_BOARD_I2C_PIN {{.scl = &pin_GPIO14, .sda = &pin_GPIO15}} + +#define CIRCUITPY_BOARD_DISPLAY (1) +#define CIRCUITPY_LCD_CS (&pin_GPIO12) +#define CIRCUITPY_LCD_CLK (&pin_GPIO38) +#define CIRCUITPY_LCD_D0 (&pin_GPIO4) +#define CIRCUITPY_LCD_D1 (&pin_GPIO5) +#define CIRCUITPY_LCD_D2 (&pin_GPIO6) +#define CIRCUITPY_LCD_D3 (&pin_GPIO7) +#define CIRCUITPY_LCD_RESET (&pin_GPIO1) + +#define CIRCUITPY_BOARD_SPI (0) + +#define DEFAULT_UART_BUS_RX (&pin_GPIO44) +#define DEFAULT_UART_BUS_TX (&pin_GPIO43) diff --git a/ports/espressif/boards/waveshare_esp32_s3_amoled_175c/mpconfigboard.mk b/ports/espressif/boards/waveshare_esp32_s3_amoled_175c/mpconfigboard.mk new file mode 100644 index 00000000000..14b5de485b6 --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_amoled_175c/mpconfigboard.mk @@ -0,0 +1,36 @@ +# This file is part of the CircuitPython project: https://circuitpython.org +# SPDX-FileCopyrightText: Copyright (c) 2026 Hassan Naeem +# SPDX-License-Identifier: MIT + +USB_VID = 0x303A +USB_PID = 0x8413 +USB_MANUFACTURER = "Waveshare" +USB_PRODUCT = "ESP32-S3-Touch-AMOLED-1.75C" + +IDF_TARGET = esp32s3 + +# 32MB quad flash +CIRCUITPY_ESP_FLASH_SIZE = 32MB +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m + +# 8MB octal PSRAM +CIRCUITPY_ESP_PSRAM_SIZE = 8MB +CIRCUITPY_ESP_PSRAM_MODE = opi +CIRCUITPY_ESP_PSRAM_FREQ = 80m + +OPTIMIZATION_FLAGS = -Os + +# QSPI bus for the CO5300 AMOLED panel +CIRCUITPY_QSPIBUS = 1 +CIRCUITPY_PARALLELDISPLAYBUS = 0 + +CIRCUITPY_ESPCAMERA = 0 + +# Touch is the CST9217 on I2C, not the ESP32-S3's capacitive pins +CIRCUITPY_TOUCHIO = 0 + +# No SD card slot on the 1.75C +CIRCUITPY_SDIOIO = 0 + +CIRCUITPY_DISPLAY_AREA_BUFFER_SIZE = 8192 diff --git a/ports/espressif/boards/waveshare_esp32_s3_amoled_175c/pins.c b/ports/espressif/boards/waveshare_esp32_s3_amoled_175c/pins.c new file mode 100644 index 00000000000..7a1c816bb23 --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_amoled_175c/pins.c @@ -0,0 +1,65 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Hassan Naeem +// +// SPDX-License-Identifier: MIT + +#include "py/obj.h" +#include "py/mphal.h" +#include "shared-bindings/board/__init__.h" +#include "shared-module/displayio/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + // Buttons. PWR reads high while held. + { MP_ROM_QSTR(MP_QSTR_BOOT), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_PWR_BUTTON), MP_ROM_PTR(&pin_GPIO3) }, + + // I2C: CST9217 touch (0x5A), AXP2101 PMU (0x34), ES8311 (0x18), + // ES7210 (0x40), QMI8658 IMU (0x6B) + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, + + // Touch + { MP_ROM_QSTR(MP_QSTR_TP_INT), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_TP_RESET), MP_ROM_PTR(&pin_GPIO2) }, + + // IMU + { MP_ROM_QSTR(MP_QSTR_IMU_INT1), MP_ROM_PTR(&pin_GPIO21) }, + + // Audio: I2S to the ES8311 (speaker) and from the ES7210 (microphones) + { MP_ROM_QSTR(MP_QSTR_I2S_MCLK), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_I2S_BCLK), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_I2S_WS), MP_ROM_PTR(&pin_GPIO45) }, + { MP_ROM_QSTR(MP_QSTR_I2S_DOUT), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_I2S_DIN), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_PA_CTRL), MP_ROM_PTR(&pin_GPIO46) }, + + // QSPI display (CO5300) + { MP_ROM_QSTR(MP_QSTR_LCD_CS), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_LCD_CLK), MP_ROM_PTR(&pin_GPIO38) }, + { MP_ROM_QSTR(MP_QSTR_LCD_D0), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_LCD_D1), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_LCD_D2), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_LCD_D3), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_LCD_RESET), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_LCD_TE), MP_ROM_PTR(&pin_GPIO13) }, + + // UART + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO44) }, + + // Test pads on the back of the board + { 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_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_DISPLAY), MP_ROM_PTR(&displays[0].display) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/espressif/boards/waveshare_esp32_s3_amoled_175c/sdkconfig b/ports/espressif/boards/waveshare_esp32_s3_amoled_175c/sdkconfig new file mode 100644 index 00000000000..f97028a88d3 --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_amoled_175c/sdkconfig @@ -0,0 +1,3 @@ +# +# Configuration file for the Waveshare ESP32-S3 Touch AMOLED 1.75C +# diff --git a/ports/espressif/boards/waveshare_esp32_s3_amoled_241/board.c b/ports/espressif/boards/waveshare_esp32_s3_amoled_241/board.c new file mode 100644 index 00000000000..966ea8e8295 --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_amoled_241/board.c @@ -0,0 +1,105 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// SPDX-FileCopyrightText: Copyright (c) 2026 Przemyslaw Patrick Socha +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" +#include "mpconfigboard.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/digitalio/DigitalInOut.h" + +#include "shared-bindings/qspibus/QSPIBus.h" +#include "shared-bindings/busdisplay/BusDisplay.h" +#include "shared-module/displayio/__init__.h" +#include "shared-module/displayio/mipi_constants.h" + +// RM690B0 AMOLED initialization sequence. +// Format: command byte, length | 0x80 (if delay), data bytes..., [delay ms] +// Based on vendor recommendations, tested with Waveshare 2.41" AMOLED panel. +// Non-const to match upstream common_hal_busdisplay_busdisplay_construct signature. +static uint8_t display_init_sequence[] = { + // Page select and configuration + 0xFE, 0x01, 0x20, // Enter user command mode + 0x26, 0x01, 0x0A, // Bias setting + 0x24, 0x01, 0x80, // Source output control + 0xFE, 0x01, 0x13, // Page 13 + 0xEB, 0x01, 0x0E, // Vendor command + 0xFE, 0x01, 0x00, // Return to page 0 + // Display configuration + 0x3A, 0x01, 0x55, // COLMOD: 16-bit RGB565 + 0xC2, 0x81, 0x00, 0x0A, // Vendor command + 10ms delay + 0x35, 0x00, // Tearing effect line on (no data) + 0x51, 0x81, 0x00, 0x0A, // Brightness control + 10ms delay + // Power on + 0x11, 0x80, 0x50, // Sleep out + 80ms delay + // Display window (MV=1: CASET→rows, RASET→cols) + 0x2A, 0x04, 0x00, 0x10, 0x01, 0xD1, // CASET: 16..465 (450px + 16 offset) + 0x2B, 0x04, 0x00, 0x00, 0x02, 0x57, // RASET: 0..599 (600px) + // Enable display + 0x29, 0x80, 0x0A, // Display on + 10ms delay + // Memory access: MV=1, ML=1 for landscape + 0x36, 0x81, 0x30, 0x0A, // MADCTL + 10ms delay + // Brightness + 0x51, 0x01, 0xFF, // Set brightness to maximum +}; + +void board_init(void) { + // 0. Enable display power before any bus/display init. + digitalio_digitalinout_obj_t power_pin; + power_pin.base.type = &digitalio_digitalinout_type; + common_hal_digitalio_digitalinout_construct(&power_pin, CIRCUITPY_LCD_POWER); + common_hal_digitalio_digitalinout_set_value(&power_pin, true); + // Allow power rail to settle before reset/init. + mp_hal_delay_ms(200); + + // 1. Allocate and construct QSPI bus + qspibus_qspibus_obj_t *bus = &allocate_display_bus_or_raise()->qspi_bus; + bus->base.type = &qspibus_qspibus_type; + + common_hal_qspibus_qspibus_construct(bus, + CIRCUITPY_LCD_CLK, // clock + CIRCUITPY_LCD_D0, // data0 + CIRCUITPY_LCD_D1, // data1 + CIRCUITPY_LCD_D2, // data2 + CIRCUITPY_LCD_D3, // data3 + CIRCUITPY_LCD_CS, // cs + NULL, // dcx (not used, QSPI uses encoded commands) + CIRCUITPY_LCD_RESET, // reset + 40000000); // 40 MHz + + // 2. Allocate and construct BusDisplay with RM690B0 init sequence. + // Physical panel: 450 cols × 600 rows. + // MADCTL MV=1 swaps row/col → logical 600×450 landscape. + busdisplay_busdisplay_obj_t *display = &allocate_display_or_raise()->display; + display->base.type = &busdisplay_busdisplay_type; + + common_hal_busdisplay_busdisplay_construct(display, + bus, + 600, // width (logical, after MV=1 swap) + 450, // height (logical, after MV=1 swap) + 0, // colstart + 16, // rowstart (physical row offset) + 0, // rotation + 16, // color_depth (RGB565) + false, // grayscale + false, // pixels_in_byte_share_row + 1, // bytes_per_cell + false, // reverse_pixels_in_byte + false, // reverse_bytes_in_word + MIPI_COMMAND_SET_COLUMN_ADDRESS, // set_column_command + MIPI_COMMAND_SET_PAGE_ADDRESS, // set_row_command + MIPI_COMMAND_WRITE_MEMORY_START, // write_ram_command + display_init_sequence, + sizeof(display_init_sequence), + NULL, // backlight_pin (AMOLED — no backlight GPIO) + 0x51, // brightness_command + 1.0f, // brightness + false, // single_byte_bounds + false, // data_as_commands + true, // auto_refresh + 60, // native_frames_per_second + true, // backlight_on_high + false, // SH1107_addressing + 50000); // backlight_pwm_frequency +} + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/waveshare_esp32_s3_amoled_241/mpconfigboard.h b/ports/espressif/boards/waveshare_esp32_s3_amoled_241/mpconfigboard.h new file mode 100644 index 00000000000..979e17a2817 --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_amoled_241/mpconfigboard.h @@ -0,0 +1,33 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// SPDX-FileCopyrightText: Copyright (c) 2026 Przemyslaw Patrick Socha +// SPDX-License-Identifier: MIT + +#pragma once + +#define MICROPY_HW_BOARD_NAME "Waveshare ESP32-S3-Touch-AMOLED-2.41" +#define MICROPY_HW_MCU_NAME "ESP32S3" + +// I2C bus - Disabled on boot to avoid conflicts. User must manually initialize I2C. +#define CIRCUITPY_BOARD_I2C (0) +#define CIRCUITPY_BOARD_I2C_PIN {{.scl = &pin_GPIO48, .sda = &pin_GPIO47}} + +// AMOLED Display (displayio + qspibus path) - initialized in board_init() +#define CIRCUITPY_BOARD_DISPLAY (1) +#define CIRCUITPY_LCD_CS (&pin_GPIO9) +#define CIRCUITPY_LCD_CLK (&pin_GPIO10) +#define CIRCUITPY_LCD_D0 (&pin_GPIO11) +#define CIRCUITPY_LCD_D1 (&pin_GPIO12) +#define CIRCUITPY_LCD_D2 (&pin_GPIO13) +#define CIRCUITPY_LCD_D3 (&pin_GPIO14) +#define CIRCUITPY_LCD_RESET (&pin_GPIO21) +#define CIRCUITPY_LCD_POWER (&pin_GPIO16) + +// No default SPI bus — SD card uses SDIO, display uses QSPI. +#define CIRCUITPY_BOARD_SPI (0) + +// Default UART bus +#define DEFAULT_UART_BUS_RX (&pin_GPIO44) +#define DEFAULT_UART_BUS_TX (&pin_GPIO43) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/waveshare_esp32_s3_amoled_241/mpconfigboard.mk b/ports/espressif/boards/waveshare_esp32_s3_amoled_241/mpconfigboard.mk new file mode 100644 index 00000000000..022525621ac --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_amoled_241/mpconfigboard.mk @@ -0,0 +1,39 @@ +# This file is part of the CircuitPython project: https://circuitpython.org +# SPDX-FileCopyrightText: Copyright (c) 2026 Przemyslaw Patrick Socha +# SPDX-License-Identifier: MIT + +USB_VID = 0x303A +USB_PID = 0x8278 +USB_MANUFACTURER = "Waveshare" +USB_PRODUCT = "ESP32-S3-Touch-AMOLED-2.41" + +IDF_TARGET = esp32s3 + +# Flash configuration - 16MB QSPI Flash +CIRCUITPY_ESP_FLASH_SIZE = 16MB +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m + +# PSRAM configuration - 8MB Octal PSRAM +CIRCUITPY_ESP_PSRAM_SIZE = 8MB +CIRCUITPY_ESP_PSRAM_MODE = opi +CIRCUITPY_ESP_PSRAM_FREQ = 80m + +OPTIMIZATION_FLAGS = -Os + +# QSPI bus for RM690B0 AMOLED display +CIRCUITPY_QSPIBUS = 1 +CIRCUITPY_PARALLELDISPLAYBUS = 0 + +# No camera on this board +CIRCUITPY_ESPCAMERA = 0 + +# Capacitive touch not available; board uses I2C touch controller +CIRCUITPY_TOUCHIO = 0 + +# SD card via SDMMC interface +CIRCUITPY_SDIOIO = 1 + +# Display refresh buffer: 8192 bytes on the stack. +# ESP32-S3 main task stack is 24KB; verified safe with this board. +CIRCUITPY_DISPLAY_AREA_BUFFER_SIZE = 8192 diff --git a/ports/espressif/boards/waveshare_esp32_s3_amoled_241/pins.c b/ports/espressif/boards/waveshare_esp32_s3_amoled_241/pins.c new file mode 100644 index 00000000000..8804cace06d --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_amoled_241/pins.c @@ -0,0 +1,109 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// SPDX-FileCopyrightText: Copyright (c) 2026 Przemyslaw Patrick Socha +// SPDX-License-Identifier: MIT + +#include "py/obj.h" +#include "py/mphal.h" +#include "shared-bindings/board/__init__.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-module/displayio/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + // ================================================================= + // ONBOARD PERIPHERALS - Functional Names + // ================================================================= + + // Boot/Control/Battery/Display Power + // NOTE: GPIO16 is shared between battery control circuitry and LCD power + // (see CIRCUITPY_QSPIBUS_PANEL_POWER_PIN in mpconfigboard.h). + { MP_ROM_QSTR(MP_QSTR_BOOT), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_KEY_BAT), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_BAT_CONTROL), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_LCD_POWER), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_BAT_ADC), MP_ROM_PTR(&pin_GPIO17) }, + + // I2C Bus (shared by Touch, RTC, IMU, IO Expander) + // NOTE: board.I2C auto-initialization is disabled (CIRCUITPY_BOARD_I2C=0) + // to avoid boot conflicts. Users must manually create I2C bus: + // i2c = busio.I2C(board.SCL, board.SDA) + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO47) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO48) }, + + // Touch Panel (FT6336U on I2C) + // NOTE: TP_INT is routed through the TCA9554 IO expander (EXIO2), + // not a direct ESP32-S3 GPIO — no TOUCH_INT alias is possible here. + { MP_ROM_QSTR(MP_QSTR_TP_SDA), MP_ROM_PTR(&pin_GPIO47) }, + { MP_ROM_QSTR(MP_QSTR_TP_SCL), MP_ROM_PTR(&pin_GPIO48) }, + { MP_ROM_QSTR(MP_QSTR_TP_RESET), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_TOUCH_SDA), MP_ROM_PTR(&pin_GPIO47) }, + { MP_ROM_QSTR(MP_QSTR_TOUCH_SCL), MP_ROM_PTR(&pin_GPIO48) }, + { MP_ROM_QSTR(MP_QSTR_TOUCH_RST), MP_ROM_PTR(&pin_GPIO3) }, + + // RTC (PCF85063 on I2C) + { MP_ROM_QSTR(MP_QSTR_RTC_SDA), MP_ROM_PTR(&pin_GPIO47) }, + { MP_ROM_QSTR(MP_QSTR_RTC_SCL), MP_ROM_PTR(&pin_GPIO48) }, + + // IMU (QMI8658 on I2C) + { MP_ROM_QSTR(MP_QSTR_IMU_SDA), MP_ROM_PTR(&pin_GPIO47) }, + { MP_ROM_QSTR(MP_QSTR_IMU_SCL), MP_ROM_PTR(&pin_GPIO48) }, + + // I/O Expander (TCA9554 on I2C) + { MP_ROM_QSTR(MP_QSTR_EXIO_SDA), MP_ROM_PTR(&pin_GPIO47) }, + { MP_ROM_QSTR(MP_QSTR_EXIO_SCL), MP_ROM_PTR(&pin_GPIO48) }, + + // USB + { MP_ROM_QSTR(MP_QSTR_USB_D_N), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_USB_D_P), MP_ROM_PTR(&pin_GPIO20) }, + + // UART + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO44) }, + + // QSPI Display (RM690B0) - canonical generic LCD aliases. + { MP_ROM_QSTR(MP_QSTR_LCD_CS), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_LCD_CLK), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_LCD_D0), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_LCD_D1), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_LCD_D2), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_LCD_D3), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_LCD_RESET), MP_ROM_PTR(&pin_GPIO21) }, + + // Display Aliases + { MP_ROM_QSTR(MP_QSTR_DISPLAY_CS), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_DISPLAY_SCK), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_DISPLAY_D0), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_DISPLAY_D1), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_DISPLAY_D2), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_DISPLAY_D3), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_DISPLAY_RST), MP_ROM_PTR(&pin_GPIO21) }, + + // SD Card (SDIO / SDMMC) + { MP_ROM_QSTR(MP_QSTR_SDIO_CLK), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_SDIO_CMD), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_SDIO_D0), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_SDIO_D3), MP_ROM_PTR(&pin_GPIO2) }, + + // ================================================================= + // GENERAL PURPOSE I/O (IOxx - Espressif Convention) + // ================================================================= + // Only pins NOT dedicated to onboard peripherals are exposed here. + // Use functional names above for dedicated pins (e.g., SDA, SD_CS). + + { MP_ROM_QSTR(MP_QSTR_IO0), MP_ROM_PTR(&pin_GPIO0) }, // BOOT button (available when not holding BOOT) + { MP_ROM_QSTR(MP_QSTR_IO1), MP_ROM_PTR(&pin_GPIO1) }, // Available + { MP_ROM_QSTR(MP_QSTR_IO3), MP_ROM_PTR(&pin_GPIO3) }, // TP_RESET (available if touch not used) + { MP_ROM_QSTR(MP_QSTR_IO7), MP_ROM_PTR(&pin_GPIO7) }, // Available + { MP_ROM_QSTR(MP_QSTR_IO8), MP_ROM_PTR(&pin_GPIO8) }, // Available + { MP_ROM_QSTR(MP_QSTR_IO18), MP_ROM_PTR(&pin_GPIO18) }, // Available + { MP_ROM_QSTR(MP_QSTR_IO40), MP_ROM_PTR(&pin_GPIO40) }, // Available + { MP_ROM_QSTR(MP_QSTR_IO41), MP_ROM_PTR(&pin_GPIO41) }, // Available + { MP_ROM_QSTR(MP_QSTR_IO42), MP_ROM_PTR(&pin_GPIO42) }, // Available + { MP_ROM_QSTR(MP_QSTR_IO45), MP_ROM_PTR(&pin_GPIO45) }, // Available + { MP_ROM_QSTR(MP_QSTR_IO46), MP_ROM_PTR(&pin_GPIO46) }, // Available + + // Board display (initialized in board_init) + { 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/espressif/boards/waveshare_esp32_s3_amoled_241/sdkconfig b/ports/espressif/boards/waveshare_esp32_s3_amoled_241/sdkconfig new file mode 100644 index 00000000000..fa60cc4c237 --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_amoled_241/sdkconfig @@ -0,0 +1,3 @@ +# +# Configuration file for the Waveshare ESP32-S3 Touch AMOLED 2.41 +# diff --git a/ports/espressif/boards/waveshare_esp32_s3_eth/mpconfigboard.h b/ports/espressif/boards/waveshare_esp32_s3_eth/mpconfigboard.h index 037fa18c0be..5630a162798 100644 --- a/ports/espressif/boards/waveshare_esp32_s3_eth/mpconfigboard.h +++ b/ports/espressif/boards/waveshare_esp32_s3_eth/mpconfigboard.h @@ -15,3 +15,6 @@ #define DEFAULT_UART_BUS_RX (&pin_GPIO44) #define DEFAULT_UART_BUS_TX (&pin_GPIO43) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/waveshare_esp32_s3_geek/board.c b/ports/espressif/boards/waveshare_esp32_s3_geek/board.c index 414188fb46a..0ce44753264 100644 --- a/ports/espressif/boards/waveshare_esp32_s3_geek/board.c +++ b/ports/espressif/boards/waveshare_esp32_s3_geek/board.c @@ -38,9 +38,9 @@ static void display_init(void) { common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO8, // TFT_DC - &pin_GPIO10, // TFT_CS - &pin_GPIO9, // TFT_RST + MP_OBJ_FROM_PTR(&pin_GPIO8), // TFT_DC + MP_OBJ_FROM_PTR(&pin_GPIO10), // TFT_CS + MP_OBJ_FROM_PTR(&pin_GPIO9), // TFT_RST 50000000, // Baudrate 0, // Polarity 0 // Phase diff --git a/ports/espressif/boards/waveshare_esp32_s3_geek/mpconfigboard.h b/ports/espressif/boards/waveshare_esp32_s3_geek/mpconfigboard.h index 87ac391f5a0..adb5a1c3af7 100644 --- a/ports/espressif/boards/waveshare_esp32_s3_geek/mpconfigboard.h +++ b/ports/espressif/boards/waveshare_esp32_s3_geek/mpconfigboard.h @@ -20,3 +20,6 @@ #define CIRCUITPY_BOARD_SPI (2) #define CIRCUITPY_BOARD_SPI_PIN {{.clock = &pin_GPIO12, .mosi = &pin_GPIO11}, \ {.clock = &pin_GPIO36, .mosi = &pin_GPIO35, .miso = &pin_GPIO37}} + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/waveshare_esp32_s3_lcd_1_28/board.c b/ports/espressif/boards/waveshare_esp32_s3_lcd_1_28/board.c index 36990c85566..fda6007da49 100644 --- a/ports/espressif/boards/waveshare_esp32_s3_lcd_1_28/board.c +++ b/ports/espressif/boards/waveshare_esp32_s3_lcd_1_28/board.c @@ -100,14 +100,13 @@ static void display_init(void) { NULL, // MISO not connected false // Not half-duplex ); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO8, // DC - &pin_GPIO9, // CS - &pin_GPIO12, // RST + MP_OBJ_FROM_PTR(&pin_GPIO8), // DC + MP_OBJ_FROM_PTR(&pin_GPIO9), // CS + MP_OBJ_FROM_PTR(&pin_GPIO12), // RST 80000000, // baudrate 0, // polarity 0 // phase diff --git a/ports/espressif/boards/waveshare_esp32_s3_lcd_1_28/mpconfigboard.h b/ports/espressif/boards/waveshare_esp32_s3_lcd_1_28/mpconfigboard.h index 1e1acbdd9f8..f19baae3c46 100644 --- a/ports/espressif/boards/waveshare_esp32_s3_lcd_1_28/mpconfigboard.h +++ b/ports/espressif/boards/waveshare_esp32_s3_lcd_1_28/mpconfigboard.h @@ -23,3 +23,6 @@ #define CIRCUITPY_CONSOLE_UART_RX DEFAULT_UART_BUS_RX #define CIRCUITPY_CONSOLE_UART_TX DEFAULT_UART_BUS_TX + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/waveshare_esp32_s3_lcd_1_28/mpconfigboard.mk b/ports/espressif/boards/waveshare_esp32_s3_lcd_1_28/mpconfigboard.mk index a8ac3b5d245..f4d1f33be79 100644 --- a/ports/espressif/boards/waveshare_esp32_s3_lcd_1_28/mpconfigboard.mk +++ b/ports/espressif/boards/waveshare_esp32_s3_lcd_1_28/mpconfigboard.mk @@ -21,4 +21,5 @@ INTERNAL_FLASH_FILESYSTEM = 0 QSPI_FLASH_FILESYSTEM = 1 EXTERNAL_FLASH_DEVICES = W25Q128JVxQ +# Not enough pins. CIRCUITPY_ESPCAMERA = 0 diff --git a/ports/espressif/boards/waveshare_esp32_s3_lcd_1_47/board.c b/ports/espressif/boards/waveshare_esp32_s3_lcd_1_47/board.c new file mode 100644 index 00000000000..4ecf87948ad --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_lcd_1_47/board.c @@ -0,0 +1,99 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Benjamin Shockley +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" +#include "mpconfigboard.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/busio/SPI.h" +#include "shared-bindings/fourwire/FourWire.h" +#include "shared-module/displayio/__init__.h" +#include "shared-module/displayio/mipi_constants.h" +#include "shared-bindings/board/__init__.h" + +#define DELAY 0x80 + +// Driver is ST7789V3 +// Display Panel is LBS147TC-IF15 +// 172 X 320 Pixels RGB 18-bit + +uint8_t display_init_sequence[] = { + 0x01, 0 | DELAY, 120, + 0x11, 0 | DELAY, 120, + 0x13, 0, + 0x36, 1, 0x00, + 0x3A, 1 | DELAY, 0x05, 10, + 0xB2, 5, 0x0C, 0x0C, 0x00, 0x33, 0x33, + 0xB7, 1, 0x35, + 0xBB, 1, 0x20, + 0xC0, 1, 0x2C, + 0xC2, 2, 0x01, 0xFF, + 0xC3, 1, 0x13, + 0xC4, 1, 0x20, + 0xC6, 1, 0x0F, + 0xD0, 2, 0xA4, 0xA1, + 0xE0, 14, 0xF0, 0x00, 0x04, 0x04, 0x04, 0x05, 0x29, 0x33, 0x3E, 0x38, 0x12, 0x12, 0x28, 0x30, + 0xE1, 14, 0xF0, 0x07, 0x0A, 0x0D, 0x0B, 0x07, 0x28, 0x33, 0x3E, 0x36, 0x14, 0x14, 0x29, 0x32, + 0x21, 0, + 0x29, 0 | DELAY, 255, +}; + +static void display_init(void) { + busio_spi_obj_t *spi = common_hal_board_create_spi(0); + fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; + bus->base.type = &fourwire_fourwire_type; + + common_hal_fourwire_fourwire_construct( + bus, + spi, + MP_OBJ_FROM_PTR(&pin_GPIO41), // DC + MP_OBJ_FROM_PTR(&pin_GPIO42), // CS + MP_OBJ_FROM_PTR(&pin_GPIO39), // RST + 80000000, // baudrate + 0, // polarity + 0 // phase + ); + + busdisplay_busdisplay_obj_t *display = &allocate_display()->display; + display->base.type = &busdisplay_busdisplay_type; + + common_hal_busdisplay_busdisplay_construct( + display, + bus, + 172, // width (after rotation) + 320, // height (after rotation) + 34, // column start + 0, // row start + 0, // 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 + display_init_sequence, + sizeof(display_init_sequence), + &pin_GPIO48, // backlight pin + NO_BRIGHTNESS_COMMAND, + 1.0f, // brightness + false, // single_byte_bounds + false, // data_as_commands + true, // auto_refresh + 60, // native_frames_per_second + true, // backlight_on_high + false, // SH1107_addressing + 50000 // backlight pwm frequency + ); +} + +void board_init(void) { + // Display + display_init(); +} + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/waveshare_esp32_s3_lcd_1_47/mpconfigboard.h b/ports/espressif/boards/waveshare_esp32_s3_lcd_1_47/mpconfigboard.h new file mode 100644 index 00000000000..47d03fe9554 --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_lcd_1_47/mpconfigboard.h @@ -0,0 +1,25 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Benjamin Shockley +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Micropython setup + +#define MICROPY_HW_BOARD_NAME "Waveshare ESP32-S3 LCD 1.47" +#define MICROPY_HW_MCU_NAME "ESP32S3" + +#define DEFAULT_UART_BUS_RX (&pin_GPIO44) +#define DEFAULT_UART_BUS_TX (&pin_GPIO43) + +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO17) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO16) + +#define CIRCUITPY_BOARD_SPI (2) +#define CIRCUITPY_BOARD_SPI_PIN {{.clock = &pin_GPIO40, .mosi = &pin_GPIO45}, \ + {.clock = &pin_GPIO14, .mosi = &pin_GPIO15, .miso = &pin_GPIO16}} + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/waveshare_esp32_s3_lcd_1_47/mpconfigboard.mk b/ports/espressif/boards/waveshare_esp32_s3_lcd_1_47/mpconfigboard.mk new file mode 100644 index 00000000000..fbdc6a7a1ec --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_lcd_1_47/mpconfigboard.mk @@ -0,0 +1,14 @@ +USB_VID = 0x303A +USB_PID = 0x828B +USB_PRODUCT = "ESP32-S3-LCD-1.47" +USB_MANUFACTURER = "Waveshare Electronics" + +IDF_TARGET = esp32s3 + +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m +CIRCUITPY_ESP_FLASH_SIZE = 16MB + +CIRCUITPY_ESP_PSRAM_SIZE = 8MB +CIRCUITPY_ESP_PSRAM_MODE = opi +CIRCUITPY_ESP_PSRAM_FREQ = 80m diff --git a/ports/espressif/boards/waveshare_esp32_s3_lcd_1_47/pins.c b/ports/espressif/boards/waveshare_esp32_s3_lcd_1_47/pins.c new file mode 100644 index 00000000000..a2ebbb79a87 --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_lcd_1_47/pins.c @@ -0,0 +1,81 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" +#include "shared-module/displayio/__init__.h" + +CIRCUITPY_BOARD_BUS_SINGLETON(sd_spi, spi, 1) + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + // Button + { MP_ROM_QSTR(MP_QSTR_BTN), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_GP0), MP_ROM_PTR(&pin_GPIO0) }, + + // RGB LED + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO38) }, + { MP_ROM_QSTR(MP_QSTR_GP38), MP_ROM_PTR(&pin_GPIO38) }, + + // 7-12 LCD + // LCD Backlight + { MP_ROM_QSTR(MP_QSTR_GP48), MP_ROM_PTR(&pin_GPIO48) }, + // LCD DC + { MP_ROM_QSTR(MP_QSTR_GP41), MP_ROM_PTR(&pin_GPIO41) }, + // LCD RST + { MP_ROM_QSTR(MP_QSTR_GP39), MP_ROM_PTR(&pin_GPIO39) }, + // LCD CS + { MP_ROM_QSTR(MP_QSTR_CS), MP_ROM_PTR(&pin_GPIO42) }, + { MP_ROM_QSTR(MP_QSTR_GP42), MP_ROM_PTR(&pin_GPIO42) }, + // LCD MOSI + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO45) }, + { MP_ROM_QSTR(MP_QSTR_GP45), MP_ROM_PTR(&pin_GPIO45) }, + // LCD SCK + { MP_ROM_QSTR(MP_QSTR_CLK), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_GP40), MP_ROM_PTR(&pin_GPIO40) }, + + // 14-21 SD + { 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_GP21), MP_ROM_PTR(&pin_GPIO21) }, + + // 43-44 UART + { MP_ROM_QSTR(MP_QSTR_GP43), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_GP44), MP_ROM_PTR(&pin_GPIO44) }, + + // UART + { 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_UART), MP_ROM_PTR(&board_uart_obj) }, + + // I2C + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, + + // SD Card + { MP_ROM_QSTR(MP_QSTR_SD_SCK), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_SD_MOSI), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_SD_MISO), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_SD_CS), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_SD_SPI), MP_ROM_PTR(&board_sd_spi_obj) }, + // Pin 38 is for the SDIO interface, and therefore not included in the SPI object + + // LCD + { MP_ROM_QSTR(MP_QSTR_LCD_MOSI), MP_ROM_PTR(&pin_GPIO45) }, + { MP_ROM_QSTR(MP_QSTR_LCD_CLK), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_LCD_CS), MP_ROM_PTR(&pin_GPIO42) }, + { MP_ROM_QSTR(MP_QSTR_LCD_RST), MP_ROM_PTR(&pin_GPIO39) }, + { MP_ROM_QSTR(MP_QSTR_LCD_BACKLIGHT), MP_ROM_PTR(&pin_GPIO48) }, + { MP_ROM_QSTR(MP_QSTR_LCD_DC), MP_ROM_PTR(&pin_GPIO41) }, + { MP_ROM_QSTR(MP_QSTR_LCD_SPI), MP_ROM_PTR(&board_spi_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/espressif/boards/waveshare_esp32_s3_lcd_1_47/sdkconfig b/ports/espressif/boards/waveshare_esp32_s3_lcd_1_47/sdkconfig new file mode 100644 index 00000000000..e9628662160 --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_lcd_1_47/sdkconfig @@ -0,0 +1,14 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Component config +# +# +# LWIP +# +# end of LWIP + +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/boards/waveshare_esp32_s3_matrix/mpconfigboard.h b/ports/espressif/boards/waveshare_esp32_s3_matrix/mpconfigboard.h index 63595cb559e..c6c68e8336f 100644 --- a/ports/espressif/boards/waveshare_esp32_s3_matrix/mpconfigboard.h +++ b/ports/espressif/boards/waveshare_esp32_s3_matrix/mpconfigboard.h @@ -13,3 +13,6 @@ #define DEFAULT_UART_BUS_RX (&pin_GPIO44) #define DEFAULT_UART_BUS_TX (&pin_GPIO43) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/waveshare_esp32_s3_matrix/mpconfigboard.mk b/ports/espressif/boards/waveshare_esp32_s3_matrix/mpconfigboard.mk index f890ec8769f..0378c23be69 100644 --- a/ports/espressif/boards/waveshare_esp32_s3_matrix/mpconfigboard.mk +++ b/ports/espressif/boards/waveshare_esp32_s3_matrix/mpconfigboard.mk @@ -13,10 +13,5 @@ CIRCUITPY_ESP_PSRAM_SIZE = 2MB CIRCUITPY_ESP_PSRAM_MODE = qio CIRCUITPY_ESP_PSRAM_FREQ = 80m -CIRCUITPY_ESPCAMERA = 0 -CIRCUITPY_BITMAPFILTER = 0 -CIRCUITPY_CODEOP = 0 -CIRCUITPY_PARALLELDISPLAYBUS = 0 - # Include these Python libraries in firmware. FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel diff --git a/ports/espressif/boards/waveshare_esp32_s3_matrix/pins.c b/ports/espressif/boards/waveshare_esp32_s3_matrix/pins.c index e21f542179c..a107cd61c22 100644 --- a/ports/espressif/boards/waveshare_esp32_s3_matrix/pins.c +++ b/ports/espressif/boards/waveshare_esp32_s3_matrix/pins.c @@ -35,7 +35,7 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO2) }, { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_GPIO2) }, - { MP_ROM_QSTR(MP_QSTR_I01), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_IO1), MP_ROM_PTR(&pin_GPIO1) }, { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO1) }, { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO1) }, diff --git a/ports/espressif/boards/waveshare_esp32_s3_pico/mpconfigboard.h b/ports/espressif/boards/waveshare_esp32_s3_pico/mpconfigboard.h index 90ef06f2a12..5c3d0147918 100644 --- a/ports/espressif/boards/waveshare_esp32_s3_pico/mpconfigboard.h +++ b/ports/espressif/boards/waveshare_esp32_s3_pico/mpconfigboard.h @@ -11,7 +11,7 @@ #define MICROPY_HW_BOARD_NAME "Waveshare ESP32-S3-Pico" #define MICROPY_HW_MCU_NAME "ESP32S3" -#define MICROPY_HW_NEOPIXEL_ORDER_GRB (1) +#define MICROPY_HW_NEOPIXEL_ORDER (STATUS_NEOPIXEL_ORDER_RGB) #define MICROPY_HW_NEOPIXEL (&pin_GPIO21) #define DEFAULT_UART_BUS_RX (&pin_GPIO12) @@ -23,3 +23,6 @@ #define DEFAULT_SPI_BUS_SCK (&pin_GPIO36) #define DEFAULT_SPI_BUS_MOSI (&pin_GPIO35) #define DEFAULT_SPI_BUS_MISO (&pin_GPIO37) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/waveshare_esp32_s3_tiny/mpconfigboard.h b/ports/espressif/boards/waveshare_esp32_s3_tiny/mpconfigboard.h index fb33519370c..c6cb81c86a4 100644 --- a/ports/espressif/boards/waveshare_esp32_s3_tiny/mpconfigboard.h +++ b/ports/espressif/boards/waveshare_esp32_s3_tiny/mpconfigboard.h @@ -12,8 +12,11 @@ #define MICROPY_HW_MCU_NAME "ESP32S3" // This corrects the color ordering so that the CircuitPython status lights behave as expected -#define MICROPY_HW_NEOPIXEL_ORDER_GRB (1) +#define MICROPY_HW_NEOPIXEL_ORDER (STATUS_NEOPIXEL_ORDER_RGB) #define MICROPY_HW_NEOPIXEL (&pin_GPIO38) #define DEFAULT_UART_BUS_RX (&pin_GPIO19) #define DEFAULT_UART_BUS_TX (&pin_GPIO20) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/waveshare_esp32_s3_tiny/sdkconfig b/ports/espressif/boards/waveshare_esp32_s3_tiny/sdkconfig index 3d0800e10d9..e9628662160 100644 --- a/ports/espressif/boards/waveshare_esp32_s3_tiny/sdkconfig +++ b/ports/espressif/boards/waveshare_esp32_s3_tiny/sdkconfig @@ -7,7 +7,6 @@ # # LWIP # -# CONFIG_LWIP_IPV6 is not set # end of LWIP # end of Component config diff --git a/ports/espressif/boards/waveshare_esp32_s3_tiny_n8r8/board.c b/ports/espressif/boards/waveshare_esp32_s3_tiny_n8r8/board.c new file mode 100644 index 00000000000..a3a9eec0471 --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_tiny_n8r8/board.c @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/waveshare_esp32_s3_tiny_n8r8/mpconfigboard.h b/ports/espressif/boards/waveshare_esp32_s3_tiny_n8r8/mpconfigboard.h new file mode 100644 index 00000000000..b8388ab4b68 --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_tiny_n8r8/mpconfigboard.h @@ -0,0 +1,22 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Micropython setup + +#define MICROPY_HW_BOARD_NAME "Waveshare ESP32-S3-Tiny-N8R8" +#define MICROPY_HW_MCU_NAME "ESP32S3" + +// This corrects the color ordering so that the CircuitPython status lights behave as expected +#define MICROPY_HW_NEOPIXEL_ORDER (STATUS_NEOPIXEL_ORDER_RGB) +#define MICROPY_HW_NEOPIXEL (&pin_GPIO38) + +#define DEFAULT_UART_BUS_RX (&pin_GPIO19) +#define DEFAULT_UART_BUS_TX (&pin_GPIO20) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/waveshare_esp32_s3_tiny_n8r8/mpconfigboard.mk b/ports/espressif/boards/waveshare_esp32_s3_tiny_n8r8/mpconfigboard.mk new file mode 100644 index 00000000000..ebb8317c457 --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_tiny_n8r8/mpconfigboard.mk @@ -0,0 +1,16 @@ +USB_VID = 0x303a +USB_PID = 0x8379 +USB_PRODUCT = "ESP32-S3-Tiny-N8R8" +USB_MANUFACTURER = "Waveshare Electronics" + +IDF_TARGET = esp32s3 + +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m +CIRCUITPY_ESP_FLASH_SIZE = 8MB + +CIRCUITPY_ESP_PSRAM_SIZE = 8MB +CIRCUITPY_ESP_PSRAM_MODE = opi +CIRCUITPY_ESP_PSRAM_FREQ = 80m + +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel diff --git a/ports/espressif/boards/waveshare_esp32_s3_tiny_n8r8/pins.c b/ports/espressif/boards/waveshare_esp32_s3_tiny_n8r8/pins.c new file mode 100644 index 00000000000..917ef0506ab --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_tiny_n8r8/pins.c @@ -0,0 +1,61 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { 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_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_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_IO43), MP_ROM_PTR(&pin_GPIO43) }, + { 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_IO47), MP_ROM_PTR(&pin_GPIO47) }, + { MP_ROM_QSTR(MP_QSTR_IO48), MP_ROM_PTR(&pin_GPIO48) }, + + // NEOPIXEL (GRB Color Order) + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO38) }, + + // UART + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj) }, + // Any pins can be I2C + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, + // Any pins can be SPI + { 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/espressif/boards/waveshare_esp32_s3_tiny_n8r8/sdkconfig b/ports/espressif/boards/waveshare_esp32_s3_tiny_n8r8/sdkconfig new file mode 100644 index 00000000000..e9628662160 --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_tiny_n8r8/sdkconfig @@ -0,0 +1,14 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Component config +# +# +# LWIP +# +# end of LWIP + +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_1_47/board.c b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_1_47/board.c new file mode 100644 index 00000000000..1bdd74e77ee --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_1_47/board.c @@ -0,0 +1,145 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 natheihei +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" +#include "mpconfigboard.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/busio/SPI.h" +#include "shared-bindings/fourwire/FourWire.h" +#include "shared-module/displayio/__init__.h" +#include "shared-module/displayio/mipi_constants.h" +#include "shared-bindings/board/__init__.h" + +#define DELAY 0x80 + +// Driver is JD9853 +// 172 X 320 Pixels RGB 18-bit +// Init sequence converted from Arduino example + +uint8_t display_init_sequence[] = { + // Command: 0x11 (SLPOUT: Sleep Out) + // Description: Exits sleep mode. A 120ms delay is added for the power supply and clock circuits to stabilize. + 0x11, 0 | DELAY, 120, + + 0xDF, 2, 0x98, 0x53, + 0xB2, 1, 0x23, + + 0xB7, 4, 0x00, 0x47, 0x00, 0x6F, + 0xBB, 6, 0x1C, 0x1A, 0x55, 0x73, 0x63, 0xF0, + 0xC0, 2, 0x44, 0xA4, + 0xC1, 1, 0x16, + 0xC3, 8, 0x7D, 0x07, 0x14, 0x06, 0xCF, 0x71, 0x72, 0x77, + 0xC4, 12, 0x00, 0x00, 0xA0, 0x79, 0x0B, 0x0A, 0x16, 0x79, 0x0B, 0x0A, 0x16, 0x82, + + 0xC8, 32, 0x3F, 0x32, 0x29, 0x29, 0x27, 0x2B, 0x27, 0x28, 0x28, 0x26, 0x25, 0x17, 0x12, 0x0D, 0x04, 0x00, + 0x3F, 0x32, 0x29, 0x29, 0x27, 0x2B, 0x27, 0x28, 0x28, 0x26, 0x25, 0x17, 0x12, 0x0D, 0x04, 0x00, + + 0xD0, 5, 0x04, 0x06, 0x6B, 0x0F, 0x00, + 0xD7, 2, 0x00, 0x30, + 0xE6, 1, 0x14, + 0xDE, 1, 0x01, + + 0xB7, 5, 0x03, 0x13, 0xEF, 0x35, 0x35, + 0xC1, 3, 0x14, 0x15, 0xC0, + 0xC2, 2, 0x06, 0x3A, + 0xC4, 2, 0x72, 0x12, + 0xBE, 1, 0x00, + 0xDE, 1, 0x02, + + 0xE5, 3, 0x00, 0x02, 0x00, + 0xE5, 3, 0x01, 0x02, 0x00, + + 0xDE, 1, 0x00, + + // Command: 0x35 (TEON: Tearing Effect Line ON) + // Description: Turns on the Tearing Effect output signal. + 0x35, 1, 0x00, + + // Command: 0x3A (COLMOD: Pixel Format Set) + // Description: Sets the pixel format for the MCU interface. + 0x3A, 1, 0x05, + + // Command: 0x2A (CASET: Column Address Set) + // Description: Defines the accessible column range in frame memory. + 0x2A, 4, 0x00, 0x22, 0x00, 0xCD, + + // Command: 0x2B (PASET: Page Address Set) + // Description: Defines the accessible page (row) range. + 0x2B, 4, 0x00, 0x00, 0x01, 0x3F, + + 0xDE, 1, 0x02, + 0xE5, 3, 0x00, 0x02, 0x00, + 0xDE, 1, 0x00, + + // Command: 0x36 (MADCTL: Memory Access Control) + // Description: Sets the read/write scanning direction of the frame memory. + 0x36, 1, 0x00, + + // Command: 0x21 (INVON: Display Inversion ON) + // 0x21, 0 | DELAY, 10, + + // Command: 0x29 (DISPON: Display ON) + // Description: Turns the display on by enabling output from the frame memory. + 0x29, 0, +}; + +static void display_init(void) { + busio_spi_obj_t *spi = common_hal_board_create_spi(0); + fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; + bus->base.type = &fourwire_fourwire_type; + + common_hal_fourwire_fourwire_construct( + bus, + spi, + MP_OBJ_FROM_PTR(&pin_GPIO45), // DC + MP_OBJ_FROM_PTR(&pin_GPIO21), // CS + MP_OBJ_FROM_PTR(&pin_GPIO40), // RST + 80000000, // baudrate + 0, // polarity + 0 // phase + ); + + busdisplay_busdisplay_obj_t *display = &allocate_display()->display; + display->base.type = &busdisplay_busdisplay_type; + + common_hal_busdisplay_busdisplay_construct( + display, + bus, + 172, // width (after rotation) + 320, // height (after rotation) + 34, // column start + 0, // row start + 0, // 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 + display_init_sequence, + sizeof(display_init_sequence), + &pin_GPIO46, // backlight pin + NO_BRIGHTNESS_COMMAND, + 1.0f, // brightness + false, // single_byte_bounds + false, // data_as_commands + true, // auto_refresh + 60, // native_frames_per_second + true, // backlight_on_high + false, // SH1107_addressing + 50000 // backlight pwm frequency + ); +} + +void board_init(void) { + // Display + display_init(); +} + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_1_47/mpconfigboard.h b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_1_47/mpconfigboard.h new file mode 100644 index 00000000000..7fed8626501 --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_1_47/mpconfigboard.h @@ -0,0 +1,25 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 natheihei +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Micropython setup + +#define MICROPY_HW_BOARD_NAME "Waveshare ESP32-S3 Touch LCD 1.47" +#define MICROPY_HW_MCU_NAME "ESP32S3" + +#define CIRCUITPY_BOARD_UART (1) +#define CIRCUITPY_BOARD_UART_PIN {{.rx = &pin_GPIO44, .tx = &pin_GPIO43}} + +#define CIRCUITPY_BOARD_I2C (1) +#define CIRCUITPY_BOARD_I2C_PIN {{.scl = &pin_GPIO41, .sda = &pin_GPIO42}} /* for Touchscreen */ + +#define CIRCUITPY_BOARD_SPI (2) +#define CIRCUITPY_BOARD_SPI_PIN {{.clock = &pin_GPIO38, .mosi = &pin_GPIO39}, /* for LCD display */ \ + {.clock = &pin_GPIO16, .mosi = &pin_GPIO15, .miso = &pin_GPIO17} /* for SD Card */} + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_1_47/mpconfigboard.mk b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_1_47/mpconfigboard.mk new file mode 100644 index 00000000000..b337b211495 --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_1_47/mpconfigboard.mk @@ -0,0 +1,14 @@ +USB_VID = 0x303A +USB_PID = 0x8325 +USB_PRODUCT = "ESP32-S3-Touch-LCD-1.47" +USB_MANUFACTURER = "Waveshare Electronics" + +IDF_TARGET = esp32s3 + +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m +CIRCUITPY_ESP_FLASH_SIZE = 16MB + +CIRCUITPY_ESP_PSRAM_SIZE = 8MB +CIRCUITPY_ESP_PSRAM_MODE = opi +CIRCUITPY_ESP_PSRAM_FREQ = 80m diff --git a/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_1_47/pins.c b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_1_47/pins.c new file mode 100644 index 00000000000..32c7d0dd21d --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_1_47/pins.c @@ -0,0 +1,58 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 natheihei +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" +#include "shared-module/displayio/__init__.h" + +CIRCUITPY_BOARD_BUS_SINGLETON(touch_i2c, i2c, 0) +CIRCUITPY_BOARD_BUS_SINGLETON(sd_spi, spi, 1) + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + // UART + { 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_UART), MP_ROM_PTR(&board_uart_obj) }, + + // GPIO + { MP_ROM_QSTR(MP_QSTR_GPIO1), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_GPIO2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_GPIO3), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_GPIO4), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_GPIO5), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_GPIO6), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_GPIO7), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_GPIO8), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_GPIO9), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_GPIO10), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_GPIO11), MP_ROM_PTR(&pin_GPIO11) }, + + // I2C (occupied by Touch I2C) + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO41) }, + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO42) }, + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, + + // SD Card + { MP_ROM_QSTR(MP_QSTR_SD_CMD), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_SD_CLK), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_SD_D0), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_SD_D1), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_SD_D2), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_SD_D3), MP_ROM_PTR(&pin_GPIO14) }, + // CLK, CMD, D0 is also included in the SPI object as its MISO pin, MOSI pin, and SCK pin respectively + { MP_ROM_QSTR(MP_QSTR_SD_SPI), MP_ROM_PTR(&board_sd_spi_obj) }, + + // AXS5106L Touch + { MP_ROM_QSTR(MP_QSTR_TOUCH_I2C), MP_ROM_PTR(&board_touch_i2c_obj) }, + { MP_ROM_QSTR(MP_QSTR_TOUCH_RST), MP_ROM_PTR(&pin_GPIO47) }, + { MP_ROM_QSTR(MP_QSTR_TOUCH_IRQ), MP_ROM_PTR(&pin_GPIO48) }, + + // JD9853 LCD Display + { MP_ROM_QSTR(MP_QSTR_DISPLAY), MP_ROM_PTR(&displays[0].display) }, + +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_1_47/sdkconfig b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_1_47/sdkconfig new file mode 100644 index 00000000000..e9628662160 --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_1_47/sdkconfig @@ -0,0 +1,14 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Component config +# +# +# LWIP +# +# end of LWIP + +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_1_69/board.c b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_1_69/board.c new file mode 100644 index 00000000000..be7573a3f4d --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_1_69/board.c @@ -0,0 +1,103 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Brian Nelson +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" +#include "mpconfigboard.h" + +#include "common-hal/microcontroller/Pin.h" +#include "shared-bindings/busdisplay/BusDisplay.h" +#include "shared-bindings/busio/SPI.h" +#include "shared-bindings/fourwire/FourWire.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-module/displayio/__init__.h" +#include "shared-module/displayio/mipi_constants.h" + +#define DELAY 0x80 + +// Power hold: the function key powers the board up; SYS_EN must stay high +// to keep it running from the battery once the key is released. +#define SYS_EN_PIN (GPIO_NUM_41) + +// ST7789V2, 240x280 glass on a 240x320 controller (20 row offset) +static uint8_t display_init_sequence[] = { + 0x01, 0 | DELAY, 150, // SWRESET + 0x11, 0 | DELAY, 255, // SLPOUT + 0x3A, 1 | DELAY, 0x55, 10, // COLMOD: 16 bits per pixel + 0x36, 1, 0x00, // MADCTL: portrait + 0x21, 0 | DELAY, 10, // INVON: this panel is inverted + 0x13, 0 | DELAY, 10, // NORON + 0x29, 0 | DELAY, 255, // DISPON +}; + +static void display_init(void) { + fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; + busio_spi_obj_t *spi = &bus->inline_bus; + common_hal_busio_spi_construct(spi, &pin_GPIO6, &pin_GPIO7, NULL, false); + + bus->base.type = &fourwire_fourwire_type; + common_hal_fourwire_fourwire_construct( + bus, + spi, + MP_OBJ_FROM_PTR(&pin_GPIO4), // DC + MP_OBJ_FROM_PTR(&pin_GPIO5), // CS + MP_OBJ_FROM_PTR(&pin_GPIO8), // RST + 80000000, // baudrate + 0, // polarity + 0 // phase + ); + + busdisplay_busdisplay_obj_t *display = &allocate_display()->display; + display->base.type = &busdisplay_busdisplay_type; + common_hal_busdisplay_busdisplay_construct( + display, + bus, + 240, // width (after rotation) + 280, // height (after rotation) + 0, // column start + 20, // row start + 0, // 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 + display_init_sequence, + sizeof(display_init_sequence), + &pin_GPIO15, // backlight pin + NO_BRIGHTNESS_COMMAND, + 1.0f, // brightness + false, // single_byte_bounds + false, // data_as_commands + true, // auto_refresh + 60, // native_frames_per_second + true, // backlight_on_high + false, // SH1107_addressing + 50000 // backlight pwm frequency + ); +} + +void board_init(void) { + // SYS_EN_PIN is the power latch that keeps the board on when it runs from + // the battery. Default to high (on). + espressif_board_reset_pin_number(SYS_EN_PIN); + + display_init(); +} + +bool espressif_board_reset_pin_number(gpio_num_t pin_number) { + // Keep the power latch asserted across resets so the board stays on from the battery + if (pin_number == SYS_EN_PIN) { + config_pin_as_output_with_level(pin_number, true); + return true; + } + return false; +} + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_1_69/mpconfigboard.h b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_1_69/mpconfigboard.h new file mode 100644 index 00000000000..567383480c8 --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_1_69/mpconfigboard.h @@ -0,0 +1,15 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Brian Nelson +// +// SPDX-License-Identifier: MIT + +#pragma once + +#define MICROPY_HW_BOARD_NAME "Waveshare ESP32-S3-Touch-LCD-1.69" +#define MICROPY_HW_MCU_NAME "ESP32S3" + +#define CIRCUITPY_BOOT_BUTTON (&pin_GPIO0) + +#define CIRCUITPY_BOARD_I2C (1) +#define CIRCUITPY_BOARD_I2C_PIN {{.scl = &pin_GPIO10, .sda = &pin_GPIO11}} diff --git a/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_1_69/mpconfigboard.mk b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_1_69/mpconfigboard.mk new file mode 100644 index 00000000000..ec94c702207 --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_1_69/mpconfigboard.mk @@ -0,0 +1,14 @@ +USB_VID = 0x303A +USB_PID = 0x821F +USB_MANUFACTURER = "Waveshare Electronics" +USB_PRODUCT = "ESP32-S3-Touch-LCD-1.69" + +IDF_TARGET = esp32s3 + +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m +CIRCUITPY_ESP_FLASH_SIZE = 16MB + +CIRCUITPY_ESP_PSRAM_SIZE = 8MB +CIRCUITPY_ESP_PSRAM_MODE = opi +CIRCUITPY_ESP_PSRAM_FREQ = 80m diff --git a/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_1_69/pins.c b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_1_69/pins.c new file mode 100644 index 00000000000..94302f02567 --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_1_69/pins.c @@ -0,0 +1,53 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Brian Nelson +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" +#include "shared-module/displayio/__init__.h" + +// Boards with 8 MB octal PSRAM (this definition) use these pins. The first +// hardware revision (V1 schematic) put the power key on GPIO36, the power hold +// on GPIO35, the buzzer on GPIO33 and the RTC interrupt on GPIO41; those GPIOs +// belong to the octal PSRAM here, so V1 boards need their own definition. + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + // BOOT button + { MP_ROM_QSTR(MP_QSTR_BUTTON), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_BOOT), MP_ROM_PTR(&pin_GPIO0) }, + + // PWR key (silkscreen "PWR", net SYS_OUT): high idle, low while pressed. + // SYS_EN high keeps the board powered from the battery; drive it low to switch off. + { MP_ROM_QSTR(MP_QSTR_PWR_BUTTON), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_SYS_OUT), MP_ROM_PTR(&pin_GPIO40) }, + + { MP_ROM_QSTR(MP_QSTR_SYS_EN), MP_ROM_PTR(&pin_GPIO41) }, + + { MP_ROM_QSTR(MP_QSTR_BUZZER), MP_ROM_PTR(&pin_GPIO42) }, + + // Battery voltage + { MP_ROM_QSTR(MP_QSTR_BAT_ADC), MP_ROM_PTR(&pin_GPIO1) }, + + // I2C: CST816 touch (0x15), PCF85063 RTC (0x51), QMI8658 IMU (0x6B) + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO11) }, + + { MP_ROM_QSTR(MP_QSTR_TP_INT), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_TP_RST), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_RTC_INT), MP_ROM_PTR(&pin_GPIO39) }, + + // ST7789V2 display, 4-wire SPI + { MP_ROM_QSTR(MP_QSTR_LCD_SCK), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_LCD_MOSI), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_LCD_DC), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_LCD_CS), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_LCD_RST), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_LCD_BACKLIGHT), MP_ROM_PTR(&pin_GPIO15) }, + + { 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/tests/feature_check/io_module.py.exp b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_1_69/sdkconfig similarity index 100% rename from tests/feature_check/io_module.py.exp rename to ports/espressif/boards/waveshare_esp32_s3_touch_lcd_1_69/sdkconfig diff --git a/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_2/board.c b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_2/board.c index e7a6b86440e..71e2d745623 100644 --- a/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_2/board.c +++ b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_2/board.c @@ -34,9 +34,9 @@ void board_init(void) { common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO42, // DC - &pin_GPIO45, // CS - &pin_GPIO0, // RST + MP_OBJ_FROM_PTR(&pin_GPIO42), // DC + MP_OBJ_FROM_PTR(&pin_GPIO45), // CS + MP_OBJ_FROM_PTR(&pin_GPIO0), // RST // 24000000, 40000000, // baudrate 0, // polarity diff --git a/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_2/mpconfigboard.h b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_2/mpconfigboard.h index b4009fdfd7f..d6b66bffafa 100644 --- a/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_2/mpconfigboard.h +++ b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_2/mpconfigboard.h @@ -17,3 +17,6 @@ #define DEFAULT_UART_BUS_RX (&pin_GPIO44) #define DEFAULT_UART_BUS_TX (&pin_GPIO43) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_2_1/board.c b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_2_1/board.c new file mode 100644 index 00000000000..529e4858397 --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_2_1/board.c @@ -0,0 +1,221 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Brian Nelson +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" +#include "mpconfigboard.h" + +#include "common-hal/microcontroller/Pin.h" +#include "driver/gpio.h" +#include "py/mphal.h" +#include "shared-bindings/board/__init__.h" +#include "shared-bindings/busio/I2C.h" +#include "shared-bindings/dotclockframebuffer/DotClockFramebuffer.h" +#include "shared-bindings/framebufferio/FramebufferDisplay.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-module/displayio/__init__.h" +#include "supervisor/shared/settings.h" + +#define DELAY 0x80 + +// TCA9554 I/O expander +#define TCA9554_ADDRESS (0x20) +#define TCA9554_REG_OUTPUT (1) +#define TCA9554_REG_CONFIG (3) + +#define EXIO_LCD_RESET (1 << 0) +#define EXIO_TP_RESET (1 << 1) +#define EXIO_LCD_CS (1 << 2) +#define EXIO_SD_CS (1 << 3) +#define EXIO_BUZZER (1 << 7) +// IMU INT2/INT1 and RTC INT (bits 4-6) are inputs +#define EXIO_INPUTS (0x70) + +// The ST7701S is configured over 3-wire (9-bit) SPI. +// CS is on the I/O expander, SDA and SCK are shared with the SD card. +#define LCD_SPI_SDA (GPIO_NUM_1) +#define LCD_SPI_SCK (GPIO_NUM_2) + +#define BACKLIGHT_PIN (GPIO_NUM_6) + +// ST7701S init sequence from the Waveshare example code +static const uint8_t display_init_sequence[] = { + 0xff, 5, 0x77, 0x01, 0x00, 0x00, 0x10, + 0xc0, 2, 0x3b, 0x00, + 0xc1, 2, 0x0b, 0x02, + 0xc2, 2, 0x07, 0x02, + 0xcc, 1, 0x10, + 0xcd, 1, 0x08, + 0xb0, 16, 0x00, 0x11, 0x16, 0x0e, 0x11, 0x06, 0x05, 0x09, 0x08, 0x21, 0x06, 0x13, 0x10, 0x29, 0x31, 0x18, + 0xb1, 16, 0x00, 0x11, 0x16, 0x0e, 0x11, 0x07, 0x05, 0x09, 0x09, 0x21, 0x05, 0x13, 0x11, 0x2a, 0x31, 0x18, + 0xff, 5, 0x77, 0x01, 0x00, 0x00, 0x11, + 0xb0, 1, 0x6d, + 0xb1, 1, 0x37, + 0xb2, 1, 0x81, + 0xb3, 1, 0x80, + 0xb5, 1, 0x43, + 0xb7, 1, 0x85, + 0xb8, 1, 0x20, + 0xc1, 1, 0x78, + 0xc2, 1, 0x78, + 0xd0, 1, 0x88, + 0xe0, 3, 0x00, 0x00, 0x02, + 0xe1, 11, 0x03, 0xa0, 0x00, 0x00, 0x04, 0xa0, 0x00, 0x00, 0x00, 0x20, 0x20, + 0xe2, 13, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xe3, 4, 0x00, 0x00, 0x11, 0x00, + 0xe4, 2, 0x22, 0x00, + 0xe5, 16, 0x05, 0xec, 0xa0, 0xa0, 0x07, 0xee, 0xa0, 0xa0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xe6, 4, 0x00, 0x00, 0x11, 0x00, + 0xe7, 2, 0x22, 0x00, + 0xe8, 16, 0x06, 0xed, 0xa0, 0xa0, 0x08, 0xef, 0xa0, 0xa0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0xeb, 7, 0x00, 0x00, 0x40, 0x40, 0x00, 0x00, 0x00, + 0xed, 16, 0xff, 0xff, 0xff, 0xba, 0x0a, 0xbf, 0x45, 0xff, 0xff, 0x54, 0xfb, 0xa0, 0xab, 0xff, 0xff, 0xff, + 0xef, 6, 0x10, 0x0d, 0x04, 0x08, 0x3f, 0x1f, + 0xff, 5, 0x77, 0x01, 0x00, 0x00, 0x13, + 0xef, 1, 0x08, + 0xff, 5, 0x77, 0x01, 0x00, 0x00, 0x00, + 0x36, 1, 0x00, // MADCTL + 0x3a, 1, 0x66, // COLMOD + 0x11, DELAY, 0xff, // SLPOUT, delay 500ms + 0x20, DELAY, 120, // INVOFF, delay 120ms + 0x29, 0, // DISPON +}; + +static const mcu_pin_obj_t *blue_pins[] = { + &pin_GPIO5, &pin_GPIO45, &pin_GPIO48, &pin_GPIO47, &pin_GPIO21 +}; +static const mcu_pin_obj_t *green_pins[] = { + &pin_GPIO14, &pin_GPIO13, &pin_GPIO12, &pin_GPIO11, &pin_GPIO10, &pin_GPIO9 +}; +static const mcu_pin_obj_t *red_pins[] = { + &pin_GPIO46, &pin_GPIO3, &pin_GPIO8, &pin_GPIO18, &pin_GPIO17 +}; + +static void expander_write(busio_i2c_obj_t *i2c, uint8_t reg, uint8_t value) { + const uint8_t buf[] = { reg, value }; + common_hal_busio_i2c_write(i2c, TCA9554_ADDRESS, buf, sizeof(buf)); +} + +static void lcd_spi_send(bool is_data, uint8_t value) { + uint16_t bits = value | (is_data ? 0x100 : 0); + // CPOL=CPHA=0, MSB first: the D/C bit, then 8 data bits + for (int i = 0; i < 9; i++) { + gpio_set_level(LCD_SPI_SCK, 0); + gpio_set_level(LCD_SPI_SDA, (bits & 0x100) != 0); + gpio_set_level(LCD_SPI_SCK, 1); + bits <<= 1; + } + gpio_set_level(LCD_SPI_SCK, 0); +} + +static void send_display_init_sequence(busio_i2c_obj_t *i2c, uint8_t idle_outputs) { + gpio_set_direction(LCD_SPI_SDA, GPIO_MODE_OUTPUT); + gpio_set_direction(LCD_SPI_SCK, GPIO_MODE_OUTPUT); + gpio_set_level(LCD_SPI_SCK, 0); + + for (size_t i = 0; i < sizeof(display_init_sequence); /* NO INCREMENT */) { + const uint8_t *cmd = display_init_sequence + i; + uint8_t data_size = cmd[1] & ~DELAY; + bool delay = (cmd[1] & DELAY) != 0; + const uint8_t *data = cmd + 2; + + expander_write(i2c, TCA9554_REG_OUTPUT, idle_outputs & ~EXIO_LCD_CS); + lcd_spi_send(false, cmd[0]); + for (uint8_t j = 0; j < data_size; j++) { + lcd_spi_send(true, data[j]); + } + expander_write(i2c, TCA9554_REG_OUTPUT, idle_outputs); + + if (delay) { + uint16_t delay_ms = data[data_size]; + if (delay_ms == 255) { + delay_ms = 500; + } + mp_hal_delay_ms(delay_ms); + data_size++; + } + i += 2 + data_size; + } + + // Release the pins for use by the SD card + gpio_reset_pin(LCD_SPI_SDA); + gpio_reset_pin(LCD_SPI_SCK); +} + +static void display_init(void) { + busio_i2c_obj_t i2c; + i2c.base.type = &busio_i2c_type; + common_hal_busio_i2c_construct(&i2c, &pin_GPIO7, &pin_GPIO15, 400000, 255); + while (!common_hal_busio_i2c_try_lock(&i2c)) { + } + + // Hold the LCD and touch controller in reset, everything else idle + const uint8_t idle_outputs = EXIO_LCD_RESET | EXIO_TP_RESET | EXIO_LCD_CS | EXIO_SD_CS; + expander_write(&i2c, TCA9554_REG_OUTPUT, idle_outputs & ~(EXIO_LCD_RESET | EXIO_TP_RESET)); + expander_write(&i2c, TCA9554_REG_CONFIG, EXIO_INPUTS); + mp_hal_delay_ms(10); + expander_write(&i2c, TCA9554_REG_OUTPUT, idle_outputs); + mp_hal_delay_ms(120); + + send_display_init_sequence(&i2c, idle_outputs); + + common_hal_busio_i2c_unlock(&i2c); + common_hal_busio_i2c_deinit(&i2c); + + mp_int_t frequency; + if (settings_get_int("CIRCUITPY_DISPLAY_FREQUENCY", &frequency) != SETTINGS_OK) { + frequency = 12000000; + } + + dotclockframebuffer_framebuffer_obj_t *framebuffer = &allocate_display_bus_or_raise()->dotclock; + framebuffer->base.type = &dotclockframebuffer_framebuffer_type; + common_hal_dotclockframebuffer_framebuffer_construct( + framebuffer, + &pin_GPIO40, // de + &pin_GPIO39, // vsync + &pin_GPIO38, // hsync + &pin_GPIO41, // pclk + red_pins, MP_ARRAY_SIZE(red_pins), + green_pins, MP_ARRAY_SIZE(green_pins), + blue_pins, MP_ARRAY_SIZE(blue_pins), + frequency, // frequency + 480, // width + 480, // height + 8, 10, 50, false, // horiz: pulse, back porch, front porch, idle low + 3, 8, 8, false, // vert: pulse, back porch, front porch, idle low + false, // DE idle high + true, // pclk active high + false, // pclk idle high + 0 // overscan left + ); + + framebufferio_framebufferdisplay_obj_t *display = &allocate_display_or_raise()->framebuffer_display; + display->base.type = &framebufferio_framebufferdisplay_type; + common_hal_framebufferio_framebufferdisplay_construct( + display, + framebuffer, + 0, // rotation + true // auto-refresh + ); +} + +void board_init(void) { + // BACKLIGHT_PIN controls the backlight. Default to high (on). The pin isn't + // claimed, so user code can still use it for PWM brightness. + espressif_board_reset_pin_number(BACKLIGHT_PIN); + + display_init(); +} + +bool espressif_board_reset_pin_number(gpio_num_t pin_number) { + // Keep the backlight on across resets, but leave the pin free for PWM brightness control + if (pin_number == BACKLIGHT_PIN) { + config_pin_as_output_with_level(pin_number, true); + return true; + } + return false; +} + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_2_1/mpconfigboard.h b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_2_1/mpconfigboard.h new file mode 100644 index 00000000000..526611ba682 --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_2_1/mpconfigboard.h @@ -0,0 +1,16 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Brian Nelson +// +// SPDX-License-Identifier: MIT + +#pragma once + +#define MICROPY_HW_BOARD_NAME "Waveshare ESP32-S3-Touch-LCD-2.1" +#define MICROPY_HW_MCU_NAME "ESP32S3" + +#define CIRCUITPY_BOARD_I2C (1) +#define CIRCUITPY_BOARD_I2C_PIN {{.scl = &pin_GPIO7, .sda = &pin_GPIO15}} + +#define DEFAULT_UART_BUS_RX (&pin_GPIO44) +#define DEFAULT_UART_BUS_TX (&pin_GPIO43) diff --git a/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_2_1/mpconfigboard.mk b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_2_1/mpconfigboard.mk new file mode 100644 index 00000000000..8505fd8c1a6 --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_2_1/mpconfigboard.mk @@ -0,0 +1,16 @@ +USB_VID = 0x303A +USB_PID = 0x825C +USB_MANUFACTURER = "Waveshare Electronics" +USB_PRODUCT = "ESP32-S3-Touch-LCD-2.1" + +IDF_TARGET = esp32s3 + +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m +CIRCUITPY_ESP_FLASH_SIZE = 16MB + +CIRCUITPY_ESP_PSRAM_SIZE = 8MB +CIRCUITPY_ESP_PSRAM_MODE = opi +CIRCUITPY_ESP_PSRAM_FREQ = 80m + +CIRCUITPY_DOTCLOCKFRAMEBUFFER = 1 diff --git a/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_2_1/pins.c b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_2_1/pins.c new file mode 100644 index 00000000000..5c753cf8403 --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_2_1/pins.c @@ -0,0 +1,128 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Brian Nelson +// +// SPDX-License-Identifier: MIT + +#include "py/objtuple.h" +#include "shared-bindings/board/__init__.h" +#include "shared-module/displayio/__init__.h" + +static const mp_rom_obj_tuple_t tft_r_pins = { + {&mp_type_tuple}, + 5, + { + MP_ROM_PTR(&pin_GPIO46), + MP_ROM_PTR(&pin_GPIO3), + MP_ROM_PTR(&pin_GPIO8), + MP_ROM_PTR(&pin_GPIO18), + MP_ROM_PTR(&pin_GPIO17), + } +}; + +static const mp_rom_obj_tuple_t tft_g_pins = { + {&mp_type_tuple}, + 6, + { + MP_ROM_PTR(&pin_GPIO14), + MP_ROM_PTR(&pin_GPIO13), + MP_ROM_PTR(&pin_GPIO12), + MP_ROM_PTR(&pin_GPIO11), + MP_ROM_PTR(&pin_GPIO10), + MP_ROM_PTR(&pin_GPIO9), + } +}; + +static const mp_rom_obj_tuple_t tft_b_pins = { + {&mp_type_tuple}, + 5, + { + MP_ROM_PTR(&pin_GPIO5), + MP_ROM_PTR(&pin_GPIO45), + MP_ROM_PTR(&pin_GPIO48), + MP_ROM_PTR(&pin_GPIO47), + MP_ROM_PTR(&pin_GPIO21), + } +}; + +static const mp_rom_map_elem_t tft_pins_table[] = { + { MP_ROM_QSTR(MP_QSTR_de), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_vsync), MP_ROM_PTR(&pin_GPIO39) }, + { MP_ROM_QSTR(MP_QSTR_hsync), MP_ROM_PTR(&pin_GPIO38) }, + { MP_ROM_QSTR(MP_QSTR_dclk), MP_ROM_PTR(&pin_GPIO41) }, + { MP_ROM_QSTR(MP_QSTR_red), MP_ROM_PTR(&tft_r_pins) }, + { MP_ROM_QSTR(MP_QSTR_green), MP_ROM_PTR(&tft_g_pins) }, + { MP_ROM_QSTR(MP_QSTR_blue), MP_ROM_PTR(&tft_b_pins) }, +}; +MP_DEFINE_CONST_DICT(tft_pins_dict, tft_pins_table); + +static const mp_rom_map_elem_t tft_timings_table[] = { + { MP_ROM_QSTR(MP_QSTR_frequency), MP_ROM_INT(12000000) }, + { MP_ROM_QSTR(MP_QSTR_width), MP_ROM_INT(480) }, + { MP_ROM_QSTR(MP_QSTR_height), MP_ROM_INT(480) }, + { MP_ROM_QSTR(MP_QSTR_hsync_pulse_width), MP_ROM_INT(8) }, + { MP_ROM_QSTR(MP_QSTR_hsync_back_porch), MP_ROM_INT(10) }, + { MP_ROM_QSTR(MP_QSTR_hsync_front_porch), MP_ROM_INT(50) }, + { MP_ROM_QSTR(MP_QSTR_hsync_idle_low), MP_ROM_FALSE }, + { MP_ROM_QSTR(MP_QSTR_vsync_pulse_width), MP_ROM_INT(3) }, + { MP_ROM_QSTR(MP_QSTR_vsync_back_porch), MP_ROM_INT(8) }, + { MP_ROM_QSTR(MP_QSTR_vsync_front_porch), MP_ROM_INT(8) }, + { MP_ROM_QSTR(MP_QSTR_vsync_idle_low), MP_ROM_FALSE }, + { MP_ROM_QSTR(MP_QSTR_de_idle_high), MP_ROM_FALSE }, + { MP_ROM_QSTR(MP_QSTR_pclk_active_high), MP_ROM_TRUE }, + { MP_ROM_QSTR(MP_QSTR_pclk_idle_high), MP_ROM_FALSE }, +}; +MP_DEFINE_CONST_DICT(tft_timings_dict, tft_timings_table); + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + // 12-pin header + { MP_ROM_QSTR(MP_QSTR_IO0), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_BOOT), MP_ROM_PTR(&pin_GPIO0) }, + + { 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) }, + + // I2C: header, touch, IMU, RTC and I/O expander + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_IO7), MP_ROM_PTR(&pin_GPIO7) }, + + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_IO15), MP_ROM_PTR(&pin_GPIO15) }, + + // CST820 touch + { MP_ROM_QSTR(MP_QSTR_TP_INT), MP_ROM_PTR(&pin_GPIO16) }, + + // Battery voltage (1/3 divider) + { MP_ROM_QSTR(MP_QSTR_BAT_ADC), MP_ROM_PTR(&pin_GPIO4) }, + + // microSD card (SPI mode; SD_CS is on the I/O expander) + { MP_ROM_QSTR(MP_QSTR_SD_CLK), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_SD_MOSI), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_SD_MISO), MP_ROM_PTR(&pin_GPIO42) }, + + // LCD + { MP_ROM_QSTR(MP_QSTR_LCD_BACKLIGHT), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_TFT_PINS), MP_ROM_PTR(&tft_pins_dict) }, + { MP_ROM_QSTR(MP_QSTR_TFT_TIMINGS), MP_ROM_PTR(&tft_timings_dict) }, + + // TCA9554 I/O expander (I2C address 0x20) pin numbers + { MP_ROM_QSTR(MP_QSTR_EXIO_LCD_RESET), MP_ROM_INT(0) }, + { MP_ROM_QSTR(MP_QSTR_EXIO_TP_RESET), MP_ROM_INT(1) }, + { MP_ROM_QSTR(MP_QSTR_EXIO_LCD_CS), MP_ROM_INT(2) }, + { MP_ROM_QSTR(MP_QSTR_EXIO_SD_CS), MP_ROM_INT(3) }, + { MP_ROM_QSTR(MP_QSTR_EXIO_IMU_INT2), MP_ROM_INT(4) }, + { MP_ROM_QSTR(MP_QSTR_EXIO_IMU_INT1), MP_ROM_INT(5) }, + { MP_ROM_QSTR(MP_QSTR_EXIO_RTC_INT), MP_ROM_INT(6) }, + { MP_ROM_QSTR(MP_QSTR_EXIO_BUZZER), MP_ROM_INT(7) }, + + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, + { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj) }, + { MP_ROM_QSTR(MP_QSTR_DISPLAY), MP_ROM_PTR(&displays[0].display) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/tests/feature_check/native_check.py.exp b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_2_1/sdkconfig similarity index 100% rename from tests/feature_check/native_check.py.exp rename to ports/espressif/boards/waveshare_esp32_s3_touch_lcd_2_1/sdkconfig diff --git a/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_2_8/board.c b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_2_8/board.c new file mode 100755 index 00000000000..49177f48fe7 --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_2_8/board.c @@ -0,0 +1,77 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" +#include "mpconfigboard.h" +#include "shared-bindings/busio/SPI.h" +#include "shared-bindings/fourwire/FourWire.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-module/displayio/__init__.h" +#include "shared-module/displayio/mipi_constants.h" +#include "shared-bindings/board/__init__.h" + +#define DELAY 0x80 + +// display init sequence according to LilyGO example app +uint8_t display_init_sequence[] = { + 0x01, DELAY, 0x96, // _SWRESET and Delay 150ms + 0x11, DELAY, 0xFF, // _SLPOUT and Delay 500ms + 0x3A, DELAY | 1, 0x55, 0x0A, // _COLMOD and Delay 10ms + 0x21, DELAY, 0x0A, // _INVON Hack and Delay 10ms + 0x13, DELAY, 0x0A, // _NORON and Delay 10ms + 0x36, 0x01, 0x60, // _MADCTL + 0x29, DELAY, 0xFF, // _DISPON and Delay 500ms +}; + +void board_init(void) { + busio_spi_obj_t *spi = common_hal_board_create_spi(0); + fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; + bus->base.type = &fourwire_fourwire_type; + + common_hal_fourwire_fourwire_construct( + bus, + spi, + MP_OBJ_FROM_PTR(&pin_GPIO41), // DC + MP_OBJ_FROM_PTR(&pin_GPIO42), // CS + MP_OBJ_FROM_PTR(&pin_GPIO39), // RST + 40000000, // baudrate + 0, // polarity + 0 // phase + ); + busdisplay_busdisplay_obj_t *display = &allocate_display()->display; + display->base.type = &busdisplay_busdisplay_type; + + common_hal_busdisplay_busdisplay_construct( + display, + bus, + 320, // width (after rotation) + 240, // height (after rotation) + 0, // column start + 0, // row start + 0, // 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 + display_init_sequence, + sizeof(display_init_sequence), + &pin_GPIO5, // backlight pin + NO_BRIGHTNESS_COMMAND, + 1.0f, // brightness + false, // single_byte_bounds + false, // data_as_commands + true, // auto_refresh + 60, // native_frames_per_second + true, // backlight_on_high + false, // SH1107_addressing + 50000 // backlight pwm frequency + ); +} diff --git a/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_2_8/mpconfigboard.h b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_2_8/mpconfigboard.h new file mode 100755 index 00000000000..a04002de73f --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_2_8/mpconfigboard.h @@ -0,0 +1,22 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Neradoc +// +// SPDX-License-Identifier: MIT + +#pragma once + +#define MICROPY_HW_BOARD_NAME "Waveshare ESP32-S3 Touch LCD 2.8" +#define MICROPY_HW_MCU_NAME "ESP32S3" + +#define CIRCUITPY_BOARD_I2C (1) +#define CIRCUITPY_BOARD_I2C_PIN {{.scl = &pin_GPIO3, .sda = &pin_GPIO1}} + +#define CIRCUITPY_BOARD_SPI (1) +#define CIRCUITPY_BOARD_SPI_PIN {{.clock = &pin_GPIO40, .mosi = &pin_GPIO45, .miso = &pin_GPIO46}} + +#define DEFAULT_UART_BUS_RX (&pin_GPIO44) +#define DEFAULT_UART_BUS_TX (&pin_GPIO43) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_2_8/mpconfigboard.mk b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_2_8/mpconfigboard.mk new file mode 100755 index 00000000000..421a5897600 --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_2_8/mpconfigboard.mk @@ -0,0 +1,14 @@ +USB_VID = 0x303A +USB_PID = 0x825F +USB_MANUFACTURER = "Waveshare Electronics" +USB_PRODUCT = "ESP32-S3 Touch LCD 2.8" + +IDF_TARGET = esp32s3 + +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m +CIRCUITPY_ESP_FLASH_SIZE = 16MB + +CIRCUITPY_ESP_PSRAM_SIZE = 8MB +CIRCUITPY_ESP_PSRAM_MODE = opi +CIRCUITPY_ESP_PSRAM_FREQ = 80m diff --git a/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_2_8/pins.c b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_2_8/pins.c new file mode 100755 index 00000000000..0bfb3e940b4 --- /dev/null +++ b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_2_8/pins.c @@ -0,0 +1,86 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" +#include "shared-module/displayio/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + // LCD (SPI0) + { MP_ROM_QSTR(MP_QSTR_LCD_SCK), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_LCD_MOSI), MP_ROM_PTR(&pin_GPIO45) }, + { MP_ROM_QSTR(MP_QSTR_LCD_MISO), MP_ROM_PTR(&pin_GPIO46) }, + { MP_ROM_QSTR(MP_QSTR_LCD_CS), MP_ROM_PTR(&pin_GPIO42) }, + { MP_ROM_QSTR(MP_QSTR_LCD_DC), MP_ROM_PTR(&pin_GPIO41) }, + { MP_ROM_QSTR(MP_QSTR_LCD_RST), MP_ROM_PTR(&pin_GPIO39) }, + { MP_ROM_QSTR(MP_QSTR_LCD_BL), MP_ROM_PTR(&pin_GPIO5) }, // PWM-capable + + // microSD (SPI1) + { MP_ROM_QSTR(MP_QSTR_SD_SCK), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_SD_MOSI), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_SD_MISO), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_SD_CS), MP_ROM_PTR(&pin_GPIO21) }, + + // Touch panel (I2C0) + { MP_ROM_QSTR(MP_QSTR_TP_SCL), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_TP_SDA), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_TP_RST), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_TP_INT), MP_ROM_PTR(&pin_GPIO4) }, + + // IMU (I2C1) + { MP_ROM_QSTR(MP_QSTR_IMU_SCL), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_IMU_SDA), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_IMU_INT2), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_IMU_INT1), MP_ROM_PTR(&pin_GPIO13) }, + + // I2S Audio + { MP_ROM_QSTR(MP_QSTR_I2S_BCK), MP_ROM_PTR(&pin_GPIO48) }, + { MP_ROM_QSTR(MP_QSTR_I2S_DIN), MP_ROM_PTR(&pin_GPIO47) }, + { MP_ROM_QSTR(MP_QSTR_I2S_LRCK), MP_ROM_PTR(&pin_GPIO38) }, + + // Battery management + { MP_ROM_QSTR(MP_QSTR_BAT_CONTROL), MP_ROM_PTR(&pin_GPIO7) }, // control pin + { MP_ROM_QSTR(MP_QSTR_BAT_PWR), MP_ROM_PTR(&pin_GPIO6) }, // Board name + { MP_ROM_QSTR(MP_QSTR_KEY_BAT), MP_ROM_PTR(&pin_GPIO6) }, // Schematics name + { MP_ROM_QSTR(MP_QSTR_BAT_ADC), MP_ROM_PTR(&pin_GPIO8) }, // VBAT sense (ADC) + + // UART header + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO44) }, + + // I2C header + { MP_ROM_QSTR(MP_QSTR_I2C_SCL), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_I2C_SDA), MP_ROM_PTR(&pin_GPIO11) }, + + // Boot/User button + { MP_ROM_QSTR(MP_QSTR_BOOT), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON0), MP_ROM_PTR(&pin_GPIO0) }, + + // Primary bus pins + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_GPIO40) }, // Primary SPI (LCD) + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO45) }, + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO46) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO3) }, // Primary I2C (TP) + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO1) }, + + // 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_ROM_QSTR(MP_QSTR_DISPLAY), MP_ROM_PTR(&displays[0].display) }, + + // User accessible + { 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_IO15), MP_ROM_PTR(&pin_GPIO15) }, + { 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_IO43), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_IO44), MP_ROM_PTR(&pin_GPIO44) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/tests/feature_check/reverse_ops.py.exp b/ports/espressif/boards/waveshare_esp32_s3_touch_lcd_2_8/sdkconfig old mode 100644 new mode 100755 similarity index 100% rename from tests/feature_check/reverse_ops.py.exp rename to ports/espressif/boards/waveshare_esp32_s3_touch_lcd_2_8/sdkconfig diff --git a/ports/espressif/boards/waveshare_esp32_s3_zero/mpconfigboard.h b/ports/espressif/boards/waveshare_esp32_s3_zero/mpconfigboard.h index da6b7a8a855..47d0b8deae9 100644 --- a/ports/espressif/boards/waveshare_esp32_s3_zero/mpconfigboard.h +++ b/ports/espressif/boards/waveshare_esp32_s3_zero/mpconfigboard.h @@ -11,8 +11,11 @@ #define MICROPY_HW_BOARD_NAME "Waveshare ESP32-S3-Zero" #define MICROPY_HW_MCU_NAME "ESP32S3" -#define MICROPY_HW_NEOPIXEL_ORDER_GRB (1) +#define MICROPY_HW_NEOPIXEL_ORDER (STATUS_NEOPIXEL_ORDER_RGB) #define MICROPY_HW_NEOPIXEL (&pin_GPIO21) #define DEFAULT_UART_BUS_RX (&pin_GPIO44) #define DEFAULT_UART_BUS_TX (&pin_GPIO43) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/waveshare_esp32_s3_zero/mpconfigboard.mk b/ports/espressif/boards/waveshare_esp32_s3_zero/mpconfigboard.mk index e1f616dea12..6e386e70e17 100644 --- a/ports/espressif/boards/waveshare_esp32_s3_zero/mpconfigboard.mk +++ b/ports/espressif/boards/waveshare_esp32_s3_zero/mpconfigboard.mk @@ -13,10 +13,5 @@ CIRCUITPY_ESP_PSRAM_SIZE = 2MB CIRCUITPY_ESP_PSRAM_MODE = qio CIRCUITPY_ESP_PSRAM_FREQ = 80m -CIRCUITPY_ESPCAMERA = 0 -CIRCUITPY_BITMAPFILTER = 0 -CIRCUITPY_CODEOP = 0 -CIRCUITPY_PARALLELDISPLAYBUS = 0 - # Include these Python libraries in firmware. FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel diff --git a/ports/espressif/boards/waveshare_esp32_s3_zero/pins.c b/ports/espressif/boards/waveshare_esp32_s3_zero/pins.c index 868c26be201..15225b1c57c 100644 --- a/ports/espressif/boards/waveshare_esp32_s3_zero/pins.c +++ b/ports/espressif/boards/waveshare_esp32_s3_zero/pins.c @@ -152,8 +152,7 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_D21), MP_ROM_PTR(&pin_GPIO21) }, { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO21) }, - { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, - { MP_ROM_QSTR(MP_QSTR_SPI), MP_ROM_PTR(&board_spi_obj) }, + // UART - using TX RX on silkscreen { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj) } }; MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/espressif/boards/waveshare_esp32s2_pico/mpconfigboard.h b/ports/espressif/boards/waveshare_esp32s2_pico/mpconfigboard.h index 2888af9184a..5875725a00f 100644 --- a/ports/espressif/boards/waveshare_esp32s2_pico/mpconfigboard.h +++ b/ports/espressif/boards/waveshare_esp32s2_pico/mpconfigboard.h @@ -23,3 +23,6 @@ #define DEFAULT_UART_BUS_RX (&pin_GPIO44) #define DEFAULT_UART_BUS_TX (&pin_GPIO43) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/weact_esp32c6_n4/mpconfigboard.mk b/ports/espressif/boards/weact_esp32c6_n4/mpconfigboard.mk index 45309d28904..bdd407ef10d 100644 --- a/ports/espressif/boards/weact_esp32c6_n4/mpconfigboard.mk +++ b/ports/espressif/boards/weact_esp32c6_n4/mpconfigboard.mk @@ -6,7 +6,3 @@ IDF_TARGET = esp32c6 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB - -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 - -CIRCUITPY_AUDIOMP3 = 0 diff --git a/ports/espressif/boards/wemos_lolin32_lite/mpconfigboard.h b/ports/espressif/boards/wemos_lolin32_lite/mpconfigboard.h index 6a9f0357156..fa0ed02f676 100644 --- a/ports/espressif/boards/wemos_lolin32_lite/mpconfigboard.h +++ b/ports/espressif/boards/wemos_lolin32_lite/mpconfigboard.h @@ -20,3 +20,6 @@ // UART pins attached to the USB-serial converter chip #define CIRCUITPY_CONSOLE_UART_TX (&pin_GPIO1) #define CIRCUITPY_CONSOLE_UART_RX (&pin_GPIO3) + +// Reduce wifi.radio.tx_power due to the antenna design of this board +#define CIRCUITPY_WIFI_DEFAULT_TX_POWER (15) diff --git a/ports/espressif/boards/wemos_lolin32_lite/mpconfigboard.mk b/ports/espressif/boards/wemos_lolin32_lite/mpconfigboard.mk index 3c456881819..83e2289e729 100644 --- a/ports/espressif/boards/wemos_lolin32_lite/mpconfigboard.mk +++ b/ports/espressif/boards/wemos_lolin32_lite/mpconfigboard.mk @@ -6,7 +6,3 @@ IDF_TARGET = esp32 CIRCUITPY_ESP_FLASH_MODE = qio CIRCUITPY_ESP_FLASH_FREQ = 80m CIRCUITPY_ESP_FLASH_SIZE = 4MB - -CIRCUITPY_ESPCAMERA = 0 - -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT = 1 diff --git a/ports/espressif/boards/xteink_x4/board.c b/ports/espressif/boards/xteink_x4/board.c new file mode 100644 index 00000000000..b782d1b4a80 --- /dev/null +++ b/ports/espressif/boards/xteink_x4/board.c @@ -0,0 +1,125 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 microDev +// SPDX-FileCopyrightText: Copyright (c) 2021 skieast/Bruce Segal +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" + +#include "mpconfigboard.h" +#include "shared-bindings/busio/SPI.h" +#include "shared-bindings/fourwire/FourWire.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-module/displayio/__init__.h" +#include "supervisor/shared/board.h" + +#define DELAY 0x80 + +// SSD1677 controller driving a GDEQ0426T82 4.26" 800x480 E-Ink display. + +const uint8_t ssd1677_display_start_sequence[] = { + // Software Reset + 0x12, DELAY, 0x00, 0x14, + + // Temperature Sensor Control (use internal sensor) + 0x18, 0x00, 0x01, 0x80, + + // Booster Soft Start + 0x0C, 0x00, 0x05, 0xAE, 0xC7, 0xC3, 0xC0, 0x40, + + // Driver Output Control: 480 gates, GD=0, SM=1, TB=0 = 0x02 + 0x01, 0x00, 0x03, 0xDF, 0x01, 0x02, + + // Data Entry Mode: X increment, Y decrement = 0x01 + 0x11, 0x00, 0x01, 0x01, + + // Border Waveform Control + 0x3C, 0x00, 0x01, 0x01, + + // Set RAM X Address Start/End: 0 to 799 + 0x44, 0x00, 0x04, 0x00, 0x00, 0x1F, 0x03, + + // Set RAM Y Address Start/End: 479 down to 0 + 0x45, 0x00, 0x04, 0xDF, 0x01, 0x00, 0x00, + + // Set RAM X Counter to 0 + 0x4E, 0x00, 0x02, 0x00, 0x00, + + // Set RAM Y Counter to 479 + 0x4F, 0x00, 0x02, 0xDF, 0x01, + + // Auto Write BW RAM (clear to white) + 0x46, DELAY, 0x01, 0xF7, 0xFF, + + // Display Update Control 1: bypass RED + 0x21, 0x00, 0x02, 0x40, 0x00, + + // Display Update Control 2: full refresh with OTP LUT + 0x22, 0x00, 0x01, 0xF7, +}; + +const uint8_t ssd1677_display_stop_sequence[] = { + 0x22, 0x00, 0x01, 0x83, + 0x20, 0x00, 0x00, + 0x10, 0x00, 0x01, 0x01, +}; + +const uint8_t ssd1677_display_refresh_sequence[] = { + 0x20, 0x00, 0x00, +}; + +void board_init(void) { + fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; + busio_spi_obj_t *spi = &bus->inline_bus; + common_hal_busio_spi_construct(spi, &pin_GPIO8, &pin_GPIO10, NULL, false); + + bus->base.type = &fourwire_fourwire_type; + common_hal_fourwire_fourwire_construct(bus, + spi, + MP_OBJ_FROM_PTR(&pin_GPIO4), + MP_OBJ_FROM_PTR(&pin_GPIO21), + MP_OBJ_FROM_PTR(&pin_GPIO5), + 40000000, + 0, + 0); + + epaperdisplay_epaperdisplay_obj_t *display = &allocate_display()->epaper_display; + display->base.type = &epaperdisplay_epaperdisplay_type; + + epaperdisplay_construct_args_t args = EPAPERDISPLAY_CONSTRUCT_ARGS_DEFAULTS; + args.bus = bus; + args.start_sequence = ssd1677_display_start_sequence; + args.start_sequence_len = sizeof(ssd1677_display_start_sequence); + args.stop_sequence = ssd1677_display_stop_sequence; + args.stop_sequence_len = sizeof(ssd1677_display_stop_sequence); + args.width = 800; + args.height = 480; + args.ram_width = 800; + args.ram_height = 480; + args.rotation = 0; + args.write_black_ram_command = 0x24; + args.black_bits_inverted = false; + args.refresh_sequence = ssd1677_display_refresh_sequence; + args.refresh_sequence_len = sizeof(ssd1677_display_refresh_sequence); + args.refresh_time = 1.6; + args.busy_pin = &pin_GPIO6; + args.busy_state = true; + args.seconds_per_frame = 5.0; + args.grayscale = false; + args.two_byte_sequence_length = true; + args.address_little_endian = true; + common_hal_epaperdisplay_epaperdisplay_construct(display, &args); +} + +void board_deinit(void) { + epaperdisplay_epaperdisplay_obj_t *display = &displays[0].epaper_display; + if (display->base.type == &epaperdisplay_epaperdisplay_type) { + while (common_hal_epaperdisplay_epaperdisplay_get_busy(display)) { + RUN_BACKGROUND_TASKS; + } + } + common_hal_displayio_release_displays(); +} + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/espressif/boards/xteink_x4/mpconfigboard.h b/ports/espressif/boards/xteink_x4/mpconfigboard.h new file mode 100644 index 00000000000..5d4bb372228 --- /dev/null +++ b/ports/espressif/boards/xteink_x4/mpconfigboard.h @@ -0,0 +1,18 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 microDev +// SPDX-FileCopyrightText: Copyright (c) 2021 skieast/Bruce Segal +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Board setup +#define MICROPY_HW_BOARD_NAME "Xteink X4" +#define MICROPY_HW_MCU_NAME "ESP32-C3" + +#define CIRCUITPY_BOARD_SPI (1) +#define CIRCUITPY_BOARD_SPI_PIN {{.clock = &pin_GPIO8, .mosi = &pin_GPIO10, .miso = &pin_GPIO7}} + +// For entering safe mode +#define CIRCUITPY_BOOT_BUTTON (&pin_GPIO3) diff --git a/ports/espressif/boards/xteink_x4/mpconfigboard.mk b/ports/espressif/boards/xteink_x4/mpconfigboard.mk new file mode 100644 index 00000000000..8668aad1818 --- /dev/null +++ b/ports/espressif/boards/xteink_x4/mpconfigboard.mk @@ -0,0 +1,29 @@ +CIRCUITPY_CREATOR_ID = 0x0EEE0000 +CIRCUITPY_CREATION_ID = 0x00C30001 + +IDF_TARGET = esp32c3 + +CIRCUITPY_ESP_FLASH_MODE = dio +CIRCUITPY_ESP_FLASH_FREQ = 40m +CIRCUITPY_ESP_FLASH_SIZE = 16MB + +CIRCUITPY_ESP_USB_SERIAL_JTAG = 1 + +CIRCUITPY_PARALLELDISPLAYBUS = 0 +CIRCUITPY_RGBMATRIX = 0 +CIRCUITPY_AUDIOBUSIO = 0 +CIRCUITPY_AUDIOCORE = 0 +CIRCUITPY_AUDIOMIXER = 0 +CIRCUITPY_AUDIOMP3 = 0 +CIRCUITPY_CAMERA = 0 +CIRCUITPY_CANIO = 0 +CIRCUITPY_DOTCLOCKFRAMEBUFFER = 0 +CIRCUITPY_KEYPAD = 0 +CIRCUITPY_ROTARYIO = 0 +CIRCUITPY_USB_HID = 0 +CIRCUITPY_USB_MIDI = 0 +CIRCUITPY_ULAB = 0 +CIRCUITPY_PULSEIO = 0 +CIRCUITPY_PWMIO = 0 +CIRCUITPY_RAINBOWIO = 0 +CIRCUITPY_SYNTHIO = 0 diff --git a/ports/espressif/boards/xteink_x4/pins.c b/ports/espressif/boards/xteink_x4/pins.c new file mode 100644 index 00000000000..6b8232d4cb3 --- /dev/null +++ b/ports/espressif/boards/xteink_x4/pins.c @@ -0,0 +1,52 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 microDev +// SPDX-FileCopyrightText: Copyright (c) 2021 skieast/Bruce Segal +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +#include "shared-module/displayio/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { MP_ROM_QSTR(MP_QSTR_BUTTON), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_BOOT0), MP_ROM_PTR(&pin_GPIO3) }, + + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_GPIO0) }, + + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON_ADC_1), MP_ROM_PTR(&pin_GPIO1) }, + + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON_ADC_2), MP_ROM_PTR(&pin_GPIO2) }, + + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_D20), MP_ROM_PTR(&pin_GPIO20) }, + + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_EPD_MOSI), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_GPIO10) }, + + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_EPD_SCK), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_GPIO8) }, + + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_SD_MISO), MP_ROM_PTR(&pin_GPIO7) }, + + { MP_ROM_QSTR(MP_QSTR_SD_CS), MP_ROM_PTR(&pin_GPIO12) }, + + { MP_ROM_QSTR(MP_QSTR_EPD_BUSY), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_EPD_RESET), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_EPD_DC), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_EPD_CS), MP_ROM_PTR(&pin_GPIO21) }, + + { MP_ROM_QSTR(MP_QSTR_SPI), MP_ROM_PTR(&board_spi_obj) }, + + { MP_ROM_QSTR(MP_QSTR_DISPLAY), MP_ROM_PTR(&displays[0].epaper_display)}, + +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/espressif/boards/xteink_x4/sdkconfig b/ports/espressif/boards/xteink_x4/sdkconfig new file mode 100644 index 00000000000..e9628662160 --- /dev/null +++ b/ports/espressif/boards/xteink_x4/sdkconfig @@ -0,0 +1,14 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Component config +# +# +# LWIP +# +# end of LWIP + +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/boards/yoto_mini_2024/board.c b/ports/espressif/boards/yoto_mini_2024/board.c new file mode 100644 index 00000000000..c5deaeeebd5 --- /dev/null +++ b/ports/espressif/boards/yoto_mini_2024/board.c @@ -0,0 +1,205 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "board.h" + +#include "supervisor/board.h" + +#include "extmod/vfs_fat.h" + +#include "py/mpstate.h" + +#include "shared-bindings/board/__init__.h" +#include "shared-bindings/busio/I2C.h" +#include "shared-bindings/busio/SPI.h" +#include "shared-bindings/fourwire/FourWire.h" +#include "shared-bindings/i2cioexpander/IOExpander.h" +#include "shared-bindings/i2cioexpander/IOPin.h" +#include "shared-bindings/sdioio/SDCard.h" +#include "shared-module/board/__init__.h" +#include "shared-module/displayio/__init__.h" +#include "shared-module/displayio/mipi_constants.h" + +#include "supervisor/filesystem.h" + +static sdioio_sdcard_obj_t sdmmc; +static mp_vfs_mount_t _sdcard_vfs; +static fs_user_mount_t _sdcard_usermount; +static i2cioexpander_ioexpander_obj_t ioexpander; + +#define DELAY 0x80 + +// This is a GC9306. +uint8_t display_init_sequence[] = { + 0xfe, 0, + 0xef, 0, + + // // sw reset + // 0x01, 0 | DELAY, 150, + // normal display mode on + // 0x13, 0, + // display and color format settings + 0x36, 1, 0x48, // Memory access control. mini does 0x48, not 0, 2, 3, 4 or 6 + 0x3A, 1 | DELAY, 0x55, 10, // COLMOD. mini does 0x06 + 0xa4, 2, 0x44, 0x44, // power control 7 + 0xa5, 2, 0x42, 0x42, + 0xaa, 2, 0x88, 0x88, + 0xae, 1, 0x2b, + 0xe8, 2, 0x22, 0x0b, // frame rate + 0xe3, 2, 0x01, 0x10, + 0xff, 1, 0x61, + 0xac, 1, 0x00, + 0xad, 1, 0x33, + 0xaf, 1, 0x77, + 0xa6, 2, 0x1c, 0x1c, // power control 2 + 0xa7, 2, 0x1c, 0x1c, // power control 3 + 0xa8, 2, 0x10, 0x10, // power control 4 + 0xa9, 2, 0x0d, 0x0d, // power control 5 + 0xf0, 6, 0x02, 0x01, 0x00, 0x00, 0x00, 0x05, // Gamma settings + 0xf1, 6, 0x01, 0x02, 0x00, 0x06, 0x10, 0x0e, + 0xf2, 6, 0x03, 0x11, 0x28, 0x02, 0x00, 0x48, + 0xf3, 6, 0x0c, 0x11, 0x30, 0x00, 0x00, 0x46, + 0xf4, 6, 0x05, 0x1f, 0x1f, 0x36, 0x30, 0x0f, + 0xf5, 6, 0x04, 0x1d, 0x1a, 0x38, 0x3f, 0x0f, // Last gamma setting + 0x35, 1, 0x00, + 0x44, 2, 0x00, 0x0a, // set tear scan line + 0x21, 0, // display inversion on + // sleep out + 0x11, 0 | DELAY, 255, + + // display on + 0x29, 0 | DELAY, 255, +}; + +void board_init(void) { + // Wait for everything to start + mp_hal_delay_ms(300); + + // Initialize the board's peripherals here. 0 means instance 0 of the boards I2C buses. + busio_i2c_obj_t *i2c = MP_OBJ_TO_PTR(common_hal_board_create_i2c(0)); + // The IO expander uses this bus after code.py ends. + board_i2c_retain(0); + + // Initialize the IOExpander + ioexpander.base.type = &i2cioexpander_ioexpander_type; + common_hal_i2cioexpander_ioexpander_construct( + &ioexpander, + MP_OBJ_FROM_PTR(i2c), + 0x20, // I2C address + 16, // Number of pins + 2, // Output register + 0, // Input register + 6); // Direction register + + board_set(MP_QSTR_IOEXPANDER, MP_OBJ_FROM_PTR(&ioexpander)); + board_set(MP_QSTR_PLUG_STATUS, ioexpander.pins->items[8 + 5]); + board_set(MP_QSTR_CHARGE_STATUS, ioexpander.pins->items[8 + 7]); + board_set(MP_QSTR_POWER_BUTTON, ioexpander.pins->items[8 + 3]); + board_set(MP_QSTR_ENC1_BUTTON, ioexpander.pins->items[5]); + board_set(MP_QSTR_ENC2_BUTTON, ioexpander.pins->items[4]); + board_set(MP_QSTR_HEADPHONE_DETECT, ioexpander.pins->items[8 + 1]); + board_set(MP_QSTR_PACTRL, ioexpander.pins->items[6]); + board_set(MP_QSTR_DISPLAY_CS, ioexpander.pins->items[0]); + board_set(MP_QSTR_DISPLAY_DC, ioexpander.pins->items[1]); + board_set(MP_QSTR_DISPLAY_RESET, ioexpander.pins->items[2]); + + board_set(MP_QSTR_LEVEL_CONVERTER, ioexpander.pins->items[3]); + board_set(MP_QSTR_LEVEL_POWER_ENABLE, ioexpander.pins->items[8 + 4]); + board_set(MP_QSTR_LEVEL_VINHOLD, ioexpander.pins->items[8 + 6]); + + board_set(MP_QSTR_TILT, ioexpander.pins->items[8 + 2]); + + // Only on some variants + board_set(MP_QSTR_RTC_INT, ioexpander.pins->items[7]); + + common_hal_i2cioexpander_iopin_switch_to_output(MP_OBJ_TO_PTR(ioexpander.pins->items[2]), true, DRIVE_MODE_PUSH_PULL); + common_hal_i2cioexpander_iopin_switch_to_output(MP_OBJ_TO_PTR(ioexpander.pins->items[3]), true, DRIVE_MODE_PUSH_PULL); + common_hal_i2cioexpander_iopin_switch_to_output(MP_OBJ_TO_PTR(ioexpander.pins->items[6]), true, DRIVE_MODE_PUSH_PULL); + common_hal_i2cioexpander_iopin_switch_to_output(MP_OBJ_TO_PTR(ioexpander.pins->items[14]), true, DRIVE_MODE_PUSH_PULL); + + busio_spi_obj_t *spi = common_hal_board_create_spi(0); + fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; + bus->base.type = &fourwire_fourwire_type; + + common_hal_fourwire_fourwire_construct( + bus, + spi, + ioexpander.pins->items[1], // DC + ioexpander.pins->items[0], // CS + ioexpander.pins->items[2], // RST + 25000000, // baudrate + 0, // polarity + 0 // phase + ); + busdisplay_busdisplay_obj_t *display = &allocate_display()->display; + display->base.type = &busdisplay_busdisplay_type; + + common_hal_busdisplay_busdisplay_construct( + display, + bus, + 240, // width (after rotation) + 240, // height (after rotation) + 0, // column start + 0, // row start + 0, // 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 + display_init_sequence, + sizeof(display_init_sequence), + &pin_GPIO26, // backlight pin + NO_BRIGHTNESS_COMMAND, + 1.0f, // brightness + false, // single_byte_bounds + false, // data_as_commands + true, // auto_refresh + 60, // native_frames_per_second + true, // backlight_on_high + false, // SH1107_addressing + 50000 // backlight pwm frequency + ); + + digitalinout_result_t sd_enable_res = common_hal_i2cioexpander_iopin_switch_to_output(MP_OBJ_TO_PTR(ioexpander.pins->items[12]), false, DRIVE_MODE_PUSH_PULL); + if (sd_enable_res != DIGITALINOUT_OK) { + mp_printf(&mp_plat_print, "Failed to initialize IOExpander. Skipping SD card\n"); + return; + } + + sdmmc.base.type = &sdioio_SDCard_type; + const mcu_pin_obj_t *data_pins[4] = {MP_ROM_PTR(&pin_GPIO2), MP_ROM_PTR(&pin_GPIO4), MP_ROM_PTR(&pin_GPIO12), MP_ROM_PTR(&pin_GPIO13)}; + common_hal_sdioio_sdcard_construct(&sdmmc, MP_ROM_PTR(&pin_GPIO14), MP_ROM_PTR(&pin_GPIO15), 4, data_pins, 25 * 1000000); + + fs_user_mount_t *vfs = &_sdcard_usermount; + vfs->base.type = &mp_fat_vfs_type; + vfs->fatfs.drv = vfs; + + // Initialise underlying block device + vfs->blockdev.block_size = FF_MIN_SS; // default, will be populated by call to MP_BLOCKDEV_IOCTL_BLOCK_SIZE + mp_vfs_blockdev_init(&vfs->blockdev, &sdmmc); + + // mount the block device so the VFS methods can be used + FRESULT res = f_mount(&vfs->fatfs); + if (res != FR_OK) { + common_hal_sdioio_sdcard_deinit(&sdmmc); + return; + } + + filesystem_set_concurrent_write_protection((supervisor_vfs_t *)vfs, true); + filesystem_set_writable_by_usb((supervisor_vfs_t *)vfs, false); + + mp_vfs_mount_t *sdcard_vfs = &_sdcard_vfs; + sdcard_vfs->str = "/sd"; + sdcard_vfs->len = 3; + sdcard_vfs->obj = MP_OBJ_FROM_PTR(&_sdcard_usermount); + sdcard_vfs->next = MP_STATE_VM(vfs_mount_table); + MP_STATE_VM(vfs_mount_table) = sdcard_vfs; +} diff --git a/ports/espressif/boards/yoto_mini_2024/board.h b/ports/espressif/boards/yoto_mini_2024/board.h new file mode 100644 index 00000000000..1e40b62b047 --- /dev/null +++ b/ports/espressif/boards/yoto_mini_2024/board.h @@ -0,0 +1,3 @@ +#include "py/obj.h" + +extern void board_set(qstr key, mp_obj_t value); diff --git a/ports/espressif/boards/yoto_mini_2024/mpconfigboard.h b/ports/espressif/boards/yoto_mini_2024/mpconfigboard.h new file mode 100644 index 00000000000..4fcc2afaae8 --- /dev/null +++ b/ports/espressif/boards/yoto_mini_2024/mpconfigboard.h @@ -0,0 +1,28 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2022 Dan Halbert for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Micropython setup + +#define MICROPY_HW_BOARD_NAME "Yoto Mini 2024" +#define MICROPY_HW_MCU_NAME "ESP32" + +#define CIRCUITPY_MUTABLE_BOARD (1) + +#define CIRCUITPY_BOARD_I2C (1) +#define CIRCUITPY_BOARD_I2C_PIN {{.scl = &pin_GPIO25, .sda = &pin_GPIO21}} +#define CIRCUITPY_BOARD_I2C_SPEED (400000) + +#define CIRCUITPY_BOARD_SPI (1) +#define CIRCUITPY_BOARD_SPI_PIN {{.clock = &pin_GPIO23, .mosi = &pin_GPIO22, .miso = NULL}} + +#define CIRCUITPY_BOARD_UART (1) +#define CIRCUITPY_BOARD_UART_PIN {{.tx = &pin_GPIO17, .rx = &pin_GPIO16}} + +// UART pins attached to the USB-serial converter chip +#define CIRCUITPY_CONSOLE_UART_TX (&pin_GPIO1) +#define CIRCUITPY_CONSOLE_UART_RX (&pin_GPIO3) diff --git a/ports/espressif/boards/yoto_mini_2024/mpconfigboard.mk b/ports/espressif/boards/yoto_mini_2024/mpconfigboard.mk new file mode 100644 index 00000000000..356e7015a04 --- /dev/null +++ b/ports/espressif/boards/yoto_mini_2024/mpconfigboard.mk @@ -0,0 +1,14 @@ +CIRCUITPY_CREATOR_ID = 0x40100000 +CIRCUITPY_CREATION_ID = 0x00320002 + +IDF_TARGET = esp32 + +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m +CIRCUITPY_ESP_FLASH_SIZE = 8MB + +CIRCUITPY_ESP_PSRAM_SIZE = 8MB +CIRCUITPY_ESP_PSRAM_MODE = qio +CIRCUITPY_ESP_PSRAM_FREQ = 40m + +CIRCUITPY_I2CIOEXPANDER = 1 diff --git a/ports/espressif/boards/yoto_mini_2024/pins.c b/ports/espressif/boards/yoto_mini_2024/pins.c new file mode 100644 index 00000000000..d4ff3b4863f --- /dev/null +++ b/ports/espressif/boards/yoto_mini_2024/pins.c @@ -0,0 +1,79 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT +// + +#include "board.h" + +#include "shared-bindings/board/__init__.h" +#include "shared-module/displayio/__init__.h" + +static mp_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_MUTABLE_BOARD_DICT_STANDARD_ITEMS + + // External pins are in silkscreen order, from top to bottom, left side, then right side + { MP_ROM_QSTR(MP_QSTR_ENC1A), MP_OBJ_FROM_PTR(&pin_GPIO39) }, + { MP_ROM_QSTR(MP_QSTR_ENC1B), MP_OBJ_FROM_PTR(&pin_GPIO35) }, + + { MP_ROM_QSTR(MP_QSTR_ENC2A), MP_OBJ_FROM_PTR(&pin_GPIO36) }, + { MP_ROM_QSTR(MP_QSTR_ENC2B), MP_OBJ_FROM_PTR(&pin_GPIO27) }, + + { MP_ROM_QSTR(MP_QSTR_SCL), MP_OBJ_FROM_PTR(&pin_GPIO25) }, + { MP_ROM_QSTR(MP_QSTR_SDA), MP_OBJ_FROM_PTR(&pin_GPIO21) }, + + { MP_ROM_QSTR(MP_QSTR_DISPLAY_SCK), MP_OBJ_FROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_DISPLAY_MOSI), MP_OBJ_FROM_PTR(&pin_GPIO22) }, + + { MP_ROM_QSTR(MP_QSTR_NFC_IN), MP_OBJ_FROM_PTR(&pin_GPIO32) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_OBJ_FROM_PTR(&pin_GPIO32) }, + { MP_ROM_QSTR(MP_QSTR_NFC_OUT), MP_OBJ_FROM_PTR(&pin_GPIO33) }, + { MP_ROM_QSTR(MP_QSTR_TX), MP_OBJ_FROM_PTR(&pin_GPIO33) }, + + { MP_ROM_QSTR(MP_QSTR_I2S_MCLK), MP_OBJ_FROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_I2S_BIT_CLOCK), MP_OBJ_FROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_I2S_BCLK), MP_OBJ_FROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_I2S_WORD_SELECT), MP_OBJ_FROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_I2S_LRCLK), MP_OBJ_FROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_I2S_DOUT), MP_OBJ_FROM_PTR(&pin_GPIO19) }, + + { MP_ROM_QSTR(MP_QSTR_IOEXPANDER_INT), MP_OBJ_FROM_PTR(&pin_GPIO34) }, + + { MP_ROM_QSTR(MP_QSTR_DISPLAY), MP_OBJ_FROM_PTR(&displays[0].display)}, + { MP_ROM_QSTR(MP_QSTR_I2C), MP_OBJ_FROM_PTR(&board_i2c_obj) }, + + // Filled in by board_init() + { MP_ROM_QSTR(MP_QSTR_IOEXPANDER), mp_const_none }, + { MP_ROM_QSTR(MP_QSTR_PLUG_STATUS), mp_const_none }, + { MP_ROM_QSTR(MP_QSTR_CHARGE_STATUS), mp_const_none }, + { MP_ROM_QSTR(MP_QSTR_POWER_BUTTON), mp_const_none }, + { MP_ROM_QSTR(MP_QSTR_ENC1_BUTTON), mp_const_none }, + { MP_ROM_QSTR(MP_QSTR_ENC2_BUTTON), mp_const_none }, + { MP_ROM_QSTR(MP_QSTR_HEADPHONE_DETECT), mp_const_none }, + { MP_ROM_QSTR(MP_QSTR_PACTRL), mp_const_none }, + { MP_ROM_QSTR(MP_QSTR_DISPLAY_CS), mp_const_none }, + { MP_ROM_QSTR(MP_QSTR_DISPLAY_DC), mp_const_none }, + { MP_ROM_QSTR(MP_QSTR_DISPLAY_RESET), mp_const_none }, + + { MP_ROM_QSTR(MP_QSTR_LEVEL_CONVERTER), mp_const_none }, + { MP_ROM_QSTR(MP_QSTR_LEVEL_POWER_ENABLE), mp_const_none }, + { MP_ROM_QSTR(MP_QSTR_LEVEL_VINHOLD), mp_const_none }, + + { MP_ROM_QSTR(MP_QSTR_TILT), mp_const_none }, + + // Only on some variants + { MP_ROM_QSTR(MP_QSTR_RTC_INT), mp_const_none }, + +}; +MP_DEFINE_MUTABLE_DICT(board_module_globals, board_module_globals_table); + +void board_set(qstr q, mp_obj_t value) { + mp_obj_t key = MP_OBJ_NEW_QSTR(q); + for (size_t i = 0; i < MP_ARRAY_SIZE(board_module_globals_table); i++) { + if (board_module_globals_table[i].key == key) { + board_module_globals_table[i].value = value; + return; + } + } +} diff --git a/tests/feature_check/set_check.py.exp b/ports/espressif/boards/yoto_mini_2024/sdkconfig similarity index 100% rename from tests/feature_check/set_check.py.exp rename to ports/espressif/boards/yoto_mini_2024/sdkconfig diff --git a/ports/espressif/boards/yoto_player_v3/board.c b/ports/espressif/boards/yoto_player_v3/board.c new file mode 100644 index 00000000000..3c473d1182d --- /dev/null +++ b/ports/espressif/boards/yoto_player_v3/board.c @@ -0,0 +1,150 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "board.h" + +#include "supervisor/board.h" + +#include "extmod/vfs_fat.h" + +#include "py/mpstate.h" + +#include "shared-bindings/board/__init__.h" +#include "shared-bindings/busio/I2C.h" +#include "shared-bindings/i2cioexpander/IOExpander.h" +#include "shared-bindings/i2cioexpander/IOPin.h" +#include "shared-bindings/sdioio/SDCard.h" +#include "shared-module/board/__init__.h" + +#include "supervisor/filesystem.h" + +static sdioio_sdcard_obj_t sdmmc; +static mp_vfs_mount_t _sdcard_vfs; +static fs_user_mount_t _sdcard_usermount; +static i2cioexpander_ioexpander_obj_t ioexpander0; // First chip (p0/p1) +static i2cioexpander_ioexpander_obj_t ioexpander1; // Second chip (p2/p3) + +void board_init(void) { + // Wait for everything to start + mp_hal_delay_ms(300); + + // Initialize the board's peripherals here. 0 means instance 0 of the boards I2C buses. + busio_i2c_obj_t *i2c = MP_OBJ_TO_PTR(common_hal_board_create_i2c(0)); + // The IO expanders use this bus after code.py ends. + board_i2c_retain(0); + + // Initialize the IOExpanders + // V3/V3-E uses two PI4IOE5V6416 chips (16 pins each) + // First chip (0x20): p0 (pins 0-7), p1 (pins 8-15) + ioexpander0.base.type = &i2cioexpander_ioexpander_type; + common_hal_i2cioexpander_ioexpander_construct( + &ioexpander0, + MP_OBJ_FROM_PTR(i2c), + 0x20, // I2C address for first chip + 16, // Number of pins + 2, // Output register + 0, // Input register + 6); // Direction register + + // Second chip (0x21): p2 (pins 0-7), p3 (pins 8-15) + ioexpander1.base.type = &i2cioexpander_ioexpander_type; + common_hal_i2cioexpander_ioexpander_construct( + &ioexpander1, + MP_OBJ_FROM_PTR(i2c), + 0x21, // I2C address for second chip + 16, // Number of pins + 2, // Output register + 0, // Input register + 6); // Direction register + + board_set(MP_QSTR_IOEXPANDER0, MP_OBJ_FROM_PTR(&ioexpander0)); + board_set(MP_QSTR_IOEXPANDER1, MP_OBJ_FROM_PTR(&ioexpander1)); + + // Battery and charging (from first chip - p0/p1) + board_set(MP_QSTR_BATTERY_ALERT, ioexpander0.pins->items[6]); // IOX.0.6 + board_set(MP_QSTR_QI_STATUS, ioexpander0.pins->items[7]); // IOX.0.7 + board_set(MP_QSTR_QI_I2C_INT, ioexpander0.pins->items[0]); // IOX.0.0 + board_set(MP_QSTR_USB_STATUS, ioexpander0.pins->items[8 + 0]); // IOX.1.0 + board_set(MP_QSTR_CHARGE_STATUS, ioexpander0.pins->items[8 + 4]); // IOX.1.4 + + // Buttons (from first chip - p0/p1) + board_set(MP_QSTR_POWER_BUTTON, ioexpander0.pins->items[8 + 3]); // IOX.1.3 + board_set(MP_QSTR_ENC1_BUTTON, ioexpander0.pins->items[5]); // IOX.0.5 + board_set(MP_QSTR_ENC2_BUTTON, ioexpander0.pins->items[4]); // IOX.0.4 + + // Audio (from first chip - p0/p1 and second chip - p2/p3) + board_set(MP_QSTR_HEADPHONE_DETECT, ioexpander0.pins->items[8 + 1]); // IOX.1.1 + board_set(MP_QSTR_PACTRL, ioexpander1.pins->items[4]); // IOX.2.4 + + // Display - V3/V3-E uses ht16d35x with 4 CS lines (from second chip - p2) + board_set(MP_QSTR_DISPLAY_CS0, ioexpander1.pins->items[0]); // IOX.2.0 + board_set(MP_QSTR_DISPLAY_CS1, ioexpander1.pins->items[1]); // IOX.2.1 + board_set(MP_QSTR_DISPLAY_CS2, ioexpander1.pins->items[2]); // IOX.2.2 + board_set(MP_QSTR_DISPLAY_CS3, ioexpander1.pins->items[3]); // IOX.2.3 + + // Power control (from second chip - p2/p3) + board_set(MP_QSTR_LEVEL_CONVERTER, ioexpander1.pins->items[8 + 0]); // IOX.3.0 + board_set(MP_QSTR_LEVEL_POWER_ENABLE, ioexpander1.pins->items[5]); // IOX.2.5 + board_set(MP_QSTR_LEVEL_VINHOLD, ioexpander1.pins->items[8 + 1]); // IOX.3.1 + board_set(MP_QSTR_LEVEL_VOUTEN, ioexpander1.pins->items[8 + 3]); // IOX.3.3 + + // Sensors (from first chip - p0/p1) + board_set(MP_QSTR_TILT, ioexpander0.pins->items[8 + 2]); // IOX.1.2 + board_set(MP_QSTR_RTC_INT, ioexpander0.pins->items[1]); // IOX.0.1 + + // Qi charging control (V3-E, from second chip - p2/p3) + board_set(MP_QSTR_QI_CHARGE_ENABLE, ioexpander1.pins->items[6]); // IOX.2.6 + board_set(MP_QSTR_USB_CHARGE_ENABLE, ioexpander1.pins->items[7]); // IOX.2.7 + board_set(MP_QSTR_QI_ENABLE_5W, ioexpander1.pins->items[8 + 5]); // IOX.3.5 + + // Output pin 3 high. Not clear why. + common_hal_i2cioexpander_iopin_switch_to_output(MP_OBJ_TO_PTR(ioexpander0.pins->items[3]), true, DRIVE_MODE_PUSH_PULL); + + // Initialize output pins + common_hal_i2cioexpander_iopin_switch_to_output(MP_OBJ_TO_PTR(ioexpander1.pins->items[0]), true, DRIVE_MODE_PUSH_PULL); // DISPLAY_CS0 (IOX.2.0) + common_hal_i2cioexpander_iopin_switch_to_output(MP_OBJ_TO_PTR(ioexpander1.pins->items[1]), true, DRIVE_MODE_PUSH_PULL); // DISPLAY_CS1 (IOX.2.1) + common_hal_i2cioexpander_iopin_switch_to_output(MP_OBJ_TO_PTR(ioexpander1.pins->items[2]), true, DRIVE_MODE_PUSH_PULL); // DISPLAY_CS2 (IOX.2.2) + common_hal_i2cioexpander_iopin_switch_to_output(MP_OBJ_TO_PTR(ioexpander1.pins->items[3]), true, DRIVE_MODE_PUSH_PULL); // DISPLAY_CS3 (IOX.2.3) + common_hal_i2cioexpander_iopin_switch_to_output(MP_OBJ_TO_PTR(ioexpander1.pins->items[4]), true, DRIVE_MODE_PUSH_PULL); // PACTRL (IOX.2.4) + common_hal_i2cioexpander_iopin_switch_to_output(MP_OBJ_TO_PTR(ioexpander1.pins->items[5]), false, DRIVE_MODE_PUSH_PULL); // LEVEL_POWER_ENABLE (IOX.2.5) + common_hal_i2cioexpander_iopin_switch_to_output(MP_OBJ_TO_PTR(ioexpander1.pins->items[6]), true, DRIVE_MODE_PUSH_PULL); // QI_CHARGE_ENABLE + common_hal_i2cioexpander_iopin_switch_to_output(MP_OBJ_TO_PTR(ioexpander1.pins->items[7]), false, DRIVE_MODE_PUSH_PULL); // USB_CHARGE_ENABLE + common_hal_i2cioexpander_iopin_switch_to_output(MP_OBJ_TO_PTR(ioexpander1.pins->items[8 + 0]), true, DRIVE_MODE_PUSH_PULL); // LEVEL_CONVERTER (IOX.3.0) + common_hal_i2cioexpander_iopin_switch_to_output(MP_OBJ_TO_PTR(ioexpander1.pins->items[8 + 1]), true, DRIVE_MODE_PUSH_PULL); // VINHOLD (IOX.3.1) + common_hal_i2cioexpander_iopin_switch_to_output(MP_OBJ_TO_PTR(ioexpander1.pins->items[8 + 3]), true, DRIVE_MODE_PUSH_PULL); // VOUTEN (IOX.3.3) + common_hal_i2cioexpander_iopin_switch_to_output(MP_OBJ_TO_PTR(ioexpander1.pins->items[8 + 5]), false, DRIVE_MODE_PUSH_PULL); // QI_ENABLE_5W (IOX.3.5) + + // Initialize SD card + // V3/V3-E uses single-line SD (sd1 mode), not 4-line (sd4 mode) like Mini + sdmmc.base.type = &sdioio_SDCard_type; + const mcu_pin_obj_t *data_pins[1] = {MP_ROM_PTR(&pin_GPIO2)}; + common_hal_sdioio_sdcard_construct(&sdmmc, MP_ROM_PTR(&pin_GPIO14), MP_ROM_PTR(&pin_GPIO15), 1, data_pins, 25 * 1000000); + + fs_user_mount_t *vfs = &_sdcard_usermount; + vfs->base.type = &mp_fat_vfs_type; + vfs->fatfs.drv = vfs; + + // Initialise underlying block device + vfs->blockdev.block_size = FF_MIN_SS; // default, will be populated by call to MP_BLOCKDEV_IOCTL_BLOCK_SIZE + mp_vfs_blockdev_init(&vfs->blockdev, &sdmmc); + + // mount the block device so the VFS methods can be used + FRESULT res = f_mount(&vfs->fatfs); + if (res != FR_OK) { + common_hal_sdioio_sdcard_deinit(&sdmmc); + return; + } + + filesystem_set_concurrent_write_protection((supervisor_vfs_t *)vfs, true); + filesystem_set_writable_by_usb((supervisor_vfs_t *)vfs, false); + + mp_vfs_mount_t *sdcard_vfs = &_sdcard_vfs; + sdcard_vfs->str = "/sd"; + sdcard_vfs->len = 3; + sdcard_vfs->obj = MP_OBJ_FROM_PTR(&_sdcard_usermount); + sdcard_vfs->next = MP_STATE_VM(vfs_mount_table); + MP_STATE_VM(vfs_mount_table) = sdcard_vfs; +} diff --git a/ports/espressif/boards/yoto_player_v3/board.h b/ports/espressif/boards/yoto_player_v3/board.h new file mode 100644 index 00000000000..1e40b62b047 --- /dev/null +++ b/ports/espressif/boards/yoto_player_v3/board.h @@ -0,0 +1,3 @@ +#include "py/obj.h" + +extern void board_set(qstr key, mp_obj_t value); diff --git a/ports/espressif/boards/yoto_player_v3/mpconfigboard.h b/ports/espressif/boards/yoto_player_v3/mpconfigboard.h new file mode 100644 index 00000000000..1660c4881f9 --- /dev/null +++ b/ports/espressif/boards/yoto_player_v3/mpconfigboard.h @@ -0,0 +1,28 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2022 Dan Halbert for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Micropython setup + +#define MICROPY_HW_BOARD_NAME "Yoto Player V3" +#define MICROPY_HW_MCU_NAME "ESP32" + +#define CIRCUITPY_MUTABLE_BOARD (1) + +#define CIRCUITPY_BOARD_I2C (1) +#define CIRCUITPY_BOARD_I2C_PIN {{.scl = &pin_GPIO25, .sda = &pin_GPIO21}} +#define CIRCUITPY_BOARD_I2C_SPEED (400000) + +#define CIRCUITPY_BOARD_SPI (1) +#define CIRCUITPY_BOARD_SPI_PIN {{.clock = &pin_GPIO23, .mosi = &pin_GPIO22, .miso = &pin_GPIO26}} + +#define CIRCUITPY_BOARD_UART (1) +#define CIRCUITPY_BOARD_UART_PIN {{.tx = &pin_GPIO17, .rx = &pin_GPIO16}} + +// UART pins attached to the USB-serial converter chip +#define CIRCUITPY_CONSOLE_UART_TX (&pin_GPIO1) +#define CIRCUITPY_CONSOLE_UART_RX (&pin_GPIO3) diff --git a/ports/espressif/boards/yoto_player_v3/mpconfigboard.mk b/ports/espressif/boards/yoto_player_v3/mpconfigboard.mk new file mode 100644 index 00000000000..a1b940316c4 --- /dev/null +++ b/ports/espressif/boards/yoto_player_v3/mpconfigboard.mk @@ -0,0 +1,14 @@ +CIRCUITPY_CREATOR_ID = 0x40100000 +CIRCUITPY_CREATION_ID = 0x00320001 + +IDF_TARGET = esp32 + +CIRCUITPY_ESP_FLASH_MODE = qio +CIRCUITPY_ESP_FLASH_FREQ = 80m +CIRCUITPY_ESP_FLASH_SIZE = 8MB + +CIRCUITPY_ESP_PSRAM_SIZE = 8MB +CIRCUITPY_ESP_PSRAM_MODE = qio +CIRCUITPY_ESP_PSRAM_FREQ = 40m + +CIRCUITPY_I2CIOEXPANDER = 1 diff --git a/ports/espressif/boards/yoto_player_v3/pins.c b/ports/espressif/boards/yoto_player_v3/pins.c new file mode 100644 index 00000000000..0862a020fdf --- /dev/null +++ b/ports/espressif/boards/yoto_player_v3/pins.c @@ -0,0 +1,104 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT +// + +#include "board.h" + +#include "shared-bindings/board/__init__.h" +#include "shared-module/displayio/__init__.h" + +static mp_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_MUTABLE_BOARD_DICT_STANDARD_ITEMS + + // External pins are in silkscreen order, from top to bottom, left side, then right side + // Encoder 1: V3-E uses GPIO26/13, V3 uses GPIO35/13 + { MP_ROM_QSTR(MP_QSTR_ENC1A), MP_OBJ_FROM_PTR(&pin_GPIO26) }, // V3-E: GPIO26, V3: GPIO35 + { MP_ROM_QSTR(MP_QSTR_ENC1A_V3), MP_OBJ_FROM_PTR(&pin_GPIO35) }, // V3-E: GPIO26, V3: GPIO35 + { MP_ROM_QSTR(MP_QSTR_ENC1B), MP_OBJ_FROM_PTR(&pin_GPIO13) }, + + // Encoder 2: Both V3 and V3-E use GPIO27/4 + { MP_ROM_QSTR(MP_QSTR_ENC2A), MP_OBJ_FROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_ENC2B), MP_OBJ_FROM_PTR(&pin_GPIO4) }, + + // Light sensor (V3/V3-E) + { MP_ROM_QSTR(MP_QSTR_LIGHT_SENSOR), MP_OBJ_FROM_PTR(&pin_GPIO36) }, + + // Temperature sensors (V3/V3-E) + { MP_ROM_QSTR(MP_QSTR_TEMP_SENSOR), MP_OBJ_FROM_PTR(&pin_GPIO39) }, + { MP_ROM_QSTR(MP_QSTR_QI_RX_TEMP_SENSOR), MP_OBJ_FROM_PTR(&pin_GPIO35) }, // V3-E only + + { MP_ROM_QSTR(MP_QSTR_SCL), MP_OBJ_FROM_PTR(&pin_GPIO25) }, + { MP_ROM_QSTR(MP_QSTR_SDA), MP_OBJ_FROM_PTR(&pin_GPIO21) }, + + { MP_ROM_QSTR(MP_QSTR_DISPLAY_SCK), MP_OBJ_FROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_SCK), MP_OBJ_FROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_DISPLAY_MOSI), MP_OBJ_FROM_PTR(&pin_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_OBJ_FROM_PTR(&pin_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_DISPLAY_MISO), MP_OBJ_FROM_PTR(&pin_GPIO26) }, // V3/V3-E have MISO + { MP_ROM_QSTR(MP_QSTR_MISO), MP_OBJ_FROM_PTR(&pin_GPIO26) }, + + { MP_ROM_QSTR(MP_QSTR_NFC_IN), MP_OBJ_FROM_PTR(&pin_GPIO32) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_OBJ_FROM_PTR(&pin_GPIO32) }, + { MP_ROM_QSTR(MP_QSTR_NFC_OUT), MP_OBJ_FROM_PTR(&pin_GPIO33) }, + { MP_ROM_QSTR(MP_QSTR_TX), MP_OBJ_FROM_PTR(&pin_GPIO33) }, + + { MP_ROM_QSTR(MP_QSTR_I2S_MCLK), MP_OBJ_FROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_I2S_BIT_CLOCK), MP_OBJ_FROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_I2S_BCLK), MP_OBJ_FROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_I2S_WORD_SELECT), MP_OBJ_FROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_I2S_LRCLK), MP_OBJ_FROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_I2S_DOUT), MP_OBJ_FROM_PTR(&pin_GPIO19) }, + + { MP_ROM_QSTR(MP_QSTR_IOEXPANDER_INT), MP_OBJ_FROM_PTR(&pin_GPIO34) }, + + { MP_ROM_QSTR(MP_QSTR_I2C), MP_OBJ_FROM_PTR(&board_i2c_obj) }, + + // Filled in by board_init() + { MP_ROM_QSTR(MP_QSTR_IOEXPANDER0), mp_const_none }, + { MP_ROM_QSTR(MP_QSTR_IOEXPANDER1), mp_const_none }, + { MP_ROM_QSTR(MP_QSTR_BATTERY_ALERT), mp_const_none }, // IOX.0.6 + { MP_ROM_QSTR(MP_QSTR_QI_STATUS), mp_const_none }, // IOX.0.7 + { MP_ROM_QSTR(MP_QSTR_USB_STATUS), mp_const_none }, // IOX.1.0 + { MP_ROM_QSTR(MP_QSTR_CHARGE_STATUS), mp_const_none }, // IOX.1.4 + { MP_ROM_QSTR(MP_QSTR_POWER_BUTTON), mp_const_none }, // IOX.1.3 + { MP_ROM_QSTR(MP_QSTR_ENC1_BUTTON), mp_const_none }, // IOX.0.5 + { MP_ROM_QSTR(MP_QSTR_ENC2_BUTTON), mp_const_none }, // IOX.0.4 + { MP_ROM_QSTR(MP_QSTR_HEADPHONE_DETECT), mp_const_none }, // IOX.1.1 + { MP_ROM_QSTR(MP_QSTR_PACTRL), mp_const_none }, // IOX.2.4 + // V3/V3-E use ht16d35x display with 4 CS lines + { MP_ROM_QSTR(MP_QSTR_DISPLAY_CS0), mp_const_none }, // IOX.2.0 + { MP_ROM_QSTR(MP_QSTR_DISPLAY_CS1), mp_const_none }, // IOX.2.1 + { MP_ROM_QSTR(MP_QSTR_DISPLAY_CS2), mp_const_none }, // IOX.2.2 + { MP_ROM_QSTR(MP_QSTR_DISPLAY_CS3), mp_const_none }, // IOX.2.3 + + { MP_ROM_QSTR(MP_QSTR_LEVEL_CONVERTER), mp_const_none }, // IOX.3.0 + { MP_ROM_QSTR(MP_QSTR_LEVEL_POWER_ENABLE), mp_const_none }, // IOX.2.5 + { MP_ROM_QSTR(MP_QSTR_LEVEL_VINHOLD), mp_const_none }, // IOX.3.1 + { MP_ROM_QSTR(MP_QSTR_LEVEL_VOUTEN), mp_const_none }, // IOX.3.3 + + { MP_ROM_QSTR(MP_QSTR_TILT), mp_const_none }, // IOX.1.2 + { MP_ROM_QSTR(MP_QSTR_RTC_INT), mp_const_none }, // IOX.0.1 + + // Qi charging pins (V3-E) + { MP_ROM_QSTR(MP_QSTR_QI_CHARGE_ENABLE), mp_const_none }, // IOX.2.6 + { MP_ROM_QSTR(MP_QSTR_QI_ENABLE_5W), mp_const_none }, // IOX.3.5 + { MP_ROM_QSTR(MP_QSTR_QI_I2C_INT), mp_const_none }, // IOX.0.0 + + // USB-C charging pins (V3/V3-E) + { MP_ROM_QSTR(MP_QSTR_USB_CHARGE_ENABLE), mp_const_none }, // IOX.2.7 + +}; +MP_DEFINE_MUTABLE_DICT(board_module_globals, board_module_globals_table); + +void board_set(qstr q, mp_obj_t value) { + mp_obj_t key = MP_OBJ_NEW_QSTR(q); + for (size_t i = 0; i < MP_ARRAY_SIZE(board_module_globals_table); i++) { + if (board_module_globals_table[i].key == key) { + board_module_globals_table[i].value = value; + return; + } + } +} diff --git a/tests/feature_check/slice.py.exp b/ports/espressif/boards/yoto_player_v3/sdkconfig similarity index 100% rename from tests/feature_check/slice.py.exp rename to ports/espressif/boards/yoto_player_v3/sdkconfig diff --git a/ports/espressif/common-hal/_bleio/Adapter.c b/ports/espressif/common-hal/_bleio/Adapter.c index f604e02c200..a47d7bc8a57 100644 --- a/ports/espressif/common-hal/_bleio/Adapter.c +++ b/ports/espressif/common-hal/_bleio/Adapter.c @@ -31,8 +31,9 @@ #include "nimble/nimble_port.h" #include "nimble/nimble_port_freertos.h" #include "host/ble_gap.h" +#include "host/ble_gatt.h" +#include "host/ble_sm.h" #include "host/util/util.h" -#include "services/ans/ble_svc_ans.h" #include "services/gap/ble_svc_gap.h" #include "services/gatt/ble_svc_gatt.h" @@ -44,10 +45,6 @@ #include "esp_nimble_hci.h" #include "nvs_flash.h" -#if CIRCUITPY_OS_GETENV -#include "shared-module/os/__init__.h" -#endif - // Status variables used while busy-waiting for events. static volatile bool _nimble_sync; static volatile int _connection_status; @@ -61,7 +58,7 @@ static void nimble_host_task(void *param) { static void _on_sync(void) { - int rc = ble_hs_util_ensure_addr(false); + int rc __attribute__((unused)) = ble_hs_util_ensure_addr(false); assert(rc == 0); _nimble_sync = true; @@ -70,7 +67,60 @@ static void _on_sync(void) { // All examples have this. It'd make sense in a header. void ble_store_config_init(void); -char default_ble_name[] = { 'C', 'I', 'R', 'C', 'U', 'I', 'T', 'P', 'Y', 0, 0, 0, 0, 0, 0, 0}; +// NimBLE sizes its client characteristic configuration (CCCD) pool once, in +// ble_gatts_start(), from the services counted by ble_gatts_count_cfg(). +// But every CircuitPython service is registered afterwards, using +// ble_gatts_add_dynamic_svcs(), which does not do its own counting, +// and does not resize the CCCD pool. +// +// So services added at runtime get no CCCDs of their own added to the pool. +// The CCCDs themselves can allocate on the NimBLE heap if needed, +// but ble_gatts_conn_can_alloc() still tests the CCCD pool size, and NimBLE refuses +// connectable advertising once the pool is empty. This is an oversight in the API. +// NimBLE returns BLE_HS_ENOMEM, which is reported as a MemoryError from +// start_advertising() as soon as the BLE workflow, a user service, and a +// connection together need more CCCDs than the built-in services reserved. +// +// To get around this, we'll make the CCCD pool larger, by calling ble_gatts_count_cfg() +// on a bulky dummy service that is never registered, just to force the pool to a +// good size. Two of the reserved CCCDs cover the BLE workflow's own notifying +// characteristics; the rest are for user services. +#define RESERVED_CCCD_COUNT (18) + +// Never called: the definition below is counted, not registered. NimBLE only +// requires that the callback not be NULL. +static int _reserved_cccd_access_cb(uint16_t conn_handle, uint16_t attr_handle, + struct ble_gatt_access_ctxt *ctxt, void *arg) { + return BLE_ATT_ERR_UNLIKELY; +} + +// Likewise unused, but must not be NULL. +static const ble_uuid16_t _reserved_cccd_uuid = BLE_UUID16_INIT(0xffff); + +// Reserve CCCDs for the services registered at runtime. NimBLE needs one CCCD +// per subscribable characteristic per connection, plus one for its cache; +// ble_gatts_count_cfg() applies that multiplier itself. +// +// Call this before nimble_port_freertos_init(): ble_gatts_start() sizes the pool +// on the nimble_host task, and counting afterwards is too late. +static void _reserve_cccds(void) { + // ble_gatts_count_cfg() only reads these definitions and keeps no pointers + // into them, so they can live on the stack and then be discarded. + struct ble_gatt_chr_def chr_defs[RESERVED_CCCD_COUNT + 1] = { 0 }; + for (size_t i = 0; i < RESERVED_CCCD_COUNT; i++) { + chr_defs[i].uuid = &_reserved_cccd_uuid.u; + chr_defs[i].access_cb = _reserved_cccd_access_cb; + // Only NOTIFY or INDICATE characteristics get a CCCD. + chr_defs[i].flags = BLE_GATT_CHR_F_NOTIFY; + } + + struct ble_gatt_svc_def svc_defs[2] = { 0 }; + svc_defs[0].type = BLE_GATT_SVC_TYPE_PRIMARY; + svc_defs[0].uuid = &_reserved_cccd_uuid.u; + svc_defs[0].characteristics = chr_defs; + + CHECK_NIMBLE_ERROR(ble_gatts_count_cfg(svc_defs)); +} void common_hal_bleio_adapter_set_enabled(bleio_adapter_obj_t *self, bool enabled) { const bool is_enabled = common_hal_bleio_adapter_get_enabled(self); @@ -96,35 +146,21 @@ void common_hal_bleio_adapter_set_enabled(bleio_adapter_obj_t *self, bool enable ble_hs_cfg.sm_their_key_dist |= BLE_SM_PAIR_KEY_DIST_ENC; ble_hs_cfg.sm_mitm = 0; - ble_hs_cfg.sm_sc = 0; + // LE Secure Connections is always offered. It's negotiated per pairing (a peer + // that only does legacy pairing still works) and is strictly better crypto, so + // there's no downside for existing "Just Works" users. Numeric-comparison pairing + // needs it. IO capability and the MITM requirement stay at the legacy defaults + // above until an attribute is constructed with a *_WITH_MITM permission, which + // raises them - see bleio_adapter_enable_mitm_pairing(). + ble_hs_cfg.sm_sc = 1; /* Stores the IRK */ ble_hs_cfg.sm_our_key_dist |= BLE_SM_PAIR_KEY_DIST_ID; ble_hs_cfg.sm_their_key_dist |= BLE_SM_PAIR_KEY_DIST_ID; ble_svc_gap_init(); ble_svc_gatt_init(); - ble_svc_ans_init(); - - #if CIRCUITPY_OS_GETENV - char ble_name[1 + MYNEWT_VAL_BLE_SVC_GAP_DEVICE_NAME_MAX_LENGTH]; - os_getenv_err_t result = common_hal_os_getenv_str("CIRCUITPY_BLE_NAME", ble_name, sizeof(ble_name)); - if (result == GETENV_OK) { - ble_svc_gap_device_name_set(ble_name); - } else - #endif - { - uint8_t mac[6]; - esp_read_mac(mac, ESP_MAC_BT); - mp_int_t len = sizeof(default_ble_name) - 1; - default_ble_name[len - 6] = nibble_to_hex_lower[mac[3] >> 4 & 0xf]; - default_ble_name[len - 5] = nibble_to_hex_lower[mac[3] & 0xf]; - default_ble_name[len - 4] = nibble_to_hex_lower[mac[4] >> 4 & 0xf]; - default_ble_name[len - 3] = nibble_to_hex_lower[mac[4] & 0xf]; - default_ble_name[len - 2] = nibble_to_hex_lower[mac[5] >> 4 & 0xf]; - default_ble_name[len - 1] = nibble_to_hex_lower[mac[5] & 0xf]; - default_ble_name[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings - ble_svc_gap_device_name_set(default_ble_name); - } + // Grow the CCCD pool so it's not too small. + _reserve_cccds(); // Clear all of the internal connection objects. for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) { @@ -150,6 +186,8 @@ void common_hal_bleio_adapter_set_enabled(bleio_adapter_obj_t *self, bool enable if (!_nimble_sync) { mp_raise_RuntimeError(MP_ERROR_TEXT("Update failed")); } + + bleio_adapter_reset_name(self); } else { int ret = nimble_port_stop(); while (xTaskGetHandle("nimble_host") != NULL && !mp_hal_is_interrupted()) { @@ -166,6 +204,15 @@ bool common_hal_bleio_adapter_get_enabled(bleio_adapter_obj_t *self) { return xTaskGetHandle("nimble_host") != NULL; } +void bleio_adapter_enable_mitm_pairing(void) { + // ble_hs_cfg is a plain global read by the SM code at pairing time, so bumping it + // here (from Characteristic / Descriptor construction, after the adapter is up) takes + // effect for every subsequent pairing. Idempotent and one-way for the lifetime of + // the adapter - a characteristic that needs authentication doesn't stop needing it. + ble_hs_cfg.sm_io_cap = BLE_SM_IO_CAP_DISP_YES_NO; + ble_hs_cfg.sm_mitm = 1; +} + bleio_address_obj_t *common_hal_bleio_adapter_get_address(bleio_adapter_obj_t *self) { uint8_t address_bytes[6]; uint8_t address_type = BLE_ADDR_RANDOM; @@ -175,20 +222,17 @@ bleio_address_obj_t *common_hal_bleio_adapter_get_address(bleio_adapter_obj_t *s return NULL; } - bleio_address_obj_t *address = mp_obj_malloc(bleio_address_obj_t, &bleio_address_type); - common_hal_bleio_address_construct(address, address_bytes, BLEIO_ADDRESS_TYPE_RANDOM_STATIC); - return address; + // The cached address is refreshed on every call. + common_hal_bleio_address_construct(&self->address, address_bytes, BLEIO_ADDRESS_TYPE_RANDOM_STATIC); + self->address.base.type = &bleio_address_type; + return &self->address; } bool common_hal_bleio_adapter_set_address(bleio_adapter_obj_t *self, bleio_address_obj_t *address) { if (address->type != BLEIO_ADDRESS_TYPE_RANDOM_STATIC) { return false; } - mp_buffer_info_t bufinfo; - if (!mp_get_buffer(address->bytes, &bufinfo, MP_BUFFER_READ)) { - return false; - } - int result = ble_hs_id_set_rnd(bufinfo.buf); + int result = ble_hs_id_set_rnd(address->bytes); return result == 0; } @@ -318,9 +362,7 @@ void common_hal_bleio_adapter_stop_scan(bleio_adapter_obj_t *self) { static void _convert_address(const bleio_address_obj_t *address, ble_addr_t *nimble_address) { nimble_address->type = address->type; - mp_buffer_info_t address_buf_info; - mp_get_buffer_raise(address->bytes, &address_buf_info, MP_BUFFER_READ); - memcpy(nimble_address->val, (uint8_t *)address_buf_info.buf, NUM_BLEIO_ADDRESS_BYTES); + memcpy(nimble_address->val, address->bytes, NUM_BLEIO_ADDRESS_BYTES); } static int _mtu_reply(uint16_t conn_handle, @@ -339,7 +381,7 @@ static int _mtu_reply(uint16_t conn_handle, return 0; } -static void _new_connection(uint16_t conn_handle) { +static void _new_connection(uint16_t conn_handle, bool user_owned) { // Set the tx_power for the connection higher than the advertisement. esp_ble_tx_power_set(conn_handle, ESP_PWR_LVL_N0); @@ -361,9 +403,19 @@ static void _new_connection(uint16_t conn_handle) { connection->conn_handle = conn_handle; connection->connection_obj = mp_const_none; connection->pair_status = PAIR_NOT_PAIRED; + connection->indicate_outstanding = false; connection->mtu = 0; + connection->user_owned = user_owned; - ble_gattc_exchange_mtu(conn_handle, _mtu_reply, connection); + if (ble_gattc_exchange_mtu(conn_handle, _mtu_reply, connection) != 0) { + // _mtu_reply() won't be called, so do its work here. + // This is the usual case with a peer that starts the MTU exchange itself, + // such as Zephyr: NimBLE answers that before this runs, and then refuses + // to start a second exchange. The BLE_GAP_EVENT_MTU it sent went to + // _connect_event(), not to the connection's event callback, so get the MTU now. + connection->mtu = ble_att_mtu(conn_handle); + _connection_status = conn_handle; + } // Change the callback for the connection. ble_gap_set_event_cb(conn_handle, bleio_connection_event_cb, connection); @@ -379,16 +431,40 @@ static int _connect_event(struct ble_gap_event *event, void *self_in) { case BLE_GAP_EVENT_CONNECT: if (event->connect.status == 0) { // This triggers an MTU exchange. Its reply will exit the loop waiting for a connection. - _new_connection(event->connect.conn_handle); + // Only user code connects in the central role. + _new_connection(event->connect.conn_handle, true); // Set connections objs back to NULL since we have a new // connection and need a new tuple. self->connection_objs = NULL; } else { - // The loop waiting for the connection to be comnpleted will stop when _connection_status changes. + // The loop waiting for the connection to be completed will stop when _connection_status changes. _connection_status = -event->connect.status; } break; + case BLE_GAP_EVENT_DISCONNECT: + // The link failed before NimBLE reported the connection, e.g. with 0x3E (connection + // failed to be established) once its automatic reattempts were used up. No + // BLE_GAP_EVENT_CONNECT follows, so end the wait here. No connection slot was + // taken yet: that only happens on BLE_GAP_EVENT_CONNECT. + #if CIRCUITPY_VERBOSE_BLE + mp_printf(&mp_plat_print, "Disconnected while connecting: reason 0x%04x\n", + event->disconnect.reason); + #endif + _connection_status = event->disconnect.reason > 0 + ? -event->disconnect.reason + : -BLE_HS_ENOTCONN; + break; + + #if MYNEWT_VAL(BLE_ENABLE_CONN_REATTEMPT) + case BLE_GAP_EVENT_REATTEMPT_COUNT: + // NimBLE is retrying a link that failed to be established. Keep waiting. + #if CIRCUITPY_VERBOSE_BLE + mp_printf(&mp_plat_print, "Connect reattempt %d\n", event->reattempt_cnt.count); + #endif + break; + #endif + default: #if CIRCUITPY_VERBOSE_BLE // For debugging. @@ -423,6 +499,10 @@ mp_obj_t common_hal_bleio_adapter_connect(bleio_adapter_obj_t *self, bleio_addre ble_addr_t addr; _convert_address(address, &addr); + // _connection_status gets set to either a positive connection handle or a negative error code. + // Reset it before connecting, so an early event isn't lost. + _connection_status = BLEIO_HANDLE_INVALID; + const int timeout_ms = SEC_TO_UNITS(timeout, UNIT_1_MS) + 0.5f; CHECK_NIMBLE_ERROR( ble_gap_connect(own_addr_type, &addr, @@ -430,20 +510,29 @@ mp_obj_t common_hal_bleio_adapter_connect(bleio_adapter_obj_t *self, bleio_addre &conn_params, _connect_event, self)); - // Wait an extra 50 ms to give the connect method the opportunity to time out. - - const uint64_t timeout_time_ms = common_hal_time_monotonic_ms() + timeout_ms; - // _connection_status gets set to either a positive connection handle or a negative error code. - _connection_status = BLEIO_HANDLE_INVALID; - while (_connection_status == BLEIO_HANDLE_INVALID && (common_hal_time_monotonic_ms() < timeout_time_ms)) { + // NimBLE ends a connection attempt with a BLE_GAP_EVENT_CONNECT, including when timeout_ms + // expires, or with a BLE_GAP_EVENT_DISCONNECT if the link fails before the connection is + // reported. Wait for one of those instead of keeping a separate deadline here. + // If we stopped waiting first, NimBLE would still be connecting, and the next connect() + // would fail. + while (_connection_status == BLEIO_HANDLE_INVALID) { RUN_BACKGROUND_TASKS; if (mp_hal_is_interrupted()) { - // Return prematurely. Then the interrupt exception will be raised. + // Stop connecting, and wait for the cancellation event, so NimBLE is ready + // for the next connect(). The interrupt exception is raised after we return. + if (ble_gap_conn_cancel() == 0) { + while (_connection_status == BLEIO_HANDLE_INVALID) { + RUN_BACKGROUND_TASKS; + } + } return mp_const_none; } } // Negative values are error codes, connection handle otherwise. + if (_connection_status == -BLE_HS_ETIMEOUT) { + mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Failed to connect: timeout")); + } if (_connection_status < 0) { CHECK_BLE_ERROR(-_connection_status); } @@ -498,7 +587,8 @@ static int _advertising_event(struct ble_gap_event *event, void *self_in) { #if !MYNEWT_VAL(BLE_EXT_ADV) if (event->connect.status == NIMBLE_OK) { - _new_connection(event->connect.conn_handle); + // The connection belongs to whoever started the advertising it answered. + _new_connection(event->connect.conn_handle, self->user_advertising); // Set connections objs back to NULL since we have a new // connection and need a new tuple. self->connection_objs = NULL; @@ -511,7 +601,8 @@ static int _advertising_event(struct ble_gap_event *event, void *self_in) { case BLE_GAP_EVENT_ADV_COMPLETE: #if MYNEWT_VAL(BLE_EXT_ADV) if (event->adv_complete.reason == NIMBLE_OK) { - _new_connection(event->adv_complete.conn_handle); + // The connection belongs to whoever started the advertising it answered. + _new_connection(event->adv_complete.conn_handle, self->user_advertising); // Set connections objs back to NULL since we have a new // connection and need a new tuple. self->connection_objs = NULL; @@ -561,10 +652,6 @@ uint32_t _common_hal_bleio_adapter_start_advertising(bleio_adapter_obj_t *self, bool high_duty_directed = directed_to != NULL && interval <= 3.5 && timeout <= 1; // Really 1.3, but it's an int uint32_t timeout_ms = timeout * 1000; - if (timeout_ms == 0) { - timeout_ms = BLE_HS_FOREVER; - } - #if MYNEWT_VAL(BLE_EXT_ADV) bool extended = advertising_data_len > BLE_ADV_LEGACY_DATA_MAX_LEN || @@ -626,8 +713,12 @@ uint32_t _common_hal_bleio_adapter_start_advertising(bleio_adapter_obj_t *self, } } + // If timeout_ms is zero, it means advertise forever. This is different than ble_gap_adv_start(). rc = ble_gap_ext_adv_start(0, timeout_ms, 0); + #else + // Extended advertising not enabled. + uint8_t conn_mode = connectable ? BLE_GAP_CONN_MODE_UND : BLE_GAP_CONN_MODE_NON; if (directed_to != NULL) { conn_mode = BLE_GAP_CONN_MODE_DIR; @@ -654,8 +745,10 @@ uint32_t _common_hal_bleio_adapter_start_advertising(bleio_adapter_obj_t *self, return rc; } } - rc = ble_gap_adv_start(own_addr_type, directed_to != NULL ? &peer: NULL, - timeout_ms, + // If timeout_ms is BLE_HS_FOREVER, it means advertise forever. This is different than ble_gap_ext_adv_start(). + rc = ble_gap_adv_start(own_addr_type, + directed_to != NULL ? &peer: NULL, + timeout_ms == 0 ? BLE_HS_FOREVER : timeout_ms, &adv_params, _advertising_event, self); #endif @@ -733,13 +826,13 @@ void common_hal_bleio_adapter_stop_advertising(bleio_adapter_obj_t *self) { } bool common_hal_bleio_adapter_get_advertising(bleio_adapter_obj_t *self) { - return ble_gap_adv_active(); + return common_hal_bleio_adapter_get_enabled(self) && ble_gap_adv_active(); } bool common_hal_bleio_adapter_get_connected(bleio_adapter_obj_t *self) { for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) { bleio_connection_internal_t *connection = &bleio_connections[i]; - if (connection->conn_handle != BLEIO_HANDLE_INVALID && connection->mtu != 0) { + if (connection->conn_handle != BLEIO_HANDLE_INVALID) { return true; } } @@ -754,7 +847,7 @@ mp_obj_t common_hal_bleio_adapter_get_connections(bleio_adapter_obj_t *self) { mp_obj_t items[BLEIO_TOTAL_CONNECTION_COUNT]; for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) { bleio_connection_internal_t *connection = &bleio_connections[i]; - if (connection->conn_handle != BLEIO_HANDLE_INVALID && connection->mtu != 0) { + if (connection->conn_handle != BLEIO_HANDLE_INVALID) { if (connection->connection_obj == mp_const_none) { connection->connection_obj = bleio_connection_new_from_internal(connection); } @@ -817,10 +910,11 @@ void bleio_adapter_gc_collect(bleio_adapter_obj_t *adapter) { } void bleio_adapter_reset(bleio_adapter_obj_t *adapter) { - common_hal_bleio_adapter_stop_scan(adapter); - if (common_hal_bleio_adapter_get_advertising(adapter)) { - common_hal_bleio_adapter_stop_advertising(adapter); + if (!common_hal_bleio_adapter_get_enabled(&common_hal_bleio_adapter_obj)) { + return; } + common_hal_bleio_adapter_stop_scan(adapter); + common_hal_bleio_adapter_stop_advertising(adapter); adapter->connection_objs = NULL; for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) { @@ -834,13 +928,13 @@ void bleio_adapter_reset(bleio_adapter_obj_t *adapter) { // Wait up to 125 ms (128 ticks) for disconnect to complete. This should be // greater than most connection intervals. - bool any_connected = false; + bool any_connected; uint64_t start_ticks = supervisor_ticks_ms64(); - while (any_connected && supervisor_ticks_ms64() - start_ticks < 128) { + do { any_connected = false; for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) { bleio_connection_internal_t *connection = &bleio_connections[i]; any_connected |= connection->conn_handle != BLEIO_HANDLE_INVALID; } - } + } while (any_connected && supervisor_ticks_ms64() - start_ticks < 128); } diff --git a/ports/espressif/common-hal/_bleio/Adapter.h b/ports/espressif/common-hal/_bleio/Adapter.h index 1dbae9946ee..31bd853f2b4 100644 --- a/ports/espressif/common-hal/_bleio/Adapter.h +++ b/ports/espressif/common-hal/_bleio/Adapter.h @@ -11,14 +11,19 @@ #include "py/obj.h" #include "py/objtuple.h" +#include "shared-bindings/_bleio/Address.h" #include "shared-bindings/_bleio/Connection.h" #include "shared-bindings/_bleio/ScanResults.h" #include "supervisor/background_callback.h" +#include "sdkconfig.h" + #ifndef BLEIO_TOTAL_CONNECTION_COUNT -#define BLEIO_TOTAL_CONNECTION_COUNT 5 +#define BLEIO_TOTAL_CONNECTION_COUNT CONFIG_BT_NIMBLE_MAX_CONNECTIONS #endif +// Do not allow more connections than NimBLE was configured for. +MP_STATIC_ASSERT(BLEIO_TOTAL_CONNECTION_COUNT <= CONFIG_BT_NIMBLE_MAX_CONNECTIONS); #define BLEIO_HANDLE_INVALID 0xffff @@ -31,7 +36,18 @@ typedef struct { mp_obj_tuple_t *connection_objs; background_callback_t background_callback; bool user_advertising; + // Cached local address returned by common_hal_bleio_adapter_get_address(). + // Stored inline so it never needs to allocate, even when read before the + // heap is available (e.g. from bleio_adapter_reset_name). + bleio_address_obj_t address; } bleio_adapter_obj_t; void bleio_adapter_gc_collect(bleio_adapter_obj_t *adapter); void bleio_adapter_reset(bleio_adapter_obj_t *adapter); + +// Raise the SM pairing configuration so an authenticated (MITM-protected) bond can be +// formed: advertise DISPLAY_YESNO IO capability and require MITM. Called from +// Characteristic / Descriptor construction when an attribute is given a *_WITH_MITM +// permission. A no-op-safe idempotent bump; devices with no such attribute keep the +// legacy "Just Works" defaults set in common_hal_bleio_adapter_set_enabled(). +void bleio_adapter_enable_mitm_pairing(void); diff --git a/ports/espressif/common-hal/_bleio/Characteristic.c b/ports/espressif/common-hal/_bleio/Characteristic.c index 6b842ad298c..1951c44eb06 100644 --- a/ports/espressif/common-hal/_bleio/Characteristic.c +++ b/ports/espressif/common-hal/_bleio/Characteristic.c @@ -23,6 +23,98 @@ static int characteristic_on_ble_gap_evt(struct ble_gap_event *event, void *param); +// A local characteristic that can notify or indicate registers an event handler +// whose storage is the characteristic object itself. NimBLE's GATT table +// holds a pointer to the object as its access-callback arg. Both stay valid +// because the characteristic's Service is retained while NimBLE knows about +// it, and the Service holds its characteristics; see Service.c. + +// Remember or forget a peer's subscription. NimBLE reports cur_notify and +// cur_indicate both clear when the peer writes zero to the CCCD and when the +// connection ends, so this handles disconnects too. +static void characteristic_set_subscription(bleio_characteristic_obj_t *self, + uint16_t conn_handle, bool notify, bool indicate) { + size_t free_slot = BLEIO_TOTAL_CONNECTION_COUNT; + for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) { + if (self->subscribers[i].conn_handle == conn_handle) { + if (notify || indicate) { + self->subscribers[i].notify = notify; + self->subscribers[i].indicate = indicate; + } else { + self->subscribers[i].conn_handle = BLEIO_HANDLE_INVALID; + } + return; + } + if (free_slot == BLEIO_TOTAL_CONNECTION_COUNT && + self->subscribers[i].conn_handle == BLEIO_HANDLE_INVALID) { + free_slot = i; + } + } + if ((notify || indicate) && free_slot < BLEIO_TOTAL_CONNECTION_COUNT) { + self->subscribers[free_slot].conn_handle = conn_handle; + self->subscribers[free_slot].notify = notify; + self->subscribers[free_slot].indicate = indicate; + } +} + +// Send one notification or indication. The send may return BLE_HS_ENOMEM, which +// could mean an empty mbuf pool or exhausted controller buffers. +// Both are transient and go away once the radio finishes sending other +// data, so wait them out instead of losing the value. +// NimBLE consumes the mbuf even when the send fails, so we need to build +// a fresh one for each attempt. +// The retry makes progress even from a background callback, +// because the draining is done by the nimble_host task, not by background callbacks. +static void characteristic_notify_indicate(bleio_characteristic_obj_t *self, + uint16_t conn_handle, mp_buffer_info_t *bufinfo, bool indicate) { + while (!mp_hal_is_interrupted()) { + struct os_mbuf *om = ble_hs_mbuf_from_flat(bufinfo->buf, bufinfo->len); + if (om != NULL) { + bleio_connection_internal_t *connection = NULL; + if (indicate) { + // NimBLE allows only one outstanding indication per connection and + // does not check in ble_gatts_indicate_custom(): a second one + // trips BLE_HS_DBG_ASSERT and corrupts the acknowledgment + // bookkeeping, so don't send a second one. + // Wait for the previous acknowledgment. + connection = bleio_conn_handle_to_connection(conn_handle); + if (connection == NULL) { + os_mbuf_free_chain(om); + return; + } + while (connection->indicate_outstanding && + connection->conn_handle == conn_handle && + !mp_hal_is_interrupted()) { + RUN_BACKGROUND_TASKS; + } + if (connection->conn_handle != conn_handle || mp_hal_is_interrupted()) { + os_mbuf_free_chain(om); + return; + } + // Set before submitting: the acknowledgment can preempt this + // task the moment the indication is on the air. + connection->indicate_outstanding = true; + } + const int rc = indicate + ? ble_gatts_indicate_custom(conn_handle, self->handle, om) + : ble_gatts_notify_custom(conn_handle, self->handle, om); + if (indicate && rc != NIMBLE_OK) { + // Never submitted, so no acknowledgment will clear it. + connection->indicate_outstanding = false; + } + if (rc == NIMBLE_OK) { + return; + } + if (rc != BLE_HS_ENOMEM) { + // Not a transient memory shortage. The peer is gone, or refused. + // These failures are not reported back to Python. + return; + } + } + RUN_BACKGROUND_TASKS; + } +} + 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, @@ -33,6 +125,9 @@ void common_hal_bleio_characteristic_construct(bleio_characteristic_obj_t *self, self->handle = BLEIO_HANDLE_INVALID; self->cccd_handle = BLEIO_HANDLE_INVALID; self->sccd_handle = BLEIO_HANDLE_INVALID; + for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) { + self->subscribers[i].conn_handle = BLEIO_HANDLE_INVALID; + } self->props = props; self->read_perm = read_perm; self->write_perm = write_perm; @@ -58,27 +153,42 @@ void common_hal_bleio_characteristic_construct(bleio_characteristic_obj_t *self, if ((props & CHAR_PROP_WRITE_NO_RESPONSE) != 0) { self->flags |= BLE_GATT_CHR_F_WRITE_NO_RSP; } - if (read_perm == SECURITY_MODE_ENC_WITH_MITM || write_perm == SECURITY_MODE_ENC_WITH_MITM || - read_perm == SECURITY_MODE_SIGNED_WITH_MITM || write_perm == SECURITY_MODE_SIGNED_WITH_MITM) { - mp_raise_NotImplementedError(MP_ERROR_TEXT("MITM security not supported")); - } + // The BLE_GATT_CHR_F_NOTIFY_INDICATE_* flags are set below to require encryption or + // authentication when writing the auto-generated CCCD, if reading the + // characteristic requires it. This matches the nordic port behavior. + // Without the flags, NimBLE registers the CCCD as writable on an unencrypted link, + // so an unpaired central can subscribe and nothing ever requires it to pair. + // + // TODO: This behavior was fixed in NimBLE 1.10.0. ESP-IDF 6.0.1 uses a fork of NimBLE. + // + // NimBLE's GATT layer has no dedicated "LESC" or "signed" characteristic flag: + // ENC_WITH_MITM, LESC_ENC_WITH_MITM and the SIGNED modes all map to the _AUTHEN + // flags, i.e. "require a man-in-the-middle-protected link". A *_WITH_MITM permission + // additionally makes the adapter offer numeric-comparison pairing (below) so such a + // link can actually be established. if (read_perm == SECURITY_MODE_ENC_NO_MITM) { - self->flags |= BLE_GATT_CHR_F_READ_ENC; + self->flags |= BLE_GATT_CHR_F_READ_ENC | BLE_GATT_CHR_F_NOTIFY_INDICATE_ENC; } - if (read_perm == SECURITY_MODE_SIGNED_NO_MITM) { - self->flags |= BLE_GATT_CHR_F_READ_AUTHEN; + if (read_perm == SECURITY_MODE_ENC_WITH_MITM || read_perm == SECURITY_MODE_LESC_ENC_WITH_MITM || + read_perm == SECURITY_MODE_SIGNED_NO_MITM || read_perm == SECURITY_MODE_SIGNED_WITH_MITM) { + self->flags |= BLE_GATT_CHR_F_READ_AUTHEN | BLE_GATT_CHR_F_NOTIFY_INDICATE_AUTHEN; } if (write_perm == SECURITY_MODE_ENC_NO_MITM) { self->flags |= BLE_GATT_CHR_F_WRITE_ENC; } - if (write_perm == SECURITY_MODE_SIGNED_NO_MITM) { + if (write_perm == SECURITY_MODE_ENC_WITH_MITM || write_perm == SECURITY_MODE_LESC_ENC_WITH_MITM || + write_perm == SECURITY_MODE_SIGNED_NO_MITM || write_perm == SECURITY_MODE_SIGNED_WITH_MITM) { self->flags |= BLE_GATT_CHR_F_WRITE_AUTHEN; } + if (bleio_attribute_security_mode_requires_mitm(read_perm) || + bleio_attribute_security_mode_requires_mitm(write_perm)) { + bleio_adapter_enable_mitm_pairing(); + } // If max_length is 0, then no storage is allocated. if (max_length > 0) { if (gc_alloc_possible()) { - self->current_value = m_malloc(max_length); + self->current_value = m_malloc_without_collect(max_length); } else { self->current_value = port_malloc(max_length, false); if (self->current_value == NULL) { @@ -92,7 +202,7 @@ void common_hal_bleio_characteristic_construct(bleio_characteristic_obj_t *self, self->max_length = max_length; self->fixed_length = fixed_length; - if (initial_value_bufinfo != NULL) { + if (!service->is_remote && initial_value_bufinfo != NULL) { common_hal_bleio_characteristic_set_value(self, initial_value_bufinfo); } @@ -108,6 +218,11 @@ void common_hal_bleio_characteristic_construct(bleio_characteristic_obj_t *self, ble_event_add_handler_entry(&self->event_handler_entry, characteristic_on_ble_gap_evt, self); } else { common_hal_bleio_service_add_characteristic(self->service, self, initial_value_bufinfo, user_description); + if ((props & (CHAR_PROP_NOTIFY | CHAR_PROP_INDICATE)) != 0) { + // Remember who subscribes: BLE_GAP_EVENT_SUBSCRIBE is the only report + // of that, and set_value() notifies subscribers and no one else. + ble_event_add_handler_entry(&self->event_handler_entry, characteristic_on_ble_gap_evt, self); + } } } @@ -119,8 +234,14 @@ void common_hal_bleio_characteristic_deinit(bleio_characteristic_obj_t *self) { if (common_hal_bleio_characteristic_deinited(self)) { return; } + // Take the characteristic off the event list before cleaning up the object. + ble_event_remove_handler(characteristic_on_ble_gap_evt, self); + for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) { + self->subscribers[i].conn_handle = BLEIO_HANDLE_INVALID; + } + if (self->current_value != NULL) { - if (gc_nbytes(self->current_value) > 0) { + if (gc_ptr_on_heap(self->current_value)) { m_free(self->current_value); } else { port_free(self->current_value); @@ -193,7 +314,25 @@ void common_hal_bleio_characteristic_set_value(bleio_characteristic_obj_t *self, self->current_value_len = bufinfo->len; memcpy(self->current_value, bufinfo->buf, self->current_value_len); - ble_gatts_chr_updated(self->handle); + // Notify and indicate subscribers here rather than by using + // ble_gatts_chr_updated(). That function cannot report a failed send, + // so we can't tell whether we succeeded or not. + // + // Unlike ble_gatts_chr_updated(), this does not persist a "changed" + // flag for bonded peers that are currently disconnected, so they are + // not notified on reconnect. This matches the nordic port. + for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) { + const uint16_t conn_handle = self->subscribers[i].conn_handle; + if (conn_handle == BLEIO_HANDLE_INVALID) { + continue; + } + if (self->subscribers[i].notify && (self->props & CHAR_PROP_NOTIFY) != 0) { + characteristic_notify_indicate(self, conn_handle, bufinfo, false); + } + if (self->subscribers[i].indicate && (self->props & CHAR_PROP_INDICATE) != 0) { + characteristic_notify_indicate(self, conn_handle, bufinfo, true); + } + } } } @@ -225,7 +364,26 @@ static int characteristic_on_ble_gap_evt(struct ble_gap_event *event, void *para } break; } + case BLE_GAP_EVENT_NOTIFY_TX: + // For indications only: BLE_HS_EDONE is the peer's acknowledgment + // and BLE_HS_ETIMEOUT is the stack giving up on getting one. Either way, + // the connection's single indication slot is free again. + if (event->notify_tx.indication != 0 && + event->notify_tx.attr_handle == self->handle && + (event->notify_tx.status == BLE_HS_EDONE || + event->notify_tx.status == BLE_HS_ETIMEOUT)) { + bleio_connection_internal_t *connection = + bleio_conn_handle_to_connection(event->notify_tx.conn_handle); + if (connection != NULL) { + connection->indicate_outstanding = false; + } + } + break; case BLE_GAP_EVENT_SUBSCRIBE: + if (event->subscribe.attr_handle == self->handle) { + characteristic_set_subscription(self, event->subscribe.conn_handle, + event->subscribe.cur_notify != 0, event->subscribe.cur_indicate != 0); + } break; default: return 0; @@ -243,6 +401,17 @@ int bleio_characteristic_access_cb(uint16_t conn_handle, uint16_t attr_handle, switch (ctxt->op) { case BLE_GATT_ACCESS_OP_READ_CHR: if (attr_handle == self->handle) { + // NimBLE has no separate read permission for a characteristic: its READ flag + // both declares the READ property and allows reads. So refuse reads here + // when the read permission is NO_ACCESS. This matches nordic and zephyr-cp. + // + // NimBLE also calls this callback, with no connection, to get the value for + // some notifications and indications. Those must still be sent, so refuse + // only reads from a connected peer. + if (conn_handle != BLE_HS_CONN_HANDLE_NONE && + self->read_perm == SECURITY_MODE_NO_ACCESS) { + return BLE_ATT_ERR_READ_NOT_PERMITTED; + } rc = os_mbuf_append(ctxt->om, self->current_value, self->current_value_len); @@ -252,6 +421,12 @@ int bleio_characteristic_access_cb(uint16_t conn_handle, uint16_t attr_handle, case BLE_GATT_ACCESS_OP_WRITE_CHR: if (attr_handle == self->handle) { + // NimBLE has no separate write permission for a characteristic: its WRITE flag + // both declares the WRITE property and allows writes. So refuse writes here + // when the write permission is NO_ACCESS. This matches nordic and zephyr-cp. + if (self->write_perm == SECURITY_MODE_NO_ACCESS) { + return BLE_ATT_ERR_WRITE_NOT_PERMITTED; + } uint16_t om_len = OS_MBUF_PKTLEN(ctxt->om); if (om_len > self->max_length || (self->fixed_length && om_len != self->max_length)) { return BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN; @@ -293,7 +468,7 @@ void common_hal_bleio_characteristic_add_descriptor(bleio_characteristic_obj_t * bleio_descriptor_obj_t *descriptor) { size_t i = self->descriptor_list->len; if (i >= MAX_DESCRIPTORS) { - mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Too many descriptors")); + mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Too many %q"), MP_QSTR_descriptors); } mp_obj_list_append(MP_OBJ_FROM_PTR(self->descriptor_list), @@ -320,7 +495,7 @@ void common_hal_bleio_characteristic_set_cccd(bleio_characteristic_obj_t *self, } const uint16_t conn_handle = bleio_connection_get_conn_handle(self->service->connection); - common_hal_bleio_check_connected(conn_handle); + bleio_check_connected(conn_handle); uint16_t cccd_value = (notify ? 1 << 0 : 0) | diff --git a/ports/espressif/common-hal/_bleio/Characteristic.h b/ports/espressif/common-hal/_bleio/Characteristic.h index 1ae32e9ddd8..e820b47015b 100644 --- a/ports/espressif/common-hal/_bleio/Characteristic.h +++ b/ports/espressif/common-hal/_bleio/Characteristic.h @@ -10,6 +10,7 @@ #include "shared-bindings/_bleio/Attribute.h" #include "common-hal/_bleio/Descriptor.h" #include "shared-module/_bleio/Characteristic.h" +#include "common-hal/_bleio/Adapter.h" #include "common-hal/_bleio/ble_events.h" #include "common-hal/_bleio/Service.h" #include "common-hal/_bleio/UUID.h" @@ -40,6 +41,18 @@ typedef struct _bleio_characteristic_obj { uint16_t user_desc_handle; uint16_t cccd_handle; uint16_t sccd_handle; + // Track currently subscribed peers. NimBLE in the current ESP-IDF offers + // no way to read a peer's CCCD, and notifying without checking would + // send to peers that never asked. NimBLE reports subscriptions with both + // flags clear on CCCD clears and on disconnect, so entries free themselves. + // One subscription per connection at most, hence BLEIO_TOTAL_CONNECTION_COUNT. + // TODO when NimBLE is updated to 1.9.0 or later: ble_gatts_read_cccd() + // reads the CCCD directly, and this table can go away. + struct { + uint16_t conn_handle; + bool notify; + bool indicate; + } subscribers[BLEIO_TOTAL_CONNECTION_COUNT]; ble_event_handler_entry_t event_handler_entry; // The actual structure is managed by the service because it needs to have // an array. diff --git a/ports/espressif/common-hal/_bleio/CharacteristicBuffer.c b/ports/espressif/common-hal/_bleio/CharacteristicBuffer.c index 8020af2873d..2f34666420b 100644 --- a/ports/espressif/common-hal/_bleio/CharacteristicBuffer.c +++ b/ports/espressif/common-hal/_bleio/CharacteristicBuffer.c @@ -16,12 +16,19 @@ #include "shared-bindings/_bleio/__init__.h" #include "shared-bindings/_bleio/Connection.h" #include "shared-bindings/_bleio/CharacteristicBuffer.h" +#include "shared-bindings/microcontroller/__init__.h" #include "supervisor/shared/tick.h" #include "common-hal/_bleio/ble_events.h" +// The ringbuf is filled from the nimble_host task, which preempts the VM task +// at arbitrary points, and ringbuf operations are not atomic, so guard them +// with interrupts disabled. + +// Runs on the nimble_host task. void bleio_characteristic_buffer_extend(bleio_characteristic_buffer_obj_t *self, const uint8_t *data, size_t len) { + common_hal_mcu_disable_interrupts(); if (self->watch_for_interrupt_char) { for (uint16_t i = 0; i < len; i++) { if (data[i] == mp_interrupt_char) { @@ -34,6 +41,7 @@ void bleio_characteristic_buffer_extend(bleio_characteristic_buffer_obj_t *self, } else { ringbuf_put_n(&self->ringbuf, data, len); } + common_hal_mcu_enable_interrupts(); } void _common_hal_bleio_characteristic_buffer_construct(bleio_characteristic_buffer_obj_t *self, @@ -54,7 +62,7 @@ void common_hal_bleio_characteristic_buffer_construct(bleio_characteristic_buffe bleio_characteristic_obj_t *characteristic, mp_float_t timeout, size_t buffer_size) { - uint8_t *buffer = m_malloc(buffer_size); + uint8_t *buffer = m_malloc_without_collect(buffer_size); _common_hal_bleio_characteristic_buffer_construct(self, characteristic, timeout, buffer, buffer_size, NULL, false); } @@ -70,20 +78,23 @@ uint32_t common_hal_bleio_characteristic_buffer_read(bleio_characteristic_buffer } } + common_hal_mcu_disable_interrupts(); uint32_t num_bytes_read = ringbuf_get_n(&self->ringbuf, data, len); + common_hal_mcu_enable_interrupts(); return num_bytes_read; } -// NOTE: The nRF port has protection around these operations because the ringbuf -// is filled from an interrupt. On ESP the ringbuf is filled from the BLE host -// task that won't interrupt us. - uint32_t common_hal_bleio_characteristic_buffer_rx_characters_available(bleio_characteristic_buffer_obj_t *self) { - return ringbuf_num_filled(&self->ringbuf); + common_hal_mcu_disable_interrupts(); + uint32_t count = ringbuf_num_filled(&self->ringbuf); + common_hal_mcu_enable_interrupts(); + return count; } void common_hal_bleio_characteristic_buffer_clear_rx_buffer(bleio_characteristic_buffer_obj_t *self) { + common_hal_mcu_disable_interrupts(); ringbuf_clear(&self->ringbuf); + common_hal_mcu_enable_interrupts(); } bool common_hal_bleio_characteristic_buffer_deinited(bleio_characteristic_buffer_obj_t *self) { diff --git a/ports/espressif/common-hal/_bleio/Connection.c b/ports/espressif/common-hal/_bleio/Connection.c index 8c88bfe3ec5..15de1fe0c5f 100644 --- a/ports/espressif/common-hal/_bleio/Connection.c +++ b/ports/espressif/common-hal/_bleio/Connection.c @@ -30,7 +30,12 @@ #include "common-hal/_bleio/ble_events.h" +#include "freertos/FreeRTOS.h" +#include "freertos/queue.h" + #include "host/ble_att.h" +#include "host/ble_sm.h" +#include "host/ble_store.h" // Uncomment to turn on debug logging just in this file. // #undef CIRCUITPY_VERBOSE_BLE @@ -43,6 +48,7 @@ int bleio_connection_event_cb(struct ble_gap_event *event, void *connection_in) case BLE_GAP_EVENT_DISCONNECT: { connection->conn_handle = BLEIO_HANDLE_INVALID; connection->pair_status = PAIR_NOT_PAIRED; + connection->mitm_protected = false; #if CIRCUITPY_VERBOSE_BLE mp_printf(&mp_plat_print, "event->disconnect.reason: 0x%x\n", event->disconnect.reason); @@ -65,7 +71,7 @@ int bleio_connection_event_cb(struct ble_gap_event *event, void *connection_in) case BLE_GAP_EVENT_CONN_UPDATE: { struct ble_gap_conn_desc desc; - int rc = ble_gap_conn_find(event->conn_update.conn_handle, &desc); + int rc __attribute__((unused)) = ble_gap_conn_find(event->conn_update.conn_handle, &desc); assert(rc == 0); connection->conn_params_updating = false; break; @@ -73,11 +79,58 @@ int bleio_connection_event_cb(struct ble_gap_event *event, void *connection_in) case BLE_GAP_EVENT_ENC_CHANGE: { struct ble_gap_conn_desc desc; ble_gap_conn_find(event->enc_change.conn_handle, &desc); + connection->sec_status = event->enc_change.status; if (desc.sec_state.encrypted) { connection->pair_status = PAIR_PAIRED; + } else if (connection->pair_status == PAIR_WAITING || + connection->pair_status == PAIR_WAITING_NUMCMP) { + // Pairing failed, or numeric comparison was rejected. + // This ends the wait in pair(), which reports sec_status. + connection->pair_status = PAIR_NOT_PAIRED; } + // .authenticated is set once the MITM leg (numeric comparison / passkey entry) + // completes; a plain "Just Works" bond leaves it clear. Surfaced as + // Connection.authenticated. + connection->mitm_protected = desc.sec_state.authenticated; break; } + case BLE_GAP_EVENT_PASSKEY_ACTION: { + // The peer started MITM pairing. An attribute was constructed with a + // *_WITH_MITM permission, which made the adapter advertise DISPLAY_YESNO IO + // capability (bleio_adapter_enable_mitm_pairing()), so NimBLE asks us to + // confirm a 6-digit numeric-comparison value. Stash it and enter + // PAIR_WAITING_NUMCMP; Python reads it via Connection.numeric_comparison + // and answers with confirm_pairing(). + if (event->passkey.params.action == BLE_SM_IOACT_NUMCMP) { + connection->pairing_numcmp = event->passkey.params.numcmp; + connection->pair_status = PAIR_WAITING_NUMCMP; + } else { + // Passkey entry / OOB: a display + yes/no button can't service these. + // Fail fast instead of letting SM hang until its ~30 s timeout. + #if CIRCUITPY_VERBOSE_BLE + mp_printf(&mp_plat_print, "unsupported passkey action %d; terminating\n", + event->passkey.params.action); + #endif + ble_gap_terminate(event->passkey.conn_handle, BLE_ERR_AUTH_FAIL); + } + break; + } + case BLE_GAP_EVENT_REPEAT_PAIRING: { + // The peer is asking to pair even though we still have a bond with it. + // This means it no longer has its own copy of that bond. Discard our bond + // and tell the BLE stack to carry on pairing. Otherwise NimBLE silently + // ignores the request, and a central that has forgotten this device can + // never pair again without erasing the bonds on the board. The + // nordic port likewise replaces the stored keys when a peer re-pairs. + struct ble_gap_conn_desc desc; + if (ble_gap_conn_find(event->repeat_pairing.conn_handle, &desc) != 0) { + return BLE_GAP_REPEAT_PAIRING_IGNORE; + } + ble_store_util_delete_peer(&desc.peer_id_addr); + // The BLE stack checks that the bond is really gone before retrying, and + // reports this event again if it is not. + return BLE_GAP_REPEAT_PAIRING_RETRY; + } case BLE_GAP_EVENT_MTU: { if (event->mtu.conn_handle != connection->conn_handle) { return 0; @@ -137,6 +190,7 @@ void common_hal_bleio_connection_pair(bleio_connection_internal_t *self, bool bo if (self->pair_status == PAIR_PAIRED) { return; } + self->sec_status = 0; self->pair_status = PAIR_WAITING; CHECK_NIMBLE_ERROR(ble_gap_security_initiate(self->conn_handle)); while (self->pair_status == PAIR_WAITING && !mp_hal_is_interrupted()) { @@ -145,6 +199,56 @@ void common_hal_bleio_connection_pair(bleio_connection_internal_t *self, bool bo if (mp_hal_is_interrupted()) { return; } + if (self->conn_handle == BLEIO_HANDLE_INVALID) { + mp_raise_ConnectionError(MP_ERROR_TEXT("Not connected")); + } + if (self->pair_status == PAIR_PAIRED) { + return; + } + // Same messages as nordic. + switch (self->sec_status) { + case BLE_HS_SM_US_ERR(BLE_SM_ERR_UNSPECIFIED): + case BLE_HS_SM_PEER_ERR(BLE_SM_ERR_UNSPECIFIED): + mp_raise_bleio_SecurityError(MP_ERROR_TEXT("Unspecified issue. The pairing request on the other device may have been declined or ignored.")); + break; + default: + mp_raise_bleio_SecurityError(MP_ERROR_TEXT("Unknown security error: 0x%04x"), self->sec_status); + break; + } +} + +// LE Secure Connections numeric comparison. Unlike pair(), these don't block: the peer +// (a central) drives the SM procedure; we just observe the pending value and inject the +// yes/no. BLE_GAP_EVENT_PASSKEY_ACTION sets pair_status = PAIR_WAITING_NUMCMP. +mp_obj_t common_hal_bleio_connection_get_numeric_comparison(bleio_connection_obj_t *self) { + if (self->connection == NULL || self->connection->pair_status != PAIR_WAITING_NUMCMP) { + return mp_const_none; + } + return mp_obj_new_int_from_uint(self->connection->pairing_numcmp); +} + +void common_hal_bleio_connection_confirm_pairing(bleio_connection_obj_t *self, bool accept) { + if (self->connection == NULL) { + mp_raise_ConnectionError(MP_ERROR_TEXT("Not connected")); + } + if (self->connection->pair_status != PAIR_WAITING_NUMCMP) { + mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("No pairing in progress")); + } + struct ble_sm_io io = { + .action = BLE_SM_IOACT_NUMCMP, + .numcmp_accept = accept, + }; + CHECK_NIMBLE_ERROR(ble_sm_inject_io(self->connection->conn_handle, &io)); + // SM proceeds from here. On accept, ENC_CHANGE moves us to PAIR_PAIRED; on reject it + // won't, so drop straight back to PAIR_NOT_PAIRED rather than waiting for the peer. + self->connection->pair_status = accept ? PAIR_WAITING : PAIR_NOT_PAIRED; +} + +bool common_hal_bleio_connection_get_authenticated(bleio_connection_obj_t *self) { + if (self->connection == NULL) { + return false; + } + return self->connection->mitm_protected; } mp_float_t common_hal_bleio_connection_get_connection_interval(bleio_connection_internal_t *self) { @@ -181,44 +285,148 @@ void common_hal_bleio_connection_set_connection_interval(bleio_connection_intern // Zero when discovery is in process. BLE_HS_EDONE or a BLE_HS_ error code when done. static volatile int _last_discovery_status; -static uint64_t _discovery_start_time; - -// Give 20 seconds for discovery +// Give 20 seconds for each step of discovery: services, characteristics, attributes. #define DISCOVERY_TIMEOUT_MS 20000 -static void _start_discovery_timeout(void) { - _discovery_start_time = common_hal_time_monotonic_ms(); +// Record result of last discovery step: services, characteristics, descriptors. +static void _set_discovery_step_status(int status) { + _last_discovery_status = status; } -static int _wait_for_discovery_step_done(void) { - const uint64_t timeout_time_ms = _discovery_start_time + DISCOVERY_TIMEOUT_MS; - while ((_last_discovery_status == 0) && (common_hal_time_monotonic_ms() < timeout_time_ms)) { - RUN_BACKGROUND_TASKS; - if (mp_hal_is_interrupted()) { - // Return prematurely. Then the interrupt will be raised. - _last_discovery_status = BLE_HS_EDONE; - } +static void _check_discovery_status(int status) { + #if CIRCUITPY_VERBOSE_BLE + mp_printf(&mp_plat_print, "discovery step status: %d\n", status); + #endif + + if (status == BLE_HS_EDONE) { + return; } - return _last_discovery_status; + if (status < BLE_HS_ERR_ATT_BASE) { + CHECK_NIMBLE_ERROR(status); + return; + } + CHECK_BLE_ERROR(status); } -// Record result of last discovery step: services, characteristics, descriptors. -static void _set_discovery_step_status(int status) { - _last_discovery_status = status; +// Raw discovery results are staged here by the NimBLE host-task callbacks. +// Those callbacks run on the "nimble_host" task, NOT the VM task, so they must +// not allocate from the MicroPython heap: an allocation there can trigger a +// gc_collect() that scans the wrong task's stack and frees the VM's live +// objects. Instead the callbacks copy the plain NimBLE result struct into this +// FreeRTOS queue, and the VM task drains it and builds the Python objects. +// +// Discovery is serialized (one discover_remote_services() at a time), so a +// single file-static queue suffices. It must hold one ATT-PDU burst of records: +// within a response PDU the host task invokes the callback repeatedly without +// yielding, so the VM task cannot drain until the next PDU's round-trip. The +// largest burst is a find-information response at the maximum ATT MTU we +// advertise (CONFIG_BT_NIMBLE_ATT_PREFERRED_MTU, 256): about 64 descriptor +// records. The depth is twice that. +// +// The queue is created on first use from the FreeRTOS (IDF) heap, not the GC +// heap, so it needs no GC root and survives soft reloads: a stale procedure's +// sends always land in live memory. It is never deleted. + +// One queue item, sized to the largest record type, so one queue can serve every +// discovery step. +typedef union { + struct ble_gatt_svc svc; + struct ble_gatt_chr chr; + struct ble_gatt_dsc dsc; +} discovery_record_t; + +#define DISCOVERY_QUEUE_DEPTH (128) +static QueueHandle_t _discovery_queue; + +// Create the queue on first use, and empty it before a discovery step. Runs on +// the VM task. xQueueReset() is safe against a stale procedure from a previous +// errored, timed-out, or interrupted discovery that may still be sending +// records on the nimble_host task. +static void _reset_discovery_queue(void) { + if (_discovery_queue == NULL) { + _discovery_queue = xQueueCreate(DISCOVERY_QUEUE_DEPTH, sizeof(discovery_record_t)); + if (_discovery_queue == NULL) { + m_malloc_fail(DISCOVERY_QUEUE_DEPTH * sizeof(discovery_record_t)); + } + } + xQueueReset(_discovery_queue); } static int _discovered_service_cb(uint16_t conn_handle, const struct ble_gatt_error *error, const struct ble_gatt_svc *svc, void *arg) { - bleio_connection_internal_t *self = (bleio_connection_internal_t *)arg; + if (error->status != 0) { + #if CIRCUITPY_VERBOSE_BLE + mp_printf(&mp_plat_print, "_discovered_service_cb error->status: %d, handle: %d\n", + error->status, error->att_handle); + #endif + + // BLE_HS_EDONE or some error has occurred. + _set_discovery_step_status(error->status); + return 0; + } + + // Runs on the nimble_host task: stage the raw result only, never allocate. + discovery_record_t record = { .svc = *svc }; + if (xQueueSend(_discovery_queue, &record, 0) != pdTRUE) { + _set_discovery_step_status(BLE_HS_ENOMEM); + } + return 0; +} + +static int _discovered_characteristic_cb(uint16_t conn_handle, + const struct ble_gatt_error *error, + const struct ble_gatt_chr *chr, + void *arg) { + if (error->status != 0) { + #if CIRCUITPY_VERBOSE_BLE + mp_printf(&mp_plat_print, "_discovered_characteristic_cb error->status: %d, handle: %d\n", + error->status, error->att_handle); + #endif + + // BLE_HS_EDONE or some error has occurred. + _set_discovery_step_status(error->status); + return 0; + } + + // Runs on the nimble_host task: stage the raw result only, never allocate. + discovery_record_t record = { .chr = *chr }; + if (xQueueSend(_discovery_queue, &record, 0) != pdTRUE) { + _set_discovery_step_status(BLE_HS_ENOMEM); + } + return 0; +} +static int _discovered_descriptor_cb(uint16_t conn_handle, + const struct ble_gatt_error *error, + uint16_t chr_val_handle, + const struct ble_gatt_dsc *dsc, + void *arg) { if (error->status != 0) { + #if CIRCUITPY_VERBOSE_BLE + mp_printf(&mp_plat_print, "_discovered_descriptor_cb error->status: %d, handle: %d\n", + error->status, error->att_handle); + #endif + // BLE_HS_EDONE or some error has occurred. _set_discovery_step_status(error->status); return 0; } + // Runs on the nimble_host task: stage the raw result only, never allocate. + discovery_record_t record = { .dsc = *dsc }; + if (xQueueSend(_discovery_queue, &record, 0) != pdTRUE) { + _set_discovery_step_status(BLE_HS_ENOMEM); + } + return 0; +} + +// Build a Service object from a staged raw record. Runs on the VM task. +static void _build_service(void *ctx, const void *record) { + bleio_connection_internal_t *self = ctx; + const struct ble_gatt_svc *svc = record; + bleio_service_obj_t *service = mp_obj_malloc(bleio_service_obj_t, &bleio_service_type); // Initialize several fields at once. @@ -236,27 +444,53 @@ static int _discovered_service_cb(uint16_t conn_handle, mp_obj_list_append(MP_OBJ_FROM_PTR(self->remote_service_list), MP_OBJ_FROM_PTR(service)); - return 0; } -static int _discovered_characteristic_cb(uint16_t conn_handle, - const struct ble_gatt_error *error, - const struct ble_gatt_chr *chr, - void *arg) { - bleio_service_obj_t *service = (bleio_service_obj_t *)arg; - - if (error->status != 0) { - // BLE_HS_EDONE or some error has occurred. - _set_discovery_step_status(error->status); - return 0; +// Drain and build all staged records on the VM task, until the step completes +// and the queue is empty. build() is invoked for each raw record with ctx +// passed through. Returns the discovery step status. +static int _drain_records(void *ctx, + void (*build)(void *ctx, const void *record)) { + const uint64_t timeout_time_ms = common_hal_time_monotonic_ms() + DISCOVERY_TIMEOUT_MS; + discovery_record_t record; + while (true) { + if (xQueueReceive(_discovery_queue, &record, 0) == pdTRUE) { + build(ctx, &record); + continue; + } + // Queue is empty. + if (_last_discovery_status != 0) { + // On EDONE or a NimBLE error, the terminal callback has already + // run, so no more records will arrive: drain any that raced in, + // then stop. On ENOMEM (our own send failure) the procedure may + // still be running, but we are raising anyway; any later + // discovery resets the queue before reuse. + while (xQueueReceive(_discovery_queue, &record, 0) == pdTRUE) { + build(ctx, &record); + } + return _last_discovery_status; + } + if (common_hal_time_monotonic_ms() >= timeout_time_ms) { + return BLE_HS_ETIMEOUT; + } + RUN_BACKGROUND_TASKS; + if (mp_hal_is_interrupted()) { + // Return prematurely. Then the interrupt will be raised. + _set_discovery_step_status(BLE_HS_EDONE); + } } +} + +// Build a Characteristic object from a staged raw record. Runs on the VM task. +static void _build_characteristic(void *ctx, const void *record) { + bleio_service_obj_t *service = ctx; + const struct ble_gatt_chr *chr = record; bleio_characteristic_obj_t *characteristic = mp_obj_malloc(bleio_characteristic_obj_t, &bleio_characteristic_type); // Known characteristic UUID. bleio_uuid_obj_t *uuid = mp_obj_malloc(bleio_uuid_obj_t, &bleio_uuid_type); - uuid->nimble_ble_uuid = chr->uuid; bleio_characteristic_properties_t props = @@ -281,32 +515,17 @@ static int _discovered_characteristic_cb(uint16_t conn_handle, characteristic->def_handle = chr->def_handle; #if CIRCUITPY_VERBOSE_BLE - mp_printf(&mp_plat_print, "_discovered_characteristic_cb: char handle: %d\n", characteristic->handle); + mp_printf(&mp_plat_print, "_build_characteristic: char handle: %d\n", characteristic->handle); #endif mp_obj_list_append(MP_OBJ_FROM_PTR(service->characteristic_list), MP_OBJ_FROM_PTR(characteristic)); - return 0; } -static int _discovered_descriptor_cb(uint16_t conn_handle, - const struct ble_gatt_error *error, - uint16_t chr_val_handle, - const struct ble_gatt_dsc *dsc, - void *arg) { - bleio_characteristic_obj_t *characteristic = (bleio_characteristic_obj_t *)arg; - - if (error->status != 0) { - - #if CIRCUITPY_VERBOSE_BLE - mp_printf(&mp_plat_print, "_discovered_descriptor_cb error->status: %d, handle: %d\n", - error->status, error->att_handle); - #endif - - // BLE_HS_EDONE or some error has occurred. - _set_discovery_step_status(error->status); - return 0; - } +// Build a Descriptor object from a staged raw record. Runs on the VM task. +static void _build_descriptor(void *ctx, const void *record) { + bleio_characteristic_obj_t *characteristic = ctx; + const struct ble_gatt_dsc *dsc = record; // Remember handles for certain well-known descriptors. switch (dsc->uuid.u16.value) { @@ -337,33 +556,28 @@ static int _discovered_descriptor_cb(uint16_t conn_handle, descriptor->handle = dsc->handle; #if CIRCUITPY_VERBOSE_BLE - mp_printf(&mp_plat_print, "_discovered_descriptor_cb: char handle: %d, desc handle: %d, uuid type: %d, u16 value: 0x%x\n", + mp_printf(&mp_plat_print, "_build_descriptor: char handle: %d, desc handle: %d, uuid type: %d, u16 value: 0x%x\n", characteristic->handle, descriptor->handle, dsc->uuid.u.type, dsc->uuid.u16.value); #endif mp_obj_list_append(MP_OBJ_FROM_PTR(characteristic->descriptor_list), MP_OBJ_FROM_PTR(descriptor)); - return 0; } static void discover_remote_services(bleio_connection_internal_t *self, mp_obj_t service_uuids_whitelist) { // Start over with an empty list. self->remote_service_list = mp_obj_new_list(0, NULL); - // Start timeout in case discovery gets stuck. - _start_discovery_timeout(); - if (service_uuids_whitelist == mp_const_none) { - // Reset discovery status before starting callbacks + // Reset discovery status and staging queue before starting callbacks. _set_discovery_step_status(0); + _reset_discovery_queue(); CHECK_NIMBLE_ERROR(ble_gattc_disc_all_svcs(self->conn_handle, _discovered_service_cb, self)); - // Wait for _discovered_service_cb() to be called multiple times until it's done. - int status = _wait_for_discovery_step_done(); - if (status != BLE_HS_EDONE) { - CHECK_BLE_ERROR(status); - } + // Drain staged services and build them on the VM task until done. + int status = _drain_records(self, _build_service); + _check_discovery_status(status); } else { mp_obj_iter_buf_t iter_buf; mp_obj_t iterable = mp_getiter(service_uuids_whitelist, &iter_buf); @@ -374,27 +588,26 @@ static void discover_remote_services(bleio_connection_internal_t *self, mp_obj_t } bleio_uuid_obj_t *uuid = MP_OBJ_TO_PTR(uuid_obj); - // Reset discovery status before starting callbacks + // Reset discovery status and staging queue before starting callbacks. _set_discovery_step_status(0); + _reset_discovery_queue(); CHECK_NIMBLE_ERROR(ble_gattc_disc_svc_by_uuid(self->conn_handle, &uuid->nimble_ble_uuid.u, _discovered_service_cb, self)); - // Wait for _discovered_service_cb() to be called multiple times until it's done. - int status = _wait_for_discovery_step_done(); - if (status != BLE_HS_EDONE) { - CHECK_BLE_ERROR(status); - } + // Drain staged services and build them on the VM task until done. + int status = _drain_records(self, _build_service); + _check_discovery_status(status); } } // Now discover characteristics for each discovered service. - for (size_t i = 0; i < self->remote_service_list->len; i++) { bleio_service_obj_t *service = MP_OBJ_TO_PTR(self->remote_service_list->items[i]); - // Reset discovery status before starting callbacks + // Reset discovery status and staging queue before starting callbacks. _set_discovery_step_status(0); + _reset_discovery_queue(); CHECK_NIMBLE_ERROR(ble_gattc_disc_all_chrs(self->conn_handle, service->start_handle, @@ -402,11 +615,9 @@ static void discover_remote_services(bleio_connection_internal_t *self, mp_obj_t _discovered_characteristic_cb, service)); - // Wait for _discovered_characteristic_cb() to be called multiple times until it's done. - int status = _wait_for_discovery_step_done(); - if (status != BLE_HS_EDONE) { - CHECK_BLE_ERROR(status); - } + // Drain staged characteristics and build them on the VM task until done. + int status = _drain_records(service, _build_characteristic); + _check_discovery_status(status); // Got characteristics for this service. Now discover descriptors for each characteristic. size_t char_list_len = service->characteristic_list->len; @@ -423,15 +634,16 @@ static void discover_remote_services(bleio_connection_internal_t *self, mp_obj_t uint16_t end_handle = next_characteristic == NULL ? service->end_handle - : next_characteristic->handle - 1; + : next_characteristic->def_handle - 1; // Pre-check if there are no descriptors to discover so descriptor discovery doesn't fail if (end_handle <= characteristic->handle) { continue; } - // Reset discovery status before starting callbacks + // Reset discovery status and staging queue before starting callbacks. _set_discovery_step_status(0); + _reset_discovery_queue(); // The descriptor handle inclusive range is [characteristic->handle + 1, end_handle], // but ble_gattc_disc_all_dscs() requires starting with characteristic->handle. @@ -439,11 +651,9 @@ static void discover_remote_services(bleio_connection_internal_t *self, mp_obj_t end_handle, _discovered_descriptor_cb, characteristic)); - // Wait for _discovered_descriptor_cb to be called multiple times until it's done. - status = _wait_for_discovery_step_done(); - if (status != BLE_HS_EDONE) { - CHECK_BLE_ERROR(status); - } + // Drain staged descriptors and build them on the VM task until done. + status = _drain_records(characteristic, _build_descriptor); + _check_discovery_status(status); } } } diff --git a/ports/espressif/common-hal/_bleio/Connection.h b/ports/espressif/common-hal/_bleio/Connection.h index 326eca02ecd..b04fdf7d8e6 100644 --- a/ports/espressif/common-hal/_bleio/Connection.h +++ b/ports/espressif/common-hal/_bleio/Connection.h @@ -22,6 +22,11 @@ typedef enum { PAIR_NOT_PAIRED, PAIR_WAITING, + // The peer is running LE Secure Connections numeric-comparison pairing and NimBLE is + // waiting for us to confirm the 6-digit value. Python reads it from + // Connection.numeric_comparison and answers with confirm_pairing(). This is a + // peer-driven, non-blocking path; the blocking pair() does not use it. + PAIR_WAITING_NUMCMP, PAIR_PAIRED, } pair_status_t; @@ -31,6 +36,15 @@ typedef enum { typedef struct { uint16_t conn_handle; bool is_central; + // True if user code initiated or accepted this connection: it connected in the + // central role, or a central answered user code's advertising. User-owned + // connections are disconnected when the VM resets; the BLE workflow connection + // is not user-owned and stays up. + bool user_owned; + // An indication we sent from characteristic_notify_indicate() awaits its + // acknowledgment or timeout. NimBLE allows one outstanding indication per + // connection, shared across all characteristics. + volatile bool indicate_outstanding; // Remote services discovered when this peripheral is acting as a client. mp_obj_list_t *remote_service_list; // The advertising data and scan response buffers are held by us, not by the SD, so we must @@ -40,7 +54,16 @@ typedef struct { // EDIV: Encrypted Diversifier: Identifies LTK during legacy pairing. uint16_t ediv; volatile pair_status_t pair_status; - uint8_t sec_status; // Internal security status. + // NimBLE status from the last BLE_GAP_EVENT_ENC_CHANGE: 0 on success, otherwise why + // pairing or encryption failed. Reported by pair(). + volatile int sec_status; + // The 6-digit LE Secure Connections numeric-comparison value stashed by + // BLE_GAP_EVENT_PASSKEY_ACTION. Only valid while pair_status == PAIR_WAITING_NUMCMP. + volatile uint32_t pairing_numcmp; + // True once the link is encrypted AND authenticated against MITM (numeric comparison + // or passkey entry completed). A plain encrypted "Just Works" link leaves this false. + // Surfaced to Python as Connection.authenticated. + volatile bool mitm_protected; mp_obj_t connection_obj; volatile bool conn_params_updating; uint16_t mtu; @@ -64,6 +87,7 @@ void bleio_connection_clear(bleio_connection_internal_t *self); int bleio_connection_event_cb(struct ble_gap_event *event, void *connection_in); +void bleio_check_connected(uint16_t conn_handle); 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); bleio_connection_internal_t *bleio_conn_handle_to_connection(uint16_t conn_handle); diff --git a/ports/espressif/common-hal/_bleio/Descriptor.c b/ports/espressif/common-hal/_bleio/Descriptor.c index 3f2870740f1..617e862206f 100644 --- a/ports/espressif/common-hal/_bleio/Descriptor.c +++ b/ports/espressif/common-hal/_bleio/Descriptor.c @@ -15,6 +15,8 @@ #include "shared-bindings/_bleio/Service.h" #include "shared-bindings/_bleio/UUID.h" +#include "common-hal/_bleio/Adapter.h" + #include "host/ble_att.h" 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) { @@ -33,22 +35,26 @@ void common_hal_bleio_descriptor_construct(bleio_descriptor_obj_t *self, bleio_c if (write_perm != SECURITY_MODE_NO_ACCESS) { self->flags |= BLE_ATT_F_WRITE; } - if (read_perm == SECURITY_MODE_ENC_WITH_MITM || write_perm == SECURITY_MODE_ENC_WITH_MITM || - read_perm == SECURITY_MODE_SIGNED_WITH_MITM || write_perm == SECURITY_MODE_SIGNED_WITH_MITM) { - mp_raise_NotImplementedError(MP_ERROR_TEXT("MITM security not supported")); - } + // MITM / LESC-MITM / SIGNED all map to the _AUTHEN flags (require an authenticated + // link); see the matching block in Characteristic.c. if (read_perm == SECURITY_MODE_ENC_NO_MITM) { self->flags |= BLE_ATT_F_READ_ENC; } - if (read_perm == SECURITY_MODE_SIGNED_NO_MITM) { + if (read_perm == SECURITY_MODE_ENC_WITH_MITM || read_perm == SECURITY_MODE_LESC_ENC_WITH_MITM || + read_perm == SECURITY_MODE_SIGNED_NO_MITM || read_perm == SECURITY_MODE_SIGNED_WITH_MITM) { self->flags |= BLE_ATT_F_READ_AUTHEN; } if (write_perm == SECURITY_MODE_ENC_NO_MITM) { self->flags |= BLE_ATT_F_WRITE_ENC; } - if (write_perm == SECURITY_MODE_SIGNED_NO_MITM) { + if (write_perm == SECURITY_MODE_ENC_WITH_MITM || write_perm == SECURITY_MODE_LESC_ENC_WITH_MITM || + write_perm == SECURITY_MODE_SIGNED_NO_MITM || write_perm == SECURITY_MODE_SIGNED_WITH_MITM) { self->flags |= BLE_ATT_F_WRITE_AUTHEN; } + if (bleio_attribute_security_mode_requires_mitm(read_perm) || + bleio_attribute_security_mode_requires_mitm(write_perm)) { + bleio_adapter_enable_mitm_pairing(); + } const mp_int_t max_length_max = BLE_ATT_ATTR_MAX_LEN; if (max_length < 0 || max_length > max_length_max) { diff --git a/ports/espressif/common-hal/_bleio/PacketBuffer.c b/ports/espressif/common-hal/_bleio/PacketBuffer.c index 1cc167cb5c8..77f19ad319f 100644 --- a/ports/espressif/common-hal/_bleio/PacketBuffer.c +++ b/ports/espressif/common-hal/_bleio/PacketBuffer.c @@ -15,6 +15,7 @@ #include "shared-bindings/_bleio/__init__.h" #include "shared-bindings/_bleio/Connection.h" #include "shared-bindings/_bleio/PacketBuffer.h" +#include "shared-bindings/microcontroller/__init__.h" #include "supervisor/shared/tick.h" #include "supervisor/shared/bluetooth/serial.h" @@ -23,6 +24,12 @@ #include "host/ble_att.h" +// The ringbuf and the pending outgoing buffers are shared with the nimble_host +// task, which preempts the CircuitPython task at arbitrary points, and ringbuf +// operations are not atomic, so guard the shared accesses with interrupts +// disabled. + +// Runs on the nimble_host task. void bleio_packet_buffer_extend(bleio_packet_buffer_obj_t *self, uint16_t conn_handle, const uint8_t *data, size_t len) { if (self->conn_handle != conn_handle) { return; @@ -34,6 +41,8 @@ void bleio_packet_buffer_extend(bleio_packet_buffer_obj_t *self, uint16_t conn_h return; } + common_hal_mcu_disable_interrupts(); + // Make room for the new value by dropping the oldest packets first. while (ringbuf_num_empty(&self->ringbuf) < len + sizeof(uint16_t)) { uint16_t packet_length; @@ -45,10 +54,18 @@ void bleio_packet_buffer_extend(bleio_packet_buffer_obj_t *self, uint16_t conn_h } ringbuf_put_n(&self->ringbuf, (uint8_t *)&len, sizeof(uint16_t)); ringbuf_put_n(&self->ringbuf, data, len); + + common_hal_mcu_enable_interrupts(); } static int packet_buffer_on_ble_client_evt(struct ble_gap_event *event, void *param); static int queue_next_write(bleio_packet_buffer_obj_t *self); +static void packet_buffer_retry_send(void *data); + +// Interval to wait between send attempts when the outgoing mbuf pool is +// exhausted. The pool drains as fast as the radio sends: a handful of packets +// per connection interval, which is typically tens of milliseconds. +#define RETRY_INTERVAL_MS (10) static int _write_cb(uint16_t conn_handle, const struct ble_gatt_error *error, @@ -61,80 +78,166 @@ static int _write_cb(uint16_t conn_handle, #endif } bleio_packet_buffer_obj_t *self = (bleio_packet_buffer_obj_t *)arg; + // Whether or not the write succeeded, it is no longer awaiting a response. On + // failure NimBLE already consumed the data, so there is nothing to retry. + self->packet_queued = false; queue_next_write(self); return 0; } +// Try to send the data waiting in the pending buffer, if any. May be called +// from the CircuitPython task or from the nimble_host task, +// which preempts the CircuitPython task. +// BLE_HS_ENOMEM means we are out of mbufs because the radio hasn't drained +// the outgoing queue yet. That is expected, not an error: keep +// the data: the background callback scheduled below and the wait loops in +// write() and flush() will retry sending. +// On other errors drop the data. static int queue_next_write(bleio_packet_buffer_obj_t *self) { - // Queue up the next outgoing buffer. We use two, one that has been passed to the SD for - // transmission (when packet_queued is true) and the other is `pending` and can still be - // modified. By primarily appending to the `pending` buffer we can reduce the protocol overhead - // of the lower level link and ATT layers. - self->packet_queued = false; - if (self->pending_size > 0) { - uint16_t conn_handle = self->conn_handle; - int err_code = NIMBLE_OK; - if (self->client) { - if (self->write_type == CHAR_PROP_WRITE_NO_RESPONSE) { - err_code = ble_gattc_write_no_rsp_flat(conn_handle, - self->characteristic->handle, - self->outgoing[self->pending_index], - self->pending_size); - // We don't set packet_queued because NimBLE will buffer our - // outgoing packets. - } else { - err_code = ble_gattc_write_flat(conn_handle, - self->characteristic->handle, - self->outgoing[self->pending_index], - self->pending_size, - _write_cb, self); - self->pending_index = (self->pending_index + 1) % 2; - self->packet_queued = true; - } + // Remember the current time if a previous send failed. + uint64_t now_ms = 0; + if (self->last_failed_ms != 0) { + now_ms = supervisor_ticks_ms64(); + } + common_hal_mcu_disable_interrupts(); + if (self->send_in_progress || self->packet_queued || + self->pending_size == 0 || + self->conn_handle == BLEIO_HANDLE_INVALID) { + // Succeed if: + // - there is nothing to send + // - a packet is already awaiting its completion event + // - another send call is already in progress (including the + // synchronous BLE_GAP_EVENT_NOTIFY_TX that our own notify and + // indicate calls below raise on this very stack). + common_hal_mcu_enable_interrupts(); + return NIMBLE_OK; + } + if (self->last_failed_ms != 0 && + (now_ms == 0 || now_ms - self->last_failed_ms < RETRY_INTERVAL_MS)) { + // Don't try before retry interval expires: the radio can only go so fast. + // Schedule a retry for later. + common_hal_mcu_enable_interrupts(); + background_callback_add(&self->retry_send_callback, packet_buffer_retry_send, self); + return BLE_HS_ENOMEM; + } + // Claim the pending buffer. While send_in_progress is set, writers wait + // instead of appending to the buffer. Other callers of this function return above, + // so the buffer contents stay stable during the send call even though + // interrupts are enabled again while it runs. + self->send_in_progress = true; + // A client Write with Response or an Indicate gets a completion event (a + // write response or an indicate acknowledgment) that calls back here to + // send whatever accumulates in the meantime. Mark such a packet as in + // flight *before* submitting it: if this task is preempted for long enough, + // the completion can arrive before the code after the send call runs, + // and it must find the flag already set so it can clear it. + bool is_completion_type = self->write_type == CHAR_PROP_WRITE || + self->write_type == CHAR_PROP_INDICATE; + self->packet_queued = is_completion_type; + uint16_t conn_handle = self->conn_handle; + uint16_t attr_handle = self->characteristic->handle; + const uint8_t *data = (const uint8_t *)self->outgoing[0]; + uint16_t data_len = self->pending_size; + common_hal_mcu_enable_interrupts(); + + int err_code; + if (self->client) { + if (self->write_type == CHAR_PROP_WRITE_NO_RESPONSE) { + // Copies the data into an mbuf before returning. No completion + // callback follows; NimBLE buffers the outgoing packet itself. + err_code = ble_gattc_write_no_rsp_flat(conn_handle, attr_handle, + data, data_len); } else { - // Allocate an mbuf because the functions below consume it. - struct os_mbuf *om = ble_hs_mbuf_from_flat(self->outgoing[self->pending_index], self->pending_size); - if (om == NULL) { - // We may not have any more mbufs if BLE busy. It isn't a problem (yet) so we'll - // just skip queueing for now. - return BLE_HS_ENOMEM; - } - size_t pending_size = self->pending_size; - self->pending_size = 0; - if (self->write_type == CHAR_PROP_NOTIFY) { - err_code = ble_gatts_notify_custom(conn_handle, self->characteristic->handle, om); - } else if (self->write_type == CHAR_PROP_INDICATE) { - err_code = ble_gatts_indicate_custom(conn_handle, self->characteristic->handle, om); - self->pending_index = (self->pending_index + 1) % 2; - self->packet_queued = true; - } else { - // Placeholder error. - err_code = BLE_HS_EUNKNOWN; - } - // Undo our queueing if it fails. We need to do it early because we may recurse back - // to here from the above ble_gatts functions. - if (err_code != NIMBLE_OK) { - self->pending_index = (self->pending_index + 1) % 2; - self->packet_queued = false; - self->pending_size = pending_size; - } + // _write_cb will be called only if the write was actually queued. + err_code = ble_gattc_write_flat(conn_handle, attr_handle, + data, data_len, _write_cb, self); } + } else { + // Allocate an mbuf because the functions below consume it, on + // success and on failure. + struct os_mbuf *om = ble_hs_mbuf_from_flat(data, data_len); + if (om == NULL) { + err_code = BLE_HS_ENOMEM; + } else if (self->write_type == CHAR_PROP_NOTIFY) { + // Raises BLE_GAP_EVENT_NOTIFY_TX on this stack before returning, + // on success and on failure. There is no later completion event + // for a notification. + err_code = ble_gatts_notify_custom(conn_handle, attr_handle, om); + } else if (self->write_type == CHAR_PROP_INDICATE) { + // The acknowledgment (or a timeout) will raise + // BLE_GAP_EVENT_NOTIFY_TX later, from the nimble_host task. + err_code = ble_gatts_indicate_custom(conn_handle, attr_handle, om); + } else { + // Placeholder error. + err_code = BLE_HS_EUNKNOWN; + } + } + + uint64_t fail_ms = 0; + if (err_code == BLE_HS_ENOMEM) { + fail_ms = supervisor_ticks_ms64(); + } + common_hal_mcu_disable_interrupts(); + self->send_in_progress = false; + if (self->conn_handle != conn_handle) { + // Disconnected or unsubscribed during the send. The event handler + // already discarded the pending data; make sure nothing looks like a + // send in progress to the new connection, if any. + self->packet_queued = false; + common_hal_mcu_enable_interrupts(); + return err_code; + } + if (err_code == NIMBLE_OK) { + // NimBLE copied the data, so the buffer is immediately reusable, + // even while a write with response or an indicate is still in + // flight: new writes coalesce in it until the completion event. + // Don't touch packet_queued: it was set before the send, and the + // completion event may already have cleared it. self->pending_size = 0; - if (err_code != NIMBLE_OK) { - // On error, simply skip updating the pending buffers so that the next HVC or WRITE - // complete event triggers another attempt. - return err_code; + self->last_failed_ms = 0; + } else { + // Nothing was queued, so no completion event will come. + self->packet_queued = false; + if (err_code == BLE_HS_ENOMEM) { + // Out of mbufs: normal while the radio works through the outgoing + // queue. Keep the data and retry from the background, + // because a failed send gets no completion event to prompt + // another attempt. Re-adding a queued callback does nothing. + self->last_failed_ms = fail_ms; + background_callback_add(&self->retry_send_callback, packet_buffer_retry_send, self); + } else { + // A real error, such as a dropped connection or an ATT failure. + // Drop the data, as before. + self->pending_size = 0; + self->last_failed_ms = 0; } } - return NIMBLE_OK; + common_hal_mcu_enable_interrupts(); + return err_code; } -// This is called from the nimble task. *Not* CircuitPython's. +// Runs as a background callback after a send failed for lack of mbufs. +static void packet_buffer_retry_send(void *data) { + bleio_packet_buffer_obj_t *self = (bleio_packet_buffer_obj_t *)data; + if (common_hal_bleio_packet_buffer_deinited(self)) { + return; + } + // Reschedules this callback (in queue_next_write()) if still out of mbufs. + queue_next_write(self); +} + +// This is usually called from the nimble task, *not* CircuitPython's. +// BLE_GAP_EVENT_NOTIFY_TX is also raised synchronously, on the task that +// called into NimBLE, by our own sends in queue_next_write(). static int packet_buffer_on_ble_client_evt(struct ble_gap_event *event, void *param) { bleio_packet_buffer_obj_t *self = (bleio_packet_buffer_obj_t *)param; if (event->type == BLE_GAP_EVENT_DISCONNECT && self->conn_handle == event->disconnect.conn.conn_handle) { self->conn_handle = BLEIO_HANDLE_INVALID; + // Discard the pending state so stale data can't be sent into a + // later connection or subscription. + self->pending_size = 0; + self->packet_queued = false; return false; } if (event->type == BLE_GAP_EVENT_SUBSCRIBE) { @@ -142,16 +245,49 @@ static int packet_buffer_on_ble_client_evt(struct ble_gap_event *event, void *pa self->conn_handle = event->subscribe.conn_handle; } else if (self->conn_handle == event->subscribe.conn_handle && event->subscribe.cur_notify == 0 && event->subscribe.cur_indicate == 0) { self->conn_handle = BLEIO_HANDLE_INVALID; + // Discard the pending state so stale data can't be sent into a + // later subscription. + self->pending_size = 0; + self->packet_queued = false; } return false; } if (event->type == BLE_GAP_EVENT_NOTIFY_TX) { if (self->conn_handle == event->notify_tx.conn_handle && self->characteristic->handle == event->notify_tx.attr_handle) { - if (event->notify_tx.indication == 1 && event->notify_tx.status == 0) { - // The indicate has been queued. + if (event->notify_tx.indication == 1) { + if (event->notify_tx.status == 0) { + // The indicate has been queued. This event is raised + // synchronously inside our own indicate call. + return false; + } + if (event->notify_tx.status == BLE_HS_EDONE || + event->notify_tx.status == BLE_HS_ETIMEOUT) { + // Acknowledged or timed out: the indicate is no longer + // awaiting a response. These statuses come only from the nimble_host + // task later on, never from inside our own send call, so + // clear packet_queued even if a new claim is in progress. + self->packet_queued = false; + if (!self->send_in_progress) { + // Send any data that accumulated in the meantime. + queue_next_write(self); + } + return false; + } + // Any other status is either our own synchronous submission + // failure, handled by the return code in queue_next_write(), + // or a failure that comes with a disconnect, which discards + // the pending state. return false; } - queue_next_write(self); + // A notification transmission was attempted (status 0 on + // success). It was raised synchronously inside a notify call: + // ours, in queue_next_write(), which acts on the result code + // itself (send_in_progress is set), or someone else's on this + // characteristic, which we can use as a prompt to send anything + // that is waiting. + if (!self->send_in_progress) { + queue_next_write(self); + } return false; } } @@ -185,10 +321,13 @@ void _common_hal_bleio_packet_buffer_construct( } self->packet_queued = false; - self->pending_index = 0; + self->send_in_progress = false; self->pending_size = 0; + self->last_failed_ms = 0; self->outgoing[0] = outgoing_buffer1; self->outgoing[1] = outgoing_buffer2; + // Don't touch retry_send_callback: for a statically allocated buffer that + // is being reconstructed, it may still be on the background callback list. if (static_handler_entry != NULL) { ble_event_add_handler_entry((ble_event_handler_entry_t *)static_handler_entry, packet_buffer_on_ble_client_evt, self); @@ -240,17 +379,22 @@ void common_hal_bleio_packet_buffer_construct( uint32_t *incoming_buffer = NULL; if (incoming) { incoming_buffer_size = buffer_size * (sizeof(uint16_t) + max_packet_size); - incoming_buffer = m_malloc(incoming_buffer_size); + incoming_buffer = m_malloc_without_collect(incoming_buffer_size); } uint32_t *outgoing1 = NULL; uint32_t *outgoing2 = NULL; if (outgoing) { - outgoing1 = m_malloc(max_packet_size); + outgoing1 = m_malloc_without_collect(max_packet_size); // Only allocate the second buffer if we are doing writes with responses. // Without responses, we just write as quickly as we can. + // + // TODO: this port never reads outgoing[1]. NimBLE copies the data at send + // time, so one buffer can be refilled immediately, unlike the nordic + // SoftDevice which keeps the caller's buffer until TX completes. Kept + // allocated so that reintroducing two-buffer use here is not a bug. if (outgoing == CHAR_PROP_WRITE || outgoing == CHAR_PROP_INDICATE) { - outgoing2 = m_malloc(max_packet_size); + outgoing2 = m_malloc_without_collect(max_packet_size); } } _common_hal_bleio_packet_buffer_construct(self, characteristic, @@ -264,6 +408,8 @@ mp_int_t common_hal_bleio_packet_buffer_readinto(bleio_packet_buffer_obj_t *self return 0; } + common_hal_mcu_disable_interrupts(); + // 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)); @@ -282,6 +428,8 @@ mp_int_t common_hal_bleio_packet_buffer_readinto(bleio_packet_buffer_obj_t *self ret = packet_length; } + common_hal_mcu_enable_interrupts(); + return ret; } @@ -308,38 +456,54 @@ mp_int_t common_hal_bleio_packet_buffer_write(bleio_packet_buffer_obj_t *self, c } outgoing_packet_length = MIN(outgoing_packet_length, self->max_packet_size); - if (len + self->pending_size > (size_t)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 != BLEIO_HANDLE_INVALID && - !mp_hal_is_interrupted()) { - RUN_BACKGROUND_TASKS; + size_t num_bytes_written = 0; + + // Append the data to the pending packet, waiting for room if it is full. + // The append must happen with interrupts disabled, with the connection + // still up and with no send call in progress (the nimble_host task can + // start one at any point), so check those conditions inside the critical + // section and retry until they all hold at once. + while (true) { + if (mp_hal_is_interrupted()) { + return -1; } + common_hal_mcu_disable_interrupts(); + if (self->conn_handle == BLEIO_HANDLE_INVALID) { + common_hal_mcu_enable_interrupts(); + return -1; + } + if (!self->send_in_progress && + len + self->pending_size <= (size_t)outgoing_packet_length) { + // Append below, still inside the critical section. + break; + } + common_hal_mcu_enable_interrupts(); + // No room for data yet. Retry the pending packet ourselves: a send that + // failed for lack of mbufs gets no completion event to prompt + // another attempt, and if we were called from a background callback + // (as the BLE workflow does), RUN_BACKGROUND_TASKS below cannot + // re-enter background callbacks to do it for us. + queue_next_write(self); + RUN_BACKGROUND_TASKS; } - if (self->conn_handle == BLEIO_HANDLE_INVALID || - mp_hal_is_interrupted()) { - return -1; - } - - size_t num_bytes_written = 0; - uint32_t *pending = self->outgoing[self->pending_index]; + uint8_t *pending = (uint8_t *)self->outgoing[0]; if (self->pending_size == 0) { memcpy(pending, header, header_len); self->pending_size += header_len; num_bytes_written += header_len; } - memcpy(((uint8_t *)pending) + self->pending_size, data, len); + memcpy(pending + self->pending_size, data, len); self->pending_size += len; num_bytes_written += len; - // If no writes are queued then sneak in this data. - if (!self->packet_queued) { - // This will queue up the packet even if it can't send immediately. - queue_next_write(self); - } + common_hal_mcu_enable_interrupts(); + + // Send now. This is a no-op if a packet is already awaiting its completion + // event; the completion will send the data instead. + queue_next_write(self); + return num_bytes_written; } @@ -423,6 +587,10 @@ void common_hal_bleio_packet_buffer_flush(bleio_packet_buffer_obj_t *self) { self->packet_queued) && self->conn_handle != BLEIO_HANDLE_INVALID && !mp_hal_is_interrupted()) { + // Retry sends that failed for lack of mbufs ourselves: they get no + // completion event, and background callbacks can't run if we were + // called from one (as the BLE workflow does). + queue_next_write(self); RUN_BACKGROUND_TASKS; } } @@ -435,9 +603,15 @@ void common_hal_bleio_packet_buffer_deinit(bleio_packet_buffer_obj_t *self) { if (common_hal_bleio_packet_buffer_deinited(self)) { return; } + // Take the packet buffer off the event list before changing anything + // inside the object. + ble_event_remove_handler(packet_buffer_on_ble_client_evt, self); bleio_characteristic_clear_observer(self->characteristic); self->characteristic = NULL; - ble_event_remove_handler(packet_buffer_on_ble_client_evt, self); + // A still-queued retry_send_callback checks deinited(), so it sees the + // NULL characteristic and does nothing. + self->pending_size = 0; + self->packet_queued = false; ringbuf_deinit(&self->ringbuf); } diff --git a/ports/espressif/common-hal/_bleio/PacketBuffer.h b/ports/espressif/common-hal/_bleio/PacketBuffer.h index 0ab084c5b01..b555cf2632f 100644 --- a/ports/espressif/common-hal/_bleio/PacketBuffer.h +++ b/ports/espressif/common-hal/_bleio/PacketBuffer.h @@ -9,24 +9,41 @@ #include "py/ringbuf.h" #include "shared-bindings/_bleio/Characteristic.h" #include "common-hal/_bleio/ble_events.h" +#include "supervisor/background_callback.h" typedef struct { mp_obj_base_t base; bleio_characteristic_obj_t *characteristic; // Ring buffer storing consecutive incoming values. 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. + // This is the outgoing packet being assembled. NimBLE copies the data at send + // time, so we only need a single buffer. The second entry exists here but is + // unused: the shared constructors expect two buffers. uint32_t *outgoing[2]; + // Number of bytes waiting in outgoing[0] to be sent. 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; - bool packet_queued; + // True while a client Write with Response or an Indicate is awaiting its + // completion event: a response or acknowledgment from the peer. Not used for + // notifications, whose NOTIFY_TX arrives inside the send call itself. + // Its completion event sends any data that accumulated in the meantime. + volatile bool packet_queued; + // True while a task is inside a send call in queue_next_write(). Writers + // wait instead of appending, and other send attempts (including the + // synchronous BLE_GAP_EVENT_NOTIFY_TX raised inside our own notify and + // indicate calls) return without doing anything. + volatile bool send_in_progress; + // Retries sends that failed for lack of mbufs; they get no completion + // event, so nothing else would try again. + background_callback_t retry_send_callback; + // Time of the last send that failed for lack of mbufs, to pace retries + // while the radio drains the pool. Zero when the last send succeeded. + uint64_t last_failed_ms; } bleio_packet_buffer_obj_t; typedef ble_event_handler_entry_t ble_event_handler_t; diff --git a/ports/espressif/common-hal/_bleio/Service.c b/ports/espressif/common-hal/_bleio/Service.c index 3afbeb2a684..fedfacd307e 100644 --- a/ports/espressif/common-hal/_bleio/Service.c +++ b/ports/espressif/common-hal/_bleio/Service.c @@ -5,8 +5,10 @@ // // SPDX-License-Identifier: MIT +#include "py/gc.h" #include "py/runtime.h" #include "common-hal/_bleio/__init__.h" +#include "shared-bindings/_bleio/__init__.h" #include "shared-bindings/_bleio/Characteristic.h" #include "shared-bindings/_bleio/Descriptor.h" #include "shared-bindings/_bleio/Service.h" @@ -14,6 +16,51 @@ #include "host/ble_gatt.h" +// NimBLE's GATT table keeps raw pointers into a registered local service and +// everything under it: the chr_defs array lives inside the service object, each +// characteristic and descriptor is an access-callback argument, and every UUID +// is referenced by address. Collecting any of them would leave those dangling, +// so retain a heap Service here for as long as NimBLE knows about it. +// Retaining the service is enough because it holds its characteristics, +// which hold their descriptors. Services in static storage, like the BLE workflow's, +// cannot be collected and are skipped. +static bleio_service_obj_t *_retained_services; + +static void service_retain(bleio_service_obj_t *self) { + if (!gc_ptr_on_heap((void *)self)) { + return; + } + for (bleio_service_obj_t *it = _retained_services; it != NULL; it = it->next_retained) { + if (it == self) { + return; + } + } + self->next_retained = _retained_services; + _retained_services = self; +} + +static void service_release(bleio_service_obj_t *self) { + bleio_service_obj_t **prev = &_retained_services; + for (bleio_service_obj_t *it = *prev; it != NULL; it = it->next_retained) { + if (it == self) { + *prev = it->next_retained; + it->next_retained = NULL; + return; + } + prev = &it->next_retained; + } +} + +void bleio_service_forget_retained(void) { + _retained_services = NULL; +} + +// Mark the retained services. One pointer is enough: the GC traces +// next_retained through the rest of the chain from the head. +void bleio_service_gc_collect(void) { + gc_collect_ptr(_retained_services); +} + 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; @@ -27,6 +74,8 @@ uint32_t _common_hal_bleio_service_construct(bleio_service_obj_t *self, bleio_uu self->service_def.includes = NULL; self->service_def.characteristics = self->chr_defs; self->next_svc_type = 0; + self->next_retained = NULL; + self->registered = false; // Don't add the service yet because we don't have any characteristics. return 0; @@ -38,9 +87,21 @@ void common_hal_bleio_service_construct(bleio_service_obj_t *self, bleio_uuid_ob } void common_hal_bleio_service_deinit(bleio_service_obj_t *self) { - // Delete the old version of the service. - if (self->characteristic_list->len > 1) { + // Take the service out of NimBLE's GATT table first, so nothing torn down + // below is still reachable from it. + if (self->registered) { ble_gatts_delete_svc(&self->uuid->nimble_ble_uuid.u); + self->registered = false; + } + // NimBLE no longer refers to this service, so stop retaining it, and deinit + // the characteristics: a local one that can notify or indicate holds an + // event handler that must come off the event list with it. + service_release(self); + if (!self->is_remote) { + for (size_t i = 0; i < self->characteristic_list->len; i++) { + common_hal_bleio_characteristic_deinit( + MP_OBJ_TO_PTR(self->characteristic_list->items[i])); + } } self->service_def.type = 0; } @@ -50,6 +111,7 @@ void bleio_service_from_connection(bleio_service_obj_t *self, mp_obj_t connectio self->uuid = NULL; self->characteristic_list = mp_obj_new_list(0, NULL); self->is_remote = true; + self->registered = false; self->is_secondary = false; self->connection = connection; } @@ -70,13 +132,18 @@ bool common_hal_bleio_service_get_is_secondary(bleio_service_obj_t *self) { return self->is_secondary; } -// Used by characteristics to update their descriptors. +// Register the service, or register it again after its definition changed: +// NimBLE cannot amend a service that is already in its GATT table, so the old +// version is deleted and the whole service added again. void bleio_service_readd(bleio_service_obj_t *self) { - // Delete the old version of the service. - if (self->characteristic_list->len > 1) { + if (self->registered) { ble_gatts_delete_svc(&self->uuid->nimble_ble_uuid.u); + self->registered = false; } CHECK_NIMBLE_ERROR(ble_gatts_add_dynamic_svcs(&self->service_def)); + self->registered = true; + // NimBLE now refers to this service and everything under it. + service_retain(self); } @@ -84,17 +151,18 @@ void common_hal_bleio_service_add_characteristic(bleio_service_obj_t *self, bleio_characteristic_obj_t *characteristic, mp_buffer_info_t *initial_value_bufinfo, const char *user_description) { + // Don't overflow chr_defs table. + size_t i = self->characteristic_list->len; + if (i >= MAX_CHARACTERISTIC_COUNT) { + mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Too many %q"), MP_QSTR_characteristics); + } + mp_obj_list_append(self->characteristic_list, MP_OBJ_FROM_PTR(characteristic)); if (user_description != NULL) { mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("Invalid %q"), MP_QSTR_user_description); } - // Delete the old version of the service. - if (self->characteristic_list->len > 1) { - ble_gatts_delete_svc(&self->uuid->nimble_ble_uuid.u); - } - size_t i = self->characteristic_list->len - 1; self->chr_defs[i].uuid = &characteristic->uuid->nimble_ble_uuid.u; self->chr_defs[i].access_cb = bleio_characteristic_access_cb; self->chr_defs[i].arg = characteristic; @@ -106,5 +174,5 @@ void common_hal_bleio_service_add_characteristic(bleio_service_obj_t *self, self->chr_defs[i + 1].uuid = NULL; characteristic->chr_def = &self->chr_defs[i]; - CHECK_NIMBLE_ERROR(ble_gatts_add_dynamic_svcs(&self->service_def)); + bleio_service_readd(self); } diff --git a/ports/espressif/common-hal/_bleio/Service.h b/ports/espressif/common-hal/_bleio/Service.h index 936627a00ee..d003a96cafa 100644 --- a/ports/espressif/common-hal/_bleio/Service.h +++ b/ports/espressif/common-hal/_bleio/Service.h @@ -21,6 +21,9 @@ typedef struct bleio_service_obj { // True if created during discovery. bool is_remote; bool is_secondary; + // True while NimBLE's GATT table holds this service: it must be deleted + // before the definition is changed or the service is torn down. + bool registered; bleio_uuid_obj_t *uuid; // The connection object is set only when this is a remote service. // A local service doesn't know the connection. @@ -33,7 +36,17 @@ typedef struct bleio_service_obj { // Include a spot for terminating the service def array. uint8_t next_svc_type; struct ble_gatt_chr_def chr_defs[MAX_CHARACTERISTIC_COUNT + 1]; + // Link in the list of services retained while NimBLE's GATT table refers + // to them; see Service.c. NULL when not on that list. + struct bleio_service_obj *next_retained; } bleio_service_obj_t; void bleio_service_from_connection(bleio_service_obj_t *self, mp_obj_t connection); void bleio_service_readd(bleio_service_obj_t *self); + +// Stop retaining every service. Call when the heap they live on is about to go +// away. +void bleio_service_forget_retained(void); + +// Mark the retained services as reachable during a GC pass. +void bleio_service_gc_collect(void); diff --git a/ports/espressif/common-hal/_bleio/__init__.c b/ports/espressif/common-hal/_bleio/__init__.c index f3637a8fddb..2a0fa237dac 100644 --- a/ports/espressif/common-hal/_bleio/__init__.c +++ b/ports/espressif/common-hal/_bleio/__init__.c @@ -24,36 +24,108 @@ #include "common-hal/_bleio/__init__.h" #include "common-hal/_bleio/ble_events.h" +#include "services/gatt/ble_svc_gatt.h" + #include "nvs_flash.h" +// State for the current GATT client read or write. The NimBLE callbacks run on the +// nimble_host task and record the result here, under _completion_mutex. +// +// We stop waiting after 2 seconds, but NimBLE waits 30 seconds for a response, so a +// callback can arrive after its caller has returned. Each request gets a new +// sequence number, passed as the callback argument, and callbacks for older requests +// are ignored. Read data is staged in _read_buf rather than written to the caller's +// buffer, which may no longer exist. +// +// After a timeout, NimBLE still has the request outstanding on that connection. It +// holds later requests on the connection until a response arrives or it disconnects +// at 30 seconds, so those requests time out too. The stale requests also occupy +// NimBLE's GATT procedure pool (CONFIG_BT_NIMBLE_GATT_MAX_PROCS), so new ones can +// fail with BLE_HS_ENOMEM until then. +static portMUX_TYPE _completion_mutex = portMUX_INITIALIZER_UNLOCKED; +static uint32_t _completion_seq; +// A status of 0 means success, so it can't also mean "still waiting". static volatile int _completion_status; -static uint64_t _timeout_start_time; +static volatile bool _completion_done; +static uint8_t _read_buf[BLE_ATT_ATTR_MAX_LEN]; +static uint16_t _read_len; background_callback_t bleio_background_callback; -void bleio_user_reset() { +void bleio_user_reset(void) { + if (!common_hal_bleio_adapter_get_enabled(&common_hal_bleio_adapter_obj)) { + return; + } // Stop any user scanning or advertising. common_hal_bleio_adapter_stop_scan(&common_hal_bleio_adapter_obj); common_hal_bleio_adapter_stop_advertising(&common_hal_bleio_adapter_obj); + // Disconnect the connections that user code initiated or accepted with its own + // advertising. Keep the BLE workflow connection if present. + // + // Remove each connection's pointers into the VM heap before disconnecting: + // the heap is about to go away, and a disconnect completes asynchronously. + for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) { + bleio_connection_internal_t *connection = &bleio_connections[i]; + connection->connection_obj = mp_const_none; + connection->remote_service_list = NULL; + if (connection->conn_handle != BLEIO_HANDLE_INVALID && connection->user_owned) { + common_hal_bleio_connection_disconnect(connection); + } + } + + // Now clear the adapter's remaining heap pointer, since it will be stale + // when the VM stops. + common_hal_bleio_adapter_obj.connection_objs = NULL; + + // Also clean up event handlers that are on the heap. ble_event_remove_heap_handlers(); + // And stop retaining heap services, whose characteristics' handler entries + // the call above just removed. + bleio_service_forget_retained(); // Maybe start advertising the BLE workflow. supervisor_bluetooth_background(); } // Turn off BLE on a reset or reload. -void bleio_reset() { +void bleio_reset(void) { // Set this explicitly to save data. if (!common_hal_bleio_adapter_get_enabled(&common_hal_bleio_adapter_obj)) { return; } + // The stop/start cycle below clears user-created services from the GATT + // table, and drops every connection, BLE workflow included. So run it + // only when user code created services. All other user BLE state has already + // been torn down individually by bleio_user_reset(). + // + // TODO: ESP-IDF NimBLE can delete individual services (ble_gatts_delete_svc(), + // used in Service.c), so bleio_user_reset() could delete user services one by + // one and never restart the BLE stack at all. For now this port matches + // nordic, whose SoftDevice can only clear services with a full cycle. + if (!bleio_get_user_services_created()) { + return; + } + bleio_clear_user_services_created(); + supervisor_stop_bluetooth(); ble_event_reset(); bleio_adapter_reset(&common_hal_bleio_adapter_obj); common_hal_bleio_adapter_set_enabled(&common_hal_bleio_adapter_obj, false); supervisor_start_bluetooth(); + + // The stop/start above rebuilt the GATT table, so now any bonded peers' cached + // tables are stale. Signal Service Changed over the whole handle range. + // Without Service Changed, a bonded host trusts its cache indefinitely and can + // look up characteristics at stale handles. + // + // supervisor_start_bluetooth() restarts the stack only when the BLE workflow + // is enabled. If it did not, NimBLE is stopped and its GATT server state is + // gone, so we can't signal anything, and if we tried, we'd cause a crash. + if (common_hal_bleio_adapter_get_enabled(&common_hal_bleio_adapter_obj)) { + ble_svc_gatt_changed(0x0001, 0xffff); + } } // The singleton _bleio.Adapter object, bound to _bleio.adapter @@ -84,6 +156,7 @@ void common_hal_bleio_init(void) { void common_hal_bleio_gc_collect(void) { bleio_adapter_gc_collect(&common_hal_bleio_adapter_obj); + bleio_service_gc_collect(); } void check_nimble_error(int rc, const char *file, size_t line) { @@ -109,12 +182,12 @@ void check_nimble_error(int rc, const char *file, size_t line) { default: #if CIRCUITPY_VERBOSE_BLE || CIRCUITPY_DEBUG if (file) { - mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Unknown system firmware error at %s:%d: %d"), file, line, rc); + mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Unknown BLE error at %s:%d: 0x%04x"), file, line, rc); } #else (void)file; (void)line; - mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Unknown system firmware error: %d"), rc); + mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Unknown BLE error: 0x%04x"), rc); #endif break; @@ -127,21 +200,38 @@ void check_ble_error(int error_code, const char *file, size_t line) { return; } switch (error_code) { + case BLE_HS_ATT_ERR(BLE_ATT_ERR_READ_NOT_PERMITTED): + mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("%q not permitted"), MP_QSTR_read); + return; + case BLE_HS_ATT_ERR(BLE_ATT_ERR_WRITE_NOT_PERMITTED): + mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("%q not permitted"), MP_QSTR_write); + return; case BLE_HS_ATT_ERR(BLE_ATT_ERR_INSUFFICIENT_AUTHEN): mp_raise_bleio_SecurityError(MP_ERROR_TEXT("Insufficient authentication")); return; + case BLE_HS_ATT_ERR(BLE_ATT_ERR_INSUFFICIENT_AUTHOR): + mp_raise_bleio_SecurityError(MP_ERROR_TEXT("Insufficient authorization")); + return; case BLE_HS_ATT_ERR(BLE_ATT_ERR_INSUFFICIENT_ENC): + case BLE_HS_ATT_ERR(BLE_ATT_ERR_INSUFFICIENT_KEY_SZ): mp_raise_bleio_SecurityError(MP_ERROR_TEXT("Insufficient encryption")); return; + case BLE_HS_ATT_ERR(BLE_ATT_ERR_INVALID_ATTR_VALUE_LEN): + mp_arg_error_invalid(MP_QSTR_length); + return; default: + if (error_code > BLE_HS_ERR_ATT_BASE && error_code < BLE_HS_ERR_HCI_BASE) { + // Some other ATT error from the peer. + mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Unknown gatt error: 0x%04x"), error_code); + } #if CIRCUITPY_VERBOSE_BLE || CIRCUITPY_DEBUG if (file) { - mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Unknown BLE error at %s:%d: %d"), file, line, error_code); + mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Unknown BLE error at %s:%d: 0x%04x"), file, line, error_code); } #else (void)file; (void)line; - mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Unknown BLE error: %d"), error_code); + mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Unknown BLE error: 0x%04x"), error_code); #endif break; @@ -155,74 +245,97 @@ void check_notify(BaseType_t result) { mp_raise_msg(&mp_type_TimeoutError, NULL); } -void common_hal_bleio_check_connected(uint16_t conn_handle) { +void bleio_check_connected(uint16_t conn_handle) { if (conn_handle == BLEIO_HANDLE_INVALID) { mp_raise_ConnectionError(MP_ERROR_TEXT("Not connected")); } } -static void _reset_completion_status(void) { +// Start a new request, which makes callbacks for any earlier request stale. +// Returns the sequence number to pass as the NimBLE callback argument. +static void *_start_request(void) { + portENTER_CRITICAL(&_completion_mutex); + _completion_seq++; _completion_status = 0; + _completion_done = false; + _read_len = 0; + const uint32_t seq = _completion_seq; + portEXIT_CRITICAL(&_completion_mutex); + return (void *)(uintptr_t)seq; +} + +// Record a callback's status if it is for the current request. Returns true if so. +// Call with _completion_mutex held. +static bool _complete_request(void *arg, int status) { + if ((uint32_t)(uintptr_t)arg != _completion_seq) { + return false; + } + _completion_status = status; + _completion_done = true; + return true; } -// Wait for a status change, recorded in a callback. -// Try twice because sometimes we get a BLE_HS_EAGAIN. -// Maybe we should try more than twice. +// Wait for a callback to record a completion status, and return that status. +// Return BLE_HS_ETIMEOUT if no callback arrives in time. If interrupted, return 0 +// with _completion_done still false, so the pending KeyboardInterrupt is raised +// instead of an error. static int _wait_for_completion(uint32_t timeout_msecs) { - for (int tries = 1; tries <= 2; tries++) { - _timeout_start_time = common_hal_time_monotonic_ms(); - while ((_completion_status == 0) && - (common_hal_time_monotonic_ms() < _timeout_start_time + timeout_msecs) && - !mp_hal_is_interrupted()) { - RUN_BACKGROUND_TASKS; + const uint64_t timeout_time_ms = common_hal_time_monotonic_ms() + timeout_msecs; + while (!_completion_done) { + if (mp_hal_is_interrupted()) { + return 0; } - if (_completion_status != BLE_HS_EAGAIN) { - // Quit, because either the status is either zero (OK) or it's an error. - break; + if (common_hal_time_monotonic_ms() >= timeout_time_ms) { + return BLE_HS_ETIMEOUT; } + RUN_BACKGROUND_TASKS; } return _completion_status; } -typedef struct { - uint8_t *buf; - uint16_t len; -} _read_info_t; +// Raise an exception for a nonzero completion status. Statuses from +// BLE_HS_ERR_ATT_BASE up are ATT errors from the peer, such as insufficient +// encryption, which check_ble_error() maps to SecurityError. +static void _check_completion_status(int status) { + if (status < BLE_HS_ERR_ATT_BASE) { + CHECK_NIMBLE_ERROR(status); + return; + } + CHECK_BLE_ERROR(status); +} static int _read_cb(uint16_t conn_handle, const struct ble_gatt_error *error, struct ble_gatt_attr *attr, void *arg) { - _read_info_t *read_info = (_read_info_t *)arg; - switch (error->status) { - case 0: { - int len = MIN(read_info->len, OS_MBUF_PKTLEN(attr->om)); - os_mbuf_copydata(attr->om, attr->offset, len, read_info->buf); - read_info->len = len; - } - MP_FALLTHROUGH; - - default: - #if CIRCUITPY_VERBOSE_BLE - // For debugging. - mp_printf(&mp_plat_print, "Read status: %d\n", error->status); - #endif - break; + #if CIRCUITPY_VERBOSE_BLE + // For debugging. + mp_printf(&mp_plat_print, "Read status: %d\n", error->status); + #endif + + portENTER_CRITICAL(&_completion_mutex); + // A single read gets exactly one callback, so the staged data can't be + // overwritten once the request is complete. + if (_complete_request(arg, error->status) && error->status == 0) { + _read_len = MIN(sizeof(_read_buf), OS_MBUF_PKTLEN(attr->om)); + os_mbuf_copydata(attr->om, attr->offset, _read_len, _read_buf); } - _completion_status = error->status; + portEXIT_CRITICAL(&_completion_mutex); return 0; } int bleio_gattc_read(uint16_t conn_handle, uint16_t value_handle, uint8_t *buf, size_t len) { - _read_info_t read_info = { - .buf = buf, - .len = len - }; - _reset_completion_status(); - CHECK_NIMBLE_ERROR(ble_gattc_read(conn_handle, value_handle, _read_cb, &read_info)); - CHECK_NIMBLE_ERROR(_wait_for_completion(2000)); - return read_info.len; + void *seq = _start_request(); + CHECK_NIMBLE_ERROR(ble_gattc_read(conn_handle, value_handle, _read_cb, seq)); + _check_completion_status(_wait_for_completion(2000)); + if (!_completion_done) { + // Interrupted: nothing was read. + return 0; + } + len = MIN(len, _read_len); + memcpy(buf, _read_buf, len); + return len; } @@ -230,13 +343,15 @@ static int _write_cb(uint16_t conn_handle, const struct ble_gatt_error *error, struct ble_gatt_attr *attr, void *arg) { - _completion_status = error->status; + portENTER_CRITICAL(&_completion_mutex); + _complete_request(arg, error->status); + portEXIT_CRITICAL(&_completion_mutex); return 0; } void bleio_gattc_write(uint16_t conn_handle, uint16_t value_handle, uint8_t *buf, size_t len) { - _reset_completion_status(); - CHECK_NIMBLE_ERROR(ble_gattc_write_flat(conn_handle, value_handle, buf, len, _write_cb, NULL)); - CHECK_NIMBLE_ERROR(_wait_for_completion(2000)); + void *seq = _start_request(); + CHECK_NIMBLE_ERROR(ble_gattc_write_flat(conn_handle, value_handle, buf, len, _write_cb, seq)); + _check_completion_status(_wait_for_completion(2000)); } diff --git a/ports/espressif/common-hal/_bleio/ble_events.c b/ports/espressif/common-hal/_bleio/ble_events.c index 6a616819a8b..5bd3e300a02 100644 --- a/ports/espressif/common-hal/_bleio/ble_events.c +++ b/ports/espressif/common-hal/_bleio/ble_events.c @@ -11,37 +11,50 @@ #include #include +#include "freertos/FreeRTOS.h" + #include "py/gc.h" #include "py/misc.h" #include "py/mpstate.h" #include "py/runtime.h" -#if CIRCUITPY_SERIAL_BLE && CIRCUITPY_VERBOSE_BLE +#if CIRCUITPY_BLE_SERIAL_SERVICE && CIRCUITPY_VERBOSE_BLE #include "supervisor/shared/bluetooth/serial.h" #endif +// Do event list manipulation in a critical section. +static portMUX_TYPE handler_list_mutex = portMUX_INITIALIZER_UNLOCKED; + void ble_event_reset(void) { // Linked list items will be gc'd. + portENTER_CRITICAL(&handler_list_mutex); MP_STATE_VM(ble_event_handler_entries) = NULL; + portEXIT_CRITICAL(&handler_list_mutex); } void ble_event_remove_heap_handlers(void) { ble_event_handler_entry_t *it = MP_STATE_VM(ble_event_handler_entries); while (it != NULL) { - // If the param is on the heap, then delete the handler. - if (gc_ptr_on_heap(it->param)) { + // Save it->next before removing: the entry may be reused and relinked + // once it is off the list. + ble_event_handler_entry_t *next = it->next; + // Remove the handler if the entry or its param is on the heap, which is + // about to go away. + if (gc_ptr_on_heap(it) || gc_ptr_on_heap(it->param)) { ble_event_remove_handler(it->func, it->param); } - it = it->next; + it = next; } } void ble_event_add_handler_entry(ble_event_handler_entry_t *entry, ble_gap_event_fn *func, void *param) { + portENTER_CRITICAL(&handler_list_mutex); ble_event_handler_entry_t *it = MP_STATE_VM(ble_event_handler_entries); while (it != NULL) { // If event handler and its corresponding param are already on the list, don't add again. if ((it->func == func) && (it->param == param)) { + portEXIT_CRITICAL(&handler_list_mutex); return; } it = it->next; @@ -51,12 +64,17 @@ void ble_event_add_handler_entry(ble_event_handler_entry_t *entry, entry->func = func; MP_STATE_VM(ble_event_handler_entries) = entry; + portEXIT_CRITICAL(&handler_list_mutex); } void ble_event_add_handler(ble_gap_event_fn *func, void *param) { + // Not in a critical section on purpose: this scan only avoids the + // allocation below when the handler is already registered. + // ble_event_add_handler_entry() repeats it in the critical section and is + // the one that decides. The allocation must stay outside, because it can + // collect or raise. ble_event_handler_entry_t *it = MP_STATE_VM(ble_event_handler_entries); while (it != NULL) { - // If event handler and its corresponding param are already on the list, don't add again. if ((it->func == func) && (it->param == param)) { return; } @@ -64,28 +82,32 @@ void ble_event_add_handler(ble_gap_event_fn *func, void *param) { } // Add a new handler to the front of the list - ble_event_handler_entry_t *handler = m_new(ble_event_handler_entry_t, 1); + ble_event_handler_entry_t *handler = m_new_obj(ble_event_handler_entry_t); ble_event_add_handler_entry(handler, func, param); } void ble_event_remove_handler(ble_gap_event_fn *func, void *param) { + portENTER_CRITICAL(&handler_list_mutex); ble_event_handler_entry_t *it = MP_STATE_VM(ble_event_handler_entries); ble_event_handler_entry_t **prev = &MP_STATE_VM(ble_event_handler_entries); while (it != NULL) { if ((it->func == func) && (it->param == param)) { - // Splice out the matching handler. + // Splice out the matching handler. Leave its next pointer alone: + // another walk in progress may already be holding this node as its + // cursor. Clearing next would end that walk here, dropping the + // event for every handler after it. *prev = it->next; - // Clear next of the removed node so it's clearly not in a list. - it->next = NULL; + portEXIT_CRITICAL(&handler_list_mutex); return; } prev = &(it->next); it = it->next; } + portEXIT_CRITICAL(&handler_list_mutex); } int ble_event_run_handlers(struct ble_gap_event *event) { - #if CIRCUITPY_SERIAL_BLE && CIRCUITPY_VERBOSE_BLE + #if CIRCUITPY_BLE_SERIAL_SERVICE && CIRCUITPY_VERBOSE_BLE ble_serial_disable(); #endif @@ -93,15 +115,23 @@ int ble_event_run_handlers(struct ble_gap_event *event) { mp_printf(&mp_plat_print, "BLE GAP event: 0x%04x\n", event->type); #endif + portENTER_CRITICAL(&handler_list_mutex); ble_event_handler_entry_t *it = MP_STATE_VM(ble_event_handler_entries); + portEXIT_CRITICAL(&handler_list_mutex); bool done = false; while (it != NULL) { - // Capture next before calling the function in case it removes itself from the list. + // Take a consistent snapshot of the node, including next, before + // calling the function: the function may remove itself from the list, + // and so may the VM task while the call runs. + portENTER_CRITICAL(&handler_list_mutex); ble_event_handler_entry_t *next = it->next; - done = it->func(event, it->param) || done; + ble_gap_event_fn *func = it->func; + void *param = it->param; + portEXIT_CRITICAL(&handler_list_mutex); + done = func(event, param) || done; it = next; } - #if CIRCUITPY_SERIAL_BLE && CIRCUITPY_VERBOSE_BLE + #if CIRCUITPY_BLE_SERIAL_SERVICE && CIRCUITPY_VERBOSE_BLE ble_serial_enable(); #endif return 0; diff --git a/ports/espressif/common-hal/alarm/SleepMemory.c b/ports/espressif/common-hal/alarm/SleepMemory.c index 938772e53ca..301f5108cbf 100644 --- a/ports/espressif/common-hal/alarm/SleepMemory.c +++ b/ports/espressif/common-hal/alarm/SleepMemory.c @@ -15,14 +15,54 @@ // Data storage for singleton instance of SleepMemory. // Might be RTC_SLOW_MEM or RTC_FAST_MEM, depending on setting of CONFIG_ESP32S2_RTCDATA_IN_FAST_MEM. -static RTC_DATA_ATTR uint8_t _sleep_mem[SLEEP_MEMORY_LENGTH]; +#if defined(CONFIG_SOC_RTC_FAST_MEM_SUPPORTED) || defined(CONFIG_SOC_RTC_SLOW_MEM_SUPPORTED) +static RTC_NOINIT_ATTR uint8_t _sleep_mem[SLEEP_MEMORY_LENGTH]; void alarm_sleep_memory_reset(void) { - // ESP-IDF build system takes care of doing esp_sleep_pd_config() or the equivalent with - // the correct settings, depending on which RTC mem we are using. - // https://docs.espressif.com/projects/esp-idf/en/latest/esp32s2/api-reference/system/sleep_modes.html#power-down-of-rtc-peripherals-and-memories + // With RTC_NOINIT_ATTR, the bootloader does not initialize sleep memory. + // Preserve contents on resets where the RTC domain stays powered (software + // reset, watchdog, panic, deep sleep wake). Clear on everything else — + // after power-on, SRAM contents are undefined; after brown-out, the RTC + // domain was reset by hardware (System Reset scope per TRM Figure 6.1-1). + // + // esp_reset_reason() does not change across supervisor reloads, + // so do this check only once per chip reset. + static bool checked_reset_reason = false; + if (checked_reset_reason) { + return; + } + checked_reset_reason = true; + + esp_reset_reason_t reason = esp_reset_reason(); + switch (reason) { + case ESP_RST_SW: // microcontroller.reset() / esp_restart() + case ESP_RST_DEEPSLEEP: // deep sleep wake + case ESP_RST_PANIC: // unhandled exception + case ESP_RST_INT_WDT: // interrupt watchdog + case ESP_RST_TASK_WDT: // task watchdog + case ESP_RST_WDT: // other watchdog + // RTC domain was not reset — sleep memory is intact. + break; + default: + // Power-on, brown-out, unknown, or any other reason where + // RTC SRAM contents may be undefined. Clear to zero. + memset(_sleep_mem, 0, sizeof(_sleep_mem)); + break; + } } +#else + +// Chips without RTC memory can't persist SleepMemory across deep sleep. +static uint8_t _sleep_mem[SLEEP_MEMORY_LENGTH]; + +void alarm_sleep_memory_reset(void) { + // Do nothing for chips without RTC memory. +} + +#endif + + uint32_t common_hal_alarm_sleep_memory_get_length(alarm_sleep_memory_obj_t *self) { return sizeof(_sleep_mem); } diff --git a/ports/espressif/common-hal/alarm/__init__.c b/ports/espressif/common-hal/alarm/__init__.c index 629f976039f..751ef121e5f 100644 --- a/ports/espressif/common-hal/alarm/__init__.c +++ b/ports/espressif/common-hal/alarm/__init__.c @@ -57,68 +57,61 @@ void alarm_reset(void) { esp_sleep_disable_wakeup_source(ESP_SLEEP_WAKEUP_ALL); } -static esp_sleep_wakeup_cause_t _get_wakeup_cause(bool deep_sleep) { +static uint32_t _get_wakeup_causes(bool deep_sleep) { // First check if the modules remember what last woke up if (alarm_pin_pinalarm_woke_this_cycle()) { - return ESP_SLEEP_WAKEUP_GPIO; + return 1 << ESP_SLEEP_WAKEUP_GPIO; } if (alarm_time_timealarm_woke_this_cycle()) { - return ESP_SLEEP_WAKEUP_TIMER; + return 1 << ESP_SLEEP_WAKEUP_TIMER; } #if CIRCUITPY_ALARM_TOUCH if (alarm_touch_touchalarm_woke_this_cycle()) { - return ESP_SLEEP_WAKEUP_TOUCHPAD; + return 1 << ESP_SLEEP_WAKEUP_TOUCHPAD; } #endif #if CIRCUITPY_ESPULP if (espulp_ulpalarm_woke_this_cycle()) { - return ESP_SLEEP_WAKEUP_ULP; + return 1 << ESP_SLEEP_WAKEUP_ULP; } #endif // If waking from true deep sleep, modules will have lost their state, // so check the deep wakeup cause manually if (deep_sleep) { - return esp_sleep_get_wakeup_cause(); + return esp_sleep_get_wakeup_causes(); } - return ESP_SLEEP_WAKEUP_UNDEFINED; + return 0; } bool common_hal_alarm_woken_from_sleep(void) { - return _get_wakeup_cause(false) != ESP_SLEEP_WAKEUP_UNDEFINED; + return _get_wakeup_causes(false) != 0; } mp_obj_t common_hal_alarm_record_wake_alarm(void) { // If woken from deep sleep, create a copy alarm similar to what would have // been passed in originally. Otherwise, just return none - esp_sleep_wakeup_cause_t cause = _get_wakeup_cause(true); - switch (cause) { - case ESP_SLEEP_WAKEUP_TIMER: { - return alarm_time_timealarm_record_wake_alarm(); - } + uint32_t causes = _get_wakeup_causes(true); - case ESP_SLEEP_WAKEUP_GPIO: - case ESP_SLEEP_WAKEUP_EXT0: - case ESP_SLEEP_WAKEUP_EXT1: { - return alarm_pin_pinalarm_record_wake_alarm(); - } + if (causes & (1 << ESP_SLEEP_WAKEUP_TIMER)) { + return alarm_time_timealarm_record_wake_alarm(); + } - #if CIRCUITPY_ALARM_TOUCH - case ESP_SLEEP_WAKEUP_TOUCHPAD: { - return alarm_touch_touchalarm_record_wake_alarm(); - } - #endif + if (causes & ((1 << ESP_SLEEP_WAKEUP_GPIO) | (1 << ESP_SLEEP_WAKEUP_EXT0) | (1 << ESP_SLEEP_WAKEUP_EXT1))) { + return alarm_pin_pinalarm_record_wake_alarm(); + } - #if CIRCUITPY_ESPULP - case ESP_SLEEP_WAKEUP_ULP: { - return espulp_ulpalarm_record_wake_alarm(); - } - #endif + #if CIRCUITPY_ALARM_TOUCH + if (causes & (1 << ESP_SLEEP_WAKEUP_TOUCHPAD)) { + return alarm_touch_touchalarm_record_wake_alarm(); + } + #endif - case ESP_SLEEP_WAKEUP_UNDEFINED: - default: - // Not a deep sleep reset. - break; + #if CIRCUITPY_ESPULP + if (causes & (1 << ESP_SLEEP_WAKEUP_ULP)) { + return espulp_ulpalarm_record_wake_alarm(); } + #endif + return mp_const_none; } @@ -144,32 +137,22 @@ mp_obj_t common_hal_alarm_light_sleep_until_alarms(size_t n_alarms, const mp_obj RUN_BACKGROUND_TASKS; // Detect if interrupt was alarm or ctrl-C interrupt. if (common_hal_alarm_woken_from_sleep()) { - esp_sleep_wakeup_cause_t cause = _get_wakeup_cause(false); - switch (cause) { - case ESP_SLEEP_WAKEUP_TIMER: { - wake_alarm = alarm_time_timealarm_find_triggered_alarm(n_alarms, alarms); - break; - } - case ESP_SLEEP_WAKEUP_GPIO: { - wake_alarm = alarm_pin_pinalarm_find_triggered_alarm(n_alarms, alarms); - break; - } - #if CIRCUITPY_ALARM_TOUCH - case ESP_SLEEP_WAKEUP_TOUCHPAD: { - wake_alarm = alarm_touch_touchalarm_find_triggered_alarm(n_alarms, alarms); - break; - } - #endif - #if CIRCUITPY_ESPULP - case ESP_SLEEP_WAKEUP_ULP: { - wake_alarm = espulp_ulpalarm_find_triggered_alarm(n_alarms, alarms); - break; - } - #endif - default: - // Should not reach this, if all light sleep types are covered correctly - break; + uint32_t causes = _get_wakeup_causes(false); + if (causes & (1 << ESP_SLEEP_WAKEUP_TIMER)) { + wake_alarm = alarm_time_timealarm_find_triggered_alarm(n_alarms, alarms); + } else if (causes & (1 << ESP_SLEEP_WAKEUP_GPIO)) { + wake_alarm = alarm_pin_pinalarm_find_triggered_alarm(n_alarms, alarms); + } + #if CIRCUITPY_ALARM_TOUCH + else if (causes & (1 << ESP_SLEEP_WAKEUP_TOUCHPAD)) { + wake_alarm = alarm_touch_touchalarm_find_triggered_alarm(n_alarms, alarms); + } + #endif + #if CIRCUITPY_ESPULP + else if (causes & (1 << ESP_SLEEP_WAKEUP_ULP)) { + wake_alarm = espulp_ulpalarm_find_triggered_alarm(n_alarms, alarms); } + #endif shared_alarm_save_wake_alarm(wake_alarm); break; } @@ -189,7 +172,7 @@ 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 common_hal_alarm_enter_deep_sleep(void) { +void MP_NORETURN common_hal_alarm_enter_deep_sleep(void) { alarm_pin_pinalarm_prepare_for_deep_sleep(); #if CIRCUITPY_ALARM_TOUCH alarm_touch_touchalarm_prepare_for_deep_sleep(); @@ -199,7 +182,7 @@ void NORETURN common_hal_alarm_enter_deep_sleep(void) { #endif // We no longer need to remember the pin preservations, since any pin resets are all done. - clear_pin_preservations(); + common_hal_alarm_clear_pin_preservations(); // 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. diff --git a/ports/espressif/common-hal/alarm/pin/PinAlarm.c b/ports/espressif/common-hal/alarm/pin/PinAlarm.c index 45f676fa599..ee20f494b4e 100644 --- a/ports/espressif/common-hal/alarm/pin/PinAlarm.c +++ b/ports/espressif/common-hal/alarm/pin/PinAlarm.c @@ -14,10 +14,12 @@ #include "esp_sleep.h" #include "hal/gpio_ll.h" +#include "driver/gpio.h" #include "esp_debug_helpers.h" #ifdef SOC_PM_SUPPORT_EXT0_WAKEUP #include "soc/rtc_cntl_reg.h" +#include "soc/rtc_io_reg.h" #endif #include "driver/rtc_io.h" @@ -100,24 +102,34 @@ mp_obj_t alarm_pin_pinalarm_find_triggered_alarm(size_t n_alarms, const mp_obj_t } mp_obj_t alarm_pin_pinalarm_record_wake_alarm(void) { - esp_sleep_wakeup_cause_t cause = esp_sleep_get_wakeup_cause(); + uint32_t causes = esp_sleep_get_wakeup_causes(); // Pin status will persist into a fake deep sleep uint64_t pin_status = ((uint64_t)pin_63_32_status) << 32 | pin_31_0_status; size_t pin_number = 64; #ifdef SOC_PM_SUPPORT_EXT0_WAKEUP - if (cause == ESP_SLEEP_WAKEUP_EXT0) { - pin_number = REG_GET_FIELD(RTC_IO_EXT_WAKEUP0_REG, RTC_IO_EXT_WAKEUP0_SEL); + if (causes & (1 << ESP_SLEEP_WAKEUP_EXT0)) { + int rtc_io_pin_number = REG_GET_FIELD(RTC_IO_EXT_WAKEUP0_REG, RTC_IO_EXT_WAKEUP0_SEL); + // Look up the GPIO equivalent pin for this RTC GPIO pin. On ESP32, the numbering + // is different for RTC_GPIO and regular GPIO, and there's no mapping table. + // The RTC and GPIO pin numbers match for all other current chips, so we could skip this + // for those chips, but it's not expensive, and maybe there will be another mismatch in the future. + for (gpio_num_t gpio_num = 0; gpio_num < SOC_GPIO_PIN_COUNT; gpio_num++) { + if (rtc_io_number_get(gpio_num) == rtc_io_pin_number) { + pin_number = gpio_num; + break; + } + } } else { #endif #ifdef SOC_PM_SUPPORT_EXT1_WAKEUP - if (cause == ESP_SLEEP_WAKEUP_EXT1) { + if (causes & (1 << ESP_SLEEP_WAKEUP_EXT1)) { pin_status = esp_sleep_get_ext1_wakeup_status(); } #endif #ifdef SOC_GPIO_SUPPORT_DEEPSLEEP_WAKEUP - if (cause == ESP_SLEEP_WAKEUP_GPIO) { + if (causes & (1 << ESP_SLEEP_WAKEUP_GPIO)) { pin_status = esp_sleep_get_gpio_wakeup_status(); } #endif @@ -295,11 +307,11 @@ static esp_err_t _setup_deep_sleep(size_t low_count, size_t high_count) { return _setup_ext1(low_count, high_count); } #endif - esp_err_t result = esp_deep_sleep_enable_gpio_wakeup(low_alarms, ESP_GPIO_WAKEUP_GPIO_LOW); + esp_err_t result = esp_sleep_enable_gpio_wakeup_on_hp_periph_powerdown(low_alarms, ESP_GPIO_WAKEUP_GPIO_LOW); if (result != ESP_OK) { return result; } - result = esp_deep_sleep_enable_gpio_wakeup(high_alarms, ESP_GPIO_WAKEUP_GPIO_HIGH); + result = esp_sleep_enable_gpio_wakeup_on_hp_periph_powerdown(high_alarms, ESP_GPIO_WAKEUP_GPIO_HIGH); return result; } #else @@ -348,38 +360,39 @@ void alarm_pin_pinalarm_set_alarms(bool deep_sleep, size_t n_alarms, const mp_ob if (gpio_isr_register(gpio_interrupt, NULL, 0, &gpio_interrupt_handle) != ESP_OK) { mp_raise_ValueError(MP_ERROR_TEXT("Can only alarm on RTC IO from deep sleep.")); } - for (size_t i = 0; i < 64; i++) { - uint64_t mask = 1ull << i; + for (gpio_num_t pin = 0; pin < SOC_GPIO_PIN_COUNT; pin++) { + uint64_t mask = 1ULL << pin; bool high = (high_alarms & mask) != 0; bool low = (low_alarms & mask) != 0; bool pull = (pull_pins & mask) != 0; if (!(high || low)) { continue; } - if (rtc_gpio_is_valid_gpio(i)) { + if (rtc_gpio_is_valid_gpio(pin)) { #ifdef SOC_PM_SUPPORT_RTC_PERIPH_PD - rtc_gpio_deinit(i); + rtc_gpio_deinit(pin); #endif } - gpio_int_type_t interrupt_mode = GPIO_INTR_DISABLE; - gpio_pull_mode_t pull_mode = GPIO_FLOATING; + gpio_set_direction(pin, GPIO_MODE_INPUT); + if (pull) { + if (high) { + ESP_ERROR_CHECK(gpio_set_pull_mode(pin, GPIO_PULLDOWN_ONLY)); + } else { + ESP_ERROR_CHECK(gpio_set_pull_mode(pin, GPIO_PULLUP_ONLY)); + } + } else { + ESP_ERROR_CHECK(gpio_set_pull_mode(pin, GPIO_FLOATING)); + } + gpio_int_type_t intr = GPIO_INTR_DISABLE; if (high) { - interrupt_mode = GPIO_INTR_HIGH_LEVEL; - pull_mode = GPIO_PULLDOWN_ONLY; + intr = GPIO_INTR_HIGH_LEVEL; } if (low) { - interrupt_mode = GPIO_INTR_LOW_LEVEL; - pull_mode = GPIO_PULLUP_ONLY; - } - gpio_set_direction(i, GPIO_MODE_DEF_INPUT); - PIN_FUNC_SELECT(GPIO_PIN_MUX_REG[i], PIN_FUNC_GPIO); - if (pull) { - gpio_set_pull_mode(i, pull_mode); + intr = GPIO_INTR_LOW_LEVEL; } - never_reset_pin_number(i); - // Sets interrupt type and wakeup bits. - gpio_wakeup_enable(i, interrupt_mode); - gpio_intr_enable(i); + gpio_wakeup_enable(pin, intr); + gpio_set_intr_type(pin, intr); + gpio_intr_enable(pin); } // Wait for any pulls to settle. mp_hal_delay_ms(50); diff --git a/ports/espressif/common-hal/alarm/touch/TouchAlarm.c b/ports/espressif/common-hal/alarm/touch/TouchAlarm.c index 5791a980d54..5148c7402a2 100644 --- a/ports/espressif/common-hal/alarm/touch/TouchAlarm.c +++ b/ports/espressif/common-hal/alarm/touch/TouchAlarm.c @@ -9,15 +9,19 @@ #include "shared-bindings/microcontroller/__init__.h" #include "shared-bindings/microcontroller/Pin.h" +#include "bindings/espidf/__init__.h" #include "esp_sleep.h" #include "peripherals/touch.h" #include "supervisor/port.h" static uint16_t touch_channel_mask; +// Bitmask of the channels in use by live TouchIn objects when an alarm took +// over the touch controller. These channels are set up again after wake. +static uint16_t touchin_channel_mask; static volatile bool woke_up = false; void common_hal_alarm_touch_touchalarm_construct(alarm_touch_touchalarm_obj_t *self, const mcu_pin_obj_t *pin) { - if (pin->touch_channel == TOUCH_PAD_MAX) { + if (pin->touch_channel == NO_TOUCH_CHANNEL) { raise_ValueError_invalid_pin(); } claim_pin(pin); @@ -40,35 +44,28 @@ mp_obj_t alarm_touch_touchalarm_record_wake_alarm(void) { alarm->base.type = &alarm_touch_touchalarm_type; alarm->pin = NULL; - #if defined(CONFIG_IDF_TARGET_ESP32) - touch_pad_t wake_channel; - if (touch_pad_get_wakeup_status(&wake_channel) != ESP_OK) { - return alarm; - } - #else - touch_pad_t wake_channel = touch_pad_get_current_meas_channel(); - if (wake_channel == TOUCH_PAD_MAX) { - return alarm; - } - #endif - // 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 (pin_obj->touch_channel == wake_channel) { - alarm->pin = mcu_pin_globals.map.table[i].value; - break; + if (pin_obj->touch_channel != NO_TOUCH_CHANNEL) { + if ((touch_channel_mask & (1 << pin_obj->touch_channel)) != 0) { + alarm->pin = mcu_pin_globals.map.table[i].value; + break; + } } } return alarm; } -// This is used to wake the main CircuitPython task. -static void touch_interrupt(void *arg) { - (void)arg; +// This callback is used to wake the main CircuitPython task during light sleep. +static bool touch_active_callback(touch_sensor_handle_t sens_handle, const touch_active_event_data_t *event, void *user_ctx) { + (void)sens_handle; + (void)event; + (void)user_ctx; woke_up = true; port_wake_main_task_from_isr(); + return false; } void alarm_touch_touchalarm_set_alarm(const bool deep_sleep, const size_t n_alarms, const mp_obj_t *alarms) { @@ -81,9 +78,7 @@ void alarm_touch_touchalarm_set_alarm(const bool deep_sleep, const size_t n_alar mp_raise_ValueError_varg(MP_ERROR_TEXT("Only one %q can be set in deep sleep."), MP_QSTR_TouchAlarm); } touch_alarm = MP_OBJ_TO_PTR(alarms[i]); - touch_channel_mask |= 1 << touch_alarm->pin->number; - // Resetting the pin will set a pull-up, which we don't want. - skip_reset_once_pin_number(touch_alarm->pin->number); + touch_channel_mask |= 1 << touch_alarm->pin->touch_channel; touch_alarm_set = true; } } @@ -92,47 +87,83 @@ void alarm_touch_touchalarm_set_alarm(const bool deep_sleep, const size_t n_alar return; } - // configure interrupt for pretend to deep sleep - // this will be disabled if we actually deep sleep + // Remember the TouchIn channels that the reset below deletes. + touchin_channel_mask = 0; + for (uint8_t i = TOUCH_MIN_CHAN_ID; i <= TOUCH_MAX_CHAN_ID; i++) { + if (peripherals_touch_get_handle(i) != NULL && (touch_channel_mask & (1 << i)) == 0) { + touchin_channel_mask |= 1 << i; + } + } - // reset touch peripheral + // Reset touch peripheral peripherals_touch_reset(); - peripherals_touch_never_reset(true); - - for (uint8_t i = 1; i <= 14; i++) { - if ((touch_channel_mask & 1 << i) != 0) { - touch_pad_t touch_channel = (touch_pad_t)i; - // initialize touchpad - peripherals_touch_init(touch_channel); - - // wait for touch data to reset - mp_hal_delay_ms(10); - - // configure trigger threshold - #if defined(CONFIG_IDF_TARGET_ESP32) - uint16_t touch_value; - // ESP32 touch_pad_read() returns a lower value when a pin is touched, not a higher value - // Typical values on a Feather ESP32 V2 are 600 with a short jumper untouched, - // 70 touched. - touch_pad_read(touch_channel, &touch_value); - touch_pad_set_thresh(touch_channel, touch_value / 2); - #else - uint32_t touch_value; - touch_pad_read_benchmark(touch_channel, &touch_value); - touch_pad_set_thresh(touch_channel, touch_value / 10); // 10% - #endif + + // Initialize all touch channels used for alarms + for (uint8_t i = TOUCH_MIN_CHAN_ID; i <= TOUCH_MAX_CHAN_ID; i++) { + if ((touch_channel_mask & (1 << i)) != 0) { + CHECK_ESP_RESULT(peripherals_touch_init(i)); } } - // configure touch interrupt - #if defined(CONFIG_IDF_TARGET_ESP32) - touch_pad_isr_register(touch_interrupt, NULL); - touch_pad_intr_enable(); - #else - touch_pad_timeout_set(true, TOUCH_PAD_THRESHOLD_MAX); - touch_pad_isr_register(touch_interrupt, NULL, TOUCH_PAD_INTR_MASK_ALL); - touch_pad_intr_enable(TOUCH_PAD_INTR_MASK_ACTIVE | TOUCH_PAD_INTR_MASK_INACTIVE); - #endif + // Wait for touch data to stabilize + mp_hal_delay_ms(10); + + // Now stop scanning and disable so we can reconfigure thresholds + touch_sensor_handle_t controller = peripherals_touch_get_controller(); + touch_sensor_stop_continuous_scanning(controller); + touch_sensor_disable(controller); + + // Configure thresholds based on initial readings + for (uint8_t i = TOUCH_MIN_CHAN_ID; i <= TOUCH_MAX_CHAN_ID; i++) { + if ((touch_channel_mask & (1 << i)) == 0) { + continue; + } + touch_channel_handle_t chan = peripherals_touch_get_handle(i); + + uint32_t benchmark = 0; + #if defined(SOC_TOUCH_SUPPORT_BENCHMARK) && SOC_TOUCH_SUPPORT_BENCHMARK + touch_channel_read_data(chan, TOUCH_CHAN_DATA_TYPE_BENCHMARK, &benchmark); + #else + touch_channel_read_data(chan, TOUCH_CHAN_DATA_TYPE_SMOOTH, &benchmark); + #endif + + #if SOC_TOUCH_SENSOR_VERSION == 1 + touch_channel_config_t chan_cfg = { + .abs_active_thresh = {(uint32_t)(benchmark / 2)}, + .charge_speed = TOUCH_CHARGE_SPEED_7, + .init_charge_volt = TOUCH_INIT_CHARGE_VOLT_DEFAULT, + .group = TOUCH_CHAN_TRIG_GROUP_BOTH, + }; + #elif SOC_TOUCH_SENSOR_VERSION == 2 + touch_channel_config_t chan_cfg = { + .active_thresh = {(uint32_t)(benchmark / 10)}, + .charge_speed = TOUCH_CHARGE_SPEED_7, + .init_charge_volt = TOUCH_INIT_CHARGE_VOLT_DEFAULT, + }; + #elif SOC_TOUCH_SENSOR_VERSION == 3 + // Values are similar to an ESP-IDF example: 1000, 2500, 5000. + touch_channel_config_t chan_cfg = { + .active_thresh = {(uint32_t)(benchmark / 10), (uint32_t)(benchmark / 4), (uint32_t)(benchmark / 2)}, + }; + #else + #error bad SOC_TOUCH_SENSOR_VERSION + #endif + touch_sensor_reconfig_channel(chan, &chan_cfg); + } + + // Set up filter for proper active/inactive detection + touch_sensor_filter_config_t filter_cfg = TOUCH_SENSOR_DEFAULT_FILTER_CONFIG(); + touch_sensor_config_filter(controller, &filter_cfg); + + // Register callback for light sleep wakeup + touch_event_callbacks_t callbacks = { + .on_active = touch_active_callback, + }; + touch_sensor_register_callbacks(controller, &callbacks, NULL); + + // Re-enable and start scanning + touch_sensor_enable(controller); + touch_sensor_start_continuous_scanning(controller); } void alarm_touch_touchalarm_prepare_for_deep_sleep(void) { @@ -140,45 +171,43 @@ void alarm_touch_touchalarm_prepare_for_deep_sleep(void) { return; } - touch_pad_t touch_channel = TOUCH_PAD_MAX; - for (uint8_t i = 1; i <= 14; i++) { - if ((touch_channel_mask & 1 << i) != 0) { - touch_channel = (touch_pad_t)i; + touch_sensor_handle_t controller = peripherals_touch_get_controller(); + + // Find the first alarm channel for deep sleep + int deep_slp_chan_id = -1; + for (uint8_t i = TOUCH_MIN_CHAN_ID; i <= TOUCH_MAX_CHAN_ID; i++) { + if ((touch_channel_mask & (1 << i)) != 0) { + deep_slp_chan_id = i; break; } } - // reset touch peripheral - peripherals_touch_never_reset(false); - peripherals_touch_reset(); - - // initialize touchpad - peripherals_touch_init(touch_channel); + if (deep_slp_chan_id < 0) { + return; + } - #if !defined(CONFIG_IDF_TARGET_ESP32) - // configure touchpad for sleep - touch_pad_sleep_channel_enable(touch_channel, true); - touch_pad_sleep_channel_enable_proximity(touch_channel, false); + // Stop scanning and disable to reconfigure for deep sleep + touch_sensor_stop_continuous_scanning(controller); + touch_sensor_disable(controller); + + #if SOC_TOUCH_SUPPORT_SLEEP_WAKEUP + touch_sleep_config_t sleep_cfg = { + .slp_wakeup_lvl = TOUCH_DEEP_SLEEP_WAKEUP, + #if SOC_TOUCH_SENSOR_VERSION == 1 + .deep_slp_sens_cfg = NULL, + #else + .deep_slp_allow_pd = false, + .deep_slp_chan = peripherals_touch_get_handle(deep_slp_chan_id), + .deep_slp_sens_cfg = NULL, + #endif + }; + touch_sensor_config_sleep_wakeup(controller, &sleep_cfg); #endif - // wait for touch data to reset - mp_hal_delay_ms(10); - - // configure trigger threshold - #if defined(CONFIG_IDF_TARGET_ESP32) - uint16_t touch_value; - touch_pad_read(touch_channel, &touch_value); - // ESP32 touch_pad_read() returns a lower value when a pin is touched, not a higher value - // Typical values on a Feather ESP32 V2 are 600 with a short jumper untouched, - // 70 touched. - touch_pad_set_thresh(touch_channel, touch_value / 2); - #else - uint32_t touch_value; - touch_pad_sleep_channel_read_smooth(touch_channel, &touch_value); - touch_pad_sleep_set_threshold(touch_channel, touch_value / 10); // 10% - #endif + // Re-enable for sleep + touch_sensor_enable(controller); + touch_sensor_start_continuous_scanning(controller); - // enable touchpad wakeup esp_sleep_enable_touchpad_wakeup(); esp_sleep_pd_config(ESP_PD_DOMAIN_RTC_PERIPH, ESP_PD_OPTION_ON); } @@ -189,6 +218,31 @@ bool alarm_touch_touchalarm_woke_this_cycle(void) { void alarm_touch_touchalarm_reset(void) { woke_up = false; + + // Release claimed pin(s), mirroring alarm_pin_pinalarm_reset(). Without this, the pin + // stays marked "in use" after light_sleep_until_alarms() returns. + if (touch_channel_mask) { + 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 (pin_obj->touch_channel != NO_TOUCH_CHANNEL && (touch_channel_mask & (1 << pin_obj->touch_channel)) != 0) { + reset_pin_number(pin_obj->number); + } + } + } + + if (touch_channel_mask) { + // Tear down the channel(s) this alarm configured. Without this, a TouchIn built after + // wake would reuse this alarm's sleep-tuned threshold instead of getting a fresh one. + peripherals_touch_reset(); + + // Set up the live TouchIn channels again. + for (uint8_t i = TOUCH_MIN_CHAN_ID; i <= TOUCH_MAX_CHAN_ID; i++) { + if ((touchin_channel_mask & (1 << i)) != 0) { + peripherals_touch_init(i); + } + } + } + touch_channel_mask = 0; - peripherals_touch_never_reset(false); + touchin_channel_mask = 0; } diff --git a/ports/espressif/common-hal/analogbufio/BufferedIn.c b/ports/espressif/common-hal/analogbufio/BufferedIn.c index aac7ad28daf..3c733fe3a63 100644 --- a/ports/espressif/common-hal/analogbufio/BufferedIn.c +++ b/ports/espressif/common-hal/analogbufio/BufferedIn.c @@ -23,7 +23,7 @@ #define NUM_SAMPLES_PER_INTERRUPT 256 #define NUM_ADC_CHANNELS 1 #define DMA_BUFFER_SIZE 1024 -#define ATTENUATION ADC_ATTEN_DB_11 +#define ATTENUATION ADC_ATTEN_DB_12 #define ADC_READ_TIMEOUT_MS 2000 #define ADC_PIN_MAX_VALUE 0xfff @@ -33,7 +33,7 @@ #elif defined(CONFIG_IDF_TARGET_ESP32S2) #define ADC_RESULT_BYTE 2 #define ADC_CONV_LIMIT_EN 0 -#elif defined(CONFIG_IDF_TARGET_ESP32C2) || defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32C6) || defined(CONFIG_IDF_TARGET_ESP32H2) || defined(CONFIG_IDF_TARGET_ESP32P4) +#elif defined(CONFIG_IDF_TARGET_ESP32C2) || defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32C5) || defined(CONFIG_IDF_TARGET_ESP32C6) || defined(CONFIG_IDF_TARGET_ESP32H2) || defined(CONFIG_IDF_TARGET_ESP32P4) || defined(CONFIG_IDF_TARGET_ESP32C61) #define ADC_RESULT_BYTE 4 #define ADC_CONV_LIMIT_EN 0 #elif defined(CONFIG_IDF_TARGET_ESP32S3) @@ -47,7 +47,6 @@ static void start_dma(analogbufio_bufferedin_obj_t *self, adc_digi_convert_mode_ static void stop_dma(analogbufio_bufferedin_obj_t *self); void common_hal_analogbufio_bufferedin_construct(analogbufio_bufferedin_obj_t *self, const mcu_pin_obj_t *pin, uint32_t sample_rate) { - self->pin = pin; self->sample_rate = sample_rate; if (pin->adc_index == NO_ADC || pin->adc_channel == NO_ADC_CHANNEL) { raise_ValueError_invalid_pin(); @@ -73,6 +72,7 @@ void common_hal_analogbufio_bufferedin_construct(analogbufio_bufferedin_obj_t *s mp_arg_validate_int_range(sample_rate, SOC_ADC_SAMPLE_FREQ_THRES_LOW, SOC_ADC_SAMPLE_FREQ_THRES_HIGH, MP_QSTR_sample_rate); + self->pin = pin; common_hal_mcu_pin_claim(pin); } diff --git a/ports/espressif/common-hal/analogio/AnalogIn.c b/ports/espressif/common-hal/analogio/AnalogIn.c index 16340e91ac9..58c80e2a7d7 100644 --- a/ports/espressif/common-hal/analogio/AnalogIn.c +++ b/ports/espressif/common-hal/analogio/AnalogIn.c @@ -23,15 +23,19 @@ #define DEFAULT_VREF 1100 #define NO_OF_SAMPLES 2 -#define ATTENUATION ADC_ATTEN_DB_11 +#define ATTENUATION ADC_ATTEN_DB_12 #if defined(CONFIG_IDF_TARGET_ESP32) #define DATA_WIDTH ADC_BITWIDTH_12 #elif defined(CONFIG_IDF_TARGET_ESP32C2) #define DATA_WIDTH ADC_BITWIDTH_12 #elif defined(CONFIG_IDF_TARGET_ESP32C3) #define DATA_WIDTH ADC_BITWIDTH_12 +#elif defined(CONFIG_IDF_TARGET_ESP32C5) +#define DATA_WIDTH ADC_BITWIDTH_12 #elif defined(CONFIG_IDF_TARGET_ESP32C6) #define DATA_WIDTH ADC_BITWIDTH_12 +#elif defined(CONFIG_IDF_TARGET_ESP32C61) +#define DATA_WIDTH ADC_BITWIDTH_12 #elif defined(CONFIG_IDF_TARGET_ESP32P4) #define DATA_WIDTH ADC_BITWIDTH_12 #elif defined(CONFIG_IDF_TARGET_ESP32S2) @@ -86,10 +90,8 @@ uint16_t common_hal_analogio_analogin_get_value(analogio_analogin_obj_t *self) { adc_cali_scheme_ver_t supported_schemes; adc_cali_check_scheme(&supported_schemes); - #ifndef CONFIG_IDF_TARGET_ESP32P4 adc_cali_scheme_ver_t calibration_scheme = 0; adc_cali_handle_t calibration; - #endif #if defined(ADC_CALI_SCHEME_CURVE_FITTING_SUPPORTED) && ADC_CALI_SCHEME_CURVE_FITTING_SUPPORTED adc_cali_curve_fitting_config_t config = { .unit_id = self->pin->adc_index, @@ -137,11 +139,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 int voltage; - #ifdef CONFIG_IDF_TARGET_ESP32P4 - voltage = 0; - #else adc_cali_raw_to_voltage(calibration, adc_reading, &voltage); - #endif #if defined(ADC_CALI_SCHEME_CURVE_FITTING_SUPPORTED) && ADC_CALI_SCHEME_CURVE_FITTING_SUPPORTED if (calibration_scheme == ADC_CALI_SCHEME_VER_CURVE_FITTING) { @@ -154,6 +152,14 @@ uint16_t common_hal_analogio_analogin_get_value(analogio_analogin_obj_t *self) { } #endif adc_oneshot_del_unit(adc_handle); + + // Some chips (e.g. ESP32-P4) have a full-scale range above 3.3V at 12 dB attenuation, + // so the calibrated voltage can exceed 3300 mV. Clamp to avoid uint16_t wraparound. + if (voltage < 0) { + voltage = 0; + } else if (voltage > 3300) { + voltage = 3300; + } return voltage * ((1 << 16) - 1) / 3300; } diff --git a/ports/espressif/common-hal/analogio/AnalogIn.h b/ports/espressif/common-hal/analogio/AnalogIn.h index 944039bec2a..cd5f1b5d9ef 100644 --- a/ports/espressif/common-hal/analogio/AnalogIn.h +++ b/ports/espressif/common-hal/analogio/AnalogIn.h @@ -8,7 +8,7 @@ #include "common-hal/microcontroller/Pin.h" -#include "components/hal/include/hal/adc_types.h" +#include "hal/adc_types.h" #include "FreeRTOS.h" #include "freertos/semphr.h" #include "py/obj.h" diff --git a/ports/espressif/common-hal/analogio/AnalogOut.c b/ports/espressif/common-hal/analogio/AnalogOut.c index 0a8ad6eaa2f..8a3e08f50fd 100644 --- a/ports/espressif/common-hal/analogio/AnalogOut.c +++ b/ports/espressif/common-hal/analogio/AnalogOut.c @@ -13,6 +13,7 @@ #include "shared-bindings/analogio/AnalogOut.h" #include "shared-bindings/microcontroller/Pin.h" +#include "bindings/espidf/__init__.h" #ifdef SOC_DAC_SUPPORTED #include "driver/dac_oneshot.h" @@ -41,8 +42,9 @@ void common_hal_analogio_analogout_construct(analogio_analogout_obj_t *self, dac_oneshot_config_t config = { .chan_id = self->channel }; - dac_oneshot_new_channel(&config, &self->handle); + CHECK_ESP_RESULT(dac_oneshot_new_channel(&config, &self->handle)); _active_handles[self->channel] = self->handle; + claim_pin(pin); #else mp_raise_NotImplementedError(NULL); #endif @@ -58,9 +60,13 @@ bool common_hal_analogio_analogout_deinited(analogio_analogout_obj_t *self) { void common_hal_analogio_analogout_deinit(analogio_analogout_obj_t *self) { #ifdef SOC_DAC_SUPPORTED + if (common_hal_analogio_analogout_deinited(self)) { + return; + } dac_oneshot_del_channel(self->handle); self->handle = NULL; _active_handles[self->channel] = NULL; + reset_pin_number(self->channel == DAC_CHAN_0 ? pin_CHANNEL_0.number : pin_CHANNEL_1.number); #endif } @@ -71,14 +77,3 @@ void common_hal_analogio_analogout_set_value(analogio_analogout_obj_t *self, dac_oneshot_output_voltage(self->handle, dac_value); #endif } - -void analogout_reset(void) { - #ifdef SOC_DAC_SUPPORTED - for (uint8_t c = 0; c < SOC_DAC_CHAN_NUM; c++) { - if (_active_handles[c] != NULL) { - dac_oneshot_del_channel(_active_handles[c]); - } - _active_handles[c] = NULL; - } - #endif -} diff --git a/ports/espressif/common-hal/analogio/AnalogOut.h b/ports/espressif/common-hal/analogio/AnalogOut.h index 91f5793f0db..1c04a39a71d 100644 --- a/ports/espressif/common-hal/analogio/AnalogOut.h +++ b/ports/espressif/common-hal/analogio/AnalogOut.h @@ -21,5 +21,3 @@ typedef struct { uint8_t channel; #endif } analogio_analogout_obj_t; - -void analogout_reset(void); diff --git a/ports/espressif/common-hal/audiobusio/I2SOut.c b/ports/espressif/common-hal/audiobusio/I2SOut.c index adfc081389a..35aa1aee79e 100644 --- a/ports/espressif/common-hal/audiobusio/I2SOut.c +++ b/ports/espressif/common-hal/audiobusio/I2SOut.c @@ -28,7 +28,11 @@ // 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, const mcu_pin_obj_t *main_clock, bool left_justified) { + const mcu_pin_obj_t *data, const mcu_pin_obj_t *main_clock, bool left_justified, + bool external_clock) { + if (external_clock) { + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_external_clock); + } port_i2s_allocate_init(&self->i2s, left_justified); i2s_std_config_t i2s_config = { @@ -42,7 +46,11 @@ void common_hal_audiobusio_i2sout_construct(audiobusio_i2sout_obj_t *self, .din = I2S_GPIO_UNUSED, } }; - CHECK_ESP_RESULT(i2s_channel_init_std_mode(self->i2s.handle, &i2s_config)); + esp_err_t err = i2s_channel_init_std_mode(self->i2s.handle, &i2s_config); + if (err != ESP_OK) { + port_i2s_deinit(&self->i2s); + CHECK_ESP_RESULT(err); + } self->bit_clock = bit_clock; self->word_select = word_select; self->mclk = main_clock; diff --git a/ports/espressif/common-hal/audiobusio/PDMIn.c b/ports/espressif/common-hal/audiobusio/PDMIn.c index c9d28ad7071..e3f183ca3f8 100644 --- a/ports/espressif/common-hal/audiobusio/PDMIn.c +++ b/ports/espressif/common-hal/audiobusio/PDMIn.c @@ -40,7 +40,7 @@ void common_hal_audiobusio_pdmin_construct(audiobusio_pdmin_obj_t *self, && bit_depth != I2S_DATA_BIT_WIDTH_16BIT && bit_depth != I2S_DATA_BIT_WIDTH_24BIT && bit_depth != I2S_DATA_BIT_WIDTH_32BIT) { - mp_raise_ValueError(MP_ERROR_TEXT("bit_depth must be 8, 16, 24, or 32.")); + mp_raise_ValueError_varg(MP_ERROR_TEXT("%q must be 8, 16, 24, or 32"), MP_QSTR_bit_depth); } i2s_chan_config_t chanConfig = I2S_CHANNEL_DEFAULT_CONFIG(I2S_NUM_0, I2S_ROLE_MASTER); @@ -61,10 +61,14 @@ void common_hal_audiobusio_pdmin_construct(audiobusio_pdmin_obj_t *self, }, }; err = i2s_channel_init_pdm_rx_mode(self->rx_chan, &pdm_rx_cfg); - CHECK_ESP_RESULT(err); - - err = i2s_channel_enable(self->rx_chan); - CHECK_ESP_RESULT(err); + if (err == ESP_OK) { + err = i2s_channel_enable(self->rx_chan); + } + if (err != ESP_OK) { + i2s_del_channel(self->rx_chan); + self->rx_chan = NULL; + CHECK_ESP_RESULT(err); + } self->clock_pin = clock_pin; self->data_pin = data_pin; diff --git a/ports/espressif/common-hal/audiobusio/__init__.c b/ports/espressif/common-hal/audiobusio/__init__.c index 226e371c5b0..b594176a75f 100644 --- a/ports/espressif/common-hal/audiobusio/__init__.c +++ b/ports/espressif/common-hal/audiobusio/__init__.c @@ -10,8 +10,12 @@ #include "common-hal/audiobusio/__init__.h" #include "bindings/espidf/__init__.h" -#include "freertos/FreeRTOS.h" -#include "freertos/task.h" +#include "esp_task.h" +#include "freertos/semphr.h" +#include "soc/soc_caps.h" +#if defined(SOC_CACHE_INTERNAL_MEM_VIA_L1CACHE) && SOC_CACHE_INTERNAL_MEM_VIA_L1CACHE +#include "esp_cache.h" +#endif #include "shared-module/audiocore/__init__.h" @@ -23,6 +27,28 @@ #define CIRCUITPY_BUFFER_SIZE (I2S_DMA_BUFFER_MAX_SIZE / 4) // The number of output channels is fixed at 2 #define CIRCUITPY_OUTPUT_SLOTS (2) +// Refill runs on its own task, above the LVGL render task, so a long display render can't starve +// it. +#define I2S_FILL_TASK_PRIORITY (ESP_TASK_MAIN_PRIO + 2) +#define I2S_FILL_TASK_STACK_SIZE (8192) + +// Held by a fill task while it refills, and by any code that changes a sample being played (see +// audiocore_lock()). Recursive because a sample may take it again itself while it fills. Created +// with the first I2SOut, from the FreeRTOS heap rather than static RAM, which is tight on the +// ESP32-S2. Until then there is no fill task to keep out. +static SemaphoreHandle_t audiocore_mutex; + +void audiocore_lock(void) { + if (audiocore_mutex != NULL) { + xSemaphoreTakeRecursive(audiocore_mutex, portMAX_DELAY); + } +} + +void audiocore_unlock(void) { + if (audiocore_mutex != NULL) { + xSemaphoreGiveRecursive(audiocore_mutex); + } +} static void i2s_fill_buffer(i2s_t *self) { if (self->next_buffer_size == 0) { @@ -39,25 +65,32 @@ static void i2s_fill_buffer(i2s_t *self) { self->next_buffer_size = 0; return; } - while (!self->stopping && output_buffer_size > 0) { + while (output_buffer_size > 0) { if (self->sample_data == self->sample_end) { + if (self->last_buffer) { + // The final buffer has been fully output; stop now instead of + // fetching another (which for a single-buffer sample would just + // replay it). + self->stopping = true; + break; + } 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_end = self->sample_data + sample_buffer_length; + if (get_buffer_result == GET_BUFFER_ERROR || sample_buffer_length == 0) { + self->stopping = true; + break; + } if (get_buffer_result == GET_BUFFER_DONE) { if (self->loop) { audiosample_reset_buffer(self->sample, false, 0); } else { - self->stopping = true; - break; + // Output this final buffer before stopping; don't fetch again. + self->last_buffer = true; } } - if (get_buffer_result == GET_BUFFER_ERROR || sample_buffer_length == 0) { - self->stopping = true; - break; - } } size_t sample_bytecount = self->sample_end - self->sample_data; // The framecount is the minimum of space left in the output buffer or left in the incoming sample. @@ -96,22 +129,44 @@ static void i2s_fill_buffer(i2s_t *self) { output_buffer += framecount * CIRCUITPY_OUTPUT_SLOTS; output_buffer_size -= framecount * bytes_per_output_frame; } + // Sample ended mid-buffer (or was empty/errored): silence the rest so the + // DMA doesn't play stale data. + if (output_buffer_size > 0) { + memset(output_buffer, 0, output_buffer_size); + } self->next_buffer = NULL; self->next_buffer_size = 0; } -static void i2s_callback_fun(void *self_in) { +static void i2s_fill_task(void *self_in) { i2s_t *self = self_in; - i2s_fill_buffer(self); + for (;;) { + ulTaskNotifyTake(pdTRUE, portMAX_DELAY); + audiocore_lock(); + #if defined(SOC_CACHE_INTERNAL_MEM_VIA_L1CACHE) && SOC_CACHE_INTERNAL_MEM_VIA_L1CACHE + void *buffer = self->next_buffer; + size_t buffer_size = self->next_buffer_size; + #endif + i2s_fill_buffer(self); + #if defined(SOC_CACHE_INTERNAL_MEM_VIA_L1CACHE) && SOC_CACHE_INTERNAL_MEM_VIA_L1CACHE + // Internal RAM is cached. IDF writes the buffer back right after on_sent, before + // we fill it here, so write it back again or the DMA plays stale data. + if (buffer != NULL) { + esp_cache_msync(buffer, buffer_size, ESP_CACHE_MSYNC_FLAG_DIR_C2M); + } + #endif + audiocore_unlock(); + } } static bool i2s_event_interrupt(i2s_chan_handle_t handle, i2s_event_data_t *event, void *self_in) { i2s_t *self = self_in; self->underrun = self->underrun || self->next_buffer != NULL; - self->next_buffer = *(int16_t **)event->data; + self->next_buffer = (int16_t *)event->dma_buf; self->next_buffer_size = event->size; - background_callback_add(&self->callback, i2s_callback_fun, self_in); - return false; + BaseType_t woken = pdFALSE; + vTaskNotifyGiveFromISR(self->fill_task, &woken); + return woken == pdTRUE; } void port_i2s_allocate_init(i2s_t *self, bool left_justified) { @@ -125,6 +180,19 @@ void port_i2s_allocate_init(i2s_t *self, bool left_justified) { if (err == ESP_ERR_NOT_FOUND) { mp_raise_RuntimeError(MP_ERROR_TEXT("Peripheral in use")); } + if (audiocore_mutex == NULL) { + audiocore_mutex = xSemaphoreCreateRecursiveMutex(); + if (audiocore_mutex == NULL) { + i2s_del_channel(self->handle); + m_malloc_fail(sizeof(StaticSemaphore_t)); + } + } + self->fill_task = NULL; + if (xTaskCreatePinnedToCore(i2s_fill_task, "i2s fill", I2S_FILL_TASK_STACK_SIZE, self, + I2S_FILL_TASK_PRIORITY, &self->fill_task, CONFIG_ESP_MAIN_TASK_AFFINITY) != pdPASS) { + port_i2s_deinit(self); + m_malloc_fail(I2S_FILL_TASK_STACK_SIZE); + } self->playing = false; self->paused = false; self->stopping = false; @@ -142,11 +210,27 @@ void port_i2s_deinit(i2s_t *self) { port_i2s_stop(self); i2s_del_channel(self->handle); self->handle = NULL; + if (self->fill_task != NULL) { + // The channel is gone, so nothing wakes the task again. Holding the lock means the task + // isn't mid-fill. + audiocore_lock(); + vTaskDelete(self->fill_task); + self->fill_task = NULL; + audiocore_unlock(); + } } void port_i2s_play(i2s_t *self, mp_obj_t sample, bool loop) { + audiosample_check(sample); // Pause to disable the I2S channel so we can adjust the clock. port_i2s_pause(self); + // Set the clock first, because it can raise and nothing below may raise while locked. + uint32_t sample_rate = audiosample_get_sample_rate(sample); + i2s_std_clk_config_t clk_config = I2S_STD_CLK_DEFAULT_CONFIG(sample_rate); + CHECK_ESP_RESULT(i2s_channel_reconfig_std_clock(self->handle, &clk_config)); + // Keep refill out while the sample changes. Samples report load errors by return value, so + // nothing here raises with the lock held. + audiocore_lock(); self->sample = sample; self->loop = loop; self->bytes_per_sample = audiosample_get_bits_per_sample(sample) / 8; @@ -164,14 +248,11 @@ void port_i2s_play(i2s_t *self, mp_obj_t sample, bool loop) { audiosample_reset_buffer(self->sample, false, 0); - uint32_t sample_rate = audiosample_get_sample_rate(sample); - i2s_std_clk_config_t clk_config = I2S_STD_CLK_DEFAULT_CONFIG(sample_rate); - CHECK_ESP_RESULT(i2s_channel_reconfig_std_clock(self->handle, &clk_config)); - // preload the data self->playing = true; self->paused = false; self->stopping = false; + self->last_buffer = false; // This will be slow but we can't rewind the underlying sample. So, we will // preload one frame at a time and drop the last sample that can't fit. // We cap ourselves at the max DMA set to prevent a sample drop if starting @@ -179,13 +260,14 @@ void port_i2s_play(i2s_t *self, mp_obj_t sample, bool loop) { uint32_t starting_frame; size_t bytes_loaded = 4; size_t preloaded = 0; - while (bytes_loaded > 0 && preloaded < CIRCUITPY_BUFFER_SIZE * CIRCUITPY_BUFFER_COUNT) { + while (bytes_loaded > 0 && preloaded < I2S_DMA_BUFFER_MAX_SIZE * CIRCUITPY_BUFFER_COUNT) { self->next_buffer = &starting_frame; self->next_buffer_size = sizeof(starting_frame); i2s_fill_buffer(self); i2s_channel_preload_data(self->handle, &starting_frame, sizeof(uint32_t), &bytes_loaded); - preloaded += 1; + preloaded += bytes_loaded; } + audiocore_unlock(); // enable the channel i2s_channel_enable(self->handle); @@ -206,9 +288,12 @@ bool port_i2s_paused(i2s_t *self) { void port_i2s_stop(i2s_t *self) { port_i2s_pause(self); + audiocore_lock(); self->sample = NULL; self->playing = false; self->stopping = false; + self->last_buffer = false; + audiocore_unlock(); } void port_i2s_pause(i2s_t *self) { diff --git a/ports/espressif/common-hal/audiobusio/__init__.h b/ports/espressif/common-hal/audiobusio/__init__.h index 0088cb87d5f..022ff7951a5 100644 --- a/ports/espressif/common-hal/audiobusio/__init__.h +++ b/ports/espressif/common-hal/audiobusio/__init__.h @@ -8,9 +8,9 @@ #include "py/obj.h" -#include "supervisor/background_callback.h" - #include "driver/i2s_std.h" +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" typedef struct { mp_obj_t *sample; @@ -19,6 +19,7 @@ typedef struct { bool paused; // True when the I2S channel is configured but disabled. bool playing; // True when the I2S channel is configured. bool stopping; + bool last_buffer; // True once the sample's final buffer has been fetched but not yet fully output. bool samples_signed; int8_t bytes_per_sample; int8_t channel_count; @@ -27,7 +28,7 @@ typedef struct { void *next_buffer; size_t next_buffer_size; i2s_chan_handle_t handle; - background_callback_t callback; + TaskHandle_t fill_task; // Refills DMA buffers when the I2S interrupt wakes it. bool underrun; } i2s_t; diff --git a/ports/espressif/common-hal/audioi2sin/I2SIn.c b/ports/espressif/common-hal/audioi2sin/I2SIn.c new file mode 100644 index 00000000000..32dec5fb9c0 --- /dev/null +++ b/ports/espressif/common-hal/audioi2sin/I2SIn.c @@ -0,0 +1,456 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include + +#include "bindings/espidf/__init__.h" + +#include "common-hal/audioi2sin/I2SIn.h" +#include "py/runtime.h" +#include "shared-bindings/audioi2sin/I2SIn.h" +#include "shared-bindings/audiocore/__init__.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-module/audioi2sin/__init__.h" +#include "supervisor/port.h" + +#include "driver/i2s_std.h" + +#if CIRCUITPY_AUDIOI2SIN + +void common_hal_audioi2sin_i2sin_construct(audioi2sin_i2sin_obj_t *self, + const mcu_pin_obj_t *bit_clock, const mcu_pin_obj_t *word_select, + const mcu_pin_obj_t *data, const mcu_pin_obj_t *main_clock, + uint32_t sample_rate, uint8_t bit_depth, uint8_t output_bit_depth, + bool mono, bool left_justified, bool samples_signed, + bool external_clock) { + if (external_clock) { + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_external_clock); + } + + i2s_data_bit_width_t bit_width = (i2s_data_bit_width_t)bit_depth; + + i2s_chan_config_t chan_cfg = I2S_CHANNEL_DEFAULT_CONFIG(I2S_NUM_AUTO, I2S_ROLE_MASTER); + esp_err_t err = i2s_new_channel(&chan_cfg, NULL, &self->rx_chan); + if (err == ESP_ERR_NOT_FOUND) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Peripheral in use")); + } + CHECK_ESP_RESULT(err); + + // Always configure the bus as stereo. The newer-family I2S peripherals + // (S2/S3/C-series) ignore I2S_SLOT_MODE_MONO on RX and write both slots + // into the DMA buffer regardless, which yields buffers that fill at 2x + // the WS rate and produces half-speed audio. By configuring stereo and + // dropping one slot ourselves in record_to_buffer, behavior is uniform + // across chips. + i2s_std_slot_config_t slot_cfg = left_justified + ? (i2s_std_slot_config_t)I2S_STD_MSB_SLOT_DEFAULT_CONFIG(bit_width, I2S_SLOT_MODE_STEREO) + : (i2s_std_slot_config_t)I2S_STD_PHILIPS_SLOT_DEFAULT_CONFIG(bit_width, I2S_SLOT_MODE_STEREO); + + i2s_std_config_t std_cfg = { + .clk_cfg = I2S_STD_CLK_DEFAULT_CONFIG(sample_rate), + .slot_cfg = slot_cfg, + .gpio_cfg = { + .mclk = main_clock != NULL ? main_clock->number : I2S_GPIO_UNUSED, + .bclk = bit_clock->number, + .ws = word_select->number, + .dout = I2S_GPIO_UNUSED, + .din = data->number, + }, + }; + err = i2s_channel_init_std_mode(self->rx_chan, &std_cfg); + if (err == ESP_OK) { + err = i2s_channel_enable(self->rx_chan); + } + if (err != ESP_OK) { + i2s_del_channel(self->rx_chan); + self->rx_chan = NULL; + CHECK_ESP_RESULT(err); + } + + self->bit_clock = bit_clock; + self->word_select = word_select; + self->data = data; + self->mclk = main_clock; + self->sample_rate = sample_rate; + self->bit_depth = bit_depth; + self->mono = mono; + self->samples_signed = samples_signed; + + // Populate the audiosample base so I2SIn can stream into the audio pipeline. + // Streaming requires an 8- or 16-bit output depth (reset_buffer enforces it); + // the owned conversion buffer is allocated lazily on first reset_buffer(). + uint8_t channel_count = mono ? 1 : 2; + self->base.sample_rate = sample_rate; + self->base.bits_per_sample = output_bit_depth; + self->base.channel_count = channel_count; + self->base.samples_signed = samples_signed; + self->base.single_buffer = false; + self->base.max_buffer_length = + 2 * AUDIOI2SIN_STREAM_FRAMES * (output_bit_depth / 8) * channel_count; + self->output_buffer = NULL; + self->output_half_bytes = self->base.max_buffer_length / 2; + self->output_index = 0; + + claim_pin(bit_clock); + claim_pin(word_select); + claim_pin(data); + if (main_clock) { + claim_pin(main_clock); + } +} + +bool common_hal_audioi2sin_i2sin_deinited(audioi2sin_i2sin_obj_t *self) { + return self->data == NULL; +} + +void common_hal_audioi2sin_i2sin_deinit(audioi2sin_i2sin_obj_t *self) { + if (common_hal_audioi2sin_i2sin_deinited(self)) { + return; + } + + if (self->rx_chan) { + i2s_channel_disable(self->rx_chan); + i2s_del_channel(self->rx_chan); + self->rx_chan = NULL; + } + + if (self->bit_clock) { + reset_pin_number(self->bit_clock->number); + } + self->bit_clock = NULL; + + if (self->word_select) { + reset_pin_number(self->word_select->number); + } + self->word_select = NULL; + + if (self->data) { + reset_pin_number(self->data->number); + } + self->data = NULL; + + if (self->mclk) { + reset_pin_number(self->mclk->number); + } + self->mclk = NULL; + + if (self->output_buffer != NULL) { + port_free(self->output_buffer); + self->output_buffer = NULL; + } + audiosample_mark_deinit(&self->base); +} + +// Sign-extend a raw I2S sample (in the low `in_depth` bits of `raw`) to a +// canonical int32 value. +static inline int32_t i2sin_normalize_signed(uint32_t raw, uint8_t in_depth) { + if (in_depth == 32) { + return (int32_t)raw; + } + if (in_depth == 24) { + uint32_t sign_bit = 0x800000u; + return (int32_t)((raw ^ sign_bit) - sign_bit); + } + if (in_depth == 16) { + return (int16_t)(raw & 0xffffu); + } + return (int8_t)(raw & 0xffu); +} + +// Read a single sample from the DMA scratch at the given byte offset for the +// configured input bit depth. +static inline uint32_t i2sin_read_raw(const uint8_t *src, uint8_t in_depth) { + if (in_depth == 8) { + return (uint32_t)(*src); + } + if (in_depth == 16) { + uint16_t v; + memcpy(&v, src, sizeof(v)); + return v; + } + uint32_t v; + memcpy(&v, src, sizeof(v)); + return v; +} + +// Normalize `raw` from `in_depth` for this port's wire format, then hand off to +// the shared converter to rescale `in_depth` -> `out_depth` and write it to +// `buffer` at sample index `idx`. The depth conversion + unsigned-WAV flip + +// container store live in `shared_audioi2sin_write_converted` (shared with other +// ports); see that helper for the upscale/downscale semantics. +static inline void i2sin_write_converted(void *buffer, uint32_t idx, + uint32_t raw, uint8_t in_depth, uint8_t out_depth, bool samples_signed) { + int32_t s = i2sin_normalize_signed(raw, in_depth); + shared_audioi2sin_write_converted(buffer, idx, s, in_depth, out_depth, samples_signed); +} + +// I2S delivers signed PCM. When samples_signed is false, XOR each sample with +// the sign bit for its width to convert to unsigned PCM (WAV convention). +static void i2sin_convert_to_unsigned(void *buffer, uint32_t samples, + uint8_t bit_depth, size_t element_size) { + (void)element_size; + uint32_t *p = (uint32_t *)buffer; + + if (bit_depth == 8) { + // 4 samples per word + uint32_t words = samples / 4; + for (uint32_t i = 0; i < words; i++) { + p[i] ^= 0x80808080u; + } + // tail: 0–3 leftover bytes + uint8_t *tail = (uint8_t *)(p + words); + for (uint32_t i = 0; i < (samples & 3u); i++) { + tail[i] ^= 0x80u; + } + } else if (bit_depth == 16) { + // 2 samples per word + uint32_t words = samples / 2; + for (uint32_t i = 0; i < words; i++) { + p[i] ^= 0x80008000u; + } + if (samples & 1u) { + ((uint16_t *)(p + words))[0] ^= 0x8000u; + } + } else { + // 24- or 32-bit: one sample per 32-bit slot + uint32_t mask = (bit_depth == 24) ? 0x00800000u : 0x80000000u; + for (uint32_t i = 0; i < samples; i++) { + p[i] ^= mask; + } + } +} + + +uint32_t common_hal_audioi2sin_i2sin_record_to_buffer(audioi2sin_i2sin_obj_t *self, + void *buffer, uint32_t length) { + size_t element_size = self->bit_depth / 8; + // 24-bit samples occupy a 32-bit slot on the I2S bus. + if (self->bit_depth == 24) { + element_size = 4; + } + + if (self->base.bits_per_sample != self->bit_depth) { + // Bit-depth conversion path: always read at input width into scratch, + // convert each sample into the user's buffer at output width. + const uint8_t in_depth = self->bit_depth; + const uint8_t out_depth = self->base.bits_per_sample; + const bool samples_signed = self->samples_signed; + uint8_t scratch[256]; + const size_t in_frame_bytes = 2 * element_size; + const size_t scratch_frames = sizeof(scratch) / in_frame_bytes; + uint32_t produced = 0; + while (produced < length) { + size_t want_frames; + if (self->mono) { + want_frames = length - produced; + } else { + want_frames = (length - produced + 1) / 2; + } + if (want_frames > scratch_frames) { + want_frames = scratch_frames; + } + size_t got_bytes = 0; + esp_err_t err = i2s_channel_read(self->rx_chan, scratch, + want_frames * in_frame_bytes, &got_bytes, portMAX_DELAY); + CHECK_ESP_RESULT(err); + size_t got_frames = got_bytes / in_frame_bytes; + for (size_t i = 0; i < got_frames && produced < length; i++) { + const uint8_t *frame = scratch + i * in_frame_bytes; + uint32_t left_raw = i2sin_read_raw(frame, in_depth); + i2sin_write_converted(buffer, produced++, left_raw, + in_depth, out_depth, samples_signed); + if (!self->mono && produced < length) { + uint32_t right_raw = i2sin_read_raw(frame + element_size, in_depth); + i2sin_write_converted(buffer, produced++, right_raw, + in_depth, out_depth, samples_signed); + } + } + if (got_frames < want_frames) { + break; + } + } + return produced; + } + + uint32_t produced; + if (!self->mono) { + size_t result = 0; + esp_err_t err = i2s_channel_read(self->rx_chan, buffer, length * element_size, + &result, portMAX_DELAY); + CHECK_ESP_RESULT(err); + produced = result / element_size; + } else { + // Mono: bus is configured stereo, so each WS frame yields two slots in + // the DMA buffer. Read in chunks into a scratch and keep only the left + // slot of each frame. + uint8_t scratch[256]; + const size_t frame_bytes = 2 * element_size; + const size_t scratch_frames = sizeof(scratch) / frame_bytes; + uint8_t *out = (uint8_t *)buffer; + produced = 0; + while (produced < length) { + size_t want_frames = length - produced; + if (want_frames > scratch_frames) { + want_frames = scratch_frames; + } + size_t got_bytes = 0; + esp_err_t err = i2s_channel_read(self->rx_chan, scratch, + want_frames * frame_bytes, &got_bytes, portMAX_DELAY); + CHECK_ESP_RESULT(err); + size_t got_frames = got_bytes / frame_bytes; + for (size_t i = 0; i < got_frames; i++) { + memcpy(out + produced * element_size, + scratch + i * frame_bytes, + element_size); + produced++; + } + if (got_frames < want_frames) { + break; + } + } + } + + if (!self->samples_signed && produced > 0) { + i2sin_convert_to_unsigned(buffer, produced, self->bit_depth, element_size); + } + return produced; +} + +uint8_t common_hal_audioi2sin_i2sin_get_bit_depth(audioi2sin_i2sin_obj_t *self) { + return self->bit_depth; +} + +uint32_t common_hal_audioi2sin_i2sin_get_sample_rate(audioi2sin_i2sin_obj_t *self) { + return self->sample_rate; +} + +bool common_hal_audioi2sin_i2sin_get_samples_signed(audioi2sin_i2sin_obj_t *self) { + return self->samples_signed; +} + +// Always false here: this port hands the capture ring to the IDF driver, which +// drops frames internally without telling us. Detecting it would require +// registering an on_recv_q_ovf callback on the channel. +bool common_hal_audioi2sin_i2sin_get_overflow(audioi2sin_i2sin_obj_t *self) { + (void)self; + return false; +} + +// Write `count` silence samples at output depth starting at sample index `idx`. +// For signed PCM silence is 0; for unsigned (WAV) it is mid-scale. +static void i2sin_fill_silence(void *buffer, uint32_t idx, uint32_t count, + uint8_t out_depth, bool samples_signed) { + if (out_depth == 8) { + uint8_t v = samples_signed ? 0 : 0x80u; + memset((uint8_t *)buffer + idx, v, count); + } else { // 16-bit (the only other streamable width) + uint16_t v = samples_signed ? 0 : 0x8000u; + uint16_t *p = (uint16_t *)buffer + idx; + for (uint32_t i = 0; i < count; i++) { + p[i] = v; + } + } +} + +// Non-blocking fill: read whatever frames are immediately available from the I2S +// driver and convert them into `buffer` (output depth, interleaved), padding the +// remainder with silence on underrun. The bus is configured stereo, so each WS +// frame yields two slots; for mono we keep the left slot. `out_depth` is always 8 +// or 16 here (reset_buffer rejects 24/32). Runs in the output backend's refill +// (background callback) context, so i2s_channel_read is called with a 0 ms +// timeout and never blocks. +void common_hal_audioi2sin_i2sin_fill_buffer(audioi2sin_i2sin_obj_t *self, + uint8_t *buffer, uint32_t frames) { + const uint8_t in_depth = self->bit_depth; + const uint8_t out_depth = self->base.bits_per_sample; + const bool samples_signed = self->samples_signed; + const bool stereo = !self->mono; + const uint8_t channel_count = stereo ? 2 : 1; + size_t element_size = (in_depth == 24) ? 4 : (in_depth / 8); + const size_t in_frame_bytes = 2 * element_size; // bus is always stereo + const uint32_t total_samples = frames * channel_count; + + uint8_t scratch[256]; + const size_t scratch_frames = sizeof(scratch) / in_frame_bytes; + + uint32_t produced = 0; + while (produced < total_samples) { + size_t want_frames = (total_samples - produced + channel_count - 1) / channel_count; + if (want_frames > scratch_frames) { + want_frames = scratch_frames; + } + size_t got_bytes = 0; + // 0 ms timeout: return immediately with whatever is buffered. + esp_err_t err = i2s_channel_read(self->rx_chan, scratch, + want_frames * in_frame_bytes, &got_bytes, 0); + if (err != ESP_OK && err != ESP_ERR_TIMEOUT) { + break; + } + size_t got_frames = got_bytes / in_frame_bytes; + if (got_frames == 0) { + break; // underrun: pad with silence below + } + for (size_t i = 0; i < got_frames && produced < total_samples; i++) { + const uint8_t *frame = scratch + i * in_frame_bytes; + uint32_t left_raw = i2sin_read_raw(frame, in_depth); + i2sin_write_converted(buffer, produced++, left_raw, + in_depth, out_depth, samples_signed); + if (stereo && produced < total_samples) { + uint32_t right_raw = i2sin_read_raw(frame + element_size, in_depth); + i2sin_write_converted(buffer, produced++, right_raw, + in_depth, out_depth, samples_signed); + } + } + if (got_frames < want_frames) { + break; + } + } + if (produced < total_samples) { + i2sin_fill_silence(buffer, produced, total_samples - produced, + out_depth, samples_signed); + } +} + +void common_hal_audioi2sin_i2sin_reset_buffer(audioi2sin_i2sin_obj_t *self, + bool single_channel_output, uint8_t channel) { + (void)single_channel_output; + (void)channel; + // The audio pipeline only carries 8- or 16-bit samples; 24/32-bit modes can + // still record() but cannot stream. + if (self->base.bits_per_sample != 8 && self->base.bits_per_sample != 16) { + mp_raise_ValueError_varg( + MP_ERROR_TEXT("%q must be 8 or 16"), MP_QSTR_output_bit_depth); + } + if (self->output_buffer == NULL) { + self->output_buffer = (uint8_t *)port_malloc(self->base.max_buffer_length, false); + if (self->output_buffer == NULL) { + m_malloc_fail(self->base.max_buffer_length); + } + } + self->output_index = 0; +} + +audioio_get_buffer_result_t common_hal_audioi2sin_i2sin_get_buffer( + audioi2sin_i2sin_obj_t *self, bool single_channel_output, uint8_t channel, + uint8_t **buffer, uint32_t *buffer_length) { + uint32_t half = self->output_half_bytes; + uint8_t *out = self->output_buffer + half * self->output_index; + self->output_index = 1 - self->output_index; + + uint32_t bytes_per_sample = self->base.bits_per_sample / 8; + uint32_t frames = half / (bytes_per_sample * self->base.channel_count); + common_hal_audioi2sin_i2sin_fill_buffer(self, out, frames); + + if (single_channel_output) { + out += (channel % self->base.channel_count) * bytes_per_sample; + } + *buffer = out; + *buffer_length = half; + // A live mic is an infinite stream; never report DONE or the backend stops. + return GET_BUFFER_MORE_DATA; +} + +#endif // CIRCUITPY_AUDIOI2SIN diff --git a/ports/espressif/common-hal/audioi2sin/I2SIn.h b/ports/espressif/common-hal/audioi2sin/I2SIn.h new file mode 100644 index 00000000000..a6fc7224c32 --- /dev/null +++ b/ports/espressif/common-hal/audioi2sin/I2SIn.h @@ -0,0 +1,43 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +#include "common-hal/microcontroller/Pin.h" + +#include "shared-module/audiocore/__init__.h" + +#include "driver/i2s_std.h" + +#if CIRCUITPY_AUDIOI2SIN + +// Frames handed to the output backend per get_buffer() call; see the matching +// rp2 header for the rationale. +#define AUDIOI2SIN_STREAM_FRAMES (256) + +typedef struct { + // so I2SIn can be used directly as an audiosample source. + audiosample_base_t base; + i2s_chan_handle_t rx_chan; + const mcu_pin_obj_t *bit_clock; + const mcu_pin_obj_t *word_select; + const mcu_pin_obj_t *data; + const mcu_pin_obj_t *mclk; + uint32_t sample_rate; + uint8_t bit_depth; + bool mono; + bool samples_signed; + // Owned double-buffer of converted (output-depth, interleaved) samples, + // allocated lazily on first reset_buffer(). base.max_buffer_length is the + // whole buffer; get_buffer() returns output_half_bytes of it. + uint8_t *output_buffer; + size_t output_half_bytes; + uint8_t output_index; +} audioi2sin_i2sin_obj_t; + +#endif diff --git a/ports/espressif/common-hal/audioi2sin/__init__.c b/ports/espressif/common-hal/audioi2sin/__init__.c new file mode 100644 index 00000000000..584c821b996 --- /dev/null +++ b/ports/espressif/common-hal/audioi2sin/__init__.c @@ -0,0 +1,5 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT diff --git a/ports/espressif/common-hal/audioio/AudioOut.c b/ports/espressif/common-hal/audioio/AudioOut.c index 6d829228e15..1fa4dd0e93d 100644 --- a/ports/espressif/common-hal/audioio/AudioOut.c +++ b/ports/espressif/common-hal/audioio/AudioOut.c @@ -42,7 +42,7 @@ static bool audioout_convert_u8s_u8m( bool buffer_changed = false; if (in_buffer_size / 2 > *out_buffer_size) { - *out_buffer = m_malloc(in_buffer_size / 2); + *out_buffer = m_malloc_without_collect(in_buffer_size / 2); buffer_changed = true; } audiosample_convert_u8s_u8m(*out_buffer, (uint8_t *)in_buffer, in_buffer_size / 2); @@ -58,7 +58,7 @@ static bool audioout_convert_u8m_u8s( bool buffer_changed = false; if (in_buffer_size * 2 > *out_buffer_size) { - *out_buffer = m_malloc(in_buffer_size * 2); + *out_buffer = m_malloc_without_collect(in_buffer_size * 2); buffer_changed = true; } audiosample_convert_u8m_u8s(*out_buffer, (uint8_t *)in_buffer, in_buffer_size); @@ -74,7 +74,7 @@ static bool audioout_convert_s8m_u8m( bool buffer_changed = false; if (in_buffer_size > *out_buffer_size) { - *out_buffer = m_malloc(in_buffer_size); + *out_buffer = m_malloc_without_collect(in_buffer_size); buffer_changed = true; } audiosample_convert_s8m_u8m(*out_buffer, (int8_t *)in_buffer, in_buffer_size); @@ -90,7 +90,7 @@ static bool audioout_convert_s8s_u8m( bool buffer_changed = false; if (in_buffer_size / 2 > *out_buffer_size) { - *out_buffer = m_malloc(in_buffer_size / 2); + *out_buffer = m_malloc_without_collect(in_buffer_size / 2); buffer_changed = true; } audiosample_convert_s8s_u8m(*out_buffer, (int8_t *)in_buffer, in_buffer_size / 2); @@ -106,7 +106,7 @@ static bool audioout_convert_s8m_u8s( bool buffer_changed = false; if (in_buffer_size * 2 > *out_buffer_size) { - *out_buffer = m_malloc(in_buffer_size * 2); + *out_buffer = m_malloc_without_collect(in_buffer_size * 2); buffer_changed = true; } audiosample_convert_s8m_u8s(*out_buffer, (int8_t *)in_buffer, in_buffer_size); @@ -122,7 +122,7 @@ static bool audioout_convert_s8s_u8s( bool buffer_changed = false; if (in_buffer_size > *out_buffer_size) { - *out_buffer = m_malloc(in_buffer_size); + *out_buffer = m_malloc_without_collect(in_buffer_size); buffer_changed = true; } audiosample_convert_s8s_u8s(*out_buffer, (int8_t *)in_buffer, in_buffer_size); @@ -138,7 +138,7 @@ static bool audioout_convert_u16m_u8m( bool buffer_changed = false; if (in_buffer_size / 2 > *out_buffer_size) { - *out_buffer = m_malloc(in_buffer_size / 2); + *out_buffer = m_malloc_without_collect(in_buffer_size / 2); buffer_changed = true; } audiosample_convert_u16m_u8m(*out_buffer, (uint16_t *)in_buffer, in_buffer_size / 2); @@ -154,7 +154,7 @@ static bool audioout_convert_u16m_u8s( bool buffer_changed = false; if (in_buffer_size > *out_buffer_size) { - *out_buffer = m_malloc(in_buffer_size); + *out_buffer = m_malloc_without_collect(in_buffer_size); buffer_changed = true; } audiosample_convert_u16m_u8s(*out_buffer, (uint16_t *)in_buffer, in_buffer_size / 2); @@ -186,7 +186,7 @@ static bool audioout_convert_u16s_u8s( bool buffer_changed = false; if (in_buffer_size / 2 > *out_buffer_size) { - *out_buffer = m_malloc(in_buffer_size / 2); + *out_buffer = m_malloc_without_collect(in_buffer_size / 2); buffer_changed = true; } audiosample_convert_u16s_u8s(*out_buffer, (uint16_t *)in_buffer, in_buffer_size / 4); @@ -202,7 +202,7 @@ static bool audioout_convert_s16m_u8m( bool buffer_changed = false; if (in_buffer_size / 2 > *out_buffer_size) { - *out_buffer = m_malloc(in_buffer_size / 2); + *out_buffer = m_malloc_without_collect(in_buffer_size / 2); buffer_changed = true; } audiosample_convert_s16m_u8m(*out_buffer, (int16_t *)in_buffer, in_buffer_size / 2); @@ -218,7 +218,7 @@ static bool audioout_convert_s16m_u8s( bool buffer_changed = false; if (in_buffer_size > *out_buffer_size) { - *out_buffer = m_malloc(in_buffer_size); + *out_buffer = m_malloc_without_collect(in_buffer_size); buffer_changed = true; } audiosample_convert_s16m_u8s(*out_buffer, (int16_t *)in_buffer, in_buffer_size / 2); @@ -250,7 +250,7 @@ static bool audioout_convert_s16s_u8s( bool buffer_changed = false; if (in_buffer_size / 2 > *out_buffer_size) { - *out_buffer = m_malloc(in_buffer_size / 2); + *out_buffer = m_malloc_without_collect(in_buffer_size / 2); buffer_changed = true; } audiosample_convert_s16s_u8s(*out_buffer, (int16_t *)in_buffer, in_buffer_size / 4); @@ -488,6 +488,15 @@ static void audioout_init(audioio_audioout_obj_t *self) { mp_raise_RuntimeError(MP_ERROR_TEXT("Failed to create continuous channels: no mem")); } + // Claim the pins here, not in construct: play() calls deinit(), which + // releases them, and then calls this again. + if (self->channel_mask & DAC_CHANNEL_MASK_CH0) { + claim_pin(&pin_CHANNEL_0); + } + if (self->channel_mask & DAC_CHANNEL_MASK_CH1) { + claim_pin(&pin_CHANNEL_1); + } + _active_handle = self->handle; dac_event_callbacks_t callbacks = { @@ -564,6 +573,12 @@ void common_hal_audioio_audioout_deinit(audioio_audioout_obj_t *self) { } self->handle = NULL; _active_handle = NULL; + if (self->channel_mask & DAC_CHANNEL_MASK_CH0) { + reset_pin_number(pin_CHANNEL_0.number); + } + if (self->channel_mask & DAC_CHANNEL_MASK_CH1) { + reset_pin_number(pin_CHANNEL_1.number); + } } void common_hal_audioio_audioout_play(audioio_audioout_obj_t *self, @@ -573,6 +588,8 @@ void common_hal_audioio_audioout_play(audioio_audioout_obj_t *self, mp_raise_RuntimeError(MP_ERROR_TEXT("already playing")); } + audiosample_check(sample); + size_t samples_size; uint8_t channel_count; bool samples_signed; diff --git a/ports/espressif/common-hal/audiomixer/__init__.c b/ports/espressif/common-hal/audiomixer/__init__.c new file mode 100644 index 00000000000..7f23b13772c --- /dev/null +++ b/ports/espressif/common-hal/audiomixer/__init__.c @@ -0,0 +1,85 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mikey Sklar for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include +#include + +#include "shared-module/audiomixer/Mixer.h" + +// ESP32-S3 PIE (SIMD), 8 signed 16-bit samples at a time. It gives the same result as +// mult16signed() and add16signed() in Mixer.c: EE.VMUL.S16 arithmetic-shifts each 32-bit +// product right by SAR and keeps the low 16 bits, and EE.VADDS.S16 saturates (ESP32-S3 +// TRM, chapter 1 "Processor Instruction Extensions"). +uint32_t audiomixer_port_mix_signed_16_bit(uint32_t *dst, const uint32_t *src, uint32_t n, + int32_t lomul, int32_t himul, bool accumulate) { + // A level of 1.0 is 32768, which does not fit in an int16 lane. Since + // (x * m) >> 15 == (x * (m >> k)) >> (15 - k) when m is a multiple of 1 << k, + // drop the common factors of two from both levels and shift by less. + int32_t both_levels = lomul | himul; + int32_t factors_of_two = both_levels ? __builtin_ctz(both_levels) : 15; + int32_t lo_level = lomul >> factors_of_two; + int32_t hi_level = himul >> factors_of_two; + if (lo_level > INT16_MAX || hi_level > INT16_MAX) { + // One channel at exactly 1.0 and the other at an odd level. + return 0; + } + + const uint32_t *source = src; + uint32_t *destination = dst; + uint32_t vectors = n / 4; + // src may be unaligned: each step loads the next aligned 16 bytes and EE.SRC.Q.QUP + // shifts the pair by SAR_BYTE, so it loads one block more than the vectors it + // produces. When src is unaligned, that last block still holds the last source word, + // and the load never leaves it. When src is aligned, it would be a whole block past + // the end, so do one vector less. + if (((uintptr_t)source & 15) == 0 && vectors > 0) { + vectors--; + } + if (vectors == 0) { + return 0; + } + uint32_t done = vectors * 4; + + int16_t levels[8] __attribute__((aligned(16))) = { + lo_level, hi_level, lo_level, hi_level, lo_level, hi_level, lo_level, hi_level + }; + int32_t shift = 15 - factors_of_two; + // SAR is not restored afterwards. GCC sets SAR before every shift it emits. + if (accumulate) { + __asm__ volatile ( + "wsr.sar %[shift]\n" + "ee.vld.128.ip q7, %[levels], 0\n" + "ee.ld.128.usar.ip q0, %[source], 16\n" + "1:\n" + "ee.ld.128.usar.ip q1, %[source], 16\n" + "ee.src.q.qup q2, q0, q1\n" + "ee.vmul.s16 q3, q2, q7\n" + "ee.vld.128.ip q4, %[destination], 0\n" + "ee.vadds.s16 q4, q4, q3\n" + "ee.vst.128.ip q4, %[destination], 16\n" + "addi %[vectors], %[vectors], -1\n" + "bnez %[vectors], 1b\n" + : [source] "+r" (source), [destination] "+r" (destination), [vectors] "+r" (vectors) + : [levels] "r" (levels), [shift] "r" (shift) + : "memory"); + } else { + __asm__ volatile ( + "wsr.sar %[shift]\n" + "ee.vld.128.ip q7, %[levels], 0\n" + "ee.ld.128.usar.ip q0, %[source], 16\n" + "1:\n" + "ee.ld.128.usar.ip q1, %[source], 16\n" + "ee.src.q.qup q2, q0, q1\n" + "ee.vmul.s16 q3, q2, q7\n" + "ee.vst.128.ip q3, %[destination], 16\n" + "addi %[vectors], %[vectors], -1\n" + "bnez %[vectors], 1b\n" + : [source] "+r" (source), [destination] "+r" (destination), [vectors] "+r" (vectors) + : [levels] "r" (levels), [shift] "r" (shift) + : "memory"); + } + return done; +} diff --git a/ports/espressif/common-hal/audiopwmio/PWMAudioOut.c b/ports/espressif/common-hal/audiopwmio/PWMAudioOut.c new file mode 100644 index 00000000000..eb715245e2b --- /dev/null +++ b/ports/espressif/common-hal/audiopwmio/PWMAudioOut.c @@ -0,0 +1,491 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tyeth Gundry +// +// SPDX-License-Identifier: MIT + +// PWM audio for the ESP32 family. +// +// LEDC has no DMA path for its duty registers, and the ESP32-S2's I2S has no +// PDM transmitter, so samples are pushed one at a time from a GPTimer alarm +// ISR running at the sample rate. Two device buffers are used: the ISR drains +// one while audiopwmout_background() refills the other. +// +// The ISR reads and writes only the internal-RAM control block, for the two +// reasons set out in PWMAudioOut.h and below. In particular it must not queue +// a background callback: on this port that macro is taskENTER_CRITICAL(), +// which aborts when called from ISR context. + +#include "common-hal/audiopwmio/PWMAudioOut.h" + +#include +#include + +#include "py/gc.h" +#include "py/runtime.h" + +#include "bindings/espidf/__init__.h" +#include "shared-bindings/audiopwmio/PWMAudioOut.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/pwmio/PWMOut.h" +#include "shared-module/audiocore/__init__.h" + +#include "driver/gptimer.h" +#include "esp_attr.h" +#include "esp_heap_caps.h" +#include "esp_memory_utils.h" +#include "hal/ledc_ll.h" +#include "soc/soc.h" + +// Carrier frequency: 80 MHz / 1024 = 78125 Hz. pwmio derives PWM_BITS back out +// of this when it picks a duty resolution, so the two stay in step. +#define PWM_FREQUENCY (APB_CLK_FREQ >> PWM_BITS) + +// GPTimer tick rate. The timer group divider must be at least 2, so 40 MHz is +// the finest available, and it keeps the sample-rate error below a cent +// (44100 Hz -> 907 ticks -> 44101.4 Hz). +#define TIMER_RESOLUTION_HZ (APB_CLK_FREQ / 2) + +// Internal RAM is scarce, and both buffers come out of it. This is generous +// for the buffer sizes the audiosample protocol actually hands over (a +// WaveFile uses 512 bytes) while still failing clearly on something silly. +#define MAX_BUFFER_BYTES (8192) + +// Each object needs its own LEDC timer, so that bounds how many can play. +static audiopwmio_pwmaudioout_obj_t *active_audio[SOC_LEDC_TIMER_NUM]; + +// Write one duty value to a LEDC channel. This mirrors what ledc_update_duty() +// does, minus the argument checks and the spinlock, so it is cheap enough to +// run at the sample rate. The fade parameters it relies on (scale 0, so the +// duty is latched rather than ramped) are left set up by pwmio's construct. +static inline void IRAM_ATTR set_duty(uint8_t channel, uint32_t duty) { + ledc_ll_set_duty_int_part(&LEDC, LEDC_LOW_SPEED_MODE, channel, duty); + ledc_ll_set_sig_out_en(&LEDC, LEDC_LOW_SPEED_MODE, channel, true); + ledc_ll_set_duty_start(&LEDC, LEDC_LOW_SPEED_MODE, channel); + ledc_ll_ls_channel_update(&LEDC, LEDC_LOW_SPEED_MODE, channel); +} + +static bool IRAM_ATTR timer_alarm_cb(gptimer_handle_t timer, + const gptimer_alarm_event_data_t *edata, void *internal_data_ptr) { + audiopwmio_internal_data_t *internal_data = + (audiopwmio_internal_data_t *)internal_data_ptr; + (void)timer; + (void)edata; + + uint8_t buf_index = internal_data->playing_buffer; + if (!internal_data->buffer_ready[buf_index]) { + // Underrun, or the sample ended. Hold the quiescent level rather than + // leaving the last sample on the pin, which would be a DC offset. + set_duty(internal_data->left_channel, internal_data->quiescent_value); + if (internal_data->stereo) { + set_duty(internal_data->right_channel, internal_data->quiescent_value); + } + return false; + } + + size_t frame = internal_data->playing_frame; + const uint16_t *sample = + &internal_data->buffers[buf_index][frame * internal_data->out_channels]; + + set_duty(internal_data->left_channel, sample[0]); + if (internal_data->stereo) { + set_duty(internal_data->right_channel, sample[1]); + } + + frame++; + if (frame >= internal_data->buffer_frames[buf_index]) { + if (internal_data->single_buffer && internal_data->loop) { + // The whole sample fits in one buffer and repeats forever, so wrap + // in place. This keeps looping RawSamples glitch-free: no refill, + // and no dependency on how promptly the background task runs. + internal_data->playing_frame = 0; + return false; + } + // This buffer is spent. Flag it; the background task does the refill. + internal_data->buffer_ready[buf_index] = false; + if (internal_data->last_buffer[buf_index]) { + internal_data->stop_queued = true; + } + internal_data->playing_frame = 0; + if (!internal_data->single_buffer) { + internal_data->playing_buffer = buf_index ^ 1; + } + } else { + internal_data->playing_frame = frame; + } + + return false; +} + +// Convert one source buffer into device buffer `buf_index`, scaling samples to +// PWM_BITS. Runs in task context, so it may touch the object freely. +static void fill_buffer(audiopwmio_pwmaudioout_obj_t *self, uint8_t buf_index) { + audiopwmio_internal_data_t *internal_data = self->internal_data; + uint8_t *source; + uint32_t source_length; + audioio_get_buffer_result_t result = + audiosample_get_buffer(self->sample, false, 0, &source, &source_length); + + if (result == GET_BUFFER_ERROR) { + internal_data->stop_queued = true; + return; + } + + uint8_t out_channels = internal_data->out_channels; + size_t frames = source_length / self->bytes_per_sample / self->sample_channel_count; + if (frames * out_channels * sizeof(uint16_t) > self->buffer_size[buf_index]) { + // Should not happen: play() sized the buffers from max_buffer_length. + frames = self->buffer_size[buf_index] / (out_channels * sizeof(uint16_t)); + } + + uint16_t *dest = internal_data->buffers[buf_index]; + if (self->bytes_per_sample == 1) { + uint8_t xor_mask = self->signed_to_unsigned ? 0x80 : 0; + for (size_t i = 0; i < frames; i++) { + uint16_t left = (uint16_t)((source[i * self->sample_channel_count] ^ xor_mask) << (PWM_BITS - 8)); + *dest++ = left; + if (out_channels == 2) { + *dest++ = (self->sample_channel_count == 2) + ? (uint16_t)((source[i * 2 + 1] ^ xor_mask) << (PWM_BITS - 8)) + : left; + } + } + } else { + uint16_t xor_mask = self->signed_to_unsigned ? 0x8000 : 0; + // Cast via void * : the sample buffer is 16-bit aligned for 16-bit + // samples, but the protocol hands it over as uint8_t *. + const uint16_t *source16 = (const uint16_t *)(const void *)source; + for (size_t i = 0; i < frames; i++) { + uint16_t left = (uint16_t)((source16[i * self->sample_channel_count] ^ xor_mask) >> SAMPLE_BITS_TO_DISCARD); + *dest++ = left; + if (out_channels == 2) { + *dest++ = (self->sample_channel_count == 2) + ? (uint16_t)((source16[i * 2 + 1] ^ xor_mask) >> SAMPLE_BITS_TO_DISCARD) + : left; + } + } + } + + internal_data->buffer_frames[buf_index] = frames; + internal_data->last_buffer[buf_index] = false; + + if (result == GET_BUFFER_DONE) { + if (internal_data->loop) { + audiosample_reset_buffer(self->sample, false, 0); + } else { + internal_data->last_buffer[buf_index] = true; + } + } + + // Publish last, so the ISR never sees a half-filled buffer. + __asm__ volatile ("" ::: "memory"); + internal_data->buffer_ready[buf_index] = (frames > 0); + if (frames == 0 && result == GET_BUFFER_DONE && !internal_data->loop) { + internal_data->stop_queued = true; + } +} + +// Tear down the timer without touching the heap, so this is also safe to call +// while the VM is being reset. +static void stop_timer(audiopwmio_pwmaudioout_obj_t *self) { + if (self->timer != NULL) { + gptimer_stop(self->timer); + gptimer_disable(self->timer); + gptimer_del_timer(self->timer); + self->timer = NULL; + } + for (size_t i = 0; i < MP_ARRAY_SIZE(active_audio); i++) { + if (active_audio[i] == self) { + active_audio[i] = NULL; + } + } +} + +static void free_buffers(audiopwmio_pwmaudioout_obj_t *self) { + for (uint8_t i = 0; i < 2; i++) { + if (self->internal_data->buffers[i] != NULL) { + heap_caps_free(self->internal_data->buffers[i]); + self->internal_data->buffers[i] = NULL; + } + self->buffer_size[i] = 0; + self->internal_data->buffer_frames[i] = 0; + self->internal_data->buffer_ready[i] = false; + self->internal_data->last_buffer[i] = false; + } +} + +void audiopwmout_background(void) { + for (size_t i = 0; i < MP_ARRAY_SIZE(active_audio); i++) { + audiopwmio_pwmaudioout_obj_t *self = active_audio[i]; + if (self == NULL || !self->playing) { + continue; + } + if (self->internal_data->stop_queued) { + common_hal_audiopwmio_pwmaudioout_stop(self); + continue; + } + if (self->paused) { + continue; + } + for (uint8_t buf = 0; buf < 2; buf++) { + if (!self->internal_data->buffer_ready[buf] && !self->internal_data->stop_queued) { + fill_buffer(self, buf); + } + if (self->internal_data->single_buffer) { + // A single-buffer sample hands back the same memory every + // time, so there is nothing to gain from a second buffer. + break; + } + } + } +} + +// 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) { + + self->timer = NULL; + self->sample = NULL; + self->playing = false; + self->paused = false; + + self->internal_data = heap_caps_calloc(1, sizeof(audiopwmio_internal_data_t), + MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL); + if (self->internal_data == NULL) { + raise_esp_error(ESP_ERR_NO_MEM); + } + self->internal_data->stereo = right_channel != NULL; + self->internal_data->out_channels = right_channel != NULL ? 2 : 1; + + // variable_frequency is false so that the two channels of a stereo pair can + // share one LEDC timer. At PWM_FREQUENCY pwmio picks a PWM_BITS-wide duty. + pwmout_result_t result = common_hal_pwmio_pwmout_construct( + &self->left_pwm, left_channel, 0, PWM_FREQUENCY, false); + if (result == PWMOUT_OK && self->internal_data->stereo) { + result = common_hal_pwmio_pwmout_construct( + &self->right_pwm, right_channel, 0, PWM_FREQUENCY, false); + if (result != PWMOUT_OK) { + common_hal_pwmio_pwmout_deinit(&self->left_pwm); + } + } + if (result != PWMOUT_OK) { + heap_caps_free(self->internal_data); + self->internal_data = NULL; + common_hal_pwmio_pwmout_raise_error(result); + } + + // Copy the channel numbers in: the ISR must not reach into the pwmio + // objects, which live on the (possibly PSRAM) MicroPython heap. + self->internal_data->left_channel = self->left_pwm.chan_handle.channel; + if (self->internal_data->stereo) { + self->internal_data->right_channel = self->right_pwm.chan_handle.channel; + } + + self->internal_data->quiescent_value = quiescent_value >> SAMPLE_BITS_TO_DISCARD; + common_hal_pwmio_pwmout_set_duty_cycle(&self->left_pwm, quiescent_value); + if (self->internal_data->stereo) { + common_hal_pwmio_pwmout_set_duty_cycle(&self->right_pwm, quiescent_value); + } +} + +bool common_hal_audiopwmio_pwmaudioout_deinited(audiopwmio_pwmaudioout_obj_t *self) { + return self->internal_data == 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); + + common_hal_pwmio_pwmout_deinit(&self->left_pwm); + if (self->internal_data->stereo) { + common_hal_pwmio_pwmout_deinit(&self->right_pwm); + } + + heap_caps_free(self->internal_data); + self->internal_data = NULL; +} + +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); + } + + audiopwmio_internal_data_t *internal_data = self->internal_data; + audiosample_base_t *base = audiosample_check(sample); + + uint32_t sample_rate = audiosample_get_sample_rate(base); + if (sample_rate == 0 || sample_rate > TIMER_RESOLUTION_HZ) { + mp_arg_error_invalid(MP_QSTR_sample_rate); + } + + self->sample = sample; + internal_data->loop = loop; + self->bytes_per_sample = audiosample_get_bits_per_sample(base) / 8; + self->sample_channel_count = audiosample_get_channel_count(base); + + uint32_t max_buffer_length; + uint8_t spacing; + audiosample_get_buffer_structure(base, false, &internal_data->single_buffer, + &self->signed_to_unsigned, &max_buffer_length, &spacing); + + size_t frames = max_buffer_length / self->bytes_per_sample / self->sample_channel_count; + size_t buffer_size = frames * internal_data->out_channels * sizeof(uint16_t); + if (buffer_size == 0) { + mp_arg_error_invalid(MP_QSTR_sample); + } + if (buffer_size > MAX_BUFFER_BYTES) { + // These come out of internal RAM, so refuse rather than exhaust it. + raise_esp_error(ESP_ERR_NO_MEM); + } + + // Claim a slot before allocating, so a failure here frees nothing. + size_t slot = MP_ARRAY_SIZE(active_audio); + for (size_t i = 0; i < MP_ARRAY_SIZE(active_audio); i++) { + if (active_audio[i] == NULL) { + slot = i; + break; + } + } + if (slot == MP_ARRAY_SIZE(active_audio)) { + raise_esp_error(ESP_ERR_NOT_FOUND); + } + + free_buffers(self); + for (uint8_t i = 0; i < 2; i++) { + // The ISR reads these with the cache possibly disabled, so they have + // to be internal RAM too, not the MicroPython heap. + internal_data->buffers[i] = heap_caps_malloc(buffer_size, + MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL); + if (internal_data->buffers[i] == NULL) { + free_buffers(self); + raise_esp_error(ESP_ERR_NO_MEM); + } + self->buffer_size[i] = buffer_size; + if (internal_data->single_buffer) { + break; + } + } + + audiosample_reset_buffer(sample, false, 0); + + internal_data->playing_buffer = 0; + internal_data->playing_frame = 0; + internal_data->stop_queued = false; + self->paused = false; + self->playing = true; + + // Prime both buffers before the timer starts. + fill_buffer(self, 0); + if (!internal_data->single_buffer && !internal_data->stop_queued) { + fill_buffer(self, 1); + } + if (internal_data->stop_queued) { + // Nothing to play (empty or broken sample). Don't start the timer, or + // there would be nothing to shut it down again. + common_hal_audiopwmio_pwmaudioout_stop(self); + return; + } + + // The GPTimer driver is built cache-safe here, so it requires the callback + // in IRAM and its user context in internal RAM, and it only checks the + // latter two. Check all of it, so a regression shows up as an error from + // play() rather than as a fault at a random later moment. + if (!esp_ptr_in_iram((const void *)timer_alarm_cb) || + !esp_ptr_internal(internal_data) || + !esp_ptr_internal(internal_data->buffers[0]) || + (internal_data->buffers[1] != NULL && !esp_ptr_internal(internal_data->buffers[1]))) { + self->playing = false; + free_buffers(self); + raise_esp_error(ESP_ERR_INVALID_ARG); + } + + gptimer_config_t timer_config = { + .clk_src = GPTIMER_CLK_SRC_DEFAULT, + .direction = GPTIMER_COUNT_UP, + .resolution_hz = TIMER_RESOLUTION_HZ, + .intr_priority = 0, + }; + gptimer_event_callbacks_t callbacks = { + .on_alarm = timer_alarm_cb, + }; + // CircuitPython builds with CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM, under which + // gptimer_set_alarm_action() rejects a config that is not in internal RAM. + // The IDF docs call for a static instance here, so give it one. + static gptimer_alarm_config_t alarm_config; + alarm_config.alarm_count = TIMER_RESOLUTION_HZ / sample_rate; + alarm_config.reload_count = 0; + alarm_config.flags.auto_reload_on_alarm = true; + + active_audio[slot] = self; + esp_err_t err = gptimer_new_timer(&timer_config, &self->timer); + if (err == ESP_OK) { + err = gptimer_register_event_callbacks(self->timer, &callbacks, internal_data); + } + if (err == ESP_OK) { + err = gptimer_set_alarm_action(self->timer, &alarm_config); + } + if (err == ESP_OK) { + err = gptimer_enable(self->timer); + } + if (err == ESP_OK) { + err = gptimer_start(self->timer); + } + if (err != ESP_OK) { + // Leave nothing half-started: a stuck `playing` would hang any + // `while playing:` loop forever. + self->playing = false; + stop_timer(self); + free_buffers(self); + raise_esp_error(err); + } +} + +void common_hal_audiopwmio_pwmaudioout_stop(audiopwmio_pwmaudioout_obj_t *self) { + stop_timer(self); + + self->playing = false; + self->paused = false; + self->internal_data->stop_queued = false; + self->sample = NULL; + + // Park the output at the quiescent level so the speaker does not sit at a + // DC offset between samples. + uint16_t quiescent = self->internal_data->quiescent_value << SAMPLE_BITS_TO_DISCARD; + if (!common_hal_pwmio_pwmout_deinited(&self->left_pwm)) { + common_hal_pwmio_pwmout_set_duty_cycle(&self->left_pwm, quiescent); + } + if (self->internal_data->stereo && !common_hal_pwmio_pwmout_deinited(&self->right_pwm)) { + common_hal_pwmio_pwmout_set_duty_cycle(&self->right_pwm, quiescent); + } + + free_buffers(self); +} + +bool common_hal_audiopwmio_pwmaudioout_get_playing(audiopwmio_pwmaudioout_obj_t *self) { + return self->playing; +} + +void common_hal_audiopwmio_pwmaudioout_pause(audiopwmio_pwmaudioout_obj_t *self) { + if (!self->playing || self->paused || self->timer == NULL) { + return; + } + gptimer_stop(self->timer); + self->paused = true; +} + +void common_hal_audiopwmio_pwmaudioout_resume(audiopwmio_pwmaudioout_obj_t *self) { + if (!self->paused || self->timer == NULL) { + return; + } + self->paused = false; + gptimer_start(self->timer); +} + +bool common_hal_audiopwmio_pwmaudioout_get_paused(audiopwmio_pwmaudioout_obj_t *self) { + return self->paused; +} diff --git a/ports/espressif/common-hal/audiopwmio/PWMAudioOut.h b/ports/espressif/common-hal/audiopwmio/PWMAudioOut.h new file mode 100644 index 00000000000..423a6cd31c8 --- /dev/null +++ b/ports/espressif/common-hal/audiopwmio/PWMAudioOut.h @@ -0,0 +1,65 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tyeth Gundry +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "common-hal/microcontroller/Pin.h" +#include "common-hal/pwmio/PWMOut.h" + +#include "py/obj.h" + +#include "driver/gptimer.h" + +// The LEDC carrier is APB_CLK (80 MHz) / 2**PWM_BITS. 10 bits puts the carrier +// at 78.125 kHz: comfortably above hearing, while leaving 10 bits of amplitude +// resolution. Going finer drags the carrier down into the audible band. +#define PWM_BITS (10) +#define SAMPLE_BITS_TO_DISCARD (16 - PWM_BITS) + +// Everything the alarm ISR touches. CircuitPython builds the GPTimer driver +// with CONFIG_GPTIMER_ISR_CACHE_SAFE, so the ISR can run while the flash cache +// is disabled - during any flash write, including the user saving code.py. +// Anything it dereferences must therefore live in internal RAM, which the +// MicroPython heap is not: port_malloc() prefers PSRAM when a board has it. +typedef struct { + uint16_t *buffers[2]; // interleaved duty values, internal RAM + size_t buffer_frames[2]; // valid frames currently in each buffer + volatile size_t playing_frame; // read cursor within the active buffer + volatile uint8_t playing_buffer; // which buffer the ISR is draining + volatile bool buffer_ready[2]; // buffer holds data the ISR has not used + volatile bool last_buffer[2]; // this buffer ends the sample + volatile bool stop_queued; // the ISR reached the end of the sample + uint16_t quiescent_value; // scaled to PWM_BITS + uint8_t left_channel; // LEDC channel numbers, copied in so the + uint8_t right_channel; // ISR never reaches into the pwmio objects + uint8_t out_channels; // 1 or 2; the stride of buffers[] + bool stereo; + bool single_buffer; + bool loop; +} audiopwmio_internal_data_t; + +typedef struct { + mp_obj_base_t base; + + pwmio_pwmout_obj_t left_pwm; + pwmio_pwmout_obj_t right_pwm; + gptimer_handle_t timer; + + mp_obj_t sample; + audiopwmio_internal_data_t *internal_data; + + size_t buffer_size[2]; // allocated bytes, for the free path + + uint8_t sample_channel_count; + uint8_t bytes_per_sample; + + bool signed_to_unsigned; + bool playing; + bool paused; +} audiopwmio_pwmaudioout_obj_t; + +// Called from port_background_task(): refills buffers the ISR has drained. +void audiopwmout_background(void); diff --git a/ports/espressif/common-hal/audiopwmio/__init__.c b/ports/espressif/common-hal/audiopwmio/__init__.c new file mode 100644 index 00000000000..98db6232125 --- /dev/null +++ b/ports/espressif/common-hal/audiopwmio/__init__.c @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tyeth Gundry +// +// SPDX-License-Identifier: MIT + +// No audiopwmio module functions. diff --git a/ports/espressif/common-hal/busio/I2C.c b/ports/espressif/common-hal/busio/I2C.c index 98c453ba3c0..f9ad3082adb 100644 --- a/ports/espressif/common-hal/busio/I2C.c +++ b/ports/espressif/common-hal/busio/I2C.c @@ -9,7 +9,8 @@ #include "py/mphal.h" #include "py/runtime.h" -#include "components/driver/i2c/include/driver/i2c.h" +#include "driver/gpio.h" +#include "soc/soc_caps.h" #include "bindings/espidf/__init__.h" #include "shared-bindings/microcontroller/__init__.h" @@ -88,6 +89,19 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, } CHECK_ESP_RESULT(result); + // Record which port the auto-selected bus landed on. There is no public accessor to map + // a bus handle back to its port, so match the handle against each initialized port. + // Other code (e.g. espcamera) needs the port number to reuse this same bus rather than + // create a second master bus on the same pins. + self->port = -1; + for (i2c_port_num_t port = 0; port < (int)SOC_HP_I2C_NUM; port++) { + i2c_master_bus_handle_t bus_handle; + if (i2c_master_get_bus_handle(port, &bus_handle) == ESP_OK && bus_handle == self->handle) { + self->port = port; + break; + } + } + self->xSemaphore = xSemaphoreCreateMutex(); if (self->xSemaphore == NULL) { i2c_del_master_bus(self->handle); @@ -128,6 +142,12 @@ void common_hal_busio_i2c_deinit(busio_i2c_obj_t *self) { i2c_del_master_bus(self->handle); self->handle = NULL; + // Release the mutex before we delete it. Otherwise FreeRTOS gets unhappy. + xSemaphoreGive(self->xSemaphore); + vSemaphoreDelete(self->xSemaphore); + self->xSemaphore = NULL; + self->has_lock = false; + common_hal_reset_pin(self->sda_pin); common_hal_reset_pin(self->scl_pin); common_hal_busio_i2c_mark_deinit(self); @@ -160,20 +180,23 @@ bool common_hal_busio_i2c_has_lock(busio_i2c_obj_t *self) { } void common_hal_busio_i2c_unlock(busio_i2c_obj_t *self) { + if (common_hal_busio_i2c_deinited(self)) { + return; + } xSemaphoreGive(self->xSemaphore); self->has_lock = false; } -static uint8_t convert_esp_err(esp_err_t result) { +static mp_negative_errno_t convert_esp_err(esp_err_t result) { switch (result) { case ESP_OK: return 0; case ESP_FAIL: - return MP_ENODEV; + return -MP_ENODEV; case ESP_ERR_TIMEOUT: - return MP_ETIMEDOUT; + return -MP_ETIMEDOUT; default: - return MP_EIO; + return -MP_EIO; } } @@ -184,7 +207,7 @@ static size_t _transaction_duration_ms(size_t frequency, size_t len) { return (len + 1) / bytes_per_ms + 1000; } -uint8_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, const uint8_t *data, size_t len) { +mp_negative_errno_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, const uint8_t *data, size_t len) { i2c_device_config_t dev_config = { .dev_addr_length = I2C_ADDR_BIT_LEN_7, .device_address = addr, @@ -197,7 +220,7 @@ uint8_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, const u return convert_esp_err(result); } -uint8_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t addr, uint8_t *data, size_t len) { +mp_negative_errno_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t addr, uint8_t *data, size_t len) { i2c_device_config_t dev_config = { .dev_addr_length = I2C_ADDR_BIT_LEN_7, .device_address = addr, @@ -210,7 +233,7 @@ uint8_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t addr, uint8_t return convert_esp_err(result); } -uint8_t common_hal_busio_i2c_write_read(busio_i2c_obj_t *self, uint16_t addr, +mp_negative_errno_t common_hal_busio_i2c_write_read(busio_i2c_obj_t *self, uint16_t addr, uint8_t *out_data, size_t out_len, uint8_t *in_data, size_t in_len) { i2c_device_config_t dev_config = { .dev_addr_length = I2C_ADDR_BIT_LEN_7, @@ -223,8 +246,3 @@ uint8_t common_hal_busio_i2c_write_read(busio_i2c_obj_t *self, uint16_t addr, CHECK_ESP_RESULT(i2c_master_bus_rm_device(dev_handle)); return convert_esp_err(result); } - -void common_hal_busio_i2c_never_reset(busio_i2c_obj_t *self) { - common_hal_never_reset_pin(self->scl_pin); - common_hal_never_reset_pin(self->sda_pin); -} diff --git a/ports/espressif/common-hal/busio/I2C.h b/ports/espressif/common-hal/busio/I2C.h index 25d9791f252..ef69cba7091 100644 --- a/ports/espressif/common-hal/busio/I2C.h +++ b/ports/espressif/common-hal/busio/I2C.h @@ -8,7 +8,7 @@ #include "common-hal/microcontroller/Pin.h" -#include "components/hal/include/hal/i2c_types.h" +#include "hal/i2c_types.h" #include "FreeRTOS.h" #include "freertos/semphr.h" #include "py/obj.h" @@ -22,6 +22,7 @@ typedef struct { size_t timeout_ms; size_t frequency; i2c_master_bus_handle_t handle; + i2c_port_num_t port; SemaphoreHandle_t xSemaphore; bool has_lock; } busio_i2c_obj_t; diff --git a/ports/espressif/common-hal/busio/SPI.c b/ports/espressif/common-hal/busio/SPI.c index 6439ca41129..43c880b60b1 100644 --- a/ports/espressif/common-hal/busio/SPI.c +++ b/ports/espressif/common-hal/busio/SPI.c @@ -16,42 +16,76 @@ #define SPI_MAX_DMA_BITS (SPI_MAX_DMA_LEN * 8) #define MAX_SPI_TRANSACTIONS 10 -static bool spi_never_reset[SOC_SPI_PERIPH_NUM]; static spi_device_handle_t spi_handle[SOC_SPI_PERIPH_NUM]; -static StaticSemaphore_t spi_mutex[SOC_SPI_PERIPH_NUM]; static bool spi_bus_is_free(spi_host_device_t host_id) { return spi_bus_get_attr(host_id) == NULL; } -void spi_reset(void) { - for (spi_host_device_t host_id = SPI2_HOST; host_id < SOC_SPI_PERIPH_NUM; host_id++) { - if (spi_never_reset[host_id]) { - continue; - } - if (!spi_bus_is_free(host_id)) { - spi_bus_remove_device(spi_handle[host_id]); - spi_bus_free(host_id); - } +// Add a throwaway device at the given target clock, ask the driver what +// frequency it would actually produce, then remove it. Returns the actual +// frequency in Hz, or -1 if a device could not be added at that target. +static int spi_probe_actual_freq(busio_spi_obj_t *self, + spi_device_interface_config_t *device_config, int target_hz) { + device_config->clock_speed_hz = target_hz; + spi_device_handle_t handle; + if (spi_bus_add_device(self->host_id, device_config, &handle) != ESP_OK) { + return -1; } + int freq_khz = 0; + spi_device_get_actual_freq(handle, &freq_khz); + spi_bus_remove_device(handle); + return freq_khz * 1000; } static void set_spi_config(busio_spi_obj_t *self, uint32_t baudrate, uint8_t polarity, uint8_t phase, uint8_t bits) { - // 128 is a 50% duty cycle. - const int closest_clock = spi_get_actual_clock(APB_CLK_FREQ, baudrate, 128); - const spi_device_interface_config_t device_config = { - .clock_speed_hz = closest_clock, + spi_device_interface_config_t device_config = { + .clock_speed_hz = baudrate, .mode = phase | (polarity << 1), .spics_io_num = -1, // No CS pin .queue_size = MAX_SPI_TRANSACTIONS, .pre_cb = NULL }; + + // The ESP-IDF driver rounds clock_speed_hz to the nearest frequency it can + // produce, which may be HIGHER than requested. Treat baudrate as a ceiling: + // probe candidate targets (each time adding a throwaway device, asking the + // driver what it actually produced, and removing it) and keep the highest + // target whose actual frequency does not exceed baudrate. We don't inspect + // divisor internals -- those vary between Espressif chips -- only the + // public add/measure/remove API. + int target = baudrate; + int actual = spi_probe_actual_freq(self, &device_config, target); + if (actual < 0 || actual > (int)baudrate) { + // Bisect for the highest target whose actual frequency is <= baudrate. + // Stop refining once the interval is within 1 kHz, the resolution that + // spi_device_get_actual_freq reports. + int lo = 1; + int hi = baudrate; + while (hi - lo > 1000) { + int mid = lo + (hi - lo) / 2; + int mid_actual = spi_probe_actual_freq(self, &device_config, mid); + if (mid_actual >= 0 && mid_actual <= (int)baudrate) { + lo = mid; + } else { + hi = mid; + } + } + target = lo; + } + + device_config.clock_speed_hz = target; esp_err_t result = spi_bus_add_device(self->host_id, &device_config, &spi_handle[self->host_id]); if (result != ESP_OK) { mp_raise_RuntimeError(MP_ERROR_TEXT("SPI configuration failed")); } - self->baudrate = closest_clock; + + // Report the frequency the driver actually settled on for the real device. + int actual_khz = 0; + spi_device_get_actual_freq(spi_handle[self->host_id], &actual_khz); + self->baudrate = actual_khz * 1000; + self->requested_baudrate = baudrate; self->polarity = polarity; self->phase = phase; self->bits = bits; @@ -61,6 +95,12 @@ 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, bool half_duplex) { + // Ensure the object starts in its deinit state. + common_hal_busio_spi_mark_deinit(self); + #if CIRCUITPY_BUSIO_SPI_ASYNC + self->async_count = 0; + #endif + const spi_bus_config_t bus_config = { .mosi_io_num = mosi != NULL ? mosi->number : -1, .miso_io_num = miso != NULL ? miso->number : -1, @@ -90,7 +130,23 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, raise_ValueError_invalid_pins(); } - set_spi_config(self, 250000, 0, 0, 8); + self->mutex = xSemaphoreCreateMutex(); + if (self->mutex == NULL) { + spi_bus_free(self->host_id); + mp_raise_RuntimeError(MP_ERROR_TEXT("Unable to create lock")); + } + + // set_spi_config() can raise. Don't leave the bus and mutex behind. + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + set_spi_config(self, 250000, 0, 0, 8); + nlr_pop(); + } else { + vSemaphoreDelete(self->mutex); + self->mutex = NULL; + spi_bus_free(self->host_id); + nlr_jump(nlr.ret_val); + } self->MOSI = mosi; self->MISO = miso; @@ -103,40 +159,39 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, claim_pin(miso); } claim_pin(clock); - - self->mutex = xSemaphoreCreateMutexStatic(&spi_mutex[self->host_id]); -} - -void common_hal_busio_spi_never_reset(busio_spi_obj_t *self) { - spi_never_reset[self->host_id] = true; - common_hal_never_reset_pin(self->clock); - if (self->MOSI != NULL) { - common_hal_never_reset_pin(self->MOSI); - } - if (self->MISO != NULL) { - common_hal_never_reset_pin(self->MISO); - } } bool common_hal_busio_spi_deinited(busio_spi_obj_t *self) { return self->clock == NULL; } +void common_hal_busio_spi_mark_deinit(busio_spi_obj_t *self) { + self->clock = NULL; +} + void common_hal_busio_spi_deinit(busio_spi_obj_t *self) { if (common_hal_busio_spi_deinited(self)) { return; } - // Wait for any other users of this to finish. - while (!common_hal_busio_spi_try_lock(self)) { + // Wait for other users to finish. Ctrl-C ends the wait and leaves the bus up. + // The mutex isn't recursive, so if this task already holds the lock (code + // that ended without unlocking), don't wait: it would never be released. + while (!common_hal_busio_spi_has_lock(self) && !common_hal_busio_spi_try_lock(self)) { + if (mp_hal_is_interrupted()) { + return; + } RUN_BACKGROUND_TASKS; } - // Mark us as deinit early in case we are used in an interrupt. + #if CIRCUITPY_BUSIO_SPI_ASYNC + common_hal_busio_spi_end(self); + #endif + + // Mark as deinit early in case we are used in an interrupt. common_hal_reset_pin(self->clock); - self->clock = NULL; + common_hal_busio_spi_mark_deinit(self); - spi_never_reset[self->host_id] = false; spi_bus_remove_device(spi_handle[self->host_id]); spi_bus_free(self->host_id); @@ -151,30 +206,41 @@ 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) { - if (baudrate == self->baudrate && + if (baudrate == self->requested_baudrate && polarity == self->polarity && phase == self->phase && bits == self->bits) { return true; } + #if CIRCUITPY_BUSIO_SPI_ASYNC + common_hal_busio_spi_end(self); + #endif spi_bus_remove_device(spi_handle[self->host_id]); set_spi_config(self, baudrate, polarity, phase, bits); return true; } -bool common_hal_busio_spi_try_lock(busio_spi_obj_t *self) { +// Wait as long as needed for the lock. This is used by SD card access from USB. +// Overrides the default busy-wait implementation in shared-bindings/busio/SPI.c +bool common_hal_busio_spi_wait_for_lock(busio_spi_obj_t *self, uint32_t timeout_ms) { if (common_hal_busio_spi_deinited(self)) { return false; } - return xSemaphoreTake(self->mutex, 1) == pdTRUE; + return xSemaphoreTake(self->mutex, pdMS_TO_TICKS(timeout_ms)) == pdTRUE; +} + +bool common_hal_busio_spi_try_lock(busio_spi_obj_t *self) { + return common_hal_busio_spi_wait_for_lock(self, 0); } bool common_hal_busio_spi_has_lock(busio_spi_obj_t *self) { - return self->mutex != NULL && xSemaphoreGetMutexHolder(self->mutex) == xTaskGetCurrentTaskHandle(); + return (self->mutex != NULL) && (xSemaphoreGetMutexHolder(self->mutex) == xTaskGetCurrentTaskHandle()); } void common_hal_busio_spi_unlock(busio_spi_obj_t *self) { - xSemaphoreGive(self->mutex); + if (self->mutex != NULL) { + xSemaphoreGive(self->mutex); + } } bool common_hal_busio_spi_write(busio_spi_obj_t *self, @@ -259,20 +325,86 @@ bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, cur_trans++; } - for (int i = 0; i < cur_trans; i++) { - spi_device_queue_trans(spi_handle[self->host_id], &transactions[i], portMAX_DELAY); + // Queueing fails if the driver can't allocate a DMA-capable bounce buffer. Wait only for + // the transactions that were queued; waiting for any others would block forever. + esp_err_t result = ESP_OK; + int queued = 0; + while (queued < cur_trans) { + result = spi_device_queue_trans(spi_handle[self->host_id], &transactions[queued], portMAX_DELAY); + if (result != ESP_OK) { + break; + } + queued++; } spi_transaction_t *rtrans; - for (int x = 0; x < cur_trans; x++) { + for (int x = 0; x < queued; x++) { RUN_BACKGROUND_TASKS; spi_device_get_trans_result(spi_handle[self->host_id], &rtrans, portMAX_DELAY); } + if (result != ESP_OK) { + return false; + } } } return true; } +#if CIRCUITPY_BUSIO_SPI_ASYNC +void common_hal_busio_spi_write_start(busio_spi_obj_t *self, const uint8_t *data, size_t len, + circuitpy_async_flag_t *done) { + common_hal_busio_spi_end(self); + CIRCUITPY_ASYNC_FLAG_INIT(done); + self->async_done = done; + size_t chunks = (len + SPI_MAX_DMA_LEN - 1) / SPI_MAX_DMA_LEN; + // Short writes, other word sizes and writes needing more transactions than we keep go the + // normal way. + if (len <= 4 || self->bits != 8 || chunks > MP_ARRAY_SIZE(self->async_trans)) { + common_hal_busio_spi_write(self, data, len); + CIRCUITPY_ASYNC_FLAG_SET(done); + return; + } + size_t queued = 0; + while (queued < chunks) { + size_t offset = queued * SPI_MAX_DMA_LEN; + spi_transaction_t *trans = &self->async_trans[queued]; + memset(trans, 0, sizeof(*trans)); + trans->length = MIN(len - offset, SPI_MAX_DMA_LEN) * 8; + trans->tx_buffer = data + offset; + if (spi_device_queue_trans(spi_handle[self->host_id], trans, portMAX_DELAY) != ESP_OK) { + break; + } + queued++; + } + if (queued < chunks) { + // Queueing fails if the driver can't allocate a DMA-capable bounce buffer. Finish the + // chunks that were queued, then send the rest the normal way. + spi_transaction_t *trans; + for (size_t i = 0; i < queued; i++) { + spi_device_get_trans_result(spi_handle[self->host_id], &trans, portMAX_DELAY); + } + size_t offset = queued * SPI_MAX_DMA_LEN; + common_hal_busio_spi_write(self, data + offset, len - offset); + CIRCUITPY_ASYNC_FLAG_SET(done); + return; + } + self->async_count = chunks; +} + +void common_hal_busio_spi_end(busio_spi_obj_t *self) { + if (self->async_count == 0) { + return; + } + // No background tasks here: the caller holds the bus, and one of them may want it. + spi_transaction_t *trans; + while (self->async_count > 0) { + spi_device_get_trans_result(spi_handle[self->host_id], &trans, portMAX_DELAY); + self->async_count--; + } + CIRCUITPY_ASYNC_FLAG_SET(self->async_done); +} +#endif + uint32_t common_hal_busio_spi_get_frequency(busio_spi_obj_t *self) { return self->baudrate; } diff --git a/ports/espressif/common-hal/busio/SPI.h b/ports/espressif/common-hal/busio/SPI.h index 820f29333c7..37f1eba7f61 100644 --- a/ports/espressif/common-hal/busio/SPI.h +++ b/ports/espressif/common-hal/busio/SPI.h @@ -6,6 +6,8 @@ #pragma once +#include "py/mpconfig.h" +#include "supervisor/shared/async_flag.h" #include "driver/spi_master.h" #include "shared-bindings/microcontroller/Pin.h" @@ -21,9 +23,13 @@ typedef struct { uint8_t bits; uint8_t phase; uint8_t polarity; - uint32_t baudrate; + uint32_t baudrate; // Actual frequency, reported by the frequency property. + uint32_t requested_baudrate; // Value passed to configure(); used for the cache-hit check. SemaphoreHandle_t mutex; + #if CIRCUITPY_BUSIO_SPI_ASYNC + spi_transaction_t async_trans[2]; // queued by write_start, collected by end + uint8_t async_count; + circuitpy_async_flag_t *async_done; + #endif } busio_spi_obj_t; - -void spi_reset(void); diff --git a/ports/espressif/common-hal/busio/UART.c b/ports/espressif/common-hal/busio/UART.c index ad5e6fcef1b..793b43f88cd 100644 --- a/ports/espressif/common-hal/busio/UART.c +++ b/ports/espressif/common-hal/busio/UART.c @@ -7,6 +7,7 @@ #include "shared-bindings/microcontroller/__init__.h" #include "shared-bindings/microcontroller/Pin.h" #include "shared-bindings/busio/UART.h" +#include "bindings/espidf/__init__.h" #include "driver/uart.h" @@ -20,8 +21,6 @@ #include "supervisor/port.h" #include "supervisor/shared/tick.h" -static uint8_t never_reset_uart_mask = 0; - static void uart_event_task(void *param) { busio_uart_obj_t *self = param; uart_event_t event; @@ -52,28 +51,6 @@ static void uart_event_task(void *param) { } } -void uart_reset(void) { - for (uart_port_t num = 0; num < UART_NUM_MAX; num++) { - #ifdef CONFIG_ESP_CONSOLE_UART_NUM - // Do not reset the UART used by the IDF for logging. - if ((int)num == CONFIG_ESP_CONSOLE_UART_NUM) { - continue; - } - #endif - if (uart_is_driver_installed(num) && !(never_reset_uart_mask & (1 << num))) { - uart_driver_delete(num); - } - } -} - -void common_hal_busio_uart_never_reset(busio_uart_obj_t *self) { - common_hal_never_reset_pin(self->rx_pin); - common_hal_never_reset_pin(self->tx_pin); - common_hal_never_reset_pin(self->rts_pin); - common_hal_never_reset_pin(self->cts_pin); - never_reset_uart_mask |= 1 << self->uart_num; -} - 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, @@ -119,6 +96,17 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, #endif for (uart_port_t num = 0; num < UART_LIMIT; num++) { + // The IDF log console usually runs on the ROM's UART code, so no driver is installed on + // it and uart_is_driver_installed() can't see it. Skip it explicitly: uart_set_pin() + // below would move the console onto our pins, and its log output would then share our + // wire, which corrupts both the logs and the data. CircuitPython builds that own the + // console UART (CIRCUITPY_CONSOLE_UART) allocate it through this function, so only + // reserve the IDF console's UART when it isn't ours. + #if !CIRCUITPY_CONSOLE_UART && defined(CONFIG_ESP_CONSOLE_UART) && CONFIG_ESP_CONSOLE_UART + if (num == (uart_port_t)CONFIG_ESP_CONSOLE_UART_NUM) { + continue; + } + #endif if (!uart_is_driver_installed(num)) { self->uart_num = num; break; @@ -140,7 +128,7 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, uart_config.flow_ctrl = UART_HW_FLOWCTRL_CTS_RTS; } else if (have_rts) { uart_config.flow_ctrl = UART_HW_FLOWCTRL_RTS; - } else if (have_rts) { + } else if (have_cts) { uart_config.flow_ctrl = UART_HW_FLOWCTRL_CTS; } @@ -150,10 +138,16 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, uart_config.rx_flow_ctrl_thresh = UART_HW_FIFO_LEN(self->uart_num) - 8; // Install the driver before we change the settings. - if (uart_driver_install(self->uart_num, receiver_buffer_size, 0, 20, &self->event_queue, 0) != ESP_OK || - uart_set_mode(self->uart_num, mode) != ESP_OK) { + if (uart_driver_install(self->uart_num, receiver_buffer_size, 0, 20, &self->event_queue, 0) != ESP_OK) { + mp_raise_RuntimeError(MP_ERROR_TEXT("UART init")); + } + if (uart_set_mode(self->uart_num, mode) != ESP_OK) { + uart_driver_delete(self->uart_num); mp_raise_RuntimeError(MP_ERROR_TEXT("UART init")); } + // IDF interrupts at 120 of the 128 FIFO bytes, which leaves 8 byte times (40 us at 2 Mbaud) + // before bytes are dropped. Half the FIFO gives 320 us at 2 Mbaud. + uart_set_rx_full_threshold(self->uart_num, UART_HW_FIFO_LEN(self->uart_num) / 2); // On the console uart, enable pattern detection to look for CTRL+C #if CIRCUITPY_CONSOLE_UART @@ -164,14 +158,17 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, #endif // Start a task to listen for uart events - xTaskCreatePinnedToCore( + if (xTaskCreatePinnedToCore( uart_event_task, "uart_event_task", configMINIMAL_STACK_SIZE + 512, self, CONFIG_PTHREAD_TASK_PRIO_DEFAULT, &self->event_task, - xPortGetCoreID()); + xPortGetCoreID()) != pdPASS) { + uart_driver_delete(self->uart_num); + mp_raise_espidf_MemoryError(); + } // uart_set_hw_flow_ctrl(self->uart_num, uart_config.flow_control, uart_config.rx_flow_ctrl_thresh); // Set baud rate @@ -226,6 +223,8 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, // config all in one? if (uart_param_config(self->uart_num, &uart_config) != ESP_OK) { + vTaskDelete(self->event_task); + uart_driver_delete(self->uart_num); mp_raise_RuntimeError(MP_ERROR_TEXT("UART init")); } @@ -374,12 +373,16 @@ size_t common_hal_busio_uart_write(busio_uart_obj_t *self, const uint8_t *data, left_to_write -= count; data += count; RUN_BACKGROUND_TASKS; + // Allow user to break out of a write blocked by flow control. + if (mp_hal_is_interrupted()) { + break; + } } - while (uart_wait_tx_done(self->uart_num, 0) == ESP_ERR_TIMEOUT) { + while (uart_wait_tx_done(self->uart_num, 0) == ESP_ERR_TIMEOUT && !mp_hal_is_interrupted()) { RUN_BACKGROUND_TASKS; } - return len; + return len - left_to_write; } uint32_t common_hal_busio_uart_get_baudrate(busio_uart_obj_t *self) { diff --git a/ports/espressif/common-hal/busio/UART.h b/ports/espressif/common-hal/busio/UART.h index b84ef298a7d..2841822029d 100644 --- a/ports/espressif/common-hal/busio/UART.h +++ b/ports/espressif/common-hal/busio/UART.h @@ -29,5 +29,3 @@ typedef struct { QueueHandle_t event_queue; TaskHandle_t event_task; } busio_uart_obj_t; - -void uart_reset(void); diff --git a/ports/espressif/common-hal/canio/CAN.c b/ports/espressif/common-hal/canio/CAN.c index 941e454b124..b6086735829 100644 --- a/ports/espressif/common-hal/canio/CAN.c +++ b/ports/espressif/common-hal/canio/CAN.c @@ -260,9 +260,3 @@ void common_hal_canio_can_deinit(canio_can_obj_t *self) { self->tx_pin = NULL; self->rx_pin = NULL; } - -void common_hal_canio_reset(void) { - (void)twai_stop(); - (void)twai_driver_uninstall(); - reserved_can = false; -} diff --git a/ports/espressif/common-hal/countio/Counter.c b/ports/espressif/common-hal/countio/Counter.c index e754017ac3d..866fe55e4c3 100644 --- a/ports/espressif/common-hal/countio/Counter.c +++ b/ports/espressif/common-hal/countio/Counter.c @@ -16,8 +16,6 @@ void common_hal_countio_counter_construct(countio_counter_obj_t *self, const mcu_pin_obj_t *pin, countio_edge_t edge, digitalio_pull_t pull) { - claim_pin(pin); - pcnt_unit_config_t unit_config = { // Set counter limit .low_limit = INT16_MIN, @@ -38,7 +36,12 @@ void common_hal_countio_counter_construct(countio_counter_obj_t *self, .edge_gpio_num = self->pin, .level_gpio_num = -1 }; - CHECK_ESP_RESULT(pcnt_new_channel(self->unit, &channel_config, &self->channel)); + esp_err_t err = pcnt_new_channel(self->unit, &channel_config, &self->channel); + if (err != ESP_OK) { + pcnt_del_unit(self->unit); + self->unit = NULL; + CHECK_ESP_RESULT(err); + } pcnt_channel_edge_action_t pos = (edge == EDGE_RISE || edge == EDGE_RISE_AND_FALL) ? PCNT_CHANNEL_EDGE_ACTION_INCREASE : PCNT_CHANNEL_EDGE_ACTION_HOLD; pcnt_channel_edge_action_t neg = (edge == EDGE_FALL || edge == EDGE_RISE_AND_FALL) ? PCNT_CHANNEL_EDGE_ACTION_INCREASE : PCNT_CHANNEL_EDGE_ACTION_HOLD; pcnt_channel_set_edge_action(self->channel, pos, neg); @@ -54,6 +57,8 @@ void common_hal_countio_counter_construct(countio_counter_obj_t *self, pcnt_unit_enable(self->unit); pcnt_unit_start(self->unit); + + claim_pin(pin); } bool common_hal_countio_counter_deinited(countio_counter_obj_t *self) { diff --git a/ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c b/ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c new file mode 100644 index 00000000000..a4474bd698d --- /dev/null +++ b/ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c @@ -0,0 +1,150 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#include + +#include "py/runtime.h" + +#include "common-hal/hardwarekey/board.h" + +#include "shared-module/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.h" +#include "shared-module/hardwarekey/HardwareKey.h" + +#include "esp_heap_caps.h" + +// Pulls in MBEDTLS_CONFIG_FILE (esp_config.h), which is what defines +// ESP_RSA_DS_DRIVER_ENABLED on chips that have the Digital Signature +// peripheral. Including only goes through the tf-psa-crypto +// config path and does NOT define it, so the opaque-driver headers below +// would compile to nothing. +#include "mbedtls/build_info.h" +#include "psa/crypto.h" + +// The Digital Signature peripheral driver is genuinely optional: +// CIRCUITPY_HARDWAREKEY is on for every HMAC-capable chip, but not every one +// of those also has SOC_DIG_SIGN_SUPPORTED. Where it's absent, +// ESP_RSA_DS_DRIVER_ENABLED is undefined and DS purpose is simply never +// reported by hardwarekey_efuse_slot_load() -- no build-time #error. +#if defined(ESP_RSA_DS_DRIVER_ENABLED) +#include "esp_ds.h" +#include "psa_crypto_driver_esp_rsa_ds.h" +#include "psa_crypto_driver_esp_rsa_ds_contexts.h" + +// Persistent (non-GC) storage for a DS slot's imported key. Allocated lazily +// on first load and reused (overwritten in place) on a later call for the +// same slot -- the PSA RSA-DS driver only supports volatile keys (IDF-15427), +// so there is no psa_destroy_key() to pair a replacement with; the old PSA +// key id is simply abandoned along with its one HMAC-key eFuse block's worth +// of state. `generation` is bumped on every (re)load; see the field comment +// in shared-module/.../DigitalSignatureKey.h. +typedef struct { + esp_ds_data_t *data; + esp_ds_data_ctx_t *ctx; + esp_rsa_ds_opaque_key_t *opaque_key; + uint32_t generation; +} ds_slot_cache_t; +static ds_slot_cache_t ds_slot_cache[HARDWAREKEY_EFUSE_SLOT_COUNT]; + +void common_hal_cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_construct( + cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_obj_t *self, + hardwarekey_hardwarekey_obj_t *source_key, const uint8_t *ds_params, size_t ds_params_len) { + if (ds_params_len != sizeof(esp_ds_data_t)) { + mp_raise_ValueError(MP_ERROR_TEXT("ds_params has the wrong length")); + } + + mp_int_t slot = common_hal_hardwarekey_hardwarekey_get_key_slot(source_key); + ds_slot_cache_t *cache = &ds_slot_cache[slot]; + if (cache->data == NULL) { + cache->data = heap_caps_malloc(sizeof(esp_ds_data_t), MALLOC_CAP_8BIT); + cache->ctx = heap_caps_malloc(sizeof(esp_ds_data_ctx_t), MALLOC_CAP_8BIT); + cache->opaque_key = heap_caps_malloc(sizeof(esp_rsa_ds_opaque_key_t), MALLOC_CAP_8BIT); + if (cache->data == NULL || cache->ctx == NULL || cache->opaque_key == NULL) { + m_malloc_fail(sizeof(esp_ds_data_t)); + } + } + memcpy(cache->data, ds_params, sizeof(esp_ds_data_t)); + + // rsa_length is stored as (bits / 32) - 1 (see esp_digital_signature_length_t). + mp_int_t rsa_bits = ((mp_int_t)cache->data->rsa_length + 1) * 32; + + *cache->ctx = (esp_ds_data_ctx_t) { + .esp_ds_data = cache->data, + .efuse_key_id = (uint8_t)slot, + .rsa_length_bits = (uint16_t)rsa_bits, + }; + *cache->opaque_key = (esp_rsa_ds_opaque_key_t) { + .ds_data_ctx = cache->ctx, + }; + + // A new load for this slot invalidates any not-yet-committed + // DigitalSignatureKey previously obtained for it -- see ensure_algorithm(). + cache->generation++; + self->generation = cache->generation; + + // The actual PSA import is deferred to ensure_algorithm(), on the first + // sign()/decrypt() call -- see its declaration in shared-module for why. + self->key_id = 0; + self->committed_alg = PSA_ALG_NONE; + self->key_size = rsa_bits; +} + +void common_hal_cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_ensure_algorithm( + cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_obj_t *self, + psa_algorithm_t alg, psa_key_usage_t usage) { + if (self->key_id != 0) { + if (self->committed_alg != alg) { + mp_raise_ValueError(MP_ERROR_TEXT( + "This key already committed to a different algorithm; call load_digital_signature_key() again to use a different one")); + } + return; + } + + hardwarekey_hardwarekey_obj_t *source_key = MP_OBJ_TO_PTR(self->source_key); + mp_int_t slot = common_hal_hardwarekey_hardwarekey_get_key_slot(source_key); + ds_slot_cache_t *cache = &ds_slot_cache[slot]; + if (self->generation != cache->generation) { + mp_raise_ValueError(MP_ERROR_TEXT( + "This key's ds_params were replaced by a later load_digital_signature_key() call for the same key slot")); + } + + psa_key_attributes_t attr = PSA_KEY_ATTRIBUTES_INIT; + psa_set_key_type(&attr, PSA_KEY_TYPE_RSA_KEY_PAIR); + psa_set_key_bits(&attr, self->key_size); + psa_set_key_usage_flags(&attr, usage); + psa_set_key_algorithm(&attr, alg); + psa_set_key_lifetime(&attr, PSA_KEY_LIFETIME_ESP_RSA_DS_VOLATILE); + + psa_key_id_t key_id = 0; + psa_status_t status = psa_import_key(&attr, + (const uint8_t *)cache->opaque_key, sizeof(*cache->opaque_key), &key_id); + if (status != PSA_SUCCESS) { + mp_raise_ValueError(MP_ERROR_TEXT("ds_params is invalid for this key slot")); + } + + self->key_id = key_id; + self->committed_alg = alg; +} + +#else + +void common_hal_cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_construct( + cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_obj_t *self, + hardwarekey_hardwarekey_obj_t *source_key, const uint8_t *ds_params, size_t ds_params_len) { + // Unreachable in practice: a Digital Signature purpose is never reported + // by hardwarekey_efuse_slot_load() on a chip without the driver, and + // shared-bindings checks `purpose` before calling this. Kept as a body + // (not a build error) so this file still compiles on those chips. + mp_raise_NotImplementedError(MP_ERROR_TEXT("Digital Signature peripheral not available on this chip")); +} + +void common_hal_cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_ensure_algorithm( + cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_obj_t *self, + psa_algorithm_t alg, psa_key_usage_t usage) { + // Also unreachable: construct() above always raises first. + mp_raise_NotImplementedError(MP_ERROR_TEXT("Digital Signature peripheral not available on this chip")); +} + +#endif diff --git a/ports/espressif/common-hal/digitalio/DigitalInOut.c b/ports/espressif/common-hal/digitalio/DigitalInOut.c index ed537419405..cf5d8170381 100644 --- a/ports/espressif/common-hal/digitalio/DigitalInOut.c +++ b/ports/espressif/common-hal/digitalio/DigitalInOut.c @@ -11,11 +11,18 @@ #include "hal/gpio_hal.h" static bool _pin_is_input(uint8_t pin_number) { - const uint32_t iomux = READ_PERI_REG(GPIO_PIN_MUX_REG[pin_number]); - return (iomux & FUN_IE) != 0; + gpio_io_config_t config; + if (gpio_get_io_config((gpio_num_t)pin_number, &config) != ESP_OK) { + return false; + } + return config.ie; } void digitalio_digitalinout_preserve_for_deep_sleep(size_t n_dios, digitalio_digitalinout_obj_t *preserve_dios[]) { + // Start from no chip-wide hold, so a hold from an earlier (fake) deep sleep + // isn't left on. preserve_pin_number() turns it back on if any pin is preserved. + disable_deep_sleep_pin_hold(); + // Mark the pin states of the given DigitalInOuts for preservation during deep sleep for (size_t i = 0; i < n_dios; i++) { if (!common_hal_digitalio_digitalinout_deinited(preserve_dios[i])) { @@ -24,11 +31,6 @@ void digitalio_digitalinout_preserve_for_deep_sleep(size_t n_dios, digitalio_dig } } -void common_hal_digitalio_digitalinout_never_reset( - 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) { claim_pin(pin); @@ -103,6 +105,10 @@ digitalinout_result_t common_hal_digitalio_digitalinout_set_drive_mode( gpio_mode_t mode = GPIO_MODE_OUTPUT; if (drive_mode == DRIVE_MODE_OPEN_DRAIN) { mode |= GPIO_MODE_OUTPUT_OD; + // Turn on open drain before gpio_set_direction() enables the output driver. It + // enables the output first, so a pin coming from input would briefly drive a + // push-pull high. On an I2C SDA line held low by a peripheral, that is a STOP. + gpio_od_enable(number); } esp_err_t result = gpio_set_direction(number, mode); if (result != ESP_OK) { @@ -113,10 +119,12 @@ 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) { - if (GPIO_HAL_GET_HW(GPIO_PORT_0)->pin[self->pin->number].pad_driver == 1) { + gpio_io_config_t config; + if (gpio_get_io_config((gpio_num_t)self->pin->number, &config) != ESP_OK) { + // Should it fail closed or open? return DRIVE_MODE_OPEN_DRAIN; } - return DRIVE_MODE_PUSH_PULL; + return config.od ? DRIVE_MODE_OPEN_DRAIN : DRIVE_MODE_PUSH_PULL; } digitalinout_result_t common_hal_digitalio_digitalinout_set_pull( @@ -134,11 +142,10 @@ digitalinout_result_t common_hal_digitalio_digitalinout_set_pull( digitalio_pull_t common_hal_digitalio_digitalinout_get_pull( 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)) { - return PULL_UP; - } else if (REG_GET_BIT(GPIO_PIN_MUX_REG[gpio_num], FUN_PD)) { - return PULL_DOWN; + gpio_io_config_t config; + if (gpio_get_io_config((gpio_num_t)self->pin->number, &config) != ESP_OK) { + // Should it fail closed or open? + return PULL_NONE; } - return PULL_NONE; + return config.pd ? PULL_DOWN : PULL_UP; } diff --git a/ports/espressif/common-hal/dotclockframebuffer/DotClockFramebuffer.c b/ports/espressif/common-hal/dotclockframebuffer/DotClockFramebuffer.c index 591c455722e..844808315ae 100644 --- a/ports/espressif/common-hal/dotclockframebuffer/DotClockFramebuffer.c +++ b/ports/espressif/common-hal/dotclockframebuffer/DotClockFramebuffer.c @@ -14,7 +14,7 @@ #include "hal/dma_types.h" #include "hal/lcd_hal.h" #include "hal/lcd_ll.h" -#include "soc/lcd_periph.h" +#include "hal/lcd_periph.h" #include "esp_log.h" #define TAG "LCD" @@ -34,9 +34,7 @@ #include "hal/gpio_hal.h" #include "soc/lcd_cam_struct.h" #include "esp_heap_caps.h" - -// should be from rom/cache.h but it wasn't working -int Cache_WriteBack_Addr(uint32_t addr, uint32_t size); +#include "esp_cache.h" #define LCD_RGB_ISR_IRAM_SAFE (1) #define LCD_RGB_INTR_ALLOC_FLAGS (ESP_INTR_FLAG_IRAM | ESP_INTR_FLAG_INTRDISABLED) @@ -48,7 +46,6 @@ static void claim_and_record(const mcu_pin_obj_t *pin, uint64_t *used_pins_mask) int number = common_hal_mcu_pin_number(pin); *used_pins_mask |= (UINT64_C(1) << number); claim_pin_number(number); - never_reset_pin_number(number); } } @@ -103,14 +100,13 @@ void common_hal_dotclockframebuffer_framebuffer_construct(dotclockframebuffer_fr cfg->timings.vsync_back_porch = vsync_back_porch; cfg->timings.vsync_front_porch = vsync_front_porch; cfg->timings.flags.hsync_idle_low = hsync_idle_low; - cfg->timings.flags.vsync_idle_low = hsync_idle_low; + cfg->timings.flags.vsync_idle_low = vsync_idle_low; cfg->timings.flags.de_idle_high = de_idle_high; cfg->timings.flags.pclk_active_neg = !pclk_active_high; cfg->timings.flags.pclk_idle_high = pclk_idle_high; cfg->data_width = 16; - cfg->sram_trans_align = 8; - cfg->psram_trans_align = 64; + cfg->dma_burst_size = 64; cfg->hsync_gpio_num = valid_pin(hsync, MP_QSTR_hsync); cfg->vsync_gpio_num = valid_pin(vsync, MP_QSTR_vsync); cfg->de_gpio_num = valid_pin(de, MP_QSTR_de); @@ -142,6 +138,16 @@ void common_hal_dotclockframebuffer_framebuffer_construct(dotclockframebuffer_fr cfg->flags.refresh_on_demand = 0; cfg->flags.fb_in_psram = 1; // allocate frame buffer in PSRAM + // Stream the PSRAM frame buffer through bounce buffers in internal RAM so + // that PSRAM access stalls cannot starve the LCD DMA. The frame buffer size + // must be a multiple of the bounce buffer size, so pick up to 10 lines that + // divide the height evenly. + int bounce_lines = 10; + while (bounce_lines > 1 && height % bounce_lines != 0) { + bounce_lines--; + } + cfg->bounce_buffer_size_px = cfg->timings.h_res * bounce_lines; + esp_err_t ret = esp_lcd_new_rgb_panel(&self->panel_config, &self->panel_handle); CHECK_ESP_RESULT(ret); CHECK_ESP_RESULT(esp_lcd_panel_reset(self->panel_handle)); @@ -204,7 +210,7 @@ mp_int_t common_hal_dotclockframebuffer_framebuffer_get_first_pixel_offset(dotcl } void common_hal_dotclockframebuffer_framebuffer_refresh(dotclockframebuffer_framebuffer_obj_t *self) { - Cache_WriteBack_Addr((uint32_t)(self->bufinfo.buf), self->bufinfo.len); + esp_cache_msync(self->bufinfo.buf, self->bufinfo.len, ESP_CACHE_MSYNC_FLAG_DIR_C2M | ESP_CACHE_MSYNC_FLAG_UNALIGNED); } mp_int_t common_hal_dotclockframebuffer_framebuffer_get_refresh_rate(dotclockframebuffer_framebuffer_obj_t *self) { diff --git a/ports/espressif/common-hal/espcamera/Camera.c b/ports/espressif/common-hal/espcamera/Camera.c index 5b45a26951e..f491db7968c 100644 --- a/ports/espressif/common-hal/espcamera/Camera.c +++ b/ports/espressif/common-hal/espcamera/Camera.c @@ -21,6 +21,12 @@ #error espcamera only works on boards configured with spiram, disable it in mpconfigboard.mk #endif +// The underlying esp-camera driver only handles a singleton camera. +// Track the camera object that owns the shared esp-camera driver so deinit +// can tell whether it should release it (and its device on the shared I2C +// bus) before the I2C bus is deinited. +static espcamera_camera_obj_t *live_camera = NULL; + static void i2c_lock(espcamera_camera_obj_t *self) { if (common_hal_busio_i2c_deinited(self->i2c)) { raise_deinited_error(); @@ -42,7 +48,7 @@ static void maybe_claim_pin(const mcu_pin_obj_t *pin) { void common_hal_espcamera_camera_construct( espcamera_camera_obj_t *self, - uint8_t data_pins[8], + const mcu_pin_obj_t **data_pins, const mcu_pin_obj_t *external_clock_pin, const mcu_pin_obj_t *pixel_clock_pin, const mcu_pin_obj_t *vsync_pin, @@ -57,8 +63,18 @@ void common_hal_espcamera_camera_construct( mp_int_t framebuffer_count, camera_grab_mode_t grab_mode) { + // Start the external clock before claiming anything: if it fails, nothing is left claimed. + if (external_clock_pin) { + common_hal_pwmio_pwmout_raise_error( + common_hal_pwmio_pwmout_construct(&self->pwm, external_clock_pin, 1, external_clock_frequency, true)); + self->camera_config.ledc_timer = self->pwm.tim_handle.timer_num; + self->camera_config.ledc_channel = self->pwm.chan_handle.channel; + } else { + self->camera_config.ledc_channel = 0xff; // NO_CAMERA_LEDC_CHANNEL + } + for (int i = 0; i < 8; i++) { - claim_pin_number(data_pins[i]); + claim_pin(data_pins[i]); } maybe_claim_pin(external_clock_pin); claim_pin(pixel_clock_pin); @@ -67,14 +83,6 @@ void common_hal_espcamera_camera_construct( maybe_claim_pin(powerdown_pin); maybe_claim_pin(reset_pin); - if (external_clock_pin) { - common_hal_pwmio_pwmout_construct(&self->pwm, external_clock_pin, 1, external_clock_frequency, true); - self->camera_config.ledc_timer = self->pwm.tim_handle.timer_num; - self->camera_config.ledc_channel = self->pwm.chan_handle.channel; - } else { - self->camera_config.ledc_channel = 0xff; // NO_CAMERA_LEDC_CHANNEL - } - self->i2c = i2c; // These pins might be NULL because they were not specified. @@ -86,16 +94,20 @@ void common_hal_espcamera_camera_construct( self->camera_config.pin_reset = reset_pin ? common_hal_mcu_pin_number(reset_pin) : NO_PIN; self->camera_config.pin_xclk = external_clock_pin ? common_hal_mcu_pin_number(external_clock_pin) : NO_PIN; - self->camera_config.sccb_i2c_master_bus_handle = self->i2c->handle; - - self->camera_config.pin_d7 = data_pins[7]; - self->camera_config.pin_d6 = data_pins[6]; - self->camera_config.pin_d5 = data_pins[5]; - self->camera_config.pin_d4 = data_pins[4]; - self->camera_config.pin_d3 = data_pins[3]; - self->camera_config.pin_d2 = data_pins[2]; - self->camera_config.pin_d1 = data_pins[1]; - self->camera_config.pin_d0 = data_pins[0]; + // Reuse the I2C bus that CircuitPython already created on these pins instead of letting + // esp32-camera create a second master bus on the same pins, which doesn't work. + self->camera_config.pin_sccb_sda = -1; + self->camera_config.pin_sccb_scl = -1; + self->camera_config.sccb_i2c_port = i2c->port; + + self->camera_config.pin_d7 = common_hal_mcu_pin_number(data_pins[7]); + self->camera_config.pin_d6 = common_hal_mcu_pin_number(data_pins[6]); + self->camera_config.pin_d5 = common_hal_mcu_pin_number(data_pins[5]); + self->camera_config.pin_d4 = common_hal_mcu_pin_number(data_pins[4]); + self->camera_config.pin_d3 = common_hal_mcu_pin_number(data_pins[3]); + self->camera_config.pin_d2 = common_hal_mcu_pin_number(data_pins[2]); + self->camera_config.pin_d1 = common_hal_mcu_pin_number(data_pins[1]); + self->camera_config.pin_d0 = common_hal_mcu_pin_number(data_pins[0]); self->camera_config.pin_vsync = common_hal_mcu_pin_number(vsync_pin); self->camera_config.pin_href = common_hal_mcu_pin_number(href_pin); @@ -116,6 +128,16 @@ void common_hal_espcamera_camera_construct( i2c_unlock(self); CHECK_ESP_RESULT(result); + + // Only record the camera once esp_camera_init() has succeeded, so a failed + // second construction doesn't overwrite the live singleton. + live_camera = self; +} + +void espcamera_reset(void) { + if (live_camera != NULL) { + common_hal_espcamera_camera_deinit(live_camera); + } } extern void common_hal_espcamera_camera_deinit(espcamera_camera_obj_t *self) { @@ -123,6 +145,14 @@ extern void common_hal_espcamera_camera_deinit(espcamera_camera_obj_t *self) { return; } + // Only tear down the shared esp-camera driver if this object owns it. A + // second, failed construction leaves live_camera pointing at the first + // camera; deiniting that failed object must not destroy the live one. + bool was_live = (live_camera == self); + if (was_live) { + live_camera = NULL; + } + common_hal_pwmio_pwmout_deinit(&self->pwm); // Does nothing if pin is NO_PIN (-1). @@ -139,7 +169,9 @@ extern void common_hal_espcamera_camera_deinit(espcamera_camera_obj_t *self) { reset_pin_number(self->camera_config.pin_d1); reset_pin_number(self->camera_config.pin_d0); - esp_camera_deinit(); + if (was_live) { + esp_camera_deinit(); + } reset_pin_number(self->camera_config.pin_pclk); reset_pin_number(self->camera_config.pin_vsync); @@ -153,7 +185,7 @@ bool common_hal_espcamera_camera_deinited(espcamera_camera_obj_t *self) { } bool common_hal_espcamera_camera_available(espcamera_camera_obj_t *self) { - return esp_camera_fb_available(); + return esp_camera_available_frames(); } camera_fb_t *common_hal_espcamera_camera_take(espcamera_camera_obj_t *self, int timeout_ms) { diff --git a/ports/espressif/common-hal/espcamera/Camera.h b/ports/espressif/common-hal/espcamera/Camera.h index 718fe9a69c4..dd099558aa6 100644 --- a/ports/espressif/common-hal/espcamera/Camera.h +++ b/ports/espressif/common-hal/espcamera/Camera.h @@ -18,3 +18,7 @@ typedef struct espcamera_camera_obj { pwmio_pwmout_obj_t pwm; busio_i2c_obj_t *i2c; } espcamera_obj_t; + +// Deinitialize the active camera, if any, so it releases its device on the +// shared I2C bus. Called from reset_port_early(). +void espcamera_reset(void); diff --git a/ports/espressif/common-hal/espidf/__init__.c b/ports/espressif/common-hal/espidf/__init__.c index 83e30657750..60dc7b35b7b 100644 --- a/ports/espressif/common-hal/espidf/__init__.c +++ b/ports/espressif/common-hal/espidf/__init__.c @@ -27,7 +27,8 @@ static size_t psram_size_usable(void) { #ifdef CONFIG_SPIRAM /* PSRAM chip may be larger than the size we can map into address space */ - #ifdef CONFIG_IDF_TARGET_ESP32P4 + #if defined(CONFIG_IDF_TARGET_ESP32P4) || defined(CONFIG_IDF_TARGET_ESP32C5) || defined(CONFIG_IDF_TARGET_ESP32S31) + // These targets don't define SOC_EXTRAM_DATA_SIZE. size_t s = esp_psram_get_size(); #else size_t s = MIN(esp_psram_get_size(), SOC_EXTRAM_DATA_SIZE); diff --git a/ports/espressif/common-hal/espnow/ESPNow.c b/ports/espressif/common-hal/espnow/ESPNow.c index 79bded96fb4..9988ffe88e3 100644 --- a/ports/espressif/common-hal/espnow/ESPNow.c +++ b/ports/espressif/common-hal/espnow/ESPNow.c @@ -17,6 +17,7 @@ #include "common-hal/espnow/ESPNow.h" +#include "esp_now.h" #include "mphalport.h" #include "esp_now.h" @@ -56,7 +57,7 @@ typedef struct { // Callback triggered when a sent packet is acknowledged by the peer (or not). // Just count the number of responses and number of failures. // These are used in the send() logic. -static void send_cb(const uint8_t *mac, esp_now_send_status_t status) { +static void send_cb(const esp_now_send_info_t *tx_info, esp_now_send_status_t status) { espnow_obj_t *self = MP_STATE_PORT(espnow_singleton); if (status == ESP_NOW_SEND_SUCCESS) { self->send_success++; @@ -119,10 +120,20 @@ void common_hal_espnow_init(espnow_obj_t *self) { common_hal_wifi_radio_set_enabled(&common_hal_wifi_radio_obj, true); } - CHECK_ESP_RESULT(esp_wifi_config_espnow_rate(ESP_IF_WIFI_STA, self->phy_rate)); - CHECK_ESP_RESULT(esp_wifi_config_espnow_rate(ESP_IF_WIFI_AP, self->phy_rate)); - CHECK_ESP_RESULT(esp_now_init()); + + // esp_now_set_peer_rate_config() is poorly documented, and we haven't figured out + // what the esp_now_rate_config_t settings should be. For now, just ignore phy_rate. + // Note that esp_now_set_peer_rate_config() must be called after esp_now-init(). + // + // esp_now_rate_config_t rate_config = { + // .phymode = WIFI_PHY_MODE_LR, + // .rate = self->phy_rate, + // .ersu = false, + // .dcm = false, + // }; + // CHECK_ESP_RESULT(esp_now_set_peer_rate_config(NULL, &rate_config)); + CHECK_ESP_RESULT(esp_now_register_send_cb(send_cb)); CHECK_ESP_RESULT(esp_now_register_recv_cb(recv_cb)); } @@ -142,11 +153,6 @@ void common_hal_espnow_deinit(espnow_obj_t *self) { self->recv_buffer = NULL; } -void espnow_reset(void) { - common_hal_espnow_deinit(MP_STATE_PORT(espnow_singleton)); - MP_STATE_PORT(espnow_singleton) = NULL; -} - void common_hal_espnow_set_phy_rate(espnow_obj_t *self, mp_int_t value) { self->phy_rate = mp_arg_validate_int_range(value, 0, WIFI_PHY_RATE_MAX - 1, MP_QSTR_phy_rate); }; diff --git a/ports/espressif/common-hal/espnow/ESPNow.h b/ports/espressif/common-hal/espnow/ESPNow.h index b68e1544fb8..bc70ee4abc9 100644 --- a/ports/espressif/common-hal/espnow/ESPNow.h +++ b/ports/espressif/common-hal/espnow/ESPNow.h @@ -25,8 +25,6 @@ typedef struct _espnow_obj_t { volatile size_t read_failure; } espnow_obj_t; -extern void espnow_reset(void); - extern void common_hal_espnow_construct(espnow_obj_t *self, mp_int_t buffer_size, mp_int_t phy_rate); extern void common_hal_espnow_init(espnow_obj_t *self); extern void common_hal_espnow_deinit(espnow_obj_t *self); diff --git a/ports/espressif/common-hal/espulp/ULP.c b/ports/espressif/common-hal/espulp/ULP.c index 7756054b06a..c325e74e934 100644 --- a/ports/espressif/common-hal/espulp/ULP.c +++ b/ports/espressif/common-hal/espulp/ULP.c @@ -32,11 +32,6 @@ static bool ulp_used = false; static uint32_t pins_used = 0; -void espulp_reset(void) { - // NOTE: This *doesn't* disable the ULP. It'll keep running even when CircuitPython isn't. - ulp_used = false; -} - void common_hal_espulp_ulp_set_wakeup_period(espulp_ulp_obj_t *self, size_t period_index, uint32_t period_us) { CHECK_ESP_RESULT(ulp_set_wakeup_period(period_index, period_us)); } @@ -69,7 +64,6 @@ void common_hal_espulp_ulp_run(espulp_ulp_obj_t *self, uint32_t *program, size_t for (uint8_t i = 0; i < 32; i++) { if ((pin_mask & (1 << i)) != 0) { claim_pin_number(i); - never_reset_pin_number(i); } } pins_used = pin_mask; diff --git a/ports/espressif/common-hal/frequencyio/FrequencyIn.c b/ports/espressif/common-hal/frequencyio/FrequencyIn.c index 96644348504..72fb36e0b91 100644 --- a/ports/espressif/common-hal/frequencyio/FrequencyIn.c +++ b/ports/espressif/common-hal/frequencyio/FrequencyIn.c @@ -117,7 +117,7 @@ void common_hal_frequencyio_frequencyin_construct(frequencyio_frequencyin_obj_t self->pin = pin->number; self->capture_period_ms = capture_period_ms; - self->internal_data = heap_caps_malloc(MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL, sizeof(_internal_data_t)); + self->internal_data = heap_caps_malloc(sizeof(_internal_data_t), MALLOC_CAP_8BIT | MALLOC_CAP_INTERNAL); if (self->internal_data == NULL) { raise_esp_error(ESP_ERR_NO_MEM); } diff --git a/ports/espressif/common-hal/hardwarekey/HardwareKey.c b/ports/espressif/common-hal/hardwarekey/HardwareKey.c new file mode 100644 index 00000000000..f325b3723ea --- /dev/null +++ b/ports/espressif/common-hal/hardwarekey/HardwareKey.c @@ -0,0 +1,109 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +// The one port-specific step: turn an eFuse key block into a PSA key id. +// Everything after that -- hmac.new()'s use of the key id, sign() -- lives in +// shared-module/hardwarekey/HardwareKey.c. Digital Signature key handling +// lives in +// ports/espressif/common-hal/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c. + +#include "py/runtime.h" + +#include "common-hal/hardwarekey/__init__.h" +#include "common-hal/hardwarekey/board.h" + +#include "shared-module/hardwarekey/HardwareKey.h" + +#include "esp_efuse.h" + +// board.h hardcodes the slot count (enum values can't be used in #if); make sure +// it still matches this chip's eFuse layout. +_Static_assert(HARDWAREKEY_EFUSE_SLOT_COUNT == EFUSE_BLK_KEY_MAX - EFUSE_BLK_KEY0, + "eFuse key block count changed; update common-hal/hardwarekey/board.h"); + +// Pulls in MBEDTLS_CONFIG_FILE (esp_config.h), which is what defines +// ESP_HMAC_OPAQUE_DRIVER_ENABLED / ESP_RSA_DS_DRIVER_ENABLED on chips that +// have those peripherals. Including only goes through the +// tf-psa-crypto config path and does NOT define either, so the opaque-driver +// headers below would compile to nothing. +#include "mbedtls/build_info.h" +#include "psa/crypto.h" +// Public header of the ESP-IDF mbedtls component's PSA opaque-key driver for +// eFuse HMAC keys (components/mbedtls/port/psa_driver/include/). +#include "psa_crypto_driver_esp_hmac_opaque.h" + +#if !defined(ESP_HMAC_OPAQUE_DRIVER_ENABLED) +#error "hardwarekey requires the ESP-IDF PSA opaque HMAC driver (SOC_HMAC_SUPPORTED targets only)" +#endif + +// The ESP HMAC peripheral consumes a 256-bit eFuse key. +#define HMAC_KEY_BITS 256 + +// One PSA key is imported per eFuse block. The imports are volatile references +// (no key material) and survive a CircuitPython soft reset -- ESP-IDF initializes +// PSA once at boot and never frees it -- so this only runs once per block. +static psa_key_id_t import_efuse_hmac_key(mp_int_t slot) { + psa_key_attributes_t attr = PSA_KEY_ATTRIBUTES_INIT; + psa_set_key_type(&attr, PSA_KEY_TYPE_HMAC); + psa_set_key_bits(&attr, HMAC_KEY_BITS); + psa_set_key_algorithm(&attr, PSA_ALG_HMAC(PSA_ALG_SHA_256)); + psa_set_key_usage_flags(&attr, PSA_KEY_USAGE_SIGN_MESSAGE | PSA_KEY_USAGE_VERIFY_MESSAGE); + psa_set_key_lifetime(&attr, PSA_KEY_LIFETIME_ESP_HMAC_VOLATILE); + + // Import data is a *reference* to the eFuse block, not key material. The + // driver independently re-checks the HMAC_UP purpose and refuses anything else. + esp_hmac_opaque_key_t keyref = { .efuse_key_id = (uint8_t)slot }; + + psa_key_id_t key_id = 0; + if (psa_import_key(&attr, (const uint8_t *)&keyref, sizeof(keyref), &key_id) != PSA_SUCCESS) { + return 0; + } + return key_id; +} + +bool hardwarekey_efuse_slot_load(mp_int_t slot, hardwarekey_hardwarekey_obj_t *key) { + key->key_slot = slot; + key->key_id = 0; + key->purpose = HARDWAREKEY_PURPOSE_UNUSED; + key->exportable = false; + + esp_efuse_block_t block = (esp_efuse_block_t)(EFUSE_BLK_KEY0 + slot); + esp_efuse_purpose_t block_purpose = esp_efuse_get_key_purpose(block); + + if (block_purpose == ESP_EFUSE_KEY_PURPOSE_HMAC_DOWN_DIGITAL_SIGNATURE) { + // No PSA import yet: unlike HMAC_UP, this purpose alone doesn't name a + // full key -- the caller still has to supply ds_params via + // cryptography.hazmat.primitives.asymmetric.rsa.load_digital_signature_key(). + // Just record that the slot is provisioned for it. + #if defined(ESP_RSA_DS_DRIVER_ENABLED) + key->purpose = HARDWAREKEY_PURPOSE_DS; + key->exportable = !esp_efuse_get_key_dis_read(block); + return true; + #else + return false; + #endif + } + + if (block_purpose != ESP_EFUSE_KEY_PURPOSE_HMAC_UP) { + return false; + } + + // PSA is already initialized by ssl / hashlib, but psa_crypto_init() is + // idempotent and keeps hardwarekey working on a build with neither. + if (psa_crypto_init() != PSA_SUCCESS) { + return false; + } + + psa_key_id_t key_id = import_efuse_hmac_key(slot); + if (key_id == 0) { + return false; + } + + key->key_id = key_id; + key->purpose = HARDWAREKEY_PURPOSE_HMAC; + key->exportable = !esp_efuse_get_key_dis_read(block); + return true; +} diff --git a/ports/espressif/common-hal/hardwarekey/__init__.c b/ports/espressif/common-hal/hardwarekey/__init__.c new file mode 100644 index 00000000000..2d33ed9a4ab --- /dev/null +++ b/ports/espressif/common-hal/hardwarekey/__init__.c @@ -0,0 +1,30 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#include "common-hal/hardwarekey/__init__.h" +#include "common-hal/hardwarekey/board.h" + +#include "shared-bindings/hardwarekey/HardwareKey.h" + +// The objects board.EFUSE_KEY0 .. board.EFUSE_KEY point at (see board.h). +// Static, not heap: the board globals dict is const and outlives the GC heap +// across a soft reset, so these must too. No GC-traced pointers inside. +hardwarekey_hardwarekey_obj_t hardwarekey_efuse_keys[HARDWAREKEY_EFUSE_SLOT_COUNT]; + +// board.EFUSE_KEYn, for repr(). Can't assume MP_QSTR_EFUSE_KEY0 + n are contiguous. +static const qstr slot_names[HARDWAREKEY_EFUSE_SLOT_COUNT] = { + MP_QSTR_EFUSE_KEY0, MP_QSTR_EFUSE_KEY1, MP_QSTR_EFUSE_KEY2, + MP_QSTR_EFUSE_KEY3, MP_QSTR_EFUSE_KEY4, MP_QSTR_EFUSE_KEY5, +}; + +void espressif_hardwarekey_init(void) { + for (mp_int_t slot = 0; slot < HARDWAREKEY_EFUSE_SLOT_COUNT; slot++) { + hardwarekey_hardwarekey_obj_t *key = &hardwarekey_efuse_keys[slot]; + key->base.type = &hardwarekey_hardwarekey_type; + key->name = slot_names[slot]; + hardwarekey_efuse_slot_load(slot, key); + } +} diff --git a/ports/espressif/common-hal/hardwarekey/__init__.h b/ports/espressif/common-hal/hardwarekey/__init__.h new file mode 100644 index 00000000000..e6c55b51bd2 --- /dev/null +++ b/ports/espressif/common-hal/hardwarekey/__init__.h @@ -0,0 +1,20 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +#include "shared-module/hardwarekey/HardwareKey.h" + +// Probe every eFuse key block and fill in the board.EFUSE_KEY* HardwareKey +// objects. Call once at startup, before user code. Never raises. +void espressif_hardwarekey_init(void); + +// Fill in `key` for eFuse key block `slot`. Sets key->purpose to HMAC when the +// block is burned HMAC_UP (importing its PSA key), else HARDWAREKEY_PURPOSE_UNUSED. +// Never raises. Returns true when the slot ended up usable. +bool hardwarekey_efuse_slot_load(mp_int_t slot, hardwarekey_hardwarekey_obj_t *key); diff --git a/ports/espressif/common-hal/hardwarekey/board.h b/ports/espressif/common-hal/hardwarekey/board.h new file mode 100644 index 00000000000..0ac32fa140c --- /dev/null +++ b/ports/espressif/common-hal/hardwarekey/board.h @@ -0,0 +1,30 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#pragma once + +// board.EFUSE_KEY0 .. board.EFUSE_KEY5: one fixed entry per eFuse key block, +// injected into every board's globals table through CIRCUITPY_BOARD_HARDWARE_KEYS +// (see shared-bindings/board/__init__.h). Each points at a static HardwareKey the +// startup probe (espressif_hardwarekey_init) fills in -- so, like board pins, the +// names exist at compile time and the objects are ready before user code runs. + +#include "shared-module/hardwarekey/HardwareKey.h" + +// Every HMAC-capable Espressif chip (S2/S3/C3/C5/C6/H2/P4) has 6 eFuse key blocks. +// HardwareKey.c static-asserts this against EFUSE_BLK_KEY_MAX - EFUSE_BLK_KEY0; +// if a future chip differs, update this list (and the assert) to match. +#define HARDWAREKEY_EFUSE_SLOT_COUNT 6 + +extern hardwarekey_hardwarekey_obj_t hardwarekey_efuse_keys[HARDWAREKEY_EFUSE_SLOT_COUNT]; + +#define CIRCUITPY_BOARD_HARDWARE_KEYS \ + { MP_ROM_QSTR(MP_QSTR_EFUSE_KEY0), MP_ROM_PTR(&hardwarekey_efuse_keys[0]) }, \ + { MP_ROM_QSTR(MP_QSTR_EFUSE_KEY1), MP_ROM_PTR(&hardwarekey_efuse_keys[1]) }, \ + { MP_ROM_QSTR(MP_QSTR_EFUSE_KEY2), MP_ROM_PTR(&hardwarekey_efuse_keys[2]) }, \ + { MP_ROM_QSTR(MP_QSTR_EFUSE_KEY3), MP_ROM_PTR(&hardwarekey_efuse_keys[3]) }, \ + { MP_ROM_QSTR(MP_QSTR_EFUSE_KEY4), MP_ROM_PTR(&hardwarekey_efuse_keys[4]) }, \ + { MP_ROM_QSTR(MP_QSTR_EFUSE_KEY5), MP_ROM_PTR(&hardwarekey_efuse_keys[5]) }, diff --git a/ports/espressif/common-hal/i2ctarget/I2CTarget.c b/ports/espressif/common-hal/i2ctarget/I2CTarget.c index 003e7731faa..9f6217eeeb8 100644 --- a/ports/espressif/common-hal/i2ctarget/I2CTarget.c +++ b/ports/espressif/common-hal/i2ctarget/I2CTarget.c @@ -12,6 +12,19 @@ #include "common-hal/i2ctarget/I2CTarget.h" #include "shared-bindings/microcontroller/Pin.h" +static bool i2c_slave_on_receive(i2c_slave_dev_handle_t i2c_slave, const i2c_slave_rx_done_event_data_t *evt_data, void *arg) { + i2ctarget_i2c_target_obj_t *self = (i2ctarget_i2c_target_obj_t *)arg; + for (uint32_t i = 0; i < evt_data->length; i++) { + uint16_t next_head = (self->recv_head + 1) % I2CTARGET_RECV_BUF_SIZE; + if (next_head == self->recv_tail) { + break; // buffer full + } + self->recv_buf[self->recv_head] = evt_data->buffer[i]; + self->recv_head = next_head; + } + return false; +} + void common_hal_i2ctarget_i2c_target_construct(i2ctarget_i2c_target_obj_t *self, const mcu_pin_obj_t *scl, const mcu_pin_obj_t *sda, uint8_t *addresses, unsigned int num_addresses, bool smbus) { @@ -29,34 +42,42 @@ void common_hal_i2ctarget_i2c_target_construct(i2ctarget_i2c_target_obj_t *self, self->addresses = addresses; self->num_addresses = num_addresses; - self->sda_pin = sda; - self->scl_pin = scl; - self->i2c_num = peripherals_i2c_get_free_num(); - - if (self->i2c_num == I2C_NUM_MAX) { - mp_raise_ValueError(MP_ERROR_TEXT("All I2C peripherals are in use")); - } - - const i2c_config_t i2c_conf = { - .mode = I2C_MODE_SLAVE, - .sda_io_num = self->sda_pin->number, - .scl_io_num = self->scl_pin->number, - .sda_pullup_en = GPIO_PULLUP_ENABLE, - .scl_pullup_en = GPIO_PULLUP_ENABLE, - .slave.addr_10bit_en = 0, - .slave.slave_addr = self->addresses[0], + self->recv_head = 0; + self->recv_tail = 0; + + i2c_slave_config_t slave_config = { + .i2c_port = -1, // auto + .sda_io_num = sda->number, + .scl_io_num = scl->number, + .clk_source = I2C_CLK_SRC_DEFAULT, + .send_buf_depth = 256, + .receive_buf_depth = 256, + .slave_addr = addresses[0], + .addr_bit_len = I2C_ADDR_BIT_LEN_7, + .flags = { + .enable_internal_pullup = true, + }, }; - // Initialize I2C. - esp_err_t err = peripherals_i2c_init(self->i2c_num, &i2c_conf); + esp_err_t err = i2c_new_slave_device(&slave_config, &self->handle); if (err != ESP_OK) { - if (err == ESP_FAIL) { + if (err == ESP_ERR_NOT_FOUND) { + mp_raise_ValueError(MP_ERROR_TEXT("All I2C peripherals are in use")); + } else if (err == ESP_FAIL) { mp_raise_OSError(MP_EIO); } else { mp_arg_error_invalid(MP_QSTR_I2CTarget); } } + self->sda_pin = sda; + self->scl_pin = scl; + + i2c_slave_event_callbacks_t cbs = { + .on_receive = i2c_slave_on_receive, + }; + i2c_slave_register_event_callbacks(self->handle, &cbs, self); + claim_pin(sda); claim_pin(scl); } @@ -70,7 +91,8 @@ void common_hal_i2ctarget_i2c_target_deinit(i2ctarget_i2c_target_obj_t *self) { return; } - peripherals_i2c_deinit(self->i2c_num); + i2c_del_slave_device(self->handle); + self->handle = NULL; common_hal_reset_pin(self->sda_pin); common_hal_reset_pin(self->scl_pin); @@ -83,24 +105,34 @@ int common_hal_i2ctarget_i2c_target_is_addressed(i2ctarget_i2c_target_obj_t *sel *address = self->addresses[0]; *is_read = true; *is_restart = false; - return 1; + // Check if we have received data + if (self->recv_head != self->recv_tail) { + *is_read = false; + return 1; + } + return 0; } int common_hal_i2ctarget_i2c_target_read_byte(i2ctarget_i2c_target_obj_t *self, uint8_t *data) { - i2c_slave_read_buffer(self->i2c_num, data, 128, 0); + if (self->recv_head == self->recv_tail) { + return 0; // no data available + } + *data = self->recv_buf[self->recv_tail]; + self->recv_tail = (self->recv_tail + 1) % I2CTARGET_RECV_BUF_SIZE; return 1; } int common_hal_i2ctarget_i2c_target_write_byte(i2ctarget_i2c_target_obj_t *self, uint8_t data) { - i2c_reset_tx_fifo(self->i2c_num); - i2c_slave_write_buffer(self->i2c_num, &data, 128, 0); + uint32_t write_len; + esp_err_t err = i2c_slave_write(self->handle, &data, 1, &write_len, 100); + if (err != ESP_OK || write_len == 0) { + return 0; + } return 1; } void common_hal_i2ctarget_i2c_target_ack(i2ctarget_i2c_target_obj_t *self, bool ack) { - } void common_hal_i2ctarget_i2c_target_close(i2ctarget_i2c_target_obj_t *self) { - } diff --git a/ports/espressif/common-hal/i2ctarget/I2CTarget.h b/ports/espressif/common-hal/i2ctarget/I2CTarget.h index 2dcfb581eb3..fc41ac84ebc 100644 --- a/ports/espressif/common-hal/i2ctarget/I2CTarget.h +++ b/ports/espressif/common-hal/i2ctarget/I2CTarget.h @@ -7,14 +7,19 @@ #pragma once #include "py/obj.h" -#include "peripherals/i2c.h" +#include "driver/i2c_slave.h" #include "common-hal/microcontroller/Pin.h" +#define I2CTARGET_RECV_BUF_SIZE 128 + typedef struct { mp_obj_base_t base; - i2c_port_t i2c_num; + i2c_slave_dev_handle_t handle; uint8_t *addresses; uint8_t num_addresses; const mcu_pin_obj_t *scl_pin; const mcu_pin_obj_t *sda_pin; + uint8_t recv_buf[I2CTARGET_RECV_BUF_SIZE]; + volatile uint16_t recv_head; + volatile uint16_t recv_tail; } i2ctarget_i2c_target_obj_t; diff --git a/ports/espressif/common-hal/jpegio/JpegDecoder.c b/ports/espressif/common-hal/jpegio/JpegDecoder.c new file mode 100644 index 00000000000..33387d2686f --- /dev/null +++ b/ports/espressif/common-hal/jpegio/JpegDecoder.c @@ -0,0 +1,218 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mikey Sklar +// +// SPDX-License-Identifier: MIT + +// Hardware JPEG decode for jpegio, on chips with SOC_JPEG_DECODE_SUPPORTED. +// The engine decodes a whole baseline JPEG to RGB565 with no scaling, so only +// decode() calls with scale=0 into a 16-bit Bitmap take this path. Anything the +// hardware does not handle returns false and jpegio falls back to TJpgDec. + +#include "py/runtime.h" + +#include "shared-bindings/bitmaptools/__init__.h" +#include "shared-module/displayio/Bitmap.h" +#include "shared-module/jpegio/JpegDecoder.h" + +#include "driver/jpeg_decode.h" +#include "esp_cache.h" +#include "esp_heap_caps.h" +#include "esp_memory_utils.h" + +// A bad image blocks the engine for at most this long. +#define JPEG_DECODE_TIMEOUT_MS (1000) + +void jpegio_jpegdecoder_hw_init(jpegio_jpegdecoder_obj_t *self) { + jpeg_decode_engine_cfg_t engine_config = { + .timeout_ms = JPEG_DECODE_TIMEOUT_MS, + }; + jpeg_decoder_handle_t engine; + if (jpeg_new_decoder_engine(&engine_config, &engine) != ESP_OK) { + engine = NULL; + } + self->hw_decoder = engine; +} + +void jpegio_jpegdecoder_hw_deinit(jpegio_jpegdecoder_obj_t *self) { + if (self->hw_decoder != NULL) { + jpeg_del_decoder_engine(self->hw_decoder); + self->hw_decoder = NULL; + } +} + +// GC blocks start on a cache line, so the engine can write Bitmap pixels directly. +#ifdef CONFIG_CACHE_L2_CACHE_LINE_SIZE +_Static_assert(MICROPY_BYTES_PER_GC_BLOCK % CONFIG_CACHE_L2_CACHE_LINE_SIZE == 0, "GC block is not a cache line"); +#endif +#ifdef CONFIG_CACHE_L1_DCACHE_LINE_SIZE +_Static_assert(MICROPY_BYTES_PER_GC_BLOCK % CONFIG_CACHE_L1_DCACHE_LINE_SIZE == 0, "GC block is not a cache line"); +#endif + +// True if the hardware may write `size` bytes at `buf` directly: the start and +// length must both be whole cache lines. +static bool output_aligned(const void *buf, size_t size) { + size_t align = esp_cache_get_line_size_by_addr(buf); + if (align < 4) { + align = 4; + } + return ((uintptr_t)buf & (align - 1)) == 0 && (size & (align - 1)) == 0; +} + +// These return false so decode() uses TJpgDec, or raise ValueError if +// software decoding is not allowed. +static bool use_software(jpegio_jpegdecoder_obj_t *self, mp_rom_error_text_t msg) { + if (!self->software_ok) { + mp_raise_ValueError(msg); + } + return false; +} + +static bool use_software_for_arg(jpegio_jpegdecoder_obj_t *self, qstr arg_name) { + if (!self->software_ok) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("Invalid %q"), arg_name); + } + return false; +} + +bool jpegio_jpegdecoder_hw_decode(jpegio_jpegdecoder_obj_t *self, const mp_buffer_info_t *jpeg, int scale) { + if (self->hw_decoder == NULL) { + return use_software(self, MP_ERROR_TEXT("Operation or feature not supported")); + } + displayio_bitmap_t *bitmap = self->dest; + if (scale != 0) { + return use_software_for_arg(self, MP_QSTR_scale); + } + if (bitmap->bits_per_value != 16 || bitmap->read_only) { + return use_software_for_arg(self, MP_QSTR_bitmap); + } + // Skip indices are slower on this path than in TJpgDec. + if (!self->skip_source_index_none) { + return use_software_for_arg(self, MP_QSTR_skip_source_index); + } + if (!self->skip_dest_index_none) { + return use_software_for_arg(self, MP_QSTR_skip_dest_index); + } + // The engine reads the input by DMA, so it must be in DMA-capable memory. + if (!esp_ptr_dma_capable(jpeg->buf) && !esp_ptr_dma_ext_capable(jpeg->buf)) { + return use_software_for_arg(self, MP_QSTR_data_source); + } + + jpeg_decode_picture_info_t info; + if (jpeg_decoder_get_info(jpeg->buf, jpeg->len, &info) != ESP_OK) { + return use_software(self, MP_ERROR_TEXT("Format not supported")); + } + + // The engine pads its output to whole MCUs: 8x8 for 4:4:4, 16x8 for 4:2:2 + // and 16x16 for 4:2:0. Grayscale is left to TJpgDec. + uint32_t mcu_width, mcu_height; + switch (info.sample_method) { + case JPEG_DOWN_SAMPLING_YUV444: + mcu_width = 8; + mcu_height = 8; + break; + case JPEG_DOWN_SAMPLING_YUV422: + mcu_width = 16; + mcu_height = 8; + break; + case JPEG_DOWN_SAMPLING_YUV420: + mcu_width = 16; + mcu_height = 16; + break; + default: + return use_software(self, MP_ERROR_TEXT("Format not supported")); + } + uint32_t width = info.width; + uint32_t height = info.height; + // The driver rejects images whose pixel count is not a multiple of 8. + if ((width * height) % 8 != 0) { + return use_software(self, MP_ERROR_TEXT("Format not supported")); + } + uint32_t output_width = (width + mcu_width - 1) / mcu_width * mcu_width; + uint32_t output_height = (height + mcu_height - 1) / mcu_height * mcu_height; + size_t output_size = output_width * output_height * sizeof(uint16_t); + + // Decode straight into the Bitmap when it is exactly the image, unpadded and + // cache-line aligned, and the whole image lands at 0,0. + bool direct = width == output_width && height == output_height && + bitmap->width == width && bitmap->height == height && + self->x == 0 && self->y == 0 && + self->lim.x1 <= 0 && self->lim.y1 <= 0 && + self->lim.x2 >= (int)width && self->lim.y2 >= (int)height && + output_aligned(bitmap->data, output_size); + + // Otherwise decode into a temporary buffer and copy the visible part out of it. + uint8_t *output; + size_t output_buffer_size; + uint8_t *scratch = NULL; + if (direct) { + output = (uint8_t *)bitmap->data; + output_buffer_size = output_size; + } else { + jpeg_decode_memory_alloc_cfg_t mem_config = { + .buffer_direction = JPEG_DEC_ALLOC_OUTPUT_BUFFER, + }; + scratch = jpeg_alloc_decoder_mem(output_size, &mem_config, &output_buffer_size); + if (scratch == NULL) { + return use_software(self, MP_ERROR_TEXT("Operation or feature not supported")); + } + output = scratch; + } + + // RGB order with RGB565 makes the engine emit the high byte first, the same + // byte-swapped RGB565 that TJpgDec produces here. JFIF files use full range + // BT601 YCbCr. + jpeg_decode_cfg_t decode_config = { + .output_format = JPEG_DECODE_OUT_FORMAT_RGB565, + .rgb_order = JPEG_DEC_RGB_ELEMENT_ORDER_RGB, + .conv_std = JPEG_YUV_RGB_CONV_STD_BT601, + .yuv_range = COLOR_RANGE_FULL, + }; + uint32_t decoded_size; + if (jpeg_decoder_process(self->hw_decoder, &decode_config, jpeg->buf, jpeg->len, + output, output_buffer_size, &decoded_size) != ESP_OK) { + // A failed direct decode may have written part of the Bitmap. TJpgDec + // then decodes the whole image over it. + heap_caps_free(scratch); + return use_software(self, MP_ERROR_TEXT("Format not supported")); + } + + if (direct) { + displayio_bitmap_set_dirty(bitmap, 0, 0, width, height); + return true; + } + + // Copy out the visible part with the same clipping TJpgDec's output callback + // applies, treating the whole image as a single block at 0,0. + displayio_bitmap_t src = { + .width = width, + .height = height, + .data = (uint32_t *)(void *)output, + .stride = output_width / 2, // in units of uint32_t + .bits_per_value = 16, + .x_shift = 1, + .x_mask = 1, + .bitmask = 0xffff, + }; + int x = self->x; + int y = self->y; + int x1 = self->lim.x1; + int y1 = self->lim.y1; + int x2 = MIN(self->lim.x2, (int)width); + int y2 = MIN(self->lim.y2, (int)height); + if (x1 < 0) { + x += -x1; + x1 = 0; + } + if (y1 < 0) { + y += -y1; + y1 = 0; + } + if (x2 > 0 && y2 > 0) { + common_hal_bitmaptools_blit(bitmap, &src, x, y, x1, y1, x2, y2, + self->skip_source_index, self->skip_source_index_none, + self->skip_dest_index, self->skip_dest_index_none); + } + heap_caps_free(scratch); + return true; +} diff --git a/ports/espressif/common-hal/jpegio/JpegDecoderFast.c b/ports/espressif/common-hal/jpegio/JpegDecoderFast.c new file mode 100644 index 00000000000..7eb3524ff92 --- /dev/null +++ b/ports/espressif/common-hal/jpegio/JpegDecoderFast.c @@ -0,0 +1,162 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mikey Sklar +// +// SPDX-License-Identifier: MIT + +// Faster software JPEG decode for jpegio, using Espressif's esp_new_jpeg +// library. On the ESP32-S3 it uses the PIE SIMD instructions for the IDCT and +// color conversion. Anything it does not handle returns false and jpegio +// decodes with TJpgDec instead. + +#include "py/runtime.h" + +#include "shared-bindings/bitmaptools/__init__.h" +#include "shared-module/displayio/Bitmap.h" +#include "shared-module/jpegio/JpegDecoder.h" + +#include "esp_jpeg_dec.h" + +// The S3 SIMD code needs a 16-byte aligned output buffer. Buffers from +// m_malloc start on a GC block, so they are aligned. +#define OUTPUT_ALIGNMENT (16) +_Static_assert(MICROPY_BYTES_PER_GC_BLOCK % OUTPUT_ALIGNMENT == 0, "GC block is not 16-byte aligned"); + +typedef enum { + MODE_NONE, // leave it to TJpgDec + MODE_DIRECT, // decode straight into the Bitmap + MODE_BANDS, // decode a band of rows at a time and blit each into the Bitmap +} fast_mode_t; + +static bool decode_direct(jpeg_dec_config_t *config, jpeg_dec_io_t *io, displayio_bitmap_t *bitmap) { + jpeg_dec_handle_t decoder; + if (jpeg_dec_open(config, &decoder) != JPEG_ERR_OK) { + return false; + } + jpeg_dec_header_info_t info; + int outbuf_len; + bool ok = jpeg_dec_parse_header(decoder, io, &info) == JPEG_ERR_OK && + jpeg_dec_get_outbuf_len(decoder, &outbuf_len) == JPEG_ERR_OK && + (size_t)outbuf_len == bitmap->width * bitmap->height * sizeof(uint16_t); + if (ok) { + io->outbuf = (uint8_t *)bitmap->data; + ok = jpeg_dec_process(decoder, io) == JPEG_ERR_OK; + } + jpeg_dec_close(decoder); + if (ok) { + displayio_area_t area = { 0, 0, bitmap->width, bitmap->height, NULL }; + displayio_bitmap_set_dirty_area(bitmap, &area); + } + return ok; +} + +// Copies each band with the same clipping as TJpgDec's output. +static bool decode_bands(jpegio_jpegdecoder_obj_t *self, jpeg_dec_config_t *config, jpeg_dec_io_t *io) { + int width = self->decoder.width; + int height = self->decoder.height; + jpeg_dec_handle_t decoder; + config->block_enable = true; + if (jpeg_dec_open(config, &decoder) != JPEG_ERR_OK) { + return false; + } + jpeg_dec_header_info_t info; + int outbuf_len; + int band_count; + uint32_t *band = NULL; + bool ok = jpeg_dec_parse_header(decoder, io, &info) == JPEG_ERR_OK && + info.width == width && info.height == height && + jpeg_dec_get_outbuf_len(decoder, &outbuf_len) == JPEG_ERR_OK && + jpeg_dec_get_process_count(decoder, &band_count) == JPEG_ERR_OK && + outbuf_len > 0 && outbuf_len % (width * 2) == 0; + if (ok) { + band = m_malloc_maybe(outbuf_len); + ok = band != NULL; + } + int top = 0; + for (int i = 0; ok && i < band_count; i++) { + io->outbuf = (uint8_t *)band; + if (jpeg_dec_process(decoder, io) != JPEG_ERR_OK) { + ok = false; + break; + } + // The last band of a 4:2:0 image can be padded past the bottom of the image. + int rows = MIN(io->out_size / (width * 2), height - top); + if (rows <= 0) { + break; + } + displayio_bitmap_t src = { + .width = width, + .height = rows, + .data = band, + .stride = width / 2, // in units of uint32_t + .bits_per_value = 16, + .x_shift = 1, + .x_mask = 1, + .bitmask = 0xffff, + }; + if (!jpegio_jpegdecoder_blit_rect(self, &src, 0, top)) { + break; + } + top += rows; + } + jpeg_dec_close(decoder); + m_free(band); + return ok; +} + +static fast_mode_t choose_mode(jpegio_jpegdecoder_obj_t *self, int scale) { + displayio_bitmap_t *bitmap = self->dest; + // TJpgDec raises the right error for these. + if (bitmap->bits_per_value != 16 || bitmap->read_only) { + return MODE_NONE; + } + // Colors differ slightly from TJpgDec's, which would change which pixels + // match a skip index. + if (!self->skip_source_index_none || !self->skip_dest_index_none) { + return MODE_NONE; + } + bool gray = self->decoder.ncomp == 1; + bool yuv420 = self->decoder.msx == 2 && self->decoder.msy == 2; + if (scale != 0 || !(gray || yuv420)) { + return MODE_NONE; + } + + int width = self->decoder.width; + int height = self->decoder.height; + bool whole = bitmap->width == width && bitmap->height == height && + self->x == 0 && self->y == 0 && + self->lim.x1 <= 0 && self->lim.y1 <= 0 && + self->lim.x2 >= width && self->lim.y2 >= height; + // Bitmap rows are padded to 32 bits, so an odd width is not packed. + bool packed = bitmap->stride * sizeof(uint32_t) == width * sizeof(uint16_t) && + ((uintptr_t)bitmap->data & (OUTPUT_ALIGNMENT - 1)) == 0; + if (whole && packed) { + return MODE_DIRECT; + } + // Band mode needs whole MCUs across and whole 8x8 blocks down. + if (width % (self->decoder.msx * 8) == 0 && height % 8 == 0) { + return MODE_BANDS; + } + return MODE_NONE; +} + +bool jpegio_jpegdecoder_fast_supported(jpegio_jpegdecoder_obj_t *self, int scale) { + return choose_mode(self, scale) != MODE_NONE; +} + +bool jpegio_jpegdecoder_fast_decode(jpegio_jpegdecoder_obj_t *self, const mp_buffer_info_t *jpeg, int scale) { + jpeg_dec_config_t config = DEFAULT_JPEG_DEC_CONFIG(); + config.output_type = JPEG_PIXEL_FORMAT_RGB565_BE; // RGB565_SWAPPED, as TJpgDec + jpeg_dec_io_t io = { + .inbuf = jpeg->buf, + .inbuf_len = jpeg->len, + }; + switch (choose_mode(self, scale)) { + case MODE_DIRECT: + return decode_direct(&config, &io, self->dest); + case MODE_BANDS: + return decode_bands(self, &config, &io); + default: + return false; + } +} diff --git a/ports/espressif/common-hal/max3421e/Max3421E.c b/ports/espressif/common-hal/max3421e/Max3421E.c index c4e2dd79062..7aa2bc58569 100644 --- a/ports/espressif/common-hal/max3421e/Max3421E.c +++ b/ports/espressif/common-hal/max3421e/Max3421E.c @@ -65,7 +65,8 @@ void common_hal_max3421e_max3421e_init_irq(max3421e_max3421e_obj_t *self) { const mcu_pin_obj_t *pin = self->irq.pin; esp_err_t result = gpio_install_isr_service(ESP_INTR_FLAG_SHARED); - if (result != ESP_OK) { + // ESP_ERR_INVALID_STATE means another object already installed the service. + if (result != ESP_OK && result != ESP_ERR_INVALID_STATE) { vTaskDelete(usb_host_task_handle); CHECK_ESP_RESULT(result); } @@ -81,7 +82,7 @@ void common_hal_max3421e_max3421e_init_irq(max3421e_max3421e_obj_t *self) { void common_hal_max3421e_max3421e_deinit_irq(max3421e_max3421e_obj_t *self) { const mcu_pin_obj_t *pin = self->irq.pin; gpio_isr_handler_remove(pin->number); - gpio_uninstall_isr_service(); + // Leave the GPIO ISR service installed: other objects may have handlers on it. vTaskDelete(usb_host_task_handle); } diff --git a/ports/espressif/common-hal/mdns/RemoteService.c b/ports/espressif/common-hal/mdns/RemoteService.c index 515a3f7bf02..3d80199397e 100644 --- a/ports/espressif/common-hal/mdns/RemoteService.c +++ b/ports/espressif/common-hal/mdns/RemoteService.c @@ -9,56 +9,27 @@ #include "shared-bindings/ipaddress/IPv4Address.h" const char *common_hal_mdns_remoteservice_get_service_type(mdns_remoteservice_obj_t *self) { - if (self->result == NULL) { - return ""; - } - return self->result->service_type; + return self->service_name; } const char *common_hal_mdns_remoteservice_get_protocol(mdns_remoteservice_obj_t *self) { - if (self->result == NULL) { - return ""; - } - return self->result->proto; + return self->protocol; } const char *common_hal_mdns_remoteservice_get_instance_name(mdns_remoteservice_obj_t *self) { - if (self->result == NULL) { - return ""; - } - return self->result->instance_name; + return self->instance_name; } const char *common_hal_mdns_remoteservice_get_hostname(mdns_remoteservice_obj_t *self) { - if (self->result == NULL) { - return ""; - } - return self->result->hostname; + return self->hostname; } mp_int_t common_hal_mdns_remoteservice_get_port(mdns_remoteservice_obj_t *self) { - if (self->result == NULL) { - return 0; - } - return self->result->port; + return self->port; } uint32_t mdns_remoteservice_get_ipv4_address(mdns_remoteservice_obj_t *self) { - if (self->result == NULL || - self->result->ip_protocol != MDNS_IP_PROTOCOL_V4 || - self->result->addr == NULL) { - return 0; - } - mdns_ip_addr_t *cur = self->result->addr; - while (cur != NULL) { - if (cur->addr.type == ESP_IPADDR_TYPE_V4) { - return cur->addr.u_addr.ip4.addr; - } - - cur = cur->next; - } - - return 0; + return self->ipv4_address; } mp_obj_t common_hal_mdns_remoteservice_get_ipv4_address(mdns_remoteservice_obj_t *self) { @@ -68,8 +39,3 @@ mp_obj_t common_hal_mdns_remoteservice_get_ipv4_address(mdns_remoteservice_obj_t } return common_hal_ipaddress_new_ipv4address(addr); } - -void common_hal_mdns_remoteservice_deinit(mdns_remoteservice_obj_t *self) { - mdns_query_results_free(self->result); - self->result = NULL; -} diff --git a/ports/espressif/common-hal/mdns/RemoteService.h b/ports/espressif/common-hal/mdns/RemoteService.h index 6fb3000c7d1..89ff69be29d 100644 --- a/ports/espressif/common-hal/mdns/RemoteService.h +++ b/ports/espressif/common-hal/mdns/RemoteService.h @@ -8,7 +8,15 @@ #include "mdns.h" +// The IDF's mdns_result_t lives on the IDF heap and is only valid while mdns +// is inited. Copy what we need into the object instead so that the object's +// lifetime is independent of the mdns.Server's. typedef struct { mp_obj_base_t base; - mdns_result_t *result; + uint32_t ipv4_address; + uint16_t port; + char protocol[5]; // RFC 6763 Section 7.2 - 4 bytes + 1 for NUL + char service_name[17]; // RFC 6763 Section 7.2 - 16 bytes + 1 for NUL + char instance_name[64]; // RFC 6763 Section 7.2 - 63 bytes + 1 for NUL + char hostname[64]; // RFC 6762 Appendix A - 63 bytes for label + 1 for NUL } mdns_remoteservice_obj_t; diff --git a/ports/espressif/common-hal/mdns/Server.c b/ports/espressif/common-hal/mdns/Server.c index e8c34ee0885..7eaa9a442a2 100644 --- a/ports/espressif/common-hal/mdns/Server.c +++ b/ports/espressif/common-hal/mdns/Server.c @@ -6,6 +6,8 @@ #include "shared-bindings/mdns/Server.h" +#include + #include "py/gc.h" #include "py/runtime.h" #include "shared-bindings/mdns/RemoteService.h" @@ -18,6 +20,13 @@ // could be created.) static mdns_server_obj_t *_active_object = NULL; +// strlcpy(), but a NULL src yields an empty string instead of undefined +// behavior. The IDF leaves mdns_result_t fields NULL when a query didn't +// resolve them. +static void strlcpy_or_empty(char *dest, const char *src, size_t dest_len) { + strlcpy(dest, src == NULL ? "" : src, dest_len); +} + void mdns_server_construct(mdns_server_obj_t *self, bool workflow) { if (_active_object != NULL) { if (self == _active_object) { @@ -33,9 +42,12 @@ void mdns_server_construct(mdns_server_obj_t *self, bool workflow) { } _active_object = self; + self->instance_name[0] = '\0'; + // Match the netif hostname set when `import wifi` was called. - esp_netif_get_hostname(common_hal_wifi_radio_obj.netif, &self->hostname); - common_hal_mdns_server_set_hostname(self, self->hostname); + const char *netif_hostname; + esp_netif_get_hostname(common_hal_wifi_radio_obj.netif, &netif_hostname); + common_hal_mdns_server_set_hostname(self, netif_hostname); self->inited = true; @@ -95,11 +107,11 @@ void common_hal_mdns_server_set_hostname(mdns_server_obj_t *self, const char *ho while (!mdns_hostname_exists(hostname)) { RUN_BACKGROUND_TASKS; } - self->hostname = hostname; + strlcpy_or_empty(self->hostname, hostname, sizeof(self->hostname)); } const char *common_hal_mdns_server_get_instance_name(mdns_server_obj_t *self) { - if (self->instance_name == NULL) { + if (self->instance_name[0] == '\0') { return self->hostname; } return self->instance_name; @@ -107,7 +119,28 @@ const char *common_hal_mdns_server_get_instance_name(mdns_server_obj_t *self) { void common_hal_mdns_server_set_instance_name(mdns_server_obj_t *self, const char *instance_name) { mdns_instance_name_set(instance_name); - self->instance_name = instance_name; + strlcpy_or_empty(self->instance_name, instance_name, sizeof(self->instance_name)); +} + +// Copy everything we expose out of the IDF's result so that the RemoteService +// no longer references IDF-owned memory. The caller is responsible for freeing +// the result itself. +static void copy_data_into_remote_service(mdns_result_t *result, mdns_remoteservice_obj_t *out) { + out->base.type = &mdns_remoteservice_type; + out->port = result->port; + out->ipv4_address = 0; + if (result->ip_protocol == MDNS_IP_PROTOCOL_V4) { + for (mdns_ip_addr_t *cur = result->addr; cur != NULL; cur = cur->next) { + if (cur->addr.type == ESP_IPADDR_TYPE_V4) { + out->ipv4_address = cur->addr.u_addr.ip4.addr; + break; + } + } + } + strlcpy_or_empty(out->protocol, result->proto, sizeof(out->protocol)); + strlcpy_or_empty(out->service_name, result->service_type, sizeof(out->service_name)); + strlcpy_or_empty(out->instance_name, result->instance_name, sizeof(out->instance_name)); + strlcpy_or_empty(out->hostname, result->hostname, sizeof(out->hostname)); } size_t mdns_server_find(mdns_server_obj_t *self, const char *service_type, const char *protocol, @@ -123,23 +156,15 @@ size_t mdns_server_find(mdns_server_obj_t *self, const char *service_type, const } mdns_query_async_delete(search); mdns_result_t *next = results; - // Don't error if we're out of memory. Instead, truncate the tuple. - uint8_t added = 0; + // Truncate if we don't have space for everything the IDF found. + size_t added = 0; while (next != NULL && added < out_len) { - mdns_remoteservice_obj_t *service = &out[added]; - - service->result = next; - service->base.type = &mdns_remoteservice_type; + copy_data_into_remote_service(next, &out[added]); next = next->next; - // Break the linked list so we free each result separately. - service->result->next = NULL; added++; } - if (added < out_len) { - // Free the remaining results from the IDF because we don't have - // enough space in Python. - mdns_query_results_free(next); - } + // We've copied out everything we need, so release the IDF's copy. + mdns_query_results_free(results); return num_results; } @@ -158,36 +183,40 @@ mp_obj_t common_hal_mdns_server_find(mdns_server_obj_t *self, const char *servic // The empty tuple object is shared and stored in flash so return early if // we got it. Without this we'll crash when trying to set len below. if (num_results == 0) { + mdns_query_results_free(results); return MP_OBJ_FROM_PTR(tuple); } mdns_result_t *next = results; // Don't error if we're out of memory. Instead, truncate the tuple. uint8_t added = 0; while (next != NULL) { - mdns_remoteservice_obj_t *service = gc_alloc(sizeof(mdns_remoteservice_obj_t), GC_ALLOC_FLAG_HAS_FINALISER); + mdns_remoteservice_obj_t *service = m_malloc_maybe(sizeof(mdns_remoteservice_obj_t)); if (service == NULL) { if (added == 0) { + mdns_query_results_free(results); m_malloc_fail(sizeof(mdns_remoteservice_obj_t)); } - // Free the remaining results from the IDF because we don't have - // enough space in Python. - mdns_query_results_free(next); break; } - service->result = next; - service->base.type = &mdns_remoteservice_type; + copy_data_into_remote_service(next, service); next = next->next; - // Break the linked list so we free each result separately. - service->result->next = NULL; tuple->items[added] = MP_OBJ_FROM_PTR(service); added++; } tuple->len = added; + // We've copied out everything we need, so release the IDF's copy. + mdns_query_results_free(results); + return MP_OBJ_FROM_PTR(tuple); } void common_hal_mdns_server_advertise_service(mdns_server_obj_t *self, const char *service_type, const char *protocol, mp_int_t port, const char *txt_records[], size_t num_txt_records) { + // Reject rather than silently drop them. See the TODO below. + if (num_txt_records > 0) { + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_txt_records); + } + if (mdns_service_exists(service_type, protocol, NULL)) { mdns_service_port_set(service_type, protocol, port); } else { diff --git a/ports/espressif/common-hal/mdns/Server.h b/ports/espressif/common-hal/mdns/Server.h index f364a539c91..e7bfabb9528 100644 --- a/ports/espressif/common-hal/mdns/Server.h +++ b/ports/espressif/common-hal/mdns/Server.h @@ -10,8 +10,11 @@ typedef struct { mp_obj_base_t base; - const char *hostname; - const char *instance_name; + // Store copies rather than the caller's pointers. The setters are handed + // GC-heap strings, which are recycled when the VM resets while this object + // (and the web workflow's static one) lives on. + char hostname[64]; // RFC 6762 Appendix A - 63 bytes for label + 1 for NUL + char instance_name[64]; // RFC 6763 Section 7.2 - 63 bytes + 1 for NUL // Track if this object owns access to the underlying MDNS service. bool inited; } mdns_server_obj_t; diff --git a/ports/espressif/common-hal/microcontroller/Pin.c b/ports/espressif/common-hal/microcontroller/Pin.c index 70912afb545..ef9772468d9 100644 --- a/ports/espressif/common-hal/microcontroller/Pin.c +++ b/ports/espressif/common-hal/microcontroller/Pin.c @@ -7,14 +7,13 @@ #include "shared-bindings/microcontroller/Pin.h" #include "shared-bindings/digitalio/DigitalInOut.h" +#include "shared-bindings/alarm/__init__.h" #include "py/mphal.h" #include "driver/gpio.h" #include "soc/gpio_periph.h" -static uint64_t _never_reset_pin_mask; -static uint64_t _skip_reset_once_pin_mask; static uint64_t _preserved_pin_mask; static uint64_t _in_use_pin_mask; @@ -77,6 +76,23 @@ static uint64_t _in_use_pin_mask; #define GPIO_SEL_47 ((uint64_t)PIN_BIT(47)) /*!< Pin 47 selected */ #define GPIO_SEL_48 ((uint64_t)PIN_BIT(48)) /*!< Pin 48 selected */ #endif +#if SOC_GPIO_PIN_COUNT > 49 +#define GPIO_SEL_49 ((uint64_t)PIN_BIT(49)) /*!< Pin 49 selected */ +#define GPIO_SEL_50 ((uint64_t)PIN_BIT(50)) /*!< Pin 50 selected */ +#define GPIO_SEL_51 ((uint64_t)PIN_BIT(51)) /*!< Pin 51 selected */ +#define GPIO_SEL_52 ((uint64_t)PIN_BIT(52)) /*!< Pin 52 selected */ +#define GPIO_SEL_53 ((uint64_t)PIN_BIT(53)) /*!< Pin 53 selected */ +#define GPIO_SEL_54 ((uint64_t)PIN_BIT(54)) /*!< Pin 54 selected */ +#define GPIO_SEL_55 ((uint64_t)PIN_BIT(55)) /*!< Pin 55 selected */ +#endif +#if SOC_GPIO_PIN_COUNT > 56 +#define GPIO_SEL_56 ((uint64_t)PIN_BIT(56)) /*!< Pin 56 selected */ +#define GPIO_SEL_57 ((uint64_t)PIN_BIT(57)) /*!< Pin 57 selected */ +#define GPIO_SEL_58 ((uint64_t)PIN_BIT(58)) /*!< Pin 58 selected */ +#define GPIO_SEL_59 ((uint64_t)PIN_BIT(59)) /*!< Pin 59 selected */ +#define GPIO_SEL_60 ((uint64_t)PIN_BIT(60)) /*!< Pin 60 selected */ +#define GPIO_SEL_61 ((uint64_t)PIN_BIT(61)) /*!< Pin 61 selected */ +#endif // Bit mask of all pins that should never EVER be reset. // Typically these are SPI flash and PSRAM control pins, and communication pins. @@ -126,6 +142,32 @@ static const uint64_t pin_mask_reset_forbidden = #endif #endif // ESP32C3 + #if defined(CONFIG_IDF_TARGET_ESP32C5) + // Never ever reset pins used to communicate with SPI flash. + // ports/espressif/esp-idf/components/esp_hal_gpspi/esp32c5/include/soc/spi_pins.h + GPIO_SEL_16 | // MSPI_IOMUX_PIN_NUM_CS0 (flash) + GPIO_SEL_17 | // MSPI_IOMUX_PIN_NUM_MISO + GPIO_SEL_18 | // MSPI_IOMUX_PIN_NUM_WP + GPIO_SEL_19 | // VDD_SPI (powers the in-module flash) + GPIO_SEL_20 | // MSPI_IOMUX_PIN_NUM_HD + GPIO_SEL_21 | // MSPI_IOMUX_PIN_NUM_CLK + GPIO_SEL_22 | // MSPI_IOMUX_PIN_NUM_MOSI + #if CIRCUITPY_ESP_USB_SERIAL_JTAG + // Never ever reset serial/JTAG communication pins. On C5, gpio_ll_func_sel() + // on either clears USB_SERIAL_JTAG.conf0.usb_pad_enable, killing the USB pads. + GPIO_SEL_13 | // USB D- (USB_INT_PHY0_DM_GPIO_NUM) + GPIO_SEL_14 | // USB D+ (USB_INT_PHY0_DP_GPIO_NUM) + #endif + #if defined(CONFIG_SPIRAM) + GPIO_SEL_15 | // MSPI_IOMUX_PIN_NUM_CS1 (PSRAM); keep if PSRAM in use + #endif + #if defined(CONFIG_ESP_CONSOLE_UART_DEFAULT) && CONFIG_ESP_CONSOLE_UART_DEFAULT && CONFIG_ESP_CONSOLE_UART_NUM == 0 + // Never reset debug UART/console pins. + GPIO_SEL_11 | + GPIO_SEL_12 | + #endif + #endif // ESP32C5 + #if defined(CONFIG_IDF_TARGET_ESP32C6) // Never ever reset pins used to communicate with SPI flash. GPIO_SEL_24 | // SPICS0 @@ -146,6 +188,29 @@ static const uint64_t pin_mask_reset_forbidden = #endif #endif // ESP32C6 + #if defined(CONFIG_IDF_TARGET_ESP32C61) + // Never ever reset pins used to communicate with SPI flash. + GPIO_SEL_15 | // SPICS0 (flash CS#) + GPIO_SEL_16 | // SPIQ (MISO/SIO1) + GPIO_SEL_17 | // SPIWP (WP#/SIO2) + GPIO_SEL_19 | // SPIHD (HOLD#/SIO3) + GPIO_SEL_20 | // SPICLK (CLK) + GPIO_SEL_21 | // SPID (MOSI/SIO0) + #if CIRCUITPY_ESP_USB_SERIAL_JTAG + // Never ever reset serial/JTAG communication pins. + GPIO_SEL_12 | // USB D- + GPIO_SEL_13 | // USB D+ + #endif + #if defined(CONFIG_SPIRAM) + GPIO_SEL_14 | // SPICS1 (PSRAM CS#); keep if PSRAM in use + #endif + #if defined(CONFIG_ESP_CONSOLE_UART_DEFAULT) && CONFIG_ESP_CONSOLE_UART_DEFAULT && CONFIG_ESP_CONSOLE_UART_NUM == 0 + // Never reset debug UART/console pins. + GPIO_SEL_10 | + GPIO_SEL_11 | + #endif + #endif // ESP32C6 + #if defined(CONFIG_IDF_TARGET_ESP32H2) // Never ever reset pins used to communicate with the in-package SPI flash. GPIO_SEL_15 | @@ -172,17 +237,27 @@ static const uint64_t pin_mask_reset_forbidden = #endif // ESP32H2 #if defined(CONFIG_IDF_TARGET_ESP32P4) - // Never ever reset pins used to communicate with the SPI flash. - GPIO_SEL_28 | - GPIO_SEL_29 | - GPIO_SEL_30 | - GPIO_SEL_32 | - GPIO_SEL_33 | - GPIO_SEL_34 | - #if CIRCUITPY_ESP_USB_SERIAL_JTAG + // SPI flash is on dedicated pins. + + // USB is on the FS OTG, whose PHY is on 26 and 27 by default and on 24 and 25 when swapped. + #if CIRCUITPY_USB_DEVICE_INSTANCE == 0 + #if CIRCUITPY_ESP32P4_SWAP_LSFS == 1 + GPIO_SEL_24 | // USB D- + GPIO_SEL_25 | // USB D+ + #else + GPIO_SEL_26 | // USB D- + GPIO_SEL_27 | // USB D+ + #endif + #endif + #if CIRCUITPY_ESP_USB_SERIAL_JTAG || (defined(CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG) && CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG) // Never ever reset serial/JTAG communication pins. - GPIO_SEL_50 | // USB D- - GPIO_SEL_51 | // USB D+ + #if CIRCUITPY_ESP32P4_SWAP_LSFS == 1 + GPIO_SEL_26 | // USB D- + GPIO_SEL_27 | // USB D+ + #else + GPIO_SEL_24 | // USB D- + GPIO_SEL_25 | // USB D+ + #endif #endif #if defined(CONFIG_ESP_CONSOLE_UART_DEFAULT) && CONFIG_ESP_CONSOLE_UART_DEFAULT && CONFIG_ESP_CONSOLE_UART_NUM == 0 // Never reset debug UART/console pins. @@ -191,6 +266,27 @@ static const uint64_t pin_mask_reset_forbidden = #endif #endif // ESP32P4 + #if defined(CONFIG_IDF_TARGET_ESP32S31) + // Never ever reset pins used to communicate with SPI flash. + // esp-idf/components/soc/esp32s31/register/soc/iomux_mspi_pin_reg.h + GPIO_SEL_26 | // MSPI_IOMUX_PIN_NUM_CS0 + GPIO_SEL_27 | // MSPI_IOMUX_PIN_NUM_MISO + GPIO_SEL_28 | // MSPI_IOMUX_PIN_NUM_WP + GPIO_SEL_30 | // MSPI_IOMUX_PIN_NUM_HD + GPIO_SEL_31 | // MSPI_IOMUX_PIN_NUM_CLK + GPIO_SEL_32 | // MSPI_IOMUX_PIN_NUM_MOSI + #if CIRCUITPY_ESP_USB_SERIAL_JTAG || (defined(CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG) && CONFIG_ESP_CONSOLE_USB_SERIAL_JTAG) + // Never ever reset serial/JTAG communication pins. + GPIO_SEL_33 | // USB D- + GPIO_SEL_34 | // USB D+ + #endif + #if defined(CONFIG_ESP_CONSOLE_UART_DEFAULT) && CONFIG_ESP_CONSOLE_UART_DEFAULT && CONFIG_ESP_CONSOLE_UART_NUM == 0 + // Never reset debug UART/console pins. + GPIO_SEL_58 | + GPIO_SEL_59 | + #endif + #endif // ESP32S31 + #if defined(CONFIG_IDF_TARGET_ESP32S2) || defined(CONFIG_IDF_TARGET_ESP32S3) #if CIRCUITPY_USB_DEVICE // Never ever reset USB pins. @@ -228,31 +324,6 @@ static const uint64_t pin_mask_reset_forbidden = -void never_reset_pin_number(gpio_num_t pin_number) { - // Some CircuitPython APIs deal in uint8_t pin numbers, but NO_PIN is -1. - // Also allow pin 255 to be treated as NO_PIN to avoid crashes - if (pin_number == NO_PIN || pin_number == (uint8_t)NO_PIN) { - return; - } - _never_reset_pin_mask |= PIN_BIT(pin_number); -} - -void skip_reset_once_pin_number(gpio_num_t pin_number) { - // Some CircuitPython APIs deal in uint8_t pin numbers, but NO_PIN is -1. - // Also allow pin 255 to be treated as NO_PIN to avoid crashes - if (pin_number == NO_PIN || pin_number == (uint8_t)NO_PIN) { - return; - } - _skip_reset_once_pin_mask |= PIN_BIT(pin_number); -} - -void common_hal_never_reset_pin(const mcu_pin_obj_t *pin) { - if (pin == NULL) { - return; - } - never_reset_pin_number(pin->number); -} - MP_WEAK bool espressif_board_reset_pin_number(gpio_num_t pin_number) { return false; } @@ -261,18 +332,6 @@ static bool _reset_forbidden(gpio_num_t pin_number) { return pin_mask_reset_forbidden & PIN_BIT(pin_number); } -static bool _never_reset(gpio_num_t pin_number) { - return _never_reset_pin_mask & PIN_BIT(pin_number); -} - -static bool _skip_reset_once(gpio_num_t pin_number) { - return _skip_reset_once_pin_mask & PIN_BIT(pin_number); -} - -static bool _preserved_pin(gpio_num_t pin_number) { - return _preserved_pin_mask & PIN_BIT(pin_number); -} - static void _reset_pin(gpio_num_t pin_number) { // Never ever reset pins used for flash, RAM, and basic communication. if (_reset_forbidden(pin_number)) { @@ -326,7 +385,15 @@ void preserve_pin_number(gpio_num_t pin_number) { } } -void clear_pin_preservations(void) { +void common_hal_alarm_clear_pin_preservations(void) { + // Release any actual holds, not just the tracking mask. Without this the + // pins would stay held after a fake deep sleep ends. + uint64_t mask = _preserved_pin_mask; + for (int i = 0; i < 64; i++, mask >>= 1) { + if ((mask & 1) && GPIO_IS_VALID_OUTPUT_GPIO(i)) { + gpio_hold_dis(i); + } + } _preserved_pin_mask = 0; } @@ -338,7 +405,6 @@ void reset_pin_number(gpio_num_t pin_number) { if (pin_number == NO_PIN || pin_number == (uint8_t)NO_PIN) { return; } - _never_reset_pin_mask &= ~PIN_BIT(pin_number); _in_use_pin_mask &= ~PIN_BIT(pin_number); _reset_pin(pin_number); @@ -363,26 +429,16 @@ void common_hal_reset_pin(const mcu_pin_obj_t *pin) { reset_pin_number(pin->number); } -void reset_all_pins(void) { - // Undo deep sleep holds in case we woke up from deep sleep. - // We still need to unhold individual pins, which is done by _reset_pin. +void disable_deep_sleep_pin_hold(void) { + // preserve_pin_number() turns on the chip-wide deep sleep hold on chips that + // can't hold single pins in deep sleep. It stays on until turned off here. #if defined(SOC_GPIO_SUPPORT_HOLD_SINGLE_IO_IN_DSLP) && !SOC_GPIO_SUPPORT_HOLD_SINGLE_IO_IN_DSLP gpio_deep_sleep_hold_dis(); #endif +} - for (uint8_t i = 0; i < GPIO_PIN_COUNT; i++) { - uint32_t iomux_address = GPIO_PIN_MUX_REG[i]; - if (iomux_address == 0 || - _never_reset(i) || - _skip_reset_once(i) || - _preserved_pin(i)) { - continue; - } - _reset_pin(i); - } - _in_use_pin_mask = _never_reset_pin_mask | pin_mask_reset_forbidden; - // Don't continue to skip resetting these pins. - _skip_reset_once_pin_mask = 0; +void claim_reset_forbidden_pins(void) { + _in_use_pin_mask |= pin_mask_reset_forbidden; } void claim_pin_number(gpio_num_t pin_number) { @@ -403,7 +459,7 @@ void common_hal_mcu_pin_claim(const mcu_pin_obj_t *pin) { } bool pin_number_is_free(gpio_num_t pin_number) { - return !(_in_use_pin_mask & PIN_BIT(pin_number)); + return GPIO_IS_VALID_GPIO(pin_number) && !(_in_use_pin_mask & PIN_BIT(pin_number)); } bool common_hal_mcu_pin_is_free(const mcu_pin_obj_t *pin) { diff --git a/ports/espressif/common-hal/microcontroller/Pin.h b/ports/espressif/common-hal/microcontroller/Pin.h index aba7fa68323..2de7be56822 100644 --- a/ports/espressif/common-hal/microcontroller/Pin.h +++ b/ports/espressif/common-hal/microcontroller/Pin.h @@ -14,22 +14,25 @@ #define PIN_BIT(pin_number) (((uint64_t)1) << pin_number) extern void common_hal_reset_pin(const mcu_pin_obj_t *pin); -extern void common_hal_never_reset_pin(const mcu_pin_obj_t *pin); -extern 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. extern void reset_pin_number(gpio_num_t pin_number); // reset all pins in `bitmask` extern void reset_pin_mask(uint64_t bitmask); -extern void skip_reset_once_pin_number(gpio_num_t pin_number); +// Turn off the chip-wide deep sleep pin hold, on chips that use one. Does not +// release individual pin holds. Does not raise. +extern void disable_deep_sleep_pin_hold(void); +// Mark the pins used for flash, PSRAM, USB, and the console as in use, so +// user code can't claim them. Called once from port_init(), before anything +// else claims pins. Does not raise. +extern void claim_reset_forbidden_pins(void); extern void claim_pin(const mcu_pin_obj_t *pin); extern void claim_pin_number(gpio_num_t pin_number); extern bool pin_number_is_free(gpio_num_t pin_number); -extern void never_reset_pin_number(gpio_num_t pin_number); + +extern uint8_t common_hal_mcu_pin_number(const mcu_pin_obj_t *pin); +extern void common_hal_mcu_pin_claim(const mcu_pin_obj_t *pin); extern void preserve_pin_number(gpio_num_t pin_number); -extern void clear_pin_preservations(void); // Allow the board to reset a pin in a board-specific way. This can be used // for LEDs or enable pins to put them in a state beside the default pull-up. diff --git a/ports/espressif/common-hal/microcontroller/Processor.c b/ports/espressif/common-hal/microcontroller/Processor.c index 8a6a14c0236..9f95432e3a8 100644 --- a/ports/espressif/common-hal/microcontroller/Processor.c +++ b/ports/espressif/common-hal/microcontroller/Processor.c @@ -15,12 +15,11 @@ #include "shared-bindings/microcontroller/Processor.h" #include "shared-bindings/microcontroller/ResetReason.h" +#include "esp_mac.h" #include "esp_sleep.h" #include "esp_system.h" #include "esp_pm.h" -#include "soc/efuse_reg.h" - #if !defined(CONFIG_IDF_TARGET_ESP32) #include "driver/temperature_sensor.h" #endif @@ -59,12 +58,18 @@ uint32_t common_hal_mcu_processor_get_frequency(void) { // If the requested frequency is not supported by the hardware, return the next lower supported frequency static uint32_t get_valid_cpu_frequency(uint32_t requested_freq_mhz) { - #if defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32C6) + #if defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32C6) || defined(CONFIG_IDF_TARGET_ESP32C61) uint32_t valid_cpu_frequencies[] = {20, 40, 80, 160}; #elif defined(CONFIG_IDF_TARGET_ESP32C2) uint32_t valid_cpu_frequencies[] = {20, 40, 80, 120}; #elif defined(CONFIG_IDF_TARGET_ESP32H2) uint32_t valid_cpu_frequencies[] = {32, 48, 64, 96}; + #elif defined(CONFIG_IDF_TARGET_ESP32C5) + // C5's 48 MHz crystal does not divide evenly to 20 or 24 MHz, both of + // which esp_pm_configure() rejects. + uint32_t valid_cpu_frequencies[] = {40, 80, 160, 240}; + #elif defined(CONFIG_IDF_TARGET_ESP32S31) + uint32_t valid_cpu_frequencies[] = {20, 40, 80, 160, 240, 320}; #else uint32_t valid_cpu_frequencies[] = {20, 40, 80, 160, 240}; #endif @@ -107,95 +112,52 @@ void common_hal_mcu_processor_set_frequency(mcu_processor_obj_t *self, uint32_t } #endif -#ifndef CONFIG_IDF_TARGET_ESP32P4 -static uint8_t swap_nibbles(uint8_t v) { - return ((v << 4) | (v >> 4)) & 0xff; -} -#endif - void common_hal_mcu_processor_get_uid(uint8_t raw_id[]) { - #ifndef CONFIG_IDF_TARGET_ESP32P4 - memset(raw_id, 0, COMMON_HAL_MCU_PROCESSOR_UID_LENGTH); - - 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 - - #if defined(CONFIG_IDF_TARGET_ESP32) - uint32_t mac_address_part = REG_READ(EFUSE_BLK0_RDATA1_REG); - #elif defined(CONFIG_IDF_TARGET_ESP32H2) - uint32_t mac_address_part = REG_READ(EFUSE_RD_MAC_SYS_0_REG); - #elif defined(CONFIG_IDF_TARGET_ESP32C2) - uint32_t mac_address_part = REG_READ(EFUSE_RD_BLK2_DATA0_REG); - #else - uint32_t mac_address_part = REG_READ(EFUSE_RD_MAC_SPI_SYS_0_REG); - #endif - - *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 - #if defined(CONFIG_IDF_TARGET_ESP32) - mac_address_part = REG_READ(EFUSE_BLK0_RDATA2_REG); - #elif defined(CONFIG_IDF_TARGET_ESP32H2) - mac_address_part = REG_READ(EFUSE_RD_MAC_SYS_1_REG); - #elif defined(CONFIG_IDF_TARGET_ESP32C2) - mac_address_part = REG_READ(EFUSE_RD_BLK2_DATA1_REG); - #else - mac_address_part = REG_READ(EFUSE_RD_MAC_SPI_SYS_1_REG); - #endif - - *ptr-- = swap_nibbles(mac_address_part & 0xff); - mac_address_part >>= 8; - *ptr-- = swap_nibbles(mac_address_part & 0xff); - #else - // TODO: Get UID for ESP32-P4. - return; - #endif + // The factory MAC is six bytes even on IEEE 802.15.4 chips. + // USB descriptor setup also calls this outside the VM, so do not raise. + if (esp_read_mac(raw_id, ESP_MAC_EFUSE_FACTORY) != ESP_OK) { + memset(raw_id, 0, COMMON_HAL_MCU_PROCESSOR_UID_LENGTH); + } } mcu_reset_reason_t common_hal_mcu_processor_get_reset_reason(void) { switch (esp_reset_reason()) { case ESP_RST_POWERON: - return RESET_REASON_POWER_ON; + return MCU_RESET_REASON_POWER_ON; case ESP_RST_SW: case ESP_RST_PANIC: - return RESET_REASON_SOFTWARE; + return MCU_RESET_REASON_SOFTWARE; case ESP_RST_INT_WDT: case ESP_RST_TASK_WDT: case ESP_RST_WDT: - return RESET_REASON_WATCHDOG; + return MCU_RESET_REASON_WATCHDOG; case ESP_RST_BROWNOUT: - return RESET_REASON_BROWNOUT; + return MCU_RESET_REASON_BROWNOUT; case ESP_RST_SDIO: case ESP_RST_EXT: - return RESET_REASON_RESET_PIN; - - case ESP_RST_DEEPSLEEP: - switch (esp_sleep_get_wakeup_cause()) { - case ESP_SLEEP_WAKEUP_TIMER: - case ESP_SLEEP_WAKEUP_EXT0: - case ESP_SLEEP_WAKEUP_EXT1: - case ESP_SLEEP_WAKEUP_TOUCHPAD: - case ESP_SLEEP_WAKEUP_ULP: - return RESET_REASON_DEEP_SLEEP_ALARM; - - case ESP_SLEEP_WAKEUP_UNDEFINED: - default: - return RESET_REASON_UNKNOWN; + return MCU_RESET_REASON_RESET_PIN; + + case ESP_RST_DEEPSLEEP: { + uint32_t wakeup_causes = esp_sleep_get_wakeup_causes(); + uint32_t alarm_causes = + BIT(ESP_SLEEP_WAKEUP_TIMER) | + BIT(ESP_SLEEP_WAKEUP_EXT0) | + BIT(ESP_SLEEP_WAKEUP_EXT1) | + BIT(ESP_SLEEP_WAKEUP_TOUCHPAD) | + BIT(ESP_SLEEP_WAKEUP_ULP); + if (wakeup_causes & alarm_causes) { + return MCU_RESET_REASON_DEEP_SLEEP_ALARM; } + return MCU_RESET_REASON_UNKNOWN; + } case ESP_RST_UNKNOWN: default: - return RESET_REASON_UNKNOWN; + return MCU_RESET_REASON_UNKNOWN; } } diff --git a/ports/espressif/common-hal/microcontroller/__init__.c b/ports/espressif/common-hal/microcontroller/__init__.c index 918366b8933..1a236c9e6f5 100644 --- a/ports/espressif/common-hal/microcontroller/__init__.c +++ b/ports/espressif/common-hal/microcontroller/__init__.c @@ -33,11 +33,19 @@ #elif defined(CONFIG_IDF_TARGET_ESP32C3) #include "soc/rtc_cntl_reg.h" #include "esp32c3/rom/rtc.h" +#elif defined(CONFIG_IDF_TARGET_ESP32C5) +#include "soc/lp_aon_reg.h" +#include "esp32c5/rom/rtc.h" #elif defined(CONFIG_IDF_TARGET_ESP32C6) #include "soc/lp_aon_reg.h" #include "esp32c6/rom/rtc.h" +#elif defined(CONFIG_IDF_TARGET_ESP32C61) +#include "soc/lp_aon_reg.h" +#include "esp32c61/rom/rtc.h" #elif defined(CONFIG_IDF_TARGET_ESP32P4) #include "esp32p4/rom/rtc.h" +#elif defined(CONFIG_IDF_TARGET_ESP32S31) +#include "esp32s31/rom/rtc.h" #elif defined(CONFIG_IDF_TARGET_ESP32S2) #include "soc/rtc_cntl_reg.h" #include "esp32s2/rom/rtc.h" @@ -83,7 +91,7 @@ void common_hal_mcu_enable_interrupts(void) { void common_hal_mcu_on_next_reset(mcu_runmode_t runmode) { switch (runmode) { case RUNMODE_UF2: - #if defined(CONFIG_IDF_TARGET_ESP32) || defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32C6) + #if defined(CONFIG_IDF_TARGET_ESP32) || defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32C5) || defined(CONFIG_IDF_TARGET_ESP32C6) || defined(CONFIG_IDF_TARGET_ESP32C61) mp_arg_error_invalid(MP_QSTR_run_mode); #else // 0x11F2 is APP_REQUEST_UF2_RESET_HINT & is defined by TinyUF2 @@ -95,7 +103,7 @@ void common_hal_mcu_on_next_reset(mcu_runmode_t runmode) { #if defined(CONFIG_IDF_TARGET_ESP32S2) || defined(CONFIG_IDF_TARGET_ESP32S3) REG_WRITE(RTC_RESET_CAUSE_REG, 0); // reset uf2 #endif - #if defined(CONFIG_IDF_TARGET_ESP32P4) + #if defined(CONFIG_IDF_TARGET_ESP32P4) || defined(CONFIG_IDF_TARGET_ESP32S31) REG_WRITE(LP_SYSTEM_REG_LP_STORE15_REG, 0); #elif defined(SOC_LP_AON_SUPPORTED) REG_WRITE(LP_AON_STORE0_REG, 0); // reset safe mode @@ -104,8 +112,8 @@ void common_hal_mcu_on_next_reset(mcu_runmode_t runmode) { #endif #if defined(CONFIG_IDF_TARGET_ESP32) // No UF2 bootloader. - #elif defined(CONFIG_IDF_TARGET_ESP32P4) - REG_WRITE(LP_SYSTEM_REG_SYS_CTRL_REG, 0); + #elif defined(CONFIG_IDF_TARGET_ESP32P4) || defined(CONFIG_IDF_TARGET_ESP32S31) + REG_CLR_BIT(LP_SYSTEM_REG_SYS_CTRL_REG, LP_SYSTEM_REG_FORCE_DOWNLOAD_BOOT); #elif defined(SOC_LP_AON_SUPPORTED) REG_WRITE(LP_AON_SYS_CFG_REG, 0); // reset bootloader #else @@ -125,8 +133,8 @@ void common_hal_mcu_on_next_reset(mcu_runmode_t runmode) { chip_usb_set_persist_flags(USBDC_BOOT_DFU); #endif - #if defined(CONFIG_IDF_TARGET_ESP32P4) - REG_WRITE(LP_SYSTEM_REG_SYS_CTRL_REG, LP_SYSTEM_REG_FORCE_DOWNLOAD_BOOT); + #if defined(CONFIG_IDF_TARGET_ESP32P4) || defined(CONFIG_IDF_TARGET_ESP32S31) + REG_SET_BIT(LP_SYSTEM_REG_SYS_CTRL_REG, LP_SYSTEM_REG_FORCE_DOWNLOAD_BOOT); #elif defined(SOC_LP_AON_SUPPORTED) REG_WRITE(LP_AON_SYS_CFG_REG, LP_AON_FORCE_DOWNLOAD_BOOT); #else @@ -139,7 +147,7 @@ void common_hal_mcu_on_next_reset(mcu_runmode_t runmode) { } } -void NORETURN common_hal_mcu_reset(void) { +void MP_NORETURN common_hal_mcu_reset(void) { filesystem_flush(); // TODO: implement as part of flash improvements esp_restart(); } @@ -341,5 +349,30 @@ static const mp_rom_map_elem_t mcu_pin_global_dict_table[] = { #ifdef GPIO54_EXISTS { MP_ROM_QSTR(MP_QSTR_GPIO54), MP_ROM_PTR(&pin_GPIO54) }, #endif + #ifdef GPIO55_EXISTS + { MP_ROM_QSTR(MP_QSTR_GPIO55), MP_ROM_PTR(&pin_GPIO55) }, + #endif + #ifdef GPIO56_EXISTS + { MP_ROM_QSTR(MP_QSTR_GPIO56), MP_ROM_PTR(&pin_GPIO56) }, + #endif + #ifdef GPIO57_EXISTS + { MP_ROM_QSTR(MP_QSTR_GPIO57), MP_ROM_PTR(&pin_GPIO57) }, + #endif + #ifdef GPIO58_EXISTS + { MP_ROM_QSTR(MP_QSTR_GPIO58), MP_ROM_PTR(&pin_GPIO58) }, + #endif + #ifdef GPIO59_EXISTS + { MP_ROM_QSTR(MP_QSTR_GPIO59), MP_ROM_PTR(&pin_GPIO59) }, + #endif + #ifdef GPIO60_EXISTS + { MP_ROM_QSTR(MP_QSTR_GPIO60), MP_ROM_PTR(&pin_GPIO60) }, + #endif + #ifdef GPIO61_EXISTS + { MP_ROM_QSTR(MP_QSTR_GPIO61), MP_ROM_PTR(&pin_GPIO61) }, + #endif + #if defined(CONFIG_IDF_TARGET_ESP32P4) || defined(CONFIG_IDF_TARGET_ESP32S31) + { MP_ROM_QSTR(MP_QSTR_USB_HS_DP), MP_ROM_PTR(&pin_USB_HS_DP) }, + { MP_ROM_QSTR(MP_QSTR_USB_HS_DM), MP_ROM_PTR(&pin_USB_HS_DM) }, + #endif }; MP_DEFINE_CONST_DICT(mcu_pin_globals, mcu_pin_global_dict_table); diff --git a/ports/espressif/common-hal/mii/Ethernet.c b/ports/espressif/common-hal/mii/Ethernet.c new file mode 100644 index 00000000000..349a3938e15 --- /dev/null +++ b/ports/espressif/common-hal/mii/Ethernet.c @@ -0,0 +1,427 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "common-hal/mii/Ethernet.h" +#include "common-hal/mii/__init__.h" +#include "shared-bindings/mii/Ethernet.h" +#include "shared-bindings/mii/__init__.h" + +#include +#include + +#include "bindings/espidf/__init__.h" + +#include "supervisor/port.h" +#include "supervisor/workflow.h" +#include "shared/runtime/interrupt_char.h" + +#if CIRCUITPY_STATUS_BAR +#include "supervisor/shared/status_bar.h" +#endif + +#include "esp_timer.h" + +#include "py/runtime.h" +#include "shared-bindings/ipaddress/IPv4Address.h" +#include "shared-module/ipaddress/__init__.h" + +#include "esp_eth.h" +#include "esp_eth_mac_esp.h" +#include "esp_eth_phy.h" +#include "esp_eth_phy_802_3.h" +#include "esp_eth_netif_glue.h" +#include "esp_event.h" +#include "esp_mac.h" +#include "esp_netif.h" + +#include "lwip/inet.h" +#include "lwip/sockets.h" + +#define MAC_ADDRESS_LENGTH 6 + +static void _ipv4address_to_esp_idf(mp_obj_t ip_address, esp_ip4_addr_t *esp_addr) { + 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); + esp_netif_set_ip4_addr(esp_addr, bytes[0], bytes[1], bytes[2], bytes[3]); +} + +static mp_obj_t _ip4_to_str(const esp_ip4_addr_t *addr) { + char buf[IPADDR_STRLEN_MAX]; + inet_ntop(AF_INET, addr, buf, sizeof(buf)); + return mp_obj_new_str(buf, strlen(buf)); +} + +static mp_obj_t _ipaddr_to_str(const esp_ip_addr_t *addr) { + char buf[IPADDR_STRLEN_MAX]; + inet_ntop(addr->type == ESP_IPADDR_TYPE_V6 ? AF_INET6 : AF_INET, addr, buf, sizeof(buf)); + return mp_obj_new_str(buf, strlen(buf)); +} + +static void _eth_event_handler(void *arg, esp_event_base_t event_base, + int32_t event_id, void *event_data) { + mii_ethernet_obj_t *self = (mii_ethernet_obj_t *)arg; + + if (event_base == ETH_EVENT) { + switch (event_id) { + case ETHERNET_EVENT_CONNECTED: + self->connected = true; + break; + case ETHERNET_EVENT_DISCONNECTED: + self->connected = false; + break; + default: + break; + } + } else if (event_base == IP_EVENT && event_id == IP_EVENT_ETH_GOT_IP) { + ip_event_got_ip_t *event = (ip_event_got_ip_t *)event_data; + self->ip_info = event->ip_info; + } + + #if CIRCUITPY_STATUS_BAR + supervisor_status_bar_request_update(false); + #endif + port_wake_main_task(); +} + +void common_hal_mii_ethernet_construct(mii_ethernet_obj_t *self, + mii_rmii_obj_t *rmii) { + self->base.type = &mii_ethernet_type; + self->started = false; + self->connected = false; + self->eth_handle = NULL; + self->netif = NULL; + self->glue = NULL; + if (rmii == NULL) { + return; + } + if (rmii->mac != NULL) { + // The EMAC instance behind this bus is already bound to an interface. + // Raise before creating a second MAC: a failed mac_new would disable + // the bus clock on error and wound the live interface. + mp_raise_RuntimeError(MP_ERROR_TEXT("Peripheral in use")); + } + + // Initialize TCP/IP stack and event loop (may already be done by wifi). + esp_netif_init(); + esp_event_loop_create_default(); + + eth_mac_config_t mac_config = ETH_MAC_DEFAULT_CONFIG(); + eth_esp32_emac_config_t esp32_emac_config = ETH_ESP32_EMAC_DEFAULT_CONFIG(); + esp32_emac_config.smi_gpio.mdc_num = rmii->mdio->mdc; + esp32_emac_config.smi_gpio.mdio_num = rmii->mdio->mdio; + #if (defined(SOC_EMAC_USE_MULTI_IO_MUX) && SOC_EMAC_USE_MULTI_IO_MUX) || (defined(SOC_EMAC_MII_USE_GPIO_MATRIX) && SOC_EMAC_MII_USE_GPIO_MATRIX) + esp32_emac_config.emac_dataif_gpio.rmii.crs_dv_num = rmii->rx_dv; + esp32_emac_config.emac_dataif_gpio.rmii.rxd0_num = rmii->rxd0; + esp32_emac_config.emac_dataif_gpio.rmii.rxd1_num = rmii->rxd1; + esp32_emac_config.emac_dataif_gpio.rmii.txd0_num = rmii->txd0; + esp32_emac_config.emac_dataif_gpio.rmii.txd1_num = rmii->txd1; + esp32_emac_config.emac_dataif_gpio.rmii.tx_en_num = rmii->tx_en; + esp32_emac_config.clock_config.rmii.clock_gpio = rmii->refclk; + #endif + + esp_eth_mac_t *mac = esp_eth_mac_new_esp32(&esp32_emac_config, &mac_config); + if (mac == NULL) { + // The EMAC instance is already bound to a live interface. + mp_raise_RuntimeError(MP_ERROR_TEXT("Peripheral in use")); + } + // Record the binding so later construct attempts on this bus refuse + // cleanly before they can wound the live interface. + rmii->mac = mac; + + eth_phy_config_t phy_config = ETH_PHY_DEFAULT_CONFIG(); + phy_config.phy_addr = rmii->device; + phy_config.reset_gpio_num = rmii->reset; + + esp_eth_phy_t *phy = esp_eth_phy_new_generic(&phy_config); + + // Probe the PHY's ID registers through the MAC's MDIO master so that a + // wrong device number fails here instead of silently never linking. + uint32_t id1 = 0, id2 = 0; + esp_err_t r1 = mac->read_phy_reg(mac, rmii->device, 2, &id1); + esp_err_t r2 = mac->read_phy_reg(mac, rmii->device, 3, &id2); + if (r1 != ESP_OK || r2 != ESP_OK || id1 == 0xffff || (id1 == 0 && id2 == 0)) { + mac->del(mac); + mp_raise_OSError_msg_varg(MP_ERROR_TEXT("%q failure: %d"), MP_QSTR_device, ENODEV); + } + + // Install the ethernet driver. + esp_eth_config_t config = ETH_DEFAULT_CONFIG(mac, phy); + CHECK_ESP_RESULT(esp_eth_driver_install(&config, &self->eth_handle)); + + // Seed the MAC from eFuse. esp_eth_mac_new_esp32 leaves it all-zero. + uint8_t mac_addr[MAC_ADDRESS_LENGTH]; + esp_efuse_mac_get_default(mac_addr); + esp_eth_ioctl(self->eth_handle, ETH_CMD_S_MAC_ADDR, mac_addr); + + // Create netif with default ethernet config + esp_netif_config_t netif_config = ESP_NETIF_DEFAULT_ETH(); + self->netif = esp_netif_new(&netif_config); + + // Create glue to attach ethernet driver to netif + self->glue = esp_eth_new_netif_glue(self->eth_handle); + CHECK_ESP_RESULT(esp_netif_attach(self->netif, self->glue)); + + // Register event handlers + CHECK_ESP_RESULT(esp_event_handler_register(ETH_EVENT, ESP_EVENT_ANY_ID, _eth_event_handler, self)); + CHECK_ESP_RESULT(esp_event_handler_register(IP_EVENT, IP_EVENT_ETH_GOT_IP, _eth_event_handler, self)); + + // Set hostname + char hostname[32]; + mii_get_default_hostname(hostname, sizeof(hostname)); + esp_netif_set_hostname(self->netif, hostname); + + // Start the ethernet driver (DHCP starts automatically with default netif config) + CHECK_ESP_RESULT(esp_eth_start(self->eth_handle)); + self->started = true; +} + +bool common_hal_mii_ethernet_get_enabled(mii_ethernet_obj_t *self) { + return self->started; +} + +void common_hal_mii_ethernet_set_enabled(mii_ethernet_obj_t *self, bool enabled) { + if (self->eth_handle == NULL) { + return; + } + if (self->started && !enabled) { + esp_netif_dhcpc_stop(self->netif); + esp_eth_stop(self->eth_handle); + self->started = false; + } else if (!self->started && enabled) { + CHECK_ESP_RESULT(esp_eth_start(self->eth_handle)); + self->started = true; + esp_netif_dhcpc_start(self->netif); + } +} + +bool common_hal_mii_ethernet_get_connected(mii_ethernet_obj_t *self) { + return self->started && self->connected; +} + +mp_obj_t common_hal_mii_ethernet_get_hostname(mii_ethernet_obj_t *self) { + if (self->netif == NULL) { + return mp_obj_new_str("", 0); + } + const char *hostname = NULL; + esp_netif_get_hostname(self->netif, &hostname); + if (hostname == NULL) { + return mp_obj_new_str("", 0); + } + return mp_obj_new_str(hostname, strlen(hostname)); +} + +void common_hal_mii_ethernet_set_hostname(mii_ethernet_obj_t *self, const char *hostname) { + if (self->netif == NULL) { + return; + } + CHECK_ESP_RESULT(esp_netif_set_hostname(self->netif, hostname)); +} + +const char *mii_get_hostname_raw(void) { + mii_ethernet_obj_t *self = (mii_ethernet_obj_t *)mii_get_default_instance(); + if (self == NULL || self->netif == NULL) { + return ""; + } + const char *hostname = NULL; + esp_netif_get_hostname(self->netif, &hostname); + return hostname == NULL ? "" : hostname; +} + +void mii_get_default_hostname(char *buf, size_t buf_size) { + if (buf_size == 0) { + return; + } + // The Ethernet constructor sets the MAC to the chip's factory default MAC. + uint8_t mac[MAC_ADDRESS_LENGTH] = {0}; + esp_efuse_mac_get_default(mac); + snprintf(buf, buf_size, "cpy-%02x%02x%02x%02x%02x%02x", + mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); +} + +// Raw uint32_t IPv4 address of the interface, in network byte order, or 0 +// when the interface has none. Used by supervisor/shared/web_workflow. +uint32_t mii_get_ipv4_address(void) { + mii_ethernet_obj_t *self = (mii_ethernet_obj_t *)mii_get_default_instance(); + if (self == NULL || self->netif == NULL || !esp_netif_is_netif_up(self->netif)) { + return 0; + } + self->ip_info.ip.addr = 0; + esp_netif_get_ip_info(self->netif, &self->ip_info); + return self->ip_info.ip.addr; +} + +// Blocks until the interface has an IPv4 address (DHCP lease or static), or +// 20s pass, or a hard interrupt arrives. Returns immediately when the +// interface cannot ever get one (down, disabled or no link). Used by the +// supervisor so the web workflow's listening socket can be created during +// the boot that brings the interface up instead of after the next VM start. +void mii_wait_for_lease(void) { + mii_ethernet_obj_t *self = (mii_ethernet_obj_t *)mii_get_default_instance(); + if (self == NULL || self->netif == NULL || !self->started || !self->connected) { + return; + } + int64_t deadline = esp_timer_get_time() + 20 * 1000000; + while (esp_timer_get_time() < deadline && mii_get_ipv4_address() == 0) { + if (mp_hal_is_interrupted()) { + break; + } + RUN_BACKGROUND_TASKS; + port_task_sleep_ms(50); + } +} + +mp_obj_t common_hal_mii_ethernet_get_mac_address(mii_ethernet_obj_t *self) { + uint8_t mac[MAC_ADDRESS_LENGTH] = {0}; + if (self->eth_handle != NULL) { + esp_eth_ioctl(self->eth_handle, ETH_CMD_G_MAC_ADDR, mac); + } + return mp_obj_new_bytes(mac, MAC_ADDRESS_LENGTH); +} + +mp_int_t common_hal_mii_ethernet_get_link_speed(mii_ethernet_obj_t *self) { + if (self->eth_handle == NULL || !self->connected) { + return 0; + } + eth_speed_t speed; + if (esp_eth_ioctl(self->eth_handle, ETH_CMD_G_SPEED, &speed) != ESP_OK) { + return 0; + } + return speed == ETH_SPEED_100M ? 100 : 10; +} + +bool common_hal_mii_ethernet_get_full_duplex(mii_ethernet_obj_t *self) { + if (self->eth_handle == NULL || !self->connected) { + return false; + } + eth_duplex_t duplex; + if (esp_eth_ioctl(self->eth_handle, ETH_CMD_G_DUPLEX_MODE, &duplex) != ESP_OK) { + return false; + } + return duplex == ETH_DUPLEX_FULL; +} + +void common_hal_mii_ethernet_start_dhcp_client(mii_ethernet_obj_t *self, bool ipv4, bool ipv6) { + if (self->netif == NULL) { + return; + } + if (ipv4) { + esp_netif_dhcpc_start(self->netif); + } else { + esp_netif_dhcpc_stop(self->netif); + } + if (ipv6) { + // TODO: DHCPv6 support + } +} + +void common_hal_mii_ethernet_stop_dhcp_client(mii_ethernet_obj_t *self) { + if (self->netif == NULL) { + return; + } + esp_netif_dhcpc_stop(self->netif); +} + +mp_obj_t common_hal_mii_ethernet_get_ipv4_gateway(mii_ethernet_obj_t *self) { + if (self->netif == NULL || !esp_netif_is_netif_up(self->netif)) { + return mp_const_none; + } + esp_netif_get_ip_info(self->netif, &self->ip_info); + return common_hal_ipaddress_new_ipv4address(self->ip_info.gw.addr); +} + +mp_obj_t common_hal_mii_ethernet_get_ipv4_subnet(mii_ethernet_obj_t *self) { + if (self->netif == NULL || !esp_netif_is_netif_up(self->netif)) { + return mp_const_none; + } + esp_netif_get_ip_info(self->netif, &self->ip_info); + return common_hal_ipaddress_new_ipv4address(self->ip_info.netmask.addr); +} + +mp_obj_t common_hal_mii_mii_get_ipv4_address(mii_ethernet_obj_t *self) { + if (self->netif == NULL || !esp_netif_is_netif_up(self->netif)) { + return mp_const_none; + } + esp_netif_get_ip_info(self->netif, &self->ip_info); + return common_hal_ipaddress_new_ipv4address(self->ip_info.ip.addr); +} + +mp_obj_t common_hal_mii_ethernet_get_ipv4_dns(mii_ethernet_obj_t *self) { + if (self->netif == NULL || !esp_netif_is_netif_up(self->netif)) { + return mp_const_none; + } + esp_netif_get_dns_info(self->netif, ESP_NETIF_DNS_MAIN, &self->dns_info); + if (self->dns_info.ip.type != ESP_IPADDR_TYPE_V4) { + return mp_const_none; + } + return common_hal_ipaddress_new_ipv4address(self->dns_info.ip.u_addr.ip4.addr); +} + +void common_hal_mii_ethernet_set_ipv4_dns(mii_ethernet_obj_t *self, mp_obj_t ipv4_dns_addr) { + if (self->netif == NULL) { + return; + } + esp_netif_dns_info_t dns_addr; + _ipv4address_to_esp_idf(ipv4_dns_addr, &dns_addr.ip.u_addr.ip4); + esp_netif_set_dns_info(self->netif, ESP_NETIF_DNS_MAIN, &dns_addr); +} + +mp_obj_t common_hal_mii_ethernet_get_addresses(mii_ethernet_obj_t *self) { + if (self->netif == NULL || !esp_netif_is_netif_up(self->netif)) { + return mp_const_empty_tuple; + } + esp_netif_ip_info_t ip_info; + esp_netif_get_ip_info(self->netif, &ip_info); + if (ip_info.ip.addr == IPADDR_ANY) { + return mp_const_empty_tuple; + } + mp_obj_t addr = _ip4_to_str(&ip_info.ip); + return mp_obj_new_tuple(1, &addr); +} + +mp_obj_t common_hal_mii_ethernet_get_dns(mii_ethernet_obj_t *self) { + if (self->netif == NULL || !esp_netif_is_netif_up(self->netif)) { + return mp_const_empty_tuple; + } + esp_netif_dns_info_t dns_info; + esp_netif_get_dns_info(self->netif, ESP_NETIF_DNS_MAIN, &dns_info); + if (dns_info.ip.type == ESP_IPADDR_TYPE_V4 && dns_info.ip.u_addr.ip4.addr == IPADDR_ANY) { + return mp_const_empty_tuple; + } + mp_obj_t addr = _ipaddr_to_str(&dns_info.ip); + return mp_obj_new_tuple(1, &addr); +} + +void common_hal_mii_ethernet_set_dns(mii_ethernet_obj_t *self, mp_obj_t dns_addrs_obj) { + (void)self; + (void)dns_addrs_obj; + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_dns); +} + +void common_hal_mii_ethernet_set_ipv4_address(mii_ethernet_obj_t *self, mp_obj_t ipv4, mp_obj_t netmask, mp_obj_t gateway, mp_obj_t ipv4_dns) { + if (self->netif == NULL) { + return; + } + common_hal_mii_ethernet_stop_dhcp_client(self); + + esp_netif_ip_info_t ip_info; + _ipv4address_to_esp_idf(ipv4, &ip_info.ip); + _ipv4address_to_esp_idf(netmask, &ip_info.netmask); + _ipv4address_to_esp_idf(gateway, &ip_info.gw); + + esp_netif_set_ip_info(self->netif, &ip_info); + + if (ipv4_dns != MP_OBJ_NULL) { + common_hal_mii_ethernet_set_ipv4_dns(self, ipv4_dns); + } +} + +mp_int_t common_hal_mii_ethernet_ping(mii_ethernet_obj_t *self, mp_obj_t ip_address, mp_float_t timeout) { + (void)self; + (void)ip_address; + (void)timeout; + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_ping); +} diff --git a/ports/espressif/common-hal/mii/Ethernet.h b/ports/espressif/common-hal/mii/Ethernet.h new file mode 100644 index 00000000000..1b0d28eb2ee --- /dev/null +++ b/ports/espressif/common-hal/mii/Ethernet.h @@ -0,0 +1,33 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +#include "common-hal/microcontroller/Pin.h" +#include "common-hal/mii/RMII.h" + +#include "esp_eth.h" +#include "esp_netif.h" + +typedef struct { + mp_obj_base_t base; + esp_eth_handle_t eth_handle; + esp_netif_t *netif; + esp_eth_netif_glue_handle_t glue; + esp_netif_ip_info_t ip_info; + esp_netif_dns_info_t dns_info; + uint32_t ping_elapsed_time; + bool started; + bool connected; +} mii_ethernet_obj_t; + +// Brings up the built-in RMII MAC on the given bus and the 802.3 PHY at MDIO +// bus, and starts the interface with DHCP. Raises when bring-up +// fails. +void common_hal_mii_ethernet_construct(mii_ethernet_obj_t *self, + mii_rmii_obj_t *rmii); diff --git a/ports/espressif/common-hal/mii/MDIO.c b/ports/espressif/common-hal/mii/MDIO.c new file mode 100644 index 00000000000..bd883240516 --- /dev/null +++ b/ports/espressif/common-hal/mii/MDIO.c @@ -0,0 +1,30 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "common-hal/mii/MDIO.h" +#include "shared-bindings/mii/MDIO.h" + +#include "py/runtime.h" + + +#include "soc/soc_caps.h" + +void common_hal_mii_mdio_construct(mii_mdio_obj_t *self, + const mcu_pin_obj_t *mdc, const mcu_pin_obj_t *mdio) { + // Board code constructs board-owned globals that don't go through + // make_new, so set the type here. + self->base.type = &mii_mdio_type; + #if !((defined(SOC_EMAC_USE_MULTI_IO_MUX) && SOC_EMAC_USE_MULTI_IO_MUX) || (defined(SOC_EMAC_MII_USE_GPIO_MATRIX) && SOC_EMAC_MII_USE_GPIO_MATRIX)) + // The EMAC's management signals can't be routed to arbitrary GPIOs. + mp_raise_NotImplementedError(NULL); + #else + self->mdc = mdc->number; + self->mdio = mdio->number; + + claim_pin(mdc); + claim_pin(mdio); + #endif +} diff --git a/ports/espressif/common-hal/mii/MDIO.h b/ports/espressif/common-hal/mii/MDIO.h new file mode 100644 index 00000000000..5637ba81fc2 --- /dev/null +++ b/ports/espressif/common-hal/mii/MDIO.h @@ -0,0 +1,23 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +#include "common-hal/microcontroller/Pin.h" + + +typedef struct { + mp_obj_base_t base; + uint8_t mdc; + uint8_t mdio; +} mii_mdio_obj_t; + +// Claims the signals. Raises NotImplementedError on chips whose EMAC cannot +// route management signals via the GPIO matrix. +void common_hal_mii_mdio_construct(mii_mdio_obj_t *self, + const mcu_pin_obj_t *mdc, const mcu_pin_obj_t *mdio); diff --git a/ports/espressif/common-hal/mii/RMII.c b/ports/espressif/common-hal/mii/RMII.c new file mode 100644 index 00000000000..0f87a290db7 --- /dev/null +++ b/ports/espressif/common-hal/mii/RMII.c @@ -0,0 +1,47 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "common-hal/mii/RMII.h" +#include "shared-bindings/mii/MDIO.h" +#include "shared-bindings/mii/RMII.h" + +#include "py/runtime.h" + + +#include "soc/soc_caps.h" + +void common_hal_mii_rmii_construct(mii_rmii_obj_t *self, + mii_mdio_obj_t *mdio, uint32_t device, + const mcu_pin_obj_t *rxd0, const mcu_pin_obj_t *rxd1, const mcu_pin_obj_t *rx_dv, + const mcu_pin_obj_t *txd0, const mcu_pin_obj_t *txd1, const mcu_pin_obj_t *tx_en, + const mcu_pin_obj_t *refclk, const mcu_pin_obj_t *reset) { + // Board code constructs board-owned globals that don't go through + // make_new, so set the type here. + self->base.type = &mii_rmii_type; + #if !((defined(SOC_EMAC_USE_MULTI_IO_MUX) && SOC_EMAC_USE_MULTI_IO_MUX) || (defined(SOC_EMAC_MII_USE_GPIO_MATRIX) && SOC_EMAC_MII_USE_GPIO_MATRIX)) + // The EMAC's RMII signals can't be routed to arbitrary GPIOs. + mp_raise_NotImplementedError(NULL); + #else + self->mdio = mdio; + self->device = device; + self->rxd0 = rxd0->number; + self->rxd1 = rxd1->number; + self->rx_dv = rx_dv->number; + self->txd0 = txd0->number; + self->txd1 = txd1->number; + self->tx_en = tx_en->number; + self->refclk = refclk->number; + self->reset = reset == NULL ? -1 : reset->number; + + const mcu_pin_obj_t *pins[] = { rxd0, rxd1, rx_dv, txd0, txd1, tx_en, refclk }; + for (size_t i = 0; i < MP_ARRAY_SIZE(pins); i++) { + claim_pin(pins[i]); + } + if (reset != NULL) { + claim_pin(reset); + } + #endif +} diff --git a/ports/espressif/common-hal/mii/RMII.h b/ports/espressif/common-hal/mii/RMII.h new file mode 100644 index 00000000000..c15092138d4 --- /dev/null +++ b/ports/espressif/common-hal/mii/RMII.h @@ -0,0 +1,44 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +#include "common-hal/mii/MDIO.h" +#include "common-hal/microcontroller/Pin.h" + +#include "esp_eth.h" + + +typedef struct { + mp_obj_base_t base; + // Shared management bus, owned by the mii_mdio_obj_t. + mii_mdio_obj_t *mdio; + // MDIO address (0-31) of the PHY hanging off the shared bus. + uint32_t device; + uint8_t rxd0; + uint8_t rxd1; + uint8_t rx_dv; + uint8_t txd0; + uint8_t txd1; + uint8_t tx_en; + uint8_t refclk; + // -1 when the PHY has no reset wiring. + int8_t reset; + // SMI master of the interface built on this bus, set by the ethernet + // construct. One EMAC instance per bus on these chips, so a non-NULL + // master means the bus can't serve another interface. + esp_eth_mac_t *mac; +} mii_rmii_obj_t; + +// Claims the signals. Raises NotImplementedError on chips whose EMAC cannot +// route RMII signals via the GPIO matrix. +void common_hal_mii_rmii_construct(mii_rmii_obj_t *self, + mii_mdio_obj_t *mdio, uint32_t device, + const mcu_pin_obj_t *rxd0, const mcu_pin_obj_t *rxd1, const mcu_pin_obj_t *rx_dv, + const mcu_pin_obj_t *txd0, const mcu_pin_obj_t *txd1, const mcu_pin_obj_t *tx_en, + const mcu_pin_obj_t *refclk, const mcu_pin_obj_t *reset); diff --git a/ports/espressif/common-hal/mii/__init__.c b/ports/espressif/common-hal/mii/__init__.c new file mode 100644 index 00000000000..ad51d36b551 --- /dev/null +++ b/ports/espressif/common-hal/mii/__init__.c @@ -0,0 +1,26 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "common-hal/mii/__init__.h" +#include "shared-bindings/mii/__init__.h" + +void mii_user_reset(void) { + // Nothing to do on user reset for now. +} + +static mii_ethernet_obj_t *_default_instance; + +// Called by board code once the board's ethernet interface is constructed. +void mii_set_default_instance(mii_ethernet_obj_t *self) { + _default_instance = self; +} + +mp_obj_t mii_get_default_instance(void) { + if (_default_instance == NULL) { + return NULL; + } + return MP_OBJ_FROM_PTR(_default_instance); +} diff --git a/ports/espressif/common-hal/mii/__init__.h b/ports/espressif/common-hal/mii/__init__.h new file mode 100644 index 00000000000..e46ce23c0a6 --- /dev/null +++ b/ports/espressif/common-hal/mii/__init__.h @@ -0,0 +1,18 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "common-hal/mii/Ethernet.h" + +void mii_user_reset(void); + +// Cross-translation-unit API for supervisor/shared/web_workflow.c; the +// declarations (and web_workflow's contract) live in +// shared-bindings/mii/__init__.h. The board calls set_default_instance +// once its own instance is constructed. +void mii_set_default_instance(mii_ethernet_obj_t *self); +mp_obj_t mii_get_default_instance(void); diff --git a/ports/espressif/common-hal/mipicsi/Camera.c b/ports/espressif/common-hal/mipicsi/Camera.c new file mode 100644 index 00000000000..5616ef8a3f1 --- /dev/null +++ b/ports/espressif/common-hal/mipicsi/Camera.c @@ -0,0 +1,483 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Jeff Epler for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "py/gc.h" +#include "py/mperrno.h" +#include "py/mphal.h" +#include "py/nlr.h" +#include "py/runtime.h" + +#include "common-hal/mipicsi/Camera.h" +#include "shared-bindings/mipicsi/Camera.h" +#include "shared-bindings/mipicsi/__init__.h" +#include "bindings/espidf/__init__.h" + +#include "common-hal/mipidsi/Bus.h" + +#include +#include "esp_attr.h" +#include "esp_cache.h" +#include "esp_cam_ctlr.h" +#include "esp_private/esp_cache_private.h" +#include "esp_cam_ctlr_csi.h" +#include "hal/color_hal.h" + +// MIPI CSI receives data from a fixed, dedicated set of pins, so no pin +// configuration or claiming is done here. + +#define ISP_CLK_HZ (80 * 1000 * 1000) + +static cam_ctlr_color_t mipicsi_color_for(mipicsi_pixel_format_t format) { + switch (format) { + case MIPICSI_FORMAT_RAW8: + return CAM_CTLR_COLOR_RAW8; + case MIPICSI_FORMAT_RAW10: + return CAM_CTLR_COLOR_RAW10; + case MIPICSI_FORMAT_RAW12: + return CAM_CTLR_COLOR_RAW12; + case MIPICSI_FORMAT_RGB888: + return CAM_CTLR_COLOR_RGB888; + case MIPICSI_FORMAT_YUV422: + return CAM_CTLR_COLOR_YUV422_YUYV; + case MIPICSI_FORMAT_GRAYSCALE: + return CAM_CTLR_COLOR_GRAY8; + case MIPICSI_FORMAT_RGB565: + default: + return CAM_CTLR_COLOR_RGB565; + } +} + +static mp_int_t mipicsi_bits_per_pixel_for(mipicsi_pixel_format_t format) { + switch (format) { + case MIPICSI_FORMAT_RAW10: + return 10; + case MIPICSI_FORMAT_RAW12: + return 12; + case MIPICSI_FORMAT_RGB888: + return 24; + case MIPICSI_FORMAT_RGB565: + case MIPICSI_FORMAT_YUV422: + return 16; + case MIPICSI_FORMAT_RAW8: + case MIPICSI_FORMAT_GRAYSCALE: + default: + return 8; + } +} + +#if SOC_ISP_SUPPORTED +// The ISP color types share their FOURCC values with the CAM_CTLR color +// types, except for GRAYSCALE (no ISP grey mode) and YUV422 (the ISP input is +// UYVY, the CAM_CTLR YUYV). Only sensor RAW formats convert here. +static isp_color_t mipicsi_isp_color_for(mipicsi_pixel_format_t format) { + switch (format) { + case MIPICSI_FORMAT_RAW8: + return ISP_COLOR_RAW8; + case MIPICSI_FORMAT_RAW10: + return ISP_COLOR_RAW10; + case MIPICSI_FORMAT_RAW12: + return ISP_COLOR_RAW12; + case MIPICSI_FORMAT_RGB565: + return ISP_COLOR_RGB565; + case MIPICSI_FORMAT_RGB888: + return ISP_COLOR_RGB888; + case MIPICSI_FORMAT_YUV422: + case MIPICSI_FORMAT_GRAYSCALE: + default: + return 0; + } +} +#endif + +// Called by the driver (in ISR context) to get the next buffer to DMA into. +static IRAM_ATTR bool mipicsi_on_get_new_trans( + esp_cam_ctlr_handle_t handle, esp_cam_ctlr_trans_t *trans, void *user_data) { + mipicsi_camera_obj_t *self = user_data; + + // DMA the whole frame into the current destination; a change is picked + // up on the next frame. The controller only runs while a destination is + // set, so dest_base is never NULL here. + trans->buffer = (void *)self->dest_base; + trans->buflen = self->buffer_len; + return false; +} + +// Called by the driver (in ISR context) when a frame has been written. +static IRAM_ATTR bool mipicsi_on_trans_finished( + esp_cam_ctlr_handle_t handle, esp_cam_ctlr_trans_t *trans, void *user_data) { + mipicsi_camera_obj_t *self = user_data; + + // Report where the frame actually landed: after a destination change + // (or a pause) the frame that was in flight lands at the previous one. + if (self->dest_base != NULL && self->dest_on_frame != NULL) { + self->dest_on_frame(self->dest_ctx, trans->buffer, NULL); + } + return false; +} + +void common_hal_mipicsi_camera_construct( + mipicsi_camera_obj_t *self, + mipicsi_pixel_format_t output_format) { + + self->width = 1; + self->height = 1; + self->pixel_format = output_format; + self->output_format = output_format; + self->dest_base = NULL; + self->dest_on_frame = NULL; + self->dest_ctx = NULL; + self->ctlr_started = false; + self->paused = false; + self->sensor = mp_const_none; + self->phy_ldo = NULL; + self->isp_proc = NULL; + self->spinlock = (portMUX_TYPE)portMUX_INITIALIZER_UNLOCKED; + // No receiver hardware yet: it is created in the videosource play step, + // where the sensor's current mode is known. +} + +void common_hal_mipicsi_camera_videosource_play( + mipicsi_camera_obj_t *self, + const mipicsi_sensor_params_t *params, + bool paused) { + + if (self->handle != NULL) { + mp_raise_RuntimeError(MP_ERROR_TEXT("already playing")); + } + + // pixel_format is reread from the sensor at every play, so validate the + // conversion here. + #if SOC_ISP_SUPPORTED + if (self->output_format != params->pixel_format) { + // The ISP only converts from RAW. Other formats must be passed + // through unconverted. + const isp_color_t isp_in = mipicsi_isp_color_for(params->pixel_format); + if (isp_in != ISP_COLOR_RAW8 && isp_in != ISP_COLOR_RAW10 && isp_in != ISP_COLOR_RAW12) { + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("unsupported %q type"), MP_QSTR_pixel_format); + } + const isp_color_t isp_out = mipicsi_isp_color_for(self->output_format); + if (isp_out != ISP_COLOR_RGB565 && isp_out != ISP_COLOR_RGB888) { + mp_raise_ValueError(MP_ERROR_TEXT("output_format must be RGB565 or RGB888")); + } + } + #else + if (self->output_format != params->pixel_format) { + mp_raise_NotImplementedError(MP_ERROR_TEXT("ISP conversion not supported on this chip")); + } + #endif + + self->paused = paused; + + // Adopt the sensor's current mode. + self->pixel_format = params->pixel_format; + self->width = params->width; + self->height = params->height; + self->bayer_order = params->bayer_order; + self->data_lanes = params->data_lanes; + self->lane_bit_rate_mbps = params->lane_bit_rate_mbps; + + const cam_ctlr_color_t color = mipicsi_color_for(self->pixel_format); + + #if SOC_ISP_SUPPORTED + if (self->output_format != self->pixel_format) { + // The CSI bridge on gen-1 P4 silicon can't convert, so the ISP does + // (as in the IDF esp_driver_cam csi test). + const isp_color_t isp_in = mipicsi_isp_color_for(self->pixel_format); + const isp_color_t isp_out = mipicsi_isp_color_for(self->output_format); + esp_isp_processor_cfg_t isp_config = { + .clk_hz = ISP_CLK_HZ, + .input_data_source = ISP_INPUT_DATA_SOURCE_CSI, + .input_data_color_type = isp_in, + .output_data_color_type = isp_out, + .has_line_start_packet = false, + .has_line_end_packet = false, + .h_res = self->width, + .v_res = self->height, + .bayer_order = (color_raw_element_order_t)self->bayer_order, + }; + CHECK_ESP_RESULT(esp_isp_new_processor(&isp_config, &self->isp_proc)); + } + #endif + + // Power the MIPI D-PHY. The LDO is shared with mipidsi (see + // mipidsi_phy_ldo_acquire). + self->phy_ldo = mipidsi_phy_ldo_acquire(); + + // The CSI bridge doesn't convert (input and output color match); the ISP + // does. bits_per_pixel is the output depth so the driver sizes the DMA + // for the converted frame, not the smaller RAW input. + esp_cam_ctlr_csi_config_t csi_config = { + .ctlr_id = 0, + .h_res = self->width, + .v_res = self->height, + .data_lane_num = self->data_lanes, + .lane_bit_rate_mbps = self->lane_bit_rate_mbps, + .input_data_color_type = color, + .output_data_color_type = color, + .data_type = { + .bits_per_pixel = mipicsi_bits_per_pixel_for(self->output_format), + .data_type_min = 0x12, + .data_type_max = 0x2f, + }, + // Frames go straight to the destination and the controller only runs + // while one is set, so skip the driver's frame-sized backup buffer. + .queue_items = 1, + .bk_buffer_dis = true, + }; + + esp_err_t result = esp_cam_new_csi_ctlr(&csi_config, &self->handle); + if (result != ESP_OK) { + mipidsi_phy_ldo_release(); + self->phy_ldo = NULL; + #if SOC_ISP_SUPPORTED + if (self->isp_proc) { + esp_isp_del_processor(self->isp_proc); + self->isp_proc = NULL; + } + #endif + raise_esp_error(result); + } + + // Unpadded frame size. set_destination() replaces it with the padded + // length before the controller starts. + self->buffer_len = ((size_t)self->width * self->height * mipicsi_bits_per_pixel_for(self->output_format) + 7) / 8; + + esp_cam_ctlr_evt_cbs_t cbs = { + .on_get_new_trans = mipicsi_on_get_new_trans, + .on_trans_finished = mipicsi_on_trans_finished, + }; + result = esp_cam_ctlr_register_event_callbacks(self->handle, &cbs, self); + if (result == ESP_OK) { + result = esp_cam_ctlr_enable(self->handle); + } + #if SOC_ISP_SUPPORTED + if (result == ESP_OK && self->isp_proc) { + result = esp_isp_enable(self->isp_proc); + } + #endif + if (result != ESP_OK) { + common_hal_mipicsi_camera_deinit(self); + raise_esp_error(result); + } + + // Start the sensor so frames are ready once a destination is set. + // Sensors' _start() is expected to be idempotent. + if (self->sensor != mp_const_none) { + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + mp_obj_t start_method[2]; + mp_load_method(self->sensor, MP_QSTR__start, start_method); + mp_call_method_n_kw(0, 0, start_method); + nlr_pop(); + } else { + common_hal_mipicsi_camera_deinit(self); + nlr_raise(nlr.ret_val); + } + } + + // The controller starts in set_destination(), once frames have somewhere + // to go. +} + +// Turn off the CSI receiver and ISP. Must not raise: this also runs from +// background contexts such as reload. The sensor is left alone. +static void mipicsi_camera_teardown(mipicsi_camera_obj_t *self) { + // Always stop, even when paused: a pause's stop finishes in the + // background, and it must be complete before the controller is disabled. + // esp_cam_ctlr_stop waits for it (and is a no-op once stopped). + if (self->handle != NULL) { + esp_cam_ctlr_stop(self->handle); + } + self->ctlr_started = false; + portENTER_CRITICAL(&self->spinlock); + self->dest_base = NULL; + self->dest_on_frame = NULL; + self->dest_ctx = NULL; + self->paused = false; + portEXIT_CRITICAL(&self->spinlock); + + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + if (self->handle != NULL) { + esp_cam_ctlr_disable(self->handle); + esp_cam_ctlr_del(self->handle); + self->handle = NULL; + } + #if SOC_ISP_SUPPORTED + if (self->isp_proc) { + esp_isp_disable(self->isp_proc); + esp_isp_del_processor(self->isp_proc); + self->isp_proc = NULL; + } + #endif + mipidsi_phy_ldo_release(); + self->phy_ldo = NULL; + nlr_pop(); + } else { + // Nothing to do about a failed teardown, not even a partially + // released one; swallow the exception and continue. + } +} + +void common_hal_mipicsi_camera_set_sensor(mipicsi_camera_obj_t *self, mp_obj_t sensor) { + self->sensor = sensor; +} + +mp_obj_t common_hal_mipicsi_camera_get_sensor(mipicsi_camera_obj_t *self) { + return self->sensor; +} + +// Sensors' _stop() is expected to be idempotent. +static void mipicsi_camera_stop_sensor(mipicsi_camera_obj_t *self) { + mp_obj_t stop_method[2]; + mp_load_method(self->sensor, MP_QSTR__stop, stop_method); + mp_call_method_n_kw(0, 0, stop_method); +} + +void common_hal_mipicsi_camera_deinit(mipicsi_camera_obj_t *self) { + if (self->handle != NULL) { + mipicsi_camera_teardown(self); + // Stop the sensor too, but only if it is still allocated: from the GC + // sweep, it may already have been freed. Ignore errors since this + // must not raise. + if (mp_obj_is_obj(self->sensor) && gc_nbytes(MP_OBJ_TO_PTR(self->sensor)) > 0) { + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + mipicsi_camera_stop_sensor(self); + nlr_pop(); + } + } + } + // Clearing the sensor marks the camera deinitialised. + self->sensor = mp_const_none; +} + +void common_hal_mipicsi_camera_videosource_stop(mipicsi_camera_obj_t *self) { + if (self->handle == NULL) { + return; // Not playing. + } + + // The receiver first: after the CSI controller stops, no more frames are + // captured, whatever the sensor does. + mipicsi_camera_teardown(self); + + // Stop the sensor (e.g. the sc2336 stops streaming and unlocks its + // mode). + if (self->sensor != mp_const_none) { + mipicsi_camera_stop_sensor(self); + } +} + +void common_hal_mipicsi_camera_videosource_pause(mipicsi_camera_obj_t *self) { + if (self->handle == NULL) { + return; // Not playing. + } + + // Keep the ISP running so its AE/AWB state survives; stopping the CSI + // controller is enough to keep frames out of memory. Stop at the frame + // end without waiting: that last frame still lands and is reported + // through on_frame so the target can repaint over it. + if (self->ctlr_started) { + // Only fails when not started, which ctlr_started rules out. + (void)esp_cam_ctlr_csi_stop_at_frame_end(self->handle); + self->ctlr_started = false; + } + self->paused = true; +} + +// May raise; paused stays set if the controller can't start. +void common_hal_mipicsi_camera_videosource_resume(mipicsi_camera_obj_t *self) { + if (self->handle == NULL) { + return; // Not playing. + } + + if (!self->ctlr_started && self->dest_base != NULL) { + // Starting while the pause's stop is still pending cancels it; the + // frame in flight still lands at the destination from pause time and + // on_frame reports it there. + CHECK_ESP_RESULT(esp_cam_ctlr_start(self->handle)); + self->ctlr_started = true; + } + self->paused = false; +} + +bool common_hal_mipicsi_camera_deinited(mipicsi_camera_obj_t *self) { + return self->sensor == mp_const_none; +} + +bool common_hal_mipicsi_camera_set_destination( + mipicsi_camera_obj_t *self, + uint8_t *base, + size_t stride, + videocore_on_frame_fun on_frame, + void *ctx) { + const size_t row_bytes = ((size_t)self->width * mipicsi_bits_per_pixel_for(self->output_format) + 7) / 8; + const size_t frame_bytes = (size_t)self->height * row_bytes; + + // The videosource protocol never passes NULL. + assert(base != NULL); + + // The driver's per-frame esp_cache_msync needs a cache-line aligned + // buffer. PSRAM GC allocations already are (64-byte GC blocks), so this + // is a safety net. + size_t cache_line = 0; + esp_cache_get_alignment(MALLOC_CAP_SPIRAM, &cache_line); + if (cache_line == 0) { + cache_line = 64; + } + if ((uintptr_t)base % cache_line != 0) { + return false; + } + + // The CSI DMA only does contiguous transfers, so rows can't be padded. + // The caller has already checked that the frame fits. + if (stride != row_bytes) { + return false; + } + + // Size handed to the driver: the frame, cache-line padded at the end so + // the driver's per-frame sync is happy. + const size_t buffer_len = (frame_bytes + cache_line - 1) / cache_line * cache_line; + + portENTER_CRITICAL(&self->spinlock); + self->dest_base = base; + self->dest_on_frame = on_frame; + self->dest_ctx = ctx; + self->buffer_len = buffer_len; + portEXIT_CRITICAL(&self->spinlock); + + // The sensor streaming and the receiver hardware exist from play(); + // here only the controller runs or doesn't. While paused, just remember + // the new destination: resume() starts the controller there. + if (!self->paused && !self->ctlr_started) { + esp_err_t result = esp_cam_ctlr_start(self->handle); + if (result != ESP_OK) { + return false; + } + self->ctlr_started = true; + } + return true; +} + +mipicsi_pixel_format_t common_hal_mipicsi_camera_get_pixel_format(mipicsi_camera_obj_t *self) { + return self->pixel_format; +} + +mipicsi_pixel_format_t common_hal_mipicsi_camera_get_output_format(mipicsi_camera_obj_t *self) { + return self->output_format; +} + +mp_int_t common_hal_mipicsi_camera_get_width(mipicsi_camera_obj_t *self) { + return self->width; +} + +mp_int_t common_hal_mipicsi_camera_get_height(mipicsi_camera_obj_t *self) { + return self->height; +} + +mp_int_t common_hal_mipicsi_camera_get_bits_per_pixel(mipicsi_camera_obj_t *self) { + return mipicsi_bits_per_pixel_for(self->output_format); +} diff --git a/ports/espressif/common-hal/mipicsi/Camera.h b/ports/espressif/common-hal/mipicsi/Camera.h new file mode 100644 index 00000000000..b709fee30c3 --- /dev/null +++ b/ports/espressif/common-hal/mipicsi/Camera.h @@ -0,0 +1,81 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Jeff Epler for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include + +#include "py/obj.h" + +#include "freertos/FreeRTOS.h" +#include "freertos/portmacro.h" + +#include "esp_cam_ctlr.h" +#include "esp_ldo_regulator.h" + +#if SOC_ISP_SUPPORTED +#include "driver/isp.h" +#endif + +#include "shared-bindings/mipicsi/__init__.h" +#include "shared-module/videocore/__init__.h" + +typedef struct mipicsi_camera_obj mipicsi_camera_obj_t; + +// Sensor parameters used to build the receiver. Read off the sensor object +// when a stream starts (the sensor is free to reconfigure between streams). +typedef struct { + mipicsi_pixel_format_t pixel_format; + mp_int_t width; + mp_int_t height; + mp_int_t bayer_order; + mp_int_t data_lanes; + mp_int_t lane_bit_rate_mbps; +} mipicsi_sensor_params_t; + +struct mipicsi_camera_obj { + mp_obj_base_t base; + esp_cam_ctlr_handle_t handle; + + // Power for the MIPI D-PHY, shared with the DSI transmitter. Acquired + // when a stream starts and released when it (or the camera) ends. + esp_ldo_channel_handle_t phy_ldo; + + // Camera sensor to receive from, or None once deinitialised. + mp_obj_t sensor; + + mipicsi_pixel_format_t output_format; + #if SOC_ISP_SUPPORTED + // Converts sensor frames to output_format when they differ. Only exists + // while playing. + isp_proc_handle_t isp_proc; + #endif + + // Streaming destination, set by videocore.VideoBuffer. The CSI controller + // only runs while dest_base is set. Frames are DMA'd contiguously into + // dest_base, which must be cache-line aligned. dest_on_frame(dest_ctx, + // frame, NULL) is called from the ISR with where each frame landed; a + // frame in flight when the destination changes lands at the previous one. + volatile void *dest_base; + videocore_on_frame_fun dest_on_frame; + void *dest_ctx; + bool ctlr_started; + // True between pause and resume: only the CSI controller is stopped. + // set_destination() still updates where resume() starts. + bool paused; + + portMUX_TYPE spinlock; + + mp_int_t width; + mp_int_t height; + mipicsi_pixel_format_t pixel_format; + mp_int_t data_lanes; + mp_int_t lane_bit_rate_mbps; + // Bayer element order of the sensor's RAW output, only used when the ISP + // converts from a RAW format. + mp_int_t bayer_order; + size_t buffer_len; // Length handed to the driver, includes cache-alignment padding. +}; diff --git a/ports/espressif/common-hal/mipicsi/__init__.c b/ports/espressif/common-hal/mipicsi/__init__.c new file mode 100644 index 00000000000..816fea93ae9 --- /dev/null +++ b/ports/espressif/common-hal/mipicsi/__init__.c @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Jeff Epler for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/mipicsi/__init__.h" diff --git a/ports/espressif/common-hal/mipidsi/Bus.c b/ports/espressif/common-hal/mipidsi/Bus.c new file mode 100644 index 00000000000..2fdbecba3f1 --- /dev/null +++ b/ports/espressif/common-hal/mipidsi/Bus.c @@ -0,0 +1,169 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/mipidsi/Bus.h" +#include "bindings/espidf/__init__.h" +#include "py/runtime.h" +#include +#include +#include "hal/mipi_dsi_phy_ll.h" + +// The PHY PLL and the reported pixel clock are quantized, so a lane rate a few +// hertz below the requested minimum is still the intended rate. Without this, +// a 4 Hz shortfall can push the link to the next PHY step, up to 10 Mbps +// higher, which makes DSI video burst instead of staying continuous. +#define MIPIDSI_FREQUENCY_TOLERANCE_HZ 1000 + +// Shared MIPI PHY LDO rail. DSI buses and CSI receivers both need it; it is +// acquired once and released only when the last user goes away. +static esp_ldo_channel_handle_t mipidsi_phy_ldo = NULL; +static uint8_t mipidsi_phy_ldo_users = 0; + +esp_ldo_channel_handle_t mipidsi_phy_ldo_acquire(void) { + if (mipidsi_phy_ldo_users == 0) { + esp_ldo_channel_handle_t ldo = NULL; + esp_ldo_channel_config_t ldo_config = { + .chan_id = 3, + .voltage_mv = 2500, + // Fixed-voltage (non-adjustable) acquire so both users share the + // rail. An adjustable acquire would block the other user. + .flags.adjustable = false, + }; + ESP_ERROR_CHECK(esp_ldo_acquire_channel(&ldo_config, &ldo)); + mipidsi_phy_ldo = ldo; + } + mipidsi_phy_ldo_users++; + return mipidsi_phy_ldo; +} + +void mipidsi_phy_ldo_release(void) { + if (mipidsi_phy_ldo_users == 0) { + return; + } + mipidsi_phy_ldo_users--; + if (mipidsi_phy_ldo_users == 0 && mipidsi_phy_ldo != NULL) { + esp_ldo_release_channel(mipidsi_phy_ldo); + mipidsi_phy_ldo = NULL; + } +} + +void common_hal_mipidsi_bus_construct(mipidsi_bus_obj_t *self, mp_uint_t minimum_frequency, uint8_t num_lanes) { + if (self->use_count > 0) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("%q in use"), MP_QSTR_mipidsi); + } + + self->frequency = 0; + self->num_data_lanes = num_lanes; + self->bus_handle = NULL; + + if (minimum_frequency > MIPI_DSI_LL_MAX_PHY_MBPS * 1000000U) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("%q is above %u"), MP_QSTR_minimum_frequency, + (unsigned)(MIPI_DSI_LL_MAX_PHY_MBPS * 1000000U)); + } + + self->phy_ldo = mipidsi_phy_ldo_acquire(); + + // The PHY PLL snaps to the nearest rate it can generate, which can be + // below the request. Ask for the minimum in whole Mbps, then step up + // until the rate read back is at least the minimum. + float requested_mbps = ceilf((float)minimum_frequency / 1000000.0f); + if (requested_mbps < MIPI_DSI_LL_MIN_PHY_MBPS) { + requested_mbps = MIPI_DSI_LL_MIN_PHY_MBPS; + } + for (uint8_t attempt = 0; attempt < 8; attempt++) { + esp_lcd_dsi_bus_config_t bus_config = { + .bus_id = 0, + .num_data_lanes = num_lanes, + .phy_clk_src = MIPI_DSI_PHY_CLK_SRC_DEFAULT, + .lane_bit_rate_mbps = requested_mbps, + }; + + esp_err_t ret = esp_lcd_new_dsi_bus(&bus_config, &self->bus_handle); + if (ret != ESP_OK) { + self->bus_handle = NULL; + mipidsi_phy_ldo_release(); + self->phy_ldo = NULL; + self->num_data_lanes = 0; + CHECK_ESP_RESULT(ret); + } + + // The PHY PLL only generates certain rates, so record the real one. + float lane_bit_rate_mbps = requested_mbps; + if (esp_lcd_dsi_bus_get_lane_bit_rate(self->bus_handle, &lane_bit_rate_mbps) == ESP_OK) { + self->frequency = (mp_uint_t)lroundf(lane_bit_rate_mbps * 1000000.0f); + } else { + self->frequency = (mp_uint_t)lroundf(requested_mbps * 1000000.0f); + } + + if (self->frequency + MIPIDSI_FREQUENCY_TOLERANCE_HZ >= minimum_frequency) { + return; + } + + // The PLL rounded down. The finest step between achievable rates is + // 10 Mbps, so asking for the next step above what it produced always + // targets a higher rate. Try again with that request. + esp_lcd_del_dsi_bus(self->bus_handle); + self->bus_handle = NULL; + self->frequency = 0; + requested_mbps = lane_bit_rate_mbps + 10.0f; + if (requested_mbps > MIPI_DSI_LL_MAX_PHY_MBPS) { + break; + } + } + + mipidsi_phy_ldo_release(); + self->phy_ldo = NULL; + self->num_data_lanes = 0; + mp_raise_ValueError_varg(MP_ERROR_TEXT("%q is not reachable by the PHY"), MP_QSTR_minimum_frequency); +} + +void common_hal_mipidsi_bus_deinit(mipidsi_bus_obj_t *self) { + if (self->use_count > 0) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("%q in use"), MP_QSTR_Bus); + } + if (common_hal_mipidsi_bus_deinited(self)) { + return; + } + + // Delete the DSI bus + if (self->bus_handle != NULL) { + esp_lcd_del_dsi_bus(self->bus_handle); + self->bus_handle = NULL; + } + + // Release our hold on the shared MIPI PHY LDO; it stays powered as long + // as a CSI receiver (or other user) still holds it. + mipidsi_phy_ldo_release(); + self->phy_ldo = NULL; + + self->frequency = 0; + self->num_data_lanes = 0; +} + +bool common_hal_mipidsi_bus_deinited(mipidsi_bus_obj_t *self) { + return self->bus_handle == NULL; +} + +mp_uint_t common_hal_mipidsi_bus_get_frequency(mipidsi_bus_obj_t *self) { + return self->frequency; +} + +uint8_t common_hal_mipidsi_bus_get_num_lanes(mipidsi_bus_obj_t *self) { + return self->num_data_lanes; +} + +void mipidsi_bus_increment_use_count(mipidsi_bus_obj_t *self) { + self->use_count++; +} +void mipidsi_bus_decrement_use_count(mipidsi_bus_obj_t *self) { + if (self->use_count == 0) { + return; + } + self->use_count--; + if (self->use_count == 0) { + common_hal_mipidsi_bus_deinit(self); + } +} diff --git a/ports/espressif/common-hal/mipidsi/Bus.h b/ports/espressif/common-hal/mipidsi/Bus.h new file mode 100644 index 00000000000..1920275d430 --- /dev/null +++ b/ports/espressif/common-hal/mipidsi/Bus.h @@ -0,0 +1,30 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" +#include +#include + +typedef struct { + mp_obj_base_t base; + mp_uint_t frequency; + esp_lcd_dsi_bus_handle_t bus_handle; + esp_ldo_channel_handle_t phy_ldo; + uint8_t num_data_lanes; + uint8_t use_count; // Up to 4 displays +} mipidsi_bus_obj_t; + +void mipidsi_bus_increment_use_count(mipidsi_bus_obj_t *self); +void mipidsi_bus_decrement_use_count(mipidsi_bus_obj_t *self); + +// Acquire the shared MIPI PHY LDO rail (LDO channel 3, 2.5 V). DSI and CSI +// users share the rail; a shared reference count keeps it powered until the +// last user releases it, so the CSI receiver can stay active while a DSI bus +// comes and goes (and vice versa). +esp_ldo_channel_handle_t mipidsi_phy_ldo_acquire(void); +void mipidsi_phy_ldo_release(void); diff --git a/ports/espressif/common-hal/mipidsi/Display.c b/ports/espressif/common-hal/mipidsi/Display.c new file mode 100644 index 00000000000..f9b47f34526 --- /dev/null +++ b/ports/espressif/common-hal/mipidsi/Display.c @@ -0,0 +1,387 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/mipidsi/Display.h" +#include "shared-bindings/mipidsi/Bus.h" +#include "shared-bindings/pwmio/PWMOut.h" +#include "shared-bindings/digitalio/DigitalInOut.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/time/__init__.h" +#include "bindings/espidf/__init__.h" +#include +#include +#include +#include "hal/axi_icm_ll.h" +#include "py/runtime.h" + +// Cache write-back function (should be from rom/cache.h but it's not always available) +extern int Cache_WriteBack_Addr(uint32_t addr, uint32_t size); + +// Delete the panel and IO handles that construct created. construct's error +// paths use this rather than deinit(): deinit() does nothing until the DPI +// panel exists, and it gives back a bus use that construct hasn't taken yet. +static void clear_panel_handles(mipidsi_display_obj_t *self) { + if (self->dpi_panel_handle != NULL) { + esp_lcd_panel_del(self->dpi_panel_handle); + self->dpi_panel_handle = NULL; + } + if (self->dbi_io_handle != NULL) { + esp_lcd_panel_io_del(self->dbi_io_handle); + self->dbi_io_handle = NULL; + } +} + +// The vsync ISR reads the frame callback and its data as a pair, so they change together. +static portMUX_TYPE frame_cb_lock = portMUX_INITIALIZER_UNLOCKED; + +static void set_frame_cb(mipidsi_display_obj_t *self, framebuffer_frame_callback_t cb, void *data) { + portENTER_CRITICAL(&frame_cb_lock); + self->frame_cb = cb; + self->frame_cb_data = data; + portEXIT_CRITICAL(&frame_cb_lock); +} + +// The DPI driver requires this callback to live in IRAM. It runs in interrupt context, so it only +// forwards to the framebuffer's frame callback (which hands off to the LVGL port) and returns. +static bool IRAM_ATTR mipidsi_display_vsync_cb(esp_lcd_panel_handle_t panel, + esp_lcd_dpi_panel_event_data_t *edata, void *user_ctx) { + (void)panel; + (void)edata; + mipidsi_display_obj_t *self = user_ctx; + portENTER_CRITICAL_ISR(&frame_cb_lock); + framebuffer_frame_callback_t cb = self->frame_cb; + void *data = self->frame_cb_data; + portEXIT_CRITICAL_ISR(&frame_cb_lock); + if (cb != NULL) { + cb(data); + } + return false; +} + +void common_hal_mipidsi_display_construct(mipidsi_display_obj_t *self, + mipidsi_bus_obj_t *bus, + const uint8_t *init_sequence, + size_t init_sequence_len, + mp_uint_t virtual_channel, + mp_uint_t width, + mp_uint_t height, + mp_int_t rotation, + mp_uint_t color_depth, + const mcu_pin_obj_t *backlight_pin, + mp_float_t brightness, + mp_uint_t native_frames_per_second, + bool backlight_on_high, + mp_uint_t hsync_pulse_width, + mp_uint_t hsync_back_porch, + mp_uint_t hsync_front_porch, + mp_uint_t vsync_pulse_width, + mp_uint_t vsync_back_porch, + mp_uint_t vsync_front_porch, + mp_uint_t pixel_clock_frequency, + bool low_power_blanking) { + self->bus = bus; + self->virtual_channel = virtual_channel; + self->width = width; + self->height = height; + self->rotation = rotation; + self->color_depth = color_depth; + self->native_frames_per_second = native_frames_per_second; + self->pixel_clock_frequency = pixel_clock_frequency; + self->backlight_on_high = backlight_on_high; + self->framebuffer = NULL; + self->dbi_io_handle = NULL; + self->dpi_panel_handle = NULL; + self->frame_cb = NULL; + self->frame_cb_data = NULL; + self->backlight_inout.base.type = &mp_type_NoneType; + + // Create the DBI interface for sending commands + esp_lcd_dbi_io_config_t dbi_config = { + .virtual_channel = virtual_channel, + .lcd_cmd_bits = 8, + .lcd_param_bits = 8, + }; + + CHECK_ESP_RESULT(esp_lcd_new_panel_io_dbi(bus->bus_handle, &dbi_config, &self->dbi_io_handle)); + + // Determine the pixel format based on color depth + lcd_color_format_t color_format; + if (color_depth == 16) { + color_format = LCD_COLOR_FMT_RGB565; + } else if (color_depth == 24) { + color_format = LCD_COLOR_FMT_RGB888; + } else { + clear_panel_handles(self); + mp_raise_ValueError_varg(MP_ERROR_TEXT("Invalid %q"), MP_QSTR_color_depth); + } + + // Create the DPI panel for sending pixel data + esp_lcd_dpi_panel_config_t dpi_config = { + .virtual_channel = virtual_channel, + .dpi_clk_src = MIPI_DSI_DPI_CLK_SRC_DEFAULT, + // .dpi_clock_freq_mhz is a float; preserve fractional clock frequency + .dpi_clock_freq_mhz = pixel_clock_frequency / 1000000.0f, + .in_color_format = color_format, + .out_color_format = color_format, + .num_fbs = 1, + .video_timing = { + .h_size = width, + .v_size = height, + .hsync_pulse_width = hsync_pulse_width, + .hsync_back_porch = hsync_back_porch, + .hsync_front_porch = hsync_front_porch, + .vsync_pulse_width = vsync_pulse_width, + .vsync_back_porch = vsync_back_porch, + .vsync_front_porch = vsync_front_porch, + }, + .flags = { + .disable_lp = !low_power_blanking, + }, + }; + + esp_err_t ret = esp_lcd_new_panel_dpi(bus->bus_handle, &dpi_config, &self->dpi_panel_handle); + if (ret != ESP_OK) { + clear_panel_handles(self); + CHECK_ESP_RESULT(ret); + } + + // Scanout continuously reads the framebuffer from PSRAM through DW-GDMA. + // Give those reads the highest AXI-ICM QoS priority so CPU, cache and PPA + // traffic cannot starve the DSI bridge FIFO. DSI does not write to PSRAM. + axi_icm_ll_set_dw_gdma_qos_arbiter_prio(0, 0, 15); + axi_icm_ll_set_dw_gdma_qos_arbiter_prio(1, 0, 15); + + // The DPI divider is an integer, so record the clock it really produces. + float pixel_clock_mhz = 0; + if (esp_lcd_dpi_panel_get_pixel_clock(self->dpi_panel_handle, &pixel_clock_mhz) == ESP_OK) { + self->pixel_clock_frequency = (mp_uint_t)lroundf(pixel_clock_mhz * 1000000.0f); + } + + // Get the framebuffer allocated by the driver + void *fb = NULL; + ret = esp_lcd_dpi_panel_get_frame_buffer(self->dpi_panel_handle, 1, &fb); + if (ret != ESP_OK) { + clear_panel_handles(self); + CHECK_ESP_RESULT(ret); + } + + self->framebuffer = (uint8_t *)fb; + self->framebuffer_size = width * height * (color_depth / 8); + + // Send initialization sequence (format matches busdisplay) + #define DELAY 0x80 + uint32_t i = 0; + while (i < init_sequence_len) { + const uint8_t *cmd = init_sequence + i; + uint8_t data_size = *(cmd + 1); + bool delay = (data_size & DELAY) != 0; + data_size &= ~DELAY; + const uint8_t *data = cmd + 2; + esp_lcd_panel_io_tx_param(self->dbi_io_handle, cmd[0], data, data_size); + + uint16_t delay_length_ms = 0; + if (delay) { + data_size++; + delay_length_ms = *(cmd + 1 + data_size); + if (delay_length_ms == 255) { + delay_length_ms = 500; + } + } + common_hal_time_delay_ms(delay_length_ms); + i += 2 + data_size; + } + + // Initialize the panel after sending init commands + ret = esp_lcd_panel_init(self->dpi_panel_handle); + if (ret != ESP_OK) { + clear_panel_handles(self); + CHECK_ESP_RESULT(ret); + } + + // VSYNC is the frame boundary a FramebufferDisplay can pace itself with. The callback stays + // registered for the life of the panel; frame_cb is only set when a display asks for it. + esp_lcd_dpi_panel_event_callbacks_t dpi_cbs = { + .on_vsync = mipidsi_display_vsync_cb, + }; + ret = esp_lcd_dpi_panel_register_event_callbacks(self->dpi_panel_handle, &dpi_cbs, self); + if (ret != ESP_OK) { + clear_panel_handles(self); + CHECK_ESP_RESULT(ret); + } + + // Send display-ON (0x29) after the DPI/video stream is running, matching + // the reference BSP flow order. + esp_lcd_panel_io_tx_param(self->dbi_io_handle, 0x29, NULL, 0); + common_hal_time_delay_ms(20); + + // Setup backlight PWM if pin is provided + if (backlight_pin != NULL && common_hal_mcu_pin_is_free(backlight_pin)) { + #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; + common_hal_digitalio_digitalinout_construct(&self->backlight_inout, backlight_pin); + } else { + self->backlight_pwm.base.type = &pwmio_pwmout_type; + } + #else + self->backlight_inout.base.type = &digitalio_digitalinout_type; + common_hal_digitalio_digitalinout_construct(&self->backlight_inout, backlight_pin); + #endif + + // Set initial brightness + #if (CIRCUITPY_PWMIO) + if (self->backlight_pwm.base.type == &pwmio_pwmout_type) { + common_hal_pwmio_pwmout_set_duty_cycle(&self->backlight_pwm, (uint16_t)(brightness * 0xFFFF)); + } else + #endif + if (self->backlight_inout.base.type == &digitalio_digitalinout_type) { + bool on = brightness > 0; + if (!backlight_on_high) { + on = !on; + } + common_hal_digitalio_digitalinout_set_value(&self->backlight_inout, on); + } + } + mipidsi_bus_increment_use_count(self->bus); +} + +void common_hal_mipidsi_display_deinit(mipidsi_display_obj_t *self) { + if (common_hal_mipidsi_display_deinited(self)) { + return; + } + + // Stop the vsync ISR from reaching a display that is going away before the panel is deleted. + set_frame_cb(self, NULL, NULL); + + // Cleanup backlight + #if (CIRCUITPY_PWMIO) + if (self->backlight_pwm.base.type == &pwmio_pwmout_type) { + common_hal_pwmio_pwmout_deinit(&self->backlight_pwm); + } else + #endif + if (self->backlight_inout.base.type == &digitalio_digitalinout_type) { + common_hal_digitalio_digitalinout_deinit(&self->backlight_inout); + } + + clear_panel_handles(self); + + mipidsi_bus_decrement_use_count(self->bus); + self->bus = NULL; + self->framebuffer = NULL; +} + +bool common_hal_mipidsi_display_deinited(mipidsi_display_obj_t *self) { + return self->dpi_panel_handle == NULL; +} + +void common_hal_mipidsi_display_refresh(mipidsi_display_obj_t *self) { + // Drawing the framebuffer we got from the IDF will flush the cache(s) so + // DMA can see our changes. It won't cause an extra copy. + esp_lcd_panel_draw_bitmap(self->dpi_panel_handle, 0, 0, self->width, self->height, self->framebuffer); + + // The DPI panel will automatically refresh from the framebuffer + // No explicit refresh call is needed as the DSI hardware continuously + // sends data from the framebuffer to the display +} + +void common_hal_mipidsi_display_set_frame_callback(mipidsi_display_obj_t *self, + framebuffer_frame_callback_t cb, void *data) { + set_frame_cb(self, cb, data); +} + +void common_hal_mipidsi_display_refresh_rows(mipidsi_display_obj_t *self, const uint8_t *dirty_row_bitmap) { + if (dirty_row_bitmap == NULL) { + common_hal_mipidsi_display_refresh(self); + return; + } + // Drawing from the framebuffer itself only writes the cache back for the given rows, + // so write back just the runs of dirty rows instead of the whole frame. + mp_uint_t y = 0; + while (y < self->height) { + if ((dirty_row_bitmap[y / 8] & (1 << (y & 7))) == 0) { + y++; + continue; + } + mp_uint_t start = y; + while (y < self->height && (dirty_row_bitmap[y / 8] & (1 << (y & 7))) != 0) { + y++; + } + esp_lcd_panel_draw_bitmap(self->dpi_panel_handle, 0, start, self->width, y, self->framebuffer); + } +} + +mp_float_t common_hal_mipidsi_display_get_brightness(mipidsi_display_obj_t *self) { + return self->current_brightness; +} + +bool common_hal_mipidsi_display_set_brightness(mipidsi_display_obj_t *self, mp_float_t 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_PWMIO) + bool ispwm = (self->backlight_pwm.base.type == &pwmio_pwmout_type) ? true : false; + #else + bool ispwm = false; + #endif + + if (ispwm) { + #if (CIRCUITPY_PWMIO) + common_hal_pwmio_pwmout_set_duty_cycle(&self->backlight_pwm, (uint16_t)(0xffff * brightness)); + ok = true; + #else + ok = false; + #endif + } else if (self->backlight_inout.base.type == &digitalio_digitalinout_type) { + common_hal_digitalio_digitalinout_set_value(&self->backlight_inout, brightness > 0.99); + ok = true; + } + if (ok) { + self->current_brightness = brightness; + } + return ok; +} + +int common_hal_mipidsi_display_get_width(mipidsi_display_obj_t *self) { + return self->width; +} + +int common_hal_mipidsi_display_get_height(mipidsi_display_obj_t *self) { + return self->height; +} + +int common_hal_mipidsi_display_get_row_stride(mipidsi_display_obj_t *self) { + return self->width * (self->color_depth / 8); +} + +int common_hal_mipidsi_display_get_color_depth(mipidsi_display_obj_t *self) { + return self->color_depth; +} + +mp_uint_t common_hal_mipidsi_display_get_pixel_clock_frequency(mipidsi_display_obj_t *self) { + return self->pixel_clock_frequency; +} + +int common_hal_mipidsi_display_get_native_frames_per_second(mipidsi_display_obj_t *self) { + return self->native_frames_per_second; +} + +bool common_hal_mipidsi_display_get_grayscale(mipidsi_display_obj_t *self) { + return false; +} + +mp_int_t common_hal_mipidsi_display_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags) { + mipidsi_display_obj_t *self = (mipidsi_display_obj_t *)self_in; + + bufinfo->buf = self->framebuffer; + bufinfo->len = self->framebuffer_size; + bufinfo->typecode = 'B'; + + return 0; +} diff --git a/ports/espressif/common-hal/mipidsi/Display.h b/ports/espressif/common-hal/mipidsi/Display.h new file mode 100644 index 00000000000..5fd254f5039 --- /dev/null +++ b/ports/espressif/common-hal/mipidsi/Display.h @@ -0,0 +1,42 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" +#include "shared-module/framebufferio/__init__.h" +#include "shared-bindings/mipidsi/Bus.h" +#include "common-hal/microcontroller/Pin.h" +#include "common-hal/digitalio/DigitalInOut.h" +#include "common-hal/pwmio/PWMOut.h" +#include +#include + +typedef struct { + mp_obj_base_t base; + mipidsi_bus_obj_t *bus; + mp_uint_t virtual_channel; + mp_uint_t width; + mp_uint_t height; + mp_int_t rotation; + mp_uint_t color_depth; + mp_uint_t native_frames_per_second; + mp_uint_t pixel_clock_frequency; + uint8_t *framebuffer; + esp_lcd_panel_io_handle_t dbi_io_handle; + esp_lcd_panel_handle_t dpi_panel_handle; + size_t framebuffer_size; + union { + digitalio_digitalinout_obj_t backlight_inout; + #if CIRCUITPY_PWMIO + pwmio_pwmout_obj_t backlight_pwm; + #endif + }; + bool backlight_on_high; + mp_float_t current_brightness; + framebuffer_frame_callback_t frame_cb; + void *frame_cb_data; +} mipidsi_display_obj_t; diff --git a/ports/espressif/common-hal/mipidsi/__init__.c b/ports/espressif/common-hal/mipidsi/__init__.c new file mode 100644 index 00000000000..173f2146e87 --- /dev/null +++ b/ports/espressif/common-hal/mipidsi/__init__.c @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/mipidsi/__init__.h" diff --git a/ports/espressif/common-hal/mipidsi/__init__.h b/ports/espressif/common-hal/mipidsi/__init__.h new file mode 100644 index 00000000000..972a7c082fd --- /dev/null +++ b/ports/espressif/common-hal/mipidsi/__init__.h @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once diff --git a/ports/espressif/common-hal/neopixel_write/__init__.c b/ports/espressif/common-hal/neopixel_write/__init__.c index d0d46a31797..cd62220f620 100644 --- a/ports/espressif/common-hal/neopixel_write/__init__.c +++ b/ports/espressif/common-hal/neopixel_write/__init__.c @@ -31,6 +31,8 @@ #include "driver/gpio.h" #include "driver/rmt_tx.h" +#include "hal/rmt_periph.h" +#include "soc/soc_caps.h" // Use closer to WS2812-style timings instead of WS2812B, to accommodate more varieties. #define WS2812_T0H_NS (316) @@ -53,14 +55,13 @@ void common_hal_neopixel_write(const digitalio_digitalinout_obj_t *digitalinout, .trans_queue_depth = 1, }; - // Greedily try and grab as much RMT memory as we can. The more we get, the - // smoother the output will be because we'll trigger fewer interrupts. We'll - // give it all back once we're done. + // Greedily allocate as much RMT memory as possible, stepping down by one + // channel's worth each time. More memory means fewer interrupts and smoother output. + // We'll give it all back once we're done. rmt_channel_handle_t channel; esp_err_t result = ESP_ERR_NOT_FOUND; - // If no other channels are in use, we can use all of the RMT RAM including the RX channels. - config.mem_block_symbols = SOC_RMT_MEM_WORDS_PER_CHANNEL * SOC_RMT_CHANNELS_PER_GROUP; - while (result == ESP_ERR_NOT_FOUND && config.mem_block_symbols > 0) { + config.mem_block_symbols = SOC_RMT_MEM_WORDS_PER_CHANNEL * RMT_LL_CHANS_PER_INST; + while (result == ESP_ERR_NOT_FOUND && config.mem_block_symbols >= SOC_RMT_MEM_WORDS_PER_CHANNEL) { result = rmt_new_tx_channel(&config, &channel); config.mem_block_symbols -= SOC_RMT_MEM_WORDS_PER_CHANNEL; } @@ -117,6 +118,7 @@ void common_hal_neopixel_write(const digitalio_digitalinout_obj_t *digitalinout, rmt_del_channel(channel); raise_esp_error(result); } + result = ESP_ERR_TIMEOUT; while (result == ESP_ERR_TIMEOUT) { RUN_BACKGROUND_TASKS; diff --git a/ports/espressif/common-hal/nvm/ByteArray.c b/ports/espressif/common-hal/nvm/ByteArray.c index adea91411b6..971f9bc7991 100644 --- a/ports/espressif/common-hal/nvm/ByteArray.c +++ b/ports/espressif/common-hal/nvm/ByteArray.c @@ -46,7 +46,7 @@ static esp_err_t get_bytes(nvs_handle_t handle, uint8_t **buf_out) { *buf_out = NULL; return result; } - buf = m_malloc(size); // this SHOULD be the same as + buf = m_malloc_without_collect(size); // this SHOULD be the same as if (result == ESP_OK) { result = nvs_get_blob(handle, "data", buf, &size); } else { diff --git a/ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c b/ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c index 7721b5e197f..bdd3520f03f 100644 --- a/ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c +++ b/ports/espressif/common-hal/paralleldisplaybus/ParallelBus.c @@ -18,7 +18,7 @@ #include "common-hal/microcontroller/Pin.h" #include "py/runtime.h" -#include "driver/gpio.h" +#include /* * Current pin limitations for ESP32-S2 ParallelBus: @@ -67,10 +67,16 @@ void common_hal_paralleldisplaybus_parallelbus_construct_nonsequential(paralleld panel_io_config.dc_levels.dc_cmd_level = 0; panel_io_config.dc_levels.dc_data_level = 1; panel_io_config.dc_levels.dc_idle_level = 1; - CHECK_ESP_RESULT(esp_lcd_new_panel_io_i80(self->bus_handle, &panel_io_config, &self->panel_io_handle)); + esp_err_t err = esp_lcd_new_panel_io_i80(self->bus_handle, &panel_io_config, &self->panel_io_handle); + if (err != ESP_OK) { + esp_lcd_del_i80_bus(self->bus_handle); + self->bus_handle = NULL; + CHECK_ESP_RESULT(err); + } + // read and reset are optional. The display bus slot is zeroed, and pin 0 is a real pin. + self->read_pin_number = NO_PIN; if (read != NULL) { - common_hal_never_reset_pin(read); gpio_config_t read_config = { .pin_bit_mask = 1ull << read->number, .mode = GPIO_MODE_OUTPUT, @@ -85,7 +91,6 @@ void common_hal_paralleldisplaybus_parallelbus_construct_nonsequential(paralleld self->reset_pin_number = NO_PIN; if (reset != NULL) { - common_hal_never_reset_pin(reset); self->reset_pin_number = reset->number; } @@ -100,12 +105,17 @@ void common_hal_paralleldisplaybus_parallelbus_construct_nonsequential(paralleld gpio_config(&chip_select_config); gpio_set_level(self->cs_pin_number, true); - common_hal_never_reset_pin(chip_select); - common_hal_never_reset_pin(command); - common_hal_never_reset_pin(write); - for (uint8_t i = 0; i < n_pins; i++) { - common_hal_never_reset_pin(data_pins[i]); + claim_pin(data_pins[i]); + } + claim_pin(command); + claim_pin(chip_select); + claim_pin(write); + if (read != NULL) { + claim_pin(read); + } + if (reset != NULL) { + claim_pin(reset); } } diff --git a/ports/espressif/common-hal/paralleldisplaybus/ParallelBus.h b/ports/espressif/common-hal/paralleldisplaybus/ParallelBus.h index 4724ba7231a..114a1e527a6 100644 --- a/ports/espressif/common-hal/paralleldisplaybus/ParallelBus.h +++ b/ports/espressif/common-hal/paralleldisplaybus/ParallelBus.h @@ -8,7 +8,7 @@ #include "common-hal/digitalio/DigitalInOut.h" -#include "esp-idf/components/esp_lcd/include/esp_lcd_panel_io.h" +#include typedef struct { mp_obj_base_t base; diff --git a/ports/espressif/common-hal/ps2io/Ps2.c b/ports/espressif/common-hal/ps2io/Ps2.c index 0ef4da4aa6d..555ae3d3005 100644 --- a/ports/espressif/common-hal/ps2io/Ps2.c +++ b/ports/espressif/common-hal/ps2io/Ps2.c @@ -29,15 +29,6 @@ #define ERROR_TX_RTS 0x1000 #define ERROR_TX_NORESP 0x2000 -static bool ps2_used = false; - -void ps2_reset(void) { - if (!ps2_used) { - return; - } - gpio_uninstall_isr_service(); -} - static void delay_us(uint32_t t) { common_hal_mcu_delay_us(t); } @@ -123,7 +114,6 @@ static void IRAM_ATTR ps2_interrupt_handler(void *self_in) { static void enable_interrupt(ps2io_ps2_obj_t *self) { // turn on falling edge interrupt - ps2_used = true; 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); @@ -238,7 +228,10 @@ void common_hal_ps2io_ps2_deinit(ps2io_ps2_obj_t *self) { if (common_hal_ps2io_ps2_deinited(self)) { return; } - gpio_uninstall_isr_service(); + // Remove only this object's handler. Uninstalling the GPIO ISR service + // would remove every other object's GPIO interrupt handler too. + disable_interrupt(self); + gpio_set_intr_type(self->clk_pin, GPIO_INTR_DISABLE); reset_pin_number(self->clk_pin); reset_pin_number(self->data_pin); self->clk_pin = GPIO_NUM_MAX; diff --git a/ports/espressif/common-hal/ps2io/Ps2.h b/ports/espressif/common-hal/ps2io/Ps2.h index a3586b59f6a..a51f334bb04 100644 --- a/ports/espressif/common-hal/ps2io/Ps2.h +++ b/ports/espressif/common-hal/ps2io/Ps2.h @@ -33,5 +33,3 @@ typedef struct { bool waiting_cmd_response; uint8_t cmd_response; } ps2io_ps2_obj_t; - -void ps2_reset(void); diff --git a/ports/espressif/common-hal/pulseio/PulseIn.c b/ports/espressif/common-hal/pulseio/PulseIn.c index 79d003a8a1e..0e3f12c935a 100644 --- a/ports/espressif/common-hal/pulseio/PulseIn.c +++ b/ports/espressif/common-hal/pulseio/PulseIn.c @@ -74,14 +74,14 @@ static bool _done_callback(rmt_channel_handle_t rx_chan, 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)); + self->buffer = (uint16_t *)m_malloc_without_collect(maxlen * sizeof(uint16_t)); if (self->buffer == NULL) { m_malloc_fail(maxlen * sizeof(uint16_t)); } // We add one to the maxlen version to ensure that two symbols at lease are // captured because we may skip the first portion of a symbol. self->raw_symbols_size = MIN(64, maxlen / 2 + 1) * sizeof(rmt_symbol_word_t); - self->raw_symbols = (rmt_symbol_word_t *)m_malloc(self->raw_symbols_size); + self->raw_symbols = (rmt_symbol_word_t *)m_malloc_without_collect(self->raw_symbols_size); if (self->raw_symbols == NULL) { m_free(self->buffer); m_malloc_fail(self->raw_symbols_size); @@ -120,6 +120,8 @@ void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t *self, const mcu rmt_rx_register_event_callbacks(self->channel, &rx_callback, self); rmt_enable(self->channel); rmt_receive(self->channel, self->raw_symbols, self->raw_symbols_size, &rx_config); + + claim_pin(pin); } bool common_hal_pulseio_pulsein_deinited(pulseio_pulsein_obj_t *self) { diff --git a/ports/espressif/common-hal/pulseio/PulseOut.c b/ports/espressif/common-hal/pulseio/PulseOut.c index 68cb64b5e60..007532c249d 100644 --- a/ports/espressif/common-hal/pulseio/PulseOut.c +++ b/ports/espressif/common-hal/pulseio/PulseOut.c @@ -18,6 +18,13 @@ void common_hal_pulseio_pulseout_construct(pulseio_pulseout_obj_t *self, uint32_t frequency, uint16_t duty_cycle) { + // Check the frequency here: IDF doesn't. It divides the RMT source clock + // (32 MHz or more) by the carrier frequency, so a frequency of 0 or above + // that clock divides by zero and hard faults. + if (duty_cycle != 0xffff) { + mp_arg_validate_int_range((mp_int_t)frequency, 1, 10000000, MP_QSTR_frequency); + } + // Reserve channel rmt_tx_channel_config_t config = { .gpio_num = pin->number, @@ -47,6 +54,9 @@ void common_hal_pulseio_pulseout_construct(pulseio_pulseout_obj_t *self, } rmt_enable(self->channel); + + self->pin = pin; + claim_pin(pin); } bool common_hal_pulseio_pulseout_deinited(pulseio_pulseout_obj_t *self) { @@ -61,6 +71,7 @@ void common_hal_pulseio_pulseout_deinit(pulseio_pulseout_obj_t *self) { rmt_del_encoder(self->encoder); rmt_del_channel(self->channel); self->channel = NULL; + reset_pin_number(self->pin->number); } void common_hal_pulseio_pulseout_send(pulseio_pulseout_obj_t *self, uint16_t *pulses, uint16_t length) { @@ -69,7 +80,7 @@ void common_hal_pulseio_pulseout_send(pulseio_pulseout_obj_t *self, uint16_t *pu // Circuitpython allows 16 bit pulse values, while ESP32 only allows 15 bits // Thus, we use entire items for one pulse, rather than switching inside each item for (size_t i = 0; i < length; i++) { - // Setting the RMT duration to 0 has undefined behavior, so avoid that pre-emptively. + // Setting the RMT duration to 0 has undefined behavior, so avoid that preemptively. if (pulses[i] == 0) { continue; } diff --git a/ports/espressif/common-hal/pulseio/PulseOut.h b/ports/espressif/common-hal/pulseio/PulseOut.h index 5dc470b67e0..8ae98a63639 100644 --- a/ports/espressif/common-hal/pulseio/PulseOut.h +++ b/ports/espressif/common-hal/pulseio/PulseOut.h @@ -15,4 +15,5 @@ typedef struct { mp_obj_base_t base; rmt_channel_handle_t channel; rmt_encoder_handle_t encoder; + const mcu_pin_obj_t *pin; } pulseio_pulseout_obj_t; diff --git a/ports/espressif/common-hal/pwmio/PWMOut.c b/ports/espressif/common-hal/pwmio/PWMOut.c index e3560df60b8..013e3ba5bf8 100644 --- a/ports/espressif/common-hal/pwmio/PWMOut.c +++ b/ports/espressif/common-hal/pwmio/PWMOut.c @@ -32,11 +32,16 @@ static uint32_t calculate_duty_cycle(uint32_t frequency) { return duty_bits; } +static void mark_deinit(pwmio_pwmout_obj_t *self) { + self->pin = NULL; +} + 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) { + mark_deinit(self); // check the frequency (avoid divide by zero below) if (frequency == 0) { @@ -110,7 +115,6 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t *self, } self->variable_frequency = variable_frequency; self->pin = pin; - self->deinited = false; self->duty_resolution = duty_bits; claim_pin(pin); @@ -120,12 +124,8 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t *self, return PWMOUT_OK; } -void common_hal_pwmio_pwmout_never_reset(pwmio_pwmout_obj_t *self) { - never_reset_pin_number(self->pin->number); -} - bool common_hal_pwmio_pwmout_deinited(pwmio_pwmout_obj_t *self) { - return self->deinited == true; + return self->pin == NULL; } void common_hal_pwmio_pwmout_deinit(pwmio_pwmout_obj_t *self) { @@ -154,7 +154,7 @@ void common_hal_pwmio_pwmout_deinit(pwmio_pwmout_obj_t *self) { varfreq_timers[self->tim_handle.timer_num] = false; } common_hal_reset_pin(self->pin); - self->deinited = true; + mark_deinit(self); } void common_hal_pwmio_pwmout_set_duty_cycle(pwmio_pwmout_obj_t *self, uint16_t duty) { diff --git a/ports/espressif/common-hal/pwmio/PWMOut.h b/ports/espressif/common-hal/pwmio/PWMOut.h index c573e729241..cbba2b3d7ea 100644 --- a/ports/espressif/common-hal/pwmio/PWMOut.h +++ b/ports/espressif/common-hal/pwmio/PWMOut.h @@ -16,5 +16,4 @@ typedef struct { const mcu_pin_obj_t *pin; uint8_t duty_resolution; bool variable_frequency : 1; - bool deinited : 1; } pwmio_pwmout_obj_t; diff --git a/ports/espressif/common-hal/qspibus/QSPIBus.c b/ports/espressif/common-hal/qspibus/QSPIBus.c new file mode 100644 index 00000000000..be089f8c907 --- /dev/null +++ b/ports/espressif/common-hal/qspibus/QSPIBus.c @@ -0,0 +1,585 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// SPDX-FileCopyrightText: Copyright (c) 2026 Przemyslaw Patrick Socha +// SPDX-License-Identifier: MIT + +#include "shared-bindings/qspibus/QSPIBus.h" + +#include "common-hal/microcontroller/Pin.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/util.h" + +#include "py/gc.h" +#include "py/runtime.h" + +#include "driver/gpio.h" +#include "esp_heap_caps.h" +#include "soc/soc_caps.h" +#include + +#define QSPI_OPCODE_WRITE_CMD (0x02U) +#define QSPI_OPCODE_WRITE_COLOR (0x32U) +#define LCD_CMD_RAMWR (0x2CU) +#define LCD_CMD_RAMWRC (0x3CU) +#define LCD_CMD_DISPOFF (0x28U) +#define LCD_CMD_SLPIN (0x10U) +#define QSPI_DMA_BUFFER_COUNT (2U) +#define QSPI_DMA_BUFFER_SIZE (16U * 1024U) +#define QSPI_COLOR_TIMEOUT_MS (1000U) +static void qspibus_release_dma_buffers(qspibus_qspibus_obj_t *self) { + for (size_t i = 0; i < QSPI_DMA_BUFFER_COUNT; i++) { + if (self->dma_buffer[i] != NULL) { + heap_caps_free(self->dma_buffer[i]); + self->dma_buffer[i] = NULL; + } + } + self->dma_buffer_size = 0; + self->active_buffer = 0; + self->inflight_transfers = 0; + self->transfer_in_progress = false; +} + +static bool qspibus_allocate_dma_buffers(qspibus_qspibus_obj_t *self) { + const size_t candidates[] = { + QSPI_DMA_BUFFER_SIZE, + QSPI_DMA_BUFFER_SIZE / 2, + QSPI_DMA_BUFFER_SIZE / 4, + }; + + for (size_t c = 0; c < MP_ARRAY_SIZE(candidates); c++) { + size_t size = candidates[c]; + bool ok = true; + for (size_t i = 0; i < QSPI_DMA_BUFFER_COUNT; i++) { + self->dma_buffer[i] = heap_caps_malloc(size, MALLOC_CAP_DMA | MALLOC_CAP_8BIT); + if (self->dma_buffer[i] == NULL) { + ok = false; + break; + } + } + if (ok) { + self->dma_buffer_size = size; + self->active_buffer = 0; + self->inflight_transfers = 0; + self->transfer_in_progress = false; + return true; + } + qspibus_release_dma_buffers(self); + } + return false; +} + +// Reset transfer bookkeeping after timeout/error. Drains any stale semaphore +// tokens that late ISR completions may have posted after the timeout expired. +static void qspibus_reset_transfer_state(qspibus_qspibus_obj_t *self) { + self->inflight_transfers = 0; + self->transfer_in_progress = false; + if (self->transfer_done_sem != NULL) { + while (xSemaphoreTake(self->transfer_done_sem, 0) == pdTRUE) { + } + } +} + +static bool qspibus_wait_one_transfer_done(qspibus_qspibus_obj_t *self, TickType_t timeout) { + if (self->inflight_transfers == 0) { + self->transfer_in_progress = false; + return true; + } + + if (xSemaphoreTake(self->transfer_done_sem, timeout) != pdTRUE) { + return false; + } + self->inflight_transfers--; + self->transfer_in_progress = (self->inflight_transfers > 0); + return true; +} + +static bool qspibus_wait_all_transfers_done(qspibus_qspibus_obj_t *self, TickType_t timeout) { + while (self->inflight_transfers > 0) { + if (!qspibus_wait_one_transfer_done(self, timeout)) { + return false; + } + } + return true; +} + +static void qspibus_send_command_bytes( + qspibus_qspibus_obj_t *self, + uint8_t command, + const uint8_t *data, + size_t len) { + + if (!self->bus_initialized) { + raise_deinited_error(); + } + if (self->inflight_transfers >= QSPI_DMA_BUFFER_COUNT) { + if (!qspibus_wait_one_transfer_done(self, pdMS_TO_TICKS(QSPI_COLOR_TIMEOUT_MS))) { + qspibus_reset_transfer_state(self); + mp_raise_OSError_msg(MP_ERROR_TEXT("Operation timed out")); + } + } + + uint32_t packed_cmd = ((uint32_t)QSPI_OPCODE_WRITE_CMD << 24) | ((uint32_t)command << 8); + esp_err_t err = esp_lcd_panel_io_tx_param(self->io_handle, packed_cmd, data, len); + if (err != ESP_OK) { + qspibus_reset_transfer_state(self); + mp_raise_OSError_msg_varg(MP_ERROR_TEXT("%q failure: %d"), MP_QSTR_QSPI, (int)err); + } +} + +static void qspibus_send_color_bytes( + qspibus_qspibus_obj_t *self, + uint8_t command, + const uint8_t *data, + size_t len) { + + if (!self->bus_initialized) { + raise_deinited_error(); + } + + if (len == 0) { + qspibus_send_command_bytes(self, command, NULL, 0); + return; + } + + // RAMWR must transition to RAMWRC for continued payload chunks. + uint8_t chunk_command = command; + const uint8_t *cursor = data; + size_t remaining = len; + + // Drain stale semaphore tokens that late ISR completions may have + // posted after a previous qspibus_reset_transfer_state(). Without + // this, a stale token could satisfy a future wait, causing the next + // transfer to skip its real DMA-done wait. + if (self->inflight_transfers == 0 && self->transfer_done_sem != NULL) { + while (xSemaphoreTake(self->transfer_done_sem, 0) == pdTRUE) { + } + } + + while (remaining > 0) { + // inflight_transfers is only modified in task context (never from ISR), + // so no atomic/critical section is needed. The ISR only signals the + // counting semaphore; all counter bookkeeping happens task-side. + if (self->inflight_transfers >= QSPI_DMA_BUFFER_COUNT) { + if (!qspibus_wait_one_transfer_done(self, pdMS_TO_TICKS(QSPI_COLOR_TIMEOUT_MS))) { + qspibus_reset_transfer_state(self); + mp_raise_OSError_msg(MP_ERROR_TEXT("Operation timed out")); + } + } + + size_t chunk = remaining; + if (chunk > self->dma_buffer_size) { + chunk = self->dma_buffer_size; + } + + uint8_t *buffer = self->dma_buffer[self->active_buffer]; + memcpy(buffer, cursor, chunk); + + uint32_t packed_cmd = ((uint32_t)QSPI_OPCODE_WRITE_COLOR << 24) | ((uint32_t)chunk_command << 8); + esp_err_t err = esp_lcd_panel_io_tx_color(self->io_handle, packed_cmd, buffer, chunk); + if (err != ESP_OK) { + qspibus_reset_transfer_state(self); + mp_raise_OSError_msg_varg(MP_ERROR_TEXT("%q failure: %d"), MP_QSTR_QSPI, (int)err); + } + + self->inflight_transfers++; + self->transfer_in_progress = true; + self->active_buffer = (self->active_buffer + 1) % QSPI_DMA_BUFFER_COUNT; + + if (chunk_command == LCD_CMD_RAMWR) { + chunk_command = LCD_CMD_RAMWRC; + } + + cursor += chunk; + remaining -= chunk; + } + + // Let DMA complete asynchronously. The next begin_transaction() will + // wait for all in-flight transfers, allowing fill_area() computation + // to overlap with DMA. The explicit wait is only needed for the + // Python write_data() API path where callers expect the transfer to + // be finished on return. +} + +static bool qspibus_is_color_payload_command(uint8_t command) { + return command == LCD_CMD_RAMWR || command == LCD_CMD_RAMWRC; +} + +static void qspibus_panel_sleep_best_effort(qspibus_qspibus_obj_t *self) { + if (!self->bus_initialized || self->io_handle == NULL) { + return; + } + + if (!qspibus_wait_all_transfers_done(self, pdMS_TO_TICKS(QSPI_COLOR_TIMEOUT_MS))) { + qspibus_reset_transfer_state(self); + } + + // If a command is buffered, flush it first so the panel state machine + // doesn't get a truncated transaction before sleep. + if (self->has_pending_command) { + uint32_t pending = ((uint32_t)QSPI_OPCODE_WRITE_CMD << 24) | ((uint32_t)self->pending_command << 8); + (void)esp_lcd_panel_io_tx_param(self->io_handle, pending, NULL, 0); + self->has_pending_command = false; + } + + uint32_t disp_off = ((uint32_t)QSPI_OPCODE_WRITE_CMD << 24) | ((uint32_t)LCD_CMD_DISPOFF << 8); + (void)esp_lcd_panel_io_tx_param(self->io_handle, disp_off, NULL, 0); + vTaskDelay(pdMS_TO_TICKS(20)); + + uint32_t sleep_in = ((uint32_t)QSPI_OPCODE_WRITE_CMD << 24) | ((uint32_t)LCD_CMD_SLPIN << 8); + (void)esp_lcd_panel_io_tx_param(self->io_handle, sleep_in, NULL, 0); + vTaskDelay(pdMS_TO_TICKS(120)); +} + +static bool IRAM_ATTR qspibus_on_color_trans_done( + esp_lcd_panel_io_handle_t io_handle, + esp_lcd_panel_io_event_data_t *event_data, + void *user_ctx) { + (void)io_handle; + (void)event_data; + + qspibus_qspibus_obj_t *self = (qspibus_qspibus_obj_t *)user_ctx; + if (self->transfer_done_sem == NULL) { + return false; + } + BaseType_t x_higher_priority_task_woken = pdFALSE; + + xSemaphoreGiveFromISR(self->transfer_done_sem, &x_higher_priority_task_woken); + return x_higher_priority_task_woken == pdTRUE; +} + +void common_hal_qspibus_qspibus_construct( + qspibus_qspibus_obj_t *self, + const mcu_pin_obj_t *clock, + const mcu_pin_obj_t *data0, + const mcu_pin_obj_t *data1, + const mcu_pin_obj_t *data2, + const mcu_pin_obj_t *data3, + const mcu_pin_obj_t *cs, + const mcu_pin_obj_t *dcx, + const mcu_pin_obj_t *reset, + uint32_t frequency) { + + self->io_handle = NULL; + self->host_id = SPI2_HOST; + self->clock_pin = clock->number; + self->data0_pin = data0->number; + self->data1_pin = data1->number; + self->data2_pin = data2->number; + self->data3_pin = data3->number; + self->cs_pin = cs->number; + self->dcx_pin = (dcx != NULL) ? dcx->number : -1; + self->reset_pin = (reset != NULL) ? reset->number : -1; + self->frequency = frequency; + self->bus_initialized = false; + self->in_transaction = false; + self->has_pending_command = false; + self->pending_command = 0; + self->transfer_in_progress = false; + self->active_buffer = 0; + self->inflight_transfers = 0; + self->dma_buffer_size = 0; + self->dma_buffer[0] = NULL; + self->dma_buffer[1] = NULL; + self->transfer_done_sem = NULL; + + self->transfer_done_sem = xSemaphoreCreateCounting(QSPI_DMA_BUFFER_COUNT, 0); + if (self->transfer_done_sem == NULL) { + mp_raise_msg(&mp_type_MemoryError, MP_ERROR_TEXT("ESP-IDF memory allocation failed")); + } + + if (!qspibus_allocate_dma_buffers(self)) { + common_hal_qspibus_qspibus_deinit(self); + mp_raise_msg(&mp_type_MemoryError, MP_ERROR_TEXT("Could not allocate DMA capable buffer")); + } + + const spi_bus_config_t bus_config = { + .sclk_io_num = self->clock_pin, + .mosi_io_num = self->data0_pin, + .miso_io_num = self->data1_pin, + .quadwp_io_num = self->data2_pin, + .quadhd_io_num = self->data3_pin, + .max_transfer_sz = self->dma_buffer_size, + .flags = SPICOMMON_BUSFLAG_MASTER | SPICOMMON_BUSFLAG_GPIO_PINS, + }; + + esp_err_t err = spi_bus_initialize(self->host_id, &bus_config, SPI_DMA_CH_AUTO); + if (err != ESP_OK) { + common_hal_qspibus_qspibus_deinit(self); + mp_raise_ValueError_varg(MP_ERROR_TEXT("%q in use"), MP_QSTR_SPI); + } + + // Mark bus as initialized so deinit knows to call spi_bus_free(). + self->bus_initialized = true; + + const esp_lcd_panel_io_spi_config_t io_config = { + .cs_gpio_num = self->cs_pin, + .dc_gpio_num = -1, + .spi_mode = 0, + .pclk_hz = self->frequency, + .trans_queue_depth = QSPI_DMA_BUFFER_COUNT, + .on_color_trans_done = qspibus_on_color_trans_done, + .user_ctx = self, + .lcd_cmd_bits = 32, + .lcd_param_bits = 8, + .flags = { + .quad_mode = 1, + }, + }; + + err = esp_lcd_new_panel_io_spi((esp_lcd_spi_bus_handle_t)self->host_id, &io_config, &self->io_handle); + if (err != ESP_OK) { + common_hal_qspibus_qspibus_deinit(self); + mp_raise_OSError_msg_varg(MP_ERROR_TEXT("%q failure: %d"), MP_QSTR_QSPI, (int)err); + } + + // Claim the bus pins. The display (e.g. board.DISPLAY) may outlive the VM; + // deinit() releases them via reset_pin_number(). + claim_pin(clock); + claim_pin(data0); + claim_pin(data1); + claim_pin(data2); + claim_pin(data3); + claim_pin(cs); + if (dcx != NULL) { + claim_pin(dcx); + gpio_set_direction((gpio_num_t)self->dcx_pin, GPIO_MODE_OUTPUT); + gpio_set_level((gpio_num_t)self->dcx_pin, 1); + } + + if (reset != NULL) { + claim_pin(reset); + + gpio_set_direction((gpio_num_t)self->reset_pin, GPIO_MODE_OUTPUT); + gpio_set_level((gpio_num_t)self->reset_pin, 0); + vTaskDelay(pdMS_TO_TICKS(10)); + gpio_set_level((gpio_num_t)self->reset_pin, 1); + vTaskDelay(pdMS_TO_TICKS(120)); + } +} + +void common_hal_qspibus_qspibus_deinit(qspibus_qspibus_obj_t *self) { + if (self->bus_initialized) { + qspibus_panel_sleep_best_effort(self); + self->in_transaction = false; + + if (self->io_handle != NULL) { + esp_lcd_panel_io_del(self->io_handle); + self->io_handle = NULL; + } + + spi_bus_free(self->host_id); + self->bus_initialized = false; + } + + if (self->transfer_done_sem != NULL) { + // Set NULL before delete so late ISR callbacks (if any) see NULL and skip. + SemaphoreHandle_t sem = self->transfer_done_sem; + self->transfer_done_sem = NULL; + vSemaphoreDelete(sem); + } + + qspibus_release_dma_buffers(self); + + reset_pin_number(self->clock_pin); + reset_pin_number(self->data0_pin); + reset_pin_number(self->data1_pin); + reset_pin_number(self->data2_pin); + reset_pin_number(self->data3_pin); + reset_pin_number(self->cs_pin); + if (self->dcx_pin >= 0) { + reset_pin_number(self->dcx_pin); + } + if (self->reset_pin >= 0) { + reset_pin_number(self->reset_pin); + } + + self->bus_initialized = false; + self->in_transaction = false; + self->has_pending_command = false; + self->pending_command = 0; + self->transfer_in_progress = false; + self->inflight_transfers = 0; + + // A failed construct calls deinit() and leaves the bus in its display bus slot, + // so release_displays() can call deinit() again later. Don't reset the pins + // twice: by then they may belong to something else. + self->clock_pin = -1; + self->data0_pin = -1; + self->data1_pin = -1; + self->data2_pin = -1; + self->data3_pin = -1; + self->cs_pin = -1; + self->dcx_pin = -1; + self->reset_pin = -1; +} + +bool common_hal_qspibus_qspibus_deinited(qspibus_qspibus_obj_t *self) { + return !self->bus_initialized; +} + +void common_hal_qspibus_qspibus_write_command( + qspibus_qspibus_obj_t *self, + uint8_t command) { + if (!self->bus_initialized) { + raise_deinited_error(); + } + if (self->in_transaction) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Internal error")); + } + + // If caller stages command-only operations repeatedly, flush the previous + // pending command as no-data before replacing it. + if (self->has_pending_command) { + qspibus_send_command_bytes(self, self->pending_command, NULL, 0); + } + + self->pending_command = command; + self->has_pending_command = true; +} + +void common_hal_qspibus_qspibus_write_data( + qspibus_qspibus_obj_t *self, + const uint8_t *data, + size_t len) { + if (!self->bus_initialized) { + raise_deinited_error(); + } + if (self->in_transaction) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Internal error")); + } + if (len == 0) { + if (self->has_pending_command) { + qspibus_send_command_bytes(self, self->pending_command, NULL, 0); + self->has_pending_command = false; + } + return; + } + if (!self->has_pending_command) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Internal error")); + } + + if (qspibus_is_color_payload_command(self->pending_command)) { + qspibus_send_color_bytes(self, self->pending_command, data, len); + // Python API: wait for DMA to finish so callers see the transfer as + // complete on return. The internal displayio path skips this wait + // to allow fill_area/DMA overlap. + if (!qspibus_wait_all_transfers_done(self, pdMS_TO_TICKS(QSPI_COLOR_TIMEOUT_MS))) { + qspibus_reset_transfer_state(self); + mp_raise_OSError_msg(MP_ERROR_TEXT("Operation timed out")); + } + } else { + qspibus_send_command_bytes(self, self->pending_command, data, len); + } + self->has_pending_command = false; +} + +bool common_hal_qspibus_qspibus_reset(mp_obj_t obj) { + qspibus_qspibus_obj_t *self = MP_OBJ_TO_PTR(obj); + if (!self->bus_initialized || self->reset_pin < 0) { + return false; + } + + gpio_set_level((gpio_num_t)self->reset_pin, 0); + vTaskDelay(pdMS_TO_TICKS(10)); + gpio_set_level((gpio_num_t)self->reset_pin, 1); + vTaskDelay(pdMS_TO_TICKS(120)); + return true; +} + +bool common_hal_qspibus_qspibus_bus_free(mp_obj_t obj) { + qspibus_qspibus_obj_t *self = MP_OBJ_TO_PTR(obj); + return self->bus_initialized && !self->in_transaction && !self->transfer_in_progress && !self->has_pending_command; +} + +bool common_hal_qspibus_qspibus_begin_transaction(mp_obj_t obj) { + qspibus_qspibus_obj_t *self = MP_OBJ_TO_PTR(obj); + if (!self->bus_initialized || self->in_transaction || self->has_pending_command) { + return false; + } + // Wait for any in-flight DMA to complete before starting a new + // transaction. This replaces the old non-blocking bus_free() check + // and enables fill_area()/DMA overlap: the CPU fills the next + // subrectangle while the previous DMA runs, and this wait only + // blocks when we actually need the bus for the next send. + if (self->transfer_in_progress) { + if (!qspibus_wait_all_transfers_done(self, pdMS_TO_TICKS(QSPI_COLOR_TIMEOUT_MS))) { + qspibus_reset_transfer_state(self); + return false; + } + } + self->in_transaction = true; + return true; +} + +void common_hal_qspibus_qspibus_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) { + qspibus_qspibus_obj_t *self = MP_OBJ_TO_PTR(obj); + (void)chip_select; + if (!self->bus_initialized) { + raise_deinited_error(); + } + if (!self->in_transaction) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Internal error")); + } + + if (data_type == DISPLAY_COMMAND) { + for (uint32_t i = 0; i < data_length; i++) { + if (self->has_pending_command) { + qspibus_send_command_bytes(self, self->pending_command, NULL, 0); + } + self->pending_command = data[i]; + self->has_pending_command = true; + } + return; + } + + if (!self->has_pending_command) { + if (data_length == 0) { + // Zero-length data write after a no-data command is benign. + return; + } + mp_raise_RuntimeError(MP_ERROR_TEXT("Internal error")); + } + + if (data_length == 0) { + qspibus_send_command_bytes(self, self->pending_command, NULL, 0); + self->has_pending_command = false; + return; + } + + if (qspibus_is_color_payload_command(self->pending_command)) { + qspibus_send_color_bytes(self, self->pending_command, data, data_length); + } else { + qspibus_send_command_bytes(self, self->pending_command, data, data_length); + } + self->has_pending_command = false; +} + +void common_hal_qspibus_qspibus_end_transaction(mp_obj_t obj) { + qspibus_qspibus_obj_t *self = MP_OBJ_TO_PTR(obj); + if (!self->bus_initialized) { + return; + } + if (self->has_pending_command) { + qspibus_send_command_bytes(self, self->pending_command, NULL, 0); + self->has_pending_command = false; + } + self->in_transaction = false; +} + +void common_hal_qspibus_qspibus_flush(mp_obj_t obj) { + qspibus_qspibus_obj_t *self = MP_OBJ_TO_PTR(obj); + if (!self->bus_initialized) { + return; + } + if (!qspibus_wait_all_transfers_done(self, pdMS_TO_TICKS(QSPI_COLOR_TIMEOUT_MS))) { + qspibus_reset_transfer_state(self); + } +} + +void common_hal_qspibus_qspibus_collect_ptrs(mp_obj_t obj) { + (void)obj; +} diff --git a/ports/espressif/common-hal/qspibus/QSPIBus.h b/ports/espressif/common-hal/qspibus/QSPIBus.h new file mode 100644 index 00000000000..eaaa971a79c --- /dev/null +++ b/ports/espressif/common-hal/qspibus/QSPIBus.h @@ -0,0 +1,50 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// SPDX-FileCopyrightText: Copyright (c) 2026 Przemyslaw Patrick Socha +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include +#include + +#include "py/obj.h" + +#include "esp-idf/components/esp_lcd/include/esp_lcd_panel_io.h" +#include "driver/spi_master.h" +#include "freertos/FreeRTOS.h" +#include "freertos/semphr.h" + +typedef struct { + mp_obj_base_t base; + + // ESP LCD panel IO handle used for QSPI transactions. + esp_lcd_panel_io_handle_t io_handle; + + // SPI host (SPI2_HOST on ESP32-S3). + spi_host_device_t host_id; + + // Claimed GPIO numbers. + int8_t clock_pin; + int8_t data0_pin; + int8_t data1_pin; + int8_t data2_pin; + int8_t data3_pin; + int8_t cs_pin; + int8_t dcx_pin; // -1 when optional DCX line is not provided. + int8_t reset_pin; // -1 when reset line is not provided. + + uint32_t frequency; + bool bus_initialized; + bool in_transaction; + bool has_pending_command; + uint8_t pending_command; + bool transfer_in_progress; + uint8_t active_buffer; + uint8_t inflight_transfers; + size_t dma_buffer_size; + uint8_t *dma_buffer[2]; + + // Signaled from ISR when panel IO transfer completes. + SemaphoreHandle_t transfer_done_sem; +} qspibus_qspibus_obj_t; diff --git a/ports/espressif/common-hal/qspibus/__init__.c b/ports/espressif/common-hal/qspibus/__init__.c new file mode 100644 index 00000000000..2f763b218cb --- /dev/null +++ b/ports/espressif/common-hal/qspibus/__init__.c @@ -0,0 +1,3 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// SPDX-FileCopyrightText: Copyright (c) 2026 Przemyslaw Patrick Socha +// SPDX-License-Identifier: MIT diff --git a/ports/espressif/common-hal/qspibus/__init__.h b/ports/espressif/common-hal/qspibus/__init__.h new file mode 100644 index 00000000000..2f763b218cb --- /dev/null +++ b/ports/espressif/common-hal/qspibus/__init__.h @@ -0,0 +1,3 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// SPDX-FileCopyrightText: Copyright (c) 2026 Przemyslaw Patrick Socha +// SPDX-License-Identifier: MIT diff --git a/ports/espressif/common-hal/rclcpy/Node.c b/ports/espressif/common-hal/rclcpy/Node.c new file mode 100644 index 00000000000..f68daa44fc3 --- /dev/null +++ b/ports/espressif/common-hal/rclcpy/Node.c @@ -0,0 +1,47 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Lucian Copeland +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/rclcpy/Node.h" +#include "shared-bindings/rclcpy/__init__.h" + +#include "esp_log.h" + +void common_hal_rclcpy_node_construct(rclcpy_node_obj_t *self, + const char *node_name, const char *node_namespace) { + + rclc_node_init_default(&self->rcl_node, node_name, node_namespace, &rclcpy_default_context.rcl_support); + if (!rcl_node_is_valid(&self->rcl_node)) { + mp_raise_RuntimeError(MP_ERROR_TEXT("ROS node failed to initialize")); + } + self->deinited = false; +} + +bool common_hal_rclcpy_node_deinited(rclcpy_node_obj_t *self) { + return self->deinited; +} + +void common_hal_rclcpy_node_deinit(rclcpy_node_obj_t *self) { + if (common_hal_rclcpy_node_deinited(self)) { + return; + } + // Clean up Micro-ROS object + rcl_ret_t ret = rcl_node_fini(&self->rcl_node); + if (ret != RCL_RET_OK) { + // TODO: node_fini returns a fail here, but doesn't impede microros + // from restarting. Debug left for future investigation. + ESP_LOGW("RCLCPY", "Node cleanup error: %d", ret); + // rclcpy_default_context.critical_fail=RCLCPY_NODE_FAIL; + } + self->deinited = true; +} + +const char *common_hal_rclcpy_node_get_name(rclcpy_node_obj_t *self) { + return rcl_node_get_name(&self->rcl_node); +} + +const char *common_hal_rclcpy_node_get_namespace(rclcpy_node_obj_t *self) { + return rcl_node_get_namespace(&self->rcl_node); +} diff --git a/ports/espressif/common-hal/rclcpy/Node.h b/ports/espressif/common-hal/rclcpy/Node.h new file mode 100644 index 00000000000..c019a654e5a --- /dev/null +++ b/ports/espressif/common-hal/rclcpy/Node.h @@ -0,0 +1,23 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Lucian Copeland +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" +#include "py/runtime.h" + +#include +#include +#include +#include +#include + + +typedef struct { + mp_obj_base_t base; + bool deinited; + rcl_node_t rcl_node; +} rclcpy_node_obj_t; diff --git a/ports/espressif/common-hal/rclcpy/Publisher.c b/ports/espressif/common-hal/rclcpy/Publisher.c new file mode 100644 index 00000000000..81df154687a --- /dev/null +++ b/ports/espressif/common-hal/rclcpy/Publisher.c @@ -0,0 +1,64 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Lucian Copeland +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/rclcpy/Publisher.h" + +#include "esp_log.h" + +void common_hal_rclcpy_publisher_construct(rclcpy_publisher_obj_t *self, rclcpy_node_obj_t *node, + const char *topic_name) { + + // Create Int32 type object + // TODO: support other message types through class imports + const rosidl_message_type_support_t *type_support = ROSIDL_GET_MSG_TYPE_SUPPORT(std_msgs, msg, Int32); + + // Creates a reliable Int32 publisher + rcl_ret_t rc = rclc_publisher_init_default( + &self->rcl_publisher, &node->rcl_node, + type_support, topic_name); + if (RCL_RET_OK != rc) { + mp_raise_RuntimeError(MP_ERROR_TEXT("ROS topic failed to initialize")); + } + + self->node = node; +} + +bool common_hal_rclcpy_publisher_deinited(rclcpy_publisher_obj_t *self) { + return self->node == NULL; +} + +void common_hal_rclcpy_publisher_deinit(rclcpy_publisher_obj_t *self) { + if (common_hal_rclcpy_publisher_deinited(self)) { + return; + } + // Clean up Micro-ROS object + rcl_ret_t ret = rcl_publisher_fini(&self->rcl_publisher, &self->node->rcl_node); + if (ret != RCL_RET_OK) { + // TODO: publisher_fini returns a fail here, but doesn't impede microros + // from restarting. Debug left for future investigation. + ESP_LOGW("RCLCPY", "Publisher cleanup error: %d", ret); + // rclcpy_default_context.critical_fail=RCLCPY_PUB_FAIL; + } + self->node = NULL; +} + +void common_hal_rclcpy_publisher_publish_int32(rclcpy_publisher_obj_t *self, int32_t data) { + // Int32 message object + std_msgs__msg__Int32 msg; + + // Set message value + msg.data = data; + + // Publish message + rcl_ret_t rc = rcl_publish(&self->rcl_publisher, &msg, NULL); + if (RCL_RET_OK != rc) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Could not publish to ROS topic")); + } +} + +const char *common_hal_rclcpy_publisher_get_topic_name(rclcpy_publisher_obj_t *self) { + return rcl_publisher_get_topic_name(&self->rcl_publisher); +} diff --git a/ports/espressif/common-hal/rclcpy/Publisher.h b/ports/espressif/common-hal/rclcpy/Publisher.h new file mode 100644 index 00000000000..fdc45293cd2 --- /dev/null +++ b/ports/espressif/common-hal/rclcpy/Publisher.h @@ -0,0 +1,26 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Lucian Copeland +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +#include "common-hal/rclcpy/Node.h" +#include "common-hal/rclcpy/__init__.h" + +#include +#include +#include +#include +#include +#include + + +typedef struct { + mp_obj_base_t base; + rclcpy_node_obj_t *node; + rcl_publisher_t rcl_publisher; +} rclcpy_publisher_obj_t; diff --git a/ports/espressif/common-hal/rclcpy/__init__.c b/ports/espressif/common-hal/rclcpy/__init__.c new file mode 100644 index 00000000000..e0e6fd8b4f4 --- /dev/null +++ b/ports/espressif/common-hal/rclcpy/__init__.c @@ -0,0 +1,122 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Lucian Copeland +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/rclcpy/__init__.h" + +#include "esp_log.h" + +#define RCLCPY_SUPPORT_FAIL 1 +#define RCLCPY_OPTIONS_FAIL 2 + +rclcpy_context_t rclcpy_default_context = { + .initialized = false, + .critical_fail = 0, +}; + +static void *microros_allocate(size_t size, void *state) { + (void)state; + return m_malloc(size); +} + +static void microros_deallocate(void *pointer, void *state) { + (void)state; + m_free(pointer); +} + +static void *microros_reallocate(void *pointer, size_t size, void *state) { + (void)state; + return m_realloc(pointer, size); +} + +static void *microros_zero_allocate(size_t number_of_elements, size_t size_of_element, void *state) { + (void)state; + size_t total_size = number_of_elements * size_of_element; + void *ptr = m_malloc(total_size); + if (ptr != NULL) { + memset(ptr, 0, total_size); + } + return ptr; +} + +void rclcpy_reset(void) { + if (rclcpy_default_context.initialized) { + // Clean up micro-ROS objects + rcl_ret_t ret = rclc_support_fini(&rclcpy_default_context.rcl_support); + if (ret != RCL_RET_OK) { + // ESP_LOGW("RCLCPY", "Support cleanup error: %d", ret); + rclcpy_default_context.critical_fail = RCLCPY_SUPPORT_FAIL; + } + ret = rcl_init_options_fini(&rclcpy_default_context.init_options); + if (ret != RCL_RET_OK) { + // ESP_LOGW("RCLCPY", "Init options cleanup error: %d", ret); + rclcpy_default_context.critical_fail = RCLCPY_OPTIONS_FAIL; + } + + // Reset context state + memset(&rclcpy_default_context, 0, sizeof(rclcpy_default_context)); + rclcpy_default_context.initialized = false; + } +} + +void common_hal_rclcpy_init(const char *agent_ip, const char *agent_port, int16_t domain_id) { + if (rclcpy_default_context.critical_fail != 0) { + mp_raise_RuntimeError_varg(MP_ERROR_TEXT("Critical ROS failure during soft reboot, reset required: %d"), rclcpy_default_context.critical_fail); + } + + // Set up circuitpython-friendly allocator + rcl_allocator_t custom_allocator = rcutils_get_zero_initialized_allocator(); + custom_allocator.allocate = microros_allocate; + custom_allocator.deallocate = microros_deallocate; + custom_allocator.reallocate = microros_reallocate; + custom_allocator.zero_allocate = microros_zero_allocate; + if (!rcutils_set_default_allocator(&custom_allocator)) { + mp_raise_RuntimeError(MP_ERROR_TEXT("ROS memory allocator failure")); + } + rclcpy_default_context.rcl_allocator = custom_allocator; + + rcl_ret_t ret; + + // Micro-ROS options initialization + rclcpy_default_context.init_options = rcl_get_zero_initialized_init_options(); + ret = rcl_init_options_init(&rclcpy_default_context.init_options, rclcpy_default_context.rcl_allocator); + if (ret != RCL_RET_OK) { + mp_raise_RuntimeError(MP_ERROR_TEXT("ROS internal setup failure")); + } + if (domain_id < 0) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Invalid ROS domain ID")); + } + ret = rcl_init_options_set_domain_id(&rclcpy_default_context.init_options, domain_id); + if (ret != RCL_RET_OK) { + mp_raise_RuntimeError(MP_ERROR_TEXT("ROS internal setup failure")); + } + + // Set up Micro-ROS Agent + rclcpy_default_context.rmw_options = rcl_init_options_get_rmw_init_options(&rclcpy_default_context.init_options); + ret = rmw_uros_options_set_udp_address(agent_ip, agent_port, rclcpy_default_context.rmw_options); + if (ret != RCL_RET_OK) { + mp_raise_RuntimeError(MP_ERROR_TEXT("ROS internal setup failure")); + } + + // Final support object init requires a connected agent + ret = rclc_support_init_with_options(&rclcpy_default_context.rcl_support, + 0, + NULL, + &rclcpy_default_context.init_options, + &rclcpy_default_context.rcl_allocator); + if (ret != RCL_RET_OK) { + mp_raise_RuntimeError(MP_ERROR_TEXT("ROS failed to initialize. Is agent connected?")); + } else { + rclcpy_default_context.initialized = true; + } +} + +rclcpy_context_t *common_hal_rclcpy_get_default_context(void) { + return &rclcpy_default_context; +} + +bool common_hal_rclcpy_default_context_is_initialized(void) { + return rclcpy_default_context.initialized; +} diff --git a/ports/espressif/common-hal/rclcpy/__init__.h b/ports/espressif/common-hal/rclcpy/__init__.h new file mode 100644 index 00000000000..f3ebd4787e7 --- /dev/null +++ b/ports/espressif/common-hal/rclcpy/__init__.h @@ -0,0 +1,30 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Lucian Copeland +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" +#include "py/runtime.h" + +#include +#include +#include +#include +#include +#include + + +typedef struct { + bool initialized; + uint8_t critical_fail; + rcl_allocator_t rcl_allocator; + rclc_support_t rcl_support; + rcl_init_options_t init_options; + rmw_init_options_t *rmw_options; +} rclcpy_context_t; + +extern rclcpy_context_t rclcpy_default_context; +void rclcpy_reset(void); diff --git a/ports/espressif/common-hal/rotaryio/IncrementalEncoder.c b/ports/espressif/common-hal/rotaryio/IncrementalEncoder.c index ba8b70221b7..f65c7fdd9f1 100644 --- a/ports/espressif/common-hal/rotaryio/IncrementalEncoder.c +++ b/ports/espressif/common-hal/rotaryio/IncrementalEncoder.c @@ -21,6 +21,10 @@ void common_hal_rotaryio_incrementalencoder_construct(rotaryio_incrementalencode // // These routines also implicitly configure the weak internal pull-ups, as expected // in CircuitPython. + + // Ensure object starts in its deinit state. + common_hal_rotaryio_incrementalencoder_mark_deinit(self); + pcnt_unit_config_t unit_config = { // Set counter limit .low_limit = INT16_MIN, @@ -87,6 +91,10 @@ void common_hal_rotaryio_incrementalencoder_deinit(rotaryio_incrementalencoder_o pcnt_del_channel(self->channel_a); pcnt_del_channel(self->channel_b); pcnt_del_unit(self->unit); + common_hal_rotaryio_incrementalencoder_mark_deinit(self); +} + +void common_hal_rotaryio_incrementalencoder_mark_deinit(rotaryio_incrementalencoder_obj_t *self) { self->unit = NULL; } diff --git a/ports/espressif/common-hal/rtc/RTC.h b/ports/espressif/common-hal/rtc/RTC.h index 18625763562..d597327fd23 100644 --- a/ports/espressif/common-hal/rtc/RTC.h +++ b/ports/espressif/common-hal/rtc/RTC.h @@ -7,5 +7,4 @@ #pragma once extern void rtc_init(void); -extern void rtc_reset(void); extern void common_hal_rtc_init(void); diff --git a/ports/espressif/common-hal/sdioio/SDCard.c b/ports/espressif/common-hal/sdioio/SDCard.c index 6fd27c28945..9251841199e 100644 --- a/ports/espressif/common-hal/sdioio/SDCard.c +++ b/ports/espressif/common-hal/sdioio/SDCard.c @@ -8,8 +8,12 @@ #include "esp_err.h" #include "driver/sdmmc_host.h" +#ifndef CONFIG_SOC_SDMMC_USE_GPIO_MATRIX +#include "soc/sdmmc_pins.h" +#endif #include "ports/espressif/esp-idf/components/sdmmc/include/sdmmc_cmd.h" +#include "extmod/vfs.h" #include "shared-bindings/microcontroller/Pin.h" #include "shared-bindings/util.h" #include "shared-bindings/sdioio/SDCard.h" @@ -20,7 +24,6 @@ static const char *TAG = "SDCard.c"; static bool slot_in_use[2]; -static bool never_reset_sdio[2] = { false, false }; static void common_hal_sdioio_sdcard_check_for_deinit(sdioio_sdcard_obj_t *self) { if (common_hal_sdioio_sdcard_deinited(self)) { @@ -33,20 +36,28 @@ static int check_pins(const mcu_pin_obj_t *clock, const mcu_pin_obj_t *command, // ESP32-S3 and P4 can use any pin for any SDMMC func in either slot // Default to SLOT_1 for SD cards ESP_LOGI(TAG, "Using chip with CONFIG_SOC_SDMMC_USE_GPIO_MATRIX"); - if (!slot_in_use[1]) { + if (!slot_in_use[1] + #ifdef CONFIG_ESP_HOSTED_SDIO_HOST_INTERFACE + && CONFIG_ESP_HOSTED_SDIO_SLOT != 1 + #endif + ) { return SDMMC_HOST_SLOT_1; - } else if (!slot_in_use[0]) { + } else if (!slot_in_use[0] + #ifdef CONFIG_ESP_HOSTED_SDIO_HOST_INTERFACE + && CONFIG_ESP_HOSTED_SDIO_SLOT != 0 + #endif + ) { return SDMMC_HOST_SLOT_0; } #else - if (command->number == GPIO_NUM_11 && clock->number == GPIO_NUM_6 && data[0]->number == GPIO_NUM_7) { + if (command->number == SDMMC_SLOT0_IOMUX_PIN_NUM_CMD && clock->number == SDMMC_SLOT0_IOMUX_PIN_NUM_CLK && data[0]->number == SDMMC_SLOT0_IOMUX_PIN_NUM_D0) { // Might be slot 0 - if (num_data == 1 || (num_data == 4 && data[1]->number == GPIO_NUM_8 && data[2]->number == GPIO_NUM_9 && data[3]->number == GPIO_NUM_10)) { + if (num_data == 1 || (num_data == 4 && data[1]->number == SDMMC_SLOT0_IOMUX_PIN_NUM_D1 && data[2]->number == SDMMC_SLOT0_IOMUX_PIN_NUM_D2 && data[3]->number == SDMMC_SLOT0_IOMUX_PIN_NUM_D3)) { return SDMMC_HOST_SLOT_0; } - } else if (command->number == GPIO_NUM_15 && clock->number == GPIO_NUM_14 && data[0]->number == 2) { + } else if (command->number == SDMMC_SLOT1_IOMUX_PIN_NUM_CMD && clock->number == SDMMC_SLOT1_IOMUX_PIN_NUM_CLK && data[0]->number == SDMMC_SLOT1_IOMUX_PIN_NUM_D0) { // Might be slot 1 - if (num_data == 1 || (num_data == 4 && data[1]->number == GPIO_NUM_4 && data[2]->number == GPIO_NUM_12 && data[3]->number == GPIO_NUM_13)) { + if (num_data == 1 || (num_data == 4 && data[1]->number == SDMMC_SLOT1_IOMUX_PIN_NUM_D1 && data[2]->number == SDMMC_SLOT1_IOMUX_PIN_NUM_D2 && data[3]->number == SDMMC_SLOT1_IOMUX_PIN_NUM_D3)) { return SDMMC_HOST_SLOT_1; } } @@ -62,9 +73,16 @@ uint8_t get_slot_index(sdioio_sdcard_obj_t *self) { } } +static void mark_deinit(sdioio_sdcard_obj_t *self) { + self->command = COMMON_HAL_MCU_NO_PIN; +} + 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, const mcu_pin_obj_t **data, uint32_t frequency) { + // A zeroed command pin is GPIO0, not NO_PIN. + mark_deinit(self); + if (num_data != 4 && num_data != 1) { mp_raise_ValueError_varg(MP_ERROR_TEXT("Number of data_pins must be %d or %d, not %d"), 1, 4, num_data); } @@ -83,6 +101,7 @@ void common_hal_sdioio_sdcard_construct(sdioio_sdcard_obj_t *self, esp_err_t err = ESP_OK; sdmmc_host_t host = SDMMC_HOST_DEFAULT(); + host.slot = sd_slot; host.max_freq_khz = frequency / 1000; sdmmc_slot_config_t slot_config = SDMMC_SLOT_CONFIG_DEFAULT(); @@ -90,7 +109,6 @@ void common_hal_sdioio_sdcard_construct(sdioio_sdcard_obj_t *self, slot_config.clk = clock->number; self->clock = clock->number; slot_config.cmd = command->number; - self->command = command->number; slot_config.d0 = data[0]->number; self->data[0] = data[0]->number; if (num_data == 4) { @@ -109,25 +127,28 @@ void common_hal_sdioio_sdcard_construct(sdioio_sdcard_obj_t *self, if (!slot_in_use[0] && !slot_in_use[1]) { err = sdmmc_host_init(); if (err != ESP_OK) { - mp_raise_OSError_msg_varg(MP_ERROR_TEXT("SDIO Init Error %x"), err); + mp_raise_OSError_msg_varg(MP_ERROR_TEXT("SDIO Init Error 0x%02x"), err); } } err = sdmmc_host_init_slot(sd_slot, &slot_config); if (err != ESP_OK) { ESP_LOGW(TAG, "Failed to initialize SDMMC slot: %x", err); - mp_raise_OSError_msg_varg(MP_ERROR_TEXT("SDIO Init Error %x"), err); + if (!slot_in_use[0] && !slot_in_use[1]) { + sdmmc_host_deinit(); + } + mp_raise_OSError_msg_varg(MP_ERROR_TEXT("SDIO Init Error 0x%02x"), err); } // sdmmc_card_t card; // self->card = malloc(sizeof(sdmmc_card_t)); err = sdmmc_card_init(&host, &self->card); if (err != ESP_OK) { ESP_LOGW(TAG, "Failed to initialize SDMMC card: %x", err); - mp_raise_OSError_msg_varg(MP_ERROR_TEXT("SDIO Init Error %x"), err); + sdmmc_host_deinit_slot(sd_slot); + mp_raise_OSError_msg_varg(MP_ERROR_TEXT("SDIO Init Error 0x%02x"), err); } - common_hal_sdioio_sdcard_check_for_deinit(self); - + self->command = command->number; slot_in_use[get_slot_index(self)] = true; claim_pin(clock); @@ -142,7 +163,7 @@ void common_hal_sdioio_sdcard_construct(sdioio_sdcard_obj_t *self, ESP_LOGI(TAG, "Number of sectors: %d with sector_size: %d", self->card.csd.capacity, self->card.csd.sector_size); - self->frequency = self->card.real_freq_khz; + self->frequency = self->card.real_freq_khz * 1000; ESP_LOGI(TAG, "Real frequency is %lu", self->frequency); self->capacity = self->card.csd.capacity; // Reported number of sectors ESP_LOGI(TAG, "Reported capacity is %lu", self->capacity); @@ -168,32 +189,73 @@ static void check_whole_block(mp_buffer_info_t *bufinfo, int sector_size) { } } -int common_hal_sdioio_sdcard_writeblocks(sdioio_sdcard_obj_t *self, uint32_t start_block, mp_buffer_info_t *bufinfo) { - common_hal_sdioio_sdcard_check_for_deinit(self); - check_whole_block(bufinfo, self->card.csd.sector_size); - esp_err_t err; - ESP_LOGI(TAG, "in common_hal_sdioio_sdcard_writeblocks"); - // err = sdmmc_io_write_blocks(&self->card, 1, start_block, bufinfo->buf, bufinfo->len); - err = sdmmc_write_sectors(&self->card, bufinfo->buf, start_block, bufinfo->len / self->card.csd.sector_size); +mp_negative_errno_t sdioio_sdcard_writeblocks(mp_obj_t self_in, uint8_t *buf, + uint32_t start_block, uint32_t num_blocks) { + sdioio_sdcard_obj_t *self = MP_OBJ_TO_PTR(self_in); + ESP_LOGI(TAG, "in sdioio_sdcard_writeblocks"); + esp_err_t err = sdmmc_write_sectors(&self->card, buf, start_block, num_blocks); if (err != ESP_OK) { ESP_LOGW(TAG, "Failed to write blocks with err 0x%X", err); + return -MP_EIO; } return 0; } -int common_hal_sdioio_sdcard_readblocks(sdioio_sdcard_obj_t *self, uint32_t start_block, mp_buffer_info_t *bufinfo) { +mp_negative_errno_t common_hal_sdioio_sdcard_writeblocks(sdioio_sdcard_obj_t *self, uint32_t start_block, mp_buffer_info_t *bufinfo) { common_hal_sdioio_sdcard_check_for_deinit(self); check_whole_block(bufinfo, self->card.csd.sector_size); - esp_err_t err; - ESP_LOGI(TAG, "in common_hal_sdioio_sdcard_readblocks"); - // err = sdmmc_io_read_blocks(&self->card, 1, start_block, bufinfo->buf, bufinfo->len); - err = sdmmc_read_sectors(&self->card, bufinfo->buf, start_block, bufinfo->len / self->card.csd.sector_size); + + uint32_t num_blocks = bufinfo->len / self->card.csd.sector_size; + return sdioio_sdcard_writeblocks(MP_OBJ_FROM_PTR(self), bufinfo->buf, + start_block, num_blocks); +} + +mp_negative_errno_t sdioio_sdcard_readblocks(mp_obj_t self_in, uint8_t *buf, + uint32_t start_block, uint32_t num_blocks) { + sdioio_sdcard_obj_t *self = MP_OBJ_TO_PTR(self_in); + ESP_LOGI(TAG, "in sdioio_sdcard_readblocks"); + esp_err_t err = sdmmc_read_sectors(&self->card, buf, start_block, num_blocks); if (err != ESP_OK) { ESP_LOGW(TAG, "Failed to read blocks with err 0x%X", err); + return -MP_EIO; } return 0; } +mp_negative_errno_t common_hal_sdioio_sdcard_readblocks(sdioio_sdcard_obj_t *self, uint32_t start_block, mp_buffer_info_t *bufinfo) { + common_hal_sdioio_sdcard_check_for_deinit(self); + check_whole_block(bufinfo, self->card.csd.sector_size); + + uint32_t num_blocks = bufinfo->len / self->card.csd.sector_size; + return sdioio_sdcard_readblocks(MP_OBJ_FROM_PTR(self), bufinfo->buf, + start_block, num_blocks); +} + +// Native function for VFS blockdev layer +bool sdioio_sdcard_ioctl(mp_obj_t self_in, size_t cmd, size_t arg, + mp_int_t *out_value) { + sdioio_sdcard_obj_t *self = MP_OBJ_TO_PTR(self_in); + *out_value = 0; + + switch (cmd) { + case MP_BLOCKDEV_IOCTL_DEINIT: + case MP_BLOCKDEV_IOCTL_SYNC: + // SDIO operations are synchronous, no action needed + return true; + + case MP_BLOCKDEV_IOCTL_BLOCK_COUNT: + *out_value = common_hal_sdioio_sdcard_get_count(self); + return true; + + case MP_BLOCKDEV_IOCTL_BLOCK_SIZE: + *out_value = 512; // SD cards use 512-byte sectors + return true; + + default: + return false; // Unsupported command + } +} + bool common_hal_sdioio_sdcard_configure(sdioio_sdcard_obj_t *self, uint32_t frequency, uint8_t bits) { return true; } @@ -207,15 +269,12 @@ void common_hal_sdioio_sdcard_deinit(sdioio_sdcard_obj_t *self) { return; } - never_reset_sdio[get_slot_index(self)] = false; + sdmmc_host_deinit_slot(self->slot); slot_in_use[get_slot_index(self)] = false; - if (!slot_in_use[0] && !slot_in_use[1]) { - sdmmc_host_deinit(); - } reset_pin_number(self->command); - self->command = COMMON_HAL_MCU_NO_PIN; + mark_deinit(self); reset_pin_number(self->clock); self->clock = COMMON_HAL_MCU_NO_PIN; for (size_t i = 0; i < self->num_data; i++) { @@ -225,35 +284,3 @@ void common_hal_sdioio_sdcard_deinit(sdioio_sdcard_obj_t *self) { return; } - -void common_hal_sdioio_sdcard_never_reset(sdioio_sdcard_obj_t *self) { - if (common_hal_sdioio_sdcard_deinited(self)) { - return; - } - - if (never_reset_sdio[get_slot_index(self)]) { - return; - } - - never_reset_sdio[get_slot_index(self)] = true; - - never_reset_pin_number(self->command); - never_reset_pin_number(self->clock); - - for (size_t i = 0; i < self->num_data; i++) { - never_reset_pin_number(self->data[i]); - } -} - -void sdioio_reset() { - for (size_t i = 0; i < MP_ARRAY_SIZE(slot_in_use); i++) { - if (!never_reset_sdio[i]) { - slot_in_use[i] = false; - } - } - if (!slot_in_use[0] && !slot_in_use[1]) { - sdmmc_host_deinit(); - } - - return; -} diff --git a/ports/espressif/common-hal/sdioio/SDCard.h b/ports/espressif/common-hal/sdioio/SDCard.h index 03fb82b37d5..0c39eb9f50f 100644 --- a/ports/espressif/common-hal/sdioio/SDCard.h +++ b/ports/espressif/common-hal/sdioio/SDCard.h @@ -23,6 +23,4 @@ typedef struct { uint32_t capacity; } sdioio_sdcard_obj_t; -void sdioio_reset(void); - uint8_t get_slot_index(sdioio_sdcard_obj_t *); diff --git a/ports/espressif/common-hal/socketpool/Socket.c b/ports/espressif/common-hal/socketpool/Socket.c index 0a36eff95b4..4c35d9bcc45 100644 --- a/ports/espressif/common-hal/socketpool/Socket.c +++ b/ports/espressif/common-hal/socketpool/Socket.c @@ -12,7 +12,9 @@ #include "py/runtime.h" #include "shared-bindings/socketpool/SocketPool.h" #include "common-hal/socketpool/__init__.h" +#if CIRCUITPY_WIFI #include "common-hal/wifi/__init__.h" +#endif #if CIRCUITPY_SSL #include "shared-bindings/ssl/SSLSocket.h" #include "shared-module/ssl/SSLSocket.h" @@ -66,6 +68,20 @@ StaticTask_t socket_select_task_buffer; TaskHandle_t socket_select_task_handle; static int socket_change_fd = -1; +// lwip reports "nothing yet" on a non-blocking socket with EAGAIN or EWOULDBLOCK; any other errno is a real error. +static bool would_block(int err) { + return err == EAGAIN || err == EWOULDBLOCK; +} + +// Returns lwip's errno as a negative error code; a reset or unconnected socket is no longer connected. +static int socket_error(socketpool_socket_obj_t *self) { + int err = errno; + if (err == ECONNRESET || err == ENOTCONN) { + self->connected = false; + } + return -err; +} + static void socket_select_task(void *arg) { uint64_t signal; fd_set readfds; @@ -283,18 +299,21 @@ int socketpool_socket_accept(socketpool_socket_obj_t *self, mp_obj_t *peer_out, } RUN_BACKGROUND_TASKS; newsoc = lwip_accept(self->num, (struct sockaddr *)&peer_addr, &socklen); - // In non-blocking mode, fail instead of timing out - if (newsoc == -1 && (self->timeout_ms == 0 || mp_hal_is_interrupted())) { - return -MP_EAGAIN; + if (newsoc == -1) { + int err = errno; + if (!would_block(err)) { + return -err; + } + // In non-blocking mode, fail instead of timing out + if (self->timeout_ms == 0 || mp_hal_is_interrupted()) { + return -MP_EAGAIN; + } } } - if (timed_out) { - return -ETIMEDOUT; - } - + // Without a socket, the loop ended because it timed out. if (newsoc < 0) { - return -MP_EBADF; + return -ETIMEDOUT; } // We got a socket. New client socket will not be non-blocking by default, so make it non-blocking. @@ -483,7 +502,7 @@ void common_hal_socketpool_socket_connect(socketpool_socket_obj_t *self, socklen_t socklen = sizeof(error_code); result = getsockopt(self->num, SOL_SOCKET, SO_ERROR, &error_code, &socklen); if (result < 0 || error_code != 0) { - mp_raise_OSError(errno); + mp_raise_OSError(error_code); } self->connected = true; return; @@ -524,20 +543,21 @@ mp_uint_t common_hal_socketpool_socket_recvfrom_into(socketpool_socket_obj_t *se } 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 (received == -1) { + int err = errno; + if (!would_block(err)) { + mp_raise_OSError(err); + } + // In non-blocking mode, fail instead of looping + if (self->timeout_ms == 0) { + mp_raise_OSError(MP_EAGAIN); + } } } - if (timed_out) { - mp_raise_OSError(ETIMEDOUT); - } - + // Without data, the loop ended because it timed out or was interrupted. if (received < 0) { - mp_raise_BrokenPipeError(); - return 0; + mp_raise_OSError(timed_out ? ETIMEDOUT : MP_EAGAIN); } if (source_out) { @@ -563,9 +583,12 @@ int socketpool_socket_recv_into(socketpool_socket_obj_t *self, } RUN_BACKGROUND_TASKS; received = lwip_recv(self->num, (void *)buf, len, 0); + if (received == -1 && !would_block(errno)) { + return socket_error(self); + } // In non-blocking mode, fail instead of looping if (received < 1 && self->timeout_ms == 0) { - if ((received == 0) || (errno == ENOTCONN)) { + if (received == 0) { self->connected = false; return -MP_ENOTCONN; } @@ -584,7 +607,8 @@ int socketpool_socket_recv_into(socketpool_socket_obj_t *self, return -MP_EBADF; } - if (timed_out) { + // Without data, the loop ended because it timed out. + if (received < 0) { return -ETIMEDOUT; } return received; @@ -605,14 +629,11 @@ int socketpool_socket_send(socketpool_socket_obj_t *self, const uint8_t *buf, ui // TODO: deal with potential failure/add timeout? sent = lwip_send(self->num, buf, len, 0); } else { - sent = -MP_EBADF; + return -MP_EBADF; } if (sent < 0) { - if (errno == ECONNRESET || errno == ENOTCONN) { - self->connected = false; - } - return -errno; + return socket_error(self); } return sent; @@ -635,8 +656,7 @@ mp_uint_t common_hal_socketpool_socket_sendto(socketpool_socket_obj_t *self, int bytes_sent = lwip_sendto(self->num, buf, len, 0, (struct sockaddr *)&addr, addr.s2_len); if (bytes_sent < 0) { - mp_raise_BrokenPipeError(); - return 0; + mp_raise_OSError(errno); } return bytes_sent; } diff --git a/ports/espressif/common-hal/socketpool/SocketPool.c b/ports/espressif/common-hal/socketpool/SocketPool.c index aa7461d3ffe..9705f133b0c 100644 --- a/ports/espressif/common-hal/socketpool/SocketPool.c +++ b/ports/espressif/common-hal/socketpool/SocketPool.c @@ -8,34 +8,35 @@ #include "common-hal/socketpool/Socket.h" #include "py/runtime.h" +#if CIRCUITPY_WIFI #include "shared-bindings/wifi/__init__.h" +#endif +#if CIRCUITPY_MII +#include "shared-bindings/mii/Ethernet.h" +#endif #include "common-hal/socketpool/__init__.h" #include "components/lwip/lwip/src/include/lwip/netdb.h" #include "bindings/espidf/__init__.h" -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(MP_ERROR_TEXT("SocketPool can only be used with wifi.radio")); +void common_hal_socketpool_socketpool_construct(socketpool_socketpool_obj_t *self, mp_obj_t network_interface) { + bool valid = false; + #if CIRCUITPY_WIFI + valid = valid || network_interface == MP_OBJ_FROM_PTR(&common_hal_wifi_radio_obj); + #endif + #if CIRCUITPY_MII + valid = valid || mp_obj_is_type(network_interface, &mii_ethernet_type); + #endif + if (!valid) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("SocketPool can only be used with %q.%q or any %q.%q"), + MP_QSTR_wifi, MP_QSTR_radio, MP_QSTR_ethernet, MP_QSTR_Ethernet); } } // common_hal_socketpool_socket is in socketpool/Socket.c to centralize open socket tracking. int socketpool_getaddrinfo_common(const char *host, int service, const struct addrinfo *hints, struct addrinfo **res) { - // As of 2022, the version of lwip in esp-idf does not handle the - // trailing-dot syntax of domain names, so emulate it. - // Remove this once https://github.com/espressif/esp-idf/issues/10013 has - // been implemented - if (host) { - size_t strlen_host = strlen(host); - if (strlen_host && host[strlen_host - 1] == '.') { - mp_obj_t nodot = mp_obj_new_str(host, strlen_host - 1); - host = mp_obj_str_get_str(nodot); - } - } - char service_buf[6]; snprintf(service_buf, sizeof(service_buf), "%d", service); diff --git a/ports/espressif/common-hal/socketpool/__init__.c b/ports/espressif/common-hal/socketpool/__init__.c index c8558f9b80a..4d807234687 100644 --- a/ports/espressif/common-hal/socketpool/__init__.c +++ b/ports/espressif/common-hal/socketpool/__init__.c @@ -5,9 +5,53 @@ // SPDX-License-Identifier: MIT #include "shared-bindings/socketpool/__init__.h" +#include "common-hal/socketpool/__init__.h" #include "common-hal/socketpool/Socket.h" +#include "py/runtime.h" + +#include "lwip/inet.h" +#include "lwip/sockets.h" + +#include + void socketpool_user_reset(void) { socket_user_reset(); } + +mp_obj_t sockaddr_to_str(const struct sockaddr_storage *sockaddr) { + char buf[IPADDR_STRLEN_MAX]; + #if CIRCUITPY_SOCKETPOOL_IPV6 + if (sockaddr->ss_family == AF_INET6) { + const struct sockaddr_in6 *addr6 = (const void *)sockaddr; + inet_ntop(AF_INET6, &addr6->sin6_addr, buf, sizeof(buf)); + } else + #endif + { + const struct sockaddr_in *addr = (const void *)sockaddr; + inet_ntop(AF_INET, &addr->sin_addr, buf, sizeof(buf)); + } + return mp_obj_new_str(buf, strlen(buf)); +} + +mp_obj_t sockaddr_to_tuple(const struct sockaddr_storage *sockaddr) { + mp_obj_t args[4] = { + sockaddr_to_str(sockaddr), + }; + int n = 2; + #if CIRCUITPY_SOCKETPOOL_IPV6 + if (sockaddr->ss_family == AF_INET6) { + const struct sockaddr_in6 *addr6 = (const void *)sockaddr; + args[1] = MP_OBJ_NEW_SMALL_INT(htons(addr6->sin6_port)); + args[2] = MP_OBJ_NEW_SMALL_INT(addr6->sin6_flowinfo); + args[3] = MP_OBJ_NEW_SMALL_INT(addr6->sin6_scope_id); + n = 4; + } else + #endif + { + const struct sockaddr_in *addr = (const void *)sockaddr; + args[1] = MP_OBJ_NEW_SMALL_INT(htons(addr->sin_port)); + } + return mp_obj_new_tuple(n, args); +} diff --git a/ports/espressif/common-hal/socketpool/__init__.h b/ports/espressif/common-hal/socketpool/__init__.h index 48773954fe5..6bf3eb92720 100644 --- a/ports/espressif/common-hal/socketpool/__init__.h +++ b/ports/espressif/common-hal/socketpool/__init__.h @@ -6,7 +6,13 @@ #pragma once +#include "py/obj.h" + struct addrinfo; +struct sockaddr_storage; int socketpool_getaddrinfo_common(const char *host, int service, const struct addrinfo *hints, struct addrinfo **res); void socketpool_resolve_host_or_throw(int family, int type, const char *hostname, struct sockaddr_storage *addr, int port); + +mp_obj_t sockaddr_to_str(const struct sockaddr_storage *addr); +mp_obj_t sockaddr_to_tuple(const struct sockaddr_storage *addr); diff --git a/ports/espressif/common-hal/touchio/TouchIn.c b/ports/espressif/common-hal/touchio/TouchIn.c index 2a37e6e526f..1596efdefde 100644 --- a/ports/espressif/common-hal/touchio/TouchIn.c +++ b/ports/espressif/common-hal/touchio/TouchIn.c @@ -7,25 +7,29 @@ #include "shared-bindings/touchio/TouchIn.h" #include "py/runtime.h" +#include "bindings/espidf/__init__.h" #include "peripherals/touch.h" #include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/digitalio/Pull.h" void common_hal_touchio_touchin_construct(touchio_touchin_obj_t *self, - const mcu_pin_obj_t *pin) { + const mcu_pin_obj_t *pin, const digitalio_pull_t pull) { if (pin->touch_channel == NO_TOUCH_CHANNEL) { raise_ValueError_invalid_pin(); } - claim_pin(pin); - // initialize touchpad - peripherals_touch_init(pin->touch_channel); + CHECK_ESP_RESULT(peripherals_touch_init(pin->touch_channel)); + claim_pin(pin); // Set a "touched" threshold not too far above the initial value. // For simple finger touch, the values may vary as much as a factor of two, // but for touches using fruit or other objects, the difference is much less. self->pin = pin; - self->threshold = common_hal_touchio_touchin_get_raw_value(self) + 100; + // Clamp to avoid uint16_t wraparound: a reading near UINT16_MAX would otherwise + // give a small threshold, and value would always be True. + uint32_t threshold = common_hal_touchio_touchin_get_raw_value(self) + 100; + self->threshold = MIN(threshold, UINT16_MAX); } bool common_hal_touchio_touchin_deinited(touchio_touchin_obj_t *self) { @@ -36,7 +40,8 @@ void common_hal_touchio_touchin_deinit(touchio_touchin_obj_t *self) { if (common_hal_touchio_touchin_deinited(self)) { return; } - reset_pin_number(self->pin->touch_channel); + peripherals_touch_deinit(self->pin->touch_channel); + reset_pin_number(self->pin->number); self->pin = NULL; } diff --git a/ports/espressif/common-hal/usb_host/Port.c b/ports/espressif/common-hal/usb_host/Port.c new file mode 100644 index 00000000000..8a629fe3b61 --- /dev/null +++ b/ports/espressif/common-hal/usb_host/Port.c @@ -0,0 +1,102 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Limor Fried for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "bindings/espidf/__init__.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/usb_host/Port.h" +#include "supervisor/port.h" +#include "supervisor/usb.h" +#include "esp_private/usb_phy.h" +#include "freertos/FreeRTOS.h" +#include "freertos/task.h" +#include "tusb.h" + +#if defined(CONFIG_IDF_TARGET_ESP32P4) +#if CIRCUITPY_USB_HOST_INSTANCE != 1 +#error "USB host requires the ESP32-P4 high-speed controller" +#endif +#elif defined(CONFIG_IDF_TARGET_ESP32S31) +// The S31 has only the high-speed controller, as TinyUSB rhport 0. +#if CIRCUITPY_USB_HOST_INSTANCE != 0 +#error "USB host requires the ESP32-S31 high-speed controller" +#endif +#else +#error "USB host is not supported on this chip" +#endif +#if CIRCUITPY_USB_DEVICE && CIRCUITPY_USB_DEVICE_INSTANCE == CIRCUITPY_USB_HOST_INSTANCE +#error "USB host and device must use different controllers" +#endif +#if !CIRCUITPY_USB_HOST_TASK +#error "The espressif USB host runs TinyUSB in a task of its own" +#endif + +// TinyUSB's host stack runs in this task, which waits on TinyUSB's event queue +// and so runs as soon as the controller interrupt posts an event. The VM +// doesn't have to get to its background tasks first: an isochronous stream +// queues its next transfer within the frame while the VM writes to an SD card +// or collects garbage. +// +// It runs above the VM's priority, like the MAX3421E's host task, so that a +// busy VM doesn't hold it up. Like the other USB tasks it is pinned to the +// same core as CircuitPython, which leaves the other core for networking. +#define USB_HOST_TASK_PRIORITY (5) +// Bytes. Enumeration and the class and Python module callbacks run on it. +#define USB_HOST_TASK_STACK_SIZE (4096) + +static usb_host_port_obj_t usb_host_instance; +static usb_phy_handle_t host_phy; + +static StackType_t _host_task_stack[USB_HOST_TASK_STACK_SIZE]; +static StaticTask_t _host_task_tcb; +static TaskHandle_t _host_task = NULL; + +static void _usb_host_task(void *param) { + (void)param; + while (true) { + // Returns once the events that came in are handled. It waits only as + // long as no TinyUSB timer (enumeration delays, control transfer + // timeouts) is due. + tuh_task_ext(UINT32_MAX, false); + // Python code may be waiting for what the events completed. + port_wake_main_task(); + } +} + +usb_host_port_obj_t *common_hal_usb_host_port_construct(const mcu_pin_obj_t *dp, const mcu_pin_obj_t *dm) { + // The high-speed PHY has dedicated pads, not GPIOs. + if (dp != &pin_USB_HS_DP || dm != &pin_USB_HS_DM) { + raise_ValueError_invalid_pins(); + } + usb_host_port_obj_t *self = &usb_host_instance; + if (self->dp != NULL) { + return self; + } + + const usb_phy_config_t config = { + .controller = USB_PHY_CTRL_OTG, + .target = USB_PHY_TARGET_UTMI, + .otg_mode = USB_OTG_MODE_HOST, + .otg_speed = USB_PHY_SPEED_HIGH, + }; + CHECK_ESP_RESULT(usb_new_phy(&config, &host_phy)); + if (!tuh_init(TUH_OPT_RHPORT)) { + usb_del_phy(host_phy); + host_phy = NULL; + CHECK_ESP_RESULT(ESP_FAIL); + } + // The port is never deinited, so neither is the task. It is the only + // caller of tuh_task_ext(), which is why it only starts after tuh_init(). + // This runs on the VM, so xPortGetCoreID() is CircuitPython's core. + if (_host_task == NULL) { + _host_task = xTaskCreateStaticPinnedToCore(_usb_host_task, "usbh", + USB_HOST_TASK_STACK_SIZE, NULL, USB_HOST_TASK_PRIORITY, + _host_task_stack, &_host_task_tcb, xPortGetCoreID()); + } + self->base.type = &usb_host_port_type; + self->dp = dp; + self->dm = dm; + return self; +} diff --git a/ports/espressif/common-hal/usb_host/Port.h b/ports/espressif/common-hal/usb_host/Port.h new file mode 100644 index 00000000000..e7b44c9524c --- /dev/null +++ b/ports/espressif/common-hal/usb_host/Port.h @@ -0,0 +1,15 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2022 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +typedef struct { + mp_obj_base_t base; + const mcu_pin_obj_t *dp; + const mcu_pin_obj_t *dm; +} usb_host_port_obj_t; diff --git a/ports/espressif/common-hal/usb_host/__init__.c b/ports/espressif/common-hal/usb_host/__init__.c new file mode 100644 index 00000000000..c3cdbae38c4 --- /dev/null +++ b/ports/espressif/common-hal/usb_host/__init__.c @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2022 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// Nothing diff --git a/ports/espressif/common-hal/watchdog/WatchDogTimer.c b/ports/espressif/common-hal/watchdog/WatchDogTimer.c index d3f66c15b6d..dfe9c572084 100644 --- a/ports/espressif/common-hal/watchdog/WatchDogTimer.c +++ b/ports/espressif/common-hal/watchdog/WatchDogTimer.c @@ -38,7 +38,7 @@ void common_hal_watchdog_feed(watchdog_watchdogtimer_obj_t *self) { esp_task_wdt_reset(); } -void common_hal_watchdog_deinit(watchdog_watchdogtimer_obj_t *self) { +void common_hal_watchdog_reset(watchdog_watchdogtimer_obj_t *self) { if (self->mode == WATCHDOGMODE_NONE) { return; } @@ -90,7 +90,7 @@ void common_hal_watchdog_set_mode(watchdog_watchdogtimer_obj_t *self, watchdog_w switch (new_mode) { case WATCHDOGMODE_NONE: - common_hal_watchdog_deinit(self); + common_hal_watchdog_reset(self); break; case WATCHDOGMODE_RAISE: case WATCHDOGMODE_RESET: diff --git a/ports/espressif/common-hal/wifi/Monitor.c b/ports/espressif/common-hal/wifi/Monitor.c index 635ba7a5a67..8de4d8a8a0c 100644 --- a/ports/espressif/common-hal/wifi/Monitor.c +++ b/ports/espressif/common-hal/wifi/Monitor.c @@ -9,13 +9,18 @@ #include "py/mpstate.h" #include "py/runtime.h" +#include "bindings/espidf/__init__.h" #include "shared-bindings/wifi/Monitor.h" #include "shared-bindings/wifi/Packet.h" +#include "supervisor/port_heap.h" +#include "esp_heap_caps.h" #include "esp_log.h" +#include "esp_memory_utils.h" #define MONITOR_PAYLOAD_FCS_LEN (4) #define MONITOR_QUEUE_TIMEOUT_TICK (0) +#define MONITOR_INTERNAL_RAM_FLOOR (32 * 1024) typedef struct { void *payload; @@ -26,9 +31,27 @@ typedef struct { static const char *TAG = "monitor"; +// port_malloc() tries PSRAM first. Keep a frame in internal RAM only while +// enough stays free for WiFi, DMA bounce buffers and the like. +static void *alloc_payload(size_t length) { + void *payload = port_malloc(length, false); + if (payload != NULL && esp_ptr_internal(payload) && + heap_caps_get_free_size(MALLOC_CAP_INTERNAL) < MONITOR_INTERNAL_RAM_FLOOR) { + port_free(payload); + payload = NULL; + } + return payload; +} + static void wifi_monitor_cb(void *recv_buf, wifi_promiscuous_pkt_type_t type) { wifi_promiscuous_pkt_t *pkt = (wifi_promiscuous_pkt_t *)recv_buf; + // Construct enables promiscuous mode before make_new sets the singleton. + wifi_monitor_obj_t *self = MP_STATE_VM(wifi_monitor_singleton); + if (self == NULL || common_hal_wifi_monitor_deinited(self)) { + return; + } + // prepare packet monitor_packet_t packet = { .channel = pkt->rx_ctrl.channel, @@ -39,27 +62,42 @@ static void wifi_monitor_cb(void *recv_buf, wifi_promiscuous_pkt_type_t type) { // for now, the monitor only dumps the length of the MISC type frame if (type != WIFI_PKT_MISC && !pkt->rx_ctrl.rx_state) { packet.length -= MONITOR_PAYLOAD_FCS_LEN; - packet.payload = malloc(packet.length); + packet.payload = alloc_payload(packet.length); if (packet.payload) { memcpy(packet.payload, pkt->payload, packet.length); - wifi_monitor_obj_t *self = MP_STATE_VM(wifi_monitor_singleton); - if (self->queue) { - // send packet - if (xQueueSendFromISR(self->queue, &packet, NULL) != pdTRUE) { - self->lost++; - free(packet.payload); - ESP_LOGE(TAG, "packet queue full"); - } + // send packet + if (xQueueSendFromISR(self->queue, &packet, NULL) != pdTRUE) { + self->lost++; + port_free(packet.payload); + ESP_LOGE(TAG, "packet queue full"); } } else { + self->lost++; ESP_LOGE(TAG, "not enough memory for packet"); } } } +// Tune the radio and return the channel it is on afterwards. Raises +// ValueError for a channel this radio cannot use. Any other failure, for +// example while the station is associated, leaves the radio where it was. +static uint8_t set_channel(uint8_t channel) { + esp_err_t result = esp_wifi_set_channel(channel, WIFI_SECOND_CHAN_NONE); + if (result == ESP_ERR_INVALID_ARG) { + mp_arg_error_invalid(MP_QSTR_channel); + } else if (result != ESP_OK) { + wifi_second_chan_t second; + CHECK_ESP_RESULT(esp_wifi_get_channel(&channel, &second)); + } + return channel; +} + void common_hal_wifi_monitor_construct(wifi_monitor_obj_t *self, uint8_t channel, size_t queue) { mp_rom_error_text_t monitor_mode_init_error = MP_ERROR_TEXT("monitor init failed"); + // Before anything needs undoing on failure. + channel = set_channel(channel); + self->queue = xQueueCreate(queue, sizeof(monitor_packet_t)); if (!self->queue) { mp_raise_RuntimeError(monitor_mode_init_error); @@ -74,19 +112,17 @@ void common_hal_wifi_monitor_construct(wifi_monitor_obj_t *self, uint8_t channel if (esp_wifi_set_promiscuous(true) != ESP_OK) { mp_raise_RuntimeError(monitor_mode_init_error); } - esp_wifi_set_channel(channel, WIFI_SECOND_CHAN_NONE); self->channel = channel; self->queue_length = queue; } -bool common_hal_wifi_monitor_deinited(void) { - bool enabled; - return (esp_wifi_get_promiscuous(&enabled) == ESP_ERR_WIFI_NOT_INIT) ? true : !enabled; +bool common_hal_wifi_monitor_deinited(wifi_monitor_obj_t *self) { + return self->queue == NULL; } void common_hal_wifi_monitor_deinit(wifi_monitor_obj_t *self) { - if (common_hal_wifi_monitor_deinited()) { + if (common_hal_wifi_monitor_deinited(self)) { return; } @@ -98,15 +134,16 @@ void common_hal_wifi_monitor_deinit(wifi_monitor_obj_t *self) { monitor_packet_t packet; while (left_items--) { xQueueReceive(self->queue, &packet, MONITOR_QUEUE_TIMEOUT_TICK); - free(packet.payload); + port_free(packet.payload); } vQueueDelete(self->queue); self->queue = NULL; + // Root pointers outlive the VM heap. + MP_STATE_VM(wifi_monitor_singleton) = NULL; } void common_hal_wifi_monitor_set_channel(wifi_monitor_obj_t *self, uint8_t channel) { - self->channel = channel; - esp_wifi_set_channel(channel, WIFI_SECOND_CHAN_NONE); + self->channel = set_channel(channel); } mp_obj_t common_hal_wifi_monitor_get_channel(wifi_monitor_obj_t *self) { @@ -130,7 +167,10 @@ mp_obj_t common_hal_wifi_monitor_get_queued(wifi_monitor_obj_t *self) { mp_obj_t common_hal_wifi_monitor_get_packet(wifi_monitor_obj_t *self) { monitor_packet_t packet; - if (xQueueReceive(self->queue, &packet, MONITOR_QUEUE_TIMEOUT_TICK) != pdTRUE) { + // Peek, so that if building the dict raises MemoryError, the packet stays + // queued for the next call instead of being lost and its payload leaked. + // Only this task removes packets, so the one received below is this one. + if (xQueuePeek(self->queue, &packet, MONITOR_QUEUE_TIMEOUT_TICK) != pdTRUE) { return (mp_obj_t)&mp_const_empty_dict_obj; } @@ -141,9 +181,11 @@ mp_obj_t common_hal_wifi_monitor_get_packet(wifi_monitor_obj_t *self) { mp_obj_dict_store(dict, cp_enum_find(&wifi_packet_type, PACKET_LEN), MP_OBJ_NEW_SMALL_INT(packet.length)); mp_obj_dict_store(dict, cp_enum_find(&wifi_packet_type, PACKET_RAW), mp_obj_new_bytes(packet.payload, packet.length)); - free(packet.payload); mp_obj_dict_store(dict, cp_enum_find(&wifi_packet_type, PACKET_RSSI), MP_OBJ_NEW_SMALL_INT(packet.rssi)); + xQueueReceive(self->queue, &packet, MONITOR_QUEUE_TIMEOUT_TICK); + port_free(packet.payload); + return MP_OBJ_FROM_PTR(dict); } diff --git a/ports/espressif/common-hal/wifi/Network.c b/ports/espressif/common-hal/wifi/Network.c index 5e29cad3193..ac7d963dd08 100644 --- a/ports/espressif/common-hal/wifi/Network.c +++ b/ports/espressif/common-hal/wifi/Network.c @@ -6,6 +6,8 @@ #include +#include "py/objlist.h" + #include "shared-bindings/wifi/Network.h" #include "shared-bindings/wifi/AuthMode.h" diff --git a/ports/espressif/common-hal/wifi/Radio.c b/ports/espressif/common-hal/wifi/Radio.c index 1e499b9d1d6..5df02ad5e7e 100644 --- a/ports/espressif/common-hal/wifi/Radio.c +++ b/ports/espressif/common-hal/wifi/Radio.c @@ -5,6 +5,7 @@ // SPDX-License-Identifier: MIT #include "shared-bindings/wifi/Radio.h" +#include "shared-bindings/wifi/__init__.h" #include "shared-bindings/wifi/Network.h" #include @@ -13,6 +14,7 @@ #include "common-hal/wifi/__init__.h" #include "shared/runtime/interrupt_char.h" #include "py/gc.h" +#include "py/mphal.h" #include "py/obj.h" #include "py/runtime.h" #include "shared-bindings/ipaddress/IPv4Address.h" @@ -23,7 +25,8 @@ #include "common-hal/socketpool/__init__.h" #include "components/esp_netif/include/esp_netif_net_stack.h" -#include "components/esp_wifi/include/esp_wifi.h" +#include "esp_wifi.h" +#include "soc/soc_caps.h" #include "components/lwip/include/apps/ping/ping_sock.h" #include "lwip/sockets.h" @@ -35,6 +38,10 @@ #include "common-hal/mdns/Server.h" #endif +#ifdef CONFIG_ESP_HOSTED_ENABLED +#include "esp_hosted.h" +#endif + #define MAC_ADDRESS_LENGTH 6 static void set_mode_station(wifi_radio_obj_t *self, bool state) { @@ -80,6 +87,11 @@ bool common_hal_wifi_radio_get_enabled(wifi_radio_obj_t *self) { } void common_hal_wifi_radio_set_enabled(wifi_radio_obj_t *self, bool enabled) { + if (self->netif == NULL) { + // Wi-Fi init failed, for example because the co-processor doesn't run ESP-Hosted. + // Leave the radio off so callers see that, rather than starting a driver that isn't there. + return; + } if (self->started && !enabled) { if (self->current_scan != NULL) { common_hal_wifi_radio_stop_scanning_networks(self); @@ -93,12 +105,57 @@ void common_hal_wifi_radio_set_enabled(wifi_radio_obj_t *self, bool enabled) { } if (!self->started && enabled) { ESP_ERROR_CHECK(esp_wifi_start()); + #if defined(SOC_WIFI_SUPPORT_5G) && SOC_WIFI_SUPPORT_5G + // Dual-band radios default to 2.4 GHz only. Enable both bands so that + // 5 GHz networks are visible to scans and can be connected to. + ESP_ERROR_CHECK(esp_wifi_set_band_mode(WIFI_BAND_MODE_AUTO)); + #endif self->started = true; common_hal_wifi_radio_set_tx_power(self, CIRCUITPY_WIFI_DEFAULT_TX_POWER); + #ifdef CONFIG_ESP_HOSTED_ENABLED + // Temporary workaround: default to no power save on ESP-Hosted co-processors. + // + // With some APs, inbound traffic stalls in MIN_MODEM power save. A likely cause is + // the ESP32-C6 missing broadcast and ARP frames from the AP in power save. + // TODO: Remove when fixed upstream. + // https://github.com/espressif/esp-idf/issues/16096 + // https://github.com/adafruit/circuitpython/issues/11682 + esp_wifi_set_ps(WIFI_PS_NONE); + #endif return; } } +mp_obj_t common_hal_wifi_radio_get_version(wifi_radio_obj_t *self) { + #ifdef CONFIG_ESP_HOSTED_ENABLED + // netif is NULL when the co-processor didn't answer as ESP-Hosted at Wi-Fi init. + if (self->netif == NULL) { + return mp_const_none; + } + esp_hosted_coprocessor_fwver_t ver; + if (esp_hosted_get_coprocessor_fwversion(&ver) != ESP_OK) { + return mp_const_none; + } + + // Co-processor firmware that predates reporting its target name sends an empty one. + // Use the configured target then. + const char *target = CONFIG_ESP_HOSTED_IDF_SLAVE_TARGET; + char reported[32] = ""; + if (esp_hosted_get_cp_info(NULL, reported, sizeof(reported)) == ESP_OK && + reported[0] != '\0') { + target = reported; + } + + vstr_t vstr; + vstr_init(&vstr, 32); + vstr_printf(&vstr, "%s ESP-Hosted %u.%u.%u", target, + (unsigned int)ver.major1, (unsigned int)ver.minor1, (unsigned int)ver.patch1); + return mp_obj_new_str_from_vstr(&vstr); + #else + return mp_const_none; + #endif +} + mp_obj_t common_hal_wifi_radio_get_hostname(wifi_radio_obj_t *self) { const char *hostname = NULL; esp_netif_get_hostname(self->netif, &hostname); @@ -113,9 +170,15 @@ void common_hal_wifi_radio_set_hostname(wifi_radio_obj_t *self, const char *host esp_netif_set_hostname(self->ap_netif, hostname); } +const char *wifi_get_hostname_raw(void) { + const char *hostname = NULL; + esp_netif_get_hostname(common_hal_wifi_radio_obj.netif, &hostname); + return hostname == NULL ? "" : hostname; +} + mp_obj_t common_hal_wifi_radio_get_mac_address(wifi_radio_obj_t *self) { uint8_t mac[MAC_ADDRESS_LENGTH]; - esp_wifi_get_mac(ESP_IF_WIFI_STA, mac); + esp_wifi_get_mac(WIFI_IF_STA, mac); return mp_obj_new_bytes(mac, MAC_ADDRESS_LENGTH); } @@ -126,7 +189,7 @@ void common_hal_wifi_radio_set_mac_address(wifi_radio_obj_t *self, const uint8_t if ((mac[0] & 0b1) == 0b1) { mp_raise_RuntimeError(MP_ERROR_TEXT("Invalid multicast MAC address")); } - esp_wifi_set_mac(ESP_IF_WIFI_STA, mac); + esp_wifi_set_mac(WIFI_IF_STA, mac); } mp_float_t common_hal_wifi_radio_get_tx_power(wifi_radio_obj_t *self) { @@ -139,28 +202,49 @@ void common_hal_wifi_radio_set_tx_power(wifi_radio_obj_t *self, const mp_float_t esp_wifi_set_max_tx_power(tx_power * 4.0f); } -mp_int_t common_hal_wifi_radio_get_listen_interval(wifi_radio_obj_t *self) { - wifi_config_t *config = &self->sta_config; - return config->sta.listen_interval; +wifi_power_management_t common_hal_wifi_radio_get_power_management(wifi_radio_obj_t *self) { + wifi_ps_type_t ps; + esp_err_t ret = esp_wifi_get_ps(&ps); + if (ret == ESP_OK) { + switch (ps) { + case WIFI_PS_MIN_MODEM: + return POWER_MANAGEMENT_MIN; + case WIFI_PS_MAX_MODEM: + return POWER_MANAGEMENT_MAX; + case WIFI_PS_NONE: + return POWER_MANAGEMENT_NONE; + } + } + return POWER_MANAGEMENT_MIN; } -void common_hal_wifi_radio_set_listen_interval(wifi_radio_obj_t *self, const mp_int_t listen_interval) { - wifi_config_t *config = &self->sta_config; - config->sta.listen_interval = listen_interval; - if (listen_interval == 1) { - esp_wifi_set_ps(WIFI_PS_MIN_MODEM); - } else if (listen_interval > 1) { - esp_wifi_set_ps(WIFI_PS_MAX_MODEM); - } else { - esp_wifi_set_ps(WIFI_PS_NONE); - } - esp_wifi_set_config(ESP_IF_WIFI_STA, config); +void common_hal_wifi_radio_set_power_management(wifi_radio_obj_t *self, wifi_power_management_t power_management) { + switch (power_management) { + case POWER_MANAGEMENT_MIN: + esp_wifi_set_ps(WIFI_PS_MIN_MODEM); + break; + case POWER_MANAGEMENT_MAX: { + // listen_interval is only used in this case. + wifi_config_t *config = &self->sta_config; + // This is a typical value seen in various examples. + config->sta.listen_interval = 3; + esp_wifi_set_ps(WIFI_PS_MAX_MODEM); + esp_wifi_set_config(WIFI_IF_STA, config); + } + break; + case POWER_MANAGEMENT_NONE: + esp_wifi_set_ps(WIFI_PS_NONE); + break; + case POWER_MANAGEMENT_UNKNOWN: + // This should be prevented in shared-bindings. + break; + } } mp_obj_t common_hal_wifi_radio_get_mac_address_ap(wifi_radio_obj_t *self) { uint8_t mac[MAC_ADDRESS_LENGTH]; - esp_wifi_get_mac(ESP_IF_WIFI_AP, mac); + esp_wifi_get_mac(WIFI_IF_AP, mac); return mp_obj_new_bytes(mac, MAC_ADDRESS_LENGTH); } @@ -171,7 +255,7 @@ void common_hal_wifi_radio_set_mac_address_ap(wifi_radio_obj_t *self, const uint if ((mac[0] & 0b1) == 0b1) { mp_raise_RuntimeError(MP_ERROR_TEXT("Invalid multicast MAC address")); } - esp_wifi_set_mac(ESP_IF_WIFI_AP, mac); + esp_wifi_set_mac(WIFI_IF_AP, mac); } mp_obj_t common_hal_wifi_radio_start_scanning_networks(wifi_radio_obj_t *self, uint8_t start_channel, uint8_t stop_channel) { @@ -179,7 +263,7 @@ mp_obj_t common_hal_wifi_radio_start_scanning_networks(wifi_radio_obj_t *self, u mp_raise_RuntimeError(MP_ERROR_TEXT("Already scanning for wifi networks")); } if (!common_hal_wifi_radio_get_enabled(self)) { - mp_raise_RuntimeError(MP_ERROR_TEXT("wifi is not enabled")); + mp_raise_RuntimeError(MP_ERROR_TEXT("WiFi is not enabled")); } set_mode_station(self, true); @@ -214,6 +298,7 @@ void common_hal_wifi_radio_stop_station(wifi_radio_obj_t *self) { } void common_hal_wifi_radio_start_ap(wifi_radio_obj_t *self, uint8_t *ssid, size_t ssid_len, uint8_t *password, size_t password_len, uint8_t channel, uint32_t authmode, uint8_t max_connections) { + bool was_ap = self->ap_mode; set_mode_ap(self, true); uint8_t esp_authmode = 0; @@ -247,7 +332,25 @@ void common_hal_wifi_radio_start_ap(wifi_radio_obj_t *self, uint8_t *ssid, size_ config->ap.max_connection = max_connections; - esp_wifi_set_config(WIFI_IF_AP, config); + esp_err_t result = esp_wifi_set_config(WIFI_IF_AP, config); + if (result != ESP_OK) { + if (!was_ap) { + set_mode_ap(self, false); + } + // The IDF returns ESP_ERR_INVALID_ARG for a channel this radio or its + // country setting cannot use (wifi_ap_config_t.channel). + if (result == ESP_ERR_INVALID_ARG) { + mp_arg_error_invalid(MP_QSTR_channel); + } + raise_esp_error(result); + } + // Wait a few ms for the AP to start. Empirically, this takes < 3ms on ESP32, and < 1ms on other chips. + for (size_t ms = 0; ms < 10; ms++) { + if (common_hal_wifi_radio_get_ap_active(self)) { + break; + } + mp_hal_delay_ms(1); + } } bool common_hal_wifi_radio_get_ap_active(wifi_radio_obj_t *self) { @@ -298,7 +401,7 @@ mp_obj_t common_hal_wifi_radio_get_stations_ap(wifi_radio_obj_t *self) { 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(MP_ERROR_TEXT("wifi is not enabled")); + mp_raise_RuntimeError(MP_ERROR_TEXT("WiFi is not enabled")); } wifi_config_t *config = &self->sta_config; @@ -365,10 +468,15 @@ wifi_radio_error_t common_hal_wifi_radio_connect(wifi_radio_obj_t *self, uint8_t } else { config->sta.scan_method = WIFI_FAST_SCAN; } - esp_wifi_set_config(ESP_IF_WIFI_STA, config); + esp_wifi_set_config(WIFI_IF_STA, config); self->starting_retries = 5; self->retries_left = 5; - esp_wifi_connect(); + // On failure no connected or disconnected event will come, and the loop below would never end. + // ESP_ERR_WIFI_STATE only means a scan was aborted; the connection attempt still goes ahead. + esp_err_t connect_result = esp_wifi_connect(); + if (connect_result != ESP_OK && connect_result != ESP_ERR_WIFI_STATE) { + return WIFI_RADIO_ERROR_UNSPECIFIED; + } do { RUN_BACKGROUND_TASKS; diff --git a/ports/espressif/common-hal/wifi/ScannedNetworks.c b/ports/espressif/common-hal/wifi/ScannedNetworks.c index 02edb9bd036..2beb6b754a3 100644 --- a/ports/espressif/common-hal/wifi/ScannedNetworks.c +++ b/ports/espressif/common-hal/wifi/ScannedNetworks.c @@ -17,7 +17,8 @@ #include "shared-bindings/wifi/Radio.h" #include "shared-bindings/wifi/ScannedNetworks.h" -#include "components/esp_wifi/include/esp_wifi.h" +#include "esp_wifi.h" +#include "soc/soc_caps.h" static void wifi_scannednetworks_done(wifi_scannednetworks_obj_t *self) { self->done = true; @@ -111,29 +112,38 @@ mp_obj_t common_hal_wifi_scannednetworks_next(wifi_scannednetworks_obj_t *self) } // We don't do a linear scan so that we look at a variety of spectrum up front. +#if defined(SOC_WIFI_SUPPORT_5G) && SOC_WIFI_SUPPORT_5G +// 2.4 GHz first, then the 5 GHz U-NII bands. DFS channels are omitted: +// they require radar detection before transmitting. +static uint8_t scan_pattern[] = {6, 1, 11, 3, 9, 13, 2, 4, 8, 12, 5, 7, 10, 14, + 36, 40, 44, 48, 149, 153, 157, 161, 165, 0}; +#else static uint8_t scan_pattern[] = {6, 1, 11, 3, 9, 13, 2, 4, 8, 12, 5, 7, 10, 14, 0}; +#endif void wifi_scannednetworks_scan_next_channel(wifi_scannednetworks_obj_t *self) { - // There is no channel 0, so use that as a flag to indicate we've run out of channels to scan. - uint8_t next_channel = 0; - while (self->current_channel_index < sizeof(scan_pattern)) { - next_channel = scan_pattern[self->current_channel_index]; - self->current_channel_index++; - // Scan only channels that are in the specified range. - if (self->start_channel <= next_channel && next_channel <= self->end_channel) { - break; + while (true) { + // There is no channel 0, so use that as a flag to indicate we've run out of channels to scan. + uint8_t next_channel = 0; + while (self->current_channel_index < sizeof(scan_pattern)) { + next_channel = scan_pattern[self->current_channel_index]; + self->current_channel_index++; + // Scan only channels that are in the specified range. + if (self->start_channel <= next_channel && next_channel <= self->end_channel) { + break; + } } - } - wifi_scan_config_t config = { 0 }; - config.channel = next_channel; - if (next_channel == 0) { - wifi_scannednetworks_done(self); - } else { - esp_err_t result = esp_wifi_scan_start(&config, false); - if (result != ESP_OK) { + if (next_channel == 0) { wifi_scannednetworks_done(self); - } else { + return; + } + wifi_scan_config_t config = { 0 }; + config.channel = next_channel; + // The radio rejects channels outside the band it is set to. Skip those + // rather than ending the scan, so the rest of the pattern still runs. + if (esp_wifi_scan_start(&config, false) == ESP_OK) { self->channel_scan_in_progress = true; + return; } } } diff --git a/ports/espressif/common-hal/wifi/__init__.c b/ports/espressif/common-hal/wifi/__init__.c index 1a4c014bfbc..f564a3c1f8a 100644 --- a/ports/espressif/common-hal/wifi/__init__.c +++ b/ports/espressif/common-hal/wifi/__init__.c @@ -17,7 +17,8 @@ #include "py/mpstate.h" #include "py/runtime.h" -#include "components/esp_wifi/include/esp_wifi.h" +#include "esp_mac.h" +#include "esp_wifi.h" #include "components/heap/include/esp_heap_caps.h" @@ -26,16 +27,26 @@ wifi_radio_obj_t common_hal_wifi_radio_obj; #include "components/log/include/esp_log.h" #include "supervisor/port.h" +#include "supervisor/shared/network.h" #include "supervisor/workflow.h" #include "lwip/sockets.h" +#if CIRCUITPY_SETTINGS_TOML +#include "supervisor/shared/settings.h" +#endif + #if CIRCUITPY_STATUS_BAR #include "supervisor/shared/status_bar.h" #endif #include "esp_ipc.h" +#ifdef CONFIG_ESP_HOSTED_ENABLED +#include "esp_hosted.h" +#include "common-hal/microcontroller/Pin.h" +#endif + #ifdef CONFIG_IDF_TARGET_ESP32 #include "nvs_flash.h" #endif @@ -88,7 +99,192 @@ static void event_handler(void *arg, esp_event_base_t event_base, ESP_LOGW(TAG, "disconnected"); 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); + const char *reason_str = "unknown"; + switch (reason) { + case WIFI_REASON_UNSPECIFIED: + reason_str = "unspecified"; + break; + case WIFI_REASON_AUTH_EXPIRE: + reason_str = "auth expire"; + break; + case WIFI_REASON_AUTH_LEAVE: + reason_str = "auth leave"; + break; + case WIFI_REASON_DISASSOC_DUE_TO_INACTIVITY: + reason_str = "disassoc inactivity"; + break; + case WIFI_REASON_ASSOC_TOOMANY: + reason_str = "assoc toomany"; + break; + case WIFI_REASON_CLASS2_FRAME_FROM_NONAUTH_STA: + reason_str = "class2 from nonauth"; + break; + case WIFI_REASON_CLASS3_FRAME_FROM_NONASSOC_STA: + reason_str = "class3 from nonassoc"; + break; + case WIFI_REASON_ASSOC_LEAVE: + reason_str = "assoc leave"; + break; + case WIFI_REASON_ASSOC_NOT_AUTHED: + reason_str = "assoc not authed"; + break; + case WIFI_REASON_DISASSOC_PWRCAP_BAD: + reason_str = "disassoc pwrcap bad"; + break; + case WIFI_REASON_DISASSOC_SUPCHAN_BAD: + reason_str = "disassoc supchan bad"; + break; + case WIFI_REASON_BSS_TRANSITION_DISASSOC: + reason_str = "bss transition disassoc"; + break; + case WIFI_REASON_IE_INVALID: + reason_str = "ie invalid"; + break; + case WIFI_REASON_MIC_FAILURE: + reason_str = "mic failure"; + break; + case WIFI_REASON_4WAY_HANDSHAKE_TIMEOUT: + reason_str = "4way handshake timeout"; + break; + case WIFI_REASON_GROUP_KEY_UPDATE_TIMEOUT: + reason_str = "group key update timeout"; + break; + case WIFI_REASON_IE_IN_4WAY_DIFFERS: + reason_str = "ie in 4way differs"; + break; + case WIFI_REASON_GROUP_CIPHER_INVALID: + reason_str = "group cipher invalid"; + break; + case WIFI_REASON_PAIRWISE_CIPHER_INVALID: + reason_str = "pairwise cipher invalid"; + break; + case WIFI_REASON_AKMP_INVALID: + reason_str = "akmp invalid"; + break; + case WIFI_REASON_UNSUPP_RSN_IE_VERSION: + reason_str = "unsupp rsn ie version"; + break; + case WIFI_REASON_INVALID_RSN_IE_CAP: + reason_str = "invalid rsn ie cap"; + break; + case WIFI_REASON_802_1X_AUTH_FAILED: + reason_str = "802.1x auth failed"; + break; + case WIFI_REASON_CIPHER_SUITE_REJECTED: + reason_str = "cipher suite rejected"; + break; + case WIFI_REASON_TDLS_PEER_UNREACHABLE: + reason_str = "tdls peer unreachable"; + break; + case WIFI_REASON_TDLS_UNSPECIFIED: + reason_str = "tdls unspecified"; + break; + case WIFI_REASON_SSP_REQUESTED_DISASSOC: + reason_str = "ssp requested disassoc"; + break; + case WIFI_REASON_NO_SSP_ROAMING_AGREEMENT: + reason_str = "no ssp roaming agreement"; + break; + case WIFI_REASON_BAD_CIPHER_OR_AKM: + reason_str = "bad cipher or akm"; + break; + case WIFI_REASON_NOT_AUTHORIZED_THIS_LOCATION: + reason_str = "not authorized this location"; + break; + case WIFI_REASON_SERVICE_CHANGE_PERCLUDES_TS: + reason_str = "service change precludes ts"; + break; + case WIFI_REASON_UNSPECIFIED_QOS: + reason_str = "unspecified qos"; + break; + case WIFI_REASON_NOT_ENOUGH_BANDWIDTH: + reason_str = "not enough bandwidth"; + break; + case WIFI_REASON_MISSING_ACKS: + reason_str = "missing acks"; + break; + case WIFI_REASON_EXCEEDED_TXOP: + reason_str = "exceeded txop"; + break; + case WIFI_REASON_STA_LEAVING: + reason_str = "sta leaving"; + break; + case WIFI_REASON_END_BA: + reason_str = "end ba"; + break; + case WIFI_REASON_UNKNOWN_BA: + reason_str = "unknown ba"; + break; + case WIFI_REASON_TIMEOUT: + reason_str = "timeout"; + break; + case WIFI_REASON_PEER_INITIATED: + reason_str = "peer initiated"; + break; + case WIFI_REASON_AP_INITIATED: + reason_str = "ap initiated"; + break; + case WIFI_REASON_INVALID_FT_ACTION_FRAME_COUNT: + reason_str = "invalid ft action frame count"; + break; + case WIFI_REASON_INVALID_PMKID: + reason_str = "invalid pmkid"; + break; + case WIFI_REASON_INVALID_MDE: + reason_str = "invalid mde"; + break; + case WIFI_REASON_INVALID_FTE: + reason_str = "invalid fte"; + break; + case WIFI_REASON_TRANSMISSION_LINK_ESTABLISH_FAILED: + reason_str = "transmission link establish failed"; + break; + case WIFI_REASON_ALTERATIVE_CHANNEL_OCCUPIED: + reason_str = "alternative channel occupied"; + break; + case WIFI_REASON_BEACON_TIMEOUT: + reason_str = "beacon timeout"; + break; + case WIFI_REASON_NO_AP_FOUND: + reason_str = "no ap found"; + break; + case WIFI_REASON_AUTH_FAIL: + reason_str = "auth fail"; + break; + case WIFI_REASON_ASSOC_FAIL: + reason_str = "assoc fail"; + break; + case WIFI_REASON_HANDSHAKE_TIMEOUT: + reason_str = "handshake timeout"; + break; + case WIFI_REASON_CONNECTION_FAIL: + reason_str = "connection fail"; + break; + case WIFI_REASON_AP_TSF_RESET: + reason_str = "ap tsf reset"; + break; + case WIFI_REASON_ROAMING: + reason_str = "roaming"; + break; + case WIFI_REASON_ASSOC_COMEBACK_TIME_TOO_LONG: + reason_str = "assoc comeback time too long"; + break; + case WIFI_REASON_SA_QUERY_TIMEOUT: + reason_str = "sa query timeout"; + break; + case WIFI_REASON_NO_AP_FOUND_W_COMPATIBLE_SECURITY: + reason_str = "no ap found w compatible security"; + break; + case WIFI_REASON_NO_AP_FOUND_IN_AUTHMODE_THRESHOLD: + reason_str = "no ap found in authmode threshold"; + break; + case WIFI_REASON_NO_AP_FOUND_IN_RSSI_THRESHOLD: + reason_str = "no ap found in rssi threshold"; + break; + default: + break; + } + ESP_LOGW(TAG, "reason %d 0x%02x %s", reason, reason, reason_str); if (radio->retries_left > 0 && reason != WIFI_REASON_AUTH_FAIL && reason != WIFI_REASON_NO_AP_FOUND && @@ -104,12 +300,132 @@ static void event_handler(void *arg, esp_event_base_t event_base, break; } - // Cases to handle later. - // case WIFI_EVENT_STA_AUTHMODE_CHANGE: - default: { - ESP_LOGW(TAG, "event %ld 0x%02ld", event_id, event_id); + case WIFI_EVENT_WIFI_READY: + ESP_LOGW(TAG, "wifi ready"); + break; + case WIFI_EVENT_STA_AUTHMODE_CHANGE: + ESP_LOGW(TAG, "sta authmode change"); + break; + case WIFI_EVENT_STA_WPS_ER_SUCCESS: + ESP_LOGW(TAG, "sta wps er success"); + break; + case WIFI_EVENT_STA_WPS_ER_FAILED: + ESP_LOGW(TAG, "sta wps er failed"); + break; + case WIFI_EVENT_STA_WPS_ER_TIMEOUT: + ESP_LOGW(TAG, "sta wps er timeout"); + break; + case WIFI_EVENT_STA_WPS_ER_PIN: + ESP_LOGW(TAG, "sta wps er pin"); + break; + case WIFI_EVENT_STA_WPS_ER_PBC_OVERLAP: + ESP_LOGW(TAG, "sta wps er pbc overlap"); + break; + case WIFI_EVENT_AP_PROBEREQRECVED: + ESP_LOGW(TAG, "ap probereqrecved"); + break; + case WIFI_EVENT_FTM_REPORT: + ESP_LOGW(TAG, "ftm report"); + break; + case WIFI_EVENT_STA_BSS_RSSI_LOW: + ESP_LOGW(TAG, "sta bss rssi low"); + break; + case WIFI_EVENT_ACTION_TX_STATUS: + ESP_LOGW(TAG, "action tx status"); + break; + case WIFI_EVENT_ROC_DONE: + ESP_LOGW(TAG, "roc done"); + break; + case WIFI_EVENT_STA_BEACON_TIMEOUT: + ESP_LOGW(TAG, "sta beacon timeout"); + break; + case WIFI_EVENT_CONNECTIONLESS_MODULE_WAKE_INTERVAL_START: + ESP_LOGW(TAG, "connectionless module wake interval start"); + break; + case WIFI_EVENT_AP_WPS_RG_SUCCESS: + ESP_LOGW(TAG, "ap wps rg success"); + break; + case WIFI_EVENT_AP_WPS_RG_FAILED: + ESP_LOGW(TAG, "ap wps rg failed"); + break; + case WIFI_EVENT_AP_WPS_RG_TIMEOUT: + ESP_LOGW(TAG, "ap wps rg timeout"); + break; + case WIFI_EVENT_AP_WPS_RG_PIN: + ESP_LOGW(TAG, "ap wps rg pin"); + break; + case WIFI_EVENT_AP_WPS_RG_PBC_OVERLAP: + ESP_LOGW(TAG, "ap wps rg pbc overlap"); + break; + case WIFI_EVENT_ITWT_SETUP: + ESP_LOGW(TAG, "itwt setup"); + break; + case WIFI_EVENT_ITWT_TEARDOWN: + ESP_LOGW(TAG, "itwt teardown"); + break; + case WIFI_EVENT_ITWT_PROBE: + ESP_LOGW(TAG, "itwt probe"); + break; + case WIFI_EVENT_ITWT_SUSPEND: + ESP_LOGW(TAG, "itwt suspend"); + break; + case WIFI_EVENT_TWT_WAKEUP: + ESP_LOGW(TAG, "twt wakeup"); + break; + case WIFI_EVENT_BTWT_SETUP: + ESP_LOGW(TAG, "btwt setup"); + break; + case WIFI_EVENT_BTWT_TEARDOWN: + ESP_LOGW(TAG, "btwt teardown"); + break; + case WIFI_EVENT_NAN_SYNC_STARTED: + ESP_LOGW(TAG, "nan sync started"); + break; + case WIFI_EVENT_NAN_SYNC_STOPPED: + ESP_LOGW(TAG, "nan sync stopped"); + break; + case WIFI_EVENT_NAN_SVC_MATCH: + ESP_LOGW(TAG, "nan svc match"); + break; + case WIFI_EVENT_NAN_REPLIED: + ESP_LOGW(TAG, "nan replied"); + break; + case WIFI_EVENT_NAN_RECEIVE: + ESP_LOGW(TAG, "nan receive"); + break; + case WIFI_EVENT_NDP_INDICATION: + ESP_LOGW(TAG, "ndp indication"); + break; + case WIFI_EVENT_NDP_CONFIRM: + ESP_LOGW(TAG, "ndp confirm"); + break; + case WIFI_EVENT_NDP_TERMINATED: + ESP_LOGW(TAG, "ndp terminated"); + break; + case WIFI_EVENT_HOME_CHANNEL_CHANGE: + ESP_LOGW(TAG, "home channel change"); + break; + case WIFI_EVENT_STA_NEIGHBOR_REP: + ESP_LOGW(TAG, "sta neighbor rep"); + break; + case WIFI_EVENT_AP_WRONG_PASSWORD: + ESP_LOGW(TAG, "ap wrong password"); + break; + case WIFI_EVENT_STA_BEACON_OFFSET_UNSTABLE: + ESP_LOGW(TAG, "sta beacon offset unstable"); + break; + case WIFI_EVENT_DPP_URI_READY: + ESP_LOGW(TAG, "dpp uri ready"); + break; + case WIFI_EVENT_DPP_CFG_RECVD: + ESP_LOGW(TAG, "dpp cfg recvd"); + break; + case WIFI_EVENT_DPP_FAILED: + ESP_LOGW(TAG, "dpp failed"); + break; + default: + ESP_LOGW(TAG, "unknown event %ld", event_id); break; - } } } @@ -132,6 +448,52 @@ static bool wifi_inited; static bool wifi_ever_inited; static bool wifi_user_initiated; +#ifdef CONFIG_ESP_HOSTED_ENABLED +// Set when the co-processor didn't answer as ESP-Hosted firmware. Its firmware can't change +// without resetting this chip too, so don't wait for it again until then. +static bool hosted_unavailable; + +static const uint8_t hosted_pins[] = { + CONFIG_ESP_HOSTED_SDIO_PIN_CLK, CONFIG_ESP_HOSTED_SDIO_PIN_CMD, + CONFIG_ESP_HOSTED_SDIO_PIN_D0, CONFIG_ESP_HOSTED_SDIO_PIN_D1, + CONFIG_ESP_HOSTED_SDIO_PIN_D2, CONFIG_ESP_HOSTED_SDIO_PIN_D3, + CONFIG_ESP_HOSTED_SDIO_GPIO_RESET_SLAVE, +}; + +// Start ESP-Hosted and check that the co-processor answers as ESP-Hosted firmware. Other firmware +// (one that doesn't use SDIO, or speaks another protocol over it) never brings the transport up. +// Every Wi-Fi call then fails, and connect() would wait forever for an event, which hangs boot when +// web workflow is configured. So if it doesn't answer, undo the start and release the pins. +static bool start_hosted(void) { + for (size_t i = 0; i < MP_ARRAY_SIZE(hosted_pins); i++) { + claim_pin_number(hosted_pins[i]); + } + esp_hosted_coprocessor_fwver_t version; + // esp_hosted_connect_to_slave() waits for the transport but always returns ESP_OK. The version + // request fails at once if the transport isn't up, and otherwise needs a working RPC reply. + if (esp_hosted_init() == ESP_OK) { + esp_hosted_connect_to_slave(); + if (esp_hosted_get_coprocessor_fwversion(&version) == ESP_OK) { + return true; + } + } + ESP_LOGE(TAG, "Co-processor is not answering as ESP-Hosted; Wi-Fi is unavailable"); + esp_hosted_deinit(); + for (size_t i = 0; i < MP_ARRAY_SIZE(hosted_pins); i++) { + reset_pin_number(hosted_pins[i]); + } + hosted_unavailable = true; + return false; +} + +// Raises when called from the VM. Outside it (web workflow at boot) the caller sees the radio off. +static void hosted_failed(void) { + if (gc_alloc_possible()) { + mp_raise_RuntimeError(MP_ERROR_TEXT("WiFi is not enabled")); + } +} +#endif + void common_hal_wifi_init(bool user_initiated) { wifi_radio_obj_t *self = &common_hal_wifi_radio_obj; @@ -141,15 +503,27 @@ void common_hal_wifi_init(bool user_initiated) { } return; } - wifi_inited = true; - wifi_user_initiated = user_initiated; common_hal_wifi_radio_obj.base.type = &wifi_radio_type; if (!wifi_ever_inited) { - ESP_ERROR_CHECK(esp_netif_init()); + #ifdef CONFIG_ESP_HOSTED_ENABLED + if (hosted_unavailable) { + hosted_failed(); + return; + } + #endif ESP_ERROR_CHECK(esp_event_loop_create_default()); + ESP_ERROR_CHECK(esp_netif_init()); + #ifdef CONFIG_ESP_HOSTED_ENABLED + if (!start_hosted()) { + hosted_failed(); + return; + } + #endif wifi_ever_inited = true; } + wifi_inited = true; + wifi_user_initiated = user_initiated; self->netif = esp_netif_create_default_wifi_sta(); self->ap_netif = esp_netif_create_default_wifi_ap(); @@ -175,6 +549,7 @@ void common_hal_wifi_init(bool user_initiated) { &self->handler_instance_got_ip)); wifi_init_config_t config = WIFI_INIT_CONFIG_DEFAULT(); + esp_err_t result = esp_wifi_init(&config); #ifdef CONFIG_ESP32_WIFI_NVS_ENABLED // Generally we don't use this because we store ssid and passwords ourselves in the filesystem. esp_err_t err = nvs_flash_init(); @@ -185,8 +560,10 @@ void common_hal_wifi_init(bool user_initiated) { err = nvs_flash_init(); } ESP_ERROR_CHECK(err); + ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_FLASH)); + #else + ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM)); #endif - esp_err_t result = esp_wifi_init(&config); if (result == ESP_ERR_NO_MEM) { if (gc_alloc_possible()) { mp_raise_msg(&mp_type_MemoryError, MP_ERROR_TEXT("Failed to allocate Wifi memory")); @@ -199,29 +576,57 @@ void common_hal_wifi_init(bool user_initiated) { ESP_LOGE(TAG, "WiFi error code: %x", result); return; } - // Set the default lwip_local_hostname capped at 32 characters. We trim off - // the start of the board name (likely manufacturer) because the end is - // often more unique to the board. - size_t board_len = MIN(32 - ((MAC_ADDRESS_LENGTH * 2) + 6), strlen(CIRCUITPY_BOARD_ID)); - size_t board_trim = strlen(CIRCUITPY_BOARD_ID) - board_len; - // Avoid double _ in the hostname. - if (CIRCUITPY_BOARD_ID[board_trim] == '_') { - board_trim++; - } - char cpy_default_hostname[board_len + (MAC_ADDRESS_LENGTH * 2) + 6]; - uint8_t mac[MAC_ADDRESS_LENGTH]; - esp_wifi_get_mac(ESP_IF_WIFI_STA, mac); - snprintf(cpy_default_hostname, sizeof(cpy_default_hostname), "cpy-%s-%02x%02x%02x%02x%02x%02x", CIRCUITPY_BOARD_ID + board_trim, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); + #if CIRCUITPY_SETTINGS_TOML + char hostname[CONFIG_LWIP_DHCPS_MAX_HOSTNAME_LEN]; + if (settings_get_str("CIRCUITPY_WIFI_HOSTNAME", hostname, sizeof(hostname)) == SETTINGS_OK) { + ESP_ERROR_CHECK(esp_netif_set_hostname(self->netif, hostname)); + } + #else + if (false) { + } + #endif + else { + // Set the default hostname, capped at 32 characters. + char cpy_default_hostname[32]; + uint8_t mac[MAC_ADDRESS_LENGTH]; + esp_wifi_get_mac(WIFI_IF_STA, mac); + network_format_default_hostname(cpy_default_hostname, sizeof(cpy_default_hostname), mac); + ESP_ERROR_CHECK(esp_netif_set_hostname(self->netif, cpy_default_hostname)); + } - const char *default_lwip_local_hostname = cpy_default_hostname; - ESP_ERROR_CHECK(esp_netif_set_hostname(self->netif, default_lwip_local_hostname)); // set station mode to avoid the default SoftAP common_hal_wifi_radio_start_station(self); // start wifi common_hal_wifi_radio_set_enabled(self, true); } +bool wifi_is_initialized(void) { + return wifi_inited; +} + +void wifi_get_default_hostname(char *buf, size_t buf_size) { + if (buf_size < 18) { + if (buf_size > 0) { + buf[0] = '\0'; + } + return; + } + // esp_wifi_get_mac() works only after the Wi-Fi driver starts. + // esp_read_mac() reads the factory MAC from the chip's one-time-programmable + // memory (efuse), so it works before the driver starts. + // + // With ESP-Hosted, a separate co-processor chip runs the Wi-Fi radio, and + // common_hal_wifi_init() uses that chip's MAC. So on those boards this + // hostname may differ from the one common_hal_wifi_init() sets. + uint8_t mac[MAC_ADDRESS_LENGTH] = {0}; + if (esp_read_mac(mac, ESP_MAC_WIFI_STA) != ESP_OK) { + memset(mac, 0, sizeof(mac)); + } + // Use the same length limit as common_hal_wifi_init(). + network_format_default_hostname(buf, MIN(buf_size, 32), mac); +} + void wifi_user_reset(void) { if (wifi_user_initiated) { wifi_reset(); @@ -233,7 +638,9 @@ void wifi_reset(void) { if (!wifi_inited) { return; } - common_hal_wifi_monitor_deinit(MP_STATE_VM(wifi_monitor_singleton)); + if (MP_STATE_VM(wifi_monitor_singleton) != NULL) { + common_hal_wifi_monitor_deinit(MP_STATE_VM(wifi_monitor_singleton)); + } wifi_radio_obj_t *radio = &common_hal_wifi_radio_obj; common_hal_wifi_radio_set_enabled(radio, false); #ifndef CONFIG_IDF_TARGET_ESP32 @@ -244,9 +651,16 @@ void wifi_reset(void) { IP_EVENT_STA_GOT_IP, radio->handler_instance_got_ip)); ESP_ERROR_CHECK(esp_wifi_deinit()); - esp_netif_destroy(radio->netif); + // Use the default-netif destructor so the Wi-Fi default event handlers let go of + // these first. esp_wifi_stop() posts WIFI_EVENT_STA_STOP/AP_STOP, which the default + // event loop handles asynchronously (and, over ESP-Hosted, after an RPC round trip), + // so it can run after this function. The handler would then call esp_netif_stop() on + // the freed netif (whose DHCP pointer is already reused memory), which asserts in + // heap_caps_free(). Clearing the handler's netif pointers here makes that stop event + // a no-op. + esp_netif_destroy_default_wifi(radio->netif); radio->netif = NULL; - esp_netif_destroy(radio->ap_netif); + esp_netif_destroy_default_wifi(radio->ap_netif); radio->ap_netif = NULL; wifi_inited = false; #endif @@ -298,42 +712,6 @@ mp_obj_t espaddr6_to_str(const esp_ip6_addr_t *espaddr) { return espaddrx_to_str(espaddr, ESP_IPADDR_TYPE_V6); } -mp_obj_t sockaddr_to_str(const struct sockaddr_storage *sockaddr) { - char buf[IPADDR_STRLEN_MAX]; - #if CIRCUITPY_SOCKETPOOL_IPV6 - if (sockaddr->ss_family == AF_INET6) { - const struct sockaddr_in6 *addr6 = (const void *)sockaddr; - inet_ntop(AF_INET6, &addr6->sin6_addr, buf, sizeof(buf)); - } else - #endif - { - const struct sockaddr_in *addr = (const void *)sockaddr; - inet_ntop(AF_INET, &addr->sin_addr, buf, sizeof(buf)); - } - return mp_obj_new_str(buf, strlen(buf)); -} - -mp_obj_t sockaddr_to_tuple(const struct sockaddr_storage *sockaddr) { - mp_obj_t args[4] = { - sockaddr_to_str(sockaddr), - }; - int n = 2; - #if CIRCUITPY_SOCKETPOOL_IPV6 - if (sockaddr->ss_family == AF_INET6) { - const struct sockaddr_in6 *addr6 = (const void *)sockaddr; - args[1] = MP_OBJ_NEW_SMALL_INT(htons(addr6->sin6_port)); - args[2] = MP_OBJ_NEW_SMALL_INT(addr6->sin6_flowinfo); - args[3] = MP_OBJ_NEW_SMALL_INT(addr6->sin6_scope_id); - n = 4; - } else - #endif - { - const struct sockaddr_in *addr = (const void *)sockaddr; - args[1] = MP_OBJ_NEW_SMALL_INT(htons(addr->sin_port)); - } - return mp_obj_new_tuple(n, args); -} - void sockaddr_to_espaddr(const struct sockaddr_storage *sockaddr, esp_ip_addr_t *espaddr) { #if CIRCUITPY_SOCKETPOOL_IPV6 MP_STATIC_ASSERT(IPADDR_TYPE_V4 == ESP_IPADDR_TYPE_V4); diff --git a/ports/espressif/common-hal/wifi/__init__.h b/ports/espressif/common-hal/wifi/__init__.h index cbd3c000a17..1b452bfd259 100644 --- a/ports/espressif/common-hal/wifi/__init__.h +++ b/ports/espressif/common-hal/wifi/__init__.h @@ -18,8 +18,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_ip4(mp_obj_t ip_address, esp_ip4_addr_t *esp_ip_address); -mp_obj_t sockaddr_to_str(const struct sockaddr_storage *addr); -mp_obj_t sockaddr_to_tuple(const struct sockaddr_storage *addr); mp_obj_t espaddr_to_str(const esp_ip_addr_t *espaddr); mp_obj_t espaddr4_to_str(const esp_ip4_addr_t *espaddr); mp_obj_t espaddr6_to_str(const esp_ip6_addr_t *espaddr); diff --git a/ports/espressif/esp-adf-libs b/ports/espressif/esp-adf-libs new file mode 160000 index 00000000000..95289ee8beb --- /dev/null +++ b/ports/espressif/esp-adf-libs @@ -0,0 +1 @@ +Subproject commit 95289ee8beba870449cbcc1fd31bf968d40855f3 diff --git a/ports/espressif/esp-camera b/ports/espressif/esp-camera index 243560e9499..b87f7eb7d16 160000 --- a/ports/espressif/esp-camera +++ b/ports/espressif/esp-camera @@ -1 +1 @@ -Subproject commit 243560e94997c262565ed537154b0578b8ce2197 +Subproject commit b87f7eb7d1652ff67552899554bda610e925f823 diff --git a/ports/espressif/esp-hosted b/ports/espressif/esp-hosted new file mode 160000 index 00000000000..dd0176e5fc9 --- /dev/null +++ b/ports/espressif/esp-hosted @@ -0,0 +1 @@ +Subproject commit dd0176e5fc959d79b306f6677a2f878123c58e9a diff --git a/ports/espressif/esp-idf b/ports/espressif/esp-idf index f388200aba7..cb733171022 160000 --- a/ports/espressif/esp-idf +++ b/ports/espressif/esp-idf @@ -1 +1 @@ -Subproject commit f388200aba73826b9039be6f4fb5385c6b7136c6 +Subproject commit cb7331710226bb08461b1bde337f87610e5c53a9 diff --git a/ports/espressif/esp-idf-config/partitions-16MB-no-uf2-ota4MB.csv b/ports/espressif/esp-idf-config/partitions-16MB-no-uf2-ota4MB.csv new file mode 100644 index 00000000000..bb61a59a1c3 --- /dev/null +++ b/ports/espressif/esp-idf-config/partitions-16MB-no-uf2-ota4MB.csv @@ -0,0 +1,10 @@ +# 4 MB OTA slots without UF2, for chips whose largest firmware image is +# bigger than 2 MB but that have no USB device port. +# Name, Type, SubType, Offset, Size +# bootloader, app, boot, 0x2000/0x0, 24/32K +# partition_table, data, table, 0x8000, 4K +nvs, data, nvs, 0x9000, 20K +otadata, data, ota, 0xe000, 8K +ota_0, app, ota_0, 0x10000, 4096K +ota_1, app, ota_1, 0x410000, 4096K +user_fs, data, fat, 0x810000, 8128K diff --git a/ports/espressif/esp-idf-config/partitions-16MB-ota4MB.csv b/ports/espressif/esp-idf-config/partitions-16MB-ota4MB.csv new file mode 100644 index 00000000000..aea7e1bcb82 --- /dev/null +++ b/ports/espressif/esp-idf-config/partitions-16MB-ota4MB.csv @@ -0,0 +1,12 @@ +# 4 MB OTA slots, matching tinyuf2's partitions-16MB-ota4MB.csv. CircuitPython +# reads the flashed partition table, so UF2 uploads and direct flashes must use +# the same layout as the bootloader. +# Name, Type, SubType, Offset, Size +# bootloader, app, boot, 0x2000/0x0, 24/32K +# partition_table, data, table, 0x8000, 4K +nvs, data, nvs, 0x9000, 20K +otadata, data, ota, 0xe000, 8K +ota_0, app, ota_0, 0x10000, 4096K +ota_1, app, ota_1, 0x410000, 4096K +uf2, app, factory, 0x810000, 256K +user_fs, data, fat, 0x850000, 7872K diff --git a/ports/espressif/esp-idf-config/partitions-4MB-no-ota-no-uf2-large-user_fs.csv b/ports/espressif/esp-idf-config/partitions-4MB-no-ota-no-uf2-large-user_fs.csv new file mode 100644 index 00000000000..59e0d9d1212 --- /dev/null +++ b/ports/espressif/esp-idf-config/partitions-4MB-no-ota-no-uf2-large-user_fs.csv @@ -0,0 +1,7 @@ +# Name, Type, SubType, Offset, Size +# bootloader, app, boot, 0x1000/0x0, 28/32K +# partition_table, data, table, 0x8000, 4K +nvs, data, nvs, 0x9000, 20K +otadata, data, ota, 0xe000, 8K +ota_0, app, ota_0, 0x10000, 2048K +user_fs, data, fat, 0x210000, 1984K diff --git a/ports/espressif/esp-idf-config/partitions-4MB-no-ota-no-uf2.csv b/ports/espressif/esp-idf-config/partitions-4MB-no-ota-no-uf2.csv index 59e0d9d1212..49d043d7672 100644 --- a/ports/espressif/esp-idf-config/partitions-4MB-no-ota-no-uf2.csv +++ b/ports/espressif/esp-idf-config/partitions-4MB-no-ota-no-uf2.csv @@ -3,5 +3,5 @@ # partition_table, data, table, 0x8000, 4K nvs, data, nvs, 0x9000, 20K otadata, data, ota, 0xe000, 8K -ota_0, app, ota_0, 0x10000, 2048K -user_fs, data, fat, 0x210000, 1984K +ota_0, app, ota_0, 0x10000, 2816K +user_fs, data, fat, 0x2d0000, 1216K diff --git a/ports/espressif/esp-idf-config/sdkconfig-debug.defaults b/ports/espressif/esp-idf-config/sdkconfig-debug.defaults index a9c8e34e547..368ba81bb4a 100644 --- a/ports/espressif/esp-idf-config/sdkconfig-debug.defaults +++ b/ports/espressif/esp-idf-config/sdkconfig-debug.defaults @@ -7,6 +7,21 @@ CONFIG_COMPILER_OPTIMIZATION_SIZE=y # end of Compiler options +# Bootloader config +# +# +# Log +# +# +# Format +# +CONFIG_BOOTLOADER_LOG_COLORS=y +# end of Format + +# end of Log + +# end of Bootloader config + # # Component config # @@ -19,6 +34,17 @@ CONFIG_ESP_CONSOLE_SECONDARY_NONE=y # CONFIG_ESP_CONSOLE_SECONDARY_USB_SERIAL_JTAG is not set # end of ESP System Settings +# +# Log +# +# +# Format +# +CONFIG_LOG_COLORS=y +# end of Format + +# end of Log + # end of Component config # end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/esp-idf-config/sdkconfig-esp32.defaults b/ports/espressif/esp-idf-config/sdkconfig-esp32.defaults index 5789c442a62..1b2698068ed 100644 --- a/ports/espressif/esp-idf-config/sdkconfig-esp32.defaults +++ b/ports/espressif/esp-idf-config/sdkconfig-esp32.defaults @@ -62,10 +62,10 @@ CONFIG_ESP_IPC_TASK_STACK_SIZE=1536 # end of Wi-Fi # -# Newlib +# LibC # -CONFIG_NEWLIB_NANO_FORMAT=y -# end of Newlib +CONFIG_LIBC_NEWLIB_NANO_FORMAT=y +# end of LibC # # SPI Flash driver diff --git a/ports/espressif/esp-idf-config/sdkconfig-esp32c2.defaults b/ports/espressif/esp-idf-config/sdkconfig-esp32c2.defaults index 19c73ca5ee5..661b2b52801 100644 --- a/ports/espressif/esp-idf-config/sdkconfig-esp32c2.defaults +++ b/ports/espressif/esp-idf-config/sdkconfig-esp32c2.defaults @@ -43,10 +43,10 @@ CONFIG_ESP_WIFI_STATIC_RX_BUFFER_NUM=4 # end of Wi-Fi # -# Newlib +# LibC # -CONFIG_NEWLIB_NANO_FORMAT=y -# end of Newlib +CONFIG_LIBC_NEWLIB_NANO_FORMAT=y +# end of LibC # end of Component config diff --git a/ports/espressif/esp-idf-config/sdkconfig-esp32c3.defaults b/ports/espressif/esp-idf-config/sdkconfig-esp32c3.defaults index 19c73ca5ee5..661b2b52801 100644 --- a/ports/espressif/esp-idf-config/sdkconfig-esp32c3.defaults +++ b/ports/espressif/esp-idf-config/sdkconfig-esp32c3.defaults @@ -43,10 +43,10 @@ CONFIG_ESP_WIFI_STATIC_RX_BUFFER_NUM=4 # end of Wi-Fi # -# Newlib +# LibC # -CONFIG_NEWLIB_NANO_FORMAT=y -# end of Newlib +CONFIG_LIBC_NEWLIB_NANO_FORMAT=y +# end of LibC # end of Component config diff --git a/ports/espressif/esp-idf-config/sdkconfig-esp32c5.defaults b/ports/espressif/esp-idf-config/sdkconfig-esp32c5.defaults new file mode 100644 index 00000000000..eb6f64cbb78 --- /dev/null +++ b/ports/espressif/esp-idf-config/sdkconfig-esp32c5.defaults @@ -0,0 +1,54 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Component config +# +# +# Bluetooth +# +CONFIG_BT_ENABLED=y +CONFIG_BT_NIMBLE_ENABLED=y +# +# NimBLE Options +# +CONFIG_BT_NIMBLE_LOG_LEVEL_NONE=y +CONFIG_BT_NIMBLE_NVS_PERSIST=y +# +# Memory Settings +# +CONFIG_BT_NIMBLE_TRANSPORT_ACL_FROM_LL_COUNT=20 +CONFIG_BT_NIMBLE_TRANSPORT_EVT_SIZE=70 +# end of Memory Settings + +CONFIG_BT_NIMBLE_EXT_ADV=y +# end of NimBLE Options + +# end of Bluetooth + +# +# Driver Configurations +# +# +# PCNT Configuration +# +CONFIG_PCNT_CTRL_FUNC_IN_IRAM=y +# end of PCNT Configuration + +# end of Driver Configurations + +# +# Wi-Fi +# +CONFIG_ESP_WIFI_STATIC_RX_BUFFER_NUM=4 +# end of Wi-Fi + +# +# mbedTLS +# +# CONFIG_MBEDTLS_HARDWARE_SHA is not set +# end of mbedTLS + +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/esp-idf-config/sdkconfig-esp32c6.defaults b/ports/espressif/esp-idf-config/sdkconfig-esp32c6.defaults index 85dde905f3c..63f42cac952 100644 --- a/ports/espressif/esp-idf-config/sdkconfig-esp32c6.defaults +++ b/ports/espressif/esp-idf-config/sdkconfig-esp32c6.defaults @@ -49,6 +49,12 @@ CONFIG_ESP_PHY_ENABLE_USB=y CONFIG_ESP_WIFI_STATIC_RX_BUFFER_NUM=4 # end of Wi-Fi +# +# mbedTLS +# +# CONFIG_MBEDTLS_HARDWARE_SHA is not set +# end of mbedTLS + # end of Component config # end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/esp-idf-config/sdkconfig-esp32c61.defaults b/ports/espressif/esp-idf-config/sdkconfig-esp32c61.defaults new file mode 100644 index 00000000000..85dde905f3c --- /dev/null +++ b/ports/espressif/esp-idf-config/sdkconfig-esp32c61.defaults @@ -0,0 +1,54 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Component config +# +# +# Bluetooth +# +CONFIG_BT_ENABLED=y +CONFIG_BT_NIMBLE_ENABLED=y +# +# NimBLE Options +# +CONFIG_BT_NIMBLE_LOG_LEVEL_NONE=y +CONFIG_BT_NIMBLE_NVS_PERSIST=y +# +# Memory Settings +# +CONFIG_BT_NIMBLE_TRANSPORT_ACL_FROM_LL_COUNT=20 +CONFIG_BT_NIMBLE_TRANSPORT_EVT_SIZE=70 +# end of Memory Settings + +CONFIG_BT_NIMBLE_EXT_ADV=y +# end of NimBLE Options + +# end of Bluetooth + +# +# Driver Configurations +# +# +# PCNT Configuration +# +CONFIG_PCNT_CTRL_FUNC_IN_IRAM=y +# end of PCNT Configuration + +# end of Driver Configurations + +# +# PHY +# +CONFIG_ESP_PHY_ENABLE_USB=y +# end of PHY + +# +# Wi-Fi +# +CONFIG_ESP_WIFI_STATIC_RX_BUFFER_NUM=4 +# end of Wi-Fi + +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/esp-idf-config/sdkconfig-esp32s2.defaults b/ports/espressif/esp-idf-config/sdkconfig-esp32s2.defaults index 66e06667a1a..64492314634 100644 --- a/ports/espressif/esp-idf-config/sdkconfig-esp32s2.defaults +++ b/ports/espressif/esp-idf-config/sdkconfig-esp32s2.defaults @@ -43,19 +43,18 @@ CONFIG_ESP_WIFI_RX_BA_WIN=4 # end of Wi-Fi # -# Newlib +# LibC # -CONFIG_NEWLIB_NANO_FORMAT=y -# end of Newlib +CONFIG_LIBC_NEWLIB_NANO_FORMAT=y +# end of LibC # # Ultra Low Power (ULP) Co-processor # CONFIG_ULP_COPROC_ENABLED=y CONFIG_ULP_COPROC_TYPE_FSM=y -CONFIG_ULP_COPROC_TYPE_RISCV=y # Note: enabling both ULPs simultaneously only works due to a modification of adafruit/esp-idf - # (see adafruit/esp-idf/pull/16) until espressif/esp-idf/issues/12999 is fixed. -CONFIG_ULP_COPROC_RESERVE_MEM=8176 +CONFIG_ULP_COPROC_TYPE_RISCV=y +CONFIG_ULP_COPROC_RESERVE_MEM=8144 # end of Ultra Low Power (ULP) Co-processor # end of Component config diff --git a/ports/espressif/esp-idf-config/sdkconfig-esp32s3.defaults b/ports/espressif/esp-idf-config/sdkconfig-esp32s3.defaults index fe3c3e0a2da..0d18d01da66 100644 --- a/ports/espressif/esp-idf-config/sdkconfig-esp32s3.defaults +++ b/ports/espressif/esp-idf-config/sdkconfig-esp32s3.defaults @@ -51,7 +51,7 @@ CONFIG_PCNT_CTRL_FUNC_IN_IRAM=y # # LCD Peripheral Configuration # -CONFIG_LCD_RGB_RESTART_IN_VSYNC=y +# CONFIG_LCD_RGB_RESTART_IN_VSYNC is not set # end of LCD Peripheral Configuration # end of LCD and Touch Panel @@ -83,19 +83,18 @@ CONFIG_ESP_WIFI_CACHE_TX_BUFFER_NUM=16 # end of Wi-Fi # -# Newlib +# LibC # -CONFIG_NEWLIB_NANO_FORMAT=y -# end of Newlib +CONFIG_LIBC_NEWLIB_NANO_FORMAT=y +# end of LibC # # Ultra Low Power (ULP) Co-processor # CONFIG_ULP_COPROC_ENABLED=y CONFIG_ULP_COPROC_TYPE_FSM=y -CONFIG_ULP_COPROC_TYPE_RISCV=y # Note: enabling both ULPs simultaneously only works due to a modification of adafruit/esp-idf - # (see adafruit/esp-idf/pull/16) until espressif/esp-idf/issues/12999 is fixed. -CONFIG_ULP_COPROC_RESERVE_MEM=8176 +CONFIG_ULP_COPROC_TYPE_RISCV=y +CONFIG_ULP_COPROC_RESERVE_MEM=8144 # end of Ultra Low Power (ULP) Co-processor # end of Component config diff --git a/ports/espressif/esp-idf-config/sdkconfig-esp32s31.defaults b/ports/espressif/esp-idf-config/sdkconfig-esp32s31.defaults new file mode 100644 index 00000000000..0806066e20b --- /dev/null +++ b/ports/espressif/esp-idf-config/sdkconfig-esp32s31.defaults @@ -0,0 +1,21 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Component config +# +# +# Bluetooth +# +# CONFIG_BT_ENABLED is not set +# end of Bluetooth + +# +# mbedTLS +# +# CONFIG_MBEDTLS_CMAC_C is not set +# end of mbedTLS + +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/esp-idf-config/sdkconfig-flash-120m.defaults b/ports/espressif/esp-idf-config/sdkconfig-flash-120m.defaults index fadf55d8d79..d582a77798c 100644 --- a/ports/espressif/esp-idf-config/sdkconfig-flash-120m.defaults +++ b/ports/espressif/esp-idf-config/sdkconfig-flash-120m.defaults @@ -1,15 +1,4 @@ CONFIG_ESPTOOLPY_FLASHFREQ_120M=y -# CONFIG_ESPTOOLPY_FLASHFREQ_80M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_64M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_60M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_48M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_40M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_32M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_30M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_26M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_24M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_20M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_16M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_15M is not set -CONFIG_ESPTOOLPY_FLASHFREQ_80M_DEFAULT=y CONFIG_SPI_FLASH_UNDER_HIGH_FREQ=y +CONFIG_SPI_FLASH_HPM_ENA=y +CONFIG_BOOTLOADER_FLASH_DC_AWARE=y diff --git a/ports/espressif/esp-idf-config/sdkconfig-flash-16MB-no-uf2-ota4MB.defaults b/ports/espressif/esp-idf-config/sdkconfig-flash-16MB-no-uf2-ota4MB.defaults new file mode 100644 index 00000000000..450c268065e --- /dev/null +++ b/ports/espressif/esp-idf-config/sdkconfig-flash-16MB-no-uf2-ota4MB.defaults @@ -0,0 +1,25 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Serial flasher config +# +# CONFIG_ESPTOOLPY_FLASHSIZE_1MB is not set +# CONFIG_ESPTOOLPY_FLASHSIZE_2MB is not set +# CONFIG_ESPTOOLPY_FLASHSIZE_4MB is not set +# CONFIG_ESPTOOLPY_FLASHSIZE_8MB is not set +CONFIG_ESPTOOLPY_FLASHSIZE_16MB=y +# CONFIG_ESPTOOLPY_FLASHSIZE_32MB is not set +# CONFIG_ESPTOOLPY_FLASHSIZE_64MB is not set +# CONFIG_ESPTOOLPY_FLASHSIZE_128MB is not set +CONFIG_ESPTOOLPY_FLASHSIZE="16MB" +# end of Serial flasher config + +# +# Partition Table +# +CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="esp-idf-config/partitions-16MB-no-uf2-ota4MB.csv" +CONFIG_PARTITION_TABLE_FILENAME="esp-idf-config/partitions-16MB-no-uf2-ota4MB.csv" +# end of Partition Table + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/esp-idf-config/sdkconfig-flash-16MB-ota4MB.defaults b/ports/espressif/esp-idf-config/sdkconfig-flash-16MB-ota4MB.defaults new file mode 100644 index 00000000000..d22ceefb0fc --- /dev/null +++ b/ports/espressif/esp-idf-config/sdkconfig-flash-16MB-ota4MB.defaults @@ -0,0 +1,25 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Serial flasher config +# +# CONFIG_ESPTOOLPY_FLASHSIZE_1MB is not set +# CONFIG_ESPTOOLPY_FLASHSIZE_2MB is not set +# CONFIG_ESPTOOLPY_FLASHSIZE_4MB is not set +# CONFIG_ESPTOOLPY_FLASHSIZE_8MB is not set +CONFIG_ESPTOOLPY_FLASHSIZE_16MB=y +# CONFIG_ESPTOOLPY_FLASHSIZE_32MB is not set +# CONFIG_ESPTOOLPY_FLASHSIZE_64MB is not set +# CONFIG_ESPTOOLPY_FLASHSIZE_128MB is not set +CONFIG_ESPTOOLPY_FLASHSIZE="16MB" +# end of Serial flasher config + +# +# Partition Table +# +CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="esp-idf-config/partitions-16MB-ota4MB.csv" +CONFIG_PARTITION_TABLE_FILENAME="esp-idf-config/partitions-16MB-ota4MB.csv" +# end of Partition Table + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/esp-idf-config/sdkconfig-flash-2MB-no-ota-no-uf2.defaults b/ports/espressif/esp-idf-config/sdkconfig-flash-2MB-no-ota-no-uf2.defaults index 2d0b2ac5eb9..21365b751d1 100644 --- a/ports/espressif/esp-idf-config/sdkconfig-flash-2MB-no-ota-no-uf2.defaults +++ b/ports/espressif/esp-idf-config/sdkconfig-flash-2MB-no-ota-no-uf2.defaults @@ -7,7 +7,6 @@ CONFIG_ESPTOOLPY_FLASHSIZE_2MB=y # CONFIG_ESPTOOLPY_FLASHSIZE_8MB is not set # CONFIG_ESPTOOLPY_FLASHSIZE_16MB is not set CONFIG_ESPTOOLPY_FLASHSIZE="2MB" -CONFIG_ESPTOOLPY_FLASHSIZE_DETECT=y # end of Serial flasher config CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="esp-idf-config/partitions-2MB-no-ota-no-uf2.csv" diff --git a/ports/espressif/esp-idf-config/sdkconfig-flash-32MB.defaults b/ports/espressif/esp-idf-config/sdkconfig-flash-32MB.defaults index bbdd32afb81..a5a93778864 100644 --- a/ports/espressif/esp-idf-config/sdkconfig-flash-32MB.defaults +++ b/ports/espressif/esp-idf-config/sdkconfig-flash-32MB.defaults @@ -8,7 +8,6 @@ # CONFIG_ESPTOOLPY_FLASHSIZE_16MB is not set CONFIG_ESPTOOLPY_FLASHSIZE_32MB=y CONFIG_ESPTOOLPY_FLASHSIZE="32MB" -CONFIG_ESPTOOLPY_FLASHSIZE_DETECT=y # end of Serial flasher config CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="esp-idf-config/partitions-32MB.csv" diff --git a/ports/espressif/esp-idf-config/sdkconfig-flash-40m.defaults b/ports/espressif/esp-idf-config/sdkconfig-flash-40m.defaults index 235a62a57ee..ffc4b5c1cb8 100644 --- a/ports/espressif/esp-idf-config/sdkconfig-flash-40m.defaults +++ b/ports/espressif/esp-idf-config/sdkconfig-flash-40m.defaults @@ -1,14 +1 @@ -# CONFIG_ESPTOOLPY_FLASHFREQ_120M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_80M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_64M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_60M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_48M is not set CONFIG_ESPTOOLPY_FLASHFREQ_40M=y -# CONFIG_ESPTOOLPY_FLASHFREQ_32M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_30M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_26M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_24M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_20M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_16M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_15M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_80M_DEFAULT is not set diff --git a/ports/espressif/esp-idf-config/sdkconfig-flash-48m.defaults b/ports/espressif/esp-idf-config/sdkconfig-flash-48m.defaults index b710fd22554..f6838e88703 100644 --- a/ports/espressif/esp-idf-config/sdkconfig-flash-48m.defaults +++ b/ports/espressif/esp-idf-config/sdkconfig-flash-48m.defaults @@ -1,14 +1 @@ -# CONFIG_ESPTOOLPY_FLASHFREQ_120M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_80M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_64M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_60M is not set CONFIG_ESPTOOLPY_FLASHFREQ_48M=y -# CONFIG_ESPTOOLPY_FLASHFREQ_40M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_32M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_30M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_26M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_24M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_20M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_16M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_15M is not set -CONFIG_ESPTOOLPY_FLASHFREQ_48M_DEFAULT=y diff --git a/ports/espressif/esp-idf-config/sdkconfig-flash-4MB-no-ota-no-uf2-large-user_fs.defaults b/ports/espressif/esp-idf-config/sdkconfig-flash-4MB-no-ota-no-uf2-large-user_fs.defaults new file mode 100644 index 00000000000..0a585e9d523 --- /dev/null +++ b/ports/espressif/esp-idf-config/sdkconfig-flash-4MB-no-ota-no-uf2-large-user_fs.defaults @@ -0,0 +1,25 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Serial flasher config +# +# CONFIG_ESPTOOLPY_FLASHSIZE_1MB is not set +# CONFIG_ESPTOOLPY_FLASHSIZE_2MB is not set +CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y +# CONFIG_ESPTOOLPY_FLASHSIZE_8MB is not set +# CONFIG_ESPTOOLPY_FLASHSIZE_16MB is not set +# CONFIG_ESPTOOLPY_FLASHSIZE_32MB is not set +# CONFIG_ESPTOOLPY_FLASHSIZE_64MB is not set +# CONFIG_ESPTOOLPY_FLASHSIZE_128MB is not set +CONFIG_ESPTOOLPY_FLASHSIZE="4MB" +# end of Serial flasher config + +# +# Partition Table +# +CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="esp-idf-config/partitions-4MB-no-ota-no-uf2-large-user_fs.csv" +CONFIG_PARTITION_TABLE_FILENAME="esp-idf-config/partitions-4MB-no-ota-no-uf2-large-user_fs.csv" +# end of Partition Table + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/esp-idf-config/sdkconfig-flash-60m.defaults b/ports/espressif/esp-idf-config/sdkconfig-flash-60m.defaults index 7068d0ce740..797665f527f 100644 --- a/ports/espressif/esp-idf-config/sdkconfig-flash-60m.defaults +++ b/ports/espressif/esp-idf-config/sdkconfig-flash-60m.defaults @@ -1,14 +1 @@ -# CONFIG_ESPTOOLPY_FLASHFREQ_120M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_80M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_64M is not set CONFIG_ESPTOOLPY_FLASHFREQ_60M=y -# CONFIG_ESPTOOLPY_FLASHFREQ_48M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_40M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_32M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_30M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_26M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_24M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_20M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_16M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_15M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_80M_DEFAULT is not set diff --git a/ports/espressif/esp-idf-config/sdkconfig-flash-80m.defaults b/ports/espressif/esp-idf-config/sdkconfig-flash-80m.defaults index 2ea44190037..7014fa95495 100644 --- a/ports/espressif/esp-idf-config/sdkconfig-flash-80m.defaults +++ b/ports/espressif/esp-idf-config/sdkconfig-flash-80m.defaults @@ -1,14 +1 @@ -# CONFIG_ESPTOOLPY_FLASHFREQ_120M is not set CONFIG_ESPTOOLPY_FLASHFREQ_80M=y -# CONFIG_ESPTOOLPY_FLASHFREQ_64M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_60M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_48M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_40M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_32M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_30M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_26M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_24M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_20M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_16M is not set -# CONFIG_ESPTOOLPY_FLASHFREQ_15M is not set -CONFIG_ESPTOOLPY_FLASHFREQ_80M_DEFAULT=y diff --git a/ports/espressif/esp-idf-config/sdkconfig-hardwarekey.defaults b/ports/espressif/esp-idf-config/sdkconfig-hardwarekey.defaults new file mode 100644 index 00000000000..64f9c3694fa --- /dev/null +++ b/ports/espressif/esp-idf-config/sdkconfig-hardwarekey.defaults @@ -0,0 +1,14 @@ +# Applied only when CIRCUITPY_HARDWAREKEY=1 (see ports/espressif/Makefile). +# +# A DS-purpose hardwarekey.HardwareKey signs through the ESP32-S2/S3 (and +# C3/C6/H2/P4) Digital Signature peripheral by way of ESP-IDF's PSA opaque +# RSA-DS driver. That driver is only compiled in when this option is set; it +# defaults to "n" upstream. On chips without SOC_DIG_SIGN_SUPPORTED the option +# has an unmet dependency and is ignored. +CONFIG_MBEDTLS_HARDWARE_RSA_DS_PERIPHERAL=y + +# The PSA RSA-DS driver needs RSA + PKCS#1 v1.5 signing wanted in the PSA build. +# Both are ESP-IDF defaults (TLS needs them), set here so a slimmed-down board +# config can't silently drop the DS peripheral. +CONFIG_MBEDTLS_RSA_C=y +CONFIG_MBEDTLS_PKCS1_V15=y diff --git a/ports/espressif/esp-idf-config/sdkconfig-native.defaults b/ports/espressif/esp-idf-config/sdkconfig-native.defaults new file mode 100644 index 00000000000..c3eed046a61 --- /dev/null +++ b/ports/espressif/esp-idf-config/sdkconfig-native.defaults @@ -0,0 +1,15 @@ +# +# Espressif IoT Development Framework Configuration +# +# +# Component config +# +# +# ESP System Settings +# +# CONFIG_ESP_SYSTEM_MEMPROT is not set +# end of ESP System Settings + +# end of Component config + +# end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/esp-idf-config/sdkconfig-opt.defaults b/ports/espressif/esp-idf-config/sdkconfig-opt.defaults index 16f5b990386..0da23e81227 100644 --- a/ports/espressif/esp-idf-config/sdkconfig-opt.defaults +++ b/ports/espressif/esp-idf-config/sdkconfig-opt.defaults @@ -38,6 +38,24 @@ CONFIG_ESP_CONSOLE_SECONDARY_NONE=y CONFIG_LOG_DEFAULT_LEVEL_NONE=y # end of Log output +# +# Log +# +# +# Log Level +# +# +# Level Settings +# +# CONFIG_LOG_DYNAMIC_LEVEL_CONTROL is not set +CONFIG_LOG_TAG_LEVEL_IMPL_NONE=y +# CONFIG_LOG_TAG_LEVEL_IMPL_CACHE_AND_LINKED_LIST is not set +# end of Level Settings + +# end of Log Level + +# end of Log + # end of Component config # end of Espressif IoT Development Framework Configuration diff --git a/ports/espressif/esp-idf-config/sdkconfig-psram-16MB.defaults b/ports/espressif/esp-idf-config/sdkconfig-psram-16MB.defaults new file mode 100644 index 00000000000..f3f2fc60bc6 --- /dev/null +++ b/ports/espressif/esp-idf-config/sdkconfig-psram-16MB.defaults @@ -0,0 +1,5 @@ +# 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 is not set +CONFIG_SPIRAM_TYPE_AUTO=y diff --git a/ports/espressif/esp-idf-config/sdkconfig.defaults b/ports/espressif/esp-idf-config/sdkconfig.defaults index ed914b98995..99caa41ebce 100644 --- a/ports/espressif/esp-idf-config/sdkconfig.defaults +++ b/ports/espressif/esp-idf-config/sdkconfig.defaults @@ -17,9 +17,15 @@ CONFIG_PARTITION_TABLE_CUSTOM=y # GPTimer Configuration # CONFIG_GPTIMER_CTRL_FUNC_IN_IRAM=y -CONFIG_GPTIMER_ISR_IRAM_SAFE=y +CONFIG_GPTIMER_ISR_CACHE_SAFE=y # end of GPTimer Configuration +# +# Touch Configuration +# +CONFIG_TOUCH_SUPPRESS_DEPRECATE_WARN=y +# end of Touch Configuration + # end of Driver Configurations # @@ -59,9 +65,15 @@ CONFIG_ESP_MAIN_TASK_STACK_SIZE=16384 CONFIG_FREERTOS_HZ=1000 # end of Kernel +# +# LibC +# +# end of LibC + # # LWIP # +CONFIG_LWIP_TCPIP_TASK_STACK_SIZE=4096 CONFIG_LWIP_MAX_SOCKETS=8 CONFIG_LWIP_SO_RCVBUF=y # @@ -71,16 +83,6 @@ CONFIG_LWIP_IPV6_AUTOCONFIG=y CONFIG_LWIP_IPV6_RDNSS_MAX_DNS_SERVERS=0 CONFIG_LWIP_IPV6_DHCP6=y # -# TCP -# -CONFIG_LWIP_MAX_ACTIVE_TCP=4 -CONFIG_LWIP_MAX_LISTENING_TCP=4 -CONFIG_LWIP_TCP_SYNMAXRTX=6 -CONFIG_LWIP_TCP_SND_BUF_DEFAULT=2880 -CONFIG_LWIP_TCP_WND_DEFAULT=2880 -CONFIG_LWIP_TCP_RTO_TIME=3000 -# end of TCP - # end of LWIP # @@ -96,9 +98,8 @@ CONFIG_MBEDTLS_SSL_OUT_CONTENT_LEN=2048 # # Certificate Bundle # -CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_NONE=y -CONFIG_MBEDTLS_CUSTOM_CERTIFICATE_BUNDLE=y -CONFIG_MBEDTLS_CUSTOM_CERTIFICATE_BUNDLE_PATH="../../lib/certificates/data/roots.pem" +# CircuitPython ships its own bundle (lib/mbedtls_config/crt_bundle.c) +# CONFIG_MBEDTLS_CERTIFICATE_BUNDLE is not set # end of Certificate Bundle # CONFIG_MBEDTLS_GCM_SUPPORT_NON_AES_CIPHER is not set @@ -115,16 +116,13 @@ CONFIG_MBEDTLS_SSL_PROTO_DTLS=y # CONFIG_MBEDTLS_PEM_WRITE_C is not set # end of Certificates -# CONFIG_MBEDTLS_ECP_DP_SECP192R1_ENABLED is not set -# CONFIG_MBEDTLS_ECP_DP_SECP224R1_ENABLED is not set # CONFIG_MBEDTLS_ECP_DP_SECP521R1_ENABLED is not set -# CONFIG_MBEDTLS_ECP_DP_SECP192K1_ENABLED is not set -# CONFIG_MBEDTLS_ECP_DP_SECP224K1_ENABLED is not set # CONFIG_MBEDTLS_ECP_DP_BP256R1_ENABLED is not set # CONFIG_MBEDTLS_ECP_DP_BP384R1_ENABLED is not set # CONFIG_MBEDTLS_ECP_DP_BP512R1_ENABLED is not set # CONFIG_MBEDTLS_ECP_FIXED_POINT_OPTIM is not set -# CONFIG_MBEDTLS_ERROR_STRINGS is not set +CONFIG_MBEDTLS_ERROR_STRINGS=y +CONFIG_MBEDTLS_AES_FEWER_TABLES=y # end of mbedTLS # @@ -135,6 +133,12 @@ CONFIG_SPI_FLASH_WRITE_CHUNK_SIZE=4096 # CONFIG_SPI_FLASH_ENABLE_ENCRYPTED_READ_WRITE is not set # end of SPI Flash driver +# +# mDNS +# +# CONFIG_MDNS_ENABLE_BROWSE is not set +# end of mDNS + # # Camera configuration # diff --git a/ports/espressif/esp-protocols b/ports/espressif/esp-protocols index 2f492c02289..f1e5cb6868a 160000 --- a/ports/espressif/esp-protocols +++ b/ports/espressif/esp-protocols @@ -1 +1 @@ -Subproject commit 2f492c02289015ecbb36851dd1bd04e0eb0a9937 +Subproject commit f1e5cb6868aa83b6147f1ecc8894aa043392332f diff --git a/ports/espressif/lvgl/lv_conf.h b/ports/espressif/lvgl/lv_conf.h new file mode 100644 index 00000000000..b27603011d6 --- /dev/null +++ b/ports/espressif/lvgl/lv_conf.h @@ -0,0 +1,108 @@ +/** + * LVGL config for CircuitPython on ESP32 P4/S31 + * Based on lv_conf_template.h with P4 optimizations + */ +#ifndef LV_CONF_H +#define LV_CONF_H + +#define LV_USE_OS LV_OS_NONE + +/* Color depth: 16 for RGB565, 32 for ARGB8888 - individual displays set their own + * format when they are created. */ +#define LV_COLOR_FORMAT_DEFAULT LV_COLOR_FORMAT_RGB565 + +/* Memory: allocate from the port heap instead of the garbage collected VM heap. + * Displays live outside the VM, so LVGL allocations must not be collected. */ +#define LV_USE_STDLIB_MALLOC LV_STDLIB_CUSTOM +#define LV_USE_STDLIB_STRING LV_STDLIB_CLIB +#define LV_USE_STDLIB_SPRINTF LV_STDLIB_CLIB + +/* Display and rendering */ +#define LV_USE_DRAW_SW 1 +#define LV_USE_IMAGE 1 +#define LV_USE_LABEL 1 +#define LV_USE_OBJ 1 + +/* Use the ESP32-P4/S31 Pixel Processing Accelerator for fills, blends and simple + * images. PPA works on cache lines, so draw buffers must be 64-byte aligned. */ +#define LV_USE_PPA 1 +#define LV_USE_PPA_IMG 1 +/* Leave regular PSRAM arbitration gaps for the DSI framebuffer scanout DMA. */ +#define LV_PPA_BURST_LENGTH 64 + +/* Rounded rectangles are drawn from cached corner alpha tables, keyed by radius. A rounded + * shape with an outline uses two entries (the outer radius and the inner one), so the default + * of 4 fills up after two shapes with different radii. Each entry is a few hundred bytes to a + * couple of KB, and a UI with a few corner radii then never rasterizes a corner again. */ +#define LV_DRAW_SW_CIRCLE_CACHE_SIZE 8 +/* LVGL 9.6 checks this before defining it, which trips -Wundef. */ +#define LV_PPA_NONBLOCKING_OPS 0 +#define LV_DRAW_BUF_ALIGN 64 +#define CONFIG_LV_DRAW_BUF_ALIGN 64 + +/* displayio hands indexed bitmaps to LVGL as I1/I2/I4/I8 images. Decode them fully + * (instead of line by line) so they can be scaled, and cache the decoded image so it is + * only decoded again when the bitmap or palette changes. An image that doesn't fit in the + * cache isn't drawn. */ +#define LV_BIN_DECODER_RAM_LOAD 1 + +/* The image cache only evicts against its own size limit, and the decoded image is allocated + * before the cache is consulted. A limit anywhere near the 16 MB of PSRAM therefore lets one + * decode exhaust the heap before anything is evicted, and the next small allocation (a draw + * task) fails. With LV_USE_ASSERT_MALLOC off that failure is a NULL dereference, not an error + * message. Keep the limit far below PSRAM: it has to fit the largest single decode (a 720p + * ARGB8888 image is 3.7 MB) with room left for the display buffers and the VM heap. */ +#define LV_CACHE_DEF_SIZE (4 * 1024 * 1024) + +/* A TileGrid composes a changed cell at a time under one batched invalidation, and scroll + * invalidates one object, so a handful of pending areas is plenty. */ +#define LV_INV_BUF_SIZE 64 + +/* Font: use built-in */ +#define LV_FONT_MONTSERRAT_14 1 + +/* Logging */ +#define LV_USE_LOG 0 + +/* displayio draws plain objects with explicit styles, so the themes aren't used. + * The default theme pulls in widgets that this config disables. */ +#define LV_USE_THEME_DEFAULT 0 +#define LV_USE_THEME_SIMPLE 0 +#define LV_USE_THEME_MONO 0 + +/* displayio uses lv_obj, lv_image, lv_canvas (the compose pass draws through a canvas + * layer) and lv_label for text. The rest of the widgets are enabled by default, and many + * of them require each other, so turn them all off to keep the build small and the + * dependency checks happy. */ +#define LV_USE_ANIMIMG 0 +#define LV_USE_ARC 0 +#define LV_USE_ARCLABEL 0 +#define LV_USE_BAR 0 +#define LV_USE_BUTTON 0 +#define LV_USE_BUTTONMATRIX 0 +#define LV_USE_CALENDAR 0 +#define LV_USE_CANVAS 1 +#define LV_USE_CHART 0 +#define LV_USE_CHECKBOX 0 +#define LV_USE_DROPDOWN 0 +#define LV_USE_IMAGEBUTTON 0 +#define LV_USE_KEYBOARD 0 +#define LV_USE_LED 0 +#define LV_USE_LINE 0 +#define LV_USE_LIST 0 +#define LV_USE_MENU 0 +#define LV_USE_MSGBOX 0 +#define LV_USE_ROLLER 0 +#define LV_USE_SCALE 0 +#define LV_USE_SLIDER 0 +#define LV_USE_SPAN 0 +#define LV_USE_SPINBOX 0 +#define LV_USE_SPINNER 0 +#define LV_USE_SWITCH 0 +#define LV_USE_TABLE 0 +#define LV_USE_TABVIEW 0 +#define LV_USE_TEXTAREA 0 +#define LV_USE_TILEVIEW 0 +#define LV_USE_WIN 0 + +#endif diff --git a/ports/espressif/microros-lib b/ports/espressif/microros-lib new file mode 160000 index 00000000000..4b2a696dec7 --- /dev/null +++ b/ports/espressif/microros-lib @@ -0,0 +1 @@ +Subproject commit 4b2a696dec7f0f865e014ea4b83f2332df7e9560 diff --git a/ports/espressif/boards/m5stack_cardputer/cardputer_keyboard.c b/ports/espressif/module/cardputer_keyboard.c similarity index 83% rename from ports/espressif/boards/m5stack_cardputer/cardputer_keyboard.c rename to ports/espressif/module/cardputer_keyboard.c index 73880f66e19..97c7f94e768 100644 --- a/ports/espressif/boards/m5stack_cardputer/cardputer_keyboard.c +++ b/ports/espressif/module/cardputer_keyboard.c @@ -16,7 +16,7 @@ #include "shared-module/keypad_demux/DemuxKeyMatrix.h" #include "supervisor/shared/reload.h" -#include "keymap.h" +#include "cardputer_keymap.h" //| """M5Stack Cardputer keyboard integration. //| """ @@ -31,12 +31,13 @@ //| """" //| KEYBOARD: keypad_demux.DemuxKeymatrix //| -keypad_demux_demuxkeymatrix_obj_t cardputer_keyboard_obj; -bool cardputer_keyboard_serial_attached = false; -void cardputer_keyboard_init(void); -void keyboard_seq(const char *seq); -void update_keyboard(keypad_eventqueue_obj_t *queue); +keypad_demux_demuxkeymatrix_obj_t cardputer_keyboard; +static bool cardputer_keyboard_serial_attached = false; + +// Forward declarations. +static void keyboard_seq(const char *seq); +static void update_keyboard(keypad_eventqueue_obj_t *queue); //| def detach_serial() -> None: //| """Stops consuming keyboard events and routing them to sys.stdin.""" @@ -44,7 +45,7 @@ void update_keyboard(keypad_eventqueue_obj_t *queue); //| static mp_obj_t detach_serial(void) { cardputer_keyboard_serial_attached = false; - common_hal_keypad_eventqueue_set_event_handler(cardputer_keyboard_obj.events, NULL); + common_hal_keypad_eventqueue_set_event_handler(cardputer_keyboard.events, NULL); return mp_const_none; } static MP_DEFINE_CONST_FUN_OBJ_0(detach_serial_obj, detach_serial); @@ -54,7 +55,7 @@ static MP_DEFINE_CONST_FUN_OBJ_0(detach_serial_obj, detach_serial); //| ... //| static mp_obj_t attach_serial(void) { - common_hal_keypad_eventqueue_set_event_handler(cardputer_keyboard_obj.events, update_keyboard); + common_hal_keypad_eventqueue_set_event_handler(cardputer_keyboard.events, update_keyboard); cardputer_keyboard_serial_attached = true; return mp_const_none; } @@ -79,20 +80,20 @@ static mp_obj_t key_to_char(mp_obj_t key_obj, mp_obj_t shifted_obj) { static MP_DEFINE_CONST_FUN_OBJ_2(key_to_char_obj, key_to_char); // Ring buffer of characters consumed from keyboard events (when serial attached) -ringbuf_t keyqueue; -char keybuf[32]; +static ringbuf_t keyqueue; +static char keybuf[32]; keypad_event_obj_t event; -char keystate[56]; +static char keystate[56] = {0}; // Keyboard pins -const mcu_pin_obj_t *row_addr_pins[] = { +static const mcu_pin_obj_t *row_addr_pins[] = { &pin_GPIO8, &pin_GPIO9, &pin_GPIO11, }; -const mcu_pin_obj_t *column_pins[] = { +static const mcu_pin_obj_t *column_pins[] = { &pin_GPIO13, &pin_GPIO15, &pin_GPIO3, @@ -102,21 +103,21 @@ const mcu_pin_obj_t *column_pins[] = { &pin_GPIO7 }; -void cardputer_keyboard_init(void) { - cardputer_keyboard_obj.base.type = &keypad_demux_demuxkeymatrix_type; +static void cardputer_keyboard_init(void) { + cardputer_keyboard.base.type = &keypad_demux_demuxkeymatrix_type; common_hal_keypad_demux_demuxkeymatrix_construct( - &cardputer_keyboard_obj, // self - 3, // num_row_addr_pins - row_addr_pins, // row_addr_pins - 7, // num_column_pins - column_pins, // column_pins - true, // columns_to_anodes - false, // transpose - 0.01f, // interval - 20, // max_events - 2 // debounce_threshold + &cardputer_keyboard, // self + MP_ARRAY_SIZE(row_addr_pins), // num_row_addr_pins + row_addr_pins, // row_addr_pins + MP_ARRAY_SIZE(column_pins), // num_column_pins + column_pins, // column_pins + true, // columns_to_anodes + false, // transpose + 0.01f, // interval + 20, // max_events + 2, // debounce_threshold + false // use_gc_allocator ); - demuxkeymatrix_never_reset(&cardputer_keyboard_obj); ringbuf_init(&keyqueue, (uint8_t *)keybuf, sizeof(keybuf)); attach_serial(); @@ -150,13 +151,13 @@ char board_serial_read(void) { } } -void keyboard_seq(const char *seq) { +static void keyboard_seq(const char *seq) { while (*seq) { ringbuf_put(&keyqueue, *seq++); } } -void update_keyboard(keypad_eventqueue_obj_t *queue) { +static void update_keyboard(keypad_eventqueue_obj_t *queue) { uint8_t ascii = 0; if (common_hal_keypad_eventqueue_get_length(queue) == 0) { @@ -223,7 +224,7 @@ void update_keyboard(keypad_eventqueue_obj_t *queue) { static const mp_rom_map_elem_t cardputer_keyboard_module_globals_table[] = { {MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_cardputer_keyboard)}, - {MP_ROM_QSTR(MP_QSTR_KEYBOARD), MP_ROM_PTR(&cardputer_keyboard_obj)}, + {MP_ROM_QSTR(MP_QSTR_KEYBOARD), MP_ROM_PTR(&cardputer_keyboard)}, {MP_ROM_QSTR(MP_QSTR_attach_serial), MP_ROM_PTR(&attach_serial_obj)}, {MP_ROM_QSTR(MP_QSTR_detach_serial), MP_ROM_PTR(&detach_serial_obj)}, {MP_ROM_QSTR(MP_QSTR_key_to_char), MP_ROM_PTR(&key_to_char_obj)}, diff --git a/ports/espressif/boards/m5stack_cardputer/keymap.h b/ports/espressif/module/cardputer_keymap.h similarity index 100% rename from ports/espressif/boards/m5stack_cardputer/keymap.h rename to ports/espressif/module/cardputer_keymap.h diff --git a/ports/espressif/mpconfigport.h b/ports/espressif/mpconfigport.h index 98c1986240b..6fbdf87a6ff 100644 --- a/ports/espressif/mpconfigport.h +++ b/ports/espressif/mpconfigport.h @@ -17,15 +17,28 @@ #define CIRCUITPY_DIGITALIO_HAVE_INPUT_ONLY (1) +// TinyUSB's host stack runs in a FreeRTOS task of its own that waits on its +// event queue, instead of as a background callback of the VM. Completion +// callbacks then run, and isochronous streams queue their next transfer, while +// the VM is busy. See common-hal/usb_host/Port.c. +#define CIRCUITPY_USB_HOST_TASK (CIRCUITPY_USB_HOST) + #include "py/circuitpy_mpconfig.h" #define MICROPY_NLR_SETJMP (1) #define CIRCUITPY_DEFAULT_STACK_SIZE 0x6000 +// PSRAM can require more stack space for GC. +#define MICROPY_ALLOC_GC_STACK_SIZE (128) + // Nearly all boards have this because it is used to enter the ROM bootloader. #ifndef CIRCUITPY_BOOT_BUTTON - #if defined(CONFIG_IDF_TARGET_ESP32C2) || defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32C6) || defined(CONFIG_IDF_TARGET_ESP32H2) + #if defined(CONFIG_IDF_TARGET_ESP32C2) || defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32C6) || defined(CONFIG_IDF_TARGET_ESP32H2) || defined(CONFIG_IDF_TARGET_ESP32C61) #define CIRCUITPY_BOOT_BUTTON (&pin_GPIO9) + #elif defined(CONFIG_IDF_TARGET_ESP32C5) + #define CIRCUITPY_BOOT_BUTTON (&pin_GPIO28) + #elif defined(CONFIG_IDF_TARGET_ESP32S31) + #define CIRCUITPY_BOOT_BUTTON (&pin_GPIO61) #elif !defined(CONFIG_IDF_TARGET_ESP32) #define CIRCUITPY_BOOT_BUTTON (&pin_GPIO0) #endif @@ -33,6 +46,9 @@ #define CIRCUITPY_INTERNAL_NVM_START_ADDR (0x9000) +// The USB task erases and rewrites a whole 4 kB sector while the VM may run. +#define CIRCUITPY_STORAGE_MAP_GUARD_BLOCKS (4096 / FILESYSTEM_BLOCK_SIZE) + // 20kB is statically allocated to nvs, but when overwriting an existing // item, it's temporarily necessary to store both the old and new copies. // Additionally, there is some overhad for the names and values of items @@ -65,3 +81,13 @@ extern portMUX_TYPE background_task_mutex; #ifndef CIRCUITPY_WIFI_DEFAULT_TX_POWER #define CIRCUITPY_WIFI_DEFAULT_TX_POWER (20) #endif + +#ifndef CIRCUITPY_ESP32P4_SWAP_LSFS +#define CIRCUITPY_ESP32P4_SWAP_LSFS (0) +#endif + +#if MICROPY_PERSISTENT_CODE_LOAD_NATIVE +// Loaded native code is copied out of the GC heap into executable RAM. +void *esp_native_code_commit(void *buf, size_t len, void *reloc); +#define MP_PLAT_COMMIT_EXEC(buf, len, reloc) esp_native_code_commit(buf, len, reloc) +#endif diff --git a/ports/espressif/mpconfigport.mk b/ports/espressif/mpconfigport.mk index c5c1198cd5b..038533d3008 100644 --- a/ports/espressif/mpconfigport.mk +++ b/ports/espressif/mpconfigport.mk @@ -1,15 +1,31 @@ +# This file is part of the CircuitPython project: https://circuitpython.org +# +# SPDX-FileCopyrightText: Copyright (c) 2025 Adafruit Industries +# +# SPDX-License-Identifier: MIT + + ifeq ($(IDF_TARGET),esp32c2) IDF_TARGET_ARCH = riscv CROSS_COMPILE = riscv32-esp-elf- else ifeq ($(IDF_TARGET),esp32c3) IDF_TARGET_ARCH = riscv CROSS_COMPILE = riscv32-esp-elf- +else ifeq ($(IDF_TARGET),esp32c5) +IDF_TARGET_ARCH = riscv +CROSS_COMPILE = riscv32-esp-elf- else ifeq ($(IDF_TARGET),esp32p4) IDF_TARGET_ARCH = riscv CROSS_COMPILE = riscv32-esp-elf- +else ifeq ($(IDF_TARGET),esp32s31) +IDF_TARGET_ARCH = riscv +CROSS_COMPILE = riscv32-esp-elf- else ifeq ($(IDF_TARGET),esp32c6) IDF_TARGET_ARCH = riscv CROSS_COMPILE = riscv32-esp-elf- +else ifeq ($(IDF_TARGET),esp32c61) +IDF_TARGET_ARCH = riscv +CROSS_COMPILE = riscv32-esp-elf- else ifeq ($(IDF_TARGET),esp32h2) IDF_TARGET_ARCH = riscv CROSS_COMPILE = riscv32-esp-elf- @@ -18,44 +34,60 @@ IDF_TARGET_ARCH = xtensa CROSS_COMPILE = xtensa-$(IDF_TARGET)-elf- endif -# Use internal flash for CIRCUITPY drive +# Fast e-paper doesn't fit in flash on the C3, C5 and C6. +ifneq ($(filter $(IDF_TARGET),esp32c3 esp32c5 esp32c6),) +CIRCUITPY_EPAPERDISPLAY_FAST ?= 0 +endif + +# Use "internal flash" for CIRCUITPY drive. +# Even thought it's an external flash chip, it appears as internal. INTERNAL_FLASH_FILESYSTEM = 1 # Internal math library is substantially smaller than toolchain one INTERNAL_LIBM = 0 -# Longints can be implemented as mpz, as longlong, or not +# Longints can be implemented as MPZ, as LONGLONG, or NONE LONGINT_IMPL = MPZ # Default to no-psram CIRCUITPY_ESP_PSRAM_SIZE ?= 0 -# New 4MB boards will not have OTA support but more room for alarm, ble and other -# newer features. -CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT ?= 0 +# Some 4MB non-USB boards were initially defined with 2MB firmware, almost 2MB user_fs partitions. +# Others were defined with 1.4M+1.4M (now a single 2.8MB) firmware partitions / 1.2MB user_fs. +# Keep the former as is, so that the user filesystem will be unchanged. +CIRCUITPY_4MB_FLASH_LARGE_USER_FS_LAYOUT ?= 0 # Enable more features CIRCUITPY_FULL_BUILD ?= 1 +# The 24 KB stack has room for a larger display refresh buffer. +CIRCUITPY_DISPLAY_AREA_BUFFER_SIZE ?= 2048 +CIRCUITPY_BUSIO_SPI_ASYNC ?= 1 + # If SSL is enabled, it's mbedtls CIRCUITPY_SSL_MBEDTLS = 1 -# Wifi Power Save -CIRCUITPY_WIFI_RADIO_SETTABLE_LISTEN_INTERVAL = 1 - # Never use our copy of MBEDTLS CIRCUITPY_HASHLIB_MBEDTLS_ONLY = 0 CIRCUITPY_PORT_SERIAL = 1 +CIRCUITPY_LIB_TLSF = 0 + +CIRCUITPY_LIBC_STRING0 = 0 + # These modules are implemented in ports//common-hal: +CIRCUITPY__EVE ?= 1 CIRCUITPY_ALARM ?= 1 -CIRCUITPY_ALARM_TOUCH ?= 0 +CIRCUITPY_ALARM_PRESERVE_DIOS ?= 1 +CIRCUITPY_ALARM_TOUCH ?= 1 CIRCUITPY_ANALOGBUFIO ?= 1 CIRCUITPY_AUDIOBUSIO ?= 1 -CIRCUITPY_AUDIOBUSIO_PDMIN ?= 0 -CIRCUITPY_AUDIOIO ?= 0 +CIRCUITPY_AUDIOBUSIO_PDMIN ?= 1 +CIRCUITPY_AUDIOI2SIN ?= 1 +CIRCUITPY_AUDIOIO ?= 1 CIRCUITPY_BLEIO_HCI = 0 +CIRCUITPY_BLEIO_NATIVE ?= 1 CIRCUITPY_CANIO ?= 1 CIRCUITPY_COUNTIO ?= 1 CIRCUITPY_ESPCAMERA ?= 1 @@ -63,47 +95,62 @@ CIRCUITPY_ESPIDF ?= 1 CIRCUITPY_ESPULP ?= 1 CIRCUITPY_FRAMEBUFFERIO ?= 1 CIRCUITPY_FREQUENCYIO ?= 1 +CIRCUITPY_HARDWAREKEY ?= 1 +CIRCUITPY_CRYPTOGRAPHY ?= 1 CIRCUITPY_HASHLIB ?= 1 -CIRCUITPY_I2CTARGET ?= 0 +CIRCUITPY_I2CTARGET = 0 CIRCUITPY_MAX3421E ?= 1 CIRCUITPY_MEMORYMAP ?= 1 +CIRCUITPY_RCLCPY ?= 0 CIRCUITPY_NVM ?= 1 CIRCUITPY_PARALLELDISPLAYBUS ?= 1 CIRCUITPY_PS2IO ?= 1 CIRCUITPY_RGBMATRIX ?= 1 CIRCUITPY_ROTARYIO ?= 1 CIRCUITPY_SDIOIO ?= 1 +CIRCUITPY_SETTABLE_PROCESSOR_FREQUENCY ?= 1 CIRCUITPY_SYNTHIO_MAX_CHANNELS ?= 12 +CIRCUITPY_TOUCHIO ?= 1 CIRCUITPY_TOUCHIO_USE_NATIVE ?= 1 CIRCUITPY_WATCHDOG ?= 1 CIRCUITPY_WIFI ?= 1 CIRCUITPY_SOCKETPOOL_IPV6 ?= 1 -# Enable _eve module -CIRCUITPY__EVE ?= 1 - -# Conditionally turn off modules/features +# Conditionally turn off modules/features per chip type +#### esp32 ############################################################ ifeq ($(IDF_TARGET),esp32) # Modules -CIRCUITPY_ALARM_TOUCH = 1 -CIRCUITPY_AUDIOIO = 1 +CIRCUITPY_MII ?= 1 CIRCUITPY_RGBMATRIX = 0 -# SDMMC not supported yet -CIRCUITPY_SDIOIO = 0 +# No HMAC peripheral (introduced starting with ESP32-S2) +CIRCUITPY_HARDWAREKEY = 0 +CIRCUITPY_CRYPTOGRAPHY = 0 -# Features +# Has no USB CIRCUITPY_USB_DEVICE = 0 +#### esp32c2 ########################################################## else ifeq ($(IDF_TARGET),esp32c2) -# C2 ROM spits out the UART at 74880 when connected to a 26mhz crystal! Debug -# prints will default to that too. +# No EMAC hardware +CIRCUITPY_MII = 0 + +# C2 ROM spits out the UART at 74880 when connected to a 26mhz crystal! +# Debug prints will default to that too. # Modules CIRCUITPY_ESPCAMERA = 0 CIRCUITPY_ESPULP = 0 CIRCUITPY_MEMORYMAP = 0 +# No HMAC peripheral (SOC_HMAC_SUPPORTED is not defined for this target) +CIRCUITPY_HARDWAREKEY = 0 +CIRCUITPY_CRYPTOGRAPHY = 0 + +# No capacitive touch peripheral +CIRCUITPY_ALARM_TOUCH = 0 +CIRCUITPY_TOUCHIO_USE_NATIVE = 0 + # No I80 support from the IDF CIRCUITPY_PARALLELDISPLAYBUS = 0 @@ -120,6 +167,10 @@ CIRCUITPY_ANALOGBUFIO = 0 # No I2S CIRCUITPY_AUDIOBUSIO = 0 +CIRCUITPY_AUDIOI2SIN = 0 + +# No DAC +CIRCUITPY_AUDIOIO = 0 # No RMT CIRCUITPY_NEOPIXEL_WRITE = 0 @@ -129,14 +180,14 @@ CIRCUITPY_RGBMATRIX = 0 # No SDMMC CIRCUITPY_SDIOIO = 0 -CIRCUITPY_TOUCHIO ?= 1 -CIRCUITPY_TOUCHIO_USE_NATIVE = 0 # Features CIRCUITPY_USB_DEVICE = 0 CIRCUITPY_ESP_USB_SERIAL_JTAG = 0 +#### esp32c3 ########################################################## else ifeq ($(IDF_TARGET),esp32c3) # Modules +CIRCUITPY_MII = 0 CIRCUITPY_ESPCAMERA = 0 CIRCUITPY_ESPULP = 0 CIRCUITPY_MEMORYMAP = 0 @@ -144,6 +195,17 @@ CIRCUITPY_MEMORYMAP = 0 # No I80 support from the IDF CIRCUITPY_PARALLELDISPLAYBUS = 0 +# No capacitive touch peripheral +CIRCUITPY_ALARM_TOUCH = 0 +CIRCUITPY_TOUCHIO_USE_NATIVE = 0 + +# No DAC +CIRCUITPY_AUDIOIO = 0 + +# No I2S peripheral PDM-to-PCM hardware support +CIRCUITPY_AUDIOBUSIO_PDMIN = 0 +CIRCUITPY_AUDIOI2SIN = 0 + # No PCNT peripheral CIRCUITPY_FREQUENCYIO = 0 CIRCUITPY_COUNTIO = 0 @@ -152,25 +214,107 @@ CIRCUITPY_ROTARYIO = 0 # No SDMMC CIRCUITPY_SDIOIO = 0 -CIRCUITPY_TOUCHIO ?= 1 -CIRCUITPY_TOUCHIO_USE_NATIVE = 0 # Features CIRCUITPY_USB_DEVICE = 0 CIRCUITPY_ESP_USB_SERIAL_JTAG ?= 1 -# No room in flash. -CIRCUITPY_AESIO = 0 -CIRCUITPY_KEYPAD_DEMUX = 0 +#### esp32c5 ########################################################## +else ifeq ($(IDF_TARGET),esp32c5) +# Modules +CIRCUITPY_MII = 0 +CIRCUITPY_ESPCAMERA = 0 +CIRCUITPY_ESPULP = 0 +CIRCUITPY_MEMORYMAP = 0 +CIRCUITPY_RGBMATRIX = 0 + +# TWAI-FD generation, needs a new canio backend +CIRCUITPY_CANIO = 0 + +# No capacitive touch peripheral +CIRCUITPY_ALARM_TOUCH = 0 +CIRCUITPY_TOUCHIO_USE_NATIVE = 0 + +# No DAC +CIRCUITPY_AUDIOIO = 0 + +# No I2S peripheral PDM-to-PCM hardware support +CIRCUITPY_AUDIOBUSIO_PDMIN = 0 + +# No LCD_CAM peripheral, so no esp_lcd_new_i80_bus() +CIRCUITPY_PARALLELDISPLAYBUS = 0 + +# No SDMMC +CIRCUITPY_SDIOIO = 0 + +# Fit the 2MB firmware partition +CIRCUITPY_ULAB_OPTIMIZE_SIZE ?= 1 +CIRCUITPY_MESSAGE_COMPRESSION_LEVEL ?= 9 + +# Features +CIRCUITPY_USB_DEVICE = 0 +CIRCUITPY_ESP_USB_SERIAL_JTAG ?= 1 +#### esp32c6 ########################################################## else ifeq ($(IDF_TARGET),esp32c6) # Modules +CIRCUITPY_MII = 0 CIRCUITPY_ESPCAMERA = 0 CIRCUITPY_ESPULP = 0 CIRCUITPY_MEMORYMAP = 0 CIRCUITPY_RGBMATRIX = 0 +# No capacitive touch peripheral +CIRCUITPY_ALARM_TOUCH = 0 +CIRCUITPY_TOUCHIO_USE_NATIVE = 0 + +# No DAC +CIRCUITPY_AUDIOIO = 0 + +# No I2S peripheral PDM-to-PCM hardware support +CIRCUITPY_AUDIOBUSIO_PDMIN = 0 + +# No I80 support from the IDF +CIRCUITPY_PARALLELDISPLAYBUS = 0 + +# No SDMMC +CIRCUITPY_SDIOIO = 0 + +# Save flash +CIRCUITPY_MESSAGE_COMPRESSION_LEVEL ?= 9 + +# Fit the 2MB firmware partition. Only 4MB boards on the default +# layout get a 2816K firmware partition. +ifneq ($(CIRCUITPY_ESP_FLASH_SIZE)$(CIRCUITPY_4MB_FLASH_LARGE_USER_FS_LAYOUT),4MB0) +CIRCUITPY_ULAB_OPTIMIZE_SIZE ?= 1 +endif + +# Features +CIRCUITPY_USB_DEVICE = 0 +CIRCUITPY_ESP_USB_SERIAL_JTAG ?= 1 + +#### esp32c61######################################################### +else ifeq ($(IDF_TARGET),esp32c61) +# Modules +CIRCUITPY_MII = 0 +CIRCUITPY_ESPCAMERA = 0 +CIRCUITPY_ESPULP = 0 +CIRCUITPY_MEMORYMAP = 0 +CIRCUITPY_RGBMATRIX = 0 + +# No HMAC peripheral (SOC_HMAC_SUPPORTED is not defined for this target) +CIRCUITPY_HARDWAREKEY = 0 +CIRCUITPY_CRYPTOGRAPHY = 0 + +# No capacitive touch peripheral +CIRCUITPY_ALARM_TOUCH = 0 +CIRCUITPY_TOUCHIO_USE_NATIVE = 0 + +# No DAC +CIRCUITPY_AUDIOIO = 0 + # No space for this CIRCUITPY_AUDIOBUSIO = 0 +CIRCUITPY_AUDIOI2SIN = 0 # No I80 support from the IDF CIRCUITPY_PARALLELDISPLAYBUS = 0 @@ -178,28 +322,48 @@ CIRCUITPY_PARALLELDISPLAYBUS = 0 # No SDMMC CIRCUITPY_SDIOIO = 0 -CIRCUITPY_TOUCHIO ?= 1 -CIRCUITPY_TOUCHIO_USE_NATIVE = 0 # Features CIRCUITPY_USB_DEVICE = 0 CIRCUITPY_ESP_USB_SERIAL_JTAG ?= 1 +# No TWAI on chip +CIRCUITPY_CANIO = 0 + +# No RMT on chip +CIRCUITPY_NEOPIXEL_WRITE = 0 +CIRCUITPY_PULSEIO = 0 +CIRCUITPY_RGBMATRIX = 0 + +# No PCNT on chip +CIRCUITPY_COUNTIO = 0 +CIRCUITPY_ROTARYIO = 0 +CIRCUITPY_FREQUENCYIO = 0 + +#### esp32h2 ########################################################## else ifeq ($(IDF_TARGET),esp32h2) # Modules +CIRCUITPY_MII = 0 CIRCUITPY_ESPCAMERA = 0 CIRCUITPY_ESPULP = 0 CIRCUITPY_MEMORYMAP = 0 CIRCUITPY_RGBMATRIX = 0 +# No capacitive touch peripheral +CIRCUITPY_ALARM_TOUCH = 0 +CIRCUITPY_TOUCHIO_USE_NATIVE = 0 + +# No DAC +CIRCUITPY_AUDIOIO = 0 + +# No I2S peripheral PDM-to-PCM hardware support +CIRCUITPY_AUDIOBUSIO_PDMIN = 0 + # No I80 support from the IDF CIRCUITPY_PARALLELDISPLAYBUS = 0 # No SDMMC CIRCUITPY_SDIOIO = 0 -CIRCUITPY_TOUCHIO ?= 1 -CIRCUITPY_TOUCHIO_USE_NATIVE = 0 - # Features CIRCUITPY_USB_DEVICE = 0 CIRCUITPY_ESP_USB_SERIAL_JTAG ?= 1 @@ -207,24 +371,63 @@ CIRCUITPY_WIFI = 0 CIRCUITPY_MAX3421E = 0 +#### esp32p4 ########################################################## else ifeq ($(IDF_TARGET),esp32p4) -# No wifi -# TODO: Support ESP32-C6 coprocessor on some boards. -CIRCUITPY_BLEIO = 0 -CIRCUITPY_WIFI = 0 -CIRCUITPY_SSL = 0 +# No DAC +CIRCUITPY_AUDIOIO = 0 +CIRCUITPY_AUDIOFILTERS ?= 1 +CIRCUITPY_AUDIOTAP ?= 1 +CIRCUITPY_USB_HOST_AUDIO ?= $(CIRCUITPY_USB_HOST) + +# MII is available on these targets with EMAC hardware. +CIRCUITPY_MII ?= 1 + +# Optional ESP-Hosted Wi-Fi coprocessor. +CIRCUITPY_ESP_HOSTED ?= 0 +CIRCUITPY_ESPNOW = 0 +CIRCUITPY_BLEIO_NATIVE = 0 +CIRCUITPY_WIFI = $(CIRCUITPY_ESP_HOSTED) +CIRCUITPY_SSL = $(CIRCUITPY_ESP_HOSTED) + +# The P4 has two USB device controllers. Controller 0 is the full-speed one with +# 7 endpoints, only 5 of which can be IN. Controller 1 is the high-speed one with +# 16 endpoints, 8 of which can be IN. Boards name the controller they use with +# CIRCUITPY_USB_DEVICE_INSTANCE in their mpconfigboard.mk so they don't have to +# know which number is which. Map the name to the number the C code needs. +ifneq ($(filter 1 HIGH_SPEED_INSTANCE,$(CIRCUITPY_USB_DEVICE_INSTANCE)),) +USB_DEVICE_INSTANCE_NUM := 1 +else +USB_DEVICE_INSTANCE_NUM := 0 +endif +CFLAGS += -DCIRCUITPY_USB_DEVICE_INSTANCE=$(USB_DEVICE_INSTANCE_NUM) -CIRCUITPY_TOUCHIO = 1 -CIRCUITPY_TOUCHIO_USE_NATIVE = 0 +# The high-speed controller is the second instance. +CIRCUITPY_USB_DEVICE_HIGH_SPEED := $(USB_DEVICE_INSTANCE_NUM) +CFLAGS += -DCIRCUITPY_USB_DEVICE_HIGH_SPEED=$(CIRCUITPY_USB_DEVICE_HIGH_SPEED) + +ifeq ($(USB_DEVICE_INSTANCE_NUM),1) +USB_NUM_ENDPOINT_PAIRS = 16 +USB_NUM_IN_ENDPOINTS = 8 +else +USB_NUM_ENDPOINT_PAIRS = 7 +USB_NUM_IN_ENDPOINTS = 5 +endif -# Second stage bootloader doesn't work when the factory partition is empty due to -# UF2 missing. -UF2_BOOTLOADER = 0 -USB_HIGHSPEED = 1 +# The full-speed controller's IN endpoints are already mostly spoken for, so HID, +# MIDI and UVC stay compiled out. The high-speed controller has room for all three, +# so turn them on there. +ifeq ($(CIRCUITPY_USB_DEVICE_HIGH_SPEED),1) +CIRCUITPY_USB_HID ?= 1 +CIRCUITPY_USB_MIDI ?= 1 +CIRCUITPY_USB_VIDEO ?= 1 +else CIRCUITPY_USB_HID = 0 CIRCUITPY_USB_MIDI = 0 +endif + CIRCUITPY_TUSB_MEM_ALIGN = 64 +CIRCUITPY_ALL_MEMORY_DMA_CAPABLE = 0 CIRCUITPY_MAX3421E = 0 @@ -243,80 +446,159 @@ CIRCUITPY_PARALLELDISPLAYBUS = 0 # Library doesn't support P4 yet it seems CIRCUITPY_ESPCAMERA = 0 +# P4 has MIPI-DSI +CIRCUITPY_MIPIDSI = 1 +CIRCUITPY_DISPLAYIO_LVGL = 1 +CFLAGS += -DLV_CONF_INCLUDE_SIMPLE + +# P4 has MIPI-CSI +CIRCUITPY_MIPICSI = 1 + +# P4 can play MIPI-CSI video into MIPI-DSI framebuffers +CIRCUITPY_VIDEOCORE = 1 + +# Hardware JPEG decoder +CIRCUITPY_JPEGIO_HW ?= $(CIRCUITPY_JPEGIO) + +#### esp32s31 ######################################################### +else ifeq ($(IDF_TARGET),esp32s31) + +# No DAC +CIRCUITPY_AUDIOIO = 0 + +# No wifi or BLE yet +CIRCUITPY_BLEIO_NATIVE = 0 +CIRCUITPY_WIFI = 0 +CIRCUITPY_SSL = 0 + +CIRCUITPY_TUSB_MEM_ALIGN = 64 +CIRCUITPY_ALL_MEMORY_DMA_CAPABLE = 0 +CIRCUITPY_MAX3421E = 0 + +# The IDF has no ADC calibration scheme for the S31 yet. +CIRCUITPY_ANALOGBUFIO = 0 +CIRCUITPY_ANALOGIO = 0 + +# Update this for multiple TWAI? +CIRCUITPY_CANIO = 0 + +# Library doesn't support S31 yet +CIRCUITPY_ESPCAMERA = 0 + +# The S31 has an LP core, not a ULP FSM or ULP RISC-V. +CIRCUITPY_ESPULP = 0 + +# The S31 has five eFuse key blocks, not six. +CIRCUITPY_HARDWAREKEY = 0 +# DigitalSignatureKey takes a HardwareKey, so it's meaningless without one. +CIRCUITPY_CRYPTOGRAPHY = 0 + +# Hardware JPEG decoder +CIRCUITPY_JPEGIO_HW ?= $(CIRCUITPY_JPEGIO) + +# No I80 support from the IDF +CIRCUITPY_PARALLELDISPLAYBUS = 0 + +# Protomatter needs an update +CIRCUITPY_RGBMATRIX = 0 + +# Touch readings saturate at 65535 on every pad. +CIRCUITPY_ALARM_TOUCH = 0 +CIRCUITPY_TOUCHIO = 0 +CIRCUITPY_TOUCHIO_USE_NATIVE = 0 +CIRCUITPY_DISPLAYIO_LVGL = 1 +CFLAGS += -DLV_CONF_INCLUDE_SIMPLE + +#### esp32s2 ########################################################## else ifeq ($(IDF_TARGET),esp32s2) # Modules -CIRCUITPY_ALARM_TOUCH = 1 -CIRCUITPY_AUDIOIO = 1 +CIRCUITPY_MII = 0 +CIRCUITPY_AUDIOIO ?= 1 +CIRCUITPY_AUDIOFILEWRITER ?= 1 + +# LEDC + GPTimer PWM audio, for boards whose speaker is not on a DAC pin. +CIRCUITPY_AUDIOPWMIO ?= 1 + +# No I2S peripheral PDM-to-PCM hardware support +CIRCUITPY_AUDIOBUSIO_PDMIN = 0 + # No BLE in hw -CIRCUITPY_BLEIO = 0 +CIRCUITPY_BLEIO_NATIVE = 0 # No SDMMC CIRCUITPY_SDIOIO = 0 CIRCUITPY_ESP_USB_SERIAL_JTAG ?= 0 +#### esp32s3 ########################################################## else ifeq ($(IDF_TARGET),esp32s3) + +# No EMAC hardware +CIRCUITPY_MII = 0 + # Modules -CIRCUITPY_ALARM_TOUCH = 1 -CIRCUITPY_AUDIOBUSIO_PDMIN = 1 CIRCUITPY_ESP_USB_SERIAL_JTAG ?= 0 -# No room for _bleio on boards with 4MB flash -ifeq ($(CIRCUITPY_ESP_FLASH_SIZE),4MB) -CIRCUITPY_BLEIO ?= 0 -endif +# No DAC +CIRCUITPY_AUDIOIO = 0 -endif +# LEDC + GPTimer PWM audio, the only analog audio output without I2S hardware. +CIRCUITPY_AUDIOPWMIO ?= 1 -# bitmapfilter does not fit on 4MB boards unless they are set up as camera boards -ifeq ($(CIRCUITPY_ESP_FLASH_SIZE),4MB) -CIRCUITPY_BITMAPFILTER ?= 0 -OPTIMIZATION_FLAGS ?= -Os -CIRCUITPY_DUALBANK ?= 0 -else -CIRCUITPY_DUALBANK ?= 1 -endif +# PIE vector instructions for audiomixer. +CIRCUITPY_AUDIOMIXER_USE_PORT_MIX ?= 1 -# We used to default to OTA partition layout but are moving away from it so that -# BLE and alarm can be included. This setting prevents the partition layout from -# changing. -ifeq ($(CIRCUITPY_LEGACY_4MB_FLASH_LAYOUT), 1) -ifeq ($(IDF_TARGET_ARCH), xtensa) - CIRCUITPY_ALARM ?= 1 -else -CIRCUITPY_ALARM = 0 -endif -CIRCUITPY_DUALBANK = 1 -CIRCUITPY_BLEIO ?= 0 -CIRCUITPY_SETTABLE_PROCESSOR_FREQUENCY = 0 -else -CIRCUITPY_SETTABLE_PROCESSOR_FREQUENCY = 1 endif +#### end chip-specific choices ######################################## + +# By default, load native .mpy files. Boards without the flash space turn it off. +CIRCUITPY_LOAD_NATIVE ?= 1 -# No room for dualbank or mp3 on boards with 2MB flash +# By default, enable dualbank, and it'll be disabled for small flash sizes +CIRCUITPY_DUALBANK ?= 1 + +# No room for large modules on 2MB boards +# 2MB boards have a single firmware partition, and can't do dualbank. ifeq ($(CIRCUITPY_ESP_FLASH_SIZE),2MB) -CIRCUITPY_BITMAPFILTER ?= 0 -CIRCUITPY_DUALBANK = 0 +CIRCUITPY__EVE = 0 CIRCUITPY_AUDIOMP3 = 0 -CIRCUITPY_BLEIO ?= 0 +CIRCUITPY_BITMAPFILTER = 0 +CIRCUITPY_BLEIO_NATIVE = 0 +CIRCUITPY_DUALBANK = 0 +CIRCUITPY_MAX3421E = 0 +CIRCUITPY_RGBMATRIX = 0 +CIRCUITPY_SETTABLE_PROCESSOR_FREQUENCY = 0 +OPTIMIZATION_FLAGS ?= -Os endif -# No room for _eve on boards with 4MB flash +# 4MB boards have a single firmware partition, and can't do dualbank. ifeq ($(CIRCUITPY_ESP_FLASH_SIZE),4MB) -CIRCUITPY__EVE = 0 +CIRCUITPY_DUALBANK = 0 +OPTIMIZATION_FLAGS ?= -Os endif -# default BLEIO after flash-size based defaults -CIRCUITPY_BLEIO ?= 1 +# espcamera does not work on boards without SPIRAM +ifeq ($(CIRCUITPY_ESP_PSRAM_SIZE),0) +CIRCUITPY_ESPCAMERA = 0 +endif # Modules dependent on other modules CIRCUITPY_ESPNOW ?= $(CIRCUITPY_WIFI) CIRCUITPY_GIFIO ?= $(CIRCUITPY_DISPLAYIO) CIRCUITPY_JPEGIO ?= $(CIRCUITPY_DISPLAYIO) +CIRCUITPY_BITMAPTOOLS_FAST_ROTOZOOM ?= $(CIRCUITPY_BITMAPTOOLS) CIRCUITPY_QRIO ?= $(CIRCUITPY_ESPCAMERA) -CIRCUITPY_BLE_FILE_SERVICE ?= $(CIRCUITPY_BLEIO) -CIRCUITPY_SERIAL_BLE ?= $(CIRCUITPY_BLEIO) +# The ESP32-S3 decodes JPEGs faster with esp_new_jpeg. It needs PSRAM for its +# buffers. It adds about 75 KB, so a board short on flash can turn it off. +ifeq ($(IDF_TARGET),esp32s3) +ifneq ($(CIRCUITPY_ESP_PSRAM_SIZE),0) +CIRCUITPY_JPEGIO_FAST ?= $(CIRCUITPY_JPEGIO) +endif +endif + +CIRCUITPY_BLE_FILE_SERVICE ?= $(CIRCUITPY_BLEIO_NATIVE) +CIRCUITPY_BLE_SERIAL_SERVICE ?= $(CIRCUITPY_BLEIO_NATIVE) # Features dependent on other features ifneq ($(CIRCUITPY_USB_DEVICE),0) @@ -334,8 +616,26 @@ endif # Due to the limited number of endpoints, some USB devices will be off by default. # For instance MIDI is available, but the device is turned off. It can be turned on # only if something else is turned off, such as HID. -USB_NUM_ENDPOINT_PAIRS = 7 -USB_NUM_IN_ENDPOINTS = 5 +# +# Targets and boards with different USB controllers override these. +USB_NUM_ENDPOINT_PAIRS ?= 7 +USB_NUM_IN_ENDPOINTS ?= 5 + +# usb_audio is compiled in on the S3 but claims no endpoints until +# usb_audio.enable() is called from boot.py, so enabling it by default does not +# affect existing boards. Freeing one IN endpoint (usb_hid.disable()) is then the +# only thing a user needs, with no custom build. +ifeq ($(IDF_TARGET),esp32s3) +# It needs the TinyUSB device stack and audiocore, so leave it off for boards +# that turn either off. CIRCUITPY_AUDIOCORE is not set yet at this point, so +# boards that drop audio are recognized by CIRCUITPY_AUDIOBUSIO = 0 instead. +ifeq ($(filter 0,$(CIRCUITPY_USB_DEVICE) $(CIRCUITPY_AUDIOCORE) $(CIRCUITPY_AUDIOBUSIO)),) +CIRCUITPY_USB_AUDIO ?= 1 +endif +endif # Usually lots of flash space available CIRCUITPY_MESSAGE_COMPRESSION_LEVEL ?= 1 + +# The CIRCUITPY partition is mapped into the data address space on first use +CIRCUITPY_STORAGE_MAP_FILE ?= 1 diff --git a/ports/espressif/mphalport.c b/ports/espressif/mphalport.c index 87b16ac3e4c..9046bbf7b10 100644 --- a/ports/espressif/mphalport.c +++ b/ports/espressif/mphalport.c @@ -8,25 +8,7 @@ #include "py/mphal.h" #include "supervisor/cpu.h" -#if defined(CONFIG_IDF_TARGET_ESP32) -#include "components/esp_rom/include/esp32/rom/ets_sys.h" -#elif defined(CONFIG_IDF_TARGET_ESP32C2) -#include "components/esp_rom/include/esp32c2/rom/ets_sys.h" -#elif defined(CONFIG_IDF_TARGET_ESP32P4) -#include "components/esp_rom/include/esp32p4/rom/ets_sys.h" -#elif defined(CONFIG_IDF_TARGET_ESP32C3) -#include "components/esp_rom/include/esp32c3/rom/ets_sys.h" -#elif defined(CONFIG_IDF_TARGET_ESP32C6) -#include "components/esp_rom/include/esp32c6/rom/ets_sys.h" -#elif defined(CONFIG_IDF_TARGET_ESP32H2) -#include "components/esp_rom/include/esp32h2/rom/ets_sys.h" -#elif defined(CONFIG_IDF_TARGET_ESP32S2) -#include "components/esp_rom/include/esp32s2/rom/ets_sys.h" -#elif defined(CONFIG_IDF_TARGET_ESP32S3) -#include "components/esp_rom/include/esp32s3/rom/ets_sys.h" -#else -#error Unknown CONFIG_IDF_TARGET_xxx -#endif +#include "rom/ets_sys.h" #include "esp_attr.h" @@ -39,7 +21,6 @@ void IRAM_ATTR mp_hal_delay_us(mp_uint_t delay) { // This is provided by the esp-idf/components/xtensa/esp32s2/libhal.a binary blob. #ifndef CONFIG_IDF_TARGET_ARCH_RISCV extern void xthal_window_spill(void); -#endif mp_uint_t cpu_get_regs_and_sp(mp_uint_t *regs) { // xtensa has more registers than an instruction can address. The 16 that @@ -55,8 +36,7 @@ mp_uint_t cpu_get_regs_and_sp(mp_uint_t *regs) { // there is a HAL call to do it. There is a bit of a race condition here // 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. - #ifndef CONFIG_IDF_TARGET_ARCH_RISCV xthal_window_spill(); - #endif - return (mp_uint_t)__builtin_frame_address(0); + return (mp_uint_t)__builtin_stack_address(); } +#endif diff --git a/ports/espressif/peripherals/esp32/pins.c b/ports/espressif/peripherals/esp32/pins.c index e2c45bd06fc..3aa12c9e675 100644 --- a/ports/espressif/peripherals/esp32/pins.c +++ b/ports/espressif/peripherals/esp32/pins.c @@ -6,11 +6,11 @@ #include "peripherals/pins.h" -const mcu_pin_obj_t pin_GPIO0 = PIN(0, ADC_UNIT_2, ADC_CHANNEL_1, TOUCH_PAD_NUM1); +const mcu_pin_obj_t pin_GPIO0 = PIN(0, ADC_UNIT_2, ADC_CHANNEL_1, 1); const mcu_pin_obj_t pin_GPIO1 = PIN(1, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); -const mcu_pin_obj_t pin_GPIO2 = PIN(2, ADC_UNIT_2, ADC_CHANNEL_2, TOUCH_PAD_NUM2); +const mcu_pin_obj_t pin_GPIO2 = PIN(2, ADC_UNIT_2, ADC_CHANNEL_2, 2); const mcu_pin_obj_t pin_GPIO3 = PIN(3, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); -const mcu_pin_obj_t pin_GPIO4 = PIN(4, ADC_UNIT_2, ADC_CHANNEL_0, TOUCH_PAD_NUM0); +const mcu_pin_obj_t pin_GPIO4 = PIN(4, ADC_UNIT_2, ADC_CHANNEL_0, 0); const mcu_pin_obj_t pin_GPIO5 = PIN(5, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); const mcu_pin_obj_t pin_GPIO6 = PIN(6, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); const mcu_pin_obj_t pin_GPIO7 = PIN(7, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); @@ -18,10 +18,10 @@ const mcu_pin_obj_t pin_GPIO8 = PIN(8, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL) const mcu_pin_obj_t pin_GPIO9 = PIN(9, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); const mcu_pin_obj_t pin_GPIO10 = PIN(10, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); const mcu_pin_obj_t pin_GPIO11 = PIN(11, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); -const mcu_pin_obj_t pin_GPIO12 = PIN(12, ADC_UNIT_2, ADC_CHANNEL_5, TOUCH_PAD_NUM5); -const mcu_pin_obj_t pin_GPIO13 = PIN(13, ADC_UNIT_2, ADC_CHANNEL_4, TOUCH_PAD_NUM4); -const mcu_pin_obj_t pin_GPIO14 = PIN(14, ADC_UNIT_2, ADC_CHANNEL_6, TOUCH_PAD_NUM6); -const mcu_pin_obj_t pin_GPIO15 = PIN(15, ADC_UNIT_2, ADC_CHANNEL_3, TOUCH_PAD_NUM3); +const mcu_pin_obj_t pin_GPIO12 = PIN(12, ADC_UNIT_2, ADC_CHANNEL_5, 5); +const mcu_pin_obj_t pin_GPIO13 = PIN(13, ADC_UNIT_2, ADC_CHANNEL_4, 4); +const mcu_pin_obj_t pin_GPIO14 = PIN(14, ADC_UNIT_2, ADC_CHANNEL_6, 6); +const mcu_pin_obj_t pin_GPIO15 = PIN(15, ADC_UNIT_2, ADC_CHANNEL_3, 3); const mcu_pin_obj_t pin_GPIO16 = PIN(16, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); const mcu_pin_obj_t pin_GPIO17 = PIN(17, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); const mcu_pin_obj_t pin_GPIO18 = PIN(18, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); @@ -34,13 +34,13 @@ const mcu_pin_obj_t pin_GPIO23 = PIN(23, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNE // no GPIO24 const mcu_pin_obj_t pin_GPIO25 = PIN(25, ADC_UNIT_2, ADC_CHANNEL_8, NO_TOUCH_CHANNEL); const mcu_pin_obj_t pin_GPIO26 = PIN(26, ADC_UNIT_2, ADC_CHANNEL_9, NO_TOUCH_CHANNEL); -const mcu_pin_obj_t pin_GPIO27 = PIN(27, ADC_UNIT_2, ADC_CHANNEL_7, TOUCH_PAD_NUM7); +const mcu_pin_obj_t pin_GPIO27 = PIN(27, ADC_UNIT_2, ADC_CHANNEL_7, 7); // no GPIO28 // no GPIO29 // no GPIO30 // no GPIO31 -const mcu_pin_obj_t pin_GPIO32 = PIN(32, ADC_UNIT_1, ADC_CHANNEL_4, TOUCH_PAD_NUM9); -const mcu_pin_obj_t pin_GPIO33 = PIN(33, ADC_UNIT_1, ADC_CHANNEL_5, TOUCH_PAD_NUM8); +const mcu_pin_obj_t pin_GPIO32 = PIN(32, ADC_UNIT_1, ADC_CHANNEL_4, 9); +const mcu_pin_obj_t pin_GPIO33 = PIN(33, ADC_UNIT_1, ADC_CHANNEL_5, 8); const mcu_pin_obj_t pin_GPIO34 = PIN(34, ADC_UNIT_1, ADC_CHANNEL_6, NO_TOUCH_CHANNEL); const mcu_pin_obj_t pin_GPIO35 = PIN(35, ADC_UNIT_1, ADC_CHANNEL_7, NO_TOUCH_CHANNEL); const mcu_pin_obj_t pin_GPIO36 = PIN(36, ADC_UNIT_1, ADC_CHANNEL_0, NO_TOUCH_CHANNEL); diff --git a/ports/espressif/peripherals/esp32c5/pins.c b/ports/espressif/peripherals/esp32c5/pins.c new file mode 100644 index 00000000000..2abf905e18f --- /dev/null +++ b/ports/espressif/peripherals/esp32c5/pins.c @@ -0,0 +1,37 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 microDev +// +// SPDX-License-Identifier: MIT + +#include "peripherals/pins.h" + +const mcu_pin_obj_t pin_GPIO0 = PIN(0, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO1 = PIN(1, ADC_UNIT_1, ADC_CHANNEL_0, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO2 = PIN(2, ADC_UNIT_1, ADC_CHANNEL_1, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO3 = PIN(3, ADC_UNIT_1, ADC_CHANNEL_2, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO4 = PIN(4, ADC_UNIT_1, ADC_CHANNEL_3, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO5 = PIN(5, ADC_UNIT_1, ADC_CHANNEL_4, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO6 = PIN(6, ADC_UNIT_1, ADC_CHANNEL_5, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO7 = PIN(7, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO8 = PIN(8, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO9 = PIN(9, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO10 = PIN(10, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO11 = PIN(11, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO12 = PIN(12, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO13 = PIN(13, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO14 = PIN(14, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO15 = PIN(15, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO16 = PIN(16, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO17 = PIN(17, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO18 = PIN(18, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO19 = PIN(19, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO20 = PIN(20, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO21 = PIN(21, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO22 = PIN(22, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO23 = PIN(23, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO24 = PIN(24, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO25 = PIN(25, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO26 = PIN(26, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO27 = PIN(27, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO28 = PIN(28, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); diff --git a/ports/espressif/peripherals/esp32c5/pins.h b/ports/espressif/peripherals/esp32c5/pins.h new file mode 100644 index 00000000000..90c28621791 --- /dev/null +++ b/ports/espressif/peripherals/esp32c5/pins.h @@ -0,0 +1,70 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2023 Scott Shawcroft for Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +// DO NOT include this file directly. +// Use shared-bindings/microcontroller/Pin.h instead. +// This ensures that all necessary includes are already included. + +#pragma once + +#define GPIO0_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO0; +#define GPIO1_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO1; +#define GPIO2_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO2; +#define GPIO3_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO3; +#define GPIO4_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO4; +#define GPIO5_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO5; +#define GPIO6_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO6; +#define GPIO7_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO7; +#define GPIO8_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO8; +#define GPIO9_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO9; +#define GPIO10_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO10; +#define GPIO11_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO11; +#define GPIO12_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO12; +#define GPIO13_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO13; +#define GPIO14_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO14; +#define GPIO15_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO15; +#define GPIO16_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO16; +#define GPIO17_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO17; +#define GPIO18_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO18; +#define GPIO19_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO19; +#define GPIO20_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO20; +#define GPIO21_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO21; +#define GPIO22_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO22; +#define GPIO23_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO23; +#define GPIO24_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO24; +#define GPIO25_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO25; +#define GPIO26_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO26; +#define GPIO27_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO27; +#define GPIO28_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO28; diff --git a/ports/espressif/peripherals/esp32c61/pins.c b/ports/espressif/peripherals/esp32c61/pins.c new file mode 100644 index 00000000000..a32e1e8da98 --- /dev/null +++ b/ports/espressif/peripherals/esp32c61/pins.c @@ -0,0 +1,38 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 microDev +// +// SPDX-License-Identifier: MIT + +#include "peripherals/pins.h" + +const mcu_pin_obj_t pin_GPIO0 = PIN(0, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO1 = PIN(1, ADC_UNIT_1, ADC_CHANNEL_0, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO2 = PIN(2, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO3 = PIN(3, ADC_UNIT_1, ADC_CHANNEL_1, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO4 = PIN(4, ADC_UNIT_1, ADC_CHANNEL_2, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO5 = PIN(5, ADC_UNIT_1, ADC_CHANNEL_3, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO6 = PIN(6, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO7 = PIN(7, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO8 = PIN(8, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO9 = PIN(9, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO10 = PIN(10, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO11 = PIN(11, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO12 = PIN(12, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO13 = PIN(13, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO14 = PIN(14, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO15 = PIN(15, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO16 = PIN(16, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO17 = PIN(17, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO18 = PIN(18, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO19 = PIN(19, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO20 = PIN(20, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO21 = PIN(21, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO22 = PIN(22, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO23 = PIN(23, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO24 = PIN(24, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO25 = PIN(25, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO26 = PIN(26, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO27 = PIN(27, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO28 = PIN(28, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO29 = PIN(29, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); diff --git a/ports/espressif/peripherals/esp32c61/pins.h b/ports/espressif/peripherals/esp32c61/pins.h new file mode 100644 index 00000000000..908c9fe29f0 --- /dev/null +++ b/ports/espressif/peripherals/esp32c61/pins.h @@ -0,0 +1,72 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2023 Scott Shawcroft for Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +// DO NOT include this file directly. +// Use shared-bindings/microcontroller/Pin.h instead. +// This ensures that all necessary includes are already included. + +#pragma once + +#define GPIO0_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO0; +#define GPIO1_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO1; +#define GPIO2_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO2; +#define GPIO3_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO3; +#define GPIO4_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO4; +#define GPIO5_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO5; +#define GPIO6_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO6; +#define GPIO7_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO7; +#define GPIO8_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO8; +#define GPIO9_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO9; +#define GPIO10_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO10; +#define GPIO11_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO11; +#define GPIO12_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO12; +#define GPIO13_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO13; +#define GPIO14_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO14; +#define GPIO15_EXISTS 0 +extern const mcu_pin_obj_t pin_GPIO15; +#define GPIO16_EXISTS 0 +extern const mcu_pin_obj_t pin_GPIO16; +#define GPIO17_EXISTS 0 +extern const mcu_pin_obj_t pin_GPIO17; +#define GPIO18_EXISTS 0 +extern const mcu_pin_obj_t pin_GPIO18; +#define GPIO19_EXISTS 0 +extern const mcu_pin_obj_t pin_GPIO19; +#define GPIO20_EXISTS 0 +extern const mcu_pin_obj_t pin_GPIO20; +#define GPIO21_EXISTS 0 +extern const mcu_pin_obj_t pin_GPIO21; +#define GPIO22_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO22; +#define GPIO23_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO23; +#define GPIO24_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO24; +#define GPIO25_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO25; +#define GPIO26_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO26; +#define GPIO27_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO27; +#define GPIO28_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO28; +#define GPIO29_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO29; diff --git a/ports/espressif/peripherals/esp32p4/pins.c b/ports/espressif/peripherals/esp32p4/pins.c index 24e509d40c6..97de6b4e486 100644 --- a/ports/espressif/peripherals/esp32p4/pins.c +++ b/ports/espressif/peripherals/esp32p4/pins.c @@ -8,20 +8,20 @@ const mcu_pin_obj_t pin_GPIO0 = PIN(0, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); const mcu_pin_obj_t pin_GPIO1 = PIN(1, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); -const mcu_pin_obj_t pin_GPIO2 = PIN(2, NO_ADC, NO_ADC_CHANNEL, TOUCH_PAD_NUM0); -const mcu_pin_obj_t pin_GPIO3 = PIN(3, NO_ADC, NO_ADC_CHANNEL, TOUCH_PAD_NUM1); -const mcu_pin_obj_t pin_GPIO4 = PIN(4, NO_ADC, NO_ADC_CHANNEL, TOUCH_PAD_NUM2); -const mcu_pin_obj_t pin_GPIO5 = PIN(5, NO_ADC, NO_ADC_CHANNEL, TOUCH_PAD_NUM3); -const mcu_pin_obj_t pin_GPIO6 = PIN(6, NO_ADC, NO_ADC_CHANNEL, TOUCH_PAD_NUM4); -const mcu_pin_obj_t pin_GPIO7 = PIN(7, NO_ADC, NO_ADC_CHANNEL, TOUCH_PAD_NUM5); -const mcu_pin_obj_t pin_GPIO8 = PIN(8, NO_ADC, NO_ADC_CHANNEL, TOUCH_PAD_NUM6); -const mcu_pin_obj_t pin_GPIO9 = PIN(9, NO_ADC, NO_ADC_CHANNEL, TOUCH_PAD_NUM7); -const mcu_pin_obj_t pin_GPIO10 = PIN(10, NO_ADC, NO_ADC_CHANNEL, TOUCH_PAD_NUM8); -const mcu_pin_obj_t pin_GPIO11 = PIN(11, NO_ADC, NO_ADC_CHANNEL, TOUCH_PAD_NUM9); -const mcu_pin_obj_t pin_GPIO12 = PIN(12, NO_ADC, NO_ADC_CHANNEL, TOUCH_PAD_NUM10); -const mcu_pin_obj_t pin_GPIO13 = PIN(13, NO_ADC, NO_ADC_CHANNEL, TOUCH_PAD_NUM11); -const mcu_pin_obj_t pin_GPIO14 = PIN(14, NO_ADC, NO_ADC_CHANNEL, TOUCH_PAD_NUM12); -const mcu_pin_obj_t pin_GPIO15 = PIN(15, NO_ADC, NO_ADC_CHANNEL, TOUCH_PAD_NUM13); +const mcu_pin_obj_t pin_GPIO2 = PIN(2, NO_ADC, NO_ADC_CHANNEL, 1); +const mcu_pin_obj_t pin_GPIO3 = PIN(3, NO_ADC, NO_ADC_CHANNEL, 2); +const mcu_pin_obj_t pin_GPIO4 = PIN(4, NO_ADC, NO_ADC_CHANNEL, 3); +const mcu_pin_obj_t pin_GPIO5 = PIN(5, NO_ADC, NO_ADC_CHANNEL, 4); +const mcu_pin_obj_t pin_GPIO6 = PIN(6, NO_ADC, NO_ADC_CHANNEL, 5); +const mcu_pin_obj_t pin_GPIO7 = PIN(7, NO_ADC, NO_ADC_CHANNEL, 6); +const mcu_pin_obj_t pin_GPIO8 = PIN(8, NO_ADC, NO_ADC_CHANNEL, 7); +const mcu_pin_obj_t pin_GPIO9 = PIN(9, NO_ADC, NO_ADC_CHANNEL, 8); +const mcu_pin_obj_t pin_GPIO10 = PIN(10, NO_ADC, NO_ADC_CHANNEL, 9); +const mcu_pin_obj_t pin_GPIO11 = PIN(11, NO_ADC, NO_ADC_CHANNEL, 10); +const mcu_pin_obj_t pin_GPIO12 = PIN(12, NO_ADC, NO_ADC_CHANNEL, 11); +const mcu_pin_obj_t pin_GPIO13 = PIN(13, NO_ADC, NO_ADC_CHANNEL, 12); +const mcu_pin_obj_t pin_GPIO14 = PIN(14, NO_ADC, NO_ADC_CHANNEL, 13); +const mcu_pin_obj_t pin_GPIO15 = PIN(15, NO_ADC, NO_ADC_CHANNEL, 14); const mcu_pin_obj_t pin_GPIO16 = PIN(16, ADC_UNIT_1, ADC_CHANNEL_0, NO_TOUCH_CHANNEL); const mcu_pin_obj_t pin_GPIO17 = PIN(17, ADC_UNIT_1, ADC_CHANNEL_1, NO_TOUCH_CHANNEL); const mcu_pin_obj_t pin_GPIO18 = PIN(18, ADC_UNIT_1, ADC_CHANNEL_2, NO_TOUCH_CHANNEL); @@ -55,9 +55,13 @@ const mcu_pin_obj_t pin_GPIO45 = PIN(45, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNE const mcu_pin_obj_t pin_GPIO46 = PIN(46, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); const mcu_pin_obj_t pin_GPIO47 = PIN(47, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); const mcu_pin_obj_t pin_GPIO48 = PIN(48, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); -const mcu_pin_obj_t pin_GPIO49 = PIN(49, ADC_UNIT_2, ADC_CHANNEL_2, NO_TOUCH_CHANNEL); -const mcu_pin_obj_t pin_GPIO50 = PIN(50, ADC_UNIT_2, ADC_CHANNEL_3, NO_TOUCH_CHANNEL); -const mcu_pin_obj_t pin_GPIO51 = PIN(51, ADC_UNIT_2, ADC_CHANNEL_4, NO_TOUCH_CHANNEL); -const mcu_pin_obj_t pin_GPIO52 = PIN(52, ADC_UNIT_2, ADC_CHANNEL_5, NO_TOUCH_CHANNEL); -const mcu_pin_obj_t pin_GPIO53 = PIN(53, ADC_UNIT_2, ADC_CHANNEL_6, NO_TOUCH_CHANNEL); -const mcu_pin_obj_t pin_GPIO54 = PIN(54, ADC_UNIT_2, ADC_CHANNEL_7, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO49 = PIN(49, ADC_UNIT_2, ADC_CHANNEL_0, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO50 = PIN(50, ADC_UNIT_2, ADC_CHANNEL_1, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO51 = PIN(51, ADC_UNIT_2, ADC_CHANNEL_2, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO52 = PIN(52, ADC_UNIT_2, ADC_CHANNEL_3, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO53 = PIN(53, ADC_UNIT_2, ADC_CHANNEL_4, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO54 = PIN(54, ADC_UNIT_2, ADC_CHANNEL_5, NO_TOUCH_CHANNEL); + +// The USB high-speed PHY pads cannot be used as GPIOs. +const mcu_pin_obj_t pin_USB_HS_DP = PIN(NO_PIN, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_USB_HS_DM = PIN(NO_PIN, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); diff --git a/ports/espressif/peripherals/esp32p4/pins.h b/ports/espressif/peripherals/esp32p4/pins.h index 59cf4258a40..7f9f7717c88 100644 --- a/ports/espressif/peripherals/esp32p4/pins.h +++ b/ports/espressif/peripherals/esp32p4/pins.h @@ -120,3 +120,6 @@ extern const mcu_pin_obj_t pin_GPIO52; extern const mcu_pin_obj_t pin_GPIO53; #define GPIO54_EXISTS 1 extern const mcu_pin_obj_t pin_GPIO54; + +extern const mcu_pin_obj_t pin_USB_HS_DP; +extern const mcu_pin_obj_t pin_USB_HS_DM; diff --git a/ports/espressif/peripherals/esp32s2/pins.c b/ports/espressif/peripherals/esp32s2/pins.c index b5e8d483175..cfaecd0ac6d 100644 --- a/ports/espressif/peripherals/esp32s2/pins.c +++ b/ports/espressif/peripherals/esp32s2/pins.c @@ -7,20 +7,20 @@ #include "peripherals/pins.h" const mcu_pin_obj_t pin_GPIO0 = PIN(0, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); -const mcu_pin_obj_t pin_GPIO1 = PIN(1, ADC_UNIT_1, ADC_CHANNEL_0, TOUCH_PAD_NUM1); -const mcu_pin_obj_t pin_GPIO2 = PIN(2, ADC_UNIT_1, ADC_CHANNEL_1, TOUCH_PAD_NUM2); -const mcu_pin_obj_t pin_GPIO3 = PIN(3, ADC_UNIT_1, ADC_CHANNEL_2, TOUCH_PAD_NUM3); -const mcu_pin_obj_t pin_GPIO4 = PIN(4, ADC_UNIT_1, ADC_CHANNEL_3, TOUCH_PAD_NUM4); -const mcu_pin_obj_t pin_GPIO5 = PIN(5, ADC_UNIT_1, ADC_CHANNEL_4, TOUCH_PAD_NUM5); -const mcu_pin_obj_t pin_GPIO6 = PIN(6, ADC_UNIT_1, ADC_CHANNEL_5, TOUCH_PAD_NUM6); -const mcu_pin_obj_t pin_GPIO7 = PIN(7, ADC_UNIT_1, ADC_CHANNEL_6, TOUCH_PAD_NUM7); -const mcu_pin_obj_t pin_GPIO8 = PIN(8, ADC_UNIT_1, ADC_CHANNEL_7, TOUCH_PAD_NUM8); -const mcu_pin_obj_t pin_GPIO9 = PIN(9, ADC_UNIT_1, ADC_CHANNEL_8, TOUCH_PAD_NUM9); -const mcu_pin_obj_t pin_GPIO10 = PIN(10, ADC_UNIT_1, ADC_CHANNEL_9, TOUCH_PAD_NUM10); -const mcu_pin_obj_t pin_GPIO11 = PIN(11, ADC_UNIT_2, ADC_CHANNEL_0, TOUCH_PAD_NUM11); -const mcu_pin_obj_t pin_GPIO12 = PIN(12, ADC_UNIT_2, ADC_CHANNEL_1, TOUCH_PAD_NUM12); -const mcu_pin_obj_t pin_GPIO13 = PIN(13, ADC_UNIT_2, ADC_CHANNEL_2, TOUCH_PAD_NUM13); -const mcu_pin_obj_t pin_GPIO14 = PIN(14, ADC_UNIT_2, ADC_CHANNEL_3, TOUCH_PAD_NUM14); +const mcu_pin_obj_t pin_GPIO1 = PIN(1, ADC_UNIT_1, ADC_CHANNEL_0, 1); +const mcu_pin_obj_t pin_GPIO2 = PIN(2, ADC_UNIT_1, ADC_CHANNEL_1, 2); +const mcu_pin_obj_t pin_GPIO3 = PIN(3, ADC_UNIT_1, ADC_CHANNEL_2, 3); +const mcu_pin_obj_t pin_GPIO4 = PIN(4, ADC_UNIT_1, ADC_CHANNEL_3, 4); +const mcu_pin_obj_t pin_GPIO5 = PIN(5, ADC_UNIT_1, ADC_CHANNEL_4, 5); +const mcu_pin_obj_t pin_GPIO6 = PIN(6, ADC_UNIT_1, ADC_CHANNEL_5, 6); +const mcu_pin_obj_t pin_GPIO7 = PIN(7, ADC_UNIT_1, ADC_CHANNEL_6, 7); +const mcu_pin_obj_t pin_GPIO8 = PIN(8, ADC_UNIT_1, ADC_CHANNEL_7, 8); +const mcu_pin_obj_t pin_GPIO9 = PIN(9, ADC_UNIT_1, ADC_CHANNEL_8, 9); +const mcu_pin_obj_t pin_GPIO10 = PIN(10, ADC_UNIT_1, ADC_CHANNEL_9, 10); +const mcu_pin_obj_t pin_GPIO11 = PIN(11, ADC_UNIT_2, ADC_CHANNEL_0, 11); +const mcu_pin_obj_t pin_GPIO12 = PIN(12, ADC_UNIT_2, ADC_CHANNEL_1, 12); +const mcu_pin_obj_t pin_GPIO13 = PIN(13, ADC_UNIT_2, ADC_CHANNEL_2, 13); +const mcu_pin_obj_t pin_GPIO14 = PIN(14, ADC_UNIT_2, ADC_CHANNEL_3, 14); const mcu_pin_obj_t pin_GPIO15 = PIN(15, ADC_UNIT_2, ADC_CHANNEL_4, NO_TOUCH_CHANNEL); const mcu_pin_obj_t pin_GPIO16 = PIN(16, ADC_UNIT_2, ADC_CHANNEL_5, NO_TOUCH_CHANNEL); const mcu_pin_obj_t pin_GPIO17 = PIN(17, ADC_UNIT_2, ADC_CHANNEL_6, NO_TOUCH_CHANNEL); diff --git a/ports/espressif/peripherals/esp32s3/pins.c b/ports/espressif/peripherals/esp32s3/pins.c index c51c4b93575..745cb4a7a67 100644 --- a/ports/espressif/peripherals/esp32s3/pins.c +++ b/ports/espressif/peripherals/esp32s3/pins.c @@ -9,20 +9,20 @@ // NOTE: These numbers do NOT always match the package and module pin number. // These are by solely by GPIO numbers. const mcu_pin_obj_t pin_GPIO0 = PIN(0, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); -const mcu_pin_obj_t pin_GPIO1 = PIN(1, ADC_UNIT_1, ADC_CHANNEL_0, TOUCH_PAD_NUM1); -const mcu_pin_obj_t pin_GPIO2 = PIN(2, ADC_UNIT_1, ADC_CHANNEL_1, TOUCH_PAD_NUM2); -const mcu_pin_obj_t pin_GPIO3 = PIN(3, ADC_UNIT_1, ADC_CHANNEL_2, TOUCH_PAD_NUM3); -const mcu_pin_obj_t pin_GPIO4 = PIN(4, ADC_UNIT_1, ADC_CHANNEL_3, TOUCH_PAD_NUM4); -const mcu_pin_obj_t pin_GPIO5 = PIN(5, ADC_UNIT_1, ADC_CHANNEL_4, TOUCH_PAD_NUM5); -const mcu_pin_obj_t pin_GPIO6 = PIN(6, ADC_UNIT_1, ADC_CHANNEL_5, TOUCH_PAD_NUM6); -const mcu_pin_obj_t pin_GPIO7 = PIN(7, ADC_UNIT_1, ADC_CHANNEL_6, TOUCH_PAD_NUM7); -const mcu_pin_obj_t pin_GPIO8 = PIN(8, ADC_UNIT_1, ADC_CHANNEL_7, TOUCH_PAD_NUM8); -const mcu_pin_obj_t pin_GPIO9 = PIN(9, ADC_UNIT_1, ADC_CHANNEL_8, TOUCH_PAD_NUM9); -const mcu_pin_obj_t pin_GPIO10 = PIN(10, ADC_UNIT_1, ADC_CHANNEL_9, TOUCH_PAD_NUM10); -const mcu_pin_obj_t pin_GPIO11 = PIN(11, ADC_UNIT_2, ADC_CHANNEL_0, TOUCH_PAD_NUM11); -const mcu_pin_obj_t pin_GPIO12 = PIN(12, ADC_UNIT_2, ADC_CHANNEL_1, TOUCH_PAD_NUM12); -const mcu_pin_obj_t pin_GPIO13 = PIN(13, ADC_UNIT_2, ADC_CHANNEL_2, TOUCH_PAD_NUM13); -const mcu_pin_obj_t pin_GPIO14 = PIN(14, ADC_UNIT_2, ADC_CHANNEL_3, TOUCH_PAD_NUM14); +const mcu_pin_obj_t pin_GPIO1 = PIN(1, ADC_UNIT_1, ADC_CHANNEL_0, 1); +const mcu_pin_obj_t pin_GPIO2 = PIN(2, ADC_UNIT_1, ADC_CHANNEL_1, 2); +const mcu_pin_obj_t pin_GPIO3 = PIN(3, ADC_UNIT_1, ADC_CHANNEL_2, 3); +const mcu_pin_obj_t pin_GPIO4 = PIN(4, ADC_UNIT_1, ADC_CHANNEL_3, 4); +const mcu_pin_obj_t pin_GPIO5 = PIN(5, ADC_UNIT_1, ADC_CHANNEL_4, 5); +const mcu_pin_obj_t pin_GPIO6 = PIN(6, ADC_UNIT_1, ADC_CHANNEL_5, 6); +const mcu_pin_obj_t pin_GPIO7 = PIN(7, ADC_UNIT_1, ADC_CHANNEL_6, 7); +const mcu_pin_obj_t pin_GPIO8 = PIN(8, ADC_UNIT_1, ADC_CHANNEL_7, 8); +const mcu_pin_obj_t pin_GPIO9 = PIN(9, ADC_UNIT_1, ADC_CHANNEL_8, 9); +const mcu_pin_obj_t pin_GPIO10 = PIN(10, ADC_UNIT_1, ADC_CHANNEL_9, 10); +const mcu_pin_obj_t pin_GPIO11 = PIN(11, ADC_UNIT_2, ADC_CHANNEL_0, 11); +const mcu_pin_obj_t pin_GPIO12 = PIN(12, ADC_UNIT_2, ADC_CHANNEL_1, 12); +const mcu_pin_obj_t pin_GPIO13 = PIN(13, ADC_UNIT_2, ADC_CHANNEL_2, 13); +const mcu_pin_obj_t pin_GPIO14 = PIN(14, ADC_UNIT_2, ADC_CHANNEL_3, 14); const mcu_pin_obj_t pin_GPIO15 = PIN(15, ADC_UNIT_2, ADC_CHANNEL_4, NO_TOUCH_CHANNEL); const mcu_pin_obj_t pin_GPIO16 = PIN(16, ADC_UNIT_2, ADC_CHANNEL_5, NO_TOUCH_CHANNEL); const mcu_pin_obj_t pin_GPIO17 = PIN(17, ADC_UNIT_2, ADC_CHANNEL_6, NO_TOUCH_CHANNEL); diff --git a/ports/espressif/peripherals/esp32s31/pins.c b/ports/espressif/peripherals/esp32s31/pins.c new file mode 100644 index 00000000000..360ac82b75b --- /dev/null +++ b/ports/espressif/peripherals/esp32s31/pins.c @@ -0,0 +1,68 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#include "peripherals/pins.h" + +// GPIO26-28 and GPIO30-32 are the SPI flash pads and are not exposed. +// GPIO29 and GPIO41 do not exist. +const mcu_pin_obj_t pin_GPIO0 = PIN(0, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO1 = PIN(1, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO2 = PIN(2, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO3 = PIN(3, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO4 = PIN(4, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO5 = PIN(5, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO6 = PIN(6, NO_ADC, NO_ADC_CHANNEL, 0); +const mcu_pin_obj_t pin_GPIO7 = PIN(7, NO_ADC, NO_ADC_CHANNEL, 1); +const mcu_pin_obj_t pin_GPIO8 = PIN(8, NO_ADC, NO_ADC_CHANNEL, 2); +const mcu_pin_obj_t pin_GPIO9 = PIN(9, NO_ADC, NO_ADC_CHANNEL, 3); +const mcu_pin_obj_t pin_GPIO10 = PIN(10, NO_ADC, NO_ADC_CHANNEL, 4); +const mcu_pin_obj_t pin_GPIO11 = PIN(11, NO_ADC, NO_ADC_CHANNEL, 5); +const mcu_pin_obj_t pin_GPIO12 = PIN(12, NO_ADC, NO_ADC_CHANNEL, 6); +const mcu_pin_obj_t pin_GPIO13 = PIN(13, NO_ADC, NO_ADC_CHANNEL, 7); +const mcu_pin_obj_t pin_GPIO14 = PIN(14, NO_ADC, NO_ADC_CHANNEL, 8); +const mcu_pin_obj_t pin_GPIO15 = PIN(15, NO_ADC, NO_ADC_CHANNEL, 9); +const mcu_pin_obj_t pin_GPIO16 = PIN(16, NO_ADC, NO_ADC_CHANNEL, 10); +const mcu_pin_obj_t pin_GPIO17 = PIN(17, NO_ADC, NO_ADC_CHANNEL, 11); +const mcu_pin_obj_t pin_GPIO18 = PIN(18, NO_ADC, NO_ADC_CHANNEL, 12); +const mcu_pin_obj_t pin_GPIO19 = PIN(19, NO_ADC, NO_ADC_CHANNEL, 13); +const mcu_pin_obj_t pin_GPIO20 = PIN(20, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO21 = PIN(21, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO22 = PIN(22, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO23 = PIN(23, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO24 = PIN(24, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO25 = PIN(25, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO33 = PIN(33, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO34 = PIN(34, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO35 = PIN(35, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO36 = PIN(36, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO37 = PIN(37, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO38 = PIN(38, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO39 = PIN(39, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO40 = PIN(40, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO42 = PIN(42, ADC_UNIT_1, ADC_CHANNEL_0, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO43 = PIN(43, ADC_UNIT_1, ADC_CHANNEL_1, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO44 = PIN(44, ADC_UNIT_1, ADC_CHANNEL_2, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO45 = PIN(45, ADC_UNIT_1, ADC_CHANNEL_3, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO46 = PIN(46, ADC_UNIT_1, ADC_CHANNEL_4, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO47 = PIN(47, ADC_UNIT_1, ADC_CHANNEL_5, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO48 = PIN(48, ADC_UNIT_1, ADC_CHANNEL_6, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO49 = PIN(49, ADC_UNIT_1, ADC_CHANNEL_7, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO50 = PIN(50, ADC_UNIT_2, ADC_CHANNEL_0, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO51 = PIN(51, ADC_UNIT_2, ADC_CHANNEL_1, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO52 = PIN(52, ADC_UNIT_2, ADC_CHANNEL_2, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO53 = PIN(53, ADC_UNIT_2, ADC_CHANNEL_3, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO54 = PIN(54, ADC_UNIT_2, ADC_CHANNEL_4, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO55 = PIN(55, ADC_UNIT_2, ADC_CHANNEL_5, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO56 = PIN(56, ADC_UNIT_2, ADC_CHANNEL_6, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO57 = PIN(57, ADC_UNIT_2, ADC_CHANNEL_7, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO58 = PIN(58, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO59 = PIN(59, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO60 = PIN(60, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_GPIO61 = PIN(61, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); + +// The USB high-speed PHY pads cannot be used as GPIOs. +const mcu_pin_obj_t pin_USB_HS_DP = PIN(NO_PIN, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); +const mcu_pin_obj_t pin_USB_HS_DM = PIN(NO_PIN, NO_ADC, NO_ADC_CHANNEL, NO_TOUCH_CHANNEL); diff --git a/ports/espressif/peripherals/esp32s31/pins.h b/ports/espressif/peripherals/esp32s31/pins.h new file mode 100644 index 00000000000..28eba010245 --- /dev/null +++ b/ports/espressif/peripherals/esp32s31/pins.h @@ -0,0 +1,123 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +// DO NOT include this file directly. +// Use shared-bindings/microcontroller/Pin.h instead. +// This ensures that all necessary includes are already included. + +#pragma once + +#define GPIO0_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO0; +#define GPIO1_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO1; +#define GPIO2_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO2; +#define GPIO3_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO3; +#define GPIO4_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO4; +#define GPIO5_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO5; +#define GPIO6_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO6; +#define GPIO7_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO7; +#define GPIO8_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO8; +#define GPIO9_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO9; +#define GPIO10_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO10; +#define GPIO11_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO11; +#define GPIO12_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO12; +#define GPIO13_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO13; +#define GPIO14_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO14; +#define GPIO15_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO15; +#define GPIO16_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO16; +#define GPIO17_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO17; +#define GPIO18_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO18; +#define GPIO19_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO19; +#define GPIO20_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO20; +#define GPIO21_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO21; +#define GPIO22_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO22; +#define GPIO23_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO23; +#define GPIO24_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO24; +#define GPIO25_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO25; +#define GPIO33_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO33; +#define GPIO34_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO34; +#define GPIO35_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO35; +#define GPIO36_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO36; +#define GPIO37_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO37; +#define GPIO38_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO38; +#define GPIO39_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO39; +#define GPIO40_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO40; +#define GPIO42_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO42; +#define GPIO43_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO43; +#define GPIO44_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO44; +#define GPIO45_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO45; +#define GPIO46_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO46; +#define GPIO47_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO47; +#define GPIO48_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO48; +#define GPIO49_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO49; +#define GPIO50_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO50; +#define GPIO51_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO51; +#define GPIO52_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO52; +#define GPIO53_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO53; +#define GPIO54_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO54; +#define GPIO55_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO55; +#define GPIO56_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO56; +#define GPIO57_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO57; +#define GPIO58_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO58; +#define GPIO59_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO59; +#define GPIO60_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO60; +#define GPIO61_EXISTS 1 +extern const mcu_pin_obj_t pin_GPIO61; + +extern const mcu_pin_obj_t pin_USB_HS_DP; +extern const mcu_pin_obj_t pin_USB_HS_DM; diff --git a/ports/espressif/peripherals/pins.h b/ports/espressif/peripherals/pins.h index f89855e308f..c0e832370af 100644 --- a/ports/espressif/peripherals/pins.h +++ b/ports/espressif/peripherals/pins.h @@ -12,16 +12,15 @@ #include "py/obj.h" -#include "components/hal/include/hal/gpio_types.h" -#include "components/hal/include/hal/adc_types.h" -#include "components/hal/include/hal/touch_sensor_types.h" +#include "hal/gpio_types.h" +#include "hal/adc_types.h" typedef struct { mp_obj_base_t base; gpio_num_t number; uint8_t adc_index : 2; uint8_t adc_channel : 6; - touch_pad_t touch_channel; + int8_t touch_channel; } mcu_pin_obj_t; extern const mp_obj_type_t mcu_pin_type; @@ -31,7 +30,7 @@ extern const mp_obj_type_t mcu_pin_type; #define NO_ADC SOC_ADC_PERIPH_NUM #define NO_ADC_CHANNEL SOC_ADC_MAX_CHANNEL_NUM -#define NO_TOUCH_CHANNEL TOUCH_PAD_MAX +#define NO_TOUCH_CHANNEL (-1) // This macro is used to simplify pin definition in peripherals//pins.c #define PIN(p_number, p_adc_index, p_adc_channel, p_touch_channel) \ @@ -50,8 +49,12 @@ extern const mp_obj_type_t mcu_pin_type; #include "esp32c2/pins.h" #elif defined(CONFIG_IDF_TARGET_ESP32C3) #include "esp32c3/pins.h" +#elif defined(CONFIG_IDF_TARGET_ESP32C5) +#include "esp32c5/pins.h" #elif defined(CONFIG_IDF_TARGET_ESP32C6) #include "esp32c6/pins.h" +#elif defined(CONFIG_IDF_TARGET_ESP32C61) +#include "esp32c61/pins.h" #elif defined(CONFIG_IDF_TARGET_ESP32P4) #include "esp32p4/pins.h" #elif defined(CONFIG_IDF_TARGET_ESP32H2) @@ -60,4 +63,6 @@ extern const mp_obj_type_t mcu_pin_type; #include "esp32s2/pins.h" #elif defined(CONFIG_IDF_TARGET_ESP32S3) #include "esp32s3/pins.h" +#elif defined(CONFIG_IDF_TARGET_ESP32S31) +#include "esp32s31/pins.h" #endif diff --git a/ports/espressif/peripherals/touch.c b/ports/espressif/peripherals/touch.c index 71340d94371..ce4283a3af2 100644 --- a/ports/espressif/peripherals/touch.c +++ b/ports/espressif/peripherals/touch.c @@ -4,54 +4,224 @@ // // SPDX-License-Identifier: MIT -#include "py/gc.h" #include "peripherals/touch.h" -static bool touch_inited = false; -static bool touch_never_reset = false; +static touch_sensor_handle_t touch_controller = NULL; +static touch_channel_handle_t touch_channels[TOUCH_TOTAL_CHAN_NUM] = {NULL}; +static bool touch_enabled = false; +static bool touch_scanning = false; + +static int chan_index(int channel_id) { + return channel_id - TOUCH_MIN_CHAN_ID; +} + +touch_sensor_handle_t peripherals_touch_get_controller(void) { + return touch_controller; +} + +touch_channel_handle_t peripherals_touch_get_handle(int channel_id) { + return touch_channels[chan_index(channel_id)]; +} + +void peripherals_touch_deinit(const int channel_id) { + int idx = chan_index(channel_id); + + if (touch_channels[idx] == NULL) { + return; + } + + // ESP-IDF deletes channels only while the controller is disabled. + if (touch_scanning) { + touch_sensor_stop_continuous_scanning(touch_controller); + touch_scanning = false; + } + if (touch_enabled) { + touch_sensor_disable(touch_controller); + touch_enabled = false; + } + + touch_sensor_del_channel(touch_channels[idx]); + touch_channels[idx] = NULL; + + bool any_channel = false; + for (unsigned int i = 0; i < TOUCH_TOTAL_CHAN_NUM; i++) { + if (touch_channels[i] != NULL) { + any_channel = true; + break; + } + } + + if (any_channel) { + // Resume scanning the remaining channels. + if (touch_sensor_enable(touch_controller) == ESP_OK) { + touch_enabled = true; + if (touch_sensor_start_continuous_scanning(touch_controller) == ESP_OK) { + touch_scanning = true; + } + } + return; + } + + touch_sensor_del_controller(touch_controller); + touch_controller = NULL; +} void peripherals_touch_reset(void) { - if (touch_inited && !touch_never_reset) { - touch_pad_deinit(); - touch_inited = false; + if (touch_controller != NULL) { + if (touch_scanning) { + touch_sensor_stop_continuous_scanning(touch_controller); + touch_scanning = false; + } + if (touch_enabled) { + touch_sensor_disable(touch_controller); + touch_enabled = false; + } + for (unsigned int i = 0; i < TOUCH_TOTAL_CHAN_NUM; i++) { + if (touch_channels[i] != NULL) { + touch_sensor_del_channel(touch_channels[i]); + touch_channels[i] = NULL; + } + } + touch_sensor_del_controller(touch_controller); + touch_controller = NULL; } } -void peripherals_touch_never_reset(const bool enable) { - touch_never_reset = enable; +static esp_err_t first_error(esp_err_t first, esp_err_t second) { + return first != ESP_OK ? first : second; } -void peripherals_touch_init(const touch_pad_t touchpad) { - if (!touch_inited) { - touch_pad_init(); - touch_pad_set_fsm_mode(TOUCH_FSM_MODE_TIMER); +esp_err_t peripherals_touch_init(const int channel_id) { + int idx = chan_index(channel_id); + + // Already initialized this channel + if (touch_channels[idx] != NULL) { + return ESP_OK; + } + + esp_err_t err; + + // Stop scanning and disable before modifying channels + if (touch_scanning) { + err = touch_sensor_stop_continuous_scanning(touch_controller); + if (err != ESP_OK) { + return err; + } + touch_scanning = false; + } + if (touch_enabled) { + err = touch_sensor_disable(touch_controller); + if (err != ESP_OK) { + return err; + } + touch_enabled = false; } - // touch_pad_config() must be done before touch_pad_fsm_start() the first time. - // Otherwise the calibration is wrong and we get maximum raw values if there is - // a trace of any significant length on the pin. - #if defined(CONFIG_IDF_TARGET_ESP32) - touch_pad_config(touchpad, 0); + + if (touch_controller == NULL) { + #if SOC_TOUCH_SENSOR_VERSION == 1 + touch_sensor_sample_config_t sample_cfg = TOUCH_SENSOR_V1_DEFAULT_SAMPLE_CONFIG(5.0, TOUCH_VOLT_LIM_L_0V5, TOUCH_VOLT_LIM_H_1V7); + #elif SOC_TOUCH_SENSOR_VERSION == 2 + touch_sensor_sample_config_t sample_cfg = TOUCH_SENSOR_V2_DEFAULT_SAMPLE_CONFIG(500, TOUCH_VOLT_LIM_L_0V5, TOUCH_VOLT_LIM_H_2V2); + #elif SOC_TOUCH_SENSOR_VERSION == 3 + touch_sensor_sample_config_t sample_cfg = TOUCH_SENSOR_V3_DEFAULT_SAMPLE_CONFIG2(3, 29, 8, 3); + #else + #error bad SOC_TOUCH_SENSOR_VERSION + #endif + touch_sensor_config_t sens_cfg = TOUCH_SENSOR_DEFAULT_BASIC_CONFIG(1, &sample_cfg); + err = touch_sensor_new_controller(&sens_cfg, &touch_controller); + if (err != ESP_OK) { + return err; + } + } + + #if SOC_TOUCH_SENSOR_VERSION == 1 + touch_channel_config_t chan_cfg = { + .abs_active_thresh = {1000}, + .charge_speed = TOUCH_CHARGE_SPEED_7, + .init_charge_volt = TOUCH_INIT_CHARGE_VOLT_DEFAULT, + .group = TOUCH_CHAN_TRIG_GROUP_BOTH, + }; + #elif SOC_TOUCH_SENSOR_VERSION == 2 + touch_channel_config_t chan_cfg = { + .active_thresh = {2000}, + .charge_speed = TOUCH_CHARGE_SPEED_7, + .init_charge_volt = TOUCH_INIT_CHARGE_VOLT_DEFAULT, + }; + #elif SOC_TOUCH_SENSOR_VERSION == 3 + // Values are similar to an ESP-IDF example: 1000, 2500, 5000. + touch_channel_config_t chan_cfg = { + .active_thresh = {1000, 2000, 5000}, + }; #else - touch_pad_config(touchpad); - touch_pad_fsm_start(); + #error bad SOC_TOUCH_SENSOR_VERSION + #endif + + // On failure, touch_channels[idx] is left NULL. + esp_err_t result = touch_sensor_new_channel(touch_controller, channel_id, &chan_cfg, &touch_channels[idx]); + + // Enable and start continuous scanning, even if the new channel failed, + // so existing channels keep working. Return the first error. + err = touch_sensor_enable(touch_controller); + if (err != ESP_OK) { + return first_error(result, err); + } + touch_enabled = true; + + #if SOC_TOUCH_SENSOR_VERSION >= 2 + // On touch V2 and V3, a channel's data is invalid (reads >= 65535) until it has + // been measured, for example after a chip reset. TouchIn would then set its + // threshold from that invalid value. Scan a few times first, as the ESP-IDF + // touch_sens_basic example does. + for (int i = 0; i < 3; i++) { + err = touch_sensor_trigger_oneshot_scanning(touch_controller, 100); + if (err != ESP_OK) { + result = first_error(result, err); + break; + } + } #endif - touch_inited = true; + + err = touch_sensor_start_continuous_scanning(touch_controller); + if (err != ESP_OK) { + return first_error(result, err); + } + touch_scanning = true; + + return result; } -uint16_t peripherals_touch_read(touch_pad_t touchpad) { - #if defined(CONFIG_IDF_TARGET_ESP32) - uint16_t touch_value; - touch_pad_read(touchpad, &touch_value); +uint16_t peripherals_touch_read(int channel_id) { + int idx = chan_index(channel_id); + if (touch_channels[idx] == NULL) { + return 0; + } + + uint32_t touch_value = 0; - // ESP32 touch_pad_read() returns a lower value when a pin is touched instead of a higher value. - // Flip the values around to be consistent with TouchIn assumptions. - return UINT16_MAX - touch_value; - #else - uint32_t touch_value; - touch_pad_read_raw_data(touchpad, &touch_value); + #if SOC_TOUCH_SENSOR_VERSION == 1 + // ESP32 touch reads a lower value when touched. + // Flip the values to be consistent with TouchIn assumptions. + touch_channel_read_data(touch_channels[idx], TOUCH_CHAN_DATA_TYPE_RAW, &touch_value); + if (touch_value > UINT16_MAX) { + return 0; + } + return UINT16_MAX - (uint16_t)touch_value; + + #elif SOC_TOUCH_SENSOR_VERSION == 2 + touch_channel_read_data(touch_channels[idx], TOUCH_CHAN_DATA_TYPE_RAW, &touch_value); + if (touch_value > UINT16_MAX) { + return UINT16_MAX; + } + return (uint16_t)touch_value; + + #elif SOC_TOUCH_SENSOR_VERSION == 3 + touch_channel_read_data(touch_channels[idx], TOUCH_CHAN_DATA_TYPE_SMOOTH, &touch_value); if (touch_value > UINT16_MAX) { return UINT16_MAX; } return (uint16_t)touch_value; + + #else + #error bad SOC_TOUCH_SENSOR_VERSION #endif } diff --git a/ports/espressif/peripherals/touch.h b/ports/espressif/peripherals/touch.h index 6be4f8c2be1..b4be7276b4b 100644 --- a/ports/espressif/peripherals/touch.h +++ b/ports/espressif/peripherals/touch.h @@ -6,9 +6,21 @@ #pragma once -#include "driver/touch_pad.h" +#include "driver/touch_sens.h" -extern uint16_t peripherals_touch_read(touch_pad_t touchpad); +// Add a touch channel, creating the touch controller if needed, and (re)start +// continuous scanning. Does nothing if the channel is already initialized. +// +// Returns ESP_OK on success, or the first ESP-IDF error. On failure the channel +// is not initialized. Scanning of any existing channels is restarted if possible. +// Does not raise. +extern esp_err_t peripherals_touch_init(const int channel_id); + +// Remove a touch channel. Scanning of any remaining channels is restarted; +// when no channels remain, the touch controller is deleted. Does nothing if +// the channel is not initialized. ESP-IDF errors are ignored. Does not raise. +extern void peripherals_touch_deinit(const int channel_id); +extern uint16_t peripherals_touch_read(int channel_id); extern void peripherals_touch_reset(void); -extern void peripherals_touch_never_reset(const bool enable); -extern void peripherals_touch_init(const touch_pad_t touchpad); +extern touch_sensor_handle_t peripherals_touch_get_controller(void); +extern touch_channel_handle_t peripherals_touch_get_handle(int channel_id); diff --git a/ports/espressif/supervisor/internal_flash.c b/ports/espressif/supervisor/internal_flash.c index a18d3fe0a0f..d89efcbf763 100644 --- a/ports/espressif/supervisor/internal_flash.c +++ b/ports/espressif/supervisor/internal_flash.c @@ -43,11 +43,15 @@ static uint32_t _cache_lba = 0xffffffff; #define SECSIZE(fs) ((fs)->ssize) #endif // FF_MAX_SS == FF_MIN_SS static DWORD fatfs_bytes(void) { - fs_user_mount_t *fs_mount = filesystem_circuitpy(); - FATFS *fatfs = &fs_mount->fatfs; + supervisor_vfs_t *fs_mount = filesystem_circuitpy(); + FATFS *fatfs = &fs_mount->fat.fatfs; return (fatfs->csize * SECSIZE(fatfs)) * (fatfs->n_fatent - 2); } -static bool storage_extended = true; +// A fresh filesystem does not extend into the next-update partition. Extending is opt-in through +// storage.erase_filesystem(extended=True), and an existing extended filesystem is kept because +// supervisor_flash_update_extended() notices it once it is mounted. That happens before the mount +// is published, so every reader of storage_extended sees the same value. +static bool storage_extended = false; static const esp_partition_t *_partition[2]; #else static const esp_partition_t *_partition[1]; @@ -80,6 +84,43 @@ uint32_t supervisor_flash_get_block_count(void) { void port_internal_flash_flush(void) { } +#if CIRCUITPY_STORAGE_MAP_FILE +// storage.map_file: each drive partition mapped into the data address space on first use. With +// extended storage the drive spans two partitions that need not be adjacent in the mapping, so +// *contiguous stops at the seam and the caller splits a cluster run there. +static const uint8_t *map_partition(size_t i) { + static const uint8_t *base[2]; + if (base[i] == NULL) { + const void *p; + esp_partition_mmap_handle_t handle; // stays mapped for the session + if (esp_partition_mmap(_partition[i], 0, _partition[i]->size, ESP_PARTITION_MMAP_DATA, + &p, &handle) != ESP_OK) { + return NULL; + } + base[i] = p; + } + return base[i]; +} + +const uint8_t *port_internal_flash_xip_address(uint32_t block, uint32_t *contiguous) { + size_t i = 0; + uint32_t blocks = _partition[0]->size / FILESYSTEM_BLOCK_SIZE; + #if CIRCUITPY_STORAGE_EXTEND + if (storage_extended && block >= blocks) { + block -= blocks; + blocks = _partition[1]->size / FILESYSTEM_BLOCK_SIZE; + i = 1; + } + #endif + const uint8_t *base = map_partition(i); + if (base == NULL) { + return NULL; + } + *contiguous = blocks - block; + return base + block * FILESYSTEM_BLOCK_SIZE; +} +#endif + static void single_partition_rw(const esp_partition_t *partition, uint8_t *data, const uint32_t offset, const uint32_t size_total, const bool op) { if (op == OP_READ) { @@ -176,6 +217,7 @@ bool supervisor_flash_get_extended(void) { void supervisor_flash_update_extended(void) { #if CIRCUITPY_STORAGE_EXTEND + // Only keep extending when the filesystem on flash is already that big. storage_extended = (_partition[0]->size < fatfs_bytes()); #endif } diff --git a/ports/espressif/supervisor/lvgl_port.c b/ports/espressif/supervisor/lvgl_port.c new file mode 100644 index 00000000000..0c5f6bd260d --- /dev/null +++ b/ports/espressif/supervisor/lvgl_port.c @@ -0,0 +1,263 @@ +// LVGL port for espressif: a dedicated FreeRTOS task pumps lv_timer_handler(). +#include "py/mpconfig.h" +#if CIRCUITPY_DISPLAYIO_LVGL +#include "lvgl.h" +#include "esp_attr.h" +#include "esp_heap_caps.h" +#include "esp_log.h" +#include "esp_task.h" +#include "esp_timer.h" +#include "freertos/FreeRTOS.h" +#include "freertos/semphr.h" +#include "freertos/task.h" +#include "py/runtime.h" +#include "core/lv_global.h" +#include "shared-module/displayio/lvgl/lvgl_internal.h" +#include "supervisor/background_callback.h" +#include "supervisor/shared/safe_mode.h" +#include "supervisor/shared/tick.h" + +static const char *lvgl_tag = "LVGL"; + +static esp_timer_handle_t lvgl_tick_timer = NULL; + +// Recursive so the shared display code can nest displayio_lvgl_lock() calls and so the render +// task can take the same lock. FreeRTOS recursive mutexes also give priority inheritance, which +// keeps the low-priority CircuitPython task from starving rendering while it holds the lock. +static SemaphoreHandle_t lvgl_mutex = NULL; +static TaskHandle_t lvgl_task_handle = NULL; + +// Incremented by a framebuffer's vsync ISR. The task coalesces multiple boundaries into one +// render, so a burst of vsyncs while it was busy doesn't cause extra frames. +static volatile uint32_t lvgl_frame_generation = 0; +static uint32_t lvgl_frame_seen = 0; + +// BusDisplay flushes stay on the CircuitPython thread. Its LVGL refresh timer is proxied to this +// background callback, so no supervisor tick is involved. +static background_callback_t lvgl_cp_refresh_cb; + +// LVGL's allocator hooks (LV_USE_STDLIB_MALLOC == LV_STDLIB_CUSTOM). Displays and +// their buffers outlive the VM, so they come from the port heap. +void lv_mem_init(void) { +} + +void lv_mem_deinit(void) { +} + +lv_mem_pool_t lv_mem_add_pool(void *mem, size_t bytes) { + // Pools aren't supported with a custom allocator. + LV_UNUSED(mem); + LV_UNUSED(bytes); + return NULL; +} + +void lv_mem_remove_pool(lv_mem_pool_t pool) { + LV_UNUSED(pool); +} + +// LVGL allocates and frees small blocks (draw tasks, objects, styles) on every frame. +// port_malloc() aligns every PSRAM allocation to MICROPY_BYTES_PER_GC_BLOCK so that heap areas, +// and therefore the bytearrays VideoBuffers stream from, are cache-line aligned. Getting that +// alignment through heap_caps_aligned_alloc() over-allocates and splits off a free remainder on +// every call, which wastes ~64 bytes and shatters PSRAM when it happens millions of times. LVGL +// aligns its own draw buffers inside the allocation (LV_DRAW_BUF_ALIGN), so give it plain +// allocations and leave the aligned port_malloc() path to the GC and DMA buffers. +static void *lvgl_heap_alloc(size_t size) { + void *ptr = NULL; + #ifdef CONFIG_SPIRAM + ptr = heap_caps_malloc(size, MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM); + #endif + if (ptr == NULL) { + ptr = heap_caps_malloc(size, MALLOC_CAP_8BIT); + } + return ptr; +} + +// A NULL from lv_malloc_core is fatal in most of LVGL (the callers dereference the result), so +// record why it happened and reset into safe mode before LVGL can dereference it. Raising a +// Python MemoryError isn't possible here because this runs during display refreshes, which may +// be on the background display task, not in a Python frame. +static MP_NORETURN void lvgl_heap_log_oom(const char *what, size_t size) { + ESP_LOGE(lvgl_tag, "%s(%u) failed: internal %u free (%u largest), PSRAM %u free (%u largest)", + what, (unsigned)size, + (unsigned)heap_caps_get_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT), + (unsigned)heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT), + (unsigned)heap_caps_get_free_size(MALLOC_CAP_SPIRAM), + (unsigned)heap_caps_get_largest_free_block(MALLOC_CAP_SPIRAM)); + reset_into_safe_mode(SAFE_MODE_LVGL_OUT_OF_MEMORY); +} + +void *lv_malloc_core(size_t size) { + void *ptr = lvgl_heap_alloc(size); + if (ptr == NULL) { + lvgl_heap_log_oom("lv_malloc", size); + } + return ptr; +} + +void *lv_realloc_core(void *p, size_t new_size) { + void *grown = NULL; + #ifdef CONFIG_SPIRAM + grown = heap_caps_realloc(p, new_size, MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM); + #endif + if (grown == NULL) { + // A failed realloc leaves p alone, so trying the internal heap can't lose it. + grown = heap_caps_realloc(p, new_size, MALLOC_CAP_8BIT); + } + if (grown == NULL) { + lvgl_heap_log_oom("lv_realloc", new_size); + } + return grown; +} + +void lv_free_core(void *p) { + heap_caps_free(p); +} + +void lv_mem_monitor_core(lv_mem_monitor_t *mon_p) { + // LVGL only uses this for its own logging. Report the whole port heap (internal RAM plus + // PSRAM) rather than pretending to track LVGL's share of it. + size_t total = heap_caps_get_total_size(MALLOC_CAP_8BIT); + size_t free_size = heap_caps_get_free_size(MALLOC_CAP_8BIT); + size_t largest = heap_caps_get_largest_free_block(MALLOC_CAP_8BIT); + lv_memzero(mon_p, sizeof(*mon_p)); + mon_p->total_size = total; + mon_p->free_size = free_size; + mon_p->free_biggest_size = largest; + mon_p->max_used = total > free_size ? total - free_size : 0; + mon_p->used_pct = total > 0 ? (uint8_t)((total - free_size) * 100 / total) : 0; + mon_p->frag_pct = free_size > 0 ? (uint8_t)(100 - largest * 100 / free_size) : 0; +} + +lv_result_t lv_mem_test_core(void) { + return LV_RESULT_OK; +} + +static void lvgl_tick_cb(void *arg) { + lv_tick_inc(5); +} + +void displayio_lvgl_port_lock(void) { + if (lvgl_mutex != NULL) { + xSemaphoreTakeRecursive(lvgl_mutex, portMAX_DELAY); + } +} + +void displayio_lvgl_port_unlock(void) { + // The shared code used to count lock depth and made an unmatched unlock a no-op. Keep that + // property at the port so a future early return can't assert inside FreeRTOS. + if (lvgl_mutex != NULL && xSemaphoreGetMutexHolder(lvgl_mutex) == (void *)xTaskGetCurrentTaskHandle()) { + xSemaphoreGiveRecursive(lvgl_mutex); + } +} + +static void lvgl_cp_refresh(void *unused) { + LV_UNUSED(unused); + displayio_lvgl_refresh_unsafe_displays(); +} + +// BusDisplay's LVGL refresh timer normally flushes on the render task. Replace its callback with +// one that stops the timer and asks the CircuitPython thread to run lv_refr_now() instead. The +// timer is resumed by LVGL whenever the display is invalidated, so this stays event driven. +static void lvgl_busdisplay_refr_timer_cb(lv_timer_t *timer) { + lv_timer_pause(timer); + background_callback_add(&lvgl_cp_refresh_cb, lvgl_cp_refresh, NULL); +} + +void displayio_lvgl_port_install_busdisplay_refresh(lv_display_t *display) { + lv_timer_t *refr_timer = lv_display_get_refr_timer(display); + if (refr_timer != NULL) { + lv_timer_set_cb(refr_timer, lvgl_busdisplay_refr_timer_cb); + } +} + +IRAM_ATTR void displayio_lvgl_port_frame_boundary(void) { + if (xPortInIsrContext()) { + lvgl_frame_generation++; + BaseType_t woken = pdFALSE; + if (lvgl_task_handle != NULL) { + vTaskNotifyGiveFromISR(lvgl_task_handle, &woken); + } + if (woken == pdTRUE) { + portYIELD_FROM_ISR(); + } + return; + } + // UVC invokes its frame callback from a background task on the CircuitPython thread. Render + // directly there; there is no task handoff. + displayio_lvgl_refresh_paced_displays(); +} + +static void lvgl_task(void *arg) { + LV_UNUSED(arg); + for (;;) { + uint32_t wait = LV_DEF_REFR_PERIOD; + if (displayio_lvgl_auto_refresh()) { + displayio_lvgl_port_lock(); + wait = lv_timer_handler(); + displayio_lvgl_port_unlock(); + // Keep animations and the REPL responsive even when LVGL has nothing to do for a + // long time. The display refresh timer itself runs at LV_DEF_REFR_PERIOD. + if (wait == LV_NO_TIMER_READY || wait > LV_DEF_REFR_PERIOD) { + wait = LV_DEF_REFR_PERIOD; + } + if (wait == 0) { + wait = 1; + } + } + // Invalidations do not wake the task: they are batched until the next timer tick or the + // framebuffer's frame boundary. + ulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(wait)); + uint32_t frame_generation = lvgl_frame_generation; + if (frame_generation != lvgl_frame_seen) { + lvgl_frame_seen = frame_generation; + displayio_lvgl_refresh_paced_displays(); + } + } +} + +void displayio_lvgl_port_init(void) { + static bool inited = false; + if (inited) { + return; + } + inited = true; + // The lock has to exist before the task starts and before any display constructor takes it. + lvgl_mutex = xSemaphoreCreateRecursiveMutex(); + if (lvgl_mutex == NULL) { + ESP_LOGE(lvgl_tag, "LVGL mutex create failed"); + } + lv_init(); + // The LVGL compositor is pumped by the dedicated task below. The supervisor tick stays + // enabled for filesystem, USB and BLE background work; it does not pump LVGL. + supervisor_enable_tick(); + // Show which rendering backends LVGL registered. With PPA enabled this includes + // "ESP_PPA" and confirms the P4/S31 accelerator is available. + lv_draw_unit_t *unit = LV_GLOBAL_DEFAULT()->draw_info.unit_head; + while (unit != NULL) { + ESP_LOGI(lvgl_tag, "draw unit: %s", unit->name); + unit = unit->next; + } + const esp_timer_create_args_t args = { + .callback = lvgl_tick_cb, + .name = "lvgl_tick", + }; + esp_timer_create(&args, &lvgl_tick_timer); + esp_timer_start_periodic(lvgl_tick_timer, 5000); // 5ms + + // The task must run above the CircuitPython task so a tight Python loop can't starve + // rendering. Pin it to the CircuitPython core as well: background_callback_add() (used by the + // BusDisplay proxy) is interrupt-safe on a single core, and sharing the core keeps it from + // racing the CircuitPython thread's callback list. A recursive mutex (priority inheritance) + // keeps that from blocking the main task for long. 16 KB covers the draw paths plus LVGL's + // internal compositor state; 8 KB overflowed on complex screens. + BaseType_t ok = xTaskCreatePinnedToCore(lvgl_task, "lvgl", 16384, NULL, + ESP_TASK_MAIN_PRIO + 1, &lvgl_task_handle, CONFIG_ESP_MAIN_TASK_AFFINITY); + if (ok != pdPASS) { + lvgl_task_handle = NULL; + ESP_LOGE(lvgl_tag, "LVGL task create failed"); + } else { + ESP_LOGI(lvgl_tag, "render task started"); + } +} +#endif diff --git a/ports/espressif/supervisor/port.c b/ports/espressif/supervisor/port.c index bd49da89125..b4743baee65 100644 --- a/ports/espressif/supervisor/port.c +++ b/ports/espressif/supervisor/port.c @@ -15,7 +15,16 @@ #include "supervisor/shared/serial.h" #include "py/mpprint.h" #include "py/runtime.h" +#if MICROPY_PERSISTENT_CODE_LOAD_NATIVE +#include "py/persistentcode.h" +#if defined(SOC_CACHE_INTERNAL_MEM_VIA_L1CACHE) && SOC_CACHE_INTERNAL_MEM_VIA_L1CACHE +#include "esp_cache.h" +#endif +#endif +#include "esp_mac.h" +#include "esp_memory_utils.h" +#include "soc/soc_caps.h" #include "freertos/FreeRTOS.h" #include "freertos/task.h" @@ -24,9 +33,15 @@ #include "bindings/espulp/__init__.h" #include "common-hal/microcontroller/Pin.h" #include "common-hal/analogio/AnalogOut.h" +#if CIRCUITPY_AUDIOPWMIO +#include "common-hal/audiopwmio/PWMAudioOut.h" +#endif #include "common-hal/busio/SPI.h" #include "common-hal/busio/UART.h" #include "common-hal/dualbank/__init__.h" +#if CIRCUITPY_HARDWAREKEY +#include "common-hal/hardwarekey/__init__.h" +#endif #include "common-hal/ps2io/Ps2.h" #include "common-hal/watchdog/WatchDogTimer.h" #include "common-hal/socketpool/Socket.h" @@ -47,12 +62,16 @@ #include "peripherals/touch.h" #endif -#if CIRCUITPY_BLEIO +#if CIRCUITPY_BLEIO_NATIVE #include "shared-bindings/_bleio/__init__.h" #endif #if CIRCUITPY_ESPCAMERA -#include "esp_camera.h" +#include "common-hal/espcamera/Camera.h" +#endif + +#if CIRCUITPY_RCLCPY +#include "common-hal/rclcpy/__init__.h" #endif #include "soc/efuse_reg.h" @@ -60,7 +79,7 @@ #include "soc/lp_aon_reg.h" #define CP_SAVED_WORD_REGISTER LP_AON_STORE0_REG #else -#ifdef CONFIG_IDF_TARGET_ESP32P4 +#if defined(CONFIG_IDF_TARGET_ESP32P4) || defined(CONFIG_IDF_TARGET_ESP32S31) #include "soc/lp_system_reg.h" #define CP_SAVED_WORD_REGISTER LP_SYSTEM_REG_LP_STORE15_REG @@ -82,6 +101,10 @@ #include "esp_rom_efuse.h" #include "esp_timer.h" +#if MICROPY_PERSISTENT_CODE_LOAD_NATIVE && defined(CONFIG_IDF_TARGET_ESP32S2) +#include "esp_memory_utils.h" +#endif + #ifdef CONFIG_IDF_TARGET_ESP32 #include "hal/efuse_hal.h" #include "esp32/rom/efuse.h" @@ -99,7 +122,7 @@ static esp_timer_handle_t _sleep_timer; TaskHandle_t circuitpython_task = NULL; -extern void esp_restart(void) NORETURN; +extern void esp_restart(void) MP_NORETURN; static void tick_on_cp_core(void *arg) { supervisor_tick(); @@ -164,55 +187,57 @@ void sleep_timer_cb(void *arg); #define PICO_V3_02_PSRAM_CS_IO 9 #endif // CONFIG_SPIRAM -static void _never_reset_spi_ram_flash(void) { - #if defined(CONFIG_IDF_TARGET_ESP32) +#if defined(CONFIG_IDF_TARGET_ESP32) +// Claim the ESP32's flash and PSRAM pins so user code can't use them. They depend +// on the chip package and efuses, so they can't be in the static reset-forbidden mask. +static void _claim_spi_ram_flash_pins(void) { #if defined(CONFIG_SPIRAM) uint32_t pkg_ver = esp_efuse_get_pkg_ver(); if (pkg_ver == EFUSE_RD_CHIP_VER_PKG_ESP32D2WDQ5) { - never_reset_pin_number(D2WD_PSRAM_CLK_IO); - never_reset_pin_number(D2WD_PSRAM_CS_IO); + claim_pin_number(D2WD_PSRAM_CLK_IO); + claim_pin_number(D2WD_PSRAM_CS_IO); } else if (pkg_ver == EFUSE_RD_CHIP_VER_PKG_ESP32PICOD4 && efuse_hal_get_major_chip_version() >= 3) { // This chip is ESP32-PICO-V3 and doesn't have PSRAM. } else if ((pkg_ver == EFUSE_RD_CHIP_VER_PKG_ESP32PICOD2) || (pkg_ver == EFUSE_RD_CHIP_VER_PKG_ESP32PICOD4)) { - never_reset_pin_number(PICO_PSRAM_CLK_IO); - never_reset_pin_number(PICO_PSRAM_CS_IO); + claim_pin_number(PICO_PSRAM_CLK_IO); + claim_pin_number(PICO_PSRAM_CS_IO); } else if (pkg_ver == EFUSE_RD_CHIP_VER_PKG_ESP32PICOV302) { - never_reset_pin_number(PICO_V3_02_PSRAM_CLK_IO); - never_reset_pin_number(PICO_V3_02_PSRAM_CS_IO); + claim_pin_number(PICO_V3_02_PSRAM_CLK_IO); + claim_pin_number(PICO_V3_02_PSRAM_CS_IO); } else if ((pkg_ver == EFUSE_RD_CHIP_VER_PKG_ESP32D0WDQ6) || (pkg_ver == EFUSE_RD_CHIP_VER_PKG_ESP32D0WDQ5)) { - never_reset_pin_number(D0WD_PSRAM_CLK_IO); - never_reset_pin_number(D0WD_PSRAM_CS_IO); + claim_pin_number(D0WD_PSRAM_CLK_IO); + claim_pin_number(D0WD_PSRAM_CS_IO); } else if (pkg_ver == EFUSE_RD_CHIP_VER_PKG_ESP32D0WDR2V3) { - never_reset_pin_number(D0WDR2_V3_PSRAM_CLK_IO); - never_reset_pin_number(D0WDR2_V3_PSRAM_CS_IO); + claim_pin_number(D0WDR2_V3_PSRAM_CLK_IO); + claim_pin_number(D0WDR2_V3_PSRAM_CS_IO); } #endif // CONFIG_SPIRAM const uint32_t spiconfig = esp_rom_efuse_get_flash_gpio_info(); if (spiconfig == ESP_ROM_EFUSE_FLASH_DEFAULT_SPI) { - never_reset_pin_number(SPI_IOMUX_PIN_NUM_CLK); - never_reset_pin_number(SPI_IOMUX_PIN_NUM_CS); - never_reset_pin_number(PSRAM_SPIQ_SD0_IO); - never_reset_pin_number(PSRAM_SPID_SD1_IO); - never_reset_pin_number(PSRAM_SPIWP_SD3_IO); - never_reset_pin_number(PSRAM_SPIHD_SD2_IO); + claim_pin_number(MSPI_IOMUX_PIN_NUM_CLK); + claim_pin_number(MSPI_IOMUX_PIN_NUM_CS0); + claim_pin_number(PSRAM_SPIQ_SD0_IO); + claim_pin_number(PSRAM_SPID_SD1_IO); + claim_pin_number(PSRAM_SPIWP_SD3_IO); + claim_pin_number(PSRAM_SPIHD_SD2_IO); } else if (spiconfig == ESP_ROM_EFUSE_FLASH_DEFAULT_HSPI) { - never_reset_pin_number(FLASH_HSPI_CLK_IO); - never_reset_pin_number(FLASH_HSPI_CS_IO); - never_reset_pin_number(PSRAM_HSPI_SPIQ_SD0_IO); - never_reset_pin_number(PSRAM_HSPI_SPID_SD1_IO); - never_reset_pin_number(PSRAM_HSPI_SPIWP_SD3_IO); - never_reset_pin_number(PSRAM_HSPI_SPIHD_SD2_IO); + claim_pin_number(FLASH_HSPI_CLK_IO); + claim_pin_number(FLASH_HSPI_CS_IO); + claim_pin_number(PSRAM_HSPI_SPIQ_SD0_IO); + claim_pin_number(PSRAM_HSPI_SPID_SD1_IO); + claim_pin_number(PSRAM_HSPI_SPIWP_SD3_IO); + claim_pin_number(PSRAM_HSPI_SPIHD_SD2_IO); } else { - never_reset_pin_number(EFUSE_SPICONFIG_RET_SPICLK(spiconfig)); - never_reset_pin_number(EFUSE_SPICONFIG_RET_SPICS0(spiconfig)); - never_reset_pin_number(EFUSE_SPICONFIG_RET_SPIQ(spiconfig)); - never_reset_pin_number(EFUSE_SPICONFIG_RET_SPID(spiconfig)); - never_reset_pin_number(EFUSE_SPICONFIG_RET_SPIHD(spiconfig)); - never_reset_pin_number(bootloader_flash_get_wp_pin()); + claim_pin_number(EFUSE_SPICONFIG_RET_SPICLK(spiconfig)); + claim_pin_number(EFUSE_SPICONFIG_RET_SPICS0(spiconfig)); + claim_pin_number(EFUSE_SPICONFIG_RET_SPIQ(spiconfig)); + claim_pin_number(EFUSE_SPICONFIG_RET_SPID(spiconfig)); + claim_pin_number(EFUSE_SPICONFIG_RET_SPIHD(spiconfig)); + claim_pin_number(bootloader_flash_get_wp_pin()); } - #endif // CONFIG_IDF_TARGET_ESP32 } +#endif // CONFIG_IDF_TARGET_ESP32 safe_mode_t port_init(void) { esp_timer_create_args_t args; @@ -235,47 +260,51 @@ safe_mode_t port_init(void) { #endif // Send the ROM output out of the UART. This includes early logs. - #if DEBUG + #if DEBUG && (defined(CONFIG_ESP_CONSOLE_UART_DEFAULT) && CONFIG_ESP_CONSOLE_UART_DEFAULT) esp_rom_install_uart_printf(); #endif - #define pin_GPIOn(n) pin_GPIO##n - #define pin_GPIOn_EXPAND(x) pin_GPIOn(x) - - #ifdef CONFIG_CONSOLE_UART_TX_GPIO - common_hal_never_reset_pin(&pin_GPIOn_EXPAND(CONFIG_CONSOLE_UART_TX_GPIO)); - #endif - - #ifdef CONFIG_CONSOLE_UART_RX_GPIO - common_hal_never_reset_pin(&pin_GPIOn_EXPAND(CONFIG_CONSOLE_UART_RX_GPIO)); - #endif - - #ifndef ENABLE_JTAG - #define ENABLE_JTAG (0) + claim_reset_forbidden_pins(); + #if defined(CONFIG_IDF_TARGET_ESP32) + _claim_spi_ram_flash_pins(); #endif - #if ENABLE_JTAG - ESP_LOGI(TAG, "Marking JTAG pins never_reset"); - // JTAG + #if defined(ENABLE_JTAG) && ENABLE_JTAG + // Keep user code off the JTAG pins in JTAG debug builds. #if defined(CONFIG_IDF_TARGET_ESP32C3) || defined(CONFIG_IDF_TARGET_ESP32C6) - common_hal_never_reset_pin(&pin_GPIO4); - common_hal_never_reset_pin(&pin_GPIO5); - common_hal_never_reset_pin(&pin_GPIO6); - common_hal_never_reset_pin(&pin_GPIO7); - #elif defined(CONFIG_IDF_TARGET_ESP32S2) || defined(CONFIG_IDF_TARGET_ESP32S3) - common_hal_never_reset_pin(&pin_GPIO39); - common_hal_never_reset_pin(&pin_GPIO40); - common_hal_never_reset_pin(&pin_GPIO41); - common_hal_never_reset_pin(&pin_GPIO42); + claim_pin_number(4); // MTMS + claim_pin_number(5); // MTDI + claim_pin_number(6); // MTCK + claim_pin_number(7); // MTDO + #elif defined(CONFIG_IDF_TARGET_ESP32C61) + claim_pin_number(3); // MTMS + claim_pin_number(4); // MTDI + claim_pin_number(5); // MTCK + claim_pin_number(6); // MTDO #elif defined(CONFIG_IDF_TARGET_ESP32P4) - common_hal_never_reset_pin(&pin_GPIO3); - common_hal_never_reset_pin(&pin_GPIO4); - common_hal_never_reset_pin(&pin_GPIO5); - common_hal_never_reset_pin(&pin_GPIO6); + claim_pin_number(2); // MTCK + claim_pin_number(3); // MTDI + claim_pin_number(4); // MTMS + claim_pin_number(5); // MTDO + #elif defined(CONFIG_IDF_TARGET_ESP32S2) || defined(CONFIG_IDF_TARGET_ESP32S3) + claim_pin_number(39); // MTCK + claim_pin_number(40); // MTDO + claim_pin_number(41); // MTDI + claim_pin_number(42); // MTMS #endif #endif - _never_reset_spi_ram_flash(); + #ifdef DOUBLE_TAP_PIN + // Pull the double-tap pin down at boot so that resets come back to + // CircuitPython. reset_pin_number() applies the pull-down. + reset_pin_number(DOUBLE_TAP_PIN->number); + #endif + + #if CIRCUITPY_HARDWAREKEY + // Populate board.EFUSE_KEY* from the eFuse key blocks. eFuse reads and the + // PSA key import need no filesystem or VM, so this is safe here. + espressif_hardwarekey_init(); + #endif esp_reset_reason_t reason = esp_reset_reason(); switch (reason) { @@ -303,75 +332,198 @@ void port_heap_init(void) { // The IDF sets up the heap, so we don't need to. } +static void port_heap_log_usage(size_t size, void *ptr); + void *port_malloc(size_t size, bool dma_capable) { - size_t caps = MALLOC_CAP_8BIT; if (dma_capable) { - caps |= MALLOC_CAP_DMA; + // SPIRAM is not DMA-capable, so don't bother to ask for it. + #if defined(SOC_CACHE_INTERNAL_MEM_VIA_L1CACHE) && SOC_CACHE_INTERNAL_MEM_VIA_L1CACHE + // Cache maintenance must not touch memory outside this allocation. + size = (size + CONFIG_CACHE_L1_CACHE_LINE_SIZE - 1) & ~(CONFIG_CACHE_L1_CACHE_LINE_SIZE - 1); + return heap_caps_aligned_alloc(CONFIG_CACHE_L1_CACHE_LINE_SIZE, size, MALLOC_CAP_8BIT | MALLOC_CAP_DMA); + #else + return heap_caps_malloc(size, MALLOC_CAP_8BIT | MALLOC_CAP_DMA); + #endif } void *ptr = NULL; - // Try SPIRAM first when available. + // Try SPIRAM first if available. Aligned to the GC block size so heap + // areas (and with 64-byte GC blocks, every GC allocation in them) are + // cache-line aligned, which video DMA destinations require. #ifdef CONFIG_SPIRAM - ptr = heap_caps_malloc(size, caps | MALLOC_CAP_SPIRAM); + ptr = heap_caps_aligned_alloc(MICROPY_BYTES_PER_GC_BLOCK, size, MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM); #endif if (ptr == NULL) { - ptr = heap_caps_malloc(size, caps); + ptr = heap_caps_malloc(size, MALLOC_CAP_8BIT); } + port_heap_log_usage(size, ptr); return ptr; } +// Debug aid for running out of PSRAM: a board that exhausts it takes the display stack (LVGL) +// down with a hard fault, and the crash dump doesn't say what used the memory. Log the big +// allocations (a GC heap split is at least megabytes) and, once the heap is nearly gone, the +// small ones too, so the log shows which consumer took the last of it. Silent otherwise. +static void port_heap_log_usage(size_t size, void *ptr) { + #ifdef CONFIG_SPIRAM + size_t psram_free = heap_caps_get_free_size(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM); + const size_t big = 1024 * 1024; + const size_t low_water = 512 * 1024; + if (size < big && (psram_free >= low_water || size < 1024)) { + return; + } + ESP_LOGI(TAG, "port_malloc(%u) = %p: PSRAM %u free (%u largest), internal %u free", + (unsigned)size, ptr, (unsigned)psram_free, + (unsigned)heap_caps_get_largest_free_block(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM), + (unsigned)heap_caps_get_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT)); + #else + (void)size; + (void)ptr; + #endif +} + +#if !CIRCUITPY_ALL_MEMORY_DMA_CAPABLE +bool port_buffer_is_dma_capable(const void *ptr, size_t len) { + if (len == 0 || !esp_ptr_dma_capable(ptr) || + !esp_ptr_dma_capable((const uint8_t *)ptr + len - 1)) { + return false; + } + #if defined(SOC_CACHE_INTERNAL_MEM_VIA_L1CACHE) && SOC_CACHE_INTERNAL_MEM_VIA_L1CACHE + // Cache maintenance must stay inside the caller's buffer at both ends. + return ((uintptr_t)ptr % CONFIG_CACHE_L1_CACHE_LINE_SIZE) == 0 && + (len % CONFIG_CACHE_L1_CACHE_LINE_SIZE) == 0; + #else + return true; + #endif +} +#endif + void port_free(void *ptr) { heap_caps_free(ptr); } -void *port_realloc(void *ptr, size_t size) { - return heap_caps_realloc(ptr, size, MALLOC_CAP_8BIT); +void *port_realloc(void *ptr, size_t size, bool dma_capable) { + size_t caps = MALLOC_CAP_8BIT; + if (dma_capable) { + caps |= MALLOC_CAP_DMA; + } + return heap_caps_realloc(ptr, size, caps); } size_t port_heap_get_largest_free_size(void) { - size_t free_size = heap_caps_get_largest_free_block(MALLOC_CAP_8BIT); - return free_size; + size_t largest = heap_caps_get_largest_free_block(MALLOC_CAP_8BIT); + #ifdef CONFIG_SPIRAM + // The VM heap only ever grows, and gc_try_add_heap() takes up to the whole largest free block + // when it doesn't need the full doubling. Without a reserve a Python allocation can therefore + // swallow the last of PSRAM, and the next display/LVGL allocation (a framebuffer, a TileGrid + // compose buffer, a draw task) fails. LVGL doesn't check for NULL there, so the board hard + // faults in the renderer instead of the VM raising MemoryError. Keep up to a quarter of the + // heap (4 MB on a 16 MB board) for the port side; gc.mem_free() reports the reduced number, + // which is the honest one. + size_t total = heap_caps_get_total_size(MALLOC_CAP_8BIT); + size_t reserve = total / 4; + const size_t max_reserve = 4 * 1024 * 1024; + if (reserve > max_reserve) { + reserve = max_reserve; + } + if (largest <= reserve) { + return 0; + } + largest -= reserve; + #endif + return largest; } -void reset_port(void) { - // TODO deinit for esp32-camera - #if CIRCUITPY_ESPCAMERA - esp_camera_deinit(); - #endif +#if MICROPY_PERSISTENT_CODE_LOAD_NATIVE +// Loaded native code, kept outside the GC heap until port_gc_deinit(). +typedef struct _native_code_node_t { + struct _native_code_node_t *next; + uint32_t data[]; +} native_code_node_t; - #if CIRCUITPY_SSL - ssl_reset(); - #endif +static native_code_node_t *native_code_head = NULL; - reset_all_pins(); +void port_gc_deinit(void) { + while (native_code_head != NULL) { + native_code_node_t *next = native_code_head->next; + heap_caps_free(native_code_head); + native_code_head = next; + } +} - #if CIRCUITPY_ANALOGIO - analogout_reset(); +// Copy `len` bytes of machine code from `buf` into executable memory and return +// the executable address, applying the relocations in `reloc` (if any) against +// that address first. Raises MemoryError when no executable memory is available. +void *esp_native_code_commit(void *buf, size_t len, void *reloc) { + len = (len + 3) & ~3; + size_t len_node = sizeof(native_code_node_t) + len; + #if defined(SOC_CACHE_INTERNAL_MEM_VIA_L1CACHE) && SOC_CACHE_INTERNAL_MEM_VIA_L1CACHE + // Internal RAM is reached through the L1 caches (ESP32-P4): the node is + // whole cache lines, so that it can be synced below. + len_node = (len_node + CONFIG_CACHE_L1_CACHE_LINE_SIZE - 1) & ~(CONFIG_CACHE_L1_CACHE_LINE_SIZE - 1); + native_code_node_t *node = heap_caps_aligned_alloc(CONFIG_CACHE_L1_CACHE_LINE_SIZE, len_node, MALLOC_CAP_EXEC); + #else + native_code_node_t *node = heap_caps_malloc(len_node, MALLOC_CAP_EXEC); #endif - - #if CIRCUITPY_BUSIO - spi_reset(); - uart_reset(); + #if defined(CONFIG_IDF_TARGET_ESP32S2) + // The S2 can hand out MALLOC_CAP_EXEC memory that the CPU cannot fetch from. + if (node != NULL && !esp_ptr_executable(node)) { + heap_caps_free(node); + node = NULL; + } #endif - - #if CIRCUITPY_SDIOIO - sdioio_reset(); + if (node == NULL) { + m_malloc_fail(len_node); + } + node->next = native_code_head; + native_code_head = node; + void *p = node->data; + if (reloc) { + mp_native_relocate(reloc, buf, (uintptr_t)p); + } + // Word copy: Xtensa executable RAM is not byte-addressable. + const uint32_t *src = buf; + uint32_t *dst = p; + for (size_t i = 0; i < len / 4; i++) { + dst[i] = src[i]; + } + #if defined(SOC_CACHE_INTERNAL_MEM_VIA_L1CACHE) && SOC_CACHE_INTERNAL_MEM_VIA_L1CACHE + // The code is still in the data cache, and the instruction cache may hold + // stale lines from the node's earlier use: write back, then invalidate. + esp_cache_msync(node, len_node, ESP_CACHE_MSYNC_FLAG_DIR_C2M | ESP_CACHE_MSYNC_FLAG_TYPE_DATA); + esp_cache_msync(node, len_node, ESP_CACHE_MSYNC_FLAG_DIR_M2C | ESP_CACHE_MSYNC_FLAG_TYPE_INST); #endif + return p; +} +#endif - #if CIRCUITPY_DUALBANK - dualbank_reset(); +void reset_port_early(void) { + // Deinit the camera now, before reset_board_buses() deinits board.I2C(). + // + // The camera shares its I2C bus with busio.I2C and keeps a device + // registered on that bus for as long as the camera is alive. ESP-IDF + // refuses to delete a bus that still has devices, so if the camera is + // still alive when the bus is deinited, the bus is never freed. Its I2C + // peripheral then stays in use until a hard reset. + // + // Waiting for the camera's finaliser doesn't work: finalisers run after + // reset_board_buses(). + #if CIRCUITPY_ESPCAMERA + espcamera_reset(); #endif +} - #if CIRCUITPY_ESPNOW - espnow_reset(); +void reset_port(void) { + #if CIRCUITPY_SSL + ssl_reset(); #endif - #if CIRCUITPY_ESPULP - espulp_reset(); + #if CIRCUITPY_DUALBANK + dualbank_reset(); #endif - #if CIRCUITPY_PS2IO - ps2_reset(); + #if CIRCUITPY_RCLCPY + rclcpy_reset(); #endif #if CIRCUITPY_RTC @@ -382,16 +534,12 @@ void reset_port(void) { socketpool_user_reset(); #endif - #if CIRCUITPY_TOUCHIO_USE_NATIVE - peripherals_touch_reset(); - #endif - #if CIRCUITPY_WATCHDOG watchdog_reset(); #endif - // Yield so the idle task can run and do any IDF cleanup needed. - port_yield(); + // Yield so the idle task, at priority 0, can run and do any IDF cleanup needed. + port_task_sleep_ms(4); } void reset_to_bootloader(void) { @@ -457,11 +605,16 @@ void port_disable_tick(void) { esp_timer_stop(_tick_timer); } -void port_wake_main_task() { +void port_wake_main_task(void) { + // background_callback_add() may be called from an interrupt. + if (xPortInIsrContext()) { + port_wake_main_task_from_isr(); + return; + } xTaskNotifyGive(circuitpython_task); } -void port_wake_main_task_from_isr() { +void port_wake_main_task_from_isr(void) { BaseType_t xHigherPriorityTaskWoken = pdFALSE; vTaskNotifyGiveFromISR(circuitpython_task, &xHigherPriorityTaskWoken); if (xHigherPriorityTaskWoken == pdTRUE) { @@ -469,8 +622,13 @@ void port_wake_main_task_from_isr() { } } -void port_yield() { - vTaskDelay(4); +// Yield to other tasks at the same priority. +void port_task_yield(void) { + vTaskDelay(0); +} + +void port_task_sleep_ms(uint32_t msecs) { + vTaskDelay(pdMS_TO_TICKS(msecs)); } void sleep_timer_cb(void *arg) { @@ -493,11 +651,22 @@ void port_idle_until_interrupt(void) { } } -void port_post_boot_py(bool heap_valid) { - if (!heap_valid && filesystem_present()) { +#if CIRCUITPY_WIFI +void port_boot_info(void) { + uint8_t mac[6]; + // This runs before esp_wifi_init(), so esp_wifi_get_mac() fails with + // ESP_ERR_WIFI_NOT_INIT and leaves mac[] untouched. esp_read_mac() reads + // efuse directly and does not need the WiFi driver started. + if (esp_read_mac(mac, ESP_MAC_WIFI_STA) != ESP_OK) { + return; + } + mp_printf(&mp_plat_print, "MAC"); + for (int i = 0; i < 6; i++) { + mp_printf(&mp_plat_print, ":%02X", mac[i]); } + mp_printf(&mp_plat_print, "\n"); } - +#endif // Wrap main in app_main that the IDF expects. extern void main(void); diff --git a/ports/espressif/supervisor/usb.c b/ports/espressif/supervisor/usb.c index c2bf90b21b1..df133fcb69c 100644 --- a/ports/espressif/supervisor/usb.c +++ b/ports/espressif/supervisor/usb.c @@ -2,6 +2,7 @@ // // SPDX-FileCopyrightText: Copyright (c) 2018 hathach for Adafruit Industries // SPDX-FileCopyrightText: Copyright (c) 2019 Lucian Copeland for Adafruit Industries +// SPDX-FileContributor: 2025 Nicolai Electronics // // SPDX-License-Identifier: MIT @@ -20,21 +21,18 @@ #include "driver/gpio.h" #include "esp_private/periph_ctrl.h" -#if defined(CONFIG_IDF_TARGET_ESP32C3) -#include "components/esp_rom/include/esp32c3/rom/gpio.h" -#elif defined(CONFIG_IDF_TARGET_ESP32C6) -#include "components/esp_rom/include/esp32c6/rom/gpio.h" -#elif defined(CONFIG_IDF_TARGET_ESP32S2) -#include "components/esp_rom/include/esp32s2/rom/gpio.h" -#elif defined(CONFIG_IDF_TARGET_ESP32S3) -#include "components/esp_rom/include/esp32s3/rom/gpio.h" -#endif - #include "freertos/FreeRTOS.h" #include "freertos/task.h" #include "tusb.h" +#ifdef CONFIG_IDF_TARGET_ESP32P4 +#include "esp_rom_sys.h" +#include "esp_system.h" +#include "hal/usb_serial_jtag_ll.h" +#include "soc/lp_system_reg.h" +#endif + #if CIRCUITPY_USB_DEVICE #ifdef CFG_TUSB_DEBUG #define USBD_STACK_SIZE (3 * configMINIMAL_STACK_SIZE) @@ -45,7 +43,21 @@ StackType_t usb_device_stack[USBD_STACK_SIZE]; StaticTask_t usb_device_taskdef; -static usb_phy_handle_t phy_hdl; +static usb_phy_handle_t device_phy_hdl; + +#ifdef CONFIG_IDF_TARGET_ESP32P4 +static void usb_shutdown(void) { + if (!(REG_READ(LP_SYSTEM_REG_SYS_CTRL_REG) & LP_SYSTEM_REG_FORCE_DOWNLOAD_BOOT)) { + return; + } + tud_disconnect(); + vTaskDelay(pdMS_TO_TICKS(20)); + // The PHY selection survives a CPU reset. Restore the ROM downloader's pins. + usb_serial_jtag_ll_phy_select(0); + // Reset the USB peripheral too so the ROM can initialize its downloader. + esp_rom_software_reset_system(); +} +#endif // USB Device Driver task // This top level thread process all usb events and invoke callbacks @@ -59,34 +71,10 @@ static void usb_device_task(void *param) { tud_task(); tud_cdc_write_flush(); } - vTaskDelay(1); - } -} - -/** - * 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 - // CircuitPython's VM is run in a separate FreeRTOS task from TinyUSB. - // So, we must notify the other task when a CTRL-C is received. - port_wake_main_task(); - // Workaround for using shared/runtime/interrupt_char.c - // Compare mp_interrupt_char with wanted_char and ignore if not matched - if (mp_interrupt_char == wanted_char) { - tud_cdc_read_flush(); // flush read fifo - mp_sched_keyboard_interrupt(); + // Yield with zero delay to switch to any other tasks at same priority. + port_task_yield(); } } - -void tud_cdc_rx_cb(uint8_t itf) { - (void)itf; - // Workaround for "press any key to enter REPL" response being delayed on espressif. - // Wake main task when any key is pressed. - port_wake_main_task(); -} #endif // CIRCUITPY_USB_DEVICE void init_usb_hardware(void) { @@ -94,14 +82,49 @@ void init_usb_hardware(void) { // Configure USB PHY usb_phy_config_t phy_conf = { .controller = USB_PHY_CTRL_OTG, + #if defined(CONFIG_IDF_TARGET_ESP32P4) && CIRCUITPY_USB_DEVICE_INSTANCE == 1 + .target = USB_PHY_TARGET_UTMI, + #else .target = USB_PHY_TARGET_INT, - + #endif .otg_mode = USB_OTG_MODE_DEVICE, + #if defined(CONFIG_IDF_TARGET_ESP32P4) && CIRCUITPY_USB_DEVICE_INSTANCE == 0 + .otg_speed = USB_PHY_SPEED_FULL, + #else // https://github.com/hathach/tinyusb/issues/2943#issuecomment-2601888322 // Set speed to undefined (auto-detect) to avoid timing/race issue with S3 with host such as macOS .otg_speed = USB_PHY_SPEED_UNDEFINED, + #endif + }; + usb_new_phy(&phy_conf, &device_phy_hdl); + + #if CIRCUITPY_ESP32P4_SWAP_LSFS == 1 + #ifndef CONFIG_IDF_TARGET_ESP32P4 + #error "LSFS swap is only supported on ESP32P4" + #endif + // Switch the USB PHY + const usb_serial_jtag_pull_override_vals_t override_disable_usb = { + .dm_pd = true, .dm_pu = false, .dp_pd = true, .dp_pu = false + }; + const usb_serial_jtag_pull_override_vals_t override_enable_usb = { + .dm_pd = false, .dm_pu = false, .dp_pd = false, .dp_pu = true }; - usb_new_phy(&phy_conf, &phy_hdl); + + // Drop off the bus by removing the pull-up on USB DP + usb_serial_jtag_ll_phy_enable_pull_override(&override_disable_usb); + + // Select USB mode by swapping and un-swapping the two PHYs + vTaskDelay(pdMS_TO_TICKS(500)); // Wait for disconnect before switching to device + usb_serial_jtag_ll_phy_select(1); + + // Put the device back onto the bus by re-enabling the pull-up on USB DP + usb_serial_jtag_ll_phy_enable_pull_override(&override_enable_usb); + usb_serial_jtag_ll_phy_disable_pull_override(); + #endif + + #ifdef CONFIG_IDF_TARGET_ESP32P4 + ESP_ERROR_CHECK(esp_register_shutdown_handler(usb_shutdown)); + #endif // Pin the USB task to the same core as CircuitPython. This way we leave // the other core for networking. @@ -109,7 +132,7 @@ void init_usb_hardware(void) { "usbd", USBD_STACK_SIZE, NULL, - 5, + 1, usb_device_stack, &usb_device_taskdef, xPortGetCoreID()); diff --git a/ports/espressif/tools/build_memory_info.py b/ports/espressif/tools/build_memory_info.py index 9a3c5550138..761e110416f 100644 --- a/ports/espressif/tools/build_memory_info.py +++ b/ports/espressif/tools/build_memory_info.py @@ -45,6 +45,11 @@ ("L2MEM", (0x4FF0_0000,), 768 * 1024), ("LP RAM", (0x5010_8000,), 32 * 1024), ], + "esp32s31": [ + # Name, Start, Length + ("HP SRAM", (0x2F00_0000,), 512 * 1024), + ("LP RAM", (0x2E00_0000,), 32 * 1024), + ], "esp32c2": [ # Name, Start, Length ("Internal SRAM 0", (0x4037_C000,), 16 * 1024), @@ -56,11 +61,22 @@ ("Internal SRAM 0", (0x4037_C000,), 16 * 1024), ("Internal SRAM 1", (0x3FC8_0000, 0x4038_0000), 384 * 1024), ], + "esp32c5": [ + # Name, Start, Length + ("LP SRAM", (0x5000_0000,), 16 * 1024), + ("HP SRAM", (0x4080_0000,), 384 * 1024), + ], "esp32c6": [ # Name, Start, Length ("LP SRAM", (0x5000_0000,), 16 * 1024), ("HP SRAM", (0x4080_0000,), 512 * 1024), ], + "esp32c61": [ + # Name, Start, Length + ("LP SRAM", (0x5000_0000,), 16 * 1024), + ("HP SRAM", (0x4080_0000,), 320 * 1024), + ("PSRAM", (0x4200_0000,), 2 * 1024 * 1024), + ], "esp32h2": [ # Name, Start, Length ("LP SRAM", (0x5000_0000,), 4 * 1024), diff --git a/ports/espressif/tools/check-sdkconfig.py b/ports/espressif/tools/check-sdkconfig.py index 12254a71d01..f16dc3c871a 100755 --- a/ports/espressif/tools/check-sdkconfig.py +++ b/ports/espressif/tools/check-sdkconfig.py @@ -34,6 +34,17 @@ def validate(sdk_config, circuitpy_config): f"{var} is incompatible with {partition_table=} (no ota_1 partition)" ) + # Native machine code executes from RAM; the PMS/PMP memory protection + # forbids that and makes MALLOC_CAP_EXEC allocations fail. + if ( + circuitpy_config.get("CIRCUITPY_ENABLE_MPY_NATIVE") + or circuitpy_config.get("CIRCUITPY_LOAD_NATIVE") + ) and sdk_config.get("CONFIG_ESP_SYSTEM_MEMPROT"): + raise SystemExit( + "CIRCUITPY_ENABLE_MPY_NATIVE=1 / CIRCUITPY_LOAD_NATIVE=1 require CONFIG_ESP_SYSTEM_MEMPROT=n " + "(see esp-idf-config/sdkconfig-native.defaults)" + ) + # Add more checks here for other things we want to verify. return diff --git a/ports/espressif/tools/decode_backtrace.py b/ports/espressif/tools/decode_backtrace.py index 024e636207e..2001482ffd6 100644 --- a/ports/espressif/tools/decode_backtrace.py +++ b/ports/espressif/tools/decode_backtrace.py @@ -10,22 +10,45 @@ import sys board = sys.argv[1] +# Allow `board-name` or `build-board-name/ as the arg, to allow simple tab completion of boardname. +board = board.replace("build-", "").replace("/", "") print(board) +elfs = [ + f"build-{board}/firmware.elf", + # Add additional ELF files here such as the ROM ELF files from: + # https://github.com/espressif/esp-rom-elfs/releases + # "/home/tannewt/Downloads/esp-rom-elfs-20241011/esp32c6_rev0_rom.elf", +] + while True: + print('"Backtrace:" or "Stack memory:". CTRL-D to finish multiline paste') addresses = input("? ") if addresses.startswith("Backtrace:"): addresses = addresses[len("Backtrace:") :] - if addresses.startswith("Stack memory:"): - addresses = addresses[len("Stack memory:") :] - addresses = addresses.strip().split() - addresses = [address.split(":")[0] for address in addresses] + addresses = addresses.strip().split() + addresses = [address.split(":")[0] for address in addresses] + elif addresses.startswith("Stack memory:"): + addresses = [] + extra_lines = sys.stdin.readlines() + for line in extra_lines: + if not line.strip(): + continue + addresses.extend(line.split(":")[1].strip().split()) for address in addresses: - result = subprocess.run( - ["xtensa-esp32s2-elf-addr2line", "-aipfe", "build-{}/firmware.elf".format(board)] - + [address], - capture_output=True, - ) - stdout = result.stdout.decode("utf-8") - if "?? ??" not in stdout: - print(stdout.strip()) + if address == "0xa5a5a5a5": + # Skip stack fill value. + continue + for elf in elfs: + result = subprocess.run( + ["riscv32-esp-elf-addr2line", "-aipfe", elf, address], + capture_output=True, + ) + stdout = result.stdout.decode("utf-8") + if not stdout: + continue + if "?? ??" not in stdout: + print(stdout.strip()) + break + + print("loop") diff --git a/ports/espressif/tools/flash_layout.py b/ports/espressif/tools/flash_layout.py new file mode 100644 index 00000000000..a8394d29a06 --- /dev/null +++ b/ports/espressif/tools/flash_layout.py @@ -0,0 +1,94 @@ +# This file is part of the CircuitPython project: https://circuitpython.org +# +# SPDX-FileCopyrightText: 2026 Adafruit Industries +# SPDX-License-Identifier: MIT + +"""Choose the shared sdkconfig-flash-*.defaults file for a board. + +ESP-IDF picks its partition table from a sdkconfig file shared by boards with +the same flash size and partition layout. The Makefile names the file for the +build and tools/update_sdkconfig.py names it again to write the file back, so +the rules live here instead of in both places. + +An OTA slot has to fit the chip family's largest firmware image, so families +that can exceed 2MB use the 4MB-slot tables. There is a UF2 variant that also +matches tinyuf2, and a no-UF2 variant for boards without a USB device port. + +This is also a script so the Makefile can query it: + + python3 tools/flash_layout.py --family esp32p4 --flash-size 16MB --uf2 +""" + +import argparse + +SDKCONFIG_DIR = "esp-idf-config" + +# The largest firmware image each chip family needs to fit. Families that are +# not listed use the default 2MB slots of the shared partition tables. +MAX_FIRMWARE_SIZE = { + "esp32p4": "4MB", + "esp32s31": "4MB", +} +DEFAULT_MAX_FIRMWARE_SIZE = "2MB" + + +def flash_layout(family): + """Return the partition layout suffix, or "" for the default 2MB slots.""" + max_size = MAX_FIRMWARE_SIZE.get(family, DEFAULT_MAX_FIRMWARE_SIZE) + if max_size == DEFAULT_MAX_FIRMWARE_SIZE: + return "" + return f"ota{max_size}" + + +def size_options(family, flash_size, uf2_bootloader, large_user_fs_layout=False): + """Return the suffix after the flash size in a sdkconfig-flash name.""" + if flash_size == "2MB": + # No 2MB board uses UF2, so there is never room for an OTA partition. + return "-no-ota-no-uf2" + if flash_size == "4MB": + if uf2_bootloader: + # S2 and S3 use a single OTA partition and do not do OTA updates. + return "-no-ota" + if large_user_fs_layout: + # Some boards use a 2MB firmware and almost 2MB user filesystem, + # for historical reasons. + return "-no-ota-no-uf2-large-user_fs" + return "-no-ota-no-uf2" + # Everything with more than 4MB of flash. + layout = flash_layout(family) + if not uf2_bootloader: + return f"-no-uf2-{layout}" if layout else "-no-uf2" + if layout: + return f"-{layout}" + return "" + + +def sdkconfig_flash_filename(family, flash_size, uf2_bootloader, large_user_fs_layout=False): + """Return e.g. esp-idf-config/sdkconfig-flash-16MB-ota4MB.defaults.""" + options = size_options(family, flash_size, uf2_bootloader, large_user_fs_layout) + return f"{SDKCONFIG_DIR}/sdkconfig-flash-{flash_size}{options}.defaults" + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--family", required=True) + parser.add_argument("--flash-size", required=True) + parser.add_argument("--uf2", action="store_true", help="the board has a UF2 bootloader") + parser.add_argument( + "--large-user-fs", + action="store_true", + help="the board uses the large user filesystem layout", + ) + args = parser.parse_args() + print( + sdkconfig_flash_filename( + args.family, + args.flash_size, + args.uf2, + args.large_user_fs, + ) + ) + + +if __name__ == "__main__": + main() diff --git a/ports/espressif/tools/update_sdkconfig.py b/ports/espressif/tools/update_sdkconfig.py index 78ffa8590ca..837061c45f3 100644 --- a/ports/espressif/tools/update_sdkconfig.py +++ b/ports/espressif/tools/update_sdkconfig.py @@ -2,12 +2,14 @@ build.""" import pathlib +import subprocess import click import copy import kconfiglib -import kconfiglib.core import os +from flash_layout import sdkconfig_flash_filename + OPT_SETTINGS = [ "CONFIG_ESP_ERR_TO_NAME_LOOKUP", "CONFIG_ESP_CONSOLE_", @@ -148,6 +150,22 @@ def sym_default(sym): return False +def make_settings(board, names): + """Return the port Makefile's values for the given print- targets.""" + result = subprocess.run( + ["make", "-s", f"BOARD={board}", *(f"print-{name}" for name in names)], + stdout=subprocess.PIPE, + text=True, + check=True, + ) + settings = {} + for line in result.stdout.splitlines(): + name, separator, value = line.partition("=") + if separator and name.strip() in names: + settings[name.strip()] = value.strip() + return settings + + @click.command() @click.option("--debug") @click.option("--board") @@ -157,14 +175,15 @@ def sym_default(sym): default=False, help="Updates the sdkconfigs outside of the board directory.", ) -def update(debug, board, update_all): # noqa: C901: too complex +def update(debug, board, update_all): # noqa: C901 too complex """Updates related sdkconfig files based on the build directory version that was likely modified by menuconfig.""" board_make = pathlib.Path(f"boards/{board}/mpconfigboard.mk") psram_size = "0" - uf2_bootloader = None ble_enabled = None + load_native = True # Matches the mpconfigport.mk default. + mpy_native = False for line in board_make.read_text().split("\n"): if "=" not in line or line.startswith("#"): continue @@ -173,8 +192,6 @@ def update(debug, board, update_all): # noqa: C901: too complex value = value.strip() if key == "IDF_TARGET": target = value - if uf2_bootloader is None: - uf2_bootloader = target in ("esp32s2", "esp32s3") if ble_enabled is None: ble_enabled = target not in ("esp32s2",) # S2 doesn't support it. elif key == "CIRCUITPY_ESP_FLASH_SIZE": @@ -189,10 +206,12 @@ def update(debug, board, update_all): # noqa: C901: too complex psram_mode = value elif key == "CIRCUITPY_ESP_PSRAM_FREQ": psram_freq = value - elif key == "UF2_BOOTLOADER": - uf2_bootloader = not (value == "0") - elif key == "CIRCUITPY_BLEIO": + elif key == "CIRCUITPY_BLEIO_NATIVE": ble_enabled = not (value == "0") + elif key == "CIRCUITPY_LOAD_NATIVE": + load_native = not (value == "0") + elif key == "CIRCUITPY_ENABLE_MPY_NATIVE": + mpy_native = value == "1" os.environ["IDF_TARGET"] = target os.environ["COMPONENT_KCONFIGS_PROJBUILD_SOURCE_FILE"] = ( @@ -203,7 +222,7 @@ def update(debug, board, update_all): # noqa: C901: too complex kconfig_path = pathlib.Path(f"build-{board}/esp-idf/kconfigs.in") kconfig_path = pathlib.Path("esp-idf/Kconfig") - kconfig = kconfiglib.Kconfig(kconfig_path) + kconfig = kconfiglib.Kconfig(str(kconfig_path)) input_config = pathlib.Path(f"build-{board}/esp-idf/sdkconfig") kconfig.load_config(input_config) @@ -216,14 +235,22 @@ def update(debug, board, update_all): # noqa: C901: too complex else: opt_config = pathlib.Path("esp-idf-config/sdkconfig-opt.defaults") sdkconfigs.append(opt_config) - size_options = "" - if flash_size == "2MB": - size_options = "-no-ota-no-uf2" - elif not uf2_bootloader: - # These boards don't have native USB. - size_options = "-no-uf2" + # Ask the Makefile for the resolved values: it knows the board overrides + # and the port/target defaults that feed the layout decision. + layout_settings = make_settings( + board, + ( + "UF2_BOOTLOADER", + "CIRCUITPY_4MB_FLASH_LARGE_USER_FS_LAYOUT", + ), + ) flash_size_config = pathlib.Path( - f"esp-idf-config/sdkconfig-flash-{flash_size}{size_options}.defaults" + sdkconfig_flash_filename( + target, + flash_size, + layout_settings["UF2_BOOTLOADER"] == "1", + layout_settings["CIRCUITPY_4MB_FLASH_LARGE_USER_FS_LAYOUT"] == "1", + ) ) flash_mode_config = pathlib.Path(f"esp-idf-config/sdkconfig-flash-{flash_mode}.defaults") flash_freq_config = pathlib.Path(f"esp-idf-config/sdkconfig-flash-{flash_freq}.defaults") @@ -240,11 +267,14 @@ def update(debug, board, update_all): # noqa: C901: too complex if ble_enabled: ble_config = pathlib.Path("esp-idf-config/sdkconfig-ble.defaults") sdkconfigs.append(ble_config) + if load_native or mpy_native: + native_config = pathlib.Path("esp-idf-config/sdkconfig-native.defaults") + sdkconfigs.append(native_config) board_config = pathlib.Path(f"boards/{board}/sdkconfig") # Don't include the board file in cp defaults. The board may have custom # overrides. - cp_kconfig_defaults = kconfiglib.Kconfig(kconfig_path) + cp_kconfig_defaults = kconfiglib.Kconfig(str(kconfig_path)) for default_file in sdkconfigs: cp_kconfig_defaults.load_config(default_file, replace=False) @@ -321,7 +351,7 @@ def update(debug, board, update_all): # noqa: C901: too complex if print_debug: print(" " * len(current_group), i, config_string.strip()) - # Some files are `rsource`d into another kconfig with $IDF_TARGET as + # Some files are `rsource`d into another kconfig with $IDF_TARGET as # codespell:ignore rsource # part of the path. kconfiglib doesn't show this as a reference so # we have to look ourselves. target_reference = target in item.name_and_loc @@ -332,7 +362,7 @@ def update(debug, board, update_all): # noqa: C901: too complex shared_keys = {} first = True for path in pathlib.Path(".").glob(loc): - kc = kconfiglib.Kconfig(path) + kc = kconfiglib.Kconfig(str(path)) all_file_syms = set() for sym in kc.unique_defined_syms: all_file_syms.add(sym) @@ -378,6 +408,8 @@ def update(debug, board, update_all): # noqa: C901: too complex all_references.update(rdep.referenced) psram_reference = False for referenced in all_references: + if not referenced.name: + continue if referenced.name.startswith("IDF_TARGET"): target_reference = True if referenced.name in target_symbols: diff --git a/ports/litex/Makefile b/ports/litex/Makefile deleted file mode 100644 index 4e20b3c4ca1..00000000000 --- a/ports/litex/Makefile +++ /dev/null @@ -1,142 +0,0 @@ -# This file is part of the CircuitPython project: https://circuitpython.org -# -# SPDX-FileCopyrightText: Copyright (c) 2019 Scott Shawcroft for Adafruit Industries -# -# SPDX-License-Identifier: MIT - -include ../../py/circuitpy_mkenv.mk - -CROSS_COMPILE = riscv64-unknown-elf- - -####################################### -# CFLAGS -####################################### - -INC += -I. -INC += -I../.. -INC += -I$(BUILD) -INC += -I$(BUILD)/genhdr -INC += -I./boards -INC += -I./boards/$(BOARD) -INC += -I./peripherals -INC += -I../../lib/mp-readline -INC += -I../../lib/tinyusb/src -INC += -I../../supervisor/shared/usb - - -#Debugging/Optimization -ifeq ($(DEBUG), 1) - CFLAGS += -ggdb - # You may want to enable these flags to make setting breakpoints easier. - CFLAGS += -fno-inline -fno-ipa-sra - OPTIMIZATION_FLAGS ?= -Og -else - CFLAGS += -DNDEBUG -ggdb3 - OPTIMIZATION_FLAGS ?= -O2 -fno-inline-functions -endif - -# option to override compiler optimization level, set in boards/$(BOARD)/mpconfigboard.mk -CFLAGS += $(OPTIMIZATION_FLAGS) - -CFLAGS += $(INC) -Werror -Wall -std=gnu11 -nostdlib -fshort-enums $(BASE_CFLAGS) $(C_DEFS) $(CFLAGS_MOD) $(COPT) -Werror=missing-prototypes - -# TODO: check this -CFLAGS += -D__START=main -DFOMU - -LD_FILE := boards/$(BOARD)/$(BOARD)-spi.ld - -LDFLAGS = $(CFLAGS) -Wl,-nostdlib -Wl,-T,$(LD_FILE) -Wl,-Map=$@.map -Wl,-cref -Wl,-gc-sections -specs=nano.specs -Wl,-melf32lriscv -LIBS := -lgcc -lc - - -LDFLAGS += -ffreestanding -nostartfiles -Wl,--gc-section -Wl,-Bstatic -Wl,-melf32lriscv -nostartfiles \ - -Wl,--no-warn-mismatch \ - -Wl,--build-id=none - -# Use toolchain libm if we're not using our own. -ifndef INTERNAL_LIBM -LIBS += -lm -endif - -# TinyUSB defines -CFLAGS += -DCFG_TUSB_MCU=OPT_MCU_VALENTYUSB_EPTRI -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 - - -###################################### -# source -###################################### - - -SRC_C += \ - background.c \ - mphalport.c \ - boards/$(BOARD)/board.c \ - boards/$(BOARD)/pins.c - -ifneq ($(CIRCUITPY_USB),0) -SRC_C += lib/tinyusb/src/portable/valentyusb/eptri/dcd_eptri.c -endif - -SRC_S = \ - crt0-vexriscv.S - -SRC_COMMON_HAL_EXPANDED = $(addprefix shared-bindings/, $(SRC_COMMON_HAL)) \ - $(addprefix shared-bindings/, $(SRC_BINDINGS_ENUMS)) \ - $(addprefix common-hal/, $(SRC_COMMON_HAL)) - -SRC_SHARED_MODULE_EXPANDED = $(addprefix shared-bindings/, $(SRC_SHARED_MODULE)) \ - $(addprefix shared-module/, $(SRC_SHARED_MODULE)) \ - $(addprefix shared-module/, $(SRC_SHARED_MODULE_INTERNAL)) - -$(BUILD)/lib/tlsf/tlsf.o: CFLAGS += -Wno-cast-align - -ifneq ($(FROZEN_MPY_DIR),) -FROZEN_MPY_PY_FILES := $(shell find -L $(FROZEN_MPY_DIR) -type f -name '*.py') -FROZEN_MPY_MPY_FILES := $(addprefix $(BUILD)/,$(FROZEN_MPY_PY_FILES:.py=.mpy)) -endif - -OBJ += $(PY_O) $(SUPERVISOR_O) $(addprefix $(BUILD)/, $(SRC_C:.c=.o)) -OBJ += $(addprefix $(BUILD)/, $(SRC_COMMON_HAL_EXPANDED:.c=.o)) -OBJ += $(addprefix $(BUILD)/, $(SRC_SHARED_MODULE_EXPANDED:.c=.o)) -ifeq ($(INTERNAL_LIBM),1) -OBJ += $(addprefix $(BUILD)/, $(SRC_LIBM:.c=.o)) -endif -OBJ += $(addprefix $(BUILD)/, $(SRC_CIRCUITPY_COMMON:.c=.o)) -OBJ += $(addprefix $(BUILD)/, $(SRC_S:.S=.o)) -OBJ += $(addprefix $(BUILD)/, $(SRC_MOD:.c=.o)) - -$(BUILD)/$(FATFS_DIR)/ff.o: COPT += -Os -$(filter $(PY_BUILD)/../extmod/vfs_fat_%.o, $(PY_O)): COPT += -Os - -# List of sources for qstr extraction -SRC_QSTR += $(SRC_C) $(SRC_SUPERVISOR) $(SRC_MOD) $(SRC_COMMON_HAL_EXPANDED) $(SRC_SHARED_MODULE_EXPANDED) $(SRC_CIRCUITPY_COMMON) -# Sources that only hold QSTRs after pre-processing. -SRC_QSTR_PREPROCESSOR += - - -all: $(BUILD)/firmware.bin $(BUILD)/firmware.dfu - -ifeq ($(VALID_BOARD),) -$(BUILD)/firmware.elf: invalid-board -else -$(BUILD)/firmware.elf: $(OBJ) - $(STEPECHO) "LINK $@" - $(Q)$(CC) -o $@ $(LDFLAGS) $^ -Wl,--print-memory-usage -Wl,--start-group $(LIBS) -Wl,--end-group - $(Q)$(SIZE) $@ | $(PYTHON) $(TOP)/tools/build_memory_info.py $(LD_FILE) $(BUILD) -endif - -$(BUILD)/firmware.bin: $(BUILD)/firmware.elf - $(STEPECHO) "Create $@" - $(Q)$(OBJCOPY) -O binary $^ $@ -# $(Q)$(OBJCOPY) -O binary -j .vectors -j .text -j .data $^ $@ - -$(BUILD)/firmware.hex: $(BUILD)/firmware.elf - $(STEPECHO) "Create $@" - $(Q)$(OBJCOPY) -O ihex $^ $@ -# $(Q)$(OBJCOPY) -O ihex -j .vectors -j .text -j .data $^ $@ - -$(BUILD)/firmware.dfu: $(BUILD)/firmware.bin - $(ECHO) "Create $@" - $(PYTHON) $(TOP)/tools/dfu.py -b $^ -D 0x1209:0x5bf0 "$(BUILD)/firmware.dfu" - -include $(TOP)/py/mkrules.mk diff --git a/ports/litex/README.rst b/ports/litex/README.rst deleted file mode 100644 index bc1d20e6170..00000000000 --- a/ports/litex/README.rst +++ /dev/null @@ -1,25 +0,0 @@ -LiteX (FPGA) -============ - -`LiteX `_ is a Python-based System on a Chip (SoC) designer -for open source supported Field Programmable Gate Array (FPGA) chips. This means that the CPU -core(s) and peripherals are not defined by the physical chip. Instead, they are loaded as separate -"gateware". Once this gateware is loaded, CircuitPython can be loaded on top of it to work as -expected. - -Installation -------------- - -You'll need ``dfu-util`` to install CircuitPython on the Fomu. - -Make sure the foboot bootloader is updated. Instructions are here: https://github.com/im-tomu/fomu-workshop/blob/master/docs/bootloader.rst - -Once you've updated the bootloader, you should know how to use ``dfu-util``. It's pretty easy! - -To install CircuitPython do: - -.. code-block:: shell - - dfu-util -D adafruit-circuitpython-fomu-en_US-.dfu - -It will install and then restart. CIRCUITPY should appear as it usually does and work the same. diff --git a/ports/litex/background.c b/ports/litex/background.c deleted file mode 100644 index a09607bdef1..00000000000 --- a/ports/litex/background.c +++ /dev/null @@ -1,20 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2017 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "py/runtime.h" -#include "supervisor/filesystem.h" -#include "supervisor/usb.h" -#include "supervisor/shared/stack.h" -#include "supervisor/port.h" - -void port_background_task(void) { -} -void port_background_tick(void) { -} -void port_start_background_tick(void) { -} -void port_finish_background_tick(void) { -} diff --git a/ports/litex/background.h b/ports/litex/background.h deleted file mode 100644 index c2d98475678..00000000000 --- a/ports/litex/background.h +++ /dev/null @@ -1,12 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2019 Dan Halbert for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#pragma once - -#ifndef MICROPY_INCLUDED_LITEX_BACKGROUND_H -#define MICROPY_INCLUDED_LITEX_BACKGROUND_H - -#endif // MICROPY_INCLUDED_LITEX_BACKGROUND_H diff --git a/ports/litex/boards/fomu/board.c b/ports/litex/boards/fomu/board.c deleted file mode 100644 index c54e877e633..00000000000 --- a/ports/litex/boards/fomu/board.c +++ /dev/null @@ -1,48 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2017 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "supervisor/board.h" - -#include "mpconfigboard.h" -#include "csr.h" - -// ICE40 LED Driver hard macro. -// See http://www.latticesemi.com/-/media/LatticeSemi/Documents/ApplicationNotes/IK/ICE40LEDDriverUsageGuide.ashx?document_id=50668 -enum led_registers { - LEDDCR0 = 8, - LEDDBR = 9, - LEDDONR = 10, - LEDDOFR = 11, - LEDDBCRR = 5, - LEDDBCFR = 6, - LEDDPWRR = 1, - LEDDPWRG = 2, - LEDDPWRB = 3, -}; - -#define BREATHE_ENABLE (1 << 7) -#define BREATHE_EDGE_ON (0 << 6) -#define BREATHE_EDGE_BOTH (1 << 6) -#define BREATHE_MODE_MODULATE (1 << 5) -#define BREATHE_RATE(x) ((x & 7) << 0) - -// Write a value into the LEDDA_IP register. -static void ledda_write(uint8_t value, uint8_t addr) { - rgb_addr_write(addr); - rgb_dat_write(value); -} - -void board_init(void) { - uint8_t onrate = 15; - uint8_t offrate = 1; - - ledda_write(BREATHE_ENABLE | BREATHE_MODE_MODULATE | BREATHE_RATE(onrate), LEDDBCRR); - ledda_write(BREATHE_ENABLE | BREATHE_MODE_MODULATE | BREATHE_RATE(offrate), LEDDBCFR); - - ledda_write(123, LEDDPWRR); // Red - ledda_write(3, LEDDPWRG); // Green - ledda_write(98, LEDDPWRB); // Blue -} diff --git a/ports/litex/boards/fomu/csr.h b/ports/litex/boards/fomu/csr.h deleted file mode 100644 index c2a2495f7b7..00000000000 --- a/ports/litex/boards/fomu/csr.h +++ /dev/null @@ -1,650 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2017 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -// -------------------------------------------------------------------------------- -// Auto-generated by Migen (f4fcd10) & LiteX (de205d4a) on 2019-11-25 14:57:34 -// -------------------------------------------------------------------------------- -#include -#pragma once -#include -#ifdef CSR_ACCESSORS_DEFINED -extern void csr_writeb(uint8_t value, unsigned long addr); -extern uint8_t csr_readb(unsigned long addr); -extern void csr_writew(uint16_t value, unsigned long addr); -extern uint16_t csr_readw(unsigned long addr); -extern void csr_writel(uint32_t value, unsigned long addr); -extern uint32_t csr_readl(unsigned long addr); -#else /* ! CSR_ACCESSORS_DEFINED */ -#include -#endif /* ! CSR_ACCESSORS_DEFINED */ - -/* ctrl */ -#define CSR_CTRL_BASE 0xe0000000L -#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; -} -static inline void ctrl_reset_write(unsigned char value) { - 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; -} -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); -} -#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; -} - -/* lxspi */ -#define CSR_LXSPI_BASE 0xe0007800L -#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; -} -static inline void lxspi_bitbang_write(unsigned char value) { - csr_writel(value, 0xe0007800L); -} -#define CSR_LXSPI_BITBANG_MOSI_OFFSET 0 -#define CSR_LXSPI_BITBANG_MOSI_SIZE 1 -#define CSR_LXSPI_BITBANG_CLK_OFFSET 1 -#define CSR_LXSPI_BITBANG_CLK_SIZE 1 -#define CSR_LXSPI_BITBANG_CS_N_OFFSET 2 -#define CSR_LXSPI_BITBANG_CS_N_SIZE 1 -#define CSR_LXSPI_BITBANG_DIR_OFFSET 3 -#define CSR_LXSPI_BITBANG_DIR_SIZE 1 -#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; -} -#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; -} -static inline void lxspi_bitbang_en_write(unsigned char value) { - csr_writel(value, 0xe0007808L); -} - -/* messible */ -#define CSR_MESSIBLE_BASE 0xe0008000L -#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; -} -static inline void messible_in_write(unsigned char value) { - 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; -} -#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; -} -#define CSR_MESSIBLE_STATUS_FULL_OFFSET 0 -#define CSR_MESSIBLE_STATUS_FULL_SIZE 1 -#define CSR_MESSIBLE_STATUS_HAVE_OFFSET 1 -#define CSR_MESSIBLE_STATUS_HAVE_SIZE 1 - -/* reboot */ -#define CSR_REBOOT_BASE 0xe0006000L -#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; -} -static inline void reboot_ctrl_write(unsigned char value) { - csr_writel(value, 0xe0006000L); -} -#define CSR_REBOOT_CTRL_IMAGE_OFFSET 0 -#define CSR_REBOOT_CTRL_IMAGE_SIZE 2 -#define CSR_REBOOT_CTRL_KEY_OFFSET 2 -#define CSR_REBOOT_CTRL_KEY_SIZE 6 -#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; -} -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); -} - -/* rgb */ -#define CSR_RGB_BASE 0xe0006800L -#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; -} -static inline void rgb_dat_write(unsigned char value) { - 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; -} -static inline void rgb_addr_write(unsigned char value) { - 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; -} -static inline void rgb_ctrl_write(unsigned char value) { - csr_writel(value, 0xe0006808L); -} -#define CSR_RGB_CTRL_EXE_OFFSET 0 -#define CSR_RGB_CTRL_EXE_SIZE 1 -#define CSR_RGB_CTRL_CURREN_OFFSET 1 -#define CSR_RGB_CTRL_CURREN_SIZE 1 -#define CSR_RGB_CTRL_RGBLEDEN_OFFSET 2 -#define CSR_RGB_CTRL_RGBLEDEN_SIZE 1 -#define CSR_RGB_CTRL_RRAW_OFFSET 3 -#define CSR_RGB_CTRL_RRAW_SIZE 1 -#define CSR_RGB_CTRL_GRAW_OFFSET 4 -#define CSR_RGB_CTRL_GRAW_SIZE 1 -#define CSR_RGB_CTRL_BRAW_OFFSET 5 -#define CSR_RGB_CTRL_BRAW_SIZE 1 -#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; -} -static inline void rgb_raw_write(unsigned char value) { - csr_writel(value, 0xe000680cL); -} -#define CSR_RGB_RAW_R_OFFSET 0 -#define CSR_RGB_RAW_R_SIZE 1 -#define CSR_RGB_RAW_G_OFFSET 1 -#define CSR_RGB_RAW_G_SIZE 1 -#define CSR_RGB_RAW_B_OFFSET 2 -#define CSR_RGB_RAW_B_SIZE 1 - -/* timer0 */ -#define CSR_TIMER0_BASE 0xe0002800L -#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; -} -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); -} -#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; -} -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); -} -#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; -} -static inline void timer0_en_write(unsigned char value) { - 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; -} -static inline void timer0_update_value_write(unsigned char value) { - 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; -} -#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; -} -static inline void timer0_ev_status_write(unsigned char value) { - 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; -} -static inline void timer0_ev_pending_write(unsigned char value) { - 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; -} -static inline void timer0_ev_enable_write(unsigned char value) { - csr_writel(value, 0xe0002840L); -} - -/* touch */ -#define CSR_TOUCH_BASE 0xe0005800L -#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; -} -static inline void touch_o_write(unsigned char value) { - 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; -} -static inline void touch_oe_write(unsigned char value) { - 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; -} - -/* usb */ -#define CSR_USB_BASE 0xe0004800L -#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; -} -static inline void usb_pullup_out_write(unsigned char value) { - 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; -} -static inline void usb_address_write(unsigned char value) { - 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; -} -#define CSR_USB_NEXT_EV_IN_OFFSET 0 -#define CSR_USB_NEXT_EV_IN_SIZE 1 -#define CSR_USB_NEXT_EV_OUT_OFFSET 1 -#define CSR_USB_NEXT_EV_OUT_SIZE 1 -#define CSR_USB_NEXT_EV_SETUP_OFFSET 2 -#define CSR_USB_NEXT_EV_SETUP_SIZE 1 -#define CSR_USB_NEXT_EV_RESET_OFFSET 3 -#define CSR_USB_NEXT_EV_RESET_SIZE 1 -#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; -} -#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; -} -static inline void usb_setup_ctrl_write(unsigned char value) { - 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; -} -#define CSR_USB_SETUP_STATUS_EPNO_OFFSET 0 -#define CSR_USB_SETUP_STATUS_EPNO_SIZE 4 -#define CSR_USB_SETUP_STATUS_HAVE_OFFSET 4 -#define CSR_USB_SETUP_STATUS_HAVE_SIZE 1 -#define CSR_USB_SETUP_STATUS_PEND_OFFSET 5 -#define CSR_USB_SETUP_STATUS_PEND_SIZE 1 -#define CSR_USB_SETUP_STATUS_IS_IN_OFFSET 6 -#define CSR_USB_SETUP_STATUS_IS_IN_SIZE 1 -#define CSR_USB_SETUP_STATUS_DATA_OFFSET 7 -#define CSR_USB_SETUP_STATUS_DATA_SIZE 1 -#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; -} -static inline void usb_setup_ev_status_write(unsigned char value) { - 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; -} -static inline void usb_setup_ev_pending_write(unsigned char value) { - 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; -} -static inline void usb_setup_ev_enable_write(unsigned char value) { - 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; -} -static inline void usb_in_data_write(unsigned char value) { - 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; -} -static inline void usb_in_ctrl_write(unsigned char value) { - csr_writel(value, 0xe0004828L); -} -#define CSR_USB_IN_CTRL_EPNO_OFFSET 0 -#define CSR_USB_IN_CTRL_EPNO_SIZE 4 -#define CSR_USB_IN_CTRL_RESET_OFFSET 5 -#define CSR_USB_IN_CTRL_RESET_SIZE 1 -#define CSR_USB_IN_CTRL_STALL_OFFSET 6 -#define CSR_USB_IN_CTRL_STALL_SIZE 1 -#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; -} -#define CSR_USB_IN_STATUS_IDLE_OFFSET 0 -#define CSR_USB_IN_STATUS_IDLE_SIZE 1 -#define CSR_USB_IN_STATUS_HAVE_OFFSET 4 -#define CSR_USB_IN_STATUS_HAVE_SIZE 1 -#define CSR_USB_IN_STATUS_PEND_OFFSET 5 -#define CSR_USB_IN_STATUS_PEND_SIZE 1 -#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; -} -static inline void usb_in_ev_status_write(unsigned char value) { - 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; -} -static inline void usb_in_ev_pending_write(unsigned char value) { - 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; -} -static inline void usb_in_ev_enable_write(unsigned char value) { - 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; -} -#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; -} -static inline void usb_out_ctrl_write(unsigned char value) { - csr_writel(value, 0xe0004840L); -} -#define CSR_USB_OUT_CTRL_EPNO_OFFSET 0 -#define CSR_USB_OUT_CTRL_EPNO_SIZE 4 -#define CSR_USB_OUT_CTRL_ENABLE_OFFSET 4 -#define CSR_USB_OUT_CTRL_ENABLE_SIZE 1 -#define CSR_USB_OUT_CTRL_RESET_OFFSET 5 -#define CSR_USB_OUT_CTRL_RESET_SIZE 1 -#define CSR_USB_OUT_CTRL_STALL_OFFSET 6 -#define CSR_USB_OUT_CTRL_STALL_SIZE 1 -#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; -} -#define CSR_USB_OUT_STATUS_EPNO_OFFSET 0 -#define CSR_USB_OUT_STATUS_EPNO_SIZE 4 -#define CSR_USB_OUT_STATUS_HAVE_OFFSET 4 -#define CSR_USB_OUT_STATUS_HAVE_SIZE 1 -#define CSR_USB_OUT_STATUS_PEND_OFFSET 5 -#define CSR_USB_OUT_STATUS_PEND_SIZE 1 -#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; -} -static inline void usb_out_ev_status_write(unsigned char value) { - 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; -} -static inline void usb_out_ev_pending_write(unsigned char value) { - 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; -} -static inline void usb_out_ev_enable_write(unsigned char value) { - 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; -} -#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; -} - -/* version */ -#define CSR_VERSION_BASE 0xe0007000L -#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; -} -#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; -} -#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; -} -#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; -} -#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; -} -#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; -} -#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; -} -#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; -} diff --git a/ports/litex/boards/fomu/fomu-spi.ld b/ports/litex/boards/fomu/fomu-spi.ld deleted file mode 100644 index 33ba3db686b..00000000000 --- a/ports/litex/boards/fomu/fomu-spi.ld +++ /dev/null @@ -1,122 +0,0 @@ -/* - GNU linker script for Fomu -*/ - -ENTRY(_start) - -/* Specify the memory areas */ -MEMORY -{ - FLASH (rx) : ORIGIN = 0x20040000, LENGTH = 0x100000 /* entire flash, 1 MiB */ - FLASH_FIRMWARE (rx) : ORIGIN = 0x20040000, LENGTH = 0x100000 /* entire flash, 1 MiB */ - RAM (xrw) : ORIGIN = 0x10000000, LENGTH = 0x00020000 /* 128 KiB */ -} - -/* top end of the stack */ -_estack = ORIGIN(RAM) + LENGTH(RAM); - -/* define output sections */ -SECTIONS -{ - /* This is the initialized data section - The program executes knowing that the data is in the RAM - but the loader puts the initial values in the FLASH_FIRMWARE (inidata). - It is one task of the startup to copy the initial values from FLASH to RAM. */ - .data : AT ( _sidata ) - { - . = ALIGN(4); - _sdata = .; /* create a global symbol at data start; used by startup code in order to initialise the .data section in RAM */ - - *(.itcm.*) /* Instruction Tightly Coupled Memory */ - *(.dtcm_data.*) /* Data Tightly Coupled Memory */ - - *(.text.cmp_lfn) - *(.text.qstr_find_strn) - *(.text.dcd_edpt_xfer) - *(.text.pop_rule) - *(.text.ff_wtoupper) - *(.text.dir_find) - *(.text.push_rule) - *(.text.csr_writel) - *(.text.csr_readl) - *(.text.timer0_ev_pending_write) - *(.text.autoreload_tick) - *(.text.filesystem_tick) - *(.text.usb_background) - - *(.text.dcd_*) - *(.text.tud_control_*) - *(.text.tud_cdc_n_write_flush) - *(.text.tud_task) - *(.text.tu_edpt_dir) - *(.text.tu_fifo_empty) - *(.text.usbd_edpt_busy) - *(.text.usb_irq_handler) - *(.text.supervisor_tick) - *(.text.port_get_raw_ticks) - *(.text.__modsi3) - *(.text.__udivsi3) - *(.text.irq_getmask) - *(.text.irq_setmask) - *(.text.irq_pending) - *(.text._osal_q_lock) - *(.text.osal_queue_receive) - - *(.text.mp_obj_get_type) - *(.text.mp_parse) - *(.text.parse_compile_execute) - *(.text.mp_map_lookup) - *(.text.mp_execute_bytecode) /* Note: this function is 7kb */ - - *(.ramtext) /* .text* sections (code) */ - *(.ramtext*) /* .text* sections (code) */ - *(.data) /* .data sections */ - *(.data*) /* .data* sections */ - *(.sdata) /* .data sections */ - *(.sdata*) /* .data* sections */ - - . = ALIGN(4); - _edata = .; /* define a global symbol at data end; used by startup code in order to initialise the .data section in RAM */ - } >RAM - - /* The program code and other data goes into FLASH_FIRMWARE */ - .text : - { - . = ALIGN(4); - KEEP(*(.text.start)) /* isr vector table */ - *(.text) /* .text sections (code) */ - *(.text*) /* .text* sections (code) */ - *(.rodata) /* .rodata sections (constants, strings, etc.) */ - *(.rodata*) /* .rodata* sections (constants, strings, etc.) */ - *(.srodata) /* .rodata sections (constants, strings, etc.) */ - *(.srodata*) /* .rodata* sections (constants, strings, etc.) */ - - . = ALIGN(4); - _etext = .; /* define a global symbol at end of code */ - _sidata = _etext; /* This is used by the startup in order to initialize the .data section */ - } >FLASH_FIRMWARE - - /* Uninitialized data section */ - .bss : - { - . = ALIGN(4); - _sbss = .; /* define a global symbol at bss start; used by startup code */ - *(.bss) - *(.bss*) - *(.dtcm_bss.*) /* Data Tightly Coupled Memory */ - *(.sbss) - *(.sbss*) - *(COMMON) - - . = ALIGN(4); - _ebss = .; /* define a global symbol at bss end; used by startup code */ - } >RAM - - - /* this is to define the start of the heap, and make sure we have a minimum size */ - .heap : - { - . = ALIGN(4); - _heap_start = .; /* define a global symbol at heap start */ - } >RAM -} diff --git a/ports/litex/boards/fomu/generated/soc.h b/ports/litex/boards/fomu/generated/soc.h deleted file mode 100644 index dc821bc6b4a..00000000000 --- a/ports/litex/boards/fomu/generated/soc.h +++ /dev/null @@ -1,61 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2024 Adafruit Industries LLC -// -// SPDX-License-Identifier: MIT - -// -------------------------------------------------------------------------------- -// Auto-generated by Migen (f4fcd10) & LiteX (de205d4a) on 2019-11-25 15:17:59 -// -------------------------------------------------------------------------------- -#pragma once -#define CONFIG_BITSTREAM_SYNC_HEADER1 2123999870 -static inline int config_bitstream_sync_header1_read(void) { - return 2123999870; -} -#define CONFIG_BITSTREAM_SYNC_HEADER2 2125109630 -static inline int config_bitstream_sync_header2_read(void) { - return 2125109630; -} -#define CONFIG_CLOCK_FREQUENCY 12000000 -static inline int config_clock_frequency_read(void) { - return 12000000; -} -#define CONFIG_CPU_RESET_ADDR 0 -static inline int config_cpu_reset_addr_read(void) { - return 0; -} -#define CONFIG_CPU_TYPE "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"; -} -#define CONFIG_CPU_VARIANT_MIN -#define CONFIG_CSR_ALIGNMENT 32 -static inline int config_csr_alignment_read(void) { - return 32; -} -#define CONFIG_CSR_DATA_WIDTH 8 -static inline int config_csr_data_width_read(void) { - return 8; -} -#define CONFIG_FOMU_REV "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; -} -#define TIMER0_INTERRUPT 2 -static inline int timer0_interrupt_read(void) { - return 2; -} -#define USB_INTERRUPT 3 -static inline int usb_interrupt_read(void) { - return 3; -} diff --git a/ports/litex/boards/fomu/mpconfigboard.h b/ports/litex/boards/fomu/mpconfigboard.h deleted file mode 100644 index 497809110ed..00000000000 --- a/ports/litex/boards/fomu/mpconfigboard.h +++ /dev/null @@ -1,18 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2019 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#pragma once - -// 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 BOARD_FLASH_SIZE (FLASH_SIZE) diff --git a/ports/litex/boards/fomu/mpconfigboard.mk b/ports/litex/boards/fomu/mpconfigboard.mk deleted file mode 100644 index c8de94e9c06..00000000000 --- a/ports/litex/boards/fomu/mpconfigboard.mk +++ /dev/null @@ -1,19 +0,0 @@ -USB_VID = 0x1209 -USB_PID = 0x5BF0 -USB_PRODUCT = "Fomu" -USB_MANUFACTURER = "Foosn" - -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 - -# Fomu only implements rv32i -CFLAGS += -march=rv32i -mabi=ilp32 -LDFLAGS += -march=rv32i -mabi=ilp32 - -CIRCUITPY_NEOPIXEL_WRITE = 1 -CIRCUITPY_DIGITALIO = 1 -CIRCUITPY_MICROCONTROLLER = 1 diff --git a/ports/litex/boards/fomu/pins.c b/ports/litex/boards/fomu/pins.c deleted file mode 100644 index a462c31528f..00000000000 --- a/ports/litex/boards/fomu/pins.c +++ /dev/null @@ -1,17 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2017 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "shared-bindings/board/__init__.h" - -static const mp_rom_map_elem_t board_module_globals_table[] = { - CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS - - { 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_module_globals_table); diff --git a/ports/litex/boards/fomu/profiling.gdb.txt b/ports/litex/boards/fomu/profiling.gdb.txt deleted file mode 100644 index 28faf45b73d..00000000000 --- a/ports/litex/boards/fomu/profiling.gdb.txt +++ /dev/null @@ -1,16 +0,0 @@ -set pagination 0 -set logging file profile.txt -set logging overwrite - -server define poor_profile -set $total = $arg0 -set $i = 0 - set logging on - while($i<$total) - set $i = $i + 1 - cont - p $pc - bt - end - set logging off -end diff --git a/ports/litex/common-hal/digitalio/DigitalInOut.c b/ports/litex/common-hal/digitalio/DigitalInOut.c deleted file mode 100644 index 30dd3f4addf..00000000000 --- a/ports/litex/common-hal/digitalio/DigitalInOut.c +++ /dev/null @@ -1,104 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2017 Scott Shawcroft for Adafruit Industries -// SPDX-FileCopyrightText: Copyright (c) 2019 Lucian Copeland for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "shared-bindings/digitalio/DigitalInOut.h" -#include "py/runtime.h" - -#include "csr.h" - -void common_hal_digitalio_digitalinout_never_reset( - 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) { - - // claim_pin(pin); - self->pin = pin; - - return DIGITALINOUT_OK; -} - -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) { - if (common_hal_digitalio_digitalinout_deinited(self)) { - return; - } - - // reset_pin_number(0, self->pin->number); - self->pin = NULL; -} - -digitalinout_result_t common_hal_digitalio_digitalinout_switch_to_input( - digitalio_digitalinout_obj_t *self, digitalio_pull_t pull) { - (void)pull; - touch_oe_write(touch_oe_read() & ~(1 << self->pin->number)); - return DIGITALINOUT_OK; -} - -digitalinout_result_t common_hal_digitalio_digitalinout_switch_to_output( - 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)); - return DIGITALINOUT_OK; -} - -digitalio_direction_t common_hal_digitalio_digitalinout_get_direction( - 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) { - touch_o_write(touch_o_read() | (1 << self->pin->number)); - } else { - touch_o_write(touch_o_read() & ~(1 << self->pin->number)); - } -} - -bool common_hal_digitalio_digitalinout_get_value( - 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) { - (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) { - return DRIVE_MODE_PUSH_PULL; - } else { - return DRIVE_MODE_OPEN_DRAIN; - } -} - -digitalinout_result_t common_hal_digitalio_digitalinout_set_pull( - digitalio_digitalinout_obj_t *self, digitalio_pull_t pull) { - (void)self; - (void)pull; - return DIGITALINOUT_OK; -} - -digitalio_pull_t common_hal_digitalio_digitalinout_get_pull( - digitalio_digitalinout_obj_t *self) { - return PULL_NONE; -} diff --git a/ports/litex/common-hal/digitalio/DigitalInOut.h b/ports/litex/common-hal/digitalio/DigitalInOut.h deleted file mode 100644 index f58b23832b1..00000000000 --- a/ports/litex/common-hal/digitalio/DigitalInOut.h +++ /dev/null @@ -1,15 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2017 Scott Shawcroft for Adafruit Industries -// SPDX-FileCopyrightText: Copyright (c) 2019 Lucian Copeland for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#pragma once - -#include "common-hal/microcontroller/Pin.h" - -typedef struct { - mp_obj_base_t base; - const mcu_pin_obj_t *pin; -} digitalio_digitalinout_obj_t; diff --git a/ports/litex/common-hal/digitalio/__init__.c b/ports/litex/common-hal/digitalio/__init__.c deleted file mode 100644 index fa222ed01f0..00000000000 --- a/ports/litex/common-hal/digitalio/__init__.c +++ /dev/null @@ -1,7 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2024 Adafruit Industries LLC -// -// SPDX-License-Identifier: MIT - -// No digitalio module functions. diff --git a/ports/litex/common-hal/microcontroller/Pin.c b/ports/litex/common-hal/microcontroller/Pin.c deleted file mode 100644 index dea848f1ec3..00000000000 --- a/ports/litex/common-hal/microcontroller/Pin.c +++ /dev/null @@ -1,46 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2016 Scott Shawcroft for Adafruit Industries -// SPDX-FileCopyrightText: Copyright (c) 2019 Lucian Copeland for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "shared-bindings/microcontroller/Pin.h" - -#include "py/mphal.h" - -static uint8_t claimed_pins[1]; - -// 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_port == 0x0F) { - return; - } - - // Clear claimed bit. - claimed_pins[pin_port] &= ~(1 << pin_number); -} - -void common_hal_reset_pin(const mcu_pin_obj_t *pin) { - if (pin == NULL) { - return; - } - reset_pin_number(0, pin->number); -} - -void claim_pin(const mcu_pin_obj_t *pin) { - // Set bit in claimed_pins bitmask. - claimed_pins[0] |= 1 << pin->number; -} - -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 << pin_number); -} - -bool common_hal_mcu_pin_is_free(const mcu_pin_obj_t *pin) { - return pin_number_is_free(0, pin->number); -} diff --git a/ports/litex/common-hal/microcontroller/Pin.h b/ports/litex/common-hal/microcontroller/Pin.h deleted file mode 100644 index 542f3e979b5..00000000000 --- a/ports/litex/common-hal/microcontroller/Pin.h +++ /dev/null @@ -1,36 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2016 Scott Shawcroft -// -// SPDX-License-Identifier: MIT - -#pragma once - -#include "py/mphal.h" - - -typedef struct { - mp_obj_base_t base; - uint8_t number; -} mcu_pin_obj_t; - -#define PIN(p_number) \ - { \ - { &mcu_pin_type }, \ - .number = p_number \ - } - -extern const mcu_pin_obj_t pin_TOUCH1; -extern const mcu_pin_obj_t pin_TOUCH2; -extern const mcu_pin_obj_t pin_TOUCH3; -extern const mcu_pin_obj_t pin_TOUCH4; - -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_port, uint8_t pin_number); -void claim_pin(const mcu_pin_obj_t *pin); -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); -uint16_t pin_mask(uint8_t pin_number); diff --git a/ports/litex/common-hal/microcontroller/Processor.c b/ports/litex/common-hal/microcontroller/Processor.c deleted file mode 100644 index cf80a01d4e6..00000000000 --- a/ports/litex/common-hal/microcontroller/Processor.c +++ /dev/null @@ -1,50 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2017 Dan Halbert for Adafruit Industries -// SPDX-FileCopyrightText: Copyright (c) 2019 Lucian Copeland for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include -#include "py/runtime.h" - -#include "common-hal/microcontroller/Processor.h" -#include "shared-bindings/microcontroller/Processor.h" -#include "shared-bindings/microcontroller/ResetReason.h" - -#include "csr.h" -#include "generated/soc.h" - -float common_hal_mcu_processor_get_temperature(void) { - return NAN; -} - -float common_hal_mcu_processor_get_voltage(void) { - return NAN; -} - -uint32_t common_hal_mcu_processor_get_frequency(void) { - return CONFIG_CLOCK_FREQUENCY; -} - -void common_hal_mcu_processor_get_uid(uint8_t raw_id[]) { - raw_id[0] = csr_readl(CSR_VERSION_MAJOR_ADDR); - raw_id[1] = csr_readl(CSR_VERSION_MINOR_ADDR); - raw_id[2] = csr_readl(CSR_VERSION_REVISION_ADDR); - raw_id[3] = csr_readl(CSR_VERSION_GITREV_ADDR + 0); - raw_id[4] = csr_readl(CSR_VERSION_GITREV_ADDR + 4); - raw_id[5] = csr_readl(CSR_VERSION_GITREV_ADDR + 8); - raw_id[6] = csr_readl(CSR_VERSION_GITREV_ADDR + 12); - raw_id[7] = csr_readl(CSR_VERSION_GITEXTRA_ADDR + 0); - raw_id[8] = csr_readl(CSR_VERSION_GITEXTRA_ADDR + 4); - raw_id[9] = csr_readl(CSR_VERSION_DIRTY_ADDR); - raw_id[10] = csr_readl(CSR_VERSION_MODEL_ADDR); - raw_id[11] = csr_readl(CSR_VERSION_SEED_ADDR + 0); - raw_id[12] = csr_readl(CSR_VERSION_SEED_ADDR + 4); - raw_id[13] = csr_readl(CSR_VERSION_SEED_ADDR + 8); - raw_id[14] = csr_readl(CSR_VERSION_SEED_ADDR + 12); -} - -mcu_reset_reason_t common_hal_mcu_processor_get_reset_reason(void) { - return RESET_REASON_UNKNOWN; -} diff --git a/ports/litex/common-hal/microcontroller/Processor.h b/ports/litex/common-hal/microcontroller/Processor.h deleted file mode 100644 index 56da8367f8c..00000000000 --- a/ports/litex/common-hal/microcontroller/Processor.h +++ /dev/null @@ -1,16 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2017 Dan Halbert for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#pragma once - -#define COMMON_HAL_MCU_PROCESSOR_UID_LENGTH 15 - -#include "py/obj.h" - -typedef struct { - mp_obj_base_t base; - // Stores no state currently. -} mcu_processor_obj_t; diff --git a/ports/litex/common-hal/microcontroller/__init__.c b/ports/litex/common-hal/microcontroller/__init__.c deleted file mode 100644 index 02f3372c392..00000000000 --- a/ports/litex/common-hal/microcontroller/__init__.c +++ /dev/null @@ -1,96 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2016 Scott Shawcroft for Adafruit Industries -// SPDX-FileCopyrightText: Copyright (c) 2019 Lucian Copeland for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "py/mphal.h" -#include "py/obj.h" -#include "py/runtime.h" - -#include "common-hal/microcontroller/Pin.h" -#include "common-hal/microcontroller/Processor.h" - -#include "shared-bindings/microcontroller/__init__.h" -#include "shared-bindings/microcontroller/Pin.h" -#include "shared-bindings/microcontroller/Processor.h" - -#include "supervisor/filesystem.h" -#include "supervisor/shared/safe_mode.h" - -#include "csr.h" -#include "irq.h" - -void common_hal_mcu_delay_us(uint32_t delay) { - // if (__get_PRIMASK() == 0x00000000) { - // //by default use ticks_ms - // uint32_t start = get_us(); - // while (get_us()-start < delay) { - // __asm__ __volatile__("nop"); - // } - // } else { - // //when SysTick is disabled, approximate with busy loop - // const uint32_t ucount = HAL_RCC_GetSysClockFreq() / 1000000 * delay / LOOP_TICKS; - // for (uint32_t count = 0; ++count <= ucount;) { - // } - // } -} - -volatile uint32_t nesting_count = 0; - -__attribute__((section(".ramtext"))) -void common_hal_mcu_disable_interrupts(void) { - if (nesting_count == 0) { - irq_setie(0); - } - nesting_count++; -} - -__attribute__((section(".ramtext"))) -void common_hal_mcu_enable_interrupts(void) { - if (nesting_count == 0) { - // This is very very bad because it means there was mismatched disable/enables. - reset_into_safe_mode(SAFE_MODE_INTERRUPT_ERROR); - } - nesting_count--; - if (nesting_count > 0) { - return; - } - irq_setie(1); -} - -void common_hal_mcu_on_next_reset(mcu_runmode_t runmode) { - if (runmode == RUNMODE_SAFE_MODE) { - safe_mode_on_next_reset(SAFE_MODE_PROGRAMMATIC); - } -} - -void common_hal_mcu_reset(void) { - filesystem_flush(); // TODO: implement as part of flash improvements - // NVIC_SystemReset(); - while (1) { - ; - } -} - -// The singleton microcontroller.Processor object, bound to microcontroller.cpu -// It currently only has properties, and no state. -const mcu_processor_obj_t common_hal_mcu_processor_obj = { - .base = { - .type = &mcu_processor_type, - }, -}; - -const mcu_pin_obj_t pin_TOUCH1 = PIN(0); -const mcu_pin_obj_t pin_TOUCH2 = PIN(1); -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_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 deleted file mode 100644 index 72750872b56..00000000000 --- a/ports/litex/common-hal/neopixel_write/__init__.c +++ /dev/null @@ -1,74 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2018 hathach for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "py/mphal.h" -#include "shared-bindings/neopixel_write/__init__.h" -#include "csr.h" - -// ICE40 LED Driver hard macro. -// See http://www.latticesemi.com/-/media/LatticeSemi/Documents/ApplicationNotes/IK/ICE40LEDDriverUsageGuide.ashx?document_id=50668 -enum led_registers { - LEDDCR0 = 8, - LEDDBR = 9, - LEDDONR = 10, - LEDDOFR = 11, - LEDDBCRR = 5, - LEDDBCFR = 6, - LEDDPWRR = 1, - LEDDPWRG = 2, - LEDDPWRB = 3, -}; - -// Control register definitions -#define LEDDCR0_LEDDEN (1 << 7) -#define LEDDCR0_FR250 (1 << 6) -#define LEDDCR0_OUTPOL (1 << 5) -#define LEDDCR0_OUTSKEW (1 << 4) -#define LEDDCR0_QUICKSTOP (1 << 3) -#define LEDDCR0_PWM_MODE (1 << 2) -#define LEDDCR0_BRMSBEXT (1 << 0) - -// Write a value into the LEDDA_IP register. -static void ledda_write(uint8_t value, uint8_t addr) { - rgb_addr_write(addr); - rgb_dat_write(value); -} - -static int ledda_init_done; - -static void ledda_init(void) { - 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)); - - ledda_write(LEDDCR0_LEDDEN | LEDDCR0_FR250 | LEDDCR0_QUICKSTOP, LEDDCR0); - - // Set clock register to 12 MHz / 64 kHz - 1 - ledda_write((12000000 / 64000) - 1, LEDDBR); - - // Ensure LED "breathe" effect is disabled - ledda_write(0, LEDDBCRR); - ledda_write(0, LEDDBCFR); - - // Also disable the LED blink time - ledda_write(0, LEDDONR); - ledda_write(0, LEDDOFR); - - ledda_init_done = 1; -} - -void common_hal_neopixel_write(const digitalio_digitalinout_obj_t *digitalinout, uint8_t *pixels, uint32_t numBytes) { - (void)digitalinout; - (void)numBytes; - ledda_init(); - - ledda_write(pixels[0], LEDDPWRR); // Red - ledda_write(pixels[1], LEDDPWRG); // Green - ledda_write(pixels[2], LEDDPWRB); // Blue -} diff --git a/ports/litex/common-hal/os/__init__.c b/ports/litex/common-hal/os/__init__.c deleted file mode 100644 index 659411187fa..00000000000 --- a/ports/litex/common-hal/os/__init__.c +++ /dev/null @@ -1,17 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2020 Sean Cross -// -// SPDX-License-Identifier: MIT - -#include "genhdr/mpversion.h" -#include "py/mpconfig.h" -#include "py/objstr.h" -#include "py/objtuple.h" -#include "py/qstr.h" - -#include "shared-bindings/os/__init__.h" - -bool common_hal_os_urandom(uint8_t *buffer, mp_uint_t length) { - return false; -} diff --git a/ports/litex/common-hal/time/__init__.c b/ports/litex/common-hal/time/__init__.c deleted file mode 100644 index 96283d79259..00000000000 --- a/ports/litex/common-hal/time/__init__.c +++ /dev/null @@ -1,25 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2016 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "py/mphal.h" - -#include "tick.h" - -uint64_t common_hal_time_monotonic_ms(void) { - return supervisor_ticks_ms64(); -} - -uint64_t common_hal_time_monotonic_ns(void) { - uint64_t ms; - uint32_t us_until_ms; - current_tick(&ms, &us_until_ms); - // us counts down. - return 1000 * (ms * 1000 + (1000 - us_until_ms)); -} - -void common_hal_time_delay_ms(uint32_t delay) { - mp_hal_delay_ms(delay); -} diff --git a/ports/litex/crt0-vexriscv.S b/ports/litex/crt0-vexriscv.S deleted file mode 100644 index 0517711865c..00000000000 --- a/ports/litex/crt0-vexriscv.S +++ /dev/null @@ -1,94 +0,0 @@ -.global main -.global isr - -.section .text.start -.global _start - -_start: - j crt_init - # This sentinel ensures that this program is loaded - # to RAM when loaded using dfu-util. - #.word 0x17ab0f23 - #.word 0x10001000 - -.section .ramtext -.global trap_entry -.align 4 -trap_entry: - sw x1, - 1*4(sp) - sw x5, - 2*4(sp) - sw x6, - 3*4(sp) - sw x7, - 4*4(sp) - sw x10, - 5*4(sp) - sw x11, - 6*4(sp) - sw x12, - 7*4(sp) - sw x13, - 8*4(sp) - sw x14, - 9*4(sp) - sw x15, -10*4(sp) - sw x16, -11*4(sp) - sw x17, -12*4(sp) - sw x28, -13*4(sp) - sw x29, -14*4(sp) - sw x30, -15*4(sp) - sw x31, -16*4(sp) - addi sp,sp,-16*4 - call isr - lw x1 , 15*4(sp) - lw x5, 14*4(sp) - lw x6, 13*4(sp) - lw x7, 12*4(sp) - lw x10, 11*4(sp) - lw x11, 10*4(sp) - lw x12, 9*4(sp) - lw x13, 8*4(sp) - lw x14, 7*4(sp) - lw x15, 6*4(sp) - lw x16, 5*4(sp) - lw x17, 4*4(sp) - lw x28, 3*4(sp) - lw x29, 2*4(sp) - lw x30, 1*4(sp) - lw x31, 0*4(sp) - addi sp,sp,16*4 - mret - -.text - -crt_init: - # # Flush the caches - # .word 16399 - # .word 19 - # .word 19 - # .word 19 - la sp, _estack - 4 - la a0, trap_entry - csrw mtvec, a0 - -bss_init: - la a0, _sbss - la a1, _ebss -bss_loop: - beq a0,a1,bss_done - sw zero,0(a0) - add a0,a0,4 - j bss_loop -bss_done: - - /* Load DATA */ - la t0, _sidata - la t1, _sdata - la t2, _edata -3: - lw t3, 0(t0) - sw t3, 0(t1) - /* _edata is aligned to 16 bytes. Use word-xfers. */ - addi t0, t0, 4 - addi t1, t1, 4 - bltu t1, t2, 3b - - li a0, 0x880 //880 enable timer + external interrupt sources (until mstatus.MIE is set, they will never trigger an interrupt) - csrw mie,a0 - - call main -infinite_loop: - j infinite_loop diff --git a/ports/litex/hw/common.h b/ports/litex/hw/common.h deleted file mode 100644 index 5597a866c62..00000000000 --- a/ports/litex/hw/common.h +++ /dev/null @@ -1,31 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2024 Adafruit Industries LLC -// -// SPDX-License-Identifier: MIT - -#pragma once -#include -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 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 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; -} diff --git a/ports/litex/irq.h b/ports/litex/irq.h deleted file mode 100644 index f0e0ee2ea4e..00000000000 --- a/ports/litex/irq.h +++ /dev/null @@ -1,73 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2024 Adafruit Industries LLC -// -// SPDX-License-Identifier: MIT - -#pragma once - -#ifdef __cplusplus -extern "C" { -#endif - - -#define CSR_MSTATUS_MIE 0x8 - -#define CSR_IRQ_MASK 0xBC0 -#define CSR_IRQ_PENDING 0xFC0 - -#define CSR_DCACHE_INFO 0xCC0 - -#define csrr(reg) ({ unsigned long __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)); }) - -#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)); }) - -#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; -} - -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 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; -} - -#ifdef __cplusplus -} -#endif diff --git a/ports/litex/mpconfigport.h b/ports/litex/mpconfigport.h deleted file mode 100644 index 7ac34a44336..00000000000 --- a/ports/litex/mpconfigport.h +++ /dev/null @@ -1,16 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2015 Glenn Ruben Bakke -// SPDX-FileCopyrightText: Copyright (c) 2019 Dan Halbert for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#pragma once - -#define CIRCUITPY_INTERNAL_NVM_SIZE (0) -#define MICROPY_NLR_THUMB (0) - -#include "py/circuitpy_mpconfig.h" - -#define MICROPY_NLR_SETJMP (1) -#define CIRCUITPY_DEFAULT_STACK_SIZE 0x6000 diff --git a/ports/litex/mpconfigport.mk b/ports/litex/mpconfigport.mk deleted file mode 100644 index a93a3890bbc..00000000000 --- a/ports/litex/mpconfigport.mk +++ /dev/null @@ -1,34 +0,0 @@ -# Internal math library is substantially smaller than toolchain one -INTERNAL_LIBM = 1 - -# Number of USB endpoint pairs. -USB_NUM_ENDPOINT_PAIRS = 16 - -# Longints can be implemented as mpz, as longlong, or not -LONGINT_IMPL = MPZ - -CIRCUITPY_ANALOGIO = 0 -CIRCUITPY_AUDIOBUSIO = 0 -CIRCUITPY_AUDIOIO = 0 -CIRCUITPY_BITBANGIO = 0 -CIRCUITPY_BLEIO_HCI = 0 -CIRCUITPY_BOARD = 0 -CIRCUITPY_BUSDEVICE = 0 -CIRCUITPY_BUSIO = 0 -CIRCUITPY_COUNTIO = 0 -CIRCUITPY_DISPLAYIO = 0 -CIRCUITPY_FREQUENCYIO = 0 -CIRCUITPY_I2CTARGET = 0 -CIRCUITPY_NVM = 0 -CIRCUITPY_PWMIO = 0 -CIRCUITPY_PULSEIO = 0 -CIRCUITPY_PWMIO = 0 -CIRCUITPY_ROTARYIO = 0 -CIRCUITPY_RTC = 0 -CIRCUITPY_SDCARDIO = 0 -# Enable USB support -CIRCUITPY_USB_HID = 1 -CIRCUITPY_USB_MIDI = 1 - -CIRCUITPY_BUILD_EXTENSIONS ?= dfu -CIRCUITPY_MIN_GCC_VERSION ?= 8 diff --git a/ports/litex/mphalport.c b/ports/litex/mphalport.c deleted file mode 100644 index cc74762a14f..00000000000 --- a/ports/litex/mphalport.c +++ /dev/null @@ -1,62 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2015 Glenn Ruben Bakke -// SPDX-FileCopyrightText: Copyright (c) 2018 Artur Pacholec -// -// SPDX-License-Identifier: MIT - -#include - -#include "lib/tinyusb/src/device/usbd.h" -#include "py/mphal.h" -#include "py/mpstate.h" -#include "py/gc.h" -#include "supervisor/cpu.h" -#include "supervisor/usb.h" - -#include "csr.h" -#include "generated/soc.h" - -#include "irq.h" - -void mp_hal_delay_us(mp_uint_t delay) { - mp_hal_delay_ms(delay / 1000); -} - -extern void SysTick_Handler(void); - -// This value contains the number of times "common_hal_mcu_disable_interrupts()" -// has been called without calling "common_hal_mcu_enable_interrupts()". Since -// this is the interrupt handler, that means we're handling an interrupt, so -// this value should be `0`. -// -// Interrupts should already be disabled when this handler is running, which means -// this value is logically already `1`. If we didn't do this, then interrupts would -// be prematurely enabled by interrupt handlers that enable and disable interrupts. -extern volatile uint32_t nesting_count; - -void isr(void); -__attribute__((section(".ramtext"))) -void isr(void) { - uint8_t irqs = irq_pending() & irq_getmask(); - - // Increase the "nesting count". Note: This should be going from 0 -> 1. - nesting_count += 1; - #ifdef CFG_TUSB_MCU - if (irqs & (1 << USB_INTERRUPT)) { - usb_irq_handler(0); - } - #endif - if (irqs & (1 << TIMER0_INTERRUPT)) { - SysTick_Handler(); - } - - // Decrease the "nesting count". Note: This should be going from 1 -> 0. - nesting_count -= 1; -} - -mp_uint_t cpu_get_regs_and_sp(mp_uint_t *regs) { - unsigned long __tmp; - asm volatile ("mv %0, x2" : "=r" (__tmp)); - return __tmp; -} diff --git a/ports/litex/mphalport.h b/ports/litex/mphalport.h deleted file mode 100644 index fc019b2f42b..00000000000 --- a/ports/litex/mphalport.h +++ /dev/null @@ -1,19 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2015 Glenn Ruben Bakke -// -// SPDX-License-Identifier: MIT - -#pragma once - -#include -#include - -#include "shared/runtime/interrupt_char.h" -#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)) - -bool mp_hal_stdin_any(void); diff --git a/ports/litex/qstrdefsport.h b/ports/litex/qstrdefsport.h deleted file mode 100644 index 2d2c2609234..00000000000 --- a/ports/litex/qstrdefsport.h +++ /dev/null @@ -1,10 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2024 Adafruit Industries LLC -// -// SPDX-License-Identifier: MIT - -// Do not use #pragma once in this file; it will cause a warning during qstr generation. - -// qstrs specific to this port -// *FORMAT-OFF* diff --git a/ports/litex/supervisor/internal_flash.c b/ports/litex/supervisor/internal_flash.c deleted file mode 100644 index ba21b91b872..00000000000 --- a/ports/litex/supervisor/internal_flash.c +++ /dev/null @@ -1,339 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2013, 2014 Damien P. George -// SPDX-FileCopyrightText: Copyright (c) 2019 Lucian Copeland for Adafruit Industries -// -// SPDX-License-Identifier: MIT -#include "supervisor/internal_flash.h" - -#include -#include -#include - -#include "extmod/vfs.h" -#include "extmod/vfs_fat.h" -#include "py/mphal.h" -#include "py/obj.h" -#include "py/runtime.h" -#include "lib/oofatfs/ff.h" - -#include "supervisor/flash.h" -#include "supervisor/usb.h" - -#include "csr.h" -#include "irq.h" - -enum pin { - PIN_MOSI = 0, - PIN_CLK = 1, - PIN_CS = 2, - PIN_MISO_EN = 3, - PIN_MISO = 4, // Value is ignored -}; - -#define NO_CACHE 0xffffffff - -static uint8_t _flash_cache[FLASH_PAGE_SIZE] __attribute__((aligned(4))); -static uint32_t _flash_page_addr = NO_CACHE; -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. -// To work around this, we execute from RAM. This is accomplished by marking -// functions as being in the section ".ramtext". -// When building under GCC with -O0 or -Od, the `inline` attribute is ignored. -// 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) { - *((volatile uint32_t *)addr) = value; -} - -__attribute__((section(".ramtext"))) -static inline uint32_t spi_readl(uint32_t addr) { - return *(volatile uint32_t *)addr; -} - -__attribute__((section(".ramtext"))) -static inline void bb_spi_write(unsigned char value) { - spi_writel(value, CSR_LXSPI_BITBANG_ADDR); -} - -__attribute__((section(".ramtext"))) -static inline uint32_t bb_read(void) { - return spi_readl(CSR_LXSPI_MISO_ADDR); -} - -__attribute__((section(".ramtext"))) -static inline void bb_spi_en(unsigned int en) { - spi_writel(en, CSR_LXSPI_BITBANG_EN_ADDR); -} - -__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); - } -} - -__attribute__((section(".ramtext"))) -static inline void bb_spi_begin(void) { - bb_spi_write((0 << PIN_CLK) | (0 << PIN_CS)); -} - -__attribute__((section(".ramtext"))) -static inline void bb_spi_end(void) { - bb_spi_write((0 << PIN_CLK) | (1 << PIN_CS)); -} - -__attribute__((section(".ramtext"))) -static void spi_single_tx(uint8_t out) { - int bit; - - for (bit = 7; bit >= 0; bit--) { - if (out & (1 << bit)) { - bb_spi_write((0 << PIN_CLK) | (1 << PIN_MOSI)); - bb_spi_write((1 << PIN_CLK) | (1 << PIN_MOSI)); - bb_spi_write((0 << PIN_CLK) | (1 << PIN_MOSI)); - } else { - bb_spi_write((0 << PIN_CLK) | (0 << PIN_MOSI)); - bb_spi_write((1 << PIN_CLK) | (0 << PIN_MOSI)); - bb_spi_write((0 << PIN_CLK) | (0 << PIN_MOSI)); - } - } -} - -__attribute__((section(".ramtext"))) -static uint8_t spi_single_rx(void) { - int bit = 0; - uint8_t in = 0; - - bb_spi_write((1 << PIN_MISO_EN) | (0 << PIN_CLK)); - - while (bit++ < 8) { - bb_spi_write((1 << PIN_MISO_EN) | (1 << PIN_CLK)); - in = (in << 1) | bb_read(); - bb_spi_write((1 << PIN_MISO_EN) | (0 << PIN_CLK)); - } - - return in; -} - -__attribute__((section(".ramtext"))) -static int bb_spi_beginErase4(uint32_t erase_addr) { - // Enable Write-Enable Latch (WEL) - bb_spi_begin(); - spi_single_tx(0x06); - bb_spi_end(); - - bb_spi_begin(); - spi_single_tx(0x20); - spi_single_tx(erase_addr >> 16); - spi_single_tx(erase_addr >> 8); - spi_single_tx(erase_addr >> 0); - bb_spi_end(); - return 0; -} - -__attribute__((section(".ramtext"))) -static int bb_spi_beginWrite(uint32_t addr, const void *v_data, unsigned int count) { - const uint8_t write_cmd = 0x02; - const uint8_t *data = v_data; - unsigned int i; - - #ifdef NDEBUG - if (v_data < (const void *)_flash_cache) { - asm ("ebreak"); - } - if ((v_data + count) > (const void *)&_flash_cache[4096]) { - asm ("ebreak"); - } - #endif - - // Enable Write-Enable Latch (WEL) - bb_spi_begin(); - spi_single_tx(0x06); - bb_spi_end(); - - bb_spi_begin(); - spi_single_tx(write_cmd); - spi_single_tx(addr >> 16); - spi_single_tx(addr >> 8); - spi_single_tx(addr >> 0); - for (i = 0; (i < count) && (i < 256); i++) { - spi_single_tx(*data++); - } - bb_spi_end(); - - return 0; -} - -__attribute__((section(".ramtext"))) -static uint8_t spi_read_status(void) { - uint8_t val; - - bb_spi_begin(); - spi_single_tx(0x05); - val = spi_single_rx(); - bb_spi_end(); - return val; -} - -__attribute__((section(".ramtext"))) -static int bb_spi_is_busy(void) { - return spi_read_status() & (1 << 0); -} - -__attribute__((used)) -uint32_t page_write_log[128]; -__attribute__((used)) -uint32_t page_write_log_offset; - -__attribute__((section(".ramtext"))) -static void bb_spi_write_page(uint32_t flash_address, const uint8_t *data) { - const uint32_t flash_address_end = flash_address + FLASH_PAGE_SIZE; - - // Ensure we're within the target flash address range. - if ((flash_address - FLASH_PARTITION_OFFSET_BYTES) > FLASH_SIZE) { - asm ("ebreak"); - return; - } - if (flash_address < FLASH_PARTITION_OFFSET_BYTES) { - asm ("ebreak"); - return; - } - - if ((flash_address_end - FLASH_PARTITION_OFFSET_BYTES) > FLASH_SIZE) { - asm ("ebreak"); - return; - } - if (flash_address_end < FLASH_PARTITION_OFFSET_BYTES) { - asm ("ebreak"); - return; - } - - // Ensure we're not erasing the middle of a flash bank - if ((flash_address & 0xfff) != 0) { - 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; - } - - while (bb_spi_is_busy()) { - ; // relax - } - bb_spi_beginErase4(flash_address); - while (bb_spi_is_busy()) { - ; // relax - } - while (flash_address < flash_address_end) { - bb_spi_beginWrite(flash_address, data, 256); - while (bb_spi_is_busy()) { - ; // relax - } - flash_address += 256; - data += 256; - } -} - -static inline uint32_t lba2addr(uint32_t block) { - return (0x20000000 + FLASH_PARTITION_OFFSET_BYTES) + (block * FILESYSTEM_BLOCK_SIZE); -} - -void supervisor_flash_init(void) { -} - -uint32_t supervisor_flash_get_block_size(void) { - return FILESYSTEM_BLOCK_SIZE; -} - -uint32_t supervisor_flash_get_block_count(void) { - 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) { - return; - } - 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 - // would crash the CPU as the program suddenly became an endless stream - // of `0xffffffff`. - bb_spi_irq_setie(0); - bb_spi_write((0 << PIN_CLK) | (1 << PIN_CS)); - bb_spi_en(1); - - bb_spi_write_page(_flash_page_addr & 0x00ffffff, (const uint8_t *)_flash_cache); - - bb_spi_en(0); - bb_spi_irq_setie(1); - - _flash_cache_dirty = false; -} - -mp_uint_t supervisor_flash_read_blocks(uint8_t *dest, uint32_t block, uint32_t num_blocks) { - // Must write out anything in cache before trying to read. - supervisor_flash_flush(); - - uint32_t src = lba2addr(block); - memcpy(dest, (uint8_t *)src, FILESYSTEM_BLOCK_SIZE * num_blocks); - - #if CIRCUITPY_USB_DEVICE - usb_background(); - #endif - - return 0; -} - -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 page_addr = addr & ~(FLASH_PAGE_SIZE - 1); - - uint32_t count = 8 - (lba % 8); // up to page boundary - count = MIN(num_blocks, count); - - if (page_addr != _flash_page_addr) { - // Write out anything in cache before overwriting it. - supervisor_flash_flush(); - - _flash_page_addr = page_addr; - _flash_cache_dirty = false; - - // Copy the current contents of the entire page into the cache. - memcpy(_flash_cache, (void *)page_addr, FLASH_PAGE_SIZE); - } - - // Overwrite part or all of the page cache with the src data, but only if it's changed. - if (_flash_cache_dirty || memcmp(_flash_cache + (addr & (FLASH_PAGE_SIZE - 1)), src, count * FILESYSTEM_BLOCK_SIZE)) { - memcpy(_flash_cache + (addr & (FLASH_PAGE_SIZE - 1)), src, count * FILESYSTEM_BLOCK_SIZE); - _flash_cache_dirty = true; - } - - // adjust for next run - lba += count; - src += count * FILESYSTEM_BLOCK_SIZE; - num_blocks -= count; - - #if CIRCUITPY_USB_DEVICE - usb_background(); - #endif - } - - return 0; // success -} - -void supervisor_flash_release_cache(void) { -} diff --git a/ports/litex/supervisor/internal_flash.h b/ports/litex/supervisor/internal_flash.h deleted file mode 100644 index 7bc26042ca5..00000000000 --- a/ports/litex/supervisor/internal_flash.h +++ /dev/null @@ -1,15 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2013, 2014 Damien P. George -// SPDX-FileCopyrightText: Copyright (c) 2019 Lucian Copeland for Adafruit Industries -// -// SPDX-License-Identifier: MIT -#pragma once - -#include -#include - -#include "py/mpconfig.h" - -#define INTERNAL_FLASH_SYSTICK_MASK (0x1ff) // 512ms -#define INTERNAL_FLASH_IDLE_TICK(tick) (((tick) & INTERNAL_FLASH_SYSTICK_MASK) == 2) diff --git a/ports/litex/supervisor/port.c b/ports/litex/supervisor/port.c deleted file mode 100644 index 7009956c317..00000000000 --- a/ports/litex/supervisor/port.c +++ /dev/null @@ -1,133 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2017 Scott Shawcroft for Adafruit Industries -// SPDX-FileCopyrightText: Copyright (c) 2019 Lucian Copeland for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include -#include "supervisor/board.h" -#include "supervisor/port.h" -#include "supervisor/shared/tick.h" -#include "irq.h" -#include "csr.h" - -#include "shared-bindings/microcontroller/__init__.h" - -// Global millisecond tick count. 1024 per second because most RTCs are clocked with 32.768khz -// crystals. -volatile uint64_t raw_ticks = 0; -volatile int subsecond = 0; -void SysTick_Handler(void); -__attribute__((section(".ramtext"))) -void SysTick_Handler(void) { - timer0_ev_pending_write(1); - raw_ticks += 1; - subsecond += 1; - // We track subsecond ticks so that we can increment raw_ticks one extra every 40 ms. We do this - // every 40 except 0 to make it 24 increments and not 25. - if (subsecond == 1000) { - subsecond = 0; - } else if (subsecond % 40 == 0) { - raw_ticks += 1; - } - supervisor_tick(); -} - -static void tick_init(void) { - int t; - - timer0_en_write(0); - t = CONFIG_CLOCK_FREQUENCY / 1000; // 1000 kHz tick - timer0_reload_write(t); - timer0_load_write(t); - timer0_en_write(1); - timer0_ev_enable_write(1); - timer0_ev_pending_write(1); - irq_setmask(irq_getmask() | (1 << TIMER0_INTERRUPT)); -} - -safe_mode_t port_init(void) { - irq_setmask(0); - irq_setie(1); - tick_init(); - return SAFE_MODE_NONE; -} - -extern uint32_t _ebss; -extern uint32_t _heap_start; -extern uint32_t _estack; - -void reset_port(void) { - // reset_all_pins(); - // i2c_reset(); - // spi_reset(); - // uart_reset(); - // pwmout_reset(); -} - -void reset_to_bootloader(void) { - reboot_ctrl_write(0xac); - for (;;) {} -} - -void reset_cpu(void) { - // "You can reset Fomu by writing a special value to the CSR_REBOOT_CTRL - // register at 0xe0006000L. All writes to this register must start with - // 0xac, to ensure random values aren’t written. We can reboot Fomu by - // simply writing this value" -- - // https://workshop.fomu.im/en/latest/riscv.html - reboot_ctrl_write(0xac); - for (;;) {} -} - -uint32_t *port_heap_get_bottom(void) { - return &_ebss; -} - -uint32_t *port_heap_get_top(void) { - return port_stack_get_limit(); -} - -uint32_t *port_stack_get_limit(void) { - #pragma GCC diagnostic push - #pragma GCC diagnostic ignored "-Warray-bounds" - return port_stack_get_top() - (CIRCUITPY_DEFAULT_STACK_SIZE + CIRCUITPY_EXCEPTION_STACK_SIZE) / sizeof(uint32_t); - #pragma GCC diagnostic pop -} - -uint32_t *port_stack_get_top(void) { - return &_estack; -} - -// Place the word to save just after our BSS section that gets blanked. -void port_set_saved_word(uint32_t value) { - _ebss = value; -} - -uint32_t port_get_saved_word(void) { - return _ebss; -} - -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; - common_hal_mcu_enable_interrupts(); - return raw_tick_snapshot; -} - -// Enable 1/1024 second tick. -void port_enable_tick(void) { -} - -// Disable 1/1024 second tick. -void port_disable_tick(void) { -} - -void port_interrupt_after_ticks(uint32_t ticks) { -} - -// TODO: Add sleep support if the SoC supports sleep. -void port_idle_until_interrupt(void) { -} diff --git a/ports/litex/supervisor/usb.c b/ports/litex/supervisor/usb.c deleted file mode 100644 index f2324a57a6e..00000000000 --- a/ports/litex/supervisor/usb.c +++ /dev/null @@ -1,14 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2018 hathach for Adafruit Industries -// SPDX-FileCopyrightText: Copyright (c) 2019 Lucian Copeland for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "supervisor/usb.h" -#include "shared/runtime/interrupt_char.h" -#include "shared/readline/readline.h" - -void init_usb_hardware(void) { - -} diff --git a/ports/mimxrt10xx/Makefile b/ports/mimxrt10xx/Makefile index 04b8c6787af..2c78179c0ef 100644 --- a/ports/mimxrt10xx/Makefile +++ b/ports/mimxrt10xx/Makefile @@ -45,7 +45,7 @@ ifeq ($(DEBUG), 1) CFLAGS += -fno-ipa-sra endif -CFLAGS += $(INC) -ggdb -Wall -Werror -std=gnu11 -nostdlib -fshort-enums $(BASE_CFLAGS) $(CFLAGS_MOD) $(COPT) -Werror=missing-prototypes +CFLAGS += $(INC) -ggdb -Wall -Werror -std=gnu11 -nostdlib -fshort-enums $(BASE_CFLAGS) $(CFLAGS_MOD) $(COPT) -Werror=missing-prototypes -Werror=old-style-definition # TODO: add these when -Werror is applied # Disable some warnings, as do most ports. NXP SDK causes undef, tinyusb causes cast-align @@ -161,30 +161,25 @@ SRC_C += \ endif -SRC_COMMON_HAL_EXPANDED = $(addprefix shared-bindings/, $(SRC_COMMON_HAL)) \ - $(addprefix shared-bindings/, $(SRC_BINDINGS_ENUMS)) \ - $(addprefix common-hal/, $(SRC_COMMON_HAL)) +SRC_S_UPPER = \ + sdk/devices/$(CHIP_FAMILY)/gcc/startup_$(CHIP_CORE).S -SRC_SHARED_MODULE_EXPANDED = $(addprefix shared-bindings/, $(SRC_SHARED_MODULE)) \ - $(addprefix shared-module/, $(SRC_SHARED_MODULE)) \ - $(addprefix shared-module/, $(SRC_SHARED_MODULE_INTERNAL)) +SRC_S = shared/runtime/gchelper_thumb2.s -SRC_S = \ - sdk/devices/$(CHIP_FAMILY)/gcc/startup_$(CHIP_CORE).S \ - supervisor/cpu.S +SRC_C += shared/runtime/gchelper_native.c OBJ = $(PY_O) $(SUPERVISOR_O) $(addprefix $(BUILD)/, $(SRC_C:.c=.o)) OBJ += $(addprefix $(BUILD)/, $(SRC_SDK:.c=.o)) -OBJ += $(addprefix $(BUILD)/, $(SRC_COMMON_HAL_EXPANDED:.c=.o)) -OBJ += $(addprefix $(BUILD)/, $(SRC_SHARED_MODULE_EXPANDED:.c=.o)) +OBJ += $(addprefix $(BUILD)/, $(SRC_COMMON_HAL_SHARED_MODULE_EXPANDED:.c=.o)) ifeq ($(INTERNAL_LIBM),1) OBJ += $(addprefix $(BUILD)/, $(SRC_LIBM:.c=.o)) endif OBJ += $(addprefix $(BUILD)/, $(SRC_CIRCUITPY_COMMON:.c=.o)) -OBJ += $(addprefix $(BUILD)/, $(SRC_S:.S=.o)) +OBJ += $(addprefix $(BUILD)/, $(SRC_S:.s=.o)) +OBJ += $(addprefix $(BUILD)/, $(SRC_S_UPPER:.S=.o)) OBJ += $(addprefix $(BUILD)/, $(SRC_MOD:.c=.o)) -SRC_QSTR += $(SRC_C) $(SRC_SUPERVISOR) $(SRC_COMMON_HAL_EXPANDED) $(SRC_SHARED_MODULE_EXPANDED) $(SRC_CIRCUITPY_COMMON) +SRC_QSTR += $(SRC_C) $(SRC_SUPERVISOR) $(SRC_COMMON_HAL_SHARED_MODULE_EXPANDED) $(SRC_CIRCUITPY_COMMON) all: $(BUILD)/firmware.bin $(BUILD)/firmware.uf2 $(BUILD)/firmware.hex @@ -194,6 +189,7 @@ else $(BUILD)/firmware.elf: $(OBJ) $(LD_FILES) $(STEPECHO) "LINK $@" $(Q)$(CC) -o $@ $(LDFLAGS) $(filter-out %.ld, $^) -Wl,--print-memory-usage -Wl,--start-group $(LIBS) -Wl,--end-group + $(Q)$(PYTHON) $(TOP)/tools/build_memory_info.py $@.map $(BUILD) --elf $@ endif # -R excludes sections from the output files. diff --git a/ports/mimxrt10xx/boards/teensy40/mpconfigboard.h b/ports/mimxrt10xx/boards/teensy40/mpconfigboard.h index e7565d64438..e6931752e3e 100644 --- a/ports/mimxrt10xx/boards/teensy40/mpconfigboard.h +++ b/ports/mimxrt10xx/boards/teensy40/mpconfigboard.h @@ -25,3 +25,6 @@ #define DEFAULT_UART_BUS_RX (&pin_GPIO_AD_B0_03) #define DEFAULT_UART_BUS_TX (&pin_GPIO_AD_B0_02) + +#define CIRCUITPY_USB_DEVICE_INSTANCE 0 +#define CIRCUITPY_USB_HOST_INSTANCE 1 diff --git a/ports/mimxrt10xx/boards/teensy40/mpconfigboard.mk b/ports/mimxrt10xx/boards/teensy40/mpconfigboard.mk index 9cb1e636b6f..f26f8dbd72b 100644 --- a/ports/mimxrt10xx/boards/teensy40/mpconfigboard.mk +++ b/ports/mimxrt10xx/boards/teensy40/mpconfigboard.mk @@ -7,4 +7,5 @@ CHIP_VARIANT = MIMXRT1062DVJ6A CHIP_FAMILY = MIMXRT1062 FLASH = W25Q16JV CIRCUITPY__EVE = 1 +CIRCUITPY_USB_HOST = 1 CIRCUITPY_SETTABLE_PROCESSOR_FREQUENCY = 1 diff --git a/ports/mimxrt10xx/boards/teensy40/pins.c b/ports/mimxrt10xx/boards/teensy40/pins.c index 7aacdf95e15..dc8b07605b2 100644 --- a/ports/mimxrt10xx/boards/teensy40/pins.c +++ b/ports/mimxrt10xx/boards/teensy40/pins.c @@ -120,6 +120,10 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { {MP_ROM_QSTR(MP_QSTR_SPI), MP_ROM_PTR(&board_spi_obj)}, {MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj)}, + // USB Host (pads) + {MP_ROM_QSTR(MP_QSTR_USB_HOST_DP), MP_ROM_PTR(&pin_USB_OTG2_DP)}, + {MP_ROM_QSTR(MP_QSTR_USB_HOST_DM), MP_ROM_PTR(&pin_USB_OTG2_DN)}, + // other i2c ports defined {MP_OBJ_NEW_QSTR(MP_QSTR_SDA1), MP_ROM_PTR(&pin_GPIO_AD_B1_06)}, {MP_OBJ_NEW_QSTR(MP_QSTR_SCL1), MP_ROM_PTR(&pin_GPIO_AD_B1_07)}, diff --git a/ports/mimxrt10xx/common-hal/audiobusio/I2SOut.c b/ports/mimxrt10xx/common-hal/audiobusio/I2SOut.c index c785f4e090e..59737763f3d 100644 --- a/ports/mimxrt10xx/common-hal/audiobusio/I2SOut.c +++ b/ports/mimxrt10xx/common-hal/audiobusio/I2SOut.c @@ -53,20 +53,18 @@ static void config_periph_pin(const mcu_periph_obj_t *periph) { // 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, const mcu_pin_obj_t *main_clock, bool left_justified) { + const mcu_pin_obj_t *data, const mcu_pin_obj_t *main_clock, bool left_justified, + bool external_clock) { + if (external_clock) { + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_external_clock); + } int instance = -1; const mcu_periph_obj_t *bclk_periph = find_pin_function(mcu_i2s_tx_bclk_list, bit_clock, &instance, MP_QSTR_bit_clock); const mcu_periph_obj_t *sync_periph = find_pin_function(mcu_i2s_tx_sync_list, word_select, &instance, MP_QSTR_word_select); const mcu_periph_obj_t *data_periph = find_pin_function(mcu_i2s_tx_data0_list, data, &instance, MP_QSTR_data); - if (main_clock != NULL) { - const mcu_periph_obj_t *mclk_periph = find_pin_function(mcu_i2s_mclk_list, main_clock, &instance, MP_QSTR_main_clock); - self->mclk = main_clock; - claim_pin(main_clock); - config_periph_pin(mclk_periph); - IOMUXC_GPR->GPR1 |= IOMUXC_GPR_GPR1_SAI1_MCLK_DIR_MASK << (instance - 1); - } + const mcu_periph_obj_t *mclk_periph = find_pin_function(mcu_i2s_mclk_list, main_clock, &instance, MP_QSTR_main_clock); self->instance = instance; sai_transceiver_t config; @@ -79,6 +77,12 @@ void common_hal_audiobusio_i2sout_construct(audiobusio_i2sout_obj_t *self, config.masterSlave = kSAI_Master; port_i2s_initialize(&self->i2s, instance, &config); + if (main_clock != NULL) { + claim_pin(main_clock); + config_periph_pin(mclk_periph); + IOMUXC_GPR->GPR1 |= IOMUXC_GPR_GPR1_SAI1_MCLK_DIR_MASK << (instance - 1); + } + self->mclk = main_clock; self->bit_clock = bit_clock; self->word_select = word_select; self->data = data; diff --git a/ports/mimxrt10xx/common-hal/audiobusio/__init__.c b/ports/mimxrt10xx/common-hal/audiobusio/__init__.c index 2430b6bdaa6..3ed760a1b30 100644 --- a/ports/mimxrt10xx/common-hal/audiobusio/__init__.c +++ b/ports/mimxrt10xx/common-hal/audiobusio/__init__.c @@ -173,7 +173,6 @@ static bool i2s_clocking(I2S_Type *peripheral) { return false; } - static bool i2s_queue_available(i2s_t *self) { return !self->handle.saiQueue[self->handle.queueUser].data; } @@ -280,7 +279,6 @@ static void i2s_transfer_callback(I2S_Type *base, sai_handle_t *handle, status_t } } - void port_i2s_initialize(i2s_t *self, int instance, sai_transceiver_t *config) { if (!i2s_in_use) { // need to set audio pll up! @@ -309,7 +307,7 @@ void port_i2s_initialize(i2s_t *self, int instance, sai_transceiver_t *config) { mp_raise_ValueError_varg(MP_ERROR_TEXT("Invalid %q"), MP_QSTR_I2SOut); } for (size_t i = 0; i < MP_ARRAY_SIZE(self->buffers); i++) { - self->buffers[i] = m_malloc(AUDIO_BUFFER_FRAME_COUNT * sizeof(uint32_t)); + self->buffers[i] = m_malloc_without_collect(AUDIO_BUFFER_FRAME_COUNT * sizeof(uint32_t)); } self->peripheral = peripheral; SAI_Init(self->peripheral); @@ -372,6 +370,7 @@ static void set_sai_clocking_for_sample_rate(uint32_t sample_rate) { } void port_i2s_play(i2s_t *self, mp_obj_t sample, bool loop) { + audiosample_check(sample); self->sample = sample; self->loop = loop; self->bytes_per_sample = audiosample_get_bits_per_sample(sample) / 8; @@ -438,7 +437,3 @@ void port_i2s_pause(i2s_t *self) { void port_i2s_resume(i2s_t *self) { self->paused = false; } - -void i2s_reset() { -// this port relies on object finalizers for reset -} diff --git a/ports/mimxrt10xx/common-hal/audiobusio/__init__.h b/ports/mimxrt10xx/common-hal/audiobusio/__init__.h index 00d016b77b4..174b93ecf1c 100644 --- a/ports/mimxrt10xx/common-hal/audiobusio/__init__.h +++ b/ports/mimxrt10xx/common-hal/audiobusio/__init__.h @@ -27,7 +27,6 @@ typedef struct { } i2s_t; -void i2s_reset(void); void port_i2s_initialize(i2s_t *self, int instance, sai_transceiver_t *config); void port_i2s_deinit(i2s_t *self); bool port_i2s_deinited(i2s_t *self); diff --git a/ports/mimxrt10xx/common-hal/audiopwmio/PWMAudioOut.c b/ports/mimxrt10xx/common-hal/audiopwmio/PWMAudioOut.c index 430d1779817..64715dba235 100644 --- a/ports/mimxrt10xx/common-hal/audiopwmio/PWMAudioOut.c +++ b/ports/mimxrt10xx/common-hal/audiopwmio/PWMAudioOut.c @@ -81,9 +81,11 @@ void common_hal_audiopwmio_pwmaudioout_construct(audiopwmio_pwmaudioout_obj_t *s self->left_channel = left_channel; self->right_channel = right_channel; claim_pin(left_channel); - claim_pin(right_channel); config_periph_pin(left_periph); - config_periph_pin(right_periph); + if (right_channel != NULL) { + claim_pin(right_channel); + config_periph_pin(right_periph); + } config_mqs(); } diff --git a/ports/mimxrt10xx/common-hal/busio/I2C.c b/ports/mimxrt10xx/common-hal/busio/I2C.c index 132b3083212..86ec33f0cc5 100644 --- a/ports/mimxrt10xx/common-hal/busio/I2C.c +++ b/ports/mimxrt10xx/common-hal/busio/I2C.c @@ -145,11 +145,6 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, claim_pin(self->scl->pin); } -void common_hal_busio_i2c_never_reset(busio_i2c_obj_t *self) { - common_hal_never_reset_pin(self->sda->pin); - common_hal_never_reset_pin(self->scl->pin); -} - bool common_hal_busio_i2c_deinited(busio_i2c_obj_t *self) { return self->sda == NULL; } @@ -201,7 +196,7 @@ void common_hal_busio_i2c_unlock(busio_i2c_obj_t *self) { self->has_lock = false; } -static uint8_t _common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, +static mp_negative_errno_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) { lpi2c_master_transfer_t xfer = { 0 }; @@ -215,15 +210,15 @@ static uint8_t _common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, return 0; } - return MP_EIO; + return -MP_EIO; } -uint8_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, +mp_negative_errno_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, const uint8_t *data, size_t len) { return _common_hal_busio_i2c_write(self, addr, data, len, true); } -uint8_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t addr, +mp_negative_errno_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t addr, uint8_t *data, size_t len) { lpi2c_master_transfer_t xfer = { 0 }; @@ -237,12 +232,12 @@ uint8_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t addr, return 0; } - return MP_EIO; + return -MP_EIO; } -uint8_t common_hal_busio_i2c_write_read(busio_i2c_obj_t *self, uint16_t addr, +mp_negative_errno_t common_hal_busio_i2c_write_read(busio_i2c_obj_t *self, uint16_t addr, uint8_t *out_data, size_t out_len, uint8_t *in_data, size_t in_len) { - uint8_t result = _common_hal_busio_i2c_write(self, addr, out_data, out_len, false); + mp_negative_errno_t result = _common_hal_busio_i2c_write(self, addr, out_data, out_len, false); if (result != 0) { return result; } diff --git a/ports/mimxrt10xx/common-hal/busio/SPI.c b/ports/mimxrt10xx/common-hal/busio/SPI.c index 732b23d8c9b..62a2f54a84b 100644 --- a/ports/mimxrt10xx/common-hal/busio/SPI.c +++ b/ports/mimxrt10xx/common-hal/busio/SPI.c @@ -19,14 +19,21 @@ #if IMXRT11XX #define LPSPI_MASTER_CLK_FREQ (24000000) #else -#define LPSPI_MASTER_CLK_FREQ (CLOCK_GetFreq(kCLOCK_Usb1PllPfd0Clk) / (CLOCK_GetDiv(kCLOCK_LpspiDiv) + 1)) +#define LPSPI_MASTER_CLK_FREQ (lpspi_clock_freq()) + +static uint32_t lpspi_clock_freq(void) { + // Indexed by the LPSPI_CLK_SEL mux setting. + static const clock_name_t sources[] = { + kCLOCK_Usb1PllPfd1Clk, kCLOCK_Usb1PllPfd0Clk, kCLOCK_SysPllClk, kCLOCK_SysPllPfd2Clk + }; + return CLOCK_GetFreq(sources[CLOCK_GetMux(kCLOCK_LpspiMux)]) / (CLOCK_GetDiv(kCLOCK_LpspiDiv) + 1); +} #endif #define MAX_SPI_BUSY_RETRIES 100 // arrays use 0 based numbering: SPI1 is stored at index 0 static bool reserved_spi[MP_ARRAY_SIZE(mcu_spi_banks)]; -static bool never_reset_spi[MP_ARRAY_SIZE(mcu_spi_banks)]; #if IMXRT11XX static const clock_ip_name_t s_lpspiClocks[] = LPSPI_CLOCKS; @@ -53,22 +60,6 @@ static void config_periph_pin(const mcu_periph_obj_t *periph) { | IOMUXC_SW_PAD_CTL_PAD_SRE(0)); } -void spi_reset(void) { - for (uint i = 0; i < MP_ARRAY_SIZE(mcu_spi_banks); i++) { - if (!never_reset_spi[i]) { - reserved_spi[i] = false; - #if IMXRT11XX - // Skip resetting SPIs that aren't clocked. Doing so generates a bus fault. - if ((CCM->LPCG[s_lpspiClocks[i + 1]].STATUS0 & CCM_LPCG_STATUS0_ON_MASK) == ((uint32_t)kCLOCK_Off & CCM_LPCG_STATUS0_ON_MASK)) { - continue; - } - #endif - - LPSPI_Deinit(mcu_spi_banks[i]); - } - } -} - 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, bool half_duplex) { @@ -82,6 +73,9 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_half_duplex); } + // Ensure the object starts in its deinit state. + common_hal_busio_spi_mark_deinit(self); + for (uint i = 0; i < sck_count; i++) { if (mcu_spi_sck_list[i].pin != clock) { continue; @@ -183,6 +177,7 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, // Always start at 250khz which is what SD cards need. They are sensitive to // SPI bus noise before they are put into SPI mode. config.baudRate = 250000; + self->target_frequency = config.baudRate; LPSPI_MasterInit(self->spi, &config, LPSPI_MASTER_CLK_FREQ); LPSPI_Enable(self->spi, false); uint32_t tcrPrescaleValue; @@ -199,36 +194,32 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, } } -void common_hal_busio_spi_never_reset(busio_spi_obj_t *self) { - never_reset_spi[self->clock->bank_idx - 1] = true; - common_hal_never_reset_pin(self->clock->pin); - if (self->mosi != NULL) { - common_hal_never_reset_pin(self->mosi->pin); - } - if (self->miso != NULL) { - common_hal_never_reset_pin(self->miso->pin); - } -} - bool common_hal_busio_spi_deinited(busio_spi_obj_t *self) { return self->clock == NULL; } +void common_hal_busio_spi_mark_deinit(busio_spi_obj_t *self) { + self->clock = NULL; + self->mosi = NULL; + self->miso = NULL; +} + void common_hal_busio_spi_deinit(busio_spi_obj_t *self) { if (common_hal_busio_spi_deinited(self)) { return; } LPSPI_Deinit(self->spi); reserved_spi[self->clock->bank_idx - 1] = false; - never_reset_spi[self->clock->bank_idx - 1] = false; common_hal_reset_pin(self->clock->pin); - common_hal_reset_pin(self->mosi->pin); - common_hal_reset_pin(self->miso->pin); + if (self->mosi != NULL) { + common_hal_reset_pin(self->mosi->pin); + } + if (self->miso != NULL) { + common_hal_reset_pin(self->miso->pin); + } - self->clock = NULL; - self->mosi = NULL; - self->miso = NULL; + common_hal_busio_spi_mark_deinit(self); } bool common_hal_busio_spi_configure(busio_spi_obj_t *self, @@ -240,8 +231,8 @@ bool common_hal_busio_spi_configure(busio_spi_obj_t *self, 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 && - (baudrate == common_hal_busio_spi_get_frequency(self))) { + (bits == ((self->spi->TCR & LPSPI_TCR_FRAMESZ_MASK) >> LPSPI_TCR_FRAMESZ_SHIFT) + 1) && + (baudrate == self->target_frequency)) { return true; } @@ -267,6 +258,7 @@ bool common_hal_busio_spi_configure(busio_spi_obj_t *self, LPSPI_Enable(self->spi, false); self->baudrate = LPSPI_MasterSetBaudRate(self->spi, baudrate, LPSPI_MASTER_CLK_FREQ, &tcrPrescaleValue); LPSPI_Enable(self->spi, true); + self->target_frequency = baudrate; return true; } diff --git a/ports/mimxrt10xx/common-hal/busio/SPI.h b/ports/mimxrt10xx/common-hal/busio/SPI.h index 67801078261..111c71f94f1 100644 --- a/ports/mimxrt10xx/common-hal/busio/SPI.h +++ b/ports/mimxrt10xx/common-hal/busio/SPI.h @@ -17,9 +17,8 @@ typedef struct { LPSPI_Type *spi; bool has_lock; uint32_t baudrate; + uint32_t target_frequency; const mcu_periph_obj_t *clock; const mcu_periph_obj_t *mosi; const mcu_periph_obj_t *miso; } busio_spi_obj_t; - -void spi_reset(void); diff --git a/ports/mimxrt10xx/common-hal/busio/UART.c b/ports/mimxrt10xx/common-hal/busio/UART.c index d372865e8a1..1ce5f2d9a60 100644 --- a/ports/mimxrt10xx/common-hal/busio/UART.c +++ b/ports/mimxrt10xx/common-hal/busio/UART.c @@ -33,7 +33,6 @@ // arrays use 0 based numbering: UART1 is stored at index 0 static bool reserved_uart[MP_ARRAY_SIZE(mcu_uart_banks)]; -static bool never_reset_uart[MP_ARRAY_SIZE(mcu_uart_banks)]; #if IMXRT11XX #define UART_CLOCK_FREQ (24000000) @@ -63,13 +62,13 @@ static void config_periph_pin(const mcu_periph_obj_t *periph) { | IOMUXC_SW_PAD_CTL_PAD_SRE(0)); } -void common_hal_busio_uart_never_reset(busio_uart_obj_t *self) { - never_reset_uart[self->index] = true; - common_hal_never_reset_pin(self->tx); - common_hal_never_reset_pin(self->rx); - common_hal_never_reset_pin(self->rts); - common_hal_never_reset_pin(self->cts); - common_hal_never_reset_pin(self->rs485_dir); +static void mark_deinit(busio_uart_obj_t *self) { + self->rx = NULL; + self->tx = NULL; + self->cts = NULL; + self->rts = NULL; + self->rs485_dir = NULL; + self->ringbuf = NULL; } void common_hal_busio_uart_construct(busio_uart_obj_t *self, @@ -80,6 +79,7 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, mp_float_t timeout, uint16_t receiver_buffer_size, byte *receiver_buffer, bool sigint_enabled) { + mark_deinit(self); self->baudrate = baudrate; self->character_bits = (uint8_t)mp_arg_validate_int_range(bits, 7, 8, MP_QSTR_bits); self->timeout_ms = timeout * 1000; @@ -151,6 +151,10 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, // we won't get here. } + if (uart_taken) { + mp_raise_ValueError(MP_ERROR_TEXT("Hardware in use, try alternative pins")); + } + if (rx && !rx_config) { raise_ValueError_invalid_pin_name(MP_QSTR_rx); } @@ -158,9 +162,8 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, raise_ValueError_invalid_pin_name(MP_QSTR_tx); } - if (uart_taken) { - mp_raise_ValueError(MP_ERROR_TEXT("Hardware in use, try alternative pins")); - } + // Use the LPUART that the RX or TX pin belongs to. + const uint8_t bank_idx = (rx_config != NULL ? rx_config : tx_config)->bank_idx; if (is_onedirection && ((rts != NULL) || (cts != NULL))) { mp_raise_ValueError(MP_ERROR_TEXT("Both RX and TX required for flow control")); @@ -188,7 +191,7 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, if ((rts != NULL) || (rs485_dir != NULL)) { for (uint32_t i = 0; i < rts_count; ++i) { - if (mcu_uart_rts_list[i].bank_idx == rx_config->bank_idx) { + if (mcu_uart_rts_list[i].bank_idx == bank_idx) { if (mcu_uart_rts_list[i].pin == rts) { rts_config = &mcu_uart_rts_list[i]; break; @@ -208,7 +211,7 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, if (cts != NULL) { for (uint32_t i = 0; i < cts_count; ++i) { - if (mcu_uart_cts_list[i].bank_idx == tx_config->bank_idx) { + if (mcu_uart_cts_list[i].bank_idx == bank_idx) { if (mcu_uart_cts_list[i].pin == cts) { cts_config = &mcu_uart_cts_list[i]; break; @@ -220,13 +223,21 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, } } - - if (self->rx) { - self->index = rx_config->bank_idx - 1; - } else { - assert(self->tx); - self->index = tx_config->bank_idx - 1; + size_t ringbuf_size = receiver_buffer_size; + if (rx_config != NULL) { + if (receiver_buffer == NULL) { + // One byte is used internally so add one to make sure we have enough space. + ringbuf_size += 1; + self->ringbuf = gc_alloc(ringbuf_size, false); + if (self->ringbuf == NULL) { + m_malloc_fail(ringbuf_size); + } + } else { + self->ringbuf = receiver_buffer; + } } + + self->index = bank_idx - 1; self->uart = mcu_uart_banks[self->index]; assert(self->uart); @@ -309,28 +320,15 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, } if (self->rx != NULL) { - if (receiver_buffer == NULL) { - // One byte is used internally so add one to make sure we have enough space. - receiver_buffer_size += 1; - self->ringbuf = gc_alloc(receiver_buffer_size, false); - } else { - self->ringbuf = receiver_buffer; - } - - - if (!self->ringbuf) { - LPUART_Deinit(self->uart); - m_malloc_fail(receiver_buffer_size); - } - // Use the internal ring buffer implementation. LPUART_TransferCreateHandle(self->uart, &self->handle, NULL, NULL); // Pass actual allocated size; the LPUART routines are cognizant that // the capacity is one less than the size. - LPUART_TransferStartRingBuffer(self->uart, &self->handle, self->ringbuf, receiver_buffer_size); + LPUART_TransferStartRingBuffer(self->uart, &self->handle, self->ringbuf, ringbuf_size); claim_pin(self->rx); } + reserved_uart[self->index] = true; DBGPrintf(&mp_plat_print, "\t<< Init completed >>\n"); } @@ -348,7 +346,6 @@ void common_hal_busio_uart_deinit(busio_uart_obj_t *self) { gc_free(self->ringbuf); reserved_uart[self->index] = false; - never_reset_uart[self->index] = false; common_hal_reset_pin(self->rx); common_hal_reset_pin(self->tx); @@ -356,11 +353,7 @@ void common_hal_busio_uart_deinit(busio_uart_obj_t *self) { common_hal_reset_pin(self->rts); common_hal_reset_pin(self->rs485_dir); - self->rx = NULL; - self->tx = NULL; - self->cts = NULL; - self->rts = NULL; - self->rs485_dir = NULL; + mark_deinit(self); } // Read characters. diff --git a/ports/mimxrt10xx/common-hal/canio/CAN.c b/ports/mimxrt10xx/common-hal/canio/CAN.c index ba2c2482a34..54c8e1794e3 100644 --- a/ports/mimxrt10xx/common-hal/canio/CAN.c +++ b/ports/mimxrt10xx/common-hal/canio/CAN.c @@ -219,6 +219,11 @@ void common_hal_canio_can_construct(canio_can_obj_t *self, const mcu_pin_obj_t * MIMXRT_CANIO_CAN_DEBUG("canio: init silent: %d\n", silent ? 1 : 0); MIMXRT_CANIO_CAN_DEBUG("canio: init baudrate: %d\n", baudrate); + // can_objs[] is indexed from 0; instance is 1 for CAN1. + if (can_objs[instance - 1] != NULL) { + mp_raise_ValueError(MP_ERROR_TEXT("Hardware in use, try alternative pins")); + } + self->rx_pin = rx; self->tx_pin = tx; config_periph_pin(rx_periph); @@ -228,7 +233,7 @@ void common_hal_canio_can_construct(canio_can_obj_t *self, const mcu_pin_obj_t * self->silent = silent; self->baudrate = baudrate; - self->data = m_new_obj(mimxrt10xx_flexcan_data_t); + self->data = m_malloc_without_collect(sizeof(mimxrt10xx_flexcan_data_t)); self->data->base = flexcan_bases[instance]; // 'flexcan_bases' start indexing from 1. (The first element is NULL) self->data->tx_state = 0; @@ -274,7 +279,7 @@ void common_hal_canio_can_construct(canio_can_obj_t *self, const mcu_pin_obj_t * claim_pin(rx); claim_pin(tx); - can_objs[instance] = self; + can_objs[instance - 1] = self; } bool common_hal_canio_can_loopback_get(canio_can_obj_t *self) { @@ -428,18 +433,21 @@ void common_hal_canio_can_deinit(canio_can_obj_t *self) { self->data = NULL; } + // Find which hardware instance we are so we can free its slot. + size_t instance = MP_ARRAY_SIZE(can_objs); + for (size_t i = 0; i < MP_ARRAY_SIZE(can_objs); i++) { + if (can_objs[i] == self) { + instance = i; + break; + } + } + if (instance < MP_ARRAY_SIZE(can_objs)) { + can_objs[instance] = NULL; + } + common_hal_reset_pin(self->rx_pin); common_hal_reset_pin(self->tx_pin); self->rx_pin = NULL; self->tx_pin = NULL; } - -void common_hal_canio_reset(void) { - for (size_t i = 0; i < MP_ARRAY_SIZE(can_objs); i++) { - if (can_objs[i]) { - common_hal_canio_can_deinit(can_objs[i]); - can_objs[i] = NULL; - } - } -} diff --git a/ports/mimxrt10xx/common-hal/canio/Listener.c b/ports/mimxrt10xx/common-hal/canio/Listener.c index c2812b8b993..081ba1b55fd 100644 --- a/ports/mimxrt10xx/common-hal/canio/Listener.c +++ b/ports/mimxrt10xx/common-hal/canio/Listener.c @@ -123,7 +123,13 @@ mp_obj_t common_hal_canio_listener_receive(canio_listener_obj_t *self) { // allows the CPU to serve the next FIFO entry FLEXCAN_ClearMbStatusFlags(self->can->data->base, (uint32_t)kFLEXCAN_RxFifoFrameAvlFlag); - canio_message_obj_t *message = m_new_obj(canio_message_obj_t); + const mp_obj_type_t *type; + if (rx_frame.type == kFLEXCAN_FrameTypeRemote) { + type = &canio_remote_transmission_request_type; + } else { + type = &canio_message_type; + } + canio_message_obj_t *message = mp_obj_malloc(canio_message_obj_t, type); memset(message, 0, sizeof(canio_message_obj_t)); if (rx_frame.format == kFLEXCAN_FrameFormatExtend) { @@ -134,11 +140,6 @@ mp_obj_t common_hal_canio_listener_receive(canio_listener_obj_t *self) { message->id = rx_frame.id >> 18; // standard ids are left-aligned } - if (rx_frame.type == kFLEXCAN_FrameTypeRemote) { - message->base.type = &canio_remote_transmission_request_type; - } else { - message->base.type = &canio_message_type; - } message->size = rx_frame.length; @@ -157,7 +158,7 @@ mp_obj_t common_hal_canio_listener_receive(canio_listener_obj_t *self) { } void common_hal_canio_listener_deinit(canio_listener_obj_t *self) { - if (self->can) { + if (self->can && !common_hal_canio_can_deinited(self->can)) { // Clear all filters. flexcan_rx_fifo_config_t fifo_config; fifo_config.idFilterNum = 0; diff --git a/ports/mimxrt10xx/common-hal/digitalio/DigitalInOut.c b/ports/mimxrt10xx/common-hal/digitalio/DigitalInOut.c index 48671f3fea9..1e121707c78 100644 --- a/ports/mimxrt10xx/common-hal/digitalio/DigitalInOut.c +++ b/ports/mimxrt10xx/common-hal/digitalio/DigitalInOut.c @@ -52,11 +52,6 @@ digitalinout_result_t common_hal_digitalio_digitalinout_construct( return DIGITALINOUT_OK; } -void common_hal_digitalio_digitalinout_never_reset( - digitalio_digitalinout_obj_t *self) { - common_hal_never_reset_pin(self->pin); -} - bool common_hal_digitalio_digitalinout_deinited(digitalio_digitalinout_obj_t *self) { return self->pin == NULL; } diff --git a/ports/mimxrt10xx/common-hal/microcontroller/Pin.c b/ports/mimxrt10xx/common-hal/microcontroller/Pin.c index c20a1738af0..6903c814936 100644 --- a/ports/mimxrt10xx/common-hal/microcontroller/Pin.c +++ b/ports/mimxrt10xx/common-hal/microcontroller/Pin.c @@ -14,7 +14,6 @@ #include "py/gc.h" static bool claimed_pins[PAD_COUNT]; -static bool never_reset_pins[PAD_COUNT]; // Default is that no pins are forbidden to reset. MP_WEAK const mcu_pin_obj_t *mimxrt10xx_reset_forbidden_pins[] = { @@ -36,19 +35,6 @@ static bool _reset_forbidden(const mcu_pin_obj_t *pin) { // IOMUXC index, used for iterating through pins and accessing reset information, // and GPIO port and number, used to store claimed and reset tagging. The two number // systems are not related and one cannot determine the other without a pin object -void reset_all_pins(void) { - for (uint8_t i = 0; i < PAD_COUNT; i++) { - claimed_pins[i] = never_reset_pins[i]; - } - for (uint8_t i = 0; i < PAD_COUNT; i++) { - mcu_pin_obj_t *pin = mcu_pin_globals.map.table[i].value; - if (never_reset_pins[pin->mux_idx]) { - continue; - } - common_hal_reset_pin(pin); - } -} - MP_WEAK bool mimxrt10xx_board_reset_pin_number(const mcu_pin_obj_t *pin) { return false; } @@ -60,6 +46,8 @@ void common_hal_reset_pin(const mcu_pin_obj_t *pin) { return; } + claimed_pins[pin->mux_idx] = false; + if (_reset_forbidden(pin)) { return; } @@ -70,8 +58,6 @@ void common_hal_reset_pin(const mcu_pin_obj_t *pin) { } disable_pin_change_interrupt(pin); - never_reset_pins[pin->mux_idx] = false; - claimed_pins[pin->mux_idx] = false; // Make sure this pin's GPIO is set to input. Otherwise, output values could interfere // with the ADC. @@ -86,13 +72,6 @@ void common_hal_reset_pin(const mcu_pin_obj_t *pin) { *(uint32_t *)pin->cfg_reg = pin->pad_reset; } -void common_hal_never_reset_pin(const mcu_pin_obj_t *pin) { - if (pin == NULL) { - return; - } - never_reset_pins[pin->mux_idx] = true; -} - bool common_hal_mcu_pin_is_free(const mcu_pin_obj_t *pin) { return !claimed_pins[pin->mux_idx]; } diff --git a/ports/mimxrt10xx/common-hal/microcontroller/Pin.h b/ports/mimxrt10xx/common-hal/microcontroller/Pin.h index c40a4dc2a68..47f9e2b215a 100644 --- a/ports/mimxrt10xx/common-hal/microcontroller/Pin.h +++ b/ports/mimxrt10xx/common-hal/microcontroller/Pin.h @@ -10,9 +10,12 @@ #include "periph.h" #include "pins.h" -void reset_all_pins(void); +void common_hal_reset_pin(const mcu_pin_obj_t *pin); void claim_pin(const mcu_pin_obj_t *pin); +uint8_t common_hal_mcu_pin_number(const mcu_pin_obj_t *pin); +void common_hal_mcu_pin_claim(const mcu_pin_obj_t *pin); + // List of pins that should never be reset. extern const mcu_pin_obj_t *mimxrt10xx_reset_forbidden_pins[]; diff --git a/ports/mimxrt10xx/common-hal/microcontroller/Processor.c b/ports/mimxrt10xx/common-hal/microcontroller/Processor.c index 23e854953d6..c7cbd52566b 100644 --- a/ports/mimxrt10xx/common-hal/microcontroller/Processor.c +++ b/ports/mimxrt10xx/common-hal/microcontroller/Processor.c @@ -77,5 +77,5 @@ void common_hal_mcu_processor_get_uid(uint8_t raw_id[]) { } mcu_reset_reason_t common_hal_mcu_processor_get_reset_reason(void) { - return RESET_REASON_UNKNOWN; + return MCU_RESET_REASON_UNKNOWN; } diff --git a/ports/mimxrt10xx/common-hal/pwmio/PWMOut.c b/ports/mimxrt10xx/common-hal/pwmio/PWMOut.c index e1507c7fc02..7ad3eba0c80 100644 --- a/ports/mimxrt10xx/common-hal/pwmio/PWMOut.c +++ b/ports/mimxrt10xx/common-hal/pwmio/PWMOut.c @@ -65,10 +65,6 @@ static uint16_t _outen_mask(pwm_submodule_t submodule, pwm_channels_t channel) { return outen_mask; } -void common_hal_pwmio_pwmout_never_reset(pwmio_pwmout_obj_t *self) { - common_hal_never_reset_pin(self->pin); -} - static void _maybe_disable_clock(uint8_t instance) { if ((_flexpwms[instance]->MCTRL & PWM_MCTRL_RUN_MASK) == 0) { CLOCK_DisableClock(_flexpwm_clocks[instance][0]); @@ -92,14 +88,19 @@ static int calculate_pulse_count(uint32_t frequency, uint8_t *prescaler) { return 0; } +static void mark_deinit(pwmio_pwmout_obj_t *self) { + self->pin = NULL; +} + 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; + mark_deinit(self); self->variable_frequency = variable_frequency; + self->pwm = NULL; for (uint32_t i = 0; i < MP_ARRAY_SIZE(mcu_pwm_list); ++i) { if (mcu_pwm_list[i].pin != pin) { continue; @@ -114,6 +115,11 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t *self, return PWMOUT_INVALID_PIN; } + // X channels can't do a full 100% duty cycle. + if (duty == 65535 && self->pwm->channel == kPWM_PwmX) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("Invalid %q"), MP_QSTR_duty_cycle); + } + PWM_Type *flexpwm = self->pwm->pwm; pwm_submodule_t submodule = self->pwm->submodule; uint16_t sm_mask = 1 << submodule; @@ -144,7 +150,7 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t *self, // We want variable frequency but another class has already claim a fixed frequency. if (variable_frequency) { - return PWMOUT_VARIABLE_FREQUENCY_NOT_AVAILABLE; + return PWMOUT_INTERNAL_RESOURCES_IN_USE; } // Another pin is already using this output. @@ -153,7 +159,7 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t *self, } if (frequency != _pwm_sm_frequencies[flexpwm_index][submodule]) { - return PWMOUT_INVALID_FREQUENCY_ON_PIN; + return PWMOUT_INTERNAL_RESOURCES_IN_USE; } // Submodule is already running at our target frequency and the output @@ -207,7 +213,7 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t *self, _pwm_sm_frequencies[flexpwm_index][submodule] = frequency; if (variable_frequency) { - _pwm_variable_frequency[flexpwm_index] = sm_mask; + _pwm_variable_frequency[flexpwm_index] |= sm_mask; } } @@ -218,6 +224,8 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t *self, // Configure the IOMUX once we know everything else is working. config_periph_pin(self->pwm); + claim_pin(pin); + self->pin = pin; return PWMOUT_OK; } @@ -236,7 +244,7 @@ void common_hal_pwmio_pwmout_deinit(pwmio_pwmout_obj_t *self) { // Reset the pin before we turn it off. common_hal_reset_pin(self->pin); - self->pin = NULL; + mark_deinit(self); // Always disable the output. flexpwm->OUTEN &= ~_outen_mask(submodule, self->pwm->channel); diff --git a/ports/mimxrt10xx/common-hal/rotaryio/IncrementalEncoder.c b/ports/mimxrt10xx/common-hal/rotaryio/IncrementalEncoder.c index c71f8b212e1..211b5c186f3 100644 --- a/ports/mimxrt10xx/common-hal/rotaryio/IncrementalEncoder.c +++ b/ports/mimxrt10xx/common-hal/rotaryio/IncrementalEncoder.c @@ -26,6 +26,9 @@ static void encoder_change(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) { + // Ensure object starts in its deinit state. + common_hal_rotaryio_incrementalencoder_mark_deinit(self); + self->pin_a = pin_a; self->pin_b = pin_b; @@ -49,7 +52,7 @@ void common_hal_rotaryio_incrementalencoder_construct(rotaryio_incrementalencode } bool common_hal_rotaryio_incrementalencoder_deinited(rotaryio_incrementalencoder_obj_t *self) { - return !self->pin_a; + return self->pin_a == NULL; } void common_hal_rotaryio_incrementalencoder_deinit(rotaryio_incrementalencoder_obj_t *self) { @@ -62,6 +65,9 @@ void common_hal_rotaryio_incrementalencoder_deinit(rotaryio_incrementalencoder_o common_hal_reset_pin(self->pin_a); common_hal_reset_pin(self->pin_b); + common_hal_rotaryio_incrementalencoder_mark_deinit(self); +} + +void common_hal_rotaryio_incrementalencoder_mark_deinit(rotaryio_incrementalencoder_obj_t *self) { self->pin_a = NULL; - self->pin_b = NULL; } diff --git a/ports/mimxrt10xx/common-hal/rtc/RTC.h b/ports/mimxrt10xx/common-hal/rtc/RTC.h index 851b08970bb..50b0539d4d6 100644 --- a/ports/mimxrt10xx/common-hal/rtc/RTC.h +++ b/ports/mimxrt10xx/common-hal/rtc/RTC.h @@ -8,4 +8,3 @@ #pragma once extern void rtc_init(void); -extern void rtc_reset(void); diff --git a/ports/mimxrt10xx/common-hal/usb_host/Port.c b/ports/mimxrt10xx/common-hal/usb_host/Port.c index 31af4ed5823..a7e73ab5b5c 100644 --- a/ports/mimxrt10xx/common-hal/usb_host/Port.c +++ b/ports/mimxrt10xx/common-hal/usb_host/Port.c @@ -47,5 +47,8 @@ usb_host_port_obj_t *common_hal_usb_host_port_construct(const mcu_pin_obj_t *dp, self->dp = dp; self->dm = dm; + claim_pin(dp); + claim_pin(dm); + return self; } diff --git a/ports/mimxrt10xx/linking/common.ld b/ports/mimxrt10xx/linking/common.ld index 2c6be0dd129..1131f2b6f1f 100644 --- a/ports/mimxrt10xx/linking/common.ld +++ b/ports/mimxrt10xx/linking/common.ld @@ -69,6 +69,12 @@ SECTIONS .text : { . = ALIGN(4); + __property_getter_start = .; + *(.property_getter) + __property_getter_end = .; + __property_getset_start = .; + *(.property_getset) + __property_getset_end = .; *(EXCLUDE_FILE( *fsl_flexspi.o *cd_ci_hs.o @@ -210,4 +216,9 @@ SECTIONS __StackTop = ORIGIN(DTCM) + LENGTH(DTCM); .ARM.attributes 0 : { *(.ARM.attributes) } + + ASSERT((__property_getter_end - __property_getter_start) % 8 == 0, + "the .property_getter section must hold whole 8-byte objects") + ASSERT((__property_getset_end - __property_getset_start) % 12 == 0, + "the .property_getset section must hold whole 12-byte objects") } diff --git a/ports/mimxrt10xx/mpconfigport.h b/ports/mimxrt10xx/mpconfigport.h index 4d5e4e59700..df634dc7328 100644 --- a/ports/mimxrt10xx/mpconfigport.h +++ b/ports/mimxrt10xx/mpconfigport.h @@ -25,6 +25,8 @@ extern uint8_t _ld_default_stack_size; // are aligned to cache lines. #define MICROPY_BYTES_PER_GC_BLOCK (32) +#define CIRCUITPY_USB_DEVICE_HIGH_SPEED (1) + #include "py/circuitpy_mpconfig.h" // TODO: diff --git a/ports/mimxrt10xx/mpconfigport.mk b/ports/mimxrt10xx/mpconfigport.mk index 20d802eb354..101568a8432 100644 --- a/ports/mimxrt10xx/mpconfigport.mk +++ b/ports/mimxrt10xx/mpconfigport.mk @@ -1,9 +1,10 @@ +# Properties get a dedicated linker section here, so they can drop the unused slots. +CIRCUITPY_OPTIMIZE_PROPERTY_FLASH_SIZE ?= 1 + LD_FILE = $(FLASH).ld $(CHIP_FAMILY).ld imxrt10xx.ld INTERNAL_LIBM = 1 -USB_HIGHSPEED = 1 - # Number of USB endpoint pairs. USB_NUM_ENDPOINT_PAIRS = 8 # Align buffers on the cache boundary so we don't inadvertently load them early. diff --git a/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1011/pin_names.h b/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1011/pin_names.h index 1d6a9cafaf8..3cf071f62ca 100644 --- a/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1011/pin_names.h +++ b/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1011/pin_names.h @@ -6,8 +6,7 @@ // // SPDX-License-Identifier: MIT -#pragma once - +// OK to include more than once because FORMAT_PIN may be different. // define FORMAT_PIN(pin_name) and then include this file. diff --git a/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1015/pin_names.h b/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1015/pin_names.h index ee8b47b61af..a0bb59e5479 100644 --- a/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1015/pin_names.h +++ b/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1015/pin_names.h @@ -6,7 +6,7 @@ // // SPDX-License-Identifier: MIT -#pragma once +// OK to include more than once because FORMAT_PIN may be different. // define FORMAT_PIN(pin_name) and then include this file. diff --git a/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1021/pin_names.h b/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1021/pin_names.h index 1218cd8ed8d..45203c59968 100644 --- a/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1021/pin_names.h +++ b/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1021/pin_names.h @@ -6,7 +6,7 @@ // // SPDX-License-Identifier: MIT -#pragma once +// OK to include more than once because FORMAT_PIN may be different. // define FORMAT_PIN(pin_name) and then include this file. diff --git a/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1042/pin_names.h b/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1042/pin_names.h index 42f03e02f91..8a98f4560a6 100644 --- a/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1042/pin_names.h +++ b/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1042/pin_names.h @@ -6,7 +6,7 @@ // // SPDX-License-Identifier: MIT -#pragma once +// OK to include more than once because FORMAT_PIN may be different. // define FORMAT_PIN(pin_name) and then include this file. diff --git a/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1052/pin_names.h b/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1052/pin_names.h index 5483206f94f..41d2d67f81a 100644 --- a/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1052/pin_names.h +++ b/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1052/pin_names.h @@ -6,7 +6,7 @@ // // SPDX-License-Identifier: MIT -#pragma once +// OK to include more than once because FORMAT_PIN may be different. // define FORMAT_PIN(pin_name) and then include this file. diff --git a/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1062/pin_names.h b/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1062/pin_names.h index 5483206f94f..41d2d67f81a 100644 --- a/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1062/pin_names.h +++ b/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1062/pin_names.h @@ -6,7 +6,7 @@ // // SPDX-License-Identifier: MIT -#pragma once +// OK to include more than once because FORMAT_PIN may be different. // define FORMAT_PIN(pin_name) and then include this file. diff --git a/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1176/pin_names.h b/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1176/pin_names.h index ec23d603de7..b5a5b86b4dd 100644 --- a/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1176/pin_names.h +++ b/ports/mimxrt10xx/peripherals/mimxrt10xx/MIMXRT1176/pin_names.h @@ -6,7 +6,7 @@ // // SPDX-License-Identifier: MIT -#pragma once +// OK to include more than once because FORMAT_PIN may be different. // define FORMAT_PIN(pin_name) and then include this file. diff --git a/ports/mimxrt10xx/peripherals/mimxrt10xx/pin_names.h b/ports/mimxrt10xx/peripherals/mimxrt10xx/pin_names.h index 22fa6c57296..ffaa74edc38 100644 --- a/ports/mimxrt10xx/peripherals/mimxrt10xx/pin_names.h +++ b/ports/mimxrt10xx/peripherals/mimxrt10xx/pin_names.h @@ -5,8 +5,6 @@ // // SPDX-License-Identifier: MIT -#pragma once - // OK to include more than once because FORMAT_PIN may be different. #ifdef MIMXRT1011_SERIES diff --git a/ports/mimxrt10xx/reset.h b/ports/mimxrt10xx/reset.h index 04c951221e9..cae838556bc 100644 --- a/ports/mimxrt10xx/reset.h +++ b/ports/mimxrt10xx/reset.h @@ -16,6 +16,6 @@ #define DBL_TAP_MAGIC 0xf01669ef // Randomly selected, adjusted to have first and last bit set #define DBL_TAP_MAGIC_QUICK_BOOT 0xf02669ef -void reset_to_bootloader(void) NORETURN; -void reset(void) NORETURN; +void reset_to_bootloader(void) MP_NORETURN; +void reset(void) MP_NORETURN; bool bootloader_available(void); diff --git a/ports/mimxrt10xx/supervisor/cpu.S b/ports/mimxrt10xx/supervisor/cpu.S deleted file mode 100755 index 9e6807a5e2e..00000000000 --- a/ports/mimxrt10xx/supervisor/cpu.S +++ /dev/null @@ -1,27 +0,0 @@ -.syntax unified -.cpu cortex-m4 -.thumb -.text -.align 2 - -@ uint cpu_get_regs_and_sp(r0=uint regs[10]) -.global cpu_get_regs_and_sp -.thumb -.thumb_func -.type cpu_get_regs_and_sp, %function -cpu_get_regs_and_sp: -@ store registers into given array -str r4, [r0], #4 -str r5, [r0], #4 -str r6, [r0], #4 -str r7, [r0], #4 -str r8, [r0], #4 -str r9, [r0], #4 -str r10, [r0], #4 -str r11, [r0], #4 -str r12, [r0], #4 -str r13, [r0], #4 - -@ return the sp -mov r0, sp -bx lr diff --git a/ports/mimxrt10xx/supervisor/port.c b/ports/mimxrt10xx/supervisor/port.c index d7f7f280d19..9b0b4520bae 100644 --- a/ports/mimxrt10xx/supervisor/port.c +++ b/ports/mimxrt10xx/supervisor/port.c @@ -22,6 +22,7 @@ #include "common-hal/microcontroller/Pin.h" #include "common-hal/rtc/RTC.h" +#include "shared-bindings/rtc/__init__.h" #include "common-hal/busio/SPI.h" #include "shared-bindings/microcontroller/__init__.h" @@ -415,7 +416,7 @@ safe_mode_t port_init(void) { #endif // Note that `reset_port` CANNOT GO HERE, unlike other ports, because `board_init` hasn't been - // run yet, which uses `never_reset` to protect critical pins from being reset by `reset_port`. + // run yet, which may claim critical pins that should not be reset by `reset_port`. if (board_requests_safe_mode()) { return SAFE_MODE_USER; @@ -425,33 +426,11 @@ safe_mode_t port_init(void) { } void reset_port(void) { - #if CIRCUITPY_BUSIO - spi_reset(); - #endif - - #if CIRCUITPY_AUDIOIO - audio_dma_reset(); - #endif - - #if CIRCUITPY_AUDIOBUSIO - i2s_reset(); - #endif - - #if CIRCUITPY_TOUCHIO && CIRCUITPY_TOUCHIO_USE_NATIVE - touchin_reset(); - #endif - #if CIRCUITPY_RTC rtc_reset(); #endif - #if CIRCUITPY_PEW - pew_reset(); - #endif - // reset_event_system(); - - reset_all_pins(); } void reset_to_bootloader(void) { diff --git a/ports/nordic/Makefile b/ports/nordic/Makefile index 85acb9d8b4e..88766e0dc3d 100755 --- a/ports/nordic/Makefile +++ b/ports/nordic/Makefile @@ -6,9 +6,12 @@ include ../../py/circuitpy_mkenv.mk -ifneq ($(SD), ) +# Skip when the make command is not board-specific i.e. fetch-port-submodules. +ifneq ($(VALID_BOARD),) +ifeq ($(CIRCUITPY_BLEIO_NATIVE),1) include bluetooth/bluetooth_common.mk endif +endif CROSS_COMPILE = arm-none-eabi- @@ -36,8 +39,8 @@ ifeq ($(DEBUG), 1) CFLAGS += -ggdb3 OPTIMIZATION_FLAGS = -Og else - OPTIMIZATION_FLAGS ?= -O2 -fno-inline-functions - CFLAGS += -DNDEBUG -ggdb3 + OPTIMIZATION_FLAGS ?= -O2 + CFLAGS += -DNDEBUG endif ifeq ($(NRF_DEBUG_PRINT), 1) @@ -47,7 +50,7 @@ endif # option to override compiler optimization level, set in boards/$(BOARD)/mpconfigboard.mk CFLAGS += $(OPTIMIZATION_FLAGS) -CFLAGS += $(INC) -Wall -Werror -std=gnu11 -nostdlib -fshort-enums $(BASE_CFLAGS) $(CFLAGS_MOD) $(COPT) -Werror=missing-prototypes +CFLAGS += $(INC) -Wall -Werror -std=gnu11 -nostdlib -fshort-enums $(BASE_CFLAGS) $(CFLAGS_MOD) $(COPT) -Werror=missing-prototypes -Werror=old-style-definition # Nordic Softdevice SDK header files contains inline assembler that has # broken constraints. As a result the IPA-modref pass, introduced in gcc-11, @@ -115,11 +118,16 @@ SRC_C += \ boards/$(BOARD)/board.c \ boards/$(BOARD)/pins.c \ device/$(MCU_VARIANT)/startup_$(MCU_SUB_VARIANT).c \ + nrfx/mdk/system_$(MCU_SUB_VARIANT).c \ + +ifeq ($(CIRCUITPY_BLEIO_NATIVE),1) +SRC_C += \ bluetooth/ble_drv.c \ common-hal/_bleio/bonding.c \ - nrfx/mdk/system_$(MCU_SUB_VARIANT).c \ sd_mutex.c \ +endif + SRC_PERIPHERALS := \ peripherals/nrf/cache.c \ peripherals/nrf/clocks.c \ @@ -146,20 +154,9 @@ SRC_C += $(SRC_DCD) $(patsubst %.c,$(BUILD)/%.o,$(SRC_DCD)): CFLAGS += -Wno-missing-prototypes endif # CIRCUITPY_USB_DEVICE -SRC_COMMON_HAL_EXPANDED = $(addprefix shared-bindings/, $(SRC_COMMON_HAL)) \ - $(addprefix shared-bindings/, $(SRC_BINDINGS_ENUMS)) \ - $(addprefix common-hal/, $(SRC_COMMON_HAL)) - -SRC_SHARED_MODULE_EXPANDED = $(addprefix shared-bindings/, $(SRC_SHARED_MODULE)) \ - $(addprefix shared-module/, $(SRC_SHARED_MODULE)) \ - $(addprefix shared-module/, $(SRC_SHARED_MODULE_INTERNAL)) - -# There may be duplicates between SRC_COMMON_HAL_EXPANDED and SRC_SHARED_MODULE_EXPANDED, -# because a few modules have files both in common-hal/ and shared-module/. -# Doing a $(sort ...) removes duplicates as part of sorting. -SRC_COMMON_HAL_SHARED_MODULE_EXPANDED = $(sort $(SRC_COMMON_HAL_EXPANDED) $(SRC_SHARED_MODULE_EXPANDED)) +SRC_S = shared/runtime/gchelper_thumb2.s -SRC_S = supervisor/cpu.s +SRC_C += shared/runtime/gchelper_native.c OBJ += $(PY_O) $(SUPERVISOR_O) $(addprefix $(BUILD)/, $(SRC_C:.c=.o)) OBJ += $(addprefix $(BUILD)/, $(SRC_NRFX:.c=.o)) @@ -180,7 +177,7 @@ $(BUILD)/$(FATFS_DIR)/ff.o: COPT += -Os $(filter $(PY_BUILD)/../extmod/vfs_fat_%.o, $(PY_O)): COPT += -Os # List of sources for qstr extraction -SRC_QSTR += $(SRC_C) $(SRC_SUPERVISOR) $(SRC_MOD) $(SRC_COMMON_HAL_EXPANDED) $(SRC_SHARED_MODULE_EXPANDED) $(SRC_CIRCUITPY_COMMON) +SRC_QSTR += $(SRC_C) $(SRC_SUPERVISOR) $(SRC_MOD) $(SRC_COMMON_HAL_SHARED_MODULE_EXPANDED) $(SRC_CIRCUITPY_COMMON) # Sources that only hold QSTRs after pre-processing. SRC_QSTR_PREPROCESSOR += @@ -188,7 +185,13 @@ UF2_FAMILY_ID_nrf52840 = 0xADA52840 UF2_FAMILY_ID_nrf52833 = 0x621E937A +ifeq ($(CIRCUITPY_BLEIO_NATIVE),1) all: $(BUILD)/firmware.bin $(BUILD)/firmware.uf2 $(BUILD)/firmware.combined.hex +else +# firmware.combined.hex merges in the SoftDevice hex; without one there is +# nothing to combine. +all: $(BUILD)/firmware.bin $(BUILD)/firmware.uf2 $(BUILD)/firmware.hex +endif ifeq ($(VALID_BOARD),) $(BUILD)/firmware.elf: invalid-board @@ -197,7 +200,7 @@ $(BUILD)/firmware.elf: $(OBJ) $(GENERATED_LD_FILE) $(STEPECHO) "LINK $@" $(Q)echo $(OBJ) > $(BUILD)/firmware.objs $(Q)$(CC) -o $@ $(LDFLAGS) @$(BUILD)/firmware.objs -Wl,--print-memory-usage -Wl,--start-group $(LIBS) -Wl,--end-group - $(Q)$(SIZE) $@ | $(PYTHON) $(TOP)/tools/build_memory_info.py $(GENERATED_LD_FILE) $(BUILD) + $(Q)$(PYTHON) $(TOP)/tools/build_memory_info.py $@.map $(BUILD) --elf $@ endif $(BUILD)/firmware.bin: $(BUILD)/firmware.elf diff --git a/ports/nordic/bluetooth/ble_drv.c b/ports/nordic/bluetooth/ble_drv.c index 35d577f117c..c2122c8845e 100644 --- a/ports/nordic/bluetooth/ble_drv.c +++ b/ports/nordic/bluetooth/ble_drv.c @@ -20,7 +20,7 @@ #include "py/mpstate.h" #include "mpconfigport.h" -#if CIRCUITPY_SERIAL_BLE && CIRCUITPY_VERBOSE_BLE +#if CIRCUITPY_BLE_SERIAL_SERVICE && CIRCUITPY_VERBOSE_BLE #include "supervisor/shared/bluetooth/serial.h" #endif @@ -141,11 +141,14 @@ void ble_drv_reset(void) { void ble_drv_remove_heap_handlers(void) { ble_drv_evt_handler_entry_t *it = MP_STATE_VM(ble_drv_evt_handler_entries); while (it != NULL) { - // If the param is on the heap, then delete the handler. - if (gc_ptr_on_heap(it->param)) { + // Save it->next before removing, because removing clears it. + ble_drv_evt_handler_entry_t *next = it->next; + // Remove the handler if the entry or its param is on the heap, which is + // about to go away. + if (gc_ptr_on_heap(it) || gc_ptr_on_heap(it->param)) { ble_drv_remove_event_handler(it->func, it->param); } - it = it->next; + it = next; } } @@ -229,7 +232,7 @@ void SD_EVT_IRQHandler(void) { } } - #if CIRCUITPY_SERIAL_BLE && CIRCUITPY_VERBOSE_BLE + #if CIRCUITPY_BLE_SERIAL_SERVICE && CIRCUITPY_VERBOSE_BLE ble_serial_disable(); #endif while (1) { @@ -270,7 +273,7 @@ void SD_EVT_IRQHandler(void) { } #endif } - #if CIRCUITPY_SERIAL_BLE && CIRCUITPY_VERBOSE_BLE + #if CIRCUITPY_BLE_SERIAL_SERVICE && CIRCUITPY_VERBOSE_BLE ble_serial_enable(); #endif } diff --git a/ports/nordic/board.h b/ports/nordic/board.h new file mode 100644 index 00000000000..560cafc6da8 --- /dev/null +++ b/ports/nordic/board.h @@ -0,0 +1,10 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Called from port_init() before any peripheral is initialized. +void board_early_init(void); diff --git a/ports/nordic/boards/TG-Watch/mpconfigboard.h b/ports/nordic/boards/TG-Watch/mpconfigboard.h index 8ebb88f6f86..4016b1ea84c 100644 --- a/ports/nordic/boards/TG-Watch/mpconfigboard.h +++ b/ports/nordic/boards/TG-Watch/mpconfigboard.h @@ -13,7 +13,7 @@ #define MICROPY_HW_MCU_NAME "nRF52840" // 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 CIRCUITPY_PYSTACK_SIZE 8192 // the board has a 32mhz crystal but NOT a 32khz one #define BOARD_HAS_32KHZ_XTAL 0 diff --git a/ports/nordic/boards/TG-Watch/mpconfigboard.mk b/ports/nordic/boards/TG-Watch/mpconfigboard.mk index 212ab7edc20..011890898ac 100644 --- a/ports/nordic/boards/TG-Watch/mpconfigboard.mk +++ b/ports/nordic/boards/TG-Watch/mpconfigboard.mk @@ -20,3 +20,5 @@ FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_LC709203F FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_DRV2605 FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_BLE FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_BLE_Apple_Notification_Center + +CIRCUITPY_EPAPERDISPLAY_FAST = 0 diff --git a/ports/nordic/boards/aramcon2_badge/mpconfigboard.h b/ports/nordic/boards/aramcon2_badge/mpconfigboard.h index 4a1d09532d7..e7abce44846 100644 --- a/ports/nordic/boards/aramcon2_badge/mpconfigboard.h +++ b/ports/nordic/boards/aramcon2_badge/mpconfigboard.h @@ -37,10 +37,6 @@ #define BOARD_USER_SAFE_MODE_ACTION MP_ERROR_TEXT("You pressed the left button at start up.") -#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) diff --git a/ports/nordic/boards/bluemicro833/board.c b/ports/nordic/boards/bluemicro833/board.c index 1abc6f4e79c..13d66ace069 100644 --- a/ports/nordic/boards/bluemicro833/board.c +++ b/ports/nordic/boards/bluemicro833/board.c @@ -13,8 +13,6 @@ #include "nrf_gpio.h" void board_init(void) { - // "never_reset" the pin here because CircuitPython will try to reset pins after a VM run otherwise. - never_reset_pin_number(POWER_SWITCH_PIN->number); // Turn on power to sensors and neopixels. nrf_gpio_cfg(POWER_SWITCH_PIN->number, NRF_GPIO_PIN_DIR_OUTPUT, diff --git a/ports/nordic/boards/bluemicro833/mpconfigboard.mk b/ports/nordic/boards/bluemicro833/mpconfigboard.mk index 3fcb7cdbb07..e1502f09b55 100644 --- a/ports/nordic/boards/bluemicro833/mpconfigboard.mk +++ b/ports/nordic/boards/bluemicro833/mpconfigboard.mk @@ -17,6 +17,7 @@ CIRCUITPY_NVM = 0 CIRCUITPY_ONEWIREIO = 0 CIRCUITPY_PIXELBUF = 1 CIRCUITPY_PIXELMAP = 0 +CIRCUITPY_PULSEIO = 0 CIRCUITPY_TOUCHIO = 0 # Features to disable diff --git a/ports/nordic/boards/challenger_840/mpconfigboard.h b/ports/nordic/boards/challenger_840/mpconfigboard.h index 84f9c1651f8..a81fad42c9a 100644 --- a/ports/nordic/boards/challenger_840/mpconfigboard.h +++ b/ports/nordic/boards/challenger_840/mpconfigboard.h @@ -23,10 +23,6 @@ #define CIRCUITPY_AUTORELOAD_DELAY_MS 500 -#define CIRCUITPY_INTERNAL_NVM_SIZE (4096) - -#define BOARD_FLASH_SIZE (FLASH_SIZE - 0x4000 - CIRCUITPY_INTERNAL_NVM_SIZE) - #define BOARD_HAS_CRYSTAL 1 #define DEFAULT_I2C_BUS_SCL (&pin_P1_12) diff --git a/ports/nordic/boards/circuitplayground_bluefruit/board.c b/ports/nordic/boards/circuitplayground_bluefruit/board.c index 17a86c6fe9b..007a6350415 100644 --- a/ports/nordic/boards/circuitplayground_bluefruit/board.c +++ b/ports/nordic/boards/circuitplayground_bluefruit/board.c @@ -9,6 +9,7 @@ #include "py/obj.h" #include "peripherals/nrf/pins.h" #include "supervisor/shared/board.h" +#include "shared-bindings/microcontroller/Pin.h" #include "nrf_gpio.h" @@ -21,6 +22,10 @@ void board_init(void) { NRF_GPIO_PIN_S0S1, NRF_GPIO_PIN_NOSENSE); nrf_gpio_pin_write(POWER_SWITCH_PIN->number, false); + + // P1.04 (SPEAKER_ENABLE) turns on the speaker amplifier. + // Default to low (off). + reset_pin_number(SPEAKER_ENABLE_PIN->number); } void board_deinit(void) { diff --git a/ports/nordic/boards/circuitplayground_bluefruit/mpconfigboard.h b/ports/nordic/boards/circuitplayground_bluefruit/mpconfigboard.h index 91cf68095d2..d63a9ccd5d8 100644 --- a/ports/nordic/boards/circuitplayground_bluefruit/mpconfigboard.h +++ b/ports/nordic/boards/circuitplayground_bluefruit/mpconfigboard.h @@ -50,3 +50,7 @@ #define DEFAULT_UART_BUS_TX (&pin_P0_14) #define SPEAKER_ENABLE_PIN (&pin_P1_04) + +// Uncomment to allow debugging over console UART +// #define CIRCUITPY_CONSOLE_UART_TX (&pin_P0_14) +// #define CIRCUITPY_CONSOLE_UART_RX (&pin_P0_30) diff --git a/ports/nordic/boards/clue_nrf52840_express/board.c b/ports/nordic/boards/clue_nrf52840_express/board.c index e2cd8a324ba..2d947dc1456 100644 --- a/ports/nordic/boards/clue_nrf52840_express/board.c +++ b/ports/nordic/boards/clue_nrf52840_express/board.c @@ -29,14 +29,13 @@ void board_init(void) { fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_P0_14, &pin_P0_15, NULL, false); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_P0_13, // TFT_DC Command or data - &pin_P0_12, // TFT_CS Chip select - &pin_P1_03, // TFT_RST Reset + MP_OBJ_FROM_PTR(&pin_P0_13), // TFT_DC Command or data + MP_OBJ_FROM_PTR(&pin_P0_12), // TFT_CS Chip select + MP_OBJ_FROM_PTR(&pin_P1_03), // TFT_RST Reset 60000000, // Baudrate 0, // Polarity 0); // Phase diff --git a/ports/nordic/boards/common.template.ld b/ports/nordic/boards/common.template.ld index dda31e4fdce..3828e3e7f9c 100644 --- a/ports/nordic/boards/common.template.ld +++ b/ports/nordic/boards/common.template.ld @@ -62,6 +62,12 @@ SECTIONS .text : { . = ALIGN(4); + __property_getter_start = .; + *(.property_getter) + __property_getter_end = .; + __property_getset_start = .; + *(.property_getset) + __property_getset_end = .; *(SORT_BY_ALIGNMENT(SORT_BY_NAME(.text))) /* .text sections (code) */ *(SORT_BY_ALIGNMENT(SORT_BY_NAME(.text*))) /* .text* sections (code) */ *(.rodata) /* .rodata sections (constants, strings, etc.) */ @@ -155,4 +161,9 @@ SECTIONS */ .ARM.attributes 0 : { *(.ARM.attributes) } + + ASSERT((__property_getter_end - __property_getter_start) % 8 == 0, + "the .property_getter section must hold whole 8-byte objects") + ASSERT((__property_getset_end - __property_getset_start) % 12 == 0, + "the .property_getset section must hold whole 12-byte objects") } diff --git a/ports/nordic/boards/electronut_labs_blip/mpconfigboard.mk b/ports/nordic/boards/electronut_labs_blip/mpconfigboard.mk index 0e3b1b90489..87d3c8c25c5 100644 --- a/ports/nordic/boards/electronut_labs_blip/mpconfigboard.mk +++ b/ports/nordic/boards/electronut_labs_blip/mpconfigboard.mk @@ -10,4 +10,6 @@ CIRCUITPY_BUILD_EXTENSIONS = hex INTERNAL_FLASH_FILESYSTEM = 1 CIRCUITPY_AUDIOIO = 0 CIRCUITPY_DISPLAYIO = 1 +CIRCUITPY_GIFIO = 0 CIRCUITPY_STAGE = 1 +CIRCUITPY_DIGITALINOUT_PROTOCOL = 0 diff --git a/ports/nordic/boards/espruino_banglejs2/board.c b/ports/nordic/boards/espruino_banglejs2/board.c index 16af0269168..8761fa813b1 100644 --- a/ports/nordic/boards/espruino_banglejs2/board.c +++ b/ports/nordic/boards/espruino_banglejs2/board.c @@ -9,7 +9,6 @@ #include "mpconfigboard.h" #include "shared-bindings/busio/SPI.h" -#include "shared-bindings/fourwire/FourWire.h" #include "shared-bindings/framebufferio/FramebufferDisplay.h" #include "shared-bindings/sharpdisplay/SharpMemoryFramebuffer.h" #include "shared-module/displayio/__init__.h" @@ -22,18 +21,15 @@ uint32_t last_down_ticks_ms; void board_init(void) { common_hal_digitalio_digitalinout_construct(&extcomin, &pin_P0_06); common_hal_digitalio_digitalinout_switch_to_output(&extcomin, true, DRIVE_MODE_PUSH_PULL); - common_hal_digitalio_digitalinout_never_reset(&extcomin); common_hal_digitalio_digitalinout_construct(&display_on, &pin_P0_07); common_hal_digitalio_digitalinout_switch_to_output(&display_on, true, DRIVE_MODE_PUSH_PULL); - common_hal_digitalio_digitalinout_never_reset(&display_on); sharpdisplay_framebuffer_obj_t *fb = &allocate_display_bus()->sharpdisplay; fb->base.type = &sharpdisplay_framebuffer_type; busio_spi_obj_t *spi = &fb->inline_bus; common_hal_busio_spi_construct(spi, &pin_P0_26, &pin_P0_27, NULL, false); - common_hal_busio_spi_never_reset(spi); common_hal_sharpdisplay_framebuffer_construct(fb, spi, &pin_P0_05, 500000, 176, 176, true); diff --git a/ports/nordic/boards/feather_bluefruit_sense/mpconfigboard.h b/ports/nordic/boards/feather_bluefruit_sense/mpconfigboard.h index b0aca947c02..82129a59347 100644 --- a/ports/nordic/boards/feather_bluefruit_sense/mpconfigboard.h +++ b/ports/nordic/boards/feather_bluefruit_sense/mpconfigboard.h @@ -35,10 +35,6 @@ #define SPI_FLASH_CS_PIN &pin_P0_20 #endif -#define CIRCUITPY_INTERNAL_NVM_SIZE (4096) - -#define BOARD_FLASH_SIZE (FLASH_SIZE - 0x4000 - CIRCUITPY_INTERNAL_NVM_SIZE) - #define DEFAULT_I2C_BUS_SCL (&pin_P0_11) #define DEFAULT_I2C_BUS_SDA (&pin_P0_12) diff --git a/ports/nordic/boards/hiibot_bluefi/board.c b/ports/nordic/boards/hiibot_bluefi/board.c index 73430d675eb..fe03e94c8ba 100644 --- a/ports/nordic/boards/hiibot_bluefi/board.c +++ b/ports/nordic/boards/hiibot_bluefi/board.c @@ -29,14 +29,13 @@ void board_init(void) { fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_P0_07, &pin_P1_08, NULL, false); // SCK, MOSI, MISO, not half-duplex - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_P0_27, // TFT_DC Command or data - &pin_P0_05, // TFT_CS Chip select - NULL, // no TFT_RST Reset + MP_OBJ_FROM_PTR(&pin_P0_27), // TFT_DC Command or data + MP_OBJ_FROM_PTR(&pin_P0_05), // TFT_CS Chip select + mp_const_none, // no TFT_RST Reset // &pin_P1_14, // TFT_RST Reset 60000000, // Baudrate 0, // Polarity diff --git a/ports/nordic/boards/ikigaisense_vita/mpconfigboard.h b/ports/nordic/boards/ikigaisense_vita/mpconfigboard.h index d78cd3b78d6..8c430b6be68 100644 --- a/ports/nordic/boards/ikigaisense_vita/mpconfigboard.h +++ b/ports/nordic/boards/ikigaisense_vita/mpconfigboard.h @@ -13,10 +13,10 @@ #define MICROPY_HW_LED_STATUS (&pin_P0_27) +// Smaller than the 8 KB default: the internal-flash filesystem leaves +// little room for firmware. #define CIRCUITPY_INTERNAL_NVM_SIZE (4096) -#define BOARD_FLASH_SIZE (FLASH_SIZE - 0x4000 - CIRCUITPY_INTERNAL_NVM_SIZE) - #define BOARD_HAS_CRYSTAL 1 #define DEFAULT_I2C_BUS_SCL (&pin_P0_08) diff --git a/ports/nordic/boards/itsybitsy_nrf52840_express/mpconfigboard.h b/ports/nordic/boards/itsybitsy_nrf52840_express/mpconfigboard.h index e328be1563b..22cabda5666 100644 --- a/ports/nordic/boards/itsybitsy_nrf52840_express/mpconfigboard.h +++ b/ports/nordic/boards/itsybitsy_nrf52840_express/mpconfigboard.h @@ -32,10 +32,6 @@ #define SPI_FLASH_CS_PIN &pin_P0_23 #endif -#define CIRCUITPY_INTERNAL_NVM_SIZE (4096) - -#define BOARD_FLASH_SIZE (FLASH_SIZE - 0x4000 - CIRCUITPY_INTERNAL_NVM_SIZE) - #define BOARD_HAS_CRYSTAL 1 #define DEFAULT_I2C_BUS_SCL (&pin_P0_14) diff --git a/ports/nordic/boards/makerdiary_m60_keyboard/board.c b/ports/nordic/boards/makerdiary_m60_keyboard/board.c index 65595a6bca5..71b2995b472 100644 --- a/ports/nordic/boards/makerdiary_m60_keyboard/board.c +++ b/ports/nordic/boards/makerdiary_m60_keyboard/board.c @@ -19,25 +19,6 @@ static void power_on(void) { nrf_gpio_pin_write(POWER_SWITCH_PIN->number, true); } -static void preserve_and_release_battery_pin(void) { - // Preserve the battery state. The battery is enabled by default in factory bootloader. - // Reset claimed_pins so user can control pin's state in the vm. - // The code below doesn't actually reset the pin's state, but only set the flags. - reset_pin_number(POWER_SWITCH_PIN->number); // clear claimed_pins and never_reset_pins - never_reset_pin_number(POWER_SWITCH_PIN->number); // set never_reset_pins -} - void board_init(void) { - // As of cpy 8.1.0, board_init() runs after reset_ports() on first run. That means - // never_reset_pins won't be set at boot, the battery pin is reset, causing system - // shutdown. - // So if we need to run on battery, we must enable the battery here. power_on(); - preserve_and_release_battery_pin(); } - -void reset_board(void) { - preserve_and_release_battery_pin(); -} - -// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/nordic/boards/makerdiary_nrf52840_m2_devkit/board.c b/ports/nordic/boards/makerdiary_nrf52840_m2_devkit/board.c index 64199b98009..5c2427b8142 100644 --- a/ports/nordic/boards/makerdiary_nrf52840_m2_devkit/board.c +++ b/ports/nordic/boards/makerdiary_nrf52840_m2_devkit/board.c @@ -30,14 +30,13 @@ void board_init(void) { fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_P0_11, &pin_P0_12, NULL, false); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_P0_08, // TFT_DC Command or data - &pin_P0_06, // TFT_CS Chip select - &pin_P1_09, // TFT_RST Reset + MP_OBJ_FROM_PTR(&pin_P0_08), // TFT_DC Command or data + MP_OBJ_FROM_PTR(&pin_P0_06), // TFT_CS Chip select + MP_OBJ_FROM_PTR(&pin_P1_09), // TFT_RST Reset 60000000, // Baudrate 0, // Polarity 0); // Phase diff --git a/ports/nordic/boards/ohs2020_badge/board.c b/ports/nordic/boards/ohs2020_badge/board.c index ea716006cb4..1f64494af5f 100644 --- a/ports/nordic/boards/ohs2020_badge/board.c +++ b/ports/nordic/boards/ohs2020_badge/board.c @@ -29,14 +29,13 @@ void board_init(void) { fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_P0_11, &pin_P0_12, NULL, false); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_P0_08, // TFT_DC Command or data - &pin_P0_14, // TFT_CS Chip select - &pin_P0_13, // TFT_RST Reset + MP_OBJ_FROM_PTR(&pin_P0_08), // TFT_DC Command or data + MP_OBJ_FROM_PTR(&pin_P0_14), // TFT_CS Chip select + MP_OBJ_FROM_PTR(&pin_P0_13), // TFT_RST Reset 60000000, // Baudrate 0, // Polarity 0); // Phase diff --git a/ports/nordic/boards/omnimo_nrf52840/board.c b/ports/nordic/boards/omnimo_nrf52840/board.c new file mode 100644 index 00000000000..b44a1ae51e0 --- /dev/null +++ b/ports/nordic/boards/omnimo_nrf52840/board.c @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2017 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/nordic/boards/omnimo_nrf52840/mpconfigboard.h b/ports/nordic/boards/omnimo_nrf52840/mpconfigboard.h new file mode 100644 index 00000000000..301df3ff9f4 --- /dev/null +++ b/ports/nordic/boards/omnimo_nrf52840/mpconfigboard.h @@ -0,0 +1,48 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2016 Glenn Ruben Bakke +// SPDX-FileCopyrightText: Copyright (c) 2018 Dan Halbert for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "nrfx/hal/nrf_gpio.h" + +#define MICROPY_HW_BOARD_NAME "OMNIMO nRF52840" +#define MICROPY_HW_MCU_NAME "nRF52840" + +#define MICROPY_HW_NEOPIXEL (&pin_P0_16) + +#define CIRCUITPY_STATUS_LED_POWER (&pin_P1_10) + + +#define MICROPY_HW_LED_STATUS (&pin_P1_15) + +#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) +#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 +#endif + +#define BOARD_HAS_CRYSTAL 1 + +#define DEFAULT_I2C_BUS_SCL (&pin_P0_11) +#define DEFAULT_I2C_BUS_SDA (&pin_P0_12) + +#define DEFAULT_SPI_BUS_SCK (&pin_P0_14) +#define DEFAULT_SPI_BUS_MOSI (&pin_P0_13) +#define DEFAULT_SPI_BUS_MISO (&pin_P0_15) + +#define DEFAULT_UART_BUS_RX (&pin_P0_24) +#define DEFAULT_UART_BUS_TX (&pin_P0_25) diff --git a/ports/nordic/boards/omnimo_nrf52840/mpconfigboard.mk b/ports/nordic/boards/omnimo_nrf52840/mpconfigboard.mk new file mode 100644 index 00000000000..e73be61d728 --- /dev/null +++ b/ports/nordic/boards/omnimo_nrf52840/mpconfigboard.mk @@ -0,0 +1,9 @@ +USB_VID = 0x1209 +USB_PID = 0xCECE +USB_PRODUCT = "OMNIMO nRF52840" +USB_MANUFACTURER = "eAFAQ" + +MCU_CHIP = nrf52840 + +QSPI_FLASH_FILESYSTEM = 1 +EXTERNAL_FLASH_DEVICES = "GD25Q16C, W25Q16JVxQ" diff --git a/ports/nordic/boards/omnimo_nrf52840/pins.c b/ports/nordic/boards/omnimo_nrf52840/pins.c new file mode 100644 index 00000000000..8016037a0ae --- /dev/null +++ b/ports/nordic/boards/omnimo_nrf52840/pins.c @@ -0,0 +1,115 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2017 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_P0_04) }, // Feather + { MP_ROM_QSTR(MP_QSTR_PMOD4), MP_ROM_PTR(&pin_P0_04) }, // PMOD + + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_P0_05) }, // Feather + { MP_ROM_QSTR(MP_QSTR_PMOD3), MP_ROM_PTR(&pin_P0_05) }, // PMOD + + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_P0_30) }, // Feather + { MP_ROM_QSTR(MP_QSTR_PMOD2), MP_ROM_PTR(&pin_P0_30) }, // PMOD + + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_P0_28) }, // Feather + { MP_ROM_QSTR(MP_QSTR_PMOD1), MP_ROM_PTR(&pin_P0_28) }, // PMOD + + { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_P0_02) }, // Feather + + { MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_P0_03) }, // Feather + + { MP_ROM_QSTR(MP_QSTR_VOLTAGE_MONITOR), MP_ROM_PTR(&pin_P0_29) }, + { MP_ROM_QSTR(MP_QSTR_A6), MP_ROM_PTR(&pin_P0_29) }, + { MP_ROM_QSTR(MP_QSTR_BATTERY), MP_ROM_PTR(&pin_P0_29) }, + + { MP_ROM_QSTR(MP_QSTR_SWITCH), MP_ROM_PTR(&pin_P1_02) }, + { MP_ROM_QSTR(MP_QSTR_BTN1), MP_ROM_PTR(&pin_P1_02) }, + + { MP_ROM_QSTR(MP_QSTR_BTN2), MP_ROM_PTR(&pin_P1_07) }, + + { 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_D2), MP_ROM_PTR(&pin_P1_09) }, // Feather + + { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_P1_08) }, // Feather + { MP_ROM_QSTR(MP_QSTR_mikroBUS_TX), MP_ROM_PTR(&pin_P1_08) }, // mikroBUS + + + { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_P0_07) }, // Feather + { MP_ROM_QSTR(MP_QSTR_mikroBUS_RX), MP_ROM_PTR(&pin_P0_07) }, // mikroBUS + + { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_P0_26) }, // Feather + { MP_ROM_QSTR(MP_QSTR_mikroBUS_INT), MP_ROM_PTR(&pin_P0_26) }, // mikroBUS + + { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_P0_27) }, // Feather + { MP_ROM_QSTR(MP_QSTR_mikroBUS_PWM), MP_ROM_PTR(&pin_P0_27) }, // mikroBUS + + { MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_P1_14) }, // Feather + { MP_ROM_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_P1_13) }, // Feather + { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_P1_12) }, // Feather + + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_P0_16) }, + + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_P0_14) }, // Feather + + { MP_ROM_QSTR(MP_QSTR_A7), MP_ROM_PTR(&pin_P0_31) }, + { MP_ROM_QSTR(MP_QSTR_mikroBUS_AN), MP_ROM_PTR(&pin_P0_31) }, // mikroBUS + + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_P0_13) }, // Feather + { MP_ROM_QSTR(MP_QSTR_mikroBUS_RST), MP_ROM_PTR(&pin_P0_13) }, // mikroBUS + + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_P0_15) }, // Feather + { MP_ROM_QSTR(MP_QSTR_mikroBUS_CS), MP_ROM_PTR(&pin_P0_15) }, // mikroBUS + + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_P0_25) }, // Feather + { MP_ROM_QSTR(MP_QSTR_mikroBUS_MISO), MP_ROM_PTR(&pin_P0_25) }, // mikroBUS + + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_P0_24) }, // Feather + { MP_ROM_QSTR(MP_QSTR_mikroBUS_SCK), MP_ROM_PTR(&pin_P0_24) }, // mikroBUS + + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_P0_11) }, // Feather + { MP_ROM_QSTR(MP_QSTR_mikroBUS_SCL), MP_ROM_PTR(&pin_P0_11) }, // mikroBUS + + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_P0_12) }, // Feather + { MP_ROM_QSTR(MP_QSTR_mikroBUS_SDA), MP_ROM_PTR(&pin_P0_12) }, // mikroBUS + + { MP_ROM_QSTR(MP_QSTR_PMOD5), MP_ROM_PTR(&pin_P1_11) }, // PMOD + { MP_ROM_QSTR(MP_QSTR_PMOD6), MP_ROM_PTR(&pin_P1_01) }, // PMOD + { MP_ROM_QSTR(MP_QSTR_PMOD7), MP_ROM_PTR(&pin_P1_03) }, // PMOD + { MP_ROM_QSTR(MP_QSTR_PMOD8), MP_ROM_PTR(&pin_P1_05) }, // PMOD + + { MP_ROM_QSTR(MP_QSTR_LED1), MP_ROM_PTR(&pin_P1_10) }, + { MP_ROM_QSTR(MP_QSTR_L), MP_ROM_PTR(&pin_P1_10) }, + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_P1_10) }, + { MP_ROM_QSTR(MP_QSTR_RED_LED), MP_ROM_PTR(&pin_P1_10) }, + { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_P1_10) }, + + { MP_ROM_QSTR(MP_QSTR_LED2), MP_ROM_PTR(&pin_P1_15) }, + { MP_ROM_QSTR(MP_QSTR_BLUE_LED), MP_ROM_PTR(&pin_P1_15) }, + + { MP_ROM_QSTR(MP_QSTR_QWIIC_SCL), MP_ROM_PTR(&pin_P0_06) }, + + { MP_ROM_QSTR(MP_QSTR_QWIIC_SDA), MP_ROM_PTR(&pin_P0_08) }, + + { MP_ROM_QSTR(MP_QSTR_VOUTEN), MP_ROM_PTR(&pin_P1_04) }, + + { MP_ROM_QSTR(MP_QSTR_D43), MP_ROM_PTR(&pin_P1_06) }, + + { 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) }, + + /// For Qwiic + { MP_ROM_QSTR(MP_QSTR_QWIIC), MP_ROM_PTR(&board_i2c_obj) }, + +}; + +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/nordic/boards/pca10100/mpconfigboard.mk b/ports/nordic/boards/pca10100/mpconfigboard.mk index a081a0db479..9997abb8bfe 100644 --- a/ports/nordic/boards/pca10100/mpconfigboard.mk +++ b/ports/nordic/boards/pca10100/mpconfigboard.mk @@ -9,3 +9,5 @@ INTERNAL_FLASH_FILESYSTEM = 1 CIRCUITPY_ONEWIREIO = 0 CIRCUITPY_AUDIOMIXER = 0 +CIRCUITPY_RAINBOWIO = 0 +CIRCUITPY_USB_MIDI = 0 diff --git a/ports/nordic/boards/teenage_engineering_sp1/board.c b/ports/nordic/boards/teenage_engineering_sp1/board.c new file mode 100644 index 00000000000..3cfa5110202 --- /dev/null +++ b/ports/nordic/boards/teenage_engineering_sp1/board.c @@ -0,0 +1,425 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// Early-boot hygiene for the Teenage Engineering SP-1. +// +// Unlike a normal CircuitPython board, this one is entered from a bootloader +// that has already brought hardware up: it starts HFCLK and LFCLK, and leaves +// PWM2, PWM3 and the SAADC enabled. It also starts a watchdog that we cannot +// stop. So the app has to take the machine over from a *running* state rather +// than a reset state, and it has to do so quickly. +// +// The bootloader's watchdog is the reason for the feeds scattered through this +// file: it is running before we are, its configuration is locked, and nothing +// but a reload keeps it from resetting the board. See wdt.h. + +#include "supervisor/board.h" + +#include "shared-bindings/board/__init__.h" +#include "shared-bindings/busio/I2C.h" + +#include "background.h" +#include "board.h" +#include "common-hal/microcontroller/Pin.h" +#include "flash_protect.h" +#include "peripherals/nrf/pins.h" +#include "power_off.h" +#include "py/misc.h" +#include "supervisor/shared/safe_mode.h" +#include "shared-module/emmcio/__init__.h" +#include "wdt.h" +#include "nrfx/drivers/include/nrfx_rtc.h" +#include "nrfx/hal/nrf_gpio.h" + +#define PIN_EMMC_RESET (DEFAULT_EMMC_RESET->number) // active low +#define PIN_EMMC_VCCQ_EN (DEFAULT_EMMC_VCCQ->number) // eMMC I/O rail + +// Pins this file drives directly. +#define PIN_OSC_EN NRF_GPIO_PIN_MAP(0, 13) // 3.072 MHz oscillator +#define PIN_TAS_RESET NRF_GPIO_PIN_MAP(0, 9) // TAS2505, active low +#define PIN_CS42_RESET NRF_GPIO_PIN_MAP(0, 15) // CS42L42, active low +#define PIN_BT_RESET NRF_GPIO_PIN_MAP(0, 10) // CYBT-353027-02, active low +#define PIN_CONTROL_RAIL NRF_GPIO_PIN_MAP(1, 10) // feeds faders + ladders +#define PIN_FUNCTION_BUTTON NRF_GPIO_PIN_MAP(0, 27) // active low, only GPIO button +#define PIN_CHARGE_ENABLE NRF_GPIO_PIN_MAP(0, 21) // BQ24232, active low +#define PIN_I2C_SCL NRF_GPIO_PIN_MAP(1, 11) // shared by both codecs +#define PIN_I2C_SDA NRF_GPIO_PIN_MAP(1, 7) + +// Both LED rows, active high. PIN_LED_HEARTBEAT is the first track LED, which +// is also MICROPY_HW_LED_STATUS and BOARD_POWER_OFF_CONFIRM_LED_PIN +#define PIN_LED_HEARTBEAT NRF_GPIO_PIN_MAP(0, 29) +static const uint8_t led_pins[] = { + NRF_GPIO_PIN_MAP(1, 13), NRF_GPIO_PIN_MAP(0, 0), // playback row (side) + NRF_GPIO_PIN_MAP(1, 12), NRF_GPIO_PIN_MAP(0, 1), + PIN_LED_HEARTBEAT, NRF_GPIO_PIN_MAP(0, 26), // track row (front) + NRF_GPIO_PIN_MAP(1, 15), NRF_GPIO_PIN_MAP(1, 14), +}; + +// Whether the boot up blink heartbeat still owns PIN_LED_HEARTBEAT. +static bool heartbeat_lit; + +// The bootloader's watchdog is fed from board_background_task(), so the CPU +// must not stay in WFI for longer than the bootloader will wait. The port owns +// RTC2 and this board builds no SoftDevice (which would own RTC0), so RTC1 is +// free to hand the main loop its turn back on a fixed period. +// +// Waking is the whole job. The feed itself deliberately stays in the main loop, +// so that a wedge there still becomes a reset. +static const nrfx_rtc_t wake_rtc = NRFX_RTC_INSTANCE(1); +#define WAKE_RTC_CHANNEL (0) +// Run the counter straight off the LFCLK, as the port's own RTC does. +#define WAKE_RTC_FREQUENCY_HZ (32768) +// How long the CPU may stay in WFI before the main loop must get another look +// in. +#define WAKE_RTC_PERIOD_TICKS (WAKE_RTC_FREQUENCY_HZ) + +static void arm_wake_rtc(void) { + nrfx_rtc_cc_set(&wake_rtc, WAKE_RTC_CHANNEL, + nrfx_rtc_counter_get(&wake_rtc) + WAKE_RTC_PERIOD_TICKS, true); +} + +static void wake_rtc_handler(nrfx_rtc_int_type_t int_type) { + (void)int_type; + arm_wake_rtc(); +} + +// Bounded wait for a peripheral to acknowledge a STOP. +#define STOP_TIMEOUT_ITERATIONS (20000) + +static void wait_for_event(volatile uint32_t *event) { + for (uint32_t i = 0; i < STOP_TIMEOUT_ITERATIONS && *event == 0; i++) { + __NOP(); + } + *event = 0; + // Read back to flush the write buffer, per the nRF52 errata guidance for + // clearing events. + (void)*event; +} + +static void stop_pwm(NRF_PWM_Type *pwm) { + if (pwm->ENABLE == 0) { + return; + } + pwm->EVENTS_STOPPED = 0; + pwm->TASKS_STOP = 1; + wait_for_event(&pwm->EVENTS_STOPPED); + pwm->INTENCLR = 0xFFFFFFFF; + pwm->ENABLE = 0; +} + +static void apply_all_pin_defaults(void); + +void board_early_init(void) { + // Feed the bootloader's watchdog before anything else. This is the first + // CircuitPython code to run on the board: port_init() calls it before it + // touches a peripheral. + bootloader_wdt_feed(); + + // Lock the bootloader out of NVMC's reach for the rest of this boot. First, + // because from here on every line of CircuitPython that runs is one more + // thing that could get it wrong, and the bootloader is this board's only + // way back in. See flash_protect.h. + board_flash_protect(); + + // A watchdog reset can only mean the main loop stopped, and on this board + // that is worth safe mode with or without a host attached: there is no + // reset pin and no removable battery, so re-running the same wedging + // `code.py` is the one thing that can make the device unrecoverable. + // port_init() asks for safe mode itself when USB is attached; this covers + // the battery case. RESETREAS is still untouched here -- port_init() reads + // and clears it after we return -- and the request is picked up by + // wait_for_safe_mode_reset() later in this same boot, not after a reset. + if ((NRF_POWER->RESETREAS & POWER_RESETREAS_DOG_Msk) != 0 && + (NRF_POWER->USBREGSTATUS & POWER_USBREGSTATUS_VBUSDETECT_Msk) == 0) { + safe_mode_on_next_reset(SAFE_MODE_WATCHDOG); + } + + // First light boot up status blink. + // + // never lights the bootloader did not jump here, or we died in + // the reset handler / SystemInit + // lights and stays on we are running, but did not reach board_init(): + // suspect the filesystem format or something + // before the workflow starts + // lights, then goes out board_init() reached; USB is next, so from here + // on the absence of a tty is a USB problem + // + nrf_gpio_cfg_output(PIN_LED_HEARTBEAT); + nrf_gpio_pin_set(PIN_LED_HEARTBEAT); + heartbeat_lit = true; + + for (size_t i = 0; i < 8; i++) { + NVIC->ICER[i] = 0xFFFFFFFF; + NVIC->ICPR[i] = 0xFFFFFFFF; + } + __DSB(); + __ISB(); + + // Break any PPI wiring before stopping peripherals, so nothing we stop can + // be restarted by a leftover event->task connection. + NRF_PPI->CHENCLR = 0xFFFFFFFF; + + // The bootloader drives the LEDs with PWM2 and PWM3. PWM0/PWM1 are stopped + // too so that pwmio starts from a known state. + stop_pwm(NRF_PWM0); + stop_pwm(NRF_PWM1); + stop_pwm(NRF_PWM2); + stop_pwm(NRF_PWM3); + + // The bootloader reads the button ladders with the SAADC and leaves it + // enabled, so clear it. + if (NRF_SAADC->ENABLE != 0) { + NRF_SAADC->EVENTS_STOPPED = 0; + NRF_SAADC->TASKS_STOP = 1; + wait_for_event(&NRF_SAADC->EVENTS_STOPPED); + NRF_SAADC->INTENCLR = 0xFFFFFFFF; + NRF_SAADC->EVENTS_END = 0; + NRF_SAADC->EVENTS_STARTED = 0; + NRF_SAADC->EVENTS_CALIBRATEDONE = 0; + NRF_SAADC->ENABLE = 0; + } + + // Last, because the blanket NVIC clear above would undo it: the periodic + // wake-up that keeps the main loop feeding the watchdog. LFCLK is not + // running yet, so the counter starts when port_init() starts it, a few + // instructions from here. + static const nrfx_rtc_config_t wake_rtc_config = { + .prescaler = RTC_FREQ_TO_PRESCALER(WAKE_RTC_FREQUENCY_HZ), + .reliable = 0, + .tick_latency = 0, + .interrupt_priority = 6, + }; + nrfx_rtc_init(&wake_rtc, &wake_rtc_config, wake_rtc_handler); + arm_wake_rtc(); + nrfx_rtc_enable(&wake_rtc); + + // Apply the board's resting state here, so nothing floats while we + // wait for code.py. The heartbeat LED is excluded by the guard in + // board_reset_pin_number() because the blink is still lit. + apply_all_pin_defaults(); +} + +// Pins that must not float. reset_pin_number() asks the board for each pin, +// so this configuration is re-applied after every reset rather than the pin +// being left in its default (disconnected) state. +// +// None of these are claimed, so Python can still claim them. This +// only makes the resting state between runs a defined, safe one. +static const uint8_t default_low_pins[] = { + // 3.072 MHz oscillator enable. Held low: it draws current straight through + // SYSTEM_OFF, so a floating pin here would drain battery. + PIN_OSC_EN, + + // Codecs and the Bluetooth module held in reset (all active low) so that + // nothing downstream of us starts making noise or driving a shared bus on + // its own. P0.09/P0.10 are the NFC pins; UICR NFCPINS reads with PROTECT + // already cleared on this board, so they are usable as GPIO. + PIN_TAS_RESET, + PIN_CS42_RESET, + PIN_BT_RESET, + + // Rail feeding the faders and both button ladders. Off unless something is + // actually reading them. + PIN_CONTROL_RAIL, + + // BQ24232 charge enable, active low: drive it low so a plugged-in device + // charges. P1.00 (CHARGE_ISET) is deliberately left untouched. It is the + // charge-current programming node (ICHG = 870 AΩ / RISET) and doubles as + // the current monitor. + PIN_CHARGE_ENABLE, +}; + +// Returns false for a pin this board has no opinion about. +static bool apply_pin_default(uint8_t pin_number) { + // Function button: the only GPIO button, active low, and the only wake + // source out of SYSTEM_OFF. Keep it readable at all times, the + // supervisor's power-off gesture depends on it. + if (pin_number == PIN_FUNCTION_BUTTON) { + nrf_gpio_cfg_input(PIN_FUNCTION_BUTTON, NRF_GPIO_PIN_PULLUP); + return true; + } + + // Both LED rows, off. + for (size_t i = 0; i < MP_ARRAY_SIZE(led_pins); i++) { + if (led_pins[i] == pin_number) { + nrf_gpio_cfg_output(pin_number); + nrf_gpio_pin_clear(pin_number); + return true; + } + } + + // eMMC held in reset with its VCCQ rail off. The contents of the chip are + // unaffected; this only keeps the rail from floating. The exception is a + // card the supervisor has automounted: it is a live filesystem between + // runs, so leave its reset and rail exactly as the driver left them. + if (pin_number == PIN_EMMC_RESET || pin_number == PIN_EMMC_VCCQ_EN) { + if (!emmcio_is_automounted()) { + nrf_gpio_cfg_output(pin_number); + nrf_gpio_pin_clear(pin_number); + } + return true; + } + + for (size_t i = 0; i < MP_ARRAY_SIZE(default_low_pins); i++) { + if (default_low_pins[i] == pin_number) { + nrf_gpio_cfg_output(pin_number); + nrf_gpio_pin_clear(pin_number); + return true; + } + } + + return false; +} + +// Put every pin this board has an opinion about into its resting state at once. +// Goes through board_reset_pin_number(), not apply_pin_default() directly, so +// the boot heartbeat LED is left alone while it is lit. +static void apply_all_pin_defaults(void) { + board_reset_pin_number(PIN_FUNCTION_BUTTON); + board_reset_pin_number(PIN_EMMC_RESET); + board_reset_pin_number(PIN_EMMC_VCCQ_EN); + for (size_t i = 0; i < MP_ARRAY_SIZE(led_pins); i++) { + board_reset_pin_number(led_pins[i]); + } + for (size_t i = 0; i < MP_ARRAY_SIZE(default_low_pins); i++) { + board_reset_pin_number(default_low_pins[i]); + } +} + +bool board_reset_pin_number(uint8_t pin_number) { + // A reset of this pin while the heartbeat is lit must not disturb it; + // board_init() hands the pin back. + if (heartbeat_lit && pin_number == PIN_LED_HEARTBEAT) { + return true; + } + + return apply_pin_default(pin_number); +} + +// Called once at start up, after the filesystem is mounted and immediately +// before the USB workflow starts. Where we end the heartbeat status blink. +void board_init(void) { + heartbeat_lit = false; + nrf_gpio_pin_clear(PIN_LED_HEARTBEAT); +} + +void board_background_task(void) { + bootloader_wdt_feed(); + + #ifdef BOARD_POWER_OFF_BUTTON_PIN + // Never returns if the hold completes. + power_off_tick(); + #endif +} + +// -- muting the codecs on the way out -------------------------------------- +// +// Dropping the reset lines and the oscillator (apply_all_pin_defaults()) is +// enough to make the board quiet and to save the battery, but it cuts both +// codecs off mid-signal: the CS42L42 loses its clock and the TAS2505's class-D +// driver loses its reset with whatever was on the output still on it. +// +// Bit-banged rather than driven through TWIM. + +#define I2C_FREQUENCY (100000) +#define I2C_TIMEOUT_MS (255) + +static busio_i2c_obj_t codec_i2c; + +// two-byte write +static bool i2c_write2(uint8_t address, uint8_t first, uint8_t second) { + const uint8_t data[2] = { first, second }; + return common_hal_busio_i2c_write(&codec_i2c, address, data, sizeof(data)) == 0; +} + +// Register addresses +#define PAGE_SELECT_REG (0x00) // register 0 selects the page, on both + +#define CS42L42_ADDRESS (0x48) +#define CS_HP_CTL_PAGE (0x20) // CS_HP_CTL = 0x2001, page = high byte +#define CS_HP_CTL_REG (0x01) +#define CS_HP_MUTE (0x0D) + +#define TAS2505_ADDRESS (0x18) +#define TAS_SW_RESET (0x01) // page 0 +#define TAS_DAC_MUTE (0x40) // page 0 +#define TAS_MUTED (0x0C) +#define TAS_SPK_POWER (0x2D) // page 1 + +// Mute the CS42L42, then mute the TAS2505, power its class-D driver down and +// soft-reset it. +static void quiesce_codecs(void) { + bootloader_wdt_feed(); + + #if CIRCUITPY_BOARD_I2C + + busio_i2c_obj_t *shared = common_hal_board_get_i2c(0); + if (shared != NULL) { + common_hal_busio_i2c_unlock(shared); + common_hal_busio_i2c_deinit(shared); + } + #endif + + if (!pin_number_is_free(PIN_I2C_SCL) || !pin_number_is_free(PIN_I2C_SDA)) { + return; + } + + codec_i2c.base.type = &busio_i2c_type; + common_hal_busio_i2c_construct(&codec_i2c, DEFAULT_I2C_BUS_SCL, + DEFAULT_I2C_BUS_SDA, I2C_FREQUENCY, I2C_TIMEOUT_MS); + + if (i2c_write2(CS42L42_ADDRESS, PAGE_SELECT_REG, CS_HP_CTL_PAGE)) { + i2c_write2(CS42L42_ADDRESS, CS_HP_CTL_REG, CS_HP_MUTE); + } + bootloader_wdt_feed(); + + if (i2c_write2(TAS2505_ADDRESS, PAGE_SELECT_REG, 0x00)) { + i2c_write2(TAS2505_ADDRESS, TAS_DAC_MUTE, TAS_MUTED); + bootloader_wdt_feed(); + if (i2c_write2(TAS2505_ADDRESS, PAGE_SELECT_REG, 0x01)) { + i2c_write2(TAS2505_ADDRESS, TAS_SPK_POWER, 0x00); + } + bootloader_wdt_feed(); + // Back to page 0 for the software reset + if (i2c_write2(TAS2505_ADDRESS, PAGE_SELECT_REG, 0x00)) { + i2c_write2(TAS2505_ADDRESS, TAS_SW_RESET, 0x01); + } + } + + common_hal_busio_i2c_deinit(&codec_i2c); + bootloader_wdt_feed(); +} + +void reset_board(void) { + quiesce_codecs(); +} + +// The board half of the power-off sequence +// Runs with the Function button still held, before the wake is armed. +void board_power_off_prepare(void) { + quiesce_codecs(); + + // Codecs into reset, CS42L42 first: it drives the I2S frames, so + // stopping it stops the bus the TAS2505 is listening to. + nrf_gpio_cfg_output(PIN_CS42_RESET); + nrf_gpio_pin_clear(PIN_CS42_RESET); + nrf_gpio_cfg_output(PIN_TAS_RESET); + nrf_gpio_pin_clear(PIN_TAS_RESET); + + // eMMC I/O rail, before the oscillator, so nothing is left half-powered + // against a clock that has stopped. + nrf_gpio_cfg_output(PIN_EMMC_RESET); + nrf_gpio_pin_clear(PIN_EMMC_RESET); + nrf_gpio_cfg_output(PIN_EMMC_VCCQ_EN); + nrf_gpio_pin_clear(PIN_EMMC_VCCQ_EN); + + // 3.072 MHz oscillator + nrf_gpio_cfg_output(PIN_OSC_EN); + nrf_gpio_pin_clear(PIN_OSC_EN); + + // Everything else, LEDs included. + apply_all_pin_defaults(); +} diff --git a/ports/nordic/boards/teenage_engineering_sp1/flash_protect.c b/ports/nordic/boards/teenage_engineering_sp1/flash_protect.c new file mode 100644 index 00000000000..db87935dbb9 --- /dev/null +++ b/ports/nordic/boards/teenage_engineering_sp1/flash_protect.c @@ -0,0 +1,52 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "flash_protect.h" + +#include "py/mpconfig.h" + +#include "nrfx/hal/nrf_acl.h" + +// protect the MBR at 0x0 and the bootloader above it, up to the +// address the bootloader jumps to. +#define PROTECT_START_ADDR (MBR_START_ADDR) +#define PROTECT_SIZE (ISR_START_ADDR - MBR_START_ADDR) + +#if PROTECT_SIZE == 0 +#error The bootloader for this board is not in low flash; nothing for the ACL to protect. +#endif + +#if PROTECT_SIZE > NRF_ACL_REGION_SIZE_MAX +#error The bootloader region is larger than a single ACL region can cover. +#endif + +#if (PROTECT_START_ADDR % FLASH_PAGE_SIZE) != 0 || (PROTECT_SIZE % FLASH_PAGE_SIZE) != 0 +#error ACL regions must start and end on a flash page boundary. +#endif + +void board_flash_protect(void) { + for (uint32_t region = 0; region < ACL_REGIONS_COUNT; region++) { + // A region's registers only take their first write after a reset, so a + // region the bootloader has already configured has to be left alone. + if (nrf_acl_region_size_get(NRF_ACL, region) != 0 || + nrf_acl_region_perm_get(NRF_ACL, region) != 0) { + continue; + } + + // Read stays enabled. The MBR's vector table is read out of this + // region on every interrupt, and the bootloader is executed in place + // out of it on the way back in. + nrf_acl_region_set(NRF_ACL, region, PROTECT_START_ADDR, PROTECT_SIZE, + NRF_ACL_PERM_READ_NO_WRITE); + + // Read back rather than trust the write: an already-claimed region + // would have ignored it. + if (nrf_acl_region_address_get(NRF_ACL, region) == PROTECT_START_ADDR && + nrf_acl_region_size_get(NRF_ACL, region) == PROTECT_SIZE) { + return; + } + } +} diff --git a/ports/nordic/boards/teenage_engineering_sp1/flash_protect.h b/ports/nordic/boards/teenage_engineering_sp1/flash_protect.h new file mode 100644 index 00000000000..4a21bfb2758 --- /dev/null +++ b/ports/nordic/boards/teenage_engineering_sp1/flash_protect.h @@ -0,0 +1,11 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Hardware write-protection for this board's bootloader. + +void board_flash_protect(void); diff --git a/ports/nordic/boards/teenage_engineering_sp1/mpconfigboard.h b/ports/nordic/boards/teenage_engineering_sp1/mpconfigboard.h new file mode 100644 index 00000000000..2365d724186 --- /dev/null +++ b/ports/nordic/boards/teenage_engineering_sp1/mpconfigboard.h @@ -0,0 +1,81 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "nrfx/hal/nrf_gpio.h" + +#define MICROPY_HW_BOARD_NAME "Teenage Engineering SP-1" +#define MICROPY_HW_MCU_NAME "nRF52840" + +// Flash map. The bootloader owns 0x00000-0x20000 and jumps to 0x20000, so +// the vector table goes there. +// +// There is no bootloader in *high* flash either, so both bootloader sizes are +// zero and BOOTLOADER_START_ADDR collapses onto the bootloader settings page +// at 0xFF000. That page belongs to the bootloader and must never be +// written. +// +// 0x00000-0x20000 bootloader (never touched) +// 0x20000-0x21000 ISR/vector table +// 0x21000-0xBD000 firmware (624 KiB) +// 0xBD000-0xBF000 microcontroller.nvm (8 KiB) +// 0xBF000-0xFF000 CIRCUITPY internal-flash FAT (256 KiB) +// 0xFF000-0x100000 bootloader settings page (RESERVED) +#define ISR_START_ADDR (0x20000) +#define BOOTLOADER_SIZE (0) +#define BOOTLOADER_MBR_SIZE (0) + +// No BLE on this board, so nothing to store for bonding. +#define CIRCUITPY_BLE_CONFIG_SIZE (0) + +// No 32.768 kHz crystal: P0.00 and P0.01 are playback LEDs. Use the RC +// oscillator for LFCLK. +#define BOARD_HAS_32KHZ_XTAL (0) + +// Power off. There is no reset pin, no power switch and no removable battery, +// so SYSTEM_OFF is the only "off" this device has. Waking from off is one +// of only two routes back to the bootloader. P0.27 (Function) is the only +// GPIO button and the only wake source; it is a plain switch to ground. +#define BOARD_POWER_OFF_BUTTON_PIN NRF_GPIO_PIN_MAP(0, 27) + +// The bootloader's DFU magic. The gate at 0x6b2 is 16 bits wide and +// split across both retention registers, +// +// GPREGRET | (GPREGRET2 << 8) == 0x7EB3 +// +// +// This bootloader has no separate UF2/OTA and serial-DFU requests. There is +// one gate, so both magics are the same pair and, reset_to_bootloader() and +// microcontroller.on_next_reset(RunMode.BOOTLOADER) both land in boot mode. +#define BOOTLOADER_DFU_MAGIC (0xB3) +#define BOOTLOADER_DFU_MAGIC2 (0x7E) +#define BOOTLOADER_UF2_MAGIC (0xB3) +#define BOOTLOADER_UF2_MAGIC2 (0x7E) + +// No SD card LUN. There is no card slot on this device. +#define CIRCUITPY_SDCARD_USB (0) + +// The 4 GB eMMC +#define DEFAULT_EMMC_CLOCK (&pin_P0_06) +#define DEFAULT_EMMC_COMMAND (&pin_P0_08) +#define DEFAULT_EMMC_DATA (&pin_P0_07) +#define DEFAULT_EMMC_RESET (&pin_P1_08) +#define DEFAULT_EMMC_VCCQ (&pin_P0_14) + +// TWIM to the CS42L42 (0x48) and TAS2505 (0x18). +#define DEFAULT_I2C_BUS_SCL (&pin_P1_11) +#define DEFAULT_I2C_BUS_SDA (&pin_P1_07) + +// The CDC REPL is normally the only place status is visible. Borrow the first +// track LED for the supervisor status LED so that safe mode is legible on the +// device itself. It is claimed only while the supervisor is showing status and +// is released before user code runs, so board.LED_TRACK1 stays usable. +#define MICROPY_HW_LED_STATUS (&pin_P0_29) + +// Blink that same LED once, ~200 ms, the moment the power-off hold completes. +// The gesture is otherwise silent. +#define BOARD_POWER_OFF_CONFIRM_LED_PIN NRF_GPIO_PIN_MAP(0, 29) diff --git a/ports/nordic/boards/teenage_engineering_sp1/mpconfigboard.mk b/ports/nordic/boards/teenage_engineering_sp1/mpconfigboard.mk new file mode 100644 index 00000000000..5f505494006 --- /dev/null +++ b/ports/nordic/boards/teenage_engineering_sp1/mpconfigboard.mk @@ -0,0 +1,62 @@ +USB_VID = 0x239A +USB_PID = 0x817A +USB_PRODUCT = "SP-1 (CircuitPython)" +USB_MANUFACTURER = "Teenage Engineering" + +MCU_CHIP = nrf52840 + +# SystemInit() burns UICR PSELRESET[0..1] = 18 and resets whenever it finds +# them unprogrammed, which is the case on this board. Opt out of it +$(BUILD)/nrfx/mdk/system_nrf52840.o: CFLAGS += -UCONFIG_GPIO_AS_PINRESET + +# No BLE. A SoftDevice would have to live at 0x1000, which is inside this +# board's bootloader, and the radio has no antenna. +CIRCUITPY_BLEIO_NATIVE = 0 +CIRCUITPY_BLE_FILE_SERVICE = 0 +CIRCUITPY_BLE_SERIAL_SERVICE = 0 + +# CIRCUITPY is in internal flash; there is no external flash chip. +INTERNAL_FLASH_FILESYSTEM = 1 + +# No UF2 bootloader on this device. +CIRCUITPY_BUILD_EXTENSIONS = bin,hex + +# displayio off no display. +CIRCUITPY_DISPLAYIO = 0 +CIRCUITPY_FRAMEBUFFERIO = 0 +CIRCUITPY_RGBMATRIX = 0 +CIRCUITPY_SHARPDISPLAY = 0 +CIRCUITPY_IS31FL3741 = 0 +CIRCUITPY_VECTORIO = 0 + +# The watchdog is started by the bootloader before our first instruction and +# its config registers are locked. +CIRCUITPY_WATCHDOG = 0 + +# alarm's idle paths need a WDT-feed audit before they are safe here. +CIRCUITPY_ALARM = 0 + +# Audio +CIRCUITPY_AUDIOPWMIO = 0 +CIRCUITPY_SYNTHIO = 1 +CIRCUITPY_AUDIOEFFECTS = 1 +CIRCUITPY_AUDIOMP3 = 1 + +# Hold-to-power-off, opted into by BOARD_POWER_OFF_BUTTON_PIN in +# mpconfigboard.h. +SRC_C += boards/$(BOARD)/power_off.c + +# ACL write-protection for the MBR and the bootloader, which this board's +# bootloader does not set up for itself. +SRC_C += boards/$(BOARD)/flash_protect.c + +# The soldered-down eMMC, and the supervisor mount that puts it on /sd and on +# USB as a second drive. +CIRCUITPY_EMMCIO = 1 +CIRCUITPY_EMMC_USB = 1 + +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_Register +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_CS42L42 +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_TAS2505 + +CIRCUITPY_REQUIRE_I2C_PULLUPS = 0 diff --git a/ports/nordic/boards/teenage_engineering_sp1/pins.c b/ports/nordic/boards/teenage_engineering_sp1/pins.c new file mode 100644 index 00000000000..66897f7514d --- /dev/null +++ b/ports/nordic/boards/teenage_engineering_sp1/pins.c @@ -0,0 +1,91 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// Pin map from Tim Knapen's reverse-engineering of the Teenage Engineering SP-1 +// https://github.com/timknapen/SP-1-dev/wiki + +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + // Four track faders, in physical left-to-right order. + { MP_ROM_QSTR(MP_QSTR_FADER1), MP_ROM_PTR(&pin_P0_05) }, + { MP_ROM_QSTR(MP_QSTR_FADER2), MP_ROM_PTR(&pin_P0_30) }, + { MP_ROM_QSTR(MP_QSTR_FADER3), MP_ROM_PTR(&pin_P0_04) }, + { MP_ROM_QSTR(MP_QSTR_FADER4), MP_ROM_PTR(&pin_P0_31) }, + + // Two resistor-ladder button rows, read as analog voltages. Both need + // LADDER_POWER driven high to read anything; the faders need it too. + // + // Rungs in ascending voltage: + // LADDER1: TRACK1, TRACK2, TRACK3, TRACK4, PLAY + // LADDER2: ROCKER-, VOL-, ROCKER+, VOL+ + // Both rows are the same resistor network; LADDER2 is LADDER1 with the + // lowest rung unpopulated, so one threshold table serves both. + // + // "ROCKER" is the left-side rocker switch + { MP_ROM_QSTR(MP_QSTR_LADDER1), MP_ROM_PTR(&pin_P0_02) }, + { MP_ROM_QSTR(MP_QSTR_LADDER2), MP_ROM_PTR(&pin_P0_03) }, + { MP_ROM_QSTR(MP_QSTR_LADDER_POWER), MP_ROM_PTR(&pin_P1_10) }, + + // The Function button ("••") is the only GPIO button, active low with a + // pull-up, and the only wake source out of SYSTEM_OFF. + { MP_ROM_QSTR(MP_QSTR_BUTTON), MP_ROM_PTR(&pin_P0_27) }, + + // Playback LED row on the side of the device, active high. + { MP_ROM_QSTR(MP_QSTR_LED_PLAY1), MP_ROM_PTR(&pin_P1_13) }, + { MP_ROM_QSTR(MP_QSTR_LED_PLAY2), MP_ROM_PTR(&pin_P0_00) }, + { MP_ROM_QSTR(MP_QSTR_LED_PLAY3), MP_ROM_PTR(&pin_P1_12) }, + { MP_ROM_QSTR(MP_QSTR_LED_PLAY4), MP_ROM_PTR(&pin_P0_01) }, + + // Track LED row above the track buttons, active high. + { MP_ROM_QSTR(MP_QSTR_LED_TRACK1), MP_ROM_PTR(&pin_P0_29) }, + { MP_ROM_QSTR(MP_QSTR_LED_TRACK2), MP_ROM_PTR(&pin_P0_26) }, + { MP_ROM_QSTR(MP_QSTR_LED_TRACK3), MP_ROM_PTR(&pin_P1_15) }, + { MP_ROM_QSTR(MP_QSTR_LED_TRACK4), MP_ROM_PTR(&pin_P1_14) }, + + // I2C to both codecs: CS42L42 headphone amp at 0x48, TAS2505 speaker amp + // at 0x18. + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_P1_11) }, + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_P1_07) }, + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, + + // Codec resets, both active low. + { MP_ROM_QSTR(MP_QSTR_TAS_RESET), MP_ROM_PTR(&pin_P0_09) }, + { MP_ROM_QSTR(MP_QSTR_CS42_RESET), MP_ROM_PTR(&pin_P0_15) }, + + // I2S + { MP_ROM_QSTR(MP_QSTR_I2S_DOUT), MP_ROM_PTR(&pin_P1_09) }, + { MP_ROM_QSTR(MP_QSTR_I2S_LRCLK), MP_ROM_PTR(&pin_P0_11) }, + { MP_ROM_QSTR(MP_QSTR_I2S_WORD_SELECT), MP_OBJ_FROM_PTR(&pin_P0_11) }, + { MP_ROM_QSTR(MP_QSTR_I2S_BCLK), MP_ROM_PTR(&pin_P0_12) }, + { MP_ROM_QSTR(MP_QSTR_I2S_BIT_CLOCK), MP_OBJ_FROM_PTR(&pin_P0_12) }, + { MP_ROM_QSTR(MP_QSTR_OSC_EN), MP_ROM_PTR(&pin_P0_13) }, + + // 4 GB eMMC + { MP_ROM_QSTR(MP_QSTR_EMMC_CLK), MP_ROM_PTR(&pin_P0_06) }, + { MP_ROM_QSTR(MP_QSTR_EMMC_DAT0), MP_ROM_PTR(&pin_P0_07) }, + { MP_ROM_QSTR(MP_QSTR_EMMC_CMD), MP_ROM_PTR(&pin_P0_08) }, + { MP_ROM_QSTR(MP_QSTR_EMMC_RESET), MP_ROM_PTR(&pin_P1_08) }, + { MP_ROM_QSTR(MP_QSTR_EMMC_VCCQ), MP_ROM_PTR(&pin_P0_14) }, + + // BQ24232 charger. CHARGE_ENABLE and the two status lines are active low. + { MP_ROM_QSTR(MP_QSTR_CHARGE_ISET), MP_ROM_PTR(&pin_P1_00) }, + { MP_ROM_QSTR(MP_QSTR_CHARGE_ENABLE), MP_ROM_PTR(&pin_P0_21) }, + { MP_ROM_QSTR(MP_QSTR_CHARGE_STATUS), MP_ROM_PTR(&pin_P0_22) }, + { MP_ROM_QSTR(MP_QSTR_POWER_GOOD), MP_ROM_PTR(&pin_P0_24) }, + + // Battery sense, AIN4, through a divider. + { MP_ROM_QSTR(MP_QSTR_VBATT), MP_ROM_PTR(&pin_P0_28) }, + { MP_ROM_QSTR(MP_QSTR_BATTERY), MP_ROM_PTR(&pin_P0_28) }, + { MP_ROM_QSTR(MP_QSTR_VOLTAGE_MONITOR), MP_ROM_PTR(&pin_P0_28) }, + + // CYBT-353027-02 Bluetooth module reset, active low + { MP_ROM_QSTR(MP_QSTR_BT_RESET), MP_ROM_PTR(&pin_P0_10) }, +}; + +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/nordic/boards/teenage_engineering_sp1/power_off.c b/ports/nordic/boards/teenage_engineering_sp1/power_off.c new file mode 100644 index 00000000000..dd20d4293e4 --- /dev/null +++ b/ports/nordic/boards/teenage_engineering_sp1/power_off.c @@ -0,0 +1,201 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "power_off.h" + +#ifdef BOARD_POWER_OFF_BUTTON_PIN + +#include "py/misc.h" + +#include "supervisor/filesystem.h" +#include "supervisor/flash.h" + +#include "wdt.h" +#include "nrfx/hal/nrf_gpio.h" +#include "nrfx/hal/nrf_power.h" + +#ifndef BOARD_POWER_OFF_HOLD_SECONDS +#define BOARD_POWER_OFF_HOLD_SECONDS (3) +#endif + +// Timings in RTC subticks (32.768 kHz). The counter is 24 bits, so every +// comparison is masked; it wraps every 512s, longer than needed. +#define RTC_COUNTER_MASK (0xFFFFFF) +#define POLL_INTERVAL_SUBTICKS (1024) // ~31 ms +#define POWER_OFF_HOLD_SUBTICKS (BOARD_POWER_OFF_HOLD_SECONDS * 32768) +#define RELEASE_DEBOUNCE_SUBTICKS (1638) // ~50 ms + +// How long the gesture will wait for a filesystem that is being built +#ifndef BOARD_POWER_OFF_FILESYSTEM_GRACE_SECONDS +#define BOARD_POWER_OFF_FILESYSTEM_GRACE_SECONDS (30) +#endif +#define FILESYSTEM_GRACE_SUBTICKS (BOARD_POWER_OFF_FILESYSTEM_GRACE_SECONDS * 32768) + +// The RTC that port.c runs the tick from, read straight out of its counter. +#define POWER_OFF_RTC (NRF_RTC2) + +// Do-nothing default; a board with hardware to quiesce overrides this. +MP_WEAK void board_power_off_prepare(void) { +} + +#ifdef BOARD_POWER_OFF_CONFIRM_LED_PIN + +#ifndef BOARD_POWER_OFF_CONFIRM_LED_MS +#define BOARD_POWER_OFF_CONFIRM_LED_MS (200) +#endif +#define CONFIRM_BLINK_SUBTICKS ((BOARD_POWER_OFF_CONFIRM_LED_MS) * 32768 / 1000) + +// One flash to say the gesture landed. +static void power_off_confirm_blink(void) { + nrf_gpio_cfg_output(BOARD_POWER_OFF_CONFIRM_LED_PIN); + nrf_gpio_pin_set(BOARD_POWER_OFF_CONFIRM_LED_PIN); + // Busy-wait on the same RTC the release loop uses, feeding the watchdog: + // 200 ms is comfortably longer than a bootloader-armed dog's patience. + uint32_t started = POWER_OFF_RTC->COUNTER; + while (((POWER_OFF_RTC->COUNTER - started) & RTC_COUNTER_MASK) < CONFIRM_BLINK_SUBTICKS) { + bootloader_wdt_feed(); + } + nrf_gpio_pin_clear(BOARD_POWER_OFF_CONFIRM_LED_PIN); +} + +#endif // BOARD_POWER_OFF_CONFIRM_LED_PIN + +// Power-off is a sequence, not a register write, and the order matters. +static void power_off(void) { + // 0. Commit the filesystem. Hold-to-power-off is this device's normal + // "off", so the dirty page sitting in the flash cache is typically the + // last thing FAT wrote. + if (filesystem_present()) { + supervisor_flash_flush(); + } + + // 1. Let the board put its own hardware to bed first, while everything is + // still powered and predictable. + board_power_off_prepare(); + + // 1a. Confirm the gesture with one flash, before anything else changes. + // Deliberately after the prepare hook, so it is drawing on a board that + // is already quiesced and the LED it leaves behind is off. + #ifdef BOARD_POWER_OFF_CONFIRM_LED_PIN + power_off_confirm_blink(); + #endif + + // 2. Detach from USB + NRF_USBD->USBPULLUP = 0; + NRF_USBD->ENABLE = 0; + + // 3. Wait for the button to be released, feeding the watchdog meanwhile. + uint32_t released_since = POWER_OFF_RTC->COUNTER; + while (true) { + bootloader_wdt_feed(); + uint32_t now = POWER_OFF_RTC->COUNTER; + if (nrf_gpio_pin_read(BOARD_POWER_OFF_BUTTON_PIN) == 0) { + released_since = now; + } else if (((now - released_since) & RTC_COUNTER_MASK) >= RELEASE_DEBOUNCE_SUBTICKS) { + break; + } + } + + // 4. Clear RESETREAS so the next boot can tell a wake-from-off from a + // watchdog reset. + NRF_POWER->RESETREAS = NRF_POWER->RESETREAS; + + // 5. Arm the wake. Clear any latched DETECT first. + NRF_P0->LATCH = 0xFFFFFFFF; + NRF_P1->LATCH = 0xFFFFFFFF; + nrf_gpio_cfg_sense_input(BOARD_POWER_OFF_BUTTON_PIN, + NRF_GPIO_PIN_PULLUP, NRF_GPIO_PIN_SENSE_LOW); + + // 6. Off. Note that the spin below deliberately does not feed the + // watchdog. If SYSTEM_OFF does not take a bootloader-armed dog + // bites within seconds and the board comes back up normally. + __DSB(); + NRF_POWER->SYSTEMOFF = 1; + __DSB(); + while (true) { + } +} + +// Reading a pin whose input buffer is disconnected returns 0, which is +// indistinguishable from the button being held. power_off_tick() would see a +// button that is down on the very first poll and never released, so the gesture +// would arm itself off permanently and the board would silently lose its only +// way to power down. +// +// So check the buffer every poll and reconnect it if it +// has gone away. Anything already configured is left exactly as it is. +static void ensure_input_buffer_connected(void) { + uint32_t pin_number = BOARD_POWER_OFF_BUTTON_PIN; + NRF_GPIO_Type *reg = nrf_gpio_pin_port_decode(&pin_number); + if ((reg->PIN_CNF[pin_number] & GPIO_PIN_CNF_INPUT_Msk) == + (GPIO_PIN_CNF_INPUT_Disconnect << GPIO_PIN_CNF_INPUT_Pos)) { + // Pull-up, matching the active-low switch-to-ground the header + // documents. Without a pull the line floats and the read is noise. + nrf_gpio_cfg_input(BOARD_POWER_OFF_BUTTON_PIN, NRF_GPIO_PIN_PULLUP); + } +} + +static bool power_off_deferred(uint32_t now) { + static uint32_t absent_since_subticks; + static bool was_absent; + + if (filesystem_present()) { + was_absent = false; + return false; + } + + if (!was_absent) { + was_absent = true; + absent_since_subticks = now; + } + return ((now - absent_since_subticks) & RTC_COUNTER_MASK) < FILESYSTEM_GRACE_SUBTICKS; +} + +void power_off_tick(void) { + uint32_t now = POWER_OFF_RTC->COUNTER; + static uint32_t last_poll_subticks; + if (((now - last_poll_subticks) & RTC_COUNTER_MASK) < POLL_INTERVAL_SUBTICKS) { + return; + } + last_poll_subticks = now; + + if (power_off_deferred(now)) { + return; + } + + ensure_input_buffer_connected(); + + // Reading IN never disturbs the pin, so the gesture still works if user + // code has claimed the button. + bool pressed = nrf_gpio_pin_read(BOARD_POWER_OFF_BUTTON_PIN) == 0; + + // Waking from SYSTEM_OFF happens with the button still held, and the + // bootloader plus start up take far less than the hold time, so a fresh + // boot would otherwise see a hold already in progress and power straight + // back off. Require the button to be seen released once first. + static bool gesture_armed; + static bool was_pressed; + if (!pressed) { + gesture_armed = true; + was_pressed = false; + return; + } + if (!gesture_armed) { + return; + } + + static uint32_t press_started_subticks; + if (!was_pressed) { + was_pressed = true; + press_started_subticks = now; + return; + } + if (((now - press_started_subticks) & RTC_COUNTER_MASK) >= POWER_OFF_HOLD_SUBTICKS) { + power_off(); + } +} + +#endif // BOARD_POWER_OFF_BUTTON_PIN diff --git a/ports/nordic/boards/teenage_engineering_sp1/power_off.h b/ports/nordic/boards/teenage_engineering_sp1/power_off.h new file mode 100644 index 00000000000..d9eef76d611 --- /dev/null +++ b/ports/nordic/boards/teenage_engineering_sp1/power_off.h @@ -0,0 +1,47 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// A supervisor-level power-off gesture, for a board whose only "off" is +// SYSTEM_OFF. +// +// A board opts in by defining BOARD_POWER_OFF_BUTTON_PIN in mpconfigboard.h to +// an active-low, switch-to-ground button that is also the wake source. Holding +// it for BOARD_POWER_OFF_HOLD_SECONDS then powers the board down; pressing it +// again wakes the chip through a reset, which on a board with a bootloader +// means the bootloader runs first. +// +// A board may also define BOARD_POWER_OFF_CONFIRM_LED_PIN to an active-high +// LED, which is flashed once (BOARD_POWER_OFF_CONFIRM_LED_MS, default 200) as +// soon as the hold completes. Without it the gesture is silent, which on a +// screen-less board leaves no way to tell a successful power-off from a hold +// that was a moment too short. +// +// The board does not have to configure that pin. If its input buffer is found +// disconnected the poll reconnects it with a pull-up. A board is still free to +// configure it, and anything already configured is left alone. +// +// The gesture holds off while the supervisor is building the filesystem, so +// that a press during a format cannot leave a half-written FAT behind. The +// press is not lost: it takes effect as soon as the filesystem is mounted. + + +#include "py/mpconfig.h" + +#ifdef BOARD_POWER_OFF_BUTTON_PIN + +// Poll the button and, if it has been held long enough, power off (never +// returns). Called from the board's board_background_task(), i.e. from every +// RUN_BACKGROUND_TASKS. +void power_off_tick(void); + +// Put the board's own hardware into its off state: rails down, resets +// asserted, anything that would drain a battery through SYSTEM_OFF switched +// off. +void board_power_off_prepare(void); + +#endif diff --git a/ports/nordic/boards/teenage_engineering_sp1/wdt.h b/ports/nordic/boards/teenage_engineering_sp1/wdt.h new file mode 100644 index 00000000000..c0107e4e1ca --- /dev/null +++ b/ports/nordic/boards/teenage_engineering_sp1/wdt.h @@ -0,0 +1,40 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Support for the watchdog that this board's bootloader starts, before +// CircuitPython's first instruction, and that cannot be stopped. +// +// This is not the `watchdog` module: that one owns the peripheral and can +// configure it. Here the WDT is already running and its configuration +// registers (CRV, RREN, CONFIG) are locked, so the only thing the application +// can do is reload it. +// +// This is the device's escape hatch. With no reset pin and no way to remove the +// battery, a wedge that stops the main loop has to become a reset, because a +// reset is what runs the bootloader and re-opens the reflashing window. So the +// feed lives in board_background_task(), never in an interrupt handler, and +// mpconfigboard.mk keeps CIRCUITPY_WATCHDOG off so that user code cannot get +// at the peripheral. + +#include + +#include "nrfx.h" + +// Value that a reload request register must be written with, per the nRF52 +// product specification. +#define NRF_WDT_RELOAD_REQUEST_VALUE (0x6E524635UL) + +// Reload the bootloader's watchdog. +// +// Call this from the main loop, never from an interrupt handler. Feeding from +// an ISR would keep a wedged main loop "alive" indefinitely. +static inline void bootloader_wdt_feed(void) { + for (size_t channel = 0; channel < 8; channel++) { + NRF_WDT->RR[channel] = NRF_WDT_RELOAD_REQUEST_VALUE; + } +} diff --git a/ports/nordic/boards/warmbit_bluepixel/mpconfigboard.h b/ports/nordic/boards/warmbit_bluepixel/mpconfigboard.h index 71743c316de..08c6860e091 100644 --- a/ports/nordic/boards/warmbit_bluepixel/mpconfigboard.h +++ b/ports/nordic/boards/warmbit_bluepixel/mpconfigboard.h @@ -13,10 +13,10 @@ #define MICROPY_HW_LED_STATUS (&pin_P0_12) +// Smaller than the 8 KB default: the internal-flash filesystem leaves +// little room for firmware. #define CIRCUITPY_INTERNAL_NVM_SIZE (4096) -#define BOARD_FLASH_SIZE (FLASH_SIZE - 0x4000 - CIRCUITPY_INTERNAL_NVM_SIZE) - #define BOARD_HAS_CRYSTAL 1 #define DEFAULT_I2C_BUS_SCL (&pin_P0_08) diff --git a/ports/nordic/common-hal/_bleio/Adapter.c b/ports/nordic/common-hal/_bleio/Adapter.c index b252cc49e58..ea3155e4da7 100644 --- a/ports/nordic/common-hal/_bleio/Adapter.c +++ b/ports/nordic/common-hal/_bleio/Adapter.c @@ -32,11 +32,6 @@ #include "supervisor/usb.h" #endif -#if CIRCUITPY_OS_GETENV -#include "shared-bindings/os/__init__.h" -#include "shared-module/os/__init__.h" -#endif - #define BLE_MIN_CONN_INTERVAL MSEC_TO_UNITS(15, UNIT_0_625_MS) #define BLE_MAX_CONN_INTERVAL MSEC_TO_UNITS(15, UNIT_0_625_MS) #define BLE_SLAVE_LATENCY 0 @@ -249,6 +244,19 @@ static bool adapter_on_ble_evt(ble_evt_t *ble_evt, void *self_in) { connection->connection_obj = mp_const_none; connection->pair_status = PAIR_NOT_PAIRED; connection->mtu = 0; + // Only user code connects in the central role, and a peripheral + // connection belongs to whoever started the advertising it answered. + connection->user_owned = connected->role == BLE_GAP_ROLE_CENTRAL || + self->advertising_started_by_user; + // Clear leftover bond state; connection slots are recycled. The + // SoftDevice fills in only the keys the new peer distributes, so a + // stale keyset could mix the previous peer's keys into this peer's + // stored bond, and a stale ediv or pending-save flag could file + // this connection's bond data under the previous peer's key. + connection->ediv = EDIV_INVALID; + connection->do_bond_cccds = false; + connection->do_bond_keys = false; + bonding_clear_keys(&connection->bonding_keys); ble_drv_add_event_handler_entry(&connection->handler_entry, connection_on_ble_evt, connection); self->connection_objs = NULL; @@ -311,31 +319,6 @@ 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}; - -static void bleio_adapter_reset_name(bleio_adapter_obj_t *self) { - // setup the default name - ble_gap_addr_t addr; // local_address - get_address(self, &addr); - mp_int_t len = sizeof(default_ble_name) - 1; - default_ble_name[len - 4] = nibble_to_hex_lower[addr.addr[1] >> 4 & 0xf]; - default_ble_name[len - 3] = nibble_to_hex_lower[addr.addr[1] & 0xf]; - default_ble_name[len - 2] = nibble_to_hex_lower[addr.addr[0] >> 4 & 0xf]; - default_ble_name[len - 1] = nibble_to_hex_lower[addr.addr[0] & 0xf]; - default_ble_name[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings - - #if CIRCUITPY_OS_GETENV - char ble_name[32]; - - os_getenv_err_t result = common_hal_os_getenv_str("CIRCUITPY_BLE_NAME", ble_name, sizeof(ble_name)); - if (result == GETENV_OK) { - common_hal_bleio_adapter_set_name(self, ble_name); - return; - } - #endif - - common_hal_bleio_adapter_set_name(self, (char *)default_ble_name); -} static void bluetooth_adapter_background(void *data) { supervisor_bluetooth_background(); @@ -377,6 +360,9 @@ void common_hal_bleio_adapter_set_enabled(bleio_adapter_obj_t *self, bool enable ble_drv_remove_event_handler(connection_on_ble_evt, connection); connection->conn_handle = BLE_CONN_HANDLE_INVALID; } + // The SoftDevice's GATT table is empty after an enable. + bleio_gatts_min_handle = 0xFFFF; + bleio_gatts_max_handle = 0; self->background_callback.fun = bluetooth_adapter_background; self->background_callback.data = self; bleio_adapter_reset_name(self); @@ -409,20 +395,19 @@ bleio_address_obj_t *common_hal_bleio_adapter_get_address(bleio_adapter_obj_t *s ble_gap_addr_t local_address; get_address(self, &local_address); - bleio_address_obj_t *address = mp_obj_malloc(bleio_address_obj_t, &bleio_address_type); - - common_hal_bleio_address_construct(address, local_address.addr, local_address.addr_type); - return address; + // Return the address cached on the adapter so this can be called before + // the heap is available (e.g. from bleio_adapter_reset_name). The shared + // common_hal_bleio_address_construct() converts the raw address bytes + // into the Address object. The cached address is refreshed on every call. + common_hal_bleio_address_construct(&self->address, local_address.addr, local_address.addr_type); + self->address.base.type = &bleio_address_type; + return &self->address; } bool common_hal_bleio_adapter_set_address(bleio_adapter_obj_t *self, bleio_address_obj_t *address) { ble_gap_addr_t local_address; - mp_buffer_info_t bufinfo; - if (!mp_get_buffer(address->bytes, &bufinfo, MP_BUFFER_READ)) { - return false; - } local_address.addr_type = address->type; - memcpy(local_address.addr, bufinfo.buf, NUM_BLEIO_ADDRESS_BYTES); + memcpy(local_address.addr, address->bytes, NUM_BLEIO_ADDRESS_BYTES); return sd_ble_gap_addr_set(&local_address) == NRF_SUCCESS; } @@ -524,7 +509,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); + uint8_t *raw_data = m_malloc_without_collect(sizeof(ble_data_t) + max_packet_size); ble_data_t *sd_data = (ble_data_t *)raw_data; self->scan_results->common_hal_data = sd_data; sd_data->len = max_packet_size; @@ -611,9 +596,7 @@ static bool connect_on_ble_evt(ble_evt_t *ble_evt, void *info_in) { static void _convert_address(const bleio_address_obj_t *address, ble_gap_addr_t *sd_address) { sd_address->addr_type = address->type; - mp_buffer_info_t address_buf_info; - mp_get_buffer_raise(address->bytes, &address_buf_info, MP_BUFFER_READ); - memcpy(sd_address->addr, (uint8_t *)address_buf_info.buf, NUM_BLEIO_ADDRESS_BYTES); + memcpy(sd_address->addr, address->bytes, NUM_BLEIO_ADDRESS_BYTES); } mp_obj_t common_hal_bleio_adapter_connect(bleio_adapter_obj_t *self, bleio_address_obj_t *address, mp_float_t timeout) { @@ -740,6 +723,9 @@ uint32_t _common_hal_bleio_adapter_start_advertising(bleio_adapter_obj_t *self, if (self->current_advertising_data != NULL && self->current_advertising_data == self->advertising_data) { return NRF_ERROR_BUSY; } + // The supervisor calls this internal function directly; user code arrives via + // common_hal_bleio_adapter_start_advertising(), which overrides this to true. + self->advertising_started_by_user = false; // If the current advertising data isn't owned by the adapter then it must be an internal // advertisement that we should stop. @@ -795,7 +781,13 @@ uint32_t _common_hal_bleio_adapter_start_advertising(bleio_adapter_obj_t *self, // advertising. This prevents a potential race condition where we // fire off a beacon with the same advertising data but a new MAC // address just as we tear down the connection. - .private_addr_cycle_s = timeout + 1, + // + // For unlimited advertising, timeout + 1 would rotate the address + // every second, too fast for a central to resolve it and connect. + // Zero selects the SoftDevice default cycle of 15 minutes + // (BLE_GAP_DEFAULT_PRIVATE_ADDR_CYCLE_INTERVAL_S). + .private_addr_cycle_s = + timeout == BLE_GAP_ADV_TIMEOUT_GENERAL_UNLIMITED ? 0 : timeout + 1, .p_device_irk = NULL, }; err_code = sd_ble_gap_privacy_set(&privacy); @@ -914,6 +906,7 @@ void common_hal_bleio_adapter_start_advertising(bleio_adapter_obj_t *self, bool tx_power, directed_to)); self->user_advertising = true; + self->advertising_started_by_user = true; } void common_hal_bleio_adapter_stop_advertising(bleio_adapter_obj_t *self) { @@ -999,13 +992,13 @@ void bleio_adapter_reset(bleio_adapter_obj_t *adapter) { // Wait up to 125 ms (128 ticks) for disconnect to complete. This should be // greater than most connection intervals. - bool any_connected = false; + bool any_connected; uint64_t start_ticks = supervisor_ticks_ms64(); - while (any_connected && supervisor_ticks_ms64() - start_ticks < 128) { + do { any_connected = false; for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) { bleio_connection_internal_t *connection = &bleio_connections[i]; any_connected |= connection->conn_handle != BLE_CONN_HANDLE_INVALID; } - } + } while (any_connected && supervisor_ticks_ms64() - start_ticks < 128); } diff --git a/ports/nordic/common-hal/_bleio/Adapter.h b/ports/nordic/common-hal/_bleio/Adapter.h index 5bc1805d072..6f776261a9c 100644 --- a/ports/nordic/common-hal/_bleio/Adapter.h +++ b/ports/nordic/common-hal/_bleio/Adapter.h @@ -11,6 +11,7 @@ #include "py/obj.h" #include "py/objtuple.h" +#include "shared-bindings/_bleio/Address.h" #include "shared-bindings/_bleio/Connection.h" #include "shared-bindings/_bleio/ScanResults.h" @@ -38,6 +39,15 @@ typedef struct { ble_drv_evt_handler_entry_t advertising_handler_entry; background_callback_t background_callback; bool user_advertising; + // Whether the current (or most recent) advertising was started by user code + // rather than the supervisor. Unlike user_advertising, this is not cleared when + // advertising stops, so the connected-event handler can still read it: the + // advertising event handler runs first and has already stopped the advertising. + bool advertising_started_by_user; + // Cached local address returned by common_hal_bleio_adapter_get_address(). + // Stored inline so it never needs to allocate, even when read before the + // heap is available (e.g. from bleio_adapter_reset_name). + bleio_address_obj_t address; } bleio_adapter_obj_t; void bleio_adapter_gc_collect(bleio_adapter_obj_t *adapter); diff --git a/ports/nordic/common-hal/_bleio/Attribute.h b/ports/nordic/common-hal/_bleio/Attribute.h index 5fa6b4d6377..9a58e16bb86 100644 --- a/ports/nordic/common-hal/_bleio/Attribute.h +++ b/ports/nordic/common-hal/_bleio/Attribute.h @@ -6,6 +6,15 @@ #pragma once +#include + +#include "py/obj.h" + #include "shared-module/_bleio/Attribute.h" extern void bleio_attribute_gatts_set_security_mode(ble_gap_conn_sec_mode_t *perm, bleio_attribute_security_mode_t security_mode); + +size_t bleio_gatts_read(uint16_t handle, uint16_t conn_handle, uint8_t *buf, size_t len); +void bleio_gatts_write(uint16_t handle, uint16_t conn_handle, mp_buffer_info_t *bufinfo); +size_t bleio_gattc_read(uint16_t handle, uint16_t conn_handle, uint8_t *buf, size_t len); +void bleio_gattc_write(uint16_t handle, uint16_t conn_handle, mp_buffer_info_t *bufinfo, bool write_no_response); diff --git a/ports/nordic/common-hal/_bleio/Characteristic.c b/ports/nordic/common-hal/_bleio/Characteristic.c index 33a373f76c4..413c97a3d6e 100644 --- a/ports/nordic/common-hal/_bleio/Characteristic.c +++ b/ports/nordic/common-hal/_bleio/Characteristic.c @@ -80,8 +80,8 @@ void common_hal_bleio_characteristic_construct(bleio_characteristic_obj_t *self, // to allocate. self->initial_value_len = initial_value_bufinfo->len; if (gc_alloc_possible()) { - if (gc_nbytes(initial_value_bufinfo->buf) > 0) { - uint8_t *initial_value = m_malloc(self->initial_value_len); + if (gc_ptr_on_heap(initial_value_bufinfo->buf)) { + uint8_t *initial_value = m_malloc_without_collect(self->initial_value_len); memcpy(initial_value, initial_value_bufinfo->buf, self->initial_value_len); self->initial_value = initial_value; } else { @@ -138,10 +138,10 @@ size_t common_hal_bleio_characteristic_get_value(bleio_characteristic_obj_t *sel if (self->handle != BLE_GATT_HANDLE_INVALID) { uint16_t conn_handle = bleio_connection_get_conn_handle(self->service->connection); if (common_hal_bleio_service_get_is_remote(self->service)) { - return common_hal_bleio_gattc_read(self->handle, conn_handle, buf, len); + return bleio_gattc_read(self->handle, conn_handle, buf, len); } else { // conn_handle is ignored for non-system attributes. - return common_hal_bleio_gatts_read(self->handle, conn_handle, buf, len); + return bleio_gatts_read(self->handle, conn_handle, buf, len); } } @@ -159,7 +159,7 @@ void common_hal_bleio_characteristic_set_value(bleio_characteristic_obj_t *self, if (common_hal_bleio_service_get_is_remote(self->service)) { 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, + bleio_gattc_write(self->handle, conn_handle, bufinfo, (self->props & CHAR_PROP_WRITE_NO_RESPONSE)); } else { // Validate data length for local characteristics only. @@ -172,7 +172,7 @@ void common_hal_bleio_characteristic_set_value(bleio_characteristic_obj_t *self, // Always write the value locally even if no connections are active. // conn_handle is ignored for non-system attributes, so we use BLE_CONN_HANDLE_INVALID. - common_hal_bleio_gatts_write(self->handle, BLE_CONN_HANDLE_INVALID, bufinfo); + bleio_gatts_write(self->handle, BLE_CONN_HANDLE_INVALID, bufinfo); // Check to see if we need to notify or indicate any active connections. for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) { bleio_connection_internal_t *connection = &bleio_connections[i]; @@ -240,6 +240,8 @@ 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)); + bleio_gatts_min_handle = MIN(bleio_gatts_min_handle, descriptor->handle); + bleio_gatts_max_handle = MAX(bleio_gatts_max_handle, descriptor->handle); mp_obj_list_append(MP_OBJ_FROM_PTR(self->descriptor_list), MP_OBJ_FROM_PTR(descriptor)); @@ -255,7 +257,7 @@ void common_hal_bleio_characteristic_set_cccd(bleio_characteristic_obj_t *self, } const uint16_t conn_handle = bleio_connection_get_conn_handle(self->service->connection); - common_hal_bleio_check_connected(conn_handle); + bleio_check_connected(conn_handle); uint16_t cccd_value = (notify ? BLE_GATT_HVX_NOTIFICATION : 0) | diff --git a/ports/nordic/common-hal/_bleio/CharacteristicBuffer.c b/ports/nordic/common-hal/_bleio/CharacteristicBuffer.c index 9a86afb39ac..6d1b9b550ef 100644 --- a/ports/nordic/common-hal/_bleio/CharacteristicBuffer.c +++ b/ports/nordic/common-hal/_bleio/CharacteristicBuffer.c @@ -97,7 +97,7 @@ void common_hal_bleio_characteristic_buffer_construct(bleio_characteristic_buffe bleio_characteristic_obj_t *characteristic, mp_float_t timeout, size_t buffer_size) { - uint8_t *buffer = m_malloc(buffer_size); + uint8_t *buffer = m_malloc_without_collect(buffer_size); _common_hal_bleio_characteristic_buffer_construct(self, characteristic, timeout, buffer, buffer_size, NULL, false); } diff --git a/ports/nordic/common-hal/_bleio/Connection.c b/ports/nordic/common-hal/_bleio/Connection.c index f32034582b4..e34aa56c4e2 100644 --- a/ports/nordic/common-hal/_bleio/Connection.c +++ b/ports/nordic/common-hal/_bleio/Connection.c @@ -289,15 +289,23 @@ bool connection_on_ble_evt(ble_evt_t *ble_evt, void *self_in) { // mode >=1 and/or level >=1 means encryption is set up self->pair_status = PAIR_NOT_PAIRED; } else { - if (bonding_load_cccd_info(self->is_central, self->conn_handle, self->ediv)) { - // Did an sd_ble_gatts_sys_attr_set() with the stored sys_attr values. - // Indicate ATTR table change because we may have reloaded since the peer last - // connected. - sd_ble_gatts_service_changed(self->conn_handle, 0xC, 0xFFFF); - } else { - // No matching bonding found, so use fresh system attributes. + if (!bonding_load_cccd_info(self->is_central, self->conn_handle, self->ediv)) { + // No stored system attributes (CCCD values) found, so use fresh ones. sd_ble_gatts_sys_attr_set(self->conn_handle, NULL, 0, 0); } + if (self->ediv != EDIV_INVALID && bleio_gatts_min_handle <= bleio_gatts_max_handle) { + // The peer reconnected using a stored bond, and the GATT table may + // have changed since it last connected: a reload can add or remove + // user services. Indicate Service Changed so the peer discards its + // cached table. This must not be conditional on the sys-attr load + // above succeeding: a peer that missed the indication would trust a + // stale cache indefinitely, and saved system attributes are the + // less reliable of the two records. The error is ignored if the + // peer hasn't subscribed to indications yet. Both handles must be + // within the application-populated range: the SoftDevice rejects + // 0xFFFF, and also 0xC, which is inside its own GATT service. + (void)sd_ble_gatts_service_changed(self->conn_handle, bleio_gatts_min_handle, bleio_gatts_max_handle); + } self->pair_status = PAIR_PAIRED; } break; @@ -324,6 +332,21 @@ bool common_hal_bleio_connection_get_paired(bleio_connection_obj_t *self) { return self->connection->pair_status == PAIR_PAIRED; } +// Authenticated (MITM-protected) pairing - numeric comparison - is implemented on the +// espressif port only. This port can't tell a "Just Works" bond from an authenticated +// one, so report the conservative answer rather than a guarantee it can't make. +bool common_hal_bleio_connection_get_authenticated(bleio_connection_obj_t *self) { + return false; +} + +mp_obj_t common_hal_bleio_connection_get_numeric_comparison(bleio_connection_obj_t *self) { + return mp_const_none; +} + +void common_hal_bleio_connection_confirm_pairing(bleio_connection_obj_t *self, bool accept) { + mp_raise_NotImplementedError(NULL); +} + bool common_hal_bleio_connection_get_connected(bleio_connection_obj_t *self) { if (self->connection == NULL) { return false; diff --git a/ports/nordic/common-hal/_bleio/Connection.h b/ports/nordic/common-hal/_bleio/Connection.h index 110677dc78b..78e2ccd5314 100644 --- a/ports/nordic/common-hal/_bleio/Connection.h +++ b/ports/nordic/common-hal/_bleio/Connection.h @@ -31,6 +31,11 @@ typedef enum { typedef struct { uint16_t conn_handle; bool is_central; + // True if user code initiated or accepted this connection: it connected in the + // central role, or a central answered user code's advertising. User-owned + // connections are disconnected when the VM resets; the BLE workflow connection + // is not user-owned and stays up. + bool user_owned; // Remote services discovered when this peripheral is acting as a client. mp_obj_list_t *remote_service_list; // The advertising data and scan response buffers are held by us, not by the SD, so we must @@ -65,6 +70,7 @@ typedef struct { void bleio_connection_clear(bleio_connection_internal_t *self); bool connection_on_ble_evt(ble_evt_t *ble_evt, void *self_in); +void bleio_check_connected(uint16_t conn_handle); 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); bleio_connection_internal_t *bleio_conn_handle_to_connection(uint16_t conn_handle); diff --git a/ports/nordic/common-hal/_bleio/Descriptor.c b/ports/nordic/common-hal/_bleio/Descriptor.c index 959c8e5c9c0..0d27ca5dc2e 100644 --- a/ports/nordic/common-hal/_bleio/Descriptor.c +++ b/ports/nordic/common-hal/_bleio/Descriptor.c @@ -43,9 +43,9 @@ size_t common_hal_bleio_descriptor_get_value(bleio_descriptor_obj_t *self, uint8 if (self->handle != BLE_GATT_HANDLE_INVALID) { uint16_t conn_handle = bleio_connection_get_conn_handle(self->characteristic->service->connection); if (common_hal_bleio_service_get_is_remote(self->characteristic->service)) { - return common_hal_bleio_gattc_read(self->handle, conn_handle, buf, len); + return bleio_gattc_read(self->handle, conn_handle, buf, len); } else { - return common_hal_bleio_gatts_read(self->handle, conn_handle, buf, len); + return bleio_gatts_read(self->handle, conn_handle, buf, len); } } @@ -58,7 +58,7 @@ void common_hal_bleio_descriptor_set_value(bleio_descriptor_obj_t *self, mp_buff uint16_t conn_handle = bleio_connection_get_conn_handle(self->characteristic->service->connection); if (common_hal_bleio_service_get_is_remote(self->characteristic->service)) { // false means WRITE_REQ, not write-no-response - common_hal_bleio_gattc_write(self->handle, conn_handle, bufinfo, false); + bleio_gattc_write(self->handle, conn_handle, bufinfo, false); } else { // Validate data length for local descriptors only. if (self->fixed_length && bufinfo->len != self->max_length) { @@ -68,7 +68,7 @@ void common_hal_bleio_descriptor_set_value(bleio_descriptor_obj_t *self, mp_buff mp_raise_ValueError(MP_ERROR_TEXT("Value length > max_length")); } - common_hal_bleio_gatts_write(self->handle, conn_handle, bufinfo); + bleio_gatts_write(self->handle, conn_handle, bufinfo); } } diff --git a/ports/nordic/common-hal/_bleio/PacketBuffer.c b/ports/nordic/common-hal/_bleio/PacketBuffer.c index db4307279ae..5be9896b706 100644 --- a/ports/nordic/common-hal/_bleio/PacketBuffer.c +++ b/ports/nordic/common-hal/_bleio/PacketBuffer.c @@ -278,14 +278,14 @@ void common_hal_bleio_packet_buffer_construct( uint32_t *incoming_buffer = NULL; if (incoming) { incoming_buffer_size = buffer_size * (sizeof(uint16_t) + max_packet_size); - incoming_buffer = m_malloc(incoming_buffer_size); + incoming_buffer = m_malloc_without_collect(incoming_buffer_size); } uint32_t *outgoing1 = NULL; uint32_t *outgoing2 = NULL; if (outgoing) { - outgoing1 = m_malloc(max_packet_size); - outgoing2 = m_malloc(max_packet_size); + outgoing1 = m_malloc_without_collect(max_packet_size); + outgoing2 = m_malloc_without_collect(max_packet_size); } _common_hal_bleio_packet_buffer_construct(self, characteristic, incoming_buffer, incoming_buffer_size, @@ -481,8 +481,14 @@ bool common_hal_bleio_packet_buffer_deinited(bleio_packet_buffer_obj_t *self) { void common_hal_bleio_packet_buffer_deinit(bleio_packet_buffer_obj_t *self) { if (!common_hal_bleio_packet_buffer_deinited(self)) { - ble_drv_remove_event_handler(packet_buffer_on_ble_client_evt, self); + if (self->client) { + ble_drv_remove_event_handler(packet_buffer_on_ble_client_evt, self); + } else { + ble_drv_remove_event_handler(packet_buffer_on_ble_server_evt, self); + } ringbuf_deinit(&self->ringbuf); + // Mark as deinited, so common_hal_bleio_packet_buffer_deinited() reports it. + self->characteristic = NULL; } } diff --git a/ports/nordic/common-hal/_bleio/Service.c b/ports/nordic/common-hal/_bleio/Service.c index edd67a5fe73..c187c54178d 100644 --- a/ports/nordic/common-hal/_bleio/Service.c +++ b/ports/nordic/common-hal/_bleio/Service.c @@ -46,6 +46,8 @@ uint32_t _common_hal_bleio_service_construct(bleio_service_obj_t *self, bleio_uu uint32_t result = sd_ble_gatts_service_add(service_type, &nordic_uuid, &self->handle); // Do a service changed indication to all connected peers. if (result == NRF_SUCCESS) { + bleio_gatts_min_handle = MIN(bleio_gatts_min_handle, self->handle); + bleio_gatts_max_handle = MAX(bleio_gatts_max_handle, self->handle); _indicate_service_change(self->handle, self->handle); } @@ -131,7 +133,7 @@ void common_hal_bleio_service_add_characteristic(bleio_service_obj_t *self, BLE_GAP_CONN_SEC_MODE_SET_OPEN(&user_desc_md.read_perm); // If the description is on the Python heap, then have the SD copy it. If not, assume it's // static and will live for longer than the SD. - user_desc_md.vloc = gc_nbytes(user_description) > 0 ? BLE_GATTS_VLOC_STACK : BLE_GATTS_VLOC_USER; + user_desc_md.vloc = gc_ptr_on_heap(user_description) ? BLE_GATTS_VLOC_STACK : BLE_GATTS_VLOC_USER; char_md.p_user_desc_md = &user_desc_md; char_md.p_char_user_desc = (const uint8_t *)user_description; char_md.char_user_desc_max_size = strlen(user_description); @@ -169,6 +171,8 @@ void common_hal_bleio_service_add_characteristic(bleio_service_obj_t *self, _expand_range(char_handles.cccd_handle, &start, &end); _expand_range(char_handles.sccd_handle, &start, &end); _expand_range(char_handles.user_desc_handle, &start, &end); + bleio_gatts_min_handle = MIN(bleio_gatts_min_handle, start); + bleio_gatts_max_handle = MAX(bleio_gatts_max_handle, end); _indicate_service_change(start, end); #if CIRCUITPY_VERBOSE_BLE diff --git a/ports/nordic/common-hal/_bleio/__init__.c b/ports/nordic/common-hal/_bleio/__init__.c index 095723194cf..36900d2d9c7 100644 --- a/ports/nordic/common-hal/_bleio/__init__.c +++ b/ports/nordic/common-hal/_bleio/__init__.c @@ -52,14 +52,33 @@ void check_gatt_status(uint16_t gatt_status) { return; } switch (gatt_status) { + case BLE_GATT_STATUS_ATTERR_READ_NOT_PERMITTED: + mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("%q not permitted"), MP_QSTR_read); + return; + case BLE_GATT_STATUS_ATTERR_WRITE_NOT_PERMITTED: + mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("%q not permitted"), MP_QSTR_write); + return; case BLE_GATT_STATUS_ATTERR_INSUF_AUTHENTICATION: mp_raise_bleio_SecurityError(MP_ERROR_TEXT("Insufficient authentication")); return; + case BLE_GATT_STATUS_ATTERR_INSUF_AUTHORIZATION: + mp_raise_bleio_SecurityError(MP_ERROR_TEXT("Insufficient authorization")); + return; case BLE_GATT_STATUS_ATTERR_INSUF_ENCRYPTION: + case BLE_GATT_STATUS_ATTERR_INSUF_ENC_KEY_SIZE: mp_raise_bleio_SecurityError(MP_ERROR_TEXT("Insufficient encryption")); return; + case BLE_GATT_STATUS_ATTERR_INVALID_ATT_VAL_LENGTH: + mp_arg_error_invalid(MP_QSTR_length); + return; default: - mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Unknown gatt error: 0x%04x"), gatt_status); + if (gatt_status > BLE_GATT_STATUS_ATTERR_INVALID && + gatt_status <= BLE_GATT_STATUS_ATTERR_CPS_OUT_OF_RANGE) { + // Some other ATT error from the peer. + mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Unknown gatt error: 0x%04x"), gatt_status); + } + // Not an ATT error, e.g. BLE_GATT_STATUS_UNKNOWN. + mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Unknown BLE error: 0x%04x"), gatt_status); } } @@ -70,21 +89,48 @@ void check_sec_status(uint8_t sec_status) { switch (sec_status) { case BLE_GAP_SEC_STATUS_UNSPECIFIED: - mp_raise_bleio_SecurityError(MP_ERROR_TEXT("Unspecified issue. Can be that the pairing prompt on the other device was declined or ignored.")); + mp_raise_bleio_SecurityError(MP_ERROR_TEXT("Unspecified issue. The pairing request on the other device may have been declined or ignored.")); return; default: mp_raise_bleio_SecurityError(MP_ERROR_TEXT("Unknown security error: 0x%04x"), sec_status); } } +uint16_t bleio_gatts_min_handle = 0xFFFF; +uint16_t bleio_gatts_max_handle; + void common_hal_bleio_init(void) { } -void bleio_user_reset() { +void bleio_user_reset(void) { if (common_hal_bleio_adapter_get_enabled(&common_hal_bleio_adapter_obj)) { // Stop any user scanning or advertising. common_hal_bleio_adapter_stop_scan(&common_hal_bleio_adapter_obj); common_hal_bleio_adapter_stop_advertising(&common_hal_bleio_adapter_obj); + + // Disconnect the connections that user code initiated or accepted with its + // own advertising. The BLE workflow connection is not user-owned and stays up. + // + // Clear each connection's pointers into the VM heap first: the heap is about + // to go away, and a disconnect completes asynchronously, possibly after it + // has. The disconnect event handler dereferences connection_obj unless it is + // mp_const_none. + for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) { + bleio_connection_internal_t *connection = &bleio_connections[i]; + connection->connection_obj = mp_const_none; + connection->remote_service_list = NULL; + if (connection->conn_handle != BLE_CONN_HANDLE_INVALID && connection->user_owned) { + common_hal_bleio_connection_disconnect(connection); + } + } + + // Clear the adapter's remaining pointers into the VM heap. The full stack + // reset in bleio_reset() used to do this implicitly, but it no longer always + // runs. The adapter struct is a GC root, so a pointer left over from this + // heap would be scanned as a live object in the next VM's heap. + common_hal_bleio_adapter_obj.connection_objs = NULL; + common_hal_bleio_adapter_obj.advertising_data = NULL; + common_hal_bleio_adapter_obj.scan_response_data = NULL; } ble_drv_remove_heap_handlers(); @@ -94,13 +140,23 @@ void bleio_user_reset() { } // Turn off BLE on a reset or reload. -void bleio_reset() { +void bleio_reset(void) { // Set this explicitly to save data. common_hal_bleio_adapter_obj.base.type = &bleio_adapter_type; if (!common_hal_bleio_adapter_get_enabled(&common_hal_bleio_adapter_obj)) { return; } + // The SoftDevice cannot remove individual services from its GATT table: the + // disable/enable cycle below is the only way to clear them, and it drops every + // connection, the BLE workflow's included. So run it only when user code created + // services. All other user BLE state has already been torn down individually by + // bleio_user_reset(). + if (!bleio_get_user_services_created()) { + return; + } + bleio_clear_user_services_created(); + supervisor_stop_bluetooth(); bleio_adapter_reset(&common_hal_bleio_adapter_obj); common_hal_bleio_adapter_set_enabled(&common_hal_bleio_adapter_obj, false); @@ -112,14 +168,14 @@ void bleio_reset() { // It currently only has properties and no state. Inited by bleio_reset bleio_adapter_obj_t common_hal_bleio_adapter_obj; -void common_hal_bleio_check_connected(uint16_t conn_handle) { +void bleio_check_connected(uint16_t conn_handle) { if (conn_handle == BLE_CONN_HANDLE_INVALID) { mp_raise_ConnectionError(MP_ERROR_TEXT("Not connected")); } } // 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 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. @@ -133,7 +189,7 @@ size_t common_hal_bleio_gatts_read(uint16_t handle, uint16_t conn_handle, uint8_ return gatts_value.len; } -void common_hal_bleio_gatts_write(uint16_t handle, uint16_t conn_handle, mp_buffer_info_t *bufinfo) { +void bleio_gatts_write(uint16_t handle, uint16_t conn_handle, mp_buffer_info_t *bufinfo) { // 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. @@ -188,8 +244,8 @@ 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) { - common_hal_bleio_check_connected(conn_handle); +size_t bleio_gattc_read(uint16_t handle, uint16_t conn_handle, uint8_t *buf, size_t len) { + bleio_check_connected(conn_handle); read_info_t read_info; read_info.buf = buf; @@ -212,16 +268,53 @@ size_t common_hal_bleio_gattc_read(uint16_t handle, uint16_t conn_handle, uint8_ while (!read_info.done) { RUN_BACKGROUND_TASKS; } - // Test if we were disconnected while reading - common_hal_bleio_check_connected(read_info.conn_handle); - + // Remove the handler before anything can raise: it points at read_info on this stack frame. ble_drv_remove_event_handler(_on_gattc_read_rsp_evt, &read_info); + + // Test if we were disconnected while reading + bleio_check_connected(read_info.conn_handle); check_gatt_status(read_info.status); return read_info.final_len; } -void common_hal_bleio_gattc_write(uint16_t handle, uint16_t conn_handle, mp_buffer_info_t *bufinfo, bool write_no_response) { - common_hal_bleio_check_connected(conn_handle); +typedef struct { + uint16_t handle; + uint16_t conn_handle; + volatile uint16_t status; + volatile bool done; +} write_info_t; + +static bool _on_gattc_write_rsp_evt(ble_evt_t *ble_evt, void *param) { + write_info_t *write = param; + switch (ble_evt->header.evt_id) { + case BLE_GATTC_EVT_WRITE_RSP: { + ble_gattc_evt_t *evt = &ble_evt->evt.gattc_evt; + // Another write request (e.g. a CCCD write) may still have been in progress + // when this one started, so match the handle as well as the connection. + uint16_t rsp_handle = evt->gatt_status == BLE_GATT_STATUS_SUCCESS + ? evt->params.write_rsp.handle + : evt->error_handle; + if (evt->conn_handle != write->conn_handle || rsp_handle != write->handle) { + return false; + } + write->status = evt->gatt_status; + write->done = true; + break; + } + case BLE_GAP_EVT_DISCONNECTED: + if (ble_evt->evt.gap_evt.conn_handle == write->conn_handle) { + write->conn_handle = BLE_CONN_HANDLE_INVALID; + write->done = true; + } + return false; + default: + return false; + } + return true; +} + +void bleio_gattc_write(uint16_t handle, uint16_t conn_handle, mp_buffer_info_t *bufinfo, bool write_no_response) { + bleio_check_connected(conn_handle); ble_gattc_write_params_t write_params = { .write_op = write_no_response ? BLE_GATT_OP_WRITE_CMD: BLE_GATT_OP_WRITE_REQ, @@ -230,24 +323,47 @@ void common_hal_bleio_gattc_write(uint16_t handle, uint16_t conn_handle, mp_buff .len = bufinfo->len, }; + // A write with response waits for the response, so that errors from the peer are reported. + write_info_t write_info = { + .handle = handle, + .conn_handle = conn_handle, + .status = BLE_GATT_STATUS_SUCCESS, + .done = false, + }; + if (!write_no_response) { + ble_drv_add_event_handler(_on_gattc_write_rsp_evt, &write_info); + } + while (1) { uint32_t err_code = sd_ble_gattc_write(conn_handle, &write_params); if (err_code == NRF_SUCCESS) { break; } - // Write with response will return NRF_ERROR_BUSY if the response has not been received. + // Write with response will return NRF_ERROR_BUSY if another write request is in progress. // Write without response will return NRF_ERROR_RESOURCES if too many writes are pending. if (err_code == NRF_ERROR_BUSY || err_code == NRF_ERROR_RESOURCES) { - // We could wait for an event indicating the write is complete, but just retrying is easier. MICROPY_VM_HOOK_LOOP; continue; } // Some real error occurred. + ble_drv_remove_event_handler(_on_gattc_write_rsp_evt, &write_info); check_nrf_error(err_code); } + if (write_no_response) { + return; + } + + while (!write_info.done) { + RUN_BACKGROUND_TASKS; + } + ble_drv_remove_event_handler(_on_gattc_write_rsp_evt, &write_info); + + // Test if we were disconnected while writing. + bleio_check_connected(write_info.conn_handle); + check_gatt_status(write_info.status); } void bleio_background(void) { diff --git a/ports/nordic/common-hal/_bleio/__init__.h b/ports/nordic/common-hal/_bleio/__init__.h index caf287f9204..eecbc32275f 100644 --- a/ports/nordic/common-hal/_bleio/__init__.h +++ b/ports/nordic/common-hal/_bleio/__init__.h @@ -8,6 +8,12 @@ void bleio_background(void); +// Remember the range of attribute handles the application has populated in the +// SoftDevice's GATT table. Required to call sd_ble_gatts_service_changed() +// with valid arguments: it fails if the args are outside that range. +extern uint16_t bleio_gatts_min_handle; +extern uint16_t bleio_gatts_max_handle; + typedef struct { ble_gap_enc_key_t own_enc; ble_gap_enc_key_t peer_enc; diff --git a/ports/nordic/common-hal/alarm/__init__.c b/ports/nordic/common-hal/alarm/__init__.c index 9753b0321fd..5db3e269994 100644 --- a/ports/nordic/common-hal/alarm/__init__.c +++ b/ports/nordic/common-hal/alarm/__init__.c @@ -232,15 +232,12 @@ mp_obj_t common_hal_alarm_light_sleep_until_alarms(size_t n_alarms, const mp_obj } void common_hal_alarm_set_deep_sleep_alarms(size_t n_alarms, const mp_obj_t *alarms, size_t n_dios, digitalio_digitalinout_obj_t **preserve_dios) { - if (n_dios > 0) { - mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_preserve_dios); - } _setup_sleep_alarms(true, n_alarms, alarms); } #define PRESCALER_VALUE_IN_DEEP_SLEEP (1024) -void NORETURN common_hal_alarm_enter_deep_sleep(void) { +void MP_NORETURN common_hal_alarm_enter_deep_sleep(void) { alarm_pin_pinalarm_prepare_for_deep_sleep(); alarm_time_timealarm_prepare_for_deep_sleep(); diff --git a/ports/nordic/common-hal/alarm/__init__.h b/ports/nordic/common-hal/alarm/__init__.h index 91d717ccce2..336447689ff 100644 --- a/ports/nordic/common-hal/alarm/__init__.h +++ b/ports/nordic/common-hal/alarm/__init__.h @@ -13,7 +13,7 @@ #include "common-hal/alarm/touch/TouchAlarm.h" typedef enum { - NRF_SLEEP_WAKEUP_UNDEFINED, + NRF_SLEEP_WAKEUP_UNDEFINED = 0, NRF_SLEEP_WAKEUP_GPIO, NRF_SLEEP_WAKEUP_TIMER, NRF_SLEEP_WAKEUP_TOUCHPAD, @@ -33,8 +33,9 @@ extern const alarm_sleep_memory_obj_t alarm_sleep_memory_obj; enum { SLEEPMEM_WAKEUP_BY_NONE = 0, - SLEEPMEM_WAKEUP_BY_PIN = 1, - SLEEPMEM_WAKEUP_BY_TIMER = 2, + SLEEPMEM_WAKEUP_BY_PIN, + SLEEPMEM_WAKEUP_BY_TIMER, + SLEEPMEM_WAKEUP_BY_TOUCH, }; #define WAKEUP_PIN_UNDEF 0xFF extern uint8_t sleepmem_wakeup_event; diff --git a/ports/nordic/common-hal/alarm/pin/PinAlarm.c b/ports/nordic/common-hal/alarm/pin/PinAlarm.c index f43eb1ed251..6fe9fd12a14 100644 --- a/ports/nordic/common-hal/alarm/pin/PinAlarm.c +++ b/ports/nordic/common-hal/alarm/pin/PinAlarm.c @@ -17,7 +17,9 @@ #include "nrfx.h" #include "nrf_gpio.h" #include "nrfx_gpiote.h" +#ifdef BLUETOOTH_SD #include "nrf_soc.h" +#endif #include #define WPIN_UNUSED 0xFF @@ -101,6 +103,9 @@ mp_obj_t alarm_pin_pinalarm_record_wake_alarm(void) { static uint64_t high_alarms = 0; static uint64_t low_alarms = 0; static uint64_t pull_pins = 0; +// Pins that nrfx_gpiote_in_init() has set up. nrfx_gpiote_in_uninit() writes out of +// bounds on a pin that has no GPIOTE channel, so only these are uninited. +static uint64_t gpiote_pins = 0; void alarm_pin_pinalarm_reset(void) { for (size_t i = 0; i < 64; i++) { @@ -110,11 +115,16 @@ void alarm_pin_pinalarm_reset(void) { if (!(high || low)) { continue; } + if (gpiote_pins & mask) { + nrfx_gpiote_in_event_disable((nrfx_gpiote_pin_t)i); + nrfx_gpiote_in_uninit((nrfx_gpiote_pin_t)i); + } + // After the uninit, which sets the pin to its default state, so a + // board's reset state for the pin wins. reset_pin_number(i); - nrfx_gpiote_in_event_disable((nrfx_gpiote_pin_t)i); - nrfx_gpiote_in_uninit((nrfx_gpiote_pin_t)i); } + gpiote_pins = 0; high_alarms = 0; low_alarms = 0; pull_pins = 0; @@ -153,11 +163,18 @@ static void configure_pins_for_sleep(void) { cfg.sense = NRF_GPIOTE_POLARITY_TOGGLE; cfg.pull = NRF_GPIO_PIN_NOPULL; } - nrfx_err_t err = nrfx_gpiote_in_init((nrfx_gpiote_pin_t)i, &cfg, - pinalarm_gpiote_handler); - assert(err == NRFX_SUCCESS); - (void)err; // In case the assert doesn't use err. - nrfx_gpiote_in_event_enable((nrfx_gpiote_pin_t)i, true); + if ((gpiote_pins & mask) == 0) { + nrfx_err_t err = nrfx_gpiote_in_init((nrfx_gpiote_pin_t)i, &cfg, + pinalarm_gpiote_handler); + if (err == NRFX_SUCCESS) { + gpiote_pins |= mask; + } + } + // Without a GPIOTE channel there is no event, but SENSE below can + // still wake the chip from deep sleep. + if (gpiote_pins & mask) { + nrfx_gpiote_in_event_enable((nrfx_gpiote_pin_t)i, true); + } if (((high_alarms & mask) != 0) && ((low_alarms & mask) == 0)) { nrf_gpio_cfg_sense_set((uint32_t)i, NRF_GPIO_PIN_SENSE_HIGH); } @@ -169,8 +186,6 @@ static void configure_pins_for_sleep(void) { void alarm_pin_pinalarm_set_alarms(bool deep_sleep, size_t n_alarms, const mp_obj_t *alarms) { // Bitmask of wake up settings. - size_t high_count = 0; - size_t low_count = 0; int pin_number = -1; for (size_t i = 0; i < n_alarms; i++) { @@ -183,10 +198,8 @@ void alarm_pin_pinalarm_set_alarms(bool deep_sleep, size_t n_alarms, const mp_ob // mp_printf(&mp_plat_print, "alarm_pin_pinalarm_set_alarms(pin#=%d, val=%d, pull=%d)\r\n", pin_number, alarm->value, alarm->pull); if (alarm->value) { high_alarms |= 1ull << pin_number; - high_count++; } else { low_alarms |= 1ull << pin_number; - low_count++; } if (alarm->pull) { pull_pins |= 1ull << pin_number; diff --git a/ports/nordic/common-hal/analogio/AnalogIn.c b/ports/nordic/common-hal/analogio/AnalogIn.c index e48c9dd2e28..1459c67c08c 100644 --- a/ports/nordic/common-hal/analogio/AnalogIn.c +++ b/ports/nordic/common-hal/analogio/AnalogIn.c @@ -23,6 +23,9 @@ void analogin_init(void) { while (nrf_saadc_event_check(NRF_SAADC, NRF_SAADC_EVENT_CALIBRATEDONE) == 0) { } nrf_saadc_event_clear(NRF_SAADC, NRF_SAADC_EVENT_CALIBRATEDONE); + nrf_saadc_event_clear(NRF_SAADC, NRF_SAADC_EVENT_END); + nrf_saadc_event_clear(NRF_SAADC, NRF_SAADC_EVENT_DONE); + nrf_saadc_event_clear(NRF_SAADC, NRF_SAADC_EVENT_RESULTDONE); nrf_saadc_disable(NRF_SAADC); } @@ -56,7 +59,8 @@ 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. - nrf_saadc_value_t value = 0; + static volatile nrf_saadc_value_t value __attribute__((aligned(4))); + value = 0; const nrf_saadc_channel_config_t config = { .resistor_p = NRF_SAADC_RESISTOR_DISABLED, @@ -78,7 +82,12 @@ uint16_t common_hal_analogio_analogin_get_value(analogio_analogin_obj_t *self) { 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_buffer_init(NRF_SAADC, (nrf_saadc_value_t *)&value, 1); + nrf_saadc_event_clear(NRF_SAADC, NRF_SAADC_EVENT_STARTED); + nrf_saadc_event_clear(NRF_SAADC, NRF_SAADC_EVENT_END); + nrf_saadc_event_clear(NRF_SAADC, NRF_SAADC_EVENT_DONE); + nrf_saadc_event_clear(NRF_SAADC, NRF_SAADC_EVENT_RESULTDONE); + nrf_saadc_event_clear(NRF_SAADC, NRF_SAADC_EVENT_STOPPED); nrf_saadc_task_trigger(NRF_SAADC, NRF_SAADC_TASK_START); while (nrf_saadc_event_check(NRF_SAADC, NRF_SAADC_EVENT_STARTED) == 0) { @@ -100,23 +109,20 @@ uint16_t common_hal_analogio_analogin_get_value(analogio_analogin_obj_t *self) { nrf_saadc_disable(NRF_SAADC); - // Adding the "asm volatile" memory fence here or anywhere after the declaration of `value` - // fixes an issue with gcc13 which causes `value` to always be zero. - // Compiling with gcc10 or gcc12 is fine. - // It can also be fixed by declaring `value` to be static. - // I think I'd like to declare `value` as volatile, but that causes type errors. - asm volatile ("" : : : "memory"); // Disconnect ADC from pin. nrf_saadc_channel_input_set(NRF_SAADC, CHANNEL_NO, NRF_SAADC_INPUT_DISABLED, NRF_SAADC_INPUT_DISABLED); + // Read the DMA'd result exactly once. + int32_t result = value; + // value is signed and might be (slightly) < 0, even on single-ended conversions, so force to 0. - if (value < 0) { - value = 0; + if (result < 0) { + result = 0; } // Stretch 14-bit ADC reading to 16-bit range - return (value << 2) | (value >> 12); + return (result << 2) | (result >> 12); } float common_hal_analogio_analogin_get_reference_voltage(analogio_analogin_obj_t *self) { diff --git a/ports/nordic/common-hal/audiobusio/I2SOut.c b/ports/nordic/common-hal/audiobusio/I2SOut.c index 01758ee9b21..f50db4ea545 100644 --- a/ports/nordic/common-hal/audiobusio/I2SOut.c +++ b/ports/nordic/common-hal/audiobusio/I2SOut.c @@ -16,6 +16,8 @@ #include "py/obj.h" #include "py/runtime.h" +#include "nrf_gpio.h" + static audiobusio_i2sout_obj_t *instance; struct { int16_t l, r; @@ -107,23 +109,30 @@ static void i2s_buffer_fill(audiobusio_i2sout_obj_t *self) { while (!self->paused && !self->stopping && bytesleft) { if (self->sample_data == self->sample_end) { + if (self->last_buffer) { + // The final buffer has been fully output; stop now instead of + // fetching another (which for a single-buffer sample would just + // replay it). + self->stopping = true; + break; + } 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_end = self->sample_data + sample_buffer_length; + if (get_buffer_result == GET_BUFFER_ERROR || sample_buffer_length == 0) { + self->stopping = true; + break; + } if (get_buffer_result == GET_BUFFER_DONE) { if (self->loop) { audiosample_reset_buffer(self->sample, false, 0); } else { - self->stopping = true; - break; + // Output this final buffer before stopping; don't fetch again. + self->last_buffer = true; } } - if (get_buffer_result == GET_BUFFER_ERROR || sample_buffer_length == 0) { - self->stopping = true; - break; - } } uint16_t bytecount = MIN(bytesleft, (size_t)(self->sample_end - self->sample_data)); if (self->samples_signed) { @@ -180,9 +189,18 @@ static void i2s_buffer_fill(audiobusio_i2sout_obj_t *self) { } } +static void mark_deinit(audiobusio_i2sout_obj_t *self) { + self->data_pin_number = NO_PIN; +} + 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, const mcu_pin_obj_t *main_clock, bool left_justified) { + const mcu_pin_obj_t *data, const mcu_pin_obj_t *main_clock, bool left_justified, + bool external_clock) { + // Ensure the object starts in its deinit state, so its finaliser does + // nothing if this raises. + mark_deinit(self); + if (main_clock != NULL) { mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_main_clock); } @@ -195,14 +213,23 @@ void common_hal_audiobusio_i2sout_construct(audiobusio_i2sout_obj_t *self, claim_pin(word_select); claim_pin(data); + self->external_clock = external_clock; + NRF_I2S->PSEL.SCK = self->bit_clock_pin_number = bit_clock->number; NRF_I2S->PSEL.LRCK = self->word_select_pin_number = word_select->number; NRF_I2S->PSEL.SDOUT = self->data_pin_number = data->number; - NRF_I2S->CONFIG.MODE = I2S_CONFIG_MODE_MODE_Master; + if (external_clock) { + nrf_gpio_cfg_input(bit_clock->number, NRF_GPIO_PIN_NOPULL); + nrf_gpio_cfg_input(word_select->number, NRF_GPIO_PIN_NOPULL); + } + + NRF_I2S->CONFIG.MODE = external_clock ? I2S_CONFIG_MODE_MODE_Slave + : I2S_CONFIG_MODE_MODE_Master; NRF_I2S->CONFIG.RXEN = I2S_CONFIG_RXEN_RXEN_Disabled; NRF_I2S->CONFIG.TXEN = I2S_CONFIG_TXEN_TXEN_Enabled; - NRF_I2S->CONFIG.MCKEN = I2S_CONFIG_MCKEN_MCKEN_Enabled; + NRF_I2S->CONFIG.MCKEN = external_clock ? I2S_CONFIG_MCKEN_MCKEN_Disabled + : I2S_CONFIG_MCKEN_MCKEN_Enabled; NRF_I2S->CONFIG.SWIDTH = I2S_CONFIG_SWIDTH_SWIDTH_16Bit; NRF_I2S->CONFIG.ALIGN = I2S_CONFIG_ALIGN_ALIGN_Left; @@ -221,13 +248,25 @@ void common_hal_audiobusio_i2sout_deinit(audiobusio_i2sout_obj_t *self) { return; } NRF_I2S->TASKS_STOP = 1; + // Mirror i2s_reset(): clear the interrupt enable and disconnect all + // PSEL lines so a later construct starts from a known state. + NRF_I2S->INTENCLR = I2S_INTENSET_TXPTRUPD_Msk; NRF_I2S->ENABLE = I2S_ENABLE_ENABLE_Disabled; + NRF_I2S->PSEL.MCK = 0xFFFFFFFF; + NRF_I2S->PSEL.SCK = 0xFFFFFFFF; + NRF_I2S->PSEL.LRCK = 0xFFFFFFFF; + NRF_I2S->PSEL.SDOUT = 0xFFFFFFFF; + NRF_I2S->PSEL.SDIN = 0xFFFFFFFF; + if (self->external_clock) { + nrf_gpio_cfg_default(self->bit_clock_pin_number); + nrf_gpio_cfg_default(self->word_select_pin_number); + } reset_pin_number(self->bit_clock_pin_number); self->bit_clock_pin_number = NO_PIN; reset_pin_number(self->word_select_pin_number); self->word_select_pin_number = NO_PIN; reset_pin_number(self->data_pin_number); - self->data_pin_number = NO_PIN; + mark_deinit(self); instance = NULL; supervisor_disable_tick(); } @@ -238,6 +277,8 @@ void common_hal_audiobusio_i2sout_play(audiobusio_i2sout_obj_t *self, common_hal_audiobusio_i2sout_stop(self); } + audiosample_check(sample); + self->sample = sample; self->loop = loop; uint32_t sample_rate = audiosample_get_sample_rate(sample); @@ -259,7 +300,11 @@ void common_hal_audiobusio_i2sout_play(audiobusio_i2sout_obj_t *self, ? I2S_CONFIG_CHANNELS_CHANNELS_Left : I2S_CONFIG_CHANNELS_CHANNELS_Stereo; - choose_i2s_clocking(self, sample_rate); + if (self->external_clock) { + self->sample_rate = sample_rate; + } else { + choose_i2s_clocking(self, sample_rate); + } /* Allocate buffers based on a maximum duration * This duration was chosen empirically based on what would * cause os.listdir('') to cause stuttering. It seems like a @@ -269,8 +314,8 @@ void common_hal_audiobusio_i2sout_play(audiobusio_i2sout_obj_t *self, self->buffer_length = sample_rate * buffer_length_ms * self->bytes_per_sample * self->channel_count / 1000; self->buffer_length = (self->buffer_length + 3) & ~3; - self->buffers[0] = m_malloc(self->buffer_length); - self->buffers[1] = m_malloc(self->buffer_length); + self->buffers[0] = m_malloc_without_collect(self->buffer_length); + self->buffers[1] = m_malloc_without_collect(self->buffer_length); audiosample_reset_buffer(self->sample, false, 0); @@ -280,6 +325,7 @@ void common_hal_audiobusio_i2sout_play(audiobusio_i2sout_obj_t *self, self->playing = true; self->paused = false; self->stopping = false; + self->last_buffer = false; i2s_buffer_fill(self); NRF_I2S->RXTXD.MAXCNT = self->buffer_length / 4; @@ -330,18 +376,3 @@ void i2s_background(void) { } } } - -void i2s_reset(void) { - NRF_I2S->TASKS_STOP = 1; - NRF_I2S->INTENCLR = I2S_INTENSET_TXPTRUPD_Msk; - NRF_I2S->ENABLE = I2S_ENABLE_ENABLE_Disabled; - NRF_I2S->PSEL.MCK = 0xFFFFFFFF; - NRF_I2S->PSEL.SCK = 0xFFFFFFFF; - NRF_I2S->PSEL.LRCK = 0xFFFFFFFF; - NRF_I2S->PSEL.SDOUT = 0xFFFFFFFF; - NRF_I2S->PSEL.SDIN = 0xFFFFFFFF; - if (instance) { - supervisor_disable_tick(); - } - instance = NULL; -} diff --git a/ports/nordic/common-hal/audiobusio/I2SOut.h b/ports/nordic/common-hal/audiobusio/I2SOut.h index 7cb62ae3d2b..c2bb8db62aa 100644 --- a/ports/nordic/common-hal/audiobusio/I2SOut.h +++ b/ports/nordic/common-hal/audiobusio/I2SOut.h @@ -28,13 +28,14 @@ typedef struct { uint8_t bytes_per_sample; bool left_justified : 1; + bool external_clock : 1; bool playing : 1; bool stopping : 1; + bool last_buffer : 1; bool paused : 1; bool loop : 1; bool samples_signed : 1; bool single_buffer : 1; } audiobusio_i2sout_obj_t; -void i2s_reset(void); void i2s_background(void); diff --git a/ports/nordic/common-hal/audiobusio/PDMIn.c b/ports/nordic/common-hal/audiobusio/PDMIn.c index c0cba8d08f6..6678a057ee1 100644 --- a/ports/nordic/common-hal/audiobusio/PDMIn.c +++ b/ports/nordic/common-hal/audiobusio/PDMIn.c @@ -15,6 +15,10 @@ NRF_PDM_Type *nrf_pdm = NRF_PDM; static uint32_t dummy_buffer[4]; +static void mark_deinit(audiobusio_pdmin_obj_t *self) { + self->clock_pin_number = NO_PIN; +} + // Caller validates that pins are free. void common_hal_audiobusio_pdmin_construct(audiobusio_pdmin_obj_t *self, const mcu_pin_obj_t *clock_pin, @@ -23,12 +27,9 @@ void common_hal_audiobusio_pdmin_construct(audiobusio_pdmin_obj_t *self, uint8_t bit_depth, bool mono, uint8_t oversample) { - claim_pin(clock_pin); - claim_pin(data_pin); - - self->mono = mono; - self->clock_pin_number = clock_pin->number; - self->data_pin_number = data_pin->number; + // Ensure the object starts in its deinit state, so its finaliser does + // nothing if this raises. + mark_deinit(self); if (sample_rate != 16000) { mp_raise_ValueError(MP_ERROR_TEXT("only sample_rate=16000 is supported")); @@ -36,6 +37,13 @@ void common_hal_audiobusio_pdmin_construct(audiobusio_pdmin_obj_t *self, if (bit_depth != 16) { mp_raise_ValueError(MP_ERROR_TEXT("only bit_depth=16 is supported")); } + + claim_pin(clock_pin); + claim_pin(data_pin); + + self->mono = mono; + self->clock_pin_number = clock_pin->number; + self->data_pin_number = data_pin->number; nrf_pdm->PSEL.CLK = self->clock_pin_number; nrf_pdm->PSEL.DIN = self->data_pin_number; nrf_pdm->PDMCLKCTRL = PDM_PDMCLKCTRL_FREQ_Default; // For Ratio64 @@ -54,12 +62,15 @@ bool common_hal_audiobusio_pdmin_deinited(audiobusio_pdmin_obj_t *self) { } void common_hal_audiobusio_pdmin_deinit(audiobusio_pdmin_obj_t *self) { + if (common_hal_audiobusio_pdmin_deinited(self)) { + return; + } nrf_pdm->ENABLE = 0; reset_pin_number(self->clock_pin_number); - self->clock_pin_number = NO_PIN; reset_pin_number(self->data_pin_number); self->data_pin_number = NO_PIN; + mark_deinit(self); } uint8_t common_hal_audiobusio_pdmin_get_bit_depth(audiobusio_pdmin_obj_t *self) { diff --git a/ports/nordic/common-hal/audiopwmio/PWMAudioOut.c b/ports/nordic/common-hal/audiopwmio/PWMAudioOut.c index 03e959ed139..75df88e4416 100644 --- a/ports/nordic/common-hal/audiopwmio/PWMAudioOut.c +++ b/ports/nordic/common-hal/audiopwmio/PWMAudioOut.c @@ -136,7 +136,7 @@ static void audiopwmout_background_obj(audiopwmio_pwmaudioout_obj_t *self) { } } -void audiopwmout_background() { +void audiopwmout_background(void) { // Check the NVIC first because it is part of the CPU and fast to read. if (!NVIC_GetPendingIRQ(PWM0_IRQn) && !NVIC_GetPendingIRQ(PWM1_IRQn) && @@ -236,6 +236,9 @@ void common_hal_audiopwmio_pwmaudioout_play(audiopwmio_pwmaudioout_obj_t *self, if (common_hal_audiopwmio_pwmaudioout_get_playing(self)) { common_hal_audiopwmio_pwmaudioout_stop(self); } + + audiosample_check(sample); + self->sample = sample; self->loop = loop; @@ -253,13 +256,13 @@ void common_hal_audiopwmio_pwmaudioout_play(audiopwmio_pwmaudioout_obj_t *self, size_t buffer_size = (size_t)max_buffer_length * 2 * sizeof(uint16_t); - self->buffers[0] = m_malloc(buffer_size); + self->buffers[0] = m_malloc_without_collect(buffer_size); #if MICROPY_MALLOC_USES_ALLOCATED_SIZE self->buffer_size[0] = buffer_size; #endif if (!self->single_buffer) { - self->buffers[1] = m_malloc(buffer_size); + self->buffers[1] = m_malloc_without_collect(buffer_size); #if MICROPY_MALLOC_USES_ALLOCATED_SIZE self->buffer_size[1] = buffer_size; #endif diff --git a/ports/nordic/common-hal/busio/I2C.c b/ports/nordic/common-hal/busio/I2C.c index 3558fad165b..cdcfc293abe 100644 --- a/ports/nordic/common-hal/busio/I2C.c +++ b/ports/nordic/common-hal/busio/I2C.c @@ -41,24 +41,18 @@ static twim_peripheral_t twim_peripherals[] = { #endif }; - -void common_hal_busio_i2c_never_reset(busio_i2c_obj_t *self) { - never_reset_pin_number(self->scl_pin_number); - never_reset_pin_number(self->sda_pin_number); -} - -static uint8_t twi_error_to_mp(const nrfx_err_t err) { +static mp_negative_errno_t twi_error_to_mp(const nrfx_err_t err) { switch (err) { case NRFX_ERROR_DRV_TWI_ERR_ANACK: - return MP_ENODEV; + return -MP_ENODEV; case NRFX_ERROR_BUSY: - return MP_EBUSY; + return -MP_EBUSY; case NRFX_ERROR_INVALID_ADDR: case NRFX_ERROR_DRV_TWI_ERR_DNACK: case NRFX_ERROR_DRV_TWI_ERR_OVERRUN: - return MP_EIO; + return -MP_EIO; case NRFX_ERROR_TIMEOUT: - return MP_ETIMEDOUT; + return -MP_ETIMEDOUT; default: break; } @@ -258,9 +252,9 @@ static nrfx_err_t _twim_xfer_with_timeout(busio_i2c_obj_t *self, nrfx_twim_xfer_ } } -static uint8_t _common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, const uint8_t *data, size_t len, bool stopBit) { +static mp_negative_errno_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) { - return common_hal_busio_i2c_probe(self, addr) ? 0 : MP_ENODEV; + return common_hal_busio_i2c_probe(self, addr) ? 0 : -MP_ENODEV; } nrfx_err_t err = NRFX_SUCCESS; @@ -286,11 +280,11 @@ static uint8_t _common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, return twi_error_to_mp(err); } -uint8_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, const uint8_t *data, size_t len) { +mp_negative_errno_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, const uint8_t *data, size_t len) { return _common_hal_busio_i2c_write(self, addr, data, len, true); } -uint8_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t addr, uint8_t *data, size_t len) { +mp_negative_errno_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t addr, uint8_t *data, size_t len) { if (len == 0) { return 0; } @@ -317,9 +311,9 @@ uint8_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t addr, uint8_t return twi_error_to_mp(err); } -uint8_t common_hal_busio_i2c_write_read(busio_i2c_obj_t *self, uint16_t addr, +mp_negative_errno_t common_hal_busio_i2c_write_read(busio_i2c_obj_t *self, uint16_t addr, uint8_t *out_data, size_t out_len, uint8_t *in_data, size_t in_len) { - uint8_t result = _common_hal_busio_i2c_write(self, addr, out_data, out_len, false); + mp_negative_errno_t result = _common_hal_busio_i2c_write(self, addr, out_data, out_len, false); if (result != 0) { return result; } diff --git a/ports/nordic/common-hal/busio/SPI.c b/ports/nordic/common-hal/busio/SPI.c index 8af4c5f4e83..24d04e685e4 100644 --- a/ports/nordic/common-hal/busio/SPI.c +++ b/ports/nordic/common-hal/busio/SPI.c @@ -14,6 +14,10 @@ #include "nrfx_spim.h" #include "nrf_gpio.h" +#if CIRCUITPY_EMMCIO +#include "common-hal/emmcio/EMMC.h" +#endif + #ifndef NRFX_SPIM3_ENABLED #define NRFX_SPIM3_ENABLED (0) #endif @@ -59,34 +63,10 @@ static const spim_peripheral_t spim_peripherals[] = { #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; -void spi_reset(void) { - for (size_t i = 0; i < MP_ARRAY_SIZE(spim_peripherals); i++) { - if (never_reset[i]) { - continue; - } - nrfx_spim_uninit(&spim_peripherals[i].spim); - } -} - -void common_hal_busio_spi_never_reset(busio_spi_obj_t *self) { - for (size_t i = 0; i < MP_ARRAY_SIZE(spim_peripherals); i++) { - if (self->spim_peripheral == &spim_peripherals[i]) { - never_reset[i] = true; - - never_reset_pin_number(self->clock_pin_number); - never_reset_pin_number(self->MOSI_pin_number); - never_reset_pin_number(self->MISO_pin_number); - break; - } - } -} - // Convert frequency to clock-speed-dependent value. Choose the next lower baudrate if in between // available baudrates. static nrf_spim_frequency_t baudrate_to_spim_frequency(const uint32_t baudrate) { @@ -125,6 +105,9 @@ static nrf_spim_frequency_t baudrate_to_spim_frequency(const uint32_t baudrate) 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, bool half_duplex) { + // Ensure the object starts in its deinit state. + common_hal_busio_spi_mark_deinit(self); + if (half_duplex) { mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_half_duplex); } @@ -132,6 +115,11 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, const mcu_pin_obj_t * // 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++) { + #if CIRCUITPY_EMMCIO + if (spim_peripherals[i].spim.p_reg == NRF_SPIM3 && emmcio_spim3_in_use()) { + continue; + } + #endif if ((spim_peripherals[i].spim.p_reg->ENABLE & SPIM_ENABLE_ENABLE_Msk) == 0) { self->spim_peripheral = &spim_peripherals[i]; break; @@ -178,6 +166,10 @@ bool common_hal_busio_spi_deinited(busio_spi_obj_t *self) { return self->clock_pin_number == NO_PIN; } +void common_hal_busio_spi_mark_deinit(busio_spi_obj_t *self) { + self->clock_pin_number = NO_PIN; +} + void common_hal_busio_spi_deinit(busio_spi_obj_t *self) { if (common_hal_busio_spi_deinited(self)) { return; @@ -188,6 +180,8 @@ void common_hal_busio_spi_deinit(busio_spi_obj_t *self) { reset_pin_number(self->clock_pin_number); reset_pin_number(self->MOSI_pin_number); reset_pin_number(self->MISO_pin_number); + + common_hal_busio_spi_mark_deinit(self); } bool common_hal_busio_spi_configure(busio_spi_obj_t *self, uint32_t baudrate, uint8_t polarity, uint8_t phase, uint8_t bits) { diff --git a/ports/nordic/common-hal/busio/SPI.h b/ports/nordic/common-hal/busio/SPI.h index 7bfddd9625d..3260c5c27de 100644 --- a/ports/nordic/common-hal/busio/SPI.h +++ b/ports/nordic/common-hal/busio/SPI.h @@ -23,5 +23,3 @@ typedef struct { uint8_t MOSI_pin_number; uint8_t MISO_pin_number; } busio_spi_obj_t; - -void spi_reset(void); diff --git a/ports/nordic/common-hal/busio/UART.c b/ports/nordic/common-hal/busio/UART.c index c9b0024db92..82a399de91d 100644 --- a/ports/nordic/common-hal/busio/UART.c +++ b/ports/nordic/common-hal/busio/UART.c @@ -36,8 +36,6 @@ static nrfx_uarte_t nrfx_uartes[] = { #endif }; -static bool never_reset[NRFX_UARTE0_ENABLED + NRFX_UARTE1_ENABLED]; - static uint32_t get_nrf_baud(uint32_t baudrate) { static const struct { @@ -111,28 +109,9 @@ static void uart_callback_irq(const nrfx_uarte_event_t *event, void *context) { } } -void uart_reset(void) { - for (size_t i = 0; i < MP_ARRAY_SIZE(nrfx_uartes); i++) { - if (never_reset[i]) { - continue; - } - nrfx_uarte_uninit(&nrfx_uartes[i]); - } -} - -void common_hal_busio_uart_never_reset(busio_uart_obj_t *self) { - // Don't never reset objects on the heap. - if (gc_alloc_possible() && gc_nbytes(self) > 0) { - return; - } - for (size_t i = 0; i < MP_ARRAY_SIZE(nrfx_uartes); i++) { - if (self->uarte == &nrfx_uartes[i]) { - never_reset[i] = true; - break; - } - } - never_reset_pin_number(self->tx_pin_number); - never_reset_pin_number(self->rx_pin_number); +// Mark the object deinited. A zeroed object also reads as deinited. +static void mark_deinit(busio_uart_obj_t *self) { + self->uarte = NULL; } void common_hal_busio_uart_construct(busio_uart_obj_t *self, @@ -143,33 +122,37 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, mp_float_t timeout, uint16_t receiver_buffer_size, byte *receiver_buffer, bool sigint_enabled) { + // Ensure the object starts in its deinit state, so its finaliser does + // nothing if this raises before the UART is set up. + mark_deinit(self); + mp_arg_validate_int(bits, 8, MP_QSTR_bits); if ((rs485_dir != NULL) || (rs485_invert)) { mp_raise_NotImplementedError(MP_ERROR_TEXT("RS485")); } + // shared-bindings checks that TX and RX are not both None, so we don't need to check here. + + mp_arg_validate_int_min(receiver_buffer_size, 1, MP_QSTR_receiver_buffer_size); + + if (parity == BUSIO_UART_PARITY_ODD) { + mp_raise_ValueError(MP_ERROR_TEXT("Odd parity is not supported")); + } + // Find a free UART peripheral. - self->uarte = NULL; + nrfx_uarte_t *uarte = NULL; 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]; + uarte = &nrfx_uartes[i]; break; } } - if (self->uarte == NULL) { + if (uarte == NULL) { mp_raise_ValueError(MP_ERROR_TEXT("All UART peripherals are in use")); } - // shared-bindings checks that TX and RX are not both None, so we don't need to check here. - - mp_arg_validate_int_min(receiver_buffer_size, 1, MP_QSTR_receiver_buffer_size); - - if (parity == BUSIO_UART_PARITY_ODD) { - mp_raise_ValueError(MP_ERROR_TEXT("Odd parity is not supported")); - } - bool hwfc = rts != NULL || cts != NULL; nrfx_uarte_config_t config = { @@ -182,28 +165,35 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, .interrupt_priority = NRFX_UARTE_DEFAULT_CONFIG_IRQ_PRIORITY, .hal_cfg = { .hwfc = hwfc ? NRF_UARTE_HWFC_ENABLED : NRF_UARTE_HWFC_DISABLED, - .parity = (parity == BUSIO_UART_PARITY_NONE) ? NRF_UARTE_PARITY_EXCLUDED : NRF_UARTE_PARITY_INCLUDED + .parity = (parity == BUSIO_UART_PARITY_NONE) ? NRF_UARTE_PARITY_EXCLUDED : NRF_UARTE_PARITY_INCLUDED, + .stop = (stop == 2 ? NRF_UARTE_STOP_TWO : NRF_UARTE_STOP_ONE), } }; - _VERIFY_ERR(nrfx_uarte_init(self->uarte, &config, uart_callback_irq)); - - // Init buffer for rx + // Init buffer for rx. Allocate it before the UARTE is enabled, in case the allocate fails. if (rx != NULL) { // Use the provided buffer when given. if (receiver_buffer != NULL) { ringbuf_init(&self->ringbuf, receiver_buffer, receiver_buffer_size); } else { if (!ringbuf_alloc(&self->ringbuf, receiver_buffer_size)) { - nrfx_uarte_uninit(self->uarte); m_malloc_fail(receiver_buffer_size); } } + } + + _VERIFY_ERR(nrfx_uarte_init(uarte, &config, uart_callback_irq)); + if (rx != NULL) { self->rx_pin_number = rx->number; claim_pin(rx); + } else { + self->rx_pin_number = NO_PIN; } + // The object is live from here. + self->uarte = uarte; + if (tx != NULL) { self->tx_pin_number = tx->number; claim_pin(tx); @@ -235,7 +225,7 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, } bool common_hal_busio_uart_deinited(busio_uart_obj_t *self) { - return self->rx_pin_number == NO_PIN; + return self->uarte == NULL; } void common_hal_busio_uart_deinit(busio_uart_obj_t *self) { @@ -250,13 +240,7 @@ void common_hal_busio_uart_deinit(busio_uart_obj_t *self) { self->rts_pin_number = NO_PIN; self->cts_pin_number = NO_PIN; ringbuf_deinit(&self->ringbuf); - - for (size_t i = 0; i < MP_ARRAY_SIZE(nrfx_uartes); i++) { - if (self->uarte == &nrfx_uartes[i]) { - never_reset[i] = false; - break; - } - } + mark_deinit(self); } } @@ -325,7 +309,7 @@ size_t common_hal_busio_uart_write(busio_uart_obj_t *self, const uint8_t *data, if (!nrfx_is_in_ram(data)) { // Allocate long strings on the heap. if (len > 128 && gc_alloc_possible()) { - tx_buf = (uint8_t *)m_malloc(len); + tx_buf = (uint8_t *)m_malloc_without_collect(len); } else { tx_buf = alloca(len); } @@ -346,7 +330,7 @@ size_t common_hal_busio_uart_write(busio_uart_obj_t *self, const uint8_t *data, RUN_BACKGROUND_TASKS; } - if (!nrfx_is_in_ram(data) && gc_alloc_possible() && gc_nbytes(tx_buf) > 0) { + if (!nrfx_is_in_ram(data) && gc_alloc_possible() && gc_ptr_on_heap(tx_buf)) { gc_free(tx_buf); } diff --git a/ports/nordic/common-hal/busio/UART.h b/ports/nordic/common-hal/busio/UART.h index 10e881ced5a..6af34a565cd 100644 --- a/ports/nordic/common-hal/busio/UART.h +++ b/ports/nordic/common-hal/busio/UART.h @@ -29,5 +29,3 @@ typedef struct { uint8_t cts_pin_number; uint8_t rts_pin_number; } busio_uart_obj_t; - -void uart_reset(void); diff --git a/ports/nordic/common-hal/countio/Counter.c b/ports/nordic/common-hal/countio/Counter.c index fdb86fc5046..fbae2569842 100644 --- a/ports/nordic/common-hal/countio/Counter.c +++ b/ports/nordic/common-hal/countio/Counter.c @@ -23,11 +23,15 @@ static void _intr_handler(nrfx_gpiote_pin_t pin, nrf_gpiote_polarity_t action) { self->count += 1; } +static void mark_deinit(countio_counter_obj_t *self) { + self->pin = NO_PIN; +} + void common_hal_countio_counter_construct(countio_counter_obj_t *self, const mcu_pin_obj_t *pin, countio_edge_t edge, digitalio_pull_t pull) { - - self->pin = pin->number; - _countio_objs[self->pin] = self; + // Ensure the object starts in its deinit state, so its finaliser does + // nothing if this raises before the pin is set. + mark_deinit(self); self->count = 0; @@ -65,10 +69,13 @@ void common_hal_countio_counter_construct(countio_counter_obj_t *self, .skip_gpio_setup = false, }; - nrfx_err_t err = nrfx_gpiote_in_init(self->pin, &cfg, _intr_handler); + nrfx_err_t err = nrfx_gpiote_in_init(pin->number, &cfg, _intr_handler); if (err != NRFX_SUCCESS) { mp_raise_RuntimeError(MP_ERROR_TEXT("All channels in use")); } + // Set the pin only now, after success to avoid out-of-bounds writes in nrfx_gpiote_in_uninit(). + self->pin = pin->number; + _countio_objs[self->pin] = self; nrfx_gpiote_in_event_enable(self->pin, true); claim_pin(pin); @@ -87,7 +94,7 @@ void common_hal_countio_counter_deinit(countio_counter_obj_t *self) { nrfx_gpiote_in_event_disable(self->pin); nrfx_gpiote_in_uninit(self->pin); reset_pin_number(self->pin); - self->pin = NO_PIN; + mark_deinit(self); } mp_int_t common_hal_countio_counter_get_count(countio_counter_obj_t *self) { diff --git a/ports/nordic/common-hal/digitalio/DigitalInOut.c b/ports/nordic/common-hal/digitalio/DigitalInOut.c index 58205c9b992..a302c94bcc5 100644 --- a/ports/nordic/common-hal/digitalio/DigitalInOut.c +++ b/ports/nordic/common-hal/digitalio/DigitalInOut.c @@ -9,11 +9,6 @@ #include "nrf_gpio.h" -void common_hal_digitalio_digitalinout_never_reset( - 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) { claim_pin(pin); diff --git a/ports/nordic/common-hal/emmcio/EMMC.c b/ports/nordic/common-hal/emmcio/EMMC.c new file mode 100644 index 00000000000..a7d1fc40231 --- /dev/null +++ b/ports/nordic/common-hal/emmcio/EMMC.c @@ -0,0 +1,1013 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// ============================================================================ +// eMMC flash driver (1-bit MMC protocol over the nRF52840) +// ============================================================================ +// Two layers: +// +// * COMMAND / control phases (init, CMD17/18 headers, busy polling) are +// bit-banged on GPIO. They are short and timing-insensitive. +// +// * The 512-byte DATA payloads ride SPIM3 + EasyDMA at 16 MHz. eMMC DAT0 at +// default speed is SPI-mode-0 compatible: the host launches data while +// CLK is low, the card samples (and launches) on the rising edge, MSB +// first. The start-bit hunt is bit-banged, then the payload + CRC16 is +// exactly byte-aligned for one RX DMA; on ENABLE=0 the pins fall back to +// their GPIO latches. +// +// INTEGRITY: every block read is verified against the card's CRC16 and the +// caller retries on a mismatch. +// +// ============================================================================ + +#include "common-hal/emmcio/EMMC.h" +#include "common-hal/emmcio/emmc_hw.h" + +#include + +#include "extmod/vfs.h" // MP_BLOCKDEV_IOCTL_* +#include "lib/sdmmc/include/sdmmc_defs.h" // MMC_* command numbers +#include "py/mphal.h" +#include "py/runtime.h" // RUN_BACKGROUND_TASKS +#include "shared-bindings/microcontroller/__init__.h" +#include "common-hal/microcontroller/Pin.h" +#include "peripherals/nrf/nrf52840/pins.h" +#include "shared-module/emmcio/__init__.h" + +#define CMD_SAFE_HALF_US 1u + +// Command-phase half-period: starts slow, switched to 0 (full-speed) after init. +static uint32_t s_cmd_half_us = CMD_SAFE_HALF_US; + +static volatile uint32_t g_emmc_clk_half_us = CMD_SAFE_HALF_US; + + +static bool s_ready; +static uint32_t s_rca; +static uint32_t s_block_count; // from EXT_CSD SEC_COUNT; 0 = not read yet +static uint8_t s_device_type; // from EXT_CSD[196]; 0 = not read yet + +// One 512-byte block + its CRC16, byte-aligned, for the RX DMA. +static uint8_t s_dma_rx[EMMC_BLOCK_SIZE + 2]; + +// ---- bounded-wait helpers -------------------------------------------------- +// The 32768 Hz counter is 24-bit, so every elapsed calculation masks. +#define US_TO_TICKS(us) ((uint32_t)(((uint64_t)(us) * EMMC_TICKS_HZ + 999999u) / 1000000u)) + +static inline uint32_t ticks_since(uint32_t t0) { + return ticks_since_raw(t0); +} + +static inline void half_delay(uint32_t us) { + if (us) { + common_hal_mcu_delay_us(us); + } +} + +static bool s_deadline_armed; +static uint32_t s_deadline_t0; +static uint32_t s_deadline_lim; + +void common_hal_emmcio_emmc_set_deadline(uint32_t timeout_us) { + s_deadline_t0 = EMMC_TICKS(); + s_deadline_lim = US_TO_TICKS(timeout_us); + s_deadline_armed = true; +} + +void common_hal_emmcio_emmc_clear_deadline(void) { + s_deadline_armed = false; +} + +static bool emmc_deadline_expired(void) { + return s_deadline_armed && ticks_since(s_deadline_t0) >= s_deadline_lim; +} + +static inline void emmc_yield(void) { + RUN_BACKGROUND_TASKS; +} + +// Safe clock pulse for command/CRC phases. +static inline void clk_pulse(void) { + CLK_HIGH(); + half_delay(s_cmd_half_us); + CLK_LOW(); + half_delay(s_cmd_half_us); +} + +static void cmd_send_bit(uint8_t bit) { + // caller (send_command) sets CMD_OUT() once. + if (bit) { + CMD_HIGH(); + } else { + CMD_LOW(); + } + clk_pulse(); +} + +// SAMPLE POINT: read the line at the END of the low phase, i.e. before this +// bit's clock pulse, not in the middle of it. That is the one point in the +// cycle where both of the card's timing modes hold valid data. +// +// * backward-compatible timing: the card launches on the FALLING edge and +// holds the bit until the next one, so the whole low phase is valid. +// tOSU(min) = tWL(min) - tODLY, data good from ~8 ns after the edge. +// We read a full low phase later. +// * high-speed timing: the card launches on the RISING edge (tODLY, 13.7 ns +// max, referenced to it) and holds until the next rising edge. +// +static uint8_t cmd_recv_bit(void) { + // caller sets CMD_IN() once before the response read + uint8_t b = (uint8_t)READ_CMD(); + clk_pulse(); + return b; +} + +static uint8_t crc7(const uint8_t *data, uint8_t len) { + uint8_t crc = 0; + for (uint8_t i = 0; i < len; i++) { + uint8_t v = data[i]; + for (int b = 7; b >= 0; b--) { + crc <<= 1; + if (((v >> b) & 1) ^ ((crc >> 7) & 1)) { + crc ^= 0x09; + } + crc &= 0x7F; + } + } + return (crc << 1) | 1; +} + +// Table-driven CRC16-CCITT +static uint16_t s_crc16_tab[256]; +static void crc16_tab_init(void) { + for (uint32_t i = 0; i < 256; i++) { + uint16_t crc = (uint16_t)(i << 8); + for (int b = 0; b < 8; b++) { + crc = (crc & 0x8000) ? (uint16_t)((crc << 1) ^ 0x1021) : (uint16_t)(crc << 1); + } + s_crc16_tab[i] = crc; + } +} + +// The port builds at -Os, so this is an opt-up. crc16 is pure computation, +// the level can only change its speed, never its value. +__attribute__((optimize("O2"))) +static uint16_t crc16(const uint8_t *data, uint32_t len) { + uint16_t crc = 0; + for (uint32_t i = 0; i < len; i++) { + crc = (uint16_t)((crc << 8) ^ s_crc16_tab[(crc >> 8) ^ data[i]]); + } + return crc; +} + +static bool send_command(uint8_t cmd_index, uint32_t arg, uint8_t *r1_out) { + uint8_t frame[6]; + frame[0] = 0x40 | (cmd_index & 0x3F); + frame[1] = (uint8_t)(arg >> 24); + frame[2] = (uint8_t)(arg >> 16); + frame[3] = (uint8_t)(arg >> 8); + frame[4] = (uint8_t)(arg); + frame[5] = crc7(frame, 5); + + // PRE-COMMAND GAP on an UNDRIVEN line + CMD_IN(); + for (int i = 0; i < 24; i++) { + clk_pulse(); + } + CMD_OUT(); + cmd_send_bit(0); + cmd_send_bit(1); + for (int b = 5; b >= 0; b--) { + cmd_send_bit((frame[0] >> b) & 1); + } + for (int i = 1; i <= 4; i++) { + for (int b = 7; b >= 0; b--) { + cmd_send_bit((frame[i] >> b) & 1); + } + } + for (int b = 7; b >= 1; b--) { + cmd_send_bit((frame[5] >> b) & 1); + } + cmd_send_bit(1); + + CMD_IN(); + bool responded = false; + for (int t = 0; t < 200; t++) { + clk_pulse(); + if (!READ_CMD()) { + responded = true; + break; + } + } + if (!responded) { + return false; + } + + if (!r1_out) { + return true; + } + + uint8_t resp[6] = {0}; + for (int i = 0; i < 38; i++) { + uint8_t bit = cmd_recv_bit(); + resp[i / 8] |= (bit << (7 - (i % 8))); + } + memcpy(r1_out, resp, 6); + + // Leave CMD as an INPUT (pulled up) + return true; +} + +// Bit-banged MMC commands intermittently miss the response on the first try +// (settling after the previous command); retry until the card answers. +static bool send_command_retry(uint8_t cmd, uint32_t arg, uint8_t *r1_out, int tries) { + for (int t = 0; t < tries; t++) { + if (emmc_deadline_expired()) { + return false; + } + if (send_command(cmd, arg, r1_out)) { + return true; + } + if (t == 0) { + // First miss = the card still settling after the previous burst: a + // handful of idle clocks is all it needs. + for (int c = 0; c < 16; c++) { + clk_pulse(); + } + } else { + mp_hal_delay_ms(2); + } + } + return false; +} + +// DATA read: per-bit CLK toggle uses the configurable (possibly 0) half-period. +// -O2 opts up from the port's -Os default and is needed: at -Os the GPIO +// and delay helpers stop being inlined and become calls inside the per-bit +// loop, and throw off the timing +__attribute__((optimize("O2"))) +static bool read_data_block(uint8_t *buf) { + const uint32_t hd = g_emmc_clk_half_us; + const uint32_t clk_bit = emmc_pinout.clk_bit; + const uint32_t dat_bit = emmc_pinout.dat_bit; + + DAT0_IN(); + // START-BIT HUNT + { + uint32_t t0 = EMMC_TICKS(); + const uint32_t lim = US_TO_TICKS(80000u); // 80 ms bound + const uint32_t yield_at = US_TO_TICKS(500u); + bool got_start = false; + for (;;) { + // This hunt samples in the HIGH phase and stays there in both + // timing modes + for (int burst = 0; burst < 64 && !got_start; burst++) { + RCLK_HIGH(clk_bit); + half_delay(hd); + EDGE_SETTLE(); + if (!RDAT_GET(dat_bit)) { + got_start = true; // leave with RCLK HIGH (as before) + break; + } + RCLK_LOW(clk_bit); + half_delay(hd); + } + uint32_t el = ticks_since(t0); + if (got_start) { + break; + } + if (el >= lim || emmc_deadline_expired()) { + return false; + } + if (el >= yield_at) { + emmc_yield(); + } + } + } + RCLK_LOW(clk_bit); + half_delay(hd); + + // The start bit was just consumed by the bit-bang hunt above, so the + // remaining 512 data bytes + CRC16 are exactly byte-aligned. + emmc_spim_xfer(NULL, 0, s_dma_rx, sizeof(s_dma_rx)); + memcpy(buf, s_dma_rx, EMMC_BLOCK_SIZE); + uint16_t card_crc = (uint16_t)(((uint16_t)s_dma_rx[EMMC_BLOCK_SIZE] << 8) | + s_dma_rx[EMMC_BLOCK_SIZE + 1]); + RCLK_HIGH(clk_bit); + half_delay(hd); + RCLK_LOW(clk_bit); + half_delay(hd); // end bit + bool crc_ok = crc16(buf, EMMC_BLOCK_SIZE) == card_crc; + DAT0_OUT(); + RDAT_HIGH(dat_bit); + return crc_ok; // a mismatch: caller retries +} + +bool common_hal_emmcio_emmc_read_status(uint8_t *r1_out) { + return send_command_retry(13, s_rca, r1_out, 8); +} + +// Clock out an R2 response and reassemble the CID. R2 framing: start(0) + +// transmission(0) + 6 reserved ones + CID[127:1] + end(1) = 136 bits. +static void drain_r2_cid(uint8_t *cid_out) { + uint8_t bits[136]; + for (int i = 0; i < 136; i++) { + bits[i] = cmd_recv_bit(); + } + memset(cid_out, 0, 16); + for (int i = 0; i < 128; i++) { + // bits[0] start, bits[1] transmission, bits[2..7] six reserved ones, + // bits[8..134] CID[127:1], bits[135] end bit + cid_out[i / 8] |= (uint8_t)(bits[8 + i] << (7 - (i % 8))); + } +} + +#define EMMC_POWER_OFF_MS 50u + +static void emmc_power_cycle(void) { + emmc_spim_deinit(); // SPIM3 must not drive DAT0 either + emmc_pins_init(); + + RST_ASSERT(); + CLK_LOW(); + CMD_LOW(); + DAT0_OUT(); + DAT0_LOW(); + VCCQ_OFF(); + mp_hal_delay_ms(EMMC_POWER_OFF_MS); +} + +static bool emmc_init(emmcio_emmc_obj_t *self) { + s_ready = false; + s_block_count = 0; + s_device_type = 0; + g_emmc_clk_half_us = CMD_SAFE_HALF_US; + s_cmd_half_us = CMD_SAFE_HALF_US; + + self->cmd0_sent = false; + self->cmd1_retries = -1; + self->cmd2_resp = false; + self->cmd3_resp = false; + self->cmd7_resp = false; + self->cmd16_resp = false; + memset(self->cid, 0, sizeof(self->cid)); + self->hs_switch_error = false; + self->hs_active = false; + self->hs_stage = 0; + + emmc_power_cycle(); + + emmc_spim_init(); // hardware-clocked data path, at M16 + crc16_tab_init(); + + CLK_LOW(); + CMD_HIGH(); + DAT0_HIGH(); + + VCCQ_ON(); + mp_hal_delay_ms(10); + + RST_ASSERT(); + mp_hal_delay_ms(1); + RST_RELEASE(); + mp_hal_delay_ms(2); + + CMD_HIGH(); + for (int i = 0; i < 80; i++) { // 74+ clocks before the first command + clk_pulse(); + } + + send_command(0, 0x00000000, NULL); // CMD0 GO_IDLE (no response expected) + self->cmd0_sent = true; + mp_hal_delay_ms(1); + + // CMD1 SEND_OP_COND, arg 0x40FF8000: HCS=1 + uint8_t r3[6] = {0}; + for (int retry = 0; retry < 1000; retry++) { + bool ok = send_command(1, 0x40FF8000, r3); + emmc_yield(); + mp_hal_delay_ms(1); + if (ok && (r3[1] & 0x80)) { // response seen AND busy bit set = ready + self->cmd1_retries = retry; + break; + } + if (emmc_deadline_expired()) { + break; + } + } + if (self->cmd1_retries < 0) { // card never responded ready -> stop + return false; + } + + for (int t = 0; t < 8; t++) { + self->cmd2_resp = send_command(2, 0, NULL); + if (self->cmd2_resp) { + drain_r2_cid(self->cid); + break; + } + mp_hal_delay_ms(2); + } + mp_hal_delay_ms(1); + + uint8_t r6[6] = {0}; + s_rca = 0x0001u << 16; + self->cmd3_resp = send_command_retry(3, s_rca, r6, 8); // SET_RELATIVE_ADDR + mp_hal_delay_ms(1); + + uint8_t r1[6] = {0}; + self->cmd7_resp = send_command_retry(7, s_rca, r1, 8); // SELECT_CARD + mp_hal_delay_ms(1); + self->cmd16_resp = send_command_retry(16, EMMC_BLOCK_SIZE, r1, 8); // SET_BLOCKLEN + mp_hal_delay_ms(1); + + // strict: ready only if the card actually selected AND accepted block length + s_ready = self->cmd7_resp && self->cmd16_resp; + if (s_ready) { + s_cmd_half_us = 0u; // identification done: full-speed commands + g_emmc_clk_half_us = 0u; + } + return s_ready; +} + +uint32_t common_hal_emmcio_emmc_get_block_count(emmcio_emmc_obj_t *self) { + (void)self; + return s_block_count; +} + +// The block-device ioctl +bool common_hal_emmcio_emmc_ioctl(uint32_t op, uint32_t arg, uint32_t *out_value) { + (void)arg; + *out_value = 0; + switch (op) { + case MP_BLOCKDEV_IOCTL_INIT: + // The constructor already did the whole CMD0..CMD16 + EXT_CSD + // walk, or raised. 0 means "initialised"; a card that has since + // been deinited answers with the error the callers check for + // (s_ready), so a mount over a dead object fails at INIT rather + // than at the first read. + *out_value = s_ready ? 0u : 1u; + break; + case MP_BLOCKDEV_IOCTL_DEINIT: + case MP_BLOCKDEV_IOCTL_SYNC: + case MP_BLOCKDEV_IOCTL_BLOCK_ERASE: + break; + case MP_BLOCKDEV_IOCTL_BLOCK_COUNT: + *out_value = s_block_count; + break; + case MP_BLOCKDEV_IOCTL_BLOCK_SIZE: + *out_value = EMMC_BLOCK_SIZE; + break; + default: + return false; + } + return true; +} + +// Power-off: release the bus pins and cut the VCCQ I/O rail. +// The card is gone until the next emmc_init(). +static void emmc_power_down(void) { + s_ready = false; + s_block_count = 0; + emmc_spim_deinit(); + RST_ASSERT(); + emmc_pins_release(); + VCCQ_OFF(); // rail off (pin stays an output) +} + +// CMD8 SEND_EXT_CSD: an ADTC (read) command -- the card responds R1, then +// sends a single 512-byte EXT_CSD data block on DAT0 exactly like CMD17. +// Read-only and safe. buf must be >= EMMC_BLOCK_SIZE. +bool common_hal_emmcio_emmc_read_ext_csd(uint8_t *buf) { + if (!s_ready) { + return false; + } + uint8_t r1[6]; + if (!send_command_retry(8, 0, r1, 8)) { + return false; + } + if (!read_data_block(buf)) { + return false; + } + // SEC_COUNT[215:212], little-endian. 0x00760000 on this part = 7,733,248 + // blocks; the value is the software LBA bound for every later read. + s_block_count = (uint32_t)buf[212] | ((uint32_t)buf[213] << 8) | + ((uint32_t)buf[214] << 16) | ((uint32_t)buf[215] << 24); + // DEVICE_TYPE[196] gates the HS_TIMING switch (bit 1 = 52 MHz supported; + // this part reads 0x57). + s_device_type = buf[196]; + return true; +} + +// ---- R1b / program busy on DAT0 -------------------------------------------- +// Shared by the CMD6 switch (below) and the write path (further down): the +// card pulls DAT0 low while it programs and releases it high when done, and it +// only advances on OUR clock, so the host must keep clocking for the card to +// get anywhere. + +#define EMMC_BUSY_LEADIN_CLOCKS 16 + +static bool dat0_busy_wait(uint32_t timeout_us, bool run_bg) { + DAT0_IN(); // never drive against a busy card + for (int i = 0; i < EMMC_BUSY_LEADIN_CLOCKS; i++) { + clk_pulse(); + } + uint32_t t0 = EMMC_TICKS(); + const uint32_t lim = US_TO_TICKS(timeout_us); + for (;;) { + bool released = false; + for (int i = 0; i < 64 && !released; i++) { + CLK_HIGH(); + half_delay(s_cmd_half_us); + released = READ_DAT0() != 0; + CLK_LOW(); + half_delay(s_cmd_half_us); + } + uint32_t el = ticks_since(t0); + if (released) { + DAT0_OUT(); // back to the read path's resting state + DAT0_HIGH(); + return true; + } + if (el >= lim || emmc_deadline_expired()) { + // DAT0 STAYS AN INPUT on a timeout + return false; + } + if (run_bg) { + emmc_yield(); + } + } +} + +// CMD6 SWITCH argument: access 0b11 (WRITE_BYTE) | index 185 | value 1 | +// cmd_set 0 -> 0x03 B9 01 00. +#define EMMC_SWITCH_HS_TIMING_ARG 0x03B90100u +#define EMMC_EXT_CSD_HS_TIMING 185u +#define EMMC_EXT_CSD_DEVICE_TYPE 196u +#define EMMC_DEVICE_TYPE_HS52 0x02u + +// GENERIC_CMD6_TIME on this part is 0x05 = 50 ms. Ten times that is the bound. +#define EMMC_CMD6_BUSY_US 500000u + +// Poll CMD13 until the card is back in tran and ready for data. This is the +// authoritative "the switch finished" test, and it is also where SWITCH_ERROR +// (status bit 7) shows up if the card rejected the write. +static bool wait_tran_after_switch(emmcio_emmc_obj_t *self, uint32_t timeout_us) { + uint32_t t0 = EMMC_TICKS(); + const uint32_t lim = US_TO_TICKS(timeout_us); + for (;;) { + uint8_t r1[6]; + if (common_hal_emmcio_emmc_read_status(r1)) { + uint32_t status = ((uint32_t)r1[1] << 24) | ((uint32_t)r1[2] << 16) | + ((uint32_t)r1[3] << 8) | (uint32_t)r1[4]; + if (status & (1u << 7)) { // SWITCH_ERROR: the card said no + self->hs_switch_error = true; + return false; + } + if (((status >> 9) & 0xFu) == 4u && ((status >> 8) & 1u)) { + return true; // tran + ready_for_data + } + } + if (ticks_since(t0) >= lim || emmc_deadline_expired()) { + return false; + } + emmc_yield(); + mp_hal_delay_ms(1); + } +} + +static bool emmc_set_high_speed(emmcio_emmc_obj_t *self) { + if (!s_ready) { + return false; + } + // Gate on the card's own capability byte. + if (!(s_device_type & EMMC_DEVICE_TYPE_HS52)) { + return false; + } + self->hs_stage = 1; + + uint8_t r1[6]; + if (!send_command_retry(6, EMMC_SWITCH_HS_TIMING_ARG, r1, 8)) { + return false; + } + self->hs_stage = 2; + // run_bg = true: a CMD6 on a volatile byte has no in-flight card state a + // power-off gesture could damage, so this wait services them as the read + // path does. + if (!dat0_busy_wait(EMMC_CMD6_BUSY_US, true)) { + return false; + } + self->hs_stage = 3; + if (!wait_tran_after_switch(self, EMMC_CMD6_BUSY_US)) { + return false; + } + self->hs_stage = 4; + + + NRF_SPIM3->CONFIG = SPIM_CONFIG_MODE1; + + // Read the byte back AT THE OLD CLOCK. + uint8_t ext_csd[EMMC_BLOCK_SIZE]; + if (!common_hal_emmcio_emmc_read_ext_csd(ext_csd) || + ext_csd[EMMC_EXT_CSD_HS_TIMING] != 1u) { + NRF_SPIM3->CONFIG = SPIM_CONFIG_MODE0; + return false; // still at M16, card still readable + } + self->hs_stage = 5; + + // Now host clock moves. The re-read is a smoke test of the + // faster bus with the integrity layer watching. + NRF_SPIM3->FREQUENCY = SPIM_FREQ_M32; + if (!common_hal_emmcio_emmc_read_ext_csd(ext_csd) || ext_csd[EMMC_EXT_CSD_HS_TIMING] != 1u) { + // Back to the old CLOCK but NOT to the old phase: the card is in + // high-speed timing and stays there until the rail drops, and + // high-speed timing is specified from 0 Hz up. Mode 1 is how we talk + // to it at M16 now. + NRF_SPIM3->FREQUENCY = SPIM_FREQ_M16; + return false; + } + self->hs_active = true; + self->hs_stage = 6; + return true; +} + +bool common_hal_emmcio_emmc_readblocks(uint32_t block_addr, uint8_t *buf, uint32_t count) { + if (!s_ready || count == 0) { + return false; + } + // Reject an out-of-range LBA before any command reaches the card + if (s_block_count != 0 && + (block_addr >= s_block_count || count > s_block_count - block_addr)) { + return false; + } + uint8_t r1[6]; + if (count == 1) { + if (!send_command_retry(17, block_addr, r1, 8)) { + return false; + } + return read_data_block(buf); + } + // RETRY like CMD17 above: at high bus duty the card intermittently misses + // the first command after the previous burst's CMD12 + if (!send_command_retry(18, block_addr, r1, 4)) { + return false; + } + + uint32_t bt0 = EMMC_TICKS(); + const uint32_t blim = US_TO_TICKS(150000u); + for (uint32_t i = 0; i < count; i++) { + if (i && (ticks_since(bt0) >= blim || emmc_deadline_expired())) { + (void)send_command_retry(12, 0, r1, 3); + return false; + } + if (!read_data_block(buf + i * EMMC_BLOCK_SIZE)) { + (void)send_command_retry(12, 0, r1, 3); + return false; + } + } + (void)send_command_retry(12, 0, r1, 3); + return true; +} + +// The card declares MIN_PERF_W_* = 0x00: no minimum write performance +#define EMMC_WR_BUSY_US 500000u +// Same shape as the read side +#define EMMC_WR_BURST_US 250000u + +// -Os states the intent for this bit-bang, but matches the port default and so +// changes nothing today. +__attribute__((optimize("Os"))) +static bool write_data_block(const uint8_t *buf) { + const uint32_t hd = g_emmc_clk_half_us; + const uint32_t clk_bit = emmc_pinout.clk_bit; + const uint32_t dat_bit = emmc_pinout.dat_bit; + + // Write convention: change DAT0 while CLK is LOW, then a full half-period + // of setup before the rising edge where the card latches it. DAT0 is a + // HIGH-DRIVE (H0H1) output. + // + // The frame opens with DAT0 idle-HIGH for a whole byte (the Nwr gap) so + // the card cannot mistake a stray low for an early start bit and misframe + // the token. + DAT0_OUT(); + RDAT_HIGH(dat_bit); + + uint8_t *tx = EMMC_TX_FRAME; // the reserved low-RAM SPIM3 buffer + uint16_t crc = crc16(buf, EMMC_BLOCK_SIZE); + tx[0] = 0xFF; // Nwr idle gap + tx[1] = 0xFE; // 7 idle bits + START 0 + memcpy(&tx[2], buf, EMMC_BLOCK_SIZE); + tx[2 + EMMC_BLOCK_SIZE] = (uint8_t)(crc >> 8); + tx[2 + EMMC_BLOCK_SIZE + 1] = (uint8_t)crc; + RCLK_LOW(clk_bit); + + const uint32_t saved_cfg = NRF_SPIM3->CONFIG; + if (saved_cfg != SPIM_CONFIG_MODE0) { + NRF_SPIM3->CONFIG = SPIM_CONFIG_MODE0; + } + // The TX frame ends exactly at the crc's last bit, no trailing idle + // byte. The card emits its CRC-status token a couple of clocks after the + // end bit. + emmc_spim_xfer(tx, 2u + EMMC_BLOCK_SIZE + 2u, NULL, 0); + if (saved_cfg != SPIM_CONFIG_MODE0) { + NRF_SPIM3->CONFIG = saved_cfg; + } + // END bit: DAT0 is back at its GPIO latch (output HIGH) -- clock it. + half_delay(hd); + EDGE_SETTLE(); + RCLK_HIGH(clk_bit); + half_delay(hd); + RCLK_LOW(clk_bit); + + // CRC-status token: the card drives DAT0 low (start bit), then 3 status + // bits -- 010 accepted, 101 CRC error, 110 write error -- then releases. + DAT0_IN(); + int wr_status = -1; + for (int i = 0; i < 16; i++) { + RCLK_HIGH(clk_bit); + half_delay(hd); + EDGE_SETTLE(); + int start = (int)RDAT_GET(dat_bit); + RCLK_LOW(clk_bit); + half_delay(hd); + if (!start) { + int st = 0; + for (int k = 0; k < 3; k++) { + RCLK_HIGH(clk_bit); + half_delay(hd); + EDGE_SETTLE(); + st = (st << 1) | (int)RDAT_GET(dat_bit); + RCLK_LOW(clk_bit); + half_delay(hd); + } + wr_status = st; + break; + } + } + + // Programming busy on DAT0 + if (!dat0_busy_wait(EMMC_WR_BUSY_US, false)) { + return false; // DAT0 left an INPUT -- see the wait + } + + // ENFORCE the token: 0b010 = accepted. Anything else means the card did + // not take the block. + if (wr_status != 0x2) { + return false; + } + return true; +} + +bool common_hal_emmcio_emmc_writeblocks(uint32_t block_addr, const uint8_t *buf, uint32_t count) { + if (!s_ready || count == 0) { + return false; + } + if (s_block_count != 0 && + (block_addr >= s_block_count || count > s_block_count - block_addr)) { + return false; + } + uint8_t r1[6]; + if (count == 1) { + if (!send_command_retry(24, block_addr, r1, 8)) { + return false; + } + return write_data_block(buf); + } + // Settle-miss retry, exactly as CMD18: at high bus duty the card + // intermittently misses the first command after the previous burst. + if (!send_command_retry(25, block_addr, r1, 4)) { + return false; + } + uint32_t bt0 = EMMC_TICKS(); + const uint32_t blim = US_TO_TICKS(EMMC_WR_BURST_US); + for (uint32_t i = 0; i < count; i++) { + if (i && (ticks_since(bt0) >= blim || emmc_deadline_expired())) { + (void)send_command_retry(12, 0, r1, 3); + return false; + } + if (!write_data_block(buf + i * EMMC_BLOCK_SIZE)) { + (void)send_command_retry(12, 0, r1, 3); + return false; + } + } + (void)send_command_retry(12, 0, r1, 3); + + (void)dat0_busy_wait(EMMC_WR_BUSY_US, false); + return true; +} + +uint32_t common_hal_emmcio_emmc_get_frequency(emmcio_emmc_obj_t *self) { + (void)self; + return NRF_SPIM3->FREQUENCY == SPIM_FREQ_M32 ? 32000000u : 16000000u; +} + +bool common_hal_emmcio_emmc_get_high_speed(emmcio_emmc_obj_t *self) { + return self->hs_active; +} + +const uint8_t *common_hal_emmcio_emmc_get_cid(emmcio_emmc_obj_t *self) { + return self->cid; +} + +static bool s_constructed; + +emmc_pinout_t emmc_pinout; + +static const mcu_pin_obj_t *s_claimed_pins[5]; +static size_t s_claimed_pin_count; + +bool emmcio_spim3_in_use(void) { + return s_constructed; +} + +void emmcio_emmc_release_hardware(void) { + emmc_power_down(); + for (size_t i = 0; i < s_claimed_pin_count; i++) { + reset_pin_number(s_claimed_pins[i]->number); + } + s_claimed_pin_count = 0; + s_constructed = false; +} + +static void emmc_claim_pins(const mcu_pin_obj_t *clock, const mcu_pin_obj_t *command, + const mcu_pin_obj_t *data, const mcu_pin_obj_t *reset, const mcu_pin_obj_t *vccq) { + emmc_pinout.clk = clock->number; + emmc_pinout.cmd = command->number; + emmc_pinout.dat0 = data->number; + emmc_pinout.rst = reset != NULL ? reset->number : EMMC_NO_PIN; + emmc_pinout.vccq = vccq != NULL ? vccq->number : EMMC_NO_PIN; + emmc_pinout.clk_bit = 1u << clock->number; + emmc_pinout.dat_bit = 1u << data->number; + emmc_pinout.dat0_cnf = &NRF_P0->PIN_CNF[data->number]; + emmc_pinout.dat0_cnf_in = EMMC_CNF_IN; + emmc_pinout.dat0_cnf_out = EMMC_CNF_OUT_H0H1; + + s_claimed_pin_count = 0; + const mcu_pin_obj_t *pins[] = { clock, command, data, reset, vccq }; + for (size_t i = 0; i < MP_ARRAY_SIZE(pins); i++) { + if (pins[i] == NULL) { + continue; + } + claim_pin(pins[i]); + s_claimed_pins[s_claimed_pin_count++] = pins[i]; + } +} + +static emmcio_construct_result_t emmc_check_pins(const mcu_pin_obj_t *clock, + const mcu_pin_obj_t *command, const mcu_pin_obj_t *data, + const mcu_pin_obj_t *reset, const mcu_pin_obj_t *vccq, int *detail) { + // The data path drives CLK and DAT0 through NRF_P0 directly, so both have + // to be on port 0. CMD, RESET and VCCQ go through the HAL and may be + // anywhere. + if (clock->number >= P0_PIN_NUM) { + *detail = MP_QSTR_clock; + return EMMCIO_ERR_PIN_PORT; + } + if (data->number >= P0_PIN_NUM) { + *detail = MP_QSTR_data; + return EMMCIO_ERR_PIN_PORT; + } + if ((NRF_SPIM3->ENABLE & SPIM_ENABLE_ENABLE_Msk) != 0) { + return EMMCIO_ERR_SPI_IN_USE; + } + const mcu_pin_obj_t *pins[] = { clock, command, data, reset, vccq }; + for (size_t i = 0; i < MP_ARRAY_SIZE(pins); i++) { + if (pins[i] != NULL && !pin_number_is_free(pins[i]->number)) { + return EMMCIO_ERR_PIN_IN_USE; + } + } + return EMMCIO_OK; +} + +#define RETURN_CMD_UNLESS(cmd, done) do { if (!(done)) { return cmd; } } while (0) + +// The MMC command that never answered, so a failure names the step it stopped at. +static int init_failure_command(emmcio_emmc_obj_t *self) { + RETURN_CMD_UNLESS(MMC_GO_IDLE_STATE, self->cmd0_sent); + RETURN_CMD_UNLESS(MMC_SEND_OP_COND, self->cmd1_retries >= 0); // never left busy + RETURN_CMD_UNLESS(MMC_ALL_SEND_CID, self->cmd2_resp); + RETURN_CMD_UNLESS(MMC_SET_RELATIVE_ADDR, self->cmd3_resp); + RETURN_CMD_UNLESS(MMC_SELECT_CARD, self->cmd7_resp); + RETURN_CMD_UNLESS(MMC_SET_BLOCKLEN, self->cmd16_resp); + return MMC_SEND_EXT_CSD; +} + +#undef RETURN_CMD_UNLESS + +// How far the high-speed switch got: hs_stage as documented on the struct, +// except that a CMD13 SWITCH_ERROR (the card rejecting HS_TIMING) reports 7 to +// tell it apart from the card simply never coming back to tran. +static int hs_failure_stage(emmcio_emmc_obj_t *self) { + if (self->hs_stage == 3 && self->hs_switch_error) { + return 7; + } + return self->hs_stage; +} + +static emmcio_construct_result_t emmc_power_up(emmcio_emmc_obj_t *self, bool high_speed, + int *detail) { + s_constructed = true; + + if (!emmc_init(self)) { + *detail = init_failure_command(self); + emmcio_emmc_release_hardware(); + return EMMCIO_ERR_INIT; + } + + uint8_t ext_csd[EMMC_BLOCK_SIZE]; + if (!common_hal_emmcio_emmc_read_ext_csd(ext_csd)) { + emmcio_emmc_release_hardware(); + *detail = 8; + return EMMCIO_ERR_INIT; + } + if (high_speed && !emmc_set_high_speed(self)) { + *detail = hs_failure_stage(self); + emmcio_emmc_release_hardware(); + return EMMCIO_ERR_HIGH_SPEED; + } + return EMMCIO_OK; +} + +emmcio_construct_result_t common_hal_emmcio_emmc_construct(emmcio_emmc_obj_t *self, + const mcu_pin_obj_t *clock, const mcu_pin_obj_t *command, const mcu_pin_obj_t *data, + const mcu_pin_obj_t *reset, const mcu_pin_obj_t *vccq, + bool high_speed, bool write_enabled, int *detail) { + // Ensure the object starts in its deinit state, so its finaliser does + // nothing if construct fails. + self->deinited = true; + *detail = 0; + if (emmcio_is_automounted()) { + return EMMCIO_ERR_USB_OWNED; + } + if (s_constructed) { + return EMMCIO_ERR_IN_USE; + } + emmcio_construct_result_t pin_err = emmc_check_pins(clock, command, data, reset, vccq, detail); + if (pin_err != EMMCIO_OK) { + return pin_err; + } + emmc_claim_pins(clock, command, data, reset, vccq); + + emmcio_construct_result_t err = emmc_power_up(self, high_speed, detail); + if (err != EMMCIO_OK) { + return err; + } + + self->deinited = false; + self->write_enabled = write_enabled; + return EMMCIO_OK; +} + +void common_hal_emmcio_emmc_deinit(emmcio_emmc_obj_t *self) { + if (self->deinited) { + return; + } + emmcio_emmc_release_hardware(); + self->deinited = true; +} + +bool common_hal_emmcio_emmc_deinited(emmcio_emmc_obj_t *self) { + return self->deinited; +} + +#if CIRCUITPY_EMMC_USB + +static emmcio_emmc_obj_t s_automount_obj; +static bool s_automounted; + +mp_obj_t emmcio_automount_construct(const mcu_pin_obj_t *clock, const mcu_pin_obj_t *command, + const mcu_pin_obj_t *data, const mcu_pin_obj_t *reset, const mcu_pin_obj_t *vccq, + bool high_speed, bool write_enabled) { + if (s_constructed) { + return MP_OBJ_NULL; + } + int detail; + if (emmc_check_pins(clock, command, data, reset, vccq, &detail) != EMMCIO_OK) { + return MP_OBJ_NULL; + } + emmc_claim_pins(clock, command, data, reset, vccq); + s_automount_obj.base.type = &emmcio_emmc_type; + if (emmc_power_up(&s_automount_obj, high_speed, &detail) != EMMCIO_OK) { + return MP_OBJ_NULL; + } + s_automount_obj.deinited = false; + s_automount_obj.write_enabled = write_enabled; + s_automounted = true; + return MP_OBJ_FROM_PTR(&s_automount_obj); +} + +bool emmcio_is_automounted(void) { + return s_automounted; +} + +void emmcio_automount_abandon(void) { + s_automounted = false; + s_automount_obj.deinited = true; + if (s_constructed) { + emmcio_emmc_release_hardware(); + } +} +#endif diff --git a/ports/nordic/common-hal/emmcio/EMMC.h b/ports/nordic/common-hal/emmcio/EMMC.h new file mode 100644 index 00000000000..5bd0d6316c2 --- /dev/null +++ b/ports/nordic/common-hal/emmcio/EMMC.h @@ -0,0 +1,101 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// The nRF52840 eMMC back end: the 1-bit MMC protocol (CLK/CMD/DAT0 plus RST_n +// and a VCCQ rail gate) bit-banged on GPIO, with the 512-byte data payloads +// carried by SPIM3 + EasyDMA. +// +// Only one EMMC object can exist at a time, it owns SPIM3. + +#pragma once + +#include +#include + +#include "py/obj.h" + +#include "common-hal/microcontroller/Pin.h" +#include "shared-bindings/emmcio/EMMC.h" + +typedef struct { + mp_obj_base_t base; + bool deinited; + bool write_enabled; + + + // How far bring-up got, so a failure names the step it stopped at + bool cmd0_sent; + int32_t cmd1_retries; // retries until ready; -1 = never ready + bool cmd2_resp; + bool cmd3_resp; + bool cmd7_resp; + bool cmd16_resp; + uint8_t cid[16]; // CMD2 R2 payload (CID[127:0]) + + // These stay at their zero values unless high_speed was asked for. + bool hs_switch_error; // CMD13 reported SWITCH_ERROR after the CMD6 + bool hs_active; // EXT_CSD[185] verified AND the host clock is at M32 + // How far the switch got, so the failure message names a step + // 0 not attempted, 1 DEVICE_TYPE ok, 2 CMD6 answered, 3 DAT0 released, + // 4 back in tran, 5 EXT_CSD[185] verified, 6 running at M32. + uint8_t hs_stage; +} emmcio_emmc_obj_t; + +// EMMCIO_OK on success. On failure *detail carries the code's extra number, +// which the binding turns into the exception's argument. +emmcio_construct_result_t common_hal_emmcio_emmc_construct(emmcio_emmc_obj_t *self, + const mcu_pin_obj_t *clock, const mcu_pin_obj_t *command, const mcu_pin_obj_t *data, + const mcu_pin_obj_t *reset, const mcu_pin_obj_t *vccq, + bool high_speed, bool write_enabled, int *detail); +void common_hal_emmcio_emmc_deinit(emmcio_emmc_obj_t *self); +bool common_hal_emmcio_emmc_deinited(emmcio_emmc_obj_t *self); + +bool common_hal_emmcio_emmc_readblocks(uint32_t block_addr, uint8_t *buf, uint32_t count); + +// CMD24 (count == 1) / CMD25 + CMD12 (count > 1), each block followed by the +// card's CRC-status token and its programming busy. Direct writes only: the +// card's volatile cache is never enabled, so when this returns true the data +// is in NAND and there is nothing to flush. +bool common_hal_emmcio_emmc_writeblocks(uint32_t block_addr, const uint8_t *buf, uint32_t count); + +// Block-device ioctl, taking extmod/vfs.h's MP_BLOCKDEV_IOCTL_* ops. False +// means the op is not implemented. +bool common_hal_emmcio_emmc_ioctl(uint32_t op, uint32_t arg, uint32_t *out_value); + +// CMD8 -> the 512-byte extended CSD. buf must be >= EMMC_BLOCK_SIZE. +bool common_hal_emmcio_emmc_read_ext_csd(uint8_t *buf); + +// CMD13 SEND_STATUS -- the 6-byte R1 response. +bool common_hal_emmcio_emmc_read_status(uint8_t *r1_out); + +uint32_t common_hal_emmcio_emmc_get_block_count(emmcio_emmc_obj_t *self); // 0 until EXT_CSD has been read +uint32_t common_hal_emmcio_emmc_get_frequency(emmcio_emmc_obj_t *self); // the SPIM data-phase clock, Hz +bool common_hal_emmcio_emmc_get_high_speed(emmcio_emmc_obj_t *self); +const uint8_t *common_hal_emmcio_emmc_get_cid(emmcio_emmc_obj_t *self); // 16 bytes, CID[127:0] + +// A wall-clock budget spanning a whole sequence of driver calls, so a card +// that never answers cannot stall a caller. +void common_hal_emmcio_emmc_set_deadline(uint32_t timeout_us); +void common_hal_emmcio_emmc_clear_deadline(void); + + + +// True while a live EMMC object owns SPIM3 +bool emmcio_spim3_in_use(void); + +// Power the card down and give up its pins +void emmcio_emmc_release_hardware(void); + +#if CIRCUITPY_EMMC_USB +// Bring up the supervisor's statically allocated EMMC object. +// Returns MP_OBJ_NULL if the card cannot be brought up. +mp_obj_t emmcio_automount_construct(const mcu_pin_obj_t *clock, const mcu_pin_obj_t *command, + const mcu_pin_obj_t *data, const mcu_pin_obj_t *reset, const mcu_pin_obj_t *vccq, + bool high_speed, bool write_enabled); + +// The automount's undo, safe to call from any of its failure paths. +void emmcio_automount_abandon(void); +#endif diff --git a/ports/nordic/common-hal/emmcio/__init__.c b/ports/nordic/common-hal/emmcio/__init__.c new file mode 100644 index 00000000000..1f2cc314796 --- /dev/null +++ b/ports/nordic/common-hal/emmcio/__init__.c @@ -0,0 +1,19 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "common-hal/emmcio/EMMC.h" +#include "shared-bindings/emmcio/__init__.h" +#include "shared-module/emmcio/__init__.h" + +void emmcio_reset(void) { + // The supervisor's mount outlives the VM, so its card stays up. + if (emmcio_is_automounted()) { + return; + } + if (emmcio_spim3_in_use()) { + emmcio_emmc_release_hardware(); + } +} diff --git a/ports/nordic/common-hal/emmcio/emmc_hw.h b/ports/nordic/common-hal/emmcio/emmc_hw.h new file mode 100644 index 00000000000..6a8f9b1c88c --- /dev/null +++ b/ports/nordic/common-hal/emmcio/emmc_hw.h @@ -0,0 +1,202 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// The hardware the eMMC driver drives: the five pins, the RTC2 tick source +// and the SPIM3 data engine. + + +#pragma once + +#include +#include + +#include "nrf.h" +#include "nrf_gpio.h" + +// CLK and DAT0 must be on port 0: the data path drives them through NRF_P0 +// directly. RST and VCCQ are optional +#define EMMC_NO_PIN 0xFFu + +typedef struct { + uint8_t clk; + uint8_t cmd; + uint8_t dat0; + uint8_t rst; // active low; may be EMMC_NO_PIN + uint8_t vccq; // I/O rail gate; may be EMMC_NO_PIN + uint32_t clk_bit; // port-0 masks, for the data path's direct register use + uint32_t dat_bit; + volatile uint32_t *dat0_cnf; + uint32_t dat0_cnf_in; // input, buffer connected, pull-up + uint32_t dat0_cnf_out; // output, input disconnected, no pull, H0H1 +} emmc_pinout_t; + +#define EMMC_CNF_IN ((GPIO_PIN_CNF_DIR_Input << GPIO_PIN_CNF_DIR_Pos) | \ + (GPIO_PIN_CNF_INPUT_Connect << GPIO_PIN_CNF_INPUT_Pos) | \ + (GPIO_PIN_CNF_PULL_Pullup << GPIO_PIN_CNF_PULL_Pos) | \ + (GPIO_PIN_CNF_DRIVE_S0S1 << GPIO_PIN_CNF_DRIVE_Pos) | \ + (GPIO_PIN_CNF_SENSE_Disabled << GPIO_PIN_CNF_SENSE_Pos)) + +#define EMMC_CNF_OUT_H0H1 ((GPIO_PIN_CNF_DIR_Output << GPIO_PIN_CNF_DIR_Pos) | \ + (GPIO_PIN_CNF_INPUT_Disconnect << GPIO_PIN_CNF_INPUT_Pos) | \ + (GPIO_PIN_CNF_PULL_Disabled << GPIO_PIN_CNF_PULL_Pos) | \ + (GPIO_PIN_CNF_DRIVE_H0H1 << GPIO_PIN_CNF_DRIVE_Pos) | \ + (GPIO_PIN_CNF_SENSE_Disabled << GPIO_PIN_CNF_SENSE_Pos)) + +extern emmc_pinout_t emmc_pinout; + +static inline void emmc_opt_pin_write(uint8_t pin, bool high) { + if (pin == EMMC_NO_PIN) { + return; + } + if (high) { + nrf_gpio_pin_set(pin); + } else { + nrf_gpio_pin_clear(pin); + } +} + +static inline void emmc_opt_pin_output(uint8_t pin) { + if (pin != EMMC_NO_PIN) { + nrf_gpio_cfg_output(pin); + } +} + +// SPIM3 clock codes. +#define SPIM_FREQ_M16 0x0A000000u +#define SPIM_FREQ_M32 0x14000000u + +// SPIM3 CONFIG codes +#define SPIM_CONFIG_MODE0 0u // MSB first, CPOL0/CPHA0 +#define SPIM_CONFIG_MODE1 (1u << 1) // MSB first, CPOL0/CPHA1 + +// ---- pin control --------------------------------------------------------- +// The command/init path uses the HAL macros; the data path uses the direct +// port-0 register accesses below +#define CLK_HIGH() nrf_gpio_pin_set(emmc_pinout.clk) +#define CLK_LOW() nrf_gpio_pin_clear(emmc_pinout.clk) +#define CMD_HIGH() nrf_gpio_pin_set(emmc_pinout.cmd) +#define CMD_LOW() nrf_gpio_pin_clear(emmc_pinout.cmd) +#define DAT0_HIGH() nrf_gpio_pin_set(emmc_pinout.dat0) +#define DAT0_LOW() nrf_gpio_pin_clear(emmc_pinout.dat0) +#define DAT0_IN() (*emmc_pinout.dat0_cnf = emmc_pinout.dat0_cnf_in) +// DAT0 as a HIGH-DRIVE output (H0H1) so edges are fast and clean. +#define DAT0_OUT() (*emmc_pinout.dat0_cnf = emmc_pinout.dat0_cnf_out) +#define CMD_IN() nrf_gpio_cfg_input(emmc_pinout.cmd, NRF_GPIO_PIN_PULLUP) +#define CMD_OUT() nrf_gpio_cfg_output(emmc_pinout.cmd) +#define READ_CMD() nrf_gpio_pin_read(emmc_pinout.cmd) +#define READ_DAT0() nrf_gpio_pin_read(emmc_pinout.dat0) + +#define RCLK_HIGH(bit) (NRF_P0->OUTSET = (bit)) +#define RCLK_LOW(bit) (NRF_P0->OUTCLR = (bit)) +#define RDAT_HIGH(bit) (NRF_P0->OUTSET = (bit)) +#define RDAT_GET(bit) ((NRF_P0->IN & (bit)) != 0u) +// A few NOPs of settle after a clock edge for the delay-free (hd==0) path: +// covers the card's data-output valid time without throttling to a busy-wait. +#define EDGE_SETTLE() __asm__ volatile ("nop\nnop\nnop") + +#define RST_ASSERT() emmc_opt_pin_write(emmc_pinout.rst, false) +#define RST_RELEASE() emmc_opt_pin_write(emmc_pinout.rst, true) +#define VCCQ_ON() emmc_opt_pin_write(emmc_pinout.vccq, true) +#define VCCQ_OFF() emmc_opt_pin_write(emmc_pinout.vccq, false) + +static inline void emmc_pins_init(void) { + nrf_gpio_cfg(emmc_pinout.clk, NRF_GPIO_PIN_DIR_OUTPUT, NRF_GPIO_PIN_INPUT_DISCONNECT, + NRF_GPIO_PIN_NOPULL, NRF_GPIO_PIN_H0H1, NRF_GPIO_PIN_NOSENSE); // high-drive CLK + nrf_gpio_cfg_output(emmc_pinout.cmd); + DAT0_OUT(); // high-drive DAT0 + emmc_opt_pin_output(emmc_pinout.rst); + // VCCQ: standard drive. Do NOT "improve" this to H0H1 without evidence -- + // the rail gate does not need the extra drive and the card came up on it. + emmc_opt_pin_output(emmc_pinout.vccq); +} + +static inline void emmc_pins_release(void) { + nrf_gpio_cfg_default(emmc_pinout.clk); + nrf_gpio_cfg_default(emmc_pinout.cmd); + nrf_gpio_cfg_default(emmc_pinout.dat0); + if (emmc_pinout.rst != EMMC_NO_PIN) { + nrf_gpio_cfg_default(emmc_pinout.rst); + } + // VCCQ stays an output, driven low: the rail must stay off, not float. +} + +// handle nrf52840 errata 198 SPIM3 data corruption +#define EMMC_TX_FRAME ((uint8_t *)SPIM3_BUFFER_RAM_START_ADDR) + +// ---- time ---------------------------------------------------------------- +// Free-running 32768 Hz counter (RTC2, the supervisor's tick source). 24-bit, +// so differences must be masked; it wraps every 512 s. +#define EMMC_TICKS_HZ 32768u +#define EMMC_TICK_MASK 0x00FFFFFFu +#define EMMC_TICKS() (NRF_RTC2->COUNTER) + +static inline uint32_t ticks_since_raw(uint32_t t0) { + return (EMMC_TICKS() - t0) & EMMC_TICK_MASK; +} + +// 20 ms, ~75x the 260 us a full block takes at M16. +#define EMMC_SPIM_TIMEOUT_TICKS ((EMMC_TICKS_HZ * 20u) / 1000u) + +// ---- SPIM3 data engine --------------------------------------------------- +// SPIM3 is the only instance that runs above 8 MHz. M16 = 16 MHz, the fastest +// in-spec step for this card at power-on timing (TRAN_SPEED 0x32 -> 26 MHz cap +// in backwards-compatible mode). The bus is fixed there; the ONE way it moves +// is emmc_set_high_speed(), which first gets the card's own EXT_CSD to read +// back HS_TIMING = 1 (52 MHz limit) and only then steps to M32. +// +// NRF_SPIM3->FREQUENCY and ->CONFIG are read and written directly: the +// peripheral register is the state, and it survives +// ENABLE=0 between transfers. emmc_spim_init() puts both back to M16 / +// mode 0 on every init, so a fresh object always starts at compat speed even +// if the previous one ran high. + +static inline void emmc_spim_init(void) { + NRF_SPIM3->ENABLE = 0; + NRF_SPIM3->PSEL.SCK = emmc_pinout.clk; + NRF_SPIM3->PSEL.MOSI = 0xFFFFFFFFu; // attached per-transfer (write path only) + NRF_SPIM3->PSEL.MISO = 0xFFFFFFFFu; + NRF_SPIM3->PSEL.CSN = 0xFFFFFFFFu; + NRF_SPIM3->FREQUENCY = SPIM_FREQ_M16; + NRF_SPIM3->CONFIG = SPIM_CONFIG_MODE0; // the card comes up in compat timing + NRF_SPIM3->ORC = 0xFF; // idle-high filler +} + +static inline void emmc_spim_deinit(void) { + NRF_SPIM3->ENABLE = 0; + NRF_SPIM3->PSEL.SCK = 0xFFFFFFFFu; + NRF_SPIM3->PSEL.MOSI = 0xFFFFFFFFu; + NRF_SPIM3->PSEL.MISO = 0xFFFFFFFFu; +} + +// One blocking DMA transfer with the wires temporarily owned by SPIM. While +// ENABLED the peripheral drives SCK (+MOSI for TX) / samples MISO; on disable +// the pins fall back to their GPIO latches (CLK low, DAT0 as configured). + +static inline void emmc_spim_xfer(const uint8_t *tx, uint32_t txlen, uint8_t *rx, uint32_t rxlen) { + NRF_SPIM3->PSEL.MOSI = tx ? emmc_pinout.dat0 : 0xFFFFFFFFu; + NRF_SPIM3->PSEL.MISO = rx ? emmc_pinout.dat0 : 0xFFFFFFFFu; + NRF_SPIM3->ENABLE = 7; + NRF_SPIM3->TXD.PTR = (uint32_t)tx; + NRF_SPIM3->TXD.MAXCNT = tx ? txlen : 0; + NRF_SPIM3->RXD.PTR = (uint32_t)rx; + NRF_SPIM3->RXD.MAXCNT = rx ? rxlen : 0; + NRF_SPIM3->EVENTS_END = 0; + NRF_SPIM3->TASKS_START = 1; + { + uint32_t t0 = EMMC_TICKS(); + while (!NRF_SPIM3->EVENTS_END) { + if (ticks_since_raw(t0) >= EMMC_SPIM_TIMEOUT_TICKS) { + NRF_SPIM3->EVENTS_STOPPED = 0; + NRF_SPIM3->TASKS_STOP = 1; + // Let EasyDMA stop writing before the buffer is handed back. + for (uint32_t i = 0; i < 10000u && !NRF_SPIM3->EVENTS_STOPPED; i++) { + } + break; + } + } + } + NRF_SPIM3->ENABLE = 0; +} diff --git a/ports/nordic/common-hal/max3421e/Max3421E.c b/ports/nordic/common-hal/max3421e/Max3421E.c index f2eb423fa8d..2a171b3bffc 100644 --- a/ports/nordic/common-hal/max3421e/Max3421E.c +++ b/ports/nordic/common-hal/max3421e/Max3421E.c @@ -35,8 +35,6 @@ void common_hal_max3421e_max3421e_init_irq(max3421e_max3421e_obj_t *self) { void common_hal_max3421e_max3421e_deinit_irq(max3421e_max3421e_obj_t *self) { size_t pin_number = self->irq.pin->number; - // Bulk reset may have already reset us but this will raise an assert in - // debug mode if so. nrfx_gpiote_in_event_disable(pin_number); nrfx_gpiote_in_uninit(pin_number); _active = NULL; diff --git a/ports/nordic/common-hal/microcontroller/Pin.c b/ports/nordic/common-hal/microcontroller/Pin.c index 8043d2dfd4d..28461fd21fc 100644 --- a/ports/nordic/common-hal/microcontroller/Pin.c +++ b/ports/nordic/common-hal/microcontroller/Pin.c @@ -12,17 +12,11 @@ #include "nrf/pins.h" -#ifdef SPEAKER_ENABLE_PIN -bool speaker_enable_in_use; -#endif - // Bit mask of claimed pins on each of up to two ports. nrf52832 has one port; nrf52840 has two. static uint32_t claimed_pins[GPIO_COUNT]; -static uint32_t never_reset_pins[GPIO_COUNT]; +#ifdef SPEAKER_ENABLE_PIN static void reset_speaker_enable_pin(void) { - #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, @@ -30,23 +24,11 @@ static void reset_speaker_enable_pin(void) { NRF_GPIO_PIN_H0H1, NRF_GPIO_PIN_NOSENSE); nrf_gpio_pin_write(SPEAKER_ENABLE_PIN->number, false); - #endif } +#endif -void reset_all_pins(void) { - for (size_t i = 0; i < GPIO_COUNT; i++) { - claimed_pins[i] = never_reset_pins[i]; - } - - for (uint32_t pin = 0; pin < NUMBER_OF_PINS; ++pin) { - if ((never_reset_pins[nrf_pin_port(pin)] & (1 << nrf_relative_pin_number(pin))) != 0) { - continue; - } - nrf_gpio_cfg_default(pin); - } - - // After configuring SWD because it may be shared. - reset_speaker_enable_pin(); +MP_WEAK bool board_reset_pin_number(uint8_t pin_number) { + return false; } // Mark pin as free and return it to a quiescent state. @@ -57,27 +39,25 @@ void reset_pin_number(uint8_t pin_number) { // Clear claimed bit. claimed_pins[nrf_pin_port(pin_number)] &= ~(1 << nrf_relative_pin_number(pin_number)); - never_reset_pins[nrf_pin_port(pin_number)] &= ~(1 << nrf_relative_pin_number(pin_number)); #ifdef SPEAKER_ENABLE_PIN if (pin_number == SPEAKER_ENABLE_PIN->number) { reset_speaker_enable_pin(); + return; } #endif -} - -void never_reset_pin_number(uint8_t pin_number) { - if (pin_number == NO_PIN) { + // Allow the board to override the reset state of any pin. + if (board_reset_pin_number(pin_number)) { return; } - 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) { - never_reset_pin_number(pin->number); + // Disconnected input, as at power-on. Classes that leave a pin driven + // (busio.SPI's SCK and MOSI, say) rely on this. + nrf_gpio_cfg_default(pin_number); } + void common_hal_reset_pin(const mcu_pin_obj_t *pin) { if (pin == NULL) { return; @@ -85,15 +65,13 @@ 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_number(uint8_t pin_number) { // Set bit in claimed_pins bitmask. - claimed_pins[nrf_pin_port(pin->number)] |= 1 << nrf_relative_pin_number(pin->number); + claimed_pins[nrf_pin_port(pin_number)] |= 1 << nrf_relative_pin_number(pin_number); +} - #ifdef SPEAKER_ENABLE_PIN - if (pin == SPEAKER_ENABLE_PIN) { - speaker_enable_in_use = true; - } - #endif +void claim_pin(const mcu_pin_obj_t *pin) { + claim_pin_number(pin->number); } @@ -102,12 +80,6 @@ bool pin_number_is_free(uint8_t pin_number) { } bool common_hal_mcu_pin_is_free(const mcu_pin_obj_t *pin) { - #ifdef SPEAKER_ENABLE_PIN - if (pin == SPEAKER_ENABLE_PIN) { - return !speaker_enable_in_use; - } - #endif - #ifdef NRF52840 // If NFC pins are enabled for NFC, don't allow them to be used for GPIO. if (((NRF_UICR->NFCPINS & UICR_NFCPINS_PROTECT_Msk) == @@ -125,10 +97,6 @@ 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) { - claim_pin(pin); -} - void common_hal_mcu_pin_reset_number(uint8_t pin_no) { reset_pin_number(pin_no); } diff --git a/ports/nordic/common-hal/microcontroller/Pin.h b/ports/nordic/common-hal/microcontroller/Pin.h index e0a7550ec3a..b0b7b04ffdd 100644 --- a/ports/nordic/common-hal/microcontroller/Pin.h +++ b/ports/nordic/common-hal/microcontroller/Pin.h @@ -10,13 +10,20 @@ #include "peripherals/nrf/pins.h" -void reset_all_pins(void); +// If a board needs a different reset state for one or more pins, implement +// board_reset_pin_number so that it sets this state and returns `true` for those +// pin numbers, `false` for others. +bool board_reset_pin_number(uint8_t pin_number); + +void common_hal_reset_pin(const mcu_pin_obj_t *pin); // 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_number(uint8_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); + +uint8_t common_hal_mcu_pin_number(const mcu_pin_obj_t *pin); // Lower 5 bits of a pin number are the pin number in a port. // upper bits (just one bit for current chips) is port number. diff --git a/ports/nordic/common-hal/microcontroller/Processor.c b/ports/nordic/common-hal/microcontroller/Processor.c index c80da222307..fc3f0e7150e 100644 --- a/ports/nordic/common-hal/microcontroller/Processor.c +++ b/ports/nordic/common-hal/microcontroller/Processor.c @@ -109,28 +109,28 @@ void common_hal_mcu_processor_get_uid(uint8_t raw_id[]) { } mcu_reset_reason_t common_hal_mcu_processor_get_reset_reason(void) { - mcu_reset_reason_t r = RESET_REASON_UNKNOWN; + mcu_reset_reason_t r = MCU_RESET_REASON_UNKNOWN; if (reset_reason_saved == 0) { - r = RESET_REASON_POWER_ON; + r = MCU_RESET_REASON_POWER_ON; } else if (reset_reason_saved & POWER_RESETREAS_RESETPIN_Msk) { - r = RESET_REASON_RESET_PIN; + r = MCU_RESET_REASON_RESET_PIN; } else if (reset_reason_saved & POWER_RESETREAS_DOG_Msk) { - r = RESET_REASON_WATCHDOG; + r = MCU_RESET_REASON_WATCHDOG; } else if (reset_reason_saved & POWER_RESETREAS_SREQ_Msk) { - r = RESET_REASON_SOFTWARE; + r = MCU_RESET_REASON_SOFTWARE; #if CIRCUITPY_ALARM // Our "deep sleep" is still actually light sleep followed by a software // reset. Adding this check here ensures we treat it as-if we're waking // from deep sleep. if (sleepmem_wakeup_event != SLEEPMEM_WAKEUP_BY_NONE) { - r = RESET_REASON_DEEP_SLEEP_ALARM; + r = MCU_RESET_REASON_DEEP_SLEEP_ALARM; } #endif } else if ((reset_reason_saved & POWER_RESETREAS_OFF_Msk) || (reset_reason_saved & POWER_RESETREAS_LPCOMP_Msk) || (reset_reason_saved & POWER_RESETREAS_NFC_Msk) || (reset_reason_saved & POWER_RESETREAS_VBUS_Msk)) { - r = RESET_REASON_DEEP_SLEEP_ALARM; + r = MCU_RESET_REASON_DEEP_SLEEP_ALARM; } return r; } diff --git a/ports/nordic/common-hal/microcontroller/__init__.c b/ports/nordic/common-hal/microcontroller/__init__.c index 86e7916d754..03746d242b8 100644 --- a/ports/nordic/common-hal/microcontroller/__init__.c +++ b/ports/nordic/common-hal/microcontroller/__init__.c @@ -8,6 +8,10 @@ #include "py/obj.h" #include "py/runtime.h" +#if CIRCUITPY_ALARM +#include "common-hal/alarm/__init__.h" +#endif + #include "common-hal/microcontroller/Pin.h" #include "common-hal/microcontroller/Processor.h" @@ -20,7 +24,9 @@ #include "supervisor/port.h" #include "supervisor/shared/safe_mode.h" #include "nrfx_glue.h" +#ifdef BLUETOOTH_SD #include "nrf_nvic.h" +#endif #include "nrf_power.h" // This routine should work even when interrupts are disabled. Used by OneWire @@ -31,7 +37,7 @@ void common_hal_mcu_delay_us(uint32_t delay) { static volatile uint32_t nesting_count = 0; static uint8_t is_nested_critical_region; -void common_hal_mcu_disable_interrupts() { +void common_hal_mcu_disable_interrupts(void) { if (nesting_count == 0) { // Unlike __disable_irq(), this should only be called the first time // "is_nested_critical_region" is sd's equivalent of our nesting count @@ -41,13 +47,20 @@ void common_hal_mcu_disable_interrupts() { // This only disables interrupts of priority 2 through 7; levels 0, 1, // and 4, are exclusive to softdevice and should never be used, so // this limitation is not important. + #ifdef BLUETOOTH_SD sd_nvic_critical_region_enter(&is_nested_critical_region); + #else + // With no SoftDevice to leave room for, mask everything. Record whether + // interrupts were already masked so the matching exit leaves them so. + is_nested_critical_region = __get_PRIMASK() ? 1 : 0; + __disable_irq(); + #endif } __DMB(); nesting_count++; } -void common_hal_mcu_enable_interrupts() { +void common_hal_mcu_enable_interrupts(void) { if (nesting_count == 0) { // This is very very bad because it means there was mismatched disable/enables. reset_into_safe_mode(SAFE_MODE_INTERRUPT_ERROR); @@ -57,20 +70,49 @@ void common_hal_mcu_enable_interrupts() { return; } __DMB(); + #ifdef BLUETOOTH_SD sd_nvic_critical_region_exit(is_nested_critical_region); + #else + if (!is_nested_critical_region) { + __enable_irq(); + } + #endif } void common_hal_mcu_on_next_reset(mcu_runmode_t runmode) { - enum { DFU_MAGIC_UF2_RESET = 0x57 }; uint8_t new_value = 0; if (runmode == RUNMODE_BOOTLOADER || runmode == RUNMODE_UF2) { - new_value = DFU_MAGIC_UF2_RESET; + new_value = BOOTLOADER_UF2_MAGIC; + } + #ifdef BOOTLOADER_UF2_MAGIC2 + // This bootloader's magic is 16 bits wide, split across both retention + // registers, so GPREGRET2 is written as a pair with GPREGRET. + uint8_t new_value2 = 0; + if (runmode == RUNMODE_BOOTLOADER || runmode == RUNMODE_UF2) { + new_value2 = BOOTLOADER_UF2_MAGIC2; } - int err_code = sd_power_gpregret_set(0, DFU_MAGIC_UF2_RESET); + #endif + #ifdef BLUETOOTH_SD + int err_code = sd_power_gpregret_set(0, BOOTLOADER_UF2_MAGIC); + #ifdef BOOTLOADER_UF2_MAGIC2 + if (err_code == NRF_SUCCESS) { + err_code = sd_power_gpregret_set(1, BOOTLOADER_UF2_MAGIC2); + } + #endif if (err_code != NRF_SUCCESS) { // Set it without the soft device if the SD failed. (It may be off.) nrf_power_gpregret_set(NRF_POWER, new_value); + #ifdef BOOTLOADER_UF2_MAGIC2 + nrf_power_gpregret2_set(NRF_POWER, new_value2); + #endif } + #else + // No SoftDevice, so write GPREGRET directly. + nrf_power_gpregret_set(NRF_POWER, new_value); + #ifdef BOOTLOADER_UF2_MAGIC2 + nrf_power_gpregret2_set(NRF_POWER, new_value2); + #endif + #endif if (runmode == RUNMODE_SAFE_MODE) { safe_mode_on_next_reset(SAFE_MODE_PROGRAMMATIC); } @@ -78,6 +120,14 @@ void common_hal_mcu_on_next_reset(mcu_runmode_t runmode) { void common_hal_mcu_reset(void) { filesystem_flush(); + + // Clear any saved info about last deep sleep wakeup, + // to avoid confusing this software reset with a real deep sleep reset. + // See logic in common_hal_mcu_processor_get_reset_reason(). + #if CIRCUITPY_ALARM + sleepmem_wakeup_event = SLEEPMEM_WAKEUP_BY_NONE; + #endif + reset_cpu(); } diff --git a/ports/nordic/common-hal/neopixel_write/__init__.c b/ports/nordic/common-hal/neopixel_write/__init__.c index 66a1d70e869..3fbf61af36f 100644 --- a/ports/nordic/common-hal/neopixel_write/__init__.c +++ b/ports/nordic/common-hal/neopixel_write/__init__.c @@ -82,7 +82,10 @@ static NRF_PWM_Type *find_free_pwm(void) { } static size_t pixels_pattern_heap_size = 0; -// Called during reset_port() to free the pattern buffer +// Clear the root pointer during reset_port() while the old GC heap (and the pattern +// buffer in it) is still alive. Root pointers are NOT zeroed between VM runs, so +// without this the pointer would dangle after the heap is torn down and re-created. +// The now-unreferenced block is reclaimed by the final sweep in gc_deinit(). void neopixel_write_reset(void) { MP_STATE_VM(pixels_pattern_heap) = NULL; pixels_pattern_heap_size = 0; @@ -125,7 +128,9 @@ void common_hal_neopixel_write(const digitalio_digitalinout_obj_t *digitalinout, pixels_pattern = (uint16_t *)stack_pixels; } else { uint8_t sd_en = 0; + #ifdef BLUETOOTH_SD (void)sd_softdevice_is_enabled(&sd_en); + #endif if (pixels_pattern_heap_size < pattern_size) { // Current heap buffer is too small. diff --git a/ports/nordic/common-hal/nvm/ByteArray.c b/ports/nordic/common-hal/nvm/ByteArray.c index c846a61f751..f245207e83c 100644 --- a/ports/nordic/common-hal/nvm/ByteArray.c +++ b/ports/nordic/common-hal/nvm/ByteArray.c @@ -11,6 +11,7 @@ #include #include +#include "background.h" #include "peripherals/nrf/nvm.h" uint32_t common_hal_nvm_bytearray_get_length(const nvm_bytearray_obj_t *self) { @@ -40,6 +41,7 @@ bool common_hal_nvm_bytearray_set_bytes(const nvm_bytearray_obj_t *self, while (len) { uint32_t write_len = MIN(len, FLASH_PAGE_SIZE - offset); + board_background_task(); if (!write_page(page_addr, offset, write_len, values)) { return false; } diff --git a/ports/nordic/common-hal/paralleldisplaybus/ParallelBus.c b/ports/nordic/common-hal/paralleldisplaybus/ParallelBus.c index 5377d020f6b..7bfd1fd4b6d 100644 --- a/ports/nordic/common-hal/paralleldisplaybus/ParallelBus.c +++ b/ports/nordic/common-hal/paralleldisplaybus/ParallelBus.c @@ -16,6 +16,10 @@ void common_hal_paralleldisplaybus_parallelbus_construct(paralleldisplaybus_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) { + // Ensure the bus starts in its deinit state, so deinit() does nothing if + // this raises. The bus lives in a display bus slot, which + // release_displays() deinits even if construct never finished. + self->bus = NULL; uint8_t data_pin = data0->number; if (data_pin % 8 != 0) { @@ -35,11 +39,14 @@ void common_hal_paralleldisplaybus_parallelbus_construct(paralleldisplaybus_para g = NRF_P1; num_pins_in_port = P1_PIN_NUM; } + for (uint8_t i = 0; i < 8; i++) { + claim_pin_number(data_pin + i); + } g->DIRSET = 0xff << (data_pin % num_pins_in_port); 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); + uint8_t *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); @@ -53,13 +60,18 @@ void common_hal_paralleldisplaybus_parallelbus_construct(paralleldisplaybus_para common_hal_digitalio_digitalinout_construct(&self->write, write); common_hal_digitalio_digitalinout_switch_to_output(&self->write, 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); + // read is optional. + self->read.base.type = &mp_type_NoneType; + if (read != NULL) { + 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; uint8_t num_pins_in_write_port; - if (data0->number < P0_PIN_NUM) { + // The write pin's own port, which may not be data0's. + if (write->number < P0_PIN_NUM) { self->write_group = NRF_P0; num_pins_in_write_port = P0_PIN_NUM; } else { @@ -73,29 +85,30 @@ void common_hal_paralleldisplaybus_parallelbus_construct(paralleldisplaybus_para 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_paralleldisplaybus_parallelbus_reset(self); } - never_reset_pin_number(command->number); - never_reset_pin_number(chip_select->number); - never_reset_pin_number(write->number); - never_reset_pin_number(read->number); - for (uint8_t i = 0; i < 8; i++) { - never_reset_pin_number(data_pin + i); - } + // The bus is live from here. + self->bus = bus; } void common_hal_paralleldisplaybus_parallelbus_deinit(paralleldisplaybus_parallelbus_obj_t *self) { + if (self->bus == NULL) { + return; + } 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.pin->number); - reset_pin_number(self->read.pin->number); - reset_pin_number(self->reset.pin->number); + // read and reset are optional. One that wasn't given was never constructed, + // so its pin is NULL, and digitalinout_deinit() returns without touching a + // DigitalInOut whose pin is NULL. + common_hal_digitalio_digitalinout_deinit(&self->command); + common_hal_digitalio_digitalinout_deinit(&self->chip_select); + common_hal_digitalio_digitalinout_deinit(&self->write); + common_hal_digitalio_digitalinout_deinit(&self->read); + common_hal_digitalio_digitalinout_deinit(&self->reset); + self->bus = NULL; } bool common_hal_paralleldisplaybus_parallelbus_reset(mp_obj_t obj) { diff --git a/ports/nordic/common-hal/pulseio/PulseIn.c b/ports/nordic/common-hal/pulseio/PulseIn.c index 0a2286090e0..afabc6d9ef0 100644 --- a/ports/nordic/common-hal/pulseio/PulseIn.c +++ b/ports/nordic/common-hal/pulseio/PulseIn.c @@ -91,21 +91,41 @@ static void _pulsein_handler(nrfx_gpiote_pin_t pin, nrf_gpiote_polarity_t action self->last_count = current_count; } +static void mark_deinit(pulseio_pulsein_obj_t *self) { + self->pin = NO_PIN; +} + void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t *self, const mcu_pin_obj_t *pin, uint16_t maxlen, bool idle_state) { + // Ensure the object starts in its deinit state, so its finaliser does + // nothing if this raises. + mark_deinit(self); + int idx = _find_pulsein_obj(NULL); if (idx < 0) { mp_raise_NotImplementedError(NULL); } - _objs[idx] = self; - self->buffer = (uint16_t *)m_malloc(maxlen * sizeof(uint16_t)); + self->buffer = (uint16_t *)m_malloc_without_collect(maxlen * sizeof(uint16_t)); if (self->buffer == NULL) { m_malloc_fail(maxlen * sizeof(uint16_t)); } + nrfx_gpiote_in_config_t cfg = { + .sense = NRF_GPIOTE_POLARITY_TOGGLE, + .pull = NRF_GPIO_PIN_NOPULL, + .is_watcher = false, // A plain input, not one that watches a pin we also drive. + .hi_accuracy = true, + .skip_gpio_setup = false + }; + nrfx_err_t err = nrfx_gpiote_in_init(pin->number, &cfg, _pulsein_handler); + if (err != NRFX_SUCCESS) { + mp_raise_RuntimeError(MP_ERROR_TEXT("All channels in use")); + } + if (refcount == 0) { timer = nrf_peripherals_allocate_timer(); if (timer == NULL) { + nrfx_gpiote_in_uninit(pin->number); mp_raise_RuntimeError(MP_ERROR_TEXT("All timers in use")); } overflow_count = 0; @@ -125,7 +145,6 @@ void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t *self, const mcu } refcount++; - self->pin = pin->number; self->maxlen = maxlen; self->idle_state = idle_state; self->start = 0; @@ -134,20 +153,11 @@ void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t *self, const mcu self->paused = false; self->last_overflow = 0; self->last_count = 0; + self->pin = pin->number; + _objs[idx] = self; claim_pin(pin); - nrfx_gpiote_in_config_t cfg = { - .sense = NRF_GPIOTE_POLARITY_TOGGLE, - .pull = NRF_GPIO_PIN_NOPULL, // idle_state ? NRF_GPIO_PIN_PULLDOWN : NRF_GPIO_PIN_PULLUP, - .is_watcher = false, // nrf_gpio_cfg_watcher vs nrf_gpio_cfg_input - .hi_accuracy = true, - .skip_gpio_setup = false - }; - nrfx_err_t err = nrfx_gpiote_in_init(self->pin, &cfg, _pulsein_handler); - if (err != NRFX_SUCCESS) { - mp_raise_RuntimeError(MP_ERROR_TEXT("All channels in use")); - } nrfx_gpiote_in_event_enable(self->pin, true); } @@ -171,7 +181,7 @@ void common_hal_pulseio_pulsein_deinit(pulseio_pulsein_obj_t *self) { _objs[idx] = NULL; reset_pin_number(self->pin); - self->pin = NO_PIN; + mark_deinit(self); refcount--; if (refcount == 0) { diff --git a/ports/nordic/common-hal/pulseio/PulseOut.c b/ports/nordic/common-hal/pulseio/PulseOut.c index 87f358845d3..096dc91dfd5 100644 --- a/ports/nordic/common-hal/pulseio/PulseOut.c +++ b/ports/nordic/common-hal/pulseio/PulseOut.c @@ -25,14 +25,18 @@ static nrfx_timer_t *timer = NULL; static uint16_t *pulse_array = NULL; static volatile uint16_t pulse_array_index = 0; static uint16_t pulse_array_length; +// The PulseOut whose send() is running. The timer is shared, so its context +// can't name the PulseOut. +static pulseio_pulseout_obj_t *active_pulseout = NULL; +// The PWMOut may have any channel of a PWM it shares with other PWMOuts. static void turn_on(pulseio_pulseout_obj_t *pulseout) { - pulseout->pwmout.pwm->PSEL.OUT[0] = pulseout->pwmout.pin->number; + pulseout->pwmout.pwm->PSEL.OUT[pulseout->pwmout.channel] = pulseout->pwmout.pin->number; } static void turn_off(pulseio_pulseout_obj_t *pulseout) { // Disconnect pin from PWM. - pulseout->pwmout.pwm->PSEL.OUT[0] = 0xffffffff; + pulseout->pwmout.pwm->PSEL.OUT[pulseout->pwmout.channel] = 0xffffffff; // Make sure pin is low. nrf_gpio_pin_clear(pulseout->pwmout.pin->number); } @@ -45,8 +49,8 @@ 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; - if (event_type != NRF_TIMER_EVENT_COMPARE0) { + pulseio_pulseout_obj_t *pulseout = active_pulseout; + if (pulseout == NULL || event_type != NRF_TIMER_EVENT_COMPARE0) { // Spurious event. return; } @@ -81,27 +85,34 @@ void common_hal_pulseio_pulseout_construct(pulseio_pulseout_obj_t *self, uint32_t frequency, uint16_t duty_cycle) { - pwmout_result_t result = common_hal_pwmio_pwmout_construct( - &self->pwmout, pin, duty_cycle, frequency, false); - - // This will raise an exception and not return if needed. - common_hal_pwmio_pwmout_raise_error(result); - + // Get the shared timer before the PWMOut, so a raise due to an error leaves nothing + // claimed or counted. if (refcount == 0) { timer = nrf_peripherals_allocate_timer_or_throw(); + + nrfx_timer_config_t timer_config = { + // PulseOut durations are in microseconds, so this is convenient. + .frequency = NRF_TIMER_FREQ_1MHz, + .mode = NRF_TIMER_MODE_TIMER, + .bit_width = NRF_TIMER_BIT_WIDTH_32, + .interrupt_priority = NRFX_TIMER_DEFAULT_CONFIG_IRQ_PRIORITY, + .p_context = NULL, + }; + nrfx_timer_init(timer, &timer_config, &pulseout_event_handler); } - refcount++; - nrfx_timer_config_t timer_config = { - // PulseOut durations are in microseconds, so this is convenient. - .frequency = NRF_TIMER_FREQ_1MHz, - .mode = NRF_TIMER_MODE_TIMER, - .bit_width = NRF_TIMER_BIT_WIDTH_32, - .interrupt_priority = NRFX_TIMER_DEFAULT_CONFIG_IRQ_PRIORITY, - .p_context = self, - }; + pwmout_result_t result = common_hal_pwmio_pwmout_construct( + &self->pwmout, pin, duty_cycle, frequency, false); + if (result != PWMOUT_OK) { + if (refcount == 0) { + nrf_peripherals_free_timer(timer); + timer = NULL; + } + // This raises. + common_hal_pwmio_pwmout_raise_error(result); + } + refcount++; - nrfx_timer_init(timer, &timer_config, &pulseout_event_handler); turn_off(self); } @@ -119,6 +130,7 @@ void common_hal_pulseio_pulseout_deinit(pulseio_pulseout_obj_t *self) { refcount--; if (refcount == 0) { nrf_peripherals_free_timer(timer); + timer = NULL; } } @@ -126,6 +138,7 @@ void common_hal_pulseio_pulseout_send(pulseio_pulseout_obj_t *self, uint16_t *pu pulse_array = pulses; pulse_array_index = 0; pulse_array_length = length; + active_pulseout = self; nrfx_timer_enable(timer); @@ -140,4 +153,5 @@ void common_hal_pulseio_pulseout_send(pulseio_pulseout_obj_t *self, uint16_t *pu } nrfx_timer_disable(timer); + active_pulseout = NULL; } diff --git a/ports/nordic/common-hal/pwmio/PWMOut.c b/ports/nordic/common-hal/pwmio/PWMOut.c index 6dc7ff56c71..dababe9dc7a 100644 --- a/ports/nordic/common-hal/pwmio/PWMOut.c +++ b/ports/nordic/common-hal/pwmio/PWMOut.c @@ -34,7 +34,13 @@ static NRF_PWM_Type *pwms[] = { static uint16_t pwm_seq[MP_ARRAY_SIZE(pwms)][CHANNELS_PER_PWM]; -static uint8_t never_reset_pwm[MP_ARRAY_SIZE(pwms)]; +// Which channels of each PWM are in use, one bit per channel. +// We can't tell from the pin setting (PSEL) whether a channel is free, because +// pulseio.PulseOut disconnects its pin between pulses but still owns the channel. +static uint8_t claimed_channels[MP_ARRAY_SIZE(pwms)]; +// True if one object owns the whole PWM. A variable-frequency PWMOut and +// PWMAudioOut can't share their PWM with anything else. +static bool exclusive[MP_ARRAY_SIZE(pwms)]; static int pwm_idx(NRF_PWM_Type *pwm) { for (size_t i = 0; i < MP_ARRAY_SIZE(pwms); i++) { @@ -45,16 +51,13 @@ static int pwm_idx(NRF_PWM_Type *pwm) { return -1; } -void common_hal_pwmio_pwmout_never_reset(pwmio_pwmout_obj_t *self) { - never_reset_pwm[pwm_idx(self->pwm)] |= 1 << self->channel; - - common_hal_never_reset_pin(self->pin); -} - static void reset_single_pwmout(uint8_t i) { NRF_PWM_Type *pwm = pwms[i]; pwm->ENABLE = 0; + // A previous user may have left shortcuts set. audiopwmio stops a non-looping + // sample with SEQEND->STOP, which would stop a PWMOut after one sequence. + pwm->SHORTS = 0; pwm->MODE = PWM_MODE_UPDOWN_Up; pwm->DECODER = PWM_DECODER_LOAD_Individual; pwm->LOOP = 0; @@ -107,9 +110,9 @@ NRF_PWM_Type *pwmout_allocate(uint16_t countertop, nrf_pwm_clk_t base_clock, 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; + bool pwm_already_in_use = claimed_channels[pwm_index] != 0; if (pwm_already_in_use) { - if (variable_frequency) { + if (variable_frequency || exclusive[pwm_index]) { // Variable frequency requires exclusive use of a PWM, so try the next one. continue; } @@ -118,8 +121,9 @@ NRF_PWM_Type *pwmout_allocate(uint16_t countertop, nrf_pwm_clk_t base_clock, // look for a free channel. if (pwm->COUNTERTOP == countertop && pwm->PRESCALER == base_clock) { for (size_t chan = 0; chan < CHANNELS_PER_PWM; chan++) { - if (pwm->PSEL.OUT[chan] == 0xFFFFFFFF) { + if (!(claimed_channels[pwm_index] & (1 << chan))) { // Channel is free. + claimed_channels[pwm_index] |= 1 << chan; if (channel_out) { *channel_out = chan; } @@ -135,6 +139,8 @@ NRF_PWM_Type *pwmout_allocate(uint16_t countertop, nrf_pwm_clk_t base_clock, } } else { // PWM not yet in use, so we can start to use it. Use channel 0. + claimed_channels[pwm_index] = 1 << 0; + exclusive[pwm_index] = variable_frequency; if (channel_out) { *channel_out = 0; } @@ -154,11 +160,18 @@ 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++) { - if (pwm->PSEL.OUT[i] != 0xFFFFFFFF) { - // Some channel is still being used, so don't disable. - return; - } + int pwm_index = pwm_idx(pwm); + if (exclusive[pwm_index]) { + // The exclusive user is giving up the whole PWM. + claimed_channels[pwm_index] = 0; + exclusive[pwm_index] = false; + } else { + claimed_channels[pwm_index] &= ~(1 << channel); + } + + if (claimed_channels[pwm_index] != 0) { + // Some channel is still being used, so don't disable. + return; } nrf_pwm_disable(pwm); @@ -226,8 +239,6 @@ void common_hal_pwmio_pwmout_deinit(pwmio_pwmout_obj_t *self) { nrf_gpio_cfg_default(self->pin->number); - never_reset_pwm[pwm_idx(self->pwm)] &= ~(1 << self->channel); - NRF_PWM_Type *pwm = self->pwm; self->pwm = NULL; diff --git a/ports/nordic/common-hal/rgbmatrix/RGBMatrix.c b/ports/nordic/common-hal/rgbmatrix/RGBMatrix.c index 01f2cbc737e..be30cb63d2a 100644 --- a/ports/nordic/common-hal/rgbmatrix/RGBMatrix.c +++ b/ports/nordic/common-hal/rgbmatrix/RGBMatrix.c @@ -14,7 +14,6 @@ extern void _PM_IRQ_HANDLER(void); 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; } @@ -36,6 +35,10 @@ void common_hal_rgbmatrix_timer_enable(void *ptr) { } void common_hal_rgbmatrix_timer_disable(void *ptr) { + // ptr is NULL when the timer allocation failed. + if (ptr == NULL) { + return; + } nrfx_timer_t *timer = nrf_peripherals_timer_from_reg(ptr); nrfx_timer_uninit(timer); } diff --git a/ports/nordic/common-hal/rotaryio/IncrementalEncoder.c b/ports/nordic/common-hal/rotaryio/IncrementalEncoder.c index b0617fae7e5..f14a22eabdb 100644 --- a/ports/nordic/common-hal/rotaryio/IncrementalEncoder.c +++ b/ports/nordic/common-hal/rotaryio/IncrementalEncoder.c @@ -32,11 +32,8 @@ static void _intr_handler(nrfx_gpiote_pin_t pin, nrf_gpiote_polarity_t action) { void common_hal_rotaryio_incrementalencoder_construct(rotaryio_incrementalencoder_obj_t *self, const mcu_pin_obj_t *pin_a, const mcu_pin_obj_t *pin_b) { - self->pin_a = pin_a->number; - self->pin_b = pin_b->number; - - _objs[self->pin_a] = self; - _objs[self->pin_b] = self; + // Ensure object starts in its deinit state. + common_hal_rotaryio_incrementalencoder_mark_deinit(self); nrfx_gpiote_in_config_t cfg = { .sense = NRF_GPIOTE_POLARITY_TOGGLE, @@ -45,15 +42,20 @@ void common_hal_rotaryio_incrementalencoder_construct(rotaryio_incrementalencode .hi_accuracy = true, .skip_gpio_setup = false }; - nrfx_err_t err = nrfx_gpiote_in_init(self->pin_a, &cfg, _intr_handler); + nrfx_err_t err = nrfx_gpiote_in_init(pin_a->number, &cfg, _intr_handler); if (err != NRFX_SUCCESS) { mp_raise_RuntimeError(MP_ERROR_TEXT("All channels in use")); } - err = nrfx_gpiote_in_init(self->pin_b, &cfg, _intr_handler); + err = nrfx_gpiote_in_init(pin_b->number, &cfg, _intr_handler); if (err != NRFX_SUCCESS) { - nrfx_gpiote_in_uninit(self->pin_a); + nrfx_gpiote_in_uninit(pin_a->number); mp_raise_RuntimeError(MP_ERROR_TEXT("All channels in use")); } + // Set the pins only now, after success to avoid out-of-bounds writes in nrfx_gpiote_in_uninit(). + self->pin_a = pin_a->number; + self->pin_b = pin_b->number; + _objs[self->pin_a] = self; + _objs[self->pin_b] = self; nrfx_gpiote_in_event_enable(self->pin_a, true); nrfx_gpiote_in_event_enable(self->pin_b, true); @@ -78,6 +80,10 @@ void common_hal_rotaryio_incrementalencoder_deinit(rotaryio_incrementalencoder_o nrfx_gpiote_in_uninit(self->pin_b); reset_pin_number(self->pin_a); reset_pin_number(self->pin_b); + + common_hal_rotaryio_incrementalencoder_mark_deinit(self); +} + +void common_hal_rotaryio_incrementalencoder_mark_deinit(rotaryio_incrementalencoder_obj_t *self) { self->pin_a = NO_PIN; - self->pin_b = NO_PIN; } diff --git a/ports/nordic/common-hal/rtc/RTC.h b/ports/nordic/common-hal/rtc/RTC.h index 18625763562..d597327fd23 100644 --- a/ports/nordic/common-hal/rtc/RTC.h +++ b/ports/nordic/common-hal/rtc/RTC.h @@ -7,5 +7,4 @@ #pragma once extern void rtc_init(void); -extern void rtc_reset(void); extern void common_hal_rtc_init(void); diff --git a/ports/nordic/common-hal/watchdog/WatchDogTimer.c b/ports/nordic/common-hal/watchdog/WatchDogTimer.c index b20aa0c0629..ce8a2f5e8ce 100644 --- a/ports/nordic/common-hal/watchdog/WatchDogTimer.c +++ b/ports/nordic/common-hal/watchdog/WatchDogTimer.c @@ -73,11 +73,8 @@ void common_hal_watchdog_feed(watchdog_watchdogtimer_obj_t *self) { } } -void common_hal_watchdog_deinit(watchdog_watchdogtimer_obj_t *self) { +void common_hal_watchdog_reset(watchdog_watchdogtimer_obj_t *self) { if (self->mode == WATCHDOGMODE_RESET) { - if (gc_alloc_possible()) { - mp_raise_RuntimeError(MP_ERROR_TEXT("WatchDogTimer cannot be deinitialized once mode is set to RESET")); - } // Don't change anything because RESET cannot be undone. return; } @@ -164,6 +161,10 @@ void common_hal_watchdog_set_mode(watchdog_watchdogtimer_obj_t *self, watchdog_w } nrfx_wdt_enable(&wdt); nrfx_wdt_feed(&wdt); + } else if (new_mode == WATCHDOGMODE_NONE && current_mode == WATCHDOGMODE_RESET) { + // raise exception on attempt to set mode back from RESET to None + mp_raise_RuntimeError(MP_ERROR_TEXT("WatchDogTimer cannot be deinitialized once mode is set to RESET")); + } // If we just switched away from RAISE, disable the timmer. diff --git a/ports/nordic/device/nrf52/startup_nrf52840.c b/ports/nordic/device/nrf52/startup_nrf52840.c index 6b81fac2a9c..f602a86e079 100644 --- a/ports/nordic/device/nrf52/startup_nrf52840.c +++ b/ports/nordic/device/nrf52/startup_nrf52840.c @@ -27,8 +27,23 @@ void Default_Handler(void) { } } +extern const func __Vectors[]; + +#ifndef BLUETOOTH_SD +// SCB->VTOR, addressed directly so the startup file need not pull in CMSIS. +#define SCB_VTOR (*(volatile uint32_t *)0xE000ED08UL) +#endif + extern void Reset_Handler(void); void Reset_Handler(void) { + #ifndef BLUETOOTH_SD + // With a SoftDevice, the MBR at 0x0 owns the vector table and forwards + // interrupts to us, so VTOR is already pointing at our table by the time we + // run. + SCB_VTOR = (uint32_t)&__Vectors[0]; + __asm volatile ("dsb 0xF" ::: "memory"); + #endif + uint32_t *p_src = &_sidata; uint32_t *p_dest = &_sdata; diff --git a/ports/nordic/mpconfigport.h b/ports/nordic/mpconfigport.h index 33fcfa371e0..a6995f9b885 100644 --- a/ports/nordic/mpconfigport.h +++ b/ports/nordic/mpconfigport.h @@ -7,10 +7,13 @@ #pragma once +#ifdef BLUETOOTH_SD #include "ble_drv.h" #include "nrf_mbr.h" // for MBR_SIZE #include "nrf_sdm.h" // for SD_FLASH_SIZE +#endif + #include "peripherals/nrf/nvm.h" // for FLASH_PAGE_SIZE #define MICROPY_PY_SYS_STDIO_BUFFER (1) @@ -44,6 +47,17 @@ // Definitions that might be overridden by mpconfigboard.h +#ifndef BLUETOOTH_SD + +#ifndef MBR_SIZE +#define MBR_SIZE (0x1000) +#endif + +#ifndef SD_FLASH_SIZE +#define SD_FLASH_SIZE (0) +#endif +#endif + #ifndef CIRCUITPY_INTERNAL_NVM_SIZE #define CIRCUITPY_INTERNAL_NVM_SIZE (8 * 1024) #endif @@ -81,7 +95,11 @@ #define SD_FLASH_START_ADDR (MBR_START_ADDR + MBR_SIZE) // SD_FLASH_SIZE is from nrf_sdm.h +// A board whose bootloader lives in low flash and jumps to a fixed address +// overrides this in mpconfigboard.h. +#ifndef ISR_START_ADDR #define ISR_START_ADDR (SD_FLASH_START_ADDR + SD_FLASH_SIZE) +#endif #define ISR_SIZE (4 * 1024) // 4kiB // Smallest unit of flash that can be erased. @@ -92,14 +110,37 @@ // Define these regions starting down from the bootloader: // Bootloader values from https://github.com/adafruit/Adafruit_nRF52_Bootloader/blob/master/src/linker/s140_v6.ld +// A board with no bootloader in high flash sets BOOTLOADER_SIZE and +// BOOTLOADER_MBR_SIZE to 0; BOOTLOADER_START_ADDR then collapses onto the +// settings page, which stays the top anchor everything else grows down from. #define BOOTLOADER_START_ADDR (FLASH_SIZE - BOOTLOADER_SIZE - BOOTLOADER_SETTINGS_SIZE - BOOTLOADER_MBR_SIZE) +#ifndef BOOTLOADER_MBR_SIZE #define BOOTLOADER_MBR_SIZE (4 * 1024) // 4kib +#endif #ifndef BOOTLOADER_SIZE #define BOOTLOADER_SIZE (40 * 1024) // 40kiB #endif #define BOOTLOADER_SETTINGS_START_ADDR (FLASH_SIZE - BOOTLOADER_SETTINGS_SIZE) #define BOOTLOADER_SETTINGS_SIZE (4 * 1024) // 4kiB +// Value left in GPREGRET to ask the bootloader to stay in DFU mode after the +// reset that reset_to_bootloader() performs. The default is the Adafruit nRF52 +// bootloader's serial-DFU magic; a board with a different bootloader overrides +// it in mpconfigboard.h. A bootloader whose magic is wider than eight bits also +// defines BOOTLOADER_DFU_MAGIC2, which is written to GPREGRET2. +#ifndef BOOTLOADER_DFU_MAGIC +#define BOOTLOADER_DFU_MAGIC (0x4e) +#endif + +// Value left in GPREGRET by common_hal_mcu_on_next_reset() for RunMode.UF2 and +// RunMode.BOOTLOADER. The default is the Adafruit nRF52 bootloader's UF2/OTA +// magic. A board whose bootloader gates on something else overrides it in +// mpconfigboard.h; if that bootloader has no separate UF2 and serial-DFU +// requests, it sets this to the same value as BOOTLOADER_DFU_MAGIC. +#ifndef BOOTLOADER_UF2_MAGIC +#define BOOTLOADER_UF2_MAGIC (0x57) +#endif + #define CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_START_ADDR (BOOTLOADER_START_ADDR - CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_SIZE) #if CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_SIZE > 0 && CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_START_ADDR != (BOOTLOADER_START_ADDR - CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_SIZE) @@ -159,7 +200,12 @@ // 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 +#ifdef BLUETOOTH_SD #define SOFTDEVICE_RAM_SIZE (56 * 1024) +#else + +#define SOFTDEVICE_RAM_SIZE (0) +#endif #endif diff --git a/ports/nordic/mpconfigport.mk b/ports/nordic/mpconfigport.mk index 58700817d51..312126fb20c 100644 --- a/ports/nordic/mpconfigport.mk +++ b/ports/nordic/mpconfigport.mk @@ -1,5 +1,8 @@ # All linking can be done with this common templated linker script, which has # parameters that vary based on chip and/or board. +# Properties get a dedicated linker section here, so they can drop the unused slots. +CIRCUITPY_OPTIMIZE_PROPERTY_FLASH_SIZE ?= 1 + LD_TEMPLATE_FILE = boards/common.template.ld INTERNAL_LIBM = 1 @@ -9,6 +12,15 @@ CIRCUITPY_BUILD_EXTENSIONS ?= uf2 # Number of USB endpoint pairs. USB_NUM_ENDPOINT_PAIRS = 8 +# The nRF52 USBD implements isochronous transfers only on the fixed, dedicated +# endpoint number 8 (EP_ISO_NUM in TinyUSB's dcd_nrf5x.c); dcd_edpt_open() rejects +# an ISO endpoint on any other number, so a usb_audio mic/speaker placed on a +# sequentially-allocated endpoint would enumerate but never transfer data. Force +# the usb_audio isochronous endpoint onto endpoint 8. (Only read by usb_audio +# code, so it is harmless when CIRCUITPY_USB_AUDIO is off; defined unconditionally +# to stay independent of where that flag gets set in the include order.) +CFLAGS += -DUSB_AUDIO_ISO_EP_NUM=8 + # All nRF ports have longints. LONGINT_IMPL = MPZ @@ -25,13 +37,15 @@ CIRCUITPY_SYNTHIO_MAX_CHANNELS = 12 # Native BLEIO is not compatible with HCI _bleio. CIRCUITPY_BLEIO_HCI = 0 -CIRCUITPY_BLEIO ?= 1 +CIRCUITPY_BLEIO_NATIVE ?= 1 # No I2CPeripheral implementation CIRCUITPY_I2CTARGET = 0 CIRCUITPY_RTC ?= 1 +CIRCUITPY_SETTINGS_TOML ?= 1 + # frequencyio not yet implemented CIRCUITPY_FREQUENCYIO = 0 @@ -40,13 +54,12 @@ CIRCUITPY_ROTARYIO_SOFTENCODER = 1 # Sleep and Wakeup CIRCUITPY_ALARM ?= 1 -# Turn on the BLE file service +# Turn on the BLE file and serial services for BLE workflow CIRCUITPY_BLE_FILE_SERVICE ?= 1 - -# Turn on the BLE serial service -CIRCUITPY_SERIAL_BLE ?= 1 +CIRCUITPY_BLE_SERIAL_SERVICE ?= 1 CIRCUITPY_COMPUTED_GOTO_SAVE_SPACE ?= 1 +CIRCUITPY_LOAD_NATIVE ?= 1 # nRF52840-specific @@ -63,6 +76,8 @@ CIRCUITPY_MEMORYMAP ?= 1 CIRCUITPY_RGBMATRIX ?= 1 CIRCUITPY_FRAMEBUFFERIO ?= 1 +CIRCUITPY_HASHLIB ?= 1 + CIRCUITPY_COUNTIO ?= 1 CIRCUITPY_WATCHDOG ?= 1 @@ -81,6 +96,17 @@ ifeq ($(INTERNAL_FLASH_FILESYSTEM),1) OPTIMIZATION_FLAGS ?= -Os CIRCUITPY_LTO = 1 CIRCUITPY_LTO_PARTITION = balanced + CIRCUITPY_CODEOP ?= 0 + CIRCUITPY_MSGPACK ?= 0 + CIRCUITPY_ULAB_OPTIMIZE_SIZE ?= 1 + # Fast e-paper doesn't fit in what internal flash has left. + CIRCUITPY_EPAPERDISPLAY_FAST ?= 0 + # Compile gc.c and vm.c with -Os instead of CSUPEROPT. Saves about 3 kB, + # for a 1-4% VM slowdown and 12% slower full gc with a live heap. + SUPEROPT_GC ?= 0 + SUPEROPT_VM ?= 0 +else + CIRCUITPY_USB_AUDIO ?= 1 endif else @@ -106,8 +132,14 @@ OPTIMIZATION_FLAGS ?= -Os CIRCUITPY_LTO = 1 CIRCUITPY_LTO_PARTITION = one ifeq ($(INTERNAL_FLASH_FILESYSTEM),1) + CIRCUITPY_EPAPERDISPLAY_FAST ?= 0 CIRCUITPY_FULL_BUILD ?= 0 CIRCUITPY_PULSEIO ?= 1 endif endif endif + +ifneq ($(CIRCUITPY_BLEIO_NATIVE),1) +CIRCUITPY_BLE_FILE_SERVICE = 0 +CIRCUITPY_BLE_SERIAL_SERVICE = 0 +endif diff --git a/ports/nordic/peripherals/nrf/nvm.h b/ports/nordic/peripherals/nrf/nvm.h index aff98094469..10bf92d90cf 100644 --- a/ports/nordic/peripherals/nrf/nvm.h +++ b/ports/nordic/peripherals/nrf/nvm.h @@ -7,9 +7,12 @@ #pragma once +#include +#include + #define FLASH_PAGE_SIZE (4096) -#if BLUETOOTH_SD +#ifdef 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); #endif diff --git a/ports/nordic/peripherals/nrf/pins.h b/ports/nordic/peripherals/nrf/pins.h index 096568e87c3..96810764de9 100644 --- a/ports/nordic/peripherals/nrf/pins.h +++ b/ports/nordic/peripherals/nrf/pins.h @@ -12,6 +12,8 @@ #include #include +#include "py/obj.h" + #include "nrf_gpio.h" typedef struct { diff --git a/ports/nordic/peripherals/nrf/timers.c b/ports/nordic/peripherals/nrf/timers.c index ec1bde65877..c570bec65f5 100644 --- a/ports/nordic/peripherals/nrf/timers.c +++ b/ports/nordic/peripherals/nrf/timers.c @@ -35,27 +35,6 @@ static nrfx_timer_t nrfx_timers[] = { }; 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++) { - if (nrfx_timer_never_reset[i]) { - continue; - } - nrfx_timer_uninit(&nrfx_timers[i]); - nrfx_timer_allocated[i] = false; - } -} - -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) { - 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++) { @@ -102,7 +81,6 @@ 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; - nrfx_timer_never_reset[idx] = false; // Safe to call even if not initialized. nrfx_timer_uninit(timer); } diff --git a/ports/nordic/peripherals/nrf/timers.h b/ports/nordic/peripherals/nrf/timers.h index 44b8bc1bf04..ea6022ffd72 100644 --- a/ports/nordic/peripherals/nrf/timers.h +++ b/ports/nordic/peripherals/nrf/timers.h @@ -9,11 +9,8 @@ #include "nrfx.h" #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); diff --git a/ports/nordic/supervisor/cpu.s b/ports/nordic/supervisor/cpu.s deleted file mode 100755 index 9e6807a5e2e..00000000000 --- a/ports/nordic/supervisor/cpu.s +++ /dev/null @@ -1,27 +0,0 @@ -.syntax unified -.cpu cortex-m4 -.thumb -.text -.align 2 - -@ uint cpu_get_regs_and_sp(r0=uint regs[10]) -.global cpu_get_regs_and_sp -.thumb -.thumb_func -.type cpu_get_regs_and_sp, %function -cpu_get_regs_and_sp: -@ store registers into given array -str r4, [r0], #4 -str r5, [r0], #4 -str r6, [r0], #4 -str r7, [r0], #4 -str r8, [r0], #4 -str r9, [r0], #4 -str r10, [r0], #4 -str r11, [r0], #4 -str r12, [r0], #4 -str r13, [r0], #4 - -@ return the sp -mov r0, sp -bx lr diff --git a/ports/nordic/supervisor/internal_flash.c b/ports/nordic/supervisor/internal_flash.c index 88b6a274d06..82a687d1dd8 100644 --- a/ports/nordic/supervisor/internal_flash.c +++ b/ports/nordic/supervisor/internal_flash.c @@ -16,6 +16,7 @@ #include "lib/oofatfs/ff.h" #include "supervisor/shared/safe_mode.h" +#include "background.h" #include "peripherals/nrf/nvm.h" #ifdef BLUETOOTH_SD @@ -54,6 +55,7 @@ void port_internal_flash_flush(void) { // Skip if data is the same if (memcmp(_flash_cache, (void *)_flash_page_addr, FLASH_PAGE_SIZE) != 0) { + board_background_task(); if (!nrf_nvm_safe_flash_page_write(_flash_page_addr, _flash_cache)) { reset_into_safe_mode(SAFE_MODE_FLASH_WRITE_FAIL); } diff --git a/ports/nordic/supervisor/port.c b/ports/nordic/supervisor/port.c index ed371c6ad85..961d16c00f3 100644 --- a/ports/nordic/supervisor/port.c +++ b/ports/nordic/supervisor/port.c @@ -11,6 +11,8 @@ #include "supervisor/background_callback.h" #include "supervisor/board.h" +#include "board.h" + #include "nrfx/hal/nrf_clock.h" #include "nrfx/hal/nrf_power.h" #include "nrfx/drivers/include/nrfx_gpiote.h" @@ -22,7 +24,13 @@ #include "nrf/power.h" #include "nrf/timers.h" +#ifdef BLUETOOTH_SD #include "nrf_nvic.h" +#endif + +#if CIRCUITPY_EMMCIO +#include "shared-bindings/emmcio/__init__.h" +#endif #include "common-hal/microcontroller/Pin.h" #include "common-hal/alarm/time/TimeAlarm.h" @@ -34,7 +42,6 @@ #include "common-hal/watchdog/WatchDogTimer.h" #include "common-hal/alarm/__init__.h" -#include "shared-bindings/_bleio/__init__.h" #include "shared-bindings/microcontroller/__init__.h" #include "shared-bindings/rtc/__init__.h" @@ -52,6 +59,10 @@ extern void qspi_disable(void); #endif +// Do-nothing, not every board needs to provide this function. +MP_WEAK void board_early_init(void) { +} + static void power_warning_handler(void) { reset_into_safe_mode(SAFE_MODE_BROWNOUT); } @@ -131,6 +142,9 @@ void tick_set_prescaler(uint32_t prescaler_val) { } safe_mode_t port_init(void) { + // Before any peripheral is touched + board_early_init(); + nrf_peripherals_clocks_init(); // If GPIO voltage is set wrong in UICR, this will fix it, and @@ -175,10 +189,10 @@ safe_mode_t port_init(void) { // next time we reboot. if (reset_reason_saved & POWER_RESETREAS_DOG_Msk) { NRF_POWER->RESETREAS = POWER_RESETREAS_DOG_Msk; - uint32_t usb_reg = NRF_POWER->USBREGSTATUS; // If USB is connected, then the user might be editing `code.py`, // in which case we should reboot into Safe Mode. + uint32_t usb_reg = NRF_POWER->USBREGSTATUS; if (usb_reg & POWER_USBREGSTATUS_VBUSDETECT_Msk) { return SAFE_MODE_WATCHDOG; } @@ -188,42 +202,41 @@ safe_mode_t port_init(void) { } void reset_port(void) { - #if CIRCUITPY_BUSIO - spi_reset(); - uart_reset(); + #if CIRCUITPY_RTC + rtc_reset(); #endif #if CIRCUITPY_NEOPIXEL_WRITE + // Must run while the old GC heap is still alive so the pattern buffer is + // reclaimed instead of left dangling behind the root pointer. neopixel_write_reset(); #endif - #if CIRCUITPY_AUDIOBUSIO - i2s_reset(); + #if CIRCUITPY_EMMCIO + emmcio_reset(); #endif - #if CIRCUITPY_RTC - rtc_reset(); - #endif - - timers_reset(); - #if CIRCUITPY_WATCHDOG watchdog_reset(); #endif - // Always reset GPIOTE because it is shared. - if (nrfx_gpiote_is_init()) { - nrfx_gpiote_uninit(); + // GPIOTE is shared by every object that needs an event channel (pulseio, + // countio, rotaryio, max3421e, alarm pins). Initialize it once and never + // tear it down here: each object uninit's its own channel in deinit + // (via __del__), and alarm pins are released by alarm_reset() in main.c + // before reset_port() runs. + if (!nrfx_gpiote_is_init()) { + nrfx_gpiote_init(NRFX_GPIOTE_CONFIG_IRQ_PRIORITY); } - nrfx_gpiote_init(NRFX_GPIOTE_CONFIG_IRQ_PRIORITY); - - reset_all_pins(); } void reset_to_bootloader(void) { - enum { DFU_MAGIC_SERIAL = 0x4e }; - - NRF_POWER->GPREGRET = DFU_MAGIC_SERIAL; + NRF_POWER->GPREGRET = BOOTLOADER_DFU_MAGIC; + #ifdef BOOTLOADER_DFU_MAGIC2 + // This bootloader's magic is 16 bits wide, split across both retention + // registers. + NRF_POWER->GPREGRET2 = BOOTLOADER_DFU_MAGIC2; + #endif reset_cpu(); } @@ -326,6 +339,7 @@ void port_idle_until_interrupt(void) { (void)__get_FPSCR(); NVIC_ClearPendingIRQ(FPU_IRQn); } + #ifdef BLUETOOTH_SD uint8_t sd_enabled; sd_softdevice_is_enabled(&sd_enabled); @@ -333,7 +347,10 @@ void port_idle_until_interrupt(void) { if (!background_callback_pending()) { sd_app_evt_wait(); } - } else { + return; + } + #endif + { // Call wait for interrupt ourselves if the SD isn't enabled. // Note that `wfi` should be called with interrupts disabled, // to ensure that the queue is properly drained. The `wfi` diff --git a/ports/raspberrypi/Makefile b/ports/raspberrypi/Makefile old mode 100644 new mode 100755 index 9b582fce83c..3ad50711687 --- a/ports/raspberrypi/Makefile +++ b/ports/raspberrypi/Makefile @@ -25,7 +25,8 @@ INC_CYW43 := \ CFLAGS_CYW43 := \ -DCYW43_LWIP=1 \ -DPICO_CYW43_ARCH_THREADSAFE_BACKGROUND=1 \ - -DCYW43_USE_SPI \ + -DCYW43_USE_SPI=1 \ + -DUSE_SDIOIT=0 \ -DIGNORE_GPIO25 \ -DIGNORE_GPIO23 \ -DIGNORE_GPIO24 \ @@ -83,6 +84,33 @@ SRC_CYW43 := SRC_LWIP := endif +ifeq ($(CIRCUITPY_WIZNET), 1) +INC_WIZNET := \ + -isystem common-hal/wiznet \ + +SRC_WIZNET := \ + common-hal/wiznet/wizchip_pio_spi.c \ + +WIZNET_PIOASM = $(BUILD)/pioasm/pioasm/pioasm +.PHONY: pioasmBuild +pioasmBuild: $(WIZNET_PIOASM) + +$(WIZNET_PIOASM): + $(Q)cmake -S pioasm -B $(BUILD)/pioasm + $(MAKE) -C $(BUILD)/pioasm pioasmBuild + +$(BUILD)/wizchip_pio_spi.pio.h: common-hal/wiznet/wizchip_pio_spi.pio $(WIZNET_PIOASM) + $(Q)$(WIZNET_PIOASM) -o c-sdk $< $@ +$(BUILD)/common-hal/wiznet/wizchip_pio_spi.o: $(BUILD)/wizchip_pio_spi.pio.h + +$(BUILD)/genhdr/qstr.i.last: $(BUILD)/wizchip_pio_spi.pio.h + +else +INC_WIZNET := +SRC_WIZNET := + +endif + CHIP_VARIANT_LOWER = $(shell echo $(CHIP_VARIANT) | tr '[:upper:]' '[:lower:]') INC += \ @@ -125,6 +153,7 @@ INC += \ -isystem sdk/src/rp2_common/hardware_powman/include/ \ -isystem sdk/src/rp2_common/hardware_pwm/include/ \ -isystem sdk/src/rp2_common/hardware_resets/include/ \ + -isystem sdk/src/rp2_common/hardware_rcp/include/ \ -isystem sdk/src/rp2_common/hardware_rtc/include/ \ -isystem sdk/src/rp2_common/hardware_spi/include/ \ -isystem sdk/src/rp2_common/hardware_sync/include/ \ @@ -149,6 +178,7 @@ INC += \ -isystem sdk/src/rp2_common/pico_float/include/ \ -isystem sdk/src/rp2_common/pico_runtime/include/ \ -isystem sdk/src/rp2_common/pico_runtime_init/include/ \ + -isystem sdk/src/rp2_common/pico_platform_common/include/ \ -isystem sdk/src/rp2_common/pico_platform_compiler/include/ \ -isystem sdk/src/rp2_common/pico_platform_sections/include/ \ -isystem sdk/src/rp2_common/pico_platform_panic/include/ \ @@ -187,7 +217,14 @@ CFLAGS += \ -DPICO_NO_BI_BOOTSEL_VIA_DOUBLE_RESET=0 \ -DDVI_1BPP_BIT_REVERSE=0 -OPTIMIZATION_FLAGS ?= -O3 +# Shared IRQ handlers, counted over all IRQs: USB (2), CYW43, audio, rp2pio, PinAlarm and +# max3421e. The SDK default of 4 is too few on Pico W boards. +CFLAGS += -DPICO_MAX_SHARED_IRQ_HANDLERS=8 + +# -O2 plus the two -O3 flags that measure: -funswitch-loops (16 KB) carries the sprite +# blits, -fvect-cost-model=dynamic (4 KB) the fills and memcpy. Same speed as -O3 on both +# cores for about 125 KB less flash. Boards may override this in mpconfigboard.mk. +OPTIMIZATION_FLAGS ?= -O2 -funswitch-loops -fvect-cost-model=dynamic # TinyUSB defines CFLAGS += \ -DCFG_TUSB_OS=OPT_OS_PICO \ @@ -223,9 +260,13 @@ endif DISABLE_WARNINGS = -Wno-cast-align -CFLAGS += $(INC) -Wtype-limits -Wall -Werror -std=gnu11 -fshort-enums $(BASE_CFLAGS) $(CFLAGS_MOD) $(COPT) $(DISABLE_WARNINGS) -Werror=missing-prototypes +CFLAGS += $(INC) -Wtype-limits -Wall -Werror -std=gnu11 -fshort-enums $(BASE_CFLAGS) $(CFLAGS_MOD) $(COPT) $(DISABLE_WARNINGS) -Werror=missing-prototypes -Wold-style-definition PICO_LDFLAGS = --specs=nosys.specs --specs=nano.specs +# The SDK's panic() is flash-resident, but core1 may run with flash access +# disabled by the MPU. Route panics to the RAM-resident __wrap_panic in +# supervisor/port.c, which halts safely on core1 and prints on core0. +PICO_LDFLAGS += -Wl,--wrap=panic # Use toolchain libm if we're not using our own. ifndef INTERNAL_LIBM @@ -393,6 +434,8 @@ OTHER_PICO_FLAGS := \ -Wl,--wrap=__aeabi_uidivmod \ -Wl,--wrap=__aeabi_uldivmod +SRC_S = shared/runtime/gchelper_thumb1.s + ifeq ($(CHIP_VARIANT),RP2040) CFLAGS += \ -march=armv6-m \ @@ -402,8 +445,7 @@ CFLAGS += \ -msoft-float \ -mfloat-abi=soft -CFLAGS += \ - -DPICO_RP2040 +CFLAGS += -DPICO_RP2040=1 -DPICO_RP2350=0 SRC_SDK_CHIP_VARIANT := \ src/rp2_common/hardware_rtc/rtc.c \ @@ -431,12 +473,12 @@ UF2_ID = 0xE48BFF56 DOUBLE_EABI = rp2040 endif ifeq ($(CHIP_VARIANT),RP2350) -CFLAGS += \ - -march=armv8-m.main+fp+dsp \ +AFLAGS = -march=armv8-m.main+fp+dsp \ -mthumb \ - -mabi=aapcs-linux \ -mcpu=cortex-m33 \ -mfloat-abi=softfp +CFLAGS += $(AFLAGS) \ + -mabi=aapcs-linux # ARM Secure family id UF2_ID = 0xe48bff59 @@ -444,12 +486,22 @@ UF2_ID = 0xe48bff59 # Double coprocessor is only available on the ARM core. DOUBLE_EABI = dcp INC += \ - -isystem sdk/src/rp2_common/hardware_dcp/include/ + -isystem sdk/src/rp2_common/hardware_dcp/include/ \ + -isystem sdk/src/rp2_common/hardware_rosc/include/ \ + -isystem sdk/src/rp2_common/pico_low_power/include/ -CFLAGS += -DPICO_RP2350=1 +CFLAGS += -DPICO_RP2040=0 -DPICO_RP2350=1 + +# Make crt0 (the SDK's startup code) run our stage 2 at boot and copy it to boot +# RAM, so the SDK reruns it after each flash write. Otherwise the boot ROM's +# flash read setup is used. +CFLAGS += -DPICO_EMBED_XIP_SETUP=1 SRC_SDK_CHIP_VARIANT := \ + src/common/pico_util/fixed_bitset.c \ src/rp2_common/hardware_powman/powman.c \ + src/rp2_common/hardware_rosc/rosc.c \ + src/rp2_common/pico_low_power/low_power.c \ SRC_S_UPPER_CHIP_VARIANT := \ sdk/src/rp2_common/pico_double/double_conv_m33.S \ @@ -470,6 +522,18 @@ endif endif +SRC_C += shared/runtime/gchelper_native.c + +ifeq ($(CIRCUITPY_PICOGAME3D),1) +# SIO interpolator fast path for the picogame3d mode7 inner row (RP2040 + RP2350). +# Portable C remains the fallback on other ports. +SRC_C += common-hal/picogame3d/interp.c +CFLAGS += -DPICOGAME_HAS_INTERP=1 +endif + +ifeq ($(CIRCUITPY_BITMAPTOOLS_FAST_ROTOZOOM),1) +SRC_C += common-hal/bitmaptools/__init__.c +endif SRC_SDK := \ src/common/hardware_claim/claim.c \ @@ -524,14 +588,21 @@ SRC_SDK := \ SRC_SDK := $(addprefix sdk/, $(SRC_SDK)) $(patsubst %.c,$(BUILD)/%.o,$(SRC_SDK) $(SRC_CYW43)): CFLAGS += -Wno-missing-prototypes -Wno-undef -Wno-unused-function -Wno-nested-externs -Wno-strict-prototypes -Wno-double-promotion -Wno-sign-compare -Wno-unused-variable -Wno-strict-overflow -Ilib/cyw43-driver +# cyw43_ll.c assigns string literals to a non-const pointer in its scan IE parser. +$(BUILD)/lib/cyw43-driver/src/cyw43_ll.o: CFLAGS += -Wno-discarded-qualifiers SRC_C += \ boards/$(BOARD)/board.c \ boards/$(BOARD)/pins.c \ + common-hal/rtc/pico_time.c \ bindings/rp2pio/StateMachine.c \ bindings/rp2pio/__init__.c \ common-hal/rp2pio/StateMachine.c \ common-hal/rp2pio/__init__.c \ + bindings/wiznet/PIO_SPI.c \ + bindings/wiznet/__init__.c \ + common-hal/wiznet/PIO_SPI.c \ + common-hal/wiznet/__init__.c \ audio_dma.c \ background.c \ peripherals/pins.c \ @@ -541,6 +612,7 @@ SRC_C += \ mphalport.c \ $(SRC_CYW43) \ $(SRC_LWIP) \ + $(SRC_WIZNET) \ ifeq ($(CIRCUITPY_USB_HOST), 1) @@ -552,129 +624,165 @@ SRC_C += \ INC += \ -isystem lib/Pico-PIO-USB/src + +ifeq ($(CIRCUITPY_USB_HOST_BULK),1) +# Pico-PIO-USB bulk IN ring, polled from the host frame handler. +CFLAGS += -DPIO_USB_HOST_BULK_STREAM=1 +endif + +# Core1 posts USB events while core0 may hold the TinyUSB queue mutex. The +# contended wait path calls these two flash-resident SDK functions, and core1 +# must not execute from flash. Replace them with RAM-resident implementations +# in common-hal/usb_host/Port.c on USB host builds only. See issue #11116. +PICO_LDFLAGS += -Wl,--wrap=best_effort_wfe_or_timeout -Wl,--wrap=time_us_64 endif ifeq ($(CIRCUITPY_PICODVI),1) SRC_C += \ bindings/picodvi/__init__.c \ + bindings/picodvi/AudioOut.c \ bindings/picodvi/Framebuffer.c \ common-hal/picodvi/__init__.c \ common-hal/picodvi/Framebuffer_$(CHIP_VARIANT).c \ -ifeq ($(CHIP_VARIANT),RP2040) +ifeq ($(CIRCUITPY_PICODVI_AUDIOOUT),1) SRC_C += \ + common-hal/picodvi/AudioOut.c \ + common-hal/picodvi/dvi_audio_packet.c \ + +endif + +ifeq ($(CHIP_VARIANT),RP2040) +SRC_PICODVI := \ lib/PicoDVI/software/libdvi/dvi.c \ lib/PicoDVI/software/libdvi/dvi_serialiser.c \ lib/PicoDVI/software/libdvi/dvi_timing.c \ lib/PicoDVI/software/libdvi/tmds_encode.c \ +SRC_C += $(SRC_PICODVI) +$(patsubst %.c,$(BUILD)/%.o,$(SRC_PICODVI))): CFLAGS += -Wno-old-style-definition + endif endif +ifeq ($(CIRCUITPY_SDIOIO),1) +# Vendored Adafruit SdFat PIO SDIO card driver (C++). The common-hal C sources +# (SDCard.c, __init__.c) are picked up automatically through SRC_COMMON_HAL. +SRC_SDIOIO_CXX := \ + common-hal/sdioio/sdfat_pio/SdCard/PioSdio/PioSdioCard.cpp \ + common-hal/sdioio/sdfat_pio/shim.cpp \ + common-hal/sdioio/sdfat_pio/cxx_runtime.cpp \ + +INC += -Icommon-hal/sdioio/sdfat_pio + +# The upstream driver body is guarded by ARDUINO_ARCH_RP2040 and was written +# against the Arduino RP2040 core, so define that macro for it. It is vendored +# third-party code, so don't fail the build on its warnings. +$(BUILD)/common-hal/sdioio/sdfat_pio/SdCard/PioSdio/PioSdioCard.o: CXXFLAGS += -DARDUINO_ARCH_RP2040 -Wno-error +endif + ifeq ($(CIRCUITPY_SSL),1) -CFLAGS += -isystem $(TOP)/mbedtls/include -SRC_MBEDTLS := $(addprefix lib/mbedtls/library/, \ - aes.c \ - aesni.c \ - arc4.c \ - asn1parse.c \ - asn1write.c \ - base64.c \ - bignum.c \ - blowfish.c \ - camellia.c \ - ccm.c \ - certs.c \ - chacha20.c \ - chachapoly.c \ - cipher.c \ - cipher_wrap.c \ - cmac.c \ - constant_time.c \ - ctr_drbg.c \ - debug.c \ - des.c \ - dhm.c \ - ecdh.c \ - ecdsa.c \ - ecjpake.c \ - ecp.c \ - ecp_curves.c \ - entropy.c \ - entropy_poll.c \ - gcm.c \ - havege.c \ - hmac_drbg.c \ - md2.c \ - md4.c \ - md5.c \ - md.c \ - oid.c \ - padlock.c \ - pem.c \ - pk.c \ - pkcs11.c \ - pkcs12.c \ - pkcs5.c \ - pkparse.c \ - pk_wrap.c \ - pkwrite.c \ - platform.c \ - platform_util.c \ - poly1305.c \ - ripemd160.c \ - rsa.c \ - rsa_internal.c \ - sha1.c \ - sha256.c \ - sha512.c \ - ssl_cache.c \ - ssl_ciphersuites.c \ - ssl_cli.c \ - ssl_cookie.c \ - ssl_msg.c \ - ssl_srv.c \ - ssl_ticket.c \ - ssl_tls.c \ - timing.c \ - x509.c \ - x509_create.c \ - x509_crl.c \ - x509_crt.c \ - x509_csr.c \ - x509write_crt.c \ - x509write_csr.c \ - xtea.c \ - ) +# mbedtls 4.x keeps only TLS and X.509 in library/; crypto lives in the tf-psa-crypto +# submodule, split across core/, drivers/builtin/src/, extras/, platform/ and +# utilities/. +# +# Deliberately excluded: +# - mbedtls_config.c, tf_psa_crypto_config.c: pure config-validation translation +# units that #include generated *_config_check_*.h headers. Skipping them is what +# lets us skip that second code generator. +# - net_sockets.c: CircuitPython drives the socket through socketpool callbacks. +# - pkcs7.c: unused, and MBEDTLS_PKCS7_C is off. +# - psa_its_file.c: filesystem-backed PSA key storage; we have no persistent keys. +# - drivers/{everest,p256-m,pqcp}: alternative curve and ML-DSA implementations. +mbedtls_sources = $(patsubst $(TOP)/%,%,$(filter-out $(2),$(wildcard $(TOP)/$(1)/*.c))) + +SRC_MBEDTLS := \ + $(call mbedtls_sources,lib/mbedtls/library,\ + $(TOP)/lib/mbedtls/library/mbedtls_config.c \ + $(TOP)/lib/mbedtls/library/net_sockets.c \ + $(TOP)/lib/mbedtls/library/pkcs7.c) \ + $(call mbedtls_sources,lib/mbedtls/tf-psa-crypto/core,\ + $(TOP)/lib/mbedtls/tf-psa-crypto/core/psa_its_file.c \ + $(TOP)/lib/mbedtls/tf-psa-crypto/core/tf_psa_crypto_config.c) \ + $(call mbedtls_sources,lib/mbedtls/tf-psa-crypto/drivers/builtin/src) \ + $(call mbedtls_sources,lib/mbedtls/tf-psa-crypto/extras) \ + $(call mbedtls_sources,lib/mbedtls/tf-psa-crypto/platform) \ + $(call mbedtls_sources,lib/mbedtls/tf-psa-crypto/utilities) SRC_C += $(SRC_MBEDTLS) lib/mbedtls_config/mbedtls_port.c lib/mbedtls_config/crt_bundle.c +# Public headers of mbedtls and of tf-psa-crypto, then the internal ones. mbedtls 4.x +# still reaches into tf-psa-crypto's internals, so upstream compiles the TLS layer +# with both; see TF_PSA_CRYPTO_LIBRARY_{PUBLIC,PRIVATE}_INCLUDE in +# lib/mbedtls/tf-psa-crypto/scripts/crypto-common.make. CFLAGS += \ -isystem $(TOP)/lib/mbedtls/include \ + -isystem $(TOP)/lib/mbedtls/tf-psa-crypto/include \ + -isystem $(TOP)/lib/mbedtls/tf-psa-crypto/drivers/builtin/include \ + -isystem $(TOP)/lib/mbedtls/library \ + -isystem $(TOP)/lib/mbedtls/tf-psa-crypto/core \ + -isystem $(TOP)/lib/mbedtls/tf-psa-crypto/dispatch \ + -isystem $(TOP)/lib/mbedtls/tf-psa-crypto/drivers/builtin/src \ + -isystem $(TOP)/lib/mbedtls/tf-psa-crypto/extras \ + -isystem $(TOP)/lib/mbedtls/tf-psa-crypto/platform \ + -isystem $(TOP)/lib/mbedtls/tf-psa-crypto/utilities \ -DMBEDTLS_CONFIG_FILE='"$(TOP)/lib/mbedtls_config/mbedtls_config.h"' \ + -DTF_PSA_CRYPTO_CONFIG_FILE='"$(TOP)/lib/mbedtls_config/tf_psa_crypto_config.h"' \ -$(BUILD)/x509_crt_bundle.S: $(TOP)/lib/certificates/data/roots.pem $(TOP)/tools/gen_crt_bundle.py +# The generated bundle holds a hash of each root's subject name, not the name itself; +# the format is described in lib/mbedtls_config/crt_bundle.c. +$(BUILD)/x509_crt_bundle.S: $(TOP)/lib/certificates/data/roots-full.pem $(TOP)/tools/gen_crt_bundle.py $(Q)$(PYTHON) $(TOP)/tools/gen_crt_bundle.py -i $< -o $@ --asm OBJ_MBEDTLS := $(BUILD)/x509_crt_bundle.o -$(patsubst %.c,$(BUILD)/%.o,$(SRC_MBEDTLS))): CFLAGS += -Wno-suggest-attribute=format + +# mbedtls 4.x dispatches PSA crypto through a wrapper layer that is generated from +# jinja templates rather than shipped in the repo, so build it. +# It is the same each time, so we could save it, but this makes updating mbedtls easier. +# +# generate_driver_wrappers.py resolves `mbedtls_framework` relative to its own tree, +# which would mean initializing a third nested submodule (tf-psa-crypto/framework). +# Point PYTHONPATH at the top-level framework submodule instead; mbedtls pins both to +# the same commit. +MBEDTLS_GEN := $(BUILD)/tf-psa-crypto +MBEDTLS_WRAPPERS_H := $(MBEDTLS_GEN)/psa_crypto_driver_wrappers.h +MBEDTLS_WRAPPERS_C := $(MBEDTLS_GEN)/psa_crypto_driver_wrappers_no_static.c + +# The script writes both files at once. Naming both as targets of one rule would run +# it twice; see the same workaround in py/py.mk. +$(MBEDTLS_WRAPPERS_C): $(MBEDTLS_WRAPPERS_H) + @true + +$(MBEDTLS_WRAPPERS_H): $(TOP)/lib/mbedtls/tf-psa-crypto/scripts/generate_driver_wrappers.py $(MBEDTLS_DISPATCH_STAMP) + $(STEPECHO) "GEN $@" + $(Q)mkdir -p $(MBEDTLS_GEN) + $(Q)PYTHONPATH=$(TOP)/lib/mbedtls/framework/scripts $(PYTHON) $< $(MBEDTLS_WRAPPERS_ARGS) $(MBEDTLS_GEN) + +OBJ_MBEDTLS += $(MBEDTLS_WRAPPERS_C:.c=.o) +CFLAGS += -I$(MBEDTLS_GEN) + +# psa_crypto.c and friends #include the generated header, so it has to exist before +# any of them compile. +$(patsubst %.c,$(BUILD)/%.o,$(SRC_MBEDTLS)) $(OBJ_MBEDTLS): $(MBEDTLS_WRAPPERS_H) +# Vendored third-party code, so don't hold it to CircuitPython's warning settings. The +# unused-but-set variables are real but harmless: they are in key-exchange paths that +# are compiled out. gcc 15.3 reports false array-bounds errors in the inlined +# mbedtls_xor_no_simd() in gcm.c and aes.c on RP2350. +$(patsubst %.c,$(BUILD)/%.o,$(SRC_MBEDTLS)) $(OBJ_MBEDTLS): CFLAGS += \ + -Wno-array-bounds \ + -Wno-suggest-attribute=format \ + -Wno-unused-but-set-variable else OBJ_MBEDTLS := endif +# SHA-256 on the RP2350 SHA-256 block, as a PSA driver that mbedtls's hash dispatch +# calls before its builtin code. The default and MBEDTLS_DRIVER_PATCH, which adds +# the driver to the dispatch, are set in mpconfigport.mk. +ifeq ($(CIRCUITPY_RP2_SHA256_HW),1) +SRC_C += sha256_psa/rp2_sha256_psa.c +CFLAGS += -Isha256_psa -isystem sdk/src/rp2_common/hardware_sha256/include/ +endif +CFLAGS += -DCIRCUITPY_RP2_SHA256_HW=$(CIRCUITPY_RP2_SHA256_HW) -SRC_COMMON_HAL_EXPANDED = $(addprefix shared-bindings/, $(SRC_COMMON_HAL)) \ - $(addprefix shared-bindings/, $(SRC_BINDINGS_ENUMS)) \ - $(addprefix common-hal/, $(SRC_COMMON_HAL)) - -SRC_SHARED_MODULE_EXPANDED = $(addprefix shared-bindings/, $(SRC_SHARED_MODULE)) \ - $(addprefix shared-module/, $(SRC_SHARED_MODULE)) \ - $(addprefix shared-module/, $(SRC_SHARED_MODULE_INTERNAL)) - -# There may be duplicates between SRC_COMMON_HAL_EXPANDED and SRC_SHARED_MODULE_EXPANDED, -# because a few modules have files both in common-hal/ and shared-module/. -# Doing a $(sort ...) removes duplicates as part of sorting. -SRC_COMMON_HAL_SHARED_MODULE_EXPANDED = $(sort $(SRC_COMMON_HAL_EXPANDED) $(SRC_SHARED_MODULE_EXPANDED)) - -SRC_S = supervisor/$(CHIP_FAMILY)_cpu.s BOOT2_S_CFLAGS ?= -DPICO_FLASH_SPI_CLKDIV=4 SRC_S_UPPER = sdk/src/rp2_common/hardware_irq/irq_handler_chain.S \ sdk/src/rp2_common/pico_bit_ops/bit_ops_aeabi.S \ @@ -690,6 +798,11 @@ endif $(patsubst %.S,$(BUILD)/%.o,$(SRC_S_UPPER)): CFLAGS += -Wno-undef +# py/mkrules.mk derives CXXFLAGS from CFLAGS, which gives the vendored C++ +# translation unit the SDK include paths and defines. Only the C++-specific +# options belong here. +CXXFLAGS += -std=gnu++17 -fno-exceptions -fno-rtti + OBJ = $(PY_O) $(SUPERVISOR_O) $(addprefix $(BUILD)/, $(SRC_C:.c=.o)) OBJ += $(addprefix $(BUILD)/, $(SRC_SDK:.c=.o)) OBJ += $(addprefix $(BUILD)/, $(SRC_COMMON_HAL_SHARED_MODULE_EXPANDED:.c=.o)) @@ -702,14 +815,25 @@ OBJ += $(addprefix $(BUILD)/, $(SRC_S_UPPER:.S=.o)) OBJ += $(addprefix $(BUILD)/, $(SRC_MOD:.c=.o)) OBJ += $(BUILD)/boot2_padded_checksummed.o OBJ += $(OBJ_MBEDTLS) +ifeq ($(CIRCUITPY_SDIOIO),1) +OBJ += $(addprefix $(BUILD)/, $(SRC_SDIOIO_CXX:.cpp=.o)) +endif $(BUILD)/%.o: $(BUILD)/%.S $(STEPECHO) "CC $<" $(Q)$(CC) $(CFLAGS) -c -o $@ $< +# RP2350 stage 2 has no checksum, so it is padded without one. The SDK's RP2350 +# pad script also defines __boot2_entry_point, which crt0 uses to run stage 2 +# and copy it to boot RAM. $(BUILD)/boot2_padded_checksummed.S: $(BUILD)/boot2.bin +ifeq ($(CHIP_VARIANT),RP2350) + $(STEPECHO) "PAD $<" + $(Q)$(PYTHON) sdk/src/rp2350/boot_stage2/pad $< $@ +else $(STEPECHO) "PAD_CHECKSUM $<" $(Q)$(PYTHON) sdk/src/rp2040/boot_stage2/pad_checksum -s 0xffffffff $< $@ +endif $(BUILD)/boot2.bin: $(BUILD)/boot2.elf $(STEPECHO) "OBJCOPY $<" @@ -726,13 +850,14 @@ $(HEADER_BUILD)/flash_info.h: flash_info.h.jinja gen_stage2.py $(Q)$(PYTHON) gen_stage2.py $< $@ $(EXTERNAL_FLASH_DEVICES) $(BUILD)/supervisor/internal_flash.o: $(HEADER_BUILD)/flash_info.h +$(BUILD)/common-hal/microcontroller/Processor.o: $(HEADER_BUILD)/flash_info.h $(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/$(CHIP_VARIANT).ld -Wl,-Map=$@.map -o $@ $< $(Q)$(SIZE) $@ -SRC_QSTR += $(SRC_C) $(SRC_SUPERVISOR) $(SRC_COMMON_HAL_EXPANDED) $(SRC_SHARED_MODULE_EXPANDED) $(SRC_CIRCUITPY_COMMON) +SRC_QSTR += $(SRC_C) $(SRC_SUPERVISOR) $(SRC_COMMON_HAL_SHARED_MODULE_EXPANDED) $(SRC_CIRCUITPY_COMMON) all: $(BUILD)/firmware.uf2 @@ -744,6 +869,21 @@ endif LINKER_SCRIPTS += -Wl,-T,link-$(CHIP_VARIANT_LOWER).ld +# Builds where core1 locks flash out via the MPU and may only execute +# RAM-resident code: USB host (PIO-USB frame loop), and picodvi on RP2040 +# (TMDS encode loop). Check the linked ELF from each core1 entry point. +# picodvi's DMA IRQ handler and scanline callback run on core1 but are +# reached only through registered pointers, so they are extra roots. +CORE1_CHECK_ROOTS := +ifeq ($(CIRCUITPY_USB_HOST),1) +CORE1_CHECK_ROOTS += --root core1_main +endif +ifeq ($(CHIP_VARIANT),RP2040) +ifeq ($(CIRCUITPY_PICODVI),1) +CORE1_CHECK_ROOTS += --root core1_main --root dvi_dma1_irq --root core1_scanline_callback +endif +endif + ifeq ($(VALID_BOARD),) $(BUILD)/firmware.elf: invalid-board else @@ -752,6 +892,11 @@ $(BUILD)/firmware.elf: $(OBJ) $(BOARD_LD) link-$(CHIP_VARIANT_LOWER).ld $(Q)echo $(OBJ) > $(BUILD)/firmware.objs $(Q)echo $(PICO_LDFLAGS) > $(BUILD)/firmware.ldflags $(Q)$(CC) -o $@ $(CFLAGS) @$(BUILD)/firmware.ldflags $(LINKER_SCRIPTS) -Wl,--print-memory-usage -Wl,-Map=$@.map -Wl,-cref -Wl,--gc-sections @$(BUILD)/firmware.objs -Wl,-lc + $(Q)$(PYTHON) $(TOP)/tools/build_memory_info.py $@.map $(BUILD) --elf $@ +ifneq ($(CORE1_CHECK_ROOTS),) + $(STEPECHO) "CHECK core1 flash calls" + $(Q)$(PYTHON) $(TOP)/tools/check_core1_flash_calls.py $@ $(CORE1_CHECK_ROOTS) +endif endif $(BUILD)/firmware.bin: $(BUILD)/firmware.elf diff --git a/ports/raspberrypi/audio_dma.c b/ports/raspberrypi/audio_dma.c index c17ec102297..23c568ace14 100644 --- a/ports/raspberrypi/audio_dma.c +++ b/ports/raspberrypi/audio_dma.c @@ -9,28 +9,27 @@ #include "shared-bindings/audiocore/RawSample.h" #include "shared-bindings/audiocore/WaveFile.h" #include "shared-bindings/microcontroller/__init__.h" -#include "bindings/rp2pio/StateMachine.h" #include "supervisor/background_callback.h" #include "py/mpstate.h" #include "py/runtime.h" #include "hardware/irq.h" -#include "hardware/regs/intctrl.h" // For isr_ macro. #if CIRCUITPY_AUDIOCORE -void audio_dma_reset(void) { - for (size_t channel = 0; channel < NUM_DMA_CHANNELS; channel++) { - if (MP_STATE_PORT(playing_audio)[channel] == NULL) { - continue; - } - - audio_dma_stop(MP_STATE_PORT(playing_audio)[channel]); - } -} +// audio_dma and rp2pio cooperate on DMA_IRQ_0 using the SDK's shared interrupt +// handlers. We add our handler when we enable our first channel and remove it +// when our last channel is disabled. See the DMA IRQ allocation notes in +// common-hal/microcontroller/__init__.c. +static void audio_dma_enable_irq(uint channel); +static void audio_dma_disable_irq(uint channel); +// Start address of each looping single buffer sample, by DMA channel. The reload DMA reads it +// once per loop, so it is kept here instead of in the audio object, which may be in PSRAM. +// A DMA read from PSRAM stalls the other DMA channels, such as picodvi. +static uint8_t *single_buffer_start[NUM_DMA_CHANNELS]; static size_t audio_dma_convert_samples(audio_dma_t *dma, uint8_t *input, uint32_t input_length, uint8_t *output, uint32_t output_length) { #pragma GCC diagnostic push @@ -159,9 +158,15 @@ static void audio_dma_load_next_block(audio_dma_t *dma, size_t buffer_idx) { !dma_channel_is_busy(dma->channel[1])) { // No data has been read, and both DMA channels have now finished, so it's safe to stop. audio_dma_stop(dma); + dma->dma_result = AUDIO_DMA_OK; + return; } } } + // Enable the channel so that it can be played. + if (!dma->paused) { + dma_hw->ch[dma_channel].al1_ctrl |= DMA_CH1_CTRL_TRIG_EN_BITS; + } dma->dma_result = AUDIO_DMA_OK; } @@ -216,6 +221,7 @@ audio_dma_result audio_dma_setup_playback( uint32_t max_buffer_length; audiosample_get_buffer_structure(sample, single_channel_output, &single_buffer, &samples_signed, &max_buffer_length, &dma->sample_spacing); + dma->single_buffer = single_buffer; // Check to see if we have to scale the resolution up. if (dma->sample_resolution <= 8 && dma->output_resolution > 8) { @@ -227,12 +233,15 @@ audio_dma_result audio_dma_setup_playback( max_buffer_length /= dma->sample_spacing; } + #if PICO_RP2350 + dma->buffer[0] = (uint8_t *)port_realloc(dma->buffer[0], max_buffer_length, true); + #else dma->buffer[0] = (uint8_t *)m_realloc(dma->buffer[0], #if MICROPY_MALLOC_USES_ALLOCATED_SIZE dma->buffer_length[0], // Old size #endif max_buffer_length); - + #endif dma->buffer_length[0] = max_buffer_length; if (dma->buffer[0] == NULL) { @@ -240,12 +249,15 @@ audio_dma_result audio_dma_setup_playback( } if (!single_buffer) { + #if PICO_RP2350 + dma->buffer[1] = (uint8_t *)port_realloc(dma->buffer[1], max_buffer_length, true); + #else dma->buffer[1] = (uint8_t *)m_realloc(dma->buffer[1], #if MICROPY_MALLOC_USES_ALLOCATED_SIZE dma->buffer_length[1], // Old size #endif max_buffer_length); - + #endif dma->buffer_length[1] = max_buffer_length; if (dma->buffer[1] == NULL) { @@ -291,6 +303,8 @@ audio_dma_result audio_dma_setup_playback( MP_STATE_PORT(playing_audio)[dma->channel[0]] = dma; MP_STATE_PORT(playing_audio)[dma->channel[1]] = dma; + dma->paused = false; + // Load the first two blocks up front. audio_dma_load_next_block(dma, 0); if (dma->dma_result != AUDIO_DMA_OK) { @@ -309,6 +323,7 @@ audio_dma_result audio_dma_setup_playback( // 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) { + single_buffer_start[dma->channel[0]] = dma->buffer[0]; 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 @@ -317,14 +332,14 @@ audio_dma_result audio_dma_setup_playback( 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->buffer[0], // read address + &single_buffer_start[dma->channel[0]], // read address 1, // transaction count false); // trigger } else { // Enable our DMA channels on DMA_IRQ_0 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); + audio_dma_enable_irq(dma->channel[0]); + audio_dma_enable_irq(dma->channel[1]); } dma->playing_in_progress = true; @@ -334,17 +349,14 @@ audio_dma_result audio_dma_setup_playback( } void audio_dma_stop(audio_dma_t *dma) { + dma->paused = true; + // Disable our interrupts. - uint32_t channel_mask = 0; if (dma->channel[0] < NUM_DMA_CHANNELS) { - channel_mask |= 1 << dma->channel[0]; + audio_dma_disable_irq(dma->channel[0]); } if (dma->channel[1] < NUM_DMA_CHANNELS) { - channel_mask |= 1 << dma->channel[1]; - } - dma_hw->inte0 &= ~channel_mask; - if (!dma_hw->inte0) { - irq_set_mask_enabled(1 << DMA_IRQ_0, false); + audio_dma_disable_irq(dma->channel[1]); } // Run any remaining audio tasks because we remove ourselves from @@ -353,12 +365,13 @@ void audio_dma_stop(audio_dma_t *dma) { for (size_t i = 0; i < 2; i++) { size_t channel = dma->channel[i]; + dma->channel[i] = NUM_DMA_CHANNELS; if (channel == NUM_DMA_CHANNELS) { // Channel not in use. continue; } - dma_channel_config c = dma_channel_get_default_config(dma->channel[i]); + dma_channel_config c = dma_channel_get_default_config(channel); channel_config_set_enable(&c, false); dma_channel_set_config(channel, &c, false /* trigger */); @@ -371,7 +384,6 @@ void audio_dma_stop(audio_dma_t *dma) { 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; } dma->playing_in_progress = false; @@ -383,6 +395,7 @@ void audio_dma_stop(audio_dma_t *dma) { void audio_dma_pause(audio_dma_t *dma) { dma_hw->ch[dma->channel[0]].al1_ctrl &= ~DMA_CH0_CTRL_TRIG_EN_BITS; dma_hw->ch[dma->channel[1]].al1_ctrl &= ~DMA_CH1_CTRL_TRIG_EN_BITS; + dma->paused = true; } void audio_dma_resume(audio_dma_t *dma) { @@ -395,15 +408,14 @@ void audio_dma_resume(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_CH1_CTRL_TRIG_EN_BITS; } + dma->paused = false; } bool audio_dma_get_paused(audio_dma_t *dma) { if (dma->channel[0] >= NUM_DMA_CHANNELS) { return false; } - uint32_t control = dma_hw->ch[dma->channel[0]].ctrl_trig; - - return (control & DMA_CH0_CTRL_TRIG_EN_BITS) == 0; + return dma->playing_in_progress && dma->paused; } uint32_t audio_dma_pause_all(void) { @@ -436,24 +448,33 @@ void audio_dma_init(audio_dma_t *dma) { dma->channel[0] = NUM_DMA_CHANNELS; dma->channel[1] = NUM_DMA_CHANNELS; + + dma->playing_in_progress = false; + dma->paused = false; } void audio_dma_deinit(audio_dma_t *dma) { + #if PICO_RP2350 + port_free(dma->buffer[0]); + #else #if MICROPY_MALLOC_USES_ALLOCATED_SIZE m_free(dma->buffer[0], dma->buffer_length[0]); #else m_free(dma->buffer[0]); #endif - + #endif dma->buffer[0] = NULL; dma->buffer_length[0] = 0; + #if PICO_RP2350 + port_free(dma->buffer[1]); + #else #if MICROPY_MALLOC_USES_ALLOCATED_SIZE m_free(dma->buffer[1], dma->buffer_length[1]); #else m_free(dma->buffer[1]); #endif - + #endif dma->buffer[1] = NULL; dma->buffer_length[1] = 0; } @@ -462,6 +483,15 @@ bool audio_dma_get_playing(audio_dma_t *dma) { if (dma->channel[0] == NUM_DMA_CHANNELS) { return false; } + // A single-buffer, non-looping sample plays entirely in hardware via DMA + // chaining, with no completion interrupt to stop it. Detect when its DMA + // channel has drained and finish so that playing_in_progress is cleared. + if (dma->single_buffer && !dma->loop && + dma->playing_in_progress && !dma->paused && + !dma_channel_is_busy(dma->channel[0])) { + audio_dma_stop(dma); + return false; + } return dma->playing_in_progress; } @@ -470,6 +500,8 @@ bool audio_dma_get_playing(audio_dma_t *dma) { // NOTE(dhalbert): I successfully printed from here while debugging. // So it's possible, but be careful. static void dma_callback_fun(void *arg) { + // Any audio interrupts that happen below will requeue the background task + // after updating channels_to_load_mask. audio_dma_t *dma = arg; if (dma == NULL) { return; @@ -477,50 +509,85 @@ static void dma_callback_fun(void *arg) { common_hal_mcu_disable_interrupts(); uint32_t channels_to_load_mask = dma->channels_to_load_mask; + // This can be 0 if the background task was queued between the call to + // dma_callback_fun and the above read of channels_to_load_mask. dma->channels_to_load_mask = 0; common_hal_mcu_enable_interrupts(); - // Load the blocks for the requested channels. - uint32_t channel = 0; - while (channels_to_load_mask) { - if (channels_to_load_mask & 1) { - if (dma->channel[0] == channel) { - audio_dma_load_next_block(dma, 0); - } - if (dma->channel[1] == channel) { - audio_dma_load_next_block(dma, 1); - } - } - channels_to_load_mask >>= 1; - channel++; + uint8_t first_filled_channel = NUM_DMA_CHANNELS; + size_t filled_count = 0; + if (dma->channel[0] != NUM_DMA_CHANNELS && (channels_to_load_mask & (1 << dma->channel[0]))) { + audio_dma_load_next_block(dma, 0); + first_filled_channel = dma->channel[0]; + filled_count++; + } + if (dma->channel[1] != NUM_DMA_CHANNELS && (channels_to_load_mask & (1 << dma->channel[1]))) { + audio_dma_load_next_block(dma, 1); + first_filled_channel = dma->channel[1]; + filled_count++; + } + + // Restart if the other channel has been queued while we were filling the first or we filled two + // now. (Two get filled if the second buffer completes while the first is waiting in the + // background task queue.) + if (first_filled_channel != NUM_DMA_CHANNELS && (dma->channels_to_load_mask != 0 || filled_count == 2)) { + dma_channel_start(first_filled_channel); } } -void __not_in_flash_func(isr_dma_0)(void) { +// Shared DMA_IRQ_0 handler for audio. It acknowledges and services only audio +// channels, leaving any other channels' interrupts for the other shared +// handlers (e.g. rp2pio) to acknowledge. +static void __not_in_flash_func(audio_dma_irq_handler)(void) { for (size_t i = 0; i < NUM_DMA_CHANNELS; i++) { uint32_t mask = 1 << i; if ((dma_hw->ints0 & mask) == 0) { continue; } + audio_dma_t *dma = MP_STATE_PORT(playing_audio)[i]; + if (dma == NULL) { + // Not one of our channels; leave it for another shared handler. + continue; + } // acknowledge interrupt early. Doing so late means that you could lose an // interrupt if the buffer is very small and the DMA operation // completed by the time callback_add() / dma_complete() returned. This // affected PIO continuous write more than audio. dma_hw->ints0 = mask; - if (MP_STATE_PORT(playing_audio)[i] != NULL) { - audio_dma_t *dma = MP_STATE_PORT(playing_audio)[i]; - // Record all channels whose DMA has completed; they need loading. - dma->channels_to_load_mask |= mask; - background_callback_add(&dma->callback, dma_callback_fun, (void *)dma); - } - if (MP_STATE_PORT(background_pio_read)[i] != NULL) { - rp2pio_statemachine_obj_t *pio = MP_STATE_PORT(background_pio_read)[i]; - rp2pio_statemachine_dma_complete_read(pio, i); - } - if (MP_STATE_PORT(background_pio_write)[i] != NULL) { - rp2pio_statemachine_obj_t *pio = MP_STATE_PORT(background_pio_write)[i]; - rp2pio_statemachine_dma_complete_write(pio, i); - } + // Record all channels whose DMA has completed; they need loading. + dma->channels_to_load_mask |= mask; + // Disable the channel so that we don't play it without filling it. + dma_hw->ch[i].al1_ctrl &= ~DMA_CH0_CTRL_TRIG_EN_BITS; + // This is a noop if the callback is already queued. + background_callback_add(&dma->callback, dma_callback_fun, (void *)dma); + } +} + +// Channels (bitmask) audio currently has enabled on DMA_IRQ_0. Used to decide +// when to add/remove our shared interrupt handler. +static uint32_t audio_dma_irq0_channel_mask = 0; + +static void audio_dma_enable_irq(uint channel) { + // Clear any latent interrupt so that we don't immediately disable the channel. + dma_hw->ints0 = 1u << channel; + if (audio_dma_irq0_channel_mask == 0) { + irq_add_shared_handler(DMA_IRQ_0, audio_dma_irq_handler, + PICO_SHARED_IRQ_HANDLER_DEFAULT_ORDER_PRIORITY); + } + audio_dma_irq0_channel_mask |= 1u << channel; + dma_irqn_set_channel_enabled(0, channel, true); + irq_set_enabled(DMA_IRQ_0, true); +} + +static void audio_dma_disable_irq(uint channel) { + dma_irqn_set_channel_enabled(0, channel, false); + audio_dma_irq0_channel_mask &= ~(1u << channel); + if (audio_dma_irq0_channel_mask == 0) { + irq_remove_handler(DMA_IRQ_0, audio_dma_irq_handler); + } + // Turn off the IRQ line entirely once no one (audio or rp2pio) needs it. + if (dma_hw->inte0 == 0) { + irq_set_enabled(DMA_IRQ_0, false); } } diff --git a/ports/raspberrypi/audio_dma.h b/ports/raspberrypi/audio_dma.h index 48cc024fda9..4e00ce51c2d 100644 --- a/ports/raspberrypi/audio_dma.h +++ b/ports/raspberrypi/audio_dma.h @@ -20,7 +20,7 @@ typedef enum { typedef struct { mp_obj_t sample; - uint8_t *buffer[2]; + uint8_t *buffer[2]; // Allocated through port_malloc on RP2350 so they are dma-able size_t buffer_length[2]; uint32_t channels_to_load_mask; uint32_t output_register_address; @@ -33,17 +33,18 @@ typedef struct { uint8_t sample_resolution; // in bits audio_dma_result dma_result; bool loop; + bool single_buffer; bool single_channel_output; bool signed_to_unsigned; bool unsigned_to_signed; bool output_signed; bool playing_in_progress; + bool paused; bool swap_channel; } audio_dma_t; 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. diff --git a/ports/raspberrypi/bindings/cyw43/__init__.c b/ports/raspberrypi/bindings/cyw43/__init__.c index 36ac3ff7b62..93755d6ce1e 100644 --- a/ports/raspberrypi/bindings/cyw43/__init__.c +++ b/ports/raspberrypi/bindings/cyw43/__init__.c @@ -16,7 +16,7 @@ #include "lib/cyw43-driver/src/cyw43.h" -static int power_management_value = PM_DISABLED; +static uint32_t power_management_value = CONST_CYW43_DEFAULT_PM; void cyw43_enter_deep_sleep(void) { #define WL_REG_ON 23 @@ -43,14 +43,23 @@ MP_DEFINE_CONST_OBJ_TYPE( print, shared_bindings_microcontroller_pin_print ); +uint32_t cyw43_get_power_management_value(void) { + return power_management_value; +} + +void cyw43_set_power_management_value(uint32_t value) { + power_management_value = value; + bindings_cyw43_wifi_enforce_pm(); +} + //| PM_STANDARD: int -//| """The standard power management mode""" +//| """The default power management mode; same as PM_PERFORMANCE""" //| PM_AGGRESSIVE: int //| """Aggressive power management mode for optimal power usage at the cost of performance""" //| PM_PERFORMANCE: int //| """Performance power management mode where more power is used to increase performance""" //| PM_DISABLED: int -//| """Disable power management and always use highest power mode. CircuitPython sets this value at reset time, because it provides the best connectivity reliability.""" +//| """Disable power management and always use highest power mode.""" //| //| //| def set_power_management(value: int) -> None: @@ -85,8 +94,7 @@ MP_DEFINE_CONST_OBJ_TYPE( //| static mp_obj_t cyw43_set_power_management(const mp_obj_t value_in) { mp_int_t value = mp_obj_get_int(value_in); - power_management_value = value; - bindings_cyw43_wifi_enforce_pm(); + cyw43_set_power_management_value(value); return mp_const_none; } static MP_DEFINE_CONST_FUN_OBJ_1(cyw43_set_power_management_obj, cyw43_set_power_management); @@ -95,7 +103,7 @@ static MP_DEFINE_CONST_FUN_OBJ_1(cyw43_set_power_management_obj, cyw43_set_power //| """Retrieve the power management register""" //| //| -static mp_obj_t cyw43_get_power_management() { +static mp_obj_t cyw43_get_power_management(void) { return mp_obj_new_int(power_management_value); } static MP_DEFINE_CONST_FUN_OBJ_0(cyw43_get_power_management_obj, cyw43_get_power_management); @@ -126,10 +134,10 @@ static const mp_rom_map_elem_t cyw43_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_CywPin), MP_ROM_PTR(&cyw43_pin_type) }, { MP_ROM_QSTR(MP_QSTR_set_power_management), &cyw43_set_power_management_obj }, { MP_ROM_QSTR(MP_QSTR_get_power_management), &cyw43_get_power_management_obj }, - { MP_ROM_QSTR(MP_QSTR_PM_STANDARD), MP_ROM_INT(PM_STANDARD) }, - { MP_ROM_QSTR(MP_QSTR_PM_AGGRESSIVE), MP_ROM_INT(PM_AGGRESSIVE) }, - { MP_ROM_QSTR(MP_QSTR_PM_PERFORMANCE), MP_ROM_INT(PM_PERFORMANCE) }, - { MP_ROM_QSTR(MP_QSTR_PM_DISABLED), MP_ROM_INT(PM_DISABLED) }, + { MP_ROM_QSTR(MP_QSTR_PM_STANDARD), MP_ROM_INT(CONST_CYW43_DEFAULT_PM) }, + { MP_ROM_QSTR(MP_QSTR_PM_AGGRESSIVE), MP_ROM_INT(CONST_CYW43_AGGRESSIVE_PM) }, + { MP_ROM_QSTR(MP_QSTR_PM_PERFORMANCE), MP_ROM_INT(CONST_CYW43_PERFORMANCE_PM) }, + { MP_ROM_QSTR(MP_QSTR_PM_DISABLED), MP_ROM_INT(CONST_CYW43_NONE_PM) }, }; static MP_DEFINE_CONST_DICT(cyw43_module_globals, cyw43_module_globals_table); diff --git a/ports/raspberrypi/bindings/cyw43/__init__.h b/ports/raspberrypi/bindings/cyw43/__init__.h index 51657b075d2..70f9ec294fb 100644 --- a/ports/raspberrypi/bindings/cyw43/__init__.h +++ b/ports/raspberrypi/bindings/cyw43/__init__.h @@ -16,21 +16,25 @@ const mcu_pin_obj_t *validate_obj_is_free_pin_including_cyw43(mp_obj_t obj, qstr const mcu_pin_obj_t *validate_obj_is_free_pin_or_gpio29(mp_obj_t obj, qstr arg_name); const mcu_pin_obj_t *validate_obj_is_pin_including_cyw43(mp_obj_t obj, qstr arg_name); -#define CONSTANT_CYW43_PM_VALUE(pm_mode, pm2_sleep_ret_ms, li_beacon_period, li_dtim_period, li_assoc) \ +// This is equivalent to the code in cyw43.h, except that the values are computed at compile time. +// A `CONST_` prefix has been added to the computation function (expressed as a macro) and the values. + +#define CONST_cyw43_pm_value(pm_mode, pm2_sleep_ret_ms, li_beacon_period, li_dtim_period, li_assoc) \ (li_assoc << 20 | /* listen interval sent to ap */ \ li_dtim_period << 16 | \ li_beacon_period << 12 | \ (pm2_sleep_ret_ms / 10) << 4 | /* cyw43_ll_wifi_pm multiplies this by 10 */ \ pm_mode /* CYW43_PM2_POWERSAVE_MODE etc */) -// CYW43_DEFAULT_PM (except a compile-time constant) -#define PM_STANDARD CONSTANT_CYW43_PM_VALUE(CYW43_PM2_POWERSAVE_MODE, 200, 1, 1, 10) -// CYW43_AGGRESSIVE_PM (except a compile-time constant) -#define PM_AGGRESSIVE CONSTANT_CYW43_PM_VALUE(CYW43_PM2_POWERSAVE_MODE, 2000, 1, 1, 10) -// CYW43_PERFORMANCE_PM (except a compile-time constant) -#define PM_PERFORMANCE CONSTANT_CYW43_PM_VALUE(CYW43_PM2_POWERSAVE_MODE, 20, 1, 1, 1) -// The 0xa11140 magic value -#define PM_DISABLED CONSTANT_CYW43_PM_VALUE(CYW43_NO_POWERSAVE_MODE, 200, 1, 1, 10) +#define CONST_CYW43_DEFAULT_PM (CONST_CYW43_PERFORMANCE_PM) + +#define CONST_CYW43_NONE_PM (CONST_cyw43_pm_value(CYW43_NO_POWERSAVE_MODE, 10, 0, 0, 0)) + +#define CONST_CYW43_AGGRESSIVE_PM (CONST_cyw43_pm_value(CYW43_PM1_POWERSAVE_MODE, 10, 0, 0, 0)) + +#define CONST_CYW43_PERFORMANCE_PM (CONST_cyw43_pm_value(CYW43_PM2_POWERSAVE_MODE, 200, 1, 1, 10)) +extern uint32_t cyw43_get_power_management_value(void); +extern void cyw43_set_power_management_value(uint32_t value); extern void bindings_cyw43_wifi_enforce_pm(void); void cyw43_enter_deep_sleep(void); diff --git a/ports/raspberrypi/bindings/picodvi/AudioOut.c b/ports/raspberrypi/bindings/picodvi/AudioOut.c new file mode 100644 index 00000000000..f5b61ace1b7 --- /dev/null +++ b/ports/raspberrypi/bindings/picodvi/AudioOut.c @@ -0,0 +1,236 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared/runtime/context_manager_helpers.h" +#include "py/obj.h" +#include "py/objproperty.h" +#include "py/runtime.h" + +#include "bindings/picodvi/AudioOut.h" +#include "bindings/picodvi/Framebuffer.h" +#include "shared-bindings/util.h" + +//| class AudioOut: +//| """Plays audio through the DVI cable of a `Framebuffer`, on displays +//| that have speakers or an audio output. RP2350 only: elsewhere the +//| constructor raises `NotImplementedError`. +//| +//| On boards with a default DVI display, ``supervisor.runtime.audio`` is an AudioOut +//| for the display configured at startup. It is ``None`` if that display +//| was not configured, its mode has no room for audio, or it was released. +//| Set ``CIRCUITPY_PICODVI_AUDIO = false`` in ``settings.toml`` to turn it +//| off.""" +//| +//| def __init__(self, framebuffer: Framebuffer) -> None: +//| """Create an AudioOut that sends audio with ``framebuffer``'s video. +//| +//| The framebuffer must use a 640-pixel-wide output mode, such as +//| 640x480 or 320x240. This reserves about 37 KB (640 wide) or +//| 50 KB (320 or 160 wide) of internal RAM until `deinit`, so create +//| the AudioOut soon after the Framebuffer. With 640x480 and 8-bit +//| color, usually only the display configured at startup has room +//| for audio. The display receives silence whenever nothing is +//| playing. +//| +//| :param Framebuffer framebuffer: The display output to add audio to +//| +//| Playing a sine tone:: +//| +//| import array +//| import math +//| import time +//| import audiocore +//| import board +//| import displayio +//| import picodvi +//| +//| displayio.release_displays() +//| fb = picodvi.Framebuffer(320, 240, clk_dp=board.CKP, clk_dn=board.CKN, +//| red_dp=board.D0P, red_dn=board.D0N, +//| green_dp=board.D1P, green_dn=board.D1N, +//| blue_dp=board.D2P, blue_dn=board.D2N) +//| audio = picodvi.AudioOut(fb) +//| sine = array.array("h", [int(8000 * math.sin(math.pi * 2 * i / 48)) for i in range(48)]) +//| tone = audiocore.RawSample(sine, sample_rate=48000) +//| audio.play(tone, loop=True) +//| time.sleep(1) +//| audio.stop()""" +//| ... +//| +static mp_obj_t picodvi_audioout_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + #if CIRCUITPY_PICODVI_AUDIOOUT + enum { ARG_framebuffer }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_framebuffer, MP_ARG_OBJ | MP_ARG_REQUIRED }, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + picodvi_framebuffer_obj_t *framebuffer = MP_OBJ_TO_PTR( + mp_arg_validate_type(args[ARG_framebuffer].u_obj, &picodvi_framebuffer_type, MP_QSTR_framebuffer)); + + picodvi_audioout_obj_t *self = mp_obj_malloc_with_finaliser(picodvi_audioout_obj_t, &picodvi_audioout_type); + common_hal_picodvi_audioout_construct(self, framebuffer); + return MP_OBJ_FROM_PTR(self); + #else + mp_raise_NotImplementedError(NULL); + #endif +} + +#if CIRCUITPY_PICODVI_AUDIOOUT +//| def deinit(self) -> None: +//| """Stops playback and releases the framebuffer for another AudioOut.""" +//| ... +//| +static mp_obj_t picodvi_audioout_deinit(mp_obj_t self_in) { + picodvi_audioout_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_picodvi_audioout_deinit(self); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(picodvi_audioout_deinit_obj, picodvi_audioout_deinit); + +static void check_for_deinit(picodvi_audioout_obj_t *self) { + if (common_hal_picodvi_audioout_deinited(self)) { + raise_deinited_error(); + } +} + +//| def __enter__(self) -> AudioOut: +//| """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.""" +//| ... +//| +// Provided by context manager helper. + +//| def play(self, sample: circuitpython_typing.AudioSample, *, loop: bool = False) -> None: +//| """Plays the sample once when loop=False and continuously when loop=True. +//| Does not block. Use `playing` to block. +//| +//| Sample must be an `audiocore.WaveFile`, `audiocore.RawSample`, `audiomixer.Mixer`, +//| `synthio.Synthesizer` or `audiomp3.MP3Decoder` with a sample rate of 32000, 44100 +//| or 48000 Hz. Other rates raise `ValueError`; use `audiospeed.Resampler` to convert +//| them. Changing rate between samples can make the display mute briefly. +//| +//| Mono samples will be converted to stereo by copying value to both the left channel and the right channel. +//| +//| The sample itself should consist of 8 bit or 16 bit samples.""" +//| ... +//| +static mp_obj_t picodvi_audioout_obj_play(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_sample, ARG_loop }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_sample, MP_ARG_OBJ | MP_ARG_REQUIRED }, + { MP_QSTR_loop, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = false} }, + }; + picodvi_audioout_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); + + common_hal_picodvi_audioout_play(self, args[ARG_sample].u_obj, args[ARG_loop].u_bool); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_KW(picodvi_audioout_play_obj, 1, picodvi_audioout_obj_play); + +//| def stop(self) -> None: +//| """Stops playback.""" +//| ... +//| +static mp_obj_t picodvi_audioout_obj_stop(mp_obj_t self_in) { + picodvi_audioout_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + common_hal_picodvi_audioout_stop(self); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(picodvi_audioout_stop_obj, picodvi_audioout_obj_stop); + +//| playing: bool +//| """True when the audio sample is being output. (read-only)""" +//| +static mp_obj_t picodvi_audioout_obj_get_playing(mp_obj_t self_in) { + picodvi_audioout_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_bool(common_hal_picodvi_audioout_get_playing(self)); +} +static MP_DEFINE_CONST_FUN_OBJ_1(picodvi_audioout_get_playing_obj, picodvi_audioout_obj_get_playing); + +MP_PROPERTY_GETTER(picodvi_audioout_playing_obj, + (mp_obj_t)&picodvi_audioout_get_playing_obj); + +//| def pause(self) -> None: +//| """Stops playback temporarily while remembering the position. Use `resume` to resume playback.""" +//| ... +//| +static mp_obj_t picodvi_audioout_obj_pause(mp_obj_t self_in) { + picodvi_audioout_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + if (!common_hal_picodvi_audioout_get_playing(self)) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Not playing")); + } + common_hal_picodvi_audioout_pause(self); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(picodvi_audioout_pause_obj, picodvi_audioout_obj_pause); + +//| def resume(self) -> None: +//| """Resumes sample playback after :py:func:`pause`.""" +//| ... +//| +static mp_obj_t picodvi_audioout_obj_resume(mp_obj_t self_in) { + picodvi_audioout_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + if (common_hal_picodvi_audioout_get_paused(self)) { + common_hal_picodvi_audioout_resume(self); + } + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(picodvi_audioout_resume_obj, picodvi_audioout_obj_resume); + +//| paused: bool +//| """True when playback is paused. (read-only)""" +//| +//| +static mp_obj_t picodvi_audioout_obj_get_paused(mp_obj_t self_in) { + picodvi_audioout_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_bool(common_hal_picodvi_audioout_get_paused(self)); +} +static MP_DEFINE_CONST_FUN_OBJ_1(picodvi_audioout_get_paused_obj, picodvi_audioout_obj_get_paused); + +MP_PROPERTY_GETTER(picodvi_audioout_paused_obj, + (mp_obj_t)&picodvi_audioout_get_paused_obj); +#endif // CIRCUITPY_PICODVI_AUDIOOUT + +static const mp_rom_map_elem_t picodvi_audioout_locals_dict_table[] = { + #if CIRCUITPY_PICODVI_AUDIOOUT + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&picodvi_audioout_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&picodvi_audioout_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, + { MP_ROM_QSTR(MP_QSTR_play), MP_ROM_PTR(&picodvi_audioout_play_obj) }, + { MP_ROM_QSTR(MP_QSTR_stop), MP_ROM_PTR(&picodvi_audioout_stop_obj) }, + { MP_ROM_QSTR(MP_QSTR_pause), MP_ROM_PTR(&picodvi_audioout_pause_obj) }, + { MP_ROM_QSTR(MP_QSTR_resume), MP_ROM_PTR(&picodvi_audioout_resume_obj) }, + + { MP_ROM_QSTR(MP_QSTR_playing), MP_ROM_PTR(&picodvi_audioout_playing_obj) }, + { MP_ROM_QSTR(MP_QSTR_paused), MP_ROM_PTR(&picodvi_audioout_paused_obj) }, + #endif // CIRCUITPY_PICODVI_AUDIOOUT +}; +static MP_DEFINE_CONST_DICT(picodvi_audioout_locals_dict, picodvi_audioout_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + picodvi_audioout_type, + MP_QSTR_AudioOut, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, picodvi_audioout_make_new, + locals_dict, &picodvi_audioout_locals_dict + ); diff --git a/ports/raspberrypi/bindings/picodvi/AudioOut.h b/ports/raspberrypi/bindings/picodvi/AudioOut.h new file mode 100644 index 00000000000..049d4ff1e3b --- /dev/null +++ b/ports/raspberrypi/bindings/picodvi/AudioOut.h @@ -0,0 +1,21 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "common-hal/picodvi/AudioOut.h" + +extern const mp_obj_type_t picodvi_audioout_type; + +void common_hal_picodvi_audioout_construct(picodvi_audioout_obj_t *self, picodvi_framebuffer_obj_t *framebuffer); +void common_hal_picodvi_audioout_deinit(picodvi_audioout_obj_t *self); +bool common_hal_picodvi_audioout_deinited(picodvi_audioout_obj_t *self); +void common_hal_picodvi_audioout_play(picodvi_audioout_obj_t *self, mp_obj_t sample, bool loop); +void common_hal_picodvi_audioout_stop(picodvi_audioout_obj_t *self); +bool common_hal_picodvi_audioout_get_playing(picodvi_audioout_obj_t *self); +void common_hal_picodvi_audioout_pause(picodvi_audioout_obj_t *self); +void common_hal_picodvi_audioout_resume(picodvi_audioout_obj_t *self); +bool common_hal_picodvi_audioout_get_paused(picodvi_audioout_obj_t *self); diff --git a/ports/raspberrypi/bindings/picodvi/Framebuffer.c b/ports/raspberrypi/bindings/picodvi/Framebuffer.c index 332fe796933..e11b75b2a2a 100644 --- a/ports/raspberrypi/bindings/picodvi/Framebuffer.c +++ b/ports/raspberrypi/bindings/picodvi/Framebuffer.c @@ -109,25 +109,28 @@ static mp_obj_t picodvi_framebuffer_make_new(const mp_obj_type_t *type, size_t n mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); - picodvi_framebuffer_obj_t *self = &allocate_display_bus_or_raise()->picodvi; - self->base.type = &picodvi_framebuffer_type; - mp_uint_t width = (mp_uint_t)mp_arg_validate_int_min(args[ARG_width].u_int, 0, MP_QSTR_width); mp_uint_t height = (mp_uint_t)mp_arg_validate_int_min(args[ARG_height].u_int, 0, MP_QSTR_height); mp_uint_t color_depth = args[ARG_color_depth].u_int; if (color_depth != 1 && color_depth != 2 && color_depth != 4 && color_depth != 8 && color_depth != 16 && color_depth != 32) { mp_raise_ValueError_varg(MP_ERROR_TEXT("Invalid %q"), MP_QSTR_color_depth); } + const mcu_pin_obj_t *clk_dp = validate_obj_is_free_pin(args[ARG_clk_dp].u_obj, MP_QSTR_clk_dp); + const mcu_pin_obj_t *clk_dn = validate_obj_is_free_pin(args[ARG_clk_dn].u_obj, MP_QSTR_clk_dn); + const mcu_pin_obj_t *red_dp = validate_obj_is_free_pin(args[ARG_red_dp].u_obj, MP_QSTR_red_dp); + const mcu_pin_obj_t *red_dn = validate_obj_is_free_pin(args[ARG_red_dn].u_obj, MP_QSTR_red_dn); + const mcu_pin_obj_t *green_dp = validate_obj_is_free_pin(args[ARG_green_dp].u_obj, MP_QSTR_green_dp); + const mcu_pin_obj_t *green_dn = validate_obj_is_free_pin(args[ARG_green_dn].u_obj, MP_QSTR_green_dn); + const mcu_pin_obj_t *blue_dp = validate_obj_is_free_pin(args[ARG_blue_dp].u_obj, MP_QSTR_blue_dp); + const mcu_pin_obj_t *blue_dn = validate_obj_is_free_pin(args[ARG_blue_dn].u_obj, MP_QSTR_blue_dn); + + // Validate everything before taking a display bus slot. + picodvi_framebuffer_obj_t *self = &allocate_display_bus_or_raise()->picodvi; + self->base.type = &picodvi_framebuffer_type; + common_hal_picodvi_framebuffer_construct(self, width, height, - validate_obj_is_free_pin(args[ARG_clk_dp].u_obj, MP_QSTR_clk_dp), - validate_obj_is_free_pin(args[ARG_clk_dn].u_obj, MP_QSTR_clk_dn), - validate_obj_is_free_pin(args[ARG_red_dp].u_obj, MP_QSTR_red_dp), - validate_obj_is_free_pin(args[ARG_red_dn].u_obj, MP_QSTR_red_dn), - validate_obj_is_free_pin(args[ARG_green_dp].u_obj, MP_QSTR_green_dp), - validate_obj_is_free_pin(args[ARG_green_dn].u_obj, MP_QSTR_green_dn), - validate_obj_is_free_pin(args[ARG_blue_dp].u_obj, MP_QSTR_blue_dp), - validate_obj_is_free_pin(args[ARG_blue_dn].u_obj, MP_QSTR_blue_dn), + clk_dp, clk_dn, red_dp, red_dn, green_dp, green_dn, blue_dp, blue_dn, color_depth); return MP_OBJ_FROM_PTR(self); @@ -178,11 +181,42 @@ MP_DEFINE_CONST_FUN_OBJ_1(picodvi_framebuffer_get_height_obj, picodvi_framebuffe MP_PROPERTY_GETTER(picodvi_framebuffer_height_obj, (mp_obj_t)&picodvi_framebuffer_get_height_obj); +//| color_depth: int +//| """The color depth of the framebuffer.""" +static mp_obj_t picodvi_framebuffer_get_color_depth(mp_obj_t self_in) { + picodvi_framebuffer_obj_t *self = (picodvi_framebuffer_obj_t *)self_in; + check_for_deinit(self); + return MP_OBJ_NEW_SMALL_INT(common_hal_picodvi_framebuffer_get_color_depth(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(picodvi_framebuffer_get_color_depth_obj, picodvi_framebuffer_get_color_depth); +MP_PROPERTY_GETTER(picodvi_framebuffer_color_depth_obj, + (mp_obj_t)&picodvi_framebuffer_get_color_depth_obj); + +//| def wait_for_vblank(self) -> None: +//| """Block until the next frame boundary (vertical blank), then return. Call this right +//| before a full-framebuffer repaint so the repaint starts at the top of scanout and races +//| ahead of the beam, avoiding tearing without a second framebuffer. The repaint must +//| complete faster than one scanout sweep (~16 ms at 60 Hz) to stay ahead of the beam; +//| if it cannot (e.g. a full 640x480 ``displayio`` refresh), use a lower resolution or +//| repaint a smaller area. Bounded by a short timeout, so it is safe even if no DVI +//| signal is active. No-op on the RP2040 PIO-DVI path.""" +//| ... +static mp_obj_t picodvi_framebuffer_wait_for_vblank(mp_obj_t self_in) { + picodvi_framebuffer_obj_t *self = (picodvi_framebuffer_obj_t *)self_in; + check_for_deinit(self); + common_hal_picodvi_framebuffer_wait_for_vblank(self); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(picodvi_framebuffer_wait_for_vblank_obj, picodvi_framebuffer_wait_for_vblank); + + static const mp_rom_map_elem_t picodvi_framebuffer_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&picodvi_framebuffer_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR_wait_for_vblank), MP_ROM_PTR(&picodvi_framebuffer_wait_for_vblank_obj) }, { MP_ROM_QSTR(MP_QSTR_width), MP_ROM_PTR(&picodvi_framebuffer_width_obj) }, { MP_ROM_QSTR(MP_QSTR_height), MP_ROM_PTR(&picodvi_framebuffer_height_obj) }, + { MP_ROM_QSTR(MP_QSTR_color_depth), MP_ROM_PTR(&picodvi_framebuffer_color_depth_obj) }, }; static MP_DEFINE_CONST_DICT(picodvi_framebuffer_locals_dict, picodvi_framebuffer_locals_dict_table); diff --git a/ports/raspberrypi/bindings/picodvi/Framebuffer.h b/ports/raspberrypi/bindings/picodvi/Framebuffer.h index 7eb7780ee49..d5f59fe84c3 100644 --- a/ports/raspberrypi/bindings/picodvi/Framebuffer.h +++ b/ports/raspberrypi/bindings/picodvi/Framebuffer.h @@ -25,6 +25,7 @@ void common_hal_picodvi_framebuffer_construct(picodvi_framebuffer_obj_t *self, void common_hal_picodvi_framebuffer_deinit(picodvi_framebuffer_obj_t *self); bool common_hal_picodvi_framebuffer_deinited(picodvi_framebuffer_obj_t *self); void common_hal_picodvi_framebuffer_refresh(picodvi_framebuffer_obj_t *self); +void common_hal_picodvi_framebuffer_wait_for_vblank(picodvi_framebuffer_obj_t *self); int common_hal_picodvi_framebuffer_get_width(picodvi_framebuffer_obj_t *self); int common_hal_picodvi_framebuffer_get_height(picodvi_framebuffer_obj_t *self); int common_hal_picodvi_framebuffer_get_row_stride(picodvi_framebuffer_obj_t *self); diff --git a/ports/raspberrypi/bindings/picodvi/__init__.c b/ports/raspberrypi/bindings/picodvi/__init__.c index 43617de1a8b..2a2a571a97e 100644 --- a/ports/raspberrypi/bindings/picodvi/__init__.c +++ b/ports/raspberrypi/bindings/picodvi/__init__.c @@ -9,12 +9,14 @@ #include "py/obj.h" #include "py/runtime.h" +#include "bindings/picodvi/AudioOut.h" #include "bindings/picodvi/Framebuffer.h" //| """Low-level routines for interacting with PicoDVI Output""" static const mp_rom_map_elem_t picodvi_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_picodvi) }, + { MP_ROM_QSTR(MP_QSTR_AudioOut), MP_ROM_PTR(&picodvi_audioout_type) }, { MP_ROM_QSTR(MP_QSTR_Framebuffer), MP_ROM_PTR(&picodvi_framebuffer_type) }, }; diff --git a/ports/raspberrypi/bindings/rp2pio/StateMachine.c b/ports/raspberrypi/bindings/rp2pio/StateMachine.c index 364e9f0461d..7a241a20614 100644 --- a/ports/raspberrypi/bindings/rp2pio/StateMachine.c +++ b/ports/raspberrypi/bindings/rp2pio/StateMachine.c @@ -29,8 +29,8 @@ //| """A type representing one of the strings ``"auto"``, ``"txrx"``, ``"tx"``, or ``"rx"``. These values are supported on both RP2350 and RP2040. For type-checking only, not actually defined in CircuitPython.""" //| MovStatusType = Literal["txfifo", "rxfifo", "irq"] //| """A type representing one of the strings ``"txfifo"``, ``"rxfifo"``, or ``"irq"``. These values are supported on RP2350. For type-checking only, not actually defined in CircuitPython.""" -//| MovStatusType_piov0 = Literal["txfifo"] -//| """A type representing the string ``"txfifo"``. This value is supported on RP2350 and RP2040. For type-checking only, not actually defined in CircuitPython.""" +//| MovStatusType_piov0 = Literal["txfifo", "rxfifo"] +//| """A type representing one of the strings ``"txfifo"``, ``"rxfifo"``. These values are supported on RP2350 and RP2040. For type-checking only, not actually defined in CircuitPython.""" //| //| //| class StateMachine: @@ -175,7 +175,9 @@ static int one_of(qstr_short_t what, mp_obj_t arg, size_t n_options, const qstr_ } static mp_obj_t rp2pio_statemachine_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { - rp2pio_statemachine_obj_t *self = mp_obj_malloc(rp2pio_statemachine_obj_t, &rp2pio_statemachine_type); + rp2pio_statemachine_obj_t *self = mp_obj_malloc_with_finaliser(rp2pio_statemachine_obj_t, &rp2pio_statemachine_type); + // Make the finaliser a no-op if construction raises before a state machine is claimed. + common_hal_rp2pio_statemachine_mark_deinit(self); enum { ARG_program, ARG_frequency, ARG_init, ARG_pio_version, ARG_may_exec, 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, @@ -1119,6 +1121,7 @@ MP_PROPERTY_GETTER(rp2pio_statemachine_last_write_obj, static const mp_rom_map_elem_t rp2pio_statemachine_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&rp2pio_statemachine_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&rp2pio_statemachine_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, diff --git a/ports/raspberrypi/bindings/rp2pio/StateMachine.h b/ports/raspberrypi/bindings/rp2pio/StateMachine.h index afdffd1eccd..98d81a4c6b5 100644 --- a/ports/raspberrypi/bindings/rp2pio/StateMachine.h +++ b/ports/raspberrypi/bindings/rp2pio/StateMachine.h @@ -42,8 +42,7 @@ void common_hal_rp2pio_statemachine_construct(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); - -void common_hal_rp2pio_statemachine_never_reset(rp2pio_statemachine_obj_t *self); +void common_hal_rp2pio_statemachine_mark_deinit(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); @@ -61,6 +60,18 @@ bool common_hal_rp2pio_statemachine_background_read(rp2pio_statemachine_obj_t *s bool common_hal_rp2pio_statemachine_stop_background_write(rp2pio_statemachine_obj_t *self); bool common_hal_rp2pio_statemachine_stop_background_read(rp2pio_statemachine_obj_t *self); +// Set the once / loop / loop2 read buffers from raw pointers without going +// through an mp_obj_t wrapper. Pass NULL/0 for unused slots. The caller owns +// the memory; it must remain valid until stop_background_read. +void common_hal_rp2pio_statemachine_set_read_buffers_raw(rp2pio_statemachine_obj_t *self, + void *once, size_t once_len, + void *loop, size_t loop_len, + void *loop2, size_t loop2_len); + +// Returns the DMA channel index used by the current background read, or -1 +// if no background read is active. +int common_hal_rp2pio_statemachine_get_read_dma_channel(rp2pio_statemachine_obj_t *self); + mp_int_t common_hal_rp2pio_statemachine_get_pending_write(rp2pio_statemachine_obj_t *self); mp_int_t common_hal_rp2pio_statemachine_get_pending_read(rp2pio_statemachine_obj_t *self); diff --git a/ports/raspberrypi/bindings/wiznet/PIO_SPI.c b/ports/raspberrypi/bindings/wiznet/PIO_SPI.c new file mode 100755 index 00000000000..1f860fc9979 --- /dev/null +++ b/ports/raspberrypi/bindings/wiznet/PIO_SPI.c @@ -0,0 +1,299 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2016 Scott Shawcroft +// +// SPDX-License-Identifier: MIT + +// TODO: wiznet.PIO_SPI class. +// This file contains all of the Python API definitions for the +// wiznet.PIO_SPI class. + +#include + +#include "shared-bindings/microcontroller/Pin.h" +#include "bindings/wiznet/PIO_SPI.h" +#include "shared-bindings/util.h" + +#include "shared/runtime/buffer_helper.h" +#include "shared/runtime/context_manager_helpers.h" +#include "py/binary.h" +#include "py/mperrno.h" +#include "py/objproperty.h" +#include "py/runtime.h" + + +// TODO: class WIZNET_PIO_SPI + + +static mp_obj_t wiznet_pio_spi_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + #if CIRCUITPY_WIZNET + wiznet_pio_spi_obj_t *self = mp_obj_malloc(wiznet_pio_spi_obj_t, &wiznet_pio_spi_type); + enum { ARG_clock, ARG_MOSI, ARG_MISO, ARG_half_duplex }; + 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_half_duplex, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = false} }, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_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, MP_QSTR_clock); + const mcu_pin_obj_t *mosi = validate_obj_is_free_pin_or_none(args[ARG_MOSI].u_obj, MP_QSTR_mosi); + const mcu_pin_obj_t *miso = validate_obj_is_free_pin_or_none(args[ARG_MISO].u_obj, MP_QSTR_miso); + + if (!miso && !mosi) { + mp_raise_ValueError(MP_ERROR_TEXT("Must provide MISO or MOSI pin")); + } + + common_hal_wiznet_pio_spi_construct(self, clock, mosi, miso, args[ARG_half_duplex].u_bool); + return MP_OBJ_FROM_PTR(self); + #else + mp_raise_NotImplementedError(NULL); + #endif // CIRCUITPY_WIZNET +} + +#if CIRCUITPY_WIZNET + +// TODO: def deinit + +static mp_obj_t wiznet_pio_spi_obj_deinit(mp_obj_t self_in) { + wiznet_pio_spi_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_wiznet_pio_spi_deinit(self); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_1(wiznet_pio_spi_deinit_obj, wiznet_pio_spi_obj_deinit); + +// TODO: def __enter__ + +// TODO: def __exit__ + +static void check_lock(wiznet_pio_spi_obj_t *self) { + asm (""); + if (!common_hal_wiznet_pio_spi_has_lock(self)) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Function requires lock")); + } +} + +static void check_for_deinit(wiznet_pio_spi_obj_t *self) { + if (common_hal_wiznet_pio_spi_deinited(self)) { + raise_deinited_error(); + } +} + +// TODO: def configure + +static mp_obj_t wiznet_pio_spi_configure(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_baudrate, ARG_polarity, ARG_phase, ARG_bits }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_baudrate, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 100000} }, + { MP_QSTR_polarity, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_phase, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_bits, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 8} }, + }; + wiznet_pio_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); + + uint8_t polarity = (uint8_t)mp_arg_validate_int_range(args[ARG_polarity].u_int, 0, 1, MP_QSTR_polarity); + uint8_t phase = (uint8_t)mp_arg_validate_int_range(args[ARG_phase].u_int, 0, 1, MP_QSTR_phase); + uint8_t bits = (uint8_t)mp_arg_validate_int_range(args[ARG_bits].u_int, 8, 9, MP_QSTR_bits); + + if (!common_hal_wiznet_pio_spi_configure(self, args[ARG_baudrate].u_int, + polarity, phase, bits)) { + mp_raise_OSError(MP_EIO); + } + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_KW(wiznet_pio_spi_configure_obj, 1, wiznet_pio_spi_configure); + +// TODO: def try_lock + +static mp_obj_t wiznet_pio_spi_obj_try_lock(mp_obj_t self_in) { + wiznet_pio_spi_obj_t *self = MP_OBJ_TO_PTR(self_in); + return mp_obj_new_bool(common_hal_wiznet_pio_spi_try_lock(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(wiznet_pio_spi_try_lock_obj, wiznet_pio_spi_obj_try_lock); + +// TODO: def unlock + +static mp_obj_t wiznet_pio_spi_obj_unlock(mp_obj_t self_in) { + wiznet_pio_spi_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + common_hal_wiznet_pio_spi_unlock(self); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_1(wiznet_pio_spi_unlock_obj, wiznet_pio_spi_obj_unlock); + +// TODO: def write + +static mp_obj_t wiznet_pio_spi_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[] = { + { 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} }, + }; + + wiznet_pio_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[ARG_buffer].u_obj, &bufinfo, MP_BUFFER_READ); + // Compute bounds in terms of elements, not bytes. + int stride_in_bytes = mp_binary_get_size('@', bufinfo.typecode, NULL); + int32_t start = args[ARG_start].u_int; + size_t length = bufinfo.len / stride_in_bytes; + normalize_buffer_bounds(&start, args[ARG_end].u_int, &length); + + // Treat start and length in terms of bytes from now on. + start *= stride_in_bytes; + length *= stride_in_bytes; + + if (length == 0) { + return mp_const_none; + } + + bool ok = common_hal_wiznet_pio_spi_write(self, ((uint8_t *)bufinfo.buf) + start, length); + + if (!ok) { + mp_raise_OSError(MP_EIO); + } + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_KW(wiznet_pio_spi_write_obj, 1, wiznet_pio_spi_write); + +// TODO: def readinto + +static mp_obj_t wiznet_pio_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} }, + }; + wiznet_pio_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[ARG_buffer].u_obj, &bufinfo, MP_BUFFER_WRITE); + // Compute bounds in terms of elements, not bytes. + int stride_in_bytes = mp_binary_get_size('@', bufinfo.typecode, NULL); + int32_t start = args[ARG_start].u_int; + size_t length = bufinfo.len / stride_in_bytes; + normalize_buffer_bounds(&start, args[ARG_end].u_int, &length); + + // Treat start and length in terms of bytes from now on. + start *= stride_in_bytes; + length *= stride_in_bytes; + + if (length == 0) { + return mp_const_none; + } + + bool ok = common_hal_wiznet_pio_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_KW(wiznet_pio_spi_readinto_obj, 1, wiznet_pio_spi_readinto); + + +// TODO: def write_readinto + +static mp_obj_t wiznet_pio_spi_write_readinto(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_out_buffer, ARG_in_buffer, ARG_out_start, ARG_out_end, ARG_in_start, ARG_in_end }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_out_buffer, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_in_buffer, 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} }, + }; + wiznet_pio_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 buf_out_info; + mp_get_buffer_raise(args[ARG_out_buffer].u_obj, &buf_out_info, MP_BUFFER_READ); + int out_stride_in_bytes = mp_binary_get_size('@', buf_out_info.typecode, NULL); + int32_t out_start = args[ARG_out_start].u_int; + size_t out_length = buf_out_info.len / out_stride_in_bytes; + 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_in_buffer].u_obj, &buf_in_info, MP_BUFFER_WRITE); + int in_stride_in_bytes = mp_binary_get_size('@', buf_in_info.typecode, NULL); + int32_t in_start = args[ARG_in_start].u_int; + size_t in_length = buf_in_info.len / in_stride_in_bytes; + normalize_buffer_bounds(&in_start, args[ARG_in_end].u_int, &in_length); + + // Treat start and length in terms of bytes from now on. + out_start *= out_stride_in_bytes; + out_length *= out_stride_in_bytes; + in_start *= in_stride_in_bytes; + in_length *= in_stride_in_bytes; + + if (out_length != in_length) { + mp_raise_ValueError(MP_ERROR_TEXT("buffer slices must be of equal length")); + } + + if (out_length == 0) { + return mp_const_none; + } + + bool ok = common_hal_wiznet_pio_spi_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(wiznet_pio_spi_write_readinto_obj, 1, wiznet_pio_spi_write_readinto); + +#endif // CIRCUITPY_WIZNET + +static const mp_rom_map_elem_t wiznet_pio_spi_locals_dict_table[] = { + #if CIRCUITPY_WIZNET + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&wiznet_pio_spi_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, + + { MP_ROM_QSTR(MP_QSTR_configure), MP_ROM_PTR(&wiznet_pio_spi_configure_obj) }, + { MP_ROM_QSTR(MP_QSTR_try_lock), MP_ROM_PTR(&wiznet_pio_spi_try_lock_obj) }, + { MP_ROM_QSTR(MP_QSTR_unlock), MP_ROM_PTR(&wiznet_pio_spi_unlock_obj) }, + + { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&wiznet_pio_spi_readinto_obj) }, + { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&wiznet_pio_spi_write_obj) }, + { MP_ROM_QSTR(MP_QSTR_write_readinto), MP_ROM_PTR(&wiznet_pio_spi_write_readinto_obj) }, + + #endif // CIRCUITPY_WIZNET +}; +static MP_DEFINE_CONST_DICT(wiznet_pio_spi_locals_dict, wiznet_pio_spi_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + wiznet_pio_spi_type, + MP_QSTR_PIO_SPI, + MP_TYPE_FLAG_NONE, + make_new, wiznet_pio_spi_make_new, + locals_dict, &wiznet_pio_spi_locals_dict + ); + +wiznet_pio_spi_obj_t *validate_obj_is_wiznet_pio_spi_bus(mp_obj_t obj, qstr arg_name) { + return mp_arg_validate_type(obj, &wiznet_pio_spi_type, arg_name); +} diff --git a/ports/raspberrypi/bindings/wiznet/PIO_SPI.h b/ports/raspberrypi/bindings/wiznet/PIO_SPI.h new file mode 100755 index 00000000000..0289ac0767a --- /dev/null +++ b/ports/raspberrypi/bindings/wiznet/PIO_SPI.h @@ -0,0 +1,40 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2016 Scott Shawcroft +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +#include "common-hal/microcontroller/Pin.h" +#include "common-hal/wiznet/PIO_SPI.h" + +// Type object used in Python. Should be shared between ports. +extern const mp_obj_type_t wiznet_pio_spi_type; + +// Construct an underlying SPI object. +extern void common_hal_wiznet_pio_spi_construct(wiznet_pio_spi_obj_t *self, + const mcu_pin_obj_t *clock, const mcu_pin_obj_t *mosi, + const mcu_pin_obj_t *miso, bool half_duplex); + +extern void common_hal_wiznet_pio_spi_deinit(wiznet_pio_spi_obj_t *self); +extern bool common_hal_wiznet_pio_spi_deinited(wiznet_pio_spi_obj_t *self); + +extern bool common_hal_wiznet_pio_spi_configure(wiznet_pio_spi_obj_t *self, uint32_t baudrate, uint8_t polarity, uint8_t phase, uint8_t bits); + +extern bool common_hal_wiznet_pio_spi_try_lock(wiznet_pio_spi_obj_t *self); +extern bool common_hal_wiznet_pio_spi_has_lock(wiznet_pio_spi_obj_t *self); +extern void common_hal_wiznet_pio_spi_unlock(wiznet_pio_spi_obj_t *self); + +// Writes out the given data. +extern bool common_hal_wiznet_pio_spi_write(wiznet_pio_spi_obj_t *self, const uint8_t *data, size_t len); + +// Reads in len bytes while outputting the byte write_value. +extern bool common_hal_wiznet_pio_spi_read(wiznet_pio_spi_obj_t *self, uint8_t *data, size_t len, uint8_t write_value); + +// Reads and write len bytes simultaneously. +extern bool common_hal_wiznet_pio_spi_transfer(wiznet_pio_spi_obj_t *self, const uint8_t *data_out, uint8_t *data_in, size_t len); + +extern wiznet_pio_spi_obj_t *validate_obj_is_wiznet_pio_spi_bus(mp_obj_t obj_in, qstr arg_name); diff --git a/ports/raspberrypi/bindings/wiznet/__init__.c b/ports/raspberrypi/bindings/wiznet/__init__.c new file mode 100755 index 00000000000..6ed3c2886cc --- /dev/null +++ b/ports/raspberrypi/bindings/wiznet/__init__.c @@ -0,0 +1,29 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2016 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include + +#include "py/obj.h" +#include "py/runtime.h" + +#include "shared-bindings/microcontroller/Pin.h" +#include "bindings/wiznet/PIO_SPI.h" + +#include "py/runtime.h" + +static const mp_rom_map_elem_t wiznet_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_wiznet) }, + { MP_ROM_QSTR(MP_QSTR_PIO_SPI), MP_ROM_PTR(&wiznet_pio_spi_type) }, +}; + +static MP_DEFINE_CONST_DICT(wiznet_module_globals, wiznet_module_globals_table); + +const mp_obj_module_t wiznet_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&wiznet_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_wiznet, wiznet_module); diff --git a/ports/zephyr-cp/bindings/zephyr_serial/__init__.h b/ports/raspberrypi/bindings/wiznet/__init__.h old mode 100644 new mode 100755 similarity index 100% rename from ports/zephyr-cp/bindings/zephyr_serial/__init__.h rename to ports/raspberrypi/bindings/wiznet/__init__.h diff --git a/ports/raspberrypi/boards/42keebs_frood/pins.c b/ports/raspberrypi/boards/42keebs_frood/pins.c index 45436250518..2e7ac22475b 100644 --- a/ports/raspberrypi/boards/42keebs_frood/pins.c +++ b/ports/raspberrypi/boards/42keebs_frood/pins.c @@ -49,6 +49,9 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_GPIO15) }, { MP_ROM_QSTR(MP_QSTR_D16), MP_ROM_PTR(&pin_GPIO16) }, + { 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_LED), MP_ROM_PTR(&pin_GPIO17) }, { MP_ROM_QSTR(MP_QSTR_D17), MP_ROM_PTR(&pin_GPIO17) }, { MP_ROM_QSTR(MP_QSTR_VBUS_SENSE), MP_ROM_PTR(&pin_GPIO19) }, diff --git a/ports/raspberrypi/boards/8086_usb_interposer/board.c b/ports/raspberrypi/boards/8086_usb_interposer/board.c index 68ed648f46b..52ad557c049 100644 --- a/ports/raspberrypi/boards/8086_usb_interposer/board.c +++ b/ports/raspberrypi/boards/8086_usb_interposer/board.c @@ -29,5 +29,9 @@ bool board_reset_pin_number(uint8_t pin_number) { return false; } void board_init(void) { + // GPIO18 (USB_HOST_5V_POWER) powers the USB host port. + // Default to high (on). + board_reset_pin_number(18); + common_hal_usb_host_port_construct(&pin_GPIO16, &pin_GPIO17); } diff --git a/ports/raspberrypi/boards/adafruit_feather_rp2040_adalogger/mpconfigboard.h b/ports/raspberrypi/boards/adafruit_feather_rp2040_adalogger/mpconfigboard.h index 34360169423..4c500366dfc 100644 --- a/ports/raspberrypi/boards/adafruit_feather_rp2040_adalogger/mpconfigboard.h +++ b/ports/raspberrypi/boards/adafruit_feather_rp2040_adalogger/mpconfigboard.h @@ -23,3 +23,11 @@ // #define CIRCUITPY_CONSOLE_UART_RX DEFAULT_UART_BUS_RX // #define CIRCUITPY_CONSOLE_UART_TX DEFAULT_UART_BUS_TX + +// Onboard microSD slot on SPI1. +#define DEFAULT_SD_SCK (&pin_GPIO18) +#define DEFAULT_SD_MOSI (&pin_GPIO19) +#define DEFAULT_SD_MISO (&pin_GPIO20) +#define DEFAULT_SD_CS (&pin_GPIO23) +#define DEFAULT_SD_CARD_DETECT (&pin_GPIO16) +#define DEFAULT_SD_CARD_INSERTED true diff --git a/ports/raspberrypi/boards/adafruit_feather_rp2040_adalogger/mpconfigboard.mk b/ports/raspberrypi/boards/adafruit_feather_rp2040_adalogger/mpconfigboard.mk index 529853b22f5..cc0880ac544 100644 --- a/ports/raspberrypi/boards/adafruit_feather_rp2040_adalogger/mpconfigboard.mk +++ b/ports/raspberrypi/boards/adafruit_feather_rp2040_adalogger/mpconfigboard.mk @@ -7,3 +7,5 @@ CHIP_VARIANT = RP2040 CHIP_FAMILY = rp2 EXTERNAL_FLASH_DEVICES = "GD25Q64C,W25Q64JVxQ" + +CIRCUITPY_SDIOIO = 1 diff --git a/ports/raspberrypi/boards/adafruit_feather_rp2040_adalogger/pins.c b/ports/raspberrypi/boards/adafruit_feather_rp2040_adalogger/pins.c index 78d09407a65..c4040512e58 100644 --- a/ports/raspberrypi/boards/adafruit_feather_rp2040_adalogger/pins.c +++ b/ports/raspberrypi/boards/adafruit_feather_rp2040_adalogger/pins.c @@ -4,8 +4,21 @@ // // SPDX-License-Identifier: MIT +#include "py/objtuple.h" #include "shared-bindings/board/__init__.h" +// Four consecutive data GPIOs for the 4-bit SDIO interface (sdioio.SDCard). +static const mp_rom_obj_tuple_t sdio_data_tuple = { + {&mp_type_tuple}, + 4, + { + MP_ROM_PTR(&pin_GPIO20), + MP_ROM_PTR(&pin_GPIO21), + MP_ROM_PTR(&pin_GPIO22), + MP_ROM_PTR(&pin_GPIO23), + } +}; + static const mp_rom_map_elem_t board_module_globals_table[] = { CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS @@ -49,18 +62,21 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_SD_CARD_DETECT), MP_ROM_PTR(&pin_GPIO16) }, { MP_ROM_QSTR(MP_QSTR_SD_CLK), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_SDIO_CLOCK), MP_ROM_PTR(&pin_GPIO18) }, { MP_ROM_QSTR(MP_QSTR_SD_MOSI), MP_ROM_PTR(&pin_GPIO19) }, - { MP_ROM_QSTR(MP_QSTR_SD_CMD), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_SDIO_COMMAND), MP_ROM_PTR(&pin_GPIO19) }, { MP_ROM_QSTR(MP_QSTR_SD_MISO), MP_ROM_PTR(&pin_GPIO20) }, - { MP_ROM_QSTR(MP_QSTR_SD_DAT0), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_SDIO_DATA0), MP_ROM_PTR(&pin_GPIO20) }, - { MP_ROM_QSTR(MP_QSTR_SD_DAT1), MP_ROM_PTR(&pin_GPIO21) }, - { MP_ROM_QSTR(MP_QSTR_SD_DAT2), MP_ROM_PTR(&pin_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_SDIO_DATA1), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_SDIO_DATA2), MP_ROM_PTR(&pin_GPIO22) }, { MP_ROM_QSTR(MP_QSTR_SD_CS), MP_ROM_PTR(&pin_GPIO23) }, - { MP_ROM_QSTR(MP_QSTR_SD_DAT3), MP_ROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_SDIO_DATA3), MP_ROM_PTR(&pin_GPIO23) }, + + { MP_ROM_QSTR(MP_QSTR_SDIO_DATA), MP_ROM_PTR(&sdio_data_tuple) }, { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, { MP_ROM_QSTR(MP_QSTR_STEMMA_I2C), MP_ROM_PTR(&board_i2c_obj) }, diff --git a/ports/raspberrypi/boards/adafruit_feather_rp2040_thinkink/mpconfigboard.mk b/ports/raspberrypi/boards/adafruit_feather_rp2040_thinkink/mpconfigboard.mk index 1f71dcb76bf..99df118f311 100644 --- a/ports/raspberrypi/boards/adafruit_feather_rp2040_thinkink/mpconfigboard.mk +++ b/ports/raspberrypi/boards/adafruit_feather_rp2040_thinkink/mpconfigboard.mk @@ -7,3 +7,5 @@ CHIP_VARIANT = RP2040 CHIP_FAMILY = rp2 EXTERNAL_FLASH_DEVICES = "GD25Q64C,W25Q64JVxQ" + +CIRCUITPY_VIDEOCORE = 1 diff --git a/ports/raspberrypi/boards/adafruit_feather_rp2040_usb_host/board.c b/ports/raspberrypi/boards/adafruit_feather_rp2040_usb_host/board.c index 68ed648f46b..52ad557c049 100644 --- a/ports/raspberrypi/boards/adafruit_feather_rp2040_usb_host/board.c +++ b/ports/raspberrypi/boards/adafruit_feather_rp2040_usb_host/board.c @@ -29,5 +29,9 @@ bool board_reset_pin_number(uint8_t pin_number) { return false; } void board_init(void) { + // GPIO18 (USB_HOST_5V_POWER) powers the USB host port. + // Default to high (on). + board_reset_pin_number(18); + common_hal_usb_host_port_construct(&pin_GPIO16, &pin_GPIO17); } diff --git a/ports/renode/boards/renode_cortex_m0plus/board.c b/ports/raspberrypi/boards/adafruit_feather_rp2350_adalogger/board.c similarity index 100% rename from ports/renode/boards/renode_cortex_m0plus/board.c rename to ports/raspberrypi/boards/adafruit_feather_rp2350_adalogger/board.c diff --git a/ports/raspberrypi/boards/adafruit_feather_rp2350_adalogger/mpconfigboard.h b/ports/raspberrypi/boards/adafruit_feather_rp2350_adalogger/mpconfigboard.h new file mode 100644 index 00000000000..b77664cf85c --- /dev/null +++ b/ports/raspberrypi/boards/adafruit_feather_rp2350_adalogger/mpconfigboard.h @@ -0,0 +1,29 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#define MICROPY_HW_BOARD_NAME "Adafruit Feather RP2350 Adalogger" +#define MICROPY_HW_MCU_NAME "rp2350a" + +#define MICROPY_HW_NEOPIXEL (&pin_GPIO21) + +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO3) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO2) + +#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) + +#define CIRCUITPY_PSRAM_CHIP_SELECT (&pin_GPIO8) + +#define DEFAULT_SD_SCK (&pin_GPIO14) +#define DEFAULT_SD_MOSI (&pin_GPIO15) +#define DEFAULT_SD_MISO (&pin_GPIO16) +#define DEFAULT_SD_CS (&pin_GPIO19) +#define DEFAULT_SD_CARD_DETECT (&pin_GPIO13) +#define DEFAULT_SD_CARD_INSERTED false diff --git a/ports/raspberrypi/boards/adafruit_feather_rp2350_adalogger/mpconfigboard.mk b/ports/raspberrypi/boards/adafruit_feather_rp2350_adalogger/mpconfigboard.mk new file mode 100644 index 00000000000..6ab89398de7 --- /dev/null +++ b/ports/raspberrypi/boards/adafruit_feather_rp2350_adalogger/mpconfigboard.mk @@ -0,0 +1,13 @@ +USB_VID = 0x239A +USB_PID = 0x816E +USB_PRODUCT = "Feather RP2350 Adalogger" +USB_MANUFACTURER = "Adafruit" + +CHIP_VARIANT = RP2350 +CHIP_PACKAGE = A +CHIP_FAMILY = rp2 + +EXTERNAL_FLASH_DEVICES = "GD25Q64C,W25Q64JVxQ" + +# GPIO12-19 needed for picodvi, but many are not available. +CIRCUITPY_PICODVI = 0 diff --git a/ports/raspberrypi/boards/adafruit_feather_rp2350_adalogger/pico-sdk-configboard.h b/ports/raspberrypi/boards/adafruit_feather_rp2350_adalogger/pico-sdk-configboard.h new file mode 100644 index 00000000000..2d9283a9192 --- /dev/null +++ b/ports/raspberrypi/boards/adafruit_feather_rp2350_adalogger/pico-sdk-configboard.h @@ -0,0 +1,10 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// Put board-specific pico-sdk definitions here. This file must exist. + +// Allow extra time for xosc to start. +#define PICO_XOSC_STARTUP_DELAY_MULTIPLIER 64 diff --git a/ports/raspberrypi/boards/adafruit_feather_rp2350_adalogger/pins.c b/ports/raspberrypi/boards/adafruit_feather_rp2350_adalogger/pins.c new file mode 100644 index 00000000000..5927681127c --- /dev/null +++ b/ports/raspberrypi/boards/adafruit_feather_rp2350_adalogger/pins.c @@ -0,0 +1,60 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { 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_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO20) }, + + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_GPIO1) }, + + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_D1), 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_IO4), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_D12), 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_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_LED), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_IO7), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_GPIO7) }, + + + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO21) }, + + { MP_ROM_QSTR(MP_QSTR_SD_CARD_DETECT), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_SD_CLK), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_SD_MOSI), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_SD_MISO), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_SD_CS), MP_ROM_PTR(&pin_GPIO19) }, + + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, + { MP_ROM_QSTR(MP_QSTR_STEMMA_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_module_globals_table); diff --git a/ports/raspberrypi/boards/adafruit_floppsy_rp2040/board.c b/ports/raspberrypi/boards/adafruit_floppsy_rp2040/board.c index 5056a4d9c7a..903ed6a9044 100644 --- a/ports/raspberrypi/boards/adafruit_floppsy_rp2040/board.c +++ b/ports/raspberrypi/boards/adafruit_floppsy_rp2040/board.c @@ -34,9 +34,9 @@ void board_init(void) { bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - CIRCUITPY_BOARD_TFT_DC, - CIRCUITPY_BOARD_TFT_CS, - NULL, // TFT_RESET Reset + MP_OBJ_FROM_PTR(CIRCUITPY_BOARD_TFT_DC), + MP_OBJ_FROM_PTR(CIRCUITPY_BOARD_TFT_CS), + mp_const_none, // TFT_RESET Reset 40000000, // Baudrate 0, // Polarity 0); // Phase diff --git a/ports/raspberrypi/boards/adafruit_floppsy_rp2040/mpconfigboard.mk b/ports/raspberrypi/boards/adafruit_floppsy_rp2040/mpconfigboard.mk index b2264a0e589..2775e10f1ea 100644 --- a/ports/raspberrypi/boards/adafruit_floppsy_rp2040/mpconfigboard.mk +++ b/ports/raspberrypi/boards/adafruit_floppsy_rp2040/mpconfigboard.mk @@ -6,7 +6,7 @@ USB_MANUFACTURER = "Adafruit" CHIP_VARIANT = RP2040 CHIP_FAMILY = rp2 -EXTERNAL_FLASH_DEVICES = "GD25Q64C,W25Q64JVxQ,W25Q128JV" +EXTERNAL_FLASH_DEVICES = "GD25Q64C,W25Q64JVxQ,W25Q128JVxQ" CIRCUITPY_USB_HOST = 0 CIRCUITPY_PICODVI = 0 diff --git a/ports/raspberrypi/boards/adafruit_fruit_jam/board.c b/ports/raspberrypi/boards/adafruit_fruit_jam/board.c index 38fbde53f6c..4c16aa6033a 100644 --- a/ports/raspberrypi/boards/adafruit_fruit_jam/board.c +++ b/ports/raspberrypi/boards/adafruit_fruit_jam/board.c @@ -16,8 +16,8 @@ #define I2S_RESET_PIN_NUMBER 22 -#if defined(DEFAULT_USB_HOST_5V_POWER) bool board_reset_pin_number(uint8_t pin_number) { + #if defined(DEFAULT_USB_HOST_5V_POWER) if (pin_number == DEFAULT_USB_HOST_5V_POWER->number) { // doing this (rather than gpio_init) in this specific order ensures no // glitch if pin was already configured as a high output. gpio_init() temporarily @@ -29,6 +29,7 @@ bool board_reset_pin_number(uint8_t pin_number) { return true; } + #endif // Set I2S out of reset. if (pin_number == I2S_RESET_PIN_NUMBER) { gpio_put(pin_number, 1); @@ -39,7 +40,6 @@ bool board_reset_pin_number(uint8_t pin_number) { } return false; } -#endif void board_init(void) { // Reset the DAC to put it in a known state. @@ -49,6 +49,12 @@ void board_init(void) { mp_hal_delay_us(1); board_reset_pin_number(I2S_RESET_PIN_NUMBER); + #if defined(DEFAULT_USB_HOST_5V_POWER) + // GPIO11 (USB_HOST_5V_POWER) powers the USB host port. + // Default to high (on). + board_reset_pin_number(DEFAULT_USB_HOST_5V_POWER->number); + #endif + #if defined(DEFAULT_USB_HOST_DATA_PLUS) common_hal_usb_host_port_construct(DEFAULT_USB_HOST_DATA_PLUS, DEFAULT_USB_HOST_DATA_MINUS); #endif diff --git a/ports/raspberrypi/boards/adafruit_fruit_jam/mpconfigboard.h b/ports/raspberrypi/boards/adafruit_fruit_jam/mpconfigboard.h index fb643deead2..25185c23b3b 100644 --- a/ports/raspberrypi/boards/adafruit_fruit_jam/mpconfigboard.h +++ b/ports/raspberrypi/boards/adafruit_fruit_jam/mpconfigboard.h @@ -17,6 +17,9 @@ #define DEFAULT_SPI_BUS_MOSI (&pin_GPIO31) #define DEFAULT_SPI_BUS_MISO (&pin_GPIO28) +#define DEFAULT_UART_BUS_RX (&pin_GPIO9) +#define DEFAULT_UART_BUS_TX (&pin_GPIO8) + #define DEFAULT_USB_HOST_DATA_PLUS (&pin_GPIO1) #define DEFAULT_USB_HOST_DATA_MINUS (&pin_GPIO2) #define DEFAULT_USB_HOST_5V_POWER (&pin_GPIO11) @@ -30,8 +33,22 @@ #define DEFAULT_DVI_BUS_BLUE_DN (&pin_GPIO18) #define DEFAULT_DVI_BUS_BLUE_DP (&pin_GPIO19) +#define DEFAULT_SD_SCK (&pin_GPIO34) +#define DEFAULT_SD_MOSI (&pin_GPIO35) +#define DEFAULT_SD_MISO (&pin_GPIO36) +#define DEFAULT_SD_CS (&pin_GPIO39) +#define DEFAULT_SD_CARD_DETECT (&pin_GPIO33) +#define DEFAULT_SD_CARD_INSERTED true + #define CIRCUITPY_PSRAM_CHIP_SELECT (&pin_GPIO47) +// The ESP32-C6 running nina-fw, on board.SPI(). nina-fw raises ESP_IRQ when a +// socket has data, so web workflow polls only then. +#define CIRCUITPY_AIRLIFT_CS (&pin_GPIO46) +#define CIRCUITPY_AIRLIFT_BUSY (&pin_GPIO3) +#define CIRCUITPY_AIRLIFT_RESET (&pin_GPIO22) +#define CIRCUITPY_AIRLIFT_GPIO0 (&pin_GPIO23) + // #define CIRCUITPY_CONSOLE_UART_TX (&pin_GPIO44) // #define CIRCUITPY_CONSOLE_UART_RX (&pin_GPIO45) diff --git a/ports/raspberrypi/boards/adafruit_fruit_jam/mpconfigboard.mk b/ports/raspberrypi/boards/adafruit_fruit_jam/mpconfigboard.mk index 31c4b130d0e..ee1c95d9712 100644 --- a/ports/raspberrypi/boards/adafruit_fruit_jam/mpconfigboard.mk +++ b/ports/raspberrypi/boards/adafruit_fruit_jam/mpconfigboard.mk @@ -9,5 +9,33 @@ CHIP_FAMILY = rp2 EXTERNAL_FLASH_DEVICES = "W25Q128JVxQ" +CIRCUITPY_SDIOIO = 1 + +CIRCUITPY_PICOGAME = 1 +CIRCUITPY_PICOGAME_FRAMEBUFFER = 1 + # CIRCUITPY_DISPLAY_FONT = $(TOP)/tools/fonts/unifont-16.0.02-all.bdf # CIRCUITPY_FONT_EXTRA_CHARACTERS = "🖮🖱️" + +# USB video (UVC) cameras have configuration descriptors of several KB. +# TinyUSB skips enumerating any device whose descriptor doesn't fit here. +CFLAGS += -DCFG_TUH_ENUMERATION_BUFSIZE=4096 +# Enable host isochronous IN support (UVC video, UAC audio). The packet ring +# is only allocated when CIRCUITPY_USB_HOST_ISO_BUFFER_SIZE is set in +# settings.toml. +CFLAGS += -DPIO_USB_HOST_ISOCHRONOUS=1 + +# USB host bulk input, for SDR devices +CIRCUITPY_USB_HOST_BULK = 1 + +# USB microphones as audio sources. Needs the isochronous ring above. +CIRCUITPY_USB_HOST_AUDIO = 1 + +# The ESP32-C6 co-processor, shared by the core and ESP32SPI. The core uses it +# for web workflow. The flags are set one by one, because CIRCUITPY_NETWORK +# would also turn on ssl, ipaddress and so on. +CIRCUITPY_AIRLIFT = 1 +CIRCUITPY_SOCKETPOOL = 1 +CIRCUITPY_WEB_WORKFLOW = 1 +CIRCUITPY_MDNS = 0 +CIRCUITPY_SSL = 0 diff --git a/ports/raspberrypi/boards/adafruit_fruit_jam/pins.c b/ports/raspberrypi/boards/adafruit_fruit_jam/pins.c index 54a8869366e..e6d41ae4989 100644 --- a/ports/raspberrypi/boards/adafruit_fruit_jam/pins.c +++ b/ports/raspberrypi/boards/adafruit_fruit_jam/pins.c @@ -4,8 +4,21 @@ // // SPDX-License-Identifier: MIT +#include "py/objtuple.h" #include "shared-bindings/board/__init__.h" +// Four consecutive data GPIOs for the 4-bit SDIO interface (sdioio.SDCard). +static const mp_rom_obj_tuple_t sdio_data_tuple = { + {&mp_type_tuple}, + 4, + { + MP_ROM_PTR(&pin_GPIO36), + MP_ROM_PTR(&pin_GPIO37), + MP_ROM_PTR(&pin_GPIO38), + MP_ROM_PTR(&pin_GPIO39), + } +}; + static const mp_rom_map_elem_t board_module_globals_table[] = { CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS @@ -28,6 +41,10 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { MP_OBJ_NEW_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO29) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_IR), MP_ROM_PTR(&pin_GPIO29) }, + + { MP_OBJ_NEW_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO32) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_BUTTON1), MP_ROM_PTR(&pin_GPIO0) }, { MP_OBJ_NEW_QSTR(MP_QSTR_BOOT), MP_ROM_PTR(&pin_GPIO0) }, @@ -41,9 +58,19 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO31) }, { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO28) }, - { MP_ROM_QSTR(MP_QSTR_ESP_CS), MP_ROM_PTR(&pin_GPIO46) }, + // Shared with ESP TX/RX. + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO9) }, - { MP_OBJ_NEW_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO32) }, + { MP_ROM_QSTR(MP_QSTR_ESP_CS), MP_ROM_PTR(&pin_GPIO46) }, + // was GPIO0 on ESP32. Used for IRQ and mode switching. + { MP_ROM_QSTR(MP_QSTR_ESP_IRQ), MP_ROM_PTR(&pin_GPIO23) }, + // BUSY is also known as READY, and is RTS for BLE mode. + { MP_ROM_QSTR(MP_QSTR_ESP_BUSY), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_ESP_RESET), MP_ROM_PTR(&pin_GPIO22) }, + // TX and RX are from the point of view of the RP2350. + { MP_ROM_QSTR(MP_QSTR_ESP_TX), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_ESP_RX), MP_ROM_PTR(&pin_GPIO9) }, { MP_ROM_QSTR(MP_QSTR_CKN), MP_ROM_PTR(&pin_GPIO12) }, { MP_ROM_QSTR(MP_QSTR_CKP), MP_ROM_PTR(&pin_GPIO13) }, @@ -56,11 +83,11 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_PERIPH_RESET), MP_ROM_PTR(&pin_GPIO22) }, - { MP_ROM_QSTR(MP_QSTR_I2S_MCLK), MP_ROM_PTR(&pin_GPIO27) }, - { MP_ROM_QSTR(MP_QSTR_I2S_BCLK), MP_ROM_PTR(&pin_GPIO26) }, - { MP_ROM_QSTR(MP_QSTR_I2S_WS), MP_ROM_PTR(&pin_GPIO25) }, { MP_ROM_QSTR(MP_QSTR_I2S_DIN), MP_ROM_PTR(&pin_GPIO24) }, - { MP_ROM_QSTR(MP_QSTR_I2S_GPIO1), MP_ROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_I2S_MCLK), MP_ROM_PTR(&pin_GPIO25) }, + { MP_ROM_QSTR(MP_QSTR_I2S_BCLK), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_I2S_WS), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_I2S_IRQ), MP_ROM_PTR(&pin_GPIO23) }, { MP_OBJ_NEW_QSTR(MP_QSTR_SD_SCK), MP_ROM_PTR(&pin_GPIO34) }, { MP_OBJ_NEW_QSTR(MP_QSTR_SDIO_CLOCK), MP_ROM_PTR(&pin_GPIO34) }, @@ -77,6 +104,8 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { MP_OBJ_NEW_QSTR(MP_QSTR_SD_CS), MP_ROM_PTR(&pin_GPIO39) }, { MP_OBJ_NEW_QSTR(MP_QSTR_SDIO_DATA3), MP_ROM_PTR(&pin_GPIO39) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_SDIO_DATA), MP_ROM_PTR(&sdio_data_tuple) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_SD_CARD_DETECT), MP_ROM_PTR(&pin_GPIO33) }, { MP_ROM_QSTR(MP_QSTR_USB_HOST_DATA_PLUS), MP_ROM_PTR(&pin_GPIO1) }, @@ -86,5 +115,7 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, { MP_ROM_QSTR(MP_QSTR_STEMMA_I2C), MP_ROM_PTR(&board_i2c_obj) }, { MP_ROM_QSTR(MP_QSTR_SPI), MP_ROM_PTR(&board_spi_obj) }, + // Shared with ESP TX/RX. + { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj) }, }; MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/raspberrypi/boards/adafruit_itsybitsy_rp2040/mpconfigboard.mk b/ports/raspberrypi/boards/adafruit_itsybitsy_rp2040/mpconfigboard.mk index 965acff2775..781dfe46ad1 100644 --- a/ports/raspberrypi/boards/adafruit_itsybitsy_rp2040/mpconfigboard.mk +++ b/ports/raspberrypi/boards/adafruit_itsybitsy_rp2040/mpconfigboard.mk @@ -6,4 +6,4 @@ USB_MANUFACTURER = "Adafruit" CHIP_VARIANT = RP2040 CHIP_FAMILY = rp2 -EXTERNAL_FLASH_DEVICES = "W25Q64JVxQ" +EXTERNAL_FLASH_DEVICES = "W25Q64JVxQ,GD25Q64C" diff --git a/ports/raspberrypi/boards/adafruit_kb2040/mpconfigboard.mk b/ports/raspberrypi/boards/adafruit_kb2040/mpconfigboard.mk index f9e1e2cf157..08c85bb3f46 100644 --- a/ports/raspberrypi/boards/adafruit_kb2040/mpconfigboard.mk +++ b/ports/raspberrypi/boards/adafruit_kb2040/mpconfigboard.mk @@ -6,4 +6,4 @@ USB_MANUFACTURER = "Adafruit" CHIP_VARIANT = RP2040 CHIP_FAMILY = rp2 -EXTERNAL_FLASH_DEVICES = "W25Q64JVxQ" +EXTERNAL_FLASH_DEVICES = "W25Q64JVxQ,GD25Q64C" diff --git a/ports/raspberrypi/boards/adafruit_macropad_rp2040/board.c b/ports/raspberrypi/boards/adafruit_macropad_rp2040/board.c index 673d9303d6b..5846897d97f 100644 --- a/ports/raspberrypi/boards/adafruit_macropad_rp2040/board.c +++ b/ports/raspberrypi/boards/adafruit_macropad_rp2040/board.c @@ -29,7 +29,7 @@ uint8_t display_init_sequence[] = { 0xda, 1, 0x12, // com pins 0x81, 1, 0xff, // contrast 255 0xd9, 1, 0x1f, // pre/dis-charge 2DCLKs/2CLKs - 0xdb, 1, 0x20, // VCOM deslect 0.770 + 0xdb, 1, 0x20, // VCOM select 0.770 0x20, 1, 0x20, 0x33, 0, // VPP 9V 0xa6, 0, // not inverted @@ -41,14 +41,13 @@ void board_init(void) { fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_GPIO26, &pin_GPIO27, NULL, false); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_GPIO24, // Command or data - &pin_GPIO22, // Chip select - &pin_GPIO23, // Reset + MP_OBJ_FROM_PTR(&pin_GPIO24), // Command or data + MP_OBJ_FROM_PTR(&pin_GPIO22), // Chip select + MP_OBJ_FROM_PTR(&pin_GPIO23), // Reset 10000000, // Baudrate 0, // Polarity 0); // Phase diff --git a/ports/raspberrypi/boards/adafruit_macropad_rp2040/mpconfigboard.h b/ports/raspberrypi/boards/adafruit_macropad_rp2040/mpconfigboard.h index 32ba5284a62..673f9cdc1c5 100644 --- a/ports/raspberrypi/boards/adafruit_macropad_rp2040/mpconfigboard.h +++ b/ports/raspberrypi/boards/adafruit_macropad_rp2040/mpconfigboard.h @@ -6,7 +6,7 @@ #pragma once -#define MICROPY_HW_BOARD_NAME "Adafruit Macropad RP2040" +#define MICROPY_HW_BOARD_NAME "Adafruit MacroPad RP2040" #define MICROPY_HW_MCU_NAME "rp2040" #define MICROPY_HW_NEOPIXEL (&pin_GPIO19) diff --git a/ports/raspberrypi/boards/adafruit_macropad_rp2040/mpconfigboard.mk b/ports/raspberrypi/boards/adafruit_macropad_rp2040/mpconfigboard.mk index 4d708bcf794..2acc4e428e5 100644 --- a/ports/raspberrypi/boards/adafruit_macropad_rp2040/mpconfigboard.mk +++ b/ports/raspberrypi/boards/adafruit_macropad_rp2040/mpconfigboard.mk @@ -1,9 +1,9 @@ USB_VID = 0x239A USB_PID = 0x8108 -USB_PRODUCT = "Macropad RP2040" +USB_PRODUCT = "MacroPad RP2040" USB_MANUFACTURER = "Adafruit" CHIP_VARIANT = RP2040 CHIP_FAMILY = rp2 -EXTERNAL_FLASH_DEVICES = "W25Q64JVxQ" +EXTERNAL_FLASH_DEVICES = "W25Q64JVxQ,GD25Q64C" diff --git a/ports/raspberrypi/boards/adafruit_metro_rp2040/mpconfigboard.h b/ports/raspberrypi/boards/adafruit_metro_rp2040/mpconfigboard.h index 4242599354c..fdbd18c0e66 100644 --- a/ports/raspberrypi/boards/adafruit_metro_rp2040/mpconfigboard.h +++ b/ports/raspberrypi/boards/adafruit_metro_rp2040/mpconfigboard.h @@ -20,3 +20,11 @@ #define DEFAULT_UART_BUS_RX (&pin_GPIO1) #define DEFAULT_UART_BUS_TX (&pin_GPIO0) + +// Onboard microSD slot. +#define DEFAULT_SD_SCK (&pin_GPIO18) +#define DEFAULT_SD_MOSI (&pin_GPIO19) +#define DEFAULT_SD_MISO (&pin_GPIO20) +#define DEFAULT_SD_CS (&pin_GPIO23) +#define DEFAULT_SD_CARD_DETECT (&pin_GPIO15) +#define DEFAULT_SD_CARD_INSERTED true diff --git a/ports/raspberrypi/boards/adafruit_metro_rp2040/mpconfigboard.mk b/ports/raspberrypi/boards/adafruit_metro_rp2040/mpconfigboard.mk index 20c3042b7a1..980ee394611 100644 --- a/ports/raspberrypi/boards/adafruit_metro_rp2040/mpconfigboard.mk +++ b/ports/raspberrypi/boards/adafruit_metro_rp2040/mpconfigboard.mk @@ -6,4 +6,6 @@ USB_MANUFACTURER = "Adafruit" CHIP_VARIANT = RP2040 CHIP_FAMILY = rp2 -EXTERNAL_FLASH_DEVICES = "GD25Q64C,W25Q64JVxQ,W25Q128JV" +EXTERNAL_FLASH_DEVICES = "GD25Q64C,W25Q64JVxQ,W25Q128JVxQ" + +CIRCUITPY_SDIOIO = 1 diff --git a/ports/raspberrypi/boards/adafruit_metro_rp2040/pins.c b/ports/raspberrypi/boards/adafruit_metro_rp2040/pins.c index 859e7cacb08..b541aea6f1f 100644 --- a/ports/raspberrypi/boards/adafruit_metro_rp2040/pins.c +++ b/ports/raspberrypi/boards/adafruit_metro_rp2040/pins.c @@ -4,8 +4,21 @@ // // SPDX-License-Identifier: MIT +#include "py/objtuple.h" #include "shared-bindings/board/__init__.h" +// Four consecutive data GPIOs for the 4-bit SDIO interface (sdioio.SDCard). +static const mp_rom_obj_tuple_t sdio_data_tuple = { + {&mp_type_tuple}, + 4, + { + MP_ROM_PTR(&pin_GPIO20), + MP_ROM_PTR(&pin_GPIO21), + MP_ROM_PTR(&pin_GPIO22), + MP_ROM_PTR(&pin_GPIO23), + } +}; + static const mp_rom_map_elem_t board_module_globals_table[] = { CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS @@ -64,6 +77,8 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { MP_OBJ_NEW_QSTR(MP_QSTR_SD_CS), MP_ROM_PTR(&pin_GPIO23) }, { MP_OBJ_NEW_QSTR(MP_QSTR_SDIO_DATA3), MP_ROM_PTR(&pin_GPIO23) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_SDIO_DATA), MP_ROM_PTR(&sdio_data_tuple) }, + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, { MP_ROM_QSTR(MP_QSTR_STEMMA_I2C), MP_ROM_PTR(&board_i2c_obj) }, { MP_ROM_QSTR(MP_QSTR_SPI), MP_ROM_PTR(&board_spi_obj) }, diff --git a/ports/raspberrypi/boards/adafruit_metro_rp2350/board.c b/ports/raspberrypi/boards/adafruit_metro_rp2350/board.c index f85d1076c0b..83682afa976 100644 --- a/ports/raspberrypi/boards/adafruit_metro_rp2350/board.c +++ b/ports/raspberrypi/boards/adafruit_metro_rp2350/board.c @@ -32,6 +32,12 @@ bool board_reset_pin_number(uint8_t pin_number) { #endif void board_init(void) { + #if defined(DEFAULT_USB_HOST_5V_POWER) + // GPIO29 (USB_HOST_5V_POWER) powers the USB host port. + // Default to high (on). + board_reset_pin_number(DEFAULT_USB_HOST_5V_POWER->number); + #endif + #if defined(DEFAULT_USB_HOST_DATA_PLUS) common_hal_usb_host_port_construct(DEFAULT_USB_HOST_DATA_PLUS, DEFAULT_USB_HOST_DATA_MINUS); #endif diff --git a/ports/raspberrypi/boards/adafruit_metro_rp2350/mpconfigboard.h b/ports/raspberrypi/boards/adafruit_metro_rp2350/mpconfigboard.h index 694a0702735..1a583046416 100644 --- a/ports/raspberrypi/boards/adafruit_metro_rp2350/mpconfigboard.h +++ b/ports/raspberrypi/boards/adafruit_metro_rp2350/mpconfigboard.h @@ -35,3 +35,10 @@ #define DEFAULT_DVI_BUS_GREEN_DP (&pin_GPIO16) #define DEFAULT_DVI_BUS_BLUE_DN (&pin_GPIO13) #define DEFAULT_DVI_BUS_BLUE_DP (&pin_GPIO12) + +#define DEFAULT_SD_SCK (&pin_GPIO34) +#define DEFAULT_SD_MOSI (&pin_GPIO35) +#define DEFAULT_SD_MISO (&pin_GPIO36) +#define DEFAULT_SD_CS (&pin_GPIO39) +#define DEFAULT_SD_CARD_DETECT (&pin_GPIO40) +#define DEFAULT_SD_CARD_INSERTED false diff --git a/ports/raspberrypi/boards/adafruit_metro_rp2350/mpconfigboard.mk b/ports/raspberrypi/boards/adafruit_metro_rp2350/mpconfigboard.mk index e43a8dcf2a3..1590b1f3aac 100644 --- a/ports/raspberrypi/boards/adafruit_metro_rp2350/mpconfigboard.mk +++ b/ports/raspberrypi/boards/adafruit_metro_rp2350/mpconfigboard.mk @@ -8,3 +8,8 @@ CHIP_PACKAGE = B CHIP_FAMILY = rp2 EXTERNAL_FLASH_DEVICES = "W25Q128JVxQ" + +CIRCUITPY_SDIOIO = 1 + +CIRCUITPY_PICOGAME = 1 +CIRCUITPY_PICOGAME_FRAMEBUFFER = 1 diff --git a/ports/raspberrypi/boards/adafruit_metro_rp2350/pins.c b/ports/raspberrypi/boards/adafruit_metro_rp2350/pins.c index 3fa135b1796..a38c2496dd6 100644 --- a/ports/raspberrypi/boards/adafruit_metro_rp2350/pins.c +++ b/ports/raspberrypi/boards/adafruit_metro_rp2350/pins.c @@ -4,8 +4,21 @@ // // SPDX-License-Identifier: MIT +#include "py/objtuple.h" #include "shared-bindings/board/__init__.h" +// Four consecutive data GPIOs for the 4-bit SDIO interface (sdioio.SDCard). +static const mp_rom_obj_tuple_t sdio_data_tuple = { + {&mp_type_tuple}, + 4, + { + MP_ROM_PTR(&pin_GPIO36), + MP_ROM_PTR(&pin_GPIO37), + MP_ROM_PTR(&pin_GPIO38), + MP_ROM_PTR(&pin_GPIO39), + } +}; + static const mp_rom_map_elem_t board_module_globals_table[] = { CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS @@ -85,6 +98,8 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { MP_OBJ_NEW_QSTR(MP_QSTR_SD_CS), MP_ROM_PTR(&pin_GPIO39) }, { MP_OBJ_NEW_QSTR(MP_QSTR_SDIO_DATA3), MP_ROM_PTR(&pin_GPIO39) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_SDIO_DATA), MP_ROM_PTR(&sdio_data_tuple) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_SD_CARD_DETECT), MP_ROM_PTR(&pin_GPIO40) }, { MP_ROM_QSTR(MP_QSTR_USB_HOST_DATA_PLUS), MP_ROM_PTR(&pin_GPIO32) }, diff --git a/ports/raspberrypi/boards/adafruit_qt2040_trinkey/mpconfigboard.mk b/ports/raspberrypi/boards/adafruit_qt2040_trinkey/mpconfigboard.mk index 5f07632b4f6..4252fafba2e 100644 --- a/ports/raspberrypi/boards/adafruit_qt2040_trinkey/mpconfigboard.mk +++ b/ports/raspberrypi/boards/adafruit_qt2040_trinkey/mpconfigboard.mk @@ -6,4 +6,4 @@ USB_MANUFACTURER = "Adafruit" CHIP_VARIANT = RP2040 CHIP_FAMILY = rp2 -EXTERNAL_FLASH_DEVICES = "W25Q64JVxQ" +EXTERNAL_FLASH_DEVICES = "W25Q64JVxQ,GD25Q64C" diff --git a/ports/raspberrypi/boards/adafruit_qtpy_rp2040/mpconfigboard.mk b/ports/raspberrypi/boards/adafruit_qtpy_rp2040/mpconfigboard.mk index 8258f878336..2b8431454b0 100644 --- a/ports/raspberrypi/boards/adafruit_qtpy_rp2040/mpconfigboard.mk +++ b/ports/raspberrypi/boards/adafruit_qtpy_rp2040/mpconfigboard.mk @@ -6,4 +6,4 @@ USB_MANUFACTURER = "Adafruit" CHIP_VARIANT = RP2040 CHIP_FAMILY = rp2 -EXTERNAL_FLASH_DEVICES = "W25Q64JVxQ" +EXTERNAL_FLASH_DEVICES = "W25Q64JVxQ,GD25Q64C" diff --git a/ports/raspberrypi/boards/adafruit_tinychad_rp2350/board.c b/ports/raspberrypi/boards/adafruit_tinychad_rp2350/board.c new file mode 100644 index 00000000000..cfa2308f796 --- /dev/null +++ b/ports/raspberrypi/boards/adafruit_tinychad_rp2350/board.c @@ -0,0 +1,12 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "py/obj.h" +#include "supervisor/board.h" + +#include "common-hal/picodvi/__init__.h" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/raspberrypi/boards/adafruit_tinychad_rp2350/mpconfigboard.h b/ports/raspberrypi/boards/adafruit_tinychad_rp2350/mpconfigboard.h new file mode 100644 index 00000000000..958ab01a0b6 --- /dev/null +++ b/ports/raspberrypi/boards/adafruit_tinychad_rp2350/mpconfigboard.h @@ -0,0 +1,20 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Dan Halbert for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#define MICROPY_HW_BOARD_NAME "Adafruit Tinychad RP2350" +#define MICROPY_HW_MCU_NAME "rp2350a" + +#define MICROPY_HW_NEOPIXEL (&pin_GPIO17) + +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO19) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO18) + +#define DEFAULT_SPI_BUS_SCK (&pin_GPIO10) +#define DEFAULT_SPI_BUS_MOSI (&pin_GPIO11) +#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/adafruit_tinychad_rp2350/mpconfigboard.mk b/ports/raspberrypi/boards/adafruit_tinychad_rp2350/mpconfigboard.mk new file mode 100644 index 00000000000..36359c88fe4 --- /dev/null +++ b/ports/raspberrypi/boards/adafruit_tinychad_rp2350/mpconfigboard.mk @@ -0,0 +1,13 @@ +USB_VID = 0x239A +USB_PID = 0x8170 +USB_PRODUCT = "Tinychad RP2350" +USB_MANUFACTURER = "Adafruit" + +CHIP_VARIANT = RP2350 +CHIP_PACKAGE = A +CHIP_FAMILY = rp2 + +EXTERNAL_FLASH_DEVICES = "GD25Q64C,W25Q64JVxQ" + +# GPIO12-19 needed for picodvi, but many are not available. +CIRCUITPY_PICODVI = 0 diff --git a/ports/raspberrypi/boards/adafruit_tinychad_rp2350/pico-sdk-configboard.h b/ports/raspberrypi/boards/adafruit_tinychad_rp2350/pico-sdk-configboard.h new file mode 100644 index 00000000000..2d9283a9192 --- /dev/null +++ b/ports/raspberrypi/boards/adafruit_tinychad_rp2350/pico-sdk-configboard.h @@ -0,0 +1,10 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// Put board-specific pico-sdk definitions here. This file must exist. + +// Allow extra time for xosc to start. +#define PICO_XOSC_STARTUP_DELAY_MULTIPLIER 64 diff --git a/ports/raspberrypi/boards/adafruit_tinychad_rp2350/pins.c b/ports/raspberrypi/boards/adafruit_tinychad_rp2350/pins.c new file mode 100644 index 00000000000..0d769fd4d56 --- /dev/null +++ b/ports/raspberrypi/boards/adafruit_tinychad_rp2350/pins.c @@ -0,0 +1,54 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Dan Halbert for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { 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_TX), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO1) }, + + { 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_D20), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_D21), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_D22), MP_ROM_PTR(&pin_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_D23), MP_ROM_PTR(&pin_GPIO23) }, + + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_GPIO13) }, + + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO19) }, + + { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_CS), MP_ROM_PTR(&pin_GPIO10) }, + + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO12) }, + + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO17) }, + + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, + { MP_ROM_QSTR(MP_QSTR_STEMMA_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_module_globals_table); diff --git a/ports/raspberrypi/boards/archi/mpconfigboard.mk b/ports/raspberrypi/boards/archi/mpconfigboard.mk index 1189e6879b9..faf9833da62 100644 --- a/ports/raspberrypi/boards/archi/mpconfigboard.mk +++ b/ports/raspberrypi/boards/archi/mpconfigboard.mk @@ -20,3 +20,5 @@ FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_Register FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_seesaw FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_framebuf FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_SimpleIO + +OPTIMIZATION_FLAGS = -O2 diff --git a/ports/raspberrypi/boards/bradanlanestudio_explorer_rp2040/board.c b/ports/raspberrypi/boards/bradanlanestudio_explorer_rp2040/board.c index a20b1647317..d8292c94668 100644 --- a/ports/raspberrypi/boards/bradanlanestudio_explorer_rp2040/board.c +++ b/ports/raspberrypi/boards/bradanlanestudio_explorer_rp2040/board.c @@ -207,14 +207,13 @@ void board_init(void) { fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_GPIO14, &pin_GPIO15, NULL, false); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_GPIO11, // DEFAULT_SPI_BUS_DC, // EPD_DC Command or data - &pin_GPIO13, // DEFAULT_SPI_BUS_CS, // EPD_CS Chip select - &pin_GPIO10, // DEFAULT_SPI_BUS_RESET, // EPD_RST Reset + MP_OBJ_FROM_PTR(&pin_GPIO11), // DEFAULT_SPI_BUS_DC, // EPD_DC Command or data + MP_OBJ_FROM_PTR(&pin_GPIO13), // DEFAULT_SPI_BUS_CS, // EPD_CS Chip select + MP_OBJ_FROM_PTR(&pin_GPIO10), // DEFAULT_SPI_BUS_RESET, // EPD_RST Reset 1000000, // Baudrate 0, // Polarity 0); // Phase @@ -251,71 +250,62 @@ void board_init(void) { if ((vid_setting == 1) || // DCNextGen SSD1681 BWR rotated 270 (vid_setting == 3) || // Explorer SSD1681 BW rotated 0 (vid_setting == 4)) { // Explorer SSD1681 BWR rotated 0 - common_hal_epaperdisplay_epaperdisplay_construct( - display, - bus, - _start_sequence_ssd1681, sizeof(_start_sequence_ssd1681), - 1.0, // start up time - _stop_sequence_ssd1681, sizeof(_stop_sequence_ssd1681), - WIDTH, // width - HEIGHT, // height - WIDTH, // ram_width - HEIGHT + 0x60, // ram_height RAM is actually only 200 bits high but we use 296 to match the 9 bits - 0, // colstart - 0, // rowstart - rotation, // rotation - SSD_SET_RAMXPOS, // set_column_window_command - SSD_SET_RAMYPOS, // set_row_window_command - SSD_SET_RAMXCOUNT, // set_current_column_command - SSD_SET_RAMYCOUNT, // set_current_row_command - SSD_WRITE_RAM_BLK, // write_black_ram_command - false, // black_bits_inverted - SSD_WRITE_RAM_RED, // write_color_ram_command - false, // color_bits_inverted - 0xFF0000, // highlight_color (RED for tri-color display) - _refresh_sequence_ssd1681, sizeof(_refresh_sequence_ssd1681), // refresh_display_command - refresh_time, // refresh_time - &pin_GPIO9, // DEFAULT_SPI_BUS_BUSY, // busy_pin - true, // busy_state - seconds_per_frame, // seconds_per_frame (does not seem the user can change this) - true, // always_toggle_chip_select - false, // not grayscale - false, // not acep - false, // not two_byte_sequence_length - true); // address_little_endian + epaperdisplay_construct_args_t args = EPAPERDISPLAY_CONSTRUCT_ARGS_DEFAULTS; + args.bus = bus; + args.start_sequence = _start_sequence_ssd1681; + args.start_sequence_len = sizeof(_start_sequence_ssd1681); + args.start_up_time = 1.0; + args.stop_sequence = _stop_sequence_ssd1681; + args.stop_sequence_len = sizeof(_stop_sequence_ssd1681); + args.width = WIDTH; + args.height = HEIGHT; + args.ram_width = WIDTH; + args.ram_height = HEIGHT + 0x60; + args.rotation = rotation; + args.set_column_window_command = SSD_SET_RAMXPOS; + args.set_row_window_command = SSD_SET_RAMYPOS; + args.set_current_column_command = SSD_SET_RAMXCOUNT; + args.set_current_row_command = SSD_SET_RAMYCOUNT; + args.write_black_ram_command = SSD_WRITE_RAM_BLK; + args.write_color_ram_command = SSD_WRITE_RAM_RED; + args.highlight_color = 0xFF0000; + args.refresh_sequence = _refresh_sequence_ssd1681; + args.refresh_sequence_len = sizeof(_refresh_sequence_ssd1681); + args.refresh_time = refresh_time; + args.busy_pin = &pin_GPIO9; + args.busy_state = true; + args.seconds_per_frame = seconds_per_frame; + args.always_toggle_chip_select = true; + args.address_little_endian = true; + common_hal_epaperdisplay_epaperdisplay_construct(display, &args); } else if (vid_setting == 2) { // Explorer SSD1608 BW - common_hal_epaperdisplay_epaperdisplay_construct( - display, - bus, - _start_sequence_ssd1608, sizeof(_start_sequence_ssd1608), - 1.0, // start up time - _stop_sequence_ssd1608, sizeof(_stop_sequence_ssd1608), - WIDTH, // width - HEIGHT, // height - WIDTH, // ram_width - HEIGHT /* + 0x60 */, // ram_height RAM is actually only 200 bits high but we use 296 to match the 9 bits - 0, // colstart - 0, // rowstart - rotation, // rotation - SSD_SET_RAMXPOS, // set_column_window_command - SSD_SET_RAMYPOS, // set_row_window_command - SSD_SET_RAMXCOUNT, // set_current_column_command - SSD_SET_RAMYCOUNT, // set_current_row_command - SSD_WRITE_RAM_BLK, // write_black_ram_command - false, // black_bits_inverted - NO_COMMAND, // write_color_ram_command - false, // color_bits_inverted - 0x000000, // highlight_color (RED for tri-color display) - _refresh_sequence_ssd1608, sizeof(_refresh_sequence_ssd1608), // refresh_display_command - refresh_time, // refresh_time - &pin_GPIO9, // DEFAULT_SPI_BUS_BUSY, // busy_pin - true, // busy_state - seconds_per_frame, // seconds_per_frame (does not seem the user can change this) - true, // always_toggle_chip_select - false, // not grayscale - false, // not acep - false, // not two_byte_sequence_length - true); // address_little_endian + epaperdisplay_construct_args_t args = EPAPERDISPLAY_CONSTRUCT_ARGS_DEFAULTS; + args.bus = bus; + args.start_sequence = _start_sequence_ssd1608; + args.start_sequence_len = sizeof(_start_sequence_ssd1608); + args.start_up_time = 1.0; + args.stop_sequence = _stop_sequence_ssd1608; + args.stop_sequence_len = sizeof(_stop_sequence_ssd1608); + args.width = WIDTH; + args.height = HEIGHT; + args.ram_width = WIDTH; + args.ram_height = HEIGHT; + args.rotation = rotation; + args.set_column_window_command = SSD_SET_RAMXPOS; + args.set_row_window_command = SSD_SET_RAMYPOS; + args.set_current_column_command = SSD_SET_RAMXCOUNT; + args.set_current_row_command = SSD_SET_RAMYCOUNT; + args.write_black_ram_command = SSD_WRITE_RAM_BLK; + args.write_color_ram_command = NO_COMMAND; + args.refresh_sequence = _refresh_sequence_ssd1608; + args.refresh_sequence_len = sizeof(_refresh_sequence_ssd1608); + args.refresh_time = refresh_time; + args.busy_pin = &pin_GPIO9; + args.busy_state = true; + args.seconds_per_frame = seconds_per_frame; + args.always_toggle_chip_select = true; + args.address_little_endian = true; + common_hal_epaperdisplay_epaperdisplay_construct(display, &args); } else { // what should happen if this firmware is installed on some other board? // currently, we mark the display as None diff --git a/ports/raspberrypi/boards/bradanlanestudio_explorer_rp2040/mpconfigboard.mk b/ports/raspberrypi/boards/bradanlanestudio_explorer_rp2040/mpconfigboard.mk index 14f27c07b99..edb4f3bb3d8 100644 --- a/ports/raspberrypi/boards/bradanlanestudio_explorer_rp2040/mpconfigboard.mk +++ b/ports/raspberrypi/boards/bradanlanestudio_explorer_rp2040/mpconfigboard.mk @@ -15,6 +15,9 @@ EXTERNAL_FLASH_DEVICES = "GD25Q64C" CIRCUITPY__EVE = 1 +# The default is -O3. +OPTIMIZATION_FLAGS = -Os + FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_asyncio FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_Bitmap_Font FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_Display_Shapes diff --git a/ports/raspberrypi/boards/challenger_rp2040_nfc/board.c b/ports/raspberrypi/boards/challenger_rp2040_nfc/board.c new file mode 100644 index 00000000000..52395d4ce04 --- /dev/null +++ b/ports/raspberrypi/boards/challenger_rp2040_nfc/board.c @@ -0,0 +1,10 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2022 Pontus Oldberg, Invector Labs +// SPDX-FileCopyrightText: Copyright (c) 2026 TheFilipcom4607 +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/raspberrypi/boards/challenger_rp2040_nfc/mpconfigboard.h b/ports/raspberrypi/boards/challenger_rp2040_nfc/mpconfigboard.h new file mode 100644 index 00000000000..630dcbce721 --- /dev/null +++ b/ports/raspberrypi/boards/challenger_rp2040_nfc/mpconfigboard.h @@ -0,0 +1,26 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2022 Pontus Oldberg, Invector Labs +// +// SPDX-License-Identifier: MIT + +#pragma once + +#define MICROPY_HW_BOARD_NAME "Challenger RP2040 NFC" +#define MICROPY_HW_MCU_NAME "rp2040" + +// The on-board PN7150 sits on GPIO10/11 with no external pull-up +// resistors: iLabs' Arduino core relies on the RP2040's internal +// pull-ups instead (TwoWire::begin() calls gpio_pull_up() on both pins). +#define CIRCUITPY_I2C_ALLOW_INTERNAL_PULL_UP (1) + +#define MICROPY_HW_LED_STATUS (&pin_GPIO24) +#define MICROPY_HW_NEOPIXEL (&pin_GPIO14) + +#define DEFAULT_UART_BUS_TX (&pin_GPIO16) +#define DEFAULT_UART_BUS_RX (&pin_GPIO17) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO0) +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO1) +#define DEFAULT_SPI_BUS_SCK (&pin_GPIO22) +#define DEFAULT_SPI_BUS_MOSI (&pin_GPIO23) +#define DEFAULT_SPI_BUS_MISO (&pin_GPIO20) diff --git a/ports/raspberrypi/boards/challenger_rp2040_nfc/mpconfigboard.mk b/ports/raspberrypi/boards/challenger_rp2040_nfc/mpconfigboard.mk new file mode 100644 index 00000000000..e8618ad660b --- /dev/null +++ b/ports/raspberrypi/boards/challenger_rp2040_nfc/mpconfigboard.mk @@ -0,0 +1,11 @@ +USB_VID = 0x2e8a +USB_PID = 0x1036 +USB_PRODUCT = "Challenger RP2040 NFC" +USB_MANUFACTURER = "Invector Labs" + +CHIP_VARIANT = RP2040 +CHIP_FAMILY = rp2 + +EXTERNAL_FLASH_DEVICES = "W25Q64JVxQ" + +CIRCUITPY__EVE = 1 diff --git a/ports/raspberrypi/boards/challenger_rp2040_nfc/pico-sdk-configboard.h b/ports/raspberrypi/boards/challenger_rp2040_nfc/pico-sdk-configboard.h new file mode 100644 index 00000000000..718b103cc2a --- /dev/null +++ b/ports/raspberrypi/boards/challenger_rp2040_nfc/pico-sdk-configboard.h @@ -0,0 +1,10 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2022 Pontus Oldberg, Invector Labs +// SPDX-FileCopyrightText: Copyright (c) 2026 TheFilipcom4607 +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Put board-specific pico-sdk definitions here. This file must exist. diff --git a/ports/raspberrypi/boards/challenger_rp2040_nfc/pins.c b/ports/raspberrypi/boards/challenger_rp2040_nfc/pins.c new file mode 100644 index 00000000000..67f8ecfe731 --- /dev/null +++ b/ports/raspberrypi/boards/challenger_rp2040_nfc/pins.c @@ -0,0 +1,86 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2022 Pontus Oldberg, Invector Labs +// SPDX-FileCopyrightText: Copyright (c) 2026 TheFilipcom4607 +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_GP0), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_GP1), MP_ROM_PTR(&pin_GPIO1) }, + + { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_GP2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_GP3), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_GP4), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_GP5), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_GP6), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_GP7), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_GP8), MP_ROM_PTR(&pin_GPIO8) }, + + // On board PN7150 NFC controller. Not available on the pin headers. + { MP_ROM_QSTR(MP_QSTR_NFC_IRQ), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_GP9), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_NFC_SDA), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_GP10), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_NFC_SCL), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_GP11), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_NFC_RESET), MP_ROM_PTR(&pin_GPIO12) }, + { 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_NEOPIXEL), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_GP14), MP_ROM_PTR(&pin_GPIO14) }, + + { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_GP16), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_GP17), MP_ROM_PTR(&pin_GPIO17) }, + + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_SDI), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_GP20), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_GP22), MP_ROM_PTR(&pin_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_SDO), MP_ROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_GP23), MP_ROM_PTR(&pin_GPIO23) }, + + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO24) }, + { MP_ROM_QSTR(MP_QSTR_GP24), MP_ROM_PTR(&pin_GPIO24) }, + + // A4 and A5 are digital only on this board. + { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_GP19), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_GP21), MP_ROM_PTR(&pin_GPIO21) }, + + { MP_ROM_QSTR(MP_QSTR_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), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_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), 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_module_globals_table); diff --git a/ports/raspberrypi/boards/challenger_rp2350_wifi6_ble5/mpconfigboard.mk b/ports/raspberrypi/boards/challenger_rp2350_wifi6_ble5/mpconfigboard.mk index d4f2cdb90d0..7663bcfb19d 100644 --- a/ports/raspberrypi/boards/challenger_rp2350_wifi6_ble5/mpconfigboard.mk +++ b/ports/raspberrypi/boards/challenger_rp2350_wifi6_ble5/mpconfigboard.mk @@ -12,5 +12,9 @@ EXTERNAL_FLASH_DEVICES = "W25Q64JVxQ" CIRCUITPY__EVE = 1 CIRCUITPY_ALARM = 0 +# GPIO12-19 needed for picodvi, but many are not available. +CIRCUITPY_PICODVI = 0 + + FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_HID FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_Register diff --git a/ports/raspberrypi/boards/cytron_edu_pico_w/link.ld b/ports/raspberrypi/boards/cytron_edu_pico_w/link.ld index e814bead4c5..d4f5109f4b6 100644 --- a/ports/raspberrypi/boards/cytron_edu_pico_w/link.ld +++ b/ports/raspberrypi/boards/cytron_edu_pico_w/link.ld @@ -1 +1 @@ -firmware_size = 1532k; +firmware_size = 1536k; diff --git a/ports/raspberrypi/boards/cytron_edu_pico_w/mpconfigboard.mk b/ports/raspberrypi/boards/cytron_edu_pico_w/mpconfigboard.mk index 0bbfb4fce64..384b0060df8 100644 --- a/ports/raspberrypi/boards/cytron_edu_pico_w/mpconfigboard.mk +++ b/ports/raspberrypi/boards/cytron_edu_pico_w/mpconfigboard.mk @@ -34,6 +34,9 @@ CFLAGS += \ # Must be accompanied by a linker script change CFLAGS += -DCIRCUITPY_FIRMWARE_SIZE='(1536 * 1024)' +# The default is -O3. Change to -O2 because the build was overflowing. +OPTIMIZATION_FLAGS = -O2 + # Include these Python libraries in firmware. FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_Motor diff --git a/ports/raspberrypi/boards/cytron_edu_v2_pico_2w/board.c b/ports/raspberrypi/boards/cytron_edu_v2_pico_2w/board.c new file mode 100644 index 00000000000..e6a868ab212 --- /dev/null +++ b/ports/raspberrypi/boards/cytron_edu_v2_pico_2w/board.c @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/raspberrypi/boards/cytron_edu_v2_pico_2w/link.ld b/ports/raspberrypi/boards/cytron_edu_v2_pico_2w/link.ld new file mode 100644 index 00000000000..d4f5109f4b6 --- /dev/null +++ b/ports/raspberrypi/boards/cytron_edu_v2_pico_2w/link.ld @@ -0,0 +1 @@ +firmware_size = 1536k; diff --git a/ports/raspberrypi/boards/cytron_edu_v2_pico_2w/mpconfigboard.h b/ports/raspberrypi/boards/cytron_edu_v2_pico_2w/mpconfigboard.h new file mode 100644 index 00000000000..8eab7e5a525 --- /dev/null +++ b/ports/raspberrypi/boards/cytron_edu_v2_pico_2w/mpconfigboard.h @@ -0,0 +1,21 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#define MICROPY_HW_BOARD_NAME "Cytron EDU PICO 2" +#define MICROPY_HW_MCU_NAME "rp2350a" + +#define CIRCUITPY_DIGITALIO_HAVE_INVALID_PULL (1) +#define CIRCUITPY_DIGITALIO_HAVE_INVALID_DRIVE_MODE (1) + +#define MICROPY_HW_LED_STATUS (&pin_CYW0) + +#define CIRCUITPY_BOARD_I2C (1) +#define CIRCUITPY_BOARD_I2C_PIN {{.scl = &pin_GPIO5, .sda = &pin_GPIO4}} + +#define CIRCUITPY_BOARD_SPI (1) +#define CIRCUITPY_BOARD_SPI_PIN {{.clock = &pin_GPIO18, .mosi = &pin_GPIO19, .miso = &pin_GPIO16}} diff --git a/ports/raspberrypi/boards/cytron_edu_v2_pico_2w/mpconfigboard.mk b/ports/raspberrypi/boards/cytron_edu_v2_pico_2w/mpconfigboard.mk new file mode 100644 index 00000000000..75d49696a13 --- /dev/null +++ b/ports/raspberrypi/boards/cytron_edu_v2_pico_2w/mpconfigboard.mk @@ -0,0 +1,57 @@ +USB_VID = 0x2E8A +USB_PID = 0x107E +USB_PRODUCT = "Cytron EDU PICO 2 for Pico 2W" +USB_MANUFACTURER = "Cytron" + +CHIP_VARIANT = RP2350 +CHIP_PACKAGE = A +CHIP_FAMILY = rp2 + +EXTERNAL_FLASH_DEVICES = "W25Q16JVxQ" + +CIRCUITPY_SDCARDIO = 1 + +CIRCUITPY__EVE = 1 + +CIRCUITPY_CYW43 = 1 +CIRCUITPY_SSL = 1 +CIRCUITPY_HASHLIB = 1 +CIRCUITPY_WEB_WORKFLOW = 1 +CIRCUITPY_MDNS = 1 +CIRCUITPY_SOCKETPOOL = 1 +CIRCUITPY_WIFI = 1 + +# GPIO12-19 needed for picodvi, but many are not available. +CIRCUITPY_PICODVI = 0 + +CFLAGS += \ + -DCYW43_PIN_WL_DYNAMIC=0 \ + -DCYW43_DEFAULT_PIN_WL_HOST_WAKE=24 \ + -DCYW43_DEFAULT_PIN_WL_REG_ON=23 \ + -DCYW43_DEFAULT_PIN_WL_CLOCK=29 \ + -DCYW43_DEFAULT_PIN_WL_DATA_IN=24 \ + -DCYW43_DEFAULT_PIN_WL_DATA_OUT=24 \ + -DCYW43_DEFAULT_PIN_WL_CS=25 \ + -DCYW43_WL_GPIO_COUNT=3 \ + -DCYW43_WL_GPIO_LED_PIN=0 + -DCYW43_PIO_CLOCK_DIV_INT=3 + +# The default is -O3. +OPTIMIZATION_FLAGS = -Os + +# Include these Python libraries in firmware. +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_Display_Text +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_Register +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_Motor +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_SimpleIO +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_framebuf +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_OPT4048 +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_SSD1306 +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_ImageLoad +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_AHTx0 +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_SD +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_HTTPServer +FROZEN_MPY_DIRS += $(TOP)/frozen/CircuitPython_edupico2_paj7620 + +CFLAGS += -DCIRCUITPY_FIRMWARE_SIZE='(1536 * 1024)' diff --git a/ports/raspberrypi/boards/cytron_edu_v2_pico_2w/pico-sdk-configboard.h b/ports/raspberrypi/boards/cytron_edu_v2_pico_2w/pico-sdk-configboard.h new file mode 100644 index 00000000000..110195b7794 --- /dev/null +++ b/ports/raspberrypi/boards/cytron_edu_v2_pico_2w/pico-sdk-configboard.h @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Put board-specific pico-sdk definitions here. This file must exist. diff --git a/ports/raspberrypi/boards/cytron_edu_v2_pico_2w/pins.c b/ports/raspberrypi/boards/cytron_edu_v2_pico_2w/pins.c new file mode 100644 index 00000000000..83b93e72685 --- /dev/null +++ b/ports/raspberrypi/boards/cytron_edu_v2_pico_2w/pins.c @@ -0,0 +1,86 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { 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_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) }, + + // Motor Controls + { MP_ROM_QSTR(MP_QSTR_M1A), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_M1B), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_M2A), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_M2B), MP_ROM_PTR(&pin_GPIO13) }, + + { MP_ROM_QSTR(MP_QSTR_GP14), MP_ROM_PTR(&pin_GPIO14) }, + + { MP_ROM_QSTR(MP_QSTR_LOG_SWITCH), MP_ROM_PTR(&pin_GPIO15) }, + { 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) }, + + // SPI Pins for SD Card + { MP_ROM_QSTR(MP_QSTR_SD_MISO), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_SD_CS), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_SD_SCK), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_SD_MOSI), 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_USB_RELAY), MP_ROM_PTR(&pin_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_GP22), MP_ROM_PTR(&pin_GPIO22) }, + + { MP_ROM_QSTR(MP_QSTR_SMPS_MODE), MP_ROM_PTR(&pin_CYW1) }, + + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_CYW0) }, + + { MP_ROM_QSTR(MP_QSTR_VBUS_SENSE), MP_ROM_PTR(&pin_CYW2) }, + + { 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_USB_HOST_DATA_PLUS), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_USB_HOST_DATA_MINUS), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_USB_HOST_POWER), MP_ROM_PTR(&pin_GPIO22) }, + + { 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_VOLTAGE_MONITOR), MP_ROM_PTR(&pin_GPIO29) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO29) }, + + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, + { MP_ROM_QSTR(MP_QSTR_SD_SPI), MP_ROM_PTR(&board_spi_obj) }, + + + { MP_ROM_QSTR(MP_QSTR_STEMMA_I2C), MP_ROM_PTR(&board_i2c_obj) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/raspberrypi/boards/cytron_maker_pi_rp2040/pins.c b/ports/raspberrypi/boards/cytron_maker_pi_rp2040/pins.c index 53fae76ac1b..dbfc713930b 100644 --- a/ports/raspberrypi/boards/cytron_maker_pi_rp2040/pins.c +++ b/ports/raspberrypi/boards/cytron_maker_pi_rp2040/pins.c @@ -62,6 +62,8 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { 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_GP29_A3), MP_ROM_PTR(&pin_GPIO29) }, + { MP_ROM_QSTR(MP_QSTR_GP29), MP_ROM_PTR(&pin_GPIO29) }, { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO29) }, { MP_ROM_QSTR(MP_QSTR_VBATT), MP_ROM_PTR(&pin_GPIO29) }, { MP_ROM_QSTR(MP_QSTR_VOLTAGE_MONITOR), MP_ROM_PTR(&pin_GPIO29) }, diff --git a/ports/raspberrypi/boards/cytron_maker_sumo_rp2350/board.c b/ports/raspberrypi/boards/cytron_maker_sumo_rp2350/board.c new file mode 100755 index 00000000000..5e436f1368c --- /dev/null +++ b/ports/raspberrypi/boards/cytron_maker_sumo_rp2350/board.c @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Alif Aiman for Cytron Technologies +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/raspberrypi/boards/cytron_maker_sumo_rp2350/mpconfigboard.h b/ports/raspberrypi/boards/cytron_maker_sumo_rp2350/mpconfigboard.h new file mode 100755 index 00000000000..666dfe2b528 --- /dev/null +++ b/ports/raspberrypi/boards/cytron_maker_sumo_rp2350/mpconfigboard.h @@ -0,0 +1,11 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Alif Aiman for Cytron Technologies +// +// SPDX-License-Identifier: MIT + +#define MICROPY_HW_BOARD_NAME "Cytron Maker Sumo RP2350" +#define MICROPY_HW_MCU_NAME "rp2350a" + +// User LED on GP3 doubles as the CircuitPython status LED +#define MICROPY_HW_LED_STATUS (&pin_GPIO3) diff --git a/ports/raspberrypi/boards/cytron_maker_sumo_rp2350/mpconfigboard.mk b/ports/raspberrypi/boards/cytron_maker_sumo_rp2350/mpconfigboard.mk new file mode 100755 index 00000000000..56f93d614fd --- /dev/null +++ b/ports/raspberrypi/boards/cytron_maker_sumo_rp2350/mpconfigboard.mk @@ -0,0 +1,16 @@ +USB_VID = 0x2E8A +USB_PID = 0x112F +USB_PRODUCT = "Maker Sumo RP2350" +USB_MANUFACTURER = "Cytron" + +CHIP_VARIANT = RP2350 +CHIP_PACKAGE = A +CHIP_FAMILY = rp2 + +# VERIFY against the flash chip on the board (W25Q16JVxQ = 2 MB) +EXTERNAL_FLASH_DEVICES = "W25Q16JVxQ" + +CIRCUITPY__EVE = 1 + +# GPIO12-19 needed for picodvi, but they are used by the buzzer, motors and servos. +CIRCUITPY_PICODVI = 0 diff --git a/ports/raspberrypi/boards/cytron_maker_sumo_rp2350/pico-sdk-configboard.h b/ports/raspberrypi/boards/cytron_maker_sumo_rp2350/pico-sdk-configboard.h new file mode 100755 index 00000000000..4e3afedf53d --- /dev/null +++ b/ports/raspberrypi/boards/cytron_maker_sumo_rp2350/pico-sdk-configboard.h @@ -0,0 +1,10 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Alif Aiman for Cytron Technologies +// +// SPDX-License-Identifier: MIT + +// Put board-specific pico-sdk definitions here. This file must exist. + +// Allow extra time for xosc to start. +#define PICO_XOSC_STARTUP_DELAY_MULTIPLIER 64 diff --git a/ports/raspberrypi/boards/cytron_maker_sumo_rp2350/pins.c b/ports/raspberrypi/boards/cytron_maker_sumo_rp2350/pins.c new file mode 100755 index 00000000000..e1f94022b2b --- /dev/null +++ b/ports/raspberrypi/boards/cytron_maker_sumo_rp2350/pins.c @@ -0,0 +1,85 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Cytron Technologies +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + // Raw GPIO names + { 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_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_GP23), MP_ROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_GP24), MP_ROM_PTR(&pin_GPIO24) }, + { MP_ROM_QSTR(MP_QSTR_GP25), MP_ROM_PTR(&pin_GPIO25) }, + { MP_ROM_QSTR(MP_QSTR_GP26), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_GP27), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_GP28), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_GP29), MP_ROM_PTR(&pin_GPIO29) }, + + // User interface + { MP_ROM_QSTR(MP_QSTR_USR_BTN), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_USR_LED), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_DIP1), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_DIP2), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_DIP3), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_BUZZER), MP_ROM_PTR(&pin_GPIO12) }, + + // Opponent sensors (active LOW: 0 = object detected) + { MP_ROM_QSTR(MP_QSTR_OPP_L), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_OPP_FL), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_OPP_FC), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_OPP_FR), MP_ROM_PTR(&pin_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_OPP_R), MP_ROM_PTR(&pin_GPIO8) }, + + // Motor driver (FAULT is active LOW: 0 = fault) + { MP_ROM_QSTR(MP_QSTR_PWM_L), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_DIR_L), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_PWM_R), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_DIR_R), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_FAULT_L), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_FAULT_R), MP_ROM_PTR(&pin_GPIO25) }, + + // Servos and IR start module + { MP_ROM_QSTR(MP_QSTR_SERVO1), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_SERVO2), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_IRST), MP_ROM_PTR(&pin_GPIO18) }, + + // Analog: edge sensors, potentiometer, motor voltage (1:11 divider) + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_EDGE_L), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_EDGE_R), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_POT), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO29) }, + { MP_ROM_QSTR(MP_QSTR_VM_SENSE), 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_module_globals_table); diff --git a/ports/raspberrypi/boards/cytron_motion_2350_pro/mpconfigboard.mk b/ports/raspberrypi/boards/cytron_motion_2350_pro/mpconfigboard.mk index 0ac939ce6a2..9a766f42da7 100644 --- a/ports/raspberrypi/boards/cytron_motion_2350_pro/mpconfigboard.mk +++ b/ports/raspberrypi/boards/cytron_motion_2350_pro/mpconfigboard.mk @@ -11,6 +11,10 @@ EXTERNAL_FLASH_DEVICES = "W25Q16JVxQ" CIRCUITPY__EVE = 1 +# GPIO12-19 needed for picodvi, but many are not available. +CIRCUITPY_PICODVI = 0 + + # Include these Python libraries in firmware. FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_Motor diff --git a/ports/raspberrypi/boards/datanoise_picoadk_v2/mpconfigboard.mk b/ports/raspberrypi/boards/datanoise_picoadk_v2/mpconfigboard.mk index 1b5c6c5d548..42d747537af 100644 --- a/ports/raspberrypi/boards/datanoise_picoadk_v2/mpconfigboard.mk +++ b/ports/raspberrypi/boards/datanoise_picoadk_v2/mpconfigboard.mk @@ -9,5 +9,8 @@ CHIP_FAMILY = rp2 EXTERNAL_FLASH_DEVICES = "GD25Q32C,W25Q32JVxQ" +# GPIO12-19 needed for picodvi, but many are not available. +CIRCUITPY_PICODVI = 0 + # Include these Python libraries in firmware. FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_SD diff --git a/ports/raspberrypi/boards/hack_club_sprig/board.c b/ports/raspberrypi/boards/hack_club_sprig/board.c index 89b1b3b75b7..94c5a7c5be9 100644 --- a/ports/raspberrypi/boards/hack_club_sprig/board.c +++ b/ports/raspberrypi/boards/hack_club_sprig/board.c @@ -10,7 +10,7 @@ #include "shared-bindings/fourwire/FourWire.h" #include "shared-module/displayio/__init__.h" #include "shared-module/displayio/mipi_constants.h" -#include "supervisor/shared/board.h" +#include "shared-bindings/board/__init__.h" // display init sequence from CircuitPython library https://github.com/adafruit/Adafruit_CircuitPython_ST7735R/blob/dfae353330cf051d1f31db9e4b681c8d70900cc5/adafruit_st7735r.py @@ -57,17 +57,14 @@ uint8_t display_init_sequence[] = { void board_init(void) { + busio_spi_obj_t *spi = common_hal_board_create_spi(0); fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; - busio_spi_obj_t *spi = &bus->inline_bus; - common_hal_busio_spi_construct(spi, &pin_GPIO18, &pin_GPIO19, &pin_GPIO16, false); - common_hal_busio_spi_never_reset(spi); - bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_GPIO22, // DC - &pin_GPIO20, // CS - &pin_GPIO26, // RST + MP_OBJ_FROM_PTR(CIRCUITPY_BOARD_TFT_DC), + MP_OBJ_FROM_PTR(CIRCUITPY_BOARD_TFT_CS), + MP_OBJ_FROM_PTR(CIRCUITPY_BOARD_TFT_RESET), 30000000, 0, 0); @@ -92,7 +89,7 @@ void board_init(void) { MIPI_COMMAND_WRITE_MEMORY_START, // Write memory command display_init_sequence, sizeof(display_init_sequence), - &pin_GPIO17, // backlight pin + CIRCUITPY_BOARD_TFT_BACKLIGHT, NO_BRIGHTNESS_COMMAND, 1.0f, // brightness false, // single_byte_bounds @@ -104,4 +101,8 @@ void board_init(void) { 50000); // backlight pwm frequency } +void board_deinit(void) { + common_hal_displayio_release_displays(); +} + // Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/raspberrypi/boards/hack_club_sprig/mpconfigboard.h b/ports/raspberrypi/boards/hack_club_sprig/mpconfigboard.h index 041aca6d45e..bfc0469a711 100644 --- a/ports/raspberrypi/boards/hack_club_sprig/mpconfigboard.h +++ b/ports/raspberrypi/boards/hack_club_sprig/mpconfigboard.h @@ -10,3 +10,11 @@ #define MICROPY_HW_MCU_NAME "rp2040" #define MICROPY_HW_LED_STATUS (&pin_GPIO4) + +#define CIRCUITPY_BOARD_TFT_DC (&pin_GPIO22) +#define CIRCUITPY_BOARD_TFT_CS (&pin_GPIO20) +#define CIRCUITPY_BOARD_TFT_RESET (&pin_GPIO26) +#define CIRCUITPY_BOARD_TFT_BACKLIGHT (&pin_GPIO17) + +#define CIRCUITPY_BOARD_SPI (1) +#define CIRCUITPY_BOARD_SPI_PIN {{.clock = &pin_GPIO18, .mosi = &pin_GPIO19, .miso = &pin_GPIO16 }} diff --git a/ports/raspberrypi/boards/hack_club_sprig/pins.c b/ports/raspberrypi/boards/hack_club_sprig/pins.c index e5ce1478398..7802ef5466d 100644 --- a/ports/raspberrypi/boards/hack_club_sprig/pins.c +++ b/ports/raspberrypi/boards/hack_club_sprig/pins.c @@ -60,7 +60,6 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO29) }, { MP_ROM_QSTR(MP_QSTR_VOLTAGE_MONITOR), MP_ROM_PTR(&pin_GPIO29) }, - // Start Sprig-specific definitions { MP_ROM_QSTR(MP_QSTR_BLUE_LED), MP_ROM_PTR(&pin_GPIO4) }, @@ -79,18 +78,23 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_BUTTON_K), MP_ROM_PTR(&pin_GPIO14) }, { MP_ROM_QSTR(MP_QSTR_BUTTON_L), MP_ROM_PTR(&pin_GPIO15) }, - { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO16) }, - { MP_ROM_QSTR(MP_QSTR_TFT_LITE), MP_ROM_PTR(&pin_GPIO17) }, { 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_TFT_CS), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_CARD_CS), MP_ROM_PTR(&pin_GPIO21) }, - { MP_ROM_QSTR(MP_QSTR_TFT_DC), MP_ROM_PTR(&pin_GPIO22) }, - { MP_ROM_QSTR(MP_QSTR_TFT_RESET), MP_ROM_PTR(&pin_GPIO23) }, + + { MP_OBJ_NEW_QSTR(MP_QSTR_TFT_DC), MP_ROM_PTR(CIRCUITPY_BOARD_TFT_DC) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_TFT_CS), MP_ROM_PTR(CIRCUITPY_BOARD_TFT_CS) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_TFT_RESET), MP_ROM_PTR(CIRCUITPY_BOARD_TFT_RESET) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_TFT_BACKLIGHT), MP_ROM_PTR(CIRCUITPY_BOARD_TFT_BACKLIGHT) }, + { MP_ROM_QSTR(MP_QSTR_TFT_LITE), MP_ROM_PTR(CIRCUITPY_BOARD_TFT_BACKLIGHT) }, + { MP_ROM_QSTR(MP_QSTR_WHITE_LED), MP_ROM_PTR(&pin_GPIO28) }, { MP_ROM_QSTR(MP_QSTR_DISPLAY), MP_ROM_PTR(&displays[0].display)}, + { 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/raspberrypi/boards/heiafr_picomo_v2/board.c b/ports/raspberrypi/boards/heiafr_picomo_v2/board.c index 8c60341489f..7dbed5d41ca 100644 --- a/ports/raspberrypi/boards/heiafr_picomo_v2/board.c +++ b/ports/raspberrypi/boards/heiafr_picomo_v2/board.c @@ -46,14 +46,13 @@ void board_init(void) { fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_GPIO18, &pin_GPIO19, NULL, false); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_GPIO16, // TFT_DC Command or data - &pin_GPIO17, // TFT_CS Chip select - NULL, // TFT_RST Reset + MP_OBJ_FROM_PTR(&pin_GPIO16), // TFT_DC Command or data + MP_OBJ_FROM_PTR(&pin_GPIO17), // TFT_CS Chip select + mp_const_none, // TFT_RST Reset 62500000, // Baudrate 0, // Polarity 0); // Phase diff --git a/ports/raspberrypi/boards/heiafr_picomo_v3/board.c b/ports/raspberrypi/boards/heiafr_picomo_v3/board.c index 8c60341489f..7dbed5d41ca 100644 --- a/ports/raspberrypi/boards/heiafr_picomo_v3/board.c +++ b/ports/raspberrypi/boards/heiafr_picomo_v3/board.c @@ -46,14 +46,13 @@ void board_init(void) { fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_GPIO18, &pin_GPIO19, NULL, false); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_GPIO16, // TFT_DC Command or data - &pin_GPIO17, // TFT_CS Chip select - NULL, // TFT_RST Reset + MP_OBJ_FROM_PTR(&pin_GPIO16), // TFT_DC Command or data + MP_OBJ_FROM_PTR(&pin_GPIO17), // TFT_CS Chip select + mp_const_none, // TFT_RST Reset 62500000, // Baudrate 0, // Polarity 0); // Phase diff --git a/ports/raspberrypi/boards/ide_tudelft_realpicoexpander/board.c b/ports/raspberrypi/boards/ide_tudelft_realpicoexpander/board.c new file mode 100644 index 00000000000..299f32da04f --- /dev/null +++ b/ports/raspberrypi/boards/ide_tudelft_realpicoexpander/board.c @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Jeff Epler for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/raspberrypi/boards/ide_tudelft_realpicoexpander/link.ld b/ports/raspberrypi/boards/ide_tudelft_realpicoexpander/link.ld new file mode 100644 index 00000000000..d4f5109f4b6 --- /dev/null +++ b/ports/raspberrypi/boards/ide_tudelft_realpicoexpander/link.ld @@ -0,0 +1 @@ +firmware_size = 1536k; diff --git a/ports/raspberrypi/boards/ide_tudelft_realpicoexpander/mpconfigboard.h b/ports/raspberrypi/boards/ide_tudelft_realpicoexpander/mpconfigboard.h new file mode 100644 index 00000000000..554747cdd4a --- /dev/null +++ b/ports/raspberrypi/boards/ide_tudelft_realpicoexpander/mpconfigboard.h @@ -0,0 +1,20 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Jeff Epler for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#define MICROPY_HW_BOARD_NAME "IDE-TUDelft RealPicoExpander" +#define MICROPY_HW_MCU_NAME "rp2350a" + +#define CIRCUITPY_DIGITALIO_HAVE_INVALID_PULL (1) +#define CIRCUITPY_DIGITALIO_HAVE_INVALID_DRIVE_MODE (1) + +#define MICROPY_HW_LED_STATUS (&pin_CYW0) +#define MICROPY_HW_NEOPIXEL (&pin_GPIO2) + +#define CIRCUITPY_BOARD_I2C (1) +#define CIRCUITPY_BOARD_I2C_PIN {{.scl = &pin_GPIO5, .sda = &pin_GPIO4}} + +#define CIRCUITPY_BOARD_SPI (1) +#define CIRCUITPY_BOARD_SPI_PIN {{.clock = &pin_GPIO18, .mosi = &pin_GPIO19, .miso = &pin_GPIO16}} diff --git a/ports/raspberrypi/boards/ide_tudelft_realpicoexpander/mpconfigboard.mk b/ports/raspberrypi/boards/ide_tudelft_realpicoexpander/mpconfigboard.mk new file mode 100644 index 00000000000..d08742d0ef8 --- /dev/null +++ b/ports/raspberrypi/boards/ide_tudelft_realpicoexpander/mpconfigboard.mk @@ -0,0 +1,38 @@ +USB_VID = 0x1209 +USB_PID = 0xC1C1 +USB_PRODUCT = "IDE-TUDelft RealPicoExpander" +USB_MANUFACTURER = "StudioLab TUDelft" + +CHIP_VARIANT = RP2350 +CHIP_PACKAGE = A +CHIP_FAMILY = rp2 + +EXTERNAL_FLASH_DEVICES = "W25Q64JVxQ" + +CIRCUITPY__EVE = 1 + +CIRCUITPY_CYW43 = 1 +CIRCUITPY_SSL = 1 +CIRCUITPY_HASHLIB = 1 +CIRCUITPY_WEB_WORKFLOW = 1 +CIRCUITPY_MDNS = 1 +CIRCUITPY_SOCKETPOOL = 1 +CIRCUITPY_WIFI = 1 + +# GPIO12-19 needed for picodvi, but GPIO15 is used for a button. +CIRCUITPY_PICODVI = 0 + +CFLAGS += \ + -DCYW43_PIN_WL_DYNAMIC=0 \ + -DCYW43_DEFAULT_PIN_WL_HOST_WAKE=24 \ + -DCYW43_DEFAULT_PIN_WL_REG_ON=23 \ + -DCYW43_DEFAULT_PIN_WL_CLOCK=29 \ + -DCYW43_DEFAULT_PIN_WL_DATA_IN=24 \ + -DCYW43_DEFAULT_PIN_WL_DATA_OUT=24 \ + -DCYW43_DEFAULT_PIN_WL_CS=25 \ + -DCYW43_WL_GPIO_COUNT=3 \ + -DCYW43_WL_GPIO_LED_PIN=0 \ + -DCYW43_PIO_CLOCK_DIV_INT=3 + +# Must be accompanied by a linker script change +CFLAGS += -DCIRCUITPY_FIRMWARE_SIZE='(1536 * 1024)' diff --git a/ports/raspberrypi/boards/ide_tudelft_realpicoexpander/pico-sdk-configboard.h b/ports/raspberrypi/boards/ide_tudelft_realpicoexpander/pico-sdk-configboard.h new file mode 100644 index 00000000000..945802d1ab1 --- /dev/null +++ b/ports/raspberrypi/boards/ide_tudelft_realpicoexpander/pico-sdk-configboard.h @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Jeff Epler for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Put board-specific pico-sdk definitions here. This file must exist. diff --git a/ports/raspberrypi/boards/ide_tudelft_realpicoexpander/pins.c b/ports/raspberrypi/boards/ide_tudelft_realpicoexpander/pins.c new file mode 100644 index 00000000000..708aa24a376 --- /dev/null +++ b/ports/raspberrypi/boards/ide_tudelft_realpicoexpander/pins.c @@ -0,0 +1,117 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Jeff Epler for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_GP0), MP_ROM_PTR(&pin_GPIO0) }, + + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_GP1), MP_ROM_PTR(&pin_GPIO1) }, + + { MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_GP2), MP_ROM_PTR(&pin_GPIO2) }, + + { MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_GPIO3) }, + { 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_D4), 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_D5), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_GP5), MP_ROM_PTR(&pin_GPIO5) }, + + { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_GP6), MP_ROM_PTR(&pin_GPIO6) }, + + { MP_ROM_QSTR(MP_QSTR_D7), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_GP7), MP_ROM_PTR(&pin_GPIO7) }, + + { MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_GP8), MP_ROM_PTR(&pin_GPIO8) }, + + { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_GP9), MP_ROM_PTR(&pin_GPIO9) }, + + { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_GP10), MP_ROM_PTR(&pin_GPIO10) }, + + { MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_GP11), MP_ROM_PTR(&pin_GPIO11) }, + + { MP_ROM_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_GP12), MP_ROM_PTR(&pin_GPIO12) }, + + { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_GP13), MP_ROM_PTR(&pin_GPIO13) }, + + { MP_ROM_QSTR(MP_QSTR_D14), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_GP14), MP_ROM_PTR(&pin_GPIO14) }, + + { MP_ROM_QSTR(MP_QSTR_BTN), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_GP15), MP_ROM_PTR(&pin_GPIO15) }, + + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_D16), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_GP16), MP_ROM_PTR(&pin_GPIO16) }, + + { MP_ROM_QSTR(MP_QSTR_CS), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_D17), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_GP17), MP_ROM_PTR(&pin_GPIO17) }, + + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_D18), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_GP18), MP_ROM_PTR(&pin_GPIO18) }, + + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_D19), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_GP19), MP_ROM_PTR(&pin_GPIO19) }, + + { MP_ROM_QSTR(MP_QSTR_D20), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_GP20), MP_ROM_PTR(&pin_GPIO20) }, + + { MP_ROM_QSTR(MP_QSTR_D21), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_GP21), MP_ROM_PTR(&pin_GPIO21) }, + + { MP_ROM_QSTR(MP_QSTR_D22), MP_ROM_PTR(&pin_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_GP22), MP_ROM_PTR(&pin_GPIO22) }, + + { MP_ROM_QSTR(MP_QSTR_A26), 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_A0), MP_ROM_PTR(&pin_GPIO26) }, + + { MP_ROM_QSTR(MP_QSTR_A27), 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_A1), MP_ROM_PTR(&pin_GPIO27) }, + + { MP_ROM_QSTR(MP_QSTR_A28), 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_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_ROM_QSTR(MP_QSTR_SMPS_MODE), MP_ROM_PTR(&pin_CYW1) }, + + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_CYW0) }, + + { MP_ROM_QSTR(MP_QSTR_VBUS_SENSE), MP_ROM_PTR(&pin_CYW2) }, + + { MP_ROM_QSTR(MP_QSTR_STEMMA_I2C), MP_ROM_PTR(&board_i2c_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_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/raspberrypi/boards/lilygo_t_display_rp2040/board.c b/ports/raspberrypi/boards/lilygo_t_display_rp2040/board.c index 78cc912130e..0f675d8b26a 100644 --- a/ports/raspberrypi/boards/lilygo_t_display_rp2040/board.c +++ b/ports/raspberrypi/boards/lilygo_t_display_rp2040/board.c @@ -56,16 +56,14 @@ static void display_init(void) { NULL, // MISO not connected false); // Not half-duplex - common_hal_busio_spi_never_reset(spi); - bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO1, // DC - &pin_GPIO5, // CS - NULL, // RST (Reset pin tie to 0, do not set here) + MP_OBJ_FROM_PTR(&pin_GPIO1), // DC + MP_OBJ_FROM_PTR(&pin_GPIO5), // CS + mp_const_none, // RST (Reset pin tie to 0, do not set here) 40000000, // baudrate 1, // polarity 0 // phase @@ -105,7 +103,6 @@ static void display_init(void) { 50000 // backlight pwm frequency ); - common_hal_never_reset_pin(&pin_GPIO4); // backlight pin } void board_init(void) { @@ -114,7 +111,6 @@ void board_init(void) { gpio_init(PWR_PIN); gpio_set_dir(PWR_PIN, GPIO_OUT); gpio_put(PWR_PIN, 1); - common_hal_never_reset_pin(&pin_GPIO22); // Display display_init(); diff --git a/ports/raspberrypi/boards/moonyard_equinox/board.c b/ports/raspberrypi/boards/moonyard_equinox/board.c new file mode 100644 index 00000000000..e6a868ab212 --- /dev/null +++ b/ports/raspberrypi/boards/moonyard_equinox/board.c @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/raspberrypi/boards/moonyard_equinox/mpconfigboard.h b/ports/raspberrypi/boards/moonyard_equinox/mpconfigboard.h new file mode 100644 index 00000000000..1cebe84664d --- /dev/null +++ b/ports/raspberrypi/boards/moonyard_equinox/mpconfigboard.h @@ -0,0 +1,17 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#define MICROPY_HW_BOARD_NAME "MoonYard Equinox" +#define MICROPY_HW_MCU_NAME "rp2350b" + +#define MICROPY_HW_LED_STATUS (&pin_GPIO18) + +#define DEFAULT_SPI_BUS_SCK (&pin_GPIO14) +#define DEFAULT_SPI_BUS_MOSI (&pin_GPIO11) +#define DEFAULT_SPI_BUS_MISO (&pin_GPIO12) + +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO4) +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO5) diff --git a/ports/raspberrypi/boards/moonyard_equinox/mpconfigboard.mk b/ports/raspberrypi/boards/moonyard_equinox/mpconfigboard.mk new file mode 100644 index 00000000000..b44285007ff --- /dev/null +++ b/ports/raspberrypi/boards/moonyard_equinox/mpconfigboard.mk @@ -0,0 +1,13 @@ +USB_VID = 0x2E8A +USB_PID = 0x115F +USB_PRODUCT = "Equinox" +USB_MANUFACTURER = "MoonYard" + +CHIP_VARIANT = RP2350 +CHIP_PACKAGE = B +CHIP_FAMILY = rp2 + +EXTERNAL_FLASH_DEVICES = "W25Q128JVxQ" + +CIRCUITPY_PICODVI = 0 +CIRCUITPY_USB_HOST = 0 diff --git a/ports/raspberrypi/boards/moonyard_equinox/pico-sdk-configboard.h b/ports/raspberrypi/boards/moonyard_equinox/pico-sdk-configboard.h new file mode 100644 index 00000000000..fe85bc18439 --- /dev/null +++ b/ports/raspberrypi/boards/moonyard_equinox/pico-sdk-configboard.h @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#define PICO_XOSC_STARTUP_DELAY_MULTIPLIER 64 diff --git a/ports/raspberrypi/boards/moonyard_equinox/pins.c b/ports/raspberrypi/boards/moonyard_equinox/pins.c new file mode 100644 index 00000000000..61bf74e351a --- /dev/null +++ b/ports/raspberrypi/boards/moonyard_equinox/pins.c @@ -0,0 +1,64 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + { MP_ROM_QSTR(MP_QSTR_BMP585_SDX), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_BMP585_SCX), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_BMI_INT1), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_BMI1088_INT1), MP_ROM_PTR(&pin_GPIO7) }, + + { MP_ROM_QSTR(MP_QSTR_LLCC68_DIO1), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_BMI1088_INT3), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_SPI_MOSI), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_SPI_MISO), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_BME680_CS), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_SPI_SCK), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_H3LIS331DLTR_CS), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_D16), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_D17), MP_ROM_PTR(&pin_GPIO17) }, + + { MP_ROM_QSTR(MP_QSTR_LED_1), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_INPUT_1), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_INPUT_2), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_H3LIS331DLTR_INT1), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_LLCC68_RESET), MP_ROM_PTR(&pin_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_LLCC68_CS), MP_ROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_LLCC68_BUSY), MP_ROM_PTR(&pin_GPIO24) }, + + { MP_ROM_QSTR(MP_QSTR_GPS_TIMEPULSE), MP_ROM_PTR(&pin_GPIO25) }, + { MP_ROM_QSTR(MP_QSTR_GPS_RESET), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_GPS_EXTINT), MP_ROM_PTR(&pin_GPIO27) }, + + { MP_ROM_QSTR(MP_QSTR_SERVO_1), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_SERVO_2), MP_ROM_PTR(&pin_GPIO29) }, + { MP_ROM_QSTR(MP_QSTR_SERVO_3), MP_ROM_PTR(&pin_GPIO30) }, + { MP_ROM_QSTR(MP_QSTR_SERVO_4), MP_ROM_PTR(&pin_GPIO31) }, + + { MP_ROM_QSTR(MP_QSTR_CHUTE_1_EN), MP_ROM_PTR(&pin_GPIO32) }, + { MP_ROM_QSTR(MP_QSTR_CHUTE_2_EN), MP_ROM_PTR(&pin_GPIO33) }, + { MP_ROM_QSTR(MP_QSTR_CHUTES_DIAG), MP_ROM_PTR(&pin_GPIO34) }, + + { MP_ROM_QSTR(MP_QSTR_ESP32_EN), MP_ROM_PTR(&pin_GPIO35) }, + { MP_ROM_QSTR(MP_QSTR_ESP32_TX), MP_ROM_PTR(&pin_GPIO44) }, + { MP_ROM_QSTR(MP_QSTR_ESP32_RX), MP_ROM_PTR(&pin_GPIO45) }, + + { MP_ROM_QSTR(MP_QSTR_GPS_TX), MP_ROM_PTR(&pin_GPIO36) }, + { MP_ROM_QSTR(MP_QSTR_GPS_RX), MP_ROM_PTR(&pin_GPIO37) }, + + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO38) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO39) }, + + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO41) }, + { MP_ROM_QSTR(MP_QSTR_CHUTE_2_MON), MP_ROM_PTR(&pin_GPIO42) }, + { MP_ROM_QSTR(MP_QSTR_TOUCH), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_CHUTE_1_MON), MP_ROM_PTR(&pin_GPIO46) }, + { MP_ROM_QSTR(MP_QSTR_BATT_SENSE), MP_ROM_PTR(&pin_GPIO47) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/raspberrypi/boards/mtm_computer/board.c b/ports/raspberrypi/boards/mtm_computer/board.c index e6a868ab212..4fec0cd5b8b 100644 --- a/ports/raspberrypi/boards/mtm_computer/board.c +++ b/ports/raspberrypi/boards/mtm_computer/board.c @@ -5,5 +5,36 @@ // SPDX-License-Identifier: MIT #include "supervisor/board.h" +#include "shared-bindings/mcp4822/MCP4822.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "peripherals/pins.h" +#include "py/runtime.h" +// board.DAC() — factory function that constructs an mcp4822.MCP4822 with +// the MTM Workshop Computer's DAC pins (GP18=SCK, GP19=SDI, GP21=CS). + +static mp_obj_t board_dac_singleton = MP_OBJ_NULL; + +static mp_obj_t board_dac_factory(void) { + if (board_dac_singleton == MP_OBJ_NULL) { + mcp4822_mcp4822_obj_t *dac = mp_obj_malloc_with_finaliser( + mcp4822_mcp4822_obj_t, &mcp4822_mcp4822_type); + common_hal_mcp4822_mcp4822_construct( + dac, + &pin_GPIO18, // clock (SCK) + &pin_GPIO19, // mosi (SDI) + &pin_GPIO21, // cs + 1); // gain 1x + board_dac_singleton = MP_OBJ_FROM_PTR(dac); + } + return board_dac_singleton; +} +MP_DEFINE_CONST_FUN_OBJ_0(board_dac_obj, board_dac_factory); + +void board_deinit(void) { + if (board_dac_singleton != MP_OBJ_NULL) { + common_hal_mcp4822_mcp4822_deinit(MP_OBJ_TO_PTR(board_dac_singleton)); + board_dac_singleton = MP_OBJ_NULL; + } +} // Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/raspberrypi/boards/mtm_computer/mpconfigboard.mk b/ports/raspberrypi/boards/mtm_computer/mpconfigboard.mk index 718c393d168..45c99711d72 100644 --- a/ports/raspberrypi/boards/mtm_computer/mpconfigboard.mk +++ b/ports/raspberrypi/boards/mtm_computer/mpconfigboard.mk @@ -11,3 +11,4 @@ EXTERNAL_FLASH_DEVICES = "W25Q16JVxQ" CIRCUITPY_AUDIOEFFECTS = 1 CIRCUITPY_IMAGECAPTURE = 0 CIRCUITPY_PICODVI = 0 +CIRCUITPY_MCP4822 = 1 diff --git a/ports/raspberrypi/boards/mtm_computer/pins.c b/ports/raspberrypi/boards/mtm_computer/pins.c index 69878182331..ffdf2687702 100644 --- a/ports/raspberrypi/boards/mtm_computer/pins.c +++ b/ports/raspberrypi/boards/mtm_computer/pins.c @@ -6,6 +6,8 @@ #include "shared-bindings/board/__init__.h" +extern const mp_obj_fun_builtin_fixed_t board_dac_obj; + static const mp_rom_map_elem_t board_module_globals_table[] = { CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS @@ -21,7 +23,6 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_PULSE_2_IN), MP_ROM_PTR(&pin_GPIO3) }, { MP_ROM_QSTR(MP_QSTR_GP3), MP_ROM_PTR(&pin_GPIO3) }, - { MP_ROM_QSTR(MP_QSTR_NORM_PROBE), MP_ROM_PTR(&pin_GPIO4) }, { MP_ROM_QSTR(MP_QSTR_GP4), MP_ROM_PTR(&pin_GPIO4) }, @@ -105,6 +106,9 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO29) }, { MP_ROM_QSTR(MP_QSTR_GP29), MP_ROM_PTR(&pin_GPIO29) }, + // Factory function: dac = board.DAC() returns a configured mcp4822.MCP4822 + { MP_ROM_QSTR(MP_QSTR_DAC), MP_ROM_PTR(&board_dac_obj) }, + // { MP_ROM_QSTR(MP_QSTR_EEPROM_I2C), MP_ROM_PTR(&board_i2c_obj) }, }; MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/raspberrypi/boards/orpheus_pico/board.c b/ports/raspberrypi/boards/orpheus_pico/board.c new file mode 100644 index 00000000000..e6a868ab212 --- /dev/null +++ b/ports/raspberrypi/boards/orpheus_pico/board.c @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/raspberrypi/boards/orpheus_pico/mpconfigboard.h b/ports/raspberrypi/boards/orpheus_pico/mpconfigboard.h new file mode 100644 index 00000000000..8c6269771fd --- /dev/null +++ b/ports/raspberrypi/boards/orpheus_pico/mpconfigboard.h @@ -0,0 +1,13 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#define MICROPY_HW_BOARD_NAME "Orpheus Pico" +#define MICROPY_HW_MCU_NAME "rp2040" + +#define MICROPY_HW_NEOPIXEL (&pin_GPIO25) +#define MICROPY_HW_LED_STATUS (&pin_GPIO23) diff --git a/ports/raspberrypi/boards/orpheus_pico/mpconfigboard.mk b/ports/raspberrypi/boards/orpheus_pico/mpconfigboard.mk new file mode 100644 index 00000000000..9b570211c8f --- /dev/null +++ b/ports/raspberrypi/boards/orpheus_pico/mpconfigboard.mk @@ -0,0 +1,11 @@ +USB_VID = 0x2E8A +USB_PID = 0x10D0 +USB_PRODUCT = "Orpheus Pico" +USB_MANUFACTURER = "Hack Club" + +CHIP_VARIANT = RP2040 +CHIP_FAMILY = rp2 + +EXTERNAL_FLASH_DEVICES = "W25Q64JVxQ" + +CIRCUITPY__EVE = 1 diff --git a/ports/raspberrypi/boards/orpheus_pico/pico-sdk-configboard.h b/ports/raspberrypi/boards/orpheus_pico/pico-sdk-configboard.h new file mode 100644 index 00000000000..110195b7794 --- /dev/null +++ b/ports/raspberrypi/boards/orpheus_pico/pico-sdk-configboard.h @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Put board-specific pico-sdk definitions here. This file must exist. diff --git a/ports/raspberrypi/boards/orpheus_pico/pins.c b/ports/raspberrypi/boards/orpheus_pico/pins.c new file mode 100644 index 00000000000..24d656c18c9 --- /dev/null +++ b/ports/raspberrypi/boards/orpheus_pico/pins.c @@ -0,0 +1,57 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { 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_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_LED), MP_ROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_GP23), MP_ROM_PTR(&pin_GPIO23) }, + + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO24) }, + { MP_ROM_QSTR(MP_QSTR_GP24), MP_ROM_PTR(&pin_GPIO24) }, + + { MP_ROM_QSTR(MP_QSTR_BUTTON), 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_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/raspberrypi/boards/pajenicko_picopad/board.c b/ports/raspberrypi/boards/pajenicko_picopad/board.c index 0ca13b3ec2e..acf893f40c5 100644 --- a/ports/raspberrypi/boards/pajenicko_picopad/board.c +++ b/ports/raspberrypi/boards/pajenicko_picopad/board.c @@ -46,15 +46,15 @@ void board_init(void) { fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_GPIO18, &pin_GPIO19, NULL, false); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_GPIO17, // TFT_DC Command or data - &pin_GPIO21, // TFT_CS Chip select - &pin_GPIO20, // TFT_RST Reset - 60000000, // Baudrate + MP_OBJ_FROM_PTR(&pin_GPIO17), // TFT_DC Command or data + MP_OBJ_FROM_PTR(&pin_GPIO21), // TFT_CS Chip select + MP_OBJ_FROM_PTR(&pin_GPIO20), // TFT_RST Reset + 62500000, // Baudrate: exactly clk_peri/2 (125MHz/2). Requesting 60MHz makes the + // PL022 divider round DOWN to 31.25MHz - half the display bandwidth. 0, // Polarity 0); // Phase diff --git a/ports/raspberrypi/boards/pajenicko_picopad/link.ld b/ports/raspberrypi/boards/pajenicko_picopad/link.ld index e814bead4c5..d4f5109f4b6 100644 --- a/ports/raspberrypi/boards/pajenicko_picopad/link.ld +++ b/ports/raspberrypi/boards/pajenicko_picopad/link.ld @@ -1 +1 @@ -firmware_size = 1532k; +firmware_size = 1536k; diff --git a/ports/raspberrypi/boards/pajenicko_picopad/mpconfigboard.mk b/ports/raspberrypi/boards/pajenicko_picopad/mpconfigboard.mk index 764e41d4d91..43c81f55bc9 100644 --- a/ports/raspberrypi/boards/pajenicko_picopad/mpconfigboard.mk +++ b/ports/raspberrypi/boards/pajenicko_picopad/mpconfigboard.mk @@ -9,11 +9,20 @@ CHIP_FAMILY = rp2 EXTERNAL_FLASH_DEVICES = "W25Q16JVxQ" +CIRCUITPY_USB_HOST = 0 + CIRCUITPY_KEYPAD = 1 CIRCUITPY_STAGE = 1 +CIRCUITPY_PICOGAME = 1 +CIRCUITPY_PICOGAME_RGB444 = 1 CIRCUITPY_AUDIOIO = 1 +CIRCUITPY_AUDIOEFFECTS = 0 -CIRCUITPY__EVE = 1 +# Peripherals this board physically lacks: no FT8xx EVE display, no camera for the +# qrio QR *decoder* (QR generation = pure-Python adafruit_miniqr, unaffected), and no +# DVI/HDMI connector. Dropping them frees flash for the picogame engine. +CIRCUITPY__EVE = 0 +CIRCUITPY_QRIO = 0 CIRCUITPY_CYW43 = 1 CIRCUITPY_SSL = 1 @@ -23,7 +32,6 @@ CIRCUITPY_MDNS = 1 CIRCUITPY_SOCKETPOOL = 1 CIRCUITPY_WIFI = 1 -CIRCUITPY_PICODVI = 1 # Pimoroni PicoSystem peripherals are compatible, we can use of existing ugame.py FROZEN_MPY_DIRS += $(TOP)/frozen/circuitpython-stage/picosystem diff --git a/ports/raspberrypi/boards/pcbcupid_glyph_mini_2040/board.c b/ports/raspberrypi/boards/pcbcupid_glyph_mini_2040/board.c new file mode 100644 index 00000000000..1ce23b26459 --- /dev/null +++ b/ports/raspberrypi/boards/pcbcupid_glyph_mini_2040/board.c @@ -0,0 +1 @@ +#include "shared-bindings/board/__init__.h" diff --git a/ports/raspberrypi/boards/pcbcupid_glyph_mini_2040/mpconfigboard.h b/ports/raspberrypi/boards/pcbcupid_glyph_mini_2040/mpconfigboard.h new file mode 100644 index 00000000000..75deccbc8ed --- /dev/null +++ b/ports/raspberrypi/boards/pcbcupid_glyph_mini_2040/mpconfigboard.h @@ -0,0 +1,12 @@ +#ifndef MICROPY_INCLUDED_RASPBERRYPI_BOARDS_PCBCUPID_Glyph_Mini_2040 +#define MICROPY_INCLUDED_RASPBERRYPI_BOARDS_PCBCUPID_Glyph_Mini_2040 + +#define MICROPY_HW_BOARD_NAME "PCBCupid Glyph Mini 2040" +#define MICROPY_HW_MCU_NAME "rp2040" + +#define FLASH_SIZE (8 * 1024 * 1024) +#define CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_SIZE (7 * 1024 * 1024) + +#define MICROPY_HW_LED_STATUS (&pin_GPIO16) + +#endif diff --git a/ports/raspberrypi/boards/pcbcupid_glyph_mini_2040/mpconfigboard.mk b/ports/raspberrypi/boards/pcbcupid_glyph_mini_2040/mpconfigboard.mk new file mode 100644 index 00000000000..415aecd6395 --- /dev/null +++ b/ports/raspberrypi/boards/pcbcupid_glyph_mini_2040/mpconfigboard.mk @@ -0,0 +1,9 @@ +USB_VID = 0x2E8A +USB_PID = 0x1123 +USB_PRODUCT = "Glyph Mini 2040" +USB_MANUFACTURER = "PCBCupid" + +CHIP_VARIANT = RP2040 +CHIP_FAMILY = rp2 + +EXTERNAL_FLASH_DEVICES = "W25Q64JVxQ" diff --git a/ports/raspberrypi/boards/pcbcupid_glyph_mini_2040/pico-sdk-configboard.h b/ports/raspberrypi/boards/pcbcupid_glyph_mini_2040/pico-sdk-configboard.h new file mode 100644 index 00000000000..110195b7794 --- /dev/null +++ b/ports/raspberrypi/boards/pcbcupid_glyph_mini_2040/pico-sdk-configboard.h @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Put board-specific pico-sdk definitions here. This file must exist. diff --git a/ports/raspberrypi/boards/pcbcupid_glyph_mini_2040/pins.c b/ports/raspberrypi/boards/pcbcupid_glyph_mini_2040/pins.c new file mode 100644 index 00000000000..d2719b1ebea --- /dev/null +++ b/ports/raspberrypi/boards/pcbcupid_glyph_mini_2040/pins.c @@ -0,0 +1,37 @@ +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { 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_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_GP26), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_GP27), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_GP28), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_GP29), MP_ROM_PTR(&pin_GPIO29) }, + + { 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_TX), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO16) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/raspberrypi/boards/pimoroni_badger2040/board.c b/ports/raspberrypi/boards/pimoroni_badger2040/board.c index 457bff33b44..31b503df82c 100644 --- a/ports/raspberrypi/boards/pimoroni_badger2040/board.c +++ b/ports/raspberrypi/boards/pimoroni_badger2040/board.c @@ -250,22 +250,18 @@ void board_init(void) { common_hal_digitalio_digitalinout_construct(&enable_pin_obj, &pin_GPIO10); common_hal_digitalio_digitalinout_switch_to_output(&enable_pin_obj, true, DRIVE_MODE_PUSH_PULL); - // Never reset - common_hal_digitalio_digitalinout_never_reset(&enable_pin_obj); - // Set up the SPI object used to control the display fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_GPIO18, &pin_GPIO19, &pin_GPIO16, false); - common_hal_busio_spi_never_reset(spi); // Set up the DisplayIO pin object bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_GPIO20, // EPD_DC Command or data - &pin_GPIO17, // EPD_CS Chip select - &pin_GPIO21, // EPD_RST Reset + MP_OBJ_FROM_PTR(&pin_GPIO20), // EPD_DC Command or data + MP_OBJ_FROM_PTR(&pin_GPIO17), // EPD_CS Chip select + MP_OBJ_FROM_PTR(&pin_GPIO21), // EPD_RST Reset 1200000, // Baudrate 0, // Polarity 0); // Phase @@ -273,38 +269,27 @@ void board_init(void) { // Set up the DisplayIO epaper object epaperdisplay_epaperdisplay_obj_t *display = &allocate_display()->epaper_display; display->base.type = &epaperdisplay_epaperdisplay_type; - common_hal_epaperdisplay_epaperdisplay_construct( - display, - bus, - display_start_sequence, sizeof(display_start_sequence), - 0, // start up time - display_stop_sequence, sizeof(display_stop_sequence), - 296, // width - 128, // height - 160, // ram_width - 296, // ram_height - 0, // colstart - 0, // rowstart - 270, // rotation - NO_COMMAND, // set_column_window_command - NO_COMMAND, // set_row_window_command - NO_COMMAND, // set_current_column_command - NO_COMMAND, // set_current_row_command - DTM2, // write_black_ram_command - true, // black_bits_inverted - DTM1, // write_color_ram_command - false, // color_bits_inverted - 0x000000, // highlight_color - refresh_sequence, sizeof(refresh_sequence), // refresh_display_command - 1.0, // refresh_time - &pin_GPIO26, // busy_pin - false, // busy_state - 2.0, // seconds_per_frame - false, // always_toggle_chip_select - false, // grayscale - false, // acep - false, // two_byte_sequence_length - false); // address_little_endian + + epaperdisplay_construct_args_t args = EPAPERDISPLAY_CONSTRUCT_ARGS_DEFAULTS; + args.bus = bus; + args.start_sequence = display_start_sequence; + args.start_sequence_len = sizeof(display_start_sequence); + args.stop_sequence = display_stop_sequence; + args.stop_sequence_len = sizeof(display_stop_sequence); + args.width = 296; + args.height = 128; + args.ram_width = 160; + args.ram_height = 296; + args.rotation = 270; + args.write_black_ram_command = DTM2; + args.black_bits_inverted = true; + args.write_color_ram_command = DTM1; + args.refresh_sequence = refresh_sequence; + args.refresh_sequence_len = sizeof(refresh_sequence); + args.refresh_time = 1.0; + args.busy_pin = &pin_GPIO26; + args.seconds_per_frame = 2.0; + common_hal_epaperdisplay_epaperdisplay_construct(display, &args); } void board_deinit(void) { diff --git a/ports/raspberrypi/boards/pimoroni_badger2040w/board.c b/ports/raspberrypi/boards/pimoroni_badger2040w/board.c index 30c05273b94..af1066d69ca 100644 --- a/ports/raspberrypi/boards/pimoroni_badger2040w/board.c +++ b/ports/raspberrypi/boards/pimoroni_badger2040w/board.c @@ -251,21 +251,17 @@ void board_init(void) { common_hal_digitalio_digitalinout_construct(&enable_pin_obj, &pin_GPIO10); common_hal_digitalio_digitalinout_switch_to_output(&enable_pin_obj, true, DRIVE_MODE_PUSH_PULL); - // Never reset - common_hal_digitalio_digitalinout_never_reset(&enable_pin_obj); - // Set up the SPI object used to control the display busio_spi_obj_t *spi = common_hal_board_create_spi(0); - common_hal_busio_spi_never_reset(spi); // Set up the DisplayIO pin object fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_GPIO20, // EPD_DC Command or data - &pin_GPIO17, // EPD_CS Chip select - &pin_GPIO21, // EPD_RST Reset + MP_OBJ_FROM_PTR(&pin_GPIO20), // EPD_DC Command or data + MP_OBJ_FROM_PTR(&pin_GPIO17), // EPD_CS Chip select + MP_OBJ_FROM_PTR(&pin_GPIO21), // EPD_RST Reset 1200000, // Baudrate 0, // Polarity 0); // Phase @@ -273,38 +269,27 @@ void board_init(void) { // Set up the DisplayIO epaper object epaperdisplay_epaperdisplay_obj_t *display = &allocate_display()->epaper_display; display->base.type = &epaperdisplay_epaperdisplay_type; - common_hal_epaperdisplay_epaperdisplay_construct( - display, - bus, - display_start_sequence, sizeof(display_start_sequence), - 0, // start up time - display_stop_sequence, sizeof(display_stop_sequence), - 296, // width - 128, // height - 160, // ram_width - 296, // ram_height - 0, // colstart - 0, // rowstart - 270, // rotation - NO_COMMAND, // set_column_window_command - NO_COMMAND, // set_row_window_command - NO_COMMAND, // set_current_column_command - NO_COMMAND, // set_current_row_command - DTM2, // write_black_ram_command - true, // black_bits_inverted - DTM1, // write_color_ram_command - false, // color_bits_inverted - 0x000000, // highlight_color - refresh_sequence, sizeof(refresh_sequence), // refresh_display_command - 1.0, // refresh_time - &pin_GPIO26, // busy_pin - false, // busy_state - 2.0, // seconds_per_frame - false, // always_toggle_chip_select - false, // grayscale - false, // acep - false, // two_byte_sequence_length - false); // address_little_endian + + epaperdisplay_construct_args_t args = EPAPERDISPLAY_CONSTRUCT_ARGS_DEFAULTS; + args.bus = bus; + args.start_sequence = display_start_sequence; + args.start_sequence_len = sizeof(display_start_sequence); + args.stop_sequence = display_stop_sequence; + args.stop_sequence_len = sizeof(display_stop_sequence); + args.width = 296; + args.height = 128; + args.ram_width = 160; + args.ram_height = 296; + args.rotation = 270; + args.write_black_ram_command = DTM2; + args.black_bits_inverted = true; + args.write_color_ram_command = DTM1; + args.refresh_sequence = refresh_sequence; + args.refresh_sequence_len = sizeof(refresh_sequence); + args.refresh_time = 1.0; + args.busy_pin = &pin_GPIO26; + args.seconds_per_frame = 2.0; + common_hal_epaperdisplay_epaperdisplay_construct(display, &args); } void board_deinit(void) { diff --git a/ports/raspberrypi/boards/pimoroni_badger2040w/link.ld b/ports/raspberrypi/boards/pimoroni_badger2040w/link.ld index e814bead4c5..d4f5109f4b6 100644 --- a/ports/raspberrypi/boards/pimoroni_badger2040w/link.ld +++ b/ports/raspberrypi/boards/pimoroni_badger2040w/link.ld @@ -1 +1 @@ -firmware_size = 1532k; +firmware_size = 1536k; diff --git a/ports/raspberrypi/boards/pimoroni_badger2350/badger2350-shared.h b/ports/raspberrypi/boards/pimoroni_badger2350/badger2350-shared.h new file mode 100644 index 00000000000..4cc67efd4df --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_badger2350/badger2350-shared.h @@ -0,0 +1,15 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" +#include "shared-bindings/digitalio/DigitalInOut.h" + +extern digitalio_digitalinout_obj_t i2c_power_en_pin_obj; +extern const mp_obj_fun_builtin_fixed_t set_update_speed_obj; +extern const mp_obj_fun_builtin_fixed_t get_reset_state_obj; +extern const mp_obj_fun_builtin_fixed_t on_reset_pressed_obj; diff --git a/ports/raspberrypi/boards/pimoroni_badger2350/board.c b/ports/raspberrypi/boards/pimoroni_badger2350/board.c new file mode 100644 index 00000000000..38bf5be366a --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_badger2350/board.c @@ -0,0 +1,246 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Bob Abeles +// +// SPDX-License-Identifier: MIT + +#include "py/obj.h" + +#include "mpconfigboard.h" +#include "shared-bindings/busio/SPI.h" +#include "shared-bindings/fourwire/FourWire.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/digitalio/DigitalInOut.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-module/displayio/__init__.h" +#include "supervisor/shared/board.h" +#include "supervisor/board.h" +#include "badger2350-shared.h" + +#include "hardware/gpio.h" +#include "hardware/structs/iobank0.h" + +digitalio_digitalinout_obj_t i2c_power_en_pin_obj; +static volatile uint32_t reset_button_state = 0; + +// Forward declaration to satisfy -Wmissing-prototypes +static void preinit_button_state(void) __attribute__((constructor(101))); + + +// pin definitions +// Button pin definitions for Badger2350 +#define SW_A_PIN 7 +#define SW_B_PIN 9 +#define SW_C_PIN 10 +#define SW_DOWN_PIN 6 +#define SW_UP_PIN 11 + +static const uint8_t _sw_pin_nrs[] = { + SW_A_PIN, SW_B_PIN, SW_C_PIN, SW_DOWN_PIN, SW_UP_PIN +}; + +// Mask of all front button pins +#define SW_MASK ((1 << SW_A_PIN) | (1 << SW_B_PIN) | (1 << SW_C_PIN) | \ + (1 << SW_DOWN_PIN) | (1 << SW_UP_PIN)) + +// This function runs BEFORE main() via constructor attribute! +// This is the key to fast button state detection. +// Priority 101 = runs very early + +static void preinit_button_state(void) { + // Configure button pins as inputs with pull-downs using direct register access + // This is faster than SDK functions and works before full init + + for (size_t i = 0; i < sizeof(_sw_pin_nrs); i++) { + uint8_t pin_nr = _sw_pin_nrs[i]; + // Set as input + sio_hw->gpio_oe_clr = 1u << pin_nr; + // enable pull-ups + pads_bank0_hw->io[pin_nr] = PADS_BANK0_GPIO0_IE_BITS | + PADS_BANK0_GPIO0_PUE_BITS; + // Set GPIO function + iobank0_hw->io[pin_nr].ctrl = 5; // SIO function + } + + // Small delay for pins to settle (just a few cycles) + for (volatile int i = 0; i < 100; i++) { + __asm volatile ("nop"); + } + + // Capture button states NOW - before anything else runs + reset_button_state = ~sio_hw->gpio_in & SW_MASK; +} + +static mp_obj_t _get_reset_state(void) { + return mp_obj_new_int(reset_button_state); +} +MP_DEFINE_CONST_FUN_OBJ_0(get_reset_state_obj, _get_reset_state); + +static mp_obj_t _on_reset_pressed(mp_obj_t pin_in) { + mcu_pin_obj_t *pin = MP_OBJ_TO_PTR(pin_in); + return mp_obj_new_bool( + (reset_button_state & (1 << pin->number)) != 0); +} +MP_DEFINE_CONST_FUN_OBJ_1(on_reset_pressed_obj, _on_reset_pressed); + +// The display uses an SSD1680 control chip. +uint8_t _start_sequence[] = { + 0x12, 0x80, 0x00, 0x14, // soft reset and wait 20ms + 0x11, 0x00, 0x01, 0x03, // Ram data entry mode + 0x3c, 0x00, 0x01, 0x03, // border color + 0x2c, 0x00, 0x01, 0x20, // Set vcom voltage (Pimoroni: 0x28) + 0x03, 0x00, 0x01, 0x17, // Set gate voltage + 0x04, 0x00, 0x03, 0x41, 0xae, 0x32, // Set source voltage + 0x4e, 0x00, 0x01, 0x00, // ram x count + 0x4f, 0x00, 0x02, 0x00, 0x00, // ram y count + 0x01, 0x00, 0x03, 0x07, 0x01, 0x00, // set display size + 0x3f, 0x00, 0x01, 0x22, // EOPT normal (0x22) + 0x32, 0x00, 0x99, // Update waveforms + + // LUT-START: offset 48 + // VS rows: only L0-L3 are swapped relative to GxEPD2_4G; + // L1 and L2 stay in place. + // Reason: CircuitPython luma maps 0 L0, 64-127 L2, 128-191 L1, 255 L3. + // GxEPD2 uses L0=white-driver, L3=black-driver + // (opposite of CircuitPython for extremes). + // GxEPD2 L1=lighter-gray, L2=darker-gray + // CircuitPython: L1=mid-bright, L2=mid-dark — same ordering. + // So: swap only L0-L3 (polarity); + // L1 and L2 keep their GxEPD2 positions (gradient preserved). + // + // Note: 0x48: VSH1/GND/VSL/GND alternating — better DC balance than + // 0x60 (VSH1/VSL/GND/GND) + + // 5x12 = 60 bytes + // VS L0 (darkest/black) == GxEPD2 L3 + 0x20, 0x48, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // VS L1 (mid-light) == GxEPD2 L1 (luma 128-191 lighter) + 0x08, 0x48, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // VS L2 (mid-dark) == GxEPD2 L2 (luma 64-127 darker) + 0x02, 0x48, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // VS L3 (lightest/white) == GxEPD2 L0 + 0x40, 0x48, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + // VS L4 VCOM + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + + // 12x7 = 84 (144 total) + // Timing groups — Good Display reference timing + // offset 108: Group0: 10+25 / 3+8 frames activation + 0x0A, 0x19, 0x00, 0x03, 0x08, 0x00, 0x00, + // offset 115: Group1: 20+1 / 20+1 frames, RP=0 repeats + 0x14, 0x01, 0x00, 0x14, 0x01, 0x00, 0x00, + // offset 122: Group2: 10+3 / 8+25 frames (mirror of G0) + 0x0A, 0x03, 0x00, 0x08, 0x19, 0x00, 0x00, + + // offset 129 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Group3 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Group4 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Group5 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Group6 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Group7 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Group8 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Group9 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Group10 + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // Group11 + + // 12x0.5 = 6, (150 total) + 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, // FR + // 3x1 = 3, (153 total) + 0x00, 0x00, 0x00, // XON + // LUT-END: offset 201 + 0x22, 0x00, 0x01, 0xc7, // display update mode +}; + +const uint8_t _stop_sequence[] = { + 0x10, 0x80, 0x01, 0x01, 0x64 // DSM deep sleep mode 1 +}; + +const uint8_t _refresh_sequence[] = { + 0x20, 0x00, 0x00 // ADUS +}; + +// Change update speed. + +// Pimoroni sets the repeat-count for Group0-Group2 and uses: +// speed=0 == slow ... 3 == fast and calculates the LUT repeat count as 3-speed + +// This implementation only changes the repeat-count in the LUT-timing of Group1. +// Default is SPEED=3. + +#define RP_OFFSET 121 + +static mp_obj_t _set_update_speed(mp_obj_t speed_in) { + mp_int_t speed = mp_obj_get_int(speed_in); + uint8_t count = (uint8_t)3 - (uint8_t)(speed & 3); + _start_sequence[RP_OFFSET] = count; + return mp_const_none; +} + +MP_DEFINE_CONST_FUN_OBJ_1(set_update_speed_obj, _set_update_speed); + +void board_init(void) { + // Drive the I2C_POWER_EN pin high + i2c_power_en_pin_obj.base.type = &digitalio_digitalinout_type; + common_hal_digitalio_digitalinout_construct( + &i2c_power_en_pin_obj, &pin_GPIO27); + common_hal_digitalio_digitalinout_switch_to_output( + &i2c_power_en_pin_obj, true, DRIVE_MODE_PUSH_PULL); + + fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; + busio_spi_obj_t *spi = &bus->inline_bus; + common_hal_busio_spi_construct(spi, &pin_GPIO18, &pin_GPIO19, NULL, false); + + bus->base.type = &fourwire_fourwire_type; + common_hal_fourwire_fourwire_construct(bus, + spi, + MP_OBJ_FROM_PTR(&pin_GPIO20), // EPD_DC Command or data + MP_OBJ_FROM_PTR(&pin_GPIO17), // EPD_CS Chip select + MP_OBJ_FROM_PTR(&pin_GPIO21), // EPD_RST Reset + 12000000, // Baudrate + 0, // Polarity + 0); // Phase + + // create and configure display + epaperdisplay_epaperdisplay_obj_t *display = &allocate_display()->epaper_display; + display->base.type = &epaperdisplay_epaperdisplay_type; + + epaperdisplay_construct_args_t args = EPAPERDISPLAY_CONSTRUCT_ARGS_DEFAULTS; + args.bus = bus; + args.start_sequence = _start_sequence; + args.start_sequence_len = sizeof(_start_sequence); + args.stop_sequence = _stop_sequence; + args.stop_sequence_len = sizeof(_stop_sequence); + args.width = 264; + args.height = 176; + args.ram_width = 250; + args.ram_height = 296; + args.rotation = 270; + args.set_column_window_command = 0x44; + args.set_row_window_command = 0x45; + args.set_current_column_command = 0x4e; + args.set_current_row_command = 0x4f; + args.write_black_ram_command = 0x24; + args.write_color_ram_command = 0x26; + args.refresh_sequence = _refresh_sequence; + args.refresh_sequence_len = sizeof(_refresh_sequence); + args.refresh_time = 1.0; + args.busy_pin = &pin_GPIO16; + args.busy_state = true; + args.seconds_per_frame = 3.0; + args.grayscale = true; + args.two_byte_sequence_length = true; + args.address_little_endian = true; + common_hal_epaperdisplay_epaperdisplay_construct(display, &args); +} + +void board_deinit(void) { + epaperdisplay_epaperdisplay_obj_t *display = &displays[0].epaper_display; + if (display->base.type == &epaperdisplay_epaperdisplay_type) { + while (common_hal_epaperdisplay_epaperdisplay_get_busy(display)) { + RUN_BACKGROUND_TASKS; + } + } + common_hal_displayio_release_displays(); +} + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/raspberrypi/boards/pimoroni_badger2350/link.ld b/ports/raspberrypi/boards/pimoroni_badger2350/link.ld new file mode 100644 index 00000000000..d4f5109f4b6 --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_badger2350/link.ld @@ -0,0 +1 @@ +firmware_size = 1536k; diff --git a/ports/raspberrypi/boards/pimoroni_badger2350/mpconfigboard.h b/ports/raspberrypi/boards/pimoroni_badger2350/mpconfigboard.h new file mode 100644 index 00000000000..6cffd190ad6 --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_badger2350/mpconfigboard.h @@ -0,0 +1,21 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Bernhard Bablok +// +// SPDX-License-Identifier: MIT + +#define MICROPY_HW_BOARD_NAME "Pimoroni Badger 2350" +#define MICROPY_HW_MCU_NAME "rp2350a" + +#define CIRCUITPY_DIGITALIO_HAVE_INVALID_PULL (1) +#define CIRCUITPY_DIGITALIO_HAVE_INVALID_DRIVE_MODE (1) + +#define MICROPY_HW_LED_STATUS (&pin_GPIO0) + +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO4) +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO5) + +#define DEFAULT_SPI_BUS_SCK (&pin_GPIO18) +#define DEFAULT_SPI_BUS_MOSI (&pin_GPIO19) + +#define CIRCUITPY_PSRAM_CHIP_SELECT (&pin_GPIO8) diff --git a/ports/raspberrypi/boards/pimoroni_badger2350/mpconfigboard.mk b/ports/raspberrypi/boards/pimoroni_badger2350/mpconfigboard.mk new file mode 100644 index 00000000000..9ef0ee0f07d --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_badger2350/mpconfigboard.mk @@ -0,0 +1,42 @@ +USB_VID = 0x2E8A +USB_PID = 0x1100 +USB_PRODUCT = "Pimoroni Badger 2350" +USB_MANUFACTURER = "Pimoroni" + +CHIP_VARIANT = RP2350 +CHIP_PACKAGE = A +CHIP_FAMILY = rp2 + +EXTERNAL_FLASH_DEVICES = "W25Q128JVxQ" + +CIRCUITPY__EVE = 1 + +CIRCUITPY_CYW43 = 1 +CIRCUITPY_SSL = 1 +CIRCUITPY_HASHLIB = 1 +CIRCUITPY_WEB_WORKFLOW = 1 +CIRCUITPY_MDNS = 1 +CIRCUITPY_SOCKETPOOL = 1 +CIRCUITPY_WIFI = 1 + +# GPIO12-19 needed for picodvi, but many are not available. +CIRCUITPY_PICODVI = 0 + +# PIO clock divider set to 2 (default), consider changing if TM2 gSPI +# becomes unreliable. +CFLAGS += \ + -DCYW43_PIN_WL_DYNAMIC=0 \ + -DCYW43_DEFAULT_PIN_WL_HOST_WAKE=24 \ + -DCYW43_DEFAULT_PIN_WL_REG_ON=23 \ + -DCYW43_DEFAULT_PIN_WL_CLOCK=29 \ + -DCYW43_DEFAULT_PIN_WL_DATA_IN=24 \ + -DCYW43_DEFAULT_PIN_WL_DATA_OUT=24 \ + -DCYW43_DEFAULT_PIN_WL_CS=25 \ + -DCYW43_WL_GPIO_COUNT=3 \ + -DCYW43_PIO_CLOCK_DIV_INT=2 \ + -DCYW43_PIO_CLOCK_DIV_FRAC=0 +# Must be accompanied by a linker script change +CFLAGS += -DCIRCUITPY_FIRMWARE_SIZE='(1536 * 1024)' + +FROZEN_MPY_DIRS += $(TOP)/frozen/circuitpython-pcf85063a +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_Register diff --git a/ports/raspberrypi/boards/pimoroni_badger2350/pico-sdk-configboard.h b/ports/raspberrypi/boards/pimoroni_badger2350/pico-sdk-configboard.h new file mode 100644 index 00000000000..42e0612bf8b --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_badger2350/pico-sdk-configboard.h @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Bob Abeles +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Put board-specific pico-sdk definitions here. This file must exist. diff --git a/ports/raspberrypi/boards/pimoroni_badger2350/pins.c b/ports/raspberrypi/boards/pimoroni_badger2350/pins.c new file mode 100644 index 00000000000..1a66961e68f --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_badger2350/pins.c @@ -0,0 +1,135 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Bob Abeles +// +// SPDX-License-Identifier: MIT + +#include "py/objtuple.h" +#include "shared-bindings/board/__init__.h" +#include "shared-module/displayio/__init__.h" +#include "badger2350-shared.h" + + +// LUT manipulation +static const mp_rom_map_elem_t lut_update_table[] = { + { MP_ROM_QSTR(MP_QSTR_SET_UPDATE_SPEED), (mp_obj_t)&set_update_speed_obj }, + { MP_ROM_QSTR(MP_QSTR_SPEED_SLOW), MP_ROM_INT(0) }, + { MP_ROM_QSTR(MP_QSTR_SPEED_FAST), MP_ROM_INT(1) }, + { MP_ROM_QSTR(MP_QSTR_SPEED_FASTER), MP_ROM_INT(2) }, + { MP_ROM_QSTR(MP_QSTR_SPEED_FASTEST), MP_ROM_INT(3) }, +}; +MP_DEFINE_CONST_DICT(lut_update_dict, lut_update_table); + +const mp_obj_module_t display_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&lut_update_dict, +}; + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { MP_ROM_QSTR(MP_QSTR_display), MP_ROM_PTR(&display_module) }, + + { MP_ROM_QSTR(MP_QSTR_GP0), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_LED0), MP_ROM_PTR(&pin_GPIO0) }, + + { MP_ROM_QSTR(MP_QSTR_GP1), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_LED1), MP_ROM_PTR(&pin_GPIO1) }, + + { MP_ROM_QSTR(MP_QSTR_GP2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_LED2), MP_ROM_PTR(&pin_GPIO2) }, + + { MP_ROM_QSTR(MP_QSTR_GP3), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_LED3), MP_ROM_PTR(&pin_GPIO3) }, + + { MP_ROM_QSTR(MP_QSTR_GP4), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO4) }, + + { MP_ROM_QSTR(MP_QSTR_GP5), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO5) }, + + { MP_ROM_QSTR(MP_QSTR_GP6), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_SW_DOWN), MP_ROM_PTR(&pin_GPIO6) }, + + { MP_ROM_QSTR(MP_QSTR_GP7), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_SW_A), MP_ROM_PTR(&pin_GPIO7) }, + + // GP8 is reserved for PSRAM chip select + + { MP_ROM_QSTR(MP_QSTR_GP9), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_SW_B), MP_ROM_PTR(&pin_GPIO9) }, + + { MP_ROM_QSTR(MP_QSTR_GP10), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_SW_C), MP_ROM_PTR(&pin_GPIO10) }, + + { MP_ROM_QSTR(MP_QSTR_GP11), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_SW_UP), MP_ROM_PTR(&pin_GPIO11) }, + + { MP_ROM_QSTR(MP_QSTR_GP12), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_VBUS_SENSE), MP_ROM_PTR(&pin_GPIO12) }, + + { MP_ROM_QSTR(MP_QSTR_GP13), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_RTC_ALARM), MP_ROM_PTR(&pin_GPIO13) }, + + { MP_ROM_QSTR(MP_QSTR_GP14), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_SW_RESET), MP_ROM_PTR(&pin_GPIO14) }, + + { MP_ROM_QSTR(MP_QSTR_GP15), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_SW_INT), MP_ROM_PTR(&pin_GPIO15) }, + + { MP_ROM_QSTR(MP_QSTR_GP16), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_INKY_BUSY), MP_ROM_PTR(&pin_GPIO16) }, + + { MP_ROM_QSTR(MP_QSTR_GP17), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_INKY_CS), MP_ROM_PTR(&pin_GPIO17) }, + + { MP_ROM_QSTR(MP_QSTR_GP18), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_GPIO18) }, + + { MP_ROM_QSTR(MP_QSTR_GP19), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO19) }, + + { MP_ROM_QSTR(MP_QSTR_GP20), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_INKY_DC), MP_ROM_PTR(&pin_GPIO20) }, + + { MP_ROM_QSTR(MP_QSTR_GP21), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_INKY_RST), MP_ROM_PTR(&pin_GPIO21) }, + + { MP_ROM_QSTR(MP_QSTR_GP22), MP_ROM_PTR(&pin_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_SW_HOME), MP_ROM_PTR(&pin_GPIO22) }, + + // GP23, GP24, GP25, and GP29 are reserved for RM2 gSPI + + { MP_ROM_QSTR(MP_QSTR_GP26), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_VBAT_SENSE), MP_ROM_PTR(&pin_GPIO26) }, + + // GP27 is the used for I2C power-enable, driven high by board.c + { MP_ROM_QSTR(MP_QSTR_I2C_POWER_EN), MP_ROM_PTR(&i2c_power_en_pin_obj) }, + + { MP_ROM_QSTR(MP_QSTR_GP28), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_SENSE_1V1), MP_ROM_PTR(&pin_GPIO28) }, + + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, + { MP_ROM_QSTR(MP_QSTR_STEMMA_I2C), MP_ROM_PTR(&board_i2c_obj) }, + + { MP_ROM_QSTR(MP_QSTR_SPI), MP_ROM_PTR(&board_spi_obj) }, + + // Pins accessed though the RM2 module (CYW43439) + // CYW0, CYW1 is unconnected + { MP_ROM_QSTR(MP_QSTR_CHARGE_STAT), MP_ROM_PTR(&pin_CYW2) }, + + { MP_ROM_QSTR(MP_QSTR_DISPLAY), MP_ROM_PTR(&displays[0].epaper_display)}, + + // button-state on reset + // Use `board.RESET_STATE()` to query the state of all buttons at reset. + // To detect individual key-presses, `board.ON_RESET_PRESSED()` + // is simpler. + { MP_ROM_QSTR(MP_QSTR_RESET_STATE), (mp_obj_t)&get_reset_state_obj }, + + // Use `board.ON_RESET_PRESSED(board.SW_A)` to check if `SW_A` was pressed + // during reset. + { MP_ROM_QSTR(MP_QSTR_ON_RESET_PRESSED), (mp_obj_t)&on_reset_pressed_obj }, + +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/raspberrypi/boards/pimoroni_explorer2350/board.c b/ports/raspberrypi/boards/pimoroni_explorer2350/board.c new file mode 100644 index 00000000000..d0c6d9a57ce --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_explorer2350/board.c @@ -0,0 +1,145 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" +#include "mpconfigboard.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/paralleldisplaybus/ParallelBus.h" +#include "shared-module/displayio/__init__.h" +#include "shared-module/displayio/mipi_constants.h" +#include "hardware/gpio.h" + +// Display pins from Pimoroni Explorer parallel bus: {cs=27, dc=28, wr=30, rd=31, d0=32, bl=26} +#define LCD_BACKLIGHT_PIN 26 +#define LCD_CS_PIN 27 +#define LCD_DC_PIN 28 +#define LCD_WR_PIN 30 +#define LCD_RD_PIN 31 +#define LCD_D0_PIN 32 // Data pins are GPIO32-39 (8 consecutive pins) + +#define DELAY 0x80 + +// ST7789V display init sequence for 320x240 parallel bus +// Based on Pimoroni's pimoroni-pico ST7789 driver configuration +uint8_t display_init_sequence[] = { + // Software reset + 0x01, 0 | DELAY, 150, + // Sleep out + 0x11, 0 | DELAY, 255, + // Tearing effect line on (frame sync) + 0x35, 1, 0x00, + // COLMOD: 16-bit color (5-6-5 RGB) + 0x3A, 1, 0x55, + // Porch control (PORCTRL) + 0xB2, 5, 0x0C, 0x0C, 0x00, 0x33, 0x33, + // Gate control (GCTRL) - VGH=13.26V, VGL=-10.43V + 0xB7, 1, 0x35, + // VCOM setting (VCOMS) + 0xBB, 1, 0x1F, + // LCM control (LCMCTRL) + 0xC0, 1, 0x2C, + // VDV and VRH command enable (VDVVRHEN) + 0xC2, 1, 0x01, + // VRH set (VRHS) + 0xC3, 1, 0x12, + // VDV set (VDVS) + 0xC4, 1, 0x20, + // Frame rate control (FRCTRL2) + 0xC6, 1, 0x0F, + // Power control 1 (PWCTRL1) + 0xD0, 2, 0xA4, 0xA1, + // RAM control (RAMCTRL) - for proper endianness + 0xB0, 2, 0x00, 0xC0, + // Positive gamma correction + 0xE0, 14, 0xD0, 0x08, 0x11, 0x08, 0x0C, 0x15, 0x39, 0x33, 0x50, 0x36, 0x13, 0x14, 0x29, 0x2D, + // Negative gamma correction + 0xE1, 14, 0xD0, 0x08, 0x10, 0x08, 0x06, 0x06, 0x39, 0x44, 0x51, 0x0B, 0x16, 0x14, 0x2F, 0x31, + // Inversion on + 0x21, 0, + // Normal display mode on + 0x13, 0 | DELAY, 10, + // MADCTL: MX=0, MY=1, MV=1, ML=1 (COL_ORDER | SWAP_XY | SCAN_ORDER) = 0x70 + // This configures the 320x240 display in landscape orientation + 0x36, 1, 0x70, + // Display on + 0x29, 0 | DELAY, 100, +}; + +static void display_init(void) { + paralleldisplaybus_parallelbus_obj_t *bus = &allocate_display_bus()->parallel_bus; + bus->base.type = ¶lleldisplaybus_parallelbus_type; + + common_hal_paralleldisplaybus_parallelbus_construct(bus, + &pin_GPIO32, // Data0 (D0) - data pins are sequential GPIO32-39 + &pin_GPIO28, // Command/Data (DC) + &pin_GPIO27, // Chip select (CS) + &pin_GPIO30, // Write (WR) + &pin_GPIO31, // Read (RD) + NULL, // Reset (directly connected to board reset) + 15000000); // Frequency - ST7789 min clock cycle ~66ns = ~15MHz + + busdisplay_busdisplay_obj_t *display = &allocate_display()->display; + display->base.type = &busdisplay_busdisplay_type; + + common_hal_busdisplay_busdisplay_construct(display, + bus, + 320, // Width + 240, // Height + 0, // column start + 0, // row start + 0, // rotation + 16, // Color depth + false, // grayscale + false, // pixels_in_byte_share_row + 1, // bytes per cell + false, // reverse_pixels_in_byte + 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 + display_init_sequence, + sizeof(display_init_sequence), + &pin_GPIO26, // Backlight pin (BL) + NO_BRIGHTNESS_COMMAND, + 1.0f, // brightness + false, // single_byte_bounds + false, // data_as_commands + true, // auto_refresh + 60, // native_frames_per_second + true, // backlight_on_high + false, // SH1107_addressing + 50000 // backlight pwm frequency + ); +} + +void board_init(void) { + // Ensure backlight is on before display init + board_reset_pin_number(LCD_BACKLIGHT_PIN); + display_init(); +} + +// Prevent the backlight pin from being reset, keeping display visible across soft resets +bool board_reset_pin_number(uint8_t pin_number) { + if (pin_number == LCD_BACKLIGHT_PIN) { + // Keep backlight on - set high output without glitching + gpio_put(pin_number, 1); + gpio_set_dir(pin_number, GPIO_OUT); + gpio_set_function(pin_number, GPIO_FUNC_SIO); + return true; + } + return false; +} + +void reset_board(void) { + // Keep backlight on during reset + board_reset_pin_number(LCD_BACKLIGHT_PIN); +} + +void board_deinit(void) { + // Backlight will be handled by board_reset_pin_number +} + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/raspberrypi/boards/pimoroni_explorer2350/mpconfigboard.h b/ports/raspberrypi/boards/pimoroni_explorer2350/mpconfigboard.h new file mode 100644 index 00000000000..dd269aa6b84 --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_explorer2350/mpconfigboard.h @@ -0,0 +1,18 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#define MICROPY_HW_BOARD_NAME "Pimoroni Explorer" +#define MICROPY_HW_MCU_NAME "rp2350b" + +#define MICROPY_HW_LED_STATUS (&pin_GPIO25) + +#define CIRCUITPY_BOARD_I2C (1) +#define CIRCUITPY_BOARD_I2C_PIN {{.scl = &pin_GPIO21, .sda = &pin_GPIO20}} + +#define DEFAULT_UART_BUS_RX (&pin_GPIO1) +#define DEFAULT_UART_BUS_TX (&pin_GPIO0) diff --git a/ports/raspberrypi/boards/pimoroni_explorer2350/mpconfigboard.mk b/ports/raspberrypi/boards/pimoroni_explorer2350/mpconfigboard.mk new file mode 100644 index 00000000000..4409dbf57df --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_explorer2350/mpconfigboard.mk @@ -0,0 +1,13 @@ +USB_VID = 0x2E8A +USB_PID = 0x10C0 +USB_PRODUCT = "Explorer" +USB_MANUFACTURER = "Pimoroni" + +CHIP_VARIANT = RP2350 +CHIP_PACKAGE = B +CHIP_FAMILY = rp2 + +EXTERNAL_FLASH_DEVICES = "W25Q128JVxQ" + +# GPIO12-19 needed for picodvi, but several are not available. +CIRCUITPY_PICODVI = 0 diff --git a/ports/raspberrypi/boards/pimoroni_explorer2350/pico-sdk-configboard.h b/ports/raspberrypi/boards/pimoroni_explorer2350/pico-sdk-configboard.h new file mode 100644 index 00000000000..66b57dfd13d --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_explorer2350/pico-sdk-configboard.h @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// Put board-specific pico-sdk definitions here. This file must exist. diff --git a/ports/raspberrypi/boards/pimoroni_explorer2350/pins.c b/ports/raspberrypi/boards/pimoroni_explorer2350/pins.c new file mode 100644 index 00000000000..8154a43de00 --- /dev/null +++ b/ports/raspberrypi/boards/pimoroni_explorer2350/pins.c @@ -0,0 +1,124 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" +#include "shared-module/displayio/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + // User GPIOs (accent connector) + { 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_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) }, + + // Servo pins + { MP_ROM_QSTR(MP_QSTR_SERVO1), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_GP9), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_SERVO2), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_GP8), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_SERVO3), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_GP7), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_SERVO4), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_GP6), MP_ROM_PTR(&pin_GPIO6) }, + + // Audio + { MP_ROM_QSTR(MP_QSTR_AUDIO), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_GP12), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_AMP_EN), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_GP13), MP_ROM_PTR(&pin_GPIO13) }, + + // Buttons + { MP_ROM_QSTR(MP_QSTR_SW_C), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_GP14), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_SW_B), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_GP15), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_SW_A), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_GP16), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_SW_X), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_GP17), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_SW_Y), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_GP18), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_SW_Z), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_GP19), MP_ROM_PTR(&pin_GPIO19) }, + + // I2C + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_GP20), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_GP21), MP_ROM_PTR(&pin_GPIO21) }, + + // User button + { MP_ROM_QSTR(MP_QSTR_SW_USER), MP_ROM_PTR(&pin_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_GP22), MP_ROM_PTR(&pin_GPIO22) }, + + // LED? + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO25) }, + { MP_ROM_QSTR(MP_QSTR_GP25), MP_ROM_PTR(&pin_GPIO25) }, + + // Display parallel bus pins (ST7789V 320x240) + // Pins from Pimoroni: {cs=27, dc=28, wr=30, rd=31, d0=32, bl=26} + { MP_ROM_QSTR(MP_QSTR_LCD_BL), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_GP26), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_LCD_CS), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_GP27), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_LCD_DC), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_GP28), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_GP29), MP_ROM_PTR(&pin_GPIO29) }, + { MP_ROM_QSTR(MP_QSTR_LCD_WR), MP_ROM_PTR(&pin_GPIO30) }, + { MP_ROM_QSTR(MP_QSTR_GP30), MP_ROM_PTR(&pin_GPIO30) }, + { MP_ROM_QSTR(MP_QSTR_LCD_RD), MP_ROM_PTR(&pin_GPIO31) }, + { MP_ROM_QSTR(MP_QSTR_GP31), MP_ROM_PTR(&pin_GPIO31) }, + { MP_ROM_QSTR(MP_QSTR_LCD_D0), MP_ROM_PTR(&pin_GPIO32) }, + { MP_ROM_QSTR(MP_QSTR_GP32), MP_ROM_PTR(&pin_GPIO32) }, + { MP_ROM_QSTR(MP_QSTR_LCD_D1), MP_ROM_PTR(&pin_GPIO33) }, + { MP_ROM_QSTR(MP_QSTR_GP33), MP_ROM_PTR(&pin_GPIO33) }, + { MP_ROM_QSTR(MP_QSTR_LCD_D2), MP_ROM_PTR(&pin_GPIO34) }, + { MP_ROM_QSTR(MP_QSTR_GP34), MP_ROM_PTR(&pin_GPIO34) }, + { MP_ROM_QSTR(MP_QSTR_LCD_D3), MP_ROM_PTR(&pin_GPIO35) }, + { MP_ROM_QSTR(MP_QSTR_GP35), MP_ROM_PTR(&pin_GPIO35) }, + { MP_ROM_QSTR(MP_QSTR_LCD_D4), MP_ROM_PTR(&pin_GPIO36) }, + { MP_ROM_QSTR(MP_QSTR_GP36), MP_ROM_PTR(&pin_GPIO36) }, + { MP_ROM_QSTR(MP_QSTR_LCD_D5), MP_ROM_PTR(&pin_GPIO37) }, + { MP_ROM_QSTR(MP_QSTR_GP37), MP_ROM_PTR(&pin_GPIO37) }, + { MP_ROM_QSTR(MP_QSTR_LCD_D6), MP_ROM_PTR(&pin_GPIO38) }, + { MP_ROM_QSTR(MP_QSTR_GP38), MP_ROM_PTR(&pin_GPIO38) }, + { MP_ROM_QSTR(MP_QSTR_LCD_D7), MP_ROM_PTR(&pin_GPIO39) }, + { MP_ROM_QSTR(MP_QSTR_GP39), MP_ROM_PTR(&pin_GPIO39) }, + + // ADC pins (RP2350B extended GPIOs) + { MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_ADC0), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_GP40), MP_ROM_PTR(&pin_GPIO40) }, + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO41) }, + { MP_ROM_QSTR(MP_QSTR_ADC1), MP_ROM_PTR(&pin_GPIO41) }, + { MP_ROM_QSTR(MP_QSTR_GP41), MP_ROM_PTR(&pin_GPIO41) }, + { MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO42) }, + { MP_ROM_QSTR(MP_QSTR_ADC2), MP_ROM_PTR(&pin_GPIO42) }, + { MP_ROM_QSTR(MP_QSTR_GP42), MP_ROM_PTR(&pin_GPIO42) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_ADC3), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_GP43), MP_ROM_PTR(&pin_GPIO43) }, + { MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_GPIO44) }, + { MP_ROM_QSTR(MP_QSTR_ADC4), MP_ROM_PTR(&pin_GPIO44) }, + { MP_ROM_QSTR(MP_QSTR_GP44), MP_ROM_PTR(&pin_GPIO44) }, + { MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_GPIO45) }, + { MP_ROM_QSTR(MP_QSTR_ADC5), MP_ROM_PTR(&pin_GPIO45) }, + { MP_ROM_QSTR(MP_QSTR_GP45), MP_ROM_PTR(&pin_GPIO45) }, + + // I2C object + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, + { MP_ROM_QSTR(MP_QSTR_STEMMA_I2C), MP_ROM_PTR(&board_i2c_obj) }, + + // Display object + { 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/raspberrypi/boards/pimoroni_inky_frame_5_7/board.c b/ports/raspberrypi/boards/pimoroni_inky_frame_5_7/board.c index 650d307711e..303bbb3150d 100644 --- a/ports/raspberrypi/boards/pimoroni_inky_frame_5_7/board.c +++ b/ports/raspberrypi/boards/pimoroni_inky_frame_5_7/board.c @@ -13,11 +13,84 @@ #include "shared-module/displayio/__init__.h" #include "shared-bindings/board/__init__.h" #include "supervisor/shared/board.h" +#include "py/mphal.h" #include "inky-shared.h" #define DELAY 0x80 digitalio_digitalinout_obj_t enable_pin_obj; +static volatile uint32_t reset_button_state = 0; + +// This function runs BEFORE main() via constructor attribute! +// This is the key to early and fast SR state readout. +// Priority 101 = runs very early +// Forward declaration to satisfy -Wmissing-prototypes +static void pre_init(void) __attribute__((constructor(101))); + +#define SR_PIN_MASK ((0b1 << 8) | (0b1 << 9) | (0b1 << 10)) +#define SR_PIN_DIR ((0b1 << 8) | (0b1 << 9)) +#define SR_PIN_VALUE ((0b1 << 9)) +#define SR_CLK (8) +#define SR_DATA (10) +#define ENABLE_3V3_PIN (2) +#define LED_CONN (7) + +// Early init: +// - latch power +// - save state of shift-register +// +// Buttons A-E physically turn on the device, so this is *not* wake +// from deep-sleep. They are wired behind a shift register. +// Save the state of the SR early so we know which button +// was pressed to turn on the device. + +static void pre_init(void) { + // Immediately latch power on + enable_pin_obj.base.type = &digitalio_digitalinout_type; + common_hal_digitalio_digitalinout_construct(&enable_pin_obj, &pin_GPIO2); + common_hal_digitalio_digitalinout_switch_to_output(&enable_pin_obj, + true, DRIVE_MODE_PUSH_PULL); + // save state of shift-register + gpio_init_mask(SR_PIN_MASK); + gpio_set_dir_masked(SR_PIN_MASK, SR_PIN_DIR); + gpio_put_masked(SR_PIN_MASK, SR_PIN_VALUE); + uint8_t state = 0u; + for (uint8_t i = 0u; i < 8; i++) { + mp_hal_delay_us(1); // reduce clockout frequency + gpio_put(SR_CLK, true); + if (gpio_get(SR_DATA)) { + state |= (0b1 << i); + } + gpio_put(SR_CLK, false); + } + reset_button_state = state; + + // Turn on LED_CONN so the user knows it is ok to release the button. + // The LED is only on for a short time, since it is reset from board_init. + gpio_init(LED_CONN); + gpio_put(LED_CONN, true); + gpio_set_dir(LED_CONN, GPIO_OUT); +} + +static mp_obj_t _get_reset_state(void) { + return mp_obj_new_int(reset_button_state); +} +MP_DEFINE_CONST_FUN_OBJ_0(get_reset_state_obj, _get_reset_state); + +static mp_obj_t _on_reset_pressed(mp_obj_t in) { + uint8_t bit_number = mp_obj_get_int(in); + return mp_obj_new_bool( + (reset_button_state & (1 << bit_number)) != 0); +} +MP_DEFINE_CONST_FUN_OBJ_1(on_reset_pressed_obj, _on_reset_pressed); + + +static mp_obj_t _power_off(void) { + gpio_put(ENABLE_3V3_PIN, false); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_0(power_off_obj, _power_off); + // This is an SPD1656 control chip. The display is a 5.7" ACeP EInk. @@ -45,60 +118,52 @@ const uint8_t refresh_sequence[] = { }; void board_init(void) { - // Drive the EN_3V3 pin high so the board stays awake on battery power - enable_pin_obj.base.type = &digitalio_digitalinout_type; - common_hal_digitalio_digitalinout_construct(&enable_pin_obj, &pin_GPIO2); - common_hal_digitalio_digitalinout_switch_to_output(&enable_pin_obj, true, DRIVE_MODE_PUSH_PULL); + // reset LED_CONN (turned on in pre_init()) + gpio_deinit(LED_CONN); - // Never reset - common_hal_digitalio_digitalinout_never_reset(&enable_pin_obj); + // create bus and display fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = common_hal_board_create_spi(0); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_GPIO28, // EPD_DC Command or data - &pin_GPIO17, // EPD_CS Chip select - &pin_GPIO27, // EPD_RST Reset + MP_OBJ_FROM_PTR(&pin_GPIO28), // EPD_DC Command or data + MP_OBJ_FROM_PTR(&pin_GPIO17), // EPD_CS Chip select + MP_OBJ_FROM_PTR(&pin_GPIO27), // EPD_RST Reset 1000000, // Baudrate 0, // Polarity 0); // Phase epaperdisplay_epaperdisplay_obj_t *display = &allocate_display()->epaper_display; display->base.type = &epaperdisplay_epaperdisplay_type; - common_hal_epaperdisplay_epaperdisplay_construct( - display, - bus, - display_start_sequence, sizeof(display_start_sequence), - 1.0, // start up time - display_stop_sequence, sizeof(display_stop_sequence), - 600, // width - 448, // height - 640, // ram_width - 480, // ram_height - 0, // colstart - 0, // rowstart - 0, // rotation - NO_COMMAND, // set_column_window_command - NO_COMMAND, // set_row_window_command - NO_COMMAND, // set_current_column_command - NO_COMMAND, // set_current_row_command - 0x10, // write_black_ram_command - false, // black_bits_inverted - NO_COMMAND, // write_color_ram_command - false, // color_bits_inverted - 0x000000, // highlight_color - refresh_sequence, sizeof(refresh_sequence), - 28.0, // refresh_time - NULL, // busy_pin - false, // busy_state - 40.0, // seconds_per_frame - false, // always_toggle_chip_select - false, // grayscale - true, // acep - false, // two_byte_sequence_length - false); // address_little_endian + + epaperdisplay_construct_args_t args = EPAPERDISPLAY_CONSTRUCT_ARGS_DEFAULTS; + args.bus = bus; + args.start_sequence = display_start_sequence; + args.start_sequence_len = sizeof(display_start_sequence); + args.start_up_time = 1.0; + args.stop_sequence = display_stop_sequence; + args.stop_sequence_len = sizeof(display_stop_sequence); + args.width = 600; + args.height = 448; + args.ram_width = 640; + args.ram_height = 480; + args.write_black_ram_command = 0x10; + args.refresh_sequence = refresh_sequence; + args.refresh_sequence_len = sizeof(refresh_sequence); + args.refresh_time = 28.0; + args.busy_pin = NULL; + args.seconds_per_frame = 40.0; + args.acep = true; + common_hal_epaperdisplay_epaperdisplay_construct(display, &args); } // Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. + +bool board_reset_pin_number(uint8_t pin_number) { + if (pin_number == ENABLE_3V3_PIN) { + return true; + } + return false; +} diff --git a/ports/raspberrypi/boards/pimoroni_inky_frame_5_7/inky-shared.h b/ports/raspberrypi/boards/pimoroni_inky_frame_5_7/inky-shared.h index c6be0048937..602b0279885 100644 --- a/ports/raspberrypi/boards/pimoroni_inky_frame_5_7/inky-shared.h +++ b/ports/raspberrypi/boards/pimoroni_inky_frame_5_7/inky-shared.h @@ -6,6 +6,10 @@ #pragma once +#include "py/obj.h" #include "shared-bindings/digitalio/DigitalInOut.h" extern digitalio_digitalinout_obj_t enable_pin_obj; +extern const mp_obj_fun_builtin_fixed_t get_reset_state_obj; +extern const mp_obj_fun_builtin_fixed_t power_off_obj; +extern const mp_obj_fun_builtin_fixed_t on_reset_pressed_obj; diff --git a/ports/raspberrypi/boards/pimoroni_inky_frame_5_7/link.ld b/ports/raspberrypi/boards/pimoroni_inky_frame_5_7/link.ld index e814bead4c5..d4f5109f4b6 100644 --- a/ports/raspberrypi/boards/pimoroni_inky_frame_5_7/link.ld +++ b/ports/raspberrypi/boards/pimoroni_inky_frame_5_7/link.ld @@ -1 +1 @@ -firmware_size = 1532k; +firmware_size = 1536k; diff --git a/ports/raspberrypi/boards/pimoroni_inky_frame_5_7/mpconfigboard.h b/ports/raspberrypi/boards/pimoroni_inky_frame_5_7/mpconfigboard.h index d2547cc1615..a8c404c4225 100644 --- a/ports/raspberrypi/boards/pimoroni_inky_frame_5_7/mpconfigboard.h +++ b/ports/raspberrypi/boards/pimoroni_inky_frame_5_7/mpconfigboard.h @@ -14,8 +14,8 @@ #define MICROPY_HW_LED_STATUS (&pin_GPIO6) -#define DEFAULT_I2C_BUS_SCL (&pin_GPIO4) -#define DEFAULT_I2C_BUS_SDA (&pin_GPIO5) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO4) +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO5) #define DEFAULT_UART_BUS_TX (&pin_GPIO0) #define DEFAULT_UART_BUS_RX (&pin_GPIO1) diff --git a/ports/raspberrypi/boards/pimoroni_inky_frame_5_7/mpconfigboard.mk b/ports/raspberrypi/boards/pimoroni_inky_frame_5_7/mpconfigboard.mk index 69b23a72be7..0a56b55a0c1 100644 --- a/ports/raspberrypi/boards/pimoroni_inky_frame_5_7/mpconfigboard.mk +++ b/ports/raspberrypi/boards/pimoroni_inky_frame_5_7/mpconfigboard.mk @@ -36,4 +36,3 @@ CFLAGS += -DCIRCUITPY_FIRMWARE_SIZE='(1536 * 1024)' FROZEN_MPY_DIRS += $(TOP)/frozen/circuitpython-pcf85063a FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_Register -FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_SD diff --git a/ports/raspberrypi/boards/pimoroni_inky_frame_5_7/pins.c b/ports/raspberrypi/boards/pimoroni_inky_frame_5_7/pins.c index 8ff1cad58bf..c89d2c3b9dd 100644 --- a/ports/raspberrypi/boards/pimoroni_inky_frame_5_7/pins.c +++ b/ports/raspberrypi/boards/pimoroni_inky_frame_5_7/pins.c @@ -93,5 +93,18 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_DISPLAY), MP_ROM_PTR(&displays[0].epaper_display)}, { MP_ROM_QSTR(MP_QSTR_ENABLE_DIO), MP_ROM_PTR(&enable_pin_obj)}, // GP2 { MP_ROM_QSTR(MP_QSTR_KEYCODES), MP_ROM_PTR(&board_keycodes_obj)}, + + // turn power off. This only works if running from batteries + { MP_ROM_QSTR(MP_QSTR_POWER_OFF), (mp_obj_t)&power_off_obj }, + + // button-state on reset + // Use `board.RESET_STATE()` to query the state of all buttons at reset. + // To detect individual key-presses, `board.ON_RESET_PRESSED()` + // is simpler. + { MP_ROM_QSTR(MP_QSTR_RESET_STATE), (mp_obj_t)&get_reset_state_obj }, + + // Use `board.ON_RESET_PRESSED(board.KEYCODES.SW_A)` + // to check if `SW_A` was pressed during reset. + { MP_ROM_QSTR(MP_QSTR_ON_RESET_PRESSED), (mp_obj_t)&on_reset_pressed_obj }, }; MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/raspberrypi/boards/pimoroni_inky_frame_7_3/board.c b/ports/raspberrypi/boards/pimoroni_inky_frame_7_3/board.c index a24c91e546d..0214492339b 100644 --- a/ports/raspberrypi/boards/pimoroni_inky_frame_7_3/board.c +++ b/ports/raspberrypi/boards/pimoroni_inky_frame_7_3/board.c @@ -11,19 +11,86 @@ #include "shared-bindings/busio/SPI.h" #include "shared-bindings/fourwire/FourWire.h" #include "shared-bindings/microcontroller/Pin.h" -#include "shared-bindings/time/__init__.h" #include "shared-module/displayio/__init__.h" #include "supervisor/shared/board.h" +#include "py/mphal.h" +#include "inky-shared.h" -#define DELAY 0x80 +digitalio_digitalinout_obj_t enable_pin_obj; +static volatile uint32_t reset_button_state = 0; + +// This function runs BEFORE main() via constructor attribute! +// This is the key to early and fast SR state readout. +// Priority 101 = runs very early +// Forward declaration to satisfy -Wmissing-prototypes +static void pre_init(void) __attribute__((constructor(101))); + +#define SR_PIN_MASK ((0b1 << 8) | (0b1 << 9) | (0b1 << 10)) +#define SR_PIN_DIR ((0b1 << 8) | (0b1 << 9)) +#define SR_PIN_VALUE ((0b1 << 9)) +#define SR_CLK (8) +#define SR_DATA (10) +#define ENABLE_3V3_PIN (2) +#define LED_CONN (7) + +// Early init: +// - latch power +// - save state of shift-register +// +// Buttons A-E physically turn on the device, so this is *not* wake +// from deep-sleep. They are wired behind a shift register. +// Save the state of the SR early so we know which button +// was pressed to turn on the device. -// This is a 7.3" ACeP EInk. +static void pre_init(void) { + // Immediately latch power on + enable_pin_obj.base.type = &digitalio_digitalinout_type; + common_hal_digitalio_digitalinout_construct(&enable_pin_obj, &pin_GPIO2); + common_hal_digitalio_digitalinout_switch_to_output(&enable_pin_obj, + true, DRIVE_MODE_PUSH_PULL); + // save state of shift-register + gpio_init_mask(SR_PIN_MASK); + gpio_set_dir_masked(SR_PIN_MASK, SR_PIN_DIR); + gpio_put_masked(SR_PIN_MASK, SR_PIN_VALUE); + uint8_t state = 0u; + for (uint8_t i = 0u; i < 8; i++) { + mp_hal_delay_us(1); // reduce clockout frequency + gpio_put(SR_CLK, true); + if (gpio_get(SR_DATA)) { + state |= (0b1 << i); + } + gpio_put(SR_CLK, false); + } + reset_button_state = state; + + // Turn on LED_CONN so the user knows it is ok to release the button. + // The LED is only on for a short time, since it is reset from board_init. + gpio_init(LED_CONN); + gpio_put(LED_CONN, true); + gpio_set_dir(LED_CONN, GPIO_OUT); +} -digitalio_digitalinout_obj_t enable_pin_obj; +static mp_obj_t _get_reset_state(void) { + return mp_obj_new_int(reset_button_state); +} +MP_DEFINE_CONST_FUN_OBJ_0(get_reset_state_obj, _get_reset_state); + +static mp_obj_t _on_reset_pressed(mp_obj_t in) { + uint8_t bit_number = mp_obj_get_int(in); + return mp_obj_new_bool( + (reset_button_state & (1 << bit_number)) != 0); +} +MP_DEFINE_CONST_FUN_OBJ_1(on_reset_pressed_obj, _on_reset_pressed); -digitalio_digitalinout_obj_t sr_clock; -digitalio_digitalinout_obj_t sr_data; -digitalio_digitalinout_obj_t sr_latch; +static mp_obj_t _power_off(void) { + gpio_put(ENABLE_3V3_PIN, false); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_0(power_off_obj, _power_off); + +#define DELAY 0x80 + +// This is a 7.3" ACeP EInk. enum reg { PSR = 0x00, @@ -94,70 +161,53 @@ const uint8_t refresh_sequence[] = { }; void board_init(void) { - // Drive the EN_3V3 pin high so the board stays awake on battery power - enable_pin_obj.base.type = &digitalio_digitalinout_type; - common_hal_digitalio_digitalinout_construct(&enable_pin_obj, &pin_GPIO2); - common_hal_digitalio_digitalinout_switch_to_output(&enable_pin_obj, true, DRIVE_MODE_PUSH_PULL); - - // Never reset - common_hal_digitalio_digitalinout_never_reset(&enable_pin_obj); - - common_hal_digitalio_digitalinout_construct(&sr_clock, &pin_GPIO8); - common_hal_digitalio_digitalinout_switch_to_output(&sr_clock, false, DRIVE_MODE_PUSH_PULL); - - common_hal_digitalio_digitalinout_construct(&sr_data, &pin_GPIO10); - common_hal_digitalio_digitalinout_switch_to_input(&sr_data, PULL_NONE); - - common_hal_digitalio_digitalinout_construct(&sr_latch, &pin_GPIO9); - common_hal_digitalio_digitalinout_switch_to_output(&sr_latch, true, DRIVE_MODE_PUSH_PULL); + // reset LED_CONN (turned on in pre_init()) + gpio_deinit(LED_CONN); + // create bus and display fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = common_hal_board_create_spi(0); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_GPIO28, // EPD_DC Command or data - &pin_GPIO17, // EPD_CS Chip select - &pin_GPIO27, // EPD_RST Reset + MP_OBJ_FROM_PTR(&pin_GPIO28), // EPD_DC Command or data + MP_OBJ_FROM_PTR(&pin_GPIO17), // EPD_CS Chip select + MP_OBJ_FROM_PTR(&pin_GPIO27), // EPD_RST Reset 1000000, // Baudrate 0, // Polarity 0); // Phase epaperdisplay_epaperdisplay_obj_t *display = &allocate_display()->epaper_display; display->base.type = &epaperdisplay_epaperdisplay_type; - common_hal_epaperdisplay_epaperdisplay_construct( - display, - bus, - display_start_sequence, sizeof(display_start_sequence), - 1.0, // start up time - display_stop_sequence, sizeof(display_stop_sequence), - 800, // width - 480, // height - 800, // ram_width - 480, // ram_height - 0, // colstart - 0, // rowstart - 180, // rotation - NO_COMMAND, // set_column_window_command - NO_COMMAND, // set_row_window_command - NO_COMMAND, // set_current_column_command - NO_COMMAND, // set_current_row_command - 0x10, // write_black_ram_command - false, // black_bits_inverted - NO_COMMAND, // write_color_ram_command - false, // color_bits_inverted - 0x000000, // highlight_color - refresh_sequence, sizeof(refresh_sequence), - 28.0, // refresh_time - NULL, // busy_pin - false, // busy_state - 30.0, // seconds_per_frame - false, // always_toggle_chip_select - false, // grayscale - true, // acep - false, // two_byte_sequence_length - false); // address_little_endian + + epaperdisplay_construct_args_t args = EPAPERDISPLAY_CONSTRUCT_ARGS_DEFAULTS; + args.bus = bus; + args.start_sequence = display_start_sequence; + args.start_sequence_len = sizeof(display_start_sequence); + args.start_up_time = 1.0; + args.stop_sequence = display_stop_sequence; + args.stop_sequence_len = sizeof(display_stop_sequence); + args.width = 800; + args.height = 480; + args.ram_width = 800; + args.ram_height = 480; + args.rotation = 180; + args.write_black_ram_command = 0x10; + args.refresh_sequence = refresh_sequence; + args.refresh_sequence_len = sizeof(refresh_sequence); + args.refresh_time = 28.0; + args.busy_pin = NULL; + args.seconds_per_frame = 30.0; + args.acep = true; + common_hal_epaperdisplay_epaperdisplay_construct(display, &args); } // Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. + +bool board_reset_pin_number(uint8_t pin_number) { + if (pin_number == ENABLE_3V3_PIN) { + return true; + } + return false; +} diff --git a/ports/raspberrypi/boards/pimoroni_inky_frame_7_3/inky-shared.h b/ports/raspberrypi/boards/pimoroni_inky_frame_7_3/inky-shared.h index c6be0048937..602b0279885 100644 --- a/ports/raspberrypi/boards/pimoroni_inky_frame_7_3/inky-shared.h +++ b/ports/raspberrypi/boards/pimoroni_inky_frame_7_3/inky-shared.h @@ -6,6 +6,10 @@ #pragma once +#include "py/obj.h" #include "shared-bindings/digitalio/DigitalInOut.h" extern digitalio_digitalinout_obj_t enable_pin_obj; +extern const mp_obj_fun_builtin_fixed_t get_reset_state_obj; +extern const mp_obj_fun_builtin_fixed_t power_off_obj; +extern const mp_obj_fun_builtin_fixed_t on_reset_pressed_obj; diff --git a/ports/raspberrypi/boards/pimoroni_inky_frame_7_3/link.ld b/ports/raspberrypi/boards/pimoroni_inky_frame_7_3/link.ld index e814bead4c5..d4f5109f4b6 100644 --- a/ports/raspberrypi/boards/pimoroni_inky_frame_7_3/link.ld +++ b/ports/raspberrypi/boards/pimoroni_inky_frame_7_3/link.ld @@ -1 +1 @@ -firmware_size = 1532k; +firmware_size = 1536k; diff --git a/ports/raspberrypi/boards/pimoroni_inky_frame_7_3/mpconfigboard.h b/ports/raspberrypi/boards/pimoroni_inky_frame_7_3/mpconfigboard.h index 42cb1196a54..32477b12c29 100644 --- a/ports/raspberrypi/boards/pimoroni_inky_frame_7_3/mpconfigboard.h +++ b/ports/raspberrypi/boards/pimoroni_inky_frame_7_3/mpconfigboard.h @@ -14,8 +14,8 @@ #define MICROPY_HW_LED_STATUS (&pin_GPIO6) -#define DEFAULT_I2C_BUS_SCL (&pin_GPIO4) -#define DEFAULT_I2C_BUS_SDA (&pin_GPIO5) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO4) +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO5) #define DEFAULT_UART_BUS_TX (&pin_GPIO0) #define DEFAULT_UART_BUS_RX (&pin_GPIO1) diff --git a/ports/raspberrypi/boards/pimoroni_inky_frame_7_3/pins.c b/ports/raspberrypi/boards/pimoroni_inky_frame_7_3/pins.c index f615be4d413..9dc7394a3af 100644 --- a/ports/raspberrypi/boards/pimoroni_inky_frame_7_3/pins.c +++ b/ports/raspberrypi/boards/pimoroni_inky_frame_7_3/pins.c @@ -14,16 +14,16 @@ #include "inky-shared.h" // For use with keypad.ShiftRegisterKeys(): maps keycodes (bit-number) -// to logical names such as board.KEYCODES.BUTTON_A etc. +// to logical names such as board.KEYCODES.SW_A etc. // N.B.: labels and bit-numbers in the schematic are reversed, i.e. -// BUTTON_A on D0 has bit-number 7 +// SW_A on D0 has bit-number 7 static const qstr board_keycodes_fields[] = { - MP_QSTR_BUTTON_A, - MP_QSTR_BUTTON_B, - MP_QSTR_BUTTON_C, - MP_QSTR_BUTTON_D, - MP_QSTR_BUTTON_E, + MP_QSTR_SW_A, + MP_QSTR_SW_B, + MP_QSTR_SW_C, + MP_QSTR_SW_D, + MP_QSTR_SW_E, MP_QSTR_RTC_ALARM, MP_QSTR_EXT_TRIGGER, MP_QSTR_INKY_BUS @@ -59,9 +59,9 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO6) }, { MP_ROM_QSTR(MP_QSTR_LED_CONN), MP_ROM_PTR(&pin_GPIO7) }, - { MP_ROM_QSTR(MP_QSTR_BUTTON_CLK), MP_ROM_PTR(&pin_GPIO8) }, - { MP_ROM_QSTR(MP_QSTR_BUTTON_LATCH), MP_ROM_PTR(&pin_GPIO9) }, - { MP_ROM_QSTR(MP_QSTR_BUTTON_OUT), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_SWITCH_CLK), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_SWITCH_LATCH), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_SWITCH_OUT), MP_ROM_PTR(&pin_GPIO10) }, { MP_ROM_QSTR(MP_QSTR_LED_A), MP_ROM_PTR(&pin_GPIO11) }, { MP_ROM_QSTR(MP_QSTR_LED_B), MP_ROM_PTR(&pin_GPIO12) }, @@ -83,6 +83,9 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_INKY_RES), MP_ROM_PTR(&pin_GPIO27) }, { MP_ROM_QSTR(MP_QSTR_INKY_DC), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_VOLTAGE_MONITOR), MP_ROM_PTR(&pin_GPIO29) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO29) }, + { MP_ROM_QSTR(MP_QSTR_PICO_LED), MP_ROM_PTR(&pin_CYW0) }, { MP_ROM_QSTR(MP_QSTR_SMPS_MODE), MP_ROM_PTR(&pin_CYW1) }, { MP_ROM_QSTR(MP_QSTR_VBUS_SENSE), MP_ROM_PTR(&pin_CYW2) }, @@ -95,5 +98,18 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_DISPLAY), MP_ROM_PTR(&displays[0].epaper_display)}, { MP_ROM_QSTR(MP_QSTR_ENABLE_DIO), MP_ROM_PTR(&enable_pin_obj)}, // GP2 { MP_ROM_QSTR(MP_QSTR_KEYCODES), MP_ROM_PTR(&board_keycodes_obj)}, + + // turn power off. This only works if running from batteries + { MP_ROM_QSTR(MP_QSTR_POWER_OFF), (mp_obj_t)&power_off_obj }, + + // button-state on reset + // Use `board.RESET_STATE()` to query the state of all buttons at reset. + // To detect individual key-presses, `board.ON_RESET_PRESSED()` + // is simpler. + { MP_ROM_QSTR(MP_QSTR_RESET_STATE), (mp_obj_t)&get_reset_state_obj }, + + // Use `board.ON_RESET_PRESSED(board.KEYCODES.SW_A)` + // to check if `SW_A` was pressed during reset. + { MP_ROM_QSTR(MP_QSTR_ON_RESET_PRESSED), (mp_obj_t)&on_reset_pressed_obj }, }; MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/raspberrypi/boards/pimoroni_pico_dv_base_w/link.ld b/ports/raspberrypi/boards/pimoroni_pico_dv_base_w/link.ld index e814bead4c5..d4f5109f4b6 100644 --- a/ports/raspberrypi/boards/pimoroni_pico_dv_base_w/link.ld +++ b/ports/raspberrypi/boards/pimoroni_pico_dv_base_w/link.ld @@ -1 +1 @@ -firmware_size = 1532k; +firmware_size = 1536k; diff --git a/ports/raspberrypi/boards/pimoroni_pico_dv_base_w/mpconfigboard.mk b/ports/raspberrypi/boards/pimoroni_pico_dv_base_w/mpconfigboard.mk index 9218192d083..02cbe3b69b7 100644 --- a/ports/raspberrypi/boards/pimoroni_pico_dv_base_w/mpconfigboard.mk +++ b/ports/raspberrypi/boards/pimoroni_pico_dv_base_w/mpconfigboard.mk @@ -19,6 +19,13 @@ CIRCUITPY_SOCKETPOOL = 1 CIRCUITPY_WIFI = 1 CIRCUITPY_PICODVI = 1 +CIRCUITPY_AUDIOEFFECTS = 0 +CIRCUITPY_AUDIOFILEWRITER = 0 +CIRCUITPY_BLEIO_HCI = 0 + +# No room: this board fills FLASH_FIRMWARE. Frees ~9kB. Not the board's I2S +# line-out/HDMI audio, which audiobusio still provides. +CIRCUITPY_USB_AUDIO = 0 CFLAGS += \ -DCYW43_PIN_WL_DYNAMIC=0 \ diff --git a/ports/raspberrypi/boards/pimoroni_pico_plus2w/link.ld b/ports/raspberrypi/boards/pimoroni_pico_plus2w/link.ld index e814bead4c5..d4f5109f4b6 100644 --- a/ports/raspberrypi/boards/pimoroni_pico_plus2w/link.ld +++ b/ports/raspberrypi/boards/pimoroni_pico_plus2w/link.ld @@ -1 +1 @@ -firmware_size = 1532k; +firmware_size = 1536k; diff --git a/ports/raspberrypi/boards/pimoroni_picosystem/board.c b/ports/raspberrypi/boards/pimoroni_picosystem/board.c index 40756b56426..f115dabfa19 100644 --- a/ports/raspberrypi/boards/pimoroni_picosystem/board.c +++ b/ports/raspberrypi/boards/pimoroni_picosystem/board.c @@ -46,14 +46,13 @@ void board_init(void) { fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_GPIO6, &pin_GPIO7, NULL, false); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_GPIO9, // TFT_DC Command or data - &pin_GPIO5, // TFT_CS Chip select - &pin_GPIO4, // TFT_RST Reset + MP_OBJ_FROM_PTR(&pin_GPIO9), // TFT_DC Command or data + MP_OBJ_FROM_PTR(&pin_GPIO5), // TFT_CS Chip select + MP_OBJ_FROM_PTR(&pin_GPIO4), // TFT_RST Reset 60000000, // Baudrate 0, // Polarity 0); // Phase diff --git a/ports/raspberrypi/boards/pimoroni_picosystem/mpconfigboard.mk b/ports/raspberrypi/boards/pimoroni_picosystem/mpconfigboard.mk index 8dca786a5e0..62d3088d9ce 100644 --- a/ports/raspberrypi/boards/pimoroni_picosystem/mpconfigboard.mk +++ b/ports/raspberrypi/boards/pimoroni_picosystem/mpconfigboard.mk @@ -12,6 +12,7 @@ CIRCUITPY__EVE = 1 CIRCUITPY_KEYPAD = 1 CIRCUITPY_STAGE = 1 +CIRCUITPY_PICOGAME = 1 CIRCUITPY_AUDIOIO = 1 diff --git a/ports/raspberrypi/boards/pimoroni_plasma2040w/link.ld b/ports/raspberrypi/boards/pimoroni_plasma2040w/link.ld index e814bead4c5..d4f5109f4b6 100644 --- a/ports/raspberrypi/boards/pimoroni_plasma2040w/link.ld +++ b/ports/raspberrypi/boards/pimoroni_plasma2040w/link.ld @@ -1 +1 @@ -firmware_size = 1532k; +firmware_size = 1536k; diff --git a/ports/raspberrypi/boards/pimoroni_plasma2350/mpconfigboard.h b/ports/raspberrypi/boards/pimoroni_plasma2350/mpconfigboard.h index 72b1e1d0439..097cbd8baa3 100644 --- a/ports/raspberrypi/boards/pimoroni_plasma2350/mpconfigboard.h +++ b/ports/raspberrypi/boards/pimoroni_plasma2350/mpconfigboard.h @@ -5,7 +5,7 @@ // SPDX-License-Identifier: MIT #define MICROPY_HW_BOARD_NAME "Pimoroni Plasma 2350" -#define MICROPY_HW_MCU_NAME "rp2350b" +#define MICROPY_HW_MCU_NAME "rp2350a" #define CIRCUITPY_RGB_STATUS_INVERTED_PWM #define CIRCUITPY_RGB_STATUS_R (&pin_GPIO16) diff --git a/ports/raspberrypi/boards/pimoroni_plasma2350/mpconfigboard.mk b/ports/raspberrypi/boards/pimoroni_plasma2350/mpconfigboard.mk index 56fd7b641de..52dcd3fbe71 100644 --- a/ports/raspberrypi/boards/pimoroni_plasma2350/mpconfigboard.mk +++ b/ports/raspberrypi/boards/pimoroni_plasma2350/mpconfigboard.mk @@ -10,3 +10,6 @@ CHIP_FAMILY = rp2 EXTERNAL_FLASH_DEVICES = "W25Q32JVxQ" CIRCUITPY__EVE = 1 + +# GPIO12-19 needed for picodvi, but many are not available. +CIRCUITPY_PICODVI = 0 diff --git a/ports/raspberrypi/boards/pimoroni_plasma2350w/mpconfigboard.h b/ports/raspberrypi/boards/pimoroni_plasma2350w/mpconfigboard.h index d9e62abb1ed..576299d939c 100644 --- a/ports/raspberrypi/boards/pimoroni_plasma2350w/mpconfigboard.h +++ b/ports/raspberrypi/boards/pimoroni_plasma2350w/mpconfigboard.h @@ -5,7 +5,7 @@ // SPDX-License-Identifier: MIT #define MICROPY_HW_BOARD_NAME "Pimoroni Plasma 2350W" -#define MICROPY_HW_MCU_NAME "rp2350A" +#define MICROPY_HW_MCU_NAME "rp2350a" #define CIRCUITPY_RGB_STATUS_INVERTED_PWM #define CIRCUITPY_RGB_STATUS_R (&pin_GPIO16) diff --git a/ports/raspberrypi/boards/pimoroni_plasma2350w/mpconfigboard.mk b/ports/raspberrypi/boards/pimoroni_plasma2350w/mpconfigboard.mk index 8563f0d0034..cab35965a0f 100644 --- a/ports/raspberrypi/boards/pimoroni_plasma2350w/mpconfigboard.mk +++ b/ports/raspberrypi/boards/pimoroni_plasma2350w/mpconfigboard.mk @@ -21,6 +21,9 @@ CIRCUITPY_WIFI = 1 CIRCUITPY_PICODVI = 0 CIRCUITPY_USB_HOST = 0 +# GPIO12-19 needed for picodvi, but many are not available. +CIRCUITPY_PICODVI = 0 + CFLAGS += \ -DCYW43_PIN_WL_DYNAMIC=0 \ -DCYW43_DEFAULT_PIN_WL_HOST_WAKE=24 \ diff --git a/ports/raspberrypi/boards/pimoroni_tiny2350/mpconfigboard.mk b/ports/raspberrypi/boards/pimoroni_tiny2350/mpconfigboard.mk index 9ffdf263003..b94022c1f6d 100644 --- a/ports/raspberrypi/boards/pimoroni_tiny2350/mpconfigboard.mk +++ b/ports/raspberrypi/boards/pimoroni_tiny2350/mpconfigboard.mk @@ -10,3 +10,6 @@ CHIP_FAMILY = rp2 EXTERNAL_FLASH_DEVICES = "W25Q32JVxQ" CIRCUITPY__EVE = 1 + +# GPIO12-19 needed for picodvi, but several are not available. +CIRCUITPY_PICODVI = 0 diff --git a/ports/raspberrypi/boards/raspberry_pi_pico/mpconfigboard.h b/ports/raspberrypi/boards/raspberry_pi_pico/mpconfigboard.h index c4aff9696d7..fecf3a2ccaa 100644 --- a/ports/raspberrypi/boards/raspberry_pi_pico/mpconfigboard.h +++ b/ports/raspberrypi/boards/raspberry_pi_pico/mpconfigboard.h @@ -13,3 +13,9 @@ #define CIRCUITPY_BOARD_I2C (1) #define CIRCUITPY_BOARD_I2C_PIN {{.scl = &pin_GPIO5, .sda = &pin_GPIO4}} + +#define CIRCUITPY_BOARD_SPI (1) +#define CIRCUITPY_BOARD_SPI_PIN {{.clock = &pin_GPIO18, .mosi = &pin_GPIO19, .miso = &pin_GPIO16}} + +#define CIRCUITPY_BOARD_UART (1) +#define CIRCUITPY_BOARD_UART_PIN {{.tx = &pin_GPIO0, .rx = &pin_GPIO1}} diff --git a/ports/raspberrypi/boards/raspberry_pi_pico/mpconfigboard.mk b/ports/raspberrypi/boards/raspberry_pi_pico/mpconfigboard.mk index 20607d50e41..6f2c657d127 100644 --- a/ports/raspberrypi/boards/raspberry_pi_pico/mpconfigboard.mk +++ b/ports/raspberrypi/boards/raspberry_pi_pico/mpconfigboard.mk @@ -9,4 +9,7 @@ CHIP_FAMILY = rp2 EXTERNAL_FLASH_DEVICES = "W25Q16JVxQ" CIRCUITPY__EVE = 1 + +CIRCUITPY_PICOGAME = 1 + CIRCUITPY_PICODVI = 1 diff --git a/ports/raspberrypi/boards/raspberry_pi_pico/pins.c b/ports/raspberrypi/boards/raspberry_pi_pico/pins.c index 5ce8ae818eb..9fd5e955058 100644 --- a/ports/raspberrypi/boards/raspberry_pi_pico/pins.c +++ b/ports/raspberrypi/boards/raspberry_pi_pico/pins.c @@ -57,6 +57,9 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO29) }, { MP_ROM_QSTR(MP_QSTR_VOLTAGE_MONITOR), MP_ROM_PTR(&pin_GPIO29) }, + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, { MP_ROM_QSTR(MP_QSTR_STEMMA_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_module_globals_table); diff --git a/ports/raspberrypi/boards/raspberry_pi_pico2/mpconfigboard.h b/ports/raspberrypi/boards/raspberry_pi_pico2/mpconfigboard.h index 5d1dda8f50f..5eb6d75c39c 100644 --- a/ports/raspberrypi/boards/raspberry_pi_pico2/mpconfigboard.h +++ b/ports/raspberrypi/boards/raspberry_pi_pico2/mpconfigboard.h @@ -11,3 +11,9 @@ #define CIRCUITPY_BOARD_I2C (1) #define CIRCUITPY_BOARD_I2C_PIN {{.scl = &pin_GPIO5, .sda = &pin_GPIO4}} + +#define CIRCUITPY_BOARD_SPI (1) +#define CIRCUITPY_BOARD_SPI_PIN {{.clock = &pin_GPIO18, .mosi = &pin_GPIO19, .miso = &pin_GPIO16}} + +#define CIRCUITPY_BOARD_UART (1) +#define CIRCUITPY_BOARD_UART_PIN {{.tx = &pin_GPIO0, .rx = &pin_GPIO1}} diff --git a/ports/raspberrypi/boards/raspberry_pi_pico2/pins.c b/ports/raspberrypi/boards/raspberry_pi_pico2/pins.c index d3626838f82..99fce62bc2a 100644 --- a/ports/raspberrypi/boards/raspberry_pi_pico2/pins.c +++ b/ports/raspberrypi/boards/raspberry_pi_pico2/pins.c @@ -57,6 +57,9 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO29) }, { MP_ROM_QSTR(MP_QSTR_VOLTAGE_MONITOR), MP_ROM_PTR(&pin_GPIO29) }, + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, { MP_ROM_QSTR(MP_QSTR_STEMMA_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_module_globals_table); diff --git a/ports/raspberrypi/boards/raspberry_pi_pico2_w/link.ld b/ports/raspberrypi/boards/raspberry_pi_pico2_w/link.ld index e814bead4c5..d4f5109f4b6 100644 --- a/ports/raspberrypi/boards/raspberry_pi_pico2_w/link.ld +++ b/ports/raspberrypi/boards/raspberry_pi_pico2_w/link.ld @@ -1 +1 @@ -firmware_size = 1532k; +firmware_size = 1536k; diff --git a/ports/raspberrypi/boards/raspberry_pi_pico2_w/mpconfigboard.h b/ports/raspberrypi/boards/raspberry_pi_pico2_w/mpconfigboard.h index 4f13dd13efc..a688f1b2418 100644 --- a/ports/raspberrypi/boards/raspberry_pi_pico2_w/mpconfigboard.h +++ b/ports/raspberrypi/boards/raspberry_pi_pico2_w/mpconfigboard.h @@ -14,3 +14,9 @@ #define CIRCUITPY_BOARD_I2C (1) #define CIRCUITPY_BOARD_I2C_PIN {{.scl = &pin_GPIO5, .sda = &pin_GPIO4}} + +#define CIRCUITPY_BOARD_SPI (1) +#define CIRCUITPY_BOARD_SPI_PIN {{.clock = &pin_GPIO18, .mosi = &pin_GPIO19, .miso = &pin_GPIO16}} + +#define CIRCUITPY_BOARD_UART (1) +#define CIRCUITPY_BOARD_UART_PIN {{.tx = &pin_GPIO0, .rx = &pin_GPIO1}} diff --git a/ports/raspberrypi/boards/raspberry_pi_pico2_w/pins.c b/ports/raspberrypi/boards/raspberry_pi_pico2_w/pins.c index 7ec6b409724..f089d6ca8cf 100644 --- a/ports/raspberrypi/boards/raspberry_pi_pico2_w/pins.c +++ b/ports/raspberrypi/boards/raspberry_pi_pico2_w/pins.c @@ -54,6 +54,9 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO29) }, { MP_ROM_QSTR(MP_QSTR_VOLTAGE_MONITOR), MP_ROM_PTR(&pin_GPIO29) }, + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, { MP_ROM_QSTR(MP_QSTR_STEMMA_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_module_globals_table); diff --git a/ports/raspberrypi/boards/raspberry_pi_pico_w/link.ld b/ports/raspberrypi/boards/raspberry_pi_pico_w/link.ld index e814bead4c5..d4f5109f4b6 100644 --- a/ports/raspberrypi/boards/raspberry_pi_pico_w/link.ld +++ b/ports/raspberrypi/boards/raspberry_pi_pico_w/link.ld @@ -1 +1 @@ -firmware_size = 1532k; +firmware_size = 1536k; diff --git a/ports/raspberrypi/boards/raspberry_pi_pico_w/mpconfigboard.h b/ports/raspberrypi/boards/raspberry_pi_pico_w/mpconfigboard.h index 5913eac4874..ceb9c877b49 100644 --- a/ports/raspberrypi/boards/raspberry_pi_pico_w/mpconfigboard.h +++ b/ports/raspberrypi/boards/raspberry_pi_pico_w/mpconfigboard.h @@ -16,3 +16,9 @@ #define CIRCUITPY_BOARD_I2C (1) #define CIRCUITPY_BOARD_I2C_PIN {{.scl = &pin_GPIO5, .sda = &pin_GPIO4}} + +#define CIRCUITPY_BOARD_SPI (1) +#define CIRCUITPY_BOARD_SPI_PIN {{.clock = &pin_GPIO18, .mosi = &pin_GPIO19, .miso = &pin_GPIO16}} + +#define CIRCUITPY_BOARD_UART (1) +#define CIRCUITPY_BOARD_UART_PIN {{.tx = &pin_GPIO0, .rx = &pin_GPIO1}} diff --git a/ports/raspberrypi/boards/raspberry_pi_pico_w/mpconfigboard.mk b/ports/raspberrypi/boards/raspberry_pi_pico_w/mpconfigboard.mk index e658db65f4d..d2bb38c0312 100644 --- a/ports/raspberrypi/boards/raspberry_pi_pico_w/mpconfigboard.mk +++ b/ports/raspberrypi/boards/raspberry_pi_pico_w/mpconfigboard.mk @@ -12,6 +12,8 @@ CIRCUITPY_USB_HOST = 0 CIRCUITPY__EVE = 1 +CIRCUITPY_PICOGAME = 1 + CIRCUITPY_CYW43 = 1 CIRCUITPY_SSL = 1 CIRCUITPY_HASHLIB = 1 diff --git a/ports/raspberrypi/boards/raspberry_pi_pico_w/pins.c b/ports/raspberrypi/boards/raspberry_pi_pico_w/pins.c index ce0a0723398..2ba4257dc97 100644 --- a/ports/raspberrypi/boards/raspberry_pi_pico_w/pins.c +++ b/ports/raspberrypi/boards/raspberry_pi_pico_w/pins.c @@ -55,6 +55,9 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO29) }, + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, { MP_ROM_QSTR(MP_QSTR_STEMMA_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_module_globals_table); diff --git a/ports/raspberrypi/boards/securinghw-xiaomao/board.c b/ports/raspberrypi/boards/securinghw-xiaomao/board.c new file mode 100644 index 00000000000..e6a868ab212 --- /dev/null +++ b/ports/raspberrypi/boards/securinghw-xiaomao/board.c @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/raspberrypi/boards/securinghw-xiaomao/mpconfigboard.h b/ports/raspberrypi/boards/securinghw-xiaomao/mpconfigboard.h new file mode 100644 index 00000000000..ed69167c774 --- /dev/null +++ b/ports/raspberrypi/boards/securinghw-xiaomao/mpconfigboard.h @@ -0,0 +1,17 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#define MICROPY_HW_BOARD_NAME "SecuringHardware.com Xiaomao" +#define MICROPY_HW_MCU_NAME "rp2040" + +#define MICROPY_HW_NEOPIXEL (&pin_GPIO7) +#define CIRCUITPY_STATUS_LED_POWER (&pin_GPIO6) + +#define CIRCUITPY_BOARD_UART (2) +#define CIRCUITPY_BOARD_UART_PIN {{.tx = &pin_GPIO16, .rx = &pin_GPIO17}, \ + {.tx = &pin_GPIO20, .rx = &pin_GPIO21}} diff --git a/ports/raspberrypi/boards/securinghw-xiaomao/mpconfigboard.mk b/ports/raspberrypi/boards/securinghw-xiaomao/mpconfigboard.mk new file mode 100644 index 00000000000..19b8639883a --- /dev/null +++ b/ports/raspberrypi/boards/securinghw-xiaomao/mpconfigboard.mk @@ -0,0 +1,9 @@ +USB_VID = 0x2E8A +USB_PID = 0x1116 +USB_PRODUCT = "Xiaomao" +USB_MANUFACTURER = "SecuringHardwarecom" + +CHIP_VARIANT = RP2040 +CHIP_FAMILY = rp2 + +EXTERNAL_FLASH_DEVICES = "W25Q128JVxQ" diff --git a/ports/raspberrypi/boards/securinghw-xiaomao/pico-sdk-configboard.h b/ports/raspberrypi/boards/securinghw-xiaomao/pico-sdk-configboard.h new file mode 100644 index 00000000000..110195b7794 --- /dev/null +++ b/ports/raspberrypi/boards/securinghw-xiaomao/pico-sdk-configboard.h @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Put board-specific pico-sdk definitions here. This file must exist. diff --git a/ports/raspberrypi/boards/securinghw-xiaomao/pins.c b/ports/raspberrypi/boards/securinghw-xiaomao/pins.c new file mode 100644 index 00000000000..a6b6cd3ac72 --- /dev/null +++ b/ports/raspberrypi/boards/securinghw-xiaomao/pins.c @@ -0,0 +1,37 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +CIRCUITPY_BOARD_BUS_SINGLETON(uart1, uart, 1) + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_GPIO1) }, + { 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_TX), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_CTS), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_RTS), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_TX1), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_RX1), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_CTS1), MP_ROM_PTR(&pin_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_BTN), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_VBUS_DET), MP_ROM_PTR(&pin_GPIO29) }, + + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_NEOPIXEL_POWER), MP_ROM_PTR(&pin_GPIO6) }, + + { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj) }, + { MP_ROM_QSTR(MP_QSTR_UART1), MP_ROM_PTR(&board_uart1_obj) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/raspberrypi/boards/seeeduino_xiao_rp2350/mpconfigboard.mk b/ports/raspberrypi/boards/seeeduino_xiao_rp2350/mpconfigboard.mk index d5f866bd89e..f51d5271215 100644 --- a/ports/raspberrypi/boards/seeeduino_xiao_rp2350/mpconfigboard.mk +++ b/ports/raspberrypi/boards/seeeduino_xiao_rp2350/mpconfigboard.mk @@ -8,3 +8,6 @@ CHIP_PACKAGE = A CHIP_FAMILY = rp2 EXTERNAL_FLASH_DEVICES = "P25Q16H" + +# GPIO12-19 needed for picodvi, but several are not available. +CIRCUITPY_PICODVI = 0 diff --git a/ports/raspberrypi/boards/sparkfun_pro_micro_rp2350/mpconfigboard.mk b/ports/raspberrypi/boards/sparkfun_pro_micro_rp2350/mpconfigboard.mk index e5d6e1b8ff8..53cdf72963f 100644 --- a/ports/raspberrypi/boards/sparkfun_pro_micro_rp2350/mpconfigboard.mk +++ b/ports/raspberrypi/boards/sparkfun_pro_micro_rp2350/mpconfigboard.mk @@ -8,3 +8,6 @@ CHIP_PACKAGE = A CHIP_FAMILY = rp2 EXTERNAL_FLASH_DEVICES = "W25Q128JVxQ" + +# GPIO12-19 needed for picodvi, but many are not available. +CIRCUITPY_PICODVI = 0 diff --git a/ports/raspberrypi/boards/sparkfun_thing_plus_rp2350/link.ld b/ports/raspberrypi/boards/sparkfun_thing_plus_rp2350/link.ld index e814bead4c5..d4f5109f4b6 100644 --- a/ports/raspberrypi/boards/sparkfun_thing_plus_rp2350/link.ld +++ b/ports/raspberrypi/boards/sparkfun_thing_plus_rp2350/link.ld @@ -1 +1 @@ -firmware_size = 1532k; +firmware_size = 1536k; diff --git a/ports/raspberrypi/boards/sparkfun_thing_plus_rp2350/mpconfigboard.mk b/ports/raspberrypi/boards/sparkfun_thing_plus_rp2350/mpconfigboard.mk index 6e81a229961..81d7f660473 100644 --- a/ports/raspberrypi/boards/sparkfun_thing_plus_rp2350/mpconfigboard.mk +++ b/ports/raspberrypi/boards/sparkfun_thing_plus_rp2350/mpconfigboard.mk @@ -23,6 +23,8 @@ CIRCUITPY_MDNS = 1 CIRCUITPY_SOCKETPOOL = 1 CIRCUITPY_WIFI = 1 +# GPIO12-19 needed for picodvi, but GPIO14 is used for a NeoPixel. +CIRCUITPY_PICODVI = 0 CFLAGS += \ -DCYW43_PIN_WL_DYNAMIC=0 \ diff --git a/ports/raspberrypi/boards/teenage_engineering_ep2350/board.c b/ports/raspberrypi/boards/teenage_engineering_ep2350/board.c new file mode 100644 index 00000000000..b59bcfa1f95 --- /dev/null +++ b/ports/raspberrypi/boards/teenage_engineering_ep2350/board.c @@ -0,0 +1,48 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" + +#include "mpconfigboard.h" +#include "common-hal/microcontroller/Pin.h" +#include "hardware/gpio.h" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. + +static void assert_power_hold(void) { + // Doing this (rather than gpio_init()) in this specific order ensures no + // glitch if the pin was already configured as a high output. gpio_init() + // temporarily configures the pin as an input, which would release the + // latch and power the board off. + gpio_put(MICROPY_HW_POWER_HOLD_PIN_NUMBER, 1); + gpio_set_dir(MICROPY_HW_POWER_HOLD_PIN_NUMBER, GPIO_OUT); + gpio_set_function(MICROPY_HW_POWER_HOLD_PIN_NUMBER, GPIO_FUNC_SIO); +} + +// Forward declaration to satisfy -Wmissing-prototypes +static void preinit_power_hold(void) __attribute__((constructor(101))); + +// Runs before main(), so the latch is set as early as it can possibly be. +static void preinit_power_hold(void) { + assert_power_hold(); +} + +// The EP-2350 has no power switch: pressing the handle applies power directly, +// and firmware must set the power hold latch on GPIO2 before the handle is +// released or the unit dies. The latch is a true set/reset latch, so a single +// high pulse is enough, but the pin must never be left low. +// +// reset_pin_number() runs this whenever the pin is reset, so the latch is +// re-asserted instead of being reset to an input. The pin is deliberately not +// claimed, so user code can still take board.POWER_HOLD and drive it low to +// power the unit off. +bool board_reset_pin_number(uint8_t pin_number) { + if (pin_number == MICROPY_HW_POWER_HOLD_PIN_NUMBER) { + assert_power_hold(); + return true; + } + return false; +} diff --git a/ports/raspberrypi/boards/teenage_engineering_ep2350/mpconfigboard.h b/ports/raspberrypi/boards/teenage_engineering_ep2350/mpconfigboard.h new file mode 100644 index 00000000000..fc3ad16bdc2 --- /dev/null +++ b/ports/raspberrypi/boards/teenage_engineering_ep2350/mpconfigboard.h @@ -0,0 +1,20 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks +// +// SPDX-License-Identifier: MIT + +#define MICROPY_HW_BOARD_NAME "Teenage Engineering ting fx EP-2350" +#define MICROPY_HW_MCU_NAME "rp2350a" + +// Top white LED. Also available as board.LED_WHITE1. +#define MICROPY_HW_LED_STATUS (&pin_GPIO0) + +// GPIO2 is the power hold latch: high keeps the unit powered, low powers it +// off immediately. It is asserted in board_reset_pin_number() so that it +// survives every pin reset. +#define MICROPY_HW_POWER_HOLD_PIN_NUMBER (2) + +// Codec (0x1b) and accelerometer (0x18) share I2C1. External pull-ups. +#define CIRCUITPY_BOARD_I2C (1) +#define CIRCUITPY_BOARD_I2C_PIN {{.scl = &pin_GPIO15, .sda = &pin_GPIO14}} diff --git a/ports/raspberrypi/boards/teenage_engineering_ep2350/mpconfigboard.mk b/ports/raspberrypi/boards/teenage_engineering_ep2350/mpconfigboard.mk new file mode 100644 index 00000000000..704edf815e6 --- /dev/null +++ b/ports/raspberrypi/boards/teenage_engineering_ep2350/mpconfigboard.mk @@ -0,0 +1,20 @@ +USB_VID = 0x239A +USB_PID = 0x8176 +USB_PRODUCT = "ting fx EP-2350" +USB_MANUFACTURER = "Teenage Engineering" + +CHIP_VARIANT = RP2350 +CHIP_PACKAGE = A +CHIP_FAMILY = rp2 + +# Winbond W25Q16JV, 2MB (16Mbit) on CS0, nothing on CS1. +EXTERNAL_FLASH_DEVICES = "W25Q16JVxQ" + +# Only 2MB of flash: firmware gets the default 1020kB and the CIRCUITPY drive +# gets the rest (~1MB). + +# GPIO12-19 are needed for picodvi, but they are all in use here (I2S, I2C, +# LEDs, handle switches) and no pins are broken out. +CIRCUITPY_PICODVI = 0 + +CIRCUITPY__EVE = 1 diff --git a/ports/raspberrypi/boards/teenage_engineering_ep2350/pico-sdk-configboard.h b/ports/raspberrypi/boards/teenage_engineering_ep2350/pico-sdk-configboard.h new file mode 100644 index 00000000000..f72de7902c9 --- /dev/null +++ b/ports/raspberrypi/boards/teenage_engineering_ep2350/pico-sdk-configboard.h @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks +// +// SPDX-License-Identifier: MIT + +// Put board-specific pico-sdk definitions here. This file must exist. diff --git a/ports/raspberrypi/boards/teenage_engineering_ep2350/pins.c b/ports/raspberrypi/boards/teenage_engineering_ep2350/pins.c new file mode 100644 index 00000000000..ed448aa4def --- /dev/null +++ b/ports/raspberrypi/boards/teenage_engineering_ep2350/pins.c @@ -0,0 +1,118 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + // LEDs, one dedicated GPIO each, active high. + // Two columns of four, numbered top (nearest the handle) to bottom. + // Note: GP0 and GP16 share a PWM slice/channel, so the their LEDs + // cannot be PWM-dimmed independently. + { MP_ROM_QSTR(MP_QSTR_GP0), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_LED_WHITE1), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO0) }, + + { MP_ROM_QSTR(MP_QSTR_GP6), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_LED_WHITE2), MP_ROM_PTR(&pin_GPIO6) }, + + { MP_ROM_QSTR(MP_QSTR_GP4), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_LED_WHITE3), MP_ROM_PTR(&pin_GPIO4) }, + + { MP_ROM_QSTR(MP_QSTR_GP5), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_LED_WHITE4), MP_ROM_PTR(&pin_GPIO5) }, + + { MP_ROM_QSTR(MP_QSTR_GP16), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_LED_RED1), MP_ROM_PTR(&pin_GPIO16) }, + + { MP_ROM_QSTR(MP_QSTR_GP24), MP_ROM_PTR(&pin_GPIO24) }, + { MP_ROM_QSTR(MP_QSTR_LED_RED2), MP_ROM_PTR(&pin_GPIO24) }, + + { MP_ROM_QSTR(MP_QSTR_GP18), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_LED_RED3), MP_ROM_PTR(&pin_GPIO18) }, + + { MP_ROM_QSTR(MP_QSTR_GP17), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_LED_RED4), MP_ROM_PTR(&pin_GPIO17) }, + + // Side buttons. Switches to ground, no external pull-ups: use Pull.UP, + // pressed reads False. + { MP_ROM_QSTR(MP_QSTR_GP21), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON_TOP), MP_ROM_PTR(&pin_GPIO21) }, + + { MP_ROM_QSTR(MP_QSTR_GP3), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON_MIDDLE), MP_ROM_PTR(&pin_GPIO3) }, + + { MP_ROM_QSTR(MP_QSTR_GP1), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON_BOTTOM), MP_ROM_PTR(&pin_GPIO1) }, + + // Handle: a two-stage switch. HANDLE_IN reads False when the handle is + // fully seated; HANDLE_OUT reads True as soon as the handle is moved. + { MP_ROM_QSTR(MP_QSTR_GP19), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_HANDLE_IN), MP_ROM_PTR(&pin_GPIO19) }, + + { MP_ROM_QSTR(MP_QSTR_GP20), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_HANDLE_OUT), MP_ROM_PTR(&pin_GPIO20) }, + + // Power hold latch. Held high by the board so the unit stays powered once + // the handle is released. Driving it low powers the unit off immediately. + { MP_ROM_QSTR(MP_QSTR_GP2), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_POWER_HOLD), MP_ROM_PTR(&pin_GPIO2) }, + + // I2C1: NAU88L21 codec at 0x1b, accelerometer at 0x18. External pull-ups. + { MP_ROM_QSTR(MP_QSTR_GP14), MP_ROM_PTR(&pin_GPIO14) }, + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_GPIO14) }, + + { MP_ROM_QSTR(MP_QSTR_GP15), MP_ROM_PTR(&pin_GPIO15) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_GPIO15) }, + + // I2S to the codec. The codec is the I2S clock source (it drives BCLK and + // LRCLK); the MCU only supplies MCLK. + { MP_ROM_QSTR(MP_QSTR_GP8), MP_ROM_PTR(&pin_GPIO8) }, + { MP_ROM_QSTR(MP_QSTR_I2S_DIN), MP_ROM_PTR(&pin_GPIO8) }, + + { MP_ROM_QSTR(MP_QSTR_GP9), MP_ROM_PTR(&pin_GPIO9) }, + { MP_ROM_QSTR(MP_QSTR_I2S_DOUT), MP_ROM_PTR(&pin_GPIO9) }, + + { MP_ROM_QSTR(MP_QSTR_GP10), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_I2S_WS), MP_ROM_PTR(&pin_GPIO10) }, + + { MP_ROM_QSTR(MP_QSTR_GP11), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_I2S_BIT_CLOCK), MP_ROM_PTR(&pin_GPIO11) }, + + { MP_ROM_QSTR(MP_QSTR_GP12), MP_ROM_PTR(&pin_GPIO12) }, + { MP_ROM_QSTR(MP_QSTR_I2S_MCLK), MP_ROM_PTR(&pin_GPIO12) }, + + // Unidentified / unconnected. + { MP_ROM_QSTR(MP_QSTR_GP7), MP_ROM_PTR(&pin_GPIO7) }, + { MP_ROM_QSTR(MP_QSTR_GP13), MP_ROM_PTR(&pin_GPIO13) }, + { MP_ROM_QSTR(MP_QSTR_GP22), MP_ROM_PTR(&pin_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_GP23), MP_ROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_GP25), MP_ROM_PTR(&pin_GPIO25) }, + + // Analog. GP26/GP27 are unconnected. + { 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), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO27) }, + + // Handle position potentiometer: how far the handle has been pressed in. + // Continuous and monotonic over the travel, but it only swings across a + // narrow part of the range, roughly 32370 counts (1.63 V) with the + // handle at rest down to 29850 counts + { 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_HANDLE_POSITION), MP_ROM_PTR(&pin_GPIO28) }, + + // Volume potentiometer wiper, full scale 0 - 3.3V. + { MP_ROM_QSTR(MP_QSTR_GP29), MP_ROM_PTR(&pin_GPIO29) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO29) }, + { MP_ROM_QSTR(MP_QSTR_VOLUME), 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_module_globals_table); diff --git a/ports/raspberrypi/boards/tinycircuits_thumby/board.c b/ports/raspberrypi/boards/tinycircuits_thumby/board.c new file mode 100644 index 00000000000..3a306b35f0d --- /dev/null +++ b/ports/raspberrypi/boards/tinycircuits_thumby/board.c @@ -0,0 +1,81 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Cooper Dalrymple +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" +#include "mpconfigboard.h" + +#include "shared-bindings/busio/SPI.h" +#include "shared-bindings/fourwire/FourWire.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-module/displayio/__init__.h" +#include "shared-module/displayio/mipi_constants.h" +#include "shared-bindings/board/__init__.h" + + +uint8_t display_init_sequence[] = { + 0xAE, 0, // DISPLAY_OFF + 0x20, 1, 0x00, // Set memory addressing to horizontal mode. + 0x81, 1, 0xcf, // set contrast control + 0xA1, 0, // Column 127 is segment 0 + 0xA6, 0, // Normal display + 0xc8, 0, // Normal display + 0xA8, 1, 0x3f, // Mux ratio is 1/64 + 0xd5, 1, 0x80, // Set divide ratio + 0xd9, 1, 0xf1, // Set pre-charge period + 0xda, 1, 0x12, // Set com configuration + 0xdb, 1, 0x40, // Set vcom configuration + 0x8d, 1, 0x14, // Enable charge pump + 0xAF, 0, // DISPLAY_ON +}; + +void board_init(void) { + busio_spi_obj_t *spi = common_hal_board_create_spi(0); + fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; + bus->base.type = &fourwire_fourwire_type; + common_hal_fourwire_fourwire_construct(bus, + spi, + MP_OBJ_FROM_PTR(CIRCUITPY_BOARD_OLED_DC), // Command or data + MP_OBJ_FROM_PTR(CIRCUITPY_BOARD_OLED_CS), // Chip select + MP_OBJ_FROM_PTR(CIRCUITPY_BOARD_OLED_RESET), // Reset + 10000000, // Baudrate + 0, // Polarity + 0); // Phase + + busdisplay_busdisplay_obj_t *display = &allocate_display()->display; + display->base.type = &busdisplay_busdisplay_type; + common_hal_busdisplay_busdisplay_construct( + display, + bus, + 72, // Width (after rotation) + 40, // Height (after rotation) + 28, // column start + 28, // row start + 0, // rotation + 1, // Color depth + true, // grayscale + false, // pixels in byte share 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 + 0x21, // Set column command + 0x22, // Set row command + 44, // Write memory command + display_init_sequence, + sizeof(display_init_sequence), + NULL, // backlight pin + 0x81, + 1.0f, // brightness + true, // single_byte_bounds + true, // data_as_commands + true, // auto_refresh + 60, // native_frames_per_second + true, // backlight_on_high + false, // SH1107_addressing + 0); // backlight pwm frequency +} + +void reset_board(void) { +} diff --git a/ports/raspberrypi/boards/tinycircuits_thumby/mpconfigboard.h b/ports/raspberrypi/boards/tinycircuits_thumby/mpconfigboard.h new file mode 100644 index 00000000000..cec0fc10f55 --- /dev/null +++ b/ports/raspberrypi/boards/tinycircuits_thumby/mpconfigboard.h @@ -0,0 +1,20 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Cooper Dalrymple +// +// SPDX-License-Identifier: MIT + +#pragma once + +#define MICROPY_HW_BOARD_NAME "TinyCircuits Thumby" +#define MICROPY_HW_MCU_NAME "rp2040" + +#define DEFAULT_SPI_BUS_SCK (&pin_GPIO18) +#define DEFAULT_SPI_BUS_MOSI (&pin_GPIO19) + +#define CIRCUITPY_BOARD_OLED_DC (&pin_GPIO17) +#define CIRCUITPY_BOARD_OLED_CS (&pin_GPIO16) +#define CIRCUITPY_BOARD_OLED_RESET (&pin_GPIO20) + +#define CIRCUITPY_BOARD_SPI (1) +#define CIRCUITPY_BOARD_SPI_PIN {{.clock = DEFAULT_SPI_BUS_SCK, .mosi = DEFAULT_SPI_BUS_MOSI, .miso = NULL}} diff --git a/ports/raspberrypi/boards/tinycircuits_thumby/mpconfigboard.mk b/ports/raspberrypi/boards/tinycircuits_thumby/mpconfigboard.mk new file mode 100644 index 00000000000..d8140e6cb0a --- /dev/null +++ b/ports/raspberrypi/boards/tinycircuits_thumby/mpconfigboard.mk @@ -0,0 +1,18 @@ +USB_VID = 0x1209 +USB_PID = 0x3500 +USB_PRODUCT = "Thumby" +USB_MANUFACTURER = "TinyCircuits" + +CHIP_VARIANT = RP2040 +CHIP_FAMILY = rp2 + +EXTERNAL_FLASH_DEVICES = "W25Q16JVxQ" + +CIRCUITPY_STAGE = 1 +CIRCUITPY_AUDIOIO = 1 +CIRCUITPY_AUDIOPWMIO = 1 +CIRCUITPY_KEYPAD = 1 + +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_framebuf +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_SSD1306 +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_DisplayIO_SSD1306 diff --git a/ports/raspberrypi/boards/tinycircuits_thumby/pico-sdk-configboard.h b/ports/raspberrypi/boards/tinycircuits_thumby/pico-sdk-configboard.h new file mode 100644 index 00000000000..ce5a7645b4e --- /dev/null +++ b/ports/raspberrypi/boards/tinycircuits_thumby/pico-sdk-configboard.h @@ -0,0 +1,12 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Put board-specific pico-sdk definitions here. This file must exist. + +// Allow extra time for xosc to start. +#define PICO_XOSC_STARTUP_DELAY_MULTIPLIER 64 diff --git a/ports/raspberrypi/boards/tinycircuits_thumby/pins.c b/ports/raspberrypi/boards/tinycircuits_thumby/pins.c new file mode 100644 index 00000000000..0a087bb8db8 --- /dev/null +++ b/ports/raspberrypi/boards/tinycircuits_thumby/pins.c @@ -0,0 +1,48 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Cooper Dalrymple +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" +#include "shared-module/displayio/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + // Link Cable (ASR00074) + { MP_ROM_QSTR(MP_QSTR_EXT_TX), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_EXT), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_EXT_PU), MP_ROM_PTR(&pin_GPIO1) }, + + // 0.42 inch OLED AST1042 + { MP_ROM_QSTR(MP_QSTR_OLED_CS), MP_ROM_PTR(CIRCUITPY_BOARD_OLED_CS) }, + { MP_ROM_QSTR(MP_QSTR_OLED_DC), MP_ROM_PTR(CIRCUITPY_BOARD_OLED_DC) }, + { MP_ROM_QSTR(MP_QSTR_OLED_RESET), MP_ROM_PTR(CIRCUITPY_BOARD_OLED_RESET) }, + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(DEFAULT_SPI_BUS_SCK) }, + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(DEFAULT_SPI_BUS_MOSI) }, + + { MP_ROM_QSTR(MP_QSTR_SPI), MP_ROM_PTR(&board_spi_obj) }, + { MP_ROM_QSTR(MP_QSTR_DISPLAY), MP_ROM_PTR(&displays[0].display)}, + + // Buttons + { MP_ROM_QSTR(MP_QSTR_BUTTON_LEFT), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON_UP), MP_ROM_PTR(&pin_GPIO4) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON_RIGHT), MP_ROM_PTR(&pin_GPIO5) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON_DOWN), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON_1), MP_ROM_PTR(&pin_GPIO24) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON_2), MP_ROM_PTR(&pin_GPIO27) }, + + // Mono PWM Speaker + { MP_ROM_QSTR(MP_QSTR_SPEAKER), MP_ROM_PTR(&pin_GPIO28) }, + + // Hardware revision ID pins + { MP_OBJ_NEW_QSTR(MP_QSTR_ID3), MP_ROM_PTR(&pin_GPIO12) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_ID2), MP_ROM_PTR(&pin_GPIO13) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_ID1), MP_ROM_PTR(&pin_GPIO14) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_ID0), MP_ROM_PTR(&pin_GPIO15) }, + + // Power pins + { MP_ROM_QSTR(MP_QSTR_VBUS_SENSE), MP_ROM_PTR(&pin_GPIO26) } +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/raspberrypi/boards/tinycircuits_thumby_color/board.c b/ports/raspberrypi/boards/tinycircuits_thumby_color/board.c new file mode 100644 index 00000000000..b9d5ddfe3e5 --- /dev/null +++ b/ports/raspberrypi/boards/tinycircuits_thumby_color/board.c @@ -0,0 +1,106 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Cooper Dalrymple +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" +#include "mpconfigboard.h" +#include "shared-bindings/busio/SPI.h" +#include "shared-bindings/fourwire/FourWire.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-module/displayio/__init__.h" +#include "shared-module/displayio/mipi_constants.h" +#include "shared-bindings/board/__init__.h" + + +#define DELAY 0x80 + +// display init sequence according to TinyCircuits-Tiny-Game-Engine +uint8_t display_init_sequence[] = { + 0xFE, 0, // inter register enable 1 + 0xEF, 0, // inter register enable 2 + 0xB0, 1, 0xC0, + 0xB1, 1, 0x80, + 0xB2, 1, 0x2F, + 0xB3, 1, 0x03, + 0xB7, 1, 0x01, + 0xB6, 1, 0x19, + 0xAC, 1, 0xC8, // Complement Principle of RGB 5, 6, 5 + 0xAB, 1, 0x0f, // ? + 0x3A, 1, 0x05, // COLMOD: Pixel Format Set + 0xB4, 1, 0x04, // ? + 0xA8, 1, 0x07, // Frame Rate Set + 0xB8, 1, 0x08, // ? + 0xE7, 1, 0x5A, // VREG_CTL + 0xE8, 1, 0x23, // VGH_SET + 0xE9, 1, 0x47, // VGL_SET + 0xEA, 1, 0x99, // VGH_VGL_CLK + 0xC6, 1, 0x30, // ? + 0xC7, 1, 0x1F, // ? + 0xF0, 14, 0x05, 0x1D, 0x51, 0x2F, 0x85, 0x2A, 0x11, 0x62, 0x00, 0x07, 0x07, 0x0F, 0x08, 0x1F, // SET_GAMMA1 + 0xF1, 14, 0x2E, 0x41, 0x62, 0x56, 0xA5, 0x3A, 0x3f, 0x60, 0x0F, 0x07, 0x0A, 0x18, 0x18, 0x1D, // SET_GAMMA2 + 0x11, 0 | DELAY, 120, + 0x29, 0 | DELAY, 10, // display on +}; + +void board_init(void) { + fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; + busio_spi_obj_t *spi = &bus->inline_bus; + common_hal_busio_spi_construct( + spi, + DEFAULT_SPI_BUS_SCK, // CLK + DEFAULT_SPI_BUS_MOSI, // MOSI + NULL, // MISO not connected + false // Not half-duplex + ); + + bus->base.type = &fourwire_fourwire_type; + + common_hal_fourwire_fourwire_construct( + bus, + spi, + MP_OBJ_FROM_PTR(CIRCUITPY_BOARD_LCD_DC), // DC + MP_OBJ_FROM_PTR(CIRCUITPY_BOARD_LCD_CS), // CS + MP_OBJ_FROM_PTR(CIRCUITPY_BOARD_LCD_RESET), // RST + 80000000, // baudrate + 0, // polarity + 0 // phase + ); + + busdisplay_busdisplay_obj_t *display = &allocate_display()->display; + display->base.type = &busdisplay_busdisplay_type; + common_hal_busdisplay_busdisplay_construct( + display, + bus, + 128, // width (after rotation) + 128, // height (after rotation) + 0, // column start + 0, // row start + 0, // 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 + display_init_sequence, + sizeof(display_init_sequence), + CIRCUITPY_BOARD_LCD_BACKLIGHT, // backlight pin + NO_BRIGHTNESS_COMMAND, + 1.0f, // brightness + false, // single_byte_bounds + false, // data_as_commands + true, // auto_refresh + 60, // native_frames_per_second + true, // backlight_on_high + false, // SH1107_addressing + 50000 // backlight pwm frequency + ); +} + +void reset_board(void) { +} diff --git a/ports/raspberrypi/boards/tinycircuits_thumby_color/mpconfigboard.h b/ports/raspberrypi/boards/tinycircuits_thumby_color/mpconfigboard.h new file mode 100644 index 00000000000..fc76138bb8a --- /dev/null +++ b/ports/raspberrypi/boards/tinycircuits_thumby_color/mpconfigboard.h @@ -0,0 +1,27 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Cooper Dalrymple +// +// SPDX-License-Identifier: MIT + +#pragma once + +#define MICROPY_HW_BOARD_NAME "TinyCircuits Thumby Color" +#define MICROPY_HW_MCU_NAME "rp2350" + +#define DEFAULT_I2C_BUS_SCL (&pin_GPIO9) +#define DEFAULT_I2C_BUS_SDA (&pin_GPIO8) + +#define CIRCUITPY_BOARD_I2C (1) +#define CIRCUITPY_BOARD_I2C_PIN {{.scl = DEFAULT_I2C_BUS_SCL, .sda = DEFAULT_I2C_BUS_SDA}} + +#define DEFAULT_SPI_BUS_SCK (&pin_GPIO18) +#define DEFAULT_SPI_BUS_MOSI (&pin_GPIO19) + +#define CIRCUITPY_BOARD_LCD_DC (&pin_GPIO16) +#define CIRCUITPY_BOARD_LCD_CS (&pin_GPIO17) +#define CIRCUITPY_BOARD_LCD_RESET (&pin_GPIO4) +#define CIRCUITPY_BOARD_LCD_BACKLIGHT (&pin_GPIO7) + +#define CIRCUITPY_BOARD_SPI (1) +#define CIRCUITPY_BOARD_SPI_PIN {{.clock = DEFAULT_SPI_BUS_SCK, .mosi = DEFAULT_SPI_BUS_MOSI, .miso = NULL}} diff --git a/ports/raspberrypi/boards/tinycircuits_thumby_color/mpconfigboard.mk b/ports/raspberrypi/boards/tinycircuits_thumby_color/mpconfigboard.mk new file mode 100644 index 00000000000..6159a39ba55 --- /dev/null +++ b/ports/raspberrypi/boards/tinycircuits_thumby_color/mpconfigboard.mk @@ -0,0 +1,18 @@ +USB_VID = 0x1209 +USB_PID = 0x3501 +USB_PRODUCT = "Thumby Color" +USB_MANUFACTURER = "TinyCircuits" + +CHIP_VARIANT = RP2350 +CHIP_PACKAGE = A +CHIP_FAMILY = rp2 + +EXTERNAL_FLASH_DEVICES = "W25Q128JVxQ" + +CIRCUITPY_STAGE = 1 +CIRCUITPY_AUDIOIO = 1 +CIRCUITPY_AUDIOPWMIO = 1 +CIRCUITPY_KEYPAD = 1 + +# GPIO12-19 needed for picodvi, but many are not available. +CIRCUITPY_PICODVI = 0 diff --git a/ports/raspberrypi/boards/tinycircuits_thumby_color/pico-sdk-configboard.h b/ports/raspberrypi/boards/tinycircuits_thumby_color/pico-sdk-configboard.h new file mode 100644 index 00000000000..110195b7794 --- /dev/null +++ b/ports/raspberrypi/boards/tinycircuits_thumby_color/pico-sdk-configboard.h @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Put board-specific pico-sdk definitions here. This file must exist. diff --git a/ports/raspberrypi/boards/tinycircuits_thumby_color/pins.c b/ports/raspberrypi/boards/tinycircuits_thumby_color/pins.c new file mode 100644 index 00000000000..d0e63512d7a --- /dev/null +++ b/ports/raspberrypi/boards/tinycircuits_thumby_color/pins.c @@ -0,0 +1,58 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Cooper Dalrymple +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" +#include "shared-module/displayio/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + // Buttons + { MP_ROM_QSTR(MP_QSTR_BUTTON_UP), MP_ROM_PTR(&pin_GPIO1) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON_LEFT), MP_ROM_PTR(&pin_GPIO0) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON_DOWN), MP_ROM_PTR(&pin_GPIO3) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON_RIGHT), MP_ROM_PTR(&pin_GPIO2) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON_A), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON_B), MP_ROM_PTR(&pin_GPIO25) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON_BUMPER_LEFT), MP_ROM_PTR(&pin_GPIO6) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON_BUMPER_RIGHT), MP_ROM_PTR(&pin_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON_MENU), MP_ROM_PTR(&pin_GPIO26) }, + + // LED + { MP_ROM_QSTR(MP_QSTR_LED_R), MP_ROM_PTR(&pin_GPIO11) }, + { MP_ROM_QSTR(MP_QSTR_LED_G), MP_ROM_PTR(&pin_GPIO10) }, + { MP_ROM_QSTR(MP_QSTR_LED_B), MP_ROM_PTR(&pin_GPIO12) }, + + // Rumble + { MP_ROM_QSTR(MP_QSTR_RUMBLE), MP_ROM_PTR(&pin_GPIO5) }, + + // Mono PWM Speaker + { MP_ROM_QSTR(MP_QSTR_SPEAKER), MP_ROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_SPEAKER_ENABLE), MP_ROM_PTR(&pin_GPIO20) }, + + // 0.85 inch TFT GC9107 + { MP_ROM_QSTR(MP_QSTR_LCD_CS), MP_ROM_PTR(CIRCUITPY_BOARD_LCD_CS) }, + { MP_ROM_QSTR(MP_QSTR_LCD_DC), MP_ROM_PTR(CIRCUITPY_BOARD_LCD_DC) }, + { MP_ROM_QSTR(MP_QSTR_LCD_RESET), MP_ROM_PTR(CIRCUITPY_BOARD_LCD_RESET) }, + { MP_ROM_QSTR(MP_QSTR_LCD_BACKLIGHT), MP_ROM_PTR(CIRCUITPY_BOARD_LCD_BACKLIGHT) }, + { MP_ROM_QSTR(MP_QSTR_LCD_SCK), MP_ROM_PTR(DEFAULT_SPI_BUS_SCK) }, + { MP_ROM_QSTR(MP_QSTR_LCD_MOSI), MP_ROM_PTR(DEFAULT_SPI_BUS_MOSI) }, + + { MP_ROM_QSTR(MP_QSTR_DISPLAY), MP_ROM_PTR(&displays[0].display) }, + { MP_ROM_QSTR(MP_QSTR_LCD_SPI), MP_ROM_PTR(&board_spi_obj) }, + + // RTC I2C + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(DEFAULT_I2C_BUS_SDA) }, + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(DEFAULT_I2C_BUS_SCL) }, + + { MP_ROM_QSTR(MP_QSTR_I2C), MP_ROM_PTR(&board_i2c_obj) }, + + // Power pins + { MP_ROM_QSTR(MP_QSTR_CHARGE_STAT), MP_ROM_PTR(&pin_GPIO24) }, + { MP_ROM_QSTR(MP_QSTR_VOLTAGE_MONITOR), MP_ROM_PTR(&pin_GPIO29) }, + +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/raspberrypi/boards/ugame22/board.c b/ports/raspberrypi/boards/ugame22/board.c index 6b8152b14ee..e5ac867843c 100644 --- a/ports/raspberrypi/boards/ugame22/board.c +++ b/ports/raspberrypi/boards/ugame22/board.c @@ -47,14 +47,13 @@ void board_init(void) { fourwire_fourwire_obj_t *bus = &allocate_display_bus()->fourwire_bus; busio_spi_obj_t *spi = &bus->inline_bus; common_hal_busio_spi_construct(spi, &pin_GPIO2, &pin_GPIO3, NULL, false); - common_hal_busio_spi_never_reset(spi); bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct(bus, spi, - &pin_GPIO4, // TFT_DC Command or data - &pin_GPIO5, // TFT_CS Chip select - &pin_GPIO1, // TFT_RST Reset + MP_OBJ_FROM_PTR(&pin_GPIO4), // TFT_DC Command or data + MP_OBJ_FROM_PTR(&pin_GPIO5), // TFT_CS Chip select + MP_OBJ_FROM_PTR(&pin_GPIO1), // TFT_RST Reset 80000000L, // Baudrate 0, // Polarity 0); // Phase diff --git a/ports/raspberrypi/boards/waveshare_rp2040_geek/board.c b/ports/raspberrypi/boards/waveshare_rp2040_geek/board.c index 71269f0d185..431840fb0c5 100644 --- a/ports/raspberrypi/boards/waveshare_rp2040_geek/board.c +++ b/ports/raspberrypi/boards/waveshare_rp2040_geek/board.c @@ -37,9 +37,9 @@ static void display_init(void) { common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO8, // TFT_DC - &pin_GPIO9, // TFT_CS - &pin_GPIO12, // TFT_RST + MP_OBJ_FROM_PTR(&pin_GPIO8), // TFT_DC + MP_OBJ_FROM_PTR(&pin_GPIO9), // TFT_CS + MP_OBJ_FROM_PTR(&pin_GPIO12), // TFT_RST 50000000, // Baudrate 0, // Polarity 0 // Phase diff --git a/ports/raspberrypi/boards/waveshare_rp2040_lcd_0_96/board.c b/ports/raspberrypi/boards/waveshare_rp2040_lcd_0_96/board.c index f17ca53d724..5ae4171eac0 100644 --- a/ports/raspberrypi/boards/waveshare_rp2040_lcd_0_96/board.c +++ b/ports/raspberrypi/boards/waveshare_rp2040_lcd_0_96/board.c @@ -53,16 +53,14 @@ static void display_init(void) { false // Not half-duplex ); - common_hal_busio_spi_never_reset(spi); - bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO8, // DC - &pin_GPIO9, // CS - &pin_GPIO12, // RST + MP_OBJ_FROM_PTR(&pin_GPIO8), // DC + MP_OBJ_FROM_PTR(&pin_GPIO9), // CS + MP_OBJ_FROM_PTR(&pin_GPIO12), // RST 40000000, // baudrate 0, // polarity 0 // phase diff --git a/ports/raspberrypi/boards/waveshare_rp2350_geek/board.c b/ports/raspberrypi/boards/waveshare_rp2350_geek/board.c index 71269f0d185..431840fb0c5 100644 --- a/ports/raspberrypi/boards/waveshare_rp2350_geek/board.c +++ b/ports/raspberrypi/boards/waveshare_rp2350_geek/board.c @@ -37,9 +37,9 @@ static void display_init(void) { common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO8, // TFT_DC - &pin_GPIO9, // TFT_CS - &pin_GPIO12, // TFT_RST + MP_OBJ_FROM_PTR(&pin_GPIO8), // TFT_DC + MP_OBJ_FROM_PTR(&pin_GPIO9), // TFT_CS + MP_OBJ_FROM_PTR(&pin_GPIO12), // TFT_RST 50000000, // Baudrate 0, // Polarity 0 // Phase diff --git a/ports/raspberrypi/boards/waveshare_rp2350_geek/mpconfigboard.mk b/ports/raspberrypi/boards/waveshare_rp2350_geek/mpconfigboard.mk index 38b69c182c7..e1d89c1fbca 100644 --- a/ports/raspberrypi/boards/waveshare_rp2350_geek/mpconfigboard.mk +++ b/ports/raspberrypi/boards/waveshare_rp2350_geek/mpconfigboard.mk @@ -10,3 +10,6 @@ CHIP_FAMILY = rp2 EXTERNAL_FLASH_DEVICES = "W25Q128JVxQ" CIRCUITPY__EVE = 1 + +# GPIO12-19 needed for picodvi, but many of the pins are used for other purposes. +CIRCUITPY_PICODVI = 0 diff --git a/ports/raspberrypi/boards/waveshare_rp2350_lcd_0_96/board.c b/ports/raspberrypi/boards/waveshare_rp2350_lcd_0_96/board.c index f17ca53d724..5ae4171eac0 100644 --- a/ports/raspberrypi/boards/waveshare_rp2350_lcd_0_96/board.c +++ b/ports/raspberrypi/boards/waveshare_rp2350_lcd_0_96/board.c @@ -53,16 +53,14 @@ static void display_init(void) { false // Not half-duplex ); - common_hal_busio_spi_never_reset(spi); - bus->base.type = &fourwire_fourwire_type; common_hal_fourwire_fourwire_construct( bus, spi, - &pin_GPIO8, // DC - &pin_GPIO9, // CS - &pin_GPIO12, // RST + MP_OBJ_FROM_PTR(&pin_GPIO8), // DC + MP_OBJ_FROM_PTR(&pin_GPIO9), // CS + MP_OBJ_FROM_PTR(&pin_GPIO12), // RST 40000000, // baudrate 0, // polarity 0 // phase diff --git a/ports/raspberrypi/boards/waveshare_rp2350_lcd_1_28/mpconfigboard.mk b/ports/raspberrypi/boards/waveshare_rp2350_lcd_1_28/mpconfigboard.mk index 8f703c5a932..f04b91f8b0d 100644 --- a/ports/raspberrypi/boards/waveshare_rp2350_lcd_1_28/mpconfigboard.mk +++ b/ports/raspberrypi/boards/waveshare_rp2350_lcd_1_28/mpconfigboard.mk @@ -11,6 +11,9 @@ EXTERNAL_FLASH_DEVICES = "P25Q32SH" CIRCUITPY__EVE = 1 +# GPIO12-19 needed for picodvi, but GPIO12 is used for display reset. +CIRCUITPY_PICODVI = 0 + # TODO: Add custom QMI8658 driver # FROZEN_MPY_DIRS += $(TOP)/frozen/circuitpython_qmi8658 diff --git a/ports/raspberrypi/boards/waveshare_rp2350_one/mpconfigboard.mk b/ports/raspberrypi/boards/waveshare_rp2350_one/mpconfigboard.mk index 75398b3269b..bde7153c029 100644 --- a/ports/raspberrypi/boards/waveshare_rp2350_one/mpconfigboard.mk +++ b/ports/raspberrypi/boards/waveshare_rp2350_one/mpconfigboard.mk @@ -10,3 +10,6 @@ CHIP_FAMILY = rp2 EXTERNAL_FLASH_DEVICES = "W25Q32JVxQ" CIRCUITPY__EVE = 1 + +# GPIO12-19 needed for picodvi, but GPIO16 is not broken out and is used for NeoPixel. +CIRCUITPY_PICODVI = 0 diff --git a/ports/raspberrypi/boards/waveshare_rp2350_tiny/mpconfigboard.mk b/ports/raspberrypi/boards/waveshare_rp2350_tiny/mpconfigboard.mk index 464c7aff283..79fafbacf5c 100644 --- a/ports/raspberrypi/boards/waveshare_rp2350_tiny/mpconfigboard.mk +++ b/ports/raspberrypi/boards/waveshare_rp2350_tiny/mpconfigboard.mk @@ -10,3 +10,6 @@ CHIP_FAMILY = rp2 EXTERNAL_FLASH_DEVICES = "P25Q32SH" CIRCUITPY__EVE = 1 + +# GPIO12-19 needed for picodvi, but GPIO16-19 are not available. +CIRCUITPY_PICODVI = 0 diff --git a/ports/raspberrypi/boards/waveshare_rp2350_touch_lcd_1_28/mpconfigboard.mk b/ports/raspberrypi/boards/waveshare_rp2350_touch_lcd_1_28/mpconfigboard.mk index 11e927c7485..0ec6c4ec008 100644 --- a/ports/raspberrypi/boards/waveshare_rp2350_touch_lcd_1_28/mpconfigboard.mk +++ b/ports/raspberrypi/boards/waveshare_rp2350_touch_lcd_1_28/mpconfigboard.mk @@ -11,6 +11,9 @@ EXTERNAL_FLASH_DEVICES = "W25Q128JVxQ" CIRCUITPY__EVE = 1 +# GPIO12-19 needed for picodvi, but GPIO12 is used for display reset. +CIRCUITPY_PICODVI = 0 + # TODO: Add custom QMI8658 driver # FROZEN_MPY_DIRS += $(TOP)/frozen/circuitpython_qmi8658 diff --git a/ports/raspberrypi/boards/waveshare_rp2350_zero/mpconfigboard.mk b/ports/raspberrypi/boards/waveshare_rp2350_zero/mpconfigboard.mk index 444850776a6..7f0a3c71cbb 100644 --- a/ports/raspberrypi/boards/waveshare_rp2350_zero/mpconfigboard.mk +++ b/ports/raspberrypi/boards/waveshare_rp2350_zero/mpconfigboard.mk @@ -10,3 +10,6 @@ CHIP_FAMILY = rp2 EXTERNAL_FLASH_DEVICES = "P25Q32SH" CIRCUITPY__EVE = 1 + +# GPIO12-19 needed for picodvi, but GPIO16 is not broken out and is used for NeoPixel. +CIRCUITPY_PICODVI = 0 diff --git a/ports/raspberrypi/boards/weact_studio_rp2350b_core/board.c b/ports/raspberrypi/boards/weact_studio_rp2350b_core/board.c new file mode 100644 index 00000000000..e6a868ab212 --- /dev/null +++ b/ports/raspberrypi/boards/weact_studio_rp2350b_core/board.c @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/raspberrypi/boards/weact_studio_rp2350b_core/mpconfigboard.h b/ports/raspberrypi/boards/weact_studio_rp2350b_core/mpconfigboard.h new file mode 100644 index 00000000000..95a81334c73 --- /dev/null +++ b/ports/raspberrypi/boards/weact_studio_rp2350b_core/mpconfigboard.h @@ -0,0 +1,10 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#define MICROPY_HW_BOARD_NAME "WeAct Studio RP2350B Core" +#define MICROPY_HW_MCU_NAME "rp2350b" + +#define CIRCUITPY_PSRAM_CHIP_SELECT (&pin_GPIO0) diff --git a/ports/raspberrypi/boards/weact_studio_rp2350b_core/mpconfigboard.mk b/ports/raspberrypi/boards/weact_studio_rp2350b_core/mpconfigboard.mk new file mode 100644 index 00000000000..d86f28280f3 --- /dev/null +++ b/ports/raspberrypi/boards/weact_studio_rp2350b_core/mpconfigboard.mk @@ -0,0 +1,12 @@ +USB_VID = 0x1209 +USB_PID = 0xDEC1 +USB_PRODUCT = "RP2350B Core" +USB_MANUFACTURER = "WeAct Studio" + +CHIP_VARIANT = RP2350 +CHIP_PACKAGE = B +CHIP_FAMILY = rp2 + +EXTERNAL_FLASH_DEVICES = "W25Q128JVxQ" + +CIRCUITPY__EVE = 1 diff --git a/ports/raspberrypi/boards/weact_studio_rp2350b_core/pico-sdk-configboard.h b/ports/raspberrypi/boards/weact_studio_rp2350b_core/pico-sdk-configboard.h new file mode 100644 index 00000000000..66b57dfd13d --- /dev/null +++ b/ports/raspberrypi/boards/weact_studio_rp2350b_core/pico-sdk-configboard.h @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// Put board-specific pico-sdk definitions here. This file must exist. diff --git a/ports/raspberrypi/boards/weact_studio_rp2350b_core/pins.c b/ports/raspberrypi/boards/weact_studio_rp2350b_core/pins.c new file mode 100644 index 00000000000..d6a82becfdd --- /dev/null +++ b/ports/raspberrypi/boards/weact_studio_rp2350b_core/pins.c @@ -0,0 +1,91 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { 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_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_GP23), MP_ROM_PTR(&pin_GPIO23) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_BUTTON), MP_ROM_PTR(&pin_GPIO23) }, + + { MP_ROM_QSTR(MP_QSTR_GP24), MP_ROM_PTR(&pin_GPIO24) }, + + { MP_ROM_QSTR(MP_QSTR_GP25), MP_ROM_PTR(&pin_GPIO25) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO25) }, + + { MP_ROM_QSTR(MP_QSTR_GP26), MP_ROM_PTR(&pin_GPIO26) }, + { MP_ROM_QSTR(MP_QSTR_GP27), MP_ROM_PTR(&pin_GPIO27) }, + { MP_ROM_QSTR(MP_QSTR_GP28), MP_ROM_PTR(&pin_GPIO28) }, + { MP_ROM_QSTR(MP_QSTR_GP29), MP_ROM_PTR(&pin_GPIO29) }, + { MP_ROM_QSTR(MP_QSTR_GP30), MP_ROM_PTR(&pin_GPIO30) }, + { MP_ROM_QSTR(MP_QSTR_GP31), MP_ROM_PTR(&pin_GPIO31) }, + { MP_ROM_QSTR(MP_QSTR_GP32), MP_ROM_PTR(&pin_GPIO32) }, + { MP_ROM_QSTR(MP_QSTR_GP33), MP_ROM_PTR(&pin_GPIO33) }, + { MP_ROM_QSTR(MP_QSTR_GP34), MP_ROM_PTR(&pin_GPIO34) }, + { MP_ROM_QSTR(MP_QSTR_GP35), MP_ROM_PTR(&pin_GPIO35) }, + { MP_ROM_QSTR(MP_QSTR_GP36), MP_ROM_PTR(&pin_GPIO36) }, + { MP_ROM_QSTR(MP_QSTR_GP37), MP_ROM_PTR(&pin_GPIO37) }, + { MP_ROM_QSTR(MP_QSTR_GP38), MP_ROM_PTR(&pin_GPIO38) }, + { MP_ROM_QSTR(MP_QSTR_GP39), MP_ROM_PTR(&pin_GPIO39) }, + + { MP_ROM_QSTR(MP_QSTR_GP40), MP_ROM_PTR(&pin_GPIO40) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_GPIO40) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_GP40_A0), MP_ROM_PTR(&pin_GPIO40) }, + + { MP_ROM_QSTR(MP_QSTR_GP41), MP_ROM_PTR(&pin_GPIO41) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_GPIO41) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_GP41_A1), MP_ROM_PTR(&pin_GPIO41) }, + + { MP_ROM_QSTR(MP_QSTR_GP42), MP_ROM_PTR(&pin_GPIO42) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_GPIO42) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_GP42_A2), MP_ROM_PTR(&pin_GPIO42) }, + + { MP_ROM_QSTR(MP_QSTR_GP43), MP_ROM_PTR(&pin_GPIO43) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO43) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_GP43_A3), MP_ROM_PTR(&pin_GPIO43) }, + + { MP_ROM_QSTR(MP_QSTR_GP44), MP_ROM_PTR(&pin_GPIO44) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_GPIO44) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_GP44_A4), MP_ROM_PTR(&pin_GPIO44) }, + + { MP_ROM_QSTR(MP_QSTR_GP45), MP_ROM_PTR(&pin_GPIO45) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_GPIO45) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_GP45_A5), MP_ROM_PTR(&pin_GPIO45) }, + + { MP_ROM_QSTR(MP_QSTR_GP46), MP_ROM_PTR(&pin_GPIO46) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_A6), MP_ROM_PTR(&pin_GPIO46) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_GP46_A6), MP_ROM_PTR(&pin_GPIO46) }, + + { MP_ROM_QSTR(MP_QSTR_GP47), MP_ROM_PTR(&pin_GPIO47) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_A7), MP_ROM_PTR(&pin_GPIO47) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_GP47_A7), MP_ROM_PTR(&pin_GPIO47) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/raspberrypi/boards/weenoisemakers_noisenugget/_aic3105.py b/ports/raspberrypi/boards/weenoisemakers_noisenugget/_aic3105.py new file mode 100644 index 00000000000..06923e374b7 --- /dev/null +++ b/ports/raspberrypi/boards/weenoisemakers_noisenugget/_aic3105.py @@ -0,0 +1,564 @@ +from adafruit_bus_device import i2c_device + +import time + +# Page select register +AIC3X_PAGE_SELECT = 0 +# Software reset register +AIC3X_RESET = 1 +# Codec Sample rate select register +AIC3X_SAMPLE_RATE_SEL_REG = 2 +# PLL progrramming register A +AIC3X_PLL_PROGA_REG = 3 +# PLL progrramming register B +AIC3X_PLL_PROGB_REG = 4 +# PLL progrramming register C +AIC3X_PLL_PROGC_REG = 5 +# PLL progrramming register D +AIC3X_PLL_PROGD_REG = 6 +# Codec datapath setup register +AIC3X_CODEC_DATAPATH_REG = 7 +# Audio serial data interface control register A +AIC3X_ASD_INTF_CTRLA = 8 +# Audio serial data interface control register B +AIC3X_ASD_INTF_CTRLB = 9 +# Audio serial data interface control register C +AIC3X_ASD_INTF_CTRLC = 10 +# Audio overflow status and PLL R value programming register +AIC3X_OVRF_STATUS_AND_PLLR_REG = 11 +# Audio codec digital filter control register +AIC3X_CODEC_DFILT_CTRL = 12 +# Headset/button press detection register +AIC3X_HEADSET_DETECT_CTRL_A = 13 +AIC3X_HEADSET_DETECT_CTRL_B = 14 +# ADC PGA Gain control registers +LADC_VOL = 15 +RADC_VOL = 16 +# MIC3 control registers +MIC3LR_2_LADC_CTRL = 17 +MIC3LR_2_RADC_CTRL = 18 +# Line1 Input control registers +LINE1L_2_LADC_CTRL = 19 +LINE1R_2_LADC_CTRL = 21 +LINE1R_2_RADC_CTRL = 22 +LINE1L_2_RADC_CTRL = 24 +# Line2 Input control registers +LINE2L_2_LADC_CTRL = 20 +LINE2R_2_RADC_CTRL = 23 +# MICBIAS Control Register +MICBIAS_CTRL = 25 + +# AGC Control Registers A, B, C +LAGC_CTRL_A = 26 +LAGC_CTRL_B = 27 +LAGC_CTRL_C = 28 +RAGC_CTRL_A = 29 +RAGC_CTRL_B = 30 +RAGC_CTRL_C = 31 + +# DAC Power and Left High Power Output control registers +DAC_PWR = 37 +HPLCOM_CFG = 37 +# Right High Power Output control registers +HPRCOM_CFG = 38 +# High Power Output Stage Control Register +HPOUT_SC = 40 +# DAC Output Switching control registers +DAC_LINE_MUX = 41 +# High Power Output Driver Pop Reduction registers +HPOUT_POP_REDUCTION = 42 +# DAC Digital control registers +LDAC_VOL = 43 +RDAC_VOL = 44 +# Left High Power Output control registers +LINE2L_2_HPLOUT_VOL = 45 +PGAL_2_HPLOUT_VOL = 46 +DACL1_2_HPLOUT_VOL = 47 +LINE2R_2_HPLOUT_VOL = 48 +PGAR_2_HPLOUT_VOL = 49 +DACR1_2_HPLOUT_VOL = 50 +HPLOUT_CTRL = 51 +# Left High Power COM control registers +LINE2L_2_HPLCOM_VOL = 52 +PGAL_2_HPLCOM_VOL = 53 +DACL1_2_HPLCOM_VOL = 54 +LINE2R_2_HPLCOM_VOL = 55 +PGAR_2_HPLCOM_VOL = 56 +DACR1_2_HPLCOM_VOL = 57 +HPLCOM_CTRL = 58 +# Right High Power Output control registers +LINE2L_2_HPROUT_VOL = 59 +PGAL_2_HPROUT_VOL = 60 +DACL1_2_HPROUT_VOL = 61 +LINE2R_2_HPROUT_VOL = 62 +PGAR_2_HPROUT_VOL = 63 +DACR1_2_HPROUT_VOL = 64 +HPROUT_CTRL = 65 +# Right High Power COM control registers +LINE2L_2_HPRCOM_VOL = 66 +PGAL_2_HPRCOM_VOL = 67 +DACL1_2_HPRCOM_VOL = 68 +LINE2R_2_HPRCOM_VOL = 69 +PGAR_2_HPRCOM_VOL = 70 +DACR1_2_HPRCOM_VOL = 71 +HPRCOM_CTRL = 72 +# Mono Line Output Plus/Minus control registers +LINE2L_2_MONOLOPM_VOL = 73 +PGAL_2_MONOLOPM_VOL = 74 +DACL1_2_MONOLOPM_VOL = 75 +LINE2R_2_MONOLOPM_VOL = 76 +PGAR_2_MONOLOPM_VOL = 77 +DACR1_2_MONOLOPM_VOL = 78 +MONOLOPM_CTRL = 79 +# Left Line Output Plus/Minus control registers +LINE2L_2_LLOPM_VOL = 80 +PGAL_2_LLOPM_VOL = 81 +DACL1_2_LLOPM_VOL = 82 +LINE2R_2_LLOPM_VOL = 83 +PGAR_2_LLOPM_VOL = 84 +DACR1_2_LLOPM_VOL = 85 +LLOPM_CTRL = 86 +# Right Line Output Plus/Minus control registers +LINE2L_2_RLOPM_VOL = 87 +PGAL_2_RLOPM_VOL = 88 +DACL1_2_RLOPM_VOL = 89 +LINE2R_2_RLOPM_VOL = 90 +PGAR_2_RLOPM_VOL = 91 +DACR1_2_RLOPM_VOL = 92 +RLOPM_CTRL = 93 + +MODULE_POWER_STATUS = 94 + +# GPIO/IRQ registers +AIC3X_STICKY_IRQ_FLAGS_REG = 96 +AIC3X_RT_IRQ_FLAGS_REG = 97 + +AIC3X_CLOCK_REG = 101 +# Clock generation control register +AIC3X_CLKGEN_CTRL_REG = 102 +# New AGC registers +LAGCN_ATTACK = 103 +LAGCN_DECAY = 104 +RAGCN_ATTACK = 105 +RAGCN_DECAY = 106 +# New Programmable ADC Digital Path and I2C Bus Condition Register +NEW_ADC_DIGITALPATH = 107 +# Passive Analog Signal Bypass Selection During Powerdown Register +PASSIVE_BYPASS = 108 +# DAC Quiescent Current Adjustment Register +DAC_ICC_ADJ = 109 + + +# My kingdom for enums, and strong typing... +LINE2_L = 0 +PGA_L = 1 +DAC_L1 = 2 +LINE2_R = 3 +PGA_R = 4 +DAC_R1 = 5 + +# Don't use the same values for the sink and source "enums", this way a runtime +# error will tell us when we mix the two. +HP_L_OUT = 10 +HP_L_COM = 11 +HP_R_OUT = 12 +HP_R_COM = 13 +LINE_OUT_L = 14 +LINE_OUT_R = 15 + + +class AIC3105: + def __init__(self, i2c_bus, sample_rate, address=0x18): + self.i2c_device = i2c_device.I2CDevice(i2c_bus, address) + self._buf = bytearray(2) + self._sample_rate = sample_rate + + self._registers_copy = [ + 0b00000000, # 0 + 0b00000000, # 1 + 0b00000000, # 2 + 0b00010000, # 3 + 0b00000010, # 4 + 0b00000000, # 5 + 0b00000000, # 6 + 0b00000000, # 7 + 0b00000000, # 8 + 0b00000000, # 9 + 0b00000000, # 10 + 0b00000001, # 11 + 0b00000000, # 12 + 0b00000000, # 13 + 0b00000000, # 14 + 0b10000000, # 15 + 0b10000000, # 16 + 0b11111111, # 17 + 0b11111111, # 18 + 0b01111000, # 19 + 0b01111000, # 20 + 0b01111000, # 21 + 0b01111000, # 22 + 0b01111000, # 23 + 0b01111000, # 24 + 0b00000000, # 25 + 0b00000000, # 26 + 0b11111110, # 27 + 0b00000000, # 28 + 0b00000000, # 29 + 0b11111110, # 30 + 0b00000000, # 31 + 0b00000000, # 32 + 0b00000000, # 33 + 0b00000000, # 34 + 0b00000000, # 35 + 0b00000000, # 36 + 0b00000000, # 37 + 0b00000000, # 38 + 0b00000000, # 39 + 0b00000000, # 40 + 0b00000000, # 41 + 0b00000000, # 42 + 0b10000000, # 43 + 0b10000000, # 44 + 0b00000000, # 45 + 0b00000000, # 46 + 0b00000000, # 47 + 0b00000000, # 48 + 0b00000000, # 49 + 0b00000000, # 50 + 0b00000110, # 51 + 0b00000000, # 52 + 0b00000000, # 53 + 0b00000000, # 54 + 0b00000000, # 55 + 0b00000000, # 56 + 0b00000000, # 57 + 0b00000110, # 58 + 0b00000000, # 59 + 0b00000000, # 60 + 0b00000000, # 61 + 0b00000000, # 62 + 0b00000000, # 63 + 0b00000000, # 64 + 0b00000010, # 65 + 0b00000000, # 66 + 0b00000000, # 67 + 0b00000000, # 68 + 0b00000000, # 69 + 0b00000000, # 70 + 0b00000000, # 71 + 0b00000010, # 72 + 0b00000000, # 73 + 0b00000000, # 74 + 0b00000000, # 75 + 0b00000000, # 76 + 0b00000000, # 77 + 0b00000000, # 78 + 0b00000000, # 79 + 0b00000000, # 80 + 0b00000000, # 81 + 0b00000000, # 82 + 0b00000000, # 83 + 0b00000000, # 84 + 0b00000000, # 85 + 0b00000010, # 86 + 0b00000000, # 87 + 0b00000000, # 88 + 0b00000000, # 89 + 0b00000000, # 90 + 0b00000000, # 91 + 0b00000000, # 92 + 0b00000010, # 93 + 0b00000000, # 94 + 0b00000000, # 95 + 0b00000000, # 96 + 0b00000000, # 97 + 0b00000000, # 98 + 0b00000000, # 99 + 0b00000000, # 100 + 0b00000000, # 101 + 0b00000010, # 102 + 0b00000000, # 103 + 0b00000000, # 104 + 0b00000000, # 105 + 0b00000000, # 106 + 0b00000000, # 107 + 0b00000000, # 108 + 0b00000000, + ] # 109 + + def _write_register(self, reg, value): + self._buf[0] = reg & 0xFF + self._buf[1] = value & 0xFF + # print("_write_register reg:0x{:02x} value:0x{:02x}".format(reg, value)) + with self.i2c_device as i2c: + i2c.write(self._buf) + self._registers_copy[reg] = value + + def _write_bit(self, reg, pos, value): + current = self._registers_copy[reg] + mask = 1 << pos + + if value == 0: + new = current & (~mask) + else: + new = current | mask + self._write_register(reg, new) + + def _write_multi(self, reg, msb, lsb, value): + new = self._registers_copy[reg] + + # Clear bits for the range we case about + for x in range(lsb, msb + 1): + new = new & (~(1 << x)) + + new = new | (value << lsb) + + self._write_register(reg, new) + + def sink_base_register(self, sink): + if sink == HP_L_OUT: + return 45 + if sink == HP_L_COM: + return 52 + if sink == HP_R_OUT: + return 59 + if sink == HP_R_COM: + return 66 + if sink == LINE_OUT_L: + return 80 + if sink == LINE_OUT_R: + return 87 + + raise RuntimeError("invalid sink") + + def source_register_offset(self, source): + if source == LINE2_L: + return 0 + if source == PGA_L: + return 1 + if source == DAC_L1: + return 2 + if source == LINE2_R: + return 3 + if source == PGA_R: + return 4 + if source == DAC_R1: + return 5 + raise RuntimeError("invalid source") + + def power_on(self, sink): + reg = self.sink_base_register(sink) + 6 + self._write_bit(reg, 0, 1) + + def power_off(self, sink): + reg = self.sink_base_register(sink) + 6 + self._write_bit(reg, 0, 0) + + def mute(self, sink): + reg = self.sink_base_register(sink) + 6 + self._write_bit(reg, 3, 0) + + def unmute(self, sink): + reg = self.sink_base_register(sink) + 6 + self._write_bit(reg, 3, 1) + + def route(self, source, sink): + reg = self.sink_base_register(sink) + self.source_register_offset(source) + self._write_bit(reg, 7, 1) + + def unroute(self, source, sink): + reg = self.sink_base_register(sink) + self.source_register_offset(source) + self._write_bit(reg, 7, 0) + + def volume_convert(self, volume, min, max, mute_value): + if volume == 0.0 or volume < 0.0: + return mute_value + elif volume > 1.0: + volume = 1.0 + + if max > min: + amplitude = max - min + val = volume * amplitude + return int(min + val) + else: + amplitude = min - max + val = (1.0 - volume) * amplitude + return int(max + val) + + def PGA_volume(self, volume): + return self.volume_convert(volume, 0, 0b1111111, 0) + + def output_stage_volume(self, volume): + return self.volume_convert(volume, 117, 0, 118) + + def set_volume(self, source, sink, volume): + vol = self.output_stage_volume(volume) + reg = self.sink_base_register(sink) + self.source_register_offset(source) + self._write_multi(reg, 6, 0, vol) + + def set_HP_volume(self, left, right): + self.set_volume(DAC_L1, HP_L_OUT, left) + self.set_volume(DAC_R1, HP_R_OUT, right) + + def enable_line_out(self, left, right): + if left: + self.power_on(LINE_OUT_L) + self.route(DAC_L1, LINE_OUT_L) + self.route(DAC_L1, LINE_OUT_R) + self.unmute(LINE_OUT_L) + else: + self.power_off(LINE_OUT_L) + self.unroute(DAC_L1, LINE_OUT_L) + self.unroute(DAC_L1, LINE_OUT_R) + self.mute(LINE_OUT_L) + + if right: + self.power_on(LINE_OUT_R) + self.route(DAC_R1, LINE_OUT_L) + self.route(DAC_R1, LINE_OUT_R) + self.unmute(LINE_OUT_R) + else: + self.power_off(LINE_OUT_R) + self.unroute(DAC_R1, LINE_OUT_L) + self.unroute(DAC_R1, LINE_OUT_R) + self.mute(LINE_OUT_R) + + def set_line_out_volume( + self, left_to_left, right_to_right, left_to_right=0.0, right_to_left=0.0 + ): + self.set_volume(DAC_L1, LINE_OUT_L, left_to_left) + self.set_volume(DAC_L1, LINE_OUT_R, left_to_right) + self.set_volume(DAC_R1, LINE_OUT_R, right_to_right) + self.set_volume(DAC_R1, LINE_OUT_L, right_to_left) + + def enable_mic_bias(self): + self._write_multi(MICBIAS_CTRL, 7, 6, 0b10) + + def start_i2s_out(self): + if self._sample_rate == 8000: + cfg = [5, 4613, 1, 8] + elif self._sample_rate == 16000: + cfg = [5, 4613, 1, 4] + elif self._sample_rate == 22050: + cfg = [7, 5264, 1, 4] + elif self._sample_rate == 32000: + cfg = [5, 4613, 1, 2] + elif self._sample_rate == 44100: + cfg = [7, 5264, 1, 2] + elif self._sample_rate == 48000: + cfg = [8, 1920, 1, 2] + else: + raise RuntimeError("invalid sample rate: " + str(self._sample_rate)) + + J = cfg[0] + D = cfg[1] + R = cfg[2] + P = cfg[3] + + # Select Page 0 + self._write_bit(AIC3X_PAGE_SELECT, 0, 0) + + # Soft reset + self._write_bit(AIC3X_RESET, 7, 1) + + # Let's start with clock configuration. + + # PLL P = 2 + self._write_multi(AIC3X_PLL_PROGA_REG, 2, 0, P) + + # PLL R = 1 + self._write_multi(AIC3X_OVRF_STATUS_AND_PLLR_REG, 3, 0, R) + + # PLL J = 7 + self._write_multi(AIC3X_PLL_PROGB_REG, 7, 2, J) + + # PLL D = 5264 + PLL_D = D + REG_C = PLL_D >> 6 + REG_D = PLL_D & 0x3F + self._write_multi(AIC3X_PLL_PROGC_REG, 7, 0, REG_C) + self._write_multi(AIC3X_PLL_PROGD_REG, 7, 2, REG_D) + + # Select the PLLCLK_IN source. 0: MCLK, 1: GPIO2, 2: BCLK + self._write_multi(AIC3X_CLKGEN_CTRL_REG, 5, 4, 2) + + # Select the CLKDIV_IN source. 0: MCLK, 1: GPIO2, 2: BCLK + # + # Note: When PLL is used CLKDIV_IN still needs some kind of clock + # signal. So if there's no MCLK, BCLK should be used here as well + self._write_multi(AIC3X_CLKGEN_CTRL_REG, 6, 7, 0) + + # Enable PLL + self._write_bit(AIC3X_PLL_PROGA_REG, 7, 1) + + # Set FS(ref) value for AGC time constants to 44.1KHz + self._write_bit(AIC3X_CODEC_DATAPATH_REG, 7, 1) + + # CODEC_CLKIN Source Selection. 0: PLLDIV_OUT. 1: CLKDIV_OUT + self._write_bit(AIC3X_CLOCK_REG, 0, 0) + + # Note: We leave the ADC Sample Rate Select and DAC Sample Rate Select + # at the default value: fs(ref) / 1 + + # Audio Serial Data Interface at the default settings: I2S + # mode, 16bits words, + self._write_multi(AIC3X_ASD_INTF_CTRLB, 7, 6, 0b00) + + # Output Driver Power-On Delay Control + self._write_multi(HPOUT_POP_REDUCTION, 7, 4, 0b1000) + + # Driver Ramp-Up Step Timing Control + self._write_multi(HPOUT_POP_REDUCTION, 3, 2, 0b01) + + # Power outputs + self.power_on(HP_L_OUT) + self.power_on(HP_R_OUT) + + # L and R DACs Power On + self._write_multi(DAC_PWR, 7, 6, 0b11) + + # Left DAC plays left input data + self._write_multi(AIC3X_CODEC_DATAPATH_REG, 4, 3, 0b01) + # Right DAC plays right input data + self._write_multi(AIC3X_CODEC_DATAPATH_REG, 2, 1, 0b01) + + # Unmute L DAC + self._write_bit(LDAC_VOL, 7, 0) + # Unmute R DAC + self._write_bit(RDAC_VOL, 7, 0) + + # Left-DAC output selects DAC_L1 path. + self._write_multi(DAC_LINE_MUX, 7, 6, 0) + # Right-DAC output selects DAC_R1 path. + self._write_multi(DAC_LINE_MUX, 5, 4, 0) + + # DAC to HP + self.route(DAC_L1, HP_L_OUT) + self.route(DAC_R1, HP_R_OUT) + + # DAC to Line-Out + self.route(DAC_L1, LINE_OUT_L) + self.route(DAC_R1, LINE_OUT_R) + + # Enable Left ADC + self._write_bit(LINE1L_2_LADC_CTRL, 2, 1) + # Enable Right ADC + self._write_bit(LINE1R_2_RADC_CTRL, 2, 1) + + # Unmute L ADC PGA + self._write_bit(LADC_VOL, 7, 0) + # Unmute R ADC PGA + self._write_bit(RADC_VOL, 7, 0) + + # Programs high-power outputs for ac-coupled driver configuration + self._write_bit(AIC3X_HEADSET_DETECT_CTRL_B, 7, 1) + + # HPLCOM configured as independent single-ended output + self._write_multi(HPLCOM_CFG, 5, 4, 2) + + # HPRCOM configured as independent single-ended output + self._write_multi(HPRCOM_CFG, 5, 3, 1) + + # Unmute outputs + self.unmute(HP_L_OUT) + self.unmute(HP_R_OUT) diff --git a/ports/raspberrypi/boards/weenoisemakers_noisenugget/_tca6408.py b/ports/raspberrypi/boards/weenoisemakers_noisenugget/_tca6408.py new file mode 100644 index 00000000000..6b3d90b5de5 --- /dev/null +++ b/ports/raspberrypi/boards/weenoisemakers_noisenugget/_tca6408.py @@ -0,0 +1,65 @@ +from adafruit_bus_device import i2c_device + +IO_EXP_SPK_Enable_L_Mask = 0b00000001 +IO_EXP_SPK_Enable_R_Mask = 0b00000010 +IO_EXP_SPK_Gain_0_Mask = 0b00000100 +IO_EXP_SPK_Gain_1_Mask = 0b00001000 +IO_EXP_DAC_Not_Reset_Mask = 0b00010000 +IO_EXP_Jack_Detect_Mask = 0b00100000 + +IO_EXP_INPUT_REG = 0 +IO_EXP_OUTPUT_REG = 1 +IO_EXP_CONFIG_REG = 3 + +IO_EXP_CONFIG_REG_INIT = IO_EXP_Jack_Detect_Mask +IO_EXP_OUTPUT_REG_INIT = 0b00000000 + + +class TCA6408: + def __init__(self, i2c_bus, address=0x20): + self._i2c_device = i2c_device.I2CDevice(i2c_bus, address) + self._buf = bytearray(2) + self._reg_state = IO_EXP_OUTPUT_REG_INIT + + self._write_register(IO_EXP_OUTPUT_REG, self._reg_state) + self._write_register(IO_EXP_CONFIG_REG, IO_EXP_CONFIG_REG_INIT) + + def _write_register(self, reg, value): + self._buf[0] = reg & 0xFF + self._buf[1] = value & 0xFF + with self._i2c_device as i2c: + i2c.write(self._buf) + + def _set_out(self, new_state): + self._write_register(IO_EXP_OUTPUT_REG, new_state) + self._reg_state = new_state + + def enable_codec(self): + self._set_out(self._reg_state | IO_EXP_DAC_Not_Reset_Mask) + + def enable_speakers(self, left, right): + new_state = self._reg_state + if left: + new_state = new_state | IO_EXP_SPK_Enable_L_Mask + else: + new_state = new_state & ~IO_EXP_SPK_Enable_L_Mask + + if right: + new_state = new_state | IO_EXP_SPK_Enable_R_Mask + else: + new_state = new_state & ~IO_EXP_SPK_Enable_R_Mask + + self._set_out(new_state) + + def set_speakers_gain(self, g0, g1): + new_state = self._reg_state + + if g0: + new_state = new_state | IO_EXP_SPK_Gain_0_Mask + else: + new_state = new_state & ~IO_EXP_SPK_Gain_0_Mask + + if g1: + new_state = new_state | IO_EXP_SPK_Gain_1_Mask + else: + new_state = new_state & ~IO_EXP_SPK_Gain_1_Mask diff --git a/ports/raspberrypi/boards/weenoisemakers_noisenugget/board.c b/ports/raspberrypi/boards/weenoisemakers_noisenugget/board.c new file mode 100644 index 00000000000..331653173ec --- /dev/null +++ b/ports/raspberrypi/boards/weenoisemakers_noisenugget/board.c @@ -0,0 +1,29 @@ +/* + * 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" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/raspberrypi/boards/weenoisemakers_noisenugget/mpconfigboard.h b/ports/raspberrypi/boards/weenoisemakers_noisenugget/mpconfigboard.h new file mode 100644 index 00000000000..ddebab5b8a3 --- /dev/null +++ b/ports/raspberrypi/boards/weenoisemakers_noisenugget/mpconfigboard.h @@ -0,0 +1,2 @@ +#define MICROPY_HW_BOARD_NAME "Noise Nugget 2040" +#define MICROPY_HW_MCU_NAME "rp2040" diff --git a/ports/raspberrypi/boards/weenoisemakers_noisenugget/mpconfigboard.mk b/ports/raspberrypi/boards/weenoisemakers_noisenugget/mpconfigboard.mk new file mode 100644 index 00000000000..a90f1a3db45 --- /dev/null +++ b/ports/raspberrypi/boards/weenoisemakers_noisenugget/mpconfigboard.mk @@ -0,0 +1,18 @@ +USB_VID = 0x2E8A +USB_PID = 0x1090 +USB_PRODUCT = "Noise Nugget 2040" +USB_MANUFACTURER = "Wee Noise Makers" + +CHIP_VARIANT = RP2040 +CHIP_FAMILY = rp2 + +EXTERNAL_FLASH_DEVICES = "W25Q128JVxQ" + +CIRCUITPY__EVE = 1 + +FROZEN_MPY_DIRS += $(TOP)/ports/raspberrypi/boards/weenoisemakers_noisenugget +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_NeoPixel +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_ImageLoad +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_DisplayIO_SSD1306 +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_Display_Text +FROZEN_MPY_DIRS += $(TOP)/frozen/Adafruit_CircuitPython_MIDI diff --git a/ports/raspberrypi/boards/weenoisemakers_noisenugget/noise_nugget.py b/ports/raspberrypi/boards/weenoisemakers_noisenugget/noise_nugget.py new file mode 100644 index 00000000000..02dab040e5f --- /dev/null +++ b/ports/raspberrypi/boards/weenoisemakers_noisenugget/noise_nugget.py @@ -0,0 +1,115 @@ +from board import * +import audiobusio +import busio +import time +import _aic3105 +import _tca6408 + +_AUDIO = None +_DAC = None +_I2C = None +_IO_EXP = None +_SAMPLE_RATE = 22050 + + +def io_exp(): + global _IO_EXP + + if not _IO_EXP: + _IO_EXP = _tca6408.TCA6408(i2c()) + + return _IO_EXP + + +def i2c(): + global _I2C + + if not _I2C: + SCL = GP7 + SDA = GP6 + _I2C = busio.I2C(SCL, SDA) + + return _I2C + + +def _init_dac(sample_rate): + global _DAC + global _SAMPLE_RATE + + if not _DAC: + _SAMPLE_RATE = sample_rate + + _DAC = _aic3105.AIC3105(i2c(), sample_rate) + _DAC.start_i2s_out() + + return _DAC + + +def audio(sample_rate=22050): + global _AUDIO + global _DAC + + if not _AUDIO: + i2s_out = GP1 + i2s_lrclk = GP2 + i2s_bclk = GP3 + + io_exp().enable_codec() + + time.sleep(0.1) + + # Must init the dac here + _init_dac(sample_rate) + _DAC.set_HP_volume(0.5, 0.5) + + _AUDIO = audiobusio.I2SOut(i2s_bclk, i2s_lrclk, i2s_out, left_justified=False) + + return _AUDIO + + +def sample_rate(): + return _SAMPLE_RATE + + +def _check_dac_init(): + global _DAC + if not _DAC: + raise RuntimeError("audio not initialized. Call noise_nugget.audio() first.") + + +def set_HP_volume(left, right): + global _DAC + + _check_dac_init() + + _DAC.set_HP_volume(left, right) + + +def enable_speakers(left, right): + global _DAC + + _check_dac_init() + + _DAC.enable_line_out(left, right) + io_exp().enable_speakers(left, right) + + +def set_speakers_volume(left_to_left, right_to_right, left_to_right=0.0, right_to_left=0.0): + global _DAC + + _check_dac_init() + + _DAC.set_line_out_volume(left_to_left, right_to_right, left_to_right, right_to_left) + + +def set_speakers_gain(gain): + if gain == 0: + io_exp().set_speakers_gain(False, False) + elif gain == 1: + io_exp().set_speakers_gain(True, False) + elif gain == 2: + io_exp().set_speakers_gain(False, True) + elif gain == 3: + io_exp().set_speakers_gain(True, True) + else: + raise RuntimeError("invalid speaker gain " + str(gain) + " (must be between 0 and 3)") diff --git a/ports/raspberrypi/boards/weenoisemakers_noisenugget/pgb1.py b/ports/raspberrypi/boards/weenoisemakers_noisenugget/pgb1.py new file mode 100644 index 00000000000..6e822e75c8c --- /dev/null +++ b/ports/raspberrypi/boards/weenoisemakers_noisenugget/pgb1.py @@ -0,0 +1,320 @@ +from board import * +import busio +import displayio +import adafruit_displayio_ssd1306 +from fourwire import FourWire +from neopixel import NeoPixel +import pwmio +from digitalio import DigitalInOut, Direction, Pull + +_DISPLAY = None +_LEDS = None +_KEYBOARD_STATE = 0 +_KEYBOARD_PREV_STATE = 0 + +VOLTAGE_MONITOR = A2 +BATTERY = A2 + +K_TRACK = 0x10000000 +K_STEP = 0x08000000 +K_PLAY = 0x02000000 +K_REC = 0x04000000 +K_ALT = 0x00040000 +K_PATT = 0x00001000 +K_SONG = 0x00000040 +K_MENU = 0x00000020 + +K_UP = 0x00020000 +K_DOWN = 0x00800000 +K_RIGHT = 0x00000800 +K_LEFT = 0x20000000 +K_A = 0x01000000 +K_B = 0x00000001 + +K_1 = 0x00400000 +K_2 = 0x00010000 +K_3 = 0x00000400 +K_4 = 0x00000010 +K_5 = 0x00000002 +K_6 = 0x00000080 +K_7 = 0x00002000 +K_8 = 0x00080000 +K_9 = 0x00200000 +K_10 = 0x00008000 +K_11 = 0x00000200 +K_12 = 0x00000008 +K_13 = 0x00000004 +K_14 = 0x00000100 +K_15 = 0x00004000 +K_16 = 0x00100000 + +KEY_LIST = [ + K_TRACK, + K_STEP, + K_PLAY, + K_REC, + K_ALT, + K_PATT, + K_SONG, + K_MENU, + K_UP, + K_DOWN, + K_RIGHT, + K_LEFT, + K_A, + K_B, + K_1, + K_2, + K_3, + K_4, + K_5, + K_6, + K_7, + K_8, + K_9, + K_10, + K_11, + K_12, + K_13, + K_14, + K_15, + K_16, +] + +KEY_NAME = { + K_TRACK: "Track", + K_STEP: "Step", + K_PLAY: "Play", + K_REC: "Rec", + K_ALT: "Alt", + K_PATT: "Pattern", + K_SONG: "Song", + K_MENU: "Menu", + K_UP: "Up", + K_DOWN: "Down", + K_RIGHT: "Right", + K_LEFT: "Left", + K_A: "A", + K_B: "B", + K_1: "1", + K_2: "2", + K_3: "3", + K_4: "4", + K_5: "5", + K_6: "6", + K_7: "7", + K_8: "8", + K_9: "9", + K_10: "10", + K_11: "11", + K_12: "12", + K_13: "13", + K_14: "14", + K_15: "15", + K_16: "16", +} + +LED_MENU = 0 +LED_SONG = 1 +LED_PATT = 2 +LED_ALT = 3 +LED_TRACK = 4 +LED_K_1 = 5 +LED_K_2 = 6 +LED_K_3 = 7 +LED_K_4 = 8 +LED_K_5 = 9 +LED_K_6 = 10 +LED_K_7 = 11 +LED_K_8 = 12 +LED_PLAY = 13 +LED_STEP = 14 +LED_K_9 = 15 +LED_K_10 = 16 +LED_K_11 = 17 +LED_K_12 = 18 +LED_K_13 = 19 +LED_K_14 = 20 +LED_K_15 = 21 +LED_K_16 = 22 +LED_REC = 23 + +_KEY_COL = [ + DigitalInOut(GP21), + DigitalInOut(GP22), + DigitalInOut(GP26), + DigitalInOut(GP23), + DigitalInOut(GP29), +] +_KEY_ROW = [ + DigitalInOut(GP20), + DigitalInOut(GP18), + DigitalInOut(GP19), + DigitalInOut(GP24), + DigitalInOut(GP25), + DigitalInOut(GP27), +] + +for pin in _KEY_COL: + pin.direction = Direction.OUTPUT + pin.value = False + +for pin in _KEY_ROW: + pin.direction = Direction.INPUT + pin.pull = Pull.DOWN + + +def scan_keyboard(): + global _KEYBOARD_STATE + global _KEYBOARD_PREV_STATE + + val = 0 + for col in _KEY_COL: + col.value = True + for row in _KEY_ROW: + val = val << 1 + if row.value: + val = val | 1 + col.value = False + _KEYBOARD_PREV_STATE = _KEYBOARD_STATE + _KEYBOARD_STATE = val + + +def pressed(keys): + global _KEYBOARD_STATE + + return (_KEYBOARD_STATE & keys) != 0 + + +def falling(keys): + global _KEYBOARD_STATE + global _KEYBOARD_PREV_STATE + + all_falling_keys = _KEYBOARD_STATE & ~_KEYBOARD_PREV_STATE + return (all_falling_keys & keys) != 0 + + +def raising(keys): + global _KEYBOARD_STATE + global _KEYBOARD_PREV_STATE + + all_raising_keys = ~_KEYBOARD_STATE & _KEYBOARD_PREV_STATE + return (all_raising_keys & keys) != 0 + + +def display(spi_frequency=1000000): + global _DISPLAY + + if not _DISPLAY: + displayio.release_displays() + + spi = busio.SPI(GP10, GP11) + cs = None + dc = GP12 + reset = GP13 + + display_bus = FourWire( + spi, command=dc, chip_select=cs, reset=reset, baudrate=spi_frequency + ) + _DISPLAY = adafruit_displayio_ssd1306.SSD1306(display_bus, width=128, height=64) + + return _DISPLAY + + +def neopixel(brightness=0.1): + global _LEDS + + if not _LEDS: + _LEDS = NeoPixel(GP14, 24, brightness=brightness) + + return _LEDS + + +def key_to_led(key): + map = { + K_TRACK: LED_TRACK, + K_STEP: LED_STEP, + K_PLAY: LED_PLAY, + K_REC: LED_REC, + K_ALT: LED_ALT, + K_PATT: LED_PATT, + K_SONG: LED_SONG, + K_MENU: LED_MENU, + K_1: LED_K_1, + K_2: LED_K_2, + K_3: LED_K_3, + K_4: LED_K_4, + K_5: LED_K_5, + K_6: LED_K_6, + K_7: LED_K_7, + K_8: LED_K_8, + K_9: LED_K_9, + K_10: LED_K_10, + K_11: LED_K_11, + K_12: LED_K_12, + K_13: LED_K_13, + K_14: LED_K_14, + K_15: LED_K_15, + K_16: LED_K_16, + } + return map[key] + + +def simple_synth(synth, verbose=False): + base_note = 60 + + leds = neopixel() + + keys = [ + (K_9, 0), + (K_2, 1), + (K_10, 2), + (K_3, 3), + (K_11, 4), + (K_12, 5), + (K_5, 6), + (K_13, 7), + (K_6, 8), + (K_14, 9), + (K_7, 10), + (K_15, 11), + (K_16, 12), + ] + + for key, _ in keys: + leds[key_to_led(key)] = (0, 0, 255) + leds[key_to_led(K_1)] = (255, 255, 0) + leds[key_to_led(K_8)] = (255, 255, 0) + leds.show() + + while True: + scan_keyboard() + + # Lower base note 1 octave down + if falling(K_1) and base_note > 12: + # Turn off any potentially on notes + for _, offset in keys: + synth.release(base_note + offset) + base_note -= 12 + if verbose: + print("Octave down") + + # Raise base note 1 octave up + if falling(K_8) and base_note <= 96: + # Turn off any potentially on notes + for _, offset in keys: + synth.release(base_note + offset) + base_note += 12 + if verbose: + print("Octave up") + + for key, offset in keys: + note = base_note + offset + if falling(key): + if verbose: + print("On " + str(note)) + synth.press(note) + if raising(key): + if verbose: + print("Off " + str(note)) + synth.release(note) diff --git a/ports/raspberrypi/boards/weenoisemakers_noisenugget/pico-sdk-configboard.h b/ports/raspberrypi/boards/weenoisemakers_noisenugget/pico-sdk-configboard.h new file mode 100644 index 00000000000..36da55d4571 --- /dev/null +++ b/ports/raspberrypi/boards/weenoisemakers_noisenugget/pico-sdk-configboard.h @@ -0,0 +1 @@ +// Put board-specific pico-sdk definitions here. This file must exist. diff --git a/ports/raspberrypi/boards/weenoisemakers_noisenugget/pins.c b/ports/raspberrypi/boards/weenoisemakers_noisenugget/pins.c new file mode 100644 index 00000000000..bbd3105956b --- /dev/null +++ b/ports/raspberrypi/boards/weenoisemakers_noisenugget/pins.c @@ -0,0 +1,54 @@ +#include "shared-bindings/board/__init__.h" + +const mcu_pin_obj_t pin_GPIO_fake; + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { 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_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_NEOPIXEL), MP_ROM_PTR(&pin_GPIO21) }, + + { MP_ROM_QSTR(MP_QSTR_GP22), MP_ROM_PTR(&pin_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_GP23), MP_ROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_GP24), MP_ROM_PTR(&pin_GPIO24) }, + { 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_GP29_A3), MP_ROM_PTR(&pin_GPIO29) }, + { MP_ROM_QSTR(MP_QSTR_GP29), MP_ROM_PTR(&pin_GPIO29) }, + { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO29) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/raspberrypi/boards/wiznet_w5100s_evb_pico/mpconfigboard.h b/ports/raspberrypi/boards/wiznet_w5100s_evb_pico/mpconfigboard.h index ba60f5f72d2..b3ff46a70d7 100644 --- a/ports/raspberrypi/boards/wiznet_w5100s_evb_pico/mpconfigboard.h +++ b/ports/raspberrypi/boards/wiznet_w5100s_evb_pico/mpconfigboard.h @@ -9,9 +9,14 @@ #define MICROPY_HW_BOARD_NAME "W5100S-EVB-Pico" #define MICROPY_HW_MCU_NAME "rp2040" +#define MICROPY_HW_LED_STATUS (&pin_GPIO25) + #define DEFAULT_SPI_BUS_SCK (&pin_GPIO18) #define DEFAULT_SPI_BUS_MOSI (&pin_GPIO19) #define DEFAULT_SPI_BUS_MISO (&pin_GPIO16) #define DEFAULT_UART_BUS_RX (&pin_GPIO1) #define DEFAULT_UART_BUS_TX (&pin_GPIO0) + +#define CIRCUITPY_BOARD_I2C (1) +#define CIRCUITPY_BOARD_I2C_PIN {{.scl = &pin_GPIO5, .sda = &pin_GPIO4}} diff --git a/ports/raspberrypi/boards/wiznet_w5100s_evb_pico/mpconfigboard.mk b/ports/raspberrypi/boards/wiznet_w5100s_evb_pico/mpconfigboard.mk index 70011c41b0c..95d228a8642 100644 --- a/ports/raspberrypi/boards/wiznet_w5100s_evb_pico/mpconfigboard.mk +++ b/ports/raspberrypi/boards/wiznet_w5100s_evb_pico/mpconfigboard.mk @@ -9,5 +9,10 @@ CHIP_FAMILY = rp2 EXTERNAL_FLASH_DEVICES = "W25Q16JVxQ" CIRCUITPY__EVE = 1 +CIRCUITPY_FLOPPYIO = 0 CIRCUITPY_SSL = 1 +CIRCUITPY_EPAPERDISPLAY_FAST = 0 CIRCUITPY_USB_HOST = 0 + +# The default is -O3. Change to -O2 because the build was overflowing. +OPTIMIZATION_FLAGS = -O2 diff --git a/ports/raspberrypi/boards/wiznet_w5100s_evb_pico/pins.c b/ports/raspberrypi/boards/wiznet_w5100s_evb_pico/pins.c index 1263586686b..969affad785 100644 --- a/ports/raspberrypi/boards/wiznet_w5100s_evb_pico/pins.c +++ b/ports/raspberrypi/boards/wiznet_w5100s_evb_pico/pins.c @@ -25,12 +25,25 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { 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_W5K_MISO), MP_ROM_PTR(&pin_GPIO16) }, { MP_ROM_QSTR(MP_QSTR_GP16), MP_ROM_PTR(&pin_GPIO16) }, + + { MP_ROM_QSTR(MP_QSTR_W5K_CS), MP_ROM_PTR(&pin_GPIO17) }, { MP_ROM_QSTR(MP_QSTR_GP17), MP_ROM_PTR(&pin_GPIO17) }, + + { MP_ROM_QSTR(MP_QSTR_W5K_SCK), MP_ROM_PTR(&pin_GPIO18) }, { MP_ROM_QSTR(MP_QSTR_GP18), MP_ROM_PTR(&pin_GPIO18) }, + + { MP_ROM_QSTR(MP_QSTR_W5K_MOSI), MP_ROM_PTR(&pin_GPIO19) }, { MP_ROM_QSTR(MP_QSTR_GP19), MP_ROM_PTR(&pin_GPIO19) }, + + { MP_ROM_QSTR(MP_QSTR_W5K_RST), MP_ROM_PTR(&pin_GPIO20) }, { MP_ROM_QSTR(MP_QSTR_GP20), MP_ROM_PTR(&pin_GPIO20) }, + + { MP_ROM_QSTR(MP_QSTR_W5K_INT), MP_ROM_PTR(&pin_GPIO21) }, { 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) }, @@ -56,5 +69,9 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO29) }, { MP_ROM_QSTR(MP_QSTR_VOLTAGE_MONITOR), MP_ROM_PTR(&pin_GPIO29) }, + + { MP_ROM_QSTR(MP_QSTR_W5K_SPI), MP_ROM_PTR(&board_spi_obj) }, + { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj) }, + { MP_ROM_QSTR(MP_QSTR_STEMMA_I2C), MP_ROM_PTR(&board_i2c_obj) }, }; MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/raspberrypi/boards/wiznet_w5100s_evb_pico2/mpconfigboard.h b/ports/raspberrypi/boards/wiznet_w5100s_evb_pico2/mpconfigboard.h index f2ff9f4b4d9..f8d7378c2d9 100644 --- a/ports/raspberrypi/boards/wiznet_w5100s_evb_pico2/mpconfigboard.h +++ b/ports/raspberrypi/boards/wiznet_w5100s_evb_pico2/mpconfigboard.h @@ -4,6 +4,8 @@ // // SPDX-License-Identifier: MIT +#pragma once + #define MICROPY_HW_BOARD_NAME "W5100S-EVB-Pico2" #define MICROPY_HW_MCU_NAME "rp2350a" diff --git a/ports/raspberrypi/boards/wiznet_w5100s_evb_pico2/mpconfigboard.mk b/ports/raspberrypi/boards/wiznet_w5100s_evb_pico2/mpconfigboard.mk index 972b560c845..c2e26d9caaf 100644 --- a/ports/raspberrypi/boards/wiznet_w5100s_evb_pico2/mpconfigboard.mk +++ b/ports/raspberrypi/boards/wiznet_w5100s_evb_pico2/mpconfigboard.mk @@ -11,3 +11,10 @@ EXTERNAL_FLASH_DEVICES = "W25Q32JVxQ" CIRCUITPY__EVE = 1 CIRCUITPY_SSL = 1 +CIRCUITPY_EPAPERDISPLAY_FAST = 0 + +# GPIO12-19 needed for picodvi, but GPIO16 is used for Wiznet. +CIRCUITPY_PICODVI = 0 + +# The default is -O3. Change to -O2 because the build was overflowing. +OPTIMIZATION_FLAGS = -O2 diff --git a/ports/raspberrypi/boards/wiznet_w5100s_evb_pico2/pico-sdk-configboard.h b/ports/raspberrypi/boards/wiznet_w5100s_evb_pico2/pico-sdk-configboard.h index 66b57dfd13d..110195b7794 100644 --- a/ports/raspberrypi/boards/wiznet_w5100s_evb_pico2/pico-sdk-configboard.h +++ b/ports/raspberrypi/boards/wiznet_w5100s_evb_pico2/pico-sdk-configboard.h @@ -4,4 +4,6 @@ // // SPDX-License-Identifier: MIT +#pragma once + // Put board-specific pico-sdk definitions here. This file must exist. diff --git a/ports/raspberrypi/boards/wiznet_w5100s_evb_pico2/pins.c b/ports/raspberrypi/boards/wiznet_w5100s_evb_pico2/pins.c index e34c68d0692..dbc4e9ad76d 100644 --- a/ports/raspberrypi/boards/wiznet_w5100s_evb_pico2/pins.c +++ b/ports/raspberrypi/boards/wiznet_w5100s_evb_pico2/pins.c @@ -25,12 +25,25 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { 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_W5K_MISO), MP_ROM_PTR(&pin_GPIO16) }, { MP_ROM_QSTR(MP_QSTR_GP16), MP_ROM_PTR(&pin_GPIO16) }, + + { MP_ROM_QSTR(MP_QSTR_W5K_CS), MP_ROM_PTR(&pin_GPIO17) }, { MP_ROM_QSTR(MP_QSTR_GP17), MP_ROM_PTR(&pin_GPIO17) }, + + { MP_ROM_QSTR(MP_QSTR_W5K_SCK), MP_ROM_PTR(&pin_GPIO18) }, { MP_ROM_QSTR(MP_QSTR_GP18), MP_ROM_PTR(&pin_GPIO18) }, + + { MP_ROM_QSTR(MP_QSTR_W5K_MOSI), MP_ROM_PTR(&pin_GPIO19) }, { MP_ROM_QSTR(MP_QSTR_GP19), MP_ROM_PTR(&pin_GPIO19) }, + + { MP_ROM_QSTR(MP_QSTR_W5K_RST), MP_ROM_PTR(&pin_GPIO20) }, { MP_ROM_QSTR(MP_QSTR_GP20), MP_ROM_PTR(&pin_GPIO20) }, + + { MP_ROM_QSTR(MP_QSTR_W5K_INT), MP_ROM_PTR(&pin_GPIO21) }, { 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) }, @@ -57,8 +70,8 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO29) }, { MP_ROM_QSTR(MP_QSTR_VOLTAGE_MONITOR), 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_W5K_SPI), MP_ROM_PTR(&board_spi_obj) }, { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj) }, + { MP_ROM_QSTR(MP_QSTR_STEMMA_I2C), MP_ROM_PTR(&board_i2c_obj) }, }; MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/raspberrypi/boards/wiznet_w5500_evb_pico/mpconfigboard.h b/ports/raspberrypi/boards/wiznet_w5500_evb_pico/mpconfigboard.h index 7aeca9bdb2c..95cd9be2cce 100644 --- a/ports/raspberrypi/boards/wiznet_w5500_evb_pico/mpconfigboard.h +++ b/ports/raspberrypi/boards/wiznet_w5500_evb_pico/mpconfigboard.h @@ -9,9 +9,14 @@ #define MICROPY_HW_BOARD_NAME "W5500-EVB-Pico" #define MICROPY_HW_MCU_NAME "rp2040" +#define MICROPY_HW_LED_STATUS (&pin_GPIO25) + #define DEFAULT_SPI_BUS_SCK (&pin_GPIO18) #define DEFAULT_SPI_BUS_MOSI (&pin_GPIO19) #define DEFAULT_SPI_BUS_MISO (&pin_GPIO16) #define DEFAULT_UART_BUS_RX (&pin_GPIO1) #define DEFAULT_UART_BUS_TX (&pin_GPIO0) + +#define CIRCUITPY_BOARD_I2C (1) +#define CIRCUITPY_BOARD_I2C_PIN {{.scl = &pin_GPIO5, .sda = &pin_GPIO4}} diff --git a/ports/raspberrypi/boards/wiznet_w5500_evb_pico/mpconfigboard.mk b/ports/raspberrypi/boards/wiznet_w5500_evb_pico/mpconfigboard.mk index b3ac9854d3d..96f36b4a0c2 100644 --- a/ports/raspberrypi/boards/wiznet_w5500_evb_pico/mpconfigboard.mk +++ b/ports/raspberrypi/boards/wiznet_w5500_evb_pico/mpconfigboard.mk @@ -9,5 +9,10 @@ CHIP_FAMILY = rp2 EXTERNAL_FLASH_DEVICES = "W25Q16JVxQ" CIRCUITPY__EVE = 1 +CIRCUITPY_FLOPPYIO = 0 CIRCUITPY_SSL = 1 +CIRCUITPY_EPAPERDISPLAY_FAST = 0 CIRCUITPY_USB_HOST = 0 + +# The default is -O3. Change to -O2 because the build was overflowing. +OPTIMIZATION_FLAGS = -O2 diff --git a/ports/raspberrypi/boards/wiznet_w5500_evb_pico/pins.c b/ports/raspberrypi/boards/wiznet_w5500_evb_pico/pins.c index a24ff3f3a60..969affad785 100644 --- a/ports/raspberrypi/boards/wiznet_w5500_evb_pico/pins.c +++ b/ports/raspberrypi/boards/wiznet_w5500_evb_pico/pins.c @@ -26,22 +26,22 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { 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_MISO), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_W5K_MISO), MP_ROM_PTR(&pin_GPIO16) }, { MP_ROM_QSTR(MP_QSTR_GP16), MP_ROM_PTR(&pin_GPIO16) }, - { MP_ROM_QSTR(MP_QSTR_W5500_CS), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_W5K_CS), MP_ROM_PTR(&pin_GPIO17) }, { MP_ROM_QSTR(MP_QSTR_GP17), MP_ROM_PTR(&pin_GPIO17) }, - { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_W5K_SCK), MP_ROM_PTR(&pin_GPIO18) }, { MP_ROM_QSTR(MP_QSTR_GP18), MP_ROM_PTR(&pin_GPIO18) }, - { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_W5K_MOSI), MP_ROM_PTR(&pin_GPIO19) }, { MP_ROM_QSTR(MP_QSTR_GP19), MP_ROM_PTR(&pin_GPIO19) }, - { MP_ROM_QSTR(MP_QSTR_W5500_RST), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_W5K_RST), MP_ROM_PTR(&pin_GPIO20) }, { MP_ROM_QSTR(MP_QSTR_GP20), MP_ROM_PTR(&pin_GPIO20) }, - { MP_ROM_QSTR(MP_QSTR_W5500_INT), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_W5K_INT), MP_ROM_PTR(&pin_GPIO21) }, { MP_ROM_QSTR(MP_QSTR_GP21), MP_ROM_PTR(&pin_GPIO21) }, { MP_ROM_QSTR(MP_QSTR_GP22), MP_ROM_PTR(&pin_GPIO22) }, @@ -55,12 +55,10 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { 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_SDA), 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_A0), MP_ROM_PTR(&pin_GPIO26) }, - { MP_ROM_QSTR(MP_QSTR_SCL), 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_A1), MP_ROM_PTR(&pin_GPIO27) }, @@ -72,8 +70,8 @@ static const mp_rom_map_elem_t board_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_GPIO29) }, { MP_ROM_QSTR(MP_QSTR_VOLTAGE_MONITOR), 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_W5K_SPI), MP_ROM_PTR(&board_spi_obj) }, { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj) }, + { MP_ROM_QSTR(MP_QSTR_STEMMA_I2C), MP_ROM_PTR(&board_i2c_obj) }, }; MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/raspberrypi/boards/wiznet_w5500_evb_pico2/board.c b/ports/raspberrypi/boards/wiznet_w5500_evb_pico2/board.c new file mode 100644 index 00000000000..e6a868ab212 --- /dev/null +++ b/ports/raspberrypi/boards/wiznet_w5500_evb_pico2/board.c @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/raspberrypi/boards/wiznet_w5500_evb_pico2/mpconfigboard.h b/ports/raspberrypi/boards/wiznet_w5500_evb_pico2/mpconfigboard.h new file mode 100644 index 00000000000..6523d82a38d --- /dev/null +++ b/ports/raspberrypi/boards/wiznet_w5500_evb_pico2/mpconfigboard.h @@ -0,0 +1,22 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#define MICROPY_HW_BOARD_NAME "W5500-EVB-Pico2" +#define MICROPY_HW_MCU_NAME "rp2350a" + +#define MICROPY_HW_LED_STATUS (&pin_GPIO25) + +#define DEFAULT_SPI_BUS_SCK (&pin_GPIO18) +#define DEFAULT_SPI_BUS_MOSI (&pin_GPIO19) +#define DEFAULT_SPI_BUS_MISO (&pin_GPIO16) + +#define DEFAULT_UART_BUS_RX (&pin_GPIO1) +#define DEFAULT_UART_BUS_TX (&pin_GPIO0) + +#define CIRCUITPY_BOARD_I2C (1) +#define CIRCUITPY_BOARD_I2C_PIN {{.scl = &pin_GPIO5, .sda = &pin_GPIO4}} diff --git a/ports/raspberrypi/boards/wiznet_w5500_evb_pico2/mpconfigboard.mk b/ports/raspberrypi/boards/wiznet_w5500_evb_pico2/mpconfigboard.mk new file mode 100644 index 00000000000..9aa01792824 --- /dev/null +++ b/ports/raspberrypi/boards/wiznet_w5500_evb_pico2/mpconfigboard.mk @@ -0,0 +1,20 @@ +USB_VID = 0x2E8A +USB_PID = 0x109F +USB_PRODUCT = "W5500-EVB-Pico2" +USB_MANUFACTURER = "WIZnet" + +CHIP_VARIANT = RP2350 +CHIP_PACKAGE = A +CHIP_FAMILY = rp2 + +EXTERNAL_FLASH_DEVICES = "W25Q32JVxQ" + +CIRCUITPY__EVE = 1 +CIRCUITPY_SSL = 1 +CIRCUITPY_EPAPERDISPLAY_FAST = 0 + +# GPIO12-19 needed for picodvi, but GPIO16 is used for Wiznet. +CIRCUITPY_PICODVI = 0 + +# The default is -O3. Change to -O2 because the build was overflowing. +OPTIMIZATION_FLAGS = -O2 diff --git a/ports/raspberrypi/boards/wiznet_w5500_evb_pico2/pico-sdk-configboard.h b/ports/raspberrypi/boards/wiznet_w5500_evb_pico2/pico-sdk-configboard.h new file mode 100644 index 00000000000..110195b7794 --- /dev/null +++ b/ports/raspberrypi/boards/wiznet_w5500_evb_pico2/pico-sdk-configboard.h @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Put board-specific pico-sdk definitions here. This file must exist. diff --git a/ports/raspberrypi/boards/wiznet_w5500_evb_pico2/pins.c b/ports/raspberrypi/boards/wiznet_w5500_evb_pico2/pins.c new file mode 100644 index 00000000000..dbc4e9ad76d --- /dev/null +++ b/ports/raspberrypi/boards/wiznet_w5500_evb_pico2/pins.c @@ -0,0 +1,77 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { 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_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_W5K_MISO), MP_ROM_PTR(&pin_GPIO16) }, + { MP_ROM_QSTR(MP_QSTR_GP16), MP_ROM_PTR(&pin_GPIO16) }, + + { MP_ROM_QSTR(MP_QSTR_W5K_CS), MP_ROM_PTR(&pin_GPIO17) }, + { MP_ROM_QSTR(MP_QSTR_GP17), MP_ROM_PTR(&pin_GPIO17) }, + + { MP_ROM_QSTR(MP_QSTR_W5K_SCK), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_GP18), MP_ROM_PTR(&pin_GPIO18) }, + + { MP_ROM_QSTR(MP_QSTR_W5K_MOSI), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_GP19), MP_ROM_PTR(&pin_GPIO19) }, + + { MP_ROM_QSTR(MP_QSTR_W5K_RST), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_GP20), MP_ROM_PTR(&pin_GPIO20) }, + + { MP_ROM_QSTR(MP_QSTR_W5K_INT), MP_ROM_PTR(&pin_GPIO21) }, + { 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_ROM_QSTR(MP_QSTR_W5K_SPI), MP_ROM_PTR(&board_spi_obj) }, + { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj) }, + { MP_ROM_QSTR(MP_QSTR_STEMMA_I2C), MP_ROM_PTR(&board_i2c_obj) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/raspberrypi/boards/wiznet_w55rp20_evb_pico/board.c b/ports/raspberrypi/boards/wiznet_w55rp20_evb_pico/board.c new file mode 100755 index 00000000000..e6a868ab212 --- /dev/null +++ b/ports/raspberrypi/boards/wiznet_w55rp20_evb_pico/board.c @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/raspberrypi/boards/wiznet_w55rp20_evb_pico/mpconfigboard.h b/ports/raspberrypi/boards/wiznet_w55rp20_evb_pico/mpconfigboard.h new file mode 100755 index 00000000000..b5ccfb5ffd9 --- /dev/null +++ b/ports/raspberrypi/boards/wiznet_w55rp20_evb_pico/mpconfigboard.h @@ -0,0 +1,30 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#define MICROPY_HW_BOARD_NAME "W55RP20-EVB-Pico" +#define MICROPY_HW_MCU_NAME "rp2040" + +#define MICROPY_HW_LED_STATUS (&pin_GPIO19) + +#define DEFAULT_SPI_BUS_SCK (&pin_GPIO21) +#define DEFAULT_SPI_BUS_MOSI (&pin_GPIO23) +#define DEFAULT_SPI_BUS_MISO (&pin_GPIO22) + +#define DEFAULT_UART_BUS_RX (&pin_GPIO1) +#define DEFAULT_UART_BUS_TX (&pin_GPIO0) + +// Wiznet HW config. +#define MICROPY_HW_WIZNET_PIO_SPI_ID (0) +#define MICROPY_HW_WIZNET_PIO_SPI_BAUDRATE (20 * 1000 * 1000) +#define MICROPY_HW_WIZNET_PIO_SPI_SCK (21) +#define MICROPY_HW_WIZNET_PIO_SPI_MOSI (23) +#define MICROPY_HW_WIZNET_PIO_SPI_MISO (22) +#define MICROPY_HW_WIZNET_PIO_PIN_CS (20) +#define MICROPY_HW_WIZNET_PIO_PIN_RST (25) +// Connecting the INTN pin enables RECV interrupt handling of incoming data. +#define MICROPY_HW_WIZNET_PIN_INTN (24) diff --git a/ports/raspberrypi/boards/wiznet_w55rp20_evb_pico/mpconfigboard.mk b/ports/raspberrypi/boards/wiznet_w55rp20_evb_pico/mpconfigboard.mk new file mode 100755 index 00000000000..edd434fe119 --- /dev/null +++ b/ports/raspberrypi/boards/wiznet_w55rp20_evb_pico/mpconfigboard.mk @@ -0,0 +1,17 @@ +USB_VID = 0x2E8A +USB_PID = 0x0005 +USB_PRODUCT = "W55RP20-EVB-Pico" +USB_MANUFACTURER = "WIZnet" + +CHIP_VARIANT = RP2040 +CHIP_FAMILY = rp2 + +EXTERNAL_FLASH_DEVICES = "PY25Q16HB" + +CIRCUITPY_WIZNET = 1 +CIRCUITPY__EVE = 1 +CIRCUITPY_SSL = 1 +CIRCUITPY_EPAPERDISPLAY_FAST = 0 +CIRCUITPY_USB_HOST = 0 + +OPTIMIZATION_FLAGS = -O2 diff --git a/ports/raspberrypi/boards/wiznet_w55rp20_evb_pico/pico-sdk-configboard.h b/ports/raspberrypi/boards/wiznet_w55rp20_evb_pico/pico-sdk-configboard.h new file mode 100755 index 00000000000..110195b7794 --- /dev/null +++ b/ports/raspberrypi/boards/wiznet_w55rp20_evb_pico/pico-sdk-configboard.h @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Put board-specific pico-sdk definitions here. This file must exist. diff --git a/ports/raspberrypi/boards/wiznet_w55rp20_evb_pico/pins.c b/ports/raspberrypi/boards/wiznet_w55rp20_evb_pico/pins.c new file mode 100755 index 00000000000..37ecfd3dfb1 --- /dev/null +++ b/ports/raspberrypi/boards/wiznet_w55rp20_evb_pico/pins.c @@ -0,0 +1,72 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/board/__init__.h" + +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { 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_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_VBUS_SENSE), MP_ROM_PTR(&pin_GPIO18) }, + { MP_ROM_QSTR(MP_QSTR_GP18), MP_ROM_PTR(&pin_GPIO18) }, + + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_GPIO19) }, + { MP_ROM_QSTR(MP_QSTR_GP19), MP_ROM_PTR(&pin_GPIO19) }, + + { MP_ROM_QSTR(MP_QSTR_W5K_CS), MP_ROM_PTR(&pin_GPIO20) }, + { MP_ROM_QSTR(MP_QSTR_GP20), MP_ROM_PTR(&pin_GPIO20) }, + + { MP_ROM_QSTR(MP_QSTR_W5K_SCK), MP_ROM_PTR(&pin_GPIO21) }, + { MP_ROM_QSTR(MP_QSTR_GP21), MP_ROM_PTR(&pin_GPIO21) }, + + { MP_ROM_QSTR(MP_QSTR_W5K_MISO), MP_ROM_PTR(&pin_GPIO22) }, + { MP_ROM_QSTR(MP_QSTR_GP22), MP_ROM_PTR(&pin_GPIO22) }, + + { MP_ROM_QSTR(MP_QSTR_W5K_MOSI), MP_ROM_PTR(&pin_GPIO23) }, + { MP_ROM_QSTR(MP_QSTR_GP23), MP_ROM_PTR(&pin_GPIO23) }, + + { MP_ROM_QSTR(MP_QSTR_W5K_INT), MP_ROM_PTR(&pin_GPIO24) }, + { MP_ROM_QSTR(MP_QSTR_GP24), MP_ROM_PTR(&pin_GPIO24) }, + + { MP_ROM_QSTR(MP_QSTR_W5K_RST), 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_ROM_QSTR(MP_QSTR_W5K_SPI), MP_ROM_PTR(&board_spi_obj) }, + { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj) }, + { MP_ROM_QSTR(MP_QSTR_STEMMA_I2C), MP_ROM_PTR(&board_i2c_obj) }, +}; +MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/raspberrypi/boot_stage2/RP2350.c.jinja b/ports/raspberrypi/boot_stage2/RP2350.c.jinja index 77969f9fcae..56fc7aabb4b 100644 --- a/ports/raspberrypi/boot_stage2/RP2350.c.jinja +++ b/ports/raspberrypi/boot_stage2/RP2350.c.jinja @@ -62,14 +62,16 @@ void __attribute__((section(".entry._stage2_boot"), used)) _stage2_boot(void) { 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; + // Data lines: clear only each pad's Schmitt trigger bit, so SD2/SD3 + // (WP#/HOLD#) keep their pull-ups. + // + // io[1] to io[4] are SD0 to SD3. SD1 carries read data in serial mode as + // well, so it is always set up. The others matter only in quad mode. + pads_qspi_hw->io[2] &= ~PADS_QSPI_GPIO_QSPI_SD1_SCHMITT_BITS; {% if quad_ok %} - pads_qspi_hw->io[1] = data_settings; - pads_qspi_hw->io[3] = data_settings; - pads_qspi_hw->io[4] = data_settings; + pads_qspi_hw->io[1] &= ~PADS_QSPI_GPIO_QSPI_SD0_SCHMITT_BITS; + pads_qspi_hw->io[3] &= ~PADS_QSPI_GPIO_QSPI_SD2_SCHMITT_BITS; + pads_qspi_hw->io[4] &= ~PADS_QSPI_GPIO_QSPI_SD3_SCHMITT_BITS; {% endif %} // QMI config @@ -122,10 +124,12 @@ void __attribute__((section(".entry._stage2_boot"), used)) _stage2_boot(void) { // Disable direct mode qmi_hw->direct_csr &= ~QMI_DIRECT_CSR_EN_BITS; + // A slow clock divider and a sample delay (RXDELAY) of 6, safe at any + // system clock. See rp2350_clock_divider in gen_stage2.py. qmi_hw->m[0].timing = 1 << QMI_M0_TIMING_COOLDOWN_LSB | - 1 << QMI_M0_TIMING_RXDELAY_LSB | - {{ clock_divider }} << QMI_M0_TIMING_CLKDIV_LSB; + 6 << QMI_M0_TIMING_RXDELAY_LSB | + {{ rp2350_clock_divider }} << QMI_M0_TIMING_CLKDIV_LSB; qmi_hw->m[0].rcmd = READ_INSTRUCTION << QMI_M0_RCMD_PREFIX_LSB | MODE_CONTINUOUS_READ << QMI_M0_RCMD_SUFFIX_LSB; @@ -134,8 +138,9 @@ void __attribute__((section(".entry._stage2_boot"), used)) _stage2_boot(void) { {{ wait_cycles }} << QMI_M0_RFMT_DUMMY_LEN_LSB; {% if quad_ok %} - // Dummy transfer to get into continuous mode. - (void) *((uint32_t*) XIP_NOCACHE_NOALLOC_BASE); + // Dummy transfer to get into continuous mode. It must be volatile, or the + // compiler drops the read and the flash never enters continuous mode. + (void) *((volatile uint32_t*) XIP_NOCACHE_NOALLOC_BASE); // Set prefix to 0 to skip the command portion. qmi_hw->m[0].rfmt &= ~QMI_M0_RFMT_PREFIX_LEN_BITS; diff --git a/ports/raspberrypi/common-hal/alarm/__init__.c b/ports/raspberrypi/common-hal/alarm/__init__.c index c47ddc31505..f70a3dea4d2 100644 --- a/ports/raspberrypi/common-hal/alarm/__init__.c +++ b/ports/raspberrypi/common-hal/alarm/__init__.c @@ -34,16 +34,18 @@ #include "hardware/structs/watchdog.h" // XOSC shutdown -#include "hardware/rtc.h" #include "hardware/pll.h" #include "hardware/regs/io_bank0.h" -// Watchdog scratch register -// Not used elsewhere in the SDK for now, keep an eye on it -#define RP_WKUP_SCRATCH_REG 0 +#if PICO_RP2350 +#include "hardware/powman.h" +#include "pico/low_power.h" +#include "pico/multicore.h" +#endif // Light sleep turns off nonvolatile Busio and other wake-only peripherals // TODO: this only saves about 2mA right now, expand with other non-essentials +#if PICO_RP2040 const uint32_t RP_LIGHTSLEEP_EN0_MASK = ~( CLOCKS_SLEEP_EN0_CLK_SYS_SPI1_BITS | CLOCKS_SLEEP_EN0_CLK_PERI_SPI1_BITS | @@ -59,7 +61,28 @@ const uint32_t RP_LIGHTSLEEP_EN0_MASK = ~( ); // This bank has the USB clocks in it, leave it for now const uint32_t RP_LIGHTSLEEP_EN1_MASK = CLOCKS_SLEEP_EN1_RESET; +#else +// Same peripherals as RP2040. RP2350 adds PIO2 and moves SPI to the second bank. +const uint32_t RP_LIGHTSLEEP_EN0_MASK = ~( + CLOCKS_SLEEP_EN0_CLK_SYS_PWM_BITS | + CLOCKS_SLEEP_EN0_CLK_SYS_PIO2_BITS | + CLOCKS_SLEEP_EN0_CLK_SYS_PIO1_BITS | + CLOCKS_SLEEP_EN0_CLK_SYS_PIO0_BITS | + CLOCKS_SLEEP_EN0_CLK_SYS_I2C1_BITS | + CLOCKS_SLEEP_EN0_CLK_SYS_I2C0_BITS | + CLOCKS_SLEEP_EN0_CLK_SYS_ADC_BITS | + CLOCKS_SLEEP_EN0_CLK_ADC_BITS + ); +// This bank has the USB clocks in it, only turn off SPI +const uint32_t RP_LIGHTSLEEP_EN1_MASK = CLOCKS_SLEEP_EN1_RESET & ~( + CLOCKS_SLEEP_EN1_CLK_SYS_SPI1_BITS | + CLOCKS_SLEEP_EN1_CLK_PERI_SPI1_BITS | + CLOCKS_SLEEP_EN1_CLK_SYS_SPI0_BITS | + CLOCKS_SLEEP_EN1_CLK_PERI_SPI0_BITS + ); +#endif +#if PICO_RP2040 // Light sleeps used for TimeAlarm deep sleep turn off almost everything const uint32_t RP_LIGHTSLEEP_EN0_MASK_HARSH = ( CLOCKS_SLEEP_EN0_CLK_RTC_RTC_BITS | @@ -68,6 +91,7 @@ const uint32_t RP_LIGHTSLEEP_EN0_MASK_HARSH = ( const uint32_t RP_LIGHTSLEEP_EN1_MASK_HARSH = 0x0; static void prepare_for_dormant_xosc(void); +#endif // Singleton instance of SleepMemory. const alarm_sleep_memory_obj_t alarm_sleep_memory_obj = { @@ -80,6 +104,19 @@ const alarm_sleep_memory_obj_t alarm_sleep_memory_obj = { // This object lives across VM instantiations, so none of these objects can contain references to the heap. alarm_wake_alarm_union_t alarm_wake_alarm; +#if PICO_RP2350 +// powman remembers what caused the last power up until the next one. Only report +// it until the first alarm_reset() after boot. +static bool powman_wakeup_reported; + +bool alarm_woke_from_powman(void) { + // powman is not reset by a watchdog reboot, so its registers would be stale. + return (powman_hw->chip_reset & POWMAN_CHIP_RESET_HAD_SWCORE_PD_BITS) && + !watchdog_caused_reboot() && + (powman_hw->last_swcore_pwrup & (RP_POWMAN_PWRUP_GPIO_BITS | RP_POWMAN_PWRUP_ALARM_BITS)); +} +#endif + void alarm_reset(void) { alarm_sleep_memory_reset(); alarm_pin_pinalarm_reset(); @@ -87,6 +124,9 @@ void alarm_reset(void) { // Reset the scratch source watchdog_hw->scratch[RP_WKUP_SCRATCH_REG] = RP_SLEEP_WAKEUP_UNDEF; + #if PICO_RP2350 + powman_wakeup_reported = true; + #endif } static uint8_t _get_wakeup_cause(void) { @@ -102,6 +142,14 @@ static uint8_t _get_wakeup_cause(void) { if (watchdog_hw->scratch[RP_WKUP_SCRATCH_REG] != RP_SLEEP_WAKEUP_UNDEF) { return watchdog_hw->scratch[RP_WKUP_SCRATCH_REG]; } + #if PICO_RP2350 + if (!powman_wakeup_reported && alarm_woke_from_powman()) { + if (powman_hw->last_swcore_pwrup & RP_POWMAN_PWRUP_ALARM_BITS) { + return RP_SLEEP_WAKEUP_RTC; + } + return RP_SLEEP_WAKEUP_GPIO; + } + #endif return RP_SLEEP_WAKEUP_UNDEF; } @@ -172,7 +220,7 @@ mp_obj_t common_hal_alarm_light_sleep_until_alarms(size_t n_alarms, const mp_obj clocks_hw->sleep_en1 = RP_LIGHTSLEEP_EN1_MASK; // Enable System Control Block (SCB) deep sleep - scb_hw->scr |= M0PLUS_SCR_SLEEPDEEP_BITS; + scb_hw->scr |= ARM_CPU_PREFIXED(SCR_SLEEPDEEP_BITS); __wfi(); } @@ -191,13 +239,48 @@ mp_obj_t common_hal_alarm_light_sleep_until_alarms(size_t n_alarms, const mp_obj } void common_hal_alarm_set_deep_sleep_alarms(size_t n_alarms, const mp_obj_t *alarms, size_t n_dios, digitalio_digitalinout_obj_t **preserve_dios) { - if (n_dios > 0) { - mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_preserve_dios); - } _setup_sleep_alarms(true, n_alarms, alarms); } -void NORETURN common_hal_alarm_enter_deep_sleep(void) { +#if PICO_RP2350 +// Power down with powman. Waking up reboots into main(), so this does not return. +static void MP_NORETURN rp2350_enter_deep_sleep(void) { + #if CIRCUITPY_CYW43 + cyw43_enter_deep_sleep(); + #endif + + // Powman does not power down until both cores are in __wfi(). Core1 may be + // busy, for example running the PIO USB host loop, so park it in the bootrom. + multicore_reset_core1(); + + // pico_low_power arms one wakeup per call and leaves the others alone, so + // arm every pin alarm first. + alarm_pin_pinalarm_enable_powman_wakeups(); + + // A NULL power state keeps only the SRAM that holds .persistent_data powered. + // That is where alarm.sleep_memory lives. + uint pin_number; + bool edge; + bool value; + if (!alarm_time_timealarm_is_set() && + alarm_pin_pinalarm_first_powman_wakeup(&pin_number, &edge, &value)) { + low_power_pstate_until_gpio_pin_state(pin_number, edge, value, NULL, NULL); + } else { + // With no alarm at all, sleep until a time that never comes. + uint64_t wakeup_ms = alarm_time_timealarm_is_set() ? alarm_time_timealarm_get_wakeup_ms() : INT64_MAX / 1000; + low_power_pstate_until_aon_timer(from_us_since_boot(wakeup_ms * 1000), NULL, NULL); + } + + // Could not power down, most likely because an alarm already fired. + watchdog_hw->scratch[RP_WKUP_SCRATCH_REG] = _get_wakeup_cause(); + reset_cpu(); +} +#endif + +void MP_NORETURN common_hal_alarm_enter_deep_sleep(void) { + #if PICO_RP2350 + rp2350_enter_deep_sleep(); + #else bool timealarm_set = alarm_time_timealarm_is_set(); #if CIRCUITPY_CYW43 @@ -222,16 +305,19 @@ void NORETURN common_hal_alarm_enter_deep_sleep(void) { // Reset uses the watchdog. Use scratch registers to store wake reason watchdog_hw->scratch[RP_WKUP_SCRATCH_REG] = _get_wakeup_cause(); + alarm_pin_pinalarm_save_wake_pin(); // Just before reset, enable the pinalarm interrupt. alarm_pin_pinalarm_entering_deep_sleep(); reset_cpu(); + #endif } void common_hal_alarm_gc_collect(void) { gc_collect_ptr(shared_alarm_get_wake_alarm()); } +#if PICO_RP2040 static void prepare_for_dormant_xosc(void) { // TODO: add ROSC support with sleep_run_from_dormant_source when it's added to SDK uint src_hz = XOSC_MHZ * MHZ; @@ -262,3 +348,4 @@ static void prepare_for_dormant_xosc(void) { pll_deinit(pll_sys); pll_deinit(pll_usb); } +#endif diff --git a/ports/raspberrypi/common-hal/alarm/__init__.h b/ports/raspberrypi/common-hal/alarm/__init__.h index 49e06a4c323..c4ca9d44322 100644 --- a/ports/raspberrypi/common-hal/alarm/__init__.h +++ b/ports/raspberrypi/common-hal/alarm/__init__.h @@ -16,6 +16,27 @@ #define RP_SLEEP_WAKEUP_GPIO 1 #define RP_SLEEP_WAKEUP_RTC 2 +// Watchdog scratch registers survive the reset that ends a deep sleep. +// The SDK and bootrom use scratch registers 4 to 7. +// +// RP_WKUP_SCRATCH_REG holds the RP_SLEEP_WAKEUP_* cause. +// RP_WKUP_PIN_SCRATCH_REG holds the GPIO number that woke an RP2040 from deep sleep, +// plus 1. 0 means no pin. +#define RP_WKUP_SCRATCH_REG 0 +#define RP_WKUP_PIN_SCRATCH_REG 1 + +// Bits in powman_hw->last_swcore_pwrup. Bit 0 is a chip reset, bits 1 to 4 are +// the four GPIO wakeups and bit 6 is the timer alarm. +#define RP_POWMAN_PWRUP_GPIO_LSB 1 +#define RP_POWMAN_PWRUP_GPIO_BITS 0x1e +#define RP_POWMAN_PWRUP_ALARM_BITS 0x40 + +#if PICO_RP2350 +// Returns true when this boot is powman powering the core back up for a deep +// sleep alarm. Returns false after any other kind of reset. +bool alarm_woke_from_powman(void); +#endif + typedef union { alarm_pin_pinalarm_obj_t pin_alarm; alarm_time_timealarm_obj_t time_alarm; diff --git a/ports/raspberrypi/common-hal/alarm/pin/PinAlarm.c b/ports/raspberrypi/common-hal/alarm/pin/PinAlarm.c index ecebb072775..da0e3e74746 100644 --- a/ports/raspberrypi/common-hal/alarm/pin/PinAlarm.c +++ b/ports/raspberrypi/common-hal/alarm/pin/PinAlarm.c @@ -14,16 +14,32 @@ #include "pico/stdlib.h" #include "hardware/gpio.h" #include "hardware/structs/iobank0.h" +#include "hardware/structs/watchdog.h" + +#if PICO_RP2350 +#include "hardware/powman.h" + +// Deep sleep on RP2350 wakes through powman, which has four GPIO wakeup slots. +// The alarm objects are gone by the time we enter deep sleep, so copy what we need. +#define POWMAN_WAKEUP_SLOTS (count_of(powman_hw->pwrup)) +typedef struct { + uint8_t pin_number; + bool edge; + bool value; +} powman_wakeup_t; +static powman_wakeup_t powman_wakeups[POWMAN_WAKEUP_SLOTS]; +static size_t powman_wakeup_count; +#endif static bool woke_up; -static uint64_t alarm_triggered_pins; // 36 actual pins -static uint64_t alarm_reserved_pins; // 36 actual pins +static uint64_t alarm_triggered_pins; // One bit per GPIO. RP2350B has 48. +static uint64_t alarm_reserved_pins; // One bit per GPIO. RP2350B has 48. static bool _not_yet_deep_sleeping = false; #define GPIO_IRQ_ALL_EVENTS 0x15u static void gpio_callback(uint gpio, uint32_t events) { - alarm_triggered_pins |= (1 << gpio); + alarm_triggered_pins |= (1ULL << gpio); woke_up = true; // gpio_acknowledge_irq(gpio, events) is called automatically, before this callback is called. @@ -39,7 +55,7 @@ static void gpio_callback(uint gpio, uint32_t events) { } } -void alarm_pin_pinalarm_entering_deep_sleep() { +void alarm_pin_pinalarm_entering_deep_sleep(void) { _not_yet_deep_sleeping = false; } @@ -76,25 +92,56 @@ mp_obj_t alarm_pin_pinalarm_find_triggered_alarm(size_t n_alarms, const mp_obj_t continue; } alarm_pin_pinalarm_obj_t *alarm = MP_OBJ_TO_PTR(alarms[i]); - if (alarm_triggered_pins & (1 << alarm->pin->number)) { + if (alarm_triggered_pins & (1ULL << alarm->pin->number)) { return alarms[i]; } } return mp_const_none; } +// Returns the lowest-numbered pin in alarm_triggered_pins, or -1 if there is none. +static int lowest_triggered_pin_number(void) { + return alarm_triggered_pins == 0 ? -1 : __builtin_ctzll(alarm_triggered_pins); +} + mp_obj_t alarm_pin_pinalarm_record_wake_alarm(void) { alarm_pin_pinalarm_obj_t *const alarm = &alarm_wake_alarm.pin_alarm; alarm->base.type = &alarm_pin_pinalarm_type; - // TODO: how to obtain the correct pin from memory? alarm->pin = NULL; + if (woke_up) { + // A fake deep sleep doesn't reset, so gpio_callback()'s record is still here. + alarm->pin = mcu_get_pin_by_number(lowest_triggered_pin_number()); + return alarm; + } + #if PICO_RP2040 + // The reset that ended deep sleep cleared alarm_triggered_pins, so use the saved copy. + uint32_t wake_pin = watchdog_hw->scratch[RP_WKUP_PIN_SCRATCH_REG]; + if (wake_pin != 0) { + alarm->pin = mcu_get_pin_by_number(wake_pin - 1); + } + #endif + #if PICO_RP2350 + // After a powman wake, the wakeup slot that fired still holds its pin number. + if (alarm_woke_from_powman()) { + uint32_t pwrup = powman_hw->last_swcore_pwrup & RP_POWMAN_PWRUP_GPIO_BITS; + for (size_t i = 0; i < POWMAN_WAKEUP_SLOTS; i++) { + if (pwrup & (1u << (i + RP_POWMAN_PWRUP_GPIO_LSB))) { + alarm->pin = mcu_get_pin_by_number(powman_hw->pwrup[i] & POWMAN_PWRUP0_SOURCE_BITS); + break; + } + } + } + #endif return alarm; } void alarm_pin_pinalarm_reset(void) { alarm_triggered_pins = 0; woke_up = false; + #if PICO_RP2040 + watchdog_hw->scratch[RP_WKUP_PIN_SCRATCH_REG] = 0; + #endif // Clear all GPIO interrupts for (uint8_t i = 0; i < 4; i++) { @@ -103,19 +150,41 @@ void alarm_pin_pinalarm_reset(void) { // Reset pins and pin IRQs for (size_t i = 0; i < NUM_BANK0_GPIOS; i++) { - if (alarm_reserved_pins & (1 << i)) { + if (alarm_reserved_pins & (1ULL << i)) { gpio_set_irq_enabled(i, GPIO_IRQ_ALL_EVENTS, false); reset_pin_number(i); } } alarm_reserved_pins = 0; + + #if PICO_RP2350 + for (size_t i = 0; i < POWMAN_WAKEUP_SLOTS; i++) { + powman_disable_gpio_wakeup(i); + } + powman_wakeup_count = 0; + #endif } void alarm_pin_pinalarm_set_alarms(bool deep_sleep, size_t n_alarms, const mp_obj_t *alarms) { + #if PICO_RP2350 + powman_wakeup_count = 0; + #endif for (size_t i = 0; i < n_alarms; i++) { if (mp_obj_is_type(alarms[i], &alarm_pin_pinalarm_type)) { alarm_pin_pinalarm_obj_t *alarm = MP_OBJ_TO_PTR(alarms[i]); + #if PICO_RP2350 + if (deep_sleep) { + if (powman_wakeup_count >= POWMAN_WAKEUP_SLOTS) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("Too many %q"), MP_QSTR_PinAlarm); + } + powman_wakeups[powman_wakeup_count].pin_number = alarm->pin->number; + powman_wakeups[powman_wakeup_count].edge = alarm->edge; + powman_wakeups[powman_wakeup_count].value = alarm->value; + powman_wakeup_count++; + } + #endif + gpio_init(alarm->pin->number); if (alarm->pull) { // If value is high, the pullup should be off, and vice versa @@ -126,8 +195,7 @@ void alarm_pin_pinalarm_set_alarms(bool deep_sleep, size_t n_alarms, const mp_ob } gpio_set_dir(alarm->pin->number, GPIO_IN); // Don't reset at end of VM (instead, pinalarm_reset will reset before next VM) - common_hal_never_reset_pin(alarm->pin); - alarm_reserved_pins |= (1 << alarm->pin->number); + alarm_reserved_pins |= (1ULL << alarm->pin->number); uint32_t event; if (alarm->value == true && alarm->edge == true) { @@ -149,3 +217,31 @@ void alarm_pin_pinalarm_set_alarms(bool deep_sleep, size_t n_alarms, const mp_ob } } } + +#if PICO_RP2040 +void alarm_pin_pinalarm_save_wake_pin(void) { + // No pin gives -1 + 1 = 0. + watchdog_hw->scratch[RP_WKUP_PIN_SCRATCH_REG] = lowest_triggered_pin_number() + 1; +} +#endif + +#if PICO_RP2350 +// Arm the powman GPIO wakeups recorded by alarm_pin_pinalarm_set_alarms(). +// Call this just before powering down for deep sleep. +void alarm_pin_pinalarm_enable_powman_wakeups(void) { + for (size_t i = 0; i < powman_wakeup_count; i++) { + powman_enable_gpio_wakeup(i, powman_wakeups[i].pin_number, + powman_wakeups[i].edge, powman_wakeups[i].value); + } +} + +bool alarm_pin_pinalarm_first_powman_wakeup(uint *pin_number, bool *edge, bool *value) { + if (powman_wakeup_count == 0) { + return false; + } + *pin_number = powman_wakeups[0].pin_number; + *edge = powman_wakeups[0].edge; + *value = powman_wakeups[0].value; + return true; +} +#endif diff --git a/ports/raspberrypi/common-hal/alarm/pin/PinAlarm.h b/ports/raspberrypi/common-hal/alarm/pin/PinAlarm.h index b9f81da847f..178d9594656 100644 --- a/ports/raspberrypi/common-hal/alarm/pin/PinAlarm.h +++ b/ports/raspberrypi/common-hal/alarm/pin/PinAlarm.h @@ -27,3 +27,17 @@ void alarm_pin_pinalarm_light_reset(void); void alarm_pin_pinalarm_set_alarms(bool deep_sleep, size_t n_alarms, const mp_obj_t *alarms); bool alarm_pin_pinalarm_woke_this_cycle(void); void alarm_pin_pinalarm_entering_deep_sleep(void); +#if PICO_RP2040 +// Saves the lowest-numbered triggered pin in a watchdog scratch register, or +// saves "no pin" if no pin alarm went off. Call this just before the reset that +// ends a deep sleep. alarm_pin_pinalarm_record_wake_alarm() reads it after the reset. +void alarm_pin_pinalarm_save_wake_pin(void); +#endif +#if PICO_RP2350 +// Arms the powman GPIO wakeups for the pin alarms given to +// alarm_pin_pinalarm_set_alarms() with deep_sleep true. +void alarm_pin_pinalarm_enable_powman_wakeups(void); +// Returns false and leaves the outputs alone when no pin alarm was set for deep sleep. +// Otherwise fills in the pin alarm that uses powman wakeup slot 0 and returns true. +bool alarm_pin_pinalarm_first_powman_wakeup(uint *pin_number, bool *edge, bool *value); +#endif diff --git a/ports/raspberrypi/common-hal/alarm/time/TimeAlarm.c b/ports/raspberrypi/common-hal/alarm/time/TimeAlarm.c index 1f7c3f9edab..c007116a571 100644 --- a/ports/raspberrypi/common-hal/alarm/time/TimeAlarm.c +++ b/ports/raspberrypi/common-hal/alarm/time/TimeAlarm.c @@ -10,13 +10,14 @@ #include "shared-bindings/alarm/time/TimeAlarm.h" #include "shared-bindings/time/__init__.h" -#include "shared/timeutils/timeutils.h" - #include "hardware/gpio.h" -#include "hardware/rtc.h" +#include "pico/aon_timer.h" static bool woke_up = false; static bool _timealarm_set = false; +#if PICO_RP2350 +static uint64_t _wakeup_ms; +#endif static void timer_callback(void) { woke_up = true; @@ -53,7 +54,7 @@ bool alarm_time_timealarm_woke_this_cycle(void) { } void alarm_time_timealarm_reset(void) { - rtc_disable_alarm(); + aon_timer_disable_alarm(); woke_up = false; } @@ -81,28 +82,19 @@ 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 mono_seconds_to_date = uint64_to_float(common_hal_time_monotonic_ms()) / 1000.0f; mp_float_t wakeup_in_secs = MAX(0.0f, timealarm->monotonic_time - mono_seconds_to_date); - datetime_t t; - - rtc_get_datetime(&t); + struct timespec t; - uint32_t rtc_seconds_to_date = timeutils_seconds_since_2000(t.year, t.month, - t.day, t.hour, t.min, t.sec); + aon_timer_get_time(&t); // The float value is always slightly under, so add 1 to compensate - uint32_t alarm_seconds = rtc_seconds_to_date + (uint32_t)wakeup_in_secs + 1; - timeutils_struct_time_t tm; - timeutils_seconds_since_2000_to_struct_time(alarm_seconds, &tm); - - // reuse t - t.hour = tm.tm_hour; - t.min = tm.tm_min; - t.sec = tm.tm_sec; - t.day = tm.tm_mday; - t.month = tm.tm_mon; - t.year = tm.tm_year; - t.dotw = (tm.tm_wday + 1) % 7; + t.tv_sec += (uint32_t)wakeup_in_secs + 1; + t.tv_nsec = 0; - rtc_set_alarm(&t, &timer_callback); + // On RP2350 the last argument makes the alarm a powman wakeup source. + aon_timer_enable_alarm(&t, &timer_callback, deep_sleep); + #if PICO_RP2350 + _wakeup_ms = (uint64_t)t.tv_sec * 1000; + #endif woke_up = false; } @@ -110,3 +102,9 @@ void alarm_time_timealarm_set_alarms(bool deep_sleep, size_t n_alarms, const mp_ bool alarm_time_timealarm_is_set(void) { return _timealarm_set; } + +#if PICO_RP2350 +uint64_t alarm_time_timealarm_get_wakeup_ms(void) { + return _wakeup_ms; +} +#endif diff --git a/ports/raspberrypi/common-hal/alarm/time/TimeAlarm.h b/ports/raspberrypi/common-hal/alarm/time/TimeAlarm.h index 824bf5ef9e0..83db9bbe591 100644 --- a/ports/raspberrypi/common-hal/alarm/time/TimeAlarm.h +++ b/ports/raspberrypi/common-hal/alarm/time/TimeAlarm.h @@ -20,3 +20,8 @@ void alarm_time_timealarm_reset(void); void alarm_time_timealarm_set_alarms(bool deep_sleep, size_t n_alarms, const mp_obj_t *alarms); bool alarm_time_timealarm_woke_this_cycle(void); bool alarm_time_timealarm_is_set(void); +#if PICO_RP2350 +// Returns the AON timer time, in milliseconds, of the last alarm given to +// alarm_time_timealarm_set_alarms(). Only meaningful when alarm_time_timealarm_is_set(). +uint64_t alarm_time_timealarm_get_wakeup_ms(void); +#endif diff --git a/ports/raspberrypi/common-hal/analogbufio/BufferedIn.c b/ports/raspberrypi/common-hal/analogbufio/BufferedIn.c index 6862f2799f2..255ef90f784 100644 --- a/ports/raspberrypi/common-hal/analogbufio/BufferedIn.c +++ b/ports/raspberrypi/common-hal/analogbufio/BufferedIn.c @@ -15,27 +15,33 @@ #include "hardware/dma.h" #include "pico/stdlib.h" -#define ADC_FIRST_PIN_NUMBER 26 -#define ADC_PIN_COUNT 4 - #define ADC_CLOCK_INPUT 48000000 #define ADC_MAX_CLOCK_DIV (1 << (ADC_DIV_INT_MSB - ADC_DIV_INT_LSB + 1)) void common_hal_analogbufio_bufferedin_construct(analogbufio_bufferedin_obj_t *self, const mcu_pin_obj_t *pin, uint32_t sample_rate) { // Make sure pin number is in range for ADC - if (pin->number < ADC_FIRST_PIN_NUMBER || pin->number >= (ADC_FIRST_PIN_NUMBER + ADC_PIN_COUNT)) { - raise_ValueError_invalid_pins(); + if ((pin->number < ADC_BASE_PIN) + || (pin->number > ADC_BASE_PIN + NUM_ADC_CHANNELS - 1) + // On many boards with a CYW43 radio co-processor, CYW43_DEFAULT_PIN_WL_CLOCK (usually GPIO29), + // is both a voltage monitor and also SPI SCK to the CYW43. + // Disallow its use for BufferedIn. + #if defined(CIRCUITPY_CYW43) && defined(CYW43_DEFAULT_PIN_WL_CLOCK) + || (pin->number == CYW43_DEFAULT_PIN_WL_CLOCK) + #endif + ) { + raise_ValueError_invalid_pin(); } - // Validate sample rate here - sample_rate = (uint32_t)mp_arg_validate_int_range(sample_rate, ADC_CLOCK_INPUT / ADC_MAX_CLOCK_DIV, ADC_CLOCK_INPUT / 96, MP_QSTR_sample_rate); + // Validate sample rate here. The divider is ADC_CLOCK_INPUT / sample_rate - 1 and must + // stay below ADC_MAX_CLOCK_DIV, so the lowest rate is 733 Hz, not 732. + sample_rate = (uint32_t)mp_arg_validate_int_range(sample_rate, ADC_CLOCK_INPUT / (ADC_MAX_CLOCK_DIV + 1) + 1, ADC_CLOCK_INPUT / 96, MP_QSTR_sample_rate); // Set pin and channel self->pin = pin; claim_pin(pin); // TODO: find a way to accept ADC4 for temperature - self->chan = pin->number - ADC_FIRST_PIN_NUMBER; + self->chan = pin->number - ADC_BASE_PIN; // Init GPIO for analogue use: hi-Z, no pulls, disable digital input buffer. // TODO: Make sure we share the ADC well. Right now we just assume it is diff --git a/ports/raspberrypi/common-hal/analogio/AnalogIn.c b/ports/raspberrypi/common-hal/analogio/AnalogIn.c index 9d107c8d14b..2a9c2d1d42d 100644 --- a/ports/raspberrypi/common-hal/analogio/AnalogIn.c +++ b/ports/raspberrypi/common-hal/analogio/AnalogIn.c @@ -12,20 +12,12 @@ #include "hardware/adc.h" -#define ADC_PIN_COUNT (NUM_ADC_CHANNELS - 1) - -#if ADC_PIN_COUNT == 4 -#define ADC_FIRST_PIN_NUMBER 26 -#else -#define ADC_FIRST_PIN_NUMBER 40 -#endif - -// Voltage monitor is special on Pico W, because this pin is shared between the -// voltage monitor function and the wifi function. Special handling is required -// to read the analog voltage. +// On many boards with a CYW43 radio co-processor, CYW43_DEFAULT_PIN_WL_CLOCK (usually GPIO29), +// is both a voltage monitor and also SPI SCK to the CYW43. +// Special handling is required to read the analog voltage. #if CIRCUITPY_CYW43 #include "bindings/cyw43/__init__.h" -#define SPECIAL_PIN(pin) (pin->number == 29) +#define SPECIAL_PIN(pin) (pin->number == CYW43_DEFAULT_PIN_WL_CLOCK) const mcu_pin_obj_t *common_hal_analogio_analogin_validate_pin(mp_obj_t obj) { return validate_obj_is_free_pin_or_gpio29(obj, MP_QSTR_pin); @@ -35,7 +27,7 @@ const mcu_pin_obj_t *common_hal_analogio_analogin_validate_pin(mp_obj_t obj) { #endif void common_hal_analogio_analogin_construct(analogio_analogin_obj_t *self, const mcu_pin_obj_t *pin) { - if (pin->number < ADC_FIRST_PIN_NUMBER || pin->number > ADC_FIRST_PIN_NUMBER + ADC_PIN_COUNT) { + if (pin->number < ADC_BASE_PIN || pin->number > ADC_BASE_PIN + NUM_ADC_CHANNELS - 1) { raise_ValueError_invalid_pin(); } @@ -70,7 +62,7 @@ uint16_t common_hal_analogio_analogin_get_value(analogio_analogin_obj_t *self) { uint32_t old_pad = pads_bank0_hw->io[self->pin->number]; uint32_t old_ctrl = io_bank0_hw->io[self->pin->number].ctrl; adc_gpio_init(self->pin->number); - adc_select_input(self->pin->number - ADC_FIRST_PIN_NUMBER); + adc_select_input(self->pin->number - ADC_BASE_PIN); common_hal_mcu_delay_us(100); value = adc_read(); gpio_init(self->pin->number); @@ -78,7 +70,7 @@ uint16_t common_hal_analogio_analogin_get_value(analogio_analogin_obj_t *self) { io_bank0_hw->io[self->pin->number].ctrl = old_ctrl; common_hal_mcu_enable_interrupts(); } else { - adc_select_input(self->pin->number - ADC_FIRST_PIN_NUMBER); + adc_select_input(self->pin->number - ADC_BASE_PIN); value = adc_read(); } // Stretch 12-bit ADC reading to 16-bit range diff --git a/ports/raspberrypi/common-hal/async_spi/SPI.c b/ports/raspberrypi/common-hal/async_spi/SPI.c new file mode 100644 index 00000000000..b610cd8b34f --- /dev/null +++ b/ports/raspberrypi/common-hal/async_spi/SPI.c @@ -0,0 +1,392 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/async_spi/SPI.h" + +#include "py/runtime.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "supervisor/background_callback.h" + +#include "hardware/dma.h" +#include "hardware/gpio.h" +#include "hardware/irq.h" + +#define NO_INSTANCE 0xff + +// Done flag of the async transfer on each kept RX channel, set when that channel finishes. +static circuitpy_async_flag_t *async_flags[NUM_DMA_CHANNELS]; +// RX channels with the interrupt enabled. +static uint32_t async_irq_mask; + +// Shared DMA_IRQ_0 handler: acknowledges and services only our channels, like audio_dma and rp2pio. +static void __not_in_flash_func(spi_dma_irq_handler)(void) { + uint32_t pending = dma_hw->ints0 & async_irq_mask; + dma_hw->ints0 = pending; + for (uint chan = 0; pending != 0; chan++, pending >>= 1) { + if ((pending & 1) && async_flags[chan] != NULL) { + CIRCUITPY_ASYNC_FLAG_SET(async_flags[chan]); + } + } +} + +static void async_irq_enable(uint chan) { + dma_hw->ints0 = 1u << chan; + if (async_irq_mask == 0) { + irq_add_shared_handler(DMA_IRQ_0, spi_dma_irq_handler, PICO_SHARED_IRQ_HANDLER_DEFAULT_ORDER_PRIORITY); + } + async_irq_mask |= 1u << chan; + dma_irqn_set_channel_enabled(0, chan, true); + irq_set_enabled(DMA_IRQ_0, true); +} + +static void async_irq_disable(uint chan) { + dma_irqn_set_channel_enabled(0, chan, false); + async_irq_mask &= ~(1u << chan); + if (async_irq_mask == 0) { + irq_remove_handler(DMA_IRQ_0, spi_dma_irq_handler); + } + if (dma_hw->inte0 == 0) { + irq_set_enabled(DMA_IRQ_0, false); + } +} + +void common_hal_async_spi_spi_construct(async_spi_spi_obj_t *self, const mcu_pin_obj_t *clock, + const mcu_pin_obj_t *mosi, const mcu_pin_obj_t *miso) { + size_t instance_index = NO_INSTANCE; + + // Ensure the object starts in its deinit state. + self->clock = NULL; + + if (clock->number % 4 == 2) { + instance_index = (clock->number / 8) % 2; + } + if (mosi != NULL) { + // Make sure the set MOSI matches the clock settings. + if (mosi->number % 4 != 3 || + (mosi->number / 8) % 2 != instance_index) { + instance_index = NO_INSTANCE; + } + } + if (miso != NULL) { + // Make sure the set MOSI matches the clock settings. + if (miso->number % 4 != 0 || + (miso->number / 8) % 2 != instance_index) { + instance_index = NO_INSTANCE; + } + } + + // TODO: Check to see if we're sharing the SPI with a native APA102. + + if (instance_index > 1) { + raise_ValueError_invalid_pins(); + } + + if (instance_index == 0) { + self->peripheral = spi0; + } else if (instance_index == 1) { + self->peripheral = spi1; + } + + if ((spi_get_hw(self->peripheral)->cr1 & SPI_SSPCR1_SSE_BITS) != 0) { + mp_raise_ValueError(MP_ERROR_TEXT("SPI peripheral in use")); + } + + circuitpy_async_lock_init(&self->lock); + self->async_active = false; + self->dma_kept = false; + self->target_frequency = 250000; + self->real_frequency = spi_init(self->peripheral, self->target_frequency); // mode 0, 8 bits + self->polarity = 0; + self->phase = 0; + self->bits = 8; + + gpio_set_function(clock->number, GPIO_FUNC_SPI); + claim_pin(clock); + self->clock = clock; + + self->mosi = mosi; + if (mosi != NULL) { + gpio_set_function(mosi->number, GPIO_FUNC_SPI); + claim_pin(mosi); + } + + self->miso = miso; + if (miso != NULL) { + gpio_set_function(miso->number, GPIO_FUNC_SPI); + claim_pin(miso); + } +} + +bool common_hal_async_spi_spi_deinited(async_spi_spi_obj_t *self) { + return self->clock == NULL; +} + +void common_hal_async_spi_spi_mark_deinit(async_spi_spi_obj_t *self) { + self->clock = NULL; +} + +static void _abort(async_spi_spi_obj_t *self); + +void common_hal_async_spi_spi_deinit(async_spi_spi_obj_t *self) { + if (common_hal_async_spi_spi_deinited(self)) { + return; + } + circuitpy_async_lock_deinit(&self->lock); + if (self->async_active) { + _abort(self); + CIRCUITPY_ASYNC_FLAG_SET(self->async_done); + } + if (self->dma_kept) { + async_irq_disable(self->dma_rx); + dma_channel_unclaim(self->dma_tx); + dma_channel_unclaim(self->dma_rx); + self->dma_kept = false; + } + spi_deinit(self->peripheral); + + common_hal_reset_pin(self->clock); + common_hal_reset_pin(self->mosi); + common_hal_reset_pin(self->miso); + + self->clock = NULL; +} + +static void _apply(async_spi_spi_obj_t *self, uint32_t baudrate, uint8_t polarity, uint8_t phase, + uint8_t bits) { + if (baudrate == self->target_frequency && + polarity == self->polarity && + phase == self->phase && + bits == self->bits) { + return; + } + + spi_set_format(self->peripheral, bits, polarity, phase, SPI_MSB_FIRST); + + // Workaround to start with clock line high if polarity=1. The hw SPI peripheral does not do this + // automatically. See https://github.com/raspberrypi/pico-sdk/issues/868 and + // https://forums.raspberrypi.com/viewtopic.php?t=336142 + // TODO: scheduled to be be fixed in pico-sdk 1.5.0. + if (polarity) { + hw_clear_bits(&spi_get_hw(self->peripheral)->cr1, SPI_SSPCR1_SSE_BITS); // disable the SPI + hw_set_bits(&spi_get_hw(self->peripheral)->cr1, SPI_SSPCR1_SSE_BITS); // re-enable the SPI + } + + self->polarity = polarity; + self->phase = phase; + self->bits = bits; + self->target_frequency = baudrate; + self->real_frequency = spi_set_baudrate(self->peripheral, baudrate); +} + +// The caller holds the lock, so no transfer is running. +void common_hal_async_spi_spi_configure(async_spi_spi_obj_t *self, uint32_t baudrate, + uint8_t polarity, uint8_t phase, uint8_t bits) { + _apply(self, baudrate, polarity, phase, bits); +} + +circuitpy_async_lock_obj_t *common_hal_async_spi_spi_get_lock(async_spi_spi_obj_t *self) { + return &self->lock; +} + +uint8_t common_hal_async_spi_spi_get_polarity(async_spi_spi_obj_t *self) { + return self->polarity; +} + +uint8_t common_hal_async_spi_spi_get_phase(async_spi_spi_obj_t *self) { + return self->phase; +} + +uint32_t common_hal_async_spi_spi_get_frequency(async_spi_spi_obj_t *self) { + return self->real_frequency; +} + +// Start a transfer. With DMA it runs in the background and done is set from the interrupt; +// otherwise it is done in software before this returns. An out or in buffer shorter than the +// transfer is one byte repeated or dropped. The DMA channels are kept until deinit, for buses +// that send often. Returns whether DMA is running. +static bool _start(async_spi_spi_obj_t *self, + const uint8_t *data_out, size_t out_len, + uint8_t *data_in, size_t in_len, circuitpy_async_flag_t *done) { + size_t len = MAX(out_len, in_len); + // Only use DMA if both data buffers are in SRAM. Otherwise, we'll stall the DMA with PSRAM or flash cache misses. + bool use_dma = len >= 32 && data_in >= (uint8_t *)SRAM_BASE && data_out >= (uint8_t *)SRAM_BASE; + if (use_dma && !self->dma_kept) { + int chan_tx = dma_claim_unused_channel(false); + int chan_rx = dma_claim_unused_channel(false); + if (chan_tx >= 0 && chan_rx >= 0) { + self->dma_tx = chan_tx; + self->dma_rx = chan_rx; + self->dma_kept = true; + async_irq_enable(chan_rx); + } else { + // If we have claimed only one channel successfully, release it. + if (chan_tx >= 0) { + dma_channel_unclaim(chan_tx); + } + if (chan_rx >= 0) { + dma_channel_unclaim(chan_rx); + } + use_dma = false; + } + } + if (use_dma) { + dma_channel_config c = dma_channel_get_default_config(self->dma_tx); + channel_config_set_transfer_data_size(&c, DMA_SIZE_8); + channel_config_set_dreq(&c, spi_get_index(self->peripheral) ? DREQ_SPI1_TX : DREQ_SPI0_TX); + channel_config_set_read_increment(&c, out_len == len); + channel_config_set_write_increment(&c, false); + dma_channel_configure(self->dma_tx, &c, + &spi_get_hw(self->peripheral)->dr, + data_out, + len, + false); + + c = dma_channel_get_default_config(self->dma_rx); + channel_config_set_transfer_data_size(&c, DMA_SIZE_8); + channel_config_set_dreq(&c, spi_get_index(self->peripheral) ? DREQ_SPI1_RX : DREQ_SPI0_RX); + channel_config_set_read_increment(&c, false); + channel_config_set_write_increment(&c, in_len == len); + dma_channel_configure(self->dma_rx, &c, + data_in, + &spi_get_hw(self->peripheral)->dr, + len, + false); + + // Before the start, so that a short transfer cannot finish unseen. + async_flags[self->dma_rx] = done; + dma_start_channel_mask((1u << self->dma_rx) | (1u << self->dma_tx)); + return true; + } + + // Use software for small transfers, or if couldn't claim two DMA channels + // Never have more transfers in flight than will fit into the RX FIFO, + // else FIFO will overflow if this code is heavily interrupted. + const size_t fifo_depth = 8; + size_t rx_remaining = len; + size_t tx_remaining = len; + + while (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; + // Increment only if the buffer is the transfer length. It's 1 otherwise. + if (out_len == len) { + data_out++; + } + --tx_remaining; + } + if (rx_remaining && spi_is_readable(self->peripheral)) { + *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++; + } + --rx_remaining; + } + RUN_BACKGROUND_TASKS; + } + return false; +} + +// Waits for the running async transfer, if any, and sets its done flag. No background tasks: +// the caller holds the bus, and one of them may want it. +static void _end(async_spi_spi_obj_t *self) { + if (!self->async_active) { + return; + } + // The RX channel finishes last. + while (dma_channel_is_busy(self->dma_rx)) { + } + self->async_active = false; + async_flags[self->dma_rx] = NULL; + CIRCUITPY_ASYNC_FLAG_SET(self->async_done); +} + +// Start an async transfer after the previous one; done is set when it has finished, here if +// it ran in software. The buffers must stay valid until then. +static __attribute__((noinline)) void _async_start(async_spi_spi_obj_t *self, const uint8_t *data_out, + size_t out_len, uint8_t *data_in, size_t in_len, circuitpy_async_flag_t *done) { + _end(self); + CIRCUITPY_ASYNC_FLAG_INIT(done); + self->async_done = done; + // An empty data side means there is nothing to send, whatever the one-byte side holds. + self->async_active = out_len != 0 && in_len != 0 && + _start(self, data_out, out_len, data_in, in_len, done); + if (!self->async_active) { + CIRCUITPY_ASYNC_FLAG_SET(done); + } +} + +void *common_hal_async_spi_spi_write_start(async_spi_spi_obj_t *self, const uint8_t *data, + size_t len, circuitpy_async_flag_t *done) { + _async_start(self, data, len, &self->one_byte, 1, done); + return NULL; +} + +void *common_hal_async_spi_spi_readinto_start(async_spi_spi_obj_t *self, uint8_t *data, + size_t len, uint8_t write_value, circuitpy_async_flag_t *done) { + self->one_byte = write_value; + _async_start(self, &self->one_byte, 1, data, len, done); + return NULL; +} + +void *common_hal_async_spi_spi_write_readinto_start(async_spi_spi_obj_t *self, + const uint8_t *data_out, uint8_t *data_in, size_t len, circuitpy_async_flag_t *done) { + _async_start(self, data_out, len, data_in, len, done); + return NULL; +} + +// Stop the running DMA transfer without setting its done flag. +static void _abort(async_spi_spi_obj_t *self) { + // A completion interrupt may still come (RP2040-E13); the handler skips a NULL flag. + async_flags[self->dma_rx] = NULL; + #if PICO_RP2350 + // RP2350-E5: an enabled channel can retrigger after the abort. + hw_clear_bits(&dma_hw->ch[self->dma_tx].al1_ctrl, DMA_CH0_CTRL_TRIG_EN_BITS); + hw_clear_bits(&dma_hw->ch[self->dma_rx].al1_ctrl, DMA_CH0_CTRL_TRIG_EN_BITS); + #endif + // Both channels at once; as dma_channel_abort(), the busy bits clear once in-flight + // transfers have retired. + dma_hw->abort = (1u << self->dma_tx) | (1u << self->dma_rx); + while ((dma_hw->ch[self->dma_tx].ctrl_trig | dma_hw->ch[self->dma_rx].ctrl_trig) & DMA_CH0_CTRL_TRIG_BUSY_BITS) { + } + self->async_active = false; + while (spi_is_busy(self->peripheral)) { + } + while (spi_is_readable(self->peripheral)) { + (void)spi_get_hw(self->peripheral)->dr; + } + spi_get_hw(self->peripheral)->icr = SPI_SSPICR_RORIC_BITS; +} + +// Stops the transfer started with done, or finishes it if done is set. Does nothing for an +// earlier transfer, and does not allocate. +static void _stop(async_spi_spi_obj_t *self, circuitpy_async_flag_t *done) { + if (!self->async_active || self->async_done != done) { + return; + } + if (CIRCUITPY_ASYNC_FLAG_IS_SET(done)) { + _end(self); + return; + } + _abort(self); +} + +bool common_hal_async_spi_spi_transfer_finish(async_spi_spi_obj_t *self, void *context, + circuitpy_async_flag_t *done) { + _stop(self, done); + return true; +} + +mp_obj_t common_hal_async_spi_spi_transfer_end(async_spi_spi_obj_t *self, void *context, + circuitpy_async_flag_t *done) { + _stop(self, done); + return mp_const_none; +} + +void common_hal_async_spi_spi_transfer_cancel(async_spi_spi_obj_t *self, void *context, + circuitpy_async_flag_t *done) { + _stop(self, done); +} diff --git a/ports/raspberrypi/common-hal/async_spi/SPI.h b/ports/raspberrypi/common-hal/async_spi/SPI.h new file mode 100644 index 00000000000..82abbc8ce6e --- /dev/null +++ b/ports/raspberrypi/common-hal/async_spi/SPI.h @@ -0,0 +1,34 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" +#include "common-hal/microcontroller/Pin.h" +#include "supervisor/shared/async_flag.h" +#include "supervisor/shared/awaitable.h" + +#include "hardware/spi.h" + +typedef struct { + mp_obj_base_t base; + circuitpy_async_lock_obj_t lock; + spi_inst_t *peripheral; + const mcu_pin_obj_t *clock; // NULL once deinited + const mcu_pin_obj_t *mosi; + const mcu_pin_obj_t *miso; + uint32_t target_frequency; + int32_t real_frequency; + uint8_t polarity; + uint8_t phase; + uint8_t bits; + bool async_active; // an async DMA transfer may still be running + bool dma_kept; // dma_tx and dma_rx are ours until deinit + uint8_t dma_tx; + uint8_t dma_rx; + uint8_t one_byte; // the one-byte side of an async write (RX) or read (TX) + circuitpy_async_flag_t *async_done; +} async_spi_spi_obj_t; diff --git a/ports/raspberrypi/common-hal/async_spi/__init__.c b/ports/raspberrypi/common-hal/async_spi/__init__.c new file mode 100644 index 00000000000..59a4cec7fe9 --- /dev/null +++ b/ports/raspberrypi/common-hal/async_spi/__init__.c @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +// No async_spi module functions. diff --git a/ports/raspberrypi/common-hal/audiobusio/I2SOut.c b/ports/raspberrypi/common-hal/audiobusio/I2SOut.c index 591d71632c9..ecd6107415d 100644 --- a/ports/raspberrypi/common-hal/audiobusio/I2SOut.c +++ b/ports/raspberrypi/common-hal/audiobusio/I2SOut.c @@ -19,139 +19,252 @@ #include "bindings/rp2pio/StateMachine.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 + +/* From i2s.pio: + +.program i2s +.side_set 2 + +; Load the next set of samples + ; /--- LRCLK + ; |/-- BCLK + ; || + pull noblock side 0b11 ; Loads OSR with the next FIFO value or X + mov x osr side 0b11 ; Save the new value in case we need it again + set y 14 side 0b11 +bitloop1: + out pins 1 side 0b10 [2] ; Right channel first + jmp y-- bitloop1 side 0b11 [2] + out pins 1 side 0b00 [2] + set y 14 side 0b01 [2] +bitloop0: + out pins 1 side 0b00 [2] ; Then left channel + jmp y-- bitloop0 side 0b01 [2] + out pins 1 side 0b10 [2] +*/ + // Above assembled with pioasm. + 0x9880, // 0: pull noblock side 3 + 0xb827, // 1: mov x, osr side 3 + 0xf84e, // 2: set y, 14 side 3 + 0x7201, // 3: out pins, 1 side 2 [2] + 0x1a83, // 4: jmp y--, 3 side 3 [2] + 0x6201, // 5: out pins, 1 side 0 [2] + 0xea4e, // 6: set y, 14 side 1 [2] + 0x6201, // 7: out pins, 1 side 0 [2] + 0x0a87, // 8: jmp y--, 7 side 1 [2] + 0x7201, // 9: out pins, 1 side 2 [2] }; + 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 0b00 [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 +/* From i2s_left.pio: + +.program i2s +.side_set 2 + +; Load the next set of samples + ; /--- LRCLK + ; |/-- BCLK + ; || + pull noblock side 0b01 ; Loads OSR with the next FIFO value or X + mov x osr side 0b01 ; Save the new value in case we need it again + set y 14 side 0b01 +bitloop1: + out pins 1 side 0b10 [2] ; Right channel first + jmp y-- bitloop1 side 0b11 [2] + out pins 1 side 0b10 [2] + set y 14 side 0b11 [2] +bitloop0: + out pins 1 side 0b00 [2] ; Then left channel + jmp y-- bitloop0 side 0b01 [2] + out pins 1 side 0b00 [2] +*/ + // Above assembled with pioasm. + 0x8880, // 0: pull noblock side 1 + 0xa827, // 1: mov x, osr side 1 + 0xe84e, // 2: set y, 14 side 1 + 0x7201, // 3: out pins, 1 side 2 [2] + 0x1a83, // 4: jmp y--, 3 side 3 [2] + 0x7201, // 5: out pins, 1 side 2 [2] + 0xfa4e, // 6: set y, 14 side 3 [2] + 0x6201, // 7: out pins, 1 side 0 [2] + 0x0a87, // 8: jmp y--, 7 side 1 [2] + 0x6201, // 9: out pins, 1 side 0 [2] }; // Another version of i2s_program with the LRCLC and BCLK pin swapped const uint16_t i2s_program_swap[] = { -// ; Load the next set of samples -// ; /--- BCLK -// ; |/-- LRCLK -// ; || -// 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 0b01 [2] - 0x6a01, -// jmp y-- bitloop1 side 0b11 [2] - 0x1a83, -// out pins 1 side 0b00 [2] - 0x6201, -// set y 14 side 0b10 [2] - 0xf24e, -// bitloop0: -// out pins 1 side 0b00 [2] - 0x6201, -// jmp y-- bitloop0 side 0b10 [2] - 0x1287, -// out pins 1 side 0b01 [2] - 0x6a01 +/* From i2s_swap.pio: + +.program i2s +.side_set 2 + +; Load the next set of samples + ; /--- BCLK + ; |/-- LRCLK + ; || + pull noblock side 0b11 ; Loads OSR with the next FIFO value or X + mov x osr side 0b11 ; Save the new value in case we need it again + set y 14 side 0b11 +bitloop1: + out pins 1 side 0b01 [2] ; Right channel first + jmp y-- bitloop1 side 0b11 [2] + out pins 1 side 0b00 [2] + set y 14 side 0b10 [2] +bitloop0: + out pins 1 side 0b00 [2] ; Then left channel + jmp y-- bitloop0 side 0b10 [2] + out pins 1 side 0b01 [2] +*/ + // Above assembled with pioasm. + 0x9880, // 0: pull noblock side 3 + 0xb827, // 1: mov x, osr side 3 + 0xf84e, // 2: set y, 14 side 3 + 0x6a01, // 3: out pins, 1 side 1 [2] + 0x1a83, // 4: jmp y--, 3 side 3 [2] + 0x6201, // 5: out pins, 1 side 0 [2] + 0xf24e, // 6: set y, 14 side 2 [2] + 0x6201, // 7: out pins, 1 side 0 [2] + 0x1287, // 8: jmp y--, 7 side 2 [2] + 0x6a01, // 9: out pins, 1 side 1 [2] }; // Another version of i2s_program_left_justified with the LRCLC and BCLK pin // swapped. const uint16_t i2s_program_left_justified_swap[] = { -// ; Load the next set of samples -// ; /--- BCLK -// ; |/-- LRCLK -// ; || -// 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 0b10 [2] - 0x1283, -// out pins 1 side 0b00 [2] - 0x6201, -// set y 14 side 0b10 [2] - 0xf24e, -// bitloop0: -// out pins 1 side 0b01 [2] - 0x6a01, -// jmp y-- bitloop0 side 0b11 [2] - 0x1a87, -// out pins 1 side 0b01 [2] - 0x6a01 +/* From i2s_swap_left.pio: + +.program i2s +.side_set 2 + +; Load the next set of samples + ; /--- BCLK + ; |/-- LRCLK + ; || + pull noblock side 0b10 ; Loads OSR with the next FIFO value or X + mov x osr side 0b10 ; Save the new value in case we need it again + set y 14 side 0b10 +bitloop1: + out pins 1 side 0b01 [2] ; Right channel first + jmp y-- bitloop1 side 0b11 [2] + out pins 1 side 0b01 [2] + set y 14 side 0b11 [2] +bitloop0: + out pins 1 side 0b00 [2] ; Then left channel + jmp y-- bitloop0 side 0b10 [2] + out pins 1 side 0b00 [2] +*/ + // Above assembled with pioasm. + 0x9080, // 0: pull noblock side 2 + 0xb027, // 1: mov x, osr side 2 + 0xf04e, // 2: set y, 14 side 2 + 0x6a01, // 3: out pins, 1 side 1 [2] + 0x1a83, // 4: jmp y--, 3 side 3 [2] + 0x6a01, // 5: out pins, 1 side 1 [2] + 0xfa4e, // 6: set y, 14 side 3 [2] + 0x6201, // 7: out pins, 1 side 0 [2] + 0x1287, // 8: jmp y--, 7 side 2 [2] + 0x6201, // 9: out pins, 1 side 0 [2] }; +// External-clock TX. BCLK and WS are inputs driven by something +// else, so the state machine side-sets nothing and waits on the two clocks +// instead. `wait gpio` encodes an absolute pin index, so unlike the internal-clock +// programs above this one cannot be a static table: it is assembled at +// construct time with the pin numbers patched in. +// +// 0: wait 0 gpio W +// 1: wait 1 gpio W ; right channel starts (WS changes on a BCLK fall) +// .wrap_target +// 2: pull noblock ; refills OSR from X on underflow, as the internal-clock program does +// 3: mov x, osr +// 4: set y, 31 +// 5: wait 1 gpio B +// 6: wait 0 gpio B ; drive on the falling edge; receiver latches on rising +// 7: out pins, 1 +// 8: jmp y--, 5 +// .wrap +// +// Left-justified moves the `out` ahead of the two waits, which drives the MSB +// on the same falling edge WS changed on. The first loop iteration's `wait 1` +// otherwise lands on the Philips delay bit, so no pre-roll is needed. +// +// One 32-bit FIFO word covers a whole 16-bit stereo frame; at 24/32 bits the +// frame is two words (right then left). Same layout the internal-clock programs use. +#define I2S_EXT_CLOCK_PROGRAM_LEN (9) +#define I2S_EXT_CLOCK_WRAP_TARGET (2) +#define I2S_EXT_CLOCK_WRAP (8) + +static void build_i2sout_ext_clock_program(uint16_t *prog, uint8_t bclk, uint8_t ws, bool left_justified) { + const uint16_t wait_0_bclk = 0x2000 | bclk; + const uint16_t wait_1_bclk = 0x2080 | bclk; + prog[0] = 0x2000 | ws; // wait 0 gpio W + prog[1] = 0x2080 | ws; // wait 1 gpio W + prog[2] = 0x8080; // pull noblock + prog[3] = 0xa027; // mov x, osr + prog[4] = 0xe05f; // set y, 31 + if (left_justified) { + prog[5] = 0x6001; // out pins, 1 + prog[6] = wait_1_bclk; + prog[7] = wait_0_bclk; + } else { + prog[5] = wait_1_bclk; + prog[6] = wait_0_bclk; + prog[7] = 0x6001; // out pins, 1 + } + prog[8] = 0x0080 | 5; // jmp y--, 5 +} + +// `wait gpio` indices are relative to the PIO's GPIO base, which +// rp2pio_statemachine_construct picks the same way. +static uint8_t i2s_wait_gpio_index(const mcu_pin_obj_t *pin, uint8_t gpio_offset) { + if (pin->number < gpio_offset) { + mp_raise_ValueError(MP_ERROR_TEXT("Cannot use GPIO0..15 together with GPIO32..47")); + } + return pin->number - gpio_offset; +} + 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, const mcu_pin_obj_t *main_clock, bool left_justified) { + const mcu_pin_obj_t *data, const mcu_pin_obj_t *main_clock, bool left_justified, + bool external_clock) { + // Ensure the object starts in its deinit state, so its finaliser does + // nothing if this raises before the state machine is constructed. + common_hal_rp2pio_statemachine_mark_deinit(&self->state_machine); + if (main_clock != NULL) { mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_main_clock); } const mcu_pin_obj_t *sideset_pin = NULL; const uint16_t *program = NULL; size_t program_len = 0; - - if (bit_clock->number == word_select->number - 1) { + uint16_t ext_clock_program[I2S_EXT_CLOCK_PROGRAM_LEN]; + pio_pinmask_t wait_gpio_mask = PIO_PINMASK_NONE; + + self->external_clock = external_clock; + + if (external_clock) { + // In external clock mode the clocks are `wait gpio` targets, so they + // need not be sequential GPIOs. + uint8_t gpio_offset = 0; + #if NUM_BANK0_GPIOS > 32 + if (bit_clock->number >= 32 || word_select->number >= 32 || data->number >= 32) { + gpio_offset = 16; + } + #endif + build_i2sout_ext_clock_program(ext_clock_program, + i2s_wait_gpio_index(bit_clock, gpio_offset), + i2s_wait_gpio_index(word_select, gpio_offset), + left_justified); + program = ext_clock_program; + program_len = I2S_EXT_CLOCK_PROGRAM_LEN; + wait_gpio_mask = PIO_PINMASK_OR(PIO_PINMASK_FROM_PIN(bit_clock->number), + PIO_PINMASK_FROM_PIN(word_select->number)); + } else if (bit_clock->number == word_select->number - 1) { sideset_pin = bit_clock; if (left_justified) { @@ -181,23 +294,28 @@ void common_hal_audiobusio_i2sout_construct(audiobusio_i2sout_obj_t *self, common_hal_rp2pio_statemachine_construct( &self->state_machine, program, program_len, - 44100 * 32 * 6, // Clock at 44.1 khz to warm the DAC up. + // Clock at 44.1 khz to warm the DAC up. In external clock mode the SM + // is driven by the waits, not the clock divider, so run it at sysclk. + external_clock ? 0 : 44100 * 32 * 6, NULL, 0, // init NULL, 0, // may_exec data, 1, PIO_PINMASK32_NONE, PIO_PINMASK32_ALL, // out pin NULL, 0, // in pins PIO_PINMASK32_NONE, PIO_PINMASK32_NONE, // in pulls NULL, 0, PIO_PINMASK32_NONE, PIO_PINMASK32_FROM_VALUE(0x1f), // set pins - sideset_pin, 2, false, PIO_PINMASK32_NONE, PIO_PINMASK32_FROM_VALUE(0x1f), // sideset pins + sideset_pin, sideset_pin == NULL ? 0 : 2, false, PIO_PINMASK32_NONE, PIO_PINMASK32_FROM_VALUE(0x1f), // sideset pins false, // No sideset enable NULL, PULL_NONE, // jump pin - PIO_PINMASK_NONE, // wait gpio pins + wait_gpio_mask, // wait gpio pins + // The clocks are shared through wait_gpio_mask, which _check_gpio_mask_free + // already allows to be shared; the data pin stays exclusively ours. true, // exclusive pin use false, 32, false, // shift out left to start with MSB false, // Wait for txstall false, 32, false, // in settings false, // Not user-interruptible. - 0, -1, // wrap settings + external_clock ? I2S_EXT_CLOCK_WRAP_TARGET : 0, + external_clock ? I2S_EXT_CLOCK_WRAP : -1, // wrap settings PIO_ANY_OFFSET, PIO_FIFO_TYPE_DEFAULT, PIO_MOV_STATUS_DEFAULT, @@ -232,6 +350,8 @@ void common_hal_audiobusio_i2sout_play(audiobusio_i2sout_obj_t *self, common_hal_audiobusio_i2sout_stop(self); } + audiosample_check(sample); + uint8_t bits_per_sample = audiosample_get_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 @@ -248,7 +368,13 @@ void common_hal_audiobusio_i2sout_play(audiobusio_i2sout_obj_t *self, mp_raise_ValueError(MP_ERROR_TEXT("Too many channels in sample.")); } - common_hal_rp2pio_statemachine_set_frequency(&self->state_machine, clocks_per_bit * frequency); + // An external clock can't be retimed: the sample rate has to match whatever + // the outside world is running WS at, or the pitch is wrong. The restart + // still matters -- it re-execs the program at its offset, so every play() + // re-syncs to WS. + if (!self->external_clock) { + common_hal_rp2pio_statemachine_set_frequency(&self->state_machine, clocks_per_bit * frequency); + } common_hal_rp2pio_statemachine_restart(&self->state_machine); // On the RP2040, output registers are always written with a 32-bit write. diff --git a/ports/raspberrypi/common-hal/audiobusio/I2SOut.h b/ports/raspberrypi/common-hal/audiobusio/I2SOut.h index 2996640dc2d..def66225bf3 100644 --- a/ports/raspberrypi/common-hal/audiobusio/I2SOut.h +++ b/ports/raspberrypi/common-hal/audiobusio/I2SOut.h @@ -18,6 +18,7 @@ typedef struct { rp2pio_statemachine_obj_t state_machine; audio_dma_t dma; bool left_justified; + bool external_clock; bool playing; } audiobusio_i2sout_obj_t; diff --git a/ports/raspberrypi/common-hal/audiobusio/PDMIn.c b/ports/raspberrypi/common-hal/audiobusio/PDMIn.c index 327bec8de72..ec8f363e6fe 100644 --- a/ports/raspberrypi/common-hal/audiobusio/PDMIn.c +++ b/ports/raspberrypi/common-hal/audiobusio/PDMIn.c @@ -36,6 +36,10 @@ void common_hal_audiobusio_pdmin_construct(audiobusio_pdmin_obj_t *self, uint8_t bit_depth, bool mono, uint8_t oversample) { + // Ensure the object starts in its deinit state, so its finaliser does + // nothing if this raises before the state machine is constructed. + common_hal_rp2pio_statemachine_mark_deinit(&self->state_machine); + if (!(bit_depth == 16 || bit_depth == 8) || !mono || oversample != OVERSAMPLING) { mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("Only 8 or 16 bit mono with %dx oversampling supported."), OVERSAMPLING); } @@ -43,7 +47,7 @@ void common_hal_audiobusio_pdmin_construct(audiobusio_pdmin_obj_t *self, // Use the state machine to manage pins. common_hal_rp2pio_statemachine_construct(&self->state_machine, pdmin, MP_ARRAY_SIZE(pdmin), - sample_rate * 32 * 2, // Frequency based on sample rate + sample_rate * OVERSAMPLING * 2, // Frequency based on sample rate NULL, 0, NULL, 0, // may_exec NULL, 1, PIO_PINMASK32_NONE, PIO_PINMASK32_ALL, // out pin @@ -64,7 +68,8 @@ void common_hal_audiobusio_pdmin_construct(audiobusio_pdmin_obj_t *self, PIO_FIFO_TYPE_DEFAULT, PIO_MOV_STATUS_DEFAULT, PIO_MOV_N_DEFAULT); uint32_t actual_frequency = common_hal_rp2pio_statemachine_get_frequency(&self->state_machine); - if (actual_frequency < MIN_MIC_CLOCK) { + if (actual_frequency < 2 * MIN_MIC_CLOCK) { // 2 PIO samples per audio clock + common_hal_audiobusio_pdmin_deinit(self); mp_raise_ValueError(MP_ERROR_TEXT("sampling rate out of range")); } diff --git a/ports/raspberrypi/common-hal/audiobusio/README.pio b/ports/raspberrypi/common-hal/audiobusio/README.pio new file mode 100644 index 00000000000..53c73fbc199 --- /dev/null +++ b/ports/raspberrypi/common-hal/audiobusio/README.pio @@ -0,0 +1,7 @@ +.pio files right now are compiled by hand with pico-sdk/tools/pioasm and inserted into I2SOut.c + +i2s.pio regular pin order, not left_justified +i2s_left.pio regular pin order, left_justified + +i2s_swap.pio swapped pin order, not left_justified +i2s_swap_left.pio swapped pin order, left_justified diff --git a/ports/raspberrypi/common-hal/audiobusio/i2s.pio b/ports/raspberrypi/common-hal/audiobusio/i2s.pio new file mode 100644 index 00000000000..b3557eeb918 --- /dev/null +++ b/ports/raspberrypi/common-hal/audiobusio/i2s.pio @@ -0,0 +1,25 @@ +; This file is part of the CircuitPython project: https://circuitpython.org +; +; SPDX-FileCopyrightText: Copyright (c) 2025 Dan Halbert for Adafruit Industries +; +; SPDX-License-Identifier: MIT + +.program i2s +.side_set 2 + +; Load the next set of samples + ; /--- LRCLK + ; |/-- BCLK + ; || + pull noblock side 0b11 ; Loads OSR with the next FIFO value or X + mov x osr side 0b11 ; Save the new value in case we need it again + set y 14 side 0b11 +bitloop1: + out pins 1 side 0b10 [2] ; Right channel first + jmp y-- bitloop1 side 0b11 [2] + out pins 1 side 0b00 [2] + set y 14 side 0b01 [2] +bitloop0: + out pins 1 side 0b00 [2] ; Then left channel + jmp y-- bitloop0 side 0b01 [2] + out pins 1 side 0b10 [2] diff --git a/ports/raspberrypi/common-hal/audiobusio/i2s_left.pio b/ports/raspberrypi/common-hal/audiobusio/i2s_left.pio new file mode 100644 index 00000000000..4830ec42078 --- /dev/null +++ b/ports/raspberrypi/common-hal/audiobusio/i2s_left.pio @@ -0,0 +1,25 @@ +; This file is part of the CircuitPython project: https://circuitpython.org +; +; SPDX-FileCopyrightText: Copyright (c) 2025 Dan Halbert for Adafruit Industries +; +; SPDX-License-Identifier: MIT + +.program i2s +.side_set 2 + +; Load the next set of samples + ; /--- LRCLK + ; |/-- BCLK + ; || + pull noblock side 0b01 ; Loads OSR with the next FIFO value or X + mov x osr side 0b01 ; Save the new value in case we need it again + set y 14 side 0b01 +bitloop1: + out pins 1 side 0b10 [2] ; Right channel first + jmp y-- bitloop1 side 0b11 [2] + out pins 1 side 0b10 [2] + set y 14 side 0b11 [2] +bitloop0: + out pins 1 side 0b00 [2] ; Then left channel + jmp y-- bitloop0 side 0b01 [2] + out pins 1 side 0b00 [2] diff --git a/ports/raspberrypi/common-hal/audiobusio/i2s_swap.pio b/ports/raspberrypi/common-hal/audiobusio/i2s_swap.pio new file mode 100644 index 00000000000..a7ecf94c764 --- /dev/null +++ b/ports/raspberrypi/common-hal/audiobusio/i2s_swap.pio @@ -0,0 +1,25 @@ +; This file is part of the CircuitPython project: https://circuitpython.org +; +; SPDX-FileCopyrightText: Copyright (c) 2025 Dan Halbert for Adafruit Industries +; +; SPDX-License-Identifier: MIT + +.program i2s +.side_set 2 + +; Load the next set of samples + ; /--- BCLK + ; |/-- LRCLK + ; || + pull noblock side 0b11 ; Loads OSR with the next FIFO value or X + mov x osr side 0b11 ; Save the new value in case we need it again + set y 14 side 0b11 +bitloop1: + out pins 1 side 0b01 [2] ; Right channel first + jmp y-- bitloop1 side 0b11 [2] + out pins 1 side 0b00 [2] + set y 14 side 0b10 [2] +bitloop0: + out pins 1 side 0b00 [2] ; Then left channel + jmp y-- bitloop0 side 0b10 [2] + out pins 1 side 0b01 [2] diff --git a/ports/raspberrypi/common-hal/audiobusio/i2s_swap_left.pio b/ports/raspberrypi/common-hal/audiobusio/i2s_swap_left.pio new file mode 100644 index 00000000000..4e6373dd65a --- /dev/null +++ b/ports/raspberrypi/common-hal/audiobusio/i2s_swap_left.pio @@ -0,0 +1,25 @@ +; This file is part of the CircuitPython project: https://circuitpython.org +; +; SPDX-FileCopyrightText: Copyright (c) 2025 Dan Halbert for Adafruit Industries +; +; SPDX-License-Identifier: MIT + +.program i2s +.side_set 2 + +; Load the next set of samples + ; /--- BCLK + ; |/-- LRCLK + ; || + pull noblock side 0b10 ; Loads OSR with the next FIFO value or X + mov x osr side 0b10 ; Save the new value in case we need it again + set y 14 side 0b10 +bitloop1: + out pins 1 side 0b01 [2] ; Right channel first + jmp y-- bitloop1 side 0b11 [2] + out pins 1 side 0b01 [2] + set y 14 side 0b11 [2] +bitloop0: + out pins 1 side 0b00 [2] ; Then left channel + jmp y-- bitloop0 side 0b10 [2] + out pins 1 side 0b00 [2] diff --git a/ports/raspberrypi/common-hal/audioi2sin/I2SIn.c b/ports/raspberrypi/common-hal/audioi2sin/I2SIn.c new file mode 100644 index 00000000000..dd596af80c9 --- /dev/null +++ b/ports/raspberrypi/common-hal/audioi2sin/I2SIn.c @@ -0,0 +1,859 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include +#include + +#include "py/mperrno.h" +#include "py/mphal.h" +#include "py/runtime.h" +#include "shared/runtime/interrupt_char.h" +#include "common-hal/audioi2sin/I2SIn.h" +#include "shared-bindings/audioi2sin/I2SIn.h" +#include "shared-bindings/audiocore/__init__.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-module/audioi2sin/__init__.h" +#include "bindings/rp2pio/StateMachine.h" +#include "supervisor/port.h" + +#include "hardware/dma.h" + +#if CIRCUITPY_AUDIOI2SIN + +// 16-bit programs sample a stereo frame of 16+16 = 32 bits and rely on +// auto-push at 32 to deliver one packed (right<<16 | left) word per frame. +// 32-bit programs sample 32 bits per channel and produce two FIFO words per +// frame (right first, then left). Each bit takes 6 PIO clocks (a [2]-delay +// pair). 24-bit recordings reuse the 32-bit programs because most 24-bit +// MEMS mics (SPH0645LM4H, INMP441, ICS-43434) transmit their 24 valid bits +// left-justified inside a 32-bit slot. +// +// `in pins 1` runs on a cycle where side-set drives BCLK high. The attached +// device updates the data line on the BCLK falling edge, so by the rising edge it +// has settled and is safe to sample. Sampling at BCLK low (the previous, +// incorrect arrangement) catches the data mid-transition and the result is +// effectively noise. +#define PIO_CLOCKS_PER_BIT (6) + +// Internal-clock RX, regular pin order (BCLK = WS - 1), Philips alignment. +static const uint16_t i2sin_program[] = { + 0xb842, // 0: nop side 3 + // .wrap_target + 0xf94e, // 1: set y, 14 side 3 [1] + 0xb242, // 2: nop side 2 [2] + 0x5801, // 3: in pins, 1 side 3 + 0x1982, // 4: jmp y--, 2 side 3 [1] + 0xa242, // 5: nop side 0 [2] + 0x4801, // 6: in pins, 1 side 1 + 0xe94e, // 7: set y, 14 side 1 [1] + 0xa242, // 8: nop side 0 [2] + 0x4801, // 9: in pins, 1 side 1 + 0x0988, // 10: jmp y--, 8 side 1 [1] + 0xb242, // 11: nop side 2 [2] + 0x5801, // 12: in pins, 1 side 3 + // .wrap +}; + +// Internal-clock RX, regular pin order, left-justified. +static const uint16_t i2sin_program_left_justified[] = { + 0xa842, // 0: nop side 1 + // .wrap_target + 0xe94e, // 1: set y, 14 side 1 [1] + 0xb242, // 2: nop side 2 [2] + 0x5801, // 3: in pins, 1 side 3 + 0x1982, // 4: jmp y--, 2 side 3 [1] + 0xb242, // 5: nop side 2 [2] + 0x5801, // 6: in pins, 1 side 3 + 0xf94e, // 7: set y, 14 side 3 [1] + 0xa242, // 8: nop side 0 [2] + 0x4801, // 9: in pins, 1 side 1 + 0x0988, // 10: jmp y--, 8 side 1 [1] + 0xa242, // 11: nop side 0 [2] + 0x4801, // 12: in pins, 1 side 1 + // .wrap +}; + +// Internal-clock RX, swapped pin order (BCLK = WS + 1), Philips alignment. +static const uint16_t i2sin_program_swap[] = { + 0xb842, // 0: nop side 3 + // .wrap_target + 0xf94e, // 1: set y, 14 side 3 [1] + 0xaa42, // 2: nop side 1 [2] + 0x5801, // 3: in pins, 1 side 3 + 0x1982, // 4: jmp y--, 2 side 3 [1] + 0xa242, // 5: nop side 0 [2] + 0x5001, // 6: in pins, 1 side 2 + 0xf14e, // 7: set y, 14 side 2 [1] + 0xa242, // 8: nop side 0 [2] + 0x5001, // 9: in pins, 1 side 2 + 0x1188, // 10: jmp y--, 8 side 2 [1] + 0xaa42, // 11: nop side 1 [2] + 0x5801, // 12: in pins, 1 side 3 + // .wrap +}; + +// Internal-clock RX, swapped pin order, left-justified. +static const uint16_t i2sin_program_left_justified_swap[] = { + 0xb042, // 0: nop side 2 + // .wrap_target + 0xf14e, // 1: set y, 14 side 2 [1] + 0xaa42, // 2: nop side 1 [2] + 0x5801, // 3: in pins, 1 side 3 + 0x1982, // 4: jmp y--, 2 side 3 [1] + 0xaa42, // 5: nop side 1 [2] + 0x5801, // 6: in pins, 1 side 3 + 0xf94e, // 7: set y, 14 side 3 [1] + 0xa242, // 8: nop side 0 [2] + 0x5001, // 9: in pins, 1 side 2 + 0x1188, // 10: jmp y--, 8 side 2 [1] + 0xa242, // 11: nop side 0 [2] + 0x5001, // 12: in pins, 1 side 2 + // .wrap +}; + +// 32-bit-per-channel variants: identical to the 16-bit programs above except +// the loop counter is set to 30 (so each `bitloop` runs 31 in's, plus one +// outside the loop = 32 in's per channel). +static const uint16_t i2sin_program_32[] = { + 0xb842, // 0: nop side 3 + // .wrap_target + 0xf95e, // 1: set y, 30 side 3 [1] + 0xb242, // 2: nop side 2 [2] + 0x5801, // 3: in pins, 1 side 3 + 0x1982, // 4: jmp y--, 2 side 3 [1] + 0xa242, // 5: nop side 0 [2] + 0x4801, // 6: in pins, 1 side 1 + 0xe95e, // 7: set y, 30 side 1 [1] + 0xa242, // 8: nop side 0 [2] + 0x4801, // 9: in pins, 1 side 1 + 0x0988, // 10: jmp y--, 8 side 1 [1] + 0xb242, // 11: nop side 2 [2] + 0x5801, // 12: in pins, 1 side 3 + // .wrap +}; + +static const uint16_t i2sin_program_left_justified_32[] = { + 0xa842, // 0: nop side 1 + // .wrap_target + 0xe95e, // 1: set y, 30 side 1 [1] + 0xb242, // 2: nop side 2 [2] + 0x5801, // 3: in pins, 1 side 3 + 0x1982, // 4: jmp y--, 2 side 3 [1] + 0xb242, // 5: nop side 2 [2] + 0x5801, // 6: in pins, 1 side 3 + 0xf95e, // 7: set y, 30 side 3 [1] + 0xa242, // 8: nop side 0 [2] + 0x4801, // 9: in pins, 1 side 1 + 0x0988, // 10: jmp y--, 8 side 1 [1] + 0xa242, // 11: nop side 0 [2] + 0x4801, // 12: in pins, 1 side 1 + // .wrap +}; + +static const uint16_t i2sin_program_swap_32[] = { + 0xb842, // 0: nop side 3 + // .wrap_target + 0xf95e, // 1: set y, 30 side 3 [1] + 0xaa42, // 2: nop side 1 [2] + 0x5801, // 3: in pins, 1 side 3 + 0x1982, // 4: jmp y--, 2 side 3 [1] + 0xa242, // 5: nop side 0 [2] + 0x5001, // 6: in pins, 1 side 2 + 0xf15e, // 7: set y, 30 side 2 [1] + 0xa242, // 8: nop side 0 [2] + 0x5001, // 9: in pins, 1 side 2 + 0x1188, // 10: jmp y--, 8 side 2 [1] + 0xaa42, // 11: nop side 1 [2] + 0x5801, // 12: in pins, 1 side 3 + // .wrap +}; + +static const uint16_t i2sin_program_left_justified_swap_32[] = { + 0xb042, // 0: nop side 2 + // .wrap_target + 0xf15e, // 1: set y, 30 side 2 [1] + 0xaa42, // 2: nop side 1 [2] + 0x5801, // 3: in pins, 1 side 3 + 0x1982, // 4: jmp y--, 2 side 3 [1] + 0xaa42, // 5: nop side 1 [2] + 0x5801, // 6: in pins, 1 side 3 + 0xf95e, // 7: set y, 30 side 3 [1] + 0xa242, // 8: nop side 0 [2] + 0x5001, // 9: in pins, 1 side 2 + 0x1188, // 10: jmp y--, 8 side 2 [1] + 0xa242, // 11: nop side 0 [2] + 0x5001, // 12: in pins, 1 side 2 + // .wrap +}; + +// External-clock RX. BCLK and WS are inputs driven by something +// else -- another I2S object or the codec -- so the state machine side-sets +// nothing and waits on the two clocks instead. `wait gpio` encodes an absolute +// pin index, so unlike the internal-clock programs above this one is assembled at +// construct time with the pin numbers patched in. +// +// 0: wait 0 gpio W ; resync: find a WS rising edge, i.e. the start +// 1: wait 1 gpio W ; of the RIGHT channel (matches word order) +// .wrap_target +// 2: set y, 31 +// 3: wait 0 gpio B ; data changes here +// 4: wait 1 gpio B ; ...and is settled here +// 5: in pins, 1 +// 6: jmp y--, 3 +// .wrap +// +// `set y, 31` + `jmp y--` runs the loop exactly 32 times, so with auto-push at +// 32 and shift-left this pushes one 32-bit word per 32 BCLK, MSB first -- +// identical to what the internal-clock programs produce, so record_to_buffer and +// fill_buffer need no changes. One template covers every bit_depth: at 16 bits +// a 32-BCLK frame is one push (right<<16 | left), at 24/32 a 64-BCLK frame is +// two pushes (right then left). +// +// The WS resync lands on the first data bit, so the program above is +// the `left_justified` alignment: data starts on the WS edge and no instruction +// is spent on a delay bit. The default (Philips) alignment is that program plus +// one more BCLK of skew, the other of the two possible alignments. +// +// Free-running after the initial sync: the external frame must be exactly +// 2 x bits_per_channel BCLKs, the same assumption internal clock mode already bakes +// in. If sync is lost it stays lost. +#define I2SIN_EXT_CLOCK_MAX_PROGRAM_LEN (8) +// The bit loop is the last 5 instructions; everything before it is one-shot sync. +#define I2SIN_EXT_CLOCK_WRAP_TARGET(len) ((int)(len) - 5) + +static size_t build_i2sin_ext_clock_program(uint16_t *prog, uint8_t bclk, uint8_t ws, + bool left_justified) { + const uint16_t wait_0_bclk = 0x2000 | bclk; + const uint16_t wait_1_bclk = 0x2080 | bclk; + size_t len = 0; + prog[len++] = 0x2000 | ws; // wait 0 gpio W + prog[len++] = 0x2080 | ws; // wait 1 gpio W + if (!left_justified) { + prog[len++] = wait_1_bclk; // one more BCLK of skew + } + const size_t bitloop = len + 1; + prog[len++] = 0xe05f; // set y, 31 + prog[len++] = wait_0_bclk; + prog[len++] = wait_1_bclk; + prog[len++] = 0x4001; // in pins, 1 + prog[len++] = 0x0080 | bitloop; // jmp y--, bitloop + return len; +} + +// `wait gpio` indices are relative to the PIO's GPIO base, which +// rp2pio_statemachine_construct picks the same way. +static uint8_t i2s_wait_gpio_index(const mcu_pin_obj_t *pin, uint8_t gpio_offset) { + if (pin->number < gpio_offset) { + mp_raise_ValueError(MP_ERROR_TEXT("Cannot use GPIO0..15 together with GPIO32..47")); + } + return pin->number - gpio_offset; +} + +// Caller validates that pins are free. +void common_hal_audioi2sin_i2sin_construct(audioi2sin_i2sin_obj_t *self, + const mcu_pin_obj_t *bit_clock, const mcu_pin_obj_t *word_select, + const mcu_pin_obj_t *data, const mcu_pin_obj_t *main_clock, + uint32_t sample_rate, uint8_t bit_depth, uint8_t output_bit_depth, + bool mono, bool left_justified, bool samples_signed, + bool external_clock) { + // Ensure the object starts in its deinit state, so its finaliser does + // nothing if this raises before the state machine is constructed. + common_hal_rp2pio_statemachine_mark_deinit(&self->state_machine); + + if (main_clock != NULL) { + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_main_clock); + } + if (bit_depth != 16 && bit_depth != 24 && bit_depth != 32) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("%q must be 16, 24, or 32"), MP_QSTR_bit_depth); + } + + // 24- and 32-bit recordings both clock 32 bits per channel; 24-bit MEMS + // mics deliver their data left-justified inside that 32-bit slot. + bool wide = (bit_depth != 16); + uint32_t bits_per_channel = wide ? 32 : 16; + uint32_t pio_clocks_per_frame = bits_per_channel * 2 * PIO_CLOCKS_PER_BIT; + + const mcu_pin_obj_t *sideset_pin = NULL; + const uint16_t *program = NULL; + size_t program_len = 0; + uint16_t ext_clock_program[I2SIN_EXT_CLOCK_MAX_PROGRAM_LEN]; + pio_pinmask_t wait_gpio_mask = PIO_PINMASK_NONE; + + if (external_clock) { + // In external clock mode the clocks are `wait gpio` targets, so they + // need not be sequential GPIOs. + uint8_t gpio_offset = 0; + #if NUM_BANK0_GPIOS > 32 + if (bit_clock->number >= 32 || word_select->number >= 32 || data->number >= 32) { + gpio_offset = 16; + } + #endif + program_len = build_i2sin_ext_clock_program(ext_clock_program, + i2s_wait_gpio_index(bit_clock, gpio_offset), + i2s_wait_gpio_index(word_select, gpio_offset), + left_justified); + program = ext_clock_program; + wait_gpio_mask = PIO_PINMASK_OR(PIO_PINMASK_FROM_PIN(bit_clock->number), + PIO_PINMASK_FROM_PIN(word_select->number)); + } else if (bit_clock->number == word_select->number - 1) { + sideset_pin = bit_clock; + if (left_justified) { + program = wide ? i2sin_program_left_justified_32 : i2sin_program_left_justified; + program_len = wide ? MP_ARRAY_SIZE(i2sin_program_left_justified_32) + : MP_ARRAY_SIZE(i2sin_program_left_justified); + } else { + program = wide ? i2sin_program_32 : i2sin_program; + program_len = wide ? MP_ARRAY_SIZE(i2sin_program_32) + : MP_ARRAY_SIZE(i2sin_program); + } + } else if (bit_clock->number == word_select->number + 1) { + sideset_pin = word_select; + if (left_justified) { + program = wide ? i2sin_program_left_justified_swap_32 : i2sin_program_left_justified_swap; + program_len = wide ? MP_ARRAY_SIZE(i2sin_program_left_justified_swap_32) + : MP_ARRAY_SIZE(i2sin_program_left_justified_swap); + } else { + program = wide ? i2sin_program_swap_32 : i2sin_program_swap; + program_len = wide ? MP_ARRAY_SIZE(i2sin_program_swap_32) + : MP_ARRAY_SIZE(i2sin_program_swap); + } + } else { + mp_raise_ValueError(MP_ERROR_TEXT("Bit clock and word select must be sequential GPIO pins")); + } + + common_hal_rp2pio_statemachine_construct( + &self->state_machine, + program, program_len, + // In external clock mode the SM is driven by the waits, not the clock + // divider, so run it at sysclk. + external_clock ? 0 : sample_rate *pio_clocks_per_frame, + NULL, 0, // init + NULL, 0, // may_exec + NULL, 0, PIO_PINMASK32_NONE, PIO_PINMASK32_NONE, // out pin + data, 1, // in pins + PIO_PINMASK32_NONE, PIO_PINMASK32_NONE, // in pulls + NULL, 0, PIO_PINMASK32_NONE, PIO_PINMASK32_FROM_VALUE(0x1f), // set pins + sideset_pin, sideset_pin == NULL ? 0 : 2, false, PIO_PINMASK32_NONE, PIO_PINMASK32_FROM_VALUE(0x1f), // sideset pins + false, // No sideset enable + NULL, PULL_NONE, // jump pin + wait_gpio_mask, // wait gpio pins + // The clocks are shared through wait_gpio_mask, which _check_gpio_mask_free + // already allows to be shared; the data pin stays exclusively ours. + true, // exclusive pin use + false, 32, false, // out settings (unused) + false, // Wait for txstall + true, 32, false, // in settings: auto-push at 32 bits, shift left (MSB first) + false, // Not user-interruptible. + external_clock ? I2SIN_EXT_CLOCK_WRAP_TARGET(program_len) : 1, + external_clock ? (int)program_len - 1 : -1, // wrap settings + PIO_ANY_OFFSET, + PIO_FIFO_TYPE_DEFAULT, + PIO_MOV_STATUS_DEFAULT, + PIO_MOV_N_DEFAULT); + + // In external clock mode the SM runs at sysclk and the real rate is + // whatever the outside world drives WS at, so `sample_rate` is a + // declaration rather than a measurement. A mismatch shows up as the same + // slow drift the underrun-pad / overflow-drop paths in fill_buffer absorb. + self->sample_rate = external_clock + ? sample_rate + : common_hal_rp2pio_statemachine_get_frequency(&self->state_machine) / pio_clocks_per_frame; + self->bit_depth = bit_depth; + self->mono = mono; + self->samples_signed = samples_signed; + self->left_justified = left_justified; + self->external_clock = external_clock; + self->settled = false; + self->ring = NULL; + self->ring_size = 0; + self->half_size = 0; + self->read_pos = 0; + self->dma_channel = -1; + self->overflow = false; + + // Populate the audiosample base so I2SIn can feed the audio pipeline as a + // streaming source. The output depth must be 8 or 16 to actually stream; we + // still fill base here (so sample_rate/bits_per_sample/etc. read back) and + // raise from reset_buffer if a 24/32-bit instance is played. The owned + // conversion buffer is allocated lazily on first reset_buffer(). + uint8_t channel_count = mono ? 1 : 2; + // Report the *nominal* requested rate (not the PIO-derived self->sample_rate, + // which can be off by a fraction of a Hz). audiosample_must_match requires + // exact equality against the consumer, which is configured for the nominal + // rate; the tiny capture-clock difference shows up as the slow drift that the + // underrun silence-pad / overflow-drop paths in fill_buffer absorb. + self->base.sample_rate = sample_rate; + self->base.bits_per_sample = output_bit_depth; + self->base.channel_count = channel_count; + self->base.samples_signed = samples_signed; + self->base.single_buffer = false; + self->base.max_buffer_length = + 2 * AUDIOI2SIN_STREAM_FRAMES * (output_bit_depth / 8) * channel_count; + self->output_buffer = NULL; + self->output_half_bytes = self->base.max_buffer_length / 2; + self->output_index = 0; + + // Each PIO frame produces 4 bytes in the FIFO regardless of bit depth + // (16-bit auto-pushes one packed stereo word, 24/32-bit pushes two + // separate 32-bit words). One stereo frame is therefore either 4 or + // 8 bytes; size the half-buffer for ~40 ms of audio so a slow consumer + // (SD card flush etc.) can complete without overrunning. + size_t bytes_per_frame = (bit_depth == 16) ? 4 : 8; + size_t target = (size_t)self->sample_rate * bytes_per_frame * 40 / 1000; + size_t half_size = (target > 4096) ? target : 4096; + // Round up to a multiple of 8 so 24/32-bit pair reads never straddle + // the half boundary. + half_size = (half_size + 7u) & ~(size_t)7u; + + self->ring = (uint8_t *)port_malloc(2 * half_size, true); + if (self->ring == NULL) { + common_hal_rp2pio_statemachine_deinit(&self->state_machine); + m_malloc_fail(2 * half_size); + } + self->half_size = half_size; + self->ring_size = 2 * half_size; + + common_hal_rp2pio_statemachine_set_read_buffers_raw(&self->state_machine, + NULL, 0, + self->ring, half_size, + self->ring + half_size, half_size); + if (!common_hal_rp2pio_statemachine_background_read(&self->state_machine, 4, false)) { + port_free(self->ring); + self->ring = NULL; + common_hal_rp2pio_statemachine_deinit(&self->state_machine); + mp_raise_OSError(MP_EIO); + } + self->dma_channel = common_hal_rp2pio_statemachine_get_read_dma_channel(&self->state_machine); +} + +bool common_hal_audioi2sin_i2sin_deinited(audioi2sin_i2sin_obj_t *self) { + return common_hal_rp2pio_statemachine_deinited(&self->state_machine); +} + +void common_hal_audioi2sin_i2sin_deinit(audioi2sin_i2sin_obj_t *self) { + if (common_hal_audioi2sin_i2sin_deinited(self)) { + return; + } + common_hal_rp2pio_statemachine_stop_background_read(&self->state_machine); + common_hal_rp2pio_statemachine_deinit(&self->state_machine); + if (self->ring != NULL) { + port_free(self->ring); + self->ring = NULL; + } + if (self->output_buffer != NULL) { + port_free(self->output_buffer); + self->output_buffer = NULL; + } + self->ring_size = 0; + self->half_size = 0; + self->dma_channel = -1; + audiosample_mark_deinit(&self->base); +} + +uint8_t common_hal_audioi2sin_i2sin_get_bit_depth(audioi2sin_i2sin_obj_t *self) { + return self->bit_depth; +} + +uint32_t common_hal_audioi2sin_i2sin_get_sample_rate(audioi2sin_i2sin_obj_t *self) { + return self->sample_rate; +} + +bool common_hal_audioi2sin_i2sin_get_samples_signed(audioi2sin_i2sin_obj_t *self) { + return self->samples_signed; +} + +// The flag latches when record_to_buffer or fill_buffer finds the DMA more than +// a half-buffer ahead of the read cursor and has to skip forward. Reading clears +// it so a streaming consumer can attribute each report to a known interval. +bool common_hal_audioi2sin_i2sin_get_overflow(audioi2sin_i2sin_obj_t *self) { + bool overflow = self->overflow; + self->overflow = false; + return overflow; +} + +// In 16-bit mode, each PIO frame produces a single 32-bit FIFO word with bits +// 31..16 = right channel and bits 15..0 = left channel (both MSB-first signed +// 16-bit). In 24/32-bit mode each frame produces two FIFO words: right first, +// then left, each MSB-first in the full 32 bits. For mono we keep the left +// channel; for stereo we emit (left, right) pairs. +// +// `output_buffer_length` is the requested number of samples to write (sample +// width = 2 bytes for bit_depth=16, 4 bytes for bit_depth=24 or 32). Returns +// the number actually written. +// Compute the byte offset inside `ring` that the DMA is currently writing +// (one past the last word it finished). Always lies in [0, ring_size). +static size_t i2sin_write_pos(audioi2sin_i2sin_obj_t *self) { + uintptr_t addr = (uintptr_t)dma_channel_hw_addr(self->dma_channel)->write_addr; + uintptr_t base = (uintptr_t)self->ring; + if (addr < base || addr >= base + self->ring_size) { + // The ISR retargets write_addr to the start of the next half right + // after a transfer completes; it should always be in-range, but if + // we observe it mid-update just report "no new data". + return self->read_pos; + } + return (size_t)(addr - base); +} + +// 24-bit non-left-justified data arrives in the low 24 bits of the FIFO word +// with the sign bit at bit 23 and bits 31..24 zero. To make it decode +// correctly as int32 (array typecode "i"), lift the sign bit to bit 31. +static inline uint32_t movesign24(uint32_t val) { + return ((val & 0x800000u) << 8) | (val & 0x7fffffu); +} + +// Sign-extend a raw FIFO sample to a canonical int32 value. `raw` holds the +// sample as delivered by the PIO program for the given input bit depth and +// alignment. The returned int32 represents the same magnitude with the sign +// bit at bit 31. +static inline int32_t i2sin_normalize_signed(uint32_t raw, uint8_t in_depth, + bool left_justified) { + if (in_depth == 32) { + return (int32_t)raw; + } + if (in_depth == 24) { + if (left_justified) { + // value in bits 31..8, sign at 31; arithmetic shift right 8 + return (int32_t)raw >> 8; + } + // value in bits 23..0, sign at 23 + uint32_t sign_bit = 0x800000u; + return (int32_t)((raw ^ sign_bit) - sign_bit); + } + // 16-bit: low 16 bits, sign at 15 + return (int16_t)(raw & 0xffffu); +} + +// Normalize `raw` (input-depth bits, just-read FIFO sample) for this port's wire +// format, then hand off to the shared converter to rescale `in_depth` -> +// `out_depth` and write it to `buffer` at sample index `idx`. The depth +// conversion + unsigned-WAV flip + container store live in +// `shared_audioi2sin_write_converted` (shared with other ports); see that helper +// for the upscale/downscale semantics. +// +// For signed 24-bit output, the int32 slot holds the sign-extended value +// (range -2^23 .. 2^23-1) — unlike the default `output_bit_depth=bit_depth=24` +// path which uses `movesign24`, the converted path returns proper two's +// complement so the result decodes correctly as int32. +static inline void i2sin_write_converted(void *buffer, uint32_t idx, + uint32_t raw, uint8_t in_depth, uint8_t out_depth, + bool samples_signed, bool left_justified) { + int32_t s = i2sin_normalize_signed(raw, in_depth, left_justified); + shared_audioi2sin_write_converted(buffer, idx, s, in_depth, out_depth, samples_signed); +} + +uint32_t common_hal_audioi2sin_i2sin_record_to_buffer(audioi2sin_i2sin_obj_t *self, + void *buffer, uint32_t output_buffer_length) { + uint32_t output_count = 0; + const size_t ring_size = self->ring_size; + const size_t half_size = self->half_size; + + // I2S delivers signed PCM. When the caller asked for unsigned samples, + // flip the sign bit per sample (XOR with 0x8000 for 16-bit, 0x800000 for + // 24-bit data in a 32-bit slot, 0x80000000 for 32-bit), matching the WAV + // convention. The default (no-conversion) path applies the flip to the + // raw FIFO word before splitting into channels; the conversion path + // applies the flip per output sample at output bit width. + const bool convert = self->base.bits_per_sample != self->bit_depth; + const uint32_t flip16 = (!convert && !self->samples_signed) ? 0x80008000u : 0u; + const uint32_t flip32 = (!convert && !self->samples_signed) + ? (self->bit_depth == 24 ? 0x800000u : 0x80000000u) + : 0u; + const bool fix_sign24 = !convert + && self->bit_depth == 24 + && self->samples_signed + && !self->left_justified; + const uint8_t in_depth = self->bit_depth; + const uint8_t out_depth = self->base.bits_per_sample; + const bool left_justified = self->left_justified; + const bool samples_signed = self->samples_signed; + + if (self->bit_depth == 16) { + // 16-bit mode auto-pushes one stereo frame per FIFO word. The DMA has + // been streaming since construct time, so the ring already contains + // settled data; drop the first 4 bytes once to discard a single + // pre-record frame (matches the prior synchronous behaviour). + uint16_t *output = convert ? NULL : (uint16_t *)buffer; + while (output_count < output_buffer_length) { + size_t write_pos = i2sin_write_pos(self); + size_t avail = (write_pos + ring_size - self->read_pos) % ring_size; + if (avail > half_size) { + // DMA has filled more than one half ahead of us -- we lost + // data. Snap to just behind the DMA on a 4-byte boundary. + self->overflow = true; + self->read_pos = write_pos & ~(size_t)3u; + avail = 0; + } + if (!self->settled && avail >= 4) { + self->read_pos = (self->read_pos + 4) % ring_size; + avail -= 4; + self->settled = true; + } + if (avail < 4) { + RUN_BACKGROUND_TASKS; + if (mp_hal_is_interrupted()) { + return output_count; + } + continue; + } + while (avail >= 4 && output_count < output_buffer_length) { + uint32_t frame = *(volatile uint32_t *)(self->ring + self->read_pos) ^ flip16; + uint16_t left = (uint16_t)(frame & 0xffff); + uint16_t right = (uint16_t)(frame >> 16); + if (!convert) { + if (self->mono) { + output[output_count++] = left; + } else { + output[output_count++] = left; + if (output_count >= output_buffer_length) { + self->read_pos = (self->read_pos + 4) % ring_size; + avail -= 4; + break; + } + output[output_count++] = right; + } + } else { + i2sin_write_converted(buffer, output_count++, left, + in_depth, out_depth, samples_signed, left_justified); + if (!self->mono) { + if (output_count >= output_buffer_length) { + self->read_pos = (self->read_pos + 4) % ring_size; + avail -= 4; + break; + } + i2sin_write_converted(buffer, output_count++, right, + in_depth, out_depth, samples_signed, left_justified); + } + } + self->read_pos = (self->read_pos + 4) % ring_size; + avail -= 4; + } + } + } else { + // 24-/32-bit mode emits two FIFO pushes per stereo frame (right then + // left). The state machine was started at instruction 0 by the + // constructor, so the very first push is the right channel and + // alternation is preserved as long as we never touch the program + // counter and always read an even number of words. half_size is a + // multiple of 8, so reading 8-byte pairs stays aligned across the + // ring wrap. + uint32_t *output = convert ? NULL : (uint32_t *)buffer; + while (output_count < output_buffer_length) { + size_t write_pos = i2sin_write_pos(self); + size_t avail = (write_pos + ring_size - self->read_pos) % ring_size; + if (avail > half_size) { + // Overflow: snap to a frame-aligned position one half behind + // the DMA's current half so we resume on the right channel. + self->overflow = true; + size_t cur_half = (write_pos < half_size) ? 0 : half_size; + self->read_pos = (cur_half + half_size) % ring_size; + self->settled = false; + avail = (write_pos + ring_size - self->read_pos) % ring_size; + } + if (!self->settled && avail >= 8) { + self->read_pos = (self->read_pos + 8) % ring_size; + avail -= 8; + self->settled = true; + } + if (avail < 8) { + RUN_BACKGROUND_TASKS; + if (mp_hal_is_interrupted()) { + return output_count; + } + continue; + } + while (avail >= 8 && output_count < output_buffer_length) { + uint32_t right = *(volatile uint32_t *)(self->ring + self->read_pos) ^ flip32; + size_t next_pos = (self->read_pos + 4) % ring_size; + uint32_t left = *(volatile uint32_t *)(self->ring + next_pos) ^ flip32; + if (fix_sign24) { + right = movesign24(right); + left = movesign24(left); + } + if (!convert) { + if (self->mono) { + output[output_count++] = left; + } else { + output[output_count++] = left; + if (output_count >= output_buffer_length) { + self->read_pos = (self->read_pos + 8) % ring_size; + avail -= 8; + break; + } + output[output_count++] = right; + } + } else { + i2sin_write_converted(buffer, output_count++, left, + in_depth, out_depth, samples_signed, left_justified); + if (!self->mono) { + if (output_count >= output_buffer_length) { + self->read_pos = (self->read_pos + 8) % ring_size; + avail -= 8; + break; + } + i2sin_write_converted(buffer, output_count++, right, + in_depth, out_depth, samples_signed, left_justified); + } + } + self->read_pos = (self->read_pos + 8) % ring_size; + avail -= 8; + } + } + } + + return output_count; +} + +// Write `count` silence samples at output depth starting at sample index `idx`. +// For signed PCM silence is 0; for unsigned (WAV) it is mid-scale. +static void i2sin_fill_silence(void *buffer, uint32_t idx, uint32_t count, + uint8_t out_depth, bool samples_signed) { + if (out_depth == 8) { + uint8_t v = samples_signed ? 0 : 0x80u; + memset((uint8_t *)buffer + idx, v, count); + } else { // 16-bit (the only other streamable width) + uint16_t v = samples_signed ? 0 : 0x8000u; + uint16_t *p = (uint16_t *)buffer + idx; + for (uint32_t i = 0; i < count; i++) { + p[i] = v; + } + } +} + +// Non-blocking fill: convert up to `frames` frames currently available in the +// DMA ring into `buffer` (output depth, interleaved), padding the remainder with +// silence on underrun rather than spinning. Used by get_buffer() from the output +// backend's refill interrupt, so it must never block. `out_depth` is always 8 or +// 16 here (reset_buffer rejects 24/32). Reuses the same per-sample conversion as +// record_to_buffer via i2sin_write_converted. +void common_hal_audioi2sin_i2sin_fill_buffer(audioi2sin_i2sin_obj_t *self, + uint8_t *buffer, uint32_t frames) { + const size_t ring_size = self->ring_size; + const size_t half_size = self->half_size; + const uint8_t in_depth = self->bit_depth; + const uint8_t out_depth = self->base.bits_per_sample; + const bool samples_signed = self->samples_signed; + const bool left_justified = self->left_justified; + const bool stereo = !self->mono; + const uint8_t channel_count = stereo ? 2 : 1; + const size_t frame_bytes = (in_depth == 16) ? 4 : 8; + const uint32_t total_samples = frames * channel_count; + + uint32_t produced = 0; + while (produced < total_samples) { + size_t write_pos = i2sin_write_pos(self); + size_t avail = (write_pos + ring_size - self->read_pos) % ring_size; + if (avail > half_size) { + // The consumer is slower than the mic and the ring is filling up + // (the overflow case record_to_buffer also handles). Drop back to + // just behind the DMA so latency stays bounded; the discarded audio + // shows up as a brief discontinuity, not a hang. + self->overflow = true; + if (in_depth == 16) { + self->read_pos = write_pos & ~(size_t)3u; + } else { + size_t cur_half = (write_pos < half_size) ? 0 : half_size; + self->read_pos = (cur_half + half_size) % ring_size; + self->settled = false; + } + avail = (write_pos + ring_size - self->read_pos) % ring_size; + } + if (!self->settled && avail >= frame_bytes) { + // Drop one frame so playback starts on a settled sample and (for + // 24/32-bit) on the right-channel word the program emits first. + self->read_pos = (self->read_pos + frame_bytes) % ring_size; + avail -= frame_bytes; + self->settled = true; + } + if (avail < frame_bytes) { + break; // underrun: pad the rest with silence below + } + uint32_t left, right; + if (in_depth == 16) { + uint32_t fr = *(volatile uint32_t *)(self->ring + self->read_pos); + left = fr & 0xffffu; + right = fr >> 16; + } else { + right = *(volatile uint32_t *)(self->ring + self->read_pos); + size_t next_pos = (self->read_pos + 4) % ring_size; + left = *(volatile uint32_t *)(self->ring + next_pos); + } + i2sin_write_converted(buffer, produced++, left, + in_depth, out_depth, samples_signed, left_justified); + if (stereo && produced < total_samples) { + i2sin_write_converted(buffer, produced++, right, + in_depth, out_depth, samples_signed, left_justified); + } + self->read_pos = (self->read_pos + frame_bytes) % ring_size; + } + if (produced < total_samples) { + i2sin_fill_silence(buffer, produced, total_samples - produced, + out_depth, samples_signed); + } +} + +void common_hal_audioi2sin_i2sin_reset_buffer(audioi2sin_i2sin_obj_t *self, + bool single_channel_output, uint8_t channel) { + (void)single_channel_output; + (void)channel; + // The audio pipeline only carries 8- or 16-bit samples. 24/32-bit modes can + // still record() but cannot stream; fail clearly the first time playback is + // set up rather than emitting garbage. + if (self->base.bits_per_sample != 8 && self->base.bits_per_sample != 16) { + mp_raise_ValueError_varg( + MP_ERROR_TEXT("%q must be 8 or 16"), MP_QSTR_output_bit_depth); + } + if (self->output_buffer == NULL) { + // The output backend's DMA reads this buffer directly, so it must be + // DMA-capable like the input ring. + self->output_buffer = (uint8_t *)port_malloc(self->base.max_buffer_length, true); + if (self->output_buffer == NULL) { + m_malloc_fail(self->base.max_buffer_length); + } + } + self->output_index = 0; + // An external-clock SM free-runs a 32-BCLK counter from the WS edge it + // synced to at construct time, so anything that disturbs the frame leaves + // it locked to the wrong half-frame or the wrong bit for good. Re-exec the + // program here so playback always begins from a fresh WS sync. An + // internal-clock SM generates its own clocks and has nothing to sync to, + // so leave it alone. + if (self->external_clock) { + common_hal_rp2pio_statemachine_restart(&self->state_machine); + // restart() clears the shift counters but not the RX FIFO, and the + // words still sitting in it were captured with the old alignment. + pio_sm_clear_fifos(self->state_machine.pio, self->state_machine.state_machine); + } + // Resync to live audio: snap the read cursor just behind the DMA write head + // (frame-aligned) and re-settle so playback begins on fresh samples. + size_t write_pos = i2sin_write_pos(self); + self->read_pos = (self->bit_depth == 16) + ? (write_pos & ~(size_t)3u) + : (write_pos & ~(size_t)7u); + self->settled = false; + self->overflow = false; +} + +audioio_get_buffer_result_t common_hal_audioi2sin_i2sin_get_buffer( + audioi2sin_i2sin_obj_t *self, bool single_channel_output, uint8_t channel, + uint8_t **buffer, uint32_t *buffer_length) { + uint32_t half = self->output_half_bytes; + uint8_t *out = self->output_buffer + half * self->output_index; + self->output_index = 1 - self->output_index; + + uint32_t bytes_per_sample = self->base.bits_per_sample / 8; + uint32_t frames = half / (bytes_per_sample * self->base.channel_count); + common_hal_audioi2sin_i2sin_fill_buffer(self, out, frames); + + if (single_channel_output) { + out += (channel % self->base.channel_count) * bytes_per_sample; + } + *buffer = out; + *buffer_length = half; + // A live mic is an infinite stream; never report DONE or the backend stops. + return GET_BUFFER_MORE_DATA; +} + +#endif // CIRCUITPY_AUDIOI2SIN diff --git a/ports/raspberrypi/common-hal/audioi2sin/I2SIn.h b/ports/raspberrypi/common-hal/audioi2sin/I2SIn.h new file mode 100644 index 00000000000..594a9fccb02 --- /dev/null +++ b/ports/raspberrypi/common-hal/audioi2sin/I2SIn.h @@ -0,0 +1,48 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "common-hal/microcontroller/Pin.h" +#include "bindings/rp2pio/StateMachine.h" + +#include "py/obj.h" + +#include "shared-module/audiocore/__init__.h" + +// Number of audio frames a single get_buffer() call hands to the output backend +// (one frame = one mono sample, or an L+R pair in stereo). This sets the pull +// granularity and the silence-pad chunk on underrun. Kept independent of the DMA +// half-buffer so the two can be tuned separately. +#define AUDIOI2SIN_STREAM_FRAMES (256) + +typedef struct { + // so I2SIn can be used directly as an audiosample source. + audiosample_base_t base; + uint32_t sample_rate; + uint8_t bit_depth; + bool mono; + bool samples_signed; + bool left_justified; + bool external_clock; + bool settled; + rp2pio_statemachine_obj_t state_machine; + // Background DMA ring buffer. The state machine alternates DMA writes + // between the two halves so BCLK never stalls between record() calls. + uint8_t *ring; + size_t ring_size; + size_t half_size; + size_t read_pos; + int dma_channel; + bool overflow; + // Owned double-buffer returned to the output backend by get_buffer(), holding + // converted (output-depth, interleaved) samples. Allocated lazily on the first + // reset_buffer() so record()-only use pays no extra RAM. base.max_buffer_length + // is the whole buffer; get_buffer() returns output_half_bytes of it. + uint8_t *output_buffer; + size_t output_half_bytes; + uint8_t output_index; +} audioi2sin_i2sin_obj_t; diff --git a/ports/raspberrypi/common-hal/audioi2sin/README.pio b/ports/raspberrypi/common-hal/audioi2sin/README.pio new file mode 100644 index 00000000000..664c1301a72 --- /dev/null +++ b/ports/raspberrypi/common-hal/audioi2sin/README.pio @@ -0,0 +1,14 @@ +.pio files right now are compiled by hand with pico-sdk/tools/pioasm and inserted into I2SIn.c + +i2sin.pio I2S RX, 16 bits/channel, regular pin order, not left_justified +i2sin_left.pio I2S RX, 16 bits/channel, regular pin order, left_justified +i2sin_swap.pio I2S RX, 16 bits/channel, swapped pin order, not left_justified +i2sin_swap_left.pio I2S RX, 16 bits/channel, swapped pin order, left_justified +i2sin_32.pio I2S RX, 32 bits/channel, regular pin order, not left_justified +i2sin_left_32.pio I2S RX, 32 bits/channel, regular pin order, left_justified +i2sin_swap_32.pio I2S RX, 32 bits/channel, swapped pin order, not left_justified +i2sin_swap_left_32.pio I2S RX, 32 bits/channel, swapped pin order, left_justified + +The 32-bit programs are also used for bit_depth=24 because most 24-bit I2S +mics (SPH0645LM4H, INMP441, ICS-43434) place their 24 valid data bits +left-justified inside a 32-bit slot. diff --git a/ports/raspberrypi/common-hal/audioi2sin/__init__.c b/ports/raspberrypi/common-hal/audioi2sin/__init__.c new file mode 100644 index 00000000000..584c821b996 --- /dev/null +++ b/ports/raspberrypi/common-hal/audioi2sin/__init__.c @@ -0,0 +1,5 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT diff --git a/ports/raspberrypi/common-hal/audioi2sin/i2sin.pio b/ports/raspberrypi/common-hal/audioi2sin/i2sin.pio new file mode 100644 index 00000000000..b9d7c9ee28e --- /dev/null +++ b/ports/raspberrypi/common-hal/audioi2sin/i2sin.pio @@ -0,0 +1,34 @@ +; This file is part of the CircuitPython project: https://circuitpython.org +; +; SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +; +; SPDX-License-Identifier: MIT + +.program i2sin +.side_set 2 + +; Internal-clock I2S RX. Generates BCLK and LRCLK via side-set and samples the +; data pin. The attached device updates `data` on BCLK falling edge, so this +; program samples on the rising edge: every `in pins 1` runs on a side-set value +; with BCLK=1, and the loop/transition instructions hold BCLK=0 so the +; device has time to settle the next bit. + ; /--- LRCLK + ; |/-- BCLK + ; || + nop side 0b11 +.wrap_target + set y 14 side 0b11 [1] +bitloop1: + nop side 0b10 [2] ; Right channel first + in pins 1 side 0b11 + jmp y-- bitloop1 side 0b11 [1] + nop side 0b00 [2] + in pins 1 side 0b01 + set y 14 side 0b01 [1] +bitloop0: + nop side 0b00 [2] ; Then left channel + in pins 1 side 0b01 + jmp y-- bitloop0 side 0b01 [1] + nop side 0b10 [2] + in pins 1 side 0b11 +.wrap diff --git a/ports/raspberrypi/common-hal/audioi2sin/i2sin_32.pio b/ports/raspberrypi/common-hal/audioi2sin/i2sin_32.pio new file mode 100644 index 00000000000..4d79a179668 --- /dev/null +++ b/ports/raspberrypi/common-hal/audioi2sin/i2sin_32.pio @@ -0,0 +1,35 @@ +; This file is part of the CircuitPython project: https://circuitpython.org +; +; SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +; +; SPDX-License-Identifier: MIT + +.program i2sin_32 +.side_set 2 + +; Internal-clock I2S RX, 32 bits per channel (also used for 24-bit mics that +; transmit data left-justified in a 32-bit slot). Generates BCLK and LRCLK +; via side-set and samples the data pin. The attached device updates `data` on +; BCLK falling edge, so this program samples on the rising edge: every `in pins 1` +; runs on a side-set value with BCLK=1, and the preceding nop holds BCLK=0 +; so the device has time to settle the next bit. + ; /--- LRCLK + ; |/-- BCLK + ; || + nop side 0b11 +.wrap_target + set y 30 side 0b11 [1] +bitloop1: + nop side 0b10 [2] ; Right channel first + in pins 1 side 0b11 + jmp y-- bitloop1 side 0b11 [1] + nop side 0b00 [2] + in pins 1 side 0b01 + set y 30 side 0b01 [1] +bitloop0: + nop side 0b00 [2] ; Then left channel + in pins 1 side 0b01 + jmp y-- bitloop0 side 0b01 [1] + nop side 0b10 [2] + in pins 1 side 0b11 +.wrap diff --git a/ports/raspberrypi/common-hal/audioi2sin/i2sin_left.pio b/ports/raspberrypi/common-hal/audioi2sin/i2sin_left.pio new file mode 100644 index 00000000000..a5b8cf15970 --- /dev/null +++ b/ports/raspberrypi/common-hal/audioi2sin/i2sin_left.pio @@ -0,0 +1,30 @@ +; This file is part of the CircuitPython project: https://circuitpython.org +; +; SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +; +; SPDX-License-Identifier: MIT + +.program i2sin_left +.side_set 2 + +; Internal-clock I2S RX, left-justified. Mirrors the timing of i2s_left.pio. + ; /--- LRCLK + ; |/-- BCLK + ; || + nop side 0b01 +.wrap_target + set y 14 side 0b01 [1] +bitloop1: + nop side 0b10 [2] ; Right channel first + in pins 1 side 0b11 + jmp y-- bitloop1 side 0b11 [1] + nop side 0b10 [2] + in pins 1 side 0b11 + set y 14 side 0b11 [1] +bitloop0: + nop side 0b00 [2] ; Then left channel + in pins 1 side 0b01 + jmp y-- bitloop0 side 0b01 [1] + nop side 0b00 [2] + in pins 1 side 0b01 +.wrap diff --git a/ports/raspberrypi/common-hal/audioi2sin/i2sin_left_32.pio b/ports/raspberrypi/common-hal/audioi2sin/i2sin_left_32.pio new file mode 100644 index 00000000000..c7c18073c0d --- /dev/null +++ b/ports/raspberrypi/common-hal/audioi2sin/i2sin_left_32.pio @@ -0,0 +1,30 @@ +; This file is part of the CircuitPython project: https://circuitpython.org +; +; SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +; +; SPDX-License-Identifier: MIT + +.program i2sin_left_32 +.side_set 2 + +; Internal-clock I2S RX, 32 bits per channel, left-justified. + ; /--- LRCLK + ; |/-- BCLK + ; || + nop side 0b01 +.wrap_target + set y 30 side 0b01 [1] +bitloop1: + nop side 0b10 [2] ; Right channel first + in pins 1 side 0b11 + jmp y-- bitloop1 side 0b11 [1] + nop side 0b10 [2] + in pins 1 side 0b11 + set y 30 side 0b11 [1] +bitloop0: + nop side 0b00 [2] ; Then left channel + in pins 1 side 0b01 + jmp y-- bitloop0 side 0b01 [1] + nop side 0b00 [2] + in pins 1 side 0b01 +.wrap diff --git a/ports/raspberrypi/common-hal/audioi2sin/i2sin_swap.pio b/ports/raspberrypi/common-hal/audioi2sin/i2sin_swap.pio new file mode 100644 index 00000000000..8ff2e468c0c --- /dev/null +++ b/ports/raspberrypi/common-hal/audioi2sin/i2sin_swap.pio @@ -0,0 +1,31 @@ +; This file is part of the CircuitPython project: https://circuitpython.org +; +; SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +; +; SPDX-License-Identifier: MIT + +.program i2sin_swap +.side_set 2 + +; Internal-clock I2S RX with the LRCLK and BCLK pin order swapped (BCLK is the +; higher-numbered GPIO). + ; /--- BCLK + ; |/-- LRCLK + ; || + nop side 0b11 +.wrap_target + set y 14 side 0b11 [1] +bitloop1: + nop side 0b01 [2] ; Right channel first + in pins 1 side 0b11 + jmp y-- bitloop1 side 0b11 [1] + nop side 0b00 [2] + in pins 1 side 0b10 + set y 14 side 0b10 [1] +bitloop0: + nop side 0b00 [2] ; Then left channel + in pins 1 side 0b10 + jmp y-- bitloop0 side 0b10 [1] + nop side 0b01 [2] + in pins 1 side 0b11 +.wrap diff --git a/ports/raspberrypi/common-hal/audioi2sin/i2sin_swap_32.pio b/ports/raspberrypi/common-hal/audioi2sin/i2sin_swap_32.pio new file mode 100644 index 00000000000..05d92ab019f --- /dev/null +++ b/ports/raspberrypi/common-hal/audioi2sin/i2sin_swap_32.pio @@ -0,0 +1,31 @@ +; This file is part of the CircuitPython project: https://circuitpython.org +; +; SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +; +; SPDX-License-Identifier: MIT + +.program i2sin_swap_32 +.side_set 2 + +; Internal-clock I2S RX, 32 bits per channel, with the LRCLK and BCLK pin order +; swapped (BCLK is the higher-numbered GPIO). + ; /--- BCLK + ; |/-- LRCLK + ; || + nop side 0b11 +.wrap_target + set y 30 side 0b11 [1] +bitloop1: + nop side 0b01 [2] ; Right channel first + in pins 1 side 0b11 + jmp y-- bitloop1 side 0b11 [1] + nop side 0b00 [2] + in pins 1 side 0b10 + set y 30 side 0b10 [1] +bitloop0: + nop side 0b00 [2] ; Then left channel + in pins 1 side 0b10 + jmp y-- bitloop0 side 0b10 [1] + nop side 0b01 [2] + in pins 1 side 0b11 +.wrap diff --git a/ports/raspberrypi/common-hal/audioi2sin/i2sin_swap_left.pio b/ports/raspberrypi/common-hal/audioi2sin/i2sin_swap_left.pio new file mode 100644 index 00000000000..79fb1bd7a6a --- /dev/null +++ b/ports/raspberrypi/common-hal/audioi2sin/i2sin_swap_left.pio @@ -0,0 +1,31 @@ +; This file is part of the CircuitPython project: https://circuitpython.org +; +; SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +; +; SPDX-License-Identifier: MIT + +.program i2sin_swap_left +.side_set 2 + +; Internal-clock I2S RX, left-justified, with the LRCLK and BCLK pin order +; swapped (BCLK is the higher-numbered GPIO). + ; /--- BCLK + ; |/-- LRCLK + ; || + nop side 0b10 +.wrap_target + set y 14 side 0b10 [1] +bitloop1: + nop side 0b01 [2] ; Right channel first + in pins 1 side 0b11 + jmp y-- bitloop1 side 0b11 [1] + nop side 0b01 [2] + in pins 1 side 0b11 + set y 14 side 0b11 [1] +bitloop0: + nop side 0b00 [2] ; Then left channel + in pins 1 side 0b10 + jmp y-- bitloop0 side 0b10 [1] + nop side 0b00 [2] + in pins 1 side 0b10 +.wrap diff --git a/ports/raspberrypi/common-hal/audioi2sin/i2sin_swap_left_32.pio b/ports/raspberrypi/common-hal/audioi2sin/i2sin_swap_left_32.pio new file mode 100644 index 00000000000..0228fa729dd --- /dev/null +++ b/ports/raspberrypi/common-hal/audioi2sin/i2sin_swap_left_32.pio @@ -0,0 +1,31 @@ +; This file is part of the CircuitPython project: https://circuitpython.org +; +; SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +; +; SPDX-License-Identifier: MIT + +.program i2sin_swap_left_32 +.side_set 2 + +; Internal-clock I2S RX, 32 bits per channel, left-justified, with the LRCLK and +; BCLK pin order swapped (BCLK is the higher-numbered GPIO). + ; /--- BCLK + ; |/-- LRCLK + ; || + nop side 0b10 +.wrap_target + set y 30 side 0b10 [1] +bitloop1: + nop side 0b01 [2] ; Right channel first + in pins 1 side 0b11 + jmp y-- bitloop1 side 0b11 [1] + nop side 0b01 [2] + in pins 1 side 0b11 + set y 30 side 0b11 [1] +bitloop0: + nop side 0b00 [2] ; Then left channel + in pins 1 side 0b10 + jmp y-- bitloop0 side 0b10 [1] + nop side 0b00 [2] + in pins 1 side 0b10 +.wrap diff --git a/ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c b/ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c index 6fa5bf02c14..c86e8fe1ed4 100644 --- a/ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c +++ b/ports/raspberrypi/common-hal/audiopwmio/PWMAudioOut.c @@ -46,7 +46,7 @@ static uint32_t limit_denominator(uint32_t max_denominator, uint32_t num_in, uin uint32_t g = gcd(n, d); d /= g; n /= g; - if (d < max_denominator) { + if (d <= max_denominator) { *den_out = d; return n; } @@ -71,8 +71,11 @@ static uint32_t limit_denominator(uint32_t max_denominator, uint32_t num_in, uin uint32_t bound1_num = p0 + k * p1, bound1_den = q0 + k * q1; uint32_t bound2_num = p1, bound2_den = q1; - if (fabsf((float)bound1_num / bound1_den - (float)num_in / den_in) <= - fabsf((float)bound2_num / bound2_den - (float)num_in / den_in)) { + // Pick the closer bound like Python does, but never a zero numerator because the pacing + // timer would never fire. Rates below den_in / max_denominator get the slowest rate instead. + if (bound2_num != 0 && + fabsf((float)bound2_num / bound2_den - (float)num_in / den_in) <= + fabsf((float)bound1_num / bound1_den - (float)num_in / den_in)) { *den_out = bound2_den; return bound2_num; } @@ -160,6 +163,8 @@ void common_hal_audiopwmio_pwmaudioout_play(audiopwmio_pwmaudioout_obj_t *self, common_hal_audiopwmio_pwmaudioout_stop(self); } + audiosample_check(sample); + // TODO: Share pacing timers based on frequency. size_t pacing_timer = NUM_DMA_TIMERS; for (size_t i = 0; i < NUM_DMA_TIMERS; i++) { diff --git a/ports/raspberrypi/common-hal/bitmaptools/__init__.c b/ports/raspberrypi/common-hal/bitmaptools/__init__.c new file mode 100644 index 00000000000..9c016e369fc --- /dev/null +++ b/ports/raspberrypi/common-hal/bitmaptools/__init__.c @@ -0,0 +1,80 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mikey Sklar for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// The fixed-point rotozoom row (shared-module/bitmaptools) on the SIO interpolator. +// +// Lane0 holds u in 16.16 and adds du on every pop (ADD_RAW). Its shifted and masked +// result is the byte offset of the source pixel in the row, and BASE2 is the row address, +// so POP_FULL is the source pixel address. Lane1 stays zero. +// +// Each pixel's address is popped one pixel ahead of its load, so a load never waits on +// the pop just before it. interp0 is per core and is reconfigured on every call, as +// picogame does. + +#include "hardware/interp.h" +#include "shared-module/bitmaptools/__init__.h" + +#define ROTOZOOM_POP() (interp0->pop[2]) + +#define ROTOZOOM_COPY(index, pixel) \ + do { \ + if (skip_index_none || (pixel) != skip_index) { \ + dest[index] = (pixel); \ + } \ + } while (0) + +#define ROTOZOOM_ROW(type) \ + do { \ + type *dest = dest_pixels; \ + uint32_t address = ROTOZOOM_POP(); \ + int i = 0; \ + for (; i + 4 <= count; i += 4) { \ + uint32_t address1 = ROTOZOOM_POP(); \ + type pixel0 = *(const type *)address; \ + uint32_t address2 = ROTOZOOM_POP(); \ + type pixel1 = *(const type *)address1; \ + uint32_t address3 = ROTOZOOM_POP(); \ + type pixel2 = *(const type *)address2; \ + address = ROTOZOOM_POP(); \ + type pixel3 = *(const type *)address3; \ + ROTOZOOM_COPY(i, pixel0); \ + ROTOZOOM_COPY(i + 1, pixel1); \ + ROTOZOOM_COPY(i + 2, pixel2); \ + ROTOZOOM_COPY(i + 3, pixel3); \ + } \ + for (; i < count; i++) { \ + uint32_t next = ROTOZOOM_POP(); \ + ROTOZOOM_COPY(i, *(const type *)address); \ + address = next; \ + } \ + } while (0) + +void bitmaptools_rotozoom_row(void *dest_pixels, const void *source_row, + uint32_t u, uint32_t du, int count, uint8_t bits_per_value, + uint32_t skip_index, bool skip_index_none) { + unsigned log2_bytes = bits_per_value == 16 ? 1 : 0; + interp_config lane0_config = interp_default_config(); + // u >> 16, times bytes per pixel. + interp_config_set_shift(&lane0_config, 16 - log2_bytes); + // The mask stops at bit 15 + log2_bytes: u < 2^31, and on RP2350 SHIFT is a right + // rotate (RP2040: logical shift), so the fraction bits come back in at the top. + interp_config_set_mask(&lane0_config, log2_bytes, 15 + log2_bytes); + interp_config_set_add_raw(&lane0_config, true); + interp_set_config(interp0, 0, &lane0_config); + interp_config lane1_config = interp_default_config(); + interp_set_config(interp0, 1, &lane1_config); + interp0->base[0] = du; + interp0->base[1] = 0; + interp0->base[2] = (uintptr_t)source_row; + interp0->accum[0] = u; + interp0->accum[1] = 0; + + if (bits_per_value == 16) { + ROTOZOOM_ROW(uint16_t); + } else { + ROTOZOOM_ROW(uint8_t); + } +} diff --git a/ports/raspberrypi/common-hal/busio/I2C.c b/ports/raspberrypi/common-hal/busio/I2C.c index 0f7e023f0e9..cca14254129 100644 --- a/ports/raspberrypi/common-hal/busio/I2C.c +++ b/ports/raspberrypi/common-hal/busio/I2C.c @@ -48,7 +48,12 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, mp_arg_validate_int_max(frequency, 1000000, MP_QSTR_frequency); - #if CIRCUITPY_REQUIRE_I2C_PULLUPS + // Don't bother to check for pull-ups when the internal pull-ups are used. + #if CIRCUITPY_REQUIRE_I2C_PULLUPS && !CIRCUITPY_I2C_ALLOW_INTERNAL_PULL_UP + + // TODO: maybe check the pull-up efficacy with timing scaled by frequency + // as is done in espressif, instead of using a fixed 3us. + // 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); @@ -86,7 +91,7 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, // // Do not use the default supplied clock stretching timeout here. // It is too short for some devices. Use the busio timeout instead. - shared_module_bitbangio_i2c_construct(&self->bitbangio_i2c, scl, sda, + shared_module_bitbangio_i2c_construct(&self->bitbangio_i2c, MP_OBJ_FROM_PTR(scl), MP_OBJ_FROM_PTR(sda), frequency, BUS_TIMEOUT_US); self->baudrate = i2c_init(self->peripheral, frequency); @@ -98,6 +103,12 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, gpio_set_function(self->scl_pin, GPIO_FUNC_I2C); gpio_set_function(self->sda_pin, GPIO_FUNC_I2C); + + #if CIRCUITPY_I2C_ALLOW_INTERNAL_PULL_UP + // Enable the internal pull-ups only once the pins belong to the I2C peripheral. + gpio_pull_up(self->scl_pin); + gpio_pull_up(self->sda_pin); + #endif } bool common_hal_busio_i2c_deinited(busio_i2c_obj_t *self) { @@ -144,7 +155,7 @@ void common_hal_busio_i2c_unlock(busio_i2c_obj_t *self) { self->has_lock = false; } -static uint8_t _common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, +static mp_negative_errno_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) { if (len == 0) { // The RP2040 I2C peripheral will not perform 0 byte writes. @@ -174,20 +185,20 @@ static uint8_t _common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, } switch (result) { case PICO_ERROR_GENERIC: - return MP_ENODEV; + return -MP_ENODEV; case PICO_ERROR_TIMEOUT: - return MP_ETIMEDOUT; + return -MP_ETIMEDOUT; default: - return MP_EIO; + return -MP_EIO; } } -uint8_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, +mp_negative_errno_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, const uint8_t *data, size_t len) { return _common_hal_busio_i2c_write(self, addr, data, len, true); } -uint8_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t addr, +mp_negative_errno_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t addr, uint8_t *data, size_t len) { size_t result = i2c_read_timeout_us(self->peripheral, addr, data, len, false, BUS_TIMEOUT_US); if (result == len) { @@ -195,25 +206,20 @@ uint8_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t addr, } switch (result) { case PICO_ERROR_GENERIC: - return MP_ENODEV; + return -MP_ENODEV; case PICO_ERROR_TIMEOUT: - return MP_ETIMEDOUT; + return -MP_ETIMEDOUT; default: - return MP_EIO; + return -MP_EIO; } } -uint8_t common_hal_busio_i2c_write_read(busio_i2c_obj_t *self, uint16_t addr, +mp_negative_errno_t common_hal_busio_i2c_write_read(busio_i2c_obj_t *self, uint16_t addr, uint8_t *out_data, size_t out_len, uint8_t *in_data, size_t in_len) { - uint8_t result = _common_hal_busio_i2c_write(self, addr, out_data, out_len, false); + mp_negative_errno_t result = _common_hal_busio_i2c_write(self, addr, out_data, out_len, false); if (result != 0) { return result; } return common_hal_busio_i2c_read(self, addr, in_data, in_len); } - -void common_hal_busio_i2c_never_reset(busio_i2c_obj_t *self) { - never_reset_pin_number(self->scl_pin); - never_reset_pin_number(self->sda_pin); -} diff --git a/ports/raspberrypi/common-hal/busio/SPI.c b/ports/raspberrypi/common-hal/busio/SPI.c deleted file mode 100644 index d20bc4d7d10..00000000000 --- a/ports/raspberrypi/common-hal/busio/SPI.c +++ /dev/null @@ -1,282 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "shared-bindings/busio/SPI.h" - -#include "shared/runtime/interrupt_char.h" -#include "py/mperrno.h" -#include "py/runtime.h" - -#include "supervisor/board.h" -#include "common-hal/microcontroller/Pin.h" -#include "shared-bindings/microcontroller/Pin.h" - -#include "hardware/dma.h" -#include "hardware/gpio.h" - -#define NO_INSTANCE 0xff - -static bool never_reset_spi[2]; -static spi_inst_t *spi[2] = {spi0, spi1}; - -void reset_spi(void) { - for (size_t i = 0; i < 2; i++) { - if (never_reset_spi[i]) { - continue; - } - - spi_deinit(spi[i]); - } -} - -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, bool half_duplex) { - size_t instance_index = NO_INSTANCE; - - if (half_duplex) { - mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_half_duplex); - } - - if (clock->number % 4 == 2) { - instance_index = (clock->number / 8) % 2; - } - if (mosi != NULL) { - // Make sure the set MOSI matches the clock settings. - if (mosi->number % 4 != 3 || - (mosi->number / 8) % 2 != instance_index) { - instance_index = NO_INSTANCE; - } - } - if (miso != NULL) { - // Make sure the set MOSI matches the clock settings. - if (miso->number % 4 != 0 || - (miso->number / 8) % 2 != instance_index) { - instance_index = NO_INSTANCE; - } - } - - // TODO: Check to see if we're sharing the SPI with a native APA102. - - if (instance_index > 1) { - raise_ValueError_invalid_pins(); - } - - if (instance_index == 0) { - self->peripheral = spi0; - } else if (instance_index == 1) { - self->peripheral = spi1; - } - - if ((spi_get_hw(self->peripheral)->cr1 & SPI_SSPCR1_SSE_BITS) != 0) { - mp_raise_ValueError(MP_ERROR_TEXT("SPI peripheral in use")); - } - - self->target_frequency = 250000; - self->real_frequency = spi_init(self->peripheral, self->target_frequency); - - gpio_set_function(clock->number, GPIO_FUNC_SPI); - claim_pin(clock); - self->clock = clock; - - self->MOSI = mosi; - if (mosi != NULL) { - gpio_set_function(mosi->number, GPIO_FUNC_SPI); - claim_pin(mosi); - } - - self->MISO = miso; - if (miso != NULL) { - gpio_set_function(miso->number, GPIO_FUNC_SPI); - claim_pin(miso); - } -} - -void common_hal_busio_spi_never_reset(busio_spi_obj_t *self) { - never_reset_spi[spi_get_index(self->peripheral)] = true; - - common_hal_never_reset_pin(self->clock); - common_hal_never_reset_pin(self->MOSI); - common_hal_never_reset_pin(self->MISO); -} - -bool common_hal_busio_spi_deinited(busio_spi_obj_t *self) { - return self->clock == NULL; -} - -void common_hal_busio_spi_deinit(busio_spi_obj_t *self) { - if (common_hal_busio_spi_deinited(self)) { - return; - } - never_reset_spi[spi_get_index(self->peripheral)] = false; - spi_deinit(self->peripheral); - - common_hal_reset_pin(self->clock); - common_hal_reset_pin(self->MOSI); - common_hal_reset_pin(self->MISO); - self->clock = NULL; -} - -bool common_hal_busio_spi_configure(busio_spi_obj_t *self, - uint32_t baudrate, uint8_t polarity, uint8_t phase, uint8_t bits) { - if (baudrate == self->target_frequency && - polarity == self->polarity && - phase == self->phase && - bits == self->bits) { - return true; - } - - spi_set_format(self->peripheral, bits, polarity, phase, SPI_MSB_FIRST); - - // Workaround to start with clock line high if polarity=1. The hw SPI peripheral does not do this - // automatically. See https://github.com/raspberrypi/pico-sdk/issues/868 and - // https://forums.raspberrypi.com/viewtopic.php?t=336142 - // TODO: scheduled to be be fixed in pico-sdk 1.5.0. - if (polarity) { - hw_clear_bits(&spi_get_hw(self->peripheral)->cr1, SPI_SSPCR1_SSE_BITS); // disable the SPI - hw_set_bits(&spi_get_hw(self->peripheral)->cr1, SPI_SSPCR1_SSE_BITS); // re-enable the SPI - } - - self->polarity = polarity; - self->phase = phase; - self->bits = bits; - self->target_frequency = baudrate; - self->real_frequency = spi_set_baudrate(self->peripheral, baudrate); - - return true; -} - -bool common_hal_busio_spi_try_lock(busio_spi_obj_t *self) { - if (common_hal_busio_spi_deinited(self)) { - return false; - } - bool grabbed_lock = false; - if (!self->has_lock) { - grabbed_lock = true; - self->has_lock = true; - } - return grabbed_lock; -} - -bool common_hal_busio_spi_has_lock(busio_spi_obj_t *self) { - return self->has_lock; -} - -void common_hal_busio_spi_unlock(busio_spi_obj_t *self) { - self->has_lock = false; -} - -static bool _transfer(busio_spi_obj_t *self, - const uint8_t *data_out, size_t out_len, - uint8_t *data_in, size_t in_len) { - // Use DMA for large transfers if channels are available - const size_t dma_min_size_threshold = 32; - int chan_tx = -1; - int chan_rx = -1; - size_t len = MAX(out_len, in_len); - if (len >= dma_min_size_threshold) { - // Use two DMA channels to service the two FIFOs - chan_tx = dma_claim_unused_channel(false); - chan_rx = dma_claim_unused_channel(false); - } - bool use_dma = chan_rx >= 0 && chan_tx >= 0; - if (use_dma) { - dma_channel_config c = dma_channel_get_default_config(chan_tx); - channel_config_set_transfer_data_size(&c, DMA_SIZE_8); - channel_config_set_dreq(&c, spi_get_index(self->peripheral) ? DREQ_SPI1_TX : DREQ_SPI0_TX); - channel_config_set_read_increment(&c, out_len == len); - channel_config_set_write_increment(&c, false); - dma_channel_configure(chan_tx, &c, - &spi_get_hw(self->peripheral)->dr, - data_out, - len, - false); - - c = dma_channel_get_default_config(chan_rx); - channel_config_set_transfer_data_size(&c, DMA_SIZE_8); - channel_config_set_dreq(&c, spi_get_index(self->peripheral) ? DREQ_SPI1_RX : DREQ_SPI0_RX); - channel_config_set_read_increment(&c, false); - channel_config_set_write_increment(&c, in_len == len); - dma_channel_configure(chan_rx, &c, - data_in, - &spi_get_hw(self->peripheral)->dr, - len, - false); - - dma_start_channel_mask((1u << chan_rx) | (1u << chan_tx)); - while (dma_channel_is_busy(chan_rx) || dma_channel_is_busy(chan_tx)) { - // TODO: We should idle here until we get a DMA interrupt or something else. - RUN_BACKGROUND_TASKS; - } - } - - // If we have claimed only one channel successfully, we should release immediately. This also - // releases the DMA after use_dma has been done. - if (chan_rx >= 0) { - dma_channel_unclaim(chan_rx); - } - if (chan_tx >= 0) { - dma_channel_unclaim(chan_tx); - } - - if (!use_dma) { - // Use software for small transfers, or if couldn't claim two DMA channels - // Never have more transfers in flight than will fit into the RX FIFO, - // else FIFO will overflow if this code is heavily interrupted. - const size_t fifo_depth = 8; - size_t rx_remaining = len; - size_t tx_remaining = len; - - while (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; - // Increment only if the buffer is the transfer length. It's 1 otherwise. - if (out_len == len) { - data_out++; - } - --tx_remaining; - } - if (rx_remaining && spi_is_readable(self->peripheral)) { - *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++; - } - --rx_remaining; - } - RUN_BACKGROUND_TASKS; - } - } - return true; -} - -bool common_hal_busio_spi_write(busio_spi_obj_t *self, - const uint8_t *data, size_t len) { - uint32_t data_in; - 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) { - 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); -} - -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) { - return self->real_frequency; -} - -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) { - return self->polarity; -} diff --git a/ports/raspberrypi/common-hal/busio/SPI.h b/ports/raspberrypi/common-hal/busio/SPI.h index 8510eb7693a..8b5ec5c444c 100644 --- a/ports/raspberrypi/common-hal/busio/SPI.h +++ b/ports/raspberrypi/common-hal/busio/SPI.h @@ -1,29 +1,10 @@ // This file is part of the CircuitPython project: https://circuitpython.org // -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2016 Scott Shawcroft // // SPDX-License-Identifier: MIT #pragma once -#include "common-hal/microcontroller/Pin.h" - -#include "py/obj.h" - -#include "hardware/spi.h" - -typedef struct { - mp_obj_base_t base; - 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; - uint32_t target_frequency; - int32_t real_frequency; - uint8_t polarity; - uint8_t phase; - uint8_t bits; -} busio_spi_obj_t; - -void reset_spi(void); +// busio.SPI is built on common-hal/async_spi. +#include "shared-module/busio/SPI.h" diff --git a/ports/raspberrypi/common-hal/busio/UART.c b/ports/raspberrypi/common-hal/busio/UART.c index 17fcfa17229..21e5e4eff93 100644 --- a/ports/raspberrypi/common-hal/busio/UART.c +++ b/ports/raspberrypi/common-hal/busio/UART.c @@ -24,24 +24,10 @@ 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 void pin_check(const uint8_t uart, const mcu_pin_obj_t *pin, const uint8_t pin_type) { if (pin == NULL) { return; @@ -50,7 +36,7 @@ static void pin_check(const uint8_t uart, const mcu_pin_obj_t *pin, const uint8_ if (pins_uart != uart) { raise_ValueError_invalid_pins(); } - #ifdef PICO_RP2350 + #if PICO_RP2350 if ((pin_type == 0 && pin->number % 4 == 2) || (pin_type == 1 && pin->number % 4 == 3)) { return; @@ -67,7 +53,7 @@ static uint8_t pin_init(const uint8_t uart, const mcu_pin_obj_t *pin, const uint } claim_pin(pin); gpio_function_t function = GPIO_FUNC_UART; - #ifdef PICO_RP2350 + #if PICO_RP2350 if ((pin_type == 0 && pin->number % 4 == 2) || (pin_type == 1 && pin->number % 4 == 3)) { function = GPIO_FUNC_UART_AUX; @@ -101,6 +87,11 @@ static void uart1_callback(void) { shared_callback(active_uarts[1]); } +// Mark the object deinited. A zeroed object also reads as deinited. +static void mark_deinit(busio_uart_obj_t *self) { + self->uart = NULL; +} + 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, @@ -109,6 +100,10 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, mp_float_t timeout, uint16_t receiver_buffer_size, byte *receiver_buffer, bool sigint_enabled) { + // Ensure the object starts in its deinit state, so its finaliser does + // nothing if this raises before the UART is set up. + mark_deinit(self); + mp_arg_validate_int_max(bits, 8, MP_QSTR_bits); mp_arg_validate_int_min(receiver_buffer_size, 1, MP_QSTR_receiver_buffer_size); @@ -188,7 +183,7 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, } bool common_hal_busio_uart_deinited(busio_uart_obj_t *self) { - return self->tx_pin == NO_PIN && self->rx_pin == NO_PIN; + return self->uart == NULL; } void common_hal_busio_uart_deinit(busio_uart_obj_t *self) { @@ -209,6 +204,7 @@ void common_hal_busio_uart_deinit(busio_uart_obj_t *self) { self->cts_pin = NO_PIN; self->rts_pin = NO_PIN; self->rs485_dir_pin = NO_PIN; + mark_deinit(self); } // Write characters. @@ -231,12 +227,16 @@ size_t common_hal_busio_uart_write(busio_uart_obj_t *self, const uint8_t *data, left_to_write--; } RUN_BACKGROUND_TASKS; + // Allow user to break out of a write blocked by flow control. + if (mp_hal_is_interrupted()) { + break; + } } if (self->rs485_dir_pin != NO_PIN) { uart_tx_wait_blocking(self->uart); gpio_put(self->rs485_dir_pin, self->rs485_invert); } - return len; + return len - left_to_write; } // Read characters. @@ -342,18 +342,3 @@ bool common_hal_busio_uart_ready_to_tx(busio_uart_obj_t *self) { } return uart_is_writable(self->uart); } - -static void pin_never_reset(uint8_t pin) { - if (pin != NO_PIN) { - never_reset_pin_number(pin); - } -} - -void common_hal_busio_uart_never_reset(busio_uart_obj_t *self) { - never_reset_uart(self->uart_id); - pin_never_reset(self->tx_pin); - pin_never_reset(self->rx_pin); - pin_never_reset(self->cts_pin); - pin_never_reset(self->rs485_dir_pin); - pin_never_reset(self->rts_pin); -} diff --git a/ports/raspberrypi/common-hal/busio/UART.h b/ports/raspberrypi/common-hal/busio/UART.h index 3709907633c..5d36485be19 100644 --- a/ports/raspberrypi/common-hal/busio/UART.h +++ b/ports/raspberrypi/common-hal/busio/UART.h @@ -28,4 +28,3 @@ typedef struct { } busio_uart_obj_t; extern void reset_uart(void); -extern void never_reset_uart(uint8_t num); diff --git a/ports/raspberrypi/common-hal/countio/Counter.c b/ports/raspberrypi/common-hal/countio/Counter.c index ba82ca8e7ab..c071f72639a 100644 --- a/ports/raspberrypi/common-hal/countio/Counter.c +++ b/ports/raspberrypi/common-hal/countio/Counter.c @@ -17,9 +17,17 @@ #include "hardware/pwm.h" #include "hardware/irq.h" +#define NO_PIN 0xff + +static void mark_deinit(countio_counter_obj_t *self) { + self->pin = NO_PIN; +} void common_hal_countio_counter_construct(countio_counter_obj_t *self, const mcu_pin_obj_t *pin, countio_edge_t edge, digitalio_pull_t pull) { + // Ensure the object starts in its deinit state, so its finaliser does + // nothing if this raises before the PWM slice is claimed. + mark_deinit(self); if (pwm_gpio_to_channel(pin->number) != PWM_CHAN_B) { mp_raise_RuntimeError(MP_ERROR_TEXT("Pin must be on PWM Channel B")); @@ -29,17 +37,19 @@ void common_hal_countio_counter_construct(countio_counter_obj_t *self, mp_raise_NotImplementedError(MP_ERROR_TEXT("RISE_AND_FALL not available on this chip")); } - self->pin = pin->number; - self->slice_num = pwm_gpio_to_slice_num(self->pin); + uint8_t slice_num = pwm_gpio_to_slice_num(pin->number); - if (MP_STATE_PORT(counting)[self->slice_num] != NULL) { + if (MP_STATE_PORT(counting)[slice_num] != NULL) { mp_raise_RuntimeError(MP_ERROR_TEXT("PWM slice already in use")); } - if (!pwmio_claim_slice_ab_channels(self->slice_num)) { + if (!pwmio_claim_slice_ab_channels(slice_num)) { mp_raise_RuntimeError(MP_ERROR_TEXT("PWM slice channel A already in use")); } + self->pin = pin->number; + self->slice_num = slice_num; + pwm_clear_irq(self->slice_num); pwm_set_irq_enabled(self->slice_num, true); irq_set_exclusive_handler(PWM_IRQ_WRAP, counter_interrupt_handler); @@ -60,16 +70,8 @@ void common_hal_countio_counter_construct(countio_counter_obj_t *self, } -void reset_countio(void) { - for (size_t i = 0; i < NUM_PWM_SLICES; i++) { - if (MP_STATE_PORT(counting)[i] != NULL) { - common_hal_countio_counter_deinit(MP_STATE_PORT(counting)[i]); - } - } -} - bool common_hal_countio_counter_deinited(countio_counter_obj_t *self) { - return self->pin == 0; + return self->pin == NO_PIN; } void common_hal_countio_counter_deinit(countio_counter_obj_t *self) { @@ -79,14 +81,30 @@ void common_hal_countio_counter_deinit(countio_counter_obj_t *self) { pwm_set_enabled(self->slice_num, false); pwm_set_irq_enabled(self->slice_num, false); + pwm_clear_irq(self->slice_num); + + // Put the slice back in its default (free-running) mode, so a later + // PWMOut on it runs. PWMOut doesn't set the clock divider mode. + pwm_config cfg = pwm_get_default_config(); + pwm_init(self->slice_num, &cfg, false); pwmio_release_slice_ab_channels(self->slice_num); reset_pin_number(self->pin); MP_STATE_PORT(counting)[self->slice_num] = NULL; - self->pin = 0; self->slice_num = 0; + mark_deinit(self); + + // Remove the wrap handler after the last Counter, so something else + // (rgbmatrix) can install its own exclusive handler later. + for (size_t i = 0; i < enum_NUM_PWM_SLICES; i++) { + if (MP_STATE_PORT(counting)[i] != NULL) { + return; + } + } + irq_set_enabled(PWM_IRQ_WRAP, false); + irq_remove_handler(PWM_IRQ_WRAP, counter_interrupt_handler); } mp_int_t common_hal_countio_counter_get_count(countio_counter_obj_t *self) { @@ -103,17 +121,16 @@ void common_hal_countio_counter_set_count(countio_counter_obj_t *self, void counter_interrupt_handler(void) { uint32_t mask = pwm_get_irq_status_mask(); - - uint8_t i = 1; - uint8_t pos = 0; - while (!(i & mask)) { - i = i << 1; - ++pos; + if (mask == 0) { + return; } + // RP2350B has more than 8 slices, so look at the whole mask. + uint pos = __builtin_ctz(mask); + pwm_clear_irq(pos); + countio_counter_obj_t *self = MP_STATE_PORT(counting)[pos]; 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 index 93b83e2c267..c18f6440e9b 100644 --- a/ports/raspberrypi/common-hal/countio/Counter.h +++ b/ports/raspberrypi/common-hal/countio/Counter.h @@ -20,5 +20,3 @@ typedef struct { void counter_interrupt_handler(void); - -void reset_countio(void); diff --git a/ports/raspberrypi/common-hal/digitalio/DigitalInOut.c b/ports/raspberrypi/common-hal/digitalio/DigitalInOut.c index f20facdad7d..6485f9e8b72 100644 --- a/ports/raspberrypi/common-hal/digitalio/DigitalInOut.c +++ b/ports/raspberrypi/common-hal/digitalio/DigitalInOut.c @@ -44,11 +44,6 @@ digitalinout_result_t common_hal_digitalio_digitalinout_construct( return DIGITALINOUT_OK; } -void common_hal_digitalio_digitalinout_never_reset( - digitalio_digitalinout_obj_t *self) { - never_reset_pin_number(self->pin->number); -} - bool common_hal_digitalio_digitalinout_deinited(digitalio_digitalinout_obj_t *self) { return self->pin == NULL; } @@ -213,19 +208,26 @@ volatile uint32_t *common_hal_digitalio_digitalinout_get_reg(digitalio_digitalin #endif const uint8_t pin = self->pin->number; - *mask = 1u << pin; + // GPIO32 and up are in the separate SIO "hi" registers. + #if NUM_BANK0_GPIOS > 32 + const bool hi = pin >= 32; + #else + const bool hi = false; + #endif + + *mask = 1u << (pin & 0x1fu); switch (op) { case DIGITALINOUT_REG_READ: - return (volatile uint32_t *)&sio_hw->gpio_in; + return (volatile uint32_t *)(hi ? &sio_hw->gpio_hi_in : &sio_hw->gpio_in); case DIGITALINOUT_REG_WRITE: - return &sio_hw->gpio_out; + return hi ? &sio_hw->gpio_hi_out : &sio_hw->gpio_out; case DIGITALINOUT_REG_SET: - return &sio_hw->gpio_set; + return hi ? &sio_hw->gpio_hi_set : &sio_hw->gpio_set; case DIGITALINOUT_REG_RESET: - return &sio_hw->gpio_clr; + return hi ? &sio_hw->gpio_hi_clr : &sio_hw->gpio_clr; case DIGITALINOUT_REG_TOGGLE: - return &sio_hw->gpio_togl; + return hi ? &sio_hw->gpio_hi_togl : &sio_hw->gpio_togl; default: return NULL; } diff --git a/ports/raspberrypi/common-hal/floppyio/__init__.c b/ports/raspberrypi/common-hal/floppyio/__init__.c index 3f76e892da8..034db15c40a 100644 --- a/ports/raspberrypi/common-hal/floppyio/__init__.c +++ b/ports/raspberrypi/common-hal/floppyio/__init__.c @@ -121,7 +121,7 @@ int common_hal_floppyio_flux_readinto(void *buf, size_t len, digitalio_digitalin while (pio_sm_is_rx_fifo_empty(reader.pio, reader.sm)) { if (time_us_64() > flux_deadline_us) { common_hal_mcu_enable_interrupts(); - common_hal_rp2pio_statemachine_deinit(&state_machine); + rp2pio_statemachine_deinit(&state_machine, true); mp_raise_RuntimeError(MP_ERROR_TEXT("timeout waiting for flux")); } } @@ -130,7 +130,7 @@ int common_hal_floppyio_flux_readinto(void *buf, size_t len, digitalio_digitalin while (READ_INDEX()) { if (time_us_64() > index_deadline_us) { common_hal_mcu_enable_interrupts(); - common_hal_rp2pio_statemachine_deinit(&state_machine); + rp2pio_statemachine_deinit(&state_machine, true); mp_raise_RuntimeError(MP_ERROR_TEXT("timeout waiting for index pulse")); } } @@ -172,7 +172,7 @@ int common_hal_floppyio_flux_readinto(void *buf, size_t len, digitalio_digitalin } common_hal_mcu_enable_interrupts(); - common_hal_rp2pio_statemachine_deinit(&state_machine); + rp2pio_statemachine_deinit(&state_machine, true); return ptr - (uint8_t *)buf; } diff --git a/ports/raspberrypi/common-hal/i2ctarget/I2CTarget.c b/ports/raspberrypi/common-hal/i2ctarget/I2CTarget.c index d1c92eea998..4760ad8923a 100644 --- a/ports/raspberrypi/common-hal/i2ctarget/I2CTarget.c +++ b/ports/raspberrypi/common-hal/i2ctarget/I2CTarget.c @@ -20,23 +20,31 @@ static i2c_inst_t *i2c[2] = {i2c0, i2c1}; #define NO_PIN 0xff +// Mark the object deinited. A zeroed object also reads as deinited. +static void mark_deinit(i2ctarget_i2c_target_obj_t *self) { + self->peripheral = NULL; +} + void common_hal_i2ctarget_i2c_target_construct(i2ctarget_i2c_target_obj_t *self, const mcu_pin_obj_t *scl, const mcu_pin_obj_t *sda, uint8_t *addresses, unsigned int num_addresses, bool smbus) { - self->peripheral = NULL; + // Ensure the object starts in its deinit state, so its finaliser does + // nothing if this raises before the peripheral is set. + mark_deinit(self); // 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. + i2c_inst_t *peripheral = NULL; size_t scl_instance = (scl->number / 2) % 2; size_t sda_instance = (sda->number / 2) % 2; if (scl->number % 2 == 1 && sda->number % 2 == 0 && scl_instance == sda_instance) { - self->peripheral = i2c[sda_instance]; + peripheral = i2c[sda_instance]; } - if (self->peripheral == NULL) { + if (peripheral == NULL) { raise_ValueError_invalid_pins(); } - if ((i2c_get_hw(self->peripheral)->enable & I2C_IC_ENABLE_ENABLE_BITS) != 0) { + if ((i2c_get_hw(peripheral)->enable & I2C_IC_ENABLE_ENABLE_BITS) != 0) { mp_raise_ValueError(MP_ERROR_TEXT("I2C peripheral in use")); } @@ -44,6 +52,7 @@ void common_hal_i2ctarget_i2c_target_construct(i2ctarget_i2c_target_obj_t *self, mp_raise_ValueError(MP_ERROR_TEXT("Only one address is allowed")); } + self->peripheral = peripheral; self->addresses = addresses; self->num_addresses = num_addresses; self->scl_pin = scl->number; @@ -59,6 +68,9 @@ void common_hal_i2ctarget_i2c_target_construct(i2ctarget_i2c_target_obj_t *self, gpio_set_pulls(sda->number, true, false); gpio_set_pulls(scl->number, true, false); + claim_pin(sda); + claim_pin(scl); + self->peripheral->hw->intr_mask |= I2C_IC_INTR_MASK_M_RESTART_DET_BITS; i2c_set_slave_mode(self->peripheral, true, self->addresses[0]); @@ -66,7 +78,7 @@ void common_hal_i2ctarget_i2c_target_construct(i2ctarget_i2c_target_obj_t *self, } bool common_hal_i2ctarget_i2c_target_deinited(i2ctarget_i2c_target_obj_t *self) { - return self->sda_pin == NO_PIN; + return self->peripheral == NULL; } void common_hal_i2ctarget_i2c_target_deinit(i2ctarget_i2c_target_obj_t *self) { @@ -80,11 +92,17 @@ void common_hal_i2ctarget_i2c_target_deinit(i2ctarget_i2c_target_obj_t *self) { reset_pin_number(self->scl_pin); self->sda_pin = NO_PIN; self->scl_pin = NO_PIN; - - return; + mark_deinit(self); } int common_hal_i2ctarget_i2c_target_is_addressed(i2ctarget_i2c_target_obj_t *self, uint8_t *address, bool *is_read, bool *is_restart) { + // Interrupt bits must be cleared by software. Clear the STOP and + // RESTART interrupt bits after an I2C transaction finishes. + if (self->peripheral->hw->raw_intr_stat & I2C_IC_INTR_STAT_R_STOP_DET_BITS) { + self->peripheral->hw->clr_stop_det; + self->peripheral->hw->clr_restart_det; + } + if (!((self->peripheral->hw->raw_intr_stat & I2C_IC_INTR_STAT_R_RX_FULL_BITS) || (self->peripheral->hw->raw_intr_stat & I2C_IC_INTR_STAT_R_RD_REQ_BITS))) { return 0; } @@ -98,12 +116,20 @@ int common_hal_i2ctarget_i2c_target_is_addressed(i2ctarget_i2c_target_obj_t *sel } int common_hal_i2ctarget_i2c_target_read_byte(i2ctarget_i2c_target_obj_t *self, uint8_t *data) { - if (self->peripheral->hw->status & I2C_IC_STATUS_RFNE_BITS) { - *data = (uint8_t)self->peripheral->hw->data_cmd; - return 1; - } else { - return 0; + // Wait for data to arrive or a STOP condition indicating the transfer is over. + // Without this wait, the CPU can drain the FIFO faster than bytes arrive on the + // I2C bus, causing transfers to be split into multiple partial reads. + for (int t = 0; t < 100; t++) { + if (self->peripheral->hw->status & I2C_IC_STATUS_RFNE_BITS) { + *data = (uint8_t)self->peripheral->hw->data_cmd; + return 1; + } + if (self->peripheral->hw->raw_intr_stat & I2C_IC_INTR_STAT_R_STOP_DET_BITS) { + break; + } + mp_hal_delay_us(10); } + return 0; } int common_hal_i2ctarget_i2c_target_write_byte(i2ctarget_i2c_target_obj_t *self, uint8_t data) { diff --git a/ports/raspberrypi/common-hal/imagecapture/ParallelImageCapture.c b/ports/raspberrypi/common-hal/imagecapture/ParallelImageCapture.c index d0a7a1d7b08..945f8f90df8 100644 --- a/ports/raspberrypi/common-hal/imagecapture/ParallelImageCapture.c +++ b/ports/raspberrypi/common-hal/imagecapture/ParallelImageCapture.c @@ -48,30 +48,18 @@ /* .wrap */ \ } -static mcu_pin_obj_t *pin_from_number(uint8_t number) { - const mp_map_t *mcu_map = &mcu_pin_globals.map; - for (uint8_t i = 0; i < mcu_map->alloc; i++) { - mp_obj_t val = mcu_map->table[i].value; - if (!mp_obj_is_type(val, &mcu_pin_type)) { - continue; - } - mcu_pin_obj_t *pin = MP_OBJ_TO_PTR(val); - if (pin->number == number) { - return pin; - } - } - return NULL; -} - void common_hal_imagecapture_parallelimagecapture_construct(imagecapture_parallelimagecapture_obj_t *self, - const uint8_t data_pins[], + const mcu_pin_obj_t **data_pins, uint8_t data_count, const mcu_pin_obj_t *data_clock, const mcu_pin_obj_t *vertical_sync, const mcu_pin_obj_t *horizontal_reference) { + // Ensure the object starts in its deinit state, so its finaliser does + // nothing if this raises before the state machine is constructed. + common_hal_rp2pio_statemachine_mark_deinit(&self->state_machine); for (int i = 1; i < data_count; i++) { - if (data_pins[i] - data_pins[0] != i) { + if (common_hal_mcu_pin_number(data_pins[i]) - common_hal_mcu_pin_number(data_pins[0]) != i) { mp_raise_RuntimeError(MP_ERROR_TEXT("Pins must be sequential")); } } @@ -84,7 +72,7 @@ void common_hal_imagecapture_parallelimagecapture_construct(imagecapture_paralle 0, 0, // init NULL, 0, // may_exec NULL, 0, PIO_PINMASK32_NONE, PIO_PINMASK32_NONE, // out pins - pin_from_number(data_pins[0]), data_count, // in pins + data_pins[0], data_count, // in pins PIO_PINMASK32_NONE, PIO_PINMASK32_NONE, // in pulls NULL, 0, PIO_PINMASK32_NONE, PIO_PINMASK32_NONE, // set pins #if DEBUG_STATE_MACHINE diff --git a/ports/raspberrypi/common-hal/mcp4822/MCP4822.c b/ports/raspberrypi/common-hal/mcp4822/MCP4822.c new file mode 100644 index 00000000000..1329b177b9f --- /dev/null +++ b/ports/raspberrypi/common-hal/mcp4822/MCP4822.c @@ -0,0 +1,291 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tod Kurt +// +// SPDX-License-Identifier: MIT +// +// MCP4822 dual-channel 12-bit SPI DAC audio output. +// Uses PIO + DMA for non-blocking audio playback, mirroring audiobusio.I2SOut. + +#include +#include + +#include "mpconfigport.h" + +#include "py/gc.h" +#include "py/mperrno.h" +#include "py/runtime.h" +#include "common-hal/mcp4822/MCP4822.h" +#include "shared-bindings/mcp4822/MCP4822.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-module/audiocore/__init__.h" +#include "bindings/rp2pio/StateMachine.h" + +// ───────────────────────────────────────────────────────────────────────────── +// PIO program for MCP4822 SPI DAC +// ───────────────────────────────────────────────────────────────────────────── +// +// Pin assignment: +// OUT pin (1) = MOSI — serial data out +// SET pins (N) = MOSI through CS — for CS control & command-bit injection +// SIDE-SET pin (1) = SCK — serial clock +// +// SET PINS bit mapping (bit0=MOSI, ..., bit N=CS): +// 0 = CS low, MOSI low 1 = CS low, MOSI high +// (1 << cs_bit_pos) = CS high, MOSI low +// +// SIDE-SET (1 pin, SCK): side 0 = SCK low, side 1 = SCK high +// +// MCP4822 16-bit command word: +// [15] channel (0=A, 1=B) [14] don't care [13] gain (1=1x, 0=2x) +// [12] output enable (1) [11:0] 12-bit data +// +// DMA feeds unsigned 16-bit audio samples. RP2040 narrow-write replication +// fills both halves of the 32-bit PIO FIFO entry with the same value, +// giving mono→stereo for free. +// +// The PIO pulls 32 bits, then sends two SPI transactions: +// Channel A: cmd nibble, then all 16 sample bits from upper half-word +// Channel B: cmd nibble, then all 16 sample bits from lower half-word +// The MCP4822 captures exactly 16 bits per CS frame (4 cmd + 12 data), +// so only the top 12 of the 16 sample bits become DAC data. The bottom +// 4 sample bits clock out harmlessly after the DAC has latched. +// This gives correct 16-bit → 12-bit scaling (effectively sample >> 4). +// +// PIO instruction encoding with .side_set 1 (no opt): +// [15:13] opcode [12] side-set [11:8] delay [7:0] operands +// +// Total: 26 instructions, 86 PIO clocks per audio sample. +// ───────────────────────────────────────────────────────────────────────────── + +static const uint16_t mcp4822_pio_program[] = { + // side SCK + // 0: pull noblock side 0 ; Get 32 bits or keep X if FIFO empty + 0x8080, + // 1: mov x, osr side 0 ; Save for pull-noblock fallback + 0xA027, + + // ── Channel A: command nibble 0b0011 (1x gain) ──────────────────────── + // 2: set pins, 0 side 0 ; CS low, MOSI=0 (bit15=0: channel A) + 0xE000, + // 3: nop side 1 ; SCK high — latch bit 15 + 0xB042, + // 4: set pins, 0 side 0 ; MOSI=0 (bit14=0: don't care) + 0xE000, + // 5: nop side 1 ; SCK high + 0xB042, + // 6: set pins, 1 side 0 ; MOSI=1 (bit13=1: gain 1x) [patched for 2x] + 0xE001, + // 7: nop side 1 ; SCK high + 0xB042, + // 8: set pins, 1 side 0 ; MOSI=1 (bit12=1: output active) + 0xE001, + // 9: nop side 1 ; SCK high + 0xB042, + // 10: set y, 15 side 0 ; Loop counter: 16 sample bits + 0xE04F, + // 11: out pins, 1 side 0 ; Data bit → MOSI; SCK low (bitloopA) + 0x6001, + // 12: jmp y--, 11 side 1 ; SCK high, loop back + 0x108B, + // 13: set pins, 4 side 0 ; CS high — DAC A latches + 0xE004, + + // ── Channel B: command nibble 0b1011 (1x gain) ──────────────────────── + // 14: set pins, 1 side 0 ; CS low, MOSI=1 (bit15=1: channel B) + 0xE001, + // 15: nop side 1 ; SCK high + 0xB042, + // 16: set pins, 0 side 0 ; MOSI=0 (bit14=0) + 0xE000, + // 17: nop side 1 ; SCK high + 0xB042, + // 18: set pins, 1 side 0 ; MOSI=1 (bit13=1: gain 1x) [patched for 2x] + 0xE001, + // 19: nop side 1 ; SCK high + 0xB042, + // 20: set pins, 1 side 0 ; MOSI=1 (bit12=1: output active) + 0xE001, + // 21: nop side 1 ; SCK high + 0xB042, + // 22: set y, 15 side 0 ; Loop counter: 16 sample bits + 0xE04F, + // 23: out pins, 1 side 0 ; Data bit → MOSI; SCK low (bitloopB) + 0x6001, + // 24: jmp y--, 23 side 1 ; SCK high, loop back + 0x1097, + // 25: set pins, 4 side 0 ; CS high — DAC B latches + 0xE004, +}; + +// Clocks per sample: 2 (pull+mov) + 42 (chanA) + 42 (chanB) = 86 +// Per channel: 8(4 cmd bits × 2 clks) + 1(set y) + 32(16 bits × 2 clks) + 1(cs high) = 42 +#define MCP4822_CLOCKS_PER_SAMPLE 86 + +// MCP4822 gain bit (bit 13) position in the PIO program: +// Instruction 6 = channel A gain bit +// Instruction 18 = channel B gain bit +// 1x gain: set pins, 1 (0xE001) — bit 13 = 1 +// 2x gain: set pins, 0 (0xE000) — bit 13 = 0 +#define MCP4822_PIO_GAIN_INSTR_A 6 +#define MCP4822_PIO_GAIN_INSTR_B 18 +#define MCP4822_PIO_GAIN_1X 0xE001 // set pins, 1 +#define MCP4822_PIO_GAIN_2X 0xE000 // set pins, 0 + +void mcp4822_reset(void) { +} + +// Caller validates that pins are free. +void common_hal_mcp4822_mcp4822_construct(mcp4822_mcp4822_obj_t *self, + const mcu_pin_obj_t *clock, const mcu_pin_obj_t *mosi, + const mcu_pin_obj_t *cs, uint8_t gain) { + // Ensure the object starts in its deinit state, so its finaliser does + // nothing if this raises before the state machine is constructed. + common_hal_rp2pio_statemachine_mark_deinit(&self->state_machine); + + // The SET pin group spans from MOSI to CS. + // MOSI must have a lower GPIO number than CS, gap at most 4. + if (cs->number <= mosi->number || (cs->number - mosi->number) > 4) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("Invalid %q and %q"), MP_QSTR_CS, MP_QSTR_MOSI); + } + + uint8_t set_count = cs->number - mosi->number + 1; + + // Build a mutable copy of the PIO program and patch the gain bit + uint16_t program[MP_ARRAY_SIZE(mcp4822_pio_program)]; + memcpy(program, mcp4822_pio_program, sizeof(mcp4822_pio_program)); + uint16_t gain_instr = (gain == 2) ? MCP4822_PIO_GAIN_2X : MCP4822_PIO_GAIN_1X; + program[MCP4822_PIO_GAIN_INSTR_A] = gain_instr; + program[MCP4822_PIO_GAIN_INSTR_B] = gain_instr; + + // Initial SET pin state: CS high (bit at CS position), others low + uint32_t cs_bit_position = cs->number - mosi->number; + pio_pinmask32_t initial_set_state = PIO_PINMASK32_FROM_VALUE(1u << cs_bit_position); + pio_pinmask32_t initial_set_dir = PIO_PINMASK32_FROM_VALUE((1u << set_count) - 1); + + common_hal_rp2pio_statemachine_construct( + &self->state_machine, + program, MP_ARRAY_SIZE(mcp4822_pio_program), + 44100 * MCP4822_CLOCKS_PER_SAMPLE, // Initial frequency; play() adjusts + NULL, 0, // No init program + NULL, 0, // No may_exec + mosi, 1, // OUT: MOSI, 1 pin + PIO_PINMASK32_NONE, PIO_PINMASK32_ALL, // OUT state=low, dir=output + NULL, 0, // IN: none + PIO_PINMASK32_NONE, PIO_PINMASK32_NONE, // IN pulls: none + mosi, set_count, // SET: MOSI..CS + initial_set_state, initial_set_dir, // SET state (CS high), dir=output + clock, 1, false, // SIDE-SET: SCK, 1 pin, not pindirs + PIO_PINMASK32_NONE, // SIDE-SET state: SCK low + PIO_PINMASK32_FROM_VALUE(0x1), // SIDE-SET dir: output + false, // No sideset enable + NULL, PULL_NONE, // No jump pin + PIO_PINMASK_NONE, // No wait GPIO + true, // Exclusive pin use + false, 32, false, // OUT shift: no autopull, 32-bit, shift left + false, // Don't wait for txstall + false, 32, false, // IN shift (unused) + false, // Not user-interruptible + 0, -1, // Wrap: whole program + PIO_ANY_OFFSET, + PIO_FIFO_TYPE_DEFAULT, + PIO_MOV_STATUS_DEFAULT, + PIO_MOV_N_DEFAULT + ); + + self->playing = false; + audio_dma_init(&self->dma); +} + +bool common_hal_mcp4822_mcp4822_deinited(mcp4822_mcp4822_obj_t *self) { + return common_hal_rp2pio_statemachine_deinited(&self->state_machine); +} + +void common_hal_mcp4822_mcp4822_deinit(mcp4822_mcp4822_obj_t *self) { + if (common_hal_mcp4822_mcp4822_deinited(self)) { + return; + } + if (common_hal_mcp4822_mcp4822_get_playing(self)) { + common_hal_mcp4822_mcp4822_stop(self); + } + common_hal_rp2pio_statemachine_deinit(&self->state_machine); + audio_dma_deinit(&self->dma); +} + +void common_hal_mcp4822_mcp4822_play(mcp4822_mcp4822_obj_t *self, + mp_obj_t sample, bool loop) { + + if (common_hal_mcp4822_mcp4822_get_playing(self)) { + common_hal_mcp4822_mcp4822_stop(self); + } + + audiosample_check(sample); + + uint8_t bits_per_sample = audiosample_get_bits_per_sample(sample); + if (bits_per_sample < 16) { + bits_per_sample = 16; + } + + uint32_t sample_rate = audiosample_get_sample_rate(sample); + uint8_t channel_count = audiosample_get_channel_count(sample); + if (channel_count > 2) { + mp_raise_ValueError(MP_ERROR_TEXT("Too many channels in sample.")); + } + + // PIO clock = sample_rate × clocks_per_sample + common_hal_rp2pio_statemachine_set_frequency( + &self->state_machine, + (uint32_t)sample_rate * MCP4822_CLOCKS_PER_SAMPLE); + common_hal_rp2pio_statemachine_restart(&self->state_machine); + + audio_dma_result result = audio_dma_setup_playback( + &self->dma, + sample, + loop, + false, // single_channel_output + 0, // audio_channel + false, // output_signed = false (unsigned for MCP4822) + bits_per_sample, // output_resolution + (uint32_t)&self->state_machine.pio->txf[self->state_machine.state_machine], + self->state_machine.tx_dreq, + false); // swap_channel + + if (result == AUDIO_DMA_DMA_BUSY) { + common_hal_mcp4822_mcp4822_stop(self); + mp_raise_RuntimeError(MP_ERROR_TEXT("No DMA channel found")); + } else if (result == AUDIO_DMA_MEMORY_ERROR) { + common_hal_mcp4822_mcp4822_stop(self); + mp_raise_RuntimeError(MP_ERROR_TEXT("Unable to allocate buffers for signed conversion")); + } else if (result == AUDIO_DMA_SOURCE_ERROR) { + common_hal_mcp4822_mcp4822_stop(self); + mp_raise_RuntimeError(MP_ERROR_TEXT("Audio source error")); + } + + self->playing = true; +} + +void common_hal_mcp4822_mcp4822_pause(mcp4822_mcp4822_obj_t *self) { + audio_dma_pause(&self->dma); +} + +void common_hal_mcp4822_mcp4822_resume(mcp4822_mcp4822_obj_t *self) { + audio_dma_resume(&self->dma); +} + +bool common_hal_mcp4822_mcp4822_get_paused(mcp4822_mcp4822_obj_t *self) { + return audio_dma_get_paused(&self->dma); +} + +void common_hal_mcp4822_mcp4822_stop(mcp4822_mcp4822_obj_t *self) { + audio_dma_stop(&self->dma); + common_hal_rp2pio_statemachine_stop(&self->state_machine); + self->playing = false; +} + +bool common_hal_mcp4822_mcp4822_get_playing(mcp4822_mcp4822_obj_t *self) { + bool playing = audio_dma_get_playing(&self->dma); + if (!playing && self->playing) { + common_hal_mcp4822_mcp4822_stop(self); + } + return playing; +} diff --git a/ports/raspberrypi/common-hal/mcp4822/MCP4822.h b/ports/raspberrypi/common-hal/mcp4822/MCP4822.h new file mode 100644 index 00000000000..53c8e862b63 --- /dev/null +++ b/ports/raspberrypi/common-hal/mcp4822/MCP4822.h @@ -0,0 +1,22 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tod Kurt +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "common-hal/microcontroller/Pin.h" +#include "common-hal/rp2pio/StateMachine.h" + +#include "audio_dma.h" +#include "py/obj.h" + +typedef struct { + mp_obj_base_t base; + rp2pio_statemachine_obj_t state_machine; + audio_dma_t dma; + bool playing; +} mcp4822_mcp4822_obj_t; + +void mcp4822_reset(void); diff --git a/ports/raspberrypi/common-hal/mcp4822/__init__.c b/ports/raspberrypi/common-hal/mcp4822/__init__.c new file mode 100644 index 00000000000..48981fc88a7 --- /dev/null +++ b/ports/raspberrypi/common-hal/mcp4822/__init__.c @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tod Kurt +// +// SPDX-License-Identifier: MIT + +// No module-level init needed. diff --git a/ports/raspberrypi/common-hal/mdns/RemoteService.c b/ports/raspberrypi/common-hal/mdns/RemoteService.c index 650e86da9d9..3d80199397e 100644 --- a/ports/raspberrypi/common-hal/mdns/RemoteService.c +++ b/ports/raspberrypi/common-hal/mdns/RemoteService.c @@ -39,6 +39,3 @@ mp_obj_t common_hal_mdns_remoteservice_get_ipv4_address(mdns_remoteservice_obj_t } return common_hal_ipaddress_new_ipv4address(addr); } - -void common_hal_mdns_remoteservice_deinit(mdns_remoteservice_obj_t *self) { -} diff --git a/ports/raspberrypi/common-hal/mdns/Server.c b/ports/raspberrypi/common-hal/mdns/Server.c index 4c87dd46640..dfa782d48c1 100644 --- a/ports/raspberrypi/common-hal/mdns/Server.c +++ b/ports/raspberrypi/common-hal/mdns/Server.c @@ -34,24 +34,41 @@ void mdns_server_construct(mdns_server_obj_t *self, bool workflow) { return; } + MICROPY_PY_LWIP_ENTER if (!inited) { mdns_resp_init(); inited = true; } else { mdns_resp_restart(NETIF_STA); } + MICROPY_PY_LWIP_EXIT self->inited = true; - uint8_t mac[6]; - wifi_radio_get_mac_address(&common_hal_wifi_radio_obj, mac); - snprintf(self->default_hostname, sizeof(self->default_hostname), "cpy-%02x%02x%02x", mac[3], mac[4], mac[5]); - common_hal_mdns_server_set_hostname(self, self->default_hostname); + self->instance_name[0] = '\0'; + self->num_txt_records = 0; + self->txt_storage = NULL; + + // Seed the mDNS hostname from the netif hostname configured via + // CIRCUITPY_WIFI_HOSTNAME. Fall back to the historical MAC-based + // cpy-XXXXXX name when the user hasn't set one, so existing default + // hostnames keep working. + if (common_hal_wifi_radio_obj.hostname[0] != '\0') { + common_hal_mdns_server_set_hostname(self, common_hal_wifi_radio_obj.hostname); + } else { + uint8_t mac[6]; + wifi_radio_get_mac_address(&common_hal_wifi_radio_obj, mac); + char default_hostname[sizeof("cpy-XXXXXX")]; + snprintf(default_hostname, sizeof(default_hostname), "cpy-%02x%02x%02x", mac[3], mac[4], mac[5]); + common_hal_mdns_server_set_hostname(self, default_hostname); + } if (workflow) { // Add a second host entry to respond to "circuitpython.local" queries as well. #if MDNS_MAX_SECONDARY_HOSTNAMES > 0 + MICROPY_PY_LWIP_ENTER mdns_resp_add_secondary_hostname(NETIF_STA, "circuitpython"); + MICROPY_PY_LWIP_EXIT #endif } } @@ -73,7 +90,9 @@ void common_hal_mdns_server_deinit(mdns_server_obj_t *self) { } self->inited = false; object_inited = false; + MICROPY_PY_LWIP_ENTER mdns_resp_remove_netif(NETIF_STA); + MICROPY_PY_LWIP_EXIT } bool common_hal_mdns_server_deinited(mdns_server_obj_t *self) { @@ -85,21 +104,26 @@ const char *common_hal_mdns_server_get_hostname(mdns_server_obj_t *self) { } void common_hal_mdns_server_set_hostname(mdns_server_obj_t *self, const char *hostname) { + MICROPY_PY_LWIP_ENTER if (mdns_resp_netif_active(NETIF_STA)) { mdns_resp_rename_netif(NETIF_STA, hostname); } else { mdns_resp_add_netif(NETIF_STA, hostname); } + MICROPY_PY_LWIP_EXIT - self->hostname = hostname; + strlcpy(self->hostname, hostname, sizeof(self->hostname)); } const char *common_hal_mdns_server_get_instance_name(mdns_server_obj_t *self) { + if (self->instance_name[0] == '\0') { + return self->hostname; + } return self->instance_name; } void common_hal_mdns_server_set_instance_name(mdns_server_obj_t *self, const char *instance_name) { - self->instance_name = instance_name; + strlcpy(self->instance_name, instance_name, sizeof(self->instance_name)); } typedef struct { @@ -177,9 +201,11 @@ size_t mdns_server_find(mdns_server_obj_t *self, const char *service_type, const state.out = out; state.out_len = out_len; + MICROPY_PY_LWIP_ENTER err_t err = mdns_search_service(NULL, service_type, proto, NETIF_STA, &search_result_cb, &state, &state.request_id); + MICROPY_PY_LWIP_EXIT if (err != ERR_OK) { return 0; } @@ -192,16 +218,19 @@ size_t mdns_server_find(mdns_server_obj_t *self, const char *service_type, const supervisor_ticks_ms64() - start_ticks < timeout_ms) { RUN_BACKGROUND_TASKS; } + MICROPY_PY_LWIP_ENTER if (state.request_id < MDNS_MAX_REQUESTS) { mdns_search_stop(state.request_id); state.request_id = MDNS_MAX_REQUESTS; } + MICROPY_PY_LWIP_EXIT return state.i; } typedef struct { uint8_t request_id; + bool out_of_memory; mdns_remoteservice_obj_t *head; size_t count; } alloc_search_state_t; @@ -211,14 +240,13 @@ static void alloc_search_result_cb(struct mdns_answer *answer, const char *varpa if ((flags & MDNS_SEARCH_RESULT_FIRST) != 0) { // first - mdns_remoteservice_obj_t *service = m_malloc(sizeof(mdns_remoteservice_obj_t)); + mdns_remoteservice_obj_t *service = m_malloc_maybe(sizeof(mdns_remoteservice_obj_t)); if (service == NULL) { // alloc fails mdns_search_stop(state->request_id); state->request_id = MDNS_MAX_REQUESTS; - if (state->count == 0) { - m_malloc_fail(sizeof(mdns_remoteservice_obj_t)); - } + // lwip holds its lock here, so find() raises the MemoryError after releasing it. + state->out_of_memory = true; return; } service->base.type = &mdns_remoteservice_type; @@ -237,12 +265,15 @@ mp_obj_t common_hal_mdns_server_find(mdns_server_obj_t *self, const char *servic } alloc_search_state_t state; + state.out_of_memory = false; state.count = 0; state.head = NULL; + MICROPY_PY_LWIP_ENTER err_t err = mdns_search_service(NULL, service_type, proto, NETIF_STA, &alloc_search_result_cb, &state, &state.request_id); + MICROPY_PY_LWIP_EXIT if (err != ERR_OK) { mp_raise_RuntimeError(MP_ERROR_TEXT("Unable to start mDNS query")); } @@ -255,10 +286,16 @@ mp_obj_t common_hal_mdns_server_find(mdns_server_obj_t *self, const char *servic supervisor_ticks_ms64() - start_ticks < timeout_ms) { RUN_BACKGROUND_TASKS; } + MICROPY_PY_LWIP_ENTER if (state.request_id < MDNS_MAX_REQUESTS) { mdns_search_stop(state.request_id); state.request_id = MDNS_MAX_REQUESTS; } + MICROPY_PY_LWIP_EXIT + + if (state.out_of_memory && state.count == 0) { + m_malloc_fail(sizeof(mdns_remoteservice_obj_t)); + } mp_obj_tuple_t *tuple = MP_OBJ_TO_PTR(mp_obj_new_tuple(state.count, NULL)); mdns_remoteservice_obj_t *next = state.head; @@ -282,21 +319,71 @@ static void srv_txt_cb(struct mdns_service *service, void *ptr) { for (size_t i = 0; i < self->num_txt_records; i++) { res = mdns_resp_add_service_txtitem(service, self->txt_records[i], strlen(self->txt_records[i])); if (res != ERR_OK) { - mp_raise_RuntimeError(MP_ERROR_TEXT("Failed to add service TXT record")); + // lwip calls this with its lock held, also from its IRQ: raising would leave the lock + // taken or unwind into lwip, so send the records that fit. return; } } } +// Take our own copies of the TXT records. lwip only stores srv_txt_cb and this +// object, and calls back at packet-build time, so the caller's strings must +// outlive the call -- and the caller hands us pointers into GC-heap strings. +// +// WARNING: the copies live on the GC heap, which is only safe because TXT +// records can reach us solely through the Python binding, so the VM is +// necessarily running and this object is itself a GC object that dies with the +// same heap. The supervisor's static mdns_server_obj_t never gets TXT records +// (web_workflow.c passes NULL, 0). If supervisor code ever needs to advertise +// TXT records, this must move off the GC heap first -- an inline pool in +// mdns_server_obj_t, or port_malloc -- or the records will dangle after the +// first VM reset. static void assign_txt_records(mdns_server_obj_t *self, const char *txt_records[], size_t num_txt_records) { - size_t allowed_num_txt_records = MDNS_MAX_TXT_RECORDS < num_txt_records ? MDNS_MAX_TXT_RECORDS : num_txt_records; - self->num_txt_records = allowed_num_txt_records; - for (size_t i = 0; i < allowed_num_txt_records; i++) { - self->txt_records[i] = txt_records[i]; + size_t total = 0; + for (size_t i = 0; i < num_txt_records; i++) { + total += strlen(txt_records[i]) + 1; } + + // Build the replacement before touching self, so that the allocation, and + // any MemoryError it raises, happens outside the lwip lock below. + char *storage = NULL; + const char *records[MDNS_MAX_TXT_RECORDS]; + if (total > 0) { + storage = m_malloc_maybe(total); + if (storage == NULL) { + m_malloc_fail(total); + } + char *next = storage; + for (size_t i = 0; i < num_txt_records; i++) { + size_t size = strlen(txt_records[i]) + 1; + memcpy(next, txt_records[i], size); + records[i] = next; + next += size; + } + } + + // srv_txt_cb reads these from the lwip IRQ, so hold lwip off while they + // change. Otherwise a callback already part way through the old records + // keeps pointers into storage we are about to release. + MICROPY_PY_LWIP_ENTER + char *old_storage = self->txt_storage; + for (size_t i = 0; i < num_txt_records; i++) { + self->txt_records[i] = records[i]; + } + self->txt_storage = storage; + self->num_txt_records = num_txt_records; + MICROPY_PY_LWIP_EXIT + + // Nothing can be holding pointers into it now, so release it here rather + // than leaving the GC to do it at an unpredictable time. + m_free(old_storage); } void common_hal_mdns_server_advertise_service(mdns_server_obj_t *self, const char *service_type, const char *protocol, mp_int_t port, const char *txt_records[], size_t num_txt_records) { + // Check before touching any state, so a rejected call leaves the existing + // advertisement alone. + mp_arg_validate_length_max(num_txt_records, MDNS_MAX_TXT_RECORDS, MP_QSTR_txt_records); + enum mdns_sd_proto proto = DNSSD_PROTO_UDP; if (strcmp(protocol, "_tcp") == 0) { proto = DNSSD_PROTO_TCP; @@ -312,11 +399,15 @@ void common_hal_mdns_server_advertise_service(mdns_server_obj_t *self, const cha } } if (existing_slot < MDNS_MAX_SERVICES) { + MICROPY_PY_LWIP_ENTER mdns_resp_del_service(NETIF_STA, existing_slot); + MICROPY_PY_LWIP_EXIT } assign_txt_records(self, txt_records, num_txt_records); - int8_t slot = mdns_resp_add_service(NETIF_STA, self->instance_name, service_type, proto, port, srv_txt_cb, self); + MICROPY_PY_LWIP_ENTER + int8_t slot = mdns_resp_add_service(NETIF_STA, common_hal_mdns_server_get_instance_name(self), service_type, proto, port, srv_txt_cb, self); + MICROPY_PY_LWIP_EXIT if (slot < 0) { mp_raise_RuntimeError(MP_ERROR_TEXT("Out of MDNS service slots")); return; diff --git a/ports/raspberrypi/common-hal/mdns/Server.h b/ports/raspberrypi/common-hal/mdns/Server.h index 620e201c897..041add08818 100644 --- a/ports/raspberrypi/common-hal/mdns/Server.h +++ b/ports/raspberrypi/common-hal/mdns/Server.h @@ -14,11 +14,16 @@ typedef struct { mp_obj_base_t base; - const char *hostname; - const char *instance_name; - char default_hostname[sizeof("cpy-XXXXXX")]; + // Store copies rather than the caller's pointers. The setters are handed + // GC-heap strings, which are recycled when the VM resets while this object + // (and the web workflow's static one) lives on. + char hostname[64]; // RFC 6762 Appendix A - 63 bytes for label + 1 for NUL + char instance_name[64]; // RFC 6763 Section 7.2 - 63 bytes + 1 for NUL const char *service_type[MDNS_MAX_SERVICES]; size_t num_txt_records; + // Owned copies of the TXT records, packed NUL-separated into txt_storage, + // which lives on the GC heap. See the warning on assign_txt_records(). + char *txt_storage; const char *txt_records[MDNS_MAX_TXT_RECORDS]; // Track if this object owns access to the underlying MDNS service. bool inited; diff --git a/ports/raspberrypi/common-hal/memorymap/AddressRange.c b/ports/raspberrypi/common-hal/memorymap/AddressRange.c index 0796a3b860b..a5e860cb40c 100644 --- a/ports/raspberrypi/common-hal/memorymap/AddressRange.c +++ b/ports/raspberrypi/common-hal/memorymap/AddressRange.c @@ -14,7 +14,7 @@ #include "hardware/regs/addressmap.h" // RP2 address map ranges, must be arranged in order by ascending start address -#ifdef PICO_RP2040 +#if PICO_RP2040 addressmap_rp2_range_t rp2_ranges[] = { {(uint8_t *)ROM_BASE, 0x00004000, ROM}, // boot ROM {(uint8_t *)XIP_BASE, 0x00100000, XIP}, // XIP normal cache operation @@ -36,7 +36,7 @@ addressmap_rp2_range_t rp2_ranges[] = { {(uint8_t *)PPB_BASE, 0x00004000, IO} // PPB registers }; #endif -#ifdef PICO_RP2350 +#if PICO_RP2350 addressmap_rp2_range_t rp2_ranges[] = { {(uint8_t *)ROM_BASE, 0x00004000, ROM}, // boot ROM {(uint8_t *)XIP_BASE, 0x00100000, XIP}, // XIP normal cache operation diff --git a/ports/raspberrypi/common-hal/microcontroller/Pin.c b/ports/raspberrypi/common-hal/microcontroller/Pin.c index 3c5286d36c4..257e1ee08ff 100644 --- a/ports/raspberrypi/common-hal/microcontroller/Pin.c +++ b/ports/raspberrypi/common-hal/microcontroller/Pin.c @@ -22,36 +22,14 @@ static uint32_t cyw_pin_claimed; void reset_pin_number_cyw(uint8_t pin_no) { cyw_pin_claimed &= ~(1LL << pin_no); -} -#endif - -static uint64_t never_reset_pins; -void reset_all_pins(void) { - for (size_t i = 0; i < NUM_BANK0_GPIOS; i++) { - if ((never_reset_pins & (1LL << i)) != 0) { - continue; - } - reset_pin_number(i); - } - #if CIRCUITPY_CYW43 - if (cyw_ever_init) { - // reset LED and SMPS_MODE to Low; don't touch VBUS_SENSE - // otherwise it is switched to output mode forever! - cyw43_arch_gpio_put(0, 0); - cyw43_arch_gpio_put(1, 0); + // Drive the LED (GPIO 0) and SMPS_MODE (GPIO 1) low. Don't touch + // VBUS_SENSE (GPIO 2): writing it would switch it to an output for good. + if (cyw_ever_init && pin_no <= 1) { + cyw43_arch_gpio_put(pin_no, false); } - cyw_pin_claimed = 0; - #endif -} - -void never_reset_pin_number(uint8_t pin_number) { - if (pin_number >= NUM_BANK0_GPIOS) { - return; - } - - never_reset_pins |= 1LL << pin_number; } +#endif // By default, all pins get reset in the same way MP_WEAK bool board_reset_pin_number(uint8_t pin_number) { @@ -64,7 +42,6 @@ void reset_pin_number(uint8_t pin_number) { } gpio_bank0_pin_claimed &= ~(1LL << pin_number); - never_reset_pins &= ~(1LL << pin_number); // Allow the board to override the reset state of any pin if (board_reset_pin_number(pin_number)) { @@ -80,11 +57,10 @@ void reset_pin_number(uint8_t pin_number) { hw_set_bits(&pads_bank0_hw->io[pin_number], PADS_BANK0_GPIO0_OD_BITS); } -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) { + if (pin == NULL) { + return; + } #if CIRCUITPY_CYW43 if (pin->base.type == &cyw43_pin_type) { reset_pin_number_cyw(pin->number); @@ -127,10 +103,6 @@ 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) { - return claim_pin(pin); -} - void common_hal_mcu_pin_reset_number(uint8_t pin_no) { reset_pin_number(pin_no); } diff --git a/ports/raspberrypi/common-hal/microcontroller/Pin.h b/ports/raspberrypi/common-hal/microcontroller/Pin.h index ce6e33a24a8..fe2191e8f25 100644 --- a/ports/raspberrypi/common-hal/microcontroller/Pin.h +++ b/ports/raspberrypi/common-hal/microcontroller/Pin.h @@ -19,14 +19,15 @@ // A default weak implementation always returns `false`. bool board_reset_pin_number(uint8_t pin_number); -void reset_all_pins(void); +void common_hal_reset_pin(const mcu_pin_obj_t *pin); // 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_number); -void never_reset_pin_number(uint8_t pin_number); void claim_pin(const mcu_pin_obj_t *pin); bool pin_number_is_free(uint8_t pin_number); +uint8_t common_hal_mcu_pin_number(const mcu_pin_obj_t *pin); + #if CIRCUITPY_CYW43 extern bool cyw_ever_init; void reset_pin_number_cyw(uint8_t pin_number); diff --git a/ports/raspberrypi/common-hal/microcontroller/Processor.c b/ports/raspberrypi/common-hal/microcontroller/Processor.c index a3ea890d9af..8d0b31f791d 100644 --- a/ports/raspberrypi/common-hal/microcontroller/Processor.c +++ b/ports/raspberrypi/common-hal/microcontroller/Processor.c @@ -10,9 +10,13 @@ #include "py/mphal.h" #include "py/runtime.h" #include "common-hal/microcontroller/Processor.h" +#include "shared-bindings/microcontroller/__init__.h" #include "shared-bindings/microcontroller/Processor.h" #include "shared-bindings/microcontroller/ResetReason.h" #include "shared-bindings/time/__init__.h" +#if CIRCUITPY_ALARM +#include "common-hal/alarm/__init__.h" +#endif #include "pico/stdlib.h" #include "hardware/adc.h" @@ -20,11 +24,22 @@ #include "hardware/vreg.h" #include "hardware/watchdog.h" -#ifdef PICO_RP2040 +#include "genhdr/flash_info.h" + +#if PICO_RP2350 +#include "hardware/regs/io_qspi.h" +#include "hardware/regs/qmi.h" +#include "hardware/structs/io_qspi.h" +#include "hardware/structs/qmi.h" +#endif + +#if PICO_RP2040 +#include "hardware/regs/ssi.h" #include "hardware/regs/vreg_and_chip_reset.h" +#include "hardware/structs/ssi.h" #include "hardware/structs/vreg_and_chip_reset.h" #endif -#ifdef PICO_RP2350 +#if PICO_RP2350 #include "hardware/regs/powman.h" #include "hardware/structs/powman.h" #endif @@ -50,6 +65,178 @@ uint32_t common_hal_mcu_processor_get_frequency(void) { return clock_get_hz(clk_sys); } +#ifdef CIRCUITPY_PSRAM_CHIP_SELECT +void __no_inline_not_in_flash_func(mcu_processor_update_psram_timing)(uint32_t sys_clk_khz) { + // MAX_SELECT is in units of 64 system clock cycles; PSRAM allows 8 us max CS + // assertion. Use 7.5 us so there is margin at any clk_sys. + uint32_t max_select = (75 * sys_clk_khz) / 640000; + // MIN_DESELECT is in system clock cycles; PSRAM needs 50 ns min CS + // deassertion. Round up so we are never under. + uint32_t min_deselect = (sys_clk_khz + 19999) / 20000; + // PSRAM SCK is clk_sys / CLKDIV and must stay at or below 133 MHz. + // Divisor 1 is not used above 100 MHz because the RXDELAY it needs is + // too late. RXDELAY samples later as the divisor grows, plus one more + // cycle once SCK is above 100 MHz. Same rule as arduino-pico. + uint32_t max_sck_khz = 133000; + #ifdef CIRCUITPY_PSRAM_MAX_SCK_HZ + // Keep a board's lower PSRAM clock limit when the CPU frequency changes. + max_sck_khz = MIN(max_sck_khz, CIRCUITPY_PSRAM_MAX_SCK_HZ / 1000); + #endif + uint32_t clkdiv = (sys_clk_khz + max_sck_khz - 1) / max_sck_khz; + if (clkdiv == 1 && sys_clk_khz > 100000) { + clkdiv = 2; + } + uint32_t rxdelay = clkdiv; + if (sys_clk_khz / clkdiv > 100000) { + rxdelay++; + } + #ifdef CIRCUITPY_PSRAM_MAX_SCK_HZ + // Slower PSRAM clocks can require a delay beyond this three-bit field. + rxdelay = MIN(rxdelay, QMI_M0_TIMING_RXDELAY_BITS >> QMI_M0_TIMING_RXDELAY_LSB); + #endif + + qmi_hw->m[1].timing = + QMI_M0_TIMING_PAGEBREAK_VALUE_1024 << QMI_M0_TIMING_PAGEBREAK_LSB | // Break between pages. + 3 << QMI_M0_TIMING_SELECT_HOLD_LSB | // Delay releasing CS for 3 extra system cycles. + 1 << QMI_M0_TIMING_COOLDOWN_LSB | + rxdelay << QMI_M0_TIMING_RXDELAY_LSB | + max_select << QMI_M0_TIMING_MAX_SELECT_LSB | + min_deselect << QMI_M0_TIMING_MIN_DESELECT_LSB | + clkdiv << QMI_M0_TIMING_CLKDIV_LSB; +} +#endif + +#if PICO_RP2350 +// Saved flash timing for the current system clock: the value of the timing +// register for QMI window 0. QMI is the Quad Memory Interface, which reads the +// flash. A flash erase, program or command leaves stage 2's slow timing in +// place, and mcu_processor_restore_flash_timing() writes this value back. +static uint32_t _flash_timing; + +void __no_inline_not_in_flash_func(mcu_processor_restore_flash_timing)(void) { + // QMI has no busy flag. Instead, wait until the flash chip select pad (SS, + // active low) is deasserted, so the timing doesn't change during a read. + while ((io_qspi_hw->io[1].status & IO_QSPI_GPIO_QSPI_SS_STATUS_OUTTOPAD_BITS) == 0) { + } + qmi_hw->m[0].timing = _flash_timing; + // The new timing applies from the next read. Read once through XIP + // (execute in place) so that it is in use before returning. + (void)*(volatile uint32_t *)XIP_NOCACHE_NOALLOC_BASE; +} + +// Maximum delays inside the RP2350 at VDDIO = 3.3 V, from RP2350 datasheet +// Table 1291 (QMI timing delay). +#define QMI_CLOCK_TO_OUTPUT_PS (2500) +#define QMI_INPUT_TO_SAMPLE_PS (1500) +// Allowance for the board trace between the RP2350 and the flash, each way. +#define FLASH_TRACE_DELAY_PS (500) +// Margin required beyond the flash's output hold time. +#define FLASH_HOLD_MARGIN_PS (500) + +void __no_inline_not_in_flash_func(mcu_processor_update_flash_timing)(uint32_t sys_clk_khz) { + // Choose the flash clock divider (CLKDIV) and sample delay (RXDELAY) from + // the flash's datasheet timing in flash_info.h, assuming worst-case delays. + // + // The flash drives each data bit after a falling clock edge. QMI samples + // the bit (CLKDIV + RXDELAY) half system clocks after that edge. + // Setup: the sample must come after the bit is valid. That is the RP2350 + // output delay, plus the flash's output valid time, plus the + // RP2350 input delay, plus the board trace delay both ways. + // Hold: the sample must come before the flash starts driving the next + // bit. That is one SCK period plus the flash's output hold time, + // less FLASH_HOLD_MARGIN_PS. The RP2350's minimum delays aren't + // specified, so they count as 0. + // + // Use the smallest divider that keeps SCK within the flash's 0xeb rating + // and has a sample delay meeting both checks. Of those sample delays, pick + // the one furthest from failing either check. + const int32_t period_ps = 1000000000 / sys_clk_khz; + const int32_t setup_ps = QMI_CLOCK_TO_OUTPUT_PS + FLASH_MAX_OUTPUT_VALID_PS + + QMI_INPUT_TO_SAMPLE_PS + 2 * FLASH_TRACE_DELAY_PS; + uint32_t max_sck_khz = FLASH_EB_MAX_SCK_KHZ; + #ifdef CIRCUITPY_FLASH_MAX_SCK_HZ + max_sck_khz = MIN(max_sck_khz, CIRCUITPY_FLASH_MAX_SCK_HZ / 1000); + #endif + const uint32_t max_rxdelay = QMI_M0_TIMING_RXDELAY_BITS >> QMI_M0_TIMING_RXDELAY_LSB; + + uint32_t clkdiv = (sys_clk_khz + max_sck_khz - 1) / max_sck_khz; + uint32_t rxdelay = max_rxdelay; + for (; clkdiv <= 255; clkdiv++) { + const int32_t hold_ps = (int32_t)clkdiv * period_ps + FLASH_MIN_OUTPUT_HOLD_PS - FLASH_HOLD_MARGIN_PS; + int32_t best_margin_ps = -1; + for (uint32_t r = 0; r <= max_rxdelay; r++) { + const int32_t sample_ps = (int32_t)(clkdiv + r) * period_ps / 2; + const int32_t margin_ps = MIN(sample_ps - setup_ps, hold_ps - sample_ps); + if (margin_ps > best_margin_ps) { + best_margin_ps = margin_ps; + rxdelay = r; + } + } + if (best_margin_ps >= 0) { + break; + } + } + if (clkdiv > 255) { + // No divider up to 255 passes both checks. That can't happen at a real + // clock speed, but fall back to the slowest timing. + clkdiv = 255; + rxdelay = max_rxdelay; + } + + // COOLDOWN = 1 keeps chip select asserted briefly after a read, so the next + // read from the following address doesn't resend the address. Stage 2 + // sets the same value. + _flash_timing = + 1 << QMI_M0_TIMING_COOLDOWN_LSB | + rxdelay << QMI_M0_TIMING_RXDELAY_LSB | + clkdiv << QMI_M0_TIMING_CLKDIV_LSB; + mcu_processor_restore_flash_timing(); +} +#endif + +#if PICO_RP2040 +// Highest RP2040 flash clock. The RP2040 datasheet gives no QSPI pad delays, +// so this can't be worked out like the RP2350 timing. 62.5 MHz (divider 2 at +// 125 MHz) is the pico-sdk default for the Pico. +// +// On a Feather RP2040, a sample delay of 1 read correctly at every divider and +// every system clock from 48 to 250 MHz. At a 75 MHz flash clock (divider 2 at +// 150 MHz), no other sample delay worked, so this limit keeps some margin. +#define RP2040_FLASH_MAX_SCK_KHZ (62500) + +// SSI clock divider for the current system clock. The SSI (synchronous serial +// interface) reads the flash. A flash erase, program or command reruns stage +// 2, which sets divider 4, and mcu_processor_restore_flash_timing() writes +// this value back. Until the first update, it is stage 2's value. +static uint32_t _flash_clock_divider = 4; + +void __no_inline_not_in_flash_func(mcu_processor_restore_flash_timing)(void) { + // The divider can change only while the SSI is disabled, which also stops + // XIP (execute in place). So this runs from RAM. + while (ssi_hw->sr & SSI_SR_BUSY_BITS) { + } + ssi_hw->ssienr = 0; + ssi_hw->baudr = _flash_clock_divider; + // Sample read data one system clock late, as stage 2 does. + ssi_hw->rx_sample_dly = 1; + ssi_hw->ssienr = 1; +} + +void mcu_processor_update_flash_timing(uint32_t sys_clk_khz) { + // Use the smallest divider that keeps the flash clock within the flash's + // 0xeb rating and RP2040_FLASH_MAX_SCK_KHZ. The SSI supports only even + // dividers, 2 or more. + uint32_t max_sck_khz = MIN(FLASH_EB_MAX_SCK_KHZ, RP2040_FLASH_MAX_SCK_KHZ); + #ifdef CIRCUITPY_FLASH_MAX_SCK_HZ + max_sck_khz = MIN(max_sck_khz, CIRCUITPY_FLASH_MAX_SCK_HZ / 1000); + #endif + uint32_t divider = (sys_clk_khz + max_sck_khz - 1) / max_sck_khz; + divider += divider & 1; + _flash_clock_divider = MAX(divider, 2); + mcu_processor_restore_flash_timing(); +} +#endif + void common_hal_mcu_processor_set_frequency(mcu_processor_obj_t *self, uint32_t frequency) { uint vco, postdiv1, postdiv2; uint32_t freq_khz = frequency / 1000; @@ -65,10 +252,30 @@ void common_hal_mcu_processor_set_frequency(mcu_processor_obj_t *self, uint32_t } else if (freq_khz > 133000) { voltage = VREG_VOLTAGE_1_20; } - vreg_set_voltage(voltage); - // Wait for a stable voltage - common_hal_time_delay_ms(10); + // Raise the voltage before raising the clock, and lower it after lowering + // the clock. + enum vreg_voltage current_voltage = vreg_get_voltage(); + if (voltage > current_voltage) { + vreg_set_voltage(voltage); + // Wait for a stable voltage + common_hal_time_delay_ms(10); + } + + // Prevent interrupt handlers from accessing flash or PSRAM until their + // timing matches the new system clock. + common_hal_mcu_disable_interrupts(); + // While the clock changes, use the flash timing for the faster of the old + // and new clocks. That keeps the flash within its timing limits at both. + mcu_processor_update_flash_timing(MAX(freq_khz, clock_get_hz(clk_sys) / 1000)); set_sys_clock_khz(freq_khz, false); + #ifdef CIRCUITPY_PSRAM_CHIP_SELECT + mcu_processor_update_psram_timing(freq_khz); + #endif + mcu_processor_update_flash_timing(freq_khz); + common_hal_mcu_enable_interrupts(); + if (voltage < current_voltage) { + vreg_set_voltage(voltage); + } } void common_hal_mcu_processor_get_uid(uint8_t raw_id[]) { @@ -78,54 +285,61 @@ void common_hal_mcu_processor_get_uid(uint8_t raw_id[]) { } mcu_reset_reason_t common_hal_mcu_processor_get_reset_reason(void) { - mcu_reset_reason_t reason = RESET_REASON_UNKNOWN; + mcu_reset_reason_t reason = MCU_RESET_REASON_UNKNOWN; - #ifdef PICO_RP2040 + #if PICO_RP2040 uint32_t chip_reset_reg = vreg_and_chip_reset_hw->chip_reset; if (chip_reset_reg & VREG_AND_CHIP_RESET_CHIP_RESET_HAD_PSM_RESTART_BITS) { - reason = RESET_REASON_RESCUE_DEBUG; + reason = MCU_RESET_REASON_RESCUE_DEBUG; } if (chip_reset_reg & VREG_AND_CHIP_RESET_CHIP_RESET_HAD_RUN_BITS) { - reason = RESET_REASON_RESET_PIN; + reason = MCU_RESET_REASON_RESET_PIN; } if (chip_reset_reg & VREG_AND_CHIP_RESET_CHIP_RESET_HAD_POR_BITS) { // NOTE: This register is also used for brownout, but there is no way to differentiate between power on and brown out - reason = RESET_REASON_POWER_ON; + reason = MCU_RESET_REASON_POWER_ON; } #endif - #ifdef PICO_RP2350 + #if PICO_RP2350 uint32_t chip_reset_reg = powman_hw->chip_reset; if (chip_reset_reg & POWMAN_CHIP_RESET_HAD_RESCUE_BITS) { - reason = RESET_REASON_RESCUE_DEBUG; + reason = MCU_RESET_REASON_RESCUE_DEBUG; } if (chip_reset_reg & POWMAN_CHIP_RESET_HAD_RUN_LOW_BITS) { - reason = RESET_REASON_RESET_PIN; + reason = MCU_RESET_REASON_RESET_PIN; } if (chip_reset_reg & POWMAN_CHIP_RESET_HAD_BOR_BITS) { - reason = RESET_REASON_BROWNOUT; + reason = MCU_RESET_REASON_BROWNOUT; } if (chip_reset_reg & POWMAN_CHIP_RESET_HAD_POR_BITS) { - reason = RESET_REASON_POWER_ON; + reason = MCU_RESET_REASON_POWER_ON; } + + #if CIRCUITPY_ALARM + // The chip reset flags above stay set through a powman wake, so check it last. + if (alarm_woke_from_powman()) { + reason = MCU_RESET_REASON_DEEP_SLEEP_ALARM; + } + #endif #endif // Check watchdog after chip reset since watchdog doesn't clear chip_reset, while chip_reset clears the watchdog // The watchdog is used for software reboots such as resetting after copying a UF2 via the bootloader. if (watchdog_caused_reboot()) { - reason = RESET_REASON_SOFTWARE; + reason = MCU_RESET_REASON_SOFTWARE; } // Actual watchdog usage will set a special value that this function detects. if (watchdog_enable_caused_reboot()) { - reason = RESET_REASON_WATCHDOG; + reason = MCU_RESET_REASON_WATCHDOG; } return reason; diff --git a/ports/raspberrypi/common-hal/microcontroller/Processor.h b/ports/raspberrypi/common-hal/microcontroller/Processor.h index df1e1cf2333..c342a0ec3a0 100644 --- a/ports/raspberrypi/common-hal/microcontroller/Processor.h +++ b/ports/raspberrypi/common-hal/microcontroller/Processor.h @@ -16,3 +16,27 @@ typedef struct { mp_obj_base_t base; // Stores no state currently. } mcu_processor_obj_t; + +#ifdef CIRCUITPY_PSRAM_CHIP_SELECT +void mcu_processor_update_psram_timing(uint32_t sys_clk_khz); +#endif + +// Set the flash clock divider and sample delay for a system clock of +// sys_clk_khz, and save them for mcu_processor_restore_flash_timing(). Returns +// nothing. +// +// The flash clock is limited by the flash's datasheet timing (flash_info.h, +// generated from data/nvm.toml). A board can lower it further with +// CIRCUITPY_FLASH_MAX_SCK_HZ. On RP2350, the sample delay is also worked out +// from the datasheet timing. On RP2040, the flash clock is also limited to +// 62.5 MHz, and the sample delay is always 1. +// +// Call with interrupts disabled and no flash operation in progress. +void mcu_processor_update_flash_timing(uint32_t sys_clk_khz); + +// Put back the flash timing last set by mcu_processor_update_flash_timing(). +// Call after each flash erase, program or command (such as reading the flash +// ID). Those leave stage 2's slow timing in place. Returns nothing. +// +// Runs from RAM. Call with interrupts disabled. +void mcu_processor_restore_flash_timing(void); diff --git a/ports/raspberrypi/common-hal/microcontroller/__init__.c b/ports/raspberrypi/common-hal/microcontroller/__init__.c index e287e551710..9021778157b 100644 --- a/ports/raspberrypi/common-hal/microcontroller/__init__.c +++ b/ports/raspberrypi/common-hal/microcontroller/__init__.c @@ -25,12 +25,29 @@ #include "hardware/watchdog.h" #include "hardware/irq.h" +// DMA interrupt (DMA_IRQ_n) allocation for this port: +// +// DMA_IRQ_0 Shared. audiocore (audio_dma.c), rp2pio (StateMachine.c) and, +// async_spi (common-hal/async_spi/SPI.c) each register a shared +// handler with irq_add_shared_handler() and +// service only their own DMA channels. Any new code that needs a +// DMA completion interrupt should do the same: add a shared handler +// on DMA_IRQ_0, check dma_hw->ints0, and acknowledge only its own +// channels. Runs at the default IRQ priority and is masked during +// flash writes (see common_hal_mcu_disable_interrupts below). +// DMA_IRQ_1 Exclusive to picodvi (Framebuffer_RP2040.c / Framebuffer_RP2350.c), +// registered with irq_set_exclusive_handler() at the highest +// priority. On RP2350 it is deliberately kept enabled during flash +// writes via BASEPRI (see below) so the display keeps refreshing. +// DMA_IRQ_2 RP2350 only; currently unused / free. +// DMA_IRQ_3 RP2350 only; currently unused / free. + void common_hal_mcu_delay_us(uint32_t delay) { mp_hal_delay_us(delay); } volatile uint32_t nesting_count = 0; -#ifdef PICO_RP2040 +#if PICO_RP2040 void common_hal_mcu_disable_interrupts(void) { // We don't use save_and_disable_interrupts() from the sdk because we don't want to worry about PRIMASK. // This is what we do on the SAMD21 via CMSIS. diff --git a/ports/raspberrypi/common-hal/os/__init__.c b/ports/raspberrypi/common-hal/os/__init__.c index 616bb8d8c79..d2a8da4caef 100644 --- a/ports/raspberrypi/common-hal/os/__init__.c +++ b/ports/raspberrypi/common-hal/os/__init__.c @@ -18,35 +18,159 @@ #include +#ifdef HAS_RP2350_TRNG +#include "hardware/structs/trng.h" +#include "hardware/sync.h" +#endif + // 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. +// essentially fully random. +// +// This works by seeding `random_state` with entropy from hardware sources +// (SHA-256 as the conditioning function), then using that state as a counter +// input (SHA-256 as a CSPRNG), re-seeding at least every 256 blocks (8kB). // -// 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). +// On RP2350, entropy comes from both the dedicated TRNG peripheral and the +// ROSC. On RP2040, the ROSC is the only available source. // // 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, +// ROSC_SAFETY_MARGIN. (it does detect "unusual" results from time to time, // as it will with any RNG) -#define RANDOM_SAFETY_MARGIN (4) + +// Number of ROSC collection rounds on RP2040. Each round feeds +// SHA256_BLOCK_SIZE bytes into the hash; we do 2*N rounds so the +// raw-to-output ratio satisfies 800-90B's 2:1 minimum. +#define ROSC_SAFETY_MARGIN (4) static BYTE random_state[SHA256_BLOCK_SIZE]; + +// Collect `count` bytes from the ROSC, one bit per read. +static void rosc_random_bytes(BYTE *buf, size_t count) { + for (size_t i = 0; i < count; i++) { + buf[i] = rosc_hw->randombit & 1; + for (int k = 0; k < 8; k++) { + buf[i] = (buf[i] << 1) ^ (rosc_hw->randombit & 1); + } + } +} + +#ifdef HAS_RP2350_TRNG + +// TRNG_DEBUG_CONTROL bypass bits: +// +// bit 1 VNC_BYPASS Von Neumann corrector +// bit 2 TRNG_CRNGT_BYPASS Continuous Random Number Generator Test +// bit 3 AUTO_CORRELATE_BYPASS Autocorrelation test +// +// We bypass Von Neumann and autocorrelation but keep CRNGT. +// +// Von Neumann (bypassed): ~4x throughput cost for bias removal. +// Redundant here because SHA-256 conditioning already handles +// biased input -- that's what the 2:1 oversampling ratio is for. +// +// Autocorrelation (bypassed): has a non-trivial false-positive rate +// at high sampling speeds and halts the TRNG until SW reset on +// failure. SHA-256 is not bothered by correlated input. ARM's own +// TZ-TRNG 90B reference configuration also bypasses it (0x0A). +// +// CRNGT (kept): compares consecutive 192-bit EHR outputs. Flags if +// identical -- false-positive rate 2^-192, throughput cost zero. +// This is our early warning for a stuck oscillator or a successful +// injection lock to a fixed state. +#define TRNG_BYPASS_BITS \ + (TRNG_TRNG_DEBUG_CONTROL_VNC_BYPASS_BITS | \ + TRNG_TRNG_DEBUG_CONTROL_AUTO_CORRELATE_BYPASS_BITS) + +// Collect 192 raw bits (6 x 32-bit words) from the TRNG. +// Returns false on CRNGT failure (consecutive identical EHR outputs). +// +// Holds PICO_SPINLOCK_ID_RAND (the SDK's lock for this peripheral) +// with interrupts disabled for the duration of the collection, which +// takes ~192 ROSC cycles (~24us at 8MHz). +static bool trng_collect_192(uint32_t out[6]) { + spin_lock_t *lock = spin_lock_instance(PICO_SPINLOCK_ID_RAND); + uint32_t save = spin_lock_blocking(lock); + + trng_hw->trng_debug_control = TRNG_BYPASS_BITS; + // One rng_clk cycle between samples. The SDK uses 0 here, but it + // also sets debug_control = -1u (full bypass). The behavior of + // sample_cnt1 = 0 with health tests still active is undocumented, + // so we use 1 to be safe. + trng_hw->sample_cnt1 = 1; + trng_hw->rnd_source_enable = 1; + trng_hw->rng_icr = 0xFFFFFFFF; + + while (trng_hw->trng_busy) { + } + + if (trng_hw->rng_isr & TRNG_RNG_ISR_CRNGT_ERR_BITS) { + // Drain ehr_data so the hardware starts a fresh collection. + // (Reading the last word clears the valid flag.) + for (int i = 0; i < 6; i++) { + (void)trng_hw->ehr_data[i]; + } + trng_hw->rng_icr = TRNG_RNG_ISR_CRNGT_ERR_BITS; + spin_unlock(lock, save); + return false; + } + + for (int i = 0; i < 6; i++) { + out[i] = trng_hw->ehr_data[i]; + } + + // Switch the inverter chain length for the next collection, using + // bits from the sample we just read. Only bits [1:0] matter -- they + // select one of four chain lengths, changing the ROSC frequency. + // This is borrowed from pico_rand's injection-locking countermeasure. + // (The SDK uses its PRNG state here instead of raw output; either + // works since the real defense is SHA-256 conditioning, not this.) + trng_hw->trng_config = out[0]; + + spin_unlock(lock, save); + return true; +} + +#endif // HAS_RP2350_TRNG + 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); + + #ifdef HAS_RP2350_TRNG + // 384 bits from TRNG + 384 bits from ROSC = 768 bits into the hash, + // giving a 3:1 ratio over the 256-bit output (800-90B wants >= 2:1). + // Two independent sources so a failure in one doesn't zero the input. + + // TRNG: 2 x 192 bits. + for (int i = 0; i < 2; i++) { + uint32_t trng_buf[6] = {0}; + for (int attempt = 0; attempt < 3; attempt++) { + if (trng_collect_192(trng_buf)) { + break; } + // CRNGT failure. If all 3 retries fail, trng_buf stays zeroed + // and we rely entirely on the ROSC contribution below. } + sha256_update(&context, (const BYTE *)trng_buf, sizeof(trng_buf)); + } + + // ROSC: 2 x 24 bytes = 384 bits. + for (int i = 0; i < 2; i++) { + BYTE rosc_buf[24]; + rosc_random_bytes(rosc_buf, sizeof(rosc_buf)); + sha256_update(&context, rosc_buf, sizeof(rosc_buf)); + } + #else + // RP2040: ROSC is the only entropy source. + for (int i = 0; i < 2 * ROSC_SAFETY_MARGIN; i++) { + rosc_random_bytes(out, SHA256_BLOCK_SIZE); sha256_update(&context, out, SHA256_BLOCK_SIZE); } + #endif + sha256_final(&context, out); } @@ -61,10 +185,11 @@ static void get_random_bits(BYTE out[SHA256_BLOCK_SIZE]) { } bool common_hal_os_urandom(uint8_t *buffer, mp_uint_t length) { -#define ROSC_POWER_SAVE (1) // assume ROSC is not necessarily active all the time + #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); + rosc_hw->ctrl = (old_rosc_ctrl & ~ROSC_CTRL_ENABLE_BITS) + | (ROSC_CTRL_ENABLE_VALUE_ENABLE << ROSC_CTRL_ENABLE_LSB); #endif while (length) { size_t n = MIN(length, SHA256_BLOCK_SIZE); diff --git a/ports/raspberrypi/common-hal/paralleldisplaybus/ParallelBus.c b/ports/raspberrypi/common-hal/paralleldisplaybus/ParallelBus.c index 517d960b765..8e8f9a3f0c1 100644 --- a/ports/raspberrypi/common-hal/paralleldisplaybus/ParallelBus.c +++ b/ports/raspberrypi/common-hal/paralleldisplaybus/ParallelBus.c @@ -52,7 +52,6 @@ void common_hal_paralleldisplaybus_parallelbus_construct(paralleldisplaybus_para 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); - never_reset_pin_number(read->number); } self->data0_pin = data_pin; @@ -63,17 +62,9 @@ void common_hal_paralleldisplaybus_parallelbus_construct(paralleldisplaybus_para 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_paralleldisplaybus_parallelbus_reset(self); } - never_reset_pin_number(command->number); - never_reset_pin_number(chip_select->number); - never_reset_pin_number(write_pin); - 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, MP_ARRAY_SIZE(parallel_program), frequency * 2, // frequency multiplied by 2 as 2 PIO instructions @@ -96,7 +87,6 @@ void common_hal_paralleldisplaybus_parallelbus_construct(paralleldisplaybus_para PIO_FIFO_TYPE_DEFAULT, PIO_MOV_STATUS_DEFAULT, PIO_MOV_N_DEFAULT); - common_hal_rp2pio_statemachine_never_reset(&self->state_machine); } void common_hal_paralleldisplaybus_parallelbus_deinit(paralleldisplaybus_parallelbus_obj_t *self) { diff --git a/ports/raspberrypi/common-hal/picodvi/AudioOut.c b/ports/raspberrypi/common-hal/picodvi/AudioOut.c new file mode 100644 index 00000000000..117f3d68b1c --- /dev/null +++ b/ports/raspberrypi/common-hal/picodvi/AudioOut.c @@ -0,0 +1,979 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// 32, 44.1 or 48 kHz stereo DVI audio for the RP2350 picodvi Framebuffer. +// No interrupt-time allocation, sample conversion, packet encoding, or Python callbacks. + +#include + +#include "py/gc.h" +#include "py/runtime.h" + +#include "bindings/picodvi/AudioOut.h" +#include "common-hal/picodvi/dvi_audio_packet.h" +#include "hardware/clocks.h" +#include "hardware/dma.h" +#include "hardware/sync.h" +#include "pico/stdlib.h" +#include "pico/time.h" +#include "shared-module/audiocore/__init__.h" +#include "shared-bindings/supervisor/Runtime.h" +#include "supervisor/background_callback.h" +#include "supervisor/port.h" + +typedef struct { + uint32_t sample_rate; + // The usual ACR N, for when no N gives an exact CTS. + uint32_t usual_n; +} dvi_audio_rate_t; + +// The basic audio rates every DVI sink takes. +static const dvi_audio_rate_t dvi_audio_rates[] = { + { 32000, 4096 }, + { 44100, 6272 }, + { 48000, 6144 }, +}; +#define DVI_AUDIO_RATE_COUNT MP_ARRAY_SIZE(dvi_audio_rates) +#define DVI_AUDIO_H_TOTAL (MODE_640_H_FRONT_PORCH + MODE_640_H_SYNC_WIDTH + MODE_640_H_BACK_PORCH + MODE_640_H_ACTIVE_PIXELS) +// Lines per frame that carry a data island. At the usual 25 MHz pixel clock +// and 48 kHz a 625 line frame needs 240 sample packets, 20 ACR packets and 2 +// InfoFrames. +#define DVI_AUDIO_SLOTS 280 +// Buffers for encoded sample packets. Other packets never change, so their +// islands point at fixed copies. 160 hold about 13 ms of 48 kHz audio. +#define DVI_AUDIO_POOL 160 +// Packet words of an island, without its two guard band words at each end. +#define DVI_AUDIO_SLOT_WORDS (HSTX_DATA_ISLAND_WORDS - 4) +// The refill never writes a slot this close ahead of the one DMA reads. +#define DVI_AUDIO_MARGIN 4 +// Nor more than this far ahead, so play() starts within about 15 ms. +#define DVI_AUDIO_AHEAD (DVI_AUDIO_SLOTS * 3 / 4) +// While a sample is waiting for data, silence is only written this close +// ahead of DMA. +#define DVI_AUDIO_LOW_WATER (DVI_AUDIO_SLOTS / 4) +// The sample pool holds about 13 ms, less than one 20 ms frame, so a timer +// queues the refill this often as well as once per frame. +#define DVI_AUDIO_REFILL_US 2500 +#define DVI_AUDIO_PREFIX_WORDS 9 +#define DVI_AUDIO_SUFFIX_BLANK_WORDS 9 +#define DVI_AUDIO_SUFFIX_ACTIVE_WORDS 15 + +typedef uint32_t dvi_audio_island_t[DVI_AUDIO_SLOT_WORDS]; + +typedef struct dvi_audio_state { + // One fixed command list. Each island line is three transfers: a prefix + // up to and including the leading guard band, the island, and a suffix + // from the trailing guard band on. Once DMA has read a slot, the refill + // points its island at the packet for the next frame. + uint32_t *commands; + dvi_audio_island_t *pool; + size_t command_size; + repeating_timer_t timer; + bool timer_running; + // Frames started on the audio command list, counted by the frame + // interrupt. + volatile uint32_t frames; + // Set to go back to video only at the next frame, then acknowledged by + // the frame interrupt once nothing reads this state any more. + volatile bool detach; + volatile bool detached; + // The next slot to write, counted from the first audio frame, and its + // index in the frame. + uint64_t write_position; + size_t write_slot; + // The last read position found, to search on from. + uint32_t read_frames; + size_t read_slot; + // Pool buffers are used in order. Each remembers the slot it was + // written for, and is free again once DMA has read that slot. + uint64_t pool_position[DVI_AUDIO_POOL]; + size_t pool_head; + size_t pool_tail; + size_t pool_count; + uint32_t pixel_clock; + // The rate being sent, and the rate play() asked for, which takes over + // from the next slot written. Indexes into dvi_audio_rates. + size_t rate_index; + size_t next_rate_index; + // ACR packets per second at each rate, 128 * fs / N. + uint32_t acr_rate[DVI_AUDIO_RATE_COUNT]; + // Sample and ACR timing, carried from slot to slot. + uint64_t sample_phase; + uint64_t acr_phase; + int channel_frame; + // Idle slots written in a row, the timing at the last idle slot 0, and + // whether the slots hold a repeating idle frame that needs no writes. + size_t idle_run; + uint64_t idle_sample_phase; + uint64_t idle_acr_phase; + bool idle_steady; + // Command list entry of each slot's island, its line, and the sample + // frames of the playing sample it holds. + uint16_t slot_entry[DVI_AUDIO_SLOTS]; + uint16_t slot_line[DVI_AUDIO_SLOTS]; + uint8_t slot_samples[DVI_AUDIO_SLOTS]; + // Packets that never change, for blanking [0] and vsync [1] lines. + dvi_audio_island_t acr[DVI_AUDIO_RATE_COUNT][2]; + dvi_audio_island_t null_packet[2]; + dvi_audio_island_t silence[2]; + dvi_audio_island_t audio_infoframe[DVI_AUDIO_RATE_COUNT]; + dvi_audio_island_t avi_infoframe; + uint32_t prefix[2][DVI_AUDIO_PREFIX_WORDS]; + uint32_t suffix_blank[2][DVI_AUDIO_SUFFIX_BLANK_WORDS]; + uint32_t suffix_active[DVI_AUDIO_SUFFIX_ACTIVE_WORDS]; +} dvi_audio_state_t; + +// Static so it can never be freed while it is queued. +static background_callback_t dvi_audio_refill_callback; + +#if defined(DEFAULT_DVI_BUS_CLK_DP) +// supervisor.runtime.audio. Static so it outlives the VM, like the boot display. +picodvi_audioout_obj_t picodvi_board_audioout = { + .base = { .type = &mp_type_NoneType }, +}; + +static bool is_board_audioout(const picodvi_audioout_obj_t *self) { + return self == &picodvi_board_audioout; +} +#else +static bool is_board_audioout(const picodvi_audioout_obj_t *self) { + (void)self; + return false; +} +#endif + +// Active line with the video preamble and guard band that audio mode needs. +static uint32_t dvi_audio_vactive_line640[] = { + HSTX_CMD_RAW_REPEAT | MODE_640_H_FRONT_PORCH, + SYNC_V1_H1, + HSTX_CMD_NOP, + HSTX_CMD_RAW_REPEAT | MODE_640_H_SYNC_WIDTH, + SYNC_V1_H0, + HSTX_CMD_NOP, + HSTX_CMD_RAW_REPEAT | (MODE_640_H_BACK_PORCH - 10), + SYNC_V1_H1, + HSTX_CMD_NOP, + HSTX_CMD_RAW_REPEAT | 8, + TMDS_CTRL_11 | (TMDS_CTRL_01 << 10) | (TMDS_CTRL_00 << 20), + HSTX_CMD_NOP, + HSTX_CMD_RAW_REPEAT | 2, + 0x2ccu | (0x133u << 10) | (0x2ccu << 20), + HSTX_CMD_TMDS | MODE_640_H_ACTIVE_PIXELS +}; + +// Fills the line pieces around a slot. The island sits in the horizontal +// sync pulse, after an 8 character data island preamble. +static void dvi_audio_init_line_pieces(dvi_audio_state_t *audio) { + for (int vsync = 0; vsync < 2; vsync++) { + uint32_t h0 = vsync ? SYNC_V0_H0 : SYNC_V1_H0; + uint32_t h1 = vsync ? SYNC_V0_H1 : SYNC_V1_H1; + // The guard band only depends on the sync levels. + hstx_packet_t packet; + hstx_data_island_t island; + hstx_packet_init(&packet); + hstx_encode_data_island(&island, &packet, vsync, true); + uint32_t guard = island.words[0]; + + uint32_t *p = audio->prefix[vsync]; + *p++ = HSTX_CMD_RAW_REPEAT | MODE_640_H_FRONT_PORCH; + *p++ = h1; + *p++ = HSTX_CMD_NOP; + *p++ = HSTX_CMD_RAW_REPEAT | 8; + *p++ = (h0 & 0x3ff) | (TMDS_CTRL_01 << 10) | (TMDS_CTRL_01 << 20); + *p++ = HSTX_CMD_NOP; + *p++ = HSTX_CMD_RAW | HSTX_DATA_ISLAND_WORDS; + *p++ = guard; + *p++ = guard; + + uint32_t *s = audio->suffix_blank[vsync]; + *s++ = guard; + *s++ = guard; + *s++ = HSTX_CMD_NOP; + *s++ = HSTX_CMD_RAW_REPEAT | (MODE_640_H_SYNC_WIDTH - 8 - HSTX_DATA_ISLAND_WORDS); + *s++ = h0; + *s++ = HSTX_CMD_NOP; + *s++ = HSTX_CMD_RAW_REPEAT | (MODE_640_H_BACK_PORCH + MODE_640_H_ACTIVE_PIXELS); + *s++ = h1; + *s++ = HSTX_CMD_NOP; + + if (!vsync) { + // Active lines are never in vsync. + memcpy(audio->suffix_active, audio->suffix_blank[0], 6 * sizeof(uint32_t)); + s = &audio->suffix_active[6]; + *s++ = HSTX_CMD_RAW_REPEAT | (MODE_640_H_BACK_PORCH - 10); + *s++ = h1; + *s++ = HSTX_CMD_NOP; + *s++ = HSTX_CMD_RAW_REPEAT | 8; + *s++ = (h1 & 0x3ff) | (TMDS_CTRL_01 << 10) | (TMDS_CTRL_00 << 20); + *s++ = HSTX_CMD_NOP; + *s++ = HSTX_CMD_RAW_REPEAT | 2; + *s++ = 0x2ccu | (0x133u << 10) | (0x2ccu << 20); + *s++ = HSTX_CMD_TMDS | MODE_640_H_ACTIVE_PIXELS; + } + } +} + +static void dvi_audio_encode(uint32_t *out, const hstx_packet_t *packet, bool vsync) { + hstx_data_island_t island; + hstx_encode_data_island(&island, packet, vsync, true); + memcpy(out, &island.words[2], sizeof(dvi_audio_island_t)); +} + +static bool dvi_audio_slot_vsync(const dvi_audio_state_t *audio, size_t slot) { + return audio->slot_line[slot] < MODE_640_V_SYNC_WIDTH; +} + +// The command list word holding the address of a slot's island. +static uint32_t *dvi_audio_slot_island(dvi_audio_state_t *audio, size_t slot) { + return &audio->commands[(audio->slot_entry[slot] + 1) * audio->command_size - 1]; +} + +// Pick N so that every frame has the same whole number of ACR packets, and +// CTS is exact. Then a frame of silence repeats exactly and needs no +// rewriting. N may be anything from 128 * fs / 1500 to 128 * fs / 300. +// If no N fits, use the usual N for the rate and round CTS. +static uint32_t dvi_audio_find_n(uint32_t pixel_clock, const dvi_audio_rate_t *rate_info) { + const uint64_t frame_pixels = (uint64_t)MODE_640_V_TOTAL_LINES * DVI_AUDIO_H_TOTAL; + const uint32_t n_times_rate = 128 * rate_info->sample_rate; + uint32_t per_frame = (1000 * frame_pixels + pixel_clock / 2) / pixel_clock; + for (uint32_t k = per_frame - 1; k <= per_frame + 1; k++) { + // ACR packets per second when each frame has k. + uint64_t rate = (uint64_t)k * pixel_clock; + if (k == 0 || rate % frame_pixels != 0) { + continue; + } + rate /= frame_pixels; + if (n_times_rate % rate != 0) { + continue; + } + uint32_t candidate = n_times_rate / rate; + if (candidate >= n_times_rate / 1500 && candidate <= n_times_rate / 300 && + ((uint64_t)pixel_clock * candidate) % n_times_rate == 0) { + return candidate; + } + } + return rate_info->usual_n; +} + +static void dvi_audio_init_packets(dvi_audio_state_t *audio) { + hstx_packet_t packet; + for (size_t rate_index = 0; rate_index < DVI_AUDIO_RATE_COUNT; rate_index++) { + const dvi_audio_rate_t *rate_info = &dvi_audio_rates[rate_index]; + const uint32_t n_times_rate = 128 * rate_info->sample_rate; + uint32_t n = dvi_audio_find_n(audio->pixel_clock, rate_info); + audio->acr_rate[rate_index] = n_times_rate / n; + uint32_t cts = ((uint64_t)audio->pixel_clock * n + n_times_rate / 2) / n_times_rate; + hstx_packet_set_acr(&packet, n, cts); + for (int vsync = 0; vsync < 2; vsync++) { + dvi_audio_encode(audio->acr[rate_index][vsync], &packet, vsync); + } + // The first two slots of every frame carry the InfoFrames. + hstx_packet_set_audio_infoframe(&packet, rate_info->sample_rate, 2, 16); + dvi_audio_encode(audio->audio_infoframe[rate_index], &packet, dvi_audio_slot_vsync(audio, 0)); + } + // 48 kHz until play() asks for another rate. + audio->rate_index = DVI_AUDIO_RATE_COUNT - 1; + audio->next_rate_index = audio->rate_index; + hstx_packet_init(&packet); + for (int vsync = 0; vsync < 2; vsync++) { + dvi_audio_encode(audio->null_packet[vsync], &packet, vsync); + } + // Frame position 4 never sets the block start flag, and frames 4 to 7 + // carry no channel status bits, so silence is the same at every rate. + audio_sample_t silence[4] = {{0}}; + hstx_packet_set_audio_samples(&packet, silence, 4, 4, dvi_audio_rates[DVI_AUDIO_RATE_COUNT - 1].sample_rate); + for (int vsync = 0; vsync < 2; vsync++) { + dvi_audio_encode(audio->silence[vsync], &packet, vsync); + } + // Unspecified VIC: preserve CircuitPython's existing 625-line timing. + hstx_packet_set_avi_infoframe(&packet, 0, 0); + dvi_audio_encode(audio->avi_infoframe, &packet, dvi_audio_slot_vsync(audio, 1)); +} + +// Builds the audio command list from the video one. Lines without a slot +// keep their video transfers, except that active lines get the video +// preamble and guard band that audio mode needs. Every island starts as a +// null packet. +static void dvi_audio_build_commands(dvi_audio_state_t *audio, const picodvi_framebuffer_obj_t *self) { + const size_t size = audio->command_size; + // Word offset of the transfer count and read address within an entry. + const size_t data = size - 2; + const size_t active_start = MODE_640_V_SYNC_WIDTH + MODE_640_V_BACK_PORCH; + const size_t active_end = active_start + MODE_640_V_ACTIVE_LINES; + const uint32_t *video = self->dma_commands; + uint32_t *out = audio->commands; + size_t slot = 0; + for (size_t line = 0; line < MODE_640_V_TOTAL_LINES; line++) { + bool active = line >= active_start && line < active_end; + bool vsync = line < MODE_640_V_SYNC_WIDTH; + // video points at this line's first entry, the whole line when + // blanking or the part before the pixels when active. + if (slot < DVI_AUDIO_SLOTS && audio->slot_line[slot] == line) { + const uint32_t *pieces[3] = { + audio->prefix[vsync], audio->null_packet[vsync], + active ? audio->suffix_active : audio->suffix_blank[vsync], + }; + const uint32_t lengths[3] = { + DVI_AUDIO_PREFIX_WORDS, DVI_AUDIO_SLOT_WORDS, + active ? DVI_AUDIO_SUFFIX_ACTIVE_WORDS : DVI_AUDIO_SUFFIX_BLANK_WORDS, + }; + for (int i = 0; i < 3; i++) { + if (i == 1) { + audio->slot_entry[slot] = (out - audio->commands) / size; + } + memcpy(out, video, data * sizeof(uint32_t)); + out[data] = lengths[i]; + out[data + 1] = (uintptr_t)pieces[i]; + out += size; + } + slot++; + } else { + memcpy(out, video, size * sizeof(uint32_t)); + if (active) { + out[data] = MP_ARRAY_SIZE(dvi_audio_vactive_line640); + out[data + 1] = (uintptr_t)dvi_audio_vactive_line640; + } + out += size; + } + video += size; + if (active) { + // The pixel transfer. + memcpy(out, video, size * sizeof(uint32_t)); + out += size; + video += size; + } + } + // The empty last entry that raises the frame interrupt. + memcpy(out, video, size * sizeof(uint32_t)); +} + +// Command list words for the framebuffer's video list plus two more +// transfers on each slot line. +static size_t dvi_audio_commands_len(const picodvi_framebuffer_obj_t *self, size_t command_size) { + return self->dma_commands_len + DVI_AUDIO_SLOTS * 2 * command_size; +} + +static void dvi_audio_free_state(dvi_audio_state_t *audio) { + if (audio->timer_running) { + cancel_repeating_timer(&audio->timer); + } + if (audio->commands) { + port_free(audio->commands); + } + if (audio->pool) { + port_free(audio->pool); + } + port_free(audio); +} + +// Frees the audio state. The caller makes sure DMA no longer reads it. +void picodvi_audioout_framebuffer_deinit(picodvi_framebuffer_obj_t *self) { + // An AudioOut lives as long as its framebuffer. + if (self->audioout != MP_OBJ_NULL) { + picodvi_audioout_obj_t *audioout = MP_OBJ_TO_PTR(self->audioout); + audioout->sample = MP_OBJ_NULL; + audioout->framebuffer = NULL; + self->audioout = MP_OBJ_NULL; + if (is_board_audioout(audioout)) { + // supervisor.runtime.audio goes back to None, as the display does. + audioout->base.type = &mp_type_NoneType; + } + } + dvi_audio_state_t *audio = self->dvi_audio; + if (!audio) { + return; + } + self->dvi_audio = NULL; + dvi_audio_free_state(audio); +} + +// The first slot DMA has not finished reading, counted from the first audio +// frame. Before the first audio frame starts, nothing has been read. +static uint64_t dvi_audio_read_position(dvi_audio_state_t *audio, const picodvi_framebuffer_obj_t *self) { + uint32_t frames; + uintptr_t read_addr; + do { + frames = audio->frames; + read_addr = dma_hw->ch[self->dma_command_channel].read_addr; + } while (frames != audio->frames); + if (frames == 0) { + return 0; + } + // Entries the command channel has loaded. The last one may still be + // sending. + size_t loaded = (read_addr - (uintptr_t)audio->commands) / (audio->command_size * sizeof(uint32_t)); + // Count the slots whose transfer is done, slot_entry[i] + 1 < loaded, + // going on from the last answer in the same frame. + size_t done = frames == audio->read_frames ? audio->read_slot : 0; + while (done < DVI_AUDIO_SLOTS && audio->slot_entry[done] + 1u < loaded) { + done++; + } + audio->read_frames = frames; + audio->read_slot = done; + return (uint64_t)(frames - 1) * DVI_AUDIO_SLOTS + done; +} + +static void dvi_audio_advance(dvi_audio_state_t *audio) { + audio->write_position++; + audio->write_slot = audio->write_slot + 1 == DVI_AUDIO_SLOTS ? 0 : audio->write_slot + 1; +} + +// Works out the packet for the next slot and advances the timing past it: +// an InfoFrame, an ACR packet, up to four sample frames from samples into a +// pool buffer, silence or a null packet. Takes real samples only while +// available is not zero, and sets *count to how many it took. Returns NULL, +// changing nothing, if the samples need a pool buffer and none is free. +static const uint32_t *dvi_audio_next_packet(dvi_audio_state_t *audio, const int16_t *samples, size_t available, size_t *count) { + size_t slot = audio->write_slot; + size_t previous = slot == 0 ? DVI_AUDIO_SLOTS - 1 : slot - 1; + size_t lines = (audio->slot_line[slot] + MODE_640_V_TOTAL_LINES - audio->slot_line[previous]) % MODE_640_V_TOTAL_LINES; + const uint64_t pixel_clock = audio->pixel_clock; + uint64_t sample_phase = audio->sample_phase + (uint64_t)lines * dvi_audio_rates[audio->rate_index].sample_rate * DVI_AUDIO_H_TOTAL; + uint64_t acr_phase = audio->acr_phase + (uint64_t)lines * audio->acr_rate[audio->rate_index] * DVI_AUDIO_H_TOTAL; + // Never let sample timing build up a long burst. + if (sample_phase > pixel_clock * 12) { + sample_phase = pixel_clock * 12; + } + bool vsync = dvi_audio_slot_vsync(audio, slot); + const uint32_t *island; + *count = 0; + if (slot == 0) { + island = audio->audio_infoframe[audio->rate_index]; + } else if (slot == 1) { + island = audio->avi_infoframe; + } else if (acr_phase >= pixel_clock) { + acr_phase -= pixel_clock; + island = audio->acr[audio->rate_index][vsync]; + } else { + // Sample packets carry four frames, fewer only at the end of a + // sample. + size_t due = 0; + while (due < 4 && sample_phase >= (due + 1) * pixel_clock) { + due++; + } + if (available > 0 && (due == 4 || (due > 0 && due >= available))) { + if (audio->pool_count == DVI_AUDIO_POOL) { + return NULL; + } + size_t n = MIN(due, available); + audio_sample_t packet_samples[4]; + for (size_t i = 0; i < n; i++) { + packet_samples[i].left = samples[2 * i]; + packet_samples[i].right = samples[2 * i + 1]; + } + hstx_packet_t packet; + audio->channel_frame = hstx_packet_set_audio_samples(&packet, packet_samples, n, audio->channel_frame, + dvi_audio_rates[audio->rate_index].sample_rate); + uint32_t *buffer = audio->pool[audio->pool_head]; + dvi_audio_encode(buffer, &packet, vsync); + audio->pool_position[audio->pool_head] = audio->write_position; + audio->pool_head = (audio->pool_head + 1) % DVI_AUDIO_POOL; + audio->pool_count++; + sample_phase -= n * pixel_clock; + island = buffer; + *count = n; + } else if (available == 0 && due == 4) { + sample_phase -= 4 * pixel_clock; + island = audio->silence[vsync]; + } else { + island = audio->null_packet[vsync]; + } + } + audio->sample_phase = sample_phase; + audio->acr_phase = acr_phase; + dvi_audio_advance(audio); + return island; +} + +// Points the next slot at its packet. Sets *used to the real sample frames +// it took. With wait set, writes nothing unless DMA is close behind. Returns +// false when the slot cannot be written yet. Never allocates or raises. +// +// With nothing to play, every frame comes out the same once the timing at +// slot 0 repeats. Then the slots already hold the right packets, and this +// stops writing until there is something to play. At 44.1 kHz a frame holds +// 882 samples, not a whole number of packets, so frames never repeat and +// silence keeps being written. +static bool dvi_audio_fill_slot(picodvi_framebuffer_obj_t *self, dvi_audio_state_t *audio, const int16_t *samples, size_t available, bool wait, size_t *used) { + *used = 0; + bool idle = available == 0 && !wait; + if (audio->detach || (audio->idle_steady && idle)) { + return false; + } + uint64_t read = dvi_audio_read_position(audio, self); + if (audio->idle_steady) { + // Catch the timing up to just ahead of DMA. The slots passed over + // already hold the packets it works out. Whole frames repeat, so + // skip them, then work through the rest of one. + uint64_t target = read + DVI_AUDIO_MARGIN; + if (audio->write_position < target) { + audio->write_position += (target - audio->write_position) / DVI_AUDIO_SLOTS * DVI_AUDIO_SLOTS; + } + while (audio->write_position < target) { + size_t count; + dvi_audio_next_packet(audio, NULL, 0, &count); + } + audio->idle_steady = false; + audio->idle_run = 0; + } + audio->rate_index = audio->next_rate_index; + // Free the pool buffers DMA has finished with. + while (audio->pool_count > 0 && audio->pool_position[audio->pool_tail] < read) { + audio->pool_tail = (audio->pool_tail + 1) % DVI_AUDIO_POOL; + audio->pool_count--; + } + if (audio->write_position >= read + DVI_AUDIO_AHEAD) { + return false; + } + if (audio->frames > 0 && audio->write_position < read + DVI_AUDIO_MARGIN) { + // Fell behind. The slots skipped send null packets rather than + // whatever they last pointed at. A frame or more behind, null every + // slot once and skip the whole frames. + uint64_t target = read + DVI_AUDIO_MARGIN; + if (target - audio->write_position >= DVI_AUDIO_SLOTS) { + for (size_t slot = 0; slot < DVI_AUDIO_SLOTS; slot++) { + *dvi_audio_slot_island(audio, slot) = (uintptr_t)audio->null_packet[dvi_audio_slot_vsync(audio, slot)]; + audio->slot_samples[slot] = 0; + } + audio->write_position += (target - audio->write_position) / DVI_AUDIO_SLOTS * DVI_AUDIO_SLOTS; + } + while (audio->write_position < target) { + size_t slot = audio->write_slot; + *dvi_audio_slot_island(audio, slot) = (uintptr_t)audio->null_packet[dvi_audio_slot_vsync(audio, slot)]; + audio->slot_samples[slot] = 0; + dvi_audio_advance(audio); + } + audio->idle_run = 0; + } + if (wait && audio->write_position >= read + DVI_AUDIO_LOW_WATER) { + return false; + } + size_t slot = audio->write_slot; + if (slot == 0 && idle) { + if (audio->idle_run >= DVI_AUDIO_SLOTS && + audio->sample_phase == audio->idle_sample_phase && + audio->acr_phase == audio->idle_acr_phase) { + audio->idle_steady = true; + return false; + } + audio->idle_sample_phase = audio->sample_phase; + audio->idle_acr_phase = audio->acr_phase; + } + size_t count; + const uint32_t *island = dvi_audio_next_packet(audio, samples, available, &count); + if (island == NULL) { + // Wait for DMA to free a pool buffer. + return false; + } + *dvi_audio_slot_island(audio, slot) = (uintptr_t)island; + audio->slot_samples[slot] = count; + audio->idle_run = idle ? audio->idle_run + 1 : 0; + *used = count; + return true; +} + +static void dvi_audio_queue_refill(void); + +static bool __not_in_flash_func(dvi_audio_timer_callback)(repeating_timer_t * timer) { + (void)timer; + dvi_audio_queue_refill(); + return true; +} + +// Allocates the audio state and starts sending audio signaling and silence +// from the next frame. Returns false, leaving nothing allocated, if internal +// RAM is short. Never raises, so it can run before the VM starts. +static bool dvi_audio_try_allocate(picodvi_framebuffer_obj_t *self) { + if (self->dvi_audio) { + return true; + } + dvi_audio_state_t *audio = port_malloc(sizeof(*audio), true); + if (!audio) { + return false; + } + memset(audio, 0, sizeof(*audio)); + audio->command_size = self->output_width != self->width ? 4 : 2; + // DMA reads all of these, so they must be in internal RAM. + audio->commands = port_malloc(dvi_audio_commands_len(self, audio->command_size) * sizeof(uint32_t), true); + audio->pool = port_malloc(DVI_AUDIO_POOL * sizeof(dvi_audio_island_t), true); + if (!audio->commands || !audio->pool) { + dvi_audio_free_state(audio); + return false; + } + audio->pixel_clock = clock_get_hz(clk_hstx) / 5; + for (size_t i = 0; i < DVI_AUDIO_SLOTS; i++) { + audio->slot_line[i] = i * MODE_640_V_TOTAL_LINES / DVI_AUDIO_SLOTS; + } + dvi_audio_init_line_pieces(audio); + dvi_audio_init_packets(audio); + dvi_audio_build_commands(audio, self); + // Start with silence, before the frame interrupt can switch to the list. + size_t used; + while (dvi_audio_fill_slot(self, audio, NULL, 0, false, &used)) { + } + audio->timer_running = add_repeating_timer_us(-DVI_AUDIO_REFILL_US, dvi_audio_timer_callback, NULL, &audio->timer); + if (!audio->timer_running) { + // Refilling once a frame can't keep ahead of DMA. + dvi_audio_free_state(audio); + return false; + } + self->dvi_audio = audio; + return true; +} + +static void audioout_refill(picodvi_audioout_obj_t *self); + +// Looks the AudioOut up again when it runs, so one deinitialized after the +// callback was queued is skipped. A deinitialized framebuffer's storage may +// already hold another display, so only the active framebuffer is touched. +static void dvi_audio_run_refill(void *data) { + picodvi_framebuffer_obj_t *self = data; + if (self != active_picodvi || self->audioout == MP_OBJ_NULL) { + return; + } + audioout_refill(MP_OBJ_TO_PTR(self->audioout)); +} + +// Called from interrupts: the frame interrupt and the refill timer. +static void __not_in_flash_func(dvi_audio_queue_refill)(void) { + if (active_picodvi != NULL && active_picodvi->dvi_audio && active_picodvi->audioout != MP_OBJ_NULL) { + background_callback_add(&dvi_audio_refill_callback, dvi_audio_run_refill, active_picodvi); + } +} + +// Called from the frame interrupt after the next frame has started. +void __not_in_flash_func(picodvi_audioout_frame_done)(void) { + dvi_audio_queue_refill(); +} + +// Called at frame boundary only; old DMA frame has completed. +uint32_t *__not_in_flash_func(picodvi_audioout_next_frame)(void) { + dvi_audio_state_t *audio = active_picodvi->dvi_audio; + if (!audio || audio->detached) { + return active_picodvi->dma_commands; + } + if (audio->detach) { + // From this frame on, DMA reads only the plain video commands. + audio->detached = true; + return active_picodvi->dma_commands; + } + audio->frames++; + return audio->commands; +} + +// Allocates the audio state and starts sending audio signaling and silence. +// Does nothing if already reserved. Raises ValueError if the output is not +// 640 pixels wide, or MemoryError, leaving nothing allocated. +static void picodvi_framebuffer_audio_reserve(picodvi_framebuffer_obj_t *self) { + if (self->output_width != 640) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("Invalid %q"), MP_QSTR_framebuffer); + } + if (!dvi_audio_try_allocate(self)) { + m_malloc_fail(sizeof(dvi_audio_state_t)); + } +} + +// Stops audio and frees the audio state, waiting up to two frames for DMA to +// stop reading it. +static void picodvi_framebuffer_audio_release(picodvi_framebuffer_obj_t *self) { + dvi_audio_state_t *audio = self->dvi_audio; + if (!audio) { + return; + } + audio->detach = true; + // Wait for the frame interrupt to move DMA back to the video commands. + // Without frame interrupts, DMA stops at the end of the current frame. + for (int i = 0; i < 1000 && !audio->detached && active_picodvi == self; i++) { + busy_wait_us(100); + } + uint32_t irq_state = save_and_disable_interrupts(); + self->dvi_audio = NULL; + restore_interrupts(irq_state); + dvi_audio_free_state(audio); +} + +// Returns the sample frames written ahead of DMA, 0 if not reserved. +static size_t picodvi_framebuffer_audio_pending(picodvi_framebuffer_obj_t *self) { + dvi_audio_state_t *audio = self->dvi_audio; + if (!audio) { + return 0; + } + uint64_t read = dvi_audio_read_position(audio, self); + size_t count = 0; + if (audio->write_position > read) { + size_t slot = read % DVI_AUDIO_SLOTS; + for (uint64_t ahead = audio->write_position - read; ahead > 0; ahead--) { + count += audio->slot_samples[slot]; + slot = slot + 1 == DVI_AUDIO_SLOTS ? 0 : slot + 1; + } + } + return count; +} + +// Forgets the sample frames written ahead of DMA. They still play, for at +// most about 15 ms. +static void picodvi_framebuffer_audio_stop(picodvi_framebuffer_obj_t *self) { + dvi_audio_state_t *audio = self->dvi_audio; + if (!audio) { + return; + } + memset(audio->slot_samples, 0, sizeof(audio->slot_samples)); +} + +// Sends the rate at rate_index in dvi_audio_rates from the next slot written. +// The packets already written ahead of DMA keep the old rate. +static void picodvi_framebuffer_audio_set_rate(picodvi_framebuffer_obj_t *self, size_t rate_index) { + self->dvi_audio->next_rate_index = rate_index; +} + +// Convert up to space frames of the current sample buffer into the stage. +static void audioout_convert(picodvi_audioout_obj_t *self, size_t space) { + audiosample_base_t *base = audiosample_cast_obj(self->sample); + size_t n = MIN(self->source_frames, space); + int16_t *out = &self->stage[self->stage_frames * 2]; + const uint8_t *in = self->source; + bool stereo = base->channel_count == 2; + if (base->bits_per_sample == 8) { + if (base->samples_signed) { + if (stereo) { + audiosample_convert_s8s_s16s(out, (const int8_t *)in, n); + } else { + audiosample_convert_s8m_s16s(out, (const int8_t *)in, n); + } + } else { + if (stereo) { + audiosample_convert_u8s_s16s(out, in, n); + } else { + audiosample_convert_u8m_s16s(out, in, n); + } + } + } else { + if (base->samples_signed) { + if (stereo) { + memcpy(out, in, n * 4); + } else { + audiosample_convert_s16m_s16s(out, (const int16_t *)in, n); + } + } else { + if (stereo) { + audiosample_convert_u16s_s16s(out, (const uint16_t *)in, n); + } else { + audiosample_convert_u16m_s16s(out, (const uint16_t *)in, n); + } + } + } + self->source += n * self->bytes_per_frame; + self->source_frames -= n; + self->stage_frames += n; +} + +// Top up the stage from the sample, getting new buffers and looping as needed. +static void audioout_stage(picodvi_audioout_obj_t *self) { + while (!self->source_done && self->stage_frames < PICODVI_AUDIOOUT_STAGE_FRAMES) { + if (self->source_frames == 0) { + if (self->source_last) { + // Also stop a looping sample with no frames at all. + if (!self->loop || self->pass_empty) { + self->source_done = true; + return; + } + audiosample_reset_buffer(self->sample, false, 0); + self->pass_empty = true; + } + uint8_t *buffer; + uint32_t length; + audioio_get_buffer_result_t result = audiosample_get_buffer(self->sample, false, 0, &buffer, &length); + if (result == GET_BUFFER_ERROR) { + self->source_done = true; + return; + } + self->source = buffer; + self->source_frames = length / self->bytes_per_frame; + if (self->source_frames > 0) { + self->pass_empty = false; + } + self->source_last = result == GET_BUFFER_DONE; + continue; + } + audioout_convert(self, PICODVI_AUDIOOUT_STAGE_FRAMES - self->stage_frames); + } +} + +// Runs in the background after every frame and every few milliseconds, and +// once from play() and resume(). Points every slot DMA has finished with at +// the next packet: from the stage, or silence when nothing is playing, so +// the timing carries on. +static void audioout_refill(picodvi_audioout_obj_t *self) { + dvi_audio_state_t *audio = self->framebuffer->dvi_audio; + if (self->refilling || !audio) { + return; + } + self->refilling = true; + // Stage frames already sent to slots. + size_t offset = 0; + while (true) { + // stop() may empty the stage while a sample buffer is fetched. + offset = MIN(offset, self->stage_frames); + bool playing = self->sample != MP_OBJ_NULL && !self->paused; + if (playing && self->stage_frames - offset < 4) { + // Move what is left to the front, then top the stage up. + self->stage_frames -= offset; + memmove(self->stage, &self->stage[offset * 2], self->stage_frames * 4); + offset = 0; + audioout_stage(self); + } + size_t available = playing ? self->stage_frames - offset : 0; + // A sample still playing may have more frames later. + bool wait = playing && available == 0 && !self->source_done; + size_t used; + if (!dvi_audio_fill_slot(self->framebuffer, audio, &self->stage[offset * 2], available, wait, &used)) { + break; + } + offset += used; + } + offset = MIN(offset, self->stage_frames); + self->stage_frames -= offset; + memmove(self->stage, &self->stage[offset * 2], self->stage_frames * 4); + self->refilling = false; +} + +void common_hal_picodvi_audioout_construct(picodvi_audioout_obj_t *self, picodvi_framebuffer_obj_t *framebuffer) { + if (framebuffer->audioout != MP_OBJ_NULL) { + mp_raise_RuntimeError_varg(MP_ERROR_TEXT("%q in use"), MP_QSTR_framebuffer); + } + picodvi_framebuffer_audio_reserve(framebuffer); + self->framebuffer = framebuffer; + self->sample = MP_OBJ_NULL; + // The framebuffer keeps this object alive and schedules its refills. + framebuffer->audioout = MP_OBJ_FROM_PTR(self); +} + +void picodvi_audioout_reset(void) { + if (active_picodvi == NULL || active_picodvi->audioout == MP_OBJ_NULL) { + return; + } + picodvi_audioout_obj_t *self = MP_OBJ_TO_PTR(active_picodvi->audioout); + if (is_board_audioout(self)) { + // Keep supervisor.runtime.audio for the next VM. Drop the sample, which is on + // the VM heap. + common_hal_picodvi_audioout_stop(self); + return; + } + common_hal_picodvi_audioout_deinit(self); +} + +void picodvi_audioout_collect_ptrs(picodvi_framebuffer_obj_t *framebuffer) { + if (framebuffer->audioout == MP_OBJ_NULL) { + return; + } + gc_collect_ptr(framebuffer->audioout); + // supervisor.runtime.audio is not on the heap, so the GC does not trace into it. + picodvi_audioout_obj_t *self = MP_OBJ_TO_PTR(framebuffer->audioout); + gc_collect_ptr(self->sample); +} + +#if defined(DEFAULT_DVI_BUS_CLK_DP) +bool picodvi_audioout_construct_board(picodvi_framebuffer_obj_t *framebuffer) { + picodvi_audioout_obj_t *self = &picodvi_board_audioout; + if (framebuffer->output_width != 640 || framebuffer->audioout != MP_OBJ_NULL) { + return false; + } + if (!dvi_audio_try_allocate(framebuffer)) { + return false; + } + memset(self, 0, sizeof(*self)); + self->base.type = &picodvi_audioout_type; + self->framebuffer = framebuffer; + self->sample = MP_OBJ_NULL; + // The framebuffer schedules its refills, which send silence until a + // sample plays. + framebuffer->audioout = MP_OBJ_FROM_PTR(self); + return true; +} + +mp_obj_t common_hal_supervisor_runtime_get_audio(void) { + if (picodvi_board_audioout.base.type != &picodvi_audioout_type) { + return mp_const_none; + } + return MP_OBJ_FROM_PTR(&picodvi_board_audioout); +} +#endif + +bool common_hal_picodvi_audioout_deinited(picodvi_audioout_obj_t *self) { + return self->framebuffer == NULL; +} + +void common_hal_picodvi_audioout_deinit(picodvi_audioout_obj_t *self) { + if (common_hal_picodvi_audioout_deinited(self)) { + return; + } + common_hal_picodvi_audioout_stop(self); + self->framebuffer->audioout = MP_OBJ_NULL; + picodvi_framebuffer_audio_release(self->framebuffer); + self->framebuffer = NULL; + if (is_board_audioout(self)) { + // Nothing can construct it again until the next reset. + self->base.type = &mp_type_NoneType; + } +} + +void common_hal_picodvi_audioout_play(picodvi_audioout_obj_t *self, mp_obj_t sample, bool loop) { + audiosample_base_t *base = audiosample_check(sample); + size_t rate_index = 0; + while (rate_index < DVI_AUDIO_RATE_COUNT && dvi_audio_rates[rate_index].sample_rate != base->sample_rate) { + rate_index++; + } + if (rate_index == DVI_AUDIO_RATE_COUNT) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("Invalid %q"), MP_QSTR_sample_rate); + } + mp_arg_validate_int_range(base->channel_count, 1, 2, MP_QSTR_channel_count); + if (base->bits_per_sample != 8 && base->bits_per_sample != 16) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("Invalid %q"), MP_QSTR_bits_per_sample); + } + common_hal_picodvi_audioout_stop(self); + picodvi_framebuffer_audio_set_rate(self->framebuffer, rate_index); + audiosample_reset_buffer(sample, false, 0); + self->bytes_per_frame = base->channel_count * base->bits_per_sample / 8; + self->source_frames = 0; + self->source_last = false; + self->source_done = false; + self->pass_empty = true; + self->stage_frames = 0; + self->loop = loop; + self->paused = false; + self->refilling = false; + self->sample = sample; + audioout_refill(self); +} + +void common_hal_picodvi_audioout_stop(picodvi_audioout_obj_t *self) { + self->sample = MP_OBJ_NULL; + self->paused = false; + // Drops what was staged. + self->stage_frames = 0; + picodvi_framebuffer_audio_stop(self->framebuffer); +} + +bool common_hal_picodvi_audioout_get_playing(picodvi_audioout_obj_t *self) { + if (self->sample == MP_OBJ_NULL) { + return false; + } + return !self->source_done || self->stage_frames > 0 || + picodvi_framebuffer_audio_pending(self->framebuffer) > 0; +} + +void common_hal_picodvi_audioout_pause(picodvi_audioout_obj_t *self) { + self->paused = true; +} + +void common_hal_picodvi_audioout_resume(picodvi_audioout_obj_t *self) { + self->paused = false; + audioout_refill(self); +} + +bool common_hal_picodvi_audioout_get_paused(picodvi_audioout_obj_t *self) { + return self->paused; +} diff --git a/ports/raspberrypi/common-hal/picodvi/AudioOut.h b/ports/raspberrypi/common-hal/picodvi/AudioOut.h new file mode 100644 index 00000000000..d271bc5fc67 --- /dev/null +++ b/ports/raspberrypi/common-hal/picodvi/AudioOut.h @@ -0,0 +1,65 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "common-hal/picodvi/Framebuffer.h" + +// More than one video frame of audio (800 frames at 48 kHz, 60 Hz), so a +// bank can always be filled completely. +#define PICODVI_AUDIOOUT_STAGE_FRAMES 1024 + +typedef struct { + mp_obj_base_t base; + picodvi_framebuffer_obj_t *framebuffer; + mp_obj_t sample; + // The sample buffer being converted, and how many frames remain in it. + const uint8_t *source; + size_t source_frames; + bool source_last; + bool source_done; + // True until the current pass through the sample gives a frame. + bool pass_empty; + uint8_t bytes_per_frame; + bool loop; + bool paused; + // Set while a refill runs. A refill started inside it, such as from + // background tasks during an SD card read, returns at once. + bool refilling; + // Converted 16-bit stereo frames waiting to be sent. + size_t stage_frames; + int16_t stage[PICODVI_AUDIOOUT_STAGE_FRAMES * 2]; +} picodvi_audioout_obj_t; + +// Called by the frame interrupt at a frame boundary. Returns the command +// list for the next frame. +uint32_t *picodvi_audioout_next_frame(void); +// Called by the frame interrupt once the next frame has started. +void picodvi_audioout_frame_done(void); +// Called by framebuffer deinit, after DMA stops, to free the audio state +// and deinit its AudioOut. +void picodvi_audioout_framebuffer_deinit(picodvi_framebuffer_obj_t *framebuffer); + +// Deinit any AudioOut before the VM heap goes away. The board AudioOut only +// stops, since it lives as long as the boot framebuffer. +void picodvi_audioout_reset(void); + +// Marks the AudioOut of each framebuffer, and its sample, as in use for the GC. +void picodvi_audioout_collect_ptrs(picodvi_framebuffer_obj_t *framebuffer); + +#if defined(DEFAULT_DVI_BUS_CLK_DP) +// supervisor.runtime.audio. Its type is NoneType until +// picodvi_audioout_construct_board succeeds, and again after it or its +// framebuffer is deinitialized. supervisor.runtime.audio returns None then. +extern picodvi_audioout_obj_t picodvi_board_audioout; + +// Makes picodvi_board_audioout send audio with the boot framebuffer. Runs +// before the VM starts, so it never allocates on the VM heap and never raises. +// Returns true on success. Returns false, leaving the board AudioOut as None +// and nothing allocated, if the output is not 640 pixels wide or internal RAM +// is short. +bool picodvi_audioout_construct_board(picodvi_framebuffer_obj_t *framebuffer); +#endif diff --git a/ports/raspberrypi/common-hal/picodvi/Framebuffer.h b/ports/raspberrypi/common-hal/picodvi/Framebuffer.h index 50288578590..82c0b189b89 100644 --- a/ports/raspberrypi/common-hal/picodvi/Framebuffer.h +++ b/ports/raspberrypi/common-hal/picodvi/Framebuffer.h @@ -6,7 +6,7 @@ #pragma once -#ifdef PICO_RP2040 +#if PICO_RP2040 #include "Framebuffer_RP2040.h" #else #include "Framebuffer_RP2350.h" diff --git a/ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c b/ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c index 788f10d6df6..b687870586d 100644 --- a/ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c +++ b/ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2040.c @@ -109,6 +109,11 @@ static void __not_in_flash_func(core1_scanline_callback)(void) { extern uint8_t dvi_vertical_repeat; extern bool dvi_monochrome_tmds; +// Mark the object deinited. A zeroed object also reads as deinited. +static void mark_deinit(picodvi_framebuffer_obj_t *self) { + self->framebuffer = NULL; +} + void common_hal_picodvi_framebuffer_construct(picodvi_framebuffer_obj_t *self, mp_uint_t width, mp_uint_t height, const mcu_pin_obj_t *clk_dp, const mcu_pin_obj_t *clk_dn, @@ -116,6 +121,10 @@ void common_hal_picodvi_framebuffer_construct(picodvi_framebuffer_obj_t *self, const mcu_pin_obj_t *green_dp, const mcu_pin_obj_t *green_dn, const mcu_pin_obj_t *blue_dp, const mcu_pin_obj_t *blue_dn, mp_uint_t color_depth) { + // Ensure the object starts in its deinit state, so its finaliser does + // nothing if this raises before the framebuffer is allocated. + mark_deinit(self); + if (active_picodvi != NULL) { mp_raise_msg_varg(&mp_type_RuntimeError, MP_ERROR_TEXT("%q in use"), MP_QSTR_picodvi); } @@ -174,32 +183,23 @@ void common_hal_picodvi_framebuffer_construct(picodvi_framebuffer_obj_t *self, uint8_t slice = pwm_gpio_to_slice_num(self->pin_pair[0]); - pio_program_t program_struct = { - .instructions = NULL, - .length = 2, - .origin = -1 - }; - size_t pio_index = NUM_PIOS; - int free_state_machines[4]; // We may find all four free. We only use the first three. - for (size_t i = 0; i < NUM_PIOS; i++) { - PIO pio = pio_get_instance(i); - uint8_t free_count = 0; - for (size_t sm = 0; sm < NUM_PIO_STATE_MACHINES; sm++) { - if (!pio_sm_is_claimed(pio, sm)) { - free_state_machines[free_count] = sm; - free_count++; - } - } - if (free_count >= 3 && pio_can_add_program(pio, &program_struct)) { - pio_index = i; - break; - } - } - + // We need a PIO with room for a 2-instruction program and 3 free state machines. + size_t pio_index = rp2pio_statemachine_find_pio(2, 3); if (pio_index == NUM_PIOS) { mp_raise_RuntimeError(MP_ERROR_TEXT("All state machines in use")); } + // Collect the free state machines on the chosen PIO. We only use the first three. + int free_state_machines[4]; // We may find all four free. + uint8_t free_count = 0; + PIO pio = pio_get_instance(pio_index); + for (size_t sm = 0; sm < NUM_PIO_STATE_MACHINES; sm++) { + if (!pio_sm_is_claimed(pio, sm)) { + free_state_machines[free_count] = sm; + free_count++; + } + } + self->width = width; self->height = height; @@ -224,26 +224,19 @@ void common_hal_picodvi_framebuffer_construct(picodvi_framebuffer_obj_t *self, size_t framebuffer_size = self->pitch * self->height; self->tmdsbuf_size = tmds_bufs_per_scanline * scanline_width / DVI_SYMBOLS_PER_WORD + 1; size_t total_allocation_size = sizeof(uint32_t) * (framebuffer_size + DVI_N_TMDS_BUFFERS * self->tmdsbuf_size); - self->framebuffer = (uint32_t *)port_malloc(total_allocation_size, true); - if (self->framebuffer == NULL) { - m_malloc_fail(total_allocation_size); - return; - } - - // Do the pwmio check last because it claims the pwm slice. + // Claim the pwm slice before allocating the framebuffer. deinited() checks + // the framebuffer, so this object must not raise once it is set. if (!pwmio_claim_slice_ab_channels(slice)) { mp_raise_ValueError(MP_ERROR_TEXT("All timers for this pin are in use")); } - self->pwm_slice = slice; - - for (size_t i = 0; i < 4; i++) { - never_reset_pin_number(self->pin_pair[i]); - never_reset_pin_number(self->pin_pair[i] + 1); - } - - for (size_t i = 0; i < 3; i++) { - rp2pio_statemachine_never_reset(pio_get_instance(pio_index), free_state_machines[i]); + uint32_t *framebuffer = (uint32_t *)port_malloc(total_allocation_size, true); + if (framebuffer == NULL) { + pwmio_release_slice_ab_channels(slice); + m_malloc_fail(total_allocation_size); + return; } + self->framebuffer = framebuffer; + self->pwm_slice = slice; // For the output. user_irq_claim(DMA_IRQ_1); @@ -350,7 +343,6 @@ void common_hal_picodvi_framebuffer_deinit(picodvi_framebuffer_obj_t *self) { int sm = self->dvi.ser_cfg.sm_tmds[i]; pio_sm_set_enabled(pio, sm, false); pio_sm_unclaim(pio, sm); - rp2pio_statemachine_reset_ok(pio, sm); } pio_remove_program(pio, &program_struct, self->dvi.ser_cfg.prog_offs); @@ -361,7 +353,7 @@ void common_hal_picodvi_framebuffer_deinit(picodvi_framebuffer_obj_t *self) { active_picodvi = NULL; port_free(self->framebuffer); - self->framebuffer = NULL; + mark_deinit(self); self->base.type = &mp_type_NoneType; } @@ -373,6 +365,11 @@ bool common_hal_picodvi_framebuffer_deinited(picodvi_framebuffer_obj_t *self) { void common_hal_picodvi_framebuffer_refresh(picodvi_framebuffer_obj_t *self) { } +void common_hal_picodvi_framebuffer_wait_for_vblank(picodvi_framebuffer_obj_t *self) { + // No frame-boundary counter on the RP2040 PIO-DVI path; vblank sync is a no-op here (the + // tear-free full-repaint path is RP2350/HSTX, e.g. Fruit Jam). Present so the binding links. +} + int common_hal_picodvi_framebuffer_get_width(picodvi_framebuffer_obj_t *self) { return self->width; } diff --git a/ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c b/ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c index 79ec315d497..e3df898592a 100644 --- a/ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c +++ b/ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.c @@ -29,6 +29,7 @@ #include "py/gc.h" #include "py/runtime.h" #include "shared-bindings/time/__init__.h" +#include "supervisor/background_callback.h" #include "supervisor/port.h" #include "pico/stdlib.h" @@ -40,58 +41,6 @@ #include "hardware/structs/hstx_ctrl.h" #include "hardware/structs/hstx_fifo.h" -// ---------------------------------------------------------------------------- -// DVI constants - -#define TMDS_CTRL_00 0x354u -#define TMDS_CTRL_01 0x0abu -#define TMDS_CTRL_10 0x154u -#define TMDS_CTRL_11 0x2abu - -#define SYNC_V0_H0 (TMDS_CTRL_00 | (TMDS_CTRL_00 << 10) | (TMDS_CTRL_00 << 20)) -#define SYNC_V0_H1 (TMDS_CTRL_01 | (TMDS_CTRL_00 << 10) | (TMDS_CTRL_00 << 20)) -#define SYNC_V1_H0 (TMDS_CTRL_10 | (TMDS_CTRL_00 << 10) | (TMDS_CTRL_00 << 20)) -#define SYNC_V1_H1 (TMDS_CTRL_11 | (TMDS_CTRL_00 << 10) | (TMDS_CTRL_00 << 20)) - -#define MODE_720_H_SYNC_POLARITY 0 -#define MODE_720_H_FRONT_PORCH 24 -#define MODE_720_H_SYNC_WIDTH 64 -#define MODE_720_H_BACK_PORCH 88 -#define MODE_720_H_ACTIVE_PIXELS 720 - -#define MODE_720_V_SYNC_POLARITY 0 -#define MODE_720_V_FRONT_PORCH 3 -#define MODE_720_V_SYNC_WIDTH 4 -#define MODE_720_V_BACK_PORCH 13 -#define MODE_720_V_ACTIVE_LINES 400 - -#define MODE_640_H_SYNC_POLARITY 0 -#define MODE_640_H_FRONT_PORCH 16 -#define MODE_640_H_SYNC_WIDTH 96 -#define MODE_640_H_BACK_PORCH 48 -#define MODE_640_H_ACTIVE_PIXELS 640 - -#define MODE_640_V_SYNC_POLARITY 0 -#define MODE_640_V_FRONT_PORCH 10 -#define MODE_640_V_SYNC_WIDTH 2 -#define MODE_640_V_BACK_PORCH 33 -#define MODE_640_V_ACTIVE_LINES 480 - -#define MODE_720_V_TOTAL_LINES ( \ - MODE_720_V_FRONT_PORCH + MODE_720_V_SYNC_WIDTH + \ - MODE_720_V_BACK_PORCH + MODE_720_V_ACTIVE_LINES \ - ) -#define MODE_640_V_TOTAL_LINES ( \ - MODE_640_V_FRONT_PORCH + MODE_640_V_SYNC_WIDTH + \ - MODE_640_V_BACK_PORCH + MODE_640_V_ACTIVE_LINES \ - ) - -#define HSTX_CMD_RAW (0x0u << 12) -#define HSTX_CMD_RAW_REPEAT (0x1u << 12) -#define HSTX_CMD_TMDS (0x2u << 12) -#define HSTX_CMD_TMDS_REPEAT (0x3u << 12) -#define HSTX_CMD_NOP (0xfu << 12) - // ---------------------------------------------------------------------------- // HSTX command lists @@ -160,6 +109,23 @@ static uint32_t vactive_line720[VACTIVE_LEN] = { picodvi_framebuffer_obj_t *active_picodvi = NULL; +#if CIRCUITPY_PICODVI_AUDIOOUT +#include "common-hal/picodvi/AudioOut.h" +#else +static inline uint32_t *picodvi_audioout_next_frame(void) { + return active_picodvi->dma_commands; +} +static inline void picodvi_audioout_frame_done(void) { +} +static inline void picodvi_audioout_framebuffer_deinit(picodvi_framebuffer_obj_t *self) { +} +#endif + +// Incremented once per completed frame by the DMA frame-boundary IRQ, so refresh() can block +// until the next frame starts (vblank sync). A full-framebuffer repaint that begins right after a +// frame boundary then races ahead of scanout, avoiding tearing without a second framebuffer. +static volatile uint32_t framebuffer_frame_count = 0; + static void __not_in_flash_func(dma_irq_handler)(void) { if (active_picodvi == NULL) { return; @@ -170,7 +136,9 @@ static void __not_in_flash_func(dma_irq_handler)(void) { // Set the read_addr back to the start and trigger the first transfer (which // will trigger the pixel channel). dma_channel_hw_t *ch = &dma_hw->ch[active_picodvi->dma_command_channel]; - ch->al3_read_addr_trig = (uintptr_t)active_picodvi->dma_commands; + ch->al3_read_addr_trig = (uintptr_t)picodvi_audioout_next_frame(); + framebuffer_frame_count++; // frame boundary: scanout has wrapped back to the top + picodvi_audioout_frame_done(); } bool common_hal_picodvi_framebuffer_preflight( @@ -223,6 +191,8 @@ void common_hal_picodvi_framebuffer_construct(picodvi_framebuffer_obj_t *self, mp_raise_ValueError_varg(MP_ERROR_TEXT("Invalid %q and %q"), MP_QSTR_width, MP_QSTR_height); } + self->dvi_audio = NULL; + self->audioout = MP_OBJ_NULL; self->dma_command_channel = -1; self->dma_pixel_channel = -1; @@ -534,7 +504,6 @@ void common_hal_picodvi_framebuffer_construct(picodvi_framebuffer_obj_t *self, for (int i = 12; i <= 19; ++i) { gpio_set_function(i, 0); // HSTX - never_reset_pin_number(i); } dma_channel_config c; @@ -598,6 +567,16 @@ void common_hal_picodvi_framebuffer_deinit(picodvi_framebuffer_obj_t *self) { return; } + // Stop frame restarts before aborting either channel. An already pending + // frame IRQ must not repoint the command DMA during teardown. + uint32_t irq_state = save_and_disable_interrupts(); + active_picodvi = NULL; + if (self->dma_pixel_channel >= 0) { + dma_channel_set_irq1_enabled(self->dma_pixel_channel, false); + dma_hw->ints1 = 1u << self->dma_pixel_channel; + } + restore_interrupts(irq_state); + for (int i = 12; i <= 19; ++i) { reset_pin_number(i); } @@ -607,7 +586,7 @@ void common_hal_picodvi_framebuffer_deinit(picodvi_framebuffer_obj_t *self) { self->dma_pixel_channel = -1; self->dma_command_channel = -1; - active_picodvi = NULL; + picodvi_audioout_framebuffer_deinit(self); port_free(self->framebuffer); self->framebuffer = NULL; @@ -625,6 +604,23 @@ bool common_hal_picodvi_framebuffer_deinited(picodvi_framebuffer_obj_t *self) { void common_hal_picodvi_framebuffer_refresh(picodvi_framebuffer_obj_t *self) { } +void common_hal_picodvi_framebuffer_wait_for_vblank(picodvi_framebuffer_obj_t *self) { + // Block until the next frame boundary (vblank). A full-framebuffer repaint issued right after + // this returns starts at the top of scanout and stays ahead of the beam, so it does not tear + // mid-screen. Bounded by a timeout so a stopped or absent DVI signal can never hang the caller. + if (self != active_picodvi) { + return; + } + uint32_t start = framebuffer_frame_count; + uint64_t timeout = common_hal_time_monotonic_ms() + 30; // ~2 frames @ 60 Hz + while (framebuffer_frame_count == start) { + RUN_BACKGROUND_TASKS; // don't starve USB host / other tasks during the ~<16 ms wait + if (common_hal_time_monotonic_ms() >= timeout) { + break; + } + } +} + int common_hal_picodvi_framebuffer_get_width(picodvi_framebuffer_obj_t *self) { return self->width; } diff --git a/ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.h b/ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.h index fa08bc77d93..904e69d83c9 100644 --- a/ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.h +++ b/ports/raspberrypi/common-hal/picodvi/Framebuffer_RP2350.h @@ -28,8 +28,66 @@ #include "py/obj.h" +// ---------------------------------------------------------------------------- +// DVI constants + +#define TMDS_CTRL_00 0x354u +#define TMDS_CTRL_01 0x0abu +#define TMDS_CTRL_10 0x154u +#define TMDS_CTRL_11 0x2abu + +#define SYNC_V0_H0 (TMDS_CTRL_00 | (TMDS_CTRL_00 << 10) | (TMDS_CTRL_00 << 20)) +#define SYNC_V0_H1 (TMDS_CTRL_01 | (TMDS_CTRL_00 << 10) | (TMDS_CTRL_00 << 20)) +#define SYNC_V1_H0 (TMDS_CTRL_10 | (TMDS_CTRL_00 << 10) | (TMDS_CTRL_00 << 20)) +#define SYNC_V1_H1 (TMDS_CTRL_11 | (TMDS_CTRL_00 << 10) | (TMDS_CTRL_00 << 20)) + +#define MODE_720_H_SYNC_POLARITY 0 +#define MODE_720_H_FRONT_PORCH 8 +#define MODE_720_H_SYNC_WIDTH 32 +#define MODE_720_H_BACK_PORCH 40 +#define MODE_720_H_ACTIVE_PIXELS 720 + +#define MODE_720_V_SYNC_POLARITY 0 +#define MODE_720_V_FRONT_PORCH 3 +#define MODE_720_V_SYNC_WIDTH 4 +#define MODE_720_V_BACK_PORCH 218 +#define MODE_720_V_ACTIVE_LINES 400 + +#define MODE_640_H_SYNC_POLARITY 0 +#define MODE_640_H_FRONT_PORCH 16 +#define MODE_640_H_SYNC_WIDTH 96 +#define MODE_640_H_BACK_PORCH 48 +#define MODE_640_H_ACTIVE_PIXELS 640 + +#define MODE_640_V_SYNC_POLARITY 0 +#define MODE_640_V_FRONT_PORCH 10 +#define MODE_640_V_SYNC_WIDTH 2 +#define MODE_640_V_BACK_PORCH 133 +#define MODE_640_V_ACTIVE_LINES 480 + +#define MODE_720_V_TOTAL_LINES ( \ + MODE_720_V_FRONT_PORCH + MODE_720_V_SYNC_WIDTH + \ + MODE_720_V_BACK_PORCH + MODE_720_V_ACTIVE_LINES \ + ) +#define MODE_640_V_TOTAL_LINES ( \ + MODE_640_V_FRONT_PORCH + MODE_640_V_SYNC_WIDTH + \ + MODE_640_V_BACK_PORCH + MODE_640_V_ACTIVE_LINES \ + ) + +#define HSTX_CMD_RAW (0x0u << 12) +#define HSTX_CMD_RAW_REPEAT (0x1u << 12) +#define HSTX_CMD_TMDS (0x2u << 12) +#define HSTX_CMD_TMDS_REPEAT (0x3u << 12) +#define HSTX_CMD_NOP (0xfu << 12) + +struct dvi_audio_state; + typedef struct { mp_obj_base_t base; + struct dvi_audio_state *dvi_audio; + // The picodvi.AudioOut using this framebuffer, or MP_OBJ_NULL. It lives + // as long as the framebuffer. + mp_obj_t audioout; uint32_t *framebuffer; size_t framebuffer_len; // in words uint32_t *dma_commands; @@ -42,3 +100,6 @@ typedef struct { int dma_pixel_channel; int dma_command_channel; } picodvi_framebuffer_obj_t; + +// The framebuffer the frame interrupt is driving, or NULL. +extern picodvi_framebuffer_obj_t *active_picodvi; diff --git a/ports/raspberrypi/common-hal/picodvi/__init__.c b/ports/raspberrypi/common-hal/picodvi/__init__.c index 9a779796694..a9276096529 100644 --- a/ports/raspberrypi/common-hal/picodvi/__init__.c +++ b/ports/raspberrypi/common-hal/picodvi/__init__.c @@ -10,19 +10,23 @@ #include "shared-bindings/busio/I2C.h" #include "shared-bindings/board/__init__.h" #include "shared-module/displayio/__init__.h" -#include "shared-module/os/__init__.h" #include "supervisor/shared/safe_mode.h" +#include "supervisor/shared/settings.h" #include "py/gc.h" #include "py/runtime.h" #include "supervisor/port_heap.h" +#if CIRCUITPY_PICODVI_AUDIOOUT && defined(DEFAULT_DVI_BUS_CLK_DP) +#include "common-hal/picodvi/AudioOut.h" +#endif + #if defined(DEFAULT_DVI_BUS_CLK_DP) static bool picodvi_autoconstruct_enabled(mp_int_t *default_width, mp_int_t *default_height) { char buf[sizeof("detect")]; buf[0] = 0; // (any failure leaves the content of buf untouched: an empty nul-terminated string - (void)common_hal_os_getenv_str("CIRCUITPY_PICODVI_ENABLE", buf, sizeof(buf)); + (void)settings_get_str("CIRCUITPY_PICODVI_ENABLE", buf, sizeof(buf)); if (!strcasecmp(buf, "never")) { return false; @@ -74,11 +78,11 @@ static bool picodvi_autoconstruct_enabled(mp_int_t *default_width, mp_int_t *def if ((established_timings & 0x80) != 0 && preferred_width % 1920 == 0 && preferred_height % 1080 == 0) { - *default_width = 720 / 2; - *default_height = 400 / 2; + *default_width = 720; + *default_height = 400; } else { - *default_width = 640 / 2; - *default_height = 480 / 2; + *default_width = 640; + *default_height = 480; } } } @@ -95,24 +99,32 @@ void picodvi_autoconstruct(void) { return; } - mp_int_t default_width = 320; - mp_int_t default_height = 240; + mp_int_t default_width = 640; + mp_int_t default_height = 480; if (!picodvi_autoconstruct_enabled(&default_width, &default_height)) { return; } + #if CIRCUITPY_PICODVI_AUDIOOUT + bool audio = true; + (void)settings_get_bool("CIRCUITPY_PICODVI_AUDIO", &audio); + #endif + mp_int_t width = default_width; mp_int_t height = 0; - mp_int_t color_depth = 16; + mp_int_t color_depth = 8; mp_int_t rotation = 0; - (void)common_hal_os_getenv_int("CIRCUITPY_DISPLAY_WIDTH", &width); - (void)common_hal_os_getenv_int("CIRCUITPY_DISPLAY_HEIGHT", &height); - (void)common_hal_os_getenv_int("CIRCUITPY_DISPLAY_COLOR_DEPTH", &color_depth); - (void)common_hal_os_getenv_int("CIRCUITPY_DISPLAY_ROTATION", &rotation); + (void)settings_get_int("CIRCUITPY_DISPLAY_WIDTH", &width); + (void)settings_get_int("CIRCUITPY_DISPLAY_HEIGHT", &height); + (void)settings_get_int("CIRCUITPY_DISPLAY_COLOR_DEPTH", &color_depth); + (void)settings_get_int("CIRCUITPY_DISPLAY_ROTATION", &rotation); if (height == 0) { switch (width) { + case 720: + height = 400; + break; case 640: height = 480; break; @@ -134,7 +146,7 @@ void picodvi_autoconstruct(void) { // invalid configuration, set back to default width = default_width; height = default_height; - color_depth = 16; + color_depth = 8; } // construct framebuffer and display @@ -159,6 +171,14 @@ void picodvi_autoconstruct(void) { MP_OBJ_FROM_PTR(fb), rotation, true); + + #if CIRCUITPY_PICODVI_AUDIOOUT + // Before the VM heap exists, so the audio buffers get internal RAM. On + // failure supervisor.runtime.audio is None, and the display still works. + if (audio) { + (void)picodvi_audioout_construct_board(fb); + } + #endif } #else void picodvi_autoconstruct(void) { diff --git a/ports/raspberrypi/common-hal/picodvi/dvi_audio_packet.c b/ports/raspberrypi/common-hal/picodvi/dvi_audio_packet.c new file mode 100644 index 00000000000..f6471fb1784 --- /dev/null +++ b/ports/raspberrypi/common-hal/picodvi/dvi_audio_packet.c @@ -0,0 +1,320 @@ +// SPDX-FileCopyrightText: 2026 fliperama86 +// +// SPDX-License-Identifier: Unlicense +// From https://github.com/fliperama86/pico_hdmi v0.0.6, with the AVI +// InfoFrame and channel status from v0.0.19. +// CircuitPython uses negative H/V sync at the 640-wide timings. + +#include "common-hal/picodvi/dvi_audio_packet.h" + +#include + +// ============================================================================ +// TERC4 Symbol Table (4-bit to 10-bit encoding) +// ============================================================================ + +static const uint16_t ter_c4[16] = { + 0b1010011100, // 0 + 0b1001100011, // 1 + 0b1011100100, // 2 + 0b1011100010, // 3 + 0b0101110001, // 4 + 0b0100011110, // 5 + 0b0110001110, // 6 + 0b0100111100, // 7 + 0b1011001100, // 8 + 0b0100111001, // 9 + 0b0110011100, // 10 + 0b1011000110, // 11 + 0b1010001110, // 12 + 0b1001110001, // 13 + 0b0101100011, // 14 + 0b1011000011, // 15 +}; + +#define GUARD_BAND_SYMBOL 0x133u // 0b0100110011 + +// ============================================================================ +// BCH Encoding +// ============================================================================ + +static const uint8_t bch_table[256] = { + 0x00, 0xd9, 0xb5, 0x6c, 0x6d, 0xb4, 0xd8, 0x01, 0xda, 0x03, 0x6f, 0xb6, 0xb7, 0x6e, 0x02, 0xdb, 0xb3, 0x6a, 0x06, + 0xdf, 0xde, 0x07, 0x6b, 0xb2, 0x69, 0xb0, 0xdc, 0x05, 0x04, 0xdd, 0xb1, 0x68, 0x61, 0xb8, 0xd4, 0x0d, 0x0c, 0xd5, + 0xb9, 0x60, 0xbb, 0x62, 0x0e, 0xd7, 0xd6, 0x0f, 0x63, 0xba, 0xd2, 0x0b, 0x67, 0xbe, 0xbf, 0x66, 0x0a, 0xd3, 0x08, + 0xd1, 0xbd, 0x64, 0x65, 0xbc, 0xd0, 0x09, 0xc2, 0x1b, 0x77, 0xae, 0xaf, 0x76, 0x1a, 0xc3, 0x18, 0xc1, 0xad, 0x74, + 0x75, 0xac, 0xc0, 0x19, 0x71, 0xa8, 0xc4, 0x1d, 0x1c, 0xc5, 0xa9, 0x70, 0xab, 0x72, 0x1e, 0xc7, 0xc6, 0x1f, 0x73, + 0xaa, 0xa3, 0x7a, 0x16, 0xcf, 0xce, 0x17, 0x7b, 0xa2, 0x79, 0xa0, 0xcc, 0x15, 0x14, 0xcd, 0xa1, 0x78, 0x10, 0xc9, + 0xa5, 0x7c, 0x7d, 0xa4, 0xc8, 0x11, 0xca, 0x13, 0x7f, 0xa6, 0xa7, 0x7e, 0x12, 0xcb, 0x83, 0x5a, 0x36, 0xef, 0xee, + 0x37, 0x5b, 0x82, 0x59, 0x80, 0xec, 0x35, 0x34, 0xed, 0x81, 0x58, 0x30, 0xe9, 0x85, 0x5c, 0x5d, 0x84, 0xe8, 0x31, + 0xea, 0x33, 0x5f, 0x86, 0x87, 0x5e, 0x32, 0xeb, 0xe2, 0x3b, 0x57, 0x8e, 0x8f, 0x56, 0x3a, 0xe3, 0x38, 0xe1, 0x8d, + 0x54, 0x55, 0x8c, 0xe0, 0x39, 0x51, 0x88, 0xe4, 0x3d, 0x3c, 0xe5, 0x89, 0x50, 0x8b, 0x52, 0x3e, 0xe7, 0xe6, 0x3f, + 0x53, 0x8a, 0x41, 0x98, 0xf4, 0x2d, 0x2c, 0xf5, 0x99, 0x40, 0x9b, 0x42, 0x2e, 0xf7, 0xf6, 0x2f, 0x43, 0x9a, 0xf2, + 0x2b, 0x47, 0x9e, 0x9f, 0x46, 0x2a, 0xf3, 0x28, 0xf1, 0x9d, 0x44, 0x45, 0x9c, 0xf0, 0x29, 0x20, 0xf9, 0x95, 0x4c, + 0x4d, 0x94, 0xf8, 0x21, 0xfa, 0x23, 0x4f, 0x96, 0x97, 0x4e, 0x22, 0xfb, 0x93, 0x4a, 0x26, 0xff, 0xfe, 0x27, 0x4b, + 0x92, 0x49, 0x90, 0xfc, 0x25, 0x24, 0xfd, 0x91, 0x48, +}; + +static const uint8_t parity_table[32] = {0x96, 0x69, 0x69, 0x96, 0x69, 0x96, 0x96, 0x69, 0x69, 0x96, 0x96, + 0x69, 0x96, 0x69, 0x69, 0x96, 0x69, 0x96, 0x96, 0x69, 0x96, 0x69, + 0x69, 0x96, 0x96, 0x69, 0x69, 0x96, 0x69, 0x96, 0x96, 0x69}; + +static inline bool compute_parity(uint8_t v) { + return (parity_table[v / 8] >> (v % 8)) & 1; +} + +static inline bool compute_parity3(uint8_t a, uint8_t b, uint8_t c) { + return compute_parity(a) ^ compute_parity(b) ^ compute_parity(c); +} + +static uint8_t encode_bch_3(const uint8_t *p) { + uint8_t v = bch_table[p[0]]; + v = bch_table[p[1] ^ v]; + v = bch_table[p[2] ^ v]; + return v; +} + +static uint8_t encode_bch_7(const uint8_t *p) { + uint8_t v = bch_table[p[0]]; + v = bch_table[p[1] ^ v]; + v = bch_table[p[2] ^ v]; + v = bch_table[p[3] ^ v]; + v = bch_table[p[4] ^ v]; + v = bch_table[p[5] ^ v]; + v = bch_table[p[6] ^ v]; + return v; +} + +static void compute_header_parity(hstx_packet_t *p) { + p->header[3] = encode_bch_3(p->header); +} + +static void compute_subpacket_parity(hstx_packet_t *p, int idx) { + p->subpacket[idx][7] = encode_bch_7(p->subpacket[idx]); +} + +static void compute_all_parity(hstx_packet_t *p) { + compute_header_parity(p); + for (int i = 0; i < 4; i++) { + compute_subpacket_parity(p, i); + } +} + +static void compute_infoframe_checksum(hstx_packet_t *p) { + int sum = 0; + for (int i = 0; i < 3; i++) { + sum += p->header[i]; + } + int len = p->header[2] + 1; + for (int j = 0; j < 4 && len > 0; j++) { + for (int i = 0; i < 7 && len > 0; i++, len--) { + sum += p->subpacket[j][i]; + } + } + p->subpacket[0][0] = (uint8_t)(-sum); +} + +// ============================================================================ +// Public API +// ============================================================================ + +void hstx_packet_init(hstx_packet_t *packet) { + memset(packet, 0, sizeof(hstx_packet_t)); +} + +void hstx_packet_set_acr(hstx_packet_t *packet, uint32_t n, uint32_t cts) { + hstx_packet_init(packet); + packet->header[0] = 0x01; + packet->header[1] = 0x00; + packet->header[2] = 0x00; + compute_header_parity(packet); + + packet->subpacket[0][0] = 0; + packet->subpacket[0][1] = (cts >> 16) & 0x0F; + packet->subpacket[0][2] = (cts >> 8) & 0xFF; + packet->subpacket[0][3] = cts & 0xFF; + packet->subpacket[0][4] = (n >> 16) & 0x0F; + packet->subpacket[0][5] = (n >> 8) & 0xFF; + packet->subpacket[0][6] = n & 0xFF; + compute_subpacket_parity(packet, 0); + + memcpy(packet->subpacket[1], packet->subpacket[0], 8); + memcpy(packet->subpacket[2], packet->subpacket[0], 8); + memcpy(packet->subpacket[3], packet->subpacket[0], 8); +} + +void hstx_packet_set_audio_infoframe(hstx_packet_t *packet, uint32_t sample_rate, uint8_t channels, + uint8_t bits_per_sample) { + hstx_packet_init(packet); + packet->header[0] = 0x84; + packet->header[1] = 0x01; + packet->header[2] = 0x0A; + + uint8_t cc = (channels - 1) & 0x07; + uint8_t ct = 0x01; + uint8_t ss = + (bits_per_sample == 16) ? 0x01 : (bits_per_sample == 20 ? 0x02 : (bits_per_sample == 24 ? 0x03 : 0x00)); + uint8_t sf = (sample_rate == 32000) ? 0x01 : (sample_rate == 44100 ? 0x02 : (sample_rate == 48000 ? 0x03 : 0x00)); + + packet->subpacket[0][1] = cc | (ct << 4); + packet->subpacket[0][2] = ss | (sf << 2); + packet->subpacket[0][3] = 0x00; + packet->subpacket[0][4] = 0x00; + packet->subpacket[0][5] = 0x00; + + compute_infoframe_checksum(packet); + compute_all_parity(packet); +} + +void hstx_packet_set_avi_infoframe(hstx_packet_t *packet, uint8_t vic, uint8_t pixel_repetition) { + hstx_packet_init(packet); + packet->header[0] = 0x82; + packet->header[1] = 0x02; + packet->header[2] = 0x0D; + + packet->subpacket[0][1] = 0x10; // A=1: active format information is valid. + packet->subpacket[0][2] = 0x18; // 4:3 picture, same active format. + // PB3: Q (bits 3:2) = 10 declares full-range RGB quantization. + packet->subpacket[0][3] = 0x08; + packet->subpacket[0][4] = vic; + packet->subpacket[0][5] = pixel_repetition & 0x0F; + + compute_infoframe_checksum(packet); + compute_all_parity(packet); +} + +// IEC 60958-3 channel status byte 3 sample frequency code. +static uint8_t channel_status_sample_frequency(uint32_t sample_rate) { + switch (sample_rate) { + case 32000: + return 0x03; + case 44100: + return 0x00; + case 48000: + return 0x02; + default: + return 0x01; // Sample rate not indicated. + } +} + +int hstx_packet_set_audio_samples(hstx_packet_t *packet, const audio_sample_t *samples, int num_samples, + int frame_count, uint32_t sample_rate) { + hstx_packet_init(packet); + if (num_samples < 1) { + num_samples = 1; + } + if (num_samples > 4) { + num_samples = 4; + } + + uint8_t sample_present = (1 << num_samples) - 1; + uint8_t b_flags = 0; + + int temp_frame_count = frame_count; + for (int i = 0; i < num_samples; i++) { + if (temp_frame_count == 0) { + b_flags |= (1 << i); + } + temp_frame_count = (temp_frame_count + 1) % 192; + } + + packet->header[0] = 0x02; + packet->header[1] = sample_present; + packet->header[2] = b_flags << 4; + compute_header_parity(packet); + + uint8_t sample_frequency = channel_status_sample_frequency(sample_rate); + for (int i = 0; i < num_samples; i++) { + uint8_t *d = packet->subpacket[i]; + int16_t left = samples[i].left; + int16_t right = samples[i].right; + + d[0] = 0x00; + d[1] = left & 0xFF; + d[2] = (left >> 8) & 0xFF; + d[3] = 0x00; + d[4] = right & 0xFF; + d[5] = (right >> 8) & 0xFF; + + // IEC 60958 byte 0 = 0x04 (copy permitted), byte 3 = sample frequency. + int frame = (frame_count + i) % 192; + uint8_t status = frame / 8 == 0 ? 0x04 : (frame / 8 == 3 ? sample_frequency : 0); + uint8_t c = (status >> (frame % 8)) & 1; + bool p_left = compute_parity3(d[1], d[2], c); + bool p_right = compute_parity3(d[4], d[5], c); + d[6] = (c << 2) | (p_left << 3) | (c << 6) | (p_right << 7); + compute_subpacket_parity(packet, i); + } + + return temp_frame_count; +} + +static inline uint32_t make_hstx_word(uint16_t lane0, uint16_t lane1, uint16_t lane2) { + return (lane0 & 0x3FF) | ((lane1 & 0x3FF) << 10) | ((lane2 & 0x3FF) << 20); +} + +static void encode_header_to_lane0(const hstx_packet_t *packet, uint16_t *lane0, int hv, bool first_packet) { + int hv1 = hv | 0x08; + if (!first_packet) { + hv = hv1; + } + + int idx = 0; + for (int i = 0; i < 4; i++) { + uint8_t h = packet->header[i]; + lane0[idx++] = ter_c4[((h << 2) & 4) | hv]; + hv = hv1; + lane0[idx++] = ter_c4[((h << 1) & 4) | hv]; + lane0[idx++] = ter_c4[(h & 4) | hv]; + lane0[idx++] = ter_c4[((h >> 1) & 4) | hv]; + lane0[idx++] = ter_c4[((h >> 2) & 4) | hv]; + lane0[idx++] = ter_c4[((h >> 3) & 4) | hv]; + lane0[idx++] = ter_c4[((h >> 4) & 4) | hv]; + lane0[idx++] = ter_c4[((h >> 5) & 4) | hv]; + } +} + +static void encode_subpackets_to_lanes(const hstx_packet_t *packet, uint16_t *lane1, uint16_t *lane2) { + for (int i = 0; i < 8; i++) { + uint32_t v = ((uint32_t)packet->subpacket[0][i] << 0) | ((uint32_t)packet->subpacket[1][i] << 8) | ((uint32_t)packet->subpacket[2][i] << 16) | + ((uint32_t)packet->subpacket[3][i] << 24); + uint32_t t = (v ^ (v >> 7)) & 0x00aa00aa; + v = v ^ t ^ (t << 7); + t = (v ^ (v >> 14)) & 0x0000cccc; + v = v ^ t ^ (t << 14); + + lane1[(i * 4) + 0] = ter_c4[(v >> 0) & 0xF]; + lane1[(i * 4) + 1] = ter_c4[(v >> 16) & 0xF]; + lane1[(i * 4) + 2] = ter_c4[(v >> 4) & 0xF]; + lane1[(i * 4) + 3] = ter_c4[(v >> 20) & 0xF]; + + lane2[(i * 4) + 0] = ter_c4[(v >> 8) & 0xF]; + lane2[(i * 4) + 1] = ter_c4[(v >> 24) & 0xF]; + lane2[(i * 4) + 2] = ter_c4[(v >> 12) & 0xF]; + lane2[(i * 4) + 3] = ter_c4[(v >> 28) & 0xF]; + } +} + +void hstx_encode_data_island(hstx_data_island_t *out, const hstx_packet_t *packet, bool vsync_active, bool hsync_active) { + // vsync_active/hsync_active indicate pulse region, not wire level. + // The hv field encodes the actual wire bits (bit1=vsync, bit0=hsync), + // inverted because the 640-wide modes use negative sync. + int hv = (vsync_active ? 0 : 2) | (hsync_active ? 0 : 1); + uint16_t lane0[32]; + uint16_t lane1[32]; + uint16_t lane2[32]; + + encode_header_to_lane0(packet, lane0, hv, true); + encode_subpackets_to_lanes(packet, lane1, lane2); + + uint16_t gb_lane0 = ter_c4[0xC | hv]; + uint32_t guard_word = make_hstx_word(gb_lane0, GUARD_BAND_SYMBOL, GUARD_BAND_SYMBOL); + + out->words[0] = guard_word; + out->words[1] = guard_word; + for (int i = 0; i < 32; i++) { + out->words[i + 2] = make_hstx_word(lane0[i], lane1[i], lane2[i]); + } + out->words[34] = guard_word; + out->words[35] = guard_word; +} diff --git a/ports/raspberrypi/common-hal/picodvi/dvi_audio_packet.h b/ports/raspberrypi/common-hal/picodvi/dvi_audio_packet.h new file mode 100644 index 00000000000..c7cc33aa20b --- /dev/null +++ b/ports/raspberrypi/common-hal/picodvi/dvi_audio_packet.h @@ -0,0 +1,39 @@ +// SPDX-FileCopyrightText: 2026 fliperama86 +// +// SPDX-License-Identifier: Unlicense +// From https://github.com/fliperama86/pico_hdmi v0.0.6, with the AVI +// InfoFrame and channel status from v0.0.19. +// CircuitPython uses negative H/V sync at the 640-wide timings. + +#pragma once + +#include +#include + +// One HSTX word per symbol: 2 guard band, 32 packet, 2 guard band. +#define HSTX_DATA_ISLAND_WORDS 36 + +// Data island packet: header and four subpackets, each with BCH parity. +typedef struct { + uint8_t header[4]; // 3 bytes header + 1 byte BCH parity + uint8_t subpacket[4][8]; // 4 subpackets, each 7 bytes + 1 byte BCH parity +} hstx_packet_t; + +// Pre-encoded data island for HSTX (36 words) +typedef struct { + uint32_t words[HSTX_DATA_ISLAND_WORDS]; +} hstx_data_island_t; + +// Audio sample structure +typedef struct { + int16_t left; + int16_t right; +} audio_sample_t; + +void hstx_packet_init(hstx_packet_t *packet); +void hstx_packet_set_acr(hstx_packet_t *packet, uint32_t n, uint32_t cts); +void hstx_packet_set_audio_infoframe(hstx_packet_t *packet, uint32_t sample_rate, uint8_t channels, uint8_t bits_per_sample); +void hstx_packet_set_avi_infoframe(hstx_packet_t *packet, uint8_t vic, uint8_t pixel_repetition); +int hstx_packet_set_audio_samples(hstx_packet_t *packet, const audio_sample_t *samples, int num_samples, int frame_count, + uint32_t sample_rate); +void hstx_encode_data_island(hstx_data_island_t *out, const hstx_packet_t *packet, bool vsync_active, bool hsync_active); diff --git a/ports/raspberrypi/common-hal/picogame3d/interp.c b/ports/raspberrypi/common-hal/picogame3d/interp.c new file mode 100644 index 00000000000..e79d11b3e06 --- /dev/null +++ b/ports/raspberrypi/common-hal/picogame3d/interp.c @@ -0,0 +1,54 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +// Mode-7 inner row via the SIO INTERPOLATOR (RP2040 + RP2350). The interpolator does the +// whole per-pixel texture walk in hardware: lane0 = (fx >> shx) & (tw-1), lane1 = +// ((fy >> shy) & (th-1)) << log2(tw), POP_FULL = texture_base + lane0 + lane1 = the texel +// ADDRESS, and (ADD_RAW) both accumulators advance by their full-precision steps on the +// same pop. That replaces ~8 shift/mask/mul/add ops per pixel with one SIO read. +// +// Per-CORE hardware: each core has its own interp0, so this stays safe even if rows are +// ever split across cores (each configures its own). The engine claims no SDK +// lane locks: CircuitPython core does not use the interpolators, and the config is +// rewritten per row call anyway. +// +// Fast path constraints (the caller guards): PAL8 texture, no transparency, stride == tw, +// log2(tw)+log2(th) <= 16 (mode7 textures are 64..256 pow2 - always true there). + +#include "py/mpconfig.h" + +#if CIRCUITPY_PICOGAME3D + +#include +#include "hardware/interp.h" +#include "shared-module/picogame3d/__init__.h" // the prototype (PICOGAME_HAS_INTERP) + +void picogame3d_mode7_row_interp(uint16_t *dst, int n, + const uint8_t *tex, const uint16_t *pal, + uint32_t fx, uint32_t fy, int32_t stepx, int32_t stepy, + int shx, int shy, int ltw, int lth) { + interp_config c0 = interp_default_config(); + interp_config_set_shift(&c0, (uint)shx); + interp_config_set_mask(&c0, 0, (uint)(ltw - 1)); + interp_config_set_add_raw(&c0, true); // accumulator advances by the RAW step + interp_set_config(interp0, 0, &c0); + interp_config c1 = interp_default_config(); + interp_config_set_shift(&c1, (uint)(shy - ltw)); + interp_config_set_mask(&c1, (uint)ltw, (uint)(ltw + lth - 1)); + interp_config_set_add_raw(&c1, true); + interp_set_config(interp0, 1, &c1); + interp0->base[0] = (uint32_t)stepx; + interp0->base[1] = (uint32_t)stepy; + interp0->base[2] = (uint32_t)(uintptr_t)tex; + interp0->accum[0] = fx; + interp0->accum[1] = fy; + for (int i = 0; i < n; i++) { + const uint8_t *p = (const uint8_t *)interp0->pop[2]; + dst[i] = pal[*p]; + } +} + +#endif diff --git a/ports/raspberrypi/common-hal/pulseio/PulseIn.c b/ports/raspberrypi/common-hal/pulseio/PulseIn.c index b56c90a9a53..c0f14e186a6 100644 --- a/ports/raspberrypi/common-hal/pulseio/PulseIn.c +++ b/ports/raspberrypi/common-hal/pulseio/PulseIn.c @@ -23,14 +23,20 @@ static const uint16_t pulsein_program[] = { 0x4001, // 1: in pins, 1 }; +static void mark_deinit(pulseio_pulsein_obj_t *self) { + self->pin = NO_PIN; +} + void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t *self, const mcu_pin_obj_t *pin, uint16_t maxlen, bool idle_state) { + // Ensure the object starts in its deinit state, so its finaliser does + // nothing if this raises before the pin is set. + mark_deinit(self); - self->buffer = (uint16_t *)m_malloc(maxlen * sizeof(uint16_t)); + self->buffer = (uint16_t *)m_malloc_without_collect(maxlen * sizeof(uint16_t)); if (self->buffer == NULL) { m_malloc_fail(maxlen * sizeof(uint16_t)); } - self->pin = pin->number; self->maxlen = maxlen; self->idle_state = idle_state; self->start = 0; @@ -57,6 +63,8 @@ void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t *self, PIO_ANY_OFFSET, PIO_FIFO_TYPE_DEFAULT, PIO_MOV_STATUS_DEFAULT, PIO_MOV_N_DEFAULT); + // Set the pin only now: deinit uses the state machine. + self->pin = pin->number; common_hal_pulseio_pulsein_pause(self); @@ -77,7 +85,7 @@ void common_hal_pulseio_pulsein_deinit(pulseio_pulsein_obj_t *self) { common_hal_rp2pio_statemachine_deinit(&self->state_machine); m_free(self->buffer); reset_pin_number(self->pin); - self->pin = NO_PIN; + mark_deinit(self); } void common_hal_pulseio_pulsein_pause(pulseio_pulsein_obj_t *self) { diff --git a/ports/raspberrypi/common-hal/pwmio/PWMOut.c b/ports/raspberrypi/common-hal/pwmio/PWMOut.c index 9ceb5a0185d..4d2a4c167f1 100644 --- a/ports/raspberrypi/common-hal/pwmio/PWMOut.c +++ b/ports/raspberrypi/common-hal/pwmio/PWMOut.c @@ -22,7 +22,6 @@ uint32_t slice_variable_frequency; #define AB_CHANNELS_PER_SLICE 2 static uint32_t channel_use; -static uint32_t never_reset_channel; // Per the RP2040 datasheet: // @@ -63,10 +62,6 @@ void pwmio_release_slice_ab_channels(uint8_t slice) { channel_use &= ~channel_mask; } -void common_hal_pwmio_pwmout_never_reset(pwmio_pwmout_obj_t *self) { - never_reset_pin_number(self->pin->number); -} - pwmout_result_t pwmout_allocate(uint8_t slice, uint8_t ab_channel, bool variable_frequency, uint32_t frequency) { uint32_t channel_use_mask = _mask(slice, ab_channel); @@ -78,7 +73,7 @@ pwmout_result_t pwmout_allocate(uint8_t slice, uint8_t ab_channel, bool variable if (target_slice_frequencies[slice] > 0) { // If we want to change frequency then we can't share. if (variable_frequency) { - return PWMOUT_VARIABLE_FREQUENCY_NOT_AVAILABLE; + return PWMOUT_INTERNAL_RESOURCES_IN_USE; } // If the other user wants a variable frequency then we can't share either. if ((slice_variable_frequency & (1 << slice)) != 0) { @@ -86,7 +81,7 @@ pwmout_result_t pwmout_allocate(uint8_t slice, uint8_t ab_channel, bool variable } // If we're both fixed frequency but we don't match target frequencies then we can't share. if (target_slice_frequencies[slice] != frequency) { - return PWMOUT_INVALID_FREQUENCY_ON_PIN; + return PWMOUT_INTERNAL_RESOURCES_IN_USE; } } @@ -147,7 +142,6 @@ bool common_hal_pwmio_pwmout_deinited(pwmio_pwmout_obj_t *self) { void pwmout_free(uint8_t slice, uint8_t ab_channel) { uint32_t channel_mask = _mask(slice, ab_channel); channel_use &= ~channel_mask; - never_reset_channel &= ~channel_mask; uint32_t slice_mask = ((1 << AB_CHANNELS_PER_SLICE) - 1) << (slice * AB_CHANNELS_PER_SLICE); if ((channel_use & slice_mask) == 0) { target_slice_frequencies[slice] = 0; diff --git a/ports/raspberrypi/common-hal/rgbmatrix/RGBMatrix.c b/ports/raspberrypi/common-hal/rgbmatrix/RGBMatrix.c index 875da343251..a0fccd8e20b 100644 --- a/ports/raspberrypi/common-hal/rgbmatrix/RGBMatrix.c +++ b/ports/raspberrypi/common-hal/rgbmatrix/RGBMatrix.c @@ -50,5 +50,10 @@ void common_hal_rgbmatrix_timer_free(void *ptr) { irq_set_enabled(PWM_IRQ_WRAP, false); pwm_clear_irq(slice); pwmout_free(slice, channel); - return; + // Protomatter installs an exclusive wrap handler. Remove it, so something + // else (countio) can install its own later. + irq_handler_t handler = irq_get_exclusive_handler(PWM_IRQ_WRAP); + if (handler != NULL) { + irq_remove_handler(PWM_IRQ_WRAP, handler); + } } diff --git a/ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c b/ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c index 113bd1900dd..d71ff60b2eb 100644 --- a/ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c +++ b/ports/raspberrypi/common-hal/rotaryio/IncrementalEncoder.c @@ -43,6 +43,9 @@ void common_hal_rotaryio_incrementalencoder_construct(rotaryio_incrementalencode const mcu_pin_obj_t *pin_a, const mcu_pin_obj_t *pin_b) { const mcu_pin_obj_t *pins[] = { pin_a, pin_b }; + // Ensure object starts in its deinit state. + common_hal_rotaryio_incrementalencoder_mark_deinit(self); + // Start out with swapped to match behavior with other ports. self->swapped = true; if (!common_hal_rp2pio_pins_are_sequential(2, pins)) { @@ -89,6 +92,7 @@ void common_hal_rotaryio_incrementalencoder_construct(rotaryio_incrementalencode } bool common_hal_rotaryio_incrementalencoder_deinited(rotaryio_incrementalencoder_obj_t *self) { + // Use the deinit state of the PIO state machine. return common_hal_rp2pio_statemachine_deinited(&self->state_machine); } @@ -100,6 +104,11 @@ void common_hal_rotaryio_incrementalencoder_deinit(rotaryio_incrementalencoder_o common_hal_rp2pio_statemachine_deinit(&self->state_machine); } +void common_hal_rotaryio_incrementalencoder_mark_deinit(rotaryio_incrementalencoder_obj_t *self) { + // Use the deinit state of the PIO state machine. + common_hal_rp2pio_statemachine_mark_deinit(&self->state_machine); +} + static void incrementalencoder_interrupt_handler(void *self_in) { rotaryio_incrementalencoder_obj_t *self = self_in; diff --git a/ports/raspberrypi/common-hal/rp2pio/StateMachine.c b/ports/raspberrypi/common-hal/rp2pio/StateMachine.c index 3e4579fe49d..0219b395aaa 100644 --- a/ports/raspberrypi/common-hal/rp2pio/StateMachine.c +++ b/ports/raspberrypi/common-hal/rp2pio/StateMachine.c @@ -33,7 +33,6 @@ static uint8_t _pin_reference_count[NUM_BANK0_GPIOS]; static uint32_t _current_program_id[NUM_PIOS][NUM_PIO_STATE_MACHINES]; static uint8_t _current_program_offset[NUM_PIOS][NUM_PIO_STATE_MACHINES]; static uint8_t _current_program_len[NUM_PIOS][NUM_PIO_STATE_MACHINES]; -static bool _never_reset[NUM_PIOS][NUM_PIO_STATE_MACHINES]; static pio_pinmask_t _current_pins[NUM_PIOS]; static pio_pinmask_t _current_sm_pins[NUM_PIOS][NUM_PIO_STATE_MACHINES]; @@ -68,14 +67,69 @@ static void rp2pio_statemachine_set_pull(pio_pinmask_t pull_pin_up, pio_pinmask_ } } +// audio_dma and rp2pio cooperate on DMA_IRQ_0 using the SDK's shared interrupt +// handlers. We add our handler when we enable our first channel and remove it +// when our last channel is disabled. See the DMA IRQ allocation notes in +// common-hal/microcontroller/__init__.c. + +// Shared DMA_IRQ_0 handler for rp2pio background reads and writes. It +// acknowledges and services only its own channels, leaving any other channels' +// interrupts (e.g. audio) for the other shared handlers to acknowledge. +static void __not_in_flash_func(rp2pio_dma_irq_handler)(void) { + for (size_t i = 0; i < NUM_DMA_CHANNELS; i++) { + uint32_t mask = 1 << i; + if ((dma_hw->ints0 & mask) == 0) { + continue; + } + rp2pio_statemachine_obj_t *read = MP_STATE_PORT(background_pio_read)[i]; + rp2pio_statemachine_obj_t *write = MP_STATE_PORT(background_pio_write)[i]; + if (read == NULL && write == NULL) { + // Not one of our channels; leave it for another shared handler. + continue; + } + // Acknowledge the interrupt early; see the comment in audio_dma.c. + dma_hw->ints0 = mask; + if (read != NULL) { + rp2pio_statemachine_dma_complete_read(read, i); + } + if (write != NULL) { + rp2pio_statemachine_dma_complete_write(write, i); + } + } +} + +// Channels (bitmask) rp2pio currently has enabled on DMA_IRQ_0. Used to decide +// when to add/remove our shared interrupt handler. +static uint32_t rp2pio_dma_irq0_channel_mask = 0; + +static void rp2pio_dma_enable_irq(uint channel) { + // Clear any latent interrupt so that we don't immediately re-trigger. + dma_hw->ints0 = 1u << channel; + if (rp2pio_dma_irq0_channel_mask == 0) { + irq_add_shared_handler(DMA_IRQ_0, rp2pio_dma_irq_handler, + PICO_SHARED_IRQ_HANDLER_DEFAULT_ORDER_PRIORITY); + } + rp2pio_dma_irq0_channel_mask |= 1u << channel; + dma_irqn_set_channel_enabled(0, channel, true); + irq_set_enabled(DMA_IRQ_0, true); +} + +static void rp2pio_dma_disable_irq(uint channel) { + dma_irqn_set_channel_enabled(0, channel, false); + rp2pio_dma_irq0_channel_mask &= ~(1u << channel); + if (rp2pio_dma_irq0_channel_mask == 0) { + irq_remove_handler(DMA_IRQ_0, rp2pio_dma_irq_handler); + } + // Turn off the IRQ line entirely once no one (audio or rp2pio) needs it. + if (dma_hw->inte0 == 0) { + irq_set_enabled(DMA_IRQ_0, false); + } +} + static void rp2pio_statemachine_clear_dma_write(int pio_index, int sm) { if (SM_DMA_ALLOCATED_WRITE(pio_index, sm)) { int channel_write = SM_DMA_GET_CHANNEL_WRITE(pio_index, sm); - uint32_t channel_mask_write = 1u << channel_write; - dma_hw->inte0 &= ~channel_mask_write; - if (!dma_hw->inte0) { - irq_set_mask_enabled(1 << DMA_IRQ_0, false); - } + rp2pio_dma_disable_irq(channel_write); MP_STATE_PORT(background_pio_write)[channel_write] = NULL; dma_channel_abort(channel_write); dma_channel_unclaim(channel_write); @@ -86,11 +140,7 @@ static void rp2pio_statemachine_clear_dma_write(int pio_index, int sm) { static void rp2pio_statemachine_clear_dma_read(int pio_index, int sm) { if (SM_DMA_ALLOCATED_READ(pio_index, sm)) { int channel_read = SM_DMA_GET_CHANNEL_READ(pio_index, sm); - uint32_t channel_mask_read = 1u << channel_read; - dma_hw->inte0 &= ~channel_mask_read; - if (!dma_hw->inte0) { - irq_set_mask_enabled(1 << DMA_IRQ_0, false); - } + rp2pio_dma_disable_irq(channel_read); MP_STATE_PORT(background_pio_read)[channel_read] = NULL; dma_channel_abort(channel_read); dma_channel_unclaim(channel_read); @@ -140,25 +190,6 @@ static void _reset_statemachine(PIO pio, uint8_t sm, bool leave_pins) { pio_sm_unclaim(pio, sm); } -void reset_rp2pio_statemachine(void) { - for (size_t i = 0; i < NUM_PIOS; i++) { - PIO pio = pio_get_instance(i); - for (size_t j = 0; j < NUM_PIO_STATE_MACHINES; j++) { - if (_never_reset[i][j]) { - continue; - } - _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 pio_pinmask_t _check_pins_free(const mcu_pin_obj_t *first_pin, uint8_t pin_count, bool exclusive_pin_use) { pio_pinmask_t pins_we_use = PIO_PINMASK_NONE; if (first_pin != NULL) { @@ -181,6 +212,24 @@ static pio_pinmask_t _check_pins_free(const mcu_pin_obj_t *first_pin, uint8_t pi return pins_we_use; } +// Same as _check_pins_free but over an explicit GPIO mask, for pins a program +// only waits on. Sharing with another state machine is always allowed for +// these; the caller isn't driving them. +static void _check_gpio_mask_free(pio_pinmask_t mask) { + for (size_t pin_number = 0; pin_number < NUM_BANK0_GPIOS; pin_number++) { + if (!PIO_PINMASK_IS_SET(mask, pin_number)) { + continue; + } + const mcu_pin_obj_t *pin = mcu_get_pin_by_number(pin_number); + if (!pin) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("%q in use"), MP_QSTR_Pin); + } + if (_pin_reference_count[pin_number] == 0) { + assert_pin_free(pin); + } + } +} + static enum pio_fifo_join compute_fifo_type(int fifo_type_in, bool rx_fifo, bool tx_fifo) { if (fifo_type_in != PIO_FIFO_JOIN_AUTO) { return fifo_type_in; @@ -222,18 +271,60 @@ static bool is_gpio_compatible(PIO pio, uint32_t used_gpio_ranges) { #endif } -static bool use_existing_program(PIO *pio_out, int *sm_out, int *offset_inout, uint32_t program_id, size_t program_len, uint gpio_base, uint gpio_count) { - uint32_t required_gpio_ranges; - if (gpio_count) { - required_gpio_ranges = (1u << (gpio_base >> 4)) | - (1u << ((gpio_base + gpio_count - 1) >> 4)); - } else { - required_gpio_ranges = 0; +static uint32_t required_gpio_ranges(uint gpio_base, uint gpio_count) { + if (!gpio_count) { + return 0; + } + return (1u << (gpio_base >> 4)) | + (1u << ((gpio_base + gpio_count - 1) >> 4)); +} + +// Look for a PIO that already uses some of the pins we need. The cross-PIO +// overlap check in rp2pio_statemachine_construct fails a construct outright +// when its pins live on another PIO, so a generic claim can hand us a PIO that +// can't work while a usable one sits idle. +static bool use_pio_owning_pins(PIO *pio_out, int *sm_out, int *offset_inout, pio_program_t *program_struct, pio_pinmask_t pins_we_use, uint gpio_base, uint gpio_count) { + if (PIO_PINMASK_VALUE(pins_we_use) == 0) { + return false; + } + uint32_t ranges = required_gpio_ranges(gpio_base, gpio_count); + for (size_t i = 0; i < NUM_PIOS; i++) { + PIO pio = pio_get_instance(i); + if (PIO_PINMASK_VALUE(PIO_PINMASK_AND(_current_pins[i], pins_we_use)) == 0) { + continue; + } + if (!is_gpio_compatible(pio, ranges) || !pio_can_add_program(pio, program_struct)) { + continue; + } + int sm = pio_claim_unused_sm(pio, false); + if (sm < 0) { + continue; + } + *pio_out = pio; + *sm_out = sm; + *offset_inout = pio_add_program(pio, program_struct); + return true; + } + return false; +} + +// FNV-1a over the instruction words. Never returns 0, which _current_program_id +// uses to mean "no program". +static uint32_t program_hash(const uint16_t *program, size_t program_len) { + uint32_t hash = 0x811c9dc5; + for (size_t i = 0; i < program_len; i++) { + hash = (hash ^ (program[i] & 0xff)) * 0x01000193; + hash = (hash ^ (program[i] >> 8)) * 0x01000193; } + return hash == 0 ? 1 : hash; +} + +static bool use_existing_program(PIO *pio_out, int *sm_out, int *offset_inout, uint32_t program_id, size_t program_len, uint gpio_base, uint gpio_count) { + uint32_t ranges = required_gpio_ranges(gpio_base, gpio_count); for (size_t i = 0; i < NUM_PIOS; i++) { PIO pio = pio_get_instance(i); - if (!is_gpio_compatible(pio, required_gpio_ranges)) { + if (!is_gpio_compatible(pio, ranges)) { continue; } for (size_t j = 0; j < NUM_PIO_STATE_MACHINES; j++) { @@ -275,8 +366,14 @@ bool rp2pio_statemachine_construct(rp2pio_statemachine_obj_t *self, int fifo_type, int mov_status_type, int mov_status_n ) { - // 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); + // Create a program id we can store without storing the original object. + // This has to hash the instructions rather than the pointer: programs that + // encode absolute pin numbers (`wait gpio`) are assembled into a caller's + // stack buffer, so two different programs can share an address, and + // use_existing_program() would then hand the second one the first one's + // already-loaded instructions. Hashing the contents also lets identical + // programs from different arrays share a single copy in instruction memory. + uint32_t program_id = program_hash(program, program_len); uint gpio_base = 0, gpio_count = 0; #if NUM_BANK0_GPIOS > 32 @@ -310,9 +407,15 @@ bool rp2pio_statemachine_construct(rp2pio_statemachine_obj_t *self, int state_machine; bool added = false; - if (!use_existing_program(&pio, &state_machine, &offset, program_id, program_len, gpio_base, gpio_count)) { + if (use_existing_program(&pio, &state_machine, &offset, program_id, program_len, gpio_base, gpio_count)) { + // Program is already loaded and shareable; nothing to add. + } else if (use_pio_owning_pins(&pio, &state_machine, &offset, &program_struct, pins_we_use, gpio_base, gpio_count)) { + added = true; + } else { uint program_offset; - bool r = pio_claim_free_sm_and_add_program_for_gpio_range(&program_struct, &pio, (uint *)&state_machine, &program_offset, gpio_base, gpio_count, true); + bool r = gpio_count + ? pio_claim_free_sm_and_add_program_for_gpio_range(&program_struct, &pio, (uint *)&state_machine, &program_offset, gpio_base, gpio_count, true) + : pio_claim_free_sm_and_add_program(&program_struct, &pio, (uint *)&state_machine, &program_offset); if (!r) { return false; } @@ -347,9 +450,20 @@ bool rp2pio_statemachine_construct(rp2pio_statemachine_obj_t *self, _current_sm_pins[pio_index][state_machine] = pins_we_use; PIO_PINMASK_MERGE(_current_pins[pio_index], pins_we_use); - pio_sm_set_pins_with_mask64(self->pio, state_machine, PIO_PINMASK_VALUE(initial_pin_state), PIO_PINMASK_VALUE(pins_we_use)); - pio_sm_set_pindirs_with_mask64(self->pio, state_machine, PIO_PINMASK_VALUE(initial_pin_direction), PIO_PINMASK_VALUE(pins_we_use)); - rp2pio_statemachine_set_pull(pull_pin_up, pull_pin_down, pins_we_use); + // Only configure the pins no other state machine has claimed yet. A shared + // pin that this state machine doesn't drive (a clock it only waits on, say) + // would otherwise be forced back to input, clobbering its owner's setup. + pio_pinmask_t pins_we_own = PIO_PINMASK_NONE; + for (size_t pin_number = 0; pin_number < NUM_BANK0_GPIOS; pin_number++) { + if (PIO_PINMASK_IS_SET(pins_we_use, pin_number) && _pin_reference_count[pin_number] == 0) { + PIO_PINMASK_SET(pins_we_own, pin_number); + } + } + self->pins_we_own = pins_we_own; + + pio_sm_set_pins_with_mask64(self->pio, state_machine, PIO_PINMASK_VALUE(initial_pin_state), PIO_PINMASK_VALUE(pins_we_own)); + pio_sm_set_pindirs_with_mask64(self->pio, state_machine, PIO_PINMASK_VALUE(initial_pin_direction), PIO_PINMASK_VALUE(pins_we_own)); + rp2pio_statemachine_set_pull(pull_pin_up, pull_pin_down, pins_we_own); self->initial_pin_state = initial_pin_state; self->initial_pin_direction = initial_pin_direction; self->pull_pin_up = pull_pin_up; @@ -386,7 +500,7 @@ bool rp2pio_statemachine_construct(rp2pio_statemachine_obj_t *self, } uint64_t frequency256 = ((uint64_t)clock_get_hz(clk_sys)) * 256; uint64_t div256 = frequency256 / frequency; - if (frequency256 % div256 > 0) { + if (frequency256 % frequency > 0) { div256 += 1; } self->actual_frequency = frequency256 / div256; @@ -465,8 +579,9 @@ bool rp2pio_statemachine_construct(rp2pio_statemachine_obj_t *self, sm_config_set_fifo_join(&c, join); + sm_config_set_mov_status(&c, mov_status_type, mov_status_n); + // TODO: these arguments - // int mov_status_type, int mov_status_n, // int set_count, int out_count self->sm_config = c; @@ -522,9 +637,10 @@ static void consider_instruction(introspect_t *state, uint16_t full_instruction, } } if (instruction == pio_instr_bits_wait) { - uint16_t wait_source = (full_instruction & 0x0060) >> 5; - uint16_t wait_index = (full_instruction & 0x001f) + state->inputs.pio_gpio_offset; - if (wait_source == 0 && !PIO_PINMASK_IS_SET(state->inputs.pins_we_use, wait_index)) { // GPIO + const uint16_t wait_source = (full_instruction & 0x0060) >> 5; + const uint16_t wait_index = full_instruction & 0x001f; + const uint16_t wait_pin = wait_index + state->inputs.pio_gpio_offset; + if (wait_source == 0 && !PIO_PINMASK_IS_SET(state->inputs.pins_we_use, wait_pin)) { // GPIO mp_raise_ValueError_varg(MP_ERROR_TEXT("%q[%u] uses extra pin"), what_program, i); } else if (wait_source == 1) { // Input pin if (!state->inputs.has_in_pin) { @@ -626,7 +742,13 @@ void common_hal_rp2pio_statemachine_construct(rp2pio_statemachine_obj_t *self, int mov_status_type, int mov_status_n) { + // Ensure object starts in its deinit state. + common_hal_rp2pio_statemachine_mark_deinit(self); + // No background read has started, so there is none pending. + self->dma_completed_read = true; + // First, check that all pins are free OR already in use by any PIO if exclusive_pin_use is false. + _check_gpio_mask_free(wait_gpio_mask); pio_pinmask_t pins_we_use = wait_gpio_mask; PIO_PINMASK_MERGE(pins_we_use, _check_pins_free(first_out_pin, out_pin_count, exclusive_pin_use)); PIO_PINMASK_MERGE(pins_we_use, _check_pins_free(first_in_pin, in_pin_count, exclusive_pin_use)); @@ -742,7 +864,7 @@ void common_hal_rp2pio_statemachine_construct(rp2pio_statemachine_obj_t *self, mov_status_type, mov_status_n); if (!ok) { // indicate state machine never inited - self->state_machine = NUM_PIO_STATE_MACHINES; + common_hal_rp2pio_statemachine_mark_deinit(self); mp_raise_RuntimeError(MP_ERROR_TEXT("All state machines in use")); } } @@ -753,11 +875,10 @@ void common_hal_rp2pio_statemachine_restart(rp2pio_statemachine_obj_t *self) { // the desired offset, so we can just use self->offset. pio_sm_exec(self->pio, self->state_machine, self->offset); pio_sm_restart(self->pio, self->state_machine); - uint8_t pio_index = pio_get_index(self->pio); - pio_pinmask_t pins_we_use = _current_sm_pins[pio_index][self->state_machine]; - pio_sm_set_pins_with_mask64(self->pio, self->state_machine, PIO_PINMASK_VALUE(self->initial_pin_state), PIO_PINMASK_VALUE(pins_we_use)); - pio_sm_set_pindirs_with_mask64(self->pio, self->state_machine, PIO_PINMASK_VALUE(self->initial_pin_direction), PIO_PINMASK_VALUE(pins_we_use)); - rp2pio_statemachine_set_pull(self->pull_pin_up, self->pull_pin_down, pins_we_use); + pio_pinmask_t pins_we_own = self->pins_we_own; + pio_sm_set_pins_with_mask64(self->pio, self->state_machine, PIO_PINMASK_VALUE(self->initial_pin_state), PIO_PINMASK_VALUE(pins_we_own)); + pio_sm_set_pindirs_with_mask64(self->pio, self->state_machine, PIO_PINMASK_VALUE(self->initial_pin_direction), PIO_PINMASK_VALUE(pins_we_own)); + rp2pio_statemachine_set_pull(self->pull_pin_up, self->pull_pin_down, pins_we_own); common_hal_rp2pio_statemachine_run(self, self->init, self->init_len); pio_sm_set_enabled(self->pio, self->state_machine, true); } @@ -782,7 +903,7 @@ void common_hal_rp2pio_statemachine_set_frequency(rp2pio_statemachine_obj_t *sel } uint64_t frequency256 = ((uint64_t)clock_get_hz(clk_sys)) * 256; uint64_t div256 = frequency256 / frequency; - if (frequency256 % div256 > 0) { + if (frequency256 % frequency > 0) { div256 += 1; } // 0 is interpreted as 0x10000 so it's valid. @@ -796,17 +917,44 @@ void common_hal_rp2pio_statemachine_set_frequency(rp2pio_statemachine_obj_t *sel pio_sm_clkdiv_restart(self->pio, self->state_machine); } -void rp2pio_statemachine_reset_ok(PIO pio, int sm) { - uint8_t pio_index = pio_get_index(pio); - _never_reset[pio_index][sm] = false; -} - -void rp2pio_statemachine_never_reset(PIO pio, int sm) { - uint8_t pio_index = pio_get_index(pio); - _never_reset[pio_index][sm] = true; +// Pick a PIO that has room for a program of program_size instructions and at +// least sm_count free state machines; returns its index, or NUM_PIOS if none +// qualifies. This lets an out-of-tree PIO user (e.g. the sdioio SDIO driver, +// which manages its own SDK-level pio_claim_unused_sm / pio_add_program) pick a +// PIO cooperatively rather than blindly seizing pio0/pio1/pio2. Because it uses +// the same SDK claim/instruction bookkeeping that rp2pio itself relies on, a hit +// here means the caller's subsequent claims on the returned PIO will succeed and +// will not collide with an existing rp2pio user. +uint8_t rp2pio_statemachine_find_pio(int program_size, int sm_count) { + pio_program_t test_program = { + .instructions = NULL, + .length = program_size, + .origin = -1, + }; + for (size_t i = 0; i < NUM_PIOS; i++) { + PIO pio = pio_get_instance(i); + if (!pio_can_add_program(pio, &test_program)) { + continue; + } + int free_sms = 0; + for (size_t j = 0; j < NUM_PIO_STATE_MACHINES; j++) { + if (!pio_sm_is_claimed(pio, j)) { + free_sms++; + } + } + if (free_sms >= sm_count) { + return i; + } + } + return NUM_PIOS; } void rp2pio_statemachine_deinit(rp2pio_statemachine_obj_t *self, bool leave_pins) { + // Already deinited, or construction raised before a state machine was claimed. + // state_machine would index past the per-state-machine arrays, and pio may be NULL. + if (common_hal_rp2pio_statemachine_deinited(self)) { + return; + } common_hal_rp2pio_statemachine_stop(self); (void)common_hal_rp2pio_statemachine_stop_background_write(self); @@ -816,7 +964,6 @@ void rp2pio_statemachine_deinit(rp2pio_statemachine_obj_t *self, bool leave_pins _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; } @@ -825,9 +972,8 @@ void common_hal_rp2pio_statemachine_deinit(rp2pio_statemachine_obj_t *self) { rp2pio_statemachine_deinit(self, false); } -void common_hal_rp2pio_statemachine_never_reset(rp2pio_statemachine_obj_t *self) { - rp2pio_statemachine_never_reset(self->pio, self->state_machine); - // TODO: never reset all the pins +void common_hal_rp2pio_statemachine_mark_deinit(rp2pio_statemachine_obj_t *self) { + self->state_machine = NUM_PIO_STATE_MACHINES; } bool common_hal_rp2pio_statemachine_deinited(rp2pio_statemachine_obj_t *self) { @@ -852,25 +998,64 @@ static bool _transfer(rp2pio_statemachine_obj_t *self, // 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. - // Use DMA for large transfers if channels are available. - // Don't exceed FIFO size. - const size_t dma_min_size_threshold = self->fifo_depth; int chan_tx = -1; int chan_rx = -1; size_t len = MAX(out_len, in_len); bool tx = data_out != NULL; bool rx = data_in != NULL; - bool use_dma = len >= dma_min_size_threshold || swap_out || swap_in; + bool free_data_out = false; + bool free_data_in = false; + uint8_t *sram_data_out = (uint8_t *)data_out; + uint8_t *sram_data_in = data_in; + bool tx_fits_in_fifo = (out_len / out_stride_in_bytes) <= self->fifo_depth; + bool rx_fits_in_fifo = (in_len / in_stride_in_bytes) <= self->fifo_depth; + bool use_dma = !(tx_fits_in_fifo && rx_fits_in_fifo) || swap_out || swap_in; + if (use_dma) { - // Use DMA channels to service the two FIFOs + // We can only reliably use DMA for SRAM buffers. So, if we're given PSRAM buffers, + // then copy them to SRAM first. If we can't, then fail. + // Use DMA channels to service the two FIFOs. Fail if we can't allocate DMA channels. if (tx) { + if (data_out < (uint8_t *)SRAM_BASE) { + // Try to allocate a temporary buffer for DMA transfer + uint8_t *temp_buffer = (uint8_t *)port_malloc(len, true); + if (temp_buffer == NULL) { + mp_printf(&mp_plat_print, "Failed to allocate temporary buffer for DMA tx\n"); + return false; + } + memcpy(temp_buffer, data_out, len); + sram_data_out = temp_buffer; + free_data_out = true; + } chan_tx = dma_claim_unused_channel(false); // DMA allocation failed... if (chan_tx < 0) { + if (free_data_out) { + port_free(sram_data_out); + } + if (free_data_in) { + port_free(sram_data_in); + } return false; } } if (rx) { + if (data_in < (uint8_t *)SRAM_BASE) { + // Try to allocate a temporary buffer for DMA transfer + uint8_t *temp_buffer = (uint8_t *)port_malloc(len, true); + if (temp_buffer == NULL) { + mp_printf(&mp_plat_print, "Failed to allocate temporary buffer for DMA rx\n"); + if (chan_tx >= 0) { + dma_channel_unclaim(chan_tx); + } + if (free_data_out) { + port_free(sram_data_out); + } + return false; + } + sram_data_in = temp_buffer; + free_data_in = true; + } chan_rx = dma_claim_unused_channel(false); // DMA allocation failed... if (chan_rx < 0) { @@ -878,6 +1063,12 @@ static bool _transfer(rp2pio_statemachine_obj_t *self, if (chan_tx >= 0) { dma_channel_unclaim(chan_tx); } + if (free_data_out) { + port_free(sram_data_out); + } + if (free_data_in) { + port_free(sram_data_in); + } return false; } } @@ -909,7 +1100,7 @@ static bool _transfer(rp2pio_statemachine_obj_t *self, channel_config_set_bswap(&c, swap_out); dma_channel_configure(chan_tx, &c, tx_destination, - data_out, + sram_data_out, out_len / out_stride_in_bytes, false); channel_mask |= 1u << chan_tx; @@ -922,7 +1113,7 @@ static bool _transfer(rp2pio_statemachine_obj_t *self, channel_config_set_write_increment(&c, true); channel_config_set_bswap(&c, swap_in); dma_channel_configure(chan_rx, &c, - data_in, + sram_data_in, rx_source, in_len / in_stride_in_bytes, false); @@ -949,8 +1140,7 @@ static bool _transfer(rp2pio_statemachine_obj_t *self, self->pio->fdebug = stall_mask; } - // If we have claimed only one channel successfully, we should release immediately. This also - // releases the DMA after use_dma has been done. + // Release the DMA channels after use_dma has been done. if (chan_rx >= 0) { dma_channel_unclaim(chan_rx); } @@ -959,31 +1149,31 @@ static bool _transfer(rp2pio_statemachine_obj_t *self, } if (!use_dma && !(self->user_interruptible && mp_hal_is_interrupted())) { - // Use software for small transfers, or if couldn't claim two DMA channels + // Use software for small transfers 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) { while (tx_remaining && !pio_sm_is_tx_fifo_full(self->pio, self->state_machine)) { if (out_stride_in_bytes == 1) { - *tx_destination = *data_out; + *tx_destination = *sram_data_out; } else if (out_stride_in_bytes == 2) { - *((uint16_t *)tx_destination) = *((uint16_t *)data_out); + *((uint16_t *)tx_destination) = *((uint16_t *)sram_data_out); } else if (out_stride_in_bytes == 4) { - *((uint32_t *)tx_destination) = *((uint32_t *)data_out); + *((uint32_t *)tx_destination) = *((uint32_t *)sram_data_out); } - data_out += out_stride_in_bytes; + sram_data_out += out_stride_in_bytes; --tx_remaining; } while (rx_remaining && !pio_sm_is_rx_fifo_empty(self->pio, self->state_machine)) { if (in_stride_in_bytes == 1) { - *data_in = (uint8_t)*rx_source; + *sram_data_in = (uint8_t)*rx_source; } else if (in_stride_in_bytes == 2) { - *((uint16_t *)data_in) = *((uint16_t *)rx_source); + *((uint16_t *)sram_data_in) = *((uint16_t *)rx_source); } else if (in_stride_in_bytes == 4) { - *((uint32_t *)data_in) = *((uint32_t *)rx_source); + *((uint32_t *)sram_data_in) = *((uint32_t *)rx_source); } - data_in += in_stride_in_bytes; + sram_data_in += in_stride_in_bytes; --rx_remaining; } RUN_BACKGROUND_TASKS; @@ -995,7 +1185,7 @@ static bool _transfer(rp2pio_statemachine_obj_t *self, self->pio->fdebug = stall_mask; } // Wait for the state machine to finish transmitting the data we've queued - // up. + // up (either from the CPU or via DMA.) if (tx) { while (!pio_sm_is_tx_fifo_empty(self->pio, self->state_machine) || (self->wait_for_txstall && (self->pio->fdebug & stall_mask) == 0)) { @@ -1005,6 +1195,14 @@ static bool _transfer(rp2pio_statemachine_obj_t *self, } } } + if (free_data_out) { + port_free(sram_data_out); + } + if (free_data_in) { + // Copy the data from the SRAM buffer to the user PSRAM buffer. + memcpy(data_in, sram_data_in, len); + port_free(sram_data_in); + } return true; } @@ -1213,12 +1411,8 @@ bool common_hal_rp2pio_statemachine_background_write(rp2pio_statemachine_obj_t * common_hal_mcu_disable_interrupts(); - // Acknowledge any previous pending interrupt - dma_hw->ints0 |= 1u << channel_write; MP_STATE_PORT(background_pio_write)[channel_write] = self; - dma_hw->inte0 |= 1u << channel_write; - - irq_set_mask_enabled(1 << DMA_IRQ_0, true); + rp2pio_dma_enable_irq(channel_write); dma_start_channel_mask(1u << channel_write); common_hal_mcu_enable_interrupts(); @@ -1377,11 +1571,8 @@ bool common_hal_rp2pio_statemachine_background_read(rp2pio_statemachine_obj_t *s false); common_hal_mcu_disable_interrupts(); - // Acknowledge any previous pending interrupt - dma_hw->ints0 |= 1u << channel_read; MP_STATE_PORT(background_pio_read)[channel_read] = self; - dma_hw->inte0 |= 1u << channel_read; - irq_set_mask_enabled(1 << DMA_IRQ_0, true); + rp2pio_dma_enable_irq(channel_read); dma_start_channel_mask((1u << channel_read)); common_hal_mcu_enable_interrupts(); @@ -1418,9 +1609,40 @@ bool common_hal_rp2pio_statemachine_stop_background_read(rp2pio_statemachine_obj memset(&self->next_read_buf_2, 0, sizeof(self->next_read_buf_2)); memset(&self->next_read_buf_3, 0, sizeof(self->next_read_buf_3)); self->pending_buffers_read = 0; + self->dma_completed_read = true; return true; } +void common_hal_rp2pio_statemachine_set_read_buffers_raw(rp2pio_statemachine_obj_t *self, + void *once, size_t once_len, + void *loop, size_t loop_len, + void *loop2, size_t loop2_len) { + memset(&self->once_read_buf_info, 0, sizeof(self->once_read_buf_info)); + memset(&self->loop_read_buf_info, 0, sizeof(self->loop_read_buf_info)); + memset(&self->loop2_read_buf_info, 0, sizeof(self->loop2_read_buf_info)); + if (once && once_len) { + self->once_read_buf_info.info.buf = once; + self->once_read_buf_info.info.len = once_len; + } + if (loop && loop_len) { + self->loop_read_buf_info.info.buf = loop; + self->loop_read_buf_info.info.len = loop_len; + } + if (loop2 && loop2_len) { + self->loop2_read_buf_info.info.buf = loop2; + self->loop2_read_buf_info.info.len = loop2_len; + } +} + +int common_hal_rp2pio_statemachine_get_read_dma_channel(rp2pio_statemachine_obj_t *self) { + uint8_t pio_index = pio_get_index(self->pio); + uint8_t sm = self->state_machine; + if (!SM_DMA_ALLOCATED_READ(pio_index, sm)) { + return -1; + } + return SM_DMA_GET_CHANNEL_READ(pio_index, sm); +} + bool common_hal_rp2pio_statemachine_get_reading(rp2pio_statemachine_obj_t *self) { return !self->dma_completed_read; } diff --git a/ports/raspberrypi/common-hal/rp2pio/StateMachine.h b/ports/raspberrypi/common-hal/rp2pio/StateMachine.h index c7ef12e1b01..88765f3bc07 100644 --- a/ports/raspberrypi/common-hal/rp2pio/StateMachine.h +++ b/ports/raspberrypi/common-hal/rp2pio/StateMachine.h @@ -12,6 +12,10 @@ #include "common-hal/memorymap/AddressRange.h" #include "hardware/pio.h" +// Shared PIO allocator declarations (rp2pio_statemachine_find_pio). Kept in a +// separate, mp-free header so external C++ drivers can include them too. +#include "pio_alloc.h" + // pio_pinmask_t can hold ANY pin masks, so it is used before selection of gpiobase #if NUM_BANK0_GPIOS > 32 typedef struct { uint64_t value; @@ -100,6 +104,7 @@ typedef struct { PIO pio; const uint16_t *init; size_t init_len; + pio_pinmask_t pins_we_own; // Subset of pins that no other state machine had already claimed. pio_pinmask_t initial_pin_state; pio_pinmask_t initial_pin_direction; pio_pinmask_t pull_pin_up; @@ -174,9 +179,4 @@ void rp2pio_statemachine_deinit(rp2pio_statemachine_obj_t *self, bool leave_pins void rp2pio_statemachine_dma_complete_write(rp2pio_statemachine_obj_t *self, int channel); void rp2pio_statemachine_dma_complete_read(rp2pio_statemachine_obj_t *self, int channel); -void rp2pio_statemachine_reset_ok(PIO pio, int sm); -void rp2pio_statemachine_never_reset(PIO pio, int sm); - -uint8_t rp2pio_statemachine_find_pio(int program_size, int sm_count); - extern const mp_obj_type_t rp2pio_statemachine_type; diff --git a/ports/raspberrypi/common-hal/rp2pio/pio_alloc.h b/ports/raspberrypi/common-hal/rp2pio/pio_alloc.h new file mode 100644 index 00000000000..d26cce81e34 --- /dev/null +++ b/ports/raspberrypi/common-hal/rp2pio/pio_alloc.h @@ -0,0 +1,30 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// Shared PIO allocator declarations that let external drivers (including the +// vendored C++ PioSdioCard driver) cooperate with CircuitPython's rp2pio PIO +// allocator instead of seizing whole PIO blocks through the raw SDK. The +// definitions live in common-hal/rp2pio/StateMachine.c. This header +// deliberately does NOT include the MicroPython object headers pulled in by the +// full rp2pio StateMachine.h, so it can be included from C++ translation units. +// The declarations are given C linkage for that reason. + +#pragma once + +#include "hardware/pio.h" + +#ifdef __cplusplus +extern "C" { +#endif + +// See common-hal/rp2pio/StateMachine.c. Returns a PIO index (0..NUM_PIOS-1) with +// room for program_size instructions and sm_count free state machines, or +// NUM_PIOS if none qualifies. +uint8_t rp2pio_statemachine_find_pio(int program_size, int sm_count); + +#ifdef __cplusplus +} +#endif diff --git a/ports/raspberrypi/common-hal/rtc/pico_time.c b/ports/raspberrypi/common-hal/rtc/pico_time.c new file mode 100644 index 00000000000..c2e3ce9e974 --- /dev/null +++ b/ports/raspberrypi/common-hal/rtc/pico_time.c @@ -0,0 +1,39 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +// The SDK expects the port to provide pico_localtime_r() and pico_mktime(); its +// weak defaults call newlib's localtime_r() and mktime(). CircuitPython has the +// same calendar arithmetic in shared/timeutils, so use that and keep newlib's +// time functions, and what they link in, out of the image. +// +// Newlib would run without a TZ setting here, so both compute UTC. + +#include + +#include "pico/util/datetime.h" +#include "shared/timeutils/timeutils.h" + +struct tm *pico_localtime_r(const time_t *time, struct tm *tm) { + timeutils_struct_time_t t; + timeutils_seconds_since_1970_to_struct_time((timeutils_timestamp_t)*time, &t); + tm->tm_year = t.tm_year - 1900; + tm->tm_mon = t.tm_mon - 1; + tm->tm_mday = t.tm_mday; + tm->tm_hour = t.tm_hour; + tm->tm_min = t.tm_min; + tm->tm_sec = t.tm_sec; + tm->tm_wday = (t.tm_wday + 1) % 7; // timeutils counts from Monday, struct tm from Sunday + tm->tm_yday = t.tm_yday - 1; + tm->tm_isdst = 0; + return tm; +} + +time_t pico_mktime(struct tm *tm) { + time_t t = (time_t)timeutils_mktime_1970(tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, + tm->tm_hour, tm->tm_min, tm->tm_sec); + pico_localtime_r(&t, tm); // mktime() also normalises the fields it was given + return t; +} diff --git a/ports/raspberrypi/common-hal/sdioio/SDCard.c b/ports/raspberrypi/common-hal/sdioio/SDCard.c new file mode 100644 index 00000000000..03b021ed6bd --- /dev/null +++ b/ports/raspberrypi/common-hal/sdioio/SDCard.c @@ -0,0 +1,205 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "common-hal/sdioio/SDCard.h" +#include "common-hal/sdioio/sdfat_pio/shim.h" + +#include "extmod/vfs.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/sdioio/SDCard.h" +#include "shared-bindings/util.h" +#include "py/mperrno.h" +#include "py/runtime.h" + +// Maximum SD clock the PIO driver is allowed to be asked for. At a typical +// 150 MHz clk_sys the driver tops out near 37.5 MHz (clkDiv == 1); the cap is +// generous and the achieved rate is reported back through the `frequency` +// property. +#define SDIO_MAX_FREQUENCY (50000000) + +// Mark the object deinited. A zeroed object also reads as deinited. +static void mark_deinit(sdioio_sdcard_obj_t *self) { + self->num_data = 0; +} + +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, const mcu_pin_obj_t **data, uint32_t frequency) { + // Ensure the object starts in its deinit state, so its finaliser does + // nothing if this raises before the pins are claimed. + mark_deinit(self); + + // The vendored PIO driver only supports 4-bit mode and requires the four + // data lines to be on consecutive GPIOs (DAT0..DAT3). + if (num_data != 4) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("Number of data_pins must be %d, not %d"), 4, num_data); + } + for (size_t i = 1; i < num_data; i++) { + if (data[i]->number != data[0]->number + i) { + mp_raise_ValueError(MP_ERROR_TEXT("Data pins must be consecutive")); + } + } + + mp_arg_validate_int_max(frequency, SDIO_MAX_FREQUENCY, MP_QSTR_frequency); + + self->num_data = num_data; + self->clock = clock->number; + self->command = command->number; + for (size_t i = 0; i < num_data; i++) { + self->data[i] = data[i]->number; + } + + claim_pin(clock); + claim_pin(command); + for (size_t i = 0; i < num_data; i++) { + claim_pin(data[i]); + } + + sdfat_pio_card_new(&self->card); + uint32_t actual_frequency = 0; + bool ok = sdfat_pio_card_begin(&self->card, clock->number, command->number, + data[0]->number, frequency, &actual_frequency); + if (!ok) { + // The driver's error code identifies the SD command/phase that failed + // (see SdCardInfo.h SD_CARD_ERROR_* codes). + uint8_t error_code = sdfat_pio_card_error_code(&self->card); + sdfat_pio_card_end(&self->card); + sdfat_pio_card_free(&self->card); + reset_pin_number(self->clock); + reset_pin_number(self->command); + for (size_t i = 0; i < num_data; i++) { + reset_pin_number(self->data[i]); + } + mark_deinit(self); + mp_raise_OSError_msg_varg( + MP_ERROR_TEXT("SDIO Init Error 0x%02x"), error_code); + } + + self->frequency = actual_frequency; + self->capacity = sdfat_pio_card_sector_count(&self->card); +} + +uint32_t common_hal_sdioio_sdcard_get_count(sdioio_sdcard_obj_t *self) { + return self->capacity; +} + +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) { + return self->num_data; +} + +static void check_for_deinit(sdioio_sdcard_obj_t *self) { + if (common_hal_sdioio_sdcard_deinited(self)) { + raise_deinited_error(); + } +} + +static void check_whole_block(mp_buffer_info_t *bufinfo) { + if (bufinfo->len % 512) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("Buffer must be a multiple of %d bytes"), 512); + } +} + +// Native function for the VFS blockdev layer. The PIO driver is polling, so +// these block until the transfer completes. Writes leave the multi-block +// transfer open until the next sync. +mp_negative_errno_t sdioio_sdcard_readblocks(mp_obj_t self_in, uint8_t *buf, + uint32_t start_block, uint32_t num_blocks) { + sdioio_sdcard_obj_t *self = MP_OBJ_TO_PTR(self_in); + if (!sdfat_pio_card_read_sectors(&self->card, start_block, buf, num_blocks)) { + return -MP_EIO; + } + return 0; +} + +mp_negative_errno_t sdioio_sdcard_writeblocks(mp_obj_t self_in, uint8_t *buf, + uint32_t start_block, uint32_t num_blocks) { + sdioio_sdcard_obj_t *self = MP_OBJ_TO_PTR(self_in); + if (!sdfat_pio_card_write_sectors(&self->card, start_block, buf, num_blocks)) { + return -MP_EIO; + } + return 0; +} + +mp_negative_errno_t common_hal_sdioio_sdcard_readblocks(sdioio_sdcard_obj_t *self, uint32_t start_block, mp_buffer_info_t *bufinfo) { + check_for_deinit(self); + check_whole_block(bufinfo); + uint32_t num_blocks = bufinfo->len / 512; + return sdioio_sdcard_readblocks(MP_OBJ_FROM_PTR(self), bufinfo->buf, + start_block, num_blocks); +} + +mp_negative_errno_t common_hal_sdioio_sdcard_writeblocks(sdioio_sdcard_obj_t *self, uint32_t start_block, mp_buffer_info_t *bufinfo) { + check_for_deinit(self); + check_whole_block(bufinfo); + uint32_t num_blocks = bufinfo->len / 512; + return sdioio_sdcard_writeblocks(MP_OBJ_FROM_PTR(self), bufinfo->buf, + start_block, num_blocks); +} + +// Native function for VFS blockdev layer. +bool sdioio_sdcard_ioctl(mp_obj_t self_in, size_t cmd, size_t arg, + mp_int_t *out_value) { + sdioio_sdcard_obj_t *self = MP_OBJ_TO_PTR(self_in); + *out_value = 0; + + switch (cmd) { + case MP_BLOCKDEV_IOCTL_DEINIT: + case MP_BLOCKDEV_IOCTL_SYNC: + // The driver keeps multi-block writes open between calls, so end + // the transfer and wait for the card to finish programming. + return sdfat_pio_card_sync(&self->card); + + case MP_BLOCKDEV_IOCTL_BLOCK_COUNT: + *out_value = common_hal_sdioio_sdcard_get_count(self); + return true; + + case MP_BLOCKDEV_IOCTL_BLOCK_SIZE: + *out_value = 512; // SD cards use 512-byte sectors. + return true; + + default: + return false; // Unsupported command. + } +} + +bool common_hal_sdioio_sdcard_configure(sdioio_sdcard_obj_t *self, uint32_t frequency, uint8_t bits) { + // Only 4-bit mode is supported (see construct); reject a request for any + // other width. Reconfiguring the clock at runtime is not implemented yet, + // so the frequency argument is accepted but ignored. + if (bits != 0 && bits != self->num_data) { + return false; + } + return true; +} + +bool common_hal_sdioio_sdcard_deinited(sdioio_sdcard_obj_t *self) { + return self->num_data == 0; +} + +void common_hal_sdioio_sdcard_deinit(sdioio_sdcard_obj_t *self) { + if (common_hal_sdioio_sdcard_deinited(self)) { + return; + } + + // Commit any open write before the PIO is released. + sdfat_pio_card_sync(&self->card); + sdfat_pio_card_end(&self->card); + sdfat_pio_card_free(&self->card); + + reset_pin_number(self->command); + self->command = COMMON_HAL_MCU_NO_PIN; + reset_pin_number(self->clock); + self->clock = COMMON_HAL_MCU_NO_PIN; + for (size_t i = 0; i < self->num_data; i++) { + reset_pin_number(self->data[i]); + self->data[i] = COMMON_HAL_MCU_NO_PIN; + } + mark_deinit(self); +} diff --git a/ports/raspberrypi/common-hal/sdioio/SDCard.h b/ports/raspberrypi/common-hal/sdioio/SDCard.h new file mode 100644 index 00000000000..c39c4586c03 --- /dev/null +++ b/ports/raspberrypi/common-hal/sdioio/SDCard.h @@ -0,0 +1,24 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "common-hal/microcontroller/Pin.h" +#include "common-hal/sdioio/sdfat_pio/shim.h" +#include "py/obj.h" + +typedef struct { + mp_obj_base_t base; + // In-place storage for the vendored C++ PioSdioCard instance, constructed + // and torn down through the extern "C" shim in sdfat_pio/. + sdioio_pio_card_storage_t card; + uint32_t frequency; + uint32_t capacity; // Number of 512-byte blocks. + uint8_t num_data; + uint8_t command; + uint8_t clock; + uint8_t data[4]; +} sdioio_sdcard_obj_t; diff --git a/ports/raspberrypi/common-hal/sdioio/__init__.c b/ports/raspberrypi/common-hal/sdioio/__init__.c new file mode 100644 index 00000000000..4a92fca8794 --- /dev/null +++ b/ports/raspberrypi/common-hal/sdioio/__init__.c @@ -0,0 +1,8 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// No sdioio module functions. The whole API lives on sdioio.SDCard, which is +// implemented in SDCard.c. diff --git a/ports/raspberrypi/common-hal/sdioio/sdfat_pio/SdCard/PioSdio/DbgLog.h b/ports/raspberrypi/common-hal/sdioio/sdfat_pio/SdCard/PioSdio/DbgLog.h new file mode 100644 index 00000000000..8d1ba8db85a --- /dev/null +++ b/ports/raspberrypi/common-hal/sdioio/sdfat_pio/SdCard/PioSdio/DbgLog.h @@ -0,0 +1,41 @@ +/** + * Copyright (c) 2011-2025 Bill Greiman, 2026 Tim Cocks for Adafruit Industries + * This file is part of the SdFat library for SD memory cards. + * + * MIT License + * + * 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. + */ +/** + * \file + * \brief Classes for Debug messages. + * + * CircuitPython vendored, trimmed copy. The upstream DbgLog.h includes the + * Arduino Printable.h and defines a family of helper print classes (Bin, Hex, + * Num, Dbl, logmsg...). Those are only referenced when debug output is enabled + * (ENABLE_DBG_MSG / USE_DEBUG_MODE), which it is not in this build, so they are + * omitted to keep the Arduino Print dependency out of the firmware. Only the + * no-op DBG_MSG() macro that PioSdioCard.cpp uses on its normal paths remains. + */ +#pragma once + +/** Debug messages are disabled in the CircuitPython build. */ +#define DBG_MSG(...) \ + do { \ + } while (0) diff --git a/ports/raspberrypi/common-hal/sdioio/sdfat_pio/SdCard/PioSdio/PioSdioCard.cpp b/ports/raspberrypi/common-hal/sdioio/sdfat_pio/SdCard/PioSdio/PioSdioCard.cpp new file mode 100644 index 00000000000..e5290e41391 --- /dev/null +++ b/ports/raspberrypi/common-hal/sdioio/sdfat_pio/SdCard/PioSdio/PioSdioCard.cpp @@ -0,0 +1,1010 @@ +/** + * Copyright (c) 2011-2025 Bill Greiman, 2026 Tim Cocks for Adafruit Industries + * This file is part of the SdFat library for SD memory cards. + * + * MIT License + * + * 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. + */ +#ifdef ARDUINO_ARCH_RP2040 +#include + +#include // Required for std::max, std::min +#define DEBUG_FILE "PioSdioCard.cpp" +#include "../SdCardInfo.h" +#include "DbgLog.h" +#include "PioSdioCard.h" +#include "PioSdioCard.pio.h" +// CIRCUITPY-CHANGE: cooperate with CircuitPython's rp2pio PIO allocator +#include "common-hal/rp2pio/pio_alloc.h" +//------------------------------------------------------------------------------ +// USE_DEBUG_MODE 0 - no debug, 1 - print message, 2 - Use scope/analyzer. +#define USE_DEBUG_MODE 0 + +const uint PIO_CLK_DIV_RUN = 1; + +const uint PIN_SDIO_UNDEFINED = 63u; + +const uint DAT_FIFO_DEPTH = 8; +//============================================================================== +// Command definitions. +enum { RSP_R0 = 0, RSP_R1 = 1, RSP_R2 = 2, RSP_R3 = 3, RSP_R6 = 6, RSP_R7 = 7 }; +static const CmdRsp_t CMD0_R0(CMD0, RSP_R0); +static const CmdRsp_t CMD2_R2(CMD2, RSP_R2); +static const CmdRsp_t CMD3_R6(CMD3, RSP_R6); +static const CmdRsp_t CMD6_R1(CMD6, RSP_R1); +static const CmdRsp_t CMD7_R1(CMD7, RSP_R1); +static const CmdRsp_t CMD8_R7(CMD8, RSP_R7); +static const CmdRsp_t CMD9_R2(CMD9, RSP_R2); +static const CmdRsp_t CMD10_R2(CMD10, RSP_R2); +static const CmdRsp_t CMD12_R1(CMD12, RSP_R1); +static const CmdRsp_t CMD13_R1(CMD13, RSP_R1); +static const CmdRsp_t CMD18_R1(CMD18, RSP_R1); +static const CmdRsp_t CMD25_R1(CMD25, RSP_R1); +static const CmdRsp_t CMD32_R1(CMD32, RSP_R1); +static const CmdRsp_t CMD33_R1(CMD33, RSP_R1); +static const CmdRsp_t CMD38_R1(CMD38, RSP_R1); +static const CmdRsp_t CMD55_R1(CMD55, RSP_R1); +static const CmdRsp_t ACMD6_R1(ACMD6, RSP_R1); +static const CmdRsp_t ACMD13_R1(ACMD13, RSP_R1); +static const CmdRsp_t ACMD41_R3(ACMD41, RSP_R3); +static const CmdRsp_t ACMD51_R1(ACMD51, RSP_R1); +//============================================================================== +class Timeout { + public: + explicit Timeout(uint ms) : _usStart(0), _usTimeout(1000 * ms) {} + bool timedOut() { + if (_usStart) { + return (usSinceBoot() - _usStart) > _usTimeout; + } + _usStart = usSinceBoot(); + return false; + } + uint32_t usSinceBoot() { return to_us_since_boot(get_absolute_time()); } + uint32_t _usStart; + uint32_t _usTimeout; +}; +//============================================================================== +#if USE_DEBUG_MODE +//------------------------------------------------------------------------------ +static inline void gpioStatus(uint gpio) { + logmsgln("gpio", gpio, " drive: ", gpio_get_drive_strength(gpio)); + // logmsgln("gpio", gpio, + // " drive: ", static_cast(gpio_get_drive_strength(gpio))); + logmsgln("gpio", gpio, " slew: ", gpio_get_slew_rate(gpio)); + logmsgln("gpio", gpio, " hyst: ", gpio_is_input_hysteresis_enabled(gpio)); + logmsgln("gpio", gpio, " pull: ", gpio_is_pulled_up(gpio)); +} +//------------------------------------------------------------------------------ +static inline void pioRegs(PIO pio) { + logmsgln("ctrl: 0b", Bin(pio->ctrl)); + logmsgln("fstat: 0b", Bin(pio->fstat)); + logmsgln("fdebug: 0b", Bin(pio->fdebug)); + logmsgln("flevel: 0b", Bin(pio->flevel)); + logmsgln("padout: 0b", Bin(pio->dbg_padout)); + logmsgln("padoe: 0b", Bin(pio->dbg_padoe)); + logmsgln("cfginfo: 0x", Hex(pio->dbg_cfginfo)); + logmsgln("sync_bypass: 0b", Bin(pio->input_sync_bypass)); +} +//------------------------------------------------------------------------------ +static inline void pioSmRegs(PIO pio, uint sm) { + logmsgln("sm", sm, " clkdiv: 0x", Hex(pio->sm[sm].clkdiv)); + logmsgln("sm", sm, " execctrl: 0x", Hex(pio->sm[sm].execctrl)); + logmsgln("sm", sm, " shiftctrl: 0x", Hex(pio->sm[sm].shiftctrl)); + logmsgln("sm", sm, " addr: 0x", Hex(pio->sm[sm].addr)); + logmsgln("sm", sm, " pinctrl: 0x", Hex(pio->sm[sm].pinctrl)); +} +//------------------------------------------------------------------------------ +#endif // USE_DEBUG_MODE +#define sdError(code) \ + { \ + setSdErrorCode(code, __LINE__); \ + DBG_MSG(#code); \ + } +#define SDIO_FAIL() DBG_MSG("SDIO_FAIL") +//============================================================================== +// CRC functions. +//------------------------------------------------------------------------------ +// See this library's extras folder. +static const uint8_t crc7_table[256] = { + 0x00, 0x12, 0x24, 0x36, 0x48, 0x5a, 0x6c, 0x7e, // 00 - 07 + 0x90, 0x82, 0xb4, 0xa6, 0xd8, 0xca, 0xfc, 0xee, // 08 - 0f + 0x32, 0x20, 0x16, 0x04, 0x7a, 0x68, 0x5e, 0x4c, // 10 - 17 + 0xa2, 0xb0, 0x86, 0x94, 0xea, 0xf8, 0xce, 0xdc, // 18 - 1f + 0x64, 0x76, 0x40, 0x52, 0x2c, 0x3e, 0x08, 0x1a, // 20 - 27 + 0xf4, 0xe6, 0xd0, 0xc2, 0xbc, 0xae, 0x98, 0x8a, // 28 - 2f + 0x56, 0x44, 0x72, 0x60, 0x1e, 0x0c, 0x3a, 0x28, // 30 - 37 + 0xc6, 0xd4, 0xe2, 0xf0, 0x8e, 0x9c, 0xaa, 0xb8, // 38 - 3f + 0xc8, 0xda, 0xec, 0xfe, 0x80, 0x92, 0xa4, 0xb6, // 40 - 47 + 0x58, 0x4a, 0x7c, 0x6e, 0x10, 0x02, 0x34, 0x26, // 48 - 4f + 0xfa, 0xe8, 0xde, 0xcc, 0xb2, 0xa0, 0x96, 0x84, // 50 - 57 + 0x6a, 0x78, 0x4e, 0x5c, 0x22, 0x30, 0x06, 0x14, // 58 - 5f + 0xac, 0xbe, 0x88, 0x9a, 0xe4, 0xf6, 0xc0, 0xd2, // 60 - 67 + 0x3c, 0x2e, 0x18, 0x0a, 0x74, 0x66, 0x50, 0x42, // 68 - 6f + 0x9e, 0x8c, 0xba, 0xa8, 0xd6, 0xc4, 0xf2, 0xe0, // 70 - 77 + 0x0e, 0x1c, 0x2a, 0x38, 0x46, 0x54, 0x62, 0x70, // 78 - 7f + 0x82, 0x90, 0xa6, 0xb4, 0xca, 0xd8, 0xee, 0xfc, // 80 - 87 + 0x12, 0x00, 0x36, 0x24, 0x5a, 0x48, 0x7e, 0x6c, // 88 - 8f + 0xb0, 0xa2, 0x94, 0x86, 0xf8, 0xea, 0xdc, 0xce, // 90 - 97 + 0x20, 0x32, 0x04, 0x16, 0x68, 0x7a, 0x4c, 0x5e, // 98 - 9f + 0xe6, 0xf4, 0xc2, 0xd0, 0xae, 0xbc, 0x8a, 0x98, // a0 - a7 + 0x76, 0x64, 0x52, 0x40, 0x3e, 0x2c, 0x1a, 0x08, // a8 - af + 0xd4, 0xc6, 0xf0, 0xe2, 0x9c, 0x8e, 0xb8, 0xaa, // b0 - b7 + 0x44, 0x56, 0x60, 0x72, 0x0c, 0x1e, 0x28, 0x3a, // b8 - bf + 0x4a, 0x58, 0x6e, 0x7c, 0x02, 0x10, 0x26, 0x34, // c0 - c7 + 0xda, 0xc8, 0xfe, 0xec, 0x92, 0x80, 0xb6, 0xa4, // c8 - cf + 0x78, 0x6a, 0x5c, 0x4e, 0x30, 0x22, 0x14, 0x06, // d0 - d7 + 0xe8, 0xfa, 0xcc, 0xde, 0xa0, 0xb2, 0x84, 0x96, // d8 - df + 0x2e, 0x3c, 0x0a, 0x18, 0x66, 0x74, 0x42, 0x50, // e0 - e7 + 0xbe, 0xac, 0x9a, 0x88, 0xf6, 0xe4, 0xd2, 0xc0, // e8 - ef + 0x1c, 0x0e, 0x38, 0x2a, 0x54, 0x46, 0x70, 0x62, // f0 - f7 + 0x8c, 0x9e, 0xa8, 0xba, 0xc4, 0xd6, 0xe0, 0xf2 // f8 - ff +}; +//------------------------------------------------------------------------------ +inline static uint8_t CRC7(const uint8_t* data, uint8_t n) { + uint8_t crc = 0; + for (uint8_t i = 0; i < n; i++) { + crc = crc7_table[crc ^ data[i]]; + } + return crc | 1; +} +//------------------------------------------------------------------------------ +// Modified from sdio_crc16_4bit_checksum() in +// https://github.com/ZuluSCSI/ZuluSCSI-firmware +// +static inline __attribute__((always_inline)) uint64_t crc16(uint64_t crc, + uint32_t data_in) { + // Shift out 8 bits for each line + uint32_t data_out = crc >> 32; + crc <<= 32; + + // XOR outgoing data to itself with 4 bit delay + data_out ^= (data_out >> 16); + + // XOR incoming data to outgoing data with 4 bit delay + data_out ^= (data_in >> 16); + + // XOR outgoing and incoming data to accumulator at each tap + uint64_t xorred = data_out ^ data_in; + crc ^= xorred; + crc ^= xorred << (5 * 4); + crc ^= xorred << (12 * 4); + return crc; +} +//------------------------------------------------------------------------------ +//============================================================================== +// add to PioSdioCard class int the future. +// PioSdioCard::PioSdioCard() +// PioSdioCard::~PioSdioCard() +//------------------------------------------------------------------------------ +bool PioSdioCard::cardAcmd(uint32_t rca, CmdRsp_t cmdRsp, uint32_t arg) { + return cardCommand(CMD55_R1, rca) && cardCommand(cmdRsp, arg); +} +//------------------------------------------------------------------------------ +bool PioSdioCard::begin(PioSdioConfig sdioConfig) { + pioEnd(); + Timeout timeout(SD_INIT_TIMEOUT); + uint32_t arg; + m_curState = IDLE_STATE; + m_errorCode = SD_CARD_ERROR_NONE; + m_highCapacity = false; + m_initDone = false; + m_version2 = false; + m_clkPin = sdioConfig.clkPin(); + m_cmdPin = sdioConfig.cmdPin(); + m_dat0Pin = sdioConfig.dat0Pin(); + + // Four PIO cycles per SD CLK cycle. + m_clkDiv = ceil((0.00025 * clock_get_hz(clk_sys)) / SD_MAX_INIT_RATE_KHZ); + +#if USE_DEBUG_MODE == 2 + Serial.println(); + pioRegs(m_pio); + pioSmRegs(m_pio, m_sm0); + pioSmRegs(m_pio, m_sm1); + gpioStatus(m_clkPin); + gpioStatus(m_cmdPin); + while (Serial.read() >= 0) { + } + Serial.println("Logic Analyzer on then type any char"); + while (!Serial.available()) { + } +#endif // USE_DEBUG_MODE + // A few cards still require clocks after power-up. + powerUpClockCycles(); + if (!pioInit()) { + goto fail; + } + pioConfig(m_clkDiv); + if (!cardCommand(CMD0_R0, 0)) { + sdError(SD_CARD_ERROR_CMD0); + goto fail; + } + if (cardCommand(CMD8_R7, 0X1AA)) { + if (m_cardRsp != 0X1AA) { + sdError(SD_CARD_ERROR_CMD8); + goto fail; + } + m_version2 = true; + } else { + m_version2 = false; + m_errorCode = SD_CARD_ERROR_NONE; + } + arg = m_version2 ? 0X40300000 : 0x00300000; + while (true) { + if (!cardAcmd(0, ACMD41_R3, arg)) { + sdError(SD_CARD_ERROR_ACMD41); + goto fail; + } + if (m_cardRsp & 0x80000000) { + break; + } + if (timeout.timedOut()) { + sdError(SD_CARD_ERROR_ACMD41); + goto fail; + } + } + m_ocr = m_cardRsp; + if (m_cardRsp & 0x40000000) { + // Is high capacity. + m_highCapacity = true; + } + if (!cardCommand(CMD2_R2, 0)) { + sdError(SD_CARD_ERROR_CMD2); + goto fail; + } + if (!cardCommand(CMD3_R6, 0)) { + sdError(SD_CARD_ERROR_CMD3); + goto fail; + } + m_rca = m_cardRsp & 0xFFFF0000; + if (!cardCommand(CMD9_R2, m_rca, &m_csd)) { + sdError(SD_CARD_ERROR_CMD9); + goto fail; + } + if (!cardCommand(CMD10_R2, m_rca, &m_cid)) { + sdError(SD_CARD_ERROR_CMD10); + goto fail; + } + if (!cardCommand(CMD7_R1, m_rca)) { + sdError(SD_CARD_ERROR_CMD7); + goto fail; + } + + if (!cardAcmd(m_rca, ACMD6_R1, 2)) { + sdError(SD_CARD_ERROR_ACMD6); + goto fail; + } + m_clkDiv = sdioConfig.clkDiv(); + pioConfig(m_clkDiv); + if (!cardAcmd(m_rca, ACMD51_R1, 0)) { + sdError(SD_CARD_ERROR_ACMD51); + goto fail; + } + if (!readData(&m_scr, sizeof(m_scr))) { + DBG_MSG("readData"); + goto fail; + } + if (!cardAcmd(m_rca, ACMD13_R1, 0)) { + sdError(SD_CARD_ERROR_ACMD13); + SDIO_FAIL(); + goto fail; + } + + if (!readData(&m_sds, sizeof(m_sds))) { + SDIO_FAIL(); + goto fail; + } + m_initDone = true; + + return true; +fail: + return false; +} +//------------------------------------------------------------------------------ +bool PioSdioCard::cardCMD6(uint32_t arg, uint8_t* status) { + if (!cardCommand(CMD6_R1, arg)) { + sdError(SD_CARD_ERROR_CMD6); + goto fail; + } + if (!readData(status, 64)) { + SDIO_FAIL(); + goto fail; + } + return true; +fail: + return false; +} +//------------------------------------------------------------------------------ +bool PioSdioCard::cardCommand(CmdRsp_t cmd, uint32_t arg, void* rsp) { + uint8_t buf[6]; + uint nRsp = cmd.rsp == RSP_R0 ? 0 : cmd.rsp == RSP_R2 ? 17 : 6; + const io_ro_8* rxFifo = reinterpret_cast(&m_pio->rxf[m_sm0]); + io_wo_8* txFifo = reinterpret_cast(&m_pio->txf[m_sm0]); + pio_sm_set_enabled(m_pio, m_sm1, false); + pio_sm_init(m_pio, m_sm0, m_cmdRspOffset, &m_cmdConfig); + pio_sm_exec(m_pio, m_sm0, pio_encode_set(pio_pindirs, 1)); + *txFifo = 55; + pio_sm_exec(m_pio, m_sm0, pio_encode_out(pio_x, 8)); + *txFifo = nRsp ? 8 * nRsp - 1 : 0; + pio_sm_exec(m_pio, m_sm0, pio_encode_out(pio_y, 8)); + pio_sm_set_enabled(m_pio, m_sm0, true); + uint n = 0; + buf[n++] = (uint8_t)(cmd.idx | 0x40); + buf[n++] = (uint8_t)(arg >> 24U); + buf[n++] = (uint8_t)(arg >> 16U); + buf[n++] = (uint8_t)(arg >> 8U); + buf[n++] = (uint8_t)arg; + buf[n++] = CRC7(buf, 5); + *txFifo = 0XFF; + for (uint i = 0; i < n; i++) { + while (pio_sm_is_tx_fifo_full(m_pio, m_sm0)) { + } + *txFifo = buf[i]; + } + + Timeout timeout(SD_CMD_TIMEOUT); + if (!nRsp) { + uint32_t fdebug_tx_stall = 1u << (PIO_FDEBUG_TXSTALL_LSB + m_sm0); + m_pio->fdebug = fdebug_tx_stall; + while (!(m_pio->fdebug & fdebug_tx_stall)) { + if (timeout.timedOut()) { + goto fail; + } + } + goto done; + } + uint8_t rtn[20]; + + for (uint i = 0; i < nRsp; i++) { + while (pio_sm_is_rx_fifo_empty(m_pio, m_sm0)) { + if (timeout.timedOut()) { + goto fail; + } + } + rtn[i] = *rxFifo; + } + if (cmd.rsp == RSP_R3) { + if (rtn[0] != 0X3F || rtn[5] != 0XFF) { + goto fail; + } + } else { + uint8_t crc; + if (cmd.rsp == RSP_R2) { + crc = CRC7(rtn + 1, nRsp - 2); + } else { + crc = CRC7(rtn, nRsp - 1); + } + if (rtn[nRsp - 1] != crc) { +#if USE_DEBUG_MODE + Serial.printf("CHK: %02X, CRC: %02X\n", rtn[nRsp - 1], crc); + for (uint i = 0; i < nRsp; i++) { + Serial.printf(" %02X", rtn[i]); + } + Serial.println(); +#endif // USE_DEBUG_MODE + sdError(SD_CARD_ERROR_READ_CRC); + goto fail; + } + } + if (nRsp == 6) { + m_cardRsp = (rtn[1] << 24) | (rtn[2] << 16) | (rtn[3] << 8) | rtn[4]; + if (rsp) { + *reinterpret_cast(rsp) = m_cardRsp; + } + } else if (rsp && nRsp == 17) { + memcpy(rsp, rtn + 1, 16); + } + +done: + pio_sm_set_enabled(m_pio, m_sm0, false); + return true; + +fail: +#if USE_DEBUG_MODE + DBG_MSG("CMD", cmd.idx, " failed"); +#endif // USE_DEBUG_MODE + pio_sm_set_enabled(m_pio, m_sm0, false); + return false; +} +//------------------------------------------------------------------------------ +void PioSdioCard::end() { pioEnd(); } +//------------------------------------------------------------------------------ +bool PioSdioCard::erase(uint32_t firstSector, uint32_t lastSector) { + Timeout timeout(SD_ERASE_TIMEOUT); + if (!syncDevice()) { + SDIO_FAIL(); + goto fail; + } + // check for single sector erase + if (!m_csd.eraseSingleBlock()) { + // erase size mask + uint8_t m = m_csd.eraseSize() - 1; + if ((firstSector & m) != 0 || ((lastSector + 1) & m) != 0) { + // error card can't erase specified area + sdError(SD_CARD_ERROR_ERASE_SINGLE_SECTOR); + goto fail; + } + } + if (!m_highCapacity) { + firstSector <<= 9; + lastSector <<= 9; + } + if (!cardCommand(CMD32_R1, firstSector)) { + sdError(SD_CARD_ERROR_CMD32); + goto fail; + } + if (!cardCommand(CMD33_R1, lastSector)) { + sdError(SD_CARD_ERROR_CMD33); + goto fail; + } + if (!cardCommand(CMD38_R1, 0)) { + sdError(SD_CARD_ERROR_CMD38); + goto fail; + } + while (isBusy()) { + if (timeout.timedOut()) { + sdError(SD_CARD_ERROR_ERASE_TIMEOUT); + goto fail; + } + } + return true; +fail: + return false; +} +//------------------------------------------------------------------------------ +uint8_t PioSdioCard::errorCode() const { return m_errorCode; } +//------------------------------------------------------------------------------ +uint32_t PioSdioCard::errorData() const { return m_cardRsp; } +//------------------------------------------------------------------------------ +uint32_t PioSdioCard::errorLine() const { return m_errorLine; } +//------------------------------------------------------------------------------ +bool PioSdioCard::isBusy() { + return gpio_get(m_dat0Pin) ? false : !(status() & CARD_STATUS_READY_FOR_DATA); +} +//------------------------------------------------------------------------------ +void PioSdioCard::pioConfig(float clkDiv) { + m_cmdConfig = + pio_cmd_rsp_program_config(m_cmdRspOffset, m_cmdPin, m_clkPin, clkDiv); + m_rdClkConfig = + pio_rd_clk_program_config(m_rdClkOffset, m_dat0Pin, m_clkPin, clkDiv); + m_rdDataConfig = + pio_rd_data_program_config(m_rdDataOffset, m_dat0Pin, clkDiv); + m_wrDataConfig = + pio_wr_data_program_config(m_wrDataOffset, m_dat0Pin, m_clkPin, clkDiv); + m_wrRespConfig = + pio_wr_resp_program_config(m_wrRespOffset, m_dat0Pin, m_clkPin, clkDiv); +} +//------------------------------------------------------------------------------ +void PioSdioCard::pioEnd() { + if (!m_pio) { + return; + } + // CIRCUITPY-CHANGE: release only the two state machines we claimed (see + // pioInit) rather than every SM on the block. + if (m_sm0 >= 0) { + pio_sm_set_enabled(m_pio, m_sm0, false); + pio_sm_unclaim(m_pio, m_sm0); + m_sm0 = -1; + } + if (m_sm1 >= 0) { + pio_sm_set_enabled(m_pio, m_sm1, false); + pio_sm_unclaim(m_pio, m_sm1); + m_sm1 = -1; + } + if (m_cmdRspOffset >= 0) { + pio_remove_program(m_pio, &cmd_rsp_program, m_cmdRspOffset); + m_cmdRspOffset = -1; + } + if (m_rdClkOffset >= 0) { + pio_remove_program(m_pio, &rd_clk_program, m_rdClkOffset); + m_rdClkOffset = -1; + } + if (m_rdDataOffset >= 0) { + pio_remove_program(m_pio, &rd_data_program, m_rdDataOffset); + m_rdDataOffset = -1; + } + if (m_wrDataOffset >= 0) { + pio_remove_program(m_pio, &wr_data_program, m_wrDataOffset); + m_wrDataOffset = -1; + } + if (m_wrRespOffset >= 0) { + pio_remove_program(m_pio, &wr_resp_program, m_wrRespOffset); + m_wrRespOffset = -1; + } + m_pio = nullptr; +} +//------------------------------------------------------------------------------ +bool PioSdioCard::pioInit() { + uint pin[] = {m_clkPin, m_cmdPin, m_dat0Pin, + m_dat0Pin + 1, m_dat0Pin + 2, m_dat0Pin + 3}; + // CIRCUITPY-CHANGE: the PIO's gpio_base (0 or 16). input_sync_bypass bits are + // relative to this base, so it must be subtracted from the raw GPIO numbers + // below (a raw `1 << pin` is UB for pins >= 32, e.g. Fruit Jam's GPIO34-39, + // and silently becomes a no-op on Cortex-M). Declared before the first goto so + // the error paths don't bypass its initialization. + uint gpio_base = 0; + // Declared before the first goto for the same reason as gpio_base. + uint pio_index = 0; + uint16_t pio_instructions[PIO_INSTRUCTION_COUNT]; + pio_program_t pio_program = {.instructions = nullptr, + .length = PIO_INSTRUCTION_COUNT, + .origin = -1, + .pio_version = 0, +#if PICO_PIO_VERSION > 0 + .used_gpio_ranges = 0x0 +#endif + }; + // CIRCUITPY-CHANGE: pick a PIO through CircuitPython's rp2pio allocator and + // claim only the two state machines this driver uses, rather than seizing an + // entire PIO block via the raw SDK. This lets sdioio coexist with rp2pio and + // other PIO users. The five programs total total_pio_length (31) instructions, + // so this effectively requires an empty PIO; find_pio enforces that, which in + // turn guarantees the chosen PIO has no other user whose gpio_base the + // pio_set_gpio_base() call below could disturb. + pio_index = rp2pio_statemachine_find_pio(total_pio_length, 2); + if (pio_index >= NUM_PIOS) { + sdError(SD_CARD_ERROR_ADD_PIO_PROGRAM); + goto fail; + } + m_pio = pio_get_instance(pio_index); + m_sm0 = pio_claim_unused_sm(m_pio, false); + m_sm1 = pio_claim_unused_sm(m_pio, false); + if (m_sm0 < 0 || m_sm1 < 0) { + sdError(SD_CARD_ERROR_ADD_PIO_PROGRAM); + goto fail; + } +#if PICO_PIO_USE_GPIO_BASE + if (std::max({m_clkPin, m_cmdPin, m_dat0Pin + 3}) > 31) { + if (std::min({m_clkPin, m_cmdPin, m_dat0Pin}) < 16 || + pio_set_gpio_base(m_pio, 16) != PICO_OK) { + sdError(SD_CARD_ERROR_ADD_PIO_PROGRAM); + goto fail; + } + gpio_base = 16; + } else if (pio_set_gpio_base(m_pio, 0) != PICO_OK) { + sdError(SD_CARD_ERROR_ADD_PIO_PROGRAM); + goto fail; + } +#endif // PICO_PIO_USE_GPIO_BASE + rd_data_patch_program(&pio_program, pio_instructions, m_clkPin); + m_rdDataOffset = pio_add_program(m_pio, &pio_program); + if (m_rdDataOffset < 0) { + DBG_MSG("m_rdDataOffset: ", m_rdDataOffset); + sdError(SD_CARD_ERROR_ADD_PIO_PROGRAM); + goto fail; + } + m_cmdRspOffset = pio_add_program(m_pio, &cmd_rsp_program); + if (m_cmdRspOffset < 0) { + sdError(SD_CARD_ERROR_ADD_PIO_PROGRAM); + goto fail; + } + m_rdClkOffset = pio_add_program(m_pio, &rd_clk_program); + if (m_rdClkOffset < 0) { + sdError(SD_CARD_ERROR_ADD_PIO_PROGRAM); + goto fail; + } + m_wrDataOffset = pio_add_program(m_pio, &wr_data_program); + if (m_wrDataOffset < 0) { + sdError(SD_CARD_ERROR_ADD_PIO_PROGRAM); + goto fail; + } + m_wrRespOffset = pio_add_program(m_pio, &wr_resp_program); + if (m_wrRespOffset < 0) { + sdError(SD_CARD_ERROR_ADD_PIO_PROGRAM); + goto fail; + } + for (uint i = 0; i < 6U; i++) { + gpio_pull_up(pin[i]); + } + gpio_set_drive_strength(m_clkPin, GPIO_DRIVE_STRENGTH_8MA); + gpio_set_slew_rate(m_clkPin, GPIO_SLEW_RATE_FAST); + + for (uint i = 0; i < 6U; i++) { + pio_gpio_init(m_pio, pin[i]); + } + // input_sync_bypass bits are relative to the PIO's gpio_base (0 or 16), so + // subtract it. Using the raw pin numbers here is undefined for pins >= 32 + // (Fruit Jam's SD pins are GPIO34-39) and evaluates to 0 on Cortex-M, leaving + // the input synchronizers in place -- benign at the ~400 kHz init rate but a + // source of CMD/DAT mis-sampling at the 25 MHz run rate. + m_pio->input_sync_bypass |= (1u << (m_clkPin - gpio_base)) | + (1u << (m_cmdPin - gpio_base)) | (0xFu << (m_dat0Pin - gpio_base)); + if (pio_sm_set_consecutive_pindirs(m_pio, m_sm0, m_clkPin, 1, true) != + PICO_OK || + pio_sm_set_consecutive_pindirs(m_pio, m_sm0, m_cmdPin, 1, true) != + PICO_OK || + pio_sm_set_consecutive_pindirs(m_pio, m_sm0, m_dat0Pin, 4, false) != + PICO_OK) { + sdError(SD_CARD_ERROR_ADD_PIO_PROGRAM); + goto fail; + } + return true; + +fail: + pioEnd(); + return false; +} +//------------------------------------------------------------------------------ +// A few cards still need at least 74 clocks after power-up. from the spec: +// +// After 1 ms VDD stable time, host provides at least 74 clocks while keeping +// CMD high before issuing the first command. In the case of SPI mode, CS +// shall be held high during 74 clock cycles. +// +// The original April 15, 2001 spec explains the 74 clocks: +// +// The additional 10 clocks (over the 64 clocks after which the card should be +// ready for communication) is provided to eliminate power-up synchronization +// problems. +// +void PioSdioCard::powerUpClockCycles() { + // Two clk_sys per SD clock cycle. + uint32_t nWait = ceil(0.0005 * clock_get_hz(clk_sys) / SD_MAX_INIT_RATE_KHZ); + gpio_init(m_cmdPin); + gpio_set_drive_strength(m_cmdPin, GPIO_DRIVE_STRENGTH_8MA); + gpio_set_dir(m_cmdPin, true); + gpio_put(m_cmdPin, 1); + gpio_init(m_clkPin); + gpio_set_drive_strength(m_clkPin, GPIO_DRIVE_STRENGTH_8MA); + gpio_set_dir(m_clkPin, true); + + // Send 80 SD CLK cycles with CMD high. End with CLK low. + for (uint i = 0; i <= 160; i++) { + gpio_put(m_clkPin, 1 & i); + busy_wait_at_least_cycles(nWait); + } +} +//------------------------------------------------------------------------------ +bool PioSdioCard::readCID(cid_t* cid) { + memcpy(cid, &m_cid, sizeof(cid_t)); + return true; +} +//------------------------------------------------------------------------------ +bool PioSdioCard::readCSD(csd_t* csd) { + memcpy(csd, &m_csd, sizeof(csd_t)); + return true; +} +//------------------------------------------------------------------------------ +bool __time_critical_func(PioSdioCard::readData)(void* dst, size_t count) { + uint32_t buf[128]; + uint n32 = count / 4; + uint nr = n32 + 2; + const uint mask = (1ul << m_sm0) | (1ul << m_sm1); + io_wo_8* txFifo = reinterpret_cast(&m_pio->txf[m_sm1]); + pio_sm_init(m_pio, m_sm0, m_rdDataOffset, &m_rdDataConfig); + pio_sm_init(m_pio, m_sm1, m_rdClkOffset, &m_rdClkConfig); + pio_set_sm_mask_enabled(m_pio, mask, true); + + uint nf = nr < DAT_FIFO_DEPTH ? nr : DAT_FIFO_DEPTH; + for (uint it = 0; it < nf; it++) { + *txFifo = 0XFF; + } + io_ro_32* rxFifo = reinterpret_cast(&m_pio->rxf[m_sm0]); + uint32_t* dst32 = (uint)dst & 3 ? buf : reinterpret_cast(dst); + uint64_t crc = 0; + uint64_t chk = 0; + Timeout timeout(SD_READ_TIMEOUT); + uint ir = 0; + if (nf < nr) { + uint nb = nr - nf; + while (true) { + while (pio_sm_get_rx_fifo_level(m_pio, m_sm0) < 4) { + if (timeout.timedOut()) { + sdError(SD_CARD_ERROR_READ_TIMEOUT); + goto fail; + } + } + uint32_t tmp = *rxFifo; + *txFifo = 0XFF; + dst32[ir++] = __builtin_bswap32(tmp); + crc = crc16(crc, tmp); + tmp = *rxFifo; + *txFifo = 0XFF; + dst32[ir++] = __builtin_bswap32(tmp); + crc = crc16(crc, tmp); + if (ir == nb) { + break; + } + tmp = *rxFifo; + *txFifo = 0XFF; + dst32[ir++] = __builtin_bswap32(tmp); + crc = crc16(crc, tmp); + tmp = *rxFifo; + *txFifo = 0XFF; + dst32[ir++] = __builtin_bswap32(tmp); + crc = crc16(crc, tmp); + } + } + for (; ir < nr; ir++) { + while (pio_sm_is_rx_fifo_empty(m_pio, m_sm0)) { + if (timeout.timedOut()) { + sdError(SD_CARD_ERROR_READ_TIMEOUT); + goto fail; + } + } + uint32_t tmp = *rxFifo; + if (ir < n32) { + dst32[ir] = __builtin_bswap32(tmp); + crc = crc16(crc, tmp); + } else { + chk <<= 32; + chk |= tmp; + } + } + if (crc != chk) { +#if USE_DEBUG_MODE + Serial.printf("crc: %llX\r\nchk: %llX\r\n", crc, chk); +#endif // USE_DEBUG_MODE + sdError(SD_CARD_ERROR_READ_CRC); + goto fail; + } + pio_set_sm_mask_enabled(m_pio, mask, false); + if (dst32 == buf) { + memcpy(dst, buf, count); + } + return true; + +fail: + pio_set_sm_mask_enabled(m_pio, mask, false); + return false; +} +//------------------------------------------------------------------------------ +bool PioSdioCard::readData(uint8_t* dst) { return readData(dst, 512); } +//------------------------------------------------------------------------------ +bool PioSdioCard::readOCR(uint32_t* ocr) { + *ocr = m_ocr; + return true; +} +//------------------------------------------------------------------------------ +bool PioSdioCard::readSCR(scr_t* scr) { + memcpy(scr, &m_scr, sizeof(scr_t)); + return true; +} +//------------------------------------------------------------------------------ +bool PioSdioCard::readSDS(sds_t* sds) { + memcpy(sds, &m_sds, sizeof(sds_t)); + return true; +} +//------------------------------------------------------------------------------ +bool PioSdioCard::readSector(Sector_t sector, uint8_t* dst) { + if (m_curState != READ_STATE || sector != m_curSector) { + if (!syncDevice()) { + SDIO_FAIL(); + goto fail; + } + if (!readStart(sector)) { + sdError(SD_CARD_ERROR_READ_START); + goto fail; + } + m_curSector = sector; + m_curState = READ_STATE; + } + if (!readData(dst, 512)) { + SDIO_FAIL(); + goto fail; + } + m_curSector++; + return true; + +fail: + return false; +} +//------------------------------------------------------------------------------ +bool PioSdioCard::readSectors(Sector_t sector, uint8_t* dst, size_t ns) { + for (size_t i = 0; i < ns; i++) { + if (!readSector(sector + i, dst + i * 512UL)) { + SDIO_FAIL(); + goto fail; + } + } + return true; + +fail: + return false; +} +//------------------------------------------------------------------------------ +bool PioSdioCard::readStart(Sector_t sector) { + uint arg = m_highCapacity ? sector : 512 * sector; + if (!cardCommand(CMD18_R1, arg)) { + sdError(SD_CARD_ERROR_CMD18); + goto fail; + } + return true; + +fail: + return false; +} +//------------------------------------------------------------------------------ +bool PioSdioCard::readStop() { + if (!syncDevice()) { + SDIO_FAIL(); + return false; + } + return true; +} +//------------------------------------------------------------------------------ +uint32_t PioSdioCard::status() { + return cardCommand(CMD13_R1, m_rca) ? m_cardRsp : CARD_STATUS_ERROR; +} +//------------------------------------------------------------------------------ +Sector_t PioSdioCard::sectorCount() { return m_csd.capacity(); } +//------------------------------------------------------------------------------ +bool PioSdioCard::syncDevice() { + if (m_curState != IDLE_STATE) { + Timeout timeout(SD_INIT_TIMEOUT); + while (!gpio_get(m_dat0Pin)) { + if (timeout.timedOut()) { + sdError(SD_CARD_ERROR_CMD12); + goto fail; + } + } + if (!cardCommand(CMD12_R1, 0)) { + sdError(SD_CARD_ERROR_CMD12); + goto fail; + } + while (isBusy()) { + if (timeout.timedOut()) { + sdError(SD_CARD_ERROR_CMD12); + goto fail; + } + } + m_curState = IDLE_STATE; + } + return true; + +fail: + return false; +} +//------------------------------------------------------------------------------ +uint8_t PioSdioCard::type() const { + return !m_initDone ? 0 + : !m_version2 ? SD_CARD_TYPE_SD1 + : !m_highCapacity ? SD_CARD_TYPE_SD2 + : SD_CARD_TYPE_SDHC; +} +//------------------------------------------------------------------------------ +bool PioSdioCard::writeSector(Sector_t sector, const uint8_t* src) { + return writeSectors(sector, src, 1); +} +//------------------------------------------------------------------------------ +bool PioSdioCard::writeSectors(Sector_t sector, const uint8_t* src, size_t ns) { + if (m_curState != WRITE_STATE || m_curSector != sector) { + if (!syncDevice()) { + SDIO_FAIL(); + goto fail; + } + if (!writeStart(sector)) { + sdError(SD_CARD_ERROR_WRITE_START); + goto fail; + } + m_curSector = sector; + m_curState = WRITE_STATE; + } + for (size_t i = 0; i < ns; i++, src += 512) { + if (!writeData(src)) { + sdError(SD_CARD_ERROR_WRITE_DATA); + goto fail; + } + } + m_curSector += ns; + return true; +fail: + return false; +} +//------------------------------------------------------------------------------ +bool __time_critical_func(PioSdioCard::writeData)(const uint8_t* src) { + const uint32_t* src32; + uint32_t buf[128]; + if ((uint)src & 3) { + memcpy(buf, src, 512); + src32 = (const uint32_t*)buf; + } else { + src32 = (const uint32_t*)src; + } + uint32_t tmp; + io_wo_32* txFifo = reinterpret_cast(&m_pio->txf[m_sm0]); + io_ro_32* rxFifo = reinterpret_cast(&m_pio->rxf[m_sm1]); + uint8_t rsp; + uint mask = (1ul << m_sm0) | (1ul << m_sm1); + uint64_t crc = 0; + + Timeout timeout(SD_WRITE_TIMEOUT); + while (!gpio_get(m_dat0Pin)) { + if (timeout.timedOut()) { + sdError(SD_CARD_ERROR_WRITE_TIMEOUT); + goto fail; + } + } + pio_sm_init(m_pio, m_sm0, m_wrDataOffset, &m_wrDataConfig); + pio_sm_init(m_pio, m_sm1, m_wrRespOffset, &m_wrRespConfig); + *txFifo = 1048; // 8 + 1024 + 16 + 1 - 1; + pio_sm_exec(m_pio, m_sm0, pio_encode_out(pio_x, 32)); + pio_sm_exec(m_pio, m_sm0, pio_encode_set(pio_pindirs, 0XF)); + *txFifo = 0xFFFFFFF0; + pio_set_sm_mask_enabled(m_pio, mask, true); + for (int i = 0; i < 128;) { + while (pio_sm_get_tx_fifo_level(m_pio, m_sm0) > 4) { + if (timeout.timedOut()) { + sdError(SD_CARD_ERROR_WRITE_FIFO); + goto fail; + } + } + tmp = __builtin_bswap32(src32[i++]); + crc = crc16(crc, tmp); + *txFifo = tmp; + tmp = __builtin_bswap32(src32[i++]); + crc = crc16(crc, tmp); + *txFifo = tmp; + tmp = __builtin_bswap32(src32[i++]); + crc = crc16(crc, tmp); + *txFifo = tmp; + tmp = __builtin_bswap32(src32[i++]); + crc = crc16(crc, tmp); + *txFifo = tmp; + } + while (pio_sm_get_tx_fifo_level(m_pio, m_sm0) > 5) { + if (timeout.timedOut()) { + sdError(SD_CARD_ERROR_WRITE_FIFO); + goto fail; + } + } + *txFifo = static_cast(crc >> 32); + *txFifo = static_cast(crc); + *txFifo = 0xFFFFFFFF; + + while (pio_sm_is_rx_fifo_empty(m_pio, m_sm1)) { + if (timeout.timedOut()) { + sdError(SD_CARD_ERROR_READ_FIFO); + goto fail; + } + } + rsp = *rxFifo; + if ((rsp & 0X1F) != 0b101) { +#if USE_DEBUG_MODE + Serial.printf("wr rsp: %02X\n", rsp); +#endif // USE_DEBUG_MODE + sdError(SD_CARD_ERROR_WRITE_DATA); + goto fail; + } + return true; +fail: + pio_set_sm_mask_enabled(m_pio, mask, false); + return false; +} +//------------------------------------------------------------------------------ +bool PioSdioCard::writeStart(Sector_t sector) { + uint arg = m_highCapacity ? sector : 512 * sector; + if (!cardCommand(CMD25_R1, arg)) { + sdError(SD_CARD_ERROR_CMD25); + goto fail; + } + return true; +fail: + return false; +} +//------------------------------------------------------------------------------ +bool PioSdioCard::writeStop() { + if (!syncDevice()) { + SDIO_FAIL(); + return false; + } + return true; +} +#endif // ARDUINO_ARCH_RP2040 diff --git a/ports/raspberrypi/common-hal/sdioio/sdfat_pio/SdCard/PioSdio/PioSdioCard.h b/ports/raspberrypi/common-hal/sdioio/sdfat_pio/SdCard/PioSdio/PioSdioCard.h new file mode 100644 index 00000000000..d3d33051763 --- /dev/null +++ b/ports/raspberrypi/common-hal/sdioio/sdfat_pio/SdCard/PioSdio/PioSdioCard.h @@ -0,0 +1,357 @@ +/** + * Copyright (c) 2011-2025 Bill Greiman, 2026 Tim Cocks for Adafruit Industries + * This file is part of the SdFat library for SD memory cards. + * + * MIT License + * + * 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. + */ +/** + * \file + * \brief Classes for PIO SDIO cards. + */ +#pragma once +// CIRCUITPY-CHANGE: Upstream relies on Arduino.h (pulled in via SdFatConfig.h) +// to declare the RP2 SDK PIO types (PIO, pio_sm_config), the `uint` alias used +// by this class's members, and the SDK functions the driver calls (gpio_*, +// clock_get_hz, the pico/time helpers) plus memcpy. This vendored build trims +// that Arduino path, so include those directly here. +#include +#include "hardware/clocks.h" +#include "hardware/gpio.h" +#include "hardware/pio.h" +#include "pico/time.h" +#include "../../common/SysCall.h" +#include "../SdCardInterface.h" +#if defined(ARDUINO_ARCH_RP2040) && defined(PIN_SD_CLK) && \ + defined(PIN_SD_CMD_MOSI) && defined(PIN_SD_DAT0_MISO) && \ + defined(PIN_SD_DAT1) && defined(PIN_SD_DAT2) && defined(PIN_SD_DAT3_CS) +#define HAS_BUILTIN_PIO_SDIO +#endif +class PioSdioConfig; +/** SdioConfig type for PIO SDIO */ +typedef PioSdioConfig SdioConfig; +class PioSdioCard; +/** Sdio type for PIO SDIO */ +typedef PioSdioCard SdioCard; +// ------------------------------------------------------------------------------ +/** + * \class PioSdioConfig + * \brief SDIO card configuration. + */ +class PioSdioConfig { +public: + /** + * PioSdioConfig constructor. + * \param[in] clkPin gpio pin for SDIO CLK. + * \param[in] cmdPin gpio pin for SDIO CMD. + * \param[in] dat0Pin gpio start pin for SDIO DAT[4]. + * \param[in] clkDiv PIO clock divisor. + */ + PioSdioConfig(uint clkPin, uint cmdPin, uint dat0Pin, float clkDiv = 1.0) + : m_clkPin(clkPin), + m_cmdPin(cmdPin), + m_dat0Pin(dat0Pin), + m_clkDiv(clkDiv) { + } + /** \return gpio for SDIO CLK */ + uint clkPin() { + return m_clkPin; + } + /** \return gpio for SDIO CMD */ + uint cmdPin() { + return m_cmdPin; + } + /** \return gpio for SDIO DAT0 */ + uint dat0Pin() { + return m_dat0Pin; + } + /** \return PIO clock divisor */ + float clkDiv() { + return m_clkDiv; + } + +private: + PioSdioConfig() : m_clkPin(63u), m_cmdPin(63u), m_dat0Pin(63u), m_clkDiv(0) { + } + const uint8_t m_clkPin; + const uint8_t m_cmdPin; + const uint8_t m_dat0Pin; + const float m_clkDiv; +}; +// ------------------------------------------------------------------------------ +/** + * \class CmdRsp_t + * \brief SD command/response type. + */ +class CmdRsp_t { +public: + /** + * \param[in] idx_ Command index. + * \param[in] rsp_ Response type. + */ + CmdRsp_t(uint8_t idx_, uint8_t rsp_) : idx(idx_), rsp(rsp_) { + } + uint8_t idx; ///< Command index. + uint8_t rsp; ///< Response type. +}; +// ------------------------------------------------------------------------------ +/** + * \class PioSdioCard + * \brief Raw SDIO access to SD and SDHC flash memory cards. + */ +class PioSdioCard: public SdCardInterface { +public: + PioSdioCard() = default; // cppcheck-suppress uninitMemberVar + /** Initialize the SD card. + * \param[in] config SDIO card configuration. + * \return true for success or false for failure. + */ + bool begin(PioSdioConfig config); + /** CMD6 Switch mode: Check Function Set Function. + * \param[in] arg CMD6 argument. + * \param[out] status return status data. + * + * \return true for success or false for failure. + */ + bool cardCMD6(uint32_t arg, uint8_t *status) final; + /** Disable an SDIO card. + * not implemented. + */ + void end() final; + + #ifndef DOXYGEN_SHOULD_SKIP_THIS + uint32_t __attribute__((error("use sectorCount()"))) cardSize(); + #endif // DOXYGEN_SHOULD_SKIP_THIS + /** Erase a range of sectors. + * + * \param[in] firstSector The address of the first sector in the range. + * \param[in] lastSector The address of the last sector in the range. + * + * \note This function requests the SD card to do a flash erase for a + * range of sectors. The data on the card after an erase operation is + * either 0 or 1, depends on the card vendor. The card must support + * single sector erase. + * + * \return true for success or false for failure. + */ + bool erase(Sector_t firstSector, Sector_t lastSector) final; + /** + * \return code for the last error. See SdCardInfo.h for a list of error + * codes. + */ + uint8_t errorCode() const final; + /** \return error data for last error. */ + uint32_t errorData() const final; + /** \return error line for last error. Tmp function for debug. */ + uint32_t errorLine() const; + /** + * Check for busy with CMD13. + * + * \return true if busy else false. + */ + bool isBusy() final; + /** \return the SD clock frequency in kHz. */ + uint32_t kHzSdClk(); + /** + * Read a 512 byte sector from an SD card. + * + * \param[in] sector Logical sector to be read. + * \param[out] dst Pointer to the location that will receive the data. + * \return true for success or false for failure. + */ + bool readSector(Sector_t sector, uint8_t *dst) final; + /** + * Read multiple 512 byte sectors from an SD card. + * + * \param[in] sector Logical sector to be read. + * \param[in] ns Number of sectors to be read. + * \param[out] dst Pointer to the location that will receive the data. + * \return true for success or false for failure. + */ + bool readSectors(Sector_t sector, uint8_t *dst, size_t ns) final; + /** + * Read a card's CID register. The CID contains card identification + * information such as Manufacturer ID, Product name, Product serial + * number and Manufacturing date. + * + * \param[out] cid pointer to area for returned data. + * + * \return true for success or false for failure. + */ + bool readCID(cid_t *cid) final; + /** + * Read a card's CSD register. The CSD contains Card-Specific Data that + * provides information regarding access to the card's contents. + * + * \param[out] csd pointer to area for returned data. + * + * \return true for success or false for failure. + */ + bool readCSD(csd_t *csd) final; + /** Read one data sector in a multiple sector read sequence + * + * \param[out] dst Pointer to the location for the data to be read. + * + * \return true for success or false for failure. + */ + bool readData(uint8_t *dst); + /** Read OCR register. + * + * \param[out] ocr Value of OCR register. + * \return true for success or false for failure. + */ + bool readOCR(uint32_t *ocr) final; + /** Read SCR register. + * + * \param[out] scr Value of SCR register. + * \return true for success or false for failure. + */ + bool readSCR(scr_t *scr) final; + /** Return the 64 byte SD Status register. + * \param[out] sds location for 64 status bytes. + * \return true for success or false for failure. + */ + bool readSDS(sds_t *sds) final; + /** Start a read multiple sectors sequence. + * + * \param[in] sector Address of first sector in sequence. + * + * \note This function is used with readData() and readStop() for optimized + * multiple sector reads. + * + * \return true for success or false for failure. + */ + bool readStart(Sector_t sector); + /** End a read multiple sectors sequence. + * + * \return true for success or false for failure. + */ + bool readStop(); + /** \return SDIO card status. */ + uint32_t status() final; + /** + * Determine the size of an SD flash memory card. + * + * \return The number of 512 byte data sectors in the card + * or zero if an error occurs. + */ + Sector_t sectorCount() final; + /** + * Send CMD12 to stop read or write. + * + * \param[in] blocking If true, wait for command complete. + * + * \return true for success or false for failure. + */ + bool stopTransmission(bool blocking); + /** \return success if sync successful. Not for user apps. */ + bool syncDevice() final; + /** Return the card type: SD V1, SD V2 or SDHC + * \return 0 - SD V1, 1 - SD V2, or 3 - SDHC. + */ + uint8_t type() const final; + /** + * Writes a 512 byte sector to an SD card. + * + * \param[in] sector Logical sector to be written. + * \param[in] src Pointer to the location of the data to be written. + * \return true for success or false for failure. + */ + bool writeSector(Sector_t sector, const uint8_t *src) final; + /** + * Write multiple 512 byte sectors to an SD card. + * + * \param[in] sector Logical sector to be written. + * \param[in] ns Number of sectors to be written. + * \param[in] src Pointer to the location of the data to be written. + * \return true for success or false for failure. + */ + bool writeSectors(Sector_t sector, const uint8_t *src, size_t ns) final; + /** Write one data sector in a multiple sector write sequence. + * \param[in] src Pointer to the location of the data to be written. + * \return true for success or false for failure. + */ + bool writeData(const uint8_t *src); + /** Start a write multiple sectors sequence. + * + * \param[in] sector Address of first sector in sequence. + * + * \note This function is used with writeData() and writeStop() + * for optimized multiple sector writes. + * + * \return true for success or false for failure. + */ + bool writeStart(Sector_t sector); + + /** End a write multiple sectors sequence. + * + * \return true for success or false for failure. + */ + bool writeStop(); + +private: + // ---------------------------------------------------------------------------- + bool cardAcmd(uint32_t rca, CmdRsp_t cmdRsp, uint32_t arg); + bool cardCommand(CmdRsp_t cmd, uint32_t arg, void *rsp = nullptr); + void pioConfig(float clkDiv); + void pioEnd(); + bool pioInit(); + void powerUpClockCycles(); + bool readData(void *dst, size_t count); + void setSdErrorCode(uint8_t code, uint32_t line) { + m_errorCode = code; + m_errorLine = line; + } + static const uint8_t IDLE_STATE = 0; + static const uint8_t READ_STATE = 1; + static const uint8_t WRITE_STATE = 2; + Sector_t m_curSector = 0; + uint8_t m_curState = IDLE_STATE; + uint m_cardRsp; + uint m_errorCode; + uint m_errorLine; + bool m_highCapacity; + bool m_initDone = false; + uint m_ocr; + bool m_version2; + uint m_rca; + cid_t m_cid; + csd_t m_csd; + scr_t m_scr; + sds_t m_sds; + + float m_clkDiv = 0; + uint m_clkPin = 63u; // PIN_SDIO_UNDEFINED; + uint m_cmdPin = 63u; // PIN_SDIO_UNDEFINED; + uint m_dat0Pin = 63u; // PIN_SDIO_UNDEFINED; + PIO m_pio = nullptr; + int m_sm0 = -1; + int m_sm1 = -1; + int m_cmdRspOffset = -1; + pio_sm_config m_cmdConfig; + int m_rdDataOffset = -1; + pio_sm_config m_rdDataConfig; + int m_rdClkOffset = -1; + pio_sm_config m_rdClkConfig; + int m_wrDataOffset = -1; + pio_sm_config m_wrDataConfig; + int m_wrRespOffset = -1; + pio_sm_config m_wrRespConfig; +}; diff --git a/ports/raspberrypi/common-hal/sdioio/sdfat_pio/SdCard/PioSdio/PioSdioCard.pio.h b/ports/raspberrypi/common-hal/sdioio/sdfat_pio/SdCard/PioSdio/PioSdioCard.pio.h new file mode 100644 index 00000000000..3130fd4edc0 --- /dev/null +++ b/ports/raspberrypi/common-hal/sdioio/sdfat_pio/SdCard/PioSdio/PioSdioCard.pio.h @@ -0,0 +1,331 @@ +/** +* Copyright (c) 2011-2025 Bill Greiman, 2026 Tim Cocks for Adafruit Industries + * This file is part of the SdFat library for SD memory cards. + * + * MIT License + * + * 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. + */ +// -------------------------------------------------- // +// This file is autogenerated by pioasm; do not edit! // +// -------------------------------------------------- // + +#pragma once + +#if !PICO_NO_HARDWARE +#include "hardware/pio.h" +#endif + +#define SDIO_IRQ 7 + +// ------- // +// cmd_rsp // +// ------- // + +#define cmd_rsp_wrap_target 0 +#define cmd_rsp_wrap 9 +#define cmd_rsp_pio_version 0 + +static const uint16_t cmd_rsp_program_instructions[] = { + // .wrap_target + 0x7101, // 0: out pins, 1 side 0 [1] + 0x1940, // 1: jmp x--, 0 side 1 [1] + 0x1160, // 2: jmp !y, 0 side 0 [1] + 0xfb80, // 3: set pindirs, 0 side 1 [3] + 0xb342, // 4: nop side 0 [3] + 0xba42, // 5: nop side 1 [2] + 0x00c4, // 6: jmp pin, 4 + 0x4001, // 7: in pins, 1 + 0x9260, // 8: push iffull block side 0 [2] + 0x1987, // 9: jmp y--, 7 side 1 [1] + // .wrap +}; + +#if !PICO_NO_HARDWARE +static const struct pio_program cmd_rsp_program = { + .instructions = cmd_rsp_program_instructions, + .length = 10, + .origin = -1, + .pio_version = cmd_rsp_pio_version, + #if PICO_PIO_VERSION > 0 + .used_gpio_ranges = 0x0 + #endif +}; + +static inline pio_sm_config cmd_rsp_program_get_default_config(uint offset) { + pio_sm_config c = pio_get_default_sm_config(); + sm_config_set_wrap(&c, offset + cmd_rsp_wrap_target, offset + cmd_rsp_wrap); + sm_config_set_sideset(&c, 2, true, false); + return c; +} + +static inline pio_sm_config pio_cmd_rsp_program_config(uint offset, uint cmd_pin, uint clk_pin, float clk_div) { + pio_sm_config c = cmd_rsp_program_get_default_config(offset); + sm_config_set_sideset_pins(&c, clk_pin); + sm_config_set_out_pins(&c, cmd_pin, 1); + sm_config_set_in_pins(&c, cmd_pin); + sm_config_set_set_pins(&c, cmd_pin, 1); + sm_config_set_jmp_pin(&c, cmd_pin); + sm_config_set_in_shift(&c, false, false, 8); + sm_config_set_out_shift(&c, false, true, 8); + sm_config_set_clkdiv(&c, clk_div); + return c; +} + +#endif + +// ------ // +// rd_clk // +// ------ // + +#define rd_clk_wrap_target 3 +#define rd_clk_wrap 4 +#define rd_clk_pio_version 0 + +static const uint16_t rd_clk_program_instructions[] = { + 0xb342, // 0: nop side 0 [3] + 0x1bc0, // 1: jmp pin, 0 side 1 [3] + 0xc007, // 2: irq nowait 7 + // .wrap_target + 0x7261, // 3: out null, 1 side 0 [2] + 0xb942, // 4: nop side 1 [1] + // .wrap +}; + +#if !PICO_NO_HARDWARE +static const struct pio_program rd_clk_program = { + .instructions = rd_clk_program_instructions, + .length = 5, + .origin = -1, + .pio_version = rd_clk_pio_version, + #if PICO_PIO_VERSION > 0 + .used_gpio_ranges = 0x0 + #endif +}; + +static inline pio_sm_config rd_clk_program_get_default_config(uint offset) { + pio_sm_config c = pio_get_default_sm_config(); + sm_config_set_wrap(&c, offset + rd_clk_wrap_target, offset + rd_clk_wrap); + sm_config_set_sideset(&c, 2, true, false); + return c; +} + +static inline pio_sm_config pio_rd_clk_program_config(uint offset, uint d0_pin, uint clk_pin, float clk_div) { + pio_sm_config c = rd_clk_program_get_default_config(offset); + sm_config_set_fifo_join(&c, PIO_FIFO_JOIN_TX); + sm_config_set_sideset_pins(&c, clk_pin); + sm_config_set_in_pins(&c, d0_pin); + sm_config_set_jmp_pin(&c, d0_pin); + sm_config_set_out_shift(&c, false, true, 8); + sm_config_set_clkdiv(&c, clk_div); + return c; +} + +#endif + +// ------- // +// rd_data // +// ------- // + +#define rd_data_wrap_target 1 +#define rd_data_wrap 3 +#define rd_data_pio_version 0 + +#define rd_data_offset_wait0 1u +#define rd_data_offset_wait1 2u + +static const uint16_t rd_data_program_instructions[] = { + 0x20c7, // 0: wait 1 irq, 7 + // .wrap_target + 0x2000, // 1: wait 0 gpio, 0 + 0x2080, // 2: wait 1 gpio, 0 + 0x4004, // 3: in pins, 4 + // .wrap +}; + +#if !PICO_NO_HARDWARE +static const struct pio_program rd_data_program = { + .instructions = rd_data_program_instructions, + .length = 4, + .origin = -1, + .pio_version = rd_data_pio_version, + #if PICO_PIO_VERSION > 0 + .used_gpio_ranges = 0x1 + #endif +}; + +static inline pio_sm_config rd_data_program_get_default_config(uint offset) { + pio_sm_config c = pio_get_default_sm_config(); + sm_config_set_wrap(&c, offset + rd_data_wrap_target, offset + rd_data_wrap); + return c; +} + +static inline void rd_data_patch_program(pio_program *prog, uint16_t *inst, uint clk_pin) { + *prog = rd_data_program; + prog->instructions = inst; + #if PICO_PIO_VERSION > 0 + prog->used_gpio_ranges = clk_pin < 16 ? 1 : clk_pin < 32 ? 2 : clk_pin < 48 ? 4 : 8; + #endif + memcpy(inst, rd_data_program_instructions, sizeof(rd_data_program_instructions)); + inst[rd_data_offset_wait0] = pio_encode_wait_gpio(0, clk_pin); + inst[rd_data_offset_wait1] = pio_encode_wait_gpio(1, clk_pin); +} +static inline pio_sm_config pio_rd_data_program_config(uint offset, uint data_pin, float clk_div) { + pio_sm_config c = rd_data_program_get_default_config(offset); + sm_config_set_fifo_join(&c, PIO_FIFO_JOIN_RX); + sm_config_set_in_pins(&c, data_pin); + sm_config_set_in_shift(&c, false, true, 32); + sm_config_set_clkdiv(&c, clk_div); + return c; +} + +#endif + +// ------- // +// wr_data // +// ------- // + +#define wr_data_wrap_target 3 +#define wr_data_wrap 3 +#define wr_data_pio_version 0 + +static const uint16_t wr_data_program_instructions[] = { + 0x7104, // 0: out pins, 4 side 0 [1] + 0x1940, // 1: jmp x--, 0 side 1 [1] + 0xc007, // 2: irq nowait 7 + // .wrap_target + 0xa042, // 3: nop + // .wrap +}; + +#if !PICO_NO_HARDWARE +static const struct pio_program wr_data_program = { + .instructions = wr_data_program_instructions, + .length = 4, + .origin = -1, + .pio_version = wr_data_pio_version, + #if PICO_PIO_VERSION > 0 + .used_gpio_ranges = 0x0 + #endif +}; + +static inline pio_sm_config wr_data_program_get_default_config(uint offset) { + pio_sm_config c = pio_get_default_sm_config(); + sm_config_set_wrap(&c, offset + wr_data_wrap_target, offset + wr_data_wrap); + sm_config_set_sideset(&c, 2, true, false); + return c; +} + +static inline pio_sm_config pio_wr_data_program_config(uint offset, uint data_pin, uint clk_pin, float clk_div) { + pio_sm_config c = wr_data_program_get_default_config(offset); + sm_config_set_fifo_join(&c, PIO_FIFO_JOIN_TX); + sm_config_set_sideset_pins(&c, clk_pin); + sm_config_set_out_pins(&c, data_pin, 4); + sm_config_set_set_pins(&c, data_pin, 4); + sm_config_set_out_shift(&c, false, true, 32); + sm_config_set_clkdiv(&c, clk_div); + return c; +} + +#endif + +// ------- // +// wr_resp // +// ------- // + +#define wr_resp_wrap_target 2 +#define wr_resp_wrap 3 +#define wr_resp_pio_version 0 + +static const uint16_t wr_resp_program_instructions[] = { + 0x20c7, // 0: wait 1 irq, 7 + 0xe180, // 1: set pindirs, 0 [1] + // .wrap_target + 0x5c01, // 2: in pins, 1 side 1 [4] + 0x9440, // 3: push iffull noblock side 0 [4] + // .wrap +}; + +#if !PICO_NO_HARDWARE +static const struct pio_program wr_resp_program = { + .instructions = wr_resp_program_instructions, + .length = 4, + .origin = -1, + .pio_version = wr_resp_pio_version, + #if PICO_PIO_VERSION > 0 + .used_gpio_ranges = 0x0 + #endif +}; + +static inline pio_sm_config wr_resp_program_get_default_config(uint offset) { + pio_sm_config c = pio_get_default_sm_config(); + sm_config_set_wrap(&c, offset + wr_resp_wrap_target, offset + wr_resp_wrap); + sm_config_set_sideset(&c, 2, true, false); + return c; +} + +static inline pio_sm_config pio_wr_resp_program_config(uint offset, uint data_pin, uint clk_pin, float clk_div) { + pio_sm_config c = wr_resp_program_get_default_config(offset); + sm_config_set_sideset_pins(&c, clk_pin); + sm_config_set_in_pins(&c, data_pin); + sm_config_set_set_pins(&c, data_pin, 4); + sm_config_set_in_shift(&c, false, false, 8); + sm_config_set_clkdiv(&c, clk_div); + return c; +} +static const size_t total_pio_length = + cmd_rsp_program.length + rd_data_program.length + rd_clk_program.length + + wr_data_program.length + wr_resp_program.length; + +#endif + +// -------- // +// fill_pio // +// -------- // + +#define fill_pio_wrap_target 0 +#define fill_pio_wrap 3 +#define fill_pio_pio_version 0 + +static const uint16_t fill_pio_program_instructions[] = { + // .wrap_target + 0x0000, // 0: jmp 0 + 0x0001, // 1: jmp 1 + 0x0002, // 2: jmp 2 + 0x0003, // 3: jmp 3 + // .wrap +}; + +#if !PICO_NO_HARDWARE +static const struct pio_program fill_pio_program = { + .instructions = fill_pio_program_instructions, + .length = 4, + .origin = -1, + .pio_version = fill_pio_pio_version, + #if PICO_PIO_VERSION > 0 + .used_gpio_ranges = 0x0 + #endif +}; + +static inline pio_sm_config fill_pio_program_get_default_config(uint offset) { + pio_sm_config c = pio_get_default_sm_config(); + sm_config_set_wrap(&c, offset + fill_pio_wrap_target, offset + fill_pio_wrap); + return c; +} +#endif diff --git a/ports/raspberrypi/common-hal/sdioio/sdfat_pio/SdCard/SdCardInfo.h b/ports/raspberrypi/common-hal/sdioio/sdfat_pio/SdCard/SdCardInfo.h new file mode 100644 index 00000000000..c84f9778725 --- /dev/null +++ b/ports/raspberrypi/common-hal/sdioio/sdfat_pio/SdCard/SdCardInfo.h @@ -0,0 +1,530 @@ +/** + * Copyright (c) 2011-2025 Bill Greiman, 2026 Tim Cocks for Adafruit Industries + * This file is part of the SdFat library for SD memory cards. + * + * MIT License + * + * 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. + */ +/** + * \file + * \brief Definitions for SD cards. + */ +#pragma once +#include + +#include "../common/SysCall.h" +// Based on the document: +// +// SD Specifications +// Part 1 +// Physical Layer +// Simplified Specification +// Version 8.00 +// Sep 23, 2020 +// +// https://www.sdcard.org/downloads/pls/ +#if __BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__ +// SD registers are big endian. +#error bit fields in structures assume little endian processor. +#endif // __BYTE_ORDER__ != __ORDER_LITTLE_ENDIAN__ +// ------------------------------------------------------------------------------ +// SD card errors +// See the SD Specification for command info. +/** Define error codes and brief description. */ +#define SD_ERROR_CODE_LIST \ + SD_CARD_ERROR(NONE, "No error") \ + SD_CARD_ERROR(CMD0, "Card reset failed") \ + SD_CARD_ERROR(CMD2, "SDIO read CID") \ + SD_CARD_ERROR(CMD3, "SDIO publish RCA") \ + SD_CARD_ERROR(CMD6, "Switch card function") \ + SD_CARD_ERROR(CMD7, "SDIO card select") \ + SD_CARD_ERROR(CMD8, "Send and check interface settings") \ + SD_CARD_ERROR(CMD9, "Read CSD data") \ + SD_CARD_ERROR(CMD10, "Read CID data") \ + SD_CARD_ERROR(CMD12, "Stop multiple block transmission") \ + SD_CARD_ERROR(CMD13, "Read card status") \ + SD_CARD_ERROR(CMD17, "Read single block") \ + SD_CARD_ERROR(CMD18, "Read multiple blocks") \ + SD_CARD_ERROR(CMD24, "Write single block") \ + SD_CARD_ERROR(CMD25, "Write multiple blocks") \ + SD_CARD_ERROR(CMD32, "Set first erase block") \ + SD_CARD_ERROR(CMD33, "Set last erase block") \ + SD_CARD_ERROR(CMD38, "Erase selected blocks") \ + SD_CARD_ERROR(CMD58, "Read OCR register") \ + SD_CARD_ERROR(CMD59, "Set CRC mode") \ + SD_CARD_ERROR(ACMD6, "Set SDIO bus width") \ + SD_CARD_ERROR(ACMD13, "Read extended status") \ + SD_CARD_ERROR(ACMD23, "Set pre-erased count") \ + SD_CARD_ERROR(ACMD41, "Activate card initialization") \ + SD_CARD_ERROR(ACMD51, "Read SCR data") \ + SD_CARD_ERROR(READ_TOKEN, "Bad read data token") \ + SD_CARD_ERROR(READ_CRC, "Read CRC error") \ + SD_CARD_ERROR(READ_FIFO, "SDIO fifo read timeout") \ + SD_CARD_ERROR(READ_REG, "Read CID or CSD failed.") \ + SD_CARD_ERROR(READ_START, "Bad readStart argument") \ + SD_CARD_ERROR(READ_TIMEOUT, "Read data timeout") \ + SD_CARD_ERROR(STOP_TRAN, "Multiple block stop failed") \ + SD_CARD_ERROR(TRANSFER_COMPLETE, "SDIO transfer complete") \ + SD_CARD_ERROR(WRITE_DATA, "Write data not accepted") \ + SD_CARD_ERROR(WRITE_FIFO, "SDIO fifo write timeout") \ + SD_CARD_ERROR(WRITE_START, "Bad writeStart argument") \ + SD_CARD_ERROR(WRITE_PROGRAMMING, "Flash programming") \ + SD_CARD_ERROR(WRITE_TIMEOUT, "Write timeout") \ + SD_CARD_ERROR(DMA, "DMA transfer failed") \ + SD_CARD_ERROR(ERASE, "Card did not accept erase commands") \ + SD_CARD_ERROR(ERASE_SINGLE_SECTOR, "Card does not support erase") \ + SD_CARD_ERROR(ERASE_TIMEOUT, "Erase command timeout") \ + SD_CARD_ERROR(INIT_NOT_CALLED, "Card has not been initialized") \ + SD_CARD_ERROR(ADD_PIO_PROGRAM, "Add PIO program") \ + SD_CARD_ERROR(INVALID_CARD_CONFIG, "Invalid card config") \ + SD_CARD_ERROR(FUNCTION_NOT_SUPPORTED, "Unsupported SDIO command") + +enum { +/** Macro for generation of error codes using an enum. */ +#define SD_CARD_ERROR(e, m) SD_CARD_ERROR_##e, + SD_ERROR_CODE_LIST +#undef SD_CARD_ERROR + SD_CARD_ERROR_UNKNOWN +}; +/** Print the enum symbol for an error code. + * \param[in] pr Print stream. + * \param[in] code enum value for error. + */ +void printSdErrorSymbol(print_t *pr, uint8_t code); +/** Print text for an error code. + * \param[in] pr Print stream. + * \param[in] code enum value for error. + */ +void printSdErrorText(print_t *pr, uint8_t code); +// ------------------------------------------------------------------------------ +// card types +/** Standard capacity V1 SD card */ +const uint8_t SD_CARD_TYPE_SD1 = 1; +/** Standard capacity V2 SD card */ +const uint8_t SD_CARD_TYPE_SD2 = 2; +/** High Capacity SD card */ +const uint8_t SD_CARD_TYPE_SDHC = 3; +// ------------------------------------------------------------------------------ +// SD operation timeouts +/** command timeout ms */ +const uint16_t SD_CMD_TIMEOUT = 300; +/** erase timeout ms */ +const uint16_t SD_ERASE_TIMEOUT = 10000; +/** init timeout ms */ +const uint16_t SD_INIT_TIMEOUT = 2000; +/** read timeout ms */ +const uint16_t SD_READ_TIMEOUT = 300; +/** write time out ms */ +const uint16_t SD_WRITE_TIMEOUT = 600; +// ------------------------------------------------------------------------------ +// SD card commands +/** GO_IDLE_STATE - init card in spi mode if CS low */ +const uint8_t CMD0 = 0X00; +/** ALL_SEND_CID - Asks any card to send the CID. */ +const uint8_t CMD2 = 0X02; +/** SEND_RELATIVE_ADDR - Ask the card to publish a new RCA. */ +const uint8_t CMD3 = 0X03; +/** SWITCH_FUNC - Switch Function Command */ +const uint8_t CMD6 = 0X06; +/** SELECT/DESELECT_CARD - toggles between the stand-by and transfer states. */ +const uint8_t CMD7 = 0X07; +/** SEND_IF_COND - verify SD Memory Card interface operating condition.*/ +const uint8_t CMD8 = 0X08; +/** SEND_CSD - read the Card Specific Data (CSD register) */ +const uint8_t CMD9 = 0X09; +/** SEND_CID - read the card identification information (CID register) */ +const uint8_t CMD10 = 0X0A; +/** VOLTAGE_SWITCH -Switch to 1.8V bus signaling level. */ +const uint8_t CMD11 = 0X0B; +/** STOP_TRANSMISSION - end multiple sector read sequence */ +const uint8_t CMD12 = 0X0C; +/** SEND_STATUS - read the card status register */ +const uint8_t CMD13 = 0X0D; +/** READ_SINGLE_SECTOR - read a single data sector from the card */ +const uint8_t CMD17 = 0X11; +/** READ_MULTIPLE_SECTOR - read multiple data sectors from the card */ +const uint8_t CMD18 = 0X12; +/** WRITE_SECTOR - write a single data sector to the card */ +const uint8_t CMD24 = 0X18; +/** WRITE_MULTIPLE_SECTOR - write sectors of data until a STOP_TRANSMISSION */ +const uint8_t CMD25 = 0X19; +/** ERASE_WR_BLK_START - sets the address of the first sector to be erased */ +const uint8_t CMD32 = 0X20; +/** ERASE_WR_BLK_END - sets the address of the last sector of the continuous + range to be erased*/ +const uint8_t CMD33 = 0X21; +/** ERASE - erase all previously selected sectors */ +const uint8_t CMD38 = 0X26; +/** APP_CMD - escape for application specific command */ +const uint8_t CMD55 = 0X37; +/** READ_OCR - read the OCR register of a card */ +const uint8_t CMD58 = 0X3A; +/** CRC_ON_OFF - enable or disable CRC checking */ +const uint8_t CMD59 = 0X3B; +/** SET_BUS_WIDTH - Defines the data bus width for data transfer. */ +const uint8_t ACMD6 = 0X06; +/** SD_STATUS - Send the SD Status. */ +const uint8_t ACMD13 = 0X0D; +/** SET_WR_BLK_ERASE_COUNT - Set the number of write sectors to be + pre-erased before writing */ +const uint8_t ACMD23 = 0X17; +/** SD_SEND_OP_COMD - Sends host capacity support information and + activates the card's initialization process */ +const uint8_t ACMD41 = 0X29; +/** Reads the SD Configuration Register (SCR). */ +const uint8_t ACMD51 = 0X33; +// ============================================================================== +// CARD_STATUS +/** The command's argument was out of the allowed range for this card. */ +const uint32_t CARD_STATUS_OUT_OF_RANGE = 1UL << 31; +/** A misaligned address which did not match the sector length. */ +const uint32_t CARD_STATUS_ADDRESS_ERROR = 1UL << 30; +/** The transferred sector length is not allowed for this card. */ +const uint32_t CARD_STATUS_SECTOR_LEN_ERROR = 1UL << 29; +/** An error in the sequence of erase commands occurred. */ +const uint32_t CARD_STATUS_ERASE_SEQ_ERROR = 1UL << 28; +/** An invalid selection of write-sectors for erase occurred. */ +const uint32_t CARD_STATUS_ERASE_PARAM = 1UL << 27; +/** Set when the host attempts to write to a protected sector. */ +const uint32_t CARD_STATUS_WP_VIOLATION = 1UL << 26; +/** When set, signals that the card is locked by the host. */ +const uint32_t CARD_STATUS_CARD_IS_LOCKED = 1UL << 25; +/** Set when a sequence or password error has been detected. */ +const uint32_t CARD_STATUS_LOCK_UNLOCK_FAILED = 1UL << 24; +/** The CRC check of the previous command failed. */ +const uint32_t CARD_STATUS_COM_CRC_ERROR = 1UL << 23; +/** Command not legal for the card state. */ +const uint32_t CARD_STATUS_ILLEGAL_COMMAND = 1UL << 22; +/** Card internal ECC was applied but failed to correct the data. */ +const uint32_t CARD_STATUS_CARD_ECC_FAILED = 1UL << 21; +/** Internal card controller error */ +const uint32_t CARD_STATUS_CC_ERROR = 1UL << 20; +/** A general or an unknown error occurred during the operation. */ +const uint32_t CARD_STATUS_ERROR = 1UL << 19; +// bits 19, 18, and 17 reserved. +/** Permanent WP set or attempt to change read only values of CSD. */ +const uint32_t CARD_STATUS_CSD_OVERWRITE = 1UL << 16; +/** partial address space was erased due to write protect. */ +const uint32_t CARD_STATUS_WP_ERASE_SKIP = 1UL << 15; +/** The command has been executed without using the internal ECC. */ +const uint32_t CARD_STATUS_CARD_ECC_DISABLED = 1UL << 14; +/** out of erase sequence command was received. */ +const uint32_t CARD_STATUS_ERASE_RESET = 1UL << 13; +/** The state of the card when receiving the command. + * 0 = idle + * 1 = ready + * 2 = ident + * 3 = stby + * 4 = tran + * 5 = data + * 6 = rcv + * 7 = prg + * 8 = dis + * 9-14 = reserved + * 15 = reserved for I/O mode + */ +const uint32_t CARD_STATUS_CURRENT_STATE = 0XF << 9; +/** Shift for current state. */ +const uint32_t CARD_STATUS_CURRENT_STATE_SHIFT = 9; +/** Corresponds to buffer empty signaling on the bus. */ +const uint32_t CARD_STATUS_READY_FOR_DATA = 1UL << 8; +// bit 7 reserved. +/** Extension Functions may set this bit to get host to deal with events. */ +const uint32_t CARD_STATUS_FX_EVENT = 1UL << 6; +/** The card will expect ACMD, or the command has been interpreted as ACMD */ +const uint32_t CARD_STATUS_APP_CMD = 1UL << 5; +// bit 4 reserved. +/** Error in the sequence of the authentication process. */ +const uint32_t CARD_STATUS_AKE_SEQ_ERROR = 1UL << 3; +// bits 2,1, and 0 reserved for manufacturer test mode. +// ============================================================================== +/** status for card in the ready state */ +const uint8_t R1_READY_STATE = 0X00; +/** status for card in the idle state */ +const uint8_t R1_IDLE_STATE = 0X01; +/** status bit for illegal command */ +const uint8_t R1_ILLEGAL_COMMAND = 0X04; +/** start data token for read or write single sector*/ +const uint8_t DATA_START_SECTOR = 0XFE; +/** stop token for write multiple sectors*/ +const uint8_t STOP_TRAN_TOKEN = 0XFD; +/** start data token for write multiple sectors*/ +const uint8_t WRITE_MULTIPLE_TOKEN = 0XFC; +/** mask for data response tokens after a write sector operation */ +const uint8_t DATA_RES_MASK = 0X1F; +/** write data accepted token */ +const uint8_t DATA_RES_ACCEPTED = 0X05; +// ============================================================================== +/** + * \class cid_t + * \brief Card Identification (CID) register. + */ +struct cid_t { + // byte 0 + /** Manufacturer ID */ + uint8_t mid; + // byte 1-2 + /** OEM/Application ID. */ + char oid[2]; + // byte 3-7 + /** Product name. */ + char pnm[5]; + // byte 8 + /** Product revision - n.m two 4-bit nibbles. */ + uint8_t prv; + // byte 9-12 + /** Product serial 32-bit number Big Endian format. */ + uint8_t psn8[4]; + // byte 13-14 + /** Manufacturing date big endian - four nibbles RYYM Reserved Year Month. */ + uint8_t mdt[2]; + // byte 15 + /** CRC7 bits 1-7 checksum, bit 0 always 1 */ + uint8_t crc; + // Extract big endian fields. + /** \return major revision number. */ + int prvN() const { + return prv >> 4; + } + /** \return minor revision number. */ + int prvM() const { + return prv & 0XF; + } + /** \return Manufacturing Year. */ + int mdtYear() const { + return 2000 + ((mdt[0] & 0XF) << 4) + (mdt[1] >> 4); + } + /** \return Manufacturing Month. */ + int mdtMonth() const { + return mdt[1] & 0XF; + } + /** \return Product Serial Number. */ + uint32_t psn() const { + return static_cast < uint32_t > (psn8[0]) << 24 | + static_cast < uint32_t > (psn8[1]) << 16 | + static_cast < uint32_t > (psn8[2]) << 8 | static_cast < uint32_t > (psn8[3]); + } +} __attribute__((packed)); +// ============================================================================== +/** + * \class csd_t + * \brief Union of old and new style CSD register. + */ +struct csd_t { + /** union of all CSD versions */ + uint8_t csd[16]; + // Extract big endian fields. + /** \return Capacity in sectors */ + uint32_t capacity() const { + uint32_t c_size; + uint8_t ver = csd[0] >> 6; + if (ver == 0) { + c_size = static_cast < uint32_t > (csd[6] & 3) << 10; + c_size |= static_cast < uint32_t > (csd[7]) << 2 | csd[8] >> 6; + uint8_t c_size_mult = (csd[9] & 3) << 1 | csd[10] >> 7; + uint8_t read_bl_len = csd[5] & 15; + return (c_size + 1) << (c_size_mult + read_bl_len + 2 - 9); + } else if (ver == 1) { + c_size = static_cast < uint32_t > (csd[7] & 63) << 16; + c_size |= static_cast < uint32_t > (csd[8]) << 8; + c_size |= csd[9]; + return (c_size + 1) << 10; + } else { + return 0; + } + } + /** \return true if erase granularity is single block. */ + bool eraseSingleBlock() const { + return csd[10] & 0X40; + } + /** \return erase size in 512 byte blocks if eraseSingleBlock is false. */ + int eraseSize() const { + return ((csd[10] & 0X3F) << 1 | csd[11] >> 7) + 1; + } + /** \return true if the contents is copied or true if original. */ + bool copy() const { + return csd[14] & 0X40; + } + /** \return true if the entire card is permanently write protected. */ + bool permWriteProtect() const { + return csd[14] & 0X20; + } + /** \return true if the entire card is temporarily write protected. */ + bool tempWriteProtect() const { + return csd[14] & 0X10; + } +}; +// ============================================================================== +/** + * \class scr_t + * \brief SCR register. + */ +struct scr_t { + /** Bytes 0-3 SD Association, bytes 4-7 reserved for manufacturer. */ + uint8_t scr[8]; + /** \return SCR_STRUCTURE field - must be zero.*/ + uint8_t srcStructure() const { + return scr[0] >> 4; + } + /** \return SD_SPEC field 0 - v1.0 or V1.01, 1 - 1.10, 2 - V2.00 or greater */ + uint8_t sdSpec() const { + return scr[0] & 0XF; + } + /** \return false if all zero, true if all one. */ + bool dataAfterErase() const { + return scr[1] & 0X80; + } + /** \return CPRM Security Version. */ + uint8_t sdSecurity() const { + return (scr[1] >> 4) & 0X7; + } + /** \return 0101b. */ + uint8_t sdBusWidths() const { + return scr[1] & 0XF; + } + /** \return true if V3.0 or greater. */ + bool sdSpec3() const { + return scr[2] & 0X80; + } + /** \return if true and sdSpecX is zero V4.xx. */ + bool sdSpec4() const { + return scr[2] & 0X4; + } + /** \return nonzero for version 5 or greater if sdSpec == 2, + sdSpec3 == true. Version is return plus four.*/ + uint8_t sdSpecX() const { + return (scr[2] & 0X3) << 2 | scr[3] >> 6; + } + /** \return bit map for support CMD58/59, CMD48/49, CMD23, and CMD20 */ + uint8_t cmdSupport() const { + return scr[3] & 0XF; + } + /** \return SD spec version */ + int16_t sdSpecVer() const { + if (sdSpec() > 2) { + return -1; + } else if (sdSpec() < 2) { + return sdSpec() ? 110 : 101; + } else if (!sdSpec3()) { + return 200; + } else if (!sdSpec4() && !sdSpecX()) { + return 300; + } + return 400 + 100 * sdSpecX(); + } +}; +// ============================================================================== +/** + * \class sds_t + * \brief SD Status. + */ +// fields are big endian +struct sds_t { + /** byte 0, bit 7-6 width, bit 5 secured mode, bits 4-0 reserved. */ + uint8_t busWidthSecureMode; + /** byte 1 reserved */ + uint8_t reserved1; + /** byte 2-3 zero for SD rd/wr memory card. */ + uint8_t sdCardType[2]; + /** byte 4-7 size of protected area big endian */ + uint8_t sizeOfProtectedArea[4]; + /** byte 8 speed class. */ + uint8_t speed; + /** byte 9 performance move */ + uint8_t performanceMove; + /** byte 10 AU size code. */ + uint8_t auSize; + /** byte 11-12 erase size big endian */ + uint8_t eraseSize[2]; + /** byte 13 erase timeout and erase offset */ + uint8_t eraseTimeoutOffset; + /** byte 14 */ + uint8_t uhsClassAuSize; + /** byte 15 */ + uint8_t videoSpeedClass; + /** byte 16-17 */ + uint8_t vscAuSize[2]; + /** byte 18-21 */ + uint8_t susAddr[3]; + /** byte 21 */ + uint8_t appPerfClass; + /** byte 22 */ + uint8_t perfEnhance; + /** byte 23 */ + uint8_t discardFule; + /** byte 24 */ + uint8_t reservedManufacturer[40]; + + /** \return appClass. */ + int appClass() { + return appPerfClass; + } + /** \return AU size in KB. or zero for error. */ + uint32_t auSizeKB() { + // 0XF mask and uint16_t array helps compiler optimize size on Uno. + uint8_t val = (auSize >> 4) & 0XF; + static const uint16_t au[] = {0, 16, 32, 64, 128, + 256, 512, 1024, 2048, 4096, + 8192, 12288, 16384, 24576, 32768}; + return val < 0XF ? au[val] : 65536UL; + } + /** \return current bus width or -1 for error. */ + uint8_t busWidth() const { + uint8_t w = busWidthSecureMode >> 6; + return w == 2 ? 4 : w == 0 ? 1 : -1; + } + /** \return true is discard operation is supported else true. */ + bool discard() const { + return discardFule & 2; + } + /** \return eraseSize in AUs. */ + uint16_t eraseSizeAU() const { + return static_cast < uint16_t > (eraseSize[0]) << 8 | + static_cast < uint16_t > (eraseSize[1]); + } + /** \return eraseTimeout seconds. */ + uint8_t eraseTimeout() const { + return eraseTimeoutOffset >> 2; + } + /** \return eraseOffset seconds. */ + uint8_t eraseOffset() const { + return eraseTimeoutOffset & 3; + } + /** \return true if full user logical erase is supported else false. */ + bool file() const { + return discardFule & 1; + } + /** \return true for secure mode else false. */ + bool secureMode() const { + return busWidthSecureMode & 0X20; + } + /** \return speed class or -1 for error. */ + int speedClass() const { + return speed < 4 ? 2 * speed : speed == 4 ? 10 : -1; + } + /** \return UHS Speed Grade. */ + int uhsClass() const { + return uhsClassAuSize >> 4; + } + /** \return Video Speed */ + int videoClass() { + return videoSpeedClass; + } +}; diff --git a/ports/raspberrypi/common-hal/sdioio/sdfat_pio/SdCard/SdCardInterface.h b/ports/raspberrypi/common-hal/sdioio/sdfat_pio/SdCard/SdCardInterface.h new file mode 100644 index 00000000000..5d36ae4d043 --- /dev/null +++ b/ports/raspberrypi/common-hal/sdioio/sdfat_pio/SdCard/SdCardInterface.h @@ -0,0 +1,118 @@ +/** + * Copyright (c) 2011-2025 Bill Greiman, 2026 Tim Cocks for Adafruit Industries + * This file is part of the SdFat library for SD memory cards. + * + * MIT License + * + * 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. + */ +/** + * \file + * \brief Abstract interface for an SD card. + */ +#pragma once +#include "../common/FsBlockDeviceInterface.h" +#include "SdCardInfo.h" +/** + * \class SdCardInterface + * \brief Abstract interface for an SD card. + */ +class SdCardInterface: public FsBlockDeviceInterface { +public: + /** CMD6 Switch mode: Check Function Set Function. + * \param[in] arg CMD6 argument. + * \param[out] status return status data. + * + * \return true for success or false for failure. + */ + virtual bool cardCMD6(uint32_t arg, uint8_t *status) = 0; + /** Erase a range of sectors. + * + * \param[in] firstSector The address of the first sector in the range. + * \param[in] lastSector The address of the last sector in the range. + * + * \return true for success or false for failure. + */ + virtual bool erase(Sector_t firstSector, Sector_t lastSector) = 0; + /** \return error code. */ + virtual uint8_t errorCode() const = 0; + /** \return error data. */ + virtual uint32_t errorData() const = 0; + /** \return false by default */ + virtual bool hasDedicatedSpi() { + return false; + } + /** \return false by default */ + virtual bool isDedicatedSpi() { + return false; + } + /** \return false by default */ + virtual bool isSpi() { + return false; + } + /** Set SPI sharing state + * \param[in] value desired state. + * \return false by default. + */ + virtual bool setDedicatedSpi(bool value) { + (void)value; + return false; + } + /** + * Read a card's CID register. + * + * \param[out] cid pointer to area for returned data. + * + * \return true for success or false for failure. + */ + virtual bool readCID(cid_t *cid) = 0; + /** + * Read a card's CSD register. + * + * \param[out] csd pointer to area for returned data. + * + * \return true for success or false for failure. + */ + virtual bool readCSD(csd_t *csd) = 0; + /** Read OCR register. + * + * \param[out] ocr Value of OCR register. + * \return true for success or false for failure. + */ + virtual bool readOCR(uint32_t *ocr) = 0; + /** Read SCR register. + * + * \param[out] scr Value of SCR register. + * \return true for success or false for failure. + */ + virtual bool readSCR(scr_t *scr) = 0; + /** Return the 64 byte SD Status register. + * \param[out] sds location for 64 status bytes. + * \return true for success or false for failure. + */ + virtual bool readSDS(sds_t *sds) = 0; + /** \return card status. */ + virtual uint32_t status() { + return 0XFFFFFFFF; + } + /** Return the card type: SD V1, SD V2 or SDHC/SDXC + * \return 0 - SD V1, 1 - SD V2, or 3 - SDHC/SDXC. + */ + virtual uint8_t type() const = 0; +}; diff --git a/ports/raspberrypi/common-hal/sdioio/sdfat_pio/common/FsBlockDeviceInterface.h b/ports/raspberrypi/common-hal/sdioio/sdfat_pio/common/FsBlockDeviceInterface.h new file mode 100644 index 00000000000..f5f5b0a8b0c --- /dev/null +++ b/ports/raspberrypi/common-hal/sdioio/sdfat_pio/common/FsBlockDeviceInterface.h @@ -0,0 +1,117 @@ +/** + * Copyright (c) 2011-2025 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * MIT License + * + * 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. + */ +/** + * \file + * \brief FsBlockDeviceInterface include file. + */ +#pragma once +#include +#include +/** + * \class FsBlockDeviceInterface + * \brief FsBlockDeviceInterface class. + */ +class FsBlockDeviceInterface { +public: + virtual ~FsBlockDeviceInterface() { + } + + /** end use of device */ + virtual void end() { + } + /** + * Check for FsBlockDevice busy. + * + * \return true if busy else false. + */ + virtual bool isBusy() = 0; + /** + * Read a sector. + * + * \param[in] sector Logical sector to be read. + * \param[out] dst Pointer to the location that will receive the data. + * \return true for success or false for failure. + */ + virtual bool readSector(Sector_t sector, uint8_t *dst) = 0; + + /** + * Read multiple sectors. + * + * \param[in] sector Logical sector to be read. + * \param[in] ns Number of sectors to be read. + * \param[out] dst Pointer to the location that will receive the data. + * \return true for success or false for failure. + */ + virtual bool readSectors(Sector_t sector, uint8_t *dst, size_t ns) = 0; + + /** \return device size in sectors. */ + virtual Sector_t sectorCount() = 0; + + /** End multi-sector transfer and go to idle state. + * \return true for success or false for failure. + */ + virtual bool syncDevice() = 0; + + /** + * Writes a sector. + * + * \param[in] sector Logical sector to be written. + * \param[in] src Pointer to the location of the data to be written. + * \return true for success or false for failure. + */ + virtual bool writeSector(Sector_t sector, const uint8_t *src) = 0; + + /** + * Write multiple sectors. + * + * \param[in] sector Logical sector to be written. + * \param[in] ns Number of sectors to be written. + * \param[in] src Pointer to the location of the data to be written. + * \return true for success or false for failure. + */ + virtual bool writeSectors(Sector_t sector, const uint8_t *src, size_t ns) = 0; + + // Adafruit SdFat v1 BaseBlockDRiver API for backward-compatible + // maybe removal since v1 is deprecated now + virtual bool syncBlocks() { + return syncDevice(); + } + + virtual bool readBlock(uint32_t block, uint8_t *dst) { + return readSector(block, dst); + } + + virtual bool readBlocks(uint32_t block, uint8_t *dst, size_t nb) { + return readSectors(block, dst, nb); + } + + virtual bool writeBlock(uint32_t block, const uint8_t *src) { + return writeSector(block, src); + } + + virtual bool writeBlocks(uint32_t block, const uint8_t *src, size_t nb) { + return writeSectors(block, src, nb); + } +}; diff --git a/ports/raspberrypi/common-hal/sdioio/sdfat_pio/common/SysCall.h b/ports/raspberrypi/common-hal/sdioio/sdfat_pio/common/SysCall.h new file mode 100644 index 00000000000..e8735ff2fd6 --- /dev/null +++ b/ports/raspberrypi/common-hal/sdioio/sdfat_pio/common/SysCall.h @@ -0,0 +1,56 @@ +/** + * Copyright (c) 2011-2025 Bill Greiman + * This file is part of the SdFat library for SD memory cards. + * + * MIT License + * + * 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. + */ +/** + * \file + * \brief SysCall class + * + * CircuitPython vendored, trimmed copy. The upstream SysCall.h pulls in + * SdFatConfig.h (and through it Arduino.h / avr/io.h) plus PrintBasic.h. The + * PIO SDIO card driver only needs the Sector_t typedef, nullptr handling, and + * the SD_MAX_INIT_RATE_KHZ tuning constant, so we provide just those here and + * leave the Arduino/Print machinery out of the build. + */ +#pragma once +#include +#include + +#if __cplusplus < 201103 +#warning nullptr defined +/** Define nullptr if not C++11 */ +#define nullptr NULL +#endif // __cplusplus < 201103 +// ------------------------------------------------------------------------------ +/** Type for FsBlockDevice sector */ +typedef uint32_t Sector_t; +// ------------------------------------------------------------------------------ +// SdCardInfo.h declares (but, in this vendored build, never defines) two error +// printing helpers that take a print_t*. Forward declare the type so those +// pointer-only declarations parse without dragging in PrintBasic / Arduino. +class print_t; +// ------------------------------------------------------------------------------ +// Normally supplied by SdFatConfig.h. +#ifndef SD_MAX_INIT_RATE_KHZ +#define SD_MAX_INIT_RATE_KHZ 400 +#endif // SD_MAX_INIT_RATE_KHZ diff --git a/ports/raspberrypi/common-hal/sdioio/sdfat_pio/cxx_runtime.cpp b/ports/raspberrypi/common-hal/sdioio/sdfat_pio/cxx_runtime.cpp new file mode 100644 index 00000000000..85a28ed8d95 --- /dev/null +++ b/ports/raspberrypi/common-hal/sdioio/sdfat_pio/cxx_runtime.cpp @@ -0,0 +1,33 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// Minimal freestanding C++ ABI support for the vendored SdFat PIO driver. +// +// CircuitPython links the firmware with gcc and without libstdc++/libsupc++, so +// a few C++ ABI symbols that the driver's class hierarchy makes the compiler +// reference must be provided here: +// * PioSdioCard's vtable contains a deleting destructor slot that names +// `operator delete`, even though we only ever placement-new the object and +// call its destructor explicitly (so it is never actually invoked). +// * The abstract base classes (SdCardInterface / FsBlockDeviceInterface) have +// pure virtuals, so their transient vtables reference `__cxa_pure_virtual`. +// Both are effectively unreachable at run time; they exist only to satisfy the +// linker. + +#include +#include + +extern "C" void __cxa_pure_virtual(void) { + abort(); +} + +void operator delete(void *ptr) noexcept { + free(ptr); +} + +void operator delete(void *ptr, size_t) noexcept { + free(ptr); +} diff --git a/ports/raspberrypi/common-hal/sdioio/sdfat_pio/shim.cpp b/ports/raspberrypi/common-hal/sdioio/sdfat_pio/shim.cpp new file mode 100644 index 00000000000..f5d5ded0cd3 --- /dev/null +++ b/ports/raspberrypi/common-hal/sdioio/sdfat_pio/shim.cpp @@ -0,0 +1,80 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// C-callable shim around the vendored C++ PioSdioCard driver. This is the only +// translation unit that includes the C++ class; everything the common-hal C +// code needs is exposed through the extern "C" entry points in shim.h. + +#include + +#include "hardware/clocks.h" + +#include "SdCard/PioSdio/PioSdioCard.h" +#include "shim.h" + +static_assert(sizeof(PioSdioCard) <= SDIOIO_PIO_CARD_STORAGE_SIZE, + "SDIOIO_PIO_CARD_STORAGE_SIZE is too small for PioSdioCard"); +static_assert(alignof(PioSdioCard) <= alignof(sdioio_pio_card_storage_t), + "sdioio_pio_card_storage_t is not aligned enough for PioSdioCard"); + +extern "C" { + +void sdfat_pio_card_new(void *storage) { + new (storage) PioSdioCard(); +} + +void sdfat_pio_card_free(void *storage) { + reinterpret_cast(storage)->~PioSdioCard(); +} + +bool sdfat_pio_card_begin(void *storage, uint32_t clk_pin, uint32_t cmd_pin, + uint32_t dat0_pin, uint32_t frequency, uint32_t *actual_frequency_out) { + PioSdioCard *card = reinterpret_cast(storage); + + // The PIO driver clocks four PIO cycles per SD clock, so the resulting SD + // clock is clk_sys / (4 * clkDiv). Invert that to turn the requested rate + // into a divisor, clamped to the fastest the divisor allows (clkDiv >= 1). + float sys_hz = (float)clock_get_hz(clk_sys); + float clk_div = sys_hz / (4.0f * (float)frequency); + if (clk_div < 1.0f) { + clk_div = 1.0f; + } + + bool ok = card->begin(PioSdioConfig(clk_pin, cmd_pin, dat0_pin, clk_div)); + + if (actual_frequency_out != nullptr) { + *actual_frequency_out = (uint32_t)(sys_hz / (4.0f * clk_div)); + } + return ok; +} + +uint32_t sdfat_pio_card_sector_count(void *storage) { + return reinterpret_cast(storage)->sectorCount(); +} + +bool sdfat_pio_card_read_sectors(void *storage, uint32_t start_sector, + uint8_t *dst, size_t num_sectors) { + return reinterpret_cast(storage)->readSectors(start_sector, dst, num_sectors); +} + +bool sdfat_pio_card_write_sectors(void *storage, uint32_t start_sector, + const uint8_t *src, size_t num_sectors) { + return reinterpret_cast(storage)->writeSectors(start_sector, src, num_sectors); +} + +bool sdfat_pio_card_sync(void *storage) { + return reinterpret_cast(storage)->syncDevice(); +} + +uint8_t sdfat_pio_card_error_code(void *storage) { + return reinterpret_cast(storage)->errorCode(); +} + +void sdfat_pio_card_end(void *storage) { + reinterpret_cast(storage)->end(); +} + +} // extern "C" diff --git a/ports/raspberrypi/common-hal/sdioio/sdfat_pio/shim.h b/ports/raspberrypi/common-hal/sdioio/sdfat_pio/shim.h new file mode 100644 index 00000000000..170f01335c6 --- /dev/null +++ b/ports/raspberrypi/common-hal/sdioio/sdfat_pio/shim.h @@ -0,0 +1,74 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// C-callable shim around the vendored C++ PioSdioCard driver. All use of the +// C++ class is confined to shim.cpp so the common-hal C sources never include +// any C++ headers. + +#pragma once + +#include +#include +#include + +// Size of the opaque storage the C object struct reserves for an in-place +// PioSdioCard instance. shim.cpp static_asserts that the real class fits. The +// real object is well under this (~320 bytes); the slack is intentional so the +// build does not break if the upstream class grows slightly. +#define SDIOIO_PIO_CARD_STORAGE_SIZE 512 + +// Opaque storage for one PioSdioCard, constructed in place by +// sdfat_pio_card_new(). The class's members are at most pointer/word aligned, so +// a pointer member is enough to align the buffer (and matches what the GC heap +// guarantees); shim.cpp static_asserts that this is sufficient. Kept as a plain +// union so the C struct needs no knowledge of the C++ type. +typedef union { + void *for_alignment; + uint8_t bytes[SDIOIO_PIO_CARD_STORAGE_SIZE]; +} sdioio_pio_card_storage_t; + +#ifdef __cplusplus +extern "C" { +#endif + +// Construct a PioSdioCard in place in the given storage buffer. +void sdfat_pio_card_new(void *storage); + +// Run the destructor for the in-place PioSdioCard. +void sdfat_pio_card_free(void *storage); + +// Initialize the card. dat0_pin is the base of four consecutive data GPIOs. +// frequency is the requested SD clock in Hz; the achieved rate is written to +// actual_frequency_out (in Hz) when it is non-NULL. Returns true on success. +bool sdfat_pio_card_begin(void *storage, uint32_t clk_pin, uint32_t cmd_pin, + uint32_t dat0_pin, uint32_t frequency, uint32_t *actual_frequency_out); + +// Number of 512-byte sectors on the card (0 if unknown). +uint32_t sdfat_pio_card_sector_count(void *storage); + +// Read `num_sectors` 512-byte sectors starting at `start_sector` into `dst`. +// Returns true on success. The driver is synchronous/polling, so this blocks. +bool sdfat_pio_card_read_sectors(void *storage, uint32_t start_sector, + uint8_t *dst, size_t num_sectors); + +// Write `num_sectors` 512-byte sectors from `src` starting at `start_sector`. +// Returns true on success. Blocks like the read path. +bool sdfat_pio_card_write_sectors(void *storage, uint32_t start_sector, + const uint8_t *src, size_t num_sectors); + +// Ends any open multi-block transfer (CMD12) and waits for the card to finish +// programming. Returns false on timeout. +bool sdfat_pio_card_sync(void *storage); + +// Last error code from the driver (see SdCardInfo.h). +uint8_t sdfat_pio_card_error_code(void *storage); + +// Release the card's PIO/state-machine resources. +void sdfat_pio_card_end(void *storage); + +#ifdef __cplusplus +} +#endif diff --git a/ports/raspberrypi/common-hal/socketpool/Socket.c b/ports/raspberrypi/common-hal/socketpool/Socket.c index 086fc4a13f7..d3346ecd1e4 100644 --- a/ports/raspberrypi/common-hal/socketpool/Socket.c +++ b/ports/raspberrypi/common-hal/socketpool/Socket.c @@ -8,6 +8,11 @@ // // SPDX-License-Identifier: MIT +#include "py/mpconfig.h" + +// With CIRCUITPY_AIRLIFT, shared-module/_airlift/socketpool.c is used instead. +#if !CIRCUITPY_AIRLIFT + #include "shared-bindings/socketpool/Socket.h" #include "py/gc.h" @@ -67,8 +72,6 @@ static mp_obj_t socketpool_ip_addr_and_port_to_tuple(const ip_addr_t *addr, int return mp_obj_new_tuple(n, args); } -#define MICROPY_PY_LWIP_SOCK_RAW (1) - #if 0 // print debugging info #define DEBUG_printf DEBUG_printf #else // don't print debugging info @@ -78,6 +81,11 @@ static mp_obj_t socketpool_ip_addr_and_port_to_tuple(const ip_addr_t *addr, int // Timeout between closing a TCP socket and doing a tcp_abort on that // socket, if the connection isn't closed cleanly in that time. #define MICROPY_PY_LWIP_TCP_CLOSE_TIMEOUT_MS (10000) +// lwIP's tcp_poll interval is measured in slow timer ticks. +#define TCP_CLOSE_POLL_TICKS \ + ((MICROPY_PY_LWIP_TCP_CLOSE_TIMEOUT_MS + TCP_SLOW_INTERVAL - 1) / TCP_SLOW_INTERVAL) +// It must fit in lwIP's u8_t pollinterval. 0 would abort on the next tick. +MP_STATIC_ASSERT(TCP_CLOSE_POLL_TICKS > 0 && TCP_CLOSE_POLL_TICKS <= UINT8_MAX); // All socket options should be globally distinct, // because we ignore option levels for efficiency. @@ -89,7 +97,7 @@ static mp_obj_t socketpool_ip_addr_and_port_to_tuple(const ip_addr_t *addr, int // socket API. // Extension to lwIP error codes -// Matches lwIP 2.0.3 +// Matches lwIP 2.2.1 #undef _ERR_BADF #define _ERR_BADF -17 static const int error_lookup_table[] = { @@ -251,7 +259,7 @@ static void _lwip_tcp_err_unaccepted(void *arg, err_t err) { // because it's only ever used by lwIP if tcp_connect is called on the TCP PCB. socketpool_socket_obj_t *socket = (socketpool_socket_obj_t *)pcb->connected; - // Array is not volatile because thiss callback is executed within the lwIP context + // Array is not volatile because this callback is executed within the lwIP context uint8_t alloc = socket->incoming.connection.alloc; struct tcp_pcb **tcp_array = (struct tcp_pcb **)lwip_socket_incoming_array(socket); @@ -473,7 +481,12 @@ static mp_uint_t lwip_tcp_send(socketpool_socket_obj_t *socket, const byte *buf, MICROPY_PY_LWIP_ENTER - u16_t available = tcp_sndbuf(socket->pcb.tcp); + // If the socket is still connecting then don't let data be written to it. + // Otherwise, get the number of available bytes in the output buffer. + u16_t available = 0; + if (socket->state != STATE_CONNECTING) { + available = tcp_sndbuf(socket->pcb.tcp); + } if (available == 0) { // Non-blocking socket @@ -490,7 +503,8 @@ static mp_uint_t lwip_tcp_send(socketpool_socket_obj_t *socket, const byte *buf, // 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) { + while (socket->state == STATE_CONNECTING + || (socket->state >= STATE_CONNECTED && (available = tcp_sndbuf(socket->pcb.tcp)) < 16)) { MICROPY_PY_LWIP_EXIT if (socket->timeout != (unsigned)-1 && mp_hal_ticks_ms() - start > socket->timeout) { *_errno = MP_ETIMEDOUT; @@ -531,9 +545,10 @@ static mp_uint_t lwip_tcp_send(socketpool_socket_obj_t *socket, const byte *buf, MICROPY_PY_LWIP_REENTER } - // 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); + // Use nagle algorithm to determine when to send segment buffer (can be + // disabled with TCP_NODELAY socket option) + if (err == ERR_OK) { + err = tcp_output_nagle(socket->pcb.tcp); } MICROPY_PY_LWIP_EXIT @@ -551,6 +566,12 @@ static mp_uint_t lwip_tcp_receive(socketpool_socket_obj_t *socket, byte *buf, mp // Check for any pending errors STREAM_ERROR_CHECK(socket); + if (socket->state == STATE_LISTENING) { + // original socket in listening state, not the accepted connection. + *_errno = MP_ENOTCONN; + return -1; + } + if (socket->incoming.pbuf == NULL) { // Non-blocking socket @@ -934,7 +955,7 @@ void socketpool_socket_close(socketpool_socket_obj_t *socket) { // Schedule a callback to abort the connection if it's not cleanly closed after // the given timeout. The callback must be set before calling tcp_close since // the latter may free the pcb; if it doesn't then the callback will be active. - tcp_poll(socket->pcb.tcp, _lwip_tcp_close_poll, MICROPY_PY_LWIP_TCP_CLOSE_TIMEOUT_MS / 500); + tcp_poll(socket->pcb.tcp, _lwip_tcp_close_poll, TCP_CLOSE_POLL_TICKS); } if (tcp_close(socket->pcb.tcp) != ERR_OK) { DEBUG_printf("lwip_close: had to call tcp_abort()\n"); @@ -1071,7 +1092,8 @@ bool common_hal_socketpool_socket_listen(socketpool_socket_obj_t *socket, int ba socket->incoming.connection.tcp.item = NULL; } else { socket->incoming.connection.alloc = backlog; - socket->incoming.connection.tcp.array = m_new0(struct tcp_pcb *, backlog); + socket->incoming.connection.tcp.array = m_malloc_without_collect(sizeof(struct tcp_pcb *) * backlog); + memset(socket->incoming.connection.tcp.array, 0, sizeof(struct tcp_pcb *) * backlog); } socket->incoming.connection.iget = 0; socket->incoming.connection.iput = 0; @@ -1212,6 +1234,20 @@ int common_hal_socketpool_socket_setsockopt(socketpool_socket_obj_t *self, int l bool enable = optlen == sizeof(&zero) && memcmp(value, &zero, optlen); switch (level) { + case SOCKETPOOL_IPPROTO_IP: + switch (optname) { + case SOCKETPOOL_IP_MULTICAST_TTL: + if (self->type != SOCKETPOOL_SOCK_DGRAM) { + return -MP_EOPNOTSUPP; + } + if (self->pcb.udp == NULL || optlen < sizeof(uint8_t)) { + return -MP_EINVAL; + } + udp_set_multicast_ttl(self->pcb.udp, *(const uint8_t *)value); + return 0; + } + break; + case SOCKETPOOL_IPPROTO_TCP: switch (optname) { case SOCKETPOOL_TCP_NODELAY: @@ -1252,7 +1288,7 @@ bool common_hal_socketpool_readable(socketpool_socket_obj_t *self) { } if (self->type == SOCKETPOOL_SOCK_STREAM && self->pcb.tcp->state == LISTEN) { - struct tcp_pcb *volatile *incoming_connection = &lwip_socket_incoming_array(self)[self->incoming.connection.iget]; + struct tcp_pcb *incoming_connection = lwip_socket_incoming_array(self)[self->incoming.connection.iget]; result = (incoming_connection != NULL); } @@ -1312,3 +1348,5 @@ void socketpool_socket_reset(socketpool_socket_obj_t *self) { self->pcb.tcp = NULL; self->state = _ERR_BADF; } + +#endif // !CIRCUITPY_AIRLIFT diff --git a/ports/raspberrypi/common-hal/socketpool/Socket.h b/ports/raspberrypi/common-hal/socketpool/Socket.h index d7898777744..7af293c0cca 100644 --- a/ports/raspberrypi/common-hal/socketpool/Socket.h +++ b/ports/raspberrypi/common-hal/socketpool/Socket.h @@ -13,6 +13,11 @@ #include "common-hal/socketpool/SocketPool.h" +#if CIRCUITPY_AIRLIFT +// The sockets live on the ESP32 co-processor (nina-fw). +#include "shared-module/_airlift/socketpool.h" +#else + typedef struct _lwip_socket_obj_t { mp_obj_base_t base; @@ -59,3 +64,5 @@ typedef struct _lwip_socket_obj_t { #define socketpool_socket_poll_resume(x) void socket_user_reset(void); + +#endif diff --git a/ports/raspberrypi/common-hal/socketpool/SocketPool.c b/ports/raspberrypi/common-hal/socketpool/SocketPool.c index 394b9779933..ebc12351632 100644 --- a/ports/raspberrypi/common-hal/socketpool/SocketPool.c +++ b/ports/raspberrypi/common-hal/socketpool/SocketPool.c @@ -4,6 +4,11 @@ // // SPDX-License-Identifier: MIT +#include "py/mpconfig.h" + +// With CIRCUITPY_AIRLIFT, shared-module/_airlift/socketpool.c is used instead. +#if !CIRCUITPY_AIRLIFT + #include "shared-bindings/socketpool/SocketPool.h" #include "common-hal/socketpool/__init__.h" #include "common-hal/socketpool/Socket.h" @@ -15,8 +20,8 @@ #include "lwip/dns.h" #include "lwip/inet.h" -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)) { +void common_hal_socketpool_socketpool_construct(socketpool_socketpool_obj_t *self, mp_obj_t network_interface) { + if (network_interface != MP_OBJ_FROM_PTR(&common_hal_wifi_radio_obj)) { mp_raise_ValueError(MP_ERROR_TEXT("SocketPool can only be used with wifi.radio")); } } @@ -54,3 +59,5 @@ mp_obj_t common_hal_socketpool_getaddrinfo_raise(socketpool_socketpool_obj_t *se tuple->items[4] = MP_OBJ_FROM_PTR(sockaddr); return mp_obj_new_list(1, (mp_obj_t *)&tuple); } + +#endif // !CIRCUITPY_AIRLIFT diff --git a/ports/raspberrypi/common-hal/socketpool/SocketPool.h b/ports/raspberrypi/common-hal/socketpool/SocketPool.h index 864a52b3283..e66255ce499 100644 --- a/ports/raspberrypi/common-hal/socketpool/SocketPool.h +++ b/ports/raspberrypi/common-hal/socketpool/SocketPool.h @@ -8,8 +8,14 @@ #include "py/obj.h" +#if CIRCUITPY_AIRLIFT +#include "shared-module/_airlift/socketpool.h" +#else + #include "lwip/ip_addr.h" typedef struct { mp_obj_base_t base; } socketpool_socketpool_obj_t; + +#endif diff --git a/ports/raspberrypi/common-hal/socketpool/__init__.c b/ports/raspberrypi/common-hal/socketpool/__init__.c index 84a5309ae11..f0ed893dc10 100644 --- a/ports/raspberrypi/common-hal/socketpool/__init__.c +++ b/ports/raspberrypi/common-hal/socketpool/__init__.c @@ -4,6 +4,11 @@ // // SPDX-License-Identifier: MIT +#include "py/mpconfig.h" + +// With CIRCUITPY_AIRLIFT, shared-module/_airlift/socketpool.c is used instead. +#if !CIRCUITPY_AIRLIFT + #include "py/runtime.h" #include "shared/runtime/interrupt_char.h" @@ -79,3 +84,5 @@ void socketpool_resolve_host_raise(const char *host, ip_addr_t *addr) { mp_raise_OSError(-result); } } + +#endif // !CIRCUITPY_AIRLIFT diff --git a/ports/raspberrypi/common-hal/socketpool/__init__.h b/ports/raspberrypi/common-hal/socketpool/__init__.h index d55e720b373..c750c8b9ee7 100644 --- a/ports/raspberrypi/common-hal/socketpool/__init__.h +++ b/ports/raspberrypi/common-hal/socketpool/__init__.h @@ -6,7 +6,9 @@ #pragma once +#if !CIRCUITPY_AIRLIFT #include "lwip/ip_addr.h" mp_obj_t socketpool_ip_addr_to_str(const ip_addr_t *addr); void socketpool_resolve_host_raise(const char *host, ip_addr_t *addr); +#endif diff --git a/ports/raspberrypi/common-hal/usb_host/Port.c b/ports/raspberrypi/common-hal/usb_host/Port.c index 5439b39bf3a..fd2ba173463 100644 --- a/ports/raspberrypi/common-hal/usb_host/Port.c +++ b/ports/raspberrypi/common-hal/usb_host/Port.c @@ -8,15 +8,17 @@ #include "shared-bindings/microcontroller/Pin.h" #include "shared-bindings/microcontroller/Processor.h" #include "shared-bindings/usb_host/Port.h" +#include "supervisor/port_heap.h" #include "supervisor/shared/serial.h" +#include "supervisor/shared/settings.h" #include "supervisor/usb.h" #include "pico/time.h" #include "hardware/structs/mpu.h" -#ifdef PICO_RP2040 +#if PICO_RP2040 #include "RP2040.h" // (cmsis) #endif -#ifdef PICO_RP2350 +#if PICO_RP2350 #include "RP2350.h" // (cmsis) #endif #include "hardware/dma.h" @@ -34,6 +36,66 @@ usb_host_port_obj_t usb_host_instance; volatile bool _core1_ready = false; +#if PIO_USB_HOST_ISOCHRONOUS +// The isochronous ring from settings.toml. Like the port, it is never freed. +static uint8_t *_iso_settings_buffer = NULL; +static uint32_t _iso_settings_size = 0; +// A ring claimed for the length of one stream, which replaces the one above +// until it is released. +static uint8_t *_iso_claimed_buffer = NULL; + +// The ring size the host controller accepts: a power of two in [2048, 65536]. +static uint32_t _iso_ring_size(size_t size) { + uint32_t rounded = 2048; + while (rounded < size && rounded < 65536) { + rounded <<= 1; + } + return rounded; +} + +// Hand the host controller another ring. Core 1 may still be in the frame +// where the endpoint stopped streaming into the old ring, so let it finish +// first. False while an endpoint streams into the ring. +static bool _iso_set_ring(uint8_t *buffer, uint32_t size) { + busy_wait_us(2000); + return pio_usb_host_set_iso_ring(buffer, size); +} +#endif + +// Core1 posts TinyUSB events while core0 may hold the queue FIFO mutex. The +// contended wait path calls best_effort_wfe_or_timeout() and time_us_64(), +// which normally live in flash, but core1 must not touch flash (see the MPU +// setup in core1_main below). These RAM-resident replacements are linked in +// with --wrap on USB host builds only (see the port Makefile). Issue #11116. +// +uint64_t __wrap_time_us_64(void); +bool __wrap_best_effort_wfe_or_timeout(absolute_time_t timeout_timestamp); + +// The same hi/lo/hi re-read loop as the SDK's timer_time_us_64, to defeat +// rollover between the two 32-bit halves. +uint64_t __not_in_flash_func(__wrap_time_us_64)(void) { + uint32_t hi = timer_hw->timerawh; + uint32_t lo; + do { + lo = timer_hw->timerawl; + uint32_t next_hi = timer_hw->timerawh; + if (hi == next_hi) { + break; + } + hi = next_hi; + } while (true); + return ((uint64_t)hi << 32) | lo; +} + +// Mirrors the SDK's own PICO_TIME_DEFAULT_ALARM_POOL_DISABLED fallback +// (a poll of the clock with no __wfe): "best effort" explicitly permits +// returning early, and every SDK caller re-checks in a loop. Polling honors +// the timeout exactly and avoids dragging the alarm pool machinery into RAM. +bool __not_in_flash_func(__wrap_best_effort_wfe_or_timeout)(absolute_time_t timeout_timestamp) { + tight_loop_contents(); + return __wrap_time_us_64() >= to_us_since_boot(timeout_timestamp); +} + static void __not_in_flash_func(core1_main)(void) { // The MPU is reset before this starts. SysTick->LOAD = (uint32_t)((common_hal_mcu_processor_get_frequency() / 1000) - 1UL); @@ -73,41 +135,19 @@ static void __not_in_flash_func(core1_main)(void) { } } -static uint8_t _sm_free_count(uint8_t pio_index) { - PIO pio = pio_get_instance(pio_index); - uint8_t free_count = 0; - for (size_t j = 0; j < NUM_PIO_STATE_MACHINES; j++) { - if (!pio_sm_is_claimed(pio, j)) { - free_count++; - } - } - return free_count; -} - -static bool _has_program_room(uint8_t pio_index, uint8_t program_size) { - PIO pio = pio_get_instance(pio_index); - pio_program_t program_struct = { - .instructions = NULL, - .length = program_size, - .origin = -1 - }; - return pio_can_add_program(pio, &program_struct); -} - // As of 0.6.1, the PIO resource requirement is 1 PIO with 3 state machines & // 32 instructions. Since there are only 32 instructions in a state machine, it should // be impossible to have an allocated state machine but 32 instruction slots available; // go ahead and check for it anyway. // -// Since we check that ALL state machines are available, it's not possible for the GPIO +// Since we require ALL state machines to be available, it's not possible for the GPIO // ranges to mismatch on rp2350b static size_t get_usb_pio(void) { - for (size_t i = 0; i < NUM_PIOS; i++) { - if (_has_program_room(i, 32) && _sm_free_count(i) == NUM_PIO_STATE_MACHINES) { - return i; - } + size_t pio_index = rp2pio_statemachine_find_pio(32, NUM_PIO_STATE_MACHINES); + if (pio_index == NUM_PIOS) { + mp_raise_RuntimeError(MP_ERROR_TEXT("All state machines in use")); } - mp_raise_RuntimeError(MP_ERROR_TEXT("All state machines in use")); + return pio_index; } @@ -146,19 +186,35 @@ usb_host_port_obj_t *common_hal_usb_host_port_construct(const mcu_pin_obj_t *dp, self->base.type = &usb_host_port_type; self->dp = dp; self->dm = dm; - - PIO pio = pio_get_instance(pio_cfg.pio_tx_num); + claim_pin(dp); + claim_pin(dm); // Unclaim everything so that the library can. dma_channel_unclaim(pio_cfg.tx_ch); - // Set all of the state machines to never reset. - rp2pio_statemachine_never_reset(pio, pio_cfg.sm_tx); - rp2pio_statemachine_never_reset(pio, pio_cfg.sm_rx); - rp2pio_statemachine_never_reset(pio, pio_cfg.sm_eop); - - common_hal_never_reset_pin(dp); - common_hal_never_reset_pin(dm); + #if PIO_USB_HOST_ISOCHRONOUS + // Ring storage for isochronous IN endpoints (UVC cameras, UAC audio), + // opt-in via settings.toml. Set before core 1 launches so it never + // observes a half-set ring. + mp_int_t iso_size = 0; + if (settings_get_int("CIRCUITPY_USB_HOST_ISO_BUFFER_SIZE", &iso_size) == SETTINGS_OK + && iso_size > 0) { + uint32_t rounded = _iso_ring_size(iso_size); + // dma_capable=true forces the internal-SRAM heap. Never PSRAM: PSRAM + // is inside the XIP region that core 1's MPU blocks below, and the + // ring is written from core 1. Like the port itself, the buffer is + // never freed; it survives soft reload. + uint8_t *iso_buf = port_malloc(rounded, true); + if (iso_buf != NULL) { + pio_usb_host_set_iso_ring(iso_buf, rounded); + _iso_settings_buffer = iso_buf; + _iso_settings_size = rounded; + } else { + mp_raise_RuntimeError_varg(MP_ERROR_TEXT("Failed to allocate %q buffer"), + MP_QSTR_USB_HOST_ISO_BUFFER); + } + } + #endif // Core 1 will run the SOF interrupt directly. _core1_ready = false; @@ -172,6 +228,45 @@ usb_host_port_obj_t *common_hal_usb_host_port_construct(const mcu_pin_obj_t *dp, return self; } +bool common_hal_usb_host_port_claim_iso_buffer(size_t size) { + #if PIO_USB_HOST_ISOCHRONOUS + // A ring left claimed because it was still streaming may be free by now. + common_hal_usb_host_port_release_iso_buffer(); + if (_iso_claimed_buffer != NULL) { + return false; + } + uint32_t rounded = _iso_ring_size(size); + // Internal SRAM only, for the same reason as the settings.toml ring above. + uint8_t *buffer = port_malloc(rounded, true); + if (buffer == NULL) { + m_malloc_fail(rounded); + } + if (!_iso_set_ring(buffer, rounded)) { + port_free(buffer); + return false; + } + _iso_claimed_buffer = buffer; + return true; + #else + (void)size; + return false; + #endif +} + +void common_hal_usb_host_port_release_iso_buffer(void) { + #if PIO_USB_HOST_ISOCHRONOUS + if (_iso_claimed_buffer == NULL) { + return; + } + // When an endpoint still streams into the ring, core 1 keeps writing it, so + // it can't be freed. It stays claimed and the next claim tries again. + if (_iso_set_ring(_iso_settings_buffer, _iso_settings_size)) { + port_free(_iso_claimed_buffer); + _iso_claimed_buffer = NULL; + } + #endif +} + // Not used, but we must define to put this hook into SRAM void __not_in_flash_func(tuh_event_hook_cb)(uint8_t rhport, uint32_t eventid, bool in_isr) { (void)rhport; diff --git a/ports/raspberrypi/common-hal/usb_host_bulk/InStream.c b/ports/raspberrypi/common-hal/usb_host_bulk/InStream.c new file mode 100644 index 00000000000..6cfcb6ea442 --- /dev/null +++ b/ports/raspberrypi/common-hal/usb_host_bulk/InStream.c @@ -0,0 +1,228 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include + +#include "shared-bindings/usb_host_bulk/InStream.h" + +#include "hardware/sync.h" +#include "py/runtime.h" +#include "shared-bindings/usb/core/__init__.h" +#include "shared-bindings/usb/core/Device.h" +#include "supervisor/port_heap.h" +#include "tusb.h" + +#include "pio_usb_bulk_stream.h" +#include "pio_usb_configuration.h" + +// Store the streams the host is polling, at most one per endpoint, so that if +// a device disappears we can deinit all streams polling it. +static usb_host_bulk_instream_obj_t *_active[PIO_USB_EP_POOL_CNT]; + +static void _forget(usb_host_bulk_instream_obj_t *self) { + for (size_t i = 0; i < MP_ARRAY_SIZE(_active); i++) { + if (_active[i] == self) { + _active[i] = NULL; + } + } +} + +// Detach the ring from the host but keep it, so that bytes captured before +// the stop can still be read. No Python allocation: also used on unplug. +// This waits about a millisecond at most. +static void _stop(usb_host_bulk_instream_obj_t *self) { + while (!pio_usb_host_bulk_stream_stop(self->ring, 1000)) { + } + _forget(self); +} + +static uint32_t _ring_in_waiting(pio_usb_bulk_ring_t *ring) { + uint32_t const read = ring->read_pos; + uint32_t const written = ring->write_pos; + __dmb(); + uint32_t const available = written - read; + return available > ring->capacity ? 0 : available; +} + +static void _free_ring(usb_host_bulk_instream_obj_t *self) { + self->lost_packets = self->ring->stats.overrun_packets; + port_free(self->storage); + port_free(self->ring); + self->ring = NULL; + self->storage = NULL; + self->device = MP_OBJ_NULL; +} + +// Finish deiniting a stream that ended without deinit(), because the +// device stalled the endpoint, was unplugged or was reconfigured: +// move the unread bytes to the VM heap, which the GC cleans up, and +// free the ring. Returns false, leaving the stream as it was, if +// there is no room for them. +static bool _retire(usb_host_bulk_instream_obj_t *self) { + uint32_t remaining = _ring_in_waiting(self->ring); + if (remaining > 0) { + uint8_t *leftover = m_malloc_maybe_without_collect(remaining); + if (leftover == NULL) { + return false; + } + pio_usb_host_bulk_stream_read(self->ring, leftover, remaining); + self->leftover = leftover; + self->leftover_len = remaining; + self->leftover_pos = 0; + } + _free_ring(self); + return true; +} + +void common_hal_usb_host_bulk_instream_construct(usb_host_bulk_instream_obj_t *self, + usb_core_device_obj_t *device, uint8_t endpoint, uint32_t buffer_size) { + size_t slot = MP_ARRAY_SIZE(_active); + for (size_t i = 0; i < MP_ARRAY_SIZE(_active); i++) { + usb_host_bulk_instream_obj_t *other = _active[i]; + if (other != NULL && !other->ring->active) { + // It ended on its own, and finishes deiniting when next used. + _active[i] = other = NULL; + } + if (other == NULL) { + slot = i; + } else if (other->device_address == device->device_address && + other->endpoint == endpoint) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Already running")); + } + } + if (slot == MP_ARRAY_SIZE(_active)) { + mp_raise_RuntimeError_varg(MP_ERROR_TEXT("Too many %q"), MP_QSTR_InStream); + } + tuh_bus_info_t bus_info; + if (!tuh_bus_info_get(device->device_address, &bus_info) || bus_info.rhport < 1 || + bus_info.speed != TUSB_SPEED_FULL) { + mp_raise_usb_core_USBError(MP_ERROR_TEXT("Operation or feature not supported")); + } + if (!common_hal_usb_core_device_open_endpoint(device, endpoint)) { + mp_raise_usb_core_USBError(MP_ERROR_TEXT("Invalid %q"), MP_QSTR_endpoint); + } + // The host core writes both from the frame handler, so they must be in SRAM. + pio_usb_bulk_ring_t *ring = port_malloc(sizeof(*ring), true); + if (ring == NULL) { + mp_raise_msg(&mp_type_MemoryError, MP_ERROR_TEXT("Could not allocate DMA capable buffer")); + } + memset(ring, 0, sizeof(*ring)); + uint8_t *storage = port_malloc(buffer_size, true); + if (storage == NULL) { + port_free(ring); + mp_raise_msg(&mp_type_MemoryError, MP_ERROR_TEXT("Could not allocate DMA capable buffer")); + } + // TinyUSB numbers the PIO root ports from 1. + if (!pio_usb_host_bulk_stream_start(bus_info.rhport - 1, device->device_address, endpoint, + ring, storage, buffer_size)) { + port_free(storage); + port_free(ring); + mp_raise_usb_core_USBError(MP_ERROR_TEXT("Invalid %q"), MP_QSTR_endpoint); + } + self->device = MP_OBJ_FROM_PTR(device); + self->ring = ring; + self->storage = storage; + self->leftover = NULL; + self->leftover_len = 0; + self->leftover_pos = 0; + self->lost_packets = 0; + self->device_address = device->device_address; + self->endpoint = endpoint; + _active[slot] = self; +} + +bool common_hal_usb_host_bulk_instream_deinited(usb_host_bulk_instream_obj_t *self) { + if (self->device != MP_OBJ_NULL && !self->ring->active) { + // Clearing active is the host's last access, so the ring now holds + // every byte it wrote. + __dmb(); + _retire(self); + } + return self->device == MP_OBJ_NULL; +} + +// Also the finaliser +void common_hal_usb_host_bulk_instream_deinit(usb_host_bulk_instream_obj_t *self) { + if (self->device != MP_OBJ_NULL) { + _stop(self); + _free_ring(self); + } + // Drop the bytes left by an ended stream. The GC frees their buffer. + self->leftover = NULL; + self->leftover_len = 0; + self->leftover_pos = 0; +} + +uint32_t common_hal_usb_host_bulk_instream_read(usb_host_bulk_instream_obj_t *self, uint8_t *data, uint32_t len) { + if (self->ring != NULL) { + return pio_usb_host_bulk_stream_read(self->ring, data, len); + } + uint32_t count = MIN(len, self->leftover_len - self->leftover_pos); + if (count > 0) { + memcpy(data, self->leftover + self->leftover_pos, count); + self->leftover_pos += count; + } + if (self->leftover != NULL && self->leftover_pos == self->leftover_len) { + m_del(uint8_t, self->leftover, self->leftover_len); + self->leftover = NULL; + self->leftover_len = 0; + self->leftover_pos = 0; + } + return count; +} + +uint32_t common_hal_usb_host_bulk_instream_get_in_waiting(usb_host_bulk_instream_obj_t *self) { + if (self->ring != NULL) { + return _ring_in_waiting(self->ring); + } + return self->leftover_len - self->leftover_pos; +} + +uint32_t common_hal_usb_host_bulk_instream_get_lost_packets(usb_host_bulk_instream_obj_t *self) { + if (self->ring != NULL) { + return self->ring->stats.overrun_packets; + } + return self->lost_packets; +} + +void common_hal_usb_host_bulk_instream_reset_input_buffer(usb_host_bulk_instream_obj_t *self) { + // read_pos belongs to the consumer, so moving it is safe while capturing. + self->ring->read_pos = self->ring->write_pos; +} + +// Stops every stream from device_address, or every stream opened through +// device if it is not NULL. +static void _stop_matching(uint8_t device_address, usb_core_device_obj_t *device) { + for (size_t i = 0; i < MP_ARRAY_SIZE(_active); i++) { + usb_host_bulk_instream_obj_t *stream = _active[i]; + if (stream == NULL) { + continue; + } + if (device != NULL ? stream->device == MP_OBJ_FROM_PTR(device) : + stream->device_address == device_address) { + _stop(stream); + } + } +} + +void usb_host_bulk_stop_device(uint8_t device_address) { + _stop_matching(device_address, NULL); +} + +bool usb_host_bulk_endpoint_busy(uint8_t device_address, uint8_t endpoint) { + for (size_t i = 0; i < MP_ARRAY_SIZE(_active); i++) { + usb_host_bulk_instream_obj_t *stream = _active[i]; + if (stream != NULL && stream->device_address == device_address && + stream->endpoint == endpoint && stream->ring->active) { + return true; + } + } + return false; +} + +void usb_host_bulk_device_deinit(usb_core_device_obj_t *device) { + _stop_matching(0, device); +} diff --git a/ports/raspberrypi/common-hal/usb_host_bulk/InStream.h b/ports/raspberrypi/common-hal/usb_host_bulk/InStream.h new file mode 100644 index 00000000000..632298842bf --- /dev/null +++ b/ports/raspberrypi/common-hal/usb_host_bulk/InStream.h @@ -0,0 +1,26 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include + +#include "py/obj.h" + +#include "pio_usb_bulk_stream.h" + +typedef struct { + mp_obj_base_t base; + mp_obj_t device; // keeps the usb.core.Device alive; NULL once deinited + pio_usb_bulk_ring_t *ring; // port heap; NULL once freed + uint8_t *storage; + uint8_t *leftover; // VM heap: bytes unread when the host ended the stream + uint32_t leftover_len; + uint32_t leftover_pos; + uint32_t lost_packets; // latched when the ring is freed + uint8_t device_address; // copies, so deinit never touches `device` + uint8_t endpoint; +} usb_host_bulk_instream_obj_t; diff --git a/ports/raspberrypi/common-hal/usb_host_bulk/__init__.c b/ports/raspberrypi/common-hal/usb_host_bulk/__init__.c new file mode 100644 index 00000000000..81be9d0b79d --- /dev/null +++ b/ports/raspberrypi/common-hal/usb_host_bulk/__init__.c @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// Nothing diff --git a/ports/raspberrypi/common-hal/watchdog/WatchDogTimer.c b/ports/raspberrypi/common-hal/watchdog/WatchDogTimer.c index bd8d0b2501b..aa6871457e4 100644 --- a/ports/raspberrypi/common-hal/watchdog/WatchDogTimer.c +++ b/ports/raspberrypi/common-hal/watchdog/WatchDogTimer.c @@ -17,7 +17,7 @@ void common_hal_watchdog_feed(watchdog_watchdogtimer_obj_t *self) { watchdog_update(); } -void common_hal_watchdog_deinit(watchdog_watchdogtimer_obj_t *self) { +void common_hal_watchdog_reset(watchdog_watchdogtimer_obj_t *self) { if (self->mode == WATCHDOGMODE_NONE) { return; } @@ -50,7 +50,7 @@ void common_hal_watchdog_set_mode(watchdog_watchdogtimer_obj_t *self, watchdog_w switch (new_mode) { case WATCHDOGMODE_NONE: - common_hal_watchdog_deinit(self); + common_hal_watchdog_reset(self); break; case WATCHDOGMODE_RAISE: mp_raise_NotImplementedError(NULL); diff --git a/ports/raspberrypi/common-hal/wifi/Monitor.c b/ports/raspberrypi/common-hal/wifi/Monitor.c index 8469c60ad56..58c49ab7916 100644 --- a/ports/raspberrypi/common-hal/wifi/Monitor.c +++ b/ports/raspberrypi/common-hal/wifi/Monitor.c @@ -23,7 +23,7 @@ void common_hal_wifi_monitor_construct(wifi_monitor_obj_t *self, uint8_t channel mp_raise_NotImplementedError(MP_ERROR_TEXT("wifi.Monitor not available")); } -bool common_hal_wifi_monitor_deinited(void) { +bool common_hal_wifi_monitor_deinited(wifi_monitor_obj_t *self) { return true; } diff --git a/ports/raspberrypi/common-hal/wifi/Network.c b/ports/raspberrypi/common-hal/wifi/Network.c index 1cd3effbd0f..0e94cb82fbb 100644 --- a/ports/raspberrypi/common-hal/wifi/Network.c +++ b/ports/raspberrypi/common-hal/wifi/Network.c @@ -6,6 +6,8 @@ #include +#include "py/objlist.h" + #include "shared-bindings/wifi/Network.h" #include "shared-bindings/wifi/AuthMode.h" @@ -29,26 +31,31 @@ 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) { - return (mp_obj_t)MP_QSTR_; + return MP_OBJ_NEW_QSTR(MP_QSTR_); } mp_obj_t common_hal_wifi_network_get_authmode(wifi_network_obj_t *self) { + uint32_t auth = self->record.auth_mode; uint32_t authmode_mask = 0; - if (self->record.auth_mode == 0) { + if (auth == 0) { authmode_mask = AUTHMODE_OPEN; } - if (self->record.auth_mode & 1) { - authmode_mask |= AUTHMODE_PSK; - } - ; - if (self->record.auth_mode & 2) { + if (auth & CYW43_AUTH_FLAG_WPA_SECURITY) { authmode_mask |= AUTHMODE_WPA; } - ; - if (self->record.auth_mode & 4) { + if (auth & CYW43_AUTH_FLAG_WPA2_SECURITY) { authmode_mask |= AUTHMODE_WPA2; } - ; + if (auth & CYW43_AUTH_FLAG_WPA3_SECURITY) { + authmode_mask |= AUTHMODE_WPA3; + } + if (auth & CYW43_AUTH_FLAG_ENTERPRISE_ENABLED) { + authmode_mask |= AUTHMODE_ENTERPRISE; + } else if (authmode_mask & (AUTHMODE_WPA | AUTHMODE_WPA2 | AUTHMODE_WPA3)) { + authmode_mask |= AUTHMODE_PSK; + } else if (auth & CYW43_AUTH_FLAG_WEP_ENABLED) { + authmode_mask |= AUTHMODE_WEP; + } mp_obj_t authmode_list = mp_obj_new_list(0, NULL); if (authmode_mask != 0) { for (uint32_t i = 0; i < 32; i++) { diff --git a/ports/raspberrypi/common-hal/wifi/Radio.c b/ports/raspberrypi/common-hal/wifi/Radio.c index b34a7670b83..0cf2e4743e3 100644 --- a/ports/raspberrypi/common-hal/wifi/Radio.c +++ b/ports/raspberrypi/common-hal/wifi/Radio.c @@ -5,7 +5,9 @@ // SPDX-License-Identifier: MIT #include "supervisor/port.h" +#include "shared-bindings/wifi/PowerManagement.h" #include "shared-bindings/wifi/Radio.h" +#include "shared-bindings/wifi/__init__.h" #include "shared-bindings/wifi/Network.h" #include @@ -47,7 +49,7 @@ static inline void nw_put_le32(uint8_t *buf, uint32_t x) { buf[3] = x >> 24; } -NORETURN static void ro_attribute(qstr attr) { +MP_NORETURN static void ro_attribute(qstr attr) { mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q is read-only for this board"), attr); } @@ -65,6 +67,11 @@ void common_hal_wifi_radio_set_enabled(wifi_radio_obj_t *self, bool enabled) { } +mp_obj_t common_hal_wifi_radio_get_version(wifi_radio_obj_t *self) { + // The CYW43 firmware is loaded by CircuitPython, so it doesn't vary independently. + return mp_const_none; +} + mp_obj_t common_hal_wifi_radio_get_hostname(wifi_radio_obj_t *self) { if (!NETIF_STA->hostname) { return mp_const_none; @@ -79,6 +86,10 @@ void common_hal_wifi_radio_set_hostname(wifi_radio_obj_t *self, const char *host netif_set_hostname(NETIF_AP, self->hostname); } +const char *wifi_get_hostname_raw(void) { + return NETIF_STA->hostname == NULL ? "" : NETIF_STA->hostname; +} + void wifi_radio_get_mac_address(wifi_radio_obj_t *self, uint8_t *mac) { memcpy(mac, cyw43_state.mac, MAC_ADDRESS_LENGTH); } @@ -107,6 +118,41 @@ void common_hal_wifi_radio_set_tx_power(wifi_radio_obj_t *self, const mp_float_t cyw43_ioctl(&cyw43_state, CYW43_IOCTL_SET_VAR, 9 + 4, buf, CYW43_ITF_AP); } +wifi_power_management_t common_hal_wifi_radio_get_power_management(wifi_radio_obj_t *self) { + uint32_t pm_value = cyw43_get_power_management_value(); + + switch (pm_value) { + case CONST_CYW43_PERFORMANCE_PM: + return POWER_MANAGEMENT_MIN; + case CONST_CYW43_AGGRESSIVE_PM: + return POWER_MANAGEMENT_MAX; + case CONST_CYW43_NONE_PM: + return POWER_MANAGEMENT_NONE; + default: + return POWER_MANAGEMENT_UNKNOWN; + } +} + + +void common_hal_wifi_radio_set_power_management(wifi_radio_obj_t *self, wifi_power_management_t power_management) { + uint32_t pm_setting = CONST_CYW43_DEFAULT_PM; + switch (power_management) { + case POWER_MANAGEMENT_MIN: + pm_setting = CONST_CYW43_PERFORMANCE_PM; + break; + case POWER_MANAGEMENT_MAX: + pm_setting = CONST_CYW43_AGGRESSIVE_PM; + break; + case POWER_MANAGEMENT_NONE: + pm_setting = CONST_CYW43_NONE_PM; + break; + default: + // Should not get here. + break; + } + cyw43_set_power_management_value(pm_setting); +} + mp_obj_t common_hal_wifi_radio_get_mac_address_ap(wifi_radio_obj_t *self) { return common_hal_wifi_radio_get_mac_address(self); } @@ -121,7 +167,7 @@ mp_obj_t common_hal_wifi_radio_start_scanning_networks(wifi_radio_obj_t *self, u mp_raise_RuntimeError(MP_ERROR_TEXT("Already scanning for wifi networks")); } if (!common_hal_wifi_radio_get_enabled(self)) { - mp_raise_RuntimeError(MP_ERROR_TEXT("Wifi is not enabled")); + mp_raise_RuntimeError(MP_ERROR_TEXT("WiFi is not enabled")); } wifi_scannednetworks_obj_t *scan = mp_obj_malloc(wifi_scannednetworks_obj_t, &wifi_scannednetworks_type); mp_obj_t args[] = { mp_const_empty_tuple, MP_OBJ_NEW_SMALL_INT(16) }; @@ -152,14 +198,23 @@ void common_hal_wifi_radio_stop_station(wifi_radio_obj_t *self) { break; } } + // Drop the DHCP address so the next connect() waits for a lease from the new network. + MICROPY_PY_LWIP_ENTER + if (dhcp_supplied_address(NETIF_STA)) { + netif_set_ipaddr(NETIF_STA, IP4_ADDR_ANY4); + } + MICROPY_PY_LWIP_EXIT bindings_cyw43_wifi_enforce_pm(); } void common_hal_wifi_radio_start_ap(wifi_radio_obj_t *self, uint8_t *ssid, size_t ssid_len, uint8_t *password, size_t password_len, uint8_t channel, uint32_t authmode, uint8_t max_connections) { if (!common_hal_wifi_radio_get_enabled(self)) { - mp_raise_RuntimeError(MP_ERROR_TEXT("Wifi is not enabled")); + mp_raise_RuntimeError(MP_ERROR_TEXT("WiFi is not enabled")); } + // The CYW43 is 2.4 GHz only. + mp_arg_validate_int_max(channel, 13, MP_QSTR_channel); + /* TODO: If the AP is stopped once it cannot be restarted. * This means that if if the user does: * @@ -207,7 +262,7 @@ bool common_hal_wifi_radio_get_ap_active(wifi_radio_obj_t *self) { void common_hal_wifi_radio_stop_ap(wifi_radio_obj_t *self) { if (!common_hal_wifi_radio_get_enabled(self)) { - mp_raise_RuntimeError(MP_ERROR_TEXT("wifi is not enabled")); + mp_raise_RuntimeError(MP_ERROR_TEXT("WiFi is not enabled")); } cyw43_arch_disable_ap_mode(); @@ -283,9 +338,44 @@ static bool connection_unchanged(wifi_radio_obj_t *self, const uint8_t *ssid, si return true; } +// Static, not on the stack: results can arrive after scan_for_auth() gives up. +static uint32_t scan_auth; +static uint8_t scan_ssid[32]; +static size_t scan_ssid_len; + +static int scan_for_auth_cb(void *env, const cyw43_ev_scan_result_t *result) { + // Only count results for the SSID being joined. + if (result->ssid_len == scan_ssid_len && memcmp(result->ssid, scan_ssid, scan_ssid_len) == 0) { + scan_auth |= result->auth_mode; + } + return 0; +} + +// Scan for one SSID. Returns its scan result auth flags, or 0 if not seen. +static uint32_t scan_for_auth(wifi_radio_obj_t *self, const uint8_t *ssid, size_t ssid_len, uint64_t deadline) { + // A user scan owns the driver's scan callback. + if (self->current_scan != NULL) { + return 0; + } + cyw43_wifi_scan_options_t opts = {0}; + opts.ssid_len = ssid_len; + memcpy(opts.ssid, ssid, ssid_len); + memcpy(scan_ssid, ssid, ssid_len); + scan_ssid_len = ssid_len; + scan_auth = 0; + if (cyw43_wifi_scan(&cyw43_state, &opts, NULL, scan_for_auth_cb) != 0) { + return 0; + } + while (cyw43_wifi_scan_active(&cyw43_state) && port_get_raw_ticks(NULL) < deadline && + !mp_hal_is_interrupted()) { + RUN_BACKGROUND_TASKS; + } + return scan_auth; +} + 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(MP_ERROR_TEXT("Wifi is not enabled")); + mp_raise_RuntimeError(MP_ERROR_TEXT("WiFi is not enabled")); } if (ssid_len > 32) { @@ -303,10 +393,20 @@ wifi_radio_error_t common_hal_wifi_radio_connect(wifi_radio_obj_t *self, uint8_t // disconnect common_hal_wifi_radio_stop_station(self); - // connect - int auth_mode = password_len ? CYW43_AUTH_WPA2_AES_PSK : CYW43_AUTH_OPEN; + // Joining with WPA3 SAE fails on a WPA2-only network, so scan for the + // network first and use WPA3 only if it advertises it. + uint32_t auth_mode = CYW43_AUTH_OPEN; + if (password_len) { + uint32_t ap_auth = scan_for_auth(self, ssid, ssid_len, deadline); + auth_mode = (ap_auth & CYW43_AUTH_FLAG_WPA3_SECURITY) ? + CYW43_AUTH_WPA3_SAE_AES_PSK : CYW43_AUTH_WPA2_AES_PSK; + } + + // connect. Record the network now: the join carries on after a timeout. + memcpy(self->connected_ssid, ssid, ssid_len); + self->connected_ssid_len = ssid_len; + self->connected_auth_mode = auth_mode; cyw43_arch_wifi_connect_async((const char *)ssid, (const char *)password, auth_mode); - // TODO: Implement authmode check like in espressif while (port_get_raw_ticks(NULL) < deadline) { RUN_BACKGROUND_TASKS; @@ -318,8 +418,6 @@ wifi_radio_error_t common_hal_wifi_radio_connect(wifi_radio_obj_t *self, uint8_t switch (result) { case CYW43_LINK_UP: - memcpy(self->connected_ssid, ssid, ssid_len); - self->connected_ssid_len = ssid_len; bindings_cyw43_wifi_enforce_pm(); return WIFI_RADIO_ERROR_NONE; case CYW43_LINK_FAIL: @@ -340,7 +438,33 @@ bool common_hal_wifi_radio_get_connected(wifi_radio_obj_t *self) { } mp_obj_t common_hal_wifi_radio_get_ap_info(wifi_radio_obj_t *self) { - mp_raise_NotImplementedError(NULL); + if (cyw43_tcpip_link_status(&cyw43_state, CYW43_ITF_STA) != CYW43_LINK_UP) { + return mp_const_none; + } + + cyw43_ev_scan_result_t record = {0}; + memcpy(record.ssid, self->connected_ssid, self->connected_ssid_len); + record.ssid_len = self->connected_ssid_len; + + // channel_info_t: hardware channel, target channel, scan channel + uint32_t channel_info[3]; + if (cyw43_ioctl(&cyw43_state, CYW43_IOCTL_GET_CHANNEL, sizeof(channel_info), (uint8_t *)channel_info, CYW43_ITF_STA) == 0) { + record.channel = channel_info[0]; + } + + int32_t rssi; + if (cyw43_wifi_get_rssi(&cyw43_state, &rssi) == 0) { + record.rssi = rssi; + } + + cyw43_wifi_get_bssid(&cyw43_state, record.bssid); + + // CYW43_AUTH_* values use the same flags as a scan result's auth_mode. + record.auth_mode = self->connected_auth_mode; + + wifi_network_obj_t *ap_info = mp_obj_malloc(wifi_network_obj_t, &wifi_network_type); + ap_info->record = record; + return MP_OBJ_FROM_PTR(ap_info); } mp_obj_t common_hal_wifi_radio_get_ipv4_gateway(wifi_radio_obj_t *self) { @@ -504,10 +628,10 @@ mp_int_t common_hal_wifi_radio_ping(wifi_radio_obj_t *self, mp_obj_t ip_address, } raw_recv(ping_pcb, ping_recv, NULL); raw_bind(ping_pcb, IP_ADDR_ANY); - MICROPY_PY_LWIP_EXIT - - ping_received = false; + ping_received = false; ping_send(ping_pcb, &ping_addr); + MICROPY_PY_LWIP_EXIT; + size_t timeout_ms = (size_t)MICROPY_FLOAT_C_FUN(ceil)(timeout * 1000); uint64_t start = port_get_raw_ticks(NULL); uint64_t deadline = start + timeout_ms; diff --git a/ports/raspberrypi/common-hal/wifi/Radio.h b/ports/raspberrypi/common-hal/wifi/Radio.h index 53b6cd8f92f..1b63c5a68af 100644 --- a/ports/raspberrypi/common-hal/wifi/Radio.h +++ b/ports/raspberrypi/common-hal/wifi/Radio.h @@ -17,6 +17,7 @@ typedef struct { wifi_scannednetworks_obj_t *current_scan; uint8_t connected_ssid[32]; uint8_t connected_ssid_len; + uint32_t connected_auth_mode; // CYW43_AUTH_* passed to the last join bool enabled; } wifi_radio_obj_t; diff --git a/ports/raspberrypi/common-hal/wifi/__init__.c b/ports/raspberrypi/common-hal/wifi/__init__.c index 5fbe3fe58d1..9c475886035 100644 --- a/ports/raspberrypi/common-hal/wifi/__init__.c +++ b/ports/raspberrypi/common-hal/wifi/__init__.c @@ -11,10 +11,18 @@ #include "shared-bindings/wifi/Monitor.h" #include "shared-bindings/wifi/Radio.h" +#include + #include "py/mperrno.h" #include "py/mpstate.h" #include "py/runtime.h" +#include "lib/cyw43-driver/src/cyw43_config.h" + +#if CIRCUITPY_SETTINGS_TOML +#include "supervisor/shared/settings.h" +#endif + wifi_radio_obj_t common_hal_wifi_radio_obj; #include "supervisor/port.h" @@ -45,10 +53,29 @@ void common_hal_wifi_init(bool user_initiated) { // set station mode to avoid the default SoftAP common_hal_wifi_radio_start_station(self); + + #if CIRCUITPY_SETTINGS_TOML + // Must be set after station starts. + char hostname[sizeof(self->hostname)]; + if (settings_get_str("CIRCUITPY_WIFI_HOSTNAME", hostname, sizeof(hostname)) == SETTINGS_OK) { + common_hal_wifi_radio_set_hostname(self, hostname); + } + #endif + // start wifi common_hal_wifi_radio_set_enabled(self, true); } +bool wifi_is_initialized(void) { + return wifi_inited; +} + +void wifi_get_default_hostname(char *buf, size_t buf_size) { + // When the station interface starts, the driver for the CYW43 Wi-Fi chip + // gives it the name CYW43_HOST_NAME. The Pico SDK sets that to "PicoW". + strlcpy(buf, CYW43_HOST_NAME, buf_size); +} + void wifi_user_reset(void) { if (wifi_user_initiated) { wifi_reset(); diff --git a/ports/raspberrypi/common-hal/wifi/__init__.h b/ports/raspberrypi/common-hal/wifi/__init__.h index 73988e84379..e5de86a8654 100644 --- a/ports/raspberrypi/common-hal/wifi/__init__.h +++ b/ports/raspberrypi/common-hal/wifi/__init__.h @@ -11,7 +11,8 @@ #include "lwip/ip_addr.h" void wifi_reset(void); -NORETURN void raise_cyw_error(int err); + +MP_NORETURN void raise_cyw_error(int err); #define CHECK_CYW_RESULT(x) do { int res = (x); if (res != 0) raise_cyw_error(res); } while (0) void ipaddress_ipaddress_to_lwip(mp_obj_t ip_address, ip_addr_t *lwip_ip_address); diff --git a/ports/raspberrypi/common-hal/wiznet/PIO_SPI.c b/ports/raspberrypi/common-hal/wiznet/PIO_SPI.c new file mode 100755 index 00000000000..30fe8c5d25c --- /dev/null +++ b/ports/raspberrypi/common-hal/wiznet/PIO_SPI.c @@ -0,0 +1,123 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "bindings/wiznet/PIO_SPI.h" + +#include "shared/runtime/interrupt_char.h" +#include "py/mperrno.h" +#include "py/runtime.h" + +#include "supervisor/board.h" +#include "common-hal/microcontroller/Pin.h" +#include "shared-bindings/microcontroller/Pin.h" + +#include "hardware/dma.h" +#include "hardware/gpio.h" +#include "hardware/pio.h" +#include "hardware/clocks.h" + +#include "wizchip_pio_spi.h" + +#define NO_INSTANCE 0xff + +#ifndef PIO_SPI_PREFERRED_PIO +#define PIO_SPI_PREFERRED_PIO 1 +#endif + +// All wiznet spi operations must start with writing a 3 byte header + +wiznet_pio_spi_config_t wiznet_pio_spi_config; +wiznet_pio_spi_handle_t wiznet_pio_spi_handle = NULL; + +void common_hal_wiznet_pio_spi_construct(wiznet_pio_spi_obj_t *self, + const mcu_pin_obj_t *clock, const mcu_pin_obj_t *mosi, + const mcu_pin_obj_t *miso, bool half_duplex) { + + if (half_duplex) { + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_half_duplex); + } + + wiznet_pio_spi_config.data_in_pin = miso->number; + wiznet_pio_spi_config.data_out_pin = mosi->number; + wiznet_pio_spi_config.clock_pin = clock->number; + + if (wiznet_pio_spi_handle != NULL) { + wiznet_pio_spi_close(wiznet_pio_spi_handle); + } + + wiznet_pio_spi_handle = wiznet_pio_spi_open(&wiznet_pio_spi_config); + (*wiznet_pio_spi_handle)->set_active(wiznet_pio_spi_handle); + +} + +bool common_hal_wiznet_pio_spi_deinited(wiznet_pio_spi_obj_t *self) { + return wiznet_pio_spi_config.clock_pin == 0; +} + +void common_hal_wiznet_pio_spi_deinit(wiznet_pio_spi_obj_t *self) { + if (common_hal_wiznet_pio_spi_deinited(self)) { + return; + } + + common_hal_reset_pin(self->clock); + common_hal_reset_pin(self->MOSI); + common_hal_reset_pin(self->MISO); + + wiznet_pio_spi_config.clock_pin = 0; +} + +bool common_hal_wiznet_pio_spi_configure(wiznet_pio_spi_obj_t *self, + uint32_t baudrate, uint8_t polarity, uint8_t phase, uint8_t bits) { + + uint32_t clock = clock_get_hz(clk_sys); + uint32_t clock_div = clock / baudrate; + + if (clock_div > clock / 4) { + clock_div = clock / 4; + } + + wiznet_pio_spi_config.clock_div_major = clock_div; + wiznet_pio_spi_config.clock_div_minor = 0; + + return true; +} + +bool common_hal_wiznet_pio_spi_try_lock(wiznet_pio_spi_obj_t *self) { + if (common_hal_wiznet_pio_spi_deinited(self)) { + return false; + } + + bool grabbed_lock = false; + if (!self->has_lock) { + grabbed_lock = true; + self->has_lock = true; + } + return grabbed_lock; +} + +bool common_hal_wiznet_pio_spi_has_lock(wiznet_pio_spi_obj_t *self) { + return self->has_lock; +} + +void common_hal_wiznet_pio_spi_unlock(wiznet_pio_spi_obj_t *self) { + self->has_lock = false; +} + +bool common_hal_wiznet_pio_spi_write(wiznet_pio_spi_obj_t *self, + const uint8_t *data, size_t len) { + wiznet_pio_spi_write_buffer(data, len); + return true; +} + +bool common_hal_wiznet_pio_spi_read(wiznet_pio_spi_obj_t *self, + uint8_t *data, size_t len, uint8_t write_value) { + wiznet_pio_spi_read_buffer(data, len); + return true; +} + +bool common_hal_wiznet_pio_spi_transfer(wiznet_pio_spi_obj_t *self, const uint8_t *data_out, uint8_t *data_in, size_t len) { + return wiznet_pio_spi_transfer(data_out, len, data_in, len); +} diff --git a/ports/raspberrypi/common-hal/wiznet/PIO_SPI.h b/ports/raspberrypi/common-hal/wiznet/PIO_SPI.h new file mode 100755 index 00000000000..6fcfb452cce --- /dev/null +++ b/ports/raspberrypi/common-hal/wiznet/PIO_SPI.h @@ -0,0 +1,25 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "common-hal/microcontroller/Pin.h" + +#include "py/obj.h" + +#include "hardware/spi.h" + +#define SPI_HEADER_LEN 3 + +typedef struct { + mp_obj_base_t base; + bool has_lock; + const mcu_pin_obj_t *clock; + const mcu_pin_obj_t *MOSI; + const mcu_pin_obj_t *MISO; +} wiznet_pio_spi_obj_t; + +void reset_spi(void); diff --git a/ports/raspberrypi/common-hal/wiznet/__init__.c b/ports/raspberrypi/common-hal/wiznet/__init__.c new file mode 100755 index 00000000000..b3d5d23882d --- /dev/null +++ b/ports/raspberrypi/common-hal/wiznet/__init__.c @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +// No wiznet module functions. diff --git a/ports/raspberrypi/common-hal/wiznet/wizchip_pio_spi.c b/ports/raspberrypi/common-hal/wiznet/wizchip_pio_spi.c new file mode 100755 index 00000000000..eb041527209 --- /dev/null +++ b/ports/raspberrypi/common-hal/wiznet/wizchip_pio_spi.c @@ -0,0 +1,389 @@ +/* + * Copyright (c) 2023 Raspberry Pi (Trading) Ltd. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#include +#include + +#include "pico/stdlib.h" +#include "pico/error.h" + +#include "hardware/dma.h" +#include "hardware/clocks.h" + +#include "wizchip_pio_spi.h" +#include "wizchip_pio_spi.pio.h" + +#ifndef PIO_SPI_PREFERRED_PIO +#define PIO_SPI_PREFERRED_PIO 1 +#endif + +#define PADS_DRIVE_STRENGTH PADS_BANK0_GPIO0_DRIVE_VALUE_12MA +#define IRQ_SAMPLE_DELAY_NS 100 + +#define WIZNET_PIO_SPI_PROGRAM_NAME wiznet_pio_spi_write_read +#define WIZNET_PIO_SPI_PROGRAM_FUNC __CONCAT(WIZNET_PIO_SPI_PROGRAM_NAME, _program) +#define WIZNET_PIO_SPI_PROGRAM_GET_DEFAULT_CONFIG_FUNC __CONCAT(WIZNET_PIO_SPI_PROGRAM_NAME, _program_get_default_config) +#define WIZNET_PIO_SPI_OFFSET_WRITE_BITS __CONCAT(WIZNET_PIO_SPI_PROGRAM_NAME, _offset_write_bits) +#define WIZNET_PIO_SPI_OFFSET_WRITE_END __CONCAT(WIZNET_PIO_SPI_PROGRAM_NAME, _offset_write_end) +#define WIZNET_PIO_SPI_OFFSET_READ_END __CONCAT(WIZNET_PIO_SPI_PROGRAM_NAME, _offset_read_end) + +// All wiznet spi operations must start with writing a 3 byte header +#define WIZNET_PIO_SPI_HEADER_LEN 3 + +#ifndef WIZNET_PICO_PIO_SPI_INSTANCE_COUNT +#define WIZNET_PICO_PIO_SPI_INSTANCE_COUNT 1 +#endif + +typedef struct wiznet_pio_spi_state { + wiznet_pio_spi_funcs_t *funcs; + const wiznet_pio_spi_config_t *spi_config; + pio_hw_t *pio; + uint8_t pio_func_sel; + int8_t pio_offset; + int8_t pio_sm; + int8_t dma_out; + int8_t dma_in; + uint8_t spi_header[WIZNET_PIO_SPI_HEADER_LEN]; + uint8_t spi_header_count; +} wiznet_pio_spi_state_t; +static wiznet_pio_spi_state_t wiznet_pio_spi_state[WIZNET_PICO_PIO_SPI_INSTANCE_COUNT]; +static wiznet_pio_spi_state_t *active_state; + +static wiznet_pio_spi_funcs_t *get_wiznet_pio_spi_impl(void); + +// Initialise our gpios +static void wiznet_pio_spi_gpio_setup(wiznet_pio_spi_state_t *state) { + + // Setup MOSI, MISO and IRQ + gpio_init(state->spi_config->data_out_pin); + gpio_set_dir(state->spi_config->data_out_pin, GPIO_OUT); + gpio_put(state->spi_config->data_out_pin, false); + + gpio_init(state->spi_config->data_in_pin); + gpio_set_dir(state->spi_config->data_in_pin, GPIO_IN); + + // Setup CS + gpio_init(state->spi_config->cs_pin); + gpio_set_dir(state->spi_config->cs_pin, GPIO_OUT); + gpio_put(state->spi_config->cs_pin, true); + + // Setup IRQ + gpio_init(state->spi_config->irq_pin); + gpio_set_dir(state->spi_config->irq_pin, GPIO_IN); + gpio_set_pulls(state->spi_config->irq_pin, false, false); +} + +wiznet_pio_spi_handle_t wiznet_pio_spi_open(const wiznet_pio_spi_config_t *wiznet_pio_spi_config) { + wiznet_pio_spi_state_t *state; + for (size_t i = 0; i < count_of(wiznet_pio_spi_state); i++) { + if (!wiznet_pio_spi_state[i].funcs) { + state = &wiznet_pio_spi_state[i]; + break; + } + } + assert(state); + // if (!state) return NULL; + state->spi_config = wiznet_pio_spi_config; + state->funcs = get_wiznet_pio_spi_impl(); + + wiznet_pio_spi_gpio_setup(state); + + pio_hw_t *pios[2] = {pio0, pio1}; + uint pio_index = PIO_SPI_PREFERRED_PIO; + + if (!pio_can_add_program(pios[pio_index], &WIZNET_PIO_SPI_PROGRAM_FUNC)) { + pio_index ^= 1; + if (!pio_can_add_program(pios[pio_index], &WIZNET_PIO_SPI_PROGRAM_FUNC)) { + return NULL; + } + } + + state->pio = pios[pio_index]; + state->dma_in = -1; + state->dma_out = -1; + + static_assert(GPIO_FUNC_PIO1 == GPIO_FUNC_PIO0 + 1, ""); + state->pio_func_sel = GPIO_FUNC_PIO0 + pio_index; + state->pio_sm = (int8_t)pio_claim_unused_sm(state->pio, false); + if (state->pio_sm < 0) { + wiznet_pio_spi_close(&state->funcs); + return NULL; + } + + state->pio_offset = pio_add_program(state->pio, &WIZNET_PIO_SPI_PROGRAM_FUNC); + + pio_sm_config sm_config = WIZNET_PIO_SPI_PROGRAM_GET_DEFAULT_CONFIG_FUNC(state->pio_offset); + + sm_config_set_clkdiv_int_frac(&sm_config, state->spi_config->clock_div_major, state->spi_config->clock_div_minor); + hw_write_masked(&pads_bank0_hw->io[state->spi_config->clock_pin], + (uint)PADS_DRIVE_STRENGTH << PADS_BANK0_GPIO0_DRIVE_LSB, + PADS_BANK0_GPIO0_DRIVE_BITS + ); + hw_write_masked(&pads_bank0_hw->io[state->spi_config->clock_pin], + (uint)1 << PADS_BANK0_GPIO0_SLEWFAST_LSB, + PADS_BANK0_GPIO0_SLEWFAST_BITS + ); + + sm_config_set_out_pins(&sm_config, state->spi_config->data_out_pin, 1); + sm_config_set_in_pins(&sm_config, state->spi_config->data_in_pin); + sm_config_set_set_pins(&sm_config, state->spi_config->data_out_pin, 1); + sm_config_set_sideset(&sm_config, 1, false, false); + sm_config_set_sideset_pins(&sm_config, state->spi_config->clock_pin); + + sm_config_set_in_shift(&sm_config, false, true, 8); + sm_config_set_out_shift(&sm_config, false, true, 8); + hw_set_bits(&state->pio->input_sync_bypass, 1u << state->spi_config->data_in_pin); + pio_sm_set_config(state->pio, state->pio_sm, &sm_config); + pio_sm_set_consecutive_pindirs(state->pio, state->pio_sm, state->spi_config->clock_pin, 1, true); + gpio_set_function(state->spi_config->data_out_pin, state->pio_func_sel); + gpio_set_function(state->spi_config->clock_pin, state->pio_func_sel); + + // Set data pin to pull down and schmitt + gpio_set_pulls(state->spi_config->data_in_pin, false, true); + gpio_set_input_hysteresis_enabled(state->spi_config->data_in_pin, true); + + pio_sm_exec(state->pio, state->pio_sm, pio_encode_set(pio_pins, 1)); + state->dma_out = (int8_t)dma_claim_unused_channel(false); // todo: Should be able to use one dma channel? + state->dma_in = (int8_t)dma_claim_unused_channel(false); + if (state->dma_out < 0 || state->dma_in < 0) { + wiznet_pio_spi_close(&state->funcs); + return NULL; + } + return &state->funcs; +} + +void wiznet_pio_spi_close(wiznet_pio_spi_handle_t handle) { + wiznet_pio_spi_state_t *state = (wiznet_pio_spi_state_t *)handle; + if (state) { + if (state->pio_sm >= 0) { + if (state->pio_offset != -1) { + pio_remove_program(state->pio, &WIZNET_PIO_SPI_PROGRAM_FUNC, state->pio_offset); + } + + pio_sm_unclaim(state->pio, state->pio_sm); + } + if (state->dma_out >= 0) { + dma_channel_unclaim(state->dma_out); + state->dma_out = -1; + } + if (state->dma_in >= 0) { + dma_channel_unclaim(state->dma_in); + state->dma_in = -1; + } + state->funcs = NULL; + } +} + +static void cs_set(wiznet_pio_spi_state_t *state, bool value) { + gpio_put(state->spi_config->cs_pin, value); +} + +static __noinline void ns_delay(uint32_t ns) { + // cycles = ns * clk_sys_hz / 1,000,000,000 + uint32_t cycles = ns * (clock_get_hz(clk_sys) >> 16u) / (1000000000u >> 16u); + busy_wait_at_least_cycles(cycles); +} + +static void wiznet_pio_spi_frame_start(void) { + assert(active_state); + + gpio_set_function(active_state->spi_config->data_out_pin, active_state->pio_func_sel); + gpio_set_function(active_state->spi_config->clock_pin, active_state->pio_func_sel); + gpio_pull_down(active_state->spi_config->clock_pin); + + // Pull CS low + cs_set(active_state, false); +} + +static void wiznet_pio_spi_frame_end(void) { + assert(active_state); + + // from this point a positive edge will cause an IRQ to be pending + cs_set(active_state, true); + + // we need to wait a bit in case the irq line is incorrectly high + #ifdef IRQ_SAMPLE_DELAY_NS + ns_delay(IRQ_SAMPLE_DELAY_NS); + #endif +} + +// send tx then receive rx +// rx can be null if you just want to send, but tx and tx_length must be valid +bool wiznet_pio_spi_transfer(const uint8_t *tx, size_t tx_length, uint8_t *rx, size_t rx_length) { + const wiznet_pio_spi_state_t *state = active_state; + if (!state || (tx == NULL)) { + return false; + } + + if (rx != NULL && tx != NULL) { + assert(tx && tx_length && rx_length); + + pio_sm_set_enabled(state->pio, state->pio_sm, false); // disable sm + pio_sm_set_wrap(state->pio, state->pio_sm, state->pio_offset + WIZNET_PIO_SPI_OFFSET_WRITE_BITS, state->pio_offset + WIZNET_PIO_SPI_OFFSET_READ_END - 1); + pio_sm_clear_fifos(state->pio, state->pio_sm); // clear fifos from previous run + pio_sm_set_pindirs_with_mask(state->pio, state->pio_sm, 1u << state->spi_config->data_out_pin, 1u << state->spi_config->data_out_pin); + pio_sm_restart(state->pio, state->pio_sm); + pio_sm_clkdiv_restart(state->pio, state->pio_sm); + pio_sm_put(state->pio, state->pio_sm, tx_length * 8 - 1); // set x + pio_sm_exec(state->pio, state->pio_sm, pio_encode_out(pio_x, 32)); + pio_sm_put(state->pio, state->pio_sm, rx_length - 1); // set y + pio_sm_exec(state->pio, state->pio_sm, pio_encode_out(pio_y, 32)); + pio_sm_exec(state->pio, state->pio_sm, pio_encode_jmp(state->pio_offset)); // setup pc + + dma_channel_abort(state->dma_out); + dma_channel_abort(state->dma_in); + + dma_channel_config out_config = dma_channel_get_default_config(state->dma_out); + channel_config_set_dreq(&out_config, pio_get_dreq(state->pio, state->pio_sm, true)); + channel_config_set_transfer_data_size(&out_config, DMA_SIZE_8); + dma_channel_configure(state->dma_out, &out_config, &state->pio->txf[state->pio_sm], tx, tx_length, true); + + dma_channel_config in_config = dma_channel_get_default_config(state->dma_in); + channel_config_set_dreq(&in_config, pio_get_dreq(state->pio, state->pio_sm, false)); + channel_config_set_write_increment(&in_config, true); + channel_config_set_read_increment(&in_config, false); + channel_config_set_transfer_data_size(&in_config, DMA_SIZE_8); + dma_channel_configure(state->dma_in, &in_config, rx, &state->pio->rxf[state->pio_sm], rx_length, true); + + pio_sm_set_enabled(state->pio, state->pio_sm, true); + __compiler_memory_barrier(); + + dma_channel_wait_for_finish_blocking(state->dma_out); + dma_channel_wait_for_finish_blocking(state->dma_in); + + __compiler_memory_barrier(); + } else if (tx != NULL) { + assert(tx_length); + + pio_sm_set_enabled(state->pio, state->pio_sm, false); + pio_sm_set_wrap(state->pio, state->pio_sm, state->pio_offset + WIZNET_PIO_SPI_OFFSET_WRITE_BITS, state->pio_offset + WIZNET_PIO_SPI_OFFSET_WRITE_END - 1); + pio_sm_clear_fifos(state->pio, state->pio_sm); + pio_sm_restart(state->pio, state->pio_sm); + pio_sm_clkdiv_restart(state->pio, state->pio_sm); + pio_sm_put(state->pio, state->pio_sm, tx_length * 8 - 1); + pio_sm_exec(state->pio, state->pio_sm, pio_encode_out(pio_x, 32)); + pio_sm_put(state->pio, state->pio_sm, tx_length - 1); + pio_sm_exec(state->pio, state->pio_sm, pio_encode_out(pio_y, 32)); + pio_sm_exec(state->pio, state->pio_sm, pio_encode_set(pio_pins, 0)); + pio_sm_set_consecutive_pindirs(state->pio, state->pio_sm, state->spi_config->data_out_pin, 1, true); + pio_sm_exec(state->pio, state->pio_sm, pio_encode_jmp(state->pio_offset + WIZNET_PIO_SPI_OFFSET_WRITE_BITS)); + + dma_channel_abort(state->dma_out); + + dma_channel_config out_config = dma_channel_get_default_config(state->dma_out); + channel_config_set_dreq(&out_config, pio_get_dreq(state->pio, state->pio_sm, true)); + + channel_config_set_transfer_data_size(&out_config, DMA_SIZE_8); + dma_channel_configure(state->dma_out, &out_config, &state->pio->txf[state->pio_sm], tx, tx_length, true); + + const uint32_t fDebugTxStall = 1u << (PIO_FDEBUG_TXSTALL_LSB + state->pio_sm); + state->pio->fdebug = fDebugTxStall; + pio_sm_set_enabled(state->pio, state->pio_sm, true); + while (!(state->pio->fdebug & fDebugTxStall)) { + // printf("WIZNET_PIO_SPI: waiting for tx stall\n"); + tight_loop_contents(); // todo timeout + } + uint32_t timeout = 1000000; + if (timeout == 0) { + printf("ERROR: PIO TXSTALL timeout!\n"); + return false; + } + __compiler_memory_barrier(); + pio_sm_set_enabled(state->pio, state->pio_sm, false); + pio_sm_set_consecutive_pindirs(state->pio, state->pio_sm, state->spi_config->data_in_pin, 1, false); + } else if (rx != NULL) { + panic_unsupported(); // shouldn't be used + } + pio_sm_exec(state->pio, state->pio_sm, pio_encode_mov(pio_pins, pio_null)); // for next time we turn output on + + return true; +} + +// To read a byte we must first have been asked to write a 3 byte spi header +static uint8_t wiznet_pio_spi_read_byte(void) { + assert(active_state); + assert(active_state->spi_header_count == WIZNET_PIO_SPI_HEADER_LEN); + uint8_t ret; + if (!wiznet_pio_spi_transfer(active_state->spi_header, active_state->spi_header_count, &ret, 1)) { + panic("spi failed read"); + } + active_state->spi_header_count = 0; + return ret; +} + +// This is not used when the burst functions are provided +static void wiznet_pio_spi_write_byte(uint8_t wb) { + panic_unsupported(); // shouldn't be used +} + +// To read a buffer we must first have been asked to write a 3 byte spi header +void wiznet_pio_spi_read_buffer(uint8_t *pBuf, uint16_t len) { + assert(active_state); + assert(active_state->spi_header_count == WIZNET_PIO_SPI_HEADER_LEN); + if (!wiznet_pio_spi_transfer(active_state->spi_header, active_state->spi_header_count, pBuf, len)) { + panic("spi failed reading buffer"); + } + active_state->spi_header_count = 0; +} + +// If we have been asked to write a spi header already, then write it and the rest of the buffer +// or else if we've been given enough data for just the spi header, save it until the next call +// or we're writing a byte in which case we're given a buffer including the spi header +void wiznet_pio_spi_write_buffer(const uint8_t *pBuf, uint16_t len) { + assert(active_state); + + if (len < WIZNET_PIO_SPI_HEADER_LEN && active_state->spi_header_count != WIZNET_PIO_SPI_HEADER_LEN) { + memcpy(&active_state->spi_header[active_state->spi_header_count], pBuf, len); // expect another call + active_state->spi_header_count++; + } else if (len == WIZNET_PIO_SPI_HEADER_LEN && active_state->spi_header_count == 0) { + memcpy(active_state->spi_header, pBuf, WIZNET_PIO_SPI_HEADER_LEN); // expect another call + active_state->spi_header_count = WIZNET_PIO_SPI_HEADER_LEN; + } else { + if (active_state->spi_header_count == WIZNET_PIO_SPI_HEADER_LEN) { + if (!wiznet_pio_spi_transfer(active_state->spi_header, WIZNET_PIO_SPI_HEADER_LEN, NULL, 0)) { + panic("spi failed writing header"); + } + active_state->spi_header_count = 0; + } + assert(active_state->spi_header_count == 0); + if (!wiznet_pio_spi_transfer(pBuf, len, NULL, 0)) { + panic("spi failed writing buffer"); + } + } +} + +static void wiznet_pio_spi_set_active(wiznet_pio_spi_handle_t handle) { + active_state = (wiznet_pio_spi_state_t *)handle; +} + +static void wiznet_pio_spi_set_inactive(void) { + active_state = NULL; +} + +static void wiznet_pio_spi_reset(wiznet_pio_spi_handle_t handle) { + wiznet_pio_spi_state_t *state = (wiznet_pio_spi_state_t *)handle; + gpio_set_dir(state->spi_config->reset_pin, GPIO_OUT); + gpio_put(state->spi_config->reset_pin, 0); + sleep_ms(100); + gpio_put(state->spi_config->reset_pin, 1); + sleep_ms(100); +} + +static wiznet_pio_spi_funcs_t *get_wiznet_pio_spi_impl(void) { + static wiznet_pio_spi_funcs_t funcs = { + .close = wiznet_pio_spi_close, + .set_active = wiznet_pio_spi_set_active, + .set_inactive = wiznet_pio_spi_set_inactive, + .frame_start = wiznet_pio_spi_frame_start, + .frame_end = wiznet_pio_spi_frame_end, + .read_byte = wiznet_pio_spi_read_byte, + .write_byte = wiznet_pio_spi_write_byte, + .read_buffer = wiznet_pio_spi_read_buffer, + .write_buffer = wiznet_pio_spi_write_buffer, + .reset = wiznet_pio_spi_reset, + }; + return &funcs; +} diff --git a/ports/raspberrypi/common-hal/wiznet/wizchip_pio_spi.h b/ports/raspberrypi/common-hal/wiznet/wizchip_pio_spi.h new file mode 100755 index 00000000000..841eb48c480 --- /dev/null +++ b/ports/raspberrypi/common-hal/wiznet/wizchip_pio_spi.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2023 Raspberry Pi (Trading) Ltd. + * + * SPDX-License-Identifier: BSD-3-Clause + */ + +#ifndef _WIZNET_PIO_SPI_H_ +#define _WIZNET_PIO_SPI_H_ + +typedef struct wiznet_pio_spi_config { + uint8_t data_in_pin; + uint8_t data_out_pin; + uint8_t cs_pin; + uint8_t clock_pin; + uint8_t irq_pin; + uint8_t reset_pin; + uint16_t clock_div_major; + uint8_t clock_div_minor; + uint8_t spi_hw_instance; +} wiznet_pio_spi_config_t; + +typedef struct wiznet_pio_spi_funcs **wiznet_pio_spi_handle_t; + +typedef struct wiznet_pio_spi_funcs { + void (*close)(wiznet_pio_spi_handle_t funcs); + void (*set_active)(wiznet_pio_spi_handle_t funcs); + void (*set_inactive)(void); + void (*frame_start)(void); + void (*frame_end)(void); + uint8_t (*read_byte)(void); + void (*write_byte)(uint8_t tx_data); + void (*read_buffer)(uint8_t *pBuf, uint16_t len); + void (*write_buffer)(const uint8_t *pBuf, uint16_t len); + void (*reset)(wiznet_pio_spi_handle_t funcs); +} wiznet_pio_spi_funcs_t; + +wiznet_pio_spi_handle_t wiznet_pio_spi_open(const wiznet_pio_spi_config_t *pio_spi_config); +void wiznet_pio_spi_close(wiznet_pio_spi_handle_t handle); +bool wiznet_pio_spi_transfer(const uint8_t *tx, size_t tx_length, uint8_t *rx, size_t rx_length); +void wiznet_pio_spi_read_buffer(uint8_t *pBuf, uint16_t len); +void wiznet_pio_spi_write_buffer(const uint8_t *pBuf, uint16_t len); + +#endif diff --git a/ports/raspberrypi/common-hal/wiznet/wizchip_pio_spi.pio b/ports/raspberrypi/common-hal/wiznet/wizchip_pio_spi.pio new file mode 100755 index 00000000000..97a1c5b73d4 --- /dev/null +++ b/ports/raspberrypi/common-hal/wiznet/wizchip_pio_spi.pio @@ -0,0 +1,24 @@ +; +; Copyright (c) 2023 Raspberry Pi (Trading) Ltd. +; +; SPDX-License-Identifier: BSD-3-Clause +; + +.program wiznet_pio_spi_write_read +.side_set 1 + +public write_bits: + out pins, 1 side 0 + jmp x-- write_bits side 1 + set pins 0 side 0 +public write_end: +read_byte_delay: + set pindirs 0 side 0 +read_byte: + set x 6 side 1 +read_bits: + in pins, 1 side 0 + jmp x-- read_bits side 1 + in pins, 1 side 0 + jmp y-- read_byte side 0 +public read_end: diff --git a/ports/raspberrypi/cyw43_configport.h b/ports/raspberrypi/cyw43_configport.h index c1769436ae4..5ff70e14d13 100644 --- a/ports/raspberrypi/cyw43_configport.h +++ b/ports/raspberrypi/cyw43_configport.h @@ -16,6 +16,10 @@ #define CYW43_NETUTILS (1) +// Keep driver warnings off the serial console. Every scan warns once per network +// that offers a cipher the driver does not know, such as GCMP on WPA3 routers. +#define CYW43_WARN(...) ((void)0) + #if CIRCUITPY_USB_DEVICE #include "supervisor/usb.h" #define CYW43_EVENT_POLL_HOOK usb_background(); diff --git a/ports/raspberrypi/flash_info.h.jinja b/ports/raspberrypi/flash_info.h.jinja index cfeb4840b9e..aa507aad400 100644 --- a/ports/raspberrypi/flash_info.h.jinja +++ b/ports/raspberrypi/flash_info.h.jinja @@ -3,3 +3,9 @@ #pragma once #define FLASH_DEFAULT_POWER_OF_TWO {{ default_power_of_two }} + +// Worst-case read timing across the board's flash devices, from data/nvm.toml. +// Used to choose the flash clock divider, and on RP2350 the sample delay. +#define FLASH_EB_MAX_SCK_KHZ {{ eb_max_khz }} +#define FLASH_MAX_OUTPUT_VALID_PS {{ max_output_valid_ps }} +#define FLASH_MIN_OUTPUT_HOLD_PS {{ min_output_hold_ps }} diff --git a/ports/raspberrypi/gen_stage2.py b/ports/raspberrypi/gen_stage2.py index 005994dc107..c41c7503112 100644 --- a/ports/raspberrypi/gen_stage2.py +++ b/ports/raspberrypi/gen_stage2.py @@ -7,17 +7,23 @@ 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: + skus = [sku.strip() for sku in skus.split(",") if sku.strip()] + if not skus: print("Set EXTERNAL_FLASH_DEVICES in mpconfigboard.mk with all possible flash skus") raise typer.Exit(code=1) + flashes = cascadetoml.filter_toml( + pathlib.Path("../../data/nvm.toml"), ['sku="{}"'.format(sku) for sku in skus] + ) + + # Stop if a listed device is not in data/nvm.toml. Otherwise it would be + # left out silently, and its settings and read timing would not be used. + found = {nvm["sku"] for nvm in flashes["nvm"]} + missing = [sku for sku in skus if sku not in found] + if missing: + print("EXTERNAL_FLASH_DEVICES lists devices not in data/nvm.toml:", ", ".join(missing)) + raise typer.Exit(code=1) + def all_have(nvms, key): for nvm in nvms: if not nvm.get(key, False): @@ -41,7 +47,6 @@ def all_match(nvms, key, default=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 @@ -64,15 +69,41 @@ def all_match(nvms, key, default=None): 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 + # RP2350 stage 2 runs after every flash erase or program, at whatever the + # system clock is then. In quad mode it makes one read to enter + # continuous-read mode. Its divider and sample delay must be safe at any + # system clock. Divider 8 with a sample delay of 6 (set in the template) + # meets the setup and hold times of flash with an output valid time of 8 ns + # or less, up to 532 MHz. CircuitPython sets the real timing for the system + # clock afterward. + rp2350_clock_divider = 8 + + # Stage 2 always uses 0xeb for quad reads, because the read timing below is + # rated for 0xeb. Datasheets often give no separate rating for 0xe7. + read_command = 0xEB if quad_ok else 0x03 + wait_cycles = 4 if quad_ok else 0 + + # Read timing for choosing the flash clock divider, and on RP2350 the sample delay + # (mcu_processor_update_flash_timing() in common-hal/microcontroller/Processor.c). + # Use the worst case across all the listed devices, because any of them may + # be fitted. A device without a value uses the defaults passed to worst() + # below: 75 MHz, an output valid time of 8 ns and an output hold time of 0. + # + # A device with eb_quad_read_max_clock_speed_mhz = 0 has no 0xeb read, so + # stage 2 uses the plain 0x03 read. All the devices in data/nvm.toml + # support 0x03 at 33 MHz or more. + def worst(key, default, pick): + values = [] + for nvm in flashes["nvm"]: + value = nvm.get(key, default) + if key == "eb_quad_read_max_clock_speed_mhz" and value == 0: + value = 33 + values.append(value) + return pick(values) + + eb_max_khz = int(worst("eb_quad_read_max_clock_speed_mhz", 75, min) * 1000) + max_output_valid_ps = int(worst("max_output_valid_ns", 8, max) * 1000) + min_output_hold_ps = int(worst("min_output_hold_ns", 0, min) * 1000) flash_settings = { "quad_ok": quad_ok, @@ -80,9 +111,13 @@ def all_match(nvms, key, default=None): "quad_enable_bit_mask": quad_enable_bit_mask, "split_status_write": split_status_write, "clock_divider": clock_divider, + "rp2350_clock_divider": rp2350_clock_divider, "read_command": read_command, "wait_cycles": wait_cycles, "default_power_of_two": default_power_of_two, + "eb_max_khz": eb_max_khz, + "max_output_valid_ps": max_output_valid_ps, + "min_output_hold_ps": min_output_hold_ps, } template = Template(input_template.read_text()) diff --git a/ports/raspberrypi/lib/Pico-PIO-USB b/ports/raspberrypi/lib/Pico-PIO-USB index e0aba546813..9e502a55998 160000 --- a/ports/raspberrypi/lib/Pico-PIO-USB +++ b/ports/raspberrypi/lib/Pico-PIO-USB @@ -1 +1 @@ -Subproject commit e0aba546813d89cb7f321bef3363bfba5f282e14 +Subproject commit 9e502a559983a6b857b8c6328c84729cbe809749 diff --git a/ports/raspberrypi/lib/cyw43-driver b/ports/raspberrypi/lib/cyw43-driver index c1075d4bc44..a117ced15c1 160000 --- a/ports/raspberrypi/lib/cyw43-driver +++ b/ports/raspberrypi/lib/cyw43-driver @@ -1 +1 @@ -Subproject commit c1075d4bc440422cf2b2fd12c64a1f53f77660ee +Subproject commit a117ced15c1cc56280e3a6592740494c28769179 diff --git a/ports/raspberrypi/link-rp2040.ld b/ports/raspberrypi/link-rp2040.ld index 6e7bd15a7b6..189c3d7c338 100644 --- a/ports/raspberrypi/link-rp2040.ld +++ b/ports/raspberrypi/link-rp2040.ld @@ -82,7 +82,7 @@ SECTIONS *(.property_getset) __property_getset_end = .; - *(EXCLUDE_FILE(*libgcc.a: *libc.a:*lib_a-mem*.o *libm.a: *interp.o *divider.o *tusb_fifo.o *mem_ops_aeabi.o *usbh.o) .text*) + *(EXCLUDE_FILE(*libgcc.a: *libc.a:*lib_a-mem*.o *libm.a: *interp.o *divider.o *pico_int64_ops_aeabi.o *tusb_fifo.o *mem_ops_aeabi.o *usbh.o) .text*) /* Allow everything in usbh.o except tuh_task_event_ready because we read it from core 1. */ *usbh.o (.text.[_uphc]* .text.tuh_[cmved]* .text.tuh_task_ext*) *(.fini) diff --git a/ports/raspberrypi/link-rp2350.ld b/ports/raspberrypi/link-rp2350.ld index a2cc62909e6..ec39f08e806 100644 --- a/ports/raspberrypi/link-rp2350.ld +++ b/ports/raspberrypi/link-rp2350.ld @@ -37,11 +37,6 @@ ENTRY(_entry_point) SECTIONS { - /* Second stage bootloader is prepended to the image. It must be 256 bytes big - and checksummed. It is usually built by the boot_stage2 target - in the Pico SDK - */ - .flash_begin : { __flash_binary_start = .; } > FLASH_FIRMWARE @@ -63,7 +58,7 @@ SECTIONS *(.property_getset) __property_getset_end = .; - *(EXCLUDE_FILE(*libgcc.a: *libc.a:*lib_a-mem*.o *libm.a: *interp.o *divider.o *tusb_fifo.o *mem_ops_aeabi.o *usbh.o *string0.o) .text*) + *(EXCLUDE_FILE(*libgcc.a: *libc.a:*lib_a-mem*.o *libm.a: *interp.o *divider.o *pico_int64_ops_aeabi.o *tusb_fifo.o *mem_ops_aeabi.o *usbh.o *string0.o) .text*) /* Allow everything in usbh.o except tuh_task_event_ready because we read it from core 1. */ *usbh.o (.text.[_uphc]* .text.tuh_[cmved]* .text.tuh_task_ext*) *(.fini) @@ -84,6 +79,22 @@ SECTIONS . = ALIGN(4); } > FLASH_FIRMWARE + /* Stage 2 (the flash read setup function), generated from + boot_stage2/RP2350.c.jinja. On RP2350 the boot ROM does not run it. + The Pico SDK's startup code (crt0) runs it at boot and copies it to boot + RAM, and the SDK reruns it after each flash erase or program. It must + fit in boot RAM's 256 bytes. + */ + .boot2 : { + . = ALIGN(4); + __boot2_start__ = .; + *(.boot2) + __boot2_end__ = .; + } > FLASH_FIRMWARE + + ASSERT(__boot2_end__ - __boot2_start__ <= 256, + "ERROR: RP2350 stage 2 must be no more than 256 bytes in size") + .rodata : { *(EXCLUDE_FILE(*libgcc.a: *libc.a:*lib_a-mem*.o *libm.a:) .rodata*) . = ALIGN(4); @@ -205,6 +216,16 @@ SECTIONS _ld_dtcm_bss_start = ADDR(.dtcm_bss); _ld_dtcm_bss_size = SIZEOF(.dtcm_bss); + /* Kept powered through deep sleep by pico_low_power. Holds alarm.sleep_memory. */ + .persistent_data (NOLOAD) : { + . = ALIGN(4); + __persistent_data_start__ = .; + *(.uninitialized) + *(.persistent_data*) + . = ALIGN(4); + __persistent_data_end__ = .; + } > RAM + .uninitialized_data (COPY): { . = ALIGN(4); *(.uninitialized_data*) diff --git a/ports/raspberrypi/lwip_src/lwip_mem.c b/ports/raspberrypi/lwip_src/lwip_mem.c index 244f51e289b..23b185354b0 100644 --- a/ports/raspberrypi/lwip_src/lwip_mem.c +++ b/ports/raspberrypi/lwip_src/lwip_mem.c @@ -8,10 +8,12 @@ #include #include "lib/tlsf/tlsf.h" #include "lwip_mem.h" +#include "shared-bindings/microcontroller/__init__.h" #include "supervisor/port_heap.h" void *lwip_heap_malloc(size_t size) { - return port_malloc(size, true); + void *ptr = port_malloc(size, true); + return ptr; } void lwip_heap_free(void *ptr) { diff --git a/ports/raspberrypi/mpconfigport.h b/ports/raspberrypi/mpconfigport.h index 1181517fdf9..82c83ce63a4 100644 --- a/ports/raspberrypi/mpconfigport.h +++ b/ports/raspberrypi/mpconfigport.h @@ -8,18 +8,29 @@ #include "hardware/platform_defs.h" -#ifdef PICO_RP2040 +// CIRCUITPY-CHANGE: CircuitPython supports raw sockets through its own lwip +// integration, independently of MICROPY_PY_LWIP. +#define MICROPY_PY_LWIP_SOCK_RAW (1) + +#if PICO_RP2040 #define MICROPY_PY_SYS_PLATFORM "RP2040" #endif -#ifdef PICO_RP2350 +#if PICO_RP2350 #define MICROPY_PY_SYS_PLATFORM "RP2350" + +// PSRAM can require more stack space for GC. +#define MICROPY_ALLOC_GC_STACK_SIZE (128) #endif // Setting a non-default value also requires a non-default link.ld #ifndef CIRCUITPY_FIRMWARE_SIZE #define CIRCUITPY_FIRMWARE_SIZE (1020 * 1024) #endif +// The nvm sector and CIRCUITPY follow the firmware, so it must end on a flash erase sector. +#if CIRCUITPY_FIRMWARE_SIZE % 4096 != 0 +#error "CIRCUITPY_FIRMWARE_SIZE must be a multiple of 4 KB" +#endif #define CIRCUITPY_INTERNAL_NVM_SIZE (4 * 1024) // This is the XIP address @@ -33,13 +44,34 @@ #define CIRCUITPY_PROCESSOR_COUNT (2) +// For RP2 boards we use a custom way to read BOOTSEL +#define CIRCUITPY_BOOT_BUTTON_NO_GPIO (1) + #if CIRCUITPY_USB_HOST #define CIRCUITPY_USB_HOST_INSTANCE 1 +// Pico-PIO-USB +#define CIRCUITPY_USB_HOST_ISO_RECORDS (1) #endif // This also includes mpconfigboard.h. #include "py/circuitpy_mpconfig.h" +// Turn on this option to allow the use of the internal pull-up resistors on +// the I2C pins, for boards whose on-board I2C peripherals lack external pull +// up resistors. The internal pull-ups are weak, and using them is only to +// compensate for design decisions that are out of the control of the authors +// of CircuitPython. It is not an endorsement of running without appropriate +// external pull up resistors. +#ifndef CIRCUITPY_I2C_ALLOW_INTERNAL_PULL_UP +#define CIRCUITPY_I2C_ALLOW_INTERNAL_PULL_UP (0) +#endif + +// CIRCUITPY_FLASH_MAX_SCK_HZ is not defined by default. The flash clock is +// chosen from the flash's datasheet timing in flash_info.h, which is +// generated from data/nvm.toml. A board whose flash or wiring needs a slower +// flash clock can define CIRCUITPY_FLASH_MAX_SCK_HZ in mpconfigboard.h as a +// limit, in Hz. + #if CIRCUITPY_CYW43 #define MICROPY_PY_LWIP_ENTER cyw43_arch_lwip_begin(); #define MICROPY_PY_LWIP_REENTER MICROPY_PY_LWIP_ENTER diff --git a/ports/raspberrypi/mpconfigport.mk b/ports/raspberrypi/mpconfigport.mk index bb4e183461b..8ea58de7b58 100644 --- a/ports/raspberrypi/mpconfigport.mk +++ b/ports/raspberrypi/mpconfigport.mk @@ -6,24 +6,37 @@ CIRCUITPY_OPTIMIZE_PROPERTY_FLASH_SIZE ?= 1 CIRCUITPY_WIFI_RADIO_SETTABLE_MAC_ADDRESS = 0 CIRCUITPY_RP2PIO ?= 1 +# SPI is async on this port; busio.SPI is built on it. +CIRCUITPY_ASYNC_SPI ?= 1 +# The 24 KB stack has room for a larger display refresh buffer. +CIRCUITPY_DISPLAY_AREA_BUFFER_SIZE ?= 2048 CIRCUITPY_NEOPIXEL_WRITE ?= $(CIRCUITPY_RP2PIO) CIRCUITPY_FLOPPYIO ?= 1 CIRCUITPY_FRAMEBUFFERIO ?= $(CIRCUITPY_DISPLAYIO) +CIRCUITPY_BITMAPTOOLS_FAST_ROTOZOOM ?= $(CIRCUITPY_BITMAPTOOLS) CIRCUITPY_FULL_BUILD ?= 1 CIRCUITPY_AUDIOMP3 ?= 1 +CIRCUITPY_AUDIOSPEED ?= 1 +CIRCUITPY_AUDIOEFFECTS ?= 1 +CIRCUITPY_AUDIOFILEWRITER ?= 1 CIRCUITPY_BITOPS ?= 1 CIRCUITPY_HASHLIB ?= 1 CIRCUITPY_HASHLIB_MBEDTLS ?= 1 CIRCUITPY_IMAGECAPTURE ?= 1 +CIRCUITPY_LOAD_NATIVE ?= 1 CIRCUITPY_MAX3421E ?= 0 +CIRCUITPY_MCP4822 ?= 0 CIRCUITPY_MEMORYMAP ?= 1 CIRCUITPY_PWMIO ?= 1 CIRCUITPY_RGBMATRIX ?= $(CIRCUITPY_DISPLAYIO) CIRCUITPY_ROTARYIO ?= 1 CIRCUITPY_ROTARYIO_SOFTENCODER = 1 +# The CIRCUITPY drive is execute-in-place on every RP2 board +CIRCUITPY_STORAGE_MAP_FILE ?= 1 CIRCUITPY_SYNTHIO_MAX_CHANNELS = 24 CIRCUITPY_USB_HOST ?= 1 CIRCUITPY_USB_VIDEO ?= 1 +CIRCUITPY_USB_AUDIO ?= 1 # Things that need to be implemented. CIRCUITPY_FREQUENCYIO = 0 @@ -41,16 +54,19 @@ CIRCUITPY_ANALOGBUFIO = 1 # Audio via PWM CIRCUITPY_AUDIOIO = 0 CIRCUITPY_AUDIOBUSIO ?= 1 +CIRCUITPY_AUDIOI2SIN ?= $(CIRCUITPY_AUDIOBUSIO) CIRCUITPY_AUDIOCORE ?= 1 CIRCUITPY_AUDIOPWMIO ?= 1 CIRCUITPY_AUDIOMIXER ?= 1 -ifeq ($(CHIP_VARIANT),RP2040) CIRCUITPY_ALARM ?= 1 +ifeq ($(CHIP_VARIANT),RP2040) # Default PICODVI off because it uses RAM to store code run on the second CPU for RP2040. CIRCUITPY_PICODVI ?= 0 +# picodvi.AudioOut needs HSTX. +CIRCUITPY_PICODVI_AUDIOOUT = 0 CIRCUITPY_TOUCHIO ?= 1 @@ -59,21 +75,28 @@ CIRCUITPY_CYW43_INIT_DELAY ?= 1000 endif ifeq ($(CHIP_VARIANT),RP2350) -# This needs to be implemented. -CIRCUITPY_ALARM = 0 +# RP2350 has PSRAM that is not DMA-capable +CIRCUITPY_ALL_MEMORY_DMA_CAPABLE = 0 + # Default PICODVI on because it doesn't require much code in RAM to talk to HSTX. CIRCUITPY_PICODVI ?= 1 - -# Our generic touchio uses a pull down and RP2350 A2 hardware doesn't work correctly. -# So, turn touchio off because it doesn't work. -CIRCUITPY_TOUCHIO = 0 +# Audio over the DVI cable. Boards without a DVI connector may turn it off. +CIRCUITPY_PICODVI_AUDIOOUT ?= $(call enable-if-all,$(CIRCUITPY_PICODVI) $(CIRCUITPY_AUDIOCORE)) # delay in ms before calling cyw43_arch_init_with_country CIRCUITPY_CYW43_INIT_DELAY ?= 0 # Audio effects CIRCUITPY_AUDIOEFFECTS ?= 1 + +# Run PSA SHA-256 (hashlib, hmac, ssl) on the SHA-256 block. Needs mbedtls, which +# is built for ssl or hashlib-only mbedtls. +CIRCUITPY_RP2_SHA256_HW ?= $(call enable-if-any,$(CIRCUITPY_SSL) $(CIRCUITPY_HASHLIB_MBEDTLS_ONLY)) endif +# RP2040 has no SHA-256 block. +CIRCUITPY_RP2_SHA256_HW ?= 0 +# Adds the driver to mbedtls's hash dispatch. +MBEDTLS_DRIVER_PATCH = $(if $(filter 1,$(CIRCUITPY_RP2_SHA256_HW)),$(TOP)/lib/mbedtls_config/psa_dispatch.patch) INTERNAL_LIBM = 1 diff --git a/ports/raspberrypi/sdk b/ports/raspberrypi/sdk index bddd20f928c..079c6f39023 160000 --- a/ports/raspberrypi/sdk +++ b/ports/raspberrypi/sdk @@ -1 +1 @@ -Subproject commit bddd20f928ce76142793bef434d4f75f4af6e433 +Subproject commit 079c6f39023649b154152db30f1d781e884879bc diff --git a/ports/raspberrypi/sha256_psa/rp2_sha256_psa.c b/ports/raspberrypi/sha256_psa/rp2_sha256_psa.c new file mode 100644 index 00000000000..dad861d15ae --- /dev/null +++ b/ports/raspberrypi/sha256_psa/rp2_sha256_psa.c @@ -0,0 +1,230 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mikey Sklar for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// PSA transparent driver for SHA-256 on the RP2350 SHA-256 block. The context holds +// an mbedtls_sha256_context, and the builtin mbedtls_sha256_*() functions do +// anything done in software. +// +// The block holds one running hash, and its state can be read but not written: +// - One context at a time owns the block. It takes the block when it first has a +// whole 64-byte block to hash, while its state still equals the initial value. +// - After a whole block, the block's state is the chaining state the software code +// keeps in ctx->state. So an owner can always move to software: for a digest, a +// clone, or when another context takes the block. +// - Partial blocks stay in ctx->buffer and ctx->total is kept as the software code +// keeps it, so a moved context goes on in software unchanged. +// +// While a context owns the block, its ctx->state holds a signature instead: its own +// address and an ownership generation. An operation freed without +// psa_hash_abort() (a hashlib object that is garbage collected) leaves a dangling +// owner pointer, so the signature is checked before writing to the old owner. If +// it is gone, the memory has been reused and the old owner is dropped. + +#include "tf_psa_crypto_common.h" +#include "mbedtls/private/sha256.h" + +#include + +#include "hardware/sha256.h" +#include "pico/bootrom/lock.h" + +#include "rp2_sha256_psa.h" + +#define SHA256_BLOCK_LENGTH PSA_HASH_BLOCK_LENGTH(PSA_ALG_SHA_256) +#define SIGNATURE_MAGIC0 (0x53324852u) +#define SIGNATURE_MAGIC1 (0x3532ac1du) + +static mbedtls_sha256_context *owner; +static uint32_t owner_generation; + +static void block_start(void) { + // Big-endian message words from a byte buffer. START loads the initial value. + sha256_set_bswap(true); + sha256_err_not_ready_clear(); + sha256_start(); +} + +static void block_write(const uint8_t *data) { + // Ready drops after the 16th word, while the block is digested. + sha256_wait_ready_blocking(); + for (size_t i = 0; i < SHA256_BLOCK_LENGTH; i += 4) { + uint32_t word; + // data may be unaligned. + memcpy(&word, data + i, sizeof(word)); + sha256_put_word(word); + } +} + +static void block_read(uint32_t state[8]) { + sha256_wait_valid_blocking(); + for (size_t i = 0; i < 8; i++) { + state[i] = sha256_hw->sum[i]; + } +} + +static bool is_owner(const mbedtls_sha256_context *ctx) { + return ctx == owner && + ctx->state[0] == SIGNATURE_MAGIC0 && + ctx->state[1] == (uint32_t)(uintptr_t)ctx && + ctx->state[2] == owner_generation && + ctx->state[3] == (~owner_generation ^ SIGNATURE_MAGIC1); +} + +static void release(void) { + owner = NULL; + bootrom_release_lock(BOOTROM_LOCK_SHA_256); +} + +// Leave the block. A live owner first gets its state back, so it can go on in +// software; a dead one is just dropped. +static void evict_owner(void) { + if (owner == NULL) { + return; + } + if (is_owner(owner)) { + block_read(owner->state); + } + release(); +} + +static void release_if_owner(const mbedtls_sha256_context *ctx) { + if (ctx == owner) { + // ctx is being reset or freed, so its state is not needed. + release(); + } +} + +static bool try_acquire(mbedtls_sha256_context *ctx) { + evict_owner(); + if (!bootrom_try_acquire_lock(BOOTROM_LOCK_SHA_256)) { + return false; + } + owner = ctx; + owner_generation++; + ctx->state[0] = SIGNATURE_MAGIC0; + ctx->state[1] = (uint32_t)(uintptr_t)ctx; + ctx->state[2] = owner_generation; + ctx->state[3] = ~owner_generation ^ SIGNATURE_MAGIC1; + block_start(); + return true; +} + +static void ctx_update(mbedtls_sha256_context *ctx, const uint8_t *input, size_t input_length) { + if (input_length == 0) { + return; + } + size_t left = ctx->total[0] & (SHA256_BLOCK_LENGTH - 1); + if (!is_owner(ctx)) { + if (ctx == owner) { + // Stale pointer to memory that was reused for this context. + release(); + } + bool fresh = ctx->total[1] == 0 && ctx->total[0] < SHA256_BLOCK_LENGTH; + if (!fresh || left + input_length < SHA256_BLOCK_LENGTH || !try_acquire(ctx)) { + // Software. Can't fail for SHA-256. + mbedtls_sha256_update(ctx, input, input_length); + return; + } + } + + // Same buffering and length counting as the builtin mbedtls_sha256_update(). + size_t fill = SHA256_BLOCK_LENGTH - left; + ctx->total[0] += input_length; + if (ctx->total[0] < input_length) { + ctx->total[1]++; + } + + if (left && input_length >= fill) { + memcpy(ctx->buffer + left, input, fill); + block_write(ctx->buffer); + input += fill; + input_length -= fill; + left = 0; + } + while (input_length >= SHA256_BLOCK_LENGTH) { + block_write(input); + input += SHA256_BLOCK_LENGTH; + input_length -= SHA256_BLOCK_LENGTH; + } + if (input_length > 0) { + memcpy(ctx->buffer + left, input, input_length); + } +} + +static void ctx_finish(mbedtls_sha256_context *ctx, uint8_t *output) { + if (is_owner(ctx)) { + // Padding is one or two blocks; do it in software from the block's state. + block_read(ctx->state); + release(); + } else { + release_if_owner(ctx); + } + mbedtls_sha256_finish(ctx, output); +} + +psa_status_t rp2_sha256_psa_hash_setup(rp2_sha256_psa_hash_operation_t *op, psa_algorithm_t alg) { + if (alg != PSA_ALG_SHA_256) { + return PSA_ERROR_NOT_SUPPORTED; + } + release_if_owner(&op->sha256); + mbedtls_sha256_init(&op->sha256); + mbedtls_sha256_starts(&op->sha256, 0); + return PSA_SUCCESS; +} + +psa_status_t rp2_sha256_psa_hash_update(rp2_sha256_psa_hash_operation_t *op, + const uint8_t *input, size_t input_length) { + ctx_update(&op->sha256, input, input_length); + return PSA_SUCCESS; +} + +psa_status_t rp2_sha256_psa_hash_finish(rp2_sha256_psa_hash_operation_t *op, + uint8_t *hash, size_t hash_size, size_t *hash_length) { + *hash_length = 0; + if (hash_size < PSA_HASH_LENGTH(PSA_ALG_SHA_256)) { + return PSA_ERROR_BUFFER_TOO_SMALL; + } + ctx_finish(&op->sha256, hash); + *hash_length = PSA_HASH_LENGTH(PSA_ALG_SHA_256); + return PSA_SUCCESS; +} + +psa_status_t rp2_sha256_psa_hash_abort(rp2_sha256_psa_hash_operation_t *op) { + release_if_owner(&op->sha256); + mbedtls_sha256_free(&op->sha256); + return PSA_SUCCESS; +} + +psa_status_t rp2_sha256_psa_hash_clone(const rp2_sha256_psa_hash_operation_t *source, + rp2_sha256_psa_hash_operation_t *target) { + mbedtls_sha256_clone(&target->sha256, &source->sha256); + if (is_owner(&source->sha256)) { + // The copy goes on in software from the block's current state. + block_read(target->sha256.state); + } + return PSA_SUCCESS; +} + +psa_status_t rp2_sha256_psa_hash_compute(psa_algorithm_t alg, + const uint8_t *input, size_t input_length, + uint8_t *hash, size_t hash_size, size_t *hash_length) { + *hash_length = 0; + if (alg != PSA_ALG_SHA_256) { + return PSA_ERROR_NOT_SUPPORTED; + } + rp2_sha256_psa_hash_operation_t op; + rp2_sha256_psa_hash_setup(&op, alg); + rp2_sha256_psa_hash_update(&op, input, input_length); + psa_status_t status = rp2_sha256_psa_hash_finish(&op, hash, hash_size, hash_length); + rp2_sha256_psa_hash_abort(&op); + return status; +} + +void rp2_sha256_psa_reset(void) { + if (owner != NULL) { + release(); + } +} diff --git a/ports/raspberrypi/sha256_psa/rp2_sha256_psa.h b/ports/raspberrypi/sha256_psa/rp2_sha256_psa.h new file mode 100644 index 00000000000..754fa33ff0f --- /dev/null +++ b/ports/raspberrypi/sha256_psa/rp2_sha256_psa.h @@ -0,0 +1,32 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mikey Sklar for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// PSA transparent driver for SHA-256 on the RP2350 SHA-256 block. mbedtls's hash +// dispatch tries it before the builtin driver; lib/mbedtls_config/psa_dispatch.patch +// adds it there and adds its context to the PSA hash operation union. + +#include "psa/crypto.h" +#include "rp2_sha256_psa_ctx.h" + +// Returns PSA_ERROR_NOT_SUPPORTED for anything but PSA_ALG_SHA_256, so the +// dispatch falls through to the builtin driver. +psa_status_t rp2_sha256_psa_hash_setup(rp2_sha256_psa_hash_operation_t *op, psa_algorithm_t alg); +psa_status_t rp2_sha256_psa_hash_update(rp2_sha256_psa_hash_operation_t *op, + const uint8_t *input, size_t input_length); +psa_status_t rp2_sha256_psa_hash_finish(rp2_sha256_psa_hash_operation_t *op, + uint8_t *hash, size_t hash_size, size_t *hash_length); +psa_status_t rp2_sha256_psa_hash_abort(rp2_sha256_psa_hash_operation_t *op); +psa_status_t rp2_sha256_psa_hash_clone(const rp2_sha256_psa_hash_operation_t *source, + rp2_sha256_psa_hash_operation_t *target); +psa_status_t rp2_sha256_psa_hash_compute(psa_algorithm_t alg, + const uint8_t *input, size_t input_length, + uint8_t *hash, size_t hash_size, size_t *hash_length); + +// Forget which operation owns the block and release its lock. Call when the VM +// ends, since no operation outlives it. Doesn't allocate or raise. +void rp2_sha256_psa_reset(void); diff --git a/ports/raspberrypi/sha256_psa/rp2_sha256_psa_ctx.h b/ports/raspberrypi/sha256_psa/rp2_sha256_psa_ctx.h new file mode 100644 index 00000000000..0deec7be229 --- /dev/null +++ b/ports/raspberrypi/sha256_psa/rp2_sha256_psa_ctx.h @@ -0,0 +1,18 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mikey Sklar for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Operation context of the RP2350 SHA-256 PSA driver. It is a member of the PSA +// hash operation union (psa/crypto_driver_contexts_primitives.h), so it is +// included from inside psa/crypto.h and must not include it. + +#include "mbedtls/private/sha256.h" + +typedef struct { + // Software SHA-256 state, used whenever the operation doesn't own the block. + mbedtls_sha256_context sha256; +} rp2_sha256_psa_hash_operation_t; diff --git a/ports/raspberrypi/supervisor/internal_flash.c b/ports/raspberrypi/supervisor/internal_flash.c index 9d5e13348aa..b189422cabd 100644 --- a/ports/raspberrypi/supervisor/internal_flash.c +++ b/ports/raspberrypi/supervisor/internal_flash.c @@ -20,10 +20,11 @@ #include "shared-bindings/microcontroller/__init__.h" #include "audio_dma.h" +#include "common-hal/microcontroller/Processor.h" #include "supervisor/flash.h" #include "supervisor/usb.h" -#ifdef PICO_RP2350 +#if PICO_RP2350 #include "hardware/structs/qmi.h" #endif #include "hardware/structs/sio.h" @@ -54,6 +55,9 @@ void supervisor_flash_pre_write(void) { } void supervisor_flash_post_write(void) { + // The flash erase, program or command left stage 2's slow timing in place. + // Restore the timing for the current system clock. + mcu_processor_restore_flash_timing(); #if CIRCUITPY_AUDIOCORE // Unpause audio DMA. audio_dma_unpause_mask(_audio_channel_mask); @@ -149,3 +153,11 @@ mp_uint_t supervisor_flash_write_blocks(const uint8_t *src, uint32_t lba, uint32 void supervisor_flash_release_cache(void) { } + +#if CIRCUITPY_STORAGE_MAP_FILE +// storage.map_file: the CIRCUITPY drive is execute-in-place on every RP2 board. +const uint8_t *port_internal_flash_xip_address(uint32_t block, uint32_t *contiguous) { + *contiguous = supervisor_flash_get_block_count() - block; + return (const uint8_t *)(XIP_BASE + CIRCUITPY_CIRCUITPY_DRIVE_START_ADDR + block * FILESYSTEM_BLOCK_SIZE); +} +#endif diff --git a/ports/raspberrypi/supervisor/port.c b/ports/raspberrypi/supervisor/port.c index 7514b4e6ad4..d76029d53d7 100644 --- a/ports/raspberrypi/supervisor/port.c +++ b/ports/raspberrypi/supervisor/port.c @@ -4,11 +4,16 @@ // // SPDX-License-Identifier: MIT +#include +#include +#include #include #include +#include #include "supervisor/background_callback.h" #include "supervisor/board.h" +#include "supervisor/linker.h" #include "supervisor/port.h" #include "bindings/rp2pio/StateMachine.h" @@ -22,8 +27,17 @@ #include "audio_dma.h" #endif +#if CIRCUITPY_PICODVI_AUDIOOUT +#include "common-hal/picodvi/AudioOut.h" +#endif + #if CIRCUITPY_SSL #include "shared-module/ssl/__init__.h" +#include "psa/crypto.h" +#endif + +#if CIRCUITPY_RP2_SHA256_HW +#include "rp2_sha256_psa.h" #endif #if CIRCUITPY_WIFI @@ -33,10 +47,17 @@ #include "common-hal/rtc/RTC.h" #include "common-hal/busio/UART.h" +#if CIRCUITPY_SDIOIO +#include "common-hal/sdioio/SDCard.h" +#endif + #include "supervisor/shared/safe_mode.h" #include "supervisor/shared/stack.h" #include "supervisor/shared/tick.h" +#include "hardware/clocks.h" +#include "hardware/structs/psm.h" +#include "hardware/structs/scb.h" #include "hardware/structs/watchdog.h" #include "hardware/gpio.h" #include "hardware/uart.h" @@ -52,10 +73,17 @@ #include "pico/bootrom.h" #include "hardware/watchdog.h" -#ifdef PICO_RP2350 +#if PICO_RP2350 #include "RP2350.h" // CMSIS #endif +#if CIRCUITPY_BOOT_BUTTON_NO_GPIO +#include "hardware/gpio.h" +#include "hardware/sync.h" +#include "hardware/structs/ioqspi.h" +#include "hardware/structs/sio.h" +#endif + #include "supervisor/shared/serial.h" #include "tusb.h" @@ -64,6 +92,40 @@ critical_section_t background_queue_lock; +// The SDK's panic() lives in flash, but core1 may run with flash access +// disabled by the MPU (usb_host and picodvi lock it out), where a flash call +// hard faults before anything is printed. -Wl,--wrap=panic routes every +// panic here instead: core0 keeps the SDK behavior, core1 halts from RAM. +// Verified by tools/check_core1_flash_calls.py. +void __wrap_panic(const char *fmt, ...) __attribute__((noreturn, format(printf, 1, 2))); +void panic_core0(const char *fmt, va_list args) __attribute__((noreturn, format(printf, 1, 0))); + +// Flash-resident; only ever called from core0 (see __wrap_panic). Mirrors +// the SDK implementation. noinline keeps the flash-calling code out of the +// RAM-resident wrapper below. +__attribute__((noinline)) void panic_core0(const char *fmt, va_list args) { + puts("\n*** PANIC ***\n"); + if (fmt) { + vprintf(fmt, args); + puts(""); + } + _exit(1); +} + +void __not_in_flash_func(__wrap_panic)(const char *fmt, ...) { + if (get_core_num() == 0) { + va_list args; + va_start(args, fmt); + panic_core0(fmt, args); + } + // Flash may be MPU-locked on this core and stdio is core0-only, so the + // message is unprintable here. Halt in RAM: a debugger stops at the + // breakpoint, otherwise spin. + __breakpoint(); + while (1) { + } +} + extern volatile bool mp_msc_enabled; static void _tick_callback(uint alarm_num); @@ -89,8 +151,7 @@ extern uint32_t _ld_itcm_size; extern uint32_t _ld_itcm_flash_copy; static tlsf_t _heap = NULL; -static pool_t _ram_pool = NULL; -static pool_t _psram_pool = NULL; +static tlsf_t _psram_heap = NULL; static size_t _psram_size = 0; #ifdef CIRCUITPY_PSRAM_CHIP_SELECT @@ -101,7 +162,11 @@ static size_t _psram_size = 0; #include "hardware/structs/xip_ctrl.h" static void __no_inline_not_in_flash_func(setup_psram)(void) { - gpio_set_function(CIRCUITPY_PSRAM_CHIP_SELECT->number, GPIO_FUNC_XIP_CS1); + // Read the system clock and the chip select pin before QMI goes into + // direct mode. Both are in flash, and flash reads fault in direct mode. + uint32_t sys_clk_khz = clock_get_hz(clk_sys) / 1000; + const uint8_t cs_pin = CIRCUITPY_PSRAM_CHIP_SELECT->number; + gpio_set_function(cs_pin, GPIO_FUNC_XIP_CS1); _psram_size = 0; common_hal_mcu_disable_interrupts(); // Try and read the PSRAM ID via direct_csr. @@ -151,10 +216,9 @@ static void __no_inline_not_in_flash_func(setup_psram)(void) { if (kgd != 0x5D) { common_hal_mcu_enable_interrupts(); - reset_pin_number(CIRCUITPY_PSRAM_CHIP_SELECT->number); + reset_pin_number(cs_pin); return; } - never_reset_pin_number(CIRCUITPY_PSRAM_CHIP_SELECT->number); // Enable quad mode. qmi_hw->direct_csr = 30 << QMI_DIRECT_CSR_CLKDIV_LSB | @@ -186,14 +250,7 @@ static void __no_inline_not_in_flash_func(setup_psram)(void) { // Disable direct csr. qmi_hw->direct_csr &= ~(QMI_DIRECT_CSR_ASSERT_CS1N_BITS | QMI_DIRECT_CSR_EN_BITS); - qmi_hw->m[1].timing = - QMI_M0_TIMING_PAGEBREAK_VALUE_1024 << QMI_M0_TIMING_PAGEBREAK_LSB | // Break between pages. - 3 << QMI_M0_TIMING_SELECT_HOLD_LSB | // Delay releasing CS for 3 extra system cycles. - 1 << QMI_M0_TIMING_COOLDOWN_LSB | - 1 << QMI_M0_TIMING_RXDELAY_LSB | - 16 << QMI_M0_TIMING_MAX_SELECT_LSB | // In units of 64 system clock cycles. PSRAM says 8us max. 8 / 0.00752 / 64 = 16.62 - 7 << QMI_M0_TIMING_MIN_DESELECT_LSB | // In units of system clock cycles. PSRAM says 50ns.50 / 7.52 = 6.64 - 2 << QMI_M0_TIMING_CLKDIV_LSB; + mcu_processor_update_psram_timing(sys_clk_khz); qmi_hw->m[1].rfmt = (QMI_M0_RFMT_PREFIX_WIDTH_VALUE_Q << QMI_M0_RFMT_PREFIX_WIDTH_LSB | QMI_M0_RFMT_ADDR_WIDTH_VALUE_Q << QMI_M0_RFMT_ADDR_WIDTH_LSB | QMI_M0_RFMT_SUFFIX_WIDTH_VALUE_Q << QMI_M0_RFMT_SUFFIX_WIDTH_LSB | @@ -245,10 +302,9 @@ static void _port_heap_init(void) { uint32_t *heap_bottom = port_heap_get_bottom(); uint32_t *heap_top = port_heap_get_top(); size_t size = (heap_top - heap_bottom) * sizeof(uint32_t); - _heap = tlsf_create_with_pool(heap_bottom, size, 64 * 1024 * 1024); - _ram_pool = tlsf_get_pool(_heap); + _heap = tlsf_create_with_pool(heap_bottom, size, size); if (_psram_size > 0) { - _psram_pool = tlsf_add_pool(_heap, (void *)0x11000000, _psram_size); + _psram_heap = tlsf_create_with_pool((void *)0x11000000, _psram_size, _psram_size); } } @@ -257,18 +313,57 @@ void port_heap_init(void) { } void *port_malloc(size_t size, bool dma_capable) { + // Prefer internal RAM for everything: it is much faster than PSRAM + // (data there skips the external bus and the shared XIP cache). PSRAM, when + // present, serves as spillover capacity for allocations that don't need DMA. + common_hal_mcu_disable_interrupts(); void *block = tlsf_malloc(_heap, size); + common_hal_mcu_enable_interrupts(); + if (block == NULL && !dma_capable && _psram_size > 0) { + common_hal_mcu_disable_interrupts(); + block = tlsf_malloc(_psram_heap, size); + common_hal_mcu_enable_interrupts(); + } return block; } void port_free(void *ptr) { - tlsf_free(_heap, ptr); + common_hal_mcu_disable_interrupts(); + if (((size_t)ptr) < SRAM_BASE) { + tlsf_free(_psram_heap, ptr); + } else { + tlsf_free(_heap, ptr); + } + common_hal_mcu_enable_interrupts(); } -void *port_realloc(void *ptr, size_t size) { - return tlsf_realloc(_heap, ptr, size); +void *port_realloc(void *ptr, size_t size, bool dma_capable) { + if (ptr == NULL) { + // Fresh allocation: same internal-first policy as port_malloc. + return port_malloc(size, dma_capable); + } + if (_psram_size > 0 && ((size_t)ptr) < SRAM_BASE) { + common_hal_mcu_disable_interrupts(); + void *block = tlsf_realloc(_psram_heap, ptr, size); + common_hal_mcu_enable_interrupts(); + if (block) { + return block; + } + } + common_hal_mcu_disable_interrupts(); + void *new_ptr = tlsf_realloc(_heap, ptr, size); + common_hal_mcu_enable_interrupts(); + return new_ptr; } +#if !CIRCUITPY_ALL_MEMORY_DMA_CAPABLE +bool port_buffer_is_dma_capable(const void *ptr, size_t len) { + // For RP2350, DMA can only access SRAM, not PSRAM + // PSRAM addresses are below SRAM_BASE + return ptr != NULL && ((size_t)ptr) >= SRAM_BASE; +} +#endif + static bool max_size_walker(void *ptr, size_t size, int used, void *user) { size_t *max_size = (size_t *)user; if (!used && *max_size < size) { @@ -279,25 +374,34 @@ static bool max_size_walker(void *ptr, size_t size, int used, void *user) { size_t port_heap_get_largest_free_size(void) { size_t max_size = 0; - tlsf_walk_pool(_ram_pool, max_size_walker, &max_size); - if (_psram_pool != NULL) { - tlsf_walk_pool(_psram_pool, max_size_walker, &max_size); + tlsf_walk_pool(tlsf_get_pool(_heap), max_size_walker, &max_size); + max_size = tlsf_fit_size(_heap, max_size); + if (_psram_heap != NULL) { + tlsf_walk_pool(tlsf_get_pool(_psram_heap), max_size_walker, &max_size); + max_size = tlsf_fit_size(_psram_heap, max_size); } - // IDF does this. Not sure why. - return tlsf_fit_size(_heap, max_size); + return max_size; } safe_mode_t port_init(void) { _binary_info(); + + // Stage 2 left slow flash timing that is safe at any system clock. Switch + // to the fastest flash timing allowed at this clock. Interrupts are off so + // that no interrupt handler reads flash during the change. + common_hal_mcu_disable_interrupts(); + mcu_processor_update_flash_timing(clock_get_hz(clk_sys) / 1000); + common_hal_mcu_enable_interrupts(); + // Set brown out. // Load from the XIP memory space that doesn't cache. That way we don't // evict anything else. The code we're loading is linked to the RAM address // anyway. - #ifdef PICO_RP2040 + #if PICO_RP2040 size_t nocache = 0x03000000; #endif - #ifdef PICO_RP2350 + #if PICO_RP2350 size_t nocache = 0x04000000; #endif @@ -323,13 +427,6 @@ safe_mode_t port_init(void) { // Set up the critical section to protect the background task queue. critical_section_init(&background_queue_lock); - #if CIRCUITPY_CYW43 - never_reset_pin_number(CYW43_DEFAULT_PIN_WL_REG_ON); - never_reset_pin_number(CYW43_DEFAULT_PIN_WL_DATA_IN); - never_reset_pin_number(CYW43_DEFAULT_PIN_WL_CS); - never_reset_pin_number(CYW43_DEFAULT_PIN_WL_CLOCK); - #endif - // Reset everything into a known state before board_init. reset_port(); @@ -338,6 +435,16 @@ safe_mode_t port_init(void) { common_hal_rtc_init(); #endif + // Send-event-on-pend, so the WFE in port_idle_until_interrupt wakes on a + // pending interrupt (as WFI did) in addition to waking on SEV — including + // the SEV core 1 sends via port_wake_main_task() when it queues USB host + // work. + #if PICO_RP2040 + scb_hw->scr |= M0PLUS_SCR_SEVONPEND_BITS; + #else + scb_hw->scr |= M33_SCR_SEVONPEND_BITS; + #endif + // For the tick. hardware_alarm_claim(0); hardware_alarm_set_callback(0, _tick_callback); @@ -379,29 +486,28 @@ safe_mode_t port_init(void) { } void reset_port(void) { - #if CIRCUITPY_BUSIO - reset_spi(); - reset_uart(); - #endif - - #if CIRCUITPY_COUNTIO - reset_countio(); - #endif - - #if CIRCUITPY_RP2PIO - reset_rp2pio_statemachine(); - #endif - #if CIRCUITPY_RTC rtc_reset(); #endif - #if CIRCUITPY_AUDIOCORE - audio_dma_reset(); + #if CIRCUITPY_PICODVI_AUDIOOUT + picodvi_audioout_reset(); #endif #if CIRCUITPY_SSL ssl_reset(); + + // For raspberrypi, we must free PSA crypto, because there are GC-heap objects + // in the key slots. We can't put this call in ssl_reset() because that's a + // shared-module implementation. Unlike raspberrypi, espressif ESP-IDF inits PSA + // once at boot and would never re-init it. + // common_hal_ssl_sslcontext_construct() re-inits PSA on demand. + // So for raspberrypi, we must call mbedtls_psa_crypto_free() explicitly. + mbedtls_psa_crypto_free(); + #endif + + #if CIRCUITPY_RP2_SHA256_HW + rp2_sha256_psa_reset(); #endif #if CIRCUITPY_WATCHDOG @@ -411,8 +517,6 @@ void reset_port(void) { #if CIRCUITPY_WIFI wifi_reset(); #endif - - reset_all_pins(); } void reset_to_bootloader(void) { @@ -421,9 +525,15 @@ void reset_to_bootloader(void) { } } -void reset_cpu(void) { - watchdog_reboot(0, SRAM_END, 0); - watchdog_start_tick(12); +// Called from isr_hardfault(), so this and everything it calls runs from RAM. +// Same register sequence as watchdog_reboot(0, 0, 0), which is in flash. +void __not_in_flash_func(reset_cpu)(void) { + hw_clear_bits(&watchdog_hw->ctrl, WATCHDOG_CTRL_ENABLE_BITS); + watchdog_hw->scratch[4] = 0; + hw_set_bits(&psm_hw->wdsel, PSM_WDSEL_BITS & ~(PSM_WDSEL_ROSC_BITS | PSM_WDSEL_XOSC_BITS)); + hw_clear_bits(&watchdog_hw->ctrl, + WATCHDOG_CTRL_PAUSE_DBG0_BITS | WATCHDOG_CTRL_PAUSE_DBG1_BITS | WATCHDOG_CTRL_PAUSE_JTAG_BITS); + hw_set_bits(&watchdog_hw->ctrl, WATCHDOG_CTRL_TRIGGER_BITS); while (true) { __wfi(); @@ -454,7 +564,7 @@ uint32_t *port_heap_get_top(void) { } uint32_t __uninitialized_ram(saved_word); -void port_set_saved_word(uint32_t value) { +void __not_in_flash_func(port_set_saved_word)(uint32_t value) { // Store in RAM because the watchdog scratch registers don't survive // resetting by pulling the RUN pin low. saved_word = value; @@ -468,11 +578,11 @@ static volatile bool ticks_enabled; static volatile bool _woken_up; uint64_t port_get_raw_ticks(uint8_t *subticks) { - uint64_t microseconds = time_us_64(); + int64_t all_subticks = time_us_64() * 512 / 15625; if (subticks != NULL) { - *subticks = (uint8_t)(((microseconds % 1000000) % 977) / 31); + *subticks = all_subticks % 32; } - return 1024 * (microseconds / 1000000) + (microseconds % 1000000) / 977; + return all_subticks / 32; } static void _tick_callback(uint alarm_num) { @@ -508,7 +618,7 @@ void port_interrupt_after_ticks(uint32_t ticks) { } void port_idle_until_interrupt(void) { - #ifdef PICO_RP2040 + #if PICO_RP2040 common_hal_mcu_disable_interrupts(); #if CIRCUITPY_USB_HOST if (!background_callback_pending() && !tud_task_event_ready() && !tuh_task_event_ready() && !_woken_up) { @@ -516,7 +626,11 @@ void port_idle_until_interrupt(void) { if (!background_callback_pending() && !tud_task_event_ready() && !_woken_up) { #endif __DSB(); - __WFI(); + // WFE, not WFI: the event register is sticky, so a SEV from core 1 + // (port_wake_main_task, e.g. a USB host event) that lands between the + // checks above and here still terminates the wait. Pending interrupts + // wake it too, via SEVONPEND (set in port_init). + __wfe(); } common_hal_mcu_enable_interrupts(); #else @@ -535,7 +649,8 @@ void port_idle_until_interrupt(void) { if (!background_callback_pending() && !tud_task_event_ready() && !_woken_up) { #endif __DSB(); - __WFI(); + // WFE, not WFI: see the RP2040 branch above. + __wfe(); } // and restore basepri before reenabling interrupts @@ -546,10 +661,24 @@ void port_idle_until_interrupt(void) { #endif } +// Called whenever a background callback is queued, including from core 1 +// (which runs the PIO-USB host and posts its events here). SEV is broadcast +// to both cores and latches in the event register, so it reliably ends the +// WFE in port_idle_until_interrupt even if it arrives before the WFE starts. +// Without this, core 0 sleeps through host events for the remainder of a +// time.sleep(): device removal processing and enumeration stall until the +// next unrelated wakeup. +// PLACE_IN_ITCM: core 1 runs with flash execute-never, so this must live in +// RAM like its background_callback_add_core caller (__sev inlines to a bare +// instruction). +void PLACE_IN_ITCM(port_wake_main_task)(void) { + __sev(); +} + /** * \brief Default interrupt handler for unused IRQs. */ -extern void isr_hardfault(void); // provide a prototype to avoid a missing-prototypes diagnostic +extern MP_NORETURN void isr_hardfault(void); // provide a prototype to avoid a missing-prototypes diagnostic __attribute__((used)) void __not_in_flash_func(isr_hardfault)(void) { // Only safe mode from core 0 which is running CircuitPython. Core 1 faulting // should not be fatal to CP. (Fingers crossed.) @@ -561,18 +690,58 @@ __attribute__((used)) void __not_in_flash_func(isr_hardfault)(void) { } } -void port_yield() { +void port_task_yield(void) { #if CIRCUITPY_CYW43 cyw43_arch_poll(); #endif } -void port_boot_info(void) { - #if CIRCUITPY_CYW43 - mp_printf(&mp_plat_print, "MAC"); - for (int i = 0; i < 6; i++) { - mp_printf(&mp_plat_print, ":%02X", cyw43_state.mac[i]); - } - mp_printf(&mp_plat_print, "\n"); +#if CIRCUITPY_BOOT_BUTTON_NO_GPIO +bool __no_inline_not_in_flash_func(port_boot_button_pressed)(void) { + // Sense the state of the boot button. Because this function + // disables flash, it cannot be safely called once the second + // core has been started. When the BOOTSEL button is sensed as + // pressed, return is delayed until the button is released and + // a delay has passed in order to debounce the button. + const uint32_t CS_PIN_INDEX = 1; + #if PICO_RP2040 + const uint32_t CS_BIT = 1u << 1; + #else + const uint32_t CS_BIT = SIO_GPIO_HI_IN_QSPI_CSN_BITS; #endif + uint32_t int_state = save_and_disable_interrupts(); + // Wait for any outstanding XIP activity to finish. Flash + // must be quiescent before disabling the chip select. Since + // there's no XIP busy indication we can test, we delay a + // generous 5 ms to allow any XIP activity to finish. + busy_wait_us(5000); + // Float the flash chip select pin. The line will HI-Z due to + // the external 10K pull-up resistor. + hw_write_masked(&ioqspi_hw->io[CS_PIN_INDEX].ctrl, + GPIO_OVERRIDE_LOW << IO_QSPI_GPIO_QSPI_SS_CTRL_OEOVER_LSB, + IO_QSPI_GPIO_QSPI_SS_CTRL_OEOVER_BITS); + // Delay 100 us to allow the CS line to stabilize. If BOOTSEL is + // pressed, the line will be pulled low by the button and its + // 1K external resistor to ground. + busy_wait_us(100); + bool button_pressed = !(sio_hw->gpio_hi_in & CS_BIT); + // Wait for the button to be released. + if (button_pressed) { + while (!(sio_hw->gpio_hi_in & CS_BIT)) { + tight_loop_contents(); + } + // Wait for 50 ms to debounce the button. + busy_wait_us(50000); + } + // Restore the flash chip select pin to its original state. + hw_write_masked(&ioqspi_hw->io[CS_PIN_INDEX].ctrl, + GPIO_OVERRIDE_NORMAL << IO_QSPI_GPIO_QSPI_SS_CTRL_OEOVER_LSB, + IO_QSPI_GPIO_QSPI_SS_CTRL_OEOVER_BITS); + // Delay 5 ms to allow the flash chip to re-enable and for the + // flash CS pin to stabilize. + busy_wait_us(5000); + // Restore the interrupt state. + restore_interrupts(int_state); + return button_pressed; } +#endif diff --git a/ports/raspberrypi/supervisor/rp2_cpu.s b/ports/raspberrypi/supervisor/rp2_cpu.s deleted file mode 100755 index 741bb21358a..00000000000 --- a/ports/raspberrypi/supervisor/rp2_cpu.s +++ /dev/null @@ -1,35 +0,0 @@ -.syntax unified -.cpu cortex-m0 -.thumb -.text -.align 2 - -@ uint cpu_get_regs_and_sp(r0=uint regs[10]) -.global cpu_get_regs_and_sp -.thumb -.thumb_func -.type cpu_get_regs_and_sp, %function -cpu_get_regs_and_sp: -@ store registers into given array -str r4, [r0, #0] -str r5, [r0, #4] -str r6, [r0, #8] -str r7, [r0, #12] -push {r1} -mov r1, r8 -str r1, [r0, #16] -mov r1, r9 -str r1, [r0, #20] -mov r1, r10 -str r1, [r0, #24] -mov r1, r11 -str r1, [r0, #28] -mov r1, r12 -str r1, [r0, #32] -mov r1, r13 -str r1, [r0, #36] -pop {r1} - -@ return the sp -mov r0, sp -bx lr diff --git a/ports/raspberrypi/supervisor/usb.c b/ports/raspberrypi/supervisor/usb.c index 398f3f448a1..244c5bbce9b 100644 --- a/ports/raspberrypi/supervisor/usb.c +++ b/ports/raspberrypi/supervisor/usb.c @@ -6,14 +6,30 @@ #include "lib/tinyusb/src/device/usbd.h" #include "supervisor/background_callback.h" +#include "supervisor/linker.h" #include "supervisor/usb.h" #include "hardware/irq.h" +#include "hardware/timer.h" #include "pico/platform.h" #include "hardware/regs/intctrl.h" void init_usb_hardware(void) { } +// Override the shared implementation with one that is safe to call from core1. +// TinyUSB's tuh_task_event_ready() calls this, and usb_host polls +// tuh_task_event_ready() from core1's PIO-USB frame loop (see +// common-hal/usb_host/Port.c). tuh_task_event_ready() is deliberately placed in +// RAM by link-rp2*.ld, and everything it calls must be RAM-resident too: on +// RP2350, core1 sets an MPU region that makes flash execute-never, and on +// RP2040 flash may be unavailable while core0 writes to it. time_us_32() is a +// static-inline register read. >>10 yields ~1.024 ms units rather than exact +// milliseconds, which is fine because TinyUSB only uses this API for relative +// delay arithmetic and every use goes through this same function. +uint32_t PLACE_IN_ITCM(tusb_time_millis_api)(void) { + return time_us_32() >> 10; +} + static void _usb_irq_wrapper(void) { usb_irq_handler(0); } diff --git a/ports/renode/Makefile b/ports/renode/Makefile deleted file mode 100644 index 98fe04f4713..00000000000 --- a/ports/renode/Makefile +++ /dev/null @@ -1,110 +0,0 @@ -# This file is part of the CircuitPython project: https://circuitpython.org -# -# SPDX-FileCopyrightText: Copyright (c) 2024 Scott Shawcroft for Adafruit Industries -# -# SPDX-License-Identifier: MIT - -include ../../py/circuitpy_mkenv.mk - -CROSS_COMPILE = arm-none-eabi- - -INC += \ - -I. \ - -I../.. \ - -I../lib/mp-readline \ - -I../shared/timeutils \ - -Iboards/$(BOARD) \ - -Iboards/ \ - -isystem ./../../lib/cmsis/inc \ - -I$(BUILD) - -CFLAGS += -ggdb3 -Os - -DISABLE_WARNINGS = -Wno-cast-align -CFLAGS += $(INC) -Wall -Werror -std=gnu11 -fshort-enums $(BASE_CFLAGS) $(CFLAGS_MOD) $(COPT) $(DISABLE_WARNINGS) -Werror=missing-prototypes - -CFLAGS += \ - -march=armv6-m \ - -mthumb \ - -mabi=aapcs \ - -mcpu=cortex-m0plus \ - -msoft-float \ - -mfloat-abi=soft \ - --specs=nano.specs - -# Use toolchain libm if we're not using our own. -ifndef INTERNAL_LIBM -LIBS += -lm -endif - -LIBS += -lc - -SRC_C += \ - boards/$(BOARD)/board.c \ - boards/$(BOARD)/pins.c \ - background.c \ - mphalport.c \ - - -SRC_COMMON_HAL_EXPANDED = $(addprefix shared-bindings/, $(SRC_COMMON_HAL)) \ - $(addprefix shared-bindings/, $(SRC_BINDINGS_ENUMS)) \ - $(addprefix common-hal/, $(SRC_COMMON_HAL)) - -SRC_SHARED_MODULE_EXPANDED = $(addprefix shared-bindings/, $(SRC_SHARED_MODULE)) \ - $(addprefix shared-module/, $(SRC_SHARED_MODULE)) \ - $(addprefix shared-module/, $(SRC_SHARED_MODULE_INTERNAL)) - -# There may be duplicates between SRC_COMMON_HAL_EXPANDED and SRC_SHARED_MODULE_EXPANDED, -# because a few modules have files both in common-hal/ and shared-module/. -# Doing a $(sort ...) removes duplicates as part of sorting. -SRC_COMMON_HAL_SHARED_MODULE_EXPANDED = $(sort $(SRC_COMMON_HAL_EXPANDED) $(SRC_SHARED_MODULE_EXPANDED)) - -SRC_S = supervisor/$(CPU)_cpu.s - -OBJ = $(PY_O) $(SUPERVISOR_O) $(addprefix $(BUILD)/, $(SRC_C:.c=.o)) -OBJ += $(addprefix $(BUILD)/, $(SRC_COMMON_HAL_SHARED_MODULE_EXPANDED:.c=.o)) -ifeq ($(INTERNAL_LIBM),1) -OBJ += $(addprefix $(BUILD)/, $(SRC_LIBM:.c=.o)) -endif -OBJ += $(addprefix $(BUILD)/, $(SRC_CIRCUITPY_COMMON:.c=.o)) -OBJ += $(addprefix $(BUILD)/, $(SRC_S:.s=.o)) -OBJ += $(addprefix $(BUILD)/, $(SRC_S_UPPER:.S=.o)) -OBJ += $(addprefix $(BUILD)/, $(SRC_MOD:.c=.o)) - -$(BUILD)/%.o: $(BUILD)/%.S - $(STEPECHO) "CC $<" - $(Q)$(CC) $(CFLAGS) -c -o $@ $< - -SRC_QSTR += $(SRC_C) $(SRC_SUPERVISOR) $(SRC_COMMON_HAL_EXPANDED) $(SRC_SHARED_MODULE_EXPANDED) $(SRC_CIRCUITPY_COMMON) - -all: $(BUILD)/firmware.elf $(BUILD)/circuitpy.img - -BOARD_LD := $(wildcard boards/$(BOARD)/link.ld) - -ifneq ($(BOARD_LD),) - LINKER_SCRIPTS = -Wl,-T,$(BOARD_LD) -endif - -LINKER_SCRIPTS += -Wl,-T,link.ld - -$(BUILD)/circuitpy.img: circuitpy/code.py - $(STEPECHO) "Create $@" - $(Q)dd if=/dev/zero of=$(BUILD)/circuitpy.img bs=1 count=0 seek=512K - $(Q)mkfs.fat -n CIRCUITPY --offset=0 $(BUILD)/circuitpy.img - $(Q)mcopy -i $(BUILD)/circuitpy.img circuitpy/* :: - -ifeq ($(VALID_BOARD),) -$(BUILD)/firmware.elf: invalid-board -else -$(BUILD)/firmware.elf: $(OBJ) $(BOARD_LD) link.ld - $(STEPECHO) "LINK $@" - $(Q)echo $(OBJ) > $(BUILD)/firmware.objs - $(Q)echo $(PICO_LDFLAGS) > $(BUILD)/firmware.ldflags - $(Q)$(CC) -o $@ $(CFLAGS) @$(BUILD)/firmware.ldflags $(LINKER_SCRIPTS) -Wl,--print-memory-usage -Wl,-Map=$@.map -Wl,-cref -Wl,--gc-sections @$(BUILD)/firmware.objs -Wl,-lc -endif - -$(BUILD)/firmware.bin: $(BUILD)/firmware.elf - $(STEPECHO) "Create $@" - $(Q)$(OBJCOPY) -O binary -R .dtcm_bss $^ $@ - -include $(TOP)/py/mkrules.mk diff --git a/ports/renode/README.md b/ports/renode/README.md deleted file mode 100644 index 16b6ba6ca4c..00000000000 --- a/ports/renode/README.md +++ /dev/null @@ -1,49 +0,0 @@ -# Renode - -Renode is an emulator targeting microcontroller-class devices. This port is a -minimal version of CircuitPython that runs under Renode. Renode is designed to -mimic full microcontrollers but CP uses more peripherals than what Renode has -implemented so far. This port allows us to run on a variety of CPUs without -worrying about peripherals. - -## Running - -1. Get Renode: https://renode.io/#downloads -2. `cd ports/renode` -3. `make BOARD=renode_cortex_m0plus` -4. In another tab: `tio /tmp/cp-uart` -5. `renode` -6. In renode: `include @renode.resc` -7. -8. `start` -9. `pause` -10. `quit` - -Step 4 sets up `tio` to talk to CircuitPython via UART <-> PTY bridge. - -## Other stuff - -### Emulator logging -Renode modules have debug logging that can be enabled with `logLevel` with an int -between `-1` for `NOISY` and `3` for errors only. - -### GDB - -Renode can provide a GDB server. It is very useful for precisely controlling the -emulator's execution. - -``` -machine StartGdbServer 3333 true -``` - -### Execution profiling - -In renode do `cpu EnableProfiler CollapsedStack $ORIGIN/profile.folded` before starting -the emulation. You can view it using [Speedscope](https://www.speedscope.app/). CircuitPython calls -a lot of functions and may overwhelm speedscope. You can enable this tracing over a specific -section of CircuitPython execution to limit the capture size. - -[Related Renode Docs](https://renode.readthedocs.io/en/latest/advanced/execution-tracing.html) - -### Execution tracing -If you want to see every instruction run you can do: `cpu CreateExecutionTracing "tracer_name" $ORIGIN/instruction_trace.txt Disassembly`. diff --git a/ports/renode/Simple32kHz.cs b/ports/renode/Simple32kHz.cs deleted file mode 100644 index 9c7bc13696e..00000000000 --- a/ports/renode/Simple32kHz.cs +++ /dev/null @@ -1,50 +0,0 @@ -// -// Copyright (c) 2010-2022 Antmicro -// Copyright (c) 2011-2015 Realtime Embedded -// -// This file is licensed under the MIT License. -// Full license text is available in 'licenses/MIT.txt'. -// -// This is modified for CircuitPython to tick at 32kHz like a slow external -// crystal would. -using System; -using Antmicro.Renode.Core; -using Antmicro.Renode.Peripherals.Bus; -using Antmicro.Renode.Time; -using Antmicro.Renode.Logging; -using System.Threading; - -namespace Antmicro.Renode.Peripherals.Timers -{ - public class Simple32kHz : IDoubleWordPeripheral, IKnownSize - { - public long Size { get { return 0x4; } } - - public Simple32kHz(IMachine machine) - { - machine.ClockSource.AddClockEntry(new ClockEntry(1, 32768, OnTick, this, String.Empty)); - } - - public virtual uint ReadDoubleWord(long offset) - { - return (uint)counter; - } - - public virtual void WriteDoubleWord(long offset, uint value) - { - this.LogUnhandledWrite(offset, value); - } - - public virtual void Reset() - { - Interlocked.Exchange(ref counter, 0); - } - - private void OnTick() - { - Interlocked.Increment(ref counter); - } - - private int counter; - } -} diff --git a/ports/renode/background.c b/ports/renode/background.c deleted file mode 100644 index 9493d3cb827..00000000000 --- a/ports/renode/background.c +++ /dev/null @@ -1,19 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "supervisor/port.h" - -void port_start_background_tick(void) { -} - -void port_finish_background_tick(void) { -} - -void port_background_tick(void) { -} - -void port_background_task(void) { -} diff --git a/ports/renode/background.h b/ports/renode/background.h deleted file mode 100644 index 3ff2509eb4a..00000000000 --- a/ports/renode/background.h +++ /dev/null @@ -1,7 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#pragma once diff --git a/ports/renode/boards/peripherals.repl b/ports/renode/boards/peripherals.repl deleted file mode 100644 index 32eddfd1e54..00000000000 --- a/ports/renode/boards/peripherals.repl +++ /dev/null @@ -1,13 +0,0 @@ -flash_firmware: Memory.MappedMemory @ sysbus 0x00000000 - size: 0x80000 // 512k - -flash_filesystem: Memory.MappedMemory @ sysbus 0x10000000 - size: 0x80000 // 512k - -sram: Memory.MappedMemory @ sysbus 0x20000000 - size: 0x20000 // 128k - - -uart: UART.PicoSoC_SimpleUART @ sysbus 0x40000000 - -time: Timers.Simple32kHz @ sysbus 0x40001000 diff --git a/ports/renode/boards/renode_cortex_m0plus/board.repl b/ports/renode/boards/renode_cortex_m0plus/board.repl deleted file mode 100644 index 3917413d541..00000000000 --- a/ports/renode/boards/renode_cortex_m0plus/board.repl +++ /dev/null @@ -1,10 +0,0 @@ -using "../peripherals.repl" - -cpu: CPU.CortexM @ sysbus - cpuType: "cortex-m0" - nvic: nvic - -nvic: IRQControllers.NVIC @ sysbus 0xE000E000 - priorityMask: 0xF0 - systickFrequency: 100000000 - IRQ -> cpu@0 diff --git a/ports/renode/boards/renode_cortex_m0plus/mpconfigboard.h b/ports/renode/boards/renode_cortex_m0plus/mpconfigboard.h deleted file mode 100644 index b09852e5085..00000000000 --- a/ports/renode/boards/renode_cortex_m0plus/mpconfigboard.h +++ /dev/null @@ -1,16 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#pragma once - -#define MICROPY_HW_BOARD_NAME "Renode Cortex-M0+" -#define MICROPY_HW_MCU_NAME "cortex-m0+" - -#define DEFAULT_UART_BUS_RX (&pin_GPIO1) -#define DEFAULT_UART_BUS_TX (&pin_GPIO0) - -#define CIRCUITPY_CONSOLE_UART_TX DEFAULT_UART_BUS_TX -#define CIRCUITPY_CONSOLE_UART_RX DEFAULT_UART_BUS_RX diff --git a/ports/renode/boards/renode_cortex_m0plus/mpconfigboard.mk b/ports/renode/boards/renode_cortex_m0plus/mpconfigboard.mk deleted file mode 100644 index 96431b9e7ee..00000000000 --- a/ports/renode/boards/renode_cortex_m0plus/mpconfigboard.mk +++ /dev/null @@ -1 +0,0 @@ -CPU = cortex-m0+ diff --git a/ports/renode/boards/renode_cortex_m0plus/pins.c b/ports/renode/boards/renode_cortex_m0plus/pins.c deleted file mode 100644 index 121d7e912bf..00000000000 --- a/ports/renode/boards/renode_cortex_m0plus/pins.c +++ /dev/null @@ -1,17 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "shared-bindings/board/__init__.h" - -static const mp_rom_map_elem_t board_module_globals_table[] = { - CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS - - { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_GPIO0) }, - { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_GPIO1) }, - - { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj) }, -}; -MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/renode/circuitpy/code.py b/ports/renode/circuitpy/code.py deleted file mode 100644 index c1d54872a62..00000000000 --- a/ports/renode/circuitpy/code.py +++ /dev/null @@ -1,4 +0,0 @@ -print("hello from renode") - -# This folder gets merged into a FATFS image loaded into renode. Put what you -# want here and run `make BOARD=renode_cortex_m0plus` diff --git a/ports/renode/common-hal/board/__init__.c b/ports/renode/common-hal/board/__init__.c deleted file mode 100644 index 1ff7f0b489f..00000000000 --- a/ports/renode/common-hal/board/__init__.c +++ /dev/null @@ -1,10 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include - -// Pins aren't actually defined here. They are in the board specific directory -// such as boards/arduino_zero/pins.c. diff --git a/ports/renode/common-hal/busio/I2C.c b/ports/renode/common-hal/busio/I2C.c deleted file mode 100644 index c94f63cb880..00000000000 --- a/ports/renode/common-hal/busio/I2C.c +++ /dev/null @@ -1,63 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "shared-bindings/busio/I2C.h" - -#include "py/mperrno.h" -#include "py/runtime.h" - -#define NO_PIN 0xff - -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) { - mp_raise_NotImplementedError(NULL); -} - -bool common_hal_busio_i2c_deinited(busio_i2c_obj_t *self) { - return true; -} - -void common_hal_busio_i2c_deinit(busio_i2c_obj_t *self) { - if (common_hal_busio_i2c_deinited(self)) { - return; - } -} - -bool common_hal_busio_i2c_probe(busio_i2c_obj_t *self, uint8_t addr) { - return false; -} - -bool common_hal_busio_i2c_try_lock(busio_i2c_obj_t *self) { - if (common_hal_busio_i2c_deinited(self)) { - return false; - } - return false; -} - -bool common_hal_busio_i2c_has_lock(busio_i2c_obj_t *self) { - return false; -} - -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) { - return 0; -} - -uint8_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t addr, - uint8_t *data, size_t len) { - return MP_EIO; -} - -uint8_t common_hal_busio_i2c_write_read(busio_i2c_obj_t *self, uint16_t addr, - uint8_t *out_data, size_t out_len, uint8_t *in_data, size_t in_len) { - return MP_EIO; -} - -void common_hal_busio_i2c_never_reset(busio_i2c_obj_t *self) { -} diff --git a/ports/renode/common-hal/busio/I2C.h b/ports/renode/common-hal/busio/I2C.h deleted file mode 100644 index 69048655560..00000000000 --- a/ports/renode/common-hal/busio/I2C.h +++ /dev/null @@ -1,13 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#pragma once - -#include "py/obj.h" - -typedef struct { - mp_obj_base_t base; -} busio_i2c_obj_t; diff --git a/ports/renode/common-hal/busio/SPI.c b/ports/renode/common-hal/busio/SPI.c deleted file mode 100644 index 6f5f6050607..00000000000 --- a/ports/renode/common-hal/busio/SPI.c +++ /dev/null @@ -1,74 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "shared-bindings/busio/SPI.h" - -#include "py/runtime.h" - -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, bool half_duplex) { - mp_raise_NotImplementedError(NULL); -} - -void common_hal_busio_spi_never_reset(busio_spi_obj_t *self) { -} - -bool common_hal_busio_spi_deinited(busio_spi_obj_t *self) { - return true; -} - -void common_hal_busio_spi_deinit(busio_spi_obj_t *self) { - if (common_hal_busio_spi_deinited(self)) { - return; - } -} - -bool common_hal_busio_spi_configure(busio_spi_obj_t *self, - uint32_t baudrate, uint8_t polarity, uint8_t phase, uint8_t bits) { - return true; -} - -bool common_hal_busio_spi_try_lock(busio_spi_obj_t *self) { - if (common_hal_busio_spi_deinited(self)) { - return false; - } - return false; -} - -bool common_hal_busio_spi_has_lock(busio_spi_obj_t *self) { - return false; -} - -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) { - return false; -} - -bool common_hal_busio_spi_read(busio_spi_obj_t *self, - uint8_t *data, size_t len, uint8_t write_value) { - return false; -} - -bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, const uint8_t *data_out, uint8_t *data_in, size_t len) { - return false; -} - -uint32_t common_hal_busio_spi_get_frequency(busio_spi_obj_t *self) { - return 0; -} - -uint8_t common_hal_busio_spi_get_phase(busio_spi_obj_t *self) { - return 0; -} - -uint8_t common_hal_busio_spi_get_polarity(busio_spi_obj_t *self) { - return 0; -} diff --git a/ports/renode/common-hal/busio/SPI.h b/ports/renode/common-hal/busio/SPI.h deleted file mode 100644 index 32e5b0c3866..00000000000 --- a/ports/renode/common-hal/busio/SPI.h +++ /dev/null @@ -1,13 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#pragma once - -#include "py/obj.h" - -typedef struct { - mp_obj_base_t base; -} busio_spi_obj_t; diff --git a/ports/renode/common-hal/busio/UART.c b/ports/renode/common-hal/busio/UART.c deleted file mode 100644 index dc71a982e4b..00000000000 --- a/ports/renode/common-hal/busio/UART.c +++ /dev/null @@ -1,87 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 microDev -// -// SPDX-License-Identifier: MIT - -#include "shared-bindings/busio/UART.h" -#include "py/runtime.h" - -#define RXTX ((volatile uint32_t *)0x40000004) -#define NO_CHAR (0xffffffff) - -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) { - self->pending_char = NO_CHAR; -} - -bool common_hal_busio_uart_deinited(busio_uart_obj_t *self) { - return true; -} - -void common_hal_busio_uart_deinit(busio_uart_obj_t *self) { - if (common_hal_busio_uart_deinited(self)) { - return; - } -} - -// Write characters. -size_t common_hal_busio_uart_write(busio_uart_obj_t *self, const uint8_t *data, size_t len, int *errcode) { - for (size_t i = 0; i < len; i++) { - *RXTX = data[i]; - } - return len; -} - -// Read characters. -size_t common_hal_busio_uart_read(busio_uart_obj_t *self, uint8_t *data, size_t len, int *errcode) { - size_t read = 0; - while (self->pending_char != NO_CHAR && read < len) { - data[read] = self->pending_char; - read++; - self->pending_char = *RXTX; - } - return read; -} - -uint32_t common_hal_busio_uart_get_baudrate(busio_uart_obj_t *self) { - return 0; -} - -void common_hal_busio_uart_set_baudrate(busio_uart_obj_t *self, uint32_t baudrate) { - mp_raise_NotImplementedError(NULL); -} - -mp_float_t common_hal_busio_uart_get_timeout(busio_uart_obj_t *self) { - return 0; -} - -void common_hal_busio_uart_set_timeout(busio_uart_obj_t *self, mp_float_t timeout) { -} - -uint32_t common_hal_busio_uart_rx_characters_available(busio_uart_obj_t *self) { - if (self->pending_char != NO_CHAR) { - return 1; - } - self->pending_char = *RXTX; - if (self->pending_char != NO_CHAR) { - return 1; - } - return 0; -} - -void common_hal_busio_uart_clear_rx_buffer(busio_uart_obj_t *self) { - self->pending_char = NO_CHAR; -} - -bool common_hal_busio_uart_ready_to_tx(busio_uart_obj_t *self) { - return true; -} - -void common_hal_busio_uart_never_reset(busio_uart_obj_t *self) { -} diff --git a/ports/renode/common-hal/busio/UART.h b/ports/renode/common-hal/busio/UART.h deleted file mode 100644 index 6f2619954c6..00000000000 --- a/ports/renode/common-hal/busio/UART.h +++ /dev/null @@ -1,14 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 microDev -// -// SPDX-License-Identifier: MIT - -#pragma once - -#include "py/obj.h" - -typedef struct { - mp_obj_base_t base; - uint32_t pending_char; -} busio_uart_obj_t; diff --git a/ports/renode/common-hal/busio/__init__.c b/ports/renode/common-hal/busio/__init__.c deleted file mode 100644 index b726684324a..00000000000 --- a/ports/renode/common-hal/busio/__init__.c +++ /dev/null @@ -1,7 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2024 Adafruit Industries LLC -// -// SPDX-License-Identifier: MIT - -// No busio module functions. diff --git a/ports/renode/common-hal/microcontroller/Pin.c b/ports/renode/common-hal/microcontroller/Pin.c deleted file mode 100644 index 03903343556..00000000000 --- a/ports/renode/common-hal/microcontroller/Pin.c +++ /dev/null @@ -1,59 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "py/runtime.h" - -#include "shared-bindings/microcontroller/Pin.h" - -void reset_all_pins(void) { -} - -void never_reset_pin_number(uint8_t pin_number) { -} - -void reset_pin_number(uint8_t pin_number) { -} - -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) { - reset_pin_number(pin->number); -} - -void claim_pin(const mcu_pin_obj_t *pin) { -} - -bool pin_number_is_free(uint8_t pin_number) { - return true; -} - -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) { - return pin->number; -} - -void common_hal_mcu_pin_claim(const mcu_pin_obj_t *pin) { - return claim_pin(pin); -} - -void common_hal_mcu_pin_reset_number(uint8_t pin_no) { - reset_pin_number(pin_no); -} - -// 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 \ - } - -PIN(0); -PIN(1); diff --git a/ports/renode/common-hal/microcontroller/Pin.h b/ports/renode/common-hal/microcontroller/Pin.h deleted file mode 100644 index 5e42c5920ac..00000000000 --- a/ports/renode/common-hal/microcontroller/Pin.h +++ /dev/null @@ -1,34 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#pragma once - -#include -#include - -#include - -typedef struct { - mp_obj_base_t base; - uint8_t number; -} mcu_pin_obj_t; - -extern const mcu_pin_obj_t pin_GPIO0; -extern const mcu_pin_obj_t pin_GPIO1; - -// If a board needs a different reset state for one or more pins, implement -// board_reset_pin_number so that it sets this state and returns `true` for those -// pin numbers, `false` for others. -// A default weak implementation always returns `false`. -bool board_reset_pin_number(uint8_t pin_number); - -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_number); -void never_reset_pin_number(uint8_t pin_number); -void claim_pin(const mcu_pin_obj_t *pin); -bool pin_number_is_free(uint8_t pin_number); diff --git a/ports/renode/common-hal/microcontroller/Processor.c b/ports/renode/common-hal/microcontroller/Processor.c deleted file mode 100644 index 3532aa6907a..00000000000 --- a/ports/renode/common-hal/microcontroller/Processor.c +++ /dev/null @@ -1,37 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include -#include - -#include "common-hal/microcontroller/Processor.h" -#include "py/runtime.h" -#include "shared-bindings/microcontroller/Processor.h" -#include "shared-bindings/microcontroller/ResetReason.h" - -float common_hal_mcu_processor_get_temperature(void) { - return NAN; -} - -float common_hal_mcu_processor_get_voltage(void) { - return NAN; -} - -uint32_t common_hal_mcu_processor_get_frequency(void) { - return 100000000; -} - -void common_hal_mcu_processor_set_frequency(mcu_processor_obj_t *self, uint32_t frequency) { - mp_raise_NotImplementedError(NULL); -} - -void common_hal_mcu_processor_get_uid(uint8_t raw_id[]) { - raw_id[0] = 0xaf; -} - -mcu_reset_reason_t common_hal_mcu_processor_get_reset_reason(void) { - return RESET_REASON_POWER_ON; -} diff --git a/ports/renode/common-hal/microcontroller/Processor.h b/ports/renode/common-hal/microcontroller/Processor.h deleted file mode 100644 index 685a452535a..00000000000 --- a/ports/renode/common-hal/microcontroller/Processor.h +++ /dev/null @@ -1,16 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#pragma once - -#define COMMON_HAL_MCU_PROCESSOR_UID_LENGTH 1 - -#include "py/obj.h" - -typedef struct { - mp_obj_base_t base; - // Stores no state currently. -} mcu_processor_obj_t; diff --git a/ports/renode/common-hal/microcontroller/__init__.c b/ports/renode/common-hal/microcontroller/__init__.c deleted file mode 100644 index 47d7f15b825..00000000000 --- a/ports/renode/common-hal/microcontroller/__init__.c +++ /dev/null @@ -1,114 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "py/mphal.h" -#include "py/obj.h" - -#include "common-hal/microcontroller/__init__.h" -#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" - -void common_hal_mcu_delay_us(uint32_t delay) { - mp_hal_delay_us(delay); -} - -volatile uint32_t nesting_count = 0; -void common_hal_mcu_disable_interrupts(void) { - // We don't use save_and_disable_interrupts() from the sdk because we don't want to worry about PRIMASK. - // This is what we do on the SAMD21 via CMSIS. - asm volatile ("cpsid i" : : : "memory"); - // __dmb(); - nesting_count++; -} - -void common_hal_mcu_enable_interrupts(void) { - if (nesting_count == 0) { - // reset_into_safe_mode(SAFE_MODE_INTERRUPT_ERROR); - } - nesting_count--; - if (nesting_count > 0) { - return; - } - // __dmb(); - asm volatile ("cpsie i" : : : "memory"); -} - -static bool next_reset_to_bootloader = false; - -void common_hal_mcu_on_next_reset(mcu_runmode_t runmode) { - switch (runmode) { - case RUNMODE_UF2: - case RUNMODE_BOOTLOADER: - next_reset_to_bootloader = true; - break; - case RUNMODE_SAFE_MODE: - safe_mode_on_next_reset(SAFE_MODE_PROGRAMMATIC); - break; - default: - break; - } -} - -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 -// It currently only has properties, and no state. -#if CIRCUITPY_PROCESSOR_COUNT > 1 -static const mcu_processor_obj_t processor0 = { - .base = { - .type = &mcu_processor_type, - }, -}; - -static const mcu_processor_obj_t processor1 = { - .base = { - .type = &mcu_processor_type, - }, -}; - -const mp_rom_obj_tuple_t common_hal_multi_processor_obj = { - {&mp_type_tuple}, - CIRCUITPY_PROCESSOR_COUNT, - { - MP_ROM_PTR(&processor0), - MP_ROM_PTR(&processor1) - } -}; -#endif - -const mcu_processor_obj_t common_hal_mcu_processor_obj = { - .base = { - .type = &mcu_processor_type, - }, -}; - -// This maps MCU pin names to pin objects. -const mp_rom_map_elem_t mcu_pin_global_dict_table[] = { - { MP_ROM_QSTR(MP_QSTR_GPIO0), MP_ROM_PTR(&pin_GPIO0) }, - { MP_ROM_QSTR(MP_QSTR_GPIO1), MP_ROM_PTR(&pin_GPIO1) }, -}; -MP_DEFINE_CONST_DICT(mcu_pin_globals, mcu_pin_global_dict_table); - -const mcu_pin_obj_t *mcu_get_pin_by_number(int number) { - for (size_t i = 0; i < MP_ARRAY_SIZE(mcu_pin_global_dict_table); i++) { - mcu_pin_obj_t *obj = MP_OBJ_TO_PTR(mcu_pin_global_dict_table[i].value); - if (obj->base.type == &mcu_pin_type && obj->number == number) { - return obj; - } - } - return NULL; -} diff --git a/ports/renode/common-hal/microcontroller/__init__.h b/ports/renode/common-hal/microcontroller/__init__.h deleted file mode 100644 index 82f9558de0a..00000000000 --- a/ports/renode/common-hal/microcontroller/__init__.h +++ /dev/null @@ -1,11 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#pragma once - -#include "shared-bindings/microcontroller/Pin.h" - -const mcu_pin_obj_t *mcu_get_pin_by_number(int); diff --git a/ports/renode/common-hal/os/__init__.c b/ports/renode/common-hal/os/__init__.c deleted file mode 100644 index 14e22960469..00000000000 --- a/ports/renode/common-hal/os/__init__.c +++ /dev/null @@ -1,17 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "genhdr/mpversion.h" -#include "py/mpconfig.h" -#include "py/objstr.h" -#include "py/objtuple.h" -#include "py/qstr.h" - -#include "shared-bindings/os/__init__.h" - -bool common_hal_os_urandom(uint8_t *buffer, mp_uint_t length) { - return false; -} diff --git a/ports/renode/link.ld b/ports/renode/link.ld deleted file mode 100644 index 125c0b0a009..00000000000 --- a/ports/renode/link.ld +++ /dev/null @@ -1,65 +0,0 @@ -MEMORY -{ - FLASH_FIRMWARE (rx) : ORIGIN = 0x00000000, LENGTH = 512k - RAM (rwx) : ORIGIN = 0x20000000, LENGTH = 128k -} - -SECTIONS -{ - .irqs : { - . = ALIGN(4); - KEEP(*(.rodata.interrupt_table .rodata.interrupt_table.*)) - . = ALIGN(4); - } > FLASH_FIRMWARE - - .text : { - *(.text*) - . = ALIGN(4); - } > FLASH_FIRMWARE - - .rodata : { - *(.rodata*) - . = ALIGN(4); - } > FLASH_FIRMWARE - - .ARM.extab : - { - *(.ARM.extab* .gnu.linkonce.armextab.*) - } > FLASH_FIRMWARE - - __exidx_start = .; - .ARM.exidx : - { - *(.ARM.exidx* .gnu.linkonce.armexidx.*) - } > FLASH_FIRMWARE - __exidx_end = .; - - /* End of .text-like segments */ - __etext = .; - - .data : { - __data_start__ = .; - *(.data*) - /* All data end */ - __data_end__ = .; - } > RAM AT> FLASH_FIRMWARE - _ld_ocram_data_destination = ADDR(.data); - _ld_ocram_data_flash_copy = LOADADDR(.data); - _ld_ocram_data_size = SIZEOF(.data); - - /* Uninitialized data section */ - .bss : { - . = ALIGN(4); - __bss_start__ = .; - *(SORT_BY_ALIGNMENT(SORT_BY_NAME(.bss*))) - *(COMMON) - . = ALIGN(4); - __bss_end__ = .; - } > RAM - _ld_ocram_bss_start = ADDR(.bss); - _ld_ocram_bss_size = SIZEOF(.bss); - _ld_heap_start = _ld_ocram_bss_start + _ld_ocram_bss_size; - _ld_ocram_start = ORIGIN(RAM); - _ld_ocram_end = ORIGIN(RAM) + LENGTH(RAM); - _ld_heap_end = _ld_ocram_end; -} diff --git a/ports/renode/mpconfigport.h b/ports/renode/mpconfigport.h deleted file mode 100644 index 185a884ed31..00000000000 --- a/ports/renode/mpconfigport.h +++ /dev/null @@ -1,16 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#pragma once - -#define MICROPY_PY_SYS_PLATFORM "Renode" - -#define MICROPY_USE_INTERNAL_PRINTF (1) - -// This also includes mpconfigboard.h. -#include "py/circuitpy_mpconfig.h" - -#define CIRCUITPY_DEFAULT_STACK_SIZE (24 * 1024) diff --git a/ports/renode/mpconfigport.mk b/ports/renode/mpconfigport.mk deleted file mode 100644 index e2171c5b6c0..00000000000 --- a/ports/renode/mpconfigport.mk +++ /dev/null @@ -1,40 +0,0 @@ -LONGINT_IMPL = MPZ -INTERNAL_LIBM = 1 - -# We build .elf files to run in the simulator. Generally, this will be a file -# type supported by the chip family's bootloader. -CIRCUITPY_BUILD_EXTENSIONS = elf - -# The port manages flash itself instead of using SPI flash via busio.SPI. -INTERNAL_FLASH_FILESYSTEM = 1 - -# Usually lots of flash space available -CIRCUITPY_MESSAGE_COMPRESSION_LEVEL = 1 - -# Disable modules included in full builds -CIRCUITPY_FULL_BUILD = 0 - -# Most ports will want to enable this early to use the USB workflow in testing -# module implementation. It depends on TinyUSB supporting the USB peripheral. -# Renode uses UART instead of USB. -CIRCUITPY_USB_DEVICE = 0 - -# Disable modules included in slim builds directly. Enable these as they are -# implemented. -CIRCUITPY_ANALOGBUFIO = 0 -CIRCUITPY_ANALOGIO = 0 -CIRCUITPY_BUSIO_I2C = 0 -CIRCUITPY_BUSIO_SPI = 0 -CIRCUITPY_DIGITALIO = 0 -CIRCUITPY_NEOPIXEL_WRITE = 0 -CIRCUITPY_NVM = 0 -CIRCUITPY_ONEWIREIO = 0 -CIRCUITPY_PWMIO = 0 -CIRCUITPY_RANDOM = 0 -CIRCUITPY_ROTARYIO = 0 -CIRCUITPY_ROTARYIO_SOFTENCODER = 0 -CIRCUITPY_RTC = 0 -CIRCUITPY_STORAGE = 0 -CIRCUITPY_TOUCHIO = 0 - -CIRCUITPY_BITBANGIO = $(CIRCUITPY_DIGITALIO) diff --git a/ports/renode/mphalport.c b/ports/renode/mphalport.c deleted file mode 100644 index b201420d9bb..00000000000 --- a/ports/renode/mphalport.c +++ /dev/null @@ -1,25 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "py/mphal.h" -#include "shared-bindings/microcontroller/__init__.h" - -#include "mpconfigboard.h" -#include "mphalport.h" - -extern uint32_t common_hal_mcu_processor_get_frequency(void); - -void mp_hal_delay_us(mp_uint_t delay) { - // TODO busy_wait_us_32(delay); -} - -void mp_hal_disable_all_interrupts(void) { - common_hal_mcu_disable_interrupts(); -} - -void mp_hal_enable_all_interrupts(void) { - common_hal_mcu_enable_interrupts(); -} diff --git a/ports/renode/mphalport.h b/ports/renode/mphalport.h deleted file mode 100644 index 802442dbaaf..00000000000 --- a/ports/renode/mphalport.h +++ /dev/null @@ -1,15 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#pragma once - -// Global millisecond tick count (driven by SysTick interrupt). -#define mp_hal_ticks_ms() ((mp_uint_t)supervisor_ticks_ms32()) - -void mp_hal_set_interrupt_char(int c); - -void mp_hal_disable_all_interrupts(void); -void mp_hal_enable_all_interrupts(void); diff --git a/ports/renode/qstrdefsport.h b/ports/renode/qstrdefsport.h deleted file mode 100644 index a754f55f42a..00000000000 --- a/ports/renode/qstrdefsport.h +++ /dev/null @@ -1,9 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2024 Adafruit Industries LLC -// -// SPDX-License-Identifier: MIT - -// Do not use #pragma once in this file; it will cause a warning during qstr generation. - -// qstrs specific to this port diff --git a/ports/renode/renode.resc b/ports/renode/renode.resc deleted file mode 100644 index 11c95e08419..00000000000 --- a/ports/renode/renode.resc +++ /dev/null @@ -1,29 +0,0 @@ -using sysbus - -include @Simple32kHz.cs -emulation CreateUartPtyTerminal "term" "/tmp/cp-uart" - -$board?="renode_cortex_m0plus" -mach create $board - -machine LoadPlatformDescription $ORIGIN/boards/renode_cortex_m0plus/board.repl - -# uart RecordToAsciinema $ORIGIN/build-renode_cortex_m0plus/serial.asciinema -connector Connect sysbus.uart term - -sysbus LoadELF @build-renode_cortex_m0plus/firmware.elf -cpu VectorTableOffset `sysbus GetSymbolAddress "interrupt_table"` - -sysbus LoadBinary @build-renode_cortex_m0plus/circuitpy.img 0x10000000 - -# Enable all debug logging -# logLevel -1 - -# Enable function profiling -# cpu EnableProfiler CollapsedStack $ORIGIN/profile.folded true - -# Enable execution tracing -# cpu CreateExecutionTracing "tracer_name" $ORIGIN/instruction_trace.txt Disassembly - -# Enable the gdb server -# machine StartGdbServer 3333 true diff --git a/ports/renode/supervisor/cortex-m0+_cpu.s b/ports/renode/supervisor/cortex-m0+_cpu.s deleted file mode 100755 index 741bb21358a..00000000000 --- a/ports/renode/supervisor/cortex-m0+_cpu.s +++ /dev/null @@ -1,35 +0,0 @@ -.syntax unified -.cpu cortex-m0 -.thumb -.text -.align 2 - -@ uint cpu_get_regs_and_sp(r0=uint regs[10]) -.global cpu_get_regs_and_sp -.thumb -.thumb_func -.type cpu_get_regs_and_sp, %function -cpu_get_regs_and_sp: -@ store registers into given array -str r4, [r0, #0] -str r5, [r0, #4] -str r6, [r0, #8] -str r7, [r0, #12] -push {r1} -mov r1, r8 -str r1, [r0, #16] -mov r1, r9 -str r1, [r0, #20] -mov r1, r10 -str r1, [r0, #24] -mov r1, r11 -str r1, [r0, #28] -mov r1, r12 -str r1, [r0, #32] -mov r1, r13 -str r1, [r0, #36] -pop {r1} - -@ return the sp -mov r0, sp -bx lr diff --git a/ports/renode/supervisor/internal_flash.c b/ports/renode/supervisor/internal_flash.c deleted file mode 100644 index 028258aee35..00000000000 --- a/ports/renode/supervisor/internal_flash.c +++ /dev/null @@ -1,48 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "supervisor/internal_flash.h" - -#include -#include -#include - -#include "supervisor/flash.h" - -#define FLASH_BASE 0x10000000 -#define FLASH_SIZE 0x80000 - -void supervisor_flash_init(void) { -} - -uint32_t supervisor_flash_get_block_size(void) { - return FILESYSTEM_BLOCK_SIZE; -} - -uint32_t supervisor_flash_get_block_count(void) { - return FLASH_SIZE / FILESYSTEM_BLOCK_SIZE; -} - -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 *)(FLASH_BASE + block * FILESYSTEM_BLOCK_SIZE), - num_blocks * FILESYSTEM_BLOCK_SIZE); - return 0; -} - -mp_uint_t supervisor_flash_write_blocks(const uint8_t *src, uint32_t lba, uint32_t num_blocks) { - memcpy((void *)(FLASH_BASE + lba * FILESYSTEM_BLOCK_SIZE), - src, - num_blocks * FILESYSTEM_BLOCK_SIZE); - - return 0; // success -} - -void supervisor_flash_release_cache(void) { -} diff --git a/ports/renode/supervisor/internal_flash.h b/ports/renode/supervisor/internal_flash.h deleted file mode 100644 index f85b4f7a24b..00000000000 --- a/ports/renode/supervisor/internal_flash.h +++ /dev/null @@ -1,8 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT -#pragma once - -#include diff --git a/ports/renode/supervisor/port.c b/ports/renode/supervisor/port.c deleted file mode 100644 index dae32b7bb8f..00000000000 --- a/ports/renode/supervisor/port.c +++ /dev/null @@ -1,217 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2021 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include -#include -#include - -#include "supervisor/background_callback.h" -#include "supervisor/port.h" - -#include "genhdr/mpversion.h" -#include "shared-bindings/microcontroller/__init__.h" - -#include "supervisor/shared/safe_mode.h" - - -extern uint32_t _ld_flash_size; -extern uint32_t _ld_stack_top; - -extern uint32_t __isr_vector[]; - -extern uint32_t _ld_ocram_start; -extern uint32_t _ld_ocram_bss_start; -extern uint32_t _ld_ocram_bss_size; -extern uint32_t _ld_ocram_data_destination; -extern uint32_t _ld_ocram_data_size; -extern uint32_t _ld_ocram_data_flash_copy; -extern uint32_t _ld_ocram_end; -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; -extern uint32_t _ld_isr_destination; -extern uint32_t _ld_isr_size; -extern uint32_t _ld_isr_flash_copy; - -extern void main(void); - -// This replaces the Reset_Handler in startup_*.S and SystemInit in system_*.c. -// Turn off optimize("no-tree-loop-distribute-patterns") so that this isn't replaced -// by calls to memcpy because we're copying it over now. -void Reset_Handler(void); -__attribute__((used, naked, no_instrument_function, optimize("no-tree-loop-distribute-patterns"))) 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++) { - // (&_ld_itcm_destination)[i] = (&_ld_itcm_flash_copy)[i]; - // } - - // for (uint32_t i = 0; i < ((size_t)&_ld_isr_size) / 4; i++) { - // (&_ld_isr_destination)[i] = (&_ld_isr_flash_copy)[i]; - // } - - // 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]; - // } - - // // Clear DTCM bss. - // 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++) { - (&_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++) { - (&_ld_ocram_bss_start)[i] = 0; - } - - main(); -} - -typedef void (*isr_vector)(void); -const isr_vector __attribute__((used)) interrupt_table[17] = { - (isr_vector) & _ld_ocram_end, - Reset_Handler, - NULL, - NULL, - NULL, - NULL, - NULL, - NULL, - NULL, - NULL, - NULL, - NULL, - NULL, - NULL, - NULL, - NULL, - NULL -}; - -safe_mode_t __attribute__((used)) port_init(void) { - // Reset everything into a known state before board_init. - reset_port(); - - return SAFE_MODE_NONE; -} - -void reset_port(void) { - // Older ports will do blanket resets here. Instead, move to a model that - // uses the deinit() functions to reset internal state. -} - -void reset_to_bootloader(void) { - while (true) { - } -} - -void reset_cpu(void) { - while (true) { - // __wfi(); - } -} - -// From the linker script -extern uint32_t _ld_heap_start; -extern uint32_t _ld_heap_end; -uint32_t *port_stack_get_limit(void) { - #pragma GCC diagnostic push - - #pragma GCC diagnostic ignored "-Warray-bounds" - return port_stack_get_top() - (CIRCUITPY_DEFAULT_STACK_SIZE + CIRCUITPY_EXCEPTION_STACK_SIZE) / sizeof(uint32_t); - #pragma GCC diagnostic pop -} - -uint32_t *port_stack_get_top(void) { - return &_ld_heap_end; -} - -uint32_t *port_heap_get_bottom(void) { - return &_ld_heap_start; -} - -uint32_t *port_heap_get_top(void) { - return port_stack_get_limit(); -} - -uint32_t saved_word; -void port_set_saved_word(uint32_t value) { - // Store in RAM because the watchdog scratch registers don't survive - // resetting by pulling the RUN pin low. - saved_word = value; -} - -uint32_t port_get_saved_word(void) { - return saved_word; -} - -static volatile bool ticks_enabled; -static volatile bool _woken_up; - -uint64_t port_get_raw_ticks(uint8_t *subticks) { - volatile uint32_t *ticks_32khz = ((volatile uint32_t *)0x40001000); - uint32_t total_ticks = *ticks_32khz; - if (subticks != NULL) { - *subticks = total_ticks % 32; - } - return total_ticks / 32; -} - -// Enable 1/1024 second tick. -void port_enable_tick(void) { - ticks_enabled = true; -} - -// Disable 1/1024 second tick. -void port_disable_tick(void) { - // One additional _tick_callback may occur, but it will just return - // whenever !ticks_enabled. Cancel is not called just in case - // it could nuke a timeout set by port_interrupt_after_ticks. - ticks_enabled = false; -} - -// This is called by sleep, we ignore it when our ticks are enabled because -// they'll wake us up earlier. If we don't, we'll mess up ticks by overwriting -// the next RTC wake up time. -void port_interrupt_after_ticks(uint32_t ticks) { - _woken_up = false; -} - -void port_idle_until_interrupt(void) { - common_hal_mcu_disable_interrupts(); - if (!background_callback_pending() && !_woken_up) { - // __DSB(); - // __WFI(); - } - common_hal_mcu_enable_interrupts(); -} - -/** - * \brief Default interrupt handler for unused IRQs. - */ -extern void HardFault_Handler(void); // provide a prototype to avoid a missing-prototypes diagnostic -__attribute__((used)) void HardFault_Handler(void) { - while (true) { - asm ("nop;"); - } -} - -void port_yield() { -} - -void port_boot_info(void) { -} diff --git a/ports/renode/tools/split_profile.py b/ports/renode/tools/split_profile.py deleted file mode 100644 index 3c3ed153ec6..00000000000 --- a/ports/renode/tools/split_profile.py +++ /dev/null @@ -1,24 +0,0 @@ -# Split a profile file into smaller chunks. - -import pathlib -import sys - -input_file = pathlib.Path(sys.argv[-1]) - -supervisor = input_file.with_suffix(".supervisor" + input_file.suffix) -boot_py = input_file.with_suffix(".boot_py" + input_file.suffix) -code_py = input_file.with_suffix(".code_py" + input_file.suffix) - -supervisor_f = supervisor.open("w") -boot_py_f = boot_py.open("w") -code_py_f = code_py.open("w") - -for line in input_file.open(): - if "run_boot_py" in line: - boot_py_f.write(line) - if "run_code_py" in line: - code_py_f.write(line) - -supervisor_f.close() -boot_py_f.close() -code_py_f.close() diff --git a/ports/silabs/Makefile b/ports/silabs/Makefile index 8c7663718e3..8f02e6d94b0 100644 --- a/ports/silabs/Makefile +++ b/ports/silabs/Makefile @@ -71,7 +71,7 @@ ifeq ($(DEBUG), 1) CFLAGS += -fno-inline -fno-ipa-sra -Og else CFLAGS += -DNDEBUG - OPTIMIZATION_FLAGS ?= -Os -fno-inline-functions + OPTIMIZATION_FLAGS ?= -Os CFLAGS += -g endif @@ -90,20 +90,10 @@ ifneq (,$(wildcard boards/$(BOARD)/sensor.c)) SRC_C += boards/$(BOARD)/sensor.c endif -SRC_S = boards/mp_efr32xg24_gchelper.s +AFLAGS = -mcpu=cortex-m33 -mthumb -mfpu=fpv5-sp-d16 -mfloat-abi=hard +SRC_S = shared/runtime/gchelper_thumb1.s -SRC_COMMON_HAL_EXPANDED = $(addprefix shared-bindings/, $(SRC_COMMON_HAL)) \ - $(addprefix shared-bindings/, $(SRC_BINDINGS_ENUMS)) \ - $(addprefix common-hal/, $(SRC_COMMON_HAL)) - -SRC_SHARED_MODULE_EXPANDED = $(addprefix shared-bindings/, $(SRC_SHARED_MODULE)) \ - $(addprefix shared-module/, $(SRC_SHARED_MODULE)) \ - $(addprefix shared-module/, $(SRC_SHARED_MODULE_INTERNAL)) - -# There may be duplicates between SRC_COMMON_HAL_EXPANDED and SRC_SHARED_MODULE_EXPANDED, -# because a few modules have files both in common-hal/ and shared-module/. -# Doing a $(sort ...) removes duplicates as part of sorting. -SRC_COMMON_HAL_SHARED_MODULE_EXPANDED = $(sort $(SRC_COMMON_HAL_EXPANDED) $(SRC_SHARED_MODULE_EXPANDED)) +SRC_C += shared/runtime/gchelper_native.c OBJ += $(PY_O) $(SUPERVISOR_O) $(addprefix $(BUILD)/, $(SRC_C:.c=.o)) OBJ += $(addprefix $(BUILD)/, $(SRC_COMMON_HAL_SHARED_MODULE_EXPANDED:.c=.o)) @@ -118,7 +108,7 @@ $(BUILD)/$(FATFS_DIR)/ff.o: COPT += -Os $(filter $(PY_BUILD)/../extmod/vfs_fat_%.o, $(PY_O)): COPT += -Os # List of sources for qstr extraction -SRC_QSTR += $(SRC_C) $(SRC_SUPERVISOR) $(SRC_MOD) $(SRC_COMMON_HAL_EXPANDED) $(SRC_SHARED_MODULE_EXPANDED) $(SRC_CIRCUITPY_COMMON) +SRC_QSTR += $(SRC_C) $(SRC_SUPERVISOR) $(SRC_MOD) $(SRC_COMMON_HAL_SHARED_MODULE_EXPANDED) $(SRC_CIRCUITPY_COMMON) # Sources that only hold QSTRs after pre-processing. SRC_QSTR_PREPROCESSOR += @@ -144,7 +134,8 @@ $(SILABS_BUILD)/$(PROJECTNAME).Makefile: | $(HEADER_BUILD)/mpversion.h $(OUTPUT_DIR)/firmware.out: $(SILABS_BUILD)/pin_functions.h $(SILABS_BUILD)/pins.c $(OBJ) $(OBJS) $(LIB_FILES) $(STEPECHO) 'Linking $(OUTPUT_DIR)/firmware.out' $(Q)echo "$(OBJS) $(OBJ)" > $(OUTPUT_DIR)/linker_objs - $(Q)$(CC) $(LD_FLAGS) @$(OUTPUT_DIR)/linker_objs -Wl,--print-memory-usage $(LIBS) -o $(OUTPUT_DIR)/firmware.out + $(Q)$(CC) $(LD_FLAGS) @$(OUTPUT_DIR)/linker_objs -Wl,--print-memory-usage -Wl,-Map=$(OUTPUT_DIR)/firmware.out.map $(LIBS) -o $(OUTPUT_DIR)/firmware.out + $(Q)$(PYTHON) $(TOP)/tools/build_memory_info.py $(OUTPUT_DIR)/firmware.out.map $(BUILD) --elf $(OUTPUT_DIR)/firmware.out $(Q)$(OBJCOPY) $(OUTPUT_DIR)/firmware.out -O binary $(OUTPUT_DIR)/firmware.bin flash: $(OUTPUT_DIR)/firmware.bin diff --git a/ports/silabs/boards/devkit_xg24_brd2601b/sensor.c b/ports/silabs/boards/devkit_xg24_brd2601b/sensor.c index aaf698a6cb2..1c991a4caaf 100644 --- a/ports/silabs/boards/devkit_xg24_brd2601b/sensor.c +++ b/ports/silabs/boards/devkit_xg24_brd2601b/sensor.c @@ -75,7 +75,7 @@ static mp_obj_t sensor_init(mp_obj_t i2c_in) { return mp_const_true; } -static mp_obj_t sensor_deinit() { +static mp_obj_t sensor_deinit(void) { sl_sensor_hall_deinit(); sl_sensor_lux_deinit(); diff --git a/ports/silabs/common-hal/_bleio/Adapter.c b/ports/silabs/common-hal/_bleio/Adapter.c index 14b1dac8207..4702555f47d 100644 --- a/ports/silabs/common-hal/_bleio/Adapter.c +++ b/ports/silabs/common-hal/_bleio/Adapter.c @@ -78,31 +78,16 @@ void common_hal_bleio_adapter_set_enabled(bleio_adapter_obj_t *self, bool enabled) { const bool is_enabled = common_hal_bleio_adapter_get_enabled(self); - bd_addr get_address; - uint8_t address_type; uint8_t conn_index; bleio_connection_internal_t *connection; - sl_status_t sc = SL_STATUS_FAIL; - uint8_t device_name[DEVICE_NAME_LEN + 1]; - memset(device_name, 0, DEVICE_NAME_LEN); // Don't enable or disable twice if (is_enabled == enabled) { return; } - sc = sl_bt_system_get_identity_address(&get_address, &address_type); - if (SL_STATUS_OK != sc) { - mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Get address fail.")); - } - snprintf((char *)device_name, DEVICE_NAME_LEN + 1, - "CIRCUITPY-%X%X", get_address.addr[1], get_address.addr[0]); - if (enabled) { - sl_bt_gatt_server_write_attribute_value(gattdb_device_name, - 0, - DEVICE_NAME_LEN, - device_name); + bleio_adapter_reset_name(self); // Clear all of the internal connection objects. for (conn_index = 0; conn_index < BLEIO_TOTAL_CONNECTION_COUNT; conn_index++) { @@ -120,17 +105,17 @@ bleio_address_obj_t *common_hal_bleio_adapter_get_address(bleio_adapter_obj_t *s bd_addr get_address; uint8_t address_type; sl_status_t sc = SL_STATUS_FAIL; - bleio_address_obj_t *address; sc = sl_bt_system_get_identity_address(&get_address, &address_type); if (SL_STATUS_OK != sc) { return NULL; } - address = mp_obj_malloc(bleio_address_obj_t, &bleio_address_type); - common_hal_bleio_address_construct(address, get_address.addr, + // The cached address is refreshed on every call. + common_hal_bleio_address_construct(&self->address, get_address.addr, BLEIO_ADDRESS_TYPE_RANDOM_STATIC); - return address; + self->address.base.type = &bleio_address_type; + return &self->address; } // Set identity address @@ -138,17 +123,13 @@ bool common_hal_bleio_adapter_set_address(bleio_adapter_obj_t *self, bleio_address_obj_t *address) { sl_status_t sc = SL_STATUS_FAIL; - mp_buffer_info_t bufinfo; bd_addr ble_addr; if (NULL == address) { return false; } - if (!mp_get_buffer(address->bytes, &bufinfo, MP_BUFFER_READ)) { - return false; - } - memcpy(ble_addr.addr, bufinfo.buf, 6); - sl_bt_system_set_identity_address(ble_addr, PUBLIC_ADDRESS); + memcpy(ble_addr.addr, address->bytes, 6); + sc = sl_bt_system_set_identity_address(ble_addr, PUBLIC_ADDRESS); return sc == SL_STATUS_OK; } @@ -172,9 +153,13 @@ mp_obj_str_t *common_hal_bleio_adapter_get_name(bleio_adapter_obj_t *self) { // Set name of the BLE adapter void common_hal_bleio_adapter_set_name(bleio_adapter_obj_t *self, const char *name) { + size_t len = strlen(name); + if (len > DEVICE_NAME_LEN) { + len = DEVICE_NAME_LEN; + } sl_bt_gatt_server_write_attribute_value(gattdb_device_name, 0, - DEVICE_NAME_LEN, + len, (const uint8_t *)name); } @@ -453,10 +438,8 @@ bool common_hal_bleio_adapter_get_advertising(bleio_adapter_obj_t *self) { // Convert mac address of remote device to connect static void _convert_address(const bleio_address_obj_t *address, bd_addr *sd_address, uint8_t *addr_type) { - mp_buffer_info_t address_buf_info; *addr_type = address->type; - mp_get_buffer_raise(address->bytes, &address_buf_info, MP_BUFFER_READ); - memcpy(sd_address->addr, (uint8_t *)address_buf_info.buf, 6); + memcpy(sd_address->addr, address->bytes, 6); } // Add new connection into connection list @@ -640,11 +623,11 @@ void bleio_adapter_reset(bleio_adapter_obj_t *adapter) { // Wait up to 125 ms (128 ticks) for disconnect to complete. This should be // greater than most connection intervals. start_ticks = supervisor_ticks_ms64(); - while (any_connected && supervisor_ticks_ms64() - start_ticks < 128) { + do { any_connected = false; for (conn_index = 0; conn_index < BLEIO_TOTAL_CONNECTION_COUNT; conn_index++) { connection = &bleio_connections[conn_index]; any_connected |= connection->conn_handle != BLEIO_HANDLE_INVALID; } - } + } while (any_connected && supervisor_ticks_ms64() - start_ticks < 128); } diff --git a/ports/silabs/common-hal/_bleio/Adapter.h b/ports/silabs/common-hal/_bleio/Adapter.h index d7f252df330..561785bab3f 100644 --- a/ports/silabs/common-hal/_bleio/Adapter.h +++ b/ports/silabs/common-hal/_bleio/Adapter.h @@ -29,6 +29,7 @@ #include "py/obj.h" #include "py/objtuple.h" +#include "shared-bindings/_bleio/Address.h" #include "shared-bindings/_bleio/Connection.h" #include "shared-bindings/_bleio/ScanResults.h" #include "supervisor/background_callback.h" @@ -54,6 +55,10 @@ typedef struct { bool user_advertising; bool is_enable; uint8_t advertising_handle; + // Cached local address returned by common_hal_bleio_adapter_get_address(). + // Stored inline so it never needs to allocate, even when read before the + // heap is available (e.g. from bleio_adapter_reset_name). + bleio_address_obj_t address; } bleio_adapter_obj_t; typedef struct { diff --git a/ports/silabs/common-hal/_bleio/Characteristic.c b/ports/silabs/common-hal/_bleio/Characteristic.c index 37fb792cd4d..9ccc6ad9c36 100644 --- a/ports/silabs/common-hal/_bleio/Characteristic.c +++ b/ports/silabs/common-hal/_bleio/Characteristic.c @@ -249,7 +249,7 @@ size_t common_hal_bleio_characteristic_get_value( return 0; } -// Get max length of charateristic +// Get max length of characteristic size_t common_hal_bleio_characteristic_get_max_length( bleio_characteristic_obj_t *self) { return self->max_length; @@ -373,7 +373,7 @@ void common_hal_bleio_characteristic_add_descriptor( // This indicates the new added descriptor shall be started. sc = sl_bt_gattdb_start_characteristic(gattdb_session, self->handle); if (SL_STATUS_OK != sc) { - mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Start charateristic fail.")); + mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Start characteristic fail.")); return; } @@ -395,7 +395,7 @@ void common_hal_bleio_characteristic_set_cccd(bleio_characteristic_obj_t *self, const uint16_t conn_handle = bleio_connection_get_conn_handle( self->service->connection); - common_hal_bleio_check_connected(conn_handle); + bleio_check_connected(conn_handle); notify = 1; indicate = 0; if (notify) { diff --git a/ports/silabs/common-hal/_bleio/CharacteristicBuffer.c b/ports/silabs/common-hal/_bleio/CharacteristicBuffer.c index 2acb6b00fca..d08fa765c4f 100644 --- a/ports/silabs/common-hal/_bleio/CharacteristicBuffer.c +++ b/ports/silabs/common-hal/_bleio/CharacteristicBuffer.c @@ -87,7 +87,7 @@ void common_hal_bleio_characteristic_buffer_construct( mp_float_t timeout, size_t buffer_size) { - uint8_t *buffer = m_malloc(buffer_size); + uint8_t *buffer = m_malloc_without_collect(buffer_size); _common_hal_bleio_characteristic_buffer_construct(self, characteristic, timeout, @@ -156,7 +156,7 @@ bool common_hal_bleio_characteristic_buffer_connected( common_hal_bleio_connection_get_connected(self->characteristic->service->connection))); } -void reset_characteristic_buffer_list() { +void reset_characteristic_buffer_list(void) { // Remove characteristic_buffer list memset(bleio_characteristic_buffer_list.data, 0, sizeof(bleio_characteristic_buffer_list.data)); diff --git a/ports/silabs/common-hal/_bleio/Connection.c b/ports/silabs/common-hal/_bleio/Connection.c index 94e556dd0bf..4f5da679931 100644 --- a/ports/silabs/common-hal/_bleio/Connection.c +++ b/ports/silabs/common-hal/_bleio/Connection.c @@ -57,6 +57,21 @@ bool common_hal_bleio_connection_get_paired(bleio_connection_obj_t *self) { return self->connection->pair_status == PAIR_PAIRED; } +// Authenticated (MITM-protected) pairing - numeric comparison - is implemented on the +// espressif port only. This port can't tell a "Just Works" bond from an authenticated +// one, so report the conservative answer rather than a guarantee it can't make. +bool common_hal_bleio_connection_get_authenticated(bleio_connection_obj_t *self) { + return false; +} + +mp_obj_t common_hal_bleio_connection_get_numeric_comparison(bleio_connection_obj_t *self) { + return mp_const_none; +} + +void common_hal_bleio_connection_confirm_pairing(bleio_connection_obj_t *self, bool accept) { + mp_raise_NotImplementedError(NULL); +} + // Get connected status bool common_hal_bleio_connection_get_connected(bleio_connection_obj_t *self) { if (self->connection == NULL) { diff --git a/ports/silabs/common-hal/_bleio/Connection.h b/ports/silabs/common-hal/_bleio/Connection.h index 56872024c93..148caecba11 100644 --- a/ports/silabs/common-hal/_bleio/Connection.h +++ b/ports/silabs/common-hal/_bleio/Connection.h @@ -85,6 +85,7 @@ typedef struct void bleio_connection_clear(bleio_connection_internal_t *self); +void bleio_check_connected(uint16_t conn_handle); uint16_t bleio_connection_get_conn_handle(bleio_connection_obj_t *self); mp_obj_t bleio_connection_new_from_internal( diff --git a/ports/silabs/common-hal/_bleio/PacketBuffer.c b/ports/silabs/common-hal/_bleio/PacketBuffer.c index 1e5159fc6a2..291523e0a6d 100644 --- a/ports/silabs/common-hal/_bleio/PacketBuffer.c +++ b/ports/silabs/common-hal/_bleio/PacketBuffer.c @@ -145,7 +145,7 @@ void _common_hal_bleio_packet_buffer_construct( uint32_t *outgoing_buffer1, uint32_t *outgoing_buffer2, size_t max_packet_size, - ble_event_handler_t static_handler_entry) { + ble_event_handler_t *static_handler_entry) { bleio_characteristic_properties_t temp_prop; self->characteristic = characteristic; @@ -223,12 +223,12 @@ void common_hal_bleio_packet_buffer_construct( if (incoming) { incoming_buffer_size = buffer_size * (sizeof(uint16_t) + max_packet_size); - incoming_buffer = m_malloc(incoming_buffer_size); + incoming_buffer = m_malloc_without_collect(incoming_buffer_size); } if (outgoing) { - outgoing1 = m_malloc(max_packet_size); - outgoing2 = m_malloc(max_packet_size); + outgoing1 = m_malloc_without_collect(max_packet_size); + outgoing2 = m_malloc_without_collect(max_packet_size); } _common_hal_bleio_packet_buffer_construct(self, characteristic, incoming_buffer, incoming_buffer_size, @@ -387,11 +387,13 @@ bool common_hal_bleio_packet_buffer_deinited(bleio_packet_buffer_obj_t *self) { void common_hal_bleio_packet_buffer_deinit(bleio_packet_buffer_obj_t *self) { if (!common_hal_bleio_packet_buffer_deinited(self)) { ringbuf_deinit(&self->ringbuf); + // Mark as deinited, so common_hal_bleio_packet_buffer_deinited() reports it. + self->characteristic = NULL; } } // Remove packet_buffer list when reload -void reset_packet_buffer_list() { +void reset_packet_buffer_list(void) { // Remove packet_buffer list memset(bleio_packet_buffer_list.data, 0, sizeof(bleio_packet_buffer_list.data)); diff --git a/ports/silabs/common-hal/_bleio/Service.c b/ports/silabs/common-hal/_bleio/Service.c index 694841e6628..50f0c4593a6 100644 --- a/ports/silabs/common-hal/_bleio/Service.c +++ b/ports/silabs/common-hal/_bleio/Service.c @@ -128,7 +128,7 @@ bleio_uuid_obj_t *common_hal_bleio_service_get_uuid(bleio_service_obj_t *self) { return self->uuid; } -// Get tuple charateristic of service +// Get tuple characteristic of service mp_obj_tuple_t *common_hal_bleio_service_get_characteristics( bleio_service_obj_t *self) { return mp_obj_new_tuple(self->characteristic_list->len, @@ -210,19 +210,19 @@ void common_hal_bleio_service_add_characteristic(bleio_service_obj_t *self, } if (SL_STATUS_OK != sc) { - mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Add charateristic fail.")); + mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Add characteristic fail.")); } sc = sl_bt_gattdb_start_characteristic(gattdb_session, characteristic->handle); if (SL_STATUS_OK != sc) { - mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Start charateristic fail.")); + mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Start characteristic fail.")); return; } sc = sl_bt_gattdb_commit(gattdb_session); if (SL_STATUS_OK != sc) { - mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Commit charateristic fail.")); + mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Commit characteristic fail.")); return; } mp_obj_list_append(self->characteristic_list, @@ -230,7 +230,7 @@ void common_hal_bleio_service_add_characteristic(bleio_service_obj_t *self, } // Remove dynamic service when reload -void reset_dynamic_service() { +void reset_dynamic_service(void) { uint16_t gattdb_session; uint8_t svc_index; diff --git a/ports/silabs/common-hal/_bleio/__init__.c b/ports/silabs/common-hal/_bleio/__init__.c index 2905dc41e09..4c5ce1f045d 100644 --- a/ports/silabs/common-hal/_bleio/__init__.c +++ b/ports/silabs/common-hal/_bleio/__init__.c @@ -54,7 +54,7 @@ const osMutexAttr_t bluetooth_connection_mutex_attr = { void common_hal_bleio_init(void) { } -void bleio_user_reset() { +void bleio_user_reset(void) { // Stop any user scanning or advertising. common_hal_bleio_adapter_stop_scan(&common_hal_bleio_adapter_obj); common_hal_bleio_adapter_stop_advertising(&common_hal_bleio_adapter_obj); @@ -63,7 +63,7 @@ void bleio_user_reset() { supervisor_bluetooth_background(); } -void bleio_reset() { +void bleio_reset(void) { reset_dynamic_service(); reset_packet_buffer_list(); reset_characteristic_buffer_list(); @@ -102,7 +102,7 @@ void check_ble_error(int error_code) { } } -void common_hal_bleio_check_connected(uint16_t conn_handle) { +void bleio_check_connected(uint16_t conn_handle) { if (conn_handle == BLEIO_HANDLE_INVALID) { mp_raise_ConnectionError(MP_ERROR_TEXT("Not connected")); } @@ -194,8 +194,7 @@ void sl_bt_on_event(sl_bt_msg_t *evt) { uuid = m_new_obj_maybe(bleio_uuid_obj_t); if (NULL == uuid) { osMutexRelease(bluetooth_connection_mutex_id); - mp_raise_bleio_BluetoothError( - MP_ERROR_TEXT("Create new service uuid obj fail")); + m_malloc_fail(sizeof(bleio_uuid_obj_t)); break; } uuid->base.type = &bleio_uuid_type; diff --git a/ports/silabs/common-hal/_bleio/__init__.h b/ports/silabs/common-hal/_bleio/__init__.h index 63eda59d84f..4ecd6456b8b 100644 --- a/ports/silabs/common-hal/_bleio/__init__.h +++ b/ports/silabs/common-hal/_bleio/__init__.h @@ -61,12 +61,6 @@ // Maximum length for variable length Attribute Values. #define BLE_GATTS_VAR_ATTR_LEN_MAX (512) -// Track if the user code modified the BLE state -// to know if we need to undo it on reload. -extern bool vm_used_ble; - -// UUID shared by all CCCD's. -extern bleio_uuid_obj_t cccd_uuid; extern void bleio_reset(); extern osMutexId_t bluetooth_connection_mutex_id; diff --git a/ports/silabs/common-hal/analogio/AnalogOut.c b/ports/silabs/common-hal/analogio/AnalogOut.c index f3fd63a32ca..3ae125e850c 100644 --- a/ports/silabs/common-hal/analogio/AnalogOut.c +++ b/ports/silabs/common-hal/analogio/AnalogOut.c @@ -152,15 +152,3 @@ void common_hal_analogio_analogout_set_value(analogio_analogout_obj_t *self, // Write the output value to VDAC DATA register VDAC_ChannelOutputSet(self->dac->vdac, self->dac->channel, value >> 4); } - -// Function reset dac peripheral -void analogout_reset(void) { - uint8_t dac_index; - mcu_dac_pin_obj_t *p_dac; - for (dac_index = 0; dac_index < DAC_BANK_ARRAY_LEN; dac_index++) { - p_dac = &mcu_dac_list[dac_index]; - if (p_dac->is_used == true) { - VDAC_Reset(p_dac->vdac); - } - } -} diff --git a/ports/silabs/common-hal/analogio/AnalogOut.h b/ports/silabs/common-hal/analogio/AnalogOut.h index a8a8e8f9ae3..d5970be477c 100644 --- a/ports/silabs/common-hal/analogio/AnalogOut.h +++ b/ports/silabs/common-hal/analogio/AnalogOut.h @@ -37,6 +37,5 @@ typedef struct mcu_dac_pin_obj_t *dac; } analogio_analogout_obj_t; -void analogout_reset(void); #endif // MICROPY_INCLUDED_EFR32_COMMON_HAL_ANALOGIO_ANALOGOUT_H diff --git a/ports/silabs/common-hal/busio/I2C.c b/ports/silabs/common-hal/busio/I2C.c index ae18f561c50..34b288be746 100644 --- a/ports/silabs/common-hal/busio/I2C.c +++ b/ports/silabs/common-hal/busio/I2C.c @@ -72,12 +72,6 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, } } -// Never reset I2C obj when reload -void common_hal_busio_i2c_never_reset(busio_i2c_obj_t *self) { - common_hal_never_reset_pin(self->sda); - common_hal_never_reset_pin(self->scl); -} - // Check I2C status, deinited or not bool common_hal_busio_i2c_deinited(busio_i2c_obj_t *self) { return self->sda == NULL; @@ -91,7 +85,6 @@ void common_hal_busio_i2c_deinit(busio_i2c_obj_t *self) { I2C_Reset(self->i2cspm); common_hal_reset_pin(self->sda); common_hal_reset_pin(self->scl); - self->i2cspm = NULL; in_used = false; common_hal_busio_i2c_mark_deinit(self); } @@ -145,7 +138,7 @@ void common_hal_busio_i2c_unlock(busio_i2c_obj_t *self) { } // Write data to the device selected by address -uint8_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, +mp_negative_errno_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, const uint8_t *data, size_t len) { I2C_TransferSeq_TypeDef seq; @@ -159,13 +152,13 @@ uint8_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, ret = I2CSPM_Transfer(self->i2cspm, &seq); if (ret != i2cTransferDone) { - return MP_EIO; + return -MP_EIO; } return 0; } // Read into buffer from the device selected by address -uint8_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, +mp_negative_errno_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t addr, uint8_t *data, size_t len) { @@ -180,13 +173,13 @@ uint8_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, ret = I2CSPM_Transfer(self->i2cspm, &seq); if (ret != i2cTransferDone) { - return MP_EIO; + return -MP_EIO; } return 0; } // Write the bytes from out_data to the device selected by address, -uint8_t common_hal_busio_i2c_write_read(busio_i2c_obj_t *self, uint16_t addr, +mp_negative_errno_t common_hal_busio_i2c_write_read(busio_i2c_obj_t *self, uint16_t addr, uint8_t *out_data, size_t out_len, uint8_t *in_data, size_t in_len) { @@ -204,7 +197,7 @@ uint8_t common_hal_busio_i2c_write_read(busio_i2c_obj_t *self, uint16_t addr, ret = I2CSPM_Transfer(self->i2cspm, &seq); if (ret != i2cTransferDone) { - return MP_EIO; + return -MP_EIO; } return 0; } diff --git a/ports/silabs/common-hal/busio/SPI.c b/ports/silabs/common-hal/busio/SPI.c index 74cfc69bfb2..a09ff092f25 100644 --- a/ports/silabs/common-hal/busio/SPI.c +++ b/ports/silabs/common-hal/busio/SPI.c @@ -37,16 +37,6 @@ static SPIDRV_HandleData_t spidrv_eusart_handle; static SPIDRV_Init_t spidrv_eusart_init = SPIDRV_MASTER_EUSART1; static bool in_used = false; -static bool never_reset = false; - -// Reset SPI when reload -void spi_reset(void) { - if (!never_reset && in_used) { - SPIDRV_DeInit(&spidrv_eusart_handle); - in_used = false; - } - return; -} // Construct SPI protocol, this function init SPI peripheral void common_hal_busio_spi_construct(busio_spi_obj_t *self, @@ -61,6 +51,9 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, MP_ERROR_TEXT("Half duplex SPI is not implemented")); } + // Ensure the object starts in its deinit state. + common_hal_busio_spi_mark_deinit(self); + if ((sck != NULL) && (mosi != NULL) && (miso != NULL)) { if (sck->function_list[FN_EUSART1_SCLK] == 1 && miso->function_list[FN_EUSART1_RX] == 1 @@ -106,19 +99,15 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, common_hal_mcu_pin_claim(miso); } -// Never reset SPI when reload -void common_hal_busio_spi_never_reset(busio_spi_obj_t *self) { - never_reset = true; - common_hal_never_reset_pin(self->mosi); - common_hal_never_reset_pin(self->miso); - common_hal_never_reset_pin(self->sck); -} - // Check SPI status, deinited or not bool common_hal_busio_spi_deinited(busio_spi_obj_t *self) { return self->sck == NULL; } +void common_hal_busio_spi_mark_deinit(busio_spi_obj_t *self) { + self->sck = NULL; +} + // Deinit SPI obj void common_hal_busio_spi_deinit(busio_spi_obj_t *self) { @@ -126,19 +115,18 @@ void common_hal_busio_spi_deinit(busio_spi_obj_t *self) { return; } + common_hal_reset_pin(self->mosi); + common_hal_reset_pin(self->miso); + common_hal_reset_pin(self->sck); + Ecode_t sc = SPIDRV_DeInit(self->handle); - if (sc != ECODE_EMDRV_SPIDRV_OK) { - mp_raise_RuntimeError(MP_ERROR_TEXT("SPI re-init")); - } + (void)sc; // Ignore errors: deinit must not raise when run from __del__. in_used = false; - self->sck = NULL; self->mosi = NULL; self->miso = NULL; self->handle = NULL; - common_hal_reset_pin(self->mosi); - common_hal_reset_pin(self->miso); - common_hal_reset_pin(self->sck); + common_hal_busio_spi_mark_deinit(self); } // Configures the SPI bus. The SPI object must be locked. diff --git a/ports/silabs/common-hal/busio/UART.c b/ports/silabs/common-hal/busio/UART.c index cfc87b6b6f8..d0e8695f83a 100644 --- a/ports/silabs/common-hal/busio/UART.c +++ b/ports/silabs/common-hal/busio/UART.c @@ -45,20 +45,9 @@ DEFINE_BUF_QUEUE(UARTDRV_USART_BUFFER_SIZE, uartdrv_usart_tx_buffer); static UARTDRV_HandleData_t uartdrv_usart_handle; static UARTDRV_InitUart_t uartdrv_usart_init; static bool in_used = false; -static bool never_reset = false; busio_uart_obj_t *context; volatile Ecode_t errflag; // Used to restart read halts -// Reset uart peripheral -void uart_reset(void) { - if ((!never_reset) && in_used) { - if (UARTDRV_DeInit(&uartdrv_usart_handle) != ECODE_EMDRV_UARTDRV_OK) { - mp_raise_ValueError(MP_ERROR_TEXT("UART Deinit fail")); - } - in_used = false; - } -} - // Construct uart obj void common_hal_busio_uart_construct(busio_uart_obj_t *self, const mcu_pin_obj_t *tx, @@ -138,14 +127,6 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, } } -// Never reset UART obj when reload -void common_hal_busio_uart_never_reset(busio_uart_obj_t *self) { - never_reset = true; - common_hal_never_reset_pin(self->tx); - common_hal_never_reset_pin(self->rx); - return; -} - // Check Uart status, deinited or not bool common_hal_busio_uart_deinited(busio_uart_obj_t *self) { return self->handle == NULL; diff --git a/ports/silabs/common-hal/busio/UART.h b/ports/silabs/common-hal/busio/UART.h index 50d43d5cd67..a91dda74165 100644 --- a/ports/silabs/common-hal/busio/UART.h +++ b/ports/silabs/common-hal/busio/UART.h @@ -47,6 +47,5 @@ typedef struct { bool sigint_enabled; } busio_uart_obj_t; -void uart_reset(void); #endif // MICROPY_INCLUDED_EFR32_COMMON_HAL_BUSIO_UART_H diff --git a/ports/silabs/common-hal/digitalio/DigitalInOut.c b/ports/silabs/common-hal/digitalio/DigitalInOut.c index e9f2767308e..1f9a20f8fab 100644 --- a/ports/silabs/common-hal/digitalio/DigitalInOut.c +++ b/ports/silabs/common-hal/digitalio/DigitalInOut.c @@ -28,12 +28,6 @@ #include "shared-bindings/microcontroller/Pin.h" #include "py/runtime.h" -// Never reset pin when reload -void common_hal_digitalio_digitalinout_never_reset( - digitalio_digitalinout_obj_t *self) { - common_hal_never_reset_pin(self->pin); -} - // Construct Digitalio obj digitalinout_result_t common_hal_digitalio_digitalinout_construct( digitalio_digitalinout_obj_t *self, const mcu_pin_obj_t *pin) { diff --git a/ports/silabs/common-hal/digitalio/DigitalInOut.h b/ports/silabs/common-hal/digitalio/DigitalInOut.h index 23a5a235378..a69eb48df33 100644 --- a/ports/silabs/common-hal/digitalio/DigitalInOut.h +++ b/ports/silabs/common-hal/digitalio/DigitalInOut.h @@ -1,29 +1,6 @@ /* * This file is part of Adafruit for EFR32 project - * - * The MIT License (MIT) - * - * Copyright 2023 Silicon Laboratories Inc. www.silabs.com - * - * 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_EFR32_COMMON_HAL_DIGITALIO_DIGITALINOUT_H #define MICROPY_INCLUDED_EFR32_COMMON_HAL_DIGITALIO_DIGITALINOUT_H diff --git a/ports/silabs/common-hal/microcontroller/Pin.c b/ports/silabs/common-hal/microcontroller/Pin.c index 249bc5ac482..5b322318e4e 100644 --- a/ports/silabs/common-hal/microcontroller/Pin.c +++ b/ports/silabs/common-hal/microcontroller/Pin.c @@ -33,48 +33,14 @@ GPIO_Port_TypeDef ports[] = {gpioPortA, gpioPortB, gpioPortC, gpioPortD}; static uint16_t claimed_pins[GPIO_PORT_COUNT]; -static uint16_t __ALIGNED(4) never_reset_pins[GPIO_PORT_COUNT]; - -// Reset all pin except pin in never_reset_pins list -void reset_all_pins(void) { - - uint8_t pin_num; - uint8_t port_num; - // Reset claimed pins - for (pin_num = 0; pin_num < GPIO_PORT_COUNT; pin_num++) { - claimed_pins[pin_num] = never_reset_pins[pin_num]; - } - - for (port_num = 0; port_num < GPIO_PORT_COUNT; port_num++) { - for (pin_num = 0; pin_num < 16; pin_num++) { - if (GPIO_PORT_PIN_VALID(ports[port_num], pin_num) - && !(never_reset_pins[port_num] >> pin_num & 0x01)) { - GPIO_PinModeSet(ports[port_num], pin_num, gpioModeInput, 1); - } - } - } -} // Mark pin as free and return it to a quiescent state. void reset_pin_number(uint8_t pin_port, uint8_t pin_number) { // Clear claimed bit & reset claimed_pins[pin_port] &= ~(1 << pin_number); - never_reset_pins[pin_port] &= ~(1 << pin_number); GPIO_PinModeSet(pin_port, pin_number, gpioModeInput, 1); } -// Mark pin as never reset -void never_reset_pin_number(uint8_t pin_port, uint8_t pin_number) { - never_reset_pins[pin_port] |= 1 << pin_number; - // Make sure never reset pins are also always claimed - claimed_pins[pin_port] |= 1 << pin_number; -} - -// Mark pin as never reset -void common_hal_never_reset_pin(const mcu_pin_obj_t *pin) { - never_reset_pin_number(pin->port, pin->number); -} - // Reset pin void common_hal_reset_pin(const mcu_pin_obj_t *pin) { if (pin == NULL) { diff --git a/ports/silabs/common-hal/microcontroller/Pin.h b/ports/silabs/common-hal/microcontroller/Pin.h index 20bf8a82f2b..4c868a2d09b 100644 --- a/ports/silabs/common-hal/microcontroller/Pin.h +++ b/ports/silabs/common-hal/microcontroller/Pin.h @@ -31,6 +31,9 @@ #include "peripherals/pins.h" -void reset_all_pins(void); +void common_hal_reset_pin(const mcu_pin_obj_t *pin); + +uint8_t common_hal_mcu_pin_number(const mcu_pin_obj_t *pin); +void common_hal_mcu_pin_claim(const mcu_pin_obj_t *pin); #endif // MICROPY_INCLUDED_EFR32_COMMON_HAL_MICROCONTROLLER_PIN_H diff --git a/ports/silabs/common-hal/microcontroller/Processor.c b/ports/silabs/common-hal/microcontroller/Processor.c index 226fe4529fb..741a147d1cf 100644 --- a/ports/silabs/common-hal/microcontroller/Processor.c +++ b/ports/silabs/common-hal/microcontroller/Processor.c @@ -62,5 +62,5 @@ void common_hal_mcu_processor_get_uid(uint8_t raw_id[]) { } mcu_reset_reason_t common_hal_mcu_processor_get_reset_reason(void) { - return RESET_REASON_UNKNOWN; + return MCU_RESET_REASON_UNKNOWN; } diff --git a/ports/silabs/common-hal/microcontroller/__init__.c b/ports/silabs/common-hal/microcontroller/__init__.c index b1472fcf437..7244af6619d 100644 --- a/ports/silabs/common-hal/microcontroller/__init__.c +++ b/ports/silabs/common-hal/microcontroller/__init__.c @@ -60,6 +60,9 @@ void common_hal_mcu_on_next_reset(mcu_runmode_t runmode) { } } +// CHIP_Reset does not return, but is not declared as such in the SDK. +void __attribute__ ((noreturn)) CHIP_Reset(void); + void common_hal_mcu_reset(void) { filesystem_flush(); // TODO: implement as part of flash improvements CHIP_Reset(); diff --git a/ports/silabs/common-hal/pwmio/PWMOut.c b/ports/silabs/common-hal/pwmio/PWMOut.c index 495199360f7..844b8966a00 100644 --- a/ports/silabs/common-hal/pwmio/PWMOut.c +++ b/ports/silabs/common-hal/pwmio/PWMOut.c @@ -88,15 +88,6 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t *self, return PWMOUT_OK; } -// Mark pwm obj to never reset after reload -void common_hal_pwmio_pwmout_never_reset(pwmio_pwmout_obj_t *self) { - common_hal_never_reset_pin(self->tim->pin); -} - -// Pwm will be reset after reloading. -void common_hal_pwmio_pwmout_reset_ok(pwmio_pwmout_obj_t *self) { -} - // Check pwm obj status, deinited or not bool common_hal_pwmio_pwmout_deinited(pwmio_pwmout_obj_t *self) { return self->tim == NULL; diff --git a/ports/silabs/common-hal/rtc/RTC.h b/ports/silabs/common-hal/rtc/RTC.h index 12683a310a7..ac18a68dd63 100644 --- a/ports/silabs/common-hal/rtc/RTC.h +++ b/ports/silabs/common-hal/rtc/RTC.h @@ -28,6 +28,5 @@ #define MICROPY_INCLUDED_STM_COMMON_HAL_RTC_RTC_H extern void rtc_init(void); -extern void rtc_reset(void); #endif // MICROPY_INCLUDED_STM_COMMON_HAL_RTC_RTC_H diff --git a/ports/silabs/common-hal/watchdog/WatchDogTimer.c b/ports/silabs/common-hal/watchdog/WatchDogTimer.c index ee25491f6ae..67da1b02645 100644 --- a/ports/silabs/common-hal/watchdog/WatchDogTimer.c +++ b/ports/silabs/common-hal/watchdog/WatchDogTimer.c @@ -39,7 +39,7 @@ void common_hal_watchdog_feed(watchdog_watchdogtimer_obj_t *self) { WDOGn_Feed(DEFAULT_WDOG); } -void common_hal_watchdog_deinit(watchdog_watchdogtimer_obj_t *self) { +void common_hal_watchdog_reset(watchdog_watchdogtimer_obj_t *self) { if (!_wdt_init) { return; } @@ -129,7 +129,7 @@ void common_hal_watchdog_set_mode(watchdog_watchdogtimer_obj_t *self, MP_ERROR_TEXT("RAISE mode is not implemented")); } else if (new_mode == WATCHDOGMODE_NONE) { self->mode = WATCHDOGMODE_NONE; - common_hal_watchdog_deinit(self); + common_hal_watchdog_reset(self); } self->mode = new_mode; common_hal_watchdog_set_timeout(self, self->timeout); diff --git a/ports/silabs/mpconfigport.mk b/ports/silabs/mpconfigport.mk index 10a7a0858eb..7192be3f415 100644 --- a/ports/silabs/mpconfigport.mk +++ b/ports/silabs/mpconfigport.mk @@ -3,7 +3,7 @@ INTERNAL_LIBM ?= 1 USB_NUM_ENDPOINT_PAIRS = 0 CIRCUITPY_ANALOGIO ?= 1 -CIRCUITPY_BLEIO ?= 1 +CIRCUITPY_BLEIO_NATIVE ?= 1 CIRCUITPY_BUSDEVICE ?= 1 CIRCUITPY_BUSIO ?= 1 CIRCUITPY_DIGITALIO ?= 1 diff --git a/ports/silabs/supervisor/port.c b/ports/silabs/supervisor/port.c index 2409e907dea..efca79bdcaa 100644 --- a/ports/silabs/supervisor/port.c +++ b/ports/silabs/supervisor/port.c @@ -156,17 +156,6 @@ safe_mode_t port_init(void) { } void reset_port(void) { - reset_all_pins(); - - #if CIRCUITPY_BUSIO - spi_reset(); - uart_reset(); - #endif - - #if CIRCUITPY_ANALOGIO - analogout_reset(); - #endif - #if CIRCUITPY_BLEIO bleio_reset(); #endif diff --git a/ports/silabs/supervisor/serial.c b/ports/silabs/supervisor/serial.c index 25dc86c1da9..24d2c3b172e 100644 --- a/ports/silabs/supervisor/serial.c +++ b/ports/silabs/supervisor/serial.c @@ -102,11 +102,9 @@ void port_serial_early_init(void) { EUSART_UartInitHf(EUSART0, &init); - // Claim and never reset UART console pin + // Claim UART console pins common_hal_mcu_pin_claim(&pin_PA5); common_hal_mcu_pin_claim(&pin_PA6); - common_hal_never_reset_pin(&pin_PA5); - common_hal_never_reset_pin(&pin_PA6); } // Enable EUSART0 interrupt, init ring buffer diff --git a/ports/stm/Makefile b/ports/stm/Makefile index ec5ba752d41..e02059afe2b 100755 --- a/ports/stm/Makefile +++ b/ports/stm/Makefile @@ -38,8 +38,7 @@ ifeq ($(DEBUG), 1) CFLAGS += -fno-inline -fno-ipa-sra else CFLAGS += -DNDEBUG - OPTIMIZATION_FLAGS ?= -O2 -fno-inline-functions - CFLAGS += -ggdb3 + OPTIMIZATION_FLAGS ?= -O2 endif # to override compiler optimization level, set in boards/$(BOARD)/mpconfigboard.mk @@ -51,7 +50,7 @@ CFLAGS += -ftree-vrp # STM32 MCU series must be defined. See supervisor/linker.h C_DEFS = -D$(MCU_PACKAGE) -DUSE_HAL_DRIVER -DUSE_FULL_LL_DRIVER -D$(MCU_VARIANT) -DSTM32$(MCU_SERIES) -CFLAGS += $(INC) -Werror -Wall -std=gnu11 -fshort-enums $(BASE_CFLAGS) $(C_DEFS) $(CFLAGS_MOD) $(COPT) -nostdlib -nostartfiles +CFLAGS += $(INC) -Werror -Wall -std=gnu11 -fshort-enums $(BASE_CFLAGS) $(C_DEFS) $(CFLAGS_MOD) $(COPT) -nostdlib -nostartfiles -Werror=old-style-definition # Undo some warnings. # STM32 HAL uses undefined preprocessor variables, shadowed variables, casts that change alignment reqs @@ -165,10 +164,17 @@ endif # Need this to avoid UART linker problems. TODO: rewrite to use registered callbacks. # Does not exist for F4 and lower -ifeq ($(MCU_VARIANT),$(filter $(MCU_VARIANT),STM32F765xx STM32F767xx STM32F769xx STM32H743xx STM32H750xx STM32L4R5xx)) +ifeq ($(MCU_VARIANT),$(filter $(MCU_VARIANT),STM32F765xx STM32F767xx STM32F769xx STM32H743xx STM32H750xx STM32L4R5xx STM32L433xx)) SRC_STM32 += $(HAL_DIR)/Src/stm32$(MCU_SERIES_LOWER)xx_hal_uart_ex.c endif +ifeq ($(MCU_VARIANT),$(filter $(MCU_VARIANT),STM32H750xx)) + C_DEFS += -DHAL_SDRAM_MODULE_ENABLED + SRC_STM32 += st_driver/stm32$(MCU_SERIES_LOWER)xx_hal_driver/Src/stm32h7xx_hal_sdram.c + SRC_STM32 += st_driver/stm32$(MCU_SERIES_LOWER)xx_hal_driver/Src/stm32h7xx_ll_fmc.c + SRC_C += peripherals/sdram.c +endif + SRC_STM32 += boards/system_stm32$(MCU_SERIES_LOWER)xx.c SRC_C += \ @@ -197,23 +203,20 @@ ifneq ($(CIRCUITPY_AUDIOBUSIO_PDMIN),0) endif ifneq ($(CIRCUITPY_USB),0) -SRC_C += \ - lib/tinyusb/src/portable/synopsys/dwc2/dcd_dwc2.c \ - lib/tinyusb/src/portable/synopsys/dwc2/dwc2_common.c + ifeq ($(MCU_VARIANT),$(filter $(MCU_VARIANT),STM32L433xx)) + SRC_C += lib/tinyusb/src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c + SRC_C += lib/tinyusb/src/portable/st/stm32_fsdev/fsdev_common.c + else + SRC_C += lib/tinyusb/src/portable/synopsys/dwc2/dcd_dwc2.c + SRC_C += lib/tinyusb/src/portable/synopsys/dwc2/dwc2_common.c + endif endif SRC_S = \ - supervisor/cpu.s \ + shared/runtime/gchelper_thumb1.s \ st_driver/cmsis_device_$(MCU_SERIES_LOWER)/Source/Templates/gcc/startup_$(MCU_VARIANT_LOWER).s -SRC_COMMON_HAL_EXPANDED = $(addprefix shared-bindings/, $(SRC_COMMON_HAL)) \ - $(addprefix shared-bindings/, $(SRC_BINDINGS_ENUMS)) \ - $(addprefix common-hal/, $(SRC_COMMON_HAL)) - -SRC_SHARED_MODULE_EXPANDED = $(addprefix shared-bindings/, $(SRC_SHARED_MODULE)) \ - $(addprefix shared-module/, $(SRC_SHARED_MODULE)) \ - $(addprefix shared-module/, $(SRC_SHARED_MODULE_INTERNAL)) - +SRC_C += shared/runtime/gchelper_native.c ifneq ($(FROZEN_MPY_DIR),) FROZEN_MPY_PY_FILES := $(shell find -L $(FROZEN_MPY_DIR) -type f -name '*.py') @@ -222,8 +225,7 @@ endif OBJ += $(PY_O) $(SUPERVISOR_O) $(addprefix $(BUILD)/, $(SRC_C:.c=.o)) OBJ += $(addprefix $(BUILD)/, $(SRC_STM32:.c=.o)) -OBJ += $(addprefix $(BUILD)/, $(SRC_COMMON_HAL_EXPANDED:.c=.o)) -OBJ += $(addprefix $(BUILD)/, $(SRC_SHARED_MODULE_EXPANDED:.c=.o)) +OBJ += $(addprefix $(BUILD)/, $(SRC_COMMON_HAL_SHARED_MODULE_EXPANDED:.c=.o)) ifeq ($(INTERNAL_LIBM),1) OBJ += $(addprefix $(BUILD)/, $(SRC_LIBM:.c=.o)) endif @@ -235,7 +237,7 @@ $(BUILD)/$(FATFS_DIR)/ff.o: COPT += -Os $(filter $(PY_BUILD)/../extmod/vfs_fat_%.o, $(PY_O)): COPT += -Os # List of sources for qstr extraction -SRC_QSTR += $(SRC_C) $(SRC_SUPERVISOR) $(SRC_MOD) $(SRC_COMMON_HAL_EXPANDED) $(SRC_SHARED_MODULE_EXPANDED) $(SRC_CIRCUITPY_COMMON) +SRC_QSTR += $(SRC_C) $(SRC_SUPERVISOR) $(SRC_MOD) $(SRC_COMMON_HAL_SHARED_MODULE_EXPANDED) $(SRC_CIRCUITPY_COMMON) # Sources that only hold QSTRs after pre-processing. SRC_QSTR_PREPROCESSOR += @@ -255,7 +257,7 @@ $(BUILD)/firmware.elf: $(OBJ) $(STEPECHO) "LINK $@" $(Q)echo $^ > $(BUILD)/firmware.objs $(Q)$(CC) -o $@ $(LDFLAGS) @$(BUILD)/firmware.objs -Wl,--print-memory-usage -Wl,--start-group $(LIBS) -Wl,--end-group - $(Q)$(SIZE) $@ | $(PYTHON) $(TOP)/tools/build_memory_info.py $(LD_FILE) $(BUILD) + $(Q)$(PYTHON) $(TOP)/tools/build_memory_info.py $@.map $(BUILD) --elf $@ endif $(BUILD)/firmware.bin: $(BUILD)/firmware.elf diff --git a/ports/stm/boards/STM32L433_boot.ld b/ports/stm/boards/STM32L433_boot.ld new file mode 100644 index 00000000000..686547a8ce6 --- /dev/null +++ b/ports/stm/boards/STM32L433_boot.ld @@ -0,0 +1,27 @@ +/* + GNU linker script for STM32L433 with bootloader +*/ + +/* Specify the memory areas */ +MEMORY +{ + FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 256k /* entire flash */ + FLASH_ISR (rx) : ORIGIN = 0x08010000, LENGTH = 4K /* ISR vector. Kind of wasteful. */ + FLASH_FIRMWARE (rx) : ORIGIN = 0x08011000, LENGTH = 192K-64K-4K + FLASH_FS (rw) : ORIGIN = 0x08030000, LENGTH = 60K + RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 640K +} + + +/* produce a link error if there is not this amount of RAM for these sections */ +_minimum_stack_size = 24K; +_minimum_heap_size = 16K; + +/* Define the top end of the stack. The stack is full descending so begins just + above last byte of RAM. Note that EABI requires the stack to be 8-byte + aligned for a call. */ +_estack = ORIGIN(RAM) + LENGTH(RAM); + +/* RAM extents for the garbage collector */ +_ram_start = ORIGIN(RAM); +_ram_end = ORIGIN(RAM) + LENGTH(RAM); diff --git a/ports/stm/boards/STM32L433_default.ld b/ports/stm/boards/STM32L433_default.ld new file mode 100644 index 00000000000..886a1b8827a --- /dev/null +++ b/ports/stm/boards/STM32L433_default.ld @@ -0,0 +1,29 @@ +/* + GNU linker script for STM32L433 with filesystem +*/ + +/* Specify the memory areas */ +MEMORY +{ + FLASH (rx) : ORIGIN = 0x08000000, LENGTH = 256K /* entire flash */ + FLASH_ISR (rx) : ORIGIN = 0x08000000, LENGTH = 16K /* ISR vector. */ + FLASH_FS (rw) : ORIGIN = 0x08004000, LENGTH = 48K + FLASH_FIRMWARE (rx) : ORIGIN = 0x08010000, LENGTH = 256K - 48K - 16K + RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 64K +} + +/* produce a link error if there is not this amount of RAM for these sections */ +_minimum_stack_size = 24K; +_minimum_heap_size = 16K; + +/* Define the top end of the stack. The stack is full descending so begins just + above last byte of RAM. Note that EABI requires the stack to be 8-byte + aligned for a call. */ +_estack = ORIGIN(RAM) + LENGTH(RAM); + +/* RAM extents for the garbage collector */ +_ram_start = ORIGIN(RAM); +_ram_end = ORIGIN(RAM) + LENGTH(RAM); + +/* ensure the firmware is within bounds */ +ASSERT ( (ORIGIN(FLASH_FIRMWARE) + LENGTH(FLASH_FIRMWARE)) <= (ORIGIN(FLASH)+LENGTH(FLASH)), "FLASH_FIRMWARE out of bounds" ); diff --git a/ports/stm/boards/blues_cygnet/board.c b/ports/stm/boards/blues_cygnet/board.c new file mode 100644 index 00000000000..eddebad3f5d --- /dev/null +++ b/ports/stm/boards/blues_cygnet/board.c @@ -0,0 +1,77 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2017 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "supervisor/board.h" +#include "mpconfigboard.h" + +#include "stm32l4xx.h" +#include "stm32l433xx.h" + +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/digitalio/DigitalInOut.h" +#include "shared-bindings/digitalio/Direction.h" +#include "shared-bindings/digitalio/DriveMode.h" +#include "board.h" + +digitalio_digitalinout_obj_t power_pin = { .base.type = &digitalio_digitalinout_type }; +digitalio_digitalinout_obj_t discharge_pin = { .base.type = &digitalio_digitalinout_type }; + +void initialize_discharge_pin(void) { + /* Initialize the 3V3 discharge to be OFF and the output power to be ON */ + __HAL_RCC_GPIOA_CLK_ENABLE(); + __HAL_RCC_GPIOH_CLK_ENABLE(); + __HAL_RCC_GPIOB_CLK_ENABLE(); + + common_hal_digitalio_digitalinout_construct(&power_pin, &pin_PH00); + common_hal_digitalio_digitalinout_construct(&discharge_pin, &pin_PH01); + + GPIO_InitTypeDef GPIO_InitStruct; + + /* Set DISCHARGE_3V3 as well as the pins we're not initially using to FLOAT */ + GPIO_InitStruct.Mode = GPIO_MODE_ANALOG; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Pin = GPIO_PIN_1; + HAL_GPIO_Init(GPIOH, &GPIO_InitStruct); /* PH1 DISCHARGE_3V3 */ + GPIO_InitStruct.Pin = GPIO_PIN_3; + HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); /* PB3 is USB_DETECT */ + GPIO_InitStruct.Pin = GPIO_PIN_15; + HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /* PA15 is CHARGE_DETECT */ + GPIO_InitStruct.Pin = GPIO_PIN_4; + HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); /* PA4 is BAT_VOLTAGE */ + + /* Turn on the 3V3 regulator */ + GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; + GPIO_InitStruct.Speed = GPIO_SPEED_LOW; + GPIO_InitStruct.Pin = GPIO_PIN_0; + HAL_GPIO_Init(GPIOH, &GPIO_InitStruct); + HAL_GPIO_WritePin(GPIOH, GPIO_InitStruct.Pin, GPIO_PIN_SET); +} + +void board_init(void) { + // enable the debugger while sleeping. Todo move somewhere more central (kind of generally useful in a debug build) + SET_BIT(DBGMCU->CR, DBGMCU_CR_DBG_SLEEP); + + // Set tick interrupt priority, default HAL value is intentionally invalid + // Without this, USB does not function. + HAL_InitTick((1UL << __NVIC_PRIO_BITS) - 1UL); + + __HAL_RCC_GPIOA_CLK_ENABLE(); + GPIO_InitTypeDef GPIO_InitStruct; + GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Speed = GPIO_SPEED_LOW; + GPIO_InitStruct.Pin = GPIO_PIN_8; + HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); + HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, GPIO_PIN_SET); + HAL_Delay(50); + HAL_GPIO_WritePin(GPIOA, GPIO_PIN_8, GPIO_PIN_RESET); +} + +void reset_board(void) { + initialize_discharge_pin(); +} + +// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/stm/boards/blues_cygnet/board.h b/ports/stm/boards/blues_cygnet/board.h new file mode 100644 index 00000000000..ce199359ba4 --- /dev/null +++ b/ports/stm/boards/blues_cygnet/board.h @@ -0,0 +1,12 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2017 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "common-hal/digitalio/DigitalInOut.h" + +extern digitalio_digitalinout_obj_t power_pin; +extern digitalio_digitalinout_obj_t discharge_pin; diff --git a/ports/stm/boards/blues_cygnet/mpconfigboard.h b/ports/stm/boards/blues_cygnet/mpconfigboard.h new file mode 100644 index 00000000000..f3b1fcc2eb7 --- /dev/null +++ b/ports/stm/boards/blues_cygnet/mpconfigboard.h @@ -0,0 +1,47 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Blues Wireless Contributors. +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Micropython setup + +#define MICROPY_HW_BOARD_NAME "Cygnet" +#define MICROPY_HW_MCU_NAME "STM32L433CCT6" + +#define MICROPY_PY_SYS_PLATFORM MICROPY_HW_BOARD_NAME + +#define STM32L433XX +#define BOARD_CYGNET + +#define LSE_VALUE ((uint32_t)32768) +#define BOARD_HAS_LOW_SPEED_CRYSTAL (1) +#define BOARD_HAS_HIGH_SPEED_CRYSTAL (0) + +// Increase drive strength of 32kHz external crystal, in line with calculations specified in ST AN2867 sections 3.3, 3.4, and STM32L4 datasheet DS12023 Table 58. LSE oscillator characteristics. +// The drive strength RCC_LSEDRIVE_LOW is marginal for the 32kHz crystal oscillator stability, and RCC_LSEDRIVE_MEDIUMLOW meets the calculated drive strength with a small margin for parasitic capacitance. +#define BOARD_LSE_DRIVE_LEVEL RCC_LSEDRIVE_MEDIUMLOW + +// Bootloader only +#ifdef UF2_BOOTLOADER_ENABLED + #define BOARD_VTOR_DEFER (1) // Leave VTOR relocation to bootloader +#endif + +#define BOARD_NO_VBUS_SENSE (1) +#define BOARD_NO_USB_OTG_ID_SENSE (1) + +#define DEFAULT_I2C_BUS_SCL (&pin_PB06) +#define DEFAULT_I2C_BUS_SDA (&pin_PB07) + +#define DEFAULT_SPI_BUS_SS (&pin_PB08) +#define DEFAULT_SPI_BUS_SCK (&pin_PA05) +#define DEFAULT_SPI_BUS_MOSI (&pin_PB05) +#define DEFAULT_SPI_BUS_MISO (&pin_PB06) + +#define DEFAULT_UART_BUS_RX (&pin_PA10) +#define DEFAULT_UART_BUS_TX (&pin_PA09) + +#define CYGNET_DISCHARGE_3V3 (&pin_PH01) +#define CYGNET_ENABLE_3V3 (&pin_PH00) diff --git a/ports/stm/boards/blues_cygnet/mpconfigboard.mk b/ports/stm/boards/blues_cygnet/mpconfigboard.mk new file mode 100644 index 00000000000..48e8241c7a6 --- /dev/null +++ b/ports/stm/boards/blues_cygnet/mpconfigboard.mk @@ -0,0 +1,105 @@ +USB_VID = 0x30A4 +USB_PID = 0x03 +USB_PRODUCT = "Cygnet" +USB_MANUFACTURER = "Blues Inc." + +MCU_SERIES = L4 +MCU_VARIANT = STM32L433xx +MCU_PACKAGE = LQFP48 + +LD_COMMON = boards/common_default.ld +LD_DEFAULT = boards/STM32L433_default.ld +UF2_OFFSET = 0x8000000 +UF2_BOOTLOADER ?= 0 +CIRCUITPY_BUILD_EXTENSIONS = bin + +INTERNAL_FLASH_FILESYSTEM = 1 +LONGINT_IMPL = NONE +CIRCUITPY_FULL_BUILD = 0 + +CIRCUITPY_AESIO = 0 +CIRCUITPY_ALARM = 0 +CIRCUITPY_ANALOGIO = 1 +CIRCUITPY_ATEXIT = 0 +CIRCUITPY_AUDIOBUSIO = 0 +CIRCUITPY_AUDIOBUSIO_I2SOUT = 0 +CIRCUITPY_AUDIOBUSIO_PDMIN = 0 +CIRCUITPY_AUDIOMIXER = 0 +CIRCUITPY_AUDIOMP3 = 0 +CIRCUITPY_AUDIOPWMIO = 0 +CIRCUITPY_BITBANGIO = 1 +CIRCUITPY_BLEIO = 0 +CIRCUITPY_BLEIO_HCI = 0 +CIRCUITPY_BINASCII = 0 +CIRCUITPY_BITMAPFILTER = 0 +CIRCUITPY_BITMAPTOOLS = 0 +CIRCUITPY_BUILTINS_POW3 = 0 +CIRCUITPY_BUSDEVICE = 0 +CIRCUITPY_BUSIO = 1 +CIRCUITPY_CANIO = 0 +CIRCUITPY_COMPUTED_GOTO_SAVE_SPACE = 1 +CIRCUITPY_COUNTIO = 0 +CIRCUITPY_DIGITALIO = 1 +CIRCUITPY_DISPLAYIO = 0 +CIRCUITPY_ENABLE_MPY_NATIVE = 0 +CIRCUITPY_FRAMEBUFFERIO = 0 +CIRCUITPY_FREQUENCYIO = 0 +CIRCUITPY_FUTURE= 0 +CIRCUITPY_GETPASS = 0 +CIRCUITPY_GIFIO = 0 +CIRCUITPY_I2CTARGET = 0 +CIRCUITPY_JSON = 0 +CIRCUITPY_KEYPAD = 0 +CIRCUITPY_KEYPAD_DEMUX = 0 +CIRCUITPY_LTO = 1 +CIRCUITPY_MICROCONTROLLER = 1 +CIRCUITPY_MSGPACK = 0 +CIRCUITPY_NEOPIXEL_WRITE = 0 +CIRCUITPY_NVM = 0 +CIRCUITPY_ONEWIREIO = 0 +CIRCUITPY_OS = 1 +CIRCUITPY_PIXELBUF = 0 +CIRCUITPY_PIXELMAP = 0 +CIRCUITPY_PULSEIO = 1 +CIRCUITPY_PWMIO = 1 +CIRCUITPY_RANDOM = 0 +CIRCUITPY_RAINBOWIO = 0 +CIRCUITPY_RE = 0 +CIRCUITPY_REQUIRE_I2C_PULLUPS = 0 +CIRCUITPY_ROTARYIO_SOFTENCODER = 1 +CIRCUITPY_RGBMATRIX = 0 +CIRCUITPY_RTC = 0 +CIRCUITPY_SAFEMODE_PY = 0 +CIRCUITPY_SDCARDIO = 0 +CIRCUITPY_STATUS_BAR= 0 +CIRCUITPY_STORAGE = 1 +CIRCUITPY_SUPERVISOR = 1 +CIRCUITPY_SYNTHIO = 0 +CIRCUITPY_TERMINALIO = 0 +CIRCUITPY_TOUCHIO = 0 +CIRCUITPY_TOUCHIO_USE_NATIVE = 1 +CIRCUITPY_TRACEBACK = 0 +CIRCUITPY_ULAB = 0 +CIRCUITPY_USB_CDC = 1 +CIRCUITPY_USB_HID = 0 +CIRCUITPY_USB_IDENTIFICATION = 1 +CIRCUITPY_USB_MIDI = 0 +CIRCUITPY_USB_MIDI_ENABLED_DEFAULT= 0 +CIRCUITPY_USB_MSC = 1 +CIRCUITPY_USB_VENDOR = 0 +CIRCUITPY_WIFI_RADIO_SETTABLE_MAC_ADDRESS= 0 +CIRCUITPY_VECTORIO = 0 +CIRCUITPY_ZLIB = 0 + +MICROPY_PY_ASYNC_AWAIT = 0 + +RELEASE_NEEDS_CLEAN_BUILD = 0 + +SUPEROPT_GC = 0 +SUPEROPT_VM = 0 + +CIRCUITPY_LTO_PARTITION = one + +OPTIMIZATION_FLAGS = -Os + +CFLAGS_BOARD = -fweb -frename-registers diff --git a/ports/stm/boards/blues_cygnet/pins.c b/ports/stm/boards/blues_cygnet/pins.c new file mode 100644 index 00000000000..f644160e4fd --- /dev/null +++ b/ports/stm/boards/blues_cygnet/pins.c @@ -0,0 +1,52 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2017 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// #include "py/objtuple.h" +#include "shared-bindings/board/__init__.h" +#include "board.h" + +// Core Feather Pins +static const mp_rom_map_elem_t board_module_globals_table[] = { + CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS + + { MP_ROM_QSTR(MP_QSTR_ENABLE_3V3), &power_pin }, + { MP_ROM_QSTR(MP_QSTR_DISCHARGE_3V3), &discharge_pin }, + + { 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_PB01) }, + { MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_PA07) }, + + { MP_ROM_QSTR(MP_QSTR_VOLTAGE_MONITOR), MP_ROM_PTR(&pin_PA04) }, + { MP_ROM_QSTR(MP_QSTR_BUTTON_USR), MP_ROM_PTR(&pin_PC13) }, + + { MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_PB08) }, + { MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_PB09) }, + { MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_PB14) }, + { MP_ROM_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_PB15) }, + + { MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_PA08) }, + { MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_PB04) }, // ADC, PWM, DAC2 output also + + { MP_ROM_QSTR(MP_QSTR_SDA), MP_ROM_PTR(&pin_PB07) }, // PWM + { MP_ROM_QSTR(MP_QSTR_SCL), MP_ROM_PTR(&pin_PB06) }, // PWM + + { MP_ROM_QSTR(MP_QSTR_SS), MP_ROM_PTR(&pin_PB08) }, + { MP_ROM_QSTR(MP_QSTR_SCK), MP_ROM_PTR(&pin_PA14) }, + { MP_ROM_QSTR(MP_QSTR_MISO), MP_ROM_PTR(&pin_PA13) }, + { MP_ROM_QSTR(MP_QSTR_MOSI), MP_ROM_PTR(&pin_PB05) }, + + { MP_ROM_QSTR(MP_QSTR_TX), MP_ROM_PTR(&pin_PA09) }, // ADC, PWM + { MP_ROM_QSTR(MP_QSTR_RX), MP_ROM_PTR(&pin_PA10) }, // PWM + + { 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_module_globals_table); diff --git a/ports/stm/boards/common_default.ld b/ports/stm/boards/common_default.ld index 7c96a42bc56..cdbe7d59a72 100644 --- a/ports/stm/boards/common_default.ld +++ b/ports/stm/boards/common_default.ld @@ -35,6 +35,12 @@ SECTIONS .text : { . = ALIGN(4); + __property_getter_start = .; + *(.property_getter) + __property_getter_end = .; + __property_getset_start = .; + *(.property_getset) + __property_getset_end = .; *(.text*) /* .text* sections (code) */ *(.rodata*) /* .rodata* sections (constants, strings, etc.) */ /* *(.glue_7) */ /* glue arm to thumb code */ @@ -81,7 +87,9 @@ SECTIONS . = . + _minimum_heap_size; . = ALIGN(4); } >RAM - _ld_heap_end = ORIGIN(RAM) + LENGTH(RAM); + /* The stack sits at the top of RAM, so end the heap below it. The extra 1K matches + CIRCUITPY_EXCEPTION_STACK_SIZE, which port_stack_get_limit() counts as stack too. */ + _ld_heap_end = ORIGIN(RAM) + LENGTH(RAM) - _ld_default_stack_size - 1K; /* this just checks there is enough RAM for the stack */ .stack : @@ -95,4 +103,9 @@ SECTIONS .ARM.attributes 0 : { *(.ARM.attributes) } + + ASSERT((__property_getter_end - __property_getter_start) % 8 == 0, + "the .property_getter section must hold whole 8-byte objects") + ASSERT((__property_getset_end - __property_getset_start) % 12 == 0, + "the .property_getset section must hold whole 12-byte objects") } diff --git a/ports/stm/boards/common_nvm.ld b/ports/stm/boards/common_nvm.ld index 1d10db8a314..b057d9480fa 100644 --- a/ports/stm/boards/common_nvm.ld +++ b/ports/stm/boards/common_nvm.ld @@ -45,6 +45,12 @@ SECTIONS .text : { . = ALIGN(4); + __property_getter_start = .; + *(.property_getter) + __property_getter_end = .; + __property_getset_start = .; + *(.property_getset) + __property_getset_end = .; *(.text*) /* .text* sections (code) */ *(.rodata*) /* .rodata* sections (constants, strings, etc.) */ /* *(.glue_7) */ /* glue arm to thumb code */ @@ -91,7 +97,9 @@ SECTIONS . = . + _minimum_heap_size; . = ALIGN(4); } >RAM - _ld_heap_end = ORIGIN(RAM) + LENGTH(RAM); + /* The stack sits at the top of RAM, so end the heap below it. The extra 1K matches + CIRCUITPY_EXCEPTION_STACK_SIZE, which port_stack_get_limit() counts as stack too. */ + _ld_heap_end = ORIGIN(RAM) + LENGTH(RAM) - _ld_default_stack_size - 1K; /* this just checks there is enough RAM for the stack */ .stack : @@ -105,4 +113,9 @@ SECTIONS .ARM.attributes 0 : { *(.ARM.attributes) } + + ASSERT((__property_getter_end - __property_getter_start) % 8 == 0, + "the .property_getter section must hold whole 8-byte objects") + ASSERT((__property_getset_end - __property_getset_start) % 12 == 0, + "the .property_getset section must hold whole 12-byte objects") } diff --git a/ports/stm/boards/common_tcm.ld b/ports/stm/boards/common_tcm.ld index 6301dbf315b..18c284f965a 100644 --- a/ports/stm/boards/common_tcm.ld +++ b/ports/stm/boards/common_tcm.ld @@ -37,6 +37,12 @@ SECTIONS .text : { . = ALIGN(4); + __property_getter_start = .; + *(.property_getter) + __property_getter_end = .; + __property_getset_start = .; + *(.property_getset) + __property_getset_end = .; *(.text*) /* .text* sections (code) */ *(.rodata*) /* .rodata* sections (constants, strings, etc.) */ /* *(.glue_7) */ /* glue arm to thumb code */ @@ -146,4 +152,9 @@ SECTIONS } >FLASH_FIRMWARE .ARM.attributes 0 : { *(.ARM.attributes) } + + ASSERT((__property_getter_end - __property_getter_start) % 8 == 0, + "the .property_getter section must hold whole 8-byte objects") + ASSERT((__property_getset_end - __property_getset_start) % 12 == 0, + "the .property_getset section must hold whole 12-byte objects") } diff --git a/ports/stm/boards/daisy_seed_with_sdram/board.c b/ports/stm/boards/daisy_seed_with_sdram/board.c index 9cf9b4a48a7..f135bcbc2e0 100644 --- a/ports/stm/boards/daisy_seed_with_sdram/board.c +++ b/ports/stm/boards/daisy_seed_with_sdram/board.c @@ -3,7 +3,58 @@ // SPDX-FileCopyrightText: Copyright (c) 2024 snkYmkrct // // SPDX-License-Identifier: MIT +#include STM32_HAL_H #include "supervisor/board.h" +#include "supervisor/stm.h" +#include "sdram.h" -// Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. + +/** SDRAM banks configuration. */ +static const struct stm32_sdram_bank_config bank_config[] = { + { .init = { + .SDBank = FMC_SDRAM_BANK1, + .ColumnBitsNumber = FMC_SDRAM_COLUMN_BITS_NUM_9, + .RowBitsNumber = FMC_SDRAM_ROW_BITS_NUM_13, + .MemoryDataWidth = FMC_SDRAM_MEM_BUS_WIDTH_32, + .InternalBankNumber = FMC_SDRAM_INTERN_BANKS_NUM_4, + .CASLatency = FMC_SDRAM_CAS_LATENCY_3, + .WriteProtection = FMC_SDRAM_WRITE_PROTECTION_DISABLE, + .SDClockPeriod = FMC_SDRAM_CLOCK_PERIOD_2, + .ReadBurst = FMC_SDRAM_RBURST_ENABLE, + .ReadPipeDelay = FMC_SDRAM_RPIPE_DELAY_0 + }, + .timing = { + .LoadToActiveDelay = 2, + .ExitSelfRefreshDelay = 8, + .SelfRefreshTime = 5, + .RowCycleDelay = 6, + .WriteRecoveryTime = 3, + .RPDelay = 2, + .RCDDelay = 2 + }} +}; + +/* SDRAM configuration. */ +static const struct stm32_sdram_config config = { + .sdram = FMC_SDRAM_DEVICE, + .power_up_delay = 100, + .num_auto_refresh = 8, + .mode_register = SDRAM_MODEREG_BURST_LENGTH_4 | + SDRAM_MODEREG_BURST_TYPE_SEQUENTIAL | + SDRAM_MODEREG_CAS_LATENCY_3 | + SDRAM_MODEREG_WRITEBURST_MODE_SINGLE, + /* Set the device refresh rate based on the RM0433 STM reference manual + refresh_rate = [(SDRAM self refresh time / number of rows) x SDRAM CLK] – 20 + = [(64ms/8192) * 100MHz] - 20 = 781.25 - 20 + */ + .refresh_rate = (64 * 100000 / 8192 - 20), + .banks = bank_config, + .banks_len = 1, +}; + +void board_init(void) { + sdram_init(&config); +// sdram_test(true); + stm_add_sdram_to_heap(); +} diff --git a/ports/stm/boards/daisy_seed_with_sdram/mpconfigboard.h b/ports/stm/boards/daisy_seed_with_sdram/mpconfigboard.h index f0af0a0732b..4951072d910 100644 --- a/ports/stm/boards/daisy_seed_with_sdram/mpconfigboard.h +++ b/ports/stm/boards/daisy_seed_with_sdram/mpconfigboard.h @@ -31,3 +31,10 @@ // for RNG not audio #define CPY_CLK_USB_USES_AUDIOPLL (1) + +// SDRAM and MPU region + +#define CIRCUITPY_HW_SDRAM_SIZE (64 * 1024 * 1024) // 64 MByte + +#define CPY_SDRAM_REGION MPU_REGION_NUMBER10 +#define CPY_SDRAM_REGION_SIZE MPU_REGION_SIZE_64MB diff --git a/ports/stm/boards/daisy_seed_with_sdram/mpconfigboard.mk b/ports/stm/boards/daisy_seed_with_sdram/mpconfigboard.mk index 7b7d4ed4448..a43c4ed177b 100644 --- a/ports/stm/boards/daisy_seed_with_sdram/mpconfigboard.mk +++ b/ports/stm/boards/daisy_seed_with_sdram/mpconfigboard.mk @@ -12,3 +12,7 @@ MCU_PACKAGE = UFBGA176 LD_COMMON = boards/common_tcm.ld LD_FILE = boards/STM32H750.ld + +CIRCUITPY_SDIOIO = 1 +CIRCUITPY_PWMIO = 1 +CIRCUITPY_AUDIOPWMIO = 1 diff --git a/ports/stm/boards/daisy_seed_with_sdram/pins.c b/ports/stm/boards/daisy_seed_with_sdram/pins.c index f5bef6d2b39..b8f8f05b901 100644 --- a/ports/stm/boards/daisy_seed_with_sdram/pins.c +++ b/ports/stm/boards/daisy_seed_with_sdram/pins.c @@ -6,8 +6,56 @@ #include "shared-bindings/board/__init__.h" +// See pinout on Daisy Seed product page +// https://electro-smith.com/products/daisy-seed?variant=45234245108004 static const mp_rom_map_elem_t board_module_globals_table[] = { {MP_ROM_QSTR(MP_QSTR_LED), MP_ROM_PTR(&pin_PC07)}, {MP_ROM_QSTR(MP_QSTR_BOOT), MP_ROM_PTR(&pin_PG03)}, + {MP_ROM_QSTR(MP_QSTR_D0), MP_ROM_PTR(&pin_PB12)}, + {MP_ROM_QSTR(MP_QSTR_D1), MP_ROM_PTR(&pin_PC11)}, + {MP_ROM_QSTR(MP_QSTR_D2), MP_ROM_PTR(&pin_PC10)}, + {MP_ROM_QSTR(MP_QSTR_D3), MP_ROM_PTR(&pin_PC09)}, + {MP_ROM_QSTR(MP_QSTR_D4), MP_ROM_PTR(&pin_PC08)}, + {MP_ROM_QSTR(MP_QSTR_D5), MP_ROM_PTR(&pin_PD02)}, + {MP_ROM_QSTR(MP_QSTR_D6), MP_ROM_PTR(&pin_PC12)}, + {MP_ROM_QSTR(MP_QSTR_D7), MP_ROM_PTR(&pin_PG10)}, + {MP_ROM_QSTR(MP_QSTR_D8), MP_ROM_PTR(&pin_PG11)}, + {MP_ROM_QSTR(MP_QSTR_D9), MP_ROM_PTR(&pin_PB04)}, + {MP_ROM_QSTR(MP_QSTR_D10), MP_ROM_PTR(&pin_PB05)}, + {MP_ROM_QSTR(MP_QSTR_D11), MP_ROM_PTR(&pin_PB08)}, + {MP_ROM_QSTR(MP_QSTR_D12), MP_ROM_PTR(&pin_PB09)}, + {MP_ROM_QSTR(MP_QSTR_D13), MP_ROM_PTR(&pin_PB06)}, + {MP_ROM_QSTR(MP_QSTR_D14), MP_ROM_PTR(&pin_PB07)}, + + {MP_ROM_QSTR(MP_QSTR_D15), MP_ROM_PTR(&pin_PC00)}, + {MP_ROM_QSTR(MP_QSTR_A0), MP_ROM_PTR(&pin_PC00)}, + {MP_ROM_QSTR(MP_QSTR_D16), MP_ROM_PTR(&pin_PA03)}, + {MP_ROM_QSTR(MP_QSTR_A1), MP_ROM_PTR(&pin_PA03)}, + {MP_ROM_QSTR(MP_QSTR_D17), MP_ROM_PTR(&pin_PB01)}, + {MP_ROM_QSTR(MP_QSTR_A2), MP_ROM_PTR(&pin_PB01)}, + {MP_ROM_QSTR(MP_QSTR_D18), MP_ROM_PTR(&pin_PA07)}, + {MP_ROM_QSTR(MP_QSTR_A3), MP_ROM_PTR(&pin_PA07)}, + {MP_ROM_QSTR(MP_QSTR_D19), MP_ROM_PTR(&pin_PA06)}, + {MP_ROM_QSTR(MP_QSTR_A4), MP_ROM_PTR(&pin_PA06)}, + {MP_ROM_QSTR(MP_QSTR_D20), MP_ROM_PTR(&pin_PC01)}, + {MP_ROM_QSTR(MP_QSTR_A5), MP_ROM_PTR(&pin_PC01)}, + {MP_ROM_QSTR(MP_QSTR_D21), MP_ROM_PTR(&pin_PC04)}, + {MP_ROM_QSTR(MP_QSTR_A6), MP_ROM_PTR(&pin_PC04)}, + {MP_ROM_QSTR(MP_QSTR_D22), MP_ROM_PTR(&pin_PA05)}, + {MP_ROM_QSTR(MP_QSTR_A7), MP_ROM_PTR(&pin_PA05)}, + {MP_ROM_QSTR(MP_QSTR_D23), MP_ROM_PTR(&pin_PA04)}, + {MP_ROM_QSTR(MP_QSTR_A8), MP_ROM_PTR(&pin_PA04)}, + {MP_ROM_QSTR(MP_QSTR_D24), MP_ROM_PTR(&pin_PA01)}, + {MP_ROM_QSTR(MP_QSTR_A9), MP_ROM_PTR(&pin_PA01)}, + {MP_ROM_QSTR(MP_QSTR_D25), MP_ROM_PTR(&pin_PA00)}, + {MP_ROM_QSTR(MP_QSTR_A10), MP_ROM_PTR(&pin_PA00)}, + {MP_ROM_QSTR(MP_QSTR_D26), MP_ROM_PTR(&pin_PD11)}, + {MP_ROM_QSTR(MP_QSTR_D27), MP_ROM_PTR(&pin_PG09)}, + {MP_ROM_QSTR(MP_QSTR_D28), MP_ROM_PTR(&pin_PA02)}, + {MP_ROM_QSTR(MP_QSTR_A11), MP_ROM_PTR(&pin_PA02)}, + {MP_ROM_QSTR(MP_QSTR_D29), MP_ROM_PTR(&pin_PB14)}, + {MP_ROM_QSTR(MP_QSTR_D30), MP_ROM_PTR(&pin_PB15)}, + }; + MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); diff --git a/ports/stm/boards/espruino_pico/README.md b/ports/stm/boards/espruino_pico/README.md index 86df1ad32a3..d930e9aeca3 100644 --- a/ports/stm/boards/espruino_pico/README.md +++ b/ports/stm/boards/espruino_pico/README.md @@ -12,4 +12,4 @@ The Espruino Pico is normally updated via a bootloader activated by the Espruino - Restart the board. -To reinstall Espruino, follow the same steps with the latest Espruino Pico binary from espruino.com/binaries. This will reinstall the usual Espruino bootloader. You must un-short the BOOT0/BTN jumper to re-use the original Espruino Bootloader again. If you used a Pencil mark then you may need to use cleaning fluid and a small brush to totally clear out the graphite. +To reinstall Espruino, follow the same steps with the latest Espruino Pico binary from espruino.com/binaries. This will reinstall the usual Espruino bootloader. You must un-short the BOOT0/BTN jumper to reuse the original Espruino Bootloader again. If you used a Pencil mark then you may need to use cleaning fluid and a small brush to totally clear out the graphite. diff --git a/ports/stm/boards/espruino_wifi/README.MD b/ports/stm/boards/espruino_wifi/README.MD index cc78811f1c7..cebe99bf6d1 100644 --- a/ports/stm/boards/espruino_wifi/README.MD +++ b/ports/stm/boards/espruino_wifi/README.MD @@ -12,4 +12,4 @@ The Espruino Wifi is normally updated via a bootloader activated by the Espruino - Restart the board. -To reinstall Espruino, follow the same steps with the latest Espruino Wifi binary from espruino.com/binaries. This will reinstall the usual Espruino bootloader. You must un-short the BOOT0/BTN jumper to re-use the original Espruino Bootloader again. If you used a Pencil mark then you may need to use cleaning fluid and a small brush to totally clear out the graphite. +To reinstall Espruino, follow the same steps with the latest Espruino Wifi binary from espruino.com/binaries. This will reinstall the usual Espruino bootloader. You must un-short the BOOT0/BTN jumper to reuse the original Espruino Bootloader again. If you used a Pencil mark then you may need to use cleaning fluid and a small brush to totally clear out the graphite. diff --git a/ports/stm/boards/meowbit_v121/board.c b/ports/stm/boards/meowbit_v121/board.c index 181f433a372..26fd0212dfc 100644 --- a/ports/stm/boards/meowbit_v121/board.c +++ b/ports/stm/boards/meowbit_v121/board.c @@ -8,6 +8,7 @@ #include "mpconfigboard.h" #include "shared-bindings/audiopwmio/PWMAudioOut.h" +#include "common-hal/microcontroller/Pin.h" #include "shared-bindings/board/__init__.h" #include "shared-module/displayio/__init__.h" #include "shared-module/displayio/mipi_constants.h" @@ -55,9 +56,9 @@ void board_init(void) { busio_spi_obj_t *internal_spi = &supervisor_flash_spi_bus; common_hal_fourwire_fourwire_construct(bus, internal_spi, - &pin_PA08, // Command or data - &pin_PB12, // Chip select - &pin_PB10, // Reset + MP_OBJ_FROM_PTR(&pin_PA08), // Command or data + MP_OBJ_FROM_PTR(&pin_PB12), // Chip select + MP_OBJ_FROM_PTR(&pin_PB10), // Reset 24000000, // Baudrate 0, // Polarity 0); // Phase @@ -96,7 +97,8 @@ void board_init(void) { 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); + // Mark the buzzer pin claimed so user code can't conflict with it. + claim_pin(pin_PB08.port, pin_PB08.number); } // Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/stm/boards/meowbit_v121/mpconfigboard.mk b/ports/stm/boards/meowbit_v121/mpconfigboard.mk index bde49ad13ef..1f48d75207e 100644 --- a/ports/stm/boards/meowbit_v121/mpconfigboard.mk +++ b/ports/stm/boards/meowbit_v121/mpconfigboard.mk @@ -23,11 +23,17 @@ LD_FILE = boards/STM32F401xe_boot.ld # LD_FILE = boards/STM32F401xe_fs.ld CIRCUITPY_AESIO = 0 +CIRCUITPY_CODEOP = 0 CIRCUITPY_BITMAPFILTER = 0 CIRCUITPY_BITMAPTOOLS = 0 CIRCUITPY_BLEIO_HCI = 0 CIRCUITPY_EPAPERDISPLAY = 0 +CIRCUITPY_FRAMEBUFFERIO = 0 +CIRCUITPY_GIFIO = 0 +CIRCUITPY_I2CDISPLAYBUS = 0 CIRCUITPY_KEYPAD_DEMUX = 0 +CIRCUITPY_MSGPACK = 0 +CIRCUITPY_PIXELMAP = 0 CIRCUITPY_SHARPDISPLAY = 0 CIRCUITPY_TILEPALETTEMAPPER = 0 CIRCUITPY_ULAB = 0 @@ -35,4 +41,6 @@ CIRCUITPY_ZLIB = 0 CIRCUITPY_STAGE = 1 +CIRCUITPY_DIGITALINOUT_PROTOCOL = 0 + FROZEN_MPY_DIRS += $(TOP)/frozen/circuitpython-stage/meowbit diff --git a/ports/stm/boards/sparkfun_stm32f405_micromod/mpconfigboard.mk b/ports/stm/boards/sparkfun_stm32f405_micromod/mpconfigboard.mk index d1df685c676..31c2b7e2874 100644 --- a/ports/stm/boards/sparkfun_stm32f405_micromod/mpconfigboard.mk +++ b/ports/stm/boards/sparkfun_stm32f405_micromod/mpconfigboard.mk @@ -1,5 +1,5 @@ USB_VID = 0X1B4F -USB_PID = 0x0027 +USB_PID = 0x0029 USB_PRODUCT = "SparkFun STM32 MicroMod Processor" USB_MANUFACTURER = "SparkFun Electronics" diff --git a/ports/stm/boards/stm32f411ce_blackpill_with_flash/mpconfigboard.mk b/ports/stm/boards/stm32f411ce_blackpill_with_flash/mpconfigboard.mk index 64be6f4f142..c46a270df65 100644 --- a/ports/stm/boards/stm32f411ce_blackpill_with_flash/mpconfigboard.mk +++ b/ports/stm/boards/stm32f411ce_blackpill_with_flash/mpconfigboard.mk @@ -9,6 +9,7 @@ EXTERNAL_FLASH_DEVICES = GD25Q16C,W25Q16JVxQ,W25Q64FV,W25Q32JVxQ,W25Q64JVxQ LONGINT_IMPL = MPZ INTERNAL_FLASH_FILESYSTEM = 0 +OPTIMIZATION_FLAGS = -Os MCU_SERIES = F4 MCU_VARIANT = STM32F411xE diff --git a/ports/stm/boards/stm32f411ve_discovery/mpconfigboard.mk b/ports/stm/boards/stm32f411ve_discovery/mpconfigboard.mk index f34fac4047a..98d13f592ff 100644 --- a/ports/stm/boards/stm32f411ve_discovery/mpconfigboard.mk +++ b/ports/stm/boards/stm32f411ve_discovery/mpconfigboard.mk @@ -9,6 +9,8 @@ MCU_SERIES = F4 MCU_VARIANT = STM32F411xE MCU_PACKAGE = LQFP100_f4 +OPTIMIZATION_FLAGS = -Os + LD_COMMON = boards/common_default.ld LD_FILE = boards/STM32F411_fs.ld diff --git a/ports/stm/boards/stm32f746g_discovery/board.c b/ports/stm/boards/stm32f746g_discovery/board.c index 5b4f3470769..cd481e6597b 100644 --- a/ports/stm/boards/stm32f746g_discovery/board.c +++ b/ports/stm/boards/stm32f746g_discovery/board.c @@ -25,7 +25,8 @@ void board_init(void) { HAL_GPIO_Init(GPIOK, &GPIO_InitStructure); HAL_GPIO_WritePin(GPIOK, GPIO_PIN_3, GPIO_PIN_RESET); - never_reset_pin_number(10, 3); + // PK3 drives the LCD backlight; mark it claimed so user code can't conflict with it. + claim_pin(10, 3); } // Use the MP_WEAK supervisor/shared/board.c versions of routines not defined here. diff --git a/ports/stm/boards/swan_r5/board.c b/ports/stm/boards/swan_r5/board.c index 690120bf5ac..a88c53b2389 100644 --- a/ports/stm/boards/swan_r5/board.c +++ b/ports/stm/boards/swan_r5/board.c @@ -28,8 +28,6 @@ void initialize_discharge_pin(void) { common_hal_digitalio_digitalinout_construct(&power_pin, &pin_PE04); common_hal_digitalio_digitalinout_construct(&discharge_pin, &pin_PE06); - common_hal_digitalio_digitalinout_never_reset(&power_pin); - common_hal_digitalio_digitalinout_never_reset(&discharge_pin); GPIO_InitTypeDef GPIO_InitStruct; /* Set the DISCHARGE pin and the USB_DETECT pin to FLOAT */ diff --git a/ports/stm/boards/swan_r5/mpconfigboard.mk b/ports/stm/boards/swan_r5/mpconfigboard.mk index ea4125e02b8..353f96cca78 100644 --- a/ports/stm/boards/swan_r5/mpconfigboard.mk +++ b/ports/stm/boards/swan_r5/mpconfigboard.mk @@ -24,7 +24,7 @@ CIRCUITPY_AUDIOBUSIO_I2SOUT = 0 CIRCUITPY_AUDIOBUSIO_PDMIN = 1 CIRCUITPY_AUDIOPWMIO = 1 CIRCUITPY_BITBANGIO = 1 -CIRCUITPY_BLEIO = 0 +CIRCUITPY_BLEIO_NATIVE = 0 CIRCUITPY_BLEIO_HCI = 0 CIRCUITPY_BUSDEVICE = 0 CIRCUITPY_BUSIO = 1 diff --git a/ports/stm/boards/thunderpack_v11/mpconfigboard.mk b/ports/stm/boards/thunderpack_v11/mpconfigboard.mk index 4fede00dc07..0107bbb1c17 100644 --- a/ports/stm/boards/thunderpack_v11/mpconfigboard.mk +++ b/ports/stm/boards/thunderpack_v11/mpconfigboard.mk @@ -13,6 +13,8 @@ MCU_SERIES = F4 MCU_VARIANT = STM32F411xE MCU_PACKAGE = UFQFPN48 +OPTIMIZATION_FLAGS = -Os + LD_COMMON = boards/common_nvm.ld LD_FILE = boards/STM32F411_nvm.ld diff --git a/ports/stm/boards/thunderpack_v12/mpconfigboard.mk b/ports/stm/boards/thunderpack_v12/mpconfigboard.mk index 276cf6d0110..353d0733e64 100644 --- a/ports/stm/boards/thunderpack_v12/mpconfigboard.mk +++ b/ports/stm/boards/thunderpack_v12/mpconfigboard.mk @@ -25,11 +25,7 @@ MCU_SERIES = F4 MCU_VARIANT = STM32F411xE MCU_PACKAGE = UFQFPN48 +OPTIMIZATION_FLAGS = -Os + LD_COMMON = boards/common_nvm.ld LD_FILE = boards/STM32F411_nvm_nofs.ld - -# Disable TERMINALIO on translations with missing characters. -ifneq (,$(filter $(TRANSLATION),ja ko ru)) -CIRCUITPY_TERMINALIO = 0 -RELEASE_NEEDS_CLEAN_BUILD = $(CIRCUITPY_DISPLAYIO) -endif diff --git a/ports/stm/common-hal/alarm/__init__.c b/ports/stm/common-hal/alarm/__init__.c index 3d6c4466882..3eac6c86546 100644 --- a/ports/stm/common-hal/alarm/__init__.c +++ b/ports/stm/common-hal/alarm/__init__.c @@ -46,6 +46,10 @@ void alarm_set_wakeup_reason(stm_sleep_source_t reason) { true_deep_wake_reason = reason; } +bool alarm_woke_from_true_deep_sleep(void) { + return true_deep_wake_reason != STM_WAKEUP_UNDEF; +} + stm_sleep_source_t alarm_get_wakeup_cause(void) { // If in light/fake sleep, check modules if (alarm_pin_pinalarm_woke_this_cycle()) { @@ -120,22 +124,19 @@ mp_obj_t common_hal_alarm_light_sleep_until_alarms(size_t n_alarms, const mp_obj port_idle_until_interrupt(); } + alarm_reset(); if (mp_hal_is_interrupted()) { return mp_const_none; // Shouldn't be given to python code because exception handling should kick in. } - alarm_reset(); return wake_alarm; } void common_hal_alarm_set_deep_sleep_alarms(size_t n_alarms, const mp_obj_t *alarms, size_t n_dios, digitalio_digitalinout_obj_t **preserve_dios) { - if (n_dios > 0) { - mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_preserve_dios); - } _setup_sleep_alarms(true, n_alarms, alarms); } -void NORETURN common_hal_alarm_enter_deep_sleep(void) { +void MP_NORETURN common_hal_alarm_enter_deep_sleep(void) { alarm_set_wakeup_reason(STM_WAKEUP_UNDEF); alarm_pin_pinalarm_prepare_for_deep_sleep(); alarm_time_timealarm_prepare_for_deep_sleep(); diff --git a/ports/stm/common-hal/alarm/__init__.h b/ports/stm/common-hal/alarm/__init__.h index e530efc58da..554c038631e 100644 --- a/ports/stm/common-hal/alarm/__init__.h +++ b/ports/stm/common-hal/alarm/__init__.h @@ -29,4 +29,5 @@ extern alarm_wake_alarm_union_t alarm_wake_alarm; extern void alarm_set_wakeup_reason(stm_sleep_source_t reason); extern stm_sleep_source_t alarm_get_wakeup_cause(void); +extern bool alarm_woke_from_true_deep_sleep(void); extern void alarm_reset(void); diff --git a/ports/stm/common-hal/alarm/pin/PinAlarm.c b/ports/stm/common-hal/alarm/pin/PinAlarm.c index 93512953d31..1cda14e0356 100644 --- a/ports/stm/common-hal/alarm/pin/PinAlarm.c +++ b/ports/stm/common-hal/alarm/pin/PinAlarm.c @@ -122,7 +122,6 @@ void alarm_pin_pinalarm_set_alarms(bool deep_sleep, size_t n_alarms, const mp_ob // so we put it off until right before sleeping. deep_wkup_enabled = true; // EXTI needs to persist past the VM cleanup for fake deep sleep - stm_peripherals_exti_never_reset(alarm->pin->number); } if (!stm_peripherals_exti_reserve(alarm->pin->number)) { mp_raise_RuntimeError(MP_ERROR_TEXT("Pin interrupt already in use")); diff --git a/ports/stm/common-hal/alarm/time/TimeAlarm.c b/ports/stm/common-hal/alarm/time/TimeAlarm.c index ca5d0de7091..8e60cd21e34 100644 --- a/ports/stm/common-hal/alarm/time/TimeAlarm.c +++ b/ports/stm/common-hal/alarm/time/TimeAlarm.c @@ -53,6 +53,9 @@ bool alarm_time_timealarm_woke_this_cycle(void) { } void alarm_time_timealarm_reset(void) { + // Turn the alarm off, as the other ports do. A TimeAlarm that didn't end the sleep would + // otherwise still fire, and the next sleep would return at once. + stm32_peripherals_rtc_cancel_alarm(PERIPHERALS_ALARM_B); woke_up = false; } @@ -76,7 +79,8 @@ 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; - uint32_t wakeup_in_secs = MAX(0.0f, timealarm->monotonic_time - now_secs); + // Scale before converting to an integer, so the fraction of a second isn't lost. + mp_float_t wakeup_in_secs = MAX(0.0f, timealarm->monotonic_time - now_secs); uint32_t wakeup_in_ticks = wakeup_in_secs * 1024; // In the deep sleep case, we can't start the timer until the USB delay has finished diff --git a/ports/stm/common-hal/analogio/AnalogOut.c b/ports/stm/common-hal/analogio/AnalogOut.c index 44fdff5af4b..b67f4cdd320 100644 --- a/ports/stm/common-hal/analogio/AnalogOut.c +++ b/ports/stm/common-hal/analogio/AnalogOut.c @@ -33,19 +33,20 @@ DAC_HandleTypeDef handle; #endif -static bool dac_on[2]; +static void mark_deinit(analogio_analogout_obj_t *self) { + self->pin = NULL; +} void common_hal_analogio_analogout_construct(analogio_analogout_obj_t *self, const mcu_pin_obj_t *pin) { + mark_deinit(self); #if !(HAS_DAC) mp_raise_ValueError(MP_ERROR_TEXT("No DAC on chip")); #else if (pin == &pin_PA04) { self->channel = DAC_CHANNEL_1; - self->dac_index = 0; } else if (pin == &pin_PA05) { self->channel = DAC_CHANNEL_2; - self->dac_index = 1; } else { raise_ValueError_invalid_pin(); } @@ -72,24 +73,25 @@ void common_hal_analogio_analogout_construct(analogio_analogout_obj_t *self, mp_raise_ValueError(MP_ERROR_TEXT("DAC Channel Init Error")); } - dac_on[self->dac_index] = true; self->pin = pin; common_hal_mcu_pin_claim(pin); #endif } bool common_hal_analogio_analogout_deinited(analogio_analogout_obj_t *self) { - return !dac_on[self->dac_index]; + return self->pin == NULL; } void common_hal_analogio_analogout_deinit(analogio_analogout_obj_t *self) { #if HAS_DAC + if (common_hal_analogio_analogout_deinited(self)) { + return; + } reset_pin_number(self->pin->port, self->pin->number); - self->pin = NULL; - dac_on[self->dac_index] = false; + mark_deinit(self); - // turn off the DAC if both channels are off - if (dac_on[0] == false && dac_on[1] == false) { + // Turn off the DAC once neither of its pins is in use by an AnalogOut or AudioOut. + if (common_hal_mcu_pin_is_free(&pin_PA04) && common_hal_mcu_pin_is_free(&pin_PA05)) { __HAL_RCC_DAC_CLK_DISABLE(); HAL_DAC_DeInit(&handle); } diff --git a/ports/stm/common-hal/analogio/AnalogOut.h b/ports/stm/common-hal/analogio/AnalogOut.h index 6a8fc2720bf..9e52795bedf 100644 --- a/ports/stm/common-hal/analogio/AnalogOut.h +++ b/ports/stm/common-hal/analogio/AnalogOut.h @@ -24,7 +24,12 @@ typedef struct { #endif const mcu_pin_obj_t *pin; uint8_t channel; - uint8_t dac_index : 1; } analogio_analogout_obj_t; void analogout_reset(void); + +// Shared DAC peripheral handle (defined in AnalogOut.c). +// AudioOut reuses this handle for DMA-triggered DAC operation on channel 1. +#if HAS_DAC +extern DAC_HandleTypeDef handle; +#endif diff --git a/ports/stm/common-hal/audioio/AudioOut.c b/ports/stm/common-hal/audioio/AudioOut.c new file mode 100644 index 00000000000..d0c96d120e7 --- /dev/null +++ b/ports/stm/common-hal/audioio/AudioOut.c @@ -0,0 +1,748 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +// DAC-based audio output for STM32F405 / STM32F407. +// +// Architecture: +// TIM6 (basic timer) generates an update event at the sample rate. +// DAC_CHANNEL_1 (PA04) is configured with DAC_TRIGGER_T6_TRGO so each +// TIM6 update latches the next sample from the DMA FIFO. +// DMA1 Stream5 Channel7 operates in circular mode, feeding 16-bit samples +// from a double-buffer. Stereo additionally drives DAC_CHANNEL_2 (PA05) +// via DMA1 Stream6 Channel7, sharing the same TIM6 trigger. +// The DMA half-complete and complete callbacks queue a background_callback +// to refill the idle half from the audio sample source. +// +// The shared DAC handle (declared in AnalogOut.c) is reused here so both +// modules share state consistently and avoid double-init conflicts. Pin +// claims (common_hal_mcu_pin_claim) act as the inter-module mutex: a second +// AudioOut, or an AnalogOut on the same pin, fails at the claim step. + +#include + +#include "py/mperrno.h" +#include "py/runtime.h" +#include "py/mphal.h" + +#include "common-hal/audioio/AudioOut.h" +#include "shared-bindings/audioio/AudioOut.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-module/audiocore/__init__.h" +#include "supervisor/background_callback.h" + +#include STM32_HAL_H + +// Shared DAC handle declared in common-hal/analogio/AnalogOut.h. +// AudioOut reconfigures channel 1 (and 2 for stereo) for DMA-triggered +// operation and restores the no-trigger config on deinit so AnalogOut can +// resume use of the channel afterwards. +#include "common-hal/analogio/AnalogOut.h" + +// Highest sample rate accepted by play(). 1 MHz mirrors atmel-samd's SAMD51 +// limit and is comfortably above any reasonable audio rate; the real hardware +// ceiling is TIM6_CLK / 2 (~42 MHz on F405) but rates that high would just +// underrun the DMA refill path. +#define AUDIOOUT_MAX_SAMPLE_RATE 1000000u + +// TIM6 handle: only one instance ever active, so file-scope is fine. +static TIM_HandleTypeDef tim6_handle; + +// Pointer to the currently active AudioOut object, used by IRQ handlers. +// Pin claims prevent two instances from existing simultaneously, but this +// pointer is also used to early-out IRQs after stop(). +static audioio_audioout_obj_t *active_audioout = NULL; + +// --------------------------------------------------------------------------- +// Helpers +// --------------------------------------------------------------------------- + +// Return the TIM6 input clock frequency in Hz. +// TIM6 sits on APB1. The clock is doubled when the APB1 prescaler != 1 +// (same logic as stm_peripherals_timer_get_source_freq in timers.c but +// applied directly to APB1 since TIM6 is not in mcu_tim_banks[]). +static uint32_t get_tim6_freq(void) { + uint32_t apb1 = HAL_RCC_GetPCLK1Freq(); + uint32_t ppre1 = (RCC->CFGR & RCC_CFGR_PPRE1) >> RCC_CFGR_PPRE1_Pos; + #if defined(RCC_DCKCFGR_TIMPRE) + uint32_t timpre = RCC->DCKCFGR & RCC_DCKCFGR_TIMPRE; + if (timpre == 0) { + return (ppre1 >= 0b100) ? apb1 * 2 : apb1; + } else { + return (ppre1 > 0b101) ? apb1 * 4 : HAL_RCC_GetHCLKFreq(); + } + #else + return (ppre1 >= 0b100) ? apb1 * 2 : apb1; + #endif +} + +// Gently ramp the given DAC channel output from from_12 to to_12 (both 12-bit, +// 0-4095) to avoid audible clicks. 64 steps × 100 µs/step = ~6.4 ms total; +// shrink the step count and clicks reappear on the F405 output stage. +static void dac_ramp_channel(uint32_t channel, uint32_t from_12, uint32_t to_12) { + if (from_12 == to_12) { + return; + } + int32_t delta = (int32_t)to_12 - (int32_t)from_12; + int32_t step = delta / 64; + if (step == 0) { + step = (delta > 0) ? 1 : -1; + } + int32_t v = (int32_t)from_12; + while (true) { + v += step; + if (step > 0 && v >= (int32_t)to_12) { + v = (int32_t)to_12; + } else if (step < 0 && v <= (int32_t)to_12) { + v = (int32_t)to_12; + } + HAL_DAC_SetValue(&handle, channel, DAC_ALIGN_12B_R, (uint16_t)v); + HAL_DAC_Start(&handle, channel); + mp_hal_delay_us(100); + if (v == (int32_t)to_12) { + break; + } + } +} + +static inline void dac_ramp(uint32_t from_12, uint32_t to_12) { + dac_ramp_channel(DAC_CHANNEL_1, from_12, to_12); +} + +// Convert a buffer of audio samples into 12-bit unsigned DAC values and write +// them into dest[]. Returns the number of DAC samples written; the caller is +// responsible for padding any remaining dest entries with the quiescent value. +// +// NOTE: ports/espressif/common-hal/audioio/AudioOut.c implements the same +// idea with a CONV_MATCH lookup table dispatching to per-format helpers in +// shared-module/audiocore — a more general-purpose pattern. If a future +// refactor lifts a 12-bit DAC variant into shared-module/audiocore, both +// this driver and any other ARM-DAC port could share it. +// +// src - raw sample bytes from audiosample_get_buffer +// src_len - byte length of src +// dest - output array of 12-bit DAC values (uint16_t) +// dest_count - capacity of dest in samples +// bytes_per_sample - 1 or 2 +// samples_signed - true if source samples are signed +// channel_count - 1 (mono) or 2 (stereo) +// channel_offset - 0 for left/mono, 1 for right channel of a stereo stream +static uint32_t convert_to_dac12( + const uint8_t *src, uint32_t src_len, + uint16_t *dest, uint32_t dest_count, + uint8_t bytes_per_sample, bool samples_signed, + uint8_t channel_count, uint8_t channel_offset) { + + // src_stride: bytes between consecutive samples of the same channel + uint32_t src_stride = (uint32_t)bytes_per_sample * channel_count; + // src_offset: byte offset to the desired channel within each frame + uint32_t src_offset = (uint32_t)bytes_per_sample * channel_offset; + uint32_t src_frames = src_len / src_stride; + uint32_t frames = (src_frames < dest_count) ? src_frames : dest_count; + + if (bytes_per_sample == 1) { + for (uint32_t i = 0; i < frames; i++) { + uint8_t u8 = src[i * src_stride + src_offset]; + int32_t s = samples_signed + ? (int32_t)(int8_t)u8 + : (int32_t)u8 - 128; + dest[i] = (uint16_t)((s + 128) & 0xFF) << 4; + } + } else { + for (uint32_t i = 0; i < frames; i++) { + uint16_t u16; + memcpy(&u16, src + i * src_stride + src_offset, 2); + int32_t s = samples_signed + ? (int32_t)(int16_t)u16 + : (int32_t)u16 - 0x8000; + dest[i] = (uint16_t)((s + 0x8000) & 0xFFFF) >> 4; + } + } + return frames; +} + +// Pad [filled, AUDIOOUT_DMA_HALF_SAMPLES) of dest_l (and dest_r if non-NULL) +// with the quiescent value. Used at end-of-stream and on errors so the DAC +// returns smoothly to its resting voltage. +static void pad_quiescent(uint16_t *dest_l, uint16_t *dest_r, + uint32_t filled, uint16_t quiescent_12) { + for (uint32_t i = filled; i < AUDIOOUT_DMA_HALF_SAMPLES; i++) { + dest_l[i] = quiescent_12; + if (dest_r) { + dest_r[i] = quiescent_12; + } + } +} + +// Load one half of the DMA circular buffer from the audio sample source. +// half: 0 = lower half (indices 0..HALF-1), 1 = upper half (HALF..END-1). +// +// Tracks position within the source buffer (src_ptr / src_remaining_len) +// across calls so that large source buffers (e.g. a 1024-sample RawSample) +// are consumed incrementally rather than re-reading from the start each time. +static void load_dma_buffer_half(audioio_audioout_obj_t *self, uint8_t half) { + uint16_t *dest_l = self->dma_buffer + ((uint32_t)half * AUDIOOUT_DMA_HALF_SAMPLES); + uint16_t *dest_r = self->dma_buffer_r + ? self->dma_buffer_r + ((uint32_t)half * AUDIOOUT_DMA_HALF_SAMPLES) + : NULL; + uint16_t quiescent_12 = self->quiescent_value >> 4; + uint32_t src_stride = (uint32_t)self->bytes_per_sample * self->channel_count; + uint32_t filled = 0; + + while (filled < AUDIOOUT_DMA_HALF_SAMPLES) { + // Fetch new source data when the previous buffer is exhausted. + if (self->src_remaining_len == 0) { + // Handle end-of-stream from previous get_buffer call. + if (self->src_done) { + if (self->loop) { + audiosample_reset_buffer(self->sample, + self->channel_count == 1, 0); + self->src_done = false; + } else { + pad_quiescent(dest_l, dest_r, filled, quiescent_12); + self->stopping = true; + return; + } + } + + uint8_t *buf; + uint32_t len; + audioio_get_buffer_result_t result = + audiosample_get_buffer(self->sample, + self->channel_count == 1, 0, &buf, &len); + + if (result == GET_BUFFER_ERROR) { + pad_quiescent(dest_l, dest_r, filled, quiescent_12); + self->stopping = true; + return; + } + + self->src_ptr = buf; + self->src_remaining_len = len; + self->src_done = (result == GET_BUFFER_DONE); + } + + uint32_t written = convert_to_dac12( + self->src_ptr, self->src_remaining_len, + dest_l + filled, AUDIOOUT_DMA_HALF_SAMPLES - filled, + self->bytes_per_sample, self->samples_signed, + self->channel_count, 0); + + if (dest_r) { + uint8_t r_offset = (self->channel_count >= 2) ? 1 : 0; + convert_to_dac12( + self->src_ptr, self->src_remaining_len, + dest_r + filled, AUDIOOUT_DMA_HALF_SAMPLES - filled, + self->bytes_per_sample, self->samples_signed, + self->channel_count, r_offset); + } + + if (written == 0) { + // src had fewer than src_stride bytes left (e.g. a corrupt WAV + // returned an odd byte count for 16-bit data). Drop the partial + // frame so the next loop iteration calls get_buffer for fresh, + // aligned data — without this the loop spins forever because + // neither filled nor src_remaining_len would advance. + self->src_remaining_len = 0; + continue; + } + + // Advance source position by the amount consumed. + uint32_t bytes_consumed = written * src_stride; + self->src_ptr += bytes_consumed; + self->src_remaining_len -= bytes_consumed; + filled += written; + } +} + +// Background callback: called from the main loop after a DMA half/full event. +static void audioout_fill_callback(void *arg) { + audioio_audioout_obj_t *self = (audioio_audioout_obj_t *)arg; + if (!self || active_audioout != self) { + return; + } + if (self->stopping) { + common_hal_audioio_audioout_stop(self); + return; + } + uint8_t mask; + __disable_irq(); + mask = self->halves_to_fill; + self->halves_to_fill = 0; + __enable_irq(); + if (mask & 0x1) { + load_dma_buffer_half(self, 0); + } + if (mask & 0x2) { + load_dma_buffer_half(self, 1); + } +} + +// --------------------------------------------------------------------------- +// IRQ handlers +// +// DMA1 Stream5/6 are claimed exclusively for DAC use here. If a future port +// change wires another peripheral onto either stream the weak-symbol override +// below will collide silently — add a build-time assertion in that file. +// --------------------------------------------------------------------------- + +void DMA1_Stream5_IRQHandler(void) { + if (active_audioout) { + HAL_DMA_IRQHandler(&active_audioout->dma_handle_l); + } +} + +void DMA1_Stream6_IRQHandler(void) { + if (active_audioout && active_audioout->dma_buffer_r) { + HAL_DMA_IRQHandler(&active_audioout->dma_handle_r); + } +} + +// HAL weak-symbol overrides: called from HAL_DMA_IRQHandler context. +// +// Only the Ch1 (left) callbacks are overridden. The Stream6 IRQ for the +// right channel still calls HAL_DACEx_ConvHalfCpltCallbackCh2 / +// HAL_DACEx_ConvCpltCallbackCh2 (the default empty weak implementations) — +// that is intentional. Both DMA streams are clocked by the same TIM6 trigger +// and started together, so their NDTR counters stay in lock-step. Refilling +// from the left-channel IRQ alone is sufficient and avoids redundant work. + +void HAL_DAC_ConvHalfCpltCallbackCh1(DAC_HandleTypeDef *hdac) { + if (active_audioout && !active_audioout->paused) { + active_audioout->halves_to_fill |= 0x1; + background_callback_add(&active_audioout->callback, + audioout_fill_callback, active_audioout); + } +} + +void HAL_DAC_ConvCpltCallbackCh1(DAC_HandleTypeDef *hdac) { + if (active_audioout && !active_audioout->paused) { + active_audioout->halves_to_fill |= 0x2; + background_callback_add(&active_audioout->callback, + audioout_fill_callback, active_audioout); + } +} + +// --------------------------------------------------------------------------- +// Public API +// --------------------------------------------------------------------------- + +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 quiescent_value) { + + #if !HAS_DAC + mp_raise_ValueError(MP_ERROR_TEXT("No DAC on chip")); + #else + + // Only PA04 (DAC_CH1) is supported as left channel. + if (left_channel != &pin_PA04) { + raise_ValueError_invalid_pin_name(MP_QSTR_left_channel); + } + + // Right channel must be PA05 (DAC_CH2 / A1) if provided. + if (right_channel != NULL && right_channel != &pin_PA05) { + raise_ValueError_invalid_pin_name(MP_QSTR_right_channel); + } + + // Claim pins first. The pin-claim system is what serialises this driver + // against another AudioOut instance and against AnalogOut on the same + // pins — if either is already using PA04/PA05 the claim raises here, and + // because nothing else is configured yet, no cleanup is needed. + // + // NOTE: ports/atmel-samd/common-hal/audioio/AudioOut.c also claims pins + // first but L242 raises *after* claiming a timer and event channel + // without releasing them on the error path; worth a follow-up there. + common_hal_mcu_pin_claim(left_channel); + if (right_channel != NULL) { + common_hal_mcu_pin_claim(right_channel); + } + + self->left_channel = left_channel; + self->right_channel = right_channel; + self->quiescent_value = quiescent_value; + self->sample = MP_OBJ_NULL; + self->dma_buffer = NULL; + self->dma_buffer_r = NULL; + memset(&self->dma_handle_l, 0, sizeof(self->dma_handle_l)); + memset(&self->dma_handle_r, 0, sizeof(self->dma_handle_r)); + memset(&self->callback, 0, sizeof(self->callback)); + self->stopping = false; + self->paused = false; + self->playing = false; + + // Configure PA04 (and PA05 if stereo) for analog (DAC) mode. + GPIO_InitTypeDef gpio_init = {0}; + gpio_init.Pin = pin_mask(left_channel->number); + gpio_init.Mode = GPIO_MODE_ANALOG; + gpio_init.Pull = GPIO_NOPULL; + HAL_GPIO_Init(pin_port(left_channel->port), &gpio_init); + + if (right_channel != NULL) { + gpio_init.Pin = pin_mask(right_channel->number); + HAL_GPIO_Init(pin_port(right_channel->port), &gpio_init); + } + + // Initialise the shared DAC handle if it hasn't been set up yet + // (i.e. AnalogOut hasn't been used since last reset). __HAL_RCC_DAC_CLK_ENABLE + // is idempotent so calling it unconditionally would be safe too, but + // matching AnalogOut's check keeps the two modules in sync. + 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) { + mp_raise_ValueError(MP_ERROR_TEXT("DAC Device Init Error")); + } + } + + // Configure DAC channel 1 with no trigger so the ramp below works + // immediately. play() switches the trigger to TIM6_TRGO. + DAC_ChannelConfTypeDef ch_cfg = {0}; + ch_cfg.DAC_Trigger = DAC_TRIGGER_NONE; + ch_cfg.DAC_OutputBuffer = DAC_OUTPUTBUFFER_ENABLE; + if (HAL_DAC_ConfigChannel(&handle, &ch_cfg, DAC_CHANNEL_1) != HAL_OK) { + mp_raise_ValueError(MP_ERROR_TEXT("DAC Channel Init Error")); + } + + // Ramp DAC output up to quiescent value to prevent an audible pop. + HAL_DAC_SetValue(&handle, DAC_CHANNEL_1, DAC_ALIGN_12B_R, 0); + HAL_DAC_Start(&handle, DAC_CHANNEL_1); + dac_ramp(0, quiescent_value >> 4); + #endif +} + +bool common_hal_audioio_audioout_deinited(audioio_audioout_obj_t *self) { + return self->left_channel == NULL; +} + +void common_hal_audioio_audioout_deinit(audioio_audioout_obj_t *self) { + if (common_hal_audioio_audioout_deinited(self)) { + return; + } + + common_hal_audioio_audioout_stop(self); + + // Ramp DAC back to zero before disconnecting. + dac_ramp(self->quiescent_value >> 4, 0); + HAL_DAC_Stop(&handle, DAC_CHANNEL_1); + + // Restore channels to no-trigger mode so AnalogOut can use them again. + DAC_ChannelConfTypeDef ch_cfg = {0}; + ch_cfg.DAC_Trigger = DAC_TRIGGER_NONE; + ch_cfg.DAC_OutputBuffer = DAC_OUTPUTBUFFER_ENABLE; + HAL_DAC_ConfigChannel(&handle, &ch_cfg, DAC_CHANNEL_1); + if (self->right_channel != NULL) { + HAL_DAC_Stop(&handle, DAC_CHANNEL_2); + HAL_DAC_ConfigChannel(&handle, &ch_cfg, DAC_CHANNEL_2); + reset_pin_number(self->right_channel->port, self->right_channel->number); + self->right_channel = NULL; + } + + // Release the left pin. Let AnalogOut manage DAC clock disable. + reset_pin_number(self->left_channel->port, self->left_channel->number); + self->left_channel = NULL; +} + +void common_hal_audioio_audioout_play(audioio_audioout_obj_t *self, + mp_obj_t sample, bool loop) { + // The shared-bindings layer guards every entry point with + // check_for_deinit, so a deinited self can't reach this function. + common_hal_audioio_audioout_stop(self); + + // Extract sample format metadata via the canonical accessors so the + // shared sample-protocol contract is honoured. + audiosample_base_t *base = audiosample_check(sample); + self->bytes_per_sample = audiosample_get_bits_per_sample(base) / 8; + self->samples_signed = base->samples_signed; + self->channel_count = audiosample_get_channel_count(base); + uint32_t sample_rate = audiosample_get_sample_rate(base); + mp_arg_validate_int_min(sample_rate, 1, MP_QSTR_sample_rate); + mp_arg_validate_int_max(sample_rate, AUDIOOUT_MAX_SAMPLE_RATE, MP_QSTR_sample_rate); + + self->sample = sample; + self->loop = loop; + self->stopping = false; + self->paused = false; + self->playing = false; + self->halves_to_fill = 0; + self->src_ptr = NULL; + self->src_remaining_len = 0; + self->src_done = false; + + // Allocate DMA circular buffer(s). m_malloc_without_collect avoids + // triggering a GC cycle while the DAC is mid-configure; m_malloc itself + // raises on failure so no null check is needed. + // + // NOTE: ports/atmel-samd uses plain m_malloc for its audio_dma scratch + // buffers — the same GC-during-fill risk applies and should be migrated + // to m_malloc_without_collect for symmetry with espressif and stm. + self->dma_buffer = (uint16_t *)m_malloc_without_collect( + AUDIOOUT_DMA_BUFFER_SAMPLES * sizeof(uint16_t)); + if (self->right_channel != NULL) { + self->dma_buffer_r = (uint16_t *)m_malloc_without_collect( + AUDIOOUT_DMA_BUFFER_SAMPLES * sizeof(uint16_t)); + } + + // Pre-fill both halves before starting DMA. single_channel_output is + // true when this AudioOut renders only one DAC channel; for stereo + // output we want the audiocore to deliver interleaved frames. + bool single_channel_output = (self->right_channel == NULL); + audiosample_reset_buffer(sample, single_channel_output, 0); + load_dma_buffer_half(self, 0); + load_dma_buffer_half(self, 1); + + // Ramp from quiescent to the first sample so the transition into + // DMA-driven output is glitch-free. The DAC is still in single-mode + // (DAC_TRIGGER_NONE) at this point, set up by construct() / stop(), + // so HAL_DAC_SetValue takes effect immediately. After the ramp the + // pin is sitting at exactly dma_buffer[0], which is also the first + // value the timer-triggered DMA will latch. + uint16_t quiescent_12 = self->quiescent_value >> 4; + dac_ramp_channel(DAC_CHANNEL_1, quiescent_12, self->dma_buffer[0]); + if (self->right_channel != NULL) { + // CH2 was not started in construct(), so it has been outputting + // its reset value (0). Ramp from there. + dac_ramp_channel(DAC_CHANNEL_2, 0, self->dma_buffer_r[0]); + } + + // --- TIM6 setup --- + // TIM6 is a basic timer on APB1. It is not managed by the common timer + // infrastructure (stm_peripherals_find_timer etc.) because it has no GPIO + // pins and is reserved for DAC use (mcu_tim_banks[5] == NULL). + __HAL_RCC_TIM6_CLK_ENABLE(); + + uint32_t tim6_clk = get_tim6_freq(); + // Round to nearest, not truncate, so the realised sample rate is the + // closest TIM6 division to the requested rate. + // NOTE: a sweep audit on atmel-samd (Circuit Playground Express) shows a + // constant -3.4 cent frequency bias across all tones, consistent with a + // truncating period calculation there. The same round-to-nearest fix + // would likely tighten frequency accuracy on that port too. + uint32_t period = (tim6_clk + sample_rate / 2) / sample_rate; + if (period < 2) { + period = 2; + } + period -= 1; + + tim6_handle.Instance = TIM6; + tim6_handle.Init.Prescaler = 0; + tim6_handle.Init.CounterMode = TIM_COUNTERMODE_UP; + tim6_handle.Init.Period = period; + tim6_handle.Init.ClockDivision = TIM_CLOCKDIVISION_DIV1; + tim6_handle.Init.AutoReloadPreload = TIM_AUTORELOAD_PRELOAD_DISABLE; + if (HAL_TIM_Base_Init(&tim6_handle) != HAL_OK) { + mp_raise_RuntimeError_varg(MP_ERROR_TEXT("%q init failed"), MP_QSTR_TIM6); + } + + // TRGO = Update event → triggers DAC conversion each period. + TIM_MasterConfigTypeDef master_cfg = {0}; + master_cfg.MasterOutputTrigger = TIM_TRGO_UPDATE; + master_cfg.MasterSlaveMode = TIM_MASTERSLAVEMODE_DISABLE; + if (HAL_TIMEx_MasterConfigSynchronization(&tim6_handle, &master_cfg) != HAL_OK) { + mp_raise_RuntimeError_varg(MP_ERROR_TEXT("%q init failed"), MP_QSTR_TIM6); + } + // NOTE: ports/atmel-samd's audio_dma_setup_playback handles AUDIO_DMA_OK + // and two specific error codes but lets any other non-OK return fall + // through silently — worth tightening there to mirror this raise-on-fail + // pattern. + + // --- DAC channel reconfiguration for DMA-triggered mode --- + // Switch the trigger source to TIM6 *without* disabling the DAC channel. + // HAL_DAC_Stop would disable the channel and momentarily drop the output + // pin to 0 V — audible as a pop between samples. + DAC_ChannelConfTypeDef ch_cfg = {0}; + ch_cfg.DAC_Trigger = DAC_TRIGGER_T6_TRGO; + ch_cfg.DAC_OutputBuffer = DAC_OUTPUTBUFFER_ENABLE; + HAL_DAC_ConfigChannel(&handle, &ch_cfg, DAC_CHANNEL_1); + if (self->right_channel != NULL) { + HAL_DAC_ConfigChannel(&handle, &ch_cfg, DAC_CHANNEL_2); + } + // Reset HAL state from BUSY (set by Start) back to READY so + // HAL_DAC_Start_DMA below doesn't reject the request. + handle.State = HAL_DAC_STATE_READY; + + // --- DMA1 Stream5 Channel7 setup (DAC CH1, left) --- + __HAL_RCC_DMA1_CLK_ENABLE(); + + DMA_HandleTypeDef *hdma = &self->dma_handle_l; + memset(hdma, 0, sizeof(*hdma)); + hdma->Instance = DMA1_Stream5; + hdma->Init.Channel = DMA_CHANNEL_7; + hdma->Init.Direction = DMA_MEMORY_TO_PERIPH; + hdma->Init.PeriphInc = DMA_PINC_DISABLE; + hdma->Init.MemInc = DMA_MINC_ENABLE; + hdma->Init.PeriphDataAlignment = DMA_PDATAALIGN_HALFWORD; + hdma->Init.MemDataAlignment = DMA_MDATAALIGN_HALFWORD; + hdma->Init.Mode = DMA_CIRCULAR; + hdma->Init.Priority = DMA_PRIORITY_VERY_HIGH; + hdma->Init.FIFOMode = DMA_FIFOMODE_DISABLE; + if (HAL_DMA_Init(hdma) != HAL_OK) { + mp_raise_RuntimeError_varg(MP_ERROR_TEXT("%q init failed"), MP_QSTR_DMA); + } + __HAL_LINKDMA(&handle, DMA_Handle1, *hdma); + + HAL_NVIC_SetPriority(DMA1_Stream5_IRQn, 6, 0); + NVIC_ClearPendingIRQ(DMA1_Stream5_IRQn); + HAL_NVIC_EnableIRQ(DMA1_Stream5_IRQn); + + // --- DMA1 Stream6 Channel7 setup (DAC CH2, right) --- + if (self->right_channel != NULL) { + DMA_HandleTypeDef *hdma_r = &self->dma_handle_r; + memset(hdma_r, 0, sizeof(*hdma_r)); + hdma_r->Instance = DMA1_Stream6; + hdma_r->Init.Channel = DMA_CHANNEL_7; + hdma_r->Init.Direction = DMA_MEMORY_TO_PERIPH; + hdma_r->Init.PeriphInc = DMA_PINC_DISABLE; + hdma_r->Init.MemInc = DMA_MINC_ENABLE; + hdma_r->Init.PeriphDataAlignment = DMA_PDATAALIGN_HALFWORD; + hdma_r->Init.MemDataAlignment = DMA_MDATAALIGN_HALFWORD; + hdma_r->Init.Mode = DMA_CIRCULAR; + hdma_r->Init.Priority = DMA_PRIORITY_VERY_HIGH; + hdma_r->Init.FIFOMode = DMA_FIFOMODE_DISABLE; + if (HAL_DMA_Init(hdma_r) != HAL_OK) { + mp_raise_RuntimeError_varg(MP_ERROR_TEXT("%q init failed"), MP_QSTR_DMA); + } + __HAL_LINKDMA(&handle, DMA_Handle2, *hdma_r); + + HAL_NVIC_SetPriority(DMA1_Stream6_IRQn, 6, 0); + NVIC_ClearPendingIRQ(DMA1_Stream6_IRQn); + HAL_NVIC_EnableIRQ(DMA1_Stream6_IRQn); + } + + // --- Start DMA transfer(s) then timer --- + active_audioout = self; + + if (HAL_DAC_Start_DMA(&handle, DAC_CHANNEL_1, + (uint32_t *)self->dma_buffer, + AUDIOOUT_DMA_BUFFER_SAMPLES, + DAC_ALIGN_12B_R) != HAL_OK) { + active_audioout = NULL; + HAL_NVIC_DisableIRQ(DMA1_Stream5_IRQn); + if (self->right_channel != NULL) { + HAL_NVIC_DisableIRQ(DMA1_Stream6_IRQn); + m_free(self->dma_buffer_r); + self->dma_buffer_r = NULL; + } + m_free(self->dma_buffer); + self->dma_buffer = NULL; + mp_raise_RuntimeError_varg(MP_ERROR_TEXT("%q init failed"), MP_QSTR_DAC); + } + + if (self->right_channel != NULL) { + if (HAL_DAC_Start_DMA(&handle, DAC_CHANNEL_2, + (uint32_t *)self->dma_buffer_r, + AUDIOOUT_DMA_BUFFER_SAMPLES, + DAC_ALIGN_12B_R) != HAL_OK) { + active_audioout = NULL; + HAL_DAC_Stop_DMA(&handle, DAC_CHANNEL_1); + HAL_NVIC_DisableIRQ(DMA1_Stream5_IRQn); + HAL_NVIC_DisableIRQ(DMA1_Stream6_IRQn); + m_free(self->dma_buffer); + self->dma_buffer = NULL; + m_free(self->dma_buffer_r); + self->dma_buffer_r = NULL; + mp_raise_RuntimeError_varg(MP_ERROR_TEXT("%q init failed"), MP_QSTR_DAC); + } + } + + HAL_TIM_Base_Start(&tim6_handle); + self->playing = true; +} + +void common_hal_audioio_audioout_stop(audioio_audioout_obj_t *self) { + if (active_audioout != self) { + return; + } + + // Stop the sample clock first so no more DMA requests are generated. + TIM6->CR1 &= ~TIM_CR1_CEN; + + // Switch the DAC channels to no-trigger mode while leaving them enabled. + // This is the key to a click-free stop: HAL_DAC_Stop_DMA / HAL_DAC_Stop + // disable the channel, which briefly pulls the output pin to 0 V before + // the ramp can run. Reconfiguring the trigger only keeps the channel + // enabled; the DAC keeps holding its last DHR value while DMA is aborted. + DAC_ChannelConfTypeDef ch_cfg = {0}; + ch_cfg.DAC_Trigger = DAC_TRIGGER_NONE; + ch_cfg.DAC_OutputBuffer = DAC_OUTPUTBUFFER_ENABLE; + HAL_DAC_ConfigChannel(&handle, &ch_cfg, DAC_CHANNEL_1); + if (self->dma_buffer_r) { + HAL_DAC_ConfigChannel(&handle, &ch_cfg, DAC_CHANNEL_2); + } + + // Capture the last DAC output now that no further DMA writes can land. + uint16_t last_l = (uint16_t)(DAC->DOR1 & 0xFFF); + uint16_t last_r = self->dma_buffer_r ? (uint16_t)(DAC->DOR2 & 0xFFF) : 0; + uint16_t quiescent_12 = self->quiescent_value >> 4; + + // Abort DMA without disabling the DAC channels (HAL_DAC_Stop_DMA would). + HAL_DMA_Abort(&self->dma_handle_l); + HAL_NVIC_DisableIRQ(DMA1_Stream5_IRQn); + NVIC_ClearPendingIRQ(DMA1_Stream5_IRQn); + if (self->dma_buffer_r) { + HAL_DMA_Abort(&self->dma_handle_r); + HAL_NVIC_DisableIRQ(DMA1_Stream6_IRQn); + NVIC_ClearPendingIRQ(DMA1_Stream6_IRQn); + m_free(self->dma_buffer_r); + self->dma_buffer_r = NULL; + } + + // Free the left DMA buffer. + if (self->dma_buffer) { + m_free(self->dma_buffer); + self->dma_buffer = NULL; + } + + // Ramp left channel from last sample back to quiescent. + dac_ramp_channel(DAC_CHANNEL_1, last_l, quiescent_12); + + // Ramp right channel back to 0 (its reset value) before disabling it, + // so the next play() can ramp cleanly from 0 again. + if (self->right_channel != NULL) { + dac_ramp_channel(DAC_CHANNEL_2, last_r, 0); + HAL_DAC_Stop(&handle, DAC_CHANNEL_2); + } + + self->sample = MP_OBJ_NULL; + self->stopping = false; + self->paused = false; + self->playing = false; + active_audioout = NULL; + + __HAL_RCC_TIM6_CLK_DISABLE(); +} + +bool common_hal_audioio_audioout_get_playing(audioio_audioout_obj_t *self) { + return active_audioout == self && self->playing; +} + +void common_hal_audioio_audioout_pause(audioio_audioout_obj_t *self) { + if (active_audioout != self) { + return; + } + self->paused = true; + // Pause the sample clock; DMA remains armed but no new triggers fire. + TIM6->CR1 &= ~TIM_CR1_CEN; +} + +void common_hal_audioio_audioout_resume(audioio_audioout_obj_t *self) { + if (active_audioout != self || !self->paused) { + return; + } + self->paused = false; + // Restart the sample clock. + TIM6->CR1 |= TIM_CR1_CEN; +} + +bool common_hal_audioio_audioout_get_paused(audioio_audioout_obj_t *self) { + // Match espressif's convention: paused only reports true while a play() + // session is active, so a stale flag from a previous session can never + // leak through. + // + // NOTE: ports/atmel-samd delegates to audio_dma_get_paused() and does + // not gate on a "playing" state — it relies on the DMA hardware staying + // quiescent after stop. Worth aligning to the espressif/stm convention. + return self->playing && self->paused; +} diff --git a/ports/stm/common-hal/audioio/AudioOut.h b/ports/stm/common-hal/audioio/AudioOut.h new file mode 100644 index 00000000000..a519d5f3869 --- /dev/null +++ b/ports/stm/common-hal/audioio/AudioOut.h @@ -0,0 +1,71 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" +#include "common-hal/microcontroller/Pin.h" +#include "supervisor/background_callback.h" +#include STM32_HAL_H + +// Total DMA circular buffer size in 16-bit samples. +// Split into two halves; one half plays while the other is refilled. +// 4096-sample halves at 22050 Hz = ~186 ms per half-buffer interrupt, +// giving the background callback enough headroom to absorb SDIO cluster +// reads, NeoPixel updates, and other main-loop stalls without underrun. +#define AUDIOOUT_DMA_BUFFER_SAMPLES 8192 +#define AUDIOOUT_DMA_HALF_SAMPLES (AUDIOOUT_DMA_BUFFER_SAMPLES / 2) + +typedef struct { + mp_obj_base_t base; + + // Left channel pin (PA04 = DAC_CH1). NULL when deinited. + const mcu_pin_obj_t *left_channel; + // Right channel pin (PA05 = DAC_CH2). NULL when mono. + const mcu_pin_obj_t *right_channel; + + // DMA handles. The DAC handle itself is the shared file-scope handle + // from AnalogOut.c; we link these to it via __HAL_LINKDMA. + DMA_HandleTypeDef dma_handle_l; // DMA1 Stream5 Channel7 (DAC CH1, left) + DMA_HandleTypeDef dma_handle_r; // DMA1 Stream6 Channel7 (DAC CH2, right) + + // Circular DMA buffers: AUDIOOUT_DMA_BUFFER_SAMPLES uint16_t elements each, + // allocated on play() and freed on stop(). + uint16_t *dma_buffer; // left (CH1) + uint16_t *dma_buffer_r; // right (CH2), NULL when mono + + // Current audio sample object being played. + mp_obj_t sample; + bool loop; + bool playing; + + // Set from ISR context to request a clean stop via background callback. + volatile bool stopping; + bool paused; + + // Sample format metadata, populated at play() time. + uint8_t bytes_per_sample; // 1 (8-bit) or 2 (16-bit) + bool samples_signed; + uint8_t channel_count; // 1 = mono, 2 = stereo + uint16_t quiescent_value; // 16-bit resting value (default 0x8000) + + // Background callback queued from DMA ISR, processed in main loop. + background_callback_t callback; + + // Bitmask of DMA halves pending refill: bit0 = lower, bit1 = upper. + // Set from half/full IRQ, drained by the background callback. A bitmask + // (not a scalar) so a back-to-back half+full pair queues both fills even + // if the callback hasn't run yet. + volatile uint8_t halves_to_fill; + + // Source buffer position tracking. Allows consuming large source buffers + // (e.g. RawSample > 256 samples) across multiple DMA half-fills. + const uint8_t *src_ptr; // current read position in source buffer + uint32_t src_remaining_len; // bytes remaining in current source buffer + bool src_done; // GET_BUFFER_DONE received for current buffer +} audioio_audioout_obj_t; + +// Called from reset_port() to stop any active playback on soft-reset. diff --git a/ports/stm/common-hal/audioio/__init__.c b/ports/stm/common-hal/audioio/__init__.c new file mode 100644 index 00000000000..ebf626832f6 --- /dev/null +++ b/ports/stm/common-hal/audioio/__init__.c @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +// No audioio module functions. diff --git a/ports/stm/common-hal/audiopwmio/PWMAudioOut.c b/ports/stm/common-hal/audiopwmio/PWMAudioOut.c index 475f3beded8..0bfd524675c 100644 --- a/ports/stm/common-hal/audiopwmio/PWMAudioOut.c +++ b/ports/stm/common-hal/audiopwmio/PWMAudioOut.c @@ -8,9 +8,15 @@ #include "py/runtime.h" #include "common-hal/audiopwmio/PWMAudioOut.h" #include "shared-bindings/audiopwmio/PWMAudioOut.h" +#include "shared-bindings/microcontroller/Pin.h" #include "timers.h" +// An entry is a number of sample ticks, after which the pin toggles. A HOLD entry +// doesn't toggle: it lets a span without a transition, such as silence, be queued. +#define HOLD (0x8000) +#define DURATION_MASK (0x7fff) + // TODO: support multiple concurrently active outputs. static TIM_HandleTypeDef tim_handle; static audiopwmio_pwmaudioout_obj_t *active_audio = NULL; @@ -39,9 +45,9 @@ static void start_timer(audiopwmio_pwmaudioout_obj_t *self) { 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]]; + self->period = self->buffer[0][self->buffer_ptr[0]] & DURATION_MASK; + if (self->pin[1] && self->period > (self->buffer[1][self->buffer_ptr[1]] & DURATION_MASK)) { + self->period = self->buffer[1][self->buffer_ptr[1]] & DURATION_MASK; } // Set the new period @@ -55,6 +61,22 @@ static void start_timer(audiopwmio_pwmaudioout_obj_t *self) { __HAL_TIM_ENABLE_IT(&tim_handle, TIM_IT_UPDATE); } +static void queue_entry(audiopwmio_pwmaudioout_obj_t *self, int8_t channel, uint16_t entry, bool replicate) { + self->buffer[channel][self->buffer_length[channel]++] = entry; + if (replicate) { + self->buffer[1 - channel][self->buffer_length[1 - channel]++] = entry; + } +} + +// Queue a channel's span so far as a HOLD entry. Two ticks stay pending, so a +// transition on the next sample is queued as before. +static void hold_span(audiopwmio_pwmaudioout_obj_t *self, int8_t channel, bool replicate) { + if (self->len[channel] > 2) { + queue_entry(self, channel, HOLD | (self->len[channel] - 2), replicate); + self->len[channel] = 2; + } +} + static bool fill_buffers(audiopwmio_pwmaudioout_obj_t *self) { // Naive PCM-to-PWM conversion int16_t threshold = 0x666; // 0.05; TODO: make configurable @@ -99,15 +121,23 @@ static bool fill_buffers(audiopwmio_pwmaudioout_obj_t *self) { 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]; - } + queue_entry(self, channel, self->len[channel], replicate); self->len[channel] = 0; } self->pos[channel] = new_pos; } - self->len[channel]++; + if (++self->len[channel] == DURATION_MASK) { + hold_span(self, channel, replicate); + } + } + } + // A block without a transition, such as silence, is queued as it is, so + // a silent source doesn't keep this loop reading forever. + if (get_buffer_result == GET_BUFFER_MORE_DATA) { + for (int8_t channel = 0; channel < effective_channels; channel++) { + if (!self->buffer_length[channel]) { + hold_span(self, channel, replicate); + } } } } while (get_buffer_result == GET_BUFFER_MORE_DATA && @@ -116,10 +146,7 @@ static bool fill_buffers(audiopwmio_pwmaudioout_obj_t *self) { 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]; - } + queue_entry(self, channel, self->len[channel], replicate); } if (self->loop) { @@ -153,17 +180,23 @@ static void pwmaudioout_event_handler(void) { 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); + uint16_t *entry = &active_audio->buffer[0][active_audio->buffer_ptr[0]]; + *entry -= active_audio->period; + if (!(*entry & DURATION_MASK)) { + if (!(*entry & HOLD)) { + 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); + entry = &active_audio->buffer[1][active_audio->buffer_ptr[1]]; + *entry -= active_audio->period; + if (!(*entry & DURATION_MASK)) { + if (!(*entry & HOLD)) { + toggle_pin(1); + } if (++(active_audio->buffer_ptr[1]) >= active_audio->buffer_length[1]) { refill = true; } @@ -191,6 +224,11 @@ static void pwmaudioout_event_handler(void) { } } +static void mark_deinit(audiopwmio_pwmaudioout_obj_t *self) { + self->pin[0] = NULL; + self->pin[1] = NULL; +} + // 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) { @@ -199,8 +237,10 @@ void common_hal_audiopwmio_pwmaudioout_construct(audiopwmio_pwmaudioout_obj_t *s self->pin[0] = left_channel; self->pin[1] = right_channel; set_drive_mode(left_channel, GPIO_MODE_OUTPUT_PP); + common_hal_mcu_pin_claim(left_channel); if (right_channel) { set_drive_mode(right_channel, GPIO_MODE_OUTPUT_PP); + common_hal_mcu_pin_claim(right_channel); } self->buffer[0] = NULL; @@ -246,8 +286,9 @@ void common_hal_audiopwmio_pwmaudioout_deinit(audiopwmio_pwmaudioout_obj_t *self free_buffers(self); - self->pin[0] = 0; - self->pin[1] = 0; + common_hal_reset_pin(self->pin[0]); + common_hal_reset_pin(self->pin[1]); + mark_deinit(self); } void common_hal_audiopwmio_pwmaudioout_play(audiopwmio_pwmaudioout_obj_t *self, mp_obj_t sample, bool loop) { @@ -255,6 +296,9 @@ void common_hal_audiopwmio_pwmaudioout_play(audiopwmio_pwmaudioout_obj_t *self, if (active_audio) { mp_raise_RuntimeError(MP_ERROR_TEXT("Another PWMAudioOut is already active")); // TODO } + + audiosample_check(sample); + self->sample = sample; self->loop = loop; @@ -279,14 +323,14 @@ void common_hal_audiopwmio_pwmaudioout_play(audiopwmio_pwmaudioout_obj_t *self, uint16_t buffer_length = (uint16_t)max_buffer_length / self->bytes_per_sample; size_t buffer_size = buffer_length * sizeof(uint16_t); - self->buffer[0] = m_malloc(buffer_size); + self->buffer[0] = m_malloc_without_collect(buffer_size); #if MICROPY_MALLOC_USES_ALLOCATED_SIZE self->buffer_size[0] = buffer_size; #endif self->buffer_ptr[0] = self->buffer_length[0] = 0; if (self->pin[1]) { - self->buffer[1] = m_malloc(buffer_size); + self->buffer[1] = m_malloc_without_collect(buffer_size); #if MICROPY_MALLOC_USES_ALLOCATED_SIZE self->buffer_size[1] = buffer_size; #endif @@ -342,7 +386,6 @@ void common_hal_audiopwmio_pwmaudioout_stop(audiopwmio_pwmaudioout_obj_t *self) tim_handle.Instance->CR1 &= ~TIM_CR1_CEN; stm_peripherals_timer_free(tim_handle.Instance); - active_audio = NULL; self->stopping = false; self->paused = false; @@ -352,6 +395,8 @@ void common_hal_audiopwmio_pwmaudioout_stop(audiopwmio_pwmaudioout_obj_t *self) set_pin(1, GPIO_PIN_RESET); } + active_audio = NULL; + // Cannot free buffers here because we may be called from // the interrupt handler, and the heap is not reentrant. } diff --git a/ports/stm/common-hal/busio/I2C.c b/ports/stm/common-hal/busio/I2C.c index e6957989cc7..ba2109cdd42 100644 --- a/ports/stm/common-hal/busio/I2C.c +++ b/ports/stm/common-hal/busio/I2C.c @@ -53,6 +53,17 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, // Ensure the object starts in its deinit state. common_hal_busio_i2c_mark_deinit(self); + #if (CPY_STM32H7 || CPY_STM32F7 || CPY_STM32L4) + uint32_t timing; + if (frequency == 400000) { + timing = CPY_I2CFAST_TIMINGR; + } else if (frequency == 100000) { + timing = CPY_I2CSTANDARD_TIMINGR; + } else { + mp_arg_error_invalid(MP_QSTR_frequency); + } + #endif + // Match pins to I2C objects I2C_TypeDef *I2Cx; uint8_t sda_len = MP_ARRAY_SIZE(mcu_i2c_sda_list); @@ -118,13 +129,7 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, // Handle the HAL handle differences #if (CPY_STM32H7 || CPY_STM32F7 || CPY_STM32L4) - if (frequency == 400000) { - self->handle.Init.Timing = CPY_I2CFAST_TIMINGR; - } else if (frequency == 100000) { - self->handle.Init.Timing = CPY_I2CSTANDARD_TIMINGR; - } else { - mp_arg_error_invalid(MP_QSTR_frequency); - } + self->handle.Init.Timing = timing; #else self->handle.Init.ClockSpeed = frequency; self->handle.Init.DutyCycle = I2C_DUTYCYCLE_2; @@ -139,6 +144,7 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, self->handle.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE; self->handle.State = HAL_I2C_STATE_RESET; if (HAL_I2C_Init(&(self->handle)) != HAL_OK) { + common_hal_busio_i2c_deinit(self); mp_raise_RuntimeError(MP_ERROR_TEXT("I2C init error")); } common_hal_mcu_pin_claim(sda); @@ -152,10 +158,6 @@ void common_hal_busio_i2c_construct(busio_i2c_obj_t *self, HAL_NVIC_EnableIRQ(self->irq); } -void common_hal_busio_i2c_never_reset(busio_i2c_obj_t *self) { - never_reset_pin_number(self->scl->pin->port, self->scl->pin->number); - never_reset_pin_number(self->sda->pin->port, self->sda->pin->number); -} bool common_hal_busio_i2c_deinited(busio_i2c_obj_t *self) { return self->sda == NULL; @@ -168,6 +170,7 @@ void common_hal_busio_i2c_deinit(busio_i2c_obj_t *self) { i2c_clock_disable(1 << (self->sda->periph_index - 1)); reserved_i2c[self->sda->periph_index - 1] = false; + MP_STATE_PORT(cpy_i2c_obj_all)[self->sda->periph_index - 1] = NULL; reset_pin_number(self->sda->pin->port, self->sda->pin->number); reset_pin_number(self->scl->pin->port, self->scl->pin->number); @@ -176,6 +179,7 @@ void common_hal_busio_i2c_deinit(busio_i2c_obj_t *self) { void common_hal_busio_i2c_mark_deinit(busio_i2c_obj_t *self) { self->sda = NULL; + self->scl = NULL; } bool common_hal_busio_i2c_probe(busio_i2c_obj_t *self, uint8_t addr) { @@ -212,7 +216,7 @@ void common_hal_busio_i2c_unlock(busio_i2c_obj_t *self) { self->has_lock = false; } -static uint8_t _common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, +static mp_negative_errno_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; if (!transmit_stop_bit) { @@ -234,19 +238,19 @@ static uint8_t _common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, 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; + return result == HAL_OK ? 0 : -MP_EIO; } -uint8_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, +mp_negative_errno_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, const uint8_t *data, size_t len) { return _common_hal_busio_i2c_write(self, addr, data, len, true); } -uint8_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t addr, +mp_negative_errno_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t addr, 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; + == HAL_OK ? 0 : -MP_EIO; } else { HAL_StatusTypeDef result = HAL_I2C_Master_Seq_Receive_IT(&(self->handle), (uint16_t)(addr << 1), (uint8_t *)data, @@ -259,9 +263,9 @@ uint8_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t addr, } } -uint8_t common_hal_busio_i2c_write_read(busio_i2c_obj_t *self, uint16_t addr, +mp_negative_errno_t common_hal_busio_i2c_write_read(busio_i2c_obj_t *self, uint16_t addr, uint8_t *out_data, size_t out_len, uint8_t *in_data, size_t in_len) { - uint8_t result = _common_hal_busio_i2c_write(self, addr, out_data, out_len, false); + mp_negative_errno_t result = _common_hal_busio_i2c_write(self, addr, out_data, out_len, false); if (result != 0) { return result; } diff --git a/ports/stm/common-hal/busio/SPI.c b/ports/stm/common-hal/busio/SPI.c index 98696271ca9..42213457022 100644 --- a/ports/stm/common-hal/busio/SPI.c +++ b/ports/stm/common-hal/busio/SPI.c @@ -19,7 +19,6 @@ #define MAX_SPI 6 static bool reserved_spi[MAX_SPI]; -static bool never_reset_spi[MAX_SPI]; #define ALL_CLOCKS 0xFF static void spi_clock_enable(uint8_t mask); @@ -76,18 +75,6 @@ static uint32_t stm32_baud_to_spi_div(uint32_t baudrate, uint16_t *prescaler, ui return SPI_BAUDRATEPRESCALER_256; } -void spi_reset(void) { - uint16_t never_reset_mask = 0x00; - for (int i = 0; i < MAX_SPI; i++) { - if (!never_reset_spi[i]) { - reserved_spi[i] = false; - } else { - never_reset_mask |= 1 << i; - } - } - spi_clock_disable(ALL_CLOCKS & ~(never_reset_mask)); -} - 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; i < sz; i++, table++) { if (periph_index == table->periph_index && pin == table->pin) { @@ -149,6 +136,10 @@ 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, bool half_duplex) { + // Ensure the object starts in its deinit state before check_pins sets + // self->sck, self->mosi, and self->miso. + common_hal_busio_spi_mark_deinit(self); + int periph_index = check_pins(self, sck, mosi, miso); SPI_TypeDef *SPIx = mcu_spi_banks[periph_index - 1]; @@ -204,6 +195,7 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, self->handle.Init.CRCCalculation = SPI_CRCCALCULATION_DISABLE; self->handle.Init.CRCPolynomial = 10; if (HAL_SPI_Init(&self->handle) != HAL_OK) { + common_hal_busio_spi_deinit(self); mp_raise_ValueError(MP_ERROR_TEXT("SPI init error")); } self->baudrate = default_baudrate; @@ -222,29 +214,23 @@ void common_hal_busio_spi_construct(busio_spi_obj_t *self, } } -void common_hal_busio_spi_never_reset(busio_spi_obj_t *self) { - - never_reset_spi[self->sck->periph_index - 1] = true; - never_reset_pin_number(self->sck->pin->port, self->sck->pin->number); - if (self->mosi != NULL) { - never_reset_pin_number(self->mosi->pin->port, self->mosi->pin->number); - } - if (self->miso != NULL) { - never_reset_pin_number(self->miso->pin->port, self->miso->pin->number); - } -} bool common_hal_busio_spi_deinited(busio_spi_obj_t *self) { return self->sck == NULL; } +void common_hal_busio_spi_mark_deinit(busio_spi_obj_t *self) { + self->sck = NULL; + self->mosi = NULL; + self->miso = NULL; +} + 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)); reserved_spi[self->sck->periph_index - 1] = false; - never_reset_spi[self->sck->periph_index - 1] = false; reset_pin_number(self->sck->pin->port, self->sck->pin->number); if (self->mosi != NULL) { @@ -253,9 +239,7 @@ void common_hal_busio_spi_deinit(busio_spi_obj_t *self) { if (self->miso != NULL) { reset_pin_number(self->miso->pin->port, self->miso->pin->number); } - self->sck = NULL; - self->mosi = NULL; - self->miso = NULL; + common_hal_busio_spi_mark_deinit(self); } bool common_hal_busio_spi_configure(busio_spi_obj_t *self, diff --git a/ports/stm/common-hal/busio/UART.c b/ports/stm/common-hal/busio/UART.c index e44fbc66a6c..c643129dfae 100644 --- a/ports/stm/common-hal/busio/UART.c +++ b/ports/stm/common-hal/busio/UART.c @@ -20,39 +20,15 @@ // 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 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 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 - MP_STATE_PORT(cpy_uart_obj_all)[periph_index] = self; - return mcu_uart_banks[periph_index]; - } else { - if (uart_taken) { - mp_raise_ValueError(MP_ERROR_TEXT("Hardware in use, try alternative pins")); - } else { - raise_ValueError_invalid_pin(); - } - } -} - -void uart_reset(void) { - uint16_t never_reset_mask = 0x00; - for (uint8_t i = 0; i < MAX_UART; i++) { - if (!never_reset_uart[i]) { - reserved_uart[i] = false; - MP_STATE_PORT(cpy_uart_obj_all)[i] = NULL; - } else { - never_reset_mask |= 1 << i; - } - } - uart_clock_disable(ALL_UARTS & ~(never_reset_mask)); +static void mark_deinit(busio_uart_obj_t *self) { + self->tx = NULL; + self->rx = NULL; } void common_hal_busio_uart_construct(busio_uart_obj_t *self, @@ -63,18 +39,22 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, mp_float_t timeout, uint16_t receiver_buffer_size, byte *receiver_buffer, bool sigint_enabled) { - // match pins to UART objects - USART_TypeDef *USARTx = NULL; - - 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 + mark_deinit(self); if ((rts != NULL) || (cts != NULL) || (rs485_dir != NULL) || (rs485_invert == true)) { mp_raise_NotImplementedError(MP_ERROR_TEXT("RS485")); } + mp_arg_validate_length_min(receiver_buffer_size, 1, MP_QSTR_receiver_buffer_size); + mp_arg_validate_int_range(bits, 8, 9, MP_QSTR_bits); + + // match pins to UART objects + const mcu_periph_obj_t *tx_periph = NULL; + const mcu_periph_obj_t *rx_periph = NULL; + 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; + // Can have both pins, or either if ((tx != NULL) && (rx != NULL)) { // normal find loop if both pins exist @@ -90,19 +70,16 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, continue; } // store pins if not - self->tx = &mcu_uart_tx_list[i]; - self->rx = &mcu_uart_rx_list[j]; + tx_periph = &mcu_uart_tx_list[i]; + rx_periph = &mcu_uart_rx_list[j]; break; } } - if (self->tx != NULL) { + if (tx_periph != NULL) { break; } } } - periph_index = self->tx->periph_index - 1; - 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 for (uint i = 0; i < rx_len; i++) { @@ -113,13 +90,10 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, continue; } // store pins if not - self->rx = &mcu_uart_rx_list[i]; + rx_periph = &mcu_uart_rx_list[i]; break; } } - periph_index = self->rx->periph_index - 1; - 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 for (uint i = 0; i < tx_len; i++) { @@ -130,26 +104,46 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, continue; } // store pins if not - self->tx = &mcu_uart_tx_list[i]; + tx_periph = &mcu_uart_tx_list[i]; break; } } - periph_index = self->tx->periph_index - 1; - USARTx = assign_uart_or_throw(self, (self->tx != NULL), - periph_index, uart_taken); } else { // TX and RX are both None. But this is already handled in shared-bindings, so // we won't get here. } - // Other errors - mp_arg_validate_length_min(receiver_buffer_size, 1, MP_QSTR_receiver_buffer_size); - mp_arg_validate_int_range(bits, 8, 9, MP_QSTR_bits); + if ((tx != NULL && tx_periph == NULL) || (rx != NULL && rx_periph == NULL)) { + if (uart_taken) { + mp_raise_ValueError(MP_ERROR_TEXT("Hardware in use, try alternative pins")); + } else { + raise_ValueError_invalid_pin(); + } + } + uint8_t periph_index = (tx_periph != NULL ? tx_periph : rx_periph)->periph_index - 1; // origin 0 corrected + USART_TypeDef *USARTx = mcu_uart_banks[periph_index]; if (USARTx == NULL) { // this can only be hit if the periph file is wrong mp_raise_RuntimeError(MP_ERROR_TEXT("Internal define error")); } + // Init buffer for rx + if (rx_periph != NULL) { + // Use the provided buffer when given. + if (receiver_buffer != NULL) { + ringbuf_init(&self->ringbuf, receiver_buffer, receiver_buffer_size); + } else { + if (!ringbuf_alloc(&self->ringbuf, receiver_buffer_size)) { + m_malloc_fail(receiver_buffer_size); + } + } + } + + self->tx = tx_periph; + self->rx = rx_periph; + // assign a root pointer pointer for IRQ + MP_STATE_PORT(cpy_uart_obj_all)[periph_index] = self; + // GPIO Init GPIO_InitTypeDef GPIO_InitStruct = {0}; if (self->tx != NULL) { @@ -187,20 +181,12 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, self->handle.Init.HwFlowCtl = UART_HWCONTROL_NONE; self->handle.Init.OverSampling = UART_OVERSAMPLING_16; if (HAL_UART_Init(&self->handle) != HAL_OK) { + common_hal_busio_uart_deinit(self); mp_raise_RuntimeError(MP_ERROR_TEXT("UART init")); - } - // Init buffer for rx and claim pins + // claim pins if (self->rx != NULL) { - // Use the provided buffer when given. - if (receiver_buffer != NULL) { - ringbuf_init(&self->ringbuf, receiver_buffer, receiver_buffer_size); - } else { - if (!ringbuf_alloc(&self->ringbuf, receiver_buffer_size)) { - m_malloc_fail(receiver_buffer_size); - } - } common_hal_mcu_pin_claim(rx); } if (self->tx != NULL) { @@ -212,6 +198,7 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, // start the interrupt series if ((HAL_UART_GetState(&self->handle) & HAL_UART_STATE_BUSY_RX) == HAL_UART_STATE_BUSY_RX) { + common_hal_busio_uart_deinit(self); mp_raise_RuntimeError(MP_ERROR_TEXT("Could not start interrupt, RX busy")); } @@ -224,16 +211,6 @@ void common_hal_busio_uart_construct(busio_uart_obj_t *self, errflag = HAL_OK; } -void common_hal_busio_uart_never_reset(busio_uart_obj_t *self) { - for (size_t i = 0; i < MP_ARRAY_SIZE(mcu_uart_banks); i++) { - if (mcu_uart_banks[i] == self->handle.Instance) { - never_reset_uart[i] = true; - never_reset_pin_number(self->tx->pin->port, self->tx->pin->number); - never_reset_pin_number(self->rx->pin->port, self->rx->pin->number); - break; - } - } -} bool common_hal_busio_uart_deinited(busio_uart_obj_t *self) { return self->tx == NULL && self->rx == NULL; @@ -244,24 +221,27 @@ void common_hal_busio_uart_deinit(busio_uart_obj_t *self) { return; } + HAL_NVIC_DisableIRQ(self->irq); 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; + MP_STATE_PORT(cpy_uart_obj_all)[i] = NULL; + // Reset the peripheral and turn its clock back off, matching construct()'s + // uart_clock_enable() for this bank. + uart_clock_disable(1 << i); break; } } if (self->tx) { reset_pin_number(self->tx->pin->port, self->tx->pin->number); - self->tx = NULL; } if (self->rx) { reset_pin_number(self->rx->pin->port, self->rx->pin->number); - self->rx = NULL; } ringbuf_deinit(&self->ringbuf); + mark_deinit(self); } size_t common_hal_busio_uart_read(busio_uart_obj_t *self, uint8_t *data, size_t len, int *errcode) { @@ -602,6 +582,7 @@ static void uart_clock_disable(uint16_t mask) { #endif } + static void uart_assign_irq(busio_uart_obj_t *self, USART_TypeDef *USARTx) { #ifdef USART1 if (USARTx == USART1) { diff --git a/ports/stm/common-hal/busio/UART.h b/ports/stm/common-hal/busio/UART.h index 5df7d457488..c047dbf58d0 100644 --- a/ports/stm/common-hal/busio/UART.h +++ b/ports/stm/common-hal/busio/UART.h @@ -34,5 +34,3 @@ typedef struct { bool sigint_enabled; } busio_uart_obj_t; - -void uart_reset(void); diff --git a/ports/stm/common-hal/canio/CAN.c b/ports/stm/common-hal/canio/CAN.c index 72a74a4b138..5bf65ba6ef7 100644 --- a/ports/stm/common-hal/canio/CAN.c +++ b/ports/stm/common-hal/canio/CAN.c @@ -48,7 +48,7 @@ void common_hal_canio_can_construct(canio_can_obj_t *self, const mcu_pin_obj_t * raise_ValueError_invalid_pin_name(MP_QSTR_rx); } - if (reserved_can[periph_index]) { + if (reserved_can[periph_index - 1]) { mp_raise_ValueError(MP_ERROR_TEXT("Hardware in use, try alternative pins")); } @@ -136,7 +136,11 @@ void common_hal_canio_can_construct(canio_can_obj_t *self, const mcu_pin_obj_t * HAL_CAN_Start(&self->handle); - reserved_can[periph_index] = true; + reserved_can[periph_index - 1] = true; + self->tx_pin = tx; + self->rx_pin = rx; + common_hal_mcu_pin_claim(tx); + common_hal_mcu_pin_claim(rx); } bool common_hal_canio_can_loopback_get(canio_can_obj_t *self) { @@ -257,14 +261,9 @@ void common_hal_canio_can_deinit(canio_can_obj_t *self) { SET_BIT(self->handle.Instance->MCR, CAN_MCR_RESET); while (READ_BIT(self->handle.Instance->MCR, CAN_MCR_RESET)) { } - reserved_can[self->periph_index] = 0; + reserved_can[self->periph_index - 1] = false; + common_hal_reset_pin(self->tx_pin); + common_hal_reset_pin(self->rx_pin); } self->handle.Instance = NULL; } - -void common_hal_canio_reset(void) { - for (size_t i = 0; i < MP_ARRAY_SIZE(mcu_can_banks); i++) { - SET_BIT(mcu_can_banks[i]->MCR, CAN_MCR_RESET); - reserved_can[i] = 0; - } -} diff --git a/ports/stm/common-hal/canio/Listener.c b/ports/stm/common-hal/canio/Listener.c index bafdd4ba2c1..1dbae5455ff 100644 --- a/ports/stm/common-hal/canio/Listener.c +++ b/ports/stm/common-hal/canio/Listener.c @@ -14,6 +14,7 @@ #include "common-hal/canio/__init__.h" #include "common-hal/canio/Listener.h" +#include "shared-bindings/canio/CAN.h" #include "shared-bindings/canio/Listener.h" #include "shared-bindings/util.h" #include "supervisor/shared/tick.h" @@ -160,14 +161,14 @@ static void install_all_match_filter(canio_listener_obj_t *self) { // filter mode: 0 = mask // (this bit should be clear already, we never set it; but just in case) - CLEAR_BIT(self->can->filter_hw->FM1R, bank); + CLEAR_BIT(self->can->filter_hw->FM1R, 1 << bank); // filter scale: 1 = 32 bits - SET_BIT(self->can->filter_hw->FS1R, bank); + SET_BIT(self->can->filter_hw->FS1R, 1 << bank); // fifo assignment: 1 = FIFO 1 if (self->fifo_idx) { - SET_BIT(self->can->filter_hw->FFA1R, bank); + SET_BIT(self->can->filter_hw->FFA1R, 1 << bank); } else { - CLEAR_BIT(self->can->filter_hw->FFA1R, bank); + CLEAR_BIT(self->can->filter_hw->FFA1R, 1 << bank); } // filter activation: 1 = enabled @@ -203,14 +204,11 @@ void set_filters(canio_listener_obj_t *self, size_t nmatch, canio_match_obj_t ** void common_hal_canio_listener_construct(canio_listener_obj_t *self, canio_can_obj_t *can, size_t nmatch, canio_match_obj_t **matches, float timeout) { + int fifo_idx; if (!can->fifo0_in_use) { - self->fifo_idx = 0; - self->rfr = &can->handle.Instance->RF0R; - can->fifo0_in_use = true; + fifo_idx = 0; } else if (!can->fifo1_in_use) { - self->fifo_idx = 1; - self->rfr = &can->handle.Instance->RF1R; - can->fifo1_in_use = true; + fifo_idx = 1; } else { mp_raise_ValueError(MP_ERROR_TEXT("All RX FIFOs in use")); } @@ -219,7 +217,15 @@ void common_hal_canio_listener_construct(canio_listener_obj_t *self, canio_can_o mp_raise_ValueError(MP_ERROR_TEXT("Filters too complex")); } - // Nothing can fail now so it's safe to assign self->can + // Nothing can fail now so it's safe to claim the FIFO and assign self->can + self->fifo_idx = fifo_idx; + if (fifo_idx == 0) { + self->rfr = &can->handle.Instance->RF0R; + can->fifo0_in_use = true; + } else { + self->rfr = &can->handle.Instance->RF1R; + can->fifo1_in_use = true; + } self->can = can; self->mailbox = &can->handle.Instance->sFIFOMailBox[self->fifo_idx]; @@ -285,7 +291,7 @@ mp_obj_t common_hal_canio_listener_receive(canio_listener_obj_t *self) { } void common_hal_canio_listener_deinit(canio_listener_obj_t *self) { - if (self->can) { + if (self->can && !common_hal_canio_can_deinited(self->can)) { clear_filters(self); if (self->fifo_idx == 0) { self->can->fifo0_in_use = false; diff --git a/ports/stm/common-hal/digitalio/DigitalInOut.c b/ports/stm/common-hal/digitalio/DigitalInOut.c index 359e278cb02..989052ad940 100644 --- a/ports/stm/common-hal/digitalio/DigitalInOut.c +++ b/ports/stm/common-hal/digitalio/DigitalInOut.c @@ -21,10 +21,6 @@ #error unknown MCU for DigitalInOut #endif -void common_hal_digitalio_digitalinout_never_reset( - 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) { diff --git a/ports/stm/common-hal/microcontroller/Pin.c b/ports/stm/common-hal/microcontroller/Pin.c index 21c77736d6b..a1b045ebce6 100644 --- a/ports/stm/common-hal/microcontroller/Pin.c +++ b/ports/stm/common-hal/microcontroller/Pin.c @@ -21,6 +21,8 @@ GPIO_TypeDef *ports[] = {GPIOA, GPIOB, GPIOC, GPIOD, GPIOE}; GPIO_TypeDef *ports[] = {GPIOA, GPIOB, GPIOC, GPIOD}; #elif defined(UFQFPN48) GPIO_TypeDef *ports[] = {GPIOA, GPIOB, GPIOC}; +#elif defined(LQFP48) +GPIO_TypeDef *ports[] = {GPIOA, GPIOB, GPIOC}; #else #error Unknown package type #endif @@ -29,17 +31,6 @@ GPIO_TypeDef *ports[] = {GPIOA, GPIOB, GPIOC}; #define GPIO_PORT_COUNT (MP_ARRAY_SIZE(ports)) static uint16_t claimed_pins[GPIO_PORT_COUNT]; -static uint16_t __ALIGNED(4) never_reset_pins[GPIO_PORT_COUNT]; - -void reset_all_pins(void) { - // Reset claimed pins - for (uint8_t i = 0; i < GPIO_PORT_COUNT; i++) { - claimed_pins[i] = never_reset_pins[i]; - } - for (uint8_t i = 0; i < GPIO_PORT_COUNT; i++) { - HAL_GPIO_DeInit(ports[i], ~never_reset_pins[i]); - } -} // Mark pin as free and return it to a quiescent state. void reset_pin_number(uint8_t pin_port, uint8_t pin_number) { @@ -52,22 +43,9 @@ void reset_pin_number(uint8_t pin_port, uint8_t pin_number) { } // Clear claimed bit & reset claimed_pins[pin_port] &= ~(1 << pin_number); - never_reset_pins[pin_port] &= ~(1 << pin_number); HAL_GPIO_DeInit(ports[pin_port], 1 << pin_number); } -void never_reset_pin_number(uint8_t pin_port, uint8_t pin_number) { - if (pin_number == NO_PIN) { - return; - } - never_reset_pins[pin_port] |= 1 << pin_number; - // Make sure never reset pins are also always claimed - claimed_pins[pin_port] |= 1 << pin_number; -} - -void common_hal_never_reset_pin(const mcu_pin_obj_t *pin) { - never_reset_pin_number(pin->port, pin->number); -} void common_hal_reset_pin(const mcu_pin_obj_t *pin) { if (pin == NULL) { diff --git a/ports/stm/common-hal/microcontroller/Pin.h b/ports/stm/common-hal/microcontroller/Pin.h index a1d347f26da..f1b54edc81f 100644 --- a/ports/stm/common-hal/microcontroller/Pin.h +++ b/ports/stm/common-hal/microcontroller/Pin.h @@ -10,12 +10,14 @@ #include "peripherals/pins.h" -void reset_all_pins(void); +void common_hal_reset_pin(const mcu_pin_obj_t *pin); // 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_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); uint16_t pin_mask(uint8_t pin_number); + +uint8_t common_hal_mcu_pin_number(const mcu_pin_obj_t *pin); +void common_hal_mcu_pin_claim(const mcu_pin_obj_t *pin); diff --git a/ports/stm/common-hal/microcontroller/Processor.c b/ports/stm/common-hal/microcontroller/Processor.c index 0781f422ee1..d6ef0a14dcf 100644 --- a/ports/stm/common-hal/microcontroller/Processor.c +++ b/ports/stm/common-hal/microcontroller/Processor.c @@ -126,9 +126,11 @@ void common_hal_mcu_processor_get_uid(uint8_t raw_id[]) { mcu_reset_reason_t common_hal_mcu_processor_get_reset_reason(void) { #if CIRCUITPY_ALARM - if (alarm_get_wakeup_cause() != STM_WAKEUP_UNDEF) { - return RESET_REASON_DEEP_SLEEP_ALARM; + // Only a wake from a real deep sleep counts, not an alarm that fired since boot: main.c + // goes straight into a real deep sleep, even with USB connected, when this says so. + if (alarm_woke_from_true_deep_sleep()) { + return MCU_RESET_REASON_DEEP_SLEEP_ALARM; } #endif - return RESET_REASON_UNKNOWN; + return MCU_RESET_REASON_UNKNOWN; } diff --git a/ports/stm/common-hal/microcontroller/__init__.c b/ports/stm/common-hal/microcontroller/__init__.c index 5a0f0ed9294..977ff3d074f 100644 --- a/ports/stm/common-hal/microcontroller/__init__.c +++ b/ports/stm/common-hal/microcontroller/__init__.c @@ -31,12 +31,14 @@ void common_hal_mcu_delay_us(uint32_t delay) { SysTick->CTRL = 0UL; } -volatile uint32_t nesting_count = 0; +static volatile uint32_t nesting_count = 0; +// 32-bit increments void common_hal_mcu_disable_interrupts(void) { - __disable_irq(); - __DMB(); - nesting_count++; + if (++nesting_count == 1) { + __disable_irq(); + __DMB(); + } } void common_hal_mcu_enable_interrupts(void) { @@ -44,12 +46,10 @@ void common_hal_mcu_enable_interrupts(void) { // This is very very bad because it means there was mismatched disable/enables. reset_into_safe_mode(SAFE_MODE_INTERRUPT_ERROR); } - nesting_count--; - if (nesting_count > 0) { - return; + if (--nesting_count == 0) { + __DMB(); + __enable_irq(); } - __DMB(); - __enable_irq(); } static bool next_reset_to_bootloader = false; @@ -61,6 +61,11 @@ void common_hal_mcu_on_next_reset(mcu_runmode_t runmode) { if (runmode == RUNMODE_BOOTLOADER) { next_reset_to_bootloader = true; } + #if BOARD_UF2_STM32F_BOOTLOADER + if (runmode == RUNMODE_UF2) { + next_reset_to_bootloader = true; + } + #endif } void common_hal_mcu_reset(void) { @@ -69,7 +74,7 @@ void common_hal_mcu_reset(void) { if (next_reset_to_bootloader) { reset_to_bootloader(); } else { - NVIC_SystemReset(); + reset_cpu(); } } diff --git a/ports/stm/common-hal/paralleldisplaybus/ParallelBus.c b/ports/stm/common-hal/paralleldisplaybus/ParallelBus.c new file mode 100644 index 00000000000..0e6d2c8932b --- /dev/null +++ b/ports/stm/common-hal/paralleldisplaybus/ParallelBus.c @@ -0,0 +1,191 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vegard Wærp +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/paralleldisplaybus/ParallelBus.h" + +#include + +#include "common-hal/microcontroller/Pin.h" +#include "peripherals/periph.h" +#include "py/runtime.h" +#include "shared-bindings/digitalio/DigitalInOut.h" +#include "shared-bindings/microcontroller/__init__.h" +#include "shared-bindings/microcontroller/Pin.h" + +// The bus is FSMC bank 1 (NOR/SRAM 1) in 8-bit SRAM mode: each byte written to +// the bank is clocked out with a write (NWE) pulse. Chip select and +// command/data are plain GPIOs, so no FSMC address lines are used. +#define FSMC_BANK1_DATA (*(volatile uint8_t *)0x60000000) + +static const mcu_periph_obj_t *find_fsmc_pin(const mcu_periph_obj_t *list, size_t len, + const mcu_pin_obj_t *pin) { + for (size_t i = 0; i < len; i++) { + if (list[i].pin == pin) { + return &list[i]; + } + } + return NULL; +} + +static void fsmc_pin_init(const mcu_periph_obj_t *periph) { + GPIO_InitTypeDef GPIO_InitStruct = {0}; + GPIO_InitStruct.Pin = pin_mask(periph->pin->number); + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; + GPIO_InitStruct.Alternate = periph->altfn_index; + HAL_GPIO_Init(pin_port(periph->pin->port), &GPIO_InitStruct); + common_hal_mcu_pin_claim(periph->pin); +} + +static void output_pin_init(digitalio_digitalinout_obj_t *self, const mcu_pin_obj_t *pin, bool value) { + self->base.type = &digitalio_digitalinout_type; + common_hal_digitalio_digitalinout_construct(self, pin); + common_hal_digitalio_digitalinout_switch_to_output(self, value, DRIVE_MODE_PUSH_PULL); +} + +void common_hal_paralleldisplaybus_parallelbus_construct(paralleldisplaybus_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) { + // The FSMC data lines are spread over several ports, so they must be given as data_pins. + raise_ValueError_invalid_pin_name(MP_QSTR_data0); +} + +void common_hal_paralleldisplaybus_parallelbus_construct_nonsequential(paralleldisplaybus_parallelbus_obj_t *self, + uint8_t n_pins, const mcu_pin_obj_t **data_pins, 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) { + + // Check every pin before claiming any of them. + if (n_pins != MP_ARRAY_SIZE(self->data_pins)) { + raise_ValueError_invalid_pins(); + } + const mcu_periph_obj_t *data_periphs[MP_ARRAY_SIZE(self->data_pins)]; + for (uint8_t i = 0; i < n_pins; i++) { + data_periphs[i] = find_fsmc_pin(mcu_fsmc_data_list, MP_ARRAY_SIZE(mcu_fsmc_data_list), data_pins[i]); + if (data_periphs[i] == NULL || data_periphs[i]->periph_index != i) { + raise_ValueError_invalid_pin_name(MP_QSTR_data_pins); + } + } + const mcu_periph_obj_t *write_strobe = find_fsmc_pin(mcu_fsmc_nwe_list, MP_ARRAY_SIZE(mcu_fsmc_nwe_list), write); + if (write_strobe == NULL) { + raise_ValueError_invalid_pin_name(MP_QSTR_write); + } + const mcu_periph_obj_t *read_strobe = NULL; + if (read != NULL) { + read_strobe = find_fsmc_pin(mcu_fsmc_noe_list, MP_ARRAY_SIZE(mcu_fsmc_noe_list), read); + if (read_strobe == NULL) { + raise_ValueError_invalid_pin_name(MP_QSTR_read); + } + } + // A write takes DATAST + 3 HCLK cycles (codal-stm32, used by MakeCode + // Arcade, gives 72 ns for DATAST = 4 at 96 MHz). DATAST is at most 255, so + // the slowest write takes 258 cycles. Refuse a lower frequency rather than + // exceed it. + mp_arg_validate_int_min(frequency, (SystemCoreClock + 257) / 258, MP_QSTR_frequency); + + for (uint8_t i = 0; i < n_pins; i++) { + fsmc_pin_init(data_periphs[i]); + self->data_pins[i] = data_pins[i]; + } + fsmc_pin_init(write_strobe); + self->write = write; + if (read_strobe != NULL) { + fsmc_pin_init(read_strobe); + } + self->read = read; + + // Use the shortest write that stays within frequency: at most 258 cycles, + // so DATAST fits. + uint32_t cycles = (SystemCoreClock + frequency - 1) / frequency; + uint32_t datast = MAX(cycles, 4) - 3; + + __HAL_RCC_FSMC_CLK_ENABLE(); + // 8-bit SRAM with writes enabled and separate write timing. The write FIFO + // is off so each byte is on the bus before command/data or chip select + // changes. 0x80 keeps a reserved bit at its reset value. These are the + // values of codal-stm32's FSMC driver, used by MakeCode Arcade, except + // DATAST, which comes from frequency. + FSMC_Bank1->BTCR[0] = FSMC_BCR1_EXTMOD | FSMC_BCR1_WREN | FSMC_BCR1_WFDIS | 0x80; + FSMC_Bank1->BTCR[1] = 0x112419; // Read timing + FSMC_Bank1E->BWTR[0] = 0x0ff00010 | (datast << FSMC_BWTR1_DATAST_Pos); + FSMC_Bank1->BTCR[0] |= FSMC_BCR1_MBKEN; + + output_pin_init(&self->command, command, true); + output_pin_init(&self->chip_select, chip_select, true); + + self->reset.base.type = &mp_type_NoneType; + if (reset != NULL) { + output_pin_init(&self->reset, reset, true); + common_hal_paralleldisplaybus_parallelbus_reset(self); + } +} + +void common_hal_paralleldisplaybus_parallelbus_deinit(paralleldisplaybus_parallelbus_obj_t *self) { + // The bus lives in a display bus slot, which is deinited even if construct + // raised. write is set only once every check passed, so guard on it: + // otherwise this would turn off the FSMC bank under another display. + if (self->write == NULL) { + return; + } + + FSMC_Bank1->BTCR[0] &= ~FSMC_BCR1_MBKEN; + + for (uint8_t i = 0; i < MP_ARRAY_SIZE(self->data_pins); i++) { + common_hal_reset_pin(self->data_pins[i]); + } + common_hal_reset_pin(self->write); + if (self->read != NULL) { + common_hal_reset_pin(self->read); + } + + common_hal_digitalio_digitalinout_deinit(&self->command); + common_hal_digitalio_digitalinout_deinit(&self->chip_select); + if (self->reset.base.type == &digitalio_digitalinout_type) { + common_hal_digitalio_digitalinout_deinit(&self->reset); + } +} + +bool common_hal_paralleldisplaybus_parallelbus_reset(mp_obj_t obj) { + paralleldisplaybus_parallelbus_obj_t *self = MP_OBJ_TO_PTR(obj); + if (self->reset.base.type == &mp_type_NoneType) { + return false; + } + + // Long enough for common controllers: the ILI9341 needs a 10 us pulse and + // 5 ms before the first command. + common_hal_digitalio_digitalinout_set_value(&self->reset, false); + common_hal_mcu_delay_us(10); + common_hal_digitalio_digitalinout_set_value(&self->reset, true); + common_hal_mcu_delay_us(5000); + return true; +} + +bool common_hal_paralleldisplaybus_parallelbus_bus_free(mp_obj_t obj) { + return true; +} + +bool common_hal_paralleldisplaybus_parallelbus_begin_transaction(mp_obj_t obj) { + paralleldisplaybus_parallelbus_obj_t *self = MP_OBJ_TO_PTR(obj); + common_hal_digitalio_digitalinout_set_value(&self->chip_select, false); + return true; +} + +// This ignores chip_select behaviour because data is clocked in by the write line toggling. +void common_hal_paralleldisplaybus_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) { + paralleldisplaybus_parallelbus_obj_t *self = MP_OBJ_TO_PTR(obj); + common_hal_digitalio_digitalinout_set_value(&self->command, byte_type == DISPLAY_DATA); + for (uint32_t i = 0; i < data_length; i++) { + FSMC_BANK1_DATA = data[i]; + } + // Let the last write finish before command/data or chip select changes. + __DSB(); +} + +void common_hal_paralleldisplaybus_parallelbus_end_transaction(mp_obj_t obj) { + paralleldisplaybus_parallelbus_obj_t *self = MP_OBJ_TO_PTR(obj); + common_hal_digitalio_digitalinout_set_value(&self->chip_select, true); +} diff --git a/ports/stm/common-hal/paralleldisplaybus/ParallelBus.h b/ports/stm/common-hal/paralleldisplaybus/ParallelBus.h new file mode 100644 index 00000000000..7ca3f99ddaa --- /dev/null +++ b/ports/stm/common-hal/paralleldisplaybus/ParallelBus.h @@ -0,0 +1,19 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vegard Wærp +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "common-hal/digitalio/DigitalInOut.h" + +typedef struct { + mp_obj_base_t base; + const mcu_pin_obj_t *data_pins[8]; + const mcu_pin_obj_t *write; + const mcu_pin_obj_t *read; + digitalio_digitalinout_obj_t command; + digitalio_digitalinout_obj_t chip_select; + digitalio_digitalinout_obj_t reset; +} paralleldisplaybus_parallelbus_obj_t; diff --git a/ports/stm/common-hal/pulseio/PulseIn.c b/ports/stm/common-hal/pulseio/PulseIn.c index 593e01f9bb9..c683584c981 100644 --- a/ports/stm/common-hal/pulseio/PulseIn.c +++ b/ports/stm/common-hal/pulseio/PulseIn.c @@ -76,31 +76,26 @@ static void pulsein_exti_event_handler(uint8_t num) { self->last_overflow = current_overflow; } +static void mark_deinit(pulseio_pulsein_obj_t *self) { + self->pin = NULL; +} + void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t *self, const mcu_pin_obj_t *pin, uint16_t maxlen, bool idle_state) { + mark_deinit(self); + // STM32 has one shared EXTI for each pin number, 0-15 if (!stm_peripherals_exti_is_free(pin->number)) { mp_raise_RuntimeError(MP_ERROR_TEXT("Pin interrupt already in use")); } // Allocate pulse buffer - self->buffer = (uint16_t *)m_malloc(maxlen * sizeof(uint16_t)); + self->buffer = (uint16_t *)m_malloc_without_collect(maxlen * sizeof(uint16_t)); if (self->buffer == NULL) { // TODO: free the EXTI here? m_malloc_fail(maxlen * sizeof(uint16_t)); } - // Set internal variables - self->pin = pin; - self->maxlen = maxlen; - self->idle_state = idle_state; - self->start = 0; - self->len = 0; - self->first_edge = true; - self->paused = false; - self->last_count = 0; - self->last_overflow = 0; - if (HAL_TIM_Base_GetState(&tim_handle) == HAL_TIM_STATE_RESET) { // Find a suitable timer TIM_TypeDef *tim_instance = stm_peripherals_find_timer(); @@ -130,6 +125,17 @@ void common_hal_pulseio_pulsein_construct(pulseio_pulsein_obj_t *self, const mcu // Add to active PulseIns refcount++; + // Set internal variables + self->pin = pin; + self->maxlen = maxlen; + self->idle_state = idle_state; + self->start = 0; + self->len = 0; + self->first_edge = true; + self->paused = false; + self->last_count = 0; + self->last_overflow = 0; + if (!stm_peripherals_exti_reserve(pin->number)) { mp_raise_RuntimeError(MP_ERROR_TEXT("Pin interrupt already in use")); } @@ -158,9 +164,10 @@ void common_hal_pulseio_pulsein_deinit(pulseio_pulsein_obj_t *self) { } // Remove pulsein slot from shared array callback_obj_ref[self->pin->number] = NULL; - stm_peripherals_exti_free(self->pin->number); + // Disable the EXTI IRQ, unreserve the line and clear the callback. + stm_peripherals_exti_reset_exti(self->pin->number); reset_pin_number(self->pin->port, self->pin->number); - self->pin = NULL; + mark_deinit(self); refcount--; if (refcount == 0) { @@ -208,23 +215,23 @@ void common_hal_pulseio_pulsein_resume(pulseio_pulsein_obj_t *self, uint16_t tri } void common_hal_pulseio_pulsein_clear(pulseio_pulsein_obj_t *self) { - stm_peripherals_exti_disable(self->pin->number); + common_hal_mcu_disable_interrupts(); self->start = 0; self->len = 0; - stm_peripherals_exti_enable(self->pin->number); + common_hal_mcu_enable_interrupts(); } uint16_t common_hal_pulseio_pulsein_get_item(pulseio_pulsein_obj_t *self, int16_t index) { - stm_peripherals_exti_disable(self->pin->number); + common_hal_mcu_disable_interrupts(); if (index < 0) { index += self->len; } if (index < 0 || index >= self->len) { - stm_peripherals_exti_enable(self->pin->number); + common_hal_mcu_enable_interrupts(); mp_raise_IndexError_varg(MP_ERROR_TEXT("%q out of range"), MP_QSTR_index); } uint16_t value = self->buffer[(self->start + index) % self->maxlen]; - stm_peripherals_exti_enable(self->pin->number); + common_hal_mcu_enable_interrupts(); return value; } @@ -232,11 +239,11 @@ uint16_t common_hal_pulseio_pulsein_popleft(pulseio_pulsein_obj_t *self) { if (self->len == 0) { mp_raise_IndexError_varg(MP_ERROR_TEXT("pop from empty %q"), MP_QSTR_PulseIn); } - stm_peripherals_exti_disable(self->pin->number); + common_hal_mcu_disable_interrupts(); uint16_t value = self->buffer[self->start]; self->start = (self->start + 1) % self->maxlen; self->len--; - stm_peripherals_exti_enable(self->pin->number); + common_hal_mcu_enable_interrupts(); return value; } diff --git a/ports/stm/common-hal/pulseio/PulseOut.c b/ports/stm/common-hal/pulseio/PulseOut.c index e2b637664d5..d5e8a4a9890 100644 --- a/ports/stm/common-hal/pulseio/PulseOut.c +++ b/ports/stm/common-hal/pulseio/PulseOut.c @@ -7,8 +7,10 @@ #include "common-hal/pulseio/PulseOut.h" #include +#include #include "py/mpconfig.h" +#include "py/runtime.h" #include "shared-bindings/pulseio/PulseOut.h" #include "shared-bindings/pwmio/PWMOut.h" @@ -81,34 +83,44 @@ static void pulseout_event_handler(void) { } } +static void free_timer(void) { + stm_peripherals_timer_free(tim_handle.Instance); + memset(&tim_handle, 0, sizeof(tim_handle)); +} + void common_hal_pulseio_pulseout_construct(pulseio_pulseout_obj_t *self, const mcu_pin_obj_t *pin, uint32_t frequency, uint16_t duty_cycle) { pwmout_result_t result = common_hal_pwmio_pwmout_construct( &self->pwmout, pin, duty_cycle, frequency, false); - // This will raise an exception and not return if needed. common_hal_pwmio_pwmout_raise_error(result); + if (tim_handle.Instance == NULL) { + TIM_TypeDef *tim_instance = stm_peripherals_find_free_timer(); + if (tim_instance == NULL) { + common_hal_pwmio_pwmout_deinit(&self->pwmout); + mp_raise_RuntimeError(MP_ERROR_TEXT("All timers in use")); + } + stm_peripherals_timer_reserve(tim_instance); + + // calculate a 1ms period + uint32_t source = stm_peripherals_timer_get_source_freq(tim_instance); + 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.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; + } + // Add to active PulseOuts refcount++; - TIM_TypeDef *tim_instance = stm_peripherals_find_timer(); - stm_peripherals_timer_reserve(tim_instance); - - // calculate a 1ms period - uint32_t source = stm_peripherals_timer_get_source_freq(tim_instance); - 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.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; - turn_off(self); } @@ -126,7 +138,7 @@ void common_hal_pulseio_pulseout_deinit(pulseio_pulseout_obj_t *self) { refcount--; if (refcount == 0) { - stm_peripherals_timer_free(tim_handle.Instance); + free_timer(); } } diff --git a/ports/stm/common-hal/pwmio/PWMOut.c b/ports/stm/common-hal/pwmio/PWMOut.c index ed3bd67e7ec..ca560dc105c 100644 --- a/ports/stm/common-hal/pwmio/PWMOut.c +++ b/ports/stm/common-hal/pwmio/PWMOut.c @@ -29,9 +29,16 @@ 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 *prescaler = 0; + if (frequency == 0) { + return false; + } for (uint32_t i = 1; i <= 0xffff; i++) { - *period = source_freq / (i * frequency); - if (*period <= 0xffff && *period >= 2) { + *period = source_freq / ((uint64_t)i * frequency); + if (*period < 2) { + // A larger prescaler only makes the period shorter. + break; + } + if (*period <= 0xffff) { *prescaler = i; break; } @@ -40,6 +47,10 @@ static bool timer_get_optimal_divisors(uint32_t *period, uint32_t *prescaler, return *prescaler != 0; } +static void mark_deinit(pwmio_pwmout_obj_t *self) { + self->tim = NULL; +} + pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t *self, const mcu_pin_obj_t *pin, uint16_t duty, @@ -49,24 +60,25 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t *self, pwmout_result_t last_failure = PWMOUT_INVALID_PIN; bool first_time_setup = true; - uint8_t tim_index; - uint8_t tim_channel_index; + mark_deinit(self); - self->tim = NULL; + const mcu_tim_pin_obj_t *found = NULL; for (uint i = 0; i < MP_ARRAY_SIZE(mcu_tim_pin_list); i++) { const mcu_tim_pin_obj_t *tim = &mcu_tim_pin_list[i]; - tim_index = tim->tim_index; - tim_channel_index = tim->channel_index; + uint8_t tim_index = tim->tim_index; + uint8_t tim_channel_index = tim->channel_index; // if pin is same if (tim->pin == pin) { - // check if the timer has a channel active, or is reserved by main timer system + // PWMOut reserves its timers too, so a reserved timer with no PWM channels + // taken belongs to an internal module (PulseIn, PulseOut, audio, ...). + if (tim_index < TIM_BANK_ARRAY_LEN && tim_channels_taken[tim_index] == 0 + && stm_peripherals_timer_is_reserved(mcu_tim_banks[tim_index])) { + last_failure = PWMOUT_INTERNAL_RESOURCES_IN_USE; + continue; // keep looking + } + // check if the timer has a channel active if (tim_index < TIM_BANK_ARRAY_LEN && tim_channels_taken[tim_index] != 0) { - // Timer has already been reserved by an internal module - if (stm_peripherals_timer_is_reserved(mcu_tim_banks[tim_index])) { - last_failure = PWMOUT_INTERNAL_RESOURCES_IN_USE; - continue; // keep looking - } // is it the same channel? (or all channels reserved by a var-freq) if (tim_channels_taken[tim_index] & (1 << tim_channel_index)) { last_failure = PWMOUT_INTERNAL_RESOURCES_IN_USE; @@ -74,41 +86,27 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t *self, } // If the frequencies are the same it's ok if (tim_frequencies[tim_index] != frequency) { - last_failure = PWMOUT_INVALID_FREQUENCY_ON_PIN; + last_failure = PWMOUT_INTERNAL_RESOURCES_IN_USE; continue; // keep looking } // you can't put a variable frequency on a partially reserved timer if (variable_frequency) { - last_failure = PWMOUT_VARIABLE_FREQUENCY_NOT_AVAILABLE; + last_failure = PWMOUT_INTERNAL_RESOURCES_IN_USE; continue; // keep looking } first_time_setup = false; // skip setting up the timer } // No problems taken, so set it up - self->tim = tim; + found = tim; break; } } - TIM_TypeDef *TIMx; - - // handle valid/invalid timer instance - if (self->tim != NULL) { - // create instance - TIMx = mcu_tim_banks[tim_index]; - // reserve timer/channel - if (variable_frequency) { - // Take all the channels. - tim_channels_taken[tim_index] = 0x0F; - } else { - tim_channels_taken[tim_index] |= 1 << tim_channel_index; - } - tim_frequencies[tim_index] = frequency; - stm_peripherals_timer_reserve(TIMx); - } else { - // no match found + if (found == NULL) { return last_failure; } + uint8_t tim_index = found->tim_index; + TIM_TypeDef *TIMx = mcu_tim_banks[tim_index]; uint32_t prescaler = 0; // prescaler is 15 bit uint32_t period = 0; // period is 16 bit @@ -117,6 +115,18 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t *self, return PWMOUT_INVALID_FREQUENCY; } + // reserve timer/channel + if (variable_frequency) { + // Take all the channels. + tim_channels_taken[tim_index] = 0x0F; + } else { + tim_channels_taken[tim_index] |= 1 << found->channel_index; + } + tim_frequencies[tim_index] = frequency; + stm_peripherals_timer_reserve(TIMx); + self->tim = found; + self->variable_frequency = variable_frequency; + GPIO_InitTypeDef GPIO_InitStruct = {0}; GPIO_InitStruct.Pin = pin_mask(pin->number); GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; @@ -125,11 +135,12 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t *self, GPIO_InitStruct.Alternate = self->tim->altfn_index; HAL_GPIO_Init(pin_port(pin->port), &GPIO_InitStruct); self->pin = pin; + common_hal_mcu_pin_claim(pin); tim_clock_enable(1 << tim_index); // translate channel into handle value: TIM_CHANNEL_1, _2, _3, _4. - self->channel = 4 * tim_channel_index; + self->channel = 4 * found->channel_index; // Timer init self->handle.Instance = TIMx; @@ -143,8 +154,15 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t *self, // 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) { + common_hal_pwmio_pwmout_deinit(self); return PWMOUT_INITIALIZATION_ERROR; } + } else { + // The timer is already running. HAL_TIM_PWM_Init() would restart it, but + // HAL_TIM_PWM_Start() refuses a channel unless the handle says it's ready. + self->handle.State = HAL_TIM_STATE_READY; + TIM_CHANNEL_STATE_SET_ALL(&self->handle, HAL_TIM_CHANNEL_STATE_READY); + TIM_CHANNEL_N_STATE_SET_ALL(&self->handle, HAL_TIM_CHANNEL_STATE_READY); } // Channel/PWM init @@ -153,13 +171,14 @@ 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) { + common_hal_pwmio_pwmout_deinit(self); return PWMOUT_INITIALIZATION_ERROR; } if (HAL_TIM_PWM_Start(&self->handle, self->channel) != HAL_OK) { + common_hal_pwmio_pwmout_deinit(self); return PWMOUT_INITIALIZATION_ERROR; } - self->variable_frequency = variable_frequency; self->frequency = frequency; self->duty_cycle = duty; self->period = period; @@ -167,9 +186,6 @@ pwmout_result_t common_hal_pwmio_pwmout_construct(pwmio_pwmout_obj_t *self, return PWMOUT_OK; } -void common_hal_pwmio_pwmout_never_reset(pwmio_pwmout_obj_t *self) { - common_hal_never_reset_pin(self->pin); -} bool common_hal_pwmio_pwmout_deinited(pwmio_pwmout_obj_t *self) { return self->tim == NULL; @@ -195,7 +211,7 @@ void common_hal_pwmio_pwmout_deinit(pwmio_pwmout_obj_t *self) { stm_peripherals_timer_free(self->handle.Instance); } - self->tim = NULL; + mark_deinit(self); } void common_hal_pwmio_pwmout_set_duty_cycle(pwmio_pwmout_obj_t *self, uint16_t duty) { @@ -217,7 +233,9 @@ void common_hal_pwmio_pwmout_set_frequency(pwmio_pwmout_obj_t *self, uint32_t fr uint32_t prescaler = 0; uint32_t period = 0; uint32_t source_freq = stm_peripherals_timer_get_source_freq(self->handle.Instance); - timer_get_optimal_divisors(&period, &prescaler, frequency, source_freq); + if (!timer_get_optimal_divisors(&period, &prescaler, frequency, source_freq)) { + mp_arg_error_invalid(MP_QSTR_frequency); + } // shut down HAL_TIM_PWM_Stop(&self->handle, self->channel); diff --git a/ports/stm/common-hal/rgbmatrix/RGBMatrix.c b/ports/stm/common-hal/rgbmatrix/RGBMatrix.c index a8014222d7d..913953e49ef 100644 --- a/ports/stm/common-hal/rgbmatrix/RGBMatrix.c +++ b/ports/stm/common-hal/rgbmatrix/RGBMatrix.c @@ -16,7 +16,6 @@ extern void _PM_IRQ_HANDLER(void); 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; } diff --git a/ports/stm/common-hal/rtc/RTC.h b/ports/stm/common-hal/rtc/RTC.h index b6e709bed4f..78492ded426 100644 --- a/ports/stm/common-hal/rtc/RTC.h +++ b/ports/stm/common-hal/rtc/RTC.h @@ -7,4 +7,3 @@ #pragma once extern void rtc_init(void); -extern void rtc_reset(void); diff --git a/ports/stm/common-hal/sdioio/SDCard.c b/ports/stm/common-hal/sdioio/SDCard.c index 92c16aef847..623fd474dcb 100644 --- a/ports/stm/common-hal/sdioio/SDCard.c +++ b/ports/stm/common-hal/sdioio/SDCard.c @@ -6,6 +6,8 @@ #include #include "shared-bindings/sdioio/SDCard.h" + +#include "extmod/vfs.h" #include "py/mperrno.h" #include "py/runtime.h" @@ -16,7 +18,6 @@ #include "shared-bindings/microcontroller/Pin.h" 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; i < sz; i++, table++) { @@ -99,12 +100,25 @@ static int check_pins(sdioio_sdcard_obj_t *self, } +static void mark_deinit(sdioio_sdcard_obj_t *self) { + self->command = NULL; + self->clock = NULL; + for (size_t i = 0; i < MP_ARRAY_SIZE(self->data); i++) { + self->data[i] = NULL; + } +} + 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, const mcu_pin_obj_t **data, uint32_t frequency) { + mark_deinit(self); int periph_index = check_pins(self, clock, command, num_data, data); + #ifdef STM32H750xx + SDMMC_TypeDef *SDMMCx = mcu_sdio_banks[periph_index - 1]; + #else SDIO_TypeDef *SDIOx = mcu_sdio_banks[periph_index - 1]; + #endif GPIO_InitTypeDef GPIO_InitStruct = {0}; @@ -128,6 +142,26 @@ void common_hal_sdioio_sdcard_construct(sdioio_sdcard_obj_t *self, GPIO_InitStruct.Pin = pin_mask(clock->number); HAL_GPIO_Init(pin_port(clock->port), &GPIO_InitStruct); + #ifdef STM32H750xx + RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0}; + PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_SDMMC; + PeriphClkInitStruct.SdmmcClockSelection = RCC_SDMMCCLKSOURCE_PLL; + if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK) { + common_hal_sdioio_sdcard_deinit(self); + mp_raise_ValueError_varg(MP_ERROR_TEXT("MMC/SDIO Clock Error %x")); + } + __HAL_RCC_SDMMC1_CLK_ENABLE(); + + self->handle.Init.ClockDiv = SDMMC_NSPEED_CLK_DIV; + self->handle.Init.ClockEdge = SDMMC_CLOCK_EDGE_RISING; + self->handle.Init.ClockPowerSave = SDMMC_CLOCK_POWER_SAVE_DISABLE; + self->handle.Init.BusWide = SDMMC_BUS_WIDE_1B; + // For the SDMMC controller Hardware Flow Control needs to be enabled + // at the default speed of 25MHz, in order to avoid FIFO underrun (TX mode) + // and overrun (RX mode) errors. + self->handle.Init.HardwareFlowControl = SDMMC_HARDWARE_FLOW_CONTROL_ENABLE; + self->handle.Instance = SDMMCx; + #else __HAL_RCC_SDIO_CLK_ENABLE(); self->handle.Init.ClockDiv = SDIO_TRANSFER_CLK_DIV; @@ -137,22 +171,30 @@ void common_hal_sdioio_sdcard_construct(sdioio_sdcard_obj_t *self, self->handle.Init.BusWide = SDIO_BUS_WIDE_1B; self->handle.Init.HardwareFlowControl = SDIO_HARDWARE_FLOW_CONTROL_DISABLE; self->handle.Instance = SDIOx; + #endif HAL_StatusTypeDef r = HAL_SD_Init(&self->handle); if (r != HAL_OK) { - mp_raise_ValueError_varg(MP_ERROR_TEXT("SDIO Init Error %x"), (unsigned int)r); + common_hal_sdioio_sdcard_deinit(self); + mp_raise_ValueError_varg(MP_ERROR_TEXT("SDIO Init Error 0x%02x"), (unsigned int)r); } HAL_SD_CardInfoTypeDef info; r = HAL_SD_GetCardInfo(&self->handle, &info); if (r != HAL_OK) { + common_hal_sdioio_sdcard_deinit(self); mp_raise_ValueError_varg(MP_ERROR_TEXT("SDIO GetCardInfo Error %d"), (int)r); } self->num_data = 1; + #ifdef STM32H750xx + uint32_t bus_wide_opt = SDMMC_BUS_WIDE_4B; + #else + uint32_t bus_wide_opt = SDIO_BUS_WIDE_4B; + #endif if (num_data == 4) { - if ((r = HAL_SD_ConfigWideBusOperation(&self->handle, SDIO_BUS_WIDE_4B)) == HAL_SD_ERROR_NONE) { - self->handle.Init.BusWide = SDIO_BUS_WIDE_4B; + if ((r = HAL_SD_ConfigWideBusOperation(&self->handle, bus_wide_opt)) == HAL_SD_ERROR_NONE) { + self->handle.Init.BusWide = bus_wide_opt; self->num_data = 4; } else { } @@ -210,33 +252,90 @@ static void check_for_deinit(sdioio_sdcard_obj_t *self) { } } -int common_hal_sdioio_sdcard_writeblocks(sdioio_sdcard_obj_t *self, uint32_t start_block, mp_buffer_info_t *bufinfo) { - check_for_deinit(self); - check_whole_block(bufinfo); +// Native function for VFS blockdev layer +mp_negative_errno_t sdioio_sdcard_writeblocks(mp_obj_t self_in, uint8_t *buf, + uint32_t start_block, uint32_t num_blocks) { + sdioio_sdcard_obj_t *self = MP_OBJ_TO_PTR(self_in); wait_write_complete(self); self->state_programming = true; common_hal_mcu_disable_interrupts(); - HAL_StatusTypeDef r = HAL_SD_WriteBlocks(&self->handle, bufinfo->buf, start_block, bufinfo->len / 512, 1000); + #ifdef STM32H750xx + // longer timeouts needed because code executing from QSPI is slower + uint32_t time_out = SDMMC_DATATIMEOUT; + #else + uint32_t time_out = 1000; + #endif + HAL_StatusTypeDef r = HAL_SD_WriteBlocks(&self->handle, buf, start_block, num_blocks, time_out); common_hal_mcu_enable_interrupts(); if (r != HAL_OK) { - return -EIO; + return -MP_EIO; } return 0; } -int common_hal_sdioio_sdcard_readblocks(sdioio_sdcard_obj_t *self, uint32_t start_block, mp_buffer_info_t *bufinfo) { +mp_negative_errno_t common_hal_sdioio_sdcard_writeblocks(sdioio_sdcard_obj_t *self, uint32_t start_block, mp_buffer_info_t *bufinfo) { check_for_deinit(self); check_whole_block(bufinfo); + + uint32_t num_blocks = bufinfo->len / 512; + return sdioio_sdcard_writeblocks(MP_OBJ_FROM_PTR(self), bufinfo->buf, + start_block, num_blocks); +} + +// Native function for VFS blockdev layer +mp_negative_errno_t sdioio_sdcard_readblocks(mp_obj_t self_in, uint8_t *buf, + uint32_t start_block, uint32_t num_blocks) { + sdioio_sdcard_obj_t *self = MP_OBJ_TO_PTR(self_in); wait_write_complete(self); common_hal_mcu_disable_interrupts(); - HAL_StatusTypeDef r = HAL_SD_ReadBlocks(&self->handle, bufinfo->buf, start_block, bufinfo->len / 512, 1000); + #ifdef STM32H750xx + // longer timeouts needed because code executing from QSPI is slower + uint32_t time_out = SDMMC_DATATIMEOUT; + #else + uint32_t time_out = 1000; + #endif + HAL_StatusTypeDef r = HAL_SD_ReadBlocks(&self->handle, buf, start_block, num_blocks, time_out); common_hal_mcu_enable_interrupts(); if (r != HAL_OK) { - return -EIO; + return -MP_EIO; } return 0; } +mp_negative_errno_t common_hal_sdioio_sdcard_readblocks(sdioio_sdcard_obj_t *self, uint32_t start_block, mp_buffer_info_t *bufinfo) { + check_for_deinit(self); + check_whole_block(bufinfo); + + uint32_t num_blocks = bufinfo->len / 512; + return sdioio_sdcard_readblocks(MP_OBJ_FROM_PTR(self), bufinfo->buf, + start_block, num_blocks); +} + +// Native function for VFS blockdev layer +bool sdioio_sdcard_ioctl(mp_obj_t self_in, size_t cmd, size_t arg, + mp_int_t *out_value) { + sdioio_sdcard_obj_t *self = MP_OBJ_TO_PTR(self_in); + *out_value = 0; + + switch (cmd) { + case MP_BLOCKDEV_IOCTL_DEINIT: + case MP_BLOCKDEV_IOCTL_SYNC: + // SDIO operations are synchronous, no action needed + return true; + + case MP_BLOCKDEV_IOCTL_BLOCK_COUNT: + *out_value = common_hal_sdioio_sdcard_get_count(self); + return true; + + case MP_BLOCKDEV_IOCTL_BLOCK_SIZE: + *out_value = 512; // SD cards use 512-byte sectors + return true; + + default: + return false; // Unsupported command + } +} + bool common_hal_sdioio_sdcard_configure(sdioio_sdcard_obj_t *self, uint32_t frequency, uint8_t bits) { check_for_deinit(self); return true; @@ -246,12 +345,6 @@ bool common_hal_sdioio_sdcard_deinited(sdioio_sdcard_obj_t *self) { return self->command == NULL; } -static void never_reset_mcu_periph(const mcu_periph_obj_t *periph) { - if (periph) { - never_reset_pin_number(periph->pin->port, periph->pin->number); - } -} - static void reset_mcu_periph(const mcu_periph_obj_t *periph) { if (periph) { reset_pin_number(periph->pin->port, periph->pin->number); @@ -264,43 +357,11 @@ void common_hal_sdioio_sdcard_deinit(sdioio_sdcard_obj_t *self) { } reserved_sdio[self->command->periph_index - 1] = false; - never_reset_sdio[self->command->periph_index - 1] = false; reset_mcu_periph(self->command); - self->command = NULL; - reset_mcu_periph(self->clock); - self->command = NULL; - for (size_t i = 0; i < MP_ARRAY_SIZE(self->data); i++) { reset_mcu_periph(self->data[i]); - self->data[i] = NULL; - } -} - -void common_hal_sdioio_sdcard_never_reset(sdioio_sdcard_obj_t *self) { - if (common_hal_sdioio_sdcard_deinited(self)) { - return; - } - - if (never_reset_sdio[self->command->periph_index] - 1) { - return; - } - - never_reset_sdio[self->command->periph_index - 1] = true; - - never_reset_mcu_periph(self->command); - never_reset_mcu_periph(self->clock); - - 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 < MP_ARRAY_SIZE(reserved_sdio); i++) { - if (!never_reset_sdio[i]) { - reserved_sdio[i] = false; - } } + mark_deinit(self); } diff --git a/ports/stm/common-hal/sdioio/SDCard.h b/ports/stm/common-hal/sdioio/SDCard.h index 8f4d9453033..0cd79a3accf 100644 --- a/ports/stm/common-hal/sdioio/SDCard.h +++ b/ports/stm/common-hal/sdioio/SDCard.h @@ -23,5 +23,3 @@ typedef struct { uint32_t frequency; uint32_t capacity; } sdioio_sdcard_obj_t; - -void sdioio_reset(void); diff --git a/ports/stm/mpconfigport.h b/ports/stm/mpconfigport.h index afa9aa3685c..01c65541db8 100644 --- a/ports/stm/mpconfigport.h +++ b/ports/stm/mpconfigport.h @@ -24,6 +24,11 @@ extern uint8_t _ld_default_stack_size; #ifndef BOARD_VTOR_DEFER #define BOARD_VTOR_DEFER (0) #endif +// The board runs the uf2-stm32f bootloader (MakeCode Arcade consoles), which +// reads RTC->BKP0R on reset to choose between UF2 mode and the application. +#ifndef BOARD_UF2_STM32F_BOOTLOADER +#define BOARD_UF2_STM32F_BOOTLOADER (0) +#endif #ifndef BOARD_NO_VBUS_SENSE #define BOARD_NO_VBUS_SENSE (0) #endif diff --git a/ports/stm/mpconfigport.mk b/ports/stm/mpconfigport.mk index 3874870a6da..71cb49ecba8 100644 --- a/ports/stm/mpconfigport.mk +++ b/ports/stm/mpconfigport.mk @@ -1,8 +1,13 @@ +# Properties get a dedicated linker section here, so they can drop the unused slots. +CIRCUITPY_OPTIMIZE_PROPERTY_FLASH_SIZE ?= 1 + LONGINT_IMPL ?= MPZ INTERNAL_LIBM ?= 1 ifeq ($(MCU_VARIANT),$(filter $(MCU_VARIANT),STM32F405xx STM32F407xx)) CIRCUITPY_ALARM = 1 + # ?= so a board reusing TIM6 / PA04 for something else can opt out. + CIRCUITPY_AUDIOIO ?= 1 CIRCUITPY_CANIO = 1 CIRCUITPY_FRAMEBUFFERIO ?= 1 CIRCUITPY_SDIOIO ?= 1 @@ -10,13 +15,23 @@ ifeq ($(MCU_VARIANT),$(filter $(MCU_VARIANT),STM32F405xx STM32F407xx)) USB_NUM_ENDPOINT_PAIRS = 4 endif +ifeq ($(INTERNAL_FLASH_FILESYSTEM),1) + OPTIMIZATION_FLAGS ?= -Os +endif + +# Fast e-paper doesn't fit in flash on the F401 and F411. +ifeq ($(MCU_VARIANT),$(filter $(MCU_VARIANT),STM32F401xE STM32F411xE)) + CIRCUITPY_EPAPERDISPLAY_FAST ?= 0 +endif + ifeq ($(MCU_VARIANT),STM32F407xx) UF2_FAMILY_ID ?= 0x6d0922fa endif ifeq ($(MCU_SERIES),F4) - # Audio via PWM - CIRCUITPY_AUDIOIO = 0 + CIRCUITPY_LOAD_NATIVE ?= 1 + # Audio via PWM (F405/F407 also supports DAC-based audioio; set above) + CIRCUITPY_AUDIOIO ?= 0 CIRCUITPY_AUDIOCORE ?= 1 CIRCUITPY_AUDIOPWMIO ?= 1 @@ -81,12 +96,20 @@ ifeq ($(MCU_SERIES),L4) CIRCUITPY_NVM ?= 0 CIRCUITPY_ROTARYIO ?= 0 CIRCUITPY_RTC ?= 1 + UF2_FAMILY_ID ?= 0x00ff6919 +endif + +ifeq ($(MCU_VARIANT),STM32L4R5xx) # todo - this varies between devices in the series # This slide deck https://www.st.com/content/ccc/resource/training/technical/product_training/98/89/c8/6c/3e/e9/49/79/STM32L4_Peripheral_USB.pdf/files/STM32L4_Peripheral_USB.pdf/jcr:content/translations/en.STM32L4_Peripheral_USB.pdf # cites 16 endpoints, 8 endpoint pairs, while section 3.39 of the L4R5 datasheet states 6 endpoint pairs. USB_NUM_ENDPOINT_PAIRS = 6 - UF2_FAMILY_ID ?= 0x00ff6919 endif -CIRCUITPY_PARALLELDISPLAYBUS := 0 +ifeq ($(MCU_VARIANT),STM32L433xx) + USB_NUM_ENDPOINT_PAIRS = 4 +endif + +# Implemented with the FSMC, for variants whose periph.c lists the FSMC pins. +CIRCUITPY_PARALLELDISPLAYBUS ?= 0 CIRCUITPY_BUILD_EXTENSIONS ?= bin diff --git a/ports/stm/mpconfigport_nanbox.h b/ports/stm/mpconfigport_nanbox.h deleted file mode 100644 index 164850112e0..00000000000 --- a/ports/stm/mpconfigport_nanbox.h +++ /dev/null @@ -1,25 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2016 Damien P. George -// -// SPDX-License-Identifier: MIT - -#pragma once - -// select nan-boxing object model -#define MICROPY_OBJ_REPR (MICROPY_OBJ_REPR_D) - -// native emitters don't work with nan-boxing -#define MICROPY_EMIT_X86 (0) -#define MICROPY_EMIT_X64 (0) -#define MICROPY_EMIT_THUMB (0) -#define MICROPY_EMIT_ARM (0) - -#include - -typedef int64_t mp_int_t; -typedef uint64_t mp_uint_t; -#define UINT_FMT "%llu" -#define INT_FMT "%lld" - -#include diff --git a/ports/stm/packages/LQFP48.c b/ports/stm/packages/LQFP48.c new file mode 100644 index 00000000000..46b737adeb8 --- /dev/null +++ b/ports/stm/packages/LQFP48.c @@ -0,0 +1,63 @@ +#include "shared-bindings/microcontroller/__init__.h" +#include "common-hal/microcontroller/Pin.h" +#include "py/obj.h" + +static const mp_rom_map_elem_t mcu_pin_globals_table[] = { +// Pins 1-12 + /* VBAT -------------------------------------------*/ + { MP_ROM_QSTR(MP_QSTR_PC13), MP_ROM_PTR(&pin_PC13) }, + // PC14 OSC32_IN ----------------------------------*/ + // PC15 OSC32_OUT ---------------------------------*/ + // { MP_ROM_QSTR(MP_QSTR_PH00), MP_ROM_PTR(&pin_PH00) }, PH00 OSC_IN + // { MP_ROM_QSTR(MP_QSTR_PH01), MP_ROM_PTR(&pin_PH01) }, PH01 OSC_OUT + // NRST -------------------------------------------*/ + // VSSA -------------------------------------------*/ + // VDDA -------------------------------------------*/ + { 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) }, + +// Pins 13-24 + { 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_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_PB10), MP_ROM_PTR(&pin_PB10) }, + { MP_ROM_QSTR(MP_QSTR_PB11), MP_ROM_PTR(&pin_PB11) }, + // VSS --------------------------------------------*/ + // VDD --------------------------------------------*/ + +// Pins 25-36 + { 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_PA08), MP_ROM_PTR(&pin_PA08) }, + { MP_ROM_QSTR(MP_QSTR_PA09), MP_ROM_PTR(&pin_PA09) }, + { MP_ROM_QSTR(MP_QSTR_PA10), MP_ROM_PTR(&pin_PA10) }, + { MP_ROM_QSTR(MP_QSTR_PA11), MP_ROM_PTR(&pin_PA11) }, + { MP_ROM_QSTR(MP_QSTR_PA12), MP_ROM_PTR(&pin_PA12) }, + { MP_ROM_QSTR(MP_QSTR_PA13), MP_ROM_PTR(&pin_PA13) }, + // VSS --------------------------------------------*/ + // VDD --------------------------------------------*/ + +// Pins 37-48 + { 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_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) }, + // BOOT0 ------------------------------------------*/ + { MP_ROM_QSTR(MP_QSTR_PB08), MP_ROM_PTR(&pin_PB08) }, + { MP_ROM_QSTR(MP_QSTR_PB09), MP_ROM_PTR(&pin_PB09) }, + // VSS --------------------------------------------*/ + // VDD --------------------------------------------*/ + +}; +MP_DEFINE_CONST_DICT(mcu_pin_globals, mcu_pin_globals_table); diff --git a/ports/stm/peripherals/exti.c b/ports/stm/peripherals/exti.c index 19fa3079ba0..657eb985823 100644 --- a/ports/stm/peripherals/exti.c +++ b/ports/stm/peripherals/exti.c @@ -13,26 +13,22 @@ #if !(CPY_STM32H7) static bool stm_exti_reserved[STM32_GPIO_PORT_SIZE]; -static bool stm_exti_never_reset[STM32_GPIO_PORT_SIZE]; static void (*stm_exti_callback[STM32_GPIO_PORT_SIZE])(uint8_t num); +// Bitmask of lines whose interrupt is enabled. +static uint16_t stm_exti_enabled; -void exti_reset(void) { - for (size_t i = 0; i < STM32_GPIO_PORT_SIZE; i++) { - if (!stm_exti_never_reset[i]) { - stm_exti_reserved[i] = false; - stm_exti_callback[i] = NULL; - stm_peripherals_exti_disable(i); - } +// Lines 5-9 and 10-15 each share one NVIC IRQ. +static uint16_t irq_lines_mask(uint8_t num) { + if (num >= 5 && num <= 9) { + return 0x03e0; + } else if (num >= 10 && num <= 15) { + return 0xfc00; } -} - -void stm_peripherals_exti_never_reset(uint8_t num) { - stm_exti_never_reset[num] = true; + return 1 << num; } void stm_peripherals_exti_reset_exti(uint8_t num) { stm_peripherals_exti_disable(num); - stm_exti_never_reset[num] = false; stm_exti_reserved[num] = false; stm_exti_callback[num] = NULL; } @@ -50,21 +46,21 @@ bool stm_peripherals_exti_reserve(uint8_t num) { } void stm_peripherals_exti_enable(uint8_t num) { + stm_exti_enabled |= 1 << num; HAL_NVIC_EnableIRQ(stm_peripherals_exti_get_irq(num)); } void stm_peripherals_exti_disable(uint8_t num) { - HAL_NVIC_DisableIRQ(stm_peripherals_exti_get_irq(num)); + stm_exti_enabled &= ~(1 << num); + if ((stm_exti_enabled & irq_lines_mask(num)) == 0) { + HAL_NVIC_DisableIRQ(stm_peripherals_exti_get_irq(num)); + } } void stm_peripherals_exti_set_callback(void (*callback)(uint8_t num), uint8_t number) { stm_exti_callback[number] = callback; } -void stm_peripherals_exti_free(uint8_t num) { - stm_exti_reserved[num] = true; -} - IRQn_Type stm_peripherals_exti_get_irq(uint8_t num) { if (num == 0) { return EXTI0_IRQn; @@ -85,45 +81,48 @@ IRQn_Type stm_peripherals_exti_get_irq(uint8_t num) { } } +#ifdef STM32L4 +#define PR PR1 +#endif +static void exti_irq_handler(uint8_t first, uint8_t last) { + uint32_t pending = EXTI->PR; + for (uint8_t i = first; i <= last; i++) { + if (!(pending & (1 << i))) { + continue; + } + if ((stm_exti_enabled & (1 << i)) && stm_exti_callback[i] != NULL) { + stm_exti_callback[i](i); + } else { + // No one is handling this line: clear it so the IRQ does not fire again. + EXTI->PR = 1 << i; + } + } +} +#ifdef STM32L4 +#undef PR +#endif + void EXTI0_IRQHandler(void) { - stm_exti_callback[0](0); + exti_irq_handler(0, 0); } void EXTI1_IRQHandler(void) { - stm_exti_callback[1](1); + exti_irq_handler(1, 1); } void EXTI2_IRQHandler(void) { - stm_exti_callback[2](2); + exti_irq_handler(2, 2); } void EXTI3_IRQHandler(void) { - stm_exti_callback[3](3); + exti_irq_handler(3, 3); } void EXTI4_IRQHandler(void) { - stm_exti_callback[4](4); + exti_irq_handler(4, 4); } - -#ifdef STM32L4 -#define PR PR1 -#endif void EXTI9_5_IRQHandler(void) { - uint32_t pending = EXTI->PR; - for (uint i = 5; i <= 9; i++) { - if (pending & (1 << i)) { - stm_exti_callback[i](i); - } - } + exti_irq_handler(5, 9); } - void EXTI15_10_IRQHandler(void) { - uint32_t pending = EXTI->PR; - for (uint i = 10; i <= 15; i++) { - if (pending & (1 << i)) { - stm_exti_callback[i](i); - } - } + exti_irq_handler(10, 15); } -#ifdef STM32L4 -#undef PR -#endif #endif diff --git a/ports/stm/peripherals/exti.h b/ports/stm/peripherals/exti.h index 94b62f1768e..0d53eb8c7d7 100644 --- a/ports/stm/peripherals/exti.h +++ b/ports/stm/peripherals/exti.h @@ -10,13 +10,10 @@ #define STM32_GPIO_PORT_SIZE 16 -void exti_reset(void); -void stm_peripherals_exti_never_reset(uint8_t num); void stm_peripherals_exti_reset_exti(uint8_t num); bool stm_peripherals_exti_is_free(uint8_t num); bool stm_peripherals_exti_reserve(uint8_t num); void stm_peripherals_exti_enable(uint8_t num); void stm_peripherals_exti_disable(uint8_t num); void stm_peripherals_exti_set_callback(void (*callback)(uint8_t num), uint8_t number); -void stm_peripherals_exti_free(uint8_t num); IRQn_Type stm_peripherals_exti_get_irq(uint8_t num); diff --git a/ports/stm/peripherals/periph.h b/ports/stm/peripherals/periph.h index e1a922cebc9..3b76deede43 100644 --- a/ports/stm/peripherals/periph.h +++ b/ports/stm/peripherals/periph.h @@ -30,7 +30,7 @@ typedef struct { // Timer Peripheral typedef struct { - uint8_t tim_index : 4; + uint8_t tim_index : 5; uint8_t altfn_index : 4; uint8_t channel_index : 4; const mcu_pin_obj_t *pin; @@ -68,6 +68,13 @@ typedef struct { #include "stm32f4/stm32f412cx/periph.h" #endif +#ifdef STM32F412Rx +#define HAS_DAC 0 +#define HAS_TRNG 1 +#define HAS_BASIC_TIM 1 +#include "stm32f4/stm32f412rx/periph.h" +#endif + #ifdef STM32F412Zx #define HAS_DAC 0 #define HAS_TRNG 1 @@ -84,6 +91,13 @@ typedef struct { #include "stm32l4/stm32l4r5xx/periph.h" #endif +#ifdef STM32L433xx +#define HAS_DAC 1 +#define HAS_TRNG 1 +#define HAS_BASIC_TIM 1 +#include "stm32l4/stm32l433xx/periph.h" +#endif + #ifdef STM32F405xx #define HAS_DAC 1 #define HAS_TRNG 1 @@ -137,3 +151,7 @@ typedef struct { #define HAS_BASIC_TIM 1 #include "stm32h7/stm32h750xx/periph.h" #endif + +#if !defined(HAS_DAC) +#error Unknown MCU +#endif diff --git a/ports/stm/peripherals/pins.h b/ports/stm/peripherals/pins.h index 7720ce0a1e0..39dcadb84ea 100644 --- a/ports/stm/peripherals/pins.h +++ b/ports/stm/peripherals/pins.h @@ -64,12 +64,18 @@ extern const mp_obj_type_t mcu_pin_type; #ifdef STM32F412Cx #include "stm32f4/stm32f412cx/pins.h" #endif +#ifdef STM32F412Rx +#include "stm32f4/stm32f412rx/pins.h" +#endif #ifdef STM32F412Zx #include "stm32f4/stm32f412zx/pins.h" #endif #ifdef STM32L4R5xx #include "stm32l4/stm32l4r5xx/pins.h" #endif +#ifdef STM32L433xx +#include "stm32l4/stm32l433xx/pins.h" +#endif #ifdef STM32F405xx #include "stm32f4/stm32f405xx/pins.h" #endif diff --git a/ports/stm/peripherals/rtc.c b/ports/stm/peripherals/rtc.c index 78ee4548834..12fb5ff2818 100644 --- a/ports/stm/peripherals/rtc.c +++ b/ports/stm/peripherals/rtc.c @@ -13,15 +13,27 @@ // Default period for ticks is 1/1024 second #define TICKS_PER_SECOND 1024 -// Based on a 32768 kHz clock +// A subtick is 1/32768 second, one period of a 32768 Hz crystal. #define SUBTICKS_PER_TICK 32 +#define SUBTICKS_PER_SECOND (TICKS_PER_SECOND * SUBTICKS_PER_TICK) static RTC_HandleTypeDef hrtc; #if BOARD_HAS_LOW_SPEED_CRYSTAL static uint32_t rtc_clock_frequency = LSE_VALUE; +static uint32_t rtc_subseconds_per_second = LSE_VALUE; #else +// LSI_VALUE is only the nominal frequency. stm32_peripherals_rtc_init() measures the real one. static uint32_t rtc_clock_frequency = LSI_VALUE; +static uint32_t rtc_subseconds_per_second = LSI_VALUE; + +// The LSI is an RC oscillator: the F4 datasheets allow 17 to 47 kHz. A measurement outside +// this range means something went wrong, so the nominal value is kept. +#define LSI_MIN_FREQUENCY 15000 +#define LSI_MAX_FREQUENCY 50000 +// About 1/30 second. Each end of the measurement is found to within one pass of the polling +// loop, well under a microsecond, so this gives the frequency to about 30 ppm. +#define LSI_MEASURE_STEPS 1024 #endif volatile uint32_t seconds_to_date = 0; @@ -43,10 +55,81 @@ bool peripherals_wkup_on = false; static void (*wkup_callback)(void); static void (*alarm_callbacks[2])(void); -uint32_t stm32_peripherals_get_rtc_freq(void) { - return rtc_clock_frequency; +// Set the prescalers so that the calendar advances once per second of rtc_clock_frequency. +static void rtc_set_prescalers(void) { + // Divide async as little as possible so that the subsecond counter has the finest steps. + // The sync prescaler has 15 bits, so a clock above 32768 Hz needs an async divider of 2. + uint32_t async_divider = (rtc_clock_frequency + 32767) / 32768; + rtc_subseconds_per_second = (rtc_clock_frequency + async_divider / 2) / async_divider; + hrtc.Init.AsynchPrediv = async_divider - 1; + hrtc.Init.SynchPrediv = rtc_subseconds_per_second - 1; + HAL_RTC_Init(&hrtc); +} + +#if !BOARD_HAS_LOW_SPEED_CRYSTAL +// With the shadow registers bypassed, a read can catch SSR as it changes. Read it until two +// reads agree. +static uint32_t rtc_read_ssr(void) { + uint32_t ssr; + do { + ssr = RTC->SSR; + } while (ssr != RTC->SSR); + return ssr; } +// Count the CPU cycles taken by LSI_MEASURE_STEPS steps of the subsecond counter. The CPU clock +// comes from the HSE crystal, so it is accurate. The async divider must be 1 (PREDIV_A = 0), so +// that each step is one LSI period. Returns the LSI frequency in Hz, or 0 if it could not be +// measured. +static uint32_t rtc_measure_lsi(void) { + CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk; + #if __CORTEX_M == 7 + // The Cortex-M7 ignores writes to the DWT until it is unlocked. + DWT->LAR = 0xC5ACCE55; + #endif + DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk; + + uint32_t last_step = DWT->CYCCNT; + uint32_t ssr = rtc_read_ssr(); + if (DWT->CYCCNT == last_step) { + // The cycle counter is not running: reading SSR takes several cycles. + return 0; + } + // Twice the longest possible LSI period. + uint32_t timeout = SystemCoreClock / (LSI_MIN_FREQUENCY / 2); + uint32_t start = 0; + uint32_t steps = 0; + bool started = false; + + // An interrupt at the start or end would delay the cycle count. + __disable_irq(); + while (steps < LSI_MEASURE_STEPS) { + uint32_t new_ssr = rtc_read_ssr(); + uint32_t now = DWT->CYCCNT; + if (new_ssr == ssr) { + if (now - last_step > timeout) { + __enable_irq(); + return 0; + } + continue; + } + if (started) { + // SSR counts down, and reloads with PREDIV_S after 0. + steps += (ssr + rtc_subseconds_per_second - new_ssr) % rtc_subseconds_per_second; + } else { + start = now; + started = true; + } + ssr = new_ssr; + last_step = now; + } + __enable_irq(); + + uint32_t cycles = last_step - start; + return ((uint64_t)SystemCoreClock * steps + cycles / 2) / cycles; +} +#endif + void stm32_peripherals_rtc_init(void) { rtc_ticks_offset = 0; rtc_subticks_offset = 0; @@ -55,14 +138,18 @@ void stm32_peripherals_rtc_init(void) { __HAL_RCC_RTC_ENABLE(); hrtc.Instance = RTC; hrtc.Init.HourFormat = RTC_HOURFORMAT_24; - // Divide async as little as possible so that we have rtc_clock_frequency count in subseconds. - // This ensures our timing > 1 second is correct. - hrtc.Init.AsynchPrediv = 0x0; - hrtc.Init.SynchPrediv = rtc_clock_frequency - 1; hrtc.Init.OutPut = RTC_OUTPUT_DISABLE; - HAL_RTC_Init(&hrtc); + rtc_set_prescalers(); HAL_RTCEx_EnableBypassShadow(&hrtc); + + #if !BOARD_HAS_LOW_SPEED_CRYSTAL + uint32_t lsi_frequency = rtc_measure_lsi(); + if (lsi_frequency >= LSI_MIN_FREQUENCY && lsi_frequency <= LSI_MAX_FREQUENCY) { + rtc_clock_frequency = lsi_frequency; + rtc_set_prescalers(); + } + #endif HAL_NVIC_EnableIRQ(RTC_Alarm_IRQn); } @@ -70,7 +157,10 @@ void stm32_peripherals_rtc_init(void) { // register value. The STM HAL always does shifts and conversion if we use it directly. static uint64_t stm32_peripherals_rtc_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. + // SSR twice to make sure we didn't read across a tick. The caller may have disabled them + // already (the HAL reads the time inside supervisor_disable_tick(), and on H7 and L4 inside + // supervisor_enable_tick() too), so restore their state afterwards instead of enabling them. + uint32_t primask = __get_PRIMASK(); __disable_irq(); uint32_t first_ssr = (uint32_t)(RTC->SSR); uint32_t time = (uint32_t)(RTC->TR & RTC_TR_RESERVED_MASK); @@ -82,9 +172,13 @@ static uint64_t stm32_peripherals_rtc_raw_ticks(uint8_t *subticks) { date = (uint32_t)(RTC->DR & RTC_DR_RESERVED_MASK); ssr = (uint32_t)(RTC->SSR); } - __enable_irq(); + __set_PRIMASK(primask); - uint32_t subseconds = rtc_clock_frequency - 1 - ssr; + uint32_t subseconds = rtc_subseconds_per_second - 1 - ssr; + // Unless the RTC clock is 32768 Hz, a step of the subsecond counter is not a whole subtick, + // so scale. subseconds < rtc_subseconds_per_second <= 32768 (the synchronous prescaler has + // 15 bits), so the product is below 2^30. + uint32_t subticks_in_second = subseconds * SUBTICKS_PER_SECOND / rtc_subseconds_per_second; if (date != cached_date) { uint32_t year = (uint8_t)((date & (RTC_DR_YT | RTC_DR_YU)) >> 16U); @@ -109,10 +203,10 @@ static uint64_t stm32_peripherals_rtc_raw_ticks(uint8_t *subticks) { uint8_t seconds = (uint8_t)(time & (RTC_TR_ST | RTC_TR_SU)); seconds = (uint8_t)RTC_Bcd2ToByte(seconds); if (subticks != NULL) { - *subticks = subseconds % SUBTICKS_PER_TICK; + *subticks = subticks_in_second % SUBTICKS_PER_TICK; } - uint64_t raw_ticks = ((uint64_t)TICKS_PER_SECOND) * (seconds_to_date + seconds_to_minute + seconds) + subseconds / SUBTICKS_PER_TICK; + uint64_t raw_ticks = ((uint64_t)TICKS_PER_SECOND) * (seconds_to_date + seconds_to_minute + seconds) + subticks_in_second / SUBTICKS_PER_TICK; return raw_ticks; } @@ -128,7 +222,9 @@ uint64_t stm32_peripherals_rtc_monotonic_ticks(uint8_t *subticks) { monotonic_ticks--; monotonic_subticks += SUBTICKS_PER_TICK; } - *subticks = (uint8_t)monotonic_subticks; + if (subticks != NULL) { + *subticks = (uint8_t)monotonic_subticks; + } return monotonic_ticks; } @@ -191,16 +287,10 @@ void stm32_peripherals_rtc_assign_wkup_callback(void (*callback)(void)) { wkup_callback = callback; } -void stm32_peripherals_rtc_set_wakeup_mode_seconds(uint32_t seconds) { - // prep stuff from CubeMX - __HAL_PWR_CLEAR_FLAG(PWR_FLAG_WU); - __HAL_RTC_WAKEUPTIMER_CLEAR_FLAG(&hrtc, RTC_FLAG_WUTF); - - HAL_RTCEx_SetWakeUpTimer_IT(&hrtc, (rtc_clock_frequency / 16) * seconds, RTC_WAKEUPCLOCK_RTCCLK_DIV16); -} - void stm32_peripherals_rtc_set_wakeup_mode_tick(void) { - HAL_RTCEx_SetWakeUpTimer_IT(&hrtc, (rtc_clock_frequency / 16) / TICKS_PER_SECOND, RTC_WAKEUPCLOCK_RTCCLK_DIV2); + // The timer counts RTCCLK / 2 and wakes every (counter + 1) counts. + uint32_t counter = (rtc_clock_frequency + TICKS_PER_SECOND) / (2 * TICKS_PER_SECOND) - 1; + HAL_RTCEx_SetWakeUpTimer_IT(&hrtc, counter, RTC_WAKEUPCLOCK_RTCCLK_DIV2); } void stm32_peripherals_rtc_enable_wakeup_timer(void) { @@ -215,22 +305,46 @@ void stm32_peripherals_rtc_disable_wakeup_timer(void) { HAL_RTCEx_DeactivateWakeUpTimer(&hrtc); } +// A clear of the wakeup flag is lost if it comes less than 1.5 RTCCLK periods before the timer +// sets the flag again, for example when a flash erase has held off the interrupt. The flag then +// stays set, the EXTI line sees no new rising edge, and the tick stops. Call with interrupts +// disabled: if that has happened, run the handler again so that it clears the flag. +void stm32_peripherals_rtc_recover_wakeup(void) { + if (peripherals_wkup_on && __HAL_RTC_WAKEUPTIMER_GET_FLAG(&hrtc, RTC_FLAG_WUTF) && + !__HAL_RTC_WAKEUPTIMER_EXTI_GET_FLAG()) { + NVIC_SetPendingIRQ(RTC_WKUP_IRQn); + } +} + void stm32_peripherals_rtc_reset_alarms(void) { HAL_RTC_DeactivateAlarm(&hrtc, RTC_ALARM_A); HAL_RTC_DeactivateAlarm(&hrtc, RTC_ALARM_B); } +void stm32_peripherals_rtc_cancel_alarm(uint8_t alarm_idx) { + HAL_RTC_DeactivateAlarm(&hrtc, (alarm_idx == PERIPHERALS_ALARM_A) ? RTC_ALARM_A : RTC_ALARM_B); +} + void stm32_peripherals_rtc_assign_alarm_callback(uint8_t alarm_idx, void (*callback)(void)) { alarm_callbacks[alarm_idx] = callback; } void stm32_peripherals_rtc_set_alarm(uint8_t alarm_idx, uint32_t ticks) { - uint64_t raw_ticks = stm32_peripherals_rtc_raw_ticks(NULL) + ticks; + // Count from the current subtick, not from the start of the current tick, which would make + // the alarm up to a tick early. + uint8_t subticks; + uint64_t target = (stm32_peripherals_rtc_raw_ticks(&subticks) + ticks) * SUBTICKS_PER_TICK + subticks; + // The first subsecond count at which stm32_peripherals_rtc_raw_ticks() reaches the target: + // the inverse of its scaling, rounded up. Both factors of the product are at most 32768, so it + // is below 2^30. Rounding up can give a whole second, so add it to the seconds before splitting. + uint32_t subticks_in_second = target % SUBTICKS_PER_SECOND; + uint64_t count = (target / SUBTICKS_PER_SECOND) * rtc_subseconds_per_second + + (subticks_in_second * rtc_subseconds_per_second + SUBTICKS_PER_SECOND - 1) / SUBTICKS_PER_SECOND; RTC_AlarmTypeDef alarm; if (ticks > TICKS_PER_SECOND) { timeutils_struct_time_t tm; - timeutils_seconds_since_2000_to_struct_time(raw_ticks / TICKS_PER_SECOND, &tm); + timeutils_seconds_since_2000_to_struct_time(count / rtc_subseconds_per_second, &tm); alarm.AlarmTime.Hours = tm.tm_hour; alarm.AlarmTime.Minutes = tm.tm_min; alarm.AlarmTime.Seconds = tm.tm_sec; @@ -243,12 +357,7 @@ void stm32_peripherals_rtc_set_alarm(uint8_t alarm_idx, uint32_t ticks) { alarm.AlarmMask = RTC_ALARMMASK_ALL; } - alarm.AlarmTime.SubSeconds = rtc_clock_frequency - 1 - - ((raw_ticks % TICKS_PER_SECOND) * SUBTICKS_PER_TICK); - if (alarm.AlarmTime.SubSeconds > rtc_clock_frequency) { - alarm.AlarmTime.SubSeconds = alarm.AlarmTime.SubSeconds + - rtc_clock_frequency; - } + alarm.AlarmTime.SubSeconds = rtc_subseconds_per_second - 1 - count % rtc_subseconds_per_second; 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. @@ -258,6 +367,15 @@ void stm32_peripherals_rtc_set_alarm(uint8_t alarm_idx, uint32_t ticks) { HAL_RTC_SetAlarm_IT(&hrtc, &alarm, RTC_FORMAT_BIN); HAL_NVIC_EnableIRQ(RTC_Alarm_IRQn); alarmed_already[alarm_idx] = false; + // The alarm matches only its exact subsecond count, and arming it takes a few RTC periods. + // If the target is less than a quarter tick away (or past), act as if the alarm had fired. + uint64_t now = stm32_peripherals_rtc_raw_ticks(&subticks); + if (now * SUBTICKS_PER_TICK + subticks + SUBTICKS_PER_TICK / 4 >= target) { + if (alarm_callbacks[alarm_idx]) { + alarm_callbacks[alarm_idx](); + } + alarmed_already[alarm_idx] = true; + } } bool stm32_peripherals_rtc_alarm_triggered(uint8_t alarm_idx) { diff --git a/ports/stm/peripherals/rtc.h b/ports/stm/peripherals/rtc.h index 9d47ece8982..a206e06df55 100644 --- a/ports/stm/peripherals/rtc.h +++ b/ports/stm/peripherals/rtc.h @@ -13,17 +13,17 @@ #define PERIPHERALS_ALARM_A 0 #define PERIPHERALS_ALARM_B 1 -uint32_t stm32_peripherals_get_rtc_freq(void); void stm32_peripherals_rtc_init(void); uint64_t stm32_peripherals_rtc_monotonic_ticks(uint8_t *subticks); void stm32_peripherals_rtc_assign_wkup_callback(void (*callback)(void)); -void stm32_peripherals_rtc_set_wakeup_mode_seconds(uint32_t seconds); void stm32_peripherals_rtc_set_wakeup_mode_tick(void); void stm32_peripherals_rtc_enable_wakeup_timer(void); void stm32_peripherals_rtc_disable_wakeup_timer(void); +void stm32_peripherals_rtc_recover_wakeup(void); void stm32_peripherals_rtc_reset_alarms(void); +void stm32_peripherals_rtc_cancel_alarm(uint8_t alarm_idx); void stm32_peripherals_rtc_assign_alarm_callback(uint8_t alarm_idx, void (*callback)(void)); void stm32_peripherals_rtc_set_alarm(uint8_t alarm_idx, uint32_t ticks); bool stm32_peripherals_rtc_alarm_triggered(uint8_t alarm_idx); diff --git a/ports/stm/peripherals/sdram.c b/ports/stm/peripherals/sdram.c new file mode 100644 index 00000000000..31ffe780035 --- /dev/null +++ b/ports/stm/peripherals/sdram.c @@ -0,0 +1,292 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 snkYmkrct +// +// based on implementation from https://github.com/micropython/micropython/blob/master/ports/stm32/sdram.c +// +// SPDX-License-Identifier: MIT + +#include +#include +#include +#include +#include STM32_HAL_H +#include "common-hal/microcontroller/Pin.h" +#include "peripherals/periph.h" +#if defined(STM32H7) +#include "stm32h7xx_ll_fmc.h" +#include "stm32h7xx_hal_sdram.h" +#include "stm32h7xx_hal_gpio.h" +#include "stm32h7xx_hal_cortex.h" +#endif +#ifdef STM32H750xx +#include "stm32h7/stm32h750xx/periph.h" +#endif + + +#include "sdram.h" + + +#if MICROPY_DEBUG_VERBOSE // print debugging info +#define DEBUG_PRINT (1) +#define DEBUG_printf DEBUG_printf +#define DEBUG_OP_printf(...) DEBUG_printf(__VA_ARGS__) +#else // don't print debugging info +#define DEBUG_printf(...) (void)0 +#define DEBUG_OP_printf(...) (void)0 +#endif + +#define SDRAM_TIMEOUT ((uint32_t)0xFFFF) +#define CIRCUITPY_HW_SDRAM_STARTUP_TEST (0) + +static uint8_t FMC_Initialized = 0; +static SDRAM_HandleTypeDef hsdram = {0}; +static uint32_t sdram_start_address = 0; + + +static void sdram_init_seq(const struct stm32_sdram_config *config); + +void sdram_init(const struct stm32_sdram_config *config) { + FMC_SDRAM_TimingTypeDef SDRAM_Timing = {0}; + + if (!FMC_Initialized) { + + RCC_PeriphCLKInitTypeDef PeriphClkInitStruct = {0}; + + /** Initializes the peripherals clock + */ + PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_FMC; + PeriphClkInitStruct.FmcClockSelection = RCC_FMCCLKSOURCE_D1HCLK; + if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct) != HAL_OK) { + DEBUG_printf("sdram: %s", "periph init clock error"); + } + /* Peripheral clock enable */ + __HAL_RCC_FMC_CLK_ENABLE(); + FMC_Initialized = 1; + for (uint i = 0; i < MP_ARRAY_SIZE(sdram_pin_list); i++) { + GPIO_InitTypeDef GPIO_InitStruct = {0}; + GPIO_InitStruct.Pin = pin_mask(sdram_pin_list[i].pin->number); + GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; + GPIO_InitStruct.Pull = GPIO_NOPULL; + GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; + GPIO_InitStruct.Alternate = GPIO_AF12_FMC; + HAL_GPIO_Init(pin_port(sdram_pin_list[i].pin->port), &GPIO_InitStruct); + } + } + + /* SDRAM device configuration */ + hsdram.Instance = config->sdram; + + for (size_t i = 0U; i < config->banks_len; i++) { + hsdram.State = HAL_SDRAM_STATE_RESET; + + memcpy(&hsdram.Init, &config->banks[i].init, sizeof(hsdram.Init)); + + memcpy(&SDRAM_Timing, &config->banks[i].timing, sizeof(SDRAM_Timing)); + + /* Initialize the SDRAM controller */ + if (HAL_SDRAM_Init(&hsdram, &SDRAM_Timing) != HAL_OK) { + DEBUG_printf("sdram bank[%d]: %s", i, "init error"); + } + } + + sdram_init_seq(config); + +} +void sdram_deinit(void) { + FMC_SDRAM_CommandTypeDef command = {0}; + if (FMC_Initialized) { + /* Send the module into powerdown mode */ + command.CommandMode = FMC_SDRAM_CMD_POWERDOWN_MODE; + command.CommandTarget = FMC_SDRAM_CMD_TARGET_BANK1; + command.AutoRefreshNumber = 1; + command.ModeRegisterDefinition = 0; + + /* Send the command */ + if (HAL_SDRAM_SendCommand(&hsdram, &command, HAL_MAX_DELAY) != HAL_OK) { + DEBUG_printf("sdram power off error:%s:%d", __func__, __LINE__); + } + } +} + +void *sdram_start(void) { + return (void *)sdram_start_address; +} + +void *sdram_end(void) { + return (void *)(sdram_start_address + CIRCUITPY_HW_SDRAM_SIZE); +} + +uint32_t sdram_size(void) { + return CIRCUITPY_HW_SDRAM_SIZE; +} + +static void sdram_init_seq(const struct stm32_sdram_config *config) { + FMC_SDRAM_CommandTypeDef command = {0}; + /* Program the SDRAM external device */ + + command.AutoRefreshNumber = config->num_auto_refresh; + command.ModeRegisterDefinition = config->mode_register; + if (config->banks_len == 2U) { + command.CommandTarget = FMC_SDRAM_CMD_TARGET_BANK1_2; + sdram_start_address = 0xC0000000; + } else if (config->banks[0].init.SDBank == FMC_SDRAM_BANK1) { + command.CommandTarget = FMC_SDRAM_CMD_TARGET_BANK1; + sdram_start_address = 0xC0000000; + } else { + command.CommandTarget = FMC_SDRAM_CMD_TARGET_BANK2; + sdram_start_address = 0xD0000000; + + } + + /* Configure a clock configuration enable command */ + command.CommandMode = FMC_SDRAM_CMD_CLK_ENABLE; + HAL_SDRAM_SendCommand(&hsdram, &command, HAL_MAX_DELAY); + + HAL_Delay(config->power_up_delay); + + /* Configure a PALL (precharge all) command */ + command.CommandMode = FMC_SDRAM_CMD_PALL; + HAL_SDRAM_SendCommand(&hsdram, &command, HAL_MAX_DELAY); + + /* Configure a Auto-Refresh command */ + command.CommandMode = FMC_SDRAM_CMD_AUTOREFRESH_MODE; + HAL_SDRAM_SendCommand(&hsdram, &command, HAL_MAX_DELAY); + + command.CommandMode = FMC_SDRAM_CMD_LOAD_MODE; + /* load mode */ + HAL_SDRAM_SendCommand(&hsdram, &command, HAL_MAX_DELAY); + + /* program refresh count */ + HAL_SDRAM_ProgramRefreshRate(&hsdram, config->refresh_rate); + + #if defined(STM32F7) || defined(STM32H7) + __disable_irq(); + MPU_Region_InitTypeDef MPU_InitStruct = {0}; + /** Enable caching for SDRAM to support non-alligned access. + */ + MPU_InitStruct.Enable = MPU_REGION_ENABLE; + MPU_InitStruct.Number = CPY_SDRAM_REGION; + MPU_InitStruct.BaseAddress = sdram_start_address; + MPU_InitStruct.Size = CPY_SDRAM_REGION_SIZE; + MPU_InitStruct.SubRegionDisable = 0x0; + MPU_InitStruct.TypeExtField = MPU_TEX_LEVEL1; + MPU_InitStruct.AccessPermission = MPU_REGION_FULL_ACCESS; + MPU_InitStruct.DisableExec = MPU_INSTRUCTION_ACCESS_ENABLE; + MPU_InitStruct.IsShareable = MPU_ACCESS_NOT_SHAREABLE; + MPU_InitStruct.IsCacheable = MPU_ACCESS_CACHEABLE; + MPU_InitStruct.IsBufferable = MPU_ACCESS_BUFFERABLE; + + HAL_MPU_ConfigRegion(&MPU_InitStruct); + __ISB(); + __DSB(); + __DMB(); + __enable_irq(); + + #endif + +} + +#if defined(CIRCUITPY_HW_SDRAM_STARTUP_TEST) && (CIRCUITPY_HW_SDRAM_STARTUP_TEST == 1) + +bool __attribute__((optimize("Os"))) sdram_test(bool exhaustive) { + uint8_t const pattern = 0xaa; + uint8_t const antipattern = 0x55; + volatile uint8_t *const mem_base = (uint8_t *)sdram_start(); + + char error_buffer[1024]; + + DEBUG_printf("sdram: %s\n", "sdram test started"); + + #if (__DCACHE_PRESENT == 1) + bool i_cache_disabled = false; + bool d_cache_disabled = false; + + // Disable caches for testing. + if (SCB->CCR & (uint32_t)SCB_CCR_IC_Msk) { + SCB_DisableICache(); + i_cache_disabled = true; + } + + if (SCB->CCR & (uint32_t)SCB_CCR_DC_Msk) { + SCB_DisableDCache(); + d_cache_disabled = true; + } + #endif + + // Test data bus + for (uint32_t i = 0; i < hsdram.Init.MemoryDataWidth; i++) { + *((volatile uint32_t *)mem_base) = (1u << i); + __DSB(); + if (*((volatile uint32_t *)mem_base) != (1u << i)) { + snprintf(error_buffer, sizeof(error_buffer), + "Data bus test failed at 0x%p expected 0x%x found 0x%lx", + &mem_base[0], (1 << i), ((volatile uint32_t *)mem_base)[0]); + DEBUG_printf("error: %s\n", error_buffer); + return false; + } + } + + // Test address bus + for (uint32_t i = 1; i < CIRCUITPY_HW_SDRAM_SIZE; i <<= 1) { + mem_base[i] = pattern; + __DSB(); + if (mem_base[i] != pattern) { + snprintf(error_buffer, sizeof(error_buffer), + "Address bus test failed at 0x%p expected 0x%x found 0x%x", + &mem_base[i], pattern, mem_base[i]); + DEBUG_printf("error: %s\n", error_buffer); + return false; + } + } + + // Check for aliasing (overlapping addresses) + mem_base[0] = antipattern; + __DSB(); + for (uint32_t i = 1; i < CIRCUITPY_HW_SDRAM_SIZE; i <<= 1) { + if (mem_base[i] != pattern) { + snprintf(error_buffer, sizeof(error_buffer), + "Address bus overlap at 0x%p expected 0x%x found 0x%x", + &mem_base[i], pattern, mem_base[i]); + DEBUG_printf("error: %s\n", error_buffer); + return false; + } + } + + // Test all RAM cells + if (exhaustive) { + // Write all memory first then compare, so even if the cache + // is enabled, it's not just writing and reading from cache. + // Note: This test should also detect refresh rate issues. + for (uint32_t i = 0; i < CIRCUITPY_HW_SDRAM_SIZE; i++) { + mem_base[i] = ((i % 2) ? pattern : antipattern); + } + + for (uint32_t i = 0; i < CIRCUITPY_HW_SDRAM_SIZE; i++) { + if (mem_base[i] != ((i % 2) ? pattern : antipattern)) { + snprintf(error_buffer, sizeof(error_buffer), + "Address bus slow test failed at 0x%p expected 0x%x found 0x%x", + &mem_base[i], ((i % 2) ? pattern : antipattern), mem_base[i]); + DEBUG_printf("error: %s\n", error_buffer); + return false; + } + } + } + + #if (__DCACHE_PRESENT == 1) + // Re-enable caches if they were enabled before the test started. + if (i_cache_disabled) { + SCB_EnableICache(); + } + + if (d_cache_disabled) { + SCB_EnableDCache(); + } + #endif + + DEBUG_printf("sdram: %s\n", "sdram test successfully!"); + + return true; +} + +#endif // sdram_test diff --git a/ports/stm/peripherals/sdram.h b/ports/stm/peripherals/sdram.h new file mode 100644 index 00000000000..46343b6861e --- /dev/null +++ b/ports/stm/peripherals/sdram.h @@ -0,0 +1,47 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 snkYmkrct +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "stm32h7xx_ll_fmc.h" +#include +#include + +#define SDRAM_MODEREG_BURST_LENGTH_1 ((uint16_t)0x0000) +#define SDRAM_MODEREG_BURST_LENGTH_2 ((uint16_t)0x0001) +#define SDRAM_MODEREG_BURST_LENGTH_4 ((uint16_t)0x0002) +#define SDRAM_MODEREG_BURST_LENGTH_8 ((uint16_t)0x0004) +#define SDRAM_MODEREG_BURST_TYPE_SEQUENTIAL ((uint16_t)0x0000) +#define SDRAM_MODEREG_BURST_TYPE_INTERLEAVED ((uint16_t)0x0008) +#define SDRAM_MODEREG_CAS_LATENCY_2 ((uint16_t)0x0020) +#define SDRAM_MODEREG_CAS_LATENCY_3 ((uint16_t)0x0030) +#define SDRAM_MODEREG_OPERATING_MODE_STANDARD ((uint16_t)0x0000) +#define SDRAM_MODEREG_WRITEBURST_MODE_PROGRAMMED ((uint16_t)0x0000) +#define SDRAM_MODEREG_WRITEBURST_MODE_SINGLE ((uint16_t)0x0200) + +/** FMC SDRAM controller bank configuration fields. */ +struct stm32_sdram_bank_config { + FMC_SDRAM_InitTypeDef init; + FMC_SDRAM_TimingTypeDef timing; +}; + +/** FMC SDRAM controller configuration fields. */ +struct stm32_sdram_config { + FMC_SDRAM_TypeDef *sdram; + uint32_t power_up_delay; + uint8_t num_auto_refresh; + uint16_t mode_register; + uint16_t refresh_rate; + const struct stm32_sdram_bank_config *banks; + size_t banks_len; +}; + +void sdram_init(const struct stm32_sdram_config *config); +void sdram_deinit(void); +void *sdram_start(void); +void *sdram_end(void); +uint32_t sdram_size(void); +bool sdram_test(bool exhaustive); diff --git a/ports/stm/peripherals/stm32f4/clocks.c b/ports/stm/peripherals/stm32f4/clocks.c index 0730d8ebacc..3475617e9d2 100644 --- a/ports/stm/peripherals/stm32f4/clocks.c +++ b/ports/stm/peripherals/stm32f4/clocks.c @@ -18,6 +18,9 @@ #ifdef STM32F412Cx #include "stm32f4/stm32f412cx/clocks.h" #endif +#ifdef STM32F412Rx +#include "stm32f4/stm32f412rx/clocks.h" +#endif #ifdef STM32F412Zx #include "stm32f4/stm32f412zx/clocks.h" #endif diff --git a/ports/stm/peripherals/stm32f4/stm32f401xe/gpio.c b/ports/stm/peripherals/stm32f4/stm32f401xe/gpio.c index 7e1809175f5..1a5267d510b 100644 --- a/ports/stm/peripherals/stm32f4/stm32f401xe/gpio.c +++ b/ports/stm/peripherals/stm32f4/stm32f401xe/gpio.c @@ -16,9 +16,9 @@ void stm32_peripherals_gpio_init(void) { __HAL_RCC_GPIOE_CLK_ENABLE(); __HAL_RCC_GPIOH_CLK_ENABLE(); - // Never reset pins - never_reset_pin_number(2, 14); // PC14 OSC32_IN - never_reset_pin_number(2, 15); // PC15 OSC32_OUT - never_reset_pin_number(0, 13); // PA13 SWDIO - never_reset_pin_number(0, 14); // PA14 SWCLK + // Pins in use by the system; mark them claimed so user code can't use them. + claim_pin(2, 14); // PC14 OSC32_IN + claim_pin(2, 15); // PC15 OSC32_OUT + claim_pin(0, 13); // PA13 SWDIO + claim_pin(0, 14); // PA14 SWCLK } diff --git a/ports/stm/peripherals/stm32f4/stm32f401xe/periph.c b/ports/stm/peripherals/stm32f4/stm32f401xe/periph.c index a5589c51f4d..dccc23cf9ef 100644 --- a/ports/stm/peripherals/stm32f4/stm32f401xe/periph.c +++ b/ports/stm/peripherals/stm32f4/stm32f401xe/periph.c @@ -67,14 +67,13 @@ const mcu_periph_obj_t mcu_spi_miso_list[8] = { PERIPH(4, 5, &pin_PE13), }; -const mcu_periph_obj_t mcu_spi_nss_list[9] = { +const mcu_periph_obj_t mcu_spi_nss_list[8] = { PERIPH(1, 5, &pin_PA04), PERIPH(1, 5, &pin_PA15), PERIPH(2, 5, &pin_PB09), PERIPH(2, 5, &pin_PB12), PERIPH(3, 6, &pin_PA04), PERIPH(3, 6, &pin_PA15), - PERIPH(4, 6, &pin_PB12), PERIPH(4, 5, &pin_PE04), PERIPH(4, 5, &pin_PE11), }; @@ -132,9 +131,9 @@ const mcu_tim_pin_obj_t mcu_tim_pin_list[44] = { TIM(4, 2, 1, &pin_PB06), TIM(4, 2, 2, &pin_PB07), TIM(4, 2, 3, &pin_PB08), - TIM(10, 2, 1, &pin_PB08), + TIM(10, 3, 1, &pin_PB08), TIM(4, 2, 4, &pin_PB09), - TIM(11, 2, 1, &pin_PB09), + TIM(11, 3, 1, &pin_PB09), TIM(2, 1, 3, &pin_PB10), TIM(3, 2, 1, &pin_PC06), TIM(3, 2, 2, &pin_PC07), diff --git a/ports/stm/peripherals/stm32f4/stm32f401xe/periph.h b/ports/stm/peripherals/stm32f4/stm32f401xe/periph.h index 6aa77eeb8ab..6d7101168e7 100644 --- a/ports/stm/peripherals/stm32f4/stm32f401xe/periph.h +++ b/ports/stm/peripherals/stm32f4/stm32f401xe/periph.h @@ -18,7 +18,7 @@ extern SPI_TypeDef *mcu_spi_banks[4]; extern const mcu_periph_obj_t mcu_spi_sck_list[9]; extern const mcu_periph_obj_t mcu_spi_mosi_list[9]; extern const mcu_periph_obj_t mcu_spi_miso_list[8]; -extern const mcu_periph_obj_t mcu_spi_nss_list[9]; +extern const mcu_periph_obj_t mcu_spi_nss_list[8]; // UART extern USART_TypeDef *mcu_uart_banks[MAX_UART]; diff --git a/ports/stm/peripherals/stm32f4/stm32f405xx/gpio.c b/ports/stm/peripherals/stm32f4/stm32f405xx/gpio.c index 9a1e8eac52c..1274763c53d 100644 --- a/ports/stm/peripherals/stm32f4/stm32f405xx/gpio.c +++ b/ports/stm/peripherals/stm32f4/stm32f405xx/gpio.c @@ -17,19 +17,14 @@ void stm32_peripherals_gpio_init(void) { __HAL_RCC_GPIOF_CLK_ENABLE(); __HAL_RCC_GPIOG_CLK_ENABLE(); - // Never reset pins - never_reset_pin_number(2, 13); // PC13 anti tamp - never_reset_pin_number(2, 14); // PC14 OSC32_IN - never_reset_pin_number(2, 15); // PC15 OSC32_OUT - never_reset_pin_number(0, 13); // PA13 SWDIO - never_reset_pin_number(0, 14); // PA14 SWCLK - // never_reset_pin_number(0,15); //PA15 JTDI - // never_reset_pin_number(1,3); //PB3 JTDO - // never_reset_pin_number(1,4); //PB4 JTRST + // Pins in use by the system; mark them claimed so user code can't use them. + claim_pin(2, 13); // PC13 anti tamp + claim_pin(2, 14); // PC14 OSC32_IN + claim_pin(2, 15); // PC15 OSC32_OUT + claim_pin(0, 13); // PA13 SWDIO + claim_pin(0, 14); // PA14 SWCLK // Port H is not included in GPIO port array - // never_reset_pin_number(5,0); //PH0 JTDO - // never_reset_pin_number(5,1); //PH1 JTRST } void stm32f4_peripherals_status_led(uint8_t led, uint8_t state) { diff --git a/ports/stm/peripherals/stm32f4/stm32f407xx/gpio.c b/ports/stm/peripherals/stm32f4/stm32f407xx/gpio.c index 9a1e8eac52c..1274763c53d 100644 --- a/ports/stm/peripherals/stm32f4/stm32f407xx/gpio.c +++ b/ports/stm/peripherals/stm32f4/stm32f407xx/gpio.c @@ -17,19 +17,14 @@ void stm32_peripherals_gpio_init(void) { __HAL_RCC_GPIOF_CLK_ENABLE(); __HAL_RCC_GPIOG_CLK_ENABLE(); - // Never reset pins - never_reset_pin_number(2, 13); // PC13 anti tamp - never_reset_pin_number(2, 14); // PC14 OSC32_IN - never_reset_pin_number(2, 15); // PC15 OSC32_OUT - never_reset_pin_number(0, 13); // PA13 SWDIO - never_reset_pin_number(0, 14); // PA14 SWCLK - // never_reset_pin_number(0,15); //PA15 JTDI - // never_reset_pin_number(1,3); //PB3 JTDO - // never_reset_pin_number(1,4); //PB4 JTRST + // Pins in use by the system; mark them claimed so user code can't use them. + claim_pin(2, 13); // PC13 anti tamp + claim_pin(2, 14); // PC14 OSC32_IN + claim_pin(2, 15); // PC15 OSC32_OUT + claim_pin(0, 13); // PA13 SWDIO + claim_pin(0, 14); // PA14 SWCLK // Port H is not included in GPIO port array - // never_reset_pin_number(5,0); //PH0 JTDO - // never_reset_pin_number(5,1); //PH1 JTRST } void stm32f4_peripherals_status_led(uint8_t led, uint8_t state) { diff --git a/ports/stm/peripherals/stm32f4/stm32f411xe/gpio.c b/ports/stm/peripherals/stm32f4/stm32f411xe/gpio.c index db53087fd24..5e5543d7370 100644 --- a/ports/stm/peripherals/stm32f4/stm32f411xe/gpio.c +++ b/ports/stm/peripherals/stm32f4/stm32f411xe/gpio.c @@ -17,20 +17,18 @@ void stm32_peripherals_gpio_init(void) { __HAL_RCC_GPIOB_CLK_ENABLE(); __HAL_RCC_GPIOD_CLK_ENABLE(); - // Never reset pins + // Pins in use by the system; mark them claimed so user code can't use them. // TODO: Move this out of peripherals. These helpers shouldn't reference anything CircuitPython // specific. - never_reset_pin_number(2, 14); // PC14 OSC32_IN - never_reset_pin_number(2, 15); // PC15 OSC32_OUT + claim_pin(2, 14); // PC14 OSC32_IN + claim_pin(2, 15); // PC15 OSC32_OUT #if !(BOARD_OVERWRITE_SWD) - never_reset_pin_number(0, 13); // PA13 SWDIO - never_reset_pin_number(0, 14); // PA14 SWCLK + claim_pin(0, 13); // PA13 SWDIO + claim_pin(0, 14); // PA14 SWCLK #endif // Port H is not included in GPIO port array - // never_reset_pin_number(5,0); //PH0 JTDO - // never_reset_pin_number(5,1); //PH1 JTRST } // LEDs are inverted on F411 DISCO diff --git a/ports/stm/peripherals/stm32f4/stm32f411xe/periph.c b/ports/stm/peripherals/stm32f4/stm32f411xe/periph.c index 0b53ae52758..3e170c0be69 100644 --- a/ports/stm/peripherals/stm32f4/stm32f411xe/periph.c +++ b/ports/stm/peripherals/stm32f4/stm32f411xe/periph.c @@ -153,9 +153,9 @@ const mcu_tim_pin_obj_t mcu_tim_pin_list[44] = { TIM(4, 2, 1, &pin_PB06), TIM(4, 2, 2, &pin_PB07), TIM(4, 2, 3, &pin_PB08), - TIM(10, 2, 1, &pin_PB08), + TIM(10, 3, 1, &pin_PB08), TIM(4, 2, 4, &pin_PB09), - TIM(11, 2, 1, &pin_PB09), + TIM(11, 3, 1, &pin_PB09), TIM(2, 1, 3, &pin_PB10), TIM(3, 2, 1, &pin_PC06), TIM(3, 2, 2, &pin_PC07), diff --git a/ports/stm/peripherals/stm32f4/stm32f412cx/gpio.c b/ports/stm/peripherals/stm32f4/stm32f412cx/gpio.c index 4cca79bf9e7..b6d45cef959 100644 --- a/ports/stm/peripherals/stm32f4/stm32f412cx/gpio.c +++ b/ports/stm/peripherals/stm32f4/stm32f412cx/gpio.c @@ -13,7 +13,7 @@ void stm32_peripherals_gpio_init(void) { __HAL_RCC_GPIOB_CLK_ENABLE(); __HAL_RCC_GPIOC_CLK_ENABLE(); - // Never reset pins - never_reset_pin_number(0, 13); // PA13 SWDIO - never_reset_pin_number(0, 14); // PA14 SWCLK + // Pins in use by the system; mark them claimed so user code can't use them. + claim_pin(0, 13); // PA13 SWDIO + claim_pin(0, 14); // PA14 SWCLK } diff --git a/ports/stm/peripherals/stm32f4/stm32f412rx/clocks.h b/ports/stm/peripherals/stm32f4/stm32f412rx/clocks.h new file mode 100644 index 00000000000..1b35a5e5eac --- /dev/null +++ b/ports/stm/peripherals/stm32f4/stm32f412rx/clocks.h @@ -0,0 +1,48 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 Lucian Copeland for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "stm32f4xx_hal.h" + +// Chip: STM32F412Rx +// Line Type: Access Line +// Speed: 100MHz (MAX) + +// Note - uses the I2S PLL for USB to enable full 100MHz operation, since USB +// can't get the right divisors from 100MHz PLL settings. + +// Defaults: +#ifndef CPY_CLK_VSCALE +#define CPY_CLK_VSCALE (PWR_REGULATOR_VOLTAGE_SCALE1) +#endif +#ifndef CPY_CLK_PLLN +#define CPY_CLK_PLLN (200) +#endif +#ifndef CPY_CLK_PLLP +#define CPY_CLK_PLLP (RCC_PLLP_DIV2) +#endif +#ifndef CPY_CLK_PLLQ +#define CPY_CLK_PLLQ (7) +#endif +#ifndef CPY_CLK_AHBDIV +#define CPY_CLK_AHBDIV (RCC_SYSCLK_DIV1) +#endif +#ifndef CPY_CLK_APB1DIV +#define CPY_CLK_APB1DIV (RCC_HCLK_DIV2) +#endif +#ifndef CPY_CLK_APB2DIV +#define CPY_CLK_APB2DIV (RCC_HCLK_DIV1) +#endif +#ifndef CPY_CLK_FLASH_LATENCY +#define CPY_CLK_FLASH_LATENCY (FLASH_LATENCY_3) +#endif +#ifndef CPY_CLK_USB_USES_AUDIOPLL +#define CPY_CLK_USB_USES_AUDIOPLL (1) +#endif +#ifndef BOARD_HSE_SOURCE +#define BOARD_HSE_SOURCE (RCC_HSE_ON) +#endif diff --git a/ports/stm/peripherals/stm32f4/stm32f412rx/gpio.c b/ports/stm/peripherals/stm32f4/stm32f412rx/gpio.c new file mode 100644 index 00000000000..822bf5ef76a --- /dev/null +++ b/ports/stm/peripherals/stm32f4/stm32f412rx/gpio.c @@ -0,0 +1,23 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Lucian Copeland for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "peripherals/gpio.h" +#include "common-hal/microcontroller/Pin.h" + +void stm32_peripherals_gpio_init(void) { + + __HAL_RCC_GPIOA_CLK_ENABLE(); + __HAL_RCC_GPIOB_CLK_ENABLE(); + __HAL_RCC_GPIOC_CLK_ENABLE(); + __HAL_RCC_GPIOD_CLK_ENABLE(); + __HAL_RCC_GPIOH_CLK_ENABLE(); + + // Pins in use by the system; mark them claimed so user code can't use them. + claim_pin(0, 13); // PA13 SWDIO + claim_pin(0, 14); // PA14 SWCLK + + // Port H is not included in GPIO port array +} diff --git a/ports/stm/peripherals/stm32f4/stm32f412rx/periph.c b/ports/stm/peripherals/stm32f4/stm32f412rx/periph.c new file mode 100644 index 00000000000..b5cad1b9685 --- /dev/null +++ b/ports/stm/peripherals/stm32f4/stm32f412rx/periph.c @@ -0,0 +1,181 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Lucian Copeland for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "py/obj.h" +#include "py/mphal.h" +#include "peripherals/pins.h" +#include "peripherals/periph.h" + +// I2C + +I2C_TypeDef *mcu_i2c_banks[3] = {I2C1, I2C2, I2C3}; + +const mcu_periph_obj_t mcu_i2c_sda_list[7] = { + PERIPH(1, 4, &pin_PB07), + PERIPH(1, 4, &pin_PB09), + PERIPH(2, 9, &pin_PB09), + PERIPH(2, 9, &pin_PB03), + PERIPH(3, 4, &pin_PC09), + PERIPH(3, 9, &pin_PB04), + PERIPH(3, 9, &pin_PB08) +}; + +const mcu_periph_obj_t mcu_i2c_scl_list[4] = { + PERIPH(1, 4, &pin_PB06), + PERIPH(1, 4, &pin_PB08), + PERIPH(2, 4, &pin_PB10), + PERIPH(3, 4, &pin_PA08) +}; + +// SPI + +SPI_TypeDef *mcu_spi_banks[5] = {SPI1, SPI2, SPI3, SPI4, SPI5}; + +const mcu_periph_obj_t mcu_spi_sck_list[10] = { + PERIPH(1, 5, &pin_PA05), + PERIPH(1, 5, &pin_PB03), + PERIPH(2, 5, &pin_PB10), + PERIPH(2, 5, &pin_PB13), + PERIPH(2, 5, &pin_PC07), + PERIPH(3, 6, &pin_PB03), + PERIPH(3, 7, &pin_PB12), + PERIPH(3, 6, &pin_PC10), + PERIPH(4, 6, &pin_PB13), + PERIPH(5, 6, &pin_PB00) +}; + +const mcu_periph_obj_t mcu_spi_mosi_list[9] = { + PERIPH(1, 5, &pin_PA07), + PERIPH(1, 5, &pin_PB05), + PERIPH(2, 5, &pin_PB15), + PERIPH(2, 5, &pin_PC03), + PERIPH(3, 6, &pin_PB05), + PERIPH(3, 6, &pin_PC12), + PERIPH(4, 5, &pin_PA01), + PERIPH(5, 6, &pin_PA10), + PERIPH(5, 6, &pin_PB08) +}; + +const mcu_periph_obj_t mcu_spi_miso_list[8] = { + PERIPH(1, 5, &pin_PA06), + PERIPH(1, 5, &pin_PB04), + PERIPH(2, 5, &pin_PB14), + PERIPH(2, 5, &pin_PC02), + PERIPH(3, 6, &pin_PB04), + PERIPH(3, 6, &pin_PC11), + PERIPH(4, 6, &pin_PA11), + PERIPH(5, 6, &pin_PA12) +}; + +const mcu_periph_obj_t mcu_spi_nss_list[8] = { + PERIPH(1, 5, &pin_PA04), + PERIPH(1, 5, &pin_PA15), + PERIPH(2, 5, &pin_PB09), + PERIPH(2, 5, &pin_PB12), + PERIPH(3, 6, &pin_PA04), + PERIPH(3, 6, &pin_PA15), + PERIPH(4, 6, &pin_PB12), + PERIPH(5, 6, &pin_PB01) +}; + +// UART + +USART_TypeDef *mcu_uart_banks[MAX_UART] = {USART1, USART2, USART3, NULL, NULL, USART6}; +bool mcu_uart_has_usart[MAX_UART] = {true, true, true, false, false, true}; + +const mcu_periph_obj_t mcu_uart_tx_list[8] = { + PERIPH(2, 7, &pin_PA02), + PERIPH(1, 7, &pin_PA09), + PERIPH(1, 7, &pin_PA15), + PERIPH(6, 8, &pin_PA11), + PERIPH(1, 7, &pin_PB06), + PERIPH(3, 7, &pin_PB10), + PERIPH(6, 8, &pin_PC06), + PERIPH(3, 7, &pin_PC10) +}; + +const mcu_periph_obj_t mcu_uart_rx_list[8] = { + PERIPH(2, 7, &pin_PA03), + PERIPH(1, 7, &pin_PA10), + PERIPH(6, 8, &pin_PA12), + PERIPH(1, 7, &pin_PB03), + PERIPH(1, 7, &pin_PB07), + PERIPH(3, 7, &pin_PC05), + PERIPH(6, 8, &pin_PC07), + PERIPH(3, 7, &pin_PC11) +}; + +// Timers +// TIM6 and TIM7 are basic timers that are only used by DAC, and don't have pins +TIM_TypeDef *mcu_tim_banks[14] = {TIM1, TIM2, TIM3, TIM4, TIM5, NULL, NULL, TIM8, TIM9, TIM10, + TIM11, TIM12, TIM13, TIM14}; + +const mcu_tim_pin_obj_t mcu_tim_pin_list[41] = { + TIM(2, 1, 1, &pin_PA00), + TIM(5, 2, 1, &pin_PA00), + TIM(2, 1, 2, &pin_PA01), + TIM(5, 2, 2, &pin_PA01), + TIM(2, 1, 3, &pin_PA02), + TIM(5, 2, 3, &pin_PA02), + TIM(2, 1, 4, &pin_PA03), + TIM(5, 2, 4, &pin_PA03), + TIM(9, 3, 1, &pin_PA02), + TIM(9, 3, 2, &pin_PA03), + TIM(3, 2, 1, &pin_PA06), + TIM(13, 9, 1, &pin_PA06), + TIM(3, 2, 2, &pin_PA07), + TIM(14, 9, 1, &pin_PA07), + TIM(1, 1, 1, &pin_PA08), + TIM(1, 1, 2, &pin_PA09), + TIM(1, 1, 3, &pin_PA10), + TIM(1, 1, 4, &pin_PA11), + TIM(2, 1, 1, &pin_PA15), + TIM(3, 2, 3, &pin_PB00), + TIM(3, 2, 4, &pin_PB01), + TIM(2, 1, 2, &pin_PB03), + TIM(3, 2, 1, &pin_PB04), + TIM(3, 2, 2, &pin_PB05), + TIM(4, 2, 1, &pin_PB06), + TIM(4, 2, 2, &pin_PB07), + TIM(4, 2, 3, &pin_PB08), + TIM(10, 3, 1, &pin_PB08), + TIM(4, 2, 4, &pin_PB09), + TIM(11, 3, 1, &pin_PB09), + TIM(2, 1, 3, &pin_PB10), + TIM(12, 9, 1, &pin_PB14), + TIM(12, 9, 2, &pin_PB15), + TIM(3, 2, 1, &pin_PC06), + TIM(3, 2, 2, &pin_PC07), + TIM(3, 2, 3, &pin_PC08), + TIM(3, 2, 4, &pin_PC09), + TIM(8, 3, 1, &pin_PC06), + TIM(8, 3, 2, &pin_PC07), + TIM(8, 3, 3, &pin_PC08), + TIM(8, 3, 4, &pin_PC09) +}; + +// FSMC, used by paralleldisplaybus. periph_index is the data bit (D0-D7). +// Pin and alternate function mapping from ST's STM32_open_pin_data. + +const mcu_periph_obj_t mcu_fsmc_data_list[8] = { + PERIPH(0, 10, &pin_PB14), + PERIPH(1, 10, &pin_PC06), + PERIPH(2, 10, &pin_PC11), + PERIPH(3, 10, &pin_PC12), + PERIPH(4, 12, &pin_PA02), + PERIPH(5, 12, &pin_PA03), + PERIPH(6, 12, &pin_PA04), + PERIPH(7, 12, &pin_PA05) +}; + +const mcu_periph_obj_t mcu_fsmc_nwe_list[2] = { + PERIPH(1, 12, &pin_PC02), + PERIPH(1, 10, &pin_PD02) +}; + +const mcu_periph_obj_t mcu_fsmc_noe_list[1] = { + PERIPH(1, 12, &pin_PC05) +}; diff --git a/ports/stm/peripherals/stm32f4/stm32f412rx/periph.h b/ports/stm/peripherals/stm32f4/stm32f412rx/periph.h new file mode 100644 index 00000000000..cac35ba7be8 --- /dev/null +++ b/ports/stm/peripherals/stm32f4/stm32f412rx/periph.h @@ -0,0 +1,40 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Lucian Copeland for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// I2C +extern I2C_TypeDef *mcu_i2c_banks[3]; + +extern const mcu_periph_obj_t mcu_i2c_sda_list[7]; +extern const mcu_periph_obj_t mcu_i2c_scl_list[4]; + + +// SPI +extern SPI_TypeDef *mcu_spi_banks[5]; + +extern const mcu_periph_obj_t mcu_spi_sck_list[10]; +extern const mcu_periph_obj_t mcu_spi_mosi_list[9]; +extern const mcu_periph_obj_t mcu_spi_miso_list[8]; +extern const mcu_periph_obj_t mcu_spi_nss_list[8]; + +// UART +extern USART_TypeDef *mcu_uart_banks[MAX_UART]; +extern bool mcu_uart_has_usart[MAX_UART]; + +extern const mcu_periph_obj_t mcu_uart_tx_list[8]; +extern const mcu_periph_obj_t mcu_uart_rx_list[8]; + +// Timers +#define TIM_BANK_ARRAY_LEN 14 +#define TIM_PIN_ARRAY_LEN 41 +extern TIM_TypeDef *mcu_tim_banks[TIM_BANK_ARRAY_LEN]; +extern const mcu_tim_pin_obj_t mcu_tim_pin_list[TIM_PIN_ARRAY_LEN]; + +// FSMC +extern const mcu_periph_obj_t mcu_fsmc_data_list[8]; +extern const mcu_periph_obj_t mcu_fsmc_nwe_list[2]; +extern const mcu_periph_obj_t mcu_fsmc_noe_list[1]; diff --git a/ports/stm/peripherals/stm32f4/stm32f412rx/pins.c b/ports/stm/peripherals/stm32f4/stm32f412rx/pins.c new file mode 100644 index 00000000000..3f31322b6bb --- /dev/null +++ b/ports/stm/peripherals/stm32f4/stm32f412rx/pins.c @@ -0,0 +1,61 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Lucian Copeland for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "py/obj.h" +#include "py/mphal.h" +#include "peripherals/pins.h" + +const mcu_pin_obj_t pin_PA00 = PIN(0, 0, ADC_INPUT(ADC_1, 0)); +const mcu_pin_obj_t pin_PA01 = PIN(0, 1, ADC_INPUT(ADC_1, 1)); +const mcu_pin_obj_t pin_PA02 = PIN(0, 2, ADC_INPUT(ADC_1, 2)); +const mcu_pin_obj_t pin_PA03 = PIN(0, 3, ADC_INPUT(ADC_1, 3)); +const mcu_pin_obj_t pin_PA04 = PIN(0, 4, ADC_INPUT(ADC_1, 4)); +const mcu_pin_obj_t pin_PA05 = PIN(0, 5, ADC_INPUT(ADC_1, 5)); +const mcu_pin_obj_t pin_PA06 = PIN(0, 6, ADC_INPUT(ADC_1, 6)); +const mcu_pin_obj_t pin_PA07 = PIN(0, 7, ADC_INPUT(ADC_1, 7)); +const mcu_pin_obj_t pin_PA08 = PIN(0, 8, NO_ADC); +const mcu_pin_obj_t pin_PA09 = PIN(0, 9, NO_ADC); +const mcu_pin_obj_t pin_PA10 = PIN(0, 10, NO_ADC); +const mcu_pin_obj_t pin_PA11 = PIN(0, 11, NO_ADC); +const mcu_pin_obj_t pin_PA12 = PIN(0, 12, NO_ADC); +const mcu_pin_obj_t pin_PA13 = PIN(0, 13, NO_ADC); +const mcu_pin_obj_t pin_PA14 = PIN(0, 14, NO_ADC); +const mcu_pin_obj_t pin_PA15 = PIN(0, 15, NO_ADC); + +const mcu_pin_obj_t pin_PB00 = PIN(1, 0, ADC_INPUT(ADC_1, 8)); +const mcu_pin_obj_t pin_PB01 = PIN(1, 1, ADC_INPUT(ADC_1, 9)); +const mcu_pin_obj_t pin_PB02 = PIN(1, 2, NO_ADC); +const mcu_pin_obj_t pin_PB03 = PIN(1, 3, NO_ADC); +const mcu_pin_obj_t pin_PB04 = PIN(1, 4, NO_ADC); +const mcu_pin_obj_t pin_PB05 = PIN(1, 5, NO_ADC); +const mcu_pin_obj_t pin_PB06 = PIN(1, 6, NO_ADC); +const mcu_pin_obj_t pin_PB07 = PIN(1, 7, NO_ADC); +const mcu_pin_obj_t pin_PB08 = PIN(1, 8, NO_ADC); +const mcu_pin_obj_t pin_PB09 = PIN(1, 9, NO_ADC); +const mcu_pin_obj_t pin_PB10 = PIN(1, 10, NO_ADC); +const mcu_pin_obj_t pin_PB12 = PIN(1, 12, NO_ADC); +const mcu_pin_obj_t pin_PB13 = PIN(1, 13, NO_ADC); +const mcu_pin_obj_t pin_PB14 = PIN(1, 14, NO_ADC); +const mcu_pin_obj_t pin_PB15 = PIN(1, 15, NO_ADC); + +const mcu_pin_obj_t pin_PC00 = PIN(2, 0, ADC_INPUT(ADC_1, 10)); +const mcu_pin_obj_t pin_PC01 = PIN(2, 1, ADC_INPUT(ADC_1, 11)); +const mcu_pin_obj_t pin_PC02 = PIN(2, 2, ADC_INPUT(ADC_1, 12)); +const mcu_pin_obj_t pin_PC03 = PIN(2, 3, ADC_INPUT(ADC_1, 13)); +const mcu_pin_obj_t pin_PC04 = PIN(2, 4, ADC_INPUT(ADC_1, 14)); +const mcu_pin_obj_t pin_PC05 = PIN(2, 5, ADC_INPUT(ADC_1, 15)); +const mcu_pin_obj_t pin_PC06 = PIN(2, 6, NO_ADC); +const mcu_pin_obj_t pin_PC07 = PIN(2, 7, NO_ADC); +const mcu_pin_obj_t pin_PC08 = PIN(2, 8, NO_ADC); +const mcu_pin_obj_t pin_PC09 = PIN(2, 9, NO_ADC); +const mcu_pin_obj_t pin_PC10 = PIN(2, 10, NO_ADC); +const mcu_pin_obj_t pin_PC11 = PIN(2, 11, NO_ADC); +const mcu_pin_obj_t pin_PC12 = PIN(2, 12, NO_ADC); +const mcu_pin_obj_t pin_PC13 = PIN(2, 13, NO_ADC); +const mcu_pin_obj_t pin_PC14 = PIN(2, 14, NO_ADC); +const mcu_pin_obj_t pin_PC15 = PIN(2, 15, NO_ADC); + +const mcu_pin_obj_t pin_PD02 = PIN(3, 2, NO_ADC); diff --git a/ports/stm/peripherals/stm32f4/stm32f412rx/pins.h b/ports/stm/peripherals/stm32f4/stm32f412rx/pins.h new file mode 100644 index 00000000000..17cc3c6e6b0 --- /dev/null +++ b/ports/stm/peripherals/stm32f4/stm32f412rx/pins.h @@ -0,0 +1,59 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Lucian Copeland for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +extern const mcu_pin_obj_t pin_PA00; +extern const mcu_pin_obj_t pin_PA01; +extern const mcu_pin_obj_t pin_PA02; +extern const mcu_pin_obj_t pin_PA03; +extern const mcu_pin_obj_t pin_PA04; +extern const mcu_pin_obj_t pin_PA05; +extern const mcu_pin_obj_t pin_PA06; +extern const mcu_pin_obj_t pin_PA07; +extern const mcu_pin_obj_t pin_PA08; +extern const mcu_pin_obj_t pin_PA09; +extern const mcu_pin_obj_t pin_PA10; +extern const mcu_pin_obj_t pin_PA11; +extern const mcu_pin_obj_t pin_PA12; +extern const mcu_pin_obj_t pin_PA13; +extern const mcu_pin_obj_t pin_PA14; +extern const mcu_pin_obj_t pin_PA15; + +extern const mcu_pin_obj_t pin_PB00; +extern const mcu_pin_obj_t pin_PB01; +extern const mcu_pin_obj_t pin_PB02; +extern const mcu_pin_obj_t pin_PB03; +extern const mcu_pin_obj_t pin_PB04; +extern const mcu_pin_obj_t pin_PB05; +extern const mcu_pin_obj_t pin_PB06; +extern const mcu_pin_obj_t pin_PB07; +extern const mcu_pin_obj_t pin_PB08; +extern const mcu_pin_obj_t pin_PB09; +extern const mcu_pin_obj_t pin_PB10; +extern const mcu_pin_obj_t pin_PB12; +extern const mcu_pin_obj_t pin_PB13; +extern const mcu_pin_obj_t pin_PB14; +extern const mcu_pin_obj_t pin_PB15; + +extern const mcu_pin_obj_t pin_PC00; +extern const mcu_pin_obj_t pin_PC01; +extern const mcu_pin_obj_t pin_PC02; +extern const mcu_pin_obj_t pin_PC03; +extern const mcu_pin_obj_t pin_PC04; +extern const mcu_pin_obj_t pin_PC05; +extern const mcu_pin_obj_t pin_PC06; +extern const mcu_pin_obj_t pin_PC07; +extern const mcu_pin_obj_t pin_PC08; +extern const mcu_pin_obj_t pin_PC09; +extern const mcu_pin_obj_t pin_PC10; +extern const mcu_pin_obj_t pin_PC11; +extern const mcu_pin_obj_t pin_PC12; +extern const mcu_pin_obj_t pin_PC13; +extern const mcu_pin_obj_t pin_PC14; +extern const mcu_pin_obj_t pin_PC15; + +extern const mcu_pin_obj_t pin_PD02; diff --git a/ports/stm/peripherals/stm32f4/stm32f412zx/gpio.c b/ports/stm/peripherals/stm32f4/stm32f412zx/gpio.c index 94c2faf68bf..a65ac6f4378 100644 --- a/ports/stm/peripherals/stm32f4/stm32f412zx/gpio.c +++ b/ports/stm/peripherals/stm32f4/stm32f412zx/gpio.c @@ -18,17 +18,12 @@ void stm32_peripherals_gpio_init(void) { __HAL_RCC_GPIOG_CLK_ENABLE(); __HAL_RCC_GPIOD_CLK_ENABLE(); - // Never reset pins - never_reset_pin_number(2, 13); // PC13 anti tamp - never_reset_pin_number(2, 14); // PC14 OSC32_IN - never_reset_pin_number(2, 15); // PC15 OSC32_OUT - never_reset_pin_number(0, 13); // PA13 SWDIO - never_reset_pin_number(0, 14); // PA14 SWCLK - // never_reset_pin_number(0,15); //PA15 JTDI - // never_reset_pin_number(1,3); //PB3 JTDO - // never_reset_pin_number(1,4); //PB4 JTRST + // Pins in use by the system; mark them claimed so user code can't use them. + claim_pin(2, 13); // PC13 anti tamp + claim_pin(2, 14); // PC14 OSC32_IN + claim_pin(2, 15); // PC15 OSC32_OUT + claim_pin(0, 13); // PA13 SWDIO + claim_pin(0, 14); // PA14 SWCLK // Port H is not included in GPIO port array - // never_reset_pin_number(5,0); //PH0 JTDO - // never_reset_pin_number(5,1); //PH1 JTRST } diff --git a/ports/stm/peripherals/stm32f4/stm32f412zx/periph.c b/ports/stm/peripherals/stm32f4/stm32f412zx/periph.c index caf8247e1a1..2ea6d8c3f7a 100644 --- a/ports/stm/peripherals/stm32f4/stm32f412zx/periph.c +++ b/ports/stm/peripherals/stm32f4/stm32f412zx/periph.c @@ -167,9 +167,9 @@ const mcu_tim_pin_obj_t mcu_tim_pin_list[60] = { TIM(4, 2, 1, &pin_PB06), TIM(4, 2, 2, &pin_PB07), TIM(4, 2, 3, &pin_PB08), - TIM(10, 2, 1, &pin_PB08), + TIM(10, 3, 1, &pin_PB08), TIM(4, 2, 4, &pin_PB09), - TIM(11, 2, 1, &pin_PB09), + TIM(11, 3, 1, &pin_PB09), TIM(2, 1, 3, &pin_PB10), TIM(2, 1, 4, &pin_PB11), TIM(12, 9, 1, &pin_PB14), diff --git a/ports/stm/peripherals/stm32f4/stm32f446xx/gpio.c b/ports/stm/peripherals/stm32f4/stm32f446xx/gpio.c index 25a7ea5a6b8..c5050b85566 100644 --- a/ports/stm/peripherals/stm32f4/stm32f446xx/gpio.c +++ b/ports/stm/peripherals/stm32f4/stm32f446xx/gpio.c @@ -15,12 +15,12 @@ void stm32_peripherals_gpio_init(void) { __HAL_RCC_GPIOA_CLK_ENABLE(); __HAL_RCC_GPIOB_CLK_ENABLE(); - // Never reset pins - never_reset_pin_number(2, 13); // PC13 anti tamp - never_reset_pin_number(2, 14); // PC14 OSC32_IN - never_reset_pin_number(2, 15); // PC15 OSC32_OUT - never_reset_pin_number(0, 13); // PA13 SWDIO - never_reset_pin_number(0, 14); // PA14 SWCLK + // Pins in use by the system; mark them claimed so user code can't use them. + claim_pin(2, 13); // PC13 anti tamp + claim_pin(2, 14); // PC14 OSC32_IN + claim_pin(2, 15); // PC15 OSC32_OUT + claim_pin(0, 13); // PA13 SWDIO + claim_pin(0, 14); // PA14 SWCLK } void stm32f4_peripherals_status_led(uint8_t led, uint8_t state) { diff --git a/ports/stm/peripherals/stm32f4/stm32f446xx/periph.c b/ports/stm/peripherals/stm32f4/stm32f446xx/periph.c index 509b302c182..565c3991dc4 100644 --- a/ports/stm/peripherals/stm32f4/stm32f446xx/periph.c +++ b/ports/stm/peripherals/stm32f4/stm32f446xx/periph.c @@ -98,9 +98,9 @@ const mcu_tim_pin_obj_t mcu_tim_pin_list[34] = { TIM(4, 2, 1, &pin_PB06), TIM(4, 2, 2, &pin_PB07), TIM(4, 2, 3, &pin_PB08), - TIM(10, 2, 1, &pin_PB08), + TIM(10, 3, 1, &pin_PB08), TIM(4, 2, 4, &pin_PB09), - TIM(11, 2, 1, &pin_PB09), + TIM(11, 3, 1, &pin_PB09), TIM(2, 1, 3, &pin_PB10), TIM(3, 2, 1, &pin_PC06), TIM(3, 2, 2, &pin_PC07), diff --git a/ports/stm/peripherals/stm32f7/stm32f746xx/gpio.c b/ports/stm/peripherals/stm32f7/stm32f746xx/gpio.c index 96cfd8eaf85..98e9cceaae1 100644 --- a/ports/stm/peripherals/stm32f7/stm32f746xx/gpio.c +++ b/ports/stm/peripherals/stm32f7/stm32f746xx/gpio.c @@ -22,11 +22,14 @@ void stm32_peripherals_gpio_init(void) { __HAL_RCC_GPIOJ_CLK_ENABLE(); __HAL_RCC_GPIOK_CLK_ENABLE(); - // Never reset pins - never_reset_pin_number(2, 14); // PC14 OSC32_IN - never_reset_pin_number(2, 15); // PC15 OSC32_OUT - never_reset_pin_number(0, 13); // PA13 SWDIO - never_reset_pin_number(0, 14); // PA14 SWCLK - never_reset_pin_number(7, 0); // PH0 OSC_IN - never_reset_pin_number(7, 1); // PH1 OSC_OUT + // Pins in use by the system; mark them claimed so user code can't use them. + claim_pin(2, 14); // PC14 OSC32_IN + claim_pin(2, 15); // PC15 OSC32_OUT + claim_pin(0, 13); // PA13 SWDIO + claim_pin(0, 14); // PA14 SWCLK + // Only guard the port-H oscillator pins when the package has port H in the pin array. + #if defined(TFBGA216) + claim_pin(7, 0); // PH0 OSC_IN + claim_pin(7, 1); // PH1 OSC_OUT + #endif } diff --git a/ports/stm/peripherals/stm32f7/stm32f767xx/gpio.c b/ports/stm/peripherals/stm32f7/stm32f767xx/gpio.c index a9fecc33540..6e495a9b80d 100644 --- a/ports/stm/peripherals/stm32f7/stm32f767xx/gpio.c +++ b/ports/stm/peripherals/stm32f7/stm32f767xx/gpio.c @@ -18,9 +18,9 @@ void stm32_peripherals_gpio_init(void) { __HAL_RCC_GPIOG_CLK_ENABLE(); __HAL_RCC_GPIOD_CLK_ENABLE(); - // Never reset pins - never_reset_pin_number(2, 14); // PC14 OSC32_IN - never_reset_pin_number(2, 15); // PC15 OSC32_OUT - never_reset_pin_number(0, 13); // PA13 SWDIO - never_reset_pin_number(0, 14); // PA14 SWCLK + // Pins in use by the system; mark them claimed so user code can't use them. + claim_pin(2, 14); // PC14 OSC32_IN + claim_pin(2, 15); // PC15 OSC32_OUT + claim_pin(0, 13); // PA13 SWDIO + claim_pin(0, 14); // PA14 SWCLK } diff --git a/ports/stm/peripherals/stm32h7/stm32h743xx/gpio.c b/ports/stm/peripherals/stm32h7/stm32h743xx/gpio.c index a9fecc33540..6e495a9b80d 100644 --- a/ports/stm/peripherals/stm32h7/stm32h743xx/gpio.c +++ b/ports/stm/peripherals/stm32h7/stm32h743xx/gpio.c @@ -18,9 +18,9 @@ void stm32_peripherals_gpio_init(void) { __HAL_RCC_GPIOG_CLK_ENABLE(); __HAL_RCC_GPIOD_CLK_ENABLE(); - // Never reset pins - never_reset_pin_number(2, 14); // PC14 OSC32_IN - never_reset_pin_number(2, 15); // PC15 OSC32_OUT - never_reset_pin_number(0, 13); // PA13 SWDIO - never_reset_pin_number(0, 14); // PA14 SWCLK + // Pins in use by the system; mark them claimed so user code can't use them. + claim_pin(2, 14); // PC14 OSC32_IN + claim_pin(2, 15); // PC15 OSC32_OUT + claim_pin(0, 13); // PA13 SWDIO + claim_pin(0, 14); // PA14 SWCLK } diff --git a/ports/stm/peripherals/stm32h7/stm32h743xx/periph.h b/ports/stm/peripherals/stm32h7/stm32h743xx/periph.h index fa4ec7f6e56..2ff49c8503c 100644 --- a/ports/stm/peripherals/stm32h7/stm32h743xx/periph.h +++ b/ports/stm/peripherals/stm32h7/stm32h743xx/periph.h @@ -30,3 +30,4 @@ extern const mcu_periph_obj_t mcu_uart_rx_list[26]; #define TIM_BANK_ARRAY_LEN 14 #define TIM_PIN_ARRAY_LEN 58 extern TIM_TypeDef *mcu_tim_banks[TIM_BANK_ARRAY_LEN]; +extern const mcu_tim_pin_obj_t mcu_tim_pin_list[TIM_PIN_ARRAY_LEN]; diff --git a/ports/stm/peripherals/stm32h7/stm32h750xx/gpio.c b/ports/stm/peripherals/stm32h7/stm32h750xx/gpio.c index f5ad843c9a6..876dcecfc9f 100644 --- a/ports/stm/peripherals/stm32h7/stm32h750xx/gpio.c +++ b/ports/stm/peripherals/stm32h7/stm32h750xx/gpio.c @@ -19,17 +19,16 @@ void stm32_peripherals_gpio_init(void) { __HAL_RCC_GPIOH_CLK_ENABLE(); __HAL_RCC_GPIOI_CLK_ENABLE(); -// Never reset pins - never_reset_pin_number(7, 0); // PH00 OSC32_IN - never_reset_pin_number(7, 1); // PH01 OSC32_OUT - never_reset_pin_number(0, 13); // PA13 SWDIO - never_reset_pin_number(0, 14); // PA14 SWCLK + // Pins in use by the system; mark them claimed so user code can't use them. + claim_pin(7, 0); // PH00 OSC32_IN + claim_pin(7, 1); // PH01 OSC32_OUT + claim_pin(0, 13); // PA13 SWDIO + claim_pin(0, 14); // PA14 SWCLK // qspi flash pins for the Daisy Seed -- TODO ? - never_reset_pin_number(5, 6); // PF06 QSPI IO3 - never_reset_pin_number(5, 7); // PF07 QSPI IO2 - never_reset_pin_number(5, 8); // PF08 QSPI IO0 - never_reset_pin_number(5, 9); // PF09 QSPI IO1 - never_reset_pin_number(5, 10); // PF10 QSPI CLK - never_reset_pin_number(6, 6); // PG06 QSPI NCS - + claim_pin(5, 6); // PF06 QSPI IO3 + claim_pin(5, 7); // PF07 QSPI IO2 + claim_pin(5, 8); // PF08 QSPI IO0 + claim_pin(5, 9); // PF09 QSPI IO1 + claim_pin(5, 10); // PF10 QSPI CLK + claim_pin(6, 6); // PG06 QSPI NCS } diff --git a/ports/stm/peripherals/stm32h7/stm32h750xx/periph.c b/ports/stm/peripherals/stm32h7/stm32h750xx/periph.c index 55acede5941..023e06ee322 100644 --- a/ports/stm/peripherals/stm32h7/stm32h750xx/periph.c +++ b/ports/stm/peripherals/stm32h7/stm32h750xx/periph.c @@ -9,8 +9,10 @@ #include "peripherals/pins.h" #include "peripherals/periph.h" +// See alternate functions tables in the STM32H750xx datasheet + // I2C -I2C_TypeDef *mcu_i2c_banks[4] = {I2C1, I2C2, I2C3, I2C4}; +I2C_TypeDef *mcu_i2c_banks[MAX_I2C] = {I2C1, I2C2, I2C3, I2C4}; const mcu_periph_obj_t mcu_i2c_sda_list[12] = { PERIPH(1, 4, &pin_PB07), @@ -44,9 +46,9 @@ const mcu_periph_obj_t mcu_i2c_scl_list[12] = { // SPI -SPI_TypeDef *mcu_spi_banks[6] = {SPI1, SPI2, SPI3, SPI4, SPI5, SPI6}; +SPI_TypeDef *mcu_spi_banks[MAX_SPI] = {SPI1, SPI2, SPI3, SPI4, SPI5, SPI6}; -const mcu_periph_obj_t mcu_spi_sck_list[19] = { +const mcu_periph_obj_t mcu_spi_sck_list[18] = { PERIPH(1, 5, &pin_PA05), PERIPH(6, 8, &pin_PA05), PERIPH(2, 5, &pin_PA09), @@ -65,10 +67,9 @@ const mcu_periph_obj_t mcu_spi_sck_list[19] = { PERIPH(6, 5, &pin_PG13), PERIPH(5, 5, &pin_PH06), PERIPH(2, 5, &pin_PI01), - PERIPH(5, 5, &pin_PI00), }; -const mcu_periph_obj_t mcu_spi_mosi_list[19] = { +const mcu_periph_obj_t mcu_spi_mosi_list[18] = { PERIPH(1, 5, &pin_PA07), PERIPH(6, 8, &pin_PA07), PERIPH(3, 7, &pin_PB02), @@ -87,10 +88,9 @@ const mcu_periph_obj_t mcu_spi_mosi_list[19] = { PERIPH(5, 5, &pin_PF11), PERIPH(6, 5, &pin_PG14), PERIPH(2, 5, &pin_PI03), - PERIPH(5, 5, &pin_PI10), }; -const mcu_periph_obj_t mcu_spi_miso_list[16] = { +const mcu_periph_obj_t mcu_spi_miso_list[15] = { PERIPH(1, 5, &pin_PA06), PERIPH(6, 8, &pin_PA06), PERIPH(1, 5, &pin_PB04), @@ -106,15 +106,15 @@ const mcu_periph_obj_t mcu_spi_miso_list[16] = { PERIPH(6, 5, &pin_PG12), PERIPH(5, 5, &pin_PH07), PERIPH(2, 5, &pin_PI02), - PERIPH(5, 5, &pin_PI11), }; // UART -USART_TypeDef *mcu_uart_banks[MAX_UART] = {USART1, USART2, USART3, UART4, UART5, USART6, UART7, UART8, LPUART1}; -bool mcu_uart_has_usart[MAX_UART] = {true, true, true, false, false, true, false, false, false}; +USART_TypeDef *mcu_uart_banks[MAX_UART] = {USART1, USART2, USART3, UART4, UART5, USART6, UART7, UART8}; +// circuitpython doesn't implement USART +// bool mcu_uart_has_usart[MAX_UART] = {true, true, true, false, false, true, false, false, false}; -const mcu_periph_obj_t mcu_uart_tx_list[25] = { +const mcu_periph_obj_t mcu_uart_tx_list[24] = { PERIPH(4, 8, &pin_PA00), PERIPH(2, 7, &pin_PA02), PERIPH(1, 7, &pin_PA09), @@ -138,11 +138,10 @@ const mcu_periph_obj_t mcu_uart_tx_list[25] = { PERIPH(7, 7, &pin_PE08), PERIPH(7, 7, &pin_PF07), PERIPH(6, 7, &pin_PG14), - PERIPH(4, 8, &pin_PI13), - PERIPH(8, 8, &pin_PI08), + PERIPH(4, 8, &pin_PH13), }; -const mcu_periph_obj_t mcu_uart_rx_list[26] = { +const mcu_periph_obj_t mcu_uart_rx_list[25] = { PERIPH(4, 8, &pin_PA01), PERIPH(2, 7, &pin_PA03), PERIPH(7, 11, &pin_PA08), @@ -166,29 +165,30 @@ const mcu_periph_obj_t mcu_uart_rx_list[26] = { PERIPH(7, 7, &pin_PE07), PERIPH(7, 7, &pin_PF06), PERIPH(6, 7, &pin_PG09), - PERIPH(4, 8, &pin_PI14), + PERIPH(4, 8, &pin_PH14), PERIPH(4, 8, &pin_PI09), - PERIPH(8, 8, &pin_PI09), }; // Timers // TIM6 and TIM7 are basic timers that are only used by DAC, and don't have pins -// TODO: H7 has more timers than this, but are they tied to pins? -TIM_TypeDef *mcu_tim_banks[14] = {TIM1, TIM2, TIM3, TIM4, TIM5, NULL, NULL, TIM8, NULL, NULL, - NULL, TIM12, TIM13, TIM14}; - -const mcu_tim_pin_obj_t mcu_tim_pin_list[58] = { +TIM_TypeDef *mcu_tim_banks[TIM_BANK_ARRAY_LEN] = {TIM1, TIM2, TIM3, TIM4, TIM5, NULL, NULL, TIM8, + NULL, NULL, NULL, TIM12, TIM13, TIM14, TIM15, TIM16, TIM17}; +const mcu_tim_pin_obj_t mcu_tim_pin_list[TIM_PIN_ARRAY_LEN] = { TIM(2, 1, 1, &pin_PA00), TIM(5, 2, 1, &pin_PA00), TIM(2, 1, 2, &pin_PA01), TIM(5, 2, 2, &pin_PA01), TIM(2, 1, 3, &pin_PA02), TIM(5, 2, 3, &pin_PA02), + TIM(15, 4, 1, &pin_PA02), TIM(2, 1, 4, &pin_PA03), TIM(5, 2, 4, &pin_PA03), + TIM(15, 4, 2, &pin_PA03), TIM(2, 1, 1, &pin_PA05), TIM(3, 2, 1, &pin_PA06), + TIM(13, 9, 1, &pin_PA06), TIM(3, 2, 2, &pin_PA07), + TIM(14, 9, 1, &pin_PA07), TIM(1, 1, 1, &pin_PA08), TIM(1, 1, 2, &pin_PA09), TIM(1, 1, 3, &pin_PA10), @@ -205,6 +205,8 @@ const mcu_tim_pin_obj_t mcu_tim_pin_list[58] = { TIM(4, 2, 4, &pin_PB09), TIM(2, 1, 3, &pin_PB10), TIM(2, 1, 4, &pin_PB11), + TIM(12, 2, 1, &pin_PB14), + TIM(12, 2, 2, &pin_PB15), TIM(3, 2, 1, &pin_PC06), TIM(8, 3, 1, &pin_PC06), TIM(3, 2, 2, &pin_PC07), @@ -217,23 +219,167 @@ const mcu_tim_pin_obj_t mcu_tim_pin_list[58] = { TIM(4, 2, 2, &pin_PD13), TIM(4, 2, 3, &pin_PD14), TIM(4, 2, 4, &pin_PD15), + TIM(15, 4, 1, &pin_PE05), + TIM(15, 4, 2, &pin_PE06), TIM(1, 1, 1, &pin_PE09), TIM(1, 1, 2, &pin_PE11), TIM(1, 1, 3, &pin_PE13), TIM(1, 1, 4, &pin_PE14), - TIM(5, 2, 1, &pin_PI10), - TIM(5, 2, 2, &pin_PI11), - TIM(5, 2, 3, &pin_PI12), + TIM(16, 1, 1, &pin_PF06), + TIM(17, 1, 1, &pin_PF07), + TIM(13, 9, 1, &pin_PF08), + TIM(14, 9, 1, &pin_PF09), + TIM(12, 2, 1, &pin_PH06), + TIM(12, 2, 2, &pin_PH09), + TIM(5, 2, 1, &pin_PH10), + TIM(5, 2, 2, &pin_PH11), + TIM(5, 2, 3, &pin_PH12), TIM(5, 2, 4, &pin_PI00), TIM(8, 3, 4, &pin_PI02), TIM(8, 3, 1, &pin_PI05), TIM(8, 3, 2, &pin_PI06), TIM(8, 3, 3, &pin_PI07), - TIM(8, 3, 2, &pin_PI06), - TIM(8, 3, 1, &pin_PI08), - TIM(1, 1, 3, &pin_PI09), - TIM(8, 3, 2, &pin_PI10), - TIM(1, 1, 2, &pin_PI11), - TIM(8, 3, 3, &pin_PI00), - TIM(1, 1, 1, &pin_PI01), +}; + +// SDIO - H750 has a MMC interface that includes SDIO +SDMMC_TypeDef *mcu_sdio_banks[1] = {SDMMC1}; + +const mcu_periph_obj_t mcu_sdio_clock_list[1] = { + PERIPH(1, 12, &pin_PC12), +}; +const mcu_periph_obj_t mcu_sdio_command_list[1] = { + PERIPH(1, 12, &pin_PD02), +}; +const mcu_periph_obj_t mcu_sdio_data0_list[1] = { + PERIPH(1, 12, &pin_PC08), +}; +const mcu_periph_obj_t mcu_sdio_data1_list[1] = { + PERIPH(1, 12, &pin_PC09), +}; +const mcu_periph_obj_t mcu_sdio_data2_list[1] = { + PERIPH(1, 12, &pin_PC10), +}; +const mcu_periph_obj_t mcu_sdio_data3_list[1] = { + PERIPH(1, 12, &pin_PC11), +}; + + +/** FMC GPIO Configuration + PE1 ------> FMC_NBL1 + PE0 ------> FMC_NBL0 + PG15 ------> FMC_SDNCAS + PD0 ------> FMC_D2 + PI7 ------> FMC_D29 + PI6 ------> FMC_D28 + PI5 ------> FMC_NBL3 + PD1 ------> FMC_D3 + PI3 ------> FMC_D27 + PI2 ------> FMC_D26 + PI9 ------> FMC_D30 + PI4 ------> FMC_NBL2 + PH15 ------> FMC_D23 + PI1 ------> FMC_D25 + PF0 ------> FMC_A0 + PI10 ------> FMC_D31 + PH13 ------> FMC_D21 + PH14 ------> FMC_D22 + PI0 ------> FMC_D24 + PH2 ------> FMC_SDCKE0 + PH3 ------> FMC_SDNE0 + PF2 ------> FMC_A2 + PF1 ------> FMC_A1 + PG8 ------> FMC_SDCLK + PF3 ------> FMC_A3 + PF4 ------> FMC_A4 + PH5 ------> FMC_SDNWE + PF5 ------> FMC_A5 + PH12 ------> FMC_D20 + PG5 ------> FMC_BA1 + PG4 ------> FMC_BA0 + PH11 ------> FMC_D19 + PH10 ------> FMC_D18 + PD15 ------> FMC_D1 + PG2 ------> FMC_A12 + PG1 ------> FMC_A11 + PH8 ------> FMC_D16 + PH9 ------> FMC_D17 + PD14 ------> FMC_D0 + PF13 ------> FMC_A7 + PG0 ------> FMC_A10 + PE13 ------> FMC_D10 + PD10 ------> FMC_D15 + PF12 ------> FMC_A6 + PF15 ------> FMC_A9 + PE8 ------> FMC_D5 + PE9 ------> FMC_D6 + PE11 ------> FMC_D8 + PE14 ------> FMC_D11 + PD9 ------> FMC_D14 + PD8 ------> FMC_D13 + PF11 ------> FMC_SDNRAS + PF14 ------> FMC_A8 + PE7 ------> FMC_D4 + PE10 ------> FMC_D7 + PE12 ------> FMC_D9 + PE15 ------> FMC_D12 + */ + +const mcu_periph_obj_t sdram_pin_list[57] = { + PERIPH(4, 12, &pin_PE01), + PERIPH(4, 12, &pin_PE00), + PERIPH(6, 12, &pin_PG15), + PERIPH(3, 12, &pin_PD00), + PERIPH(8, 12, &pin_PI07), + PERIPH(8, 12, &pin_PI06), + PERIPH(8, 12, &pin_PI05), + PERIPH(3, 12, &pin_PD01), + PERIPH(8, 12, &pin_PI03), + PERIPH(8, 12, &pin_PI02), + PERIPH(8, 12, &pin_PI09), + PERIPH(8, 12, &pin_PI04), + PERIPH(7, 12, &pin_PH15), + PERIPH(8, 12, &pin_PI01), + PERIPH(5, 12, &pin_PF00), + PERIPH(8, 12, &pin_PI10), + PERIPH(7, 12, &pin_PH13), + PERIPH(7, 12, &pin_PH14), + PERIPH(8, 12, &pin_PI00), + PERIPH(7, 12, &pin_PH02), + PERIPH(7, 12, &pin_PH03), + PERIPH(5, 12, &pin_PF02), + PERIPH(5, 12, &pin_PF01), + PERIPH(6, 12, &pin_PG08), + PERIPH(5, 12, &pin_PF03), + PERIPH(5, 12, &pin_PF04), + PERIPH(7, 12, &pin_PH05), + PERIPH(5, 12, &pin_PF05), + PERIPH(7, 12, &pin_PH12), + PERIPH(6, 12, &pin_PG05), + PERIPH(6, 12, &pin_PG04), + PERIPH(7, 12, &pin_PH11), + PERIPH(7, 12, &pin_PH10), + PERIPH(3, 12, &pin_PD15), + PERIPH(6, 12, &pin_PG02), + PERIPH(6, 12, &pin_PG01), + PERIPH(7, 12, &pin_PH08), + PERIPH(7, 12, &pin_PH09), + PERIPH(3, 12, &pin_PD14), + PERIPH(5, 12, &pin_PF13), + PERIPH(6, 12, &pin_PG00), + PERIPH(4, 12, &pin_PE13), + PERIPH(3, 12, &pin_PD10), + PERIPH(5, 12, &pin_PF12), + PERIPH(5, 12, &pin_PF15), + PERIPH(4, 12, &pin_PE08), + PERIPH(4, 12, &pin_PE09), + PERIPH(4, 12, &pin_PE11), + PERIPH(4, 12, &pin_PE14), + PERIPH(3, 12, &pin_PD09), + PERIPH(3, 12, &pin_PD08), + PERIPH(5, 12, &pin_PF11), + PERIPH(5, 12, &pin_PF14), + PERIPH(4, 12, &pin_PE07), + PERIPH(4, 12, &pin_PE10), + PERIPH(4, 12, &pin_PE12), + PERIPH(4, 12, &pin_PE15), }; diff --git a/ports/stm/peripherals/stm32h7/stm32h750xx/periph.h b/ports/stm/peripherals/stm32h7/stm32h750xx/periph.h index f2cb1c2524e..f90f5507180 100644 --- a/ports/stm/peripherals/stm32h7/stm32h750xx/periph.h +++ b/ports/stm/peripherals/stm32h7/stm32h750xx/periph.h @@ -7,26 +7,39 @@ #pragma once // I2C -extern I2C_TypeDef *mcu_i2c_banks[4]; +extern I2C_TypeDef *mcu_i2c_banks[MAX_I2C]; extern const mcu_periph_obj_t mcu_i2c_sda_list[12]; extern const mcu_periph_obj_t mcu_i2c_scl_list[12]; // SPI -extern SPI_TypeDef *mcu_spi_banks[6]; +extern SPI_TypeDef *mcu_spi_banks[MAX_SPI]; -extern const mcu_periph_obj_t mcu_spi_sck_list[19]; -extern const mcu_periph_obj_t mcu_spi_mosi_list[19]; -extern const mcu_periph_obj_t mcu_spi_miso_list[16]; +extern const mcu_periph_obj_t mcu_spi_sck_list[18]; +extern const mcu_periph_obj_t mcu_spi_mosi_list[18]; +extern const mcu_periph_obj_t mcu_spi_miso_list[15]; // UART extern USART_TypeDef *mcu_uart_banks[MAX_UART]; extern bool mcu_uart_has_usart[MAX_UART]; -extern const mcu_periph_obj_t mcu_uart_tx_list[25]; -extern const mcu_periph_obj_t mcu_uart_rx_list[26]; +extern const mcu_periph_obj_t mcu_uart_tx_list[24]; +extern const mcu_periph_obj_t mcu_uart_rx_list[25]; // Timers -#define TIM_BANK_ARRAY_LEN 14 -#define TIM_PIN_ARRAY_LEN 58 +#define TIM_PIN_ARRAY_LEN 65 +extern const mcu_tim_pin_obj_t mcu_tim_pin_list[TIM_PIN_ARRAY_LEN]; +#define TIM_BANK_ARRAY_LEN 17 extern TIM_TypeDef *mcu_tim_banks[TIM_BANK_ARRAY_LEN]; + +// SDIO - H750 has a MMC interface that includes SDIO +extern SDMMC_TypeDef *mcu_sdio_banks[1]; + +extern const mcu_periph_obj_t mcu_sdio_clock_list[1]; +extern const mcu_periph_obj_t mcu_sdio_command_list[1]; +extern const mcu_periph_obj_t mcu_sdio_data0_list[1]; +extern const mcu_periph_obj_t mcu_sdio_data1_list[1]; +extern const mcu_periph_obj_t mcu_sdio_data2_list[1]; +extern const mcu_periph_obj_t mcu_sdio_data3_list[1]; +// SDRam +extern const mcu_periph_obj_t sdram_pin_list[57]; diff --git a/ports/stm/peripherals/stm32l4/clocks.c b/ports/stm/peripherals/stm32l4/clocks.c index a005c2bf790..4a7adc62de7 100644 --- a/ports/stm/peripherals/stm32l4/clocks.c +++ b/ports/stm/peripherals/stm32l4/clocks.c @@ -9,8 +9,10 @@ #include // L4 Series -#ifdef STM32L4R5xx +#if defined(STM32L4R5xx) #include "stm32l4/stm32l4r5xx/clocks.h" +#elif defined(STM32L433xx) +#include "stm32l4/stm32l433xx/clocks.h" #else #error Please add other MCUs here so that they are not silently ignored due to #define typos #endif @@ -44,49 +46,86 @@ void stm32_peripherals_clocks_init(void) { /** Configure the main internal regulator output voltage */ + #if defined(STM32L4R5xx) if (HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1_BOOST) != HAL_OK) { Error_Handler(); } - + #elif defined(STM32L433xx) + if (HAL_PWREx_ControlVoltageScaling(PWR_REGULATOR_VOLTAGE_SCALE1) != HAL_OK) { + Error_Handler(); + } + #endif /* Activate PLL with MSI , stabilizied via PLL by LSE */ + #if defined(STM32L4R5xx) RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE | RCC_OSCILLATORTYPE_MSI; RCC_OscInitStruct.MSIState = RCC_MSI_ON; RCC_OscInitStruct.LSEState = RCC_LSE_ON; - RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_11; RCC_OscInitStruct.MSICalibrationValue = RCC_MSICALIBRATION_DEFAULT; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_MSI; + RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2; + RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_11; RCC_OscInitStruct.PLL.PLLM = 6; RCC_OscInitStruct.PLL.PLLN = 30; RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV5; RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2; + #elif defined(STM32L433xx) + RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_LSE | RCC_OSCILLATORTYPE_HSI48 | RCC_OSCILLATORTYPE_MSI; + RCC_OscInitStruct.HSI48State = RCC_HSI48_ON; + RCC_OscInitStruct.MSIState = RCC_MSI_ON; + RCC_OscInitStruct.LSEState = RCC_LSE_ON; + RCC_OscInitStruct.MSICalibrationValue = 0; + RCC_OscInitStruct.MSIClockRange = RCC_MSIRANGE_6; + RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; + RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_MSI; + RCC_OscInitStruct.PLL.PLLM = 1; + RCC_OscInitStruct.PLL.PLLN = 40; + RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV7; + RCC_OscInitStruct.PLL.PLLQ = RCC_PLLQ_DIV2; RCC_OscInitStruct.PLL.PLLR = RCC_PLLR_DIV2; + #else + #error Unknown MCU + #endif + HAL_CHECK(HAL_RCC_OscConfig(&RCC_OscInitStruct)); + #ifdef STM32L4R5xx /* Enable MSI Auto-calibration through LSE */ HAL_RCCEx_EnableMSIPLLMode(); + #endif /* Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2 clocks dividers */ RCC_ClkInitStruct.ClockType = (RCC_CLOCKTYPE_SYSCLK | RCC_CLOCKTYPE_HCLK | RCC_CLOCKTYPE_PCLK1 | RCC_CLOCKTYPE_PCLK2); RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; - // Avoid overshoot and start with HCLK 60 MHz RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV1; RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1; + #if defined(STM32L4R5xx) HAL_CHECK(HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_3)); + #elif defined(STM32L433xx) + HAL_CHECK(HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_4)); + #else + #error Please expand the conditional compilation to set the default flash latency + #endif /* AHB prescaler divider at 1 as second step */ + #ifdef STM32L4R5xx RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK; RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1; HAL_CHECK(HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5)); + #endif /* Select MSI output as USB clock source */ PeriphClkInitStruct.PeriphClockSelection = RCC_PERIPHCLK_USB | RCC_PERIPHCLK_RTC | RCC_PERIPHCLK_ADC; + #if defined(STM32L4R5xx) PeriphClkInitStruct.UsbClockSelection = RCC_USBCLKSOURCE_MSI; + #elif defined(STM32L433xx) + PeriphClkInitStruct.UsbClockSelection = RCC_USBCLKSOURCE_HSI48; + #endif PeriphClkInitStruct.RTCClockSelection = RCC_RTCCLKSOURCE_LSE; PeriphClkInitStruct.AdcClockSelection = RCC_ADCCLKSOURCE_SYSCLK; - HAL_CHECK(HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct)); + HAL_CHECK(HAL_RCCEx_PeriphCLKConfig(&PeriphClkInitStruct)); } diff --git a/ports/stm/peripherals/stm32l4/stm32l433xx/clocks.h b/ports/stm/peripherals/stm32l4/stm32l433xx/clocks.h new file mode 100644 index 00000000000..a01cae704d6 --- /dev/null +++ b/ports/stm/peripherals/stm32l4/stm32l433xx/clocks.h @@ -0,0 +1,49 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Blues Wireless Contributors +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "stm32l4xx_hal.h" + +// Chip: STM32L433 +// Line Type: Foundation Line +// Speed: 80MHz (MAX) + +// Defaults: +#ifndef CPY_CLK_VSCALE +#define CPY_CLK_VSCALE (PWR_REGULATOR_VOLTAGE_SCALE1) // up to 80MHz +#endif +#ifndef CPY_CLK_PLLM +#define CPY_CLK_PLLM (1) +#endif +#ifndef CPY_CLK_PLLN +#define CPY_CLK_PLLN (40) +#endif +#ifndef CPY_CLK_PLLP +#define CPY_CLK_PLLP (RCC_PLLP_DIV7) +#endif +#ifndef CPY_CLK_PLLQ +#define CPY_CLK_PLLQ (2) +#endif +#ifndef CPY_CLK_AHBDIV +#define CPY_CLK_AHBDIV (RCC_SYSCLK_DIV1) +#endif +#ifndef CPY_CLK_APB1DIV +#define CPY_CLK_APB1DIV (RCC_HCLK_DIV1) +#endif +#ifndef CPY_CLK_APB2DIV +#define CPY_CLK_APB2DIV (RCC_HCLK_DIV1) +#endif +#ifndef CPY_CLK_FLASH_LATENCY +#define CPY_CLK_FLASH_LATENCY (FLASH_LATENCY_4) +#endif +#ifndef CPY_CLK_USB_USES_AUDIOPLL +#define CPY_CLK_USB_USES_AUDIOPLL (0) +#endif + +#ifndef BOARD_HAS_HIGH_SPEED_CRYSTAL +#define BOARD_HAS_HIGH_SPEED_CRYSTAL (1) +#endif diff --git a/ports/stm/peripherals/stm32l4/stm32l433xx/gpio.c b/ports/stm/peripherals/stm32l4/stm32l433xx/gpio.c new file mode 100644 index 00000000000..c2967752b93 --- /dev/null +++ b/ports/stm/peripherals/stm32l4/stm32l433xx/gpio.c @@ -0,0 +1,26 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Blues Wireless Contributors +// +// SPDX-License-Identifier: MIT + +#include "peripherals/gpio.h" +#include "common-hal/microcontroller/Pin.h" + +void stm32_peripherals_gpio_init(void) { + // Enable all GPIO for now + __HAL_RCC_GPIOA_CLK_ENABLE(); + __HAL_RCC_GPIOB_CLK_ENABLE(); + __HAL_RCC_GPIOC_CLK_ENABLE(); + __HAL_RCC_GPIOH_CLK_ENABLE(); + + // Pins in use by the system; mark them claimed so user code can't use them. + claim_pin(2, 14); // PC14 OSC32_IN + claim_pin(2, 15); // PC15 OSC32_OUT + claim_pin(0, 13); // PA13 SWDIO + claim_pin(0, 14); // PA14 SWCLK +} + +void stm32l4_peripherals_status_led(uint8_t led, uint8_t state) { + +} diff --git a/ports/stm/peripherals/stm32l4/stm32l433xx/periph.c b/ports/stm/peripherals/stm32l4/stm32l433xx/periph.c new file mode 100644 index 00000000000..14eed76eb59 --- /dev/null +++ b/ports/stm/peripherals/stm32l4/stm32l433xx/periph.c @@ -0,0 +1,91 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Blues Wireless Contributors +// +// SPDX-License-Identifier: MIT + +#include "py/obj.h" +#include "py/mphal.h" +#include "peripherals/pins.h" +#include "peripherals/periph.h" + +I2C_TypeDef *mcu_i2c_banks[I2C_BANK_ARRAY_LEN] = {I2C1, I2C2}; + +const mcu_periph_obj_t mcu_i2c_sda_list[I2C_SDA_ARRAY_LEN] = { + PERIPH(1, 4, &pin_PA10), + PERIPH(2, 4, &pin_PB14), +}; + +const mcu_periph_obj_t mcu_i2c_scl_list[I2C_SCL_ARRAY_LEN] = { + PERIPH(1, 4, &pin_PA09), + PERIPH(2, 4, &pin_PB13), +}; + +SPI_TypeDef *mcu_spi_banks[SPI_BANK_ARRAY_LEN] = {SPI1}; + +const mcu_periph_obj_t mcu_spi_sck_list[SPI_SCK_ARRAY_LEN] = { + PERIPH(1, 5, &pin_PB03), +}; +const mcu_periph_obj_t mcu_spi_mosi_list[SPI_MOSI_ARRAY_LEN] = { + PERIPH(1, 5, &pin_PA12), +}; +const mcu_periph_obj_t mcu_spi_miso_list[SPI_MISO_ARRAY_LEN] = { + PERIPH(1, 5, &pin_PA11), +}; +const mcu_periph_obj_t mcu_spi_nss_list[SPI_NSS_ARRAY_LEN] = { + PERIPH(1, 5, &pin_PA15), +}; + +USART_TypeDef *mcu_uart_banks[MAX_UART] = {USART1, USART2, USART3}; +bool mcu_uart_has_usart[MAX_UART] = {true, true, true, false, false}; + +const mcu_periph_obj_t mcu_uart_tx_list[UART_TX_ARRAY_LEN] = { + PERIPH(2, 7, &pin_PA02), + PERIPH(1, 7, &pin_PA09), + PERIPH(1, 7, &pin_PB06), + PERIPH(3, 7, &pin_PB10), +}; +const mcu_periph_obj_t mcu_uart_rx_list[UART_RX_ARRAY_LEN] = { + PERIPH(2, 7, &pin_PA03), + PERIPH(1, 7, &pin_PA10), + PERIPH(2, 3, &pin_PA15), + PERIPH(1, 7, &pin_PB07), + PERIPH(3, 7, &pin_PB11), +}; + +// Timers +TIM_TypeDef *mcu_tim_banks[TIM_BANK_ARRAY_LEN] = {TIM1, TIM2, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, TIM15, TIM16, NULL}; + +const mcu_tim_pin_obj_t mcu_tim_pin_list[TIM_PIN_ARRAY_LEN] = { + TIM(2, 1, 1, &pin_PA00), + TIM(2, 1, 2, &pin_PA01), + TIM(2, 1, 3, &pin_PA02), + TIM(15, 14, 1, &pin_PA02), + TIM(2, 1, 4, &pin_PA03), + TIM(15, 14, 2, &pin_PA03), + TIM(2, 1, 1, &pin_PA05), + TIM(16, 14, 1, &pin_PA06), + TIM(1, 1, 1, &pin_PA08), + TIM(1, 1, 2, &pin_PA09), + TIM(1, 1, 3, &pin_PA10), + TIM(1, 1, 4, &pin_PA11), + TIM(2, 1, 1, &pin_PA15), + TIM(2, 1, 2, &pin_PB03), + TIM(16, 14, 1, &pin_PB08), + TIM(2, 1, 3, &pin_PB10), + TIM(2, 1, 4, &pin_PB11), + TIM(15, 14, 1, &pin_PB14), + TIM(15, 14, 2, &pin_PB15), +}; + +// CAN +CAN_TypeDef *mcu_can_banks[] = {CAN1}; + +const mcu_periph_obj_t mcu_can_tx_list[2] = { + PERIPH(1, 10, &pin_PA12), + PERIPH(1, 10, &pin_PB09), +}; +const mcu_periph_obj_t mcu_can_rx_list[2] = { + PERIPH(1, 10, &pin_PA11), + PERIPH(1, 10, &pin_PB08), +}; diff --git a/ports/stm/peripherals/stm32l4/stm32l433xx/periph.h b/ports/stm/peripherals/stm32l4/stm32l433xx/periph.h new file mode 100644 index 00000000000..6bf0add01fe --- /dev/null +++ b/ports/stm/peripherals/stm32l4/stm32l433xx/periph.h @@ -0,0 +1,46 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Blues Wireless Contributors +// +// SPDX-License-Identifier: MIT + +#pragma once + +// I2C +#define I2C_BANK_ARRAY_LEN 2 +#define I2C_SDA_ARRAY_LEN 2 +#define I2C_SCL_ARRAY_LEN 2 +extern I2C_TypeDef *mcu_i2c_banks[I2C_BANK_ARRAY_LEN]; +extern const mcu_periph_obj_t mcu_i2c_sda_list[I2C_SDA_ARRAY_LEN]; +extern const mcu_periph_obj_t mcu_i2c_scl_list[I2C_SCL_ARRAY_LEN]; + +// SPI +#define SPI_BANK_ARRAY_LEN 1 +#define SPI_SCK_ARRAY_LEN 1 +#define SPI_MOSI_ARRAY_LEN 1 +#define SPI_MISO_ARRAY_LEN 1 +#define SPI_NSS_ARRAY_LEN 1 +extern SPI_TypeDef *mcu_spi_banks[SPI_BANK_ARRAY_LEN]; +extern const mcu_periph_obj_t mcu_spi_sck_list[SPI_SCK_ARRAY_LEN]; +extern const mcu_periph_obj_t mcu_spi_mosi_list[SPI_MOSI_ARRAY_LEN]; +extern const mcu_periph_obj_t mcu_spi_miso_list[SPI_MISO_ARRAY_LEN]; +extern const mcu_periph_obj_t mcu_spi_nss_list[SPI_NSS_ARRAY_LEN]; + +// UART +#define UART_TX_ARRAY_LEN 4 +#define UART_RX_ARRAY_LEN 5 +extern USART_TypeDef *mcu_uart_banks[MAX_UART]; +extern bool mcu_uart_has_usart[MAX_UART]; +extern const mcu_periph_obj_t mcu_uart_tx_list[UART_TX_ARRAY_LEN]; +extern const mcu_periph_obj_t mcu_uart_rx_list[UART_RX_ARRAY_LEN]; + +// Timers +#define TIM_BANK_ARRAY_LEN 17 +#define TIM_PIN_ARRAY_LEN 19 +extern TIM_TypeDef *mcu_tim_banks[TIM_BANK_ARRAY_LEN]; +extern const mcu_tim_pin_obj_t mcu_tim_pin_list[TIM_PIN_ARRAY_LEN]; + +// CAN +extern CAN_TypeDef *mcu_can_banks[1]; +extern const mcu_periph_obj_t mcu_can_tx_list[2]; +extern const mcu_periph_obj_t mcu_can_rx_list[2]; diff --git a/ports/stm/peripherals/stm32l4/stm32l433xx/pins.c b/ports/stm/peripherals/stm32l4/stm32l433xx/pins.c new file mode 100644 index 00000000000..060f53031bb --- /dev/null +++ b/ports/stm/peripherals/stm32l4/stm32l433xx/pins.c @@ -0,0 +1,50 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Blues Wireless Contributors +// +// SPDX-License-Identifier: MIT + +#include "py/obj.h" +#include "py/mphal.h" +#include "peripherals/pins.h" + +#include STM32_HAL_H + +const mcu_pin_obj_t pin_PA00 = PIN(0, 0, ADC_INPUT(ADC_1, 5)); +const mcu_pin_obj_t pin_PA01 = PIN(0, 1, ADC_INPUT(ADC_1, 6)); +const mcu_pin_obj_t pin_PA02 = PIN(0, 2, ADC_INPUT(ADC_1, 7)); +const mcu_pin_obj_t pin_PA03 = PIN(0, 3, ADC_INPUT(ADC_1, 8)); +const mcu_pin_obj_t pin_PA04 = PIN(0, 4, ADC_INPUT(ADC_1, 9)); +const mcu_pin_obj_t pin_PA05 = PIN(0, 5, ADC_INPUT(ADC_1, 10)); +const mcu_pin_obj_t pin_PA06 = PIN(0, 6, ADC_INPUT(ADC_1, 11)); +const mcu_pin_obj_t pin_PA07 = PIN(0, 7, ADC_INPUT(ADC_1, 12)); +const mcu_pin_obj_t pin_PA08 = PIN(0, 8, NO_ADC); +const mcu_pin_obj_t pin_PA09 = PIN(0, 9, NO_ADC); +const mcu_pin_obj_t pin_PA10 = PIN(0, 10, NO_ADC); +const mcu_pin_obj_t pin_PA11 = PIN(0, 11, NO_ADC); +const mcu_pin_obj_t pin_PA12 = PIN(0, 12, NO_ADC); +const mcu_pin_obj_t pin_PA13 = PIN(0, 13, NO_ADC); +const mcu_pin_obj_t pin_PA14 = PIN(0, 14, NO_ADC); +const mcu_pin_obj_t pin_PA15 = PIN(0, 15, NO_ADC); +const mcu_pin_obj_t pin_PB00 = PIN(1, 0, ADC_INPUT(ADC_1, 15)); +const mcu_pin_obj_t pin_PB01 = PIN(1, 1, ADC_INPUT(ADC_1, 16)); +const mcu_pin_obj_t pin_PB02 = PIN(1, 2, NO_ADC); +const mcu_pin_obj_t pin_PB03 = PIN(1, 3, NO_ADC); +const mcu_pin_obj_t pin_PB04 = PIN(1, 4, NO_ADC); +const mcu_pin_obj_t pin_PB05 = PIN(1, 5, NO_ADC); +const mcu_pin_obj_t pin_PB06 = PIN(1, 6, NO_ADC); +const mcu_pin_obj_t pin_PB07 = PIN(1, 7, NO_ADC); +const mcu_pin_obj_t pin_PB08 = PIN(1, 8, NO_ADC); +const mcu_pin_obj_t pin_PB09 = PIN(1, 9, NO_ADC); +const mcu_pin_obj_t pin_PB10 = PIN(1, 10, NO_ADC); +const mcu_pin_obj_t pin_PB11 = PIN(1, 11, NO_ADC); +const mcu_pin_obj_t pin_PB12 = PIN(1, 12, NO_ADC); +const mcu_pin_obj_t pin_PB13 = PIN(1, 13, NO_ADC); +const mcu_pin_obj_t pin_PB14 = PIN(1, 14, NO_ADC); +const mcu_pin_obj_t pin_PB15 = PIN(1, 15, NO_ADC); +const mcu_pin_obj_t pin_PC13 = PIN(2, 13, NO_ADC); +const mcu_pin_obj_t pin_PC14 = PIN(2, 14, NO_ADC); +const mcu_pin_obj_t pin_PC15 = PIN(2, 15, NO_ADC); +const mcu_pin_obj_t pin_PH00 = PIN(5, 0, NO_ADC); +const mcu_pin_obj_t pin_PH01 = PIN(5, 1, NO_ADC); +const mcu_pin_obj_t pin_PH03 = PIN(5, 3, NO_ADC); diff --git a/ports/stm/peripherals/stm32l4/stm32l433xx/pins.h b/ports/stm/peripherals/stm32l4/stm32l433xx/pins.h new file mode 100644 index 00000000000..93a175ddbad --- /dev/null +++ b/ports/stm/peripherals/stm32l4/stm32l433xx/pins.h @@ -0,0 +1,46 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Blues Wireless Contributors +// +// SPDX-License-Identifier: MIT + +#pragma once + +extern const mcu_pin_obj_t pin_PA00; +extern const mcu_pin_obj_t pin_PA01; +extern const mcu_pin_obj_t pin_PA02; +extern const mcu_pin_obj_t pin_PA03; +extern const mcu_pin_obj_t pin_PA04; +extern const mcu_pin_obj_t pin_PA05; +extern const mcu_pin_obj_t pin_PA06; +extern const mcu_pin_obj_t pin_PA07; +extern const mcu_pin_obj_t pin_PA08; +extern const mcu_pin_obj_t pin_PA09; +extern const mcu_pin_obj_t pin_PA10; +extern const mcu_pin_obj_t pin_PA11; +extern const mcu_pin_obj_t pin_PA12; +extern const mcu_pin_obj_t pin_PA13; +extern const mcu_pin_obj_t pin_PA14; +extern const mcu_pin_obj_t pin_PA15; +extern const mcu_pin_obj_t pin_PB00; +extern const mcu_pin_obj_t pin_PB01; +extern const mcu_pin_obj_t pin_PB02; +extern const mcu_pin_obj_t pin_PB03; +extern const mcu_pin_obj_t pin_PB04; +extern const mcu_pin_obj_t pin_PB05; +extern const mcu_pin_obj_t pin_PB06; +extern const mcu_pin_obj_t pin_PB07; +extern const mcu_pin_obj_t pin_PB08; +extern const mcu_pin_obj_t pin_PB09; +extern const mcu_pin_obj_t pin_PB10; +extern const mcu_pin_obj_t pin_PB11; +extern const mcu_pin_obj_t pin_PB12; +extern const mcu_pin_obj_t pin_PB13; +extern const mcu_pin_obj_t pin_PB14; +extern const mcu_pin_obj_t pin_PB15; +extern const mcu_pin_obj_t pin_PC13; +extern const mcu_pin_obj_t pin_PC14; +extern const mcu_pin_obj_t pin_PC15; +extern const mcu_pin_obj_t pin_PH00; +extern const mcu_pin_obj_t pin_PH01; +extern const mcu_pin_obj_t pin_PH03; diff --git a/ports/stm/peripherals/stm32l4/stm32l4r5xx/gpio.c b/ports/stm/peripherals/stm32l4/stm32l4r5xx/gpio.c index 18fe8b760a2..342a071213d 100644 --- a/ports/stm/peripherals/stm32l4/stm32l4r5xx/gpio.c +++ b/ports/stm/peripherals/stm32l4/stm32l4r5xx/gpio.c @@ -17,22 +17,17 @@ void stm32_peripherals_gpio_init(void) { __HAL_RCC_GPIOF_CLK_ENABLE(); __HAL_RCC_GPIOG_CLK_ENABLE(); - // These ports are not used on the Swan R5 but may need to be enabeld on other boards + // These ports are not used on the Swan R5 but may need to be enabled on other boards // __HAL_RCC_GPIOH_CLK_ENABLE(); // __HAL_RCC_GPIOI_CLK_ENABLE(); - // Never reset pins - never_reset_pin_number(2, 14); // PC14 OSC32_IN - never_reset_pin_number(2, 15); // PC15 OSC32_OUT - never_reset_pin_number(0, 13); // PA13 SWDIO - never_reset_pin_number(0, 14); // PA14 SWCLK - // never_reset_pin_number(0,15); //PA15 JTDI - // never_reset_pin_number(1,3); //PB3 JTDO - // never_reset_pin_number(1,4); //PB4 JTRST + // Pins in use by the system; mark them claimed so user code can't use them. + claim_pin(2, 14); // PC14 OSC32_IN + claim_pin(2, 15); // PC15 OSC32_OUT + claim_pin(0, 13); // PA13 SWDIO + claim_pin(0, 14); // PA14 SWCLK // Port H is not included in GPIO port array - // never_reset_pin_number(5,0); //PH0 JTDO - // never_reset_pin_number(5,1); //PH1 JTRST } void stm32l4_peripherals_status_led(uint8_t led, uint8_t state) { diff --git a/ports/stm/peripherals/stm32l4/stm32l4r5xx/periph.c b/ports/stm/peripherals/stm32l4/stm32l4r5xx/periph.c index 7a5d52e0c83..18d980043bf 100644 --- a/ports/stm/peripherals/stm32l4/stm32l4r5xx/periph.c +++ b/ports/stm/peripherals/stm32l4/stm32l4r5xx/periph.c @@ -116,21 +116,21 @@ USART_TypeDef *mcu_uart_banks[MAX_UART] = {USART1, USART2, USART3, UART4, UART5} bool mcu_uart_has_usart[MAX_UART] = {true, true, true, false, false}; const mcu_periph_obj_t mcu_uart_tx_list[UART_TX_ARRAY_LEN] = { - PERIPH(4, 9, &pin_PA00), + PERIPH(4, 8, &pin_PA00), PERIPH(2, 7, &pin_PA02), PERIPH(1, 7, &pin_PA09), PERIPH(1, 7, &pin_PB06), PERIPH(3, 7, &pin_PB10), PERIPH(3, 7, &pin_PC04), PERIPH(3, 7, &pin_PC10), - PERIPH(4, 9, &pin_PC10), - PERIPH(5, 9, &pin_PC12), + PERIPH(4, 8, &pin_PC10), + PERIPH(5, 8, &pin_PC12), PERIPH(2, 7, &pin_PD05), PERIPH(3, 7, &pin_PD08), PERIPH(1, 7, &pin_PG09), }; const mcu_periph_obj_t mcu_uart_rx_list[UART_RX_ARRAY_LEN] = { - PERIPH(4, 9, &pin_PA01), + PERIPH(4, 8, &pin_PA01), PERIPH(2, 7, &pin_PA03), PERIPH(1, 7, &pin_PA10), PERIPH(2, 3, &pin_PA15), @@ -138,8 +138,8 @@ const mcu_periph_obj_t mcu_uart_rx_list[UART_RX_ARRAY_LEN] = { PERIPH(3, 7, &pin_PB11), PERIPH(3, 7, &pin_PC05), PERIPH(3, 7, &pin_PC11), - PERIPH(4, 9, &pin_PC11), - PERIPH(5, 9, &pin_PD02), + PERIPH(4, 8, &pin_PC11), + PERIPH(5, 8, &pin_PD02), PERIPH(2, 7, &pin_PD06), PERIPH(3, 7, &pin_PD09), PERIPH(1, 7, &pin_PG10), @@ -156,13 +156,13 @@ const mcu_tim_pin_obj_t mcu_tim_pin_list[TIM_PIN_ARRAY_LEN] = { TIM(5, 2, 2, &pin_PA01), TIM(2, 1, 3, &pin_PA02), TIM(5, 2, 3, &pin_PA02), - TIM(15, 15, 1, &pin_PA02), + TIM(15, 14, 1, &pin_PA02), TIM(2, 1, 4, &pin_PA03), TIM(5, 2, 4, &pin_PA03), - TIM(15, 15, 2, &pin_PA03), + TIM(15, 14, 2, &pin_PA03), TIM(2, 1, 1, &pin_PA05), TIM(3, 2, 1, &pin_PA06), - TIM(16, 15, 1, &pin_PA06), + TIM(16, 14, 1, &pin_PA06), TIM(3, 2, 2, &pin_PA07), // TIM(17, 15, 1, &pin_PA07), // peripheral indices are 1 based, stored 0-based with 4 bits available. TIM(1, 1, 1, &pin_PA08), @@ -178,13 +178,13 @@ const mcu_tim_pin_obj_t mcu_tim_pin_list[TIM_PIN_ARRAY_LEN] = { TIM(4, 2, 1, &pin_PB06), TIM(4, 2, 2, &pin_PB07), TIM(4, 2, 3, &pin_PB08), - TIM(16, 15, 1, &pin_PB08), + TIM(16, 14, 1, &pin_PB08), TIM(4, 2, 4, &pin_PB09), // TIM(17, 15, 1, &pin_PB09), // peripheral indices are 1 based, stored 0-based with 4 bits available. TIM(2, 1, 3, &pin_PB10), TIM(2, 1, 4, &pin_PB11), - TIM(15, 15, 1, &pin_PB14), - TIM(15, 15, 2, &pin_PB15), + TIM(15, 14, 1, &pin_PB14), + TIM(15, 14, 2, &pin_PB15), TIM(3, 2, 1, &pin_PC06), TIM(8, 3, 1, &pin_PC06), TIM(3, 2, 2, &pin_PC07), @@ -197,7 +197,7 @@ const mcu_tim_pin_obj_t mcu_tim_pin_list[TIM_PIN_ARRAY_LEN] = { TIM(4, 2, 2, &pin_PD13), TIM(4, 2, 3, &pin_PD14), TIM(4, 2, 4, &pin_PD15), - TIM(16, 15, 1, &pin_PE00), + TIM(16, 14, 1, &pin_PE00), // TIM(17, 15, 1, &pin_PE01), // peripheral indices are 1 based, stored 0-based with 4 bits available. TIM(3, 2, 1, &pin_PE03), TIM(3, 2, 2, &pin_PE04), @@ -211,10 +211,10 @@ const mcu_tim_pin_obj_t mcu_tim_pin_list[TIM_PIN_ARRAY_LEN] = { TIM(5, 2, 2, &pin_PF07), TIM(5, 2, 3, &pin_PF08), TIM(5, 2, 4, &pin_PF09), - TIM(15, 15, 1, &pin_PF09), - TIM(15, 15, 2, &pin_PF10), - TIM(15, 15, 1, &pin_PG10), - TIM(15, 15, 2, &pin_PG11), + TIM(15, 14, 1, &pin_PF09), + TIM(15, 14, 2, &pin_PF10), + TIM(15, 14, 1, &pin_PG10), + TIM(15, 14, 2, &pin_PG11), TIM(5, 2, 1, &pin_PH10), TIM(5, 2, 2, &pin_PH11), TIM(5, 2, 3, &pin_PH12), diff --git a/ports/stm/peripherals/timers.c b/ports/stm/peripherals/timers.c index 9d963487a04..d2cd249995d 100644 --- a/ports/stm/peripherals/timers.c +++ b/ports/stm/peripherals/timers.c @@ -5,20 +5,21 @@ // SPDX-License-Identifier: MIT #include "timers.h" -#include "py/mpconfig.h" #include "py/obj.h" #include "py/runtime.h" +#include "ports/stm/peripherals/periph.h" #include "shared-bindings/microcontroller/__init__.h" #include "shared-bindings/microcontroller/Pin.h" +#ifdef STM32H7 +#include "stm32h7xx_hal_rcc.h" +#endif -#if !(CPY_STM32H7) #define ALL_CLOCKS 0xFFFF #define NULL_IRQ 0xFF static bool stm_timer_reserved[MP_ARRAY_SIZE(mcu_tim_banks)]; -static bool stm_timer_never_reset[MP_ARRAY_SIZE(mcu_tim_banks)]; typedef void (*stm_timer_callback_t)(void); // Array of function pointers. @@ -161,17 +162,29 @@ uint32_t stm_peripherals_timer_get_source_freq(TIM_TypeDef *timer) { // TIM{1,8,9,10,11} are on APB2 source = HAL_RCC_GetPCLK2Freq(); // 0b0xx means not divided; 0b100 is divide by 2; 0b101 by 4; 0b110 by 8; 0b111 by 16. + #ifdef STM32H7 + clk_div = (RCC->D2CFGR & RCC_D2CFGR_D2PPRE2) >> RCC_D2CFGR_D2PPRE2_Pos; + #else clk_div = (RCC->CFGR & RCC_CFGR_PPRE2) >> RCC_CFGR_PPRE2_Pos; + #endif } else { // TIM{2,3,4,5,6,7,12,13,14} are on APB1 source = HAL_RCC_GetPCLK1Freq(); // 0b0xx means not divided; 0b100 is divide by 2; 0b101 by 4; 0b110 by 8; 0b111 by 16. + #ifdef STM32H7 + clk_div = (RCC->D1CFGR & RCC_D1CFGR_D1PPRE) >> RCC_D1CFGR_D1PPRE_Pos; + #else clk_div = (RCC->CFGR & RCC_CFGR_PPRE1) >> RCC_CFGR_PPRE1_Pos; + #endif } // Only some STM32's have TIMPRE. #if defined(RCC_CFGR_TIMPRE) + #ifdef STM32H7 + uint32_t timpre = RCC->CFGR & RCC_CFGR_TIMPRE; + #else uint32_t timpre = RCC->DCKCFGR & RCC_CFGR_TIMPRE; + #endif if (timpre == 0) { if (clk_div >= 0b100) { source *= 2; @@ -196,7 +209,7 @@ size_t stm_peripherals_timer_get_irqnum(TIM_TypeDef *instance) { return irq_map[tim_id]; } -TIM_TypeDef *stm_peripherals_find_timer(void) { +TIM_TypeDef *stm_peripherals_find_free_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; @@ -215,22 +228,29 @@ TIM_TypeDef *stm_peripherals_find_timer(void) { } // If no results are found, no unclaimed pins with this timer are in this package, // and it is safe to pick - if (timer_in_package == false && mcu_tim_banks[i] != NULL) { + if (timer_in_package == false && mcu_tim_banks[i] != NULL && !stm_timer_reserved[i]) { return mcu_tim_banks[i]; } } // 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--) { + for (size_t i = MP_ARRAY_SIZE(mcu_tim_banks); i-- > 0;) { if ((!stm_timer_reserved[i]) && (mcu_tim_banks[i] != NULL)) { return mcu_tim_banks[i]; } } - mp_raise_RuntimeError(MP_ERROR_TEXT("All timers in use")); return NULL; } +TIM_TypeDef *stm_peripherals_find_timer(void) { + TIM_TypeDef *timer = stm_peripherals_find_free_timer(); + if (timer == NULL) { + mp_raise_RuntimeError(MP_ERROR_TEXT("All timers in use")); + } + return timer; +} + 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; @@ -250,26 +270,15 @@ void stm_peripherals_timer_set_callback(void (*callback)(void), TIM_TypeDef *tim void stm_peripherals_timer_free(TIM_TypeDef *instance) { size_t tim_idx = stm_peripherals_timer_get_index(instance); + // Gating the clock keeps the register state, so stop the timer and clear its + // interrupts; otherwise the next user gets a stale update interrupt. + instance->CR1 &= ~TIM_CR1_CEN; + instance->DIER = 0; + instance->SR = 0; HAL_NVIC_DisableIRQ(irq_map[tim_idx]); stm_timer_callback[tim_idx] = NULL; tim_clock_disable(1 << tim_idx); stm_timer_reserved[tim_idx] = false; - stm_timer_never_reset[tim_idx] = false; -} - -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) { - 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) { - 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) { @@ -287,7 +296,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(uint32_t mask) { #ifdef TIM1 if (mask & (1 << 0)) { __HAL_RCC_TIM1_CLK_ENABLE(); @@ -349,9 +358,28 @@ void tim_clock_enable(uint16_t mask) { __HAL_RCC_TIM14_CLK_ENABLE(); } #endif + + #ifdef STM32H750xx + // only enabled on the H750 board for now + #ifdef TIM15 + if (mask & (1 << 14)) { + __HAL_RCC_TIM15_CLK_ENABLE(); + } + #endif + #ifdef TIM16 + if (mask & (1 << 15)) { + __HAL_RCC_TIM16_CLK_ENABLE(); + } + #endif + #ifdef TIM17 + if (mask & (1 << 16)) { + __HAL_RCC_TIM17_CLK_ENABLE(); + } + #endif + #endif } -void tim_clock_disable(uint16_t mask) { +void tim_clock_disable(uint32_t mask) { #ifdef TIM1 if (mask & (1 << 0)) { __HAL_RCC_TIM1_CLK_DISABLE(); @@ -413,6 +441,26 @@ void tim_clock_disable(uint16_t mask) { __HAL_RCC_TIM14_CLK_DISABLE(); } #endif + + #ifdef STM32H750xx + // only enabled on the H750 board for now + #ifdef TIM15 + if (mask & (1 << 14)) { + __HAL_RCC_TIM15_CLK_DISABLE(); + } + #endif + #ifdef TIM16 + if (mask & (1 << 15)) { + __HAL_RCC_TIM16_CLK_DISABLE(); + } + #endif + #ifdef TIM17 + if (mask & (1 << 16)) { + __HAL_RCC_TIM17_CLK_DISABLE(); + } + #endif + #endif + } static void callback_router(size_t index) { @@ -421,75 +469,108 @@ static void callback_router(size_t index) { } } +#ifdef TIM1 void TIM1_CC_IRQHandler(void) { // Advanced timer callback_router(1); } +#endif +#ifdef TIM2 void TIM2_IRQHandler(void) { callback_router(2); } +#endif +#ifdef TIM3 void TIM3_IRQHandler(void) { callback_router(3); } +#endif +#ifdef TIM4 void TIM4_IRQHandler(void) { callback_router(4); } +#endif +#ifdef TIM5 void TIM5_IRQHandler(void) { callback_router(5); } +#endif +#ifdef TIM6 void TIM6_DAC_IRQHandler(void) { // Basic timer (DAC) callback_router(6); } +#endif +#ifdef TIM7 void TIM7_IRQHandler(void) { // Basic timer callback_router(7); } +#endif +#ifdef TIM8 void TIM8_CC_IRQHandler(void) { // Advanced timer callback_router(8); } +#endif // Advanced timer interrupts are currently unused. +#ifdef TIM9 void TIM1_BRK_TIM9_IRQHandler(void) { callback_router(9); } +#endif +#ifdef TIM10 void TIM1_UP_TIM10_IRQHandler(void) { callback_router(10); } +#endif +#ifdef TIM11 void TIM1_TRG_COM_TIM11_IRQHandler(void) { callback_router(11); } +#endif +#ifdef TIM12 void TIM8_BRK_TIM12_IRQHandler(void) { callback_router(12); } +#endif +#ifdef TIM13 void TIM8_UP_TIM13_IRQHandler(void) { callback_router(13); } +#endif +#ifdef TIM14 void TIM8_TRG_COM_TIM14_IRQHandler(void) { callback_router(14); } +#endif -#if (CPY_STM32H7) +#ifdef STM32H750xx +// only enabled on the H750 board for now +#ifdef TIM15 void TIM15_IRQHandler(void) { callback_router(15); } +#endif +#ifdef TIM16 void TIM16_IRQHandler(void) { callback_router(16); } +#endif +#ifdef TIM17 void TIM17_IRQHandler(void) { callback_router(17); } #endif - #endif diff --git a/ports/stm/peripherals/timers.h b/ports/stm/peripherals/timers.h index db3f9472e1e..285ff793588 100644 --- a/ports/stm/peripherals/timers.h +++ b/ports/stm/peripherals/timers.h @@ -7,22 +7,21 @@ #pragma once #include -#include "py/mphal.h" -#include "peripherals/periph.h" +#include #include STM32_HAL_H -void tim_clock_enable(uint16_t mask); -void tim_clock_disable(uint16_t mask); +void tim_clock_enable(uint32_t mask); +void tim_clock_disable(uint32_t mask); 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); +// Returns a free timer, or NULL if every timer is reserved. +TIM_TypeDef *stm_peripherals_find_free_timer(void); +// Like stm_peripherals_find_free_timer(), but raises if every timer is reserved. 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/cpu.s b/ports/stm/supervisor/cpu.s deleted file mode 100755 index 9e6807a5e2e..00000000000 --- a/ports/stm/supervisor/cpu.s +++ /dev/null @@ -1,27 +0,0 @@ -.syntax unified -.cpu cortex-m4 -.thumb -.text -.align 2 - -@ uint cpu_get_regs_and_sp(r0=uint regs[10]) -.global cpu_get_regs_and_sp -.thumb -.thumb_func -.type cpu_get_regs_and_sp, %function -cpu_get_regs_and_sp: -@ store registers into given array -str r4, [r0], #4 -str r5, [r0], #4 -str r6, [r0], #4 -str r7, [r0], #4 -str r8, [r0], #4 -str r9, [r0], #4 -str r10, [r0], #4 -str r11, [r0], #4 -str r12, [r0], #4 -str r13, [r0], #4 - -@ return the sp -mov r0, sp -bx lr diff --git a/ports/stm/supervisor/internal_flash.c b/ports/stm/supervisor/internal_flash.c index 11fdc0a198d..240dbba9960 100644 --- a/ports/stm/supervisor/internal_flash.c +++ b/ports/stm/supervisor/internal_flash.c @@ -75,12 +75,18 @@ static const flash_layout_t flash_layout[] = { #endif static uint8_t _flash_cache[0x20000] __attribute__((aligned(4))); -#elif defined(STM32L4) +#elif defined(STM32L4R5xx) static const flash_layout_t flash_layout[] = { { 0x08100000, 0x1000, 256 }, }; static uint8_t _flash_cache[0x1000] __attribute__((aligned(4))); +#elif defined(STM32L433xx) +static const flash_layout_t flash_layout[] = { + { 0x08000000, 0x0800, 128 }, +}; +static uint8_t _flash_cache[0x0800] __attribute__((aligned(4))); + #else #error Unsupported processor #endif @@ -185,8 +191,13 @@ void port_internal_flash_flush(void) { // set up for erase FLASH_EraseInitTypeDef EraseInitStruct = {}; #if CPY_STM32L4 + #if defined(STM32L4R5xx) EraseInitStruct.TypeErase = TYPEERASE_PAGES; - EraseInitStruct.Banks = FLASH_BANK_2; // filesystem stored in upper 1MB of flash in dual bank mode + EraseInitStruct.Banks = FLASH_BANK_2; // filesystem stored in upper 1MB of flash in dual bank mode + #elif defined(STM32L433xx) + EraseInitStruct.TypeErase = TYPEERASE_PAGES; + EraseInitStruct.Banks = FLASH_BANK_1; + #endif #else EraseInitStruct.TypeErase = TYPEERASE_SECTORS; EraseInitStruct.VoltageRange = VOLTAGE_RANGE_3; // voltage range needs to be 2.7V to 3.6V diff --git a/ports/stm/supervisor/internal_flash.h b/ports/stm/supervisor/internal_flash.h index e9979e6a010..2f4edbbf278 100644 --- a/ports/stm/supervisor/internal_flash.h +++ b/ports/stm/supervisor/internal_flash.h @@ -38,6 +38,16 @@ #endif #endif +#ifdef STM32F412Rx +#define STM32_FLASH_SIZE 0x80000 // 512KiB (F412RE; F412RG has 1MB) +#ifndef INTERNAL_FLASH_FILESYSTEM_SIZE + #define INTERNAL_FLASH_FILESYSTEM_SIZE 0xC000 // 48KiB +#endif +#ifndef INTERNAL_FLASH_FILESYSTEM_START_ADDR + #define INTERNAL_FLASH_FILESYSTEM_START_ADDR 0x08004000 +#endif +#endif + #ifdef STM32F412Zx #define STM32_FLASH_SIZE 0x100000 // 1MB #define INTERNAL_FLASH_FILESYSTEM_SIZE 0xC000 // 48KiB @@ -93,6 +103,12 @@ #define INTERNAL_FLASH_FILESYSTEM_START_ADDR 0x08100000 #endif +#ifdef STM32L433xx +#define STM32_FLASH_SIZE 0x40000 // 256KiB +#define INTERNAL_FLASH_FILESYSTEM_SIZE 0xC000 // 48KiB +#define INTERNAL_FLASH_FILESYSTEM_START_ADDR 0x08004000 +#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 diff --git a/ports/stm/supervisor/port.c b/ports/stm/supervisor/port.c index 7743d82f601..79f6303fcc5 100644 --- a/ports/stm/supervisor/port.c +++ b/ports/stm/supervisor/port.c @@ -32,6 +32,9 @@ #if CIRCUITPY_RTC #include "shared-bindings/rtc/__init__.h" #endif +#if CIRCUITPY_AUDIOIO +#include "common-hal/audioio/AudioOut.h" +#endif #include "peripherals/clocks.h" #include "peripherals/gpio.h" @@ -39,9 +42,18 @@ #include STM32_HAL_H -void NVIC_SystemReset(void) NORETURN; +void NVIC_SystemReset(void) MP_NORETURN; #if (CPY_STM32H7) || (CPY_STM32F7) +#if defined(CIRCUITPY_HW_SDRAM_SIZE) +#include "stm.h" +#include "sdram.h" +#include +#include +#include "lib/tlsf/tlsf.h" +// internal SRAM + external SDRAM +#define CIRCUITPY_RAM_DEVICE_COUNT (2) +#endif // Device memories must be accessed in order. #define DEVICE 2 @@ -146,6 +158,16 @@ __attribute__((used, naked)) void Reset_Handler(void) { start execution of the firmware from the external flash. It also makes the SystemInit() call not necessary for this chip. */ + #if defined(__ICACHE_PRESENT) && (__ICACHE_PRESENT == 1U) + /* Enable I cache. */ + SCB_EnableICache(); + #endif /* __ICACHE_PRESENT */ + + #if defined(__DCACHE_PRESENT) && (__DCACHE_PRESENT == 1U) + /* Enable D cache. */ + SCB_EnableDCache(); + #endif /* __DCACHE_PRESENT */ + #else SystemInit(); #endif @@ -157,7 +179,151 @@ __attribute__((used, naked)) void Reset_Handler(void) { // Low power clock variables static volatile uint32_t systick_ms; +#if defined(CIRCUITPY_HW_SDRAM_SIZE) +static tlsf_t _heap = NULL; +static pool_t pools[CIRCUITPY_RAM_DEVICE_COUNT] = {NULL}; + + +void port_heap_init(void) { + // heap init in _port_heap_init called from port_init +} + +void stm_add_sdram_to_heap(void) { + size_t sdram_memory_size = sdram_size(); + pools[1] = tlsf_add_pool(_heap, sdram_start(), sdram_memory_size); +} + +static void _port_heap_init(void) { + uint32_t *heap_bottom = port_heap_get_bottom(); + uint32_t *heap_top = port_heap_get_top(); + size_t size = (heap_top - heap_bottom) * sizeof(uint32_t); + size_t sdram_memory_size = sdram_size(); + + _heap = tlsf_create_with_pool(heap_bottom, size, size + sdram_memory_size); + pools[0] = tlsf_get_pool(_heap); +} + +static bool max_size_walker(void *ptr, size_t size, int used, void *user) { + size_t *max_size = (size_t *)user; + if (!used && *max_size < size) { + *max_size = size; + } + return true; +} + +size_t port_heap_get_largest_free_size(void) { + size_t max_size = 0; + for (size_t i = 0; i < CIRCUITPY_RAM_DEVICE_COUNT; i++) { + if (pools[i]) { + tlsf_walk_pool(pools[i], max_size_walker, &max_size); + } + } + return tlsf_fit_size(_heap, max_size); +} + +void *port_malloc(size_t size, bool dma_capable) { + void *block = tlsf_malloc(_heap, size); + return block; +} + +void port_free(void *ptr) { + tlsf_free(_heap, ptr); +} + +void *port_realloc(void *ptr, size_t size, bool dma_capable) { + return tlsf_realloc(_heap, ptr, size); +} +#endif + +// Pending request for the ST system bootloader. This lives in the saved word, +// RAM that startup does not clear, which is where the other ports keep theirs: +// _bootloader_dbl_tap on atmel-samd, NRF_POWER->GPREGRET on nordic, +// SNVS->LPGPR[3] on mimxrt10xx. The low byte is the attempt count. +#define BOOTLOADER_MAGIC 0xf05a0000 +#define BOOTLOADER_MAGIC_MASK 0xffff0000 +// Magic in the top half, RTC seconds of the last attempt in bits 15:8, attempt +// count in bits 7:0. +#define BOOTLOADER_SECONDS_SHIFT 8 +#define BOOTLOADER_FIELD_MASK 0xff + +// A retry only counts if it follows the previous attempt closely. The ROM fails +// and resets within a second, so anything slower is the part being reset by +// something else while the bootloader was running, and the request is stale. +// Without this, exiting DFU with a software reset lands straight back in DFU. +#define BOOTLOADER_RETRY_WINDOW_S 5 + +// The ROM clocks USB from the HSE but does not know which crystal is fitted, so +// it measures one against the HSI and resets the part when that misses: AN2606 +// Figure 32/33, "HSE detected" -> no -> "Generate System reset". On the 12 MHz +// Feather STM32F405 Express one attempt reached DFU 5 times in 12. +#define BOOTLOADER_MAX_ATTEMPTS 16 + +#if CPY_STM32F4 +// Seconds field of the RTC clock, read straight from the register because the +// HAL handle is not initialised this early. rtc_init() leaves shadow bypass on +// and that setting survives a reset, so the register reads live. Only a read is +// needed, so the backup domain does not have to be unlocked for write. +static uint32_t bootloader_rtc_seconds(void) { + uint32_t tr = RTC->TR; + return ((tr >> 4) & 0x7) * 10 + (tr & 0xF); +} + +// Naked so nothing touches the stack between setting MSP and the branch. +MP_NORETURN static __attribute__((naked)) void branch_to_bootloader(uint32_t bl_addr) { + __asm volatile ( + "ldr r2, [r0, #0]\n" + "msr msp, r2\n" + "ldr r2, [r0, #4]\n" + "bx r2\n" + ); +} + +// Runs before HAL_Init() starts SysTick, so the ROM gets the part close to reset +// state. The ROM sets its own VTOR and runs from 0x1FFF0000, so no SYSCFG remap +// is needed here. +static void check_enter_bootloader(void) { + uint32_t request = port_get_saved_word(); + if ((request & BOOTLOADER_MAGIC_MASK) != BOOTLOADER_MAGIC) { + // Not our word. Safe mode shares it, so leave it alone. + return; + } + + // The ROM signals its HSE-detect failure with a software reset, so SFTRSTF is + // what tells a retry apart from a cold boot, and a power cycle always leaves + // the bootloader. + if (!(RCC->CSR & RCC_CSR_SFTRSTF)) { + port_set_saved_word(0); + return; + } + + uint32_t now = bootloader_rtc_seconds(); + uint32_t then = (request >> BOOTLOADER_SECONDS_SHIFT) & BOOTLOADER_FIELD_MASK; + if ((now + 60 - then) % 60 > BOOTLOADER_RETRY_WINDOW_S) { + port_set_saved_word(0); + return; + } + + uint32_t attempts = request & BOOTLOADER_FIELD_MASK; + if (attempts >= BOOTLOADER_MAX_ATTEMPTS) { + port_set_saved_word(0); + return; + } + port_set_saved_word(BOOTLOADER_MAGIC | + (now << BOOTLOADER_SECONDS_SHIFT) | (attempts + 1)); + // Clearing the flags cancels the request once the ROM succeeds: leaving DFU + // is a jump, not a reset, so SFTRSTF stays clear and the branch above zeroes + // the flag on the way back into the application. + RCC->CSR |= RCC_CSR_RMVF; + + branch_to_bootloader(0x1FFF0000); +} +#endif + safe_mode_t port_init(void) { + #if CPY_STM32F4 + check_enter_bootloader(); + #endif + HAL_Init(); // Turns on SysTick __HAL_RCC_SYSCFG_CLK_ENABLE(); @@ -190,6 +356,9 @@ safe_mode_t port_init(void) { __HAL_PWR_CLEAR_FLAG(PWR_FLAG_WU); stm32_peripherals_rtc_reset_alarms(); + #if defined(CIRCUITPY_HW_SDRAM_SIZE) + _port_heap_init(); + #endif // Turn off SysTick SysTick->CTRL = 0; @@ -207,7 +376,7 @@ void HAL_Delay(uint32_t delay_ms) { } } -uint32_t HAL_GetTick() { +uint32_t HAL_GetTick(void) { if (SysTick->CTRL != 0) { return systick_ms; } else { @@ -224,63 +393,35 @@ void SysTick_Handler(void) { } void reset_port(void) { - reset_all_pins(); - #if CIRCUITPY_RTC rtc_reset(); #endif - - #if CIRCUITPY_BUSIO - spi_reset(); - uart_reset(); - #endif - #if CIRCUITPY_SDIOIO - sdioio_reset(); - #endif - #if CIRCUITPY_ALARM - exti_reset(); - #endif } -void reset_to_bootloader(void) { +#if BOARD_UF2_STM32F_BOOTLOADER +// uf2-stm32f (https://github.com/mmoskal/uf2-stm32f) reads RTC->BKP0R on reset. +// With no signature it starts UF2 mode and, once USB enumerates, stays there. +// port_init() resets the backup domain, so this is written just before reset. +#define UF2_STM32F_BOOT_SIGNATURE 0x71a21877 +#define UF2_STM32F_APP_SIGNATURE 0x24a22d12 -/* -From STM AN2606: -Before jumping to bootloader user must: -• Disable all peripheral clocks -• Disable used PLL -• Disable interrupts -• Clear pending interrupts -System memory boot mode can be exited by getting out from bootloader activation -condition and generating hardware reset or using Go command to execute user code -*/ - HAL_RCC_DeInit(); - HAL_DeInit(); - - // Disable all pending interrupts using NVIC - for (uint8_t i = 0; i < MP_ARRAY_SIZE(NVIC->ICER); ++i) { - NVIC->ICER[i] = 0xFFFFFFFF; - } - - // if it is necessary to ensure an interrupt will not be triggered after disabling it in the NVIC, - // add a DSB instruction and then an ISB instruction. (ARM Cortex™-M Programming Guide to - // Memory Barrier Instructions, 4.6 Disabling Interrupts using NVIC) - __DSB(); - __ISB(); - - // Clear all pending interrupts using NVIC - for (uint8_t i = 0; i < MP_ARRAY_SIZE(NVIC->ICPR); ++i) { - NVIC->ICPR[i] = 0xFFFFFFFF; - } +static void set_uf2_stm32f_signature(uint32_t signature) { + __HAL_RCC_PWR_CLK_ENABLE(); + HAL_PWR_EnableBkUpAccess(); + RTC->BKP0R = signature; +} +#endif - // information about jump addresses has been taken from STM AN2606. - #if defined(STM32F4) - __set_MSP(*((uint32_t *)0x1FFF0000)); - ((void (*)(void)) * ((uint32_t *)0x1FFF0004))(); - #else - // DFU mode for STM32 variant note implemented. - NVIC_SystemReset(); +void reset_to_bootloader(void) { + #if BOARD_UF2_STM32F_BOOTLOADER + set_uf2_stm32f_signature(UF2_STM32F_BOOT_SIGNATURE); + #elif CPY_STM32F4 + // Record the request and reset, rather than jumping from a running + // application. check_enter_bootloader() jumps on the way back up. + port_set_saved_word(BOOTLOADER_MAGIC | + (bootloader_rtc_seconds() << BOOTLOADER_SECONDS_SHIFT)); #endif + NVIC_SystemReset(); while (true) { asm ("nop;"); @@ -288,6 +429,9 @@ condition and generating hardware reset or using Go command to execute user code } void reset_cpu(void) { + #if BOARD_UF2_STM32F_BOOTLOADER + set_uf2_stm32f_signature(UF2_STM32F_APP_SIGNATURE); + #endif NVIC_SystemReset(); } @@ -384,6 +528,8 @@ void port_idle_until_interrupt(void) { return; } common_hal_mcu_disable_interrupts(); + // Don't sleep on a tick that has stopped. + stm32_peripherals_rtc_recover_wakeup(); if (!background_callback_pending()) { __WFI(); } diff --git a/ports/stm/supervisor/stm.h b/ports/stm/supervisor/stm.h new file mode 100644 index 00000000000..6d3342137fb --- /dev/null +++ b/ports/stm/supervisor/stm.h @@ -0,0 +1,10 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 snkYmkrct +// +// SPDX-License-Identifier: MIT + +#pragma once + + +void stm_add_sdram_to_heap(void); diff --git a/ports/stm/supervisor/usb.c b/ports/stm/supervisor/usb.c index 61a7d54f08b..c1387378912 100644 --- a/ports/stm/supervisor/usb.c +++ b/ports/stm/supervisor/usb.c @@ -29,7 +29,7 @@ static void init_usb_vbus_sense(void) { // B-peripheral session valid override enable USB_OTG_FS->GOTGCTL |= USB_OTG_GOTGCTL_BVALOEN; USB_OTG_FS->GOTGCTL |= USB_OTG_GOTGCTL_BVALOVAL; - #else + #elif !defined(STM32L433xx) && !defined(STM32L4R5xx) USB_OTG_FS->GCCFG |= USB_OTG_GCCFG_NOVBUSSENS; USB_OTG_FS->GCCFG &= ~USB_OTG_GCCFG_VBUSBSEN; USB_OTG_FS->GCCFG &= ~USB_OTG_GCCFG_VBUSASEN; @@ -56,7 +56,7 @@ void init_usb_hardware(void) { GPIO_InitTypeDef GPIO_InitStruct = {0}; /**USB_OTG_FS GPIO Configuration - PA10 ------> USB_OTG_FS_ID + PA10 ------> USB_OTG_FS_ID (not present on STM32L433) PA11 ------> USB_OTG_FS_DM PA12 ------> USB_OTG_FS_DP */ @@ -69,12 +69,15 @@ void init_usb_hardware(void) { GPIO_InitStruct.Pull = GPIO_NOPULL; #if CPY_STM32H7 GPIO_InitStruct.Alternate = GPIO_AF10_OTG1_FS; - #elif CPY_STM32F4 || CPY_STM32F7 || CPY_STM32L4 + #elif CPY_STM32F4 || CPY_STM32F7 || defined(STM32L4R5xx) GPIO_InitStruct.Alternate = GPIO_AF10_OTG_FS; + #elif defined(STM32L433xx) + GPIO_InitStruct.Alternate = GPIO_AF10_USB_FS; + #else + #error Unknown MCU #endif HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); - never_reset_pin_number(0, 11); - never_reset_pin_number(0, 12); + claim_pin(0, 11); claim_pin(0, 12); @@ -84,7 +87,6 @@ void init_usb_hardware(void) { GPIO_InitStruct.Mode = GPIO_MODE_INPUT; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); - never_reset_pin_number(0, 9); claim_pin(0, 9); #endif @@ -100,7 +102,6 @@ void init_usb_hardware(void) { GPIO_InitStruct.Alternate = GPIO_AF10_OTG_FS; #endif HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); - never_reset_pin_number(0, 10); claim_pin(0, 10); #endif @@ -110,22 +111,27 @@ void init_usb_hardware(void) { GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_OD; GPIO_InitStruct.Pull = GPIO_NOPULL; HAL_GPIO_Init(GPIOG, &GPIO_InitStruct); - never_reset_pin_number(0, 8); claim_pin(0, 8); #endif #if CPY_STM32H7 HAL_PWREx_EnableUSBVoltageDetector(); __HAL_RCC_USB2_OTG_FS_CLK_ENABLE(); - #else + #elif CPY_STM32F4 || CPY_STM32F7 || defined(STM32L4R5xx) /* Peripheral clock enable */ __HAL_RCC_USB_OTG_FS_CLK_ENABLE(); + #else + __HAL_RCC_USB_CLK_ENABLE(); #endif - init_usb_vbus_sense(); } -void OTG_FS_IRQHandler(void) { +#if defined(STM32L433xx) +void USB_IRQHandler(void) +#else +void OTG_FS_IRQHandler(void) +#endif +{ usb_irq_handler(0); } diff --git a/ports/unix/Makefile b/ports/unix/Makefile index cd0403a8f5d..62fa4c732e9 100644 --- a/ports/unix/Makefile +++ b/ports/unix/Makefile @@ -17,6 +17,10 @@ endif # If the build directory is not given, make it reflect the variant name. BUILD ?= build-$(VARIANT) +ifneq ($(MICROPY_FORCE_32BIT),) +$(warning *** The MICROPY_FORCE_32BIT flag is no longer affecting builds, please update your environment ***) +endif + include ../../py/mkenv.mk -include mpconfigport.mk include $(VARIANT_DIR)/mpconfigvariant.mk @@ -27,6 +31,9 @@ FROZEN_MANIFEST ?= variants/manifest.py # This should be configured by the mpconfigvariant.mk PROG ?= micropython +# For use in test rules below +ABS_PROG = $(abspath $(BUILD)/$(PROG)) + # qstr definitions (must come before including py.mk) QSTR_DEFS += qstrdefsport.h QSTR_GLOBAL_DEPENDENCIES += $(VARIANT_DIR)/mpconfigvariant.h @@ -46,24 +53,38 @@ INC += -I$(BUILD) # compiler settings CWARN = -Wall -Werror -CWARN += -Wextra -Wno-unused-parameter -Wpointer-arith -Wdouble-promotion -Wfloat-conversion -CFLAGS += $(INC) $(CWARN) -std=gnu99 -DUNIX $(COPT) -I$(VARIANT_DIR) $(CFLAGS_EXTRA) +# CIRCUITPY-CHANGE: add -Wno-missing-field-initializers +CWARN += -Wextra -Wno-unused-parameter -Wpointer-arith -Wdouble-promotion -Wfloat-conversion -Wno-missing-field-initializers +# CIRCUITPY-CHANGE: use gnu11 instead of gnu99 +CFLAGS += $(INC) $(CWARN) -std=gnu11 -DUNIX $(COPT) -I$(VARIANT_DIR) $(CFLAGS_EXTRA) + +# Force the use of 64-bits for file sizes in C library functions on 32-bit platforms. +# This option has no effect on 64-bit builds. +CFLAGS += -D_FILE_OFFSET_BITS=64 + +# Force the use of 64-bits for time_t in C library functions on 32-bit platforms. +# This option has no effect on 64-bit builds. +CFLAGS += -D_TIME_BITS=64 + +# Debug info flag is added if either DEBUG=1 or STRIP= is passed to make +# (to produce a debug binary, or a release binary with all symbols, respectively.) +DEBUG_INFO = -ggdb3 # Debugging/Optimization ifdef DEBUG COPT ?= -Og +CFLAGS += $(DEBUG_INFO) else COPT ?= -Os COPT += -DNDEBUG +ifndef STRIP +CFLAGS += $(DEBUG_INFO) endif +endif # ifdef DEBUG # Remove unused sections. COPT += -fdata-sections -ffunction-sections -# Note: Symbols and debug information will still be stripped from the final binary -# unless "DEBUG=1" or "STRIP=" is passed to make, see README.md for details. -CFLAGS += -g - ifndef DEBUG # _FORTIFY_SOURCE is a feature in gcc/glibc which is intended to provide extra # security for detecting buffer overflows. Some distros (Ubuntu at the very least) @@ -97,11 +118,7 @@ endif # while cross-compile ports require gcc, so we test here for OSX and # if necessary override the value of 'CC' set in py/mkenv.mk ifeq ($(UNAME_S),Darwin) -ifeq ($(MICROPY_FORCE_32BIT),1) -CC = clang -m32 -else CC = clang -endif # Use clang syntax for map file LDFLAGS_ARCH = -Wl,-map,$@.map -Wl,-dead_strip else @@ -113,16 +130,6 @@ LDFLAGS += $(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 -ifeq ($(MICROPY_PY_FFI),1) -ifeq ($(UNAME_S),Linux) -CFLAGS += -I/usr/include/i686-linux-gnu -endif -endif -endif - ifeq ($(MICROPY_USE_READLINE),1) INC += -I$(TOP)/shared/readline CFLAGS += -DMICROPY_USE_READLINE=1 @@ -135,7 +142,11 @@ ifeq ($(MICROPY_PY_SOCKET),1) CFLAGS += -DMICROPY_PY_SOCKET=1 endif ifeq ($(MICROPY_PY_THREAD),1) +ifeq ($(MICROPY_PY_THREAD_GIL),1) +CFLAGS += -DMICROPY_PY_THREAD=1 -DMICROPY_PY_THREAD_GIL=1 +else CFLAGS += -DMICROPY_PY_THREAD=1 -DMICROPY_PY_THREAD_GIL=0 +endif LDFLAGS += $(LIBPTHREAD) endif @@ -169,12 +180,8 @@ ifeq ($(MICROPY_STANDALONE),1) # Build libffi from source. GIT_SUBMODULES += lib/libffi DEPLIBS += libffi -LIBFFI_CFLAGS := -I$(shell ls -1d $(BUILD)/lib/libffi/out/lib/libffi-*/include) - ifeq ($(MICROPY_FORCE_32BIT),1) - LIBFFI_LDFLAGS = $(BUILD)/lib/libffi/out/lib32/libffi.a - else - LIBFFI_LDFLAGS = $(BUILD)/lib/libffi/out/lib/libffi.a - endif +LIBFFI_CFLAGS := -I$(shell ls -1d $(BUILD)/lib/libffi/include) +LIBFFI_LDFLAGS = $(BUILD)/lib/libffi/out/lib/libffi.a else # Use system version of libffi. LIBFFI_CFLAGS := $(shell pkg-config --cflags libffi) @@ -204,6 +211,8 @@ SRC_C += \ input.c \ alloc.c \ fatfs_port.c \ + shared-module/os/__init__.c \ + supervisor/shared/settings.c \ supervisor/stub/filesystem.c \ supervisor/stub/safe_mode.c \ supervisor/stub/stack.c \ @@ -219,6 +228,7 @@ $(BUILD)/supervisor/shared/translate/translate.o: $(HEADER_BUILD)/qstrdefs.gener SHARED_SRC_C += $(addprefix shared/,\ runtime/gchelper_generic.c \ + runtime/pyexec.c \ timeutils/timeutils.c \ $(SHARED_SRC_C_EXTRA) \ ) @@ -243,12 +253,6 @@ CFLAGS += -DMPZ_DIG_SIZE=16 # force 16 bits to work on both 32 and 64 bit archs CFLAGS += -DMICROPY_MODULE_FROZEN_STR endif -CXXFLAGS += $(filter-out -Wmissing-prototypes -Wold-style-definition -std=gnu99,$(CFLAGS) $(CXXFLAGS_MOD)) - -ifeq ($(MICROPY_FORCE_32BIT),1) -RUN_TESTS_MPY_CROSS_FLAGS = --mpy-cross-flags='-march=x86' -endif - ifeq ($(CROSS_COMPILE),arm-linux-gnueabi-) # Force disable error text compression when compiling for ARM as the compiler # cannot optimise out the giant strcmp list generated for MP_MATCH_COMPRESSED. @@ -274,7 +278,7 @@ print-failures clean-failures: TEST_ARGS ?= test: $(BUILD)/$(PROG) $(TOP)/tests/run-tests.py $(eval DIRNAME=ports/$(notdir $(CURDIR))) - cd $(TOP)/tests && MICROPY_MICROPYTHON=../$(DIRNAME)/$(BUILD)/$(PROG) ./run-tests.py $(TEST_ARGS) + cd $(TOP)/tests && MICROPY_MICROPYTHON=../$(DIRNAME)/$(BUILD)/$(PROG) ./run-tests.py test_full: $(BUILD)/$(PROG) $(TOP)/tests/run-tests.py $(eval DIRNAME=ports/$(notdir $(CURDIR))) diff --git a/ports/unix/README.md b/ports/unix/README.md index 61dfd7453e6..720be8a047c 100644 --- a/ports/unix/README.md +++ b/ports/unix/README.md @@ -1,17 +1,60 @@ -The Unix version -================ +MicroPython Unix port +===================== + +The "unix" port runs in standard Unix-like environments including Linux, BSD, +macOS, and Windows Subsystem for Linux. + +The x86 and x64 architectures are supported (i.e. x86 32- and 64-bit), as well +as ARM, MIPS, RISC-V, and LoongArch. Extending the unix port to another +architecture requires writing some assembly code for the exception handling +and garbage collection. Alternatively, a fallback implementation based on +setjmp/longjmp can be used. + +Building +-------- + +### Dependencies + +To build the unix port locally then you will need: + +* git command line executable, unless you downloaded a source .tar.xz file from + https://micropython.org/download/ +* an appropriate GCC or Clang toolchain for your target (macOS only supports Clang) +* GNU Make +* Python 3.x + +To build the default "standard" variant and configuration, then you will also +need: -The "unix" port requires a standard Unix-like environment with gcc and GNU -make. This includes Linux, BSD, macOS, and Windows Subsystem for Linux. The -x86 and x64 architectures are supported (i.e. x86 32- and 64-bit), as well as -ARM and MIPS. Making a full-featured port to another architecture requires -writing some assembly code for the exception handling and garbage collection. -Alternatively, a fallback implementation based on setjmp/longjmp can be used. +* `pkg-config` tool +* `libffi` library and headers -To build (see section below for required dependencies): +On Debian/Ubuntu/Mint and related Linux distros, you can install all these +dependencies with a command like: + +``` +# apt install build-essential git python3 pkg-config libffi-dev +``` + +(See below for steps to build either a standalone or minimal MicroPython +executable that doesn't require system `libffi` or `pkg-config`.) + +### Default build steps + +To set up the environment for building (not needed every time), starting from +the top-level MicroPython directory: $ cd ports/unix + $ make -C ../../mpy-cross $ make submodules + +The `mpy-cross` step builds the [MicroPython +cross-compiler](https://github.com/micropython/micropython/?tab=readme-ov-file#the-micropython-cross-compiler-mpy-cross). +The `make submodules` step can be skipped if you didn't clone the MicroPython +source from git. + +Next, to build the actual executable (still in the `ports/unix` directory): + $ make Then to give it a try: @@ -30,6 +73,14 @@ To run the complete testsuite, use: $ make test +There are other make targets to interact with the testsuite: + + $ make test//int # Run all tests matching the pattern "int" + $ make test/ports/unix # Run all tests in ports/unix + $ make test-failures # Re-run only the failed tests + $ make print-failures # print the differences for failed tests + $ make clean-failures # delete the .exp and .out files from failed tests + The Unix port comes with a built-in package manager called `mip`, e.g.: $ ./build-standard/micropython -m mip install hmac @@ -45,44 +96,211 @@ Browse available modules at [Package management](https://docs.micropython.org/en/latest/reference/packages.html) for more information about `mip`. -External dependencies -===================== - -The `libffi` library and `pkg-config` tool are required. On Debian/Ubuntu/Mint -derivative Linux distros, install `build-essential`(includes toolchain and -make), `libffi-dev`, and `pkg-config` packages. +### Minimal Variant -Other dependencies can be built together with MicroPython. This may -be required to enable extra features or capabilities, and in recent -versions of MicroPython, these may be enabled by default. To build -these additional dependencies, in the unix port directory first execute: +The "standard" variant of MicroPython is the default. It enables most features, +including external modules interfaced using `libffi`. To instead build the +"minimal" variant, which disables almost all optional features and modules: + $ cd ports/unix $ make submodules + $ make VARIANT=minimal + +The executable will be built at `build-minimal/micropython`. + +Additional variants can be found in the `variants` sub-directory of the port, +although these are mostly of interest to MicroPython maintainers. + +### Standalone build + +By default, the "standard" variant uses `pkg-config` to link to the system's +shared `libffi` library. -This will fetch all the relevant git submodules (sub repositories) that -the port needs. Use the same command to get the latest versions of -submodules as they are updated from time to time. After that execute: +It is possible to instead build a standalone MicroPython where `libffi` is built +from source and linked statically into the `micropython` executable. This is +mostly useful for embedded or cross-compiled applications. - $ make deplibs +Building standalone requires `autoconf` and `libtool` to also be installed. -This will build all available dependencies (regardless whether they are used -or not). If you intend to build MicroPython with additional options -(like cross-compiling), the same set of options should be passed to `make -deplibs`. To actually enable/disable use of dependencies, edit the +To build standalone: + + $ export MICROPY_STANDALONE=1 + $ make submodules # fetches libffi submodule + $ make deplibs # build just the external libraries + $ make # build MicroPython itself + +`make deplibs` causes all supported external libraries (currently only `libffi`) +to be built inside the build directory, so it needs to run again only after +`make clean`. + +If you intend to build MicroPython with additional options (like +cross-compiling), the same set of options should be passed to both `make +deplibs` and `make`. + +### Other dependencies + +To actually enable/disable use of dependencies, edit the `ports/unix/mpconfigport.mk` file, which has inline descriptions of the options. For example, to build the SSL module, `MICROPY_PY_SSL` should be set to 1. -Debug Symbols -============= +### Debug Symbols By default, builds are stripped of symbols and debug information to save size. -To build a debuggable version of the Unix port, there are two options +To build a debuggable version of the Unix port, there are two options: 1. Run `make [other arguments] DEBUG=1`. Note setting `DEBUG` also reduces the - optimisation level, so it's not a good option for builds that also want the - best performance. + optimisation level and enables assertions, so it's not a good option for + builds that also want the best performance. 2. Run `make [other arguments] STRIP=`. Note that the value of `STRIP` is empty. This will skip the build step that strips symbols and debug information, but changes nothing else in the build configuration. + +### Optimisation Level + +The default compiler optimisation level is -Os, or -Og if `DEBUG=1` is set. + +Setting the variable `COPT` will explicitly set the optimisation level. For +example `make [other arguments] COPT=-O0 DEBUG=1` will build a binary with no +optimisations, assertions enabled, and debug symbols. + +### Sanitizers + +Sanitizers are extra runtime checks supported by GCC and Clang. The CI process +supports building with the "undefined behavior" (UBSan) or "address" (ASan) +sanitizers. The script `tools/ci.sh` is the source of truth about how to build +and run in these modes. + +Several classes of checks are disabled via compiler flags: + +* In the undefined behavior sanitizer, checks based on the presence of the + `non_null` attribute are disabled because the code makes technically incorrect + calls like `memset(NULL, 0, 0)`. A future C standard is likely to permit such + calls. +* In the address sanitizer, `detect_stack_use_after_return` is disabled. This + check is intended to make sure locals in a "returned from" stack frame are not + used. However, this mode interferes with various assumptions that + MicroPython's stack checking, NLR, and GC rely on. + +### Notes about x86 (i686) support + +It used to be possible to create an x86 (32-bits) build on a x64 (64-bits) host +by passing `MICROPY_FORCE_32BIT=1` to `make`. That option was retired: x86 +usage has declined quite a bit in the past few years, and MicroPython now +supports at least one more mixed 32/64-bits target architecture for which +enabling `MICROPY_FORCE_32BIT` would make builds fail. + +x86 will be treated as a cross-compilation target from now on. This means you +will need to install a suitable compiler (on Ubuntu you can install either the +`gcc-i686-linux-gnu` and `g++-i686-linux-gnu` packages for GCC, or the `clang` +package for Clang, for example) and pass the appropriate command arguments to +`make` depending on which compiler you chose. + +### Building x86 (i686) code with GCC + +For GCC, you will need to pass the toolchain's command prefix to the +`CROSS_COMPILE` command line variable. + +This change is also extended to native modules, for which you may need to pass +the toolchain's command prefix to the `CROSS` command line variable if your +x86 compiler cannot be invoked with `i686-linux-gnu-gcc`. + +Or, as an example: + +```bash +$ printf "%s %s %s %s\n" $(lsb_release -d | cut -f 2) $(uname -m) +Ubuntu 24.04.4 LTS x86_64 + +$ i686-linux-gnu-gcc --version | head -n 1 +i686-linux-gnu-gcc (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0 + +$ CROSS_COMPILE=i686-linux-gnu- make -C ports/unix +make: Entering directory '/ports/unix' +Use make V=1 or set BUILD_VERBOSE in your environment to increase build verbosity. +... +LINK build-standard/micropython + text data bss dec hex filename + 723115 36104 2124 761343 b9dff build-standard/micropython +make: Leaving directory '/ports/unix' + +$ file -b ports/unix/build-standard/micropython | cut -d, -f-2 +ELF 32-bit LSB pie executable, Intel 80386 + +# `i686-linux-gnu-` is the default prefix for x86 native modules now, it has +# been explicitly mentioned here in case you want to see how to set it. + +$ make -C examples/natmod/features0 ARCH=x86 CROSS=i686-linux-gnu- +make: Entering directory '/examples/natmod/features0' +GEN build/features0.config.h +CC features0.c +LINK build/features0.o +arch: EM_386 +text size: 192 +bss size: 0 +GOT entries: 4 +GEN features0.mpy +make: Leaving directory '/examples/natmod/features0' + +$ cd examples/natmod/features0 && ../../../ports/unix/build-standard/micropython +MicroPython v1.29.0-preview.490.gb4c58f7ba5.dirty on 2026-07-04; linux [GCC 13.3.0] version +Type "help()" for more information. +>>> import features0 +>>> features0.factorial(10) +3628800 +``` + +### Building x86 (i686) code with Clang + +For Clang, you will need need to pass both the name of the compiler to invoke +as the `CC` command line variable and the extra command line arguments needed +to let Clang know you are building an i686 binary as the `CFLAGS_EXTRA` and +`LDFLAGS_EXTRA` command line variables (usually +`--target=i686-unknown-linux-gnu`). + +For native modules, since linking is not done by the compiler, only the `CC` +and `CFLAGS_EXTRA` arguments are needed. + +Or, as an example: + +```bash +$ printf "%s %s %s %s\n" $(lsb_release -d | cut -f 2) $(uname -m) +Ubuntu 24.04.4 LTS x86_64 + +$ clang --version | head -1 +Ubuntu clang version 18.1.3 (1ubuntu1) + +$ clang -print-targets | grep -i 32-bit.x86 + x86 - 32-bit X86: Pentium-Pro and above + +$ make -C ports/unix CC=clang CFLAGS_EXTRA="--target=i686-unknown-linux-gnu" LDFLAGS_EXTRA='--target=i686-unknown-linux-gnu' +make: Entering directory '/ports/unix' +Use make V=1 or set BUILD_VERBOSE in your environment to increase build verbosity. +... +LINK build-standard/micropython + text data bss dec hex filename + 836241 34748 2052 873041 d5251 build-standard/micropython +make: Leaving directory '/ports/unix' + +$ file -b ports/unix/build-standard/micropython | cut -d, -f-2 +ELF 32-bit LSB pie executable, Intel 80386 + +$ make -C examples/natmod/features0 ARCH=x86 CC=clang CFLAGS_EXTRA="--target=i686-unknown-linux-gnu" +make: Entering directory '/examples/natmod/features0' +GEN build-x86/features0.config.h +CC features0.c +LINK build-x86/features0.o +arch: EM_386 +text size: 180 +bss size: 0 +GOT entries: 2 +GEN features0.mpy +make: Leaving directory '/examples/natmod/features0' + +$ cd examples/natmod/features0 && ../../../ports/unix/build-standard/micropython +MicroPython v1.29.0-preview.490.gb4c58f7ba5.dirty on 2026-07-04; linux [Clang 18.1.3] version +Type "help()" for more information. +>>> import features0 +>>> features0.factorial(10) +3628800 +``` diff --git a/ports/unix/alloc.c b/ports/unix/alloc.c index e9cf521583d..7e1b261261e 100644 --- a/ports/unix/alloc.c +++ b/ports/unix/alloc.c @@ -31,9 +31,8 @@ #include #include "py/mpstate.h" -#include "py/gc.h" -#if MICROPY_EMIT_NATIVE || (MICROPY_PY_FFI && MICROPY_FORCE_PLAT_ALLOC_EXEC) +#if MICROPY_ENABLE_NATIVE_CODE #if defined(__OpenBSD__) || defined(__MACH__) #define MAP_ANONYMOUS MAP_ANON @@ -79,31 +78,6 @@ void mp_unix_free_exec(void *ptr, size_t size) { } } -void mp_unix_mark_exec(void) { - for (mmap_region_t *rg = MP_STATE_VM(mmap_region_head); rg != NULL; rg = rg->next) { - gc_collect_root(rg->ptr, rg->len / sizeof(mp_uint_t)); - } -} - -#if MICROPY_FORCE_PLAT_ALLOC_EXEC -// Provide implementation of libffi ffi_closure_* functions in terms -// of the functions above. On a normal Linux system, this save a lot -// of code size. -void *ffi_closure_alloc(size_t size, void **code); -void ffi_closure_free(void *ptr); - -void *ffi_closure_alloc(size_t size, void **code) { - size_t dummy; - mp_unix_alloc_exec(size, code, &dummy); - return *code; -} - -void ffi_closure_free(void *ptr) { - (void)ptr; - // TODO -} -#endif - MP_REGISTER_ROOT_POINTER(void *mmap_region_head); -#endif // MICROPY_EMIT_NATIVE || (MICROPY_PY_FFI && MICROPY_FORCE_PLAT_ALLOC_EXEC) +#endif // MICROPY_ENABLE_NATIVE_CODE diff --git a/ports/unix/coverage.c b/ports/unix/coverage.c index 4308ca6a1d2..b15bef1cabc 100644 --- a/ports/unix/coverage.c +++ b/ports/unix/coverage.c @@ -4,8 +4,10 @@ #include "py/obj.h" #include "py/objfun.h" +#include "py/objint.h" #include "py/objstr.h" #include "py/runtime.h" +#include "py/stackctrl.h" #include "py/gc.h" #include "py/repl.h" #include "py/mpz.h" @@ -95,6 +97,7 @@ static const mp_rom_map_elem_t rawfile_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) }, { MP_ROM_QSTR(MP_QSTR_write1), MP_ROM_PTR(&mp_stream_write1_obj) }, { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) }, + { MP_ROM_QSTR(MP_QSTR_readinto1), MP_ROM_PTR(&mp_stream_readinto1_obj) }, { MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj) }, { MP_ROM_QSTR(MP_QSTR_ioctl), MP_ROM_PTR(&mp_stream_ioctl_obj) }, }; @@ -169,19 +172,34 @@ static void pairheap_test(size_t nops, int *ops) { if (mp_pairheap_is_empty(pairheap_lt, heap)) { mp_printf(&mp_plat_print, " -"); } else { - mp_printf(&mp_plat_print, " %d", mp_pairheap_peek(pairheap_lt, heap) - &node[0]); + mp_printf(&mp_plat_print, " %d", (int)(mp_pairheap_peek(pairheap_lt, heap) - &node[0])); ; } } mp_printf(&mp_plat_print, "\npop all:"); while (!mp_pairheap_is_empty(pairheap_lt, heap)) { - mp_printf(&mp_plat_print, " %d", mp_pairheap_peek(pairheap_lt, heap) - &node[0]); + mp_printf(&mp_plat_print, " %d", (int)(mp_pairheap_peek(pairheap_lt, heap) - &node[0])); ; heap = mp_pairheap_pop(pairheap_lt, heap); } mp_printf(&mp_plat_print, "\n"); } +// CIRCUITPY-CHANGE: not turned on in CircuitPython +#if MICROPY_SCHEDULER_STATIC_NODES +static mp_sched_node_t mp_coverage_sched_node; +static bool coverage_sched_function_continue; + +static void coverage_sched_function(mp_sched_node_t *node) { + (void)node; + mp_printf(&mp_plat_print, "scheduled function\n"); + if (coverage_sched_function_continue) { + // Re-scheduling node will cause it to run again next time scheduled functions are run + mp_sched_schedule_node(&mp_coverage_sched_node, coverage_sched_function); + } +} +#endif + // function to run extra tests for things that can't be checked by scripts static mp_obj_t extra_coverage(void) { // mp_printf (used by ports that don't have a native printf) @@ -189,10 +207,22 @@ static mp_obj_t extra_coverage(void) { mp_printf(&mp_plat_print, "# mp_printf\n"); mp_printf(&mp_plat_print, "%d %+d % d\n", -123, 123, 123); // sign mp_printf(&mp_plat_print, "%05d\n", -123); // negative number with zero padding - mp_printf(&mp_plat_print, "%ld\n", 123); // long - mp_printf(&mp_plat_print, "%lx\n", 0x123); // long hex - mp_printf(&mp_plat_print, "%X\n", 0x1abcdef); // capital hex - mp_printf(&mp_plat_print, "%.2s %.3s '%4.4s' '%5.5q' '%.3q'\n", "abc", "abc", "abc", MP_QSTR_True, MP_QSTR_True); // fixed string precision + mp_printf(&mp_plat_print, "%ld\n", 123l); // long + mp_printf(&mp_plat_print, "%lx\n", 0x123fl); // long hex + mp_printf(&mp_plat_print, "%lX\n", 0x123fl); // capital long hex + if (sizeof(mp_int_t) == 8) { + mp_printf(&mp_plat_print, "%llx\n", LLONG_MAX); // long long hex + mp_printf(&mp_plat_print, "%llX\n", LLONG_MAX); // capital long long hex + mp_printf(&mp_plat_print, "%llu\n", ULLONG_MAX); // unsigned long long + } else { + // fake for platforms without narrower mp_int_t + mp_printf(&mp_plat_print, "7fffffffffffffff\n"); + mp_printf(&mp_plat_print, "7FFFFFFFFFFFFFFF\n"); + mp_printf(&mp_plat_print, "18446744073709551615\n"); + } + mp_printf(&mp_plat_print, "%p\n", (void *)0x789f); // pointer + mp_printf(&mp_plat_print, "%P\n", (void *)0x789f); // pointer uppercase + mp_printf(&mp_plat_print, "%.2s %.3s '%4.4s' '%5.5q' '%.3q'\n", "abc", "abc", "abc", (qstr)MP_QSTR_True, (qstr)MP_QSTR_True); // fixed string precision mp_printf(&mp_plat_print, "%.*s\n", -1, "abc"); // negative string precision mp_printf(&mp_plat_print, "%b %b\n", 0, 1); // bools #ifndef NDEBUG @@ -202,10 +232,36 @@ static mp_obj_t extra_coverage(void) { #endif mp_printf(&mp_plat_print, "%d\n", 0x80000000); // should print signed mp_printf(&mp_plat_print, "%u\n", 0x80000000); // should print unsigned - mp_printf(&mp_plat_print, "%x\n", 0x80000000); // should print unsigned - mp_printf(&mp_plat_print, "%X\n", 0x80000000); // should print unsigned - mp_printf(&mp_plat_print, "abc\n%"); // string ends in middle of format specifier + mp_printf(&mp_plat_print, "%x\n", 0x8000000f); // should print unsigned + mp_printf(&mp_plat_print, "%X\n", 0x8000000f); // should print unsigned + // note: storing the string in a variable is enough to prevent the + // format string checker from checking this format string. Otherwise, + // it would be a compile time diagnostic under the format string + // checker. + const char msg[] = "abc\n%"; + mp_printf(&mp_plat_print, msg); // string ends in middle of format specifier mp_printf(&mp_plat_print, "%%\n"); // literal % character + mp_printf(&mp_plat_print, ".%-3s.\n", "a"); // left adjust + + // Check that all kinds of mp_printf arguments are parsed out + // correctly, by having a char argument before and after each main type + // of value that can be formatted. + mp_printf(&mp_plat_print, "%c%%%c\n", '<', '>'); + mp_printf(&mp_plat_print, "%c%p%c\n", '<', (void *)0xaaaa, '>'); + mp_printf(&mp_plat_print, "%c%b%c\n", '<', true, '>'); + mp_printf(&mp_plat_print, "%c%d%c\n", '<', 0xaaaa, '>'); + mp_printf(&mp_plat_print, "%c%ld%c\n", '<', 0xaaaal, '>'); + mp_printf(&mp_plat_print, "%c" INT_FMT "%c\n", '<', (mp_int_t)0xaaaa, '>'); + mp_printf(&mp_plat_print, "%c%s%c\n", '<', "test", '>'); + mp_printf(&mp_plat_print, "%c%f%c\n", '<', MICROPY_FLOAT_CONST(1000.), '>'); + mp_printf(&mp_plat_print, "%c%q%c\n", '<', (qstr)MP_QSTR_True, '>'); + if (sizeof(mp_int_t) == 8) { + mp_printf(&mp_plat_print, "%c%lld%c\n", '<', LLONG_MAX, '>'); + } else { + mp_printf(&mp_plat_print, "<9223372036854775807>\n"); + } + + } // GC @@ -218,11 +274,33 @@ static mp_obj_t extra_coverage(void) { gc_unlock(); // using gc_realloc to resize to 0, which means free the memory - void *p = gc_alloc(4, false); + void *p = gc_alloc(4, 0); mp_printf(&mp_plat_print, "%p\n", gc_realloc(p, 0, false)); // calling gc_nbytes with a non-heap pointer - mp_printf(&mp_plat_print, "%p\n", gc_nbytes(NULL)); + mp_printf(&mp_plat_print, "%d\n", (int)gc_nbytes(NULL)); + + // test gc_info_fast + void *p0 = gc_alloc(4, 0); + void *p1 = gc_alloc(4, 0); + void *p2 = gc_alloc(4, 0); + + // Create a hole + gc_free(p1); + + gc_info_t info_slow; + gc_info_t info_fast; + + gc_info(&info_slow); + gc_info_fast(&info_fast); + + // Free allocs + gc_free(p0); + gc_free(p2); + + // Should be equal + mp_printf(&mp_plat_print, "%d\n", info_slow.used == info_fast.used); + mp_printf(&mp_plat_print, "%d\n", info_slow.free == info_fast.free); } // GC initialisation and allocation stress test, to check the logic behind ALLOC_TABLE_GAP_BYTE @@ -283,13 +361,20 @@ static mp_obj_t extra_coverage(void) { } ptrs[i][j] = j; } - mp_printf(&mp_plat_print, "%d %d\n", i, all_zero); + mp_printf(&mp_plat_print, "%d %d\n", (int)i, (int)all_zero); // hide the pointer from the GC and collect ptrs[i] = FLIP_POINTER(ptrs[i]); gc_collect(); } + // resize one of the blocks + void *before = ptrs[1]; + ptrs[1] = FLIP_POINTER(m_tracked_realloc(FLIP_POINTER(ptrs[1]), 2 * NUM_BYTES)); + void *after = ptrs[1]; + bool location_changed = before != after; + mp_printf(&mp_plat_print, "%d\n", location_changed); + // check the memory blocks have the correct content for (size_t i = 0; i < NUM_PTRS; ++i) { bool correct_contents = true; @@ -299,7 +384,7 @@ static mp_obj_t extra_coverage(void) { break; } } - mp_printf(&mp_plat_print, "%d %d\n", i, correct_contents); + mp_printf(&mp_plat_print, "%d %d\n", (int)i, (int)correct_contents); } // free the memory blocks @@ -308,6 +393,65 @@ static mp_obj_t extra_coverage(void) { } mp_printf(&mp_plat_print, "m_tracked_head = %p\n", MP_STATE_VM(m_tracked_head)); + + // Test realloc with black-box behavioral testing + mp_printf(&mp_plat_print, "# tracked realloc\n"); + + // Test 1: Basic realloc with data preservation + uint8_t *test_ptr = m_tracked_calloc(1, 32); + for (int i = 0; i < 32; i++) { + test_ptr[i] = i; + } + + test_ptr = m_tracked_realloc(test_ptr, 64); // Grow + bool data_preserved = (test_ptr[0] == 0 && test_ptr[31] == 31); + mp_printf(&mp_plat_print, "grow preserves data: %d\n", data_preserved); + + test_ptr = m_tracked_realloc(test_ptr, 16); // Shrink + bool shrink_ok = (test_ptr[0] == 0 && test_ptr[15] == 15); + mp_printf(&mp_plat_print, "shrink preserves data: %d\n", shrink_ok); + + m_tracked_free(test_ptr); + + // Test 2: Multiple allocations + reallocs + GC stability + uint8_t *realloc_ptrs[5]; + for (int i = 0; i < 5; i++) { + realloc_ptrs[i] = m_tracked_calloc(1, 32); + realloc_ptrs[i][0] = 'A' + i; // Mark each + } + + // Realloc some in different positions + realloc_ptrs[0] = m_tracked_realloc(realloc_ptrs[0], 64); // First allocated (tail of list) + realloc_ptrs[2] = m_tracked_realloc(realloc_ptrs[2], 64); // Middle + realloc_ptrs[4] = m_tracked_realloc(realloc_ptrs[4], 64); // Last allocated (head of list) + + // Run GC - if list corrupted, this might crash/fail + gc_collect(); + + // Verify markers intact + bool markers_ok = true; + for (int i = 0; i < 5; i++) { + if (realloc_ptrs[i][0] != 'A' + i) { + markers_ok = false; + break; + } + } + mp_printf(&mp_plat_print, "realloc gc stable: %d\n", markers_ok); + + // Cleanup + for (int i = 0; i < 5; i++) { + m_tracked_free(realloc_ptrs[i]); + } + + // Test 3: Edge cases + uint8_t *null_alloc = m_tracked_realloc(NULL, 32); + null_alloc[0] = 'X'; + mp_printf(&mp_plat_print, "realloc(NULL) ok: %d\n", null_alloc[0] == 'X'); + + void *free_result = m_tracked_realloc(null_alloc, 0); + mp_printf(&mp_plat_print, "realloc(ptr, 0) returns NULL: %d\n", free_result == NULL); + + mp_printf(&mp_plat_print, "m_tracked_head after cleanup: %p\n", MP_STATE_VM(m_tracked_head)); } // vstr @@ -388,7 +532,7 @@ static mp_obj_t extra_coverage(void) { mp_printf(&mp_plat_print, "# str\n"); // intern string - mp_printf(&mp_plat_print, "%d\n", mp_obj_is_qstr(mp_obj_str_intern(mp_obj_new_str("intern me", 9)))); + mp_printf(&mp_plat_print, "%d\n", mp_obj_is_qstr(mp_obj_str_intern(mp_obj_new_str_from_cstr("intern me")))); } // bytearray @@ -398,7 +542,7 @@ static mp_obj_t extra_coverage(void) { // create a bytearray via mp_obj_new_bytearray mp_buffer_info_t bufinfo; mp_get_buffer_raise(mp_obj_new_bytearray(4, "data"), &bufinfo, MP_BUFFER_RW); - mp_printf(&mp_plat_print, "%.*s\n", bufinfo.len, bufinfo.buf); + mp_printf(&mp_plat_print, "%.*s\n", (int)bufinfo.len, bufinfo.buf); } // mpz @@ -455,6 +599,84 @@ static mp_obj_t extra_coverage(void) { mpz_mul_inpl(&mpz, &mpz2, &mpz); mpz_as_uint_checked(&mpz, &value); mp_printf(&mp_plat_print, "%d\n", (int)value); + + // mpz_not_inpl with argument==0, testing ~0 + mpz_set_from_int(&mpz, 0); + mpz_not_inpl(&mpz, &mpz); + mp_int_t value_signed; + mpz_as_int_checked(&mpz, &value_signed); + mp_printf(&mp_plat_print, "%d\n", (int)value_signed); + + // hash the zero mpz integer + mpz_set_from_int(&mpz, 0); + mp_printf(&mp_plat_print, "%d\n", (int)mpz_hash(&mpz)); + + // convert the mpz zero integer to int + mp_printf(&mp_plat_print, "%d\n", mpz_as_int_checked(&mpz, &value_signed)); + mp_printf(&mp_plat_print, "%d\n", (int)value_signed); + + // mpz_set_from_float with 0 as argument + mpz_set_from_float(&mpz, 0); + mp_printf(&mp_plat_print, "%f\n", mpz_as_float(&mpz)); + + // convert a large integer value (stored in a mpz) to mp_uint_t and to ll; + mp_obj_t obj_bigint = mp_obj_new_int_from_uint((mp_uint_t)0xdeadbeef); + mp_printf(&mp_plat_print, "%x\n", (int)mp_obj_get_uint(obj_bigint)); + obj_bigint = mp_obj_new_int_from_ll(0xc0ffee777c0ffeell); + long long value_ll = mp_obj_get_ll(obj_bigint); + mp_printf(&mp_plat_print, "%x%08x\n", (uint32_t)(value_ll >> 32), (uint32_t)value_ll); + + // convert a large integer value (stored via a struct object) to uint and to ll + // `deadbeef` global is an uctypes.struct defined by extra_coverage.py + obj_bigint = mp_load_global(MP_QSTR_deadbeef); + mp_printf(&mp_plat_print, "%x\n", (int)mp_obj_get_uint(obj_bigint)); + value_ll = mp_obj_get_ll(obj_bigint); + mp_printf(&mp_plat_print, "%x%08x\n", (uint32_t)(value_ll >> 32), (uint32_t)value_ll); + + // convert a smaller integer value to mp_uint_t and to ll + obj_bigint = mp_obj_new_int_from_uint(0xc0ffee); + mp_printf(&mp_plat_print, "%x\n", (int)mp_obj_get_uint(obj_bigint)); + value_ll = mp_obj_get_ll(obj_bigint); + mp_printf(&mp_plat_print, "%x%08x\n", (uint32_t)(value_ll >> 32), (uint32_t)value_ll); + } + + // list argument helpers + { + mp_printf(&mp_plat_print, "# list argument helpers\n"); + + // Create a list to test with + mp_obj_t list_items[] = { mp_const_none, MP_OBJ_NEW_SMALL_INT(77), mp_obj_new_str_from_cstr("hello") }; + size_t list_len = MP_ARRAY_SIZE(list_items); + mp_obj_t list = mp_obj_new_list(list_len, list_items); + + // mp_obj_list_ensure + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + mp_obj_list_ensure(MP_OBJ_NEW_SMALL_INT(-1), 5); // Not a list + nlr_pop(); + } else { + mp_obj_print_exception(&mp_plat_print, MP_OBJ_FROM_PTR(nlr.ret_val)); + } + + if (nlr_push(&nlr) == 0) { + mp_obj_list_ensure(list, list_len + 2); // List shorter than minimum length + nlr_pop(); + } else { + mp_obj_print_exception(&mp_plat_print, MP_OBJ_FROM_PTR(nlr.ret_val)); + } + + mp_obj_list_t *as_ptr = mp_obj_list_ensure(list, list_len); // Acceptable! + mp_printf(&mp_plat_print, "mp_obj_list_ensure same list? %d\n", MP_OBJ_TO_PTR(list) == as_ptr); + + // mp_obj_list_optional_arg() + as_ptr = mp_obj_list_optional_arg(list, list_len); + mp_printf(&mp_plat_print, "mp_obj_list_optional_arg same list? %d\n", MP_OBJ_TO_PTR(list) == as_ptr); + + as_ptr = mp_obj_list_optional_arg(mp_const_none, list_len); + mp_printf(&mp_plat_print, "mp_obj_list_optional_arg new list len " SIZE_FMT "\n", as_ptr->len); + + as_ptr = mp_obj_list_optional_arg(MP_OBJ_NULL, list_len); + mp_printf(&mp_plat_print, "mp_obj_list_optional_arg new list from NULL len " SIZE_FMT "\n", as_ptr->len); } // runtime utils @@ -464,12 +686,15 @@ static mp_obj_t extra_coverage(void) { // call mp_call_function_1_protected mp_call_function_1_protected(MP_OBJ_FROM_PTR(&mp_builtin_abs_obj), MP_OBJ_NEW_SMALL_INT(1)); // call mp_call_function_1_protected with invalid args - mp_call_function_1_protected(MP_OBJ_FROM_PTR(&mp_builtin_abs_obj), mp_obj_new_str("abc", 3)); + mp_call_function_1_protected(MP_OBJ_FROM_PTR(&mp_builtin_abs_obj), mp_obj_new_str_from_cstr("abc")); // call mp_call_function_2_protected mp_call_function_2_protected(MP_OBJ_FROM_PTR(&mp_builtin_divmod_obj), MP_OBJ_NEW_SMALL_INT(1), MP_OBJ_NEW_SMALL_INT(1)); // call mp_call_function_2_protected with invalid args - mp_call_function_2_protected(MP_OBJ_FROM_PTR(&mp_builtin_divmod_obj), mp_obj_new_str("abc", 3), mp_obj_new_str("abc", 3)); + mp_call_function_2_protected(MP_OBJ_FROM_PTR(&mp_builtin_divmod_obj), mp_obj_new_str_from_cstr("abc"), mp_obj_new_str_from_cstr("abc")); + + // mp_obj_int_get_checked with mp_obj_int_t that has a value that is a small integer + mp_printf(&mp_plat_print, "%d\n", (int)mp_obj_int_get_checked(MP_OBJ_FROM_PTR(mp_obj_int_new_mpz()))); // mp_obj_int_get_uint_checked with non-negative small-int mp_printf(&mp_plat_print, "%d\n", (int)mp_obj_int_get_uint_checked(MP_OBJ_NEW_SMALL_INT(1))); @@ -494,6 +719,22 @@ static mp_obj_t extra_coverage(void) { mp_obj_print_exception(&mp_plat_print, MP_OBJ_FROM_PTR(nlr.ret_val)); } + // mp_obj_get_uint from a non-int object (should raise exception) + if (nlr_push(&nlr) == 0) { + mp_obj_get_uint(mp_const_none); + nlr_pop(); + } else { + mp_obj_print_exception(&mp_plat_print, MP_OBJ_FROM_PTR(nlr.ret_val)); + } + + // mp_obj_int_get_ll from a non-int object (should raise exception) + if (nlr_push(&nlr) == 0) { + mp_obj_get_ll(mp_const_none); + nlr_pop(); + } else { + mp_obj_print_exception(&mp_plat_print, MP_OBJ_FROM_PTR(nlr.ret_val)); + } + // call mp_obj_new_exception_args (it's a part of the public C API and not used in the core) mp_obj_print_exception(&mp_plat_print, mp_obj_new_exception_args(&mp_type_ValueError, 0, NULL)); } @@ -503,39 +744,6 @@ static mp_obj_t extra_coverage(void) { mp_emitter_warning(MP_PASS_CODE_SIZE, "test"); } - // format float - { - mp_printf(&mp_plat_print, "# format float\n"); - - // format with inadequate buffer size - char buf[5]; - mp_format_float(1, buf, sizeof(buf), 'g', 0, '+'); - mp_printf(&mp_plat_print, "%s\n", buf); - - // format with just enough buffer so that precision must be - // set from 0 to 1 twice - char buf2[8]; - mp_format_float(1, buf2, sizeof(buf2), 'g', 0, '+'); - mp_printf(&mp_plat_print, "%s\n", buf2); - - // format where precision is trimmed to avoid buffer overflow - mp_format_float(1, buf2, sizeof(buf2), 'e', 0, '+'); - mp_printf(&mp_plat_print, "%s\n", buf2); - } - - // binary - { - mp_printf(&mp_plat_print, "# binary\n"); - - // call function with float and double typecodes - float far[1]; - double dar[1]; - mp_binary_set_val_array_from_int('f', far, 0, 123); - mp_printf(&mp_plat_print, "%.0f\n", (double)far[0]); - mp_binary_set_val_array_from_int('d', dar, 0, 456); - mp_printf(&mp_plat_print, "%.0lf\n", dar[0]); - } - // VM { mp_printf(&mp_plat_print, "# VM\n"); @@ -546,14 +754,26 @@ static mp_obj_t extra_coverage(void) { fun_bc.context = &context; fun_bc.child_table = NULL; fun_bc.bytecode = (const byte *)"\x01"; // just needed for n_state + #if MICROPY_PY_SYS_SETTRACE + struct _mp_raw_code_t rc = {}; + fun_bc.rc = &rc; + #endif mp_code_state_t *code_state = m_new_obj_var(mp_code_state_t, state, mp_obj_t, 1); code_state->fun_bc = &fun_bc; code_state->ip = (const byte *)"\x00"; // just needed for an invalid opcode code_state->sp = &code_state->state[0]; code_state->exc_sp_idx = 0; code_state->old_globals = NULL; + #if MICROPY_STACKLESS + code_state->prev = NULL; + #endif + #if MICROPY_PY_SYS_SETTRACE + code_state->prev_state = NULL; + code_state->frame = NULL; + #endif + mp_vm_return_kind_t ret = mp_execute_bytecode(code_state, MP_OBJ_NULL); - mp_printf(&mp_plat_print, "%d %d\n", ret, mp_obj_get_type(code_state->state[0]) == &mp_type_NotImplementedError); + mp_printf(&mp_plat_print, "%d %d\n", (int)ret, mp_obj_get_type(code_state->state[0]) == &mp_type_NotImplementedError); } // scheduler @@ -610,9 +830,25 @@ static mp_obj_t extra_coverage(void) { mp_obj_print_exception(&mp_plat_print, MP_OBJ_FROM_PTR(nlr.ret_val)); } mp_handle_pending(true); + + // CIRCUITPY-CHANGE: not turned on in CircuitPython + #if MICROPY_SCHEDULER_STATIC_NODES + coverage_sched_function_continue = true; + mp_sched_schedule_node(&mp_coverage_sched_node, coverage_sched_function); + for (int i = 0; i < 3; ++i) { + mp_printf(&mp_plat_print, "loop\n"); + mp_handle_pending(true); + } + // Clear this flag to prevent the function scheduling itself again + coverage_sched_function_continue = false; + // Will only run the first time through this loop, then not scheduled again + for (int i = 0; i < 3; ++i) { + mp_handle_pending(true); + } + #endif } - // CIRCUITPY-CHANGE: ringbuf is different + // CIRCUITPY-CHANGE: ringbuf is quite different // ringbuf { #define RINGBUF_SIZE 99 @@ -624,36 +860,36 @@ static mp_obj_t extra_coverage(void) { mp_printf(&mp_plat_print, "# ringbuf\n"); // Single-byte put/get with empty ringbuf. - mp_printf(&mp_plat_print, "%d %d\n", ringbuf_num_empty(&ringbuf), ringbuf_num_filled(&ringbuf)); + mp_printf(&mp_plat_print, "%d %d\n", (int)ringbuf_num_empty(&ringbuf), (int)ringbuf_num_filled(&ringbuf)); ringbuf_put(&ringbuf, 22); - mp_printf(&mp_plat_print, "%d %d\n", ringbuf_num_empty(&ringbuf), ringbuf_num_filled(&ringbuf)); + mp_printf(&mp_plat_print, "%d %d\n", (int)ringbuf_num_empty(&ringbuf), (int)ringbuf_num_filled(&ringbuf)); mp_printf(&mp_plat_print, "%d\n", ringbuf_get(&ringbuf)); - mp_printf(&mp_plat_print, "%d %d\n", ringbuf_num_empty(&ringbuf), ringbuf_num_filled(&ringbuf)); + mp_printf(&mp_plat_print, "%d %d\n", (int)ringbuf_num_empty(&ringbuf), (int)ringbuf_num_filled(&ringbuf)); // Two-byte put/get with empty ringbuf. ringbuf_put16(&ringbuf, 0xaa55); - mp_printf(&mp_plat_print, "%d %d\n", ringbuf_num_empty(&ringbuf), ringbuf_num_filled(&ringbuf)); + mp_printf(&mp_plat_print, "%d %d\n", (int)ringbuf_num_empty(&ringbuf), (int)ringbuf_num_filled(&ringbuf)); mp_printf(&mp_plat_print, "%04x\n", ringbuf_get16(&ringbuf)); - mp_printf(&mp_plat_print, "%d %d\n", ringbuf_num_empty(&ringbuf), ringbuf_num_filled(&ringbuf)); + mp_printf(&mp_plat_print, "%d %d\n", (int)ringbuf_num_empty(&ringbuf), (int)ringbuf_num_filled(&ringbuf)); // Two-byte put with full ringbuf. for (int i = 0; i < RINGBUF_SIZE; ++i) { ringbuf_put(&ringbuf, i); } - mp_printf(&mp_plat_print, "%d %d\n", ringbuf_num_empty(&ringbuf), ringbuf_num_filled(&ringbuf)); + mp_printf(&mp_plat_print, "%d %d\n", (int)ringbuf_num_empty(&ringbuf), (int)ringbuf_num_filled(&ringbuf)); mp_printf(&mp_plat_print, "%d\n", ringbuf_put16(&ringbuf, 0x11bb)); // Two-byte put with one byte free. ringbuf_get(&ringbuf); - mp_printf(&mp_plat_print, "%d %d\n", ringbuf_num_empty(&ringbuf), ringbuf_num_filled(&ringbuf)); + mp_printf(&mp_plat_print, "%d %d\n", (int)ringbuf_num_empty(&ringbuf), (int)ringbuf_num_filled(&ringbuf)); mp_printf(&mp_plat_print, "%d\n", ringbuf_put16(&ringbuf, 0x3377)); ringbuf_get(&ringbuf); - mp_printf(&mp_plat_print, "%d %d\n", ringbuf_num_empty(&ringbuf), ringbuf_num_filled(&ringbuf)); + mp_printf(&mp_plat_print, "%d %d\n", (int)ringbuf_num_empty(&ringbuf), (int)ringbuf_num_filled(&ringbuf)); mp_printf(&mp_plat_print, "%d\n", ringbuf_put16(&ringbuf, 0xcc99)); for (int i = 0; i < RINGBUF_SIZE - 2; ++i) { ringbuf_get(&ringbuf); } mp_printf(&mp_plat_print, "%04x\n", ringbuf_get16(&ringbuf)); - mp_printf(&mp_plat_print, "%d %d\n", ringbuf_num_empty(&ringbuf), ringbuf_num_filled(&ringbuf)); + mp_printf(&mp_plat_print, "%d %d\n", (int)ringbuf_num_empty(&ringbuf), (int)ringbuf_num_filled(&ringbuf)); // Two-byte put with wrap around on first byte: ringbuf_clear(&ringbuf); @@ -681,6 +917,35 @@ static mp_obj_t extra_coverage(void) { ringbuf_clear(&ringbuf); ringbuf_put(&ringbuf, 0xaa); mp_printf(&mp_plat_print, "%d\n", ringbuf_get16(&ringbuf)); + + // Multi-byte put/get that wrap around, and discard. + { + byte data[RINGBUF_SIZE + 1]; + byte out[RINGBUF_SIZE + 1]; + for (int i = 0; i < RINGBUF_SIZE + 1; ++i) { + data[i] = i; + } + ringbuf_clear(&ringbuf); + for (int i = 0; i < RINGBUF_SIZE - 10; ++i) { + ringbuf_put(&ringbuf, i); + ringbuf_get(&ringbuf); + } + // 20 bytes from 10 before the end: wraps. + mp_printf(&mp_plat_print, "%d\n", (int)ringbuf_put_n(&ringbuf, data, 20)); + mp_printf(&mp_plat_print, "%d %d\n", (int)ringbuf_num_empty(&ringbuf), (int)ringbuf_num_filled(&ringbuf)); + // Only what fits. + mp_printf(&mp_plat_print, "%d\n", (int)ringbuf_put_n(&ringbuf, data + 20, RINGBUF_SIZE + 1 - 20)); + mp_printf(&mp_plat_print, "%d %d\n", (int)ringbuf_num_empty(&ringbuf), (int)ringbuf_num_filled(&ringbuf)); + mp_printf(&mp_plat_print, "%d\n", (int)ringbuf_put_n(&ringbuf, data, 1)); + // Discard 5, then get what is left, which wraps. + mp_printf(&mp_plat_print, "%d\n", (int)ringbuf_discard_n(&ringbuf, 5)); + mp_printf(&mp_plat_print, "%d\n", (int)ringbuf_get_n(&ringbuf, out, sizeof(out))); + mp_printf(&mp_plat_print, "%d\n", memcmp(out, data + 5, RINGBUF_SIZE - 5) == 0); + mp_printf(&mp_plat_print, "%d %d\n", (int)ringbuf_num_empty(&ringbuf), (int)ringbuf_num_filled(&ringbuf)); + // Nothing to get or discard. + mp_printf(&mp_plat_print, "%d\n", (int)ringbuf_get_n(&ringbuf, out, 1)); + mp_printf(&mp_plat_print, "%d\n", (int)ringbuf_discard_n(&ringbuf, 1)); + } } // pairheap @@ -723,12 +988,38 @@ static mp_obj_t extra_coverage(void) { // mp_obj_is_integer accepts ints and booleans mp_printf(&mp_plat_print, "%d %d\n", mp_obj_is_integer(MP_OBJ_NEW_SMALL_INT(1)), mp_obj_is_integer(mp_obj_new_int_from_ll(1))); mp_printf(&mp_plat_print, "%d %d\n", mp_obj_is_integer(mp_const_true), mp_obj_is_integer(mp_const_false)); - mp_printf(&mp_plat_print, "%d %d\n", mp_obj_is_integer(mp_obj_new_str("1", 1)), mp_obj_is_integer(mp_const_none)); + mp_printf(&mp_plat_print, "%d %d\n", mp_obj_is_integer(mp_obj_new_str_from_cstr("1")), mp_obj_is_integer(mp_const_none)); // mp_obj_is_int accepts small int and object ints mp_printf(&mp_plat_print, "%d %d\n", mp_obj_is_int(MP_OBJ_NEW_SMALL_INT(1)), mp_obj_is_int(mp_obj_new_int_from_ll(1))); } + // Legacy stackctrl.h API, this has been replaced by cstack.h + { + mp_printf(&mp_plat_print, "# stackctrl\n"); + char *old_stack_top = MP_STATE_THREAD(stack_top); + size_t old_stack_limit = 0; + size_t new_stack_limit = SIZE_MAX; + #if MICROPY_STACK_CHECK + old_stack_limit = MP_STATE_THREAD(stack_limit); + MP_STACK_CHECK(); + #endif + + mp_stack_ctrl_init(); // Will set stack top incorrectly + mp_stack_set_top(old_stack_top); // ... and restore it + + #if MICROPY_STACK_CHECK + mp_stack_set_limit(MP_STATE_THREAD(stack_limit)); + MP_STACK_CHECK(); + new_stack_limit = MP_STATE_THREAD(stack_limit); + #endif + + // Nothing should have changed + mp_printf(&mp_plat_print, "%d %d\n", + old_stack_top == MP_STATE_THREAD(stack_top), + MICROPY_STACK_CHECK == 0 || old_stack_limit == new_stack_limit); + } + mp_printf(&mp_plat_print, "# end coverage.c\n"); mp_obj_streamtest_t *s = mp_obj_malloc(mp_obj_streamtest_t, &mp_type_stest_fileio); @@ -739,7 +1030,7 @@ static mp_obj_t extra_coverage(void) { mp_obj_streamtest_t *s2 = mp_obj_malloc(mp_obj_streamtest_t, &mp_type_stest_textio2); // return a tuple of data for testing on the Python side - mp_obj_t items[] = {(mp_obj_t)&str_no_hash_obj, (mp_obj_t)&bytes_no_hash_obj, MP_OBJ_FROM_PTR(s), MP_OBJ_FROM_PTR(s2)}; + mp_obj_t items[] = {MP_OBJ_FROM_PTR(&str_no_hash_obj), MP_OBJ_FROM_PTR(&bytes_no_hash_obj), MP_OBJ_FROM_PTR(s), MP_OBJ_FROM_PTR(s2)}; return mp_obj_new_tuple(MP_ARRAY_SIZE(items), items); } MP_DEFINE_CONST_FUN_OBJ_0(extra_coverage_obj, extra_coverage); diff --git a/ports/unix/coveragecpp.cpp b/ports/unix/coveragecpp.cpp index 93c1b387fe2..8ba308f6468 100644 --- a/ports/unix/coveragecpp.cpp +++ b/ports/unix/coveragecpp.cpp @@ -1,11 +1,77 @@ extern "C" { -#include "py/obj.h" +// Include the complete public API to verify everything compiles as C++. +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include } +// Invoke all (except one, see below) public API macros which initialize structs to make sure +// they are C++-compatible, meaning they explicitly initialize all struct members. +mp_obj_t f0(); +MP_DEFINE_CONST_FUN_OBJ_0(f0_obj, f0); +mp_obj_t f1(mp_obj_t); +MP_DEFINE_CONST_FUN_OBJ_1(f1_obj, f1); +mp_obj_t f2(mp_obj_t, mp_obj_t); +MP_DEFINE_CONST_FUN_OBJ_2(f2_obj, f2); +mp_obj_t f3(mp_obj_t, mp_obj_t, mp_obj_t); +MP_DEFINE_CONST_FUN_OBJ_3(f3_obj, f3); +mp_obj_t fvar(size_t, const mp_obj_t *); +MP_DEFINE_CONST_FUN_OBJ_VAR(fvar_obj, 1, fvar); +mp_obj_t fvarbetween(size_t, const mp_obj_t *); +MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(fvarbetween_obj, 1, 2, fvarbetween); +mp_obj_t fkw(size_t, const mp_obj_t *, mp_map_t *); +MP_DEFINE_CONST_FUN_OBJ_KW(fkw_obj, 1, fkw); + +static const mp_rom_map_elem_t table[] = { + { MP_ROM_QSTR(MP_QSTR_f0), MP_ROM_PTR(&f0_obj) }, +}; +MP_DEFINE_CONST_MAP(map, table); +MP_DEFINE_CONST_DICT(dict, table); + +static const qstr attrtuple_fields[] = { + MP_QSTR_f0, +}; +MP_DEFINE_ATTRTUPLE(attrtuple, attrtuple_fields, 1, MP_ROM_PTR(&f0_obj)); + +void nlr_cb(void *); +void nlr_cb(void *){ +} + +// The MP_DEFINE_CONST_OBJ_TYPE macro is not C++-compatible because each of the +// MP_DEFINE_CONST_OBJ_TYPE_NARGS_X macros only initializes some of _mp_obj_type_t's +// .slot_index_xxx members but that cannot be fixed to be done in a deterministic way. + + #if defined(MICROPY_UNIX_COVERAGE) // Just to test building of C++ code. static mp_obj_t extra_cpp_coverage_impl() { + MP_DEFINE_NLR_JUMP_CALLBACK_FUNCTION_1(ctx, nlr_cb, (void *) nlr_cb); + + // To avoid 'error: unused variable [-Werror,-Wunused-const-variable]'. + (void) ctx; + (void) f0_obj; + (void) f1_obj; + (void) f2_obj; + (void) f3_obj; + (void) fvar_obj; + (void) fvarbetween_obj; + (void) fkw_obj; + (void) map; + (void) dict; + (void) attrtuple; return mp_const_none; } diff --git a/ports/unix/displayio_min.c b/ports/unix/displayio_min.c index 06b57d04df2..cb8a083b3ef 100644 --- a/ports/unix/displayio_min.c +++ b/ports/unix/displayio_min.c @@ -23,6 +23,7 @@ MAKE_ENUM_VALUE(displayio_colorspace_type, displayio_colorspace, BGR565_SWAPPED, MAKE_ENUM_VALUE(displayio_colorspace_type, displayio_colorspace, BGR555, DISPLAYIO_COLORSPACE_BGR555); MAKE_ENUM_VALUE(displayio_colorspace_type, displayio_colorspace, BGR555_SWAPPED, DISPLAYIO_COLORSPACE_BGR555_SWAPPED); MAKE_ENUM_VALUE(displayio_colorspace_type, displayio_colorspace, L8, DISPLAYIO_COLORSPACE_L8); +MAKE_ENUM_VALUE(displayio_colorspace_type, displayio_colorspace, L1, DISPLAYIO_COLORSPACE_L1); //| class Colorspace: //| """The colorspace for a `ColorConverter` to operate in""" @@ -53,6 +54,7 @@ MAKE_ENUM_MAP(displayio_colorspace) { MAKE_ENUM_MAP_ENTRY(displayio_colorspace, BGR555), MAKE_ENUM_MAP_ENTRY(displayio_colorspace, BGR555_SWAPPED), MAKE_ENUM_MAP_ENTRY(displayio_colorspace, L8), + MAKE_ENUM_MAP_ENTRY(displayio_colorspace, L1), }; static MP_DEFINE_CONST_DICT(displayio_colorspace_locals_dict, displayio_colorspace_locals_table); @@ -74,16 +76,3 @@ const mp_obj_module_t displayio_module = { }; MP_REGISTER_MODULE(MP_QSTR_displayio, displayio_module); - -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 -}; diff --git a/ports/unix/gccollect.c b/ports/unix/gccollect.c index 94c9c61ea4d..8f0f5a6769d 100644 --- a/ports/unix/gccollect.c +++ b/ports/unix/gccollect.c @@ -39,9 +39,6 @@ void gc_collect(void) { #if MICROPY_PY_THREAD mp_thread_gc_others(); #endif - #if MICROPY_EMIT_NATIVE - mp_unix_mark_exec(); - #endif gc_collect_end(); } diff --git a/ports/unix/input.c b/ports/unix/input.c index 31926a5a8e1..260e9eac8c9 100644 --- a/ports/unix/input.c +++ b/ports/unix/input.c @@ -104,6 +104,9 @@ void prompt_write_history(void) { #if MICROPY_USE_READLINE == 1 char *home = getenv("HOME"); if (home != NULL) { + if (MP_STATE_THREAD(gc_lock_depth) != 0) { + return; + } vstr_t vstr; vstr_init(&vstr, 50); vstr_printf(&vstr, "%s/.micropython.history", home); diff --git a/ports/unix/main.c b/ports/unix/main.c index 28521c12514..caaf020ccbb 100644 --- a/ports/unix/main.c +++ b/ports/unix/main.c @@ -44,7 +44,8 @@ #include "py/repl.h" #include "py/gc.h" #include "py/objstr.h" -#include "py/stackctrl.h" +#include "py/cstack.h" +#include "py/mperrno.h" #include "py/mphal.h" #include "py/mpthread.h" #include "extmod/misc.h" @@ -53,38 +54,11 @@ #include "extmod/vfs_posix.h" #include "genhdr/mpversion.h" #include "input.h" - -// CIRCUITPY-CHANGE -#if defined(MICROPY_UNIX_COVERAGE) -#include "py/objstr.h" -typedef int os_getenv_err_t; -mp_obj_t common_hal_os_getenv(const char *key, mp_obj_t default_); -os_getenv_err_t common_hal_os_getenv_str(const char *key, char *value, size_t value_len); -os_getenv_err_t common_hal_os_getenv_int(const char *key, mp_int_t *value); - -static mp_obj_t mod_os_getenv_int(mp_obj_t var_in) { - mp_int_t value; - os_getenv_err_t result = common_hal_os_getenv_int(mp_obj_str_get_str(var_in), &value); - if (result == 0) { - return mp_obj_new_int(value); - } - return mp_const_none; -} -MP_DEFINE_CONST_FUN_OBJ_1(mod_os_getenv_int_obj, mod_os_getenv_int); - -static mp_obj_t mod_os_getenv_str(mp_obj_t var_in) { - char buf[4096]; - os_getenv_err_t result = common_hal_os_getenv_str(mp_obj_str_get_str(var_in), buf, sizeof(buf)); - if (result == 0) { - return mp_obj_new_str_copy(&mp_type_str, (byte *)buf, strlen(buf)); - } - return mp_const_none; -} -MP_DEFINE_CONST_FUN_OBJ_1(mod_os_getenv_str_obj, mod_os_getenv_str); -#endif +#include "stack_size.h" +#include "shared/runtime/pyexec.h" // Command line options, with their defaults -static bool compile_only = false; +bool mp_compile_only = false; static uint emit_opt = MP_EMIT_OPT_NONE; #if MICROPY_ENABLE_GC @@ -98,6 +72,33 @@ long heap_size = 1024 * 1024 * (sizeof(mp_uint_t) / 4); #define MICROPY_GC_SPLIT_HEAP_N_HEAPS (1) #endif +// CIRCUITPY-CHANGE: let the collector add and free heaps, as it does on the boards +#if MICROPY_GC_SPLIT_HEAP_AUTO +// The heap starts with one of the MICROPY_GC_SPLIT_HEAP_N_HEAPS parts of heap_size and the +// collector adds the others when it needs them, so the total stays the same. +static size_t heaps_added; + +size_t gc_get_max_new_split(void) { + if (heaps_added < MICROPY_GC_SPLIT_HEAP_N_HEAPS - 1) { + return heap_size / MICROPY_GC_SPLIT_HEAP_N_HEAPS; + } + return 0; +} + +void *unix_alloc_heap(size_t size) { + void *heap = malloc(size); + if (heap != NULL) { + heaps_added++; + } + return heap; +} + +void unix_free_heap(void *heap) { + heaps_added--; + free(heap); +} +#endif + #if !MICROPY_PY_SYS_PATH #error "The unix port requires MICROPY_PY_SYS_PATH=1" #endif @@ -118,7 +119,8 @@ static void stderr_print_strn(void *env, const char *str, size_t len) { const mp_print_t mp_stderr_print = {NULL, stderr_print_strn}; -#define FORCED_EXIT (0x100) +// CIRCUITPY-CHANGE: be consistent about using PYEXEC_FORCED_EXIT +// #define FORCED_EXIT (0x100) // If exc is SystemExit, return value where FORCED_EXIT bit set, // and lower 8 bits are SystemExit value. For all other exceptions, // return 1. @@ -131,7 +133,8 @@ static int handle_uncaught_exception(mp_obj_base_t *exc) { if (exit_val != mp_const_none && !mp_obj_get_int_maybe(exit_val, &val)) { val = 1; } - return FORCED_EXIT | (val & 255); + // CIRCUITPY-CHANGE: be consistent about using PYEXEC_FORCED_EXIT + return PYEXEC_FORCED_EXIT | (val & 255); } // Report all other exceptions @@ -140,8 +143,6 @@ static int handle_uncaught_exception(mp_obj_base_t *exc) { } #define LEX_SRC_STR (1) -#define LEX_SRC_VSTR (2) -#define LEX_SRC_FILENAME (3) #define LEX_SRC_STDIN (4) // Returns standard error codes: 0 for success, 1 for all other errors, @@ -157,19 +158,13 @@ static int execute_from_lexer(int source_kind, const void *source, mp_parse_inpu if (source_kind == LEX_SRC_STR) { const char *line = source; lex = mp_lexer_new_from_str_len(MP_QSTR__lt_stdin_gt_, line, strlen(line), false); - } else if (source_kind == LEX_SRC_VSTR) { - 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) { - const char *filename = (const char *)source; - lex = mp_lexer_new_from_file(qstr_from_str(filename)); } else { // LEX_SRC_STDIN lex = mp_lexer_new_from_fd(MP_QSTR__lt_stdin_gt_, 0, false); } qstr source_name = lex->source_name; - #if MICROPY_PY___FILE__ + #if MICROPY_MODULE___FILE__ if (input_kind == MP_PARSE_FILE_INPUT) { mp_store_global(MP_QSTR___file__, MP_OBJ_NEW_QSTR(source_name)); } @@ -179,7 +174,7 @@ static int execute_from_lexer(int source_kind, const void *source, mp_parse_inpu #if defined(MICROPY_UNIX_COVERAGE) // allow to print the parse tree in the coverage build - if (mp_verbose_flag >= 3) { + if (MP_STATE_VM(mp_verbose_flag) >= 3) { printf("----------------\n"); mp_parse_node_print(&mp_plat_print, parse_tree.root, 0); printf("----------------\n"); @@ -188,7 +183,7 @@ static int execute_from_lexer(int source_kind, const void *source, mp_parse_inpu mp_obj_t module_fun = mp_compile(&parse_tree, source_name, is_repl); - if (!compile_only) { + if (!mp_compile_only) { // execute it mp_call_function_0(module_fun); } @@ -225,92 +220,32 @@ static char *strjoin(const char *s1, int sep_char, const char *s2) { #endif static int do_repl(void) { - mp_hal_stdout_tx_str(MICROPY_BANNER_NAME_AND_VERSION); - mp_hal_stdout_tx_str("; " MICROPY_BANNER_MACHINE); - mp_hal_stdout_tx_str("\nUse Ctrl-D to exit, Ctrl-E for paste mode\n"); - #if MICROPY_USE_READLINE == 1 - // use MicroPython supplied readline + // use MicroPython supplied readline-based REPL - vstr_t line; - vstr_init(&line, 16); + int ret = 0; for (;;) { - mp_hal_stdio_mode_raw(); - - input_restart: - vstr_reset(&line); - int ret = readline(&line, mp_repl_get_ps1()); - mp_parse_input_kind_t parse_input_kind = MP_PARSE_SINGLE_INPUT; - - if (ret == CHAR_CTRL_C) { - // cancel input - mp_hal_stdout_tx_str("\r\n"); - goto input_restart; - } else if (ret == CHAR_CTRL_D) { - // EOF - printf("\n"); - mp_hal_stdio_mode_orig(); - vstr_clear(&line); - return 0; - } else if (ret == CHAR_CTRL_E) { - // paste mode - mp_hal_stdout_tx_str("\npaste mode; Ctrl-C to cancel, Ctrl-D to finish\n=== "); - vstr_reset(&line); - for (;;) { - char c = mp_hal_stdin_rx_chr(); - if (c == CHAR_CTRL_C) { - // cancel everything - mp_hal_stdout_tx_str("\n"); - goto input_restart; - } else if (c == CHAR_CTRL_D) { - // end of input - mp_hal_stdout_tx_str("\n"); - break; - } else { - // add char to buffer and echo - vstr_add_byte(&line, c); - if (c == '\r') { - mp_hal_stdout_tx_str("\n=== "); - } else { - mp_hal_stdout_tx_strn(&c, 1); - } - } - } - parse_input_kind = MP_PARSE_FILE_INPUT; - } else if (line.len == 0) { - if (ret != 0) { - printf("\n"); + if (pyexec_mode_kind == PYEXEC_MODE_RAW_REPL) { + if ((ret = pyexec_raw_repl()) != 0) { + break; } - goto input_restart; } else { - // got a line with non-zero length, see if it needs continuing - while (mp_repl_continue_with_input(vstr_null_terminated_str(&line))) { - vstr_add_byte(&line, '\n'); - ret = readline(&line, mp_repl_get_ps2()); - if (ret == CHAR_CTRL_C) { - // cancel everything - printf("\n"); - goto input_restart; - } else if (ret == CHAR_CTRL_D) { - // stop entering compound statement - break; - } + if ((ret = pyexec_friendly_repl()) != 0) { + break; } } - - mp_hal_stdio_mode_orig(); - - ret = execute_from_lexer(LEX_SRC_VSTR, &line, parse_input_kind, true); - if (ret & FORCED_EXIT) { - return ret; - } } + return ret; #else // use simple readline + mp_hal_stdout_tx_str(MICROPY_BANNER_NAME_AND_VERSION); + mp_hal_stdout_tx_str("; " MICROPY_BANNER_MACHINE); + mp_hal_stdout_tx_str("\nUse Ctrl-D to exit, Ctrl-E for paste mode\n"); + for (;;) { char *line = prompt((char *)mp_repl_get_ps1()); if (line == NULL) { @@ -330,7 +265,8 @@ static int do_repl(void) { int ret = execute_from_lexer(LEX_SRC_STR, line, MP_PARSE_SINGLE_INPUT, true); free(line); - if (ret & FORCED_EXIT) { + // CIRCUITPY-CHANGE: be consistent about using PYEXEC_FORCED_EXIT + if (ret & PYEXEC_FORCED_EXIT) { return ret; } } @@ -338,18 +274,51 @@ static int do_repl(void) { #endif } +static inline int convert_pyexec_result(int ret) { + #if MICROPY_PYEXEC_ENABLE_EXIT_CODE_HANDLING + // With exit code handling enabled: + // pyexec returns exit code with PYEXEC_FORCED_EXIT flag set for SystemExit + // Unix port expects: 0 for success, non-zero for error/exit + if (ret & PYEXEC_FORCED_EXIT) { + // SystemExit: extract exit code from lower bits + return ret & 0xFF; + } + // Normal execution or exception: return as-is (0 for success, 1 for exception) + return ret; + #else + // pyexec returns 1 for success, 0 for exception, PYEXEC_FORCED_EXIT for SystemExit + // Convert to unix port's expected codes: 0 for success, 1 for exception, FORCED_EXIT|val for SystemExit + if (ret == 1) { + return 0; // success + } else if (ret & PYEXEC_FORCED_EXIT) { + return ret; // SystemExit with exit value in lower 8 bits + } else { + return 1; // exception + } + #endif +} + static int do_file(const char *file) { - return execute_from_lexer(LEX_SRC_FILENAME, file, MP_PARSE_FILE_INPUT, false); + // CIRCUITPY-CHANGE: pyexec_file result arg + pyexec_result_t pyexec_result; + return convert_pyexec_result(pyexec_file(file, &pyexec_result)); } static int do_str(const char *str) { - return execute_from_lexer(LEX_SRC_STR, str, MP_PARSE_FILE_INPUT, false); + vstr_t vstr; + vstr.buf = (char *)str; + vstr.len = strlen(str); + // CIRCUITPY-CHANGE: pyexec_vstr result arg + pyexec_result_t pyexec_result; + int ret = pyexec_vstr(&vstr, true, &pyexec_result); + return convert_pyexec_result(ret); } static void print_help(char **argv) { printf( "usage: %s [] [-X ] [-c | -m | ]\n" "Options:\n" + "--version : show version information\n" "-h : print this help message\n" "-i : enable inspection via REPL after running command/module/file\n" #if MICROPY_DEBUG_PRINTERS @@ -401,13 +370,17 @@ static void pre_process_options(int argc, char **argv) { print_help(argv); exit(0); } + if (strcmp(argv[a], "--version") == 0) { + printf(MICROPY_BANNER_NAME_AND_VERSION "; " MICROPY_BANNER_MACHINE "\n"); + exit(0); + } if (strcmp(argv[a], "-X") == 0) { if (a + 1 >= argc) { exit(invalid_args()); } if (0) { } else if (strcmp(argv[a + 1], "compile-only") == 0) { - compile_only = true; + mp_compile_only = true; } else if (strcmp(argv[a + 1], "emit=bytecode") == 0) { emit_opt = MP_EMIT_OPT_BYTECODE; #if MICROPY_EMIT_NATIVE @@ -479,10 +452,13 @@ static void set_sys_argv(char *argv[], int argc, int start_arg) { #if MICROPY_PY_SYS_EXECUTABLE extern mp_obj_str_t mp_sys_executable_obj; -static char executable_path[MICROPY_ALLOC_PATH_MAX]; +static char *executable_path = NULL; static void sys_set_excecutable(char *argv0) { - if (realpath(argv0, executable_path)) { + if (executable_path == NULL) { + executable_path = realpath(argv0, NULL); + } + if (executable_path != NULL) { mp_obj_str_set_data(&mp_sys_executable_obj, (byte *)executable_path, strlen(executable_path)); } } @@ -500,12 +476,16 @@ int main(int argc, char **argv) { #if MICROPY_PY_THREAD mp_thread_init(); #endif + + // Define a reasonable stack limit to detect stack overflow. + mp_uint_t stack_size = 40000 * UNIX_STACK_MULTIPLIER; + // We should capture stack top ASAP after start, and it should be // captured guaranteedly before any other stack variables are allocated. // For this, actual main (renamed main_) should not be inlined into // this function. main_() itself may have other functions inlined (with // their own stack variables), that's why we need this main/main_ split. - mp_stack_ctrl_init(); + mp_cstack_init_with_sp_here(stack_size); return main_(argc, argv); } @@ -524,14 +504,6 @@ MP_NOINLINE int main_(int argc, char **argv) { signal(SIGPIPE, SIG_IGN); #endif - // Define a reasonable stack limit to detect stack overflow. - mp_uint_t stack_limit = 40000 * (sizeof(void *) / 4); - #if defined(__arm__) && !defined(__thumb2__) - // ARM (non-Thumb) architectures require more stack. - stack_limit *= 2; - #endif - mp_stack_set_limit(stack_limit); - pre_process_options(argc, argv); #if MICROPY_ENABLE_GC @@ -543,6 +515,13 @@ MP_NOINLINE int main_(int argc, char **argv) { char *heaps[MICROPY_GC_SPLIT_HEAP_N_HEAPS]; long multi_heap_size = heap_size / MICROPY_GC_SPLIT_HEAP_N_HEAPS; for (size_t i = 0; i < MICROPY_GC_SPLIT_HEAP_N_HEAPS; i++) { + // CIRCUITPY-CHANGE: with MICROPY_GC_SPLIT_HEAP_AUTO the collector adds the other heaps itself + #if MICROPY_GC_SPLIT_HEAP_AUTO + if (i > 0) { + heaps[i] = NULL; + continue; + } + #endif heaps[i] = malloc(multi_heap_size); if (i == 0) { gc_init(heaps[i], heaps[i] + multi_heap_size); @@ -575,7 +554,14 @@ MP_NOINLINE int main_(int argc, char **argv) { MP_OBJ_NEW_QSTR(MP_QSTR__slash_), }; mp_vfs_mount(2, args, (mp_map_t *)&mp_const_empty_map); + + // Make sure the root that was just mounted is the current VFS (it's always at + // the end of the linked list). Can't use chdir('/') because that will change + // the current path within the VfsPosix object. MP_STATE_VM(vfs_cur) = MP_STATE_VM(vfs_mount_table); + while (MP_STATE_VM(vfs_cur)->next != NULL) { + MP_STATE_VM(vfs_cur) = MP_STATE_VM(vfs_cur)->next; + } } #endif @@ -594,7 +580,12 @@ MP_NOINLINE int main_(int argc, char **argv) { // First entry is empty. We've already added an empty entry to sys.path, so skip it. ++path; } - bool path_remaining = *path; + // GCC targeting RISC-V 64 reports a warning about `path_remaining` being clobbered by + // either setjmp or vfork if that variable it is allocated on the stack. This may + // probably be a compiler error as it occurs on a few recent GCC releases (up to 14.1.0) + // but LLVM doesn't report any warnings. + static bool path_remaining; + path_remaining = *path; while (path_remaining) { char *path_entry_end = strchr(path, PATHLIST_SEP_CHAR); if (path_entry_end == NULL) { @@ -627,24 +618,9 @@ MP_NOINLINE int main_(int argc, char **argv) { // CIRCUITPY-CHANGE: test native base classes work as needed by CircuitPython libraries. extern const mp_obj_type_t native_base_class_type; mp_store_global(MP_QSTR_NativeBaseClass, MP_OBJ_FROM_PTR(&native_base_class_type)); - mp_store_global(MP_QSTR_getenv_int, MP_OBJ_FROM_PTR(&mod_os_getenv_int_obj)); - mp_store_global(MP_QSTR_getenv_str, MP_OBJ_FROM_PTR(&mod_os_getenv_str_obj)); } #endif - // Here is some example code to create a class and instance of that class. - // First is the Python, then the C code. - // - // class TestClass: - // pass - // test_obj = TestClass() - // test_obj.attr = 42 - // - // mp_obj_t test_class_type, test_class_instance; - // test_class_type = mp_obj_new_type(qstr_from_str("TestClass"), mp_const_empty_tuple, mp_obj_new_dict(0)); - // mp_store_name(qstr_from_str("test_obj"), test_class_instance = mp_call_function_0(test_class_type)); - // mp_store_attr(test_class_instance, qstr_from_str("attr"), mp_obj_new_int(42)); - /* printf("bytes:\n"); printf(" total %d\n", m_get_total_bytes_allocated()); @@ -676,7 +652,7 @@ MP_NOINLINE int main_(int argc, char **argv) { return invalid_args(); } mp_obj_t import_args[4]; - import_args[0] = mp_obj_new_str(argv[a + 1], strlen(argv[a + 1])); + import_args[0] = mp_obj_new_str_from_cstr(argv[a + 1]); import_args[1] = import_args[2] = mp_const_none; // Ask __import__ to handle imported module specially - set its __name__ // to __main__, and also return this leaf module, not top-level package @@ -698,12 +674,18 @@ MP_NOINLINE int main_(int argc, char **argv) { subpkg_tried = false; reimport: + mp_hal_set_interrupt_char(CHAR_CTRL_C); if (nlr_push(&nlr) == 0) { mod = mp_builtin___import__(MP_ARRAY_SIZE(import_args), import_args); + mp_hal_set_interrupt_char(-1); + mp_handle_pending(true); nlr_pop(); } else { // uncaught exception - return handle_uncaught_exception(nlr.ret_val) & 0xff; + mp_hal_set_interrupt_char(-1); + mp_handle_pending(false); + ret = handle_uncaught_exception(nlr.ret_val) & 0xff; + break; } // If this module is a package, see if it has a `__main__.py`. @@ -726,7 +708,7 @@ MP_NOINLINE int main_(int argc, char **argv) { a += 1; #if MICROPY_DEBUG_PRINTERS } else if (strcmp(argv[a], "-v") == 0) { - mp_verbose_flag++; + MP_STATE_VM(mp_verbose_flag)++; #endif } else if (strncmp(argv[a], "-O", 2) == 0) { if (unichar_isdigit(argv[a][2])) { @@ -740,11 +722,9 @@ MP_NOINLINE int main_(int argc, char **argv) { return invalid_args(); } } else { - char *pathbuf = malloc(PATH_MAX); - char *basedir = realpath(argv[a], pathbuf); + char *basedir = realpath(argv[a], NULL); if (basedir == NULL) { mp_printf(&mp_stderr_print, "%s: can't open file '%s': [Errno %d] %s\n", argv[0], argv[a], errno, strerror(errno)); - free(pathbuf); // CPython exits with 2 in such case ret = 2; break; @@ -753,7 +733,7 @@ MP_NOINLINE int main_(int argc, char **argv) { // Set base dir of the script as first entry in sys.path. char *p = strrchr(basedir, '/'); mp_obj_list_store(mp_sys_path, MP_OBJ_NEW_SMALL_INT(0), mp_obj_new_str_via_qstr(basedir, p - basedir)); - free(pathbuf); + free(basedir); set_sys_argv(argv, argc, a); ret = do_file(argv[a]); @@ -787,13 +767,13 @@ MP_NOINLINE int main_(int argc, char **argv) { #endif #if MICROPY_PY_MICROPYTHON_MEM_INFO - if (mp_verbose_flag) { + if (MP_STATE_VM(mp_verbose_flag)) { mp_micropython_mem_info(0, NULL); } #endif #if MICROPY_PY_BLUETOOTH - void mp_bluetooth_deinit(void); + int mp_bluetooth_deinit(void); mp_bluetooth_deinit(); #endif @@ -819,8 +799,20 @@ MP_NOINLINE int main_(int argc, char **argv) { #endif #endif + #if MICROPY_PY_SYS_EXECUTABLE && !defined(NDEBUG) + // Again, make memory leak detector happy + free(executable_path); + #endif + // printf("total bytes = %d\n", m_get_total_bytes_allocated()); - return ret & 0xff; + + // CIRCUITPY-CHANGE: handle PYEXEC_UNHANDLED_EXCEPTION + if (ret == PYEXEC_UNHANDLED_EXCEPTION) { + // Return exit status code 1 so the invoker knows there was an uncaught exception. + return 1; + } else { + return ret & 0xff; + } } void nlr_jump_fail(void *val) { @@ -830,3 +822,22 @@ void nlr_jump_fail(void *val) { fprintf(stderr, "FATAL: uncaught NLR %p\n", val); exit(1); } + +#if MICROPY_VFS_ROM_IOCTL + +static uint8_t romfs_buf[4] = { 0xd2, 0xcd, 0x31, 0x00 }; // empty ROMFS +static const MP_DEFINE_MEMORYVIEW_OBJ(romfs_obj, 'B', 0, sizeof(romfs_buf), romfs_buf); + +mp_obj_t mp_vfs_rom_ioctl(size_t n_args, const mp_obj_t *args) { + switch (mp_obj_get_int(args[0])) { + case MP_VFS_ROM_IOCTL_GET_NUMBER_OF_SEGMENTS: + return MP_OBJ_NEW_SMALL_INT(1); + + case MP_VFS_ROM_IOCTL_GET_SEGMENT: + return MP_OBJ_FROM_PTR(&romfs_obj); + } + + return MP_OBJ_NEW_SMALL_INT(-MP_EINVAL); +} + +#endif diff --git a/ports/unix/mbedtls/mbedtls_config_port.h b/ports/unix/mbedtls/mbedtls_config_port.h index c619de9b8b1..aec65e6581e 100644 --- a/ports/unix/mbedtls/mbedtls_config_port.h +++ b/ports/unix/mbedtls/mbedtls_config_port.h @@ -32,7 +32,18 @@ // Enable mbedtls modules #define MBEDTLS_TIMING_C +#if defined(MICROPY_UNIX_COVERAGE) +// Test the "bare metal" memory management in the coverage build +#define MICROPY_MBEDTLS_CONFIG_BARE_METAL (1) +#endif + // Include common mbedtls configuration. #include "extmod/mbedtls/mbedtls_config_common.h" +#if defined(MICROPY_UNIX_COVERAGE) +// See comment above, but fall back to the default platform entropy functions +#undef MBEDTLS_ENTROPY_HARDWARE_ALT +#undef MBEDTLS_NO_PLATFORM_ENTROPY +#endif + #endif /* MICROPY_INCLUDED_MBEDTLS_CONFIG_H */ diff --git a/ports/unix/modffi.c b/ports/unix/modffi.c index b7d03e84dde..c16d40ad3b4 100644 --- a/ports/unix/modffi.c +++ b/ports/unix/modffi.c @@ -174,7 +174,7 @@ static mp_obj_t return_ffi_value(ffi_union_t *val, char type) { if (!s) { return mp_const_none; } - return mp_obj_new_str(s, strlen(s)); + return mp_obj_new_str_from_cstr(s); } case 'v': return mp_const_none; @@ -190,10 +190,13 @@ static mp_obj_t return_ffi_value(ffi_union_t *val, char type) { case 'h': case 'i': case 'l': - return mp_obj_new_int((signed)val->ffi); + return mp_obj_new_int((ffi_sarg)val->ffi); + case 'I': + // On RV64, 32-bit values are stored as signed integers inside the + // holding register. + return mp_obj_new_int_from_uint(val->ffi & 0xFFFFFFFF); case 'B': case 'H': - case 'I': case 'L': return mp_obj_new_int_from_uint(val->ffi); case 'q': @@ -334,7 +337,8 @@ static mp_obj_t mod_ffi_callback(size_t n_args, const mp_obj_t *pos_args, mp_map 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 = mp_obj_malloc_var(mp_obj_fficallback_t, params, ffi_type *, nparams, &fficallback_type); + mp_obj_fficallback_t *o = (mp_obj_fficallback_t *)m_tracked_calloc(offsetof(mp_obj_fficallback_t, params) + sizeof(ffi_type *) * nparams, sizeof(uint8_t)); + o->base.type = &fficallback_type; o->clo = ffi_closure_alloc(sizeof(ffi_closure), &o->func); @@ -442,7 +446,7 @@ static unsigned long long ffi_get_int_value(mp_obj_t o) { return MP_OBJ_SMALL_INT_VALUE(o); } else { unsigned long long res; - mp_obj_int_to_bytes_impl(o, MP_ENDIANNESS_BIG, sizeof(res), (byte *)&res); + mp_obj_int_to_bytes(o, sizeof(res), (byte *)&res, MP_ENDIANNESS_BIG, false, false); return res; } } diff --git a/ports/unix/modjni.c b/ports/unix/modjni.c index d953e7e0152..0a29a94fbd4 100644 --- a/ports/unix/modjni.c +++ b/ports/unix/modjni.c @@ -337,7 +337,7 @@ static mp_obj_t new_jobject(jobject jo) { return mp_const_none; } else if (JJ(IsInstanceOf, jo, String_class)) { const char *s = JJ(GetStringUTFChars, jo, NULL); - mp_obj_t ret = mp_obj_new_str(s, strlen(s)); + mp_obj_t ret = mp_obj_new_str_from_cstr(s); JJ(ReleaseStringUTFChars, jo, s); return ret; } else if (JJ(IsInstanceOf, jo, Class_class)) { @@ -357,7 +357,7 @@ static void jmethod_print(const mp_print_t *print, mp_obj_t self_in, mp_print_ki (void)kind; 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)); + mp_printf(print, "", (qstr)self->name); } #define IMATCH(s, static) ((!strncmp(s, static, sizeof(static) - 1)) && (s += sizeof(static) - 1)) diff --git a/ports/unix/modmachine.c b/ports/unix/modmachine.c index 6f3ab809440..d1cdbe8619a 100644 --- a/ports/unix/modmachine.c +++ b/ports/unix/modmachine.c @@ -36,9 +36,6 @@ #define MICROPY_PAGE_MASK (MICROPY_PAGE_SIZE - 1) #endif -// This variable is needed for machine.soft_reset(), but the variable is otherwise unused. -int pyexec_system_exit = 0; - uintptr_t mod_machine_mem_get_addr(mp_obj_t addr_o, uint align) { uintptr_t addr = mp_obj_get_int_truncated(addr_o); if ((addr & (align - 1)) != 0) { diff --git a/ports/unix/modos.c b/ports/unix/modos.c index 09d82984310..28f232e42bc 100644 --- a/ports/unix/modos.c +++ b/ports/unix/modos.c @@ -32,13 +32,12 @@ #include "py/runtime.h" #include "py/mphal.h" -// CIRCUITPY-CHANGE: enhanced getenv +// CIRCUITPY-CHANGE: use shared-module os getenv #if defined(MICROPY_UNIX_COVERAGE) #include "py/objstr.h" -typedef int os_getenv_err_t; +#include "shared-module/os/__init__.h" +#include "supervisor/shared/settings.h" mp_obj_t common_hal_os_getenv(const char *key, mp_obj_t default_); -os_getenv_err_t common_hal_os_getenv_str(const char *key, char *value, size_t value_len); -os_getenv_err_t common_hal_os_getenv_int(const char *key, mp_int_t *value); #endif static mp_obj_t mp_os_getenv(size_t n_args, const mp_obj_t *args) { @@ -56,32 +55,9 @@ static mp_obj_t mp_os_getenv(size_t n_args, const mp_obj_t *args) { } return mp_const_none; } - return mp_obj_new_str(s, strlen(s)); + return mp_obj_new_str_from_cstr(s); } -MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_os_getenv_obj, 1, 2, mp_os_getenv); - -// CIRCUITPY-CHANGE: getenv differences -#if defined(MICROPY_UNIX_COVERAGE) -static mp_obj_t mp_os_getenv_int(mp_obj_t var_in) { - mp_int_t value; - os_getenv_err_t result = common_hal_os_getenv_int(mp_obj_str_get_str(var_in), &value); - if (result == 0) { - return mp_obj_new_int(value); - } - return mp_const_none; -} -MP_DEFINE_CONST_FUN_OBJ_1(mp_os_getenv_int_obj, mp_os_getenv_int); - -static mp_obj_t mp_os_getenv_str(mp_obj_t var_in) { - char buf[4096]; - os_getenv_err_t result = common_hal_os_getenv_str(mp_obj_str_get_str(var_in), buf, sizeof(buf)); - if (result == 0) { - return mp_obj_new_str_copy(&mp_type_str, (byte *)buf, strlen(buf)); - } - return mp_const_none; -} -MP_DEFINE_CONST_FUN_OBJ_1(mp_os_getenv_str_obj, mp_os_getenv_str); -#endif +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_os_getenv_obj, 1, 2, mp_os_getenv); static mp_obj_t mp_os_putenv(mp_obj_t key_in, mp_obj_t value_in) { const char *key = mp_obj_str_get_str(key_in); @@ -131,15 +107,6 @@ static mp_obj_t mp_os_system(mp_obj_t cmd_in) { } static MP_DEFINE_CONST_FUN_OBJ_1(mp_os_system_obj, mp_os_system); -static mp_obj_t mp_os_urandom(mp_obj_t num) { - mp_int_t n = mp_obj_get_int(num); - vstr_t vstr; - vstr_init_len(&vstr, n); - mp_hal_get_random(n, vstr.buf); - return mp_obj_new_bytes_from_vstr(&vstr); -} -static MP_DEFINE_CONST_FUN_OBJ_1(mp_os_urandom_obj, mp_os_urandom); - static mp_obj_t mp_os_errno(size_t n_args, const mp_obj_t *args) { if (n_args == 0) { return MP_OBJ_NEW_SMALL_INT(errno); diff --git a/ports/unix/modtermios.c b/ports/unix/modtermios.c index b1ad9a450e0..d7b94038aa1 100644 --- a/ports/unix/modtermios.c +++ b/ports/unix/modtermios.c @@ -141,6 +141,27 @@ static const mp_rom_map_elem_t mp_module_termios_globals_table[] = { #ifdef B115200 C(B115200), #endif + #ifdef B230400 + C(B230400), + #endif + #ifdef B460800 + C(B460800), + #endif + #ifdef B500000 + C(B500000), + #endif + #ifdef B576000 + C(B576000), + #endif + #ifdef B921600 + C(B921600), + #endif + #ifdef B1000000 + C(B1000000), + #endif + #ifdef B1152000 + C(B1152000) + #endif #undef C }; diff --git a/ports/unix/modtime.c b/ports/unix/modtime.c index fbd94b5ecd1..97c9b292d06 100644 --- a/ports/unix/modtime.c +++ b/ports/unix/modtime.c @@ -34,6 +34,7 @@ #include "py/mphal.h" #include "py/runtime.h" +#include "shared/timeutils/timeutils.h" #ifdef _WIN32 static inline int msec_sleep_tv(struct timeval *tv) { @@ -94,6 +95,7 @@ static mp_obj_t mp_time_sleep(mp_obj_t arg) { tv.tv_sec = (suseconds_t)ipart; int res; while (1) { + mp_handle_pending(MP_HANDLE_PENDING_CALLBACKS_AND_EXCEPTIONS); MP_THREAD_GIL_EXIT(); res = sleep_select(0, NULL, NULL, NULL, &tv); MP_THREAD_GIL_ENTER(); @@ -103,7 +105,6 @@ static mp_obj_t mp_time_sleep(mp_obj_t arg) { if (res != -1 || errno != EINTR) { break; } - mp_handle_pending(true); // printf("select: EINTR: %ld:%ld\n", tv.tv_sec, tv.tv_usec); #else break; @@ -113,13 +114,13 @@ static mp_obj_t mp_time_sleep(mp_obj_t arg) { #else int seconds = mp_obj_get_int(arg); for (;;) { + mp_handle_pending(MP_HANDLE_PENDING_CALLBACKS_AND_EXCEPTIONS); MP_THREAD_GIL_EXIT(); seconds = sleep(seconds); MP_THREAD_GIL_ENTER(); if (seconds == 0) { break; } - mp_handle_pending(true); } #endif return mp_const_none; @@ -130,12 +131,7 @@ static mp_obj_t mod_time_gm_local_time(size_t n_args, const mp_obj_t *args, stru if (n_args == 0) { t = time(NULL); } else { - #if MICROPY_PY_BUILTINS_FLOAT && MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE - mp_float_t val = mp_obj_get_float(args[0]); - t = (time_t)MICROPY_FLOAT_C_FUN(trunc)(val); - #else - t = mp_obj_get_int(args[0]); - #endif + t = (time_t)timeutils_obj_get_timestamp(args[0]); } struct tm *tm = time_func(&t); @@ -193,10 +189,10 @@ static mp_obj_t mod_time_mktime(mp_obj_t tuple) { time.tm_isdst = -1; // auto-detect } time_t ret = mktime(&time); - if (ret == -1) { + if (ret == (time_t)-1) { mp_raise_msg(&mp_type_OverflowError, MP_ERROR_TEXT("invalid mktime usage")); } - return mp_obj_new_int(ret); + return timeutils_obj_from_timestamp(ret); } MP_DEFINE_CONST_FUN_OBJ_1(mod_time_mktime_obj, mod_time_mktime); diff --git a/ports/unix/mpbthciport.c b/ports/unix/mpbthciport.c index 95c39f55991..765146677e8 100644 --- a/ports/unix/mpbthciport.c +++ b/ports/unix/mpbthciport.c @@ -196,10 +196,7 @@ int mp_bluetooth_hci_uart_init(uint32_t port, uint32_t baudrate) { } // Create a thread to run the polling loop. - pthread_attr_t attr; - pthread_attr_init(&attr); - pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); - pthread_create(&hci_poll_thread_id, &attr, &hci_poll_thread, NULL); + pthread_create(&hci_poll_thread_id, NULL, &hci_poll_thread, NULL); return 0; } diff --git a/ports/unix/mpbtstackport_usb.c b/ports/unix/mpbtstackport_usb.c index 8b1d1fff218..a924fc3ca91 100644 --- a/ports/unix/mpbtstackport_usb.c +++ b/ports/unix/mpbtstackport_usb.c @@ -110,10 +110,7 @@ static void *btstack_thread(void *arg) { void mp_bluetooth_btstack_port_start(void) { // Create a thread to run the btstack loop. - pthread_attr_t attr; - pthread_attr_init(&attr); - pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); - pthread_create(&bstack_thread_id, &attr, &btstack_thread, NULL); + pthread_create(&bstack_thread_id, NULL, &btstack_thread, NULL); } #endif // MICROPY_PY_BLUETOOTH && MICROPY_BLUETOOTH_BTSTACK && MICROPY_BLUETOOTH_BTSTACK_USB diff --git a/ports/unix/mpconfigport.h b/ports/unix/mpconfigport.h index afc1c3a38d1..7c2ede3bad3 100644 --- a/ports/unix/mpconfigport.h +++ b/ports/unix/mpconfigport.h @@ -32,6 +32,9 @@ // features to work on Unix-like systems, see mpconfigvariant.h (and // mpconfigvariant_common.h) for feature enabling. +// For time_t, needed by MICROPY_TIMESTAMP_IMPL_TIME_T. +#include + // For size_t and ssize_t #include @@ -41,6 +44,7 @@ // CIRCUITPY-CHANGE #define CIRCUITPY_MICROPYTHON_ADVANCED (1) #define MICROPY_PY_ASYNC_AWAIT (1) +#define MICROPY_PY_DOUBLE_TYPECODE (1) #define MICROPY_PY_UCTYPES (0) #ifndef MICROPY_CONFIG_ROM_LEVEL @@ -50,13 +54,20 @@ #ifndef MICROPY_PY_SYS_PLATFORM #if defined(__APPLE__) && defined(__MACH__) #define MICROPY_PY_SYS_PLATFORM "darwin" +#elif defined(__FreeBSD__) + #define MICROPY_PY_SYS_PLATFORM "freebsd" #else #define MICROPY_PY_SYS_PLATFORM "linux" #endif #endif #ifndef MICROPY_PY_SYS_PATH_DEFAULT -#define MICROPY_PY_SYS_PATH_DEFAULT ".frozen:~/.micropython/lib:/usr/lib/micropython" +#if defined(__FreeBSD__) +#define SYSTEM_LIB_PATH "/usr/local/lib/micropython" +#else +#define SYSTEM_LIB_PATH "/usr/lib/micropython" +#endif +#define MICROPY_PY_SYS_PATH_DEFAULT ".frozen:~/.micropython/lib:" SYSTEM_LIB_PATH #endif #define MP_STATE_PORT MP_STATE_VM @@ -78,21 +89,6 @@ #define MICROPY_EMIT_ARM (1) #endif -// Type definitions for the specific machine based on the word size. -#ifndef MICROPY_OBJ_REPR -#ifdef __LP64__ -typedef long mp_int_t; // must be pointer size -typedef unsigned long mp_uint_t; // must be pointer size -#else -// These are definitions for machines where sizeof(int) == sizeof(void*), -// regardless of actual size. -typedef int mp_int_t; // must be pointer size -typedef unsigned int mp_uint_t; // must be pointer size -#endif -#else -// Assume that if we already defined the obj repr then we also defined types. -#endif - // Cannot include , as it may lead to symbol name clashes #if _FILE_OFFSET_BITS == 64 && !defined(__LP64__) typedef long long mp_off_t; @@ -112,10 +108,15 @@ typedef long mp_off_t; // Always enable GC. #define MICROPY_ENABLE_GC (1) - -#if !(defined(MICROPY_GCREGS_SETJMP) || defined(__x86_64__) || defined(__i386__) || defined(__thumb2__) || defined(__thumb__) || defined(__arm__)) -// Fall back to setjmp() implementation for discovery of GC pointers in registers. -#define MICROPY_GCREGS_SETJMP (1) +// CIRCUITPY-CHANGE +#define MICROPY_ENABLE_SELECTIVE_COLLECT (1) + +// Fall back to setjmp() implementation for discovery of GC pointers in registers +// if running on intel-based macOS, or on architectures for which there is no +// specialised GC pointer discovery mechanism. +#if (defined(__APPLE__) && defined(__MACH__) && (defined(__i386__) || defined(__x86_64__))) || \ + (!(defined(MICROPY_GCREGS_SETJMP) || defined(__x86_64__) || defined(__i386__) || defined(__thumb2__) || defined(__thumb__) || defined(__arm__) || (defined(__riscv) && __riscv_xlen <= 64) || (defined(__loongarch__) && defined(__loongarch64)))) +#define MICROPY_GCREGS_SETJMP (1) #endif // Enable the VFS, and enable the posix "filesystem". @@ -125,13 +126,17 @@ typedef long mp_off_t; #define MICROPY_HELPER_LEXER_UNIX (1) #define MICROPY_VFS_POSIX (1) #define MICROPY_READER_POSIX (1) +// CIRCUITPY-CHANGE: define no matter what #ifndef MICROPY_TRACKED_ALLOC -#define MICROPY_TRACKED_ALLOC (MICROPY_BLUETOOTH_BTSTACK) +#define MICROPY_TRACKED_ALLOC (MICROPY_PY_FFI || MICROPY_BLUETOOTH_BTSTACK) #endif // VFS stat functions should return time values relative to 1970/1/1 #define MICROPY_EPOCH_IS_1970 (1) +// port modtime functions use time_t +#define MICROPY_TIMESTAMP_IMPL (MICROPY_TIMESTAMP_IMPL_TIME_T) + // Assume that select() call, interrupted with a signal, and erroring // with EINTR, updates remaining timeout value. #define MICROPY_SELECT_REMAINING_TIME (1) @@ -142,6 +147,9 @@ typedef long mp_off_t; #define MICROPY_STACKLESS_STRICT (0) #endif +// Recursive mutex is needed when threading is enabled, regardless of GIL setting. +#define MICROPY_PY_THREAD_RECURSIVE_MUTEX (MICROPY_PY_THREAD) + // Implementation of the machine module. #define MICROPY_PY_MACHINE_INCLUDEFILE "ports/unix/modmachine.c" @@ -169,6 +177,12 @@ typedef long mp_off_t; // Enable sys.executable. #define MICROPY_PY_SYS_EXECUTABLE (1) +// Enable support for compile-only mode. +#define MICROPY_PYEXEC_COMPILE_ONLY (1) + +// Enable handling of sys.exit() exit codes. +#define MICROPY_PYEXEC_ENABLE_EXIT_CODE_HANDLING (1) + #define MICROPY_PY_SOCKET_LISTEN_BACKLOG_DEFAULT (SOMAXCONN < 128 ? SOMAXCONN : 128) // Bare-metal ports don't have stderr. Printing debug to stderr may give tests @@ -180,14 +194,8 @@ extern const struct _mp_print_t mp_stderr_print; // For the native emitter configure how to mark a region as executable. 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) #define MP_PLAT_FREE_EXEC(ptr, size) mp_unix_free_exec(ptr, size) -#ifndef MICROPY_FORCE_PLAT_ALLOC_EXEC -// Use MP_PLAT_ALLOC_EXEC for any executable memory allocation, including for FFI -// (overriding libffi own implementation) -#define MICROPY_FORCE_PLAT_ALLOC_EXEC (1) -#endif // If enabled, configure how to seed random on init. #ifdef MICROPY_PY_RANDOM_SEED_INIT_FUNC diff --git a/ports/unix/mpconfigport.mk b/ports/unix/mpconfigport.mk index d6b57ca8860..5260bd46aa1 100644 --- a/ports/unix/mpconfigport.mk +++ b/ports/unix/mpconfigport.mk @@ -1,8 +1,5 @@ # Enable/disable modules and 3rd-party libs to be included in interpreter -# Build 32-bit binaries on a 64-bit host -MICROPY_FORCE_32BIT = 0 - # This variable can take the following values: # 0 - no readline, just simple stdin input # 1 - use MicroPython version of readline @@ -14,6 +11,7 @@ MICROPY_PY_BTREE = 0 # _thread module using pthreads MICROPY_PY_THREAD = 1 +MICROPY_PY_THREAD_GIL = 0 # Subset of CPython termios module MICROPY_PY_TERMIOS = 1 @@ -41,7 +39,7 @@ MICROPY_PY_JNI = 0 # Avoid using system libraries, use copies bundled with MicroPython # as submodules (currently affects only libffi). -MICROPY_STANDALONE = 0 +MICROPY_STANDALONE ?= 0 # CIRCUITPY-CHANGE: not used MICROPY_ROM_TEXT_COMPRESSION = 0 @@ -54,5 +52,4 @@ MICROPY_VFS_LFS2 = 0 # CIRCUITPY-CHANGE CIRCUITPY_ULAB = 1 CIRCUITPY_MESSAGE_COMPRESSION_LEVEL = 1 -MICROPY_EMIT_NATIVE = 0 CFLAGS += -DCIRCUITPY=1 diff --git a/ports/unix/mphalport.h b/ports/unix/mphalport.h index 7f71217632a..91d44d1688d 100644 --- a/ports/unix/mphalport.h +++ b/ports/unix/mphalport.h @@ -25,7 +25,6 @@ */ #include #include -// CIRCUITPY-CHANGE: extra include #include #ifndef CHAR_CTRL_C @@ -38,6 +37,20 @@ #define MICROPY_END_ATOMIC_SECTION(x) (void)x; mp_thread_unix_end_atomic_section() #endif +// In lieu of a WFI(), slow down polling from being a tight loop. +// +// Note that we don't delay for the full TIMEOUT_MS, as execution +// can't be woken from the delay. +#define MICROPY_INTERNAL_WFE(TIMEOUT_MS) \ + do { \ + MP_THREAD_GIL_EXIT(); \ + mp_hal_delay_us(500); \ + MP_THREAD_GIL_ENTER(); \ + } while (0) + +// The port provides `mp_hal_stdio_mode_raw()` and `mp_hal_stdio_mode_orig()`. +#define MICROPY_HAL_HAS_STDIO_MODE_SWITCH (1) + // CIRCUITPY-CHANGE: mp_hal_set_interrupt_char(int) instead of char void mp_hal_set_interrupt_char(int c); bool mp_hal_is_interrupted(void); @@ -110,3 +123,15 @@ enum { void mp_hal_get_mac(int idx, uint8_t buf[6]); #endif + +#if defined(__linux__) && (defined(__ARM_32BIT_STATE) || defined(__riscv)) +#if __has_builtin(__builtin___clear_cache) +#define MP_HAL_CLEAN_DCACHE(fun_data, fun_len) \ + do { \ + __builtin___clear_cache((void *)fun_data, (char *)fun_data + fun_len); \ + } while (0) +#endif +#endif + +// Global variable to control compile-only mode. +extern bool mp_compile_only; diff --git a/ports/unix/mpthreadport.c b/ports/unix/mpthreadport.c index 16ac4da8bf5..a41b3ec9f47 100644 --- a/ports/unix/mpthreadport.c +++ b/ports/unix/mpthreadport.c @@ -31,6 +31,7 @@ #include "py/runtime.h" #include "py/mpthread.h" #include "py/gc.h" +#include "stack_size.h" #if MICROPY_PY_THREAD @@ -45,8 +46,14 @@ // potential conflict with other uses of the more commonly used SIGUSR1. #ifdef SIGRTMIN #define MP_THREAD_GC_SIGNAL (SIGRTMIN + 5) +#ifdef __ANDROID__ +#define MP_THREAD_TERMINATE_SIGNAL (SIGRTMIN + 6) +#endif #else #define MP_THREAD_GC_SIGNAL (SIGUSR1) +#ifdef __ANDROID__ +#define MP_THREAD_TERMINATE_SIGNAL (SIGUSR2) +#endif #endif // This value seems to be about right for both 32-bit and 64-bit builds. @@ -65,7 +72,7 @@ static pthread_key_t tls_key; // The mutex is used for any code in this port that needs to be thread safe. // Specifically for thread management, access to the linked list is one example. // But also, e.g. scheduler state. -static pthread_mutex_t thread_mutex; +static mp_thread_recursive_mutex_t thread_mutex; static mp_thread_t *thread; // this is used to synchronise the signal handler of the thread @@ -78,11 +85,11 @@ static sem_t thread_signal_done; #endif void mp_thread_unix_begin_atomic_section(void) { - pthread_mutex_lock(&thread_mutex); + mp_thread_recursive_mutex_lock(&thread_mutex, true); } void mp_thread_unix_end_atomic_section(void) { - pthread_mutex_unlock(&thread_mutex); + mp_thread_recursive_mutex_unlock(&thread_mutex); } // this signal handler is used to scan the regs and stack of a thread @@ -107,16 +114,25 @@ static void mp_thread_gc(int signo, siginfo_t *info, void *context) { } } +// On Android, pthread_cancel and pthread_setcanceltype are not implemented. +// To achieve that result a new signal handler responding on either +// (SIGRTMIN + 6) or SIGUSR2 is installed on every child thread. The sole +// purpose of this new signal handler is to terminate the thread in a safe +// asynchronous manner. + +#ifdef __ANDROID__ +static void mp_thread_terminate(int signo, siginfo_t *info, void *context) { + pthread_exit(NULL); +} +#endif + void mp_thread_init(void) { pthread_key_create(&tls_key, NULL); pthread_setspecific(tls_key, &mp_state_ctx.thread); // Needs to be a recursive mutex to emulate the behavior of // BEGIN_ATOMIC_SECTION on bare metal. - pthread_mutexattr_t thread_mutex_attr; - pthread_mutexattr_init(&thread_mutex_attr); - pthread_mutexattr_settype(&thread_mutex_attr, PTHREAD_MUTEX_RECURSIVE); - pthread_mutex_init(&thread_mutex, &thread_mutex_attr); + mp_thread_recursive_mutex_init(&thread_mutex); // create first entry in linked list of all threads thread = malloc(sizeof(mp_thread_t)); @@ -138,6 +154,14 @@ void mp_thread_init(void) { sa.sa_sigaction = mp_thread_gc; sigemptyset(&sa.sa_mask); sigaction(MP_THREAD_GC_SIGNAL, &sa, NULL); + + // Install a signal handler for asynchronous termination if needed. + #if defined(__ANDROID__) + sa.sa_flags = SA_SIGINFO; + sa.sa_sigaction = mp_thread_terminate; + sigemptyset(&sa.sa_mask); + sigaction(MP_THREAD_TERMINATE_SIGNAL, &sa, NULL); + #endif } void mp_thread_deinit(void) { @@ -145,7 +169,11 @@ void mp_thread_deinit(void) { while (thread->next != NULL) { mp_thread_t *th = thread; thread = thread->next; + #if defined(__ANDROID__) + pthread_kill(th->id, MP_THREAD_TERMINATE_SIGNAL); + #else pthread_cancel(th->id); + #endif free(th); } mp_thread_unix_end_atomic_section(); @@ -203,7 +231,9 @@ void mp_thread_start(void) { } #endif + #if !defined(__ANDROID__) pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL); + #endif mp_thread_unix_begin_atomic_section(); for (mp_thread_t *th = thread; th != NULL; th = th->next) { if (th->id == pthread_self()) { @@ -215,14 +245,14 @@ void mp_thread_start(void) { } mp_uint_t mp_thread_create(void *(*entry)(void *), void *arg, size_t *stack_size) { - // default stack size is 8k machine-words + // default stack size if (*stack_size == 0) { - *stack_size = 8192 * sizeof(void *); + *stack_size = 32768 * UNIX_STACK_MULTIPLIER; } // minimum stack size is set by pthreads - if (*stack_size < PTHREAD_STACK_MIN) { - *stack_size = PTHREAD_STACK_MIN; + if (*stack_size < (size_t)PTHREAD_STACK_MIN) { + *stack_size = (size_t)PTHREAD_STACK_MIN; } // ensure there is enough stack to include a stack-overflow margin @@ -321,6 +351,26 @@ void mp_thread_mutex_unlock(mp_thread_mutex_t *mutex) { // TODO check return value } +#if MICROPY_PY_THREAD_RECURSIVE_MUTEX + +void mp_thread_recursive_mutex_init(mp_thread_recursive_mutex_t *mutex) { + pthread_mutexattr_t attr; + pthread_mutexattr_init(&attr); + pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE); + pthread_mutex_init(mutex, &attr); + pthread_mutexattr_destroy(&attr); +} + +int mp_thread_recursive_mutex_lock(mp_thread_recursive_mutex_t *mutex, int wait) { + return mp_thread_mutex_lock(mutex, wait); +} + +void mp_thread_recursive_mutex_unlock(mp_thread_recursive_mutex_t *mutex) { + mp_thread_mutex_unlock(mutex); +} + +#endif // MICROPY_PY_THREAD_RECURSIVE_MUTEX + #endif // MICROPY_PY_THREAD // this is used even when MICROPY_PY_THREAD is disabled diff --git a/ports/unix/mpthreadport.h b/ports/unix/mpthreadport.h index b365f200edf..a38223e720b 100644 --- a/ports/unix/mpthreadport.h +++ b/ports/unix/mpthreadport.h @@ -28,6 +28,7 @@ #include typedef pthread_mutex_t mp_thread_mutex_t; +typedef pthread_mutex_t mp_thread_recursive_mutex_t; void mp_thread_init(void); void mp_thread_deinit(void); diff --git a/ports/unix/stack_size.h b/ports/unix/stack_size.h new file mode 100644 index 00000000000..95ec502b0f8 --- /dev/null +++ b/ports/unix/stack_size.h @@ -0,0 +1,61 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2025 Angus Gratton + * + * 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_UNIX_STACK_SIZE_H +#define MICROPY_INCLUDED_UNIX_STACK_SIZE_H + +#include "py/misc.h" + +// Define scaling factors for the stack size (also applies to main thread) +#ifndef UNIX_STACK_MULTIPLIER + +#if defined(__arm__) && !defined(__thumb2__) +// ARM (non-Thumb) architectures require more stack. +#define UNIX_STACK_MUL_ARM 2 +#else +#define UNIX_STACK_MUL_ARM 1 +#endif + +#if MP_SANITIZER_BUILD +// Sanitizer features consume significant stack in some cases +// This multiplier can probably be removed when using GCC 12 or newer. +#define UNIX_STACK_MUL_SANITIZERS 4 +#else +#define UNIX_STACK_MUL_SANITIZERS 1 +#endif + +#if defined(_MSC_VER) +// Similarly Windows seems to require more stack +#define UNIX_STACK_MUL_WINDOWS 2 +#else +#define UNIX_STACK_MUL_WINDOWS 1 +#endif + +// Double the stack size for 64-bit builds, plus additional scalings +#define UNIX_STACK_MULTIPLIER ((sizeof(void *) / 4) * (UNIX_STACK_MUL_ARM)*(UNIX_STACK_MUL_SANITIZERS)*(UNIX_STACK_MUL_WINDOWS)) + +#endif // UNIX_STACK_MULTIPLIER + +#endif // MICROPY_INCLUDED_UNIX_STACK_SIZE_H diff --git a/ports/unix/unix_mphal.c b/ports/unix/unix_mphal.c index 238d1cb5ee8..ac75f20eee4 100644 --- a/ports/unix/unix_mphal.c +++ b/ports/unix/unix_mphal.c @@ -117,12 +117,12 @@ void mp_hal_stdio_mode_raw(void) { termios.c_lflag = 0; termios.c_cc[VMIN] = 1; termios.c_cc[VTIME] = 0; - tcsetattr(0, TCSAFLUSH, &termios); + tcsetattr(0, TCSANOW, &termios); } void mp_hal_stdio_mode_orig(void) { // restore terminal settings - tcsetattr(0, TCSAFLUSH, &orig_termios); + tcsetattr(0, TCSANOW, &orig_termios); } #endif @@ -251,9 +251,13 @@ uint64_t mp_hal_time_ns(void) { #ifndef mp_hal_delay_ms void mp_hal_delay_ms(mp_uint_t ms) { - mp_uint_t start = mp_hal_ticks_ms(); - while (mp_hal_ticks_ms() - start < ms) { - mp_event_wait_ms(1); + if (ms) { + mp_uint_t start = mp_hal_ticks_ms(); + while (mp_hal_ticks_ms() - start < ms) { + mp_event_wait_ms(1); + } + } else { + mp_handle_pending(true); } } #endif diff --git a/ports/unix/variants/coverage/manifest.py b/ports/unix/variants/coverage/manifest.py index 37f2531a842..2d459103ef2 100644 --- a/ports/unix/variants/coverage/manifest.py +++ b/ports/unix/variants/coverage/manifest.py @@ -1,5 +1,5 @@ add_library("unix-ffi", "$(MPY_LIB_DIR)/unix-ffi") freeze_as_str("frzstr") freeze_as_mpy("frzmpy") -freeze_mpy("$(MPY_DIR)/tests/frozen") +freeze_mpy("$(MPY_DIR)/tests/assets") require("ssl") diff --git a/ports/unix/variants/coverage/mpconfigvariant.h b/ports/unix/variants/coverage/mpconfigvariant.h index 11f4b2eb4b1..7695d1b91c5 100644 --- a/ports/unix/variants/coverage/mpconfigvariant.h +++ b/ports/unix/variants/coverage/mpconfigvariant.h @@ -36,14 +36,39 @@ // Enable testing of split heap. #define MICROPY_GC_SPLIT_HEAP (1) #define MICROPY_GC_SPLIT_HEAP_N_HEAPS (4) +// CIRCUITPY-CHANGE: the collector adds and frees heaps, as it does on the boards +#define MICROPY_GC_SPLIT_HEAP_AUTO (1) +#include +void *unix_alloc_heap(size_t size); +void unix_free_heap(void *heap); +#define MP_PLAT_ALLOC_HEAP(size) unix_alloc_heap(size) +#define MP_PLAT_FREE_HEAP(ptr) unix_free_heap(ptr) // Enable additional features. #define MICROPY_DEBUG_PARSE_RULE_NAME (1) +// CIRCUITPY-CHANGE: off +#define MICROPY_PY_SYS_SETTRACE (0) #define MICROPY_TRACKED_ALLOC (1) #define MICROPY_WARNINGS_CATEGORY (1) +#undef MICROPY_VFS_ROM_IOCTL +#define MICROPY_VFS_ROM_IOCTL (1) +#define MICROPY_PY_CRYPTOLIB_CTR (1) +// CIRCUITPY-CHANGE: off +#define MICROPY_SCHEDULER_STATIC_NODES (0) + +// Enable os.uname for attrtuple coverage test +#define MICROPY_PY_OS_UNAME (1) +#define MICROPY_HW_BOARD_NAME "a machine" +#define MICROPY_HW_MCU_NAME MICROPY_PY_SYS_PLATFORM +// Keep the standard banner message +#define MICROPY_BANNER_MACHINE MICROPY_PY_SYS_PLATFORM " [" MICROPY_PLATFORM_COMPILER "] version" // CIRCUITPY-CHANGE: Disable things never used in circuitpython -#define MICROPY_PY_CRYPTOLIB (0) -#define MICROPY_PY_CRYPTOLIB_CTR (0) +#define MICROPY_PY_CRYPTOLIB (0) +#undef MICROPY_PY_CRYPTOLIB_CTR +#define MICROPY_PY_CRYPTOLIB_CTR (0) +#define MICROPY_PY_MICROPYTHON_RINGIO (0) // CircuitPython uses shared-bindings struct #define MICROPY_PY_STRUCT (0) +#undef MICROPY_VFS_ROM_IOCTL +#define MICROPY_VFS_ROM_IOCTL (0) diff --git a/ports/unix/variants/coverage/mpconfigvariant.mk b/ports/unix/variants/coverage/mpconfigvariant.mk index 94a246e0199..c965684f9b0 100644 --- a/ports/unix/variants/coverage/mpconfigvariant.mk +++ b/ports/unix/variants/coverage/mpconfigvariant.mk @@ -12,7 +12,6 @@ CFLAGS += \ LDFLAGS += -fprofile-arcs -ftest-coverage FROZEN_MANIFEST ?= $(VARIANT_DIR)/manifest.py -USER_C_MODULES = $(TOP)/examples/usercmodule # CIRCUITPY-CHANGE: use CircuitPython bindings and implementations SRC_QRIO := $(patsubst ../../%,%,$(wildcard ../../shared-bindings/qrio/*.c ../../shared-module/qrio/*.c ../../lib/quirc/lib/*.c)) @@ -34,11 +33,21 @@ SRC_BITMAP := \ shared-bindings/audiocore/RawSample.c \ shared-bindings/audiocore/WaveFile.c \ shared-bindings/audiodelays/Echo.c \ + shared-bindings/audiodelays/Chorus.c \ shared-bindings/audiodelays/PitchShift.c \ + shared-bindings/audiodelays/GranularPitchShift.c \ + shared-bindings/audiodelays/MultiTapDelay.c \ + shared-bindings/audiodelays/Flanger.c \ shared-bindings/audiodelays/__init__.c \ shared-bindings/audiofilters/Distortion.c \ shared-bindings/audiofilters/Filter.c \ + shared-bindings/audiofilters/Phaser.c \ shared-bindings/audiofilters/__init__.c \ + shared-bindings/audiotap/LevelReader.c \ + shared-bindings/audiotap/Tap.c \ + shared-bindings/audiotap/__init__.c \ + shared-bindings/audiofreeverb/Freeverb.c \ + shared-bindings/audiofreeverb/__init__.c \ shared-bindings/audiomixer/__init__.c \ shared-bindings/audiomixer/Mixer.c \ shared-bindings/audiomixer/MixerVoice.c \ @@ -62,7 +71,6 @@ SRC_BITMAP := \ shared-bindings/synthio/LFO.c \ shared-bindings/synthio/Note.c \ shared-bindings/synthio/Biquad.c \ - shared-bindings/synthio/BlockBiquad.c \ shared-bindings/synthio/Synthesizer.c \ shared-bindings/traceback/__init__.c \ shared-bindings/util.c \ @@ -78,11 +86,21 @@ SRC_BITMAP := \ shared-module/audiocore/RawSample.c \ shared-module/audiocore/WaveFile.c \ shared-module/audiodelays/Echo.c \ + shared-module/audiodelays/Chorus.c \ shared-module/audiodelays/PitchShift.c \ + shared-module/audiodelays/GranularPitchShift.c \ + shared-module/audiodelays/MultiTapDelay.c \ + shared-module/audiodelays/Flanger.c \ shared-module/audiodelays/__init__.c \ shared-module/audiofilters/Distortion.c \ shared-module/audiofilters/Filter.c \ + shared-module/audiofilters/Phaser.c \ shared-module/audiofilters/__init__.c \ + shared-module/audiotap/LevelReader.c \ + shared-module/audiotap/Tap.c \ + shared-module/audiotap/__init__.c \ + shared-module/audiofreeverb/Freeverb.c \ + shared-module/audiofreeverb/__init__.c \ shared-module/audiomixer/__init__.c \ shared-module/audiomp3/MP3Decoder.c \ shared-module/audiomixer/Mixer.c \ @@ -90,13 +108,12 @@ SRC_BITMAP := \ shared-module/bitmapfilter/__init__.c \ shared-module/bitmaptools/__init__.c \ shared-module/displayio/area.c \ - shared-module/displayio/Bitmap.c \ - shared-module/displayio/ColorConverter.c \ - shared-module/displayio/Palette.c \ + shared-module/displayio/legacy/Bitmap.c \ + shared-module/displayio/legacy/ColorConverter.c \ + shared-module/displayio/legacy/Palette.c \ shared-module/floppyio/__init__.c \ shared-module/jpegio/__init__.c \ shared-module/jpegio/JpegDecoder.c \ - shared-module/os/getenv.c \ shared-module/rainbowio/__init__.c \ shared-module/struct/__init__.c \ shared-module/synthio/__init__.c \ @@ -105,14 +122,13 @@ SRC_BITMAP := \ shared-module/synthio/LFO.c \ shared-module/synthio/Note.c \ shared-module/synthio/Biquad.c \ - shared-module/synthio/BlockBiquad.c \ shared-module/synthio/Synthesizer.c \ shared-bindings/vectorio/Circle.c \ shared-module/vectorio/Circle.c \ shared-module/vectorio/__init__.c \ shared-module/vectorio/Polygon.c \ shared-module/vectorio/Rectangle.c \ - shared-module/vectorio/VectorShape.c \ + shared-module/vectorio/legacy/VectorShape.c \ shared-module/traceback/__init__.c \ shared-module/zlib/__init__.c \ @@ -138,6 +154,10 @@ SRC_C += $(addprefix lib/mp3/src/, \ $(BUILD)/lib/mp3/src/buffers.o: CFLAGS += -include "shared-module/audiomp3/__init__.h" -D'MPDEC_ALLOCATOR(x)=malloc(x)' -D'MPDEC_FREE(x)=free(x)' -fwrapv +# mp3dec.h only recognizes a fixed list of platforms and errors out on anything +# else, including aarch64. Ask for the portable C code path, like espressif does. +CFLAGS += -DMP3DEC_GENERIC + CFLAGS += \ -DCIRCUITPY_AESIO=1 \ -DCIRCUITPY_AUDIOCORE=1 \ @@ -145,9 +165,12 @@ CFLAGS += \ -DCIRCUITPY_AUDIODELAYS=1 \ -DCIRCUITPY_AUDIOFILTERS=1 \ -DCIRCUITPY_AUDIOMIXER=1 \ + -DCIRCUITPY_AUDIOMIXER_USE_PORT_MIX=0 \ + -DCIRCUITPY_AUDIOTAP=1 \ -DCIRCUITPY_AUDIOMP3=1 \ -DCIRCUITPY_AUDIOCORE_DEBUG=1 \ -DCIRCUITPY_BITMAPTOOLS=1 \ + -DCIRCUITPY_BITMAPTOOLS_FAST_ROTOZOOM=1 \ -DCIRCUITPY_CODEOP=1 \ -DCIRCUITPY_DISPLAYIO_UNIX=1 \ -DCIRCUITPY_FLOPPYIO=1 \ @@ -155,8 +178,8 @@ CFLAGS += \ -DCIRCUITPY_GIFIO=1 \ -DCIRCUITPY_JPEGIO=1 \ -DCIRCUITPY_LOCALE=1 \ - -DCIRCUITPY_OS_GETENV=1 \ -DCIRCUITPY_RAINBOWIO=1 \ + -DCIRCUITPY_SETTINGS_TOML=1 \ -DCIRCUITPY_STRUCT=1 \ -DCIRCUITPY_SYNTHIO=1 \ -DCIRCUITPY_SYNTHIO_MAX_CHANNELS=14 \ diff --git a/ports/unix/variants/longlong/mpconfigvariant.h b/ports/unix/variants/longlong/mpconfigvariant.h new file mode 100644 index 00000000000..1554d537c04 --- /dev/null +++ b/ports/unix/variants/longlong/mpconfigvariant.h @@ -0,0 +1,44 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2016 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. + */ + +// This config exists to test that the MICROPY_LONGINT_IMPL_LONGLONG variant +// (i.e. minimal form of "big integer" that's backed by 64-bit int only) builds +// and passes tests. + +#define MICROPY_LONGINT_IMPL (MICROPY_LONGINT_IMPL_LONGLONG) + +// We build it on top of REPR C, which uses memory-efficient floating point +// objects encoded directly mp_obj_t (30 bits only). +// Therefore this variant should be built for a 32-bits target. + +#define MICROPY_OBJ_REPR (MICROPY_OBJ_REPR_C) +#define MICROPY_FLOAT_IMPL (MICROPY_FLOAT_IMPL_FLOAT) + +// Set base feature level. +#define MICROPY_CONFIG_ROM_LEVEL (MICROPY_CONFIG_ROM_LEVEL_EXTRA_FEATURES) + +// Enable extra Unix features. +#include "../mpconfigvariant_common.h" diff --git a/ports/unix/variants/longlong/mpconfigvariant.mk b/ports/unix/variants/longlong/mpconfigvariant.mk new file mode 100644 index 00000000000..9fe20cd584d --- /dev/null +++ b/ports/unix/variants/longlong/mpconfigvariant.mk @@ -0,0 +1,8 @@ +# build interpreter with "bigints" implemented as "longlong" + +# This needs to be built for a 32-bits target, otherwise small ints will +# essentially be 64-bit wide. + +MICROPY_PY_FFI := 0 + +MPY_TOOL_FLAGS = -mlongint-impl longlong diff --git a/ports/unix/variants/minimal/mpconfigvariant.h b/ports/unix/variants/minimal/mpconfigvariant.h index 97ed786b8f4..0e280a8f730 100644 --- a/ports/unix/variants/minimal/mpconfigvariant.h +++ b/ports/unix/variants/minimal/mpconfigvariant.h @@ -49,6 +49,7 @@ #define MICROPY_COMP_DOUBLE_TUPLE_ASSIGN (1) #define MICROPY_ENABLE_COMPILER (1) #define MICROPY_ENABLE_EXTERNAL_IMPORT (1) +#define MICROPY_STACK_CHECK (1) #define MICROPY_FULL_CHECKS (1) #define MICROPY_HELPER_REPL (1) #define MICROPY_KBD_EXCEPTION (1) @@ -61,6 +62,5 @@ #define MICROPY_PY_BUILTINS_RANGE_ATTRS (1) #define MICROPY_PY_GENERATOR_PEND_THROW (1) -// Enable just the sys and os built-in modules. -#define MICROPY_PY_SYS (1) +// Add just the os built-in module. #define MICROPY_PY_OS (1) diff --git a/ports/unix/variants/mpconfigvariant_common.h b/ports/unix/variants/mpconfigvariant_common.h index 2e34055bf77..382579ead61 100644 --- a/ports/unix/variants/mpconfigvariant_common.h +++ b/ports/unix/variants/mpconfigvariant_common.h @@ -29,7 +29,7 @@ // Send raise KeyboardInterrupt directly from the signal handler rather than // scheduling it into the VM. -#define MICROPY_ASYNC_KBD_INTR (1) +#define MICROPY_ASYNC_KBD_INTR (!MICROPY_PY_THREAD_GIL) // Enable helpers for printing debugging information. #ifndef MICROPY_DEBUG_PRINTERS @@ -83,7 +83,9 @@ #define MICROPY_PY_GC_COLLECT_RETVAL (1) // Enable detailed error messages and warnings. +#ifndef MICROPY_ERROR_REPORTING #define MICROPY_ERROR_REPORTING (MICROPY_ERROR_REPORTING_DETAILED) +#endif #define MICROPY_WARNINGS (1) #define MICROPY_PY_STR_BYTES_CMP_WARN (1) @@ -95,7 +97,6 @@ #define MICROPY_PY_OS_INCLUDEFILE "ports/unix/modos.c" #define MICROPY_PY_OS_ERRNO (1) #define MICROPY_PY_OS_GETENV_PUTENV_UNSETENV (1) -#define MICROPY_PY_OS_SEP (1) #define MICROPY_PY_OS_SYSTEM (1) #define MICROPY_PY_OS_URANDOM (1) @@ -105,12 +106,6 @@ #define MICROPY_PY_TIME_CUSTOM_SLEEP (1) #define MICROPY_PY_TIME_INCLUDEFILE "ports/unix/modtime.c" -#if MICROPY_PY_SSL -#define MICROPY_PY_HASHLIB_MD5 (1) -#define MICROPY_PY_HASHLIB_SHA1 (1) -#define MICROPY_PY_CRYPTOLIB (1) -#endif - // The "select" module is enabled by default, but disable select.select(). #define MICROPY_PY_SELECT_POSIX_OPTIMISATIONS (1) #define MICROPY_PY_SELECT_SELECT (0) @@ -122,3 +117,6 @@ #define MICROPY_PY_MACHINE (1) #define MICROPY_PY_MACHINE_PULSE (1) #define MICROPY_PY_MACHINE_PIN_BASE (1) + +#define MICROPY_VFS_ROM (1) +#define MICROPY_VFS_ROM_IOCTL (0) diff --git a/ports/unix/variants/nanbox/mpconfigvariant.h b/ports/unix/variants/nanbox/mpconfigvariant.h index 7b13b7dc6ce..c9e9c1f63d9 100644 --- a/ports/unix/variants/nanbox/mpconfigvariant.h +++ b/ports/unix/variants/nanbox/mpconfigvariant.h @@ -41,10 +41,3 @@ #define MICROPY_EMIT_X64 (0) #define MICROPY_EMIT_THUMB (0) #define MICROPY_EMIT_ARM (0) - -#include - -typedef int64_t mp_int_t; -typedef uint64_t mp_uint_t; -#define UINT_FMT "%llu" -#define INT_FMT "%lld" diff --git a/ports/unix/variants/nanbox/mpconfigvariant.mk b/ports/unix/variants/nanbox/mpconfigvariant.mk index e588e657efc..6d63a86e9b0 100644 --- a/ports/unix/variants/nanbox/mpconfigvariant.mk +++ b/ports/unix/variants/nanbox/mpconfigvariant.mk @@ -1,3 +1,4 @@ # build interpreter with nan-boxing as object model (object repr D) -MICROPY_FORCE_32BIT = 1 +# This needs to be built for a 32-bits target, as object representation D is +# only meant to work on 32-bits machines. diff --git a/ports/zephyr-cp/.gitignore b/ports/zephyr-cp/.gitignore index 65d8deaa722..f366a85fc2a 100644 --- a/ports/zephyr-cp/.gitignore +++ b/ports/zephyr-cp/.gitignore @@ -1,7 +1,15 @@ -# West manages these folders. +# West manages these folders. modules/* are west clones, except iobroker, +# which is an in-tree Zephyr module (see modules/iobroker/README.md); its +# datasheets/ PDFs are licensed by Nordic and not redistributed here. bootloader build -modules -tools +modules/* +!modules/iobroker +modules/iobroker/datasheets/* +!modules/iobroker/datasheets/README.md +/tools zephyr +# The west workspace above, not the module descriptors of the in-tree Zephyr +# modules (internal-modules//zephyr/module.yml). +!internal-modules/*/zephyr/ .west diff --git a/ports/zephyr-cp/AGENTS.md b/ports/zephyr-cp/AGENTS.md new file mode 100644 index 00000000000..e8e240bde80 --- /dev/null +++ b/ports/zephyr-cp/AGENTS.md @@ -0,0 +1,8 @@ +- Build a board by doing `make BOARD=_`. +- The corresponding configuration files are in `boards//`, including the + board's devicetree overlay (`board.overlay`) and Kconfig fragment (`board.conf`). The Makefile + passes them to Zephyr; the overlay replaces `app.overlay`, so include it if the board wants it. +- To flash it on a board do `make BOARD=_ flash`. +- Zephyr board docs are at `zephyr/boards//`. +- Run zephyr-cp tests with `make test`. +- Do not add new translatable error strings (`MP_ERROR_TEXT`). Instead, use `raise_zephyr_error()` or `CHECK_ZEPHYR_RESULT()` from `bindings/zephyr_kernel/__init__.h` to convert Zephyr errno values into Python exceptions. diff --git a/ports/zephyr-cp/CLAUDE.md b/ports/zephyr-cp/CLAUDE.md new file mode 100644 index 00000000000..43c994c2d36 --- /dev/null +++ b/ports/zephyr-cp/CLAUDE.md @@ -0,0 +1 @@ +@AGENTS.md diff --git a/ports/zephyr-cp/CMakeLists.txt b/ports/zephyr-cp/CMakeLists.txt index e35b4b7c764..c63405d2cd2 100644 --- a/ports/zephyr-cp/CMakeLists.txt +++ b/ports/zephyr-cp/CMakeLists.txt @@ -1,10 +1,54 @@ cmake_minimum_required(VERSION 3.20.0) -find_package(Zephyr REQUIRED HINTS lib/zephyr) +# The dynamic peripheral allocation / runtime pin routing code lives in a +# Zephyr module kept in-tree for now (modules/iobroker, see its README.md). +# It must be set before find_package(Zephyr). Repoint this at the module's new + +# home to consume an externalized copy. +set(ZEPHYR_EXTRA_MODULES + ${CMAKE_CURRENT_SOURCE_DIR}/internal-modules/iobroker + # NeoPixel (WS2812-style) transmit on a runtime-chosen pin (see + # internal-modules/neopixel/README.md). + ${CMAKE_CURRENT_SOURCE_DIR}/internal-modules/neopixel + # Emulated PWM controller for native_sim tests (see + # internal-modules/pwm_emul/src/pwm_emul.c). + ${CMAKE_CURRENT_SOURCE_DIR}/internal-modules/pwm_emul + # Entropy for the WCH CH32V4x7 (see + # internal-modules/ch32v4x7_entropy/src/entropy_ch32v4x7_adc.c). + ${CMAKE_CURRENT_SOURCE_DIR}/internal-modules/ch32v4x7_entropy + # Kconfig-only module with defaults that must merge before Zephyr's + # subsystem Kconfig files (see internal-modules/circuitpython-kconfig/Kconfig). + ${CMAKE_CURRENT_SOURCE_DIR}/internal-modules/circuitpython-kconfig + # The same LVGL copy the Espressif port builds (lib/lvgl), instead of the one + # west checks out for Zephyr. It has the same module name, which zephyr_module.py + # resolves in favor of extra modules, so both ports build the same LVGL. + ${CMAKE_CURRENT_SOURCE_DIR}/../../lib/lvgl +) + +find_package(Zephyr REQUIRED HINTS ${ZEPHYR_BASE} $ENV{ZEPHYR_BASE} lib/zephyr) project(circuitpython) +include(ExternalProject) + target_sources(app PRIVATE zephyr_main.c) +# The i.MX RT10xx FlexRAM is split into OCRAM, DTCM and ITCM (64/32/32 KB on the +# RT1011), and only OCRAM is zephyr,sram. Put the kernel's no-init stacks (the +# main thread's, where the VM runs, plus the interrupt and idle stacks) in DTCM, +# as ports/mimxrt10xx does, so OCRAM is left for the heap. +if(CONFIG_SOC_SERIES_IMXRT10XX) + zephyr_code_relocate(FILES ${ZEPHYR_BASE}/kernel/init.c LOCATION DTCM_NOINIT) +endif() + +# Add native_sim test support helpers. +if(CONFIG_BOARD_NATIVE_SIM) + target_sources(app PRIVATE native_sim_i2c_emul_control.c native_sim_spi_loopback_emul.c) +endif() + +if(CONFIG_TRACING_PERFETTO) + zephyr_include_directories(${ZEPHYR_BINARY_DIR}/subsys/tracing/perfetto/proto) +endif() + # From: https://github.com/zephyrproject-rtos/zephyr/blob/main/samples/application_development/external_lib/CMakeLists.txt # The external static library that we are linking with does not know # how to build for this platform so we export all the flags used in @@ -29,8 +73,24 @@ set(external_project_cflags zephyr_get(TRANSLATION SYSBUILD GLOBAL) zephyr_get(CONFIG_LTO SYSBUILD GLOBAL) +zephyr_get(CONFIG_LVGL SYSBUILD GLOBAL) zephyr_get(BOARD_ALIAS SYSBUILD GLOBAL) +# displayio hands indexed bitmaps to LVGL as I1/I2/I4/I8 images. Decode them fully +# (instead of line by line) so they can be scaled and cached. LVGL's lv_conf_internal.h +# doesn't map a Kconfig option for this, so define it directly. +if(CONFIG_LVGL) + zephyr_compile_definitions(LV_BIN_DECODER_RAM_LOAD=1) +endif() + +# LVGL module (used by the displayio LVGL compositing core) passes its include paths to the +# CircuitPython static library build explicitly, since the core build does not consume CMake +# target information. +set(LVGL_MODULE_DIR "") +if(CONFIG_LVGL AND DEFINED ZEPHYR_LVGL_MODULE_DIR) + set(LVGL_MODULE_DIR ${ZEPHYR_LVGL_MODULE_DIR}) +endif() + ExternalProject_Add(circuitpython DOWNLOAD_COMMAND "" CONFIGURE_COMMAND "" @@ -47,6 +107,8 @@ ExternalProject_Add(circuitpython PORT_SRC_DIR=${CMAKE_CURRENT_SOURCE_DIR} TRANSLATION=${TRANSLATION} LTO=${CONFIG_LTO} + LVGL=${CONFIG_LVGL} + LVGL_DIR=${LVGL_MODULE_DIR} BUILD_BYPRODUCTS ${CMAKE_CURRENT_BINARY_DIR}/libcircuitpython.a BUILD_JOB_SERVER_AWARE TRUE BUILD_ALWAYS TRUE diff --git a/ports/zephyr-cp/Kconfig b/ports/zephyr-cp/Kconfig new file mode 100644 index 00000000000..3a952bb9a2e --- /dev/null +++ b/ports/zephyr-cp/Kconfig @@ -0,0 +1,13 @@ +# CircuitPython Zephyr port — application Kconfig +# +# Sources Zephyr's main Kconfig. CircuitPython-specific symbol defaults live +# in internal-modules/circuitpython-kconfig/Kconfig, a Kconfig-only Zephyr module: +# Zephyr merges a +# module's Kconfig right after the SoC/board defconfigs and BEFORE its kernel/, +# drivers/, lib/ and subsys/ Kconfigs, so the defaults there take precedence +# over any default Zephyr's subsystem Kconfigs define. This file is merged +# after all of Zephyr, where a Zephyr-side default would silently shadow the +# port's value (first `default` wins). Boards can override any of the defaults +# in their boards///board.conf file. + +osource "$(ZEPHYR_BASE)/Kconfig.zephyr" diff --git a/ports/zephyr-cp/Kconfig.sysbuild b/ports/zephyr-cp/Kconfig.sysbuild index cd74ff13592..cb75e861e3e 100644 --- a/ports/zephyr-cp/Kconfig.sysbuild +++ b/ports/zephyr-cp/Kconfig.sysbuild @@ -1,13 +1,16 @@ # Copyright 2023-2024 Nordic Semiconductor ASA # SPDX-License-Identifier: Apache-2.0 +# Whether a board boots via Adaboot is declared by the mcuboot fork itself, in +# bootloader/mcuboot/dts/Kconfig.sysbuild (SB_CONFIG_ADABOOT_BOARD). + source "share/sysbuild/Kconfig" config NET_CORE_BOARD string default "nrf5340dk/nrf5340/cpunet" if $(BOARD) = "nrf5340dk" - default "nrf7002dk/nrf5340/cpunet" if $(BOARD) = "nrf7002dk" default "nrf5340_audio_dk/nrf5340/cpunet" if $(BOARD) = "nrf5340_audio_dk" + default "nrf5340bsim/nrf5340/cpunet" if $(BOARD) = "nrf5340bsim" config NET_CORE_IMAGE_HCI_IPC bool "HCI IPC image on network core" diff --git a/ports/zephyr-cp/Makefile b/ports/zephyr-cp/Makefile index 217e094e3dc..69af73f9171 100644 --- a/ports/zephyr-cp/Makefile +++ b/ports/zephyr-cp/Makefile @@ -1,33 +1,282 @@ -ALL_BOARDS_IN_PORT := $($(wildcard boards/*/*):boards/=:/=) +ALL_BOARDS_IN_PORT := $(patsubst boards/%,%,$(wildcard boards/*/*)) + +# Needed to print the board list one board per line below. +empty := +space := $(empty) $(empty) +define newline + + +endef # An incorrect BOARD might have been specified, so check against the list. -# There is deliberately no space after the := -VALID_BOARD :=$(filter $(BOARD),$(ALL_BOARDS_IN_PORT)) +# Boards are stored as vendor/name but BOARD is the flattened vendor_name, so +# flatten the list the same way (vendors contain no underscores). There is +# deliberately no space after the := +VALID_BOARD :=$(filter $(BOARD),$(subst /,_,$(ALL_BOARDS_IN_PORT))) + +# Fail fast on a mistyped BOARD instead of letting west build a board the port +# isn't configured for (which dies later with confusing Kconfig errors). Targets +# like `clean` don't take a BOARD, so only check when one is given. +ifneq ($(strip $(BOARD)),) +ifeq ($(strip $(VALID_BOARD)),) +$(error Invalid BOARD '$(BOARD)'. Valid boards:$(newline)$(subst $(space),$(newline),$(subst /,_,$(ALL_BOARDS_IN_PORT)))) +endif +endif # If the build directory is not given, make it reflect the board name. BUILD ?= build-$(BOARD) TRANSLATION ?= en_US -.PHONY: $(BUILD)/zephyr-cp/zephyr/zephyr.elf flash debug clean menuconfig +# Compute shield args once. Command-line SHIELD/SHIELDS values override board defaults from circuitpython.toml. +ifneq ($(strip $(BOARD)),) +WEST_SHIELD_ARGS := $(shell SHIELD_ORIGIN="$(origin SHIELD)" SHIELDS_ORIGIN="$(origin SHIELDS)" SHIELD="$(SHIELD)" SHIELDS="$(SHIELDS)" python cptools/get_west_shield_args.py $(BOARD)) +endif + +WEST_CMAKE_ARGS := -DZEPHYR_BOARD_ALIASES=$(CURDIR)/boards/board_aliases.cmake + +# Board files live in the board's own folder as board.overlay / board.conf. Zephyr only auto-applies +# boards/.overlay and boards/.conf named after the RESOLVED Zephyr board, so it finds +# neither those (wrong directory) nor files named after a board declared through cp_board_alias() +# (wrong name) - the build silently produces a different firmware instead of warning. Pass them +# explicitly when they exist. +CP_BOARD_DIR := $(CURDIR)/boards/$(firstword $(subst _, ,$(BOARD)))/$(patsubst $(firstword $(subst _, ,$(BOARD)))_%,%,$(BOARD)) +# DTC_OVERLAY_FILE, not EXTRA_: a board overlay REPLACES app.overlay (Zephyr only falls back to +# app.overlay when no board overlay is found), which is why the board overlays here include it +# themselves - and why one board that has no USB deliberately does not. Adding the overlay instead +# would force app.overlay on every board. socs/ ships .conf only, so nothing else is displaced. +CP_BOARD_OVERLAY := $(wildcard $(CP_BOARD_DIR)/board.overlay) +ifneq ($(CP_BOARD_OVERLAY),) +WEST_CMAKE_ARGS += -Dzephyr-cp_DTC_OVERLAY_FILE=$(CP_BOARD_OVERLAY) +endif +CP_BOARD_CONF := $(wildcard $(CP_BOARD_DIR)/board.conf) + +# bsim boards link against the BabbleSim simulator checked out under tools/bsim. +# Zephyr's bsim_hw_models module requires these env vars at configure time, so +# export them here instead of relying on the caller's shell having them set. +ifneq ($(findstring bsim,$(BOARD)),) +export BSIM_COMPONENTS_PATH := $(CURDIR)/tools/bsim/components +export BSIM_OUT_PATH := $(CURDIR)/tools/bsim +endif + +# When DEBUG=1, apply additional Kconfig fragments for debug-friendly settings. +DEBUG_CONF_FILE ?= $(CURDIR)/debug.conf +ifeq ($(DEBUG),1) +CP_BOARD_CONF := $(strip $(CP_BOARD_CONF) $(DEBUG_CONF_FILE)) +endif +# When CONSOLE=1 (implied by DEBUG=1), apply the board's console.overlay, if it has one, and the +# port's console.conf. Boards whose console pins are also user pins enable the Zephyr UART console +# only then. +CONSOLE ?= $(DEBUG) +CP_BOARD_CONSOLE_OVERLAY := +ifeq ($(CONSOLE),1) +CP_BOARD_CONSOLE_OVERLAY := $(wildcard $(CP_BOARD_DIR)/console.overlay) +ifneq ($(CP_BOARD_CONSOLE_OVERLAY),) +CP_BOARD_CONF := $(strip $(CP_BOARD_CONF) $(CURDIR)/console.conf) +endif +endif +CP_BOARD_CONF := $(subst $(eval) ,;,$(CP_BOARD_CONF)) +# Always pass the conf and console overlay files, even if empty. This undoes DEBUG=1 or CONSOLE=1 +# when it's omitted on a later run. Quoted because the conf value can be a semicolon-separated +# list, and an unquoted semicolon would end the shell command. +WEST_CMAKE_ARGS += -Dzephyr-cp_EXTRA_CONF_FILE="$(CP_BOARD_CONF)" +WEST_CMAKE_ARGS += -Dzephyr-cp_EXTRA_DTC_OVERLAY_FILE="$(CP_BOARD_CONSOLE_OVERLAY)" + +# Boards can opt into building the MCUboot bootloader (and thus BLE OTA +# updates) by shipping a sysbuild.conf fragment. It sets sysbuild-level +# Kconfig (SB_CONFIG_BOOTLOADER_MCUBOOT, bootloader mode, signing keys, ...). +CP_BOARD_SYSBUILD_CONF := $(wildcard $(CP_BOARD_DIR)/sysbuild.conf) +ifneq ($(CP_BOARD_SYSBUILD_CONF),) +WEST_CMAKE_ARGS += -DSB_EXTRA_CONF_FILE=$(CP_BOARD_SYSBUILD_CONF) +endif + +# Boards that enable the bootloader can also tune the MCUboot image itself +# (Kconfig for the bootloader build) via a mcuboot.conf fragment. +CP_BOARD_MCUBOOT_CONF := $(wildcard $(CP_BOARD_DIR)/mcuboot.conf) +ifneq ($(CP_BOARD_MCUBOOT_CONF),) +WEST_CMAKE_ARGS += -Dmcuboot_EXTRA_CONF_FILE=$(CP_BOARD_MCUBOOT_CONF) +endif + +.PHONY: $(BUILD)/zephyr-cp/zephyr/zephyr.elf flash recover debug debug-jlink debugserver attach run run-sim clean menuconfig all clean-all sim clean-sim test fetch-port-submodules adaboot + +# In the environment, not a cmake argument, so a new language does not reconfigure. +export TRANSLATION + +# west reruns the whole sysbuild configure whenever it gets a cmake argument, so pass +# them only when the build directory is new or they changed since the last configure. +WEST_CONFIGURE_ARGS := -b $(BOARD) $(WEST_SHIELD_ARGS) --sysbuild -- $(WEST_CMAKE_ARGS) +WEST_ARGS_STAMP := $(BUILD)/west_configure_args.txt $(BUILD)/zephyr-cp/zephyr/zephyr.elf: python cptools/pre_zephyr_build_prep.py $(BOARD) - west build -b $(BOARD) -d $(BUILD) --sysbuild -- -DZEPHYR_BOARD_ALIASES=$(CURDIR)/boards/board_aliases.cmake -Dzephyr-cp_TRANSLATION=$(TRANSLATION) + @mkdir -p $(BUILD) + @if [ ! -f $(BUILD)/build.ninja ] || [ "$$(cat $(WEST_ARGS_STAMP) 2>/dev/null)" != '$(WEST_CONFIGURE_ARGS)' ]; then \ + echo west build -d $(BUILD) $(WEST_CONFIGURE_ARGS); \ + echo '$(WEST_CONFIGURE_ARGS)' > $(WEST_ARGS_STAMP); \ + west build -d $(BUILD) $(WEST_CONFIGURE_ARGS) || { rm -f $(WEST_ARGS_STAMP); exit 1; }; \ + else \ + echo west build -d $(BUILD); \ + west build -d $(BUILD); \ + fi + python ../../tools/build_memory_info.py $(BUILD)/zephyr-cp/zephyr/zephyr.map $(BUILD) --elf $(BUILD)/zephyr-cp/zephyr/zephyr.elf $(BUILD)/firmware.elf: $(BUILD)/zephyr-cp/zephyr/zephyr.elf cp $^ $@ +# Boards the Adaboot fork owns the memory map for (BOARD id minus its vendor +# prefix is the fork's boards.toml key): pull in its generated make fragment, +# which carries MCUBOOT_UF2_APP_BASE -- the app slot's offset within its +# flash device, i.e. the base address .uf2 files must use (Adaboot's UF2 +# writer routes blocks by flash-area offset, see boot/zephyr/uf2_disk.c). +# Like the fork's dts/ tree, the per-board conf/mk fragments live in vendor +# subdirectories; the vendor is the BOARD id's first underscore-separated +# token (the fork's boards.toml keys are board ids minus that prefix). Adafruit +# boards are the exception: their keys keep the prefix (adafruit_metro_m7), and +# the board id adds _zephyr to it (adafruit_metro_m7_zephyr). +ADABOOT_VENDOR := $(word 1,$(subst _, ,$(BOARD))) +ifneq ($(filter %_zephyr,$(BOARD)),) +ADABOOT_KEY := $(patsubst %_zephyr,%,$(BOARD)) +else +ADABOOT_KEY := $(subst $(ADABOOT_VENDOR)_,,$(BOARD)) +endif +-include bootloader/mcuboot/conf/$(ADABOOT_VENDOR)/$(ADABOOT_KEY)-autogen.mk + +# MCUBOOT_UF2_APP_BASE is only set for boards that boot via the Adaboot +# MCUboot fork: the app links into the slot0 partition, so the flashable app +# image is the signed one (MCUboot header + hash TLV), and firmware.hex +# carries both the bootloader and signed app images so it can be flashed +# directly. Standalone boards +# (adafruit/raspberrypi UF2-native, native sim, nrf54l15tag) have no +# bootloader domain and ship Zephyr's own unsigned outputs. +ifeq ($(MCUBOOT_UF2_APP_BASE),) + $(BUILD)/firmware.hex: $(BUILD)/zephyr-cp/zephyr/zephyr.elf cp $(BUILD)/zephyr-cp/zephyr/zephyr.hex $@ +$(BUILD)/firmware.uf2: $(BUILD)/zephyr-cp/zephyr/zephyr.elf + # Zephyr generates the UF2 itself, with the board's family ID and + # flash base (CONFIG_BUILD_OUTPUT_UF2*). + cp $(BUILD)/zephyr-cp/zephyr/zephyr.uf2 $@ + +else + +# west flash programs every sysbuild domain, so ship the same in one hex: +# bootloader, signed app, and the network-core image (if this board builds +# one) so it can be flashed directly with a programmer. The unsigned app +# zephyr.hex also links into slot0 but carries no MCUboot header, so the +# bootloader rejects it. +$(BUILD)/firmware.hex: $(BUILD)/zephyr-cp/zephyr/zephyr.elf $(wildcard $(BUILD)/hci_ipc/zephyr/zephyr.hex) + # hexmerge.py merges the bootloader and app images; it drops the ELF + # start-address records, as a programmer expects. + python zephyr/scripts/build/mergehex.py -o $@ $(BUILD)/mcuboot/zephyr/zephyr.hex $(BUILD)/zephyr-cp/zephyr/zephyr.signed.hex $(wildcard $(BUILD)/hci_ipc/zephyr/zephyr.hex) + +# The signed slot0 image: what an SMP device-manager uploads into slot1 for +# a BLE update (and the payload firmware.uf2 wraps). +$(BUILD)/firmware.signed.bin: $(BUILD)/zephyr-cp/zephyr/zephyr.elf + cp $(BUILD)/zephyr-cp/zephyr/zephyr.signed.bin $@ + +$(BUILD)/firmware.uf2: $(BUILD)/zephyr-cp/zephyr/zephyr.elf + # Base for uf2conv: MCUBOOT_UF2_APP_BASE from the fork's autogen .mk, + # the app slot's offset within its flash device (see the ADABOOT_KEY + # comment above). Family 0xf4b47471 is Adaboot's own; it routes blocks + # by base address, so any consistent non-zero ID is fine but keep it + # stable for bootloaders that check it. + python zephyr/scripts/build/uf2conv.py -c -f 0xf4b47471 -b $(MCUBOOT_UF2_APP_BASE) -o $@ $(BUILD)/zephyr-cp/zephyr/zephyr.signed.bin + +endif + +$(BUILD)/firmware.exe: $(BUILD)/zephyr-cp/zephyr/zephyr.elf + cp $(BUILD)/zephyr-cp/zephyr/zephyr.exe $@ + +$(BUILD)/firmware.rps: $(BUILD)/zephyr-cp/zephyr/zephyr.elf + cp $(BUILD)/zephyr-cp/zephyr/zephyr.rps $@ + flash: $(BUILD)/zephyr-cp/zephyr/zephyr.elf west flash -d $(BUILD) +recover: $(BUILD)/zephyr-cp/zephyr/zephyr.elf + west flash --recover -d $(BUILD) + debug: $(BUILD)/zephyr-cp/zephyr/zephyr.elf west debug -d $(BUILD) +debug-jlink: $(BUILD)/zephyr-cp/zephyr/zephyr.elf + west debug --runner jlink -d $(BUILD) + +debugserver: $(BUILD)/zephyr-cp/zephyr/zephyr.elf + west debugserver -d $(BUILD) + +attach: $(BUILD)/zephyr-cp/zephyr/zephyr.elf + west attach -d $(BUILD) + +run: $(BUILD)/firmware.exe + $^ + +run-sim: + $(MAKE) BOARD=native_native_sim BUILD=build-native_native_sim build-native_native_sim/firmware.exe + truncate -s 2M build-native_native_sim/flash.bin + mformat -i build-native_native_sim/flash.bin :: + @if [ -d CIRCUITPY ] && [ -n "$$(find CIRCUITPY -mindepth 1 -print -quit)" ]; then \ + echo "Populating build-native_native_sim/flash.bin from ./CIRCUITPY"; \ + mcopy -s -i build-native_native_sim/flash.bin CIRCUITPY/* ::; \ + fi + build-native_native_sim/firmware.exe --flash=build-native_native_sim/flash.bin --flash_rm -wait_uart -rt --i2s_capture=build-native_native_sim/i2s_capture.wav + menuconfig: - west build --sysbuild -d $(BUILD) -t menuconfig + west build $(WEST_SHIELD_ARGS) --sysbuild -d $(BUILD) -t menuconfig -- $(WEST_CMAKE_ARGS) + +adaboot: + west build -d $(BUILD) --domain mcuboot clean: rm -rf $(BUILD) + +fetch-port-submodules: + python ../../tools/ci_fetch_deps.py zephyr-cp + +# Build all boards. The + prefix allows jobserver file descriptors to be passed through. +# This enables parallel builds across all boards when invoked with `make -jN all`. +all: + +python cptools/build_all_boards.py --continue-on-error + +clean-all: + rm -rf build build-* + +# Build all sim boards concurrently using the same jobserver as `make all`. +sim: + +python cptools/build_all_boards.py --vendor native --continue-on-error + +clean-sim: + rm -rf $(wildcard build-native_*) + +# Every board the test suite uses: native sim (legacy + lvgl compositors, each +# with an asan variant, plus lfs) and the bsim boards (tests/bsim/conftest.py parametrizes over +# both). Zephyr samples for bsim tests are built on demand by the zephyr_sample +# fixture. +TEST_BOARDS := native_native_sim native_native_sim_lvgl native_native_sim_lvgl_asan native_native_sim_asan native_native_sim_lfs native_nrf5340bsim native_nrf54lm20bsim + +# Delegate to a sub-make with BOARD set so the per-board build rule (and its +# shield args + bsim prep) applies. The targets are phony: the west builds are +# incremental, so this just keeps the test binaries fresh. +define test_board_rule +.PHONY: test-build-$(1) +test-build-$(1): + +$$(MAKE) BOARD=$(1) BUILD=build-$(1) build-$(1)/zephyr-cp/zephyr/zephyr.elf +endef +$(foreach board,$(TEST_BOARDS),$(eval $(call test_board_rule,$(board)))) + +# CI splits this into several jobs, one board each, narrowing TEST_BOARDS and +# PYTEST_ARGS; see .github/workflows/run-zephyr-tests.yml. +PYTEST_ARGS ?= tests/ + +test: $(TEST_BOARDS:%=test-build-%) + pytest cptools/tests + pytest -v $(PYTEST_ARGS) + +# The core test suite (tests/run-tests.py) on native_sim. Pass test directories +# or files and the number of simulators in RUN_TESTS_ARGS, for example +# RUN_TESTS_ARGS="-j 8 -d basics extmod". +RUN_TESTS_ARGS ?= + +.PHONY: test-run-tests +test-run-tests: test-build-native_native_sim + python cptools/run_tests_native_sim.py $(RUN_TESTS_ARGS) diff --git a/ports/zephyr-cp/README.md b/ports/zephyr-cp/README.md index 4d08936cad6..241eb0380e3 100644 --- a/ports/zephyr-cp/README.md +++ b/ports/zephyr-cp/README.md @@ -15,19 +15,272 @@ pip install west west init -l zephyr-config west update west zephyr-export -pip install -r lib/zephyr/scripts/requirements.txt +pip install -r zephyr/scripts/requirements.txt west sdk install ``` -Now to build from the top level: +Now to build from `ports/zephyr-cp`: ```sh -make BOARD=nordic_nrf7002dk +make BOARD=nordic_nrf5340dk ``` This uses Zephyr's cmake to generate Makefiles that then delegate to `tools/cpbuild/build_circuitpython.py` to build the CircuitPython bits in parallel. +`DEBUG=1` adds the debug Kconfig settings in `debug.conf`. `CONSOLE=1` (implied +by `DEBUG=1`) applies a board's `console.overlay`, if it has one, together with +the port's `console.conf`, which turns the Zephyr UART console back on. Boards +whose console UART pins are also user pins, such as the Feather nRF52840, have +the Zephyr UART console only in those builds. + +## Native simulator build container + +Building the native sim requires `libsdl2-dev:i386` and other 32bit dependencies that +can cause conflicts on 64bit systems resulting in the removal of 64bit versions of critical +software such as the display manager and network manager. A Containerfile and a few scripts +are provided to set up a container to make the native sim build inside without affecting the +host system. + +The container automatically mounts this instance of the circuitpython repo inside at +`/home/dev/circuitpython`. Changes made in the repo inside the container and on the host PC +will sync automatically between host and container. + +To use the container file: + +1. Build the container with `podman build -t zephyr-cp-dev -f native_sim_build_Containerfile .` +2. Run/Start the container by running `./native_sim_build_run_container.sh` on the host PC. + The script will automatically run or start based on whether the container has been run before. +3. Init requirements inside the container with `./native_sim_build_init_container.sh` + +`ZCP_CONTAINER` and `ZCP_IMAGE` override the container and image names, and `ZCP_PODMAN_ARGS` +adds options to `podman run` when the container is first created. + +If `DISPLAY` is set when the container is first created, the run script shares the host's X11 +socket and a copy of your X cookie with it, so the simulator can open its display window. This +works on a Linux desktop and under WSLg. The cookie is copied with `xauth` each time the script +runs. Set `ZCP_NO_DISPLAY=1` to turn it off. A container created before this needs to be removed +with `podman rm -f zcp` and created again. + +If `west sdk install` fails with `Cannot change mode to ...: Operation not permitted`, the +container runtime is rejecting the `fchmodat2` syscall that Ubuntu 24.04's tar uses. This +happens with older runtimes such as crun 0.17 from Ubuntu 22.04. Remove the container with +`podman rm -f zcp` and create it again with `ZCP_PODMAN_ARGS="--runtime runc"` if runc is +installed, or with `ZCP_PODMAN_ARGS="--security-opt seccomp=unconfined"` otherwise. + +To delete the container and cleanup associated files: +```sh +podman ps -a --filter ancestor=zephyr-cp-dev -q | xargs -r podman rm -f +podman rmi zephyr-cp-dev +podman image prune -f +podman rm -f zcp +``` + +## Running the native simulator + +From `ports/zephyr-cp`, run: + +```sh +make run-sim +``` + +`run-sim` starts the native simulator in realtime. +It prints the PTY path to connect to the simulator REPL. +If a local `./CIRCUITPY/` folder exists, its files are used as the simulator's CIRCUITPY drive. + +Edit files in `./CIRCUITPY` (for example `code.py`) and rerun `make run-sim` to test changes. + +### Running the simulator interactively + +`make run-sim` opens a window for the simulated display and waits until something connects to +its UART before it starts CircuitPython. Look for the PTY path in its output: + +``` +uart connected to pseudotty: /dev/pts/1 +``` + +and open it from a second terminal. In the build container, open the second shell with +`podman exec -it zcp bash` and use pyserial's terminal (exit with Ctrl-]): + +```sh +python -m serial.tools.miniterm /dev/pts/1 115200 +``` + +If the container has no display (it was created without `DISPLAY` or with `ZCP_NO_DISPLAY=1`), +run the simulator as `SDL_VIDEODRIVER=dummy make run-sim`. + +### Testing LVGL with AddressSanitizer + +The `native_native_sim_lvgl_asan` board runs the LVGL displayio compositor with +AddressSanitizer enabled for CircuitPython and LVGL. It also poisons allocations in +LVGL's private `sys_heap` to catch buffer overruns and use-after-free, and stops on +the first ASan error. ASan does not replace explicit leak checks. + +```sh +make BOARD=native_native_sim_lvgl_asan +make test TEST_BOARDS=native_native_sim_lvgl_asan \ + PYTEST_ARGS="tests/ --ignore=tests/bsim -k native_native_sim_lvgl_asan" +``` + +The executable is `build-native_native_sim_lvgl_asan/zephyr-cp/zephyr/zephyr.exe`. +The regular `make test` target includes this board as well as the unsanitized LVGL +and legacy-compositor variants. + +## Running the core test suite + +`make test-run-tests` runs `tests/run-tests.py` against the native simulator. It needs +mtools and the `lib/micropython-lib` submodule (for `unittest`). By default it runs the +`basics`, `float`, `misc` and `unicode` tests on several simulators at once. Other +directories still have tests that fail on the simulator. + +```sh +make test-run-tests +make test-run-tests RUN_TESTS_ARGS="-j 4 -d basics extmod" +make test-run-tests RUN_TESTS_ARGS="basics/int1.py" +``` + +The results, including the `.exp` and `.out` files of failed tests, are in +`build-native_native_sim/run-tests/`. + +## Shields + +Board defaults can be set in `boards///circuitpython.toml`: + +```toml +SHIELDS = ["shield1", "shield2"] +``` + +For example, `boards/renesas/ek_ra8d1/circuitpython.toml` enables: + +```toml +SHIELDS = ["rtkmipilcdb00000be"] +``` + +You can override shield selection from the command line: + +```sh +# Single shield +make BOARD=renesas_ek_ra8d1 SHIELD=rtkmipilcdb00000be + +# Multiple shields (comma, semicolon, or space separated) +make BOARD=my_vendor_my_board SHIELDS="shield1,shield2" +``` + +Behavior and precedence: + +- If `SHIELD` or `SHIELDS` is explicitly provided, it overrides board defaults. +- If neither is provided, defaults from `circuitpython.toml` are used. +- Use `SHIELD=` (empty) to disable a board default shield for one build. + +## Pin names + +Human readable pin names (the `board` module) come from the devicetree by +default: `gpio-leds` and `gpio-keys` labels, node aliases, and connector +`gpio-map`s. Boards can add names without any devicetree involvement by +listing them in `boards///circuitpython.toml` under `[pins]`. +Each entry maps a board module name to the pin number exposed by the board's +hardware: the SoC package pin (or, for ball grid array packages, the +datasheet's ball id, e.g. `"B2"`), or the castellated module pin when the +board uses a module like the Raytac MDBT50Q: + +```toml +[pins] +LED = 17 # QFN package pin number +SDA = "B2" # ball id for BGA/CSP packages +D13 = 8 # MDBT50Q-1MV2 module pin number +``` + +The build resolves each package pin to a SoC pad using the iobroker package +pin map selected by `CONFIG_IOBROKER_PACKAGE_` +(`modules/iobroker/packages/.toml`) and exposes the name on the +matching pad in the `board` module. A name that already maps to the same pin +(from the devicetree or an earlier entry) is deduplicated; a name that maps +to two different pins is a build error. The package map must not be `CUSTOM` +or missing, and the pad must be on an enabled GPIO controller; otherwise the +build fails with an error naming the offending entry. + +## Connector names + +Devicetree connector nodes (`gpio-map`) get their names from a generic +per-compatible list in `cptools/zephyr2cp.py`. A board whose silkscreen +differs can override them per position in `circuitpython.toml` under +`[connectors.]`, keying the gpio-map position (the header pin +number, as a string) to a name: + +```toml +[connectors.nordic_expansion_header] +0 = "EXP_00" # header GPIO 00 +21 = "EXP_21" # header GPIO 21 (QSPI CS) +``` + +Positions left out of the table get no name. + +## OTA firmware updates over BLE + +Boards with Bluetooth and a `slot1_partition` can update CircuitPython +itself over the air. A board opts in by shipping a `sysbuild.conf` in its +board folder: + +``` +boards///sysbuild.conf: + +SB_CONFIG_BOOTLOADER_MCUBOOT=y +``` + +That makes sysbuild build the MCUboot bootloader into the board's +`boot_partition` and link the application into `slot0_partition` (it must +link into slot0 — see `nrf54lm20dk` for an example of a board that does +not). The app image is wrapped with an MCUboot header using imgtool — +signed, or hash-only when the board sets `SB_CONFIG_BOOT_SIGNATURE_TYPE_NONE` +(like `nordic_nrf54l15dk` does). The port Kconfig then enables Zephyr's +MCUmgr/SMP server over the Bluetooth SMP service: + +- `img upload` writes the uploaded image into slot 1 +- `img test`/`img confirm` plus `os reset` reboot into the new image +- the app confirms the running image once it has booted, so an update that + fails to start is automatically reverted (the `TEST_AND_CONFIRM` flow in + the reference clients) + +The service requires an encrypted connection. CircuitPython has no +display or keyboard IO capability, so authenticated (MITM) pairing can +never complete; the OTA boards pair with Just Works instead +(`CONFIG_BT_SMP_ENFORCE_MITM=n` and the SMP service's GATT permissions set +to encryption-only, in the OTA boards' `board.conf`). Once paired and +bonded, the client can upload. + +To update a device, flash it with `make BOARD= flash` (which flashes +both MCUboot and the app) and then use an SMP client such as Nordic's open +source [nRF Connect Device Manager](https://github.com/nordicsemi/Android-nRF-Connect-Device-Manager) +apps (the sample app is what's published on the app stores) or the `mcumgr` +CLI, uploading the signed app image (`zephyr.signed.bin` from the build +directory). + +### Resetting into the bootloader + +Code (and update tools) can enter the bootloader's update mode +programmatically, the way a double-tap of the reset button does: +`supervisor/port.c`'s `reset_to_bootloader()` (invoked by the 1200-bps CDC +touch) and `microcontroller.OnNextReset(RunMode.UF2 / RunMode.BOOTLOADER)` +set a request before resetting, via the adaboot fork's +`adaboot/update_mode.h` helpers. + +The mechanism depends on which bootloader the board boots: fork adaboot +(MCUboot) boards read the boot-mode retention flag, so the app needs +`RETENTION_BOOT_MODE` (defaulted in the port Kconfig for boards whose layout +provides a `zephyr,boot-mode` region) and the board's bootloader conf +(`bootloader/mcuboot/conf//.conf`) needs the matching entrance +option (`MCUBOOT_UF2_ENTRANCE_BOOT_MODE`, or `BOOT_SERIAL_BOOT_MODE` on USB-less +boards like `nrf54l15dk`). Boards that boot the stock Adafruit nRF52 +bootloader (the Adafruit boards) read the request from the raw GPREGRET +register instead and need no bootloader-side changes. + +`nordic_nrf54l15dk` is the first MCUboot board with this enabled. + +RP2 boards have no MCUboot. The request is a flag in a few bytes of RAM that +survive the reset. Early in the next boot Zephyr sees the flag and jumps to +the chip's built-in ROM bootloader, which shows up as the RPI-RP2 (RP2040) or +RP2350 UF2 drive. adaboot sets up that RAM region for the RP2 boards. + ## Testing other boards [Any Zephyr board](https://docs.zephyrproject.org/latest/boards/index.html#) can @@ -45,3 +298,13 @@ west build -b nrf52840dk/nrf52840 ``` This is already supported in `ports/nordic` as `pca10056`. + +The manifest in `zephyr-config/west.yml` skips the HALs of vendors that no board +here uses, so a board from one of them needs its entry removed from the +`name-blocklist` and a `west update` to fetch it. For the +`esp32s3_devkitc` board, that is `hal_espressif`: + +```sh +west update +west build -b esp32s3_devkitc/esp32s3/procpu +``` diff --git a/ports/zephyr-cp/app.overlay b/ports/zephyr-cp/app.overlay new file mode 100644 index 00000000000..bb2be8924f6 --- /dev/null +++ b/ports/zephyr-cp/app.overlay @@ -0,0 +1,22 @@ +&zephyr_udc0 { + cdc_acm_console: cdc_acm_console { + compatible = "zephyr,cdc-acm-uart"; + label = "CircuitPython Console"; + }; + cdc_acm_data: cdc_acm_data { + compatible = "zephyr,cdc-acm-uart"; + label = "CircuitPython Data"; + }; +}; + +/ { + hid_dev_0: hid_dev_0 { + compatible = "zephyr,hid-device"; + label = "HID0"; + protocol-code = "none"; + in-polling-period-us = <1000>; + in-report-size = <64>; + out-polling-period-us = <1000>; + out-report-size = <64>; + }; +}; diff --git a/ports/zephyr-cp/background.c b/ports/zephyr-cp/background.c index 9afade89136..56e9e98f1f2 100644 --- a/ports/zephyr-cp/background.c +++ b/ports/zephyr-cp/background.c @@ -9,17 +9,7 @@ #include "py/runtime.h" #include "supervisor/port.h" -#if CIRCUITPY_DISPLAYIO -#include "shared-module/displayio/__init__.h" -#endif - -#if CIRCUITPY_AUDIOBUSIO -#include "common-hal/audiobusio/I2SOut.h" -#endif - -#if CIRCUITPY_AUDIOPWMIO -#include "common-hal/audiopwmio/PWMAudioOut.h" -#endif +#include void port_start_background_tick(void) { } @@ -28,18 +18,12 @@ void port_finish_background_tick(void) { } void port_background_tick(void) { - #if CIRCUITPY_AUDIOPWMIO - audiopwmout_background(); - #endif - #if CIRCUITPY_AUDIOBUSIO - i2s_background(); - #endif -} - -// Allow boards to override this. -MP_WEAK void board_background_task(void) { + // No, ticks. We use Zephyr threads instead. } void port_background_task(void) { - board_background_task(); + // Make sure time advances in the simulator. + #if defined(CONFIG_ARCH_POSIX) + k_busy_wait(100); + #endif } diff --git a/ports/zephyr-cp/bindings/hostnetwork/HostNetwork.c b/ports/zephyr-cp/bindings/hostnetwork/HostNetwork.c new file mode 100644 index 00000000000..fc0fb9ecc4f --- /dev/null +++ b/ports/zephyr-cp/bindings/hostnetwork/HostNetwork.c @@ -0,0 +1,37 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "bindings/hostnetwork/HostNetwork.h" + +#include "py/runtime.h" + +//| class HostNetwork: +//| """Native networking for the host simulator.""" +//| +//| def __init__(self) -> None: +//| """Create a HostNetwork instance.""" +//| ... +//| +static mp_obj_t hostnetwork_hostnetwork_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, 0, false); + + hostnetwork_hostnetwork_obj_t *self = mp_obj_malloc(hostnetwork_hostnetwork_obj_t, &hostnetwork_hostnetwork_type); + common_hal_hostnetwork_hostnetwork_construct(self); + return MP_OBJ_FROM_PTR(self); +} + +static const mp_rom_map_elem_t hostnetwork_hostnetwork_locals_dict_table[] = { +}; +static MP_DEFINE_CONST_DICT(hostnetwork_hostnetwork_locals_dict, hostnetwork_hostnetwork_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + hostnetwork_hostnetwork_type, + MP_QSTR_HostNetwork, + MP_TYPE_FLAG_NONE, + make_new, hostnetwork_hostnetwork_make_new, + locals_dict, &hostnetwork_hostnetwork_locals_dict + ); diff --git a/ports/zephyr-cp/bindings/hostnetwork/HostNetwork.h b/ports/zephyr-cp/bindings/hostnetwork/HostNetwork.h new file mode 100644 index 00000000000..009d8c06087 --- /dev/null +++ b/ports/zephyr-cp/bindings/hostnetwork/HostNetwork.h @@ -0,0 +1,19 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include + +#include "py/obj.h" + +typedef struct { + mp_obj_base_t base; +} hostnetwork_hostnetwork_obj_t; + +extern const mp_obj_type_t hostnetwork_hostnetwork_type; + +void common_hal_hostnetwork_hostnetwork_construct(hostnetwork_hostnetwork_obj_t *self); diff --git a/ports/zephyr-cp/bindings/hostnetwork/__init__.c b/ports/zephyr-cp/bindings/hostnetwork/__init__.c new file mode 100644 index 00000000000..92302b67d0e --- /dev/null +++ b/ports/zephyr-cp/bindings/hostnetwork/__init__.c @@ -0,0 +1,26 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "py/obj.h" + +#include "bindings/hostnetwork/__init__.h" +#include "bindings/hostnetwork/HostNetwork.h" + +//| """Host networking support for the native simulator.""" +//| + +static const mp_rom_map_elem_t hostnetwork_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_hostnetwork) }, + { MP_ROM_QSTR(MP_QSTR_HostNetwork), MP_ROM_PTR(&hostnetwork_hostnetwork_type) }, +}; +static MP_DEFINE_CONST_DICT(hostnetwork_module_globals, hostnetwork_module_globals_table); + +const mp_obj_module_t hostnetwork_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&hostnetwork_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_hostnetwork, hostnetwork_module); diff --git a/ports/zephyr-cp/bindings/hostnetwork/__init__.h b/ports/zephyr-cp/bindings/hostnetwork/__init__.h new file mode 100644 index 00000000000..a6731546bde --- /dev/null +++ b/ports/zephyr-cp/bindings/hostnetwork/__init__.h @@ -0,0 +1,11 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "bindings/hostnetwork/HostNetwork.h" + +extern hostnetwork_hostnetwork_obj_t common_hal_hostnetwork_obj; diff --git a/ports/zephyr-cp/bindings/zephyr_display/Display.c b/ports/zephyr-cp/bindings/zephyr_display/Display.c new file mode 100644 index 00000000000..c09f131cc73 --- /dev/null +++ b/ports/zephyr-cp/bindings/zephyr_display/Display.c @@ -0,0 +1,317 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "bindings/zephyr_display/Display.h" + +#include + +#include "bindings/zephyr_kernel/__init__.h" +#include "py/objproperty.h" +#include "py/objtype.h" +#include "py/runtime.h" +#include "shared-bindings/displayio/__init__.h" +#include "shared-bindings/displayio/Group.h" +#include "shared-bindings/util.h" +#include "shared-module/displayio/__init__.h" + +//| class Display: +//| """Manage the display selected by the Zephyr devicetree +//| +//| There is no display bus argument because the device comes from the +//| ``zephyr,display`` chosen devicetree node. +//| +//| Creating a `Display` releases the display built during startup +//| (``supervisor.runtime.display``), as with other display classes.""" +//| +// The current implementation composites with LVGL, which drives only one display and draws +// from its own fixed-size heap (CONFIG_LV_Z_MEM_POOL_SIZE). Those are implementation details, +// so they stay out of the docs above, but they explain why only one Display can exist and why +// complex scenes can fail inside the draw code instead of raising MemoryError. +//| def __init__(self, *, rotation: int = 0, auto_refresh: bool = True) -> None: +//| """Create a `Display` for the ``zephyr,display`` device. +//| +//| :param int rotation: The rotation of the display in degrees. Must be a multiple +//| of 90. +//| :param bool auto_refresh: Automatically refresh the screen. +//| """ +//| ... +//| +static mp_obj_t zephyr_display_display_make_new(const mp_obj_type_t *type, + size_t n_args, + size_t n_kw, + const mp_obj_t *all_args) { + enum { ARG_rotation, ARG_auto_refresh }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_rotation, MP_ARG_KW_ONLY | MP_ARG_INT, { .u_int = 0 } }, + { MP_QSTR_auto_refresh, MP_ARG_KW_ONLY | MP_ARG_BOOL, { .u_bool = true } }, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + mp_int_t rotation = args[ARG_rotation].u_int; + if (rotation % 90 != 0) { + mp_raise_ValueError(MP_ERROR_TEXT("Display rotation must be in 90 degree increments")); + } + + const struct device *display_dev = device_get_binding(DEVICE_DT_NAME(DT_CHOSEN(zephyr_display))); + if (display_dev == NULL || !device_is_ready(display_dev)) { + raise_zephyr_error(-ENODEV); + } + + // The display device is a singleton and LVGL drives only one display at a time, so the one + // board_init() made has to be released first (as with any other display class). + primary_display_t *display_obj = allocate_display_or_raise(); + zephyr_display_display_obj_t *self = &display_obj->zephyr_display; + self->base.type = &zephyr_display_display_type; + common_hal_zephyr_display_display_construct_from_device(self, display_dev, rotation, + args[ARG_auto_refresh].u_bool); + return MP_OBJ_FROM_PTR(self); +} + +// Helper to ensure we have the native super class instead of a subclass. +// Raises if the display has been released. +static zephyr_display_display_obj_t *native_display(mp_obj_t display_obj) { + mp_obj_t native = mp_obj_cast_to_native_base(display_obj, &zephyr_display_display_type); + if (native == MP_OBJ_NULL) { + raise_deinited_error(); + } + mp_obj_assert_native_inited(native); + zephyr_display_display_obj_t *self = MP_OBJ_TO_PTR(native); + if (self->base.type != &zephyr_display_display_type) { + raise_deinited_error(); + } + return self; +} + +//| def deinit(self) -> None: +//| """Release the display. A new `Display` can then be created. +//| +//| To release the display built during startup, use +//| ``supervisor.runtime.display.deinit()``. +//| As of CircuitPython 11.0.0, this replaces `displayio.release_displays()`, which is deprecated. +//| """ +//| ... +//| +static mp_obj_t zephyr_display_display_obj_deinit(mp_obj_t self_in) { + mp_obj_t native = mp_obj_cast_to_native_base(self_in, &zephyr_display_display_type); + if (native != MP_OBJ_NULL) { + common_hal_displayio_deinit_display(native); + } + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_1(zephyr_display_display_deinit_obj, zephyr_display_display_obj_deinit); + +static mp_obj_t zephyr_display_display_obj_show(mp_obj_t self_in, mp_obj_t group_in) { + (void)self_in; + (void)group_in; + mp_raise_AttributeError(MP_ERROR_TEXT(".show(x) removed. Use .root_group = x")); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(zephyr_display_display_show_obj, zephyr_display_display_obj_show); + +//| def refresh( +//| self, +//| *, +//| target_frames_per_second: Optional[int] = None, +//| minimum_frames_per_second: int = 0, +//| ) -> bool: +//| """When auto_refresh is off, and ``target_frames_per_second`` is not `None` this +//| waits for the target frame rate and then refreshes the display, returning +//| `True`. If the call has taken too long since the last refresh call for the given +//| target frame rate, then the refresh returns `False` immediately without updating +//| the screen to try to keep latency low. +//| +//| If the time since the last successful refresh is below the minimum frame rate, +//| then an exception will be raised. The default ``minimum_frames_per_second`` of 0 +//| disables this behavior. +//| +//| When auto_refresh is off, and ``target_frames_per_second`` is `None` this will +//| update the display immediately. When auto_refresh is on, it updates the display +//| immediately too; the display also updates without calls to this. +//| +//| :param Optional[int] target_frames_per_second: The target frame rate that +//| :py:func:`refresh` should try to achieve. Set to `None` for immediate +//| refresh. +//| :param int minimum_frames_per_second: The minimum number of times the screen +//| should be updated per second. +//| """ +//| ... +//| +static mp_obj_t zephyr_display_display_obj_refresh(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { + ARG_target_frames_per_second, + ARG_minimum_frames_per_second, + }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_target_frames_per_second, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = mp_const_none} }, + { MP_QSTR_minimum_frames_per_second, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, + }; + + 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); + + zephyr_display_display_obj_t *self = native_display(pos_args[0]); + + uint32_t maximum_ms_per_real_frame = NO_FPS_LIMIT; + mp_int_t minimum_frames_per_second = args[ARG_minimum_frames_per_second].u_int; + if (minimum_frames_per_second > 0) { + maximum_ms_per_real_frame = 1000 / minimum_frames_per_second; + } + + uint32_t target_ms_per_frame; + if (args[ARG_target_frames_per_second].u_obj == mp_const_none) { + target_ms_per_frame = NO_FPS_LIMIT; + } else { + target_ms_per_frame = 1000 / mp_obj_get_int(args[ARG_target_frames_per_second].u_obj); + } + + return mp_obj_new_bool(common_hal_zephyr_display_display_refresh( + self, + target_ms_per_frame, + maximum_ms_per_real_frame)); +} +MP_DEFINE_CONST_FUN_OBJ_KW(zephyr_display_display_refresh_obj, 1, zephyr_display_display_obj_refresh); + +//| auto_refresh: bool +//| """True when the display is refreshed automatically.""" +static mp_obj_t zephyr_display_display_obj_get_auto_refresh(mp_obj_t self_in) { + zephyr_display_display_obj_t *self = native_display(self_in); + return mp_obj_new_bool(common_hal_zephyr_display_display_get_auto_refresh(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(zephyr_display_display_get_auto_refresh_obj, zephyr_display_display_obj_get_auto_refresh); + +static mp_obj_t zephyr_display_display_obj_set_auto_refresh(mp_obj_t self_in, mp_obj_t auto_refresh) { + zephyr_display_display_obj_t *self = native_display(self_in); + common_hal_zephyr_display_display_set_auto_refresh(self, mp_obj_is_true(auto_refresh)); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(zephyr_display_display_set_auto_refresh_obj, zephyr_display_display_obj_set_auto_refresh); + +MP_PROPERTY_GETSET(zephyr_display_display_auto_refresh_obj, + (mp_obj_t)&zephyr_display_display_get_auto_refresh_obj, + (mp_obj_t)&zephyr_display_display_set_auto_refresh_obj); + +//| brightness: float +//| """The brightness of the display as a float. 0.0 is off and 1.0 is full brightness. +//| +//| .. note:: Zephyr displays do not implement brightness control yet, so reading or +//| writing this raises `RuntimeError`.""" +static mp_obj_t zephyr_display_display_obj_get_brightness(mp_obj_t self_in) { + zephyr_display_display_obj_t *self = native_display(self_in); + mp_float_t brightness = common_hal_zephyr_display_display_get_brightness(self); + if (brightness < 0) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Brightness not adjustable")); + } + return mp_obj_new_float(brightness); +} +MP_DEFINE_CONST_FUN_OBJ_1(zephyr_display_display_get_brightness_obj, zephyr_display_display_obj_get_brightness); + +static mp_obj_t zephyr_display_display_obj_set_brightness(mp_obj_t self_in, mp_obj_t brightness_obj) { + zephyr_display_display_obj_t *self = native_display(self_in); + mp_float_t brightness = mp_obj_get_float(brightness_obj); + if (brightness < 0.0f || brightness > 1.0f) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("%q must be %d-%d"), MP_QSTR_brightness, 0, 1); + } + bool ok = common_hal_zephyr_display_display_set_brightness(self, brightness); + if (!ok) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Brightness not adjustable")); + } + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(zephyr_display_display_set_brightness_obj, zephyr_display_display_obj_set_brightness); + +MP_PROPERTY_GETSET(zephyr_display_display_brightness_obj, + (mp_obj_t)&zephyr_display_display_get_brightness_obj, + (mp_obj_t)&zephyr_display_display_set_brightness_obj); + +//| width: int +//| """The width of the display in pixels, with rotation applied.""" +static mp_obj_t zephyr_display_display_obj_get_width(mp_obj_t self_in) { + zephyr_display_display_obj_t *self = native_display(self_in); + return MP_OBJ_NEW_SMALL_INT(common_hal_zephyr_display_display_get_width(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(zephyr_display_display_get_width_obj, zephyr_display_display_obj_get_width); +MP_PROPERTY_GETTER(zephyr_display_display_width_obj, (mp_obj_t)&zephyr_display_display_get_width_obj); + +//| height: int +//| """The height of the display in pixels, with rotation applied.""" +static mp_obj_t zephyr_display_display_obj_get_height(mp_obj_t self_in) { + zephyr_display_display_obj_t *self = native_display(self_in); + return MP_OBJ_NEW_SMALL_INT(common_hal_zephyr_display_display_get_height(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(zephyr_display_display_get_height_obj, zephyr_display_display_obj_get_height); +MP_PROPERTY_GETTER(zephyr_display_display_height_obj, (mp_obj_t)&zephyr_display_display_get_height_obj); + +//| rotation: int +//| """The rotation of the display in degrees.""" +static mp_obj_t zephyr_display_display_obj_get_rotation(mp_obj_t self_in) { + zephyr_display_display_obj_t *self = native_display(self_in); + return MP_OBJ_NEW_SMALL_INT(common_hal_zephyr_display_display_get_rotation(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(zephyr_display_display_get_rotation_obj, zephyr_display_display_obj_get_rotation); + +static mp_obj_t zephyr_display_display_obj_set_rotation(mp_obj_t self_in, mp_obj_t value) { + zephyr_display_display_obj_t *self = native_display(self_in); + common_hal_zephyr_display_display_set_rotation(self, mp_obj_get_int(value)); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(zephyr_display_display_set_rotation_obj, zephyr_display_display_obj_set_rotation); + +MP_PROPERTY_GETSET(zephyr_display_display_rotation_obj, + (mp_obj_t)&zephyr_display_display_get_rotation_obj, + (mp_obj_t)&zephyr_display_display_set_rotation_obj); + +//| root_group: Optional[displayio.Group] +//| """The `displayio.Group` that is drawn on the display, or `None` when the display +//| is cleared. +//| +//| A `displayio.Group` can only be the root group of one display at a time. Setting a +//| group that is already in use raises `ValueError`.""" +static mp_obj_t zephyr_display_display_obj_get_root_group(mp_obj_t self_in) { + zephyr_display_display_obj_t *self = native_display(self_in); + return common_hal_zephyr_display_display_get_root_group(self); +} +MP_DEFINE_CONST_FUN_OBJ_1(zephyr_display_display_get_root_group_obj, zephyr_display_display_obj_get_root_group); + +static mp_obj_t zephyr_display_display_obj_set_root_group(mp_obj_t self_in, mp_obj_t group_in) { + zephyr_display_display_obj_t *self = native_display(self_in); + displayio_group_t *group = NULL; + if (group_in != mp_const_none) { + group = MP_OBJ_TO_PTR(native_group(group_in)); + } + + bool ok = common_hal_zephyr_display_display_set_root_group(self, group); + if (!ok) { + mp_raise_ValueError(MP_ERROR_TEXT("Group already used")); + } + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(zephyr_display_display_set_root_group_obj, zephyr_display_display_obj_set_root_group); + +MP_PROPERTY_GETSET(zephyr_display_display_root_group_obj, + (mp_obj_t)&zephyr_display_display_get_root_group_obj, + (mp_obj_t)&zephyr_display_display_set_root_group_obj); + +static const mp_rom_map_elem_t zephyr_display_display_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&zephyr_display_display_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR_show), MP_ROM_PTR(&zephyr_display_display_show_obj) }, + { MP_ROM_QSTR(MP_QSTR_refresh), MP_ROM_PTR(&zephyr_display_display_refresh_obj) }, + + { MP_ROM_QSTR(MP_QSTR_auto_refresh), MP_ROM_PTR(&zephyr_display_display_auto_refresh_obj) }, + { MP_ROM_QSTR(MP_QSTR_brightness), MP_ROM_PTR(&zephyr_display_display_brightness_obj) }, + { MP_ROM_QSTR(MP_QSTR_width), MP_ROM_PTR(&zephyr_display_display_width_obj) }, + { MP_ROM_QSTR(MP_QSTR_height), MP_ROM_PTR(&zephyr_display_display_height_obj) }, + { MP_ROM_QSTR(MP_QSTR_rotation), MP_ROM_PTR(&zephyr_display_display_rotation_obj) }, + { MP_ROM_QSTR(MP_QSTR_root_group), MP_ROM_PTR(&zephyr_display_display_root_group_obj) }, +}; +static MP_DEFINE_CONST_DICT(zephyr_display_display_locals_dict, zephyr_display_display_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + zephyr_display_display_type, + MP_QSTR_Display, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, zephyr_display_display_make_new, + locals_dict, &zephyr_display_display_locals_dict); diff --git a/ports/zephyr-cp/bindings/zephyr_display/Display.h b/ports/zephyr-cp/bindings/zephyr_display/Display.h new file mode 100644 index 00000000000..80693228520 --- /dev/null +++ b/ports/zephyr-cp/bindings/zephyr_display/Display.h @@ -0,0 +1,41 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-module/displayio/Group.h" +#include "common-hal/zephyr_display/Display.h" + +extern const mp_obj_type_t zephyr_display_display_type; + +// Port hooks for the LVGL compositor (see shared-module/displayio/lvgl/lvgl_internal.h). +void displayio_lvgl_port_lock(void); +void displayio_lvgl_port_unlock(void); + +#define NO_FPS_LIMIT 0xffffffff + +void common_hal_zephyr_display_display_construct_from_device(zephyr_display_display_obj_t *self, + const struct device *device, + uint16_t rotation, + bool auto_refresh); + +bool common_hal_zephyr_display_display_refresh(zephyr_display_display_obj_t *self, + uint32_t target_ms_per_frame, + uint32_t maximum_ms_per_real_frame); + +bool common_hal_zephyr_display_display_get_auto_refresh(zephyr_display_display_obj_t *self); +void common_hal_zephyr_display_display_set_auto_refresh(zephyr_display_display_obj_t *self, bool auto_refresh); + +uint16_t common_hal_zephyr_display_display_get_width(zephyr_display_display_obj_t *self); +uint16_t common_hal_zephyr_display_display_get_height(zephyr_display_display_obj_t *self); +uint16_t common_hal_zephyr_display_display_get_rotation(zephyr_display_display_obj_t *self); +void common_hal_zephyr_display_display_set_rotation(zephyr_display_display_obj_t *self, int rotation); + +mp_float_t common_hal_zephyr_display_display_get_brightness(zephyr_display_display_obj_t *self); +bool common_hal_zephyr_display_display_set_brightness(zephyr_display_display_obj_t *self, mp_float_t brightness); + +mp_obj_t common_hal_zephyr_display_display_get_root_group(zephyr_display_display_obj_t *self); +bool common_hal_zephyr_display_display_set_root_group(zephyr_display_display_obj_t *self, displayio_group_t *root_group); diff --git a/ports/zephyr-cp/bindings/zephyr_display/__init__.c b/ports/zephyr-cp/bindings/zephyr_display/__init__.c new file mode 100644 index 00000000000..180f8572977 --- /dev/null +++ b/ports/zephyr-cp/bindings/zephyr_display/__init__.c @@ -0,0 +1,39 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "py/obj.h" +#include "py/runtime.h" + +#include "bindings/zephyr_display/Display.h" + +//| """Display access for Zephyr boards +//| +//| This module provides `Display`, a `displayio` display class for the device selected by +//| the ``zephyr,display`` devicetree chosen property. +//| +//| .. note:: This module is Zephyr-specific. On other ports the equivalent class is one of +//| the `displayio` display classes, such as `busdisplay.BusDisplay`. +//| """ +// +// The current implementation composites with LVGL, which draws from its own fixed-size heap +// (CONFIG_LV_Z_MEM_POOL_SIZE) instead of the Python heap and drives only one display. Both are +// implementation details rather than part of this class's contract, so they aren't documented +// above, but they explain why complex scenes can fail inside LVGL and why only one `Display` +// can exist. + +static const mp_rom_map_elem_t zephyr_display_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_zephyr_display) }, + { MP_ROM_QSTR(MP_QSTR_Display), MP_ROM_PTR(&zephyr_display_display_type) }, +}; + +static MP_DEFINE_CONST_DICT(zephyr_display_module_globals, zephyr_display_module_globals_table); + +const mp_obj_module_t zephyr_display_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&zephyr_display_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_zephyr_display, zephyr_display_module); diff --git a/ports/zephyr-cp/bindings/zephyr_display/__init__.h b/ports/zephyr-cp/bindings/zephyr_display/__init__.h new file mode 100644 index 00000000000..4256bfac2fe --- /dev/null +++ b/ports/zephyr-cp/bindings/zephyr_display/__init__.h @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once diff --git a/ports/zephyr-cp/bindings/zephyr_input/__init__.c b/ports/zephyr-cp/bindings/zephyr_input/__init__.c new file mode 100644 index 00000000000..36560af8a30 --- /dev/null +++ b/ports/zephyr-cp/bindings/zephyr_input/__init__.c @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: MIT + +#include +#include + +#include "py/obj.h" +#include "py/runtime.h" +#include "zephyr/input/input.h" + +typedef struct { + int32_t x; + int32_t y; + bool pressed; +} zephyr_input_touch_state_t; +static zephyr_input_touch_state_t touch_state; +static zephyr_input_touch_state_t buffered_touch_state; + +static void zephyr_input_callback(struct input_event *event, void *user_data) { + (void)user_data; + if (event->type == INPUT_EV_ABS && event->code == INPUT_ABS_X) { + touch_state.x = event->value; + } else if (event->type == INPUT_EV_ABS && event->code == INPUT_ABS_Y) { + touch_state.y = event->value; + } else if (event->type == INPUT_EV_KEY && event->code == INPUT_BTN_TOUCH) { + touch_state.pressed = event->value != 0; + } + // Like the GT911 driver, retain the latest complete touch sample. + if (event->sync) { + buffered_touch_state = touch_state; + } +} + +INPUT_CALLBACK_DEFINE(NULL, zephyr_input_callback, NULL); + +//| """Access input devices provided by Zephyr.""" +//| +//| def touch() -> tuple[int, int] | None: +//| """Return the latest buffered touch coordinates, or ``None`` when released. +//| +//| On native_sim, SDL mouse button and motion events are reported as touch. +//| """ +//| ... +static mp_obj_t zephyr_input_touch(void) { + if (!buffered_touch_state.pressed) { + return mp_const_none; + } + mp_obj_t coordinates[] = { + mp_obj_new_int(buffered_touch_state.x), + mp_obj_new_int(buffered_touch_state.y), + }; + return mp_obj_new_tuple(2, coordinates); +} +static MP_DEFINE_CONST_FUN_OBJ_0(zephyr_input_touch_obj, zephyr_input_touch); + +static const mp_rom_map_elem_t zephyr_input_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_zephyr_input) }, + { MP_ROM_QSTR(MP_QSTR_touch), MP_ROM_PTR(&zephyr_input_touch_obj) }, +}; +static MP_DEFINE_CONST_DICT(zephyr_input_module_globals, zephyr_input_module_globals_table); + +const mp_obj_module_t zephyr_input_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&zephyr_input_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_zephyr_input, zephyr_input_module); diff --git a/ports/zephyr-cp/bindings/zephyr_serial/UART.c b/ports/zephyr-cp/bindings/zephyr_serial/UART.c deleted file mode 100644 index dbb643645f5..00000000000 --- a/ports/zephyr-cp/bindings/zephyr_serial/UART.c +++ /dev/null @@ -1,291 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2016 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include - -#include "bindings/zephyr_serial/UART.h" -#include "shared-bindings/microcontroller/Pin.h" -#include "shared-bindings/util.h" - -#include "shared/runtime/context_manager_helpers.h" -#include "shared/runtime/interrupt_char.h" - -#include "py/stream.h" -#include "py/objproperty.h" -#include "py/objtype.h" -#include "py/runtime.h" -#include "py/stream.h" - -#define STREAM_DEBUG(...) (void)0 -// #define STREAM_DEBUG(...) mp_printf(&mp_plat_print __VA_OPT__(,) __VA_ARGS__) - -//| class UART: -//| """A bidirectional serial protocol. Already initialized for Zephyr defined -//| busses in :py:mod:`board`. -//| -//| .. raw:: html -//| -//|

-//|

-//| Available on these boards -//|
    -//| {% for board in support_matrix_reverse["zephyr_serial.UART"] %} -//|
  • {{ board }} -//| {% endfor %} -//|
-//|
-//|

-//| -//| """ -//| - -static void validate_timeout(mp_float_t timeout) { - mp_arg_validate_int_range((int)timeout, 0, 100, MP_QSTR_timeout); -} - -// Helper to ensure we have the native super class instead of a subclass. -static zephyr_serial_uart_obj_t *native_uart(mp_obj_t uart_obj) { - mp_obj_t native_uart = mp_obj_cast_to_native_base(uart_obj, MP_OBJ_FROM_PTR(&zephyr_serial_uart_type)); - if (native_uart == MP_OBJ_NULL) { - mp_raise_ValueError_varg(MP_ERROR_TEXT("Must be a %q subclass."), MP_QSTR_UART); - } - mp_obj_assert_native_inited(native_uart); - return MP_OBJ_TO_PTR(native_uart); -} - - -//| def deinit(self) -> None: -//| """Deinitialises the UART and releases any hardware resources for reuse.""" -//| ... -//| -static mp_obj_t _zephyr_serial_uart_obj_deinit(mp_obj_t self_in) { - zephyr_serial_uart_obj_t *self = native_uart(self_in); - zephyr_serial_uart_deinit(self); - return mp_const_none; -} -static MP_DEFINE_CONST_FUN_OBJ_1(_zephyr_serial_uart_deinit_obj, _zephyr_serial_uart_obj_deinit); - -static void check_for_deinit(zephyr_serial_uart_obj_t *self) { - if (zephyr_serial_uart_deinited(self)) { - raise_deinited_error(); - } -} - -//| def __enter__(self) -> UART: -//| """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.""" -//| ... -//| -// Provided by context manager helper. - -// These are standard stream methods. Code is in py/stream.c. -// -//| def read(self, nbytes: Optional[int] = None) -> Optional[bytes]: -//| """Read bytes. If ``nbytes`` is specified then read at most that many -//| bytes. Otherwise, read everything that arrives until the connection -//| times out. Providing the number of bytes expected is highly recommended -//| because it will be faster. If no bytes are read, return ``None``. -//| -//| .. note:: When no bytes are read due to a timeout, this function returns ``None``. -//| This matches the behavior of `io.RawIOBase.read` in Python 3, but -//| differs from pyserial which returns ``b''`` in that situation. -//| -//| :return: Data read -//| :rtype: bytes or None""" -//| ... -//| - -//| def readinto(self, buf: WriteableBuffer) -> Optional[int]: -//| """Read bytes into the ``buf``. Read at most ``len(buf)`` bytes. -//| -//| :return: number of bytes read and stored into ``buf`` -//| :rtype: int or None (on a non-blocking error) -//| -//| *New in CircuitPython 4.0:* No length parameter is permitted.""" -//| ... -//| - -//| def readline(self) -> bytes: -//| """Read a line, ending in a newline character, or -//| return ``None`` if a timeout occurs sooner, or -//| return everything readable if no newline is found and -//| ``timeout=0`` -//| -//| :return: the line read -//| :rtype: bytes or None""" -//| ... -//| - -//| def write(self, buf: ReadableBuffer) -> Optional[int]: -//| """Write the buffer of bytes to the bus. -//| -//| *New in CircuitPython 4.0:* ``buf`` must be bytes, not a string. -//| -//| :return: the number of bytes written -//| :rtype: int or None""" -//| ... -//| - -// These three methods are used by the shared stream methods. -static mp_uint_t _zephyr_serial_uart_read(mp_obj_t self_in, void *buf_in, mp_uint_t size, int *errcode) { - STREAM_DEBUG("_zephyr_serial_uart_read stream %d\n", size); - zephyr_serial_uart_obj_t *self = native_uart(self_in); - check_for_deinit(self); - byte *buf = buf_in; - - // make sure we want at least 1 char - if (size == 0) { - return 0; - } - - return zephyr_serial_uart_read(self, buf, size, errcode); -} - -static mp_uint_t _zephyr_serial_uart_write(mp_obj_t self_in, const void *buf_in, mp_uint_t size, int *errcode) { - zephyr_serial_uart_obj_t *self = native_uart(self_in); - check_for_deinit(self); - const byte *buf = buf_in; - - return zephyr_serial_uart_write(self, buf, size, errcode); -} - -static mp_uint_t _zephyr_serial_uart_ioctl(mp_obj_t self_in, mp_uint_t request, mp_uint_t arg, int *errcode) { - zephyr_serial_uart_obj_t *self = native_uart(self_in); - check_for_deinit(self); - mp_uint_t ret; - if (request == MP_STREAM_POLL) { - mp_uint_t flags = arg; - ret = 0; - if ((flags & MP_STREAM_POLL_RD) && zephyr_serial_uart_rx_characters_available(self) > 0) { - ret |= MP_STREAM_POLL_RD; - } - if ((flags & MP_STREAM_POLL_WR) && zephyr_serial_uart_ready_to_tx(self)) { - ret |= MP_STREAM_POLL_WR; - } - } else { - *errcode = MP_EINVAL; - ret = MP_STREAM_ERROR; - } - return ret; -} - -//| baudrate: int -//| """The current baudrate.""" -static mp_obj_t _zephyr_serial_uart_obj_get_baudrate(mp_obj_t self_in) { - zephyr_serial_uart_obj_t *self = native_uart(self_in); - check_for_deinit(self); - return MP_OBJ_NEW_SMALL_INT(zephyr_serial_uart_get_baudrate(self)); -} -MP_DEFINE_CONST_FUN_OBJ_1(_zephyr_serial_uart_get_baudrate_obj, _zephyr_serial_uart_obj_get_baudrate); - -static mp_obj_t _zephyr_serial_uart_obj_set_baudrate(mp_obj_t self_in, mp_obj_t baudrate) { - zephyr_serial_uart_obj_t *self = native_uart(self_in); - check_for_deinit(self); - zephyr_serial_uart_set_baudrate(self, mp_obj_get_int(baudrate)); - return mp_const_none; -} -MP_DEFINE_CONST_FUN_OBJ_2(_zephyr_serial_uart_set_baudrate_obj, _zephyr_serial_uart_obj_set_baudrate); - - -MP_PROPERTY_GETSET(_zephyr_serial_uart_baudrate_obj, - (mp_obj_t)&_zephyr_serial_uart_get_baudrate_obj, - (mp_obj_t)&_zephyr_serial_uart_set_baudrate_obj); - -//| in_waiting: int -//| """The number of bytes in the input buffer, available to be read""" -static mp_obj_t _zephyr_serial_uart_obj_get_in_waiting(mp_obj_t self_in) { - zephyr_serial_uart_obj_t *self = native_uart(self_in); - check_for_deinit(self); - return MP_OBJ_NEW_SMALL_INT(zephyr_serial_uart_rx_characters_available(self)); -} -MP_DEFINE_CONST_FUN_OBJ_1(_zephyr_serial_uart_get_in_waiting_obj, _zephyr_serial_uart_obj_get_in_waiting); - -MP_PROPERTY_GETTER(_zephyr_serial_uart_in_waiting_obj, - (mp_obj_t)&_zephyr_serial_uart_get_in_waiting_obj); - -//| timeout: float -//| """The current timeout, in seconds (float).""" -//| -static mp_obj_t _zephyr_serial_uart_obj_get_timeout(mp_obj_t self_in) { - zephyr_serial_uart_obj_t *self = native_uart(self_in); - check_for_deinit(self); - return mp_obj_new_float(zephyr_serial_uart_get_timeout(self)); -} -MP_DEFINE_CONST_FUN_OBJ_1(_zephyr_serial_uart_get_timeout_obj, _zephyr_serial_uart_obj_get_timeout); - -static mp_obj_t _zephyr_serial_uart_obj_set_timeout(mp_obj_t self_in, mp_obj_t timeout) { - zephyr_serial_uart_obj_t *self = native_uart(self_in); - check_for_deinit(self); - mp_float_t timeout_float = mp_obj_get_float(timeout); - validate_timeout(timeout_float); - zephyr_serial_uart_set_timeout(self, timeout_float); - return mp_const_none; -} -MP_DEFINE_CONST_FUN_OBJ_2(_zephyr_serial_uart_set_timeout_obj, _zephyr_serial_uart_obj_set_timeout); - - -MP_PROPERTY_GETSET(_zephyr_serial_uart_timeout_obj, - (mp_obj_t)&_zephyr_serial_uart_get_timeout_obj, - (mp_obj_t)&_zephyr_serial_uart_set_timeout_obj); - -//| def reset_input_buffer(self) -> None: -//| """Discard any unread characters in the input buffer.""" -//| ... -//| -//| -static mp_obj_t _zephyr_serial_uart_obj_reset_input_buffer(mp_obj_t self_in) { - zephyr_serial_uart_obj_t *self = native_uart(self_in); - check_for_deinit(self); - zephyr_serial_uart_clear_rx_buffer(self); - return mp_const_none; -} -static MP_DEFINE_CONST_FUN_OBJ_1(_zephyr_serial_uart_reset_input_buffer_obj, _zephyr_serial_uart_obj_reset_input_buffer); - -static const mp_rom_map_elem_t _zephyr_serial_uart_locals_dict_table[] = { - { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&_zephyr_serial_uart_deinit_obj) }, - { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&_zephyr_serial_uart_deinit_obj) }, - { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, - { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, - - // Standard stream methods. - { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) }, - { MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj)}, - { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) }, - { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) }, - - { MP_ROM_QSTR(MP_QSTR_reset_input_buffer), MP_ROM_PTR(&_zephyr_serial_uart_reset_input_buffer_obj) }, - - // Properties - { MP_ROM_QSTR(MP_QSTR_baudrate), MP_ROM_PTR(&_zephyr_serial_uart_baudrate_obj) }, - { MP_ROM_QSTR(MP_QSTR_in_waiting), MP_ROM_PTR(&_zephyr_serial_uart_in_waiting_obj) }, - { MP_ROM_QSTR(MP_QSTR_timeout), MP_ROM_PTR(&_zephyr_serial_uart_timeout_obj) }, - -}; -static MP_DEFINE_CONST_DICT(_zephyr_serial_uart_locals_dict, _zephyr_serial_uart_locals_dict_table); - -static const mp_stream_p_t uart_stream_p = { - .read = _zephyr_serial_uart_read, - .write = _zephyr_serial_uart_write, - .ioctl = _zephyr_serial_uart_ioctl, - .is_text = false, - // Disallow optional length argument for .readinto() - .pyserial_readinto_compatibility = true, -}; - -MP_DEFINE_CONST_OBJ_TYPE( - zephyr_serial_uart_type, - MP_QSTR_UART, - MP_TYPE_FLAG_ITER_IS_ITERNEXT | MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, - locals_dict, &_zephyr_serial_uart_locals_dict, - iter, mp_stream_unbuffered_iter, - protocol, &uart_stream_p - ); diff --git a/ports/zephyr-cp/bindings/zephyr_serial/UART.h b/ports/zephyr-cp/bindings/zephyr_serial/UART.h deleted file mode 100644 index 704b9a2d605..00000000000 --- a/ports/zephyr-cp/bindings/zephyr_serial/UART.h +++ /dev/null @@ -1,41 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2016 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#pragma once - -#include "common-hal/microcontroller/Pin.h" -#include "common-hal/zephyr_serial/UART.h" -#include "py/ringbuf.h" - -#include - -extern const mp_obj_type_t zephyr_serial_uart_type; - -// Construct an underlying UART object. -extern void zephyr_serial_uart_construct(zephyr_serial_uart_obj_t *self, - const struct device *const uart_device, uint16_t receiver_buffer_size, byte *receiver_buffer); - -extern void zephyr_serial_uart_deinit(zephyr_serial_uart_obj_t *self); -extern bool zephyr_serial_uart_deinited(zephyr_serial_uart_obj_t *self); - -// Read characters. len is in characters NOT bytes! -extern size_t zephyr_serial_uart_read(zephyr_serial_uart_obj_t *self, - uint8_t *data, size_t len, int *errcode); - -// Write characters. len is in characters NOT bytes! -extern size_t zephyr_serial_uart_write(zephyr_serial_uart_obj_t *self, - const uint8_t *data, size_t len, int *errcode); - -extern uint32_t zephyr_serial_uart_get_baudrate(zephyr_serial_uart_obj_t *self); -extern void zephyr_serial_uart_set_baudrate(zephyr_serial_uart_obj_t *self, uint32_t baudrate); -extern mp_float_t zephyr_serial_uart_get_timeout(zephyr_serial_uart_obj_t *self); -extern void zephyr_serial_uart_set_timeout(zephyr_serial_uart_obj_t *self, mp_float_t timeout); - -extern uint32_t zephyr_serial_uart_rx_characters_available(zephyr_serial_uart_obj_t *self); -extern void zephyr_serial_uart_clear_rx_buffer(zephyr_serial_uart_obj_t *self); -extern bool zephyr_serial_uart_ready_to_tx(zephyr_serial_uart_obj_t *self); - -extern void zephyr_serial_uart_never_reset(zephyr_serial_uart_obj_t *self); diff --git a/ports/zephyr-cp/bindings/zephyr_serial/__init__.c b/ports/zephyr-cp/bindings/zephyr_serial/__init__.c deleted file mode 100644 index f4a3c7b92e3..00000000000 --- a/ports/zephyr-cp/bindings/zephyr_serial/__init__.c +++ /dev/null @@ -1,32 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2016 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include - -#include "py/obj.h" -#include "py/runtime.h" - -#include "shared-bindings/microcontroller/Pin.h" -#include "bindings/zephyr_serial/__init__.h" -#include "bindings/zephyr_serial/UART.h" - -#include "py/runtime.h" - -//| """Zephyr UART driver for fixed busses.""" - -static const mp_rom_map_elem_t zephyr_serial_module_globals_table[] = { - { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_zephyr_serial) }, - { MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&zephyr_serial_uart_type) }, -}; - -static MP_DEFINE_CONST_DICT(zephyr_serial_module_globals, zephyr_serial_module_globals_table); - -const mp_obj_module_t zephyr_serial_module = { - .base = { &mp_type_module }, - .globals = (mp_obj_dict_t *)&zephyr_serial_module_globals, -}; - -MP_REGISTER_MODULE(MP_QSTR_zephyr_serial, zephyr_serial_module); diff --git a/ports/zephyr-cp/boards/adafruit/circuitplayground_bluefruit_zephyr/autogen_board_info.toml b/ports/zephyr-cp/boards/adafruit/circuitplayground_bluefruit_zephyr/autogen_board_info.toml new file mode 100644 index 00000000000..8e03c9a4ca4 --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/circuitplayground_bluefruit_zephyr/autogen_board_info.toml @@ -0,0 +1,145 @@ +# This file is autogenerated when a board is built. Do not edit. Do commit it to git. Other scripts use its info. +name = "Adafruit Circuit Playground Bluefruit" + +[modules] +__future__ = true +_airlift = false +_bleio = true # Zephyr board has _bleio +_eve = false +_pew = false +_pixelmap = true # Zephyr board has neopixel_write +_stage = false +adafruit_bus_device = true +adafruit_pixelbuf = true # Zephyr board has neopixel_write +aesio = true +alarm = false +analogbufio = false +analogio = true # Zephyr board has analogio +async_spi = true # Zephyr board has async_spi +atexit = true +audiobusio = false +audiocore = false +audiodelays = false +audiofilewriter = false +audiofilters = false +audiofreeverb = false +audioi2sin = false +audioio = false +audiomixer = false +audiomp3 = false +audiopwmio = false +audiospeed = false +audiotap = false +aurora_epaper = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio +bitops = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio +camera = false +canio = false +codeop = true +countio = false +cryptography = false +digitalio = true +displayio = true # Zephyr board has busio +dotclockframebuffer = false +dualbank = false +emmcio = false +epaperdisplay = true # Zephyr board has busio +floppyio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio +frequencyio = false +getpass = true +gifio = true # Zephyr board has busio +gnss = false +hardwarekey = false +hashlib = true +hmac = false +hostnetwork = false +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false +i2ctarget = false +imagecapture = false +ipaddress = false +is31fl3741 = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true +max3421e = false +mcp4822 = false +mdns = false +memorymap = false +memorymonitor = false +microcontroller = true +mii = false +mipicsi = false +mipidsi = false +msgpack = true +neopixel_write = true # Zephyr board has neopixel_write +nvm = true # Board has NVM partition +onewireio = false +os = true +paralleldisplaybus = false +picogame = false +picogame3d = false +ps2io = false +pulseio = false +pwmio = true # Zephyr board has pwmio +qrio = false +qspibus = false +rainbowio = true +random = true +rclcpy = false +rgbmatrix = false +rotaryio = true # Zephyr board has rotaryio +rtc = false +sdcardio = true # Zephyr board has busio +sdioio = false +sharpdisplay = true # Zephyr board has busio +socketpool = false +spitarget = false +ssl = false +storage = true # Zephyr board has flash +struct = true +supervisor = true +synthio = false +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio +time = true +touchio = true +traceback = true +uheap = false +usb = false +usb_audio = false +usb_cdc = true +usb_hid = true +usb_host = false +usb_host_audio = false +usb_host_bulk = false +usb_midi = false +usb_video = false +ustack = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog +wifi = false +zephyr_display = false +zephyr_input = true # Zephyr board has zephyr_input +zephyr_kernel = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/adafruit/circuitplayground_bluefruit_zephyr/board.conf b/ports/zephyr-cp/boards/adafruit/circuitplayground_bluefruit_zephyr/board.conf new file mode 100644 index 00000000000..14455847fb0 --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/circuitplayground_bluefruit_zephyr/board.conf @@ -0,0 +1,18 @@ +CONFIG_BOARD_SERIAL_BACKEND_CDC_ACM=n + +# The board overlay deletes the Zephyr chosen console/shell/mcumgr nodes: +# CircuitPython drives USB CDC ACM through its own usb_cdc bindings. Turn off +# Zephyr's UART console so nothing references the deleted +# DT_CHOSEN(zephyr_console). SERIAL stays on for the dynamically routed UART. +CONFIG_UART_CONSOLE=n +CONFIG_LOG_BACKEND_UART=n + +# The CPB has a bare nRF52840, so pin numbers are aQFN73 package pins. +CONFIG_IOBROKER_PACKAGE_NRF52840_AQFN73=y + +# PWM instances are enabled in board.overlay with disconnected outputs so +# iobroker can allocate them at runtime for neopixel_write and pwmio. +CONFIG_PWM=y + +# SAADC for analogio testing/use (pads resolve to AIN through iobroker) +CONFIG_ADC=y diff --git a/ports/zephyr-cp/boards/adafruit/circuitplayground_bluefruit_zephyr/board.overlay b/ports/zephyr-cp/boards/adafruit/circuitplayground_bluefruit_zephyr/board.overlay new file mode 100644 index 00000000000..6829088e22e --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/circuitplayground_bluefruit_zephyr/board.overlay @@ -0,0 +1,280 @@ +/* Partition layout is owned by the mcuboot fork + * (dts/adafruit/adafruit_circuitplayground_bluefruit.dtsi) and applied to + * this image by sysbuild. This overlay only adds board/app config. */ +/* No Zephyr console by default, so TX/RX are free for busio.UART. A CONSOLE=1 + * build puts the console back on UART0 (console.overlay). */ +/ { + chosen { + /delete-property/ zephyr,console; + /delete-property/ zephyr,shell-uart; + /delete-property/ zephyr,uart-mcumgr; + /delete-property/ zephyr,bt-mon-uart; + /delete-property/ zephyr,bt-c2h-uart; + }; +}; + +&zephyr_udc0 { + /delete-node/ board_cdc_acm_uart; +}; + +// UART0, I2C0, I2C1, SPI2 and SPI3 are enabled with all pins disconnected and +// marked zephyr,deferred-init so nothing is claimed at boot: the iobroker +// initializes and routes a device to arbitrary pins when a busio object is +// constructed, and de-initializes it on release. (QSPI is the fixed external +// flash. The onboard sensors, such as the LIS3DH on +// ACCELEROMETER_SCL/ACCELEROMETER_SDA, have no devicetree nodes, so no I2C +// instance needs to be fixed.) +// +// See "nRF serial instances" in internal-modules/iobroker/README.md for how +// the instances are shared and allocated. +// +// I2C1 and SPI1 are the same peripheral instance (0x40004000), so only one +// mode can be enabled: I2C is the more useful dynamic bus, and two I2C +// instances let board.I2C() and the accelerometer bus be open at once. +// SPI1 is left disabled; UART1 is enabled by neither overlay because UART0 +// already provides a dynamic serial instance. + +&pinctrl { + uart0_dyn_default: uart0_dyn_default { + group1 { + psels = , + ; + }; + }; + + uart0_dyn_sleep: uart0_dyn_sleep { + group1 { + psels = , + ; + }; + }; + + i2c0_dyn_default: i2c0_dyn_default { + group1 { + psels = , + ; + }; + }; + + i2c0_dyn_sleep: i2c0_dyn_sleep { + group1 { + psels = , + ; + }; + }; + + i2c1_dyn_default: i2c1_dyn_default { + group1 { + psels = , + ; + }; + }; + + i2c1_dyn_sleep: i2c1_dyn_sleep { + group1 { + psels = , + ; + }; + }; + + spi2_dyn_default: spi2_dyn_default { + group1 { + psels = , + , + ; + }; + }; + + spi2_dyn_sleep: spi2_dyn_sleep { + group1 { + psels = , + , + ; + }; + }; + + spi3_dyn_default: spi3_dyn_default { + group1 { + psels = , + , + ; + }; + }; + + spi3_dyn_sleep: spi3_dyn_sleep { + group1 { + psels = , + , + ; + }; + }; + + pwm0_dyn_default: pwm0_dyn_default { + group1 { + psels = , + , + , + ; + }; + }; + + pwm0_dyn_sleep: pwm0_dyn_sleep { + group1 { + psels = , + , + , + ; + }; + }; + + pwm1_dyn_default: pwm1_dyn_default { + group1 { + psels = , + , + , + ; + }; + }; + + pwm1_dyn_sleep: pwm1_dyn_sleep { + group1 { + psels = , + , + , + ; + }; + }; + + pwm2_dyn_default: pwm2_dyn_default { + group1 { + psels = , + , + , + ; + }; + }; + + pwm2_dyn_sleep: pwm2_dyn_sleep { + group1 { + psels = , + , + , + ; + }; + }; + + pwm3_dyn_default: pwm3_dyn_default { + group1 { + psels = , + , + , + ; + }; + }; + + pwm3_dyn_sleep: pwm3_dyn_sleep { + group1 { + psels = , + , + , + ; + }; + }; +}; + +// The upstream board uses the legacy UART driver for UART0, which can't be +// de-initialized, so iobroker could not route it again once it was released. +// Instead, use the UARTE driver, which can be deinited. +&uart0 { + compatible = "nordic,nrf-uarte"; + status = "okay"; + zephyr,deferred-init; + current-speed = <115200>; + pinctrl-0 = <&uart0_dyn_default>; + pinctrl-1 = <&uart0_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +// The upstream board fixes I2C0 to SCL/SDA with the legacy TWI driver. Use +// TWIM like I2C1 so iobroker can route it. +&i2c0 { + compatible = "nordic,nrf-twim"; + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&i2c0_dyn_default>; + pinctrl-1 = <&i2c0_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&i2c1 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&i2c1_dyn_default>; + pinctrl-1 = <&i2c1_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +// SPI1 shares the 0x40004000 instance with I2C1, which is enabled above, so +// leave SPI1 disabled. +&spi1 { + status = "disabled"; +}; + +&spi2 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&spi2_dyn_default>; + pinctrl-1 = <&spi2_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&spi3 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&spi3_dyn_default>; + pinctrl-1 = <&spi3_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +// PWM instances, same scheme: all four outputs disconnected and deferred +// init, so iobroker can hand an instance to neopixel_write and pwmio and +// route its outputs at runtime. + +&pwm0 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&pwm0_dyn_default>; + pinctrl-1 = <&pwm0_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&pwm1 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&pwm1_dyn_default>; + pinctrl-1 = <&pwm1_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&pwm2 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&pwm2_dyn_default>; + pinctrl-1 = <&pwm2_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&pwm3 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&pwm3_dyn_default>; + pinctrl-1 = <&pwm3_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +#include "../../../app.overlay" + +/* Enable the SAADC for analogio (AIN0..AIN7 are on P0.02..P0.05 and P0.28..P0.31). */ +&adc { + status = "okay"; +}; diff --git a/ports/zephyr-cp/boards/adafruit/circuitplayground_bluefruit_zephyr/circuitpython.toml b/ports/zephyr-cp/boards/adafruit/circuitplayground_bluefruit_zephyr/circuitpython.toml new file mode 100644 index 00000000000..6a0506fc84d --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/circuitplayground_bluefruit_zephyr/circuitpython.toml @@ -0,0 +1,63 @@ +CIRCUITPY_BUILD_EXTENSIONS = ["hex", "uf2"] +USB_VID=0x239A +USB_PID=0x8046 +NAME="Circuit Playground Bluefruit" +VENDOR="Adafruit" + +# Non-Zephyr build of the same board; nvm and CIRCUITPY must sit where it puts them. +counterpart = "nordic/circuitplayground_bluefruit" + +# Status RGB LED, driven with neopixel_write; name from [pins]. +STATUS_NEOPIXEL = "NEOPIXEL" + + +[pins] +# Pin names copied from the ports/ counterpart board's pins.c and resolved +# to nRF52840 aQFN73 package pin numbers through the package pin map +# selected in board.conf. +AUDIO = 27 # P0.26 +D12 = 27 # P0.26 +SPEAKER = 27 # P0.26 +A1 = 3 # P0.02 +D6 = 3 # P0.02 +SCK = 3 # P0.02 +A2 = 2 # P0.29 +D9 = 2 # P0.29 +MISO = 2 # P0.29 +A3 = 16 # P0.03 +D10 = 16 # P0.03 +MOSI = 16 # P0.03 +A4 = 30 # P0.04 +D3 = 30 # P0.04 +SCL = 30 # P0.04 +A5 = 32 # P0.05 +D2 = 32 # P0.05 +SDA = 32 # P0.05 +A6 = 14 # P0.30 +D0 = 14 # P0.30 +RX = 14 # P0.30 +D1 = 54 # P0.14 +TX = 54 # P0.14 +LIGHT = 15 # P0.28 +A8 = 15 # P0.28 +TEMPERATURE = 1 # P0.31 +A9 = 1 # P0.31 +BUTTON_A = 48 # P1.02 +D4 = 48 # P1.02 +BUTTON_B = 4 # P1.15 +D5 = 4 # P1.15 +SLIDE_SWITCH = 41 # P1.06 +D7 = 41 # P1.06 +POWER_SWITCH = 33 # P0.06 +D35 = 33 # P0.06 +LED = 17 # P1.14 +L = 17 # P1.14 +D13 = 17 # P1.14 +NEOPIXEL = 65 # P0.13 +D8 = 65 # P0.13 +MICROPHONE_CLOCK = 67 # P0.17 +MICROPHONE_DATA = 55 # P0.16 +ACCELEROMETER_INTERRUPT = 5 # P1.13 +ACCELEROMETER_SDA = 7 # P1.10 +ACCELEROMETER_SCL = 18 # P1.12 +SPEAKER_ENABLE = 45 # P1.04 diff --git a/ports/zephyr-cp/boards/adafruit/circuitplayground_bluefruit_zephyr/console.overlay b/ports/zephyr-cp/boards/adafruit/circuitplayground_bluefruit_zephyr/console.overlay new file mode 100644 index 00000000000..095c4aa1d2d --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/circuitplayground_bluefruit_zephyr/console.overlay @@ -0,0 +1,18 @@ +/* Applied after board.overlay in CONSOLE=1 and DEBUG=1 builds: the Zephyr + * console on UART0, fixed to the TX/RX pins. TX/RX are then not available to + * busio.UART. */ +/ { + chosen { + zephyr,console = &uart0; + zephyr,shell-uart = &uart0; + zephyr,uart-mcumgr = &uart0; + zephyr,bt-mon-uart = &uart0; + zephyr,bt-c2h-uart = &uart0; + }; +}; + +&uart0 { + /delete-property/ zephyr,deferred-init; + pinctrl-0 = <&uart0_default>; + pinctrl-1 = <&uart0_sleep>; +}; diff --git a/ports/zephyr-cp/boards/adafruit/clue_nrf52840_zephyr/autogen_board_info.toml b/ports/zephyr-cp/boards/adafruit/clue_nrf52840_zephyr/autogen_board_info.toml new file mode 100644 index 00000000000..b92f125b4ef --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/clue_nrf52840_zephyr/autogen_board_info.toml @@ -0,0 +1,145 @@ +# This file is autogenerated when a board is built. Do not edit. Do commit it to git. Other scripts use its info. +name = "Adafruit CLUE nRF52840 Express" + +[modules] +__future__ = true +_airlift = false +_bleio = true # Zephyr board has _bleio +_eve = false +_pew = false +_pixelmap = true # Zephyr board has neopixel_write +_stage = false +adafruit_bus_device = true +adafruit_pixelbuf = true # Zephyr board has neopixel_write +aesio = true +alarm = false +analogbufio = false +analogio = true # Zephyr board has analogio +async_spi = true # Zephyr board has async_spi +atexit = true +audiobusio = false +audiocore = false +audiodelays = false +audiofilewriter = false +audiofilters = false +audiofreeverb = false +audioi2sin = false +audioio = false +audiomixer = false +audiomp3 = false +audiopwmio = false +audiospeed = false +audiotap = false +aurora_epaper = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio +bitops = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio +camera = false +canio = false +codeop = true +countio = false +cryptography = false +digitalio = true +displayio = true # Zephyr board has displayio +dotclockframebuffer = false +dualbank = false +emmcio = false +epaperdisplay = true # Zephyr board has busio +floppyio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio +frequencyio = false +getpass = true +gifio = true # Zephyr board has busio +gnss = false +hardwarekey = false +hashlib = true +hmac = false +hostnetwork = false +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false +i2ctarget = false +imagecapture = false +ipaddress = false +is31fl3741 = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true +max3421e = false +mcp4822 = false +mdns = false +memorymap = false +memorymonitor = false +microcontroller = true +mii = false +mipicsi = false +mipidsi = false +msgpack = true +neopixel_write = true # Zephyr board has neopixel_write +nvm = true # Board has NVM partition +onewireio = false +os = true +paralleldisplaybus = false +picogame = false +picogame3d = false +ps2io = false +pulseio = false +pwmio = true # Zephyr board has pwmio +qrio = false +qspibus = false +rainbowio = true +random = true +rclcpy = false +rgbmatrix = false +rotaryio = true # Zephyr board has rotaryio +rtc = false +sdcardio = true # Zephyr board has busio +sdioio = false +sharpdisplay = true # Zephyr board has busio +socketpool = false +spitarget = false +ssl = false +storage = true # Zephyr board has flash +struct = true +supervisor = true +synthio = false +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio +time = true +touchio = true +traceback = true +uheap = false +usb = false +usb_audio = false +usb_cdc = true +usb_hid = true +usb_host = false +usb_host_audio = false +usb_host_bulk = false +usb_midi = false +usb_video = false +ustack = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog +wifi = false +zephyr_display = true # Zephyr board has zephyr_display +zephyr_input = true # Zephyr board has zephyr_input +zephyr_kernel = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/adafruit/clue_nrf52840_zephyr/board.conf b/ports/zephyr-cp/boards/adafruit/clue_nrf52840_zephyr/board.conf new file mode 100644 index 00000000000..26ff6d9ad58 --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/clue_nrf52840_zephyr/board.conf @@ -0,0 +1,22 @@ +CONFIG_BOARD_SERIAL_BACKEND_CDC_ACM=n + +# The board overlay deletes the Zephyr chosen console/shell/mcumgr nodes: +# CircuitPython drives USB CDC ACM through its own usb_cdc bindings. Turn off +# Zephyr's UART console so nothing references the deleted +# DT_CHOSEN(zephyr_console). SERIAL stays on for the dynamically routed UART. +CONFIG_UART_CONSOLE=n +CONFIG_LOG_BACKEND_UART=n + +# Enable the ST7789V TFT via the Zephyr display subsystem +CONFIG_DISPLAY=y + +# Pin numbers are module pins (MDBT50Q-1MV2 carries the aQFN73 inside). +# The CLUE uses the MDBT50Q-1MV2 module, so pin numbers are module pins. +CONFIG_IOBROKER_PACKAGE_MDBT50Q_1MV2=y + +# PWM instances are enabled in board.overlay with disconnected outputs so +# iobroker can allocate them at runtime for neopixel_write and pwmio. +CONFIG_PWM=y + +# SAADC for analogio testing/use (pads resolve to AIN through iobroker) +CONFIG_ADC=y diff --git a/ports/zephyr-cp/boards/adafruit/clue_nrf52840_zephyr/board.overlay b/ports/zephyr-cp/boards/adafruit/clue_nrf52840_zephyr/board.overlay new file mode 100644 index 00000000000..fedbc1b0429 --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/clue_nrf52840_zephyr/board.overlay @@ -0,0 +1,265 @@ +/* Partition layout is owned by the mcuboot fork + * (dts/adafruit/adafruit_clue_nrf52840.dtsi) and applied to this image by + * sysbuild. This overlay only adds board/app config. */ +/* No Zephyr console by default, so TX/RX are free for busio.UART. A CONSOLE=1 + * build puts the console back on UART0 (console.overlay). */ +/ { + chosen { + /delete-property/ zephyr,console; + /delete-property/ zephyr,shell-uart; + /delete-property/ zephyr,uart-mcumgr; + /delete-property/ zephyr,bt-mon-uart; + /delete-property/ zephyr,bt-c2h-uart; + }; + + // The STEMMA QT connector is on SCL/SDA, so board.STEMMA_I2C is the same + // bus as board.I2C(). The upstream board has no node for it. + stemma_connector: stemma_connector { + compatible = "stemma-qt-connector"; + #gpio-cells = <2>; + gpio-map-mask = <0xffffffff 0xffffffc0>; + gpio-map-pass-thru = <0 0x3f>; + gpio-map = <0 0 &gpio0 25 0>, /* SCL */ + <1 0 &gpio0 24 0>; /* SDA */ + }; +}; + +&zephyr_udc0 { + /delete-node/ board_cdc_acm_uart; +}; + +// UART0, I2C0, I2C1 and SPI3 are enabled with all pins disconnected and +// marked zephyr,deferred-init so nothing is claimed at boot: the iobroker +// initializes and routes a device to arbitrary pins when a busio object is +// constructed, and de-initializes it on release. (SPI2 is the fixed display +// bus and QSPI the fixed external flash. The onboard sensors are on SCL/SDA +// but have no devicetree nodes, so I2C0 does not need to be fixed.) +// +// See "nRF serial instances" in internal-modules/iobroker/README.md for how +// the instances are shared and allocated. +// +// I2C1 and SPI1 are the same peripheral instance (0x40004000), so only one +// mode can be enabled: I2C is the more useful dynamic bus on the CLUE. +// SPI1 is left disabled; UART1 is enabled by neither overlay because UART0 +// already provides a dynamic serial instance. + +&pinctrl { + uart0_dyn_default: uart0_dyn_default { + group1 { + psels = , + ; + }; + }; + + uart0_dyn_sleep: uart0_dyn_sleep { + group1 { + psels = , + ; + }; + }; + + i2c0_dyn_default: i2c0_dyn_default { + group1 { + psels = , + ; + }; + }; + + i2c0_dyn_sleep: i2c0_dyn_sleep { + group1 { + psels = , + ; + }; + }; + + i2c1_dyn_default: i2c1_dyn_default { + group1 { + psels = , + ; + }; + }; + + i2c1_dyn_sleep: i2c1_dyn_sleep { + group1 { + psels = , + ; + }; + }; + + spi3_dyn_default: spi3_dyn_default { + group1 { + psels = , + , + ; + }; + }; + + spi3_dyn_sleep: spi3_dyn_sleep { + group1 { + psels = , + , + ; + }; + }; + + pwm0_dyn_default: pwm0_dyn_default { + group1 { + psels = , + , + , + ; + }; + }; + + pwm0_dyn_sleep: pwm0_dyn_sleep { + group1 { + psels = , + , + , + ; + }; + }; + + pwm1_dyn_default: pwm1_dyn_default { + group1 { + psels = , + , + , + ; + }; + }; + + pwm1_dyn_sleep: pwm1_dyn_sleep { + group1 { + psels = , + , + , + ; + }; + }; + + pwm2_dyn_default: pwm2_dyn_default { + group1 { + psels = , + , + , + ; + }; + }; + + pwm2_dyn_sleep: pwm2_dyn_sleep { + group1 { + psels = , + , + , + ; + }; + }; + + pwm3_dyn_default: pwm3_dyn_default { + group1 { + psels = , + , + , + ; + }; + }; + + pwm3_dyn_sleep: pwm3_dyn_sleep { + group1 { + psels = , + , + , + ; + }; + }; +}; + +// The upstream board uses the legacy UART driver for UART0, which can't be +// de-initialized, so iobroker could not route it again once it was released. +// Instead, use the UARTE driver, which can be deinited. +&uart0 { + compatible = "nordic,nrf-uarte"; + status = "okay"; + zephyr,deferred-init; + current-speed = <115200>; + pinctrl-0 = <&uart0_dyn_default>; + pinctrl-1 = <&uart0_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +// The upstream board fixes I2C0 to SCL/SDA with the legacy TWI driver. Use +// TWIM like I2C1 so iobroker can route it. +&i2c0 { + compatible = "nordic,nrf-twim"; + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&i2c0_dyn_default>; + pinctrl-1 = <&i2c0_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&i2c1 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&i2c1_dyn_default>; + pinctrl-1 = <&i2c1_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +// SPI1 shares the 0x40004000 instance with I2C1, which is enabled above, so +// leave SPI1 disabled. +&spi1 { + status = "disabled"; +}; + +&spi3 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&spi3_dyn_default>; + pinctrl-1 = <&spi3_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +// PWM instances, same scheme: all four outputs disconnected and deferred +// init, so iobroker can hand an instance to neopixel_write and pwmio and +// route its outputs at runtime. + +&pwm0 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&pwm0_dyn_default>; + pinctrl-1 = <&pwm0_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&pwm1 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&pwm1_dyn_default>; + pinctrl-1 = <&pwm1_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&pwm2 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&pwm2_dyn_default>; + pinctrl-1 = <&pwm2_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&pwm3 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&pwm3_dyn_default>; + pinctrl-1 = <&pwm3_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +#include "../../../app.overlay" + +/* Enable the SAADC for analogio (AIN0..AIN7 are on P0.02..P0.05 and P0.28..P0.31). */ +&adc { + status = "okay"; +}; diff --git a/ports/zephyr-cp/boards/adafruit/clue_nrf52840_zephyr/circuitpython.toml b/ports/zephyr-cp/boards/adafruit/clue_nrf52840_zephyr/circuitpython.toml new file mode 100644 index 00000000000..e8dbeeac17d --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/clue_nrf52840_zephyr/circuitpython.toml @@ -0,0 +1,94 @@ +CIRCUITPY_BUILD_EXTENSIONS = ["hex", "uf2"] +USB_VID=0x239A +USB_PID=0x8072 +NAME="CLUE nRF52840 Express" +VENDOR="Adafruit" + +# Non-Zephyr build of the same board; nvm and CIRCUITPY must sit where it puts them. +counterpart = "nordic/clue_nrf52840_express" + +# Status RGB LED, driven with neopixel_write; name from [pins]. +STATUS_NEOPIXEL = "NEOPIXEL" + + +# Pin names copied from the ports/ counterpart board's pins.c and resolved +# through the package pin map selected in board.conf. + +[pins] +# Pin names copied from the ports/ counterpart board's pins.c and resolved +# to MDBT50Q-1MV2 module pin numbers through the package pin map selected +# in board.conf. +P0 = 20 +D0 = 20 +A2 = 20 +RX = 20 +P1 = 21 +D1 = 21 +A3 = 21 +TX = 21 +P2 = 9 +D2 = 9 +A4 = 9 +P3 = 13 +D3 = 13 +A5 = 13 +P4 = 11 +D4 = 11 +A6 = 11 +P5 = 50 +D5 = 50 +BUTTON_A = 50 +P6 = 26 +D6 = 26 +P7 = 23 +D7 = 23 +P8 = 58 +D8 = 58 +P9 = 16 +D9 = 16 +P10 = 14 +D10 = 14 +A7 = 14 +P11 = 3 +D11 = 3 +BUTTON_B = 3 +P12 = 12 +D12 = 12 +A0 = 12 +P13 = 24 +D13 = 24 +SCK = 24 +P14 = 22 +D14 = 22 +MISO = 22 +P15 = 19 +D15 = 19 +MOSI = 19 +P16 = 10 +D16 = 10 +A1 = 10 +P17 = 61 +D17 = 61 +L = 61 +LED = 61 +P18 = 38 +D18 = 38 +NEOPIXEL = 38 +P19 = 49 +D19 = 49 +SCL = 49 +P20 = 48 +D20 = 48 +SDA = 48 +MICROPHONE_CLOCK = 18 +MICROPHONE_DATA = 17 +SPEAKER = 47 +PROXIMITY_LIGHT_INTERRUPT = 52 +ACCELEROMETER_GYRO_INTERRUPT = 57 +WHITE_LEDS = 54 +TFT_RESET = 60 +TFT_BACKLIGHT = 59 +TFT_CS = 29 +TFT_DC = 37 +TFT_SCK = 36 +TFT_MOSI = 39 diff --git a/ports/zephyr-cp/boards/adafruit/clue_nrf52840_zephyr/console.overlay b/ports/zephyr-cp/boards/adafruit/clue_nrf52840_zephyr/console.overlay new file mode 100644 index 00000000000..095c4aa1d2d --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/clue_nrf52840_zephyr/console.overlay @@ -0,0 +1,18 @@ +/* Applied after board.overlay in CONSOLE=1 and DEBUG=1 builds: the Zephyr + * console on UART0, fixed to the TX/RX pins. TX/RX are then not available to + * busio.UART. */ +/ { + chosen { + zephyr,console = &uart0; + zephyr,shell-uart = &uart0; + zephyr,uart-mcumgr = &uart0; + zephyr,bt-mon-uart = &uart0; + zephyr,bt-c2h-uart = &uart0; + }; +}; + +&uart0 { + /delete-property/ zephyr,deferred-init; + pinctrl-0 = <&uart0_default>; + pinctrl-1 = <&uart0_sleep>; +}; diff --git a/ports/zephyr-cp/boards/adafruit/feather_nrf52840_sense_zephyr/autogen_board_info.toml b/ports/zephyr-cp/boards/adafruit/feather_nrf52840_sense_zephyr/autogen_board_info.toml new file mode 100644 index 00000000000..6ffb51ee7ce --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/feather_nrf52840_sense_zephyr/autogen_board_info.toml @@ -0,0 +1,145 @@ +# This file is autogenerated when a board is built. Do not edit. Do commit it to git. Other scripts use its info. +name = "Adafruit Feather Bluefruit Sense" + +[modules] +__future__ = true +_airlift = false +_bleio = true # Zephyr board has _bleio +_eve = false +_pew = false +_pixelmap = true # Zephyr board has neopixel_write +_stage = false +adafruit_bus_device = true +adafruit_pixelbuf = true # Zephyr board has neopixel_write +aesio = true +alarm = false +analogbufio = false +analogio = true # Zephyr board has analogio +async_spi = true # Zephyr board has async_spi +atexit = true +audiobusio = false +audiocore = false +audiodelays = false +audiofilewriter = false +audiofilters = false +audiofreeverb = false +audioi2sin = false +audioio = false +audiomixer = false +audiomp3 = false +audiopwmio = false +audiospeed = false +audiotap = false +aurora_epaper = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio +bitops = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio +camera = false +canio = false +codeop = true +countio = false +cryptography = false +digitalio = true +displayio = true # Zephyr board has busio +dotclockframebuffer = false +dualbank = false +emmcio = false +epaperdisplay = true # Zephyr board has busio +floppyio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio +frequencyio = false +getpass = true +gifio = true # Zephyr board has busio +gnss = false +hardwarekey = false +hashlib = true +hmac = false +hostnetwork = false +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false +i2ctarget = false +imagecapture = false +ipaddress = false +is31fl3741 = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true +max3421e = false +mcp4822 = false +mdns = false +memorymap = false +memorymonitor = false +microcontroller = true +mii = false +mipicsi = false +mipidsi = false +msgpack = true +neopixel_write = true # Zephyr board has neopixel_write +nvm = true # Board has NVM partition +onewireio = false +os = true +paralleldisplaybus = false +picogame = false +picogame3d = false +ps2io = false +pulseio = false +pwmio = true # Zephyr board has pwmio +qrio = false +qspibus = false +rainbowio = true +random = true +rclcpy = false +rgbmatrix = false +rotaryio = true # Zephyr board has rotaryio +rtc = false +sdcardio = true # Zephyr board has busio +sdioio = false +sharpdisplay = true # Zephyr board has busio +socketpool = false +spitarget = false +ssl = false +storage = true # Zephyr board has flash +struct = true +supervisor = true +synthio = false +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio +time = true +touchio = true +traceback = true +uheap = false +usb = false +usb_audio = false +usb_cdc = true +usb_hid = true +usb_host = false +usb_host_audio = false +usb_host_bulk = false +usb_midi = false +usb_video = false +ustack = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog +wifi = false +zephyr_display = false +zephyr_input = true # Zephyr board has zephyr_input +zephyr_kernel = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/adafruit/feather_nrf52840_sense_zephyr/board.conf b/ports/zephyr-cp/boards/adafruit/feather_nrf52840_sense_zephyr/board.conf new file mode 100644 index 00000000000..414256fc88f --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/feather_nrf52840_sense_zephyr/board.conf @@ -0,0 +1,17 @@ +CONFIG_BOARD_SERIAL_BACKEND_CDC_ACM=n + +# No Zephyr UART console by default (see board.overlay); a CONSOLE=1 build turns +# it back on in console.conf. +CONFIG_UART_CONSOLE=n +CONFIG_LOG_BACKEND_UART=n + +# Pin numbers are module pins (MDBT50Q-1MV2 carries the aQFN73 inside). +# The feathers use the MDBT50Q-1MV2 module, so pin numbers are module pins. +CONFIG_IOBROKER_PACKAGE_MDBT50Q_1MV2=y + +# PWM instances are enabled in board.overlay with disconnected outputs so +# iobroker can allocate them at runtime for neopixel_write and pwmio. +CONFIG_PWM=y + +# SAADC for analogio testing/use (pads resolve to AIN through iobroker) +CONFIG_ADC=y diff --git a/ports/zephyr-cp/boards/adafruit/feather_nrf52840_sense_zephyr/board.overlay b/ports/zephyr-cp/boards/adafruit/feather_nrf52840_sense_zephyr/board.overlay new file mode 100644 index 00000000000..72163bd5a2c --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/feather_nrf52840_sense_zephyr/board.overlay @@ -0,0 +1,7 @@ +/* Same as the Feather nRF52840 Express, whose upstream board is the same + * apart from the LED pin and the SHT3XD node below. */ +#include "../feather_nrf52840_zephyr/board.overlay" + +// CircuitPython drives the SHT31 from Python, so drop the Zephyr sensor node +// on the now dynamic I2C0. +/delete-node/ &SHT3XD; diff --git a/ports/zephyr-cp/boards/adafruit/feather_nrf52840_sense_zephyr/circuitpython.toml b/ports/zephyr-cp/boards/adafruit/feather_nrf52840_sense_zephyr/circuitpython.toml new file mode 100644 index 00000000000..62ea18e6798 --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/feather_nrf52840_sense_zephyr/circuitpython.toml @@ -0,0 +1,57 @@ +CIRCUITPY_BUILD_EXTENSIONS = ["hex", "uf2"] +USB_VID=0x239A +USB_PID=0x8088 +NAME="Feather Bluefruit Sense" +VENDOR="Adafruit" + +# Non-Zephyr build of the same board; nvm and CIRCUITPY must sit where it puts them. +counterpart = "nordic/feather_bluefruit_sense" + +# Status RGB LED, driven with neopixel_write; name from [pins]. +STATUS_NEOPIXEL = "NEOPIXEL" + + +# Pin names copied from the ports/ counterpart board's pins.c and resolved +# through the package pin map selected in board.conf. + +[pins] +# Pin names copied from the ports/ counterpart board's pins.c and resolved +# to MDBT50Q-1MV2 module pin numbers through the package pin map selected +# in board.conf. +A0 = 20 +A1 = 21 +A2 = 14 +A3 = 13 +A4 = 11 +A5 = 9 +AREF = 12 +VOLTAGE_MONITOR = 10 +BATTERY = 10 +SWITCH = 50 +NFC1 = 52 +NFC2 = 54 +D2 = 54 +D3 = 4 +D5 = 25 +D6 = 23 +D9 = 19 +D10 = 16 +D11 = 22 +D12 = 24 +D13 = 26 +NEOPIXEL = 38 +SCK = 36 +MOSI = 37 +MISO = 39 +TX = 49 +RX = 48 +SCL = 27 +SDA = 29 +L = 26 +LED = 26 +RED_LED = 26 +BLUE_LED = 3 +MICROPHONE_CLOCK = 18 +MICROPHONE_DATA = 17 +PROXIMITY_LIGHT_INTERRUPT = 47 +ACCELEROMETER_GYRO_INTERRUPT = 4 diff --git a/ports/zephyr-cp/boards/adafruit/feather_nrf52840_sense_zephyr/console.overlay b/ports/zephyr-cp/boards/adafruit/feather_nrf52840_sense_zephyr/console.overlay new file mode 100644 index 00000000000..03f4f3d1c3b --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/feather_nrf52840_sense_zephyr/console.overlay @@ -0,0 +1,2 @@ +/* Same console setup as the Feather nRF52840 Express. */ +#include "../feather_nrf52840_zephyr/console.overlay" diff --git a/ports/zephyr-cp/boards/adafruit/feather_nrf52840_zephyr/autogen_board_info.toml b/ports/zephyr-cp/boards/adafruit/feather_nrf52840_zephyr/autogen_board_info.toml new file mode 100644 index 00000000000..f9623146552 --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/feather_nrf52840_zephyr/autogen_board_info.toml @@ -0,0 +1,145 @@ +# This file is autogenerated when a board is built. Do not edit. Do commit it to git. Other scripts use its info. +name = "Adafruit Feather nRF52840 Express" + +[modules] +__future__ = true +_airlift = false +_bleio = true # Zephyr board has _bleio +_eve = false +_pew = false +_pixelmap = true # Zephyr board has neopixel_write +_stage = false +adafruit_bus_device = true +adafruit_pixelbuf = true # Zephyr board has neopixel_write +aesio = true +alarm = false +analogbufio = false +analogio = true # Zephyr board has analogio +async_spi = true # Zephyr board has async_spi +atexit = true +audiobusio = false +audiocore = false +audiodelays = false +audiofilewriter = false +audiofilters = false +audiofreeverb = false +audioi2sin = false +audioio = false +audiomixer = false +audiomp3 = false +audiopwmio = false +audiospeed = false +audiotap = false +aurora_epaper = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio +bitops = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio +camera = false +canio = false +codeop = true +countio = false +cryptography = false +digitalio = true +displayio = true # Zephyr board has busio +dotclockframebuffer = false +dualbank = false +emmcio = false +epaperdisplay = true # Zephyr board has busio +floppyio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio +frequencyio = false +getpass = true +gifio = true # Zephyr board has busio +gnss = false +hardwarekey = false +hashlib = true +hmac = false +hostnetwork = false +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false +i2ctarget = false +imagecapture = false +ipaddress = false +is31fl3741 = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true +max3421e = false +mcp4822 = false +mdns = false +memorymap = false +memorymonitor = false +microcontroller = true +mii = false +mipicsi = false +mipidsi = false +msgpack = true +neopixel_write = true # Zephyr board has neopixel_write +nvm = true # Board has NVM partition +onewireio = false +os = true +paralleldisplaybus = false +picogame = false +picogame3d = false +ps2io = false +pulseio = false +pwmio = true # Zephyr board has pwmio +qrio = false +qspibus = false +rainbowio = true +random = true +rclcpy = false +rgbmatrix = false +rotaryio = true # Zephyr board has rotaryio +rtc = false +sdcardio = true # Zephyr board has busio +sdioio = false +sharpdisplay = true # Zephyr board has busio +socketpool = false +spitarget = false +ssl = false +storage = true # Zephyr board has flash +struct = true +supervisor = true +synthio = false +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio +time = true +touchio = true +traceback = true +uheap = false +usb = false +usb_audio = false +usb_cdc = true +usb_hid = true +usb_host = false +usb_host_audio = false +usb_host_bulk = false +usb_midi = false +usb_video = false +ustack = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog +wifi = false +zephyr_display = false +zephyr_input = true # Zephyr board has zephyr_input +zephyr_kernel = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/adafruit/feather_nrf52840_zephyr/board.conf b/ports/zephyr-cp/boards/adafruit/feather_nrf52840_zephyr/board.conf new file mode 100644 index 00000000000..414256fc88f --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/feather_nrf52840_zephyr/board.conf @@ -0,0 +1,17 @@ +CONFIG_BOARD_SERIAL_BACKEND_CDC_ACM=n + +# No Zephyr UART console by default (see board.overlay); a CONSOLE=1 build turns +# it back on in console.conf. +CONFIG_UART_CONSOLE=n +CONFIG_LOG_BACKEND_UART=n + +# Pin numbers are module pins (MDBT50Q-1MV2 carries the aQFN73 inside). +# The feathers use the MDBT50Q-1MV2 module, so pin numbers are module pins. +CONFIG_IOBROKER_PACKAGE_MDBT50Q_1MV2=y + +# PWM instances are enabled in board.overlay with disconnected outputs so +# iobroker can allocate them at runtime for neopixel_write and pwmio. +CONFIG_PWM=y + +# SAADC for analogio testing/use (pads resolve to AIN through iobroker) +CONFIG_ADC=y diff --git a/ports/zephyr-cp/boards/adafruit/feather_nrf52840_zephyr/board.overlay b/ports/zephyr-cp/boards/adafruit/feather_nrf52840_zephyr/board.overlay new file mode 100644 index 00000000000..a26e02917e2 --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/feather_nrf52840_zephyr/board.overlay @@ -0,0 +1,294 @@ +/* Partition layout is owned by the mcuboot fork + * (dts/adafruit/adafruit_feather_nrf52840.dtsi) and applied to this image by + * sysbuild. This overlay only adds board/app config. */ +/* No Zephyr console by default, so TX/RX are free for busio.UART. A CONSOLE=1 + * build puts the console back on UART0 (console.overlay). */ +/ { + chosen { + /delete-property/ zephyr,console; + /delete-property/ zephyr,shell-uart; + /delete-property/ zephyr,uart-mcumgr; + /delete-property/ zephyr,bt-mon-uart; + /delete-property/ zephyr,bt-c2h-uart; + }; +}; + +&zephyr_udc0 { + /delete-node/ board_cdc_acm_uart; +}; + +// Bus instances enabled with all pins disconnected and marked +// zephyr,deferred-init so nothing is claimed at boot: the iobroker +// initializes and routes a device to arbitrary pins when a busio object is +// constructed, and de-initializes it on release: I2C0, I2C1, SPI2, SPI3, +// UART0 and UART1. +// +// See "nRF serial instances" in internal-modules/iobroker/README.md for how +// the instances are shared and allocated. + +&pinctrl { + i2c0_dyn_default: i2c0_dyn_default { + group1 { + psels = , + ; + }; + }; + + i2c0_dyn_sleep: i2c0_dyn_sleep { + group1 { + psels = , + ; + }; + }; + + i2c1_dyn_default: i2c1_dyn_default { + group1 { + psels = , + ; + }; + }; + + i2c1_dyn_sleep: i2c1_dyn_sleep { + group1 { + psels = , + ; + }; + }; + + pwm0_dyn_default: pwm0_dyn_default { + group1 { + psels = , + , + , + ; + }; + }; + + pwm0_dyn_sleep: pwm0_dyn_sleep { + group1 { + psels = , + , + , + ; + }; + }; + + pwm1_dyn_default: pwm1_dyn_default { + group1 { + psels = , + , + , + ; + }; + }; + + pwm1_dyn_sleep: pwm1_dyn_sleep { + group1 { + psels = , + , + , + ; + }; + }; + + pwm2_dyn_default: pwm2_dyn_default { + group1 { + psels = , + , + , + ; + }; + }; + + pwm2_dyn_sleep: pwm2_dyn_sleep { + group1 { + psels = , + , + , + ; + }; + }; + + pwm3_dyn_default: pwm3_dyn_default { + group1 { + psels = , + , + , + ; + }; + }; + + pwm3_dyn_sleep: pwm3_dyn_sleep { + group1 { + psels = , + , + , + ; + }; + }; + + spi2_dyn_default: spi2_dyn_default { + group1 { + psels = , + , + ; + }; + }; + + spi2_dyn_sleep: spi2_dyn_sleep { + group1 { + psels = , + , + ; + }; + }; + + spi3_dyn_default: spi3_dyn_default { + group1 { + psels = , + , + ; + }; + }; + + spi3_dyn_sleep: spi3_dyn_sleep { + group1 { + psels = , + , + ; + }; + }; + + uart0_dyn_default: uart0_dyn_default { + group1 { + psels = , + ; + }; + }; + + uart0_dyn_sleep: uart0_dyn_sleep { + group1 { + psels = , + ; + }; + }; + + uart1_dyn_default: uart1_dyn_default { + group1 { + psels = , + ; + }; + }; + + uart1_dyn_sleep: uart1_dyn_sleep { + group1 { + psels = , + ; + }; + }; +}; + +// The upstream board fixes I2C0 to SCL/SDA with the legacy TWI driver. Use +// TWIM like I2C1 so iobroker can route it. +&i2c0 { + compatible = "nordic,nrf-twim"; + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&i2c0_dyn_default>; + pinctrl-1 = <&i2c0_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&i2c1 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&i2c1_dyn_default>; + pinctrl-1 = <&i2c1_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +// PWM instances, same scheme: all four outputs disconnected and deferred +// init, so iobroker can hand an instance to neopixel_write and pwmio and +// route its outputs at runtime. + +&pwm0 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&pwm0_dyn_default>; + pinctrl-1 = <&pwm0_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&pwm1 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&pwm1_dyn_default>; + pinctrl-1 = <&pwm1_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&pwm2 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&pwm2_dyn_default>; + pinctrl-1 = <&pwm2_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&pwm3 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&pwm3_dyn_default>; + pinctrl-1 = <&pwm3_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +// SPI1 is the same peripheral instance as I2C1, so leave it disabled. +&spi1 { + status = "disabled"; +}; + +&spi2 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&spi2_dyn_default>; + pinctrl-1 = <&spi2_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&spi3 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&spi3_dyn_default>; + pinctrl-1 = <&spi3_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +// The upstream board uses the legacy UART driver for UART0, which can't be +// de-initialized, so iobroker could not route it again once it was released. +// Instead, use the UARTE driver, which can be deinited, like UART1. +&uart0 { + compatible = "nordic,nrf-uarte"; + status = "okay"; + zephyr,deferred-init; + current-speed = <115200>; + pinctrl-0 = <&uart0_dyn_default>; + pinctrl-1 = <&uart0_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&uart1 { + status = "okay"; + zephyr,deferred-init; + current-speed = <115200>; + pinctrl-0 = <&uart1_dyn_default>; + pinctrl-1 = <&uart1_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +#include "../../../app.overlay" + +/* Enable the SAADC for analogio (AIN0..AIN7 are on P0.02..P0.05 and P0.28..P0.31). */ +&adc { + status = "okay"; +}; diff --git a/ports/zephyr-cp/boards/adafruit/feather_nrf52840_zephyr/circuitpython.toml b/ports/zephyr-cp/boards/adafruit/feather_nrf52840_zephyr/circuitpython.toml new file mode 100644 index 00000000000..632c5bc8f7b --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/feather_nrf52840_zephyr/circuitpython.toml @@ -0,0 +1,55 @@ +CIRCUITPY_BUILD_EXTENSIONS = ["elf", "uf2"] +USB_VID=0x239A +USB_PID=0x802A +NAME="Feather nRF52840 Express" +VENDOR="Adafruit" + +# Non-Zephyr build of the same board; nvm and CIRCUITPY must sit where it puts them. +counterpart = "nordic/feather_nrf52840_express" + +# Status RGB LED, driven with neopixel_write; names from [pins]. +STATUS_NEOPIXEL = "NEOPIXEL" +STATUS_NEOPIXEL_POWER = "NEOPIXEL_POWER" + + +# Pin names copied from the ports/ counterpart board's pins.c and resolved +# through the package pin map selected in board.conf. + +[pins] +# Pin names copied from the ports/ counterpart board's pins.c and resolved +# to MDBT50Q-1MV2 module pin numbers through the package pin map selected +# in board.conf. +A0 = 20 +A1 = 21 +A2 = 14 +A3 = 13 +A4 = 11 +A5 = 9 +AREF = 12 +VOLTAGE_MONITOR = 10 +BATTERY = 10 +SWITCH = 50 +NFC1 = 52 +NFC2 = 54 +D2 = 54 +D5 = 25 +D6 = 23 +D9 = 19 +D10 = 16 +D11 = 22 +D12 = 24 +D13 = 26 +NEOPIXEL = 38 +NEOPIXEL_POWER = 7 +SCK = 36 +MOSI = 37 +MISO = 39 +TX = 49 +RX = 48 +SCL = 27 +SDA = 29 +L = 8 +LED = 8 +RED_LED = 8 +D3 = 8 +BLUE_LED = 3 diff --git a/ports/zephyr-cp/boards/adafruit/feather_nrf52840_zephyr/console.overlay b/ports/zephyr-cp/boards/adafruit/feather_nrf52840_zephyr/console.overlay new file mode 100644 index 00000000000..095c4aa1d2d --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/feather_nrf52840_zephyr/console.overlay @@ -0,0 +1,18 @@ +/* Applied after board.overlay in CONSOLE=1 and DEBUG=1 builds: the Zephyr + * console on UART0, fixed to the TX/RX pins. TX/RX are then not available to + * busio.UART. */ +/ { + chosen { + zephyr,console = &uart0; + zephyr,shell-uart = &uart0; + zephyr,uart-mcumgr = &uart0; + zephyr,bt-mon-uart = &uart0; + zephyr,bt-c2h-uart = &uart0; + }; +}; + +&uart0 { + /delete-property/ zephyr,deferred-init; + pinctrl-0 = <&uart0_default>; + pinctrl-1 = <&uart0_sleep>; +}; diff --git a/ports/zephyr-cp/boards/adafruit/feather_rp2040_zephyr/autogen_board_info.toml b/ports/zephyr-cp/boards/adafruit/feather_rp2040_zephyr/autogen_board_info.toml new file mode 100644 index 00000000000..a2d4cc02795 --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/feather_rp2040_zephyr/autogen_board_info.toml @@ -0,0 +1,145 @@ +# This file is autogenerated when a board is built. Do not edit. Do commit it to git. Other scripts use its info. +name = "Adafruit Feather RP2040" + +[modules] +__future__ = true +_airlift = false +_bleio = false +_eve = false +_pew = false +_pixelmap = false +_stage = false +adafruit_bus_device = true +adafruit_pixelbuf = false +aesio = true +alarm = false +analogbufio = false +analogio = false +async_spi = true # Zephyr board has async_spi +atexit = true +audiobusio = false +audiocore = false +audiodelays = false +audiofilewriter = false +audiofilters = false +audiofreeverb = false +audioi2sin = false +audioio = false +audiomixer = false +audiomp3 = false +audiopwmio = false +audiospeed = false +audiotap = false +aurora_epaper = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio +bitops = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio +camera = false +canio = false +codeop = true +countio = false +cryptography = false +digitalio = true +displayio = true # Zephyr board has busio +dotclockframebuffer = false +dualbank = false +emmcio = false +epaperdisplay = true # Zephyr board has busio +floppyio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio +frequencyio = false +getpass = true +gifio = true # Zephyr board has busio +gnss = false +hardwarekey = false +hashlib = true +hmac = false +hostnetwork = false +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false +i2ctarget = false +imagecapture = false +ipaddress = false +is31fl3741 = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true +max3421e = false +mcp4822 = false +mdns = false +memorymap = false +memorymonitor = false +microcontroller = true +mii = false +mipicsi = false +mipidsi = false +msgpack = true +neopixel_write = false +nvm = true # Board has NVM partition +onewireio = false +os = true +paralleldisplaybus = false +picogame = false +picogame3d = false +ps2io = false +pulseio = false +pwmio = false +qrio = false +qspibus = false +rainbowio = true +random = true +rclcpy = false +rgbmatrix = false +rotaryio = true # Zephyr board has rotaryio +rtc = false +sdcardio = true # Zephyr board has busio +sdioio = false +sharpdisplay = true # Zephyr board has busio +socketpool = false +spitarget = false +ssl = false +storage = true +struct = true +supervisor = true +synthio = false +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio +time = true +touchio = true +traceback = true +uheap = false +usb = false +usb_audio = false +usb_cdc = true +usb_hid = true +usb_host = false +usb_host_audio = false +usb_host_bulk = false +usb_midi = false +usb_video = false +ustack = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog +wifi = false +zephyr_display = false +zephyr_input = false +zephyr_kernel = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/adafruit/feather_rp2040_zephyr/board.conf b/ports/zephyr-cp/boards/adafruit/feather_rp2040_zephyr/board.conf new file mode 100644 index 00000000000..cc4c6a17d5b --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/feather_rp2040_zephyr/board.conf @@ -0,0 +1,9 @@ +CONFIG_GPIO=y + +# Package pin map for the RP2040 QFN-56 used by this board. +CONFIG_IOBROKER_PACKAGE_RP2040_QFN56=y + +# No Zephyr UART console by default (see board.overlay); a CONSOLE=1 build turns +# it back on in console.conf. +CONFIG_UART_CONSOLE=n +CONFIG_LOG_BACKEND_UART=n diff --git a/ports/zephyr-cp/boards/adafruit/feather_rp2040_zephyr/board.overlay b/ports/zephyr-cp/boards/adafruit/feather_rp2040_zephyr/board.overlay new file mode 100644 index 00000000000..873e03cdbf2 --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/feather_rp2040_zephyr/board.overlay @@ -0,0 +1,12 @@ +/* Partition layout is owned by the mcuboot fork (dts/adafruit/adafruit_feather_rp2040.dtsi) + * and applied to this image by sysbuild. This overlay only adds board/app config. */ +#include "../../../app.overlay" + +/* No Zephyr console by default, so TX/RX (GPIO0/GPIO1) (UART0) are free for busio.UART. A + * CONSOLE=1 build puts the console back on UART0 (console.overlay). */ +/ { + chosen { + /delete-property/ zephyr,console; + /delete-property/ zephyr,shell-uart; + }; +}; diff --git a/ports/zephyr-cp/boards/adafruit/feather_rp2040_zephyr/circuitpython.toml b/ports/zephyr-cp/boards/adafruit/feather_rp2040_zephyr/circuitpython.toml new file mode 100644 index 00000000000..19291431712 --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/feather_rp2040_zephyr/circuitpython.toml @@ -0,0 +1,41 @@ +CIRCUITPY_BUILD_EXTENSIONS = ["uf2"] +USB_VID=0x239A +USB_PID=0x80F2 +NAME="Feather RP2040" +VENDOR="Adafruit" +USB_MANUFACTURER="Adafruit" + +# Non-Zephyr build of the same board; nvm and CIRCUITPY must sit where it puts them. +counterpart = "raspberrypi/adafruit_feather_rp2040" + + +# Pin names copied from the ports/ counterpart board's pins.c and resolved +# through the package pin map selected in board.conf. +[pins] +A0 = 38 +A1 = 39 +A2 = 40 +A3 = 41 +D24 = 36 +D25 = 37 +SCK = 29 +MOSI = 30 +MISO = 31 +D0 = 3 +RX = 3 +D1 = 2 +TX = 2 +D4 = 8 +SDA = 4 +SCL = 5 +D5 = 9 +D6 = 11 +D9 = 12 +D10 = 13 +D11 = 14 +D12 = 15 +LED = 16 +D13 = 16 +BUTTON = 6 +BOOT = 6 +NEOPIXEL = 27 diff --git a/ports/zephyr-cp/boards/adafruit/feather_rp2040_zephyr/console.overlay b/ports/zephyr-cp/boards/adafruit/feather_rp2040_zephyr/console.overlay new file mode 100644 index 00000000000..c52fa7ac485 --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/feather_rp2040_zephyr/console.overlay @@ -0,0 +1,9 @@ +/* Applied after board.overlay in CONSOLE=1 and DEBUG=1 builds: the Zephyr + * console on UART0, on the TX/RX pins (GPIO0/GPIO1). TX/RX are then not + * available to busio.UART. */ +/ { + chosen { + zephyr,console = &uart0; + zephyr,shell-uart = &uart0; + }; +}; diff --git a/ports/zephyr-cp/boards/adafruit/itsybitsy_nrf52840_zephyr/autogen_board_info.toml b/ports/zephyr-cp/boards/adafruit/itsybitsy_nrf52840_zephyr/autogen_board_info.toml new file mode 100644 index 00000000000..2e7cf4de442 --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/itsybitsy_nrf52840_zephyr/autogen_board_info.toml @@ -0,0 +1,145 @@ +# This file is autogenerated when a board is built. Do not edit. Do commit it to git. Other scripts use its info. +name = "Adafruit ItsyBitsy nRF52840 Express" + +[modules] +__future__ = true +_airlift = false +_bleio = true # Zephyr board has _bleio +_eve = false +_pew = false +_pixelmap = true # Zephyr board has neopixel_write +_stage = false +adafruit_bus_device = true +adafruit_pixelbuf = true # Zephyr board has neopixel_write +aesio = true +alarm = false +analogbufio = false +analogio = true # Zephyr board has analogio +async_spi = true # Zephyr board has async_spi +atexit = true +audiobusio = false +audiocore = false +audiodelays = false +audiofilewriter = false +audiofilters = false +audiofreeverb = false +audioi2sin = false +audioio = false +audiomixer = false +audiomp3 = false +audiopwmio = false +audiospeed = false +audiotap = false +aurora_epaper = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio +bitops = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio +camera = false +canio = false +codeop = true +countio = false +cryptography = false +digitalio = true +displayio = true # Zephyr board has busio +dotclockframebuffer = false +dualbank = false +emmcio = false +epaperdisplay = true # Zephyr board has busio +floppyio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio +frequencyio = false +getpass = true +gifio = true # Zephyr board has busio +gnss = false +hardwarekey = false +hashlib = true +hmac = false +hostnetwork = false +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false +i2ctarget = false +imagecapture = false +ipaddress = false +is31fl3741 = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true +max3421e = false +mcp4822 = false +mdns = false +memorymap = false +memorymonitor = false +microcontroller = true +mii = false +mipicsi = false +mipidsi = false +msgpack = true +neopixel_write = true # Zephyr board has neopixel_write +nvm = true # Board has NVM partition +onewireio = false +os = true +paralleldisplaybus = false +picogame = false +picogame3d = false +ps2io = false +pulseio = false +pwmio = true # Zephyr board has pwmio +qrio = false +qspibus = false +rainbowio = true +random = true +rclcpy = false +rgbmatrix = false +rotaryio = true # Zephyr board has rotaryio +rtc = false +sdcardio = true # Zephyr board has busio +sdioio = false +sharpdisplay = true # Zephyr board has busio +socketpool = false +spitarget = false +ssl = false +storage = true # Zephyr board has flash +struct = true +supervisor = true +synthio = false +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio +time = true +touchio = true +traceback = true +uheap = false +usb = false +usb_audio = false +usb_cdc = true +usb_hid = true +usb_host = false +usb_host_audio = false +usb_host_bulk = false +usb_midi = false +usb_video = false +ustack = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog +wifi = false +zephyr_display = false +zephyr_input = true # Zephyr board has zephyr_input +zephyr_kernel = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/adafruit/itsybitsy_nrf52840_zephyr/board.conf b/ports/zephyr-cp/boards/adafruit/itsybitsy_nrf52840_zephyr/board.conf new file mode 100644 index 00000000000..86beb3879a2 --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/itsybitsy_nrf52840_zephyr/board.conf @@ -0,0 +1,17 @@ +CONFIG_BOARD_SERIAL_BACKEND_CDC_ACM=n + +# No Zephyr UART console by default (see board.overlay); a CONSOLE=1 build turns +# it back on in console.conf. +CONFIG_UART_CONSOLE=n +CONFIG_LOG_BACKEND_UART=n + +# The ItsyBitsy uses the MDBT50Q-1MV2 module (aQFN73 inside), so pin numbers +# are module pins. +CONFIG_IOBROKER_PACKAGE_MDBT50Q_1MV2=y + +# PWM instances are enabled in board.overlay with disconnected outputs so +# iobroker can allocate them at runtime for neopixel_write and pwmio. +CONFIG_PWM=y + +# SAADC for analogio testing/use (pads resolve to AIN through iobroker) +CONFIG_ADC=y diff --git a/ports/zephyr-cp/boards/adafruit/itsybitsy_nrf52840_zephyr/board.overlay b/ports/zephyr-cp/boards/adafruit/itsybitsy_nrf52840_zephyr/board.overlay new file mode 100644 index 00000000000..2ec1700c2b0 --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/itsybitsy_nrf52840_zephyr/board.overlay @@ -0,0 +1,344 @@ +/* Partition layout is owned by the mcuboot fork + * (dts/adafruit/adafruit_itsybitsy_nrf52840.dtsi) and applied to this image by + * sysbuild. This overlay only adds board/app config. */ +/* No Zephyr console by default, so TX/RX are free for busio.UART. A CONSOLE=1 + * build puts the console back on UART0 (console.overlay). */ +/ { + chosen { + /delete-property/ zephyr,console; + /delete-property/ zephyr,shell-uart; + /delete-property/ zephyr,uart-mcumgr; + /delete-property/ zephyr,bt-mon-uart; + /delete-property/ zephyr,bt-c2h-uart; + }; + + aliases { + /delete-property/ led-strip; + }; + + // The upstream board has no header connector. Its pins name the board + // pins, including the SCL/SDA, SCK/MOSI/MISO and TX/RX of board.I2C(), + // board.SPI() and board.UART(). See CONNECTORS in cptools/zephyr2cp.py. + itsybitsy_header: connector { + compatible = "adafruit-itsybitsy-header"; + #gpio-cells = <2>; + gpio-map-mask = <0xffffffff 0xffffffc0>; + gpio-map-pass-thru = <0 0x3f>; + gpio-map = <0 0 &gpio0 4 0>, /* A0 */ + <1 0 &gpio0 30 0>, /* A1 */ + <2 0 &gpio0 28 0>, /* A2 */ + <3 0 &gpio0 31 0>, /* A3 */ + <4 0 &gpio0 2 0>, /* A4 */ + <5 0 &gpio0 3 0>, /* A5 */ + <6 0 &gpio0 13 0>, /* SCK */ + <7 0 &gpio0 15 0>, /* MOSI */ + <8 0 &gpio0 20 0>, /* MISO */ + <9 0 &gpio0 25 0>, /* D0/RX */ + <10 0 &gpio0 24 0>, /* D1/TX */ + <11 0 &gpio1 2 0>, /* D2 */ + <12 0 &gpio0 16 0>, /* SDA */ + <13 0 &gpio0 14 0>, /* SCL */ + <14 0 &gpio0 27 0>, /* D5 */ + <15 0 &gpio1 8 0>, /* D7 */ + <16 0 &gpio0 7 0>, /* D9 */ + <17 0 &gpio0 5 0>, /* D10 */ + <18 0 &gpio0 26 0>, /* D11 */ + <19 0 &gpio0 11 0>, /* D12 */ + <20 0 &gpio0 12 0>; /* D13 */ + }; +}; + +&zephyr_udc0 { + /delete-node/ board_cdc_acm_uart; +}; + +// The upstream board calls the user LED red, but it is blue. The label +// becomes a board pin name. +&led0 { + label = "Blue LED"; +}; + +// The upstream board clocks QSPI at 32 MHz, which the GD25Q16C doesn't do +// reliably here: the filesystem fails with I/O errors. Use 16 MHz, like the +// Feather nRF52840 and ports/nordic (adafruit/circuitpython#1418). +&gd25q16 { + sck-frequency = <16000000>; +}; + +// Bus instances enabled with all pins disconnected and marked +// zephyr,deferred-init so nothing is claimed at boot: the iobroker +// initializes and routes a device to arbitrary pins when a busio object is +// constructed, and de-initializes it on release: I2C0, I2C1, SPI2, SPI3, +// UART0 and UART1. +// +// See "nRF serial instances" in internal-modules/iobroker/README.md for how +// the instances are shared and allocated. + +&pinctrl { + i2c0_dyn_default: i2c0_dyn_default { + group1 { + psels = , + ; + }; + }; + + i2c0_dyn_sleep: i2c0_dyn_sleep { + group1 { + psels = , + ; + }; + }; + + i2c1_dyn_default: i2c1_dyn_default { + group1 { + psels = , + ; + }; + }; + + i2c1_dyn_sleep: i2c1_dyn_sleep { + group1 { + psels = , + ; + }; + }; + + pwm0_dyn_default: pwm0_dyn_default { + group1 { + psels = , + , + , + ; + }; + }; + + pwm0_dyn_sleep: pwm0_dyn_sleep { + group1 { + psels = , + , + , + ; + }; + }; + + pwm1_dyn_default: pwm1_dyn_default { + group1 { + psels = , + , + , + ; + }; + }; + + pwm1_dyn_sleep: pwm1_dyn_sleep { + group1 { + psels = , + , + , + ; + }; + }; + + pwm2_dyn_default: pwm2_dyn_default { + group1 { + psels = , + , + , + ; + }; + }; + + pwm2_dyn_sleep: pwm2_dyn_sleep { + group1 { + psels = , + , + , + ; + }; + }; + + pwm3_dyn_default: pwm3_dyn_default { + group1 { + psels = , + , + , + ; + }; + }; + + pwm3_dyn_sleep: pwm3_dyn_sleep { + group1 { + psels = , + , + , + ; + }; + }; + + spi2_dyn_default: spi2_dyn_default { + group1 { + psels = , + , + ; + }; + }; + + spi2_dyn_sleep: spi2_dyn_sleep { + group1 { + psels = , + , + ; + }; + }; + + spi3_dyn_default: spi3_dyn_default { + group1 { + psels = , + , + ; + }; + }; + + spi3_dyn_sleep: spi3_dyn_sleep { + group1 { + psels = , + , + ; + }; + }; + + uart0_dyn_default: uart0_dyn_default { + group1 { + psels = , + ; + }; + }; + + uart0_dyn_sleep: uart0_dyn_sleep { + group1 { + psels = , + ; + }; + }; + + uart1_dyn_default: uart1_dyn_default { + group1 { + psels = , + ; + }; + }; + + uart1_dyn_sleep: uart1_dyn_sleep { + group1 { + psels = , + ; + }; + }; +}; + +// The upstream board fixes I2C0 to SCL/SDA with the legacy TWI driver. Use +// TWIM like I2C1 so iobroker can route it. +&i2c0 { + compatible = "nordic,nrf-twim"; + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&i2c0_dyn_default>; + pinctrl-1 = <&i2c0_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&i2c1 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&i2c1_dyn_default>; + pinctrl-1 = <&i2c1_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +// PWM instances, same scheme: all four outputs disconnected and deferred +// init, so iobroker can hand an instance to neopixel_write and pwmio and +// route its outputs at runtime. + +&pwm0 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&pwm0_dyn_default>; + pinctrl-1 = <&pwm0_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&pwm1 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&pwm1_dyn_default>; + pinctrl-1 = <&pwm1_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&pwm2 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&pwm2_dyn_default>; + pinctrl-1 = <&pwm2_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&pwm3 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&pwm3_dyn_default>; + pinctrl-1 = <&pwm3_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +// SPI1 is the same peripheral instance as I2C1, so leave it disabled. +&spi1 { + status = "disabled"; +}; + +// The upstream board puts the DotStar on SPI2 with the legacy SPI driver. +// The status LED code bit-bangs the DotStar instead, so drop the node and use +// SPIM like SPI3. +/delete-node/ &apa102; + +&spi2 { + compatible = "nordic,nrf-spim"; + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&spi2_dyn_default>; + pinctrl-1 = <&spi2_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&spi3 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&spi3_dyn_default>; + pinctrl-1 = <&spi3_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&uart0 { + status = "okay"; + zephyr,deferred-init; + current-speed = <115200>; + pinctrl-0 = <&uart0_dyn_default>; + pinctrl-1 = <&uart0_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&uart1 { + status = "okay"; + zephyr,deferred-init; + current-speed = <115200>; + pinctrl-0 = <&uart1_dyn_default>; + pinctrl-1 = <&uart1_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +#include "../../../app.overlay" + +/* Enable the SAADC for analogio (AIN0..AIN7 are on P0.02..P0.05 and P0.28..P0.31). */ +&adc { + status = "okay"; +}; diff --git a/ports/zephyr-cp/boards/adafruit/itsybitsy_nrf52840_zephyr/circuitpython.toml b/ports/zephyr-cp/boards/adafruit/itsybitsy_nrf52840_zephyr/circuitpython.toml new file mode 100644 index 00000000000..f6696d38725 --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/itsybitsy_nrf52840_zephyr/circuitpython.toml @@ -0,0 +1,25 @@ +CIRCUITPY_BUILD_EXTENSIONS = ["elf", "uf2"] +USB_VID=0x239A +USB_PID=0x8052 +NAME="ItsyBitsy nRF52840 Express" +VENDOR="Adafruit" + +# Non-Zephyr build of the same board; nvm and CIRCUITPY must sit where it puts them. +counterpart = "nordic/itsybitsy_nrf52840_express" + +# Status DotStar, driven with bit-banged SPI; names from [pins]. +STATUS_DOTSTAR_DATA = "DOTSTAR_DATA" +STATUS_DOTSTAR_CLOCK = "DOTSTAR_CLOCK" + +[pins] +# Pins not on the header connector (see board.overlay), with names copied +# from the ports/ counterpart board's pins.c and resolved to MDBT50Q-1MV2 +# module pin numbers through the package pin map selected in board.conf. +SWITCH = 10 +APA102_MOSI = 24 +DOTSTAR_DATA = 24 +APA102_SCK = 26 +DOTSTAR_CLOCK = 26 +L = 22 +LED = 22 +BLUE_LED = 22 diff --git a/ports/zephyr-cp/boards/adafruit/itsybitsy_nrf52840_zephyr/console.overlay b/ports/zephyr-cp/boards/adafruit/itsybitsy_nrf52840_zephyr/console.overlay new file mode 100644 index 00000000000..095c4aa1d2d --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/itsybitsy_nrf52840_zephyr/console.overlay @@ -0,0 +1,18 @@ +/* Applied after board.overlay in CONSOLE=1 and DEBUG=1 builds: the Zephyr + * console on UART0, fixed to the TX/RX pins. TX/RX are then not available to + * busio.UART. */ +/ { + chosen { + zephyr,console = &uart0; + zephyr,shell-uart = &uart0; + zephyr,uart-mcumgr = &uart0; + zephyr,bt-mon-uart = &uart0; + zephyr,bt-c2h-uart = &uart0; + }; +}; + +&uart0 { + /delete-property/ zephyr,deferred-init; + pinctrl-0 = <&uart0_default>; + pinctrl-1 = <&uart0_sleep>; +}; diff --git a/ports/zephyr-cp/boards/adafruit/macropad_rp2040_zephyr/autogen_board_info.toml b/ports/zephyr-cp/boards/adafruit/macropad_rp2040_zephyr/autogen_board_info.toml new file mode 100644 index 00000000000..110e6a26872 --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/macropad_rp2040_zephyr/autogen_board_info.toml @@ -0,0 +1,145 @@ +# This file is autogenerated when a board is built. Do not edit. Do commit it to git. Other scripts use its info. +name = "Adafruit MacroPad RP2040" + +[modules] +__future__ = true +_airlift = false +_bleio = false +_eve = false +_pew = false +_pixelmap = false +_stage = false +adafruit_bus_device = true +adafruit_pixelbuf = false +aesio = true +alarm = false +analogbufio = false +analogio = false +async_spi = true # Zephyr board has async_spi +atexit = true +audiobusio = false +audiocore = false +audiodelays = false +audiofilewriter = false +audiofilters = false +audiofreeverb = false +audioi2sin = false +audioio = false +audiomixer = false +audiomp3 = false +audiopwmio = false +audiospeed = false +audiotap = false +aurora_epaper = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio +bitops = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio +camera = false +canio = false +codeop = true +countio = false +cryptography = false +digitalio = true +displayio = true # Zephyr board has displayio +dotclockframebuffer = false +dualbank = false +emmcio = false +epaperdisplay = true # Zephyr board has busio +floppyio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio +frequencyio = false +getpass = true +gifio = true # Zephyr board has busio +gnss = false +hardwarekey = false +hashlib = true +hmac = false +hostnetwork = false +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false +i2ctarget = false +imagecapture = false +ipaddress = false +is31fl3741 = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true +max3421e = false +mcp4822 = false +mdns = false +memorymap = false +memorymonitor = false +microcontroller = true +mii = false +mipicsi = false +mipidsi = false +msgpack = true +neopixel_write = false +nvm = true # Board has NVM partition +onewireio = false +os = true +paralleldisplaybus = false +picogame = false +picogame3d = false +ps2io = false +pulseio = false +pwmio = false +qrio = false +qspibus = false +rainbowio = true +random = true +rclcpy = false +rgbmatrix = false +rotaryio = true # Zephyr board has rotaryio +rtc = false +sdcardio = true # Zephyr board has busio +sdioio = false +sharpdisplay = true # Zephyr board has busio +socketpool = false +spitarget = false +ssl = false +storage = true +struct = true +supervisor = true +synthio = false +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio +time = true +touchio = true +traceback = true +uheap = false +usb = false +usb_audio = false +usb_cdc = true +usb_hid = true +usb_host = false +usb_host_audio = false +usb_host_bulk = false +usb_midi = false +usb_video = false +ustack = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog +wifi = false +zephyr_display = true # Zephyr board has zephyr_display +zephyr_input = false +zephyr_kernel = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/adafruit/macropad_rp2040_zephyr/board.conf b/ports/zephyr-cp/boards/adafruit/macropad_rp2040_zephyr/board.conf new file mode 100644 index 00000000000..cdf74780abb --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/macropad_rp2040_zephyr/board.conf @@ -0,0 +1,12 @@ +CONFIG_GPIO=y + +# Package pin map for the RP2040 QFN-56 used by this board. +CONFIG_IOBROKER_PACKAGE_RP2040_QFN56=y + +# Enable the SH1106 OLED via the Zephyr display subsystem +CONFIG_DISPLAY=y + +# No Zephyr UART console by default (see board.overlay), so SCL/SDA are free +# for I2C. A CONSOLE=1 build turns it back on in console.conf. +CONFIG_UART_CONSOLE=n +CONFIG_LOG_BACKEND_UART=n diff --git a/ports/zephyr-cp/boards/adafruit/macropad_rp2040_zephyr/board.overlay b/ports/zephyr-cp/boards/adafruit/macropad_rp2040_zephyr/board.overlay new file mode 100644 index 00000000000..4ab09025a06 --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/macropad_rp2040_zephyr/board.overlay @@ -0,0 +1,32 @@ +/* Partition layout is owned by the mcuboot fork (dts/adafruit/adafruit_macropad_rp2040.dtsi) + * and applied to this image by sysbuild. This overlay only adds board/app config. */ +#include "../../../app.overlay" + +/* Free the key and encoder pins for keypad and rotaryio. */ +/ { + keys { + status = "disabled"; + }; + + encoder { + status = "disabled"; + }; +}; + +/* No Zephyr console by default, so SCL/SDA (GPIO21/20) are free for I2C0. A + * CONSOLE=1 build puts the console back on UART1 (console.overlay). */ +/ { + chosen { + /delete-property/ zephyr,console; + /delete-property/ zephyr,shell-uart; + }; +}; + +&uart1 { + status = "disabled"; +}; + +/* The zephyr_i2c label makes this board.STEMMA_I2C as well as board.I2C. */ +zephyr_i2c: &i2c0 { + status = "okay"; +}; diff --git a/ports/zephyr-cp/boards/adafruit/macropad_rp2040_zephyr/circuitpython.toml b/ports/zephyr-cp/boards/adafruit/macropad_rp2040_zephyr/circuitpython.toml new file mode 100644 index 00000000000..c294f98c580 --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/macropad_rp2040_zephyr/circuitpython.toml @@ -0,0 +1,44 @@ +CIRCUITPY_BUILD_EXTENSIONS = ["uf2"] +USB_VID=0x239A +USB_PID=0x8108 +NAME="MacroPad RP2040" +VENDOR="Adafruit" +USB_MANUFACTURER="Adafruit" + +# Non-Zephyr build of the same board; nvm and CIRCUITPY must sit where it puts them. +counterpart = "raspberrypi/adafruit_macropad_rp2040" + + +# Pin names from the ports/ counterpart board's pins.c, as RP2040 QFN-56 +# package pin numbers. +[pins] +KEY1 = 3 +KEY2 = 4 +KEY3 = 5 +KEY4 = 6 +KEY5 = 7 +KEY6 = 8 +KEY7 = 9 +KEY8 = 11 +KEY9 = 12 +KEY10 = 13 +KEY11 = 14 +KEY12 = 15 +LED = 16 +SPEAKER_ENABLE = 17 +SPEAKER = 27 +ENCODER_SWITCH = 2 +BUTTON = 2 +ENCODER_A = 28 +ROTA = 28 +ENCODER_B = 29 +ROTB = 29 +NEOPIXEL = 30 +SDA = 31 +SCL = 32 +OLED_CS = 34 +OLED_RESET = 35 +OLED_DC = 36 +SCK = 38 +MOSI = 39 +MISO = 40 diff --git a/ports/zephyr-cp/boards/adafruit/macropad_rp2040_zephyr/console.overlay b/ports/zephyr-cp/boards/adafruit/macropad_rp2040_zephyr/console.overlay new file mode 100644 index 00000000000..cc66afa94b8 --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/macropad_rp2040_zephyr/console.overlay @@ -0,0 +1,17 @@ +/* Applied after board.overlay in CONSOLE=1 and DEBUG=1 builds: the Zephyr + * console on UART1, on the STEMMA QT pins (TX on SDA/GPIO20, RX on SCL/GPIO21). + * board.I2C() and board.STEMMA_I2C are then not available. */ +/ { + chosen { + zephyr,console = &uart1; + zephyr,shell-uart = &uart1; + }; +}; + +&uart1 { + status = "okay"; +}; + +&i2c0 { + status = "disabled"; +}; diff --git a/ports/zephyr-cp/boards/adafruit/metro_ch32v407_zephyr/autogen_board_info.toml b/ports/zephyr-cp/boards/adafruit/metro_ch32v407_zephyr/autogen_board_info.toml new file mode 100644 index 00000000000..2c89f85b066 --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/metro_ch32v407_zephyr/autogen_board_info.toml @@ -0,0 +1,145 @@ +# This file is autogenerated when a board is built. Do not edit. Do commit it to git. Other scripts use its info. +name = "Adafruit Industries LLC Metro CH32V407" + +[modules] +__future__ = true +_airlift = false +_bleio = false +_eve = false +_pew = false +_pixelmap = false +_stage = false +adafruit_bus_device = true +adafruit_pixelbuf = false +aesio = true +alarm = false +analogbufio = false +analogio = false +async_spi = true # Zephyr board has async_spi +atexit = true +audiobusio = false +audiocore = false +audiodelays = false +audiofilewriter = false +audiofilters = false +audiofreeverb = false +audioi2sin = false +audioio = false +audiomixer = false +audiomp3 = false +audiopwmio = false +audiospeed = false +audiotap = false +aurora_epaper = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio +bitops = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio +camera = false +canio = false +codeop = true +countio = false +cryptography = false +digitalio = true +displayio = true # Zephyr board has busio +dotclockframebuffer = false +dualbank = false +emmcio = false +epaperdisplay = true # Zephyr board has busio +floppyio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio +frequencyio = false +getpass = true +gifio = true # Zephyr board has busio +gnss = false +hardwarekey = false +hashlib = true +hmac = false +hostnetwork = false +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false +i2ctarget = false +imagecapture = false +ipaddress = false +is31fl3741 = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true +max3421e = false +mcp4822 = false +mdns = false +memorymap = false +memorymonitor = false +microcontroller = true +mii = false +mipicsi = false +mipidsi = false +msgpack = true +neopixel_write = false +nvm = true # Board has NVM partition +onewireio = false +os = true +paralleldisplaybus = false +picogame = false +picogame3d = false +ps2io = false +pulseio = false +pwmio = false +qrio = false +qspibus = false +rainbowio = true +random = true +rclcpy = false +rgbmatrix = false +rotaryio = true # Zephyr board has rotaryio +rtc = false +sdcardio = true # Zephyr board has busio +sdioio = false +sharpdisplay = true # Zephyr board has busio +socketpool = false +spitarget = false +ssl = false +storage = true # Zephyr board has flash +struct = true +supervisor = true +synthio = false +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio +time = true +touchio = true +traceback = true +uheap = false +usb = false +usb_audio = false +usb_cdc = true +usb_hid = true +usb_host = false +usb_host_audio = false +usb_host_bulk = false +usb_midi = false +usb_video = false +ustack = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog +wifi = false +zephyr_display = false +zephyr_input = true # Zephyr board has zephyr_input +zephyr_kernel = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/adafruit/metro_ch32v407_zephyr/board.conf b/ports/zephyr-cp/boards/adafruit/metro_ch32v407_zephyr/board.conf new file mode 100644 index 00000000000..2ed82902d9b --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/metro_ch32v407_zephyr/board.conf @@ -0,0 +1,6 @@ +# Nothing on this board uses settings, so leave settings and NVS off. +CONFIG_SETTINGS=n +CONFIG_NVS=n + +# REPL is on USB. No Zephyr UART console, so D0/D1 are free for busio.UART. +CONFIG_UART_CONSOLE=n diff --git a/ports/zephyr-cp/boards/adafruit/metro_ch32v407_zephyr/board.overlay b/ports/zephyr-cp/boards/adafruit/metro_ch32v407_zephyr/board.overlay new file mode 100644 index 00000000000..db603104453 --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/metro_ch32v407_zephyr/board.overlay @@ -0,0 +1,32 @@ +/* No Zephyr console by default, so D0/D1 (USART1) are free for busio.UART. A + * CONSOLE=1 build puts the console back on USART1 (console.overlay). */ +/ { + chosen { + /delete-property/ zephyr,console; + /delete-property/ zephyr,shell-uart; + zephyr,entropy = &adc_entropy; + }; + + // The on-chip RNG repeats too often to use. + adc_entropy: adc-entropy { + compatible = "adafruit,ch32v4x7-adc-entropy"; + status = "okay"; + }; + + // Named pins that are not on the Arduino header. + // Their names are in circuitpython.toml [connectors.metro_ch32v4x7_pins]. + metro_ch32v4x7_pins: metro-ch32v4x7-pins { + compatible = "adafruit-metro-ch32v4x7-pins"; + #gpio-cells = <2>; + gpio-map-mask = <0xffffffff 0xffffffc0>; + gpio-map-pass-thru = <0 0x3f>; + gpio-map = <0 0 &gpioa 5 0>, /* SCK */ + <1 0 &gpioa 7 0>, /* MOSI */ + <2 0 &gpioa 6 0>, /* MISO */ + <3 0 &gpioc 14 0>, /* NEOPIXEL */ + <4 0 &gpioc 15 0>, /* BUTTON */ + <5 0 &gpioa 10 0>; /* SD_CD */ + }; +}; + +#include "../../../app.overlay" diff --git a/ports/zephyr-cp/boards/adafruit/metro_ch32v407_zephyr/circuitpython.toml b/ports/zephyr-cp/boards/adafruit/metro_ch32v407_zephyr/circuitpython.toml new file mode 100644 index 00000000000..ebc7bd7b793 --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/metro_ch32v407_zephyr/circuitpython.toml @@ -0,0 +1,36 @@ +CIRCUITPY_BUILD_EXTENSIONS = ["uf2"] +USB_VID=0x239A +USB_PID=0x817E +NAME="Metro CH32V407" + +[connectors.arduino_header] +"0" = "A0" +"1" = "A1" +"2" = "A2" +"3" = "A3" +"4" = "A4" +"5" = "A5" +"6" = ["D0", "RX"] +"7" = ["D1", "TX"] +"8" = "D2" +"9" = "D3" +"10" = "D4" +"11" = "D5" +"12" = "D6" +"13" = "D7" +"14" = "D8" +"15" = "D9" +"16" = "D10" +"17" = "D11" +"18" = "D12" +"19" = ["D13", "LED"] +"20" = "SDA" +"21" = "SCL" + +[connectors.metro_ch32v4x7_pins] +"0" = "SCK" +"1" = "MOSI" +"2" = "MISO" +"3" = "NEOPIXEL" +"4" = "BUTTON" +"5" = "SD_CD" diff --git a/ports/zephyr-cp/boards/adafruit/metro_ch32v407_zephyr/console.overlay b/ports/zephyr-cp/boards/adafruit/metro_ch32v407_zephyr/console.overlay new file mode 100644 index 00000000000..2c4aab32afb --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/metro_ch32v407_zephyr/console.overlay @@ -0,0 +1,9 @@ +/* Applied after board.overlay in CONSOLE=1 and DEBUG=1 builds: the Zephyr + * console on USART1, on the D0/D1 pins. D0/D1 are then not available to + * busio.UART. */ +/ { + chosen { + zephyr,console = &usart1; + zephyr,shell-uart = &usart1; + }; +}; diff --git a/ports/zephyr-cp/boards/adafruit/metro_ch32v467_zephyr/autogen_board_info.toml b/ports/zephyr-cp/boards/adafruit/metro_ch32v467_zephyr/autogen_board_info.toml new file mode 100644 index 00000000000..0fbd1136b48 --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/metro_ch32v467_zephyr/autogen_board_info.toml @@ -0,0 +1,145 @@ +# This file is autogenerated when a board is built. Do not edit. Do commit it to git. Other scripts use its info. +name = "Adafruit Industries LLC Metro CH32V467" + +[modules] +__future__ = true +_airlift = false +_bleio = false +_eve = false +_pew = false +_pixelmap = false +_stage = false +adafruit_bus_device = true +adafruit_pixelbuf = false +aesio = true +alarm = false +analogbufio = false +analogio = false +async_spi = true # Zephyr board has async_spi +atexit = true +audiobusio = false +audiocore = false +audiodelays = false +audiofilewriter = false +audiofilters = false +audiofreeverb = false +audioi2sin = false +audioio = false +audiomixer = false +audiomp3 = false +audiopwmio = false +audiospeed = false +audiotap = false +aurora_epaper = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio +bitops = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio +camera = false +canio = false +codeop = true +countio = false +cryptography = false +digitalio = true +displayio = true # Zephyr board has busio +dotclockframebuffer = false +dualbank = false +emmcio = false +epaperdisplay = true # Zephyr board has busio +floppyio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio +frequencyio = false +getpass = true +gifio = true # Zephyr board has busio +gnss = false +hardwarekey = false +hashlib = true +hmac = false +hostnetwork = false +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false +i2ctarget = false +imagecapture = false +ipaddress = false +is31fl3741 = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true +max3421e = false +mcp4822 = false +mdns = false +memorymap = false +memorymonitor = false +microcontroller = true +mii = false +mipicsi = false +mipidsi = false +msgpack = true +neopixel_write = false +nvm = true # Board has NVM partition +onewireio = false +os = true +paralleldisplaybus = false +picogame = false +picogame3d = false +ps2io = false +pulseio = false +pwmio = false +qrio = false +qspibus = false +rainbowio = true +random = true +rclcpy = false +rgbmatrix = false +rotaryio = true # Zephyr board has rotaryio +rtc = false +sdcardio = true # Zephyr board has busio +sdioio = false +sharpdisplay = true # Zephyr board has busio +socketpool = false +spitarget = false +ssl = false +storage = true # Zephyr board has flash +struct = true +supervisor = true +synthio = false +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio +time = true +touchio = true +traceback = true +uheap = false +usb = false +usb_audio = false +usb_cdc = true +usb_hid = true +usb_host = false +usb_host_audio = false +usb_host_bulk = false +usb_midi = false +usb_video = false +ustack = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog +wifi = false +zephyr_display = false +zephyr_input = true # Zephyr board has zephyr_input +zephyr_kernel = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/adafruit/metro_ch32v467_zephyr/board.conf b/ports/zephyr-cp/boards/adafruit/metro_ch32v467_zephyr/board.conf new file mode 100644 index 00000000000..2ed82902d9b --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/metro_ch32v467_zephyr/board.conf @@ -0,0 +1,6 @@ +# Nothing on this board uses settings, so leave settings and NVS off. +CONFIG_SETTINGS=n +CONFIG_NVS=n + +# REPL is on USB. No Zephyr UART console, so D0/D1 are free for busio.UART. +CONFIG_UART_CONSOLE=n diff --git a/ports/zephyr-cp/boards/adafruit/metro_ch32v467_zephyr/board.overlay b/ports/zephyr-cp/boards/adafruit/metro_ch32v467_zephyr/board.overlay new file mode 100644 index 00000000000..db603104453 --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/metro_ch32v467_zephyr/board.overlay @@ -0,0 +1,32 @@ +/* No Zephyr console by default, so D0/D1 (USART1) are free for busio.UART. A + * CONSOLE=1 build puts the console back on USART1 (console.overlay). */ +/ { + chosen { + /delete-property/ zephyr,console; + /delete-property/ zephyr,shell-uart; + zephyr,entropy = &adc_entropy; + }; + + // The on-chip RNG repeats too often to use. + adc_entropy: adc-entropy { + compatible = "adafruit,ch32v4x7-adc-entropy"; + status = "okay"; + }; + + // Named pins that are not on the Arduino header. + // Their names are in circuitpython.toml [connectors.metro_ch32v4x7_pins]. + metro_ch32v4x7_pins: metro-ch32v4x7-pins { + compatible = "adafruit-metro-ch32v4x7-pins"; + #gpio-cells = <2>; + gpio-map-mask = <0xffffffff 0xffffffc0>; + gpio-map-pass-thru = <0 0x3f>; + gpio-map = <0 0 &gpioa 5 0>, /* SCK */ + <1 0 &gpioa 7 0>, /* MOSI */ + <2 0 &gpioa 6 0>, /* MISO */ + <3 0 &gpioc 14 0>, /* NEOPIXEL */ + <4 0 &gpioc 15 0>, /* BUTTON */ + <5 0 &gpioa 10 0>; /* SD_CD */ + }; +}; + +#include "../../../app.overlay" diff --git a/ports/zephyr-cp/boards/adafruit/metro_ch32v467_zephyr/circuitpython.toml b/ports/zephyr-cp/boards/adafruit/metro_ch32v467_zephyr/circuitpython.toml new file mode 100644 index 00000000000..3db237eec18 --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/metro_ch32v467_zephyr/circuitpython.toml @@ -0,0 +1,36 @@ +CIRCUITPY_BUILD_EXTENSIONS = ["uf2"] +USB_VID=0x239A +USB_PID=0x8180 +NAME="Metro CH32V467" + +[connectors.arduino_header] +"0" = "A0" +"1" = "A1" +"2" = "A2" +"3" = "A3" +"4" = "A4" +"5" = "A5" +"6" = ["D0", "RX"] +"7" = ["D1", "TX"] +"8" = "D2" +"9" = "D3" +"10" = "D4" +"11" = "D5" +"12" = "D6" +"13" = "D7" +"14" = "D8" +"15" = "D9" +"16" = "D10" +"17" = "D11" +"18" = "D12" +"19" = ["D13", "LED"] +"20" = "SDA" +"21" = "SCL" + +[connectors.metro_ch32v4x7_pins] +"0" = "SCK" +"1" = "MOSI" +"2" = "MISO" +"3" = "NEOPIXEL" +"4" = "BUTTON" +"5" = "SD_CD" diff --git a/ports/zephyr-cp/boards/adafruit/metro_ch32v467_zephyr/console.overlay b/ports/zephyr-cp/boards/adafruit/metro_ch32v467_zephyr/console.overlay new file mode 100644 index 00000000000..2c4aab32afb --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/metro_ch32v467_zephyr/console.overlay @@ -0,0 +1,9 @@ +/* Applied after board.overlay in CONSOLE=1 and DEBUG=1 builds: the Zephyr + * console on USART1, on the D0/D1 pins. D0/D1 are then not available to + * busio.UART. */ +/ { + chosen { + zephyr,console = &usart1; + zephyr,shell-uart = &usart1; + }; +}; diff --git a/ports/zephyr-cp/boards/adafruit/metro_m7_airlift_zephyr/autogen_board_info.toml b/ports/zephyr-cp/boards/adafruit/metro_m7_airlift_zephyr/autogen_board_info.toml new file mode 100644 index 00000000000..216f47d4852 --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/metro_m7_airlift_zephyr/autogen_board_info.toml @@ -0,0 +1,145 @@ +# This file is autogenerated when a board is built. Do not edit. Do commit it to git. Other scripts use its info. +name = "Adafruit Industries LLC Metro M7 iMX RT1011 AirLift" + +[modules] +__future__ = true +_airlift = false +_bleio = false +_eve = false +_pew = false +_pixelmap = false +_stage = false +adafruit_bus_device = true +adafruit_pixelbuf = false +aesio = true +alarm = false +analogbufio = false +analogio = false +async_spi = true # Zephyr board has async_spi +atexit = true +audiobusio = false +audiocore = false +audiodelays = false +audiofilewriter = false +audiofilters = false +audiofreeverb = false +audioi2sin = false +audioio = false +audiomixer = false +audiomp3 = false +audiopwmio = false +audiospeed = false +audiotap = false +aurora_epaper = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio +bitops = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio +camera = false +canio = false +codeop = true +countio = false +cryptography = false +digitalio = true +displayio = true # Zephyr board has busio +dotclockframebuffer = false +dualbank = false +emmcio = false +epaperdisplay = true # Zephyr board has busio +floppyio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio +frequencyio = false +getpass = true +gifio = true # Zephyr board has busio +gnss = false +hardwarekey = false +hashlib = true +hmac = false +hostnetwork = false +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false +i2ctarget = false +imagecapture = false +ipaddress = false +is31fl3741 = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true +max3421e = false +mcp4822 = false +mdns = false +memorymap = false +memorymonitor = false +microcontroller = true +mii = false +mipicsi = false +mipidsi = false +msgpack = true +neopixel_write = false +nvm = true # Board has NVM partition +onewireio = false +os = true +paralleldisplaybus = false +picogame = false +picogame3d = false +ps2io = false +pulseio = false +pwmio = false +qrio = false +qspibus = false +rainbowio = true +random = true +rclcpy = false +rgbmatrix = false +rotaryio = true # Zephyr board has rotaryio +rtc = true # Zephyr board has rtc +sdcardio = true # Zephyr board has busio +sdioio = false +sharpdisplay = true # Zephyr board has busio +socketpool = false +spitarget = false +ssl = false +storage = true +struct = true +supervisor = true +synthio = false +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio +time = true +touchio = true +traceback = true +uheap = false +usb = false +usb_audio = false +usb_cdc = true +usb_hid = true +usb_host = false +usb_host_audio = false +usb_host_bulk = false +usb_midi = false +usb_video = false +ustack = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog +wifi = false +zephyr_display = false +zephyr_input = false +zephyr_kernel = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/adafruit/metro_m7_airlift_zephyr/board.conf b/ports/zephyr-cp/boards/adafruit/metro_m7_airlift_zephyr/board.conf new file mode 100644 index 00000000000..e4fd5782295 --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/metro_m7_airlift_zephyr/board.conf @@ -0,0 +1,4 @@ +# No Zephyr UART console by default (see board.overlay); a CONSOLE=1 build turns +# it back on in console.conf. +CONFIG_UART_CONSOLE=n +CONFIG_LOG_BACKEND_UART=n diff --git a/ports/zephyr-cp/boards/adafruit/metro_m7_airlift_zephyr/board.overlay b/ports/zephyr-cp/boards/adafruit/metro_m7_airlift_zephyr/board.overlay new file mode 100644 index 00000000000..3110b7bcbe5 --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/metro_m7_airlift_zephyr/board.overlay @@ -0,0 +1,29 @@ +/* No Zephyr console by default, so LPUART1 on D0/D1, which is also the + * ESP32's UART, is free for busio.UART, as in ports/mimxrt10xx. A CONSOLE=1 + * build puts the console back on LPUART1 (console.overlay). */ +/ { + chosen { + /delete-property/ zephyr,console; + /delete-property/ zephyr,shell-uart; + /delete-property/ zephyr,uart-mcumgr; + }; + + // Named pins that are not on the Arduino header, as in ports/mimxrt10xx. + // Their names are in circuitpython.toml [connectors.metro_m7_pins]. + metro_m7_pins: metro-m7-pins { + compatible = "adafruit-metro-m7-pins"; + #gpio-cells = <2>; + gpio-map-mask = <0xffffffff 0xffffffc0>; + gpio-map-pass-thru = <0 0x3f>; + gpio-map = <0 0 &gpio1 20 0>, /* SCK, GPIO_AD_06 */ + <1 0 &gpio1 18 0>, /* MOSI, GPIO_AD_04 */ + <2 0 &gpio1 17 0>, /* MISO, GPIO_AD_03 */ + <3 0 &gpio1 0 0>, /* NEOPIXEL, GPIO_00 */ + <4 0 &gpio1 28 0>, /* ESP_CS, GPIO_AD_14 */ + <5 0 &gpio1 25 0>, /* ESP_BUSY, GPIO_AD_11 */ + <6 0 &gpio1 21 0>, /* ESP_RESET, GPIO_AD_07 */ + <7 0 &gpio2 5 0>; /* ESP_GPIO0, GPIO_SD_05 */ + }; +}; + +#include "../../../app.overlay" diff --git a/ports/zephyr-cp/boards/adafruit/metro_m7_airlift_zephyr/circuitpython.toml b/ports/zephyr-cp/boards/adafruit/metro_m7_airlift_zephyr/circuitpython.toml new file mode 100644 index 00000000000..265f53116fc --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/metro_m7_airlift_zephyr/circuitpython.toml @@ -0,0 +1,44 @@ +CIRCUITPY_BUILD_EXTENSIONS = ["hex", "uf2"] +USB_VID=0x239A +USB_PID=0x80E2 +NAME="Metro M7 iMX RT1011 AirLift" + +# Pin names from ports/mimxrt10xx/boards/metro_m7_1011/pins.c. + +[connectors.arduino_header] +# The generic arduino-header-r3 names put SCK, MOSI and MISO on D13, D11 and +# D12, but the Metro's SPI pins are on the 2x3 header (metro_m7_pins below), +# and the classic port names SDA and SCL without D14 and D15. D0 and D1 are +# also the ESP32's UART. +"0" = "A0" +"1" = "A1" +"2" = "A2" +"3" = "A3" +"4" = "A4" +"5" = "A5" +"6" = ["D0", "RX", "ESP_RX"] +"7" = ["D1", "TX", "ESP_TX"] +"8" = "D2" +"9" = "D3" +"10" = "D4" +"11" = "D5" +"12" = "D6" +"13" = "D7" +"14" = "D8" +"15" = ["D9", "I2S_BIT_CLOCK", "I2S_BCLK"] +"16" = ["D10", "I2S_WORD_SELECT", "I2S_WSEL"] +"17" = "D11" +"18" = ["D12", "I2S_DATA", "I2S_DOUT"] +"19" = "D13" +"20" = "SDA" +"21" = "SCL" + +[connectors.metro_m7_pins] +"0" = "SCK" +"1" = "MOSI" +"2" = "MISO" +"3" = "NEOPIXEL" +"4" = "ESP_CS" +"5" = "ESP_BUSY" +"6" = "ESP_RESET" +"7" = "ESP_GPIO0" diff --git a/ports/zephyr-cp/boards/adafruit/metro_m7_airlift_zephyr/console.overlay b/ports/zephyr-cp/boards/adafruit/metro_m7_airlift_zephyr/console.overlay new file mode 100644 index 00000000000..2e046552ad2 --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/metro_m7_airlift_zephyr/console.overlay @@ -0,0 +1,9 @@ +/* Applied after board.overlay in CONSOLE=1 and DEBUG=1 builds: the Zephyr + * console on LPUART1, D0/D1. D0/D1 are then not available to busio.UART. */ +/ { + chosen { + zephyr,console = &lpuart1; + zephyr,shell-uart = &lpuart1; + zephyr,uart-mcumgr = &lpuart1; + }; +}; diff --git a/ports/zephyr-cp/boards/adafruit/metro_m7_zephyr/autogen_board_info.toml b/ports/zephyr-cp/boards/adafruit/metro_m7_zephyr/autogen_board_info.toml new file mode 100644 index 00000000000..c4350345295 --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/metro_m7_zephyr/autogen_board_info.toml @@ -0,0 +1,145 @@ +# This file is autogenerated when a board is built. Do not edit. Do commit it to git. Other scripts use its info. +name = "Adafruit Industries LLC Metro M7 iMX RT1011 SD" + +[modules] +__future__ = true +_airlift = false +_bleio = false +_eve = false +_pew = false +_pixelmap = false +_stage = false +adafruit_bus_device = true +adafruit_pixelbuf = false +aesio = true +alarm = false +analogbufio = false +analogio = false +async_spi = true # Zephyr board has async_spi +atexit = true +audiobusio = false +audiocore = false +audiodelays = false +audiofilewriter = false +audiofilters = false +audiofreeverb = false +audioi2sin = false +audioio = false +audiomixer = false +audiomp3 = false +audiopwmio = false +audiospeed = false +audiotap = false +aurora_epaper = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio +bitops = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio +camera = false +canio = false +codeop = true +countio = false +cryptography = false +digitalio = true +displayio = true # Zephyr board has busio +dotclockframebuffer = false +dualbank = false +emmcio = false +epaperdisplay = true # Zephyr board has busio +floppyio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio +frequencyio = false +getpass = true +gifio = true # Zephyr board has busio +gnss = false +hardwarekey = false +hashlib = true +hmac = false +hostnetwork = false +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false +i2ctarget = false +imagecapture = false +ipaddress = false +is31fl3741 = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true +max3421e = false +mcp4822 = false +mdns = false +memorymap = false +memorymonitor = false +microcontroller = true +mii = false +mipicsi = false +mipidsi = false +msgpack = true +neopixel_write = false +nvm = true # Board has NVM partition +onewireio = false +os = true +paralleldisplaybus = false +picogame = false +picogame3d = false +ps2io = false +pulseio = false +pwmio = false +qrio = false +qspibus = false +rainbowio = true +random = true +rclcpy = false +rgbmatrix = false +rotaryio = true # Zephyr board has rotaryio +rtc = true # Zephyr board has rtc +sdcardio = true # Zephyr board has busio +sdioio = false +sharpdisplay = true # Zephyr board has busio +socketpool = false +spitarget = false +ssl = false +storage = true +struct = true +supervisor = true +synthio = false +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio +time = true +touchio = true +traceback = true +uheap = false +usb = false +usb_audio = false +usb_cdc = true +usb_hid = true +usb_host = false +usb_host_audio = false +usb_host_bulk = false +usb_midi = false +usb_video = false +ustack = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog +wifi = false +zephyr_display = false +zephyr_input = false +zephyr_kernel = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/adafruit/metro_m7_zephyr/board.conf b/ports/zephyr-cp/boards/adafruit/metro_m7_zephyr/board.conf new file mode 100644 index 00000000000..e4fd5782295 --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/metro_m7_zephyr/board.conf @@ -0,0 +1,4 @@ +# No Zephyr UART console by default (see board.overlay); a CONSOLE=1 build turns +# it back on in console.conf. +CONFIG_UART_CONSOLE=n +CONFIG_LOG_BACKEND_UART=n diff --git a/ports/zephyr-cp/boards/adafruit/metro_m7_zephyr/board.overlay b/ports/zephyr-cp/boards/adafruit/metro_m7_zephyr/board.overlay new file mode 100644 index 00000000000..67abe25b3e3 --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/metro_m7_zephyr/board.overlay @@ -0,0 +1,27 @@ +/* No Zephyr console by default, so LPUART1 on D0/D1 is free for busio.UART, + * as in ports/mimxrt10xx. A CONSOLE=1 build puts the console back on LPUART1 + * (console.overlay). */ +/ { + chosen { + /delete-property/ zephyr,console; + /delete-property/ zephyr,shell-uart; + /delete-property/ zephyr,uart-mcumgr; + }; + + // Named pins that are not on the Arduino header, as in ports/mimxrt10xx. + // Their names are in circuitpython.toml [connectors.metro_m7_pins]. + metro_m7_pins: metro-m7-pins { + compatible = "adafruit-metro-m7-pins"; + #gpio-cells = <2>; + gpio-map-mask = <0xffffffff 0xffffffc0>; + gpio-map-pass-thru = <0 0x3f>; + gpio-map = <0 0 &gpio1 20 0>, /* SCK, GPIO_AD_06 */ + <1 0 &gpio1 18 0>, /* MOSI, GPIO_AD_04 */ + <2 0 &gpio1 17 0>, /* MISO, GPIO_AD_03 */ + <3 0 &gpio1 0 0>, /* NEOPIXEL, GPIO_00 */ + <4 0 &gpio1 28 0>, /* SD_CS, GPIO_AD_14 */ + <5 0 &gpio1 25 0>; /* SD_CD, GPIO_AD_11 */ + }; +}; + +#include "../../../app.overlay" diff --git a/ports/zephyr-cp/boards/adafruit/metro_m7_zephyr/circuitpython.toml b/ports/zephyr-cp/boards/adafruit/metro_m7_zephyr/circuitpython.toml new file mode 100644 index 00000000000..e469f241028 --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/metro_m7_zephyr/circuitpython.toml @@ -0,0 +1,41 @@ +CIRCUITPY_BUILD_EXTENSIONS = ["hex", "uf2"] +USB_VID=0x239A +USB_PID=0x8142 +NAME="Metro M7 iMX RT1011 SD" + +# Pin names from ports/mimxrt10xx/boards/adafruit_metro_m7_1011_sd/pins.c. + +[connectors.arduino_header] +# The generic arduino-header-r3 names put SCK, MOSI and MISO on D13, D11 and +# D12, but the Metro's SPI pins are on the 2x3 header (metro_m7_pins below), +# and the classic port names SDA and SCL without D14 and D15. +"0" = "A0" +"1" = "A1" +"2" = "A2" +"3" = "A3" +"4" = "A4" +"5" = "A5" +"6" = ["D0", "RX"] +"7" = ["D1", "TX"] +"8" = "D2" +"9" = "D3" +"10" = "D4" +"11" = "D5" +"12" = "D6" +"13" = "D7" +"14" = "D8" +"15" = ["D9", "I2S_BIT_CLOCK"] +"16" = ["D10", "I2S_WORD_SELECT"] +"17" = "D11" +"18" = ["D12", "I2S_DATA"] +"19" = "D13" +"20" = "SDA" +"21" = "SCL" + +[connectors.metro_m7_pins] +"0" = "SCK" +"1" = "MOSI" +"2" = "MISO" +"3" = "NEOPIXEL" +"4" = "SD_CS" +"5" = "SD_CD" diff --git a/ports/zephyr-cp/boards/adafruit/metro_m7_zephyr/console.overlay b/ports/zephyr-cp/boards/adafruit/metro_m7_zephyr/console.overlay new file mode 100644 index 00000000000..2e046552ad2 --- /dev/null +++ b/ports/zephyr-cp/boards/adafruit/metro_m7_zephyr/console.overlay @@ -0,0 +1,9 @@ +/* Applied after board.overlay in CONSOLE=1 and DEBUG=1 builds: the Zephyr + * console on LPUART1, D0/D1. D0/D1 are then not available to busio.UART. */ +/ { + chosen { + zephyr,console = &lpuart1; + zephyr,shell-uart = &lpuart1; + zephyr,uart-mcumgr = &lpuart1; + }; +}; diff --git a/ports/zephyr-cp/boards/board_aliases.cmake b/ports/zephyr-cp/boards/board_aliases.cmake index b8df9fb87f5..d7b9e2454e3 100644 --- a/ports/zephyr-cp/boards/board_aliases.cmake +++ b/ports/zephyr-cp/boards/board_aliases.cmake @@ -1,8 +1,52 @@ -set(pca10056_BOARD_ALIAS nrf52840dk/nrf52840) -set(renesas_ek_ra6m5_BOARD_ALIAS ek_ra6m5) -set(renesas_ek_ra8d1_BOARD_ALIAS ek_ra8d1) -set(nordic_nrf54l15dk_BOARD_ALIAS nrf54l15dk/nrf54l15/cpuapp) -set(nordic_nrf5340dk_BOARD_ALIAS nrf5340dk/nrf5340/cpuapp) -set(nordic_nrf7002dk_BOARD_ALIAS nrf7002dk/nrf5340/cpuapp) -set(st_stm32h7b3i_dk_BOARD_ALIAS stm32h7b3i_dk) -set(st_nucleo_u575zi_q_BOARD_ALIAS nucleo_u575zi_q/stm32u575xx) +# Translate CircuitPython board names to full Zephyr board targets. +# +# Zephyr loads this file before it splits BOARD into name, revision and +# qualifiers, so setting BOARD to the full target is enough. +macro(cp_board_alias alias target) + if(BOARD STREQUAL "${alias}") + set(BOARD_ALIAS "${alias}" CACHE STRING "Board alias, provided by user") + set(BOARD "${target}") + endif() +endmacro() + +cp_board_alias(adafruit_circuitplayground_bluefruit_zephyr adafruit_circuitplayground_bluefruit/nrf52840/uf2) +cp_board_alias(adafruit_clue_nrf52840_zephyr adafruit_clue_nrf52840/nrf52840/uf2) +cp_board_alias(adafruit_feather_nrf52840_zephyr adafruit_feather_nrf52840/nrf52840/uf2) +cp_board_alias(adafruit_feather_nrf52840_sense_zephyr adafruit_feather_nrf52840/nrf52840/sense/uf2) +cp_board_alias(adafruit_feather_rp2040_zephyr adafruit_feather_rp2040/rp2040) +cp_board_alias(adafruit_itsybitsy_nrf52840_zephyr adafruit_itsybitsy/nrf52840) +cp_board_alias(adafruit_macropad_rp2040_zephyr adafruit_macropad_rp2040/rp2040) +cp_board_alias(adafruit_metro_ch32v407_zephyr adafruit_metro_ch32v407) +cp_board_alias(adafruit_metro_ch32v467_zephyr adafruit_metro_ch32v467) +cp_board_alias(adafruit_metro_m7_zephyr adafruit_metro_m7) +cp_board_alias(adafruit_metro_m7_airlift_zephyr adafruit_metro_m7_airlift) +cp_board_alias(native_native_sim native_sim/native) +cp_board_alias(native_native_sim_asan native_sim/native) +cp_board_alias(native_native_sim_lfs native_sim/native) +cp_board_alias(native_native_sim_lvgl native_sim/native) +cp_board_alias(native_native_sim_lvgl_asan native_sim/native) +cp_board_alias(native_nrf5340bsim nrf5340bsim/nrf5340/cpuapp) +cp_board_alias(native_nrf54lm20bsim nrf54lm20bsim/nrf54lm20a/cpuapp) +cp_board_alias(nordic_nrf5340dk nrf5340dk/nrf5340/cpuapp) +cp_board_alias(nordic_nrf54h20dk nrf54h20dk/nrf54h20/cpuapp) +cp_board_alias(nordic_nrf54l15dk nrf54l15dk/nrf54l15/cpuapp) +cp_board_alias(nordic_nrf54l15tag nrf54l15tag/nrf54l15/cpuapp) +cp_board_alias(nordic_nrf54lm20dk nrf54lm20dk/nrf54lm20a/cpuapp) +cp_board_alias(nxp_frdm_mcxn947 frdm_mcxn947/mcxn947/cpu0) +cp_board_alias(nxp_frdm_rw612 frdm_rw612) +cp_board_alias(nxp_mimxrt1010_evk mimxrt1010_evk) +cp_board_alias(nxp_mimxrt1170_evk mimxrt1170_evk@A/mimxrt1176/cm7) +cp_board_alias(pca10056 nrf52840dk/nrf52840) +cp_board_alias(raspberrypi_rpi_pico_zephyr rpi_pico/rp2040) +cp_board_alias(raspberrypi_rpi_pico_w_zephyr rpi_pico/rp2040/w) +cp_board_alias(raspberrypi_rpi_pico2_zephyr rpi_pico2/rp2350a/m33_0) +cp_board_alias(raspberrypi_rpi_pico2_w_zephyr rpi_pico2/rp2350a/m33_0/w) +cp_board_alias(renesas_da14695_dk_usb da14695_dk_usb) +cp_board_alias(renesas_ek_ra6m5 ek_ra6m5) +cp_board_alias(renesas_ek_ra8d1 ek_ra8d1) +cp_board_alias(silabs_siwx917_dk2605a siwx917_dk2605a) +cp_board_alias(st_nucleo_n657x0_q nucleo_n657x0_q/stm32n657xx) +cp_board_alias(st_nucleo_u575zi_q nucleo_u575zi_q/stm32u575xx) +cp_board_alias(st_stm32h750b_dk stm32h750b_dk/stm32h750xx/ext_flash_app) +cp_board_alias(st_stm32h7b3i_dk stm32h7b3i_dk) +cp_board_alias(st_stm32wba65i_dk1 stm32wba65i_dk1) diff --git a/ports/zephyr-cp/boards/ek_ra8d1.overlay b/ports/zephyr-cp/boards/ek_ra8d1.overlay deleted file mode 100644 index 29735d02b8f..00000000000 --- a/ports/zephyr-cp/boards/ek_ra8d1.overlay +++ /dev/null @@ -1,3 +0,0 @@ -&s28hl512t { - /delete-node/ partitions; -}; diff --git a/ports/zephyr-cp/boards/mcuboot_siwx917_dk2605a.conf b/ports/zephyr-cp/boards/mcuboot_siwx917_dk2605a.conf new file mode 100644 index 00000000000..c330b45f498 --- /dev/null +++ b/ports/zephyr-cp/boards/mcuboot_siwx917_dk2605a.conf @@ -0,0 +1,7 @@ +# The ROM only boots MCUboot through the RPS header in zephyr.rps. With a .hex +# present, west flash writes that instead and leaves the header page stale. +CONFIG_BUILD_OUTPUT_HEX=n + +# Instruction fetch from flash goes through the icache, so turning it off +# before jumping to the app hangs MCUboot. +CONFIG_BOOT_DISABLE_CACHES=n diff --git a/ports/zephyr-cp/boards/native/native_sim/autogen_board_info.toml b/ports/zephyr-cp/boards/native/native_sim/autogen_board_info.toml new file mode 100644 index 00000000000..7d1f7929d5c --- /dev/null +++ b/ports/zephyr-cp/boards/native/native_sim/autogen_board_info.toml @@ -0,0 +1,145 @@ +# This file is autogenerated when a board is built. Do not edit. Do commit it to git. Other scripts use its info. +name = "zephyr Native simulator - native_sim" + +[modules] +__future__ = true +_airlift = false +_bleio = false +_eve = false +_pew = false +_pixelmap = false +_stage = false +adafruit_bus_device = true +adafruit_pixelbuf = false +aesio = true +alarm = false +analogbufio = false +analogio = true # Zephyr board has analogio +async_spi = true # Zephyr board has async_spi +atexit = true +audiobusio = true # Zephyr board has audiobusio +audiocore = true # Zephyr board has audiobusio +audiodelays = true # Zephyr board has audiobusio +audiofilewriter = false +audiofilters = true # Zephyr board has audiobusio +audiofreeverb = true # Zephyr board has audiobusio +audioi2sin = false +audioio = false +audiomixer = true # Zephyr board has audiobusio +audiomp3 = true # Zephyr board has audiobusio +audiopwmio = false +audiospeed = false +audiotap = true # Zephyr board has audiobusio +aurora_epaper = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio +bitops = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio +camera = false +canio = false +codeop = true +countio = false +cryptography = false +digitalio = true +displayio = true # Zephyr board has displayio +dotclockframebuffer = false +dualbank = false +emmcio = false +epaperdisplay = true # Zephyr board has busio +floppyio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio +frequencyio = false +getpass = true +gifio = true # Zephyr board has busio +gnss = false +hardwarekey = false +hashlib = true # Zephyr networking enabled +hmac = false +hostnetwork = true # Zephyr board has hostnetwork +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false +i2ctarget = false +imagecapture = false +ipaddress = true # Zephyr networking enabled +is31fl3741 = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true +max3421e = false +mcp4822 = false +mdns = false +memorymap = false +memorymonitor = false +microcontroller = true +mii = false +mipicsi = false +mipidsi = false +msgpack = true +neopixel_write = false +nvm = true # Board has NVM partition +onewireio = false +os = true +paralleldisplaybus = false +picogame = false +picogame3d = false +ps2io = false +pulseio = false +pwmio = true # Zephyr board has pwmio +qrio = false +qspibus = false +rainbowio = true +random = true +rclcpy = false +rgbmatrix = false +rotaryio = true # Zephyr board has rotaryio +rtc = true # Zephyr board has rtc +sdcardio = true # Zephyr board has busio +sdioio = false +sharpdisplay = true # Zephyr board has busio +socketpool = true # Zephyr networking enabled +spitarget = false +ssl = true # Zephyr hostnetwork enabled +storage = true # Zephyr board has flash +struct = true +supervisor = true +synthio = true # Zephyr board has audiobusio +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio +time = true +touchio = true +traceback = true +uheap = false +usb = false +usb_audio = false +usb_cdc = false +usb_hid = false +usb_host = false +usb_host_audio = false +usb_host_bulk = false +usb_midi = false +usb_video = false +ustack = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog +wifi = false +zephyr_display = true # Zephyr board has zephyr_display +zephyr_input = true # Zephyr board has zephyr_input +zephyr_kernel = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/native/native_sim/board.conf b/ports/zephyr-cp/boards/native/native_sim/board.conf new file mode 100644 index 00000000000..6374db35701 --- /dev/null +++ b/ports/zephyr-cp/boards/native/native_sim/board.conf @@ -0,0 +1,69 @@ +# No Bluetooth hardware on native_sim +CONFIG_BT=n + +# native_sim has no physical package: use the identity package pin map so +# pin objects (LED, P_00..P_31) resolve to their GPIO controller. +CONFIG_IOBROKER_PACKAGE_ONE_TO_ONE=y + +CONFIG_EMUL=y +CONFIG_GPIO=y +CONFIG_NATIVE_SIM_SLOWDOWN_TO_REAL_TIME=n + +# So we can test safe mode +CONFIG_NATIVE_SIM_REBOOT=y + +CONFIG_TRACING=y +CONFIG_TRACING_PERFETTO=y +CONFIG_TRACING_SYNC=y +CONFIG_TRACING_BACKEND_POSIX=y +CONFIG_TRACING_GPIO=y + +# I2C emulation for testing +CONFIG_I2C_EMUL=y + +# Display emulation for display/terminal golden tests. +CONFIG_DISPLAY=y +CONFIG_SDL_DISPLAY=y +# Don't require hardware acceleration so the software renderer can be used. +CONFIG_SDL_DISPLAY_USE_HARDWARE_ACCELERATOR=n + +# Legacy scanline displayio compositor (CIRCUITPY_DISPLAYIO_LVGL=0). The +# LVGL-based compositor is exercised by the native_sim_lvgl board; this board +# keeps the scanline core and the display-side modules it needs (busdisplay, +# fourwire, i2cdisplaybus, vectorio, ...). + +# EEPROM emulation for testing +CONFIG_EEPROM=y +CONFIG_EEPROM_AT24=y +CONFIG_EEPROM_AT2X_EMUL=y + +# ADC emulation for analogio testing +CONFIG_ADC=y +CONFIG_ADC_EMUL=y + +# DAC emulation for analogio testing (the vnd,dac node in the board overlay +# turns on CONFIG_DAC_TEST) +CONFIG_DAC=y + +# PWM emulation for pwmio testing (the adafruit,pwm-emul nodes in the board +# overlay turn on CONFIG_PWM_ADAFRUIT_EMUL) +CONFIG_PWM=y + +# I2S SDL emulation for audio testing +CONFIG_I2S_SDL=y + +CONFIG_NETWORKING=y +CONFIG_NET_IPV4=y +CONFIG_NET_TCP=y +CONFIG_NET_SOCKETS=y +CONFIG_ETH_NATIVE_TAP=n +CONFIG_NET_DRIVERS=y +CONFIG_NET_SOCKETS_OFFLOAD=y +CONFIG_NET_NATIVE_OFFLOADED_SOCKETS=y +CONFIG_HEAP_MEM_POOL_SIZE=1024 + +CONFIG_NET_LOG=y + +CONFIG_MBEDTLS=y +CONFIG_PSA_WANT_ALG_SHA_1=y +CONFIG_PSA_WANT_ALG_SHA_256=y diff --git a/ports/zephyr-cp/boards/native/native_sim/board.overlay b/ports/zephyr-cp/boards/native/native_sim/board.overlay new file mode 100644 index 00000000000..3d4776350dd --- /dev/null +++ b/ports/zephyr-cp/boards/native/native_sim/board.overlay @@ -0,0 +1,98 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * Device tree overlay for CircuitPython on native_sim. + * Adds simulated SRAM region required by CircuitPython build system. + */ + +#include + +/* Partition layout is owned by the mcuboot fork (dts/native/native_sim.dtsi) + * and applied to this image by sysbuild. This overlay only adds board/app config. */ + +/ { + sram0: memory@20000000 { + device_type = "memory"; + compatible = "zephyr,memory-region", "mmio-sram"; + reg = <0x20000000 DT_SIZE_M(1)>; + zephyr,memory-region = "SRAM"; + }; + + chosen { + zephyr,sram = &sram0; + /delete-property/ zephyr,flash; + }; +}; + +/* Add emulated I2C devices for testing */ +&i2c0 { + at24_eeprom: eeprom@50 { + compatible = "atmel,at24"; + reg = <0x50>; + size = <256>; + pagesize = <8>; + address-width = <8>; + timeout = <5>; + }; +}; + +/* A second PTY UART, so there is a UART that isn't the console (uart0): + * board.UART() and the busio.UART tests use it. */ +&uart1 { + status = "okay"; +}; + +/* Expand ADC channels for analogio tests. */ +&adc0 { + nchannels = <4>; + ref-internal-mv = <3300>; + ref-vdd-mv = <3300>; +}; + +/* Emulated watchdog for the watchdog module, built on the native_sim counter + * like Zephyr's own watchdog tests do (tests/drivers/watchdog). */ +/ { + wdt_counter: wdt-counter { + compatible = "zephyr,counter-watchdog"; + status = "okay"; + counter = <&counter0>; + }; + + aliases { + watchdog0 = &wdt_counter; + }; +}; + +/ { + dac0: dac { + compatible = "vnd,dac"; + status = "okay"; + #io-channel-cells = <1>; + vref-mv = <3300>; + }; +}; + +/* Emulated PWM controller for pwmio tests: one channel per gpio_emul pin + * and two period groups that any channel can join, clocked at 16 MHz. */ +/ { + pwm_emul: pwm-emul { + compatible = "adafruit,pwm-emul"; + status = "okay"; + #pwm-cells = <3>; + channels = <32>; + groups = <2>; + clock-frequency = <16000000>; + }; +}; + + +/* An SPI loopback for testing: MOSI wired to MISO. */ +&spi0 { + loopback: loopback@0 { + compatible = "circuitpython,spi-loopback"; + reg = <0>; + spi-max-frequency = <50000000>; + }; +}; + +#include "../../../app.overlay" diff --git a/ports/zephyr-cp/boards/native/native_sim/circuitpython.toml b/ports/zephyr-cp/boards/native/native_sim/circuitpython.toml new file mode 100644 index 00000000000..7177c825f17 --- /dev/null +++ b/ports/zephyr-cp/boards/native/native_sim/circuitpython.toml @@ -0,0 +1 @@ +CIRCUITPY_BUILD_EXTENSIONS = ["exe"] diff --git a/ports/zephyr-cp/boards/native/native_sim_asan/autogen_board_info.toml b/ports/zephyr-cp/boards/native/native_sim_asan/autogen_board_info.toml new file mode 100644 index 00000000000..7d1f7929d5c --- /dev/null +++ b/ports/zephyr-cp/boards/native/native_sim_asan/autogen_board_info.toml @@ -0,0 +1,145 @@ +# This file is autogenerated when a board is built. Do not edit. Do commit it to git. Other scripts use its info. +name = "zephyr Native simulator - native_sim" + +[modules] +__future__ = true +_airlift = false +_bleio = false +_eve = false +_pew = false +_pixelmap = false +_stage = false +adafruit_bus_device = true +adafruit_pixelbuf = false +aesio = true +alarm = false +analogbufio = false +analogio = true # Zephyr board has analogio +async_spi = true # Zephyr board has async_spi +atexit = true +audiobusio = true # Zephyr board has audiobusio +audiocore = true # Zephyr board has audiobusio +audiodelays = true # Zephyr board has audiobusio +audiofilewriter = false +audiofilters = true # Zephyr board has audiobusio +audiofreeverb = true # Zephyr board has audiobusio +audioi2sin = false +audioio = false +audiomixer = true # Zephyr board has audiobusio +audiomp3 = true # Zephyr board has audiobusio +audiopwmio = false +audiospeed = false +audiotap = true # Zephyr board has audiobusio +aurora_epaper = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio +bitops = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio +camera = false +canio = false +codeop = true +countio = false +cryptography = false +digitalio = true +displayio = true # Zephyr board has displayio +dotclockframebuffer = false +dualbank = false +emmcio = false +epaperdisplay = true # Zephyr board has busio +floppyio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio +frequencyio = false +getpass = true +gifio = true # Zephyr board has busio +gnss = false +hardwarekey = false +hashlib = true # Zephyr networking enabled +hmac = false +hostnetwork = true # Zephyr board has hostnetwork +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false +i2ctarget = false +imagecapture = false +ipaddress = true # Zephyr networking enabled +is31fl3741 = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true +max3421e = false +mcp4822 = false +mdns = false +memorymap = false +memorymonitor = false +microcontroller = true +mii = false +mipicsi = false +mipidsi = false +msgpack = true +neopixel_write = false +nvm = true # Board has NVM partition +onewireio = false +os = true +paralleldisplaybus = false +picogame = false +picogame3d = false +ps2io = false +pulseio = false +pwmio = true # Zephyr board has pwmio +qrio = false +qspibus = false +rainbowio = true +random = true +rclcpy = false +rgbmatrix = false +rotaryio = true # Zephyr board has rotaryio +rtc = true # Zephyr board has rtc +sdcardio = true # Zephyr board has busio +sdioio = false +sharpdisplay = true # Zephyr board has busio +socketpool = true # Zephyr networking enabled +spitarget = false +ssl = true # Zephyr hostnetwork enabled +storage = true # Zephyr board has flash +struct = true +supervisor = true +synthio = true # Zephyr board has audiobusio +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio +time = true +touchio = true +traceback = true +uheap = false +usb = false +usb_audio = false +usb_cdc = false +usb_hid = false +usb_host = false +usb_host_audio = false +usb_host_bulk = false +usb_midi = false +usb_video = false +ustack = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog +wifi = false +zephyr_display = true # Zephyr board has zephyr_display +zephyr_input = true # Zephyr board has zephyr_input +zephyr_kernel = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/native/native_sim_asan/board.conf b/ports/zephyr-cp/boards/native/native_sim_asan/board.conf new file mode 100644 index 00000000000..34f319ed8a2 --- /dev/null +++ b/ports/zephyr-cp/boards/native/native_sim_asan/board.conf @@ -0,0 +1,71 @@ +# Build with AddressSanitizer to catch memory errors in tests. +CONFIG_ASAN=y + +# No Bluetooth hardware on native_sim +CONFIG_BT=n + +# native_sim has no physical package: use the identity package pin map so +# pin objects (LED, P_00..P_31) resolve to their GPIO controller. +CONFIG_IOBROKER_PACKAGE_ONE_TO_ONE=y + +CONFIG_EMUL=y +CONFIG_GPIO=y +CONFIG_NATIVE_SIM_SLOWDOWN_TO_REAL_TIME=n + +# So we can test safe mode +CONFIG_NATIVE_SIM_REBOOT=y + +CONFIG_TRACING=y +CONFIG_TRACING_PERFETTO=y +CONFIG_TRACING_SYNC=y +CONFIG_TRACING_BACKEND_POSIX=y +CONFIG_TRACING_GPIO=y + +# I2C emulation for testing +CONFIG_I2C_EMUL=y + +# Display emulation for display/terminal golden tests. +CONFIG_DISPLAY=y +CONFIG_SDL_DISPLAY=y +# Don't require hardware acceleration so the software renderer can be used. +CONFIG_SDL_DISPLAY_USE_HARDWARE_ACCELERATOR=n + +# Legacy scanline displayio compositor (CIRCUITPY_DISPLAYIO_LVGL=0); see +# native_sim/board.conf. The ASan board exists to catch memory errors in the +# default (legacy) build. + +# EEPROM emulation for testing +CONFIG_EEPROM=y +CONFIG_EEPROM_AT24=y +CONFIG_EEPROM_AT2X_EMUL=y + +# ADC emulation for analogio testing +CONFIG_ADC=y +CONFIG_ADC_EMUL=y + +# DAC emulation for analogio testing (the vnd,dac node in the board overlay +# turns on CONFIG_DAC_TEST) +CONFIG_DAC=y + +# PWM emulation for pwmio testing (the adafruit,pwm-emul nodes in the board +# overlay turn on CONFIG_PWM_ADAFRUIT_EMUL) +CONFIG_PWM=y + +# I2S SDL emulation for audio testing +CONFIG_I2S_SDL=y + +CONFIG_NETWORKING=y +CONFIG_NET_IPV4=y +CONFIG_NET_TCP=y +CONFIG_NET_SOCKETS=y +CONFIG_ETH_NATIVE_TAP=n +CONFIG_NET_DRIVERS=y +CONFIG_NET_SOCKETS_OFFLOAD=y +CONFIG_NET_NATIVE_OFFLOADED_SOCKETS=y +CONFIG_HEAP_MEM_POOL_SIZE=1024 + +CONFIG_NET_LOG=y + +CONFIG_MBEDTLS=y +CONFIG_PSA_WANT_ALG_SHA_1=y +CONFIG_PSA_WANT_ALG_SHA_256=y diff --git a/ports/zephyr-cp/boards/native/native_sim_asan/board.overlay b/ports/zephyr-cp/boards/native/native_sim_asan/board.overlay new file mode 100644 index 00000000000..33cbc530998 --- /dev/null +++ b/ports/zephyr-cp/boards/native/native_sim_asan/board.overlay @@ -0,0 +1,8 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * Device tree overlay for CircuitPython on native_sim with AddressSanitizer. + * Identical hardware description to the non-asan board, so just reuse it. + */ + +#include "../native_sim/board.overlay" diff --git a/ports/zephyr-cp/boards/native/native_sim_asan/circuitpython.toml b/ports/zephyr-cp/boards/native/native_sim_asan/circuitpython.toml new file mode 100644 index 00000000000..7177c825f17 --- /dev/null +++ b/ports/zephyr-cp/boards/native/native_sim_asan/circuitpython.toml @@ -0,0 +1 @@ +CIRCUITPY_BUILD_EXTENSIONS = ["exe"] diff --git a/ports/zephyr-cp/boards/native/native_sim_lfs/autogen_board_info.toml b/ports/zephyr-cp/boards/native/native_sim_lfs/autogen_board_info.toml new file mode 100644 index 00000000000..dee6c6f9e88 --- /dev/null +++ b/ports/zephyr-cp/boards/native/native_sim_lfs/autogen_board_info.toml @@ -0,0 +1,145 @@ +# This file is autogenerated when a board is built. Do not edit. Do commit it to git. Other scripts use its info. +name = "zephyr Native simulator - littlefs filesystem" + +[modules] +__future__ = true +_airlift = false +_bleio = false +_eve = false +_pew = false +_pixelmap = false +_stage = false +adafruit_bus_device = true +adafruit_pixelbuf = false +aesio = true +alarm = false +analogbufio = false +analogio = true # Zephyr board has analogio +async_spi = true # Zephyr board has async_spi +atexit = true +audiobusio = true # Zephyr board has audiobusio +audiocore = true # Zephyr board has audiobusio +audiodelays = true # Zephyr board has audiobusio +audiofilewriter = false +audiofilters = true # Zephyr board has audiobusio +audiofreeverb = true # Zephyr board has audiobusio +audioi2sin = false +audioio = false +audiomixer = true # Zephyr board has audiobusio +audiomp3 = true # Zephyr board has audiobusio +audiopwmio = false +audiospeed = false +audiotap = true # Zephyr board has audiobusio +aurora_epaper = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio +bitops = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio +camera = false +canio = false +codeop = true +countio = false +cryptography = false +digitalio = true +displayio = true # Zephyr board has displayio +dotclockframebuffer = false +dualbank = false +emmcio = false +epaperdisplay = true # Zephyr board has busio +floppyio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio +frequencyio = false +getpass = true +gifio = true # Zephyr board has busio +gnss = false +hardwarekey = false +hashlib = true # Zephyr networking enabled +hmac = false +hostnetwork = true # Zephyr board has hostnetwork +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false +i2ctarget = false +imagecapture = false +ipaddress = true # Zephyr networking enabled +is31fl3741 = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true +max3421e = false +mcp4822 = false +mdns = false +memorymap = false +memorymonitor = false +microcontroller = true +mii = false +mipicsi = false +mipidsi = false +msgpack = true +neopixel_write = false +nvm = true # Board has NVM partition +onewireio = false +os = true +paralleldisplaybus = false +picogame = false +picogame3d = false +ps2io = false +pulseio = false +pwmio = true # Zephyr board has pwmio +qrio = false +qspibus = false +rainbowio = true +random = true +rclcpy = false +rgbmatrix = false +rotaryio = true # Zephyr board has rotaryio +rtc = true # Zephyr board has rtc +sdcardio = true # Zephyr board has busio +sdioio = false +sharpdisplay = true # Zephyr board has busio +socketpool = true # Zephyr networking enabled +spitarget = false +ssl = true # Zephyr hostnetwork enabled +storage = true # Zephyr board has flash +struct = true +supervisor = true +synthio = true # Zephyr board has audiobusio +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio +time = true +touchio = true +traceback = true +uheap = false +usb = false +usb_audio = false +usb_cdc = false +usb_hid = false +usb_host = false +usb_host_audio = false +usb_host_bulk = false +usb_midi = false +usb_video = false +ustack = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog +wifi = false +zephyr_display = true # Zephyr board has zephyr_display +zephyr_input = true # Zephyr board has zephyr_input +zephyr_kernel = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/native/native_sim_lfs/board.conf b/ports/zephyr-cp/boards/native/native_sim_lfs/board.conf new file mode 100644 index 00000000000..c5769b18bef --- /dev/null +++ b/ports/zephyr-cp/boards/native/native_sim_lfs/board.conf @@ -0,0 +1,60 @@ +# No Bluetooth hardware on native_sim +CONFIG_BT=n + +CONFIG_EMUL=y +CONFIG_GPIO=y +CONFIG_NATIVE_SIM_SLOWDOWN_TO_REAL_TIME=n + +# So we can test safe mode +CONFIG_NATIVE_SIM_REBOOT=y + +CONFIG_TRACING=y +CONFIG_TRACING_PERFETTO=y +CONFIG_TRACING_SYNC=y +CONFIG_TRACING_BACKEND_POSIX=y +CONFIG_TRACING_GPIO=y + +# I2C emulation for testing +CONFIG_I2C_EMUL=y + +# Display emulation for display/terminal golden tests. +CONFIG_DISPLAY=y +CONFIG_SDL_DISPLAY=y +# Don't require hardware acceleration so the software renderer can be used. +CONFIG_SDL_DISPLAY_USE_HARDWARE_ACCELERATOR=n + +# EEPROM emulation for testing +CONFIG_EEPROM=y +CONFIG_EEPROM_AT24=y +CONFIG_EEPROM_AT2X_EMUL=y + +# ADC emulation for analogio testing +CONFIG_ADC=y +CONFIG_ADC_EMUL=y + +# DAC emulation for analogio testing (the vnd,dac node in the board overlay +# turns on CONFIG_DAC_TEST) +CONFIG_DAC=y + +# PWM emulation for pwmio testing (the adafruit,pwm-emul nodes in the board +# overlay turn on CONFIG_PWM_ADAFRUIT_EMUL) +CONFIG_PWM=y + +# I2S SDL emulation for audio testing +CONFIG_I2S_SDL=y + +CONFIG_NETWORKING=y +CONFIG_NET_IPV4=y +CONFIG_NET_TCP=y +CONFIG_NET_SOCKETS=y +CONFIG_ETH_NATIVE_TAP=n +CONFIG_NET_DRIVERS=y +CONFIG_NET_SOCKETS_OFFLOAD=y +CONFIG_NET_NATIVE_OFFLOADED_SOCKETS=y +CONFIG_HEAP_MEM_POOL_SIZE=1024 + +CONFIG_NET_LOG=y + +CONFIG_MBEDTLS=y +CONFIG_PSA_WANT_ALG_SHA_1=y +CONFIG_PSA_WANT_ALG_SHA_256=y diff --git a/ports/zephyr-cp/boards/native/native_sim_lfs/board.overlay b/ports/zephyr-cp/boards/native/native_sim_lfs/board.overlay new file mode 100644 index 00000000000..a40d65d84f3 --- /dev/null +++ b/ports/zephyr-cp/boards/native/native_sim_lfs/board.overlay @@ -0,0 +1,127 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * Device tree overlay for CircuitPython on native_sim (littlefs filesystem). + * Same as the native_sim overlay, but the user filesystem partition node is + * named littlefs_partition to match the supervisor's littlefs build. + */ + +#include + +/* The mcuboot fork's layout (dts/native/native_sim.dtsi) is applied to this + * image first and names the filesystem node fatfs_partition. Replace the whole + * partition table so the filesystem node is littlefs_partition; the supervisor + * opens the filesystem by that nodelabel. The geometry must match the fork's + * layout: filesystem, then 8 KB storage, then 8 KB nvm. */ + +&flash0 { + /delete-node/ partitions; + + partitions { + #address-cells = <1>; + #size-cells = <1>; + + littlefs_partition: partition@0 { + compatible = "zephyr,mapped-partition"; + label = "filesystem"; + reg = <0x00000000 DT_SIZE_K(2032)>; + }; + + storage_partition: partition@1fc000 { + compatible = "zephyr,mapped-partition"; + label = "storage"; + reg = <0x001fc000 DT_SIZE_K(8)>; + }; + + nvm_partition: partition@1fe000 { + compatible = "zephyr,mapped-partition"; + label = "nvm"; + reg = <0x001fe000 0x00002000>; + }; + }; +}; + +/ { + sram0: memory@20000000 { + device_type = "memory"; + compatible = "zephyr,memory-region", "mmio-sram"; + reg = <0x20000000 DT_SIZE_M(1)>; + zephyr,memory-region = "SRAM"; + }; + + chosen { + zephyr,sram = &sram0; + /delete-property/ zephyr,flash; + }; +}; + +/* Add emulated I2C devices for testing */ +&i2c0 { + at24_eeprom: eeprom@50 { + compatible = "atmel,at24"; + reg = <0x50>; + size = <256>; + pagesize = <8>; + address-width = <8>; + timeout = <5>; + }; +}; + +/* A second PTY UART, so there is a UART that isn't the console (uart0): + * board.UART() and the busio.UART tests use it. */ +&uart1 { + status = "okay"; +}; + +/* Expand ADC channels for analogio tests. */ +&adc0 { + nchannels = <4>; + ref-internal-mv = <3300>; + ref-vdd-mv = <3300>; +}; + +/ { + dac0: dac { + compatible = "vnd,dac"; + status = "okay"; + #io-channel-cells = <1>; + vref-mv = <3300>; + }; + + /* Emulated watchdog for the watchdog module, built on the native_sim counter + * like Zephyr's own watchdog tests do (tests/drivers/watchdog). */ + wdt_counter: wdt-counter { + compatible = "zephyr,counter-watchdog"; + status = "okay"; + counter = <&counter0>; + }; + + aliases { + watchdog0 = &wdt_counter; + }; +}; + +/* Emulated PWM controller for pwmio tests: one channel per gpio_emul pin + * and two period groups that any channel can join, clocked at 16 MHz. */ +/ { + pwm_emul: pwm-emul { + compatible = "adafruit,pwm-emul"; + status = "okay"; + #pwm-cells = <3>; + channels = <32>; + groups = <2>; + clock-frequency = <16000000>; + }; +}; + + +#include "../../../app.overlay" + +/* An SPI loopback for testing: MOSI wired to MISO. */ +&spi0 { + loopback: loopback@0 { + compatible = "circuitpython,spi-loopback"; + reg = <0>; + spi-max-frequency = <50000000>; + }; +}; diff --git a/ports/zephyr-cp/boards/native/native_sim_lfs/circuitpython.toml b/ports/zephyr-cp/boards/native/native_sim_lfs/circuitpython.toml new file mode 100644 index 00000000000..f98422e04c7 --- /dev/null +++ b/ports/zephyr-cp/boards/native/native_sim_lfs/circuitpython.toml @@ -0,0 +1,2 @@ +NAME = "Native simulator - littlefs filesystem" +CIRCUITPY_BUILD_EXTENSIONS = ["exe"] diff --git a/ports/zephyr-cp/boards/native/native_sim_lvgl/autogen_board_info.toml b/ports/zephyr-cp/boards/native/native_sim_lvgl/autogen_board_info.toml new file mode 100644 index 00000000000..863142f4fe0 --- /dev/null +++ b/ports/zephyr-cp/boards/native/native_sim_lvgl/autogen_board_info.toml @@ -0,0 +1,145 @@ +# This file is autogenerated when a board is built. Do not edit. Do commit it to git. Other scripts use its info. +name = "zephyr Native simulator - LVGL displayio compositor" + +[modules] +__future__ = true +_airlift = false +_bleio = false +_eve = false +_pew = false +_pixelmap = false +_stage = false +adafruit_bus_device = true +adafruit_pixelbuf = false +aesio = true +alarm = false +analogbufio = false +analogio = true # Zephyr board has analogio +async_spi = true # Zephyr board has async_spi +atexit = true +audiobusio = true # Zephyr board has audiobusio +audiocore = true # Zephyr board has audiobusio +audiodelays = true # Zephyr board has audiobusio +audiofilewriter = false +audiofilters = true # Zephyr board has audiobusio +audiofreeverb = true # Zephyr board has audiobusio +audioi2sin = false +audioio = false +audiomixer = true # Zephyr board has audiobusio +audiomp3 = true # Zephyr board has audiobusio +audiopwmio = false +audiospeed = false +audiotap = true # Zephyr board has audiobusio +aurora_epaper = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio +bitops = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio +camera = false +canio = false +codeop = true +countio = false +cryptography = false +digitalio = true +displayio = true # Zephyr board has displayio +dotclockframebuffer = false +dualbank = false +emmcio = false +epaperdisplay = false # Legacy scanline display module; excluded from LVGL builds +floppyio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio +frequencyio = false +getpass = true +gifio = true # Zephyr board has busio +gnss = false +hardwarekey = false +hashlib = true # Zephyr networking enabled +hmac = false +hostnetwork = true # Zephyr board has hostnetwork +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false +i2ctarget = false +imagecapture = false +ipaddress = true # Zephyr networking enabled +is31fl3741 = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true +max3421e = false +mcp4822 = false +mdns = false +memorymap = false +memorymonitor = false +microcontroller = true +mii = false +mipicsi = false +mipidsi = false +msgpack = true +neopixel_write = false +nvm = true # Board has NVM partition +onewireio = false +os = true +paralleldisplaybus = false +picogame = false +picogame3d = false +ps2io = false +pulseio = false +pwmio = true # Zephyr board has pwmio +qrio = false +qspibus = false +rainbowio = true +random = true +rclcpy = false +rgbmatrix = false +rotaryio = true # Zephyr board has rotaryio +rtc = true # Zephyr board has rtc +sdcardio = true # Zephyr board has busio +sdioio = false +sharpdisplay = false # Legacy scanline display module; excluded from LVGL builds +socketpool = true # Zephyr networking enabled +spitarget = false +ssl = true # Zephyr hostnetwork enabled +storage = true # Zephyr board has flash +struct = true +supervisor = true +synthio = true # Zephyr board has audiobusio +terminalio = true # Zephyr board has busio +tilepalettemapper = false # Legacy scanline display module; excluded from LVGL builds +time = true +touchio = true +traceback = true +uheap = false +usb = false +usb_audio = false +usb_cdc = false +usb_hid = false +usb_host = false +usb_host_audio = false +usb_host_bulk = false +usb_midi = false +usb_video = false +ustack = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog +wifi = false +zephyr_display = true # Zephyr board has zephyr_display +zephyr_input = true # Zephyr board has zephyr_input +zephyr_kernel = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/native/native_sim_lvgl/board.conf b/ports/zephyr-cp/boards/native/native_sim_lvgl/board.conf new file mode 100644 index 00000000000..986b6bc913a --- /dev/null +++ b/ports/zephyr-cp/boards/native/native_sim_lvgl/board.conf @@ -0,0 +1,86 @@ +# No Bluetooth hardware on native_sim +CONFIG_BT=n + +# native_sim has no physical package: use the identity package pin map so +# pin objects (LED, P_00..P_31) resolve to their GPIO controller. +CONFIG_IOBROKER_PACKAGE_ONE_TO_ONE=y + +CONFIG_EMUL=y +CONFIG_GPIO=y +CONFIG_NATIVE_SIM_SLOWDOWN_TO_REAL_TIME=n +CONFIG_SPEED_OPTIMIZATIONS=y + +# So we can test safe mode +CONFIG_NATIVE_SIM_REBOOT=y + +CONFIG_TRACING=y +CONFIG_TRACING_PERFETTO=y +CONFIG_TRACING_SYNC=y +CONFIG_TRACING_BACKEND_POSIX=y +CONFIG_TRACING_GPIO=y + +# I2C emulation for testing +CONFIG_I2C_EMUL=y + +# Display emulation for display/terminal golden tests. +CONFIG_DISPLAY=y +CONFIG_SDL_DISPLAY=y +# Don't require hardware acceleration so the software renderer can be used. +CONFIG_SDL_DISPLAY_USE_HARDWARE_ACCELERATOR=n +# Keep the priority-5 CircuitPython audio thread above display/input work. +CONFIG_SDL_THREAD_PRIORITY=6 +CONFIG_SDL_DISPLAY_THREAD_PRIORITY=6 + +# Route SDL mouse button/motion events through Zephyr's touch input driver. +CONFIG_INPUT_SDL_TOUCH=y +CONFIG_INPUT_MODE_SYNCHRONOUS=y + +# LVGL-based displayio compositing core. LVGL renders on its own RTOS thread (this +# workqueue, also matching the RTOS deployment model); CircuitPython's compositor mirror +# mutations take the glue's LVGL mutex so they don't interleave with lv_timer_handler. +CONFIG_LVGL=y +CONFIG_LV_Z_RUN_LVGL_ON_WORKQUEUE=y +CONFIG_LV_Z_LVGL_WORKQUEUE_PRIORITY=6 +# LVGL allocates objects and draw buffers from its own heap sizing. +CONFIG_LV_Z_MEM_POOL_SIZE=16777216 +# Cache decoded images (OnDiskBitmaps and other LVGL images) so they're only decoded +# again when the source or palette changes. +CONFIG_LV_CACHE_DEF_SIZE=4194304 +# Print the areas LVGL redraws, so tests can check how much a change redraws. +CONFIG_CIRCUITPY_LVGL_PRINT_DIRTY_AREAS=y + +# EEPROM emulation for testing +CONFIG_EEPROM=y +CONFIG_EEPROM_AT24=y +CONFIG_EEPROM_AT2X_EMUL=y + +# ADC emulation for analogio testing +CONFIG_ADC=y +CONFIG_ADC_EMUL=y + +# DAC emulation for analogio testing (the vnd,dac node in the board overlay +# turns on CONFIG_DAC_TEST) +CONFIG_DAC=y + +# PWM emulation for pwmio testing (the adafruit,pwm-emul nodes in the board +# overlay turn on CONFIG_PWM_ADAFRUIT_EMUL) +CONFIG_PWM=y + +# I2S SDL emulation for audio testing +CONFIG_I2S_SDL=y + +CONFIG_NETWORKING=y +CONFIG_NET_IPV4=y +CONFIG_NET_TCP=y +CONFIG_NET_SOCKETS=y +CONFIG_ETH_NATIVE_TAP=n +CONFIG_NET_DRIVERS=y +CONFIG_NET_SOCKETS_OFFLOAD=y +CONFIG_NET_NATIVE_OFFLOADED_SOCKETS=y +CONFIG_HEAP_MEM_POOL_SIZE=1024 + +CONFIG_NET_LOG=y + +CONFIG_MBEDTLS=y +CONFIG_PSA_WANT_ALG_SHA_1=y +CONFIG_PSA_WANT_ALG_SHA_256=y diff --git a/ports/zephyr-cp/boards/native/native_sim_lvgl/board.overlay b/ports/zephyr-cp/boards/native/native_sim_lvgl/board.overlay new file mode 100644 index 00000000000..aebcb45bb14 --- /dev/null +++ b/ports/zephyr-cp/boards/native/native_sim_lvgl/board.overlay @@ -0,0 +1,9 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * Device tree overlay for CircuitPython on native_sim with the LVGL-based + * displayio compositor. Identical hardware description to the legacy-compositor + * board, so just reuse it. + */ + +#include "../native_sim/board.overlay" diff --git a/ports/zephyr-cp/boards/native/native_sim_lvgl/circuitpython.toml b/ports/zephyr-cp/boards/native/native_sim_lvgl/circuitpython.toml new file mode 100644 index 00000000000..bcff2a77f75 --- /dev/null +++ b/ports/zephyr-cp/boards/native/native_sim_lvgl/circuitpython.toml @@ -0,0 +1,2 @@ +NAME = "Native simulator - LVGL displayio compositor" +CIRCUITPY_BUILD_EXTENSIONS = ["exe"] diff --git a/ports/zephyr-cp/boards/native/native_sim_lvgl_asan/autogen_board_info.toml b/ports/zephyr-cp/boards/native/native_sim_lvgl_asan/autogen_board_info.toml new file mode 100644 index 00000000000..c4735eeb668 --- /dev/null +++ b/ports/zephyr-cp/boards/native/native_sim_lvgl_asan/autogen_board_info.toml @@ -0,0 +1,145 @@ +# This file is autogenerated when a board is built. Do not edit. Do commit it to git. Other scripts use its info. +name = "zephyr Native simulator - LVGL + ASan" + +[modules] +__future__ = true +_airlift = false +_bleio = false +_eve = false +_pew = false +_pixelmap = false +_stage = false +adafruit_bus_device = true +adafruit_pixelbuf = false +aesio = true +alarm = false +analogbufio = false +analogio = true # Zephyr board has analogio +async_spi = true # Zephyr board has async_spi +atexit = true +audiobusio = true # Zephyr board has audiobusio +audiocore = true # Zephyr board has audiobusio +audiodelays = true # Zephyr board has audiobusio +audiofilewriter = false +audiofilters = true # Zephyr board has audiobusio +audiofreeverb = true # Zephyr board has audiobusio +audioi2sin = false +audioio = false +audiomixer = true # Zephyr board has audiobusio +audiomp3 = true # Zephyr board has audiobusio +audiopwmio = false +audiospeed = false +audiotap = true # Zephyr board has audiobusio +aurora_epaper = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio +bitops = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio +camera = false +canio = false +codeop = true +countio = false +cryptography = false +digitalio = true +displayio = true # Zephyr board has displayio +dotclockframebuffer = false +dualbank = false +emmcio = false +epaperdisplay = false # Legacy scanline display module; excluded from LVGL builds +floppyio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio +frequencyio = false +getpass = true +gifio = true # Zephyr board has busio +gnss = false +hardwarekey = false +hashlib = true # Zephyr networking enabled +hmac = false +hostnetwork = true # Zephyr board has hostnetwork +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false +i2ctarget = false +imagecapture = false +ipaddress = true # Zephyr networking enabled +is31fl3741 = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true +max3421e = false +mcp4822 = false +mdns = false +memorymap = false +memorymonitor = false +microcontroller = true +mii = false +mipicsi = false +mipidsi = false +msgpack = true +neopixel_write = false +nvm = true # Board has NVM partition +onewireio = false +os = true +paralleldisplaybus = false +picogame = false +picogame3d = false +ps2io = false +pulseio = false +pwmio = true # Zephyr board has pwmio +qrio = false +qspibus = false +rainbowio = true +random = true +rclcpy = false +rgbmatrix = false +rotaryio = true # Zephyr board has rotaryio +rtc = true # Zephyr board has rtc +sdcardio = true # Zephyr board has busio +sdioio = false +sharpdisplay = false # Legacy scanline display module; excluded from LVGL builds +socketpool = true # Zephyr networking enabled +spitarget = false +ssl = true # Zephyr hostnetwork enabled +storage = true # Zephyr board has flash +struct = true +supervisor = true +synthio = true # Zephyr board has audiobusio +terminalio = true # Zephyr board has busio +tilepalettemapper = false # Legacy scanline display module; excluded from LVGL builds +time = true +touchio = true +traceback = true +uheap = false +usb = false +usb_audio = false +usb_cdc = false +usb_hid = false +usb_host = false +usb_host_audio = false +usb_host_bulk = false +usb_midi = false +usb_video = false +ustack = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog +wifi = false +zephyr_display = true # Zephyr board has zephyr_display +zephyr_input = true # Zephyr board has zephyr_input +zephyr_kernel = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/native/native_sim_lvgl_asan/board.conf b/ports/zephyr-cp/boards/native/native_sim_lvgl_asan/board.conf new file mode 100644 index 00000000000..926d977fe9c --- /dev/null +++ b/ports/zephyr-cp/boards/native/native_sim_lvgl_asan/board.conf @@ -0,0 +1,83 @@ +# AddressSanitizer covers both CircuitPython and LVGL. Poison allocations in +# LVGL's sys_heap too, so accesses to freed buffers and buffer overruns are caught. +# The big-heap format provides the 8-byte alignment ASan's shadow requires. +CONFIG_ASAN=y +CONFIG_ASAN_RECOVER=n +CONFIG_SYS_HEAP_BIG_ONLY=y +CONFIG_SYS_HEAP_SANITIZER_ASAN=y + +# No Bluetooth hardware on native_sim +CONFIG_BT=n + +# native_sim has no physical package: use the identity package pin map so +# pin objects (LED, P_00..P_31) resolve to their GPIO controller. +CONFIG_IOBROKER_PACKAGE_ONE_TO_ONE=y + +CONFIG_EMUL=y +CONFIG_GPIO=y +CONFIG_NATIVE_SIM_SLOWDOWN_TO_REAL_TIME=n + +# So we can test safe mode +CONFIG_NATIVE_SIM_REBOOT=y + +CONFIG_TRACING=y +CONFIG_TRACING_PERFETTO=y +CONFIG_TRACING_SYNC=y +CONFIG_TRACING_BACKEND_POSIX=y +CONFIG_TRACING_GPIO=y + +# I2C emulation for testing +CONFIG_I2C_EMUL=y + +# Display emulation for display/terminal golden tests. +CONFIG_DISPLAY=y +CONFIG_SDL_DISPLAY=y +# Don't require hardware acceleration so the software renderer can be used. +CONFIG_SDL_DISPLAY_USE_HARDWARE_ACCELERATOR=n + +# LVGL-based displayio compositing core. LVGL renders on its own RTOS thread (this +# workqueue, also matching the RTOS deployment model); CircuitPython's compositor mirror +# mutations take the glue's LVGL mutex so they don't interleave with lv_timer_handler. +CONFIG_LVGL=y +CONFIG_LV_Z_RUN_LVGL_ON_WORKQUEUE=y +# LVGL allocates objects and draw buffers from its own heap sizing. +CONFIG_LV_Z_MEM_POOL_SIZE=16777216 +# Cache decoded images (OnDiskBitmaps and other LVGL images) so they're only decoded +# again when the source or palette changes. +CONFIG_LV_CACHE_DEF_SIZE=4194304 + +# EEPROM emulation for testing +CONFIG_EEPROM=y +CONFIG_EEPROM_AT24=y +CONFIG_EEPROM_AT2X_EMUL=y + +# ADC emulation for analogio testing +CONFIG_ADC=y +CONFIG_ADC_EMUL=y + +# DAC emulation for analogio testing (the vnd,dac node in the board overlay +# turns on CONFIG_DAC_TEST) +CONFIG_DAC=y + +# PWM emulation for pwmio testing (the adafruit,pwm-emul nodes in the board +# overlay turn on CONFIG_PWM_ADAFRUIT_EMUL) +CONFIG_PWM=y + +# I2S SDL emulation for audio testing +CONFIG_I2S_SDL=y + +CONFIG_NETWORKING=y +CONFIG_NET_IPV4=y +CONFIG_NET_TCP=y +CONFIG_NET_SOCKETS=y +CONFIG_ETH_NATIVE_TAP=n +CONFIG_NET_DRIVERS=y +CONFIG_NET_SOCKETS_OFFLOAD=y +CONFIG_NET_NATIVE_OFFLOADED_SOCKETS=y +CONFIG_HEAP_MEM_POOL_SIZE=1024 + +CONFIG_NET_LOG=y + +CONFIG_MBEDTLS=y +CONFIG_PSA_WANT_ALG_SHA_1=y +CONFIG_PSA_WANT_ALG_SHA_256=y diff --git a/ports/zephyr-cp/boards/native/native_sim_lvgl_asan/board.overlay b/ports/zephyr-cp/boards/native/native_sim_lvgl_asan/board.overlay new file mode 100644 index 00000000000..78b57d64cef --- /dev/null +++ b/ports/zephyr-cp/boards/native/native_sim_lvgl_asan/board.overlay @@ -0,0 +1,7 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * Reuse the LVGL native simulator's hardware description for its ASan variant. + */ + +#include "../native_sim_lvgl/board.overlay" diff --git a/ports/zephyr-cp/boards/native/native_sim_lvgl_asan/circuitpython.toml b/ports/zephyr-cp/boards/native/native_sim_lvgl_asan/circuitpython.toml new file mode 100644 index 00000000000..913adb512b3 --- /dev/null +++ b/ports/zephyr-cp/boards/native/native_sim_lvgl_asan/circuitpython.toml @@ -0,0 +1,2 @@ +NAME = "Native simulator - LVGL + ASan" +CIRCUITPY_BUILD_EXTENSIONS = ["exe"] diff --git a/ports/zephyr-cp/boards/native/nrf5340bsim/autogen_board_info.toml b/ports/zephyr-cp/boards/native/nrf5340bsim/autogen_board_info.toml new file mode 100644 index 00000000000..1371119bfa1 --- /dev/null +++ b/ports/zephyr-cp/boards/native/nrf5340bsim/autogen_board_info.toml @@ -0,0 +1,145 @@ +# This file is autogenerated when a board is built. Do not edit. Do commit it to git. Other scripts use its info. +name = "zephyr nRF5340 simulated boards (BabbleSim)" + +[modules] +__future__ = true +_airlift = false +_bleio = true # Zephyr board has _bleio +_eve = false +_pew = false +_pixelmap = false +_stage = false +adafruit_bus_device = true +adafruit_pixelbuf = false +aesio = true +alarm = false +analogbufio = false +analogio = false +async_spi = false +atexit = true +audiobusio = false +audiocore = false +audiodelays = false +audiofilewriter = false +audiofilters = false +audiofreeverb = false +audioi2sin = false +audioio = false +audiomixer = false +audiomp3 = false +audiopwmio = false +audiospeed = false +audiotap = false +aurora_epaper = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio +bitops = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio +camera = false +canio = false +codeop = true +countio = false +cryptography = false +digitalio = true +displayio = true # Zephyr board has busio +dotclockframebuffer = false +dualbank = false +emmcio = false +epaperdisplay = true # Zephyr board has busio +floppyio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio +frequencyio = false +getpass = true +gifio = true # Zephyr board has busio +gnss = false +hardwarekey = false +hashlib = true +hmac = false +hostnetwork = false +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false +i2ctarget = false +imagecapture = false +ipaddress = false +is31fl3741 = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true +max3421e = false +mcp4822 = false +mdns = false +memorymap = false +memorymonitor = false +microcontroller = true +mii = false +mipicsi = false +mipidsi = false +msgpack = true +neopixel_write = false +nvm = false +onewireio = false +os = true +paralleldisplaybus = false +picogame = false +picogame3d = false +ps2io = false +pulseio = false +pwmio = false +qrio = false +qspibus = false +rainbowio = true +random = true +rclcpy = false +rgbmatrix = false +rotaryio = true # Zephyr board has rotaryio +rtc = false +sdcardio = true # Zephyr board has busio +sdioio = false +sharpdisplay = true # Zephyr board has busio +socketpool = false +spitarget = false +ssl = false +storage = true +struct = true +supervisor = true +synthio = false +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio +time = true +touchio = true +traceback = true +uheap = false +usb = false +usb_audio = false +usb_cdc = false +usb_hid = false +usb_host = false +usb_host_audio = false +usb_host_bulk = false +usb_midi = false +usb_video = false +ustack = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog +wifi = false +zephyr_display = false +zephyr_input = false +zephyr_kernel = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/native/nrf5340bsim/board.conf b/ports/zephyr-cp/boards/native/nrf5340bsim/board.conf new file mode 100644 index 00000000000..2579bf28d67 --- /dev/null +++ b/ports/zephyr-cp/boards/native/nrf5340bsim/board.conf @@ -0,0 +1,20 @@ +# Configuration for nrf5340bsim simulated board +# Mirror settings from native_sim.conf for compatibility + +CONFIG_GPIO=y + +# Enable Bluetooth stack - bsim is for BT simulation +CONFIG_BT_HCI=y +CONFIG_BT_HCI_VS=y + +# Override Kconfig default +CONFIG_BT_BUF_CMD_TX_COUNT=2 + +# Ensure the network core image starts when using native simulator +CONFIG_NATIVE_SIMULATOR_AUTOSTART_MCU=y + +CONFIG_TRACING=y +CONFIG_TRACING_PERFETTO=y +CONFIG_TRACING_SYNC=y +CONFIG_TRACING_BACKEND_POSIX=y +CONFIG_TRACING_GPIO=y diff --git a/ports/zephyr-cp/boards/native/nrf5340bsim/board.overlay b/ports/zephyr-cp/boards/native/nrf5340bsim/board.overlay new file mode 100644 index 00000000000..4a1693ce39f --- /dev/null +++ b/ports/zephyr-cp/boards/native/nrf5340bsim/board.overlay @@ -0,0 +1,17 @@ +/* SPDX-License-Identifier: Apache-2.0 */ + +/* Partition layout is owned by the mcuboot fork (dts/native/nrf5340bsim.dtsi) + * and applied to this image by sysbuild. This overlay only adds board/app config. */ + +/ { + chosen { + zephyr,sram = &sram0; + }; +}; + +&sram0 { + compatible = "zephyr,memory-region", "mmio-sram"; + zephyr,memory-region = "SRAM"; +}; + +/* Note: bsim doesn't have USB, so we don't include app.overlay */ diff --git a/ports/zephyr-cp/boards/native/nrf5340bsim/circuitpython.toml b/ports/zephyr-cp/boards/native/nrf5340bsim/circuitpython.toml new file mode 100644 index 00000000000..7177c825f17 --- /dev/null +++ b/ports/zephyr-cp/boards/native/nrf5340bsim/circuitpython.toml @@ -0,0 +1 @@ +CIRCUITPY_BUILD_EXTENSIONS = ["exe"] diff --git a/ports/zephyr-cp/boards/native/nrf54lm20bsim/autogen_board_info.toml b/ports/zephyr-cp/boards/native/nrf54lm20bsim/autogen_board_info.toml new file mode 100644 index 00000000000..371b690d1b3 --- /dev/null +++ b/ports/zephyr-cp/boards/native/nrf54lm20bsim/autogen_board_info.toml @@ -0,0 +1,145 @@ +# This file is autogenerated when a board is built. Do not edit. Do commit it to git. Other scripts use its info. +name = "zephyr nRF54LM20 simulated boards (BabbleSim)" + +[modules] +__future__ = true +_airlift = false +_bleio = true # Zephyr board has _bleio +_eve = false +_pew = false +_pixelmap = false +_stage = false +adafruit_bus_device = true +adafruit_pixelbuf = false +aesio = true +alarm = false +analogbufio = false +analogio = false +async_spi = false +atexit = true +audiobusio = false +audiocore = false +audiodelays = false +audiofilewriter = false +audiofilters = false +audiofreeverb = false +audioi2sin = false +audioio = false +audiomixer = false +audiomp3 = false +audiopwmio = false +audiospeed = false +audiotap = false +aurora_epaper = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio +bitops = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio +camera = false +canio = false +codeop = true +countio = false +cryptography = false +digitalio = true +displayio = true # Zephyr board has busio +dotclockframebuffer = false +dualbank = false +emmcio = false +epaperdisplay = true # Zephyr board has busio +floppyio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio +frequencyio = false +getpass = true +gifio = true # Zephyr board has busio +gnss = false +hardwarekey = false +hashlib = true +hmac = false +hostnetwork = false +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false +i2ctarget = false +imagecapture = false +ipaddress = false +is31fl3741 = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true +max3421e = false +mcp4822 = false +mdns = false +memorymap = false +memorymonitor = false +microcontroller = true +mii = false +mipicsi = false +mipidsi = false +msgpack = true +neopixel_write = false +nvm = false +onewireio = false +os = true +paralleldisplaybus = false +picogame = false +picogame3d = false +ps2io = false +pulseio = false +pwmio = false +qrio = false +qspibus = false +rainbowio = true +random = true +rclcpy = false +rgbmatrix = false +rotaryio = true # Zephyr board has rotaryio +rtc = false +sdcardio = true # Zephyr board has busio +sdioio = false +sharpdisplay = true # Zephyr board has busio +socketpool = false +spitarget = false +ssl = false +storage = true +struct = true +supervisor = true +synthio = false +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio +time = true +touchio = true +traceback = true +uheap = false +usb = false +usb_audio = false +usb_cdc = false +usb_hid = false +usb_host = false +usb_host_audio = false +usb_host_bulk = false +usb_midi = false +usb_video = false +ustack = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog +wifi = false +zephyr_display = false +zephyr_input = false +zephyr_kernel = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/native/nrf54lm20bsim/board.conf b/ports/zephyr-cp/boards/native/nrf54lm20bsim/board.conf new file mode 100644 index 00000000000..e2a9595c2a3 --- /dev/null +++ b/ports/zephyr-cp/boards/native/nrf54lm20bsim/board.conf @@ -0,0 +1,27 @@ +# Configuration for nrf54lm20bsim simulated board + +CONFIG_GPIO=y + +# Enable Bluetooth stack - bsim is for BT simulation +CONFIG_BT_HCI=y +CONFIG_BT_HCI_VS=y + +# Match nrf54lm20dk hardware: support dynamic TX power control +CONFIG_BT_CTLR_TX_PWR_DYNAMIC_CONTROL=y + +# Override Kconfig default +CONFIG_BT_BUF_CMD_TX_COUNT=2 + +# The bsim native_sim does not drive the BLE controller ticker time-slot +# mechanism used for radio-synchronized flash operations. With the default +# SOC_FLASH_NRF_RADIO_SYNC_TICKER, flash erase/write waits on a semaphore +# that is never given, hanging for ~34s (FLASH_TIMEOUT_MS) per operation. +# Disable radio sync so flash operations run directly, matching nrf5340bsim +# (which uses an IPC-based controller and so defaults to _NONE). +CONFIG_SOC_FLASH_NRF_RADIO_SYNC_NONE=y + +CONFIG_TRACING=y +CONFIG_TRACING_PERFETTO=y +CONFIG_TRACING_SYNC=y +CONFIG_TRACING_BACKEND_POSIX=y +CONFIG_TRACING_GPIO=y diff --git a/ports/zephyr-cp/boards/native/nrf54lm20bsim/board.overlay b/ports/zephyr-cp/boards/native/nrf54lm20bsim/board.overlay new file mode 100644 index 00000000000..c627a95c76e --- /dev/null +++ b/ports/zephyr-cp/boards/native/nrf54lm20bsim/board.overlay @@ -0,0 +1,19 @@ +/* SPDX-License-Identifier: Apache-2.0 */ + +/* Partition layout is owned by the mcuboot fork (dts/native/nrf54lm20bsim.dtsi) + * and applied to this image by sysbuild. This overlay only adds board/app config. */ + +/ { + sram0: memory@20000000 { + device_type = "memory"; + compatible = "zephyr,memory-region", "mmio-sram"; + reg = <0x20000000 DT_SIZE_K(511)>; + zephyr,memory-region = "SRAM"; + }; + + chosen { + zephyr,sram = &sram0; + }; +}; + +/* Note: bsim doesn't have USB, so we don't include app.overlay */ diff --git a/ports/zephyr-cp/boards/native/nrf54lm20bsim/circuitpython.toml b/ports/zephyr-cp/boards/native/nrf54lm20bsim/circuitpython.toml new file mode 100644 index 00000000000..7177c825f17 --- /dev/null +++ b/ports/zephyr-cp/boards/native/nrf54lm20bsim/circuitpython.toml @@ -0,0 +1 @@ +CIRCUITPY_BUILD_EXTENSIONS = ["exe"] diff --git a/ports/zephyr-cp/boards/nordic/nrf5340dk/autogen_board_info.toml b/ports/zephyr-cp/boards/nordic/nrf5340dk/autogen_board_info.toml index ba0291f6430..b2cb8aebf50 100644 --- a/ports/zephyr-cp/boards/nordic/nrf5340dk/autogen_board_info.toml +++ b/ports/zephyr-cp/boards/nordic/nrf5340dk/autogen_board_info.toml @@ -2,110 +2,144 @@ name = "Nordic Semiconductor nRF5340 DK" [modules] -__future__ = false -_bleio = false +__future__ = true +_airlift = false +_bleio = true # Zephyr board has _bleio _eve = false _pew = false -_pixelmap = false +_pixelmap = true # Zephyr board has neopixel_write _stage = false -adafruit_bus_device = false -adafruit_pixelbuf = false -aesio = false +adafruit_bus_device = true +adafruit_pixelbuf = true # Zephyr board has neopixel_write +aesio = true alarm = false analogbufio = false analogio = false -atexit = false +async_spi = true # Zephyr board has async_spi +atexit = true audiobusio = false audiocore = false audiodelays = false +audiofilewriter = false audiofilters = false +audiofreeverb = false +audioi2sin = false audioio = false audiomixer = false audiomp3 = false audiopwmio = false +audiospeed = false +audiotap = false aurora_epaper = false -bitbangio = false -bitmapfilter = false -bitmaptools = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio bitops = false -board = false -busdisplay = false -busio = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio camera = false canio = false -codeop = false +codeop = true countio = false +cryptography = false digitalio = true -displayio = false +displayio = true # Zephyr board has busio dotclockframebuffer = false dualbank = false -epaperdisplay = false +emmcio = false +epaperdisplay = true # Zephyr board has busio floppyio = false -fontio = false -fourwire = false -framebufferio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio frequencyio = false -getpass = false -gifio = false +getpass = true +gifio = true # Zephyr board has busio gnss = false -hashlib = false -i2cdisplaybus = false +hardwarekey = false +hashlib = true +hmac = false +hostnetwork = false +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false i2ctarget = false imagecapture = false ipaddress = false is31fl3741 = false -jpegio = false -keypad = false -keypad_demux = false -locale = false -math = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true max3421e = false +mcp4822 = false mdns = false memorymap = false memorymonitor = false microcontroller = true -msgpack = false -neopixel_write = false -nvm = false +mii = false +mipicsi = false +mipidsi = false +msgpack = true +neopixel_write = true # Zephyr board has neopixel_write +nvm = true # Board has NVM partition onewireio = false os = true paralleldisplaybus = false +picogame = false +picogame3d = false ps2io = false pulseio = false -pwmio = false +pwmio = true # Zephyr board has pwmio qrio = false -rainbowio = false +qspibus = false +rainbowio = true random = true +rclcpy = false rgbmatrix = false -rotaryio = false +rotaryio = true # Zephyr board has rotaryio rtc = false -sdcardio = false +sdcardio = true # Zephyr board has busio sdioio = false -sharpdisplay = false +sharpdisplay = true # Zephyr board has busio socketpool = false spitarget = false ssl = false storage = true # Zephyr board has flash struct = true -supervisor = false +supervisor = true synthio = false -terminalio = false -tilepalettemapper = false +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio time = true -touchio = false -traceback = false +touchio = true +traceback = true uheap = false usb = false +usb_audio = false usb_cdc = true -usb_hid = false +usb_hid = true usb_host = false +usb_host_audio = false +usb_host_bulk = false usb_midi = false usb_video = false ustack = false -vectorio = false -warnings = false -watchdog = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog wifi = false +zephyr_display = false +zephyr_input = true # Zephyr board has zephyr_input zephyr_kernel = false -zephyr_serial = true -zlib = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/nordic/nrf5340dk/board.conf b/ports/zephyr-cp/boards/nordic/nrf5340dk/board.conf new file mode 100644 index 00000000000..9c1dde55f95 --- /dev/null +++ b/ports/zephyr-cp/boards/nordic/nrf5340dk/board.conf @@ -0,0 +1,3 @@ +# PWM instances 1-3 are enabled in board.overlay with disconnected outputs so +# iobroker can allocate them at runtime for neopixel_write and pwmio. +CONFIG_PWM=y diff --git a/ports/zephyr-cp/boards/nordic/nrf5340dk/board.overlay b/ports/zephyr-cp/boards/nordic/nrf5340dk/board.overlay new file mode 100644 index 00000000000..775763d7523 --- /dev/null +++ b/ports/zephyr-cp/boards/nordic/nrf5340dk/board.overlay @@ -0,0 +1,209 @@ +// TODO: restore the I2S for the Open Music Labs Audio Codec Shield. The fixed +// i2s0 that was here used the Arduino SPI pins (D10-D13), so board.SPI() could +// not use them, and audiobusio.I2SOut can't be routed dynamically yet. + +// Enable free serial peripheral instances so CircuitPython can mux them to +// arbitrary pins at runtime. Each instance is enabled in one mode because the +// i2c/spi/uart nodes of an instance are the same peripheral (enforced by +// zephyr/soc/nordic/validate_enabled_instances.c). All signals are +// disconnected and the devices are marked zephyr,deferred-init so nothing is +// claimed at boot; iobroker initializes and routes a device when a busio +// object is constructed and de-initializes it on release. +// +// See "nRF serial instances" in internal-modules/iobroker/README.md for how +// the instances are shared and allocated. +// +// Instance 0 is left alone: uart0 is the console and i2c0/spi0 share that +// same peripheral, so they must not be enabled. Instance 1 is i2c1, the +// Arduino header I2C. spi4 is the upstream Arduino header SPI and the only +// SPI instance. uart1 is the upstream Arduino serial, but it is the same +// instance as i2c1, so busio.UART uses uart3. + +&pinctrl { + i2c1_dyn_default: i2c1_dyn_default { + group1 { + psels = , + ; + }; + }; + + i2c1_dyn_sleep: i2c1_dyn_sleep { + group1 { + psels = , + ; + }; + }; + + spi4_dyn_default: spi4_dyn_default { + group1 { + psels = , + , + ; + }; + }; + + spi4_dyn_sleep: spi4_dyn_sleep { + group1 { + psels = , + , + ; + }; + }; + + i2c2_dyn_default: i2c2_dyn_default { + group1 { + psels = , + ; + }; + }; + + i2c2_dyn_sleep: i2c2_dyn_sleep { + group1 { + psels = , + ; + }; + }; + + uart3_dyn_default: uart3_dyn_default { + group1 { + psels = , + ; + }; + }; + + uart3_dyn_sleep: uart3_dyn_sleep { + group1 { + psels = , + ; + }; + }; +}; + +&i2c1 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&i2c1_dyn_default>; + pinctrl-1 = <&i2c1_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&i2c2 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&i2c2_dyn_default>; + pinctrl-1 = <&i2c2_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&spi4 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&spi4_dyn_default>; + pinctrl-1 = <&spi4_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&uart3 { + status = "okay"; + zephyr,deferred-init; + current-speed = <115200>; + pinctrl-0 = <&uart3_dyn_default>; + pinctrl-1 = <&uart3_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +// The upstream board forwards the Arduino D0/D1 pins (P1.00/P1.01) and +// P0.10/P0.11 to the network core for its UART console, so the application +// core could not use them. Keep them on the application core, for +// board.UART() on TX/RX (D1/D0). +&gpio_fwd { + status = "disabled"; +}; + +// PWM instances 1-3, same scheme: all four outputs disconnected and deferred +// init, so iobroker can hand an instance to neopixel_write and pwmio and +// route its outputs at runtime. Instance 0 is left as the board defines it: +// enabled with fixed pins for the PWM LED. nRF5340 has no power-domain pin +// restrictions, so any instance can drive any pad. + +&pinctrl { + pwm1_dyn_default: pwm1_dyn_default { + group1 { + psels = , + , + , + ; + }; + }; + + pwm1_dyn_sleep: pwm1_dyn_sleep { + group1 { + psels = , + , + , + ; + }; + }; + + pwm2_dyn_default: pwm2_dyn_default { + group1 { + psels = , + , + , + ; + }; + }; + + pwm2_dyn_sleep: pwm2_dyn_sleep { + group1 { + psels = , + , + , + ; + }; + }; + + pwm3_dyn_default: pwm3_dyn_default { + group1 { + psels = , + , + , + ; + }; + }; + + pwm3_dyn_sleep: pwm3_dyn_sleep { + group1 { + psels = , + , + , + ; + }; + }; +}; + +&pwm1 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&pwm1_dyn_default>; + pinctrl-1 = <&pwm1_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&pwm2 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&pwm2_dyn_default>; + pinctrl-1 = <&pwm2_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&pwm3 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&pwm3_dyn_default>; + pinctrl-1 = <&pwm3_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +#include "../../../app.overlay" diff --git a/ports/zephyr-cp/boards/nordic/nrf5340dk/circuitpython.toml b/ports/zephyr-cp/boards/nordic/nrf5340dk/circuitpython.toml index bf17d26d91b..f0a4cd45cfd 100644 --- a/ports/zephyr-cp/boards/nordic/nrf5340dk/circuitpython.toml +++ b/ports/zephyr-cp/boards/nordic/nrf5340dk/circuitpython.toml @@ -1,3 +1,3 @@ -CIRCUITPY_BUILD_EXTENSIONS = ["elf"] +CIRCUITPY_BUILD_EXTENSIONS = ["hex", "uf2", "signed.bin"] USB_VID=0x239A USB_PID=0x8166 diff --git a/ports/zephyr-cp/boards/nordic/nrf54h20dk/autogen_board_info.toml b/ports/zephyr-cp/boards/nordic/nrf54h20dk/autogen_board_info.toml new file mode 100644 index 00000000000..acbdbd52003 --- /dev/null +++ b/ports/zephyr-cp/boards/nordic/nrf54h20dk/autogen_board_info.toml @@ -0,0 +1,145 @@ +# This file is autogenerated when a board is built. Do not edit. Do commit it to git. Other scripts use its info. +name = "Nordic Semiconductor nRF54H20 DK" + +[modules] +__future__ = true +_airlift = false +_bleio = false +_eve = false +_pew = false +_pixelmap = false +_stage = false +adafruit_bus_device = true +adafruit_pixelbuf = false +aesio = true +alarm = false +analogbufio = false +analogio = false +async_spi = true # Zephyr board has async_spi +atexit = true +audiobusio = false +audiocore = false +audiodelays = false +audiofilewriter = false +audiofilters = false +audiofreeverb = false +audioi2sin = false +audioio = false +audiomixer = false +audiomp3 = false +audiopwmio = false +audiospeed = false +audiotap = false +aurora_epaper = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio +bitops = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio +camera = false +canio = false +codeop = true +countio = false +cryptography = false +digitalio = true +displayio = true # Zephyr board has busio +dotclockframebuffer = false +dualbank = false +emmcio = false +epaperdisplay = true # Zephyr board has busio +floppyio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio +frequencyio = false +getpass = true +gifio = false # Zephyr board has busio +gnss = false +hardwarekey = false +hashlib = true +hmac = false +hostnetwork = false +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false +i2ctarget = false +imagecapture = false +ipaddress = false +is31fl3741 = false +jpegio = false # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true +max3421e = false +mcp4822 = false +mdns = false +memorymap = false +memorymonitor = false +microcontroller = true +mii = false +mipicsi = false +mipidsi = false +msgpack = true +neopixel_write = false +nvm = false +onewireio = false +os = true +paralleldisplaybus = false +picogame = false +picogame3d = false +ps2io = false +pulseio = false +pwmio = false +qrio = false +qspibus = false +rainbowio = true +random = true +rclcpy = false +rgbmatrix = false +rotaryio = true # Zephyr board has rotaryio +rtc = false +sdcardio = true # Zephyr board has busio +sdioio = false +sharpdisplay = true # Zephyr board has busio +socketpool = false +spitarget = false +ssl = false +storage = true # Zephyr board has flash +struct = true +supervisor = true +synthio = false +terminalio = true # Zephyr board has busio +tilepalettemapper = false # Zephyr board has busio +time = true +touchio = true +traceback = true +uheap = false +usb = false +usb_audio = false +usb_cdc = true +usb_hid = true +usb_host = false +usb_host_audio = false +usb_host_bulk = false +usb_midi = false +usb_video = false +ustack = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog +wifi = false +zephyr_display = false +zephyr_input = true # Zephyr board has zephyr_input +zephyr_kernel = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/nordic/nrf54h20dk/board.conf b/ports/zephyr-cp/boards/nordic/nrf54h20dk/board.conf new file mode 100644 index 00000000000..3aca8d77007 --- /dev/null +++ b/ports/zephyr-cp/boards/nordic/nrf54h20dk/board.conf @@ -0,0 +1,11 @@ +CONFIG_FLASH_MSPI_NOR_LAYOUT_PAGE_SIZE=4096 + +# BLE overflows flash on this board. +CONFIG_BT=n + +# Reduce flash usage for this board. +CONFIG_LOG=y +CONFIG_LOG_MAX_LEVEL=2 +CONFIG_ASSERT=n +CONFIG_FRAME_POINTER=n +CONFIG_HW_STACK_PROTECTION=n diff --git a/ports/zephyr-cp/boards/nordic/nrf54h20dk/board.overlay b/ports/zephyr-cp/boards/nordic/nrf54h20dk/board.overlay new file mode 100644 index 00000000000..6a2395bfc7b --- /dev/null +++ b/ports/zephyr-cp/boards/nordic/nrf54h20dk/board.overlay @@ -0,0 +1,140 @@ +// board.I2C() is on SCL/SDA (P2.10/P2.11), the pins that circuitpython.toml +// names SCL and SDA. + +// Enable P2's GPIO controller so its pads get pin objects. The SoC dtsi +// leaves every port disabled and the board enables only the LED and button +// ports. +&gpio2 { + status = "okay"; +}; + +/* The flash layout comes from the mcuboot fork's generated + * nrf54h20dk-partitions.dtsi: slot0 is expanded to 1.3 MB, the OTA slot1 + * lives on external flash and the cpurad slots are absorbed, so no + * partition fix-ups are needed here. + */ + +// Enable free serial peripheral instances so CircuitPython can mux them to +// arbitrary pins at runtime. On this SoC the i2c/spi/uart nodes with the same +// instance number are the same peripheral block (e.g. i2c130/spi130/uart130 +// all sit at 0x9a5000), so each instance is enabled in exactly one mode. All +// signals are disconnected and the devices are marked zephyr,deferred-init so +// nothing is claimed at boot; iobroker initializes and routes a device when a +// busio object is constructed and de-initializes it on release. +// +// See "nRF serial instances" in internal-modules/iobroker/README.md for how +// the instances are shared and allocated. +// +// Instance 130 is i2c130, which the upstream board fixes to P2.10/P2.11. +// Instances 120, +// 135 and 136 are left alone: uart120 and uart135 are the console UARTs of +// the (not built here) FLPR and PPR cores, and uart136 is the app console. +// The DMA region is required on this SoC: the serial drivers only access +// memory the peripheral's EasyDMA is allowed to reach. + +&pinctrl { + i2c130_dyn_default: i2c130_dyn_default { + group1 { + psels = , + ; + }; + }; + + i2c130_dyn_sleep: i2c130_dyn_sleep { + group1 { + psels = , + ; + }; + }; + + i2c131_dyn_default: i2c131_dyn_default { + group1 { + psels = , + ; + }; + }; + + i2c131_dyn_sleep: i2c131_dyn_sleep { + group1 { + psels = , + ; + }; + }; + + spi132_dyn_default: spi132_dyn_default { + group1 { + psels = , + , + ; + }; + }; + + spi132_dyn_sleep: spi132_dyn_sleep { + group1 { + psels = , + , + ; + }; + }; + + uart137_dyn_default: uart137_dyn_default { + group1 { + psels = , + ; + }; + }; + + uart137_dyn_sleep: uart137_dyn_sleep { + group1 { + psels = , + ; + }; + }; +}; + +&i2c130 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&i2c130_dyn_default>; + pinctrl-1 = <&i2c130_dyn_sleep>; + pinctrl-names = "default", "sleep"; + zephyr,concat-buf-size = <256>; + memory-regions = <&cpuapp_dma_region>; +}; + +&i2c131 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&i2c131_dyn_default>; + pinctrl-1 = <&i2c131_dyn_sleep>; + pinctrl-names = "default", "sleep"; + zephyr,concat-buf-size = <256>; + memory-regions = <&cpuapp_dma_region>; +}; + +&spi132 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&spi132_dyn_default>; + pinctrl-1 = <&spi132_dyn_sleep>; + pinctrl-names = "default", "sleep"; + memory-regions = <&cpuapp_dma_region>; +}; + +&uart137 { + status = "okay"; + zephyr,deferred-init; + current-speed = <115200>; + pinctrl-0 = <&uart137_dyn_default>; + pinctrl-1 = <&uart137_dyn_sleep>; + pinctrl-names = "default", "sleep"; + memory-regions = <&cpuapp_dma_region>; +}; + +// Enable the hardware watchdog for the watchdog module. The Zephyr board dts +// aliases watchdog0 to wdt010, but the SoC dtsi leaves it disabled. +&wdt010 { + status = "okay"; +}; + +#include "../../../app.overlay" diff --git a/ports/zephyr-cp/boards/nordic/nrf54h20dk/circuitpython.toml b/ports/zephyr-cp/boards/nordic/nrf54h20dk/circuitpython.toml new file mode 100644 index 00000000000..7b8d0483c9c --- /dev/null +++ b/ports/zephyr-cp/boards/nordic/nrf54h20dk/circuitpython.toml @@ -0,0 +1,9 @@ +CIRCUITPY_BUILD_EXTENSIONS = ["hex", "uf2"] +DISABLED_MODULES=["jpegio", "gifio", "tilepalettemapper"] + +# No package map for this SoC yet, so pins are global GPIO numbers +# (port * 32 + pin). +[pins] +# board.I2C() pins: P2.10/P2.11. +SCL = 74 +SDA = 75 diff --git a/ports/zephyr-cp/boards/nordic/nrf54l15dk/autogen_board_info.toml b/ports/zephyr-cp/boards/nordic/nrf54l15dk/autogen_board_info.toml index 88178af3b28..b751ab10fd0 100644 --- a/ports/zephyr-cp/boards/nordic/nrf54l15dk/autogen_board_info.toml +++ b/ports/zephyr-cp/boards/nordic/nrf54l15dk/autogen_board_info.toml @@ -2,110 +2,144 @@ name = "Nordic Semiconductor nRF54L15 DK" [modules] -__future__ = false -_bleio = false +__future__ = true +_airlift = false +_bleio = true # Zephyr board has _bleio _eve = false _pew = false -_pixelmap = false +_pixelmap = true # Zephyr board has neopixel_write _stage = false -adafruit_bus_device = false -adafruit_pixelbuf = false -aesio = false +adafruit_bus_device = true +adafruit_pixelbuf = true # Zephyr board has neopixel_write +aesio = true alarm = false analogbufio = false analogio = false -atexit = false +async_spi = true # Zephyr board has async_spi +atexit = true audiobusio = false audiocore = false audiodelays = false +audiofilewriter = false audiofilters = false +audiofreeverb = false +audioi2sin = false audioio = false audiomixer = false audiomp3 = false audiopwmio = false +audiospeed = false +audiotap = false aurora_epaper = false -bitbangio = false -bitmapfilter = false -bitmaptools = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio bitops = false -board = false -busdisplay = false -busio = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio camera = false canio = false -codeop = false +codeop = true countio = false +cryptography = false digitalio = true -displayio = false +displayio = true # Zephyr board has busio dotclockframebuffer = false dualbank = false -epaperdisplay = false +emmcio = false +epaperdisplay = true # Zephyr board has busio floppyio = false -fontio = false -fourwire = false -framebufferio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio frequencyio = false -getpass = false -gifio = false +getpass = true +gifio = true # Zephyr board has busio gnss = false -hashlib = false -i2cdisplaybus = false +hardwarekey = false +hashlib = true +hmac = false +hostnetwork = false +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false i2ctarget = false imagecapture = false ipaddress = false is31fl3741 = false -jpegio = false -keypad = false -keypad_demux = false -locale = false -math = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true max3421e = false +mcp4822 = false mdns = false memorymap = false memorymonitor = false microcontroller = true -msgpack = false -neopixel_write = false -nvm = false +mii = false +mipicsi = false +mipidsi = false +msgpack = true +neopixel_write = true # Zephyr board has neopixel_write +nvm = true # Board has NVM partition onewireio = false os = true paralleldisplaybus = false +picogame = false +picogame3d = false ps2io = false pulseio = false -pwmio = false +pwmio = true # Zephyr board has pwmio qrio = false -rainbowio = false +qspibus = false +rainbowio = true random = true +rclcpy = false rgbmatrix = false -rotaryio = false +rotaryio = true # Zephyr board has rotaryio rtc = false -sdcardio = false +sdcardio = true # Zephyr board has busio sdioio = false -sharpdisplay = false +sharpdisplay = true # Zephyr board has busio socketpool = false spitarget = false ssl = false storage = true # Zephyr board has flash struct = true -supervisor = false +supervisor = true synthio = false -terminalio = false -tilepalettemapper = false +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio time = true -touchio = false -traceback = false +touchio = true +traceback = true uheap = false usb = false +usb_audio = false usb_cdc = false usb_hid = false usb_host = false +usb_host_audio = false +usb_host_bulk = false usb_midi = false usb_video = false ustack = false -vectorio = false -warnings = false -watchdog = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog wifi = false +zephyr_display = false +zephyr_input = true # Zephyr board has zephyr_input zephyr_kernel = false -zephyr_serial = true -zlib = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/nordic/nrf54l15dk/board.conf b/ports/zephyr-cp/boards/nordic/nrf54l15dk/board.conf new file mode 100644 index 00000000000..d522bda460e --- /dev/null +++ b/ports/zephyr-cp/boards/nordic/nrf54l15dk/board.conf @@ -0,0 +1,19 @@ +# Enable the controller's Zephyr VS HCI set/get TX power commands, which +# _bleio's start_advertising(tx_power=...) uses. Without this the controller +# rejects the commands and tx power is fixed at the BT_CTLR_TX_PWR default (0 dBm). +# The nRF54L15 radio supports -46 to +8 dBm. +CONFIG_BT_CTLR_TX_PWR_DYNAMIC_CONTROL=y + +# Work around a latent bug in soc_flash_nrf_ticker.c: with the default +# NRF_RRAM_WRITE_BUFFER_SIZE=1, FLASH_SLOT_WRITE (500 us) < +# FLASH_SYNC_SWITCHING_TIME (1700 us), so `interval = duration - +# FLASH_SYNC_SWITCHING_TIME` underflows and the next flash slot is scheduled +# ~71 minutes out. Any write larger than a single 16-byte slot then times out +# (-ETIMEDOUT / -116), e.g. persisting bond keys right after pairing. +# See zephyr/tests/boards/nrf/rram/overlay-radio_sync.conf. +CONFIG_NRF_RRAM_WRITE_BUFFER_SIZE=32 + +# PWM instances 21 and 22 are enabled in board.overlay with disconnected +# outputs so iobroker can allocate them at runtime for neopixel_write and +# pwmio. +CONFIG_PWM=y diff --git a/ports/zephyr-cp/boards/nordic/nrf54l15dk/board.overlay b/ports/zephyr-cp/boards/nordic/nrf54l15dk/board.overlay new file mode 100644 index 00000000000..03d399f05b3 --- /dev/null +++ b/ports/zephyr-cp/boards/nordic/nrf54l15dk/board.overlay @@ -0,0 +1,157 @@ +// nRF54L15 DK doesn't have USB, so no app.overlay for CDC ACM. + +// Enable every free serial peripheral instance so CircuitPython can mux it to +// arbitrary pins at runtime. Each instance is enabled in one mode because the +// i2c/spi/uart nodes of an instance are the same peripheral (enforced by +// zephyr/soc/nordic/validate_enabled_instances.c). All signals are +// disconnected and the devices are marked zephyr,deferred-init so nothing is +// claimed at boot; iobroker initializes and routes a device when a busio +// object is constructed and de-initializes it on release. +// +// See "nRF serial instances" in internal-modules/iobroker/README.md for how +// the instances are shared and allocated. +// +// Instance 20 is left alone: uart20 is the console (main UART) and i2c20/spi20 +// share that same peripheral, so they must not be enabled. Instance 00 is +// owned by spi00 and the MX25R64 SPI flash (no TWI00 on this SoC). + +&pinctrl { + i2c21_dyn_default: i2c21_dyn_default { + group1 { + psels = , + ; + }; + }; + + i2c21_dyn_sleep: i2c21_dyn_sleep { + group1 { + psels = , + ; + }; + }; + + spi22_dyn_default: spi22_dyn_default { + group1 { + psels = , + , + ; + }; + }; + + spi22_dyn_sleep: spi22_dyn_sleep { + group1 { + psels = , + , + ; + }; + }; + + uart30_dyn_default: uart30_dyn_default { + group1 { + psels = , + ; + }; + }; + + uart30_dyn_sleep: uart30_dyn_sleep { + group1 { + psels = , + ; + }; + }; + + pwm21_dyn_default: pwm21_dyn_default { + group1 { + psels = , + , + , + ; + }; + }; + + pwm21_dyn_sleep: pwm21_dyn_sleep { + group1 { + psels = , + , + , + ; + }; + }; + + pwm22_dyn_default: pwm22_dyn_default { + group1 { + psels = , + , + , + ; + }; + }; + + pwm22_dyn_sleep: pwm22_dyn_sleep { + group1 { + psels = , + , + , + ; + }; + }; +}; + +&i2c21 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&i2c21_dyn_default>; + pinctrl-1 = <&i2c21_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&spi22 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&spi22_dyn_default>; + pinctrl-1 = <&spi22_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&uart30 { + status = "okay"; + zephyr,deferred-init; + current-speed = <115200>; + pinctrl-0 = <&uart30_dyn_default>; + pinctrl-1 = <&uart30_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +// PWM instances 21 and 22, same scheme: all four outputs disconnected and +// deferred init, so iobroker can hand an instance to neopixel_write and +// pwmio and route its outputs at runtime. Instance 20 is left as the board +// defines it: enabled with fixed pins for the PWM LED. On this SoC the "2x" +// instances can only drive P1 pads (see the iobroker README). + +&pwm21 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&pwm21_dyn_default>; + pinctrl-1 = <&pwm21_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&pwm22 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&pwm22_dyn_default>; + pinctrl-1 = <&pwm22_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +/ { + chosen { + zephyr,code-partition = &slot0_partition; + }; +}; + +// Enable the hardware watchdog for the watchdog module. The Zephyr board dts +// aliases watchdog0 to wdt31, but the SoC dtsi leaves it disabled. +&wdt31 { + status = "okay"; +}; diff --git a/ports/zephyr-cp/boards/nordic/nrf54l15dk/circuitpython.toml b/ports/zephyr-cp/boards/nordic/nrf54l15dk/circuitpython.toml index 3272dd4c5f3..5ea381dcd6f 100644 --- a/ports/zephyr-cp/boards/nordic/nrf54l15dk/circuitpython.toml +++ b/ports/zephyr-cp/boards/nordic/nrf54l15dk/circuitpython.toml @@ -1 +1,7 @@ -CIRCUITPY_BUILD_EXTENSIONS = ["elf"] +CIRCUITPY_BUILD_EXTENSIONS = ["hex", "signed.bin"] + +# QFN48 package pin numbers. +[pins] +# board.UART() pins: P0.00/P0.01, the debugger's VCOM0 serial port. +TX = 23 +RX = 24 diff --git a/ports/zephyr-cp/boards/nordic/nrf54l15tag/autogen_board_info.toml b/ports/zephyr-cp/boards/nordic/nrf54l15tag/autogen_board_info.toml new file mode 100644 index 00000000000..4469ea39bae --- /dev/null +++ b/ports/zephyr-cp/boards/nordic/nrf54l15tag/autogen_board_info.toml @@ -0,0 +1,145 @@ +# This file is autogenerated when a board is built. Do not edit. Do commit it to git. Other scripts use its info. +name = "Nordic Semiconductor nRF54L15 TAG" + +[modules] +__future__ = true +_airlift = false +_bleio = true # Zephyr board has _bleio +_eve = false +_pew = false +_pixelmap = false +_stage = false +adafruit_bus_device = true +adafruit_pixelbuf = false +aesio = true +alarm = false +analogbufio = false +analogio = false +async_spi = true # Zephyr board has async_spi +atexit = true +audiobusio = false +audiocore = false +audiodelays = false +audiofilewriter = false +audiofilters = false +audiofreeverb = false +audioi2sin = false +audioio = false +audiomixer = false +audiomp3 = false +audiopwmio = false +audiospeed = false +audiotap = false +aurora_epaper = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio +bitops = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio +camera = false +canio = false +codeop = true +countio = false +cryptography = false +digitalio = true +displayio = true # Zephyr board has busio +dotclockframebuffer = false +dualbank = false +emmcio = false +epaperdisplay = true # Zephyr board has busio +floppyio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio +frequencyio = false +getpass = true +gifio = true # Zephyr board has busio +gnss = false +hardwarekey = false +hashlib = true +hmac = false +hostnetwork = false +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false +i2ctarget = false +imagecapture = false +ipaddress = false +is31fl3741 = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = false +locale = true +lvfontio = true # Zephyr board has busio +math = true +max3421e = false +mcp4822 = false +mdns = false +memorymap = false +memorymonitor = false +microcontroller = true +mii = false +mipicsi = false +mipidsi = false +msgpack = false +neopixel_write = false +nvm = false +onewireio = false +os = true +paralleldisplaybus = false +picogame = false +picogame3d = false +ps2io = false +pulseio = false +pwmio = false +qrio = false +qspibus = false +rainbowio = true +random = true +rclcpy = false +rgbmatrix = false +rotaryio = true # Zephyr board has rotaryio +rtc = false +sdcardio = true # Zephyr board has busio +sdioio = false +sharpdisplay = true # Zephyr board has busio +socketpool = false +spitarget = false +ssl = false +storage = true +struct = true +supervisor = true +synthio = false +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio +time = true +touchio = true +traceback = true +uheap = false +usb = false +usb_audio = false +usb_cdc = false +usb_hid = false +usb_host = false +usb_host_audio = false +usb_host_bulk = false +usb_midi = false +usb_video = false +ustack = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog +wifi = false +zephyr_display = false +zephyr_input = false +zephyr_kernel = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/nordic/nrf54l15tag/board.conf b/ports/zephyr-cp/boards/nordic/nrf54l15tag/board.conf new file mode 100644 index 00000000000..dc4084719cc --- /dev/null +++ b/ports/zephyr-cp/boards/nordic/nrf54l15tag/board.conf @@ -0,0 +1,19 @@ +# Enable UART console (not enabled in the Zephyr board defconfig) +CONFIG_SERIAL=y +CONFIG_CONSOLE=y +CONFIG_UART_CONSOLE=y + +# Enable the controller's Zephyr VS HCI set/get TX power commands, which +# _bleio's start_advertising(tx_power=...) uses. Without this the controller +# rejects the commands and tx power is fixed at the BT_CTLR_TX_PWR default (0 dBm). +# The nRF54L15 radio supports -46 to +8 dBm. +CONFIG_BT_CTLR_TX_PWR_DYNAMIC_CONTROL=y + +# Work around a latent bug in soc_flash_nrf_ticker.c: with the default +# NRF_RRAM_WRITE_BUFFER_SIZE=1, FLASH_SLOT_WRITE (500 us) < +# FLASH_SYNC_SWITCHING_TIME (1700 us), so `interval = duration - +# FLASH_SYNC_SWITCHING_TIME` underflows and the next flash slot is scheduled +# ~71 minutes out. Any write larger than a single 16-byte slot then times out +# (-ETIMEDOUT / -116), e.g. persisting bond keys right after pairing. +# See zephyr/tests/boards/nrf/rram/overlay-radio_sync.conf. +CONFIG_NRF_RRAM_WRITE_BUFFER_SIZE=32 diff --git a/ports/zephyr-cp/boards/nordic/nrf54l15tag/board.overlay b/ports/zephyr-cp/boards/nordic/nrf54l15tag/board.overlay new file mode 100644 index 00000000000..582aec3fc0f --- /dev/null +++ b/ports/zephyr-cp/boards/nordic/nrf54l15tag/board.overlay @@ -0,0 +1,159 @@ +// No app.overlay because it doesn't have USB. + +// Keep the button nodes and their GPIOs available for board pin-name +// generation, but don't instantiate the GPIO-keys input driver. The +// zephyr_input module currently exposes touch input only, and the input +// subsystem otherwise consumes most of this board's remaining flash. +&{/buttons} { + status = "disabled"; +}; + +// The nrf54l15tag Zephyr board doesn't enable a UART or set zephyr,console, +// unlike the nrf54l15dk. Set up UART30 as the console using available pins. +&uart30 { + status = "okay"; + current-speed = <115200>; + pinctrl-0 = <&uart30_default>; + pinctrl-1 = <&uart30_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&pinctrl { + uart30_default: uart30_default { + group1 { + psels = ; + }; + group2 { + psels = ; + bias-pull-up; + }; + }; + + uart30_sleep: uart30_sleep { + group1 { + psels = , + ; + low-power-enable; + }; + }; +}; + +/ { + chosen { + zephyr,console = &uart30; + zephyr,shell-uart = &uart30; + zephyr,uart-mcumgr = &uart30; + }; +}; + +// Enable free serial peripheral instances so CircuitPython can mux them to +// arbitrary pins at runtime. Each instance is enabled in one mode because the +// i2c/spi/uart nodes of an instance are the same peripheral (enforced by +// zephyr/soc/nordic/validate_enabled_instances.c). All signals are +// disconnected and the devices are marked zephyr,deferred-init so nothing is +// claimed at boot; iobroker initializes and routes a device when a busio +// object is constructed and de-initializes it on release. +// +// See "nRF serial instances" in internal-modules/iobroker/README.md for how +// the instances are shared and allocated. +// +// Instance 21 is i2c21, the bus the bme688 and adxl367 hang off, and instance +// 22 is spi22, the bmi270's bus (its CS is P1.07). Their Zephyr sensor nodes +// are disabled, so both are routed like the others. Instance 30 is left alone: +// uart30 is the console above and i2c30/spi30 share that same peripheral, so +// they must not be enabled. There is no i2c00 on this SoC, so instance 00 can +// only carry spi00 (or uart00). + +&pinctrl { + i2c21_dyn_default: i2c21_dyn_default { + group1 { + psels = , + ; + }; + }; + + i2c21_dyn_sleep: i2c21_dyn_sleep { + group1 { + psels = , + ; + }; + }; + + spi22_dyn_default: spi22_dyn_default { + group1 { + psels = , + , + ; + }; + }; + + spi22_dyn_sleep: spi22_dyn_sleep { + group1 { + psels = , + , + ; + }; + }; + + i2c20_dyn_default: i2c20_dyn_default { + group1 { + psels = , + ; + }; + }; + + i2c20_dyn_sleep: i2c20_dyn_sleep { + group1 { + psels = , + ; + }; + }; + + spi00_dyn_default: spi00_dyn_default { + group1 { + psels = , + , + ; + }; + }; + + spi00_dyn_sleep: spi00_dyn_sleep { + group1 { + psels = , + , + ; + }; + }; +}; + +&i2c21 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&i2c21_dyn_default>; + pinctrl-1 = <&i2c21_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&spi22 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&spi22_dyn_default>; + pinctrl-1 = <&spi22_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&i2c20 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&i2c20_dyn_default>; + pinctrl-1 = <&i2c20_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&spi00 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&spi00_dyn_default>; + pinctrl-1 = <&spi00_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; diff --git a/ports/zephyr-cp/boards/nordic/nrf54l15tag/circuitpython.toml b/ports/zephyr-cp/boards/nordic/nrf54l15tag/circuitpython.toml new file mode 100644 index 00000000000..e1d763eaa33 --- /dev/null +++ b/ports/zephyr-cp/boards/nordic/nrf54l15tag/circuitpython.toml @@ -0,0 +1,13 @@ +CIRCUITPY_BUILD_EXTENSIONS = ["hex"] +# The ru build ran out of flash. keypad_demux has no known users. +DISABLED_MODULES = ["msgpack", "keypad_demux"] + +# QFN48 package pin numbers. +[pins] +# board.I2C() pins: the sensor I2C bus, P1.11/P1.12. +SCL = 39 +SDA = 40 +# board.SPI() pins: the bmi270's bus, P1.08/P1.06/P1.05. +SCK = 9 +MOSI = 7 +MISO = 6 diff --git a/ports/zephyr-cp/boards/nordic/nrf54lm20dk/autogen_board_info.toml b/ports/zephyr-cp/boards/nordic/nrf54lm20dk/autogen_board_info.toml new file mode 100644 index 00000000000..d0a951713de --- /dev/null +++ b/ports/zephyr-cp/boards/nordic/nrf54lm20dk/autogen_board_info.toml @@ -0,0 +1,145 @@ +# This file is autogenerated when a board is built. Do not edit. Do commit it to git. Other scripts use its info. +name = "Nordic Semiconductor nRF54LM20 DK" + +[modules] +__future__ = true +_airlift = false +_bleio = true # Zephyr board has _bleio +_eve = false +_pew = false +_pixelmap = true # Zephyr board has neopixel_write +_stage = false +adafruit_bus_device = true +adafruit_pixelbuf = true # Zephyr board has neopixel_write +aesio = true +alarm = false +analogbufio = false +analogio = false +async_spi = true # Zephyr board has async_spi +atexit = true +audiobusio = false +audiocore = false +audiodelays = false +audiofilewriter = false +audiofilters = false +audiofreeverb = false +audioi2sin = false +audioio = false +audiomixer = false +audiomp3 = false +audiopwmio = false +audiospeed = false +audiotap = false +aurora_epaper = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio +bitops = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio +camera = false +canio = false +codeop = true +countio = false +cryptography = false +digitalio = true +displayio = true # Zephyr board has busio +dotclockframebuffer = false +dualbank = false +emmcio = false +epaperdisplay = true # Zephyr board has busio +floppyio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio +frequencyio = false +getpass = true +gifio = true # Zephyr board has busio +gnss = false +hardwarekey = false +hashlib = true +hmac = false +hostnetwork = false +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false +i2ctarget = false +imagecapture = false +ipaddress = false +is31fl3741 = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true +max3421e = false +mcp4822 = false +mdns = false +memorymap = false +memorymonitor = false +microcontroller = true +mii = false +mipicsi = false +mipidsi = false +msgpack = true +neopixel_write = true # Zephyr board has neopixel_write +nvm = true # Board has NVM partition +onewireio = false +os = true +paralleldisplaybus = false +picogame = false +picogame3d = false +ps2io = false +pulseio = false +pwmio = true # Zephyr board has pwmio +qrio = false +qspibus = false +rainbowio = true +random = true +rclcpy = false +rgbmatrix = false +rotaryio = true # Zephyr board has rotaryio +rtc = false +sdcardio = true # Zephyr board has busio +sdioio = false +sharpdisplay = true # Zephyr board has busio +socketpool = false +spitarget = false +ssl = false +storage = true # Zephyr board has flash +struct = true +supervisor = true +synthio = false +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio +time = true +touchio = true +traceback = true +uheap = false +usb = false +usb_audio = false +usb_cdc = true +usb_hid = true +usb_host = false +usb_host_audio = false +usb_host_bulk = false +usb_midi = false +usb_video = false +ustack = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog +wifi = false +zephyr_display = false +zephyr_input = true # Zephyr board has zephyr_input +zephyr_kernel = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/nordic/nrf54lm20dk/board.conf b/ports/zephyr-cp/boards/nordic/nrf54lm20dk/board.conf new file mode 100644 index 00000000000..76a97a6cb8a --- /dev/null +++ b/ports/zephyr-cp/boards/nordic/nrf54lm20dk/board.conf @@ -0,0 +1,15 @@ +CONFIG_BT_CTLR_TX_PWR_DYNAMIC_CONTROL=y + +# Work around a latent bug in soc_flash_nrf_ticker.c: with the default +# NRF_RRAM_WRITE_BUFFER_SIZE=1, FLASH_SLOT_WRITE (500 us) < +# FLASH_SYNC_SWITCHING_TIME (1700 us), so `interval = duration - +# FLASH_SYNC_SWITCHING_TIME` underflows and the next flash slot is scheduled +# ~71 minutes out. Any write larger than a single 16-byte slot then times out +# (-ETIMEDOUT / -116), e.g. persisting bond keys right after pairing. +# See zephyr/tests/boards/nrf/rram/overlay-radio_sync.conf. +CONFIG_NRF_RRAM_WRITE_BUFFER_SIZE=32 + +# PWM instances 21 and 22 are enabled in board.overlay with disconnected +# outputs so iobroker can allocate them at runtime for neopixel_write and +# pwmio. +CONFIG_PWM=y diff --git a/ports/zephyr-cp/boards/nordic/nrf54lm20dk/board.overlay b/ports/zephyr-cp/boards/nordic/nrf54lm20dk/board.overlay new file mode 100644 index 00000000000..e07eac751f5 --- /dev/null +++ b/ports/zephyr-cp/boards/nordic/nrf54lm20dk/board.overlay @@ -0,0 +1,197 @@ +// nRF54LM20 DK has USB. Include the main app overlay for USB CDC ACM console and data. +// +// Enable the SoC watchdog for the watchdog module: the upstream board dtsi +// already aliases watchdog0 to &wdt31, the node itself is just disabled. +&wdt31 { status = "okay"; }; + +#include "../../../app.overlay" + +// Enable every free serial peripheral instance so CircuitPython can mux it to +// arbitrary pins at runtime. Each instance is enabled in one mode because the +// i2c/spi/uart nodes of an instance are the same peripheral (enforced by +// zephyr/soc/nordic/validate_enabled_instances.c). All signals are +// disconnected and the devices are marked zephyr,deferred-init so nothing is +// claimed at boot; iobroker initializes and routes a device when a busio +// object is constructed and de-initializes it on release. +// +// See "nRF serial instances" in internal-modules/iobroker/README.md for how +// the instances are shared and allocated. +// +// Instance 20 is left alone: uart20 is the console (main UART) and i2c20/spi20 +// share that same peripheral, so they must not be enabled. Instance 00 is +// owned by spi00 and the MX25R64 SPI flash, so uart00 must not be enabled. + +&pinctrl { + i2c21_dyn_default: i2c21_dyn_default { + group1 { + psels = , + ; + }; + }; + + i2c21_dyn_sleep: i2c21_dyn_sleep { + group1 { + psels = , + ; + }; + }; + + i2c23_dyn_default: i2c23_dyn_default { + group1 { + psels = , + ; + }; + }; + + i2c23_dyn_sleep: i2c23_dyn_sleep { + group1 { + psels = , + ; + }; + }; + + spi22_dyn_default: spi22_dyn_default { + group1 { + psels = , + , + ; + }; + }; + + spi22_dyn_sleep: spi22_dyn_sleep { + group1 { + psels = , + , + ; + }; + }; + + spi24_dyn_default: spi24_dyn_default { + group1 { + psels = , + , + ; + }; + }; + + spi24_dyn_sleep: spi24_dyn_sleep { + group1 { + psels = , + , + ; + }; + }; + + uart30_dyn_default: uart30_dyn_default { + group1 { + psels = , + ; + }; + }; + + uart30_dyn_sleep: uart30_dyn_sleep { + group1 { + psels = , + ; + }; + }; + + pwm21_dyn_default: pwm21_dyn_default { + group1 { + psels = , + , + , + ; + }; + }; + + pwm21_dyn_sleep: pwm21_dyn_sleep { + group1 { + psels = , + , + , + ; + }; + }; + + pwm22_dyn_default: pwm22_dyn_default { + group1 { + psels = , + , + , + ; + }; + }; + + pwm22_dyn_sleep: pwm22_dyn_sleep { + group1 { + psels = , + , + , + ; + }; + }; +}; + +&i2c21 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&i2c21_dyn_default>; + pinctrl-1 = <&i2c21_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&i2c23 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&i2c23_dyn_default>; + pinctrl-1 = <&i2c23_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&spi22 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&spi22_dyn_default>; + pinctrl-1 = <&spi22_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&spi24 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&spi24_dyn_default>; + pinctrl-1 = <&spi24_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&uart30 { + status = "okay"; + zephyr,deferred-init; + current-speed = <115200>; + pinctrl-0 = <&uart30_dyn_default>; + pinctrl-1 = <&uart30_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +// PWM instances 21 and 22, same scheme: all four outputs disconnected and +// deferred init, so iobroker can hand an instance to neopixel_write and +// pwmio and route its outputs at runtime. Instance 20 is left as the board +// defines it: enabled with fixed pins for the PWM LED. On this SoC the "2x" +// instances can only drive P1 and P3 pads (see the iobroker README). + +&pwm21 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&pwm21_dyn_default>; + pinctrl-1 = <&pwm21_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; + +&pwm22 { + status = "okay"; + zephyr,deferred-init; + pinctrl-0 = <&pwm22_dyn_default>; + pinctrl-1 = <&pwm22_dyn_sleep>; + pinctrl-names = "default", "sleep"; +}; diff --git a/ports/zephyr-cp/boards/nordic/nrf54lm20dk/circuitpython.toml b/ports/zephyr-cp/boards/nordic/nrf54lm20dk/circuitpython.toml new file mode 100644 index 00000000000..a4a1462c121 --- /dev/null +++ b/ports/zephyr-cp/boards/nordic/nrf54lm20dk/circuitpython.toml @@ -0,0 +1,123 @@ +CIRCUITPY_BUILD_EXTENSIONS = ["hex", "uf2", "signed.bin"] + +# Headers silkscreened PORT0 (P0.00-P0.09), PORT1:00-15 (P1.00-P1.15), +# PORT1:16-31 (P1.16-P1.31), PORT2 (P2.00-P2.10) and PORT3 (P3.00-P3.12), +# resolved to CSP98 ball names through the package map selected in board.conf. + +[pins] +PORT0_00 = "K3" +PORT0_01 = "K2" +PORT0_02 = "J3" +PORT0_03 = "J2" +PORT0_04 = "J1" +PORT0_05 = "H3" +PORT0_06 = "H2" +PORT0_07 = "G3" +PORT0_08 = "F3" +PORT0_09 = "E3" + +# P1.01 (NFC1) and P1.02 (NFC2) are routed to the NFC antenna by default; +# move R33/R34 to R3/R4 and disable the NFCT peripheral to use them as GPIO. +PORT1_00 = "K8" +PORT1_01 = "J6" +PORT1_02 = "J7" +PORT1_03 = "H9" +PORT1_04 = "J9" +PORT1_05 = "H8" +PORT1_06 = "J8" +PORT1_07 = "G8" +PORT1_08 = "F8" +PORT1_09 = "E8" +PORT1_10 = "D5" +PORT1_11 = "C5" +PORT1_12 = "C4" +PORT1_13 = "C3" +PORT1_14 = "C2" +PORT1_15 = "B2" +PORT1_16 = "B3" +PORT1_17 = "B4" +PORT1_18 = "B5" +PORT1_19 = "B6" +# P1.20/P1.21 feed the 32.768 kHz crystal by default; short SB3/SB4 (and cut +# SB1/SB2) to use them as GPIO. +PORT1_22 = "D6" +PORT1_23 = "B7" +PORT1_24 = "D7" +PORT1_25 = "E7" +PORT1_26 = "B8" +PORT1_27 = "C8" +PORT1_28 = "D8" +PORT1_29 = "H10" +PORT1_30 = "J10" +PORT1_31 = "K9" + +# P2.00-P2.05 are shared with the MX25R64 external flash. +PORT2_00 = "B10" +PORT2_01 = "C10" +PORT2_02 = "D10" +PORT2_03 = "E10" +PORT2_04 = "F10" +PORT2_05 = "G9" +PORT2_06 = "B9" +PORT2_07 = "C9" +PORT2_08 = "D9" +PORT2_09 = "E9" +PORT2_10 = "F9" + +PORT3_00 = "H7" +PORT3_01 = "H6" +PORT3_02 = "H5" +PORT3_03 = "H4" +PORT3_04 = "J4" +PORT3_05 = "G7" +PORT3_06 = "G6" +PORT3_07 = "G5" +PORT3_08 = "G4" +PORT3_09 = "F7" +PORT3_10 = "F4" +PORT3_11 = "E4" +PORT3_12 = "D4" + +# Silkscreen button names. LED0-LED3, SW0-SW3 and PUSH_BUTTON_0-3 already come +# from the devicetree. +BUTTON0 = "B8" +BUTTON1 = "E8" +BUTTON2 = "F8" +BUTTON3 = "H3" + +# board.SPI() pins: the expansion header's SPI positions (header D3/D0/D1). +SCK = "H4" +MOSI = "H7" +MISO = "H6" +# board.UART() pins: P0.06/P0.07, the debugger's VCOM0 serial port. +TX = "H2" +RX = "G3" + +# Nordic expansion board header (P17), named per the board silkscreen. +# Positions key the gpio-map order (header GPIO 00-21, odd/even columns from +# the A0/B0 end); I0 sits opposite the header's mid GND and has no gpio-map +# entry. Function groups check out: B0 = PWM (P3.04), D0-D3 = SPI +# (P3.00-P3.03), H0-H5 = QSPI (P2.00-P2.05). +[connectors.nordic_expansion_header] +0 = "A0" +1 = "B0" +2 = "C0" +3 = "C1" +4 = "C2" +5 = "C3" +6 = "D0" +7 = "D1" +8 = "E2" +9 = "E1" +10 = "D2" +11 = "D3" +12 = "F0" +13 = "F1" +14 = "C4" +15 = "G0" +16 = "H0" +17 = "H1" +18 = "H2" +19 = "H3" +20 = "H4" +21 = "H5" diff --git a/ports/zephyr-cp/boards/nordic/nrf7002dk/autogen_board_info.toml b/ports/zephyr-cp/boards/nordic/nrf7002dk/autogen_board_info.toml deleted file mode 100644 index 85b5a9c7e0f..00000000000 --- a/ports/zephyr-cp/boards/nordic/nrf7002dk/autogen_board_info.toml +++ /dev/null @@ -1,111 +0,0 @@ -# This file is autogenerated when a board is built. Do not edit. Do commit it to git. Other scripts use its info. -name = "Nordic Semiconductor nRF7002 DK" - -[modules] -__future__ = false -_bleio = false -_eve = false -_pew = false -_pixelmap = false -_stage = false -adafruit_bus_device = false -adafruit_pixelbuf = false -aesio = false -alarm = false -analogbufio = false -analogio = false -atexit = false -audiobusio = false -audiocore = false -audiodelays = false -audiofilters = false -audioio = false -audiomixer = false -audiomp3 = false -audiopwmio = false -aurora_epaper = false -bitbangio = false -bitmapfilter = false -bitmaptools = false -bitops = false -board = false -busdisplay = false -busio = false -camera = false -canio = false -codeop = false -countio = false -digitalio = true -displayio = false -dotclockframebuffer = false -dualbank = false -epaperdisplay = false -floppyio = false -fontio = false -fourwire = false -framebufferio = false -frequencyio = false -getpass = false -gifio = false -gnss = false -hashlib = false -i2cdisplaybus = false -i2ctarget = false -imagecapture = false -ipaddress = false -is31fl3741 = false -jpegio = false -keypad = false -keypad_demux = false -locale = false -math = false -max3421e = false -mdns = false -memorymap = false -memorymonitor = false -microcontroller = true -msgpack = false -neopixel_write = false -nvm = false -onewireio = false -os = true -paralleldisplaybus = false -ps2io = false -pulseio = false -pwmio = false -qrio = false -rainbowio = false -random = true -rgbmatrix = false -rotaryio = false -rtc = false -sdcardio = false -sdioio = false -sharpdisplay = false -socketpool = true # Zephyr networking enabled -spitarget = false -ssl = true # Zephyr networking enabled -storage = true # Zephyr board has flash -struct = true -supervisor = false -synthio = false -terminalio = false -tilepalettemapper = false -time = true -touchio = false -traceback = false -uheap = false -usb = false -usb_cdc = true -usb_hid = false -usb_host = false -usb_midi = false -usb_video = false -ustack = false -vectorio = false -warnings = false -watchdog = false -wifi = true # Zephyr board has wifi -zephyr_kernel = false -zephyr_serial = true -zlib = false diff --git a/ports/zephyr-cp/boards/nordic/nrf7002dk/circuitpython.toml b/ports/zephyr-cp/boards/nordic/nrf7002dk/circuitpython.toml deleted file mode 100644 index 76b10578813..00000000000 --- a/ports/zephyr-cp/boards/nordic/nrf7002dk/circuitpython.toml +++ /dev/null @@ -1,4 +0,0 @@ -CIRCUITPY_BUILD_EXTENSIONS = ["elf"] -USB_VID=0x239A -USB_PID=0x8168 -BLOBS=["nrf_wifi"] diff --git a/ports/zephyr-cp/boards/nrf5340dk_nrf5340_cpuapp.conf b/ports/zephyr-cp/boards/nrf5340dk_nrf5340_cpuapp.conf deleted file mode 100644 index fa0532e8150..00000000000 --- a/ports/zephyr-cp/boards/nrf5340dk_nrf5340_cpuapp.conf +++ /dev/null @@ -1,6 +0,0 @@ -CONFIG_BT=y -CONFIG_BT_PERIPHERAL=y -CONFIG_BT_CENTRAL=y -CONFIG_BT_BROADCASTER=y -CONFIG_BT_OBSERVER=y -CONFIG_BT_EXT_ADV=y diff --git a/ports/zephyr-cp/boards/nrf7002dk_nrf5340_cpuapp.conf b/ports/zephyr-cp/boards/nrf7002dk_nrf5340_cpuapp.conf deleted file mode 100644 index 6f01624bb3a..00000000000 --- a/ports/zephyr-cp/boards/nrf7002dk_nrf5340_cpuapp.conf +++ /dev/null @@ -1,12 +0,0 @@ -CONFIG_NETWORKING=y -CONFIG_WIFI=y - -CONFIG_MBEDTLS_TLS_VERSION_1_2=y -CONFIG_MBEDTLS_USE_PSA_CRYPTO=n - -CONFIG_BT=y -CONFIG_BT_PERIPHERAL=y -CONFIG_BT_CENTRAL=y -CONFIG_BT_BROADCASTER=y -CONFIG_BT_OBSERVER=y -CONFIG_BT_EXT_ADV=y diff --git a/ports/zephyr-cp/boards/nxp/frdm_mcxn947/autogen_board_info.toml b/ports/zephyr-cp/boards/nxp/frdm_mcxn947/autogen_board_info.toml new file mode 100644 index 00000000000..a8c6f652eb1 --- /dev/null +++ b/ports/zephyr-cp/boards/nxp/frdm_mcxn947/autogen_board_info.toml @@ -0,0 +1,145 @@ +# This file is autogenerated when a board is built. Do not edit. Do commit it to git. Other scripts use its info. +name = "NXP Semiconductors FRDM-MCXN947" + +[modules] +__future__ = true +_airlift = false +_bleio = false +_eve = false +_pew = false +_pixelmap = false +_stage = false +adafruit_bus_device = true +adafruit_pixelbuf = false +aesio = true +alarm = false +analogbufio = false +analogio = true # Zephyr board has analogio +async_spi = true # Zephyr board has async_spi +atexit = true +audiobusio = true # Zephyr board has audiobusio +audiocore = true # Zephyr board has audiobusio +audiodelays = true # Zephyr board has audiobusio +audiofilewriter = false +audiofilters = true # Zephyr board has audiobusio +audiofreeverb = true # Zephyr board has audiobusio +audioi2sin = false +audioio = false +audiomixer = true # Zephyr board has audiobusio +audiomp3 = true # Zephyr board has audiobusio +audiopwmio = false +audiospeed = false +audiotap = true # Zephyr board has audiobusio +aurora_epaper = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio +bitops = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio +camera = false +canio = false +codeop = true +countio = false +cryptography = false +digitalio = true +displayio = true # Zephyr board has busio +dotclockframebuffer = false +dualbank = false +emmcio = false +epaperdisplay = true # Zephyr board has busio +floppyio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio +frequencyio = false +getpass = true +gifio = true # Zephyr board has busio +gnss = false +hardwarekey = false +hashlib = true # Zephyr networking enabled +hmac = false +hostnetwork = false +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false +i2ctarget = false +imagecapture = false +ipaddress = true # Zephyr networking enabled +is31fl3741 = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true +max3421e = false +mcp4822 = false +mdns = false +memorymap = false +memorymonitor = false +microcontroller = true +mii = true # Zephyr board has ethernet +mipicsi = false +mipidsi = false +msgpack = true +neopixel_write = false +nvm = true # Board has NVM partition +onewireio = false +os = true +paralleldisplaybus = false +picogame = false +picogame3d = false +ps2io = false +pulseio = false +pwmio = false +qrio = false +qspibus = false +rainbowio = true +random = true +rclcpy = false +rgbmatrix = false +rotaryio = true # Zephyr board has rotaryio +rtc = true # Zephyr board has rtc +sdcardio = true # Zephyr board has busio +sdioio = false +sharpdisplay = true # Zephyr board has busio +socketpool = true # Zephyr networking enabled +spitarget = false +ssl = true # Zephyr ethernet enabled +storage = true # Zephyr board has flash +struct = true +supervisor = true +synthio = true # Zephyr board has audiobusio +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio +time = true +touchio = true +traceback = true +uheap = false +usb = false +usb_audio = false +usb_cdc = true +usb_hid = true +usb_host = false +usb_host_audio = false +usb_host_bulk = false +usb_midi = false +usb_video = false +ustack = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog +wifi = false +zephyr_display = false +zephyr_input = true # Zephyr board has zephyr_input +zephyr_kernel = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/nxp/frdm_mcxn947/board.conf b/ports/zephyr-cp/boards/nxp/frdm_mcxn947/board.conf new file mode 100644 index 00000000000..311648c6154 --- /dev/null +++ b/ports/zephyr-cp/boards/nxp/frdm_mcxn947/board.conf @@ -0,0 +1,7 @@ +CONFIG_DMA_TCD_QUEUE_SIZE=4 + +# analogio: the board overlay enables lpadc0 (with its vref regulator) and +# dac0; iobroker resolves SoC pads to their fixed LPADC channel and the +# LPDAC output pad. +CONFIG_ADC=y +CONFIG_DAC=y diff --git a/ports/zephyr-cp/boards/nxp/frdm_mcxn947/board.overlay b/ports/zephyr-cp/boards/nxp/frdm_mcxn947/board.overlay new file mode 100644 index 00000000000..ae9febdb29f --- /dev/null +++ b/ports/zephyr-cp/boards/nxp/frdm_mcxn947/board.overlay @@ -0,0 +1,25 @@ + +#include "../../../app.overlay" + +/* analogio: enable LPADC0 (with its vref regulator) and the LPDAC0. + * The SoC pads' analog functions are bonded at mux 0 (see the pin functions + * table in modules/hal/nxp/dts/nxp/mcx/MCXN947VDF-pinctrl.h); iobroker + * resolves pads to their fixed LPADC/LPDAC channels. + * + * analogio measures inputs against the SoC's supply-referenced range, so + * mux CFG[REFSEL] to VDDA (3.3 V) instead of the on-die VREF regulator + * (1.8 V full scale): board signals (e.g. the Arduino analog pins) run to + * 3.3 V. VREFH can't be used instead: the schematic wires it to the VREF + * regulator output through 0-ohm R171, so it is 1.8 V like REFSEL = 1. */ +&vref { + status = "okay"; +}; + +&lpadc0 { + status = "okay"; + voltage-ref = <2>; +}; + +&dac0 { + status = "okay"; +}; diff --git a/ports/zephyr-cp/boards/nxp/frdm_mcxn947/circuitpython.toml b/ports/zephyr-cp/boards/nxp/frdm_mcxn947/circuitpython.toml new file mode 100644 index 00000000000..966dc2ae634 --- /dev/null +++ b/ports/zephyr-cp/boards/nxp/frdm_mcxn947/circuitpython.toml @@ -0,0 +1,18 @@ +CIRCUITPY_BUILD_EXTENSIONS = ["hex", "uf2"] + +[pins] +# Arduino header J4's analog pins, from UM12018 Table 20. A0 (ANA_0) and +# A1 (ANA_1) sit on analog-only pads, which only the package pin map can +# name; A2..A5 are GPIO pads the devicetree's arduino-header gpio-map +# already names. +A0 = "P3" +A1 = "R3" + +[connectors.arduino_header] +# The generic arduino-header-r3 name list assumes the gpio-map enumerates +# the whole header; this board only maps its four analog pins (J4 pins 6, +# 8, 10 and 12), so rebind them to their silkscreen names. +"0" = "A2" +"1" = "A3" +"2" = "A4" +"3" = "A5" diff --git a/ports/zephyr-cp/boards/nxp/frdm_rw612/autogen_board_info.toml b/ports/zephyr-cp/boards/nxp/frdm_rw612/autogen_board_info.toml new file mode 100644 index 00000000000..ef7bdcbc378 --- /dev/null +++ b/ports/zephyr-cp/boards/nxp/frdm_rw612/autogen_board_info.toml @@ -0,0 +1,145 @@ +# This file is autogenerated when a board is built. Do not edit. Do commit it to git. Other scripts use its info. +name = "NXP Semiconductors FRDM-RW612" + +[modules] +__future__ = true +_airlift = false +_bleio = true # Zephyr board has _bleio +_eve = false +_pew = false +_pixelmap = false +_stage = false +adafruit_bus_device = true +adafruit_pixelbuf = false +aesio = true +alarm = false +analogbufio = false +analogio = false +async_spi = true # Zephyr board has async_spi +atexit = true +audiobusio = false +audiocore = false +audiodelays = false +audiofilewriter = false +audiofilters = false +audiofreeverb = false +audioi2sin = false +audioio = false +audiomixer = false +audiomp3 = false +audiopwmio = false +audiospeed = false +audiotap = false +aurora_epaper = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio +bitops = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio +camera = false +canio = false +codeop = true +countio = false +cryptography = false +digitalio = true +displayio = true # Zephyr board has busio +dotclockframebuffer = false +dualbank = false +emmcio = false +epaperdisplay = true # Zephyr board has busio +floppyio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio +frequencyio = false +getpass = true +gifio = true # Zephyr board has busio +gnss = false +hardwarekey = false +hashlib = true # Zephyr networking enabled +hmac = false +hostnetwork = false +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false +i2ctarget = false +imagecapture = false +ipaddress = true # Zephyr networking enabled +is31fl3741 = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true +max3421e = false +mcp4822 = false +mdns = false +memorymap = false +memorymonitor = false +microcontroller = true +mii = true # Zephyr board has ethernet +mipicsi = false +mipidsi = false +msgpack = true +neopixel_write = false +nvm = true # Board has NVM partition +onewireio = false +os = true +paralleldisplaybus = false +picogame = false +picogame3d = false +ps2io = false +pulseio = false +pwmio = false +qrio = false +qspibus = false +rainbowio = true +random = true +rclcpy = false +rgbmatrix = false +rotaryio = true # Zephyr board has rotaryio +rtc = false +sdcardio = true # Zephyr board has busio +sdioio = false +sharpdisplay = true # Zephyr board has busio +socketpool = true # Zephyr networking enabled +spitarget = false +ssl = true # Zephyr wifi enabled +storage = true +struct = true +supervisor = true +synthio = false +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio +time = true +touchio = true +traceback = true +uheap = false +usb = false +usb_audio = false +usb_cdc = true +usb_hid = true +usb_host = false +usb_host_audio = false +usb_host_bulk = false +usb_midi = false +usb_video = false +ustack = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog +wifi = true # Zephyr board has wifi +zephyr_display = false +zephyr_input = true # Zephyr board has zephyr_input +zephyr_kernel = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/nxp/frdm_rw612/board.conf b/ports/zephyr-cp/boards/nxp/frdm_rw612/board.conf new file mode 100644 index 00000000000..53697d07627 --- /dev/null +++ b/ports/zephyr-cp/boards/nxp/frdm_rw612/board.conf @@ -0,0 +1,28 @@ +CONFIG_NETWORKING=y +CONFIG_NET_IPV4=y +CONFIG_NET_DHCPV4=y +CONFIG_NET_SOCKETS=y + +CONFIG_WIFI=y +CONFIG_WIFI_NM_WPA_SUPPLICANT_LEGACY_CRYPTO=n +CONFIG_NET_L2_WIFI_MGMT=y +CONFIG_NET_MGMT_EVENT=y +CONFIG_NET_MGMT_EVENT_INFO=y + +CONFIG_NET_HOSTNAME_ENABLE=y +CONFIG_NET_HOSTNAME_DYNAMIC=y +CONFIG_NET_HOSTNAME="circuitpython" + +CONFIG_MBEDTLS=y + +# BLE implies the p256-m secp256r1 driver; with it on, the additional curves +# wanted for TLS certificate chains (384/521, brainpool, k1, x25519) are +# unaccelerated, and tf-psa-crypto's driver-only-builds check rejects the +# resulting partial ECC acceleration. Disable the driver so every wanted curve +# uses the builtin implementation and the config check passes. +CONFIG_MBEDTLS_PSA_P256M_DRIVER_ENABLED=n + +# Override Kconfig default (3) +CONFIG_BT_BUF_ACL_TX_COUNT=8 + +CONFIG_UDC_WORKQUEUE_STACK_SIZE=1024 diff --git a/ports/zephyr-cp/boards/nxp/frdm_rw612/board.overlay b/ports/zephyr-cp/boards/nxp/frdm_rw612/board.overlay new file mode 100644 index 00000000000..cb054681fa5 --- /dev/null +++ b/ports/zephyr-cp/boards/nxp/frdm_rw612/board.overlay @@ -0,0 +1,2 @@ + +#include "../../../app.overlay" diff --git a/ports/zephyr-cp/boards/nxp/frdm_rw612/circuitpython.toml b/ports/zephyr-cp/boards/nxp/frdm_rw612/circuitpython.toml new file mode 100644 index 00000000000..dc00f11fef3 --- /dev/null +++ b/ports/zephyr-cp/boards/nxp/frdm_rw612/circuitpython.toml @@ -0,0 +1,5 @@ +CIRCUITPY_BUILD_EXTENSIONS = ["hex", "uf2", "signed.bin"] +BLOBS=["hal_nxp"] + +[blob_fetch_args] +hal_nxp = ["--allow-regex", "^rw61x/"] diff --git a/ports/zephyr-cp/boards/nxp/mimxrt1010_evk/autogen_board_info.toml b/ports/zephyr-cp/boards/nxp/mimxrt1010_evk/autogen_board_info.toml new file mode 100644 index 00000000000..7192cdf4b91 --- /dev/null +++ b/ports/zephyr-cp/boards/nxp/mimxrt1010_evk/autogen_board_info.toml @@ -0,0 +1,145 @@ +# This file is autogenerated when a board is built. Do not edit. Do commit it to git. Other scripts use its info. +name = "NXP Semiconductors IMXRT1010-EVK" + +[modules] +__future__ = true +_airlift = false +_bleio = false +_eve = false +_pew = false +_pixelmap = false +_stage = false +adafruit_bus_device = true +adafruit_pixelbuf = false +aesio = true +alarm = false +analogbufio = false +analogio = false +async_spi = true # Zephyr board has async_spi +atexit = true +audiobusio = false +audiocore = false +audiodelays = false +audiofilewriter = false +audiofilters = false +audiofreeverb = false +audioi2sin = false +audioio = false +audiomixer = false +audiomp3 = false +audiopwmio = false +audiospeed = false +audiotap = false +aurora_epaper = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio +bitops = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio +camera = false +canio = false +codeop = true +countio = false +cryptography = false +digitalio = true +displayio = true # Zephyr board has busio +dotclockframebuffer = false +dualbank = false +emmcio = false +epaperdisplay = true # Zephyr board has busio +floppyio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio +frequencyio = false +getpass = true +gifio = true # Zephyr board has busio +gnss = false +hardwarekey = false +hashlib = true +hmac = false +hostnetwork = false +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false +i2ctarget = false +imagecapture = false +ipaddress = false +is31fl3741 = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true +max3421e = false +mcp4822 = false +mdns = false +memorymap = false +memorymonitor = false +microcontroller = true +mii = false +mipicsi = false +mipidsi = false +msgpack = true +neopixel_write = false +nvm = true # Board has NVM partition +onewireio = false +os = true +paralleldisplaybus = false +picogame = false +picogame3d = false +ps2io = false +pulseio = false +pwmio = false +qrio = false +qspibus = false +rainbowio = true +random = true +rclcpy = false +rgbmatrix = false +rotaryio = true # Zephyr board has rotaryio +rtc = true # Zephyr board has rtc +sdcardio = true # Zephyr board has busio +sdioio = false +sharpdisplay = true # Zephyr board has busio +socketpool = false +spitarget = false +ssl = false +storage = true +struct = true +supervisor = true +synthio = false +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio +time = true +touchio = true +traceback = true +uheap = false +usb = false +usb_audio = false +usb_cdc = true +usb_hid = true +usb_host = false +usb_host_audio = false +usb_host_bulk = false +usb_midi = false +usb_video = false +ustack = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog +wifi = false +zephyr_display = false +zephyr_input = true # Zephyr board has zephyr_input +zephyr_kernel = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/nxp/mimxrt1010_evk/board.conf b/ports/zephyr-cp/boards/nxp/mimxrt1010_evk/board.conf new file mode 100644 index 00000000000..e4fd5782295 --- /dev/null +++ b/ports/zephyr-cp/boards/nxp/mimxrt1010_evk/board.conf @@ -0,0 +1,4 @@ +# No Zephyr UART console by default (see board.overlay); a CONSOLE=1 build turns +# it back on in console.conf. +CONFIG_UART_CONSOLE=n +CONFIG_LOG_BACKEND_UART=n diff --git a/ports/zephyr-cp/boards/nxp/mimxrt1010_evk/board.overlay b/ports/zephyr-cp/boards/nxp/mimxrt1010_evk/board.overlay new file mode 100644 index 00000000000..9a94f6ea244 --- /dev/null +++ b/ports/zephyr-cp/boards/nxp/mimxrt1010_evk/board.overlay @@ -0,0 +1,13 @@ +/* No Zephyr console by default, so LPUART1 on the Arduino header's D0/D1 + * (also the debug probe's serial port) is free for busio.UART, as in + * ports/mimxrt10xx. A CONSOLE=1 build puts the console back on LPUART1 + * (console.overlay). */ +/ { + chosen { + /delete-property/ zephyr,console; + /delete-property/ zephyr,shell-uart; + /delete-property/ zephyr,uart-mcumgr; + }; +}; + +#include "../../../app.overlay" diff --git a/ports/zephyr-cp/boards/nxp/mimxrt1010_evk/circuitpython.toml b/ports/zephyr-cp/boards/nxp/mimxrt1010_evk/circuitpython.toml new file mode 100644 index 00000000000..6da3affe9ba --- /dev/null +++ b/ports/zephyr-cp/boards/nxp/mimxrt1010_evk/circuitpython.toml @@ -0,0 +1,4 @@ +CIRCUITPY_BUILD_EXTENSIONS = ["hex", "uf2"] +USB_VID=0x239A +USB_PID=0x8078 +NAME="IMXRT1010-EVK" diff --git a/ports/zephyr-cp/boards/nxp/mimxrt1010_evk/console.overlay b/ports/zephyr-cp/boards/nxp/mimxrt1010_evk/console.overlay new file mode 100644 index 00000000000..ab75c266e45 --- /dev/null +++ b/ports/zephyr-cp/boards/nxp/mimxrt1010_evk/console.overlay @@ -0,0 +1,10 @@ +/* Applied after board.overlay in CONSOLE=1 and DEBUG=1 builds: the Zephyr + * console on LPUART1, the Arduino header's D0/D1 and the debug probe's serial + * port. D0/D1 are then not available to busio.UART. */ +/ { + chosen { + zephyr,console = &lpuart1; + zephyr,shell-uart = &lpuart1; + zephyr,uart-mcumgr = &lpuart1; + }; +}; diff --git a/ports/zephyr-cp/boards/nxp/mimxrt1170_evk/autogen_board_info.toml b/ports/zephyr-cp/boards/nxp/mimxrt1170_evk/autogen_board_info.toml new file mode 100644 index 00000000000..0a1fcce924f --- /dev/null +++ b/ports/zephyr-cp/boards/nxp/mimxrt1170_evk/autogen_board_info.toml @@ -0,0 +1,145 @@ +# This file is autogenerated when a board is built. Do not edit. Do commit it to git. Other scripts use its info. +name = "NXP Semiconductors MIMXRT1170-EVK" + +[modules] +__future__ = true +_airlift = false +_bleio = false +_eve = false +_pew = false +_pixelmap = false +_stage = false +adafruit_bus_device = true +adafruit_pixelbuf = false +aesio = true +alarm = false +analogbufio = false +analogio = false +async_spi = true # Zephyr board has async_spi +atexit = true +audiobusio = true # Zephyr board has audiobusio +audiocore = true # Zephyr board has audiobusio +audiodelays = true # Zephyr board has audiobusio +audiofilewriter = false +audiofilters = true # Zephyr board has audiobusio +audiofreeverb = true # Zephyr board has audiobusio +audioi2sin = false +audioio = false +audiomixer = true # Zephyr board has audiobusio +audiomp3 = true # Zephyr board has audiobusio +audiopwmio = false +audiospeed = false +audiotap = true # Zephyr board has audiobusio +aurora_epaper = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio +bitops = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio +camera = false +canio = false +codeop = true +countio = false +cryptography = false +digitalio = true +displayio = true # Zephyr board has busio +dotclockframebuffer = false +dualbank = false +emmcio = false +epaperdisplay = true # Zephyr board has busio +floppyio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio +frequencyio = false +getpass = true +gifio = true # Zephyr board has busio +gnss = false +hardwarekey = false +hashlib = true # Zephyr networking enabled +hmac = false +hostnetwork = false +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false +i2ctarget = false +imagecapture = false +ipaddress = true # Zephyr networking enabled +is31fl3741 = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true +max3421e = false +mcp4822 = false +mdns = false +memorymap = false +memorymonitor = false +microcontroller = true +mii = true # Zephyr board has ethernet +mipicsi = false +mipidsi = false +msgpack = true +neopixel_write = false +nvm = true # Board has NVM partition +onewireio = false +os = true +paralleldisplaybus = false +picogame = false +picogame3d = false +ps2io = false +pulseio = false +pwmio = false +qrio = false +qspibus = false +rainbowio = true +random = true +rclcpy = false +rgbmatrix = false +rotaryio = true # Zephyr board has rotaryio +rtc = false +sdcardio = true # Zephyr board has busio +sdioio = false +sharpdisplay = true # Zephyr board has busio +socketpool = true # Zephyr networking enabled +spitarget = false +ssl = true # Zephyr ethernet enabled +storage = true +struct = true +supervisor = true +synthio = true # Zephyr board has audiobusio +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio +time = true +touchio = true +traceback = true +uheap = false +usb = false +usb_audio = false +usb_cdc = true +usb_hid = true +usb_host = false +usb_host_audio = false +usb_host_bulk = false +usb_midi = false +usb_video = false +ustack = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog +wifi = false +zephyr_display = false +zephyr_input = true # Zephyr board has zephyr_input +zephyr_kernel = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/nxp/mimxrt1170_evk/board.conf b/ports/zephyr-cp/boards/nxp/mimxrt1170_evk/board.conf new file mode 100644 index 00000000000..61f2d18ca3c --- /dev/null +++ b/ports/zephyr-cp/boards/nxp/mimxrt1170_evk/board.conf @@ -0,0 +1 @@ +CONFIG_DMA_TCD_QUEUE_SIZE=4 diff --git a/ports/zephyr-cp/boards/nxp/mimxrt1170_evk/board.overlay b/ports/zephyr-cp/boards/nxp/mimxrt1170_evk/board.overlay new file mode 100644 index 00000000000..0d0f7420cad --- /dev/null +++ b/ports/zephyr-cp/boards/nxp/mimxrt1170_evk/board.overlay @@ -0,0 +1,6 @@ + +&sai1 { + mclk-output; +}; + +#include "../../../app.overlay" diff --git a/ports/zephyr-cp/boards/nxp/mimxrt1170_evk/circuitpython.toml b/ports/zephyr-cp/boards/nxp/mimxrt1170_evk/circuitpython.toml new file mode 100644 index 00000000000..40562364cde --- /dev/null +++ b/ports/zephyr-cp/boards/nxp/mimxrt1170_evk/circuitpython.toml @@ -0,0 +1 @@ +CIRCUITPY_BUILD_EXTENSIONS = ["hex", "uf2"] diff --git a/ports/zephyr-cp/boards/raspberrypi/rpi_pico2_w_zephyr/autogen_board_info.toml b/ports/zephyr-cp/boards/raspberrypi/rpi_pico2_w_zephyr/autogen_board_info.toml new file mode 100644 index 00000000000..a7c25e7fd83 --- /dev/null +++ b/ports/zephyr-cp/boards/raspberrypi/rpi_pico2_w_zephyr/autogen_board_info.toml @@ -0,0 +1,145 @@ +# This file is autogenerated when a board is built. Do not edit. Do commit it to git. Other scripts use its info. +name = "Raspberry Pi Pico 2 W" + +[modules] +__future__ = true +_airlift = false +_bleio = false +_eve = false +_pew = false +_pixelmap = false +_stage = false +adafruit_bus_device = true +adafruit_pixelbuf = false +aesio = true +alarm = false +analogbufio = false +analogio = false +async_spi = true # Zephyr board has async_spi +atexit = true +audiobusio = false +audiocore = false +audiodelays = false +audiofilewriter = false +audiofilters = false +audiofreeverb = false +audioi2sin = false +audioio = false +audiomixer = false +audiomp3 = false +audiopwmio = false +audiospeed = false +audiotap = false +aurora_epaper = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio +bitops = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio +camera = false +canio = false +codeop = true +countio = false +cryptography = false +digitalio = true +displayio = true # Zephyr board has busio +dotclockframebuffer = false +dualbank = false +emmcio = false +epaperdisplay = true # Zephyr board has busio +floppyio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio +frequencyio = false +getpass = true +gifio = true # Zephyr board has busio +gnss = false +hardwarekey = false +hashlib = true # Zephyr networking enabled +hmac = false +hostnetwork = false +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false +i2ctarget = false +imagecapture = false +ipaddress = true # Zephyr networking enabled +is31fl3741 = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true +max3421e = false +mcp4822 = false +mdns = false +memorymap = false +memorymonitor = false +microcontroller = true +mii = false +mipicsi = false +mipidsi = false +msgpack = true +neopixel_write = false +nvm = true # Board has NVM partition +onewireio = false +os = true +paralleldisplaybus = false +picogame = false +picogame3d = false +ps2io = false +pulseio = false +pwmio = false +qrio = false +qspibus = false +rainbowio = true +random = true +rclcpy = false +rgbmatrix = false +rotaryio = true # Zephyr board has rotaryio +rtc = false +sdcardio = true # Zephyr board has busio +sdioio = false +sharpdisplay = true # Zephyr board has busio +socketpool = true # Zephyr networking enabled +spitarget = false +ssl = true # Zephyr wifi enabled +storage = true +struct = true +supervisor = true +synthio = false +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio +time = true +touchio = true +traceback = true +uheap = false +usb = false +usb_audio = false +usb_cdc = true +usb_hid = true +usb_host = false +usb_host_audio = false +usb_host_bulk = false +usb_midi = false +usb_video = false +ustack = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog +wifi = true # Zephyr board has wifi +zephyr_display = false +zephyr_input = false +zephyr_kernel = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/raspberrypi/rpi_pico2_w_zephyr/board.conf b/ports/zephyr-cp/boards/raspberrypi/rpi_pico2_w_zephyr/board.conf new file mode 100644 index 00000000000..1ec5bcbcc75 --- /dev/null +++ b/ports/zephyr-cp/boards/raspberrypi/rpi_pico2_w_zephyr/board.conf @@ -0,0 +1,25 @@ +CONFIG_NETWORKING=y +CONFIG_NET_IPV4=y +CONFIG_NET_DHCPV4=y +CONFIG_NET_SOCKETS=y + +CONFIG_WIFI=y +CONFIG_WIFI_NM_WPA_SUPPLICANT_LEGACY_CRYPTO=n +CONFIG_NET_L2_WIFI_MGMT=y +CONFIG_NET_MGMT_EVENT=y +CONFIG_NET_MGMT_EVENT_INFO=y + +CONFIG_NET_HOSTNAME_ENABLE=y +CONFIG_NET_HOSTNAME_DYNAMIC=y +CONFIG_NET_HOSTNAME="circuitpython" + +CONFIG_MBEDTLS=y +# Allocate PSA key material with malloc() instead of 38 KB of static slots. +CONFIG_MBEDTLS_PSA_STATIC_KEY_SLOTS=n +# Keep the AES tables in flash instead of copying 8 KB of them into RAM. +CONFIG_MBEDTLS_AES_ROM_TABLES=y + +# No Zephyr UART console by default (see board.overlay); a CONSOLE=1 build turns +# it back on in console.conf. +CONFIG_UART_CONSOLE=n +CONFIG_LOG_BACKEND_UART=n diff --git a/ports/zephyr-cp/boards/raspberrypi/rpi_pico2_w_zephyr/board.overlay b/ports/zephyr-cp/boards/raspberrypi/rpi_pico2_w_zephyr/board.overlay new file mode 100644 index 00000000000..f68c98e5aec --- /dev/null +++ b/ports/zephyr-cp/boards/raspberrypi/rpi_pico2_w_zephyr/board.overlay @@ -0,0 +1,12 @@ +/* Partition layout is owned by the mcuboot fork (dts/raspberrypi/rpi_pico2.dtsi) + * and applied to this image by sysbuild. This overlay only adds board/app config. */ +#include "../../../app.overlay" + +/* No Zephyr console by default, so GP0/GP1 (UART0) are free for busio.UART. A + * CONSOLE=1 build puts the console back on UART0 (console.overlay). */ +/ { + chosen { + /delete-property/ zephyr,console; + /delete-property/ zephyr,shell-uart; + }; +}; diff --git a/ports/zephyr-cp/boards/raspberrypi/rpi_pico2_w_zephyr/circuitpython.toml b/ports/zephyr-cp/boards/raspberrypi/rpi_pico2_w_zephyr/circuitpython.toml new file mode 100644 index 00000000000..343de7d902b --- /dev/null +++ b/ports/zephyr-cp/boards/raspberrypi/rpi_pico2_w_zephyr/circuitpython.toml @@ -0,0 +1,10 @@ +CIRCUITPY_BUILD_EXTENSIONS = ["hex", "uf2"] +USB_VID=0x239A +USB_PID=0x8162 +BLOBS=["hal_infineon"] +NAME="Pico 2 W" +VENDOR="Raspberry Pi" +USB_MANUFACTURER="Raspberry Pi" + +# Non-Zephyr build of the same board; nvm and CIRCUITPY must sit where it puts them. +counterpart = "raspberrypi/raspberry_pi_pico2_w" diff --git a/ports/zephyr-cp/boards/raspberrypi/rpi_pico2_w_zephyr/console.overlay b/ports/zephyr-cp/boards/raspberrypi/rpi_pico2_w_zephyr/console.overlay new file mode 100644 index 00000000000..e9fe53dd84f --- /dev/null +++ b/ports/zephyr-cp/boards/raspberrypi/rpi_pico2_w_zephyr/console.overlay @@ -0,0 +1,9 @@ +/* Applied after board.overlay in CONSOLE=1 and DEBUG=1 builds: the Zephyr + * console on UART0, on GP0 (TX) and GP1 (RX). GP0/GP1 are then not + * available to busio.UART. */ +/ { + chosen { + zephyr,console = &uart0; + zephyr,shell-uart = &uart0; + }; +}; diff --git a/ports/zephyr-cp/boards/raspberrypi/rpi_pico2_zephyr/autogen_board_info.toml b/ports/zephyr-cp/boards/raspberrypi/rpi_pico2_zephyr/autogen_board_info.toml new file mode 100644 index 00000000000..86c3369cc9f --- /dev/null +++ b/ports/zephyr-cp/boards/raspberrypi/rpi_pico2_zephyr/autogen_board_info.toml @@ -0,0 +1,145 @@ +# This file is autogenerated when a board is built. Do not edit. Do commit it to git. Other scripts use its info. +name = "Raspberry Pi Pico 2" + +[modules] +__future__ = true +_airlift = false +_bleio = false +_eve = false +_pew = false +_pixelmap = false +_stage = false +adafruit_bus_device = true +adafruit_pixelbuf = false +aesio = true +alarm = false +analogbufio = false +analogio = false +async_spi = false +atexit = true +audiobusio = false +audiocore = false +audiodelays = false +audiofilewriter = false +audiofilters = false +audiofreeverb = false +audioi2sin = false +audioio = false +audiomixer = false +audiomp3 = false +audiopwmio = false +audiospeed = false +audiotap = false +aurora_epaper = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio +bitops = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio +camera = false +canio = false +codeop = true +countio = false +cryptography = false +digitalio = true +displayio = true # Zephyr board has busio +dotclockframebuffer = false +dualbank = false +emmcio = false +epaperdisplay = true # Zephyr board has busio +floppyio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio +frequencyio = false +getpass = true +gifio = true # Zephyr board has busio +gnss = false +hardwarekey = false +hashlib = true +hmac = false +hostnetwork = false +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false +i2ctarget = false +imagecapture = false +ipaddress = false +is31fl3741 = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true +max3421e = false +mcp4822 = false +mdns = false +memorymap = false +memorymonitor = false +microcontroller = true +mii = false +mipicsi = false +mipidsi = false +msgpack = true +neopixel_write = false +nvm = true # Board has NVM partition +onewireio = false +os = true +paralleldisplaybus = false +picogame = false +picogame3d = false +ps2io = false +pulseio = false +pwmio = false +qrio = false +qspibus = false +rainbowio = true +random = true +rclcpy = false +rgbmatrix = false +rotaryio = true # Zephyr board has rotaryio +rtc = false +sdcardio = true # Zephyr board has busio +sdioio = false +sharpdisplay = true # Zephyr board has busio +socketpool = false +spitarget = false +ssl = false +storage = true +struct = true +supervisor = true +synthio = false +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio +time = true +touchio = true +traceback = true +uheap = false +usb = false +usb_audio = false +usb_cdc = true +usb_hid = true +usb_host = false +usb_host_audio = false +usb_host_bulk = false +usb_midi = false +usb_video = false +ustack = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog +wifi = false +zephyr_display = false +zephyr_input = false +zephyr_kernel = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/raspberrypi/rpi_pico2_zephyr/board.conf b/ports/zephyr-cp/boards/raspberrypi/rpi_pico2_zephyr/board.conf new file mode 100644 index 00000000000..e4fd5782295 --- /dev/null +++ b/ports/zephyr-cp/boards/raspberrypi/rpi_pico2_zephyr/board.conf @@ -0,0 +1,4 @@ +# No Zephyr UART console by default (see board.overlay); a CONSOLE=1 build turns +# it back on in console.conf. +CONFIG_UART_CONSOLE=n +CONFIG_LOG_BACKEND_UART=n diff --git a/ports/zephyr-cp/boards/raspberrypi/rpi_pico2_zephyr/board.overlay b/ports/zephyr-cp/boards/raspberrypi/rpi_pico2_zephyr/board.overlay new file mode 100644 index 00000000000..f68c98e5aec --- /dev/null +++ b/ports/zephyr-cp/boards/raspberrypi/rpi_pico2_zephyr/board.overlay @@ -0,0 +1,12 @@ +/* Partition layout is owned by the mcuboot fork (dts/raspberrypi/rpi_pico2.dtsi) + * and applied to this image by sysbuild. This overlay only adds board/app config. */ +#include "../../../app.overlay" + +/* No Zephyr console by default, so GP0/GP1 (UART0) are free for busio.UART. A + * CONSOLE=1 build puts the console back on UART0 (console.overlay). */ +/ { + chosen { + /delete-property/ zephyr,console; + /delete-property/ zephyr,shell-uart; + }; +}; diff --git a/ports/zephyr-cp/boards/raspberrypi/rpi_pico2_zephyr/circuitpython.toml b/ports/zephyr-cp/boards/raspberrypi/rpi_pico2_zephyr/circuitpython.toml new file mode 100644 index 00000000000..0af0548a67c --- /dev/null +++ b/ports/zephyr-cp/boards/raspberrypi/rpi_pico2_zephyr/circuitpython.toml @@ -0,0 +1,9 @@ +CIRCUITPY_BUILD_EXTENSIONS = ["hex", "uf2"] +USB_VID=0x2E8A +USB_PID=0x000B +NAME="Pico 2" +VENDOR="Raspberry Pi" +USB_MANUFACTURER="Raspberry Pi" + +# Non-Zephyr build of the same board; nvm and CIRCUITPY must sit where it puts them. +counterpart = "raspberrypi/raspberry_pi_pico2" diff --git a/ports/zephyr-cp/boards/raspberrypi/rpi_pico2_zephyr/console.overlay b/ports/zephyr-cp/boards/raspberrypi/rpi_pico2_zephyr/console.overlay new file mode 100644 index 00000000000..e9fe53dd84f --- /dev/null +++ b/ports/zephyr-cp/boards/raspberrypi/rpi_pico2_zephyr/console.overlay @@ -0,0 +1,9 @@ +/* Applied after board.overlay in CONSOLE=1 and DEBUG=1 builds: the Zephyr + * console on UART0, on GP0 (TX) and GP1 (RX). GP0/GP1 are then not + * available to busio.UART. */ +/ { + chosen { + zephyr,console = &uart0; + zephyr,shell-uart = &uart0; + }; +}; diff --git a/ports/zephyr-cp/boards/raspberrypi/rpi_pico_w_zephyr/autogen_board_info.toml b/ports/zephyr-cp/boards/raspberrypi/rpi_pico_w_zephyr/autogen_board_info.toml new file mode 100644 index 00000000000..d0f14614912 --- /dev/null +++ b/ports/zephyr-cp/boards/raspberrypi/rpi_pico_w_zephyr/autogen_board_info.toml @@ -0,0 +1,145 @@ +# This file is autogenerated when a board is built. Do not edit. Do commit it to git. Other scripts use its info. +name = "Raspberry Pi Pico W" + +[modules] +__future__ = true +_airlift = false +_bleio = false +_eve = false +_pew = false +_pixelmap = false +_stage = false +adafruit_bus_device = true +adafruit_pixelbuf = false +aesio = true +alarm = false +analogbufio = false +analogio = false +async_spi = true # Zephyr board has async_spi +atexit = true +audiobusio = false +audiocore = false +audiodelays = false +audiofilewriter = false +audiofilters = false +audiofreeverb = false +audioi2sin = false +audioio = false +audiomixer = false +audiomp3 = false +audiopwmio = false +audiospeed = false +audiotap = false +aurora_epaper = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio +bitops = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio +camera = false +canio = false +codeop = true +countio = false +cryptography = false +digitalio = true +displayio = true # Zephyr board has busio +dotclockframebuffer = false +dualbank = false +emmcio = false +epaperdisplay = true # Zephyr board has busio +floppyio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio +frequencyio = false +getpass = true +gifio = true # Zephyr board has busio +gnss = false +hardwarekey = false +hashlib = true # Zephyr networking enabled +hmac = false +hostnetwork = false +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false +i2ctarget = false +imagecapture = false +ipaddress = true # Zephyr networking enabled +is31fl3741 = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true +max3421e = false +mcp4822 = false +mdns = false +memorymap = false +memorymonitor = false +microcontroller = true +mii = false +mipicsi = false +mipidsi = false +msgpack = true +neopixel_write = false +nvm = true # Board has NVM partition +onewireio = false +os = true +paralleldisplaybus = false +picogame = false +picogame3d = false +ps2io = false +pulseio = false +pwmio = false +qrio = false +qspibus = false +rainbowio = true +random = true +rclcpy = false +rgbmatrix = false +rotaryio = true # Zephyr board has rotaryio +rtc = true # Zephyr board has rtc +sdcardio = true # Zephyr board has busio +sdioio = false +sharpdisplay = true # Zephyr board has busio +socketpool = true # Zephyr networking enabled +spitarget = false +ssl = true # Zephyr wifi enabled +storage = true +struct = true +supervisor = true +synthio = false +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio +time = true +touchio = true +traceback = true +uheap = false +usb = false +usb_audio = false +usb_cdc = true +usb_hid = true +usb_host = false +usb_host_audio = false +usb_host_bulk = false +usb_midi = false +usb_video = false +ustack = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog +wifi = true # Zephyr board has wifi +zephyr_display = false +zephyr_input = false +zephyr_kernel = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/raspberrypi/rpi_pico_w_zephyr/board.conf b/ports/zephyr-cp/boards/raspberrypi/rpi_pico_w_zephyr/board.conf new file mode 100644 index 00000000000..0ce053aa190 --- /dev/null +++ b/ports/zephyr-cp/boards/raspberrypi/rpi_pico_w_zephyr/board.conf @@ -0,0 +1,27 @@ +CONFIG_NETWORKING=y +CONFIG_NET_IPV4=y +CONFIG_NET_DHCPV4=y +CONFIG_NET_SOCKETS=y + +CONFIG_WIFI=y +CONFIG_WIFI_NM_WPA_SUPPLICANT_LEGACY_CRYPTO=n +CONFIG_NET_L2_WIFI_MGMT=y +CONFIG_NET_MGMT_EVENT=y +CONFIG_NET_MGMT_EVENT_INFO=y + +CONFIG_NET_HOSTNAME_ENABLE=y +CONFIG_NET_HOSTNAME_DYNAMIC=y +CONFIG_NET_HOSTNAME="circuitpython" + +CONFIG_MBEDTLS=y +# Allocate PSA key material with malloc() instead of 38 KB of static slots. +CONFIG_MBEDTLS_PSA_STATIC_KEY_SLOTS=n +# Keep the AES tables in flash instead of copying 8 KB of them into RAM. +CONFIG_MBEDTLS_AES_ROM_TABLES=y + +CONFIG_TEST_RANDOM_GENERATOR=y + +# No Zephyr UART console by default (see board.overlay); a CONSOLE=1 build turns +# it back on in console.conf. +CONFIG_UART_CONSOLE=n +CONFIG_LOG_BACKEND_UART=n diff --git a/ports/zephyr-cp/boards/raspberrypi/rpi_pico_w_zephyr/board.overlay b/ports/zephyr-cp/boards/raspberrypi/rpi_pico_w_zephyr/board.overlay new file mode 100644 index 00000000000..c9a33ed07cc --- /dev/null +++ b/ports/zephyr-cp/boards/raspberrypi/rpi_pico_w_zephyr/board.overlay @@ -0,0 +1,12 @@ +/* Partition layout is owned by the mcuboot fork (dts/raspberrypi/rpi_pico.dtsi) + * and applied to this image by sysbuild. This overlay only adds board/app config. */ +#include "../../../app.overlay" + +/* No Zephyr console by default, so GP0/GP1 (UART0) are free for busio.UART. A + * CONSOLE=1 build puts the console back on UART0 (console.overlay). */ +/ { + chosen { + /delete-property/ zephyr,console; + /delete-property/ zephyr,shell-uart; + }; +}; diff --git a/ports/zephyr-cp/boards/raspberrypi/rpi_pico_w_zephyr/circuitpython.toml b/ports/zephyr-cp/boards/raspberrypi/rpi_pico_w_zephyr/circuitpython.toml new file mode 100644 index 00000000000..3cff93205bc --- /dev/null +++ b/ports/zephyr-cp/boards/raspberrypi/rpi_pico_w_zephyr/circuitpython.toml @@ -0,0 +1,10 @@ +CIRCUITPY_BUILD_EXTENSIONS = ["hex", "uf2"] +USB_VID=0x239A +USB_PID=0x8120 +BLOBS=["hal_infineon"] +NAME="Pico W" +VENDOR="Raspberry Pi" +USB_MANUFACTURER="Raspberry Pi" + +# Non-Zephyr build of the same board; nvm and CIRCUITPY must sit where it puts them. +counterpart = "raspberrypi/raspberry_pi_pico_w" diff --git a/ports/zephyr-cp/boards/raspberrypi/rpi_pico_w_zephyr/console.overlay b/ports/zephyr-cp/boards/raspberrypi/rpi_pico_w_zephyr/console.overlay new file mode 100644 index 00000000000..e9fe53dd84f --- /dev/null +++ b/ports/zephyr-cp/boards/raspberrypi/rpi_pico_w_zephyr/console.overlay @@ -0,0 +1,9 @@ +/* Applied after board.overlay in CONSOLE=1 and DEBUG=1 builds: the Zephyr + * console on UART0, on GP0 (TX) and GP1 (RX). GP0/GP1 are then not + * available to busio.UART. */ +/ { + chosen { + zephyr,console = &uart0; + zephyr,shell-uart = &uart0; + }; +}; diff --git a/ports/zephyr-cp/boards/raspberrypi/rpi_pico_zephyr/autogen_board_info.toml b/ports/zephyr-cp/boards/raspberrypi/rpi_pico_zephyr/autogen_board_info.toml new file mode 100644 index 00000000000..c32cbed1b83 --- /dev/null +++ b/ports/zephyr-cp/boards/raspberrypi/rpi_pico_zephyr/autogen_board_info.toml @@ -0,0 +1,145 @@ +# This file is autogenerated when a board is built. Do not edit. Do commit it to git. Other scripts use its info. +name = "Raspberry Pi Pico" + +[modules] +__future__ = true +_airlift = false +_bleio = false +_eve = false +_pew = false +_pixelmap = false +_stage = false +adafruit_bus_device = true +adafruit_pixelbuf = false +aesio = true +alarm = false +analogbufio = false +analogio = false +async_spi = true # Zephyr board has async_spi +atexit = true +audiobusio = false +audiocore = false +audiodelays = false +audiofilewriter = false +audiofilters = false +audiofreeverb = false +audioi2sin = false +audioio = false +audiomixer = false +audiomp3 = false +audiopwmio = false +audiospeed = false +audiotap = false +aurora_epaper = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio +bitops = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio +camera = false +canio = false +codeop = true +countio = false +cryptography = false +digitalio = true +displayio = true # Zephyr board has busio +dotclockframebuffer = false +dualbank = false +emmcio = false +epaperdisplay = true # Zephyr board has busio +floppyio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio +frequencyio = false +getpass = true +gifio = true # Zephyr board has busio +gnss = false +hardwarekey = false +hashlib = true +hmac = false +hostnetwork = false +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false +i2ctarget = false +imagecapture = false +ipaddress = false +is31fl3741 = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true +max3421e = false +mcp4822 = false +mdns = false +memorymap = false +memorymonitor = false +microcontroller = true +mii = false +mipicsi = false +mipidsi = false +msgpack = true +neopixel_write = false +nvm = true # Board has NVM partition +onewireio = false +os = true +paralleldisplaybus = false +picogame = false +picogame3d = false +ps2io = false +pulseio = false +pwmio = false +qrio = false +qspibus = false +rainbowio = true +random = true +rclcpy = false +rgbmatrix = false +rotaryio = true # Zephyr board has rotaryio +rtc = true # Zephyr board has rtc +sdcardio = true # Zephyr board has busio +sdioio = false +sharpdisplay = true # Zephyr board has busio +socketpool = false +spitarget = false +ssl = false +storage = true +struct = true +supervisor = true +synthio = false +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio +time = true +touchio = true +traceback = true +uheap = false +usb = false +usb_audio = false +usb_cdc = true +usb_hid = true +usb_host = false +usb_host_audio = false +usb_host_bulk = false +usb_midi = false +usb_video = false +ustack = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog +wifi = false +zephyr_display = false +zephyr_input = false +zephyr_kernel = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/raspberrypi/rpi_pico_zephyr/board.conf b/ports/zephyr-cp/boards/raspberrypi/rpi_pico_zephyr/board.conf new file mode 100644 index 00000000000..e4fd5782295 --- /dev/null +++ b/ports/zephyr-cp/boards/raspberrypi/rpi_pico_zephyr/board.conf @@ -0,0 +1,4 @@ +# No Zephyr UART console by default (see board.overlay); a CONSOLE=1 build turns +# it back on in console.conf. +CONFIG_UART_CONSOLE=n +CONFIG_LOG_BACKEND_UART=n diff --git a/ports/zephyr-cp/boards/raspberrypi/rpi_pico_zephyr/board.overlay b/ports/zephyr-cp/boards/raspberrypi/rpi_pico_zephyr/board.overlay new file mode 100644 index 00000000000..c9a33ed07cc --- /dev/null +++ b/ports/zephyr-cp/boards/raspberrypi/rpi_pico_zephyr/board.overlay @@ -0,0 +1,12 @@ +/* Partition layout is owned by the mcuboot fork (dts/raspberrypi/rpi_pico.dtsi) + * and applied to this image by sysbuild. This overlay only adds board/app config. */ +#include "../../../app.overlay" + +/* No Zephyr console by default, so GP0/GP1 (UART0) are free for busio.UART. A + * CONSOLE=1 build puts the console back on UART0 (console.overlay). */ +/ { + chosen { + /delete-property/ zephyr,console; + /delete-property/ zephyr,shell-uart; + }; +}; diff --git a/ports/zephyr-cp/boards/raspberrypi/rpi_pico_zephyr/circuitpython.toml b/ports/zephyr-cp/boards/raspberrypi/rpi_pico_zephyr/circuitpython.toml new file mode 100644 index 00000000000..57b1151d7bd --- /dev/null +++ b/ports/zephyr-cp/boards/raspberrypi/rpi_pico_zephyr/circuitpython.toml @@ -0,0 +1,9 @@ +CIRCUITPY_BUILD_EXTENSIONS = ["hex", "uf2"] +USB_VID=0x239A +USB_PID=0x80F4 +NAME="Pico" +VENDOR="Raspberry Pi" +USB_MANUFACTURER="Raspberry Pi" + +# Non-Zephyr build of the same board; nvm and CIRCUITPY must sit where it puts them. +counterpart = "raspberrypi/raspberry_pi_pico" diff --git a/ports/zephyr-cp/boards/raspberrypi/rpi_pico_zephyr/console.overlay b/ports/zephyr-cp/boards/raspberrypi/rpi_pico_zephyr/console.overlay new file mode 100644 index 00000000000..e9fe53dd84f --- /dev/null +++ b/ports/zephyr-cp/boards/raspberrypi/rpi_pico_zephyr/console.overlay @@ -0,0 +1,9 @@ +/* Applied after board.overlay in CONSOLE=1 and DEBUG=1 builds: the Zephyr + * console on UART0, on GP0 (TX) and GP1 (RX). GP0/GP1 are then not + * available to busio.UART. */ +/ { + chosen { + zephyr,console = &uart0; + zephyr,shell-uart = &uart0; + }; +}; diff --git a/ports/zephyr-cp/boards/renesas/da14695_dk_usb/autogen_board_info.toml b/ports/zephyr-cp/boards/renesas/da14695_dk_usb/autogen_board_info.toml new file mode 100644 index 00000000000..bce95f961db --- /dev/null +++ b/ports/zephyr-cp/boards/renesas/da14695_dk_usb/autogen_board_info.toml @@ -0,0 +1,145 @@ +# This file is autogenerated when a board is built. Do not edit. Do commit it to git. Other scripts use its info. +name = "Renesas Electronics Corporation DA14695 Development Kit USB" + +[modules] +__future__ = true +_airlift = false +_bleio = true # Zephyr board has _bleio +_eve = false +_pew = false +_pixelmap = false +_stage = false +adafruit_bus_device = true +adafruit_pixelbuf = false +aesio = true +alarm = false +analogbufio = false +analogio = false +async_spi = false +atexit = true +audiobusio = false +audiocore = false +audiodelays = false +audiofilewriter = false +audiofilters = false +audiofreeverb = false +audioi2sin = false +audioio = false +audiomixer = false +audiomp3 = false +audiopwmio = false +audiospeed = false +audiotap = false +aurora_epaper = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio +bitops = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio +camera = false +canio = false +codeop = true +countio = false +cryptography = false +digitalio = true +displayio = true # Zephyr board has busio +dotclockframebuffer = false +dualbank = false +emmcio = false +epaperdisplay = true # Zephyr board has busio +floppyio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio +frequencyio = false +getpass = true +gifio = true # Zephyr board has busio +gnss = false +hardwarekey = false +hashlib = true +hmac = false +hostnetwork = false +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false +i2ctarget = false +imagecapture = false +ipaddress = false +is31fl3741 = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true +max3421e = false +mcp4822 = false +mdns = false +memorymap = false +memorymonitor = false +microcontroller = true +mii = false +mipicsi = false +mipidsi = false +msgpack = true +neopixel_write = false +nvm = true # Board has NVM partition +onewireio = false +os = true +paralleldisplaybus = false +picogame = false +picogame3d = false +ps2io = false +pulseio = false +pwmio = false +qrio = false +qspibus = false +rainbowio = true +random = true +rclcpy = false +rgbmatrix = false +rotaryio = true # Zephyr board has rotaryio +rtc = false +sdcardio = true # Zephyr board has busio +sdioio = false +sharpdisplay = true # Zephyr board has busio +socketpool = false +spitarget = false +ssl = false +storage = true +struct = true +supervisor = true +synthio = false +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio +time = true +touchio = true +traceback = true +uheap = false +usb = false +usb_audio = false +usb_cdc = true +usb_hid = true +usb_host = false +usb_host_audio = false +usb_host_bulk = false +usb_midi = false +usb_video = false +ustack = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog +wifi = false +zephyr_display = false +zephyr_input = true # Zephyr board has zephyr_input +zephyr_kernel = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/renesas/da14695_dk_usb/board.overlay b/ports/zephyr-cp/boards/renesas/da14695_dk_usb/board.overlay new file mode 100644 index 00000000000..cb054681fa5 --- /dev/null +++ b/ports/zephyr-cp/boards/renesas/da14695_dk_usb/board.overlay @@ -0,0 +1,2 @@ + +#include "../../../app.overlay" diff --git a/ports/zephyr-cp/boards/renesas/da14695_dk_usb/circuitpython.toml b/ports/zephyr-cp/boards/renesas/da14695_dk_usb/circuitpython.toml new file mode 100644 index 00000000000..60a5b67efb9 --- /dev/null +++ b/ports/zephyr-cp/boards/renesas/da14695_dk_usb/circuitpython.toml @@ -0,0 +1,2 @@ +CIRCUITPY_BUILD_EXTENSIONS = ["hex", "uf2", "signed.bin"] +BLOBS=["hal_renesas"] diff --git a/ports/zephyr-cp/boards/renesas/ek_ra6m5/autogen_board_info.toml b/ports/zephyr-cp/boards/renesas/ek_ra6m5/autogen_board_info.toml index 674a19ab107..aa31397ddf2 100644 --- a/ports/zephyr-cp/boards/renesas/ek_ra6m5/autogen_board_info.toml +++ b/ports/zephyr-cp/boards/renesas/ek_ra6m5/autogen_board_info.toml @@ -2,110 +2,144 @@ name = "Renesas Electronics Corporation RA6M5 Evaluation Kit" [modules] -__future__ = false +__future__ = true +_airlift = false _bleio = false _eve = false _pew = false _pixelmap = false _stage = false -adafruit_bus_device = false +adafruit_bus_device = true adafruit_pixelbuf = false -aesio = false +aesio = true alarm = false analogbufio = false analogio = false -atexit = false +async_spi = true # Zephyr board has async_spi +atexit = true audiobusio = false audiocore = false audiodelays = false +audiofilewriter = false audiofilters = false +audiofreeverb = false +audioi2sin = false audioio = false audiomixer = false audiomp3 = false audiopwmio = false +audiospeed = false +audiotap = false aurora_epaper = false -bitbangio = false -bitmapfilter = false -bitmaptools = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio bitops = false -board = false -busdisplay = false -busio = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio camera = false canio = false -codeop = false +codeop = true countio = false +cryptography = false digitalio = true -displayio = false +displayio = true # Zephyr board has busio dotclockframebuffer = false dualbank = false -epaperdisplay = false +emmcio = false +epaperdisplay = true # Zephyr board has busio floppyio = false -fontio = false -fourwire = false -framebufferio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio frequencyio = false -getpass = false -gifio = false +getpass = true +gifio = true # Zephyr board has busio gnss = false -hashlib = false -i2cdisplaybus = false +hardwarekey = false +hashlib = true # Zephyr networking enabled +hmac = false +hostnetwork = false +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false i2ctarget = false imagecapture = false -ipaddress = false +ipaddress = true # Zephyr networking enabled is31fl3741 = false -jpegio = false -keypad = false -keypad_demux = false -locale = false -math = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true max3421e = false +mcp4822 = false mdns = false memorymap = false memorymonitor = false microcontroller = true -msgpack = false +mii = true # Zephyr board has ethernet +mipicsi = false +mipidsi = false +msgpack = true neopixel_write = false -nvm = false +nvm = true # Board has NVM partition onewireio = false os = true paralleldisplaybus = false +picogame = false +picogame3d = false ps2io = false pulseio = false pwmio = false qrio = false -rainbowio = false +qspibus = false +rainbowio = true random = true +rclcpy = false rgbmatrix = false -rotaryio = false +rotaryio = true # Zephyr board has rotaryio rtc = false -sdcardio = false +sdcardio = true # Zephyr board has busio sdioio = false -sharpdisplay = false -socketpool = false +sharpdisplay = true # Zephyr board has busio +socketpool = true # Zephyr networking enabled spitarget = false -ssl = false +ssl = true # Zephyr ethernet enabled storage = true # Zephyr board has flash struct = true -supervisor = false +supervisor = true synthio = false -terminalio = false -tilepalettemapper = false +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio time = true -touchio = false -traceback = false +touchio = true +traceback = true uheap = false usb = false -usb_cdc = false # No TinyUSB settings for r7fa6m5bh3cfc -usb_hid = false +usb_audio = false +usb_cdc = true +usb_hid = true usb_host = false +usb_host_audio = false +usb_host_bulk = false usb_midi = false usb_video = false ustack = false -vectorio = false -warnings = false -watchdog = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog wifi = false +zephyr_display = false +zephyr_input = true # Zephyr board has zephyr_input zephyr_kernel = false -zephyr_serial = true -zlib = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/renesas/ek_ra6m5/board.conf b/ports/zephyr-cp/boards/renesas/ek_ra6m5/board.conf new file mode 100644 index 00000000000..e69de29bb2d diff --git a/ports/zephyr-cp/boards/renesas/ek_ra6m5/board.overlay b/ports/zephyr-cp/boards/renesas/ek_ra6m5/board.overlay new file mode 100644 index 00000000000..c626ea5ae04 --- /dev/null +++ b/ports/zephyr-cp/boards/renesas/ek_ra6m5/board.overlay @@ -0,0 +1,28 @@ +/* This board boots via the Adaboot MCUboot fork. Its + * bootloader/mcuboot/dts/renesas/ek_ra6m5.dtsi owns the partition layout + * (boot, slot0 and storage on the internal code flash, nvm on the data + * flash) and is applied to both the bootloader and the application image + * by sysbuild, so no partition definitions belong here. CIRCUITPY gets the + * fatfs_partition the layout carves from the 32 MB QSPI NOR (mx25l25645g). + * + * Disable OFS (Option Function Select) nodes so their high-address + * sections don't end up in the app HEX. MCUboot's own build still has + * them, so the merged HEX programs OFS correctly. + */ +&option_setting_ofs0 { status = "disabled"; }; +&option_setting_dualsel { status = "disabled"; }; +&option_setting_ofs1_sec { status = "disabled"; }; +&option_setting_banksel_sec { status = "disabled"; }; +&option_setting_bps_sec { status = "disabled"; }; +&option_setting_pbps_sec { status = "disabled"; }; +&option_setting_ofs1_sel { status = "disabled"; }; +&option_setting_banksel_sel { status = "disabled"; }; +&option_setting_bps_sel { status = "disabled"; }; + +/* The RA WDT driver (r_wdt.c) doesn't build for RA6M5: it uses + * BSP_CFG_OPTION_SETTING_OFS0, which the RA6M5 BSP config doesn't define. + * Disable the wdt node so the driver isn't enabled and the watchdog module + * stays off. */ +&wdt { status = "disabled"; }; + +#include "../../../app.overlay" diff --git a/ports/zephyr-cp/boards/renesas/ek_ra6m5/circuitpython.toml b/ports/zephyr-cp/boards/renesas/ek_ra6m5/circuitpython.toml index 3272dd4c5f3..a741a9bfbdf 100644 --- a/ports/zephyr-cp/boards/renesas/ek_ra6m5/circuitpython.toml +++ b/ports/zephyr-cp/boards/renesas/ek_ra6m5/circuitpython.toml @@ -1 +1,3 @@ -CIRCUITPY_BUILD_EXTENSIONS = ["elf"] +# TX is on pin P411. RX is on pin P410. + +CIRCUITPY_BUILD_EXTENSIONS = ["hex", "uf2"] diff --git a/ports/zephyr-cp/boards/renesas/ek_ra8d1/autogen_board_info.toml b/ports/zephyr-cp/boards/renesas/ek_ra8d1/autogen_board_info.toml index 4f920c59f11..8e1fa8de6b0 100644 --- a/ports/zephyr-cp/boards/renesas/ek_ra8d1/autogen_board_info.toml +++ b/ports/zephyr-cp/boards/renesas/ek_ra8d1/autogen_board_info.toml @@ -2,110 +2,144 @@ name = "Renesas Electronics Corporation RA8D1 Evaluation Kit" [modules] -__future__ = false +__future__ = true +_airlift = false _bleio = false _eve = false _pew = false _pixelmap = false _stage = false -adafruit_bus_device = false +adafruit_bus_device = true adafruit_pixelbuf = false -aesio = false +aesio = true alarm = false analogbufio = false -analogio = false -atexit = false +analogio = true # Zephyr board has analogio +async_spi = true # Zephyr board has async_spi +atexit = true audiobusio = false audiocore = false audiodelays = false +audiofilewriter = false audiofilters = false +audiofreeverb = false +audioi2sin = false audioio = false audiomixer = false audiomp3 = false audiopwmio = false +audiospeed = false +audiotap = false aurora_epaper = false -bitbangio = false -bitmapfilter = false -bitmaptools = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio bitops = false -board = false -busdisplay = false -busio = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio camera = false canio = false -codeop = false +codeop = true countio = false +cryptography = false digitalio = true -displayio = false +displayio = true # Zephyr board has displayio dotclockframebuffer = false dualbank = false -epaperdisplay = false +emmcio = false +epaperdisplay = true # Zephyr board has busio floppyio = false -fontio = false -fourwire = false -framebufferio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio frequencyio = false -getpass = false -gifio = false +getpass = true +gifio = true # Zephyr board has busio gnss = false -hashlib = false -i2cdisplaybus = false +hardwarekey = false +hashlib = true # Zephyr networking enabled +hmac = false +hostnetwork = false +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false i2ctarget = false imagecapture = false -ipaddress = false +ipaddress = true # Zephyr networking enabled is31fl3741 = false -jpegio = false -keypad = false -keypad_demux = false -locale = false -math = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true max3421e = false +mcp4822 = false mdns = false memorymap = false memorymonitor = false microcontroller = true -msgpack = false +mii = true # Zephyr board has ethernet +mipicsi = false +mipidsi = false +msgpack = true neopixel_write = false -nvm = false +nvm = true # Board has NVM partition onewireio = false os = true paralleldisplaybus = false +picogame = false +picogame3d = false ps2io = false pulseio = false pwmio = false qrio = false -rainbowio = false +qspibus = false +rainbowio = true random = true +rclcpy = false rgbmatrix = false -rotaryio = false +rotaryio = true # Zephyr board has rotaryio rtc = false -sdcardio = false +sdcardio = true # Zephyr board has busio sdioio = false -sharpdisplay = false -socketpool = false +sharpdisplay = true # Zephyr board has busio +socketpool = true # Zephyr networking enabled spitarget = false -ssl = false +ssl = true # Zephyr ethernet enabled storage = true # Zephyr board has flash struct = true -supervisor = false +supervisor = true synthio = false -terminalio = false -tilepalettemapper = false +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio time = true -touchio = false -traceback = false +touchio = true +traceback = true uheap = false usb = false -usb_cdc = false # No TinyUSB settings for r7fa8d1bhecbd -usb_hid = false +usb_audio = false +usb_cdc = true +usb_hid = true usb_host = false +usb_host_audio = false +usb_host_bulk = false usb_midi = false usb_video = false ustack = false -vectorio = false -warnings = false -watchdog = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog wifi = false +zephyr_display = true # Zephyr board has zephyr_display +zephyr_input = true # Zephyr board has zephyr_input zephyr_kernel = false -zephyr_serial = true -zlib = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/renesas/ek_ra8d1/board.conf b/ports/zephyr-cp/boards/renesas/ek_ra8d1/board.conf new file mode 100644 index 00000000000..c0f2ad0718b --- /dev/null +++ b/ports/zephyr-cp/boards/renesas/ek_ra8d1/board.conf @@ -0,0 +1,17 @@ +# Enable Zephyr display subsystem so DT chosen zephyr,display creates a device. +CONFIG_DISPLAY=y + +# RA8 USB can generate bursts of UDC/USBD events (especially with HS + MSC). +# Keep queues/buffers larger to avoid dropped events that can desynchronize +# control-transfer state (e.g. "udc: Cannot determine the next stage"). +CONFIG_UDC_RENESAS_RA_MAX_QMESSAGES=32 +CONFIG_USBD_MAX_UDC_MSG=32 +CONFIG_USBD_MSG_SLAB_COUNT=32 +CONFIG_UDC_BUF_COUNT=32 +CONFIG_UDC_BUF_POOL_SIZE=2048 + +# ADC0 is on the mikroBUS AN pin (P0.04); analogio resolves pads to their +# fixed channels through iobroker. The board dts also enables dac0, whose +# fixed-per-SoC output pad (P0.14) iobroker applies analog enable on. +CONFIG_ADC=y +CONFIG_DAC=y diff --git a/ports/zephyr-cp/boards/renesas/ek_ra8d1/board.overlay b/ports/zephyr-cp/boards/renesas/ek_ra8d1/board.overlay new file mode 100644 index 00000000000..f15674142d5 --- /dev/null +++ b/ports/zephyr-cp/boards/renesas/ek_ra8d1/board.overlay @@ -0,0 +1,23 @@ + +/* Disable OFS (Option Function Select) nodes so their high-address + * sections don't end up in the app HEX. MCUboot's own build still + * has them, so the merged HEX programs OFS correctly. + */ +&option_setting_ofs0 { status = "disabled"; }; +&option_setting_ofs2 { status = "disabled"; }; +&option_setting_dualsel { status = "disabled"; }; +&option_setting_ofs1_sec { status = "disabled"; }; +&option_setting_banksel_sec { status = "disabled"; }; +&option_setting_bps_sec { status = "disabled"; }; +&option_setting_pbps_sec { status = "disabled"; }; +&option_setting_ofs1_sel { status = "disabled"; }; +&option_setting_banksel_sel { status = "disabled"; }; +&option_setting_bps_sel { status = "disabled"; }; + +/* The RA WDT driver (r_wdt.c) doesn't build for RA8D1 either: it needs + * BSP_CFG_OPTION_SETTING_OFS0, which the RA8D1 BSP config doesn't define. + * Disable the wdt node so the driver isn't enabled and the watchdog module + * stays off. */ +&wdt { status = "disabled"; }; + +#include "../../../app.overlay" diff --git a/ports/zephyr-cp/boards/renesas/ek_ra8d1/circuitpython.toml b/ports/zephyr-cp/boards/renesas/ek_ra8d1/circuitpython.toml index 3272dd4c5f3..21b7c923ebe 100644 --- a/ports/zephyr-cp/boards/renesas/ek_ra8d1/circuitpython.toml +++ b/ports/zephyr-cp/boards/renesas/ek_ra8d1/circuitpython.toml @@ -1 +1,2 @@ -CIRCUITPY_BUILD_EXTENSIONS = ["elf"] +CIRCUITPY_BUILD_EXTENSIONS = ["hex", "uf2"] +SHIELDS = ["rtkmipilcdb00000be"] diff --git a/ports/zephyr-cp/boards/silabs/siwx917_dk2605a/autogen_board_info.toml b/ports/zephyr-cp/boards/silabs/siwx917_dk2605a/autogen_board_info.toml new file mode 100644 index 00000000000..e41e2687beb --- /dev/null +++ b/ports/zephyr-cp/boards/silabs/siwx917_dk2605a/autogen_board_info.toml @@ -0,0 +1,145 @@ +# This file is autogenerated when a board is built. Do not edit. Do commit it to git. Other scripts use its info. +name = "Silicon Labs SiWx917 Wi-Fi 6 and Bluetooth LE SoC Dev Kit (BRD2605A)" + +[modules] +__future__ = true +_airlift = false +_bleio = true # Zephyr board has _bleio +_eve = false +_pew = false +_pixelmap = false +_stage = false +adafruit_bus_device = true +adafruit_pixelbuf = false +aesio = true +alarm = false +analogbufio = false +analogio = false +async_spi = true # Zephyr board has async_spi +atexit = true +audiobusio = false +audiocore = false +audiodelays = false +audiofilewriter = false +audiofilters = false +audiofreeverb = false +audioi2sin = false +audioio = false +audiomixer = false +audiomp3 = false +audiopwmio = false +audiospeed = false +audiotap = false +aurora_epaper = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio +bitops = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio +camera = false +canio = false +codeop = true +countio = false +cryptography = false +digitalio = true +displayio = true # Zephyr board has busio +dotclockframebuffer = false +dualbank = false +emmcio = false +epaperdisplay = true # Zephyr board has busio +floppyio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio +frequencyio = false +getpass = true +gifio = true # Zephyr board has busio +gnss = false +hardwarekey = false +hashlib = true # Zephyr networking enabled +hmac = false +hostnetwork = false +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false +i2ctarget = false +imagecapture = false +ipaddress = true # Zephyr networking enabled +is31fl3741 = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true +max3421e = false +mcp4822 = false +mdns = false +memorymap = false +memorymonitor = false +microcontroller = true +mii = false +mipicsi = false +mipidsi = false +msgpack = true +neopixel_write = false +nvm = true # Board has NVM partition +onewireio = false +os = true +paralleldisplaybus = false +picogame = false +picogame3d = false +ps2io = false +pulseio = false +pwmio = false +qrio = false +qspibus = false +rainbowio = true +random = true +rclcpy = false +rgbmatrix = false +rotaryio = true # Zephyr board has rotaryio +rtc = false +sdcardio = true # Zephyr board has busio +sdioio = false +sharpdisplay = true # Zephyr board has busio +socketpool = true # Zephyr networking enabled +spitarget = false +ssl = true # Zephyr wifi enabled +storage = true +struct = true +supervisor = true +synthio = false +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio +time = true +touchio = true +traceback = true +uheap = false +usb = false +usb_audio = false +usb_cdc = false +usb_hid = false +usb_host = false +usb_host_audio = false +usb_host_bulk = false +usb_midi = false +usb_video = false +ustack = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog +wifi = true # Zephyr board has wifi +zephyr_display = false +zephyr_input = true # Zephyr board has zephyr_input +zephyr_kernel = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/silabs/siwx917_dk2605a/board.conf b/ports/zephyr-cp/boards/silabs/siwx917_dk2605a/board.conf new file mode 100644 index 00000000000..a25ce7c7865 --- /dev/null +++ b/ports/zephyr-cp/boards/silabs/siwx917_dk2605a/board.conf @@ -0,0 +1,81 @@ +# The upstream board defconfig does not enable GPIO, so no gpio device structs +# are instantiated and the generated board.c fails to link. +CONFIG_GPIO=y + +# getaddrinfo() calls k_calloc(), which is compiled out when the kernel heap is +# zero-sized. prj.conf also draws thread stacks from this heap. +CONFIG_HEAP_MEM_POOL_SIZE=16384 + +CONFIG_NETWORKING=y +CONFIG_NET_IPV4=y +CONFIG_NET_DHCPV4=y +CONFIG_NET_SOCKETS=y + +# Not implied by the options above, and the siwx91x driver defaults to the +# native stack. Without it association and DHCP still work, since DHCP is UDP, +# while every SOCK_STREAM socket fails. +CONFIG_NET_TCP=y + +# dns_resolve_reconfigure() is additive by default: it fills free slots and +# stops when there are none, then still returns 0. With one server slot held by +# DHCP, assigning to radio.dns would install nothing and report success. This +# makes reconfigure rebuild the list instead, which is the replace semantics +# the binding implies by exposing dns as a settable Sequence[str]. +CONFIG_DNS_RECONFIGURE_CLEANUP=y + +# Zephyr's console (printk, boot banner, driver logs) goes to SEGGER RTT over +# the existing SWD connection rather than sharing the UART with the REPL, where +# net event printks interleave with and corrupt the REPL stream. CircuitPython's +# REPL is unaffected: supervisor/serial.c takes its device from +# DT_CHOSEN(zephyr_console) and drives it directly. +CONFIG_USE_SEGGER_RTT=y +CONFIG_RTT_CONSOLE=y +CONFIG_UART_CONSOLE=n + +CONFIG_WIFI=y +CONFIG_NET_L2_WIFI_MGMT=y +CONFIG_NET_MGMT_EVENT=y +CONFIG_NET_MGMT_EVENT_INFO=y + +# Answers .local and advertises services registered through +# mdns.Server.advertise_service(). Zephyr's responder is push-only, so +# mdns.Server.find() has nothing to search with yet. +CONFIG_MDNS_RESPONDER=y +CONFIG_DNS_SD=y +CONFIG_MDNS_RESPONDER_DNS_SD=y + +CONFIG_MBEDTLS_SSL_PROTO_TLS1_2=y +CONFIG_MBEDTLS_CIPHERSUITE_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256=y +CONFIG_MBEDTLS_ENTROPY_C=y +CONFIG_MBEDTLS_CTR_DRBG_C=y + +# BLE implies the p256-m secp256r1 driver; with it on, the additional curves +# wanted for TLS certificate chains (384/521, brainpool, k1, x25519) are +# unaccelerated, and tf-psa-crypto's driver-only-builds check rejects the +# resulting partial ECC acceleration. Disable the driver so every wanted curve +# uses the builtin implementation and the config check passes. +CONFIG_MBEDTLS_PSA_P256M_DRIVER_ENABLED=n + +# Long writes need at least one prepare slot. Zephyr's unconditional default of +# 0 rejects any write that does not fit a single ATT_WRITE_REQ, and only an +# explicit assignment here overrides it. +CONFIG_BT_ATT_PREPARE_COUNT=2 +# Zephyr splits the pool between BT_MAX_CONN connections, which would leave +# each one a single buffer. Let one connection use both, as before. +CONFIG_BT_ATT_PREPARE_COUNT_PER_CONN=2 + +# Zephyr's default preferred supervision timeout is 420ms, which the peripheral +# pushes onto the central shortly into every connection. That is thin on a +# single-antenna part whose network processor shares the radio with Wi-Fi. +# 400 = 4.0s, Apple's accessory guideline value. +CONFIG_BT_PERIPHERAL_PREF_MIN_INT=24 +CONFIG_BT_PERIPHERAL_PREF_MAX_INT=40 +CONFIG_BT_PERIPHERAL_PREF_LATENCY=0 +CONFIG_BT_PERIPHERAL_PREF_TIMEOUT=400 + +# The controller reports 15 ACL TX buffers while the host defaults to 3, which +# it warns about at boot. Match the host to the controller. +CONFIG_BT_BUF_ACL_TX_COUNT=15 + +# DMA for the GSPI controller, which serves the breakout pads. +CONFIG_DMA=y diff --git a/ports/zephyr-cp/boards/silabs/siwx917_dk2605a/board.overlay b/ports/zephyr-cp/boards/silabs/siwx917_dk2605a/board.overlay new file mode 100644 index 00000000000..4fd0ff10e3d --- /dev/null +++ b/ports/zephyr-cp/boards/silabs/siwx917_dk2605a/board.overlay @@ -0,0 +1,57 @@ +// Replaces the port's app.overlay, which does `&zephyr_udc0 { ... }` to add a +// CDC-ACM console. The SiWG917 has no USB device controller, so the console +// falls back to the Zephyr console on &ulpuart, reaching the host over the +// on-board J-Link VCOM. + +// GSPI on the breakout pads. The board .dts leaves spi0 disabled and wires +// nothing, so the pin assignment here is taken from the mapping Silicon Labs +// ships for this board in +// zephyr/tests/drivers/spi/spi_loopback/boards/siwx917_dk2605a.overlay: +// CLK on pad 3, MOSI on pad 5, MISO on pad 7, CS on gpiob 12. +// +// spi0 is the SoC's only SPI controller node and is compatible "silabs,gspi". +// The on-board IMU is on a separate ULP SPI bus that has no controller node in +// devicetree, so it is not reachable through this one. +&pinctrl0 { + spi0_default: spi0_default { + out { + pinmux = , ; + }; + + in { + pinmux = ; + }; + }; +}; + +&spi0 { + status = "okay"; + cs-gpios = <&gpiob 12 GPIO_ACTIVE_LOW>; + pinctrl-0 = <&spi0_default>; + pinctrl-names = "default"; + + dmas = <&gpdma 0 11>, <&gpdma 1 10>; + dma-names = "tx", "rx"; +}; + +&gpdma { + status = "okay"; +}; + +// 8 MB of PSRAM on the QSPI2 path. Present in ram_bounds; the Python heap does +// not use it yet. +&psram { + status = "okay"; +}; + +// Enable the SoC watchdog and expose it through the `watchdog0` alias +// (Zephyr's watchdog sample selection) for the watchdog module. +&watchdog { + status = "okay"; +}; + +/ { + aliases { + watchdog0 = &watchdog; + }; +}; diff --git a/ports/zephyr-cp/boards/silabs/siwx917_dk2605a/circuitpython.toml b/ports/zephyr-cp/boards/silabs/siwx917_dk2605a/circuitpython.toml new file mode 100644 index 00000000000..1f15a6f8349 --- /dev/null +++ b/ports/zephyr-cp/boards/silabs/siwx917_dk2605a/circuitpython.toml @@ -0,0 +1 @@ +CIRCUITPY_BUILD_EXTENSIONS = ["rps"] diff --git a/ports/zephyr-cp/boards/st/nucleo_n657x0_q/autogen_board_info.toml b/ports/zephyr-cp/boards/st/nucleo_n657x0_q/autogen_board_info.toml new file mode 100644 index 00000000000..5b3f5c4af48 --- /dev/null +++ b/ports/zephyr-cp/boards/st/nucleo_n657x0_q/autogen_board_info.toml @@ -0,0 +1,145 @@ +# This file is autogenerated when a board is built. Do not edit. Do commit it to git. Other scripts use its info. +name = "STMicroelectronics Nucleo N657X0-Q" + +[modules] +__future__ = true +_airlift = false +_bleio = false +_eve = false +_pew = false +_pixelmap = false +_stage = false +adafruit_bus_device = true +adafruit_pixelbuf = false +aesio = true +alarm = false +analogbufio = false +analogio = false +async_spi = true # Zephyr board has async_spi +atexit = true +audiobusio = false +audiocore = false +audiodelays = false +audiofilewriter = false +audiofilters = false +audiofreeverb = false +audioi2sin = false +audioio = false +audiomixer = false +audiomp3 = false +audiopwmio = false +audiospeed = false +audiotap = false +aurora_epaper = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio +bitops = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio +camera = false +canio = false +codeop = true +countio = false +cryptography = false +digitalio = true +displayio = true # Zephyr board has busio +dotclockframebuffer = false +dualbank = false +emmcio = false +epaperdisplay = true # Zephyr board has busio +floppyio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio +frequencyio = false +getpass = true +gifio = true # Zephyr board has busio +gnss = false +hardwarekey = false +hashlib = true # Zephyr networking enabled +hmac = false +hostnetwork = false +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false +i2ctarget = false +imagecapture = false +ipaddress = true # Zephyr networking enabled +is31fl3741 = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true +max3421e = false +mcp4822 = false +mdns = false +memorymap = false +memorymonitor = false +microcontroller = true +mii = true # Zephyr board has ethernet +mipicsi = false +mipidsi = false +msgpack = true +neopixel_write = false +nvm = true # Board has NVM partition +onewireio = false +os = true +paralleldisplaybus = false +picogame = false +picogame3d = false +ps2io = false +pulseio = false +pwmio = false +qrio = false +qspibus = false +rainbowio = true +random = true +rclcpy = false +rgbmatrix = false +rotaryio = true # Zephyr board has rotaryio +rtc = true # Zephyr board has rtc +sdcardio = true # Zephyr board has busio +sdioio = false +sharpdisplay = true # Zephyr board has busio +socketpool = true # Zephyr networking enabled +spitarget = false +ssl = true # Zephyr ethernet enabled +storage = true +struct = true +supervisor = true +synthio = false +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio +time = true +touchio = true +traceback = true +uheap = false +usb = false +usb_audio = false +usb_cdc = true +usb_hid = true +usb_host = false +usb_host_audio = false +usb_host_bulk = false +usb_midi = false +usb_video = false +ustack = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog +wifi = false +zephyr_display = false +zephyr_input = true # Zephyr board has zephyr_input +zephyr_kernel = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/st/nucleo_n657x0_q/board.conf b/ports/zephyr-cp/boards/st/nucleo_n657x0_q/board.conf new file mode 100644 index 00000000000..721df88a7fc --- /dev/null +++ b/ports/zephyr-cp/boards/st/nucleo_n657x0_q/board.conf @@ -0,0 +1,7 @@ +# The N6 has no internal flash and the upstream board defconfig sets XIP=n, +# linking the whole image into the RAMLOAD region, which is too small for +# CircuitPython ("Image is too large to fit RAMLOAD configuration"). The +# mcuboot fork's dts/st/nucleo_n657x0_q.dtsi points zephyr,flash at the +# memory-mapped XSPI NOR, so execute in place from the slot0 partition +# instead. +CONFIG_XIP=y diff --git a/ports/zephyr-cp/boards/st/nucleo_n657x0_q/board.overlay b/ports/zephyr-cp/boards/st/nucleo_n657x0_q/board.overlay new file mode 100644 index 00000000000..05c5775d9ac --- /dev/null +++ b/ports/zephyr-cp/boards/st/nucleo_n657x0_q/board.overlay @@ -0,0 +1,8 @@ +/* The USB device controller (zephyr_udc0), the XIP code flash (xip_flash) + * with its partition map, and the flash chosen properties are defined in the + * mcuboot fork's dts/st/nucleo_n657x0_q.dtsi, which sysbuild prepends to this + * image's overlays. app-partition.overlay then points + * zephyr,code-partition at slot0_partition. app.overlay only adds the CDC + * ACM console/data endpoints and the HID device. + */ +#include "../../../app.overlay" diff --git a/ports/zephyr-cp/boards/st/nucleo_n657x0_q/circuitpython.toml b/ports/zephyr-cp/boards/st/nucleo_n657x0_q/circuitpython.toml new file mode 100644 index 00000000000..87123c491f7 --- /dev/null +++ b/ports/zephyr-cp/boards/st/nucleo_n657x0_q/circuitpython.toml @@ -0,0 +1,5 @@ +CIRCUITPY_BUILD_EXTENSIONS = ["hex", "uf2"] + +# This part executes from RAM and is already at 93% of it, so it cannot +# absorb the roughly 90 KB ulab adds. +CIRCUITPY_ULAB = false diff --git a/ports/zephyr-cp/boards/st/nucleo_u575zi_q/autogen_board_info.toml b/ports/zephyr-cp/boards/st/nucleo_u575zi_q/autogen_board_info.toml index 000155eafa7..7fe019d1147 100644 --- a/ports/zephyr-cp/boards/st/nucleo_u575zi_q/autogen_board_info.toml +++ b/ports/zephyr-cp/boards/st/nucleo_u575zi_q/autogen_board_info.toml @@ -2,110 +2,144 @@ name = "STMicroelectronics Nucleo U575ZI Q" [modules] -__future__ = false +__future__ = true +_airlift = false _bleio = false _eve = false _pew = false _pixelmap = false _stage = false -adafruit_bus_device = false +adafruit_bus_device = true adafruit_pixelbuf = false -aesio = false +aesio = true alarm = false analogbufio = false analogio = false -atexit = false +async_spi = true # Zephyr board has async_spi +atexit = true audiobusio = false audiocore = false audiodelays = false +audiofilewriter = false audiofilters = false +audiofreeverb = false +audioi2sin = false audioio = false audiomixer = false audiomp3 = false audiopwmio = false +audiospeed = false +audiotap = false aurora_epaper = false -bitbangio = false -bitmapfilter = false -bitmaptools = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio bitops = false -board = false -busdisplay = false -busio = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio camera = false canio = false -codeop = false +codeop = true countio = false +cryptography = false digitalio = true -displayio = false +displayio = true # Zephyr board has busio dotclockframebuffer = false dualbank = false -epaperdisplay = false +emmcio = false +epaperdisplay = true # Zephyr board has busio floppyio = false -fontio = false -fourwire = false -framebufferio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio frequencyio = false -getpass = false -gifio = false +getpass = true +gifio = true # Zephyr board has busio gnss = false -hashlib = false -i2cdisplaybus = false +hardwarekey = false +hashlib = true +hmac = false +hostnetwork = false +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false i2ctarget = false imagecapture = false ipaddress = false is31fl3741 = false -jpegio = false -keypad = false -keypad_demux = false -locale = false -math = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true max3421e = false +mcp4822 = false mdns = false memorymap = false memorymonitor = false microcontroller = true -msgpack = false +mii = false +mipicsi = false +mipidsi = false +msgpack = true neopixel_write = false -nvm = false +nvm = true # Board has NVM partition onewireio = false os = true paralleldisplaybus = false +picogame = false +picogame3d = false ps2io = false pulseio = false pwmio = false qrio = false -rainbowio = false +qspibus = false +rainbowio = true random = true +rclcpy = false rgbmatrix = false -rotaryio = false -rtc = false -sdcardio = false +rotaryio = true # Zephyr board has rotaryio +rtc = true # Zephyr board has rtc +sdcardio = true # Zephyr board has busio sdioio = false -sharpdisplay = false +sharpdisplay = true # Zephyr board has busio socketpool = false spitarget = false ssl = false -storage = false +storage = true struct = true -supervisor = false +supervisor = true synthio = false -terminalio = false -tilepalettemapper = false +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio time = true -touchio = false -traceback = false +touchio = true +traceback = true uheap = false usb = false +usb_audio = false usb_cdc = true -usb_hid = false +usb_hid = true usb_host = false +usb_host_audio = false +usb_host_bulk = false usb_midi = false usb_video = false ustack = false -vectorio = false -warnings = false -watchdog = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog wifi = false +zephyr_display = false +zephyr_input = true # Zephyr board has zephyr_input zephyr_kernel = false -zephyr_serial = true -zlib = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/st/nucleo_u575zi_q/circuitpython.toml b/ports/zephyr-cp/boards/st/nucleo_u575zi_q/circuitpython.toml index 3ca45dd798b..3e307eac332 100644 --- a/ports/zephyr-cp/boards/st/nucleo_u575zi_q/circuitpython.toml +++ b/ports/zephyr-cp/boards/st/nucleo_u575zi_q/circuitpython.toml @@ -1,3 +1,3 @@ -CIRCUITPY_BUILD_EXTENSIONS = ["hex"] +CIRCUITPY_BUILD_EXTENSIONS = ["hex", "uf2"] USB_VID=0x239A USB_PID=0x816A diff --git a/ports/zephyr-cp/boards/st/stm32h750b_dk/autogen_board_info.toml b/ports/zephyr-cp/boards/st/stm32h750b_dk/autogen_board_info.toml new file mode 100644 index 00000000000..7a0907b8ea3 --- /dev/null +++ b/ports/zephyr-cp/boards/st/stm32h750b_dk/autogen_board_info.toml @@ -0,0 +1,145 @@ +# This file is autogenerated when a board is built. Do not edit. Do commit it to git. Other scripts use its info. +name = "STMicroelectronics STM32H750B Discovery Kit" + +[modules] +__future__ = true +_airlift = false +_bleio = false +_eve = false +_pew = false +_pixelmap = false +_stage = false +adafruit_bus_device = true +adafruit_pixelbuf = false +aesio = true +alarm = false +analogbufio = false +analogio = false +async_spi = false +atexit = true +audiobusio = false +audiocore = false +audiodelays = false +audiofilewriter = false +audiofilters = false +audiofreeverb = false +audioi2sin = false +audioio = false +audiomixer = false +audiomp3 = false +audiopwmio = false +audiospeed = false +audiotap = false +aurora_epaper = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio +bitops = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio +camera = false +canio = false +codeop = true +countio = false +cryptography = false +digitalio = true +displayio = true # Zephyr board has displayio +dotclockframebuffer = false +dualbank = false +emmcio = false +epaperdisplay = true # Zephyr board has busio +floppyio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio +frequencyio = false +getpass = true +gifio = true # Zephyr board has busio +gnss = false +hardwarekey = false +hashlib = true +hmac = false +hostnetwork = false +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false +i2ctarget = false +imagecapture = false +ipaddress = false +is31fl3741 = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true +max3421e = false +mcp4822 = false +mdns = false +memorymap = false +memorymonitor = false +microcontroller = true +mii = false +mipicsi = false +mipidsi = false +msgpack = true +neopixel_write = false +nvm = true # Board has NVM partition +onewireio = false +os = true +paralleldisplaybus = false +picogame = false +picogame3d = false +ps2io = false +pulseio = false +pwmio = false +qrio = false +qspibus = false +rainbowio = true +random = true +rclcpy = false +rgbmatrix = false +rotaryio = true # Zephyr board has rotaryio +rtc = true # Zephyr board has rtc +sdcardio = true # Zephyr board has busio +sdioio = false +sharpdisplay = true # Zephyr board has busio +socketpool = false +spitarget = false +ssl = false +storage = true # Zephyr board has flash +struct = true +supervisor = true +synthio = false +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio +time = true +touchio = true +traceback = true +uheap = false +usb = false +usb_audio = false +usb_cdc = true +usb_hid = true +usb_host = false +usb_host_audio = false +usb_host_bulk = false +usb_midi = false +usb_video = false +ustack = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog +wifi = false +zephyr_display = true # Zephyr board has zephyr_display +zephyr_input = true # Zephyr board has zephyr_input +zephyr_kernel = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/st/stm32h750b_dk/board.conf b/ports/zephyr-cp/boards/st/stm32h750b_dk/board.conf new file mode 100644 index 00000000000..24afffb8e88 --- /dev/null +++ b/ports/zephyr-cp/boards/st/stm32h750b_dk/board.conf @@ -0,0 +1,2 @@ +# Enable Zephyr display subsystem so the built-in LTDC panel is available. +CONFIG_DISPLAY=y diff --git a/ports/zephyr-cp/boards/st/stm32h750b_dk/board.overlay b/ports/zephyr-cp/boards/st/stm32h750b_dk/board.overlay new file mode 100644 index 00000000000..70324b711aa --- /dev/null +++ b/ports/zephyr-cp/boards/st/stm32h750b_dk/board.overlay @@ -0,0 +1,25 @@ +&rng { + status = "okay"; +}; + +/* The USB device controller (zephyr_udc0) and the QSPI flash partition map + * are defined in the mcuboot fork's dts/st/stm32h750b_dk.dtsi, which + * sysbuild prepends to this image's overlays. app.overlay only adds the + * CDC ACM console/data endpoints. + */ +// Enable the SoC watchdog and expose it through the `watchdog0` alias +// (Zephyr's watchdog sample selection) for the watchdog module. The IWDG +// doesn't start on boot (START_ACTIVE_BY_DEFAULT is off); it only arms when +// Python code sets a mode. It cannot be stopped once armed, like the native +// STM32 CircuitPython port. +&iwdg { + status = "okay"; +}; + +/ { + aliases { + watchdog0 = &iwdg; + }; +}; + +#include "../../../app.overlay" diff --git a/ports/zephyr-cp/boards/st/stm32h750b_dk/circuitpython.toml b/ports/zephyr-cp/boards/st/stm32h750b_dk/circuitpython.toml new file mode 100644 index 00000000000..40562364cde --- /dev/null +++ b/ports/zephyr-cp/boards/st/stm32h750b_dk/circuitpython.toml @@ -0,0 +1 @@ +CIRCUITPY_BUILD_EXTENSIONS = ["hex", "uf2"] diff --git a/ports/zephyr-cp/boards/st/stm32h7b3i_dk/autogen_board_info.toml b/ports/zephyr-cp/boards/st/stm32h7b3i_dk/autogen_board_info.toml index ac0aff61a59..e8d9a6f28b8 100644 --- a/ports/zephyr-cp/boards/st/stm32h7b3i_dk/autogen_board_info.toml +++ b/ports/zephyr-cp/boards/st/stm32h7b3i_dk/autogen_board_info.toml @@ -2,110 +2,144 @@ name = "STMicroelectronics STM32H7B3I Discovery kit" [modules] -__future__ = false +__future__ = true +_airlift = false _bleio = false _eve = false _pew = false _pixelmap = false _stage = false -adafruit_bus_device = false +adafruit_bus_device = true adafruit_pixelbuf = false -aesio = false +aesio = true alarm = false analogbufio = false analogio = false -atexit = false +async_spi = true # Zephyr board has async_spi +atexit = true audiobusio = false audiocore = false audiodelays = false +audiofilewriter = false audiofilters = false +audiofreeverb = false +audioi2sin = false audioio = false audiomixer = false audiomp3 = false audiopwmio = false +audiospeed = false +audiotap = false aurora_epaper = false -bitbangio = false -bitmapfilter = false -bitmaptools = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio bitops = false -board = false -busdisplay = false -busio = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio camera = false canio = false -codeop = false +codeop = true countio = false +cryptography = false digitalio = true -displayio = false +displayio = true # Zephyr board has displayio dotclockframebuffer = false dualbank = false -epaperdisplay = false +emmcio = false +epaperdisplay = true # Zephyr board has busio floppyio = false -fontio = false -fourwire = false -framebufferio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio frequencyio = false -getpass = false -gifio = false +getpass = true +gifio = true # Zephyr board has busio gnss = false -hashlib = false -i2cdisplaybus = false +hardwarekey = false +hashlib = true +hmac = false +hostnetwork = false +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false i2ctarget = false imagecapture = false ipaddress = false is31fl3741 = false -jpegio = false -keypad = false -keypad_demux = false -locale = false -math = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true max3421e = false +mcp4822 = false mdns = false memorymap = false memorymonitor = false microcontroller = true -msgpack = false +mii = false +mipicsi = false +mipidsi = false +msgpack = true neopixel_write = false -nvm = false +nvm = true # Board has NVM partition onewireio = false os = true paralleldisplaybus = false +picogame = false +picogame3d = false ps2io = false pulseio = false pwmio = false qrio = false -rainbowio = false +qspibus = false +rainbowio = true random = true +rclcpy = false rgbmatrix = false -rotaryio = false +rotaryio = true # Zephyr board has rotaryio rtc = false -sdcardio = false +sdcardio = true # Zephyr board has busio sdioio = false -sharpdisplay = false +sharpdisplay = true # Zephyr board has busio socketpool = false spitarget = false ssl = false storage = true # Zephyr board has flash struct = true -supervisor = false +supervisor = true synthio = false -terminalio = false -tilepalettemapper = false +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio time = true -touchio = false -traceback = false +touchio = true +traceback = true uheap = false usb = false -usb_cdc = false -usb_hid = false +usb_audio = false +usb_cdc = true +usb_hid = true usb_host = false +usb_host_audio = false +usb_host_bulk = false usb_midi = false usb_video = false ustack = false -vectorio = false -warnings = false -watchdog = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog wifi = false +zephyr_display = true # Zephyr board has zephyr_display +zephyr_input = true # Zephyr board has zephyr_input zephyr_kernel = false -zephyr_serial = true -zlib = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/st/stm32h7b3i_dk/board.conf b/ports/zephyr-cp/boards/st/stm32h7b3i_dk/board.conf new file mode 100644 index 00000000000..c4b8937cfda --- /dev/null +++ b/ports/zephyr-cp/boards/st/stm32h7b3i_dk/board.conf @@ -0,0 +1,3 @@ +# Enable Zephyr display subsystem so the built-in LTDC panel is available. +CONFIG_DISPLAY=y +CONFIG_GPIO=y diff --git a/ports/zephyr-cp/boards/st/stm32h7b3i_dk/board.overlay b/ports/zephyr-cp/boards/st/stm32h7b3i_dk/board.overlay new file mode 100644 index 00000000000..8e12b1207fd --- /dev/null +++ b/ports/zephyr-cp/boards/st/stm32h7b3i_dk/board.overlay @@ -0,0 +1,41 @@ + +&sram5 { + status = "disabled"; +}; + +&rng { + status = "okay"; +}; + +&fdcan1 { + status = "disabled"; +}; + +/ { + chosen { + /delete-property/ zephyr,canbus; + }; +}; + +zephyr_udc0: &usbotg_hs { + pinctrl-0 = <&usb_otg_hs_dm_pa11 &usb_otg_hs_dp_pa12>; + pinctrl-names = "default"; + status = "okay"; +}; + +// Enable the SoC watchdog and expose it through the `watchdog0` alias +// (Zephyr's watchdog sample selection) for the watchdog module. The IWDG +// doesn't start on boot (START_ACTIVE_BY_DEFAULT is off); it only arms when +// Python code sets a mode. It cannot be stopped once armed, like the native +// STM32 CircuitPython port. +&iwdg { + status = "okay"; +}; + +/ { + aliases { + watchdog0 = &iwdg; + }; +}; + +#include "../../../app.overlay" diff --git a/ports/zephyr-cp/boards/st/stm32h7b3i_dk/circuitpython.toml b/ports/zephyr-cp/boards/st/stm32h7b3i_dk/circuitpython.toml index 83e6bcd39c4..40562364cde 100644 --- a/ports/zephyr-cp/boards/st/stm32h7b3i_dk/circuitpython.toml +++ b/ports/zephyr-cp/boards/st/stm32h7b3i_dk/circuitpython.toml @@ -1 +1 @@ -CIRCUITPY_BUILD_EXTENSIONS = ["hex"] +CIRCUITPY_BUILD_EXTENSIONS = ["hex", "uf2"] diff --git a/ports/zephyr-cp/boards/st/stm32wba65i_dk1/autogen_board_info.toml b/ports/zephyr-cp/boards/st/stm32wba65i_dk1/autogen_board_info.toml new file mode 100644 index 00000000000..ce918210aa1 --- /dev/null +++ b/ports/zephyr-cp/boards/st/stm32wba65i_dk1/autogen_board_info.toml @@ -0,0 +1,145 @@ +# This file is autogenerated when a board is built. Do not edit. Do commit it to git. Other scripts use its info. +name = "STMicroelectronics STM32WBA65I Discovery kit" + +[modules] +__future__ = true +_airlift = false +_bleio = true # Zephyr board has _bleio +_eve = false +_pew = false +_pixelmap = false +_stage = false +adafruit_bus_device = true +adafruit_pixelbuf = false +aesio = true +alarm = false +analogbufio = false +analogio = false +async_spi = true # Zephyr board has async_spi +atexit = true +audiobusio = false +audiocore = false +audiodelays = false +audiofilewriter = false +audiofilters = false +audiofreeverb = false +audioi2sin = false +audioio = false +audiomixer = false +audiomp3 = false +audiopwmio = false +audiospeed = false +audiotap = false +aurora_epaper = false +bitbangio = true +bitmapfilter = true # Zephyr board has busio +bitmaptools = true # Zephyr board has busio +bitops = false +board = true # Always enabled +busdisplay = true # Zephyr board has busio +busio = true # Zephyr board has busio +camera = false +canio = false +codeop = true +countio = false +cryptography = false +digitalio = true +displayio = true # Zephyr board has busio +dotclockframebuffer = false +dualbank = false +emmcio = false +epaperdisplay = true # Zephyr board has busio +floppyio = false +fontio = true # Zephyr board has busio +fourwire = true # Zephyr board has busio +framebufferio = true # Zephyr board has busio +frequencyio = false +getpass = true +gifio = true # Zephyr board has busio +gnss = false +hardwarekey = false +hashlib = true +hmac = false +hostnetwork = false +i2cdisplaybus = true # Zephyr board has busio +i2cioexpander = false +i2ctarget = false +imagecapture = false +ipaddress = false +is31fl3741 = false +jpegio = true # Zephyr board has busio +keypad = true +keypad_demux = true +locale = true +lvfontio = true # Zephyr board has busio +math = true +max3421e = false +mcp4822 = false +mdns = false +memorymap = false +memorymonitor = false +microcontroller = true +mii = false +mipicsi = false +mipidsi = false +msgpack = true +neopixel_write = false +nvm = true # Board has NVM partition +onewireio = false +os = true +paralleldisplaybus = false +picogame = false +picogame3d = false +ps2io = false +pulseio = false +pwmio = false +qrio = false +qspibus = false +rainbowio = true +random = true +rclcpy = false +rgbmatrix = false +rotaryio = true # Zephyr board has rotaryio +rtc = true # Zephyr board has rtc +sdcardio = true # Zephyr board has busio +sdioio = false +sharpdisplay = true # Zephyr board has busio +socketpool = false +spitarget = false +ssl = false +storage = true +struct = true +supervisor = true +synthio = false +terminalio = true # Zephyr board has busio +tilepalettemapper = true # Zephyr board has busio +time = true +touchio = true +traceback = true +uheap = false +usb = false +usb_audio = false +usb_cdc = true +usb_hid = true +usb_host = false +usb_host_audio = false +usb_host_bulk = false +usb_midi = false +usb_video = false +ustack = false +vectorio = true # Zephyr board has busio +videocore = false +videogif = false +warnings = true +watchdog = true # Zephyr board has watchdog +wifi = false +zephyr_display = false +zephyr_input = false +zephyr_kernel = false +zlib = true +# extmod modules shared with MicroPython +asyncio = true +binascii = true +json = true +re = true +select = true diff --git a/ports/zephyr-cp/boards/st/stm32wba65i_dk1/board.conf b/ports/zephyr-cp/boards/st/stm32wba65i_dk1/board.conf new file mode 100644 index 00000000000..7247e3f6d09 --- /dev/null +++ b/ports/zephyr-cp/boards/st/stm32wba65i_dk1/board.conf @@ -0,0 +1,14 @@ +# USB OTG on STM32WBA requires VOS Range 1. Keep HCLK > 16 MHz. +CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC=32000000 + +# GPIO was previously selected indirectly by the GPIO-keys input driver. +# CircuitPython's digitalio support needs it even with input nodes disabled. +CONFIG_GPIO=y + +# Bluetooth doesn't start up for some reason. +# CONFIG_BT=y +# CONFIG_BT_PERIPHERAL=y +# CONFIG_BT_CENTRAL=y + +# Board-specific BT calibration +CONFIG_BT_STM32WBA_USE_TEMP_BASED_CALIB=n diff --git a/ports/zephyr-cp/boards/st/stm32wba65i_dk1/board.overlay b/ports/zephyr-cp/boards/st/stm32wba65i_dk1/board.overlay new file mode 100644 index 00000000000..ce05f93571e --- /dev/null +++ b/ports/zephyr-cp/boards/st/stm32wba65i_dk1/board.overlay @@ -0,0 +1,51 @@ + +&rng { + status = "okay"; +}; + +/* Keep the button/key nodes available for board pin-name generation, but + * don't instantiate the input drivers. zephyr_input currently exposes touch + * input only, so these key devices don't provide useful input through it. */ +&{/gpio_keys} { + status = "disabled"; +}; + +&{/adc-keys} { + status = "disabled"; +}; + +/* The board's &rtc node is already status-okay in the upstream devicetree, so + * alias it so the rtc module picks it up like other RTC boards do. */ +/ { + aliases { + rtc = &rtc; + }; +}; + +/* The upstream board devicetree already enables the IWDG; the alias only + * exposes it to the watchdog module. */ +/ { + aliases { + watchdog0 = &iwdg; + }; +}; + +/* The USB device controller (zephyr_udc0, including the OTG HS PHY and the + * HSE/VOS clocking it needs) and the joystick-selector boot button are + * defined in the mcuboot fork's dts/st/stm32wba65i_dk1.dtsi, which sysbuild + * prepends to this image's overlays so both images share the definitions. + */ + +&bt_hci_wba { + /* Use HASH IRQ to allocate Radio SW Low Process (Warning HASH is not used) */ + interrupts = <66 0>, <61 14>; + interrupt-names = "radio", "radio-sw-low"; +}; + +&ieee802154 { + /* Use HASH IRQ to allocate Radio SW Low Process (Warning HASH is not used) */ + interrupts = <66 0>, <61 14>; + interrupt-names = "radio", "radio-sw-low"; +}; + +#include "../../../app.overlay" diff --git a/ports/zephyr-cp/boards/st/stm32wba65i_dk1/circuitpython.toml b/ports/zephyr-cp/boards/st/stm32wba65i_dk1/circuitpython.toml new file mode 100644 index 00000000000..44c6b374674 --- /dev/null +++ b/ports/zephyr-cp/boards/st/stm32wba65i_dk1/circuitpython.toml @@ -0,0 +1,2 @@ +CIRCUITPY_BUILD_EXTENSIONS = ["hex", "uf2"] +BLOBS=["hal_stm32"] diff --git a/ports/zephyr-cp/boards/stm32h7b3i_dk.overlay b/ports/zephyr-cp/boards/stm32h7b3i_dk.overlay deleted file mode 100644 index 88ad0415485..00000000000 --- a/ports/zephyr-cp/boards/stm32h7b3i_dk.overlay +++ /dev/null @@ -1,7 +0,0 @@ -&mx25lm51245 { - /delete-node/ partitions; -}; - -&rng { - status = "okay"; -}; diff --git a/ports/zephyr-cp/common-hal/_bleio/Adapter.c b/ports/zephyr-cp/common-hal/_bleio/Adapter.c new file mode 100644 index 00000000000..7819e68676e --- /dev/null +++ b/ports/zephyr-cp/common-hal/_bleio/Adapter.c @@ -0,0 +1,944 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018 Dan Halbert for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "py/gc.h" +#include "py/runtime.h" +#include "bindings/zephyr_kernel/__init__.h" +#include "shared-bindings/_bleio/__init__.h" +#include "common-hal/_bleio/__init__.h" +#include "shared-bindings/_bleio/Adapter.h" +#include "shared-bindings/_bleio/Address.h" +#include "shared-module/_bleio/Address.h" +#include "shared-module/_bleio/ScanResults.h" +#include "supervisor/background_callback.h" +#include "supervisor/shared/bluetooth/bluetooth.h" +#include "supervisor/shared/tick.h" + +bleio_connection_internal_t bleio_connections[BLEIO_TOTAL_CONNECTION_COUNT]; + +// Background pump: drains the BLE file-transfer / serial PacketBuffers by +// calling supervisor_bluetooth_background(). Queued from GATT write callbacks +// and connection events so the VM processes incoming data promptly. +static background_callback_t bluetooth_background_cb = {NULL, NULL}; + +static void bluetooth_adapter_background(void *data) { + (void)data; + supervisor_bluetooth_background(); +} + +void bleio_request_bluetooth_background(void) { + if (bluetooth_background_cb.fun != NULL) { + background_callback_add_core(&bluetooth_background_cb); + } +} + +static bool scan_callbacks_registered = false; +static bleio_scanresults_obj_t *active_scan_results = NULL; +static struct bt_le_scan_cb scan_callbacks; +static bool ble_advertising = false; +// True when advertising was started by the BLE workflow (supervisor) rather +// than user code. Lets the workflow restart its own adverts without disturbing +// user-initiated advertising. +static bool ble_advertising_internal = false; +// Set to true when common_hal_bleio_adapter_set_enabled(true) brings the stack up. +// set_enabled(false) clears this flag and stops advertising and scanning, but +// the controller keeps running. +static bool ble_adapter_enabled = false; + +#define BLEIO_ADV_MAX_FIELDS 16 +#define BLEIO_ADV_MAX_DATA_LEN 31 +static struct bt_data adv_data[BLEIO_ADV_MAX_FIELDS]; +static struct bt_data scan_resp_data[BLEIO_ADV_MAX_FIELDS]; +static uint8_t adv_data_storage[BLEIO_ADV_MAX_DATA_LEN]; +static uint8_t scan_resp_storage[BLEIO_ADV_MAX_DATA_LEN]; + +static uint8_t bleio_address_type_from_zephyr(const bt_addr_le_t *addr) { + if (addr == NULL) { + return BLEIO_ADDRESS_TYPE_PUBLIC; + } + + switch (addr->type) { + case BT_ADDR_LE_PUBLIC: + case BT_ADDR_LE_PUBLIC_ID: + return BLEIO_ADDRESS_TYPE_PUBLIC; + case BT_ADDR_LE_RANDOM: + case BT_ADDR_LE_RANDOM_ID: + case BT_ADDR_LE_UNRESOLVED: + if (BT_ADDR_IS_RPA(&addr->a)) { + return BLEIO_ADDRESS_TYPE_RANDOM_PRIVATE_RESOLVABLE; + } + if (BT_ADDR_IS_NRPA(&addr->a)) { + return BLEIO_ADDRESS_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE; + } + return BLEIO_ADDRESS_TYPE_RANDOM_STATIC; + default: + return BLEIO_ADDRESS_TYPE_PUBLIC; + } +} + +static uint8_t bleio_address_type_to_zephyr(uint8_t type) { + switch (type) { + case BLEIO_ADDRESS_TYPE_PUBLIC: + return BT_ADDR_LE_PUBLIC; + case BLEIO_ADDRESS_TYPE_RANDOM_STATIC: + case BLEIO_ADDRESS_TYPE_RANDOM_PRIVATE_RESOLVABLE: + case BLEIO_ADDRESS_TYPE_RANDOM_PRIVATE_NON_RESOLVABLE: + return BT_ADDR_LE_RANDOM; + default: + return BT_ADDR_LE_PUBLIC; + } +} + +static bleio_connection_internal_t *bleio_connection_find_by_conn(const struct bt_conn *conn) { + for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) { + bleio_connection_internal_t *connection = &bleio_connections[i]; + if (connection->conn == conn) { + return connection; + } + } + + return NULL; +} + +static bleio_connection_internal_t *bleio_connection_track(struct bt_conn *conn) { + bleio_connection_internal_t *connection = bleio_connection_find_by_conn(conn); + if (connection == NULL) { + for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) { + bleio_connection_internal_t *candidate = &bleio_connections[i]; + if (candidate->conn == NULL) { + connection = candidate; + break; + } + } + } + + if (connection == NULL) { + return NULL; + } + + if (connection->conn == NULL) { + connection->conn = bt_conn_ref(conn); + } + + return connection; +} + +static void bleio_connection_clear(bleio_connection_internal_t *self) { + if (self == NULL) { + return; + } + + if (self->conn != NULL) { + bt_conn_unref(self->conn); + self->conn = NULL; + } + + self->connection_obj = mp_const_none; + self->pair_status = PAIR_NOT_PAIRED; + self->sec_err = 0; + self->user_owned = false; +} + +static void bleio_connection_release(bleio_connection_internal_t *connection, uint8_t reason) { + if (connection == NULL) { + return; + } + + if (connection->connection_obj != mp_const_none) { + bleio_connection_obj_t *connection_obj = MP_OBJ_TO_PTR(connection->connection_obj); + connection_obj->connection = NULL; + connection_obj->disconnect_reason = reason; + } + + bleio_connection_clear(connection); + common_hal_bleio_adapter_obj.connection_objs = NULL; +} + +// Per-connection ATT MTU exchange parameters. The params struct must persist +// until the exchange callback fires, so it lives for the lifetime of the slot. +static struct bt_gatt_exchange_params mtu_exchange_params[BLEIO_TOTAL_CONNECTION_COUNT]; + +static void on_mtu_exchanged(struct bt_conn *conn, uint8_t err, + struct bt_gatt_exchange_params *params) { + (void)conn; + (void)params; + if (err == 0) { + // Wake the workflow so outgoing_packet_length is recomputed with the + // now-larger negotiated MTU. + bleio_request_bluetooth_background(); + } +} + +static void bleio_connected_cb(struct bt_conn *conn, uint8_t err) { + if (err != 0) { + return; + } + + bleio_connection_internal_t *connection = bleio_connection_track(conn); + if (connection == NULL) { + bt_conn_disconnect(conn, BT_HCI_ERR_CONN_LIMIT_EXCEEDED); + return; + } + + // Initiate an ATT MTU exchange so the negotiated MTU reflects the larger + // payload our stack supports (CONFIG_BT_L2CAP_TX_MTU). Many centrals do + // this themselves, but if they don't we'd be stuck at the default 23-byte + // MTU (20-byte payload). That forces the file-transfer workflow to split + // protocol messages across notifications in ways peers can't reassemble + // (e.g. a listdir_entry whose second fragment begins with a 0x00 flags + // byte is misread as "unknown command 0x00"). bt_gatt_exchange_mtu returns + // -EALREADY if the peer already initiated, so this is safe either way. + size_t idx = (size_t)(connection - bleio_connections); + mtu_exchange_params[idx].func = on_mtu_exchanged; + int mtu_err = bt_gatt_exchange_mtu(conn, &mtu_exchange_params[idx]); + (void)mtu_err; + + // A peripheral connection belongs to whoever started the advertising it + // answered: the BLE workflow (internal) or user code. Central connections + // are marked in common_hal_bleio_adapter_connect(). + connection->user_owned = !ble_advertising_internal; + + // When connectable advertising results in a connection, the controller + // auto-stops advertising. Clear our flag to match (we cannot call + // stop_advertising() here because this callback runs in Zephyr's BT + // thread context). + ble_advertising = false; + ble_advertising_internal = false; + + common_hal_bleio_adapter_obj.connection_objs = NULL; + + // Pump the workflow once now, and arm the recurring background callback + // so future GATT writes / events get drained by the VM. + bluetooth_background_cb.fun = bluetooth_adapter_background; + bluetooth_background_cb.data = NULL; + bluetooth_adapter_background(NULL); +} + +static void bleio_disconnected_cb(struct bt_conn *conn, uint8_t reason) { + bleio_connection_discovery_abort(); + bleio_connection_release(bleio_connection_find_by_conn(conn), reason); + bleio_request_bluetooth_background(); +} + +static void bleio_security_changed_cb(struct bt_conn *conn, bt_security_t level, + enum bt_security_err err) { + bleio_connection_internal_t *connection = bleio_connection_find_by_conn(conn); + if (connection == NULL) { + return; + } + + if (err == BT_SECURITY_ERR_SUCCESS && level > BT_SECURITY_L1) { + // Security was established (encryption enabled). + // This happens both on first-time pairing and when reconnecting + // with stored bond keys. + connection->pair_status = PAIR_PAIRED; + } else if (err != BT_SECURITY_ERR_SUCCESS) { + connection->pair_status = PAIR_NOT_PAIRED; + connection->sec_err = (uint8_t)err; + } +} + +BT_CONN_CB_DEFINE(bleio_connection_callbacks) = { + .connected = bleio_connected_cb, + .disconnected = bleio_disconnected_cb, + .security_changed = bleio_security_changed_cb, +}; + +static void scan_recv_cb(const struct bt_le_scan_recv_info *info, struct net_buf_simple *buf) { + if (active_scan_results == NULL || info == NULL || buf == NULL) { + return; + } + + const bool connectable = (info->adv_props & BT_GAP_ADV_PROP_CONNECTABLE) != 0; + const bool scan_response = (info->adv_props & BT_GAP_ADV_PROP_SCAN_RESPONSE) != 0; + const bt_addr_le_t *addr = info->addr; + + uint8_t addr_bytes[NUM_BLEIO_ADDRESS_BYTES] = {0}; + if (addr != NULL) { + memcpy(addr_bytes, addr->a.val, sizeof(addr_bytes)); + } + + shared_module_bleio_scanresults_append(active_scan_results, + supervisor_ticks_ms64(), + connectable, + scan_response, + info->rssi, + addr_bytes, + bleio_address_type_from_zephyr(addr), + buf->data, + buf->len); +} + +static void scan_timeout_cb(void) { + if (active_scan_results == NULL) { + return; + } + shared_module_bleio_scanresults_set_done(active_scan_results, true); + active_scan_results = NULL; +} + +// We need to disassemble the full advertisement packet because the Zephyr takes +// in each ADT in an array. +static size_t bleio_parse_adv_data(const uint8_t *raw, size_t raw_len, struct bt_data *out, + size_t out_len, uint8_t *storage, size_t storage_len) { + size_t count = 0; + size_t offset = 0; + size_t storage_offset = 0; + + while (offset < raw_len) { + uint8_t field_len = raw[offset]; + if (field_len == 0) { + offset++; + continue; + } + uint8_t data_len = field_len - 1; + if (offset + field_len + 1 > raw_len || + count >= out_len || + storage_offset + data_len > storage_len) { + return 0; + } + uint8_t type = raw[offset + 1]; + memcpy(storage + storage_offset, raw + offset + 2, data_len); + out[count].type = type; + out[count].data_len = data_len; + out[count].data = storage + storage_offset; + storage_offset += data_len; + count++; + offset += field_len + 1; + } + + return count; +} + +static uint16_t bleio_validate_and_convert_timeout(mp_float_t timeout) { + mp_arg_validate_float_range(timeout, 0, UINT16_MAX, MP_QSTR_timeout); + + if (timeout <= 0.0f) { + return 0; + } + + const mp_int_t timeout_units = + mp_arg_validate_int_range((mp_int_t)(timeout * 100.0f + 0.5f), 1, UINT16_MAX, MP_QSTR_timeout); + + return (uint16_t)timeout_units; +} + +// Start the Zephyr Bluetooth host and load its settings (identity, bond keys, +// CCC state) if that hasn't happened yet. Returns 0 or a negative Zephyr errno. +// +// This is separate from set_enabled() because the BLE workflow asks about +// bonds (is_bonded_to_central(), erase_bonding()) in supervisor_bluetooth_init(), +// before it enables the adapter in supervisor_start_bluetooth(). Bond keys live +// in the settings subsystem and are only in RAM after settings_load(), so those +// calls must be able to bring the stack up on their own. Nothing here powers the +// controller down later: set_enabled(false) leaves it running. +static int bleio_adapter_ensure_stack_ready(void) { + if (bt_is_ready()) { + return 0; + } + int err = bt_enable(NULL); + if (err != 0 && err != -EALREADY) { + return err; + } + + // bt_init() returns early without setting BT_DEV_READY when + // CONFIG_BT_SETTINGS=y and no identity is loaded yet. + // Load settings so the BT settings handler fires and calls + // bt_finalize_init() which sets BT_DEV_READY. + settings_load(); + return 0; +} + +void common_hal_bleio_adapter_set_enabled(bleio_adapter_obj_t *self, bool enabled) { + if (enabled == ble_adapter_enabled) { + return; + } + if (enabled) { + for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) { + bleio_connection_clear(&bleio_connections[i]); + } + int err = bleio_adapter_ensure_stack_ready(); + if (err != 0) { + raise_zephyr_error(err); + } + // Ensure a local identity exists so advertising/connections work and the + // name is stable across reboots. bt_id_create persists the identity when + // CONFIG_BT_SETTINGS is enabled. bleio_adapter_reset_name() reads the + // identity address back via common_hal_bleio_adapter_get_address(). + bt_addr_le_t id_addrs[CONFIG_BT_ID_MAX]; + size_t id_count = CONFIG_BT_ID_MAX; + bt_id_get(id_addrs, &id_count); + if (id_count == 0 || bt_addr_le_eq(&id_addrs[BT_ID_DEFAULT], BT_ADDR_LE_ANY)) { + (void)bt_id_create(NULL, NULL); + bt_id_get(id_addrs, &id_count); + } + bleio_adapter_reset_name(self); + ble_adapter_enabled = true; + return; + } + + // On Zephyr bsim + HCI IPC, disabling and immediately re-enabling BLE can + // race endpoint rebinding during soft reload. Keep the controller running, + // but present adapter.enabled=False to CircuitPython code. + common_hal_bleio_adapter_stop_scan(self); + common_hal_bleio_adapter_stop_advertising(self); + ble_adapter_enabled = false; +} + +bool common_hal_bleio_adapter_get_enabled(bleio_adapter_obj_t *self) { + return ble_adapter_enabled; +} + +mp_int_t common_hal_bleio_adapter_get_tx_power(bleio_adapter_obj_t *self) { + struct bt_hci_cp_vs_read_tx_power_level *cp; + struct bt_hci_rp_vs_read_tx_power_level *rp; + struct net_buf *buf, *rsp = NULL; + + buf = bt_hci_cmd_alloc(K_MSEC(1000)); + if (!buf) { + mp_raise_msg(&mp_type_MemoryError, NULL); + } + cp = net_buf_add(buf, sizeof(*cp)); + cp->handle_type = BT_HCI_VS_LL_HANDLE_TYPE_ADV; + cp->handle = 0; + + int err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_READ_TX_POWER_LEVEL, buf, &rsp); + if (err) { + raise_zephyr_error(err); + } + + rp = (void *)rsp->data; + int8_t power = rp->tx_power_level; + net_buf_unref(rsp); + return power; +} + +// Non-raising variant of common_hal_bleio_adapter_set_tx_power for use from the +// BLE workflow, which runs outside the VM. Returns 0 on success. +static int bleio_adapter_set_tx_power_noraise(mp_int_t tx_power) { + struct bt_hci_cp_vs_write_tx_power_level *cp; + struct net_buf *buf, *rsp = NULL; + + buf = bt_hci_cmd_alloc(K_MSEC(3000)); + if (!buf) { + return -ENOMEM; + } + cp = net_buf_add(buf, sizeof(*cp)); + cp->handle_type = BT_HCI_VS_LL_HANDLE_TYPE_ADV; + cp->handle = 0; + cp->tx_power_level = (int8_t)tx_power; + + int err = bt_hci_cmd_send_sync(BT_HCI_OP_VS_WRITE_TX_POWER_LEVEL, buf, &rsp); + if (err) { + return err; + } + + net_buf_unref(rsp); + return 0; +} + +void common_hal_bleio_adapter_set_tx_power(bleio_adapter_obj_t *self, mp_int_t tx_power) { + int err = bleio_adapter_set_tx_power_noraise(tx_power); + if (err) { + raise_zephyr_error(err); + } +} + +bleio_address_obj_t *common_hal_bleio_adapter_get_address(bleio_adapter_obj_t *self) { + // Report the local identity address, which is the same address used to + // derive the default adapter name in common_hal_bleio_adapter_set_enabled. + bt_addr_le_t id_addrs[CONFIG_BT_ID_MAX]; + size_t id_count = CONFIG_BT_ID_MAX; + bt_id_get(id_addrs, &id_count); + if (id_count == 0 || bt_addr_le_eq(&id_addrs[BT_ID_DEFAULT], BT_ADDR_LE_ANY)) { + (void)bt_id_create(NULL, NULL); + bt_id_get(id_addrs, &id_count); + } + + const bt_addr_le_t *addr = &id_addrs[BT_ID_DEFAULT]; + // Cache the address on the adapter so this can be called before the heap + // is available (e.g. from bleio_adapter_reset_name). The shared + // common_hal_bleio_address_construct() converts the raw address bytes + // into the Address object. + common_hal_bleio_address_construct(&self->address, addr->a.val, + bleio_address_type_from_zephyr(addr)); + self->address.base.type = &bleio_address_type; + return &self->address; +} + +bool common_hal_bleio_adapter_set_address(bleio_adapter_obj_t *self, bleio_address_obj_t *address) { + mp_raise_NotImplementedError(NULL); +} + +mp_obj_str_t *common_hal_bleio_adapter_get_name(bleio_adapter_obj_t *self) { + (void)self; + const char *name = bt_get_name(); + return mp_obj_new_str(name, strlen(name)); +} + +void common_hal_bleio_adapter_set_name(bleio_adapter_obj_t *self, const char *name) { + (void)self; + size_t len = strlen(name); + int err = 0; + if (len > CONFIG_BT_DEVICE_NAME_MAX) { + char truncated[CONFIG_BT_DEVICE_NAME_MAX + 1]; + memcpy(truncated, name, CONFIG_BT_DEVICE_NAME_MAX); + truncated[CONFIG_BT_DEVICE_NAME_MAX] = '\0'; + err = bt_set_name(truncated); + } else { + err = bt_set_name(name); + } + if (err != 0) { + raise_zephyr_error(err); + } +} + +// Internal start_advertising used by the BLE workflow (file transfer + serial +// services). Runs outside the VM, so it must not raise. Returns 0 on success or +// a positive errno on failure. A timeout of 0 means advertise indefinitely. +// This is the core implementation; common_hal_bleio_adapter_start_advertising() +// delegates here and translates errors into exceptions. +uint32_t _common_hal_bleio_adapter_start_advertising(bleio_adapter_obj_t *self, + bool connectable, bool anonymous, uint32_t timeout, float interval, + const uint8_t *advertising_data, uint16_t advertising_data_len, + const uint8_t *scan_response_data, uint16_t scan_response_data_len, + mp_int_t tx_power, const bleio_address_obj_t *directed_to) { + (void)directed_to; + (void)interval; + (void)anonymous; + (void)timeout; + + if (advertising_data_len > BLEIO_ADV_MAX_DATA_LEN || + scan_response_data_len > BLEIO_ADV_MAX_DATA_LEN) { + return (uint32_t)EINVAL; + } + + // Don't disturb advertising that is already active (either user code or the + // workflow's own previous advert). The caller is responsible for stopping + // first if a restart is desired. + if (ble_advertising) { + return (uint32_t)EBUSY; + } + + bt_addr_le_t id_addrs[CONFIG_BT_ID_MAX]; + size_t id_count = CONFIG_BT_ID_MAX; + bt_id_get(id_addrs, &id_count); + if (id_count == 0 || bt_addr_le_eq(&id_addrs[BT_ID_DEFAULT], BT_ADDR_LE_ANY)) { + int id = bt_id_create(NULL, NULL); + if (id < 0) { + return (uint32_t)(-id); + } + } + + size_t adv_count = bleio_parse_adv_data(advertising_data, + advertising_data_len, + adv_data, + BLEIO_ADV_MAX_FIELDS, + adv_data_storage, + sizeof(adv_data_storage)); + if (adv_count == 0) { + return (uint32_t)EINVAL; + } + + size_t scan_resp_count = 0; + if (scan_response_data_len > 0) { + scan_resp_count = bleio_parse_adv_data(scan_response_data, + scan_response_data_len, + scan_resp_data, + BLEIO_ADV_MAX_FIELDS, + scan_resp_storage, + sizeof(scan_resp_storage)); + if (scan_resp_count == 0) { + return (uint32_t)EINVAL; + } + } + + struct bt_le_adv_param adv_params; + if (connectable) { + adv_params = (struct bt_le_adv_param)BT_LE_ADV_PARAM_INIT( + BT_LE_ADV_OPT_CONN, + BT_GAP_ADV_FAST_INT_MIN_1, + BT_GAP_ADV_FAST_INT_MAX_1, + NULL); + } else if (scan_resp_count > 0) { + adv_params = (struct bt_le_adv_param)BT_LE_ADV_PARAM_INIT( + BT_LE_ADV_OPT_SCANNABLE, + BT_GAP_ADV_FAST_INT_MIN_2, + BT_GAP_ADV_FAST_INT_MAX_2, + NULL); + } else { + adv_params = (struct bt_le_adv_param)BT_LE_ADV_PARAM_INIT( + 0, + BT_GAP_ADV_FAST_INT_MIN_2, + BT_GAP_ADV_FAST_INT_MAX_2, + NULL); + } + + // Best-effort TX power: the vendor HCI command may not exist on all + // controllers, so ignore failures here. + (void)bleio_adapter_set_tx_power_noraise(tx_power); + + int err = bt_le_adv_start(&adv_params, + adv_data, + adv_count, + scan_resp_count > 0 ? scan_resp_data : NULL, + scan_resp_count); + if (err) { + return (uint32_t)(-err); + } + + ble_advertising = true; + // Default to workflow-owned; the public wrapper overrides this for user code. + ble_advertising_internal = true; + return 0; +} + +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, + mp_int_t tx_power, const bleio_address_obj_t *directed_to) { + (void)directed_to; + (void)interval; + + if (advertising_data_bufinfo->len > BLEIO_ADV_MAX_DATA_LEN || + scan_response_data_bufinfo->len > BLEIO_ADV_MAX_DATA_LEN) { + mp_raise_ValueError(MP_ERROR_TEXT("Data too large for advertisement packet")); + } + + if (timeout != 0) { + mp_raise_NotImplementedError(NULL); + } + + if (anonymous) { + mp_raise_NotImplementedError(NULL); + } + + if (ble_advertising) { + if (!ble_advertising_internal) { + // User code is already advertising. + raise_zephyr_error(-EALREADY); + } + // The workflow is advertising. Stop it so user code can take over. + common_hal_bleio_adapter_stop_advertising(self); + } + + uint32_t status = _common_hal_bleio_adapter_start_advertising(self, + connectable, + anonymous, + timeout, + interval, + advertising_data_bufinfo->buf, + advertising_data_bufinfo->len, + scan_response_data_bufinfo->buf, + scan_response_data_bufinfo->len, + tx_power, + directed_to); + if (status == (uint32_t)EINVAL) { + mp_raise_ValueError(MP_ERROR_TEXT("Invalid advertising data")); + } + if (status != 0) { + raise_zephyr_error(-(int)status); + } + + // Mark as user-owned so the workflow won't clobber it. + ble_advertising_internal = false; +} + +void common_hal_bleio_adapter_stop_advertising(bleio_adapter_obj_t *self) { + (void)self; + if (!ble_advertising) { + return; + } + bt_le_adv_stop(); + ble_advertising = false; + ble_advertising_internal = false; +} + +bool common_hal_bleio_adapter_get_advertising(bleio_adapter_obj_t *self) { + (void)self; + return ble_advertising; +} + +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) { + (void)extended; + + if (self->scan_results != NULL) { + if (!shared_module_bleio_scanresults_get_done(self->scan_results)) { + common_hal_bleio_adapter_stop_scan(self); + } else { + self->scan_results = NULL; + } + } + + int err = 0; + + self->scan_results = shared_module_bleio_new_scanresults(buffer_size, prefixes, prefix_length, minimum_rssi); + active_scan_results = self->scan_results; + + if (!scan_callbacks_registered) { + scan_callbacks.recv = scan_recv_cb; + scan_callbacks.timeout = scan_timeout_cb; + err = bt_le_scan_cb_register(&scan_callbacks); + if (err != 0) { + self->scan_results = NULL; + active_scan_results = NULL; + raise_zephyr_error(err); + } + scan_callbacks_registered = true; + } + + uint16_t interval_units = (uint16_t)((interval / 0.000625f) + 0.5f); + uint16_t window_units = (uint16_t)((window / 0.000625f) + 0.5f); + uint16_t timeout_units = bleio_validate_and_convert_timeout(timeout); + + struct bt_le_scan_param scan_params = { + .type = active ? BT_LE_SCAN_TYPE_ACTIVE : BT_LE_SCAN_TYPE_PASSIVE, + /* Do not filter duplicates: the application merges advertisement and + * scan-response packets and needs to observe updated advertisements + * from the same device (e.g. when user code replaces the workflow + * advert). */ + .options = 0, + .interval = interval_units, + .window = window_units, + .timeout = (uint16_t)timeout_units, + .interval_coded = 0, + .window_coded = 0, + }; + + err = bt_le_scan_start(&scan_params, NULL); + if (err != 0) { + self->scan_results = NULL; + active_scan_results = NULL; + raise_zephyr_error(err); + } + + return MP_OBJ_FROM_PTR(self->scan_results); +} + +void common_hal_bleio_adapter_stop_scan(bleio_adapter_obj_t *self) { + if (self->scan_results == NULL) { + return; + } + bt_le_scan_stop(); + shared_module_bleio_scanresults_set_done(self->scan_results, true); + active_scan_results = NULL; + self->scan_results = NULL; +} + +bool common_hal_bleio_adapter_get_connected(bleio_adapter_obj_t *self) { + if (!ble_adapter_enabled) { + return false; + } + + for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) { + if (bleio_connections[i].conn != NULL) { + return true; + } + } + + return false; +} + +mp_obj_t common_hal_bleio_adapter_get_connections(bleio_adapter_obj_t *self) { + if (!ble_adapter_enabled) { + self->connection_objs = NULL; + return mp_const_empty_tuple; + } + + if (self->connection_objs != NULL) { + return self->connection_objs; + } + + size_t total_connected = 0; + mp_obj_t items[BLEIO_TOTAL_CONNECTION_COUNT]; + for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) { + bleio_connection_internal_t *connection = &bleio_connections[i]; + if (connection->conn == NULL) { + continue; + } + + if (connection->connection_obj == mp_const_none) { + connection->connection_obj = bleio_connection_new_from_internal(connection); + } + + items[total_connected] = connection->connection_obj; + total_connected++; + } + + self->connection_objs = mp_obj_new_tuple(total_connected, items); + return self->connection_objs; +} + +mp_obj_t common_hal_bleio_adapter_connect(bleio_adapter_obj_t *self, bleio_address_obj_t *address, mp_float_t timeout) { + common_hal_bleio_adapter_stop_scan(self); + + const uint16_t timeout_units = bleio_validate_and_convert_timeout(timeout); + + bt_addr_le_t peer = { + .type = bleio_address_type_to_zephyr(address->type), + }; + memcpy(peer.a.val, address->bytes, NUM_BLEIO_ADDRESS_BYTES); + + struct bt_conn_le_create_param create_params = BT_CONN_LE_CREATE_PARAM_INIT( + BT_CONN_LE_OPT_NONE, + BT_GAP_SCAN_FAST_INTERVAL, + BT_GAP_SCAN_FAST_INTERVAL); + create_params.timeout = timeout_units; + + struct bt_conn *conn = NULL; + int err = bt_conn_le_create(&peer, &create_params, BT_LE_CONN_PARAM_DEFAULT, &conn); + if (err != 0) { + raise_zephyr_error(err); + } + + while (true) { + struct bt_conn_info info; + err = bt_conn_get_info(conn, &info); + if (err == 0) { + if (info.state == BT_CONN_STATE_CONNECTED) { + break; + } + + if (info.state == BT_CONN_STATE_DISCONNECTED) { + bt_conn_unref(conn); + mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Failed to connect: timeout")); + } + } else if (err != -ENOTCONN) { + bt_conn_unref(conn); + raise_zephyr_error(err); + } + + RUN_BACKGROUND_TASKS; + } + + bleio_connection_internal_t *connection = bleio_connection_find_by_conn(conn); + if (connection == NULL) { + connection = bleio_connection_track(conn); + } + + if (connection == NULL) { + bt_conn_unref(conn); + mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Failed to connect: internal error")); + } + + // bt_conn_le_create() gave us a ref in `conn`; `connection` keeps its own + // ref via bleio_connection_track(). Drop the create ref now. + bt_conn_unref(conn); + + // Only user code connects in the central role. + connection->user_owned = true; + + self->connection_objs = NULL; + return bleio_connection_new_from_internal(connection); +} + +struct bond_collect_ctx { + bt_addr_le_t *addrs; + size_t *count; + size_t max; +}; + +static void bond_iterator_collect(const struct bt_bond_info *info, void *user_data) { + struct bond_collect_ctx *ctx = (struct bond_collect_ctx *)user_data; + if (*ctx->count < ctx->max) { + bt_addr_le_copy(&ctx->addrs[*ctx->count], &info->addr); + (*ctx->count)++; + } +} + +static void bond_iterator_check(const struct bt_bond_info *info, void *user_data) { + (void)info; + bool *has_bonds = (bool *)user_data; + *has_bonds = true; +} + +void common_hal_bleio_adapter_erase_bonding(bleio_adapter_obj_t *self) { + // Can be called from Python as _bleio.adapter.erase_bonding(), and from + // supervisor_bluetooth_init() on a discovery-mode boot, before the adapter is + // enabled. Bond keys are only visible once the stack is up and settings are + // loaded; without this the loop below finds nothing and the bond reappears + // when the workflow starts. The workflow call runs before the VM, so a failure + // to start the stack is ignored here rather than raised. + if (bleio_adapter_ensure_stack_ready() != 0) { + return; + } + + // Unpair all bonded devices for all local identities. + for (uint8_t id = 0; id < CONFIG_BT_ID_MAX; id++) { + // bt_unpair takes an addr; use bt_foreach_bond to iterate and unpair. + // We need to collect addresses first since we can't unpair during iteration. + bt_addr_le_t addrs[CONFIG_BT_MAX_PAIRED]; + size_t addr_count = 0; + + bt_foreach_bond(id, bond_iterator_collect, &(struct bond_collect_ctx) { + .addrs = addrs, + .count = &addr_count, + .max = CONFIG_BT_MAX_PAIRED + }); + + for (size_t i = 0; i < addr_count; i++) { + bt_unpair(id, &addrs[i]); + } + } + + // Reset pairing state on all connections + for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) { + bleio_connections[i].pair_status = PAIR_NOT_PAIRED; + bleio_connections[i].sec_err = 0; + } +} + +bool common_hal_bleio_adapter_is_bonded_to_central(bleio_adapter_obj_t *self) { + // Called only by the BLE workflow, from supervisor_bluetooth_init() before + // the adapter is enabled and from supervisor_bluetooth_background(); see + // erase_bonding() above. Runs before the VM, so don't raise. + if (bleio_adapter_ensure_stack_ready() != 0) { + return false; + } + + // Check if any bond exists for any local identity. + for (uint8_t id = 0; id < CONFIG_BT_ID_MAX; id++) { + bool has_bonds = false; + bt_foreach_bond(id, bond_iterator_check, &has_bonds); + if (has_bonds) { + return true; + } + } + return false; +} + +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)); +} + +bleio_adapter_obj_t *common_hal_bleio_allocate_adapter_or_raise(void) { + return &common_hal_bleio_adapter_obj; +} + +uint16_t bleio_adapter_get_name(char *buf, uint16_t len) { + const char *name = bt_get_name(); + uint16_t full_len = strlen(name); + if (len > 0) { + uint16_t copy_len = len < full_len ? len : full_len; + memcpy(buf, name, copy_len); + } + return full_len; +} diff --git a/ports/zephyr-cp/common-hal/_bleio/Adapter.h b/ports/zephyr-cp/common-hal/_bleio/Adapter.h new file mode 100644 index 00000000000..ba84e810bfe --- /dev/null +++ b/ports/zephyr-cp/common-hal/_bleio/Adapter.h @@ -0,0 +1,37 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018 Dan Halbert for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" +#include "py/objtuple.h" + +#include "shared-bindings/_bleio/Address.h" +#include "shared-bindings/_bleio/Connection.h" +#include "shared-bindings/_bleio/ScanResults.h" + +#define BLEIO_TOTAL_CONNECTION_COUNT CONFIG_BT_MAX_CONN + +extern bleio_connection_internal_t bleio_connections[BLEIO_TOTAL_CONNECTION_COUNT]; + +typedef struct { + mp_obj_base_t base; + bleio_scanresults_obj_t *scan_results; + mp_obj_t name; + mp_obj_tuple_t *connection_objs; + bool user_advertising; + // Cached local address returned by common_hal_bleio_adapter_get_address(). + // Stored inline so it never needs to allocate, even when read before the + // heap is available (e.g. from bleio_adapter_reset_name). + bleio_address_obj_t address; +} bleio_adapter_obj_t; + +void bleio_adapter_gc_collect(bleio_adapter_obj_t *adapter); + +// Queue a background run of supervisor_bluetooth_background() so the VM drains +// incoming BLE PacketBuffer data. Safe to call from Zephyr BT/workqueue context. +void bleio_request_bluetooth_background(void); diff --git a/ports/zephyr-cp/common-hal/_bleio/Attribute.c b/ports/zephyr-cp/common-hal/_bleio/Attribute.c new file mode 100644 index 00000000000..6312f3d46b8 --- /dev/null +++ b/ports/zephyr-cp/common-hal/_bleio/Attribute.c @@ -0,0 +1,8 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018 Dan Halbert for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// Attribute is defined in shared-module, no port-specific implementation needed diff --git a/ports/zephyr-cp/common-hal/_bleio/Attribute.h b/ports/zephyr-cp/common-hal/_bleio/Attribute.h new file mode 100644 index 00000000000..24b0f78a106 --- /dev/null +++ b/ports/zephyr-cp/common-hal/_bleio/Attribute.h @@ -0,0 +1,10 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018 Dan Halbert for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-module/_bleio/Attribute.h" diff --git a/ports/zephyr-cp/common-hal/_bleio/Characteristic.c b/ports/zephyr-cp/common-hal/_bleio/Characteristic.c new file mode 100644 index 00000000000..e1ba8b7349f --- /dev/null +++ b/ports/zephyr-cp/common-hal/_bleio/Characteristic.c @@ -0,0 +1,413 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Dan Halbert for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include + +#include +#include +#include + +#include "py/runtime.h" +#include "py/gc.h" +#include "bindings/zephyr_kernel/__init__.h" +#include "shared-bindings/_bleio/__init__.h" +#include "shared-bindings/_bleio/Characteristic.h" +#include "shared-bindings/_bleio/Descriptor.h" +#include "shared-bindings/_bleio/Service.h" +#include "shared-bindings/_bleio/UUID.h" +#include "common-hal/_bleio/__init__.h" +#include "common-hal/_bleio/CharacteristicBuffer.h" +#include "common-hal/_bleio/Connection.h" +#include "common-hal/_bleio/UUID.h" +#include "common-hal/_bleio/PacketBuffer.h" +#include "shared-bindings/_bleio/CharacteristicBuffer.h" +#include "shared-bindings/_bleio/PacketBuffer.h" +#include "supervisor/port_heap.h" + +// CCCD write callback — captures the subscribing connection for PacketBuffer. +ssize_t bleio_ccc_write_cb(struct bt_conn *conn, + const struct bt_gatt_attr *attr, uint16_t value) { + struct bt_gatt_ccc_managed_user_data *ccc_data = + (struct bt_gatt_ccc_managed_user_data *)attr->user_data; + bleio_characteristic_obj_t *characteristic = + (bleio_characteristic_obj_t *)((char *)ccc_data + - offsetof(bleio_characteristic_obj_t, zephyr_ccc)); + + if (characteristic->observer != mp_const_none && + mp_obj_is_type(characteristic->observer, &bleio_packet_buffer_type)) { + bleio_packet_buffer_set_conn( + MP_OBJ_TO_PTR(characteristic->observer), + value != 0 ? conn : NULL); + } + return sizeof(value); +} + +uint16_t bleio_security_to_zephyr_perm( + bleio_attribute_security_mode_t read_perm, + bleio_attribute_security_mode_t write_perm, + bleio_characteristic_properties_t props) { + uint16_t perm = 0; + + if (props & CHAR_PROP_READ) { + switch (read_perm) { + case SECURITY_MODE_OPEN: + perm |= BT_GATT_PERM_READ; + break; + case SECURITY_MODE_ENC_NO_MITM: + perm |= BT_GATT_PERM_READ_ENCRYPT; + break; + case SECURITY_MODE_ENC_WITH_MITM: + perm |= BT_GATT_PERM_READ_AUTHEN; + break; + case SECURITY_MODE_LESC_ENC_WITH_MITM: + perm |= BT_GATT_PERM_READ_LESC; + break; + default: + break; + } + } + + if (props & (CHAR_PROP_WRITE | CHAR_PROP_WRITE_NO_RESPONSE)) { + switch (write_perm) { + case SECURITY_MODE_OPEN: + perm |= BT_GATT_PERM_WRITE; + break; + case SECURITY_MODE_ENC_NO_MITM: + perm |= BT_GATT_PERM_WRITE_ENCRYPT; + break; + case SECURITY_MODE_ENC_WITH_MITM: + perm |= BT_GATT_PERM_WRITE_AUTHEN; + break; + case SECURITY_MODE_LESC_ENC_WITH_MITM: + perm |= BT_GATT_PERM_WRITE_LESC; + break; + default: + break; + } + } + + return perm; +} + +ssize_t bleio_char_read_cb(struct bt_conn *conn, + const struct bt_gatt_attr *attr, void *buf, uint16_t len, uint16_t offset) { + bleio_characteristic_obj_t *self = attr->user_data; + (void)conn; + return bt_gatt_attr_read(conn, attr, buf, len, offset, + self->current_value, self->current_value_len); +} + +ssize_t bleio_char_write_cb(struct bt_conn *conn, + const struct bt_gatt_attr *attr, const void *buf, uint16_t len, + uint16_t offset, uint8_t flags) { + bleio_characteristic_obj_t *self = attr->user_data; + (void)flags; + if (offset + len > self->max_length) { + return BT_GATT_ERR(BT_ATT_ERR_INVALID_OFFSET); + } + memcpy(self->current_value + offset, buf, len); + if (offset + len > self->current_value_len) { + self->current_value_len = offset + len; + } + + // Notify any observer (e.g., CharacteristicBuffer, PacketBuffer) of the write. + if (self->observer != mp_const_none) { + if (mp_obj_is_type(self->observer, &bleio_characteristic_buffer_type)) { + bleio_characteristic_buffer_extend(MP_OBJ_TO_PTR(self->observer), buf, len); + } else if (mp_obj_is_type(self->observer, &bleio_packet_buffer_type)) { + bleio_packet_buffer_extend(MP_OBJ_TO_PTR(self->observer), conn, buf, len); + } + } + + return len; +} + +void bleio_ccc_changed_cb(const struct bt_gatt_attr *attr, uint16_t value) { + // Track subscription state if needed in the future. + (void)attr; + (void)value; +} + +bleio_characteristic_properties_t common_hal_bleio_characteristic_get_properties(bleio_characteristic_obj_t *self) { + return self->props; +} + +mp_obj_tuple_t *common_hal_bleio_characteristic_get_descriptors(bleio_characteristic_obj_t *self) { + if (self->descriptor_list == NULL) { + return mp_const_empty_tuple; + } + return mp_obj_new_tuple(self->descriptor_list->len, self->descriptor_list->items); +} + +bleio_service_obj_t *common_hal_bleio_characteristic_get_service(bleio_characteristic_obj_t *self) { + return self->service; +} + +bleio_uuid_obj_t *common_hal_bleio_characteristic_get_uuid(bleio_characteristic_obj_t *self) { + return self->uuid; +} + +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) { + if (self->service != NULL && self->service->is_remote) { + // Remote characteristic: read via GATT client + bleio_connection_obj_t *connection = MP_OBJ_TO_PTR(self->service->connection); + if (connection == NULL || connection->connection == NULL || + connection->connection->conn == NULL) { + mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Not connected")); + } + + return bleio_gattc_read_sync(connection->connection->conn, + self->handle, buf, len); + } + + // Local characteristic + size_t copy_len = self->current_value_len; + if (copy_len > len) { + copy_len = len; + } + memcpy(buf, self->current_value, copy_len); + return copy_len; +} + +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, + const char *user_description) { + + self->service = service; + self->uuid = uuid; + self->handle = handle; + self->props = props; + self->read_perm = read_perm; + self->write_perm = write_perm; + self->max_length = max_length; + self->fixed_length = fixed_length; + self->observer = mp_const_none; + // The descriptor list is an mp_obj (GC object). When constructed before + // gc_init() (e.g. the BLE workflow at boot), the GC heap isn't available, + // so leave it NULL and lazily create it on first use. Matches the nordic + // port's handling. + if (gc_alloc_possible()) { + self->descriptor_list = mp_obj_new_list(0, NULL); + } else { + self->descriptor_list = NULL; + } + + // Allocate value buffer + self->current_value = port_malloc(max_length, false); + memset(self->current_value, 0, max_length); + self->current_value_alloc = max_length; + self->current_value_len = 0; + + // Copy initial value if provided + if (initial_value_bufinfo != NULL && initial_value_bufinfo->len > 0) { + size_t len = initial_value_bufinfo->len; + if (len > (size_t)max_length) { + len = max_length; + } + memcpy(self->current_value, initial_value_bufinfo->buf, len); + self->current_value_len = len; + } + + // Convert UUID to Zephyr format + bleio_uuid_to_zephyr(uuid, &self->zephyr_uuid); + + if (service->is_remote) { + // Remote characteristic: just add to the service's list + mp_obj_list_append(MP_OBJ_FROM_PTR(service->characteristic_list), + MP_OBJ_FROM_PTR(self)); + } else { + common_hal_bleio_service_add_characteristic(service, self, + initial_value_bufinfo, user_description); + + // Create a Descriptor object for user_description (CUD 0x2901) + if (user_description != NULL && user_description[0] != '\0') { + bleio_uuid_obj_t *desc_uuid = mp_obj_malloc(bleio_uuid_obj_t, &bleio_uuid_type); + common_hal_bleio_uuid_construct(desc_uuid, 0x2901, NULL); + + bleio_descriptor_obj_t *descriptor = mp_obj_malloc(bleio_descriptor_obj_t, &bleio_descriptor_type); + + size_t desc_len = strlen(user_description); + mp_buffer_info_t desc_bufinfo = { + .buf = (void *)user_description, + .len = desc_len, + }; + + common_hal_bleio_descriptor_construct( + descriptor, self, desc_uuid, + SECURITY_MODE_OPEN, SECURITY_MODE_OPEN, + desc_len, false, &desc_bufinfo); + + common_hal_bleio_characteristic_add_descriptor(self, descriptor); + } + } +} + +bool common_hal_bleio_characteristic_deinited(bleio_characteristic_obj_t *self) { + return self->service == NULL; +} + +void common_hal_bleio_characteristic_deinit(bleio_characteristic_obj_t *self) { + // Nothing to do - service handles unregistration + if (self->current_value != NULL) { + port_free(self->current_value); + self->current_value = NULL; + self->current_value_alloc = 0; + self->current_value_len = 0; + } +} + +// Struct for tracking GATT notification subscriptions on remote characteristics. +typedef struct { + struct bt_gatt_subscribe_params params; + uint16_t value_handle; + uint16_t ccc_handle; + bleio_characteristic_obj_t *characteristic; + volatile bool subscribed; +} zephyr_subscription_t; + +static uint8_t on_gattc_notify(struct bt_conn *conn, + struct bt_gatt_subscribe_params *params, + const void *data, uint16_t length) { + zephyr_subscription_t *sub = CONTAINER_OF(params, zephyr_subscription_t, params); + if (sub->characteristic != NULL && + sub->characteristic->observer != mp_const_none) { + if (mp_obj_is_type(sub->characteristic->observer, &bleio_characteristic_buffer_type)) { + bleio_characteristic_buffer_extend( + MP_OBJ_TO_PTR(sub->characteristic->observer), data, length); + } else if (mp_obj_is_type(sub->characteristic->observer, &bleio_packet_buffer_type)) { + bleio_packet_buffer_extend( + MP_OBJ_TO_PTR(sub->characteristic->observer), conn, data, length); + } + } + return BT_GATT_ITER_CONTINUE; +} + +void common_hal_bleio_characteristic_set_cccd(bleio_characteristic_obj_t *self, bool notify, bool indicate) { + // Only valid for remote characteristics (client-side). + if (self->service == NULL || !self->service->is_remote) { + return; + } + + bleio_connection_obj_t *connection_obj = MP_OBJ_TO_PTR(self->service->connection); + if (connection_obj == NULL || connection_obj->connection == NULL || + connection_obj->connection->conn == NULL) { + mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Not connected")); + } + + struct bt_conn *conn = connection_obj->connection->conn; + + if (!notify && !indicate) { + // Unsubscribe from any existing subscription. + // We don't track subscriptions per-characteristic yet, + // so just return for now. + return; + } + + if (self->cccd_handle == 0) { + mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("No CCCD for this Characteristic")); + } + + // Allocate subscription tracking from port heap (won't move on GC). + // Note: Simplified - we allocate a new subscription each time. + // A production implementation would track and reuse subscriptions. + zephyr_subscription_t *sub = port_malloc(sizeof(zephyr_subscription_t), false); + if (sub == NULL) { + mp_raise_msg(&mp_type_MemoryError, NULL); + } + + // Zero-initialize the entire structure so that unset fields + // (subscribe, flags, discover_params, work_q, node) are NULL/0 + // rather than garbage from the heap. bt_gatt_subscribe checks + // subscribe==NULL to decide whether to do a synchronous write. + memset(sub, 0, sizeof(zephyr_subscription_t)); + + sub->characteristic = self; + sub->value_handle = self->handle; + sub->ccc_handle = self->cccd_handle; + sub->subscribed = false; + + sub->params.notify = on_gattc_notify; + sub->params.value_handle = self->handle; + sub->params.ccc_handle = self->cccd_handle; + sub->params.value = notify ? BT_GATT_CCC_NOTIFY : BT_GATT_CCC_INDICATE; + + int err = bt_gatt_subscribe(conn, &sub->params); + if (err != 0) { + port_free(sub); + raise_zephyr_error(err); + } + sub->subscribed = true; +} + +void common_hal_bleio_characteristic_set_value(bleio_characteristic_obj_t *self, mp_buffer_info_t *bufinfo) { + if (self->service != NULL && self->service->is_remote) { + // Remote characteristic: write via GATT client + bleio_connection_obj_t *connection = MP_OBJ_TO_PTR(self->service->connection); + if (connection == NULL || connection->connection == NULL || + connection->connection->conn == NULL) { + mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Not connected")); + } + + if (self->props & CHAR_PROP_WRITE_NO_RESPONSE) { + int err = bt_gatt_write_without_response( + connection->connection->conn, + self->handle, + bufinfo->buf, bufinfo->len, false); + if (err != 0) { + raise_zephyr_error(err); + } + } else { + bleio_gattc_write_sync(connection->connection->conn, + self->handle, bufinfo->buf, bufinfo->len); + } + return; + } + + // Local characteristic + size_t len = bufinfo->len; + if (len > self->max_length) { + len = self->max_length; + } + memcpy(self->current_value, bufinfo->buf, len); + self->current_value_len = len; + + // If NOTIFY and service is registered, send notification + if ((self->props & CHAR_PROP_NOTIFY) && self->service != NULL && + self->service->registered) { + bt_gatt_notify(NULL, &self->service->attrs[self->value_attr_index], + self->current_value, self->current_value_len); + } +} + +void common_hal_bleio_characteristic_add_descriptor(bleio_characteristic_obj_t *self, + bleio_descriptor_obj_t *descriptor) { + if (self->descriptor_list == NULL) { + self->descriptor_list = mp_obj_new_list(0, NULL); + } + mp_obj_list_append(MP_OBJ_FROM_PTR(self->descriptor_list), + MP_OBJ_FROM_PTR(descriptor)); + // Descriptors added after characteristic construction would need + // service re-registration; for now the common case is handled by + // Service.add_characteristic which adds descriptors at registration time. +} + +void bleio_characteristic_set_observer(bleio_characteristic_obj_t *self, mp_obj_t observer) { + self->observer = observer; +} + +void bleio_characteristic_clear_observer(bleio_characteristic_obj_t *self) { + self->observer = mp_const_none; +} diff --git a/ports/zephyr-cp/common-hal/_bleio/Characteristic.h b/ports/zephyr-cp/common-hal/_bleio/Characteristic.h new file mode 100644 index 00000000000..f4a578c888a --- /dev/null +++ b/ports/zephyr-cp/common-hal/_bleio/Characteristic.h @@ -0,0 +1,63 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Dan Halbert for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include + +#include "py/obj.h" +#include "py/objlist.h" +#include "shared-bindings/_bleio/Attribute.h" +#include "shared-module/_bleio/Characteristic.h" +#include "common-hal/_bleio/Descriptor.h" +#include "common-hal/_bleio/Service.h" +#include "common-hal/_bleio/UUID.h" + +typedef struct _bleio_characteristic_obj { + mp_obj_base_t base; + bleio_service_obj_t *service; + bleio_uuid_obj_t *uuid; + mp_obj_t observer; + uint8_t *current_value; + uint16_t current_value_len; + uint16_t current_value_alloc; + uint16_t max_length; + uint16_t def_handle; + uint16_t handle; + bleio_characteristic_properties_t props; + bleio_attribute_security_mode_t read_perm; + bleio_attribute_security_mode_t write_perm; + mp_obj_list_t *descriptor_list; + uint16_t user_desc_handle; + uint16_t cccd_handle; + uint16_t sccd_handle; + bool fixed_length; + // Zephyr GATT server fields: + struct bt_gatt_chrc zephyr_chrc; + struct bt_uuid_128 zephyr_uuid; + struct bt_gatt_ccc_managed_user_data zephyr_ccc; + size_t value_attr_index; // index in service attrs for notify +} bleio_characteristic_obj_t; + +void bleio_characteristic_set_observer(bleio_characteristic_obj_t *self, mp_obj_t observer); +void bleio_characteristic_clear_observer(bleio_characteristic_obj_t *self); + +// Callbacks used by Service.c when building GATT attr table +ssize_t bleio_char_read_cb(struct bt_conn *conn, + const struct bt_gatt_attr *attr, void *buf, uint16_t len, uint16_t offset); +ssize_t bleio_char_write_cb(struct bt_conn *conn, + const struct bt_gatt_attr *attr, const void *buf, uint16_t len, + uint16_t offset, uint8_t flags); +void bleio_ccc_changed_cb(const struct bt_gatt_attr *attr, uint16_t value); +ssize_t bleio_ccc_write_cb(struct bt_conn *conn, + const struct bt_gatt_attr *attr, uint16_t value); + +// Permission mapping helper +uint16_t bleio_security_to_zephyr_perm( + bleio_attribute_security_mode_t read_perm, + bleio_attribute_security_mode_t write_perm, + bleio_characteristic_properties_t props); diff --git a/ports/zephyr-cp/common-hal/_bleio/CharacteristicBuffer.c b/ports/zephyr-cp/common-hal/_bleio/CharacteristicBuffer.c new file mode 100644 index 00000000000..5b96b841d55 --- /dev/null +++ b/ports/zephyr-cp/common-hal/_bleio/CharacteristicBuffer.c @@ -0,0 +1,142 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Dan Halbert for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include +#include + +#include + +#include "py/runtime.h" +#include "py/stream.h" + +#include "shared/runtime/interrupt_char.h" + +#include "shared-bindings/_bleio/__init__.h" +#include "shared-bindings/_bleio/Connection.h" +#include "shared-bindings/_bleio/CharacteristicBuffer.h" + +#include "supervisor/shared/tick.h" + +#include "common-hal/_bleio/Adapter.h" + +#include "common-hal/_bleio/CharacteristicBuffer.h" +#include "common-hal/_bleio/Characteristic.h" + +// Zephyr's ring_buf is safe for single-producer/single-consumer without +// locks. The GATT callbacks (system workqueue) are the sole producer; +// the CircuitPython VM (main thread) is the sole consumer. + +// Called from Zephyr GATT callbacks (system workqueue context). +void bleio_characteristic_buffer_extend(bleio_characteristic_buffer_obj_t *self, + const uint8_t *data, size_t len) { + if (self->watch_for_interrupt_char) { + for (size_t i = 0; i < len; i++) { + if (data[i] == mp_interrupt_char) { + mp_sched_keyboard_interrupt(); + ring_buf_reset(&self->ringbuf); + } else { + ring_buf_put(&self->ringbuf, &data[i], 1); + } + } + } else { + ring_buf_put(&self->ringbuf, data, len); + } + // Wake the main task so it can service the new RX data instead of + // sleeping out its full timeout. This is what makes the "Press any key" + // wait end early when REPL input arrives over the BLE serial service. + bleio_request_bluetooth_background(); +} + +void _common_hal_bleio_characteristic_buffer_construct(bleio_characteristic_buffer_obj_t *self, + bleio_characteristic_obj_t *characteristic, + mp_float_t timeout, + uint8_t *buffer, size_t buffer_size, + void *static_handler_entry, + bool watch_for_interrupt_char) { + + self->characteristic = characteristic; + self->timeout_ms = timeout * 1000; + self->watch_for_interrupt_char = watch_for_interrupt_char; + self->ringbuf_data = buffer; + ring_buf_init(&self->ringbuf, buffer_size, buffer); + + // Set ourselves as the characteristic's observer so we receive + // incoming writes (local) and notifications (remote). + bleio_characteristic_set_observer(characteristic, MP_OBJ_FROM_PTR(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) { + uint8_t *buffer = m_malloc_without_collect(buffer_size); + _common_hal_bleio_characteristic_buffer_construct(self, characteristic, timeout, + buffer, buffer_size, NULL, false); +} + +uint32_t common_hal_bleio_characteristic_buffer_read(bleio_characteristic_buffer_obj_t *self, + uint8_t *data, size_t len, int *errcode) { + uint64_t start_ticks = supervisor_ticks_ms64(); + + // Wait for all bytes received or timeout + while ((ring_buf_size_get(&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()) { + return 0; + } + } + + return ring_buf_get(&self->ringbuf, data, len); +} + +uint32_t common_hal_bleio_characteristic_buffer_rx_characters_available( + bleio_characteristic_buffer_obj_t *self) { + return ring_buf_size_get(&self->ringbuf); +} + +void common_hal_bleio_characteristic_buffer_clear_rx_buffer( + bleio_characteristic_buffer_obj_t *self) { + ring_buf_reset(&self->ringbuf); +} + +bool common_hal_bleio_characteristic_buffer_deinited(bleio_characteristic_buffer_obj_t *self) { + return self->characteristic == NULL; +} + +void common_hal_bleio_characteristic_buffer_deinit(bleio_characteristic_buffer_obj_t *self) { + if (common_hal_bleio_characteristic_buffer_deinited(self)) { + return; + } + bleio_characteristic_clear_observer(self->characteristic); + self->characteristic = NULL; + // ringbuf_data was allocated with m_malloc_without_collect; free it. + m_free(self->ringbuf_data); + self->ringbuf_data = NULL; +} + +bool common_hal_bleio_characteristic_buffer_connected(bleio_characteristic_buffer_obj_t *self) { + bleio_characteristic_obj_t *characteristic = self->characteristic; + if (characteristic == NULL || characteristic->service == NULL) { + return false; + } + + if (!characteristic->service->is_remote) { + // Local service: we're always "connected" as long as the service exists. + return true; + } + + // Remote service: check if the connection is still active. + if (characteristic->service->connection == mp_const_none) { + return false; + } + bleio_connection_obj_t *connection = + MP_OBJ_TO_PTR(characteristic->service->connection); + return common_hal_bleio_connection_get_connected(connection); +} diff --git a/ports/zephyr-cp/common-hal/_bleio/CharacteristicBuffer.h b/ports/zephyr-cp/common-hal/_bleio/CharacteristicBuffer.h new file mode 100644 index 00000000000..85a5d253be2 --- /dev/null +++ b/ports/zephyr-cp/common-hal/_bleio/CharacteristicBuffer.h @@ -0,0 +1,29 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Dan Halbert for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include + +#include + +#include "py/obj.h" +#include "shared-bindings/_bleio/Characteristic.h" + +typedef struct { + mp_obj_base_t base; + bleio_characteristic_obj_t *characteristic; + uint32_t timeout_ms; + struct ring_buf ringbuf; + uint8_t *ringbuf_data; + bool watch_for_interrupt_char; +} bleio_characteristic_buffer_obj_t; + +// Called from GATT callbacks (system workqueue context) to push +// data into the CharacteristicBuffer ring buffer. +void bleio_characteristic_buffer_extend(bleio_characteristic_buffer_obj_t *self, + const uint8_t *data, size_t len); diff --git a/ports/zephyr-cp/common-hal/_bleio/Connection.c b/ports/zephyr-cp/common-hal/_bleio/Connection.c new file mode 100644 index 00000000000..12b2a8efe5f --- /dev/null +++ b/ports/zephyr-cp/common-hal/_bleio/Connection.c @@ -0,0 +1,738 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Dan Halbert for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include +#include + +#include +#include +#include +#include + +#include "py/runtime.h" +#include "shared/runtime/interrupt_char.h" +#include "bindings/zephyr_kernel/__init__.h" +#include "shared-bindings/_bleio/__init__.h" +#include "shared-bindings/_bleio/Characteristic.h" +#include "shared-bindings/_bleio/Connection.h" +#include "shared-bindings/_bleio/Descriptor.h" +#include "shared-bindings/_bleio/Service.h" +#include "shared-bindings/_bleio/UUID.h" +#include "common-hal/_bleio/__init__.h" +#include "common-hal/_bleio/Characteristic.h" +#include "supervisor/port_heap.h" + +// Discovery context passed through Zephyr callbacks. +typedef struct { + volatile bool done; + volatile int err; +} discovery_context_t; + +// Convert a Zephyr bt_uuid to a CircuitPython bleio UUID object. +// Must be called OUTSIDE Zephyr callback context. +static bleio_uuid_obj_t *bleio_uuid_from_zephyr(const struct bt_uuid *zuuid) { + bleio_uuid_obj_t *uuid = mp_obj_malloc(bleio_uuid_obj_t, &bleio_uuid_type); + if (zuuid->type == BT_UUID_TYPE_16) { + common_hal_bleio_uuid_construct(uuid, BT_UUID_16(zuuid)->val, NULL); + } else { + // Both Zephyr and CP store UUID bytes in little-endian order. + const struct bt_uuid_128 *uuid128 = BT_UUID_128(zuuid); + common_hal_bleio_uuid_construct(uuid, + (uuid128->val[13] << 8) | uuid128->val[12], uuid128->val); + } + return uuid; +} + +// Temporary storage for discovered services before creating CP objects. +// Each node is port_malloc'd in the callback and appended to a sys_slist. +typedef struct { + sys_snode_t node; + struct bt_uuid_128 uuid; + uint16_t start_handle; + uint16_t end_handle; +} discovered_service_t; + +// Temporary storage for discovered characteristics before creating CP objects. +typedef struct { + sys_snode_t node; + struct bt_uuid_128 uuid; + uint16_t value_handle; + uint16_t decl_handle; + uint8_t properties; +} discovered_char_t; + +// Temporary storage for discovered descriptors. +typedef struct { + sys_snode_t node; + struct bt_uuid_128 uuid; + uint16_t handle; +} discovered_desc_t; + +// File-scope discovery state for synchronous blocking. +static discovery_context_t *active_discovery_ctx; +static sys_slist_t discovered_list; +static struct bt_gatt_discover_params discovery_params; + +// Called from the disconnect callback (BT workqueue context) to abort any +// in-flight GATT discovery. Without this the main thread's spin loop would +// hang waiting for a callback that will never come, and the caller would then +// NULL-dereference the now-cleared connection in bt_gatt_discover(). +void bleio_connection_discovery_abort(void) { + discovery_context_t *ctx = active_discovery_ctx; + if (ctx != NULL) { + ctx->err = -ENOTCONN; + ctx->done = true; + } +} + +static uint8_t on_service_discovered(struct bt_conn *conn, + const struct bt_gatt_attr *attr, + struct bt_gatt_discover_params *params) { + discovery_context_t *ctx = active_discovery_ctx; + + if (attr == NULL) { + ctx->done = true; + return BT_GATT_ITER_STOP; + } + + discovered_service_t *ds = port_malloc(sizeof(discovered_service_t), false); + if (ds == NULL) { + ctx->done = true; + return BT_GATT_ITER_STOP; + } + + struct bt_gatt_service_val *svc_val = (struct bt_gatt_service_val *)attr->user_data; + ds->start_handle = attr->handle; + ds->end_handle = svc_val->end_handle; + + // Copy UUID into our storage + if (svc_val->uuid->type == BT_UUID_TYPE_16) { + ds->uuid.uuid.type = BT_UUID_TYPE_16; + ((struct bt_uuid_16 *)&ds->uuid)->val = BT_UUID_16(svc_val->uuid)->val; + } else { + memcpy(&ds->uuid, svc_val->uuid, sizeof(struct bt_uuid_128)); + } + + sys_slist_append(&discovered_list, &ds->node); + + return BT_GATT_ITER_CONTINUE; +} + +static uint8_t on_characteristic_discovered(struct bt_conn *conn, + const struct bt_gatt_attr *attr, + struct bt_gatt_discover_params *params) { + discovery_context_t *ctx = active_discovery_ctx; + + if (attr == NULL) { + ctx->done = true; + return BT_GATT_ITER_STOP; + } + + discovered_char_t *dc = port_malloc(sizeof(discovered_char_t), false); + if (dc == NULL) { + ctx->done = true; + return BT_GATT_ITER_STOP; + } + + struct bt_gatt_chrc *chrc = (struct bt_gatt_chrc *)attr->user_data; + dc->value_handle = chrc->value_handle; + dc->decl_handle = attr->handle; + dc->properties = chrc->properties; + + // Copy UUID into our storage + if (chrc->uuid->type == BT_UUID_TYPE_16) { + dc->uuid.uuid.type = BT_UUID_TYPE_16; + ((struct bt_uuid_16 *)&dc->uuid)->val = BT_UUID_16(chrc->uuid)->val; + } else { + memcpy(&dc->uuid, chrc->uuid, sizeof(struct bt_uuid_128)); + } + + sys_slist_append(&discovered_list, &dc->node); + + return BT_GATT_ITER_CONTINUE; +} + +// Pairing: characteristic pointer with its declaration handle for descriptor discovery. +typedef struct { + bleio_characteristic_obj_t *characteristic; + uint16_t decl_handle; +} char_with_decl_t; + +// Forward declaration for use by descriptor discovery. +static void free_discovered_list(void); +static void bleio_discovery_check_connected(struct bt_conn *conn, + discovery_context_t *ctx); + +// Callback for descriptor discovery. +static uint8_t on_descriptor_discovered(struct bt_conn *conn, + const struct bt_gatt_attr *attr, + struct bt_gatt_discover_params *params) { + discovery_context_t *ctx = active_discovery_ctx; + + if (attr == NULL) { + ctx->done = true; + return BT_GATT_ITER_STOP; + } + + discovered_desc_t *dd = port_malloc(sizeof(discovered_desc_t), false); + if (dd == NULL) { + ctx->done = true; + return BT_GATT_ITER_STOP; + } + + dd->handle = attr->handle; + + // Copy UUID into our storage + if (attr->uuid->type == BT_UUID_TYPE_16) { + dd->uuid.uuid.type = BT_UUID_TYPE_16; + ((struct bt_uuid_16 *)&dd->uuid)->val = BT_UUID_16(attr->uuid)->val; + } else { + memcpy(&dd->uuid, attr->uuid, sizeof(struct bt_uuid_128)); + } + + sys_slist_append(&discovered_list, &dd->node); + + return BT_GATT_ITER_CONTINUE; +} + +// Create descriptors from discovered_list and add them to the characteristic. +// Called OUTSIDE the Zephyr callback context. Drains and frees all nodes. +static void create_descriptors_from_discovered(bleio_characteristic_obj_t *characteristic) { + sys_snode_t *node; + while ((node = sys_slist_get(&discovered_list)) != NULL) { + discovered_desc_t *dd = CONTAINER_OF(node, discovered_desc_t, node); + + bleio_uuid_obj_t *uuid = bleio_uuid_from_zephyr(&dd->uuid.uuid); + + // Remember handles for certain well-known descriptors. + if (dd->uuid.uuid.type == BT_UUID_TYPE_16) { + switch (((struct bt_uuid_16 *)&dd->uuid)->val) { + case 0x2902: + characteristic->cccd_handle = dd->handle; + break; + case 0x2903: + characteristic->sccd_handle = dd->handle; + break; + case 0x2901: + characteristic->user_desc_handle = dd->handle; + break; + default: + break; + } + } + + bleio_descriptor_obj_t *descriptor = + mp_obj_malloc(bleio_descriptor_obj_t, &bleio_descriptor_type); + + // Remote descriptors: set characteristic and UUID only. + // Reads/writes go over GATT via the handle. + descriptor->characteristic = characteristic; + descriptor->uuid = uuid; + descriptor->handle = dd->handle; + descriptor->read_perm = SECURITY_MODE_OPEN; + descriptor->write_perm = SECURITY_MODE_OPEN; + descriptor->max_length = 20; + descriptor->fixed_length = false; + descriptor->value = m_malloc(20); + memset(descriptor->value, 0, 20); + descriptor->value_length = 0; + + common_hal_bleio_characteristic_add_descriptor(characteristic, descriptor); + + port_free(dd); + } +} + +// Discover descriptors for a single characteristic. +static void discover_descriptors_for_characteristic(struct bt_conn *conn, + discovery_context_t *ctx, bleio_characteristic_obj_t *characteristic, + uint16_t end_handle) { + // Bail cleanly if the link dropped before this phase began. + bleio_discovery_check_connected(conn, ctx); + uint16_t start = characteristic->handle + 1; + if (start > end_handle) { + return; + } + + sys_slist_init(&discovered_list); + ctx->done = false; + ctx->err = 0; + + memset(&discovery_params, 0, sizeof(discovery_params)); + discovery_params.uuid = NULL; + discovery_params.start_handle = start; + discovery_params.end_handle = end_handle; + discovery_params.type = BT_GATT_DISCOVER_DESCRIPTOR; + discovery_params.func = on_descriptor_discovered; + + int err = bt_gatt_discover(conn, &discovery_params); + if (err != 0) { + free_discovered_list(); + if (err == -ENOENT) { + return; + } + raise_zephyr_error(err); + } + + while (!ctx->done) { + RUN_BACKGROUND_TASKS; + } + + // The link may have dropped while we were waiting. + bleio_discovery_check_connected(conn, ctx); + + create_descriptors_from_discovered(characteristic); +} + +// Create CircuitPython characteristic objects from the discovered_list. +// Called OUTSIDE the Zephyr callback context so MP allocations are safe. +// Drains and frees all nodes from the list. +// Returns the number of characteristics created and fills the chars_out array +// (which must be large enough). +static size_t create_characteristics_from_discovered(bleio_service_obj_t *service, + char_with_decl_t *chars_out, size_t max_chars) { + size_t count = 0; + sys_snode_t *node; + while ((node = sys_slist_get(&discovered_list)) != NULL) { + discovered_char_t *dc = CONTAINER_OF(node, discovered_char_t, node); + + bleio_uuid_obj_t *uuid = bleio_uuid_from_zephyr(&dc->uuid.uuid); + + bleio_characteristic_properties_t props = 0; + if (dc->properties & BT_GATT_CHRC_BROADCAST) { + props |= CHAR_PROP_BROADCAST; + } + if (dc->properties & BT_GATT_CHRC_READ) { + props |= CHAR_PROP_READ; + } + if (dc->properties & BT_GATT_CHRC_WRITE_WITHOUT_RESP) { + props |= CHAR_PROP_WRITE_NO_RESPONSE; + } + if (dc->properties & BT_GATT_CHRC_WRITE) { + props |= CHAR_PROP_WRITE; + } + if (dc->properties & BT_GATT_CHRC_NOTIFY) { + props |= CHAR_PROP_NOTIFY; + } + if (dc->properties & BT_GATT_CHRC_INDICATE) { + props |= CHAR_PROP_INDICATE; + } + + bleio_characteristic_obj_t *characteristic = + mp_obj_malloc(bleio_characteristic_obj_t, &bleio_characteristic_type); + + // Use max_length=20 for remote chars - reads go over the wire. + common_hal_bleio_characteristic_construct( + characteristic, service, + dc->value_handle, uuid, props, + SECURITY_MODE_OPEN, SECURITY_MODE_OPEN, + 20, false, NULL, NULL); + + if (count < max_chars) { + chars_out[count].characteristic = characteristic; + chars_out[count].decl_handle = dc->decl_handle; + } + count++; + + port_free(dc); + } + return count; +} + +// Helper to drain and free all nodes from the discovered_list. +static void free_discovered_list(void) { + sys_snode_t *node; + while ((node = sys_slist_get(&discovered_list)) != NULL) { + port_free(node); + } +} + +// The link dropped during discovery: the disconnect callback cleared +// connection->conn (so a subsequent bt_gatt_discover() would NULL-deref, since +// CONFIG_ASSERT is off) and/or aborted the active discovery (ctx->err set). +// Stop discovery cleanly with a "Not connected" exception instead of +// crashing or hanging on the spin loop. +static void bleio_discovery_check_connected(struct bt_conn *conn, + discovery_context_t *ctx) { + if (conn == NULL || ctx->err != 0) { + free_discovered_list(); + active_discovery_ctx = NULL; + mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Not connected")); + } +} + +// Discover characteristics for a single remote service. +static void discover_characteristics_for_service(struct bt_conn *conn, + discovery_context_t *ctx, bleio_service_obj_t *service) { + // Bail cleanly if the link dropped before this phase began. + bleio_discovery_check_connected(conn, ctx); + // Need at least 2 handles: one for the service declaration, one for a characteristic + if (service->end_handle <= service->start_handle) { + return; + } + + sys_slist_init(&discovered_list); + ctx->done = false; + ctx->err = 0; + + memset(&discovery_params, 0, sizeof(discovery_params)); + discovery_params.uuid = NULL; + discovery_params.start_handle = service->start_handle + 1; + discovery_params.end_handle = service->end_handle; + discovery_params.type = BT_GATT_DISCOVER_CHARACTERISTIC; + discovery_params.func = on_characteristic_discovered; + + int err = bt_gatt_discover(conn, &discovery_params); + if (err != 0) { + free_discovered_list(); + // -ENOENT means no characteristics found in the range, which is fine. + if (err == -ENOENT) { + return; + } + raise_zephyr_error(err); + } + + while (!ctx->done) { + RUN_BACKGROUND_TASKS; + } + + // The link may have dropped while we were waiting. + bleio_discovery_check_connected(conn, ctx); + + // Create CP objects outside of callback context where MP allocations are safe. + // This drains and frees the list nodes. + char_with_decl_t chars[16]; + size_t num_chars = create_characteristics_from_discovered(service, chars, 16); + + // Discover descriptors for each characteristic. + // The descriptor range for char[i] is from char[i].handle+1 to + // char[i+1].decl_handle-1 (or service.end_handle for the last). + for (size_t i = 0; i < num_chars && i < 16; i++) { + uint16_t desc_end; + if (i + 1 < num_chars) { + desc_end = chars[i + 1].decl_handle - 1; + } else { + desc_end = service->end_handle; + } + discover_descriptors_for_characteristic(conn, ctx, + chars[i].characteristic, desc_end); + } +} + +// ===== PAIRING / BONDING ===== + +// Auth info callbacks to track pairing completion/failure +static struct bt_conn_auth_info_cb auth_info_cb; +static bool auth_info_cb_registered = false; + +static void on_pairing_complete(struct bt_conn *conn, bool bonded) { + for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) { + if (bleio_connections[i].conn == conn) { + bleio_connections[i].pair_status = PAIR_PAIRED; + bleio_connections[i].sec_err = 0; + break; + } + } +} + +static void on_pairing_failed(struct bt_conn *conn, enum bt_security_err reason) { + for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) { + if (bleio_connections[i].conn == conn) { + bleio_connections[i].pair_status = PAIR_NOT_PAIRED; + bleio_connections[i].sec_err = (uint8_t)reason; + break; + } + } +} + +void bleio_connection_register_auth_callbacks(void) { + if (!auth_info_cb_registered) { + auth_info_cb.pairing_complete = on_pairing_complete; + auth_info_cb.pairing_failed = on_pairing_failed; + bt_conn_auth_info_cb_register(&auth_info_cb); + auth_info_cb_registered = true; + } +} + +void common_hal_bleio_connection_pair(bleio_connection_internal_t *self, bool bond) { + (void)bond; // Bonding is enabled globally via CONFIG_BT_BONDABLE=y + + if (self == NULL || self->conn == NULL) { + mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Not connected")); + } + + // Already paired? + if (self->pair_status == PAIR_PAIRED) { + return; + } + + // Ensure auth callbacks are registered + bleio_connection_register_auth_callbacks(); + + self->pair_status = PAIR_WAITING; + self->sec_err = 0; + + int err = bt_conn_set_security(self->conn, BT_SECURITY_L2); + if (err != 0) { + self->pair_status = PAIR_NOT_PAIRED; + raise_zephyr_error(err); + } + + // bt_conn_set_security may return 0 immediately if already encrypted + // (e.g., reconnection with stored bond keys). Check current security level. + if (bt_conn_get_security(self->conn) > BT_SECURITY_L1) { + self->pair_status = PAIR_PAIRED; + return; + } + + // Wait for pairing to complete. Zephyr's SMP reports each attempt via + // pairing_failed before auto-restarting security (smp.c), so a stale-bond + // retry shows up as an intermediate BT_SECURITY_ERR_PIN_OR_KEY_MISSING + // followed by a fresh attempt that can succeed. Ride through those and + // rely on Zephyr to signal the end: success (PAIR_PAIRED), SMP_TIMEOUT + // dropping the link (observed as conn == NULL), or a user interrupt. + while (self->pair_status != PAIR_PAIRED + && self->conn != NULL + && !mp_hal_is_interrupted()) { + RUN_BACKGROUND_TASKS; + } + + if (mp_hal_is_interrupted()) { + if (self->conn != NULL) { + bt_conn_auth_cancel(self->conn); + } + self->pair_status = PAIR_NOT_PAIRED; + return; + } + + if (self->pair_status == PAIR_PAIRED) { + return; + } + + // Reuse the messages shared with the nordic _bleio implementation + // (check_sec_status). A dropped link clears sec_err, so it falls through + // to the "unspecified issue" message alongside the explicit UNSPECIFIED + // error code rather than introducing a zephyr-specific "Pairing failed" + // string. + uint8_t sec_err_code = self->sec_err; + if (sec_err_code == BT_SECURITY_ERR_UNSPECIFIED || sec_err_code == 0) { + mp_raise_bleio_SecurityError(MP_ERROR_TEXT("Unspecified issue. The pairing request on the other device may have been declined or ignored.")); + } else { + mp_raise_bleio_SecurityError(MP_ERROR_TEXT("Unknown security error: 0x%04x"), sec_err_code); + } +} + +void common_hal_bleio_connection_disconnect(bleio_connection_internal_t *self) { + if (self == NULL || self->conn == NULL) { + return; + } + + int err = bt_conn_disconnect(self->conn, BT_HCI_ERR_REMOTE_USER_TERM_CONN); + if (err != 0 && err != -ENOTCONN) { + raise_zephyr_error(err); + } + + // The connection may now be disconnecting; force connections tuple rebuild. + common_hal_bleio_adapter_obj.connection_objs = NULL; +} + +bool common_hal_bleio_connection_get_connected(bleio_connection_obj_t *self) { + if (self == NULL || self->connection == NULL) { + return false; + } + + bleio_connection_internal_t *connection = self->connection; + if (connection->conn == NULL) { + return false; + } + + struct bt_conn_info info; + if (bt_conn_get_info(connection->conn, &info) != 0) { + return false; + } + + return info.state == BT_CONN_STATE_CONNECTED || info.state == BT_CONN_STATE_DISCONNECTING; +} + +mp_int_t common_hal_bleio_connection_get_max_packet_length(bleio_connection_internal_t *self) { + if (self == NULL || self->conn == NULL) { + return 20; + } + + uint16_t mtu = bt_gatt_get_mtu(self->conn); + if (mtu < 3) { + return 20; + } + return mtu - 3; +} + +bool common_hal_bleio_connection_get_paired(bleio_connection_obj_t *self) { + if (self == NULL || self->connection == NULL) { + return false; + } + return self->connection->pair_status == PAIR_PAIRED; +} + +// Authenticated (MITM-protected) pairing - numeric comparison - is implemented on the +// espressif port only. This port can't tell a "Just Works" bond from an authenticated +// one, so report the conservative answer rather than a guarantee it can't make. +bool common_hal_bleio_connection_get_authenticated(bleio_connection_obj_t *self) { + return false; +} + +mp_obj_t common_hal_bleio_connection_get_numeric_comparison(bleio_connection_obj_t *self) { + return mp_const_none; +} + +void common_hal_bleio_connection_confirm_pairing(bleio_connection_obj_t *self, bool accept) { + mp_raise_NotImplementedError(NULL); +} + +mp_obj_tuple_t *common_hal_bleio_connection_discover_remote_services(bleio_connection_obj_t *self, mp_obj_t service_uuids_whitelist) { + bleio_connection_internal_t *connection = self->connection; + if (connection == NULL || connection->conn == NULL) { + mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Not connected")); + } + + discovery_context_t ctx; + ctx.done = false; + ctx.err = 0; + + active_discovery_ctx = &ctx; + sys_slist_init(&discovered_list); + + // Create the result list for service objects. + mp_obj_list_t *service_list = mp_obj_new_list(0, NULL); + + // Discover primary services (callback appends nodes to discovered_list). + // When a whitelist is given, pass each UUID to Zephyr so filtering happens + // on the remote device — only matching services are returned. + if (service_uuids_whitelist == mp_const_none) { + memset(&discovery_params, 0, sizeof(discovery_params)); + discovery_params.uuid = NULL; + discovery_params.start_handle = BT_ATT_FIRST_ATTRIBUTE_HANDLE; + discovery_params.end_handle = BT_ATT_LAST_ATTRIBUTE_HANDLE; + discovery_params.type = BT_GATT_DISCOVER_PRIMARY; + discovery_params.func = on_service_discovered; + + int err = bt_gatt_discover(connection->conn, &discovery_params); + if (err != 0) { + free_discovered_list(); + active_discovery_ctx = NULL; + raise_zephyr_error(err); + } + + while (!ctx.done) { + RUN_BACKGROUND_TASKS; + } + + // The link may have dropped during primary discovery. + bleio_discovery_check_connected(connection->conn, &ctx); + } else { + mp_obj_iter_buf_t iter_buf; + mp_obj_t iterable = mp_getiter(service_uuids_whitelist, &iter_buf); + mp_obj_t uuid_obj; + while ((uuid_obj = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) { + bleio_uuid_obj_t *cp_uuid = mp_arg_validate_type(uuid_obj, &bleio_uuid_type, MP_QSTR_uuid); + + memset(&discovery_params, 0, sizeof(discovery_params)); + discovery_params.start_handle = BT_ATT_FIRST_ATTRIBUTE_HANDLE; + discovery_params.end_handle = BT_ATT_LAST_ATTRIBUTE_HANDLE; + discovery_params.type = BT_GATT_DISCOVER_PRIMARY; + discovery_params.func = on_service_discovered; + + // Set the Zephyr UUID filter. Stack variables are safe because + // bt_gatt_discover is synchronous (we spin until ctx.done). + union { + struct bt_uuid_16 u16; + struct bt_uuid_128 u128; + } z_uuid; + if (cp_uuid->size == BT_UUID_SIZE_16) { + z_uuid.u16.uuid.type = BT_UUID_TYPE_16; + z_uuid.u16.val = cp_uuid->uuid16; + discovery_params.uuid = &z_uuid.u16.uuid; + } else { + z_uuid.u128.uuid.type = BT_UUID_TYPE_128; + memcpy(z_uuid.u128.val, cp_uuid->uuid128, 16); + discovery_params.uuid = &z_uuid.u128.uuid; + } + + ctx.done = false; + ctx.err = 0; + + int err = bt_gatt_discover(connection->conn, &discovery_params); + if (err != 0) { + free_discovered_list(); + active_discovery_ctx = NULL; + raise_zephyr_error(err); + } + + while (!ctx.done) { + RUN_BACKGROUND_TASKS; + } + + // The link may have dropped during this UUID's discovery; stop + // before the next iteration clears ctx.err and crashes on a NULL conn. + bleio_discovery_check_connected(connection->conn, &ctx); + } + } + + // Create CP service objects outside callback context where MP allocations are safe. + // Drain and free the discovered service nodes. + mp_obj_list_t *result_list = service_list; + sys_snode_t *snode; + while ((snode = sys_slist_get(&discovered_list)) != NULL) { + discovered_service_t *ds = CONTAINER_OF(snode, discovered_service_t, node); + bleio_uuid_obj_t *uuid = bleio_uuid_from_zephyr(&ds->uuid.uuid); + bleio_service_obj_t *service = mp_obj_malloc(bleio_service_obj_t, &bleio_service_type); + common_hal_bleio_service_from_remote_service(service, self, uuid, false); + service->start_handle = ds->start_handle; + service->end_handle = ds->end_handle; + mp_obj_list_append(MP_OBJ_FROM_PTR(service_list), MP_OBJ_FROM_PTR(service)); + port_free(ds); + } + + // Discover characteristics for each service + for (size_t i = 0; i < result_list->len; i++) { + bleio_service_obj_t *svc = MP_OBJ_TO_PTR(result_list->items[i]); + if (svc->start_handle < svc->end_handle) { + // discover_characteristics_for_service re-checks, but guard here + // too so we don't enter the phase after a mid-loop disconnect. + bleio_discovery_check_connected(connection->conn, &ctx); + discover_characteristics_for_service(connection->conn, &ctx, svc); + } + } + + active_discovery_ctx = NULL; + + return mp_obj_new_tuple(result_list->len, result_list->items); +} + +mp_float_t common_hal_bleio_connection_get_connection_interval(bleio_connection_internal_t *self) { + mp_raise_NotImplementedError(NULL); +} + +void common_hal_bleio_connection_set_connection_interval(bleio_connection_internal_t *self, mp_float_t new_interval) { + mp_raise_NotImplementedError(NULL); +} + +mp_obj_t bleio_connection_new_from_internal(bleio_connection_internal_t *connection) { + if (connection == NULL) { + return mp_const_none; + } + + if (connection->connection_obj != mp_const_none) { + return connection->connection_obj; + } + + bleio_connection_obj_t *connection_obj = mp_obj_malloc(bleio_connection_obj_t, &bleio_connection_type); + connection_obj->connection = connection; + connection_obj->disconnect_reason = 0; + connection->connection_obj = MP_OBJ_FROM_PTR(connection_obj); + + return connection->connection_obj; +} diff --git a/ports/zephyr-cp/common-hal/_bleio/Connection.h b/ports/zephyr-cp/common-hal/_bleio/Connection.h new file mode 100644 index 00000000000..9565fd31b8b --- /dev/null +++ b/ports/zephyr-cp/common-hal/_bleio/Connection.h @@ -0,0 +1,40 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Dan Halbert for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include + +#include "py/obj.h" + +struct bt_conn; + +typedef enum { + PAIR_NOT_PAIRED, + PAIR_WAITING, + PAIR_PAIRED, +} pair_status_t; + +typedef struct { + struct bt_conn *conn; + mp_obj_t connection_obj; + volatile pair_status_t pair_status; + uint8_t sec_err; // Security error code from pairing attempt + // True if user code initiated this connection or accepted it with its own + // advertising. bleio_user_reset() disconnects only these; the BLE workflow + // connection is not user-owned and survives VM restarts. + bool user_owned; +} bleio_connection_internal_t; + +typedef struct { + mp_obj_base_t base; + bleio_connection_internal_t *connection; + uint8_t disconnect_reason; +} bleio_connection_obj_t; + +mp_obj_t bleio_connection_new_from_internal(bleio_connection_internal_t *connection); +void bleio_connection_register_auth_callbacks(void); diff --git a/ports/zephyr-cp/common-hal/_bleio/Descriptor.c b/ports/zephyr-cp/common-hal/_bleio/Descriptor.c new file mode 100644 index 00000000000..a2219d8b5cd --- /dev/null +++ b/ports/zephyr-cp/common-hal/_bleio/Descriptor.c @@ -0,0 +1,109 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Dan Halbert for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include + +#include "py/runtime.h" +#include "shared-bindings/_bleio/__init__.h" +#include "shared-bindings/_bleio/Descriptor.h" +#include "shared-bindings/_bleio/Characteristic.h" +#include "common-hal/_bleio/__init__.h" +#include "common-hal/_bleio/Characteristic.h" +#include "common-hal/_bleio/Connection.h" +#include "supervisor/port_heap.h" + +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) { + + self->characteristic = characteristic; + self->uuid = uuid; + self->read_perm = read_perm; + self->write_perm = write_perm; + self->max_length = max_length; + self->fixed_length = fixed_length; + + // Allocate value buffer + self->value = m_malloc(max_length); + memset(self->value, 0, max_length); + self->value_length = 0; + + // Copy initial value if provided + if (initial_value_bufinfo != NULL && initial_value_bufinfo->len > 0) { + size_t len = initial_value_bufinfo->len; + if (len > (size_t)max_length) { + len = max_length; + } + memcpy(self->value, initial_value_bufinfo->buf, len); + self->value_length = len; + } + + // Convert UUID to Zephyr format + bleio_uuid_to_zephyr(uuid, &self->zephyr_uuid); +} + +bleio_uuid_obj_t *common_hal_bleio_descriptor_get_uuid(bleio_descriptor_obj_t *self) { + return self->uuid; +} + +bleio_characteristic_obj_t *common_hal_bleio_descriptor_get_characteristic(bleio_descriptor_obj_t *self) { + return (bleio_characteristic_obj_t *)self->characteristic; +} + +static bool descriptor_is_remote(bleio_descriptor_obj_t *self) { + return self->characteristic != NULL && + self->characteristic->service != NULL && + self->characteristic->service->is_remote; +} + +size_t common_hal_bleio_descriptor_get_value(bleio_descriptor_obj_t *self, uint8_t *buf, size_t len) { + if (descriptor_is_remote(self)) { + bleio_connection_obj_t *connection = + MP_OBJ_TO_PTR(self->characteristic->service->connection); + if (connection == NULL || connection->connection == NULL || + connection->connection->conn == NULL) { + mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Not connected")); + } + + return bleio_gattc_read_sync(connection->connection->conn, + self->handle, buf, len); + } + + // Local descriptor + size_t copy_len = self->value_length; + if (copy_len > len) { + copy_len = len; + } + memcpy(buf, self->value, copy_len); + return copy_len; +} + +void common_hal_bleio_descriptor_set_value(bleio_descriptor_obj_t *self, mp_buffer_info_t *bufinfo) { + if (descriptor_is_remote(self)) { + bleio_connection_obj_t *connection = + MP_OBJ_TO_PTR(self->characteristic->service->connection); + if (connection == NULL || connection->connection == NULL || + connection->connection->conn == NULL) { + mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Not connected")); + } + + bleio_gattc_write_sync(connection->connection->conn, + self->handle, bufinfo->buf, bufinfo->len); + return; + } + + // Local descriptor + size_t len = bufinfo->len; + if (len > self->max_length) { + len = self->max_length; + } + memcpy(self->value, bufinfo->buf, len); + self->value_length = len; +} diff --git a/ports/zephyr-cp/common-hal/_bleio/Descriptor.h b/ports/zephyr-cp/common-hal/_bleio/Descriptor.h new file mode 100644 index 00000000000..b6d3ab4452e --- /dev/null +++ b/ports/zephyr-cp/common-hal/_bleio/Descriptor.h @@ -0,0 +1,31 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Dan Halbert for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include + +#include "py/obj.h" +#include "shared-bindings/_bleio/Attribute.h" +#include "common-hal/_bleio/UUID.h" + +// Forward declaration to break circular dependency +struct _bleio_characteristic_obj; + +typedef struct _bleio_descriptor_obj { + mp_obj_base_t base; + bleio_uuid_obj_t *uuid; + uint16_t handle; + bleio_attribute_security_mode_t read_perm; + bleio_attribute_security_mode_t write_perm; + uint16_t max_length; + bool fixed_length; + uint8_t *value; + uint16_t value_length; + struct _bleio_characteristic_obj *characteristic; + struct bt_uuid_128 zephyr_uuid; +} bleio_descriptor_obj_t; diff --git a/ports/zephyr-cp/common-hal/_bleio/PacketBuffer.c b/ports/zephyr-cp/common-hal/_bleio/PacketBuffer.c new file mode 100644 index 00000000000..6e3f42a6729 --- /dev/null +++ b/ports/zephyr-cp/common-hal/_bleio/PacketBuffer.c @@ -0,0 +1,629 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Dan Halbert for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include + +#include +#include +#include + +#include "py/runtime.h" +#include "py/stream.h" + +#include "shared/runtime/interrupt_char.h" + +#include "shared-bindings/_bleio/__init__.h" +#include "shared-bindings/_bleio/Connection.h" +#include "shared-bindings/_bleio/PacketBuffer.h" +#include "shared-bindings/microcontroller/__init__.h" + +#include "supervisor/shared/tick.h" +#include "supervisor/port_heap.h" + +#include "common-hal/_bleio/Characteristic.h" +#include "common-hal/_bleio/PacketBuffer.h" +#include "common-hal/_bleio/Adapter.h" +#include "common-hal/_bleio/Connection.h" +#include "common-hal/_bleio/__init__.h" +#include "bindings/zephyr_kernel/__init__.h" + +// Zephyr's ring_buf is safe for single-producer/single-consumer without +// locks. The GATT callbacks (system workqueue) are the sole producer of +// incoming data; the CircuitPython VM (main thread) is the sole consumer. + +// Forward declarations. +static bool conn_is_valid(bleio_packet_buffer_obj_t *self); +static void packet_buffer_send_work_handler(struct k_work *work); +static void notify_complete_cb(struct bt_conn *conn, void *user_data); + +// Called from Zephyr GATT callbacks (system workqueue context). +// Wraps incoming data with a uint16_t length prefix and pushes into ringbuf. +// Tracks the first connection so notifications target the right peer. +void bleio_packet_buffer_extend(bleio_packet_buffer_obj_t *self, + struct bt_conn *conn, const uint8_t *data, size_t len) { + // Track the first/current connection for notifications. + if (conn != NULL) { + conn_is_valid(self); // clear stale conn if needed + if (self->conn == NULL) { + self->conn = conn; + } + } + if (len > UINT16_MAX) { + return; + } + + uint16_t packet_len = (uint16_t)len; + size_t total = sizeof(uint16_t) + len; + + // If the packet doesn't fit, drop oldest packets to make room. + while (ring_buf_space_get(&self->ringbuf) < total) { + uint16_t old_len; + if (ring_buf_size_get(&self->ringbuf) < sizeof(uint16_t)) { + // Not enough data for a length prefix, just reset. + ring_buf_reset(&self->ringbuf); + break; + } + uint32_t peeked = ring_buf_peek(&self->ringbuf, (uint8_t *)&old_len, sizeof(uint16_t)); + if (peeked < sizeof(uint16_t)) { + ring_buf_reset(&self->ringbuf); + break; + } + // Discard the length prefix + ring_buf_get(&self->ringbuf, (uint8_t *)&old_len, sizeof(uint16_t)); + // Discard the packet data + size_t to_discard = old_len; + if (to_discard > ring_buf_size_get(&self->ringbuf)) { + to_discard = ring_buf_size_get(&self->ringbuf); + } + uint8_t discard_buf[32]; + while (to_discard > 0) { + size_t chunk = to_discard > sizeof(discard_buf) ? sizeof(discard_buf) : to_discard; + ring_buf_get(&self->ringbuf, discard_buf, chunk); + to_discard -= chunk; + } + } + + ring_buf_put(&self->ringbuf, (uint8_t *)&packet_len, sizeof(uint16_t)); + ring_buf_put(&self->ringbuf, data, len); + + // Wake the VM background task so it drains the ring buffer promptly. + bleio_request_bluetooth_background(); +} + +void bleio_packet_buffer_set_conn(bleio_packet_buffer_obj_t *self, + struct bt_conn *conn) { + self->conn = conn; +} + +// Returns true if the tracked connection is still connected. +// Clears self->conn if the connection is stale. +static bool conn_is_valid(bleio_packet_buffer_obj_t *self) { + if (self->conn == NULL) { + return false; + } + struct bt_conn_info info; + if (bt_conn_get_info(self->conn, &info) != 0 || + info.state == BT_CONN_STATE_DISCONNECTED) { + self->conn = NULL; + return false; + } + return true; +} + +// Completion callback for bt_gatt_notify_cb. Runs on the system workqueue (per +// the Zephyr bt_gatt_notify_cb contract) — the same context send_work runs in +// — so packet_queued is single-threaded here and needs no lock. +static void notify_complete_cb(struct bt_conn *conn, void *user_data) { + (void)conn; + bleio_packet_buffer_obj_t *self = (bleio_packet_buffer_obj_t *)user_data; + self->packet_queued = false; + // Drain the other buffer now that this notify is done. K_NO_WAIT runs + // send_work immediately, cancelling any pending delayed retry. + k_work_reschedule(&self->send_work, K_NO_WAIT); +} + +// The deferred sender. Runs only on the system workqueue (submitted by the VM +// on write/flush and by notify_complete_cb on completion). It is the sole +// caller of bt_gatt_notify_cb, so packet_queued / pending_index / pending_size +// are touched here and in the VM's brief critical section — nowhere else. +static void packet_buffer_send_work_handler(struct k_work *work) { + bleio_packet_buffer_obj_t *self = CONTAINER_OF( + k_work_delayable_from_work(work), bleio_packet_buffer_obj_t, send_work); + + // Server-side notify path only; clients write directly. characteristic is + // NULL after deinit, so bail before touching it (notify_complete_cb() can + // reschedule send_work after teardown). + bleio_characteristic_obj_t *c = self->characteristic; + if (c == NULL || self->client) { + return; + } + if (!conn_is_valid(self)) { + // The peer is gone: drop everything staged, and clear packet_queued even + // if a notification was handed to bt_gatt_notify_cb() already and its + // notify_complete_cb() has not run. It never will: Zephyr does not call + // the ATT callback for a PDU destroyed by a disconnect (att.c + // att_on_sent_cb(): "Bearer not connected, dropping ATT cb"). If + // packet_queued stayed set, the early return below would skip every + // later send on this buffer, even after the peer reconnects. + self->pending_size = 0; + self->packet_queued = false; + return; + } + + // A notification has been handed to bt_gatt_notify_cb() and its + // notify_complete_cb() has not run yet. That callback reschedules send_work, + // so this handler will run again once the controller has sent the PDU. + if (self->packet_queued) { + return; + } + if (self->pending_size == 0) { + return; // nothing staged + } + + // Staging keeps pending_size <= the negotiated ATT MTU payload, so the + // whole staged packet fits in one notification. + struct bt_gatt_notify_params params = { + .attr = &c->service->attrs[c->value_attr_index], + .data = self->outgoing[self->pending_index], + .len = self->pending_size, + .func = notify_complete_cb, + .user_data = self, + }; + + int err = bt_gatt_notify_cb(self->conn, ¶ms); + if (err == 0) { + // Accepted by the controller; the payload was copied into a PDU and + // will go out at the next connection event. Hand this buffer off and + // let the VM fill the other one while it's in flight. + self->packet_queued = true; + self->pending_size = 0; + self->pending_index ^= 1; // VM fills the other buffer next + return; + } + if (err == -ENOMEM || err == -EAGAIN) { + // No ATT TX buffer right now. The ATT TX pool is shared across all ATT + // traffic on all connections, so it can be full from other + // notifies/indications/responses even when we have nothing in flight. + // Running on the workqueue makes the allocator use K_NO_WAIT: it returns + // NULL and the stack returns -ENOMEM *before* copying or queueing a PDU — + // nothing sent, nothing dropped; the bytes are still in + // outgoing[pending_index]. Leave the data staged and reschedule ourselves + // after a short delay so we retry even when the VM is idle (no write/flush + // to drive us). The delay — not an immediate resubmit — keeps the workqueue + // from busy-looping against a full pool. + k_work_reschedule(&self->send_work, K_MSEC(2)); + return; + } + if (err == -ENOTCONN) { + // Peer disconnected — forget the connection too. (We're here only when + // packet_queued is clear, so no in-flight completion is owed.) + self->conn = NULL; + } + // Any other error is not transient: -ENOTCONN (peer gone), -EPERM (link not + // encrypted and the characteristic requires it), -EINVAL (peer not + // subscribed; CONFIG_BT_GATT_ENFORCE_SUBSCRIPTION), -ENOENT (attribute not + // registered). Retrying would spin forever and wedge this buffer. Drop the + // staged packet, as nordic and espressif do on non-resource errors, and + // cancel any pending delayed retry. + self->pending_size = 0; + self->packet_queued = false; + k_work_cancel_delayable(&self->send_work); +} + +// Shared core for both the Python-facing (allocating) and workflow +// (caller-supplied static buffer) constructors. Wires the ring buffer, the two +// outgoing buffers, the characteristic observer, and (for client-side) CCCD +// subscription. No GC heap allocation happens here. +static void packet_buffer_init_common(bleio_packet_buffer_obj_t *self, + bleio_characteristic_obj_t *characteristic, + uint8_t *ringbuf_data, size_t ringbuf_size, bool owns_ringbuf_data, + uint8_t *outgoing0, uint8_t *outgoing1, + bool owns_outgoing0, bool owns_outgoing1, + size_t max_packet_size) { + + self->characteristic = characteristic; + self->timeout_ms = 0; + self->max_packet_size = max_packet_size; + self->conn = NULL; + self->client = (characteristic->service != NULL && characteristic->service->is_remote); + self->outgoing[0] = outgoing0; + self->outgoing[1] = outgoing1; + self->owns_outgoing[0] = owns_outgoing0; + self->owns_outgoing[1] = owns_outgoing1; + self->pending_index = 0; + self->pending_size = 0; + self->packet_queued = false; + + self->ringbuf_data = ringbuf_data; + self->ringbuf_size = ringbuf_size; + self->owns_ringbuf_data = owns_ringbuf_data; + if (ringbuf_data != NULL && ringbuf_size > 0) { + ring_buf_init(&self->ringbuf, ringbuf_size, ringbuf_data); + } else { + // No incoming buffer (e.g. a server-side NOTIFY-only characteristic). + ring_buf_init(&self->ringbuf, 0, NULL); + } + + // The deferred sender drives server-side notifications. Client-side writes + // go out synchronously and never schedule it, but initializing it always is + // harmless and keeps flush()/deinit() simple. + k_work_init_delayable(&self->send_work, packet_buffer_send_work_handler); + + // Set ourselves as the characteristic's observer so GATT write/notify + // callbacks push incoming data into our ring buffer. + bleio_characteristic_set_observer(characteristic, MP_OBJ_FROM_PTR(self)); + + bleio_characteristic_properties_t props = + common_hal_bleio_characteristic_get_properties(characteristic); + + // For client-side characteristics with NOTIFY/INDICATE, subscribe to + // notifications from the remote peer. + if (self->client && (props & (CHAR_PROP_NOTIFY | CHAR_PROP_INDICATE))) { + bool do_notify = (props & CHAR_PROP_NOTIFY) != 0; + bool do_indicate = (props & CHAR_PROP_INDICATE) != 0; + common_hal_bleio_characteristic_set_cccd(characteristic, do_notify, do_indicate); + } +} + +void common_hal_bleio_packet_buffer_construct( + bleio_packet_buffer_obj_t *self, bleio_characteristic_obj_t *characteristic, + size_t buffer_size, size_t max_packet_size) { + + bleio_characteristic_properties_t props = + common_hal_bleio_characteristic_get_properties(characteristic); + bool client = (characteristic->service != NULL && characteristic->service->is_remote); + + // Allocate ring buffer: buffer_size packets, each with 2-byte length prefix + size_t ringbuf_size = buffer_size * (sizeof(uint16_t) + max_packet_size); + uint8_t *ringbuf_data = port_malloc(ringbuf_size, false); + + // Allocate outgoing buffers. Client-side writes go out directly and only + // need one scratch buffer. Server-side notifications ping-pong between two + // buffers so the VM can fill one while the other is in flight. + uint8_t *outgoing0 = NULL; + uint8_t *outgoing1 = NULL; + bool owns0 = false; + bool owns1 = false; + if (client) { + outgoing0 = port_malloc(max_packet_size, false); + owns0 = true; + } else if (props & (CHAR_PROP_NOTIFY | CHAR_PROP_INDICATE)) { + outgoing0 = port_malloc(max_packet_size, false); + outgoing1 = port_malloc(max_packet_size, false); + owns0 = true; + owns1 = true; + } + + packet_buffer_init_common(self, characteristic, + ringbuf_data, ringbuf_size, true, + outgoing0, outgoing1, owns0, owns1, + max_packet_size); +} + +// Allocation-free version for BLE workflow use. The caller supplies static +// buffers so this can run before gc_init() without touching the GC heap. +// outgoing_buffer1 -> outgoing[0], outgoing_buffer2 -> outgoing[1]. +void _common_hal_bleio_packet_buffer_construct( + bleio_packet_buffer_obj_t *self, bleio_characteristic_obj_t *characteristic, + uint32_t *incoming_buffer, size_t incoming_buffer_size, + uint32_t *outgoing_buffer1, uint32_t *outgoing_buffer2, size_t max_packet_size, + ble_event_handler_t *static_handler_entry) { + (void)static_handler_entry; + + uint8_t *ringbuf_data = (uint8_t *)incoming_buffer; + size_t ringbuf_size = incoming_buffer_size; + + bleio_characteristic_properties_t props = + common_hal_bleio_characteristic_get_properties(characteristic); + bool client = (characteristic->service != NULL && characteristic->service->is_remote); + + uint8_t *outgoing0 = NULL; + uint8_t *outgoing1 = NULL; + bool owns0 = false; + bool owns1 = false; + + if (client) { + // Client-side: one scratch buffer for synchronous writes. + if (outgoing_buffer1 != NULL) { + outgoing0 = (uint8_t *)outgoing_buffer1; + } else { + outgoing0 = port_malloc(max_packet_size, false); + owns0 = true; + } + } else if (props & (CHAR_PROP_NOTIFY | CHAR_PROP_INDICATE)) { + // Server-side: two buffers to ping-pong between. + if (outgoing_buffer1 != NULL) { + outgoing0 = (uint8_t *)outgoing_buffer1; + } else { + outgoing0 = port_malloc(max_packet_size, false); + owns0 = true; + } + if (outgoing_buffer2 != NULL) { + outgoing1 = (uint8_t *)outgoing_buffer2; + } else { + outgoing1 = port_malloc(max_packet_size, false); + owns1 = true; + } + } + + packet_buffer_init_common(self, characteristic, + ringbuf_data, ringbuf_size, false, + outgoing0, outgoing1, owns0, owns1, + max_packet_size); +} + +mp_int_t common_hal_bleio_packet_buffer_readinto(bleio_packet_buffer_obj_t *self, + uint8_t *data, size_t len) { + // Need at least 2 bytes for the length prefix + if (ring_buf_size_get(&self->ringbuf) < sizeof(uint16_t)) { + return 0; + } + + // Peek at the packet length (don't consume yet) + uint16_t packet_length; + uint32_t peeked = ring_buf_peek(&self->ringbuf, (uint8_t *)&packet_length, sizeof(uint16_t)); + if (peeked < sizeof(uint16_t)) { + return 0; + } + + mp_int_t ret; + if (packet_length > len) { + // Packet is longer than requested. Return negative of overrun value. + ret = len - packet_length; + // Discard the packet + ring_buf_get(&self->ringbuf, (uint8_t *)&packet_length, sizeof(uint16_t)); + if (packet_length <= ring_buf_size_get(&self->ringbuf)) { + // Discard data in chunks + uint8_t discard[32]; + size_t remaining = packet_length; + while (remaining > 0) { + size_t chunk = remaining > sizeof(discard) ? sizeof(discard) : remaining; + ring_buf_get(&self->ringbuf, discard, chunk); + remaining -= chunk; + } + } + } else { + // Consume the length prefix + ring_buf_get(&self->ringbuf, (uint8_t *)&packet_length, sizeof(uint16_t)); + // Read packet data + ring_buf_get(&self->ringbuf, data, packet_length); + ret = packet_length; + } + + return ret; +} + +mp_int_t common_hal_bleio_packet_buffer_write(bleio_packet_buffer_obj_t *self, + const uint8_t *data, size_t len, uint8_t *header, size_t header_len) { + if (self->outgoing[0] == NULL) { + mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Writes not supported on Characteristic")); + } + + mp_int_t outgoing_packet_length = + common_hal_bleio_packet_buffer_get_outgoing_packet_length(self); + if (outgoing_packet_length < 0) { + return -1; + } + + mp_int_t total_len = len + header_len; + if (total_len > outgoing_packet_length) { + mp_raise_ValueError_varg( + MP_ERROR_TEXT("Total data to write is larger than %q"), + MP_QSTR_outgoing_packet_length); + } + if (total_len > (mp_int_t)self->max_packet_size) { + mp_raise_ValueError_varg( + MP_ERROR_TEXT("Total data to write is larger than %q"), + MP_QSTR_max_packet_size); + } + + // Client-side (remote characteristic): write the request directly to the + // remote GATT server. The server-side path below stages into a double + // buffer and drains it from the system workqueue via send_work, so handle + // client writes separately (and synchronously). + if (self->characteristic != NULL && + self->characteristic->service != NULL && + self->characteristic->service->is_remote) { + bleio_characteristic_obj_t *c = self->characteristic; + bleio_connection_obj_t *connection = MP_OBJ_TO_PTR(c->service->connection); + if (connection == NULL || connection->connection == NULL || + connection->connection->conn == NULL) { + return -1; + } + struct bt_conn *conn = connection->connection->conn; + + // Combine header + data into the outgoing buffer (max_packet_size). + memcpy(self->outgoing[0], header, header_len); + memcpy(self->outgoing[0] + header_len, data, len); + size_t total = header_len + len; + + if (c->props & CHAR_PROP_WRITE_NO_RESPONSE) { + // Fire-and-forget write. Retry on transient "no TX buffer" + // (-EAGAIN) so paced protocols (e.g. BLE file transfer) don't + // silently drop data. + int err; + while ((err = bt_gatt_write_without_response(conn, c->handle, + self->outgoing[0], total, false)) == -EAGAIN) { + RUN_BACKGROUND_TASKS; + } + if (err != 0) { + raise_zephyr_error(err); + } + } else if (c->props & CHAR_PROP_WRITE) { + bleio_gattc_write_sync(conn, c->handle, self->outgoing[0], total); + } else { + // No write property; nothing to send. + return -1; + } + return (mp_int_t)total; + } + + // Server-side notify path: stage header + data into the pending buffer, + // then hand it to send_work on the system workqueue. bt_gatt_notify_cb + // blocks (K_FOREVER) off the workqueue, so we never call it here; send_work + // does, and the completion callback paces us to one notification in flight. + // The header prefixes each packet, so it's only written when the packet is + // empty (pending_size == 0). pending_size counts bytes staged but not yet + // accepted by the controller. + + if (mp_hal_is_interrupted()) { + return -1; + } + + // If this write would overflow the current packet, wait for send_work to + // drain it (which requires the in-flight notification to complete first). + if ((size_t)len + self->pending_size > (size_t)outgoing_packet_length) { + while (self->pending_size != 0 && + conn_is_valid(self) && + !mp_hal_is_interrupted()) { + k_work_reschedule(&self->send_work, K_NO_WAIT); + RUN_BACKGROUND_TASKS; + } + } + if (!conn_is_valid(self) || mp_hal_is_interrupted()) { + return -1; + } + + size_t num_bytes_written = 0; + + // send_work (system workqueue) may preempt us and modify pending_index / + // pending_size / packet_queued, so guard the append. + common_hal_mcu_disable_interrupts(); + { + uint8_t *pending = self->outgoing[self->pending_index]; + if (self->pending_size == 0 && header_len > 0) { + memcpy(pending, header, header_len); + self->pending_size += header_len; + num_bytes_written += header_len; + } + memcpy(pending + self->pending_size, data, len); + self->pending_size += len; + num_bytes_written += len; + } + common_hal_mcu_enable_interrupts(); + + // If no notification is in flight, kick the deferred sender to drain what + // we just staged (K_NO_WAIT runs it immediately, cancelling any pending + // delayed retry). If one is in flight, its completion will resubmit. + if (!self->packet_queued) { + k_work_reschedule(&self->send_work, K_NO_WAIT); + } + return (mp_int_t)num_bytes_written; +} + +mp_int_t common_hal_bleio_packet_buffer_get_incoming_packet_length( + bleio_packet_buffer_obj_t *self) { + if (self->characteristic == NULL) { + return -1; + } + + if (self->characteristic->service != NULL && + self->characteristic->service->is_remote && + self->characteristic->service->connection != mp_const_none && + (common_hal_bleio_characteristic_get_properties(self->characteristic) & + (CHAR_PROP_INDICATE | CHAR_PROP_NOTIFY))) { + // We are receiving from a remote service via NOTIFY/INDICATE. + bleio_connection_obj_t *connection = + MP_OBJ_TO_PTR(self->characteristic->service->connection); + if (connection != NULL && connection->connection != NULL && + common_hal_bleio_connection_get_connected(connection)) { + return common_hal_bleio_connection_get_max_packet_length(connection->connection); + } + return -1; + } + return self->characteristic->max_length; +} + +mp_int_t common_hal_bleio_packet_buffer_get_outgoing_packet_length( + bleio_packet_buffer_obj_t *self) { + if (self->characteristic == NULL) { + return -1; + } + + if (self->characteristic->service != NULL && + !self->characteristic->service->is_remote && + (common_hal_bleio_characteristic_get_properties(self->characteristic) & + (CHAR_PROP_INDICATE | CHAR_PROP_NOTIFY))) { + // We are sending to a client via NOTIFY/INDICATE. The maximum payload + // per packet is bounded by the negotiated ATT MTU (ATT_MTU - 3 for the + // opcode and handle in a Handle Value Notification PDU). Without a + // current connection we can't know the MTU, so return -1 to signal + // that writes aren't possible yet. + if (!conn_is_valid(self)) { + return -1; + } + uint16_t mtu = bt_gatt_get_mtu(self->conn); + if (mtu < 3) { + return -1; + } + mp_int_t mtu_payload = (mp_int_t)mtu - 3; + return MIN(MIN(mtu_payload, (mp_int_t)self->max_packet_size), + (mp_int_t)self->characteristic->max_length); + } + // Writing to remote characteristic or local without NOTIFY + return MIN(self->characteristic->max_length, self->max_packet_size); +} + +void common_hal_bleio_packet_buffer_flush(bleio_packet_buffer_obj_t *self) { + // Wait until everything written has been handed to the controller AND its + // completion has fired (we pace to one notification in flight at a time). + // send_work runs on the system workqueue, which is higher priority than + // this thread, so k_work_reschedule(K_NO_WAIT) lets it preempt us; + // RUN_BACKGROUND_TASKS advances simulated time / lets completion callbacks + // fire so packet_queued clears. For client-side writes (synchronous) there + // is nothing pending, so this returns immediately. + while ((self->pending_size != 0 || self->packet_queued) && + conn_is_valid(self) && + !mp_hal_is_interrupted()) { + k_work_reschedule(&self->send_work, K_NO_WAIT); + RUN_BACKGROUND_TASKS; + } +} + +bool common_hal_bleio_packet_buffer_deinited(bleio_packet_buffer_obj_t *self) { + return self->characteristic == NULL; +} + +void common_hal_bleio_packet_buffer_deinit(bleio_packet_buffer_obj_t *self) { + if (common_hal_bleio_packet_buffer_deinited(self)) { + return; + } + bleio_characteristic_clear_observer(self->characteristic); + self->characteristic = NULL; + // Cancel any pending delayed retry so it can't fire after we free the + // buffers (or after the object is gone). + k_work_cancel_delayable(&self->send_work); + // Free buffers if we own them (port_malloc'd). The BLE workflow path + // supplies static buffers that must not be freed. + if (self->owns_ringbuf_data && self->ringbuf_data != NULL) { + port_free(self->ringbuf_data); + } + self->ringbuf_data = NULL; + for (int i = 0; i < 2; i++) { + if (self->owns_outgoing[i] && self->outgoing[i] != NULL) { + port_free(self->outgoing[i]); + } + self->outgoing[i] = NULL; + } +} + +bool common_hal_bleio_packet_buffer_connected(bleio_packet_buffer_obj_t *self) { + if (common_hal_bleio_packet_buffer_deinited(self)) { + return false; + } + // Check if the characteristic's connection is still active. + if (self->characteristic->service != NULL && + self->characteristic->service->is_remote) { + if (self->characteristic->service->connection == mp_const_none) { + return false; + } + bleio_connection_obj_t *connection = + MP_OBJ_TO_PTR(self->characteristic->service->connection); + return common_hal_bleio_connection_get_connected(connection); + } + return true; +} diff --git a/ports/zephyr-cp/common-hal/_bleio/PacketBuffer.h b/ports/zephyr-cp/common-hal/_bleio/PacketBuffer.h new file mode 100644 index 00000000000..67216775257 --- /dev/null +++ b/ports/zephyr-cp/common-hal/_bleio/PacketBuffer.h @@ -0,0 +1,79 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Dan Halbert for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include + +#include +#include + +#include "py/obj.h" +#include "shared-bindings/_bleio/Characteristic.h" + +struct bt_conn; + +typedef void *ble_event_handler_t; + +typedef struct { + mp_obj_base_t base; + bleio_characteristic_obj_t *characteristic; + uint32_t timeout_ms; + // Store the connection we are talking to. We expect to talk over a single + // connection at a time. + struct bt_conn *conn; + bool client; + // The current MTU negotiated with the active connection. + size_t max_packet_size; + + // ringbuf to store incoming packets. + struct ring_buf ringbuf; + uint8_t *ringbuf_data; + size_t ringbuf_size; + + // Outgoing path. Two fixed buffers alternate so the VM can keep filling one + // while the other is in flight with the controller. + // + // outgoing[pending_index] is the buffer the VM is filling (pending_size + // bytes staged, not yet sent). packet_queued means a notification has been + // accepted by the controller and its completion callback hasn't fired yet + // — at most one is in flight at a time. + // + uint8_t *outgoing[2]; + uint8_t pending_index; // which buffer the VM is filling + volatile uint16_t pending_size; // bytes staged in outgoing[pending_index] + volatile bool packet_queued; // a notification is in flight + + // send_work is a delayable work item, the only caller of bt_gatt_notify_cb + // (that API blocks (K_FOREVER) off the workqueue but returns -ENOMEM from + // it). It's rescheduled with K_NO_WAIT to drain after a write/completion, + // and with a short delay on -ENOMEM so it self-retries even when the VM is + // idle and the shared ATT TX pool is full from other traffic. It and the + // completion callback both run on the workqueue (serialized with each + // other); the VM is the only other toucher of these fields and guards its + // read-modify-write with common_hal_mcu_disable_interrupts() (the workqueue + // preempts the VM, so the critical section keeps it out while we append). + // bt_gatt_notify_cb copies the payload into a PDU on success, so the source + // buffer may be reused once the call returns 0; the completion callback + // paces us to one in flight and makes flush() accurate. + struct k_work_delayable send_work; + + // Ownership: true if the buffer was port_malloc'd and should be freed in + // deinit; false if it is a caller-supplied static buffer (the BLE workflow + // path, which runs before gc_init()). + bool owns_ringbuf_data; + bool owns_outgoing[2]; +} bleio_packet_buffer_obj_t; + +// Called from GATT callbacks (system workqueue context) to push +// data into the PacketBuffer ring buffer with length-prefix framing. +void bleio_packet_buffer_extend(bleio_packet_buffer_obj_t *self, + struct bt_conn *conn, const uint8_t *data, size_t len); + +// Called from CCCD write callback to record the subscribing connection. +void bleio_packet_buffer_set_conn(bleio_packet_buffer_obj_t *self, + struct bt_conn *conn); diff --git a/ports/zephyr-cp/common-hal/_bleio/Service.c b/ports/zephyr-cp/common-hal/_bleio/Service.c new file mode 100644 index 00000000000..4333ee21c25 --- /dev/null +++ b/ports/zephyr-cp/common-hal/_bleio/Service.c @@ -0,0 +1,346 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Dan Halbert for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// GATT server service implementation for Zephyr. +// +// Each bleio Service owns a dynamically-allocated array of bt_gatt_attr +// (the Zephyr GATT attribute table). When a Characteristic is added, we +// append 2-4 attrs (declaration, value, optional CCC, optional CUD) and +// (re-)register the service with bt_gatt_service_register(). +// +// IMPORTANT: Zephyr's BT_UUID_GATT_PRIMARY / BT_UUID_GATT_CHRC / … macros +// expand to compound-literal pointers. Inside a function those have automatic +// storage duration and become dangling once the function returns. We therefore +// declare file-scope static const UUIDs (_uuid_primary, _uuid_chrc, …) and +// reference those from every bt_gatt_attr we build. + +#include +#include + +#include + +#include "py/gc.h" +#include "py/runtime.h" +#include "supervisor/port_heap.h" +#include "bindings/zephyr_kernel/__init__.h" +#include "shared-bindings/_bleio/Characteristic.h" +#include "shared-bindings/_bleio/Service.h" +#include "common-hal/_bleio/__init__.h" +#include "common-hal/_bleio/Characteristic.h" + +#define INITIAL_ATTR_CAPACITY 16 + +// Standard GATT UUIDs with static storage duration. +// BT_UUID_GATT_PRIMARY etc. expand to compound literals which have automatic +// storage when used inside functions - the resulting pointers dangle after the +// function returns. These static constants persist for the lifetime of the +// program. +static const struct bt_uuid_16 _uuid_primary = BT_UUID_INIT_16(BT_UUID_GATT_PRIMARY_VAL); +static const struct bt_uuid_16 _uuid_secondary = BT_UUID_INIT_16(BT_UUID_GATT_SECONDARY_VAL); +static const struct bt_uuid_16 _uuid_chrc = BT_UUID_INIT_16(BT_UUID_GATT_CHRC_VAL); +static const struct bt_uuid_16 _uuid_ccc = BT_UUID_INIT_16(BT_UUID_GATT_CCC_VAL); +static const struct bt_uuid_16 _uuid_cud = BT_UUID_INIT_16(BT_UUID_GATT_CUD_VAL); + +// User-created services live on the GC heap, but once registered, Zephyr's GATT +// database holds a pointer to the bt_gatt_service node inside the object. So a +// registered heap service must stay reachable until it is unregistered, and it +// must be unregistered before the heap it lives in goes away. The zephyr port never +// restarts the Bluetooth stack (set_enabled(false) leaves it running), so the +// database is never cleared for us: bleio_user_reset() unregisters the services at the +// end of every VM run. Same pattern as ports/espressif/common-hal/_bleio/Service.c. +static bleio_service_obj_t *_retained_services; + +static void service_retain(bleio_service_obj_t *self) { + if (!gc_ptr_on_heap((void *)self)) { + // Statically allocated workflow service; the supervisor owns its lifetime. + return; + } + for (bleio_service_obj_t *it = _retained_services; it != NULL; it = it->next_retained) { + if (it == self) { + return; + } + } + self->next_retained = _retained_services; + _retained_services = self; +} + +static void service_release(bleio_service_obj_t *self) { + bleio_service_obj_t **prev = &_retained_services; + for (bleio_service_obj_t *it = *prev; it != NULL; it = it->next_retained) { + if (it == self) { + *prev = it->next_retained; + it->next_retained = NULL; + return; + } + prev = &it->next_retained; + } +} + +// One pointer is enough: the GC traces next_retained through the rest of the chain. +void bleio_service_gc_collect(void) { + gc_collect_ptr(_retained_services); +} + +void bleio_service_unregister_retained(void) { + while (_retained_services != NULL) { + bleio_service_obj_t *service = _retained_services; + // The characteristics' value buffers are on the port heap and nothing + // else frees them once the VM heap is gone. + mp_obj_list_t *list = service->characteristic_list; + if (list != NULL) { + for (size_t i = 0; i < list->len; i++) { + common_hal_bleio_characteristic_deinit(MP_OBJ_TO_PTR(list->items[i])); + } + } + // Unregisters from Zephyr, frees attrs, and removes it from this list. + common_hal_bleio_service_deinit(service); + } +} + +// Zephyr write permission for the CCC descriptor. If reading the characteristic +// value requires encryption or authentication, so does subscribing to it; +// otherwise a client could get the value from notifications without ever being +// made to pair. An unencrypted write then gets Insufficient Encryption or +// Authentication, which is what makes a host pair. Same as espressif (#11236). +// NO_ACCESS on read is not a link-security level, so it leaves the CCC writable; +// nordic differs and makes such a characteristic unsubscribable. +static uint16_t ccc_write_perm(bleio_attribute_security_mode_t read_perm) { + switch (read_perm) { + case SECURITY_MODE_ENC_NO_MITM: + return BT_GATT_PERM_WRITE_ENCRYPT; + case SECURITY_MODE_ENC_WITH_MITM: + return BT_GATT_PERM_WRITE_AUTHEN; + case SECURITY_MODE_LESC_ENC_WITH_MITM: + return BT_GATT_PERM_WRITE_LESC; + default: + return BT_GATT_PERM_WRITE; + } +} + +static void service_ensure_capacity(bleio_service_obj_t *self, size_t needed) { + if (self->attr_count + needed <= self->attr_capacity) { + return; + } + size_t new_capacity = self->attr_capacity; + while (new_capacity < self->attr_count + needed) { + new_capacity *= 2; + } + struct bt_gatt_attr *new_attrs = port_realloc(self->attrs, + new_capacity * sizeof(struct bt_gatt_attr), false); + self->attrs = new_attrs; + self->attr_capacity = new_capacity; +} + +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->is_secondary = is_secondary; + self->is_remote = false; + self->connection = mp_const_none; + self->characteristic_list = characteristic_list; + self->start_handle = 0; + self->end_handle = 0; + self->registered = false; + self->next_retained = NULL; + + // Convert UUID to Zephyr format + bleio_uuid_to_zephyr(uuid, &self->zephyr_uuid); + + // Allocate attrs array + self->attr_capacity = INITIAL_ATTR_CAPACITY; + self->attrs = port_malloc(self->attr_capacity * sizeof(struct bt_gatt_attr), false); + memset(self->attrs, 0, self->attr_capacity * sizeof(struct bt_gatt_attr)); + self->attr_count = 0; + + // Add primary/secondary service declaration at index 0 + const struct bt_uuid *svc_type_uuid = is_secondary + ? (const struct bt_uuid *)&_uuid_secondary + : (const struct bt_uuid *)&_uuid_primary; + self->attrs[0] = (struct bt_gatt_attr) { + .uuid = svc_type_uuid, + .perm = BT_GATT_PERM_READ, + .read = bt_gatt_attr_read_service, + .user_data = (void *)&self->zephyr_uuid, + }; + self->attr_count = 1; + + return 0; +} + +void common_hal_bleio_service_construct(bleio_service_obj_t *self, + bleio_uuid_obj_t *uuid, bool is_secondary) { + mp_obj_list_t *char_list = mp_obj_new_list(0, NULL); + _common_hal_bleio_service_construct(self, uuid, is_secondary, char_list); +} + +void common_hal_bleio_service_deinit(bleio_service_obj_t *self) { + if (self->registered) { + bt_gatt_service_unregister(&self->zephyr_service); + self->registered = false; + } + service_release(self); + if (self->attrs != NULL) { + port_free(self->attrs); + self->attrs = NULL; + self->attr_capacity = 0; + self->attr_count = 0; + } +} + +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) { + self->uuid = uuid; + self->is_secondary = is_secondary; + self->is_remote = true; + self->connection = MP_OBJ_FROM_PTR(connection); + self->characteristic_list = mp_obj_new_list(0, NULL); + self->start_handle = 0; + self->end_handle = 0; + self->registered = false; + self->next_retained = NULL; + self->attrs = NULL; + self->attr_count = 0; + self->attr_capacity = 0; + bleio_uuid_to_zephyr(uuid, &self->zephyr_uuid); +} + +bleio_uuid_obj_t *common_hal_bleio_service_get_uuid(bleio_service_obj_t *self) { + return self->uuid; +} + +mp_obj_tuple_t *common_hal_bleio_service_get_characteristics(bleio_service_obj_t *self) { + return mp_obj_new_tuple(self->characteristic_list->len, self->characteristic_list->items); +} + +bool common_hal_bleio_service_get_is_remote(bleio_service_obj_t *self) { + return self->is_remote; +} + +bool common_hal_bleio_service_get_is_secondary(bleio_service_obj_t *self) { + return self->is_secondary; +} + +void common_hal_bleio_service_add_characteristic(bleio_service_obj_t *self, + bleio_characteristic_obj_t *characteristic, + mp_buffer_info_t *initial_value_bufinfo, + const char *user_description) { + + if (self->registered) { + bt_gatt_service_unregister(&self->zephyr_service); + self->registered = false; + } + + // Calculate how many attrs we need: + // 1 = characteristic declaration, 1 = value attr + // +1 if NOTIFY|INDICATE (CCC descriptor) + // +1 if user_description + size_t attrs_needed = 2; + bool needs_ccc = (characteristic->props & (CHAR_PROP_NOTIFY | CHAR_PROP_INDICATE)) != 0; + bool needs_user_desc = (user_description != NULL && user_description[0] != '\0'); + if (needs_ccc) { + attrs_needed++; + } + if (needs_user_desc) { + attrs_needed++; + } + + service_ensure_capacity(self, attrs_needed); + + // Map CP properties to Zephyr BT spec properties + uint8_t zephyr_props = 0; + if (characteristic->props & CHAR_PROP_BROADCAST) { + zephyr_props |= BT_GATT_CHRC_BROADCAST; + } + if (characteristic->props & CHAR_PROP_READ) { + zephyr_props |= BT_GATT_CHRC_READ; + } + if (characteristic->props & CHAR_PROP_WRITE_NO_RESPONSE) { + zephyr_props |= BT_GATT_CHRC_WRITE_WITHOUT_RESP; + } + if (characteristic->props & CHAR_PROP_WRITE) { + zephyr_props |= BT_GATT_CHRC_WRITE; + } + if (characteristic->props & CHAR_PROP_NOTIFY) { + zephyr_props |= BT_GATT_CHRC_NOTIFY; + } + if (characteristic->props & CHAR_PROP_INDICATE) { + zephyr_props |= BT_GATT_CHRC_INDICATE; + } + + // Set up the Zephyr chrc struct in the characteristic + characteristic->zephyr_chrc.uuid = &characteristic->zephyr_uuid.uuid; + characteristic->zephyr_chrc.value_handle = 0; + characteristic->zephyr_chrc.properties = zephyr_props; + + // Map permissions + uint16_t perm = bleio_security_to_zephyr_perm( + characteristic->read_perm, characteristic->write_perm, characteristic->props); + + // Attr: characteristic declaration + size_t idx = self->attr_count; + self->attrs[idx] = (struct bt_gatt_attr) { + .uuid = (const struct bt_uuid *)&_uuid_chrc, + .perm = BT_GATT_PERM_READ, + .read = bt_gatt_attr_read_chrc, + .user_data = &characteristic->zephyr_chrc, + }; + idx++; + + // Attr: characteristic value (UUID points into characteristic, which persists) + characteristic->value_attr_index = idx; + self->attrs[idx] = (struct bt_gatt_attr) { + .uuid = &characteristic->zephyr_uuid.uuid, + .perm = perm, + .read = (characteristic->props & CHAR_PROP_READ) ? bleio_char_read_cb : NULL, + .write = (characteristic->props & (CHAR_PROP_WRITE | CHAR_PROP_WRITE_NO_RESPONSE)) ? bleio_char_write_cb : NULL, + .user_data = characteristic, + }; + idx++; + + // Attr: CCC descriptor (for NOTIFY/INDICATE) + if (needs_ccc) { + characteristic->zephyr_ccc = (struct bt_gatt_ccc_managed_user_data) + BT_GATT_CCC_MANAGED_USER_DATA_INIT(bleio_ccc_changed_cb, bleio_ccc_write_cb, NULL); + self->attrs[idx] = (struct bt_gatt_attr) { + .uuid = (const struct bt_uuid *)&_uuid_ccc, + .perm = BT_GATT_PERM_READ | ccc_write_perm(characteristic->read_perm), + .read = bt_gatt_attr_read_ccc, + .write = bt_gatt_attr_write_ccc, + .user_data = &characteristic->zephyr_ccc, + }; + idx++; + } + + // Attr: user description descriptor + if (needs_user_desc) { + self->attrs[idx] = (struct bt_gatt_attr) { + .uuid = (const struct bt_uuid *)&_uuid_cud, + .perm = BT_GATT_PERM_READ, + .read = bt_gatt_attr_read_cud, + .user_data = (void *)user_description, + }; + idx++; + } + + self->attr_count = idx; + + // Add characteristic to list + mp_obj_list_append(MP_OBJ_FROM_PTR(self->characteristic_list), + MP_OBJ_FROM_PTR(characteristic)); + + // Register the service + self->zephyr_service.attrs = self->attrs; + self->zephyr_service.attr_count = self->attr_count; + int err = bt_gatt_service_register(&self->zephyr_service); + if (err != 0) { + raise_zephyr_error(err); + } + self->registered = true; + // Zephyr now points into this object; keep it alive until unregistered. + service_retain(self); +} diff --git a/ports/zephyr-cp/common-hal/_bleio/Service.h b/ports/zephyr-cp/common-hal/_bleio/Service.h new file mode 100644 index 00000000000..75731bc6e09 --- /dev/null +++ b/ports/zephyr-cp/common-hal/_bleio/Service.h @@ -0,0 +1,43 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Dan Halbert for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include + +#include "py/obj.h" +#include "py/objlist.h" +#include "common-hal/_bleio/UUID.h" + +typedef struct bleio_service_obj { + mp_obj_base_t base; + bleio_uuid_obj_t *uuid; + mp_obj_t connection; + mp_obj_list_t *characteristic_list; + uint16_t start_handle; + uint16_t end_handle; + bool is_remote; + bool is_secondary; + // Zephyr GATT server fields: + struct bt_gatt_service zephyr_service; + struct bt_gatt_attr *attrs; + size_t attr_count; + size_t attr_capacity; + struct bt_uuid_128 zephyr_uuid; + bool registered; + // Link in the list of heap services retained while Zephyr's GATT database + // refers to them. See bleio_service_unregister_retained(). + struct bleio_service_obj *next_retained; +} bleio_service_obj_t; + +// Unregister every user-created service still in Zephyr's GATT database and +// free their port-heap buffers. Call from bleio_user_reset(), while the GC heap +// the service objects live in is still valid. +void bleio_service_unregister_retained(void); + +// Mark the retained services as reachable during a GC pass. +void bleio_service_gc_collect(void); diff --git a/ports/zephyr-cp/common-hal/_bleio/UUID.c b/ports/zephyr-cp/common-hal/_bleio/UUID.c new file mode 100644 index 00000000000..9e963b1b0bc --- /dev/null +++ b/ports/zephyr-cp/common-hal/_bleio/UUID.c @@ -0,0 +1,50 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Dan Halbert for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include + +#include "py/runtime.h" +#include "shared-bindings/_bleio/UUID.h" + +void common_hal_bleio_uuid_construct(bleio_uuid_obj_t *self, mp_int_t uuid16, const uint8_t uuid128[16]) { + self->uuid16 = (uint16_t)uuid16; + if (uuid128 == NULL) { + // 16-bit UUID — only bytes 12-13 matter; rest is zero (matching ble_hci). + self->size = BT_UUID_SIZE_16; + memset(self->uuid128, 0, 16); + self->uuid128[12] = uuid16 & 0xff; + self->uuid128[13] = (uuid16 >> 8) & 0xff; + } else { + // 128-bit UUID — uuid128 has bytes 12-13 zeroed, uuid16 is extracted from them + self->size = BT_UUID_SIZE_128; + memcpy(self->uuid128, uuid128, 16); + // Restore the 16-bit portion from uuid16 into bytes 12-13 (little-endian). + self->uuid128[12] = uuid16 & 0xff; + self->uuid128[13] = uuid16 >> 8; + } +} + +uint32_t common_hal_bleio_uuid_get_uuid16(bleio_uuid_obj_t *self) { + return self->uuid16; +} + +void common_hal_bleio_uuid_get_uuid128(bleio_uuid_obj_t *self, uint8_t uuid128[16]) { + memcpy(uuid128, self->uuid128, 16); +} + +uint32_t common_hal_bleio_uuid_get_size(bleio_uuid_obj_t *self) { + return self->size == BT_UUID_SIZE_16 ? 16 : 128; +} + +void common_hal_bleio_uuid_pack_into(bleio_uuid_obj_t *self, uint8_t *buf) { + if (self->size == BT_UUID_SIZE_16) { + buf[0] = self->uuid128[12]; + buf[1] = self->uuid128[13]; + } else { + memcpy(buf, self->uuid128, 16); + } +} diff --git a/ports/zephyr-cp/common-hal/_bleio/UUID.h b/ports/zephyr-cp/common-hal/_bleio/UUID.h new file mode 100644 index 00000000000..9a0743a1b60 --- /dev/null +++ b/ports/zephyr-cp/common-hal/_bleio/UUID.h @@ -0,0 +1,19 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Dan Halbert for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include + +#include "py/obj.h" + +typedef struct { + mp_obj_base_t base; + uint8_t uuid128[16]; + uint8_t size; // BT_UUID_SIZE_16 (2) or BT_UUID_SIZE_128 (16) + uint16_t uuid16; +} bleio_uuid_obj_t; diff --git a/ports/zephyr-cp/common-hal/_bleio/__init__.c b/ports/zephyr-cp/common-hal/_bleio/__init__.c new file mode 100644 index 00000000000..c29e7aae085 --- /dev/null +++ b/ports/zephyr-cp/common-hal/_bleio/__init__.c @@ -0,0 +1,268 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018 Dan Halbert for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "py/runtime.h" +#include "shared-bindings/_bleio/__init__.h" +#include "shared-bindings/_bleio/Adapter.h" +#include "common-hal/_bleio/Adapter.h" +#include "common-hal/_bleio/__init__.h" +#include "bindings/zephyr_kernel/__init__.h" +#include "common-hal/_bleio/Connection.h" +#include "common-hal/_bleio/Service.h" +#include "supervisor/shared/bluetooth/bluetooth.h" +#include "supervisor/shared/tick.h" + +#include + +// The singleton _bleio.Adapter object +bleio_adapter_obj_t common_hal_bleio_adapter_obj; + +// Called once by the BLE workflow at boot and again on every `import _bleio`, +// so it must not disturb a running adapter: the workflow may be advertising or +// connected by the time user code imports the module. Starting the BLE stack happens in +// common_hal_bleio_adapter_set_enabled(), which the importer calls next. +void common_hal_bleio_init(void) { + common_hal_bleio_adapter_obj.base.type = &bleio_adapter_type; + bleio_connection_register_auth_callbacks(); +} + +// Tear down user BLE state at the end of a VM run, leaving the BLE workflow +// connection up. Runs while the VM heap is still valid. +void bleio_user_reset(void) { + if (common_hal_bleio_adapter_get_enabled(&common_hal_bleio_adapter_obj)) { + // Stop any user scanning or advertising. + common_hal_bleio_adapter_stop_scan(&common_hal_bleio_adapter_obj); + common_hal_bleio_adapter_stop_advertising(&common_hal_bleio_adapter_obj); + + // Disconnect the connections that user code initiated or accepted with its + // own advertising. The BLE workflow connection is not user-owned and stays up. + // + // Clear each connection's pointer into the VM heap first: the heap is about + // to go away, and a disconnect completes asynchronously, possibly after the heap + // is gone. + for (size_t i = 0; i < BLEIO_TOTAL_CONNECTION_COUNT; i++) { + bleio_connection_internal_t *connection = &bleio_connections[i]; + connection->connection_obj = mp_const_none; + if (connection->conn != NULL && connection->user_owned) { + common_hal_bleio_connection_disconnect(connection); + } + } + + // Remove references to any VM heap objects. + common_hal_bleio_adapter_obj.connection_objs = NULL; + common_hal_bleio_adapter_obj.scan_results = NULL; + } + + // Remove user-created services from Zephyr's GATT database and free their + // buffers. Zephyr indicates Service Changed to connected peers itself, and + // records it for bonded peers to receive when they next connect. + bleio_service_unregister_retained(); + + // Maybe start advertising the BLE workflow. + supervisor_bluetooth_background(); +} + +// Called after the VM heap is gone. On nordic and espressif this restarts the +// BLE stack when user code created GATT services, because their stacks can't +// remove services one at a time. Zephyr can, and bleio_user_reset() already did, +// so there is nothing left that requires dropping the workflow connection. +void bleio_reset(void) { + common_hal_bleio_adapter_obj.base.type = &bleio_adapter_type; + bleio_clear_user_services_created(); +} + +void common_hal_bleio_gc_collect(void) { + bleio_adapter_gc_collect(&common_hal_bleio_adapter_obj); + bleio_service_gc_collect(); +} + +// ======================================================================= +// Shared synchronous GATT helpers +// ======================================================================= + +typedef struct { + uint8_t *buf; + size_t buf_len; + size_t read_len; + volatile bool done; + volatile int err; +} gattc_read_ctx_t; + +typedef struct { + volatile bool done; + volatile int err; +} gattc_write_ctx_t; + +static gattc_read_ctx_t *active_read_ctx; +static gattc_write_ctx_t *active_write_ctx; +static struct bt_gatt_read_params read_params; +static struct bt_gatt_write_params write_params; + +static uint8_t on_gattc_read(struct bt_conn *conn, uint8_t err, + struct bt_gatt_read_params *params, + const void *data, uint16_t length) { + gattc_read_ctx_t *ctx = active_read_ctx; + if (ctx == NULL) { + return BT_GATT_ITER_STOP; + } + + if (err) { + ctx->err = err; + ctx->done = true; + return BT_GATT_ITER_STOP; + } + + if (data == NULL || length == 0) { + ctx->done = true; + return BT_GATT_ITER_STOP; + } + + size_t copy_len = length; + if (ctx->read_len + copy_len > ctx->buf_len) { + copy_len = ctx->buf_len - ctx->read_len; + } + if (copy_len > 0) { + memcpy(ctx->buf + ctx->read_len, data, copy_len); + ctx->read_len += copy_len; + } + + ctx->done = true; + return BT_GATT_ITER_STOP; +} + +static void on_gattc_write(struct bt_conn *conn, uint8_t err, + struct bt_gatt_write_params *params) { + gattc_write_ctx_t *ctx = active_write_ctx; + if (ctx == NULL) { + return; + } + ctx->err = err; + ctx->done = true; +} + +// Raise an exception for a nonzero ATT error code from a GATT client read or write. +// connected is whether the connection was still up when the request finished. +static void check_gattc_status(bool connected, uint8_t err) { + if (err == 0) { + return; + } + // Zephyr reports local failures, including a disconnect while the request was + // outstanding, as BT_ATT_ERR_UNLIKELY. Check the connection before blaming the peer. + if (!connected) { + mp_raise_ConnectionError(MP_ERROR_TEXT("Not connected")); + } + switch (err) { + case BT_ATT_ERR_READ_NOT_PERMITTED: + mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("%q not permitted"), MP_QSTR_read); + return; + case BT_ATT_ERR_WRITE_NOT_PERMITTED: + mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("%q not permitted"), MP_QSTR_write); + return; + case BT_ATT_ERR_AUTHENTICATION: + mp_raise_bleio_SecurityError(MP_ERROR_TEXT("Insufficient authentication")); + return; + case BT_ATT_ERR_AUTHORIZATION: + mp_raise_bleio_SecurityError(MP_ERROR_TEXT("Insufficient authorization")); + return; + case BT_ATT_ERR_INSUFFICIENT_ENCRYPTION: + case BT_ATT_ERR_ENCRYPTION_KEY_SIZE: + mp_raise_bleio_SecurityError(MP_ERROR_TEXT("Insufficient encryption")); + return; + case BT_ATT_ERR_INVALID_ATTRIBUTE_LEN: + mp_arg_error_invalid(MP_QSTR_length); + return; + default: + mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Unknown gatt error: 0x%04x"), err); + } +} + +static bool conn_is_connected(struct bt_conn *conn) { + struct bt_conn_info info; + return bt_conn_get_info(conn, &info) == 0 && info.state == BT_CONN_STATE_CONNECTED; +} + +size_t bleio_gattc_read_sync(struct bt_conn *conn, uint16_t handle, + uint8_t *buf, size_t len) { + gattc_read_ctx_t ctx = { + .buf = buf, + .buf_len = len, + .read_len = 0, + .done = false, + .err = 0, + }; + active_read_ctx = &ctx; + + memset(&read_params, 0, sizeof(read_params)); + read_params.func = on_gattc_read; + read_params.handle_count = 1; + read_params.single.handle = handle; + read_params.single.offset = 0; + + // `bt_conn_ref()` holds a reference to the connection, so conn stays valid until + // its state is checked below, even if a disconnect drops the connection's own + // reference meanwhile. It returns NULL if the peer has already disconnected. + if (bt_conn_ref(conn) == NULL) { + active_read_ctx = NULL; + mp_raise_ConnectionError(MP_ERROR_TEXT("Not connected")); + } + int err = bt_gatt_read(conn, &read_params); + if (err != 0) { + active_read_ctx = NULL; + bt_conn_unref(conn); + raise_zephyr_error(err); + } + + while (!ctx.done) { + RUN_BACKGROUND_TASKS; + } + active_read_ctx = NULL; + + bool connected = conn_is_connected(conn); + bt_conn_unref(conn); + check_gattc_status(connected, ctx.err); + + return ctx.read_len; +} + +void bleio_gattc_write_sync(struct bt_conn *conn, uint16_t handle, + const uint8_t *data, size_t len) { + gattc_write_ctx_t ctx = { + .done = false, + .err = 0, + }; + active_write_ctx = &ctx; + + memset(&write_params, 0, sizeof(write_params)); + write_params.func = on_gattc_write; + write_params.handle = handle; + write_params.offset = 0; + write_params.data = data; + write_params.length = len; + + // `bt_conn_ref()` holds a reference to the connection, so conn stays valid until + // its state is checked below, even if a disconnect drops the connection's own + // reference meanwhile. It returns NULL if the peer has already disconnected. + if (bt_conn_ref(conn) == NULL) { + active_write_ctx = NULL; + mp_raise_ConnectionError(MP_ERROR_TEXT("Not connected")); + } + int err = bt_gatt_write(conn, &write_params); + if (err != 0) { + active_write_ctx = NULL; + bt_conn_unref(conn); + raise_zephyr_error(err); + } + + while (!ctx.done) { + RUN_BACKGROUND_TASKS; + } + active_write_ctx = NULL; + + bool connected = conn_is_connected(conn); + bt_conn_unref(conn); + check_gattc_status(connected, ctx.err); +} diff --git a/ports/zephyr-cp/common-hal/_bleio/__init__.h b/ports/zephyr-cp/common-hal/_bleio/__init__.h new file mode 100644 index 00000000000..72dc249d142 --- /dev/null +++ b/ports/zephyr-cp/common-hal/_bleio/__init__.h @@ -0,0 +1,47 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018 Dan Halbert for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include + +#include +#include +#include + +#include "common-hal/_bleio/UUID.h" + +// Convert a CircuitPython bleio UUID to a Zephyr bt_uuid stored in caller- +// provided bt_uuid_128 storage. For 16-bit UUIDs we reinterpret the storage +// as bt_uuid_16 and write .val (at offset 2, matching Zephyr's struct layout). +// For 128-bit UUIDs the 16-byte value is copied directly into bt_uuid_128.val. +// The result can be used as `&out->uuid` wherever a `const struct bt_uuid *` +// is needed; Zephyr dispatches on the .type field at runtime. +static inline void bleio_uuid_to_zephyr(const bleio_uuid_obj_t *cp_uuid, + struct bt_uuid_128 *out) { + if (cp_uuid->size == BT_UUID_SIZE_16) { + out->uuid.type = BT_UUID_TYPE_16; + ((struct bt_uuid_16 *)out)->val = + (cp_uuid->uuid128[13] << 8) | cp_uuid->uuid128[12]; + } else { + out->uuid.type = BT_UUID_TYPE_128; + // Both CP and Zephyr store UUID bytes in little-endian order. + memcpy(out->val, cp_uuid->uuid128, 16); + } +} + +// Shared synchronous GATT helpers — wrap Zephyr's async bt_gatt_read/write +// into a blocking call with RUN_BACKGROUND_TASKS spinning. +size_t bleio_gattc_read_sync(struct bt_conn *conn, uint16_t handle, + uint8_t *buf, size_t len); +void bleio_gattc_write_sync(struct bt_conn *conn, uint16_t handle, + const uint8_t *data, size_t len); + +// Abort any in-flight remote GATT discovery; called from the disconnect +// callback so discover_remote_services() fails cleanly instead of hanging +// or NULL-dereferencing the cleared connection. +void bleio_connection_discovery_abort(void); diff --git a/ports/zephyr-cp/common-hal/analogio/AnalogIn.c b/ports/zephyr-cp/common-hal/analogio/AnalogIn.c new file mode 100644 index 00000000000..70f27962495 --- /dev/null +++ b/ports/zephyr-cp/common-hal/analogio/AnalogIn.c @@ -0,0 +1,173 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/analogio/AnalogIn.h" +#include "shared-bindings/microcontroller/Pin.h" + +#include + +#include +#include + +#include "bindings/zephyr_kernel/__init__.h" +#include "py/runtime.h" + +// Zephyr has no API to query an ADC's native resolution: adc_sequence.resolution +// is set by the caller and drivers reject values they can't meet (from probe +// time, before any conversion starts). Ask the driver for the highest +// resolution it accepts with a descending ladder of one-read probes. The +// emulated ADC answers 16; the SAADC only accepts 8/10/12/14 and the Renesas +// RA ADC its fixed hardware resolution. +static const uint8_t adc_resolutions[] = {16, 14, 12, 10, 8}; + +// Every (reference, gain) pair over the VDD-derived references with gain +// cancelling the divider, i.e. full scale = reference / gain = VDD, which is +// what the 16-bit analogio scaling contract assumes. Drivers only accept the +// combinations their hardware supports (the nRF52 family SAADC has no full-VDD +// reference and lands on VDD/4); probe down the ladder at construct time. +static const struct { + enum adc_reference reference; + enum adc_gain gain; +} adc_railings[] = { + {ADC_REF_VDD_1, ADC_GAIN_1}, + {ADC_REF_VDD_1_2, ADC_GAIN_1_2}, + {ADC_REF_VDD_1_3, ADC_GAIN_1_3}, + {ADC_REF_VDD_1_4, ADC_GAIN_1_4}, +}; + +void common_hal_analogio_analogin_construct(analogio_analogin_obj_t *self, const mcu_pin_obj_t *pin) { + // Allocate the pad's analog input through the iobroker module: the call + // claims the pad so that bus and GPIO allocations refuse it, resolves the + // fixed analog input the pad is bonded to (identity on the emulated ADC) + // and hands out a free channel slot on the ADC device. + const struct device *adc; + uint8_t channel; + uint8_t input; + int res = iobroker_adc_allocate(pin->package_pin, &adc, &channel, &input); + if (res == -ENOSYS) { + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_AnalogIn); + } + if (res == -EINVAL) { + // The pad exists but isn't bonded to an analog input. Match the other + // ports, which raise ValueError("Invalid pin") for such pins. + raise_ValueError_invalid_pin(); + } + if (res < 0) { + raise_zephyr_error(res); + } + + if (!device_is_ready(adc)) { + iobroker_adc_release(adc, channel); + raise_zephyr_error(-ENODEV); + } + + // Sample against the analog supply, like the other ports (SAMD's + // INTVCC1, RP2040's VREF pin, STM32/Espressif's supply-referenced + // ranges): full scale is VDD/VDDA, so a full-rail input reads 65535. + struct adc_channel_cfg channel_cfg = { + .acquisition_time = ADC_ACQ_TIME_DEFAULT, + .channel_id = channel, + }; + #ifdef CONFIG_ADC_CONFIGURABLE_INPUTS + channel_cfg.input_positive = input; + #endif + + int err = 0; + for (uint8_t i = 0; i < ARRAY_SIZE(adc_railings); i++) { + channel_cfg.reference = adc_railings[i].reference; + channel_cfg.gain = adc_railings[i].gain; + err = adc_channel_setup(adc, &channel_cfg); + if (err != -EINVAL) { + break; + } + } + if (err != 0) { + iobroker_adc_release(adc, channel); + raise_zephyr_error(err); + } + + // Do dummy reads to determine what resolution the device actually support. + uint16_t probe = 0; + uint8_t resolution = 0; + for (uint8_t i = 0; i < ARRAY_SIZE(adc_resolutions); i++) { + struct adc_sequence probe_sequence = { + .channels = BIT(channel), + .buffer = &probe, + .buffer_size = sizeof(probe), + .resolution = adc_resolutions[i], + }; + err = adc_read(adc, &probe_sequence); + if (err == 0) { + resolution = adc_resolutions[i]; + break; + } + if (err != -EINVAL && err != -ENOTSUP) { + // Not a resolution rejection (drivers report those before sampling): + // surface driver errors like -EBUSY rather than skipping them. + iobroker_adc_release(adc, channel); + raise_zephyr_error(err); + } + } + if (resolution == 0) { + iobroker_adc_release(adc, channel); + raise_zephyr_error(-ENOTSUP); + } + + self->pin = pin; + self->adc = adc; + self->channel_id = channel; + self->resolution = resolution; +} + +bool common_hal_analogio_analogin_deinited(analogio_analogin_obj_t *self) { + return self->adc == NULL; +} + +void common_hal_analogio_analogin_deinit(analogio_analogin_obj_t *self) { + if (common_hal_analogio_analogin_deinited(self)) { + return; + } + + (void)iobroker_adc_release(self->adc, self->channel_id); + self->pin = NULL; + self->adc = NULL; +} + +uint16_t common_hal_analogio_analogin_get_value(analogio_analogin_obj_t *self) { + // Sample at the ADC's full hardware resolution (probed at construct) and + // stretch the raw code to CircuitPython's 16-bit contract relative to the + // reference voltage, which is what the analogio contract is. + uint16_t raw = 0; + struct adc_sequence sequence = { + .channels = BIT(self->channel_id), + .buffer = &raw, + .buffer_size = sizeof(raw), + .resolution = self->resolution, + }; + + int err = adc_read(self->adc, &sequence); + if (err != 0) { + raise_zephyr_error(err); + } + + if (self->resolution >= 16) { + return raw; + } + + // Mirror the top 16 - resolution bits into the bottom: for a 14-bit read, + // (value << 2) | (value >> 12) (atmel-samd does the same for its 12-bit + // reads). raw << shift fits in 16 bits because raw is at most resolution + // bits wide. Zero and full scale map to themselves, unlike scaling by + // 65535 / max_raw which bunches codes near zero. + const uint8_t shift = 16 - self->resolution; + return (uint16_t)((raw << shift) | (raw >> (self->resolution - shift))); +} + +float common_hal_analogio_analogin_get_reference_voltage(analogio_analogin_obj_t *self) { + // Hard-coded until the reference-voltage query API (upstream adc_ref_get()) + // is available; every other port also reports the nominal analog supply. + return 3.3f; +} diff --git a/ports/zephyr-cp/common-hal/analogio/AnalogIn.h b/ports/zephyr-cp/common-hal/analogio/AnalogIn.h new file mode 100644 index 00000000000..e8fababe1e0 --- /dev/null +++ b/ports/zephyr-cp/common-hal/analogio/AnalogIn.h @@ -0,0 +1,21 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "common-hal/microcontroller/Pin.h" + +#include + +#include "py/obj.h" + +typedef struct { + mp_obj_base_t base; + const mcu_pin_obj_t *pin; + const struct device *adc; + uint8_t channel_id; + uint8_t resolution; +} analogio_analogin_obj_t; diff --git a/ports/zephyr-cp/common-hal/analogio/AnalogOut.c b/ports/zephyr-cp/common-hal/analogio/AnalogOut.c new file mode 100644 index 00000000000..a558a0e2b82 --- /dev/null +++ b/ports/zephyr-cp/common-hal/analogio/AnalogOut.c @@ -0,0 +1,106 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/analogio/AnalogOut.h" +#include "shared-bindings/microcontroller/Pin.h" + +#include +#include +#include + +#include "bindings/zephyr_kernel/__init__.h" +#include "py/runtime.h" + +void common_hal_analogio_analogout_construct(analogio_analogout_obj_t *self, const mcu_pin_obj_t *pin) { + // Allocate the pad's analog output through the iobroker module: the call + // claims the pad so that bus and GPIO allocations refuse it and hands out + // a free channel slot on the DAC device. + const struct device *dac; + uint8_t channel; + uint8_t input; + int res = iobroker_dac_allocate(pin->package_pin, &dac, &channel, &input); + if (res == -ENOSYS) { + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_AnalogOut); + } + if (res == -EINVAL) { + // The pad exists but isn't bonded to a DAC output. Match the other + // ports, which raise ValueError("Invalid pin") for such pins. + raise_ValueError_invalid_pin(); + } + if (res < 0) { + raise_zephyr_error(res); + } + + struct dac_channel_cfg channel_cfg = { + .channel_id = channel, + .buffered = true, + .internal = false, + }; + + // Ask the driver for the highest resolution it accepts, instead of picking + // one per driver Kconfig: drivers reject an unsupported resolution from + // dac_channel_setup() with -EINVAL/-ENOTSUP before touching hardware. The + // emulated test DAC answers 16; the RA DAC12 and NXP LPDAC only accept + // their 12-bit hardware resolution; writes are scaled down in + // common_hal_analogio_analogout_set_value(). + static const uint8_t dac_resolutions[] = {16, 12}; + for (uint8_t i = 0; i < ARRAY_SIZE(dac_resolutions); i++) { + channel_cfg.resolution = dac_resolutions[i]; + res = dac_channel_setup(dac, &channel_cfg); + if (res == 0 || (res != -EINVAL && res != -ENOTSUP)) { + // Not a resolution rejection: surface driver errors like -EBUSY. + break; + } + } + if (res != 0) { + iobroker_dac_release(dac, channel); + raise_zephyr_error(res); + } + + self->pin = pin; + self->dac = dac; + self->channel_id = channel; + self->resolution = channel_cfg.resolution; +} + +bool common_hal_analogio_analogout_deinited(analogio_analogout_obj_t *self) { + return self->dac == NULL; +} + +void common_hal_analogio_analogout_deinit(analogio_analogout_obj_t *self) { + if (common_hal_analogio_analogout_deinited(self)) { + return; + } + + (void)iobroker_dac_release(self->dac, self->channel_id); + self->pin = NULL; + self->dac = NULL; +} + +void common_hal_analogio_analogout_set_value(analogio_analogout_obj_t *self, uint16_t value) { + if (common_hal_analogio_analogout_deinited(self)) { + return; + } + + if (self->resolution != 16) { + // CircuitPython's 16-bit code scales down to the DAC's resolution + // (probed at construct) with converter rounding: (value * out_max + + // in_max / 2) / in_max, the same rounding the emulated DAC applies in + // reverse. + const uint32_t in_max = 65535u; + const uint32_t out_max = (1u << self->resolution) - 1u; + uint32_t scaled = ((uint32_t)value * out_max + in_max / 2u) / in_max; + if (scaled > out_max) { + scaled = out_max; + } + value = (uint16_t)scaled; + } + + int err = dac_write_value(self->dac, self->channel_id, value); + if (err != 0) { + raise_zephyr_error(err); + } +} diff --git a/ports/zephyr-cp/common-hal/analogio/AnalogOut.h b/ports/zephyr-cp/common-hal/analogio/AnalogOut.h new file mode 100644 index 00000000000..333163cb2b1 --- /dev/null +++ b/ports/zephyr-cp/common-hal/analogio/AnalogOut.h @@ -0,0 +1,21 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +#include + +#include "common-hal/microcontroller/Pin.h" + +typedef struct { + mp_obj_base_t base; + const mcu_pin_obj_t *pin; + const struct device *dac; + uint8_t channel_id; + uint8_t resolution; +} analogio_analogout_obj_t; diff --git a/ports/zephyr-cp/common-hal/analogio/__init__.c b/ports/zephyr-cp/common-hal/analogio/__init__.c new file mode 100644 index 00000000000..803ce3b3cb7 --- /dev/null +++ b/ports/zephyr-cp/common-hal/analogio/__init__.c @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +// No analogio module functions. diff --git a/ports/zephyr-cp/common-hal/async_spi/SPI.c b/ports/zephyr-cp/common-hal/async_spi/SPI.c new file mode 100644 index 00000000000..0a87f240eab --- /dev/null +++ b/ports/zephyr-cp/common-hal/async_spi/SPI.c @@ -0,0 +1,263 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/async_spi/SPI.h" + +#include + +#include "py/runtime.h" +#include "supervisor/port.h" +#include "bindings/zephyr_kernel/__init__.h" + +#include +#include + +// Settings take the other config slot: drivers see a change by the pointer. +static void apply_config(async_spi_spi_obj_t *self, uint32_t frequency, uint16_t operation) { + struct spi_config *current = &self->config[self->active_config]; + if (current->frequency == frequency && current->operation == operation) { + return; + } + self->active_config = 1 - self->active_config; + self->config[self->active_config].frequency = frequency; + self->config[self->active_config].operation = operation; +} + +static void transfer_done(const struct device *dev, int result, void *userdata) { + ARG_UNUSED(dev); + async_spi_spi_obj_t *self = userdata; + self->result = result; + CIRCUITPY_ASYNC_FLAG_SET(self->done); + port_wake_main_task_from_isr(); +} + +// Zephyr cannot stop a transfer, so cancel and deinit wait for it. No background tasks: this +// also runs from a finalizer during GC. +static void wait_done(async_spi_spi_obj_t *self) { + if (self->done == NULL) { + return; + } + while (!CIRCUITPY_ASYNC_FLAG_IS_SET(self->done)) { + port_task_sleep_ms(1); + } + self->done = NULL; +} + +// A fixed devicetree device, as for board.SPI(): already initialized, never released. +void common_hal_async_spi_spi_construct_from_device(async_spi_spi_obj_t *self, + const struct device *dev) { + circuitpy_async_lock_init(&self->lock); + self->spi_device = dev; + self->dynamic = false; + self->clock = NULL; + self->mosi = NULL; + self->miso = NULL; + self->active_config = 0; + for (size_t i = 0; i < 2; i++) { + self->config[i].frequency = 100000; + self->config[i].operation = SPI_OP_MODE_MASTER | SPI_WORD_SET(8) | SPI_LINES_SINGLE; + } + self->done = NULL; + self->fill = NULL; + self->fill_len = 0; +} + +static void free_fill(async_spi_spi_obj_t *self) { + port_free(self->fill); + self->fill = NULL; + self->fill_len = 0; +} + +void common_hal_async_spi_spi_construct(async_spi_spi_obj_t *self, const mcu_pin_obj_t *clock, + const mcu_pin_obj_t *mosi, const mcu_pin_obj_t *miso) { + const struct device *dev = NULL; + int ret = iobroker_spi_allocate(clock->package_pin, + mosi != NULL ? mosi->package_pin : IOBROKER_NO_PIN, + miso != NULL ? miso->package_pin : IOBROKER_NO_PIN, &dev); + if (ret < 0) { + if (ret == -ENODEV) { + mp_raise_ValueError(MP_ERROR_TEXT("All SPI peripherals are in use")); + } + if (ret == -EBUSY) { + mp_raise_ValueError(MP_ERROR_TEXT("Internal resource(s) in use")); + } + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("Use device tree to define %q devices"), MP_QSTR_SPI); + } + + common_hal_async_spi_spi_construct_from_device(self, dev); + self->dynamic = true; + self->clock = clock; + self->mosi = mosi; + self->miso = miso; + + // A routed device is initialized now; a fixed one already was (-EALREADY). + int init_ret = device_init(dev); + if (init_ret < 0 && init_ret != -EALREADY) { + common_hal_async_spi_spi_deinit(self); + raise_zephyr_error(init_ret); + } +} + +bool common_hal_async_spi_spi_deinited(async_spi_spi_obj_t *self) { + return self->spi_device == NULL; +} + +void common_hal_async_spi_spi_deinit(async_spi_spi_obj_t *self) { + if (common_hal_async_spi_spi_deinited(self)) { + return; + } + circuitpy_async_lock_deinit(&self->lock); + wait_done(self); + free_fill(self); + // A fixed devicetree device (board.SPI()) stays usable. + if (!self->dynamic) { + return; + } + (void)iobroker_release(self->spi_device); + self->spi_device = NULL; + self->clock = NULL; + self->mosi = NULL; + self->miso = NULL; +} + +void common_hal_async_spi_spi_mark_deinit(async_spi_spi_obj_t *self) { + if (self->dynamic) { + self->spi_device = NULL; + } +} + +static uint16_t operation_of(uint8_t polarity, uint8_t phase, uint8_t bits) { + uint16_t operation = SPI_OP_MODE_MASTER | SPI_WORD_SET(bits) | SPI_LINES_SINGLE; + if (polarity) { + operation |= SPI_MODE_CPOL; + } + if (phase) { + operation |= SPI_MODE_CPHA; + } + return operation; +} + +// The caller holds the lock, so no transfer is running. +void common_hal_async_spi_spi_configure(async_spi_spi_obj_t *self, uint32_t baudrate, + uint8_t polarity, uint8_t phase, uint8_t bits) { + apply_config(self, baudrate, operation_of(polarity, phase, bits)); +} + +circuitpy_async_lock_obj_t *common_hal_async_spi_spi_get_lock(async_spi_spi_obj_t *self) { + return &self->lock; +} + +uint8_t common_hal_async_spi_spi_get_polarity(async_spi_spi_obj_t *self) { + return (self->config[self->active_config].operation & SPI_MODE_CPOL) != 0; +} + +uint8_t common_hal_async_spi_spi_get_phase(async_spi_spi_obj_t *self) { + return (self->config[self->active_config].operation & SPI_MODE_CPHA) != 0; +} + +uint32_t common_hal_async_spi_spi_get_frequency(async_spi_spi_obj_t *self) { + return self->config[self->active_config].frequency; +} + +// Start a transfer; done is set from the driver's callback, or at once for an empty one. +static void start(async_spi_spi_obj_t *self, const uint8_t *data_out, uint8_t *data_in, + size_t len, circuitpy_async_flag_t *done) { + wait_done(self); + CIRCUITPY_ASYNC_FLAG_INIT(done); + self->done = done; + self->result = 0; + if (len == 0) { + CIRCUITPY_ASYNC_FLAG_SET(done); + return; + } + self->tx_buf.buf = (void *)data_out; + self->tx_buf.len = len; + self->tx.buffers = &self->tx_buf; + self->tx.count = data_out != NULL ? 1 : 0; + self->rx_buf.buf = data_in; + self->rx_buf.len = len; + self->rx.buffers = &self->rx_buf; + self->rx.count = data_in != NULL ? 1 : 0; + + int ret = -ENOTSUP; + if (DEVICE_API_GET(spi, self->spi_device)->transceive_async != NULL) { + ret = spi_transceive_cb(self->spi_device, &self->config[self->active_config], + self->tx.count ? &self->tx : NULL, self->rx.count ? &self->rx : NULL, + transfer_done, self); + } + if (ret < 0) { + // Reported by transfer_end() or transfer_finish(); nothing raises here, as a + // blocking busio call may run from a background callback. + self->result = ret; + CIRCUITPY_ASYNC_FLAG_SET(done); + } +} + +void *common_hal_async_spi_spi_write_start(async_spi_spi_obj_t *self, const uint8_t *data, + size_t len, circuitpy_async_flag_t *done) { + start(self, data, NULL, len, done); + return NULL; +} + +void *common_hal_async_spi_spi_readinto_start(async_spi_spi_obj_t *self, uint8_t *data, + size_t len, uint8_t write_value, circuitpy_async_flag_t *done) { + // Without a TX buffer a driver sends its own idle value (0xFF on nRF), so the read sends + // write_value from a buffer, kept for the next read. The previous transfer must be over + // before it is touched. + wait_done(self); + uint8_t *fill = NULL; + if (len != 0) { + if (self->fill_len < len) { + free_fill(self); + // Allocate from the port heap, because board.SPI() and other static buses are not + // scanned by the GC. + self->fill = port_malloc(len, false); + if (self->fill == NULL) { + self->result = -ENOMEM; + CIRCUITPY_ASYNC_FLAG_INIT(done); + CIRCUITPY_ASYNC_FLAG_SET(done); + self->done = done; + return NULL; + } + self->fill_len = len; + } + fill = self->fill; + memset(fill, write_value, len); + } + start(self, fill, data, len, done); + return NULL; +} + +void *common_hal_async_spi_spi_write_readinto_start(async_spi_spi_obj_t *self, + const uint8_t *data_out, uint8_t *data_in, size_t len, circuitpy_async_flag_t *done) { + start(self, data_out, data_in, len, done); + return NULL; +} + +// Called once done is set. +bool common_hal_async_spi_spi_transfer_finish(async_spi_spi_obj_t *self, void *context, + circuitpy_async_flag_t *done) { + if (self->done != done) { + return true; + } + self->done = NULL; + return self->result == 0; +} + +mp_obj_t common_hal_async_spi_spi_transfer_end(async_spi_spi_obj_t *self, void *context, + circuitpy_async_flag_t *done) { + if (!common_hal_async_spi_spi_transfer_finish(self, context, done)) { + raise_zephyr_error(self->result); + } + return mp_const_none; +} + +void common_hal_async_spi_spi_transfer_cancel(async_spi_spi_obj_t *self, void *context, + circuitpy_async_flag_t *done) { + if (self->done == done) { + wait_done(self); + } +} diff --git a/ports/zephyr-cp/common-hal/async_spi/SPI.h b/ports/zephyr-cp/common-hal/async_spi/SPI.h new file mode 100644 index 00000000000..f81b013338c --- /dev/null +++ b/ports/zephyr-cp/common-hal/async_spi/SPI.h @@ -0,0 +1,39 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" +#include "common-hal/microcontroller/Pin.h" +#include "supervisor/shared/async_flag.h" +#include "supervisor/shared/awaitable.h" + +#include +#include +#include + +typedef struct { + mp_obj_base_t base; + circuitpy_async_lock_obj_t lock; + const struct device *spi_device; // NULL once deinited + bool dynamic; // routed to pins at construction, released at deinit + struct spi_config config[2]; // two slots: a driver sees a change by the pointer + uint8_t active_config; + const mcu_pin_obj_t *clock; + const mcu_pin_obj_t *mosi; + const mcu_pin_obj_t *miso; + circuitpy_async_flag_t *done; // of the running transfer, NULL when none + int result; // of the last transfer, from the driver + struct spi_buf tx_buf; // the running transfer's buffers + struct spi_buf rx_buf; + struct spi_buf_set tx; + struct spi_buf_set rx; + uint8_t *fill; // the bytes a read sends, when not zero + size_t fill_len; +} async_spi_spi_obj_t; + +void common_hal_async_spi_spi_construct_from_device(async_spi_spi_obj_t *self, + const struct device *dev); diff --git a/ports/zephyr-cp/common-hal/async_spi/__init__.c b/ports/zephyr-cp/common-hal/async_spi/__init__.c new file mode 100644 index 00000000000..59a4cec7fe9 --- /dev/null +++ b/ports/zephyr-cp/common-hal/async_spi/__init__.c @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +// No async_spi module functions. diff --git a/ports/zephyr-cp/common-hal/audiobusio/I2SOut.c b/ports/zephyr-cp/common-hal/audiobusio/I2SOut.c new file mode 100644 index 00000000000..d409d55a539 --- /dev/null +++ b/ports/zephyr-cp/common-hal/audiobusio/I2SOut.c @@ -0,0 +1,319 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/audiobusio/I2SOut.h" + +#include +#include +#include +#include +#include + +#include "bindings/zephyr_kernel/__init__.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-module/audiocore/__init__.h" +#include "py/gc.h" +#include "py/runtime.h" +#include "supervisor/port.h" + +#if CIRCUITPY_AUDIOBUSIO_I2SOUT + +#define AUDIO_THREAD_STACK_SIZE 2048 +#define AUDIO_THREAD_PRIORITY 5 + +// Forward declarations +static void fill_buffer(audiobusio_i2sout_obj_t *self, uint8_t *buffer, size_t buffer_size); +static void audio_thread_func(void *self_in, void *unused1, void *unused2); + +// Helper function for Zephyr-specific initialization from device tree +mp_obj_t common_hal_audiobusio_i2sout_construct_from_device(audiobusio_i2sout_obj_t *self, const struct device *i2s_device) { + self->base.type = &audiobusio_i2sout_type; + self->i2s_dev = i2s_device; + self->left_justified = false; + self->playing = false; + self->paused = false; + self->sample = NULL; + self->slab_buffer = NULL; + self->thread_stack = NULL; + self->thread_id = NULL; + self->block_size = 0; + + return MP_OBJ_FROM_PTR(self); +} + +// Standard audiobusio construct - not used in Zephyr port (devices come from device tree) +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, const mcu_pin_obj_t *main_clock, bool left_justified, + bool external_clock) { + if (external_clock) { + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_external_clock); + } + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("Use device tree to define %q devices"), MP_QSTR_I2S); +} + +bool common_hal_audiobusio_i2sout_deinited(audiobusio_i2sout_obj_t *self) { + return self->i2s_dev == NULL; +} + +void common_hal_audiobusio_i2sout_deinit(audiobusio_i2sout_obj_t *self) { + if (common_hal_audiobusio_i2sout_deinited(self)) { + return; + } + + // Stop playback (which will free buffers) + common_hal_audiobusio_i2sout_stop(self); + + // Note: Pins and I2S device are managed by Zephyr, not released here + self->i2s_dev = NULL; +} + +static void fill_buffer(audiobusio_i2sout_obj_t *self, uint8_t *buffer, size_t buffer_size) { + if (self->sample == NULL || self->paused || self->stopping) { + // Fill with silence + memset(buffer, 0, buffer_size); + return; + } + + uint32_t bytes_filled = 0; + while (bytes_filled < buffer_size) { + uint8_t *sample_buffer; + uint32_t sample_buffer_length; + + audioio_get_buffer_result_t result = audiosample_get_buffer( + self->sample, false, 0, &sample_buffer, &sample_buffer_length); + + if (result == GET_BUFFER_ERROR) { + // Error getting buffer, stop playback + self->stopping = true; + memset(buffer + bytes_filled, 0, buffer_size - bytes_filled); + return; + } + + // Copy the returned data first, even when this is the final buffer + // (GET_BUFFER_DONE). A single-buffer sample returns its entire buffer + // together with GET_BUFFER_DONE on the first call, so handling DONE + // before the copy would drop the audio and produce silence. + uint32_t bytes_to_copy = sample_buffer_length; + if (bytes_filled + bytes_to_copy > buffer_size) { + bytes_to_copy = buffer_size - bytes_filled; + } + + memcpy(buffer + bytes_filled, sample_buffer, bytes_to_copy); + bytes_filled += bytes_to_copy; + + if (result == GET_BUFFER_DONE) { + if (self->loop) { + // Reset to beginning + audiosample_reset_buffer(self->sample, false, 0); + } else { + // Final buffer copied; stop once this block drains. + self->stopping = true; + i2s_trigger(self->i2s_dev, I2S_DIR_TX, I2S_TRIGGER_DRAIN); + memset(buffer + bytes_filled, 0, buffer_size - bytes_filled); + return; + } + } + } +} + +static void audio_thread_func(void *self_in, void *unused1, void *unused2) { + audiobusio_i2sout_obj_t *self = (audiobusio_i2sout_obj_t *)self_in; + + while (!self->stopping) { + uint8_t *next_buffer = NULL; + // Wait until I2S has freed the buffer it is sending. + if (k_mem_slab_alloc(&self->mem_slab, (void **)&next_buffer, K_FOREVER) != 0) { + break; + } + if (self->stopping) { + // Stopping so break. + k_mem_slab_free(&self->mem_slab, next_buffer); + break; + } + fill_buffer(self, next_buffer, self->block_size); + + // Write to I2S + int ret = i2s_write(self->i2s_dev, next_buffer, self->block_size); + if (ret < 0) { + printk("i2s_write failed: %d\n", ret); + k_mem_slab_free(&self->mem_slab, next_buffer); + // Error writing, stop playback + self->playing = false; + break; + } + } +} + +void common_hal_audiobusio_i2sout_play(audiobusio_i2sout_obj_t *self, + mp_obj_t sample, bool loop) { + // Stop any existing playback + common_hal_audiobusio_i2sout_stop(self); + + audiosample_check(sample); + + // Get sample information + uint8_t bits_per_sample = audiosample_get_bits_per_sample(sample); + uint32_t sample_rate = audiosample_get_sample_rate(sample); + uint8_t channel_count = audiosample_get_channel_count(sample); + + // Store sample parameters + self->loop = loop; + self->bytes_per_sample = bits_per_sample / 8; + self->channel_count = channel_count; + self->stopping = false; + + // Get buffer structure from the sample + bool single_buffer, samples_signed; + uint32_t max_buffer_length; + uint8_t sample_spacing; + audiosample_get_buffer_structure(sample, /* single_channel_output */ false, + &single_buffer, &samples_signed, &max_buffer_length, &sample_spacing); + + // Use max_buffer_length from the sample as the block size + self->block_size = max_buffer_length; + if (channel_count == 1) { + // Make room for stereo samples. + self->block_size *= 2; + } + size_t block_size = self->block_size; + uint32_t num_blocks = 4; // Use 4 blocks for buffering + + // Allocate memory slab buffer. Board I2SOut objects are static, so the GC doesn't scan them. + self->slab_buffer = port_malloc(self->block_size * num_blocks, true); + if (self->slab_buffer == NULL) { + m_malloc_fail(self->block_size * num_blocks); + } + self->sample = sample; + + // Initialize memory slab + int ret = k_mem_slab_init(&self->mem_slab, self->slab_buffer, block_size, num_blocks); + if (ret != 0) { + common_hal_audiobusio_i2sout_stop(self); + raise_zephyr_error(ret); + } + + // Configure I2S + struct i2s_config config; + config.word_size = bits_per_sample; + config.channels = 2; + config.format = self->left_justified ? I2S_FMT_DATA_FORMAT_LEFT_JUSTIFIED : I2S_FMT_DATA_FORMAT_I2S; + config.options = I2S_OPT_BIT_CLK_MASTER | I2S_OPT_FRAME_CLK_MASTER; + config.frame_clk_freq = sample_rate; + config.mem_slab = &self->mem_slab; + config.block_size = block_size; + config.timeout = 1000; // Not a k_timeout_t. In milliseconds. + + // Configure returns EINVAL if the I2S device is not ready. We loop on this + // because it should be ready after it comes to a complete stop. + ret = -EAGAIN; + while (ret == -EAGAIN) { + ret = i2s_configure(self->i2s_dev, I2S_DIR_TX, &config); + } + if (ret != 0) { + common_hal_audiobusio_i2sout_stop(self); + raise_zephyr_error(ret); + } + + // Fill every slab before starting playback to avoid underruns. + for (uint32_t i = 0; i < num_blocks; i++) { + uint8_t *buf = NULL; + k_mem_slab_alloc(&self->mem_slab, (void **)&buf, K_NO_WAIT); + fill_buffer(self, buf, block_size); + ret = i2s_write(self->i2s_dev, buf, block_size); + if (ret < 0) { + printk("i2s_write failed: %d\n", ret); + k_mem_slab_free(&self->mem_slab, buf); + common_hal_audiobusio_i2sout_stop(self); + raise_zephyr_error(ret); + } + } + + // Allocate thread stack with proper MPU alignment for HW stack protection + self->thread_stack = k_thread_stack_alloc(AUDIO_THREAD_STACK_SIZE, 0); + + // Create and start audio processing thread + self->thread_id = k_thread_create(&self->thread, self->thread_stack, + AUDIO_THREAD_STACK_SIZE, + audio_thread_func, + self, NULL, NULL, + AUDIO_THREAD_PRIORITY, 0, K_NO_WAIT); + // Start I2S + ret = i2s_trigger(self->i2s_dev, I2S_DIR_TX, I2S_TRIGGER_START); + if (ret < 0) { + common_hal_audiobusio_i2sout_stop(self); + raise_zephyr_error(ret); + } + + self->playing = true; +} + +void common_hal_audiobusio_i2sout_stop(audiobusio_i2sout_obj_t *self) { + self->playing = false; + self->paused = false; + // Nothing to stop until play() has allocated the slab. play() also calls this on its error + // paths, before it sets playing. + if (self->slab_buffer == NULL) { + return; + } + self->stopping = true; + + // Stop I2S + i2s_trigger(self->i2s_dev, I2S_DIR_TX, I2S_TRIGGER_DROP); + + // Wait for thread to finish + if (self->thread_id != NULL) { + k_thread_join(self->thread_id, K_FOREVER); + self->thread_id = NULL; + } + + // Free thread stack + if (self->thread_stack != NULL) { + k_thread_stack_free(self->thread_stack); + self->thread_stack = NULL; + } + + // Free buffers + if (self->slab_buffer != NULL) { + port_free(self->slab_buffer); + self->slab_buffer = NULL; + } + + self->sample = NULL; +} + +void audiobusio_i2sout_collect_ptrs(audiobusio_i2sout_obj_t *self) { + gc_collect_ptr(self->sample); +} + +bool common_hal_audiobusio_i2sout_get_playing(audiobusio_i2sout_obj_t *self) { + return self->playing; +} + +void common_hal_audiobusio_i2sout_pause(audiobusio_i2sout_obj_t *self) { + if (!self->playing || self->paused) { + return; + } + + self->paused = true; + i2s_trigger(self->i2s_dev, I2S_DIR_TX, I2S_TRIGGER_STOP); +} + +void common_hal_audiobusio_i2sout_resume(audiobusio_i2sout_obj_t *self) { + if (!self->playing || !self->paused) { + return; + } + + self->paused = false; + // Thread will automatically resume filling buffers + i2s_trigger(self->i2s_dev, I2S_DIR_TX, I2S_TRIGGER_START); +} + +bool common_hal_audiobusio_i2sout_get_paused(audiobusio_i2sout_obj_t *self) { + return self->paused; +} + +#endif // CIRCUITPY_AUDIOBUSIO_I2SOUT diff --git a/ports/zephyr-cp/common-hal/audiobusio/I2SOut.h b/ports/zephyr-cp/common-hal/audiobusio/I2SOut.h new file mode 100644 index 00000000000..7b99f3afe74 --- /dev/null +++ b/ports/zephyr-cp/common-hal/audiobusio/I2SOut.h @@ -0,0 +1,49 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" +#include "common-hal/microcontroller/Pin.h" +#include "shared-module/audiocore/__init__.h" + +#include +#include +#include + +#if CIRCUITPY_AUDIOBUSIO_I2SOUT + +typedef struct { + mp_obj_base_t base; + const struct device *i2s_dev; + const mcu_pin_obj_t *bit_clock; + const mcu_pin_obj_t *word_select; + const mcu_pin_obj_t *data; + const mcu_pin_obj_t *main_clock; + mp_obj_t sample; + struct k_mem_slab mem_slab; + char *slab_buffer; + struct k_thread thread; + k_thread_stack_t *thread_stack; + k_tid_t thread_id; + size_t block_size; + bool left_justified; + bool playing; + bool paused; + bool loop; + bool stopping; + bool single_buffer; + uint8_t bytes_per_sample; + uint8_t channel_count; +} audiobusio_i2sout_obj_t; + +mp_obj_t common_hal_audiobusio_i2sout_construct_from_device(audiobusio_i2sout_obj_t *self, const struct device *i2s_device); + +void i2sout_reset(void); +void i2sout_gc_collect(void); +void audiobusio_i2sout_collect_ptrs(audiobusio_i2sout_obj_t *self); + +#endif // CIRCUITPY_AUDIOBUSIO_I2SOUT diff --git a/ports/zephyr-cp/common-hal/audiobusio/PDMIn.c b/ports/zephyr-cp/common-hal/audiobusio/PDMIn.c new file mode 100644 index 00000000000..3d3cfef5258 --- /dev/null +++ b/ports/zephyr-cp/common-hal/audiobusio/PDMIn.c @@ -0,0 +1,39 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/audiobusio/PDMIn.h" + +#include "py/runtime.h" + +#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, + uint32_t sample_rate, uint8_t bit_depth, bool mono, uint8_t oversample) { + mp_raise_NotImplementedError(NULL); +} + +bool common_hal_audiobusio_pdmin_deinited(audiobusio_pdmin_obj_t *self) { + return true; +} + +void common_hal_audiobusio_pdmin_deinit(audiobusio_pdmin_obj_t *self) { +} + +uint8_t common_hal_audiobusio_pdmin_get_bit_depth(audiobusio_pdmin_obj_t *self) { + return 0; +} + +uint32_t common_hal_audiobusio_pdmin_get_sample_rate(audiobusio_pdmin_obj_t *self) { + return 0; +} + +uint32_t common_hal_audiobusio_pdmin_record_to_buffer(audiobusio_pdmin_obj_t *self, + uint16_t *output_buffer, uint32_t output_buffer_length) { + return 0; +} + +#endif // CIRCUITPY_AUDIOBUSIO_PDMIN diff --git a/ports/zephyr-cp/common-hal/audiobusio/PDMIn.h b/ports/zephyr-cp/common-hal/audiobusio/PDMIn.h new file mode 100644 index 00000000000..195a436f3cf --- /dev/null +++ b/ports/zephyr-cp/common-hal/audiobusio/PDMIn.h @@ -0,0 +1,18 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" +#include "common-hal/microcontroller/Pin.h" + +#if CIRCUITPY_AUDIOBUSIO_PDMIN + +typedef struct { + mp_obj_base_t base; +} audiobusio_pdmin_obj_t; + +#endif // CIRCUITPY_AUDIOBUSIO_PDMIN diff --git a/ports/zephyr-cp/common-hal/audiobusio/__init__.c b/ports/zephyr-cp/common-hal/audiobusio/__init__.c new file mode 100644 index 00000000000..5d2e802904d --- /dev/null +++ b/ports/zephyr-cp/common-hal/audiobusio/__init__.c @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// No special initialization required for audiobusio diff --git a/ports/zephyr-cp/common-hal/audiobusio/__init__.h b/ports/zephyr-cp/common-hal/audiobusio/__init__.h new file mode 100644 index 00000000000..8ba7882bf94 --- /dev/null +++ b/ports/zephyr-cp/common-hal/audiobusio/__init__.h @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// No common definitions needed for audiobusio diff --git a/ports/zephyr-cp/common-hal/busio/I2C.c b/ports/zephyr-cp/common-hal/busio/I2C.c new file mode 100644 index 00000000000..fa038e0f173 --- /dev/null +++ b/ports/zephyr-cp/common-hal/busio/I2C.c @@ -0,0 +1,213 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/busio/I2C.h" +#include "shared-bindings/microcontroller/Pin.h" + +#include "bindings/zephyr_kernel/__init__.h" +#include "py/mperrno.h" +#include "py/runtime.h" + +#include + +#include +#include +#include + +// Helper function for Zephyr-specific initialization from device tree +mp_obj_t common_hal_busio_i2c_construct_from_device(busio_i2c_obj_t *self, const struct device *i2c_device) { + self->base.type = &busio_i2c_type; + self->i2c_device = i2c_device; + k_mutex_init(&self->mutex); + self->has_lock = false; + self->dynamic = false; + self->sda = NULL; + self->scl = NULL; + return MP_OBJ_FROM_PTR(self); +} + +static void raise_no_i2c_peripheral(int err) { + if (err == -ENODEV) { + mp_raise_ValueError(MP_ERROR_TEXT("All I2C peripherals are in use")); + } + if (err == -EBUSY) { + mp_raise_ValueError(MP_ERROR_TEXT("Internal resource(s) in use")); + } + if (err == -EINVAL) { + raise_ValueError_invalid_pins(); + } + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("Use device tree to define %q devices"), MP_QSTR_I2C); +} + +// Standard busio construct: pick a free peripheral instance and route it to +// the requested pins at runtime (supported on nRF SoCs). +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_ms) { + const struct device *dev = NULL; + int ret = iobroker_i2c_allocate(sda->package_pin, scl->package_pin, &dev); + if (ret < 0) { + raise_no_i2c_peripheral(ret); + } + + common_hal_busio_i2c_construct_from_device(self, dev); + self->dynamic = true; + self->sda = sda; + self->scl = scl; + + // Initialize the deferred device now that it is routed to the requested + // pins. Fixed devicetree instances are already initialized (-EALREADY). + int init_ret = device_init(dev); + if (init_ret < 0 && init_ret != -EALREADY) { + // The failed init may have routed pins and left the device in a + // partial state; deinit gives up the claim and resets the pins. + common_hal_busio_i2c_deinit(self); + raise_zephyr_error(init_ret); + } + + // Apply the requested bus frequency. Zephyr nRF drivers support 100k, + // 400k and (on TWIM) 1M. + uint8_t speed; + if (frequency <= 100000) { + speed = I2C_SPEED_STANDARD; + } else if (frequency <= 400000) { + speed = I2C_SPEED_FAST; + } else { + speed = I2C_SPEED_FAST_PLUS; + } + int config_ret = i2c_configure(self->i2c_device, I2C_SPEED_SET(speed)); + if (config_ret < 0) { + common_hal_busio_i2c_deinit(self); + raise_zephyr_error(config_ret); + } +} + +bool common_hal_busio_i2c_deinited(busio_i2c_obj_t *self) { + return self->i2c_device == NULL; +} + +void common_hal_busio_i2c_deinit(busio_i2c_obj_t *self) { + if (common_hal_busio_i2c_deinited(self)) { + return; + } + if (self->dynamic) { + // The release de-inits the device, which applies its low-power + // pinctrl state and leaves the routed pins disconnected. + (void)iobroker_release(self->i2c_device); + self->sda = NULL; + self->scl = NULL; + self->i2c_device = NULL; + } +} + +void common_hal_busio_i2c_mark_deinit(busio_i2c_obj_t *self) { + if (self->dynamic) { + self->i2c_device = NULL; + } +} + +bool common_hal_busio_i2c_probe(busio_i2c_obj_t *self, uint8_t addr) { + if (common_hal_busio_i2c_deinited(self)) { + return false; + } + + // Try a zero-length write to probe for device + uint8_t dummy; + int ret = i2c_write(self->i2c_device, &dummy, 0, addr); + return ret == 0; +} + +bool common_hal_busio_i2c_try_lock(busio_i2c_obj_t *self) { + if (common_hal_busio_i2c_deinited(self)) { + return false; + } + + self->has_lock = k_mutex_lock(&self->mutex, K_NO_WAIT) == 0; + return self->has_lock; +} + +bool common_hal_busio_i2c_has_lock(busio_i2c_obj_t *self) { + return self->has_lock; +} + +void common_hal_busio_i2c_unlock(busio_i2c_obj_t *self) { + self->has_lock = false; + k_mutex_unlock(&self->mutex); +} + +mp_negative_errno_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, + const uint8_t *data, size_t len) { + + if (common_hal_busio_i2c_deinited(self)) { + return -MP_EIO; + } + + int ret = i2c_write(self->i2c_device, data, len, addr); + if (ret != 0) { + // Map Zephyr error codes to errno + if (ret == -ENOTSUP) { + return -MP_EOPNOTSUPP; + } else if (ret == -EIO || ret == -ENXIO) { + return -MP_EIO; + } else if (ret == -EBUSY) { + return -MP_EBUSY; + } + return -MP_EIO; + } + + return 0; +} + +mp_negative_errno_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t addr, + uint8_t *data, size_t len) { + + if (common_hal_busio_i2c_deinited(self)) { + return -MP_EIO; + } + + if (len == 0) { + return 0; + } + + int ret = i2c_read(self->i2c_device, data, len, addr); + if (ret != 0) { + // Map Zephyr error codes to errno + if (ret == -ENOTSUP) { + return -MP_EOPNOTSUPP; + } else if (ret == -EIO || ret == -ENXIO) { + return -MP_EIO; + } else if (ret == -EBUSY) { + return -MP_EBUSY; + } + return -MP_EIO; + } + + return 0; +} + +mp_negative_errno_t common_hal_busio_i2c_write_read(busio_i2c_obj_t *self, uint16_t addr, + uint8_t *out_data, size_t out_len, uint8_t *in_data, size_t in_len) { + + if (common_hal_busio_i2c_deinited(self)) { + return -MP_EIO; + } + + // Use i2c_write_read for combined transaction with repeated start + int ret = i2c_write_read(self->i2c_device, addr, out_data, out_len, in_data, in_len); + if (ret != 0) { + // Map Zephyr error codes to errno + if (ret == -ENOTSUP) { + return -MP_EOPNOTSUPP; + } else if (ret == -EIO || ret == -ENXIO) { + return -MP_EIO; + } else if (ret == -EBUSY) { + return -MP_EBUSY; + } + return -MP_EIO; + } + + return 0; +} diff --git a/ports/zephyr-cp/common-hal/busio/I2C.h b/ports/zephyr-cp/common-hal/busio/I2C.h new file mode 100644 index 00000000000..607a0422d9c --- /dev/null +++ b/ports/zephyr-cp/common-hal/busio/I2C.h @@ -0,0 +1,28 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +#include "common-hal/microcontroller/Pin.h" +#include + +typedef struct { + mp_obj_base_t base; + const struct device *i2c_device; + const mcu_pin_obj_t *sda; + const mcu_pin_obj_t *scl; + struct k_mutex mutex; + bool has_lock; + // True when the underlying Zephyr device was dynamically routed to the + // pins below at construction time. Such objects deinitialize the device + // and release their pins. + bool dynamic; +} busio_i2c_obj_t; + +// Helper function to construct from Zephyr device tree device +mp_obj_t common_hal_busio_i2c_construct_from_device(busio_i2c_obj_t *self, const struct device *i2c_device); diff --git a/ports/zephyr-cp/common-hal/busio/SPI.c b/ports/zephyr-cp/common-hal/busio/SPI.c new file mode 100644 index 00000000000..5c9977d6528 --- /dev/null +++ b/ports/zephyr-cp/common-hal/busio/SPI.c @@ -0,0 +1,14 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/busio/SPI.h" + +mp_obj_t common_hal_busio_spi_construct_from_device(busio_spi_obj_t *self, const struct device *spi_device) { + self->base.type = &busio_spi_type; + common_hal_async_spi_spi_construct_from_device(&self->async_spi, spi_device); + self->sent = NULL; + return MP_OBJ_FROM_PTR(self); +} diff --git a/ports/zephyr-cp/common-hal/busio/SPI.h b/ports/zephyr-cp/common-hal/busio/SPI.h new file mode 100644 index 00000000000..3d171915dd2 --- /dev/null +++ b/ports/zephyr-cp/common-hal/busio/SPI.h @@ -0,0 +1,13 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// busio.SPI is built on common-hal/async_spi. +#include "shared-module/busio/SPI.h" + +// A fixed devicetree device, for the generated board.SPI(). +mp_obj_t common_hal_busio_spi_construct_from_device(busio_spi_obj_t *self, const struct device *spi_device); diff --git a/ports/zephyr-cp/common-hal/busio/UART.c b/ports/zephyr-cp/common-hal/busio/UART.c new file mode 100644 index 00000000000..01e7433be56 --- /dev/null +++ b/ports/zephyr-cp/common-hal/busio/UART.c @@ -0,0 +1,330 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/microcontroller/__init__.h" +#include "shared-bindings/busio/UART.h" +#include "shared-bindings/microcontroller/Pin.h" + +#include "shared/runtime/interrupt_char.h" +#include "py/mpconfig.h" +#include "py/gc.h" +#include "py/mphal.h" +#include "py/mperrno.h" +#include "py/runtime.h" +#include "py/stream.h" + +#include "bindings/zephyr_kernel/__init__.h" +#include "supervisor/port.h" + +#include +#include + +#include +#include +#include +LOG_MODULE_REGISTER(busio_uart); + +// Turn RX back on after serial_cb() paused it for a full msgq. +static void resume_rx(busio_uart_obj_t *self) { + if (self->rx_paused) { + self->rx_paused = false; + uart_irq_rx_enable(self->uart_device); + } +} + +/* + * Feed pending TX bytes to the driver, then move received characters into + * the message queue. + */ +static void serial_cb(const struct device *dev, void *user_data) { + busio_uart_obj_t *self = (busio_uart_obj_t *)user_data; + + uint8_t c; + + uart_irq_update(dev); + + if (self->tx_len > 0 && uart_irq_tx_ready(dev)) { + int sent = uart_fifo_fill(dev, self->tx_data, self->tx_len); + if (sent > 0) { + self->tx_data += sent; + self->tx_len -= sent; + } + if (self->tx_len == 0) { + uart_irq_tx_disable(dev); + k_sem_give(&self->tx_done); + } + } + + if (!uart_irq_rx_ready(dev)) { + return; + } + + /* read until FIFO empty, or until msgq full if flow_control */ + while (true) { + if (self->flow_control && k_msgq_num_free_get(&self->msgq) == 0) { + // Leave the remaining bytes in the driver instead of dropping + // them. USB CDC then stops accepting packets, so the host + // waits. read() calls resume_rx() after taking bytes out of + // the msgq. + self->rx_paused = true; + uart_irq_rx_disable(dev); + // read() may have freed msgq space just before rx_paused was + // set. Then read() saw rx_paused false and did not call + // resume_rx(), so check for space again. + if (k_msgq_num_free_get(&self->msgq) == 0) { + break; + } + resume_rx(self); + } + if (uart_fifo_read(dev, &c, 1) != 1) { + break; + } + if (self->sigint_enabled && mp_interrupt_char == c) { + common_hal_busio_uart_clear_rx_buffer(self); + mp_sched_keyboard_interrupt(); + port_wake_main_task_from_isr(); + } else if (k_msgq_put(&self->msgq, &c, K_NO_WAIT) == 0) { + // Wake the main task so it can service the new RX data + // instead of sleeping out its full timeout. + port_wake_main_task_from_isr(); + } + } +} + +// Helper function for Zephyr-specific initialization from device tree +mp_obj_t common_hal_busio_uart_construct_from_device(busio_uart_obj_t *self, const struct device *uart_device, uint16_t receiver_buffer_size, byte *receiver_buffer, bool sigint_enabled) { + self->base.type = &busio_uart_type; + self->uart_device = uart_device; + self->dynamic = false; + self->receiver_buffer = NULL; + self->tx = NULL; + self->rx = NULL; + self->rts = NULL; + self->cts = NULL; + int ret = uart_irq_callback_user_data_set(uart_device, serial_cb, self); + + if (ret < 0) { + LOG_ERR("Failed to set UART IRQ callback: %d", ret); + } + + k_msgq_init(&self->msgq, receiver_buffer, 1, receiver_buffer_size); + + self->timeout = K_FOREVER; + self->write_timeout = K_FOREVER; + self->tx_len = 0; + k_sem_init(&self->tx_done, 0, 1); + self->rx_paused = false; + self->flow_control = false; + self->sigint_enabled = sigint_enabled; + uart_irq_rx_enable(uart_device); + + return MP_OBJ_FROM_PTR(self); +} + +// Standard busio construct: pick a free peripheral instance and route it to +// the requested pins at runtime (supported on nRF SoCs). +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) { + if (rs485_dir != NULL) { + mp_raise_NotImplementedError(MP_ERROR_TEXT("RS485")); + } + // nRF UARTE only supports 8 data bits. + mp_arg_validate_int(bits, 8, MP_QSTR_bits); + + bool allocated_buffer = false; + if (receiver_buffer == NULL) { + receiver_buffer = m_malloc(receiver_buffer_size); + allocated_buffer = true; + } + + const struct device *dev = NULL; + int ret = iobroker_uart_allocate(tx != NULL ? tx->package_pin : IOBROKER_NO_PIN, + rx != NULL ? rx->package_pin : IOBROKER_NO_PIN, + rts != NULL ? rts->package_pin : IOBROKER_NO_PIN, + cts != NULL ? cts->package_pin : IOBROKER_NO_PIN, &dev); + if (ret < 0) { + if (ret == -ENODEV) { + mp_raise_ValueError(MP_ERROR_TEXT("All UART peripherals are in use")); + } + if (ret == -EBUSY) { + mp_raise_ValueError(MP_ERROR_TEXT("Internal resource(s) in use")); + } + if (ret == -EINVAL) { + raise_ValueError_invalid_pins(); + } + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("Use device tree to define %q devices"), MP_QSTR_UART); + } + + common_hal_busio_uart_construct_from_device(self, dev, receiver_buffer_size, receiver_buffer, sigint_enabled); + self->dynamic = true; + self->receiver_buffer = allocated_buffer ? receiver_buffer : NULL; + self->tx = tx; + self->rx = rx; + self->rts = rts; + self->cts = cts; + + // Initialize the deferred device now that it is routed to the requested + // pins. Fixed devicetree instances are already initialized (-EALREADY). + int init_ret = device_init(dev); + if (init_ret < 0 && init_ret != -EALREADY) { + // The failed init may have routed pins and left the device in a + // partial state; deinit gives up the claim and resets the pins. + common_hal_busio_uart_deinit(self); + raise_zephyr_error(init_ret); + } + + // Apply line configuration. + struct uart_config config = { + .baudrate = baudrate, + .data_bits = UART_CFG_DATA_BITS_8, + .parity = (parity == BUSIO_UART_PARITY_NONE) ? UART_CFG_PARITY_NONE : + ((parity == BUSIO_UART_PARITY_EVEN) ? UART_CFG_PARITY_EVEN : UART_CFG_PARITY_ODD), + .stop_bits = (stop == 1) ? UART_CFG_STOP_BITS_1 : UART_CFG_STOP_BITS_2, + .flow_ctrl = (rts != NULL && cts != NULL) ? UART_CFG_FLOW_CTRL_RTS_CTS : UART_CFG_FLOW_CTRL_NONE, + }; + int config_ret = uart_configure(self->uart_device, &config); + if (config_ret < 0) { + LOG_ERR("uart_configure failed: %d (baudrate=%u stop=%u flow=%u)", + config_ret, baudrate, stop, (rts != NULL && cts != NULL)); + common_hal_busio_uart_deinit(self); + raise_zephyr_error(config_ret); + } + + self->timeout = K_USEC((uint64_t)(timeout * 1000000)); +} + +bool common_hal_busio_uart_deinited(busio_uart_obj_t *self) { + return self->uart_device == NULL; +} + +void common_hal_busio_uart_deinit(busio_uart_obj_t *self) { + if (common_hal_busio_uart_deinited(self)) { + return; + } + if (self->dynamic) { + // The device may not be fully initialized: construct de-inits this + // object when device_init() fails partway through. Zephyr then + // reports it not ready (init_res != 0), so only poke the driver + // when it is really up and running. The iobroker claim and any + // routed pins are still given up below. + if (device_is_ready(self->uart_device)) { + uart_irq_rx_disable(self->uart_device); + uart_irq_callback_user_data_set(self->uart_device, NULL, NULL); + } + // The release de-inits the device, which applies its low-power + // pinctrl state and leaves the routed pins disconnected. + (void)iobroker_release(self->uart_device); + self->tx = NULL; + self->rx = NULL; + self->rts = NULL; + self->cts = NULL; + if (self->receiver_buffer != NULL) { + m_free(self->receiver_buffer); + self->receiver_buffer = NULL; + } + self->uart_device = NULL; + } +} + +// Read characters. +size_t common_hal_busio_uart_read(busio_uart_obj_t *self, uint8_t *data, size_t len, int *errcode) { + size_t count = 0; + while (count < len && k_msgq_get(&self->msgq, data + count, self->timeout) == 0) { + count++; + } + if (count > 0) { + resume_rx(self); + } + + return count; +} + +// Write characters. serial_cb() feeds the driver from the TX interrupt, so +// this thread only waits and can stop on Ctrl-C. +size_t common_hal_busio_uart_write(busio_uart_obj_t *self, const uint8_t *data, size_t len, int *errcode) { + if (len == 0) { + return 0; + } + k_sem_reset(&self->tx_done); + self->tx_data = data; + self->tx_len = len; + uart_irq_tx_enable(self->uart_device); + while (k_sem_take(&self->tx_done, K_MSEC(10)) != 0) { + RUN_BACKGROUND_TASKS; + if (mp_hal_is_interrupted()) { + break; + } + } + uart_irq_tx_disable(self->uart_device); + + unsigned int key = irq_lock(); + size_t not_sent = self->tx_len; + self->tx_len = 0; + irq_unlock(key); + + return len - not_sent; +} + +void zephyr_uart_write_blocking(busio_uart_obj_t *self, const uint8_t *data, size_t len) { + for (size_t i = 0; i < len; i++) { + uart_poll_out(self->uart_device, data[i]); + } +} + +uint32_t common_hal_busio_uart_get_baudrate(busio_uart_obj_t *self) { + struct uart_config config; + uart_config_get(self->uart_device, &config); + return config.baudrate; +} + +void common_hal_busio_uart_set_baudrate(busio_uart_obj_t *self, uint32_t baudrate) { + struct uart_config config; + uart_config_get(self->uart_device, &config); + config.baudrate = baudrate; + uart_configure(self->uart_device, &config); +} + +// K_FOREVER reads as -1, which usb_cdc reports as None. +static mp_float_t timeout_to_seconds(k_timeout_t timeout) { + if (K_TIMEOUT_EQ(timeout, K_FOREVER)) { + return -1; + } + return (mp_float_t)k_ticks_to_us_floor64(timeout.ticks) / MICROPY_FLOAT_CONST(1000000.0); +} + +mp_float_t common_hal_busio_uart_get_timeout(busio_uart_obj_t *self) { + return timeout_to_seconds(self->timeout); +} + +void common_hal_busio_uart_set_timeout(busio_uart_obj_t *self, mp_float_t timeout) { + self->timeout = timeout < 0 ? K_FOREVER : K_USEC((uint64_t)(timeout * 1000000)); +} + +mp_float_t common_hal_busio_uart_get_write_timeout(busio_uart_obj_t *self) { + return timeout_to_seconds(self->write_timeout); +} + +void common_hal_busio_uart_set_write_timeout(busio_uart_obj_t *self, mp_float_t write_timeout) { + self->write_timeout = write_timeout < 0 ? K_FOREVER : K_USEC((uint64_t)(write_timeout * 1000000)); +} + +uint32_t common_hal_busio_uart_rx_characters_available(busio_uart_obj_t *self) { + return k_msgq_num_used_get(&self->msgq); +} + +void common_hal_busio_uart_clear_rx_buffer(busio_uart_obj_t *self) { + k_msgq_purge(&self->msgq); + resume_rx(self); +} + +bool common_hal_busio_uart_ready_to_tx(busio_uart_obj_t *self) { + return true; +} diff --git a/ports/zephyr-cp/common-hal/busio/UART.h b/ports/zephyr-cp/common-hal/busio/UART.h new file mode 100644 index 00000000000..c9a1e11fec4 --- /dev/null +++ b/ports/zephyr-cp/common-hal/busio/UART.h @@ -0,0 +1,62 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +#include "common-hal/microcontroller/Pin.h" + +#include + +typedef struct { + mp_obj_base_t base; + + const struct device *uart_device; + struct k_msgq msgq; + + k_timeout_t timeout; + k_timeout_t write_timeout; + // Bytes not yet handed to the driver by serial_cb(), and a semaphore it + // gives when they are all sent. + const uint8_t *tx_data; + size_t tx_len; + struct k_sem tx_done; + byte *receiver_buffer; + const mcu_pin_obj_t *tx; + const mcu_pin_obj_t *rx; + const mcu_pin_obj_t *rts; + const mcu_pin_obj_t *cts; + + bool rx_paused; // set by irq if no space in rbuf + // Set when the sender waits for unread data (USB CDC), so RX can + // pause on a full msgq instead of dropping bytes. + bool flow_control; + // Raise KeyboardInterrupt on mp_interrupt_char. + bool sigint_enabled; + + // True when the underlying Zephyr device was dynamically routed to the + // pins above at construction time. Such objects own their receiver + // buffer and deinitialize the device and release their pins. + bool dynamic; +} busio_uart_obj_t; + +// Helper function for Zephyr-specific initialization from device tree +mp_obj_t common_hal_busio_uart_construct_from_device(busio_uart_obj_t *self, const struct device *uart_device, uint16_t receiver_buffer_size, byte *receiver_buffer, bool sigint_enabled); + +// Internal helper for clearing buffer +void common_hal_busio_uart_clear_rx_buffer(busio_uart_obj_t *self); + +// Write all of data with uart_poll_out(). Used by the console and usb_cdc +// instead of common_hal_busio_uart_write(), which stops early on a pending +// Ctrl-C or reload and would cut console output short. With the host port +// closed, the CDC ACM driver drops this output instead of blocking, as on +// TinyUSB ports. +void zephyr_uart_write_blocking(busio_uart_obj_t *self, const uint8_t *data, size_t len); + +// Zephyr-port-specific write-timeout accessors, used by usb_cdc/Serial.c. +mp_float_t common_hal_busio_uart_get_write_timeout(busio_uart_obj_t *self); +void common_hal_busio_uart_set_write_timeout(busio_uart_obj_t *self, mp_float_t write_timeout); diff --git a/ports/zephyr-cp/common-hal/busio/__init__.c b/ports/zephyr-cp/common-hal/busio/__init__.c new file mode 100644 index 00000000000..135a53f4907 --- /dev/null +++ b/ports/zephyr-cp/common-hal/busio/__init__.c @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +// No busio module functions. diff --git a/ports/zephyr-cp/common-hal/digitalio/DigitalInOut.c b/ports/zephyr-cp/common-hal/digitalio/DigitalInOut.c index 0da16a9b720..74b677fce03 100644 --- a/ports/zephyr-cp/common-hal/digitalio/DigitalInOut.c +++ b/ports/zephyr-cp/common-hal/digitalio/DigitalInOut.c @@ -6,27 +6,36 @@ #include "shared-bindings/digitalio/DigitalInOut.h" +#include + #include #include -void common_hal_digitalio_digitalinout_never_reset( - digitalio_digitalinout_obj_t *self) { -} - digitalinout_result_t common_hal_digitalio_digitalinout_construct( digitalio_digitalinout_obj_t *self, const mcu_pin_obj_t *pin) { - claim_pin(pin); + // Claim the pin in the iobroker module so that bus allocations refuse + // it while this object holds it. The call also resolves the GPIO + // controller device and pin number from the pin's global number; they are + // kept in the object for every later pad operation. + int ret = iobroker_gpio_allocate(pin->package_pin, &self->port, &self->number); + if (ret < 0) { + return DIGITALINOUT_PIN_BUSY; + } + self->pin = pin; - if (!device_is_ready(pin->port)) { + if (!device_is_ready(self->port)) { printk("Port device not ready\n"); + common_hal_digitalio_digitalinout_deinit(self); return DIGITALINOUT_PIN_BUSY; } - if (gpio_pin_configure(pin->port, pin->number, GPIO_INPUT) != 0) { + if (gpio_pin_configure(self->port, self->number, GPIO_INPUT) != 0) { + common_hal_digitalio_digitalinout_deinit(self); return DIGITALINOUT_PIN_BUSY; } self->direction = DIRECTION_INPUT; + self->fake_open_drain = false; return DIGITALINOUT_OK; } @@ -40,7 +49,7 @@ void common_hal_digitalio_digitalinout_deinit(digitalio_digitalinout_obj_t *self return; } - reset_pin(self->pin); + (void)iobroker_gpio_release(self->port, self->number); self->pin = NULL; } @@ -56,6 +65,8 @@ digitalinout_result_t common_hal_digitalio_digitalinout_switch_to_output( digitalio_drive_mode_t drive_mode) { self->direction = DIRECTION_OUTPUT; + // set_drive_mode() starts the output at self->value. + self->value = value; common_hal_digitalio_digitalinout_set_drive_mode(self, drive_mode); common_hal_digitalio_digitalinout_set_value(self, value); return DIGITALINOUT_OK; @@ -68,7 +79,12 @@ digitalio_direction_t common_hal_digitalio_digitalinout_get_direction( void common_hal_digitalio_digitalinout_set_value( digitalio_digitalinout_obj_t *self, bool value) { - int res = gpio_pin_set(self->pin->port, self->pin->number, value); + int res; + if (self->fake_open_drain) { + res = gpio_pin_configure(self->port, self->number, value ? GPIO_INPUT : GPIO_OUTPUT_LOW); + } else { + res = gpio_pin_set(self->port, self->number, value); + } if (res != 0) { printk("Failed to set value %d\n", res); } @@ -81,23 +97,31 @@ bool common_hal_digitalio_digitalinout_get_value( if (self->direction == DIRECTION_OUTPUT) { return self->value; } - return gpio_pin_get(self->pin->port, self->pin->number) == 1; + return gpio_pin_get(self->port, self->number) == 1; } digitalinout_result_t common_hal_digitalio_digitalinout_set_drive_mode( digitalio_digitalinout_obj_t *self, digitalio_drive_mode_t drive_mode) { - // Also INPUT so we can read the value back. - gpio_flags_t flags = GPIO_OUTPUT; + // Start the output at the cached value. Plain GPIO_OUTPUT would keep the + // pin's old output level, which is low after emulated open drain has + // driven it low, even if value has since been set to True. + gpio_flags_t flags = self->value ? GPIO_OUTPUT_HIGH : GPIO_OUTPUT_LOW; if (drive_mode == DRIVE_MODE_OPEN_DRAIN) { flags |= GPIO_OPEN_DRAIN; } - int res = gpio_pin_configure(self->pin->port, self->pin->number, flags); + int res = gpio_pin_configure(self->port, self->number, flags); + if (res == -ENOTSUP && drive_mode == DRIVE_MODE_OPEN_DRAIN) { + self->fake_open_drain = true; + self->drive_mode = drive_mode; + common_hal_digitalio_digitalinout_set_value(self, self->value); + return DIGITALINOUT_OK; + } if (res != 0) { - // TODO: Fake open drain. printk("Failed to set drive mode %d\n", res); return DIGITALINOUT_INVALID_DRIVE_MODE; } + self->fake_open_drain = false; self->drive_mode = drive_mode; return DIGITALINOUT_OK; } @@ -115,7 +139,7 @@ digitalinout_result_t common_hal_digitalio_digitalinout_set_pull( } else if (pull == PULL_DOWN) { pull_flags = GPIO_PULL_DOWN; } - if (gpio_pin_configure(self->pin->port, self->pin->number, GPIO_INPUT | pull_flags) != 0) { + if (gpio_pin_configure(self->port, self->number, GPIO_INPUT | pull_flags) != 0) { return DIGITALINOUT_INVALID_PULL; } self->pull = pull; diff --git a/ports/zephyr-cp/common-hal/digitalio/DigitalInOut.h b/ports/zephyr-cp/common-hal/digitalio/DigitalInOut.h index 9e0c3265268..d2888d1f68f 100644 --- a/ports/zephyr-cp/common-hal/digitalio/DigitalInOut.h +++ b/ports/zephyr-cp/common-hal/digitalio/DigitalInOut.h @@ -14,8 +14,16 @@ typedef struct { mp_obj_base_t base; const mcu_pin_obj_t *pin; + // GPIO controller device and pin number within it, resolved from the + // pin's global number by the gpio allocate call at construct time. + const struct device *port; + gpio_pin_t number; digitalio_direction_t direction; bool value; digitalio_drive_mode_t drive_mode; + // Set when this pin's GPIO driver rejects GPIO_OPEN_DRAIN with -ENOTSUP + // (such as gpio_emul): open drain is then emulated by driving low and + // releasing high as an input. + bool fake_open_drain; digitalio_pull_t pull; } digitalio_digitalinout_obj_t; diff --git a/ports/zephyr-cp/common-hal/hostnetwork/HostNetwork.c b/ports/zephyr-cp/common-hal/hostnetwork/HostNetwork.c new file mode 100644 index 00000000000..494b21cb02d --- /dev/null +++ b/ports/zephyr-cp/common-hal/hostnetwork/HostNetwork.c @@ -0,0 +1,15 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "bindings/hostnetwork/HostNetwork.h" + +hostnetwork_hostnetwork_obj_t common_hal_hostnetwork_obj = { + .base = { &hostnetwork_hostnetwork_type }, +}; + +void common_hal_hostnetwork_hostnetwork_construct(hostnetwork_hostnetwork_obj_t *self) { + (void)self; +} diff --git a/ports/zephyr-cp/common-hal/hostnetwork/HostNetwork.h b/ports/zephyr-cp/common-hal/hostnetwork/HostNetwork.h new file mode 100644 index 00000000000..a6731546bde --- /dev/null +++ b/ports/zephyr-cp/common-hal/hostnetwork/HostNetwork.h @@ -0,0 +1,11 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "bindings/hostnetwork/HostNetwork.h" + +extern hostnetwork_hostnetwork_obj_t common_hal_hostnetwork_obj; diff --git a/ports/zephyr-cp/common-hal/microcontroller/Pin.c b/ports/zephyr-cp/common-hal/microcontroller/Pin.c index 66882b6b5f0..d37214a1707 100644 --- a/ports/zephyr-cp/common-hal/microcontroller/Pin.c +++ b/ports/zephyr-cp/common-hal/microcontroller/Pin.c @@ -5,69 +5,14 @@ // SPDX-License-Identifier: MIT #include "shared-bindings/microcontroller/Pin.h" -#include "shared-bindings/digitalio/DigitalInOut.h" #include "py/mphal.h" -// Bit mask of claimed pins on each of up to two ports. nrf52832 has one port; nrf52840 has two. -// static uint32_t claimed_pins[GPIO_COUNT]; -// static uint32_t never_reset_pins[GPIO_COUNT]; +#include -void reset_all_pins(void) { - // for (size_t i = 0; i < GPIO_COUNT; i++) { - // claimed_pins[i] = never_reset_pins[i]; - // } - - // for (uint32_t pin = 0; pin < NUMBER_OF_PINS; ++pin) { - // if ((never_reset_pins[nrf_pin_port(pin)] & (1 << nrf_relative_pin_number(pin))) != 0) { - // continue; - // } - // nrf_gpio_cfg_default(pin); - // } - - // // After configuring SWD because it may be shared. - // reset_speaker_enable_pin(); -} - -// Mark pin as free and return it to a quiescent state. -void reset_pin(const mcu_pin_obj_t *pin) { - - // Clear claimed bit. - // claimed_pins[nrf_pin_port(pin_number)] &= ~(1 << nrf_relative_pin_number(pin_number)); - // never_reset_pins[nrf_pin_port(pin_number)] &= ~(1 << nrf_relative_pin_number(pin_number)); -} - - -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) { - never_reset_pin_number(pin->number); -} - -void common_hal_reset_pin(const mcu_pin_obj_t *pin) { +bool common_hal_mcu_pin_is_free(const mcu_pin_obj_t *pin) { if (pin == NULL) { - return; + return true; } - reset_pin(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); -} - - -bool pin_number_is_free(uint8_t pin_number) { - return false; // !(claimed_pins[nrf_pin_port(pin_number)] & (1 << nrf_relative_pin_number(pin_number))); -} - -bool common_hal_mcu_pin_is_free(const mcu_pin_obj_t *pin) { - return true; - -} - -void common_hal_mcu_pin_claim(const mcu_pin_obj_t *pin) { - claim_pin(pin); + return !iobroker_pin_in_use(pin->package_pin); } diff --git a/ports/zephyr-cp/common-hal/microcontroller/Pin.h b/ports/zephyr-cp/common-hal/microcontroller/Pin.h index eb0304dc72f..c3ec3869d1c 100644 --- a/ports/zephyr-cp/common-hal/microcontroller/Pin.h +++ b/ports/zephyr-cp/common-hal/microcontroller/Pin.h @@ -7,17 +7,17 @@ #pragma once #include "py/mphal.h" +#include "py/obj.h" +#include #include typedef struct { mp_obj_base_t base; - const struct device *port; - gpio_pin_t number; + // Package pin of the SoC package the pad is bonded to, resolved at + // build time from the board's package pin map. IOBROKER_NO_PIN when the + // pad has no entry in the map (or the SoC has no package pin map). + package_pin_t package_pin; } mcu_pin_obj_t; #include "autogen-pins.h" - -void reset_all_pins(void); -void reset_pin(const mcu_pin_obj_t *pin); -void claim_pin(const mcu_pin_obj_t *pin); diff --git a/ports/zephyr-cp/common-hal/microcontroller/Processor.c b/ports/zephyr-cp/common-hal/microcontroller/Processor.c index ddc8b97056d..8266a1ade5e 100644 --- a/ports/zephyr-cp/common-hal/microcontroller/Processor.c +++ b/ports/zephyr-cp/common-hal/microcontroller/Processor.c @@ -12,16 +12,53 @@ #include "shared-bindings/microcontroller/ResetReason.h" #include +#include #include +#if defined(CONFIG_WIFI) +#include + +// Fallback for SoCs with no hwinfo driver, where hwinfo_get_device_id() returns +// -ENOSYS and cpu.uid would otherwise be all zeros. A WiFi link address is +// per-device, so it is a better answer than nothing, and at least one vendor +// (Silicon Labs, for the siwx91x) defines that part's unique ID as exactly this: +// the WiFi MAC zero-extended to eight bytes. +// +// This is not a burned-in serial. A MAC can generally be reprogrammed by vendor +// tooling, so cpu.uid must not be relied on as tamper proof where it comes from +// here. Boards whose SoC has a real hwinfo driver never reach this path. +static ssize_t uid_from_wifi_mac(uint8_t raw_id[]) { + if (COMMON_HAL_MCU_PROCESSOR_UID_LENGTH < 8) { + return -1; + } + struct net_if *iface = net_if_get_first_wifi(); + struct net_linkaddr *addr = (iface != NULL) ? net_if_get_link_addr(iface) : NULL; + if (addr == NULL || addr->len != 6) { + return -1; + } + raw_id[0] = 0; + raw_id[1] = 0; + memcpy(&raw_id[2], addr->addr, 6); + return 8; +} +#endif + float common_hal_mcu_processor_get_temperature(void) { return 0.0; } -extern uint32_t SystemCoreClock; +#define CPU_NODE DT_PATH(cpus, cpu_0) + uint32_t common_hal_mcu_processor_get_frequency(void) { - return SystemCoreClock; + #if DT_NODE_HAS_PROP(CPU_NODE, clock_frequency) + return DT_PROP(CPU_NODE, clock_frequency); + #elif DT_NODE_HAS_PROP(CPU_NODE, clocks) + // No clock-frequency on the cpu node (nRF54L), so use the clock that drives it. + return DT_PROP_OR(DT_CLOCKS_CTLR(CPU_NODE), clock_frequency, CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC); + #else + return CONFIG_SYS_CLOCK_HW_CYCLES_PER_SEC; + #endif } float common_hal_mcu_processor_get_voltage(void) { @@ -30,6 +67,14 @@ float common_hal_mcu_processor_get_voltage(void) { void common_hal_mcu_processor_get_uid(uint8_t raw_id[]) { ssize_t len = hwinfo_get_device_id(raw_id, COMMON_HAL_MCU_PROCESSOR_UID_LENGTH); + #if defined(CONFIG_WIFI) + if (len < 0) { + ssize_t mac_len = uid_from_wifi_mac(raw_id); + if (mac_len > 0) { + len = mac_len; + } + } + #endif if (len < 0) { printk("UID retrieval failed: %d\n", len); len = 0; @@ -40,7 +85,34 @@ void common_hal_mcu_processor_get_uid(uint8_t raw_id[]) { } } +// Set in zephyr_main.c main() at boot: the hwinfo reset cause that was read +// (and cleared there) for this run. nRF's RESETREAS bits are sticky, so a +// live hwinfo_get_reset_cause() would mask newer causes (e.g. a watchdog +// reset would keep reporting an old pin reset) with stale bits. +extern uint32_t cp_reset_cause; + mcu_reset_reason_t common_hal_mcu_processor_get_reset_reason(void) { - mcu_reset_reason_t r = RESET_REASON_UNKNOWN; - return r; + // cp_reset_cause holds only the bits set for THIS boot since zephyr_main + // cleared the raw register at startup. Check in priority order. + uint32_t cause = cp_reset_cause; + if (cause == 0) { + return MCU_RESET_REASON_UNKNOWN; + } + if (cause & RESET_POR) { + return MCU_RESET_REASON_POWER_ON; + } else if (cause & RESET_WATCHDOG) { + return MCU_RESET_REASON_WATCHDOG; + } else if (cause & RESET_CPU_LOCKUP) { + // Treat LOCKUP like a WATCHDOG + return MCU_RESET_REASON_WATCHDOG; + } else if (cause & RESET_BROWNOUT) { + return MCU_RESET_REASON_BROWNOUT; + } else if (cause & RESET_SOFTWARE) { + return MCU_RESET_REASON_SOFTWARE; + } else if (cause & RESET_PIN) { + return MCU_RESET_REASON_RESET_PIN; + } else if (cause & RESET_DEBUG || cause & RESET_LOW_POWER_WAKE) { + return MCU_RESET_REASON_UNKNOWN; + } + return MCU_RESET_REASON_UNKNOWN; } diff --git a/ports/zephyr-cp/common-hal/microcontroller/Processor.h b/ports/zephyr-cp/common-hal/microcontroller/Processor.h index f47f582a1ce..890bca2a2e8 100644 --- a/ports/zephyr-cp/common-hal/microcontroller/Processor.h +++ b/ports/zephyr-cp/common-hal/microcontroller/Processor.h @@ -6,7 +6,7 @@ #pragma once -#if CONFIG_HWINFO_NRF +#if CONFIG_HWINFO_NRF || CONFIG_HWINFO_RPI_PICO #define COMMON_HAL_MCU_PROCESSOR_UID_LENGTH 8 #else // Extra long and the remainder will be left empty. Will print out the actual length. diff --git a/ports/zephyr-cp/common-hal/microcontroller/__init__.c b/ports/zephyr-cp/common-hal/microcontroller/__init__.c index 6ebf5f4c368..e9a2600cc26 100644 --- a/ports/zephyr-cp/common-hal/microcontroller/__init__.c +++ b/ports/zephyr-cp/common-hal/microcontroller/__init__.c @@ -11,12 +11,13 @@ #include "common-hal/microcontroller/Pin.h" #include "common-hal/microcontroller/Processor.h" -// #include "shared-bindings/nvm/ByteArray.h" +#include "shared-bindings/nvm/ByteArray.h" #include "shared-bindings/microcontroller/__init__.h" #include "shared-bindings/microcontroller/Pin.h" #include "shared-bindings/microcontroller/Processor.h" #include "supervisor/filesystem.h" +#include "adaboot/update_mode.h" #include "supervisor/port.h" #include "supervisor/shared/safe_mode.h" @@ -25,6 +26,7 @@ // This routine should work even when interrupts are disabled. Used by OneWire // for precise timing. void common_hal_mcu_delay_us(uint32_t delay) { + k_busy_wait(delay); } static uint32_t _irq_key; @@ -65,16 +67,15 @@ void common_hal_mcu_enable_interrupts() { } void common_hal_mcu_on_next_reset(mcu_runmode_t runmode) { - enum { DFU_MAGIC_UF2_RESET = 0x57 }; - uint8_t new_value = 0; if (runmode == RUNMODE_BOOTLOADER || runmode == RUNMODE_UF2) { - new_value = DFU_MAGIC_UF2_RESET; + // Both modes ask for the bootloader's update mode, the state a + // double-tap of the reset button produces. + adaboot_request_update_mode(true); + } else { + // Any other mode boots normally: drop a request left over from an + // earlier on_next_reset() call. + adaboot_clear_update_request(); } - // int err_code = sd_power_gpregret_set(0, DFU_MAGIC_UF2_RESET); - // if (err_code != NRF_SUCCESS) { - // // Set it without the soft device if the SD failed. (It may be off.) - // nrf_power_gpregret_set(NRF_POWER, new_value); - // } if (runmode == RUNMODE_SAFE_MODE) { safe_mode_on_next_reset(SAFE_MODE_PROGRAMMATIC); } @@ -93,14 +94,12 @@ const mcu_processor_obj_t common_hal_mcu_processor_obj = { }, }; -#if CIRCUITPY_NVM && CIRCUITPY_INTERNAL_NVM_SIZE > 0 +#if CIRCUITPY_NVM // The singleton nvm.ByteArray object. const nvm_bytearray_obj_t common_hal_mcu_nvm_obj = { .base = { .type = &nvm_bytearray_type, }, - .start_address = (uint8_t *)CIRCUITPY_INTERNAL_NVM_START_ADDR, - .len = CIRCUITPY_INTERNAL_NVM_SIZE, }; #endif @@ -112,5 +111,6 @@ watchdog_watchdogtimer_obj_t common_hal_mcu_watchdogtimer_obj = { }, .timeout = 0.0f, .mode = WATCHDOGMODE_NONE, + .channel_id = -1, }; #endif diff --git a/ports/zephyr-cp/common-hal/mii/Ethernet.c b/ports/zephyr-cp/common-hal/mii/Ethernet.c new file mode 100644 index 00000000000..c5923ca3d45 --- /dev/null +++ b/ports/zephyr-cp/common-hal/mii/Ethernet.c @@ -0,0 +1,454 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/mii/__init__.h" +#include "shared-bindings/mii/Ethernet.h" + +#include + +#include "bindings/zephyr_kernel/__init__.h" + +#include "supervisor/port.h" +#include "supervisor/shared/network.h" +#include "supervisor/workflow.h" +#include "shared/runtime/interrupt_char.h" + +#if CIRCUITPY_STATUS_BAR +#include "supervisor/shared/status_bar.h" +#endif + +#include "py/runtime.h" +#include "shared-bindings/ipaddress/IPv4Address.h" +#include "shared-module/ipaddress/__init__.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "common-hal/mii/__init__.h" +#include "common-hal/mii/Ethernet.h" + +#define MAC_ADDRESS_LENGTH 6 + +static struct net_mgmt_event_callback eth_carrier_cb; +static struct net_mgmt_event_callback eth_ipv4_cb; + +bool common_hal_mii_ethernet_get_enabled(mii_ethernet_obj_t *self) { + return self->started; +} + +void common_hal_mii_ethernet_set_enabled(mii_ethernet_obj_t *self, bool enabled) { + if (self->netif == NULL) { + return; + } + if (self->started && !enabled) { + net_dhcpv4_stop(self->netif); + CHECK_ZEPHYR_RESULT(net_if_down(self->netif)); + self->started = false; + } else if (!self->started && enabled) { + int up_res = net_if_up(self->netif); + // -EALREADY means the interface is already up. That's not an error. + if (up_res < 0 && up_res != -EALREADY) { + raise_zephyr_error(up_res); + } + self->started = true; + net_dhcpv4_start(self->netif); + // An explicit enable implies imminent use; wait out the lease so the + // very first getaddrinfo()/connect() does not race it. + mii_wait_for_lease(); + } +} + +bool common_hal_mii_ethernet_get_connected(mii_ethernet_obj_t *self) { + if (self->netif == NULL) { + return false; + } + return net_if_is_carrier_ok(self->netif) && net_if_is_up(self->netif); +} + +mp_obj_t common_hal_mii_ethernet_get_hostname(mii_ethernet_obj_t *self) { + const char *hostname = net_hostname_get(); + return mp_obj_new_str(hostname, strlen(hostname)); +} + +void common_hal_mii_ethernet_set_hostname(mii_ethernet_obj_t *self, const char *hostname) { + CHECK_ZEPHYR_RESULT(net_hostname_set((char *)hostname, strlen(hostname))); +} + +mp_obj_t common_hal_mii_ethernet_get_mac_address(mii_ethernet_obj_t *self) { + if (self->netif == NULL) { + return mp_obj_new_bytes((const uint8_t *)"\0\0\0\0\0\0", MAC_ADDRESS_LENGTH); + } + struct net_linkaddr *mac = net_if_get_link_addr(self->netif); + return mp_obj_new_bytes(mac->addr, MAC_ADDRESS_LENGTH); +} + +mp_int_t common_hal_mii_ethernet_get_link_speed(mii_ethernet_obj_t *self) { + if (self->netif == NULL || !net_if_is_carrier_ok(self->netif)) { + return 0; + } + const struct device *phy = net_eth_get_phy(self->netif); + if (phy == NULL) { + return 0; + } + struct phy_link_state state; + if (phy_get_link_state(phy, &state) != 0) { + return 0; + } + switch (state.speed) { + case LINK_HALF_10BASE: + case LINK_FULL_10BASE: + return 10; + case LINK_HALF_100BASE: + case LINK_FULL_100BASE: + return 100; + case LINK_HALF_1000BASE: + case LINK_FULL_1000BASE: + return 1000; + default: + return 0; + } +} + +bool common_hal_mii_ethernet_get_full_duplex(mii_ethernet_obj_t *self) { + if (self->netif == NULL || !net_if_is_carrier_ok(self->netif)) { + return false; + } + const struct device *phy = net_eth_get_phy(self->netif); + if (phy == NULL) { + return false; + } + struct phy_link_state state; + if (phy_get_link_state(phy, &state) != 0) { + return false; + } + switch (state.speed) { + case LINK_FULL_10BASE: + case LINK_FULL_100BASE: + case LINK_FULL_1000BASE: + return true; + default: + return false; + } +} + +void common_hal_mii_ethernet_start_dhcp_client(mii_ethernet_obj_t *self, bool ipv4, bool ipv6) { + if (self->netif == NULL) { + return; + } + if (ipv4) { + net_dhcpv4_start(self->netif); + } else { + net_dhcpv4_stop(self->netif); + } + if (ipv6) { + // TODO: DHCPv6 support + } +} + +void common_hal_mii_ethernet_stop_dhcp_client(mii_ethernet_obj_t *self) { + if (self->netif == NULL) { + return; + } + net_dhcpv4_stop(self->netif); +} + +mp_obj_t common_hal_mii_ethernet_get_ipv4_gateway(mii_ethernet_obj_t *self) { + if (self->netif == NULL || !net_if_is_up(self->netif)) { + return mp_const_none; + } + struct net_if_config *config = net_if_get_config(self->netif); + if (config == NULL || config->ip.ipv4 == NULL) { + return mp_const_none; + } + return common_hal_ipaddress_new_ipv4address(config->ip.ipv4->gw.s_addr); +} + +mp_obj_t common_hal_mii_ethernet_get_ipv4_subnet(mii_ethernet_obj_t *self) { + if (self->netif == NULL || !net_if_is_up(self->netif)) { + return mp_const_none; + } + struct net_if_config *config = net_if_get_config(self->netif); + if (config == NULL || config->ip.ipv4 == NULL) { + return mp_const_none; + } + // Return netmask of first active address + for (int i = 0; i < NET_IF_MAX_IPV4_ADDR; i++) { + if (config->ip.ipv4->unicast[i].ipv4.addr_state == NET_ADDR_PREFERRED) { + return common_hal_ipaddress_new_ipv4address(config->ip.ipv4->unicast[i].netmask.s_addr); + } + } + return mp_const_none; +} + +mp_obj_t common_hal_mii_mii_get_ipv4_address(mii_ethernet_obj_t *self) { + if (self->netif == NULL || !net_if_is_up(self->netif)) { + return mp_const_none; + } + struct net_if_config *config = net_if_get_config(self->netif); + if (config == NULL || config->ip.ipv4 == NULL) { + return mp_const_none; + } + // Return the first preferred unicast address + for (int i = 0; i < NET_IF_MAX_IPV4_ADDR; i++) { + struct net_if_addr *addr = &config->ip.ipv4->unicast[i].ipv4; + if (addr->addr_state == NET_ADDR_PREFERRED) { + return common_hal_ipaddress_new_ipv4address(addr->address.in_addr.s_addr); + } + } + return mp_const_none; +} + +mp_obj_t common_hal_mii_ethernet_get_ipv4_dns(mii_ethernet_obj_t *self) { + (void)self; + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_ipv4_dns); +} + +void common_hal_mii_ethernet_set_ipv4_dns(mii_ethernet_obj_t *self, mp_obj_t ipv4_dns_addr) { + (void)self; + (void)ipv4_dns_addr; + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_ipv4_dns); +} + +mp_obj_t common_hal_mii_ethernet_get_addresses(mii_ethernet_obj_t *self) { + if (self->netif == NULL || !net_if_is_up(self->netif)) { + return mp_const_empty_tuple; + } + struct net_if_config *config = net_if_get_config(self->netif); + if (config == NULL || config->ip.ipv4 == NULL) { + return mp_const_empty_tuple; + } + + // Count valid addresses + int count = 0; + for (int i = 0; i < NET_IF_MAX_IPV4_ADDR; i++) { + if (config->ip.ipv4->unicast[i].ipv4.addr_state == NET_ADDR_PREFERRED) { + count++; + } + } + if (count == 0) { + return mp_const_empty_tuple; + } + + mp_obj_tuple_t *result = MP_OBJ_TO_PTR(mp_obj_new_tuple(count, NULL)); + int idx = 0; + for (int i = 0; i < NET_IF_MAX_IPV4_ADDR && idx < count; i++) { + struct net_if_addr *addr = &config->ip.ipv4->unicast[i].ipv4; + if (addr->addr_state == NET_ADDR_PREFERRED) { + char buf[NET_IPV4_ADDR_LEN]; + net_addr_ntop(AF_INET, &addr->address.in_addr, buf, sizeof(buf)); + result->items[idx++] = mp_obj_new_str(buf, strlen(buf)); + } + } + return MP_OBJ_FROM_PTR(result); +} + +mp_obj_t common_hal_mii_ethernet_get_dns(mii_ethernet_obj_t *self) { + (void)self; + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_dns); +} + +void common_hal_mii_ethernet_set_dns(mii_ethernet_obj_t *self, mp_obj_t dns_addr) { + (void)self; + (void)dns_addr; + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_dns); +} + +void common_hal_mii_ethernet_set_ipv4_address(mii_ethernet_obj_t *self, mp_obj_t ipv4, mp_obj_t netmask, mp_obj_t gateway, mp_obj_t ipv4_dns) { + if (self->netif == NULL) { + return; + } + + // Stop DHCP first + common_hal_mii_ethernet_stop_dhcp_client(self); + + // Get packed IPv4 bytes from ipaddress objects + mp_obj_t packed; + size_t len; + const char *bytes; + + // Set the address + struct in_addr addr; + packed = common_hal_ipaddress_ipv4address_get_packed(ipv4); + bytes = mp_obj_str_get_data(packed, &len); + memcpy(&addr, bytes, sizeof(addr)); + struct net_if_addr *if_addr = net_if_ipv4_addr_add(self->netif, &addr, NET_ADDR_MANUAL, 0); + if (if_addr == NULL) { + // No free slots; go through the port's standard errno path rather + // than adding a new translatable string. + raise_zephyr_error(-ENOMEM); + } + + // Set the netmask + struct in_addr mask; + packed = common_hal_ipaddress_ipv4address_get_packed(netmask); + bytes = mp_obj_str_get_data(packed, &len); + memcpy(&mask, bytes, sizeof(mask)); + net_if_ipv4_set_netmask_by_addr(self->netif, &addr, &mask); + + // Set the gateway + struct in_addr gw; + packed = common_hal_ipaddress_ipv4address_get_packed(gateway); + bytes = mp_obj_str_get_data(packed, &len); + memcpy(&gw, bytes, sizeof(gw)); + net_if_ipv4_set_gw(self->netif, &gw); + + if (ipv4_dns != MP_OBJ_NULL) { + common_hal_mii_ethernet_set_ipv4_dns(self, ipv4_dns); + } +} + +mp_int_t common_hal_mii_ethernet_ping(mii_ethernet_obj_t *self, mp_obj_t ip_address, mp_float_t timeout) { + (void)self; + (void)ip_address; + (void)timeout; + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_ping); +} + +static void _eth_event_handler(struct net_mgmt_event_callback *cb, uint64_t mgmt_event, struct net_if *iface) { + (void)cb; + (void)iface; + + switch (mgmt_event) { + case NET_EVENT_ETHERNET_CARRIER_ON: + case NET_EVENT_ETHERNET_CARRIER_OFF: + case NET_EVENT_IPV4_ADDR_ADD: + #if CIRCUITPY_STATUS_BAR + supervisor_status_bar_request_update(false); + #endif + port_wake_main_task(); + break; + } +} + +void common_hal_mii_ethernet_construct(mii_ethernet_obj_t *self, + mii_rmii_obj_t *rmii) { + self->base.type = &mii_ethernet_type; + self->started = false; + self->netif = NULL; + if (rmii != NULL) { + mp_raise_NotImplementedError( + MP_ERROR_TEXT("cannot construct ethernet interfaces; use board.ETHERNET")); + } + + // Find the first ethernet interface + self->netif = net_if_get_first_by_type(&NET_L2_GET_NAME(ETHERNET)); + if (self->netif == NULL) { + return; + } + + net_mgmt_init_event_callback(ð_carrier_cb, _eth_event_handler, + NET_EVENT_ETHERNET_CARRIER_ON | + NET_EVENT_ETHERNET_CARRIER_OFF); + net_mgmt_init_event_callback(ð_ipv4_cb, _eth_event_handler, + NET_EVENT_IPV4_ADDR_ADD); + + net_mgmt_add_event_callback(ð_carrier_cb); + net_mgmt_add_event_callback(ð_ipv4_cb); + + #if defined(CONFIG_NET_HOSTNAME) + // Set the default hostname, capped at NET_HOSTNAME_MAX_LEN characters. + char cpy_default_hostname[NET_HOSTNAME_MAX_LEN]; + struct net_linkaddr *mac = net_if_get_link_addr(self->netif); + if (mac->len >= MAC_ADDRESS_LENGTH) { + size_t len = network_format_default_hostname(cpy_default_hostname, sizeof(cpy_default_hostname), mac->addr); + net_hostname_set(cpy_default_hostname, len); + } + #endif + + // Enabled by default, start DHCP + int up_res = net_if_up(self->netif); + // -EALREADY means the interface is already up. That's not an error. + if (up_res < 0 && up_res != -EALREADY) { + raise_zephyr_error(up_res); + } + self->started = true; + net_dhcpv4_start(self->netif); +} + +// Cross-translation-unit helpers for supervisor/shared/web_workflow.c; they +// all operate on the first registered instance (the devicetree one). + +// Raw uint32_t IPv4 address of the interface, in network byte order, or 0 +// when the interface has none. +uint32_t mii_get_ipv4_address(void) { + mii_ethernet_obj_t *self = (mii_ethernet_obj_t *)mii_get_default_instance(); + if (self == NULL || self->netif == NULL || !net_if_is_up(self->netif)) { + return 0; + } + struct in_addr *addr = net_if_ipv4_get_global_addr(self->netif, NET_ADDR_PREFERRED); + if (addr == NULL) { + return 0; + } + return addr->s_addr; +} + +// Raw hostname of the network interface as set via net_hostname_set (and sent +// as DHCP option 12). Never allocates. The returned pointer points into +// storage owned by Zephyr and stays valid until set via +// common_hal_mii_ethernet_set_hostname, so use it promptly rather than +// holding onto it. +const char *mii_get_hostname_raw(void) { + mii_ethernet_obj_t *self = (mii_ethernet_obj_t *)mii_get_default_instance(); + if (self == NULL || self->netif == NULL) { + return ""; + } + return net_hostname_get(); +} + +void mii_get_default_hostname(char *buf, size_t buf_size) { + if (buf_size == 0) { + return; + } + buf[0] = '\0'; + #if defined(CONFIG_NET_HOSTNAME) + if (buf_size < 18) { + return; + } + // The Ethernet constructor uses the first Ethernet network interface. + // Zephyr creates that interface at boot, so it already exists. + struct net_if *netif = net_if_get_first_by_type(&NET_L2_GET_NAME(ETHERNET)); + if (netif == NULL) { + return; + } + struct net_linkaddr *mac = net_if_get_link_addr(netif); + if (mac->len < MAC_ADDRESS_LENGTH) { + return; + } + // Use the same length limit as the constructor. + network_format_default_hostname(buf, MIN(buf_size, NET_HOSTNAME_MAX_LEN), mac->addr); + #endif +} + +// Blocks until the DHCP lease is bound. DHCPv4 parses its options (which adds +// the DNS server to the resolver) and only then binds the address, so a +// preferred global address implies getaddrinfo() has everything it needs. +// Starting a query before that fails with DNS_EAI_SYSTEM ("getaddrinfo +// failure: -11") because the resolver still has no server to send to. +// +// Returns immediately when the interface cannot ever get a lease: it is down, +// disabled or has no carrier. Used by the supervisor so the web workflow's +// listening socket can be created during this boot instead of being deferred +// until the next VM start. +void mii_wait_for_lease(void) { + mii_ethernet_obj_t *self = (mii_ethernet_obj_t *)mii_get_default_instance(); + if (self == NULL || self->netif == NULL || !self->started || !net_if_is_carrier_ok(self->netif)) { + return; + } + int64_t deadline = k_uptime_get() + 20000; + while (k_uptime_get() < deadline && mii_get_ipv4_address() == 0) { + if (mp_hal_is_interrupted()) { + break; + } + RUN_BACKGROUND_TASKS; + k_msleep(50); + } +} diff --git a/ports/zephyr-cp/common-hal/mii/Ethernet.h b/ports/zephyr-cp/common-hal/mii/Ethernet.h new file mode 100644 index 00000000000..ff08e5c09a7 --- /dev/null +++ b/ports/zephyr-cp/common-hal/mii/Ethernet.h @@ -0,0 +1,27 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +#include "common-hal/microcontroller/Pin.h" +#include "common-hal/mii/RMII.h" + +#include + +typedef struct { + mp_obj_base_t base; + struct net_if *netif; + bool started; +} mii_ethernet_obj_t; + +// Brings up the devicetree ethernet interface, enables DHCP and starts it. +// Constructing with an RMII bus is not supported (the wiring comes from the +// devicetree) and raises NotImplementedError; the board's generated code +// passes NULL. +void common_hal_mii_ethernet_construct(mii_ethernet_obj_t *self, + mii_rmii_obj_t *rmii); diff --git a/ports/zephyr-cp/common-hal/mii/MDIO.c b/ports/zephyr-cp/common-hal/mii/MDIO.c new file mode 100644 index 00000000000..c8687ee8efc --- /dev/null +++ b/ports/zephyr-cp/common-hal/mii/MDIO.c @@ -0,0 +1,17 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "common-hal/mii/MDIO.h" +#include "shared-bindings/mii/MDIO.h" + +#include "py/runtime.h" + +void common_hal_mii_mdio_construct(mii_mdio_obj_t *self, + const mcu_pin_obj_t *mdc, const mcu_pin_obj_t *mdio) { + (void)mdc; + (void)mdio; + mp_raise_NotImplementedError(NULL); +} diff --git a/ports/zephyr-cp/common-hal/mii/MDIO.h b/ports/zephyr-cp/common-hal/mii/MDIO.h new file mode 100644 index 00000000000..699084ea988 --- /dev/null +++ b/ports/zephyr-cp/common-hal/mii/MDIO.h @@ -0,0 +1,20 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +#include "common-hal/microcontroller/Pin.h" + +typedef struct { + mp_obj_base_t base; +} mii_mdio_obj_t; + +// Zephyr pulls its MDIO wiring from the devicetree; constructing the bus is +// not supported and raises NotImplementedError. +void common_hal_mii_mdio_construct(mii_mdio_obj_t *self, + const mcu_pin_obj_t *mdc, const mcu_pin_obj_t *mdio); diff --git a/ports/zephyr-cp/common-hal/mii/RMII.c b/ports/zephyr-cp/common-hal/mii/RMII.c new file mode 100644 index 00000000000..950182ddfff --- /dev/null +++ b/ports/zephyr-cp/common-hal/mii/RMII.c @@ -0,0 +1,29 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "common-hal/mii/RMII.h" +#include "shared-bindings/mii/RMII.h" + +#include "py/runtime.h" + +void common_hal_mii_rmii_construct(mii_rmii_obj_t *self, + mii_mdio_obj_t *mdio, uint32_t device, + const mcu_pin_obj_t *rxd0, const mcu_pin_obj_t *rxd1, const mcu_pin_obj_t *rx_dv, + const mcu_pin_obj_t *txd0, const mcu_pin_obj_t *txd1, const mcu_pin_obj_t *tx_en, + const mcu_pin_obj_t *refclk, const mcu_pin_obj_t *reset) { + (void)self; + (void)mdio; + (void)device; + (void)rxd0; + (void)rxd1; + (void)rx_dv; + (void)txd0; + (void)txd1; + (void)tx_en; + (void)refclk; + (void)reset; + mp_raise_NotImplementedError(NULL); +} diff --git a/ports/zephyr-cp/common-hal/mii/RMII.h b/ports/zephyr-cp/common-hal/mii/RMII.h new file mode 100644 index 00000000000..b64e93d61d1 --- /dev/null +++ b/ports/zephyr-cp/common-hal/mii/RMII.h @@ -0,0 +1,24 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +#include "common-hal/mii/MDIO.h" +#include "common-hal/microcontroller/Pin.h" + +typedef struct { + mp_obj_base_t base; +} mii_rmii_obj_t; + +// Zephyr pulls its RMII wiring from the devicetree; constructing the bus is +// not supported and raises NotImplementedError. +void common_hal_mii_rmii_construct(mii_rmii_obj_t *self, + mii_mdio_obj_t *mdio, uint32_t device, + const mcu_pin_obj_t *rxd0, const mcu_pin_obj_t *rxd1, const mcu_pin_obj_t *rx_dv, + const mcu_pin_obj_t *txd0, const mcu_pin_obj_t *txd1, const mcu_pin_obj_t *tx_en, + const mcu_pin_obj_t *refclk, const mcu_pin_obj_t *reset); diff --git a/ports/zephyr-cp/common-hal/mii/__init__.c b/ports/zephyr-cp/common-hal/mii/__init__.c new file mode 100644 index 00000000000..ec3ce6b595b --- /dev/null +++ b/ports/zephyr-cp/common-hal/mii/__init__.c @@ -0,0 +1,28 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "common-hal/mii/__init__.h" +#include "shared-bindings/mii/__init__.h" + +#include + +void mii_user_reset(void) { + // Nothing to do on user reset for now. +} + +static mii_ethernet_obj_t *_default_instance; + +// Called by board code once the board's ethernet instance is constructed. +void mii_set_default_instance(mii_ethernet_obj_t *self) { + _default_instance = self; +} + +mp_obj_t mii_get_default_instance(void) { + if (_default_instance == NULL) { + return NULL; + } + return MP_OBJ_FROM_PTR(_default_instance); +} diff --git a/ports/zephyr-cp/common-hal/mii/__init__.h b/ports/zephyr-cp/common-hal/mii/__init__.h new file mode 100644 index 00000000000..e46ce23c0a6 --- /dev/null +++ b/ports/zephyr-cp/common-hal/mii/__init__.h @@ -0,0 +1,18 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "common-hal/mii/Ethernet.h" + +void mii_user_reset(void); + +// Cross-translation-unit API for supervisor/shared/web_workflow.c; the +// declarations (and web_workflow's contract) live in +// shared-bindings/mii/__init__.h. The board calls set_default_instance +// once its own instance is constructed. +void mii_set_default_instance(mii_ethernet_obj_t *self); +mp_obj_t mii_get_default_instance(void); diff --git a/ports/zephyr-cp/common-hal/neopixel_write/__init__.c b/ports/zephyr-cp/common-hal/neopixel_write/__init__.c new file mode 100644 index 00000000000..867e0483f16 --- /dev/null +++ b/ports/zephyr-cp/common-hal/neopixel_write/__init__.c @@ -0,0 +1,122 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Dan Halbert for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// neopixel_write on top of the neopixel Zephyr module +// (internal-modules/neopixel): this file waits for any previous write to +// finish, provides the pattern buffer the module needs, and maps its errors. +// The waveform itself is produced by the module's per-SoC implementation. + +#include + +#include +#include + +#include +#include + +#include "py/mpstate.h" +#include "py/runtime.h" + +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/neopixel_write/__init__.h" +#include "common-hal/neopixel_write/__init__.h" +#include "supervisor/port.h" + +LOG_MODULE_REGISTER(neopixel_write); + +// Earliest raw tick at which the next write may start. The strip latches the +// previous data while its input stays low for the reset period (a few tens +// of microseconds); a raw tick is about a millisecond, so 4 ticks is ample. +static uint64_t next_start_raw_ticks = 0; + +// Pattern buffer for the module: writes of up to STACK_PIXELS RGB pixels +// (or 3/4 as many RGBW pixels: the buffer is sized in pixel bytes) use a +// stack array (uint32_t for the 4-byte alignment the module requires). As +// in ports/nordic: the status NeoPixel is written between VM instantiations, +// when the heap is not available, so it must never allocate, and 24 pixels +// also covers Circuit Playground's 10 and the common 12- and 16-pixel rings. +// Longer strips use a heap buffer that is kept between writes and grown when +// a longer strip appears. Only user code with such a strip reaches the heap +// path, with the VM running, so the raising allocator is fine there. +#define STACK_PIXELS 24 +#define STACK_PATTERN_BUFFER_SIZE NEOPIXEL_PATTERN_BUFFER_SIZE(3 * STACK_PIXELS) + +static size_t pattern_buffer_heap_size = 0; + +void neopixel_write_reset(void) { + MP_STATE_VM(neopixel_write_pattern_buffer_heap) = NULL; + pattern_buffer_heap_size = 0; +} + +// Claim the pin as a GPIO again after neopixel_send() and put it back in the +// configuration the DigitalInOut recorded (normally an output driven low). +static void reclaim_pin(const digitalio_digitalinout_obj_t *digitalinout) { + const struct device *port; + gpio_pin_t number; + if (iobroker_gpio_allocate(digitalinout->pin->package_pin, &port, &number) < 0) { + LOG_WRN("could not reclaim the pin after a write"); + return; + } + gpio_flags_t flags; + if (digitalinout->direction == DIRECTION_OUTPUT) { + flags = digitalinout->value ? GPIO_OUTPUT_HIGH : GPIO_OUTPUT_LOW; + if (digitalinout->drive_mode == DRIVE_MODE_OPEN_DRAIN) { + flags |= GPIO_OPEN_DRAIN; + } + } else { + flags = GPIO_INPUT; + if (digitalinout->pull == PULL_UP) { + flags |= GPIO_PULL_UP; + } else if (digitalinout->pull == PULL_DOWN) { + flags |= GPIO_PULL_DOWN; + } + } + (void)gpio_pin_configure(port, number, flags); +} + +void common_hal_neopixel_write(const digitalio_digitalinout_obj_t *digitalinout, + uint8_t *pixels, uint32_t num_bytes) { + size_t pattern_buffer_size = NEOPIXEL_PATTERN_BUFFER_SIZE(num_bytes); + uint32_t stack_pattern_buffer[(STACK_PATTERN_BUFFER_SIZE + 3) / sizeof(uint32_t)]; + void *pattern_buffer; + if (pattern_buffer_size <= sizeof(stack_pattern_buffer)) { + pattern_buffer = stack_pattern_buffer; + pattern_buffer_size = sizeof(stack_pattern_buffer); + } else { + if (pattern_buffer_heap_size < pattern_buffer_size) { + MP_STATE_VM(neopixel_write_pattern_buffer_heap) = + m_realloc(MP_STATE_VM(neopixel_write_pattern_buffer_heap), pattern_buffer_size); + pattern_buffer_heap_size = pattern_buffer_size; + } + pattern_buffer = MP_STATE_VM(neopixel_write_pattern_buffer_heap); + pattern_buffer_size = pattern_buffer_heap_size; + } + + while (port_get_raw_ticks(NULL) < next_start_raw_ticks) { + } + + // neopixel_send() allocates the transmit hardware and the pin itself, so + // the DigitalInOut's GPIO claim is released for the frame. + (void)iobroker_gpio_release(digitalinout->port, digitalinout->number); + int ret = neopixel_send(digitalinout->pin->package_pin, pixels, num_bytes, + pattern_buffer, pattern_buffer_size); + reclaim_pin(digitalinout); + next_start_raw_ticks = port_get_raw_ticks(NULL) + 4; + + if (ret == -EINVAL) { + // No transmit hardware can drive this pad, neither a PWM instance nor + // bit-bang (such as nRF54L P0): a wrong pin choice, so say so. + raise_ValueError_invalid_pin(); + } + if (ret < 0) { + // A runtime condition (a frame preempted on every resend, a transfer + // error) the status LED must survive, since it calls this from the + // supervisor: skip the write. + LOG_WRN("write skipped (%d)", ret); + } +} + +MP_REGISTER_ROOT_POINTER(uint8_t * neopixel_write_pattern_buffer_heap); diff --git a/ports/zephyr-cp/common-hal/neopixel_write/__init__.h b/ports/zephyr-cp/common-hal/neopixel_write/__init__.h new file mode 100644 index 00000000000..3fbe51c80ed --- /dev/null +++ b/ports/zephyr-cp/common-hal/neopixel_write/__init__.h @@ -0,0 +1,10 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Dan Halbert for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Called from reset_port() to drop any buffer held across writes. +void neopixel_write_reset(void); diff --git a/ports/zephyr-cp/common-hal/nvm/ByteArray.c b/ports/zephyr-cp/common-hal/nvm/ByteArray.c new file mode 100644 index 00000000000..a1b76a2806c --- /dev/null +++ b/ports/zephyr-cp/common-hal/nvm/ByteArray.c @@ -0,0 +1,107 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "py/runtime.h" +#include "common-hal/nvm/ByteArray.h" +#include "shared-bindings/nvm/ByteArray.h" + +#include + +#include +#include + +#define NVM_PARTITION nvm_partition + +#if FIXED_PARTITION_EXISTS(NVM_PARTITION) + +static const struct flash_area *nvm_area = NULL; +static size_t nvm_erase_size = 0; + +static bool ensure_nvm_open(void) { + if (nvm_area != NULL) { + return true; + } + int rc = flash_area_open(FIXED_PARTITION_ID(NVM_PARTITION), &nvm_area); + if (rc != 0) { + return false; + } + + const struct device *dev = flash_area_get_device(nvm_area); + struct flash_pages_info info; + flash_get_page_info_by_offs(dev, nvm_area->fa_off, &info); + nvm_erase_size = info.size; + + return true; +} + +uint32_t common_hal_nvm_bytearray_get_length(const nvm_bytearray_obj_t *self) { + // The nvm partition size comes from the devicetree, so it's only known at + // runtime. The singleton object's len field is never initialized; look it + // up from the opened flash area instead. + (void)self; + if (!ensure_nvm_open()) { + return 0; + } + return nvm_area->fa_size; +} + +bool common_hal_nvm_bytearray_set_bytes(const nvm_bytearray_obj_t *self, + uint32_t start_index, uint8_t *values, uint32_t len) { + if (!ensure_nvm_open()) { + return false; + } + + uint32_t address = start_index; + while (len > 0) { + uint32_t page_offset = address % nvm_erase_size; + uint32_t page_start = address - page_offset; + uint32_t write_len = MIN(len, nvm_erase_size - page_offset); + + uint8_t *buffer = m_malloc(nvm_erase_size); + if (buffer == NULL) { + return false; + } + + // Read the full erase page. + int rc = flash_area_read(nvm_area, page_start, buffer, nvm_erase_size); + if (rc != 0) { + m_free(buffer); + return false; + } + + // Modify the relevant bytes. + memcpy(buffer + page_offset, values, write_len); + + // Erase the page. + rc = flash_area_erase(nvm_area, page_start, nvm_erase_size); + if (rc != 0) { + m_free(buffer); + return false; + } + + // Write the page back. + rc = flash_area_write(nvm_area, page_start, buffer, nvm_erase_size); + m_free(buffer); + if (rc != 0) { + return false; + } + + address += write_len; + values += write_len; + len -= write_len; + } + return true; +} + +void common_hal_nvm_bytearray_get_bytes(const nvm_bytearray_obj_t *self, + uint32_t start_index, uint32_t len, uint8_t *values) { + if (!ensure_nvm_open()) { + return; + } + flash_area_read(nvm_area, start_index, values, len); +} + +#endif // FIXED_PARTITION_EXISTS(NVM_PARTITION) diff --git a/ports/zephyr-cp/common-hal/nvm/ByteArray.h b/ports/zephyr-cp/common-hal/nvm/ByteArray.h new file mode 100644 index 00000000000..97014de905b --- /dev/null +++ b/ports/zephyr-cp/common-hal/nvm/ByteArray.h @@ -0,0 +1,15 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +typedef struct { + mp_obj_base_t base; + uint8_t *start_address; + uint32_t len; +} nvm_bytearray_obj_t; diff --git a/ports/zephyr-cp/common-hal/pwmio/PWMOut.c b/ports/zephyr-cp/common-hal/pwmio/PWMOut.c new file mode 100644 index 00000000000..7ed25b31fd7 --- /dev/null +++ b/ports/zephyr-cp/common-hal/pwmio/PWMOut.c @@ -0,0 +1,172 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Dan Halbert for Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +// pwmio on Zephyr's PWM API. The iobroker module picks the PWM device and +// channel for the pin; channels that share a period (an nRF instance's +// outputs) are grouped there, so nothing here is SoC-specific. The period is +// computed here from the device's clock. Checking that the hardware can +// produce it is left to the driver, which doesn't reliably do so yet (pwm_nrfx +// skips the check at 0 % and 100 % duty). + +#include + +#include +#include +#include + +#include "py/runtime.h" + +#include "shared-bindings/pwmio/PWMOut.h" + +// Shortest period accepted, in clock cycles: a period needs a high and a low +// part. +#define MIN_PERIOD_CYCLES 2U + +// Truncate a frequency to a whole number of clock cycles, so the actual +// frequency is the same or slightly higher. Returns 0, or a negative errno +// when the period would be out of range or the clock is unknown. +static int frequency_to_period(const struct device *dev, uint32_t channel, + uint32_t frequency, uint32_t *period_cycles_out) { + uint64_t cycles_per_sec; + int ret = pwm_get_cycles_per_sec(dev, channel, &cycles_per_sec); + if (ret < 0) { + return ret; + } + uint64_t period = cycles_per_sec / frequency; + if (period < MIN_PERIOD_CYCLES || period > UINT32_MAX) { + return -EINVAL; + } + *period_cycles_out = (uint32_t)period; + return 0; +} + +static uint32_t pulse_cycles(uint32_t period_cycles, uint16_t duty) { + return (uint32_t)(((uint64_t)period_cycles * duty) / 0xffff); +} + +// Program the channel's period and the stored duty cycle. +static int set_period_and_duty(pwmio_pwmout_obj_t *self) { + return pwm_set_cycles(self->dev, self->channel, self->period_cycles, + pulse_cycles(self->period_cycles, self->duty_cycle), 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) { + // Deinited until construction succeeds. + self->dev = NULL; + if (frequency == 0) { + return PWMOUT_INVALID_FREQUENCY; + } + const struct device *dev; + uint32_t channel; + // A variable frequency needs a group of its own, since changing the + // period would change it for every channel in the group. + int ret = iobroker_pwm_channel_allocate(pin->package_pin, frequency, + variable_frequency, &dev, &channel); + switch (ret) { + case 0: + break; + case -ENODEV: + return PWMOUT_INTERNAL_RESOURCES_IN_USE; + case -EINVAL: + case -EBUSY: + case -ENOSYS: + return PWMOUT_INVALID_PIN; + default: + return PWMOUT_INITIALIZATION_ERROR; + } + + // The first channel of a group initializes the device; an existing + // group reports -EALREADY. + ret = device_init(dev); + if (ret < 0 && ret != -EALREADY) { + (void)iobroker_pwm_channel_release(dev, channel); + return PWMOUT_INITIALIZATION_ERROR; + } + uint32_t period_cycles; + if (frequency_to_period(dev, channel, frequency, &period_cycles) < 0) { + (void)iobroker_pwm_channel_release(dev, channel); + return PWMOUT_INVALID_FREQUENCY; + } + + self->pin = pin; + self->dev = dev; + self->channel = channel; + self->period_cycles = period_cycles; + self->duty_cycle = duty; + self->variable_frequency = variable_frequency; + // The driver may reject a period its hardware can't produce. + if (set_period_and_duty(self) < 0) { + (void)iobroker_pwm_channel_release(dev, channel); + self->dev = NULL; + return PWMOUT_INVALID_FREQUENCY; + } + return PWMOUT_OK; +} + +bool common_hal_pwmio_pwmout_deinited(pwmio_pwmout_obj_t *self) { + return self->dev == NULL; +} + +void common_hal_pwmio_pwmout_deinit(pwmio_pwmout_obj_t *self) { + if (common_hal_pwmio_pwmout_deinited(self)) { + return; + } + // Stop the output, then hand the channel back. + (void)pwm_set_cycles(self->dev, self->channel, self->period_cycles, 0, 0); + (void)iobroker_pwm_channel_release(self->dev, self->channel); + self->dev = NULL; + self->pin = NULL; +} + +void common_hal_pwmio_pwmout_set_duty_cycle(pwmio_pwmout_obj_t *self, uint16_t duty) { + self->duty_cycle = duty; + (void)set_period_and_duty(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) { + // shared-bindings raises AttributeError unless variable_frequency=True, + // so the channel's group is exclusive and no other channel shares the + // period. It also rejects 0 Hz, so frequency_to_period() can divide. + uint32_t period_cycles; + if (frequency_to_period(self->dev, self->channel, frequency, &period_cycles) < 0) { + common_hal_pwmio_pwmout_raise_error(PWMOUT_INVALID_FREQUENCY); + } + uint32_t old_period_cycles = self->period_cycles; + self->period_cycles = period_cycles; + if (set_period_and_duty(self) < 0) { + // The driver rejected the period: keep the old one. + self->period_cycles = old_period_cycles; + (void)set_period_and_duty(self); + common_hal_pwmio_pwmout_raise_error(PWMOUT_INVALID_FREQUENCY); + } +} + +uint32_t common_hal_pwmio_pwmout_get_frequency(pwmio_pwmout_obj_t *self) { + // The frequency the stored period produces. The driver may truncate the + // period further to fit its registers (on nRF, to a multiple of the + // prescaler), which Zephyr's PWM API doesn't report, so at low + // frequencies this can be very slightly below the actual output (under + // 0.01 % on nRF). + uint64_t cycles_per_sec; + if (pwm_get_cycles_per_sec(self->dev, self->channel, &cycles_per_sec) < 0) { + return 0; + } + return (uint32_t)((cycles_per_sec + self->period_cycles / 2) / self->period_cycles); +} + +bool common_hal_pwmio_pwmout_get_variable_frequency(pwmio_pwmout_obj_t *self) { + return self->variable_frequency; +} + +const mcu_pin_obj_t *common_hal_pwmio_pwmout_get_pin(pwmio_pwmout_obj_t *self) { + return self->pin; +} diff --git a/ports/zephyr-cp/common-hal/pwmio/PWMOut.h b/ports/zephyr-cp/common-hal/pwmio/PWMOut.h new file mode 100644 index 00000000000..15e44f70669 --- /dev/null +++ b/ports/zephyr-cp/common-hal/pwmio/PWMOut.h @@ -0,0 +1,27 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Dan Halbert for Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "common-hal/microcontroller/Pin.h" + +#include + +#include "py/obj.h" + +typedef struct { + mp_obj_base_t base; + const mcu_pin_obj_t *pin; + // PWM device and channel from iobroker_pwm_channel_allocate(); dev is + // NULL when deinited. + const struct device *dev; + uint32_t channel; + // Period in the device's PWM clock cycles, from the frequency. Every + // pwm_set_cycles() call passes exactly this value. + uint32_t period_cycles; + uint16_t duty_cycle; + bool variable_frequency; +} pwmio_pwmout_obj_t; diff --git a/ports/zephyr-cp/common-hal/pwmio/__init__.c b/ports/zephyr-cp/common-hal/pwmio/__init__.c new file mode 100644 index 00000000000..14e9fd91630 --- /dev/null +++ b/ports/zephyr-cp/common-hal/pwmio/__init__.c @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Dan Halbert for Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +// No pwmio module functions. diff --git a/ports/zephyr-cp/common-hal/rotaryio/IncrementalEncoder.c b/ports/zephyr-cp/common-hal/rotaryio/IncrementalEncoder.c new file mode 100644 index 00000000000..07ac4fa1634 --- /dev/null +++ b/ports/zephyr-cp/common-hal/rotaryio/IncrementalEncoder.c @@ -0,0 +1,126 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#include "common-hal/rotaryio/IncrementalEncoder.h" +#include "shared-bindings/rotaryio/IncrementalEncoder.h" +#include "shared-module/rotaryio/IncrementalEncoder.h" + +#include "bindings/zephyr_kernel/__init__.h" +#include "py/runtime.h" + +#include +#include +#include +#include +#include + +static void incrementalencoder_gpio_callback(const struct device *port, + struct gpio_callback *cb, gpio_port_pins_t pins) { + (void)port; + (void)pins; + rotaryio_incrementalencoder_gpio_callback_t *callback = + CONTAINER_OF(cb, rotaryio_incrementalencoder_gpio_callback_t, callback); + rotaryio_incrementalencoder_obj_t *self = callback->encoder; + if (self == NULL || self->pin_a == NULL) { + return; + } + + int a = gpio_pin_get(self->port_a, self->number_a); + int b = gpio_pin_get(self->port_b, self->number_b); + if (a < 0 || b < 0) { + return; + } + uint8_t new_state = ((uint8_t)a << 1) | (uint8_t)b; + shared_module_softencoder_state_update(self, new_state); +} + +// Runs an iobroker/GPIO call and, on failure, releases any partial setup +// before raising a Python exception with the Zephyr errno. +#define CHECK_RESULT_OR_DEINIT(x) \ + do { \ + int _res = (x); \ + if (_res < 0) { \ + common_hal_rotaryio_incrementalencoder_deinit(self); \ + raise_zephyr_error(_res); \ + } \ + } while (0) + +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) { + // Ensure object starts in its deinit state. + common_hal_rotaryio_incrementalencoder_mark_deinit(self); + + self->pin_a = pin_a; + self->pin_b = pin_b; + self->divisor = 4; + + // Claim both pins in the iobroker module so that bus allocations + // refuse them while this object holds them. The calls also resolve the + // GPIO controller devices and pin numbers from the pins' global numbers; + // they are kept in the object for every later pad operation. + CHECK_RESULT_OR_DEINIT(iobroker_gpio_allocate(pin_a->package_pin, &self->port_a, &self->number_a)); + CHECK_RESULT_OR_DEINIT(iobroker_gpio_allocate(pin_b->package_pin, &self->port_b, &self->number_b)); + + CHECK_RESULT_OR_DEINIT(device_is_ready(self->port_a) && device_is_ready(self->port_b) ? 0 : -ENODEV); + + CHECK_RESULT_OR_DEINIT(gpio_pin_configure(self->port_a, self->number_a, GPIO_INPUT | GPIO_PULL_UP)); + CHECK_RESULT_OR_DEINIT(gpio_pin_configure(self->port_b, self->number_b, GPIO_INPUT | GPIO_PULL_UP)); + + self->callback_a.encoder = self; + gpio_init_callback(&self->callback_a.callback, incrementalencoder_gpio_callback, + BIT(self->number_a)); + CHECK_RESULT_OR_DEINIT(gpio_add_callback(self->port_a, &self->callback_a.callback)); + + self->callback_b.encoder = self; + gpio_init_callback(&self->callback_b.callback, incrementalencoder_gpio_callback, + BIT(self->number_b)); + CHECK_RESULT_OR_DEINIT(gpio_add_callback(self->port_b, &self->callback_b.callback)); + + CHECK_RESULT_OR_DEINIT(gpio_pin_interrupt_configure(self->port_a, self->number_a, GPIO_INT_EDGE_BOTH)); + CHECK_RESULT_OR_DEINIT(gpio_pin_interrupt_configure(self->port_b, self->number_b, GPIO_INT_EDGE_BOTH)); + + int a = gpio_pin_get(self->port_a, self->number_a); + int b = gpio_pin_get(self->port_b, self->number_b); + uint8_t quiescent_state = ((uint8_t)(a > 0) << 1) | (uint8_t)(b > 0); + shared_module_softencoder_state_init(self, quiescent_state); +} + +bool common_hal_rotaryio_incrementalencoder_deinited(rotaryio_incrementalencoder_obj_t *self) { + return self->pin_a == NULL; +} + +void common_hal_rotaryio_incrementalencoder_deinit(rotaryio_incrementalencoder_obj_t *self) { + if (common_hal_rotaryio_incrementalencoder_deinited(self)) { + return; + } + + // Best-effort cleanup. During failed construct(), some of these may not be + // initialized yet. Ignore cleanup errors. The pad operations are only run + // when both claims were taken, so that the devices are valid. + if (self->port_a != NULL && self->port_b != NULL) { + gpio_pin_interrupt_configure(self->port_a, self->number_a, GPIO_INT_DISABLE); + gpio_pin_interrupt_configure(self->port_b, self->number_b, GPIO_INT_DISABLE); + gpio_remove_callback(self->port_a, &self->callback_a.callback); + gpio_remove_callback(self->port_b, &self->callback_b.callback); + } + if (self->port_a != NULL) { + (void)iobroker_gpio_release(self->port_a, self->number_a); + self->port_a = NULL; + } + if (self->port_b != NULL) { + (void)iobroker_gpio_release(self->port_b, self->number_b); + self->port_b = NULL; + } + + common_hal_rotaryio_incrementalencoder_mark_deinit(self); +} + +void common_hal_rotaryio_incrementalencoder_mark_deinit(rotaryio_incrementalencoder_obj_t *self) { + self->pin_a = NULL; + self->pin_b = NULL; + self->port_a = NULL; + self->port_b = NULL; +} diff --git a/ports/zephyr-cp/common-hal/rotaryio/IncrementalEncoder.h b/ports/zephyr-cp/common-hal/rotaryio/IncrementalEncoder.h new file mode 100644 index 00000000000..55ab26c65d4 --- /dev/null +++ b/ports/zephyr-cp/common-hal/rotaryio/IncrementalEncoder.h @@ -0,0 +1,37 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include + +#include "common-hal/microcontroller/Pin.h" +#include "py/obj.h" + +typedef struct rotaryio_incrementalencoder_obj rotaryio_incrementalencoder_obj_t; + +typedef struct { + struct gpio_callback callback; + rotaryio_incrementalencoder_obj_t *encoder; +} rotaryio_incrementalencoder_gpio_callback_t; + +struct rotaryio_incrementalencoder_obj { + mp_obj_base_t base; + const mcu_pin_obj_t *pin_a; + const mcu_pin_obj_t *pin_b; + // GPIO controller devices and pin numbers within them, resolved from the + // pins' global numbers by the gpio allocate calls at construct time. + const struct device *port_a; + gpio_pin_t number_a; + const struct device *port_b; + gpio_pin_t number_b; + rotaryio_incrementalencoder_gpio_callback_t callback_a; + rotaryio_incrementalencoder_gpio_callback_t callback_b; + uint8_t state; // + int8_t sub_count; // count intermediate transitions between detents + int8_t divisor; // Number of quadrature edges required per count + mp_int_t position; +}; diff --git a/ports/zephyr-cp/common-hal/rotaryio/__init__.c b/ports/zephyr-cp/common-hal/rotaryio/__init__.c new file mode 100644 index 00000000000..67cae26a8b7 --- /dev/null +++ b/ports/zephyr-cp/common-hal/rotaryio/__init__.c @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +// No rotaryio module functions. diff --git a/ports/zephyr-cp/common-hal/rtc/RTC.c b/ports/zephyr-cp/common-hal/rtc/RTC.c new file mode 100644 index 00000000000..2e4c93ebc21 --- /dev/null +++ b/ports/zephyr-cp/common-hal/rtc/RTC.c @@ -0,0 +1,90 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include + +#include "py/obj.h" +#include "py/runtime.h" +#include "shared/timeutils/timeutils.h" +#include "shared-bindings/rtc/RTC.h" +#include "common-hal/rtc/RTC.h" + +#include "bindings/zephyr_kernel/__init__.h" + +#include +#include +#include + +// The RTC driver already initializes its device at Zephyr boot time, so there +// is nothing for the port to start up: time is simply read from and written +// to the devicetree `rtc` device. +static const struct device *const rtc_dev = DEVICE_DT_GET(DT_ALIAS(rtc)); + +// Zephyr stores calibration in parts per billion. CircuitPython's calibration +// unit is approximately one part per million. +#define CALIBRATION_PPM_TO_ZEPHYR (1000) + +void common_hal_rtc_get_time(timeutils_struct_time_t *tm) { + struct rtc_time zephyr_tm; + int ret = rtc_get_time(rtc_dev, &zephyr_tm); + if (ret == -ENODATA) { + // The RTC has never been set (no battery-backed hardware and no + // seeded time). Report the start of the CircuitPython epoch, + // 2000-01-01, instead of failing; users set it with + // rtc.RTC().datetime. + timeutils_seconds_since_2000_to_struct_time(0, tm); + return; + } + CHECK_ZEPHYR_RESULT(ret); + + tm->tm_year = zephyr_tm.tm_year + 1900; + tm->tm_mon = zephyr_tm.tm_mon + 1; + tm->tm_mday = zephyr_tm.tm_mday; + tm->tm_hour = zephyr_tm.tm_hour; + tm->tm_min = zephyr_tm.tm_min; + tm->tm_sec = zephyr_tm.tm_sec; + // tm_wday and tm_yday are filled in by struct_time_from_tm. +} + +void common_hal_rtc_set_time(timeutils_struct_time_t *tm) { + struct rtc_time zephyr_tm = { + .tm_year = tm->tm_year - 1900, + .tm_mon = tm->tm_mon - 1, + .tm_mday = tm->tm_mday, + .tm_hour = tm->tm_hour, + .tm_min = tm->tm_min, + .tm_sec = tm->tm_sec, + }; + CHECK_ZEPHYR_RESULT(rtc_set_time(rtc_dev, &zephyr_tm)); +} + +int common_hal_rtc_get_calibration(void) { + #ifdef CONFIG_RTC_CALIBRATION + int32_t zephyr_calibration; + int ret = rtc_get_calibration(rtc_dev, &zephyr_calibration); + if (ret == -ENOSYS || ret == -ENOTSUP) { + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_calibration); + } + CHECK_ZEPHYR_RESULT(ret); + return zephyr_calibration / CALIBRATION_PPM_TO_ZEPHYR; + #else + // The Zephyr RTC calibration syscall only exists with + // CONFIG_RTC_CALIBRATION, which is off unless a driver needs it. + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_calibration); + #endif +} + +void common_hal_rtc_set_calibration(int calibration) { + #ifdef CONFIG_RTC_CALIBRATION + int ret = rtc_set_calibration(rtc_dev, (int32_t)calibration * CALIBRATION_PPM_TO_ZEPHYR); + if (ret == -ENOSYS || ret == -ENOTSUP) { + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_calibration); + } + CHECK_ZEPHYR_RESULT(ret); + #else + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_calibration); + #endif +} diff --git a/ports/zephyr-cp/common-hal/rtc/RTC.h b/ports/zephyr-cp/common-hal/rtc/RTC.h new file mode 100644 index 00000000000..083d1d052c7 --- /dev/null +++ b/ports/zephyr-cp/common-hal/rtc/RTC.h @@ -0,0 +1,12 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// The RTC device is selected by the devicetree `rtc` alias, following +// Zephyr's own RTC sample (samples/drivers/rtc). The rtc module is only +// enabled (CIRCUITPY_RTC=1) when the alias exists and CONFIG_RTC is on, so +// common-hal/rtc/RTC.c can always DEVICE_DT_GET(DT_ALIAS(rtc)). diff --git a/ports/zephyr-cp/common-hal/rtc/__init__.c b/ports/zephyr-cp/common-hal/rtc/__init__.c new file mode 100644 index 00000000000..a24f54f1cdd --- /dev/null +++ b/ports/zephyr-cp/common-hal/rtc/__init__.c @@ -0,0 +1,5 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT diff --git a/ports/zephyr-cp/common-hal/socketpool/Socket.c b/ports/zephyr-cp/common-hal/socketpool/Socket.c index 857526a12de..1ea73fdeb02 100644 --- a/ports/zephyr-cp/common-hal/socketpool/Socket.c +++ b/ports/zephyr-cp/common-hal/socketpool/Socket.c @@ -20,170 +20,117 @@ #include "supervisor/shared/tick.h" #include "supervisor/workflow.h" -#include - -// void socketpool_resolve_host_or_throw(int family, int type, const char *hostname, struct sockaddr_storage *addr, int port) { -// // struct addrinfo *result_i; -// // const struct addrinfo hints = { -// // .ai_family = family, -// // .ai_socktype = type, -// // }; -// // int error = socketpool_getaddrinfo_common(hostname, port, &hints, &result_i); -// if (true) { -// common_hal_socketpool_socketpool_raise_gaierror_noname(); -// } -// // memcpy(addr, result_i->ai_addr, sizeof(struct sockaddr_storage)); -// // lwip_freeaddrinfo(result_i); -// } - -// static void resolve_host_or_throw(socketpool_socket_obj_t *self, const char *hostname, struct sockaddr_storage *addr, int port) { -// socketpool_resolve_host_or_throw(self->family, self->type, hostname, addr, port); -// } - -// StackType_t socket_select_stack[2 * configMINIMAL_STACK_SIZE]; - -// /* Socket state table: -// * 0 := Closed (unused) -// * 1 := Open -// * 2 := Closing (remove from rfds) -// * Index into socket_fd_state is calculated from actual lwip fd. idx := fd - LWIP_SOCKET_OFFSET -// */ -// #define FDSTATE_CLOSED 0 -// #define FDSTATE_OPEN 1 -// #define FDSTATE_CLOSING 2 -// static uint8_t socket_fd_state[CONFIG_LWIP_MAX_SOCKETS]; +#include +#include +#include +#include +#include -// How long to wait between checks for a socket to connect. -#define SOCKET_CONNECT_POLL_INTERVAL_MS 100 +#include +#include +#include -// static socketpool_socket_obj_t *user_socket[CONFIG_LWIP_MAX_SOCKETS]; -// StaticTask_t socket_select_task_buffer; -// TaskHandle_t socket_select_task_handle; -// static int socket_change_fd = -1; - -// static void socket_select_task(void *arg) { -// uint64_t signal; -// fd_set readfds; -// fd_set excptfds; - -// while (true) { -// FD_ZERO(&readfds); -// FD_ZERO(&excptfds); -// FD_SET(socket_change_fd, &readfds); -// int max_fd = socket_change_fd; -// for (size_t i = 0; i < MP_ARRAY_SIZE(socket_fd_state); i++) { -// if ((socket_fd_state[i] == FDSTATE_OPEN) && (user_socket[i] == NULL)) { -// int sockfd = i + LWIP_SOCKET_OFFSET; -// max_fd = MAX(max_fd, sockfd); -// FD_SET(sockfd, &readfds); -// FD_SET(sockfd, &excptfds); -// } -// } - -// int num_triggered = select(max_fd + 1, &readfds, NULL, &excptfds, NULL); -// // Hard error (or someone closed a socket on another thread) -// if (num_triggered == -1) { -// assert(errno == EBADF); -// continue; -// } - -// assert(num_triggered > 0); - -// // Notice event trigger -// if (FD_ISSET(socket_change_fd, &readfds)) { -// read(socket_change_fd, &signal, sizeof(signal)); -// num_triggered--; -// } - -// // Handle active FDs, close the dead ones -// for (size_t i = 0; i < MP_ARRAY_SIZE(socket_fd_state); i++) { -// int sockfd = i + LWIP_SOCKET_OFFSET; -// if (socket_fd_state[i] != FDSTATE_CLOSED) { -// if (FD_ISSET(sockfd, &readfds) || FD_ISSET(sockfd, &excptfds)) { -// if (socket_fd_state[i] == FDSTATE_CLOSING) { -// socket_fd_state[i] = FDSTATE_CLOSED; -// num_triggered--; -// } -// } -// } -// } - -// if (num_triggered > 0) { -// // Wake up CircuitPython by queuing request -// supervisor_workflow_request_background(); -// ulTaskNotifyTake(pdTRUE, portMAX_DELAY); -// } -// } - -// close(socket_change_fd); -// socket_change_fd = -1; -// vTaskDelete(NULL); -// } +#define SOCKETPOOL_IP_STR_LEN 48 -void socket_user_reset(void) { - // if (socket_change_fd < 0) { - // esp_vfs_eventfd_config_t config = ESP_VFS_EVENTD_CONFIG_DEFAULT(); - // ESP_ERROR_CHECK(esp_vfs_eventfd_register(&config)); - - // // Clear initial socket states - // for (size_t i = 0; i < MP_ARRAY_SIZE(socket_fd_state); i++) { - // socket_fd_state[i] = FDSTATE_CLOSED; - // user_socket[i] = NULL; - // } - // socket_change_fd = eventfd(0, 0); - // // Run this at the same priority as CP so that the web workflow background task can be - // // queued while CP is running. Both tasks can still sleep and, therefore, sleep overall. - // socket_select_task_handle = xTaskCreateStaticPinnedToCore(socket_select_task, - // "socket_select", - // 2 * configMINIMAL_STACK_SIZE, - // NULL, - // uxTaskPriorityGet(NULL), - // socket_select_stack, - // &socket_select_task_buffer, - // xPortGetCoreID()); - // } else { - // // Not init - close open user sockets - // for (size_t i = 0; i < MP_ARRAY_SIZE(socket_fd_state); i++) { - // if ((socket_fd_state[i] == FDSTATE_OPEN) && user_socket[i]) { - // common_hal_socketpool_socket_close(user_socket[i]); - // } - // } - // } +static mp_obj_t _format_address(const struct sockaddr *addr, int family) { + char ip_str[SOCKETPOOL_IP_STR_LEN]; + const struct sockaddr_in *a = (void *)addr; + + switch (family) { + #if CIRCUITPY_SOCKETPOOL_IPV6 + case AF_INET6: + zsock_inet_ntop(family, &((const struct sockaddr_in6 *)a)->sin6_addr, ip_str, sizeof(ip_str)); + break; + #endif + default: + case AF_INET: + zsock_inet_ntop(family, &((const struct sockaddr_in *)a)->sin_addr, ip_str, sizeof(ip_str)); + break; + } + return mp_obj_new_str(ip_str, strlen(ip_str)); } -// Unblock select task (ok if not blocked yet) -void socketpool_socket_poll_resume(void) { - // if (socket_select_task_handle) { - // xTaskNotifyGive(socket_select_task_handle); - // } +static mp_obj_t _sockaddr_to_tuple(const struct sockaddr_storage *sockaddr) { + mp_obj_t args[4] = { + _format_address((const struct sockaddr *)sockaddr, sockaddr->ss_family), + }; + int n = 2; + #if CIRCUITPY_SOCKETPOOL_IPV6 + if (sockaddr->ss_family == AF_INET6) { + const struct sockaddr_in6 *addr6 = (const void *)sockaddr; + args[1] = MP_OBJ_NEW_SMALL_INT(ntohs(addr6->sin6_port)); + args[2] = MP_OBJ_NEW_SMALL_INT(addr6->sin6_flowinfo); + args[3] = MP_OBJ_NEW_SMALL_INT(addr6->sin6_scope_id); + n = 4; + } else + #endif + { + const struct sockaddr_in *addr = (const void *)sockaddr; + args[1] = MP_OBJ_NEW_SMALL_INT(ntohs(addr->sin_port)); + } + return mp_obj_new_tuple(n, args); +} + +static void socketpool_resolve_host_or_throw(int family, int type, const char *hostname, struct sockaddr_storage *addr, int port) { + const struct zsock_addrinfo hints = { + .ai_family = family, + .ai_socktype = type, + }; + struct zsock_addrinfo *result_i = NULL; + char service_buf[6]; + + snprintf(service_buf, sizeof(service_buf), "%d", port); + + int error = zsock_getaddrinfo(hostname, service_buf, &hints, &result_i); + if (error != 0 || result_i == NULL) { + // Report what the resolver said. A null result with no error is the + // one case that really is "not found". + if (error == 0) { + error = DNS_EAI_NONAME; + } + common_hal_socketpool_socketpool_raise_gaierror(error); + } + + memcpy(addr, result_i->ai_addr, sizeof(struct sockaddr_storage)); + zsock_freeaddrinfo(result_i); } -// The writes below send an event to the socket select task so that it redoes the -// select with the new open socket set. +static void resolve_host_or_throw(socketpool_socket_obj_t *self, const char *hostname, struct sockaddr_storage *addr, int port) { + socketpool_resolve_host_or_throw(self->family, self->type, hostname, addr, port); +} -// static bool register_open_socket(int fd) { -// if (fd < FD_SETSIZE) { -// socket_fd_state[fd - LWIP_SOCKET_OFFSET] = FDSTATE_OPEN; -// user_socket[fd - LWIP_SOCKET_OFFSET] = NULL; +// How long to wait between checks for a socket to connect. +#define SOCKET_CONNECT_POLL_INTERVAL_MS 100 -// uint64_t signal = 1; -// write(socket_change_fd, &signal, sizeof(signal)); -// socketpool_socket_poll_resume(); -// return true; -// } -// return false; -// } +void socket_user_reset(void) { + // User sockets are heap objects with __del__ bound to close(). + // During VM shutdown/reset, gc_sweep_all() runs finalizers, so sockets + // are closed there rather than being tracked and closed explicitly here. +} -// static void mark_user_socket(int fd, socketpool_socket_obj_t *obj) { -// socket_fd_state[fd - LWIP_SOCKET_OFFSET] = FDSTATE_OPEN; -// user_socket[fd - LWIP_SOCKET_OFFSET] = obj; -// // No need to wakeup select task -// } +static struct k_work_delayable socketpool_poll_work; +static bool socketpool_poll_work_initialized; + +static void socketpool_poll_work_handler(struct k_work *work) { + (void)work; + supervisor_workflow_request_background(); +} + +// Unblock select task (ok if not blocked yet) +void socketpool_socket_poll_resume(void) { + if (!socketpool_poll_work_initialized) { + k_work_init_delayable(&socketpool_poll_work, socketpool_poll_work_handler); + socketpool_poll_work_initialized = true; + } + k_work_schedule(&socketpool_poll_work, K_MSEC(10)); +} static bool _socketpool_socket(socketpool_socketpool_obj_t *self, socketpool_socketpool_addressfamily_t family, socketpool_socketpool_sock_t type, int proto, socketpool_socket_obj_t *sock) { + sock->num = -1; + int addr_family; int ipproto; @@ -212,16 +159,23 @@ static bool _socketpool_socket(socketpool_socketpool_obj_t *self, sock->pool = self; sock->timeout_ms = (uint)-1; - // Create LWIP socket - // int socknum = -1; - // socknum = lwip_socket(sock->family, sock->type, sock->ipproto); - // if (socknum < 0) { - // return false; - // } + int socknum = zsock_socket(sock->family, sock->type, sock->ipproto); + if (socknum < 0) { + return false; + } - // sock->num = socknum; - // // Sockets should be nonblocking in most cases - // lwip_fcntl(socknum, F_SETFL, O_NONBLOCK); + sock->num = socknum; + + // Enable address reuse by default to avoid bind failures on recently-used ports. + int reuseaddr = 1; + if (zsock_setsockopt(socknum, SOL_SOCKET, SO_REUSEADDR, &reuseaddr, sizeof(reuseaddr)) < 0) { + // Ignore if SO_REUSEADDR is unsupported. + } + + // Sockets should be nonblocking in most cases. + if (zsock_fcntl(socknum, F_SETFL, ZVFS_O_NONBLOCK) < 0) { + // Ignore if non-blocking is unsupported. + } return true; } @@ -235,11 +189,6 @@ bool socketpool_socket(socketpool_socketpool_obj_t *self, return false; } - // This shouldn't happen since we have room for the same number of sockets as LWIP. - // if (!register_open_socket(sock->num)) { - // lwip_close(sock->num); - // return false; - // } return true; } @@ -258,15 +207,17 @@ socketpool_socket_obj_t *common_hal_socketpool_socket(socketpool_socketpool_obj_ socketpool_socket_obj_t *sock = mp_obj_malloc_with_finaliser(socketpool_socket_obj_t, &socketpool_socket_type); if (!_socketpool_socket(self, family, type, proto, sock)) { - mp_raise_RuntimeError(MP_ERROR_TEXT("Out of sockets")); + // Report zsock_socket's real error: -EPFNOSUPPORT (e.g. TCP compiled + // out) is very different from a full fd table (EMFILE), so hiding the + // errno behind the generic "Out of sockets" hides the actual cause. + mp_raise_OSError(errno); } - // mark_user_socket(sock->num, sock); return sock; } int socketpool_socket_accept(socketpool_socket_obj_t *self, mp_obj_t *peer_out, socketpool_socket_obj_t *accepted) { struct sockaddr_storage peer_addr; - // socklen_t socklen = sizeof(peer_addr); + socklen_t socklen = sizeof(peer_addr); int newsoc = -1; bool timed_out = false; uint64_t start_ticks = supervisor_ticks_ms64(); @@ -277,11 +228,14 @@ int socketpool_socket_accept(socketpool_socket_obj_t *self, mp_obj_t *peer_out, timed_out = supervisor_ticks_ms64() - start_ticks >= self->timeout_ms; } RUN_BACKGROUND_TASKS; - // newsoc = lwip_accept(self->num, (struct sockaddr *)&peer_addr, &socklen); + newsoc = zsock_accept(self->num, (struct sockaddr *)&peer_addr, &socklen); // In non-blocking mode, fail instead of timing out if (newsoc == -1 && (self->timeout_ms == 0 || mp_hal_is_interrupted())) { return -MP_EAGAIN; } + if (newsoc == -1 && errno != EAGAIN && errno != EWOULDBLOCK) { + return -errno; + } } if (timed_out) { @@ -293,18 +247,14 @@ int socketpool_socket_accept(socketpool_socket_obj_t *self, mp_obj_t *peer_out, } // We got a socket. New client socket will not be non-blocking by default, so make it non-blocking. - // lwip_fcntl(newsoc, F_SETFL, O_NONBLOCK); + if (zsock_fcntl(newsoc, F_SETFL, ZVFS_O_NONBLOCK) < 0) { + // Ignore if non-blocking is unsupported. + } if (accepted != NULL) { // Error if called with open socket object. assert(common_hal_socketpool_socket_get_closed(accepted)); - // Register if system socket - // if (!register_open_socket(newsoc)) { - // lwip_close(newsoc); - // return -MP_EBADF; - // } - // Replace the old accepted socket with the new one. accepted->num = newsoc; accepted->pool = self->pool; @@ -313,7 +263,7 @@ int socketpool_socket_accept(socketpool_socket_obj_t *self, mp_obj_t *peer_out, } if (peer_out) { - *peer_out = sockaddr_to_tuple(&peer_addr); + *peer_out = _sockaddr_to_tuple(&peer_addr); } return newsoc; @@ -325,9 +275,8 @@ socketpool_socket_obj_t *common_hal_socketpool_socket_accept(socketpool_socket_o socketpool_socket_obj_t *sock = mp_obj_malloc_with_finaliser(socketpool_socket_obj_t, NULL); int newsoc = socketpool_socket_accept(self, peer_out, NULL); - if (newsoc > 0) { + if (newsoc >= 0) { // Create the socket - // mark_user_socket(newsoc, sock); sock->base.type = &socketpool_socket_type; sock->num = newsoc; sock->pool = self->pool; @@ -343,40 +292,42 @@ socketpool_socket_obj_t *common_hal_socketpool_socket_accept(socketpool_socket_o size_t common_hal_socketpool_socket_bind(socketpool_socket_obj_t *self, const char *host, size_t hostlen, uint32_t port) { - // struct sockaddr_storage bind_addr; + struct sockaddr_storage bind_addr; const char *broadcast = ""; + uint32_t local_port = port; - // bind_addr.ss_family = self->family; + memset(&bind_addr, 0, sizeof(bind_addr)); + bind_addr.ss_family = self->family; #if CIRCUITPY_SOCKETPOOL_IPV6 if (self->family == AF_INET6) { struct sockaddr_in6 *addr6 = (void *)&bind_addr; - addr6->sin6_port = htons(port); + addr6->sin6_port = htons(local_port); // no ipv6 broadcast if (hostlen == 0) { memset(&addr6->sin6_addr, 0, sizeof(addr6->sin6_addr)); } else { - socketpool_resolve_host_or_throw(self->family, self->type, host, &bind_addr, port); + socketpool_resolve_host_or_throw(self->family, self->type, host, &bind_addr, local_port); } } else #endif { - // struct sockaddr_in *addr4 = (void *)&bind_addr; - // addr4->sin_port = htons(port); + struct sockaddr_in *addr4 = (void *)&bind_addr; + addr4->sin_port = htons(local_port); if (hostlen == 0) { - // addr4->sin_addr.s_addr = IPADDR_ANY; + addr4->sin_addr.s_addr = htonl(INADDR_ANY); } else if (hostlen == strlen(broadcast) && memcmp(host, broadcast, strlen(broadcast)) == 0) { - // addr4->sin_addr.s_addr = IPADDR_BROADCAST; + addr4->sin_addr.s_addr = htonl(INADDR_BROADCAST); } else { - // socketpool_resolve_host_or_throw(self->family, self->type, host, &bind_addr, port); + socketpool_resolve_host_or_throw(self->family, self->type, host, &bind_addr, local_port); } } - // int result = lwip_bind(self->num, (struct sockaddr *)&bind_addr, sizeof(bind_addr)); - // if (result == 0) { - // return 0; - // } + int result = zsock_bind(self->num, (struct sockaddr *)&bind_addr, sizeof(bind_addr)); + if (result == 0) { + return 0; + } return errno; } @@ -390,20 +341,11 @@ void socketpool_socket_close(socketpool_socket_obj_t *self) { } #endif self->connected = false; - // int fd = self->num; - // Ignore bogus/closed sockets - // if (fd >= LWIP_SOCKET_OFFSET) { - // if (user_socket[fd - LWIP_SOCKET_OFFSET] == NULL) { - // socket_fd_state[fd - LWIP_SOCKET_OFFSET] = FDSTATE_CLOSING; - // lwip_shutdown(fd, SHUT_RDWR); - // lwip_close(fd); - // } else { - // lwip_shutdown(fd, SHUT_RDWR); - // lwip_close(fd); - // socket_fd_state[fd - LWIP_SOCKET_OFFSET] = FDSTATE_CLOSED; - // user_socket[fd - LWIP_SOCKET_OFFSET] = NULL; - // } - // } + int fd = self->num; + if (fd >= 0) { + zsock_shutdown(fd, ZSOCK_SHUT_RDWR); + zsock_close(fd); + } self->num = -1; } @@ -413,16 +355,11 @@ void common_hal_socketpool_socket_close(socketpool_socket_obj_t *self) { void common_hal_socketpool_socket_connect(socketpool_socket_obj_t *self, const char *host, size_t hostlen, uint32_t port) { - // struct sockaddr_storage addr; - // resolve_host_or_throw(self, host, &addr, port); + (void)hostlen; + struct sockaddr_storage addr; + resolve_host_or_throw(self, host, &addr, port); - // Replace above with function call ----- - - // Emulate SO_CONTIMEO, which is not implemented by lwip. - // All our sockets are non-blocking, so we check the timeout ourselves. - - int result = -1; - // result = lwip_connect(self->num, (struct sockaddr *)&addr, addr.s2_len); + int result = zsock_connect(self->num, (struct sockaddr *)&addr, sizeof(addr)); if (result == 0) { // Connected immediately. @@ -436,12 +373,7 @@ void common_hal_socketpool_socket_connect(socketpool_socket_obj_t *self, return; } - // struct timeval timeout = { - // .tv_sec = 0, - // .tv_usec = SOCKET_CONNECT_POLL_INTERVAL_MS * 1000, - // }; - - // Keep checking, using select(), until timeout expires, at short intervals. + // Keep checking, using poll(), until timeout expires, at short intervals. // This allows ctrl-C interrupts to be detected and background tasks to run. mp_uint_t timeout_left = self->timeout_ms; @@ -452,14 +384,22 @@ void common_hal_socketpool_socket_connect(socketpool_socket_obj_t *self, return; } - // fd_set fds; - // FD_ZERO(&fds); - // FD_SET(self->num, &fds); + struct zsock_pollfd fd = { + .fd = self->num, + .events = ZSOCK_POLLOUT, + }; + int poll_timeout = SOCKET_CONNECT_POLL_INTERVAL_MS; + if (self->timeout_ms == (uint)-1) { + poll_timeout = -1; + } else if (timeout_left < SOCKET_CONNECT_POLL_INTERVAL_MS) { + poll_timeout = timeout_left; + } - // result = select(self->num + 1, NULL, &fds, NULL, &timeout); + result = zsock_poll(&fd, 1, poll_timeout); if (result == 0) { - // No change to fd's after waiting for timeout, so try again if some time is still left. - // Don't wrap below 0, because we're using a uint. + if (self->timeout_ms == (uint)-1) { + continue; + } if (timeout_left < SOCKET_CONNECT_POLL_INTERVAL_MS) { timeout_left = 0; } else { @@ -469,16 +409,14 @@ void common_hal_socketpool_socket_connect(socketpool_socket_obj_t *self, } if (result < 0) { - // Some error happened when doing select(); error is in errno. mp_raise_OSError(errno); } - // select() indicated the socket is writable. Check if any connection error occurred. int error_code = 0; - // socklen_t socklen = sizeof(error_code); - // result = getsockopt(self->num, SOL_SOCKET, SO_ERROR, &error_code, &socklen); + socklen_t socklen = sizeof(error_code); + result = zsock_getsockopt(self->num, SOL_SOCKET, SO_ERROR, &error_code, &socklen); if (result < 0 || error_code != 0) { - mp_raise_OSError(errno); + mp_raise_OSError(error_code != 0 ? error_code : errno); } self->connected = true; return; @@ -498,17 +436,15 @@ bool common_hal_socketpool_socket_get_connected(socketpool_socket_obj_t *self) { } bool common_hal_socketpool_socket_listen(socketpool_socket_obj_t *self, int backlog) { - // return lwip_listen(self->num, backlog) == 0; - return false; + return zsock_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, mp_obj_t *source_out) { - // struct sockaddr_storage source_addr; - // socklen_t socklen = sizeof(source_addr); + struct sockaddr_storage source_addr; + socklen_t socklen = sizeof(source_addr); - // LWIP Socket uint64_t start_ticks = supervisor_ticks_ms64(); int received = -1; bool timed_out = false; @@ -519,11 +455,18 @@ mp_uint_t common_hal_socketpool_socket_recvfrom_into(socketpool_socket_obj_t *se 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); + received = zsock_recvfrom(self->num, buf, len, ZSOCK_MSG_DONTWAIT, (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 (received < 0 && errno != EAGAIN && errno != EWOULDBLOCK) { + mp_raise_OSError(errno); + } + + if (received == -1 && (errno == EAGAIN || errno == EWOULDBLOCK)) { + // In non-blocking mode, fail instead of looping + if (self->timeout_ms == 0) { + mp_raise_OSError(MP_EAGAIN); + } + continue; } } @@ -537,7 +480,7 @@ mp_uint_t common_hal_socketpool_socket_recvfrom_into(socketpool_socket_obj_t *se } if (source_out) { - // *source_out = sockaddr_to_tuple(&source_addr); + *source_out = _sockaddr_to_tuple(&source_addr); } return received; @@ -549,7 +492,6 @@ int socketpool_socket_recv_into(socketpool_socket_obj_t *self, bool timed_out = false; if (self->num != -1) { - // LWIP Socket uint64_t start_ticks = supervisor_ticks_ms64(); received = -1; while (received == -1 && @@ -558,7 +500,16 @@ int socketpool_socket_recv_into(socketpool_socket_obj_t *self, timed_out = supervisor_ticks_ms64() - start_ticks >= self->timeout_ms; } RUN_BACKGROUND_TASKS; - // received = lwip_recv(self->num, (void *)buf, len, 0); + received = zsock_recv(self->num, (void *)buf, len, ZSOCK_MSG_DONTWAIT); + if (received < 0 && errno != EAGAIN && errno != EWOULDBLOCK) { + return -errno; + } + if (received < 1 && (errno == EAGAIN || errno == EWOULDBLOCK)) { + if (self->timeout_ms == 0) { + return -MP_EAGAIN; + } + continue; + } // In non-blocking mode, fail instead of looping if (received < 1 && self->timeout_ms == 0) { if ((received == 0) || (errno == ENOTCONN)) { @@ -597,9 +548,7 @@ mp_uint_t common_hal_socketpool_socket_recv_into(socketpool_socket_obj_t *self, int 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); + sent = zsock_send(self->num, buf, len, 0); } else { sent = -MP_EBADF; } @@ -626,15 +575,15 @@ mp_uint_t common_hal_socketpool_socket_send(socketpool_socket_obj_t *self, const 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) { - // struct sockaddr_storage addr; - // resolve_host_or_throw(self, host, &addr, port); + (void)hostlen; + struct sockaddr_storage addr; + resolve_host_or_throw(self, host, &addr, port); - // int bytes_sent = lwip_sendto(self->num, buf, len, 0, (struct sockaddr *)&addr, addr.s2_len); - // if (bytes_sent < 0) { - // mp_raise_BrokenPipeError(); - // return 0; - // } - int bytes_sent = 0; + int bytes_sent = zsock_sendto(self->num, buf, len, 0, (struct sockaddr *)&addr, sizeof(addr)); + if (bytes_sent < 0) { + mp_raise_BrokenPipeError(); + return 0; + } return bytes_sent; } @@ -648,7 +597,44 @@ mp_int_t common_hal_socketpool_socket_get_type(socketpool_socket_obj_t *self) { int common_hal_socketpool_socket_setsockopt(socketpool_socket_obj_t *self, int level, int optname, const void *value, size_t optlen) { - int err = 0; // lwip_setsockopt(self->num, level, optname, value, optlen); + int zephyr_level = level; + int zephyr_optname = optname; + + switch (level) { + case SOCKETPOOL_SOL_SOCKET: + zephyr_level = SOL_SOCKET; + break; + case SOCKETPOOL_IPPROTO_IP: + zephyr_level = IPPROTO_IP; + break; + case SOCKETPOOL_IPPROTO_TCP: + zephyr_level = IPPROTO_TCP; + break; + case SOCKETPOOL_IPPROTO_UDP: + zephyr_level = IPPROTO_UDP; + break; + #if CIRCUITPY_SOCKETPOOL_IPV6 + case SOCKETPOOL_IPPROTO_IPV6: + zephyr_level = IPPROTO_IPV6; + break; + #endif + } + + if (zephyr_level == SOL_SOCKET) { + switch (optname) { + case SOCKETPOOL_SO_REUSEADDR: + zephyr_optname = SO_REUSEADDR; + break; + } + } else if (zephyr_level == IPPROTO_TCP) { + switch (optname) { + case SOCKETPOOL_TCP_NODELAY: + zephyr_optname = TCP_NODELAY; + break; + } + } + + int err = zsock_setsockopt(self->num, zephyr_level, zephyr_optname, value, optlen); if (err != 0) { return -errno; } @@ -656,29 +642,23 @@ int common_hal_socketpool_socket_setsockopt(socketpool_socket_obj_t *self, int l } bool common_hal_socketpool_readable(socketpool_socket_obj_t *self) { - // struct timeval immediate = {0, 0}; + struct zsock_pollfd fd = { + .fd = self->num, + .events = ZSOCK_POLLIN, + }; - // fd_set fds; - // FD_ZERO(&fds); - // FD_SET(self->num, &fds); - // int num_triggered = select(self->num + 1, &fds, NULL, &fds, &immediate); - - // including returning true in the error case - // return num_triggered != 0; - return false; + int num_triggered = zsock_poll(&fd, 1, 0); + return num_triggered > 0; } bool common_hal_socketpool_writable(socketpool_socket_obj_t *self) { - // struct timeval immediate = {0, 0}; - - // fd_set fds; - // FD_ZERO(&fds); - // FD_SET(self->num, &fds); - // int num_triggered = select(self->num + 1, NULL, &fds, &fds, &immediate); + struct zsock_pollfd fd = { + .fd = self->num, + .events = ZSOCK_POLLOUT, + }; - // including returning true in the error case - // return num_triggered != 0; - return false; + int num_triggered = zsock_poll(&fd, 1, 0); + return num_triggered > 0; } void socketpool_socket_move(socketpool_socket_obj_t *self, socketpool_socket_obj_t *sock) { diff --git a/ports/zephyr-cp/common-hal/socketpool/SocketPool.c b/ports/zephyr-cp/common-hal/socketpool/SocketPool.c index 4531c5bf1b7..4fca41f2c31 100644 --- a/ports/zephyr-cp/common-hal/socketpool/SocketPool.c +++ b/ports/zephyr-cp/common-hal/socketpool/SocketPool.c @@ -8,114 +8,186 @@ #include "common-hal/socketpool/Socket.h" #include "py/runtime.h" +#include "shared/runtime/interrupt_char.h" +#if CIRCUITPY_HOSTNETWORK +#include "bindings/hostnetwork/__init__.h" +#endif +#if CIRCUITPY_WIFI #include "shared-bindings/wifi/__init__.h" +#endif +#if CIRCUITPY_MII +#include "shared-bindings/mii/Ethernet.h" +#endif #include "common-hal/socketpool/__init__.h" -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(MP_ERROR_TEXT("SocketPool can only be used with wifi.radio")); +#include +#include + +#include +#include + +void common_hal_socketpool_socketpool_construct(socketpool_socketpool_obj_t *self, mp_obj_t network_interface) { + bool is_wifi = false; + #if CIRCUITPY_WIFI + is_wifi = network_interface == MP_OBJ_FROM_PTR(&common_hal_wifi_radio_obj); + #endif + bool is_ethernet = false; + #if CIRCUITPY_MII + is_ethernet = mp_obj_is_type(network_interface, &mii_ethernet_type); + #endif + bool is_hostnetwork = false; + #if CIRCUITPY_HOSTNETWORK + is_hostnetwork = mp_obj_is_type(network_interface, &hostnetwork_hostnetwork_type); + #endif + if (!(is_wifi || is_ethernet || is_hostnetwork)) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("SocketPool can only be used with %q.%q, %q.%q, or %q.%q"), + MP_QSTR_wifi, MP_QSTR_radio, MP_QSTR_board, MP_QSTR_ETHERNET, + MP_QSTR_hostnetwork, MP_QSTR_HostNetwork); } } // common_hal_socketpool_socket is in socketpool/Socket.c to centralize open socket tracking. -// int socketpool_getaddrinfo_common(const char *host, int service, const struct addrinfo *hints, struct addrinfo **res) { -// // As of 2022, the version of lwip in esp-idf does not handle the -// // trailing-dot syntax of domain names, so emulate it. -// // Remove this once https://github.com/espressif/esp-idf/issues/10013 has -// // been implemented -// if (host) { -// size_t strlen_host = strlen(host); -// if (strlen_host && host[strlen_host - 1] == '.') { -// mp_obj_t nodot = mp_obj_new_str(host, strlen_host - 1); -// host = mp_obj_str_get_str(nodot); -// } -// } - -// // char service_buf[6]; -// // snprintf(service_buf, sizeof(service_buf), "%d", service); - -// // return lwip_getaddrinfo(host, service_buf, hints, res); -// return 0; -// } - -// static mp_obj_t format_address(const struct sockaddr *addr, int family) { -// char ip_str[IPADDR_STRLEN_MAX]; // big enough for any supported address type -// const struct sockaddr_in *a = (void *)addr; - -// switch (family) { -// #if CIRCUITPY_SOCKETPOOL_IPV6 -// case AF_INET6: -// inet_ntop(family, &((const struct sockaddr_in6 *)a)->sin6_addr, ip_str, sizeof(ip_str)); -// break; -// #endif -// default: -// case AF_INET: -// inet_ntop(family, &((const struct sockaddr_in *)a)->sin_addr, ip_str, sizeof(ip_str)); -// break; -// } -// return mp_obj_new_str(ip_str, strlen(ip_str)); -// } - -// static mp_obj_t convert_sockaddr(const struct addrinfo *ai, int port) { -// #if CIRCUITPY_SOCKETPOOL_IPV6 -// mp_int_t n_tuple = ai->ai_family == AF_INET6 ? 4 : 2; -// #else -// mp_int_t n_tuple = 2; -// #endif -// mp_obj_tuple_t *result = MP_OBJ_TO_PTR(mp_obj_new_tuple(n_tuple, NULL)); -// result->items[0] = format_address(ai->ai_addr, ai->ai_family); -// result->items[1] = MP_OBJ_NEW_SMALL_INT(port); -// #if CIRCUITPY_SOCKETPOOL_IPV6 -// if (ai->ai_family == AF_INET6) { -// const struct sockaddr_in6 *ai6 = (void *)ai->ai_addr; -// result->items[2] = MP_OBJ_NEW_SMALL_INT(ai6->sin6_flowinfo); -// result->items[3] = MP_OBJ_NEW_SMALL_INT(ai6->sin6_scope_id); -// } -// #endif -// return result; -// } - -// static mp_obj_t convert_addrinfo(const struct addrinfo *ai, int port) { -// MP_STATIC_ASSERT(AF_INET == SOCKETPOOL_AF_INET); -// #if CIRCUITPY_SOCKETPOOL_IPV6 -// MP_STATIC_ASSERT(AF_INET6 == SOCKETPOOL_AF_INET6); -// #endif -// // MP_STATIC_ASSERT(AF_UNSPEC == SOCKETPOOL_AF_UNSPEC); -// mp_obj_tuple_t *result = MP_OBJ_TO_PTR(mp_obj_new_tuple(5, NULL)); -// result->items[0] = MP_OBJ_NEW_SMALL_INT(ai->ai_family); -// result->items[1] = MP_OBJ_NEW_SMALL_INT(ai->ai_socktype); -// result->items[2] = MP_OBJ_NEW_SMALL_INT(ai->ai_protocol); -// result->items[3] = ai->ai_canonname ? mp_obj_new_str(ai->ai_canonname, strlen(ai->ai_canonname)) : MP_OBJ_NEW_QSTR(MP_QSTR_); -// result->items[4] = convert_sockaddr(ai, port); -// return result; -// } +static int socketpool_getaddrinfo_common(const char *host, int service, const struct zsock_addrinfo *hints, struct zsock_addrinfo **res) { + char service_buf[6]; + snprintf(service_buf, sizeof(service_buf), "%d", service); + + return zsock_getaddrinfo(host, service_buf, hints, res); +} + +#define SOCKETPOOL_IP_STR_LEN 48 + +// Zephyr's net namespace renumbers address families (NET_PF_INET = 1, +// NET_PF_INET6 = 2) while CircuitPython exposes the BSD numbers (AF_INET = 2, +// AF_INET6 = 10) through socketpool. Translate in both directions so the +// tuples getaddrinfo() produces and the hints callers pass in are in Python +// terms; AF_UNSPEC (0) is the same in both and passes through. +static int socketpool_family_to_zephyr(int family) { + switch (family) { + case SOCKETPOOL_AF_INET: + return NET_AF_INET; + #if CIRCUITPY_SOCKETPOOL_IPV6 + case SOCKETPOOL_AF_INET6: + return NET_AF_INET6; + #endif + default: + return NET_AF_UNSPEC; + } +} + +static int socketpool_family_from_zephyr(int family) { + switch (family) { + case NET_AF_INET: + return SOCKETPOOL_AF_INET; + case NET_AF_INET6: + return SOCKETPOOL_AF_INET6; + default: + return family; + } +} + +static mp_obj_t format_address(const struct sockaddr *addr, int family) { + char ip_str[SOCKETPOOL_IP_STR_LEN]; + const struct sockaddr_in *a = (void *)addr; + + switch (family) { + #if CIRCUITPY_SOCKETPOOL_IPV6 + case AF_INET6: + zsock_inet_ntop(family, &((const struct sockaddr_in6 *)a)->sin6_addr, ip_str, sizeof(ip_str)); + break; + #endif + default: + case AF_INET: + zsock_inet_ntop(family, &((const struct sockaddr_in *)a)->sin_addr, ip_str, sizeof(ip_str)); + break; + } + return mp_obj_new_str(ip_str, strlen(ip_str)); +} + +static mp_obj_t convert_sockaddr(const struct zsock_addrinfo *ai, int port) { + #if CIRCUITPY_SOCKETPOOL_IPV6 + mp_int_t n_tuple = ai->ai_family == AF_INET6 ? 4 : 2; + #else + mp_int_t n_tuple = 2; + #endif + mp_obj_tuple_t *result = MP_OBJ_TO_PTR(mp_obj_new_tuple(n_tuple, NULL)); + result->items[0] = format_address(ai->ai_addr, ai->ai_family); + result->items[1] = MP_OBJ_NEW_SMALL_INT(port); + #if CIRCUITPY_SOCKETPOOL_IPV6 + if (ai->ai_family == AF_INET6) { + const struct sockaddr_in6 *ai6 = (void *)ai->ai_addr; + result->items[2] = MP_OBJ_NEW_SMALL_INT(ai6->sin6_flowinfo); + result->items[3] = MP_OBJ_NEW_SMALL_INT(ai6->sin6_scope_id); + } + #endif + return result; +} + +static mp_obj_t convert_addrinfo(const struct zsock_addrinfo *ai, int port) { + mp_obj_tuple_t *result = MP_OBJ_TO_PTR(mp_obj_new_tuple(5, NULL)); + result->items[0] = MP_OBJ_NEW_SMALL_INT(socketpool_family_from_zephyr(ai->ai_family)); + result->items[1] = MP_OBJ_NEW_SMALL_INT(ai->ai_socktype); + result->items[2] = MP_OBJ_NEW_SMALL_INT(ai->ai_protocol); + result->items[3] = ai->ai_canonname ? mp_obj_new_str(ai->ai_canonname, strlen(ai->ai_canonname)) : MP_OBJ_NEW_QSTR(MP_QSTR_); + result->items[4] = convert_sockaddr(ai, port); + return result; +} mp_obj_t common_hal_socketpool_getaddrinfo_raise(socketpool_socketpool_obj_t *self, const char *host, int port, int family, int type, int proto, int flags) { - // const struct addrinfo hints = { - // .ai_flags = flags, - // .ai_family = family, - // .ai_protocol = proto, - // .ai_socktype = type, - // }; - - // struct addrinfo *res = NULL; - // int err = socketpool_getaddrinfo_common(host, port, &hints, &res); - if (true) { - common_hal_socketpool_socketpool_raise_gaierror_noname(); + // A fetch can run before DHCP has fed the resolver its server (scripts + // commonly connect() and then immediately fetch). Until the resolver has + // at least one server, a hostname lookup fails outright, reported as + // DNS_EAI_SYSTEM ("getaddrinfo failure: -11"). Rather than racing the + // lease at every caller, only wait when the resolver is genuinely empty; + // a ready resolver (the common case) passes straight through. + #if defined(CONFIG_DNS_RESOLVER) && defined(CONFIG_NET_DHCPV4) + { + struct dns_resolve_context *ctx = dns_resolve_get_default(); + bool have_server = false; + int64_t deadline = k_uptime_get() + 10000; + while (k_uptime_get() < deadline) { + for (int i = 0; i < CONFIG_DNS_RESOLVER_MAX_SERVERS; i++) { + if (ctx->servers[i].dns_server.sa_family != NET_AF_UNSPEC) { + have_server = true; + break; + } + } + if (have_server || mp_hal_is_interrupted()) { + break; + } + RUN_BACKGROUND_TASKS; + k_msleep(50); + } + } + #endif + + const struct zsock_addrinfo hints = { + .ai_flags = flags, + .ai_family = socketpool_family_to_zephyr(family), + .ai_protocol = proto, + .ai_socktype = type, + }; + + struct zsock_addrinfo *res = NULL; + int err = socketpool_getaddrinfo_common(host, port, &hints, &res); + if (err != 0 || res == NULL) { + if (err == 0) { + err = DNS_EAI_NONAME; + } + common_hal_socketpool_socketpool_raise_gaierror(err); } nlr_buf_t nlr; if (nlr_push(&nlr) == 0) { mp_obj_t result = mp_obj_new_list(0, NULL); - // for (struct addrinfo *ai = res; ai; ai = ai->ai_next) { - // mp_obj_list_append(result, convert_addrinfo(ai, port)); - // } + for (struct zsock_addrinfo *ai = res; ai; ai = ai->ai_next) { + mp_obj_list_append(result, convert_addrinfo(ai, port)); + } nlr_pop(); - // lwip_freeaddrinfo(res); + zsock_freeaddrinfo(res); return result; } else { - // lwip_freeaddrinfo(res); + zsock_freeaddrinfo(res); nlr_raise(MP_OBJ_FROM_PTR(nlr.ret_val)); } } diff --git a/ports/zephyr-cp/common-hal/socketpool/SocketPool.h b/ports/zephyr-cp/common-hal/socketpool/SocketPool.h index 64f91e01e1c..7891a8b8e48 100644 --- a/ports/zephyr-cp/common-hal/socketpool/SocketPool.h +++ b/ports/zephyr-cp/common-hal/socketpool/SocketPool.h @@ -6,6 +6,9 @@ #pragma once +#include +#include + #include "py/obj.h" typedef struct { diff --git a/ports/zephyr-cp/common-hal/usb_cdc/Serial.c b/ports/zephyr-cp/common-hal/usb_cdc/Serial.c new file mode 100644 index 00000000000..61d24462a51 --- /dev/null +++ b/ports/zephyr-cp/common-hal/usb_cdc/Serial.c @@ -0,0 +1,71 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Dan Halbert for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared/runtime/interrupt_char.h" +#include "shared-bindings/usb_cdc/Serial.h" +#include "shared-bindings/busio/UART.h" +#include "common-hal/busio/UART.h" +#include "supervisor/shared/tick.h" + +mp_obj_t common_hal_usb_cdc_serial_construct_from_device(usb_cdc_serial_obj_t *self, const struct device *uart_device, uint16_t receiver_buffer_size, byte *receiver_buffer, bool sigint_enabled) { + common_hal_busio_uart_construct_from_device(self, uart_device, receiver_buffer_size, receiver_buffer, sigint_enabled); + self->flow_control = true; + self->base.type = &usb_cdc_serial_type; + return MP_OBJ_FROM_PTR(self); +} + +size_t common_hal_usb_cdc_serial_read(usb_cdc_serial_obj_t *self, uint8_t *data, size_t len, int *errcode) { + return common_hal_busio_uart_read(self, data, len, errcode); +} + +size_t common_hal_usb_cdc_serial_write(usb_cdc_serial_obj_t *self, const uint8_t *data, size_t len, int *errcode) { + zephyr_uart_write_blocking(self, data, len); + return len; +} + +uint32_t common_hal_usb_cdc_serial_get_in_waiting(usb_cdc_serial_obj_t *self) { + return common_hal_busio_uart_rx_characters_available(self); +} + +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); + return 0; +} + +void common_hal_usb_cdc_serial_reset_input_buffer(usb_cdc_serial_obj_t *self) { + common_hal_busio_uart_clear_rx_buffer(self); +} + +uint32_t common_hal_usb_cdc_serial_reset_output_buffer(usb_cdc_serial_obj_t *self) { + // return tud_cdc_n_write_clear(self->idx); + return 0; +} + +uint32_t common_hal_usb_cdc_serial_flush(usb_cdc_serial_obj_t *self) { + // return tud_cdc_n_write_flush(self->idx); + return 0; +} + +bool common_hal_usb_cdc_serial_get_connected(usb_cdc_serial_obj_t *self) { + return !common_hal_busio_uart_deinited(self); +} + +mp_float_t common_hal_usb_cdc_serial_get_timeout(usb_cdc_serial_obj_t *self) { + return common_hal_busio_uart_get_timeout(self); +} + +void common_hal_usb_cdc_serial_set_timeout(usb_cdc_serial_obj_t *self, mp_float_t timeout) { + common_hal_busio_uart_set_timeout(self, timeout); +} + +mp_float_t common_hal_usb_cdc_serial_get_write_timeout(usb_cdc_serial_obj_t *self) { + return common_hal_busio_uart_get_write_timeout(self); +} + +void common_hal_usb_cdc_serial_set_write_timeout(usb_cdc_serial_obj_t *self, mp_float_t write_timeout) { + common_hal_busio_uart_set_write_timeout(self, write_timeout); +} diff --git a/ports/zephyr-cp/common-hal/usb_cdc/Serial.h b/ports/zephyr-cp/common-hal/usb_cdc/Serial.h new file mode 100644 index 00000000000..fdad46bec31 --- /dev/null +++ b/ports/zephyr-cp/common-hal/usb_cdc/Serial.h @@ -0,0 +1,14 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Dan Halbert for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-bindings/busio/UART.h" + +typedef busio_uart_obj_t usb_cdc_serial_obj_t; + +// Helper function for Zephyr-specific initialization from device tree +mp_obj_t common_hal_usb_cdc_serial_construct_from_device(usb_cdc_serial_obj_t *self, const struct device *uart_device, uint16_t receiver_buffer_size, byte *receiver_buffer, bool sigint_enabled); diff --git a/ports/zephyr-cp/common-hal/usb_cdc/__init__.c b/ports/zephyr-cp/common-hal/usb_cdc/__init__.c new file mode 100644 index 00000000000..7bcae396733 --- /dev/null +++ b/ports/zephyr-cp/common-hal/usb_cdc/__init__.c @@ -0,0 +1,40 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Dan Halbert for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#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 "supervisor/usb.h" + +static bool usb_cdc_console_is_enabled; +static bool usb_cdc_data_is_enabled; + +void usb_cdc_set_defaults(void) { + common_hal_usb_cdc_enable(true, + false); +} + +bool usb_cdc_console_enabled(void) { + return usb_cdc_console_is_enabled; +} + +bool usb_cdc_data_enabled(void) { + return usb_cdc_data_is_enabled; +} + +bool common_hal_usb_cdc_disable(void) { + return common_hal_usb_cdc_enable(false, false); +} + +bool common_hal_usb_cdc_enable(bool console, bool data) { + usb_cdc_console_is_enabled = console; + usb_cdc_data_is_enabled = data; + return true; +} diff --git a/ports/zephyr-cp/common-hal/usb_cdc/__init__.h b/ports/zephyr-cp/common-hal/usb_cdc/__init__.h new file mode 100644 index 00000000000..daf06d580ad --- /dev/null +++ b/ports/zephyr-cp/common-hal/usb_cdc/__init__.h @@ -0,0 +1,16 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2021 Dan Halbert for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/mpconfig.h" +#include "py/objtuple.h" +#include "supervisor/usb.h" + +bool usb_cdc_console_enabled(void); +bool usb_cdc_data_enabled(void); + +void usb_cdc_set_defaults(void); diff --git a/ports/zephyr-cp/common-hal/usb_hid/Device.c b/ports/zephyr-cp/common-hal/usb_hid/Device.c new file mode 100644 index 00000000000..ba263d44d74 --- /dev/null +++ b/ports/zephyr-cp/common-hal/usb_hid/Device.c @@ -0,0 +1,150 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018 hathach for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include +#include + +#include "py/gc.h" +#include "py/runtime.h" +#include "shared-bindings/usb_hid/Device.h" +#include "shared-module/usb_hid/__init__.h" +#include "shared-module/usb_hid/Device.h" +#include "shared-module/usb_hid/report_descriptors.h" +#include "common-hal/usb_hid/__init__.h" +#include "supervisor/shared/tick.h" + +const usb_hid_device_obj_t usb_hid_device_keyboard_obj = { + .base = { + .type = &usb_hid_device_type, + }, + .report_descriptor = keyboard_report_descriptor, + .report_descriptor_length = sizeof(keyboard_report_descriptor), + .usage_page = 0x01, + .usage = 0x06, + .num_report_ids = 1, + .report_ids = { 0x01, }, + .in_report_lengths = { 8, }, + .out_report_lengths = { 1, }, +}; + +const usb_hid_device_obj_t usb_hid_device_mouse_obj = { + .base = { + .type = &usb_hid_device_type, + }, + .report_descriptor = mouse_report_descriptor, + .report_descriptor_length = sizeof(mouse_report_descriptor), + .usage_page = 0x01, + .usage = 0x02, + .num_report_ids = 1, + .report_ids = { 0x02, }, + .in_report_lengths = { 4, }, + .out_report_lengths = { 0, }, +}; + +const usb_hid_device_obj_t usb_hid_device_consumer_control_obj = { + .base = { + .type = &usb_hid_device_type, + }, + .report_descriptor = consumer_control_report_descriptor, + .report_descriptor_length = sizeof(consumer_control_report_descriptor), + .usage_page = 0x0C, + .usage = 0x01, + .num_report_ids = 1, + .report_ids = { 0x03 }, + .in_report_lengths = { 2, }, + .out_report_lengths = { 0, }, +}; + +char *custom_usb_hid_interface_name; + +static size_t get_report_id_idx(usb_hid_device_obj_t *self, size_t report_id) { + for (size_t i = 0; i < self->num_report_ids; i++) { + if (report_id == self->report_ids[i]) { + return i; + } + } + return CIRCUITPY_USB_HID_MAX_REPORT_IDS_PER_DESCRIPTOR; +} + +uint8_t common_hal_usb_hid_device_validate_report_id(usb_hid_device_obj_t *self, mp_int_t report_id_arg) { + if (report_id_arg == -1 && self->num_report_ids == 1) { + return self->report_ids[0]; + } + if (!(report_id_arg >= 0 && + get_report_id_idx(self, (size_t)report_id_arg) < CIRCUITPY_USB_HID_MAX_REPORT_IDS_PER_DESCRIPTOR)) { + mp_arg_error_invalid(MP_QSTR_report_id); + } + return (uint8_t)report_id_arg; +} + +void common_hal_usb_hid_device_construct(usb_hid_device_obj_t *self, mp_obj_t report_descriptor, uint16_t usage_page, uint16_t usage, size_t num_report_ids, uint8_t *report_ids, uint8_t *in_report_lengths, uint8_t *out_report_lengths) { + mp_arg_validate_length_max( + num_report_ids, CIRCUITPY_USB_HID_MAX_REPORT_IDS_PER_DESCRIPTOR, MP_QSTR_report_ids); + + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(report_descriptor, &bufinfo, MP_BUFFER_READ); + self->report_descriptor_length = bufinfo.len; + + uint8_t *descriptor_bytes = gc_alloc(bufinfo.len, false); + memcpy(descriptor_bytes, bufinfo.buf, bufinfo.len); + self->report_descriptor = descriptor_bytes; + + self->usage_page = usage_page; + self->usage = usage; + self->num_report_ids = num_report_ids; + memcpy(self->report_ids, report_ids, num_report_ids); + memcpy(self->in_report_lengths, in_report_lengths, num_report_ids); + memcpy(self->out_report_lengths, out_report_lengths, num_report_ids); +} + +uint16_t common_hal_usb_hid_device_get_usage_page(usb_hid_device_obj_t *self) { + return self->usage_page; +} + +uint16_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, uint8_t report_id) { + size_t id_idx = get_report_id_idx(self, report_id); + + mp_arg_validate_length(len, self->in_report_lengths[id_idx], MP_QSTR_report); + + // Wait until interface is ready, timeout = 2 seconds + uint64_t end_ticks = supervisor_ticks_ms64() + 2000; + while ((supervisor_ticks_ms64() < end_ticks) && !usb_hid_ready()) { + RUN_BACKGROUND_TASKS; + } + + if (!usb_hid_submit_report(report_id, report, len)) { + mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("USB error")); + } +} + +mp_obj_t common_hal_usb_hid_device_get_last_received_report(usb_hid_device_obj_t *self, uint8_t report_id) { + size_t id_idx = get_report_id_idx(self, report_id); + if (!self->out_report_buffers_updated[id_idx]) { + return mp_const_none; + } + self->out_report_buffers_updated[id_idx] = false; + return mp_obj_new_bytes(self->out_report_buffers[id_idx], self->out_report_lengths[id_idx]); +} + +void usb_hid_device_create_report_buffers(usb_hid_device_obj_t *self) { + for (size_t i = 0; i < self->num_report_ids; i++) { + self->in_report_buffers[i] = + self->in_report_lengths[i] > 0 + ? gc_alloc(self->in_report_lengths[i], false) + : NULL; + + self->out_report_buffers[i] = + self->out_report_lengths[i] > 0 + ? gc_alloc(self->out_report_lengths[i], false) + : NULL; + } + memset(self->out_report_buffers_updated, 0, sizeof(self->out_report_buffers_updated)); +} diff --git a/ports/zephyr-cp/common-hal/usb_hid/__init__.c b/ports/zephyr-cp/common-hal/usb_hid/__init__.c new file mode 100644 index 00000000000..552a91e102b --- /dev/null +++ b/ports/zephyr-cp/common-hal/usb_hid/__init__.c @@ -0,0 +1,377 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include + +#include "py/gc.h" +#include "py/runtime.h" +#include "shared-bindings/usb_hid/__init__.h" +#include "shared-bindings/usb_hid/Device.h" +#include "shared-module/usb_hid/Device.h" +#include "supervisor/port.h" + +#include +#include +#include +#include +#include + +#define MAX_HID_DEVICES 8 + +static usb_hid_device_obj_t hid_devices[MAX_HID_DEVICES]; +// If 0, USB HID is disabled. +static mp_int_t num_hid_devices; +// Which boot device is available? 0: no boot devices, 1: boot keyboard, 2: boot mouse. +static uint8_t hid_boot_device; +// Whether a boot device was requested by a SET_PROTOCOL request from the host. +static bool hid_boot_device_requested; +// This tuple is stored in usb_hid.devices. +static mp_obj_tuple_t *hid_devices_tuple; + +// Whether the HID interface is ready (USB configured). +static bool hid_interface_ready; + +static mp_obj_tuple_t default_hid_devices_tuple = { + .base = { + .type = &mp_type_tuple, + }, + .len = 3, + .items = { + MP_OBJ_FROM_PTR(&usb_hid_device_keyboard_obj), + MP_OBJ_FROM_PTR(&usb_hid_device_mouse_obj), + MP_OBJ_FROM_PTR(&usb_hid_device_consumer_control_obj), + }, +}; + +// These describe the standard descriptors used for boot keyboard and mouse, +// which don't use report IDs. +static const usb_hid_device_obj_t boot_keyboard_obj = { + .base = { + .type = &usb_hid_device_type, + }, + .report_descriptor = NULL, + .report_descriptor_length = 0, + .usage_page = 0x01, + .usage = 0x06, + .num_report_ids = 1, + .report_ids = { 0, }, + .in_report_lengths = { 8, }, + .out_report_lengths = { 1, }, +}; + +static const usb_hid_device_obj_t boot_mouse_obj = { + .base = { + .type = &usb_hid_device_type, + }, + .report_descriptor = NULL, + .report_descriptor_length = 0, + .usage_page = 0x01, + .usage = 0x02, + .num_report_ids = 1, + .report_ids = { 0, }, + .in_report_lengths = { 4, }, + .out_report_lengths = { 0, }, +}; + +bool usb_hid_enabled(void) { + return num_hid_devices > 0; +} + +uint8_t usb_hid_boot_device(void) { + return hid_boot_device; +} + +// Returns 1 or 2 if host requested a boot device and boot protocol was enabled. +uint8_t common_hal_usb_hid_get_boot_device(void) { + return hid_boot_device_requested ? hid_boot_device : 0; +} + +void usb_hid_set_defaults(void) { + hid_boot_device = 0; + hid_boot_device_requested = false; + hid_interface_ready = false; + common_hal_usb_hid_enable( + CIRCUITPY_USB_HID_ENABLED_DEFAULT ? &default_hid_devices_tuple : mp_const_empty_tuple, 0); +} + +// Make up a fresh tuple containing the device objects saved in the static +// devices table. Save the tuple in usb_hid.devices. +static void usb_hid_set_devices_from_hid_devices(void) { + mp_obj_t tuple_items[num_hid_devices]; + for (mp_int_t i = 0; i < num_hid_devices; i++) { + tuple_items[i] = &hid_devices[i]; + } + hid_devices_tuple = mp_obj_new_tuple(num_hid_devices, tuple_items); + usb_hid_set_devices(hid_devices_tuple); +} + +bool common_hal_usb_hid_disable(void) { + return common_hal_usb_hid_enable(mp_const_empty_tuple, 0); +} + +bool common_hal_usb_hid_enable(const mp_obj_t devices, uint8_t boot_device) { + // We can't change the devices once USB is connected. + if (hid_interface_ready) { + return false; + } + + const mp_int_t num_devices = MP_OBJ_SMALL_INT_VALUE(mp_obj_len(devices)); + mp_arg_validate_length_max(num_devices, MAX_HID_DEVICES, MP_QSTR_devices); + + num_hid_devices = num_devices; + hid_boot_device = boot_device; + + // Remember the devices in static storage so they live across VMs. + for (mp_int_t i = 0; i < num_hid_devices; i++) { + usb_hid_device_obj_t *device = + MP_OBJ_TO_PTR(mp_obj_subscr(devices, MP_OBJ_NEW_SMALL_INT(i), MP_OBJ_SENTINEL)); + memcpy(&hid_devices[i], device, sizeof(usb_hid_device_obj_t)); + } + + usb_hid_set_devices_from_hid_devices(); + + return true; +} + +// Called when HID devices are ready to be used, when code.py or the REPL starts running. +void usb_hid_setup_devices(void) { + // If the host requested a boot device, replace the current list of devices + // with a single-element tuple containing the proper boot device. + if (hid_boot_device_requested) { + memcpy(&hid_devices[0], + hid_boot_device == 1 ? &boot_keyboard_obj : &boot_mouse_obj, + sizeof(usb_hid_device_obj_t)); + num_hid_devices = 1; + } + + usb_hid_set_devices_from_hid_devices(); + + // Create report buffers on the heap. + for (mp_int_t i = 0; i < num_hid_devices; i++) { + usb_hid_device_create_report_buffers(&hid_devices[i]); + } +} + +// Build the combined HID report descriptor from all devices. +static uint8_t *hid_report_descriptor = NULL; + +size_t usb_hid_report_descriptor_length(void) { + size_t total_hid_report_descriptor_length = 0; + for (mp_int_t i = 0; i < num_hid_devices; i++) { + total_hid_report_descriptor_length += hid_devices[i].report_descriptor_length; + } + return total_hid_report_descriptor_length; +} + +void usb_hid_build_report_descriptor(void) { + if (!usb_hid_enabled()) { + return; + } + size_t report_length = usb_hid_report_descriptor_length(); + hid_report_descriptor = port_malloc(report_length, false); + if (hid_report_descriptor == NULL) { + return; + } + + uint8_t *report_descriptor_start = hid_report_descriptor; + for (mp_int_t i = 0; i < num_hid_devices; i++) { + usb_hid_device_obj_t *device = &hid_devices[i]; + memcpy(report_descriptor_start, device->report_descriptor, device->report_descriptor_length); + report_descriptor_start += device->report_descriptor_length; + // Clear the heap pointer to the bytes of the descriptor. + device->report_descriptor = NULL; + } +} + +void usb_hid_gc_collect(void) { + gc_collect_ptr(hid_devices_tuple); + + for (mp_int_t device_idx = 0; device_idx < num_hid_devices; device_idx++) { + gc_collect_ptr((void *)hid_devices[device_idx].report_descriptor); + + for (size_t id_idx = 0; id_idx < hid_devices[device_idx].num_report_ids; id_idx++) { + gc_collect_ptr(hid_devices[device_idx].in_report_buffers[id_idx]); + gc_collect_ptr(hid_devices[device_idx].out_report_buffers[id_idx]); + } + } +} + +bool usb_hid_get_device_with_report_id(uint8_t report_id, usb_hid_device_obj_t **device_out, size_t *id_idx_out) { + for (uint8_t device_idx = 0; device_idx < num_hid_devices; device_idx++) { + usb_hid_device_obj_t *device = &hid_devices[device_idx]; + for (size_t id_idx = 0; id_idx < device->num_report_ids; id_idx++) { + if (device->report_ids[id_idx] == report_id) { + *device_out = device; + *id_idx_out = id_idx; + return true; + } + } + } + return false; +} + +// ===== Zephyr USBD HID Device Callbacks ===== + +static void hid_iface_ready(const struct device *dev, const bool ready) { + hid_interface_ready = ready; +} + +static int hid_get_report(const struct device *dev, + const uint8_t type, const uint8_t id, + const uint16_t len, uint8_t *const buf) { + // Support Input Report and Feature Report + if (type != HID_REPORT_TYPE_INPUT && type != HID_REPORT_TYPE_FEATURE) { + return -ENOTSUP; + } + + usb_hid_device_obj_t *hid_device; + size_t id_idx; + if (!usb_hid_get_device_with_report_id(id, &hid_device, &id_idx)) { + return 0; + } + if (!hid_device->in_report_buffers[id_idx]) { + return 0; + } + + uint8_t in_len = hid_device->in_report_lengths[id_idx]; + const uint8_t *src = hid_device->in_report_buffers[id_idx]; + + // When the descriptor uses Report IDs (id != 0), the on-wire report is + // prefixed with the Report ID byte. Zephyr sends the buffer verbatim, so + // prepend the ID here. id == 0 means no Report ID item -> no prefix. + if (id != 0) { + if (len == 0) { + return 0; + } + buf[0] = id; + uint16_t copy_len = len - 1; + if (copy_len > in_len) { + copy_len = in_len; + } + memcpy(&buf[1], src, copy_len); + return 1 + copy_len; + } + + uint16_t copy_len = len; + if (copy_len > in_len) { + copy_len = in_len; + } + memcpy(buf, src, copy_len); + return copy_len; +} + +static int hid_set_report(const struct device *dev, + const uint8_t type, const uint8_t id, + const uint16_t len, const uint8_t *const buf) { + uint8_t report_id = id; + const uint8_t *data = buf; + uint16_t data_len = len; + + if (report_id != 0 && len > 0) { + // Descriptor uses Report IDs: the on-wire SET_REPORT data stage is + // prefixed with the Report ID byte. Zephyr passes the raw payload, so + // strip the leading ID byte (it should match the id from wValue). + if (buf[0] == report_id) { + data = &buf[1]; + data_len = len - 1; + } + } else if (report_id == 0 && len > 0) { + // id==0 normally means no Report ID item (no prefix). But if no device + // has report ID 0 with a matching out length, treat the first byte as a + // report ID (host sent a prefixed report despite id==0). + usb_hid_device_obj_t *hid0 = NULL; + size_t idx0; + if (!(usb_hid_get_device_with_report_id(0, &hid0, &idx0) && + hid0 && hid0->out_report_buffers[idx0] && + hid0->out_report_lengths[idx0] == len)) { + report_id = buf[0]; + data = &buf[1]; + data_len = len - 1; + } + } + + // Look up the device for the resolved report_id. + usb_hid_device_obj_t *hid_device = NULL; + size_t id_idx; + if (!usb_hid_get_device_with_report_id(report_id, &hid_device, &id_idx)) { + return -EINVAL; + } + + if (hid_device->out_report_buffers[id_idx] && + hid_device->out_report_lengths[id_idx] == data_len) { + memcpy(hid_device->out_report_buffers[id_idx], data, data_len); + hid_device->out_report_buffers_updated[id_idx] = true; + return 0; + } + + return -EINVAL; +} + +static void hid_set_protocol(const struct device *dev, const uint8_t proto) { + hid_boot_device_requested = (proto == HID_PROTOCOL_BOOT); +} + +static struct hid_device_ops hid_ops = { + .iface_ready = hid_iface_ready, + .get_report = hid_get_report, + .set_report = hid_set_report, + .set_protocol = hid_set_protocol, +}; + +// ===== HID Device Registration ===== + +// Get the Zephyr HID device for submitting reports +static const struct device *hid_zephyr_dev; + +const struct device *usb_hid_get_zephyr_device(void) { + return hid_zephyr_dev; +} + +void usb_hid_init_devices(void) { + if (!usb_hid_enabled()) { + return; + } + + hid_zephyr_dev = DEVICE_DT_GET_ONE(zephyr_hid_device); + if (!device_is_ready(hid_zephyr_dev)) { + return; + } + + usb_hid_build_report_descriptor(); + if (hid_report_descriptor == NULL) { + return; + } + + int ret = hid_device_register(hid_zephyr_dev, + hid_report_descriptor, + usb_hid_report_descriptor_length(), + &hid_ops); + if (ret != 0) { + return; + } +} + +bool usb_hid_ready(void) { + return hid_zephyr_dev != NULL && hid_interface_ready; +} + +// Submit an input report through Zephyr's HID device. +// Called from common_hal_usb_hid_device_send_report(). +bool usb_hid_submit_report(uint8_t report_id, const uint8_t *report, uint8_t len) { + if (hid_zephyr_dev == NULL || !hid_interface_ready) { + return false; + } + + // Send report_id zero without a prefix + if (report_id == 0) { + return hid_device_submit_report(hid_zephyr_dev, len, report) == 0; + } + + uint8_t __attribute__((aligned(sizeof(void *)))) report_buffer[1 + len]; + report_buffer[0] = report_id; + memcpy(&report_buffer[1], report, len); + return hid_device_submit_report(hid_zephyr_dev, len + 1, report_buffer) == 0; +} diff --git a/ports/zephyr-cp/common-hal/usb_hid/__init__.h b/ports/zephyr-cp/common-hal/usb_hid/__init__.h new file mode 100644 index 00000000000..1985ea29549 --- /dev/null +++ b/ports/zephyr-cp/common-hal/usb_hid/__init__.h @@ -0,0 +1,28 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-module/usb_hid/Device.h" +#include "supervisor/usb.h" + +extern usb_hid_device_obj_t usb_hid_devices[]; + +bool usb_hid_enabled(void); +uint8_t usb_hid_boot_device(void); +void usb_hid_set_defaults(void); +void usb_hid_setup_devices(void); +size_t usb_hid_report_descriptor_length(void); +void usb_hid_build_report_descriptor(void); +bool usb_hid_get_device_with_report_id(uint8_t report_id, usb_hid_device_obj_t **device_out, size_t *id_idx_out); +void usb_hid_gc_collect(void); + +// For supervisor/usb.c integration +void usb_hid_init_devices(void); + +// For Device.c send_report +bool usb_hid_ready(void); +bool usb_hid_submit_report(uint8_t report_id, const uint8_t *report, uint8_t len); diff --git a/ports/zephyr-cp/common-hal/watchdog/WatchDogMode.c b/ports/zephyr-cp/common-hal/watchdog/WatchDogMode.c new file mode 100644 index 00000000000..b8225c3a217 --- /dev/null +++ b/ports/zephyr-cp/common-hal/watchdog/WatchDogMode.c @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +// No watchdog module functions. diff --git a/ports/zephyr-cp/common-hal/watchdog/WatchDogTimer.c b/ports/zephyr-cp/common-hal/watchdog/WatchDogTimer.c new file mode 100644 index 00000000000..750dd90c0d7 --- /dev/null +++ b/ports/zephyr-cp/common-hal/watchdog/WatchDogTimer.c @@ -0,0 +1,303 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#include "py/runtime.h" + +#include "shared-bindings/watchdog/__init__.h" +#include "shared-bindings/watchdog/WatchDogMode.h" +#include "shared-bindings/microcontroller/__init__.h" + +#include "common-hal/watchdog/WatchDogTimer.h" + +#include "bindings/zephyr_kernel/__init__.h" + +#include "supervisor/background_callback.h" +#include "supervisor/port.h" + +#include +#include +#include +#include +#include +#include + +// Register the CircuitPython watchdog port code as its own Zephyr log module +// but share the WDT module's log level (CONFIG_WDT_LOG_LEVEL, set to DBG via +// CONFIG_WDT_LOG_LEVEL_DBG=y), so driver and port logs turn on together. +LOG_MODULE_REGISTER(cp_watchdog, CONFIG_WDT_LOG_LEVEL); + +// The hardware watchdog device, when the board provides one, is selected by +// the devicetree `watchdog0` alias (the same selection Zephyr's own watchdog +// sample, samples/drivers/watchdog, uses). RAISE mode works on every board via +// the software timer; only RESET mode needs the hardware device, so the alias +// is optional and boards without it raise NotImplementedError when RESET is +// requested. Use status-okay rather than node-exists so that boards which +// deliberately disable the alias target (e.g. Renesas RA boards, where the RA +// WDT driver doesn't build) still compile; a disabled node has no device +// struct, so DEVICE_DT_GET would fail for it. +#if DT_NODE_EXISTS(DT_ALIAS(watchdog0)) && DT_NODE_HAS_STATUS_OKAY(DT_ALIAS(watchdog0)) +#define CP_WDT_HAS_HW 1 +static const struct device *const wdt_dev = DEVICE_DT_GET(DT_ALIAS(watchdog0)); +#else +#define CP_WDT_HAS_HW 0 +static const struct device *const wdt_dev = NULL; +#endif + +static background_callback_t wdt_timeout_callback; + +// Raises the WatchDogTimeout exception in thread context. Runs from the +// background callback machinery after the watchdog's interrupt callback fed +// the hardware, so the VM state is never touched from interrupt context. +// DEBUG leds used to prove which watchdog paths actually run on hardware. +// Only compiled when the board's devicetree provides both led0 and led1 +// (native_sim, e.g., only has led0). +#if DT_NODE_EXISTS(DT_NODELABEL(led0)) && DT_NODE_EXISTS(DT_NODELABEL(led1)) +#define CP_WDT_DEBUG_LEDS 1 +#else +#define CP_WDT_DEBUG_LEDS 0 +#endif + +#if CP_WDT_DEBUG_LEDS +static const struct gpio_dt_spec debug_led_red = GPIO_DT_SPEC_GET(DT_NODELABEL(led0), gpios); +static const struct gpio_dt_spec debug_led_blue = GPIO_DT_SPEC_GET(DT_NODELABEL(led1), gpios); + +// Red LED ON: the raise timer expired in ISR context. Blue LED ON: the +// thread-context raise ran. +static void debug_isr_mark(void) { + gpio_pin_set_dt(&debug_led_red, 1); +} + +static void debug_thread_mark(void) { + gpio_pin_set_dt(&debug_led_blue, 1); +} +#else +static void debug_isr_mark(void) { +} + +static void debug_thread_mark(void) { +} +#endif + +static void wdt_raise_in_thread(void *unused) { + debug_thread_mark(); + LOG_DBG("raise WatchDogTimeout in thread context"); + + mp_obj_exception_clear_traceback(MP_OBJ_FROM_PTR(&mp_watchdog_timeout_exception)); + MP_STATE_THREAD(mp_pending_exception) = &mp_watchdog_timeout_exception; + #if MICROPY_ENABLE_SCHEDULER + if (MP_STATE_VM(sched_state) == MP_SCHED_IDLE) { + MP_STATE_VM(sched_state) = MP_SCHED_PENDING; + } + #endif +} + +// k_timer expiry, runs from the system clock timer ISR. Schedule the +// WatchDogTimeout raise in thread context via the background callback, which +// also wakes the VM task if it is idle. There is nothing to feed: the timer +// just stops on its own until the next k_timer_start(). +static void wdt_raise_timer_expiry(struct k_timer *unused) { + // LOG_* calls are ISR-safe in deferred logging mode (CONFIG_LOG_MODE_DEFERRED=y). + debug_isr_mark(); + LOG_DBG("raise timer expired, scheduling thread raise"); + + watchdog_watchdogtimer_obj_t *self = &common_hal_mcu_watchdogtimer_obj; + self->mode = WATCHDOGMODE_NONE; + + background_callback_add(&wdt_timeout_callback, wdt_raise_in_thread, NULL); +} + +// Static definition includes the k_timer_start()-installed expiry function. +K_TIMER_DEFINE(wdt_raise_timer, wdt_raise_timer_expiry, NULL); + +// Install the timeout for the current mode and start the watchdog. For RAISE +// mode (software timer) restarting while running is fine; for RESET mode +// (hardware WDT) the watchdog must not be running (timeouts are installed +// before wdt_setup()). +static void watchdog_install(watchdog_watchdogtimer_obj_t *self) { + // DEBUG: configure the status LEDs as outputs so the marks are visible. + #if CP_WDT_DEBUG_LEDS + gpio_pin_configure_dt(&debug_led_red, GPIO_OUTPUT_ACTIVE); + gpio_pin_configure_dt(&debug_led_blue, GPIO_OUTPUT_ACTIVE); + gpio_pin_set_dt(&debug_led_red, 0); + gpio_pin_set_dt(&debug_led_blue, 0); + #endif + + // Zephyr's watchdog API is millisecond based, shared with CircuitPython's + // float seconds through this window. + uint32_t timeout_ms = (uint32_t)(self->timeout * 1000); + + if (self->mode == WATCHDOGMODE_RAISE) { + // Nordic's WDT (and other hardware watchdogs) reset unconditionally + // a few LFCLK cycles after the timeout event, callback or not, and + // feeding cannot cancel that reset (nRF54 product spec). So RAISE + // mode never touches the hardware watchdog: a Zephyr k_timer armed + // with the timeout raises the exception instead, exactly what the + // nordic port does with a TIMER peripheral. RESET mode keeps the + // true hardware watchdog. + LOG_DBG("raise mode: starting software timer for %u ms", timeout_ms); + k_timer_start(&wdt_raise_timer, K_MSEC(timeout_ms), K_NO_WAIT); + self->channel_id = -1; + return; + } + + // WATCHDOGMODE_RESET: no callback, reset the SoC on expiry. window.min is + // left at 0, which drivers without feed windows require. + if (!device_is_ready(wdt_dev)) { + raise_zephyr_error(-ENODEV); + } + LOG_DBG("reset mode: installing hardware WDT with %u ms timeout", timeout_ms); + struct wdt_timeout_cfg cfg = { + .window.min = 0, + .window.max = timeout_ms, + .callback = NULL, + .flags = WDT_FLAG_RESET_SOC, + }; + int channel_id = wdt_install_timeout(wdt_dev, &cfg); + CHECK_ZEPHYR_RESULT(channel_id); + + self->channel_id = channel_id; + CHECK_ZEPHYR_RESULT(wdt_setup(wdt_dev, 0)); + // Start the first timeout period. + CHECK_ZEPHYR_RESULT(wdt_feed(wdt_dev, channel_id)); +} + +void common_hal_watchdog_feed(watchdog_watchdogtimer_obj_t *self) { + if (self->mode == WATCHDOGMODE_NONE) { + return; + } + if (self->mode == WATCHDOGMODE_RAISE) { + // Restart the timer: k_timer_start() on a running timer discards the + // time already elapsed and arms the full period again. + LOG_DBG("RAISE mode feed: restarting software timer for %u ms", + (uint32_t)(self->timeout * 1000)); + k_timer_start(&wdt_raise_timer, + K_MSEC((uint32_t)(self->timeout * 1000)), K_NO_WAIT); + return; + } + int err = wdt_feed(wdt_dev, self->channel_id); + if (err != 0) { + LOG_ERR("feed failed: %d", err); + } + CHECK_ZEPHYR_RESULT(err); +} + +// Stop the watchdog if the implementation allows it, leaving the mode state +// untouched when it doesn't (some hardware, like STM32's IWDG, can't be +// disabled once started). `mode = None` is the only Python-facing way to stop +// the watchdog since watchdog.deinit() was removed in 10.0.0. +static void watchdog_stop(watchdog_watchdogtimer_obj_t *self) { + if (self->mode == WATCHDOGMODE_NONE) { + return; + } + if (self->mode == WATCHDOGMODE_RAISE) { + LOG_DBG("stopping software raise timer"); + k_timer_stop(&wdt_raise_timer); + self->channel_id = -1; + self->mode = WATCHDOGMODE_NONE; + return; + } + LOG_DBG("disabling hardware WDT"); + if (!device_is_ready(wdt_dev) || wdt_disable(wdt_dev) < 0) { + LOG_WRN("hw watchdog not stoppable; keeps running"); + return; + } + self->channel_id = -1; + self->mode = WATCHDOGMODE_NONE; +} + +void common_hal_watchdog_reset(watchdog_watchdogtimer_obj_t *self) { + watchdog_stop(self); +} + +mp_float_t common_hal_watchdog_get_timeout(watchdog_watchdogtimer_obj_t *self) { + return self->timeout; +} + +void common_hal_watchdog_set_timeout(watchdog_watchdogtimer_obj_t *self, mp_float_t new_timeout) { + // Zephyr's API takes the timeout in milliseconds through a uint32_t. + mp_arg_validate_int_max((mp_int_t)new_timeout, UINT32_MAX / 1000, MP_QSTR_timeout); + self->timeout = new_timeout; + + if (self->mode == WATCHDOGMODE_NONE) { + return; + } + + if (self->mode == WATCHDOGMODE_RAISE) { + // For the software timer a restart with the new value is enough. + watchdog_install(self); + return; + } + + // Zephyr only accepts new timeout configurations while the hardware + // watchdog is stopped. A hardware watchdog that can't be stopped keeps + // running with the old configuration (same failure mode as failing + // watchdog_stop()). + int err = wdt_disable(wdt_dev); + if (err != 0) { + LOG_WRN("wdt_disable failed: %d; cannot install new timeout, watchdog " + "keeps running with the old configuration", err); + } + CHECK_ZEPHYR_RESULT(err); + self->channel_id = -1; + + watchdog_install(self); +} + +watchdog_watchdogmode_t common_hal_watchdog_get_mode(watchdog_watchdogtimer_obj_t *self) { + return self->mode; +} + +void common_hal_watchdog_set_mode(watchdog_watchdogtimer_obj_t *self, watchdog_watchdogmode_t new_mode) { + watchdog_watchdogmode_t current_mode = self->mode; + if (new_mode == current_mode) { + return; + } + + if (new_mode == WATCHDOGMODE_NONE) { + watchdog_stop(self); + return; + } + + if (new_mode != WATCHDOGMODE_RAISE && new_mode != WATCHDOGMODE_RESET) { + return; + } + + if (new_mode == WATCHDOGMODE_RESET) { + // RESET mode needs the hardware watchdog: it must reset a locked-up + // system, which no software timer can do. RAISE mode works on every + // board; boards without a watchdog0 alias only support RAISE. + #if CP_WDT_HAS_HW + if (!device_is_ready(wdt_dev)) { + raise_zephyr_error(-ENODEV); + } + #else + mp_raise_NotImplementedError(NULL); + #endif + } + + if (current_mode != WATCHDOGMODE_NONE) { + // Bring down the previous implementation. The software timer always + // stops; a hardware watchdog only stops when the driver allows it. + // Bringing a hardware watchdog down isn't always possible, and a + // failure there leaves it running with the old configuration. + if (current_mode == WATCHDOGMODE_RAISE) { + k_timer_stop(&wdt_raise_timer); + LOG_DBG("stopped software raise timer for mode switch"); + } else { + int err = wdt_disable(wdt_dev); + if (err != 0) { + LOG_WRN("wdt_disable failed: %d; watchdog keeps running with " + "the old configuration", err); + } + CHECK_ZEPHYR_RESULT(err); + } + } + self->channel_id = -1; + + self->mode = new_mode; + + watchdog_install(self); +} diff --git a/ports/zephyr-cp/common-hal/watchdog/WatchDogTimer.h b/ports/zephyr-cp/common-hal/watchdog/WatchDogTimer.h new file mode 100644 index 00000000000..736bb64267e --- /dev/null +++ b/ports/zephyr-cp/common-hal/watchdog/WatchDogTimer.h @@ -0,0 +1,28 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +#include "shared-module/watchdog/__init__.h" + +#include "shared-bindings/watchdog/WatchDogMode.h" +#include "shared-bindings/watchdog/WatchDogTimer.h" + +// The watchdog device is selected by the devicetree `watchdog0` alias, the +// same selection Zephyr's own watchdog sample uses. The module is only +// enabled (CIRCUITPY_WATCHDOG=1) when the alias exists and CONFIG_WATCHDOG is +// on (see cptools/zephyr2cp.py), so DEVICE_DT_GET(DT_ALIAS(watchdog0)) in +// WatchDogTimer.c always resolves. +struct _watchdog_watchdogtimer_obj_t { + mp_obj_base_t base; + mp_float_t timeout; + watchdog_watchdogmode_t mode; + // The timeout channel installed with wdt_install_timeout(), or -1 when + // the watchdog isn't running. + int channel_id; +}; diff --git a/ports/zephyr-cp/common-hal/watchdog/__init__.c b/ports/zephyr-cp/common-hal/watchdog/__init__.c new file mode 100644 index 00000000000..b8225c3a217 --- /dev/null +++ b/ports/zephyr-cp/common-hal/watchdog/__init__.c @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +// No watchdog module functions. diff --git a/ports/zephyr-cp/common-hal/wifi/Monitor.c b/ports/zephyr-cp/common-hal/wifi/Monitor.c index 7cacb8b520a..cca7ebd2174 100644 --- a/ports/zephyr-cp/common-hal/wifi/Monitor.c +++ b/ports/zephyr-cp/common-hal/wifi/Monitor.c @@ -54,6 +54,9 @@ typedef struct { // } void common_hal_wifi_monitor_construct(wifi_monitor_obj_t *self, uint8_t channel, size_t queue) { + // Monitor mode isn't implemented yet; the rest of this file is a stub. + mp_raise_NotImplementedError(NULL); + // mp_rom_error_text_t monitor_mode_init_error = MP_ERROR_TEXT("monitor init failed"); // self->queue = xQueueCreate(queue, sizeof(monitor_packet_t)); @@ -76,14 +79,14 @@ void common_hal_wifi_monitor_construct(wifi_monitor_obj_t *self, uint8_t channel // self->queue_length = queue; } -bool common_hal_wifi_monitor_deinited(void) { +bool common_hal_wifi_monitor_deinited(wifi_monitor_obj_t *self) { // bool enabled; // return (esp_wifi_get_promiscuous(&enabled) == ESP_ERR_WIFI_NOT_INIT) ? true : !enabled; return true; } void common_hal_wifi_monitor_deinit(wifi_monitor_obj_t *self) { - if (common_hal_wifi_monitor_deinited()) { + if (common_hal_wifi_monitor_deinited(self)) { return; } diff --git a/ports/zephyr-cp/common-hal/wifi/Network.c b/ports/zephyr-cp/common-hal/wifi/Network.c index 44c049f88c1..dad9293a149 100644 --- a/ports/zephyr-cp/common-hal/wifi/Network.c +++ b/ports/zephyr-cp/common-hal/wifi/Network.c @@ -6,6 +6,8 @@ #include +#include "py/objlist.h" + #include "shared-bindings/wifi/Network.h" #include "shared-bindings/wifi/AuthMode.h" @@ -34,35 +36,44 @@ mp_obj_t common_hal_wifi_network_get_country(wifi_network_obj_t *self) { } mp_obj_t common_hal_wifi_network_get_authmode(wifi_network_obj_t *self) { + // Translate Zephyr's wifi_security_type. An empty list would read as an + // open network to any caller checking for AUTHMODE_OPEN. uint32_t authmode_mask = 0; - // switch (self->record.authmode) { - // case WIFI_AUTH_OPEN: - // authmode_mask = AUTHMODE_OPEN; - // break; - // case WIFI_AUTH_WEP: - // authmode_mask = AUTHMODE_WEP; - // break; - // case WIFI_AUTH_WPA_PSK: - // authmode_mask = AUTHMODE_WPA | AUTHMODE_PSK; - // break; - // case WIFI_AUTH_WPA2_PSK: - // authmode_mask = AUTHMODE_WPA2 | AUTHMODE_PSK; - // break; - // case WIFI_AUTH_WPA_WPA2_PSK: - // authmode_mask = AUTHMODE_WPA | AUTHMODE_WPA2 | AUTHMODE_PSK; - // break; - // case WIFI_AUTH_WPA2_ENTERPRISE: - // authmode_mask = AUTHMODE_WPA2 | AUTHMODE_ENTERPRISE; - // break; - // case WIFI_AUTH_WPA3_PSK: - // authmode_mask = AUTHMODE_WPA3 | AUTHMODE_PSK; - // break; - // case WIFI_AUTH_WPA2_WPA3_PSK: - // authmode_mask = AUTHMODE_WPA2 | AUTHMODE_WPA3 | AUTHMODE_PSK; - // break; - // default: - // break; - // } + switch (self->scan_result.security) { + case WIFI_SECURITY_TYPE_NONE: + authmode_mask = AUTHMODE_OPEN; + break; + case WIFI_SECURITY_TYPE_WEP: + authmode_mask = AUTHMODE_WEP; + break; + case WIFI_SECURITY_TYPE_WPA_PSK: + authmode_mask = AUTHMODE_WPA | AUTHMODE_PSK; + break; + case WIFI_SECURITY_TYPE_PSK: + case WIFI_SECURITY_TYPE_PSK_SHA256: + authmode_mask = AUTHMODE_WPA2 | AUTHMODE_PSK; + break; + case WIFI_SECURITY_TYPE_SAE: // == WIFI_SECURITY_TYPE_SAE_HNP (alias) + case WIFI_SECURITY_TYPE_SAE_H2E: + case WIFI_SECURITY_TYPE_SAE_AUTO: + case WIFI_SECURITY_TYPE_SAE_EXT_KEY: + case WIFI_SECURITY_TYPE_FT_SAE: + authmode_mask = AUTHMODE_WPA3 | AUTHMODE_PSK; + break; + case WIFI_SECURITY_TYPE_WPA_AUTO_PERSONAL: + authmode_mask = AUTHMODE_WPA | AUTHMODE_WPA2 | AUTHMODE_WPA3 | AUTHMODE_PSK; + break; + case WIFI_SECURITY_TYPE_EAP: // == WIFI_SECURITY_TYPE_EAP_TLS (alias) + case WIFI_SECURITY_TYPE_EAP_PEAP_MSCHAPV2: + case WIFI_SECURITY_TYPE_EAP_PEAP_GTC: + case WIFI_SECURITY_TYPE_EAP_TTLS_MSCHAPV2: + case WIFI_SECURITY_TYPE_EAP_PEAP_TLS: + case WIFI_SECURITY_TYPE_FT_EAP: + authmode_mask = AUTHMODE_WPA2 | AUTHMODE_ENTERPRISE; + break; + default: + break; + } mp_obj_t authmode_list = mp_obj_new_list(0, NULL); if (authmode_mask != 0) { for (uint8_t i = 0; i < 32; i++) { diff --git a/ports/zephyr-cp/common-hal/wifi/Radio.c b/ports/zephyr-cp/common-hal/wifi/Radio.c index fe053b6f60e..17d6506f410 100644 --- a/ports/zephyr-cp/common-hal/wifi/Radio.c +++ b/ports/zephyr-cp/common-hal/wifi/Radio.c @@ -5,6 +5,7 @@ // SPDX-License-Identifier: MIT #include "shared-bindings/wifi/Radio.h" +#include "shared-bindings/wifi/__init__.h" #include "ports/zephyr-cp/common-hal/wifi/ScannedNetworks.h" #include "shared-bindings/wifi/Network.h" @@ -25,14 +26,25 @@ #include "bindings/zephyr_kernel/__init__.h" #include +#include +#include +// dns_resolve_get_default() for radio.ipv4_dns. +#include #include +#if CIRCUITPY_WIFI_PING +// net_icmp_* for radio.ping(). +#include +#endif #include #include +#include #if CIRCUITPY_MDNS #include "common-hal/mdns/Server.h" #endif +LOG_MODULE_DECLARE(cp_wifi); + #define MAC_ADDRESS_LENGTH 6 // static void set_mode_station(wifi_radio_obj_t *self, bool state) { @@ -85,14 +97,20 @@ void common_hal_wifi_radio_set_enabled(wifi_radio_obj_t *self, bool enabled) { // #if CIRCUITPY_MDNS // mdns_server_deinit_singleton(); // #endif - printk("net_if_down\n"); - CHECK_ZEPHYR_RESULT(net_if_down(self->sta_netif)); + LOG_DBG("net_if_down"); + int res = net_if_down(self->sta_netif); + if (res < 0 && res != -EALREADY) { + raise_zephyr_error(res); + } self->started = false; return; } if (!self->started && enabled) { - printk("net_if_up\n"); - CHECK_ZEPHYR_RESULT(net_if_up(self->sta_netif)); + LOG_DBG("net_if_up"); + int res = net_if_up(self->sta_netif); + if (res < 0 && res != -EALREADY) { + raise_zephyr_error(res); + } self->started = true; self->current_scan = NULL; // common_hal_wifi_radio_set_tx_power(self, CIRCUITPY_WIFI_DEFAULT_TX_POWER); @@ -100,6 +118,11 @@ void common_hal_wifi_radio_set_enabled(wifi_radio_obj_t *self, bool enabled) { } } +mp_obj_t common_hal_wifi_radio_get_version(wifi_radio_obj_t *self) { + // No WiFi co-processor version is reported on this port yet. + return mp_const_none; +} + mp_obj_t common_hal_wifi_radio_get_hostname(wifi_radio_obj_t *self) { const char *hostname = net_hostname_get(); return mp_obj_new_str(hostname, strlen(hostname)); @@ -111,9 +134,18 @@ void common_hal_wifi_radio_set_hostname(wifi_radio_obj_t *self, const char *host } } +const char *wifi_get_hostname_raw(void) { + return net_hostname_get(); +} + mp_obj_t common_hal_wifi_radio_get_mac_address(wifi_radio_obj_t *self) { - uint8_t mac[MAC_ADDRESS_LENGTH]; - // esp_wifi_get_mac(ESP_IF_WIFI_STA, mac); + uint8_t mac[MAC_ADDRESS_LENGTH] = { 0 }; + if (self->sta_netif != NULL) { + struct net_linkaddr *addr = net_if_get_link_addr(self->sta_netif); + if (addr != NULL && addr->len >= MAC_ADDRESS_LENGTH) { + memcpy(mac, addr->addr, MAC_ADDRESS_LENGTH); + } + } return mp_obj_new_bytes(mac, MAC_ADDRESS_LENGTH); } @@ -137,10 +169,44 @@ void common_hal_wifi_radio_set_tx_power(wifi_radio_obj_t *self, const mp_float_t // esp_wifi_set_max_tx_power(tx_power * 4.0f); } -mp_int_t common_hal_wifi_radio_get_listen_interval(wifi_radio_obj_t *self) { - // wifi_config_t *config = &self->sta_config; - // return config->sta.listen_interval; - return 0; +wifi_power_management_t common_hal_wifi_radio_get_power_management(wifi_radio_obj_t *self) { + // wifi_ps_type_t ps; + // esp_err_t ret = esp_wifi_get_ps(&ps); + // if (ret == ESP_OK) { + // switch (ps) { + // case WIFI_PS_MIN_MODEM: + // return POWER_MANAGEMENT_MIN; + // case WIFI_PS_MAX_MODEM: + // return POWER_MANAGEMENT_MAX; + // case WIFI_PS_NONE: + // return POWER_MANAGEMENT_NONE; + // } + // } + return POWER_MANAGEMENT_UNKNOWN; +} + + +void common_hal_wifi_radio_set_power_management(wifi_radio_obj_t *self, wifi_power_management_t power_management) { + // switch (power_management) { + // case POWER_MANAGEMENT_MIN: + // esp_wifi_set_ps(WIFI_PS_MIN_MODEM); + // break; + // case POWER_MANAGEMENT_MAX: { + // // listen_interval is only used in this case. + // wifi_config_t *config = &self->sta_config; + // // This is a typical value seen in various examples. + // config->sta.listen_interval = 3; + // esp_wifi_set_ps(WIFI_PS_MAX_MODEM); + // esp_wifi_set_config(ESP_IF_WIFI_STA, config); + // } + // break; + // case POWER_MANAGEMENT_NONE: + // esp_wifi_set_ps(WIFI_PS_NONE); + // break; + // case POWER_MANAGEMENT_UNKNOWN: + // // This should be prevented in shared-bindings. + // break; + // } } void common_hal_wifi_radio_set_listen_interval(wifi_radio_obj_t *self, const mp_int_t listen_interval) { @@ -174,14 +240,12 @@ void common_hal_wifi_radio_set_mac_address_ap(wifi_radio_obj_t *self, const uint } mp_obj_t common_hal_wifi_radio_start_scanning_networks(wifi_radio_obj_t *self, uint8_t start_channel, uint8_t stop_channel) { - printk("common_hal_wifi_radio_start_scanning_networks\n"); + LOG_DBG("common_hal_wifi_radio_start_scanning_networks"); if (self->current_scan != NULL) { - printk("Already scanning for wifi networks\n"); mp_raise_RuntimeError(MP_ERROR_TEXT("Already scanning for wifi networks")); } if (!common_hal_wifi_radio_get_enabled(self)) { - printk("wifi is not enabled\n"); - mp_raise_RuntimeError(MP_ERROR_TEXT("wifi is not enabled")); + mp_raise_RuntimeError(MP_ERROR_TEXT("WiFi is not enabled")); } wifi_scannednetworks_obj_t *scan = mp_obj_malloc(wifi_scannednetworks_obj_t, &wifi_scannednetworks_type); @@ -206,12 +270,12 @@ mp_obj_t common_hal_wifi_radio_start_scanning_networks(wifi_radio_obj_t *self, u K_POLL_MODE_NOTIFY_ONLY, &scan->msgq); wifi_scannednetworks_scan_next_channel(scan); - printk("common_hal_wifi_radio_start_scanning_networks done %p\n", scan); + LOG_DBG("common_hal_wifi_radio_start_scanning_networks done %p", scan); return scan; } void common_hal_wifi_radio_stop_scanning_networks(wifi_radio_obj_t *self) { - printk("common_hal_wifi_radio_stop_scanning_networks\n"); + LOG_DBG("common_hal_wifi_radio_stop_scanning_networks"); // Return early if self->current_scan is NULL to avoid hang if (self->current_scan == NULL) { return; @@ -315,7 +379,7 @@ mp_obj_t common_hal_wifi_radio_get_stations_ap(wifi_radio_obj_t *self) { 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(MP_ERROR_TEXT("wifi is not enabled")); + mp_raise_RuntimeError(MP_ERROR_TEXT("WiFi is not enabled")); } // wifi_config_t *config = &self->sta_config; @@ -416,17 +480,170 @@ wifi_radio_error_t common_hal_wifi_radio_connect(wifi_radio_obj_t *self, uint8_t // // We're connected, allow us to retry if we get disconnected. // self->retries_left = self->starting_retries; // } + + struct wifi_connect_req_params params = { 0 }; + + params.ssid = ssid; + params.ssid_length = ssid_len; + params.band = WIFI_FREQ_BAND_2_4_GHZ; + params.channel = channel == 0 ? WIFI_CHANNEL_ANY : channel; + params.mfp = WIFI_MFP_OPTIONAL; + params.timeout = SYS_FOREVER_MS; + + if (password_len > 0) { + params.psk = password; + params.psk_length = password_len; + // WPA_AUTO_PERSONAL lets the driver settle on WPA2 or WPA3 with the AP + // rather than us guessing: it maps to WPA3-transition, which an AP in + // either mode accepts. WIFI_SECURITY_TYPE_UNKNOWN is not an option, the + // driver rejects it with -ENOTSUP. + params.security = WIFI_SECURITY_TYPE_WPA_AUTO_PERSONAL; + } else { + params.security = WIFI_SECURITY_TYPE_NONE; + } + + if (bssid_len == WIFI_MAC_ADDR_LEN) { + memcpy(params.bssid, bssid, WIFI_MAC_ADDR_LEN); + } + + // Already associated to the network being asked for: leave the link alone. + // supervisor_start_web_workflow() calls connect() on every invocation, so + // tearing the association down here would churn the link continuously. + if (self->connected && + ssid_len == self->current_ssid_len && + memcmp(ssid, self->current_ssid, ssid_len) == 0) { + return WIFI_RADIO_ERROR_NONE; + } + + // Switching networks. Connecting while associated returns -EALREADY and the + // failure path takes the interface down, so disconnect first. + if (self->connected) { + // A failure here is tolerated on purpose: if the interface really is + // unusable, the connect below returns a proper error to the caller. + (void)net_mgmt(NET_REQUEST_WIFI_DISCONNECT, self->sta_netif, NULL, 0); + // Give the controller a moment to tear the association down. + for (int i = 0; i < 40 && self->connected; i++) { + RUN_BACKGROUND_TASKS; + k_msleep(50); + } + self->connected = false; + } + + self->connected = false; + self->last_connect_status = -1; + self->last_disconnect_reason = 0; + k_sem_reset(&self->connect_sem); + + int res = net_mgmt(NET_REQUEST_WIFI_CONNECT, self->sta_netif, ¶ms, sizeof(params)); + if (res == -EALREADY) { + // Record the SSID as the success path does, so the early return above + // matches on a later connect() to the same network. + self->connected = true; + self->current_ssid_len = MIN(ssid_len, sizeof(self->current_ssid)); + memcpy(self->current_ssid, ssid, self->current_ssid_len); + return WIFI_RADIO_ERROR_NONE; + } + if (res < 0) { + return WIFI_RADIO_ERROR_UNSPECIFIED; + } + + // Wait for NET_EVENT_WIFI_CONNECT_RESULT (or a DISCONNECT_RESULT standing + // in for a failed attempt), staying responsive to ctrl-C. + mp_float_t timeout_s = timeout <= 0 ? (mp_float_t)10 : timeout; + int64_t deadline = k_uptime_get() + (int64_t)(timeout_s * 1000); + bool signalled = false; + while (k_uptime_get() < deadline) { + RUN_BACKGROUND_TASKS; + if (k_sem_take(&self->connect_sem, K_MSEC(50)) == 0) { + signalled = true; + break; + } + if (mp_hal_is_interrupted()) { + return WIFI_RADIO_ERROR_UNSPECIFIED; + } + } + + if (!signalled) { + return WIFI_RADIO_ERROR_HANDSHAKE_TIMEOUT; + } + if (!self->connected) { + switch (self->last_connect_status) { + case WIFI_STATUS_CONN_WRONG_PASSWORD: + return WIFI_RADIO_ERROR_AUTH_FAIL; + case WIFI_STATUS_CONN_AP_NOT_FOUND: + return WIFI_RADIO_ERROR_NO_AP_FOUND; + case WIFI_STATUS_CONN_TIMEOUT: + return WIFI_RADIO_ERROR_HANDSHAKE_TIMEOUT; + default: + return WIFI_RADIO_ERROR_CONNECTION_FAIL; + } + } + + // Remember which network this association is for, so a later connect() for + // the same SSID can return without disturbing it. + self->current_ssid_len = MIN(ssid_len, sizeof(self->current_ssid)); + memcpy(self->current_ssid, ssid, self->current_ssid_len); + + // Associated. Ask for an address; the AP side of DHCP can take a moment. + #if defined(CONFIG_NET_DHCPV4) + net_dhcpv4_start(self->sta_netif); + int64_t ip_deadline = k_uptime_get() + 15000; + while (k_uptime_get() < ip_deadline) { + if (net_if_ipv4_get_global_addr(self->sta_netif, NET_ADDR_PREFERRED) != NULL) { + break; + } + if (mp_hal_is_interrupted()) { + break; + } + RUN_BACKGROUND_TASKS; + k_msleep(50); + } + #endif + return WIFI_RADIO_ERROR_NONE; } bool common_hal_wifi_radio_get_connected(wifi_radio_obj_t *self) { - // return self->sta_mode && esp_netif_is_netif_up(self->netif); - return false; + return self->connected && self->sta_netif != NULL && + net_if_is_up(self->sta_netif); } mp_obj_t common_hal_wifi_radio_get_ap_info(wifi_radio_obj_t *self) { - // if (!esp_netif_is_netif_up(self->netif)) { - return mp_const_none; + if (self->sta_netif == NULL || !self->connected) { + return mp_const_none; + } + + // NET_REQUEST_WIFI_IFACE_STATUS carries everything a wifi.Network needs, so + // this reports the live association without spending a scan on it. + struct wifi_iface_status status = { 0 }; + if (net_mgmt(NET_REQUEST_WIFI_IFACE_STATUS, self->sta_netif, + &status, sizeof(status)) != 0) { + return mp_const_none; + } + + // Associated is the weakest state that has a meaningful BSSID and RSSI. + if (status.state < WIFI_STATE_ASSOCIATED) { + return mp_const_none; + } + + // wifi.Network wraps a scan result, so translate the status into one. + wifi_network_obj_t *ap_info = mp_obj_malloc(wifi_network_obj_t, &wifi_network_type); + size_t ssid_len = MIN(status.ssid_len, sizeof(ap_info->scan_result.ssid) - 1); + memcpy(ap_info->scan_result.ssid, status.ssid, ssid_len); + ap_info->scan_result.ssid[ssid_len] = '\0'; + ap_info->scan_result.ssid_length = ssid_len; + memcpy(ap_info->scan_result.mac, status.bssid, WIFI_MAC_ADDR_LEN); + ap_info->scan_result.mac_length = WIFI_MAC_ADDR_LEN; + ap_info->scan_result.band = status.band; + ap_info->scan_result.channel = status.channel; + ap_info->scan_result.security = status.security; + ap_info->scan_result.wpa3_ent_type = status.wpa3_ent_type; + ap_info->scan_result.mfp = status.mfp; + // status.rssi is int, scan_result.rssi is int8_t. Clamp, since a truncated + // value would wrap to a positive dBm. + ap_info->scan_result.rssi = (int8_t)MIN(MAX(status.rssi, INT8_MIN), INT8_MAX); + return MP_OBJ_FROM_PTR(ap_info); + // } // // Make sure the interface is in STA mode @@ -459,11 +676,23 @@ mp_obj_t common_hal_wifi_radio_get_ap_info(wifi_radio_obj_t *self) { } mp_obj_t common_hal_wifi_radio_get_ipv4_gateway(wifi_radio_obj_t *self) { - // if (!esp_netif_is_netif_up(self->netif)) { + if (self->sta_netif == NULL || !net_if_is_up(self->sta_netif)) { + return mp_const_none; + } + // net_if_ip.ipv4 only exists with CONFIG_NET_IPV4, and this file builds for + // every Wi-Fi board in the port, not just ones that enable it. + #if defined(CONFIG_NET_IPV4) + const struct net_if_config *cfg = net_if_get_config(self->sta_netif); + if (cfg == NULL || cfg->ip.ipv4 == NULL) { + return mp_const_none; + } + if (cfg->ip.ipv4->gw.s_addr == 0) { + return mp_const_none; + } + return common_hal_ipaddress_new_ipv4address(cfg->ip.ipv4->gw.s_addr); + #else return mp_const_none; - // } - // esp_netif_get_ip_info(self->netif, &self->ip_info); - // return common_hal_ipaddress_new_ipv4address(self->ip_info.gw.addr); + #endif } mp_obj_t common_hal_wifi_radio_get_ipv4_gateway_ap(wifi_radio_obj_t *self) { @@ -475,11 +704,24 @@ mp_obj_t common_hal_wifi_radio_get_ipv4_gateway_ap(wifi_radio_obj_t *self) { } mp_obj_t common_hal_wifi_radio_get_ipv4_subnet(wifi_radio_obj_t *self) { - // if (!esp_netif_is_netif_up(self->netif)) { + if (self->sta_netif == NULL || !net_if_is_up(self->sta_netif)) { + return mp_const_none; + } + // See get_ipv4_gateway: net_if_ip.ipv4 needs CONFIG_NET_IPV4. + #if defined(CONFIG_NET_IPV4) + struct net_if_ipv4 *ipv4 = self->sta_netif->config.ip.ipv4; + if (ipv4 == NULL) { + return mp_const_none; + } + for (int i = 0; i < NET_IF_MAX_IPV4_ADDR; i++) { + if (ipv4->unicast[i].ipv4.is_used && + ipv4->unicast[i].ipv4.addr_state == NET_ADDR_PREFERRED) { + return common_hal_ipaddress_new_ipv4address( + ipv4->unicast[i].netmask.s_addr); + } + } + #endif return mp_const_none; - // } - // esp_netif_get_ip_info(self->netif, &self->ip_info); - // return common_hal_ipaddress_new_ipv4address(self->ip_info.netmask.addr); } mp_obj_t common_hal_wifi_radio_get_ipv4_subnet_ap(wifi_radio_obj_t *self) { @@ -522,31 +764,48 @@ mp_obj_t common_hal_wifi_radio_get_ipv4_subnet_ap(wifi_radio_obj_t *self) { // } mp_obj_t common_hal_wifi_radio_get_addresses(wifi_radio_obj_t *self) { - // return common_hal_wifi_radio_get_addresses_netif(self, self->netif); - return mp_const_none; + // shared-bindings documents this as Sequence[str], empty when not + // connected, so format as a dotted-quad string rather than returning an + // IPv4Address object. Same address as wifi_radio_get_ipv4_address(). + uint32_t ipv4_address = wifi_radio_get_ipv4_address(self); + if (ipv4_address == 0) { + return mp_const_empty_tuple; + } + uint8_t *octets = (uint8_t *)&ipv4_address; + char buf[16]; + snprintf(buf, sizeof(buf), "%d.%d.%d.%d", octets[0], octets[1], octets[2], octets[3]); + mp_obj_t args[] = { mp_obj_new_str(buf, strlen(buf)) }; + return mp_obj_new_tuple(MP_ARRAY_SIZE(args), args); } mp_obj_t common_hal_wifi_radio_get_addresses_ap(wifi_radio_obj_t *self) { - // return common_hal_wifi_radio_get_addresses_netif(self, self->ap_netif); - return mp_const_none; + // AP mode is unimplemented here, but mp_const_none is still the wrong type + // for the Sequence[str] contract. + return mp_const_empty_tuple; } uint32_t wifi_radio_get_ipv4_address(wifi_radio_obj_t *self) { - // if (!esp_netif_is_netif_up(self->netif)) { - // return 0; - // } - // esp_netif_get_ip_info(self->netif, &self->ip_info); - // return self->ip_info.ip.addr; - return 0; + // Raw uint32_t sibling of common_hal_wifi_radio_get_ipv4_address(), + // used internally by supervisor/shared/web_workflow/web_workflow.c. + if (self->sta_netif == NULL || !net_if_is_up(self->sta_netif)) { + return 0; + } + struct in_addr *addr = net_if_ipv4_get_global_addr(self->sta_netif, NET_ADDR_PREFERRED); + if (addr == NULL) { + return 0; + } + return addr->s_addr; } mp_obj_t common_hal_wifi_radio_get_ipv4_address(wifi_radio_obj_t *self) { - // if (!esp_netif_is_netif_up(self->netif)) { - // return mp_const_none; - // } - // esp_netif_get_ip_info(self->netif, &self->ip_info); - // return common_hal_ipaddress_new_ipv4address(self->ip_info.ip.addr); - return mp_const_none; + if (self->sta_netif == NULL || !net_if_is_up(self->sta_netif)) { + return mp_const_none; + } + struct in_addr *addr = net_if_ipv4_get_global_addr(self->sta_netif, NET_ADDR_PREFERRED); + if (addr == NULL) { + return mp_const_none; + } + return common_hal_ipaddress_new_ipv4address(addr->s_addr); } mp_obj_t common_hal_wifi_radio_get_ipv4_address_ap(wifi_radio_obj_t *self) { @@ -559,20 +818,26 @@ mp_obj_t common_hal_wifi_radio_get_ipv4_address_ap(wifi_radio_obj_t *self) { } mp_obj_t common_hal_wifi_radio_get_ipv4_dns(wifi_radio_obj_t *self) { - // if (!esp_netif_is_netif_up(self->netif)) { - // return mp_const_none; - // } - - // esp_netif_get_dns_info(self->netif, ESP_NETIF_DNS_MAIN, &self->dns_info); - - // if (self->dns_info.ip.type != ESP_IPADDR_TYPE_V4) { - // return mp_const_none; - // } - // // dns_info is of type esp_netif_dns_info_t, which is just ever so slightly - // // different than esp_netif_ip_info_t used for - // // common_hal_wifi_radio_get_ipv4_address (includes both ipv4 and 6), - // // so some extra jumping is required to get to the actual address - // return common_hal_ipaddress_new_ipv4address(self->dns_info.ip.u_addr.ip4.addr); + // Zephyr keeps resolver state in the DNS resolve context rather than on + // the interface, so read it there. + #if defined(CONFIG_DNS_RESOLVER) + if (self->sta_netif == NULL || !net_if_is_up(self->sta_netif)) { + return mp_const_none; + } + struct dns_resolve_context *ctx = dns_resolve_get_default(); + if (ctx == NULL) { + return mp_const_none; + } + for (int i = 0; i < CONFIG_DNS_RESOLVER_MAX_SERVERS; i++) { + if (ctx->servers[i].dns_server.sa_family == AF_INET) { + struct sockaddr_in *addr = + (struct sockaddr_in *)&ctx->servers[i].dns_server; + if (addr->sin_addr.s_addr != 0) { + return common_hal_ipaddress_new_ipv4address(addr->sin_addr.s_addr); + } + } + } + #endif return mp_const_none; } @@ -645,58 +910,187 @@ void common_hal_wifi_radio_set_ipv4_address_ap(wifi_radio_obj_t *self, mp_obj_t // common_hal_wifi_radio_start_dhcp_server(self); // restart access point DHCP } -// static void ping_success_cb(esp_ping_handle_t hdl, void *args) { -// wifi_radio_obj_t *self = (wifi_radio_obj_t *)args; -// esp_ping_get_profile(hdl, ESP_PING_PROF_TIMEGAP, &self->ping_elapsed_time, sizeof(self->ping_elapsed_time)); -// } +#if CIRCUITPY_WIFI_PING +// Zephyr delivers the echo reply on the network RX thread, not the caller's, so +// the two halves share this state through the ICMP context's user_data. It lives +// on the calling thread's stack, hence the cleanup discipline in ping() below. +typedef struct { + struct k_sem reply_sem; + int64_t sent_ms; + int64_t elapsed_ms; + uint16_t identifier; + uint16_t sequence; +} ping_session_t; + +// Zephyr keeps struct net_icmpv4_echo_req in subsys/net/ip/icmpv4.h, a private +// header that code outside the net stack cannot include, so mirror the four +// bytes that follow the ICMP header here. +struct ping_echo_hdr { + uint16_t identifier; + uint16_t sequence; +} __packed; + +// An echo carries no port number, so the sequence is the only thing telling two +// back-to-back requests apart; without it a late reply would be reported as the +// next call's round trip. The identifier is randomized once per boot. +static uint16_t ping_identifier; +static uint16_t ping_sequence; + +static enum net_verdict ping_reply_handler(struct net_icmp_ctx *ctx, + struct net_pkt *pkt, + struct net_icmp_ip_hdr *ip_hdr, + struct net_icmp_hdr *icmp_hdr, + void *user_data) { + NET_PKT_DATA_ACCESS_CONTIGUOUS_DEFINE(echo_access, struct ping_echo_hdr); + ping_session_t *session = user_data; + struct ping_echo_hdr *echo; + + (void)ctx; + (void)ip_hdr; + (void)icmp_hdr; + + if (session == NULL) { + return NET_CONTINUE; + } + + // net_pkt_get_data() leaves the cursor where it found it, which the + // NET_CONTINUE below relies on: the next handler starts at the echo header. + echo = (struct ping_echo_hdr *)net_pkt_get_data(pkt, &echo_access); + if (echo == NULL) { + return NET_CONTINUE; + } + + if (net_ntohs(echo->identifier) != session->identifier || + net_ntohs(echo->sequence) != session->sequence) { + // A reply to an earlier ping of ours, or to somebody else's. Leave it + // alone rather than waking the caller with a round trip time that + // belongs to a different request. + return NET_CONTINUE; + } + + // Stamp arrival here rather than after k_sem_take() returns, so the + // measurement does not absorb the woken thread's scheduling delay. + session->elapsed_ms = k_uptime_get() - session->sent_ms; + k_sem_give(&session->reply_sem); + + return NET_OK; +} mp_int_t common_hal_wifi_radio_ping(wifi_radio_obj_t *self, mp_obj_t ip_address, mp_float_t timeout) { - // esp_ping_config_t ping_config = ESP_PING_DEFAULT_CONFIG(); - // ipaddress_ipaddress_to_esp_idf(ip_address, &ping_config.target_addr); - // ping_config.count = 1; - - // // We must fetch ping information using the callback mechanism, because the session storage is freed when - // // the ping session is done, even before esp_ping_delete_session(). - // esp_ping_callbacks_t ping_callbacks = { - // .on_ping_success = ping_success_cb, - // .cb_args = (void *)self, - // }; + // radio.ping() is documented to take an ipaddress.IPv4Address. + if (!mp_obj_is_type(ip_address, &ipaddress_ipv4address_type)) { + mp_raise_ValueError(MP_ERROR_TEXT("Only IPv4 addresses supported")); + } - // size_t timeout_ms = timeout * 1000; + // get_packed() takes a concrete ipaddress_ipv4address_obj_t *, so the + // MP_OBJ_TO_PTR is needed under object representations C and D. + ipaddress_ipv4address_obj_t *addr_obj = MP_OBJ_TO_PTR(ip_address); + size_t packed_len; + const char *packed = mp_obj_str_get_data( + common_hal_ipaddress_ipv4address_get_packed(addr_obj), &packed_len); + if (packed_len != sizeof(struct net_in_addr)) { + mp_raise_ValueError(MP_ERROR_TEXT("Only IPv4 addresses supported")); + } - // // ESP-IDF creates a task to do the ping session. It shuts down when done, but only after a one second delay. - // // Calling common_hal_wifi_radio_ping() too fast will cause resource exhaustion. - // esp_ping_handle_t ping; - // if (esp_ping_new_session(&ping_config, &ping_callbacks, &ping) != ESP_OK) { - // // Wait for old task to go away and then try again. - // // Empirical testing shows we have to wait at least two seconds, despite the task - // // having a one-second timeout. - // common_hal_time_delay_ms(2000); - // // Return if interrupted now, to show the interruption as KeyboardInterrupt instead of the - // // IDF error. - // if (mp_hal_is_interrupted()) { - // return (uint32_t)(-1); - // } - // CHECK_ESP_RESULT(esp_ping_new_session(&ping_config, &ping_callbacks, &ping)); - // } + // This Zephyr renamed the socket address types, so the destination is a + // struct net_sockaddr_in carrying NET_AF_INET, not a sockaddr_in/AF_INET. + struct net_sockaddr_in dst = { + .sin_family = NET_AF_INET, + }; + memcpy(&dst.sin_addr, packed, sizeof(dst.sin_addr)); + + if (ping_identifier == 0) { + // Seeded lazily. sys_rand16_get() may legitimately return 0, in which + // case we simply reseed on the next call. + ping_identifier = sys_rand16_get(); + } + + ping_session_t session = { + .identifier = ping_identifier, + .sequence = ++ping_sequence, + .elapsed_ms = -1, + }; + k_sem_init(&session.reply_sem, 0, 1); + + struct net_icmp_ctx icmp_ctx; + int res = net_icmp_init_ctx(&icmp_ctx, NET_AF_INET, NET_ICMPV4_ECHO_REPLY, 0, + ping_reply_handler); + if (res < 0) { + LOG_DBG("ping: net_icmp_init_ctx failed (%d)", res); + return -1; + } - // // Use all ones as a flag that the elapsed time was not set (ping failed or timed out). - // self->ping_elapsed_time = (uint32_t)(-1); + struct net_icmp_ping_params params = { + .identifier = session.identifier, + .sequence = session.sequence, + .tc_tos = 0, + // A negative priority leaves the packet at the stack default and lets + // tc_tos drive the DSCP/ECN bits instead. + .priority = -1, + .data = NULL, + .data_size = 0, + }; + + session.sent_ms = k_uptime_get(); + + // A NULL sta_netif is fine; the stack picks an interface from the + // destination. This is the blocking send, as Zephyr's net shell uses: it + // waits up to a second for a buffer, so a ping can take timeout + 1s. + res = net_icmp_send_echo_request(&icmp_ctx, self->sta_netif, + (struct net_sockaddr *)&dst, ¶ms, &session); + if (res < 0) { + LOG_DBG("ping: send failed (%d)", res); + (void)net_icmp_cleanup_ctx(&icmp_ctx); + return -1; + } - // esp_ping_start(ping); + // Wait for ping_reply_handler() to signal, staying responsive to ctrl-C at + // the same 50 ms granularity as the association wait in + // common_hal_wifi_radio_connect(). + mp_float_t timeout_s = timeout <= 0 ? (mp_float_t)0.5 : timeout; + int64_t deadline = k_uptime_get() + (int64_t)(timeout_s * 1000); + bool replied = false; + while (true) { + int64_t remaining_ms = deadline - k_uptime_get(); + if (remaining_ms <= 0) { + break; + } - // uint32_t start_time = common_hal_time_monotonic_ms(); - // while ((self->ping_elapsed_time == (uint32_t)(-1)) && - // (common_hal_time_monotonic_ms() - start_time < timeout_ms) && - // !mp_hal_is_interrupted()) { - // RUN_BACKGROUND_TASKS; - // } - // esp_ping_stop(ping); - // esp_ping_delete_session(ping); + // Poll in 50 ms slices so ctrl-C stays responsive, clamped to the + // caller's deadline so a reply arriving after the timeout is not + // reported as a success. MIN() is avoided here because py/misc.h and + // zephyr/sys/util.h both define it and this file includes both. + int64_t wait_ms = remaining_ms < 50 ? remaining_ms : 50; + + if (k_sem_take(&session.reply_sem, K_MSEC(wait_ms)) == 0) { + replied = true; + break; + } + if (mp_hal_is_interrupted()) { + break; + } + } + + // Unregister before returning. net_icmp_cleanup_ctx() takes the same mutex + // the stack holds while dispatching handlers, so once it returns no handler + // can still be looking at session, which lives on this stack frame. This + // has to happen on every exit path, including the error paths above. + (void)net_icmp_cleanup_ctx(&icmp_ctx); + + if (!replied || session.elapsed_ms < 0) { + return -1; + } - // return (mp_int_t)self->ping_elapsed_time; - return 0; + // shared-bindings turns exactly -1 into None and divides anything else by + // 1000, so every failure path must return -1, not 0. + return (mp_int_t)session.elapsed_ms; +} +#else +mp_int_t common_hal_wifi_radio_ping(wifi_radio_obj_t *self, mp_obj_t ip_address, mp_float_t timeout) { + // Boards that turn ping off to save flash report no reply. + return -1; } +#endif void common_hal_wifi_radio_gc_collect(wifi_radio_obj_t *self) { // Only bother to scan the actual object references. diff --git a/ports/zephyr-cp/common-hal/wifi/Radio.h b/ports/zephyr-cp/common-hal/wifi/Radio.h index f177f493685..2500079df09 100644 --- a/ports/zephyr-cp/common-hal/wifi/Radio.h +++ b/ports/zephyr-cp/common-hal/wifi/Radio.h @@ -11,7 +11,9 @@ #include "shared-bindings/wifi/ScannedNetworks.h" #include "shared-bindings/wifi/Network.h" +#include #include +#include // Event bits for the Radio event group. #define WIFI_SCAN_DONE_BIT BIT0 @@ -38,6 +40,16 @@ typedef struct { uint8_t retries_left; uint8_t starting_retries; uint8_t last_disconnect_reason; + // Signalled from the net_mgmt event handler when a connect attempt + // finishes, so common_hal_wifi_radio_connect() can wait on the result. + struct k_sem connect_sem; + // Latest wifi_conn_status from NET_EVENT_WIFI_CONNECT_RESULT. + int last_connect_status; + bool connected; + // SSID of the association that `connected` refers to, so that a connect() + // for the network we are already on can return without touching the link. + uint8_t current_ssid[WIFI_SSID_MAX_LEN]; + size_t current_ssid_len; } wifi_radio_obj_t; extern void common_hal_wifi_radio_gc_collect(wifi_radio_obj_t *self); diff --git a/ports/zephyr-cp/common-hal/wifi/ScannedNetworks.c b/ports/zephyr-cp/common-hal/wifi/ScannedNetworks.c index 3a6c21c5b83..d7df14ffa5c 100644 --- a/ports/zephyr-cp/common-hal/wifi/ScannedNetworks.c +++ b/ports/zephyr-cp/common-hal/wifi/ScannedNetworks.c @@ -16,14 +16,18 @@ #include "shared-bindings/wifi/Network.h" #include "shared-bindings/wifi/Radio.h" #include "shared-bindings/wifi/ScannedNetworks.h" +#include "bindings/zephyr_kernel/__init__.h" #include +#include #include +LOG_MODULE_DECLARE(cp_wifi); + void wifi_scannednetworks_scan_result(wifi_scannednetworks_obj_t *self, struct wifi_scan_result *result) { if (k_msgq_put(&self->msgq, result, K_NO_WAIT) != 0) { - printk("Dropping scan result!\n"); + LOG_WRN("Dropping scan result"); } } @@ -103,7 +107,7 @@ void wifi_scannednetworks_scan_next_channel(wifi_scannednetworks_obj_t *self) { } else { int res = net_mgmt(NET_REQUEST_WIFI_SCAN, self->netif, ¶ms, sizeof(params)); if (res != 0) { - printk("Failed to start wifi scan %d\n", res); + LOG_ERR("Failed to start wifi scan %d", res); raise_zephyr_error(res); wifi_scannednetworks_done(self); } else { diff --git a/ports/zephyr-cp/common-hal/wifi/__init__.c b/ports/zephyr-cp/common-hal/wifi/__init__.c index 57f073a9cbb..f878f708111 100644 --- a/ports/zephyr-cp/common-hal/wifi/__init__.c +++ b/ports/zephyr-cp/common-hal/wifi/__init__.c @@ -20,17 +20,27 @@ wifi_radio_obj_t common_hal_wifi_radio_obj; #include "supervisor/port.h" +#include "supervisor/shared/network.h" #include "supervisor/workflow.h" +#if CIRCUITPY_SETTINGS_TOML +#include "supervisor/shared/settings.h" +#endif + #if CIRCUITPY_STATUS_BAR #include "supervisor/shared/status_bar.h" #endif #include +#include #include +#include + #define MAC_ADDRESS_LENGTH 6 +LOG_MODULE_REGISTER(cp_wifi, CONFIG_LOG_DEFAULT_LEVEL); + static void schedule_background_on_cp_core(void *arg) { #if CIRCUITPY_STATUS_BAR supervisor_status_bar_request_update(false); @@ -44,62 +54,89 @@ static void schedule_background_on_cp_core(void *arg) { static struct net_mgmt_event_callback wifi_cb; static struct net_mgmt_event_callback ipv4_cb; -static void _event_handler(struct net_mgmt_event_callback *cb, uint32_t mgmt_event, struct net_if *iface) { +static void _event_handler(struct net_mgmt_event_callback *cb, uint64_t mgmt_event, struct net_if *iface) { wifi_radio_obj_t *self = &common_hal_wifi_radio_obj; - printk("_event_handler cb %p event %08x if %p\n", cb, mgmt_event, iface); + (void)iface; switch (mgmt_event) { - case NET_EVENT_WIFI_SCAN_RESULT: - printk("NET_EVENT_WIFI_SCAN_RESULT\n"); - struct wifi_scan_result *result = (struct wifi_scan_result *)cb->info; - if (self->current_scan != NULL) { + case NET_EVENT_WIFI_SCAN_RESULT: { + LOG_DBG("NET_EVENT_WIFI_SCAN_RESULT"); + const struct wifi_scan_result *result = cb->info; + if (result != NULL && self->current_scan != NULL) { wifi_scannednetworks_scan_result(self->current_scan, result); } break; + } case NET_EVENT_WIFI_SCAN_DONE: - printk("NET_EVENT_WIFI_SCAN_DONE\n"); + LOG_DBG("NET_EVENT_WIFI_SCAN_DONE (thread: %s prio=%d)", + k_thread_name_get(k_current_get()), + k_thread_priority_get(k_current_get())); if (self->current_scan != NULL) { k_poll_signal_raise(&self->current_scan->channel_done, 0); } break; - case NET_EVENT_WIFI_CONNECT_RESULT: - printk("NET_EVENT_WIFI_CONNECT_RESULT\n"); + case NET_EVENT_WIFI_CONNECT_RESULT: { + const struct wifi_status *status = cb->info; + self->last_connect_status = status != NULL ? status->status : -1; + self->connected = self->last_connect_status == WIFI_STATUS_CONN_SUCCESS; + LOG_DBG("NET_EVENT_WIFI_CONNECT_RESULT status %d", self->last_connect_status); + k_sem_give(&self->connect_sem); break; - case NET_EVENT_WIFI_DISCONNECT_RESULT: - printk("NET_EVENT_WIFI_DISCONNECT_RESULT\n"); + } + case NET_EVENT_WIFI_DISCONNECT_RESULT: { + const struct wifi_status *status = cb->info; + self->last_disconnect_reason = status != NULL ? (uint8_t)status->status : 0; + self->connected = false; + LOG_DBG("NET_EVENT_WIFI_DISCONNECT_RESULT reason %d", self->last_disconnect_reason); + // A disconnect can also be the failure result of a connect attempt, + // so release any waiter rather than letting it sit until timeout. + k_sem_give(&self->connect_sem); break; + } case NET_EVENT_WIFI_IFACE_STATUS: - printk("NET_EVENT_WIFI_IFACE_STATUS\n"); + LOG_DBG("NET_EVENT_WIFI_IFACE_STATUS"); break; case NET_EVENT_WIFI_TWT: - printk("NET_EVENT_WIFI_TWT\n"); + LOG_DBG("NET_EVENT_WIFI_TWT"); break; case NET_EVENT_WIFI_TWT_SLEEP_STATE: - printk("NET_EVENT_WIFI_TWT_SLEEP_STATE\n"); + LOG_DBG("NET_EVENT_WIFI_TWT_SLEEP_STATE"); break; case NET_EVENT_WIFI_RAW_SCAN_RESULT: - printk("NET_EVENT_WIFI_RAW_SCAN_RESULT\n"); + LOG_DBG("NET_EVENT_WIFI_RAW_SCAN_RESULT"); break; case NET_EVENT_WIFI_DISCONNECT_COMPLETE: - printk("NET_EVENT_WIFI_DISCONNECT_COMPLETE\n"); + LOG_DBG("NET_EVENT_WIFI_DISCONNECT_COMPLETE"); break; case NET_EVENT_WIFI_SIGNAL_CHANGE: - printk("NET_EVENT_WIFI_SIGNAL_CHANGE\n"); + LOG_DBG("NET_EVENT_WIFI_SIGNAL_CHANGE"); break; case NET_EVENT_WIFI_NEIGHBOR_REP_COMP: - printk("NET_EVENT_WIFI_NEIGHBOR_REP_COMP\n"); + LOG_DBG("NET_EVENT_WIFI_NEIGHBOR_REP_COMP"); break; case NET_EVENT_WIFI_AP_ENABLE_RESULT: - printk("NET_EVENT_WIFI_AP_ENABLE_RESULT\n"); + LOG_DBG("NET_EVENT_WIFI_AP_ENABLE_RESULT"); break; case NET_EVENT_WIFI_AP_DISABLE_RESULT: - printk("NET_EVENT_WIFI_AP_DISABLE_RESULT\n"); + LOG_DBG("NET_EVENT_WIFI_AP_DISABLE_RESULT"); break; case NET_EVENT_WIFI_AP_STA_CONNECTED: - printk("NET_EVENT_WIFI_AP_STA_CONNECTED\n"); + LOG_DBG("NET_EVENT_WIFI_AP_STA_CONNECTED"); break; case NET_EVENT_WIFI_AP_STA_DISCONNECTED: - printk("NET_EVENT_WIFI_AP_STA_DISCONNECTED\n"); + LOG_DBG("NET_EVENT_WIFI_AP_STA_DISCONNECTED"); + break; + case NET_EVENT_IPV4_ADDR_ADD: + // DHCP bound, or a static address was configured. The address is read + // live by the ipv4_address getter, so nothing is stored here; the + // status bar just needs a refresh or it keeps showing "No IP". + LOG_DBG("NET_EVENT_IPV4_ADDR_ADD"); + schedule_background_on_cp_core(NULL); + break; + default: + // Print all 64 bits. The layer lives in the high bits, so a 32-bit + // print collapses every unhandled event in a layer to one value. + LOG_DBG("unhandled net event %llx", (unsigned long long)mgmt_event); break; } } @@ -184,7 +221,7 @@ static bool wifi_user_initiated; void common_hal_wifi_init(bool user_initiated) { wifi_radio_obj_t *self = &common_hal_wifi_radio_obj; - printk("common_hal_wifi_init\n"); + LOG_DBG("common_hal_wifi_init"); if (wifi_inited) { if (user_initiated && !wifi_user_initiated) { @@ -195,6 +232,9 @@ void common_hal_wifi_init(bool user_initiated) { wifi_inited = true; wifi_user_initiated = user_initiated; self->base.type = &wifi_radio_type; + k_sem_init(&self->connect_sem, 0, 1); + self->connected = false; + self->last_connect_status = -1; // struct net_if *default_iface = net_if_get_default(); // printk("default interface %p\n", default_iface); @@ -211,8 +251,8 @@ void common_hal_wifi_init(bool user_initiated) { // } self->sta_netif = net_if_get_wifi_sta(); self->ap_netif = net_if_get_wifi_sap(); - printk("sta_netif %p\n", self->sta_netif); - printk("ap_netif %p\n", self->ap_netif); + LOG_DBG("sta_netif %p", self->sta_netif); + LOG_DBG("ap_netif %p", self->ap_netif); struct wifi_iface_status status = { 0 }; @@ -220,39 +260,39 @@ void common_hal_wifi_init(bool user_initiated) { CHECK_ZEPHYR_RESULT(net_mgmt(NET_REQUEST_WIFI_IFACE_STATUS, self->sta_netif, &status, sizeof(struct wifi_iface_status))); if (net_if_is_up(self->sta_netif)) { - printk("STA is up\n"); + LOG_DBG("STA is up"); } else { - printk("STA is down\n"); + LOG_DBG("STA is down"); } if (net_if_is_carrier_ok(self->sta_netif)) { - printk("STA carrier is ok\n"); + LOG_DBG("STA carrier is ok"); } else { - printk("STA carrier is not ok\n"); + LOG_DBG("STA carrier is not ok"); } if (net_if_is_dormant(self->sta_netif)) { - printk("STA is dormant\n"); + LOG_DBG("STA is dormant"); } else { - printk("STA is not dormant\n"); + LOG_DBG("STA is not dormant"); } } if (self->ap_netif != NULL) { int res = net_mgmt(NET_REQUEST_WIFI_IFACE_STATUS, self->ap_netif, &status, sizeof(struct wifi_iface_status)); - printk("AP status request response %d\n", res); + LOG_DBG("AP status request response %d", res); if (net_if_is_up(self->ap_netif)) { - printk("AP is up\n"); + LOG_DBG("AP is up"); } else { - printk("AP is down\n"); + LOG_DBG("AP is down"); } if (net_if_is_carrier_ok(self->ap_netif)) { - printk("AP carrier is ok\n"); + LOG_DBG("AP carrier is ok"); } else { - printk("AP carrier is not ok\n"); + LOG_DBG("AP carrier is not ok"); } if (net_if_is_dormant(self->ap_netif)) { - printk("AP is dormant\n"); + LOG_DBG("AP is dormant"); } else { - printk("AP is not dormant\n"); + LOG_DBG("AP is not dormant"); } } @@ -266,6 +306,7 @@ void common_hal_wifi_init(bool user_initiated) { // self->ap_mode = 0; net_mgmt_init_event_callback(&wifi_cb, _event_handler, + NET_EVENT_WIFI_SCAN_RESULT | NET_EVENT_WIFI_SCAN_DONE | NET_EVENT_WIFI_CONNECT_RESULT | NET_EVENT_WIFI_DISCONNECT_RESULT | @@ -281,32 +322,63 @@ void common_hal_wifi_init(bool user_initiated) { net_mgmt_add_event_callback(&wifi_cb); net_mgmt_add_event_callback(&ipv4_cb); - // Set the default hostname capped at NET_HOSTNAME_MAX_LEN characters. We trim off - // the start of the board name (likely manufacturer) because the end is - // often more unique to the board. - size_t board_len = MIN(NET_HOSTNAME_MAX_LEN - ((MAC_ADDRESS_LENGTH * 2) + 6), strlen(CIRCUITPY_BOARD_ID)); - size_t board_trim = strlen(CIRCUITPY_BOARD_ID) - board_len; - // Avoid double _ in the hostname. - if (CIRCUITPY_BOARD_ID[board_trim] == '_') { - board_trim++; + #if defined(CONFIG_NET_HOSTNAME) + #if CIRCUITPY_SETTINGS_TOML + char hostname[NET_HOSTNAME_MAX_LEN]; + if (settings_get_str("CIRCUITPY_WIFI_HOSTNAME", hostname, sizeof(hostname)) == SETTINGS_OK) { + CHECK_ZEPHYR_RESULT(net_hostname_set(hostname, strlen(hostname))); } - - char cpy_default_hostname[board_len + (MAC_ADDRESS_LENGTH * 2) + 6]; - struct net_linkaddr *mac = net_if_get_link_addr(self->sta_netif); - if (mac->len < MAC_ADDRESS_LENGTH) { - printk("MAC address too short"); + #else + if (false) { } - snprintf(cpy_default_hostname, sizeof(cpy_default_hostname), "cpy-%s-%02x%02x%02x%02x%02x%02x", CIRCUITPY_BOARD_ID + board_trim, mac->addr[0], mac->addr[1], mac->addr[2], mac->addr[3], mac->addr[4], mac->addr[5]); - - if (net_hostname_set(cpy_default_hostname, strlen(cpy_default_hostname)) != 0) { - printk("setting hostname failed\n"); + #endif + else { + // Set the default hostname, capped at NET_HOSTNAME_MAX_LEN characters. + char cpy_default_hostname[NET_HOSTNAME_MAX_LEN]; + struct net_linkaddr *mac = net_if_get_link_addr(self->sta_netif); + if (mac->len < MAC_ADDRESS_LENGTH) { + LOG_ERR("MAC address too short"); + } + size_t len = network_format_default_hostname(cpy_default_hostname, sizeof(cpy_default_hostname), mac->addr); + CHECK_ZEPHYR_RESULT(net_hostname_set(cpy_default_hostname, len)); } + #else + LOG_WRN("Hostname support disabled in Zephyr config"); + #endif // set station mode to avoid the default SoftAP common_hal_wifi_radio_start_station(self); // start wifi common_hal_wifi_radio_set_enabled(self, true); - printk("common_hal_wifi_init done\n"); + LOG_DBG("common_hal_wifi_init done"); +} + +bool wifi_is_initialized(void) { + return wifi_inited; +} + +void wifi_get_default_hostname(char *buf, size_t buf_size) { + if (buf_size == 0) { + return; + } + buf[0] = '\0'; + #if defined(CONFIG_NET_HOSTNAME) + if (buf_size < 18) { + return; + } + // Zephyr creates the interface at boot, so it exists before + // common_hal_wifi_init() runs. + struct net_if *sta_netif = net_if_get_wifi_sta(); + if (sta_netif == NULL) { + return; + } + struct net_linkaddr *mac = net_if_get_link_addr(sta_netif); + if (mac->len < MAC_ADDRESS_LENGTH) { + return; + } + // Use the same length limit as common_hal_wifi_init(). + network_format_default_hostname(buf, MIN(buf_size, NET_HOSTNAME_MAX_LEN), mac->addr); + #endif } void wifi_user_reset(void) { @@ -317,7 +389,7 @@ void wifi_user_reset(void) { } void wifi_reset(void) { - printk("wifi_reset\n"); + LOG_DBG("wifi_reset"); if (!wifi_inited) { return; } diff --git a/ports/zephyr-cp/common-hal/wifi/__init__.h b/ports/zephyr-cp/common-hal/wifi/__init__.h index dab519b1a5f..937ac699021 100644 --- a/ports/zephyr-cp/common-hal/wifi/__init__.h +++ b/ports/zephyr-cp/common-hal/wifi/__init__.h @@ -8,6 +8,8 @@ #include "py/obj.h" +#include + struct sockaddr_storage; void wifi_reset(void); diff --git a/ports/zephyr-cp/common-hal/zephyr_display/Display.h b/ports/zephyr-cp/common-hal/zephyr_display/Display.h new file mode 100644 index 00000000000..78d2e588b1d --- /dev/null +++ b/ports/zephyr-cp/common-hal/zephyr_display/Display.h @@ -0,0 +1,15 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// The Zephyr display object layout and API are the same for both compositors; only the +// implementation differs. +#if CIRCUITPY_DISPLAYIO_LVGL +#include "common-hal/zephyr_display/lvgl/Display.h" +#else +#include "common-hal/zephyr_display/legacy/Display.h" +#endif diff --git a/ports/zephyr-cp/common-hal/zephyr_display/legacy/Display.c b/ports/zephyr-cp/common-hal/zephyr_display/legacy/Display.c new file mode 100644 index 00000000000..d1585b5f291 --- /dev/null +++ b/ports/zephyr-cp/common-hal/zephyr_display/legacy/Display.c @@ -0,0 +1,440 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "bindings/zephyr_display/Display.h" + +#include + +#include "bindings/zephyr_kernel/__init__.h" +#include "py/gc.h" +#include "py/runtime.h" +#include "shared-bindings/time/__init__.h" +#include "shared-module/displayio/__init__.h" +#include "supervisor/shared/display.h" +#include "supervisor/shared/tick.h" + +static const displayio_area_t *zephyr_display_get_refresh_areas(zephyr_display_display_obj_t *self) { + if (self->core.full_refresh) { + self->core.area.next = NULL; + return &self->core.area; + } else if (self->core.current_group != NULL) { + return displayio_group_get_refresh_areas(self->core.current_group, NULL); + } + return NULL; +} + +static enum display_pixel_format zephyr_display_select_pixel_format(const struct display_capabilities *caps) { + uint32_t formats = caps->supported_pixel_formats; + + if (formats & PIXEL_FORMAT_RGB_565) { + return PIXEL_FORMAT_RGB_565; + } + if (formats & PIXEL_FORMAT_RGB_888) { + return PIXEL_FORMAT_RGB_888; + } + if (formats & PIXEL_FORMAT_ARGB_8888) { + return PIXEL_FORMAT_ARGB_8888; + } + if (formats & PIXEL_FORMAT_RGB_565X) { + return PIXEL_FORMAT_RGB_565X; + } + if (formats & PIXEL_FORMAT_L_8) { + return PIXEL_FORMAT_L_8; + } + if (formats & PIXEL_FORMAT_AL_88) { + return PIXEL_FORMAT_AL_88; + } + if (formats & PIXEL_FORMAT_MONO01) { + return PIXEL_FORMAT_MONO01; + } + if (formats & PIXEL_FORMAT_MONO10) { + return PIXEL_FORMAT_MONO10; + } + return caps->current_pixel_format; +} + +static void zephyr_display_select_colorspace(zephyr_display_display_obj_t *self, + uint16_t *color_depth, + uint8_t *bytes_per_cell, + bool *grayscale, + bool *pixels_in_byte_share_row, + bool *reverse_pixels_in_byte, + bool *reverse_bytes_in_word) { + *color_depth = 16; + *bytes_per_cell = 2; + *grayscale = false; + *pixels_in_byte_share_row = false; + *reverse_pixels_in_byte = false; + *reverse_bytes_in_word = false; + + if (self->pixel_format == PIXEL_FORMAT_RGB_565X) { + // RGB_565X is big-endian RGB_565, so byte-swap from native LE. + *reverse_bytes_in_word = true; + } else if (self->pixel_format == PIXEL_FORMAT_RGB_888) { + *color_depth = 24; + *bytes_per_cell = 3; + *reverse_bytes_in_word = false; + } else if (self->pixel_format == PIXEL_FORMAT_ARGB_8888) { + *color_depth = 32; + *bytes_per_cell = 4; + *reverse_bytes_in_word = false; + } else if (self->pixel_format == PIXEL_FORMAT_L_8 || + self->pixel_format == PIXEL_FORMAT_AL_88) { + *color_depth = 8; + *bytes_per_cell = 1; + *grayscale = true; + *reverse_bytes_in_word = false; + } else if (self->pixel_format == PIXEL_FORMAT_MONO01 || + self->pixel_format == PIXEL_FORMAT_MONO10) { + bool vtiled = self->capabilities.screen_info & SCREEN_INFO_MONO_VTILED; + bool msb_first = self->capabilities.screen_info & SCREEN_INFO_MONO_MSB_FIRST; + *color_depth = 1; + *bytes_per_cell = 1; + *grayscale = true; + *pixels_in_byte_share_row = !vtiled; + *reverse_pixels_in_byte = msb_first; + *reverse_bytes_in_word = false; + } +} + +void common_hal_zephyr_display_display_construct_from_device(zephyr_display_display_obj_t *self, + const struct device *device, + uint16_t rotation, + bool auto_refresh) { + self->auto_refresh = false; + + if (device == NULL || !device_is_ready(device)) { + raise_zephyr_error(-ENODEV); + } + + self->device = device; + display_get_capabilities(self->device, &self->capabilities); + + self->pixel_format = zephyr_display_select_pixel_format(&self->capabilities); + if (self->pixel_format != self->capabilities.current_pixel_format) { + (void)display_set_pixel_format(self->device, self->pixel_format); + display_get_capabilities(self->device, &self->capabilities); + self->pixel_format = self->capabilities.current_pixel_format; + } + + uint16_t color_depth; + uint8_t bytes_per_cell; + bool grayscale; + bool pixels_in_byte_share_row; + bool reverse_pixels_in_byte; + bool reverse_bytes_in_word; + zephyr_display_select_colorspace(self, &color_depth, &bytes_per_cell, + &grayscale, &pixels_in_byte_share_row, &reverse_pixels_in_byte, + &reverse_bytes_in_word); + + displayio_display_core_construct( + &self->core, + self->capabilities.x_resolution, + self->capabilities.y_resolution, + 0, + color_depth, + grayscale, + pixels_in_byte_share_row, + bytes_per_cell, + reverse_pixels_in_byte, + reverse_bytes_in_word); + + self->native_frames_per_second = 60; + self->native_ms_per_frame = 1000 / self->native_frames_per_second; + self->first_manual_refresh = !auto_refresh; + + if (rotation != 0) { + common_hal_zephyr_display_display_set_rotation(self, rotation); + } + + (void)display_blanking_off(self->device); + + displayio_display_core_set_root_group(&self->core, &circuitpython_splash); + common_hal_zephyr_display_display_set_auto_refresh(self, auto_refresh); +} + +uint16_t common_hal_zephyr_display_display_get_width(zephyr_display_display_obj_t *self) { + return displayio_display_core_get_width(&self->core); +} + +uint16_t common_hal_zephyr_display_display_get_height(zephyr_display_display_obj_t *self) { + return displayio_display_core_get_height(&self->core); +} + +mp_float_t common_hal_zephyr_display_display_get_brightness(zephyr_display_display_obj_t *self) { + (void)self; + return -1; +} + +bool common_hal_zephyr_display_display_set_brightness(zephyr_display_display_obj_t *self, mp_float_t brightness) { + (void)self; + (void)brightness; + return false; +} + +static bool zephyr_display_refresh_area(zephyr_display_display_obj_t *self, const displayio_area_t *area) { + uint16_t buffer_size = CIRCUITPY_DISPLAY_AREA_BUFFER_SIZE / sizeof(uint32_t); + + displayio_area_t clipped; + if (!displayio_display_core_clip_area(&self->core, area, &clipped)) { + return true; + } + + uint16_t rows_per_buffer = displayio_area_height(&clipped); + uint8_t pixels_per_word = (sizeof(uint32_t) * 8) / self->core.colorspace.depth; + // For AL_88, displayio fills at 1 byte/pixel (L_8) but output needs 2 bytes/pixel, + // so halve the effective pixels_per_word for buffer sizing. + uint8_t effective_pixels_per_word = pixels_per_word; + if (self->pixel_format == PIXEL_FORMAT_AL_88) { + effective_pixels_per_word = sizeof(uint32_t) / 2; + } + uint16_t pixels_per_buffer = displayio_area_size(&clipped); + uint16_t subrectangles = 1; + + // When pixels_in_byte_share_row is false (mono vtiled), 8 vertical pixels + // pack into one column byte. The byte layout needs width * ceil(height/8) + // bytes, which can exceed the pixel-count-based buffer size. + bool vtiled = self->core.colorspace.depth < 8 && + !self->core.colorspace.pixels_in_byte_share_row; + + bool needs_subdivision = displayio_area_size(&clipped) > buffer_size * effective_pixels_per_word; + if (vtiled && !needs_subdivision) { + uint16_t width = displayio_area_width(&clipped); + uint16_t height = displayio_area_height(&clipped); + uint32_t vtiled_bytes = (uint32_t)width * ((height + 7) / 8); + needs_subdivision = vtiled_bytes > buffer_size * sizeof(uint32_t); + } + + if (needs_subdivision) { + rows_per_buffer = buffer_size * effective_pixels_per_word / displayio_area_width(&clipped); + if (vtiled) { + rows_per_buffer = (rows_per_buffer / 8) * 8; + if (rows_per_buffer == 0) { + rows_per_buffer = 8; + } + } + if (rows_per_buffer == 0) { + rows_per_buffer = 1; + } + subrectangles = displayio_area_height(&clipped) / rows_per_buffer; + if (displayio_area_height(&clipped) % rows_per_buffer != 0) { + subrectangles++; + } + pixels_per_buffer = rows_per_buffer * displayio_area_width(&clipped); + buffer_size = pixels_per_buffer / pixels_per_word; + if (pixels_per_buffer % pixels_per_word) { + buffer_size += 1; + } + // Ensure buffer is large enough for vtiled packing. + if (vtiled) { + uint16_t width = displayio_area_width(&clipped); + uint16_t vtiled_words = (width * ((rows_per_buffer + 7) / 8) + sizeof(uint32_t) - 1) / sizeof(uint32_t); + if (vtiled_words > buffer_size) { + buffer_size = vtiled_words; + } + } + // Ensure buffer is large enough for AL_88 expansion. + if (self->pixel_format == PIXEL_FORMAT_AL_88) { + uint16_t al88_words = (pixels_per_buffer * 2 + sizeof(uint32_t) - 1) / sizeof(uint32_t); + if (al88_words > buffer_size) { + buffer_size = al88_words; + } + } + } + + uint32_t buffer[buffer_size]; + uint32_t mask_length = (pixels_per_buffer / 32) + 1; + uint32_t mask[mask_length]; + + uint16_t remaining_rows = displayio_area_height(&clipped); + + for (uint16_t j = 0; j < subrectangles; j++) { + displayio_area_t subrectangle = { + .x1 = clipped.x1, + .y1 = clipped.y1 + rows_per_buffer * j, + .x2 = clipped.x2, + .y2 = clipped.y1 + rows_per_buffer * (j + 1), + }; + + if (remaining_rows < rows_per_buffer) { + subrectangle.y2 = subrectangle.y1 + remaining_rows; + } + remaining_rows -= rows_per_buffer; + + memset(mask, 0, mask_length * sizeof(mask[0])); + memset(buffer, 0, buffer_size * sizeof(buffer[0])); + + displayio_display_core_fill_area(&self->core, &subrectangle, mask, buffer); + + uint16_t width = displayio_area_width(&subrectangle); + uint16_t height = displayio_area_height(&subrectangle); + size_t pixel_count = (size_t)width * (size_t)height; + + if (self->pixel_format == PIXEL_FORMAT_MONO10) { + uint8_t *bytes = (uint8_t *)buffer; + size_t byte_count = (pixel_count + 7) / 8; + for (size_t i = 0; i < byte_count; i++) { + bytes[i] = ~bytes[i]; + } + } + + if (self->pixel_format == PIXEL_FORMAT_AL_88) { + uint8_t *bytes = (uint8_t *)buffer; + for (size_t i = pixel_count; i > 0; i--) { + bytes[(i - 1) * 2 + 1] = 0xFF; + bytes[(i - 1) * 2] = bytes[i - 1]; + } + } + + // Compute buf_size based on the Zephyr pixel format. + uint32_t buf_size_bytes; + if (self->pixel_format == PIXEL_FORMAT_MONO01 || + self->pixel_format == PIXEL_FORMAT_MONO10) { + buf_size_bytes = (pixel_count + 7) / 8; + } else if (self->pixel_format == PIXEL_FORMAT_AL_88) { + buf_size_bytes = pixel_count * 2; + } else { + buf_size_bytes = pixel_count * (self->core.colorspace.depth / 8); + } + + struct display_buffer_descriptor desc = { + .buf_size = buf_size_bytes, + .width = width, + .height = height, + .pitch = width, + .frame_incomplete = false, + }; + + int err = display_write(self->device, subrectangle.x1, subrectangle.y1, &desc, buffer); + if (err < 0) { + return false; + } + + RUN_BACKGROUND_TASKS; + } + + return true; +} + +static void zephyr_display_refresh(zephyr_display_display_obj_t *self) { + if (!displayio_display_core_start_refresh(&self->core)) { + return; + } + + const displayio_area_t *current_area = zephyr_display_get_refresh_areas(self); + while (current_area != NULL) { + if (!zephyr_display_refresh_area(self, current_area)) { + break; + } + current_area = current_area->next; + } + + displayio_display_core_finish_refresh(&self->core); +} + +void common_hal_zephyr_display_display_set_rotation(zephyr_display_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) { + int tmp = self->core.width; + self->core.width = self->core.height; + self->core.height = tmp; + } + + displayio_display_core_set_rotation(&self->core, rotation); + + if (self == &displays[0].zephyr_display) { + supervisor_stop_terminal(); + supervisor_start_terminal(self->core.width, self->core.height); + } + + if (self->core.current_group != NULL) { + displayio_group_update_transform(self->core.current_group, &self->core.transform); + } +} + +uint16_t common_hal_zephyr_display_display_get_rotation(zephyr_display_display_obj_t *self) { + return self->core.rotation; +} + +bool common_hal_zephyr_display_display_refresh(zephyr_display_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 != NO_FPS_LIMIT)) { + uint64_t current_time = supervisor_ticks_ms64(); + uint32_t current_ms_since_real_refresh = current_time - self->core.last_refresh; + if (current_ms_since_real_refresh > maximum_ms_per_real_frame) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Below minimum frame rate")); + } + uint32_t current_ms_since_last_call = current_time - self->last_refresh_call; + self->last_refresh_call = current_time; + if (current_ms_since_last_call > target_ms_per_frame) { + return false; + } + uint32_t remaining_time = target_ms_per_frame - (current_ms_since_real_refresh % target_ms_per_frame); + while (supervisor_ticks_ms64() - self->last_refresh_call < remaining_time) { + RUN_BACKGROUND_TASKS; + } + } + self->first_manual_refresh = false; + zephyr_display_refresh(self); + return true; +} + +bool common_hal_zephyr_display_display_get_auto_refresh(zephyr_display_display_obj_t *self) { + return self->auto_refresh; +} + +void common_hal_zephyr_display_display_set_auto_refresh(zephyr_display_display_obj_t *self, bool auto_refresh) { + self->first_manual_refresh = !auto_refresh; + if (auto_refresh != self->auto_refresh) { + if (auto_refresh) { + supervisor_enable_tick(); + } else { + supervisor_disable_tick(); + } + } + self->auto_refresh = auto_refresh; +} + +void zephyr_display_display_background(zephyr_display_display_obj_t *self) { + if (self->auto_refresh && (supervisor_ticks_ms64() - self->core.last_refresh) > self->native_ms_per_frame) { + zephyr_display_refresh(self); + } +} + +void release_zephyr_display(zephyr_display_display_obj_t *self) { + common_hal_zephyr_display_display_set_auto_refresh(self, false); + release_display_core(&self->core); + self->device = NULL; + self->base.type = &mp_type_NoneType; +} + +void zephyr_display_display_collect_ptrs(zephyr_display_display_obj_t *self) { + (void)self; + displayio_display_core_collect_ptrs(&self->core); +} + +void zephyr_display_display_reset(zephyr_display_display_obj_t *self) { + if (self->device != NULL && device_is_ready(self->device)) { + common_hal_zephyr_display_display_set_auto_refresh(self, true); + displayio_display_core_set_root_group(&self->core, &circuitpython_splash); + self->core.full_refresh = true; + } else { + release_zephyr_display(self); + } +} + +mp_obj_t common_hal_zephyr_display_display_get_root_group(zephyr_display_display_obj_t *self) { + if (self->core.current_group == NULL) { + return mp_const_none; + } + return self->core.current_group; +} + +bool common_hal_zephyr_display_display_set_root_group(zephyr_display_display_obj_t *self, displayio_group_t *root_group) { + return displayio_display_core_set_root_group(&self->core, root_group); +} diff --git a/ports/zephyr-cp/common-hal/zephyr_display/legacy/Display.h b/ports/zephyr-cp/common-hal/zephyr_display/legacy/Display.h new file mode 100644 index 00000000000..bdec1e96ba5 --- /dev/null +++ b/ports/zephyr-cp/common-hal/zephyr_display/legacy/Display.h @@ -0,0 +1,31 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include + +#include "py/obj.h" +#include "shared-module/displayio/display_core.h" + +typedef struct { + mp_obj_base_t base; + displayio_display_core_t core; + const struct device *device; + struct display_capabilities capabilities; + enum display_pixel_format pixel_format; + uint64_t last_refresh_call; + uint16_t native_frames_per_second; + uint16_t native_ms_per_frame; + bool auto_refresh; + bool first_manual_refresh; +} zephyr_display_display_obj_t; + +void zephyr_display_display_background(zephyr_display_display_obj_t *self); +void zephyr_display_display_collect_ptrs(zephyr_display_display_obj_t *self); +void zephyr_display_display_reset(zephyr_display_display_obj_t *self); +void release_zephyr_display(zephyr_display_display_obj_t *self); diff --git a/ports/zephyr-cp/common-hal/zephyr_display/lvgl/Display.c b/ports/zephyr-cp/common-hal/zephyr_display/lvgl/Display.c new file mode 100644 index 00000000000..cd2b6f57508 --- /dev/null +++ b/ports/zephyr-cp/common-hal/zephyr_display/lvgl/Display.c @@ -0,0 +1,793 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "bindings/zephyr_display/Display.h" + +#include + +#include "bindings/zephyr_kernel/__init__.h" +#include "py/gc.h" +#include "py/runtime.h" +#include "shared-bindings/time/__init__.h" +#include "shared-module/displayio/__init__.h" +#include "shared-module/displayio/ColorConverter.h" +#include "supervisor/shared/display.h" +#include "supervisor/shared/tick.h" + + +#include +#include +#include +#include + +#include "lvgl/draw/lv_draw_utils.h" +#include "lvgl_private.h" + +#include "shared-bindings/displayio/Group.h" +#include "shared-module/displayio/lvgl/lvgl_internal.h" +#include "shared-bindings/displayio/__init__.h" + +// Display objects live in displayio's static slot registry. Each slot owns its LVGL +// display and buffers until release_displays(); soft reload keeps the primary slot. + +#if defined(CONFIG_LV_Z_RUN_LVGL_ON_WORKQUEUE) +// The Zephyr LVGL glue creates its display during SYS_INIT from the driver's current +// pixel format. If that format is monochrome, the glue's flush callback expects a +// conversion buffer that it only allocates when LVGL itself is built at 1bpp (which it +// isn't when the panel format is chosen at runtime). Pause rendering until CircuitPython +// has recreated the display with the matching buffers; running the workqueue before that +// flushes through a NULL conversion buffer. +static int zephyr_display_lvgl_pause_rendering(void) { + lvgl_timer_handler_pause(); + return 0; +} +SYS_INIT(zephyr_display_lvgl_pause_rendering, APPLICATION, 0); +#endif + +// LVGL is initialized by the Zephyr glue at boot. +void displayio_lvgl_port_init(void) { +} + +// The LVGL compositor's port hooks: the RTOS renders LVGL on its workqueue thread, and +// CircuitPython-side mirror mutations take the glue's LVGL lock. +void displayio_lvgl_port_lock(void) { + lvgl_lock(); +} + +void displayio_lvgl_port_unlock(void) { + lvgl_unlock(); +} + +void displayio_lvgl_port_install_busdisplay_refresh(lv_display_t *display) { + // The Zephyr glue flushes every display on the LVGL workqueue, including BusDisplay. + LV_UNUSED(display); +} + +void displayio_lvgl_port_frame_boundary(void) { + // No Zephyr framebuffer exposes a frame callback yet. If one does, this must be made ISR + // safe (for example by scheduling the refresh on the LVGL workqueue). + displayio_lvgl_refresh_paced_displays(); +} + +static void zephyr_display_lvgl_flush_argb_alpha0(lv_display_t *display, const lv_area_t *area, + uint8_t *px_map) { + // The legacy compositor's transfer buffer for 32-bit displays carried no alpha + // channel (0x00RRGGBB), which the SDL capture surfaces as its transparency grid. + // Match that: clear the alpha byte of every pixel before handing the buffer to the + // glue's 32-bit flush. + uint32_t size = (uint32_t)(area->x2 - area->x1 + 1) * (uint32_t)(area->y2 - area->y1 + 1); + for (uint32_t i = 0; i < size; i++) { + px_map[i * 4 + 3] = 0x00; + } + lvgl_flush_cb_32bit(display, area, px_map); +} + +static void zephyr_display_lvgl_flush_565x(lv_display_t *display, const lv_area_t *area, + uint8_t *px_map) { + // The driver for RGB_565X panels reads big-endian pixels. Keep LVGL's buffer in + // plain RGB565 and swap on the way out (mirrors the legacy colorspace-level swap). + uint32_t size = (uint32_t)(area->x2 - area->x1 + 1) * (uint32_t)(area->y2 - area->y1 + 1); + uint16_t *px = (uint16_t *)px_map; + for (uint32_t i = 0; i < size; i++) { + px[i] = (uint16_t)((px[i] << 8) | (px[i] >> 8)); + } + lvgl_flush_cb_16bit(display, area, px_map); +} + +// LVGL borrows user_data and render buffers; lv_display_delete() does not free them. +// Keep our allocations together and release them on every delete, including failed setup. +typedef struct { + struct lvgl_disp_data driver; + void *buf; + // Grayscale and mono displays render through LVGL in RGB888 so the transfer can use + // displayio's luminance coefficients (which the legacy compositor uses). + void *flush_buf; + // The Zephyr glue's flush callbacks copy rendered areas straight to the display and + // don't rotate them. When the display is rotated, the rendered partial buffer is + // rotated into this scratch buffer before the glue callback runs. + void *rotation_buf; + uint32_t rotation_buf_size; + lv_display_flush_cb_t base_flush_cb; +} circuitpython_lvgl_display_data_t; + +static void zephyr_display_rotate_i1(const uint8_t *src, uint8_t *dest, + int32_t width, int32_t height, int32_t rotated_height, + uint32_t src_stride, uint32_t dest_stride, lv_display_rotation_t rotation) { + // I1 buffers start with the two-entry palette, and the glue's mono flush strips it + // itself, so keep the header at the front of the rotated buffer. + const uint32_t palette_size = LV_COLOR_INDEXED_PALETTE_SIZE(LV_COLOR_FORMAT_I1) * 4; + memcpy(dest, src, palette_size); + const uint8_t *src_bits = src + palette_size; + uint8_t *dest_bits = dest + palette_size; + memset(dest_bits, 0, (size_t)dest_stride * rotated_height); + + for (int32_t y = 0; y < height; y++) { + for (int32_t x = 0; x < width; x++) { + uint8_t bit = (src_bits[y * src_stride + x / 8] >> (7 - (x % 8))) & 1; + if (bit == 0) { + continue; + } + int32_t dest_x; + int32_t dest_y; + switch (rotation) { + case LV_DISPLAY_ROTATION_90: + dest_x = y; + dest_y = width - 1 - x; + break; + case LV_DISPLAY_ROTATION_270: + dest_x = height - 1 - y; + dest_y = x; + break; + default: // LV_DISPLAY_ROTATION_180 + dest_x = width - 1 - x; + dest_y = height - 1 - y; + break; + } + dest_bits[dest_y * dest_stride + dest_x / 8] |= 1 << (7 - (dest_x % 8)); + } + } +} + +static void zephyr_display_lvgl_rotate_flush(lv_display_t *display, const lv_area_t *area, + uint8_t *px_map) { + circuitpython_lvgl_display_data_t *data = lv_display_get_user_data(display); + if (data->base_flush_cb == NULL) { + return; + } + lv_display_rotation_t rotation = lv_display_get_rotation(display); + if (rotation == LV_DISPLAY_ROTATION_0) { + data->base_flush_cb(display, area, px_map); + return; + } + + lv_color_format_t color_format = lv_display_get_color_format(display); + int32_t width = lv_area_get_width(area); + int32_t height = lv_area_get_height(area); + lv_area_t rotated_area = *area; + lv_display_rotate_area(display, &rotated_area); + int32_t rotated_width = lv_area_get_width(&rotated_area); + int32_t rotated_height = lv_area_get_height(&rotated_area); + uint32_t src_stride = lv_draw_buf_width_to_stride(width, color_format); + uint32_t dest_stride = lv_draw_buf_width_to_stride(rotated_width, color_format); + uint32_t palette_size = LV_COLOR_INDEXED_PALETTE_SIZE(color_format) * 4; + + if ((size_t)dest_stride * rotated_height + palette_size > data->rotation_buf_size) { + // Don't fall back to writing the unrotated buffer: it would land at the wrong + // physical coordinates. Skipping the flush is safer than overflowing the buffer. + lv_display_flush_ready(display); + return; + } + + if (color_format == LV_COLOR_FORMAT_I1) { + zephyr_display_rotate_i1(px_map, data->rotation_buf, width, height, + rotated_height, src_stride, dest_stride, rotation); + } else { + // LVGL's rotate only lists core formats. RGB565_SWAPPED and AL88 use the same + // 16-bit pixel layout for the purpose of moving pixels around. + lv_color_format_t rotate_format = color_format; + if (rotate_format == LV_COLOR_FORMAT_RGB565_SWAPPED || + rotate_format == LV_COLOR_FORMAT_AL88) { + rotate_format = LV_COLOR_FORMAT_RGB565; + } + lv_draw_rotate(px_map, data->rotation_buf, width, height, + src_stride, dest_stride, rotation, rotate_format); + } + + data->base_flush_cb(display, &rotated_area, data->rotation_buf); +} + +static void zephyr_display_lvgl_delete_cb(lv_event_t *event) { + circuitpython_lvgl_display_data_t *data = lv_event_get_user_data(event); + lv_free(data->rotation_buf); + lv_free(data->flush_buf); + lv_free(data->buf); + lv_free(data); +} + +// LVGL has merged the invalidated areas into the list it is about to redraw. +static void zephyr_display_lvgl_print_dirty_cb(lv_event_t *event) { + lv_display_t *display = lv_event_get_target(event); + for (uint32_t i = 0; i < display->inv_p; i++) { + if (display->inv_area_joined[i]) { + continue; + } + const lv_area_t *area = &display->inv_areas[i]; + printk("lvgl dirty %d %d %d %d\n", (int)area->x1, (int)area->y1, (int)area->x2, + (int)area->y2); + } +} + +// Grayscale and mono panels need the same luminance calculation as the legacy +// compositor. LVGL's own conversion uses different coefficients, so render those +// displays in RGB888 and convert the flushed pixels with displayio's routine. +static void zephyr_display_lvgl_flush_luma(lv_display_t *display, const lv_area_t *area, + uint8_t *px_map) { + circuitpython_lvgl_display_data_t *data = lv_display_get_user_data(display); + const struct display_capabilities *cap = &data->driver.cap; + uint16_t width = lv_area_get_width(area); + uint16_t height = lv_area_get_height(area); + uint32_t pixel_count = (uint32_t)width * (uint32_t)height; + uint32_t src_stride = lv_draw_buf_width_to_stride(width, LV_COLOR_FORMAT_RGB888); + uint8_t *out = data->flush_buf; + struct display_buffer_descriptor desc = { + .width = width, + .pitch = width, + .height = height, + .frame_incomplete = !lv_display_flush_is_last(display), + }; + + if (cap->current_pixel_format == PIXEL_FORMAT_L_8 || + cap->current_pixel_format == PIXEL_FORMAT_AL_88) { + uint8_t *dest = out; + for (uint16_t y = 0; y < height; y++) { + const uint8_t *src = px_map + (uint32_t)y * src_stride; + for (uint16_t x = 0; x < width; x++) { + // LVGL's RGB888 is stored in memory as B, G, R. + uint8_t luma = displayio_colorconverter_compute_luma( + (uint32_t)src[x * 3 + 2] << 16 | + (uint32_t)src[x * 3 + 1] << 8 | + src[x * 3]); + *dest++ = luma; + if (cap->current_pixel_format == PIXEL_FORMAT_AL_88) { + *dest++ = 0xff; + } + } + } + desc.buf_size = pixel_count * + (cap->current_pixel_format == PIXEL_FORMAT_AL_88 ? 2 : 1); + } else { + // Pack the luminance into the display's row- or column-major 1bpp layout, + // matching the Zephyr glue's mono conversion. + uint32_t out_size = (pixel_count + 7) / 8; + bool vtiled = cap->screen_info & SCREEN_INFO_MONO_VTILED; + bool msb_first = cap->screen_info & SCREEN_INFO_MONO_MSB_FIRST; + #ifdef CONFIG_LV_Z_COLOR_MONO_HW_INVERSION + uint8_t clear_color = 0x00; + #else + uint8_t clear_color = cap->current_pixel_format == PIXEL_FORMAT_MONO01 ? 0x00 : 0xff; + #endif + memset(out, clear_color, out_size); + for (uint16_t y = 0; y < height; y++) { + const uint8_t *src = px_map + (uint32_t)y * src_stride; + for (uint16_t x = 0; x < width; x++) { + uint8_t luma = displayio_colorconverter_compute_luma( + (uint32_t)src[x * 3 + 2] << 16 | + (uint32_t)src[x * 3 + 1] << 8 | + src[x * 3]); + if (luma < 128) { + continue; + } + uint32_t bit; + uint8_t *byte; + if (vtiled) { + bit = msb_first ? 7 - (y % 8) : y % 8; + byte = &out[x + (y / 8) * width]; + } else { + bit = msb_first ? 7 - (x % 8) : x % 8; + byte = &out[x / 8 + y * (width / 8)]; + } + #ifdef CONFIG_LV_Z_COLOR_MONO_HW_INVERSION + *byte |= 1 << bit; + #else + if (cap->current_pixel_format == PIXEL_FORMAT_MONO01) { + *byte |= 1 << bit; + } else { + *byte &= ~(1 << bit); + } + #endif + } + } + desc.buf_size = out_size; + desc.pitch = width; + } + + const bool is_epd = cap->screen_info & SCREEN_INFO_EPD; + const bool is_last = lv_display_flush_is_last(display); + if (is_epd && !data->driver.blanking_on && !is_last) { + display_blanking_on(data->driver.display_dev); + data->driver.blanking_on = true; + } + display_write(data->driver.display_dev, area->x1, area->y1, &desc, out); + if (cap->screen_info & SCREEN_INFO_DOUBLE_BUFFER) { + display_write(data->driver.display_dev, area->x1, area->y1, &desc, out); + } + if (is_epd && is_last && data->driver.blanking_on) { + display_blanking_off(data->driver.display_dev); + data->driver.blanking_on = false; + } + lv_display_flush_ready(display); +} + +// Recreate the default LVGL display for the (possibly newly selected) driver pixel format, +// mirroring the glue's lvgl_init() display setup. The caller holds the LVGL lock. +static int zephyr_display_lvgl_recreate_display(zephyr_display_display_obj_t *self) { + lv_display_t *old = lv_display_get_default(); + if (old != NULL) { + lv_display_delete(old); + } + + lv_display_t *display = lv_display_create(self->capabilities.x_resolution, + self->capabilities.y_resolution); + if (display == NULL) { + return -ENOMEM; + } + + circuitpython_lvgl_display_data_t *data = lv_malloc_zeroed(sizeof(*data)); + if (data == NULL) { + lv_display_delete(display); + return -ENOMEM; + } + lv_display_add_event_cb(display, zephyr_display_lvgl_delete_cb, LV_EVENT_DELETE, data); + if (IS_ENABLED(CONFIG_CIRCUITPY_LVGL_PRINT_DIRTY_AREAS)) { + lv_display_add_event_cb(display, zephyr_display_lvgl_print_dirty_cb, LV_EVENT_RENDER_START, + NULL); + } + data->driver.display_dev = self->device; + display_get_capabilities(self->device, &data->driver.cap); + lv_display_set_user_data(display, &data->driver); + + int result = set_lvgl_rendering_cb(display); + // The glue rejects monochrome unless LVGL itself renders 1bpp, and returns before + // adding its rounder. The luma flush below renders it instead and packs 8 pixels + // per byte, so areas still need rounding to whole bytes. + if (result == -ENOTSUP && (self->pixel_format == PIXEL_FORMAT_MONO01 || + self->pixel_format == PIXEL_FORMAT_MONO10)) { + lv_display_add_event_cb(display, lvgl_rounder_cb_mono, LV_EVENT_INVALIDATE_AREA, display); + result = 0; + } + if (result != 0) { + lv_display_delete(display); + return result; + } + + // Override the glue's flush choice where the legacy-compatible transfer differs. + bool legacy_luma = self->pixel_format == PIXEL_FORMAT_L_8 || + self->pixel_format == PIXEL_FORMAT_AL_88 || + self->pixel_format == PIXEL_FORMAT_MONO01 || + self->pixel_format == PIXEL_FORMAT_MONO10; + if (legacy_luma) { + // Render in RGB888, then convert with displayio's luminance coefficients in + // zephyr_display_lvgl_flush_luma(). + lv_display_set_color_format(display, LV_COLOR_FORMAT_RGB888); + lv_display_set_flush_cb(display, zephyr_display_lvgl_flush_luma); + } else if (self->pixel_format == PIXEL_FORMAT_RGB_565X) { + lv_display_set_color_format(display, LV_COLOR_FORMAT_RGB565); + lv_display_set_flush_cb(display, zephyr_display_lvgl_flush_565x); + } else if (self->pixel_format == PIXEL_FORMAT_ABGR_8888 || + self->pixel_format == PIXEL_FORMAT_BGRA_8888) { + // Legacy treated ABGR/BGRA as 32-bit passthrough without alpha as well. + lv_display_set_flush_cb(display, zephyr_display_lvgl_flush_argb_alpha0); + } else if (self->pixel_format == PIXEL_FORMAT_ARGB_8888) { + lv_display_set_flush_cb(display, zephyr_display_lvgl_flush_argb_alpha0); + } + + // Partial-render-mode buffer, sized like the glue does. + uint16_t hor_res = lv_display_get_horizontal_resolution(display); + uint16_t ver_res = lv_display_get_vertical_resolution(display); + uint32_t buf_nbr_pixels = (CONFIG_LV_Z_VDB_SIZE * hor_res * ver_res) / 100; + if (buf_nbr_pixels < hor_res) { + buf_nbr_pixels = hor_res; + } + uint32_t buf_size; + bool al88 = self->pixel_format == PIXEL_FORMAT_AL_88; + switch (self->pixel_format) { + case PIXEL_FORMAT_ARGB_8888: + case PIXEL_FORMAT_ABGR_8888: + buf_size = 4 * buf_nbr_pixels; + break; + case PIXEL_FORMAT_RGB_888: + case PIXEL_FORMAT_BGR_888: + buf_size = 3 * buf_nbr_pixels; + break; + case PIXEL_FORMAT_RGB_565: + case PIXEL_FORMAT_RGB_565X: + buf_size = 2 * buf_nbr_pixels; + break; + case PIXEL_FORMAT_L_8: + buf_size = buf_nbr_pixels; + break; + case PIXEL_FORMAT_MONO01: + case PIXEL_FORMAT_MONO10: + buf_size = buf_nbr_pixels / 8 + 8; + buf_size += (buf_nbr_pixels % 8) == 0 ? 0 : 1; + break; + default: + buf_size = 2 * buf_nbr_pixels; + break; + } + if (legacy_luma) { + // The temporary RGB888 render buffer. + buf_size = 3 * buf_nbr_pixels; + } else if (al88) { + buf_size = 2 * buf_nbr_pixels; + } + + data->buf = lv_malloc(buf_size); + if (data->buf == NULL) { + lv_display_delete(display); + return -ENOMEM; + } + lv_display_set_buffers(display, data->buf, NULL, buf_size, LV_DISPLAY_RENDER_MODE_PARTIAL); + + if (legacy_luma) { + uint32_t flush_buf_size = buf_nbr_pixels; + if (al88) { + flush_buf_size *= 2; + } else if (self->pixel_format == PIXEL_FORMAT_MONO01 || + self->pixel_format == PIXEL_FORMAT_MONO10) { + flush_buf_size = buf_nbr_pixels / 8 + 8; + } + data->flush_buf = lv_malloc(flush_buf_size); + if (data->flush_buf == NULL) { + lv_display_delete(display); + return -ENOMEM; + } + } + + // A rotated flush has the same number of pixels as the rendered area, but may need + // the I1 palette header in front of the pixel data. + data->rotation_buf_size = buf_size + LV_COLOR_INDEXED_PALETTE_SIZE(LV_COLOR_FORMAT_I1) * 4; + data->rotation_buf = lv_malloc(data->rotation_buf_size); + if (data->rotation_buf == NULL) { + lv_display_delete(display); + return -ENOMEM; + } + + data->base_flush_cb = lv_display_get_flush_cb(display); + lv_display_set_flush_cb(display, zephyr_display_lvgl_rotate_flush); + + self->lv_display = display; + return 0; +} + + + +static enum display_pixel_format zephyr_display_select_pixel_format(const struct display_capabilities *caps) { + uint32_t formats = caps->supported_pixel_formats; + + if (formats & PIXEL_FORMAT_RGB_565) { + return PIXEL_FORMAT_RGB_565; + } + if (formats & PIXEL_FORMAT_RGB_888) { + return PIXEL_FORMAT_RGB_888; + } + if (formats & PIXEL_FORMAT_ARGB_8888) { + return PIXEL_FORMAT_ARGB_8888; + } + if (formats & PIXEL_FORMAT_RGB_565X) { + return PIXEL_FORMAT_RGB_565X; + } + if (formats & PIXEL_FORMAT_L_8) { + return PIXEL_FORMAT_L_8; + } + if (formats & PIXEL_FORMAT_AL_88) { + return PIXEL_FORMAT_AL_88; + } + if (formats & PIXEL_FORMAT_MONO01) { + return PIXEL_FORMAT_MONO01; + } + if (formats & PIXEL_FORMAT_MONO10) { + return PIXEL_FORMAT_MONO10; + } + return caps->current_pixel_format; +} + +static void zephyr_display_select_colorspace(zephyr_display_display_obj_t *self, + uint16_t *color_depth, + uint8_t *bytes_per_cell, + bool *grayscale, + bool *pixels_in_byte_share_row, + bool *reverse_pixels_in_byte, + bool *reverse_bytes_in_word) { + *color_depth = 16; + *bytes_per_cell = 2; + *grayscale = false; + *pixels_in_byte_share_row = false; + *reverse_pixels_in_byte = false; + *reverse_bytes_in_word = false; + + if (self->pixel_format == PIXEL_FORMAT_RGB_565X) { + // RGB_565X is big-endian RGB_565, so byte-swap from native LE. + *reverse_bytes_in_word = true; + } else if (self->pixel_format == PIXEL_FORMAT_RGB_888) { + *color_depth = 24; + *bytes_per_cell = 3; + *reverse_bytes_in_word = false; + } else if (self->pixel_format == PIXEL_FORMAT_ARGB_8888) { + *color_depth = 32; + *bytes_per_cell = 4; + *reverse_bytes_in_word = false; + } else if (self->pixel_format == PIXEL_FORMAT_L_8 || + self->pixel_format == PIXEL_FORMAT_AL_88) { + *color_depth = 8; + *bytes_per_cell = 1; + *grayscale = true; + *reverse_bytes_in_word = false; + } else if (self->pixel_format == PIXEL_FORMAT_MONO01 || + self->pixel_format == PIXEL_FORMAT_MONO10) { + bool vtiled = self->capabilities.screen_info & SCREEN_INFO_MONO_VTILED; + bool msb_first = self->capabilities.screen_info & SCREEN_INFO_MONO_MSB_FIRST; + *color_depth = 1; + *bytes_per_cell = 1; + *grayscale = true; + *pixels_in_byte_share_row = !vtiled; + *reverse_pixels_in_byte = msb_first; + *reverse_bytes_in_word = false; + } +} + +void common_hal_zephyr_display_display_construct_from_device(zephyr_display_display_obj_t *self, + const struct device *device, + uint16_t rotation, + bool auto_refresh) { + self->auto_refresh = false; + self->lv_display = NULL; + + if (device == NULL || !device_is_ready(device)) { + raise_zephyr_error(-ENODEV); + } + + self->device = device; + display_get_capabilities(self->device, &self->capabilities); + + // Lock for the whole LVGL setup: the workqueue may already be running timers. + nlr_jump_callback_node_t cleanup; + displayio_lvgl_lock_with_cleanup(&cleanup); + // Pick the pixel format exactly like the legacy compositor does (RGB565 preferred). + self->pixel_format = zephyr_display_select_pixel_format(&self->capabilities); + if (self->pixel_format != self->capabilities.current_pixel_format) { + (void)display_set_pixel_format(self->device, self->pixel_format); + display_get_capabilities(self->device, &self->capabilities); + self->pixel_format = self->capabilities.current_pixel_format; + } + // The LVGL display glue configured itself from the driver's original current format at + // boot. Recreate the LVGL display so its buffers and flush callbacks match the format + // actually selected above. + int result = zephyr_display_lvgl_recreate_display(self); + if (result != 0) { + self->device = NULL; + self->base.type = &mp_type_NoneType; + raise_zephyr_error(result); + } + + uint16_t color_depth; + uint8_t bytes_per_cell; + bool grayscale; + bool pixels_in_byte_share_row; + bool reverse_pixels_in_byte; + bool reverse_bytes_in_word; + zephyr_display_select_colorspace(self, &color_depth, &bytes_per_cell, + &grayscale, &pixels_in_byte_share_row, &reverse_pixels_in_byte, + &reverse_bytes_in_word); + + displayio_display_core_construct( + &self->core, + self->capabilities.x_resolution, + self->capabilities.y_resolution, + 0, + color_depth, + grayscale, + pixels_in_byte_share_row, + bytes_per_cell, + reverse_pixels_in_byte, + reverse_bytes_in_word); + + self->native_frames_per_second = 60; + self->native_ms_per_frame = 1000 / self->native_frames_per_second; + self->first_manual_refresh = !auto_refresh; + + if (rotation != 0) { + common_hal_zephyr_display_display_set_rotation(self, rotation); + } + + (void)display_blanking_off(self->device); + + displayio_lvgl_init(); + displayio_lvgl_register_display(lv_display_get_default()); + + displayio_display_core_set_root_group(&self->core, &circuitpython_splash); + displayio_lvgl_set_root_group(&circuitpython_splash); + displayio_lvgl_unlock_with_cleanup(); + #if defined(CONFIG_LV_Z_RUN_LVGL_ON_WORKQUEUE) + // Buffers and flush callbacks now match the panel; let the workqueue render. + lvgl_timer_handler_resume(); + #endif + common_hal_zephyr_display_display_set_auto_refresh(self, auto_refresh); +} + +uint16_t common_hal_zephyr_display_display_get_width(zephyr_display_display_obj_t *self) { + return displayio_display_core_get_width(&self->core); +} + +uint16_t common_hal_zephyr_display_display_get_height(zephyr_display_display_obj_t *self) { + return displayio_display_core_get_height(&self->core); +} + +mp_float_t common_hal_zephyr_display_display_get_brightness(zephyr_display_display_obj_t *self) { + (void)self; + return -1; +} + +bool common_hal_zephyr_display_display_set_brightness(zephyr_display_display_obj_t *self, mp_float_t brightness) { + (void)self; + (void)brightness; + return false; +} + + +void common_hal_zephyr_display_display_set_rotation(zephyr_display_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) { + int tmp = self->core.width; + self->core.width = self->core.height; + self->core.height = tmp; + } + + displayio_display_core_set_rotation(&self->core, rotation); + + nlr_jump_callback_node_t cleanup; + displayio_lvgl_lock_with_cleanup(&cleanup); + + if (self->lv_display != NULL) { + // LVGL maps the logical (rotated) coordinates to the panel's physical orientation + // while flushing; the port's rotate flush callback moves the pixels into place. + // LVGL rotates the opposite way from displayio for the transposed orientations. + lv_display_rotation_t lv_rotation; + switch (rotation) { + case 90: + lv_rotation = LV_DISPLAY_ROTATION_270; + break; + case 270: + lv_rotation = LV_DISPLAY_ROTATION_90; + break; + case 180: + lv_rotation = LV_DISPLAY_ROTATION_180; + break; + default: + lv_rotation = LV_DISPLAY_ROTATION_0; + break; + } + lv_display_set_rotation(self->lv_display, lv_rotation); + lv_display_set_default(self->lv_display); + } + + if (self == &displays[0].zephyr_display) { + supervisor_stop_terminal(); + supervisor_start_terminal(self->core.width, self->core.height); + } + + if (self->core.current_group != NULL) { + displayio_lvgl_set_root_group(self->core.current_group); + } + lv_obj_t *screen = lv_screen_active(); + if (screen != NULL) { + lv_obj_invalidate(screen); + } + + displayio_lvgl_unlock_with_cleanup(); +} + +uint16_t common_hal_zephyr_display_display_get_rotation(zephyr_display_display_obj_t *self) { + return self->core.rotation; +} + +bool common_hal_zephyr_display_display_refresh(zephyr_display_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 != NO_FPS_LIMIT)) { + uint64_t current_time = supervisor_ticks_ms64(); + uint32_t current_ms_since_real_refresh = current_time - self->core.last_refresh; + if (current_ms_since_real_refresh > maximum_ms_per_real_frame) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Below minimum frame rate")); + } + uint32_t current_ms_since_last_call = current_time - self->last_refresh_call; + self->last_refresh_call = current_time; + if (current_ms_since_last_call > target_ms_per_frame) { + return false; + } + uint32_t remaining_time = target_ms_per_frame - (current_ms_since_real_refresh % target_ms_per_frame); + while (supervisor_ticks_ms64() - self->last_refresh_call < remaining_time) { + RUN_BACKGROUND_TASKS; + } + } + self->first_manual_refresh = false; + self->core.last_refresh = supervisor_ticks_ms64(); + // Manual refresh must render immediately, not on LVGL's timer cadence. The + // workqueue's own handler already holds the lock, so no re-entrancy here. + lvgl_lock(); + lv_refr_now(lv_display_get_default()); + lvgl_unlock(); + return true; +} + +bool common_hal_zephyr_display_display_get_auto_refresh(zephyr_display_display_obj_t *self) { + return self->auto_refresh; +} + +void common_hal_zephyr_display_display_set_auto_refresh(zephyr_display_display_obj_t *self, bool auto_refresh) { + self->first_manual_refresh = !auto_refresh; + if (auto_refresh != self->auto_refresh) { + if (auto_refresh) { + supervisor_enable_tick(); + } else { + supervisor_disable_tick(); + } + } + self->auto_refresh = auto_refresh; +} + +void zephyr_display_display_background(zephyr_display_display_obj_t *self) { + // LVGL renders on its own RTOS thread (the LVGL workqueue), so the CircuitPython + // background task has nothing to pump. + (void)self; +} + +void release_zephyr_display(zephyr_display_display_obj_t *self) { + common_hal_zephyr_display_display_set_auto_refresh(self, false); + nlr_jump_callback_node_t cleanup; + displayio_lvgl_lock_with_cleanup(&cleanup); + displayio_lvgl_set_root_group(NULL); + if (self->lv_display != NULL) { + lv_display_delete(self->lv_display); + self->lv_display = NULL; + } + release_display_core(&self->core); + self->device = NULL; + self->base.type = &mp_type_NoneType; + displayio_lvgl_unlock_with_cleanup(); +} + +void zephyr_display_display_collect_ptrs(zephyr_display_display_obj_t *self) { + (void)self; + displayio_display_core_collect_ptrs(&self->core); +} + +void zephyr_display_display_reset(zephyr_display_display_obj_t *self) { + if (self->device != NULL && device_is_ready(self->device)) { + common_hal_zephyr_display_display_set_auto_refresh(self, true); + displayio_display_core_set_root_group(&self->core, &circuitpython_splash); + displayio_lvgl_set_root_group(&circuitpython_splash); + displayio_lvgl_lock(); + lv_refr_now(lv_display_get_default()); + displayio_lvgl_unlock(); + } else { + release_zephyr_display(self); + } +} + +mp_obj_t common_hal_zephyr_display_display_get_root_group(zephyr_display_display_obj_t *self) { + if (self->core.current_group == NULL) { + return mp_const_none; + } + return self->core.current_group; +} + +bool common_hal_zephyr_display_display_set_root_group(zephyr_display_display_obj_t *self, displayio_group_t *root_group) { + bool ok = displayio_display_core_set_root_group(&self->core, root_group); + displayio_lvgl_set_root_group(ok ? root_group : NULL); + return ok; +} diff --git a/ports/zephyr-cp/common-hal/zephyr_display/lvgl/Display.h b/ports/zephyr-cp/common-hal/zephyr_display/lvgl/Display.h new file mode 100644 index 00000000000..50efe626da4 --- /dev/null +++ b/ports/zephyr-cp/common-hal/zephyr_display/lvgl/Display.h @@ -0,0 +1,33 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include + +#include "py/obj.h" +#include "lvgl.h" +#include "shared-module/displayio/display_core.h" + +typedef struct { + mp_obj_base_t base; + displayio_display_core_t core; + lv_display_t *lv_display; + const struct device *device; + struct display_capabilities capabilities; + enum display_pixel_format pixel_format; + uint64_t last_refresh_call; + uint16_t native_frames_per_second; + uint16_t native_ms_per_frame; + bool auto_refresh; + bool first_manual_refresh; +} zephyr_display_display_obj_t; + +void zephyr_display_display_background(zephyr_display_display_obj_t *self); +void zephyr_display_display_collect_ptrs(zephyr_display_display_obj_t *self); +void zephyr_display_display_reset(zephyr_display_display_obj_t *self); +void release_zephyr_display(zephyr_display_display_obj_t *self); diff --git a/ports/zephyr-cp/common-hal/zephyr_i2c/I2C.c b/ports/zephyr-cp/common-hal/zephyr_i2c/I2C.c deleted file mode 100644 index d5bb0d44669..00000000000 --- a/ports/zephyr-cp/common-hal/zephyr_i2c/I2C.c +++ /dev/null @@ -1,92 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2019 Dan Halbert for Adafruit Industries -// SPDX-FileCopyrightText: Copyright (c) 2018 Artur Pacholec -// SPDX-FileCopyrightText: Copyright (c) 2017 hathach -// SPDX-FileCopyrightText: Copyright (c) 2016 Sandeep Mistry All right reserved. -// -// SPDX-License-Identifier: MIT - -#include "shared-bindings/busio/I2C.h" -#include "shared-bindings/microcontroller/__init__.h" -#include "shared-bindings/microcontroller/Pin.h" -#include "supervisor/shared/tick.h" -#include "py/mperrno.h" -#include "py/runtime.h" - - -void common_hal_busio_i2c_never_reset(busio_i2c_obj_t *self) { - // never_reset_pin_number(self->scl_pin_number); - // never_reset_pin_number(self->sda_pin_number); -} - -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) { - -} - -bool common_hal_busio_i2c_deinited(busio_i2c_obj_t *self) { - // return self->sda_pin_number == NO_PIN; - return true; -} - -void common_hal_busio_i2c_deinit(busio_i2c_obj_t *self) { - if (common_hal_busio_i2c_deinited(self)) { - return; - } - - // nrfx_twim_uninit(&self->twim_peripheral->twim); - - // reset_pin_number(self->sda_pin_number); - // reset_pin_number(self->scl_pin_number); - - // self->twim_peripheral->in_use = false; - // common_hal_busio_i2c_mark_deinit(self); -} - -void common_hal_busio_i2c_mark_deinit(busio_i2c_obj_t *self) { - // self->sda_pin_number = NO_PIN; -} - -// nrfx_twim_tx doesn't support 0-length data so we fall back to the hal API -bool common_hal_busio_i2c_probe(busio_i2c_obj_t *self, uint8_t addr) { - bool found = true; - - return found; -} - -bool common_hal_busio_i2c_try_lock(busio_i2c_obj_t *self) { - if (common_hal_busio_i2c_deinited(self)) { - return false; - } - bool grabbed_lock = false; - return grabbed_lock; -} - -bool common_hal_busio_i2c_has_lock(busio_i2c_obj_t *self) { - return self->has_lock; -} - -void common_hal_busio_i2c_unlock(busio_i2c_obj_t *self) { - self->has_lock = false; -} - -uint8_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t addr, const uint8_t *data, size_t len) { - return 0; -} - -uint8_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t addr, uint8_t *data, size_t len) { - if (len == 0) { - return 0; - } - -} - -uint8_t common_hal_busio_i2c_write_read(busio_i2c_obj_t *self, uint16_t addr, - uint8_t *out_data, size_t out_len, uint8_t *in_data, size_t in_len) { - uint8_t result = _common_hal_busio_i2c_write(self, addr, out_data, out_len, false); - if (result != 0) { - return result; - } - - return common_hal_busio_i2c_read(self, addr, in_data, in_len); -} diff --git a/ports/zephyr-cp/common-hal/zephyr_i2c/I2C.h b/ports/zephyr-cp/common-hal/zephyr_i2c/I2C.h deleted file mode 100644 index 22e9251b3f1..00000000000 --- a/ports/zephyr-cp/common-hal/zephyr_i2c/I2C.h +++ /dev/null @@ -1,17 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2016 Scott Shawcroft -// -// SPDX-License-Identifier: MIT - -#pragma once - -#include "py/obj.h" - -typedef struct { - mp_obj_base_t base; - // twim_peripheral_t *twim_peripheral; - bool has_lock; - uint8_t scl_pin_number; - uint8_t sda_pin_number; -} busio_i2c_obj_t; diff --git a/ports/zephyr-cp/common-hal/zephyr_i2c/__init__.c b/ports/zephyr-cp/common-hal/zephyr_i2c/__init__.c deleted file mode 100644 index db93a442f04..00000000000 --- a/ports/zephyr-cp/common-hal/zephyr_i2c/__init__.c +++ /dev/null @@ -1,7 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2024 Adafruit Industries LLC -// -// SPDX-License-Identifier: MIT - -// No zephyr_i2c module functions. diff --git a/ports/zephyr-cp/common-hal/zephyr_kernel/__init__.c b/ports/zephyr-cp/common-hal/zephyr_kernel/__init__.c index 042f06b0ed2..178f33e028d 100644 --- a/ports/zephyr-cp/common-hal/zephyr_kernel/__init__.c +++ b/ports/zephyr-cp/common-hal/zephyr_kernel/__init__.c @@ -6,11 +6,15 @@ #include "bindings/zephyr_kernel/__init__.h" #include "py/runtime.h" +#include #include - +#include void raise_zephyr_error(int err) { + if (err == 0) { + return; + } switch (-err) { case EALREADY: printk("EALREADY\n"); @@ -39,7 +43,20 @@ void raise_zephyr_error(int err) { case ENOTSUP: printk("ENOTSUP\n"); break; + case EADDRINUSE: + printk("EADDRINUSE\n"); + break; + case EIO: + printk("EIO\n"); + break; + case ENOSYS: + printk("ENOSYS\n"); + break; + case EINVAL: + printk("EINVAL\n"); + break; default: printk("Zephyr error %d\n", err); } + mp_raise_OSError(-err); } diff --git a/ports/zephyr-cp/common-hal/zephyr_serial/UART.c b/ports/zephyr-cp/common-hal/zephyr_serial/UART.c deleted file mode 100644 index fcc05c22f1a..00000000000 --- a/ports/zephyr-cp/common-hal/zephyr_serial/UART.c +++ /dev/null @@ -1,130 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "shared-bindings/microcontroller/__init__.h" -#include "bindings/zephyr_serial/UART.h" - -#include "shared/runtime/interrupt_char.h" -#include "py/mpconfig.h" -#include "py/gc.h" -#include "py/mperrno.h" -#include "py/runtime.h" -#include "py/stream.h" - -#include -#include - -#include - -/* - * Read characters from UART until line end is detected. Afterwards push the - * data to the message queue. - */ -static void serial_cb(const struct device *dev, void *user_data) { - zephyr_serial_uart_obj_t *self = (zephyr_serial_uart_obj_t *)user_data; - - uint8_t c; - - if (!uart_irq_update(dev)) { - return; - } - - if (!uart_irq_rx_ready(dev)) { - return; - } - - /* read until FIFO empty */ - while (uart_fifo_read(dev, &c, 1) == 1) { - if (mp_interrupt_char == c) { - zephyr_serial_uart_clear_rx_buffer(self); - mp_sched_keyboard_interrupt(); - } else if (!self->rx_paused) { - if (k_msgq_put(&self->msgq, &c, K_NO_WAIT) != 0) { - self->rx_paused = true; - } - } - } -} - -void zephyr_serial_uart_never_reset(zephyr_serial_uart_obj_t *self) { -} - - -void zephyr_serial_uart_construct(zephyr_serial_uart_obj_t *self, const struct device *const uart_device, uint16_t receiver_buffer_size, byte *receiver_buffer) { - self->uart_device = uart_device; - int ret = uart_irq_callback_user_data_set(uart_device, serial_cb, self); - - - k_msgq_init(&self->msgq, receiver_buffer, 1, receiver_buffer_size); - - if (ret < 0) { - if (ret == -ENOTSUP) { - printk("Interrupt-driven UART API support not enabled\n"); - } else if (ret == -ENOSYS) { - printk("UART device does not support interrupt-driven API\n"); - } else { - printk("Error setting UART callback: %d\n", ret); - } - return; - } - self->timeout = K_USEC(100); - uart_irq_rx_enable(uart_device); -} - -bool zephyr_serial_uart_deinited(zephyr_serial_uart_obj_t *self) { - return !device_is_ready(self->uart_device); -} - -void zephyr_serial_uart_deinit(zephyr_serial_uart_obj_t *self) { -} - -// Read characters. -size_t zephyr_serial_uart_read(zephyr_serial_uart_obj_t *self, uint8_t *data, size_t len, int *errcode) { - size_t count = 0; - while (count < len && k_msgq_get(&self->msgq, data + count, self->timeout) == 0) { - count++; - } - if (count > 0) { - self->rx_paused = false; - } - - return count; -} - -// Write characters. -size_t zephyr_serial_uart_write(zephyr_serial_uart_obj_t *self, const uint8_t *data, size_t len, int *errcode) { - for (int i = 0; i < len; i++) { - uart_poll_out(self->uart_device, data[i]); - } - - return len; -} - -uint32_t zephyr_serial_uart_get_baudrate(zephyr_serial_uart_obj_t *self) { - return 0; -} - -void zephyr_serial_uart_set_baudrate(zephyr_serial_uart_obj_t *self, uint32_t baudrate) { -} - -mp_float_t zephyr_serial_uart_get_timeout(zephyr_serial_uart_obj_t *self) { - return 0; -} - -void zephyr_serial_uart_set_timeout(zephyr_serial_uart_obj_t *self, mp_float_t timeout) { -} - -uint32_t zephyr_serial_uart_rx_characters_available(zephyr_serial_uart_obj_t *self) { - return k_msgq_num_used_get(&self->msgq); -} - -void zephyr_serial_uart_clear_rx_buffer(zephyr_serial_uart_obj_t *self) { - k_msgq_purge(&self->msgq); -} - -bool zephyr_serial_uart_ready_to_tx(zephyr_serial_uart_obj_t *self) { - return true; -} diff --git a/ports/zephyr-cp/common-hal/zephyr_serial/UART.h b/ports/zephyr-cp/common-hal/zephyr_serial/UART.h deleted file mode 100644 index 4e220ee6307..00000000000 --- a/ports/zephyr-cp/common-hal/zephyr_serial/UART.h +++ /dev/null @@ -1,22 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft -// -// SPDX-License-Identifier: MIT - -#pragma once - -#include "py/obj.h" - -#include - -typedef struct { - mp_obj_base_t base; - - const struct device *uart_device; - struct k_msgq msgq; - - k_timeout_t timeout; - - bool rx_paused; // set by irq if no space in rbuf -} zephyr_serial_uart_obj_t; diff --git a/ports/zephyr-cp/common-hal/zephyr_serial/__init__.c b/ports/zephyr-cp/common-hal/zephyr_serial/__init__.c deleted file mode 100644 index 2784446ba15..00000000000 --- a/ports/zephyr-cp/common-hal/zephyr_serial/__init__.c +++ /dev/null @@ -1,7 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2024 Adafruit Industries LLC -// -// SPDX-License-Identifier: MIT - -// No zephyr_serial module functions. diff --git a/ports/zephyr-cp/common-hal/zephyr_spi/SPI.c b/ports/zephyr-cp/common-hal/zephyr_spi/SPI.c deleted file mode 100644 index 5601492fd69..00000000000 --- a/ports/zephyr-cp/common-hal/zephyr_spi/SPI.c +++ /dev/null @@ -1,74 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2019 Dan Halbert for Adafruit Industries -// SPDX-FileCopyrightText: Copyright (c) 2018 Artur Pacholec -// -// SPDX-License-Identifier: MIT - -#include - -#include "shared-bindings/busio/SPI.h" -#include "py/mperrno.h" -#include "py/runtime.h" - -void spi_reset(void) { -} - -void common_hal_busio_spi_never_reset(busio_spi_obj_t *self) { -} - -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, bool half_duplex) { - -} - -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)) { - return; - } -} - -bool common_hal_busio_spi_configure(busio_spi_obj_t *self, uint32_t baudrate, uint8_t polarity, uint8_t phase, uint8_t bits) { - return true; -} - -bool common_hal_busio_spi_try_lock(busio_spi_obj_t *self) { - if (common_hal_busio_spi_deinited(self)) { - return false; - } - bool grabbed_lock = false; - return grabbed_lock; -} - -bool common_hal_busio_spi_has_lock(busio_spi_obj_t *self) { - return self->has_lock; -} - -void common_hal_busio_spi_unlock(busio_spi_obj_t *self) { - self->has_lock = false; -} - -bool common_hal_busio_spi_write(busio_spi_obj_t *self, const uint8_t *data, size_t len) { - return true; -} - -bool common_hal_busio_spi_read(busio_spi_obj_t *self, uint8_t *data, size_t len, uint8_t write_value) { - return true; -} - -bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, const uint8_t *data_out, uint8_t *data_in, size_t len) { - return true; -} - -uint32_t common_hal_busio_spi_get_frequency(busio_spi_obj_t *self) { -} - -uint8_t common_hal_busio_spi_get_phase(busio_spi_obj_t *self) { - return 0; -} - -uint8_t common_hal_busio_spi_get_polarity(busio_spi_obj_t *self) { - return 0; -} diff --git a/ports/zephyr-cp/common-hal/zephyr_spi/SPI.h b/ports/zephyr-cp/common-hal/zephyr_spi/SPI.h deleted file mode 100644 index 5a1c91c8f0f..00000000000 --- a/ports/zephyr-cp/common-hal/zephyr_spi/SPI.h +++ /dev/null @@ -1,20 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2016 Scott Shawcroft -// -// SPDX-License-Identifier: MIT - -#pragma once - -#include "py/obj.h" - -typedef struct { - mp_obj_base_t base; - // const spim_peripheral_t *spim_peripheral; - bool has_lock; - uint8_t clock_pin_number; - uint8_t MOSI_pin_number; - uint8_t MISO_pin_number; -} busio_spi_obj_t; - -void spi_reset(void); diff --git a/ports/zephyr-cp/common-hal/zephyr_spi/__init__.c b/ports/zephyr-cp/common-hal/zephyr_spi/__init__.c deleted file mode 100644 index d3a4d472733..00000000000 --- a/ports/zephyr-cp/common-hal/zephyr_spi/__init__.c +++ /dev/null @@ -1,7 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2024 Adafruit Industries LLC -// -// SPDX-License-Identifier: MIT - -// No zephyr_spi module functions. diff --git a/ports/zephyr-cp/console.conf b/ports/zephyr-cp/console.conf new file mode 100644 index 00000000000..c2f90e7e25b --- /dev/null +++ b/ports/zephyr-cp/console.conf @@ -0,0 +1,5 @@ +# CONSOLE=1 and DEBUG=1 builds of boards that have a console.overlay: turn the +# Zephyr UART console back on, on the UART that the board's console.overlay +# sets up. +CONFIG_UART_CONSOLE=y +CONFIG_LOG_BACKEND_UART=y diff --git a/ports/zephyr-cp/cptools/board_tools.py b/ports/zephyr-cp/cptools/board_tools.py index 088b4bb5491..305abab3f19 100644 --- a/ports/zephyr-cp/cptools/board_tools.py +++ b/ports/zephyr-cp/cptools/board_tools.py @@ -1,3 +1,6 @@ +import tomllib + + def find_mpconfigboard(portdir, board_id): next_underscore = board_id.find("_") while next_underscore != -1: @@ -8,3 +11,27 @@ def find_mpconfigboard(portdir, board_id): return p next_underscore = board_id.find("_", next_underscore + 1) return None + + +def load_mpconfigboard(portdir, board_id): + mpconfigboard_path = find_mpconfigboard(portdir, board_id) + if mpconfigboard_path is None or not mpconfigboard_path.exists(): + return None, {} + + with mpconfigboard_path.open("rb") as f: + return mpconfigboard_path, tomllib.load(f) + + +def get_shields(mpconfigboard): + shields = mpconfigboard.get("SHIELDS") + if shields is None: + shields = mpconfigboard.get("SHIELD") + + if shields is None: + return [] + if isinstance(shields, str): + return [shields] + if isinstance(shields, (list, tuple)): + return [str(shield) for shield in shields] + + return [str(shields)] diff --git a/ports/zephyr-cp/cptools/build_all_boards.py b/ports/zephyr-cp/cptools/build_all_boards.py new file mode 100755 index 00000000000..bab09e8fb42 --- /dev/null +++ b/ports/zephyr-cp/cptools/build_all_boards.py @@ -0,0 +1,529 @@ +#!/usr/bin/env python3 +""" +Build all CircuitPython boards for the Zephyr port. + +This script discovers all boards by finding circuitpython.toml files +and builds them in parallel while sharing a single jobserver across +all builds. + +This is agent generated and works. Don't bother reading too closely because it +is just a tool for us. +""" + +import argparse +import concurrent.futures +import os +import pathlib +import select +import shlex +import subprocess +import sys +import time + + +class Jobserver: + def __init__(self, read_fd, write_fd, jobs=None, owns_fds=False): + self.read_fd = read_fd + self.write_fd = write_fd + self.jobs = jobs + self.owns_fds = owns_fds + + def acquire(self): + while True: + try: + os.read(self.read_fd, 1) + return + except InterruptedError: + continue + except BlockingIOError: + # GNU make opens its jobserver pipe non-blocking, so reading when + # no token is available raises instead of blocking. Wait until a + # token is written or the pipe closes. + select.select([self.read_fd], [], []) + + def release(self): + while True: + try: + os.write(self.write_fd, b"+") + return + except InterruptedError: + continue + except BlockingIOError: + # Defensive: a non-blocking pipe can also refuse writes when full. + select.select([], [self.write_fd], []) + + def pass_fds(self): + return (self.read_fd, self.write_fd) + + def close(self): + if self.owns_fds: + os.close(self.read_fd) + os.close(self.write_fd) + + +def _parse_makeflags_jobserver(makeflags): + jobserver_auth = None + jobs = None + + for token in shlex.split(makeflags): + if token == "-j" or token == "--jobs": + continue + if token.startswith("-j") and token != "-j": + try: + jobs = int(token[2:]) + except ValueError: + pass + elif token.startswith("--jobs="): + try: + jobs = int(token.split("=", 1)[1]) + except ValueError: + pass + elif token.startswith("--jobserver-auth=") or token.startswith("--jobserver-fds="): + jobserver_auth = token.split("=", 1)[1] + + if not jobserver_auth: + return None, jobs, False + + if jobserver_auth.startswith("fifo:"): + fifo_path = jobserver_auth[len("fifo:") :] + read_fd = os.open(fifo_path, os.O_RDONLY) + write_fd = os.open(fifo_path, os.O_WRONLY) + os.set_inheritable(read_fd, True) + os.set_inheritable(write_fd, True) + return (read_fd, write_fd), jobs, True + + if "," in jobserver_auth: + read_fd, write_fd = jobserver_auth.split(",", 1) + return (int(read_fd), int(write_fd)), jobs, False + + return None, jobs, False + + +def _create_jobserver(jobs): + read_fd, write_fd = os.pipe() + os.set_inheritable(read_fd, True) + os.set_inheritable(write_fd, True) + for _ in range(jobs): + os.write(write_fd, b"+") + return Jobserver(read_fd, write_fd, jobs=jobs, owns_fds=True) + + +def _jobserver_from_env(): + makeflags = os.environ.get("MAKEFLAGS", "") + fds, jobs, owns_fds = _parse_makeflags_jobserver(makeflags) + if not fds: + return None, jobs + read_fd, write_fd = fds + os.set_inheritable(read_fd, True) + os.set_inheritable(write_fd, True) + return Jobserver(read_fd, write_fd, jobs=jobs, owns_fds=owns_fds), jobs + + +def discover_boards(port_dir): + """ + Discover all boards by finding circuitpython.toml files. + + Returns a list of (vendor, board) tuples. + """ + boards = [] + boards_dir = port_dir / "boards" + + # Find all circuitpython.toml files + for toml_file in boards_dir.glob("*/*/circuitpython.toml"): + # Extract vendor and board from path: boards/vendor/board/circuitpython.toml + parts = toml_file.relative_to(boards_dir).parts + if len(parts) == 3: + vendor = parts[0] + board = parts[1] + boards.append((vendor, board)) + + return sorted(boards) + + +def build_board( + port_dir, + vendor, + board, + extra_args=None, + jobserver=None, + env=None, + log_dir=None, +): + """ + Build a single board using make. + + Args: + port_dir: Path to the zephyr-cp port directory + vendor: Board vendor name + board: Board name + extra_args: Additional arguments to pass to make + jobserver: Jobserver instance to limit parallel builds + env: Environment variables for the subprocess + log_dir: Directory to write build logs + + Returns: + (success: bool, elapsed_time: float, output: str, log_path: pathlib.Path) + """ + board_id = f"{vendor}_{board}" + start_time = time.time() + log_path = None + + cmd = ["make", f"BOARD={board_id}"] + + # Add extra arguments (like -j) + if extra_args: + cmd.extend(extra_args) + + if jobserver: + jobserver.acquire() + + try: + result = subprocess.run( + cmd, + cwd=port_dir, + # Inherit stdin alongside jobserver file descriptors + stdin=sys.stdin, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + text=True, + env=env, + pass_fds=jobserver.pass_fds() if jobserver else (), + ) + elapsed = time.time() - start_time + output = result.stdout or "" + if log_dir: + log_path = log_dir / f"{board_id}.log" + log_path.write_text(output) + return result.returncode == 0, elapsed, output, log_path + except KeyboardInterrupt: + raise + finally: + if jobserver: + jobserver.release() + + +def _format_status(status): + state = status["state"] + elapsed = status.get("elapsed") + if state == "queued": + return "QUEUED" + if state == "running": + return f"RUNNING {elapsed:.1f}s" + if state == "success": + return f"SUCCESS {elapsed:.1f}s" + if state == "failed": + return f"FAILED {elapsed:.1f}s" + if state == "skipped": + return "SKIPPED" + return state.upper() + + +def _build_status_table(boards, statuses, start_time, stop_submitting): + from rich.table import Table + from rich.text import Text + + elapsed = time.time() - start_time + title = f"Building {len(boards)} boards | Elapsed: {elapsed:.1f}s" + if stop_submitting: + title += " | STOPPING AFTER FAILURE" + + table = Table(title=title) + table.add_column("#", justify="right") + table.add_column("Board", no_wrap=True) + table.add_column("Status", no_wrap=True) + + for i, (vendor, board) in enumerate(boards): + board_id = f"{vendor}_{board}" + status_text = _format_status(statuses[i]) + state = statuses[i]["state"] + style = None + if state == "success": + style = "green" + elif state == "failed": + style = "red" + table.add_row( + f"{i + 1}/{len(boards)}", + board_id, + Text(status_text, style=style) if style else status_text, + ) + + return table + + +def _run_builds_tui( + port_dir, + boards, + extra_args, + jobserver, + env, + log_dir, + max_workers, + continue_on_error, +): + from rich.live import Live + + statuses = [ + {"state": "queued", "elapsed": 0.0, "start": None, "log_path": None} for _ in boards + ] + results = [] + futures = {} + next_index = 0 + stop_submitting = False + start_time = time.time() + + with Live( + _build_status_table(boards, statuses, start_time, stop_submitting), + refresh_per_second=4, + transient=False, + ) as live: + with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor: + while next_index < len(boards) and len(futures) < max_workers: + vendor, board = boards[next_index] + statuses[next_index]["state"] = "running" + statuses[next_index]["start"] = time.time() + future = executor.submit( + build_board, + port_dir, + vendor, + board, + extra_args, + jobserver, + env, + log_dir, + ) + futures[future] = next_index + next_index += 1 + + while futures: + for status in statuses: + if status["state"] == "running": + status["elapsed"] = time.time() - status["start"] + + live.update(_build_status_table(boards, statuses, start_time, stop_submitting)) + + done, _ = concurrent.futures.wait( + futures, + timeout=0.1, + return_when=concurrent.futures.FIRST_COMPLETED, + ) + for future in done: + index = futures.pop(future) + vendor, board = boards[index] + success, elapsed, _output, log_path = future.result() + statuses[index]["elapsed"] = elapsed + statuses[index]["log_path"] = log_path + statuses[index]["state"] = "success" if success else "failed" + results.append((vendor, board, success, elapsed)) + + if not success and not continue_on_error: + stop_submitting = True + + if not stop_submitting and next_index < len(boards): + vendor, board = boards[next_index] + statuses[next_index]["state"] = "running" + statuses[next_index]["start"] = time.time() + future = executor.submit( + build_board, + port_dir, + vendor, + board, + extra_args, + jobserver, + env, + log_dir, + ) + futures[future] = next_index + next_index += 1 + + if stop_submitting: + for index in range(next_index, len(boards)): + if statuses[index]["state"] == "queued": + statuses[index]["state"] = "skipped" + + live.update(_build_status_table(boards, statuses, start_time, stop_submitting)) + + return results, stop_submitting + + +def _run_builds_plain( + port_dir, + boards, + extra_args, + jobserver, + env, + log_dir, + max_workers, + continue_on_error, +): + results = [] + futures = {} + next_index = 0 + stop_submitting = False + + with concurrent.futures.ThreadPoolExecutor(max_workers=max_workers) as executor: + while next_index < len(boards) and len(futures) < max_workers: + vendor, board = boards[next_index] + future = executor.submit( + build_board, + port_dir, + vendor, + board, + extra_args, + jobserver, + env, + log_dir, + ) + futures[future] = (vendor, board) + next_index += 1 + + while futures: + done, _ = concurrent.futures.wait( + futures, + return_when=concurrent.futures.FIRST_COMPLETED, + ) + for future in done: + vendor, board = futures.pop(future) + success, elapsed, _output, _log_path = future.result() + board_id = f"{vendor}_{board}" + status = "SUCCESS" if success else "FAILURE" + print(f"{board_id}: {status} ({elapsed:.1f}s)") + results.append((vendor, board, success, elapsed)) + + if not success and not continue_on_error: + stop_submitting = True + + if not stop_submitting and next_index < len(boards): + vendor, board = boards[next_index] + future = executor.submit( + build_board, + port_dir, + vendor, + board, + extra_args, + jobserver, + env, + log_dir, + ) + futures[future] = (vendor, board) + next_index += 1 + + return results, stop_submitting + + +def main(): + parser = argparse.ArgumentParser( + description="Build all CircuitPython boards for the Zephyr port", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=""" +Examples: + # Build all boards in parallel with 32 jobserver slots + %(prog)s -j32 + + # Build all boards using make's jobserver (recommended) + make -j32 all +""", + ) + parser.add_argument( + "-j", + "--jobs", + type=int, + default=None, + help="Number of shared jobserver slots across all board builds", + ) + parser.add_argument( + "--continue-on-error", + action="store_true", + help="Continue building remaining boards even if one fails", + ) + parser.add_argument( + "--vendor", + type=str, + default=None, + help="Only build boards from this vendor (e.g. 'native' for sim boards)", + ) + + args = parser.parse_args() + + if args.jobs is not None and args.jobs < 1: + print("ERROR: --jobs must be at least 1") + return 2 + + # Get the port directory + port_dir = pathlib.Path(__file__).parent.resolve().parent + + # Discover all boards + boards = discover_boards(port_dir) + + if args.vendor: + boards = [(v, b) for v, b in boards if v == args.vendor] + + if not boards: + print("ERROR: No boards found!") + return 1 + + # Prepare jobserver and extra make arguments + jobserver, detected_jobs = _jobserver_from_env() + env = os.environ.copy() + + extra_args = [] + jobserver_jobs = detected_jobs + + if not jobserver: + jobserver_jobs = args.jobs if args.jobs else (os.cpu_count() or 1) + jobserver = _create_jobserver(jobserver_jobs) + env["MAKEFLAGS"] = ( + f"-j{jobserver_jobs} --jobserver-auth={jobserver.read_fd},{jobserver.write_fd}" + ) + + max_workers = jobserver_jobs + if max_workers is None: + max_workers = min(len(boards), os.cpu_count() or 1) + max_workers = max(1, min(len(boards), max_workers)) + + # Build all boards + log_dir = port_dir / "build-logs" + log_dir.mkdir(parents=True, exist_ok=True) + + try: + use_tui = sys.stdout.isatty() + if use_tui: + try: + import rich # noqa: F401 + except ImportError: + use_tui = False + + if use_tui: + results, stop_submitting = _run_builds_tui( + port_dir, + boards, + extra_args, + jobserver, + env, + log_dir, + max_workers, + args.continue_on_error, + ) + else: + results, stop_submitting = _run_builds_plain( + port_dir, + boards, + extra_args, + jobserver, + env, + log_dir, + max_workers, + args.continue_on_error, + ) + except KeyboardInterrupt: + print("\n\nBuild interrupted by user.") + return 130 # Standard exit code for SIGINT + finally: + if jobserver: + jobserver.close() + + failed = [r for r in results if not r[2]] + return 0 if len(failed) == 0 else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/ports/zephyr-cp/cptools/build_circuitpython.py b/ports/zephyr-cp/cptools/build_circuitpython.py index e6ebd97b3bd..dd5eaa68777 100644 --- a/ports/zephyr-cp/cptools/build_circuitpython.py +++ b/ports/zephyr-cp/cptools/build_circuitpython.py @@ -1,16 +1,17 @@ import asyncio -import colorlog -import sys import logging import os import pathlib -import tomllib -import tomlkit -import yaml import pickle +import re +import sys -import cpbuild import board_tools +import colorlog +import cpbuild +import tomlkit +import tomllib +import yaml logger = logging.getLogger(__name__) @@ -42,18 +43,117 @@ compiler = cpbuild.Compiler(srcdir, builddir, cmake_args) ALWAYS_ON_MODULES = ["sys", "collections"] +# Keep in alphabetical order. DEFAULT_MODULES = [ - "time", - "os", - "microcontroller", - "struct", + "__future__", + "adafruit_bus_device", + "aesio", "array", + "asyncio", + "atexit", + "binascii", + "bitbangio", + "codeop", + "digitalio", + "errno", + "getpass", + "hashlib", + "io", "json", + "keypad", + "keypad_demux", + "locale", + "math", + "microcontroller", + "msgpack", + "os", + "rainbowio", "random", - "digitalio", - "zephyr_serial", + "re", + "rotaryio", + "select", + "storage", + "struct", + "supervisor", + "time", + "touchio", + "traceback", + "warnings", + "zlib", ] -MPCONFIG_FLAGS = ["ulab", "nvm", "displayio", "warnings", "alarm", "array", "json"] +# Flags that don't match with with a *bindings module. Some used by adafruit_requests +MPCONFIG_FLAGS = ["array", "errno", "io", "json", "math", "binascii"] + +# extmod-based modules that should appear in the autogen list even though they +# don't have shared-bindings/ or bindings/ directories. +EXTMOD_MODULES = ["asyncio", "binascii", "json", "re", "select"] + +# List of other modules (the value) that can be enabled when another one (the key) is. +REVERSE_DEPENDENCIES = { + "audiobusio": ["audiocore"], + "audiocore": [ + "audiodelays", + "audiofilters", + "audiofreeverb", + "audiomixer", + "audiomp3", + "audiotap", + "synthio", + ], + "busio": ["fourwire", "i2cdisplaybus", "sdcardio", "sharpdisplay"], + "fourwire": ["displayio", "busdisplay", "epaperdisplay"], + "i2cdisplaybus": ["displayio", "busdisplay", "epaperdisplay"], + "neopixel_write": ["adafruit_pixelbuf", "_pixelmap"], + # Zephyr display backends need displayio and, by extension, terminalio so + # the REPL console appears on the display by default. + "zephyr_display": ["displayio"], + "displayio": [ + "vectorio", + "bitmapfilter", + "bitmaptools", + "terminalio", + "lvfontio", + "tilepalettemapper", + "fontio", + "gifio", + "jpegio", + ], + "sharpdisplay": ["framebufferio"], + "framebufferio": ["displayio"], +} + +# Other flags to set when a module is enabled +EXTRA_FLAGS = { + "audiobusio": {"AUDIOBUSIO_I2SOUT": 1, "AUDIOBUSIO_PDMIN": 0}, + "busio": {"BUSIO_SPI": 1, "BUSIO_I2C": 1, "BUSIO_UART": 1}, + "keypad": {"KEYPAD_KEYMATRIX": 1, "KEYPAD_KEYS": 1, "KEYPAD_SHIFTREGISTERKEYS": 1}, + "rotaryio": {"ROTARYIO_SOFTENCODER": 1}, + "synthio": {"SYNTHIO_MAX_CHANNELS": 12}, + "touchio": {"TOUCHIO_USE_NATIVE": 0}, +} + +# Library sources. Will be globbed from the top level directory +# No QSTR processing or CIRCUITPY specific flags +LIBRARY_SOURCE = { + "audiomp3": ["lib/mp3/src/*.c"], + "zlib": [ + "lib/uzlib/tinflate.c", + "lib/uzlib/tinfzlib.c", + "lib/uzlib/tinfgzip.c", + "lib/uzlib/adler32.c", + "lib/uzlib/crc32.c", + ], + "jpegio": ["lib/tjpgd/src/tjpgd.c"], + "gifio": ["lib/AnimatedGIF/gif.c"], +} + +SHARED_MODULE_AND_COMMON_HAL = ["_bleio", "os", "rotaryio", "watchdog"] + +# Mapping from module directory name to the flag name used in CIRCUITPY_ +MODULE_FLAG_NAMES = { + "__future__": "FUTURE", + "_bleio": "BLEIO", +} async def preprocess_and_split_defs(compiler, source_file, build_path, flags): @@ -81,23 +181,69 @@ async def preprocess_and_split_defs(compiler, source_file, build_path, flags): ) +def _concatenate_if_changed(inputs, output_file): + """Write the concatenation of inputs to output_file, but only if it differs from what is + already there, so an unchanged output keeps its modification time.""" + content = "".join(path.read_text() for path in inputs) + if not output_file.exists() or output_file.read_text() != content: + output_file.write_text(content) + + async def collect_defs(mode, build_path): output_file = build_path / f"{mode}defs.collected" splitdir = build_path / "genhdr" / mode - await cpbuild.run_command( - ["cat", "-s", *splitdir.glob(f"**/*.{mode}"), ">", output_file], - splitdir, + # Sorted so the output does not depend on directory order. + to_collect = sorted(splitdir.glob(f"**/*.{mode}")) + await cpbuild.run_function( + _concatenate_if_changed, + (to_collect, output_file), + {}, + description=f"Collect {mode} definitions -> {output_file.relative_to(build_path)}", ) return output_file +def _rewrite_qstr_lines_if_changed(input_file, output_file, pattern, replacement): + content = re.sub(pattern, replacement, input_file.read_text(), flags=re.MULTILINE) + if not output_file.exists() or output_file.read_text() != content: + output_file.write_text(content) + + +async def preprocess_qstrdefs(build_path, compiler, flags): + """Preprocess py/qstrdefs.h like py/py.mk does. It holds the qstrs whose value + can't be recovered from their MP_QSTR_ name, such as {:#b}. The Q() lines are + quoted so the preprocessor passes them through unchanged.""" + quoted = build_path / "genhdr" / "qstrdefs.quoted.c" + quoted_pp = build_path / "genhdr" / "qstrdefs.quoted.pp" + preprocessed = build_path / "genhdr" / "qstrdefs.preprocessed.h" + await cpbuild.run_function( + _rewrite_qstr_lines_if_changed, + (srcdir / "py" / "qstrdefs.h", quoted, r"^Q\(.*\)$", r'"\g<0>"'), + {}, + description=f"Quote py/qstrdefs.h -> {quoted.relative_to(build_path)}", + ) + await compiler.preprocess(quoted, quoted_pp, flags) + await cpbuild.run_function( + _rewrite_qstr_lines_if_changed, + (quoted_pp, preprocessed, r'^"(Q\(.*\))"$', r"\1"), + {}, + description=f"Unquote -> {preprocessed.relative_to(build_path)}", + ) + return preprocessed + + async def generate_qstr_headers(build_path, compiler, flags, translation): collected = await collect_defs("qstr", build_path) + qstrdefs = await preprocess_qstrdefs(build_path, compiler, flags) generated = build_path / "genhdr" / "qstrdefs.generated.h" + # check_hash: the collected file is rewritten on every build, so this reruns every + # build too. Keep the old modification time when the header comes out unchanged, or + # every file that includes it would be recompiled. await cpbuild.run_command( - ["python", srcdir / "py" / "makeqstrdata.py", collected, ">", generated], + ["python", srcdir / "py" / "makeqstrdata.py", qstrdefs, collected, ">", generated], srcdir, + check_hash=[generated], ) compression_level = 9 @@ -136,108 +282,214 @@ async def generate_qstr_headers(build_path, compiler, flags, translation): async def generate_module_header(build_path): collected = await collect_defs("module", build_path) + generated = build_path / "genhdr" / "moduledefs.h" await cpbuild.run_command( - [ - "python", - srcdir / "py" / "makemoduledefs.py", - collected, - ">", - build_path / "genhdr" / "moduledefs.h", - ], + ["python", srcdir / "py" / "makemoduledefs.py", collected, ">", generated], srcdir, + check_hash=[generated], ) async def generate_root_pointer_header(build_path): collected = await collect_defs("root_pointer", build_path) + generated = build_path / "genhdr" / "root_pointers.h" + await cpbuild.run_command( + ["python", srcdir / "py" / "make_root_pointers.py", collected, ">", generated], + srcdir, + check_hash=[generated], + ) + + +async def generate_display_resources( + output_path, translation, font, extra_characters, lvgl_tilegrid +): + cmd = [ + "python", + srcdir / "tools" / "gen_display_resources.py", + "--font", + srcdir / font, + "--sample_file", + srcdir / "locale" / f"{translation}.po", + "--extra_characters", + repr(extra_characters), + "--output_c_file", + output_path, + ] + if lvgl_tilegrid: + cmd.append("--lvgl-tilegrid") + await cpbuild.run_command(cmd, srcdir, check_hash=[output_path]) + + +async def generate_web_workflow_static(output_path, static_files): await cpbuild.run_command( [ "python", - srcdir / "py" / "make_root_pointers.py", - collected, - ">", - build_path / "genhdr" / "root_pointers.h", + srcdir / "tools" / "gen_web_workflow_static.py", + "--output_c_file", + output_path, + *static_files, ], srcdir, + check_hash=[output_path], ) -TINYUSB_SETTINGS = { - "": { - "CFG_TUSB_MCU": "OPT_MCU_MIMXRT10XX", - "CFG_TUD_CDC_RX_BUFSIZE": 640, - "CFG_TUD_CDC_TX_BUFSIZE": 512, - }, - "stm32u575xx": {"CFG_TUSB_MCU": "OPT_MCU_STM32U5"}, - "nrf52840": {"CFG_TUSB_MCU": "OPT_MCU_NRF5X"}, - "nrf5340": {"CFG_TUSB_MCU": "OPT_MCU_NRF5X"}, - # "r7fa8d1bhecbd": {"CFG_TUSB_MCU": "OPT_MCU_RAXXX", "USB_HIGHSPEED": "1", "USBHS_USB_INT_RESUME_IRQn": "54", "USBFS_INT_IRQn": "54", "CIRCUITPY_USB_DEVICE_INSTANCE": "1"}, - # ifeq ($(CHIP_FAMILY),$(filter $(CHIP_FAMILY),MIMXRT1011 MIMXRT1015)) - # CFLAGS += -DCFG_TUD_MIDI_RX_BUFSIZE=512 -DCFG_TUD_MIDI_TX_BUFSIZE=64 -DCFG_TUD_MSC_BUFSIZE=512 - # else - # CFLAGS += -DCFG_TUD_MIDI_RX_BUFSIZE=512 -DCFG_TUD_MIDI_TX_BUFSIZE=512 -DCFG_TUD_MSC_BUFSIZE=1024 - # endif -} +def determine_enabled_modules(board_info, portdir, srcdir): + """Determine which CircuitPython modules should be enabled based on board capabilities. -TINYUSB_SOURCE = { - "stm32u575xx": [ - "src/portable/st/stm32_fsdev/dcd_stm32_fsdev.c", - "src/portable/synopsys/dwc2/dcd_dwc2.c", - "src/portable/synopsys/dwc2/hcd_dwc2.c", - "src/portable/synopsys/dwc2/dwc2_common.c", - ], - "nrf52840": [ - "src/portable/nordic/nrf5x/dcd_nrf5x.c", - ], - "nrf5340": [ - "src/portable/nordic/nrf5x/dcd_nrf5x.c", - ], - # "r7fa8d1bhecbd": [ - # "src/portable/renesas/rusb2/dcd_rusb2.c", - # "src/portable/renesas/rusb2/hcd_rusb2.c", - # "src/portable/renesas/rusb2/rusb2_common.c", - # ], -} + Args: + board_info: Dictionary containing board hardware capabilities + portdir: Path to the port directory (ports/zephyr-cp) + srcdir: Path to the CircuitPython source root + + Returns: + tuple: (enabled_modules set, module_reasons dict) + """ + enabled_modules = set(DEFAULT_MODULES) + module_reasons = {} + + # The board module is always built: shared-bindings/board/__init__.c and the + # generated pin/board.c are compiled unconditionally in build_circuitpython(). + enabled_modules.add("board") + module_reasons["board"] = "Always enabled" + + if board_info["wifi"]: + enabled_modules.add("wifi") + module_reasons["wifi"] = "Zephyr board has wifi" + + if board_info.get("ethernet", False): + enabled_modules.add("mii") + module_reasons["mii"] = "Zephyr board has ethernet" + + if board_info["flash_count"] > 0: + enabled_modules.add("storage") + module_reasons["storage"] = "Zephyr board has flash" + + if board_info.get("nvm_size", 0) > 0: + enabled_modules.add("nvm") + module_reasons["nvm"] = "Board has NVM partition" + + network_enabled = ( + board_info.get("wifi", False) + or board_info.get("ethernet", False) + or board_info.get("hostnetwork", False) + ) + + if network_enabled: + enabled_modules.add("ipaddress") + module_reasons["ipaddress"] = "Zephyr networking enabled" + enabled_modules.add("socketpool") + module_reasons["socketpool"] = "Zephyr networking enabled" + enabled_modules.add("hashlib") + module_reasons["hashlib"] = "Zephyr networking enabled" + + if board_info.get("wifi", False): + enabled_modules.add("ssl") + module_reasons["ssl"] = "Zephyr wifi enabled" + elif board_info.get("ethernet", False): + enabled_modules.add("ssl") + module_reasons["ssl"] = "Zephyr ethernet enabled" + elif board_info.get("hostnetwork", False): + enabled_modules.add("ssl") + module_reasons["ssl"] = "Zephyr hostnetwork enabled" + + # Iterate the shared-bindings directory in a stable (sorted) order. Several + # modules can enable the same reverse dependency, and the "reason" comment + # recorded in autogen_board_info.toml belongs to whichever module enabled it + # first. Directory iteration order is filesystem dependent (it differs + # between machines and CI runners), so an unsorted walk made the generated + # comments - and therefore the committed toml files - change between builds. + for port_module in sorted((portdir / "bindings").iterdir(), key=lambda x: x.name): + if not board_info.get(port_module.name, False): + continue + enabled_modules.add(port_module.name) + module_reasons[port_module.name] = f"Zephyr board has {port_module.name}" + + for shared_module in sorted((srcdir / "shared-bindings").iterdir(), key=lambda x: x.name): + if not board_info.get(shared_module.name, False) or not shared_module.glob("*.c"): + continue + enabled_modules.add(shared_module.name) + module_reasons[shared_module.name] = f"Zephyr board has {shared_module.name}" + + more_modules = [] + more_modules.extend(REVERSE_DEPENDENCIES.get(shared_module.name, [])) + while more_modules: + reverse_dependency = more_modules.pop(0) + if reverse_dependency in enabled_modules: + continue + logger.debug(f"Enabling {reverse_dependency} because {shared_module.name} is enabled") + enabled_modules.add(reverse_dependency) + more_modules.extend(REVERSE_DEPENDENCIES.get(reverse_dependency, [])) + module_reasons[reverse_dependency] = f"Zephyr board has {shared_module.name}" + return enabled_modules, module_reasons -async def build_circuitpython(): + +async def build_circuitpython(): # noqa: C901 circuitpython_flags = ["-DCIRCUITPY"] port_flags = [] enable_mpy_native = False - full_build = False + full_build = True usb_host = False - tusb_mem_align = 4 + zephyr_board = cmake_args["BOARD"] board = cmake_args["BOARD_ALIAS"] if not board: - board = cmake_args["BOARD"] - translation = cmake_args["TRANSLATION"] - if not translation: - translation = "en_US" + board = zephyr_board + # The environment wins, so the Makefile can switch languages without a reconfigure. + translation = os.environ.get("TRANSLATION") or cmake_args["TRANSLATION"] or "en_US" for module in ALWAYS_ON_MODULES: circuitpython_flags.append(f"-DCIRCUITPY_{module.upper()}=1") lto = cmake_args.get("LTO", "n") == "y" + # LVGL module enabled for this board. The flag comes from CONFIG_LVGL via + # ExternalProject args so it stays in sync with the Kconfig choice. Any board that + # sets CONFIG_LVGL gets the LVGL-based displayio compositing core; boards without + # LVGL build the legacy scanline compositor. + lvgl_enabled = cmake_args.get("LVGL", "n") == "y" + lvgl_dir = cmake_args.get("LVGL_DIR", "") + logger.info(f"LVGL compositing core enabled: {lvgl_enabled} (dir={lvgl_dir or 'none'})") circuitpython_flags.append(f"-DCIRCUITPY_ENABLE_MPY_NATIVE={1 if enable_mpy_native else 0}") circuitpython_flags.append(f"-DCIRCUITPY_FULL_BUILD={1 if full_build else 0}") + circuitpython_flags.append("-DCIRCUITPY_OPT_LOAD_ATTR_FAST_PATH=1") + circuitpython_flags.append(f"-DCIRCUITPY_OPT_MAP_LOOKUP_CACHE={1 if full_build else 0}") + circuitpython_flags.append(f"-DCIRCUITPY_SETTINGS_TOML={1 if full_build else 0}") + circuitpython_flags.append(f"-DMICROPY_PY_ASYNC_AWAIT={1 if full_build else 0}") + circuitpython_flags.append(f"-DMICROPY_PY_ASYNCIO={1 if full_build else 0}") + circuitpython_flags.append(f"-DMICROPY_PY_SELECT={1 if full_build else 0}") + circuitpython_flags.append(f"-DMICROPY_PY_SELECT_SELECT={1 if full_build else 0}") + circuitpython_flags.append("-DCIRCUITPY_STATUS_BAR=1") + if lvgl_enabled: + circuitpython_flags.append("-DCIRCUITPY_DISPLAYIO_LVGL=1") + circuitpython_flags.extend(("-isystem", lvgl_dir)) + circuitpython_flags.extend(("-isystem", lvgl_dir + "/include")) + # The zephyr-provided LV_CONF_PATH definition loses its shell quoting while + # crossing the ExternalProject boundary. Re-supply it quoted so LVGL resolves + # the config header. + lv_conf_path = portdir / "zephyr" / "modules" / "lvgl" / "include" / "lv_conf.h" + circuitpython_flags.append("-ULV_CONF_PATH") + # The command runs through a shell, so escape the quotes for it. + circuitpython_flags.append(f'-DLV_CONF_PATH=\\"{lv_conf_path}\\"') circuitpython_flags.append(f"-DCIRCUITPY_USB_HOST={1 if usb_host else 0}") - circuitpython_flags.append(f'-DCIRCUITPY_BOARD_ID=\\"{board}\\"') - circuitpython_flags.append(f"-DCIRCUITPY_TUSB_MEM_ALIGN={tusb_mem_align}") + circuitpython_flags.append(f"-DCIRCUITPY_BOARD_ID='\"{board}\"'") circuitpython_flags.append(f"-DCIRCUITPY_TRANSLATE_OBJECT={1 if lto else 0}") circuitpython_flags.append("-DINTERNAL_FLASH_FILESYSTEM") circuitpython_flags.append("-DLONGINT_IMPL_MPZ") circuitpython_flags.append("-DCIRCUITPY_SSL_MBEDTLS") - circuitpython_flags.append('-DFFCONF_H=\\"lib/oofatfs/ffconf.h\\"') + circuitpython_flags.append("-DFFCONF_H='\"lib/oofatfs/ffconf.h\"'") + circuitpython_flags.append( + "-D_DEFAULT_SOURCE" + ) # To get more from picolibc to match newlib such as M_PI circuitpython_flags.extend(("-I", srcdir)) - circuitpython_flags.extend(("-I", srcdir / "lib/tinyusb/src")) - circuitpython_flags.extend(("-I", srcdir / "supervisor/shared/usb")) circuitpython_flags.extend(("-I", builddir)) circuitpython_flags.extend(("-I", portdir)) - # circuitpython_flags.extend(("-I", srcdir / "ports" / port / "peripherals")) - - # circuitpython_flags.extend(("-I", build_path / board_id)) genhdr = builddir / "genhdr" genhdr.mkdir(exist_ok=True, parents=True) version_header = genhdr / "mpversion.h" + mpconfigboard_fn = board_tools.find_mpconfigboard(portdir, board) + mpconfigboard = {"USB_VID": 0x1209, "USB_PID": 0x000C, "USB_INTERFACE_NAME": "CircuitPython"} + if mpconfigboard_fn is not None and mpconfigboard_fn.exists(): + with mpconfigboard_fn.open("rb") as f: + mpconfigboard.update(tomllib.load(f)) async with asyncio.TaskGroup() as tg: tg.create_task( cpbuild.run_command( @@ -254,13 +506,10 @@ async def build_circuitpython(): ) ) - board_autogen_task = tg.create_task(zephyr_dts_to_cp_board(builddir, zephyrbuilddir)) + board_autogen_task = tg.create_task( + zephyr_dts_to_cp_board(zephyr_board, portdir, builddir, zephyrbuilddir, mpconfigboard) + ) board_info = board_autogen_task.result() - mpconfigboard_fn = board_tools.find_mpconfigboard(portdir, board) - mpconfigboard = { - "USB_VID": 0x1209, - "USB_PID": 0x000C, - } if mpconfigboard_fn is None: mpconfigboard_fn = ( portdir / "boards" / board_info["vendor_id"] / board / "circuitpython.toml" @@ -268,41 +517,77 @@ async def build_circuitpython(): logging.warning( f"Could not find board config at: boards/{board_info['vendor_id']}/{board}" ) - elif mpconfigboard_fn.exists(): - with mpconfigboard_fn.open("rb") as f: - mpconfigboard = tomllib.load(f) autogen_board_info_fn = mpconfigboard_fn.parent / "autogen_board_info.toml" - enabled_modules = set(DEFAULT_MODULES) - module_reasons = {} - if board_info["wifi"]: - enabled_modules.add("wifi") - module_reasons["wifi"] = "Zephyr board has wifi" - - if board_info["flash_count"] > 0: - enabled_modules.add("storage") - module_reasons["storage"] = "Zephyr board has flash" - - if "wifi" in enabled_modules: - enabled_modules.add("socketpool") - enabled_modules.add("ssl") - module_reasons["socketpool"] = "Zephyr networking enabled" - module_reasons["ssl"] = "Zephyr networking enabled" + # Filesystem type is a compile-time choice made by the partition layout: + # zephyr2cp reports littlefs when the devicetree has a littlefs_partition + # node, otherwise the supervisor mounts FAT. + filesystem_littlefs = board_info.get("littlefs", False) + circuitpython_flags.append( + f"-DCIRCUITPY_FILESYSTEM_LITTLEFS={1 if filesystem_littlefs else 0}" + ) + if filesystem_littlefs: + circuitpython_flags.append("-DMICROPY_VFS_LFS2=1") + + creator_id = mpconfigboard.get("CIRCUITPY_CREATOR_ID", mpconfigboard.get("USB_VID", 0x1209)) + creation_id = mpconfigboard.get("CIRCUITPY_CREATION_ID", mpconfigboard.get("USB_PID", 0x000C)) + circuitpython_flags.append(f"-DCIRCUITPY_CREATOR_ID=0x{creator_id:08x}") + circuitpython_flags.append(f"-DCIRCUITPY_CREATION_ID=0x{creation_id:08x}") + + vendor = mpconfigboard.get("VENDOR", board_info["vendor"]) + name = mpconfigboard.get("NAME", board_info["name"]) + usb_manufacturer = mpconfigboard.get("USB_MANUFACTURER", board_info["vendor"]) + + enabled_modules, module_reasons = determine_enabled_modules(board_info, portdir, srcdir) + for m in mpconfigboard.get("DISABLED_MODULES", []): + enabled_modules.discard(m) + + if lvgl_enabled: + # These display-side modules render through the scanline compositor and do not + # work with the LVGL one. Exclude them so LVGL builds don't link legacy rendering + # machinery. BusDisplay, FramebufferDisplay, FourWire and I2CDisplayBus have LVGL + # implementations and stay enabled. bitmaptools and jpegio stay enabled because + # bitmaptools now writes through the Bitmap dirty API and jpegio decodes through + # bitmaptools.blit. + legacy_display_modules = [ + "epaperdisplay", + "sharpdisplay", + "tilepalettemapper", + ] + for m in legacy_display_modules: + if m in enabled_modules: + enabled_modules.discard(m) + module_reasons[m] = "Legacy scanline display module; excluded from LVGL builds" + + web_workflow_enabled = ( + board_info.get("wifi", False) + or board_info.get("hostnetwork", False) + or "mii" in enabled_modules + ) circuitpython_flags.extend(board_info["cflags"]) + circuitpython_flags.append(f"-DCIRCUITPY_WEB_WORKFLOW={1 if web_workflow_enabled else 0}") supervisor_source = [ "main.c", + "extmod/modjson.c", + "extmod/modbinascii.c", + "extmod/modre.c", + "extmod/modasyncio.c", + "extmod/modselect.c", "extmod/vfs_fat.c", "lib/tlsf/tlsf.c", portdir / "background.c", + portdir / "supervisor/adaboot_info.c", portdir / "common-hal/microcontroller/__init__.c", portdir / "common-hal/microcontroller/Pin.c", portdir / "common-hal/microcontroller/Processor.c", portdir / "common-hal/os/__init__.c", - "supervisor/stub/misc.c", "shared/readline/readline.c", + "shared/runtime/buffer_helper.c", "shared/runtime/context_manager_helpers.c", + "shared/runtime/gchelper_generic.c", + "shared/runtime/gchelper_native.c", "shared/runtime/pyexec.c", "shared/runtime/interrupt_char.c", "shared/runtime/stdout_helpers.c", @@ -320,139 +605,83 @@ async def build_circuitpython(): supervisor_source = [pathlib.Path(p) for p in supervisor_source] supervisor_source.extend(board_info["source_files"]) supervisor_source.extend(top.glob("supervisor/shared/*.c")) + ble_workflow_enabled = "_bleio" in enabled_modules + if ble_workflow_enabled: + supervisor_source.append(top / "supervisor/shared/bluetooth/bluetooth.c") + # BLE workflow = file transfer + serial services, matching other ports. + supervisor_source.append(top / "supervisor/shared/bluetooth/file_transfer.c") + supervisor_source.append(top / "supervisor/shared/bluetooth/serial.c") + circuitpython_flags.append(f"-DCIRCUITPY_BLE_FILE_SERVICE={1 if ble_workflow_enabled else 0}") + circuitpython_flags.append( + f"-DCIRCUITPY_BLE_SERIAL_SERVICE={1 if ble_workflow_enabled else 0}" + ) supervisor_source.append(top / "supervisor/shared/translate/translate.c") - # if web_workflow: - # supervisor_source.extend(top.glob("supervisor/shared/web_workflow/*.c")) - - usb_num_endpoint_pairs = board_info.get("usb_num_endpoint_pairs", 0) - soc = board_info["soc"] - usb_ok = usb_num_endpoint_pairs > 0 and soc in TINYUSB_SETTINGS - circuitpython_flags.append(f"-DCIRCUITPY_TINYUSB={1 if usb_ok else 0}") + if web_workflow_enabled: + supervisor_source.extend(top.glob("supervisor/shared/web_workflow/*.c")) + + usb_ok = board_info.get("usb_device", False) + if usb_ok and filesystem_littlefs: + # USB MSC can only expose a FAT block image; a littlefs CIRCUITPY has + # no MSC-compatible layout and USB MSC of it would corrupt the drive. + # Rename the filesystem partition to fatfs_partition in the board's + # Adaboot layout dtsi, or remove the USB device from the devicetree. + raise SystemExit( + f"{board}: littlefs CIRCUITPY filesystem is incompatible with USB. " + "Rename the littlefs_partition node to fatfs_partition in the board's " + "layout dtsi, or disable the USB device controller in the devicetree." + ) circuitpython_flags.append(f"-DCIRCUITPY_USB_DEVICE={1 if usb_ok else 0}") + # MSC is the CIRCUITPY drive interface. The Zephyr port registers it only when + # storage.disable_usb_drive() has not turned it off (see supervisor/usb.c). + circuitpython_flags.append(f"-DCIRCUITPY_USB_MSC={1 if usb_ok else 0}") + circuitpython_flags.append(f"-DCIRCUITPY_USB_MSC_ENABLED_DEFAULT={1 if usb_ok else 0}") - tinyusb_files = [] if usb_ok: enabled_modules.add("usb_cdc") - for setting in TINYUSB_SETTINGS[soc]: - circuitpython_flags.append(f"-D{setting}={TINYUSB_SETTINGS[soc][setting]}") - tinyusb_files.extend((top / "lib" / "tinyusb" / path for path in TINYUSB_SOURCE[soc])) + enabled_modules.add("usb_hid") + + usb_num_endpoint_pairs = board_info.get("usb_num_endpoint_pairs", 4) + circuitpython_flags.append(f"-DUSB_NUM_ENDPOINT_PAIRS={usb_num_endpoint_pairs}") + circuitpython_flags.append("-DCIRCUITPY_USB_HID_ENABLED_DEFAULT=1") + for macro in ("USB_PID", "USB_VID"): + print(f"Setting {macro} to {mpconfigboard.get(macro)}") circuitpython_flags.append(f"-D{macro}=0x{mpconfigboard.get(macro):04x}") + circuitpython_flags.append( + f"-DUSB_INTERFACE_NAME='\"{mpconfigboard['USB_INTERFACE_NAME']}\"'" + ) for macro, limit, value in ( - ("USB_PRODUCT", 16, board_info["name"]), - ("USB_MANUFACTURER", 8, board_info["vendor"]), + ("USB_PRODUCT", 16, name), + ("USB_MANUFACTURER", 8, usb_manufacturer), ): circuitpython_flags.append(f"-D{macro}='\"{value}\"'") circuitpython_flags.append(f"-D{macro}_{limit}='\"{value[:limit]}\"'") - usb_interface_name = "CircuitPython" + circuitpython_flags.append("-DCIRCUITPY_USB_CDC_CONSOLE_ENABLED_DEFAULT=1") + circuitpython_flags.append("-DCIRCUITPY_USB_CDC_DATA_ENABLED_DEFAULT=0") - circuitpython_flags.append("-DCFG_TUSB_OS=OPT_OS_ZEPHYR") - circuitpython_flags.append(f"-DUSB_INTERFACE_NAME='\"{usb_interface_name}\"'") - circuitpython_flags.append(f"-DUSB_NUM_ENDPOINT_PAIRS={usb_num_endpoint_pairs}") - for direction in ("IN", "OUT"): - circuitpython_flags.append(f"-DUSB_NUM_{direction}_ENDPOINTS={usb_num_endpoint_pairs}") - # USB is special because it doesn't have a matching module. - msc_enabled = board_info["flash_count"] > 0 - if msc_enabled: - circuitpython_flags.append("-DCFG_TUD_MSC_BUFSIZE=1024") - circuitpython_flags.append("-DCIRCUITPY_USB_MSC_ENABLED_DEFAULT=1") - tinyusb_files.append(top / "lib/tinyusb/src/class/msc/msc_device.c") - supervisor_source.append(top / "supervisor/shared/usb/usb_msc_flash.c") - circuitpython_flags.append(f"-DCIRCUITPY_USB_MSC={1 if msc_enabled else 0}") - if "usb_cdc" in enabled_modules: - tinyusb_files.extend(top.glob("lib/tinyusb/*.c")) - tinyusb_files.append(top / "lib/tinyusb/src/class/cdc/cdc_device.c") - circuitpython_flags.append("-DCFG_TUD_CDC_RX_BUFSIZE=640") - circuitpython_flags.append("-DCFG_TUD_CDC_TX_BUFSIZE=512") - circuitpython_flags.append("-DCFG_TUD_CDC=2") - circuitpython_flags.append("-DCIRCUITPY_USB_CDC_CONSOLE_ENABLED_DEFAULT=1") - circuitpython_flags.append("-DCIRCUITPY_USB_CDC_DATA_ENABLED_DEFAULT=0") - - if "usb_hid_enabled_default" not in mpconfigboard: - mpconfigboard["usb_hid_enabled_default"] = usb_num_endpoint_pairs >= 5 - if "usb_midi_enabled_default" not in mpconfigboard: - mpconfigboard["usb_midi_enabled_default"] = usb_num_endpoint_pairs >= 8 - - tinyusb_files.extend( - (top / "lib/tinyusb/src/common/tusb_fifo.c", top / "lib/tinyusb/src/tusb.c") - ) supervisor_source.extend( - (portdir / "supervisor/usb.c", top / "supervisor/shared/usb/usb.c") + (portdir / "supervisor/usb.c", srcdir / "supervisor/shared/usb.c") ) - tinyusb_files.extend( - ( - top / "lib/tinyusb/src/device/usbd.c", - top / "lib/tinyusb/src/device/usbd_control.c", - ) - ) - supervisor_source.extend( - (top / "supervisor/shared/usb/usb_desc.c", top / "supervisor/shared/usb/usb_device.c") - ) - elif usb_num_endpoint_pairs > 0: - module_reasons["usb_cdc"] = f"No TinyUSB settings for {soc}" - - circuitpython_flags.append(f"-DCIRCUITPY_PORT_SERIAL={0 if usb_ok else 1}") - # 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_VIDEO), 1) - # SRC_SUPERVISOR += \ - # shared-bindings/usb_video/__init__.c \ - # shared-module/usb_video/__init__.c \ - # shared-bindings/usb_video/USBFramebuffer.c \ - # shared-module/usb_video/USBFramebuffer.c \ - # lib/tinyusb/src/class/video/video_device.c \ - - # CFLAGS += -DCFG_TUD_VIDEO=1 -DCFG_TUD_VIDEO_STREAMING=1 -DCFG_TUD_VIDEO_STREAMING_EP_BUFSIZE=256 -DCFG_TUD_VIDEO_STREAMING_BULK=1 - # endif - - # ifeq ($(CIRCUITPY_USB_VENDOR), 1) - # SRC_SUPERVISOR += \ - # lib/tinyusb/src/class/vendor/vendor_device.c \ - - # endif - - # ifeq ($(CIRCUITPY_TINYUSB_HOST), 1) - # SRC_SUPERVISOR += \ - # lib/tinyusb/src/host/hub.c \ - # lib/tinyusb/src/host/usbh.c \ - - # endif - - # ifeq ($(CIRCUITPY_USB_KEYBOARD_WORKFLOW), 1) - # SRC_SUPERVISOR += \ - # lib/tinyusb/src/class/hid/hid_host.c \ - # supervisor/shared/usb/host_keyboard.c \ - - # endif - - if "ssl" in enabled_modules: + creator_id = mpconfigboard.get("CIRCUITPY_CREATOR_ID", mpconfigboard.get("USB_VID")) + creation_id = mpconfigboard.get("CIRCUITPY_CREATION_ID", mpconfigboard.get("USB_PID")) + if creator_id is not None: + circuitpython_flags.append(f"-DCIRCUITPY_CREATOR_ID=0x{creator_id:08x}") + if creation_id is not None: + circuitpython_flags.append(f"-DCIRCUITPY_CREATION_ID=0x{creation_id:08x}") + + # Always use port serial. It'll switch between USB and UART automatically. + circuitpython_flags.append("-DCIRCUITPY_PORT_SERIAL=1") + + if "hashlib" in enabled_modules: + circuitpython_flags.append("-DCIRCUITPY_HASHLIB_MBEDTLS=1") + if "ssl" not in enabled_modules: + circuitpython_flags.append("-DCIRCUITPY_HASHLIB_MBEDTLS_ONLY=1") + + if "ssl" in enabled_modules or "hashlib" in enabled_modules: # TODO: Figure out how to get these paths from zephyr - circuitpython_flags.append('-DMBEDTLS_CONFIG_FILE=\\"config-tls-generic.h\\"') - circuitpython_flags.extend( - ("-isystem", portdir / "modules" / "crypto" / "tinycrypt" / "lib" / "include") - ) + circuitpython_flags.append("-DMBEDTLS_CONFIG_FILE='\"config-mbedtls.h\"'") circuitpython_flags.extend( ("-isystem", portdir / "modules" / "crypto" / "mbedtls" / "include") ) @@ -460,27 +689,48 @@ async def build_circuitpython(): ("-isystem", portdir / "modules" / "crypto" / "mbedtls" / "configs") ) circuitpython_flags.extend( - ("-isystem", portdir / "modules" / "crypto" / "mbedtls" / "include") + ("-isystem", portdir / "modules" / "crypto" / "tf-psa-crypto" / "include") + ) + circuitpython_flags.extend( + ( + "-isystem", + portdir / "modules" / "crypto" / "tf-psa-crypto" / "dispatch" / "include", + ) + ) + circuitpython_flags.extend( + ( + "-isystem", + portdir + / "modules" + / "crypto" + / "tf-psa-crypto" + / "drivers" + / "builtin" + / "include", + ) ) circuitpython_flags.extend(("-isystem", zephyrdir / "modules" / "mbedtls" / "configs")) - supervisor_source.append(top / "lib" / "mbedtls_config" / "crt_bundle.c") + if "ssl" in enabled_modules: + supervisor_source.append(top / "lib" / "mbedtls_config" / "crt_bundle.c") # Make sure all modules have a setting by filling in defaults. hal_source = [] + library_sources = [] autogen_board_info = tomlkit.document() autogen_board_info.add( tomlkit.comment( "This file is autogenerated when a board is built. Do not edit. Do commit it to git. Other scripts use its info." ) ) - autogen_board_info.add("name", board_info["vendor"] + " " + board_info["name"]) + autogen_board_info.add("name", vendor + " " + name) autogen_modules = tomlkit.table() autogen_board_info.add("modules", autogen_modules) for module in sorted( list(top.glob("shared-bindings/*")) + list(portdir.glob("bindings/*")), key=lambda x: x.name, ): - if not module.is_dir(): + # Skip files and directories without C source files (like artifacts from a docs build) + if not module.is_dir() or len(list(module.glob("*.c"))) == 0: continue enabled = module.name in enabled_modules # print(f"Module {module.name} enabled: {enabled}") @@ -488,32 +738,169 @@ async def build_circuitpython(): if module.name in module_reasons: v.comment(module_reasons[module.name]) autogen_modules.add(module.name, v) - circuitpython_flags.append(f"-DCIRCUITPY_{module.name.upper()}={1 if enabled else 0}") + flag_name = MODULE_FLAG_NAMES.get(module.name, module.name.upper()) + circuitpython_flags.append(f"-DCIRCUITPY_{flag_name}={1 if enabled else 0}") + + if enabled: + if module.name in EXTRA_FLAGS: + for flag, value in EXTRA_FLAGS[module.name].items(): + circuitpython_flags.append(f"-DCIRCUITPY_{flag}={value}") if enabled: hal_source.extend(portdir.glob(f"bindings/{module.name}/*.c")) - hal_source.extend(top.glob(f"ports/zephyr-cp/common-hal/{module.name}/*.c")) - hal_source.extend(top.glob(f"shared-bindings/{module.name}/*.c")) - hal_source.extend(top.glob(f"shared-module/{module.name}/*.c")) + len_before = len(hal_source) + if module.name == "zephyr_display": + backend_dir = "lvgl" if lvgl_enabled else "legacy" + hal_source.extend( + top.glob(f"ports/zephyr-cp/common-hal/zephyr_display/{backend_dir}/*.c") + ) + else: + hal_source.extend(top.glob(f"ports/zephyr-cp/common-hal/{module.name}/*.c")) + # Only include shared-module/*.c if no common-hal/*.c files were found + if len(hal_source) == len_before or module.name in SHARED_MODULE_AND_COMMON_HAL: + shared_module_sources = top.glob(f"shared-module/{module.name}/**/*.c") + if module.name == "displayio": + # The compositing core (Group/TileGrid) is selected by backend directory. + backend_dir = "lvgl" if lvgl_enabled else "legacy" + backend_root = top / "shared-module" / "displayio" + shared_module_sources = [ + s + for s in shared_module_sources + # The legacy slot registry is shared by the LVGL compositor so that + # displayio.release_displays() can find displays. + if s.parent.parent != backend_root + or s.parent.name == backend_dir + or (s.parent.name == "legacy" and s.name == "__init__.c") + ] + if module.name in ("busdisplay", "epaperdisplay", "framebufferio"): + # These have legacy scanline implementations and LVGL ones. + backend_dir = "lvgl" if lvgl_enabled else "legacy" + backend_root = top / "shared-module" / module.name + shared_module_sources = [ + s + for s in shared_module_sources + if s.parent == backend_root or s.parent.name == backend_dir + ] + if module.name == "vectorio": + # The vector shape wrapper is selected by backend directory too; the + # shape math (Circle/Polygon/Rectangle) is backend agnostic. + backend_dir = "lvgl" if lvgl_enabled else "legacy" + backend_root = top / "shared-module" / "vectorio" + shared_module_sources = [ + s + for s in shared_module_sources + if s.parent.parent != backend_root or s.parent.name == backend_dir + ] + if module.name == "videocore": + # The video source/target state is shared; only the VideoBuffer's + # compositor mirror is backend specific. + backend_dir = "lvgl" if lvgl_enabled else "legacy" + backend_root = top / "shared-module" / "videocore" + shared_module_sources = [ + s + for s in shared_module_sources + if s.parent == backend_root or s.parent.name == backend_dir + ] + hal_source.extend(shared_module_sources) + # The USB HID report descriptors are shared with the TinyUSB ports and + # have no common-hal override, so always compile them. + if module.name == "usb_hid": + hal_source.append(top / "shared-module/usb_hid/report_descriptors.c") + # busio.SPI is built on common-hal/async_spi, with or without the async_spi module. + if module.name == "busio": + hal_source.append(top / "shared-module/busio/SPI.c") + hal_source.append(top / "ports/zephyr-cp/common-hal/async_spi/SPI.c") + hal_source.extend(top.glob(f"shared-bindings/{module.name}/**/*.c")) + if module.name in LIBRARY_SOURCE: + for library_source in LIBRARY_SOURCE[module.name]: + library_sources.extend(top.glob(library_source)) + + autogen_modules.add(tomlkit.comment("extmod modules shared with MicroPython")) + for extmod_module in EXTMOD_MODULES: + enabled = extmod_module in enabled_modules + v = tomlkit.item(enabled) + if extmod_module in module_reasons: + v.comment(module_reasons[extmod_module]) + autogen_modules.add(extmod_module, v) + flag_name = MODULE_FLAG_NAMES.get(extmod_module, extmod_module.upper()) + circuitpython_flags.append(f"-DCIRCUITPY_{flag_name}={1 if enabled else 0}") if os.environ.get("CI", "false") == "true": - # Fail the build if it isn't up to date. + # Warn if it isn't up to date. if ( not autogen_board_info_fn.exists() or autogen_board_info_fn.read_text() != tomlkit.dumps(autogen_board_info) ): - logger.error("autogen_board_info.toml is out of date.") - raise RuntimeError( + logger.warning( f"autogen_board_info.toml is missing or out of date. Please run `make BOARD={board}` locally and commit {autogen_board_info_fn}." ) - elif autogen_board_info_fn.parent.exists(): + # Also as an annotation, so it shows on the run and next to the file in the + # pull request rather than in one board log out of 29. The board builds once + # per language, so only the first build of it says anything. + reported = builddir / "autogen_board_info.reported" + if not reported.exists(): + reported.touch() + print( + f"::warning file={autogen_board_info_fn.relative_to(srcdir)}::" + f"out of date, run `make BOARD={board}` and commit it", + flush=True, + ) + + if autogen_board_info_fn.parent.exists(): autogen_board_info_fn.write_text(tomlkit.dumps(autogen_board_info)) + # Set NVM size from the board's NVM partition. + nvm_size = board_info.get("nvm_size", 0) + circuitpython_flags.append(f"-DCIRCUITPY_INTERNAL_NVM_SIZE={nvm_size}") + if nvm_size > 0: + circuitpython_flags.append("-DCIRCUITPY_INTERNAL_NVM_START_ADDR=0") + for mpflag in MPCONFIG_FLAGS: enabled = mpflag in DEFAULT_MODULES circuitpython_flags.append(f"-DCIRCUITPY_{mpflag.upper()}={1 if enabled else 0}") + # ulab is on by default and boards that cannot spare the flash set + # CIRCUITPY_ULAB = false in their circuitpython.toml. Flags mirror py/py.mk. + ulab_enabled = mpconfigboard.get("CIRCUITPY_ULAB", True) + circuitpython_flags.append(f"-DCIRCUITPY_ULAB={1 if ulab_enabled else 0}") + if ulab_enabled: + circuitpython_flags.extend( + ( + "-DMODULE_ULAB_ENABLED=1", + "-DULAB_HAS_USER_MODULE=0", + "-iquote", + str(top / "extmod" / "ulab" / "code"), + ) + ) + # radio.ping() builds on Zephyr's ICMP API. On by default; boards that cannot + # spare the flash set CIRCUITPY_WIFI_PING = false in their circuitpython.toml + # and radio.ping() then reports no reply, as it does for an unreachable host. + circuitpython_flags.append( + f"-DCIRCUITPY_WIFI_PING={1 if mpconfigboard.get('CIRCUITPY_WIFI_PING', True) else 0}" + ) + + # The busio and async_spi modules both name common-hal/async_spi/SPI.c. + hal_source = list(dict.fromkeys(hal_source)) source_files = supervisor_source + hal_source + ["extmod/vfs.c"] + if filesystem_littlefs: + source_files.extend( + ( + "extmod/vfs_lfs.c", + "lib/littlefs/lfs2.c", + "lib/littlefs/lfs2_util.c", + ) + ) + circuitpython_flags.extend( + ( + "-DLFS2_NO_MALLOC", + "-DLFS2_NO_DEBUG", + "-DLFS2_NO_WARN", + "-DLFS2_NO_ERROR", + "-DLFS2_NO_ASSERT", + ) + ) + if ulab_enabled: + source_files.extend(sorted((top / "extmod" / "ulab" / "code").rglob("*.c"))) assembly_files = [] for file in top.glob("py/*.c"): source_files.append(file) @@ -531,7 +918,7 @@ async def build_circuitpython(): if "ssl" in enabled_modules: crt_bundle = builddir / "x509_crt_bundle.S" - roots_pem = srcdir / "lib/certificates/data/roots.pem" + roots_pem = srcdir / "lib/certificates/data/roots-full.pem" generator = srcdir / "tools/gen_crt_bundle.py" tg.create_task( cpbuild.run_command( @@ -559,6 +946,25 @@ async def build_circuitpython(): tg.create_task(generate_module_header(board_build)) tg.create_task(generate_root_pointer_header(board_build)) + if "terminalio" in enabled_modules: + output_path = board_build / f"autogen_display_resources-{translation}.c" + font_path = srcdir / mpconfigboard.get( + "CIRCUITPY_DISPLAY_FONT", "tools/fonts/ter-u12n.bdf" + ) + extra_characters = mpconfigboard.get("CIRCUITPY_FONT_EXTRA_CHARACTERS", "") + tg.create_task( + generate_display_resources( + output_path, translation, font_path, extra_characters, lvgl_enabled + ) + ) + source_files.append(output_path) + + if web_workflow_enabled: + output_path = board_build / "autogen_web_workflow_static.c" + static_files = sorted((srcdir / "supervisor/shared/web_workflow/static").glob("*")) + tg.create_task(generate_web_workflow_static(output_path, static_files)) + source_files.append(output_path) + # This file is generated by the QSTR/translation process. source_files.append(builddir / f"translations-{translation}.c") # These files don't include unique QSTRs. They just need to be compiled. @@ -576,14 +982,16 @@ async def build_circuitpython(): source_files.append(portdir / "common-hal/zephyr_kernel/__init__.c") # source_files.append(srcdir / "ports" / port / "peripherals" / "nrf" / "nrf52840" / "pins.c") - assembly_files.append(srcdir / "ports/nordic/supervisor/cpu.s") - source_files.extend(assembly_files) - source_files.extend(tinyusb_files) - objects = [] async with asyncio.TaskGroup() as tg: + for source_file in library_sources: + source_file = top / source_file + build_file = source_file.with_suffix(".o") + object_file = builddir / (build_file.relative_to(top)) + objects.append(object_file) + tg.create_task(compiler.compile(source_file, object_file)) for source_file in source_files: source_file = top / source_file build_file = source_file.with_suffix(".o") diff --git a/ports/zephyr-cp/cptools/check_partitions.py b/ports/zephyr-cp/cptools/check_partitions.py new file mode 100644 index 00000000000..92016eaaac3 --- /dev/null +++ b/ports/zephyr-cp/cptools/check_partitions.py @@ -0,0 +1,461 @@ +#!/usr/bin/env python3 +"""Check the flash partition layout a board's devicetree actually resolved to. + +Board overlays in ``boards/`` routinely rebuild the ``partitions`` node so the +board gets a CIRCUITPY filesystem. Rebuilding it is easy to get subtly wrong in +a way nothing reports: drop the ``ranges;`` the board DTS declared and +devicetree stops translating partition addresses into the SoC's address space, +so every partition resolves to a bare offset instead. The build still succeeds. +What changes is anything keyed off the address -- on RP2040, +``RP2_REQUIRES_SECOND_STAGE_BOOT`` matches the code partition against +0x10000100, so a partition left at 0x100 silently turns it off and the UF2 is +built for the wrong address with no second stage bootloader linked in. + +A board that CircuitPython also builds from another port (``counterpart`` in its +``circuitpython.toml``) is additionally compared with that build: nvm and the +CIRCUITPY drive must sit exactly where ``ports/`` puts them, or switching +firmware between the two builds loses the user's data. The expected placement +is derived from the counterpart's configuration files the same way its +``mpconfigport.h`` derives it. + +This reads the ``edt.pickle`` a build already produced, so it costs no build +time -- point it at build directories after building, or run it with no +arguments to check every build directory in the port. + + python cptools/check_partitions.py # every build-* dir + python cptools/check_partitions.py build-raspberrypi_rpi_pico_zephyr + python cptools/check_partitions.py --board raspberrypi_rpi_pico_zephyr build-x + +Exits non-zero when a layout has problems. +""" + +import argparse +import pathlib +import pickle +import re +import sys +import tomllib + +import board_tools + +PORT_DIR = pathlib.Path(__file__).resolve().parent.parent +TOP = PORT_DIR.parent.parent +EDT_MODULE = PORT_DIR / "zephyr" / "scripts" / "dts" / "python-devicetree" / "src" + +# Parity with the non-Zephyr build. A board that CircuitPython also builds from another +# port (ports/raspberrypi, ports/nordic) names it in circuitpython.toml: +# +# counterpart = "raspberrypi/raspberry_pi_pico_w" +# +# The nvm and CIRCUITPY drive of the Zephyr build then have to sit exactly where that +# build puts them, so that switching firmware between the two never loses user data. +# The expected placement is derived from the counterpart's own configuration files, the +# same way its mpconfigport.h derives it, rather than copied into the overlay by hand. +DEFINE_RE = re.compile(r"^\s*#\s*define\s+([A-Za-z_]\w*)\s+(.+?)\s*(?://.*|/\*.*)?$", re.MULTILINE) +CFLAG_DEFINE_RE = re.compile(r"-D([A-Za-z_]\w*)=(?:'([^']*)'|\"([^\"]*)\"|(\S+))") +MK_ASSIGN_RE = re.compile(r"^\s*([A-Za-z_]\w*)\s*[?:+]?=\s*(.*?)\s*$", re.MULTILINE) +IDENTIFIER_RE = re.compile(r"(?]+$") + + +def load_edt(build_dir): + """Load the pickled devicetree a build produced, or None if there is none.""" + edt_path = build_dir / "zephyr-cp" / "zephyr" / "edt.pickle" + if not edt_path.is_file(): + edt_path = build_dir / "zephyr" / "edt.pickle" + if not edt_path.is_file(): + return None + sys.path.insert(0, str(EDT_MODULE)) + with open(edt_path, "rb") as f: + return pickle.load(f) + + +def partition_device(node): + """Walk up to the NVM device owning a partition. + + The device is the first ancestor carrying ``reg``; the ``partitions`` + grouping node in between has none. + """ + parent = getattr(node, "parent", None) + while parent is not None: + if parent.props.get("reg") is not None: + return parent + parent = getattr(parent, "parent", None) + return None + + +def device_size(node): + """Total size of an NVM device. + + External SPI/QSPI NOR carries its capacity in the ``size`` property (in + bits) and uses ``reg`` for the chip select, so reading ``reg`` alone gives + 0 for exactly the devices CIRCUITPY usually lives on. + """ + size = node.props.get("size") + if size: + return size.val // 8 + reg = node.props.get("reg") + if reg and len(reg.val) >= 2: + return reg.val[1] + return 0 + + +def is_partition_child(node): + """True for any node under a ``partitions`` grouping node. + + Membership is positional rather than by ``compatible``: an overlay may add + a partition carrying neither ``zephyr,mapped-partition`` nor a + ``fixed-partitions`` parent, and it still occupies the space and still is + what the layout means to describe. + """ + parent = getattr(node, "parent", None) + return parent is not None and getattr(parent, "name", "") == "partitions" + + +def iter_partitions(edt): + """Yield ``(node, device, offset, size, mapped)`` for every partition.""" + for node in edt.nodes: + mapped = "zephyr,mapped-partition" in getattr(node, "compats", []) + if not mapped and not is_partition_child(node): + continue + reg = node.props.get("reg") + if not reg or len(reg.val) < 2: + continue + dev = partition_device(node) + if dev is None: + continue + if mapped and (not getattr(node, "regs", None) or not getattr(dev, "regs", None)): + continue + yield node, dev, reg.val[0], reg.val[1], mapped + + +def check_layout(edt): + """Return a list of problems with the resolved layout. + + Mapped partitions are checked for address translation; every partition is + checked for overlap and for running past the end of its device. Erase-page + alignment is not checked: RP2040 deliberately puts its code partition at + 0x100, directly behind the 256-byte second stage bootloader. + """ + problems = [] + by_device = {} + for node, dev, offset, size, mapped in iter_partitions(edt): + label = node.labels[0] if node.labels else node.name + dev_label = dev.labels[0] if dev.labels else dev.name + total = device_size(dev) + if mapped: + # Test the resolved address against the device's own window rather + # than against base + reg. Both forms are in use: a partition reg + # is usually an offset, but some overlays write the absolute + # address and leave the partitions node without ranges, which + # resolves to the same correct address. What is never right is a + # partition resolving outside the device it lives in -- which is + # exactly what a rebuilt partitions node missing ranges; produces, + # since the offset is then left untranslated. + base = dev.regs[0].addr + actual = node.regs[0].addr + if total and not (base <= actual < base + total): + problems.append( + f"{label}: resolves to 0x{actual:x}, outside {dev_label} " + f"(0x{base:x}-0x{base + total:x}) -- address translation is " + f"broken; does the partitions node declare ranges;?" + ) + # Geometry below is compared in offsets from the device base, so a + # partition declared either way lands in the same space. When the + # translation is broken the difference is meaningless (and often + # negative), so keep the declared offset rather than running the + # geometry checks on nonsense. + translated = actual - base + if 0 <= translated and (not total or translated < total): + offset = translated + by_device.setdefault(dev_label, (dev, total, []))[2].append((label, offset, size)) + + for dev_label, (dev, total, parts) in sorted(by_device.items()): + ordered = sorted(parts, key=lambda p: p[1]) + for label, offset, size in ordered: + if total and offset + size > total: + problems.append( + f"{label}: ends at 0x{offset + size:x}, past the end of " + f"{dev_label} (0x{total:x})" + ) + # A running high-water mark, not neighbouring pairs: a partition + # spanning several later ones only overlaps its immediate successor in + # a pairwise walk. + high_label, high_end = None, 0 + for label, offset, size in ordered: + if offset < high_end: + problems.append( + f"{high_label} (ends 0x{high_end:x}) overlaps " + f"{label} (starts 0x{offset:x}) on {dev_label}" + ) + if offset + size > high_end: + high_label, high_end = label, offset + size + return problems + + +def read_defines(paths): + """Collect ``#define``s, ``-D`` flags and make assignments from configuration files. + + The first definition of a name wins, and files earlier in ``paths`` take + precedence, so list the board's files before the port's defaults. + """ + defines = {} + for path in paths: + if not path.is_file(): + continue + text = path.read_text() + if path.suffix == ".mk": + for match in CFLAG_DEFINE_RE.finditer(text): + value = next(v for v in match.groups()[1:] if v is not None) + defines.setdefault(match.group(1), value) + for match in MK_ASSIGN_RE.finditer(text): + defines.setdefault(match.group(1), match.group(2)) + else: + for match in DEFINE_RE.finditer(text): + defines.setdefault(match.group(1), match.group(2)) + return defines + + +def evaluate(defines, name, default=None): + """Integer value of a define, following references to other defines. + + Returns ``default`` when the name is undefined and None when it cannot be + evaluated, so that a layout is never declared correct on a guess. + """ + expr = defines.get(name) + if expr is None: + return default + for ident in sorted(set(IDENTIFIER_RE.findall(expr)), key=len, reverse=True): + value = evaluate(defines, ident) + if value is None: + return None + expr = re.sub(rf"(?/`` under ``ports/`` and ``flash_size`` the + size of the internal flash. Returns ``{"nvm": (offset, size), "circuitpy": + (offset, size)}``; ``"circuitpy"`` is the string ``"external"`` when that + build uses a whole external flash chip as the drive. Raises ValueError when + the port's rules are unknown or a value cannot be derived. + """ + port, _, board = counterpart.partition("/") + port_dir = TOP / "ports" / port + board_dir = port_dir / "boards" / board + if not board_dir.is_dir(): + raise ValueError(f"{counterpart}: no such board under ports/") + defines = read_defines( + [ + board_dir / "mpconfigboard.mk", + board_dir / "mpconfigboard.h", + port_dir / "mpconfigport.mk", + port_dir / "mpconfigport.h", + ] + ) + + def value(name, default=None): + result = evaluate(defines, name, default) + if result is None: + raise ValueError(f"{counterpart}: cannot evaluate {name}") + return result + + if port == "raspberrypi": + # ports/raspberrypi/mpconfigport.h: nvm directly follows the firmware region, + # the drive follows nvm (and the saves partition on boards that have one). + firmware = value("CIRCUITPY_FIRMWARE_SIZE") + nvm_size = value("CIRCUITPY_INTERNAL_NVM_SIZE") + drive = firmware + nvm_size + value("CIRCUITPY_SAVES_PARTITION_SIZE", 0) + return {"nvm": (firmware, nvm_size), "circuitpy": (drive, flash_size - drive)} + if port == "nordic": + # ports/nordic/mpconfigport.h: the bootloader sits at the top of flash, an + # internal filesystem (when there is one) directly below it and nvm below that. + bootloader = ( + flash_size + - value("BOOTLOADER_SIZE") + - value("BOOTLOADER_SETTINGS_SIZE") + - value("BOOTLOADER_MBR_SIZE") + ) + external = any( + defines.get(flag, "0").strip() == "1" + for flag in ("QSPI_FLASH_FILESYSTEM", "SPI_FLASH_FILESYSTEM") + ) + fs_size = 0 if external else value("CIRCUITPY_INTERNAL_FLASH_FILESYSTEM_SIZE") + fs_start = bootloader - fs_size + nvm_size = value("CIRCUITPY_INTERNAL_NVM_SIZE") + return { + "nvm": (fs_start - nvm_size, nvm_size), + "circuitpy": "external" if external else (fs_start, fs_size), + } + raise ValueError(f"{counterpart}: no layout rules known for port {port}") + + +def is_internal_flash(node): + return "soc-nv-flash" in getattr(node, "compats", []) + + +def is_external_flash(node): + return node.props.get("size") is not None and any( + "nor" in compat for compat in getattr(node, "compats", []) + ) + + +def check_parity(edt, counterpart): + """Return problems where the layout differs from the non-Zephyr ``counterpart``.""" + internal = [node for node in edt.nodes if is_internal_flash(node)] + if not internal: + return [f"no soc-nv-flash device to compare with {counterpart}"] + try: + expected = reference_layout(counterpart, device_size(internal[0])) + except ValueError as e: + return [str(e)] + + partitions = {} + for node, dev, offset, size, mapped in iter_partitions(edt): + label = node.labels[0] if node.labels else node.name + partitions[label] = (dev, offset, size) + + problems = [] + + def compare(label, want): + found = partitions.get(label) + if found is None: + problems.append( + f"{label}: missing, {counterpart} has it at 0x{want[0]:x}+0x{want[1]:x}" + ) + return + dev, offset, size = found + if not is_internal_flash(dev): + problems.append(f"{label}: not on the internal flash, unlike {counterpart}") + if (offset, size) != want: + problems.append( + f"{label}: 0x{offset:x}+0x{size:x}, {counterpart} has it at " + f"0x{want[0]:x}+0x{want[1]:x}" + ) + + compare("nvm_partition", expected["nvm"]) + if expected["circuitpy"] == "external": + # supervisor/flash.c uses the first flash device no partition covers as the + # drive, which is the whole chip only while the chip carries no partitions. + # An explicit single partition covering the whole chip is equivalent -- + # it pins the drive to the same area the dynamic-area fallback would + # claim -- so allow exactly that: one external partition starting at + # offset 0. Anything else on external flash (extra partitions, or a + # partition that doesn't start at 0) would not be claimed by the + # fallback and breaks the drive. + external = [node for node in edt.nodes if is_external_flash(node)] + if not external: + problems.append(f"no external flash, but {counterpart} keeps the drive on one") + external_partitions = [ + (dev, offset, size) + for dev, offset, size in partitions.values() + if is_external_flash(dev) + ] + whole_chip_ok = len(external_partitions) == 1 and external_partitions[0][1] == 0 + if external_partitions and not whole_chip_ok: + dev = external_partitions[0][0] + problems.append( + f"{dev.labels[0] if dev.labels else dev.name}: carries partitions, " + f"but {counterpart} uses the whole chip as the drive" + ) + else: + # The partition is on internal flash. The fork names it + # fatfs_partition (boards with native USB) or littlefs_partition (no + # USB); the older CircuitPython port layout named it circuitpy_partition. + # supervisor/flash.c accepts all three via FIXED_PARTITION_EXISTS. + want = expected["circuitpy"] + fs_labels = ("circuitpy_partition", "fatfs_partition", "littlefs_partition") + found = next( + (partitions[label] for label in fs_labels if label in partitions), + None, + ) + if found is None: + problems.append( + f"circuitpy_partition: missing, {counterpart} has it at " + f"0x{want[0]:x}+0x{want[1]:x}" + ) + else: + dev, offset, size = found + if not is_internal_flash(dev): + problems.append( + f"circuitpy_partition: not on the internal flash, unlike {counterpart}" + ) + if (offset, size) != want: + problems.append( + f"circuitpy_partition: 0x{offset:x}+0x{size:x}, {counterpart} has it at " + f"0x{want[0]:x}+0x{want[1]:x}" + ) + return problems + + +def counterpart_of(board_id): + """The ``counterpart`` a board declares in its circuitpython.toml, if any.""" + toml_path = board_tools.find_mpconfigboard(PORT_DIR, board_id) if board_id else None + if toml_path is None: + return None + with toml_path.open("rb") as f: + return tomllib.load(f).get("counterpart") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument( + "build_dirs", + nargs="*", + help="Build directories to check (default: every build-* in the port)", + ) + parser.add_argument( + "--board", + help="Board built in the (single) build directory; default: taken from its name", + ) + args = parser.parse_args() + + dirs = [pathlib.Path(d) for d in args.build_dirs] + if not dirs: + dirs = sorted(p for p in PORT_DIR.glob("build-*") if p.is_dir()) + if not dirs: + print("No build directories found; build a board first.", file=sys.stderr) + return 1 + if args.board and len(dirs) != 1: + parser.error("--board applies to exactly one build directory") + + failed = [] + checked = 0 + for build_dir in dirs: + edt = load_edt(build_dir) + if edt is None: + continue + checked += 1 + n_parts = sum(1 for _ in iter_partitions(edt)) + problems = check_layout(edt) + board = args.board or build_dir.name.removeprefix("build-") + counterpart = counterpart_of(board) + if counterpart: + problems += check_parity(edt, counterpart) + if problems: + failed.append(build_dir.name) + print(f"{build_dir.name}:") + for problem in problems: + print(f" FAIL {problem}") + else: + # Say how much was inspected: a board whose overlay defines no + # partitions at all would otherwise be indistinguishable from a + # verified-good one. + parity = f", matches ports/{counterpart}" if counterpart else "" + print(f"{build_dir.name}: ok ({n_parts} partitions checked{parity})") + + if not checked: + print("No build directory held an edt.pickle; build a board first.", file=sys.stderr) + return 1 + if failed: + print(f"\n{len(failed)} board(s) with layout problems: {', '.join(failed)}") + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/ports/zephyr-cp/cptools/compat2driver.py b/ports/zephyr-cp/cptools/compat2driver.py index 2b818c4c237..186c70e77b9 100644 --- a/ports/zephyr-cp/cptools/compat2driver.py +++ b/ports/zephyr-cp/cptools/compat2driver.py @@ -1,18 +1,31 @@ # This file was generated by gen_compat2driver.py COMPAT_TO_DRIVER = { # adc + "adi_ad4050_adc": "adc", + "adi_ad4052_adc": "adc", "adi_ad4114_adc": "adc", + "adi_ad4130_adc": "adc", + "adi_ad4170_adc": "adc", + "adi_ad4190_adc": "adc", + "adi_ad4195_adc": "adc", "adi_ad559x_adc": "adc", + "adi_ad7124_adc": "adc", "adi_max32_adc": "adc", "ambiq_adc": "adc", "atmel_sam0_adc": "adc", "atmel_sam_adc": "adc", "atmel_sam_afec": "adc", + "bflb_adc": "adc", + "ene_kb106x_adc": "adc", "ene_kb1200_adc": "adc", "espressif_esp32_adc": "adc", "gd_gd32_adc": "adc", - "infineon_cat1_adc": "adc", + "infineon_adc": "adc", + "infineon_autanalog_sar_adc": "adc", + "infineon_hppass_sar_adc": "adc", + "infineon_sar_adc": "adc", "infineon_xmc4xxx_adc": "adc", + "ite_it51xxx_adc": "adc", "ite_it8xxx2_adc": "adc", "lltc_ltc2451": "adc", "maxim_max11102": "adc", @@ -26,6 +39,8 @@ "maxim_max11117": "adc", "maxim_max11253": "adc", "maxim_max11254": "adc", + "microchip_adc_g1": "adc", + "microchip_mcp356xr": "adc", "microchip_xec_adc": "adc", "nordic_nrf_adc": "adc", "nordic_nrf_saadc": "adc", @@ -37,13 +52,23 @@ "nxp_lpc_lpadc": "adc", "nxp_mcux_12b1msps_sar": "adc", "nxp_s32_adc_sar": "adc", + "nxp_sar_adc": "adc", "nxp_vf610_adc": "adc", "raspberrypi_pico_adc": "adc", - "renesas_ra_adc": "adc", + "realtek_rts5912_adc": "adc", + "renesas_ra_adc12": "adc", + "renesas_ra_adc16": "adc", + "renesas_rx_adc": "adc", + "renesas_rz_adc": "adc", + "renesas_rz_adc_c": "adc", + "renesas_rz_adc_e": "adc", + "renesas_rza2m_adc": "adc", "renesas_smartbond_adc": "adc", "renesas_smartbond_sdadc": "adc", + "sifli_sf32lb_gpadc": "adc", "silabs_gecko_adc": "adc", - "silabs_gecko_iadc": "adc", + "silabs_iadc": "adc", + "silabs_siwx91x_adc": "adc", "st_stm32_adc": "adc", "st_stm32wb0_adc": "adc", "telink_b91_adc": "adc", @@ -55,10 +80,27 @@ "ti_ads1114": "adc", "ti_ads1115": "adc", "ti_ads1119": "adc", + "ti_ads114s06": "adc", "ti_ads114s08": "adc", + "ti_ads124s06": "adc", + "ti_ads124s08": "adc", "ti_ads131m02": "adc", "ti_ads7052": "adc", + "ti_ads7950": "adc", + "ti_ads7951": "adc", + "ti_ads7952": "adc", + "ti_ads7953": "adc", + "ti_ads7954": "adc", + "ti_ads7955": "adc", + "ti_ads7956": "adc", + "ti_ads7957": "adc", + "ti_ads7958": "adc", + "ti_ads7959": "adc", + "ti_ads7960": "adc", + "ti_ads7961": "adc", + "ti_am335x_adc": "adc", "ti_cc13xx_cc26xx_adc": "adc", + "ti_cc23x0_adc": "adc", "ti_cc32xx_adc": "adc", "ti_lmp90077": "adc", "ti_lmp90078": "adc", @@ -72,40 +114,65 @@ "ti_tla2022": "adc", "ti_tla2024": "adc", "vnd_adc": "adc", + "wch_adc": "adc", "zephyr_adc_emul": "adc", # # audio + "ambiq_pdm": "audio", + "cirrus_cs43l22": "audio", + "dlg_da7212": "audio", + "maxim_max98091": "audio", + "nordic_nrf_pdm": "audio", "nxp_dmic": "audio", + "nxp_micfil": "audio", + "sifli_sf32lb_audcodec": "audio", "st_mpxxdtyy": "audio", + "ti_pcm1681": "audio", "ti_tas6422dac": "audio", + "ti_tlv320aic3110": "audio", "ti_tlv320dac": "audio", "wolfson_wm8904": "audio", + "wolfson_wm8962": "audio", + # + # audio/mic_privacy/intel + "intel_adsp_mic_privacy": "audio/mic_privacy/intel", # # auxdisplay + "gpio_7_segment": "auxdisplay", "hit_hd44780": "auxdisplay", "jhd_jhd1313": "auxdisplay", "noritake_itron": "auxdisplay", "ptc_pt6314": "auxdisplay", "sparkfun_serlcd": "auxdisplay", + "titanmec_tm1637": "auxdisplay", # # bbram "ite_it8xxx2_bbram": "bbram", "microchip_xec_bbram": "bbram", + "motorola_mc146818_bbram": "bbram", "nuvoton_npcx_bbram": "bbram", + "realtek_rts5912_bbram": "bbram", "st_stm32_bbram": "bbram", "zephyr_bbram_emul": "bbram", # + # biometrics + "adh_tech_gt5x": "biometrics", + "zephyr_biometrics_emul": "biometrics", + "zhiantec_zfm_x0": "biometrics", + # # bluetooth/hci "ambiq_bt_hci_spi": "bluetooth/hci", "espressif_esp32_bt_hci": "bluetooth/hci", - "infineon_cat1_bless_hci": "bluetooth/hci", + "infineon_bless_hci": "bluetooth/hci", + "infineon_bt_hci_uart": "bluetooth/hci", "infineon_cyw208xx_hci": "bluetooth/hci", - "infineon_cyw43xxx_bt_hci": "bluetooth/hci", "nxp_bt_hci_uart": "bluetooth/hci", "nxp_hci_ble": "bluetooth/hci", "renesas_bt_hci_da1453x": "bluetooth/hci", "renesas_bt_hci_da1469x": "bluetooth/hci", + "sifli_sf32lb_mailbox": "bluetooth/hci", "silabs_bt_hci_efr32": "bluetooth/hci", + "silabs_siwx91x_bt_hci": "bluetooth/hci", "st_hci_spi_v1": "bluetooth/hci", "st_hci_spi_v2": "bluetooth/hci", "st_hci_stm32wb0": "bluetooth/hci", @@ -116,8 +183,13 @@ "zephyr_bt_hci_spi": "bluetooth/hci", "zephyr_bt_hci_uart": "bluetooth/hci", "zephyr_bt_hci_userchan": "bluetooth/hci", + "zephyr_bt_hci_ll_sw_split": "bluetooth/hci", + # + # cache + "bflb_l1c": "cache", # # can + "adi_max32_can": "can", "atmel_sam0_can": "can", "atmel_sam_can": "can", "espressif_esp32_twai": "can", @@ -132,6 +204,7 @@ "nxp_s32_canxl": "can", "renesas_ra_canfd": "can", "renesas_rcar_can": "can", + "renesas_rz_canfd": "can", "st_stm32_bxcan": "can", "st_stm32_fdcan": "can", "st_stm32h7_fdcan": "can", @@ -145,21 +218,43 @@ # # charger "maxim_max20335_charger": "charger", + "nxp_pca9422_charger": "charger", + "nxp_pf1550_charger": "charger", "sbs_sbs_charger": "charger", "ti_bq24190": "charger", "ti_bq25180": "charger", + "ti_bq25186": "charger", + "ti_bq25188": "charger", + "ti_bq25713": "charger", + "x_powers_axp2101_charger": "charger", + "zephyr_charger_gpio": "charger", # # clock_control "adi_max32_gcr": "clock_control", + "alif_clockctrl": "clock_control", "ambiq_clkctrl": "clock_control", "arm_beetle_syscon": "clock_control", "arm_scmi_clock": "clock_control", "aspeed_ast10x0_clock": "clock_control", "atmel_sam_pmc": "clock_control", - "espressif_esp32_rtc": "clock_control", + "bflb_bl60x_clock_controller": "clock_control", + "bflb_bl61x_clock_controller": "clock_control", + "bflb_bl70x_clock_controller": "clock_control", + "espressif_esp32_clock": "clock_control", "fixed_clock": "clock_control", + "focaltech_ft9001_cpm": "clock_control", "gd_gd32_cctl": "clock_control", + "infineon_fixed_clock": "clock_control", + "infineon_fixed_factor_clock": "clock_control", + "infineon_peri_div": "clock_control", "intel_agilex5_clock": "clock_control", + "ite_it51xxx_ecpm": "clock_control", + "microchip_pic32cm_jh_clock": "clock_control", + "microchip_pic32cm_pl_clock": "clock_control", + "microchip_pic32cz_ca_clock": "clock_control", + "microchip_sam_d5x_e5x_clock": "clock_control", + "microchip_sam_pmc": "clock_control", + "microchip_sama7g5_sckc": "clock_control", "microchip_xec_pcr": "clock_control", "nordic_nrf54h_hfxo": "clock_control", "nordic_nrf_auxpll": "clock_control", @@ -167,7 +262,9 @@ "nordic_nrf_fll16m": "clock_control", "nordic_nrf_hsfll_global": "clock_control", "nordic_nrf_hsfll_local": "clock_control", + "nordic_nrf_iron_hsfll_local": "clock_control", "nordic_nrf_lfclk": "clock_control", + "nordic_nrfs_audiopll": "clock_control", "nuvoton_npcm_pcc": "clock_control", "nuvoton_npcx_pcc": "clock_control", "nuvoton_numaker_scc": "clock_control", @@ -179,27 +276,51 @@ "nxp_kinetis_sim": "clock_control", "nxp_lpc11u6x_syscon": "clock_control", "nxp_lpc_syscon": "clock_control", + "nxp_mc_cgm": "clock_control", "nxp_s32_clock": "clock_control", "nxp_scg_k4": "clock_control", "openisa_rv32m1_pcc": "clock_control", "pwm_clock": "clock_control", "raspberrypi_pico_clock_controller": "clock_control", + "realtek_bee_cctl": "clock_control", + "realtek_rts5817_clock": "clock_control", "realtek_rts5912_sccon": "clock_control", "renesas_r8a7795_cpg_mssr": "clock_control", "renesas_r8a779f0_cpg_mssr": "clock_control", + "renesas_ra_cgc_subclk": "clock_control", + "renesas_rx_cgc_pclk": "clock_control", + "renesas_rx_cgc_pll": "clock_control", + "renesas_rx_cgc_root_clock": "clock_control", + "renesas_rz_cgc": "clock_control", + "renesas_rz_cpg": "clock_control", + "renesas_rza2m_cpg": "clock_control", + "sifli_sf32lb_hxt48": "clock_control", + "sifli_sf32lb_rcc_clk": "clock_control", "silabs_series_clock": "clock_control", "silabs_si32_ahb": "clock_control", "silabs_si32_apb": "clock_control", "silabs_si32_pll": "clock_control", + "silabs_siwx91x_clock": "clock_control", "smartbond_clock": "clock_control", "st_stm32_clock_mco": "clock_control", "st_stm32_clock_mux": "clock_control", "st_stm32f1_clock_mco": "clock_control", + "ti_k2g_sci_clk": "clock_control", "wch_rcc": "clock_control", # # comparator + "ite_it51xxx_vcmp": "comparator", + "microchip_ac_g1_comparator": "comparator", "nordic_nrf_comp": "comparator", "nordic_nrf_lpcomp": "comparator", + "nxp_acomp": "comparator", + "nxp_cmp": "comparator", + "nxp_hscmp": "comparator", + "renesas_ra_acmphs": "comparator", + "renesas_ra_lvd": "comparator", + "renesas_rx_lvd": "comparator", + "silabs_acmp": "comparator", + "st_stm32_comp": "comparator", "zephyr_fake_comp": "comparator", # # coredump @@ -208,21 +329,34 @@ # counter "adi_max32_counter": "counter", "adi_max32_rtc_counter": "counter", + "adi_max32_wut": "counter", "ambiq_counter": "counter", "andestech_atcpit100": "counter", "arm_cmsdk_dtimer": "counter", "arm_cmsdk_timer": "counter", "atmel_sam0_tc32": "counter", "atmel_sam_tc": "counter", + "espressif_esp32_counter": "counter", "espressif_esp32_rtc_timer": "counter", - "espressif_esp32_timer": "counter", "gd_gd32_timer": "counter", - "infineon_cat1_counter": "counter", + "infineon_counter": "counter", + "infineon_tcpwm_counter": "counter", + "ite_it51xxx_counter": "counter", + "ite_it8xxx2_counter": "counter", "maxim_ds3231": "counter", "microchip_mcp7940n": "counter", + "microchip_sam_pit64b_counter": "counter", + "microchip_tc_g1_counter": "counter", + "microchip_tcc_g1_counter": "counter", "microchip_xec_timer": "counter", + "microcrystal_rv3032_counter": "counter", + "neorv32_gptmr": "counter", "nordic_nrf_rtc": "counter", "nordic_nrf_timer": "counter", + "nuvoton_npck_lct": "counter", + "nuvoton_npcx_lct_v1": "counter", + "nuvoton_npcx_lct_v2": "counter", + "nxp_ftm": "counter", "nxp_imx_epit": "counter", "nxp_imx_gpt": "counter", "nxp_imx_qtmr": "counter", @@ -231,37 +365,68 @@ "nxp_lpc_ctimer": "counter", "nxp_lpc_rtc": "counter", "nxp_lpc_rtc_highres": "counter", + "nxp_lpit": "counter", "nxp_mrt": "counter", "nxp_pit": "counter", "nxp_rtc": "counter", + "nxp_rtc_jdp": "counter", "nxp_s32_sys_timer": "counter", + "nxp_stm": "counter", "nxp_tpm_timer": "counter", + "raspberrypi_pico_pit": "counter", + "raspberrypi_pico_pit_channel": "counter", "raspberrypi_pico_timer": "counter", + "realtek_rts5912_slwtimer": "counter", + "realtek_rts5912_timer": "counter", "renesas_ra_agt_counter": "counter", + "renesas_rz_cmtw_counter": "counter", + "renesas_rz_gtm_counter": "counter", "renesas_smartbond_timer": "counter", + "silabs_burtc_counter": "counter", "silabs_gecko_rtcc": "counter", - "silabs_gecko_stimer": "counter", + "silabs_timer_counter": "counter", "snps_dw_timers": "counter", "st_stm32_counter": "counter", + "ti_cc23x0_lgpt": "counter", + "ti_cc23x0_rtc": "counter", + "ti_mspm0_timer_counter": "counter", "xlnx_xps_timer_1_00_a": "counter", - "zephyr_native_posix_counter": "counter", + "zephyr_native_sim_counter": "counter", + # + # crc + "nxp_crc": "crc", + "nxp_lpc_crc": "crc", + "renesas_ra_crc": "crc", + "sifli_sf32lb_crc": "crc", # # crypto "atmel_ataes132a": "crypto", + "espressif_esp32_aes": "crypto", + "espressif_esp32_sha": "crypto", "intel_adsp_sha": "crypto", + "ite_it51xxx_sha": "crypto", "ite_it8xxx2_sha": "crypto", "ite_it8xxx2_sha_v2": "crypto", + "microchip_sha_g1_crypto": "crypto", "microchip_xec_symcr": "crypto", "nordic_nrf_ecb": "crypto", "nuvoton_npcx_sha": "crypto", "nxp_mcux_dcp": "crypto", + "nxp_s32_crypto_hse_mu": "crypto", + "raspberrypi_pico_sha256": "crypto", + "realtek_rts5912_sha": "crypto", "renesas_smartbond_crypto": "crypto", "silabs_si32_aes": "crypto", "st_stm32_aes": "crypto", "st_stm32_cryp": "crypto", + "st_stm32_hash": "crypto", + "ti_cc23x0_aes": "crypto", # # dac "adi_ad559x_dac": "dac", + "adi_ad5601": "dac", + "adi_ad5611": "dac", + "adi_ad5621": "dac", "adi_ad5628": "dac", "adi_ad5648": "dac", "adi_ad5668": "dac", @@ -279,15 +444,21 @@ "adi_max22017_dac": "dac", "atmel_sam0_dac": "dac", "atmel_sam_dac": "dac", + "atmel_samd5x_dac": "dac", "espressif_esp32_dac": "dac", "gd_gd32_dac": "dac", + "microchip_dac_g1": "dac", "microchip_mcp4725": "dac", "microchip_mcp4728": "dac", + "nxp_dac12": "dac", "nxp_gau_dac": "dac", "nxp_kinetis_dac": "dac", "nxp_kinetis_dac32": "dac", "nxp_lpdac": "dac", + "renesas_ra_dac": "dac", + "silabs_vdac": "dac", "st_stm32_dac": "dac", + "ti_dac161s997": "dac", "ti_dacx0501": "dac", "vnd_dac": "dac", # @@ -303,9 +474,19 @@ # dai/intel/ssp "intel_ssp_dai": "dai/intel/ssp", # + # dai/nxp/esai + "nxp_dai_esai": "dai/nxp/esai", + # + # dai/nxp/micfil + "nxp_dai_micfil": "dai/nxp/micfil", + # # dai/nxp/sai "nxp_dai_sai": "dai/nxp/sai", # + # debug + "nordic_coresight_nrf": "debug", + "silabs_pti": "debug", + # # disk "st_stm32_sdmmc": "disk", "zephyr_flash_disk": "disk", @@ -317,42 +498,52 @@ "nvme_controller": "disk/nvme", # # display + "chipone_co5300": "display", "frida_nt35510": "display", "galaxycore_gc9x01x": "display", + "himax_hx8379c": "display", "himax_hx8394": "display", "ilitek_ili9806e_dsi": "display", "intel_multiboot_framebuffer": "display", "istech_ist3931": "display", + "jdi_lpm013m126": "display", "led_strip_matrix": "display", "maxim_max7219": "display", "nxp_dcnano_lcdif": "display", "nxp_imx_elcdif": "display", + "nxp_imx_lcdifv3": "display", "orisetech_otm8009a": "display", "raydium_rm67162": "display", "raydium_rm68200": "display", "renesas_ra_glcdc": "display", "renesas_smartbond_display": "display", "sharp_ls0xx": "display", + "sitronix_st75256": "display", + "sitronix_st7701": "display", "sitronix_st7735r": "display", "sitronix_st7789v": "display", "sitronix_st7796s": "display", "solomon_ssd1322": "display", "st_stm32_ltdc": "display", + "waveshare_dsi2dpi": "display", "zephyr_dummy_dc": "display", + "zephyr_hub12": "display", "zephyr_sdl_dc": "display", # # dma "adi_max32_dma": "dma", "altr_msgdma": "dma", - "andestech_atcdmac300": "dma", + "andestech_atcdmacx00": "dma", + "arm_dma_pl330": "dma", "atmel_sam0_dmac": "dma", "atmel_sam_xdmac": "dma", + "bflb_dma": "dma", "brcm_iproc_pax_dma_v1": "dma", "brcm_iproc_pax_dma_v2": "dma", "espressif_esp32_gdma": "dma", "gd_gd32_dma": "dma", "gd_gd32_dma_v1": "dma", - "infineon_cat1_dma": "dma", + "infineon_dma": "dma", "infineon_xmc4xxx_dma": "dma", "intel_adsp_gpdma": "dma", "intel_adsp_hda_host_in": "dma", @@ -361,7 +552,11 @@ "intel_adsp_hda_link_out": "dma", "intel_lpss": "dma", "intel_sedi_dma": "dma", + "microchip_dmac_g1_dma": "dma", "microchip_xec_dmac": "dma", + "nuvoton_npcx_gdma": "dma", + "nxp_4ch_dma": "dma", + "nxp_edma": "dma", "nxp_lpc_dma": "dma", "nxp_mcux_edma": "dma", "nxp_pxp": "dma", @@ -369,9 +564,15 @@ "nxp_smartdma": "dma", "nxp_sof_host_dma": "dma", "raspberrypi_pico_dma": "dma", + "renesas_ra_dma": "dma", + "renesas_rz_dmac": "dma", + "renesas_rz_dmac_b": "dma", "renesas_smartbond_dma": "dma", + "sifli_sf32lb_dmac": "dma", + "silabs_gpdma": "dma", "silabs_ldma": "dma", "silabs_si32_dma": "dma", + "silabs_siwx91x_dma": "dma", "snps_designware_dma": "dma", "snps_designware_dma_axi": "dma", "st_stm32_bdma": "dma", @@ -380,6 +581,8 @@ "st_stm32_dma_v2bis": "dma", "st_stm32_dmamux": "dma", "st_stm32u5_dma": "dma", + "ti_cc23x0_dma": "dma", + "wch_wch_dma": "dma", "xlnx_axi_dma_1_00_a": "dma", "xlnx_eth_dma": "dma", "zephyr_dma_emul": "dma", @@ -389,40 +592,57 @@ # # edac "intel_ibecc": "edac", + "nxp_erm": "edac", + "xlnx_zynqmp_ddrc_2_40a": "edac", # # eeprom "atmel_at24": "eeprom", "fujitsu_mb85rcxx": "eeprom", "fujitsu_mb85rsxx": "eeprom", + "infineon_fm25xxx": "eeprom", "microchip_xec_eeprom": "eeprom", "nxp_lpc11u6x_eeprom": "eeprom", "st_stm32_eeprom": "eeprom", - "ti_tmp116_eeprom": "eeprom", + "ti_tmp11x_eeprom": "eeprom", "zephyr_emu_eeprom": "eeprom", "zephyr_fake_eeprom": "eeprom", "zephyr_sim_eeprom": "eeprom", # # entropy "adi_max32_trng": "entropy", + "adi_maxq10xx_trng": "entropy", + "ambiq_puf_trng": "entropy", "atmel_sam_trng": "entropy", + "brcm_iproc_rng200": "entropy", "espressif_esp32_trng": "entropy", + "gd_gd32_trng": "entropy", "litex_prbs": "entropy", + "microchip_trng_g1_entropy": "entropy", "neorv32_trng": "entropy", + "nordic_nrf_cracen_ctrdrbg": "entropy", "nordic_nrf_rng": "entropy", "nuvoton_npcx_drbg": "entropy", + "nxp_ele_trng": "entropy", "nxp_imx_caam": "entropy", "nxp_kinetis_rnga": "entropy", "nxp_kinetis_trng": "entropy", "nxp_lpc_rng": "entropy", "openisa_rv32m1_trng": "entropy", + "raspberrypi_pico_rng": "entropy", "renesas_smartbond_trng": "entropy", + "sensry_sy1xx_trng": "entropy", + "sifli_sf32lb_trng": "entropy", "silabs_gecko_semailbox": "entropy", "silabs_gecko_trng": "entropy", + "silabs_siwx91x_rng": "entropy", "st_stm32_rng": "entropy", + "st_stm32_rng_noirq": "entropy", "telink_b91_trng": "entropy", "ti_cc13xx_cc26xx_trng": "entropy", + "ti_mspm0_trng": "entropy", + "virtio_device4": "entropy", "zephyr_bt_hci_entropy": "entropy", - "zephyr_native_posix_rng": "entropy", + "zephyr_native_sim_rng": "entropy", "zephyr_psa_crypto_rng": "entropy", # # espi @@ -435,6 +655,7 @@ "nuvoton_npcx_espi": "espi", "nuvoton_npcx_espi_taf": "espi", "nuvoton_npcx_host_sub": "espi", + "realtek_rts5912_espi": "espi", "zephyr_espi_emul_controller": "espi", # # ethernet @@ -448,26 +669,40 @@ "litex_liteeth": "ethernet", "microchip_enc28j60": "ethernet", "microchip_enc424j600": "ethernet", - "microchip_ksz8794": "ethernet", - "microchip_ksz8863": "ethernet", "microchip_lan865x": "ethernet", "microchip_lan9250": "ethernet", "nuvoton_numaker_ethernet": "ethernet", - "nxp_imx_netc_psi": "ethernet", + "nxp_enet": "ethernet", + "nxp_enet1g": "ethernet", + "nxp_enet_mac": "ethernet", "nxp_s32_gmac": "ethernet", "nxp_s32_netc_psi": "ethernet", "nxp_s32_netc_vsi": "ethernet", "renesas_ra_ethernet": "ethernet", + "sensry_sy1xx_mac": "ethernet", "siemens_ivshmem_eth": "ethernet", "silabs_gecko_ethernet": "ethernet", "smsc_lan91c111": "ethernet", + "smsc_lan91c111_mdio": "ethernet", "smsc_lan9220": "ethernet", "snps_designware_ethernet": "ethernet", "snps_ethernet_cyclonev": "ethernet", "st_stm32_ethernet": "ethernet", "ti_stellaris_ethernet": "ethernet", + "virtio_net": "ethernet", "vnd_ethernet": "ethernet", "wiznet_w5500": "ethernet", + "wiznet_w6100": "ethernet", + "xlnx_axi_ethernet_1_00_a": "ethernet", + "xlnx_gem": "ethernet", + "xlnx_xps_ethernetlite_1_00_a_mac": "ethernet", + "xlnx_xps_ethernetlite_3_00_a_mac": "ethernet", + # + # ethernet/dsa + "microchip_ksz8463": "ethernet/dsa", + "microchip_ksz8794": "ethernet/dsa", + "microchip_ksz8863": "ethernet/dsa", + "nxp_netc_switch": "ethernet/dsa", # # ethernet/dwc_xgmac "snps_dwcxgmac": "ethernet/dwc_xgmac", @@ -476,57 +711,102 @@ "nxp_enet_qos": "ethernet/eth_nxp_enet_qos", "nxp_enet_qos_mac": "ethernet/eth_nxp_enet_qos", # - # ethernet/nxp_enet - "nxp_enet": "ethernet/nxp_enet", - "nxp_enet1g": "ethernet/nxp_enet", - "nxp_enet_mac": "ethernet/nxp_enet", - "nxp_kinetis_ethernet": "ethernet/nxp_enet", + # ethernet/intel + "intel_eth_plat": "ethernet/intel", + "intel_igc_mac": "ethernet/intel", + # + # ethernet/mdio + "adi_adin2111_mdio": "ethernet/mdio", + "atmel_sam_mdio": "ethernet/mdio", + "espressif_esp32_mdio": "ethernet/mdio", + "infineon_xmc4xxx_mdio": "ethernet/mdio", + "intel_igc_mdio": "ethernet/mdio", + "litex_liteeth_mdio": "ethernet/mdio", + "microchip_lan865x_mdio": "ethernet/mdio", + "nxp_enet_mdio": "ethernet/mdio", + "nxp_enet_qos_mdio": "ethernet/mdio", + "nxp_imx_netc_emdio": "ethernet/mdio", + "nxp_s32_gmac_mdio": "ethernet/mdio", + "nxp_s32_netc_emdio": "ethernet/mdio", + "renesas_ra_mdio": "ethernet/mdio", + "sensry_sy1xx_mdio": "ethernet/mdio", + "snps_dwcxgmac_mdio": "ethernet/mdio", + "st_stm32_mdio": "ethernet/mdio", + "xlnx_axi_ethernet_1_00_a_mdio": "ethernet/mdio", + "xlnx_xps_ethernetlite_1_00_a_mdio": "ethernet/mdio", + "xlnx_xps_ethernetlite_3_00_a_mdio": "ethernet/mdio", + "zephyr_mdio_gpio": "ethernet/mdio", + # + # ethernet/nxp_imx_netc + "nxp_imx_netc_blk_ctrl": "ethernet/nxp_imx_netc", + "nxp_imx_netc_psi": "ethernet/nxp_imx_netc", # # ethernet/phy "adi_adin1100_phy": "ethernet/phy", "adi_adin2111_phy": "ethernet/phy", "davicom_dm8806_phy": "ethernet/phy", "ethernet_phy": "ethernet/phy", + "ethernet_phy_fixed_link": "ethernet/phy", "microchip_ksz8081": "ethernet/phy", + "microchip_ksz9131": "ethernet/phy", + "microchip_lan8742": "ethernet/phy", "microchip_t1s_phy": "ethernet/phy", "microchip_vsc8541": "ethernet/phy", + "motorcomm_yt8521": "ethernet/phy", "nxp_tja1103": "ethernet/phy", + "nxp_tja11xx": "ethernet/phy", "qca_ar8031": "ethernet/phy", "realtek_rtl8211f": "ethernet/phy", "ti_dp83825": "ethernet/phy", + "ti_dp83867": "ethernet/phy", # # firmware/scmi + "arm_scmi": "firmware/scmi", "arm_scmi_shmem": "firmware/scmi", # + # firmware/tisci + "ti_k2g_sci": "firmware/tisci", + # # flash "adi_max32_flash_controller": "flash", - "altr_nios2_qspi_nor": "flash", + "adi_max32_spixf_nor": "flash", "ambiq_flash_controller": "flash", "andestech_qspi_nor": "flash", + "andestech_qspi_nor_xip": "flash", + "atmel_at25xv021a": "flash", "atmel_at45": "flash", "atmel_sam0_nvmctrl": "flash", "atmel_sam_flash_controller": "flash", + "bflb_flash_controller": "flash", "cdns_nand": "flash", "cdns_qspi_nor": "flash", "espressif_esp32_flash_controller": "flash", "gd_gd32_flash_controller": "flash", - "infineon_cat1_flash_controller": "flash", - "infineon_cat1_qspi_flash": "flash", + "infineon_flash_controller": "flash", + "infineon_qspi_flash": "flash", "infineon_xmc4xxx_flash_controller": "flash", + "ite_it51xxx_manual_flash_1k": "flash", "ite_it8xxx2_flash_controller": "flash", + "jedec_mspi_nor": "flash", + "jedec_spi_nand": "flash", "jedec_spi_nor": "flash", + "microchip_nvmctrl_g1_flash": "flash", "mspi_atxp032": "flash", + "mspi_is25xx0xx": "flash", + "netsol_s3axx04": "flash", "nordic_mram": "flash", "nordic_nrf51_flash_controller": "flash", "nordic_nrf52_flash_controller": "flash", "nordic_nrf53_flash_controller": "flash", "nordic_nrf91_flash_controller": "flash", + "nordic_nrf_mramc": "flash", "nordic_qspi_nor": "flash", "nordic_rram_controller": "flash", "nuvoton_npcx_fiu_nor": "flash", "nuvoton_npcx_fiu_qspi": "flash", "nuvoton_numaker_fmc": "flash", "nuvoton_numaker_rmc": "flash", + "nxp_c40_flash_controller": "flash", "nxp_iap_fmc11": "flash", "nxp_iap_fmc54": "flash", "nxp_iap_fmc55": "flash", @@ -535,18 +815,31 @@ "nxp_imx_flexspi_mx25um51345g": "flash", "nxp_imx_flexspi_nor": "flash", "nxp_kinetis_ftfa": "flash", + "nxp_kinetis_ftfc": "flash", "nxp_kinetis_ftfe": "flash", "nxp_kinetis_ftfl": "flash", "nxp_msf1": "flash", + "nxp_s32_qspi_hyperflash": "flash", "nxp_s32_qspi_nor": "flash", + "nxp_s32_xspi_hyperram": "flash", + "nxp_xspi_nor": "flash", "openisa_rv32m1_ftfe": "flash", "raspberrypi_pico_flash_controller": "flash", + "realtek_rts5912_flash_controller": "flash", "renesas_ra_flash_hp_controller": "flash", + "renesas_ra_flash_lp_controller": "flash", + "renesas_ra_mram_controller": "flash", "renesas_ra_ospi_b_nor": "flash", "renesas_ra_qspi_nor": "flash", + "renesas_rx_flash": "flash", + "renesas_rz_qspi_spibsc": "flash", + "renesas_rz_qspi_xspi": "flash", "renesas_smartbond_flash_controller": "flash", + "sifli_sf32lb_mpi_qspi_nor": "flash", "silabs_gecko_flash_controller": "flash", + "silabs_series2_flash_controller": "flash", "silabs_si32_flash_controller": "flash", + "silabs_siwx91x_flash_controller": "flash", "st_stm32_flash_controller": "flash", "st_stm32_ospi_nor": "flash", "st_stm32_qspi_nor": "flash", @@ -556,6 +849,7 @@ "st_stm32wba_flash_controller": "flash", "telink_b91_flash_controller": "flash", "ti_cc13xx_cc26xx_flash_controller": "flash", + "ti_cc23x0_flash_controller": "flash", "zephyr_mspi_emul_flash": "flash", "zephyr_sim_flash": "flash", # @@ -568,12 +862,27 @@ "renesas_slg47115": "fpga", "xlnx_fpga": "fpga", # + # fuel_gauge/axp2101 + "x_powers_axp2101_fuel_gauge": "fuel_gauge/axp2101", + # # fuel_gauge/bq27z746 "ti_bq27z746": "fuel_gauge/bq27z746", # + # fuel_gauge/bq40z50 + "ti_bq40z50": "fuel_gauge/bq40z50", + # # fuel_gauge/composite "zephyr_fuel_gauge_composite": "fuel_gauge/composite", # + # fuel_gauge/hy4245 + "hycon_hy4245": "fuel_gauge/hy4245", + # + # fuel_gauge/lc709203f + "onnn_lc709203f": "fuel_gauge/lc709203f", + # + # fuel_gauge/ltc2959 + "adi_ltc2959": "fuel_gauge/ltc2959", + # # fuel_gauge/max17048 "maxim_max17048": "fuel_gauge/max17048", # @@ -581,47 +890,63 @@ "sbs_sbs_gauge": "fuel_gauge/sbs_gauge", "sbs_sbs_gauge_new_api": "fuel_gauge/sbs_gauge", # + # fuel_gauge/sy24561 + "silergy_sy24561": "fuel_gauge/sy24561", + # # gnss "gnss_nmea_generic": "gnss", "luatos_air530z": "gnss", "quectel_lc26g": "gnss", "quectel_lc76g": "gnss", "quectel_lc86g": "gnss", - "u_blox_m8": "gnss", "zephyr_gnss_emul": "gnss", # + # gnss/u_blox + "u_blox_f9p": "gnss/u_blox", + "u_blox_m8": "gnss/u_blox", + # # gpio "adi_ad559x_gpio": "gpio", "adi_adp5585_gpio": "gpio", "adi_max14906_gpio": "gpio", + "adi_max14915_gpio": "gpio", "adi_max14916_gpio": "gpio", + "adi_max14917_gpio": "gpio", "adi_max22017_gpio": "gpio", "adi_max22190_gpio": "gpio", + "adi_max22199_gpio": "gpio", "adi_max32_gpio": "gpio", + "aesc_gpio": "gpio", "altr_pio_1_0": "gpio", "ambiq_gpio_bank": "gpio", "andestech_atcgpio100": "gpio", "arm_cmsdk_gpio": "gpio", + "arm_mmio32_gpio": "gpio", "atmel_sam0_gpio": "gpio", "atmel_sam4l_gpio": "gpio", "atmel_sam_gpio": "gpio", "awinic_aw9523b_gpio": "gpio", + "bflb_bl60x_70x_gpio": "gpio", + "bflb_bl61x_gpio": "gpio", "brcm_bcm2711_gpio": "gpio", "brcm_brcmstb_gpio": "gpio", "brcm_iproc_gpio": "gpio", "cypress_cy8c95xx_gpio_port": "gpio", "cypress_psoc6_gpio": "gpio", "efinix_sapphire_gpio": "gpio", + "ene_kb106x_gpio": "gpio", "ene_kb1200_gpio": "gpio", "espressif_esp32_gpio": "gpio", + "espressif_esp32_lpgpio": "gpio", "fcs_fxl6408": "gpio", "gaisler_grgpio": "gpio", "gd_gd32_gpio": "gpio", - "infineon_cat1_gpio": "gpio", + "infineon_gpio": "gpio", "infineon_tle9104_gpio": "gpio", "infineon_xmc4xxx_gpio": "gpio", "intel_gpio": "gpio", "intel_sedi_gpio": "gpio", + "ite_it51xxx_gpio": "gpio", "ite_it8801_gpio": "gpio", "ite_it8xxx2_gpio": "gpio", "ite_it8xxx2_gpio_v2": "gpio", @@ -636,12 +961,13 @@ "microchip_mcp23s09": "gpio", "microchip_mcp23s17": "gpio", "microchip_mcp23s18": "gpio", - "microchip_mec5_gpio": "gpio", "microchip_mpfs_gpio": "gpio", + "microchip_port_g1_gpio": "gpio", + "microchip_sam_pio4": "gpio", "microchip_xec_gpio": "gpio", - "microchip_xec_gpio_v2": "gpio", "neorv32_gpio": "gpio", "nordic_npm1300_gpio": "gpio", + "nordic_npm1304_gpio": "gpio", "nordic_npm2100_gpio": "gpio", "nordic_npm6001_gpio": "gpio", "nordic_nrf_gpio": "gpio", @@ -656,27 +982,38 @@ "nxp_kinetis_gpio": "gpio", "nxp_lpc11u6x_gpio": "gpio", "nxp_lpc_gpio_port": "gpio", + "nxp_pca6408": "gpio", + "nxp_pca6416": "gpio", "nxp_pca9538": "gpio", "nxp_pca9539": "gpio", "nxp_pca9554": "gpio", "nxp_pca9555": "gpio", "nxp_pca95xx": "gpio", + "nxp_pcal6408": "gpio", "nxp_pcal6408a": "gpio", + "nxp_pcal6416": "gpio", "nxp_pcal6416a": "gpio", "nxp_pcal6524": "gpio", "nxp_pcal6534": "gpio", + "nxp_pcal9538": "gpio", + "nxp_pcal9539": "gpio", + "nxp_pcal9722": "gpio", "nxp_pcf857x": "gpio", - "nxp_s32_gpio": "gpio", "nxp_sc18im704_gpio": "gpio", + "nxp_sc18is606_gpio": "gpio", + "nxp_siul2_gpio": "gpio", "openisa_rv32m1_gpio": "gpio", "quicklogic_eos_s3_gpio": "gpio", - "raspberrypi_pico_gpio": "gpio", + "raspberrypi_pico_gpio_port": "gpio", "raspberrypi_rp1_gpio": "gpio", + "realtek_ameba_gpio": "gpio", + "realtek_bee_gpio": "gpio", "realtek_rts5912_gpio": "gpio", - "renesas_ra_gpio": "gpio", "renesas_ra_gpio_ioport": "gpio", "renesas_rcar_gpio": "gpio", + "renesas_rx_gpio": "gpio", "renesas_rz_gpio": "gpio", + "renesas_rza2m_gpio": "gpio", "renesas_rzt2m_gpio": "gpio", "renesas_smartbond_gpio": "gpio", "richtek_rt1718s": "gpio", @@ -685,18 +1022,25 @@ "semtech_sx1509b": "gpio", "sensry_sy1xx_gpio": "gpio", "sifive_gpio0": "gpio", + "sifli_sf32lb_gpio": "gpio", "silabs_gecko_gpio_port": "gpio", + "silabs_gpio": "gpio", "silabs_si32_gpio": "gpio", + "silabs_siwx91x_gpio": "gpio", + "silabs_siwx91x_gpio_uulp": "gpio", "snps_creg_gpio": "gpio", "snps_designware_gpio": "gpio", + "st_mfxstm32l152": "gpio", "st_stm32_gpio": "gpio", "st_stmpe1600": "gpio", "telink_b91_gpio": "gpio", - "ti_ads114s0x_gpio": "gpio", + "ti_ads1x4s0x_gpio": "gpio", "ti_cc13xx_cc26xx_gpio": "gpio", + "ti_cc23x0_gpio": "gpio", "ti_cc32xx_gpio": "gpio", "ti_davinci_gpio": "gpio", "ti_lmp90xxx_gpio": "gpio", + "ti_mspm0_gpio": "gpio", "ti_sn74hc595": "gpio", "ti_stellaris_gpio": "gpio", "ti_tca6424a": "gpio", @@ -710,11 +1054,15 @@ "zephyr_gpio_emul": "gpio", "zephyr_gpio_emul_sdl": "gpio", # - # haptics - "ti_drv2605": "haptics", + # haptics/cirrus + "cirrus_cs40l5x": "haptics/cirrus", + # + # haptics/ti + "ti_drv2605": "haptics/ti", # # hdlc_rcp_if "nxp_hdlc_rcp_if": "hdlc_rcp_if", + "spi_hdlc_rcp_if": "hdlc_rcp_if", "uart_hdlc_rcp_if": "hdlc_rcp_if", # # hwinfo @@ -726,9 +1074,12 @@ "nxp_imx_src": "hwinfo", "nxp_imx_src_rev2": "hwinfo", "nxp_lpc_uid": "hwinfo", + "wch_esig": "hwinfo", # # hwspinlock + "nxp_sema42": "hwspinlock", "sqn_hwspinlock": "hwspinlock", + "vnd_hwspinlock": "hwspinlock", # # i2c "adi_max32_i2c": "i2c", @@ -740,47 +1091,68 @@ "atmel_sam_i2c_twi": "i2c", "atmel_sam_i2c_twihs": "i2c", "atmel_sam_i2c_twim": "i2c", + "bflb_i2c": "i2c", "brcm_iproc_i2c": "i2c", + "cdns_i2c": "i2c", "ene_kb1200_i2c": "i2c", "espressif_esp32_i2c": "i2c", "fsl_imx21_i2c": "i2c", "gd_gd32_i2c": "i2c", "gpio_i2c": "i2c", "gpio_i2c_switch": "i2c", - "infineon_cat1_i2c": "i2c", + "infineon_i2c": "i2c", "infineon_xmc4xxx_i2c": "i2c", "intel_sedi_i2c": "i2c", "ite_enhance_i2c": "i2c", + "ite_it51xxx_i2c": "i2c", "ite_it8xxx2_i2c": "i2c", "litex_i2c": "i2c", + "litex_litei2c": "i2c", "microchip_mpfs_i2c": "i2c", + "microchip_sercom_g1_i2c": "i2c", "microchip_xec_i2c": "i2c", "microchip_xec_i2c_v2": "i2c", + "nordic_nrf_twi": "i2c", + "nordic_nrf_twim": "i2c", "nordic_nrf_twis": "i2c", "nuvoton_npcx_i2c_ctrl": "i2c", "nuvoton_npcx_i2c_port": "i2c", "nuvoton_numaker_i2c": "i2c", + "nxp_ii2c": "i2c", "nxp_kinetis_i2c": "i2c", "nxp_lpc11u6x_i2c": "i2c", "nxp_lpc_i2c": "i2c", "nxp_lpi2c": "i2c", "nxp_sc18im704_i2c": "i2c", "openisa_rv32m1_lpi2c": "i2c", + "realtek_rts5912_i2c": "i2c", + "renesas_ra_i2c_sci": "i2c", + "renesas_ra_i2c_sci_b": "i2c", "renesas_ra_iic": "i2c", "renesas_rcar_i2c": "i2c", + "renesas_rx_i2c": "i2c", + "renesas_rz_iic": "i2c", + "renesas_rz_riic": "i2c", + "renesas_rza2m_riic": "i2c", "renesas_smartbond_i2c": "i2c", + "sensry_sy1xx_i2c": "i2c", "sifive_i2c0": "i2c", + "sifli_sf32lb_i2c": "i2c", "silabs_gecko_i2c": "i2c", + "silabs_i2c": "i2c", + "snps_designware_i2c": "i2c", "st_stm32_i2c_v1": "i2c", "st_stm32_i2c_v2": "i2c", "telink_b91_i2c": "i2c", "ti_cc13xx_cc26xx_i2c": "i2c", + "ti_cc23x0_i2c": "i2c", "ti_cc32xx_i2c": "i2c", "ti_omap_i2c": "i2c", "ti_tca9544a": "i2c", "ti_tca9546a": "i2c", "ti_tca9548a": "i2c", "vnd_i2c": "i2c", + "wch_i2c": "i2c", "xlnx_xps_iic_2_00_a": "i2c", "xlnx_xps_iic_2_1": "i2c", "zephyr_i2c_emul_controller": "i2c", @@ -789,26 +1161,42 @@ "zephyr_i2c_target_eeprom": "i2c/target", # # i2s + "adi_max32_i2s": "i2s", + "ambiq_i2s": "i2s", "atmel_sam_ssc": "i2s", "espressif_esp32_i2s": "i2s", + "infineon_i2s": "i2s", + "nordic_nrf_i2s": "i2s", "nxp_lpc_i2s": "i2s", "nxp_mcux_i2s": "i2s", + "renesas_ra_i2s_ssie": "i2s", + "silabs_siwx91x_i2s": "i2s", "st_stm32_i2s": "i2s", + "st_stm32_sai": "i2s", "vnd_i2s": "i2s", + "zephyr_i2s_sdl": "i2s", # # i3c + "adi_max32_i3c": "i3c", "cdns_i3c": "i3c", + "ite_it51xxx_i3cm": "i3c", + "ite_it51xxx_i3cs": "i3c", "nuvoton_npcx_i3c": "i3c", "nxp_mcux_i3c": "i3c", + "renesas_ra_i3c": "i3c", + "snps_designware_i3c": "i3c", "st_stm32_i3c": "i3c", "vnd_i3c": "i3c", # # ieee802154 "atmel_rf2xx": "ieee802154", "decawave_dw1000": "ieee802154", + "espressif_esp32_ieee802154": "ieee802154", "nordic_nrf_ieee802154": "ieee802154", "nxp_kw41z_ieee802154": "ieee802154", "nxp_mcr20a": "ieee802154", + "nxp_mcxw_ieee802154": "ieee802154", + "st_stm32wba_ieee802154": "ieee802154", "telink_b91_zb": "ieee802154", "ti_cc1200": "ieee802154", "ti_cc13xx_cc26xx_ieee802154": "ieee802154", @@ -819,10 +1207,15 @@ # input "adc_keys": "input", "analog_axis": "input", + "arduino_modulino_buttons": "input", + "bflb_irx": "input", + "chipsemi_chsc5x": "input", "chipsemi_chsc6x": "input", "cirque_pinnacle": "input", + "cypress_cy8cmbr3xxx": "input", "espressif_esp32_touch": "input", "focaltech_ft5336": "input", + "focaltech_ft6146": "input", "futaba_sbus": "input", "goodix_gt911": "input", "gpio_kbd_matrix": "input", @@ -830,22 +1223,35 @@ "gpio_qdec": "input", "hynitron_cst816s": "input", "ilitek_ili2132a": "input", + "ite_it51xxx_kbd": "input", "ite_it8801_kbd": "input", "ite_it8xxx2_kbd": "input", "microchip_cap12xx": "input", "microchip_xec_kbd": "input", "nintendo_nunchuk": "input", "nuvoton_npcx_kbd": "input", + "nxp_mcux_kpp": "input", + "parade_tma525b": "input", "pixart_pat912x": "input", "pixart_paw32xx": "input", "pixart_pmw3610": "input", + "realtek_rts5912_kbd": "input", + "renesas_ra_ctsu": "input", + "renesas_ra_ctsu_button": "input", + "renesas_ra_ctsu_slider": "input", + "renesas_ra_ctsu_wheel": "input", + "renesas_rx_ctsu": "input", "sitronix_cf1133": "input", + "st_stm32_tsc": "input", "st_stmpe811": "input", + "vishay_vs1838b": "input", + "wch_ch9350l": "input", "xptek_xpt2046": "input", "zephyr_input_sdl_touch": "input", "zephyr_native_linux_evdev": "input", # # interrupt_controller + "adi_max32_rv32_intc": "interrupt_controller", "arm_gic_v1": "interrupt_controller", "arm_gic_v2": "interrupt_controller", "arm_gic_v3": "interrupt_controller", @@ -853,24 +1259,33 @@ "atmel_sam0_eic": "interrupt_controller", "gaisler_irqmp": "interrupt_controller", "gd_gd32_exti": "interrupt_controller", + "hazard3_hazard3_intc": "interrupt_controller", "infineon_xmc4xxx_intc": "interrupt_controller", "intel_ace_intc": "interrupt_controller", "intel_cavs_intc": "interrupt_controller", "intel_ioapic": "interrupt_controller", "intel_loapic": "interrupt_controller", "intel_vt_d": "interrupt_controller", + "ite_it51xxx_wuc": "interrupt_controller", "ite_it8xxx2_wuc": "interrupt_controller", "litex_vexriscv_intc0": "interrupt_controller", "mediatek_adsp_intc": "interrupt_controller", + "microchip_eic_g1_intc": "interrupt_controller", "microchip_xec_ecia": "interrupt_controller", "nuclei_eclic": "interrupt_controller", "nuvoton_npcx_miwu": "interrupt_controller", + "nxp_gint": "interrupt_controller", "nxp_irqsteer_intc": "interrupt_controller", "nxp_pint": "interrupt_controller", - "nxp_s32_siul2_eirq": "interrupt_controller", "nxp_s32_wkpu": "interrupt_controller", + "nxp_siul2_eirq": "interrupt_controller", "openisa_rv32m1_intmux": "interrupt_controller", - "renesas_ra_interrupt_controller_unit": "interrupt_controller", + "renesas_rx_grp_intc": "interrupt_controller", + "renesas_rx_icu": "interrupt_controller", + "renesas_rz_ext_irq": "interrupt_controller", + "renesas_rz_tint": "interrupt_controller", + "riscv_clic": "interrupt_controller", + "riscv_imsic": "interrupt_controller", "shared_irq": "interrupt_controller", "sifive_plic_1_0_0": "interrupt_controller", "snps_arcv2_intc": "interrupt_controller", @@ -878,6 +1293,7 @@ "st_stm32wb0_gpio_intc": "interrupt_controller", "swerv_pic": "interrupt_controller", "ti_vim": "interrupt_controller", + "wch_exti": "interrupt_controller", "wch_pfic": "interrupt_controller", # # ipm @@ -893,20 +1309,23 @@ "xlnx_zynqmp_ipi_mailbox": "ipm", "zephyr_mbox_ipm": "ipm", # - # kscan - "zephyr_kscan_input": "kscan", - # # led + "arduino_modulino_buttons_leds": "led", + "dac_leds": "led", "gpio_leds": "led", "holtek_ht16k33": "led", "issi_is31fl3194": "led", "issi_is31fl3216a": "led", "issi_is31fl3733": "led", + "leds_group_multicolor": "led", "microchip_xec_bbled": "led", "nordic_npm1300_led": "led", + "nordic_npm1304_led": "led", + "nxp_pca9533": "led", "nxp_pca9633": "led", "onnn_ncp5623": "led", "pwm_leds": "led", + "sct_sct2024": "led", "ti_lp3943": "led", "ti_lp5009": "led", "ti_lp5012": "led", @@ -920,6 +1339,7 @@ # # led_strip "apa_apa102": "led_strip", + "arduino_modulino_pixels": "led_strip", "greeled_lpd8803": "led_strip", "greeled_lpd8806": "led_strip", "ti_tlc5971": "led_strip", @@ -928,14 +1348,23 @@ "worldsemi_ws2812_i2s": "led_strip", "worldsemi_ws2812_rpi_pico_pio": "led_strip", "worldsemi_ws2812_spi": "led_strip", + "worldsemi_ws2812_uart": "led_strip", # # lora "reyax_rylrxxx": "lora", - "semtech_sx1272": "lora", - "semtech_sx1276": "lora", + # + # lora/loramac-node + "semtech_sx1272": "lora/loramac-node", + "semtech_sx1276": "lora/loramac-node", + # + # lora/native/sx126x + "semtech_sx1261": "lora/native/sx126x", + "semtech_sx1262": "lora/native/sx126x", + "st_stm32wl_subghz_radio": "lora/native/sx126x", # # mbox "andestech_mbox_plic_sw": "mbox", + "arm_mhuv3": "mbox", "espressif_mbox_esp32": "mbox", "linaro_ivshmem_mbox": "mbox", "nordic_mbox_nrf_ipc": "mbox", @@ -948,45 +1377,44 @@ "nxp_mbox_imx_mu": "mbox", "nxp_mbox_mailbox": "mbox", "nxp_s32_mru": "mbox", + "raspberrypi_pico_mbox": "mbox", + "renesas_ra_ipc_mbox": "mbox", + "renesas_rz_mhu_mbox": "mbox", "st_mbox_stm32_hsem": "mbox", - # - # mdio - "adi_adin2111_mdio": "mdio", - "atmel_sam_mdio": "mdio", - "espressif_esp32_mdio": "mdio", - "infineon_xmc4xxx_mdio": "mdio", - "litex_liteeth_mdio": "mdio", - "microchip_lan865x_mdio": "mdio", - "nxp_enet_mdio": "mdio", - "nxp_enet_qos_mdio": "mdio", - "nxp_imx_netc_emdio": "mdio", - "nxp_s32_gmac_mdio": "mdio", - "nxp_s32_netc_emdio": "mdio", - "renesas_ra_mdio": "mdio", - "smsc_lan91c111_mdio": "mdio", - "snps_dwcxgmac_mdio": "mdio", - "st_stm32_mdio": "mdio", - "zephyr_mdio_gpio": "mdio", + "ti_omap_mailbox": "mbox", + "ti_secure_proxy": "mbox", + "xlnx_mbox_versal_ipi_mailbox": "mbox", # # memc + "adi_max32_hpb": "memc", "atmel_sam_smc": "memc", + "bflb_bl61x_psram": "memc", "mspi_aps6404l": "memc", + "mspi_aps_z8": "memc", "nxp_imx_flexspi": "memc", + "nxp_imx_flexspi_is66wvs8m8": "memc", "nxp_imx_flexspi_s27ks0641": "memc", "nxp_imx_flexspi_w956a8mbya": "memc", "nxp_s32_qspi": "memc", + "nxp_s32_xspi": "memc", + "nxp_xspi": "memc", + "nxp_xspi_psram": "memc", "renesas_ra_sdram": "memc", "renesas_smartbond_nor_psram": "memc", "sifive_fu740_c000_ddr": "memc", + "silabs_siwx91x_qspi_memory": "memc", "st_stm32_fmc": "memc", "st_stm32_fmc_nor_psram": "memc", "st_stm32_fmc_sdram": "memc", + "st_stm32_ospi_psram": "memc", + "st_stm32_xspi_psram": "memc", "st_stm32h7_fmc": "memc", # # mfd "adi_ad559x": "mfd", "adi_adp5585": "mfd", "adi_max22017": "mfd", + "adi_maxq10xx": "mfd", "awinic_aw9523b": "mfd", "infineon_tle9104": "mfd", "ite_it8801_altctrl": "mfd", @@ -994,18 +1422,29 @@ "maxim_ds3231_mfd": "mfd", "maxim_max20335": "mfd", "maxim_max31790": "mfd", + "microchip_sam_flexcom": "mfd", + "microcrystal_rv3032_mfd": "mfd", + "motorola_mc146818_mfd": "mfd", "nordic_npm1300": "mfd", + "nordic_npm1304": "mfd", "nordic_npm2100": "mfd", "nordic_npm6001": "mfd", "nuvoton_nct38xx": "mfd", "nxp_lp_flexcomm": "mfd", + "nxp_pca9422": "mfd", + "nxp_pf1550": "mfd", + "nxp_sc18is606": "mfd", "rohm_bd8lb600fs": "mfd", - "x_powers_axp192": "mfd", # # mipi_dbi + "bflb_dbi": "mipi_dbi", + "espressif_esp32_lcd_cam_mipi_dbi": "mipi_dbi", "nxp_lcdic": "mipi_dbi", + "nxp_mipi_dbi_dcnano_lcdif": "mipi_dbi", "nxp_mipi_dbi_flexio_lcdif": "mipi_dbi", + "raspberrypi_pico_mipi_dbi_pio": "mipi_dbi", "renesas_smartbond_mipi_dbi": "mipi_dbi", + "sifli_sf32lb_lcdc_mipi_dbi": "mipi_dbi", "st_stm32_fmc_mipi_dbi": "mipi_dbi", "zephyr_mipi_dbi_bitbang": "mipi_dbi", "zephyr_mipi_dbi_spi": "mipi_dbi", @@ -1013,6 +1452,7 @@ # mipi_dsi "nxp_imx_mipi_dsi": "mipi_dsi", "nxp_mipi_dsi_2l": "mipi_dsi", + "nxp_mipi_dsi_dwc": "mipi_dsi", "renesas_ra_mipi_dsi": "mipi_dsi", "st_stm32_mipi_dsi": "mipi_dsi", "vnd_mipi_dsi": "mipi_dsi", @@ -1022,6 +1462,8 @@ # # misc/ethos_u "arm_ethos_u": "misc/ethos_u", + "nuvoton_numaker_npu": "misc/ethos_u", + "renesas_ra_npu": "misc/ethos_u", # # misc/ft8xx "ftdi_ft800": "misc/ft8xx", @@ -1029,12 +1471,22 @@ # misc/grove_lcd_rgb "seeed_grove_lcd_rgb": "misc/grove_lcd_rgb", # + # misc/interconn/renesas_elc + "renesas_ra_elc": "misc/interconn/renesas_elc", + # # misc/mcux_flexio "nxp_flexio": "misc/mcux_flexio", # # misc/nordic_vpr_launcher "nordic_nrf_vpr_coprocessor": "misc/nordic_vpr_launcher", # + # misc/nxp_imx93_mediamix + "nxp_imx93_mediamix": "misc/nxp_imx93_mediamix", + # + # misc/nxp_rtxxx_dsp_ctrl + "nxp_rt600_dsp_ctrl": "misc/nxp_rtxxx_dsp_ctrl", + "nxp_rt700_dsp_ctrl_hifi4": "misc/nxp_rtxxx_dsp_ctrl", + # # misc/nxp_s32_emios "nxp_s32_emios": "misc/nxp_s32_emios", # @@ -1044,20 +1496,32 @@ # misc/renesas_ra_external_interrupt "renesas_ra_external_interrupt": "misc/renesas_ra_external_interrupt", # + # misc/renesas_rx_dtc + "renesas_rx_dtc": "misc/renesas_rx_dtc", + # + # misc/renesas_rx_external_interrupt + "renesas_rx_external_interrupt": "misc/renesas_rx_external_interrupt", + # + # misc/stm32n6_axisram + "st_stm32n6_ramcfg": "misc/stm32n6_axisram", + # # misc/timeaware_gpio "intel_timeaware_gpio": "misc/timeaware_gpio", # # mm + "intel_adsp_mtl_tlb": "mm", "intel_adsp_tlb": "mm", # # modem "nordic_nrf91_slm": "modem", "quectel_bg95": "modem", + "quectel_bg96": "modem", "quectel_bg9x": "modem", "quectel_eg25_g": "modem", - "simcom_sim7080": "modem", + "quectel_eg800q": "modem", + "simcom_a76xx": "modem", "sqn_gm02s": "modem", - "swir_hl7800": "modem", + "st_st87mxx": "modem", "telit_me310g1": "modem", "telit_me910g1": "modem", "u_blox_lara_r6": "modem", @@ -1065,10 +1529,36 @@ "u_blox_sara_r5": "modem", "wnc_m14a2a": "modem", # + # modem/hl78xx + "swir_hl7800": "modem/hl78xx", + "swir_hl7800_gnss": "modem/hl78xx", + "swir_hl7800_offload": "modem/hl78xx", + "swir_hl7812": "modem/hl78xx", + "swir_hl7812_gnss": "modem/hl78xx", + "swir_hl7812_offload": "modem/hl78xx", + # + # modem/simcom/sim7080 + "simcom_sim7080": "modem/simcom/sim7080", + # # mspi "ambiq_mspi_controller": "mspi", + "snps_designware_ssi": "mspi", + "st_stm32_ospi_controller": "mspi", + "st_stm32_qspi_controller": "mspi", + "st_stm32_xspi_controller": "mspi", "zephyr_mspi_emul_controller": "mspi", # + # opamp + "nxp_opamp": "opamp", + "nxp_opamp_fast": "opamp", + "st_stm32_opamp": "opamp", + # + # otp + "nxp_ocotp": "otp", + "sifli_sf32lb_efuse": "otp", + "st_stm32_bsec": "otp", + "zephyr_otp_emul": "otp", + # # pcie/controller "brcm_brcmstb_pcie": "pcie/controller", # @@ -1086,10 +1576,12 @@ "nuvoton_npcx_peci": "peci", # # pinctrl + "alif_pinctrl": "pinctrl", + "brcm_bcm2711_pinctrl": "pinctrl", + "ene_kb106x_pinctrl": "pinctrl", "ene_kb1200_pinctrl": "pinctrl", "infineon_xmc4xxx_pinctrl": "pinctrl", "ite_it8xxx2_pinctrl_func": "pinctrl", - "microchip_mec5_pinctrl": "pinctrl", "microchip_xec_pinctrl": "pinctrl", "nuvoton_numaker_pinctrl": "pinctrl", "nuvoton_numicro_pinctrl": "pinctrl", @@ -1099,12 +1591,19 @@ "realtek_rts5912_pinctrl": "pinctrl", "sensry_sy1xx_pinctrl": "pinctrl", "sifive_pinctrl": "pinctrl", + "sifli_sf32lb52x_pinmux": "pinctrl", "silabs_dbus_pinctrl": "pinctrl", + "silabs_siwx91x_pinctrl": "pinctrl", "snps_emsdp_pinctrl": "pinctrl", "telink_b91_pinctrl": "pinctrl", "ti_cc13xx_cc26xx_pinctrl": "pinctrl", + "ti_cc23x0_pinctrl": "pinctrl", "ti_cc32xx_pinctrl": "pinctrl", "ti_k3_pinctrl": "pinctrl", + "ti_mspm0_pinctrl": "pinctrl", + "wch_00x_afio": "pinctrl", + "wch_20x_30x_afio": "pinctrl", + "wch_afio": "pinctrl", "xlnx_pinctrl_zynq": "pinctrl", "xlnx_pinctrl_zynqmp": "pinctrl", # @@ -1112,46 +1611,69 @@ "renesas_rcar_pfc": "pinctrl/renesas/rcar", # # pinctrl/renesas/rz + "renesas_rza2m_pinctrl": "pinctrl/renesas/rz", "renesas_rzt2m_pinctrl": "pinctrl/renesas/rz", # # pm_cpu_ops + "arm_fvp_pwrc": "pm_cpu_ops", "arm_psci_0_2": "pm_cpu_ops", "arm_psci_1_1": "pm_cpu_ops", # # power_domain + "arm_scmi_power_domain": "power_domain", "intel_adsp_power_domain": "power_domain", + "nordic_nrfs_gdpwr": "power_domain", + "nordic_nrfs_swext": "power_domain", "nxp_scu_pd": "power_domain", "power_domain_gpio": "power_domain", "power_domain_gpio_monitor": "power_domain", + "power_domain_soc_state_change": "power_domain", + "silabs_siwx91x_power_domain": "power_domain", + "ti_sci_pm_domain": "power_domain", # # ps2 + "ite_it51xxx_ps2": "ps2", "microchip_xec_ps2": "ps2", "nuvoton_npcx_ps2_channel": "ps2", "nuvoton_npcx_ps2_ctrl": "ps2", # + # psi5 + "nxp_s32_psi5": "psi5", + # # ptp_clock "nxp_enet_ptp_clock": "ptp_clock", + "nxp_netc_ptp_clock": "ptp_clock", # # pwm "adi_max32_pwm": "pwm", + "ambiq_ctimer_pwm": "pwm", + "ambiq_timer_pwm": "pwm", "atmel_sam0_tc_pwm": "pwm", "atmel_sam0_tcc_pwm": "pwm", "atmel_sam_pwm": "pwm", + "bflb_pwm_1": "pwm", + "bflb_pwm_2": "pwm", + "ene_kb106x_pwm": "pwm", "ene_kb1200_pwm": "pwm", "espressif_esp32_ledc": "pwm", "espressif_esp32_mcpwm": "pwm", "fsl_imx27_pwm": "pwm", "gd_gd32_pwm": "pwm", - "infineon_cat1_pwm": "pwm", + "infineon_tcpwm_pwm": "pwm", "infineon_xmc4xxx_ccu4_pwm": "pwm", "infineon_xmc4xxx_ccu8_pwm": "pwm", "intel_blinky_pwm": "pwm", + "ite_it51xxx_pwm": "pwm", "ite_it8801_pwm": "pwm", "ite_it8xxx2_pwm": "pwm", "litex_pwm": "pwm", "maxim_max31790_pwm": "pwm", + "microchip_tc_g1_pwm": "pwm", + "microchip_tcc_g1_pwm": "pwm", "microchip_xec_pwm": "pwm", "microchip_xec_pwmbbled": "pwm", + "neorv32_pwm": "pwm", + "nordic_nrf_pwm": "pwm", "nordic_nrf_sw_pwm": "pwm", "nuvoton_npcx_pwm": "pwm", "nuvoton_numaker_pwm": "pwm", @@ -1167,14 +1689,27 @@ "nxp_sctimer_pwm": "pwm", "openisa_rv32m1_tpm": "pwm", "raspberrypi_pico_pwm": "pwm", + "realtek_rts5912_pwm": "pwm", "renesas_pwm_rcar": "pwm", "renesas_ra_pwm": "pwm", + "renesas_rx_mtu_pwm": "pwm", + "renesas_rz_gpt_pwm": "pwm", + "renesas_rz_mtu_pwm": "pwm", + "renesas_rza2m_gpt_pwm": "pwm", "sifive_pwm0": "pwm", + "sifli_sf32lb_atim_pwm": "pwm", + "sifli_sf32lb_gpt_pwm": "pwm", "silabs_gecko_pwm": "pwm", + "silabs_letimer_pwm": "pwm", + "silabs_siwx91x_pwm": "pwm", + "silabs_timer_pwm": "pwm", "st_stm32_pwm": "pwm", "telink_b91_pwm": "pwm", "ti_cc13xx_cc26xx_timer_pwm": "pwm", + "ti_cc23x0_lgpt_pwm": "pwm", + "ti_mspm0_timer_pwm": "pwm", "vnd_pwm": "pwm", + "wch_gptm_pwm": "pwm", "xlnx_xps_timer_1_00_a_pwm": "pwm", "zephyr_fake_pwm": "pwm", # @@ -1185,70 +1720,110 @@ "mps_mpm54304": "regulator", "nordic_npm1100": "regulator", "nordic_npm1300_regulator": "regulator", + "nordic_npm1304_regulator": "regulator", "nordic_npm2100_regulator": "regulator", "nordic_npm6001_regulator": "regulator", "nxp_pca9420": "regulator", + "nxp_pca9422_regulator": "regulator", + "nxp_pf1550_regulator": "regulator", "nxp_vref": "regulator", + "nxp_vrefv1": "regulator", "raspberrypi_core_supply_regulator": "regulator", "regulator_fixed": "regulator", "regulator_gpio": "regulator", "renesas_smartbond_regulator": "regulator", - "x_powers_axp192_regulator": "regulator", + "st_stm32_vrefbuf": "regulator", + "ti_tps55287": "regulator", "zephyr_fake_regulator": "regulator", # # reset "aspeed_ast10x0_reset": "reset", + "focaltech_ft9001_cpm_rctl": "reset", "gd_gd32_rctl": "reset", "intel_socfpga_reset": "reset", + "microchip_mpfs_reset": "reset", + "microchip_rstc_g1_reset": "reset", "nuvoton_npcx_rst": "reset", "nuvoton_numaker_rst": "reset", "nxp_lpc_syscon_reset": "reset", + "nxp_mrcc_reset": "reset", "nxp_rstctl": "reset", "raspberrypi_pico_reset": "reset", + "realtek_rts5817_reset": "reset", + "reset_mmio": "reset", + "sifli_sf32lb_rcc_rctl": "reset", "st_stm32_rcc_rctl": "reset", # # retained_mem "nordic_nrf_gpregret": "retained_mem", + "silabs_buram": "retained_mem", "zephyr_retained_ram": "retained_mem", "zephyr_retained_reg": "retained_mem", # # rtc + "adi_max31331": "rtc", "ambiq_am1805": "rtc", "ambiq_rtc": "rtc", "atmel_sam_rtc": "rtc", - "infineon_cat1_rtc": "rtc", + "epson_rx8130ce_rtc": "rtc", + "infineon_rtc": "rtc", "infineon_xmc4xxx_rtc": "rtc", + "maxim_ds1302": "rtc", "maxim_ds1307": "rtc", + "maxim_ds1337": "rtc", "maxim_ds3231_rtc": "rtc", + "microchip_rtc_g1": "rtc", + "microchip_rtc_g2": "rtc", "microcrystal_rv3028": "rtc", + "microcrystal_rv3032": "rtc", "microcrystal_rv8803": "rtc", "microcrystal_rv_8263_c8": "rtc", "motorola_mc146818": "rtc", "nuvoton_numaker_rtc": "rtc", "nxp_irtc": "rtc", + "nxp_pcf2123": "rtc", + "nxp_pcf85063a": "rtc", "nxp_pcf8523": "rtc", "nxp_pcf8563": "rtc", "raspberrypi_pico_rtc": "rtc", + "realtek_rts5912_rtc": "rtc", + "renesas_ra_rtc": "rtc", "renesas_smartbond_rtc": "rtc", + "sifli_sf32lb_rtc": "rtc", + "silabs_siwx91x_rtc": "rtc", "st_stm32_rtc": "rtc", + "ti_bq32002": "rtc", + "ti_mspm0_rtc": "rtc", "zephyr_fake_rtc": "rtc", + "zephyr_rtc_counter": "rtc", "zephyr_rtc_emul": "rtc", # # sdhc + "adi_max32_sdhc": "sdhc", + "ambiq_sdio": "sdhc", "atmel_sam_hsmci": "sdhc", "cdns_sdhc": "sdhc", "espressif_esp32_sdhc_slot": "sdhc", - "infineon_cat1_sdhc_sdio": "sdhc", + "infineon_sdhc_sdio": "sdhc", "intel_emmc_host": "sdhc", + "microchip_sama7g5_sdmmc": "sdhc", "nxp_imx_usdhc": "sdhc", "nxp_lpc_sdif": "sdhc", "renesas_ra_sdhc": "sdhc", "renesas_rcar_mmc": "sdhc", + "st_stm32_sdio": "sdhc", + "xlnx_versal_8_9a": "sdhc", "zephyr_sdhc_spi_slot": "sdhc", # # sensor/a01nyub "dfrobot_a01nyub": "sensor/a01nyub", # + # sensor/adi/ad2s1210 + "adi_ad2s1210": "sensor/adi/ad2s1210", + # + # sensor/adi/ade7978 + "adi_ade7978": "sensor/adi/ade7978", + # # sensor/adi/adltc2990 "adi_adltc2990": "sensor/adi/adltc2990", # @@ -1271,12 +1846,24 @@ # sensor/adi/adxl372 "adi_adxl372": "sensor/adi/adxl372", # + # sensor/adi/max30210 + "adi_max30210": "sensor/adi/max30210", + # + # sensor/adi/max32664c + "maxim_max32664c": "sensor/adi/max32664c", + # + # sensor/als31300 + "allegro_als31300": "sensor/als31300", + # # sensor/amd_sb_tsi "amd_sb_tsi": "sensor/amd_sb_tsi", # # sensor/amg88xx "panasonic_amg88xx": "sensor/amg88xx", # + # sensor/ams/ams_as5048 + "ams_as5048": "sensor/ams/ams_as5048", + # # sensor/ams/ams_as5600 "ams_as5600": "sensor/ams/ams_as5600", # @@ -1339,6 +1926,12 @@ # sensor/bosch/bmc150_magn "bosch_bmc150_magn": "sensor/bosch/bmc150_magn", # + # sensor/bosch/bme280 + "bosch_bme280": "sensor/bosch/bme280", + # + # sensor/bosch/bme680 + "bosch_bme680": "sensor/bosch/bme680", + # # sensor/bosch/bmg160 "bosch_bmg160": "sensor/bosch/bmg160", # @@ -1355,6 +1948,12 @@ # sensor/bosch/bmi323 "bosch_bmi323": "sensor/bosch/bmi323", # + # sensor/bosch/bmm150 + "bosch_bmm150": "sensor/bosch/bmm150", + # + # sensor/bosch/bmm350 + "bosch_bmm350": "sensor/bosch/bmm350", + # # sensor/bosch/bmp180 "bosch_bmp180": "sensor/bosch/bmp180", # @@ -1362,6 +1961,12 @@ "bosch_bmp388": "sensor/bosch/bmp388", "bosch_bmp390": "sensor/bosch/bmp388", # + # sensor/bosch/bmp581 + "bosch_bmp581": "sensor/bosch/bmp581", + # + # sensor/broadcom/afbr_s50 + "brcm_afbr_s50": "sensor/broadcom/afbr_s50", + # # sensor/current_amp "current_sense_amplifier": "sensor/current_amp", # @@ -1377,6 +1982,9 @@ # sensor/espressif/pcnt_esp32 "espressif_esp32_pcnt": "sensor/espressif/pcnt_esp32", # + # sensor/everlight/als_pt19 + "everlight_als_pt19": "sensor/everlight/als_pt19", + # # sensor/explorir_m "gss_explorir_m": "sensor/explorir_m", # @@ -1414,6 +2022,12 @@ # sensor/infineon/xmc4xxx_temp "infineon_xmc4xxx_temp": "sensor/infineon/xmc4xxx_temp", # + # sensor/ist8310 + "isentek_ist8310": "sensor/ist8310", + # + # sensor/ite/ite_tach_it51xxx + "ite_it51xxx_tach": "sensor/ite/ite_tach_it51xxx", + # # sensor/ite/ite_tach_it8xxx2 "ite_it8xxx2_tach": "sensor/ite/ite_tach_it8xxx2", # @@ -1423,6 +2037,9 @@ # sensor/jedec/jc42 "jedec_jc_42_4_temp": "sensor/jedec/jc42", # + # sensor/liteon/ltrf216a + "liteon_ltrf216a": "sensor/liteon/ltrf216a", + # # sensor/lm35 "lm35": "sensor/lm35", # @@ -1432,9 +2049,6 @@ # sensor/lm77 "lm77": "sensor/lm77", # - # sensor/ltrf216a - "ltr_f216a": "sensor/ltrf216a", - # # sensor/maxim/ds18b20 "maxim_ds18b20": "sensor/maxim/ds18b20", "maxim_ds18s20": "sensor/maxim/ds18b20", @@ -1458,6 +2072,9 @@ # sensor/maxim/max31855 "maxim_max31855": "sensor/maxim/max31855", # + # sensor/maxim/max31865 + "maxim_max31865": "sensor/maxim/max31865", + # # sensor/maxim/max31875 "maxim_max31875": "sensor/maxim/max31875", # @@ -1467,11 +2084,15 @@ # sensor/maxim/max6675 "maxim_max6675": "sensor/maxim/max6675", # + # sensor/mb7040 + "maxbotix_mb7040": "sensor/mb7040", + # # sensor/meas/ms5607 "meas_ms5607": "sensor/meas/ms5607", # # sensor/meas/ms5837 - "meas_ms5837": "sensor/meas/ms5837", + "meas_ms5837_02ba": "sensor/meas/ms5837", + "meas_ms5837_30ba": "sensor/meas/ms5837", # # sensor/melexis/mlx90394 "melexis_mlx90394": "sensor/melexis/mlx90394", @@ -1479,6 +2100,9 @@ # sensor/memsic/mc3419 "memsic_mc3419": "sensor/memsic/mc3419", # + # sensor/memsic/mmc56x3 + "memsic_mmc56x3": "sensor/memsic/mmc56x3", + # # sensor/mhz19b "winsen_mhz19b": "sensor/mhz19b", # @@ -1491,14 +2115,18 @@ # sensor/microchip/mcp970x "microchip_mcp970x": "sensor/microchip/mcp970x", # + # sensor/microchip/mtch9010 + "microchip_mtch9010": "sensor/microchip/mtch9010", + # # sensor/microchip/tcn75a "microchip_tcn75a": "sensor/microchip/tcn75a", # # sensor/nct75 "onnn_nct75": "sensor/nct75", # - # sensor/nordic/npm1300_charger - "nordic_npm1300_charger": "sensor/nordic/npm1300_charger", + # sensor/nordic/npm13xx_charger + "nordic_npm1300_charger": "sensor/nordic/npm13xx_charger", + "nordic_npm1304_charger": "sensor/nordic/npm13xx_charger", # # sensor/nordic/npm2100_vbat "nordic_npm2100_vbat": "sensor/nordic/npm2100_vbat", @@ -1520,6 +2148,9 @@ # sensor/nuvoton/nuvoton_adc_cmp_npcx "nuvoton_adc_cmp": "sensor/nuvoton/nuvoton_adc_cmp_npcx", # + # sensor/nuvoton/nuvoton_adc_v2t_npcx + "nuvoton_npcx_adc_v2t": "sensor/nuvoton/nuvoton_adc_v2t_npcx", + # # sensor/nuvoton/nuvoton_tach_npcx "nuvoton_npcx_tach": "sensor/nuvoton/nuvoton_tach_npcx", # @@ -1541,9 +2172,21 @@ # sensor/nxp/nxp_kinetis_temp "nxp_kinetis_temperature": "sensor/nxp/nxp_kinetis_temp", # + # sensor/nxp/nxp_lpadc_temp40 + "nxp_lpadc_temp40": "sensor/nxp/nxp_lpadc_temp40", + # + # sensor/nxp/nxp_pmc_tmpsns + "nxp_pmc_tmpsns": "sensor/nxp/nxp_pmc_tmpsns", + # # sensor/nxp/nxp_tempmon "nxp_tempmon": "sensor/nxp/nxp_tempmon", # + # sensor/nxp/nxp_tempsense + "nxp_tempsense": "sensor/nxp/nxp_tempsense", + # + # sensor/nxp/nxp_tmpsns + "nxp_tmpsns": "sensor/nxp/nxp_tmpsns", + # # sensor/nxp/p3t1755 "nxp_p3t1755": "sensor/nxp/p3t1755", # @@ -1553,12 +2196,40 @@ # sensor/nxp/qdec_nxp_s32 "nxp_qdec_s32": "sensor/nxp/qdec_nxp_s32", # + # sensor/nxp/qdec_tpm + "nxp_tpm_qdec": "sensor/nxp/qdec_tpm", + # + # sensor/omron/2smpb_02e + "omron_2smpb_02e": "sensor/omron/2smpb_02e", + # + # sensor/omron/d6f + "omron_d6f_p0001": "sensor/omron/d6f", + "omron_d6f_p0010": "sensor/omron/d6f", + # + # sensor/pixart/paa3905 + "pixart_paa3905": "sensor/pixart/paa3905", + # + # sensor/pixart/paj7620 + "pixart_paj7620": "sensor/pixart/paj7620", + # + # sensor/pixart/pat9136 + "pixart_pat9136": "sensor/pixart/pat9136", + # # sensor/pms7003 "plantower_pms7003": "sensor/pms7003", # + # sensor/pni/rm3100 + "pni_rm3100": "sensor/pni/rm3100", + # + # sensor/pzem004t + "peacefair_pzem004t": "sensor/pzem004t", + # # sensor/qdec_sam "atmel_sam_tc_qdec": "sensor/qdec_sam", # + # sensor/realtek/rts5912 + "realtek_rts5912_tach": "sensor/realtek/rts5912", + # # sensor/renesas/hs300x "renesas_hs300x": "sensor/renesas/hs300x", # @@ -1571,12 +2242,21 @@ # sensor/rohm/bd8lb600fs "rohm_bd8lb600fs_diagnostics": "sensor/rohm/bd8lb600fs", # + # sensor/rohm/bh1730 + "rohm_bh1730": "sensor/rohm/bh1730", + # # sensor/rohm/bh1750 "rohm_bh1750": "sensor/rohm/bh1750", # + # sensor/rohm/bh1790 + "rohm_bh1790": "sensor/rohm/bh1790", + # # sensor/rpi_pico_temp "raspberrypi_pico_temp": "sensor/rpi_pico_temp", # + # sensor/rv3032_temp + "microcrystal_rv3032_temp": "sensor/rv3032_temp", + # # sensor/s11059 "hamamatsu_s11059": "sensor/s11059", # @@ -1606,6 +2286,9 @@ # sensor/sensirion/sts4x "sensirion_sts4x": "sensor/sensirion/sts4x", # + # sensor/sifli/sf32lb_tsen + "sifli_sf32lb_tsen": "sensor/sifli/sf32lb_tsen", + # # sensor/silabs/si7006 "sensirion_sht21": "sensor/silabs/si7006", "silabs_si7006": "sensor/silabs/si7006", @@ -1643,6 +2326,9 @@ # sensor/st/iis3dhhc "st_iis3dhhc": "sensor/st/iis3dhhc", # + # sensor/st/iis3dwb + "st_iis3dwb": "sensor/st/iis3dwb", + # # sensor/st/ism330dhcx "st_ism330dhcx": "sensor/st/ism330dhcx", # @@ -1702,7 +2388,16 @@ "st_lsm6dso16is": "sensor/st/lsm6dso16is", # # sensor/st/lsm6dsv16x + "DT_DRV_COMPAT_LSM6DSV16X": "sensor/st/lsm6dsv16x", + "DT_DRV_COMPAT_LSM6DSV32X": "sensor/st/lsm6dsv16x", "st_lsm6dsv16x": "sensor/st/lsm6dsv16x", + "st_lsm6dsv32x": "sensor/st/lsm6dsv16x", + # + # sensor/st/lsm6dsvxxx + "st_ism6hg256x": "sensor/st/lsm6dsvxxx", + "st_lsm6dsv320x": "sensor/st/lsm6dsvxxx", + "st_lsm6dsv80x": "sensor/st/lsm6dsvxxx", + "st_lsm6dsvxxx": "sensor/st/lsm6dsvxxx", # # sensor/st/lsm9ds0_gyro "st_lsm9ds0_gyro": "sensor/st/lsm9ds0_gyro", @@ -1713,6 +2408,9 @@ # sensor/st/lsm9ds1 "st_lsm9ds1": "sensor/st/lsm9ds1", # + # sensor/st/lsm9ds1_mag + "st_lsm9ds1_mag": "sensor/st/lsm9ds1_mag", + # # sensor/st/qdec_stm32 "st_stm32_qdec": "sensor/st/qdec_stm32", # @@ -1745,18 +2443,36 @@ # sensor/sx9500 "semtech_sx9500": "sensor/sx9500", # + # sensor/tach_gpio + "zephyr_tach_gpio": "sensor/tach_gpio", + # + # sensor/tdk/icm40627 + "invensense_icm40627": "sensor/tdk/icm40627", + # # sensor/tdk/icm42605 "invensense_icm42605": "sensor/tdk/icm42605", # - # sensor/tdk/icm42670 - "invensense_icm42670p": "sensor/tdk/icm42670", - "invensense_icm42670s": "sensor/tdk/icm42670", + # sensor/tdk/icm4268x + "invensense_icm42688": "sensor/tdk/icm4268x", + "invensense_icm4268x": "sensor/tdk/icm4268x", # - # sensor/tdk/icm42688 - "invensense_icm42688": "sensor/tdk/icm42688", + # sensor/tdk/icm42x70 + "invensense_icm42370p": "sensor/tdk/icm42x70", + "invensense_icm42670p": "sensor/tdk/icm42x70", + "invensense_icm42670s": "sensor/tdk/icm42x70", # - # sensor/tdk/icp10125 - "invensense_icp10125": "sensor/tdk/icp10125", + # sensor/tdk/icm45686 + "invensense_icm45605": "sensor/tdk/icm45686", + "invensense_icm45605s": "sensor/tdk/icm45686", + "invensense_icm45686": "sensor/tdk/icm45686", + "invensense_icm45686s": "sensor/tdk/icm45686", + "invensense_icm45688p": "sensor/tdk/icm45686", + # + # sensor/tdk/icp101xx + "invensense_icp101xx": "sensor/tdk/icp101xx", + # + # sensor/tdk/icp201xx + "invensense_icp201xx": "sensor/tdk/icp201xx", # # sensor/tdk/mpu6050 "invensense_mpu6050": "sensor/tdk/mpu6050", @@ -1776,26 +2492,34 @@ # sensor/ti/ina219 "ti_ina219": "sensor/ti/ina219", # - # sensor/ti/ina226 - "ti_ina226": "sensor/ti/ina226", - # - # sensor/ti/ina23x - "ti_ina230": "sensor/ti/ina23x", - "ti_ina236": "sensor/ti/ina23x", - "ti_ina237": "sensor/ti/ina23x", + # sensor/ti/ina2xx + "ti_ina226": "sensor/ti/ina2xx", + "ti_ina228": "sensor/ti/ina2xx", + "ti_ina230": "sensor/ti/ina2xx", + "ti_ina232": "sensor/ti/ina2xx", + "ti_ina236": "sensor/ti/ina2xx", + "ti_ina237": "sensor/ti/ina2xx", # # sensor/ti/ina3221 "ti_ina3221": "sensor/ti/ina3221", # + # sensor/ti/ina7xx + "ti_ina7xx": "sensor/ti/ina7xx", + # # sensor/ti/lm95234 "national_lm95234": "sensor/ti/lm95234", # - # sensor/ti/opt3001 - "ti_opt3001": "sensor/ti/opt3001", + # sensor/ti/opt300x + "ti_opt3001": "sensor/ti/opt300x", + "ti_opt3004": "sensor/ti/opt300x", + "ti_opt300x": "sensor/ti/opt300x", # # sensor/ti/ti_hdc "ti_hdc": "sensor/ti/ti_hdc", # + # sensor/ti/ti_hdc302x + "ti_hdc302x": "sensor/ti/ti_hdc302x", + # # sensor/ti/tmag5170 "ti_tmag5170": "sensor/ti/tmag5170", # @@ -1807,6 +2531,7 @@ # # sensor/ti/tmp108 "ams_as6212": "sensor/ti/tmp108", + "ams_as6221": "sensor/ti/tmp108", "ti_tmp108": "sensor/ti/tmp108", # # sensor/ti/tmp112 @@ -1815,8 +2540,11 @@ # sensor/ti/tmp114 "ti_tmp114": "sensor/ti/tmp114", # - # sensor/ti/tmp116 - "ti_tmp116": "sensor/ti/tmp116", + # sensor/ti/tmp11x + "ti_tmp11x": "sensor/ti/tmp11x", + # + # sensor/ti/tmp435 + "ti_tmp435": "sensor/ti/tmp435", # # sensor/tsic_xx6 "ist_tsic_xx6": "sensor/tsic_xx6", @@ -1830,6 +2558,12 @@ # sensor/vishay/vcnl4040 "vishay_vcnl4040": "sensor/vishay/vcnl4040", # + # sensor/vishay/veml6031 + "vishay_veml6031": "sensor/vishay/veml6031", + # + # sensor/vishay/veml6046 + "vishay_veml6046": "sensor/vishay/veml6046", + # # sensor/vishay/veml7700 "vishay_veml7700": "sensor/vishay/veml7700", # @@ -1839,37 +2573,65 @@ # sensor/wsen/wsen_hids_2525020210002 "we_wsen_hids_2525020210002": "sensor/wsen/wsen_hids_2525020210002", # + # sensor/wsen/wsen_isds_2536030320001 + "we_wsen_isds_2536030320001": "sensor/wsen/wsen_isds_2536030320001", + # + # sensor/wsen/wsen_itds_2533020201601 + "we_wsen_itds_2533020201601": "sensor/wsen/wsen_itds_2533020201601", + # + # sensor/wsen/wsen_pads_2511020213301 + "we_wsen_pads_2511020213301": "sensor/wsen/wsen_pads_2511020213301", + # + # sensor/wsen/wsen_pdms_25131308XXX05 + "we_wsen_pdms_25131308xxx05": "sensor/wsen/wsen_pdms_25131308XXX05", + # # sensor/wsen/wsen_pdus_25131308XXXXX "we_wsen_pdus_25131308xxxxx": "sensor/wsen/wsen_pdus_25131308XXXXX", # + # sensor/wsen/wsen_tids_2521020222501 + "we_wsen_tids_2521020222501": "sensor/wsen/wsen_tids_2521020222501", + # + # sensor/xbr818 + "phosense_xbr818": "sensor/xbr818", + # + # sent + "nxp_s32_sent": "sent", + # # serial "SBSA_COMPAT": "serial", "adi_max32_uart": "serial", + "aesc_uart": "serial", "altr_jtag_uart": "serial", "altr_uart": "serial", + "ambiq_uart": "serial", "arm_cmsdk_uart": "serial", "arm_pl011": "serial", "atmel_sam0_uart": "serial", "atmel_sam_uart": "serial", "atmel_sam_usart": "serial", + "bflb_uart": "serial", "brcm_bcm2711_aux_uart": "serial", "cdns_uart": "serial", "cypress_psoc6_uart": "serial", "efinix_sapphire_uart0": "serial", + "ene_kb106x_uart": "serial", "ene_kb1200_uart": "serial", + "espressif_esp32_lpuart": "serial", "espressif_esp32_uart": "serial", "espressif_esp32_usb_serial": "serial", + "focaltech_ft9001_usart": "serial", "gaisler_apbuart": "serial", "gd_gd32_usart": "serial", - "infineon_cat1_uart": "serial", + "infineon_uart": "serial", "infineon_xmc4xxx_uart": "serial", "intel_lw_uart": "serial", "intel_sedi_uart": "serial", + "ite_it51xxx_uart": "serial", "ite_it8xxx2_uart": "serial", "litex_uart": "serial", "lowrisc_opentitan_uart": "serial", "microchip_coreuart": "serial", - "microchip_mec5_uart": "serial", + "microchip_sercom_g1_uart": "serial", "microchip_xec_uart": "serial", "neorv32_uart": "serial", "nordic_nrf_uart": "serial", @@ -1888,38 +2650,51 @@ "openisa_rv32m1_lpuart": "serial", "quicklogic_usbserialport_s3b": "serial", "raspberrypi_pico_uart_pio": "serial", + "realtek_ameba_loguart": "serial", + "realtek_bee_uart": "serial", "realtek_rts5912_uart": "serial", "renesas_ra8_uart_sci_b": "serial", "renesas_ra_sci_uart": "serial", - "renesas_ra_uart_sci": "serial", "renesas_rcar_hscif": "serial", "renesas_rcar_scif": "serial", + "renesas_rx_uart_sci": "serial", + "renesas_rx_uart_sci_qemu": "serial", + "renesas_rz_sci_b_uart": "serial", + "renesas_rz_sci_uart": "serial", "renesas_rz_scif_uart": "serial", + "renesas_rza2m_scif_uart": "serial", "renesas_rzt2m_uart": "serial", "renesas_smartbond_uart": "serial", "segger_rtt_uart": "serial", "sensry_sy1xx_uart": "serial", "sifive_uart0": "serial", + "sifli_sf32lb_usart": "serial", "silabs_eusart_uart": "serial", "silabs_gecko_leuart": "serial", "silabs_gecko_uart": "serial", "silabs_gecko_usart": "serial", "silabs_si32_usart": "serial", + "silabs_usart_uart": "serial", "snps_hostlink_uart": "serial", "st_stm32_uart": "serial", "telink_b91_uart": "serial", "ti_cc13xx_cc26xx_uart": "serial", + "ti_cc23x0_uart": "serial", "ti_cc32xx_uart": "serial", "ti_msp432p4xx_uart": "serial", + "ti_mspm0_uart": "serial", "ti_stellaris_uart": "serial", + "virtio_console": "serial", "vnd_serial": "serial", "wch_usart": "serial", "xen_hvc_consoleio": "serial", "xlnx_xps_uartlite_1_00_a": "serial", "xlnx_xuartps": "serial", - "zephyr_native_posix_uart": "serial", + "zephyr_native_pty_uart": "serial", "zephyr_native_tty_uart": "serial", "zephyr_nus_uart": "serial", + "zephyr_uart_bitbang": "serial", + "zephyr_uart_bridge": "serial", "zephyr_uart_emul": "serial", # # sip_svc @@ -1938,22 +2713,29 @@ "arm_pl022": "spi", "atmel_sam0_spi": "spi", "atmel_sam_spi": "spi", + "bflb_spi": "spi", + "cdns_spi": "spi", "cypress_psoc6_spi": "spi", + "egis_et171_spi": "spi", "espressif_esp32_spi": "spi", "gaisler_spimctrl": "spi", "gd_gd32_spi": "spi", - "infineon_cat1_spi": "spi", + "infineon_spi": "spi", "infineon_xmc4xxx_spi": "spi", "intel_penwell_spi": "spi", "intel_sedi_spi": "spi", + "ite_it51xxx_spi": "spi", "ite_it8xxx2_spi": "spi", "litex_spi": "spi", "litex_spi_litespi": "spi", "lowrisc_opentitan_spi": "spi", "microchip_mpfs_qspi": "spi", "microchip_mpfs_spi": "spi", + "microchip_sercom_g1_spi": "spi", "microchip_xec_qmspi": "spi", "microchip_xec_qmspi_ldma": "spi", + "nordic_nrf_spi": "spi", + "nordic_nrf_spim": "spi", "nuvoton_npcx_spip": "spi", "nuvoton_numaker_spi": "spi", "nxp_dspi": "spi", @@ -1961,20 +2743,33 @@ "nxp_imx_ecspi": "spi", "nxp_lpc_spi": "spi", "nxp_s32_spi": "spi", + "nxp_sc18is606_spi": "spi", "opencores_spi_simple": "spi", "openisa_rv32m1_lpspi": "spi", "raspberrypi_pico_spi_pio": "spi", + "realtek_rts5912_spi": "spi", "renesas_ra8_spi_b": "spi", "renesas_ra_spi": "spi", + "renesas_ra_spi_sci": "spi", + "renesas_ra_spi_sci_b": "spi", + "renesas_rx_rspi": "spi", + "renesas_rz_rspi": "spi", + "renesas_rz_spi": "spi", "renesas_smartbond_spi": "spi", + "sensry_sy1xx_spi": "spi", "sifive_spi0": "spi", + "sifli_sf32lb_spi": "spi", "silabs_eusart_spi": "spi", + "silabs_gspi": "spi", "silabs_usart_spi": "spi", "snps_designware_spi": "spi", "st_stm32_spi": "spi", "telink_b91_spi": "spi", "ti_cc13xx_cc26xx_spi": "spi", + "ti_cc23x0_spi": "spi", + "ti_omap_mcspi": "spi", "vnd_spi": "spi", + "wch_spi": "spi", "xlnx_xps_spi_2_00_a": "spi", "zephyr_spi_bitbang": "spi", "zephyr_spi_emul_controller": "spi", @@ -1983,68 +2778,92 @@ "nxp_lpspi": "spi/spi_nxp_lpspi", # # stepper - "zephyr_fake_stepper": "stepper", - "zephyr_gpio_stepper": "stepper", + "zephyr_fake_stepper_ctrl": "stepper", + "zephyr_fake_stepper_driver": "stepper", + # + # stepper/adi_tmc/tmc22xx + "adi_tmc2209": "stepper/adi_tmc/tmc22xx", + # + # stepper/adi_tmc/tmc50xx + "adi_tmc50xx": "stepper/adi_tmc/tmc50xx", + "adi_tmc50xx_stepper_ctrl": "stepper/adi_tmc/tmc50xx", + "adi_tmc50xx_stepper_driver": "stepper/adi_tmc/tmc50xx", + # + # stepper/adi_tmc/tmc51xx + "adi_tmc51xx": "stepper/adi_tmc/tmc51xx", + "adi_tmc51xx_stepper_ctrl": "stepper/adi_tmc/tmc51xx", + "adi_tmc51xx_stepper_driver": "stepper/adi_tmc/tmc51xx", # - # stepper/adi_tmc - "adi_tmc2209": "stepper/adi_tmc", - "adi_tmc5041": "stepper/adi_tmc", + # stepper/allegro + "allegro_a4979": "stepper/allegro", + # + # stepper/gpio_stepper + "zephyr_gpio_step_dir_stepper_ctrl": "stepper/gpio_stepper", + "zephyr_h_bridge_stepper_ctrl": "stepper/gpio_stepper", # # stepper/ti - "ti_drv8424": "stepper/ti", + "ti_drv84xx": "stepper/ti", # # syscon + "bflb_efuse": "syscon", "syscon": "syscon", # # tee/optee "linaro_optee_tz": "tee/optee", # # timer + "adi_max32_rv32_sys_timer": "timer", "ambiq_stimer": "timer", - "andestech_machine_timer": "timer", "atmel_sam0_rtc": "timer", "gaisler_gptimer": "timer", + "infineon_lp_timer": "timer", "intel_adsp_timer": "timer", "intel_hpet": "timer", + "ite_it51xxx_timer": "timer", "ite_it8xxx2_timer": "timer", "litex_timer0": "timer", - "lowrisc_machine_timer": "timer", - "microchip_mec5_ktimer": "timer", + "microchip_sam_pit64b": "timer", "microchip_xec_rtos_timer": "timer", - "neorv32_machine_timer": "timer", - "niosv_machine_timer": "timer", - "nuclei_systimer": "timer", "nuvoton_npcx_itim_timer": "timer", "nxp_gpt_hw_timer": "timer", - "nxp_kinetis_lptmr": "timer", "nxp_lptmr": "timer", "nxp_os_timer": "timer", "openisa_rv32m1_lptmr": "timer", "realtek_rts5912_rtmr": "timer", + "renesas_ra_ulpt_timer": "timer", "renesas_rcar_cmt": "timer", - "scr_machine_timer": "timer", - "sifive_clint0": "timer", + "renesas_rx_timer_cmt": "timer", + "renesas_rz_gtm_os_timer": "timer", + "renesas_rza2m_ostm": "timer", + "riscv_machine_timer": "timer", "silabs_gecko_burtc": "timer", "st_stm32_lptim": "timer", "sy1xx_sys_timer": "timer", - "telink_machine_timer": "timer", "ti_am654_timer": "timer", "ti_cc13xx_cc26xx_rtc_timer": "timer", + "ti_cc23x0_rtc_timer": "timer", + "ti_cc23x0_systim_timer": "timer", "wch_systick": "timer", "xlnx_ttcps": "timer", # # usb/bc12 "diodes_pi3usb9201": "usb/bc12", # + # usb/common/stm32 + "*/": "usb/common/stm32", + "st_stm32u5_otghs_phy": "usb/common/stm32", + # # usb/device - "atmel_sam0_usb": "usb/device", "atmel_sam_usbc": "usb/device", "atmel_sam_usbhs": "usb/device", # # usb/udc + "adi_max32_usbhs": "usb/udc", "ambiq_usb": "usb/udc", + "atmel_sam0_usb": "usb/udc", "ite_it82xx2_usb": "usb/udc", "nordic_nrf_usbd": "usb/udc", + "nuvoton_numaker_hsusbd": "usb/udc", "nuvoton_numaker_usbd": "usb/udc", "nxp_ehci": "usb/udc", "nxp_kinetis_usbd": "usb/udc", @@ -2056,11 +2875,16 @@ "st_stm32_otgfs": "usb/udc", "st_stm32_otghs": "usb/udc", "st_stm32_usb": "usb/udc", + "wch_usbhs2": "usb/udc", "zephyr_udc_skeleton": "usb/udc", "zephyr_udc_virtual": "usb/udc", # # usb/uhc "maxim_max3421e_spi": "usb/uhc", + "nxp_uhc_ehci": "usb/uhc", + "nxp_uhc_ip3516hs": "usb/uhc", + "nxp_uhc_khci": "usb/uhc", + "nxp_uhc_ohci": "usb/uhc", "zephyr_uhc_virtual": "usb/uhc", # # usb_c/ppc @@ -2069,6 +2893,7 @@ # # usb_c/tcpc "nuvoton_numaker_tcpc": "usb_c/tcpc", + "onnn_fusb307_tcpc": "usb_c/tcpc", "parade_ps8xxx": "usb_c/tcpc", "richtek_rt1715": "usb_c/tcpc", "st_stm32_ucpd": "usb_c/tcpc", @@ -2080,19 +2905,34 @@ # # video "aptina_mt9m114": "video", - "espressif_esp32_lcd_cam": "video", + "espressif_esp32_lcd_cam_dvp": "video", "galaxycore_gc2145": "video", + "himax_hm01b0": "video", + "himax_hm0360": "video", "nxp_imx_csi": "video", "nxp_mipi_csi2rx": "video", "nxp_video_smartdma": "video", "ovti_ov2640": "video", "ovti_ov5640": "video", + "ovti_ov5642": "video", "ovti_ov7670": "video", + "ovti_ov7675": "video", "ovti_ov7725": "video", + "ovti_ov9655": "video", + "renesas_ra_ceu": "video", + "sony_imx335": "video", + "st_mipid02": "video", "st_stm32_dcmi": "video", - "zephyr_sw_generator": "video", + "st_stm32_dcmipp": "video", + "st_stm32_jpeg": "video", + "st_stm32_venc": "video", "zephyr_video_emul_imager": "video", "zephyr_video_emul_rx": "video", + "zephyr_video_sw_generator": "video", + # + # virtio + "virtio_mmio": "virtio", + "virtio_pci": "virtio", # # virtualization "qemu_ivshmem": "virtualization", @@ -2109,45 +2949,66 @@ # # watchdog "adi_max32_watchdog": "watchdog", + "adi_max42500_watchdog": "watchdog", "ambiq_watchdog": "watchdog", "andestech_atcwdt200": "watchdog", "arm_cmsdk_watchdog": "watchdog", "atmel_sam0_watchdog": "watchdog", + "atmel_sam4l_watchdog": "watchdog", "atmel_sam_watchdog": "watchdog", + "bflb_wdt": "watchdog", + "ene_kb106x_watchdog": "watchdog", "ene_kb1200_watchdog": "watchdog", "espressif_esp32_watchdog": "watchdog", "espressif_esp32_xt_wdt": "watchdog", "gd_gd32_fwdgt": "watchdog", "gd_gd32_wwdgt": "watchdog", - "infineon_cat1_watchdog": "watchdog", + "infineon_watchdog": "watchdog", "infineon_xmc4xxx_watchdog": "watchdog", "intel_adsp_watchdog": "watchdog", "intel_tco_wdt": "watchdog", + "ite_it51xxx_watchdog": "watchdog", "ite_it8xxx2_watchdog": "watchdog", "litex_watchdog": "watchdog", "lowrisc_opentitan_aontimer": "watchdog", + "microchip_wdt_g1": "watchdog", "microchip_xec_watchdog": "watchdog", "nordic_npm1300_wdt": "watchdog", + "nordic_npm1304_wdt": "watchdog", "nordic_npm2100_wdt": "watchdog", "nordic_npm6001_wdt": "watchdog", + "nordic_nrf_wdt": "watchdog", "nuvoton_npcx_watchdog": "watchdog", "nuvoton_numaker_wwdt": "watchdog", + "nxp_cop": "watchdog", + "nxp_ewm": "watchdog", "nxp_fs26_wdog": "watchdog", "nxp_imx_wdog": "watchdog", "nxp_kinetis_wdog": "watchdog", "nxp_lpc_wwdt": "watchdog", + "nxp_rtwdog": "watchdog", "nxp_s32_swt": "watchdog", "nxp_wdog32": "watchdog", "raspberrypi_pico_watchdog": "watchdog", + "realtek_rts5817_watchdog": "watchdog", + "realtek_rts5912_watchdog": "watchdog", + "renesas_rx_iwdt": "watchdog", + "renesas_rz_wdt": "watchdog", "renesas_smartbond_watchdog": "watchdog", "sifive_wdt": "watchdog", + "sifli_sf32lb_wdt": "watchdog", "silabs_gecko_wdog": "watchdog", + "silabs_siwx91x_wdt": "watchdog", "snps_designware_watchdog": "watchdog", "st_stm32_watchdog": "watchdog", "st_stm32_window_watchdog": "watchdog", "ti_cc13xx_cc26xx_watchdog": "watchdog", + "ti_cc23x0_wdt": "watchdog", "ti_cc32xx_watchdog": "watchdog", + "ti_j7_rti_wdt": "watchdog", "ti_tps382x": "watchdog", + "wch_iwdg": "watchdog", + "xlnx_versal_wwdt": "watchdog", "xlnx_xps_timebase_wdt_1_00_a": "watchdog", # # wifi/esp32/src @@ -2156,16 +3017,25 @@ # wifi/esp_at "espressif_esp_at": "wifi/esp_at", # + # wifi/esp_hosted + "espressif_esp_hosted": "wifi/esp_hosted", + # # wifi/eswifi "inventek_eswifi": "wifi/eswifi", "inventek_eswifi_uart": "wifi/eswifi", # + # wifi/infineon + "infineon_airoc_wifi": "wifi/infineon", + # # wifi/nrf_wifi/off_raw_tx/src "nordic_wlan": "wifi/nrf_wifi/off_raw_tx/src", # # wifi/nxp "nxp_wifi": "wifi/nxp", # + # wifi/siwx91x + "silabs_siwx91x_wifi": "wifi/siwx91x", + # # wifi/winc1500 "atmel_winc1500": "wifi/winc1500", } diff --git a/ports/zephyr-cp/cptools/cpbuild.py b/ports/zephyr-cp/cptools/cpbuild.py index 335234b8c76..8121f4b8016 100644 --- a/ports/zephyr-cp/cptools/cpbuild.py +++ b/ports/zephyr-cp/cptools/cpbuild.py @@ -1,15 +1,14 @@ import asyncio -import inspect +import atexit +import hashlib +import json import logging import os import pathlib -import shlex -import time -import hashlib -import atexit -import json import re -import sys +import tempfile +import time +from typing import Optional logger = logging.getLogger(__name__) @@ -24,7 +23,7 @@ LAST_BUILD_TIMES = json.load(f) logger.info("Build times loaded.") else: - logger.warn( + logger.warning( "No last build times found. This is normal if you're running this for the first time." ) @@ -97,13 +96,27 @@ async def __aexit__(self, exc_type, exc, tb): self.new_token(token) +def _default_job_count(): + # process_cpu_count() (Python 3.13+) counts only the CPUs this process is allowed to + # run on, e.g. inside a container or under taskset. cpu_count() counts all CPUs. + if hasattr(os, "process_cpu_count"): + return os.process_cpu_count() or 1 + return os.cpu_count() or 1 + + def _create_semaphore(): match = re.search(r"fifo:([^\s]+)", os.environ.get("MAKEFLAGS", "")) fifo_path = None if match: fifo_path = match.group(1) return _MakeJobClient(fifo_path=fifo_path) - return asyncio.BoundedSemaphore(1) + # No fifo jobserver found. Either we were not run from make at all, or make is older + # than 4.4. Older make shares its jobserver as a pair of inherited file descriptors + # (--jobserver-auth=R,W in MAKEFLAGS), and only keeps them open for commands that + # start with "+" or $(MAKE); the west build command is neither, so we cannot use them. + # ubuntu-24.04 CI runners have make 4.3. Rather than compile one file at a time, + # run as many compiles as there are CPUs. + return asyncio.BoundedSemaphore(_default_job_count()) shared_semaphore = _create_semaphore() @@ -111,7 +124,14 @@ def _create_semaphore(): max_track = 0 -async def run_command(command, working_directory, description=None, check_hash=[], extradeps=[]): +async def run_command( + command, + working_directory, + description=None, + check_hash=[], + extradeps=[], + responsefile: Optional[pathlib.Path] = None, +): """ Runs a command asynchronously. The command should ideally be a list of strings and pathlib.Path objects. If all of the paths haven't been modified since the last @@ -124,26 +144,39 @@ async def run_command(command, working_directory, description=None, check_hash=[ Paths in check_hash are hashed before and after the command. If the hash is the same, then the old mtimes are reset. This is helpful if a command may produce - the same result and you don't want the rest of the build impacted. + the same result and you don't want the rest of the build impacted + + responsefile is used to store the command line arguments if they are too long for the OS. + The arguments will be replaced with @ and tried again. + If None, commands that are too long will fail. """ paths = [] + responsefile_contents = None if isinstance(command, list): for i, part in enumerate(command): if isinstance(part, pathlib.Path): paths.append(part) part = part.relative_to(working_directory, walk_up=True) - # if isinstance(part, list): command[i] = str(part) - command = " ".join(command) + command_string = " ".join(command) + + # When on windows, use a responsefile if the command string is >= 8192 + if responsefile is not None and os.name == "nt" and len(command_string) >= 8192: + # Escape backslashes + responsefile_contents = "\n".join(part.replace("\\", "\\\\") for part in command[1:]) + responsefile.write_text(responsefile_contents) + command_string = f"{command[0]} -v @{responsefile}" + else: + command_string = command - command_hash = hashlib.sha3_256(command.encode("utf-8")) + command_hash = hashlib.sha3_256(command_string.encode("utf-8")) command_hash.update(str(working_directory).encode("utf-8")) command_hash = command_hash.hexdigest() # If a command is run multiple times, then wait for the first one to continue. Don't run it again. if command_hash in ALREADY_RUN: - logger.debug(f"Already running {command_hash} {command}") + logger.debug(f"Already running {command_hash} {command_string}") await ALREADY_RUN[command_hash].wait() return ALREADY_RUN[command_hash] = asyncio.Event() @@ -169,7 +202,7 @@ async def run_command(command, working_directory, description=None, check_hash=[ run_reason = f"{p.relative_to(working_directory, walk_up=True)} is newer" break if nothing_newer: - logger.debug(f"Nothing newer {command[-32:]}") + logger.debug(f"Nothing newer {command_string[-32:]}") ALREADY_RUN[command_hash].set() return else: @@ -196,7 +229,7 @@ async def run_command(command, working_directory, description=None, check_hash=[ track = tracks.pop() start_time = time.perf_counter_ns() // 1000 process = await asyncio.create_subprocess_shell( - command, + command_string, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE, cwd=working_directory, @@ -242,22 +275,25 @@ async def run_command(command, working_directory, description=None, check_hash=[ raise cancellation if description: logger.info(f"{description} ({run_reason})") - logger.debug(command) + logger.debug(command_string) else: - logger.info(f"{command} ({run_reason})") + logger.info(f"{command_string} ({run_reason})") if old_newest_file == newest_file: logger.error("No files were modified by the command.") raise RuntimeError() else: if command_hash in LAST_BUILD_TIMES: del LAST_BUILD_TIMES[command_hash] + logger.error(command_string) + if responsefile_contents: + logger.error(f"Response file contents:\n{responsefile_contents}") + logger.error(f"Return code: {process.returncode}") if stdout: logger.info(stdout.decode("utf-8").strip()) if stderr: logger.warning(stderr.decode("utf-8").strip()) if not stdout and not stderr: logger.warning("No output") - logger.error(command) if cancellation: raise cancellation raise RuntimeError() @@ -335,8 +371,8 @@ async def preprocess( ): output_file.parent.mkdir(parents=True, exist_ok=True) depfile = output_file.parent / (output_file.name + ".d") - if depfile.exists(): - pass + responsefile = output_file.parent / (output_file.name + ".rsp") + await run_command( [ self.c_compiler, @@ -354,6 +390,7 @@ async def preprocess( description=f"Preprocess {source_file.relative_to(self.srcdir)} -> {output_file.relative_to(self.builddir)}", working_directory=self.srcdir, check_hash=[output_file], + responsefile=responsefile, ) async def compile( @@ -365,6 +402,7 @@ async def compile( output_file = self.builddir / output_file output_file.parent.mkdir(parents=True, exist_ok=True) depfile = output_file.with_suffix(".d") + responsefile = output_file.with_suffix(".rsp") extradeps = [] if depfile.exists(): depfile_contents = depfile.read_text().split() @@ -375,25 +413,35 @@ async def compile( extradeps.append(pathlib.Path(dep)) else: extradeps.append(self.srcdir / dep) + await run_command( - [self.c_compiler, self.cflags, "-MMD", "-c", source_file, *flags, "-o", output_file], + [ + self.c_compiler, + self.cflags, + "-MMD", + "-c", + source_file, + *flags, + "-o", + output_file, + ], description=f"Compile {source_file.relative_to(self.srcdir)} -> {output_file.relative_to(self.builddir)}", working_directory=self.srcdir, extradeps=extradeps, + responsefile=responsefile, ) async def archive(self, objects: list[pathlib.Path], output_file: pathlib.Path): output_file.parent.mkdir(parents=True, exist_ok=True) - # Do one file at a time so that we don't have a long command line. run_command - # should skip unchanged files ok. - input_files = output_file.with_suffix(output_file.suffix + ".input_files") - input_file_content = "\n".join(str(p) for p in objects) - # Windows paths have \ as separator but ar wants them as / (like UNIX) - input_file_content = input_file_content.replace("\\", "/") - input_files.write_text(input_file_content) + responsefile = output_file.with_suffix(".rsp") + # Always create the archive from scratch. `ar r` on an existing archive replaces the + # members named on its command line and keeps every other member, so after a build + # of another language the old translations-*.o and autogen_display_resources-*.o + # stayed in the archive ahead of the new ones and the linker used them. + output_file.unlink(missing_ok=True) await run_command( - [self.ar, "rvs", output_file, f"@{input_files}"], + [self.ar, "rcs", output_file, *objects], description=f"Create archive {output_file.relative_to(self.srcdir)}", working_directory=self.srcdir, - extradeps=objects, + responsefile=responsefile, ) diff --git a/ports/zephyr-cp/cptools/gen_compat2driver.py b/ports/zephyr-cp/cptools/gen_compat2driver.py index 0cb6a16f9da..ffe8da18596 100644 --- a/ports/zephyr-cp/cptools/gen_compat2driver.py +++ b/ports/zephyr-cp/cptools/gen_compat2driver.py @@ -2,8 +2,8 @@ mapping = {} -drivers = pathlib.Path("lib/zephyr/drivers") -for p in drivers.glob("**/*.c"): +drivers = pathlib.Path("zephyr/drivers") +for p in drivers.glob("**/*.[ch]"): for line in p.open(): if line.startswith("#define DT_DRV_COMPAT"): compat = line.rsplit(None, 1)[-1].strip() diff --git a/ports/zephyr-cp/cptools/get_west_shield_args.py b/ports/zephyr-cp/cptools/get_west_shield_args.py new file mode 100644 index 00000000000..deda6bf5f26 --- /dev/null +++ b/ports/zephyr-cp/cptools/get_west_shield_args.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Resolve shield arguments for west build. + +Priority: +1. SHIELD / SHIELDS make variables (if explicitly provided) +2. SHIELD / SHIELDS from boards///circuitpython.toml +""" + +import argparse +import os +import pathlib +import re +import shlex + +import board_tools + + +def split_shields(raw): + if not raw: + return [] + + return [shield for shield in re.split(r"[,;\s]+", raw.strip()) if shield] + + +def dedupe(values): + deduped = [] + seen = set() + + for value in values: + if value in seen: + continue + seen.add(value) + deduped.append(value) + + return deduped + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("board") + args = parser.parse_args() + + portdir = pathlib.Path(__file__).resolve().parent.parent + + _, mpconfigboard = board_tools.load_mpconfigboard(portdir, args.board) + + shield_origin = os.environ.get("SHIELD_ORIGIN", "undefined") + shields_origin = os.environ.get("SHIELDS_ORIGIN", "undefined") + + shield_override = os.environ.get("SHIELD", "") + shields_override = os.environ.get("SHIELDS", "") + + override_requested = shield_origin != "undefined" or shields_origin != "undefined" + + if override_requested: + shields = split_shields(shield_override) + split_shields(shields_override) + else: + shields = board_tools.get_shields(mpconfigboard) + + shields = dedupe(shields) + + west_shield_args = [] + for shield in shields: + west_shield_args.extend(("--shield", shield)) + + print(shlex.join(west_shield_args)) + + +if __name__ == "__main__": + main() diff --git a/ports/zephyr-cp/cptools/pre_zephyr_build_prep.py b/ports/zephyr-cp/cptools/pre_zephyr_build_prep.py index 0ed280cbc67..f42fc1a3a85 100644 --- a/ports/zephyr-cp/cptools/pre_zephyr_build_prep.py +++ b/ports/zephyr-cp/cptools/pre_zephyr_build_prep.py @@ -2,7 +2,6 @@ import pathlib import subprocess import sys -import tomllib import board_tools @@ -10,14 +9,20 @@ board = sys.argv[-1] -mpconfigboard = board_tools.find_mpconfigboard(portdir, board) -if mpconfigboard is None: +_, mpconfigboard = board_tools.load_mpconfigboard(portdir, board) +if not mpconfigboard: # Assume it doesn't need any prep. sys.exit(0) -with mpconfigboard.open("rb") as f: - mpconfigboard = tomllib.load(f) - blobs = mpconfigboard.get("BLOBS", []) +blob_fetch_args = mpconfigboard.get("blob_fetch_args", {}) for blob in blobs: - subprocess.run(["west", "blobs", "fetch", blob], check=True) + args = blob_fetch_args.get(blob, []) + subprocess.run(["west", "blobs", "fetch", blob, *args], check=True) + +if board.endswith("bsim"): + subprocess.run( + ["make", "everything", "-j", "8"], + cwd=portdir / "tools" / "bsim", + check=True, + ) diff --git a/ports/zephyr-cp/cptools/run_tests_native_sim.py b/ports/zephyr-cp/cptools/run_tests_native_sim.py new file mode 100755 index 00000000000..5992d9bb7ff --- /dev/null +++ b/ports/zephyr-cp/cptools/run_tests_native_sim.py @@ -0,0 +1,177 @@ +#!/usr/bin/env python3 +# SPDX-FileCopyrightText: 2026 Vladimír Smitka +# SPDX-License-Identifier: MIT + +"""Run the core test suite (tests/run-tests.py) on the native_sim build. + +Each simulator gets a flash image that already holds what the tests import +from the device: tests/testlib and micropython-lib's unittest, in /lib. +run-tests.py runs one test at a time on a device, so the tests are split +over several simulators (-j) and the results are merged afterwards. When a +test takes the simulator down, it is counted as failed and run-tests.py is +started again with the rest of the tests. +""" + +import argparse +import collections +import concurrent.futures +import glob +import os +import pathlib +import re +import shutil +import subprocess +import sys +import time + +ZEPHYR_CP = pathlib.Path(__file__).resolve().parent.parent +TOP = ZEPHYR_CP.parent.parent +TESTS = TOP / "tests" +UNITTEST = TOP / "lib/micropython-lib/python-stdlib/unittest/unittest/__init__.py" +FLASH_SIZE = 2 * 1024 * 1024 +# The other directories still have tests that fail on the simulator. +DEFAULT_DIRS = ("basics", "float", "misc", "unicode") +RESULT_LINE = re.compile(r"^(pass|FAIL|skip|lrge) +(\S+)") +RESULTS = {"pass": "pass", "FAIL": "fail", "skip": "skip", "lrge": "skip"} + + +def make_flash_image(path): + path.write_bytes(b"\xff" * FLASH_SIZE) + subprocess.run(["mformat", "-i", path, "::"], check=True) + subprocess.run(["mmd", "-i", path, "::lib", "::lib/unittest"], check=True) + testlib = sorted(f for f in (TESTS / "testlib").iterdir() if f.is_file()) + subprocess.run(["mcopy", "-i", path, *testlib, "::lib/"], check=True) + subprocess.run(["mcopy", "-i", path, UNITTEST, "::lib/unittest/"], check=True) + + +def run_shard(exe, flash, shard, tests, env): + """Run tests on one simulator, restarting it after a crash. + + Returns {test: result} and an error message if run-tests.py could not run at all.""" + shard.mkdir() + shutil.copy(flash, shard / "flash.bin") + sim = f"{exe} --flash={shard / 'flash.bin'} -no-rt -wait_uart -display_headless -i2s_earless" + cmd = [sys.executable, "run-tests.py", "-t", "execpty:" + sim, "-r", str(shard)] + results = {} + attempt = 0 + while True: + remaining = [test for test in tests if test not in results] + if not remaining: + return results, None + log_file = shard / f"run-tests-{attempt}.log" + with open(log_file, "w") as log: + proc = subprocess.run( + cmd + remaining, cwd=TESTS, env=env, stdout=log, stderr=subprocess.STDOUT + ) + log = log_file.read_text() + if proc.returncode < 0: + # Killed by a signal, for example Ctrl-C. + return results, f"run-tests.py was stopped by signal {-proc.returncode}" + if "platform=" not in log: + return results, f"run-tests.py did not start, see {log_file}:\n{log[-2000:]}" + for line in log.splitlines(): + m = RESULT_LINE.match(line) + if m: + results[m.group(2)] = RESULTS[m.group(1)] + # run-tests.py stopped early, most likely because the test after the + # last one it reported took the simulator down. + crashed = next((test for test in remaining if test not in results), None) + if crashed is not None: + results[crashed] = "fail" + out = shard / (crashed.replace("/", "_") + ".out") + out.write_text(f"run-tests.py stopped during this test, see {log_file}\n") + attempt += 1 + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--build", + default=ZEPHYR_CP / "build-native_native_sim", + type=pathlib.Path, + help="native_sim build directory (default: %(default)s)", + ) + parser.add_argument( + "-j", + "--jobs", + # A simulator without -rt keeps a CPU busy even while it waits for input. + default=max(1, (os.cpu_count() or 2) // 2), + type=int, + help="number of simulators to run at once (default: %(default)s)", + ) + parser.add_argument( + "-d", + "--test-dirs", + nargs="*", + help="test directories, relative to tests/ (default: %s)" % " ".join(DEFAULT_DIRS), + ) + parser.add_argument("files", nargs="*", help="test files, relative to tests/") + args = parser.parse_args() + + exe = args.build.resolve() / "zephyr-cp/zephyr/zephyr.exe" + if not exe.exists(): + sys.exit(f"{exe} not found, build it with: make BOARD=native_native_sim") + if not UNITTEST.exists(): + sys.exit(f"{UNITTEST} not found, run: git submodule update --init lib/micropython-lib") + + tests = list(args.files) + for test_dir in args.test_dirs or ([] if tests else DEFAULT_DIRS): + tests += sorted( + os.path.relpath(f, TESTS) for f in glob.glob(str(TESTS / test_dir / "*.py")) + ) + if not tests: + sys.exit("no tests found") + + work = args.build.resolve() / "run-tests" + # run-tests.py splits the execpty command on whitespace. + if any(c.isspace() for c in str(work) + str(exe)): + sys.exit(f"paths must not contain whitespace: {work}") + shutil.rmtree(work, ignore_errors=True) + results_dir = work / "results" + results_dir.mkdir(parents=True) + flash = work / "flash.bin" + make_flash_image(flash) + + env = dict(os.environ) + env.setdefault("SDL_VIDEODRIVER", "dummy") + jobs = max(1, min(args.jobs, len(tests))) + start = time.monotonic() + with concurrent.futures.ThreadPoolExecutor(jobs) as pool: + futures = [ + pool.submit(run_shard, exe, flash, work / f"shard{i}", tests[i::jobs], env) + for i in range(jobs) + ] + elapsed = time.monotonic() - start + + results = {} + errors = [] + for i, future in enumerate(futures): + shard_results, error = future.result() + results.update(shard_results) + if error: + errors.append(error) + for out in glob.glob(str(work / f"shard{i}" / "*.exp")) + glob.glob( + str(work / f"shard{i}" / "*.out") + ): + shutil.move(out, results_dir) + + counts = collections.defaultdict(collections.Counter) + for test, result in results.items(): + counts[os.path.dirname(test)][result] += 1 + print(f"{'directory':<20} {'pass':>6} {'fail':>6} {'skip':>6}") + for test_dir, count in sorted(counts.items()): + print(f"{test_dir:<20} {count['pass']:>6} {count['fail']:>6} {count['skip']:>6}") + print(f"{len(results)} of {len(tests)} tests run in {elapsed:.0f} s on {jobs} simulators") + + failed = sorted(test for test, result in results.items() if result == "fail") + if failed: + print(f"{len(failed)} tests failed: {' '.join(failed)}") + print(f"Show the diffs with: tests/run-tests.py --print-failures -r {results_dir}") + for error in errors: + print(error) + if failed or errors: + sys.exit(1) + + +if __name__ == "__main__": + main() diff --git a/ports/zephyr-cp/cptools/tests/README.md b/ports/zephyr-cp/cptools/tests/README.md new file mode 100644 index 00000000000..6bc8aa43ce6 --- /dev/null +++ b/ports/zephyr-cp/cptools/tests/README.md @@ -0,0 +1,28 @@ +# Zephyr2CP Tests + +This directory contains unit tests for the `zephyr2cp.py` module using real device tree parsing and pytest. + +## Running Tests + +To run all tests: +```bash +cd /home/tannewt/repos/circuitpython/ports/zephyr-cp +make test +``` + +For verbose output: +```bash +pytest test_zephyr2cp.py -v +``` + +To run specific test classes: +```bash +pytest test_zephyr2cp.py::TestFindFlashDevices -v +pytest test_zephyr2cp.py::TestFindRAMRegions -v +pytest test_zephyr2cp.py::TestIntegration -v +``` + +To run a specific test: +```bash +pytest test_zephyr2cp.py::TestFindFlashDevices::test_valid_flash_device -v +``` diff --git a/ports/zephyr-cp/cptools/tests/test_check_partitions.py b/ports/zephyr-cp/cptools/tests/test_check_partitions.py new file mode 100644 index 00000000000..c6754c6930c --- /dev/null +++ b/ports/zephyr-cp/cptools/tests/test_check_partitions.py @@ -0,0 +1,570 @@ +"""Unit tests for cptools/check_partitions.py using real device tree parsing. + +Each case here is a layout that actually occurs in this port, so the checks are +exercised against devicetree as edtlib resolves it rather than against +hand-built stand-ins. +""" + +import pathlib +import sys +import tempfile + +import pytest + +portdir = pathlib.Path(__file__).parent.parent.parent +sys.path.append(str(portdir / "zephyr/scripts/dts/python-devicetree/src/")) + +from devicetree import edtlib # noqa: E402 + +sys.path.insert(0, str(pathlib.Path(__file__).parent.parent)) + +from check_partitions import ( # noqa: E402 + check_layout, + check_parity, + device_size, + evaluate, + iter_partitions, + read_defines, + reference_layout, +) + +BINDINGS = [str(portdir / "zephyr/dts/bindings")] + + +def parse_dts_string(dts_content): + """Parse device tree source and return the resolved edtlib.EDT.""" + with tempfile.NamedTemporaryFile(mode="w", suffix=".dts", delete=False) as f: + f.write(dts_content) + f.flush() + temp_path = f.name + + try: + return edtlib.EDT(temp_path, BINDINGS) + finally: + pathlib.Path(temp_path).unlink() + + +def xip_flash(partitions, ranges="ranges;", size="0x200000"): + """A memory-mapped flash at 0x10000000, the RP2040 arrangement. + + ``ranges`` is what the overlays get wrong: the board DTS declares it on the + partitions node, and an overlay that deletes and rebuilds that node without + it leaves every partition untranslated. + """ + return f"""/dts-v1/; + +/ {{ + #address-cells = <1>; + #size-cells = <1>; + + soc {{ + #address-cells = <1>; + #size-cells = <1>; + ranges; + + flash0: flash@10000000 {{ + compatible = "soc-nv-flash"; + erase-block-size = <4096>; + reg = <0x10000000 {size}>; + ranges = <0x0 0x10000000 {size}>; + #address-cells = <1>; + #size-cells = <1>; + + partitions {{ + {ranges} + #address-cells = <1>; + #size-cells = <1>; +{partitions} + }}; + }}; + }}; +}}; +""" + + +MAPPED_PARTS = """ + code_partition: partition@100 { + compatible = "zephyr,mapped-partition"; + label = "code-partition"; + reg = <0x100 0x17ff00>; + }; + + circuitpy_partition: partition@180000 { + compatible = "zephyr,mapped-partition"; + label = "circuitpy"; + reg = <0x180000 0x80000>; + }; +""" + + +class TestAddressTranslation: + """The partitions node must keep translating addresses to the SoC's space.""" + + def test_missing_ranges_is_reported(self): + """This is the bug the checker exists for: without ranges; on the + rebuilt partitions node the partitions resolve to bare offsets.""" + edt = parse_dts_string(xip_flash(MAPPED_PARTS, ranges="")) + problems = check_layout(edt) + + assert len(problems) == 2 + assert any("code_partition" in p and "0x100" in p for p in problems) + assert all("ranges" in p for p in problems) + + def test_ranges_present_passes(self): + """The same layout with ranges; must be clean, or the check would only + ever be able to fail.""" + edt = parse_dts_string(xip_flash(MAPPED_PARTS)) + + assert check_layout(edt) == [] + + def test_absolute_addresses_pass(self): + """Some overlays write the absolute address into reg and leave the + partitions node without ranges. That resolves to the same correct + address, so it must not be reported.""" + parts = """ + code_partition: partition@10000100 { + compatible = "zephyr,mapped-partition"; + label = "code-partition"; + reg = <0x10000100 0x17ff00>; + }; +""" + edt = parse_dts_string(xip_flash(parts, ranges="")) + + assert check_layout(edt) == [] + + def test_flash_based_at_zero_passes(self): + """On a device based at 0 -- the nRF arrangement -- the translated and + the bare value coincide, so nothing is wrong either way.""" + dts = """/dts-v1/; + +/ { + #address-cells = <1>; + #size-cells = <1>; + + soc { + #address-cells = <1>; + #size-cells = <1>; + ranges; + + flash0: flash@0 { + compatible = "soc-nv-flash"; + erase-block-size = <4096>; + reg = <0x0 0x100000>; + ranges = <0x0 0x0 0x100000>; + #address-cells = <1>; + #size-cells = <1>; + + partitions { + #address-cells = <1>; + #size-cells = <1>; + + slot0_partition: partition@10000 { + compatible = "zephyr,mapped-partition"; + label = "image-0"; + reg = <0x10000 0x10000>; + }; + }; + }; + }; +}; +""" + edt = parse_dts_string(dts) + + assert check_layout(edt) == [] + + +class TestPartitionDiscovery: + """What counts as a partition is decided by position, not by compatible.""" + + def test_partition_without_compatible_is_seen(self): + """An overlay may add a partition carrying no compatible at all. It + still occupies the space, and treating it as absent would report a + board that has a filesystem as having none.""" + parts = """ + storage_partition: partition@180000 { + label = "storage"; + reg = <0x180000 0x1000>; + }; + + circuitpy_partition: partition@181000 { + label = "circuitpy"; + reg = <0x181000 0x7f000>; + }; +""" + edt = parse_dts_string(xip_flash(parts)) + labels = [node.labels[0] for node, _dev, _off, _size, _mapped in iter_partitions(edt)] + + assert "storage_partition" in labels + assert "circuitpy_partition" in labels + + +class TestDeviceSize: + """Bus-attached flash keeps its capacity in size, not in reg.""" + + def test_size_property_wins_over_chip_select(self): + """An SPI NOR's reg is a chip select. Reading a size out of it gives 0, + which would silently skip every check on the device CIRCUITPY usually + lives on.""" + dts = """/dts-v1/; + +/ { + #address-cells = <1>; + #size-cells = <1>; + + soc { + #address-cells = <1>; + #size-cells = <1>; + ranges; + + spi@0 { + compatible = "vnd,spi"; + reg = <0x0 0x100>; + #address-cells = <1>; + #size-cells = <0>; + status = "okay"; + + mx25r64: mx25r6435f@0 { + compatible = "jedec,spi-nor"; + reg = <0>; + size = <67108864>; + spi-max-frequency = <8000000>; + jedec-id = [c2 28 17]; + }; + }; + }; +}; +""" + edt = parse_dts_string(dts) + node = edt.get_node("/soc/spi@0/mx25r6435f@0") + + assert device_size(node) == 8 * 1024 * 1024 + + +class TestGeometry: + """Partitions must not overlap or leave their device.""" + + def test_partition_spanning_several_others_is_reported(self): + """Comparing neighbouring pairs only would catch the first overlap and + miss the rest, so a partition covering three others must report more + than once.""" + parts = """ + slot0_partition: partition@0 { + compatible = "zephyr,mapped-partition"; + label = "image-0"; + reg = <0x0 0x30000>; + }; + + nvm_partition: partition@10000 { + compatible = "zephyr,mapped-partition"; + label = "nvm"; + reg = <0x10000 0x1000>; + }; + + storage_partition: partition@20000 { + compatible = "zephyr,mapped-partition"; + label = "storage"; + reg = <0x20000 0x1000>; + }; +""" + edt = parse_dts_string(xip_flash(parts)) + problems = [p for p in check_layout(edt) if "overlaps" in p] + + assert len(problems) == 2 + + def test_partition_past_end_of_device_is_reported(self): + """A partition may not run past the flash it lives in.""" + parts = """ + circuitpy_partition: partition@1f0000 { + compatible = "zephyr,mapped-partition"; + label = "circuitpy"; + reg = <0x1f0000 0x20000>; + }; +""" + edt = parse_dts_string(xip_flash(parts)) + + assert any("past the end" in p for p in check_layout(edt)) + + +class TestEmptyLayout: + """A board whose overlay defines nothing must not look verified.""" + + def test_no_partitions_yields_nothing_checked(self): + """check_layout has nothing to complain about here, which is why the + caller reports how many partitions it inspected: an empty layout and a + good one are otherwise indistinguishable.""" + edt = parse_dts_string(xip_flash("")) + + assert check_layout(edt) == [] + assert list(iter_partitions(edt)) == [] + + +if __name__ == "__main__": + sys.exit(pytest.main([__file__])) + + +class TestParity: + """Agreement with the non-Zephyr build of the same board. + + The reference values are what ports/raspberrypi/mpconfigport.h and + ports/nordic/mpconfigport.h derive for these boards; the tests read the real + board files so a change there is caught here. + """ + + def test_evaluate_follows_references(self): + defines = {"A": "(2 * B)", "B": "(512 * 1024)", "C": "A + UNKNOWN"} + assert evaluate(defines, "A") == 1024 * 1024 + assert evaluate(defines, "B") == 512 * 1024 + assert evaluate(defines, "C") is None + assert evaluate(defines, "MISSING", 7) == 7 + + def test_read_defines_precedence(self, tmp_path): + mk = tmp_path / "mpconfigboard.mk" + mk.write_text( + "CFLAGS += -DCIRCUITPY_FIRMWARE_SIZE='(1536 * 1024)'\nQSPI_FLASH_FILESYSTEM = 1\n" + ) + header = tmp_path / "mpconfigport.h" + header.write_text( + "#ifndef CIRCUITPY_FIRMWARE_SIZE\n#define CIRCUITPY_FIRMWARE_SIZE (1020 * 1024)\n#endif\n" + ) + defines = read_defines([mk, header]) + assert evaluate(defines, "CIRCUITPY_FIRMWARE_SIZE") == 1536 * 1024 + assert defines["QSPI_FLASH_FILESYSTEM"] == "1" + + def test_raspberrypi_default_firmware_size(self): + layout = reference_layout("raspberrypi/raspberry_pi_pico", 0x200000) + assert layout["nvm"] == (0xFF000, 0x1000) + assert layout["circuitpy"] == (0x100000, 0x100000) + + def test_raspberrypi_board_firmware_size(self): + layout = reference_layout("raspberrypi/raspberry_pi_pico_w", 0x200000) + assert layout["nvm"] == (0x180000, 0x1000) + assert layout["circuitpy"] == (0x181000, 0x7F000) + + def test_nordic_external_drive(self): + layout = reference_layout("nordic/feather_nrf52840_express", 0x100000) + assert layout["nvm"] == (0xF2000, 0x2000) + assert layout["circuitpy"] == "external" + + def test_unknown_port_and_board_rejected(self): + with pytest.raises(ValueError): + reference_layout("espressif/adafruit_feather_esp32s3", 0x400000) + with pytest.raises(ValueError): + reference_layout("raspberrypi/no_such_board", 0x200000) + + def rp2040_layout(self, nvm_offset): + return xip_flash( + f""" + code_partition: partition@100 {{ + compatible = "zephyr,mapped-partition"; + reg = <0x100 0xfdf00>; + }}; + nvm_partition: partition@{nvm_offset:x} {{ + compatible = "zephyr,mapped-partition"; + label = "nvm"; + reg = <0x{nvm_offset:x} 0x1000>; + }}; + circuitpy_partition: partition@100000 {{ + compatible = "zephyr,mapped-partition"; + label = "circuitpy"; + reg = <0x100000 0x100000>; + }}; + """ + ) + + def test_parity_matches(self): + edt = parse_dts_string(self.rp2040_layout(0xFF000)) + assert check_parity(edt, "raspberrypi/raspberry_pi_pico") == [] + + def test_parity_reports_moved_nvm(self): + edt = parse_dts_string(self.rp2040_layout(0xFE000)) + problems = check_parity(edt, "raspberrypi/raspberry_pi_pico") + assert len(problems) == 1 + assert "nvm_partition" in problems[0] + assert "0xfe000" in problems[0] and "0xff000" in problems[0] + + def test_parity_reports_missing_partition(self): + edt = parse_dts_string( + xip_flash( + """ + code_partition: partition@100 { + compatible = "zephyr,mapped-partition"; + reg = <0x100 0xfdf00>; + }; + """ + ) + ) + problems = check_parity(edt, "raspberrypi/raspberry_pi_pico") + assert any(p.startswith("nvm_partition: missing") for p in problems) + assert any(p.startswith("circuitpy_partition: missing") for p in problems) + + # The Adaboot fork's dtsi names the filesystem partition by its backing + # store (fatfs_partition for native-USB drives, littlefs_partition for + # boards without USB); the older CircuitPython port layout named it + # circuitpy_partition. supervisor/flash.c accepts all three via + # FIXED_PARTITION_EXISTS, so check_parity must too. + + def test_parity_accepts_fatfs_partition_in_place_of_circuitpy(self): + edt = parse_dts_string(self.rp2040_layout_with_fs_label(0xFF000, "fatfs_partition")) + assert check_parity(edt, "raspberrypi/raspberry_pi_pico") == [] + + def test_parity_accepts_littlefs_partition_in_place_of_circuitpy(self): + edt = parse_dts_string(self.rp2040_layout_with_fs_label(0xFF000, "littlefs_partition")) + assert check_parity(edt, "raspberrypi/raspberry_pi_pico") == [] + + def rp2040_layout_with_fs_label(self, nvm_offset, fs_label): + return xip_flash( + f""" + code_partition: partition@100 {{ + compatible = "zephyr,mapped-partition"; + reg = <0x100 0xfdf00>; + }}; + nvm_partition: partition@{nvm_offset:x} {{ + compatible = "zephyr,mapped-partition"; + label = "nvm"; + reg = <0x{nvm_offset:x} 0x1000>; + }}; + {fs_label}: partition@100000 {{ + compatible = "zephyr,mapped-partition"; + label = "filesystem"; + reg = <0x100000 0x100000>; + }}; + """ + ) + + def nordic_with_external_drive(self, gd25_partitions): + """Internal flash + an SPI NOR gd25q16 partition layout for the nRF52 + boards. Counterpart is nordic/feather_nrf52840_express, which uses + QSPI_FLASH_FILESYSTEM=1 (the whole chip is the drive).""" + return f"""/dts-v1/; + +/ {{ + #address-cells = <1>; + #size-cells = <1>; + + soc {{ + #address-cells = <1>; + #size-cells = <1>; + ranges; + + flash0: flash@0 {{ + compatible = "soc-nv-flash"; + erase-block-size = <4096>; + reg = <0x0 0x100000>; + ranges = <0x0 0x0 0x100000>; + #address-cells = <1>; + #size-cells = <1>; + + partitions {{ + ranges; + #address-cells = <1>; + #size-cells = <1>; + + code_partition: partition@26000 {{ + compatible = "zephyr,mapped-partition"; + label = "code-partition"; + reg = <0x26000 0xc4000>; + }}; + storage_partition: partition@ea000 {{ + compatible = "zephyr,mapped-partition"; + label = "storage"; + reg = <0xea000 0x8000>; + }}; + nvm_partition: partition@f2000 {{ + compatible = "zephyr,mapped-partition"; + label = "nvm"; + reg = <0xf2000 0x2000>; + }}; + }}; + }}; + + qspi {{ + compatible = "vnd,spi"; + reg = <0x0 0x100>; + #address-cells = <1>; + #size-cells = <0>; + status = "okay"; + + gd25q16: gd25q16@0 {{ + compatible = "jedec,spi-nor"; + reg = <0>; + size = <2097152>; + spi-max-frequency = <8000000>; + jedec-id = [c8 40 15]; + + partitions {{ + compatible = "fixed-partitions"; + #address-cells = <1>; + #size-cells = <1>; +{gd25_partitions} + }}; + }}; + }}; + }}; +}}; +""" + + def test_parity_accepts_explicit_whole_chip_fatfs_partition(self): + """A single fatfs_partition covering the entire external flash chip is + equivalent to the nordic-port QSPI_FLASH_FILESYSTEM=1 dynamic-area + fallback -- both pin the drive to the whole 2 MB chip -- so the parity + check must accept it.""" + edt = parse_dts_string( + self.nordic_with_external_drive( + """ + fatfs_partition: partition@0 { + label = "filesystem"; + reg = <0x0 0x200000>; + }; + """ + ) + ) + assert check_parity(edt, "nordic/feather_nrf52840_express") == [] + + def test_parity_accepts_explicit_whole_chip_littlefs_partition(self): + edt = parse_dts_string( + self.nordic_with_external_drive( + """ + littlefs_partition: partition@0 { + label = "filesystem"; + reg = <0x0 0x200000>; + }; + """ + ) + ) + assert check_parity(edt, "nordic/feather_nrf52840_express") == [] + + def test_parity_rejects_offset_external_partition(self): + """A partition starting above offset 0 on the external chip breaks the + dynamic-area fallback, so it must be reported even though it is the + only partition on the chip.""" + edt = parse_dts_string( + self.nordic_with_external_drive( + """ + fatfs_partition: partition@1000 { + label = "filesystem"; + reg = <0x1000 0x1ff000>; + }; + """ + ) + ) + problems = check_parity(edt, "nordic/feather_nrf52840_express") + assert any("gd25q16" in p for p in problems) + + def test_parity_rejects_extra_external_partitions(self): + """More than one partition on the external chip would also leave the + dynamic-area fallback unable to claim it; report it.""" + edt = parse_dts_string( + self.nordic_with_external_drive( + """ + fatfs_partition: partition@0 { + label = "filesystem"; + reg = <0x0 0x100000>; + }; + other_partition: partition@100000 { + reg = <0x100000 0x100000>; + }; + """ + ) + ) + problems = check_parity(edt, "nordic/feather_nrf52840_express") + assert any("gd25q16" in p for p in problems) diff --git a/ports/zephyr-cp/cptools/tests/test_zephyr2cp.py b/ports/zephyr-cp/cptools/tests/test_zephyr2cp.py new file mode 100644 index 00000000000..1099ea461bd --- /dev/null +++ b/ports/zephyr-cp/cptools/tests/test_zephyr2cp.py @@ -0,0 +1,1012 @@ +import sys +import pathlib +import tempfile +from types import SimpleNamespace + +# Add devicetree library to path +portdir = pathlib.Path(__file__).parent.parent.parent +sys.path.append(str(portdir / "zephyr/scripts/dts/python-devicetree/src/")) + +from devicetree import dtlib + +# Add parent directory to path to import zephyr2cp +sys.path.insert(0, str(pathlib.Path(__file__).parent.parent)) + +# Mock cpbuild before importing +sys.modules["cpbuild"] = type(sys)("cpbuild") +sys.modules["cpbuild"].run_in_thread = lambda x: x + +import pytest + +from zephyr2cp import ( + find_flash_devices, + find_ram_regions, + BLOCKED_FLASH_COMPAT, + MINIMUM_RAM_SIZE, + STEMMA_I2C_PINS, + add_toml_pin_names, + _board_i2c_buses, + _fastest_first, + _named_pins, + _standard_bus_pins, + _toml_status_dotstar, + _toml_status_pin, + _used_by_zephyr, +) + + +def parse_dts_string(dts_content): + """ + Parse a device tree string and return the dtlib.DT object. + + Args: + dts_content: String containing device tree source + + Returns: + dtlib.DT object with parsed device tree + """ + with tempfile.NamedTemporaryFile(mode="w", suffix=".dts", delete=False) as f: + f.write(dts_content) + f.flush() + temp_path = f.name + + try: + dt = dtlib.DT(temp_path) + return dt + finally: + pathlib.Path(temp_path).unlink() + + +class TestFindFlashDevices: + """Test suite for find_flash_devices function.""" + + def test_no_compatible_returns_empty(self): + """Test that device tree with no flash devices returns empty list.""" + dts = """ +/dts-v1/; + +/ { + #address-cells = <1>; + #size-cells = <1>; + + memory@0 { + reg = <0x0 0x100000>; + }; + + chosen { + }; +}; +""" + dt = parse_dts_string(dts) + result = find_flash_devices(dt) + assert result == [] + + def test_chosen_flash_excluded(self): + """Test that chosen flash nodes are excluded.""" + dts = """ +/dts-v1/; + +/ { + #address-cells = <1>; + #size-cells = <1>; + + flash0: flash@0 { + compatible = "soc-nv-flash"; + reg = <0x0 0x100000>; + }; + + chosen { + zephyr,flash = &flash0; + }; +}; +""" + dt = parse_dts_string(dts) + result = find_flash_devices(dt) + assert result == [], "Chosen flash should be excluded" + + def test_blocked_compat_excluded(self): + """Test that blocked compatible strings are excluded.""" + dts = """ +/dts-v1/; + +/ { + #address-cells = <1>; + #size-cells = <1>; + + qspi0: qspi@40000 { + compatible = "renesas,ra-qspi"; + reg = <0x40000 0x1000>; + }; + + spi0: spi@50000 { + compatible = "nordic,nrf-spim"; + reg = <0x50000 0x1000>; + }; + + chosen { + }; +}; +""" + dt = parse_dts_string(dts) + result = find_flash_devices(dt) + assert result == [], "Blocked flash controllers should be excluded" + + def test_valid_flash_device(self): + """Test that valid flash device is detected.""" + dts = """ +/dts-v1/; + +/ { + #address-cells = <1>; + #size-cells = <1>; + + flash0: flash@0 { + compatible = "jedec,spi-nor"; + reg = <0x0 0x100000>; + }; + + chosen { + }; +}; +""" + dt = parse_dts_string(dts) + result = find_flash_devices(dt) + assert len(result) == 1 + assert result[0] == "flash0" + + def test_valid_flash_device_multiple_drivers(self): + """Test that valid flash device is detected.""" + dts = """ +/dts-v1/; + +/ { + #address-cells = <1>; + #size-cells = <1>; + + flash0: flash@0 { + compatible = "other,driver", "jedec,spi-nor"; + reg = <0x0 0x100000>; + }; + + chosen { + }; +}; +""" + dt = parse_dts_string(dts) + result = find_flash_devices(dt) + assert len(result) == 1 + assert result[0] == "flash0" + + def test_external_flash_not_chosen(self): + """Test external flash is included when internal is chosen.""" + dts = """ +/dts-v1/; + +/ { + #address-cells = <1>; + #size-cells = <1>; + + internal_flash: flash@0 { + compatible = "soc-nv-flash"; + reg = <0x0 0x100000>; + }; + + external_flash: flash@1000000 { + compatible = "jedec,spi-nor"; + reg = <0x1000000 0x800000>; + }; + + chosen { + zephyr,flash = &internal_flash; + }; +}; +""" + dt = parse_dts_string(dts) + result = find_flash_devices(dt) + + # Should only include external flash, not chosen internal flash + assert len(result) == 1 + assert "external_flash" in result[0] + assert "internal_flash" not in result[0] + + def test_disabled_flash_excluded(self): + """Test that disabled flash devices are excluded.""" + dts = """ +/dts-v1/; + +/ { + #address-cells = <1>; + #size-cells = <1>; + + flash0: flash@0 { + compatible = "jedec,spi-nor"; + reg = <0x0 0x100000>; + status = "disabled"; + }; + + chosen { + }; +}; +""" + dt = parse_dts_string(dts) + result = find_flash_devices(dt) + assert result == [], "Disabled flash should be excluded" + + +class TestFindRAMRegions: + """Test suite for find_ram_regions function.""" + + def test_no_ram_returns_empty(self): + """Test that device tree with no RAM returns empty list.""" + dts = """ +/dts-v1/; + +/ { + #address-cells = <1>; + #size-cells = <1>; + + flash@0 { + compatible = "soc-nv-flash"; + reg = <0x0 0x100000>; + }; + + chosen { + }; +}; +""" + dt = parse_dts_string(dts) + result = find_ram_regions(dt) + assert result == [] + + def test_chosen_sram_basic(self): + """Test chosen sram region is detected correctly.""" + dts = """ +/dts-v1/; + +/ { + #address-cells = <1>; + #size-cells = <1>; + + sram0: memory@20000000 { + compatible = "mmio-sram"; + reg = <0x20000000 0x40000>; + }; + + chosen { + zephyr,sram = &sram0; + }; +}; +""" + dt = parse_dts_string(dts) + result = find_ram_regions(dt) + + assert len(result) == 1 + label, start, end, size, path = result[0] + + assert label == "sram0" + assert start == "z_mapped_end" + assert ( + end + == "(uint32_t*) (DT_REG_ADDR(DT_NODELABEL(sram0)) + DT_REG_SIZE(DT_NODELABEL(sram0)))" + ) + assert size == 0x40000 + + def test_memory_region_with_custom_name(self): + """Test memory region with zephyr,memory-region property.""" + dts = """ +/dts-v1/; + +/ { + #address-cells = <1>; + #size-cells = <1>; + + sram0: memory@20000000 { + compatible = "mmio-sram"; + reg = <0x20000000 0x40000>; + }; + + reserved_mem: memory@30000000 { + compatible = "zephyr,memory-region", "mmio-sram"; + reg = <0x30000000 0x10000>; + zephyr,memory-region = "CUSTOM_REGION"; + }; + + chosen { + zephyr,sram = &sram0; + }; +}; +""" + dt = parse_dts_string(dts) + result = find_ram_regions(dt) + + # Should have both regions, chosen first + assert len(result) == 2 + + # First should be chosen SRAM + assert result[0][0] == "sram0" + + # Second should be custom region + label, start, end, size, path = result[1] + assert label == "reserved_mem" + assert start == "__CUSTOM_REGION_end" + + def test_memory_region_requires_sram_or_device_type(self): + """Test memory regions require mmio-sram compatibility or device_type=memory.""" + dts = """ +/dts-v1/; + +/ { + #address-cells = <1>; + #size-cells = <1>; + + sram0: memory@20000000 { + compatible = "mmio-sram"; + reg = <0x20000000 0x40000>; + }; + + reserved_mem: memory@30000000 { + compatible = "zephyr,memory-region"; + reg = <0x30000000 0x10000>; + zephyr,memory-region = "CUSTOM_REGION"; + }; + + external_mem: memory@40000000 { + compatible = "zephyr,memory-region"; + device_type = "memory"; + reg = <0x40000000 0x20000>; + zephyr,memory-region = "EXT_REGION"; + }; + + chosen { + zephyr,sram = &sram0; + }; +}; +""" + dt = parse_dts_string(dts) + result = find_ram_regions(dt) + + assert len(result) == 2 + assert result[0][0] == "sram0" + assert result[1][0] == "external_mem" + + def test_disabled_ram_excluded(self): + """Test that disabled RAM regions are excluded.""" + dts = """ +/dts-v1/; + +/ { + #address-cells = <1>; + #size-cells = <1>; + + sram0: memory@20000000 { + compatible = "mmio-sram"; + reg = <0x20000000 0x40000>; + }; + + sram1: memory@30000000 { + compatible = "zephyr,memory-region", "mmio-sram"; + reg = <0x30000000 0x10000>; + status = "disabled"; + zephyr,memory-region = "CUSTOM_REGION"; + }; + + chosen { + zephyr,sram = &sram0; + }; +}; +""" + dt = parse_dts_string(dts) + result = find_ram_regions(dt) + + # Should only have chosen SRAM, not disabled one + assert len(result) == 1 + assert result[0][0] == "sram0" + + +class TestIntegration: + """Integration tests with realistic device tree configurations.""" + + def test_typical_nrf_board_configuration(self): + """Test typical Nordic nRF board with internal and external flash.""" + dts = """ +/dts-v1/; + +/ { + #address-cells = <1>; + #size-cells = <1>; + + soc { + #address-cells = <1>; + #size-cells = <1>; + + flash0: flash@0 { + compatible = "soc-nv-flash"; + reg = <0x0 0x100000>; + }; + + sram0: memory@20000000 { + compatible = "mmio-sram"; + reg = <0x20000000 0x40000>; + }; + }; + + external_flash: spi_flash@0 { + compatible = "jedec,spi-nor"; + reg = <0x0 0x800000>; + }; + + chosen { + zephyr,flash = &flash0; + zephyr,sram = &sram0; + }; +}; +""" + dt = parse_dts_string(dts) + + # Test flash detection + flashes = find_flash_devices(dt) + assert len(flashes) == 1, "Should find external flash only" + assert "external_flash" in flashes[0] + + # Test RAM detection + rams = find_ram_regions(dt) + assert len(rams) == 1, "Should find chosen SRAM only" + assert rams[0][0] == "sram0" + + def test_board_with_nrf5340_regions(self): + """Test that RAM subregions are included with the right addresses.""" + dts = """ +/dts-v1/; + +/ { + #address-cells = <1>; + #size-cells = <1>; + chosen { + zephyr,sram = &sram0_image; + }; + /* node '/soc/peripheral@50000000/qspi@2b000' defined in zephyr/dts/arm/nordic/nrf5340_cpuapp_peripherals.dtsi:475 */ + qspi: qspi@2b000 { + compatible = "nordic,nrf-qspi"; /* in zephyr/dts/arm/nordic/nrf5340_cpuapp_peripherals.dtsi:476 */ + #address-cells = < 0x1 >; /* in zephyr/dts/arm/nordic/nrf5340_cpuapp_peripherals.dtsi:477 */ + #size-cells = < 0x0 >; /* in zephyr/dts/arm/nordic/nrf5340_cpuapp_peripherals.dtsi:478 */ + reg = < 0x2b000 0x1000 >, + < 0x10000000 0x10000000 >; /* in zephyr/dts/arm/nordic/nrf5340_cpuapp_peripherals.dtsi:479 */ + reg-names = "qspi", + "qspi_mm"; /* in zephyr/dts/arm/nordic/nrf5340_cpuapp_peripherals.dtsi:480 */ + interrupts = < 0x2b 0x1 >; /* in zephyr/dts/arm/nordic/nrf5340_cpuapp_peripherals.dtsi:481 */ + status = "okay"; /* in zephyr/boards/nordic/nrf5340dk/nrf5340_cpuapp_common.dtsi:118 */ + + /* node '/soc/peripheral@50000000/qspi@2b000/mx25r6435f@0' defined in zephyr/boards/nordic/nrf5340dk/nrf5340_cpuapp_common.dtsi:123 */ + mx25r64: mx25r6435f@0 { + compatible = "nordic,qspi-nor"; /* in zephyr/boards/nordic/nrf5340dk/nrf5340_cpuapp_common.dtsi:124 */ + reg = < 0x0 >; /* in zephyr/boards/nordic/nrf5340dk/nrf5340_cpuapp_common.dtsi:125 */ + writeoc = "pp4io"; /* in zephyr/boards/nordic/nrf5340dk/nrf5340_cpuapp_common.dtsi:127 */ + readoc = "read4io"; /* in zephyr/boards/nordic/nrf5340dk/nrf5340_cpuapp_common.dtsi:129 */ + sck-frequency = < 0x7a1200 >; /* in zephyr/boards/nordic/nrf5340dk/nrf5340_cpuapp_common.dtsi:130 */ + jedec-id = [ C2 28 17 ]; /* in zephyr/boards/nordic/nrf5340dk/nrf5340_cpuapp_common.dtsi:131 */ + sfdp-bfp = [ E5 20 F1 FF FF FF FF 03 44 EB 08 6B 08 3B 04 BB EE FF FF FF FF FF 00 FF FF FF 00 + FF 0C 20 0F 52 10 D8 00 FF 23 72 F5 00 82 ED 04 CC 44 83 68 44 30 B0 30 B0 F7 C4 + D5 5C 00 BE 29 FF F0 D0 FF FF ]; /* in zephyr/boards/nordic/nrf5340dk/nrf5340_cpuapp_common.dtsi:132 */ + size = < 0x4000000 >; /* in zephyr/boards/nordic/nrf5340dk/nrf5340_cpuapp_common.dtsi:136 */ + has-dpd; /* in zephyr/boards/nordic/nrf5340dk/nrf5340_cpuapp_common.dtsi:137 */ + t-enter-dpd = < 0x2710 >; /* in zephyr/boards/nordic/nrf5340dk/nrf5340_cpuapp_common.dtsi:138 */ + t-exit-dpd = < 0x88b8 >; /* in zephyr/boards/nordic/nrf5340dk/nrf5340_cpuapp_common.dtsi:139 */ + }; + }; + + /* node '/soc/memory@20000000' defined in zephyr/dts/arm/nordic/nrf5340_cpuapp.dtsi:55 */ + sram0: memory@20000000 { + compatible = "mmio-sram"; /* in zephyr/dts/arm/nordic/nrf5340_cpuapp.dtsi:56 */ + #address-cells = < 0x1 >; /* in zephyr/dts/arm/nordic/nrf5340_cpuapp.dtsi:57 */ + #size-cells = < 0x1 >; /* in zephyr/dts/arm/nordic/nrf5340_cpuapp.dtsi:58 */ + reg = < 0x20000000 0x80000 >; /* in zephyr/dts/arm/nordic/nrf5340_cpuapp_qkaa.dtsi:15 */ + ranges = < 0x0 0x20000000 0x80000 >; /* in zephyr/dts/arm/nordic/nrf5340_cpuapp_qkaa.dtsi:16 */ + + /* node '/soc/memory@20000000/sram@0' defined in zephyr/dts/vendor/nordic/nrf5340_sram_partition.dtsi:16 */ + sram0_image: sram@0 { + reg = < 0x0 0x70000 >; /* in zephyr/dts/vendor/nordic/nrf5340_sram_partition.dtsi:18 */ + ranges = < 0x0 0x0 0x70000 >; /* in zephyr/dts/vendor/nordic/nrf5340_sram_partition.dtsi:19 */ + #address-cells = < 0x1 >; /* in zephyr/dts/vendor/nordic/nrf5340_sram_partition.dtsi:20 */ + #size-cells = < 0x1 >; /* in zephyr/dts/vendor/nordic/nrf5340_sram_partition.dtsi:21 */ + + /* node '/soc/memory@20000000/sram@0/sram0_image@0' defined in zephyr/dts/vendor/nordic/nrf5340_sram_partition.dtsi:23 */ + sram0_s: sram0_image@0 { + reg = < 0x0 0x40000 >; /* in zephyr/dts/vendor/nordic/nrf5340_sram_partition.dtsi:25 */ + }; + }; + + /* node '/soc/memory@20000000/sram@40000' defined in zephyr/dts/vendor/nordic/nrf5340_sram_partition.dtsi:33 */ + sram0_ns: sram@40000 { + reg = < 0x40000 0x40000 >; /* in zephyr/dts/vendor/nordic/nrf5340_sram_partition.dtsi:35 */ + ranges = < 0x0 0x40000 0x40000 >; /* in zephyr/dts/vendor/nordic/nrf5340_sram_partition.dtsi:36 */ + #address-cells = < 0x1 >; /* in zephyr/dts/vendor/nordic/nrf5340_sram_partition.dtsi:37 */ + #size-cells = < 0x1 >; /* in zephyr/dts/vendor/nordic/nrf5340_sram_partition.dtsi:38 */ + + /* node '/soc/memory@20000000/sram@40000/sram0_ns@0' defined in zephyr/dts/vendor/nordic/nrf5340_sram_partition.dtsi:40 */ + sram0_ns_app: sram0_ns@0 { + reg = < 0x0 0x30000 >; /* in zephyr/dts/vendor/nordic/nrf5340_sram_partition.dtsi:42 */ + }; + }; + + /* node '/soc/memory@20000000/sram@70000' defined in zephyr/dts/vendor/nordic/nrf5340_shared_sram_partition.dtsi:27 */ + sram0_shared: sram@70000 { + reg = < 0x70000 0x10000 >; /* in zephyr/dts/vendor/nordic/nrf5340_shared_sram_partition.dtsi:29 */ + phandle = < 0x11 >; /* in zephyr/dts/arm/nordic/nrf5340_cpuapp_ipc.dtsi:9 */ + }; + }; +}; +""" + dt = parse_dts_string(dts) + flashes = find_flash_devices(dt) + rams = find_ram_regions(dt) + + # Should only get chosen SRAM + assert len(rams) == 1 + assert rams[0][0] == "sram0_image" + + assert len(flashes) == 1 + assert flashes[0] == "mx25r64" + + def test_board_with_chosen_memory_region(self): + """Test that RAM subregions are included with the right addresses.""" + dts = """ +/dts-v1/; + +/ { + #address-cells = <1>; + #size-cells = <1>; + chosen { + zephyr,sram = &axisram2; /* in zephyr/boards/st/nucleo_n657x0_q/nucleo_n657x0_q_common.dtsi:18 */ + }; + + + /* node '/memory@34000000' defined in zephyr/dts/arm/st/n6/stm32n6.dtsi:42 */ + axisram1: memory@34000000 { + compatible = "zephyr,memory-region", + "mmio-sram"; /* in zephyr/dts/arm/st/n6/stm32n6.dtsi:43 */ + zephyr,memory-region = "AXISRAM1"; /* in zephyr/dts/arm/st/n6/stm32n6.dtsi:44 */ + reg = < 0x34000000 0x200000 >; /* in zephyr/dts/arm/st/n6/stm32n657X0.dtsi:12 */ + }; + + /* node '/memory@34180400' defined in zephyr/dts/arm/st/n6/stm32n6.dtsi:47 */ + axisram2: memory@34180400 { + compatible = "zephyr,memory-region", + "mmio-sram"; /* in zephyr/dts/arm/st/n6/stm32n6.dtsi:48 */ + zephyr,memory-region = "AXISRAM2"; /* in zephyr/dts/arm/st/n6/stm32n6.dtsi:49 */ + reg = < 0x34180400 0x7fc00 >; /* in zephyr/dts/arm/st/n6/stm32n657X0.dtsi:17 */ + }; + + /* node '/soc/ramcfg@42023100' defined in zephyr/dts/arm/st/n6/stm32n6.dtsi:251 */ + ramcfg_sram3_axi: ramcfg@42023100 { + compatible = "st,stm32n6-ramcfg"; /* in zephyr/dts/arm/st/n6/stm32n6.dtsi:252 */ + #address-cells = < 0x1 >; /* in zephyr/dts/arm/st/n6/stm32n6.dtsi:253 */ + #size-cells = < 0x1 >; /* in zephyr/dts/arm/st/n6/stm32n6.dtsi:254 */ + reg = < 0x42023100 0x80 >; /* in zephyr/dts/arm/st/n6/stm32n6.dtsi:255 */ + + /* node '/soc/ramcfg@42023100/memory@34200000' defined in zephyr/dts/arm/st/n6/stm32n6.dtsi:259 */ + axisram3: memory@34200000 { + compatible = "zephyr,memory-region", + "mmio-sram"; /* in zephyr/dts/arm/st/n6/stm32n6.dtsi:260 */ + zephyr,memory-region = "AXISRAM3"; /* in zephyr/dts/arm/st/n6/stm32n6.dtsi:261 */ + zephyr,memory-attr = < 0x100000 >; /* in zephyr/dts/arm/st/n6/stm32n6.dtsi:262 */ + reg = < 0x34200000 0x70000 >; /* in zephyr/dts/arm/st/n6/stm32n657X0.dtsi:23 */ + status = "disabled"; /* in zephyr/dts/arm/st/n6/stm32n657X0.dtsi:24 */ + }; + }; +}; +""" + dt = parse_dts_string(dts) + rams = find_ram_regions(dt) + + print(rams) + + # Should only get chosen SRAM + assert len(rams) == 2 + assert rams[0][0] == "axisram2" + assert rams[1][0] == "axisram1" + + +class TestAddTomlPinNames: + """Test suite for add_toml_pin_names.""" + + def _add( + self, toml_pins, package_pins, port_indexes, ioports, pad_names=None, board_names=None + ): + board_names = dict(board_names or {}) + pad_pin = {} + pad_gpio = {} + pad_names = {} if pad_names is None else dict(pad_names) + for entry in package_pins or []: + if "pad" not in entry and "pad_name" not in entry: + # Informational module pin. + continue + pad = entry.get("pad", entry["pin"]) + pad_pin[pad] = entry["pin"] + if "gpio" in entry: + pad_gpio[pad] = entry["gpio"] + if "pad_name" in entry and pad not in pad_names: + pad_names[pad] = entry["pad_name"] + analog_board_names = add_toml_pin_names( + board_names, + {"pins": toml_pins}, + package_pins, + "nrf54l15_qfn48", + port_indexes, + ioports, + pad_names, + pad_gpio, + ) + return board_names, analog_board_names + + def test_package_pin_number(self): + package_pins = [ + {"pin": 1, "pad_name": "P1.00", "gpio": 32}, + {"pin": 5, "pad_name": "P0.07", "gpio": 7}, + ] + board_names, _ = self._add( + {"LED": 5}, package_pins, {"gpio0": 0, "gpio1": 1}, {"gpio0": {7}} + ) + assert board_names == {("gpio0", 7): ["LED"]} + + def test_ball_id(self): + package_pins = [{"pin": 12, "pad_name": "P1.15", "ball": "B2", "gpio": 47}] + board_names, _ = self._add( + {"LED": "b2"}, package_pins, {"gpio0": 0, "gpio1": 1}, {"gpio1": {15}} + ) + assert board_names == {("gpio1", 15): ["LED"]} + + def test_name_sanitized(self): + package_pins = [{"pin": 3, "pad_name": "P0.00", "gpio": 0}] + board_names, _ = self._add({"boot button": 3}, package_pins, {"gpio0": 0}, {"gpio0": {0}}) + assert board_names == {("gpio0", 0): ["BOOT_BUTTON"]} + + def test_missing_package_map_raises(self): + with pytest.raises(RuntimeError, match="package pin map"): + add_toml_pin_names( + {}, + {"pins": {"LED": 1}}, + None, + "custom", + {"gpio0": 0}, + {"gpio0": {0}}, + {}, + {}, + ) + + def test_unknown_package_pin_raises(self): + package_pins = [{"pin": 1, "pad_name": "P1.00", "gpio": 32}] + with pytest.raises(RuntimeError, match="package pin 9 is not in"): + self._add({"LED": 9}, package_pins, {"gpio0": 0, "gpio1": 1}, {"gpio0": {0}}) + + def test_unknown_ball_raises(self): + package_pins = [{"pin": 1, "pad_name": "P1.00", "gpio": 32}] + with pytest.raises(RuntimeError, match="ball Z9"): + self._add({"LED": "Z9"}, package_pins, {"gpio0": 0, "gpio1": 1}, {"gpio0": {0}}) + + def test_bad_value_type_raises(self): + package_pins = [{"pin": 1, "pad_name": "P1.00", "gpio": 32}] + with pytest.raises(RuntimeError, match="package pin number"): + self._add({"LED": True}, package_pins, {"gpio0": 0, "gpio1": 1}, {"gpio0": {0}}) + + def test_bad_name_raises(self): + package_pins = [{"pin": 1, "pad_name": "P1.00", "gpio": 32}] + with pytest.raises(RuntimeError, match="not usable"): + self._add({"1 LED": 1}, package_pins, {"gpio0": 0, "gpio1": 1}, {"gpio0": {0}}) + + def test_pad_not_on_gpio_controller_raises(self): + # A pad bonded to a GPIO controller the board doesn't enable: it is + # an error. + package_pins = [{"pin": 1, "pad_name": "P1.00", "gpio": 32}] + with pytest.raises(RuntimeError, match="not on an enabled GPIO controller"): + self._add({"LED": 1}, package_pins, {"gpio0": 0, "gpio1": 1}, {"gpio0": {0}}) + + def test_analog_only_pad_returns_names_by_pad(self): + # Pads whose package map entry carries no GPIO bond (analog-only + # pads like MCX N's ANA pads) return their board module names keyed + # by SoC pad; the caller creates their pin objects from the map's + # datasheet pad names. + package_pins = [{"pin": 110, "pad_name": "ANA_0"}] + board_names, analog_board_names = self._add( + {"A0": 110}, package_pins, {"gpio0": 0}, {"gpio0": {0}}, {110: "ANA_0"} + ) + assert board_names == {} + assert analog_board_names == {110: ["A0"]} + + def test_analog_pad_conflict_raises(self): + # The name is already bound to a GPIO pad by the devicetree walk, + # so [pins] cannot rebind it to an analog-only pad. + package_pins = [{"pin": 110, "pad_name": "ANA_0"}] + with pytest.raises(RuntimeError, match="already maps to gpio0 pin 0"): + self._add( + {"A0": 110}, + package_pins, + {"gpio0": 0}, + {"gpio0": {0}}, + {110: "ANA_0"}, + board_names={("gpio0", 0): ["A0"]}, + ) + + def test_no_pins_is_noop(self): + board_names = {} + analog = add_toml_pin_names( + board_names, {}, None, None, {"gpio0": 0}, {"gpio0": {0}}, {}, {} + ) + assert board_names == {} + assert analog == {} + + +class TestAddTomlPinNamesDuplicates: + """Deduplication and conflict behavior of add_toml_pin_names.""" + + PACKAGE_PINS = [ + {"pin": 5, "pad_name": "P1.04", "gpio": 36}, + {"pin": 27, "pad_name": "P0.02", "gpio": 2}, + ] + PORT_INDEXES = {"gpio0": 0, "gpio1": 1} + IOPORTS = {"gpio0": {2}, "gpio1": {4}} + + def _add(self, toml_pins, board_names=None): + board_names = dict(board_names or {}) + add_toml_pin_names( + board_names, + {"pins": toml_pins}, + self.PACKAGE_PINS, + "nrf54l15_qfn48", + self.PORT_INDEXES, + self.IOPORTS, + {e["pin"]: e["pad_name"] for e in self.PACKAGE_PINS}, + {e["pin"]: e["gpio"] for e in self.PACKAGE_PINS}, + ) + return board_names + + def test_dedupes_two_keys_same_name_same_pin(self): + board_names = self._add({"MY PIN": 5, "my-pin": 5}) + assert board_names == {("gpio1", 4): ["MY_PIN"]} + + def test_conflict_two_keys_same_name_different_pins(self): + with pytest.raises(RuntimeError, match="already maps to gpio1 pin 4"): + self._add({"MY PIN": 5, "my-pin": 27}) + + def test_dedupes_existing_devicetree_name_same_pin(self): + board_names = self._add({"green led": 5}, {("gpio1", 4): ["Green LED"]}) + assert board_names == {("gpio1", 4): ["Green LED"]} + + def test_conflict_existing_devicetree_name_different_pin(self): + with pytest.raises(RuntimeError, match="already maps to gpio0 pin 2"): + self._add({"STATUS": 5}, {("gpio0", 2): ["STATUS"]}) + + +class TestTomlStatusPin: + """Resolution of circuitpython.toml STATUS_NEOPIXEL-style keys to pins.""" + + BOARD_NAMES = { + ("gpio0", 16): ["NEOPIXEL"], + ("gpio1", 14): ["NEOPIXEL_POWER"], + ("gpio1", 15): ["LED", "L"], + } + + def test_resolves_pins_table_name(self): + assert _toml_status_pin( + {"STATUS_NEOPIXEL": "NEOPIXEL"}, self.BOARD_NAMES, "STATUS_NEOPIXEL" + ) == ("gpio0", 16) + + def test_matches_sanitized_name(self): + assert _toml_status_pin( + {"STATUS_NEOPIXEL_POWER": "neopixel-power"}, + self.BOARD_NAMES, + "STATUS_NEOPIXEL_POWER", + ) == ("gpio1", 14) + + def test_absent_key_is_none(self): + assert _toml_status_pin({}, self.BOARD_NAMES, "STATUS_NEOPIXEL") is None + assert _toml_status_pin(None, self.BOARD_NAMES, "STATUS_NEOPIXEL") is None + + def test_unknown_name_raises(self): + with pytest.raises(RuntimeError, match="STATUS_NEOPIXEL = 'NOPE' is not a board pin name"): + _toml_status_pin({"STATUS_NEOPIXEL": "NOPE"}, self.BOARD_NAMES, "STATUS_NEOPIXEL") + + +class TestStandardBusPins: + """The standard pins of board.I2C(), board.SPI() and board.UART().""" + + BOARD_NAMES = { + ("gpio0", 11): ["SCL"], + ("gpio0", 12): ["SDA"], + ("gpio0", 14): ["SCK"], + ("gpio0", 13): ["MOSI"], + ("gpio0", 15): ["MISO"], + ("gpio0", 25): ["TX"], + ("gpio0", 24): ["RX"], + } + + def test_all_standard_names(self): + assert _standard_bus_pins(self.BOARD_NAMES) == { + "i2c": {"scl": ("gpio0", 11), "sda": ("gpio0", 12)}, + "spi": {"clock": ("gpio0", 14), "mosi": ("gpio0", 13), "miso": ("gpio0", 15)}, + "uart": {"tx": ("gpio0", 25), "rx": ("gpio0", 24)}, + } + + def test_missing_name_leaves_out_bus(self): + names = {key: value for key, value in self.BOARD_NAMES.items() if value != ["MISO"]} + assert list(_standard_bus_pins(names)) == ["i2c", "uart"] + + def test_no_standard_names(self): + assert _standard_bus_pins({("gpio0", 2): ["D2"]}) == {} + + def test_pin_names_ignore_case(self): + names = dict(self.BOARD_NAMES) + names[("gpio0", 11)] = ["scl"] + assert _standard_bus_pins(names)["i2c"]["scl"] == ("gpio0", 11) + + def test_connector_aliases(self): + # Arduino header pins carry both their header name and the standard name. + names = { + ("gpio1", 0): ["D0", "RX"], + ("gpio1", 1): ["D1", "TX"], + ("gpio1", 2): ["D14", "SDA"], + ("gpio1", 3): ["D15", "SCL"], + } + assert _standard_bus_pins(names) == { + "i2c": {"scl": ("gpio1", 3), "sda": ("gpio1", 2)}, + "uart": {"tx": ("gpio1", 1), "rx": ("gpio1", 0)}, + } + + +class TestUsedByZephyr: + """Fixed bus instances that Zephyr itself uses.""" + + DTS = """ +/dts-v1/; +/ { + chosen { + zephyr,console = &uart0; + }; + uart0: uart@0 { + }; + uart1: uart@1 { + }; + spi0: spi@0 { + flash@0 { + reg = <0>; + }; + }; + spi1: spi@1 { + }; + spi2: spi@2 { + }; + display { + spi-dev = <&spi1>; + }; + disabled_display { + status = "disabled"; + spi-dev = <&spi2>; + }; +}; +""" + + def _used(self, label): + dt = parse_dts_string(self.DTS) + return _used_by_zephyr(dt, dt.label2node[label]) + + def test_chosen_console(self): + assert self._used("uart0") + + def test_child_device(self): + assert self._used("spi0") + + def test_referenced_by_phandle(self): + assert self._used("spi1") + + def test_referenced_only_by_disabled_node(self): + assert not self._used("spi2") + + def test_unused(self): + assert not self._used("uart1") + + +class TestStemmaI2cPins: + """The pins of board.STEMMA_I2C, named by the stemma-qt-connector entry.""" + + def test_same_pins_as_i2c(self): + names = {("gpio0", 3): ["SCL", "STEMMA_SCL"], ("gpio0", 2): ["SDA", "STEMMA_SDA"]} + assert _named_pins(names, STEMMA_I2C_PINS) == { + "scl": ("gpio0", 3), + "sda": ("gpio0", 2), + } + + def test_own_pins(self): + names = { + ("gpio0", 25): ["SCL"], + ("gpio0", 24): ["SDA"], + ("gpio0", 23): ["SCL1", "STEMMA_SCL"], + ("gpio0", 22): ["SDA1", "STEMMA_SDA"], + } + assert _named_pins(names, STEMMA_I2C_PINS) == { + "scl": ("gpio0", 23), + "sda": ("gpio0", 22), + } + + def test_no_connector(self): + assert _named_pins({("gpio0", 3): ["SCL"], ("gpio0", 2): ["SDA"]}, STEMMA_I2C_PINS) is None + + +class TestBoardI2cBuses: + """The board I2C buses for board.I2C() and board.STEMMA_I2C.""" + + I2C = {"scl": ("gpio0", 25), "sda": ("gpio0", 24)} + STEMMA = {"scl": ("gpio0", 23), "sda": ("gpio0", 22)} + + def test_no_stemma_connector(self): + assert _board_i2c_buses(self.I2C, None) == ([self.I2C], None) + + def test_stemma_on_the_i2c_pins(self): + assert _board_i2c_buses(self.I2C, dict(self.I2C)) == ([self.I2C], 0) + + def test_stemma_on_other_pins(self): + assert _board_i2c_buses(self.I2C, self.STEMMA) == ([self.I2C, self.STEMMA], 1) + + def test_stemma_without_standard_i2c(self): + assert _board_i2c_buses(None, self.STEMMA) == ([self.STEMMA], 0) + + def test_neither(self): + assert _board_i2c_buses(None, None) == ([], None) + + +class TestFastestFirst: + """Ordering of bus instance pools by devicetree max-frequency.""" + + @staticmethod + def _node(name, max_frequency=None): + props = {} + if max_frequency is not None: + props["max-frequency"] = SimpleNamespace(to_num=lambda: max_frequency) + return SimpleNamespace(name=name, props=props) + + def test_highest_first(self): + nodes = [self._node("spi2", 8_000_000), self._node("spi3", 32_000_000)] + assert [n.name for n in _fastest_first(nodes)] == ["spi3", "spi2"] + + def test_stable_for_equal_and_missing(self): + nodes = [ + self._node("i2c1"), + self._node("spi22", 8_000_000), + self._node("i2c0"), + self._node("spi21", 8_000_000), + self._node("spi00", 32_000_000), + ] + assert [n.name for n in _fastest_first(nodes)] == [ + "spi00", + "spi22", + "spi21", + "i2c1", + "i2c0", + ] + + +class TestTomlStatusDotstar: + """Resolution of circuitpython.toml STATUS_DOTSTAR_DATA/CLOCK keys.""" + + BOARD_NAMES = { + ("gpio0", 8): ["DOTSTAR_DATA"], + ("gpio1", 9): ["DOTSTAR_CLOCK"], + ("gpio0", 16): ["NEOPIXEL"], + } + DOTSTAR = {"STATUS_DOTSTAR_DATA": "DOTSTAR_DATA", "STATUS_DOTSTAR_CLOCK": "DOTSTAR_CLOCK"} + + def test_resolves_data_and_clock(self): + assert _toml_status_dotstar(self.DOTSTAR, self.BOARD_NAMES) == ( + ("gpio0", 8), + ("gpio1", 9), + ) + + def test_absent_keys_are_none(self): + assert _toml_status_dotstar({}, self.BOARD_NAMES) is None + assert _toml_status_dotstar(None, self.BOARD_NAMES) is None + + def test_one_key_only_raises(self): + with pytest.raises(RuntimeError, match="needs both"): + _toml_status_dotstar({"STATUS_DOTSTAR_DATA": "DOTSTAR_DATA"}, self.BOARD_NAMES) + + def test_with_status_neopixel_raises(self): + with pytest.raises(RuntimeError, match="both STATUS_NEOPIXEL and a status DotStar"): + _toml_status_dotstar({**self.DOTSTAR, "STATUS_NEOPIXEL": "NEOPIXEL"}, self.BOARD_NAMES) diff --git a/ports/zephyr-cp/cptools/update_board_info.py b/ports/zephyr-cp/cptools/update_board_info.py new file mode 100755 index 00000000000..935fc07c17d --- /dev/null +++ b/ports/zephyr-cp/cptools/update_board_info.py @@ -0,0 +1,101 @@ +#!/usr/bin/env python3 + +import pathlib +import sys +import tomlkit + + +def find_modules(top_dir, port_dir): + """Find all available modules in shared-bindings and port bindings.""" + modules = set() + for module in sorted( + list(top_dir.glob("shared-bindings/*")) + list(port_dir.glob("bindings/*")), + key=lambda x: x.name, + ): + if not module.is_dir(): + continue + modules.add(module.name) + return sorted(modules) + + +def find_board_info_files(port_dir): + """Find all autogen_board_info.toml files in the port directory.""" + return list(port_dir.glob("boards/**/autogen_board_info.toml")) + + +def update_board_info(board_info_path, available_modules): + """Update board info file with new modules set to false.""" + if not board_info_path.exists(): + print(f"Error: Board info file {board_info_path} does not exist", file=sys.stderr) + return False + + # Load existing board info + with open(board_info_path, "r", encoding="utf-8") as f: + board_info = tomlkit.load(f) + + # Get current modules + current_modules = set(board_info.get("modules", {})) + + # Find new modules + new_modules = set(available_modules) - current_modules + if not new_modules: + print( + f"No new modules found for {board_info_path.relative_to(board_info_path.parents[3])}" + ) + return True + + # Add new modules as disabled in alphabetical order + modules_table = board_info["modules"] + # Get all modules (existing and new) and sort them + all_modules = list(current_modules | new_modules) + all_modules.sort() + + # Create a new table with sorted modules + sorted_table = tomlkit.table() + for module in all_modules: + if module in modules_table: + # TODO: Use modules_table.item once tomlkit is released with changes from January 2025 + sorted_table[module] = modules_table._value.item(module) + else: + sorted_table[module] = tomlkit.item(False) + + # Replace the modules table with the sorted one + board_info["modules"] = sorted_table + + # Write updated board info + with open(board_info_path, "w", encoding="utf-8") as f: + tomlkit.dump(board_info, f) + + print( + f"Updated {board_info_path.relative_to(board_info_path.parents[3])} with {len(new_modules)} new modules:" + ) + for module in sorted(new_modules): + print(f" - {module}") + return True + + +def main(): + # Get repo paths + script_dir = pathlib.Path(__file__).parent + top_dir = script_dir.parents[2] # circuitpython root + port_dir = script_dir.parent # zephyr-cp directory + + # Get available modules once + available_modules = find_modules(top_dir, port_dir) + + # Update all board info files + board_info_files = find_board_info_files(port_dir) + if not board_info_files: + print("No board info files found") + sys.exit(1) + + success = True + for board_info_path in board_info_files: + if not update_board_info(board_info_path, available_modules): + success = False + + sys.exit(0 if success else 1) + + +if __name__ == "__main__": + main() diff --git a/ports/zephyr-cp/cptools/zephyr2cp.py b/ports/zephyr-cp/cptools/zephyr2cp.py index cd0e3a6f2aa..da558eea1e8 100644 --- a/ports/zephyr-cp/cptools/zephyr2cp.py +++ b/ports/zephyr-cp/cptools/zephyr2cp.py @@ -1,16 +1,54 @@ import logging import pathlib -import cpbuild +import re +import tomllib -from devicetree import dtlib +import cpbuild import yaml - from compat2driver import COMPAT_TO_DRIVER +from devicetree import dtlib logger = logging.getLogger(__name__) +logger.setLevel(logging.DEBUG) + +# GPIO flags defined here: include/zephyr/dt-bindings/gpio/gpio.h +GPIO_ACTIVE_LOW = 1 << 0 +# A region has to be big enough to host TLSF's control structure to be usable as +# the first heap pool, and TLSF sizes that structure from the maximum heap size +# rather than from the region: at an 8 MB maximum it is 2412 bytes. Anything +# smaller than this is not worth adding as a later pool either. The previous +# value of 1024 let through two SiWx917 regions that are exactly 0x400 bytes, +# /memory@0 (reserved for the network processor) and /memory-dma@24061c00, +# neither of which should ever be in the Python heap. +MINIMUM_RAM_SIZE = 8192 + +# Preferred spellings and capitalizations for MICROPY_HW_MCU_NAME, keyed by the Zephyr +# SoC name from board.yml. SoCs not listed use the Zephyr name as is. +SOC_NAMES = { + "nrf52840": "nRF52840", + "nrf5340": "nRF5340", + "nrf54h20": "nRF54H20", + "nrf54l15": "nRF54L15", + "nrf54lm20a": "nRF54LM20A", +} + +# Checked before the generated COMPAT_TO_DRIVER, so an entry here overrides a +# wrong generated one. MANUAL_COMPAT_TO_DRIVER = { "renesas_ra_nv_flash": "flash", + "soc_nv_flash": "flash", + "jedec_nor": "flash", + "nordic_nrf_uarte": "serial", + "nordic_nrf_uart": "serial", + "nordic_nrf_twim": "i2c", + "nordic_nrf_twi": "i2c", + "nordic_nrf_spim": "spi", + "nordic_nrf_spi": "spi", + "nordic_nrf_i2s": "i2s", + # The driver lives in drivers/spi/spi_nxp_lpspi/, so the generated table + # names it "spi/spi_nxp_lpspi", which is not a busio class. + "nxp_lpspi": "spi", } # These are controllers, not the flash devices themselves. @@ -20,46 +58,77 @@ "nordic,nrf-spim", ) +BUSIO_CLASSES = {"serial": "UART", "i2c": "I2C", "spi": "SPI"} + +# Compatibles analogio is implemented against: the SoC ADC (whose pads +# iobroker resolves to their fixed analog input), the SoC DAC (whose output +# pad is fixed per SoC) and the emulated devices. +ANALOG_COMPAT = { + "nordic_nrf_saadc": "adc", + "zephyr_adc_emul": "adc", + "vnd_dac": "dac", + "renesas_ra_dac": "dac", + "nxp_lpc_lpadac": "adc", + "nxp_lpdac": "dac", +} + +AUDIOBUSIO_CLASSES = {"i2s": "I2SOut"} + +# Board pin names for each connector compatible, in gpio-map order. Keep the +# entries in alphabetical order. CONNECTORS = { - "mikro-bus": [ - "AN", - "RST", - "CS", - "SCK", - "MISO", - "MOSI", - "PWM", - "INT", - "RX", - "TX", - "SCL", - "SDA", + "adafruit-clue": [ + ["P0", "D0", "A2", "RX"], + ["P1", "D1", "A3", "TX"], + ["P2", "D2", "A4"], + ["P3", "D3", "A5"], + ["P4", "D4", "A6"], + ["P5", "D5", "BUTTON_A"], + ["P6", "D6"], + ["P7", "D7"], + ["P8", "D8"], + ["P9", "D9"], + ["P10", "D10", "A7"], + ["P11", "D11", "BUTTON_B"], + ["P12", "D12", "A0"], + ["P13", "D13", "SCK"], + ["P14", "D14", "MISO"], + ["P15", "D15", "MOSI"], + ["P16", "D16", "A1"], + ["P17", "D17", "L", "LED"], + ["P18", "D18", "NEOPIXEL"], + ["P19", "D19", "SCL"], + ["P20", "D20", "SDA"], ], - "arduino-header-r3": [ + "adafruit-feather-header": [ "A0", "A1", "A2", "A3", "A4", "A5", - "D0", - "D1", - "D2", - "D3", + "SCK", + "MOSI", + "MISO", + "RX", + "TX", "D4", + "SDA", + "SCL", "D5", "D6", - "D7", - "D8", "D9", "D10", "D11", "D12", "D13", - "D14", - "D15", ], - "adafruit-feather-header": [ + # Our own binding (dts/bindings/adafruit-itsybitsy-header.yaml): the + # ItsyBitsy nRF52840 header pins only. + # TODO: figure out how to handle the extra pins on other ItsyBitsy + # boards, such as D3 and D4 on the ItsyBitsy M4 and RP2040. We may want + # separate connectors for the different board families. + "adafruit-itsybitsy-header": [ "A0", "A1", "A2", @@ -69,19 +138,176 @@ "SCK", "MOSI", "MISO", - "RX", - "TX", - "D4", + ["D0", "RX"], + ["D1", "TX"], + "D2", "SDA", "SCL", "D5", - "D6", + "D7", "D9", "D10", "D11", "D12", "D13", ], + "arducam,dvp-20pin-connector": [ + "SCL", + "SDA", + "VS", + "HS", + "PCLK", + "XCLK", + "D7", + "D6", + "D5", + "D4", + "D3", + "D2", + "D1", + "D0", + "PEN", + "PDN", + "GPIO0", + "GPIO1", + ], + # The standard bus pin names are those on Arduino Uno R3 boards: TX/RX on + # D1/D0, SPI on D11-D13 (and the 2x3 SPI header), and SDA/SCL on the two + # pins above AREF, which this binding calls D14 and D15. + "arduino-header-r3": [ + "A0", + "A1", + "A2", + "A3", + "A4", + "A5", + ["D0", "RX"], + ["D1", "TX"], + "D2", + "D3", + "D4", + "D5", + "D6", + "D7", + "D8", + "D9", + "D10", + ["D11", "MOSI"], + ["D12", "MISO"], + ["D13", "SCK"], + ["D14", "SDA"], + ["D15", "SCL"], + ], + "mikro-bus": [ + "AN", + "RST", + "CS", + "SCK", + "MISO", + "MOSI", + "PWM", + "INT", + "RX", + "TX", + "SCL", + "SDA", + ], + "nordic,expansion-board-header": [ + "P1_04", + "P1_05", + "P1_06", + "P1_07", + "P1_08", + "P1_09", + "P1_10", + "P1_11", + "P1_12", + "P1_13", + "P1_14", + ], + "nxp,cam-44pins-connector": ["CAM_RESETB", "CAM_PWDN"], + "nxp,lcd-8080": [ + "TOUCH_SCL", + "TOUCH_SDA", + "TOUCH_INT", + "BACKLIGHT", + "RESET", + "LCD_DC", + "LCD_CS", + "LCD_WR", + "LCD_RD", + "LCD_TE", + "LCD_D0", + "LCD_D1", + "LCD_D2", + "LCD_D3", + "LCD_D4", + "LCD_D5", + "LCD_D6", + "LCD_D7", + "LCD_D8", + "LCD_D9", + "LCD_D10", + "LCD_D11", + "LCD_D12", + "LCD_D13", + "LCD_D14", + "LCD_D15", + ], + "nxp,lcd-pmod": [ + "LCD_WR", + "TOUCH_SCL", + "LCD_DC", + "TOUCH_SDA", + "LCD_MOSI", + "TOUCH_RESET", + "LCD_CS", + "TOUCH_INT", + ], + "raspberrypi,csi-connector": [ + "CSI_D0_N", + "CSI_D0_P", + "CSI_D1_N", + "CSI_D1_P", + "CSI_CK_N", + "CSI_CK_P", + "CSI_D2_N", + "CSI_D2_P", + "CSI_D3_N", + "CSI_D3_P", + "IO0", + "IO1", + "I2C_SCL", + "I2C_SDA", + ], + "raspberrypi,pico-header": [ + "GP0", + "GP1", + "GP2", + "GP3", + "GP4", + "GP5", + "GP6", + "GP7", + "GP8", + "GP9", + "GP10", + "GP11", + "GP12", + "GP13", + "GP14", + "GP15", + "GP16", + "GP17", + "GP18", + "GP19", + "GP20", + "GP21", + "GP22", + ["GP26_A0", "GP26", "A0"], + ["GP27_A1", "GP27", "A1"], + ["GP28_A2", "GP28", "A2"], + ], "renesas,ra-gpio-mipi-header": [ "IIC_SDA", "DISP_BLEN", @@ -89,26 +315,716 @@ "DISP_INT", "DISP_RST", ], + "renesas,ra-parallel-graphics-header": [ + "DISP_BLEN", + "IIC_SDA", + "DISP_INT", + "IIC_SCL", + "DISP_RST", + "LCDC_TCON0", + "LCDC_CLK", + "LCDC_TCON2", + "LCDC_TCON1", + "LCDC_EXTCLK", + "LCDC_TCON3", + "LCDC_DATA01", + "LCDC_DATA00", + "LCDC_DATA03", + "LCDC_DATA02", + "LCDC_DATA05", + "LCDC_DATA04", + "LCDC_DATA07", + "LCDC_DATA16", + "LCDC_DATA09", + "LCDC_DATA08", + "LCDC_DATA11", + "LCDC_DATA10", + "LCDC_DATA13", + "LCDC_DATA12", + "LCDC_DATA15", + "LCDC_DATA14", + "LCDC_DATA17", + "LCDC_DATA16", + "LCDC_DATA19", + "LCDC_DATA18", + "LCDC_DATA21", + "LCDC_DATA20", + "LCDC_DATA23", + "LCDC_DATA22", + ], + "st,stm32-dcmi-camera-fpu-330zh": [ + "SCL", + "SDA", + "RESET", + "PEN", + "VS", + "HS", + "PCLK", + "D7", + "D6", + "D5", + "D4", + "D3", + "D2", + "D1", + "D0", + ], + # STEMMA QT connectors, and Qwiic connectors, which use the same binding. + # board.STEMMA_I2C is on these pins (see STEMMA_I2C_PINS). + "stemma-qt-connector": ["STEMMA_SCL", "STEMMA_SDA"], } +EXCEPTIONAL_DRIVERS = ["entropy", "gpio", "led"] + + +def find_flash_devices(device_tree): + """ + Find all flash devices from a device tree. + + Args: + device_tree: Parsed device tree (dtlib.DT object) + + Returns: + List of device tree flash device reference strings + """ + # Build path2chosen mapping + path2chosen = {} + for k in device_tree.root.nodes["chosen"].props: + value = device_tree.root.nodes["chosen"].props[k] + path2chosen[value.to_path()] = k + + # Paths of zephyr,sim-flash controllers (the flash simulator used by + # native_sim). The simulator driver defines its device on the controller + # node, not on its soc-nv-flash child, so the controller must be used and + # the child skipped. + sim_flash_controller_paths = set() + + flashes = [] + logger.debug("Flash devices:") + + # Traverse all nodes in the device tree + # A list, not a set, so the nodes are visited in the same order every build. + remaining_nodes = [device_tree.root] + while remaining_nodes: + node = remaining_nodes.pop() + remaining_nodes.extend(node.nodes.values()) + + # Get compatible strings + compatible = [] + if "compatible" in node.props: + compatible = node.props["compatible"].to_strings() + + # Get status + status = node.props.get("status", None) + if status is None: + status = "okay" + else: + status = status.to_string() + + # Check if this is a flash device + if not compatible or status != "okay": + continue + + # Check for flash driver via compat2driver + drivers = [] + for c in compatible: + underscored = c.replace(",", "_").replace("-", "_") + driver = MANUAL_COMPAT_TO_DRIVER.get(underscored, None) + if not driver: + driver = COMPAT_TO_DRIVER.get(underscored, None) + if driver: + drivers.append(driver) + logger.debug(f" {node.labels[0] if node.labels else node.name} drivers: {drivers}") + + if "flash" not in drivers: + continue + + if compatible[0] == "zephyr,sim-flash": + # Always use the controller for the flash simulator, even when it + # is chosen as zephyr,flash-controller. + sim_flash_controller_paths.add(node.path) + if node.labels: + flashes.append(node.labels[0]) + continue + + # The soc-nv-flash child of a flash simulator has no device defined on + # it; the controller (handled above) is the flash device. + if node.parent is not None and node.parent.path in sim_flash_controller_paths: + logger.debug( + f" skipping flash {node.labels[0] if node.labels else node.name} (sim-flash child)" + ) + continue + + # Skip chosen nodes because they are used by Zephyr + if node in path2chosen: + logger.debug( + f" skipping flash {node.labels[0] if node.labels else node.name} (chosen)" + ) + continue + + # Skip blocked flash compatibles (controllers, not actual flash devices) + if compatible[0] in BLOCKED_FLASH_COMPAT: + logger.debug( + f" skipping flash {node.labels[0] if node.labels else node.name} (blocked compat)" + ) + continue + + if node.labels: + flashes.append(node.labels[0]) + + logger.debug("Flash devices:") + for flash in flashes: + logger.debug(f" {flash}") + + return flashes + + +def _label_to_end(label): + return f"(uint32_t*) (DT_REG_ADDR(DT_NODELABEL({label})) + DT_REG_SIZE(DT_NODELABEL({label})))" + + +def find_ram_regions(device_tree): + """ + Find all RAM regions from a device tree. Includes the zephyr,sram node and + any zephyr,memory-region nodes. + + Returns: + List of RAM region info tuples: (label, start, end, size, path) + """ + rams = [] + chosen = None + # Get the chosen SRAM node directly + if "zephyr,sram" in device_tree.root.nodes["chosen"].props: + chosen = device_tree.root.nodes["chosen"].props["zephyr,sram"].to_path() + label = chosen.labels[0] + size = chosen.props["reg"].to_nums()[1] + logger.debug(f"Found chosen SRAM node: {label} with size {size}") + rams.append((label, "z_mapped_end", _label_to_end(label), size, chosen.path)) + + # Traverse all nodes in the device tree to find memory-region nodes + # A list, not a set, so the nodes are visited in the same order every build. + remaining_nodes = [device_tree.root] + while remaining_nodes: + node = remaining_nodes.pop() + + # Check status first so we don't add child nodes that aren't active. + status = node.props.get("status", None) + if status is None: + status = "okay" + else: + status = status.to_string() + + if status != "okay": + continue + + if node == chosen: + continue + + remaining_nodes.extend(node.nodes.values()) + + if "compatible" not in node.props or not node.labels: + continue + + compatible = node.props["compatible"].to_strings() + + if "zephyr,memory-region" not in compatible or "zephyr,memory-region" not in node.props: + continue + + is_mmio_sram = "mmio-sram" in compatible + # The i.MX RT DTCM and ITCM are read/write RAM too, but their nodes are + # not mmio-sram. On RT10xx the kernel stacks are relocated to DTCM and + # the XIP-sensitive flash code to ITCM; what each leaves free (from + # __DTCM_end / __ITCM_end) becomes heap. + is_imx_tcm = "nxp,imx-dtcm" in compatible or "nxp,imx-itcm" in compatible + device_type = node.props.get("device_type") + has_memory_device_type = device_type and device_type.to_string() == "memory" + if not (is_mmio_sram or is_imx_tcm or has_memory_device_type): + continue + + size = node.props["reg"].to_nums()[1] + + start = "__" + node.props["zephyr,memory-region"].to_string() + "_end" + end = _label_to_end(node.labels[0]) + + # Filter by minimum size + if size >= MINIMUM_RAM_SIZE: + logger.debug( + f"Adding extra RAM info: ({node.labels[0]}, {start}, {end}, {size}, {node.path})" + ) + info = (node.labels[0], start, end, size, node.path) + rams.append(info) + + return rams + + +# gpio-keys nodes identify a key with `zephyr,code` rather than the optional and +# deprecated `label`, so the code is the only name a modern board gives. +INPUT_KEY_NAMES = {} + + +# Mask selecting the nRF pin number field (absolute pin, port*32+pin) of +# a pinctrl psel entry. The pin control entry uses all-ones in this field to +# mark a disconnected signal (NRF_PIN_DISCONNECTED). +NRF_PIN_FIELD_MASK = 0x1FF + + +def _reg_addr_expr(device_tree, label): + """C expression for a node's register block address, or 0 when it has none. + + The iobroker tables carry the address for SoC routing code that decides + reachability from it (nRF54L power domains). Some nodes the tables list + have no reg property (native_sim's gpio_emul, PIO-based buses), and + DT_REG_ADDR() does not compile for them. + """ + node = device_tree.label2node.get(label) + if node is None or "reg" not in node.props: + return "0" + return f"DT_REG_ADDR(DT_NODELABEL({label}))" + + +def _fastest_first(nodes): + """Order bus instance nodes by their ``max-frequency``, highest first. + + iobroker hands out the first free instance in a pool, so this gives + busio the fastest one first, such as the nRF52840's 32 MHz SPIM3. The + sort is stable: nodes with equal or no ``max-frequency`` keep their order. + """ + + def max_frequency(node): + prop = node.props.get("max-frequency") + return prop.to_num() if prop is not None else 0 + + return sorted(nodes, key=max_frequency, reverse=True) + + +def _pinctrl_default_psels(node): + """Return the raw nRF psel entries of a node's "default" pinctrl state. + + The state node (referenced by pinctrl-0) groups its configuration in + child nodes (typically named group1, group2, ...) that each carry a + psels property. + + Returns None when the node does not use pinctrl. + """ + prop = node.props.get("pinctrl-0") + if prop is None: + return None + psels = [] + try: + for state in prop.to_nodes(): + for group in state.nodes.values(): + if "psels" not in group.props: + continue + for value in group.props["psels"].to_nums(): + psels.append(value) + except (dtlib.DTError, KeyError): + return None + return psels + + +def _populate_input_key_names(): + header = ( + pathlib.Path(__file__).parent.parent + / "zephyr" + / "include" + / "zephyr" + / "dt-bindings" + / "input" + / "input-event-codes.h" + ) + if not header.exists(): + return + pattern = re.compile(r"^#define\s+INPUT_(?PKEY_\w+)\s+(?P\d+)") + for line in header.read_text().splitlines(): + match = pattern.match(line) + if match: + INPUT_KEY_NAMES.setdefault(int(match.group("code")), match.group("name")) + + +_populate_input_key_names() + + +def add_toml_pin_names( + board_names, + mpconfigboard, + package_pins, + package_choice, + port_indexes, + ioports, + pad_name_of_pad, + gpio_pad_of_pad, +): + """Add board pin names from circuitpython.toml's ``[pins]`` table. + + Each entry maps a board module name to a package pin number or, for ball + grid array packages, the datasheet's ball id (e.g. ``"A1"``). Entries are + resolved to SoC pads with the iobroker package pin map selected by the + ``IOBROKER_PACKAGE`` choice, and appended to ``board_names`` like + devicetree-derived names are. + + A name that already maps to the same pin (from the devicetree walk or an + earlier entry) is deduplicated; a name that would map to a different pin + than an existing entry is a build error. + + Pads whose package map entry carries no GPIO bond (the map's + analog-only pads) cannot key ``board_names``, whose entries describe + GPIO controller pins; the names collected for them are keyed by SoC pad + and returned as a ``pad -> board module names`` dict instead, with the + pin objects created from the map's datasheet pad names (e.g. + "ANA_0") by the caller. + """ + toml_pins = (mpconfigboard or {}).get("pins") + if not toml_pins: + return {} + if package_pins is None: + reason = "NONE" if package_choice == "none" else "unset" + raise RuntimeError( + f"circuitpython.toml [pins] needs an iobroker package pin map but " + f"CONFIG_IOBROKER_PACKAGE is {reason}" + ) + port_label_of_index = {index: label for label, index in port_indexes.items()} + + # Board module names for the package map's analog-only pads, keyed by + # their SoC pad (a pad no enabled GPIO controller covers). + analog_board_names = {} + + def sanitize(name): + return name.upper().replace(" ", "_").replace("-", "_").replace("(", "").replace(")", "") + + # Package pin -> pad (the SoC pad number; SoC packages default it to + # the pin), ball id -> pad, for resolving [pins] values. + package_pin_to_pad = {} + balls = {} + for package_pin_entry in package_pins: + pad = package_pin_entry.get("pad", None) + if pad is None and "pad_name" not in package_pin_entry: + # Informational module pin (e.g. bonded to GND): no pad. + continue + pin = package_pin_entry["pin"] + if pad is None: + pad = pin + if pin in package_pin_to_pad and package_pin_to_pad[pin] != pad: + raise RuntimeError(f"package pin {pin} maps to multiple pads in the package pin map") + package_pin_to_pad[pin] = pad + if "ball" in package_pin_entry: + ball = package_pin_entry["ball"] + if ball in balls and balls[ball] != pad: + raise RuntimeError(f"ball {ball} maps to multiple pads in the package pin map") + balls[ball] = pad + + # Names already in use from the devicetree walk, as sanitized name -> + # list of pins it is attached to. + pins_of_name = {} + for pin_key, names in board_names.items(): + for existing_name in names: + pins = pins_of_name.setdefault(sanitize(existing_name), []) + if pin_key not in pins: + pins.append(pin_key) + for name, package_pin in toml_pins.items(): + board_name = sanitize(name) + if not re.match(r"^[A-Z][A-Z0-9_]*$", board_name): + raise RuntimeError( + f"circuitpython.toml [pins] name {name!r} is not usable as a board module name" + ) + if isinstance(package_pin, str): + ball = package_pin.strip().upper() + pad = balls.get(ball) + if pad is None: + raise RuntimeError( + f"circuitpython.toml [pins] name {name}: ball {package_pin} is not in " + f"the package pin map" + ) + elif isinstance(package_pin, int) and not isinstance(package_pin, bool): + pad = package_pin_to_pad.get(package_pin) + if pad is None: + raise RuntimeError( + f"circuitpython.toml [pins] name {name}: package pin {package_pin} is " + f"not in the package pin map" + ) + else: + raise RuntimeError( + f"circuitpython.toml [pins] name {name}: value must be a package pin number " + f"or ball id" + ) + gpio = gpio_pad_of_pad.get(pad) + if gpio is None: + # A pad whose package map entry carries no GPIO bond (an + # analog-only pad): the pin object is created by the caller + # from the map's datasheet pad name. + # A pad no enabled GPIO controller covers (an analog-only pad): + # the pin object is created by the caller from the map's + # datasheet pad name. + if pad not in pad_name_of_pad: + raise RuntimeError( + f"circuitpython.toml [pins] name {name}: package pin {package_pin} is " + f"on pad {pad}, which has no GPIO bond and no pad name in the " + f"package pin map" + ) + previous = pins_of_name.get(board_name, []) + if previous and pad not in previous: + previous = ", ".join( + f"{label} pin {num}" if isinstance(label, str) else f"pad {label}" + for label, num in previous + ) + raise RuntimeError( + f"circuitpython.toml [pins] name {name}: already maps to {previous}, " + f"but [pins] assigns it to analog pad {pad}" + ) + if previous: + # Same name already attached to this pad (devicetree or an + # earlier entry); nothing to add. + continue + pins_of_name[board_name] = [pad] + analog_board_names.setdefault(pad, []).append(board_name) + continue + label = port_label_of_index.get(gpio // 32) + if label is None or gpio % 32 not in ioports.get(label, []): + raise RuntimeError( + f"circuitpython.toml [pins] name {name}: pad {pad} bonds gpio pad " + f"{gpio}, which is not on an enabled GPIO controller" + ) + pin_key = (label, gpio % 32) + previous_pins = pins_of_name.get(board_name, []) + if previous_pins and pin_key not in previous_pins: + previous = ", ".join(f"{label} pin {num}" for label, num in previous_pins) + raise RuntimeError( + f"circuitpython.toml [pins] name {name}: already maps to {previous}, " + f"but [pins] assigns it to {label} pin {gpio % 32}" + ) + if previous_pins: + # Same name already attached to this pin (devicetree or an + # earlier entry); nothing to add. + continue + pins_of_name[board_name] = [pin_key] + board_names.setdefault(pin_key, []).append(board_name) + return analog_board_names + + +def _toml_status_pin(mpconfigboard, board_names, key): + """Resolve a circuitpython.toml status pin key to its ``(ioport, num)``. + + The key's value is a board pin name (``[pins]`` entries and + devicetree-derived names alike, matched after sanitizing the same way). + Returns None when the key is absent; raises when the name is unknown. + """ + name = (mpconfigboard or {}).get(key) + if name is None: + return None + wanted = str(name).upper().replace(" ", "_").replace("-", "_") + for pin_key, names in board_names.items(): + if any(existing.upper() == wanted for existing in names): + return pin_key + raise RuntimeError(f"circuitpython.toml {key} = {name!r} is not a board pin name") + + +# The standard pins of each board bus. For example: +# +# "i2c [bus kind]": {"scl [pin field]": "SCL [pin name]", "sda [pin field]": "SDA [pin name]"}, +# +# - bus kind: board.I2C(), board.SPI() or board.UART(). The generated pin table +# for shared-module/board is named after it (CIRCUITPY_BOARD_I2C_PIN). +# - pin field: The corresponding name of the field in the struct holding the +# pins for the bus in shared-module/board/__init__.c. For instance, the `scl` +# field in the `board_i2c_pin_t` struct. +# - pin name: the standard board pin name whose pin goes in that field. A +# board's connector (see CONNECTORS) or its circuitpython.toml [pins] table +# gives its header pins these names. +BOARD_BUS_PINS = { + "i2c": {"scl": "SCL", "sda": "SDA"}, + "spi": {"clock": "SCK", "mosi": "MOSI", "miso": "MISO"}, + "uart": {"tx": "TX", "rx": "RX"}, +} +# The board bus kind for each busio driver kind. For example: +# +# "serial [driver kind]": "uart [bus kind]", +# +# - driver kind: a BUSIO_CLASSES key, the kind of devicetree device that a +# busio class uses ("serial" for busio.UART, after Zephyr's serial drivers). +# - bus kind: a BOARD_BUS_PINS key, the board bus that such devices provide +# ("uart" for board.UART()). +BOARD_BUS_OF_DRIVER = {"i2c": "i2c", "spi": "spi", "serial": "uart"} +# The pins of board.STEMMA_I2C, as fields of board_i2c_pin_t (see +# BOARD_BUS_PINS). The stemma-qt-connector entry in CONNECTORS names them. +STEMMA_I2C_PINS = {"scl": "STEMMA_SCL", "sda": "STEMMA_SDA"} + + +def _board_pin_named(board_names, name): + """Return the ``(ioport, num)`` of the board pin called ``name``, or None.""" + for pin_key, names in board_names.items(): + if any(existing.upper() == name for existing in names): + return pin_key + return None + + +def _named_pins(board_names, fields): + """Return ``{field: pin}`` for ``fields``, a ``{field: board pin name}`` + dict, or None if the board lacks any of the names. ``pin`` is an + ``(ioport, num)`` key of ``board_names``. + """ + pins = {field: _board_pin_named(board_names, name) for field, name in fields.items()} + if None in pins.values(): + return None + return pins + + +def _standard_bus_pins(board_names): + """Find the standard pins of each board bus class. + + A class has standard pins when the board names every pin it needs with + the standard names in BOARD_BUS_PINS. Returns ``{bus: {field: pin}}``. + """ + standard_pins = {} + for bus, fields in BOARD_BUS_PINS.items(): + pins = _named_pins(board_names, fields) + if pins is not None: + standard_pins[bus] = pins + return standard_pins + + +def _board_i2c_buses(i2c_pins, stemma_pins): + """Lay out the board I2C buses for board.I2C() and board.STEMMA_I2C. + + ``i2c_pins`` are board.I2C()'s pins and ``stemma_pins`` the STEMMA QT + connector's, each a ``{field: pin}`` dict or None. STEMMA_I2C is the same + bus as I2C when its connector uses the same pins, and its own bus + otherwise. Returns ``(buses, stemma_index)``: the pin dicts of the board + I2C buses, in instance order, and the instance that STEMMA_I2C names (or + None). + """ + buses = [i2c_pins] if i2c_pins else [] + if stemma_pins is None: + return buses, None + if stemma_pins not in buses: + buses.append(stemma_pins) + return buses, buses.index(stemma_pins) + + +def _node_enabled(node): + """Return True if a devicetree node's status is "okay" (or unset).""" + status = node.props.get("status") + return status is None or status.to_string() == "okay" + + +def _used_by_zephyr(device_tree, node): + """Return True if Zephyr itself uses a bus node. + + A bus is Zephyr's when a /chosen property points at it (such as the + zephyr,console UART), it has child device nodes (such as a flash chip), + or another enabled node refers to it by phandle (such as a display's + mipi-dbi node). + """ + for prop in device_tree.root.nodes["chosen"].props.values(): + try: + if prop.to_path() is node: + return True + except dtlib.DTError: + pass + if node.nodes: + return True + for other in device_tree.node_iter(): + if other is node or not _node_enabled(other): + continue + for prop in other.props.values(): + if prop.type == dtlib.Type.PHANDLE: + referenced = [prop.to_node()] + elif prop.type == dtlib.Type.PHANDLES: + referenced = prop.to_nodes() + else: + continue + if node in referenced: + return True + return False + + +def _toml_status_dotstar(mpconfigboard, board_names): + """Resolve the status DotStar's ``STATUS_DOTSTAR_DATA`` and + ``STATUS_DOTSTAR_CLOCK`` keys to a ``(data, clock)`` pair of pins. + + Returns None when neither key is present. Raises when only one is, or + when ``STATUS_NEOPIXEL`` is also set: the status LED code would use the + NeoPixel and ignore the DotStar. + """ + data = _toml_status_pin(mpconfigboard, board_names, "STATUS_DOTSTAR_DATA") + clock = _toml_status_pin(mpconfigboard, board_names, "STATUS_DOTSTAR_CLOCK") + if data is None and clock is None: + return None + if data is None or clock is None: + raise RuntimeError( + "circuitpython.toml needs both STATUS_DOTSTAR_DATA and STATUS_DOTSTAR_CLOCK" + ) + if (mpconfigboard or {}).get("STATUS_NEOPIXEL") is not None: + raise RuntimeError( + "circuitpython.toml sets both STATUS_NEOPIXEL and a status DotStar; use one" + ) + return data, clock + @cpbuild.run_in_thread -def zephyr_dts_to_cp_board(builddir, zephyrbuilddir): # noqa: C901 +def zephyr_dts_to_cp_board(board_id, portdir, builddir, zephyrbuilddir, mpconfigboard=None): # noqa: C901 board_dir = builddir / "board" # Auto generate board files from device tree. board_info = { "wifi": False, + "ethernet": False, "usb_device": False, + "_bleio": False, + # The native_sim board and its variant boards (asan, lfs, lvgl) all run + # on the host and can use the host's network stack. + "hostnetwork": board_id.startswith("native_sim"), + "audiobusio": False, + "neopixel_write": False, } + config_bt_enabled = False + config_bt_found = False + config_adc_enabled = False + config_dac_enabled = False + config_rtc_enabled = False + config_soc = None + config_present = True + config = zephyrbuilddir / ".config" + if not config.exists(): + config_present = False + else: + for line in config.read_text().splitlines(): + if line.startswith("CONFIG_BT="): + config_bt_enabled = line.strip().endswith("=y") + config_bt_found = True + elif line.startswith("# CONFIG_BT is not set"): + config_bt_enabled = False + config_bt_found = True + elif line.startswith("CONFIG_ADC="): + config_adc_enabled = line.strip().endswith("=y") + elif line.startswith("CONFIG_DAC="): + config_dac_enabled = line.strip().endswith("=y") + elif line.startswith("CONFIG_RTC="): + config_rtc_enabled = line.strip().endswith("=y") + elif line.startswith("CONFIG_SOC="): + config_soc = line.split("=", 1)[1].strip().strip('"') + runners = zephyrbuilddir / "runners.yaml" runners = yaml.safe_load(runners.read_text()) zephyr_board_dir = pathlib.Path(runners["config"]["board_dir"]) board_yaml = zephyr_board_dir / "board.yml" board_yaml = yaml.safe_load(board_yaml.read_text()) - board_info["vendor_id"] = board_yaml["board"]["vendor"] - vendor_index = zephyr_board_dir.parent / "index.rst" + if "board" not in board_yaml and "boards" in board_yaml: + for board in board_yaml["boards"]: + if board["name"] == board_id: + board_yaml = board + break + else: + board_yaml = board_yaml["board"] + board_info["vendor_id"] = board_yaml["vendor"] + # Most vendors put boards directly in boards//, but some group + # them further, like boards/silabs/dev_kits/. Walk up to the directory + # named for the vendor so we read the vendor's index.rst and not a category's. + vendor_dir = zephyr_board_dir.parent + for parent in zephyr_board_dir.parents: + if parent.name == board_info["vendor_id"]: + vendor_dir = parent + break + vendor_index = vendor_dir / "index.rst" if vendor_index.exists(): vendor_index = vendor_index.read_text() vendor_index = vendor_index.split("\n") @@ -116,40 +1032,67 @@ def zephyr_dts_to_cp_board(builddir, zephyrbuilddir): # noqa: C901 else: vendor_name = board_info["vendor_id"] board_info["vendor"] = vendor_name - soc_name = board_yaml["board"]["socs"][0]["name"] + soc_names = [soc["name"] for soc in board_yaml["socs"]] + soc_name = config_soc if config_soc in soc_names else soc_names[0] board_info["soc"] = soc_name - board_name = board_yaml["board"]["full_name"] + board_name = board_yaml["full_name"] + if mpconfigboard and "NAME" in mpconfigboard: + board_name = mpconfigboard["NAME"] board_info["name"] = board_name + # Banner board name: VENDOR + NAME when circuitpython.toml sets VENDOR, else just the name. + banner_name = board_name + if mpconfigboard and "VENDOR" in mpconfigboard: + banner_name = f"{mpconfigboard['VENDOR']} {board_name}" # board_id_yaml = zephyr_board_dir / (zephyr_board_dir.name + ".yaml") # board_id_yaml = yaml.safe_load(board_id_yaml.read_text()) # print(board_id_yaml) # board_name = board_id_yaml["name"] dts = zephyrbuilddir / "zephyr.dts" - edt_pickle = dtlib.DT(dts) + device_tree = dtlib.DT(dts) node2alias = {} - for alias in edt_pickle.alias2node: - node = edt_pickle.alias2node[alias] + for alias in device_tree.alias2node: + node = device_tree.alias2node[alias] if node not in node2alias: node2alias[node] = [] node2alias[node].append(alias) ioports = {} all_ioports = [] board_names = {} - flashes = [] - rams = [] status_led = None + status_led_inverted = False + boot_button = None + boot_button_active_high = False path2chosen = {} chosen2path = {} + + # Find flash and RAM regions using extracted functions + flashes = find_flash_devices(device_tree) + rams = find_ram_regions(device_tree) # Returns filtered and sorted list + + # Store active Zephyr device labels per-driver so that we can make them available via board. + active_zephyr_devices = {} usb_num_endpoint_pairs = 0 - for k in edt_pickle.root.nodes["chosen"].props: - value = edt_pickle.root.nodes["chosen"].props[k] + ble_hardware_present = False + adc_present = False + dac_present = False + for k in device_tree.root.nodes["chosen"].props: + value = device_tree.root.nodes["chosen"].props[k] path2chosen[value.to_path()] = k chosen2path[k] = value.to_path() - remaining_nodes = set([edt_pickle.root]) + + chosen_display = chosen2path.get("zephyr,display") + if chosen_display is not None: + status = chosen_display.props.get("status", None) + if status is None or status.to_string() == "okay": + board_info["zephyr_display"] = True + board_info["displayio"] = True + + # A list, not a set, so the nodes are visited in the same order every build. + remaining_nodes = [device_tree.root] while remaining_nodes: node = remaining_nodes.pop() - remaining_nodes.update(node.nodes.values()) + remaining_nodes.extend(node.nodes.values()) gpio = node.props.get("gpio-controller", False) gpio_map = node.props.get("gpio-map", []) status = node.props.get("status", None) @@ -161,52 +1104,23 @@ def zephyr_dts_to_cp_board(builddir, zephyrbuilddir): # noqa: C901 compatible = [] if "compatible" in node.props: compatible = node.props["compatible"].to_strings() - logger.debug(node.name, status) + logger.debug(f"{node.name}: {status}") + logger.debug(f"compatible: {compatible}") chosen = None if node in path2chosen: chosen = path2chosen[node] - logger.debug(" chosen:", chosen) + logger.debug(f" chosen: {chosen}") for c in compatible: underscored = c.replace(",", "_").replace("-", "_") - driver = COMPAT_TO_DRIVER.get(underscored, None) - if "mmio" in c: - logger.debug(" ", c, node.labels, node.props) - address, size = node.props["reg"].to_nums() - end = address + size - if chosen == "zephyr,sram": - start = "z_mapped_end" - elif "zephyr,memory-region" in node.props: - start = "__" + node.props["zephyr,memory-region"].to_string() + "_end" - else: - # Check to see if the chosen sram is a subset of this region. If it is, - # then do as above for a smaller region and assume the rest is reserved. - chosen_sram = chosen2path["zephyr,sram"] - chosen_address, chosen_size = chosen_sram.props["reg"].to_nums() - chosen_end = chosen_address + chosen_size - if address <= chosen_address <= end and address <= chosen_end <= end: - start = "z_mapped_end" - address = chosen_address - size = chosen_size - end = chosen_end - else: - start = address - info = (node.labels[0], start, end, size, node.path) - if chosen == "zephyr,sram": - rams.insert(0, info) - else: - rams.append(info) - if not driver: - driver = MANUAL_COMPAT_TO_DRIVER.get(underscored, None) - logger.debug(" ", underscored, driver) + driver = MANUAL_COMPAT_TO_DRIVER.get(underscored, None) if not driver: + driver = COMPAT_TO_DRIVER.get(underscored, None) + logger.debug(f" {c} -> {underscored} -> {driver}") + if not driver or status != "okay": continue - if driver == "flash" and status == "okay": - if not chosen and compatible[0] not in BLOCKED_FLASH_COMPAT: - # Skip chosen nodes because they are used by Zephyr. - flashes.append(f"DEVICE_DT_GET(DT_NODELABEL({node.labels[0]}))") - else: - logger.debug(" skipping due to blocked compat") - if driver == "usb/udc" and status == "okay": + if driver == "flash": + pass # Handled by find_flash_devices() + elif driver == "usb/udc" or "zephyr_udc0" in node.labels: board_info["usb_device"] = True props = node.props if "num-bidir-endpoints" not in props: @@ -220,8 +1134,55 @@ def zephyr_dts_to_cp_board(builddir, zephyrbuilddir): # noqa: C901 single_direction_endpoints.append(props[eps].to_num() if eps in props else 0) # Count separate in/out pairs as bidirectional. usb_num_endpoint_pairs += min(single_direction_endpoints) - if driver.startswith("wifi") and status == "okay": + elif driver.startswith("wifi"): board_info["wifi"] = True + elif driver.startswith("ethernet"): + board_info["ethernet"] = True + elif driver == "bluetooth/hci": + ble_hardware_present = True + elif driver in AUDIOBUSIO_CLASSES: + # audiobusio driver (i2s, audio/dmic) + board_info["audiobusio"] = True + logger.info(f"Supported audiobusio driver: {driver}") + if driver not in active_zephyr_devices: + active_zephyr_devices[driver] = [] + active_zephyr_devices[driver].append(node.labels) + elif driver == "input": + board_info["zephyr_input"] = True + logger.info("Supported Zephyr input device: %s", underscored) + elif driver in EXCEPTIONAL_DRIVERS: + pass + elif driver in BUSIO_CLASSES: + # busio driver (i2c, spi, uart) + board_info["busio"] = True + if driver == "spi": + board_info["async_spi"] = True + logger.info(f"Supported busio driver: {driver}") + if driver not in active_zephyr_devices: + active_zephyr_devices[driver] = [] + active_zephyr_devices[driver].append(node.labels) + elif driver == "pwm": + # PWM instances are allocated at runtime through iobroker + # for neopixel_write and pwmio; no board singleton. + logger.info(f"Supported pwm driver: {driver}") + if driver not in active_zephyr_devices: + active_zephyr_devices[driver] = [] + active_zephyr_devices[driver].append(node.labels) + elif driver in ("adc", "dac"): + # Analog peripherals: analogio is only enabled for the + # compatibles it implements (the SoC ADCs iobroker can resolve + # to their fixed analog inputs, and the emulated devices); + # external sensor ADC chips are not pad-addressable. + if underscored in ANALOG_COMPAT: + if driver == "adc": + adc_present = True + else: + dac_present = True + logger.info(f"Supported analog driver: {underscored}") + else: + logger.debug(f"Analog driver without analogio support: {underscored}") + else: + logger.warning(f"Unsupported driver: {driver}") if gpio: if "ngpios" in node.props: @@ -230,23 +1191,61 @@ def zephyr_dts_to_cp_board(builddir, zephyrbuilddir): # noqa: C901 ngpios = 32 all_ioports.append(node.labels[0]) if status == "okay": - ioports[node.labels[0]] = set(range(0, ngpios)) - if gpio_map: - i = 0 - for offset, t, label in gpio_map._markers: - if not label: - continue - num = int.from_bytes(gpio_map.value[offset + 4 : offset + 8], "big") - if (label, num) not in board_names: - board_names[(label, num)] = [] - board_names[(label, num)].append(CONNECTORS[compatible[0]][i]) - i += 1 + ioports[node.labels[0]] = range(0, ngpios) + if gpio_map and compatible and compatible[0] != "gpio-nexus": + # Per-board connector names from circuitpython.toml's + # ``[connectors.]`` table take precedence. They key the + # gpio-map position (the header pin number as a string) to a name + # or a list of names, so boards whose silkscreen differs from the + # generic per-compatible list can supply their own. + connector_override = None + if node.labels: + connector_override = ( + (mpconfigboard or {}).get("connectors", {}).get(node.labels[0]) + ) + connector_pins = ( + connector_override + if connector_override is not None + else CONNECTORS.get(compatible[0], None) + ) + if connector_pins is None: + logger.warning(f"Unsupported connector mapping compatible: {compatible[0]}") + else: + i = 0 + for offset, t, label in gpio_map._markers: + if not label: + continue + num = int.from_bytes(gpio_map.value[offset + 4 : offset + 8], "big") + if isinstance(connector_pins, dict): + pin_entry = connector_pins.get(str(i)) + if pin_entry is None: + logger.debug( + f"Connector {node.labels[0]} position {i} has no name; skipping" + ) + i += 1 + continue + else: + if i >= len(connector_pins): + logger.warning( + f"Connector mapping for {compatible[0]} has more pins than names; " + f"stopping at {len(connector_pins)}" + ) + break + pin_entry = connector_pins[i] + if (label, num) not in board_names: + board_names[(label, num)] = [] + if isinstance(pin_entry, list): + board_names[(label, num)].extend(pin_entry) + else: + board_names[(label, num)].append(pin_entry) + i += 1 if "gpio-leds" in compatible: for led in node.nodes: led = node.nodes[led] props = led.props ioport = props["gpios"]._markers[1][2] num = int.from_bytes(props["gpios"].value[4:8], "big") + flags = int.from_bytes(props["gpios"].value[8:12], "big") if "label" in props: if (ioport, num) not in board_names: board_names[(ioport, num)] = [] @@ -257,88 +1256,812 @@ def zephyr_dts_to_cp_board(builddir, zephyrbuilddir): # noqa: C901 if "led0" in node2alias[led]: board_names[(ioport, num)].append("LED") status_led = (ioport, num) + status_led_inverted = flags & GPIO_ACTIVE_LOW board_names[(ioport, num)].extend(node2alias[led]) if "gpio-keys" in compatible: for key in node.nodes: - props = node.nodes[key].props + key_node = node.nodes[key] + props = key_node.props ioport = props["gpios"]._markers[1][2] num = int.from_bytes(props["gpios"].value[4:8], "big") + flags = int.from_bytes(props["gpios"].value[8:12], "big") + active_high = not (flags & GPIO_ACTIVE_LOW) if (ioport, num) not in board_names: board_names[(ioport, num)] = [] - board_names[(ioport, num)].append(props["label"].to_string()) - if key in node2alias: - if "sw0" in node2alias[key]: + # `label` is optional and deprecated on gpio-keys. Modern + # boards identify keys with `zephyr,code`, so fall back to the + # name of that code. + if "label" in props: + board_names[(ioport, num)].append(props["label"].to_string()) + elif "zephyr,code" in props: + key_code = props["zephyr,code"].to_num() + if key_code in INPUT_KEY_NAMES: + board_names[(ioport, num)].append(INPUT_KEY_NAMES[key_code]) + if key_node in node2alias: + aliases = node2alias[key_node] + if "sw0" in aliases: board_names[(ioport, num)].append("BUTTON") - board_names[(ioport, num)].extend(node2alias[key]) - - a, b = all_ioports[:2] - i = 0 - while a[i] == b[i]: - i += 1 - shared_prefix = a[:i] - for ioport in ioports: - if not ioport.startswith(shared_prefix): - shared_prefix = "" - break + # The sw0 alias designates the conventional first user + # button, so prefer it as the boot button. + boot_button = (ioport, num) + boot_button_active_high = active_high + board_names[(ioport, num)].extend(aliases) + # Default to the first button in device tree order when no sw0 + # alias has designated one yet. + if boot_button is None: + boot_button = (ioport, num) + boot_button_active_high = active_high + + if len(all_ioports) > 1: + a, b = all_ioports[:2] + i = 0 + max_i = min(len(a), len(b)) + while i < max_i and a[i] == b[i]: + i += 1 + shared_prefix = a[:i] + for ioport in ioports: + if not ioport.startswith(shared_prefix): + shared_prefix = "" + break + elif all_ioports: + shared_prefix = all_ioports[0] + else: + shared_prefix = "" pin_defs = [] pin_declarations = ["#pragma once"] mcu_pin_mapping = [] board_pin_mapping = [] + # Hardware port index of each GPIO controller; it defines the global pin + # numbering (index * 32 + pin) that pin objects and the iobroker module + # both use. On nRF SoCs the index comes from the label digits (gpio0 -> + # port 0, gpio6 -> port 6). Virtual GPIO controllers, such as the + # infineon,cyw43-gpio on the Pico 2 W, get the lowest unused index so they + # never collide with a numbered controller. + port_indexes = {} + used_indexes = set() + for label in sorted(ioports.keys()): + match = re.match(r"^gpio(\d+)$", label) + if match: + port_indexes[label] = int(match.group(1)) + used_indexes.add(port_indexes[label]) + for label in sorted(ioports.keys()): + if label in port_indexes: + continue + index = 0 + while index in used_indexes: + index += 1 + port_indexes[label] = index + used_indexes.add(index) + # Package pin map selected through the IOBROKER_PACKAGE choice: the pin + # objects, their package pins and the reserved pads all come from the + # iobroker package data. Pads are numbered by the package's pin ids + # (row-major ball order, or the datasheet's pin number for a QFN/QFP + # package); a pad bonded to a GPIO controller carries its global GPIO + # number (port index * 32 + pin). The 1:1 choice is an identity map (pad + # == package pin == GPIO number); IOBROKER_PACKAGE_NONE has no map, so + # every pin object gets IOBROKER_NO_PIN. + package_pin_of_pad = {} + gpio_pad_of_pad = {} + # Datasheet pad name of every mapped pad (e.g. "P0.02", "ANA_0"): the + # pin objects take their names from these. + pad_name_of_pad = {} + package_pins = None + package_choice = None + if config_present: + for line in config.read_text().splitlines(): + stripped = line.strip() + if not stripped.startswith("CONFIG_IOBROKER_PACKAGE_") or not stripped.endswith("=y"): + continue + package_choice = stripped[len("CONFIG_IOBROKER_PACKAGE_") : -len("=y")].lower() + break + if package_choice == "one_to_one": + # Identity map over the enabled GPIO controllers. + package_pins = [] + for ioport in sorted(ioports.keys()): + for num in ioports[ioport]: + global_number = port_indexes[ioport] * 32 + num + pin_object_name = f"P{ioport[len(shared_prefix) :].upper()}_{num:02d}" + package_pins.append( + { + "pin": global_number, + "pad": global_number, + "pad_name": pin_object_name, + "gpio": global_number, + } + ) + package_pin_of_pad[global_number] = global_number + gpio_pad_of_pad[global_number] = global_number + pad_name_of_pad[global_number] = pin_object_name + elif package_choice not in (None, "none"): + package_toml = ( + pathlib.Path(__file__).resolve().parent.parent + / "internal-modules" + / "iobroker" + / "packages" + / f"{package_choice}.toml" + ) + with package_toml.open("rb") as f: + package = tomllib.load(f) + package_pins = package["pins"] + for package_pin_entry in package_pins: + if "pad_name" not in package_pin_entry and "pad" not in package_pin_entry: + # Informational module pin (e.g. bonded to GND): it + # carries no SoC pad, so it maps nothing. + continue + pad = package_pin_entry.get("pad", package_pin_entry["pin"]) + package_pin_of_pad[pad] = package_pin_entry["pin"] + if "pad_name" in package_pin_entry: + pad_name_of_pad[pad] = package_pin_entry["pad_name"] + if "gpio" in package_pin_entry: + gpio_pad_of_pad[pad] = package_pin_entry["gpio"] + # Pads no package pin names (GPIO pads whose controller is missing from + # the map or pads the board enables beyond the package): they get pin + # objects named after the GPIO controller with an IOBROKER_NO_PIN + # package pin, like boards without an iobroker package always had. + # Board pin names from circuitpython.toml: ``[pins]`` maps a board module + # name to a package pin number or ball id, resolved to a SoC pad with + # the package pin map above. This is independent of Zephyr's devicetree + # labels and aliases. Pads with no GPIO bond (the map's analog-only + # pads) get their names back keyed by pad; their pin objects are + # created below from the map's datasheet pad names. + analog_board_names = add_toml_pin_names( + board_names, + mpconfigboard, + package_pins, + package_choice, + port_indexes, + ioports, + pad_name_of_pad, + gpio_pad_of_pad, + ) + # Status NeoPixel from circuitpython.toml: ``STATUS_NEOPIXEL`` (and the + # optional ``STATUS_NEOPIXEL_POWER``) name a board pin, usually one from + # the [pins] table, that the status LED code drives with neopixel_write. + status_neopixel = _toml_status_pin(mpconfigboard, board_names, "STATUS_NEOPIXEL") + status_neopixel_power = _toml_status_pin(mpconfigboard, board_names, "STATUS_NEOPIXEL_POWER") + pinctrl_nrf = False + pwm_nrfx = False + pwm_emul = False + if config_present: + for line in config.read_text().splitlines(): + if line.startswith("CONFIG_PINCTRL_NRF="): + pinctrl_nrf = line.strip().endswith("=y") + elif line.startswith("CONFIG_PWM_NRFX="): + # Zephyr's nRF PWM driver defines the PWM instance devices. + # Without it, PWM nodes have no device to reference, and + # neopixel_write (the neopixel module's nRF implementation, + # which allocates an instance through iobroker) cannot transmit, so + # both the pwm pool and the module follow this symbol. pwmio + # allocates its channels through iobroker's nRF implementation + # too. + pwm_nrfx = line.strip().endswith("=y") + elif line.startswith("CONFIG_PWM_ADAFRUIT_EMUL="): + # The emulated PWM controllers on native_sim (pwm_emul + # module), which iobroker allocates pwmio channels on too. + pwm_emul = line.strip().endswith("=y") + board_info["neopixel_write"] = pwm_nrfx + standard_bus_pins = _standard_bus_pins(board_names) + stemma_i2c_pins = _named_pins(board_names, STEMMA_I2C_PINS) + pin_object_of = {} + # Status DotStar: ``STATUS_DOTSTAR_DATA`` and ``STATUS_DOTSTAR_CLOCK``, + # driven by the status LED code with bit-banged SPI. + status_dotstar = _toml_status_dotstar(mpconfigboard, board_names) + # GPIO pad number -> pad: every (label, num) name and alias the + # devicetree walk produced keys into one pin object per pad. + pad_of_gpio = {} + for pad, gpio in gpio_pad_of_pad.items(): + if gpio in pad_of_gpio and pad_of_gpio[gpio] != pad: + logger.warning( + f"package pin maps {pad_of_gpio[gpio]} and {pad} both bond gpio pad {gpio}" + ) + continue + pad_of_gpio[gpio] = pad + # Pin object names, deduplicated: two pads with the same datasheet name + # would produce two MP_QSTR bindings for one name. + pin_name_of_pad = {} + seen_pin_names = {} + for pad, name in pad_name_of_pad.items(): + pin_object_name = ( + name.upper() + .replace(".", "_") + .replace(" ", "_") + .replace("-", "_") + .replace("(", "") + .replace(")", "") + ) + if not re.match(r"^[A-Z][A-Z0-9_]*$", pin_object_name): + logger.warning( + f"pad {pad} has unusable pad name {name!r} in the package " + f"pin map; its pin object is skipped" + ) + continue + if pin_object_name in seen_pin_names: + raise RuntimeError( + f"package pin map: pads {seen_pin_names[pin_object_name]} and {pad} " + f"both carry pad name {name!r}" + ) + seen_pin_names[pin_object_name] = pad + pin_name_of_pad[pad] = pin_object_name for ioport in sorted(ioports.keys()): for num in ioports[ioport]: - pin_object_name = f"P{ioport[len(shared_prefix) :].upper()}_{num:02d}" + gpio = port_indexes[ioport] * 32 + num + pad = pad_of_gpio.get(gpio) + if pad is not None: + pin_object_name = pin_name_of_pad.get(pad) + if pin_object_name is None: + continue + package_pin = package_pin_of_pad[pad] + package_pin_init = str(package_pin) + else: + # Unbonded GPIO pad: no package pin; keep the object for + # devicetree names, with a disconnected package pin. + pin_object_name = f"P{ioport[len(shared_prefix) :].upper()}_{num:02d}" + package_pin_init = "IOBROKER_NO_PIN" if status_led and (ioport, num) == status_led: status_led = pin_object_name + if boot_button and (ioport, num) == boot_button: + boot_button = pin_object_name + if status_neopixel and (ioport, num) == status_neopixel: + status_neopixel = pin_object_name + if status_neopixel_power and (ioport, num) == status_neopixel_power: + status_neopixel_power = pin_object_name + pin_object_of[(ioport, num)] = pin_object_name + if status_dotstar: + status_dotstar = tuple( + pin_object_name if pin == (ioport, num) else pin for pin in status_dotstar + ) pin_defs.append( - f"const mcu_pin_obj_t pin_{pin_object_name} = {{ .base.type = &mcu_pin_type, .port = DEVICE_DT_GET(DT_NODELABEL({ioport})), .number = {num}}};" + f"const mcu_pin_obj_t pin_{pin_object_name} = {{ .base.type = &mcu_pin_type, .package_pin = {package_pin_init}}};" ) pin_declarations.append(f"extern const mcu_pin_obj_t pin_{pin_object_name};") mcu_pin_mapping.append( f"{{ MP_ROM_QSTR(MP_QSTR_{pin_object_name}), MP_ROM_PTR(&pin_{pin_object_name}) }}," ) - board_pin_names = board_names.get((ioport, num), []) - + # A pin prints as its first board name, so list the STEMMA QT + # names last: board.SCL should print as board.SCL, not + # board.STEMMA_SCL. + board_pin_names = sorted( + board_names.get((ioport, num), []), + key=lambda name: name.upper() in STEMMA_I2C_PINS.values(), + ) for board_pin_name in board_pin_names: - board_pin_name = board_pin_name.upper().replace(" ", "_").replace("-", "_") + board_pin_name = ( + board_pin_name.upper() + .replace(" ", "_") + .replace("-", "_") + .replace("(", "") + .replace(")", "") + ) board_pin_mapping.append( f"{{ MP_ROM_QSTR(MP_QSTR_{board_pin_name}), MP_ROM_PTR(&pin_{pin_object_name}) }}," ) + # Pin objects for the package map's analog-only pads (pads with no GPIO + # bond, e.g. MCX N's ANA pads), keyed by pad: they are named by their + # datasheet pad name and reach the outside world only through the + # analog APIs, which take package pins. + for pad in sorted(analog_board_names): + pin_object_name = pin_name_of_pad.get(pad) + if pin_object_name is None: + continue + pin_defs.append( + f"const mcu_pin_obj_t pin_{pin_object_name} = {{ .base.type = &mcu_pin_type, .package_pin = {package_pin_of_pad[pad]}}};" + ) + pin_declarations.append(f"extern const mcu_pin_obj_t pin_{pin_object_name};") + mcu_pin_mapping.append( + f"{{ MP_ROM_QSTR(MP_QSTR_{pin_object_name}), MP_ROM_PTR(&pin_{pin_object_name}) }}," + ) + for board_pin_name in analog_board_names[pad]: + board_pin_mapping.append( + f"{{ MP_ROM_QSTR(MP_QSTR_{board_pin_name}), MP_ROM_PTR(&pin_{pin_object_name}) }}," + ) + pin_defs = "\n".join(pin_defs) pin_declarations = "\n".join(pin_declarations) board_pin_mapping = "\n ".join(board_pin_mapping) mcu_pin_mapping = "\n ".join(mcu_pin_mapping) + # Bus instances the board enabled with all-disconnected pins are routed to + # arbitrary pins at runtime by busio objects instead of being exposed as + # fixed board.X() singletons. For now only nRF has iobroker routing. Other + # SoCs' pinctrl states have no psels, so all() of the empty list would + # wrongly mark every one of their buses as routable. + # + # TODO: add iobroker routing for the non-nRF SoCs. + iobroker_labels = set() + if pinctrl_nrf: + for driver in BUSIO_CLASSES: + for labels in active_zephyr_devices.get(driver, []): + node = device_tree.label2node[labels[0]] + psels = _pinctrl_default_psels(node) + if psels is not None and all( + (value & NRF_PIN_FIELD_MASK) == NRF_PIN_FIELD_MASK for value in psels + ): + iobroker_labels.add(labels[0]) + + # The zephyr,console and zephyr,shell-uart UARTs belong to Zephyr, so they + # are never board objects. + chosen_props = device_tree.root.nodes["chosen"].props + console_nodes = [ + chosen_props[name].to_path() + for name in ("zephyr,console", "zephyr,shell-uart") + if name in chosen_props + ] + + # A board either routes its I2C, SPI and UART buses with iobroker (nRF + # boards with routable instances) or has only fixed buses from the + # devicetree. + # + # - With iobroker, board.I2C(), board.SPI() and board.UART() are buses on + # the board's standard pins, and iobroker picks the instance when the + # bus is constructed. Fixed bus instances are never board objects, and + # only Zephyr may use them (see _used_by_zephyr()). + # - With only fixed buses, the board objects are fixed instances (below). + uses_iobroker = pinctrl_nrf and any( + labels[0] in iobroker_labels + for driver in BOARD_BUS_OF_DRIVER + for labels in active_zephyr_devices.get(driver, []) + ) + # The pin dicts of each kind's board buses, in instance order. + board_buses = {} + stemma_i2c_index = None + if uses_iobroker: + for driver, bus in BOARD_BUS_OF_DRIVER.items(): + instances = active_zephyr_devices.get(driver, []) + for labels in instances: + node = device_tree.label2node[labels[0]] + if labels[0] not in iobroker_labels and not _used_by_zephyr(device_tree, node): + message = ( + f"devicetree node {labels[0]} is a fixed {driver} instance, but the " + "board routes its buses with iobroker: make it dynamic (all pins " + "disconnected, zephyr,deferred-init) or disable it" + ) + # The build's TaskGroup reports only that a task failed, + # so log the reason too. + logger.error(message) + raise RuntimeError(message) + if not any(labels[0] in iobroker_labels for labels in instances): + continue + if bus == "i2c": + buses, stemma_i2c_index = _board_i2c_buses( + standard_bus_pins.get("i2c"), stemma_i2c_pins + ) + if buses: + board_buses["i2c"] = buses + elif bus in standard_bus_pins: + board_buses[bus] = [standard_bus_pins[bus]] + + zephyr_binding_headers = [] + zephyr_binding_objects = [] + zephyr_binding_labels = [] + i2sout_instance_names = [] + for driver, instances in active_zephyr_devices.items(): + # Determine if this is busio or audiobusio + if driver in BUSIO_CLASSES: + module = "busio" + driverclass = BUSIO_CLASSES[driver] + elif driver in AUDIOBUSIO_CLASSES: + module = "audiobusio" + driverclass = AUDIOBUSIO_CLASSES[driver] + else: + continue + + zephyr_binding_headers.append(f'#include "shared-bindings/{module}/{driverclass}.h"') + + # A board has at most one object per class, under the class's + # standard name (board.I2C, board.I2SOUT, ...). Other fixed instances + # are not board objects. + bus = BOARD_BUS_OF_DRIVER.get(driver) + candidates = [ + labels + for labels in instances + if labels[0] not in iobroker_labels + and device_tree.label2node[labels[0]] not in console_nodes + ] + main = None + if uses_iobroker and bus is not None: + # The board bus, if any, has the standard name. + pass + elif len(candidates) == 1: + main = candidates[0] + else: + # A label picks the main instance. + for priority_label in (driverclass, f"zephyr_{driver}", f"arduino_{driver}"): + main = next((labels for labels in candidates if priority_label in labels), None) + if main is not None: + break + # The board names of each instance that gets a board object. + names_of = {} + if main is not None: + names_of[main[0]] = [driverclass.upper()] + # On an all-static board with a STEMMA QT (or Qwiic) connector, + # board.STEMMA_I2C is the instance labeled zephyr_i2c, Zephyr's label + # for the bus wired to such connectors. Its pins aren't compared + # with the connector's: that would mean decoding each SoC's pinctrl. + if driver == "i2c" and not uses_iobroker and stemma_i2c_pins is not None: + stemma = next((labels for labels in candidates if "zephyr_i2c" in labels), None) + if stemma is not None: + names_of.setdefault(stemma[0], []).append("STEMMA_I2C") + for label, names in names_of.items(): + instance_name = f"{driver.replace('/', '_')}_{label}" + c_function_name = f"_{instance_name}" + singleton_ptr = f"{c_function_name}_singleton" + function_object = f"{c_function_name}_obj" + obj_type = f"{module}_{driverclass.lower()}" + + # Handle special cases for different drivers + if driver == "serial": + # UART needs a receiver buffer + buffer_decl = f"static byte {instance_name}_buffer[128];" + construct_call = f"common_hal_busio_uart_construct_from_device(&{instance_name}_obj, DEVICE_DT_GET(DT_NODELABEL({label})), 128, {instance_name}_buffer, false)" + else: + # Default case (I2C, SPI, I2S) + buffer_decl = "" + construct_call = f"common_hal_{module}_{driverclass.lower()}_construct_from_device(&{instance_name}_obj, DEVICE_DT_GET(DT_NODELABEL({label})))" + + if driver == "i2s": + i2sout_instance_names.append(instance_name) + + zephyr_binding_objects.append( + f"""{buffer_decl} +static {obj_type}_obj_t {instance_name}_obj; +static mp_obj_t {singleton_ptr} = mp_const_none; +static mp_obj_t {c_function_name}(void) {{ + if ({singleton_ptr} != mp_const_none && !common_hal_{obj_type}_deinited(&{instance_name}_obj)) {{ + return {singleton_ptr}; + }} + {singleton_ptr} = {construct_call}; + return {singleton_ptr}; +}} +static MP_DEFINE_CONST_FUN_OBJ_0({function_object}, {c_function_name});""".lstrip() + ) + for name in names: + zephyr_binding_labels.append( + f"{{ MP_ROM_QSTR(MP_QSTR_{name}), MP_ROM_PTR(&{function_object}) }}," + ) + zephyr_binding_headers = "\n".join(zephyr_binding_headers) + zephyr_binding_objects = "\n".join(zephyr_binding_objects) + zephyr_binding_labels = "\n".join(zephyr_binding_labels) + + # Board buses: the CIRCUITPY_BOARD_* pin tables for shared-module/board, + # and the board name for each bus. board.I2C(), board.SPI() and + # board.UART() are instance 0 when the board has their standard pins. + # board.STEMMA_I2C is the same object as board.I2C() when it uses the + # same pins, and its own I2C instance otherwise. + board_bus_defines = [] + board_bus_objects = [] + board_bus_labels = [] + for bus, buses in board_buses.items(): + tables = ", ".join( + "{" + + ", ".join(f".{field} = &pin_{pin_object_of[pin]}" for field, pin in pins.items()) + + "}" + for pins in buses + ) + board_bus_defines.append(f"#define CIRCUITPY_BOARD_{bus.upper()} ({len(buses)})") + board_bus_defines.append(f"#define CIRCUITPY_BOARD_{bus.upper()}_PIN {{{tables}}}") + if bus in standard_bus_pins: + board_bus_labels.append( + f"{{ MP_ROM_QSTR(MP_QSTR_{bus.upper()}), MP_ROM_PTR(&board_{bus}_obj) }}," + ) + if stemma_i2c_index == 0: + board_bus_labels.append("{ MP_ROM_QSTR(MP_QSTR_STEMMA_I2C), MP_ROM_PTR(&board_i2c_obj) },") + elif stemma_i2c_index is not None: + board_bus_objects.append( + f"CIRCUITPY_BOARD_BUS_SINGLETON(stemma_i2c, i2c, {stemma_i2c_index})" + ) + board_bus_labels.append( + "{ MP_ROM_QSTR(MP_QSTR_STEMMA_I2C), MP_ROM_PTR(&board_stemma_i2c_obj) }," + ) + board_bus_defines = "\n".join(board_bus_defines) + board_bus_objects = "\n".join(board_bus_objects) + board_bus_labels = "\n".join(board_bus_labels) + + # Generate tables of allocatable bus instances for the iobroker + # Zephyr module (dynamic pin routing; nRF SoCs). Instances enabled with + # all-disconnected pinctrl can be routed to arbitrary pins at runtime; + # instances with fixed devicetree pins are only usable when the requested + # pins match their state. + board_info["pwmio"] = pwm_nrfx or pwm_emul + + iobroker_includes = """ +#include +#include +""" + + iobroker_tables = "" + table_parts = [] + + # Map GPIO controller devices to their hardware port index. The indexes + # define the global pin numbering shared by the pin objects and the + # iobroker module, which resolves a global number back to the + # controller device and pin within it. Boards without GPIO controllers + # generate an empty table so that gpio_split() returns -EINVAL. + if ioports: + devices = ", ".join( + f"DEVICE_DT_GET(DT_NODELABEL({label}))" for label in sorted(ioports.keys()) + ) + indexes = ", ".join(str(port_indexes[label]) for label in sorted(ioports.keys())) + addrs = ", ".join(_reg_addr_expr(device_tree, label) for label in sorted(ioports.keys())) + count = len(port_indexes) + else: + devices = "NULL" + indexes = "0" + addrs = "0" + count = 0 + table_parts.append( + f""" +const struct device * const iobroker_gpio_port_devices[] = {{ {devices} }}; +const uint8_t iobroker_gpio_port_indexes[] = {{ {indexes} }}; +const uint32_t iobroker_gpio_port_addrs[] = {{ {addrs} }}; +const size_t iobroker_gpio_port_count = {count}; +""" + ) + + if pinctrl_nrf: + pool_kinds = (("i2c", "i2c"), ("spi", "spi"), ("serial", "uart"), ("pwm", "pwm")) + bus_table_parts = [] + for driver, pool in pool_kinds: + dynamic_entries = [] + fixed_entries = [] + # PWM instances only exist as devices when the driver is built. + instances = ( + active_zephyr_devices.get(driver, []) if driver != "pwm" or pwm_nrfx else [] + ) + nodes = _fastest_first(device_tree.label2node[labels[0]] for labels in instances) + for node in nodes: + label = node.labels[0] + if node in path2chosen: + # Console and other system devices are not allocatable. + continue + psels = _pinctrl_default_psels(node) + if psels is None or len(psels) > 4: + continue + if all((value & NRF_PIN_FIELD_MASK) == NRF_PIN_FIELD_MASK for value in psels): + dynamic_entries.append((label, None, 0)) + else: + fixed_entries.append((label, psels, len(psels))) + + entries = dynamic_entries + fixed_entries + + # Always define all four pools, even when empty: iobroker.c and + # the nRF routing code reference every pool's tables whenever + # CONFIG_PINCTRL_NRF is on, so an empty pool is still an empty + # array plus a zero count. + if not entries: + bus_table_parts.append( + "const iobroker_instance_t" + f" iobroker_{pool}_buses[] = {{}};\n" + "iobroker_state_t" + f" iobroker_{pool}_bus_states[ARRAY_SIZE(iobroker_{pool}_buses)];\n" + "const size_t" + f" iobroker_{pool}_bus_count = ARRAY_SIZE(iobroker_{pool}_buses);" + ) + continue + + entry_lines = [] + psel_arrays = [] + declares = [] + for label, psels, count in entries: + declares.append(f"PINCTRL_DT_DEV_CONFIG_DECLARE(DT_NODELABEL({label}));") + entry = ( + f" {{ .dev = DEVICE_DT_GET(DT_NODELABEL({label})), " + f".reg_addr = {_reg_addr_expr(device_tree, label)}, " + f".pcfg = PINCTRL_DT_DEV_CONFIG_GET(DT_NODELABEL({label}))" + ) + if psels is not None: + values = ", ".join(hex(value) for value in psels) + psel_arrays.append( + f"static const pinctrl_soc_pin_t cp_{label}_dt_psels[] = {{ {values} }};" + ) + entry += f", .dt_psels = cp_{label}_dt_psels, .dt_psel_count = {count}" + entry += " }," + entry_lines.append(entry) + + bus_table_parts.append( + "\n".join(declares) + + "\n\n" + + "\n".join(psel_arrays) + + f"\nconst iobroker_instance_t iobroker_{pool}_buses[] = {{\n" + + "\n".join(entry_lines) + + "\n};\n" + + f"iobroker_state_t iobroker_{pool}_bus_states[ARRAY_SIZE(iobroker_{pool}_buses)];\n" + + f"const size_t iobroker_{pool}_bus_count = ARRAY_SIZE(iobroker_{pool}_buses);" + ) + + iobroker_tables = ( + "#if defined(CONFIG_PINCTRL)\n" + "#include \n" + + "\n\n".join(bus_table_parts) + + "\n#endif // CONFIG_PINCTRL" + ) + + if pinctrl_nrf: + # Pads claimed at boot by fixed peripherals (console UART, flash + # instance, I2S, ...): their devicetree pinctrl "default" state points + # at real pads. iobroker reports these pads as always in use so that + # allocate() rejects requests for them with -EBUSY instead of + # re-routing pads that something else is already driving. Dynamically + # routable instances have all-disconnected default states and + # contribute nothing here. The pads are iobroker package pads: the + # devicetree psels carry global GPIO numbers, so translate through + # the package map; pads without a package pin stay unrestricted + # (they are unreachable through the package pin APIs). + reserved_pads = set() + for instances in active_zephyr_devices.values(): + for labels in instances: + node = device_tree.label2node[labels[0]] + psels = _pinctrl_default_psels(node) + if psels is None: + continue + for value in psels: + gpio = value & NRF_PIN_FIELD_MASK + if gpio == NRF_PIN_FIELD_MASK: + continue + pad = pad_of_gpio.get(gpio) + if pad is not None: + reserved_pads.add(pad) + # Always emit the table, even when empty: iobroker.c references it + # whenever CONFIG_PINCTRL_NRF is on, so an empty set is still an + # empty array plus a zero count. + pads = ", ".join(str(pad) for pad in sorted(reserved_pads)) + reserved_table = ( + "const uint16_t iobroker_reserved_pads[] = { " + pads + " };\n" + "const size_t iobroker_reserved_pads_count = " + f"{len(reserved_pads)};" + ) + iobroker_tables = ( + "#if defined(CONFIG_PINCTRL)\n" + "#include \n" + + "\n\n".join(bus_table_parts + [reserved_table]) + + "\n#endif // CONFIG_PINCTRL" + ) + + if table_parts: + iobroker_tables = iobroker_tables + "\n\n" + "\n\n".join(table_parts) + + # Generate i2sout_reset() that stops the board's I2SOut objects. It is + # generated even when there are none, because reset_port() calls it on + # every board with audiobusio.I2SOut. + stop_calls = "\n ".join( + f"common_hal_audiobusio_i2sout_stop(&{name}_obj);" for name in i2sout_instance_names + ) + # And i2sout_gc_collect(): the board's I2SOut objects are static, so the GC doesn't scan them. + collect_calls = "\n ".join( + f"audiobusio_i2sout_collect_ptrs(&{name}_obj);" for name in i2sout_instance_names + ) + i2sout_reset_func = f""" +void i2sout_reset(void) {{ + {stop_calls} +}} + +void i2sout_gc_collect(void) {{ + {collect_calls} +}}""" + + zephyr_display_header = "" + zephyr_display_init = "" + zephyr_display_board_entry = "" + if board_info.get("zephyr_display", False): + zephyr_display_header = """ +#include +#include +#include "shared-module/displayio/__init__.h" +#include "bindings/zephyr_display/Display.h" + """.strip() + zephyr_display_init = """ +#if CIRCUITPY_ZEPHYR_DISPLAY && DT_HAS_CHOSEN(zephyr_display) + // Always allocate a display slot so board.DISPLAY is at least a valid + // NoneType object even if the underlying Zephyr display is unavailable. + primary_display_t *display_obj = allocate_display(); + if (display_obj != NULL) { + zephyr_display_display_obj_t *display = &display_obj->zephyr_display; + display->base.type = &mp_type_NoneType; + + const struct device *display_dev = device_get_binding(DEVICE_DT_NAME(DT_CHOSEN(zephyr_display))); + if (display_dev != NULL && device_is_ready(display_dev)) { + display->base.type = &zephyr_display_display_type; + common_hal_zephyr_display_display_construct_from_device(display, display_dev, 0, true); + } + } +#endif + """.strip() + zephyr_display_board_entry = """ +{ MP_ROM_QSTR(MP_QSTR_DISPLAY), MP_ROM_PTR(&displays[0].zephyr_display) }, + """.strip() + + ethernet_init = "" + ethernet_static_obj = "" + if board_info.get("ethernet", False): + ethernet_init = """ +#if CIRCUITPY_MII + common_hal_mii_ethernet_construct(ðernet_obj, NULL); + mii_set_default_instance(ðernet_obj); +#endif + """.strip() + + ethernet_static_obj = """#if CIRCUITPY_MII +// The board owns this instance; the supervisor reaches the default instance +// that board_init registers. +static mii_ethernet_obj_t ethernet_obj; +#endif +""" + board_dir.mkdir(exist_ok=True, parents=True) header = board_dir / "mpconfigboard.h" if status_led: status_led = f"#define MICROPY_HW_LED_STATUS (&pin_{status_led})\n" + status_led_inverted = ( + f"#define MICROPY_HW_LED_STATUS_INVERTED ({'1' if status_led_inverted else '0'})\n" + ) else: status_led = "" + status_led_inverted = "" + if boot_button: + boot_button = f"#define CIRCUITPY_BOOT_BUTTON (&pin_{boot_button})\n" + boot_button_active_high = ( + f"#define CIRCUITPY_BOOT_BUTTON_ACTIVE_HIGH " + f"({'1' if boot_button_active_high else '0'})\n" + ) + else: + boot_button = "" + boot_button_active_high = "" + if status_neopixel: + status_neopixel = f"#define MICROPY_HW_NEOPIXEL (&pin_{status_neopixel})\n" + else: + status_neopixel = "" + if status_neopixel_power: + status_neopixel_power = ( + f"#define CIRCUITPY_STATUS_LED_POWER (&pin_{status_neopixel_power})\n" + ) + else: + status_neopixel_power = "" + if status_dotstar: + status_dotstar = ( + f"#define MICROPY_HW_APA102_MOSI (&pin_{status_dotstar[0]})\n" + f"#define MICROPY_HW_APA102_SCK (&pin_{status_dotstar[1]})\n" + "#define CIRCUITPY_BITBANG_APA102 (1)\n" + ) + else: + status_dotstar = "" ram_list = [] ram_externs = [] max_size = 0 for ram in rams: device, start, end, size, path = ram max_size = max(max_size, size) - if isinstance(start, str): + # We always start at the end of a Zephyr linker section so we need the externs and &. + # Native/simulated boards don't have real memory-mapped RAM, so we allocate static arrays. + if board_id.startswith("native_sim") or "bsim" in board_id: + ram_externs.append("// This is a native board so we provide all of RAM for our heaps.") + ram_externs.append(f"static uint32_t _{device}[{size // 4}]; // {path}") + start = f"(const uint32_t *) (_{device})" + end = f"(const uint32_t *)(_{device} + {size // 4})" + else: ram_externs.append(f"extern uint32_t {start};") start = "&" + start - else: - start = f"(uint32_t*) 0x{start:08x}" - ram_list.append(f" {start}, (uint32_t*) 0x{end:08x}, // {path}") + ram_list.append(f" {start}, {end}, // {path}") ram_list = "\n".join(ram_list) ram_externs = "\n".join(ram_externs) + flashes = [f"DEVICE_DT_GET(DT_NODELABEL({flash}))" for flash in flashes] + new_header_content = f"""#pragma once -#define MICROPY_HW_BOARD_NAME "{board_name}" -#define MICROPY_HW_MCU_NAME "{soc_name}" +#define MICROPY_HW_BOARD_NAME "{banner_name}" +#define MICROPY_HW_MCU_NAME "{SOC_NAMES.get(soc_name, soc_name)}" #define CIRCUITPY_RAM_DEVICE_COUNT {len(rams)} {status_led} +{status_led_inverted} +{boot_button} +{boot_button_active_high} +{status_neopixel} +{status_neopixel_power} +{board_bus_defines} +{status_dotstar} """ if not header.exists() or header.read_text() != new_header_content: header.write_text(new_header_content) @@ -348,16 +2071,46 @@ def zephyr_dts_to_cp_board(builddir, zephyrbuilddir): # noqa: C901 pins.write_text(pin_declarations) board_c = board_dir / "board.c" + hostnetwork_include = "" + hostnetwork_entry = "" + if board_info.get("hostnetwork", False): + hostnetwork_include = ( + '#if CIRCUITPY_HOSTNETWORK\n#include "bindings/hostnetwork/__init__.h"\n#endif\n' + ) + hostnetwork_entry = ( + "#if CIRCUITPY_HOSTNETWORK\n" + " { MP_ROM_QSTR(MP_QSTR_NETWORK), MP_ROM_PTR(&common_hal_hostnetwork_obj) },\n" + "#endif\n" + ) + + ethernet_include = "" + ethernet_entry = "" + if board_info.get("ethernet", False): + ethernet_include = '#if CIRCUITPY_MII\n#include "common-hal/mii/__init__.h"\n#endif\n' + ethernet_entry = ( + "#if CIRCUITPY_MII\n" + " { MP_ROM_QSTR(MP_QSTR_ETHERNET), MP_ROM_PTR(ðernet_obj) },\n" + "#endif\n" + ) + new_board_c_content = f""" // This file is autogenerated by build_circuitpython.py #include "shared-bindings/board/__init__.h" +{hostnetwork_include} +{ethernet_include} + #include #include "py/obj.h" #include "py/mphal.h" +{zephyr_binding_headers} +{iobroker_includes} +{zephyr_display_header} + + const struct device* const flashes[] = {{ {", ".join(flashes)} }}; const int circuitpy_flash_device_count = {len(flashes)}; @@ -367,8 +2120,20 @@ def zephyr_dts_to_cp_board(builddir, zephyrbuilddir): # noqa: C901 }}; const size_t circuitpy_max_ram_size = {max_size}; +{ethernet_static_obj} {pin_defs} +{zephyr_binding_objects} +{board_bus_objects} +{iobroker_tables} + +void board_init(void) {{ + {zephyr_display_init} + {ethernet_init} +}} + +{i2sout_reset_func} + static const mp_rom_map_elem_t mcu_pin_globals_table[] = {{ {mcu_pin_mapping} }}; @@ -377,17 +2142,79 @@ def zephyr_dts_to_cp_board(builddir, zephyrbuilddir): # noqa: C901 static const mp_rom_map_elem_t board_module_globals_table[] = {{ CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS +{hostnetwork_entry} +{ethernet_entry} +{zephyr_display_board_entry} {board_pin_mapping} -// {{ MP_ROM_QSTR(MP_QSTR_UART), MP_ROM_PTR(&board_uart_obj) }}, +{zephyr_binding_labels} +{board_bus_labels} + }}; MP_DEFINE_CONST_DICT(board_module_globals, board_module_globals_table); """ - if not board_c.exists() or new_board_c_content != board_c.read_text(): + # Only write board.c when it has changed. Rewriting it on every build gives it a new + # modification time even if the content is the same, and cpbuild then recompiles it, + # regenerates qstrdefs.generated.h from its qstrs, and recompiles every file that + # includes that header, which is all of them. + if not board_c.exists() or board_c.read_text() != new_board_c_content: board_c.write_text(new_board_c_content) + if ble_hardware_present: + if not config_present: + raise RuntimeError( + "Missing Zephyr .config; CONFIG_BT must be set explicitly when BLE hardware is present." + ) + if not config_bt_found: + raise RuntimeError( + "CONFIG_BT is missing from Zephyr .config; set it explicitly when BLE hardware is present." + ) + + board_info["_bleio"] = ble_hardware_present and config_bt_enabled board_info["source_files"] = [board_c] board_info["cflags"] = ("-I", board_dir) board_info["flash_count"] = len(flashes) + board_info["rotaryio"] = bool(ioports) + # analogio requires both the devicetree device and the Zephyr driver: + # the ADC path resolves pads to their analog inputs through iobroker and + # the DAC path needs the emulated DAC for its counter tracks. + board_info["analogio"] = (adc_present and config_adc_enabled) or ( + dac_present and config_dac_enabled + ) + board_info["rtc"] = False + # RTC needs both a devicetree `rtc` alias pointing at the RTC device + # (the same selection Zephyr's own RTC sample uses) and the Zephyr RTC + # driver layer enabled (CONFIG_RTC). + rtc_node = device_tree.alias2node.get("rtc") + if rtc_node is not None: + rtc_status = rtc_node.props.get("status") + rtc_present = rtc_status is None or rtc_status.to_string() == "okay" + if rtc_present and config_rtc_enabled: + board_info["rtc"] = True + elif rtc_present: + logger.warning( + "Devicetree has a status-okay 'rtc' alias but CONFIG_RTC is " + "not enabled, so the rtc module is disabled." + ) + board_info["watchdog"] = True + # Watchdog is always enabled: RAISE mode raises the WatchDogTimeout + # exception from a software Zephyr k_timer and works on every board. + # RESET mode additionally uses the hardware watchdog selected by the + # devicetree `watchdog0` alias (the same selection Zephyr's own watchdog + # sample uses); boards without the alias support only RAISE mode and + # raise NotImplementedError when RESET is requested. board_info["usb_num_endpoint_pairs"] = usb_num_endpoint_pairs + + # Detect NVM partition size from the device tree. + nvm_size = 0 + nvm_node = device_tree.label2node.get("nvm_partition") + if nvm_node and "reg" in nvm_node.props: + nvm_size = nvm_node.props["reg"].to_nums()[1] + board_info["nvm_size"] = nvm_size + + # The user filesystem type is a compile-time choice made by the partition + # layout: a littlefs_partition node (named for littlefs in the Adaboot + # fork's layout dtsi) mounts littlefs; everything else mounts FAT. + board_info["littlefs"] = device_tree.label2node.get("littlefs_partition") is not None + return board_info diff --git a/ports/zephyr-cp/debug.conf b/ports/zephyr-cp/debug.conf new file mode 100644 index 00000000000..8fbdc6b6b87 --- /dev/null +++ b/ports/zephyr-cp/debug.conf @@ -0,0 +1,107 @@ +CONFIG_DEBUG=y +CONFIG_DEBUG_OPTIMIZATIONS=y +CONFIG_LOG_MAX_LEVEL=4 + +CONFIG_STACK_SENTINEL=y +CONFIG_DEBUG_THREAD_INFO=y +CONFIG_EXCEPTION_STACK_TRACE=y +CONFIG_EXCEPTION_DUMP=y + +CONFIG_ASSERT=y +CONFIG_LOG_BLOCK_IN_THREAD=y +CONFIG_FRAME_POINTER=y + +CONFIG_FLASH_LOG_LEVEL_DBG=y +CONFIG_LOG_MODE_IMMEDIATE=y + +# Quiet the UDC device-controller drivers in the debug build. The DWC2 driver +# logs "Prepare RX 0x%02x doeptsiz 0x%x" (LOG_INF) on every OUT endpoint RX +# prepare, which is noisy. Drop UDC_DRIVER to WRN to keep errors/warnings +# while compiling out INF/DBG. (Shared by all udc drivers; only one is active +# per board.) +CONFIG_UDC_DRIVER_LOG_LEVEL_WRN=y + +# Bluetooth: enable BT host debug logging so success paths print, not just +# LOG_ERR. In particular bt_keys logs "Stored keys for " (LOG_DBG) on a +# successful bt_keys_store(); without this only the failure message +# "Failed to save keys (err -116)" is visible. Also enable the adjacent +# modules (SMP drives pairing, BT_SETTINGS is the NVS backend that returns +# the store err) so the -EALREADY (-116) store-failure context is complete. +CONFIG_BT_KEYS_LOG_LEVEL_DBG=y +CONFIG_BT_SETTINGS_LOG_LEVEL_DBG=y +CONFIG_BT_SMP_LOG_LEVEL_DBG=y + + +# Bump stacks for debug build - verbose logging consumes more stack. +CONFIG_SYSTEM_WORKQUEUE_STACK_SIZE=4096 +CONFIG_MAIN_STACK_SIZE=32768 +CONFIG_ISR_STACK_SIZE=4096 +CONFIG_UDC_DWC2_STACK_SIZE=4096 +CONFIG_UDC_NRF_THREAD_STACK_SIZE=4096 +CONFIG_USBD_THREAD_STACK_SIZE=4096 +CONFIG_USBD_MSC_STACK_SIZE=4096 +CONFIG_IDLE_STACK_SIZE=1024 + +# Bluetooth stacks: debug logging + assertions + LOG_MODE_IMMEDIATE consume +# substantial extra stack in the BT host RX workqueue (runs all event callbacks, +# including SMP/pairing) and the long workqueue (deferred SMP/pairing/crypto + +# NVS bond-key store). Zephyr's own SMP/pairing test app +# (tests/bluetooth/tester/prj.conf) uses 4096 for BT_RX_STACK_SIZE. +# (BT_CTLR_RX_PRIO_STACK_SIZE is bumped in the Zephyr controller Kconfig +# default since it's a hidden symbol. BT_HCI_TX/BT_CTLR_RX are also hidden and +# haven't overflowed — left at their defaults.) +CONFIG_BT_RX_STACK_SIZE=4096 +CONFIG_BT_LONG_WQ_STACK_SIZE=4096 + +# ===== Networking: trace the DHCP / DNS / socket path ===== +# These answer: did DHCP bind and hand the resolver its server, what errno did +# the DNS query get (getaddrinfo reports the resolver's failures as +# DNS_EAI_SYSTEM, "getaddrinfo failure: -11"), and which socket operation ran +# when a socket crash occurs. The log modules register as net_core, net_if, +# net_ipv4, net_ipv4_dhcpv4, net_tcp, net_sock and net_dns_resolve. +CONFIG_NET_LOG=y +CONFIG_LOG_DEFAULT_LEVEL=4 +# The kernel module logs a mutex lock/unlock line for every single mutex +# operation in the network stack, which drowns the useful net trace; keep the +# kernel at INF. +CONFIG_KERNEL_LOG_LEVEL_INF=y +CONFIG_NET_CORE_LOG_LEVEL_DBG=y +CONFIG_NET_IF_LOG_LEVEL_DBG=y +CONFIG_NET_IPV4_LOG_LEVEL_DBG=y +CONFIG_NET_DHCPV4_LOG_LEVEL_DBG=y +CONFIG_NET_SOCKETS_LOG_LEVEL_DBG=y +CONFIG_NET_TCP_LOG_LEVEL_DBG=y +CONFIG_DNS_RESOLVER_LOG_LEVEL_DBG=y +CONFIG_DNS_SOCKET_DISPATCHER_LOG_LEVEL_DBG=y +CONFIG_ETHERNET_LOG_LEVEL_DBG=y + +# The TLS rework's handshake failures surface as a generic mapped ValueError +# ("invalid key"); MBEDTLS_DEBUG_C turns on the mbedtls handshake trace, which +# SSLSocket prints to the REPL as DBG:: so the failing +# step of the connection manager's https fetch is visible. +CONFIG_MBEDTLS_DEBUG_C=y + +# Keep the logging stacks from overflowing under the extra DBG output. +CONFIG_SYSTEM_WORKQUEUE_STACK_SIZE=8192 +CONFIG_THREAD_NAME=y + +# The ENET-QoS RX thread logs every packet at DBG level; its normal build +# stack (2048) is not enough for the debug logging depth. +CONFIG_ETH_NXP_ENET_QOS_RX_THREAD_STACK_SIZE=4096 + +# Ditto the per-interface network TX/RX queues, which process every received +# packet under the net_if/net_ipv6/net_dhcpv4 DBG logs. +CONFIG_NET_TX_STACK_SIZE=4096 +CONFIG_NET_RX_STACK_SIZE=4096 + +# ... and the net_mgmt event thread, which runs the carrier/address-add/DHCP +# event callbacks (and their DBG logs) that fire around address setup. +CONFIG_NET_MGMT_EVENT_STACK_SIZE=4096 + +# ... and the socket-service thread, which runs the DNS resolver's poll set +# and every registered socket callback. +CONFIG_NET_SOCKETS_SERVICE_STACK_SIZE=4096 + +# ... and the TCP workqueue, which processes every TCP segment (with the +# net_tcp DBG trace) plus retransmission/timer work. +CONFIG_NET_TCP_WORKQ_STACK_SIZE=4096 diff --git a/ports/zephyr-cp/docs/perfetto-tracing.md b/ports/zephyr-cp/docs/perfetto-tracing.md new file mode 100644 index 00000000000..ff35d361f70 --- /dev/null +++ b/ports/zephyr-cp/docs/perfetto-tracing.md @@ -0,0 +1,150 @@ +# Perfetto Tracing + +The Zephyr port supports Perfetto tracing for performance analysis. This document +describes how to capture, validate, and view traces. + +## Capturing Traces + +Traces are written to `circuitpython.perfetto-trace` in the port directory when +running with tracing enabled (e.g., on native_sim). + +## Validating Traces + +### Using trace_processor + +The Perfetto trace_processor tool can validate and query trace files: + +```bash +~/repos/perfetto/tools/trace_processor circuitpython.perfetto-trace +``` + +This will download the trace_processor binary if needed and open an interactive +SQL shell. If the trace loads successfully, you can query it: + +```sql +SELECT COUNT(*) FROM slice; +``` + +### Using the Perfetto UI + +Open https://ui.perfetto.dev and drag your trace file onto the page. + +## Debugging Invalid Traces + +### Common Error: Packets Skipped Due to Invalid Incremental State + +If trace_processor reports packets being skipped with messages like: + +``` +packet_skipped_seq_needs_incremental_state_invalid +``` + +This means packets have `SEQ_NEEDS_INCREMENTAL_STATE` (value 2) set but no +prior packet set `SEQ_INCREMENTAL_STATE_CLEARED` (value 1) to initialize the +incremental state. + +**Root Cause**: The process descriptor packet (which sets `SEQ_INCREMENTAL_STATE_CLEARED`) +must be emitted before any other trace packets. + +**Diagnosis**: Use protoc to inspect the raw trace: + +```bash +protoc --decode_raw < circuitpython.perfetto-trace | head -100 +``` + +Look for field 13 (sequence_flags) in the first few packets: + +- `13: 1` = SEQ_INCREMENTAL_STATE_CLEARED (good - should be first) +- `13: 2` = SEQ_NEEDS_INCREMENTAL_STATE (requires prior cleared packet) + +A valid trace should have the process descriptor with `13: 1` as one of the +first packets. + +**Fix**: Ensure `perfetto_start()` is called before any trace events are emitted. +The descriptor emit functions in `perfetto_encoder.c` should check: + +```c +if (!started) { + perfetto_start(); +} +``` + +### Analyzing Raw Trace Structure + +To understand the trace structure: + +```bash +# Count total packets +protoc --decode_raw < circuitpython.perfetto-trace | grep -c "^1 {" + +# Find all sequence_flags values +protoc --decode_raw < circuitpython.perfetto-trace | grep "13:" | sort | uniq -c + +# Look for track descriptors (field 60) +protoc --decode_raw < circuitpython.perfetto-trace | grep -A20 "60 {" + +# Look for process descriptors (field 3 inside track_descriptor) +protoc --decode_raw < circuitpython.perfetto-trace | grep -B5 "3 {" +``` + +### Key Protobuf Field Numbers + +TracePacket fields: + +| Field | Description | +|-------|-------------| +| 8 | timestamp | +| 10 | trusted_packet_sequence_id | +| 11 | track_event | +| 12 | interned_data | +| 13 | sequence_flags | +| 60 | track_descriptor | + +TrackDescriptor fields (inside field 60): + +| Field | Description | +|-------|-------------| +| 1 | uuid | +| 2 | name | +| 3 | process (ProcessDescriptor) | +| 4 | thread (ThreadDescriptor) | +| 5 | parent_uuid | + +## Build Verification + +After modifying tracing code, verify the build is updated: + +```bash +# Check source vs object file timestamps +ls -la zephyr/subsys/tracing/perfetto/perfetto_encoder.c +ls -la zephyr/build/zephyr/subsys/tracing/perfetto/CMakeFiles/subsys__tracing__perfetto.dir/perfetto_encoder.c.obj +``` + +The object file timestamp must be newer than the source file timestamp. If not, +rebuild the project before capturing a new trace. + +## Architecture + +The tracing implementation consists of: + +- `perfetto_encoder.c`: Encodes trace packets using nanopb +- `perfetto_top.c`: Implements Zephyr tracing hooks (sys_trace_*) +- `perfetto_encoder.h`: Public API and UUID definitions + +Key UUIDs: + +| Constant | Value | Description | +|----------|-------|-------------| +| PROCESS_UUID | 1 | Root process track | +| ISR_TRACK_UUID | 2 | Interrupt service routine track | +| TRACE_TRACK_UUID | 3 | Top-level trace track | + +### Initialization Flow + +1. `SYS_INIT` calls `perfetto_init()` at POST_KERNEL priority 0 +2. `perfetto_init()` calls `perfetto_encoder_init()` +3. `perfetto_initialized` is set to true +4. Thread hooks start firing +5. First emit function calls `perfetto_start()` +6. `perfetto_start()` emits process descriptor with `SEQ_INCREMENTAL_STATE_CLEARED` +7. Subsequent packets use `SEQ_NEEDS_INCREMENTAL_STATE` diff --git a/ports/zephyr-cp/dts/bindings/adafruit-itsybitsy-header.yaml b/ports/zephyr-cp/dts/bindings/adafruit-itsybitsy-header.yaml new file mode 100644 index 00000000000..553bf7443e4 --- /dev/null +++ b/ports/zephyr-cp/dts/bindings/adafruit-itsybitsy-header.yaml @@ -0,0 +1,25 @@ +# SPDX-FileCopyrightText: 2026 Dan Halbert for Adafruit Industries +# SPDX-License-Identifier: MIT + +description: | + GPIO pins exposed on the Adafruit ItsyBitsy nRF52840 headers. + + This binding provides a nexus mapping for 21 pins. The positions are in + the order of the CONNECTORS["adafruit-itsybitsy-header"] names in + cptools/zephyr2cp.py, not in physical header order: + + 0 A0 7 MOSI 14 D5 + 1 A1 8 MISO 15 D7 + 2 A2 9 D0/RX 16 D9 + 3 A3 10 D1/TX 17 D10 + 4 A4 11 D2 18 D11 + 5 A5 12 SDA 19 D12 + 6 SCK 13 SCL 20 D13 + + TODO: figure out how to handle the extra pins on other ItsyBitsy boards, + such as D3 and D4 on the ItsyBitsy M4 and RP2040. We may want separate + connectors for the different board families. + +compatible: "adafruit-itsybitsy-header" + +include: [gpio-nexus.yaml, base.yaml] diff --git a/ports/zephyr-cp/dts/bindings/adafruit-metro-ch32v4x7-pins.yaml b/ports/zephyr-cp/dts/bindings/adafruit-metro-ch32v4x7-pins.yaml new file mode 100644 index 00000000000..018dcddae91 --- /dev/null +++ b/ports/zephyr-cp/dts/bindings/adafruit-metro-ch32v4x7-pins.yaml @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: 2026 Adafruit Industries +# SPDX-License-Identifier: MIT + +description: | + Named Adafruit Metro CH32V407/CH32V467 pins that are not on its Arduino + header: the 2x3 SPI header, the NeoPixel, the USER button and the microSD + card detect. + + The pin names come from the board's circuitpython.toml + [connectors.] table, keyed by gpio-map position. + +compatible: "adafruit-metro-ch32v4x7-pins" + +include: [gpio-nexus.yaml, base.yaml] diff --git a/ports/zephyr-cp/dts/bindings/adafruit-metro-m7-pins.yaml b/ports/zephyr-cp/dts/bindings/adafruit-metro-m7-pins.yaml new file mode 100644 index 00000000000..b5036201aad --- /dev/null +++ b/ports/zephyr-cp/dts/bindings/adafruit-metro-m7-pins.yaml @@ -0,0 +1,14 @@ +# SPDX-FileCopyrightText: 2026 Dan Halbert for Adafruit Industries +# SPDX-License-Identifier: MIT + +description: | + Named Adafruit Metro M7 pins that are not on its Arduino header: the 2x3 + SPI header, the NeoPixel, and the microSD or AirLift ESP32 control pins. + + The pin names come from the board's circuitpython.toml + [connectors.] table, keyed by gpio-map position, because the + microSD and AirLift boards name different pins. + +compatible: "adafruit-metro-m7-pins" + +include: [gpio-nexus.yaml, base.yaml] diff --git a/ports/zephyr-cp/dts/bindings/circuitpython,spi-loopback.yaml b/ports/zephyr-cp/dts/bindings/circuitpython,spi-loopback.yaml new file mode 100644 index 00000000000..e74e499215f --- /dev/null +++ b/ports/zephyr-cp/dts/bindings/circuitpython,spi-loopback.yaml @@ -0,0 +1,8 @@ +# SPDX-FileCopyrightText: 2026 Vladimir Smitka +# SPDX-License-Identifier: MIT + +description: SPI loopback for tests, MOSI wired to MISO + +compatible: "circuitpython,spi-loopback" + +include: spi-device.yaml diff --git a/ports/zephyr-cp/internal-modules/ch32v4x7_entropy/CMakeLists.txt b/ports/zephyr-cp/internal-modules/ch32v4x7_entropy/CMakeLists.txt new file mode 100644 index 00000000000..ff8e80b0490 --- /dev/null +++ b/ports/zephyr-cp/internal-modules/ch32v4x7_entropy/CMakeLists.txt @@ -0,0 +1,12 @@ +# ch32v4x7_entropy Zephyr module build: the entropy driver, built when the +# devicetree enables an adafruit,ch32v4x7-adc-entropy node. + +if(CONFIG_ENTROPY_CH32V4X7_ADC) + set(circuitpython_root ${ZEPHYR_CURRENT_MODULE_DIR}/../../../..) + zephyr_library() + zephyr_library_sources( + src/entropy_ch32v4x7_adc.c + ${circuitpython_root}/lib/crypto-algorithms/sha256.c + ) + zephyr_library_include_directories(${circuitpython_root}) +endif() diff --git a/ports/zephyr-cp/internal-modules/ch32v4x7_entropy/Kconfig b/ports/zephyr-cp/internal-modules/ch32v4x7_entropy/Kconfig new file mode 100644 index 00000000000..1eb0e04b7d5 --- /dev/null +++ b/ports/zephyr-cp/internal-modules/ch32v4x7_entropy/Kconfig @@ -0,0 +1,11 @@ +# ch32v4x7_entropy: entropy driver for the WCH CH32V4x7. + +config ENTROPY_CH32V4X7_ADC + bool "CH32V4x7 ADC temperature sensor entropy driver" + default y + depends on ENTROPY_GENERATOR + depends on DT_HAS_ADAFRUIT_CH32V4X7_ADC_ENTROPY_ENABLED + select ENTROPY_HAS_DRIVER + help + Entropy from ADC1 internal temperature sensor noise, conditioned + with SHA-256. diff --git a/ports/zephyr-cp/internal-modules/ch32v4x7_entropy/dts/bindings/rng/adafruit,ch32v4x7-adc-entropy.yaml b/ports/zephyr-cp/internal-modules/ch32v4x7_entropy/dts/bindings/rng/adafruit,ch32v4x7-adc-entropy.yaml new file mode 100644 index 00000000000..55b7e87c063 --- /dev/null +++ b/ports/zephyr-cp/internal-modules/ch32v4x7_entropy/dts/bindings/rng/adafruit,ch32v4x7-adc-entropy.yaml @@ -0,0 +1,10 @@ +# SPDX-FileCopyrightText: 2026 Mikey Sklar for Adafruit Industries +# SPDX-License-Identifier: MIT + +description: | + CH32V4x7 entropy source: ADC1 internal temperature sensor noise, + hashed with SHA-256. + +compatible: "adafruit,ch32v4x7-adc-entropy" + +include: base.yaml diff --git a/ports/zephyr-cp/internal-modules/ch32v4x7_entropy/src/entropy_ch32v4x7_adc.c b/ports/zephyr-cp/internal-modules/ch32v4x7_entropy/src/entropy_ch32v4x7_adc.c new file mode 100644 index 00000000000..c2945c21b48 --- /dev/null +++ b/ports/zephyr-cp/internal-modules/ch32v4x7_entropy/src/entropy_ch32v4x7_adc.c @@ -0,0 +1,217 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mikey Sklar for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// Entropy source for the WCH CH32V4x7, whose on-chip RNG repeats too often to +// use. Each 32-byte output block is SHA-256 over 512 ADC readings of the +// internal temperature sensor, credited at 0.5 bit each. +// +// This driver owns ADC1. Nothing else on these boards uses it. +// +// The hash is CircuitPython's own SHA-256, not PSA crypto, because PSA seeds +// its random generator from this driver and is not ready at PRE_KERNEL_1. + +#define DT_DRV_COMPAT adafruit_ch32v4x7_adc_entropy + +#include +#include + +#include +#include +#include +#include +#include + +#include "lib/crypto-algorithms/sha256.h" + +#define REG(addr) (*(volatile uint32_t *)(addr)) + +// RCC (reference manual chapter 3). +#define RCC_CFGR0 0x40021004u +#define RCC_CFGR0_ADCPRE_MASK (3u << 14) +#define RCC_CFGR0_ADCPRE_DIV8 (3u << 14) +#define RCC_PB2PCENR 0x40021018u +#define RCC_PB2PCENR_ADC1EN (1u << 9) + +// ADC1 (chapter 12). +#define ADC1_BASE 0x40012400u +#define ADC_STATR (ADC1_BASE + 0x00) +#define ADC_STATR_EOC (1u << 1) +#define ADC_CTLR1 (ADC1_BASE + 0x04) +#define ADC_CTLR2 (ADC1_BASE + 0x08) +#define ADC_CTLR2_ADON (1u << 0) +#define ADC_CTLR2_CAL (1u << 2) +#define ADC_CTLR2_RSTCAL (1u << 3) +#define ADC_CTLR2_EXTSEL_SWSTART (7u << 17) +#define ADC_CTLR2_EXTTRIG (1u << 20) +#define ADC_CTLR2_SWSTART (1u << 22) +#define ADC_CTLR2_TSVREFE (1u << 23) +#define ADC_SAMPTR1 (ADC1_BASE + 0x0C) +#define ADC_SAMPTR1_SMP16_MASK (7u << 18) +#define ADC_RSQR1 (ADC1_BASE + 0x2C) +#define ADC_RSQR3 (ADC1_BASE + 0x34) +#define ADC_RDATAR (ADC1_BASE + 0x4C) +#define ADC_CHANNEL_TEMPSENSOR 16u + +// Electronic signature (chapter 31): 96-bit unique ID. +#define ESIG_UNIID1 0x1FFFF7E8u + +#define SAMPLES_PER_BLOCK 512 +#define SAMPLES_PER_UPDATE 64 +#define TIMEOUT_LOOPS 100000 + +// SP 800-90B health test cutoffs for 0.5 bit per reading and a false alarm +// rate of 2^-20. +// Repetition count test (4.4.1): one reading this many times in a row. +#define REPETITION_CUTOFF 41 +// Adaptive proportion test (4.4.2): the first reading of a block this many +// times in the 512 readings of that block. +#define PROPORTION_CUTOFF 410 + +static K_MUTEX_DEFINE(entropy_lock); +static uint32_t block_counter; +// Repetition count state, kept across calls so a run can't hide at a call +// boundary. +static uint16_t repetition_last; +static int repetition_count; + +static void wipe(void *p, size_t n) { + volatile uint8_t *v = p; + while (n--) { + *v++ = 0; + } +} + +static bool adc_read(uint16_t *out) { + REG(ADC_CTLR2) |= ADC_CTLR2_EXTTRIG | ADC_CTLR2_SWSTART; + for (int i = 0; i < TIMEOUT_LOOPS; i++) { + if (REG(ADC_STATR) & ADC_STATR_EOC) { + // Reading RDATAR clears EOC. + *out = REG(ADC_RDATAR); + return true; + } + } + return false; +} + +static bool wait_ctlr2_clear(uint32_t bit) { + for (int i = 0; i < TIMEOUT_LOOPS; i++) { + if (!(REG(ADC_CTLR2) & bit)) { + return true; + } + } + return false; +} + +static int ch32v4x7_adc_entropy_get(const struct device *dev, uint8_t *buf, uint16_t len) { + ARG_UNUSED(dev); + int ret = 0; + bool locked = !k_is_pre_kernel(); + if (locked) { + k_mutex_lock(&entropy_lock, K_FOREVER); + } + + CRYAL_SHA256_CTX ctx; + uint32_t header[5]; + uint16_t samples[SAMPLES_PER_UPDATE]; + BYTE digest[SHA256_BLOCK_SIZE]; + + while (len > 0) { + sha256_init(&ctx); + header[0] = ++block_counter; + header[1] = csr_read(mcycle); + header[2] = REG(ESIG_UNIID1); + header[3] = REG(ESIG_UNIID1 + 4); + header[4] = REG(ESIG_UNIID1 + 8); + sha256_update(&ctx, (const BYTE *)header, sizeof(header)); + + uint16_t proportion_first = 0; + int proportion_count = 0; + for (int i = 0; i < SAMPLES_PER_BLOCK; i += SAMPLES_PER_UPDATE) { + for (int j = 0; j < SAMPLES_PER_UPDATE; j++) { + uint16_t sample; + if (!adc_read(&sample)) { + ret = -EIO; + goto done; + } + samples[j] = sample; + + if (repetition_count > 0 && sample == repetition_last) { + if (++repetition_count >= REPETITION_CUTOFF) { + ret = -EIO; + goto done; + } + } else { + repetition_last = sample; + repetition_count = 1; + } + + if (i + j == 0) { + proportion_first = sample; + } + if (sample == proportion_first && ++proportion_count >= PROPORTION_CUTOFF) { + ret = -EIO; + goto done; + } + } + sha256_update(&ctx, (const BYTE *)samples, sizeof(samples)); + } + + sha256_final(&ctx, digest); + size_t n = MIN(len, sizeof(digest)); + memcpy(buf, digest, n); + buf += n; + len -= n; + } + +done: + wipe(&ctx, sizeof(ctx)); + wipe(header, sizeof(header)); + wipe(samples, sizeof(samples)); + wipe(digest, sizeof(digest)); + if (locked) { + k_mutex_unlock(&entropy_lock); + } + return ret; +} + +static int ch32v4x7_adc_entropy_init(const struct device *dev) { + ARG_UNUSED(dev); + + // ADC1 on the internal temperature sensor, software triggered, with the + // shortest sample time because that gives the most noise. + REG(RCC_PB2PCENR) |= RCC_PB2PCENR_ADC1EN; + REG(RCC_CFGR0) = (REG(RCC_CFGR0) & ~RCC_CFGR0_ADCPRE_MASK) | RCC_CFGR0_ADCPRE_DIV8; + REG(ADC_CTLR1) = 0; + REG(ADC_CTLR2) = ADC_CTLR2_EXTSEL_SWSTART | ADC_CTLR2_TSVREFE; + REG(ADC_RSQR1) = 0; + REG(ADC_RSQR3) = ADC_CHANNEL_TEMPSENSOR; + REG(ADC_SAMPTR1) &= ~ADC_SAMPTR1_SMP16_MASK; + REG(ADC_CTLR2) |= ADC_CTLR2_ADON; + + // Let the ADC and sensor start up. The system timer is not running yet in + // PRE_KERNEL_1, so this is a plain loop, far longer than the start-up + // times. + for (volatile int i = 0; i < 10000; i++) { + } + + REG(ADC_CTLR2) |= ADC_CTLR2_RSTCAL; + if (!wait_ctlr2_clear(ADC_CTLR2_RSTCAL)) { + return -EIO; + } + REG(ADC_CTLR2) |= ADC_CTLR2_CAL; + if (!wait_ctlr2_clear(ADC_CTLR2_CAL)) { + return -EIO; + } + + return 0; +} + +static DEVICE_API(entropy, ch32v4x7_adc_entropy_api) = { + .get_entropy = ch32v4x7_adc_entropy_get, +}; + +DEVICE_DT_INST_DEFINE(0, ch32v4x7_adc_entropy_init, NULL, NULL, NULL, PRE_KERNEL_1, + CONFIG_ENTROPY_INIT_PRIORITY, &ch32v4x7_adc_entropy_api); diff --git a/ports/zephyr-cp/internal-modules/ch32v4x7_entropy/zephyr/module.yml b/ports/zephyr-cp/internal-modules/ch32v4x7_entropy/zephyr/module.yml new file mode 100644 index 00000000000..a65ce7a47c3 --- /dev/null +++ b/ports/zephyr-cp/internal-modules/ch32v4x7_entropy/zephyr/module.yml @@ -0,0 +1,11 @@ +# Zephyr module descriptor for the ch32v4x7_entropy module. +# +# The module is loaded from the CircuitPython tree via ZEPHYR_EXTRA_MODULES in +# ports/zephyr-cp/CMakeLists.txt. +name: ch32v4x7_entropy +build: + cmake: . + kconfig: Kconfig + settings: + # dts/bindings/ holds the adafruit,ch32v4x7-adc-entropy binding. + dts_root: . diff --git a/ports/zephyr-cp/internal-modules/circuitpython-kconfig/Kconfig b/ports/zephyr-cp/internal-modules/circuitpython-kconfig/Kconfig new file mode 100644 index 00000000000..fbfbc298c37 --- /dev/null +++ b/ports/zephyr-cp/internal-modules/circuitpython-kconfig/Kconfig @@ -0,0 +1,653 @@ +# CircuitPython defaults that must merge before Zephyr's subsystem Kconfig +# files. +# +# Zephyr merges this file via its module mechanism (Kconfig.zephyr sources +# "modules/Kconfig", which pulls in every module's Kconfig) right after the +# SoC/board defconfigs and BEFORE kernel/, drivers/, lib/ and subsys/. Kconfig +# takes the first `default` it sees for a symbol, so defaults defined here win +# over the ones Zephyr's own subsystem Kconfigs define later. +# +# These same defaults must NOT live in the application Kconfig +# (ports/zephyr-cp/Kconfig): it is sourced after all of Zephyr, so any symbol +# Zephyr gives a (conditional) default of its own would silently shadow the +# port's value there. Examples that were shadowed here before this module +# existed: BT_BUF_* (Zephyr defaults them for BT_CLASSIC/BT_MESH/... boards), +# BT_DEVICE_NAME_MAX, BT_L2CAP_TX_MTU, MCUMGR_TRANSPORT_NETBUF_SIZE. +# +# Boards can override any of these in their boards///board.conf. + +# ===== Peripheral defaults — enabled by default, boards can disable ===== + +config I2C + default y + +config SPI + default y + +config SPI_ASYNC + default y + +config I2S + default y + +config UART_LINE_CTRL + default y + +config ENTROPY_GENERATOR + default y + +# ===== Logging ===== +# Log only when the board has a console. Boards with no console in their +# normal build delete the zephyr,console chosen node in board.overlay, and +# then save the log buffer and logging thread, about 2 KB; their +# console.overlay, used in CONSOLE=1 builds, sets it again. This checks the +# devicetree because the console Kconfig symbols (UART_CONSOLE, RTT_CONSOLE) +# would make a dependency loop with LOG. +DT_CHOSEN_Z_CONSOLE := zephyr,console + +config LOG + default y if $(dt_chosen_enabled,$(DT_CHOSEN_Z_CONSOLE)) || ARCH_POSIX + +# Warnings and errors only, and block a logging thread rather than drop +# messages when the log buffer is full. Defaults rather than prj.conf settings, +# which would warn on boards where LOG is off. +if LOG +config LOG_MAX_LEVEL + default 2 + +config LOG_BLOCK_IN_THREAD + default y +endif + +# ===== Dynamic pin routing (nRF) ===== +# CircuitPython routes peripherals to pins at runtime on nRF SoCs. That needs +# pinctrl states to be swappable (PINCTRL_DYNAMIC) and devices to be +# de-initializable/re-initializable (DEVICE_DEINIT_SUPPORT). Both cost a little +# RAM (pinctrl configs move out of flash) and one function pointer per device. +config PINCTRL_DYNAMIC + default y if SOC_FAMILY_NORDIC_NRF + +config DEVICE_DEINIT_SUPPORT + default y if SOC_FAMILY_NORDIC_NRF + +# ===== Interrupt locking versus the Bluetooth controller (nRF) ===== +# CircuitPython cannot bound its critical sections (bitbangio, onewireio, user +# code calling disable_interrupts(), the neopixel_write bit-bang fallback). +# +# Let the controller's radio interrupts (BT_CTLR_ZLI, default on) bypass +# irq_lock(), as the SoftDevice's interrupts do in ports/nordic. +config ZERO_LATENCY_IRQS + default y if SOC_FAMILY_NORDIC_NRF + +# The upper link layer schedules each radio event from an ordinary interrupt +# and the controller allows 733 us (EVENT_OVERHEAD_START_US) for that to run. +# Zephyr's default makes a longer delay a fatal assertion that halts the +# system; with the assertion off the controller skips the delayed radio event +# instead, which is the behavior we want. +config BT_CTLR_ASSERT_OVERHEAD_START + default n if SOC_FAMILY_NORDIC_NRF + +# ===== Flash filesystem scratch page ===== +# supervisor/flash.c caches the erase page being written in RAM. With a +# scratch page, it allocates the cache only while writing, and stages writes +# in the last erase page of the filesystem when it can't. Without one, it +# allocates the cache once at startup and keeps it, and the filesystem gets +# the whole partition. +# +# ports/raspberrypi caches one 4 KB sector in a static buffer and reserves no +# scratch page, so do the same on RP2040 and RP2350: the filesystem sizes +# then match, and either port can use a filesystem formatted by the other. +config CIRCUITPY_FLASH_SCRATCH_PAGE + bool "Stage flash writes in a scratch page when the RAM cache can't be allocated" + default n if SOC_FAMILY_RPI_PICO + default y + +# ===== Zephyr malloc arena reserve ===== +# The VM heap grows into Zephyr's malloc arena, but Zephyr also allocates from +# the arena for BLE and TLS, on its own threads, which can't use the GC heap. +# port_heap_get_largest_free_size() leaves this many bytes of the arena for +# them. Without a reserve, a full VM heap makes BLE pairing fail. +config CIRCUITPY_ZEPHYR_MALLOC_RESERVE + int "Bytes of Zephyr's malloc arena the VM heap leaves free" + depends on COMMON_LIBC_MALLOC + default 4096 + +# ===== LVGL dirty areas ===== +# Test aid: before each LVGL redraw, printk the areas it is about to redraw +# (after LVGL merges the invalidated ones) as "lvgl dirty x1 y1 x2 y2". The +# native_sim LVGL board turns it on so tests can check how much is redrawn. +config CIRCUITPY_LVGL_PRINT_DIRTY_AREAS + bool "Print the areas LVGL redraws" + depends on LVGL + +# ===== External NOR flash ===== +# supervisor/flash.c sets aside the last erase page of the filesystem as a +# scratch page, and caches a whole erase page in RAM while writing. The NOR +# flash drivers' default layout page is the 64 KB erase block, which loses +# 64 KB of the filesystem and needs a 64 KB RAM cache. Use the 4 KB sector +# instead; the drivers erase 4 KB sectors too. Changing one block then +# rewrites 4 KB instead of 64 KB, which is faster for small writes such as +# FAT updates. Filesystem partitions also start and end on 4 KB boundaries, +# but not always on 64 KB ones. +# +# On nRF QSPI boards, the filesystem size then matches ports/nordic, so +# either port can use a filesystem formatted by the other. +config NORDIC_QSPI_NOR_FLASH_LAYOUT_PAGE_SIZE + default 4096 if NORDIC_QSPI_NOR + +config SPI_NOR_FLASH_LAYOUT_PAGE_SIZE + default 4096 if SPI_NOR + +config FLASH_MSPI_NOR_LAYOUT_PAGE_SIZE + default 4096 if FLASH_MSPI_NOR + +# ===== Bluetooth defaults ===== + +# Use a variable for the chosen name so the comma isn't parsed as an argument separator +DT_BT_HCI_CHOSEN := zephyr,bt-hci + +config BT + default $(dt_chosen_enabled,$(DT_BT_HCI_CHOSEN)) + +config BT_PERIPHERAL + default y + +config BT_CENTRAL + default y + +config BT_BROADCASTER + default y + +config BT_OBSERVER + default y + +config BT_EXT_ADV + default y + +config BT_DEVICE_APPEARANCE_DYNAMIC + default y + +config BT_DEVICE_NAME_DYNAMIC + default y + +config BT_DEVICE_NAME_MAX + default 28 + +config BT_L2CAP_TX_MTU + default 253 + +# BT Buffers +config BT_BUF_CMD_TX_SIZE + default 255 + +config BT_BUF_EVT_RX_COUNT + default 16 + +config BT_BUF_EVT_RX_SIZE + default 255 + +config BT_BUF_ACL_TX_COUNT + default 3 + +config BT_BUF_ACL_TX_SIZE + default 251 + +config BT_BUF_ACL_RX_COUNT_EXTRA + default 1 + +config BT_BUF_ACL_RX_SIZE + default 255 + +config BT_GATT_DYNAMIC_DB + default y + +config BT_GATT_CLIENT + default y + +config BT_SMP + default y + +config BT_BONDABLE + default y + +config SETTINGS + default y + +config BT_SETTINGS + default y + +config BT_KEYS_OVERWRITE_OLDEST + default y + +# ===== Networking ===== + +# Auto-enable the networking stack when the devicetree contains an ethernet +# controller so ethernet boards don't need the boilerplate block in their +# board.conf (NETWORKING, NET_IPV4, NET_DHCPV4, NET_SOCKETS, NET_L2_ETHERNET, +# NET_MGMT_EVENT, NET_MGMT_EVENT_INFO and a bigger kernel heap). The DT_HAS_* +# symbols are generated by Zephyr from the devicetree bindings. Extend the +# list as new ethernet drivers/SoC families get ported; boards can still +# override any of these in board.conf. +config ZCP_ETHERNET_DT + bool + default y if \ + DT_HAS_ADI_ADIN1110_ENABLED || \ + DT_HAS_ADI_ADIN2111_ENABLED || \ + DT_HAS_ATMEL_SAM0_GMAC_ENABLED || \ + DT_HAS_ATMEL_SAM_GMAC_ENABLED || \ + DT_HAS_ESPRESSIF_ESP32_ETH_ENABLED || \ + DT_HAS_INFINEON_XMC4XXX_ETHERNET_ENABLED || \ + DT_HAS_INTEL_E1000_ENABLED || \ + DT_HAS_LITEX_LITEETH_ENABLED || \ + DT_HAS_MICROCHIP_ENC28J60_ENABLED || \ + DT_HAS_MICROCHIP_ENC424J600_ENABLED || \ + DT_HAS_MICROCHIP_LAN865X_ENABLED || \ + DT_HAS_MICROCHIP_LAN9250_ENABLED || \ + DT_HAS_NUVOTON_NUMAKER_ETHERNET_ENABLED || \ + DT_HAS_NXP_ENET_ENABLED || \ + DT_HAS_NXP_ENET_MAC_ENABLED || \ + DT_HAS_NXP_ENET_QOS_ENABLED || \ + DT_HAS_NXP_ENET_QOS_MAC_ENABLED || \ + DT_HAS_NXP_S32_GMAC_ENABLED || \ + DT_HAS_RENESAS_RA_ETHERNET_ENABLED || \ + DT_HAS_SENSRY_SY1XX_MAC_ENABLED || \ + DT_HAS_SIEMENS_IVSHMEM_ETH_ENABLED || \ + DT_HAS_SILABS_GECKO_ETHERNET_ENABLED || \ + DT_HAS_SMSC_LAN91C111_ENABLED || \ + DT_HAS_SMSC_LAN9220_ENABLED || \ + DT_HAS_SNPS_DESIGNWARE_ETHERNET_ENABLED || \ + DT_HAS_SNPS_ETHERNET_CYCLONEV_ENABLED || \ + DT_HAS_ST_STM32_ETHERNET_ENABLED || \ + DT_HAS_TI_STELLARIS_ETHERNET_ENABLED || \ + DT_HAS_WIZNET_W5500_ENABLED || \ + DT_HAS_WIZNET_W6100_ENABLED || \ + DT_HAS_XLNX_GEM_ENABLED + +config NETWORKING + default y if ZCP_ETHERNET_DT + +config NET_L2_ETHERNET + default y if ZCP_ETHERNET_DT + +config NET_IPV4 + default y if ZCP_ETHERNET_DT + +config NET_DHCPV4 + default y if ZCP_ETHERNET_DT + +config NET_SOCKETS + default y if ZCP_ETHERNET_DT + +config NET_MGMT_EVENT + default y if ZCP_ETHERNET_DT + +config NET_MGMT_EVENT_INFO + default y if ZCP_ETHERNET_DT + +config HEAP_MEM_POOL_SIZE + default 4096 if ZCP_ETHERNET_DT + +# getaddrinfo() resolves hostnames through Zephyr's DNS resolver. Without it, +# the resolver symbols stay invisible and only literal IP addresses resolve; +# every hostname lookup returns DNS_EAI_NONAME ("Name or service not known"). +# DHCP feeds the resolver the DNS server from its lease via +# NET_DHCPV4_OPTION_DNS_ADDRESS (default y once DNS_RESOLVER is on). Boards +# can turn it off with CONFIG_DNS_RESOLVER=n in board.conf. +config DNS_RESOLVER + default y if NETWORKING + +# Every SOCK_STREAM socket, from the connection manager to the web workflow +# listener, needs the TCP stack. NETWORKING + NET_SOCKETS only give UDP until +# this is set: socketpool raises "Out of sockets" (because zsock_socket() +# fails with -EPFNOSUPPORT) for every TCP attempt. Silabs documented the same +# gap for its native-stack board, so default it on for every networked board. +config NET_TCP + default y if NETWORKING + +# Zephyr's 2 s DNS window gives exactly one query: the first lookup right +# after a boot (when the resolver just learned its server and the APR entry +# may not exist yet) gets cancelled outright, reported as DNS_EAI_CANCELED +# (-101). 10 s with 5 s backoff gives every lookup one retry. +config NET_SOCKETS_DNS_TIMEOUT + default 10000 if DNS_RESOLVER + +# The ENET-QoS RX thread's Zephyr default stack of 1024 bytes barely fits the +# driver, and overflows once the network stack logs (the packet-trace DBG +# lines in net_pkt land on this thread too), faulting with "Stack overflow" +# on ENETQOS_RX. 2048 covers normal operations; debug builds take more in +# debug.conf. +config ETH_NXP_ENET_QOS_RX_THREAD_STACK_SIZE + default 2048 + +# ZVFS_POLL_MAX must be strictly greater than the number of services +# registered on the socket-service thread: DNS_RESOLVER registers one and +# MDNS_RESPONDER two. Zephyr's default of 3 has no headroom for them, so the +# service thread fails at boot and every socket it owns is unread. +config ZVFS_POLL_MAX + default 6 if DNS_RESOLVER || MDNS_RESPONDER + +# Budgets for the network stack's tables. Zephyr's small defaults (6 network +# contexts, 8 connections, and a zero-based fd table that rounds up only to +# the subsystem adders) are exhausted by the DNS resolver's sockets, the +# web-workflow listener and the connection manager's socket pool together: +# socket creation then fails ("Out of sockets"), getaddrinfo() cannot hand its +# query to the resolver (reported as DNS_EAI_SYSTEM, "getaddrinfo failure: +# -11"), and Zephyr's socket service can walk freed table entries and fault. +# Each closed TCP connection holds a slot for TIME_WAIT, so the headroom also +# keeps web workflow bursts from being refused. 12, as on the boards that +# documented this before the default existed. +config NET_MAX_CONTEXTS + default 12 if NETWORKING + +config NET_MAX_CONN + default 12 if NETWORKING + +config ZVFS_OPEN_MAX + default 12 if NETWORKING + +# The per-interface TX/RX queue threads run the full network stack plus its +# logs; Zephyr's 1200/1500-1792 baselines overflow when the debug packet +# tracing lands on those threads, faulting rx_q[...] with "Stack overflow". +config NET_TX_STACK_SIZE + default 3072 if NETWORKING + +config NET_RX_STACK_SIZE + default 3072 if NETWORKING + +# The net_mgmt event thread runs interface/wifi/ethernet management callbacks +# (carrier, address add, DHCP bind...) — including their logging. Zephyr's 800 +# byte default overflows on those events. +config NET_MGMT_EVENT_STACK_SIZE + default 2048 if NETWORKING + +# ... and the socket-service thread, whose poll() set includes the DNS +# resolver's UDP sockets; its 1200 byte default overflows under DBG logs. +config NET_SOCKETS_SERVICE_STACK_SIZE + default 2400 if NETWORKING + +# ... and the TCP workqueue, which runs the whole TCP input path (segment +# processing, retransmit timers and the net_tcp DBG logs) on its own thread; +# Zephyr's 1024 default overflows under TCP DBG logging. +config NET_TCP_WORKQ_STACK_SIZE + default 2400 if NETWORKING + +# The mbedtls TLS configuration needed by shared-module/ssl (protocol, key +# exchange, RNG and PEM parsing). It applies to every board with a network +# interface (wifi, ethernet or offloaded sockets) because Zephyr's mbedtls +# build is fully Kconfig-driven: without PEM parsing, for example, +# shared-bindings/ssl cannot load PEM CAs. Boards can disable it with +# CONFIG_ZCP_MBEDTLS_TLS=n in their board.conf. +config ZCP_MBEDTLS_TLS + bool "mbedtls TLS support for the ssl module" + default y if WIFI || NET_L2_ETHERNET || NET_NATIVE_OFFLOADED_SOCKETS + # Client-side TLS as required by shared-module/ssl: TLS 1.2 with the + # ECDHE-RSA key exchange, X.509 certificates and PEM parsing. Selecting + # Zephyr's MBEDTLS_CIPHERSUITE_* config instead would also force RSA-PSS + # and RSA key-pair generation, which a TLS client never needs and which + # don't fit flash-tight boards. A board can still + # enable such cipher-suite extras in its board.conf. + select MBEDTLS_SSL_PROTO_TLS1_2 + select MBEDTLS_X509_CRT_PARSE_C + select MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED + select MBEDTLS_PEM_PARSE_C + # RNG: prefer the smaller external-RNG backend whenever the board has a + # CSPRNG driver (Zephyr's default), and only select the legacy entropy + + # CTR-DRBG path (several KB) on boards without one. + select MBEDTLS_ENTROPY_C if !MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG + select MBEDTLS_CTR_DRBG_C if !MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG + +# The PSA crypto wants needed to verify real-world certificate chains: certs +# signed with SHA-384/512 (e.g. Sectigo "R"-series CAs) and ECDSA signatures, +# plus the curve/cipher selection matching ports/espressif/sdkconfig so web +# TLS behaves the same. Gated on ZCP_MBEDTLS_TLS rather than set in prj.conf: +# Zephyr compiles PSA code for every wanted algorithm, so on BLE-only boards +# (which still get PSA crypto from CONFIG_PSA_CRYPTO for BT) the unconditional +# wants would build RSA/ECC code paths that fail -Werror (unused-parameter in +# dead rsa.c wrappers) or, on silabs, trip the driver-only-builds +# "Unsupported partial support for ECC curves acceleration" check. Boards can +# still override any of these in board.conf to save flash. +config PSA_WANT_ALG_SHA_384 + default y if ZCP_MBEDTLS_TLS + +config PSA_WANT_ALG_SHA_512 + default y if ZCP_MBEDTLS_TLS + +config PSA_WANT_ALG_ECDSA + default y if ZCP_MBEDTLS_TLS + +config PSA_WANT_ALG_GCM + default y if ZCP_MBEDTLS_TLS + +config PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY + default y if ZCP_MBEDTLS_TLS + +config PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY + default y if ZCP_MBEDTLS_TLS + +config PSA_WANT_ECC_SECP_R1_384 + default y if ZCP_MBEDTLS_TLS + +config PSA_WANT_ECC_SECP_R1_521 + default y if ZCP_MBEDTLS_TLS + +config PSA_WANT_ECC_SECP_K1_256 + default y if ZCP_MBEDTLS_TLS + +config PSA_WANT_ECC_MONTGOMERY_255 + default y if ZCP_MBEDTLS_TLS + +config PSA_WANT_ECC_BRAINPOOL_P_R1_256 + default y if ZCP_MBEDTLS_TLS + +config PSA_WANT_ECC_BRAINPOOL_P_R1_384 + default y if ZCP_MBEDTLS_TLS + +config PSA_WANT_ECC_BRAINPOOL_P_R1_512 + default y if ZCP_MBEDTLS_TLS + +# What the ECDHE-RSA / TLS 1.2 handshake itself needs (the PSA wants the +# removed Zephyr cipher-suite select used to bring in). These are also plain +# defaults so flash-tight boards can drop, e.g., RSA-PSS or the RSA key-pair +# operations a TLS client never performs. +config PSA_WANT_ALG_TLS12_PRF + default y if ZCP_MBEDTLS_TLS + +# ECDHE key exchange needs ECDH; mbedtls_check_config.h rejects +# MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED without it (MBEDTLS_CAN_ECDH). +config PSA_WANT_ALG_ECDH + default y if ZCP_MBEDTLS_TLS + +config PSA_WANT_ALG_HMAC + default y if ZCP_MBEDTLS_TLS + +config PSA_WANT_ALG_CBC_NO_PADDING + default y if ZCP_MBEDTLS_TLS + +config PSA_WANT_KEY_TYPE_AES + default y if ZCP_MBEDTLS_TLS + +config PSA_WANT_ALG_RSA_PKCS1V15_SIGN + default y if ZCP_MBEDTLS_TLS + +config PSA_WANT_ALG_RSA_PSS + default y if ZCP_MBEDTLS_TLS + +config PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_IMPORT + default y if ZCP_MBEDTLS_TLS + +config PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_IMPORT + default y if ZCP_MBEDTLS_TLS + +config PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_EXPORT + default y if ZCP_MBEDTLS_TLS + +config PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_GENERATE + default y if ZCP_MBEDTLS_TLS + +config PSA_WANT_ECC_SECP_R1_256 + default y if ZCP_MBEDTLS_TLS +# The BLE controller's "Assert on Prepare Latency" (lll_adv prepare_cb) halts +# the whole system with a kernel oops in the radio ISR when an ADV/connection +# event starts late. CircuitPython runs arbitrary user Python code, so the +# controller can never assume bounded CPU latency between events: a VM busy +# with GC, printing or a big allocation will occasionally push an event past +# its planned start (Zephyr GitHub issue #67868 fails exactly like this under +# CPU overheads). Defining the default here puts it before Zephyr's +# controller Kconfig, and Kconfig takes the first default, so late events are +# skipped gracefully instead of halting, as Zephyr's help text recommends. +# (The symbol resolves as promptless in this port's Kconfig tree - its +# visibility is 0 - so setting CONFIG_BT_CTLR_ASSERT_OVERHEAD_START=n in +# prj.conf/debug.conf is silently ignored, hence this defaults-module entry.) +config BT_CTLR_ASSERT_OVERHEAD_START + default n + +# ===== OTA firmware updates over BLE (SMP/MCUmgr) ===== +# +# Boards that boot under MCUboot opt in via boards///sysbuild.conf +# setting CONFIG_BOOTLOADER_MCUBOOT, which sysbuild turns into an app-side +# CONFIG_BOOTLOADER_MCUBOOT. OTA is enabled when the app boots from slot0 under +# MCUboot and has Bluetooth; the app boots with the image upload in slot1. +# +# A slot1_partition must also exist in the final app devicetree: the mcuboot +# fork's partition layout overlays are applied there, so boards.toml-driven +# layouts count. Boards with a single-app layout (e.g. stm32wba65i_dk1, +# siwx917_dk2605a) have no slot1 to stage an upload in, and zephyr_img_mgmt +# fails to build without one, so MCUmgr defaults off for them automatically +# instead of needing a CONFIG_MCUMGR=n override in board.conf. +# +# Gating on BOOTLOADER_MCUBOOT (not just on a slot1_partition existing) keeps +# boards that link the app over the whole flash (e.g. nrf54lm20dk) from letting +# an upload erase the running image that happens to overlap slot1. + +DT_HAS_SLOT1 := $(dt_nodelabel_enabled,slot1_partition) + +config ZCBOR + default y if BT && BOOTLOADER_MCUBOOT && $(DT_HAS_SLOT1) + +config MCUMGR + default y if BT && BOOTLOADER_MCUBOOT && $(DT_HAS_SLOT1) + +config MCUMGR_TRANSPORT_BT + default y if BT && BOOTLOADER_MCUBOOT + +config MCUMGR_TRANSPORT_BT_REASSEMBLY + default y if MCUMGR_TRANSPORT_BT + +# Just Works pairing for the SMP service. The port registers no interactive +# pairing callbacks (no display/keyboard IO capability; numeric comparison +# raises NotImplementedError here), so MITM-authenticated pairing can never +# complete. Zephyr's defaults are the opposite (BT_SMP_ENFORCE_MITM=y and the +# PERM choice defaulting to MCUMGR_TRANSPORT_BT_PERM_RW_AUTHEN), which puts +# WRITE_AUTHEN on the SMP characteristics and makes every SMP write fail with +# insufficient authentication. Pair Just Works and require encryption only, +# per the OTA policy documented in the port README. +config BT_SMP_ENFORCE_MITM + default n if BT && BOOTLOADER_MCUBOOT + +# The default for the SMP service's GATT-permission choice. Zephyr's own +# default (subsys/mgmt/mcumgr/transport/Kconfig.bluetooth) is +# MCUMGR_TRANSPORT_BT_PERM_RW_AUTHEN, which puts WRITE_AUTHEN on the SMP +# characteristics and makes every SMP write fail with insufficient +# authentication. This module Kconfig is merged before Zephyr's subsystem +# Kconfigs, so this `default` (on the choice, not the symbol) wins. The +# choice itself is Zephyr's; only the default is added here. +choice MCUMGR_TRANSPORT_BT_PERM + default MCUMGR_TRANSPORT_BT_PERM_RW_ENCRYPT if MCUMGR_TRANSPORT_BT +endchoice + +# Request a fast connection interval while an upload is in progress. +config MCUMGR_TRANSPORT_BT_CONN_PARAM_CONTROL + default y if MCUMGR_TRANSPORT_BT + +config IMG_MANAGER + default y if MCUMGR_TRANSPORT_BT + +# IMG_MANAGER ("DFU image manager") depends on STREAM_FLASH, which has no +# default of its own, so enable it with the same gate as IMG_MANAGER. +config STREAM_FLASH + default y if MCUMGR_TRANSPORT_BT + +config MCUMGR_GRP_IMG + default y if IMG_MANAGER + +config MCUMGR_GRP_OS + default y if MCUMGR_TRANSPORT_BT + +# Let clients discover the SMP buffer count/size so they can use optimal +# upload chunking and window sizes (the nRF Connect Device Manager apps do +# this automatically). +config MCUMGR_GRP_OS_MCUMGR_PARAMS + default y if MCUMGR_GRP_OS + +# Fit a full ATT write (the port raises BT_L2CAP_TX_MTU to 515) plus the +# 8-byte MCUmgr BT overhead in each buffer, so one upload packet fills one +# buffer instead of needing reassembly. +config MCUMGR_TRANSPORT_NETBUF_SIZE + default 528 if MCUMGR_TRANSPORT_BT + +# Debug logging for the whole MCUmgr stack (OTA/SMP) cannot be defaulted +# from Kconfig source: the per-module log levels (CONFIG_..._LOG_LEVEL_DBG) +# are members of anonymous Kconfig choices, so neither `default` on the int +# nor `select` on a choice member overrides the built-in "Default" member. +# Instead, the OTA boards (the ones whose .config has CONFIG_MCUMGR=y, +# i.e. BT + MCUboot + slot1) set the assignments in their board.conf: +# +# CONFIG_MCUMGR_LOG_LEVEL_DBG=y +# CONFIG_MCUMGR_TRANSPORT_LOG_LEVEL_DBG=y +# CONFIG_MCUMGR_GRP_IMG_LOG_LEVEL_DBG=y +# CONFIG_MCUMGR_GRP_OS_LOG_LEVEL_DBG=y +# +# (In a board.conf the assignments are only valid while MCUmgr is enabled, +# which is exactly what the OTA gate guarantees there.) With +# CONFIG_LOG_MODE_IMMEDIATE the logs go straight out of the console backend +# (the board's console UART), interleaved with the CircuitPython output. + +# ===== Resetting into the bootloader ===== +# +# The app asks the installed bootloader for its update mode (the state a +# double-tap of the reset button produces) on reset_to_bootloader() and +# microcontroller.OnNextReset(RunMode.UF2 / RunMode.BOOTLOADER), via the +# adaboot fork's adaboot/update_mode.h helpers. Two bootloaders are in play: +# +# - The fork's adaboot (MCUboot) reads the boot-mode retention flag (io.c's +# io_detect_boot_mode()), so the app needs the retained-memory chain +# enabled; the flag region (zephyr,boot-mode, e.g. gpregret1) is provided +# by the fork's dtsi, which sysbuild applies to the application image too. +# Every board that boots via adaboot has a boot-mode region in its layout +# (a GPREGRET register on the Nordic SoCs, a retained SRAM byte elsewhere). +# - The stock Adafruit nRF52 bootloader (the Adafruit boards, which boot UF2 +# with no MCUboot domain) reads the raw GPREGRET register instead, so no +# retention subsystem is needed for them. + +DT_BOOT_MODE_CHOSEN := zephyr,boot-mode +DT_BOOT_INFO_CHOSEN := zephyr,bootloader-info + +config RETAINED_MEM + default y if BOOTLOADER_MCUBOOT && ($(dt_chosen_enabled,$(DT_BOOT_MODE_CHOSEN)) || $(dt_chosen_enabled,$(DT_BOOT_INFO_CHOSEN))) + +config RETENTION + default y if RETAINED_MEM + +config RETENTION_BOOT_MODE + default y if RETENTION && $(dt_chosen_enabled,$(DT_BOOT_MODE_CHOSEN)) + +# Read the boot state (mode/running slot/version) the bootloader leaves in +# the zephyr,bootloader-info shared-data region, and teach Zephyr's SMP +# bootloader-info command the fork's identity: without a hook, the +# application-side handler reports the hardcoded "MCUboot" and derives the +# mode from the app's own Kconfig. The hook answers in +# supervisor/adaboot_info.c. +config RETENTION_BOOTLOADER_INFO + default y if BOOTLOADER_MCUBOOT && $(dt_chosen_enabled,$(DT_BOOT_INFO_CHOSEN)) + +config RETENTION_BOOTLOADER_INFO_TYPE_MCUBOOT + default y if RETENTION_BOOTLOADER_INFO + +config MCUMGR_MGMT_NOTIFICATION_HOOKS + default y if MCUMGR && RETENTION_BOOTLOADER_INFO_TYPE_MCUBOOT + +config MCUMGR_GRP_OS_BOOTLOADER_INFO + default y if MCUMGR + +config MCUMGR_GRP_OS_BOOTLOADER_INFO_HOOK + default y if MCUMGR_MGMT_NOTIFICATION_HOOKS diff --git a/ports/zephyr-cp/internal-modules/circuitpython-kconfig/zephyr/module.yml b/ports/zephyr-cp/internal-modules/circuitpython-kconfig/zephyr/module.yml new file mode 100644 index 00000000000..b0e6a3b5105 --- /dev/null +++ b/ports/zephyr-cp/internal-modules/circuitpython-kconfig/zephyr/module.yml @@ -0,0 +1,9 @@ +# Zephyr module descriptor for the defaults module. +# +# The module is loaded from the CircuitPython tree via ZEPHYR_EXTRA_MODULES in +# ports/zephyr-cp/CMakeLists.txt. It is Kconfig-only: it exists so its +# Kconfig merges before Zephyr's subsystem Kconfig files (see Kconfig here for +# why that ordering matters). +name: defaults +build: + kconfig: Kconfig diff --git a/ports/zephyr-cp/internal-modules/iobroker/CMakeLists.txt b/ports/zephyr-cp/internal-modules/iobroker/CMakeLists.txt new file mode 100644 index 00000000000..c4bc0642301 --- /dev/null +++ b/ports/zephyr-cp/internal-modules/iobroker/CMakeLists.txt @@ -0,0 +1,112 @@ +# iobroker Zephyr module build. +# +# The core is always compiled so that callers (CircuitPython's common-hal +# code) can include and call the module directly on +# every SoC. SoC-specific routing implementations are added under +# src///; without one the allocate functions report -ENOSYS. + +zephyr_library() +# SoC-agnostic core: package pin resolution, GPIO claims, pin-in-use. +zephyr_library_sources(src/iobroker.c) + +# SoC implementations live in src///. The nRF implementation +# covers every nRF SoC (they share one pinctrl encoding), so the +# level is the nRF family. Other vendors add their own directories and a +# corresponding zephyr_library_sources_ifdef() line here. +zephyr_library_sources_ifdef(CONFIG_PINCTRL_NRF + src/nordic/nrf/iobroker_route.c +) + +# Analog pad allocation: the nRF SAADC, the Renesas RA ADC/DAC and the +# emulated ADC/DAC devices used on native_sim. Other SoCs' implementations go +# into src/// and get a corresponding line here. +zephyr_library_sources_ifdef(CONFIG_ADC_NRFX_SAADC + src/nordic/nrf/iobroker_analog.c +) +if(CONFIG_DAC_RENESAS_RA) + zephyr_library_sources(src/renesas/ra/iobroker_analog.c) +endif() +if(CONFIG_ADC_EMUL OR CONFIG_DAC_TEST) + zephyr_library_sources(src/emul/iobroker_analog.c) +endif() +# The NXP MCX N LPADC/LPDAC implementation: covers both the two LPADC units +# and the LPDAC output. +if(CONFIG_ADC_MCUX_LPADC OR CONFIG_DAC_MCUX_LPDAC) + zephyr_library_sources(src/nxp/mcxn/iobroker_analog.c) +endif() + +# PWM channel allocation for the emulated PWM controllers on native_sim (the +# nRF implementation is part of src/nordic/nrf/iobroker_route.c). +zephyr_library_sources_ifdef(CONFIG_PWM_ADAFRUIT_EMUL + src/emul/iobroker_pwm.c +) +# Private headers shared by the core and the vendor implementations. +zephyr_library_include_directories(src) + +# Package pin map: render the TOML selected through the IOBROKER_PACKAGE +# choice into a build-directory translation unit. Kconfig has already run by +# the time module CMakeLists are included, so the CONFIG_ symbols are final +# here. When no reference map applies to the SoC, an empty map is generated +# instead, so package pin lookups fail cleanly with -EINVAL rather than the +# build failing to link. +set(IOBROKER_PACKAGE_CONFIGS + IOBROKER_PACKAGE_NRF54L15_QFN48 + IOBROKER_PACKAGE_NRF54LM20_CSP98 + IOBROKER_PACKAGE_NRF5340_QKAA + IOBROKER_PACKAGE_MDBT50Q_1MV2 + IOBROKER_PACKAGE_NRF52840_AQFN73 + IOBROKER_PACKAGE_RP2040_QFN56 + IOBROKER_PACKAGE_MCXN947_VDF + IOBROKER_PACKAGE_MCXN947_VNL +) +set(IOBROKER_PACKAGE_TOMLS + nrf54l15_qfn48 + nrf54lm20_csp98 + nrf5340_qkaa + mdbt50q_1mv2 + nrf52840_aqfn73 + rp2040_qfn56 + mcxn947_vdf + mcxn947_vnl +) +set(pkg_selected) +set(pkg_name) +foreach(pkg toml IN ZIP_LISTS IOBROKER_PACKAGE_CONFIGS IOBROKER_PACKAGE_TOMLS) + if(CONFIG_${pkg}) + set(pkg_selected ${pkg}) + set(pkg_name ${toml}) + endif() +endforeach() + +if(pkg_selected) + set(pkg_toml_file ${CMAKE_CURRENT_LIST_DIR}/packages/${pkg_name}.toml) + set(pkg_c_file ${CMAKE_CURRENT_BINARY_DIR}/package_pins_${pkg_name}.c) + add_custom_command(OUTPUT ${pkg_c_file} + COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_LIST_DIR}/tools/gen_package_c.py + ${pkg_toml_file} ${pkg_c_file} + DEPENDS ${pkg_toml_file} ${CMAKE_CURRENT_LIST_DIR}/tools/gen_package_c.py + COMMENT "iobroker: generating package pin map ${pkg_name}" + ) + set_source_files_properties(${pkg_c_file} PROPERTIES GENERATED TRUE) +else() + # No package map applies to this SoC (yet): an empty map keeps the symbols + # defined so the core can report -EINVAL for every package pin lookup. + set(pkg_c_file ${CMAKE_CURRENT_BINARY_DIR}/package_pins_empty.c) + file(WRITE ${pkg_c_file} + "// Generated by the iobroker module build -- no package pin map for this SoC.\n" + "#include \n" + "const iobroker_package_pin_t iobroker_package_pins[1] = {{0, 0, IOBROKER_PAD_NO_GPIO}};\n" + "const size_t iobroker_package_pin_count = 0;\n" + ) +endif() + +# The generated file is consumed by the zephyr target from the same +# directory, so order the compilation explicitly through a custom target. +add_custom_target(iobroker_package_pins DEPENDS ${pkg_c_file}) +add_dependencies(zephyr iobroker_package_pins) +target_sources(zephyr PRIVATE ${pkg_c_file}) + +# Register the public headers app-wide (zephyr_interface) so that external +# builds that consume Zephyr's exported compile flags, such as the +# CircuitPython static library build, can include them too. +zephyr_include_directories(include) diff --git a/ports/zephyr-cp/internal-modules/iobroker/Kconfig b/ports/zephyr-cp/internal-modules/iobroker/Kconfig new file mode 100644 index 00000000000..0265248ef5c --- /dev/null +++ b/ports/zephyr-cp/internal-modules/iobroker/Kconfig @@ -0,0 +1,53 @@ +# iobroker: dynamic peripheral allocation and runtime pin routing. +# +# The module's core is always compiled (see CMakeLists.txt); callers call it +# directly. Runtime routing needs SoC support: today it is implemented for +# nRF SoCs, whose pin control encoding can be computed at runtime and whose +# peripherals can be routed to (almost) any pin via PSEL. On other SoCs the +# allocate functions always report -ENOSYS. + +config IOBROKER_GPIO_MAX_PINS + int "Maximum number of pins allocatable for GPIO use" + default 32 + help + Size of the registry of pins claimed for plain GPIO use via + iobroker_gpio_allocate(). + +config IOBROKER_ANALOG_MAX_PINS + int "Maximum number of pins allocatable for analog use" + default 16 + help + Size of the registry of pads claimed for analog use (ADC inputs via + iobroker_adc_allocate(), DAC outputs via iobroker_dac_allocate()). + +choice IOBROKER_PACKAGE + prompt "SoC package pin map" + help + The module resolves requested package pins to SoC pads through the + package pin map selected here. Reference maps shipped with the module + live in packages/; the ONE_TO_ONE option is an identity map for boards + without a transcribed physical package, and NONE keeps the map empty so + every package pin lookup fails with -EINVAL. + +config IOBROKER_PACKAGE_ONE_TO_ONE + bool "1:1 (package pin number is the global pin number)" + help + Identity package pin map: package pin N maps to SoC pad N, where the + SoC pad is the global pin numbering (gpio port index * 32 + pin within + the port). Boards without a transcribed physical package, such as the + native simulator, use this so that pin objects can hand the iobroker + module a package pin that resolves to their pad. + +config IOBROKER_PACKAGE_NONE + bool "None (package pin lookups fail)" + help + No package pin map is available for this SoC yet. Package pin + lookups (and therefore pin claims and bus pin routing) fail with + -EINVAL until a reference map is added for the SoC. + +# Reference maps (one option per package transcribed from a SoC datasheet) +# live in Kconfig.packages; each depends on the SOC_* symbols of the SoCs the +# map applies to, so only the options valid for the selected SoC are visible. +rsource "Kconfig.packages" + +endchoice diff --git a/ports/zephyr-cp/internal-modules/iobroker/Kconfig.packages b/ports/zephyr-cp/internal-modules/iobroker/Kconfig.packages new file mode 100644 index 00000000000..d435ad97ca9 --- /dev/null +++ b/ports/zephyr-cp/internal-modules/iobroker/Kconfig.packages @@ -0,0 +1,93 @@ +# Reference package pin maps for the IOBROKER_PACKAGE choice. +# +# Generated by hand from the transcriptions in packages/*.toml (one option per +# TOML, depends on the SOC_* symbols of the SoCs the map applies to). When a +# package option is invisible the SoC does not come in that package, so the +# option cannot be selected or set from conf fragments either. +# +# Choice defaults live here too, most-specific first: the development kits' +# packages preselect the reference map for their SoC; boards with more than +# one matching package (e.g. nRF52840 modules) set their choice explicitly in +# board.conf; SoCs with no reference map fall back to the 1:1 identity map +# (package pin number == global pin number), which lets their pins resolve. + +config IOBROKER_PACKAGE_NRF54L15_QFN48 + bool "nRF54L15/10/05 QFN48 (QFAA)" + depends on SOC_NRF54L15 || SOC_NRF54L10 || SOC_NRF54L05 + help + QFN48 package pin map for the nRF54L15, nRF54L10 and nRF54L05, which + are pin-compatible. 48 pins, 31 routable GPIOs. Used by the + nRF54L15 DK. + +config IOBROKER_PACKAGE_NRF54LM20_CSP98 + bool "nRF54LM20 CSP98 (PAAA)" + depends on SOC_NRF54LM20A || SOC_NRF54LM20B + help + CSP98 (flip-chip) package pin map for the nRF54LM20A and nRF54LM20B. + 98 balls, 66 routable GPIOs, numbered sequentially in row-major order + (the datasheet labels them A1..K10). Used by the nRF54LM20 DK. + +config IOBROKER_PACKAGE_NRF5340_QKAA + bool "nRF5340 aQFN94 (QKAA)" + depends on SOC_NRF5340_CPUAPP + help + aQFN94 package pin map for the nRF5340 application core. 94 balls + (plus four corner pads and a die pad, not in the map), all 48 GPIOs + bonded, numbered sequentially in row-major order (the datasheet only + labels the balls, e.g. A17). Used by the nRF5340 DK and the nRF7002 DK. + +config IOBROKER_PACKAGE_MDBT50Q_1MV2 + bool "Raytac MDBT50Q-1MV2 module" + depends on SOC_NRF52840_QIAA + help + Pin map for the Raytac MDBT50Q-1MV2 module, which carries the + nRF52840 aQFN73 inside. 'pin' numbers the module's 61 castellated + pins as the datasheet numbers them and 'pad' remaps them to the + aQFN73 ball ids they bond to; 'gpio' carries each pad's global GPIO + number. + +config IOBROKER_PACKAGE_NRF52840_AQFN73 + bool "nRF52840 aQFN73 (NQI73)" + depends on SOC_NRF52840_QIAA + help + aQFN73 package pin map for the nRF52840. 73 balls, all 48 GPIOs + bonded, numbered sequentially in row-major order (the datasheet only + labels the balls, e.g. A8). + +config IOBROKER_PACKAGE_RP2040_QFN56 + bool "RP2040 QFN-56" + depends on SOC_RP2040 + help + QFN-56 package pin map for the RP2040. 30 user GPIOs (the package + pin map covers GPIO0..GPIO29; QSPI and power pins are omitted), + numbered as the datasheet numbers the pins. Used by the Feather + RP2040 board. + +config IOBROKER_PACKAGE_MCXN947_VDF + bool "MCXN947 VFBGA184 (VDF)" + depends on SOC_MCXN947 + help + 184-ball VFBGA package (9 x 9 mm, 0.5 mm pitch) pin map for the + MCXN947, which Zephyr orders as MCXN947VDF. Used by the + FRDM-MCXN947 board. 184 balls, 124 routable GPIOs, numbered + sequentially in row-major order (the datasheet only labels the + balls, e.g. A17). + +config IOBROKER_PACKAGE_MCXN947_VNL + bool "MCXN947 HLQFP100 (VNL)" + depends on SOC_MCXN947 + help + 100-pin HLQFP package (0.5 mm pitch) pin map for the MCXN947, + which Zephyr orders as MCXN947VNL. 100 pins, 78 routable GPIOs, + numbered as the datasheet numbers the pins. + +choice IOBROKER_PACKAGE + default IOBROKER_PACKAGE_NRF54L15_QFN48 if SOC_NRF54L15 || SOC_NRF54L10 || SOC_NRF54L05 + default IOBROKER_PACKAGE_NRF54LM20_CSP98 if SOC_NRF54LM20A || SOC_NRF54LM20B + default IOBROKER_PACKAGE_NRF5340_QKAA if SOC_NRF5340_CPUAPP_QKAA + default IOBROKER_PACKAGE_NRF52840_AQFN73 if SOC_NRF52840_QIAA + default IOBROKER_PACKAGE_RP2040_QFN56 if SOC_RP2040 + default IOBROKER_PACKAGE_MCXN947_VDF if SOC_PART_NUMBER_MCXN947VDF + default IOBROKER_PACKAGE_MCXN947_VNL if SOC_PART_NUMBER_MCXN947VNL + default IOBROKER_PACKAGE_ONE_TO_ONE +endchoice diff --git a/ports/zephyr-cp/internal-modules/iobroker/README.md b/ports/zephyr-cp/internal-modules/iobroker/README.md new file mode 100644 index 00000000000..6435dc43373 --- /dev/null +++ b/ports/zephyr-cp/internal-modules/iobroker/README.md @@ -0,0 +1,233 @@ +# iobroker + +A Zephyr module for **dynamic peripheral allocation and runtime pin routing**: +pick a free peripheral instance (I2C, SPI, UART, PWM) enabled in the +devicetree, re-route it to requested pins at runtime and hand the Zephyr +device to the caller. + +Pins are specified using `package_pin_t` and represent a single pin on a package +or module containing a system-on-a-chip (SoC). This is the most common boundary +between an SoC and printed circuit board (PCB). Packages and modules may choose +to map more than one SoC pin to a package pin and this way IOBroker ensures that +each package pin is only used for one thing at a time. GPIO port and pin numbers +are often used as names for these pins but using package pins allow us to +accommodate pins without GPIO and those with multiple GPIO. + +IOBroker takes in a number of package pins and a device type. Device types are +usually `drivers/` in the zephyr source tree. For example, +`int iobroker_i2c_allocate(package_pin_t sda, package_pin_t scl, const struct device **dev_out);` +will find a Zephyr I2C device that pins sda and scl can be connected to, connect +them using pinctrl, claim these resources and return it. It will return +`-ENODEV` if no such device can be found. The board DTS must enable these +devices with `status = "okay";`, mark them as `zephyr,deferred-init;` and +provide default pinctrl settings that will be overridden. + +## Status + +Currently, runtime routing is implemented for nRF SoCs, whose pin control +encoding can be computed at runtime and whose peripherals can be routed to +(almost) any pin via PSEL. On other SoCs the module compiles but the allocate +functions always return `-ENOSYS`. + +Analog pads are allocated through two function pairs, ADC inputs via +`iobroker_adc_allocate()` and DAC outputs via `iobroker_dac_allocate()`. Both +have no routing: the pad's analog function is fixed by the SoC, so the call +resolves it (for example a SAADC AIN number, or the RA's PmnPFS.ASEL analog +switch) from a per-SoC table, claims the pad and hands out a free channel slot +on the analog device. Zephyr's ADC API has no channel release, so the release +implementation unconfigures the slot per SoC (through `nrfx` for the SAADC). +See `src/nordic/nrf/iobroker_analog.c`, `src/nxp/mcxn/iobroker_analog.c`, +`src/renesas/ra/iobroker_analog.c` and `src/emul/iobroker_analog.c`. + +## Source layout + +The source is organized by vendor and SoC family under `src/`: + +``` +src/ + iobroker.c # SoC-agnostic core: package pin map + # lookup, GPIO controller split, claim + # registry, -ENOSYS stubs when routing + # is unavailable + iobroker_internal.h # helpers shared between core and + # vendor implementations (private) + nordic/ + nrf/ # every nRF SoC shares one pinctrl + iobroker_route.c # encoding, so the family is one dir + nxp/ + mcxn/ # NXP MCX N: LPADC inputs and the LPDAC + iobroker_analog.c # output pad resolve from the pin + # functions table +``` + +The core compiles on every SoC. Each vendor adds a `src///` +directory with an implementation of the bus allocate/release functions and a +corresponding `zephyr_library_sources_ifdef()` line in `CMakeLists.txt`; +without one the core's `#if !IOBROKER_ROUTING` stubs report `-ENOSYS`. When +an implementation covers a whole SoC family (as the nRF one does, keyed on +`CONFIG_PINCTRL_NRF`), the directory is named for the family. + +## Enabling + +The module is registered by the CircuitPython Zephyr application +(`ports/zephyr-cp/CMakeLists.txt`) via `ZEPHYR_EXTRA_MODULES`, so it works +without west manifest changes. Its core is always compiled and its callers +include `` directly; runtime routing additionally +requires `CONFIG_PINCTRL_DYNAMIC` and `CONFIG_DEVICE_DEINIT_SUPPORT`, which +the port enables by default on nRF SoCs. + +## Board tables + +The core does not know which instances are allocatable; the application must +provide per-board tables (the generated `board.c` always emits them): + +```c +const iobroker_instance_t iobroker_i2c_buses[]; // + _states[] and _bus_count +const iobroker_instance_t iobroker_spi_buses[]; // ... +const iobroker_instance_t iobroker_uart_buses[]; // ... +const iobroker_instance_t iobroker_pwm_buses[]; // ... +const struct device * const iobroker_gpio_port_devices[]; // + _indexes[] and _count +const iobroker_package_pin_t iobroker_package_pins[]; // + _pin_count +const uint16_t iobroker_reserved_pads[]; // + _pin_count +``` + +The package pin map is selected from the module's reference maps: +`Kconfig.packages` offers one option per transcribed package +(`packages/*.toml`), each visible only for the SoCs it applies to and +preselected for the development kits. The map's SoC pads are numbered by +the package's own pin ids (row-major ball order, or the datasheet's pin +number for a QFN/QFP package); each pad carries the global GPIO number +it bonds to when it sits on a GPIO controller. Analog-only pads (pads no +GPIO controller covers, e.g. MCX N's ANA pads) carry the datasheet's pad +name in `pad_name` and become pin objects named by `zephyr2cp.py` from +that name, so analogio can reach them. SoCs with no reference map fall +back to `IOBROKER_PACKAGE_ONE_TO_ONE`, an identity map where the package +pin number is the global pin number (gpio port index * 32 + pin within +the port), so boards without a transcribed physical package can still +resolve their pins. `IOBROKER_PACKAGE_NONE` is also available and +generates an empty map, making package pin lookups fail with `-EINVAL`. +The selected TOML (or the empty map) is rendered into a build-directory +translation unit at build time. The identity map needs no rendered +table: the core applies it directly. +New maps are transcribed from a SoC datasheet with `tools/gen_package.py` +(see the script's docstring; the datasheets live in `datasheets/`). +Each instance entry contains the Zephyr device, its `struct +pinctrl_dev_config` (via `PINCTRL_DT_DEV_CONFIG_DECLARE`/`_GET`) and, when the +devicetree state has fixed pins, the raw `pinctrl_soc_pin_t` values of the +"default" state. Instances whose devicetree "default" state leaves every +signal disconnected (`NRF_PIN_DISCONNECTED`) set `.dt_psels = NULL` and can be +routed to any pin at runtime. Instances with fixed devicetree pins are only +allocatable when a request matches their existing state. + +In the CircuitPython tree these tables are generated into the board's +`board.c` by `cptools/zephyr2cp.py` at build time. + +`iobroker_reserved_pads` lists the SoC pads that fixed peripherals (console +UART, flash instance, I2S, ...) drive at boot through their devicetree +pinctrl default state. `iobroker_pin_in_use()` reports them as busy so that +allocate() rejects requests for those pads with `-EBUSY` instead of +re-routing pads something else is already driving. The table only contains +connected pins; dynamically routable instances (all signals disconnected in +the devicetree) contribute nothing. + +The GPIO controller table pairs each controller device with its hardware +port index. The indexes define the global pin numbering (index * 32 + pin +within the port) shared with the pin objects, and let the module resolve a +global pin number back to the controller device and pin number that +Zephyr's GPIO API takes. + +## nRF serial instances + +On nRF SoCs, the I2C and SPI nodes with the same instance number are one +peripheral, and on nRF53, nRF54L and nRF91 so is the UART node: on the +nRF52840, `i2c1` and `spi1` are both the peripheral at 0x40004000. Only one +mode of an instance can be enabled, which Zephyr checks at build time +(`zephyr/soc/nordic/validate_enabled_instances.c`). + +So the board overlay decides how many instances of each kind there are. It +enables each free instance in one mode, with all signals disconnected and +`zephyr,deferred-init`, and leaves alone the instances the board uses for a +fixed purpose, such as the console or external flash. The overlay's +comment says what it chose and why. + +The Feather nRF52840 boards use the same split as `ports/nordic`, whose +`nrfx_config.h` defaults to `CIRCUITPY_NRF_NUM_I2C` = 2: + +| Kind | Instances | +|---|---| +| I2C | `i2c0`, `i2c1` (TWIM) | +| SPI | `spi2`, `spi3` (SPIM) | +| UART | `uart0`, `uart1` (UARTE, separate peripherals on nRF52) | + +`spi0` and `spi1` stay disabled because I2C has those instances. + +`zephyr2cp.py` lists each pool's instances by devicetree `max-frequency`, +highest first, and iobroker allocates the first free instance that can +reach the requested pins. So busio gets the nRF52840's 32 MHz SPIM3 before +the 8 MHz SPIM2, and on the nRF54L the 32 MHz `spi00` before the 8 MHz +instances, when a board leaves `spi00` dynamic. + +## Public API + +See `include/iobroker/iobroker.h`. Signals are requested with +`package_pin_t` values (`PACKAGE_PIN(n)`): the physical package pin numbered +as the SoC datasheet numbers it (QFN pins 1..N; CSP/BGA balls numbered +sequentially in row-major order, with the datasheet's ball label noted in the +map and the generated C). The module resolves package pins to SoC pads +through the package pin map, `iobroker_package_pins[]`, selected via +`CONFIG_IOBROKER_PACKAGE_*` (see above); internally the lookup then +proceeds package pin -> SoC pad -> peripheral routing. `IOBROKER_NO_PIN` leaves a +signal disconnected. Pull resistors are chosen by the module per bus signal +(I2C SDA/SCL and UART RX idle high). Every allocate call must be paired with +`iobroker_release()`, so the application owns the lifecycle. Releasing also +leaves the pins quiescent: `iobroker_release()` de-initializes the device, +which applies its low-power pinctrl state to the routed pins. +`iobroker_pin_in_use()` reports whether a package pin is claimed by a +currently allocated instance, and `allocate()` refuses (-EBUSY) requests that +would double-use a pin. Package pins can also be claimed for plain GPIO use +with `iobroker_gpio_allocate()` / `iobroker_gpio_release()`: the caller +configures the pad while the claim is held and the module returns it to a +quiescent state (disconnected) on release, and GPIO claims conflict with bus +allocations the same way bus allocations conflict with each other. +`iobroker_gpio_allocate()` resolves the package pin through the map +and returns both the GPIO controller device and the pin number within it. +PWM channels are allocated with `iobroker_pwm_channel_allocate()`, which +shares an instance between pins. Channels that share a period form a group +(for instance, on nRF, the four outputs of an instance; on other SoCs this +might be a slice or a timer). The call takes the requested frequency only as +the sharing key: it joins a running group requested at exactly the same +frequency and with a free channel, or takes a free instance. It returns the +device and the channel number; the caller turns the frequency into a period +itself and passes it to `pwm_set_cycles()`. Checking that the hardware can +produce that period is left to the driver, which doesn't reliably do so yet. +Joining or leaving a running group connects or disconnects only that one +output, so the group's other outputs are not disturbed. An exclusive request +gets a group of its own that nobody joins: pwmio uses it for a variable +frequency, and neopixel_write to program a whole nRF instance itself. +`iobroker_pwm_channel_release()` returns a channel; the group's last channel +releases the instance. + +Not every instance can reach every pad. On nRF52 and nRF53 the routing is a +full crossbar, but on nRF54L peripherals and GPIO controllers are grouped in +power domains and a peripheral can only drive pads of its own domain (the +domain is encoded in the register addresses, which the instance and GPIO +controller tables carry). An allocate call whose pins no instance of the +requested kind can reach fails with `-EINVAL`, like a pin that is not in +the package map: it is a property of the request, distinct from `-ENODEV` +for "every instance that could is busy", so callers can report a wrong pin +choice rather than a busy peripheral. +`iobroker_gpio_package_pin()` maps a GPIO controller's hardware port index +and pin number (the two halves of the global pin numbering) back to the +package pin the pad is bonded to. + +## Externalizing + +This module is application-agnostic: it depends only on Zephyr. To move it +into its own repository: + +1. Copy this directory (minus this README) to the new repo root, keeping + `zephyr/module.yml`, `CMakeLists.txt`, `Kconfig`, `include/` and `src/`. +2. Point `ZEPHYR_EXTRA_MODULES` in `ports/zephyr-cp/CMakeLists.txt` at the new + checkout, or register it as a project in `zephyr-config/west.yml`. +3. Keep `iobroker.h`'s struct/function names stable — the generated + board tables are part of the module's de-facto API. diff --git a/ports/zephyr-cp/internal-modules/iobroker/datasheets/README.md b/ports/zephyr-cp/internal-modules/iobroker/datasheets/README.md new file mode 100644 index 00000000000..584d82e7971 --- /dev/null +++ b/ports/zephyr-cp/internal-modules/iobroker/datasheets/README.md @@ -0,0 +1,64 @@ +# Datasheets + +The package pin maps in `../packages/` are transcribed from Nordic's SoC +datasheets. The PDFs are not redistributed in this repository; download them +from Nordic (https://docs.nordicsemi.com) into this directory and verify them +against the SHA-256 hashes below before regenerating a map. + +| File | SHA-256 | +|------|---------| +| `nRF54L15_nRF54L10_nRF54L05_Datasheet_v1.0.pdf` | `ade0d340ba95e31f8299e6721b08d53a702962335d9b87fa202f8d2767603554` | +| `nRF54LM20A_nRF54LM20B_Datasheet_v1.0.pdf` | `03a834fb52be8cf6248df6f67737f055c035cfb83492d44d58bdc2f0bfa3a3af` | +| `nRF5340_PS_v1.6.pdf` | `fe5c7e8908c94080548a1ddd4ec8b96aa09a4b97239fe9b32afb49eb8cf2fc87` | +| `nRF52840_PS_v1.1.pdf` | `c619e336b9c0610663273041f057f2537a65fd408ce0c5b8214a26de2aa88422` | +| `[nRF52840] MDBT50Q-1MV2 & MDBT50Q-P1MV2_Ver.L spec.pdf` | `61fec8c0c9f8c33175be2237a8ebba73c6cfc0a3572fe3835fd341079c103d03` | +| `rp2040-datasheet.pdf` | `be56fbb75ba0ae9e26558a73c93ac3e75c2ad4e6878d3b6703de2a76d886ea8c` | +| `MCXNP184M150F70.pdf` | `f3a680d2ac36960f81b474e9e7589ab7a54fc2690eaf9baa67de1d442c5135aa` | +| `MCXNP184M150F70_Pinout.xlsx` | `ba047de2d40dc99caf32502abd3afb69e88f8168dd767949f57d37a67e4295a5` | +| `UM12018(3).pdf` | `2036bf71b7a474e7cd37c55e90af2d87d09bd41d2decf30630480f7de1c68469` | +| `FRDM-MCXN947-TOP.avif` | `5ac1064c118947bd1418e248d1b6210d739fda7c8af9d7b4e600910368173e46` | + +The nRF52840 Product Specification is Nordic's, downloadable from +https://docs.nordicsemi.com; the copy here came from +https://cdn-learn.adafruit.com/assets/assets/000/092/427/original/nRF52840_PS_v1.1.pdf. +The MDBT50Q module datasheet is Raytac's, from +https://www.raytac.com. The RP2040 datasheet is Raspberry Pi's, from +https://datasheets.raspberrypi.com/rp2040/rp2040-datasheet.pdf. + +MCXNP184M150F70.pdf is NXP's MCXN947/946/547/546/537/536/527/526/247 +product data sheet (document MCXNP184M150F70, Rev. 8.2, 11 June 2026), +downloadable from https://www.nxp.com (MCX-N947 product page). +UM12018(3).pdf is NXP's FRDM-MCXN947 Board User Manual (UM12018 Rev. 2.0), +from https://www.nxp.com/docs/en/user-guide/UM12018.pdf. The FRDM board +photos come from the board's website (https://www.nxp.com/design/design-center/development-boards-and-designs/FRDM-MCXN947) +and show the header silkscreen. + +MCXNP184M150F70_Pinout.xlsx is the pinout workbook attached to the data +sheet (Signal multiplexing and pin assignments; from the document's +Download PDF bundle at https://docs.nxp.com/bundle/MCXNP184M150F70), +with the full ball/pin map of each package, power pins included. + +The MCX N maps in `packages/mcxn947_*.toml` come from the datasheet's +section 6.1 Table 93 (Pinmux): the 184BGA column is the VFBGA184 package +(Zephyr's MCXN947VDF part number, the FRDM board's chip) and the 100HLQFP +N94 column is the MCXN947/MCXN946 100-pin HLQFP (MCXN947VNL). The +transcription command lines are recorded in the header of each +`packages/*.toml`; the pin ids for the VFBGA184 map come from the +workbook's VFBGA184 tab (the full 184-ball map, power balls included, so +the pad ids carry the datasheet's gaps). Table 93 also lists the +analog-only pads (Pad type - ANA), which are not wired to a GPIO +controller: ANA_0 = ADC0_A0 (the FRDM's Arduino A0), ANA_1 = ADC0_B0 +(Arduino A1), ANA_4 = ADC1_A0 (the mikroBUS AN input), ANA_5 = ADC1_B0, +ANA_6 = the DAC2 (HPDAC) output, ANA_14/18/22 = OPAMP inputs, ANA_7 +unused. Both mcxn947 maps carry them +in the row-major ball numbering; zephyr2cp names their pin objects +ANA_x and binds the board's A0/A1 aliases to them, so analogio reaches +them. The DAC2 output stays unsupported: the iobroker DAC backend binds +the LPDAC (dac0, muxed on the P4_02 pad). + +The transcription command lines are recorded in the header of each +`packages/*.toml` (section number, package name, pin count). After running +`pdftotext -layout` on a verified PDF, the same command reproduces the map. + +This directory is ignored by git; this README is force-added so the hashes +stay with the code. diff --git a/ports/zephyr-cp/internal-modules/iobroker/include/iobroker/iobroker.h b/ports/zephyr-cp/internal-modules/iobroker/include/iobroker/iobroker.h new file mode 100644 index 00000000000..1609826fefe --- /dev/null +++ b/ports/zephyr-cp/internal-modules/iobroker/include/iobroker/iobroker.h @@ -0,0 +1,363 @@ +// iobroker: dynamic peripheral allocation and runtime pin routing. +// +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +// Allocate a free bus instance (I2C, SPI, UART) enabled in the devicetree, +// route it to the requested pins at runtime and hand the Zephyr device to the +// caller. Per-board tables of allocatable instances are provided by the +// application (the CircuitPython build generates them from the board's +// devicetree; see modules/iobroker/README.md for the contract). +// +// Runtime routing works on nRF SoCs because their pin control encoding is a +// simple bit-packed value (see zephyr/dt-bindings/pinctrl/nrf-pinctrl.h and +// soc/nordic/common/pinctrl_soc.h) that can be computed at runtime, and any +// peripheral function can be routed to (almost) any pin via PSEL. + +#pragma once + +#include +#include +#include + +#include +#include + +// Runtime bus routing lets the module re-route a bus instance's pins at +// runtime. It is available when Zephyr is built with dynamic pinctrl states and +// device de-init support. Without it the bus allocate/release functions report +// -ENOSYS and the bus instance tables are not used. +#if defined(CONFIG_PINCTRL_NRF) && defined(CONFIG_PINCTRL_DYNAMIC) && \ + defined(CONFIG_DEVICE_DEINIT_SUPPORT) +#define IOBROKER_ROUTING 1 +#else +#define IOBROKER_ROUTING 0 +#endif + +// ADC pad allocation is available when a supported ADC device is built: the +// nRF SAADC driver (src/nordic/nrf/), the NXP MCX N LPADC +// (src/nxp/mcxn/) or the emulated ADC (src/emul/, native_sim). Without it +// the allocate function reports -ENOSYS. +#if defined(CONFIG_ADC_NRFX_SAADC) || defined(CONFIG_ADC_EMUL) || \ + defined(CONFIG_ADC_MCUX_LPADC) +#define IOBROKER_ADC 1 +#else +#define IOBROKER_ADC 0 +#endif + +// DAC pad allocation is available when a supported DAC device is built: the +// Renesas RA DAC (src/renesas/ra/), the NXP MCX N LPDAC (src/nxp/mcxn/) or +// the emulated test DAC (src/emul/, native_sim). Without it the allocate +// function reports -ENOSYS. +#if defined(CONFIG_DAC_TEST) || defined(CONFIG_DAC_RENESAS_RA) || \ + defined(CONFIG_DAC_MCUX_LPDAC) +#define IOBROKER_DAC 1 +#else +#define IOBROKER_DAC 0 +#endif + +// PWM channel allocation (iobroker_pwm_channel_allocate()) is available with +// nRF runtime routing (src/nordic/nrf/) and with the emulated PWM on +// native_sim (src/emul/). Without it the PWM channel functions report +// -ENOSYS. +#if IOBROKER_ROUTING || defined(CONFIG_PWM_ADAFRUIT_EMUL) +#define IOBROKER_PWM_CHANNELS 1 +#else +#define IOBROKER_PWM_CHANNELS 0 +#endif + +// Signals needed by the widest bus (UART with tx/rx/rts/cts). +#define IOBROKER_MAX_PINS 4 + +// Package pin that leaves a signal disconnected (only valid for optional +// signals such as UART rts/cts). +#define IOBROKER_NO_PIN ((package_pin_t)0xffff) + +// Marker for a SoC pad with no GPIO controller (an analog-only pad). +#define IOBROKER_PAD_NO_GPIO ((uint16_t)0xffff) + +// A physical pin of the SoC's package, numbered the way the SoC datasheet +// numbers its package pins (1..N for QFN-style packages; BGA-style packages +// use the datasheet's sequential numbering of the balls). Translating a pin +// name from a schematic or board layout to a package pin is a board concern; +// the module only knows the package pin -> SoC pad mapping below. +typedef uint16_t package_pin_t; + +// Wrap a datasheet package pin number into a package_pin_t. +#define PACKAGE_PIN(number) ((package_pin_t)(number)) + +// One entry of the package pin map: a physical package pin and the SoC pad +// it is bonded to. The SoC pad is numbered by the package's pin ids -- balls +// in row-major order for a ball grid (the datasheet only labels them, e.g. +// A17), or the datasheet's pin number for a QFN/QFP package. Pads bonded to +// a GPIO controller carry that bond as their global GPIO number (port index +// * 32 + pin within the port, what the GPIO controller table below +// resolves); analog-only pads, which no GPIO controller covers, have no +// bond and only the analog APIs reach them, through their package pin. +// Package pins that bond neither a GPIO nor an analog function (power, ...) +// are omitted; requesting one fails with -EINVAL. +// +// The map is generated by the module build from the selected IOBROKER_PACKAGE +// choice (see packages/), or as an empty map when no package applies to the +// SoC. With an empty map every package pin lookup fails with -EINVAL. +typedef struct { + package_pin_t package_pin; + uint16_t soc_pad; + // Global GPIO number the pad is bonded to, or IOBROKER_PAD_NO_GPIO when + // the pad has no GPIO controller (an analog-only pad). + uint16_t gpio_pad; +} iobroker_package_pin_t; + +extern const iobroker_package_pin_t iobroker_package_pins[]; +extern const size_t iobroker_package_pin_count; + +// GPIO controller table: the board lists every GPIO controller together with +// its hardware port index, which defines the global pin numbering +// (index * 32 + pin). Generated into board.c; boards without GPIO +// controllers generate an empty table, so lookups return -EINVAL. +extern const struct device *const iobroker_gpio_port_devices[]; +extern const uint8_t iobroker_gpio_port_indexes[]; +// Register block address of each controller, same order; see +// iobroker_instance_t.reg_addr. +extern const uint32_t iobroker_gpio_port_addrs[]; +extern const size_t iobroker_gpio_port_count; + +// Resolve a global pin number to its GPIO controller device and the pin +// number within that controller (the two values Zephyr's GPIO API takes). +// Returns 0, or -EINVAL when no controller covers the number. +int iobroker_gpio_split(uint16_t number, const struct device **port_out, + gpio_pin_t *pin_out); + +// Map a GPIO controller's hardware port index and the pin number within it +// (the two halves of the global pin numbering: index * 32 + pin) to the +// package pin the pad is bonded to. The inverse of the package pin map's +// soc_pad column. Returns 0, or -EINVAL when the pad has no entry in the +// package pin map. +int iobroker_gpio_package_pin(uint8_t port, gpio_pin_t pin, + package_pin_t *package_pin_out); + +#if defined(CONFIG_PINCTRL_NRF) + +#include + +// Description of one allocatable bus instance. Filled in by the board tables. +typedef struct { + const struct device *dev; + // Register block address of the instance, from the devicetree. The SoC + // routing code uses it to decide which pads the instance can reach: on + // nRF54L, peripherals only drive pads of their own power domain, which + // the address encodes. + uint32_t reg_addr; + // Pin control configuration of the device. Mutable because + // CONFIG_PINCTRL_DYNAMIC moves these to RAM so that states can be + // swapped at runtime. + struct pinctrl_dev_config *pcfg; + // Pin control entries of the devicetree "default" state, or NULL when + // the instance was enabled with disconnected pins so that it can be + // routed dynamically to any pin. + const pinctrl_soc_pin_t *dt_psels; + uint8_t dt_psel_count; +} iobroker_instance_t; + +// Runtime bookkeeping for one allocatable bus instance. The arrays live for +// the life of the firmware because Zephyr's pinctrl API keeps pointers to +// them inside the device's pinctrl_dev_config. +typedef struct { + pinctrl_soc_pin_t default_pins[IOBROKER_MAX_PINS]; + pinctrl_soc_pin_t sleep_pins[IOBROKER_MAX_PINS]; + struct pinctrl_state states[2]; + bool in_use; + // True when the instance's states were swapped for runtime-built entries. + bool routed; + // Package pins the current allocation claims (copies of the request). + // Used by iobroker_pin_in_use(); empty while the instance is free. + package_pin_t pins[IOBROKER_MAX_PINS]; + uint8_t pin_count; + // The fields below are used only for PWM instances allocated by channel + // (iobroker_pwm_channel_allocate()); buses leave them 0. + // Frequency in Hz that the instance's channels were requested at; a + // request joins only at exactly this frequency. + uint32_t frequency; + // True when one caller holds the instance alone, so no other channel + // may join it. + bool exclusive; + // Bit n is set while output n is allocated to a channel. + uint8_t channels_used; +} iobroker_state_t; + +// Generated board tables, emitted by the board's generated board.c whenever +// the nRF pinctrl driver is built. They are used only when runtime routing is +// available (IOBROKER_ROUTING); boards without it still define them. +extern const iobroker_instance_t iobroker_i2c_buses[]; +extern const size_t iobroker_i2c_bus_count; +extern iobroker_state_t iobroker_i2c_bus_states[]; + +extern const iobroker_instance_t iobroker_spi_buses[]; +extern const size_t iobroker_spi_bus_count; +extern iobroker_state_t iobroker_spi_bus_states[]; + +extern const iobroker_instance_t iobroker_uart_buses[]; +extern const size_t iobroker_uart_bus_count; +extern iobroker_state_t iobroker_uart_bus_states[]; + +// PWM instances. Each nRF PWM instance has four outputs (OUT0..OUT3) that +// are routed with the same pinctrl mechanism as bus signals. +extern const iobroker_instance_t iobroker_pwm_buses[]; +extern const size_t iobroker_pwm_bus_count; +extern iobroker_state_t iobroker_pwm_bus_states[]; + +// SoC pads owned by fixed peripherals (console UART, flash instance, I2S, +// ...): the pads their devicetree pinctrl default state drives at boot. +// iobroker_pin_in_use() reports these as always busy so that allocate() +// rejects requests for them with -EBUSY. +extern const uint16_t iobroker_reserved_pads[]; +extern const size_t iobroker_reserved_pads_count; + +#endif // CONFIG_PINCTRL_NRF + +// The functions below return 0 on success and set *dev_out to the Zephyr +// device of an allocated instance. A negative errno is returned on failure: +// -ENODEV: no compatible instance is free +// -ENOSYS: dynamic pin routing is unsupported on this SoC +// -EBUSY: a requested pin is already claimed by an allocated instance +// -EINVAL: a pin is not in the package map, has no GPIO, or no instance +// of this kind can be routed to the requested pins on this SoC +// (a pin-to-peripheral restriction, not a busy one) +// other negative values: a routing operation failed +// Optional signals may be disconnected (IOBROKER_NO_PIN). Every allocate +// call must be paired with iobroker_release(). +int iobroker_i2c_allocate(package_pin_t sda, package_pin_t scl, + const struct device **dev_out); +int iobroker_spi_allocate(package_pin_t clock, package_pin_t mosi, + package_pin_t miso, const struct device **dev_out); +int iobroker_uart_allocate(package_pin_t tx, package_pin_t rx, + package_pin_t rts, package_pin_t cts, const struct device **dev_out); + +// Allocate one PWM output channel for a pin. +// +// Channels that share a period form a group. What a group is depends on +// the SoC: +// nRF: a whole PWM instance (four channels) +// RP2: a slice (channels A and B) +// ESP32: an LEDC timer and the channels bound to it +// STM32: a timer (up to four channels sharing its auto-reload period) +// +// frequency (Hz) is used only to decide sharing; this call does not set the +// frequency. The caller converts it to a period itself (with +// pwm_get_cycles_per_sec()) and sets it with pwm_set_cycles(). Requests at +// the same frequency thus pass identical periods to pwm_set_cycles(), as +// drivers require of channels in one group. +// +// A request joins a running group requested at exactly the same frequency, +// unless the group or the request is exclusive. Otherwise a free group is +// taken. An exclusive request gets a group of its own that nobody joins, for +// a caller that changes the period or programs the group's hardware itself. +// +// On success returns 0 and sets *dev_out and *channel_out (the channel number +// pwm_set_cycles() takes). The caller then calls device_init(), which returns +// -EALREADY if the group was already running. Joining a running group only +// connects the new pin; the group's other outputs are not disturbed. +// +// Returns a negative errno on failure, with the out parameters untouched: +// -EINVAL: the pin is disconnected, not in the package map, has no GPIO, +// or no PWM group can reach it +// -EBUSY: the pin is already claimed +// -ENODEV: no group with a free channel is compatible with the request +// -ENOSYS: PWM channel allocation is unsupported on this SoC +// Every allocation must be paired with iobroker_pwm_channel_release(). +int iobroker_pwm_channel_allocate(package_pin_t pin, uint32_t frequency, + bool exclusive, const struct device **dev_out, uint32_t *channel_out); + +// Release a channel allocated with iobroker_pwm_channel_allocate(): its pin +// is disconnected from the group and left quiescent. Releasing the group's +// last channel releases the whole group, de-initializing its device. The +// caller stops the channel's output (pwm_set_cycles() with a zero pulse) +// first. Returns true when the channel was allocated. +bool iobroker_pwm_channel_release(const struct device *dev, uint32_t channel); + +// Allocate a package pin for the ADC. Analog inputs have no runtime routing: +// the pad's analog input is fixed by the SoC, so the call resolves and +// returns it in *input_out (the input selector the device's channel +// configuration takes, such as a SAADC AIN number; undefined when the device +// has no selectable inputs, as on the emulated ADC). The call also assigns a +// free channel slot on the ADC device, returned in *channel_out; the caller +// configures the channel itself (adc_channel_setup()) with channel_id = +// *channel_out and input_positive = *input_out where the device takes an +// input selector. The pad stays claimed while the allocation is held, so bus +// allocate() calls and GPIO allocations refuse it with -EBUSY. +// +// Returns 0, or a negative errno: +// -ENOSYS: no ADC support on this SoC +// -EINVAL: the pin is disconnected, unknown, or has no analog function +// -EBUSY: the pad is already claimed +// -ENOMEM: the analog claim registry is full +int iobroker_adc_allocate(package_pin_t pin, const struct device **dev_out, + uint8_t *channel_out, uint8_t *input_out); + +// Release an ADC pad allocated with iobroker_adc_allocate(), unconfigure its +// channel if the ADC device needs that (Zephyr's ADC API has no channel +// release, so implementations handle it per SoC) and return the pad to a +// quiescent state. Pass the device and channel the allocate call returned. +// Returns true when an allocation was held. +bool iobroker_adc_release(const struct device *dev, uint8_t channel); + +// Allocate a package pin for the DAC and hand out a free channel slot on the +// DAC device. DAC outputs are like ADC inputs fixed per pad: no runtime +// routing, the pad's analog switch is applied by the implementation. The +// caller configures the channel itself (dac_channel_setup()) with channel_id +// = *channel_out and input_positive = *input_out where the device takes an +// input selector. The pad stays claimed while the allocation is held, so bus +// allocate() calls and GPIO allocations refuse it with -EBUSY. +// +// Returns 0, or a negative errno: +// -ENOSYS: no DAC support on this SoC +// -EINVAL: the pin is disconnected, unknown, or has no analog function +// -EBUSY: the pad is already claimed +// -ENOMEM: the analog claim registry is full +int iobroker_dac_allocate(package_pin_t pin, const struct device **dev_out, + uint8_t *channel_out, uint8_t *input_out); + +// Release a DAC pad allocated with iobroker_dac_allocate(), unconfigure its +// channel if the DAC device needs that (Zephyr's DAC API has no channel +// release, so implementations handle it per SoC) and return the pad to a +// quiescent state. Pass the device and channel the allocate call returned. +// Returns true when an allocation was held. +bool iobroker_dac_release(const struct device *dev, uint8_t channel); + +// Returns true when the package pin is currently claimed by an allocated bus +// instance, a GPIO allocation, or a fixed peripheral (console UART, flash +// instance, ... whose pads are listed in iobroker_reserved_pads). Call this +// before allocate() to find out which requested pin is already in use. +// Disconnected signals (IOBROKER_NO_PIN) and package pins with no SoC pad are +// never in use. +bool iobroker_pin_in_use(package_pin_t pin); + +// Allocate a package pin for plain GPIO use. The module only claims it: while +// held, bus allocate() calls and further GPIO allocations fail with -EBUSY. +// The pin is resolved through the package pin map, and both values Zephyr's +// GPIO API needs are returned: *port_out receives the GPIO controller device +// and *pin_out the pin number within it, so that the caller can configure the +// pad itself (gpio_pin_configure()). Returns 0, or a negative errno: +// -EINVAL: pin is disconnected (IOBROKER_NO_PIN) or has no entry in the +// package pin map +// -EBUSY: the pin is already claimed +// -ENOMEM: the GPIO claim registry is full +int iobroker_gpio_allocate(package_pin_t pin, + const struct device **port_out, gpio_pin_t *pin_out); + +// Release a GPIO claim made with iobroker_gpio_allocate() and return the pad +// to a quiescent state: disconnected from any peripheral routing, input +// buffer and driver off, no pulls (a plain input on SoCs without +// GPIO_DISCONNECTED support). Pass the device and pin number that the +// allocate call returned. Returns true when a claim was held. +bool iobroker_gpio_release(const struct device *port, gpio_pin_t number); + +// Release an instance previously returned by one of the allocate functions. +// Returns true when the instance had been dynamically routed, in which case +// the caller is responsible for resetting the pins it had routed to it. The +// device is de-initialized on release, so it is left uninitialized; the +// caller initializes it again when it allocates the instance next. +bool iobroker_release(const struct device *dev); diff --git a/ports/zephyr-cp/internal-modules/iobroker/packages/mcxn947_vdf.toml b/ports/zephyr-cp/internal-modules/iobroker/packages/mcxn947_vdf.toml new file mode 100644 index 00000000000..58757be8353 --- /dev/null +++ b/ports/zephyr-cp/internal-modules/iobroker/packages/mcxn947_vdf.toml @@ -0,0 +1,954 @@ +# Package pin map for mcxn947_vdf, transcribed from MCXNP184M150F70.pdf, +# section 6.1 Table 93 (Pinmux), 184BGA column ("ALL": the same ball +# assignments apply across the family), with a one-off pdftotext -layout +# parse of the datasheet and the workbook's ball map. Review against the NXP package drawing (98ASA01888D) before +# editing by hand; regenerate instead when the datasheet changes. +# +# Ball packages: 'pin' numbers the 184 present balls sequentially in +# row-major order (the datasheet only labels them, e.g. A17), so power +# balls leave gaps; the pad->pin ids come from the package's Pinout +# workbook (MCXNP184M150F70_Pinout.xlsx, VFBGA184 tab). +# + +# The ``gpio`` column is the pad's global GPIO number (gpio port index * 32 +# + pin, the numbering the GPIO controller table resolves) when the pad +# bonds a GPIO controller; pads without it (the analog-only pads) are +# reachable only through the analog APIs. + +# The analog-only pads (Pad type - ANA, no GPIO controller) carry the +# datasheet's ANA_x pad names and integrate into the row-major ball +# numbering; zephyr2cp turns them into pin objects named by their +# pad_name: +# ANA_0 = ADC0_A0 (ball P3, pad 139) +# ANA_1 = ADC0_B0 (ball R3, pad 150) +# ANA_14 = OPAMP0_INN (ball U6, pad 178) +# ANA_18 = OPAMP1_INN (ball U8, pad 179) +# ANA_22 = OPAMP2_INN (ball U10, pad 180) +# ANA_4 = ADC1_A0 (ball T2, pad 162) +# ANA_5 = ADC1_B0 (ball T3, pad 163) +# ANA_6 = DAC2_OUT (ball U2, pad 176) +# ANA_7 = unused (ball U4, pad 177) + +name = "mcxn947_vdf" +socs = ["SOC_MCXN947"] + +[[pins]] +pin = 1 +ball = "A1" +pad_name = "P1.08" +gpio = 40 + + +[[pins]] +pin = 2 +ball = "A2" +pad_name = "P1.07" +gpio = 39 + + +[[pins]] +pin = 3 +ball = "A4" +pad_name = "P1.04" +gpio = 36 + + +[[pins]] +pin = 4 +ball = "A6" +pad_name = "P0.25" +gpio = 25 + + +[[pins]] +pin = 5 +ball = "A8" +pad_name = "P0.21" +gpio = 21 + + +[[pins]] +pin = 6 +ball = "A10" +pad_name = "P0.17" +gpio = 17 + + +[[pins]] +pin = 7 +ball = "A12" +pad_name = "P0.09" +gpio = 9 + + +[[pins]] +pin = 8 +ball = "A14" +pad_name = "P0.05" +gpio = 5 + + +[[pins]] +pin = 9 +ball = "A16" +pad_name = "P0.01" +gpio = 1 + + +[[pins]] +pin = 10 +ball = "A17" +pad_name = "P0.00" +gpio = 0 + + +[[pins]] +pin = 11 +ball = "B1" +pad_name = "P1.09" +gpio = 41 + + +[[pins]] +pin = 12 +ball = "B2" +pad_name = "P1.06" +gpio = 38 + + +[[pins]] +pin = 13 +ball = "B3" +pad_name = "P1.05" +gpio = 37 + + +[[pins]] +pin = 14 +ball = "B4" +pad_name = "P1.03" +gpio = 35 + + +[[pins]] +pin = 15 +ball = "B6" +pad_name = "P0.24" +gpio = 24 + + +[[pins]] +pin = 16 +ball = "B7" +pad_name = "P0.23" +gpio = 23 + + +[[pins]] +pin = 17 +ball = "B8" +pad_name = "P0.22" +gpio = 22 + + +[[pins]] +pin = 18 +ball = "B10" +pad_name = "P0.16" +gpio = 16 + + +[[pins]] +pin = 19 +ball = "B11" +pad_name = "P0.11" +gpio = 11 + + +[[pins]] +pin = 20 +ball = "B12" +pad_name = "P0.10" +gpio = 10 + + +[[pins]] +pin = 21 +ball = "B14" +pad_name = "P0.04" +gpio = 4 + + +[[pins]] +pin = 22 +ball = "B15" +pad_name = "P0.03" +gpio = 3 + + +[[pins]] +pin = 23 +ball = "B16" +pad_name = "P0.02" +gpio = 2 + + +[[pins]] +pin = 24 +ball = "B17" +pad_name = "P3.00" +gpio = 96 + + +[[pins]] +pin = 25 +ball = "C3" +pad_name = "P1.10" +gpio = 42 + + +[[pins]] +pin = 26 +ball = "C4" +pad_name = "P1.02" +gpio = 34 + + +[[pins]] +pin = 27 +ball = "C5" +pad_name = "P1.01" +gpio = 33 + + +[[pins]] +pin = 28 +ball = "C6" +pad_name = "P1.00" +gpio = 32 + + +[[pins]] +pin = 29 +ball = "C8" +pad_name = "P0.20" +gpio = 20 + + +[[pins]] +pin = 30 +ball = "C9" +pad_name = "P0.19" +gpio = 19 + + +[[pins]] +pin = 31 +ball = "C10" +pad_name = "P0.18" +gpio = 18 + + +[[pins]] +pin = 32 +ball = "C12" +pad_name = "P0.08" +gpio = 8 + + +[[pins]] +pin = 33 +ball = "C13" +pad_name = "P0.07" +gpio = 7 + + +[[pins]] +pin = 34 +ball = "C14" +pad_name = "P0.06" +gpio = 6 + + +[[pins]] +pin = 35 +ball = "C15" +pad_name = "P3.01" +gpio = 97 + + +[[pins]] +pin = 36 +ball = "D1" +pad_name = "P1.13" +gpio = 45 + + +[[pins]] +pin = 37 +ball = "D2" +pad_name = "P1.12" +gpio = 44 + + +[[pins]] +pin = 38 +ball = "D3" +pad_name = "P1.11" +gpio = 43 + + +[[pins]] +pin = 39 +ball = "D4" +pad_name = "P1.14" +gpio = 46 + + +[[pins]] +pin = 41 +ball = "D7" +pad_name = "P0.31" +gpio = 31 + + +[[pins]] +pin = 43 +ball = "D11" +pad_name = "P0.12" +gpio = 12 + + +[[pins]] +pin = 45 +ball = "D14" +pad_name = "P3.07" +gpio = 103 + + +[[pins]] +pin = 46 +ball = "D15" +pad_name = "P3.02" +gpio = 98 + + +[[pins]] +pin = 47 +ball = "D16" +pad_name = "P3.03" +gpio = 99 + + +[[pins]] +pin = 48 +ball = "D17" +pad_name = "P3.06" +gpio = 102 + + +[[pins]] +pin = 49 +ball = "E4" +pad_name = "P1.15" +gpio = 47 + + +[[pins]] +pin = 51 +ball = "E7" +pad_name = "P0.30" +gpio = 30 + + +[[pins]] +pin = 52 +ball = "E8" +pad_name = "P0.28" +gpio = 28 + + +[[pins]] +pin = 53 +ball = "E10" +pad_name = "P0.27" +gpio = 27 + + +[[pins]] +pin = 54 +ball = "E11" +pad_name = "P0.14" +gpio = 14 + + +[[pins]] +pin = 56 +ball = "E14" +pad_name = "P3.08" +gpio = 104 + + +[[pins]] +pin = 57 +ball = "F1" +pad_name = "P1.30" +gpio = 62 + + +[[pins]] +pin = 58 +ball = "F2" +pad_name = "P1.31" +gpio = 63 + + +[[pins]] +pin = 60 +ball = "F4" +pad_name = "P1.17" +gpio = 49 + + +[[pins]] +pin = 61 +ball = "F6" +pad_name = "P1.16" +gpio = 48 + + +[[pins]] +pin = 62 +ball = "F8" +pad_name = "P0.29" +gpio = 29 + + +[[pins]] +pin = 63 +ball = "F10" +pad_name = "P0.26" +gpio = 26 + + +[[pins]] +pin = 64 +ball = "F12" +pad_name = "P0.13" +gpio = 13 + + +[[pins]] +pin = 65 +ball = "F14" +pad_name = "P3.04" +gpio = 100 + + +[[pins]] +pin = 66 +ball = "F15" +pad_name = "P3.09" +gpio = 105 + + +[[pins]] +pin = 67 +ball = "F16" +pad_name = "P3.11" +gpio = 107 + + +[[pins]] +pin = 68 +ball = "F17" +pad_name = "P3.10" +gpio = 106 + + +[[pins]] +pin = 70 +ball = "G4" +pad_name = "P1.18" +gpio = 50 + + +[[pins]] +pin = 71 +ball = "G5" +pad_name = "P1.19" +gpio = 51 + + +[[pins]] +pin = 74 +ball = "G13" +pad_name = "P0.15" +gpio = 15 + + +[[pins]] +pin = 75 +ball = "G14" +pad_name = "P3.05" +gpio = 101 + + +[[pins]] +pin = 76 +ball = "G16" +pad_name = "P3.12" +gpio = 108 + + +[[pins]] +pin = 77 +ball = "H1" +pad_name = "P2.01" +gpio = 65 + + +[[pins]] +pin = 78 +ball = "H2" +pad_name = "P2.00" +gpio = 64 + + +[[pins]] +pin = 79 +ball = "H3" +pad_name = "P2.02" +gpio = 66 + + +[[pins]] +pin = 87 +ball = "H15" +pad_name = "P3.15" +gpio = 111 + + +[[pins]] +pin = 88 +ball = "H16" +pad_name = "P3.13" +gpio = 109 + + +[[pins]] +pin = 89 +ball = "H17" +pad_name = "P3.14" +gpio = 110 + + +[[pins]] +pin = 90 +ball = "J3" +pad_name = "P2.03" +gpio = 67 + + +[[pins]] +pin = 95 +ball = "J15" +pad_name = "P3.16" +gpio = 112 + + +[[pins]] +pin = 96 +ball = "K1" +pad_name = "P2.05" +gpio = 69 + + +[[pins]] +pin = 97 +ball = "K2" +pad_name = "P2.06" +gpio = 70 + + +[[pins]] +pin = 98 +ball = "K3" +pad_name = "P2.04" +gpio = 68 + + +[[pins]] +pin = 99 +ball = "K5" +pad_name = "P1.20" +gpio = 52 + + +[[pins]] +pin = 104 +ball = "K12" +pad_name = "P5.05" +gpio = 165 + + +[[pins]] +pin = 105 +ball = "K13" +pad_name = "P5.06" +gpio = 166 + + +[[pins]] +pin = 106 +ball = "K15" +pad_name = "P3.17" +gpio = 113 + + +[[pins]] +pin = 107 +ball = "K16" +pad_name = "P3.18" +gpio = 114 + + +[[pins]] +pin = 108 +ball = "K17" +pad_name = "P3.19" +gpio = 115 + + +[[pins]] +pin = 109 +ball = "L2" +pad_name = "P2.07" +gpio = 71 + + +[[pins]] +pin = 110 +ball = "L4" +pad_name = "P1.22" +gpio = 54 + + +[[pins]] +pin = 111 +ball = "L5" +pad_name = "P1.21" +gpio = 53 + + +[[pins]] +pin = 114 +ball = "L13" +pad_name = "P5.07" +gpio = 167 + + +[[pins]] +pin = 115 +ball = "L14" +pad_name = "P5.08" +gpio = 168 + + +[[pins]] +pin = 116 +ball = "L16" +pad_name = "P3.21" +gpio = 117 + + +[[pins]] +pin = 117 +ball = "M1" +pad_name = "P2.09" +gpio = 73 + + +[[pins]] +pin = 118 +ball = "M2" +pad_name = "P2.08" +gpio = 72 + + +[[pins]] +pin = 119 +ball = "M3" +pad_name = "P2.10" +gpio = 74 + + +[[pins]] +pin = 120 +ball = "M4" +pad_name = "P1.23" +gpio = 55 + + +[[pins]] +pin = 121 +ball = "M6" +pad_name = "P4.04" +gpio = 132 + + +[[pins]] +pin = 122 +ball = "M8" +pad_name = "P4.05" +gpio = 133 + + +[[pins]] +pin = 123 +ball = "M10" +pad_name = "P5.02" +gpio = 162 + + +[[pins]] +pin = 124 +ball = "M12" +pad_name = "P5.04" +gpio = 164 + + +[[pins]] +pin = 125 +ball = "M14" +pad_name = "P5.09" +gpio = 169 + + +[[pins]] +pin = 126 +ball = "M15" +pad_name = "P3.23" +gpio = 119 + + +[[pins]] +pin = 127 +ball = "M16" +pad_name = "P3.22" +gpio = 118 + + +[[pins]] +pin = 128 +ball = "M17" +pad_name = "P3.20" +gpio = 116 + + +[[pins]] +pin = 129 +ball = "N4" +pad_name = "P2.11" +gpio = 75 + + +[[pins]] +pin = 131 +ball = "N7" +pad_name = "P4.06" +gpio = 134 + + +[[pins]] +pin = 132 +ball = "N8" +pad_name = "P4.14" +gpio = 142 + + +[[pins]] +pin = 133 +ball = "N10" +pad_name = "P4.18" +gpio = 146 + + +[[pins]] +pin = 134 +ball = "N11" +pad_name = "P5.03" +gpio = 163 + + +[[pins]] +pin = 137 +ball = "P1" +pad_name = "P4.00" +gpio = 128 + + +[[pins]] +pin = 138 +ball = "P2" +pad_name = "P4.01" +gpio = 129 + + +[[pins]] +pin = 139 +ball = "P3" +pad_name = "ANA_0" + + +[[pins]] +pin = 150 +ball = "R3" +pad_name = "ANA_1" + + +[[pins]] +pin = 154 +ball = "R8" +pad_name = "P4.16" +gpio = 144 + + +[[pins]] +pin = 155 +ball = "R9" +pad_name = "P4.17" +gpio = 145 + + +[[pins]] +pin = 156 +ball = "R10" +pad_name = "P4.19" +gpio = 147 + + +[[pins]] +pin = 161 +ball = "T1" +pad_name = "P4.02" +gpio = 130 + + +[[pins]] +pin = 162 +ball = "T2" +pad_name = "ANA_4" + + +[[pins]] +pin = 163 +ball = "T3" +pad_name = "ANA_5" + + +[[pins]] +pin = 164 +ball = "T4" +pad_name = "P4.07" +gpio = 135 + + +[[pins]] +pin = 165 +ball = "T6" +pad_name = "P4.12" +gpio = 140 + + +[[pins]] +pin = 166 +ball = "T7" +pad_name = "P4.13" +gpio = 141 + + +[[pins]] +pin = 167 +ball = "T8" +pad_name = "P4.15" +gpio = 143 + + +[[pins]] +pin = 168 +ball = "T10" +pad_name = "P4.20" +gpio = 148 + + +[[pins]] +pin = 169 +ball = "T11" +pad_name = "P4.21" +gpio = 149 + + +[[pins]] +pin = 170 +ball = "T12" +pad_name = "P4.22" +gpio = 150 + + +[[pins]] +pin = 175 +ball = "U1" +pad_name = "P4.03" +gpio = 131 + + +[[pins]] +pin = 176 +ball = "U2" +pad_name = "ANA_6" + + +[[pins]] +pin = 177 +ball = "U4" +pad_name = "ANA_7" + + +[[pins]] +pin = 178 +ball = "U6" +pad_name = "ANA_14" + + +[[pins]] +pin = 179 +ball = "U8" +pad_name = "ANA_18" + + +[[pins]] +pin = 180 +ball = "U10" +pad_name = "ANA_22" + + +[[pins]] +pin = 181 +ball = "U12" +pad_name = "P4.23" +gpio = 151 + + +[[pins]] +pin = 183 +ball = "U16" +pad_name = "P5.00" +gpio = 160 + + +[[pins]] +pin = 184 +ball = "U17" +pad_name = "P5.01" +gpio = 161 diff --git a/ports/zephyr-cp/internal-modules/iobroker/packages/mcxn947_vnl.toml b/ports/zephyr-cp/internal-modules/iobroker/packages/mcxn947_vnl.toml new file mode 100644 index 00000000000..e987d11372d --- /dev/null +++ b/ports/zephyr-cp/internal-modules/iobroker/packages/mcxn947_vnl.toml @@ -0,0 +1,529 @@ +# Package pin map for mcxn947_vnl, transcribed from MCXNP184M150F70.pdf, +# section 6.1 Table 93 (Pinmux), 100HLQFP N94 column, with a one-off +# pdftotext -layout parse. Review against the datasheet figure before +# editing by hand; regenerate instead when the datasheet changes. +# +# QFN-style package: 'pin' holds the datasheet's pin number (1..100); the +# pads the package does not bond are omitted, so the numbering has gaps. + +# The ``gpio`` column is the pad's global GPIO number (gpio port index * 32 +# + pin, the numbering the GPIO controller table resolves) when the pad +# bonds a GPIO controller; pads without it (the analog-only pads) are +# reachable only through the analog APIs. + +# The analog-only pads (ANA) carry datasheet pad names: +# ANA_0 = ADC0_A0 (pin 22, pad 139) +# ANA_1 = ADC0_B0 (pin 23, pad 150) +# ANA_14 = OPAMP0_INN (pin 36, pad 178) +# ANA_18 = OPAMP1_INN (pin 39, pad 179) +# ANA_4 = ADC1_A0 (pin 26, pad 162) +# ANA_5 = ADC1_B0 (pin 27, pad 163) +# ANA_6 = DAC2_OUT (pin 28, pad 176) +# ANA_7 = unused (pin 29, pad 177) + +[[pins]] +pin = 76 +pad_name = "P0.00" +gpio = 0 + + +[[pins]] +pin = 77 +pad_name = "P0.01" +gpio = 1 + + +[[pins]] +pin = 78 +pad_name = "P0.02" +gpio = 2 + + +[[pins]] +pin = 79 +pad_name = "P0.03" +gpio = 3 + + +[[pins]] +pin = 80 +pad_name = "P0.04" +gpio = 4 + + +[[pins]] +pin = 81 +pad_name = "P0.05" +gpio = 5 + + +[[pins]] +pin = 82 +pad_name = "P0.06" +gpio = 6 + + +[[pins]] +pin = 84 +pad_name = "P0.16" +gpio = 16 + + +[[pins]] +pin = 85 +pad_name = "P0.17" +gpio = 17 + + +[[pins]] +pin = 86 +pad_name = "P0.18" +gpio = 18 + + +[[pins]] +pin = 87 +pad_name = "P0.19" +gpio = 19 + + +[[pins]] +pin = 88 +pad_name = "P0.20" +gpio = 20 + + +[[pins]] +pin = 89 +pad_name = "P0.21" +gpio = 21 + + +[[pins]] +pin = 90 +pad_name = "P0.22" +gpio = 22 + + +[[pins]] +pin = 91 +pad_name = "P0.23" +gpio = 23 + + +[[pins]] +pin = 92 +pad_name = "P1.00" +gpio = 32 + + +[[pins]] +pin = 93 +pad_name = "P1.01" +gpio = 33 + + +[[pins]] +pin = 94 +pad_name = "P1.02" +gpio = 34 + + +[[pins]] +pin = 95 +pad_name = "P1.03" +gpio = 35 + + +[[pins]] +pin = 97 +pad_name = "P1.04" +gpio = 36 + + +[[pins]] +pin = 98 +pad_name = "P1.05" +gpio = 37 + + +[[pins]] +pin = 99 +pad_name = "P1.06" +gpio = 38 + + +[[pins]] +pin = 100 +pad_name = "P1.07" +gpio = 39 + + +[[pins]] +pin = 1 +pad_name = "P1.08" +gpio = 40 + + +[[pins]] +pin = 2 +pad_name = "P1.09" +gpio = 41 + + +[[pins]] +pin = 3 +pad_name = "P1.10" +gpio = 42 + + +[[pins]] +pin = 4 +pad_name = "P1.11" +gpio = 43 + + +[[pins]] +pin = 5 +pad_name = "P1.12" +gpio = 44 + + +[[pins]] +pin = 6 +pad_name = "P1.13" +gpio = 45 + + +[[pins]] +pin = 7 +pad_name = "P1.14" +gpio = 46 + + +[[pins]] +pin = 8 +pad_name = "P1.15" +gpio = 47 + + +[[pins]] +pin = 10 +pad_name = "P1.30" +gpio = 62 + + +[[pins]] +pin = 11 +pad_name = "P1.31" +gpio = 63 + + +[[pins]] +pin = 14 +pad_name = "P2.00" +gpio = 64 + + +[[pins]] +pin = 15 +pad_name = "P2.01" +gpio = 65 + + +[[pins]] +pin = 16 +pad_name = "P2.02" +gpio = 66 + + +[[pins]] +pin = 17 +pad_name = "P2.03" +gpio = 67 + + +[[pins]] +pin = 18 +pad_name = "P2.04" +gpio = 68 + + +[[pins]] +pin = 19 +pad_name = "P2.05" +gpio = 69 + + +[[pins]] +pin = 20 +pad_name = "P2.06" +gpio = 70 + + +[[pins]] +pin = 21 +pad_name = "P2.07" +gpio = 71 + + +[[pins]] +pin = 75 +pad_name = "P3.00" +gpio = 96 + + +[[pins]] +pin = 74 +pad_name = "P3.01" +gpio = 97 + + +[[pins]] +pin = 72 +pad_name = "P3.06" +gpio = 102 + + +[[pins]] +pin = 71 +pad_name = "P3.07" +gpio = 103 + + +[[pins]] +pin = 70 +pad_name = "P3.08" +gpio = 104 + + +[[pins]] +pin = 69 +pad_name = "P3.09" +gpio = 105 + + +[[pins]] +pin = 68 +pad_name = "P3.10" +gpio = 106 + + +[[pins]] +pin = 67 +pad_name = "P3.11" +gpio = 107 + + +[[pins]] +pin = 65 +pad_name = "P3.12" +gpio = 108 + + +[[pins]] +pin = 64 +pad_name = "P3.13" +gpio = 109 + + +[[pins]] +pin = 63 +pad_name = "P3.14" +gpio = 110 + + +[[pins]] +pin = 62 +pad_name = "P3.15" +gpio = 111 + + +[[pins]] +pin = 61 +pad_name = "P3.16" +gpio = 112 + + +[[pins]] +pin = 60 +pad_name = "P3.17" +gpio = 113 + + +[[pins]] +pin = 57 +pad_name = "P3.20" +gpio = 116 + + +[[pins]] +pin = 56 +pad_name = "P3.21" +gpio = 117 + + +[[pins]] +pin = 22 +pad_name = "P4.00" +gpio = 128 + + +[[pins]] +pin = 23 +pad_name = "P4.01" +gpio = 129 + + +[[pins]] +pin = 24 +pad_name = "P4.02" +gpio = 130 + + +[[pins]] +pin = 25 +pad_name = "P4.03" +gpio = 131 + + +[[pins]] +pin = 26 +pad_name = "P4.04" +gpio = 132 + + +[[pins]] +pin = 27 +pad_name = "P4.05" +gpio = 133 + + +[[pins]] +pin = 28 +pad_name = "P4.06" +gpio = 134 + + +[[pins]] +pin = 29 +pad_name = "P4.07" +gpio = 135 + + +[[pins]] +pin = 35 +pad_name = "P4.12" +gpio = 140 + + +[[pins]] +pin = 36 +pad_name = "P4.13" +gpio = 141 + + +[[pins]] +pin = 37 +pad_name = "P4.15" +gpio = 143 + + +[[pins]] +pin = 38 +pad_name = "P4.16" +gpio = 144 + + +[[pins]] +pin = 39 +pad_name = "P4.17" +gpio = 145 + + +[[pins]] +pin = 40 +pad_name = "P4.19" +gpio = 147 + + +[[pins]] +pin = 41 +pad_name = "P4.20" +gpio = 148 + + +[[pins]] +pin = 42 +pad_name = "P4.21" +gpio = 149 + + +[[pins]] +pin = 43 +pad_name = "P4.23" +gpio = 151 + + +[[pins]] +pin = 48 +pad_name = "P5.00" +gpio = 160 + + +[[pins]] +pin = 49 +pad_name = "P5.01" +gpio = 161 + + +[[pins]] +pin = 50 +pad_name = "P5.02" +gpio = 162 + + +[[pins]] +pin = 51 +pad_name = "P5.03" +gpio = 163 + + +[[pins]] +pin = 22 +pad_name = "ANA_0" + + +[[pins]] +pin = 23 +pad_name = "ANA_1" + + +[[pins]] +pin = 36 +pad_name = "ANA_14" + + +[[pins]] +pin = 39 +pad_name = "ANA_18" + + +[[pins]] +pin = 26 +pad_name = "ANA_4" + + +[[pins]] +pin = 27 +pad_name = "ANA_5" + + +[[pins]] +pin = 28 +pad_name = "ANA_6" + + +[[pins]] +pin = 29 +pad_name = "ANA_7" diff --git a/ports/zephyr-cp/internal-modules/iobroker/packages/mdbt50q_1mv2.toml b/ports/zephyr-cp/internal-modules/iobroker/packages/mdbt50q_1mv2.toml new file mode 100644 index 00000000000..82c7981337e --- /dev/null +++ b/ports/zephyr-cp/internal-modules/iobroker/packages/mdbt50q_1mv2.toml @@ -0,0 +1,410 @@ +# Package pin map for the Raytac MDBT50Q-1MV2 module (nRF52840 aQFN73 +# inside), transcribed from "[nRF52840] MDBT50Q-1MV2 & MDBT50Q-P1MV2_Ver.L +# spec.pdf", section 2.5 Pin Assignment, with a one-off pdftotext -layout +# parse. Review against the datasheet figure before editing by hand. +# +# 'pin' numbers the module's castellated pins as the datasheet numbers them +# (1..61); non-GPIO pins carry no pad. + +name = "mdbt50q_1mv2" +socs = ["SOC_NRF52840_QIAA"] + +[[pins]] +pin = 1 +name = "GND" # non-GPIO + + +[[pins]] +pin = 2 +name = "GND" # non-GPIO + + +[[pins]] +pin = 3 +pad = 7 +pad_name = "P1.10" +gpio = 42 + + +[[pins]] +pin = 4 +pad = 19 +pad_name = "P1.11" +gpio = 43 + + +[[pins]] +pin = 5 +pad = 18 +pad_name = "P1.12" +gpio = 44 + + +[[pins]] +pin = 6 +pad = 5 +pad_name = "P1.13" +gpio = 45 + + +[[pins]] +pin = 7 +pad = 17 +pad_name = "P1.14" +gpio = 46 + + +[[pins]] +pin = 8 +pad = 4 +pad_name = "P1.15" +gpio = 47 + + +[[pins]] +pin = 9 +pad = 16 +pad_name = "P0.03" +gpio = 3 + + +[[pins]] +pin = 10 +pad = 2 +pad_name = "P0.29" +gpio = 29 + + +[[pins]] +pin = 11 +pad = 3 +pad_name = "P0.02" +gpio = 2 + + +[[pins]] +pin = 12 +pad = 1 +pad_name = "P0.31" +gpio = 31 + + +[[pins]] +pin = 13 +pad = 15 +pad_name = "P0.28" +gpio = 28 + + +[[pins]] +pin = 14 +pad = 14 +pad_name = "P0.30" +gpio = 30 + + +[[pins]] +pin = 15 +name = "GND" # non-GPIO + + +[[pins]] +pin = 16 +pad = 28 +pad_name = "P0.27" +gpio = 27 + + +[[pins]] +pin = 17 +pad = 22 +pad_name = "P0.00" +gpio = 0 + + +[[pins]] +pin = 18 +pad = 25 +pad_name = "P0.01" +gpio = 1 + + +[[pins]] +pin = 19 +pad = 27 +pad_name = "P0.26" +gpio = 26 + + +[[pins]] +pin = 20 +pad = 30 +pad_name = "P0.04" +gpio = 4 + + +[[pins]] +pin = 21 +pad = 32 +pad_name = "P0.05" +gpio = 5 + + +[[pins]] +pin = 22 +pad = 33 +pad_name = "P0.06" +gpio = 6 + + +[[pins]] +pin = 23 +pad = 35 +pad_name = "P0.07" +gpio = 7 + + +[[pins]] +pin = 24 +pad = 36 +pad_name = "P0.08" +gpio = 8 + + +[[pins]] +pin = 25 +pad = 38 +pad_name = "P1.08" +gpio = 40 + + +[[pins]] +pin = 26 +pad = 40 +pad_name = "P1.09" +gpio = 41 + + +[[pins]] +pin = 27 +pad = 42 +pad_name = "P0.11" +gpio = 11 + + +[[pins]] +pin = 28 +name = "VDD" # non-GPIO + + +[[pins]] +pin = 29 +pad = 44 +pad_name = "P0.12" +gpio = 12 + + +[[pins]] +pin = 30 +name = "VDD" # non-GPIO + + +[[pins]] +pin = 31 +name = "DCCH" # non-GPIO + + +[[pins]] +pin = 32 +name = "VBUS" # non-GPIO + + +[[pins]] +pin = 33 +name = "GND" # non-GPIO + + +[[pins]] +pin = 34 +name = "D-" # non-GPIO + + +[[pins]] +pin = 35 +name = "D+" # non-GPIO + + +[[pins]] +pin = 36 +pad = 54 +pad_name = "P0.14" +gpio = 14 + + +[[pins]] +pin = 37 +pad = 65 +pad_name = "P0.13" +gpio = 13 + + +[[pins]] +pin = 38 +pad = 55 +pad_name = "P0.16" +gpio = 16 + + +[[pins]] +pin = 39 +pad = 66 +pad_name = "P0.15" +gpio = 15 + + +[[pins]] +pin = 40 +pad = 56 +pad_name = "P0.18" +gpio = 18 + + +[[pins]] +pin = 41 +pad = 67 +pad_name = "P0.17" +gpio = 17 + + +[[pins]] +pin = 42 +pad = 57 +pad_name = "P0.19" +gpio = 19 + + +[[pins]] +pin = 43 +pad = 58 +pad_name = "P0.21" +gpio = 21 + + +[[pins]] +pin = 44 +pad = 69 +pad_name = "P0.20" +gpio = 20 + + +[[pins]] +pin = 45 +pad = 59 +pad_name = "P0.23" +gpio = 23 + + +[[pins]] +pin = 46 +pad = 70 +pad_name = "P0.22" +gpio = 22 + + +[[pins]] +pin = 47 +pad = 72 +pad_name = "P1.00" +gpio = 32 + + +[[pins]] +pin = 48 +pad = 71 +pad_name = "P0.24" +gpio = 24 + + +[[pins]] +pin = 49 +pad = 60 +pad_name = "P0.25" +gpio = 25 + + +[[pins]] +pin = 50 +pad = 48 +pad_name = "P1.02" +gpio = 34 + + +[[pins]] +pin = 51 +name = "SWDIO" # non-GPIO + + +[[pins]] +pin = 52 +pad = 34 +pad_name = "P0.09" +gpio = 9 + + +[[pins]] +pin = 53 +name = "SWDCLK" # non-GPIO + + +[[pins]] +pin = 54 +pad = 31 +pad_name = "P0.10" +gpio = 10 + + +[[pins]] +pin = 55 +name = "GND" # non-GPIO + + +[[pins]] +pin = 56 +pad = 45 +pad_name = "P1.04" +gpio = 36 + + +[[pins]] +pin = 57 +pad = 41 +pad_name = "P1.06" +gpio = 38 + + +[[pins]] +pin = 58 +pad = 39 +pad_name = "P1.07" +gpio = 39 + + +[[pins]] +pin = 59 +pad = 43 +pad_name = "P1.05" +gpio = 37 + + +[[pins]] +pin = 60 +pad = 46 +pad_name = "P1.03" +gpio = 35 + + +[[pins]] +pin = 61 +pad = 50 +pad_name = "P1.01" +gpio = 33 diff --git a/ports/zephyr-cp/internal-modules/iobroker/packages/nrf52840_aqfn73.toml b/ports/zephyr-cp/internal-modules/iobroker/packages/nrf52840_aqfn73.toml new file mode 100644 index 00000000000..936f759115e --- /dev/null +++ b/ports/zephyr-cp/internal-modules/iobroker/packages/nrf52840_aqfn73.toml @@ -0,0 +1,345 @@ +# Package pin map for nrf52840_aqfn73, transcribed from nRF52840_PS_v1.1.pdf, +# section 7.1.1 (aQFN73 ball assignments), +# by tools/gen_package.py. Review against the datasheet figure before +# editing by hand; regenerate instead when the datasheet changes. + +# Ball packages: 'pin' numbers the balls sequentially in row-major +# order (the datasheet only labels them, e.g. B2). + +name = "nrf52840_aqfn73" +socs = ["SOC_NRF52840_QIAA"] + +[[pins]] +pin = 1 +ball = "A8" +pad_name = "P0.31" +gpio = 31 + + +[[pins]] +pin = 2 +ball = "A10" +pad_name = "P0.29" +gpio = 29 + + +[[pins]] +pin = 3 +ball = "A12" +pad_name = "P0.02" +gpio = 2 + + +[[pins]] +pin = 4 +ball = "A14" +pad_name = "P1.15" +gpio = 47 + + +[[pins]] +pin = 5 +ball = "A16" +pad_name = "P1.13" +gpio = 45 + + +[[pins]] +pin = 7 +ball = "A20" +pad_name = "P1.10" +gpio = 42 + + +[[pins]] +pin = 14 +ball = "B9" +pad_name = "P0.30" +gpio = 30 + + +[[pins]] +pin = 15 +ball = "B11" +pad_name = "P0.28" +gpio = 28 + + +[[pins]] +pin = 16 +ball = "B13" +pad_name = "P0.03" +gpio = 3 + + +[[pins]] +pin = 17 +ball = "B15" +pad_name = "P1.14" +gpio = 46 + + +[[pins]] +pin = 18 +ball = "B17" +pad_name = "P1.12" +gpio = 44 + + +[[pins]] +pin = 19 +ball = "B19" +pad_name = "P1.11" +gpio = 43 + + +[[pins]] +pin = 22 +ball = "D2" +pad_name = "P0.00" +gpio = 0 + + +[[pins]] +pin = 25 +ball = "F2" +pad_name = "P0.01" +gpio = 1 + + +[[pins]] +pin = 27 +ball = "G1" +pad_name = "P0.26" +gpio = 26 + + +[[pins]] +pin = 28 +ball = "H2" +pad_name = "P0.27" +gpio = 27 + + +[[pins]] +pin = 30 +ball = "J1" +pad_name = "P0.04" +gpio = 4 + + +[[pins]] +pin = 31 +ball = "J24" +pad_name = "P0.10" +gpio = 10 + + +[[pins]] +pin = 32 +ball = "K2" +pad_name = "P0.05" +gpio = 5 + + +[[pins]] +pin = 33 +ball = "L1" +pad_name = "P0.06" +gpio = 6 + + +[[pins]] +pin = 34 +ball = "L24" +pad_name = "P0.09" +gpio = 9 + + +[[pins]] +pin = 35 +ball = "M2" +pad_name = "P0.07" +gpio = 7 + + +[[pins]] +pin = 36 +ball = "N1" +pad_name = "P0.08" +gpio = 8 + + +[[pins]] +pin = 38 +ball = "P2" +pad_name = "P1.08" +gpio = 40 + + +[[pins]] +pin = 39 +ball = "P23" +pad_name = "P1.07" +gpio = 39 + + +[[pins]] +pin = 40 +ball = "R1" +pad_name = "P1.09" +gpio = 41 + + +[[pins]] +pin = 41 +ball = "R24" +pad_name = "P1.06" +gpio = 38 + + +[[pins]] +pin = 42 +ball = "T2" +pad_name = "P0.11" +gpio = 11 + + +[[pins]] +pin = 43 +ball = "T23" +pad_name = "P1.05" +gpio = 37 + + +[[pins]] +pin = 44 +ball = "U1" +pad_name = "P0.12" +gpio = 12 + + +[[pins]] +pin = 45 +ball = "U24" +pad_name = "P1.04" +gpio = 36 + + +[[pins]] +pin = 46 +ball = "V23" +pad_name = "P1.03" +gpio = 35 + + +[[pins]] +pin = 48 +ball = "W24" +pad_name = "P1.02" +gpio = 34 + + +[[pins]] +pin = 50 +ball = "Y23" +pad_name = "P1.01" +gpio = 33 + + +[[pins]] +pin = 54 +ball = "AC9" +pad_name = "P0.14" +gpio = 14 + + +[[pins]] +pin = 55 +ball = "AC11" +pad_name = "P0.16" +gpio = 16 + + +[[pins]] +pin = 56 +ball = "AC13" +pad_name = "P0.18" +gpio = 18 + + +[[pins]] +pin = 57 +ball = "AC15" +pad_name = "P0.19" +gpio = 19 + + +[[pins]] +pin = 58 +ball = "AC17" +pad_name = "P0.21" +gpio = 21 + + +[[pins]] +pin = 59 +ball = "AC19" +pad_name = "P0.23" +gpio = 23 + + +[[pins]] +pin = 60 +ball = "AC21" +pad_name = "P0.25" +gpio = 25 + + +[[pins]] +pin = 65 +ball = "AD8" +pad_name = "P0.13" +gpio = 13 + + +[[pins]] +pin = 66 +ball = "AD10" +pad_name = "P0.15" +gpio = 15 + + +[[pins]] +pin = 67 +ball = "AD12" +pad_name = "P0.17" +gpio = 17 + + +[[pins]] +pin = 69 +ball = "AD16" +pad_name = "P0.20" +gpio = 20 + + +[[pins]] +pin = 70 +ball = "AD18" +pad_name = "P0.22" +gpio = 22 + + +[[pins]] +pin = 71 +ball = "AD20" +pad_name = "P0.24" +gpio = 24 + + +[[pins]] +pin = 72 +ball = "AD22" +pad_name = "P1.00" +gpio = 32 diff --git a/ports/zephyr-cp/internal-modules/iobroker/packages/nrf5340_qkaa.toml b/ports/zephyr-cp/internal-modules/iobroker/packages/nrf5340_qkaa.toml new file mode 100644 index 00000000000..8cbd9ab1f06 --- /dev/null +++ b/ports/zephyr-cp/internal-modules/iobroker/packages/nrf5340_qkaa.toml @@ -0,0 +1,345 @@ +# Package pin map for nrf5340_qkaa, transcribed from nRF5340_PS_v1.6.pdf, +# section 9.1.1 (aQFN94 pin assignments), +# by tools/gen_package.py. Review against the datasheet figure before +# editing by hand; regenerate instead when the datasheet changes. + +# Ball packages: 'pin' numbers the balls sequentially in row-major +# order (the datasheet only labels them, e.g. B2). + +name = "nrf5340_qkaa" +socs = ["SOC_NRF5340_CPUAPP"] + +[[pins]] +pin = 4 +ball = "A17" +pad_name = "P1.13" +gpio = 45 + + +[[pins]] +pin = 16 +ball = "B14" +pad_name = "P1.15" +gpio = 47 + + +[[pins]] +pin = 17 +ball = "B16" +pad_name = "P1.14" +gpio = 46 + + +[[pins]] +pin = 18 +ball = "B18" +pad_name = "P1.12" +gpio = 44 + + +[[pins]] +pin = 19 +ball = "B20" +pad_name = "P1.11" +gpio = 43 + + +[[pins]] +pin = 20 +ball = "B22" +pad_name = "P0.31" +gpio = 31 + + +[[pins]] +pin = 21 +ball = "B24" +pad_name = "P0.30" +gpio = 30 + + +[[pins]] +pin = 39 +ball = "M2" +pad_name = "P1.00" +gpio = 32 + + +[[pins]] +pin = 40 +ball = "N1" +pad_name = "P0.00" +gpio = 0 + + +[[pins]] +pin = 42 +ball = "P2" +pad_name = "P1.01" +gpio = 33 + + +[[pins]] +pin = 43 +ball = "R1" +pad_name = "P0.01" +gpio = 1 + + +[[pins]] +pin = 44 +ball = "R31" +pad_name = "P1.10" +gpio = 42 + + +[[pins]] +pin = 47 +ball = "U31" +pad_name = "P0.29" +gpio = 29 + + +[[pins]] +pin = 48 +ball = "V2" +pad_name = "P0.04" +gpio = 4 + + +[[pins]] +pin = 49 +ball = "W1" +pad_name = "P0.02" +gpio = 2 + + +[[pins]] +pin = 51 +ball = "Y2" +pad_name = "P0.05" +gpio = 5 + + +[[pins]] +pin = 52 +ball = "AA1" +pad_name = "P0.03" +gpio = 3 + + +[[pins]] +pin = 54 +ball = "AB2" +pad_name = "P0.06" +gpio = 6 + + +[[pins]] +pin = 57 +ball = "AD2" +pad_name = "P0.07" +gpio = 7 + + +[[pins]] +pin = 58 +ball = "AE1" +pad_name = "P1.02" +gpio = 34 + + +[[pins]] +pin = 59 +ball = "AE31" +pad_name = "P0.28" +gpio = 28 + + +[[pins]] +pin = 60 +ball = "AF2" +pad_name = "P1.03" +gpio = 35 + + +[[pins]] +pin = 63 +ball = "AH2" +pad_name = "P0.08" +gpio = 8 + + +[[pins]] +pin = 64 +ball = "AJ1" +pad_name = "P0.09" +gpio = 9 + + +[[pins]] +pin = 66 +ball = "AK2" +pad_name = "P0.10" +gpio = 10 + + +[[pins]] +pin = 67 +ball = "AK4" +pad_name = "P0.11" +gpio = 11 + + +[[pins]] +pin = 68 +ball = "AK6" +pad_name = "P0.12" +gpio = 12 + + +[[pins]] +pin = 69 +ball = "AK8" +pad_name = "P0.14" +gpio = 14 + + +[[pins]] +pin = 70 +ball = "AK10" +pad_name = "P0.15" +gpio = 15 + + +[[pins]] +pin = 71 +ball = "AK12" +pad_name = "P0.17" +gpio = 17 + + +[[pins]] +pin = 72 +ball = "AK14" +pad_name = "P0.18" +gpio = 18 + + +[[pins]] +pin = 73 +ball = "AK16" +pad_name = "P0.20" +gpio = 20 + + +[[pins]] +pin = 74 +ball = "AK18" +pad_name = "P0.22" +gpio = 22 + + +[[pins]] +pin = 75 +ball = "AK20" +pad_name = "P0.23" +gpio = 23 + + +[[pins]] +pin = 76 +ball = "AK22" +pad_name = "P1.05" +gpio = 37 + + +[[pins]] +pin = 77 +ball = "AK24" +pad_name = "P1.07" +gpio = 39 + + +[[pins]] +pin = 78 +ball = "AK26" +pad_name = "P1.09" +gpio = 41 + + +[[pins]] +pin = 79 +ball = "AK28" +pad_name = "P0.25" +gpio = 25 + + +[[pins]] +pin = 80 +ball = "AK30" +pad_name = "P0.27" +gpio = 27 + + +[[pins]] +pin = 82 +ball = "AL5" +pad_name = "P0.13" +gpio = 13 + + +[[pins]] +pin = 84 +ball = "AL9" +pad_name = "P0.16" +gpio = 16 + + +[[pins]] +pin = 86 +ball = "AL13" +pad_name = "P0.19" +gpio = 19 + + +[[pins]] +pin = 87 +ball = "AL15" +pad_name = "P0.21" +gpio = 21 + + +[[pins]] +pin = 89 +ball = "AL19" +pad_name = "P1.04" +gpio = 36 + + +[[pins]] +pin = 90 +ball = "AL21" +pad_name = "P1.06" +gpio = 38 + + +[[pins]] +pin = 91 +ball = "AL23" +pad_name = "P1.08" +gpio = 40 + + +[[pins]] +pin = 93 +ball = "AL27" +pad_name = "P0.24" +gpio = 24 + + +[[pins]] +pin = 94 +ball = "AL29" +pad_name = "P0.26" +gpio = 26 diff --git a/ports/zephyr-cp/internal-modules/iobroker/packages/nrf54l15_qfn48.toml b/ports/zephyr-cp/internal-modules/iobroker/packages/nrf54l15_qfn48.toml new file mode 100644 index 00000000000..73a0ae539c8 --- /dev/null +++ b/ports/zephyr-cp/internal-modules/iobroker/packages/nrf54l15_qfn48.toml @@ -0,0 +1,192 @@ +# Package pin map for nrf54l15_qfn48, transcribed from nRF54L15_nRF54L10_nRF54L05_Datasheet_v1.0.pdf, +# section 10.1.4 (QFN48, QFAA package pin assignments), +# by tools/gen_package.py. Review against the datasheet figure before +# editing by hand; regenerate instead when the datasheet changes. + +name = "nrf54l15_qfn48" +socs = ["SOC_NRF54L15", "SOC_NRF54L10", "SOC_NRF54L05"] + +[[pins]] +pin = 1 +pad_name = "P1.00" +gpio = 32 + + +[[pins]] +pin = 2 +pad_name = "P1.01" +gpio = 33 + + +[[pins]] +pin = 3 +pad_name = "P1.02" +gpio = 34 + + +[[pins]] +pin = 4 +pad_name = "P1.03" +gpio = 35 + + +[[pins]] +pin = 5 +pad_name = "P1.04" +gpio = 36 + + +[[pins]] +pin = 6 +pad_name = "P1.05" +gpio = 37 + + +[[pins]] +pin = 7 +pad_name = "P1.06" +gpio = 38 + + +[[pins]] +pin = 8 +pad_name = "P1.07" +gpio = 39 + + +[[pins]] +pin = 9 +pad_name = "P1.08" +gpio = 40 + + +[[pins]] +pin = 11 +pad_name = "P2.00" +gpio = 64 + + +[[pins]] +pin = 12 +pad_name = "P2.01" +gpio = 65 + + +[[pins]] +pin = 13 +pad_name = "P2.02" +gpio = 66 + + +[[pins]] +pin = 14 +pad_name = "P2.03" +gpio = 67 + + +[[pins]] +pin = 15 +pad_name = "P2.04" +gpio = 68 + + +[[pins]] +pin = 16 +pad_name = "P2.05" +gpio = 69 + + +[[pins]] +pin = 17 +pad_name = "P2.06" +gpio = 70 + + +[[pins]] +pin = 18 +pad_name = "P2.07" +gpio = 71 + + +[[pins]] +pin = 19 +pad_name = "P2.08" +gpio = 72 + + +[[pins]] +pin = 20 +pad_name = "P2.09" +gpio = 73 + + +[[pins]] +pin = 21 +pad_name = "P2.10" +gpio = 74 + + +[[pins]] +pin = 23 +pad_name = "P0.00" +gpio = 0 + + +[[pins]] +pin = 24 +pad_name = "P0.01" +gpio = 1 + + +[[pins]] +pin = 27 +pad_name = "P0.02" +gpio = 2 + + +[[pins]] +pin = 28 +pad_name = "P0.03" +gpio = 3 + + +[[pins]] +pin = 29 +pad_name = "P0.04" +gpio = 4 + + +[[pins]] +pin = 37 +pad_name = "P1.09" +gpio = 41 + + +[[pins]] +pin = 38 +pad_name = "P1.10" +gpio = 42 + + +[[pins]] +pin = 39 +pad_name = "P1.11" +gpio = 43 + + +[[pins]] +pin = 40 +pad_name = "P1.12" +gpio = 44 + + +[[pins]] +pin = 41 +pad_name = "P1.13" +gpio = 45 + + +[[pins]] +pin = 42 +pad_name = "P1.14" +gpio = 46 diff --git a/ports/zephyr-cp/internal-modules/iobroker/packages/nrf54lm20_csp98.toml b/ports/zephyr-cp/internal-modules/iobroker/packages/nrf54lm20_csp98.toml new file mode 100644 index 00000000000..31b0bd32314 --- /dev/null +++ b/ports/zephyr-cp/internal-modules/iobroker/packages/nrf54lm20_csp98.toml @@ -0,0 +1,471 @@ +# Package pin map for nrf54lm20_csp98, transcribed from nRF54LM20A_nRF54LM20B_Datasheet_v1.0.pdf, +# section 10.1.4 (CSP98, PAAA package pin assignments), +# by tools/gen_package.py. Review against the datasheet figure before +# editing by hand; regenerate instead when the datasheet changes. + +# Ball packages: 'pin' numbers the balls sequentially in row-major +# order (the datasheet only labels them, e.g. B2). + +name = "nrf54lm20_csp98" +socs = ["SOC_NRF54LM20A", "SOC_NRF54LM20B"] + +[[pins]] +pin = 12 +ball = "B2" +pad_name = "P1.15" +gpio = 47 + + +[[pins]] +pin = 13 +ball = "B3" +pad_name = "P1.16" +gpio = 48 + + +[[pins]] +pin = 14 +ball = "B4" +pad_name = "P1.17" +gpio = 49 + + +[[pins]] +pin = 15 +ball = "B5" +pad_name = "P1.18" +gpio = 50 + + +[[pins]] +pin = 16 +ball = "B6" +pad_name = "P1.19" +gpio = 51 + + +[[pins]] +pin = 17 +ball = "B7" +pad_name = "P1.23" +gpio = 55 + + +[[pins]] +pin = 18 +ball = "B8" +pad_name = "P1.26" +gpio = 58 + + +[[pins]] +pin = 19 +ball = "B9" +pad_name = "P2.06" +gpio = 70 + + +[[pins]] +pin = 20 +ball = "B10" +pad_name = "P2.00" +gpio = 64 + + +[[pins]] +pin = 22 +ball = "C2" +pad_name = "P1.14" +gpio = 46 + + +[[pins]] +pin = 23 +ball = "C3" +pad_name = "P1.13" +gpio = 45 + + +[[pins]] +pin = 24 +ball = "C4" +pad_name = "P1.12" +gpio = 44 + + +[[pins]] +pin = 25 +ball = "C5" +pad_name = "P1.11" +gpio = 43 + + +[[pins]] +pin = 26 +ball = "C6" +pad_name = "P1.20" +gpio = 52 + + +[[pins]] +pin = 27 +ball = "C7" +pad_name = "P1.21" +gpio = 53 + + +[[pins]] +pin = 28 +ball = "C8" +pad_name = "P1.27" +gpio = 59 + + +[[pins]] +pin = 29 +ball = "C9" +pad_name = "P2.07" +gpio = 71 + + +[[pins]] +pin = 30 +ball = "C10" +pad_name = "P2.01" +gpio = 65 + + +[[pins]] +pin = 33 +ball = "D4" +pad_name = "P3.12" +gpio = 108 + + +[[pins]] +pin = 34 +ball = "D5" +pad_name = "P1.10" +gpio = 42 + + +[[pins]] +pin = 35 +ball = "D6" +pad_name = "P1.22" +gpio = 54 + + +[[pins]] +pin = 36 +ball = "D7" +pad_name = "P1.24" +gpio = 56 + + +[[pins]] +pin = 37 +ball = "D8" +pad_name = "P1.28" +gpio = 60 + + +[[pins]] +pin = 38 +ball = "D9" +pad_name = "P2.08" +gpio = 72 + + +[[pins]] +pin = 39 +ball = "D10" +pad_name = "P2.02" +gpio = 66 + + +[[pins]] +pin = 41 +ball = "E3" +pad_name = "P0.09" +gpio = 9 + + +[[pins]] +pin = 42 +ball = "E4" +pad_name = "P3.11" +gpio = 107 + + +[[pins]] +pin = 45 +ball = "E7" +pad_name = "P1.25" +gpio = 57 + + +[[pins]] +pin = 46 +ball = "E8" +pad_name = "P1.09" +gpio = 41 + + +[[pins]] +pin = 47 +ball = "E9" +pad_name = "P2.09" +gpio = 73 + + +[[pins]] +pin = 48 +ball = "E10" +pad_name = "P2.03" +gpio = 67 + + +[[pins]] +pin = 51 +ball = "F3" +pad_name = "P0.08" +gpio = 8 + + +[[pins]] +pin = 52 +ball = "F4" +pad_name = "P3.10" +gpio = 106 + + +[[pins]] +pin = 55 +ball = "F7" +pad_name = "P3.09" +gpio = 105 + + +[[pins]] +pin = 56 +ball = "F8" +pad_name = "P1.08" +gpio = 40 + + +[[pins]] +pin = 57 +ball = "F9" +pad_name = "P2.10" +gpio = 74 + + +[[pins]] +pin = 58 +ball = "F10" +pad_name = "P2.04" +gpio = 68 + + +[[pins]] +pin = 61 +ball = "G3" +pad_name = "P0.07" +gpio = 7 + + +[[pins]] +pin = 62 +ball = "G4" +pad_name = "P3.08" +gpio = 104 + + +[[pins]] +pin = 63 +ball = "G5" +pad_name = "P3.07" +gpio = 103 + + +[[pins]] +pin = 64 +ball = "G6" +pad_name = "P3.06" +gpio = 102 + + +[[pins]] +pin = 65 +ball = "G7" +pad_name = "P3.05" +gpio = 101 + + +[[pins]] +pin = 66 +ball = "G8" +pad_name = "P1.07" +gpio = 39 + + +[[pins]] +pin = 67 +ball = "G9" +pad_name = "P2.05" +gpio = 69 + + +[[pins]] +pin = 70 +ball = "H2" +pad_name = "P0.06" +gpio = 6 + + +[[pins]] +pin = 71 +ball = "H3" +pad_name = "P0.05" +gpio = 5 + + +[[pins]] +pin = 72 +ball = "H4" +pad_name = "P3.03" +gpio = 99 + + +[[pins]] +pin = 73 +ball = "H5" +pad_name = "P3.02" +gpio = 98 + + +[[pins]] +pin = 74 +ball = "H6" +pad_name = "P3.01" +gpio = 97 + + +[[pins]] +pin = 75 +ball = "H7" +pad_name = "P3.00" +gpio = 96 + + +[[pins]] +pin = 76 +ball = "H8" +pad_name = "P1.05" +gpio = 37 + + +[[pins]] +pin = 77 +ball = "H9" +pad_name = "P1.03" +gpio = 35 + + +[[pins]] +pin = 78 +ball = "H10" +pad_name = "P1.29" +gpio = 61 + + +[[pins]] +pin = 79 +ball = "J1" +pad_name = "P0.04" +gpio = 4 + + +[[pins]] +pin = 80 +ball = "J2" +pad_name = "P0.03" +gpio = 3 + + +[[pins]] +pin = 81 +ball = "J3" +pad_name = "P0.02" +gpio = 2 + + +[[pins]] +pin = 82 +ball = "J4" +pad_name = "P3.04" +gpio = 100 + + +[[pins]] +pin = 84 +ball = "J6" +pad_name = "P1.01" +gpio = 33 + + +[[pins]] +pin = 85 +ball = "J7" +pad_name = "P1.02" +gpio = 34 + + +[[pins]] +pin = 86 +ball = "J8" +pad_name = "P1.06" +gpio = 38 + + +[[pins]] +pin = 87 +ball = "J9" +pad_name = "P1.04" +gpio = 36 + + +[[pins]] +pin = 88 +ball = "J10" +pad_name = "P1.30" +gpio = 62 + + +[[pins]] +pin = 90 +ball = "K2" +pad_name = "P0.01" +gpio = 1 + + +[[pins]] +pin = 91 +ball = "K3" +pad_name = "P0.00" +gpio = 0 + + +[[pins]] +pin = 96 +ball = "K8" +pad_name = "P1.00" +gpio = 32 + + +[[pins]] +pin = 97 +ball = "K9" +pad_name = "P1.31" +gpio = 63 diff --git a/ports/zephyr-cp/internal-modules/iobroker/packages/rp2040_qfn56.toml b/ports/zephyr-cp/internal-modules/iobroker/packages/rp2040_qfn56.toml new file mode 100644 index 00000000000..0d21b1448f9 --- /dev/null +++ b/ports/zephyr-cp/internal-modules/iobroker/packages/rp2040_qfn56.toml @@ -0,0 +1,188 @@ +# Package pin map for rp2040_qfn56, transcribed from rp2040-datasheet.pdf, +# Table 615 (GPIO pins), with a one-off pdftotext -layout parse. Review +# against the datasheet figure before editing by hand. +# +# RP2040 has a single GPIO port; pads are numbered 0-29 and pad_name uses +# the datasheet's GPIOx naming. + +name = "rp2040_qfn56" +socs = ["SOC_RP2040"] + +[[pins]] +pin = 2 +pad_name = "GPIO0" +gpio = 0 + + +[[pins]] +pin = 3 +pad_name = "GPIO1" +gpio = 1 + + +[[pins]] +pin = 4 +pad_name = "GPIO2" +gpio = 2 + + +[[pins]] +pin = 5 +pad_name = "GPIO3" +gpio = 3 + + +[[pins]] +pin = 6 +pad_name = "GPIO4" +gpio = 4 + + +[[pins]] +pin = 7 +pad_name = "GPIO5" +gpio = 5 + + +[[pins]] +pin = 8 +pad_name = "GPIO6" +gpio = 6 + + +[[pins]] +pin = 9 +pad_name = "GPIO7" +gpio = 7 + + +[[pins]] +pin = 11 +pad_name = "GPIO8" +gpio = 8 + + +[[pins]] +pin = 12 +pad_name = "GPIO9" +gpio = 9 + + +[[pins]] +pin = 13 +pad_name = "GPIO10" +gpio = 10 + + +[[pins]] +pin = 14 +pad_name = "GPIO11" +gpio = 11 + + +[[pins]] +pin = 15 +pad_name = "GPIO12" +gpio = 12 + + +[[pins]] +pin = 16 +pad_name = "GPIO13" +gpio = 13 + + +[[pins]] +pin = 17 +pad_name = "GPIO14" +gpio = 14 + + +[[pins]] +pin = 18 +pad_name = "GPIO15" +gpio = 15 + + +[[pins]] +pin = 27 +pad_name = "GPIO16" +gpio = 16 + + +[[pins]] +pin = 28 +pad_name = "GPIO17" +gpio = 17 + + +[[pins]] +pin = 29 +pad_name = "GPIO18" +gpio = 18 + + +[[pins]] +pin = 30 +pad_name = "GPIO19" +gpio = 19 + + +[[pins]] +pin = 31 +pad_name = "GPIO20" +gpio = 20 + + +[[pins]] +pin = 32 +pad_name = "GPIO21" +gpio = 21 + + +[[pins]] +pin = 34 +pad_name = "GPIO22" +gpio = 22 + + +[[pins]] +pin = 35 +pad_name = "GPIO23" +gpio = 23 + + +[[pins]] +pin = 36 +pad_name = "GPIO24" +gpio = 24 + + +[[pins]] +pin = 37 +pad_name = "GPIO25" +gpio = 25 + + +[[pins]] +pin = 38 +pad_name = "GPIO26" +gpio = 26 + + +[[pins]] +pin = 39 +pad_name = "GPIO27" +gpio = 27 + + +[[pins]] +pin = 40 +pad_name = "GPIO28" +gpio = 28 + + +[[pins]] +pin = 41 +pad_name = "GPIO29" +gpio = 29 diff --git a/ports/zephyr-cp/internal-modules/iobroker/src/emul/iobroker_analog.c b/ports/zephyr-cp/internal-modules/iobroker/src/emul/iobroker_analog.c new file mode 100644 index 00000000000..c469f1d74cc --- /dev/null +++ b/ports/zephyr-cp/internal-modules/iobroker/src/emul/iobroker_analog.c @@ -0,0 +1,149 @@ +// Emulated analog pad allocation for the iobroker module (native_sim). +// +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-License-Identifier: MIT + +// The emulated ADC (zephyr,adc-emul) and the test DAC (vnd,dac) have no +// analog mux: the emulated channel a pad feeds is the pad number itself, and +// the pads are plain GPIO controller pads on the one-to-one package map +// native_sim selects. So allocate resolves the channel from the pad's global +// number and claims the pad; release only drops the claim (the emulated +// devices need no channel teardown). + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "iobroker_internal.h" + +LOG_MODULE_DECLARE(iobroker, CONFIG_LOG_DEFAULT_LEVEL); + +// Emulated devices: one instance each. Additional instances are ignored +// (there are none in practice on native_sim). + +#if IOBROKER_ADC +#if defined(CONFIG_ADC_EMUL) && DT_HAS_COMPAT_STATUS_OKAY(zephyr_adc_emul) +#define ANALOG_ADC_NODE DT_COMPAT_GET_ANY_STATUS_OKAY(zephyr_adc_emul) +static const struct device *analog_adc_device(void) { + return DEVICE_DT_GET(ANALOG_ADC_NODE); +} + +static uint8_t analog_adc_channel_count(void) { + return DT_PROP(ANALOG_ADC_NODE, nchannels); +} +#else +static const struct device *analog_adc_device(void) { + return NULL; +} + +static uint8_t analog_adc_channel_count(void) { + return 0; +} +#endif +#endif // IOBROKER_ADC + +#if IOBROKER_DAC +#if defined(CONFIG_DAC_TEST) && DT_HAS_COMPAT_STATUS_OKAY(vnd_dac) +#define ANALOG_DAC_NODE DT_COMPAT_GET_ANY_STATUS_OKAY(vnd_dac) +static const struct device *analog_dac_device(void) { + return DEVICE_DT_GET(ANALOG_DAC_NODE); +} + +// The test DAC's binding has no channel count; the emulated hardware takes +// any channel id, so the number of channels is not bounded beyond the claim +// registry itself. +#define ANALOG_DAC_CHANNEL_COUNT 8 +#else +static const struct device *analog_dac_device(void) { + return NULL; +} + +#define ANALOG_DAC_CHANNEL_COUNT 0 +#endif +#endif // IOBROKER_DAC + +#if IOBROKER_ADC || IOBROKER_DAC +static int adc_dac_allocate(package_pin_t pin, const struct device *dev, + uint8_t count, const struct device **dev_out, uint8_t *channel_out, + uint8_t *input_out, const char *what) { + if (dev == NULL || count == 0) { + return -ENOSYS; + } + + uint16_t soc_pad; + int ret = iobroker_package_pin_soc_pad(pin, &soc_pad); + if (ret < 0) { + LOG_WRN("%s allocate: package pin %u not in package map", + what, (unsigned)pin); + return ret; + } + + // Emulated devices have no analog mux: the channel a pad feeds is the + // pad's global number itself, while it indexes into the device's + // channel array. + if (soc_pad >= count) { + LOG_WRN("%s allocate: pad %u has no analog channel on %s", + what, (unsigned)soc_pad, dev->name); + return -EINVAL; + } + *channel_out = (uint8_t)soc_pad; + + ret = iobroker_analog_claim_add(pin, dev, *channel_out); + if (ret < 0) { + return ret; + } + + *dev_out = dev; + // The emulated devices have no selectable inputs; the caller ignores + // this when it configures the channel. + *input_out = 0; + LOG_INF("%s allocate: package pin %u (pad %u) -> %s channel %u", + what, (unsigned)pin, (unsigned)soc_pad, dev->name, + (unsigned)*channel_out); + return 0; +} + +static bool adc_dac_release(const struct device *dev, uint8_t channel, + const char *what) { + uint16_t soc_pad; + if (!iobroker_analog_claim_remove(dev, channel, &soc_pad)) { + LOG_DBG("%s release: %s channel %u not allocated", + what, dev == NULL ? "(null)" : dev->name, (unsigned)channel); + return false; + } + + iobroker_gpio_pad_quiesce(soc_pad); + LOG_INF("%s release: %s channel %u released", what, dev->name, + (unsigned)channel); + return true; +} + +int iobroker_adc_allocate(package_pin_t pin, const struct device **dev_out, + uint8_t *channel_out, uint8_t *input_out) { + return adc_dac_allocate(pin, analog_adc_device(), analog_adc_channel_count(), + dev_out, channel_out, input_out, "adc"); +} + +bool iobroker_adc_release(const struct device *dev, uint8_t channel) { + return adc_dac_release(dev, channel, "adc"); +} +#endif // IOBROKER_ADC || IOBROKER_DAC + +#if IOBROKER_DAC +int iobroker_dac_allocate(package_pin_t pin, const struct device **dev_out, + uint8_t *channel_out, uint8_t *input_out) { + return adc_dac_allocate(pin, analog_dac_device(), ANALOG_DAC_CHANNEL_COUNT, + dev_out, channel_out, input_out, "dac"); +} + +bool iobroker_dac_release(const struct device *dev, uint8_t channel) { + return adc_dac_release(dev, channel, "dac"); +} +#endif // IOBROKER_DAC diff --git a/ports/zephyr-cp/internal-modules/iobroker/src/emul/iobroker_pwm.c b/ports/zephyr-cp/internal-modules/iobroker/src/emul/iobroker_pwm.c new file mode 100644 index 00000000000..8e683e64025 --- /dev/null +++ b/ports/zephyr-cp/internal-modules/iobroker/src/emul/iobroker_pwm.c @@ -0,0 +1,131 @@ +// Emulated PWM channel allocation for the iobroker module (native_sim). +// +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Dan Halbert for Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +// The emulated PWM controller (adafruit,pwm-emul, see the pwm_emul module) +// has one channel per GPIO: the channel a pad drives is the pad's global +// GPIO number, as with the emulated ADC and DAC. Channels that share a +// period form a group; the controller has a pool of them (the groups +// property), and any channel can join any group, without a channel limit. +// So this models only the pwmio rules every SoC shares, not any SoC's +// layout: a shared request joins a group requested at the same frequency, +// an exclusive request takes a group of its own, and with no usable group +// left the request fails. The pad is claimed as a GPIO, +// which makes it busy for every other allocation. + +#include +#include +#include +#include + +#include +#include +#include +#include + +#include "iobroker_internal.h" + +LOG_MODULE_DECLARE(iobroker, CONFIG_LOG_DEFAULT_LEVEL); + +#define EMUL_PWM_NODE DT_COMPAT_GET_ANY_STATUS_OKAY(adafruit_pwm_emul) +#define EMUL_PWM_CHANNELS DT_PROP(EMUL_PWM_NODE, channels) +#define EMUL_PWM_GROUPS DT_PROP(EMUL_PWM_NODE, groups) + +// Period groups. A group is free while it has no users. +typedef struct { + // Frequency in Hz the group's channels were requested at. + uint32_t frequency; + // One caller holds the group alone; nobody may join. + bool exclusive; + uint16_t users; +} emul_pwm_group_t; + +static emul_pwm_group_t groups[EMUL_PWM_GROUPS]; + +// The group each channel belongs to, while the channel is allocated. +static uint8_t channel_group[EMUL_PWM_CHANNELS]; +BUILD_ASSERT(EMUL_PWM_GROUPS <= UINT8_MAX, "group index must fit channel_group[]"); + +// Channels currently allocated, so release only drops claims it made. +static uint32_t allocated[DIV_ROUND_UP(EMUL_PWM_CHANNELS, 32)]; + +// Pick the group for a request: a running group at the same frequency that +// nobody holds exclusively, unless the request is exclusive itself, or else +// a free group. Returns the group index, or -1 when none is usable. +static int emul_pwm_group_pick(uint32_t frequency, bool exclusive) { + if (!exclusive) { + for (int i = 0; i < EMUL_PWM_GROUPS; i++) { + if (groups[i].users > 0 && !groups[i].exclusive && + groups[i].frequency == frequency) { + return i; + } + } + } + for (int i = 0; i < EMUL_PWM_GROUPS; i++) { + if (groups[i].users == 0) { + return i; + } + } + return -1; +} + +static const struct device *emul_pwm_device(void) { + return DEVICE_DT_GET(EMUL_PWM_NODE); +} + +int iobroker_pwm_channel_allocate(package_pin_t pin, uint32_t frequency, + bool exclusive, const struct device **dev_out, uint32_t *channel_out) { + uint16_t soc_pad; + uint16_t gpio_pad; + if (pin == IOBROKER_NO_PIN || iobroker_package_pin_soc_pad(pin, &soc_pad) < 0 || + iobroker_pad_gpio(soc_pad, &gpio_pad) < 0 || gpio_pad >= EMUL_PWM_CHANNELS) { + LOG_WRN("pwm channel allocate: package pin %u has no emulated PWM channel", + (unsigned)pin); + return -EINVAL; + } + int group = emul_pwm_group_pick(frequency, exclusive); + if (group < 0) { + LOG_WRN("pwm channel allocate: no usable period group for package pin %u", + (unsigned)pin); + return -ENODEV; + } + const struct device *port; + gpio_pin_t number; + int ret = iobroker_gpio_allocate(pin, &port, &number); + if (ret < 0) { + return ret; + } + if (groups[group].users == 0) { + groups[group].frequency = frequency; + groups[group].exclusive = exclusive; + } + groups[group].users++; + channel_group[gpio_pad] = (uint8_t)group; + allocated[gpio_pad / 32] |= BIT(gpio_pad % 32); + *dev_out = emul_pwm_device(); + *channel_out = gpio_pad; + LOG_INF("pwm channel allocate: package pin %u -> %s channel %u, group %d", + (unsigned)pin, (*dev_out)->name, (unsigned)gpio_pad, group); + return 0; +} + +bool iobroker_pwm_channel_release(const struct device *dev, uint32_t channel) { + if (dev != emul_pwm_device() || channel >= EMUL_PWM_CHANNELS || + !(allocated[channel / 32] & BIT(channel % 32))) { + LOG_WRN("pwm channel release: %s channel %u is not allocated", + dev == NULL ? "(null)" : dev->name, (unsigned)channel); + return false; + } + allocated[channel / 32] &= ~BIT(channel % 32); + groups[channel_group[channel]].users--; + const struct device *port; + gpio_pin_t number; + if (iobroker_gpio_split((uint16_t)channel, &port, &number) == 0) { + (void)iobroker_gpio_release(port, number); + } + return true; +} diff --git a/ports/zephyr-cp/internal-modules/iobroker/src/iobroker.c b/ports/zephyr-cp/internal-modules/iobroker/src/iobroker.c new file mode 100644 index 00000000000..ef8631881d2 --- /dev/null +++ b/ports/zephyr-cp/internal-modules/iobroker/src/iobroker.c @@ -0,0 +1,492 @@ +// iobroker: dynamic peripheral allocation and runtime pin routing. +// +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +// SoC-agnostic core: package pin resolution, GPIO controller lookup and the +// claim registry. The bus allocate/release functions are SoC-specific and +// live in src///; the -ENOSYS stubs below stand in for SoCs +// with no implementation. + +#include +#include + +#include +#include +#include +#include + +#include "iobroker_internal.h" + +// One log instance for the whole module; iobroker_route.c declares it. +// Compiles away when CONFIG_LOG is off. +LOG_MODULE_REGISTER(iobroker, CONFIG_LOG_DEFAULT_LEVEL); + +int iobroker_gpio_split(uint16_t number, const struct device **port_out, + gpio_pin_t *pin_out) { + for (size_t i = 0; i < iobroker_gpio_port_count; i++) { + uint32_t base = (uint32_t)iobroker_gpio_port_indexes[i] * 32U; + if (number >= base && number < base + 32U) { + *port_out = iobroker_gpio_port_devices[i]; + *pin_out = (gpio_pin_t)(number - base); + return 0; + } + } + return -EINVAL; +} + +int iobroker_gpio_package_pin(uint8_t port, gpio_pin_t pin, + package_pin_t *package_pin_out) { + uint16_t gpio_pad = (uint16_t)((uint32_t)port * 32U + pin); + #if defined(CONFIG_IOBROKER_PACKAGE_ONE_TO_ONE) + // Identity map: the package pin is the global pin number. + *package_pin_out = gpio_pad; + return 0; + #else + for (size_t i = 0; i < iobroker_package_pin_count; i++) { + if (iobroker_package_pins[i].gpio_pad == gpio_pad) { + *package_pin_out = iobroker_package_pins[i].package_pin; + return 0; + } + } + return -EINVAL; + #endif +} + +int iobroker_package_pin_soc_pad(package_pin_t pin, uint16_t *soc_pad_out) { + if (pin == IOBROKER_NO_PIN) { + *soc_pad_out = IOBROKER_NO_PIN; + return 0; + } + #if defined(CONFIG_IOBROKER_PACKAGE_ONE_TO_ONE) + // Identity map: the package pin is the global pin number. + *soc_pad_out = pin; + return 0; + #else + for (size_t i = 0; i < iobroker_package_pin_count; i++) { + if (iobroker_package_pins[i].package_pin == pin) { + *soc_pad_out = iobroker_package_pins[i].soc_pad; + return 0; + } + } + return -EINVAL; + #endif +} + +int iobroker_pad_gpio(uint16_t soc_pad, uint16_t *gpio_pad_out) { + if (soc_pad == IOBROKER_NO_PIN) { + *gpio_pad_out = IOBROKER_NO_PIN; + return 0; + } + #if defined(CONFIG_IOBROKER_PACKAGE_ONE_TO_ONE) + // Identity map: the package pin is the global pin number, so every pad + // sits on its GPIO controller. + *gpio_pad_out = soc_pad; + return 0; + #else + for (size_t i = 0; i < iobroker_package_pin_count; i++) { + if (iobroker_package_pins[i].soc_pad == soc_pad) { + if (iobroker_package_pins[i].gpio_pad == IOBROKER_PAD_NO_GPIO) { + // Analog-only pad: no GPIO controller bond. + return -EINVAL; + } + *gpio_pad_out = iobroker_package_pins[i].gpio_pad; + return 0; + } + } + return -EINVAL; + #endif +} + +#if !IOBROKER_ROUTING + +// SoCs without runtime routing: the bus allocate/release API still exists so +// busio can call it, but every allocate reports -ENOSYS. The implementations +// for routing SoCs live in src///. +int iobroker_i2c_allocate(package_pin_t sda, package_pin_t scl, + const struct device **dev_out) { + (void)sda; + (void)scl; + (void)dev_out; + return -ENOSYS; +} + +#if defined(CONFIG_BOARD_NATIVE_SIM) && DT_HAS_COMPAT_STATUS_OKAY(zephyr_spi_emul_controller) +// native_sim has no pin routing: any pins get the emulated SPI controller. +#define NATIVE_SIM_SPI DEVICE_DT_GET_ONE(zephyr_spi_emul_controller) +static bool native_sim_spi_in_use; +#endif + +int iobroker_spi_allocate(package_pin_t clock, package_pin_t mosi, + package_pin_t miso, const struct device **dev_out) { + (void)clock; + (void)mosi; + (void)miso; + #ifdef NATIVE_SIM_SPI + if (native_sim_spi_in_use) { + return -ENODEV; + } + native_sim_spi_in_use = true; + *dev_out = NATIVE_SIM_SPI; + return 0; + #else + (void)dev_out; + return -ENOSYS; + #endif +} + +int iobroker_uart_allocate(package_pin_t tx, package_pin_t rx, + package_pin_t rts, package_pin_t cts, const struct device **dev_out) { + (void)tx; + (void)rx; + (void)rts; + (void)cts; + (void)dev_out; + return -ENOSYS; +} + +bool iobroker_release(const struct device *dev) { + #ifdef NATIVE_SIM_SPI + if (dev == NATIVE_SIM_SPI) { + native_sim_spi_in_use = false; + } + #endif + (void)dev; + LOG_DBG("release: no routing support on this SoC, nothing to release"); + return false; +} + +#endif // !IOBROKER_ROUTING + +#if !IOBROKER_PWM_CHANNELS + +// SoCs without a PWM channel implementation: the API still exists so pwmio +// can call it, but every allocation reports -ENOSYS. The implementations +// live in src/// (nRF) and in src/emul/ (the emulated PWM). +int iobroker_pwm_channel_allocate(package_pin_t pin, uint32_t frequency, + bool exclusive, const struct device **dev_out, uint32_t *channel_out) { + (void)pin; + (void)frequency; + (void)exclusive; + (void)dev_out; + (void)channel_out; + return -ENOSYS; +} + +bool iobroker_pwm_channel_release(const struct device *dev, uint32_t channel) { + (void)dev; + (void)channel; + return false; +} + +#endif // !IOBROKER_PWM_CHANNELS + +#if !IOBROKER_ADC + +// SoCs without an ADC implementation: the ADC allocate/release API still +// exists so analogio can call it, but every call reports -ENOSYS. The +// implementations live in src/// (nRF SAADC) and in src/emul/ +// (the emulated ADC). +int iobroker_adc_allocate(package_pin_t pin, const struct device **dev_out, + uint8_t *channel_out, uint8_t *input_out) { + (void)pin; + (void)dev_out; + (void)channel_out; + (void)input_out; + return -ENOSYS; +} + +bool iobroker_adc_release(const struct device *dev, uint8_t channel) { + (void)dev; + (void)channel; + LOG_DBG("adc release: no ADC support on this SoC, nothing to release"); + return false; +} + +#endif // !IOBROKER_ADC + +#if !IOBROKER_DAC + +// SoCs without a DAC implementation: the DAC allocate/release API still +// exists so analogio can call it, but every call reports -ENOSYS. The +// implementations live in src/// (Renesas RA DAC) and in +// src/emul/ (the emulated test DAC). +int iobroker_dac_allocate(package_pin_t pin, const struct device **dev_out, + uint8_t *channel_out, uint8_t *input_out) { + (void)pin; + (void)dev_out; + (void)channel_out; + (void)input_out; + return -ENOSYS; +} + +bool iobroker_dac_release(const struct device *dev, uint8_t channel) { + (void)dev; + (void)channel; + LOG_DBG("dac release: no DAC support on this SoC, nothing to release"); + return false; +} + +#endif // !IOBROKER_DAC + +// Pins currently claimed for plain GPIO use. The module leaves the pad alone +// on allocate (the caller configures it) but returns it to a quiescent state +// on release. Claims store the GPIO controller device and pin number that the +// allocate call resolved and returned. +typedef struct { + const struct device *port; + gpio_pin_t number; + bool in_use; +} gpio_claim_t; + +static gpio_claim_t gpio_claims[CONFIG_IOBROKER_GPIO_MAX_PINS]; + +// Pads currently claimed for analog use (ADC inputs, DAC outputs). Analog +// functions have no runtime routing; the claim only marks the pad busy for +// bus and GPIO allocations, and records which analog device and channel slot +// the allocation holds. The implementations keep the registry consistent +// through the claim_add/claim_remove helpers below. +typedef struct { + const struct device *dev; + uint8_t channel; + uint16_t soc_pad; + bool in_use; +} analog_claim_t; + +static analog_claim_t analog_claims[CONFIG_IOBROKER_ANALOG_MAX_PINS]; + +// Returns true when the package pin is claimed by a currently allocated +// instance or a GPIO allocation. Disconnected signals (IOBROKER_NO_PIN) +// and package pins with no entry in the map claim nothing. The bus loops +// below exist whenever the nRF pinctrl driver is built (the board emits the +// instance tables); without routing the tables are never marked in use. +bool iobroker_pin_in_use(package_pin_t pin) { + if (pin == IOBROKER_NO_PIN) { + return false; + } + #if defined(CONFIG_PINCTRL_NRF) + for (size_t i = 0; i < iobroker_i2c_bus_count; i++) { + if (!iobroker_i2c_bus_states[i].in_use) { + continue; + } + for (uint8_t j = 0; j < iobroker_i2c_bus_states[i].pin_count; j++) { + if (iobroker_i2c_bus_states[i].pins[j] == pin) { + return true; + } + } + } + for (size_t i = 0; i < iobroker_spi_bus_count; i++) { + if (!iobroker_spi_bus_states[i].in_use) { + continue; + } + for (uint8_t j = 0; j < iobroker_spi_bus_states[i].pin_count; j++) { + if (iobroker_spi_bus_states[i].pins[j] == pin) { + return true; + } + } + } + for (size_t i = 0; i < iobroker_uart_bus_count; i++) { + if (!iobroker_uart_bus_states[i].in_use) { + continue; + } + for (uint8_t j = 0; j < iobroker_uart_bus_states[i].pin_count; j++) { + if (iobroker_uart_bus_states[i].pins[j] == pin) { + return true; + } + } + } + for (size_t i = 0; i < iobroker_pwm_bus_count; i++) { + if (!iobroker_pwm_bus_states[i].in_use) { + continue; + } + for (uint8_t j = 0; j < iobroker_pwm_bus_states[i].pin_count; j++) { + if (iobroker_pwm_bus_states[i].pins[j] == pin) { + return true; + } + } + } + #endif // CONFIG_PINCTRL_NRF + uint16_t soc_pad; + if (iobroker_package_pin_soc_pad(pin, &soc_pad) < 0) { + return false; + } + #if defined(CONFIG_PINCTRL_NRF) + // Pads owned by fixed peripherals (console UART, flash instance, ...) are + // always in use: their pinctrl state drives them from boot. + for (size_t i = 0; i < iobroker_reserved_pads_count; i++) { + if (iobroker_reserved_pads[i] == soc_pad) { + return true; + } + } + #endif + // Analog claims don't involve GPIO controllers (the analog input is a + // fixed mux setting of the SoC), so match by pad. Analog-only pads, which + // no GPIO controller covers, are reported through this loop. + for (size_t i = 0; i < ARRAY_SIZE(analog_claims); i++) { + if (analog_claims[i].in_use && analog_claims[i].soc_pad == soc_pad) { + return true; + } + } + uint16_t gpio_pad; + if (iobroker_pad_gpio(soc_pad, &gpio_pad) < 0) { + return false; + } + const struct device *port; + gpio_pin_t number; + if (iobroker_gpio_split(gpio_pad, &port, &number) < 0) { + return false; + } + for (size_t i = 0; i < ARRAY_SIZE(gpio_claims); i++) { + if (gpio_claims[i].in_use && gpio_claims[i].port == port && + gpio_claims[i].number == number) { + return true; + } + } + return false; +} + +// Claim a package pin for GPIO use. The caller configures the pad itself +// while the claim is held; release returns it to a quiescent state. The pin +// is resolved through the package pin map, and the GPIO controller device and +// pin number within it are returned. +int iobroker_gpio_allocate(package_pin_t pin, + const struct device **port_out, gpio_pin_t *pin_out) { + if (pin == IOBROKER_NO_PIN) { + LOG_WRN("gpio allocate: pin is disconnected"); + return -EINVAL; + } + if (iobroker_pin_in_use(pin)) { + LOG_WRN("gpio allocate: package pin %u already claimed", (unsigned)pin); + return -EBUSY; + } + uint16_t soc_pad; + int ret = iobroker_package_pin_soc_pad(pin, &soc_pad); + if (ret < 0) { + LOG_WRN("gpio allocate: package pin %u not in package map", (unsigned)pin); + return ret; + } + uint16_t gpio_pad; + ret = iobroker_pad_gpio(soc_pad, &gpio_pad); + if (ret < 0) { + LOG_WRN("gpio allocate: no GPIO controller for pad %u", (unsigned)soc_pad); + return ret; + } + ret = iobroker_gpio_split(gpio_pad, port_out, pin_out); + if (ret < 0) { + LOG_WRN("gpio allocate: no GPIO controller for pad %u", (unsigned)soc_pad); + return ret; + } + for (size_t i = 0; i < ARRAY_SIZE(gpio_claims); i++) { + if (gpio_claims[i].in_use) { + continue; + } + gpio_claims[i].port = *port_out; + gpio_claims[i].number = *pin_out; + gpio_claims[i].in_use = true; + LOG_DBG("gpio allocate: package pin %u -> %s pin %u", + (unsigned)pin, (*port_out)->name, (unsigned)*pin_out); + return 0; + } + LOG_WRN("gpio allocate: claim registry full (%u pins)", + (unsigned)CONFIG_IOBROKER_GPIO_MAX_PINS); + return -ENOMEM; +} + +// Return a pad to a quiescent state: disconnected from any peripheral +// routing, input buffer and driver off, no pulls. +static void gpio_deconfigure(const struct device *port, gpio_pin_t number) { + if (gpio_pin_configure(port, number, GPIO_DISCONNECTED) == -ENOTSUP) { + // SoCs without GPIO_DISCONNECTED support settle for a plain input. + gpio_pin_configure(port, number, GPIO_INPUT); + } +} + +// Release a GPIO claim and return the pad to a quiescent state. Pass the +// device and pin number that the allocate call returned. Returns true when a +// claim was held. +bool iobroker_gpio_release(const struct device *port, gpio_pin_t number) { + for (size_t i = 0; i < ARRAY_SIZE(gpio_claims); i++) { + if (gpio_claims[i].in_use && gpio_claims[i].port == port && + gpio_claims[i].number == number) { + gpio_claims[i].in_use = false; + gpio_deconfigure(port, number); + LOG_DBG("gpio release: %s pin %u back to quiescent state", + port->name, (unsigned)number); + return true; + } + } + return false; +} + +// Shared analog claim registry helpers, used by the analog implementations. +// See iobroker_internal.h for the contract. + +bool iobroker_analog_channel_in_use(const struct device *dev, uint8_t channel) { + for (size_t i = 0; i < ARRAY_SIZE(analog_claims); i++) { + if (analog_claims[i].in_use && analog_claims[i].dev == dev && + analog_claims[i].channel == channel) { + return true; + } + } + return false; +} + +int iobroker_analog_claim_add(package_pin_t pin, const struct device *dev, + uint8_t channel) { + if (iobroker_pin_in_use(pin)) { + LOG_WRN("analog claim: package pin %u already claimed", (unsigned)pin); + return -EBUSY; + } + uint16_t soc_pad; + int ret = iobroker_package_pin_soc_pad(pin, &soc_pad); + if (ret < 0) { + LOG_WRN("analog claim: package pin %u not in package map", (unsigned)pin); + return ret; + } + for (size_t i = 0; i < ARRAY_SIZE(analog_claims); i++) { + if (analog_claims[i].in_use) { + continue; + } + analog_claims[i].dev = dev; + analog_claims[i].channel = channel; + analog_claims[i].soc_pad = soc_pad; + analog_claims[i].in_use = true; + LOG_DBG("analog claim: package pin %u (pad %u) -> %s channel %u", + (unsigned)pin, (unsigned)soc_pad, dev->name, (unsigned)channel); + return 0; + } + LOG_WRN("analog claim: registry full (%u pads)", + (unsigned)CONFIG_IOBROKER_ANALOG_MAX_PINS); + return -ENOMEM; +} + +bool iobroker_analog_claim_remove(const struct device *dev, uint8_t channel, + uint16_t *soc_pad_out) { + for (size_t i = 0; i < ARRAY_SIZE(analog_claims); i++) { + if (analog_claims[i].in_use && analog_claims[i].dev == dev && + analog_claims[i].channel == channel) { + analog_claims[i].in_use = false; + *soc_pad_out = analog_claims[i].soc_pad; + return true; + } + } + return false; +} + +void iobroker_gpio_pad_quiesce(uint16_t soc_pad) { + uint16_t gpio_pad; + // Analog-only pads, which no GPIO controller covers, have no digital + // configuration to quiesce. + if (iobroker_pad_gpio(soc_pad, &gpio_pad) < 0) { + return; + } + const struct device *port; + gpio_pin_t number; + if (iobroker_gpio_split(gpio_pad, &port, &number) < 0) { + return; + } + gpio_deconfigure(port, number); +} diff --git a/ports/zephyr-cp/internal-modules/iobroker/src/iobroker_internal.h b/ports/zephyr-cp/internal-modules/iobroker/src/iobroker_internal.h new file mode 100644 index 00000000000..6b74dafcebe --- /dev/null +++ b/ports/zephyr-cp/internal-modules/iobroker/src/iobroker_internal.h @@ -0,0 +1,52 @@ +// iobroker internal helpers shared between the SoC-agnostic core and the +// vendor/SoC implementations in src///. Not part of the public +// API; see include/iobroker/iobroker.h for that. +// +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include + +// Resolve a package pin to the SoC pad it is bonded to (defined by the core). +// IOBROKER_NO_PIN passes through unchanged so that disconnected optional +// signals stay disconnected. Returns 0, or -EINVAL when the pin is not in +// the map. +int iobroker_package_pin_soc_pad(package_pin_t pin, uint16_t *soc_pad_out); + +// Resolve a SoC pad to the global GPIO number it is bonded to (port index * +// 32 + pin). Returns 0, or -EINVAL when the pad has no GPIO controller (an +// analog-only pad). +int iobroker_pad_gpio(uint16_t soc_pad, uint16_t *gpio_pad_out); + +// Analog claim registry helpers, shared by the analog implementations in +// src/// and src/emul/. The registry is what +// iobroker_pin_in_use() reports, so bus allocate() calls and GPIO +// allocations refuse analog-claimed pads. + +// Returns true when the channel slot is currently taken by an analog +// allocation on the given device. +bool iobroker_analog_channel_in_use(const struct device *dev, uint8_t channel); + +// Record an analog claim: the pad is validated (nothing else may hold it) +// and its SoC pad stored alongside the device and channel. Call after the +// implementation has resolved the pad and picked a free channel slot. +// Returns 0, or -EBUSY (pad already claimed), -EINVAL (pin has no SoC pad) +// or -ENOMEM (claim registry full). +int iobroker_analog_claim_add(package_pin_t pin, const struct device *dev, + uint8_t channel); + +// Drop the analog claim for the given device and channel. *soc_pad_out +// receives the claimed pad's SoC pad number for quiescing. Returns true when +// a claim was held. +bool iobroker_analog_claim_remove(const struct device *dev, uint8_t channel, + uint16_t *soc_pad_out); + +// Return a pad to a quiescent state (disconnected from any peripheral +// routing, input buffer and driver off, no pulls). Analog-only pads, which no +// GPIO controller covers, are left alone. +void iobroker_gpio_pad_quiesce(uint16_t soc_pad); diff --git a/ports/zephyr-cp/internal-modules/iobroker/src/nordic/nrf/iobroker_analog.c b/ports/zephyr-cp/internal-modules/iobroker/src/nordic/nrf/iobroker_analog.c new file mode 100644 index 00000000000..5bf0b313e71 --- /dev/null +++ b/ports/zephyr-cp/internal-modules/iobroker/src/nordic/nrf/iobroker_analog.c @@ -0,0 +1,179 @@ +// nRF analog pad allocation for the iobroker module. +// +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-License-Identifier: MIT + +// The SAADC's analog inputs are hardwired to pads: each pad exposes at most +// one AIN input and there is no runtime routing (unlike the digital +// peripherals' PSEL). Allocate therefore resolves the pad's AIN number from +// the SoC's pin functions table, claims the pad and hands out a free SAADC +// channel slot (the software channels are a runtime resource; Zephyr's ADC +// API has no channel release, so release unconfigures the slot through +// nrfx_saadc_channels_deconfig()). +// +// No DAC peripheral driver exists in Zephyr for nRF SoCs, so +// iobroker_dac_allocate() reports -ENOSYS. + +#include +#include +#include + +#include +#include +#include +#include + +#include +#include + +#include "iobroker_internal.h" + +LOG_MODULE_DECLARE(iobroker, CONFIG_LOG_DEFAULT_LEVEL); + +#if !DT_HAS_COMPAT_STATUS_OKAY(nordic_nrf_saadc) +// SAADC not enabled in the devicetree: the symbols must still exist, but +// every allocate reports -ENOSYS. +#define ANALOG_INPUT_PADS NULL +#define ANALOG_INPUT_COUNT 0 +static const struct device *analog_input_device(void) { + return NULL; +} +static uint8_t analog_input_channel_count(void) { + return 0; +} +#else + +// Package pad (the SoC package's ball id number, in row-major ball order) +// that each SAADC analog input is bonded to, in AIN number order. From the +// pin tables of the packages/ transcriptions (the packages' gpio column +// names the GPIO pad each ball id bonds to; e.g. aQFN73 ball id 3 = P0.02 +// = AIN0). SoCs without a transcribed table report -ENOSYS; add the +// mapping through the SoC's package pin map. +#if defined(NRF52840_XXAA) || defined(NRF52833_XXAA) || defined(NRF52832_XXAA) || \ + defined(NRF52820_XXAA) || defined(NRF52811_XXAA) || defined(NRF52810_XXAA) || \ + defined(NRF52805_XXAA) +// nRF52 series: AIN0..AIN7 are P0.02..P0.05 and P0.28..P0.31, ball ids from +// nrf52840_aqfn73.toml (ball grid packages remap them per package; the +// module maps share the aQFN73 balls). +static const uint16_t analog_input_pads[] = { 3, 16, 30, 32, 15, 2, 14, 1 }; +#define ANALOG_INPUT_PADS analog_input_pads +#define ANALOG_INPUT_COUNT ARRAY_SIZE(analog_input_pads) +#elif defined(NRF5340_XXAA_APPLICATION) +// nRF5340 application core: AIN0..AIN7 are P0.13..P0.20, ball ids from +// nrf5340_qkaa.toml. +static const uint16_t analog_input_pads[] = { 82, 69, 70, 84, 71, 72, 86, 73 }; +#define ANALOG_INPUT_PADS analog_input_pads +#define ANALOG_INPUT_COUNT ARRAY_SIZE(analog_input_pads) +#else +// TODO: add the AIN -> ball id mapping from the SoC's package pin map for +// this SoC. +#define ANALOG_INPUT_PADS NULL +#define ANALOG_INPUT_COUNT 0 +#endif + +static const struct device *analog_input_device(void) { + return DEVICE_DT_GET_ANY(nordic_nrf_saadc); +} + +static uint8_t analog_input_channel_count(void) { + // One software channel slot per hardware SAADC channel. + return SAADC_CH_NUM; +} + +#endif // DT_HAS_COMPAT_STATUS_OKAY(nordic_nrf_saadc) + +int iobroker_adc_allocate(package_pin_t pin, const struct device **dev_out, + uint8_t *channel_out, uint8_t *input_out) { + if (ANALOG_INPUT_COUNT == 0) { + LOG_DBG("analog allocate: no AIN pad table for this SoC"); + return -ENOSYS; + } + + uint16_t soc_pad; + int ret = iobroker_package_pin_soc_pad(pin, &soc_pad); + if (ret < 0) { + LOG_WRN("analog allocate: package pin %u not in package map", + (unsigned)pin); + return ret; + } + + // Find the analog input the pad is bonded to. + uint8_t input = 0; + bool found = false; + for (uint8_t i = 0; i < ANALOG_INPUT_COUNT; i++) { + if (ANALOG_INPUT_PADS[i] == soc_pad) { + input = i; + found = true; + break; + } + } + if (!found) { + LOG_WRN("analog allocate: pad %u has no analog input", (unsigned)soc_pad); + return -EINVAL; + } + + const struct device *dev = analog_input_device(); + if (dev == NULL || !device_is_ready(dev)) { + LOG_WRN("analog allocate: no ready SAADC device"); + return -ENODEV; + } + + // Hand out a free channel slot. + uint8_t count = analog_input_channel_count(); + uint8_t channel = count; + for (uint8_t i = 0; i < count; i++) { + if (!iobroker_analog_channel_in_use(dev, i)) { + channel = i; + break; + } + } + if (channel == count) { + LOG_WRN("analog allocate: %s has no free channel", dev->name); + return -ENOMEM; + } + + ret = iobroker_analog_claim_add(pin, dev, channel); + if (ret < 0) { + return ret; + } + + // The pad's digital side is quiesced: no routing, no input buffer, no + // pull. The analog input is an internal mux setting, so nothing else to + // apply until the caller configures the channel. + iobroker_gpio_pad_quiesce(soc_pad); + + *dev_out = dev; + *channel_out = channel; + *input_out = input; + LOG_INF("adc allocate: package pin %u (pad %u) -> %s channel %u, AIN%u", + (unsigned)pin, (unsigned)soc_pad, dev->name, (unsigned)channel, + (unsigned)input); + return 0; +} + +bool iobroker_adc_release(const struct device *dev, uint8_t channel) { + uint16_t soc_pad; + if (!iobroker_analog_claim_remove(dev, channel, &soc_pad)) { + LOG_DBG("adc release: %s channel %u not allocated", + dev == NULL ? "(null)" : dev->name, (unsigned)channel); + return false; + } + + // Unconfigure the channel so the slot becomes usable again; Zephyr's ADC + // API has no channel release, so this goes through the nrfx HAL the + // Zephyr driver is built on (0 on success, negative errno on failure). + int ret = nrfx_saadc_channels_deconfig(BIT(channel)); + if (ret != 0) { + LOG_WRN("adc release: deconfig of %s channel %u failed: %d", + dev->name, (unsigned)channel, ret); + } + + iobroker_gpio_pad_quiesce(soc_pad); + LOG_INF("adc release: %s channel %u released", dev->name, + (unsigned)channel); + return true; +} + +// No DAC driver exists in Zephyr for nRF SoCs, so IOBROKER_DAC is always 0 +// here and the core's -ENOSYS stub covers iobroker_dac_allocate(). diff --git a/ports/zephyr-cp/internal-modules/iobroker/src/nordic/nrf/iobroker_route.c b/ports/zephyr-cp/internal-modules/iobroker/src/nordic/nrf/iobroker_route.c new file mode 100644 index 00000000000..1044409cf6c --- /dev/null +++ b/ports/zephyr-cp/internal-modules/iobroker/src/nordic/nrf/iobroker_route.c @@ -0,0 +1,666 @@ +// iobroker: nRF runtime pin routing. +// +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +// / = nordic/nrf: one implementation covers every nRF SoC, +// because their pin control encoding is a simple bit-packed value (see +// zephyr/dt-bindings/pinctrl/nrf-pinctrl.h and soc/nordic/common/pinctrl_soc.h) +// that can be computed at runtime, and any peripheral function can be routed +// to (almost) any pin via PSEL. +// +// Compiled whenever CONFIG_PINCTRL_NRF is on. The allocate/release +// definitions here only exist with the full feature set +// (CONFIG_PINCTRL_DYNAMIC and CONFIG_DEVICE_DEINIT_SUPPORT); otherwise the +// stubs in the core report -ENOSYS. + +#include +#include +#include + +#include +#include +#include +#include + +#include "iobroker_internal.h" + +LOG_MODULE_DECLARE(iobroker, CONFIG_LOG_DEFAULT_LEVEL); + +#if IOBROKER_ROUTING + +// Bit positions/fields replicated from nrf-pinctrl.h so that entries can be +// encoded at runtime instead of by the DT macros. +#define NRF_PSEL_FUN(fun) (((uint32_t)(fun) & NRF_FUN_MSK) << NRF_FUN_POS) +#define NRF_PSEL_PIN(pin) (((uint32_t)(pin) & NRF_PIN_MSK) << NRF_PIN_POS) +#define NRF_PSEL_DISCONNECT(fun) \ + ((uint32_t)NRF_PIN_DISCONNECTED | NRF_PSEL_FUN(fun)) +#define NRF_PSEL_PULL_UP ((uint32_t)NRF_PULL_UP << NRF_PULL_POS) +#define NRF_PSEL_LP ((uint32_t)NRF_LP_ENABLE << NRF_LP_POS) +#define NRF_PSEL_CLOCKPIN BIT(NRF_CLOCKPIN_ENABLE_POS) +// Pin + function bits, used to compare a request against a devicetree state. +#define NRF_PSEL_PINFUN_MASK \ + (((uint32_t)NRF_PIN_MSK << NRF_PIN_POS) | ((uint32_t)NRF_FUN_MSK << NRF_FUN_POS)) + +// Log decode helpers: turn a fun code and a SoC pad into readable names, so +// that the logs say which peripheral function goes to which GPIO. +static const char *nrf_fun_name(uint32_t fun) { + static const char *const names[] = { + "UART_TX", "UART_RX", "UART_RTS", "UART_CTS", + "SPIM_SCK", "SPIM_MOSI", "SPIM_MISO", + "SPIS_SCK", "SPIS_MOSI", "SPIS_MISO", "SPIS_CSN", + "TWIM_SCL", "TWIM_SDA", + "I2S_SCK_M", "I2S_SCK_S", "I2S_LRCK_M", "I2S_LRCK_S", "I2S_SDIN", + "I2S_SDOUT", "I2S_MCK", + "PDM_CLK", "PDM_DIN", + "PWM_OUT0", "PWM_OUT1", "PWM_OUT2", "PWM_OUT3", + }; + if (fun < ARRAY_SIZE(names)) { + return names[fun]; + } + return "(other)"; +} + +// Render a SoC pad as a GPIO name ("P0.09"), or "disconnected" for +// IOBROKER_NO_PIN. Writes into buf; returns buf for chaining. +static const char *nrf_pad_name(uint32_t soc_pad, char *buf, size_t size) { + if (soc_pad == IOBROKER_NO_PIN) { + return "disconnected"; + } + snprintf(buf, size, "P%u.%02u", (unsigned)(soc_pad / 32U), + (unsigned)(soc_pad % 32U)); + return buf; +} + +// Decode one pinctrl entry into flags text, e.g. "pull-up clockpin". buf +// receives an empty string when neither flag is set. +static const char *nrf_pin_flags(uint32_t psel, char *buf, size_t size) { + buf[0] = '\0'; + size_t used = 0; + uint32_t pull = NRF_GET_PULL(psel); + if (pull == NRF_PULL_UP) { + used += (size_t)snprintf(buf + used, size - used, "pull-up"); + } else if (pull == NRF_PULL_DOWN) { + used += (size_t)snprintf(buf + used, size - used, "pull-down"); + } + if (NRF_GET_CLOCKPIN_ENABLE(psel)) { + if (used > 0) { + used += (size_t)snprintf(buf + used, size - used, " "); + } + snprintf(buf + used, size - used, "clockpin"); + } + return buf; +} + +// Encode one nRF pin control entry. soc_pad may be IOBROKER_NO_PIN to +// leave the signal disconnected. pull_up enables the internal pull resistor; +// the caller picks it per bus signal (I2C SDA/SCL and UART RX idle high). +static pinctrl_soc_pin_t nrf_psel_encode(uint32_t fun, uint16_t soc_pad, + bool pull_up) { + uint32_t psel; + + if (soc_pad != IOBROKER_NO_PIN) { + psel = NRF_PSEL_PIN(soc_pad) | NRF_PSEL_FUN(fun); + // On nRF54 the GPIO pin clock must be enabled for signals that drive + // the pad. The pinctrl driver ignores this bit where unsupported + // (nRF52/nRF53). + switch (fun) { + case NRF_FUN_TWIM_SDA: + case NRF_FUN_TWIM_SCL: + case NRF_FUN_SPIM_SCK: + case NRF_FUN_SPIM_MOSI: + case NRF_FUN_UART_TX: + psel |= NRF_PSEL_CLOCKPIN; + break; + default: + break; + } + } else { + psel = NRF_PSEL_DISCONNECT(fun); + } + + if (pull_up) { + psel |= NRF_PSEL_PULL_UP; + } + + return psel; +} + +// Whether an instance can drive a pad, given as its global GPIO number +// (port index * 32 + pin). nRF52 and nRF53 are a full crossbar. +// On nRF54L, peripherals and GPIO controllers are grouped in power domains +// and a peripheral can only drive pads of its own domain; the domain is +// encoded in the register address (each occupies its own 256 KiB window: +// 0x4xxxx for the "00" instances and P2, 0xcxxxx-0xfxxxx for the "2x" +// instances and P1/P3, 0x10xxxx for the "30" instances and P0). +static bool nrf_instance_reaches_pad(uint32_t reg_addr, uint16_t gpio_pad) { + #if defined(CONFIG_SOC_SERIES_NRF54L) + uint8_t port = (uint8_t)(gpio_pad / 32U); + for (size_t i = 0; i < iobroker_gpio_port_count; i++) { + if (iobroker_gpio_port_indexes[i] == port) { + return (reg_addr >> 18) == (iobroker_gpio_port_addrs[i] >> 18); + } + } + return false; + #else + (void)reg_addr; + (void)gpio_pad; + return true; + #endif +} + +// Whether an instance can drive every connected pad of a set of encoded +// entries (disconnected entries pass). +static bool nrf_instance_reaches_all(uint32_t reg_addr, + const pinctrl_soc_pin_t *pins, uint8_t pin_count) { + for (uint8_t i = 0; i < pin_count; i++) { + uint32_t pad = NRF_GET_PIN(pins[i]); + if (pad != NRF_PIN_DISCONNECTED && !nrf_instance_reaches_pad(reg_addr, (uint16_t)pad)) { + return false; + } + } + return true; +} + +// Check whether a set of requested entries matches the devicetree default +// state of an instance (pin + function only; configuration bits ignored). +static bool nrf_psels_match(const pinctrl_soc_pin_t *psels, uint8_t count, + const pinctrl_soc_pin_t *requested, uint8_t requested_count) { + uint32_t mask = NRF_PSEL_PINFUN_MASK; + + for (uint8_t i = 0; i < requested_count; i++) { + bool found = false; + for (uint8_t j = 0; j < count; j++) { + if ((psels[j] & mask) == (requested[i] & mask)) { + found = true; + break; + } + } + if (!found) { + return false; + } + } + // The DT state must not use extra pins either. + for (uint8_t j = 0; j < count; j++) { + bool found = false; + for (uint8_t i = 0; i < requested_count; i++) { + if ((psels[j] & mask) == (requested[i] & mask)) { + found = true; + break; + } + } + if (!found) { + return false; + } + } + return true; +} + +// Re-point an instance at the requested pins: ensure the device is +// de-initialized (initialization is the caller's job), then swap its pinctrl +// states for entries built at runtime. The caller initializes the device +// afterwards, which applies the new "default" state. +static int iobroker_route(const iobroker_instance_t *inst, iobroker_state_t *state, + const pinctrl_soc_pin_t *pins, uint8_t pin_count) { + if (pin_count > IOBROKER_MAX_PINS) { + return -EINVAL; + } + + LOG_INF("routing %s: de-initializing then swapping in %u runtime psels", + inst->dev->name, (unsigned)pin_count); + int ret = device_deinit(inst->dev); + if (ret < 0 && ret != -ENOSYS && ret != -EPERM) { + LOG_WRN("routing %s: device_deinit failed: %d", inst->dev->name, ret); + return ret; + } + + // The Zephyr pinctrl core requires the same set of state ids to be + // provided, so mirror the ids the device currently has. + uint8_t state_cnt = MIN(inst->pcfg->state_cnt, ARRAY_SIZE(state->states)); + if (state_cnt == 0) { + return -ENOENT; + } + + for (uint8_t i = 0; i < pin_count; i++) { + state->default_pins[i] = pins[i]; + // Sleep state: same pins, low power (input buffer disconnected). + state->sleep_pins[i] = pins[i] | NRF_PSEL_LP; + } + for (uint8_t s = 0; s < state_cnt; s++) { + uint8_t id = inst->pcfg->states[s].id; + state->states[s].id = id; + if (id == PINCTRL_STATE_SLEEP) { + state->states[s].pins = state->sleep_pins; + } else { + state->states[s].pins = state->default_pins; + } + state->states[s].pin_cnt = pin_count; + } + + ret = pinctrl_update_states(inst->pcfg, state->states, state_cnt); + if (ret < 0) { + LOG_WRN("routing %s: pinctrl_update_states failed: %d", + inst->dev->name, ret); + } else { + for (uint8_t i = 0; i < pin_count; i++) { + uint32_t psel = pins[i]; + char pad[12]; + char flags[24]; + LOG_INF("routing %s: psel[%u] = 0x%08x -> %s %s %s", + inst->dev->name, (unsigned)i, (unsigned)psel, + nrf_fun_name(NRF_GET_FUN(psel)), + nrf_pad_name(NRF_GET_PIN(psel), pad, sizeof(pad)), + nrf_pin_flags(psel, flags, sizeof(flags))); + } + } + return ret; +} + +// Allocate an instance from a pool. Instances that the board enabled with +// disconnected pins are routed dynamically to the requested pins. Instances +// with fixed devicetree pins are only used when the request matches their +// existing state exactly. The requested pins are recorded in the instance's +// state so that iobroker_pin_in_use() can report them. +static int iobroker_allocate(const char *kind, const iobroker_instance_t *buses, + size_t count, iobroker_state_t *states, const package_pin_t *requested, + const pinctrl_soc_pin_t *pins, uint8_t pin_count, const struct device **dev_out) { + bool reachable = false; + for (size_t i = 0; i < count; i++) { + iobroker_state_t *state = &states[i]; + if (!nrf_instance_reaches_all(buses[i].reg_addr, pins, pin_count)) { + continue; + } + reachable = true; + if (state->in_use) { + continue; + } + + if (buses[i].dt_psels == NULL) { + int ret = iobroker_route(&buses[i], state, pins, pin_count); + if (ret < 0) { + continue; + } + state->in_use = true; + state->routed = true; + state->pin_count = pin_count; + for (uint8_t j = 0; j < pin_count; j++) { + state->pins[j] = requested[j]; + } + *dev_out = buses[i].dev; + LOG_INF("%s: allocated %s, routed to %u package pins", + kind, buses[i].dev->name, (unsigned)pin_count); + return 0; + } + + if (nrf_psels_match(buses[i].dt_psels, buses[i].dt_psel_count, pins, pin_count)) { + // Already routed to these pins by the devicetree; just claim it. + state->in_use = true; + state->routed = false; + state->pin_count = pin_count; + for (uint8_t j = 0; j < pin_count; j++) { + state->pins[j] = requested[j]; + } + *dev_out = buses[i].dev; + LOG_INF("%s: allocated %s, devicetree pins match request", + kind, buses[i].dev->name); + return 0; + } + } + if (!reachable) { + LOG_WRN("%s: no instance can be routed to the requested pins", kind); + return -EINVAL; + } + LOG_WRN("%s: no free instance for the requested pins", kind); + return -ENODEV; +} + +// Returns -EBUSY when any requested pin is already claimed by an allocated +// instance, so that a pin is only ever used by one allocate() call at a time. +static int iobroker_check_request(const char *kind, const package_pin_t *pins, + size_t count) { + for (size_t i = 0; i < count; i++) { + if (iobroker_pin_in_use(pins[i])) { + LOG_WRN("%s: package pin %u already in use", kind, + (unsigned)pins[i]); + return -EBUSY; + } + } + return 0; +} + +static bool iobroker_state_find(const struct device *dev, iobroker_state_t **state_out) { + for (size_t i = 0; i < iobroker_i2c_bus_count; i++) { + if (iobroker_i2c_buses[i].dev == dev) { + *state_out = &iobroker_i2c_bus_states[i]; + return true; + } + } + for (size_t i = 0; i < iobroker_spi_bus_count; i++) { + if (iobroker_spi_buses[i].dev == dev) { + *state_out = &iobroker_spi_bus_states[i]; + return true; + } + } + for (size_t i = 0; i < iobroker_uart_bus_count; i++) { + if (iobroker_uart_buses[i].dev == dev) { + *state_out = &iobroker_uart_bus_states[i]; + return true; + } + } + for (size_t i = 0; i < iobroker_pwm_bus_count; i++) { + if (iobroker_pwm_buses[i].dev == dev) { + *state_out = &iobroker_pwm_bus_states[i]; + return true; + } + } + return false; +} + +bool iobroker_release(const struct device *dev) { + iobroker_state_t *state = NULL; + if (!iobroker_state_find(dev, &state)) { + LOG_WRN("release: %s is not an iobroker-managed instance", + dev == NULL ? "(null)" : dev->name); + return false; + } + bool routed = state->routed; + // De-init so that the device ends up de-initialized (like deferred-init + // devices are after boot); the caller initializes it again when it + // allocates the instance next. + (void)device_deinit(dev); + state->in_use = false; + state->routed = false; + state->pin_count = 0; + LOG_INF("released %s (was dynamically routed: %u)", dev->name, + (unsigned)routed); + return routed; +} + +int iobroker_i2c_allocate(package_pin_t sda, package_pin_t scl, + const struct device **dev_out) { + LOG_INF("i2c allocate: sda=%u scl=%u", (unsigned)sda, (unsigned)scl); + const package_pin_t requested[] = { sda, scl }; + int ret = iobroker_check_request("i2c", requested, 2); + if (ret < 0) { + return ret; + } + uint16_t sda_pad; + uint16_t scl_pad; + uint16_t sda_gpio; + uint16_t scl_gpio; + if (iobroker_package_pin_soc_pad(sda, &sda_pad) < 0 || + iobroker_package_pin_soc_pad(scl, &scl_pad) < 0 || + iobroker_pad_gpio(sda_pad, &sda_gpio) < 0 || + iobroker_pad_gpio(scl_pad, &scl_gpio) < 0) { + LOG_WRN("i2c allocate: package pin %u or %u is unknown or has no GPIO", + (unsigned)sda, (unsigned)scl); + return -EINVAL; + } + char sda_name[12]; + char scl_name[12]; + LOG_INF("i2c allocate: SDA package pin %u -> %s, SCL package pin %u -> %s", + (unsigned)sda, nrf_pad_name(sda_gpio, sda_name, sizeof(sda_name)), + (unsigned)scl, nrf_pad_name(scl_gpio, scl_name, sizeof(scl_name))); + pinctrl_soc_pin_t pins[2]; + // Open-drain bus: both lines idle high via the internal pull-up. + pins[0] = nrf_psel_encode(NRF_FUN_TWIM_SDA, sda_gpio, true); + pins[1] = nrf_psel_encode(NRF_FUN_TWIM_SCL, scl_gpio, true); + return iobroker_allocate("i2c", iobroker_i2c_buses, iobroker_i2c_bus_count, + iobroker_i2c_bus_states, requested, pins, 2, dev_out); +} + +int iobroker_spi_allocate(package_pin_t clock, package_pin_t mosi, + package_pin_t miso, const struct device **dev_out) { + LOG_INF("spi allocate: clock=%u mosi=%u miso=%u", (unsigned)clock, + (unsigned)mosi, (unsigned)miso); + const package_pin_t requested[] = { clock, mosi, miso }; + int ret = iobroker_check_request("spi", requested, 3); + if (ret < 0) { + return ret; + } + uint16_t clock_pad; + uint16_t mosi_pad; + uint16_t miso_pad; + uint16_t clock_gpio; + uint16_t mosi_gpio; + uint16_t miso_gpio; + if (iobroker_package_pin_soc_pad(clock, &clock_pad) < 0 || + iobroker_package_pin_soc_pad(mosi, &mosi_pad) < 0 || + iobroker_package_pin_soc_pad(miso, &miso_pad) < 0 || + iobroker_pad_gpio(clock_pad, &clock_gpio) < 0 || + iobroker_pad_gpio(mosi_pad, &mosi_gpio) < 0 || + iobroker_pad_gpio(miso_pad, &miso_gpio) < 0) { + LOG_WRN("spi allocate: a package pin (%u/%u/%u) is unknown or has no GPIO", + (unsigned)clock, (unsigned)mosi, (unsigned)miso); + return -EINVAL; + } + char clock_name[12]; + char mosi_name[12]; + char miso_name[12]; + LOG_INF("spi allocate: SCK package pin %u -> %s, MOSI %u -> %s, MISO %u -> %s", + (unsigned)clock, nrf_pad_name(clock_gpio, clock_name, sizeof(clock_name)), + (unsigned)mosi, nrf_pad_name(mosi_gpio, mosi_name, sizeof(mosi_name)), + (unsigned)miso, nrf_pad_name(miso_gpio, miso_name, sizeof(miso_name))); + pinctrl_soc_pin_t pins[3]; + // All signals are push-pull outputs (MISO from the peripheral's view). + pins[0] = nrf_psel_encode(NRF_FUN_SPIM_SCK, clock_gpio, false); + pins[1] = nrf_psel_encode(NRF_FUN_SPIM_MOSI, mosi_gpio, false); + pins[2] = nrf_psel_encode(NRF_FUN_SPIM_MISO, miso_gpio, false); + return iobroker_allocate("spi", iobroker_spi_buses, iobroker_spi_bus_count, + iobroker_spi_bus_states, requested, pins, 3, dev_out); +} + +int iobroker_uart_allocate(package_pin_t tx, package_pin_t rx, + package_pin_t rts, package_pin_t cts, const struct device **dev_out) { + LOG_INF("uart allocate: tx=%u rx=%u rts=%u cts=%u", (unsigned)tx, + (unsigned)rx, (unsigned)rts, (unsigned)cts); + const package_pin_t requested[] = { tx, rx, rts, cts }; + int ret = iobroker_check_request("uart", requested, 4); + if (ret < 0) { + return ret; + } + uint16_t tx_pad; + uint16_t rx_pad; + uint16_t rts_pad; + uint16_t cts_pad; + uint16_t tx_gpio; + uint16_t rx_gpio; + uint16_t rts_gpio; + uint16_t cts_gpio; + if (iobroker_package_pin_soc_pad(tx, &tx_pad) < 0 || + iobroker_package_pin_soc_pad(rx, &rx_pad) < 0 || + iobroker_package_pin_soc_pad(rts, &rts_pad) < 0 || + iobroker_package_pin_soc_pad(cts, &cts_pad) < 0 || + iobroker_pad_gpio(tx_pad, &tx_gpio) < 0 || + iobroker_pad_gpio(rx_pad, &rx_gpio) < 0 || + iobroker_pad_gpio(rts_pad, &rts_gpio) < 0 || + iobroker_pad_gpio(cts_pad, &cts_gpio) < 0) { + LOG_WRN("uart allocate: a package pin (%u/%u/%u/%u) is unknown or has no GPIO", + (unsigned)tx, (unsigned)rx, (unsigned)rts, (unsigned)cts); + return -EINVAL; + } + char tx_name[12]; + char rx_name[12]; + char rts_name[12]; + char cts_name[12]; + LOG_INF("uart allocate: TX package pin %u -> %s, RX %u -> %s, RTS %u -> %s, CTS %u -> %s", + (unsigned)tx, nrf_pad_name(tx_gpio, tx_name, sizeof(tx_name)), + (unsigned)rx, nrf_pad_name(rx_gpio, rx_name, sizeof(rx_name)), + (unsigned)rts, nrf_pad_name(rts_gpio, rts_name, sizeof(rts_name)), + (unsigned)cts, nrf_pad_name(cts_gpio, cts_name, sizeof(cts_name))); + pinctrl_soc_pin_t pins[4]; + // RX floats until the peer drives it, so pull it up internally. + pins[0] = nrf_psel_encode(NRF_FUN_UART_TX, tx_gpio, false); + pins[1] = nrf_psel_encode(NRF_FUN_UART_RX, rx_gpio, true); + pins[2] = nrf_psel_encode(NRF_FUN_UART_RTS, rts_gpio, false); + pins[3] = nrf_psel_encode(NRF_FUN_UART_CTS, cts_gpio, false); + return iobroker_allocate("uart", iobroker_uart_buses, iobroker_uart_bus_count, + iobroker_uart_bus_states, requested, pins, 4, dev_out); +} + +// Allocate a whole PWM instance for one output pin, routed to its first +// output (OUT0); the other outputs stay disconnected. Used for a new +// channel group. +static int nrf_pwm_instance_allocate(package_pin_t pin, const struct device **dev_out) { + LOG_INF("pwm allocate: pin=%u", (unsigned)pin); + // The pin goes to OUT0; OUT1..OUT3 stay disconnected, and are recorded as + // disconnected so the instance's pin list is complete. + const package_pin_t requested[] = { pin, IOBROKER_NO_PIN, IOBROKER_NO_PIN, IOBROKER_NO_PIN }; + int ret = iobroker_check_request("pwm", requested, 1); + if (ret < 0) { + return ret; + } + uint16_t soc_pad; + uint16_t pad; + if (pin == IOBROKER_NO_PIN || + iobroker_package_pin_soc_pad(pin, &soc_pad) < 0 || + iobroker_pad_gpio(soc_pad, &pad) < 0) { + LOG_WRN("pwm allocate: package pin %u is unknown or has no GPIO", (unsigned)pin); + return -EINVAL; + } + char name[12]; + LOG_INF("pwm allocate: OUT0 package pin %u -> %s", (unsigned)pin, + nrf_pad_name(pad, name, sizeof(name))); + pinctrl_soc_pin_t pins[4]; + // Push-pull output, no pull. + pins[0] = nrf_psel_encode(NRF_FUN_PWM_OUT0, pad, false); + pins[1] = nrf_psel_encode(NRF_FUN_PWM_OUT1, IOBROKER_NO_PIN, false); + pins[2] = nrf_psel_encode(NRF_FUN_PWM_OUT2, IOBROKER_NO_PIN, false); + pins[3] = nrf_psel_encode(NRF_FUN_PWM_OUT3, IOBROKER_NO_PIN, false); + return iobroker_allocate("pwm", iobroker_pwm_buses, iobroker_pwm_bus_count, + iobroker_pwm_bus_states, requested, pins, 4, dev_out); +} + +// Each PWM instance is one period group: its four outputs share COUNTERTOP +// and PRESCALER. +#define NRF_PWM_OUTPUTS 4 +BUILD_ASSERT(NRF_FUN_PWM_OUT1 == NRF_FUN_PWM_OUT0 + 1 && + NRF_FUN_PWM_OUT2 == NRF_FUN_PWM_OUT0 + 2 && + NRF_FUN_PWM_OUT3 == NRF_FUN_PWM_OUT0 + 3, + "PWM output function codes must be consecutive"); +static iobroker_state_t *nrf_pwm_state_find(const struct device *dev) { + for (size_t i = 0; i < iobroker_pwm_bus_count; i++) { + if (iobroker_pwm_buses[i].dev == dev) { + return &iobroker_pwm_bus_states[i]; + } + } + return NULL; +} + +// Connect output `out` of a running instance to a pad, or disconnect it when +// pad is IOBROKER_NO_PIN. Only that output's PSEL (and its pad, when +// connecting) is configured, so the instance's other outputs keep running +// undisturbed. The stored states are updated too, so that the sleep state +// applied at de-init covers exactly the connected pads. +static int nrf_pwm_connect_output(const iobroker_instance_t *inst, + iobroker_state_t *state, uint8_t out, uint16_t pad) { + pinctrl_soc_pin_t psel = nrf_psel_encode(NRF_FUN_PWM_OUT0 + out, pad, false); + int ret = pinctrl_configure_pins(&psel, 1, inst->pcfg->reg); + if (ret < 0) { + LOG_WRN("pwm: connecting %s OUT%u failed: %d", inst->dev->name, + (unsigned)out, ret); + return ret; + } + state->default_pins[out] = psel; + state->sleep_pins[out] = psel | NRF_PSEL_LP; + return 0; +} + +int iobroker_pwm_channel_allocate(package_pin_t pin, uint32_t frequency, + bool exclusive, const struct device **dev_out, uint32_t *channel_out) { + LOG_INF("pwm channel allocate: pin=%u frequency=%u exclusive=%u", + (unsigned)pin, (unsigned)frequency, (unsigned)exclusive); + const package_pin_t requested[] = { pin }; + int ret = iobroker_check_request("pwm", requested, 1); + if (ret < 0) { + return ret; + } + uint16_t soc_pad; + uint16_t pad; + if (pin == IOBROKER_NO_PIN || + iobroker_package_pin_soc_pad(pin, &soc_pad) < 0 || + iobroker_pad_gpio(soc_pad, &pad) < 0) { + LOG_WRN("pwm channel allocate: package pin %u is unknown or has no GPIO", + (unsigned)pin); + return -EINVAL; + } + + // Join a running group requested at the same frequency, with a free + // output. + for (size_t i = 0; i < iobroker_pwm_bus_count && !exclusive; i++) { + const iobroker_instance_t *inst = &iobroker_pwm_buses[i]; + iobroker_state_t *state = &iobroker_pwm_bus_states[i]; + if (!state->in_use || state->channels_used == 0 || state->exclusive || + state->frequency != frequency || + !nrf_instance_reaches_pad(inst->reg_addr, pad)) { + continue; + } + for (uint8_t out = 0; out < NRF_PWM_OUTPUTS; out++) { + if (state->channels_used & BIT(out)) { + continue; + } + if (nrf_pwm_connect_output(inst, state, out, pad) < 0) { + break; + } + state->channels_used |= BIT(out); + state->pins[out] = pin; + LOG_INF("pwm channel allocate: joined %s as OUT%u", inst->dev->name, + (unsigned)out); + *dev_out = inst->dev; + *channel_out = out; + return 0; + } + } + + // Otherwise take a free instance, with the pin on OUT0. + const struct device *dev; + ret = nrf_pwm_instance_allocate(pin, &dev); + if (ret < 0) { + // No new PWM available. + return ret; + } + iobroker_state_t *state = nrf_pwm_state_find(dev); + state->frequency = frequency; + state->exclusive = exclusive; + state->channels_used = BIT(0); + *dev_out = dev; + *channel_out = 0; + return 0; +} + +bool iobroker_pwm_channel_release(const struct device *dev, uint32_t channel) { + iobroker_state_t *state = nrf_pwm_state_find(dev); + if (state == NULL || channel >= NRF_PWM_OUTPUTS || + !(state->channels_used & BIT(channel))) { + LOG_WRN("pwm channel release: %s channel %u is not allocated", + dev == NULL ? "(null)" : dev->name, (unsigned)channel); + return false; + } + const iobroker_instance_t *inst = &iobroker_pwm_buses[state - iobroker_pwm_bus_states]; + package_pin_t pin = state->pins[channel]; + uint16_t soc_pad; + bool have_pad = iobroker_package_pin_soc_pad(pin, &soc_pad) == 0; + + state->channels_used &= ~BIT(channel); + if (state->channels_used == 0) { + // Last channel: release the whole group. De-init applies the sleep + // state to the instance's pads. + state->frequency = 0; + state->exclusive = false; + (void)iobroker_release(dev); + } else { + (void)nrf_pwm_connect_output(inst, state, (uint8_t)channel, IOBROKER_NO_PIN); + state->pins[channel] = IOBROKER_NO_PIN; + } + if (have_pad) { + iobroker_gpio_pad_quiesce(soc_pad); + } + LOG_INF("pwm channel release: %s OUT%u (%s)", dev->name, (unsigned)channel, + state->in_use ? "group still running" : "group released"); + return true; +} + +#endif // IOBROKER_ROUTING diff --git a/ports/zephyr-cp/internal-modules/iobroker/src/nxp/mcxn/iobroker_analog.c b/ports/zephyr-cp/internal-modules/iobroker/src/nxp/mcxn/iobroker_analog.c new file mode 100644 index 00000000000..5bb50ad9714 --- /dev/null +++ b/ports/zephyr-cp/internal-modules/iobroker/src/nxp/mcxn/iobroker_analog.c @@ -0,0 +1,377 @@ +// NXP MCX N LPADC/LPDAC analog pad allocation for the iobroker module. +// +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-License-Identifier: MIT + +// The LPADC inputs and LPDAC outputs are bonded to pads: each pad exposes at +// most one analog function per unit (a few pads feed both LPADC units and the +// DAC output) and there is no runtime analog routing. Allocate resolves the +// pad's analog function from the SoC's pin functions table and claims the pad. +// +// ADC: allocate additionally hands out a free LPADC command-channel slot (the +// Zephyr channel_id indexes the CMD registers; the number is +// ADC_CMDL_COUNT). The hardware input comes from input_positive, +// which Zephyr encodes as the channel number in bits 0..4 and the B-side mux +// in bit 5 (the driver writes ADCH = input & 0x1f and picks the sample mode's +// side from bit 5). The same channel slot is handed back at release; the +// LPADC driver has no persistent per-channel state (commands are set up per +// adc_read()), so a release only frees the slot. +// +// DAC: the LPDAC has a single output channel, so channel 0 is always the +// slot; values are 12-bit (scaled down by analogout before the write). +// +// Neither needs pin activity: the analog functions are bonded at mux 0 like +// every other analog function on MCX N (see +// modules/hal/nxp/dts/nxp/mcx/MCXN947VDF-pinctrl.h, e.g. ADC0_A2_PIO4_23 and +// DAC0_OUT_PIO4_2), so the quiesced pad exposes the analog signal once the +// driver has configured the peripheral. + +#include +#include +#include + +#include +#include +#include + +#include + +#include "iobroker_internal.h" + +LOG_MODULE_DECLARE(iobroker, CONFIG_LOG_DEFAULT_LEVEL); + +#if IOBROKER_DAC && !DT_HAS_COMPAT_STATUS_OKAY(nxp_lpdac) +#error "iobroker: DAC support built but no nxp,lpdac node is okay" +#endif + +#if IOBROKER_ADC + +// Zephyr's io-channel encoding of one LPADC input for the lpadc driver: +// ADCH channel number in the low 5 bits, bit 5 set for a B-side input (the +// driver reads it as input_positive and maps it onto the command's channel +// number and sample-side mode). +#define LPADC_INPUT_A(ch) (ch) +#define LPADC_INPUT_B(ch) (0x20U | (ch)) + +#if defined(CONFIG_SOC_MCXN947) + +// The package pads each LPADC input is bonded to, transcribed from the +// MCXN947 VFBGA184 pin functions (modules/hal/nxp/dts/nxp/mcx/ +// MCXN947VDF-pinctrl.h, entries ADCn_Xy_PIOx_y: unit n, side X (A/B), +// channel y), keyed to the package pad ids the package numbers its pins +// by (mcxn947_vdf.toml: row-major ball order with power balls leaving +// gaps, per the package Pinout workbook; the analog-only ANA_x pads are +// carried by name; e.g. ANA_0 = ball P3 = pad 139, P4_23 = ball U12 = +// pad 181). Entries are ordered by pad; a pad can bond to more than one +// input (across the two units and the mux sides), and the first entry +// wins with the single-ended A-side input preferred. +// +// Add the mapping from the SoC's pin function table for other MCX SoCs; a +// SoC whose table is empty reports -ENOSYS. +struct analog_input { + uint16_t pad; + uint8_t unit; + uint8_t input; +}; + +static const struct analog_input analog_inputs[] = { + // Ball-id pads from the VFBGA184 ball map (mcxn947_vdf.toml): the + // grid's row-major numbering with power balls leaving gaps. The + // analog-only pads carry ANA_x names (ANA_0 = ball P3 = pad 139). + {1, 1, LPADC_INPUT_A(8)}, + {2, 0, LPADC_INPUT_A(23)}, + {3, 0, LPADC_INPUT_A(20)}, + {4, 0, LPADC_INPUT_B(17)}, + {5, 0, LPADC_INPUT_A(13)}, + {6, 0, LPADC_INPUT_A(9)}, + {7, 0, LPADC_INPUT_B(9)}, + {11, 1, LPADC_INPUT_A(9)}, + {12, 0, LPADC_INPUT_A(22)}, + {13, 0, LPADC_INPUT_A(21)}, + {14, 0, LPADC_INPUT_A(19)}, + {15, 0, LPADC_INPUT_B(16)}, + {16, 0, LPADC_INPUT_A(15)}, + {17, 0, LPADC_INPUT_A(14)}, + {18, 0, LPADC_INPUT_A(8)}, + {19, 0, LPADC_INPUT_B(11)}, + {20, 0, LPADC_INPUT_B(10)}, + {25, 1, LPADC_INPUT_A(10)}, + {26, 0, LPADC_INPUT_A(18)}, + {27, 0, LPADC_INPUT_A(17)}, + {28, 0, LPADC_INPUT_A(16)}, + {29, 0, LPADC_INPUT_A(12)}, + {30, 0, LPADC_INPUT_A(11)}, + {31, 0, LPADC_INPUT_A(10)}, + {32, 0, LPADC_INPUT_B(8)}, + {36, 1, LPADC_INPUT_A(13)}, + {37, 1, LPADC_INPUT_A(12)}, + {38, 1, LPADC_INPUT_A(11)}, + {39, 1, LPADC_INPUT_A(14)}, + {41, 0, LPADC_INPUT_B(23)}, + {43, 0, LPADC_INPUT_B(12)}, + {49, 1, LPADC_INPUT_A(15)}, + {51, 0, LPADC_INPUT_B(22)}, + {52, 0, LPADC_INPUT_B(20)}, + {53, 0, LPADC_INPUT_B(19)}, + {54, 0, LPADC_INPUT_B(14)}, + {60, 1, LPADC_INPUT_A(17)}, + {61, 1, LPADC_INPUT_A(16)}, + {62, 0, LPADC_INPUT_B(21)}, + {63, 0, LPADC_INPUT_B(18)}, + {64, 0, LPADC_INPUT_B(13)}, + {70, 1, LPADC_INPUT_A(18)}, + {71, 1, LPADC_INPUT_A(19)}, + {74, 0, LPADC_INPUT_B(15)}, + {99, 1, LPADC_INPUT_A(20)}, + {104, 1, LPADC_INPUT_B(13)}, + {105, 1, LPADC_INPUT_B(14)}, + {110, 1, LPADC_INPUT_A(22)}, + {111, 1, LPADC_INPUT_A(21)}, + {114, 1, LPADC_INPUT_B(15)}, + {115, 1, LPADC_INPUT_B(16)}, + {120, 1, LPADC_INPUT_A(23)}, + {123, 1, LPADC_INPUT_B(10)}, + {124, 1, LPADC_INPUT_B(12)}, + {125, 1, LPADC_INPUT_B(17)}, + {134, 1, LPADC_INPUT_B(11)}, + {139, 0, LPADC_INPUT_A(0)}, + {150, 0, LPADC_INPUT_B(0)}, + {154, 0, LPADC_INPUT_A(6)}, + {155, 0, LPADC_INPUT_B(6)}, + {156, 0, LPADC_INPUT_B(1)}, + {161, 0, LPADC_INPUT_A(4)}, + {161, 1, LPADC_INPUT_A(4)}, + {162, 1, LPADC_INPUT_A(0)}, + {163, 1, LPADC_INPUT_B(0)}, + {165, 0, LPADC_INPUT_A(5)}, + {165, 1, LPADC_INPUT_A(5)}, + {166, 0, LPADC_INPUT_B(5)}, + {166, 1, LPADC_INPUT_B(5)}, + {167, 0, LPADC_INPUT_A(1)}, + {168, 1, LPADC_INPUT_A(6)}, + {169, 1, LPADC_INPUT_B(6)}, + {175, 0, LPADC_INPUT_B(4)}, + {175, 1, LPADC_INPUT_B(4)}, + {181, 0, LPADC_INPUT_A(2)}, + {181, 1, LPADC_INPUT_B(3)}, + {183, 1, LPADC_INPUT_B(8)}, + {184, 1, LPADC_INPUT_B(9)}, +}; +#define ANALOG_INPUT_COUNT ARRAY_SIZE(analog_inputs) + +// The two LPADC units, in devicetree lpadc0/lpadc1 label order; NULL when +// the unit is not enabled or the SoC has no such node. +static const struct device *const analog_adc_devices[2] = { + #if DT_NODE_EXISTS(DT_NODELABEL(lpadc0)) && \ + DT_NODE_HAS_STATUS(DT_NODELABEL(lpadc0), okay) + DEVICE_DT_GET(DT_NODELABEL(lpadc0)), + #else + NULL, + #endif + #if DT_NODE_EXISTS(DT_NODELABEL(lpadc1)) && \ + DT_NODE_HAS_STATUS(DT_NODELABEL(lpadc1), okay) + DEVICE_DT_GET(DT_NODELABEL(lpadc1)), + #else + NULL, + #endif +}; + +static uint8_t analog_adc_channel_count(const struct device *dev) { + (void)dev; + // One command-channel slot per LPADC CMD register. + return ADC_CMDL_COUNT; +} + +#else +// TODO: add the LPADC input -> pad mapping from this SoC's pin function +// table (see CONFIG_SOC_MCXN947 above). +#define ANALOG_INPUT_COUNT 0 + +static const struct device *const analog_adc_devices[2] = {NULL, NULL}; + +static uint8_t analog_adc_channel_count(const struct device *dev) { + (void)dev; + return 0; +} +#endif // CONFIG_SOC_MCXN947 + +int iobroker_adc_allocate(package_pin_t pin, const struct device **dev_out, + uint8_t *channel_out, uint8_t *input_out) { + if (ANALOG_INPUT_COUNT == 0) { + LOG_DBG("adc allocate: no LPADC input table for this SoC"); + return -ENOSYS; + } + + uint16_t soc_pad; + int ret = iobroker_package_pin_soc_pad(pin, &soc_pad); + if (ret < 0) { + LOG_WRN("adc allocate: package pin %u not in package map", + (unsigned)pin); + return ret; + } + + // Find the analog input the pad is bonded to. + const struct analog_input *found = NULL; + for (size_t i = 0; i < ANALOG_INPUT_COUNT; i++) { + if (analog_inputs[i].pad == soc_pad) { + found = &analog_inputs[i]; + break; + } + } + if (found == NULL) { + LOG_WRN("adc allocate: pad %u has no analog input", (unsigned)soc_pad); + return -EINVAL; + } + const struct device *dev = analog_adc_devices[found->unit]; + if (dev == NULL || !device_is_ready(dev)) { + LOG_WRN("adc allocate: no ready LPADC unit %u", (unsigned)found->unit); + return -ENODEV; + } + + // Hand out a free command-channel slot. + uint8_t count = analog_adc_channel_count(dev); + uint8_t channel = count; + for (uint8_t i = 0; i < count; i++) { + if (!iobroker_analog_channel_in_use(dev, i)) { + channel = i; + break; + } + } + if (channel == count) { + LOG_WRN("adc allocate: %s has no free channel", dev->name); + return -ENOMEM; + } + + ret = iobroker_analog_claim_add(pin, dev, channel); + if (ret < 0) { + return ret; + } + + // The pad's digital side is quiesced; the analog input is a bond, not a + // mux setting beyond mux 0, so nothing else to apply until the caller + // configures the channel. + iobroker_gpio_pad_quiesce(soc_pad); + + *dev_out = dev; + *channel_out = channel; + *input_out = found->input; + LOG_INF("adc allocate: package pin %u (pad %u) -> %s channel %u, LPADC%u " + "input 0x%02x", + (unsigned)pin, (unsigned)soc_pad, dev->name, (unsigned)channel, + (unsigned)found->unit, (unsigned)found->input); + return 0; +} + +bool iobroker_adc_release(const struct device *dev, uint8_t channel) { + uint16_t soc_pad; + if (!iobroker_analog_claim_remove(dev, channel, &soc_pad)) { + LOG_DBG("adc release: %s channel %u not allocated", + dev == NULL ? "(null)" : dev->name, (unsigned)channel); + return false; + } + + // The LPADC driver keeps no persistent per-channel configuration: the + // command registers are rewritten by every adc_read() call, so freeing + // the slot needs no device activity. + iobroker_gpio_pad_quiesce(soc_pad); + LOG_INF("adc release: %s channel %u released", dev->name, + (unsigned)channel); + return true; +} + +#endif // IOBROKER_ADC + +#if IOBROKER_DAC + +// Package pad (gpio port index * 32 + pin within the port) bonded to the +// LPDAC outputs (MCXN947 pin functions: DAC0_OUT on P4_02, DAC1_OUT on +// P4_03), as the package map's ball ids (mcxn947_vdf.toml: P4_02 = ball +// T1 = pad 161, P4_03 = ball U1 = pad 175). +#define DAC0_OUTPUT_PAD 161 +#define DAC1_OUTPUT_PAD 175 + +#if DT_NODE_EXISTS(DT_NODELABEL(dac0)) && \ + DT_NODE_HAS_STATUS(DT_NODELABEL(dac0), okay) +#define ANALOG_DAC_DEVICE DEVICE_DT_GET(DT_NODELABEL(dac0)) +#define ANALOG_DAC_OUTPUT_PAD DAC0_OUTPUT_PAD +#elif DT_NODE_EXISTS(DT_NODELABEL(dac1)) && \ + DT_NODE_HAS_STATUS(DT_NODELABEL(dac1), okay) +#define ANALOG_DAC_DEVICE DEVICE_DT_GET(DT_NODELABEL(dac1)) +#define ANALOG_DAC_OUTPUT_PAD DAC1_OUTPUT_PAD +#endif + +#ifdef ANALOG_DAC_DEVICE +int iobroker_dac_allocate(package_pin_t pin, const struct device **dev_out, + uint8_t *channel_out, uint8_t *input_out) { + uint16_t soc_pad; + int ret = iobroker_package_pin_soc_pad(pin, &soc_pad); + if (ret < 0) { + LOG_WRN("dac allocate: package pin %u not in package map", + (unsigned)pin); + return ret; + } + + if (soc_pad != ANALOG_DAC_OUTPUT_PAD) { + LOG_WRN("dac allocate: pad %u is not a DAC output", (unsigned)soc_pad); + return -EINVAL; + } + + const struct device *dev = ANALOG_DAC_DEVICE; + if (dev == NULL || !device_is_ready(dev)) { + LOG_WRN("dac allocate: no ready DAC device"); + return -ENODEV; + } + + // The LPDAC has one output channel. + if (iobroker_analog_channel_in_use(dev, 0)) { + LOG_WRN("dac allocate: %s has no free channel", dev->name); + return -ENOMEM; + } + + ret = iobroker_analog_claim_add(pin, dev, 0); + if (ret < 0) { + return ret; + } + + iobroker_gpio_pad_quiesce(soc_pad); + + *dev_out = dev; + *channel_out = 0; + // The device takes no input selector; the caller ignores this when it + // configures the channel. + *input_out = 0; + LOG_INF("dac allocate: package pin %u (pad %u) -> %s channel 0", + (unsigned)pin, (unsigned)soc_pad, dev->name); + return 0; +} +#else +int iobroker_dac_allocate(package_pin_t pin, const struct device **dev_out, + uint8_t *channel_out, uint8_t *input_out) { + (void)pin; + (void)dev_out; + (void)channel_out; + (void)input_out; + LOG_DBG("dac allocate: no enabled nxp,lpdac instance"); + return -ENOSYS; +} +#endif + +bool iobroker_dac_release(const struct device *dev, uint8_t channel) { + uint16_t soc_pad; + if (!iobroker_analog_claim_remove(dev, channel, &soc_pad)) { + LOG_DBG("dac release: %s channel %u not allocated", + dev == NULL ? "(null)" : dev->name, (unsigned)channel); + return false; + } + + // Zephyr's DAC API has no channel release: the write value stays applied + // until the next channel_setup reconfigures the device. The claim is + // dropped and the pad is quiesced. + iobroker_gpio_pad_quiesce(soc_pad); + LOG_INF("dac release: %s channel %u released", dev->name, + (unsigned)channel); + return true; +} + +#endif // IOBROKER_DAC diff --git a/ports/zephyr-cp/internal-modules/iobroker/src/renesas/ra/iobroker_analog.c b/ports/zephyr-cp/internal-modules/iobroker/src/renesas/ra/iobroker_analog.c new file mode 100644 index 00000000000..ea2e5ffefd3 --- /dev/null +++ b/ports/zephyr-cp/internal-modules/iobroker/src/renesas/ra/iobroker_analog.c @@ -0,0 +1,127 @@ +// Renesas RA DAC pad allocation for the iobroker module. +// +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-License-Identifier: MIT +// +// The DAC output pads are hardwired: each pad bonds at most one DA output and +// there is no runtime routing (unlike the digital peripherals' PSEL). +// Allocate resolves the pad's DA channel from the SoC's pin functions table +// (the datasheet's "Register settings for input/output pin function" tables, +// e.g. RA8M1/RA8D1 table 19.6: AN007/DA0 = P0.14, AN105/DA1 = P0.15), applies +// the analog switch and claims the pad alongside the channel slot. +// +// The analog switch is the PmnPFS.ASEL bit, applied through the datasheet's +// "Notes on Using Analog Functions" sequence: PMR and PDR 0 so the pad acts +// as a general input, then ASEL 1. The Zephyr pinctrl shim writes the whole +// PmnPFS bundle in one go (with the R_BSP_PinAccessEnable protection wrap), +// so a config of only the ASEL bit implements the sequence. +// +// ADC inputs on RA SoCs are not implemented here yet: resolving a pad to the +// FSP adc_channel_t id and the right unit needs the per-SoC AN0xx/AN1xx +// channel numbering checked against a second datasheet source, so +// iobroker_adc_allocate() stays on the core's -ENOSYS stub for RA. + +#include +#include +#include + +#include +#include +#include +#include + +#include + +#include "iobroker_internal.h" + +LOG_MODULE_DECLARE(iobroker, CONFIG_LOG_DEFAULT_LEVEL); + +#if IOBROKER_DAC && !DT_HAS_COMPAT_STATUS_OKAY(renesas_ra_dac) +#error "iobroker: DAC support built but no renesas,ra-dac node is okay" +#endif + +#if defined(CONFIG_SOC_SERIES_RA8M1) || defined(CONFIG_SOC_SERIES_RA8D1) +// DAC12 channel 0 is bonded to P0.14 (AN007/DA0 in table 19.6); channel 1 to +// P0.15 (AN105/DA1). Zephyr's renesas_ra_dac driver only supports channel 0: +// both the write and the setup reject any other channel id, so only P0.14 +// resolves. Add the DAx -> pad mapping from the datasheet for new SoCs. +#define RA_DAC_OUTPUT_PAD 14 +#else +// TODO: add the DAx -> pad mapping from the datasheet for this SoC. +#define RA_DAC_OUTPUT_PAD 0xffff +#endif + +// The pinctrl shim holds struct ra_pinctrl_soc_pin { port_num: 4, pin_num: 4, +// cfg } (see zephyr/soc/renesas/ra/common/pinctrl_soc.h); cfg sets only ASEL, +// which is what the analog sequence asks for. +static void ra_analog_enable(uint16_t soc_pad) { + struct ra_pinctrl_soc_pin cfg = { + .port_num = (soc_pad / 32U), + .pin_num = (soc_pad % 32U), + .cfg = (1u << R_PFS_PORT_PIN_PmnPFS_ASEL_Pos), + }; + + pinctrl_configure_pins(&cfg, 1, PINCTRL_REG_NONE); + LOG_DBG("dac allocate: pad %u (port %u pin %u) analog switch applied", + (unsigned)soc_pad, (unsigned)cfg.port_num, (unsigned)cfg.pin_num); +} + +#if IOBROKER_DAC + +int iobroker_dac_allocate(package_pin_t pin, const struct device **dev_out, + uint8_t *channel_out, uint8_t *input_out) { + uint16_t soc_pad; + int ret = iobroker_package_pin_soc_pad(pin, &soc_pad); + if (ret < 0) { + LOG_WRN("dac allocate: package pin %u not in package map", + (unsigned)pin); + return ret; + } + + if (soc_pad != RA_DAC_OUTPUT_PAD) { + LOG_WRN("dac allocate: pad %u is not a DAC output", (unsigned)soc_pad); + return -EINVAL; + } + + const struct device *dev = DEVICE_DT_GET_ANY(renesas_ra_dac); + if (dev == NULL || !device_is_ready(dev)) { + LOG_WRN("dac allocate: no ready DAC device"); + return -ENODEV; + } + + ret = iobroker_analog_claim_add(pin, dev, 0); + if (ret < 0) { + return ret; + } + + ra_analog_enable(soc_pad); + + *dev_out = dev; + *channel_out = 0; + // The device has no selectable inputs; the caller ignores this when it + // configures the channel. + *input_out = 0; + LOG_INF("dac allocate: package pin %u (pad %u) -> %s channel 0", + (unsigned)pin, (unsigned)soc_pad, dev->name); + return 0; +} + +bool iobroker_dac_release(const struct device *dev, uint8_t channel) { + uint16_t soc_pad; + if (!iobroker_analog_claim_remove(dev, channel, &soc_pad)) { + LOG_DBG("dac release: %s channel %u not allocated", + dev == NULL ? "(null)" : dev->name, (unsigned)channel); + return false; + } + + // Zephyr's DAC API has no channel release, and the renesas_ra_dac driver + // only closes the device from the next channel_setup, so there is no + // channel to unconfigure. The claim is dropped and the pad's analog + // switch stays applied until a later GPIO allocation rewires the pad. + LOG_INF("dac release: %s channel %u released", dev->name, + (unsigned)channel); + return true; +} + +#endif // IOBROKER_DAC diff --git a/ports/zephyr-cp/internal-modules/iobroker/tools/gen_package.py b/ports/zephyr-cp/internal-modules/iobroker/tools/gen_package.py new file mode 100644 index 00000000000..0240cc3601c --- /dev/null +++ b/ports/zephyr-cp/internal-modules/iobroker/tools/gen_package.py @@ -0,0 +1,280 @@ +#!/usr/bin/env python3 +"""Transcribe a package pin assignment table into a iobroker package TOML. + +Input is a `pdftotext -layout` dump of a Nordic SoC datasheet (the module's +datasheets/ directory keeps the PDFs; run pdftotext -layout yourself). The +script locates one "X.Y.Z () package pin assignments" section, +parses its pin table and cross-checks the GPIO pads it finds against the pads +named in the section's pin assignment figure. + +The pin tables are laid out with the pin number vertically centered in its +row, so a pin's GPIO pad name can appear on the line before its number. The +parser therefore assigns every GPIO pad (P.) to the next pin +number at or after it in reading order; sequential pin numbering makes that +unambiguous. Every mapped pin is printed for manual review -- the datasheet +figure remains the source of truth, so diff the output against it. + +Usage (nRF54 datasheets, " () package pin assignments" with +numeric QFN pin numbers or a ball grid): + + gen_package.py DATASHEET.txt --section 10.1.4 --name nrf54l15_qfn48 \ + --socs SOC_NRF54L15,SOC_NRF54L10,SOC_NRF54L05 --pins 48 \ + --source nRF54L15_nRF54L10_nRF54L05_Datasheet_v1.0.pdf \ + --out ../packages/nrf54l15_qfn48.toml + +Ball grids label their pins "A5"-style instead of numbering them; pass the +grid's row letters with --rows (comma-separated when the grid has two-letter +rows, as the aQFN grids do: --rows A,B,...,Y,AA,...,AL) and --cols. + +nRF52/nRF53 product specifications name their sections " pin/ball +assignments" without a package code and lay the table out the same way (the +"Pin" column holds the ball label, there is no Clock column, and the aQFN +tables follow the main table with a "Corner pads" subsection); the same +options transcribe them: + + gen_package.py DATASHEET.txt --section 9.1.1 --name nrf5340_qkaa \ + --socs SOC_NRF5340_CPUAPP --pins 94 \ + --rows A,B,C,D,E,F,G,H,J,K,L,M,N,P,R,T,U,V,W,Y,AA,AB,AC,AD,AE,AF,AG,AH,AJ,AK,AL \ + --cols 31 --source nRF5340_PS_v1.6.pdf --out ../packages/nrf5340_qkaa.toml +""" + +import argparse +import re +import sys +from pathlib import Path + +PAD_RE = re.compile(r"P(\d+)\.(\d+)") +# Section headings: "10.1.4 QFN48 (QFAA) package pin assignments" (nRF54 +# datasheets; title plus package code) or "9.1.1 aQFN94 pin assignments" / +# "7.1.1 aQFN73 ball assignments" (nRF52840/nRF5340 product specifications; no +# package code). The heading must end in the assignments phrase, which keeps +# table-of-contents lines (trailing dot leaders and page numbers) out. +SECTION_RE = re.compile( + r"^\s*(\d+\.\d+\.\d+)\s+(.+?)\s+((?:package\s+)?(?:pin|ball)\s+assignments)$" +) +# Optional "()" at the end of a section title, as in the nRF54 headings. +TITLE_CODE_RE = re.compile(r"^(.*?)\s*\((\S+)\)$") +FIGURE_END_RE = re.compile(r"^\s*Figure \d+:") +# A pin number line: optionally preceded by the "Yes" clock-pin marker, either +# alone or with the row's first name/function entry on the same line. +PIN_LINE_RE = re.compile(r"^\s*(?:Yes\s+)?(\d+)(?:\s+(\S.*))?$") +# A ball name line (aQFN/CSP/BGA packages): row letter(s) + column at column 0. +BALL_LINE_RE = re.compile(r"^([A-Z]+)(\d+)(?:\s+|$)") +TABLE_HEADER_RE = re.compile(r"^\s*Pin\s+(?:Clock\s+)?Name\s+Function\s+Description") +# The pin table ends at its "Table N:" caption, or -- for aQFN packages, +# which list their corner pads right after the main table -- at the +# "Corner pads" heading. Neither belongs to the table. +TABLE_END_RE = re.compile(r"^\s*(?:Table\s+\d+:|Corner pads\b)") + + +def find_section(lines, section): + """Return (title, code, kind, section lines) for a numbered heading. + + code is the package code in the nRF54 "QFN48 (QFAA)" headings, or None + when the heading carries none ("aQFN94 pin assignments"). kind is the + heading's "package pin assignments"/"pin assignments"/"ball assignments" + phrase, used in the output header comment. + """ + starts = [(i, SECTION_RE.match(line)) for i, line in enumerate(lines)] + starts = [(i, m) for i, m in starts if m] + for index, (i, m) in enumerate(starts): + if m.group(1) == section: + end = starts[index + 1][0] if index + 1 < len(starts) else len(lines) + title, code = m.group(2), None + code_match = TITLE_CODE_RE.match(title) + if code_match: + title, code = code_match.group(1), code_match.group(2) + return title, code, m.group(3), lines[i + 1 : end] + raise SystemExit(f"section {section!r} not found") + + +def parse_table(section_lines, rows=None, cols=10): + """Return ({pin_id: [(port, pin), ...]}, ordered pin ids) from the table. + + Numeric packages (QFN) use 1-based pin numbers validated against + sequential numbering. Ball packages pass the grid's row letters (a list, + since aQFN grids have two-letter rows); pins are (row, column) pairs, + ordered row-major. + """ + header = next((i for i, line in enumerate(section_lines) if TABLE_HEADER_RE.match(line)), None) + if header is None: + raise SystemExit("pin table header ('Pin Clock Name Function ...') not found") + body = section_lines[header + 1 :] + # The table ends at its caption line or at the "Corner pads" subsection + # some packages list after it; neither is part of the table. + end = next((i for i, line in enumerate(body) if TABLE_END_RE.match(line)), None) + if end is not None: + body = body[:end] + + # Pass 1: pin lines. Numeric mode validates against sequential numbering + # so page numbers and stray digits cannot be mistaken for pins; ball mode + # validates against the grid instead. + number_lines = [] + if rows: + valid = {(row, column) for row in rows for column in range(1, cols + 1)} + for i, line in enumerate(body): + m = BALL_LINE_RE.match(line) + if m and (m.group(1), int(m.group(2))) in valid: + ball = (m.group(1), int(m.group(2))) + if ball in (b for _, b in number_lines): + raise SystemExit(f"duplicate ball {ball[0]}{ball[1]}") + number_lines.append((i, ball)) + else: + for i, line in enumerate(body): + m = PIN_LINE_RE.match(line) + if m and int(m.group(1)) == len(number_lines) + 1: + number_lines.append((i, int(m.group(1)))) + if not number_lines: + raise SystemExit("no pin numbers found; table layout mismatch?") + + # Pass 2: assign each GPIO pad to the next pin at or after it. The pin + # number is vertically centered in its table row, so the row's GPIO pad + # name can sit on the line before the number. + pins = {pin: [] for _, pin in number_lines} + for i, line in enumerate(body): + for m in PAD_RE.finditer(line): + owner = next((pin for j, pin in number_lines if j >= i), None) + if owner is None: + raise SystemExit(f"GPIO pad {m.group(0)!r} after the last pin") + pins[owner].append((int(m.group(1)), int(m.group(2)))) + order = [pin for _, pin in number_lines] + return pins, order + + +def parse_figure(section_lines): + """GPIO pads named anywhere in the section's pin assignment figure.""" + pads = set() + for line in section_lines: + if FIGURE_END_RE.match(line): + break + pads.update(PAD_RE.finditer(line)) + return {(int(m.group(1)), int(m.group(2))) for m in pads} + + +def main(): + parser = argparse.ArgumentParser( + description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter + ) + parser.add_argument("datasheet", type=Path, help="pdftotext -layout dump") + parser.add_argument("--section", required=True, help="e.g. 10.1.4") + parser.add_argument("--name", required=True, help="package map name, e.g. nrf54l15_qfn48") + parser.add_argument( + "--socs", required=True, help="comma-separated Kconfig SoC symbols the map applies to" + ) + parser.add_argument( + "--pins", type=int, required=True, help="expected number of package pins (or balls)" + ) + parser.add_argument( + "--rows", + help="ball row letters, e.g. ABCDEFGHJK (comma-separated A,B,...,AA " + "when the grid has two-letter rows), for ball grid packages; " + "pins are numbered sequentially in row-major order", + ) + parser.add_argument("--cols", type=int, default=10, help="ball grid columns (with --rows)") + parser.add_argument( + "--die-pad", + action="store_true", + help="the table lists the exposed die pad as one pin past --pins; " + "it is bonded to VSS and never routable", + ) + parser.add_argument( + "--source", required=True, help="datasheet file name for the header comment" + ) + parser.add_argument("--out", type=Path, required=True, help="output TOML path") + args = parser.parse_args() + + # Ball row letters: comma-separated when the grid has two-letter rows. + rows = None + if args.rows: + rows = args.rows.split(",") if "," in args.rows else list(args.rows) + + lines = args.datasheet.read_text().splitlines() + title, code, kind, section_lines = find_section(lines, args.section) + + pins, order = parse_table(section_lines, rows=rows, cols=args.cols) + expected_max = args.pins + (1 if args.die_pad else 0) + if len(order) != expected_max: + raise SystemExit(f"parsed {len(order)} pins, expected {expected_max}") + if args.die_pad: + die_pad = order[-1] + if pins[die_pad]: + raise SystemExit(f"die pad {die_pad} unexpectedly bonded to GPIO {pins[die_pad]}") + del pins[die_pad] + order = order[:-1] + if not args.rows: + missing = [n for n in range(1, args.pins + 1) if n not in pins] + if missing: + raise SystemExit(f"pin numbers not found: {missing}") + + # Every pin must bond at most one GPIO pad, and the set of bonded pads + # must match the pads the figure shows for this package. + multi = {n: p for n, p in pins.items() if len(p) > 1} + if multi: + raise SystemExit(f"pins with more than one GPIO pad: {multi}") + table_pads = {p[0] for p in pins.values() if p} + figure_pads = parse_figure(section_lines) + if not figure_pads: + # CSP/BGA figures are unlabeled ball grids; there is nothing to + # cross-check against. The pad-count sanity check below still applies. + print("note: figure names no GPIO pads; skipping table/figure cross-check") + elif table_pads != figure_pads: + raise SystemExit( + "pad mismatch table vs figure:\n" + f" only in table: {sorted(table_pads - figure_pads)}\n" + f" only in figure: {sorted(figure_pads - table_pads)}" + ) + + skipped = [pin for pin in order if not pins[pin]] + + def pin_label(pin): + return f"{pin[0]}{pin[1]}" if isinstance(pin, tuple) else str(pin) + + header_notes = [] + if args.rows: + header_notes += [ + "# Ball packages: 'pin' numbers the balls sequentially in row-major", + "# order (the datasheet only labels them, e.g. B2).", + "", + ] + out_lines = [ + f"# Package pin map for {args.name}, transcribed from {args.source},", + f"# section {args.section} ({title}{f', {code}' if code else ''} {kind}),", + "# by tools/gen_package.py. Review against the datasheet figure before", + "# editing by hand; regenerate instead when the datasheet changes.", + "", + *header_notes, + f'name = "{args.name}"', + f"socs = [{', '.join(f'"{s}"' for s in args.socs.split(','))}]", + "", + ] + for number, pin in enumerate(order, start=1): + pad = pins[pin][0] if pins[pin] else None + if not pad: + continue + soc_pad = pad[0] * 32 + pad[1] + out_lines.append("[[pins]]") + out_lines.append(f"pin = {number}") + if isinstance(pin, tuple): + out_lines.append(f'ball = "{pin[0]}{pin[1]}"') + out_lines.append(f"pad = {soc_pad}") + out_lines.append(f'pad_name = "P{pad[0]}.{pad[1]:02d}"') + out_lines.append("") + if skipped: + out_lines.append("# Package pins without a GPIO pad (not routable):") + out_lines.append("# " + ", ".join(pin_label(pin) for pin in skipped)) + out_lines.append("") + + args.out.write_text("\n".join(out_lines)) + + print( + f"{args.out}: {sum(1 for p in pins.values() if p)} GPIO pads " + f"on {len(order)} package pins, {len(skipped)} skipped" + ) + for number, pin in enumerate(order, start=1): + pad = pins[pin][0] if pins[pin] else None + if pad: + print(f" pin {pin_label(pin):>4} -> P{pad[0]}.{pad[1]:02d}") + + +if __name__ == "__main__": + main() diff --git a/ports/zephyr-cp/internal-modules/iobroker/tools/gen_package_c.py b/ports/zephyr-cp/internal-modules/iobroker/tools/gen_package_c.py new file mode 100644 index 00000000000..a67d0b32d36 --- /dev/null +++ b/ports/zephyr-cp/internal-modules/iobroker/tools/gen_package_c.py @@ -0,0 +1,60 @@ +#!/usr/bin/env python3 +"""Render a iobroker package TOML as the C pin map translation unit. + +Run at build time by the module's CMakeLists.txt for the package selected via +CONFIG_IOBROKER_PACKAGE_*; the output lands in the build directory, so +nothing generated is committed. The declarations live in iobroker.h. + +Usage: + gen_package_c.py packages/nrf54l15_qfn48.toml package_pins.c +""" + +import sys +import tomllib +from pathlib import Path + + +def main(): + if len(sys.argv) != 3: + raise SystemExit(__doc__) + toml_path, out_path = Path(sys.argv[1]), Path(sys.argv[2]) + with toml_path.open("rb") as f: + data = tomllib.load(f) + + lines = [ + f"// Generated from {toml_path.name} by tools/gen_package_c.py -- do not edit.", + f"// Package pin map '{data['name']}' for {', '.join(data['socs'])}.", + "", + "#include ", + "#include ", + "", + "#include ", + "", + "const iobroker_package_pin_t iobroker_package_pins[] = {", + ] + for entry in data["pins"]: + if "pad_name" not in entry and "pad" not in entry: + # Informational module pins (e.g. a castellation bonded to GND): + # they carry no SoC pad, so they map nothing. + continue + # The SoC pad is the pad id the package numbers its pins by (row + # -major over the ball grid, or the datasheet's pin number); module + # packages remap it per entry and SoC packages default to the pin. + pad = entry.get("pad", entry["pin"]) + # The pad's GPIO attachment, or IOBROKER_PAD_NO_GPIO for analog-only + # pads. + gpio = entry.get("gpio", 0xFFFF) + ball = f" ({entry['ball']})" if "ball" in entry else "" + pad_name = f" {entry['pad_name']}" if "pad_name" in entry else "" + comment = f" //{ball}{pad_name}" + lines.append(f" {{ PACKAGE_PIN({entry['pin']}), {pad}, {gpio} }},{comment}") + lines += [ + "};", + f"const size_t iobroker_package_pin_count = {len(data['pins'])};", + "", + ] + out_path.write_text("\n".join(lines)) + + +if __name__ == "__main__": + main() diff --git a/ports/zephyr-cp/internal-modules/iobroker/zephyr/module.yml b/ports/zephyr-cp/internal-modules/iobroker/zephyr/module.yml new file mode 100644 index 00000000000..6d5d548c16e --- /dev/null +++ b/ports/zephyr-cp/internal-modules/iobroker/zephyr/module.yml @@ -0,0 +1,10 @@ +# Zephyr module descriptor for the iobroker module. +# +# The module is loaded from the CircuitPython tree via ZEPHYR_EXTRA_MODULES in +# ports/zephyr-cp/CMakeLists.txt. To externalize it, move this directory into +# its own repository and either point ZEPHYR_EXTRA_MODULES at the new checkout +# or add it to the west manifest instead. +name: iobroker +build: + cmake: . + kconfig: Kconfig diff --git a/ports/zephyr-cp/internal-modules/neopixel/CMakeLists.txt b/ports/zephyr-cp/internal-modules/neopixel/CMakeLists.txt new file mode 100644 index 00000000000..72eb589a689 --- /dev/null +++ b/ports/zephyr-cp/internal-modules/neopixel/CMakeLists.txt @@ -0,0 +1,21 @@ +# neopixel Zephyr module build. +# +# The core is always compiled so that callers can include +# and call the module on every SoC. SoC-specific +# transmit implementations are added under src///; without one +# the send function reports -ENOSYS. + +zephyr_library() +# SoC-agnostic core: -ENOSYS stubs when no SoC implementation is built. +zephyr_library_sources(src/neopixel.c) + +# SoC implementations live in src///. The nRF implementation +# covers every nRF SoC with a PWM peripheral, so the level is the nRF +# family. Other vendors add their own directories and a corresponding +# zephyr_library_sources_ifdef() line here. +zephyr_library_sources_ifdef(CONFIG_SOC_FAMILY_NORDIC_NRF + src/nordic/nrf/neopixel_nrf.c +) + +# Public header. +zephyr_include_directories(include) diff --git a/ports/zephyr-cp/internal-modules/neopixel/Kconfig b/ports/zephyr-cp/internal-modules/neopixel/Kconfig new file mode 100644 index 00000000000..953f7e4662f --- /dev/null +++ b/ports/zephyr-cp/internal-modules/neopixel/Kconfig @@ -0,0 +1,15 @@ +# neopixel: NeoPixel (WS2812-style) LED strip transmit on a runtime-chosen +# pin. +# +# The module's core is always compiled (see CMakeLists.txt); callers call it +# directly. Transmitting needs SoC support: today it is implemented for nRF +# SoCs, using a PWM instance's DMA sequence playback with a bit-bang +# fallback. On other SoCs neopixel_send() reports -ENOSYS. + +config NEOPIXEL + bool "NeoPixel (WS2812-style) transmit" + default y + help + Transmit NeoPixel (WS2812-style) LED data on a pin chosen at runtime, + allocating a peripheral instance from the iobroker module for each + transfer. diff --git a/ports/zephyr-cp/internal-modules/neopixel/README.md b/ports/zephyr-cp/internal-modules/neopixel/README.md new file mode 100644 index 00000000000..6b2b8305b5c --- /dev/null +++ b/ports/zephyr-cp/internal-modules/neopixel/README.md @@ -0,0 +1,51 @@ +# neopixel + +A Zephyr module that transmits NeoPixel (WS2812-style) LED data on a pin +chosen at runtime. Callers hand it pixel bytes in the strip's byte order and +a package pin, which they must not hold claimed during the call; the SoC +implementation picks the transmit hardware per call and allocates it, with +the pin, from the [iobroker](../iobroker/README.md) module for the duration +of the transfer. On nRF that is a PWM instance's DMA sequence playback, with +a bit-bang fallback when every instance is busy or none can +reach the pin (nRF54L PWMs drive only their own power domain's pads), +except where the CPU's GPIO access is too slow to bit-bang (nRF54L P0, whose +pins raise `ValueError`). + +## Status + +Implemented for nRF SoCs. On other SoCs the module compiles but +`neopixel_send()` returns `-ENOSYS`. + +## Source layout + +``` +include/neopixel/neopixel.h # public API +src/ + neopixel.c # -ENOSYS stubs when no SoC implementation + nordic/ + nrf/ + neopixel_nrf.c # PWM sequence playback + bit-bang fallback +``` + +Each vendor adds a `src///` directory with an implementation of +`neopixel_send()`, its `NEOPIXEL_PATTERN_BUFFER_SIZE()` formula in the public +header, a corresponding `zephyr_library_sources_ifdef()` line in +`CMakeLists.txt`, and its SoC condition in the `#if` that guards the stub in +`src/neopixel.c`. + +## Enabling + +The module is registered by the CircuitPython Zephyr application +(`ports/zephyr-cp/CMakeLists.txt`) via `ZEPHYR_EXTRA_MODULES`, so it works +without west manifest changes. It depends on the iobroker module for +peripheral allocation and package pin resolution. + +## Public API + +See `include/neopixel/neopixel.h`. `NEOPIXEL_PATTERN_BUFFER_SIZE()` tells the +caller how large a pattern buffer (the waveform built from the pixel bytes) a +transfer of a given length needs, as a constant expression, so the caller +decides where that memory lives; `neopixel_send()` transmits. The caller +configures the pin as an output driving low before the call and paces +successive calls so that the strip's reset (latch) period elapses between +them. diff --git a/ports/zephyr-cp/internal-modules/neopixel/include/neopixel/neopixel.h b/ports/zephyr-cp/internal-modules/neopixel/include/neopixel/neopixel.h new file mode 100644 index 00000000000..ee76b6094e8 --- /dev/null +++ b/ports/zephyr-cp/internal-modules/neopixel/include/neopixel/neopixel.h @@ -0,0 +1,52 @@ +// neopixel: NeoPixel (WS2812-style) LED strip transmit on a runtime-chosen pin. +// +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +// Send a buffer of pixel bytes, already in the byte order the strip expects +// (GRB or GRBW), as a NeoPixel waveform on a package pin. The SoC +// implementation chooses the transmit hardware per call and allocates it, +// with the pin, from the iobroker module for the frame: on nRF a PWM +// instance routed to the pin, with a bit-bang fallback on the pin as a GPIO +// when every instance is busy or none can reach the pin (nRF54L PWMs drive +// only their own power domain's pads), except where the CPU's GPIO access is +// too slow to bit-bang (nRF54L P0). The pin must not be claimed in iobroker +// during the call; a caller that holds it as a GPIO releases it first and +// drives it low again afterwards, so that the strip latches the data when +// the line stays low, which the caller paces. + +#pragma once + +#include +#include + +#include + +// Bytes of pattern buffer the SoC implementation needs to send num_bytes of +// pixel data: the waveform it builds from the pixel bytes for its transmit +// hardware. The caller provides the buffer to neopixel_send(), 4-byte +// aligned, so that it decides where the memory lives (stack for small +// strips, heap for long ones). A constant expression, so that a caller can +// size a static or stack buffer with it. +#if defined(CONFIG_SOC_FAMILY_NORDIC_NRF) +// nRF PWM sequence: one 16-bit entry per bit plus two end-of-sequence entries. +#define NEOPIXEL_PATTERN_BUFFER_SIZE(num_bytes) \ + ((num_bytes) * 8 * sizeof(uint16_t) + 2 * sizeof(uint16_t)) +#else +// No transmit implementation: nothing to build. +#define NEOPIXEL_PATTERN_BUFFER_SIZE(num_bytes) ((size_t)0) +#endif + +// Send num_bytes of pixel data on the package pin. pattern_buffer must hold +// at least NEOPIXEL_PATTERN_BUFFER_SIZE(num_bytes) bytes. Returns 0, or a +// negative errno: +// -ENOSYS: no transmit implementation for this SoC +// -EINVAL: the pin is not in the package pin map, no transmit hardware +// can drive it (on nRF: an nRF54L P0 pad), or the pattern buffer +// is too small or misaligned +// other negative values: the transfer could not be completed +int neopixel_send(package_pin_t pin, const uint8_t *pixels, size_t num_bytes, + void *pattern_buffer, size_t pattern_buffer_size); diff --git a/ports/zephyr-cp/internal-modules/neopixel/src/neopixel.c b/ports/zephyr-cp/internal-modules/neopixel/src/neopixel.c new file mode 100644 index 00000000000..0472e58c0bb --- /dev/null +++ b/ports/zephyr-cp/internal-modules/neopixel/src/neopixel.c @@ -0,0 +1,28 @@ +// neopixel: SoC-agnostic core. +// +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +// The transmit functions are SoC-specific and live in src///; +// the -ENOSYS stubs below stand in for SoCs with no implementation. + +#include + +#include + +#if !defined(CONFIG_SOC_FAMILY_NORDIC_NRF) + +int neopixel_send(package_pin_t pin, const uint8_t *pixels, size_t num_bytes, + void *pattern_buffer, size_t pattern_buffer_size) { + (void)pin; + (void)pixels; + (void)num_bytes; + (void)pattern_buffer; + (void)pattern_buffer_size; + return -ENOSYS; +} + +#endif // !CONFIG_SOC_FAMILY_NORDIC_NRF diff --git a/ports/zephyr-cp/internal-modules/neopixel/src/nordic/nrf/neopixel_nrf.c b/ports/zephyr-cp/internal-modules/neopixel/src/nordic/nrf/neopixel_nrf.c new file mode 100644 index 00000000000..9610ac0c050 --- /dev/null +++ b/ports/zephyr-cp/internal-modules/neopixel/src/nordic/nrf/neopixel_nrf.c @@ -0,0 +1,273 @@ +// neopixel: nRF transmit. +// +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +// / = nordic/nrf: play the NeoPixel waveform with a PWM +// instance's EasyDMA sequence, one 16-bit entry per data bit setting that +// bit's high time, as CircuitPython's ports/nordic does. The PWM instance is +// allocated from iobroker, routed to the pin, for the duration of each +// transfer: initializing the Zephyr device applies its pinctrl state, which +// connects OUT0 to the pin, and releasing it de-initializes the device again. +// The waveform itself is programmed through the HAL, since Zephyr's PWM API +// has no sequence playback. When every instance is busy, or none can reach +// the pin, the pin is allocated from iobroker as a GPIO and the waveform is +// bit-banged on it instead, except on nRF54L P0, whose GPIO is too slow for +// it. + +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +LOG_MODULE_REGISTER(neopixel, CONFIG_LOG_DEFAULT_LEVEL); + +// PWM counter runs at 16 MHz with a period of 20 counts (1.25 us per bit). +// Entries of the waveform sequence carry the polarity bit (0x8000) so the +// output idles low. +// WS2812 (rev A) timing, 0.35/0.7 us, works with everything tried so far, +// including the timing-sensitive https://adafru.it/5225. +#define MAGIC_T0H (5UL | 0x8000) // 0.3125 us high +#define MAGIC_T1H (12UL | 0x8000) // 0.75 us high +#define CTOPVAL 20UL // 1.25 us period + +// PWM instances enabled in the devicetree, with their register blocks. The +// iobroker hands out the Zephyr device; the HAL uses the registers. Zephyr +// has no public way to get a device's register address, but the devicetree +// knows it. +typedef struct { + const struct device *dev; + NRF_PWM_Type *regs; +} pwm_regs_t; + +#define PWM_REGS_ENTRY(node_id) \ + { .dev = DEVICE_DT_GET(node_id), .regs = (NRF_PWM_Type *)DT_REG_ADDR(node_id) }, + +static const pwm_regs_t pwm_regs[] = { + DT_FOREACH_STATUS_OKAY(nordic_nrf_pwm, PWM_REGS_ENTRY) +}; + +static NRF_PWM_Type *pwm_regs_for(const struct device *dev) { + for (size_t i = 0; i < ARRAY_SIZE(pwm_regs); i++) { + if (pwm_regs[i].dev == dev) { + return pwm_regs[i].regs; + } + } + return NULL; +} + +// Fallback when no PWM instance is free or none can reach the pin: bit-bang the waveform with +// interrupts locked, timed by the DWT cycle counter. The cycle counts are +// ports/nordic's 64 MHz values (71 per bit, 18 high for a zero, 41 high for +// a one) expressed as dividers of SystemCoreClock: a 1.11 us bit interval, +// 0.28 us and 0.64 us high, which the loop's own overhead stretches by a few +// cycles each. +// +// The Bluetooth controller's radio interrupts are zero-latency +// (CONFIG_ZERO_LATENCY_IRQS) so they still preempt the locked section. A +// preempted bit runs long and may have latched garbage, so, in the spirit of +// ports/nordic's resend after SoftDevice preemption, every bit period is +// checked and the frame is resent after the strip's reset period when any +// bit ran more than twice its nominal length. The check is per bit rather +// than per frame because a few tens of microseconds of interrupt is a small +// fraction of a long frame but a whole latch period for the strip. +// +// This is the vendor-specific register poking that Zephyr's proposed fast +// GPIO API (https://github.com/zephyrproject-rtos/zephyr/issues/106831) +// would replace; switch to that API once it lands. +#define BITBANG_MAX_ATTEMPTS 8 + +static int bitbang_send(NRF_GPIO_Type *port, uint32_t mask, const uint8_t *pixels, + size_t num_bytes) { + uint32_t interval = SystemCoreClock / 900000; + uint32_t t0 = SystemCoreClock / 3500000; + uint32_t t1 = SystemCoreClock / 1560000; + uint32_t limit = interval * 2; + + CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk; + DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk; + + for (int attempt = 0; attempt < BITBANG_MAX_ATTEMPTS; attempt++) { + bool preempted = false; + unsigned int key = irq_lock(); + for (size_t n = 0; n < num_bytes; n++) { + uint8_t pix = pixels[n]; + for (uint8_t bit_mask = 0x80; bit_mask > 0; bit_mask >>= 1) { + uint32_t high = (pix & bit_mask) ? t1 : t0; + uint32_t start = DWT->CYCCNT; + port->OUTSET = mask; + while (DWT->CYCCNT - start < high) { + } + port->OUTCLR = mask; + while (DWT->CYCCNT - start < interval) { + } + if (DWT->CYCCNT - start > limit) { + preempted = true; + } + } + } + irq_unlock(key); + if (!preempted) { + return 0; + } + // Let the strip latch whatever it got, then send the whole frame again. + k_busy_wait(300); + } + LOG_WRN("bit-bang frame preempted %d times; giving up", BITBANG_MAX_ATTEMPTS); + return -EIO; +} + +static int pwm_send(NRF_PWM_Type *pwm, const uint8_t *pixels, size_t num_bytes, + uint16_t *sequence) { + size_t pos = 0; + for (size_t n = 0; n < num_bytes; n++) { + uint8_t pix = pixels[n]; + for (uint8_t mask = 0x80; mask > 0; mask >>= 1) { + sequence[pos++] = (pix & mask) ? MAGIC_T1H : MAGIC_T0H; + } + } + // Two zero-width entries end the waveform sequence with the line low. + sequence[pos++] = 0 | 0x8000; + sequence[pos++] = 0 | 0x8000; + + nrf_pwm_configure(pwm, NRF_PWM_CLK_16MHz, NRF_PWM_MODE_UP, CTOPVAL); + nrf_pwm_loop_set(pwm, 0); + nrf_pwm_decoder_set(pwm, NRF_PWM_LOAD_COMMON, NRF_PWM_STEP_AUTO); + nrf_pwm_seq_ptr_set(pwm, 0, sequence); + nrf_pwm_seq_cnt_set(pwm, 0, pos); + nrf_pwm_seq_refresh_set(pwm, 0, 0); + nrf_pwm_seq_end_delay_set(pwm, 0, 0); + + // OUT0's PSEL was set from the instance's pinctrl state by device_init(). + nrf_pwm_enable(pwm); + + nrf_pwm_event_clear(pwm, NRF_PWM_EVENT_SEQEND0); + nrf_pwm_task_trigger(pwm, NRF_PWM_TASK_SEQSTART0); + while (!nrf_pwm_event_check(pwm, NRF_PWM_EVENT_SEQEND0)) { + k_yield(); + } + nrf_pwm_event_clear(pwm, NRF_PWM_EVENT_SEQEND0); + + nrf_pwm_disable(pwm); + return 0; +} + +// Register block of a GPIO controller, from iobroker's controller table. +// Zephyr's GPIO API is too slow to bit-bang with: a gpio_port_set_bits_raw() +// call takes about 31 cycles on the nRF52840 at 64 MHz, more than a zero +// bit's 18-cycle high time, where a register write takes about 3. +static NRF_GPIO_Type *gpio_regs_for(const struct device *port) { + for (size_t i = 0; i < iobroker_gpio_port_count; i++) { + if (iobroker_gpio_port_devices[i] == port) { + return (NRF_GPIO_Type *)iobroker_gpio_port_addrs[i]; + } + } + return NULL; +} + +// Whether the CPU can bit-bang the waveform on a GPIO port. On nRF54L the P0 +// port sits in the low-power (LP) domain, which runs at 16 MHz asynchronously +// to the CPU: a register write to it stalls about 0.5 us (65 cycles at +// 128 MHz, measured on the nRF54LM20A), longer than a zero bit's 0.3 us high +// time, so every bit would read as a one. P1-P3 (PERI and MCU domains) take +// 7 to 26 cycles. The domain is in bits 18-20 of the register address, the +// same decoding as nrfx_gppi_domain_id_get(); LP is 3. +#define NRF54L_DOMAIN_LP 3 + +static bool port_can_bitbang(NRF_GPIO_Type *port) { + #if defined(CONFIG_SOC_SERIES_NRF54L) + return (((uintptr_t)port >> 18) & 0x7) - 1 != NRF54L_DOMAIN_LP; + #else + (void)port; + return true; + #endif +} + +// Send on an allocated PWM instance: initializing the device connects OUT0 to +// the pin through its pinctrl state, driven low until the sequence starts. +static int pwm_send_on(const struct device *dev, const uint8_t *pixels, size_t num_bytes, + uint16_t *sequence) { + NRF_PWM_Type *pwm = pwm_regs_for(dev); + if (pwm == NULL) { + LOG_WRN("%s has no register entry", dev->name); + return -ENODEV; + } + int ret = device_init(dev); + if (ret < 0) { + LOG_WRN("%s: device_init failed: %d", dev->name, ret); + return ret; + } + return pwm_send(pwm, pixels, num_bytes, sequence); +} + +// Bit-bang on the pin as a GPIO output, allocated from iobroker for the frame. +// A pin whose port is too slow to bit-bang on gets -EINVAL. +static int bitbang_send_on(package_pin_t pin, const uint8_t *pixels, size_t num_bytes) { + const struct device *port; + gpio_pin_t number; + int ret = iobroker_gpio_allocate(pin, &port, &number); + if (ret < 0) { + return ret; + } + NRF_GPIO_Type *regs = gpio_regs_for(port); + if (regs == NULL) { + LOG_WRN("%s has no register entry", port->name); + ret = -ENODEV; + } else if (!port_can_bitbang(regs)) { + ret = -EINVAL; + } else { + ret = gpio_pin_configure(port, number, GPIO_OUTPUT_LOW); + if (ret == 0) { + ret = bitbang_send(regs, BIT(number), pixels, num_bytes); + } + } + (void)iobroker_gpio_release(port, number); + return ret; +} + +int neopixel_send(package_pin_t pin, const uint8_t *pixels, size_t num_bytes, + void *pattern_buffer, size_t pattern_buffer_size) { + if (pattern_buffer_size < NEOPIXEL_PATTERN_BUFFER_SIZE(num_bytes) || + ((uintptr_t)pattern_buffer & 3) != 0) { + return -EINVAL; + } + + // An exclusive channel gets a group of its own, which on nRF is a whole + // PWM instance: the sequence drives all of the instance's outputs + // (NRF_PWM_LOAD_COMMON), and only this pin's output is connected. The + // frequency, the 800 kHz bit rate, only matters for sharing, which an + // exclusive channel never does. + const struct device *dev = NULL; + uint32_t channel; + int ret = iobroker_pwm_channel_allocate(pin, 800000, true, &dev, &channel); + if (ret == 0) { + ret = pwm_send_on(dev, pixels, num_bytes, pattern_buffer); + (void)iobroker_pwm_channel_release(dev, channel); + return ret; + } + if (ret == -ENODEV || ret == -EINVAL) { + // Every instance is busy (pwmio or something else is holding them all), + // or none can reach this pin (nRF54L PWMs drive only their own power + // domain's pads): bit-bang instead. That locks ordinary interrupts for + // the frame; the zero-latency radio interrupt can still preempt it and + // glitch the output, which bitbang_send() detects and resends. A pin + // with no GPIO, or on a port too slow to bit-bang, gets -EINVAL. + return bitbang_send_on(pin, pixels, num_bytes); + } + return ret; +} diff --git a/ports/zephyr-cp/internal-modules/neopixel/zephyr/module.yml b/ports/zephyr-cp/internal-modules/neopixel/zephyr/module.yml new file mode 100644 index 00000000000..613491d17e2 --- /dev/null +++ b/ports/zephyr-cp/internal-modules/neopixel/zephyr/module.yml @@ -0,0 +1,10 @@ +# Zephyr module descriptor for the neopixel module. +# +# The module is loaded from the CircuitPython tree via ZEPHYR_EXTRA_MODULES in +# ports/zephyr-cp/CMakeLists.txt. To externalize it, move this directory into +# its own repository and either point ZEPHYR_EXTRA_MODULES at the new checkout +# or add it to the west manifest instead. +name: neopixel +build: + cmake: . + kconfig: Kconfig diff --git a/ports/zephyr-cp/internal-modules/pwm_emul/CMakeLists.txt b/ports/zephyr-cp/internal-modules/pwm_emul/CMakeLists.txt new file mode 100644 index 00000000000..b82aa8005d0 --- /dev/null +++ b/ports/zephyr-cp/internal-modules/pwm_emul/CMakeLists.txt @@ -0,0 +1,7 @@ +# pwm_emul Zephyr module build: the emulated PWM driver, built when the +# devicetree enables an adafruit,pwm-emul node (native_sim). + +if(CONFIG_PWM_ADAFRUIT_EMUL) + zephyr_library() + zephyr_library_sources(src/pwm_emul.c) +endif() diff --git a/ports/zephyr-cp/internal-modules/pwm_emul/Kconfig b/ports/zephyr-cp/internal-modules/pwm_emul/Kconfig new file mode 100644 index 00000000000..3fcf9e01c74 --- /dev/null +++ b/ports/zephyr-cp/internal-modules/pwm_emul/Kconfig @@ -0,0 +1,12 @@ +# pwm_emul: emulated PWM controller for native_sim tests. + +config PWM_ADAFRUIT_EMUL + bool "Emulated PWM controller" + default y + depends on DT_HAS_ADAFRUIT_PWM_EMUL_ENABLED + depends on PWM + help + Emulated PWM controller (adafruit,pwm-emul) for native_sim tests. It + produces no output; it records the period and pulse each channel is + set to and, with Perfetto tracing, emits them as counter tracks. + Channel N stands for GPIO N. diff --git a/ports/zephyr-cp/internal-modules/pwm_emul/dts/bindings/pwm/adafruit,pwm-emul.yaml b/ports/zephyr-cp/internal-modules/pwm_emul/dts/bindings/pwm/adafruit,pwm-emul.yaml new file mode 100644 index 00000000000..dcaa878600d --- /dev/null +++ b/ports/zephyr-cp/internal-modules/pwm_emul/dts/bindings/pwm/adafruit,pwm-emul.yaml @@ -0,0 +1,43 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 Dan Halbert for Adafruit Industries LLC +# SPDX-License-Identifier: MIT + +description: | + Emulated PWM controller for native_sim tests. It produces no output: it + records the period and pulse each channel is set to, and with Perfetto + tracing emits them on the counter tracks "pwm.NN.period" and + "pwm.NN.pulse". Channel N stands for GPIO N. Only one controller is + supported. + + Channels that share a period form a group. Any channel can join any + group, and a group has no channel limit; the number of groups is set by + the groups property. The driver itself only records settings: CircuitPython's + iobroker module hands out the groups. + +compatible: "adafruit,pwm-emul" + +include: [pwm-controller.yaml, base.yaml] + +properties: + channels: + required: true + + clock-frequency: + type: int + required: true + description: | + Frequency in Hz that pwm_get_cycles_per_sec() reports; periods and + pulses are counted in cycles of this clock. + + groups: + type: int + required: true + description: | + Number of period groups (sets of channels sharing a period) available. + + "#pwm-cells": + const: 3 + +pwm-cells: + - channel + - period + - flags diff --git a/ports/zephyr-cp/internal-modules/pwm_emul/src/pwm_emul.c b/ports/zephyr-cp/internal-modules/pwm_emul/src/pwm_emul.c new file mode 100644 index 00000000000..6dd982d7d73 --- /dev/null +++ b/ports/zephyr-cp/internal-modules/pwm_emul/src/pwm_emul.c @@ -0,0 +1,129 @@ +// pwm_emul: emulated PWM controller for native_sim tests. +// +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Dan Halbert for Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +// The emulated controller (adafruit,pwm-emul) implements Zephyr's PWM API +// but produces no output. Its channels are independent, each with its own +// period, and channel N stands for GPIO N. set_cycles() records the period +// and pulse and, with Perfetto tracing, emits them on the counter tracks +// "pwm.NN.period" and "pwm.NN.pulse" (matching the "gpio_emul.NN" tracks). + +#include +#include +#include +#include + +#include +#include +#include +#include + +#if defined(CONFIG_TRACING_PERFETTO) +#include "perfetto_encoder.h" +#endif + +#define DT_DRV_COMPAT adafruit_pwm_emul + +// Channel numbers are GPIO numbers, so one controller covers every pin and +// the track names need no controller prefix. +BUILD_ASSERT(DT_NUM_INST_STATUS_OKAY(DT_DRV_COMPAT) <= 1, + "only one adafruit,pwm-emul controller is supported"); + +struct pwm_emul_channel { + uint32_t period_cycles; + uint32_t pulse_cycles; + // Whether this channel's tracks have been described. + bool described; +}; + +struct pwm_emul_config { + uint32_t clock_frequency; + struct pwm_emul_channel *channels; + uint32_t channel_count; +}; + +#if defined(CONFIG_TRACING_PERFETTO) + +// Track UUIDs, clear of the ranges the Zephyr encoder and the GPIO tracks +// use: a "PWM" group track, then two counter tracks per channel (period, +// then pulse). +#define PWM_EMUL_GROUP_TRACK_UUID 0x50000000ULL +#define PWM_EMUL_TRACK_UUID(channel, pulse) \ + (PWM_EMUL_GROUP_TRACK_UUID + 1 + (uint64_t)(channel) * 2 + ((pulse) ? 1 : 0)) + +static bool group_described; + +static void trace_channel(uint32_t channel, struct pwm_emul_channel *ch) { + if (!perfetto_start()) { + return; + } + if (!group_described) { + perfetto_emit_track_descriptor(PWM_EMUL_GROUP_TRACK_UUID, + perfetto_get_trace_uuid(), "PWM"); + group_described = true; + } + if (!ch->described) { + char name[24]; + snprintf(name, sizeof(name), "pwm.%02u.period", (unsigned)channel); + perfetto_emit_counter_track_descriptor(PWM_EMUL_TRACK_UUID(channel, false), + PWM_EMUL_GROUP_TRACK_UUID, name, PERFETTO_COUNTER_UNIT_COUNT); + snprintf(name, sizeof(name), "pwm.%02u.pulse", (unsigned)channel); + perfetto_emit_counter_track_descriptor(PWM_EMUL_TRACK_UUID(channel, true), + PWM_EMUL_GROUP_TRACK_UUID, name, PERFETTO_COUNTER_UNIT_COUNT); + ch->described = true; + } + perfetto_emit_counter(PWM_EMUL_TRACK_UUID(channel, false), ch->period_cycles); + perfetto_emit_counter(PWM_EMUL_TRACK_UUID(channel, true), ch->pulse_cycles); +} + +#else + +static void trace_channel(uint32_t channel, struct pwm_emul_channel *ch) { + (void)channel; + (void)ch; +} + +#endif // CONFIG_TRACING_PERFETTO + +static int pwm_emul_set_cycles(const struct device *dev, uint32_t channel, + uint32_t period_cycles, uint32_t pulse_cycles, pwm_flags_t flags) { + (void)flags; + const struct pwm_emul_config *config = dev->config; + if (channel >= config->channel_count) { + return -EINVAL; + } + struct pwm_emul_channel *ch = &config->channels[channel]; + ch->period_cycles = period_cycles; + ch->pulse_cycles = pulse_cycles; + trace_channel(channel, ch); + return 0; +} + +static int pwm_emul_get_cycles_per_sec(const struct device *dev, uint32_t channel, + uint64_t *cycles) { + (void)channel; + const struct pwm_emul_config *config = dev->config; + *cycles = config->clock_frequency; + return 0; +} + +static DEVICE_API(pwm, pwm_emul_api) = { + .set_cycles = pwm_emul_set_cycles, + .get_cycles_per_sec = pwm_emul_get_cycles_per_sec, +}; + +#define PWM_EMUL_DEFINE(n) \ + static struct pwm_emul_channel pwm_emul_channels_##n[DT_INST_PROP(n, channels)]; \ + static const struct pwm_emul_config pwm_emul_config_##n = { \ + .clock_frequency = DT_INST_PROP(n, clock_frequency), \ + .channels = pwm_emul_channels_##n, \ + .channel_count = DT_INST_PROP(n, channels), \ + }; \ + DEVICE_DT_INST_DEFINE(n, NULL, NULL, NULL, &pwm_emul_config_##n, POST_KERNEL, \ + CONFIG_PWM_INIT_PRIORITY, &pwm_emul_api); + +DT_INST_FOREACH_STATUS_OKAY(PWM_EMUL_DEFINE) diff --git a/ports/zephyr-cp/internal-modules/pwm_emul/zephyr/module.yml b/ports/zephyr-cp/internal-modules/pwm_emul/zephyr/module.yml new file mode 100644 index 00000000000..836c05423cb --- /dev/null +++ b/ports/zephyr-cp/internal-modules/pwm_emul/zephyr/module.yml @@ -0,0 +1,13 @@ +# Zephyr module descriptor for the pwm_emul module. +# +# The module is loaded from the CircuitPython tree via ZEPHYR_EXTRA_MODULES in +# ports/zephyr-cp/CMakeLists.txt. To externalize it, move this directory into +# its own repository and either point ZEPHYR_EXTRA_MODULES at the new checkout +# or add it to the west manifest instead. +name: pwm_emul +build: + cmake: . + kconfig: Kconfig + settings: + # dts/bindings/ holds the adafruit,pwm-emul binding. + dts_root: . diff --git a/ports/zephyr-cp/mpconfigport.h b/ports/zephyr-cp/mpconfigport.h index 5b5b077a371..cc990c0208e 100644 --- a/ports/zephyr-cp/mpconfigport.h +++ b/ports/zephyr-cp/mpconfigport.h @@ -10,13 +10,31 @@ // 24kiB stack #define CIRCUITPY_DEFAULT_STACK_SIZE (24 * 1024) +#if defined(CONFIG_TRACING_PERFETTO) && defined(CONFIG_BOARD_NATIVE_SIM) +// Raising the RuntimeError for a C stack overflow allocates the exception, and +// gc_alloc() then emits a Perfetto counter whose encoder needs about 2.5kiB of +// stack. Leave room for it, or the simulator crashes instead of raising. +#define CIRCUITPY_EXCEPTION_STACK_SIZE (8 * 1024) +#endif + #define MICROPY_PY_SYS_PLATFORM "Zephyr" +// Add "(Zephyr)" to distinguish zephyr-cp builds from classic-port builds for the same board in the banner. +#define MICROPY_BANNER_MACHINE MICROPY_HW_BOARD_NAME " with " MICROPY_HW_MCU_NAME " (Zephyr)" + #define CIRCUITPY_DIGITALIO_HAVE_INVALID_PULL (1) #define DIGITALINOUT_INVALID_DRIVE_MODE (1) #define CIRCUITPY_DEBUG_TINYUSB 0 +// NVM size is determined at runtime from the Zephyr partition table. +#define CIRCUITPY_INTERNAL_NVM_SIZE 1 + +// Disable native _Float16 handling for host builds. +#define MICROPY_FLOAT_USE_NATIVE_FLT16 (0) + +#define MICROPY_NLR_THUMB_USE_LONG_JUMP (1) + //////////////////////////////////////////////////////////////////////////////////////////////////// // This also includes mpconfigboard.h. diff --git a/ports/zephyr-cp/mphalport.h b/ports/zephyr-cp/mphalport.h index b3adf5830d0..ee696a4f043 100644 --- a/ports/zephyr-cp/mphalport.h +++ b/ports/zephyr-cp/mphalport.h @@ -13,7 +13,12 @@ #include "py/mpconfig.h" #include "supervisor/shared/tick.h" +#include + #define mp_hal_ticks_ms() ((mp_uint_t)supervisor_ticks_ms32()) -#define mp_hal_delay_us(us) NRFX_DELAY_US((uint32_t)(us)) + +static inline void mp_hal_delay_us(mp_uint_t us) { + k_busy_wait((uint32_t)us); +} bool mp_hal_stdin_any(void); diff --git a/ports/zephyr-cp/native_sim_build_Containerfile b/ports/zephyr-cp/native_sim_build_Containerfile new file mode 100644 index 00000000000..ea4dde171f5 --- /dev/null +++ b/ports/zephyr-cp/native_sim_build_Containerfile @@ -0,0 +1,40 @@ +FROM docker.io/library/ubuntu:24.04 +ENV DEBIAN_FRONTEND=noninteractive TZ=Etc/UTC +ENV PKG_CONFIG_PATH=/usr/lib/i386-linux-gnu/pkgconfig + +RUN dpkg --add-architecture i386 && apt-get update && apt-get install -y --no-install-recommends \ + git cmake ninja-build gperf ccache dfu-util device-tree-compiler \ + curl wget python3 python3-dev python3-pip python3-venv python3-setuptools \ + python3-tk python3-wheel xz-utils file make gcc \ + gcc-multilib g++-multilib libc6-dev-i386 \ + libsdl2-dev:i386 libsdl2-image-dev:i386 \ + libmagic1 mtools pkg-config ca-certificates unzip \ + protobuf-compiler sudo \ + && rm -rf /var/lib/apt/lists/* + +# Remove the default ubuntu:24.04 'ubuntu' user (UID 1000) so 'dev' can take +# UID 1000 — required for --userns=keep-id to map host UID 1000 to 'dev'. +RUN userdel -r ubuntu 2>/dev/null || true \ + && useradd -m -u 1000 -s /bin/bash dev \ + && echo 'dev ALL=(ALL) NOPASSWD:ALL' > /etc/sudoers.d/dev \ + && chmod 440 /etc/sudoers.d/dev +USER dev +WORKDIR /home/dev + +RUN python3 -m venv /home/dev/.venv +ENV PATH="/home/dev/.venv/bin:${PATH}" +RUN pip install --no-cache-dir west pytest pyelftools pyyaml intelhex protobuf grpcio-tools + +# The repo is expected to be bind-mounted here at runtime: +# podman run -v ~/circuitpython:/home/dev/circuitpython:Z --userns=keep-id ... +# On first run, inside the container do: +# cd ~/circuitpython/ports/zephyr-cp +# west init -l zephyr-config +# west update +# pip install -r zephyr/scripts/requirements.txt +# pip install -r ../../requirements-dev.txt +# west zephyr-export +# west sdk install -t x86_64-zephyr-elf +# python ../../tools/ci_fetch_deps.py zephyr-cp +WORKDIR /home/dev/circuitpython/ports/zephyr-cp +CMD ["/bin/bash"] diff --git a/ports/zephyr-cp/native_sim_build_init_container.sh b/ports/zephyr-cp/native_sim_build_init_container.sh new file mode 100755 index 00000000000..c9f0975f97b --- /dev/null +++ b/ports/zephyr-cp/native_sim_build_init_container.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +# One-time setup to run INSIDE the zephyr-cp-dev container on the first +# launch against a fresh bind-mounted circuitpython checkout. +# +# Usage (inside the container): +# cd ~/circuitpython/ports/zephyr-cp +# ./native_sim_build_init_container.sh +# +# Safe to re-run; west/pip/etc. are idempotent. +set -euo pipefail + +git config --global --add safe.directory /home/dev/circuitpython + +cd "$(dirname "${BASH_SOURCE[0]}")" + +echo "==> west init" +if [ ! -d .west ]; then + west init -l zephyr-config +else + echo " (already initialized, skipping)" +fi + +echo "==> west update" +west update + +echo "==> pip install Zephyr requirements" +pip install -r zephyr/scripts/requirements.txt + +echo "==> pip install CircuitPython dev requirements" +pip install -r ../../requirements-dev.txt + +echo "==> west zephyr-export" +west zephyr-export + +echo "==> west sdk install (x86_64-zephyr-elf)" +west sdk install -t x86_64-zephyr-elf + +echo "==> fetch port submodules" +python ../../tools/ci_fetch_deps.py zephyr-cp + +echo +echo "First-run setup complete." +echo "You can now build with: make BOARD=native_native_sim" diff --git a/ports/zephyr-cp/native_sim_build_run_container.sh b/ports/zephyr-cp/native_sim_build_run_container.sh new file mode 100755 index 00000000000..d2f281998bc --- /dev/null +++ b/ports/zephyr-cp/native_sim_build_run_container.sh @@ -0,0 +1,55 @@ +#!/usr/bin/env bash +# Launch (or re-attach to) the zephyr-cp-dev container with the enclosing +# circuitpython checkout bind-mounted at /home/dev/circuitpython. Works from +# any CWD — the mount is resolved relative to this script's location. +# +# On first invocation, creates a persistent container named "zcp". On +# subsequent invocations, re-starts the same container so installed state +# (e.g. the Zephyr SDK under /home/dev/zephyr-sdk-*) survives across sessions. +# +# Optional environment variables: +# ZCP_CONTAINER container name (default: zcp) +# ZCP_IMAGE image name (default: localhost/zephyr-cp-dev) +# ZCP_PODMAN_ARGS extra options for "podman run", used only when the +# container is first created (e.g. "--runtime runc") +# ZCP_NO_DISPLAY set to 1 to not share the host's X11 display +# +# If DISPLAY is set when the container is first created, the host's X11 +# socket and a copy of its X cookie are shared so the simulator can open its +# display window. This works on a Linux desktop and in WSLg. +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "$SCRIPT_DIR/../.." && pwd)" +CONTAINER_NAME="${ZCP_CONTAINER:-zcp}" +IMAGE="${ZCP_IMAGE:-localhost/zephyr-cp-dev}" +read -r -a EXTRA_ARGS <<< "${ZCP_PODMAN_ARGS:-}" + +DISPLAY_ARGS=() +if [ -z "${ZCP_NO_DISPLAY:-}" ] && [ -n "${DISPLAY:-}" ] && [ -d /tmp/.X11-unix ]; then + # The host's X cookie is tied to its hostname, which the container does + # not share. Copy it as a wildcard entry on every start, so a cookie + # renewed by a new desktop session reaches the container too. + XAUTH_DIR="${XDG_CACHE_HOME:-$HOME/.cache}/zcp-xauth/$CONTAINER_NAME" + mkdir -p "$XAUTH_DIR" + rm -f "$XAUTH_DIR/xauth" + touch "$XAUTH_DIR/xauth" + if command -v xauth >/dev/null; then + xauth nlist "$DISPLAY" 2>/dev/null | sed -e 's/^..../ffff/' \ + | xauth -f "$XAUTH_DIR/xauth" nmerge - 2>/dev/null || true + fi + DISPLAY_ARGS+=(-v /tmp/.X11-unix:/tmp/.X11-unix:ro -e DISPLAY + -v "$XAUTH_DIR:/home/dev/.zcp-xauth:ro" + -e XAUTHORITY=/home/dev/.zcp-xauth/xauth) +fi + +if podman container exists "$CONTAINER_NAME"; then + exec podman start -ai "$CONTAINER_NAME" +else + exec podman run -it --init --name "$CONTAINER_NAME" \ + -v "$REPO_ROOT:/home/dev/circuitpython:Z" \ + --userns=keep-id \ + ${DISPLAY_ARGS[@]+"${DISPLAY_ARGS[@]}"} \ + ${EXTRA_ARGS[@]+"${EXTRA_ARGS[@]}"} \ + "$IMAGE" "$@" +fi diff --git a/ports/zephyr-cp/native_sim_i2c_emul_control.c b/ports/zephyr-cp/native_sim_i2c_emul_control.c new file mode 100644 index 00000000000..de467122a7b --- /dev/null +++ b/ports/zephyr-cp/native_sim_i2c_emul_control.c @@ -0,0 +1,169 @@ +/* + * SPDX-License-Identifier: Apache-2.0 + * + * Command-line control for enabling/disabling emulated I2C devices + * on native_sim. This allows testing device hot-plug and error scenarios. + */ + +#include +#include +#include +#include +#include +#include + +#include "nsi_cmdline.h" +#include "posix_native_task.h" + +LOG_MODULE_REGISTER(i2c_emul_control, LOG_LEVEL_INF); + +#define MAX_DISABLED_DEVICES 16 + +struct disabled_device { + const char *name; + const struct emul *emul; + struct i2c_emul_api mock_api; + bool disabled; +}; + +static struct disabled_device disabled_devices[MAX_DISABLED_DEVICES]; +static int num_disabled_devices = 0; + +static char *disabled_device_args[MAX_DISABLED_DEVICES]; +static int num_disabled_device_args = 0; + +/* + * Mock transfer function that returns -EIO (NACK) when device is disabled, + * or -ENOSYS to fall back to the real emulator. + */ +static int disabled_device_transfer(const struct emul *target, + struct i2c_msg *msgs, + int num_msgs, + int addr) { + ARG_UNUSED(msgs); + ARG_UNUSED(num_msgs); + ARG_UNUSED(addr); + + for (int i = 0; i < num_disabled_devices; i++) { + if (disabled_devices[i].emul == target) { + if (disabled_devices[i].disabled) { + LOG_DBG("Device %s is disabled, returning -EIO", + disabled_devices[i].name); + return -EIO; + } + break; + } + } + /* Fall back to normal emulator behavior */ + return -ENOSYS; +} + +int i2c_emul_control_disable_device(const char *name) { + const struct emul *emul = emul_get_binding(name); + if (!emul) { + LOG_ERR("Emulator '%s' not found", name); + return -ENODEV; + } + + if (emul->bus_type != EMUL_BUS_TYPE_I2C) { + LOG_ERR("Emulator '%s' is not an I2C device", name); + return -EINVAL; + } + + /* Find existing entry or create new one */ + int idx = -1; + for (int i = 0; i < num_disabled_devices; i++) { + if (disabled_devices[i].emul == emul) { + idx = i; + break; + } + } + + if (idx < 0) { + if (num_disabled_devices >= MAX_DISABLED_DEVICES) { + LOG_ERR("Too many disabled devices"); + return -ENOMEM; + } + idx = num_disabled_devices++; + disabled_devices[idx].name = name; + disabled_devices[idx].emul = emul; + disabled_devices[idx].mock_api.transfer = disabled_device_transfer; + + /* Install our mock_api to intercept transfers */ + emul->bus.i2c->mock_api = &disabled_devices[idx].mock_api; + } + + disabled_devices[idx].disabled = true; + LOG_INF("Disabled I2C emulator: %s", name); + return 0; +} + +int i2c_emul_control_enable_device(const char *name) { + for (int i = 0; i < num_disabled_devices; i++) { + if (strcmp(disabled_devices[i].name, name) == 0) { + disabled_devices[i].disabled = false; + LOG_INF("Enabled I2C emulator: %s", name); + return 0; + } + } + LOG_ERR("Device '%s' not in disabled list", name); + return -ENODEV; +} + +bool i2c_emul_control_is_disabled(const char *name) { + for (int i = 0; i < num_disabled_devices; i++) { + if (strcmp(disabled_devices[i].name, name) == 0) { + return disabled_devices[i].disabled; + } + } + return false; +} + +/* Command-line option handler */ +static void cmd_disable_i2c_device(char *argv, int offset) { + /* The value is at argv + offset (after the '=' in --disable-i2c=value) */ + char *value = argv + offset; + if (num_disabled_device_args < MAX_DISABLED_DEVICES) { + disabled_device_args[num_disabled_device_args++] = value; + } else { + printk("i2c_emul_control: Too many --disable-i2c arguments, ignoring: %s\n", value); + } +} + +static struct args_struct_t i2c_emul_args[] = { + { + .option = "disable-i2c", + .name = "device", + .type = 's', + .call_when_found = cmd_disable_i2c_device, + .descript = "Disable an emulated I2C device by name (can be repeated). " + "Example: --disable-i2c=bmi160" + }, + ARG_TABLE_ENDMARKER +}; + +static void register_cmdline_opts(void) { + nsi_add_command_line_opts(i2c_emul_args); +} + +/* Register command-line options early in boot */ +NATIVE_TASK(register_cmdline_opts, PRE_BOOT_1, 0); + +static int apply_disabled_devices(void) { + LOG_DBG("Applying %d disabled device(s)", num_disabled_device_args); + for (int i = 0; i < num_disabled_device_args; i++) { + int rc = i2c_emul_control_disable_device(disabled_device_args[i]); + if (rc != 0) { + LOG_WRN("Failed to disable I2C device '%s': %d", + disabled_device_args[i], rc); + } + } + return 0; +} + +/* + * Apply after emulators are initialized. + * I2C emulators are registered at POST_KERNEL level, so we need to run + * at APPLICATION level to ensure they exist. + */ +SYS_INIT(apply_disabled_devices, APPLICATION, 99); diff --git a/ports/zephyr-cp/native_sim_spi_loopback_emul.c b/ports/zephyr-cp/native_sim_spi_loopback_emul.c new file mode 100644 index 00000000000..2736f8929fd --- /dev/null +++ b/ports/zephyr-cp/native_sim_spi_loopback_emul.c @@ -0,0 +1,63 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +// SPI loopback for native_sim: every byte sent is read back, and zeros when nothing is sent. + +#define DT_DRV_COMPAT circuitpython_spi_loopback + +#include +#include +#include +#include + +static int loopback_io(const struct emul *target, const struct spi_config *config, + const struct spi_buf_set *tx_bufs, const struct spi_buf_set *rx_bufs) { + ARG_UNUSED(target); + ARG_UNUSED(config); + if (rx_bufs == NULL) { + return 0; + } + // A buffer without data is that many idle or dropped bytes, as in Zephyr's drivers. + size_t tx_i = 0; + size_t tx_pos = 0; + for (size_t i = 0; i < rx_bufs->count; i++) { + uint8_t *rx = rx_bufs->buffers[i].buf; + for (size_t j = 0; j < rx_bufs->buffers[i].len; j++) { + uint8_t value = 0; + while (tx_bufs != NULL && tx_i < tx_bufs->count && tx_pos >= tx_bufs->buffers[tx_i].len) { + tx_i++; + tx_pos = 0; + } + if (tx_bufs != NULL && tx_i < tx_bufs->count) { + const uint8_t *tx = tx_bufs->buffers[tx_i].buf; + if (tx != NULL) { + value = tx[tx_pos]; + } + tx_pos++; + } + if (rx != NULL) { + rx[j] = value; + } + } + } + return 0; +} + +static int loopback_init(const struct emul *target, const struct device *parent) { + ARG_UNUSED(target); + ARG_UNUSED(parent); + return 0; +} + +static const struct spi_emul_api loopback_api = { + .io = loopback_io, +}; + +#define LOOPBACK_DEFINE(n) \ + DEVICE_DT_INST_DEFINE(n, NULL, NULL, NULL, NULL, POST_KERNEL, CONFIG_SPI_INIT_PRIORITY, NULL); \ + EMUL_DT_INST_DEFINE(n, loopback_init, NULL, NULL, &loopback_api, NULL); + +DT_INST_FOREACH_STATUS_OKAY(LOOPBACK_DEFINE) diff --git a/ports/zephyr-cp/prj.conf b/ports/zephyr-cp/prj.conf index f769d7dc6b8..a91ec2501bd 100644 --- a/ports/zephyr-cp/prj.conf +++ b/ports/zephyr-cp/prj.conf @@ -1,28 +1,149 @@ +# Keep allocation statistics for Zephyr's malloc arena. This is the only way +# to find out how much of the arena is free: port_heap_get_largest_free_size() +# needs that number so the VM heap can grow into the arena. CONFIG_SYS_HEAP_RUNTIME_STATS=y CONFIG_FLASH=y CONFIG_FLASH_MAP=y -CONFIG_STD_C23=y +CONFIG_USE_DT_CODE_PARTITION=y + +# The MCUboot integration signs zephyr.hex into zephyr.signed.hex; boards whose +# SoC does not select BUILD_OUTPUT_HEX (e.g. STM32 does) otherwise only emit a +# .bin, and the Makefile's firmware.hex merge then has nothing to sign. +CONFIG_BUILD_OUTPUT_HEX=y CONFIG_DYNAMIC_INTERRUPTS=y CONFIG_UART_INTERRUPT_DRIVEN=y CONFIG_FLASH_MAP_LABELS=y CONFIG_MAIN_STACK_SIZE=24288 -CONFIG_SPI_NOR_FLASH_LAYOUT_PAGE_SIZE=4096 -CONFIG_NORDIC_QSPI_NOR_FLASH_LAYOUT_PAGE_SIZE=4096 + +# The system workqueue is used by BT settings delayed store (NVS flash writes +# during bond key save). RRAM flash drivers on nRF54L need more than the +# default 1024 bytes to avoid stack overflow. +CONFIG_SYSTEM_WORKQUEUE_STACK_SIZE=3072 CONFIG_THREAD_STACK_INFO=y -CONFIG_STACK_SENTINEL=y -CONFIG_DEBUG_THREAD_INFO=y -CONFIG_DEBUG_INFO=y +CONFIG_ARCH_POSIX_UPDATE_STACK_INFO=y +CONFIG_STACK_SENTINEL=n +CONFIG_DEBUG_THREAD_INFO=n +CONFIG_EXCEPTION_STACK_TRACE=n + +CONFIG_USB_DEVICE_STACK_NEXT=y +CONFIG_USBD_CDC_ACM_CLASS=y +CONFIG_USBD_HID_SUPPORT=y +CONFIG_USBD_MSC_STACK_SIZE=1536 +CONFIG_CDC_ACM_SERIAL_INITIALIZE_AT_BOOT=n -CONFIG_USB_DEVICE_STACK=n +CONFIG_USBD_MSC_CLASS=y +CONFIG_USBD_MSC_LUNS_PER_INSTANCE=1 +# Two (double-buffered) 1 KB SCSI buffers. Reads are as fast as with 4 KB +# buffers, and writes match the classic ports; 4 KB writes were faster only on +# nRF52840 (77 vs 68 KB/s) and cost 6 KB more RAM. 512-byte buffers read +# much slower (a third of the speed on the i.MX RT1011). +CONFIG_USBD_MSC_SCSI_BUFFER_SIZE=1024 CONFIG_HWINFO=y CONFIG_REBOOT=y -CONFIG_ENTROPY_GENERATOR=y - -CONFIG_ASSERT=y -CONFIG_LOG_BLOCK_IN_THREAD=y +CONFIG_ASSERT=n +# The fault register dump is only useful when debugging, and debug.conf turns +# it back on. Safe mode still reports a hard fault without it. +CONFIG_EXCEPTION_DUMP=n CONFIG_EVENTS=y + +# Enable the input subsystem so boards with status-okay input devices in their +# devicetree get a working zephyr_input module via zephyr2cp. +CONFIG_INPUT=y + +# Enable the RTC driver layer so boards with a status-okay `rtc` devicetree +# alias (e.g. native_sim's rtc-emul, STM32, RP2040, SmartBond) get a working +# rtc module via common-hal/rtc. Boards without the alias only pay for the +# tiny RTC core (syscall table + rtc_utils). +CONFIG_RTC=y + +# Enable the watchdog driver layer so boards with a status-okay `watchdog0` +# devicetree alias (the same selection Zephyr's watchdog sample uses, e.g. +# native_sim's counter-based emulation, Nordic WDT, RP2040, STM32) get a +# working watchdog module via common-hal/watchdog. Boards without the alias +# only pay for the tiny watchdog core (syscall table). +CONFIG_WATCHDOG=y + +CONFIG_SERIAL=y + +# Fail quickly on hung I2C devices (probe/scan also uses this timeout) +CONFIG_I2C_TRANSFER_TIMEOUT_MS=50 + +# Zephyr's Nordic SoC defconfig sets UART_USE_RUNTIME_CONFIGURE default n +# (soc/nordic/Kconfig.defconfig) for footprint. Without it the UARTE driver +# does not register api.configure and uart_configure() returns -ENOSYS +# unconditionally, which makes busio.UART fail with "Unsupported UART +# configuration" for every config. Runtime configure is required for the +# iobroker-routed UARTs to get their baudrate/parity/stop bits applied. +CONFIG_UART_USE_RUNTIME_CONFIGURE=y + +CONFIG_FRAME_POINTER=n + +CONFIG_NET_HOSTNAME_ENABLE=y +CONFIG_NET_HOSTNAME_DYNAMIC=y +CONFIG_NET_HOSTNAME="circuitpython" + +CONFIG_DYNAMIC_THREAD=y +CONFIG_DYNAMIC_THREAD_ALLOC=y +CONFIG_DYNAMIC_THREAD_PREFER_ALLOC=y + +CONFIG_FPU=y + +CONFIG_MBEDTLS=y + +# Override Kconfig default not taking effect. The BLE file-transfer workflow +# packs up to BLEIO_PACKET_BUFFER_MAX_PACKET_SIZE (512) bytes per notification, +# so the L2CAP/ATT MTU must accommodate a 512-byte payload plus the 3-byte +# ATT header (opcode + handle). Without this the default with SMP is only 65, +# and notifications larger than the negotiated MTU fail with +# "No ATT channel for MTU". +CONFIG_BT_L2CAP_TX_MTU=515 +CONFIG_BT_BUF_ACL_RX_SIZE=255 +CONFIG_BT_BUF_ACL_TX_SIZE=251 +CONFIG_BT_RX_STACK_SIZE=2048 +CONFIG_BT_LONG_WQ_STACK_SIZE=3072 +CONFIG_MBEDTLS_BUILTIN=y +CONFIG_PSA_CRYPTO=y +CONFIG_PSA_WANT_ALG_SHA_1=y +CONFIG_PSA_WANT_ALG_SHA_256=y + +# Real-world certificate chains use SHA-384/512 signatures (e.g. Sectigo +# "R"-series CAs) and ECDSA signatures. The PSA wants for those, and for the +# curve/cipher selection matching ports/espressif/sdkconfig, are gated on +# ZCP_MBEDTLS_TLS in internal-modules/circuitpython-kconfig/Kconfig. They +# cannot be unconditional here: BT boards without the TLS stack would compile +# the corresponding unused tf-psa-crypto code, which trips -Werror and the +# driver-only-builds config checks. + +# Zephyr defaults the TLS input buffer to 1500 bytes, but real-world TLS +# peer certificates arrive in single records larger than that (e.g. ~4 KB +# from adafruit.com). mbedtls then fails fetch_input() with +# MBEDTLS_ERR_SSL_BAD_INPUT_DATA, which in mbedtls 4.x numerically collides +# with MBEDTLS_ERR_PK_BAD_INPUT_DATA, so CircuitPython surfaces it as a +# misleading "invalid key" ValueError in the middle of the handshake. +# Use mbedtls-style defaults matching ports/espressif/sdkconfig and +# lib/mbedtls_config/mbedtls_config.h: 16384 in, 4096 out. +CONFIG_MBEDTLS_SSL_IN_CONTENT_LEN=16384 +CONFIG_MBEDTLS_SSL_OUT_CONTENT_LEN=4096 + +# Settings storage backend for BT bond keys +# SECTOR_COUNT is set high — the init code caps it to what fits in the storage +# partition: min(sector_count, partition_size / sector_size) +CONFIG_NVS=y +CONFIG_SETTINGS_NVS=y +CONFIG_SETTINGS_NVS_SECTOR_COUNT=256 + +# Zephyr's host reserves a connection object for a connectable advertiser, and +# the controller sizes its RX node pool from this too. With the default of 1, +# user code cannot connect as a central or start a timed scan while the BLE +# workflow advertises. 5 matches nordic. About 2.9 KB of RAM per connection. +CONFIG_BT_MAX_CONN=5 + +# Number of stored bonds. The default of 1 means bonding to a second peer +# evicts the BLE workflow's bond (BT_KEYS_OVERWRITE_OLDEST). 3 matches +# espressif's NimBLE default; nordic keeps dozens. +CONFIG_BT_MAX_PAIRED=3 diff --git a/ports/zephyr-cp/socs/mimxrt1011.conf b/ports/zephyr-cp/socs/mimxrt1011.conf new file mode 100644 index 00000000000..3c2b084cf7a --- /dev/null +++ b/ports/zephyr-cp/socs/mimxrt1011.conf @@ -0,0 +1,6 @@ +# The RT1011 has only 128 KB of FlexRAM, so trim to fit the heap. +# - 20 KB main stack, as ports/mimxrt10xx has. +# - The system workqueue peaked at 264 bytes (thread analyzer, CDC traffic, +# CIRCUITPY writes); the 3072 in prj.conf is for BLE bond saves on nRF54L. +CONFIG_MAIN_STACK_SIZE=20480 +CONFIG_SYSTEM_WORKQUEUE_STACK_SIZE=2048 diff --git a/ports/zephyr-cp/socs/nrf52840.conf b/ports/zephyr-cp/socs/nrf52840.conf index bf70997d83f..734d26db8e9 100644 --- a/ports/zephyr-cp/socs/nrf52840.conf +++ b/ports/zephyr-cp/socs/nrf52840.conf @@ -1,4 +1,3 @@ -CONFIG_NRFX_UARTE0=y -CONFIG_NRFX_UARTE1=y +CONFIG_NRFX_UARTE=y CONFIG_NRFX_POWER=y diff --git a/ports/zephyr-cp/socs/nrf5340_cpuapp.conf b/ports/zephyr-cp/socs/nrf5340_cpuapp.conf index bf70997d83f..734d26db8e9 100644 --- a/ports/zephyr-cp/socs/nrf5340_cpuapp.conf +++ b/ports/zephyr-cp/socs/nrf5340_cpuapp.conf @@ -1,4 +1,3 @@ -CONFIG_NRFX_UARTE0=y -CONFIG_NRFX_UARTE1=y +CONFIG_NRFX_UARTE=y CONFIG_NRFX_POWER=y diff --git a/ports/zephyr-cp/socs/stm32h7b3xx.conf b/ports/zephyr-cp/socs/stm32h7b3xx.conf index 3c7daeb753d..14a93b52ce8 100644 --- a/ports/zephyr-cp/socs/stm32h7b3xx.conf +++ b/ports/zephyr-cp/socs/stm32h7b3xx.conf @@ -1,4 +1 @@ -CONFIG_USE_STM32_LL_USB=y -CONFIG_USE_STM32_HAL_PCD=y - CONFIG_MEMC=y diff --git a/ports/zephyr-cp/socs/stm32u575xx.conf b/ports/zephyr-cp/socs/stm32u575xx.conf index 78cefbfef40..e69de29bb2d 100644 --- a/ports/zephyr-cp/socs/stm32u575xx.conf +++ b/ports/zephyr-cp/socs/stm32u575xx.conf @@ -1,2 +0,0 @@ -CONFIG_USE_STM32_LL_USB=y -CONFIG_USE_STM32_HAL_PCD=y diff --git a/ports/zephyr-cp/supervisor/adaboot_info.c b/ports/zephyr-cp/supervisor/adaboot_info.c new file mode 100644 index 00000000000..c0459c66521 --- /dev/null +++ b/ports/zephyr-cp/supervisor/adaboot_info.c @@ -0,0 +1,93 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// Adaboot identity for the SMP "bootloader info" command. Zephyr's +// application-side os_mgmt handler reports the hardcoded "MCUboot" and +// derives the boot mode from the application's own Kconfig. This hook +// answers with the fork's name and fills mode/running slot from the BLINFO +// TLVs the bootloader left in the zephyr,bootloader-info shared-data +// retention area (written by boot_write_shared_data() on every boot). + +#include + +#include + +#if defined(CONFIG_MCUMGR_GRP_OS_BOOTLOADER_INFO_HOOK) && \ + defined(CONFIG_RETENTION_BOOTLOADER_INFO_TYPE_MCUBOOT) + +/* The bootloader-info hook API is part of the MCUmgr/SMP stack: the event's + * data struct embeds a live zcbor response encoder and a zcbor_string query, + * and the hook appends its answers with zcbor put calls. The headers (and + * Zephyr's zcbor include path, which only exists when CONFIG_MCUMGR selects + * ZCBOR) are therefore guarded along with the hook: SMP boards compile it + * in, no-Bluetooth boards like frdm_mcxn947 compile the whole hook out and + * never need the headers. */ +#include +#include +#include +#include +#include + +#include +#include + +// Only answer the queries we know how to fill from the shared data; leave +// everything else for Zephyr's handler (which reports the query error). +#define ADABOOT_INFO_NAME "Adaboot" + +static enum mgmt_cb_return adaboot_info_event(uint32_t event, + enum mgmt_cb_return prev_status, int32_t *rc, + uint16_t *group, bool *abort_more, void *data, + size_t data_size) { + struct os_mgmt_bootloader_info_data *info = data; + struct zcbor_string query = *info->query; + int32_t value; + + if (*info->has_output) { + // Another hook already answered; leave the response alone. + return MGMT_CB_OK; + } + + if (*info->decoded == 0) { + // Empty query: identify the bootloader. + if (zcbor_tstr_put_lit(info->zse, "bootloader") && + zcbor_tstr_put_lit(info->zse, ADABOOT_INFO_NAME)) { + *info->has_output = true; + } + return MGMT_CB_OK; + } + + if (query.len == 4 && memcmp(query.value, "mode", 4) == 0) { + int rc = blinfo_lookup(BLINFO_MODE, (char *)&value, sizeof(value)); + if (rc == sizeof(value) && + zcbor_tstr_put_lit(info->zse, "mode") && + zcbor_int32_put(info->zse, value)) { + *info->has_output = true; + } + } else if (query.len == 4 && memcmp(query.value, "slot", 4) == 0) { + // Single-application layouts never write a running-slot TLV; leave + // the query unanswered so Zephyr reports its usual error. + int rc = blinfo_lookup(BLINFO_RUNNING_SLOT, (char *)&value, sizeof(value)); + if (rc == sizeof(value) && + zcbor_tstr_put_lit(info->zse, "slot") && + zcbor_int32_put(info->zse, value)) { + *info->has_output = true; + } + } + + return MGMT_CB_OK; +} + +static struct mgmt_callback adaboot_info_callback = { + .callback = adaboot_info_event, + .event_id = MGMT_EVT_OP_OS_MGMT_BOOTLOADER_INFO, +}; + +void adaboot_info_init(void) { + mgmt_callback_register(&adaboot_info_callback); +} + +#endif diff --git a/ports/zephyr-cp/supervisor/flash.c b/ports/zephyr-cp/supervisor/flash.c index 6b893f89abe..9c43dcfd758 100644 --- a/ports/zephyr-cp/supervisor/flash.c +++ b/ports/zephyr-cp/supervisor/flash.c @@ -20,8 +20,40 @@ #include #include +// The filesystem partition node label comes from the Adaboot fork's layout +// dtsi (and the native simulator layouts). Prefer the explicit fatfs/littlefs +// names, then fall back to the older circuitpy_partition name some boards use, +// and finally to runtime discovery of an unpartitioned flash device. +#if FIXED_PARTITION_EXISTS(littlefs_partition) +#define CIRCUITPY_PARTITION littlefs_partition +#elif FIXED_PARTITION_EXISTS(fatfs_partition) +#define CIRCUITPY_PARTITION fatfs_partition +#elif FIXED_PARTITION_EXISTS(circuitpy_partition) #define CIRCUITPY_PARTITION circuitpy_partition -static struct flash_area *filesystem_area = NULL; +#endif + +// Check that the filesystem partition starts and ends on a layout page +// boundary: flash.c addresses erase pages relative to the start of the +// partition. The NOR flash drivers set their layout page size in Kconfig, so +// they can be checked at build time. (Other drivers report it only at run +// time.) +#if FIXED_PARTITION_EXISTS(CIRCUITPY_PARTITION) +#define CIRCUITPY_PARTITION_NODE DT_NODELABEL(CIRCUITPY_PARTITION) +#define CIRCUITPY_PARTITION_MTD DT_MTD_FROM_FIXED_PARTITION(CIRCUITPY_PARTITION_NODE) +#if defined(CONFIG_NORDIC_QSPI_NOR) && DT_NODE_HAS_COMPAT(CIRCUITPY_PARTITION_MTD, nordic_qspi_nor) +#define CIRCUITPY_LAYOUT_PAGE_SIZE CONFIG_NORDIC_QSPI_NOR_FLASH_LAYOUT_PAGE_SIZE +#elif defined(CONFIG_SPI_NOR) && DT_NODE_HAS_COMPAT(CIRCUITPY_PARTITION_MTD, jedec_spi_nor) +#define CIRCUITPY_LAYOUT_PAGE_SIZE CONFIG_SPI_NOR_FLASH_LAYOUT_PAGE_SIZE +#elif defined(CONFIG_FLASH_MSPI_NOR) && DT_NODE_HAS_COMPAT(CIRCUITPY_PARTITION_MTD, jedec_nor) +#define CIRCUITPY_LAYOUT_PAGE_SIZE CONFIG_FLASH_MSPI_NOR_LAYOUT_PAGE_SIZE +#endif +#ifdef CIRCUITPY_LAYOUT_PAGE_SIZE +BUILD_ASSERT(DT_REG_ADDR(CIRCUITPY_PARTITION_NODE) % CIRCUITPY_LAYOUT_PAGE_SIZE == 0 && + DT_REG_SIZE(CIRCUITPY_PARTITION_NODE) % CIRCUITPY_LAYOUT_PAGE_SIZE == 0, + "filesystem partition must start and end on a flash layout page boundary"); +#endif +#endif +static const struct flash_area *filesystem_area = NULL; #if !FIXED_PARTITION_EXISTS(CIRCUITPY_PARTITION) static struct flash_area _dynamic_area; @@ -31,15 +63,14 @@ static struct flash_area _dynamic_area; extern const struct device *const flashes[]; extern const int circuitpy_flash_device_count; -// Size of an erase area +// Size of an erase page. static size_t _page_size; -// Size of a write area -static size_t _row_size; +// The value a flash byte has after being erased (usually 0xFF, but can differ). +static uint8_t _erase_value; -// Number of file system blocks in a page. +// Number of FILESYSTEM_BLOCK_SIZE blocks in an erase page. static size_t _blocks_per_page; -static size_t _rows_per_block; static uint32_t _page_mask; #define NO_PAGE_LOADED 0xFFFFFFFF @@ -49,14 +80,47 @@ static uint32_t _current_page_address; static uint32_t _scratch_page_address; -// Track which blocks (up to 32) in the current sector currently live in the -// cache. -static uint32_t _dirty_mask; -static uint32_t _loaded_mask; +// Size of the filesystem in bytes: every whole page, less the scratch page if +// there is one. +static uint32_t _filesystem_size; + +static bool allocate_ram_cache(void); + +// Per-block flags packed into a uint8_t array (one byte per block). +#define ROW_LOADED 0x01 // Block data is present in the cache. +#define ROW_DIRTY 0x02 // Block has been modified since last flush. +#define ROW_ERASED 0x04 // Block is all 0xFF; no need to write after erase. + +static uint8_t *_row_flags = NULL; + +static inline void _clear_row_flags(void) { + if (_row_flags != NULL) { + memset(_row_flags, 0, _blocks_per_page); + } +} + +static inline bool _any_dirty(void) { + for (size_t i = 0; i < _blocks_per_page; i++) { + if (_row_flags[i] & ROW_DIRTY) { + return true; + } + } + return false; +} + +// Check if a buffer is entirely the erase value. +static bool _buffer_is_erased(const uint8_t *buf, size_t len) { + for (size_t i = 0; i < len; i++) { + if (buf[i] != _erase_value) { + return false; + } + } + return true; +} // Table of pointers to each cached block. Should be zero'd after allocation. -#define FLASH_CACHE_TABLE_NUM_ENTRIES (_blocks_per_page * _rows_per_block) -#define FLASH_CACHE_TABLE_SIZE (FLASH_CACHE_TABLE_NUM_ENTRIES * sizeof (uint8_t *)) +#define FLASH_CACHE_TABLE_NUM_ENTRIES (_blocks_per_page) +#define FLASH_CACHE_TABLE_SIZE (FLASH_CACHE_TABLE_NUM_ENTRIES * sizeof(uint8_t *)) static uint8_t **flash_cache_table = NULL; static K_MUTEX_DEFINE(_mutex); @@ -106,11 +170,17 @@ void supervisor_flash_init(void) { // printk("flash area %d %d\n", filesystem_area->fa_id, filesystem_area->fa_size); printk("hello from flash init\n"); bool covered_by_areas[circuitpy_flash_device_count]; + // fa_cb only sets entries to true, so start from all false. + memset(covered_by_areas, 0, sizeof(covered_by_areas)); flash_area_foreach(fa_cb, covered_by_areas); for (int i = 0; i < circuitpy_flash_device_count; i++) { const struct device *d = flashes[i]; printk("flash %p %s\n", d, d->name); + if (!device_is_ready(d)) { + printk(" not ready\n"); + continue; + } if (covered_by_areas[i]) { printk(" covered by flash area\n"); continue; @@ -167,52 +237,66 @@ void supervisor_flash_init(void) { return; } - const struct device *d = flash_area_get_device(filesystem_area); - _row_size = flash_get_write_block_size(d); - if (_row_size < 256) { - if (256 % _row_size == 0) { - _row_size = 256; - } else { - size_t new_row_size = _row_size; - while (new_row_size < 256) { - new_row_size += _row_size; - } - _row_size = new_row_size; - } - } struct flash_pages_info first_info; + const struct device *d = flash_area_get_device(filesystem_area); + const struct flash_parameters *fp = flash_get_parameters(d); + _erase_value = fp->erase_value; flash_get_page_info_by_offs(d, filesystem_area->fa_off, &first_info); - struct flash_pages_info last_info; - flash_get_page_info_by_offs(d, filesystem_area->fa_off + filesystem_area->fa_size - _row_size, &last_info); _page_size = first_info.size; if (_page_size < FILESYSTEM_BLOCK_SIZE) { _page_size = FILESYSTEM_BLOCK_SIZE; } - printk(" erase page size %d\n", _page_size); - // Makes sure that a cached page has 32 or fewer rows. Our dirty mask is - // only 32 bits. - while (_page_size / _row_size > 32) { - _row_size *= 2; - } - printk(" write row size %d\n", _row_size); _blocks_per_page = _page_size / FILESYSTEM_BLOCK_SIZE; - printk(" blocks per page %d\n", _blocks_per_page); - _rows_per_block = FILESYSTEM_BLOCK_SIZE / _row_size; _page_mask = ~(_page_size - 1); - // The last page is the scratch sector. - _scratch_page_address = last_info.start_offset; + printk(" erase page size %d\n", _page_size); + printk(" blocks per page %d\n", _blocks_per_page); + + // Page addresses are relative to the start of the area. If the area + // doesn't end on a page boundary, its last partial page can't be erased + // without going past the end, so it is left unused. + size_t page_count = filesystem_area->fa_size / _page_size; + size_t min_page_count = IS_ENABLED(CONFIG_CIRCUITPY_FLASH_SCRATCH_PAGE) ? 2 : 1; + if (page_count < min_page_count) { + printk("Filesystem area too small (%zu pages)\n", page_count); + filesystem_area = NULL; + return; + } + + _row_flags = port_malloc(_blocks_per_page, false); + if (_row_flags == NULL) { + printk("Unable to allocate row flags (%d bytes)\n", _blocks_per_page); + filesystem_area = NULL; + return; + } + memset(_row_flags, 0, _blocks_per_page); + _current_page_address = NO_PAGE_LOADED; + + #if CONFIG_CIRCUITPY_FLASH_SCRATCH_PAGE + // The last whole page is the scratch page. + _scratch_page_address = (page_count - 1) * _page_size; + _filesystem_size = _scratch_page_address; + #else + // No scratch page: allocate the RAM cache now and keep it, so writes + // never need one. + if (!allocate_ram_cache()) { + printk("Unable to allocate the filesystem ram cache\n"); + filesystem_area = NULL; + return; + } + _filesystem_size = page_count * _page_size; + #endif } uint32_t supervisor_flash_get_block_size(void) { - return 512; + return FILESYSTEM_BLOCK_SIZE; } uint32_t supervisor_flash_get_block_count(void) { if (filesystem_area == NULL) { return 0; } - return (_scratch_page_address - filesystem_area->fa_off) / 512; + return _filesystem_size / FILESYSTEM_BLOCK_SIZE; } @@ -241,10 +325,8 @@ static bool write_flash(uint32_t address, const uint8_t *data, uint32_t data_len static bool block_erased(uint32_t sector_address) { uint8_t short_buffer[4]; if (read_flash(sector_address, short_buffer, 4)) { - for (uint16_t i = 0; i < 4; i++) { - if (short_buffer[i] != 0xff) { - return false; - } + if (!_buffer_is_erased(short_buffer, 4)) { + return false; } } else { return false; @@ -253,10 +335,8 @@ static bool block_erased(uint32_t sector_address) { // Now check the full length. uint8_t full_buffer[FILESYSTEM_BLOCK_SIZE]; if (read_flash(sector_address, full_buffer, FILESYSTEM_BLOCK_SIZE)) { - for (uint16_t i = 0; i < FILESYSTEM_BLOCK_SIZE; i++) { - if (short_buffer[i] != 0xff) { - return false; - } + if (!_buffer_is_erased(full_buffer, FILESYSTEM_BLOCK_SIZE)) { + return false; } } else { return false; @@ -274,17 +354,26 @@ static bool erase_page(uint32_t sector_address) { return res == 0; } -// Sector is really 24 bits. static bool copy_block(uint32_t src_address, uint32_t dest_address) { - // Copy row by row to minimize RAM buffer. - uint8_t buffer[_row_size]; - for (uint32_t i = 0; i < FILESYSTEM_BLOCK_SIZE / _row_size; i++) { - if (!read_flash(src_address + i * _row_size, buffer, _row_size)) { - return false; - } - if (!write_flash(dest_address + i * _row_size, buffer, _row_size)) { - return false; - } + uint8_t buffer[FILESYSTEM_BLOCK_SIZE]; + if (!read_flash(src_address, buffer, FILESYSTEM_BLOCK_SIZE)) { + return false; + } + if (!write_flash(dest_address, buffer, FILESYSTEM_BLOCK_SIZE)) { + return false; + } + return true; +} + +// Load a block into the ram cache and set its flags. Returns false on read error. +static bool _load_block_into_cache(size_t block_index) { + if (!read_flash(_current_page_address + block_index * FILESYSTEM_BLOCK_SIZE, + flash_cache_table[block_index], FILESYSTEM_BLOCK_SIZE)) { + return false; + } + _row_flags[block_index] |= ROW_LOADED; + if (_buffer_is_erased(flash_cache_table[block_index], FILESYSTEM_BLOCK_SIZE)) { + _row_flags[block_index] |= ROW_ERASED; } return true; } @@ -299,12 +388,12 @@ static bool flush_scratch_flash(void) { // cached. bool copy_to_scratch_ok = true; for (size_t i = 0; i < _blocks_per_page; i++) { - if ((_dirty_mask & (1 << i)) == 0) { + if (!(_row_flags[i] & ROW_DIRTY)) { copy_to_scratch_ok = copy_to_scratch_ok && copy_block(_current_page_address + i * FILESYSTEM_BLOCK_SIZE, _scratch_page_address + i * FILESYSTEM_BLOCK_SIZE); } - _loaded_mask |= (1 << i); + _row_flags[i] |= ROW_LOADED; } if (!copy_to_scratch_ok) { // TODO(tannewt): Do more here. We opted to not erase and copy bad data @@ -318,6 +407,10 @@ static bool flush_scratch_flash(void) { copy_block(_scratch_page_address + i * FILESYSTEM_BLOCK_SIZE, _current_page_address + i * FILESYSTEM_BLOCK_SIZE); } + // Every scratch block is now written, so the next write must erase the + // scratch page first. Unload the page so that it does. + _current_page_address = NO_PAGE_LOADED; + _clear_row_flags(); return true; } @@ -337,7 +430,7 @@ static void release_ram_cache(void) { port_free(flash_cache_table); flash_cache_table = NULL; _current_page_address = NO_PAGE_LOADED; - _loaded_mask = 0; + _clear_row_flags(); } // Attempts to allocate a new set of page buffers for caching a full sector in @@ -346,7 +439,7 @@ static void release_ram_cache(void) { static bool allocate_ram_cache(void) { flash_cache_table = port_malloc(FLASH_CACHE_TABLE_SIZE, false); if (flash_cache_table == NULL) { - // Not enough space even for the cache table. + printk("Unable to allocate ram cache table\n"); return false; } @@ -355,21 +448,20 @@ static bool allocate_ram_cache(void) { bool success = true; for (size_t i = 0; i < _blocks_per_page && success; i++) { - for (size_t j = 0; j < _rows_per_block && success; j++) { - uint8_t *page_cache = port_malloc(_row_size, false); - if (page_cache == NULL) { - success = false; - break; - } - flash_cache_table[i * _rows_per_block + j] = page_cache; + uint8_t *block_cache = port_malloc(FILESYSTEM_BLOCK_SIZE, false); + if (block_cache == NULL) { + success = false; + break; } + flash_cache_table[i] = block_cache; } // We couldn't allocate enough so give back what we got. if (!success) { + printk("Unable to allocate ram cache pages\n"); release_ram_cache(); } - _loaded_mask = 0; + _clear_row_flags(); _current_page_address = NO_PAGE_LOADED; return success; } @@ -382,7 +474,7 @@ static bool flush_ram_cache(bool keep_cache) { return true; } - if (_current_page_address == NO_PAGE_LOADED || _dirty_mask == 0) { + if (_current_page_address == NO_PAGE_LOADED || !_any_dirty()) { if (!keep_cache) { release_ram_cache(); } @@ -393,21 +485,12 @@ static bool flush_ram_cache(bool keep_cache) { // erase below. bool copy_to_ram_ok = true; for (size_t i = 0; i < _blocks_per_page; i++) { - if ((_loaded_mask & (1 << i)) == 0) { - for (size_t j = 0; j < _rows_per_block; j++) { - copy_to_ram_ok = read_flash( - _current_page_address + (i * _rows_per_block + j) * _row_size, - flash_cache_table[i * _rows_per_block + j], - _row_size); - if (!copy_to_ram_ok) { - break; - } + if (!(_row_flags[i] & ROW_LOADED)) { + if (!_load_block_into_cache(i)) { + copy_to_ram_ok = false; + break; } } - if (!copy_to_ram_ok) { - break; - } - _loaded_mask |= (1 << i); } if (!copy_to_ram_ok) { @@ -417,14 +500,19 @@ static bool flush_ram_cache(bool keep_cache) { erase_page(_current_page_address); // Lastly, write all the data in ram that we've cached. for (size_t i = 0; i < _blocks_per_page; i++) { - for (size_t j = 0; j < _rows_per_block; j++) { - write_flash(_current_page_address + (i * _rows_per_block + j) * _row_size, - flash_cache_table[i * _rows_per_block + j], - _row_size); + // Skip blocks that are entirely erased — the page erase already + // set them to 0xFF so writing would be redundant. + if (_row_flags[i] & ROW_ERASED) { + continue; } + write_flash(_current_page_address + i * FILESYSTEM_BLOCK_SIZE, + flash_cache_table[i], + FILESYSTEM_BLOCK_SIZE); + } + // Nothing is dirty anymore. Clear dirty but keep loaded and erased. + for (size_t i = 0; i < _blocks_per_page; i++) { + _row_flags[i] &= ~ROW_DIRTY; } - // Nothing is dirty anymore. Some may already be in the cache cleanly. - _dirty_mask = 0; // We're done with the cache for now so give it back. if (!keep_cache) { @@ -436,6 +524,10 @@ static bool flush_ram_cache(bool keep_cache) { // Delegates to the correct flash flush method depending on the existing cache. // TODO Don't blink the status indicator if we don't actually do any writing (hard to tell right now). static void _flush_keep_cache(bool keep_cache) { + #if !CONFIG_CIRCUITPY_FLASH_SCRATCH_PAGE + // Without a scratch page, the RAM cache is never released. + keep_cache = true; + #endif #ifdef MICROPY_HW_LED_MSC port_pin_set_output_level(MICROPY_HW_LED_MSC, true); #endif @@ -487,15 +579,10 @@ static bool _flash_read_block(uint8_t *dest, uint32_t block) { // Mask out the lower bits that designate the address within the sector. uint32_t page_address = address & _page_mask; size_t block_index = (address / FILESYSTEM_BLOCK_SIZE) % _blocks_per_page; - uint32_t mask = 1 << (block_index); // We're reading from the currently cached sector. - if (_current_page_address == page_address && (mask & _loaded_mask) > 0) { + if (_current_page_address == page_address && (_row_flags[block_index] & ROW_LOADED)) { if (flash_cache_table != NULL) { - for (int i = 0; i < _rows_per_block; i++) { - memcpy(dest + i * _row_size, - flash_cache_table[block_index * _rows_per_block + i], - _row_size); - } + memcpy(dest, flash_cache_table[block_index], FILESYSTEM_BLOCK_SIZE); return true; } uint32_t scratch_block_address = _scratch_page_address + block_index * FILESYSTEM_BLOCK_SIZE; @@ -514,34 +601,37 @@ static bool _flash_write_block(const uint8_t *data, uint32_t block) { // Mask out the lower bits that designate the address within the sector. uint32_t page_address = address & _page_mask; size_t block_index = (address / FILESYSTEM_BLOCK_SIZE) % _blocks_per_page; - uint32_t mask = 1 << (block_index); - // Flush the cache if we're moving onto a different page. - if (_current_page_address != page_address) { + // Flush the cache if we're moving onto a different page, or if we're + // writing the same block again while caching in the scratch page: flash + // can't be rewritten without an erase, so the second write must start a + // fresh scratch page. + bool scratch_rewrite = flash_cache_table == NULL && + _current_page_address == page_address && + (_row_flags[block_index] & ROW_DIRTY); + if (_current_page_address != page_address || scratch_rewrite) { // Check to see if we'd write to an erased block and aren't writing to - // our cache. In that case we can write directly. - if (block_erased(address)) { + // our cache. In that case we can write directly. Do not take this fast + // path when the target block is part of the currently cached page: the + // cache copy would go stale and later reads would return the old data. + if (block_erased(address) && + !(_current_page_address == page_address && (_row_flags[block_index] & ROW_LOADED))) { return write_flash(address, data, FILESYSTEM_BLOCK_SIZE); } if (_current_page_address != NO_PAGE_LOADED) { - supervisor_flash_flush(); + // Flush only the old page. supervisor_flash_flush() would also + // clear the dirty flag, which littlefs sets before writing. + _flush_keep_cache(true); } if (flash_cache_table == NULL && !allocate_ram_cache()) { erase_page(_scratch_page_address); } _current_page_address = page_address; - _dirty_mask = 0; - _loaded_mask = 0; + _clear_row_flags(); } - _dirty_mask |= mask; - _loaded_mask |= mask; - + _row_flags[block_index] = ROW_DIRTY | ROW_LOADED; // Copy the block to the appropriate cache. if (flash_cache_table != NULL) { - for (int i = 0; i < _rows_per_block; i++) { - memcpy(flash_cache_table[block_index * _rows_per_block + i], - data + i * _row_size, - _row_size); - } + memcpy(flash_cache_table[block_index], data, FILESYSTEM_BLOCK_SIZE); return true; } else { uint32_t scratch_block_address = _scratch_page_address + block_index * FILESYSTEM_BLOCK_SIZE; diff --git a/ports/zephyr-cp/supervisor/port.c b/ports/zephyr-cp/supervisor/port.c index c1d6c913d6a..c13aa728323 100644 --- a/ports/zephyr-cp/supervisor/port.c +++ b/ports/zephyr-cp/supervisor/port.c @@ -7,15 +7,67 @@ #include "supervisor/port.h" #include "mpconfigboard.h" +#include "adaboot/update_mode.h" +#include "supervisor/shared/tick.h" + +#if CIRCUITPY_AUDIOBUSIO_I2SOUT +#include "common-hal/audiobusio/I2SOut.h" +#endif +#if CIRCUITPY_WATCHDOG +#include "shared-module/watchdog/__init__.h" +#endif +#if CIRCUITPY_NEOPIXEL_WRITE +#include "common-hal/neopixel_write/__init__.h" +#endif + +#if CIRCUITPY_RTC +#include "shared-bindings/rtc/__init__.h" +#endif +#if CIRCUITPY_SSL +#include "shared-module/ssl/__init__.h" +#endif + +#include #include #include #include +#include + +#if defined(CONFIG_ARCH_POSIX) +#include +#include +#include + +#include "cmdline.h" +#include "nsi_host_trampolines.h" +#include "posix_board_if.h" +#include "posix_native_task.h" +#endif #include "lib/tlsf/tlsf.h" #include +#include + +#if defined(CONFIG_IMG_MANAGER) +#include +#endif + +#if defined(CONFIG_SOC_FAMILY_RPI_PICO) +#include +#include +#endif + +#if defined(CONFIG_TRACING_PERFETTO) && defined(CONFIG_BOARD_NATIVE_SIM) +#include "perfetto_encoder.h" +#include +#define CIRCUITPY_PERFETTO_TRACK_GROUP_UUID 0x3000ULL +#define CIRCUITPY_PERFETTO_VM_HEAP_USED_UUID 0x3001ULL +#define CIRCUITPY_PERFETTO_OUTER_HEAP_USED_UUID 0x3002ULL +#endif static tlsf_t heap; +static size_t tlsf_heap_used = 0; // Auto generated in pins.c extern const struct device *const rams[]; @@ -23,15 +75,207 @@ extern const uint32_t *const ram_bounds[]; extern const size_t circuitpy_max_ram_size; static pool_t pools[CIRCUITPY_RAM_DEVICE_COUNT]; +static uint8_t valid_pool_count = 0; +static bool zephyr_malloc_active = false; +static void *zephyr_malloc_top = NULL; +static void *zephyr_malloc_bottom = NULL; static K_EVENT_DEFINE(main_needed); +static struct k_timer tick_timer; + +#if defined(CONFIG_ARCH_POSIX) +// Number of VM runs before exiting. +// <= 0 means run forever. +// INT32_MAX means option was not provided. +static int32_t native_sim_port_resets = INT32_MAX; +static uint32_t native_sim_reset_port_count = 0; + +// Path to a file used to preserve retained memory across the execv reboot, or +// NULL if disabled. Set with --retained-memory= (see +// cp_retained_save/restore()). +static const char *native_sim_retained_memory; + +typedef struct { + uint32_t saved_word; + uint32_t port_reset_count; +} cp_retained_data_t; + +static struct args_struct_t native_sim_port_args[] = { + { + .option = "port-resets", + .name = "count", + .type = 'i', + .dest = &native_sim_port_resets, + .descript = "Exit native_sim after this many port_reset() calls. " + "Example: --port-resets=2" + }, + { + .option = "retained-memory", + .name = "path", + .type = 's', + .dest = (void *)&native_sim_retained_memory, + .descript = "File used to preserve some state" + " across the process re-exec reboot. " + "Example: --retained-memory=/tmp/cp_retained.bin" + }, + ARG_TABLE_ENDMARKER +}; + +static void native_sim_register_cmdline_opts(void) { + native_add_command_line_opts(native_sim_port_args); +} + +NATIVE_TASK(native_sim_register_cmdline_opts, PRE_BOOT_1, 0); +#endif + +#if defined(CONFIG_TRACING_PERFETTO) && defined(CONFIG_BOARD_NATIVE_SIM) +static bool perfetto_circuitpython_tracks_emitted; + +static void perfetto_emit_outer_heap_stats(void) { + if (!perfetto_start()) { + return; + } + size_t total = tlsf_heap_used; + #if defined(CONFIG_COMMON_LIBC_MALLOC) && defined(CONFIG_SYS_HEAP_RUNTIME_STATS) + extern int malloc_runtime_stats_get(struct sys_memory_stats *stats); + struct sys_memory_stats stats; + if (malloc_runtime_stats_get(&stats) == 0) { + total += stats.allocated_bytes; + } + #endif + perfetto_emit_counter(CIRCUITPY_PERFETTO_OUTER_HEAP_USED_UUID, (int64_t)total); + Z_SPIN_DELAY(1); +} + +static void perfetto_emit_circuitpython_tracks(void) { + if (perfetto_circuitpython_tracks_emitted) { + return; + } + if (!perfetto_start()) { + return; + } + perfetto_emit_track_descriptor(CIRCUITPY_PERFETTO_TRACK_GROUP_UUID, + perfetto_get_process_uuid(), + "CircuitPython"); + perfetto_emit_counter_track_descriptor(CIRCUITPY_PERFETTO_VM_HEAP_USED_UUID, + CIRCUITPY_PERFETTO_TRACK_GROUP_UUID, + "VM Heap Used", + PERFETTO_COUNTER_UNIT_BYTES); + perfetto_emit_counter_track_descriptor(CIRCUITPY_PERFETTO_OUTER_HEAP_USED_UUID, + CIRCUITPY_PERFETTO_TRACK_GROUP_UUID, + "Outer Heap Used", + PERFETTO_COUNTER_UNIT_BYTES); + perfetto_circuitpython_tracks_emitted = true; +} +#else +static inline void perfetto_emit_outer_heap_stats(void) { +} + +static inline void perfetto_emit_circuitpython_tracks(void) { +} +#endif + +static void _tick_function(struct k_timer *timer_id) { + supervisor_tick(); +} + +// Save and retrieve a word from memory that is preserved over reset. Used for safe mode. +static __noinit uint32_t cp_saved_word; + +void port_set_saved_word(uint32_t value) { + cp_saved_word = value; +} + +uint32_t port_get_saved_word(void) { + return cp_saved_word; +} + +// Save and restore retained memory across the native_sim/bsim reboot. Opt in +// with --retained-memory=. +#if defined(CONFIG_ARCH_POSIX) +static void cp_retained_save(void) { + const char *path = native_sim_retained_memory; + if (path == NULL || path[0] == '\0') { + return; + } + int fd = nsi_host_open(path, O_WRONLY | O_CREAT | O_TRUNC, 0644); + if (fd < 0) { + return; + } + cp_retained_data_t data = { + .saved_word = cp_saved_word, + .port_reset_count = native_sim_reset_port_count, + }; + (void)nsi_host_write(fd, &data, sizeof(data)); + (void)nsi_host_close(fd); +} + +static void cp_retained_restore(void) { + const char *path = native_sim_retained_memory; + if (path == NULL || path[0] == '\0') { + return; + } + int fd = nsi_host_open(path, O_RDONLY, 0 /* unused */); + if (fd < 0) { + return; // First boot: no save file yet. + } + cp_retained_data_t data = { 0 }; + (void)nsi_host_read(fd, &data, sizeof(data)); + (void)nsi_host_close(fd); + cp_saved_word = data.saved_word; + native_sim_reset_port_count = data.port_reset_count; +} +#endif + safe_mode_t port_init(void) { + #if defined(CONFIG_ARCH_POSIX) + cp_retained_restore(); + #endif + + // We run CircuitPython at the lowest priority (just higher than idle.) + // This allows networking and USB to preempt us. + k_thread_priority_set(k_current_get(), CONFIG_NUM_PREEMPT_PRIORITIES - 1); + + #if defined(CONFIG_MCUMGR_GRP_OS_BOOTLOADER_INFO_HOOK) + // Called from here, not SYS_INIT: this file is an archive member that + // nothing references, so the linker never pulls it in unless another + // always-linked translation unit calls into it. + adaboot_info_init(); + #endif + + #if defined(CONFIG_IMG_MANAGER) + // Confirm the running image so MCUboot treats it as permanent instead of + // reverting to the other slot on the next boot. Reaching here means the + // image booted far enough to run the port, which is the usual recovery + // criterion for a test (TEST_AND_CONFIRM) OTA upgrade. + if (!boot_is_img_confirmed()) { + (void)boot_write_img_confirmed(); + } + #endif + + k_timer_init(&tick_timer, _tick_function, NULL); + perfetto_emit_circuitpython_tracks(); return SAFE_MODE_NONE; } // Reset the microcontroller completely. void reset_cpu(void) { + #if defined(CONFIG_ARCH_POSIX) + cp_retained_save(); + #endif + + #if defined(CONFIG_SOC_FAMILY_RPI_PICO) + // On RP2 the Arm system reset leaves the USB controller running, so the + // host never sees the board go away. Reset the whole chip through the + // watchdog instead, as pico-sdk's watchdog_reboot() does. Zephyr's + // hal_rpi_pico does not build watchdog.c, so write the registers here. + hw_clear_bits(&watchdog_hw->ctrl, WATCHDOG_CTRL_ENABLE_BITS); + watchdog_hw->scratch[4] = 0; + hw_set_bits(&psm_hw->wdsel, PSM_WDSEL_BITS & ~(PSM_WDSEL_ROSC_BITS | PSM_WDSEL_XOSC_BITS)); + hw_set_bits(&watchdog_hw->ctrl, WATCHDOG_CTRL_TRIGGER_BITS); + #endif + // Try a warm reboot first. It won't return if it works but isn't always // implemented. sys_reboot(SYS_REBOOT_WARM); @@ -41,11 +285,46 @@ void reset_cpu(void) { } } +void port_gc_collect(void) { + #if CIRCUITPY_AUDIOBUSIO_I2SOUT + i2sout_gc_collect(); + #endif +} + void reset_port(void) { + #if CIRCUITPY_WATCHDOG + watchdog_reset(); + #endif + #if CIRCUITPY_AUDIOBUSIO_I2SOUT + i2sout_reset(); + #endif + #if CIRCUITPY_NEOPIXEL_WRITE + neopixel_write_reset(); + #endif + + #if CIRCUITPY_RTC + rtc_reset(); + #endif + + #if CIRCUITPY_SSL + ssl_reset(); + #endif + + #if defined(CONFIG_ARCH_POSIX) + native_sim_reset_port_count++; + if (native_sim_port_resets != INT32_MAX && + native_sim_port_resets > 0 && + native_sim_reset_port_count >= (uint32_t)(native_sim_port_resets + 1)) { + printk("posix: exiting after %d port resets\n", native_sim_port_resets); + posix_exit(0); + } + #endif } void reset_to_bootloader(void) { + // Ask for UF2 mode so the bootloader shows its drive. + adaboot_request_update_mode(true); reset_cpu(); } @@ -57,34 +336,74 @@ void port_wake_main_task_from_isr(void) { k_event_set(&main_needed, 1); } -void port_yield(void) { +void port_task_yield(void) { k_yield(); } +void port_task_sleep_ms(uint32_t msecs) { + k_msleep(msecs); +} + void port_boot_info(void) { } // Get stack limit address uint32_t *port_stack_get_limit(void) { - return k_current_get()->stack_info.start; + #if defined(CONFIG_ARCH_POSIX) + // The VM runs on the main thread, which on hosted builds has a pthread stack + // of several megabytes. Give it the stack size it has on a board, so deep + // recursion raises RuntimeError like on a board instead of running out of + // heap first. + return port_stack_get_top() - CONFIG_MAIN_STACK_SIZE / sizeof(uint32_t); + #else + return (uint32_t *)k_current_get()->stack_info.start; + #endif } // Get stack top address uint32_t *port_stack_get_top(void) { _thread_stack_info_t stack_info = k_current_get()->stack_info; - return stack_info.start + stack_info.size - stack_info.delta; -} - -// Save and retrieve a word from memory that is preserved over reset. Used for safe mode. -void port_set_saved_word(uint32_t) { - -} -uint32_t port_get_saved_word(void) { - return 0; + uint32_t *top = (uint32_t *)(stack_info.start + stack_info.size - stack_info.delta); + #if defined(CONFIG_ARCH_POSIX) + // On hosted builds the thread stack is a pthread stack. pthread_getattr_np(), + // which the POSIX arch uses to fix up stack_info, can report a size larger + // than the real mapping (ASan intercepts it and inflates the size). The GC + // scans up to the returned top, so clamp it to the end of the mapping that + // contains the current stack pointer. + // + // Only ever clamp *downwards*: /proc/self/maps merges adjacent anonymous + // mappings with the same flags, so the line containing our stack pointer + // routinely covers several thread stacks at once (e.g. 0xf63c2000-0xf73c4000 + // for two 8MB stacks). Taking its end as the top made the GC scan megabytes + // past this thread's stack, into the neighbouring thread's live stack -- and + // segfault whenever the range had an unmapped hole (a guard page, or a stack + // that has since been freed). + volatile uint32_t stack_probe; + uintptr_t sp = (uintptr_t)&stack_probe; + FILE *maps = fopen("/proc/self/maps", "r"); + if (maps != NULL) { + char line[256]; + unsigned long low, high; + while (fgets(line, sizeof(line), maps) != NULL) { + if (sscanf(line, "%lx-%lx", &low, &high) == 2 && low <= sp && sp < high) { + if (high < (uintptr_t)top) { + top = (uint32_t *)high; + } + break; + } + } + fclose(maps); + } + #endif + return top; } uint64_t port_get_raw_ticks(uint8_t *subticks) { + // Make sure time advances in the simulator. + #if defined(CONFIG_ARCH_POSIX) + k_busy_wait(100); + #endif int64_t uptime = k_uptime_ticks() * 32768 / CONFIG_SYS_CLOCK_TICKS_PER_SEC; if (subticks != NULL) { *subticks = uptime % 32; @@ -94,12 +413,12 @@ uint64_t port_get_raw_ticks(uint8_t *subticks) { // Enable 1/1024 second tick. void port_enable_tick(void) { - + k_timer_start(&tick_timer, K_USEC(1000000 / 1024), K_USEC(1000000 / 1024)); } // Disable 1/1024 second tick. void port_disable_tick(void) { - + k_timer_stop(&tick_timer); } static k_timeout_t next_timeout; @@ -123,36 +442,118 @@ void port_idle_until_interrupt(void) { // Zephyr doesn't maintain one multi-heap. So, make our own using TLSF. void port_heap_init(void) { + // Do a test malloc to determine if Zephyr has an outer heap that may + // overlap with a memory region we've identified in ram_bounds. We'll + // corrupt each other if we both use it. + #ifdef CONFIG_COMMON_LIBC_MALLOC + uint32_t *test_malloc = malloc(32); + free(test_malloc); // Free right away so we don't forget. We don't actually write it anyway. + zephyr_malloc_active = test_malloc != NULL; + #endif + for (size_t i = 0; i < CIRCUITPY_RAM_DEVICE_COUNT; i++) { uint32_t *heap_bottom = ram_bounds[2 * i]; uint32_t *heap_top = ram_bounds[2 * i + 1]; size_t size = (heap_top - heap_bottom) * sizeof(uint32_t); + // The linker script may fill up a region we thought we could use at + // build time. (The ram_bounds values are sometimes determined by the + // linker.) So, we need to guard against regions that aren't actually + // free. + if (size < 1024) { + printk("Skipping region because the linker filled it up.\n"); + continue; + } + #ifdef CONFIG_COMMON_LIBC_MALLOC + // Skip a ram region if our test malloc is within it. We'll use Zephyr's + // malloc to share that space with Zephyr. + if (heap_bottom <= test_malloc && test_malloc < heap_top) { + zephyr_malloc_top = heap_top; + zephyr_malloc_bottom = heap_bottom; + printk("Skipping region because Zephyr malloc is within bounds\n"); + pools[i] = NULL; + continue; + } + #endif printk("Init heap at %p - %p with size %d\n", heap_bottom, heap_top, size); // If this crashes, then make sure you've enabled all of the Kconfig needed for the drivers. - if (i == 0) { + if (valid_pool_count == 0) { heap = tlsf_create_with_pool(heap_bottom, size, circuitpy_max_ram_size); + if (heap == NULL) { + // Can happen for a region the linker filled almost to the top, + // which the build-time MINIMUM_RAM_SIZE filter cannot predict + // because it only sees the devicetree size. + printk("Heap creation failed at %p; trying the next region\n", heap_bottom); + pools[i] = NULL; + continue; + } pools[i] = tlsf_get_pool(heap); } else { pools[i] = tlsf_add_pool(heap, heap_bottom + 1, size - sizeof(uint32_t)); } + valid_pool_count++; } + perfetto_emit_outer_heap_stats(); #if !DT_HAS_CHOSEN(zephyr_sram) #error "No SRAM!" #endif } void *port_malloc(size_t size, bool dma_capable) { - void *block = tlsf_malloc(heap, size); + void *block = NULL; + if (valid_pool_count > 0) { + block = tlsf_malloc(heap, size); + } + if (block != NULL) { + tlsf_heap_used += tlsf_block_size(block); + } + #ifdef CONFIG_COMMON_LIBC_MALLOC + if (block == NULL) { + block = malloc(size); + } + #endif + if (block != NULL) { + perfetto_emit_outer_heap_stats(); + } return block; } void port_free(void *ptr) { - tlsf_free(heap, ptr); + if (ptr == NULL) { + return; + } + if (valid_pool_count > 0 && !(ptr >= zephyr_malloc_bottom && ptr < zephyr_malloc_top)) { + tlsf_heap_used -= tlsf_block_size(ptr); + tlsf_free(heap, ptr); + } else { + #ifdef CONFIG_COMMON_LIBC_MALLOC + free(ptr); + #endif + } + perfetto_emit_outer_heap_stats(); } -void *port_realloc(void *ptr, size_t size) { - return tlsf_realloc(heap, ptr, size); +void *port_realloc(void *ptr, size_t size, bool dma_capable) { + if (ptr == NULL) { + return port_malloc(size, dma_capable); + } + if (valid_pool_count > 0 && !(ptr >= zephyr_malloc_bottom && ptr < zephyr_malloc_top)) { + size_t old_size = tlsf_block_size(ptr); + void *new_block = tlsf_realloc(heap, ptr, size); + if (new_block != NULL) { + tlsf_heap_used = tlsf_heap_used - old_size + tlsf_block_size(new_block); + perfetto_emit_outer_heap_stats(); + } + return new_block; + } + #ifdef CONFIG_COMMON_LIBC_MALLOC + void *new_block = realloc(ptr, size); + if (new_block != NULL) { + perfetto_emit_outer_heap_stats(); + } + return new_block; + #endif + return NULL; } static bool max_size_walker(void *ptr, size_t size, int used, void *user) { @@ -163,11 +564,60 @@ static bool max_size_walker(void *ptr, size_t size, int used, void *user) { return true; } +// The larger of the TLSF and Zephyr malloc free space, because port_malloc() +// falls back to Zephyr's malloc when TLSF can't satisfy a request. size_t port_heap_get_largest_free_size(void) { - size_t max_size = 0; - for (size_t i = 0; i < CIRCUITPY_RAM_DEVICE_COUNT; i++) { - tlsf_walk_pool(pools[i], max_size_walker, &max_size); + bool known = false; + size_t largest = 0; + if (valid_pool_count > 0) { + size_t max_size = 0; + for (size_t i = 0; i < CIRCUITPY_RAM_DEVICE_COUNT; i++) { + if (pools[i] == NULL) { + continue; + } + tlsf_walk_pool(pools[i], max_size_walker, &max_size); + } + // IDF does this. Not sure why. + largest = tlsf_fit_size(heap, max_size); + known = true; + } + #if defined(CONFIG_COMMON_LIBC_MALLOC) && defined(CONFIG_SYS_HEAP_RUNTIME_STATS) + // Compute how much of Zephyr's malloc arena the VM heap may take: the + // arena's total free bytes, minus: + // - Alignment padding. sys_heap can add up to __alignof__(z_max_align_t) + // bytes to a malloc() request, so a request for all the free bytes + // would fail. + // - CONFIG_CIRCUITPY_ZEPHYR_MALLOC_RESERVE, left for Zephyr's own + // allocations, such as for TLS connections and BLE pairing. + // + // This can be misleading when the arena is fragmented. sys_heap only + // reports total free bytes, not the largest free block, so the result can + // be larger than any single block malloc() can return. gc_try_add_heap() + // then retries with smaller sizes. + // + // zephyr_malloc_active is set by port_heap_init() when Zephyr's malloc() + // works at all. + if (zephyr_malloc_active) { + extern int malloc_runtime_stats_get(struct sys_memory_stats *stats); + struct sys_memory_stats stats; + if (malloc_runtime_stats_get(&stats) == 0) { + size_t held_back = __alignof__(z_max_align_t) + CONFIG_CIRCUITPY_ZEPHYR_MALLOC_RESERVE; + size_t arena_free = stats.free_bytes > held_back ? stats.free_bytes - held_back : 0; + largest = MAX(largest, arena_free); + known = true; + } + } + #endif + return known ? largest : 64 * 1024; +} + +void assert_post_action(const char *file, unsigned int line) { + // printk("Assertion failed at %s:%u\n", file, line); + // Check that this is arm + #if defined(__arm__) + __asm__ ("bkpt"); + #endif + while (1) { + ; } - // IDF does this. Not sure why. - return tlsf_fit_size(heap, max_size); } diff --git a/ports/zephyr-cp/supervisor/serial.c b/ports/zephyr-cp/supervisor/serial.c index 97e2bee9ce5..efc7647df62 100644 --- a/ports/zephyr-cp/supervisor/serial.c +++ b/ports/zephyr-cp/supervisor/serial.c @@ -6,52 +6,80 @@ #include "supervisor/shared/serial.h" -#include "bindings/zephyr_serial/UART.h" +#include "supervisor/zephyr-cp.h" -static zephyr_serial_uart_obj_t zephyr_console; -static uint8_t buffer[64]; +#if CIRCUITPY_USB_DEVICE == 1 +#include "shared-bindings/usb_cdc/Serial.h" +usb_cdc_serial_obj_t *usb_console; +#else +#include "shared-bindings/busio/UART.h" +static busio_uart_obj_t uart_console; +static uint8_t buffer[1024]; +#endif void port_serial_early_init(void) { #if CIRCUITPY_USB_DEVICE == 0 - zephyr_console.base.type = &zephyr_serial_uart_type; - zephyr_serial_uart_construct(&zephyr_console, DEVICE_DT_GET(DT_CHOSEN(zephyr_console)), sizeof(buffer), buffer); + uart_console.base.type = &busio_uart_type; + common_hal_busio_uart_construct_from_device(&uart_console, DEVICE_DT_GET(DT_CHOSEN(zephyr_console)), sizeof(buffer), buffer, true); #endif } void port_serial_init(void) { + #if CIRCUITPY_USB_DEVICE == 1 + usb_console = usb_cdc_serial_get_console(); + #endif } bool port_serial_connected(void) { #if CIRCUITPY_USB_DEVICE == 1 - return false; + if (usb_console == NULL) { + return false; + } + return common_hal_usb_cdc_serial_get_connected(usb_console); #else return true; #endif } char port_serial_read(void) { - #if CIRCUITPY_USB_DEVICE == 0 + #if CIRCUITPY_USB_DEVICE == 1 + if (usb_console == NULL) { + return -1; + } char buf[1]; - size_t count = zephyr_serial_uart_read(&zephyr_console, buf, 1, NULL); + size_t count = common_hal_usb_cdc_serial_read(usb_console, buf, 1, NULL); if (count == 0) { return -1; } return buf[0]; #else - return -1; + char buf[1]; + size_t count = common_hal_busio_uart_read(&uart_console, buf, 1, NULL); + if (count == 0) { + return -1; + } + return buf[0]; #endif } uint32_t port_serial_bytes_available(void) { - #if CIRCUITPY_USB_DEVICE == 0 - return zephyr_serial_uart_rx_characters_available(&zephyr_console); + #if CIRCUITPY_USB_DEVICE == 1 + if (usb_console == NULL) { + return 0; + } + return common_hal_usb_cdc_serial_get_in_waiting(usb_console); #else - return 0; + return common_hal_busio_uart_rx_characters_available(&uart_console); #endif } void port_serial_write_substring(const char *text, uint32_t length) { - #if CIRCUITPY_USB_DEVICE == 0 - zephyr_serial_uart_write(&zephyr_console, text, length, NULL); + #if CIRCUITPY_USB_DEVICE == 1 + if (usb_console == NULL) { + return; + } + common_hal_usb_cdc_serial_write(usb_console, text, length, NULL); + #else + zephyr_uart_write_blocking(&uart_console, (const uint8_t *)text, length); #endif } diff --git a/ports/zephyr-cp/supervisor/usb.c b/ports/zephyr-cp/supervisor/usb.c index 18eb2847ad9..c10cdec9737 100644 --- a/ports/zephyr-cp/supervisor/usb.c +++ b/ports/zephyr-cp/supervisor/usb.c @@ -1,202 +1,584 @@ #include "supervisor/usb.h" -#include "tusb_option.h" +#include "shared-bindings/usb_cdc/__init__.h" +#include "shared-bindings/usb_cdc/Serial.h" -#if CFG_TUSB_MCU == OPT_MCU_STM32U5 -#include +#if CIRCUITPY_USB_HID +#include "common-hal/usb_hid/__init__.h" #endif -#if CFG_TUSB_MCU == OPT_MCU_NRF5X -#include -#include -#endif +#include "supervisor/zephyr-cp.h" + +#include "extmod/vfs.h" +#include "extmod/vfs_fat.h" +#include "lib/oofatfs/diskio.h" +#include "lib/oofatfs/ff.h" #include +#include #include -#include +#include #include - -#if DT_HAS_COMPAT_STATUS_OKAY(st_stm32_otghs) -#define UDC_IRQ_NAME otghs -#elif DT_HAS_COMPAT_STATUS_OKAY(st_stm32_otgfs) -#define UDC_IRQ_NAME otgfs -#elif DT_HAS_COMPAT_STATUS_OKAY(st_stm32_usb) -#define UDC_IRQ_NAME usb -#elif DT_HAS_COMPAT_STATUS_OKAY(renesas_ra_usb) -#define UDC_IRQ_NAME usbhs_ir +#include +#include +#if DT_HAS_COMPAT_STATUS_OKAY(nordic_nrf_usbd) +#include #endif -#if DT_HAS_COMPAT_STATUS_OKAY(renesas_ra_usb) -#define USB_NAME usbhs -#else -#define USB_NAME zephyr_udc0 +#include "shared-module/storage/__init__.h" +#include "supervisor/filesystem.h" +#include "supervisor/port.h" +#include "supervisor/shared/reload.h" + +#include +LOG_MODULE_REGISTER(cpusb, CONFIG_LOG_DEFAULT_LEVEL); + +#define USB_DEVICE DT_NODELABEL(zephyr_udc0) + +// usbd_register_class() below names the CDC ACM classes "cdc_acm_", where +// n is the devicetree instance number. A board or bootloader overlay that +// adds its own cdc-acm-uart node renumbers them, so check that instance 0 is +// the console and instance 1 the data port. +BUILD_ASSERT(DT_SAME_NODE(DT_INST(0, zephyr_cdc_acm_uart), DT_NODELABEL(cdc_acm_console)), + "CDC ACM instance 0 must be cdc_acm_console"); +BUILD_ASSERT(DT_SAME_NODE(DT_INST(1, zephyr_cdc_acm_uart), DT_NODELABEL(cdc_acm_data)), + "CDC ACM instance 1 must be cdc_acm_data"); + +USBD_DEVICE_DEFINE(main_usbd, + DEVICE_DT_GET(DT_NODELABEL(zephyr_udc0)), + USB_VID, USB_PID); + +USBD_DESC_LANG_DEFINE(main_lang); +USBD_DESC_MANUFACTURER_DEFINE(main_mfr, USB_MANUFACTURER); +USBD_DESC_PRODUCT_DEFINE(main_product, USB_PRODUCT); +// The stack fills this from hwinfo and fails the request without a driver. +#if defined(CONFIG_HWINFO_HAS_DRIVER) +USBD_DESC_SERIAL_NUMBER_DEFINE(main_sn); #endif -#define USB_DEVICE DT_NODELABEL(USB_NAME) +USBD_DESC_CONFIG_DEFINE(fs_cfg_desc, "FS Configuration"); +USBD_DESC_CONFIG_DEFINE(hs_cfg_desc, "HS Configuration"); + +/* doc configuration instantiation start */ +static const uint8_t attributes = 0; -#ifdef UDC_IRQ_NAME -#define UDC_IRQ DT_IRQ_BY_NAME(USB_DEVICE, UDC_IRQ_NAME, irq) -#define UDC_IRQ_PRI DT_IRQ_BY_NAME(USB_DEVICE, UDC_IRQ_NAME, priority) -#else -#define UDC_IRQ DT_IRQ(USB_DEVICE, irq) -#define UDC_IRQ_PRI DT_IRQ(USB_DEVICE, priority) +USBD_CONFIGURATION_DEFINE(main_fs_config, + attributes, + 100, &fs_cfg_desc); + +USBD_CONFIGURATION_DEFINE(main_hs_config, + attributes, + 100, &hs_cfg_desc); + +static usb_cdc_serial_obj_t usb_cdc_console_obj; +static usb_cdc_serial_obj_t usb_cdc_data_obj; + +#ifndef USBD_DEFINE_MSC_LUN +#error "MSC not enabled" #endif -PINCTRL_DT_DEFINE(USB_DEVICE); -static const struct pinctrl_dev_config *usb_pcfg = - PINCTRL_DT_DEV_CONFIG_GET(USB_DEVICE); +#define LUN_COUNT 1 +#define MSC_FLASH_BLOCK_SIZE 512 + +// The ellipsis range in the designated initializer of `ejected` is not standard C, +// but it works in both gcc and clang. +static bool locked[LUN_COUNT] = { [0 ... (LUN_COUNT - 1)] = false}; + +// Set to true if a write was in a file data or metadata area, +// as opposed to in the filesystem metadata area (e.g., dirty bit). +// Used to determine if an auto-reload is warranted. +static bool content_write[LUN_COUNT] = { [0 ... (LUN_COUNT - 1)] = false}; + +int _zephyr_disk_init(struct disk_info *disk); +int _zephyr_disk_status(struct disk_info *disk); +int _zephyr_disk_read(struct disk_info *disk, uint8_t *data_buf, uint32_t start_sector, uint32_t num_sector); +int _zephyr_disk_write(struct disk_info *disk, const uint8_t *data_buf, uint32_t start_sector, uint32_t num_sector); +int _zephyr_disk_ioctl(struct disk_info *disk, uint8_t cmd, void *buff); +static bool msc_enabled(void); + +static const struct disk_operations disk_ops = { + .init = _zephyr_disk_init, + .status = _zephyr_disk_status, + .read = _zephyr_disk_read, + .write = _zephyr_disk_write, + .ioctl = _zephyr_disk_ioctl, +}; -#if CFG_TUSB_MCU == OPT_MCU_NRF5X -// Value is chosen to be as same as NRFX_POWER_USB_EVT_* in nrfx_power.h -enum { - USB_EVT_DETECTED = 0, - USB_EVT_REMOVED = 1, - USB_EVT_READY = 2 +static struct disk_info circuitpy_disk = { + .name = "CIRCUITPY", + .ops = &disk_ops, + .dev = NULL }; -#ifdef NRF5340_XXAA - #define LFCLK_SRC_RC CLOCK_LFCLKSRC_SRC_LFRC - #define VBUSDETECT_Msk USBREG_USBREGSTATUS_VBUSDETECT_Msk - #define OUTPUTRDY_Msk USBREG_USBREGSTATUS_OUTPUTRDY_Msk - #define GPIOTE_IRQn GPIOTE1_IRQn -#else - #define LFCLK_SRC_RC CLOCK_LFCLKSRC_SRC_RC - #define VBUSDETECT_Msk POWER_USBREGSTATUS_VBUSDETECT_Msk - #define OUTPUTRDY_Msk POWER_USBREGSTATUS_OUTPUTRDY_Msk -#endif +USBD_DEFINE_MSC_LUN(circuitpy_lun, "CIRCUITPY", "Zephyr", "FlashDisk", "0.00"); -// tinyusb function that handles power event (detected, ready, removed) -// We must call it within SD's SOC event handler, or set it as power event handler if SD is not enabled. -extern void tusb_hal_nrf_power_event(uint32_t event); -// nrf power callback, could be unused if SD is enabled or usb is disabled (board_test example) -TU_ATTR_UNUSED static void power_event_handler(nrfx_power_usb_evt_t event) { - tusb_hal_nrf_power_event((uint32_t)event); +int _zephyr_disk_init(struct disk_info *disk) { + printk("Initializing disk\n"); + return 0; } -#endif -void init_usb_hardware(void) { - #if CFG_TUSB_MCU == OPT_MCU_RAXXX - #if !USBHS_PHY_CLOCK_SOURCE_IS_XTAL - if (data->udc_cfg.usb_speed == USBD_SPEED_HS) { - LOG_ERR("High-speed operation is not supported in case PHY clock source is not " - "XTAL"); - return; +// We don't check whether the filesystem is littlefs below because we know these +// are APIs used by USB MSC and we enforce it to be FAT at build time. +int _zephyr_disk_status(struct disk_info *disk) { + supervisor_vfs_t *root_vfs = filesystem_circuitpy(); + fs_user_mount_t *root = root_vfs == NULL ? NULL : &root_vfs->fat; + int lun = 0; + if (!msc_enabled()) { + return DISK_STATUS_NOMEDIA; + } + if (root == NULL) { + printk("Status: No media\n"); + return DISK_STATUS_NOMEDIA; + } + if (!filesystem_is_writable_by_usb(root)) { + printk("Status: Read-only\n"); + return DISK_STATUS_WR_PROTECT; + } + // Lock the blockdev once we say we're writable. + if (!locked[lun] && !blockdev_lock((supervisor_vfs_t *)root)) { + printk("Status: Locked\n"); + return DISK_STATUS_WR_PROTECT; + } + locked[lun] = true; + return DISK_STATUS_OK; +} + +int _zephyr_disk_read(struct disk_info *disk, uint8_t *data_buf, uint32_t start_sector, uint32_t num_sector) { + supervisor_vfs_t *root_vfs = filesystem_circuitpy(); + fs_user_mount_t *root = root_vfs == NULL ? NULL : &root_vfs->fat; + + uint32_t disk_block_count; + disk_ioctl(root, GET_SECTOR_COUNT, &disk_block_count); + + if (start_sector + num_sector > disk_block_count) { + return -EIO; } + disk_read(root, data_buf, start_sector, num_sector); + return 0; +} + +int _zephyr_disk_write(struct disk_info *disk, const uint8_t *data_buf, uint32_t start_sector, uint32_t num_sector) { + supervisor_vfs_t *root_vfs = filesystem_circuitpy(); + fs_user_mount_t *root = root_vfs == NULL ? NULL : &root_vfs->fat; + int lun = 0; + autoreload_suspend(AUTORELOAD_SUSPEND_USB); + disk_write(root, data_buf, start_sector, num_sector); + // Since by getting here we assume the mount is read-only to + // CircuitPython let's update the cached FatFs sector if it's the one + // we just wrote. + if + #if FF_MAX_SS != FF_MIN_SS + (root->fatfs.ssize == MSC_FLASH_BLOCK_SIZE) + #else + // The compiler can optimize this away. + (FF_MAX_SS == FILESYSTEM_BLOCK_SIZE) #endif + { + if (start_sector == root->fatfs.winsect && start_sector > 0) { + memcpy(root->fatfs.win, + data_buf + MSC_FLASH_BLOCK_SIZE * (root->fatfs.winsect - start_sector), + MSC_FLASH_BLOCK_SIZE); + } + } + + // A write to an lba below fatbase is in the filesystem metadata (BPB) area or the "Reserved Region", + // and is probably setting or clearing the dirty bit. This should not trigger auto-reload. + // All other writes will trigger auto-reload. + if (start_sector >= root->fatfs.fatbase) { + content_write[lun] = true; + } + return 0; +} + +int _zephyr_disk_ioctl(struct disk_info *disk, uint8_t cmd, void *buff) { + + supervisor_vfs_t *root_vfs = filesystem_circuitpy(); + fs_user_mount_t *root = root_vfs == NULL ? NULL : &root_vfs->fat; + int lun = 0; + switch (cmd) { + case DISK_IOCTL_GET_SECTOR_COUNT: + disk_ioctl(root, GET_SECTOR_COUNT, buff); + return 0; + case DISK_IOCTL_GET_SECTOR_SIZE: + disk_ioctl(root, GET_SECTOR_SIZE, buff); + return 0; + case DISK_IOCTL_CTRL_SYNC: + // Zephyr's MSC class sends this after every WRITE10. Don't flush + // here; the background flush writes the cached page. + autoreload_resume(AUTORELOAD_SUSPEND_USB); + + // This write is complete; initiate an autoreload if this was a file data or metadata write, + // not just a dirty-bit write. + if (content_write[lun] && lun == 0) { + autoreload_trigger(); + content_write[lun] = false; + } + return 0; + default: + printk("Unsupported disk ioctl %02x\n", cmd); + return -ENOTSUP; + } + return 0; +} - R_ICU->IELSR[UDC_IRQ] = ELC_EVENT_USBHS_USB_INT_RESUME; +// Tracks whether the USB host has selected a configuration, i.e. the device has +// enumerated. Written from the USBD message callback (USBD thread or system +// workqueue context) and read from the CircuitPython VM thread, so keep it +// volatile to avoid the compiler caching stale values. +static volatile bool usb_configured = false; + +// Whether the CIRCUITPY MSC drive is enabled (storage.disable_usb_drive() clears it). +static bool msc_enabled(void) { + #if CIRCUITPY_USB_MSC && CIRCUITPY_STORAGE + return storage_usb_enabled(); + #else + return false; #endif +} +// Release the USB MSC lock on CIRCUITPY, if disk status took it. Other holders are not touched. +void usb_msc_release_circuitpy_lock(void) { + if (!locked[0]) { + return; + } + supervisor_vfs_t *circuitpy = filesystem_circuitpy(); + if (circuitpy != NULL) { + blockdev_unlock(circuitpy); + } + locked[0] = false; +} - IRQ_CONNECT(UDC_IRQ, UDC_IRQ_PRI, usb_irq_handler, 0, 0); +// Whether USB MSC holds the blockdev lock on this mount. +bool usb_msc_holds_lock(fs_user_mount_t *vfs) { + supervisor_vfs_t *circuitpy = filesystem_circuitpy(); + return locked[0] && circuitpy != NULL && &circuitpy->fat == vfs; +} - /* Configure USB GPIOs */ - int err = pinctrl_apply_state(usb_pcfg, PINCTRL_STATE_DEFAULT); - if (err < 0) { - printk("USB pinctrl setup failed (%d)\n", err); - } else { - printk("USB pins setup\n"); +// Zephyr's MSC reports the LUN state on every TEST UNIT READY, so there is no eject state to reset. +void usb_msc_remount(fs_user_mount_t *fs_mount) { + (void)fs_mount; +} + +static const struct device *const console_dev = DEVICE_DT_GET(DT_NODELABEL(cdc_acm_console)); +static bool console_dtr = false; +static bool usb_suspended = false; + +// With flow control on, the CDC ACM driver's poll_out waits for room in its +// TX buffer instead of dropping output. Use it for the console only while +// the host is connected, awake and holds DTR, as TinyUSB does. +static void update_console_flow_control(void) { + bool on = usb_configured && !usb_suspended && console_dtr; + struct uart_config config = { + .flow_ctrl = on ? UART_CFG_FLOW_CTRL_RTS_CTS : UART_CFG_FLOW_CTRL_NONE, + }; + uart_configure(console_dev, &config); +} + +// First enabled CDC, as on TinyUSB ports. +static const struct device *touch_cdc; + +static bool touch_requested(void) { + uint32_t baudrate = 0; + uint32_t dtr = 1; + if (uart_line_ctrl_get(touch_cdc, UART_LINE_CTRL_BAUD_RATE, &baudrate) != 0 || + uart_line_ctrl_get(touch_cdc, UART_LINE_CTRL_DTR, &dtr) != 0) { + return false; } + return baudrate == 1200 && dtr == 0; +} -// #ifdef USB_DRD_FS -// // STM32U535/STM32U545 +static void _msg_cb(struct usbd_context *const ctx, const struct usbd_msg *msg) { + LOG_INF("USBD message: %s", usbd_msg_type_string(msg->type)); + + if (usbd_can_detect_vbus(ctx)) { + if (msg->type == USBD_MSG_VBUS_READY) { + usb_configured = false; + if (usbd_enable(ctx)) { + LOG_ERR("Failed to enable device support"); + } + } + + if (msg->type == USBD_MSG_VBUS_REMOVED) { + usb_configured = false; + if (usbd_disable(ctx)) { + LOG_ERR("Failed to disable device support"); + } + } + } -// /* Enable USB power on Pwrctrl CR2 register */ -// HAL_PWREx_EnableVddUSB(); + // A non-zero configuration value means the host has enumerated us. + // A value of zero (or a bus reset / VBUS removal) unconfigures us. + if (msg->type == USBD_MSG_CONFIGURATION) { + usb_configured = (msg->status != 0); + } else if (msg->type == USBD_MSG_RESET) { + usb_configured = false; + } -// /* USB clock enable */ -// __HAL_RCC_USB_FS_CLK_ENABLE(); + if (msg->type == USBD_MSG_SUSPEND) { + usb_suspended = true; + } else if (msg->type == USBD_MSG_RESUME || msg->type == USBD_MSG_RESET) { + usb_suspended = false; + } + if (msg->type == USBD_MSG_RESET) { + console_dtr = false; + } else if (msg->type == USBD_MSG_CDC_ACM_CONTROL_LINE_STATE && msg->dev == console_dev) { + uint32_t dtr = 0; + uart_line_ctrl_get(console_dev, UART_LINE_CTRL_DTR, &dtr); + console_dtr = dtr != 0; + } + update_console_flow_control(); + + // 1200 baud + DTR low, in either order. + if ((msg->type == USBD_MSG_CDC_ACM_LINE_CODING || + msg->type == USBD_MSG_CDC_ACM_CONTROL_LINE_STATE) && + msg->dev == touch_cdc && touch_requested()) { + // Detach so the host sees a disconnect. + usbd_disable(&main_usbd); + reset_to_bootloader(); + } +} -// #endif +void usb_init(void) { + printk("Initializing USB\n"); + int err; + + printk("Adding language descriptor\n"); + err = usbd_add_descriptor(&main_usbd, &main_lang); + if (err) { + LOG_ERR("Failed to initialize language descriptor (%d)", err); + return; + } - #if CFG_TUSB_MCU == OPT_MCU_STM32U5 && defined(USB_OTG_FS) - /* Enable USB power on Pwrctrl CR2 register */ - // HAL_PWREx_EnableVddUSB(); - LL_PWR_EnableVddUSB(); + err = usbd_add_descriptor(&main_usbd, &main_mfr); + if (err) { + LOG_ERR("Failed to initialize manufacturer descriptor (%d)", err); + return; + } - /* USB clock enable */ - __HAL_RCC_USB_OTG_FS_CLK_ENABLE(); + err = usbd_add_descriptor(&main_usbd, &main_product); + if (err) { + LOG_ERR("Failed to initialize product descriptor (%d)", err); + return; + } + #if defined(CONFIG_HWINFO_HAS_DRIVER) + err = usbd_add_descriptor(&main_usbd, &main_sn); + if (err) { + LOG_ERR("Failed to initialize serial number descriptor (%d)", err); + return; + } #endif -// #ifdef USB_OTG_HS -// // STM59x/Ax/Fx/Gx only have 1 USB HS port + bool console = usb_cdc_console_enabled(); + if (console) { + uint8_t *receiver_buffer = port_malloc(1024, true); + if (receiver_buffer != NULL) { + common_hal_usb_cdc_serial_construct_from_device(&usb_cdc_console_obj, DEVICE_DT_GET(DT_NODELABEL(cdc_acm_console)), 1024, receiver_buffer, true); + } else { + console = false; + } + } + usb_cdc_set_console(console ? MP_OBJ_FROM_PTR(&usb_cdc_console_obj) : mp_const_none); + + bool data = usb_cdc_data_enabled(); + if (data) { + uint8_t *receiver_buffer = port_malloc(1024, true); + if (receiver_buffer != NULL) { + common_hal_usb_cdc_serial_construct_from_device(&usb_cdc_data_obj, DEVICE_DT_GET(DT_NODELABEL(cdc_acm_data)), 1024, receiver_buffer, false); + } else { + data = false; + } + } + usb_cdc_set_data(data ? MP_OBJ_FROM_PTR(&usb_cdc_data_obj) : mp_const_none); -// #if CFG_TUSB_OS == OPT_OS_FREERTOS -// // If freeRTOS is used, IRQ priority is limit by max syscall ( smaller is higher ) -// NVIC_SetPriority(OTG_HS_IRQn, configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY); -// #endif + err = disk_access_register(&circuitpy_disk); + if (err) { + printk("Failed to register disk access %d\n", err); + return; + } -// /* USB clock enable */ -// __HAL_RCC_USB_OTG_HS_CLK_ENABLE(); -// __HAL_RCC_USBPHYC_CLK_ENABLE(); + if (USBD_SUPPORTS_HIGH_SPEED && + usbd_caps_speed(&main_usbd) == USBD_SPEED_HS) { + printk("Adding High-Speed configuration\n"); + err = usbd_add_configuration(&main_usbd, USBD_SPEED_HS, + &main_hs_config); + if (err) { + LOG_ERR("Failed to add High-Speed configuration"); + return; + } + + printk("Registering High-Speed cdc_acm class\n"); + if (usb_cdc_console_enabled()) { + err = usbd_register_class(&main_usbd, "cdc_acm_0", USBD_SPEED_HS, 1); + if (err) { + printk("Failed to add register classes %d\n", err); + return; + } + } + + if (usb_cdc_data_enabled()) { + err = usbd_register_class(&main_usbd, "cdc_acm_1", USBD_SPEED_HS, 1); + if (err) { + printk("Failed to add register classes %d\n", err); + return; + } + } + + if (msc_enabled()) { + err = usbd_register_class(&main_usbd, "msc_0", USBD_SPEED_HS, 1); + if (err) { + return; + } + } + + #if CIRCUITPY_USB_HID + if (usb_hid_enabled()) { + printk("Registering High-Speed hid class\n"); + err = usbd_register_class(&main_usbd, "hid_0", USBD_SPEED_HS, 1); + if (err) { + printk("Failed to register HID class (HS) %d\n", err); + return; + } + } + #endif -// /* Enable USB power on Pwrctrl CR2 register */ -// HAL_PWREx_EnableVddUSB(); -// HAL_PWREx_EnableUSBHSTranceiverSupply(); + usbd_device_set_code_triple(&main_usbd, USBD_SPEED_HS, + USB_BCC_MISCELLANEOUS, 0x02, 0x01); + } -// /*Configuring the SYSCFG registers OTG_HS PHY*/ -// HAL_SYSCFG_EnableOTGPHY(SYSCFG_OTG_HS_PHY_ENABLE); + /* doc configuration register start */ + printk("Adding Full-Speed configuration\n"); + err = usbd_add_configuration(&main_usbd, USBD_SPEED_FS, + &main_fs_config); + if (err) { + LOG_ERR("Failed to add Full-Speed configuration"); + return; + } + /* doc configuration register end */ -// // Disable VBUS sense (B device) -// USB_OTG_HS->GCCFG &= ~USB_OTG_GCCFG_VBDEN; + /* doc functions register start */ -// // B-peripheral session valid override enable -// USB_OTG_HS->GCCFG |= USB_OTG_GCCFG_VBVALEXTOEN; -// USB_OTG_HS->GCCFG |= USB_OTG_GCCFG_VBVALOVAL; -// #endif // USB_OTG_FS + if (usb_cdc_console_enabled()) { + printk("Registering Full-Speed cdc_acm class\n"); + err = usbd_register_class(&main_usbd, "cdc_acm_0", USBD_SPEED_FS, 1); + if (err) { + printk("Failed to add register classes\n"); + return; + } + } + if (usb_cdc_data_enabled()) { + printk("Registering Full-Speed cdc_acm class\n"); + err = usbd_register_class(&main_usbd, "cdc_acm_1", USBD_SPEED_FS, 1); + if (err) { + printk("Failed to add register classes\n"); + return; + } + } - #if CFG_TUSB_MCU == OPT_MCU_NRF5X - #ifdef CONFIG_HAS_HW_NRF_USBREG - /* Use CLOCK/POWER priority for compatibility with other series where - * USB events are handled by CLOCK interrupt handler. - */ - IRQ_CONNECT(USBREGULATOR_IRQn, - DT_IRQ(DT_INST(0, nordic_nrf_clock), priority), - nrfx_isr, nrfx_usbreg_irq_handler, 0); - irq_enable(USBREGULATOR_IRQn); - #endif - // USB power may already be ready at this time -> no event generated - // We need to invoke the handler based on the status initially - uint32_t usb_reg; - { - // Power module init - static const nrfx_power_config_t pwr_cfg = { - .dcdcen = (DT_PROP(DT_INST(0, nordic_nrf5x_regulator), regulator_initial_mode) - == NRF5X_REG_MODE_DCDC), - #if NRFX_POWER_SUPPORTS_DCDCEN_VDDH - .dcdcenhv = COND_CODE_1(CONFIG_SOC_SERIES_NRF52X, - (DT_NODE_HAS_STATUS_OKAY(DT_INST(0, nordic_nrf52x_regulator_hv))), - (DT_NODE_HAS_STATUS_OKAY(DT_INST(0, nordic_nrf53x_regulator_hv)))), - #endif - }; - nrfx_power_init(&pwr_cfg); - - // Register tusb function as USB power handler - // cause cast-function-type warning - const nrfx_power_usbevt_config_t config = {.handler = power_event_handler}; - nrfx_power_usbevt_init(&config); - nrfx_power_usbevt_enable(); - - // USB power may already be ready at this time -> no event generated - // We need to invoke the handler based on the status initially - #ifdef NRF5340_XXAA - usb_reg = NRF_USBREGULATOR->USBREGSTATUS; - #else - usb_reg = NRF_POWER->USBREGSTATUS; - #endif + if (msc_enabled()) { + err = usbd_register_class(&main_usbd, "msc_0", USBD_SPEED_FS, 1); + if (err) { + return; + } } + /* doc functions register end */ + + #if CIRCUITPY_USB_HID + if (usb_hid_enabled()) { + printk("Registering Full-Speed hid class\n"); + err = usbd_register_class(&main_usbd, "hid_0", USBD_SPEED_FS, 1); + if (err) { + printk("Failed to register HID class (FS) %d\n", err); + return; + } + } + #endif + + usbd_device_set_code_triple(&main_usbd, USBD_SPEED_FS, + USB_BCC_MISCELLANEOUS, 0x02, 0x01); + printk("Setting self powered\n"); + usbd_self_powered(&main_usbd, attributes & USB_SCD_SELF_POWERED); - if (usb_reg & VBUSDETECT_Msk) { - tusb_hal_nrf_power_event(USB_EVT_DETECTED); + if (usb_cdc_console_enabled()) { + touch_cdc = DEVICE_DT_GET(DT_NODELABEL(cdc_acm_console)); + } else if (usb_cdc_data_enabled()) { + touch_cdc = DEVICE_DT_GET(DT_NODELABEL(cdc_acm_data)); } - if (usb_reg & OUTPUTRDY_Msk) { - tusb_hal_nrf_power_event(USB_EVT_READY); + + printk("Registering callback\n"); + err = usbd_msg_register_cb(&main_usbd, _msg_cb); + if (err) { + LOG_ERR("Failed to register message callback"); + return; } - printk("usb started hopefully\n"); + #if CIRCUITPY_USB_HID + printk("Initializing HID\n"); + usb_hid_init_devices(); #endif + printk("usbd_init\n"); + err = usbd_init(&main_usbd); + if (err) { + LOG_ERR("Failed to initialize device support (%d)", err); + return; + } + + printk("USB initialized\n"); + + if (!usbd_can_detect_vbus(&main_usbd)) { + /* No VBUS detection — just enable unconditionally. */ + err = usbd_enable(&main_usbd); + if (err) { + LOG_ERR("Failed to enable device support (%d)", err); + return; + } + } else { + #if DT_HAS_COMPAT_STATUS_OKAY(nordic_nrf_usbd) + /* + * On nRF52 USBD, the UDC driver enables VBUS detection interrupts + * inside usbd_init(). If USB is already plugged in, the VBUS_READY + * event arrives before usbd_init() sets status.initialized = true, + * causing a __ASSERT in usbd_thread (with CONFIG_ASSERT=y) that kills + * the event-processing thread. Our _msg_cb then never receives + * VBUS_READY, and USB never enumerates. + * + * Work around the race by checking the current VBUS state directly. + * udc_nrf_enable() does not require VBUS to be present, so it's safe + * to call usbd_enable() if VBUS is already up. + */ + nrfx_power_usb_state_t vbus = nrfx_power_usbstatus_get(); + if (vbus != NRFX_POWER_USB_STATE_DISCONNECTED) { + err = usbd_enable(&main_usbd); + if (err) { + LOG_ERR("Failed to enable device support (%d)", err); + return; + } + } + #else + /* + * On nRF54 USBHS, VBUS events arrive via NRFS IPC which has a natural + * startup delay, so the assert race doesn't occur. Additionally, + * udc_enable() blocks until VBUS is ready, so we must NOT call + * usbd_enable() here — let _msg_cb handle it on VBUS_READY. + */ + #endif + } +} + +bool usb_connected(void) { + // Mirrors TinyUSB's tud_ready(): configured (mounted) and not suspended. + return usb_configured && !usbd_is_suspended(&main_usbd); +} + +void usb_disconnect(void) { +} + +usb_cdc_serial_obj_t *usb_cdc_serial_get_console(void) { + if (usb_cdc_console_enabled()) { + return &usb_cdc_console_obj; + } + return NULL; } diff --git a/ports/zephyr-cp/supervisor/zephyr-cp.h b/ports/zephyr-cp/supervisor/zephyr-cp.h new file mode 100644 index 00000000000..ecf7d42e3b4 --- /dev/null +++ b/ports/zephyr-cp/supervisor/zephyr-cp.h @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/usb_cdc/Serial.h" + +usb_cdc_serial_obj_t *usb_cdc_serial_get_console(void); diff --git a/ports/zephyr-cp/sysbuild.cmake b/ports/zephyr-cp/sysbuild.cmake index f0968e05b5c..e7de682bc77 100644 --- a/ports/zephyr-cp/sysbuild.cmake +++ b/ports/zephyr-cp/sysbuild.cmake @@ -13,9 +13,6 @@ if(SB_CONFIG_NET_CORE_IMAGE_HCI_IPC) BOARD ${SB_CONFIG_NET_CORE_BOARD} ) - set(${NET_APP}_CONF_FILE - ${NET_APP_SRC_DIR}/nrf5340_cpunet_iso-bt_ll_sw_split.conf - CACHE INTERNAL "" - ) - + native_simulator_set_child_images(${DEFAULT_IMAGE} ${NET_APP}) + native_simulator_set_final_executable(${DEFAULT_IMAGE}) endif() diff --git a/ports/zephyr-cp/sysbuild.conf b/ports/zephyr-cp/sysbuild.conf index e69de29bb2d..84f34aa4bfb 100644 --- a/ports/zephyr-cp/sysbuild.conf +++ b/ports/zephyr-cp/sysbuild.conf @@ -0,0 +1,2 @@ +# Board-specific MCUboot settings are applied conditionally +# via SB_EXTRA_CONF_FILE in sysbuild/CMakeLists.txt. diff --git a/ports/zephyr-cp/sysbuild/CMakeLists.txt b/ports/zephyr-cp/sysbuild/CMakeLists.txt new file mode 100644 index 00000000000..4df7396f57a --- /dev/null +++ b/ports/zephyr-cp/sysbuild/CMakeLists.txt @@ -0,0 +1,35 @@ +# Resolve board aliases before sysbuild runs, so BOARD is the canonical Zephyr +# board id when we derive board-specific file names from it below. +include(${CMAKE_CURRENT_LIST_DIR}/../boards/board_aliases.cmake) + +# Partitioning and bootloader policy are owned by the mcuboot fork +# (bootloader/mcuboot, see its dts/README.md): as a sysbuild module it applies +# dts//.dtsi to both the application and bootloader images and +# defaults SB_CONFIG_BOOTLOADER_* per board. What is left here is CircuitPython's +# own bootloader UI configuration. +set(cp_boards_dir ${CMAKE_CURRENT_LIST_DIR}/../boards) +string(REGEX REPLACE "[@/].*" "" board_name "${BOARD}") + +# Common MCUboot conf (UF2, double-tap, etc.) plus optional board fragment. +# Unused unless a mcuboot image is built for this board. +set(mcuboot_confs ${CMAKE_CURRENT_LIST_DIR}/mcuboot.conf) +if(EXISTS ${cp_boards_dir}/mcuboot_${board_name}.conf) + list(APPEND mcuboot_confs ${cp_boards_dir}/mcuboot_${board_name}.conf) +endif() +set(mcuboot_EXTRA_CONF_FILE "${mcuboot_confs}" + CACHE INTERNAL "MCUboot conf fragments" +) + +# Escape hatch for board defaults we disagree with, e.g. forcing +# SB_CONFIG_BOOTLOADER_NONE=y on a board whose own Kconfig.sysbuild turns MCUboot +# on. Board Kconfig is parsed before module Kconfig, so the fork's defaults +# cannot express this. +if(EXISTS ${cp_boards_dir}/sysbuild_${board_name}.conf) + set(SB_EXTRA_CONF_FILE ${cp_boards_dir}/sysbuild_${board_name}.conf + CACHE INTERNAL "Board sysbuild override" + ) +endif() + +find_package(Sysbuild REQUIRED HINTS $ENV{ZEPHYR_BASE}) + +project(sysbuild LANGUAGES) diff --git a/ports/zephyr-cp/sysbuild/hci_ipc.conf b/ports/zephyr-cp/sysbuild/hci_ipc.conf new file mode 100644 index 00000000000..c86f0192f37 --- /dev/null +++ b/ports/zephyr-cp/sysbuild/hci_ipc.conf @@ -0,0 +1,39 @@ +# Enable dynamic TX power control so that BT_HCI_OP_VS_WRITE_TX_POWER_LEVEL +# is supported by the controller. +CONFIG_BT_CTLR_TX_PWR_DYNAMIC_CONTROL=y + +# The rest matches the controller Zephyr v4.5.0 built from +# samples/bluetooth/hci_ipc/extra-cis-bt_ll_sw_split.conf, minus connected ISO, +# which CircuitPython does not use. Only lines that change the result are kept. + +# Three links, 251 byte data length, extended advertising and scanning. +CONFIG_BT_MAX_CONN=3 +CONFIG_BT_EXT_ADV=y +CONFIG_BT_BUF_EVT_RX_COUNT=16 +CONFIG_BT_BUF_ACL_RX_SIZE=255 +CONFIG_BT_BUF_ACL_TX_SIZE=251 +CONFIG_BT_CTLR_RX_BUFFERS=9 +CONFIG_BT_CTLR_DATA_LENGTH_MAX=251 +CONFIG_BT_CTLR_ADV_SET=3 +CONFIG_BT_CTLR_ADV_DATA_LEN_MAX=191 +CONFIG_BT_CTLR_ADV_DATA_BUF_MAX=6 +CONFIG_BT_CTLR_SCAN_DATA_LEN_MAX=1650 +CONFIG_BT_CTLR_SCAN_AUX_SET=3 +CONFIG_BT_CTLR_LLCP_LOCAL_PROC_CTX_BUF_NUM=6 + +# Controller scheduling. +CONFIG_ISR_STACK_SIZE=1536 +CONFIG_BT_CTLR_ADVANCED_FEATURES=y +CONFIG_BT_CTLR_ADV_AUX_PDU_BACK2BACK=y +CONFIG_BT_CTLR_LOW_LAT_ULL=y +CONFIG_BT_CTLR_ADV_RESERVE_MAX=n +CONFIG_BT_CTLR_CENTRAL_RESERVE_MAX=n +CONFIG_BT_CTLR_PERIPHERAL_RESERVE_MAX=n +CONFIG_BT_CTLR_SLOT_RESERVATION_UPDATE=n +CONFIG_BT_CTLR_SCAN_UNRESERVED=y +CONFIG_BT_TICKER_EXT_SLOT_WINDOW_YIELD=y + +# Test mode and controller fault reporting. +CONFIG_BT_CTLR_DTM_HCI=y +CONFIG_BT_CTLR_ASSERT_HANDLER=y +CONFIG_BT_HCI_VS_FATAL_ERROR=y diff --git a/ports/zephyr-cp/sysbuild/mcuboot.conf b/ports/zephyr-cp/sysbuild/mcuboot.conf new file mode 100644 index 00000000000..10f2636c4d9 --- /dev/null +++ b/ports/zephyr-cp/sysbuild/mcuboot.conf @@ -0,0 +1,28 @@ +# Emit the bootloader image as a .hex as well: the port's Makefile merges +# mcuboot/zephyr/zephyr.hex with the signed app hex into firmware.hex, so the +# whole (bootloader + app) image can be programmed with a single file. +CONFIG_BUILD_OUTPUT_HEX=y + +# Bootloader-image settings that apply to every board. Bootloader *policy* +# (UF2 vs UART serial recovery, entrance methods, SPI NOR for slot1's device, +# per-board logging to fit small boot partitions) is owned by the mcuboot +# fork (bootloader/mcuboot): its Kconfig defaults decide UF2 vs serial from +# the devicetree's zephyr_udc0, and its conf//.conf fragments +# (applied to this image by boot/zephyr/sysbuild/CMakeLists.txt) layer board +# opt-ins on top. Assigning those symbols here would force one policy onto +# every board, including the USB-less ones that cannot run UF2. + +# The bootloader yields the CPU between image loads. +CONFIG_MAIN_THREAD_PRIORITY=0 + +# Heap for UF2 block tracking bitmap (sized from flash area at runtime) and +# other bootloader allocations. +CONFIG_HEAP_MEM_POOL_SIZE=4096 + +# Detailed USB and entrance logging for debugging (per-board conf fragments +# turn this off where the boot partition is too small for it). +CONFIG_LOG=y +CONFIG_MCUBOOT_LOG_LEVEL_DBG=y +# CONFIG_USBD_LOG_LEVEL_DBG=y +# CONFIG_UDC_DRIVER_LOG_LEVEL_DBG=y +# CONFIG_USBD_MSC_LOG_LEVEL_DBG=y diff --git a/ports/zephyr-cp/tests/TEST_IDEAS.md b/ports/zephyr-cp/tests/TEST_IDEAS.md new file mode 100644 index 00000000000..6ef71d7a5a0 --- /dev/null +++ b/ports/zephyr-cp/tests/TEST_IDEAS.md @@ -0,0 +1,623 @@ +# CircuitPython Simulator Test Ideas + +Test ideas for the native_sim simulator, organized by module/category. + +## Core Python / Interpreter + +### 1. Multiple file priority +Test that boot.py runs before code.py, and main.py is used as fallback when code.py doesn't exist. + +```python +# boot.py +print("boot.py ran") + +# code.py +print("code.py ran") +``` + +Expected output order: "boot.py ran" then "code.py ran" + +### 2. Exception handling +Verify tracebacks print correctly with file/line info, and exception types propagate properly. + +```python +def inner(): + raise ValueError("test error") + +def outer(): + inner() + +outer() +``` + +### 3. Memory / gc module +Test `gc.collect()`, `gc.mem_free()`, `gc.mem_alloc()`, and behavior under memory pressure. + +```python +import gc +gc.collect() +free_before = gc.mem_free() +data = [0] * 1000 +free_after = gc.mem_free() +assert free_after < free_before +del data +gc.collect() +free_final = gc.mem_free() +print("done") +``` + +### 4. Import system +Test importing frozen modules vs filesystem modules, verify import errors are clear. + +```python +import sys +import board +import digitalio +print(f"modules loaded: {len(sys.modules)}") +print("done") +``` + +--- + +## digitalio + +### 5. Input mode +Test reading GPIO input state. May require trace file injection or loopback configuration. + +```python +import board +import digitalio + +pin = digitalio.DigitalInOut(board.D0) +pin.direction = digitalio.Direction.INPUT +value = pin.value +print(f"input value: {value}") +print("done") +``` + +### 6. Pull resistors +Verify pull-up/pull-down configuration affects input readings. + +```python +import board +import digitalio + +pin = digitalio.DigitalInOut(board.D0) +pin.direction = digitalio.Direction.INPUT +pin.pull = digitalio.Pull.UP +value_up = pin.value +pin.pull = digitalio.Pull.DOWN +value_down = pin.value +print(f"pull-up: {value_up}, pull-down: {value_down}") +print("done") +``` + +### 7. Direction switching +Switch same pin between input/output modes multiple times. + +```python +import board +import digitalio + +pin = digitalio.DigitalInOut(board.D0) +pin.direction = digitalio.Direction.OUTPUT +pin.value = True +pin.direction = digitalio.Direction.INPUT +_ = pin.value +pin.direction = digitalio.Direction.OUTPUT +pin.value = False +print("done") +``` + +--- + +## time module + +### 8. time.sleep() precision +Verify sleep timing via Perfetto trace timestamps. Use GPIO transitions as timing markers. + +```python +import time +import board +import digitalio + +led = digitalio.DigitalInOut(board.LED) +led.direction = digitalio.Direction.OUTPUT + +led.value = True +time.sleep(0.05) # 50ms +led.value = False +time.sleep(0.1) # 100ms +led.value = True +time.sleep(0.05) # 50ms +led.value = False +print("done") +``` + +Verify trace shows: 50ms high, 100ms low, 50ms high pattern. + +### 9. time.monotonic() +Test monotonic clock increments correctly and never goes backward. + +```python +import time + +samples = [] +for _ in range(10): + samples.append(time.monotonic()) + time.sleep(0.01) + +# Verify monotonic increase +for i in range(1, len(samples)): + assert samples[i] > samples[i-1], "monotonic went backward!" + +elapsed = samples[-1] - samples[0] +assert 0.08 < elapsed < 0.15, f"unexpected elapsed: {elapsed}" +print("done") +``` + +### 10. time.localtime / struct_time +Test time structure operations if available. + +```python +import time + +t = time.localtime() +print(f"year: {t.tm_year}") +print(f"month: {t.tm_mon}") +print(f"day: {t.tm_mday}") +print("done") +``` + +--- + +## microcontroller + +### 11. microcontroller.cpu properties +Test frequency, temperature, UID properties. + +```python +import microcontroller + +print(f"frequency: {microcontroller.cpu.frequency}") +print(f"uid: {microcontroller.cpu.uid.hex()}") +print("done") +``` + +### 12. Safe mode +Trigger and verify safe mode entry (requires CONFIG_NATIVE_SIM_REBOOT=y). + +```python +import microcontroller +# This would trigger safe mode - test carefully +# microcontroller.on_next_reset(microcontroller.RunMode.SAFE_MODE) +# microcontroller.reset() +print("done") +``` + +### 13. Reset reason +Test microcontroller.reset_reason after various reset types. + +```python +import microcontroller + +reason = microcontroller.reset_reason +print(f"reset reason: {reason}") +print("done") +``` + +--- + +## os module + +### 14. os.uname() +Verify returns correct system info for native_sim. + +```python +import os + +info = os.uname() +print(f"sysname: {info.sysname}") +print(f"machine: {info.machine}") +print(f"release: {info.release}") +print("done") +``` + +### 15. Filesystem operations +Test os.listdir(), os.stat(), os.remove(). + +```python +import os + +# List root +files = os.listdir("/") +print(f"root files: {files}") + +# Stat a file +if "code.py" in files: + stat = os.stat("/code.py") + print(f"code.py size: {stat[6]}") + +print("done") +``` + +### 16. os.getenv() +Test environment variable reading. + +```python +import os + +# May return None if not set +path = os.getenv("PATH") +print(f"PATH exists: {path is not None}") +print("done") +``` + +--- + +## board module + +### 17. board.board_id +Verify board ID matches expected value. + +```python +import board + +print(f"board_id: {board.board_id}") +assert board.board_id == "native_native_sim" +print("done") +``` + +### 18. Pin availability +Test that board.LED and other defined pins exist. + +```python +import board + +assert hasattr(board, "LED"), "board.LED missing" +print(f"LED pin: {board.LED}") +print("done") +``` + +--- + +## Filesystem + +### 19. File read/write +Create, read, and modify files on CIRCUITPY. + +```python +# Write a test file +with open("/test.txt", "w") as f: + f.write("hello world") + +# Read it back +with open("/test.txt", "r") as f: + content = f.read() + +assert content == "hello world" +print("done") +``` + +### 20. Directory operations +Test mkdir, rmdir, nested paths. + +```python +import os + +# Create directory +os.mkdir("/testdir") +assert "testdir" in os.listdir("/") + +# Create file in directory +with open("/testdir/file.txt", "w") as f: + f.write("nested") + +# Clean up +os.remove("/testdir/file.txt") +os.rmdir("/testdir") +assert "testdir" not in os.listdir("/") +print("done") +``` + +### 21. Large file handling +Test with larger files approaching flash limits. + +```python +import gc + +# Write 10KB file +data = "x" * 10240 +with open("/large.txt", "w") as f: + f.write(data) + +# Verify size +import os +stat = os.stat("/large.txt") +assert stat[6] == 10240 + +# Clean up +os.remove("/large.txt") +gc.collect() +print("done") +``` + +--- + +## Error Conditions + +### 22. Syntax error in code.py +Verify graceful error message when code.py has syntax error. + +```python +# code.py with intentional syntax error: +def broken( + print("missing close paren" +``` + +Expected: Clear syntax error message with line number. + +### 23. Runtime error +Verify traceback format shows file, line, and function. + +```python +def cause_error(): + x = 1 / 0 + +cause_error() +``` + +Expected: Traceback showing ZeroDivisionError with line info. + +### 24. Keyboard interrupt +Test Ctrl+C handling via PTY if applicable. + +```python +import time + +print("starting long loop") +for i in range(100): + print(f"iteration {i}") + time.sleep(0.1) +print("done") +``` + +Send Ctrl+C during execution, verify clean KeyboardInterrupt. + +--- + +## busio (if emulation available) + +### 25. busio.UART +Basic UART operations if configured. + +```python +import board +import busio + +# Check if UART pins exist +if hasattr(board, "TX") and hasattr(board, "RX"): + uart = busio.UART(board.TX, board.RX, baudrate=115200) + uart.write(b"test") + uart.deinit() +print("done") +``` + +### 26. busio.I2C scan +Scan for emulated I2C devices. + +```python +import board +import busio + +if hasattr(board, "SCL") and hasattr(board, "SDA"): + i2c = busio.I2C(board.SCL, board.SDA) + while not i2c.try_lock(): + pass + devices = i2c.scan() + print(f"I2C devices: {[hex(d) for d in devices]}") + i2c.unlock() + i2c.deinit() +print("done") +``` + +### 27. busio.SPI +Basic SPI transfer to emulated device. + +```python +import board +import busio + +if hasattr(board, "SCK") and hasattr(board, "MOSI"): + spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=getattr(board, "MISO", None)) + while not spi.try_lock(): + pass + spi.configure(baudrate=1000000) + result = bytearray(4) + spi.write_readinto(b"\x00\x00\x00\x00", result) + spi.unlock() + spi.deinit() +print("done") +``` + +--- + +## Serial/PTY Input + +These tests require extending conftest.py to support writing to the PTY, not just reading. + +### 28. Basic serial input +Test reading single characters from serial via PTY write. + +```python +import sys + +print("ready") +char = sys.stdin.read(1) +print(f"received: {repr(char)}") +print("done") +``` + +**Test harness**: After seeing "ready", write "A" to PTY, verify output shows "received: 'A'". + +### 29. input() function +Test the built-in input() function with PTY input. + +```python +print("ready") +name = input("Enter name: ") +print(f"hello {name}") +print("done") +``` + +**Test harness**: After seeing "Enter name:", write "World\n" to PTY, verify "hello World". + +### 30. Serial line buffering +Test reading a complete line with newline termination. + +```python +import sys + +print("ready") +line = sys.stdin.readline() +print(f"got: {repr(line)}") +print("done") +``` + +**Test harness**: Write "test line\n" to PTY, verify complete line received. + +### 31. usb_cdc.console data read +Test reading from usb_cdc.console.data if available. + +```python +import usb_cdc + +print("ready") +if usb_cdc.console: + while not usb_cdc.console.in_waiting: + pass + data = usb_cdc.console.read(usb_cdc.console.in_waiting) + print(f"console got: {data}") +print("done") +``` + +**Test harness**: Write bytes to PTY, verify they're received via usb_cdc.console. + +### 32. REPL interaction +Test entering REPL mode and executing commands interactively. + +```python +# No code.py - boots to REPL +``` + +**Test harness**: +1. Boot with empty/no code.py to get REPL prompt +2. Write "1 + 1\r\n" to PTY +3. Verify output contains "2" +4. Write "print('hello')\r\n" +5. Verify output contains "hello" + +### 33. Ctrl+C interrupt via PTY +Test sending Ctrl+C (0x03) to interrupt running code. + +```python +import time + +print("starting") +for i in range(100): + print(f"loop {i}") + time.sleep(0.1) +print("completed") # Should not reach this +``` + +**Test harness**: +1. Wait for "loop 5" in output +2. Write b"\x03" (Ctrl+C) to PTY +3. Verify KeyboardInterrupt raised +4. Verify "completed" NOT in output + +### 34. Ctrl+D soft reload via PTY +Test sending Ctrl+D (0x04) to trigger soft reload. + +```python +print("first run") +import time +time.sleep(10) # Long sleep to allow interrupt +print("done") +``` + +**Test harness**: +1. Wait for "first run" +2. Write b"\x04" (Ctrl+D) to PTY +3. Verify code restarts (see "first run" again or reload message) + +### 35. Serial input timeout +Test behavior when waiting for input with timeout. + +```python +import sys +import select + +print("ready") +# Poll for input with timeout +readable, _, _ = select.select([sys.stdin], [], [], 0.5) +if readable: + data = sys.stdin.read(1) + print(f"got: {repr(data)}") +else: + print("timeout") +print("done") +``` + +**Test harness**: Don't send anything, verify "timeout" appears. + +--- + +## Fixture Changes for PTY Input + +The `run_circuitpython` fixture in conftest.py needs to be extended: + +```python +@dataclass +class SimulatorResult: + output: str + trace_file: Path + pty_write_fd: int # New: file descriptor for writing to PTY + +def _run(code: str | None, timeout: float = 5.0, ...) -> SimulatorResult: + # Open PTY for both read AND write + pty_fd = os.open(pty_path, os.O_RDWR | os.O_NONBLOCK) + # ... +``` + +Or provide a callback/queue mechanism: + +```python +def _run(code, timeout=5.0, input_sequence=None): + """ + input_sequence: list of (trigger_text, bytes_to_send) tuples + When trigger_text is seen in output, send bytes_to_send to PTY + """ +``` + +--- + +## Implementation Priority + +Suggested order for implementation: + +### Phase 1: Basic module tests (no fixture changes) +1. **#17 board.board_id** - Quick sanity check +2. **#14 os.uname()** - Tests another module, simple +3. **#9 time.monotonic()** - Core timing functionality +4. **#8 time.sleep() precision** - Builds on GPIO trace infrastructure +5. **#1 Multiple file priority** - Tests interpreter boot sequence +6. **#19 File read/write** - Tests filesystem layer +7. **#3 Memory / gc** - Tests memory management +8. **#2 Exception handling** - Tests error reporting + +### Phase 2: PTY input tests (requires fixture extension) +9. **#28 Basic serial input** - Foundation for all input tests +10. **#33 Ctrl+C interrupt** - Important for interactive use +11. **#29 input() function** - Common user pattern +12. **#32 REPL interaction** - Tests interactive mode diff --git a/ports/zephyr-cp/tests/__init__.py b/ports/zephyr-cp/tests/__init__.py new file mode 100644 index 00000000000..5357f20467d --- /dev/null +++ b/ports/zephyr-cp/tests/__init__.py @@ -0,0 +1,226 @@ +from pathlib import Path + +import serial +import subprocess +import threading +import time + + +class StdSerial: + def __init__(self, stdin, stdout): + self.stdin = stdin + self.stdout = stdout + + def read(self, amount=None): + data = self.stdout.read(amount) + if data == b"": + raise EOFError("stdout closed") + return data + + def write(self, buf): + if self.stdin is None: + return + self.stdin.write(buf) + self.stdin.flush() + + def close(self): + if self.stdin is not None: + self.stdin.close() + self.stdout.close() + + def read_some(self, limit=65536): + # read1() hands back whatever is already buffered and does at most one + # read on the pipe, so it blocks only when nothing has arrived yet. + data = self.stdout.read1(limit) + if data == b"": + raise EOFError("stdout closed") + return data + + @property + def in_waiting(self): + if self.stdout is None: + return 0 + return len(self.stdout.peek()) + + +class SerialSaver: + """Capture serial output in a background thread so output isn't missed.""" + + def __init__(self, serial_obj, name="serial"): + self.all_output = "" + self.all_input = "" + self.serial = serial_obj + self.name = name + + self._stop = threading.Event() + self._lock = threading.Lock() + self._cv = threading.Condition(self._lock) + self._read_some = getattr(serial_obj, "read_some", None) + self._reader = threading.Thread(target=self._reader_loop, daemon=True) + self._reader.start() + + def _reader_loop(self): + while not self._stop.is_set(): + try: + if self._read_some is not None: + read = self._read_some() + else: + read = self.serial.read(1) + # in_waiting is a non-blocking check on a real serial port, + # so draining it here is free. + waiting = self.serial.in_waiting + if waiting: + read += self.serial.read(waiting) + except Exception: + # Serial port closed or device disconnected. + break + + if read == b"": + # Timeout with no data — keep waiting. Only a real + # exception or an explicit stop should end the loop. + continue + + text = read.decode("utf-8", errors="replace") + with self._cv: + self.all_output += text + self._cv.notify_all() + in_waiting = 0 + try: + in_waiting = self.serial.in_waiting + except OSError: + pass + if in_waiting > 0: + self.all_output += self.serial.read().decode("utf-8", errors="replace") + + def wait_for(self, text, timeout=10): + with self._cv: + while text not in self.all_output and self._reader.is_alive(): + if not self._cv.wait(timeout=timeout): + break + if text not in self.all_output: + tail = self.all_output[-400:] + raise TimeoutError( + f"Timed out waiting for {text!r} on {self.name}. Output tail:\n{tail}" + ) + + def read(self, amount=None): + # Kept for compatibility with existing callers. + return + + def close(self): + if not self.serial: + return + + self._stop.set() + self._reader.join(timeout=1.0) + try: + self.serial.close() + except Exception: + pass + self.serial = None + + def write(self, text): + self.all_input += text + self.serial.write(text.encode("utf-8")) + + +class NativeSimProcess: + def __init__(self, cmd, timeout=5, trace_file=None, env=None, flash_file=None): + if trace_file: + cmd.append(f"--trace-file={trace_file}") + + self._timeout = timeout + self.trace_file = trace_file + self.flash_file = flash_file + print("Running", " ".join(cmd)) + self._proc = subprocess.Popen( + cmd, + stdin=subprocess.PIPE, + stdout=subprocess.PIPE, + stderr=None, + env=env, + ) + if self._proc.stdout is None: + raise RuntimeError("Failed to capture simulator stdout") + + # Discard the test warning + uart_pty_line = self._proc.stdout.readline().decode("utf-8") + if "connected to pseudotty:" not in uart_pty_line: + raise RuntimeError("Failed to connect to UART") + pty_path = uart_pty_line.strip().rsplit(":", maxsplit=1)[1].strip() + # The console UART's device name ("uart"). Other PTY UARTs announce + # their pseudotty in the same way, so reconnect_serial() looks for this + # name's line only. + self._console_pty_marker = ( + uart_pty_line.split("connected to pseudotty:")[0].strip() + " connected to pseudotty:" + ) + self.serial = SerialSaver( + serial.Serial(pty_path, baudrate=115200, timeout=0.05, write_timeout=0), + name="uart0", + ) + self.debug_serial = SerialSaver( + StdSerial(self._proc.stdin, self._proc.stdout), name="debug" + ) + # Offset into debug_serial output for finding the next UART PTY path. + self._pty_search_offset = 0 + + def reconnect_serial(self, timeout=30.0): + """Wait for the simulator to reboot (execv) and reopen the UART. + + native_sim/bsim reboot by re-executing the process; the UART PTY master + fd is O_CLOEXEC so it closes on execv and a new PTY is opened. The new + "connected to pseudotty: " line is printed to the process stdout + (which survives execv), so it shows up in debug_serial. This method waits + for that line and reopens ``self.serial`` on the new PTY. + """ + import time + + marker = self._console_pty_marker + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if self._proc.poll() is not None: + return False + out = self.debug_serial.all_output + # Only a line that starts with the console's name: the marker must + # not match the end of another UART's line. + idx = out.find(marker, self._pty_search_offset) + while idx > 0 and out[idx - 1] not in "\r\n": + idx = out.find(marker, idx + 1) + newline = out.find("\n", idx) if idx >= 0 else -1 + if idx >= 0 and newline >= 0: + line = out[idx:newline] + pty_path = line.strip().rsplit(":", maxsplit=1)[1].strip() + self._pty_search_offset = newline + 1 + try: + self.serial.close() + except Exception: + pass + self.serial = SerialSaver( + serial.Serial(pty_path, baudrate=115200, timeout=0.05, write_timeout=0), + name="uart0", + ) + return True + time.sleep(0.05) + return False + + def shutdown(self): + if self._proc.poll() is None: + self._proc.terminate() + self._proc.wait(timeout=self._timeout) + + self.serial.close() + self.debug_serial.close() + + def display_capture_paths(self) -> list[Path]: + """Return paths to numbered PNG capture files produced by trace-driven capture.""" + pattern = getattr(self, "_capture_png_pattern", None) + count = getattr(self, "_capture_count", 0) + if not pattern or count == 0: + return [] + return [Path(pattern % i) for i in range(count)] + + def wait_until_done(self): + start_time = time.monotonic() + while self._proc.poll() is None and time.monotonic() - start_time < self._timeout: + time.sleep(0.01) + self.shutdown() diff --git a/ports/zephyr-cp/tests/bsim/__init__.py b/ports/zephyr-cp/tests/bsim/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/ports/zephyr-cp/tests/bsim/conftest.py b/ports/zephyr-cp/tests/bsim/conftest.py new file mode 100644 index 00000000000..a0c2c9fca27 --- /dev/null +++ b/ports/zephyr-cp/tests/bsim/conftest.py @@ -0,0 +1,273 @@ +# SPDX-FileCopyrightText: 2025 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""Pytest fixtures for CircuitPython bsim testing.""" + +import logging +import os +import shutil +import subprocess +from pathlib import Path + +import pytest + +from .. import SerialSaver, StdSerial + +logger = logging.getLogger(__name__) + +ZEPHYR_CP = Path(__file__).resolve().parents[2] +BSIM_ROOT = ZEPHYR_CP / "tools/bsim" +BSIM_PHY_BINARY = BSIM_ROOT / "bin/bs_2G4_phy_v1" + + +@pytest.fixture +def native_sim_env() -> dict[str, str]: + env = os.environ.copy() + env["BSIM_OUT_PATH"] = str(BSIM_ROOT) + env["BSIM_COMPONENTS_PATH"] = str(BSIM_ROOT / "components") + lib_path = str(BSIM_ROOT / "lib") + existing = env.get("LD_LIBRARY_PATH", "") + env["LD_LIBRARY_PATH"] = f"{lib_path}:{existing}" if existing else lib_path + return env + + +@pytest.fixture(params=["native_nrf5340bsim", "native_nrf54lm20bsim"]) +def board(request): + """Parametrized board fixture for bsim tests. + + Overrides the parent conftest's board fixture to run each test on both + bsim boards. + """ + return request.param + + +@pytest.fixture +def bsim_phy_binary(): + """Return path to BabbleSim PHY binary, skip if not present.""" + if not BSIM_PHY_BINARY.exists(): + pytest.skip(f"bs_2G4_phy_v1 not found: {BSIM_PHY_BINARY}") + return BSIM_PHY_BINARY + + +class BsimPhyInstance: + def __init__(self, proc: subprocess.Popen, serial: SerialSaver, timeout: float): + self.proc = proc + self.serial = serial + self.timeout = timeout + + def finish_sim(self) -> None: + self.serial.wait_for("Cleaning up", timeout=self.timeout + 5) + + def shutdown(self) -> None: + if self.proc.poll() is None: + self.proc.terminate() + self.proc.wait(timeout=2) + self.serial.close() + + +class ZephyrSampleProcess: + def __init__(self, proc: subprocess.Popen, timeout: float): + self._proc = proc + self._timeout = timeout + if proc.stdout is None: + raise RuntimeError("Failed to capture Zephyr sample stdout") + self.serial = SerialSaver(StdSerial(None, proc.stdout), name="zephyr sample") + + def shutdown(self) -> None: + if self._proc.poll() is None: + self._proc.terminate() + self._proc.wait(timeout=self._timeout) + self.serial.close() + + +@pytest.fixture +def bsim_phy(request, bsim_phy_binary, native_sim_env, sim_id): + duration_marker = request.node.get_closest_marker("duration") + duration = float(duration_marker.args[0]) if duration_marker else 20.0 + + devices = 1 + if "circuitpython2" in request.fixturenames or "zephyr_sample" in request.fixturenames: + devices = 2 + + sample_marker = request.node.get_closest_marker("zephyr_sample") + if sample_marker is not None: + sample_device_id = int(sample_marker.kwargs.get("device_id", 1)) + devices = max(devices, sample_device_id + 1) + + # Do not pass -sim_length: if the PHY exits on simulated time, device 0 can + # still be flushing UART output and test output can get truncated. Instead, + # let pytest own process lifetime and terminate the PHY at fixture teardown. + cmd = [ + "stdbuf", + "-oL", + str(bsim_phy_binary), + "-v=9", # Cleaning up level is on 9. Connecting is 7. + f"-s={sim_id}", + f"-D={devices}", + "-argschannel", + "-at=40", # 40 dB attenuation (default 60) so RSSI ~ -40 dBm + ] + print("Running:", " ".join(cmd)) + proc = subprocess.Popen( + cmd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + env=native_sim_env, + cwd=BSIM_ROOT / "bin", + ) + if proc.stdout is None: + raise RuntimeError("Failed to capture bsim phy stdout") + + # stdbuf -oL forces line-buffered stdout so SerialSaver can + # stream-read PHY output in real time. Wrapping in StdSerial + # ensures the reader thread exits on EOF when the PHY process + # terminates, rather than spinning on empty timeout reads. + phy_output = SerialSaver(StdSerial(None, proc.stdout), name="bsim phy") + try: + phy_output.wait_for("Connecting", timeout=2) + except TimeoutError: + if proc.poll() is not None: + print(phy_output.all_output) + raise RuntimeError("bsim PHY exited immediately") + # Assume bsim is running + + phy = BsimPhyInstance(proc, phy_output, timeout=duration) + yield phy + phy.shutdown() + + print("bsim phy output:") + print(phy_output.all_output) + + +def _build_zephyr_sample(build_dir: Path, source_dir: Path, board: str) -> Path: + if shutil.which("west") is None: + raise RuntimeError("west not found") + + cmd = [ + "west", + "build", + "-b", + board, + "-d", + str(build_dir), + "-p=auto", + str(source_dir), + ] + logger.info("Building Zephyr sample: %s", " ".join(cmd)) + subprocess.run(cmd, check=True, cwd=ZEPHYR_CP) + + return build_dir / "zephyr/zephyr.exe" + + +@pytest.fixture +def zephyr_sample(request, bsim_phy, native_sim_env, sim_id): + marker = request.node.get_closest_marker("zephyr_sample") + if marker is None or len(marker.args) != 1: + raise RuntimeError( + "zephyr_sample fixture requires @pytest.mark.zephyr_sample('')" + ) + + sample = marker.args[0] + board = marker.kwargs.get("board", "nrf52_bsim") + device_id = int(marker.kwargs.get("device_id", 1)) + timeout = float(marker.kwargs.get("timeout", 10.0)) + + sample_rel = str(sample).removeprefix("zephyr/samples/") + source_dir = ZEPHYR_CP / "zephyr/samples" / sample_rel + if not source_dir.exists(): + source_dir = ZEPHYR_CP / sample # port-local sample + if not source_dir.exists(): + pytest.skip(f"Zephyr sample not found: {source_dir}") + + build_name = f"build-bsim-sample-{sample_rel.replace('/', '_')}-{board}" + build_dir = ZEPHYR_CP / build_name + binary = build_dir / "zephyr/zephyr.exe" + + needs_rebuild = False + if not binary.exists(): + needs_rebuild = True + else: + # Rebuild if any source file is newer than the binary. + binary_mtime = binary.stat().st_mtime + for root, _dirs, files in os.walk(source_dir): + for f in files: + if Path(root, f).stat().st_mtime > binary_mtime: + needs_rebuild = True + break + if needs_rebuild: + break + + if needs_rebuild: + try: + binary = _build_zephyr_sample(build_dir, source_dir, board) + except (subprocess.CalledProcessError, RuntimeError) as exc: + pytest.skip(f"Failed to build Zephyr sample {sample_rel}: {exc}") + + if not binary.exists(): + pytest.skip(f"Zephyr sample binary not found: {binary}") + + cmd = [ + str(binary), + f"-s={sim_id}", + f"-d={device_id}", + "-disconnect_on_exit=1", + ] + logger.info("Running: %s", " ".join(cmd)) + proc = subprocess.Popen( + cmd, + stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, + env=native_sim_env, + ) + sample_proc = ZephyrSampleProcess(proc, timeout=timeout) + yield sample_proc + sample_proc.shutdown() + + print("Zephyr sample output:") + print(sample_proc.serial.all_output) + + +FROZEN_ROOT = (ZEPHYR_CP / "../../frozen").resolve() + + +def get_library_files(name: str) -> dict[str, str]: + """Return a dict mapping CIRCUITPY paths to file contents for all + .py files in a frozen library, suitable for circuitpy_drive. + + Looks up ``name`` under the ``frozen/`` directory (e.g. + ``get_library_files("adafruit_ble")`` walks + ``frozen/Adafruit_CircuitPython_BLE/adafruit_ble/``). + """ + files: dict[str, str] = {} + + # Try directory-style library: *//**/*.py + py_files = sorted(FROZEN_ROOT.glob(f"*/{name}/**/*.py")) + if py_files: + repo_dir = py_files[0].relative_to(FROZEN_ROOT).parts[0] + lib_parent = FROZEN_ROOT / repo_dir + for py_file in py_files: + rel = py_file.relative_to(lib_parent) + files[str(rel)] = py_file.read_text(encoding="utf-8") + return files + + # Try single-file module: */.py + py_files = list(FROZEN_ROOT.glob(f"*/{name}.py")) + if py_files: + py_file = py_files[0] + files[name + ".py"] = py_file.read_text(encoding="utf-8") + return files + + raise FileNotFoundError(f"Library {name!r} not found under {FROZEN_ROOT}") + + +# pytest markers are defined inside out meaning the bottom one is first in the +# list and the top is last. So use negative indices to reverse them. +@pytest.fixture +def circuitpython1(circuitpython): + return circuitpython[-1] + + +@pytest.fixture +def circuitpython2(circuitpython): + return circuitpython[-2] diff --git a/ports/zephyr-cp/tests/bsim/samples/central_battery_client/CMakeLists.txt b/ports/zephyr-cp/tests/bsim/samples/central_battery_client/CMakeLists.txt new file mode 100644 index 00000000000..d3635c95059 --- /dev/null +++ b/ports/zephyr-cp/tests/bsim/samples/central_battery_client/CMakeLists.txt @@ -0,0 +1,9 @@ +# SPDX-License-Identifier: MIT + +cmake_minimum_required(VERSION 3.20.0) +find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE}) +project(central_battery_client) + +target_sources(app PRIVATE + src/main.c +) diff --git a/ports/zephyr-cp/tests/bsim/samples/central_battery_client/prj.conf b/ports/zephyr-cp/tests/bsim/samples/central_battery_client/prj.conf new file mode 100644 index 00000000000..56a790677be --- /dev/null +++ b/ports/zephyr-cp/tests/bsim/samples/central_battery_client/prj.conf @@ -0,0 +1,4 @@ +CONFIG_BT=y +CONFIG_BT_CENTRAL=y +CONFIG_BT_GATT_CLIENT=y +CONFIG_LOG=y diff --git a/ports/zephyr-cp/tests/bsim/samples/central_battery_client/src/main.c b/ports/zephyr-cp/tests/bsim/samples/central_battery_client/src/main.c new file mode 100644 index 00000000000..34ed2fa09b9 --- /dev/null +++ b/ports/zephyr-cp/tests/bsim/samples/central_battery_client/src/main.c @@ -0,0 +1,212 @@ +/* + * SPDX-FileCopyrightText: 2026 Scott Shawcroft for Adafruit Industries + * SPDX-License-Identifier: MIT + * + * Zephyr BLE central that connects to a device named "CPSVC", + * discovers Battery Service (0x180F), reads Battery Level (0x2A19), + * prints the value, and disconnects. + */ + +#include +#include + +#include +#include + +#include +#include +#include +#include + +static struct bt_conn *default_conn; +static struct bt_gatt_discover_params discover_params; +static struct bt_gatt_read_params read_params; + +/* Battery Service UUID: 0x180F */ +static struct bt_uuid_16 bas_uuid = BT_UUID_INIT_16(0x180F); +/* Battery Level Characteristic UUID: 0x2A19 */ +static struct bt_uuid_16 bat_level_uuid = BT_UUID_INIT_16(0x2A19); + +static uint16_t bat_level_handle; + +static void start_scan(void); + +static void device_found(const bt_addr_le_t *addr, int8_t rssi, uint8_t type, + struct net_buf_simple *ad) { + if (default_conn) { + return; + } + + /* Only interested in connectable devices */ + if (type != BT_GAP_ADV_TYPE_ADV_IND && + type != BT_GAP_ADV_TYPE_ADV_DIRECT_IND) { + return; + } + + /* Clone ad data so we can parse it without affecting the original */ + struct net_buf_simple ad_copy; + uint8_t ad_buf[64]; + size_t copy_len = ad->len < sizeof(ad_buf) ? ad->len : sizeof(ad_buf); + memcpy(ad_buf, ad->data, copy_len); + net_buf_simple_init_with_data(&ad_copy, ad_buf, copy_len); + + char addr_str[BT_ADDR_LE_STR_LEN]; + bt_addr_le_to_str(addr, addr_str, sizeof(addr_str)); + printk("Found CPSVC device: %s (RSSI %d)\n", addr_str, rssi); + + if (bt_le_scan_stop()) { + return; + } + + int err = bt_conn_le_create(addr, BT_CONN_LE_CREATE_CONN, + BT_LE_CONN_PARAM_DEFAULT, &default_conn); + if (err) { + printk("Create conn failed (%d)\n", err); + start_scan(); + } +} + +static void start_scan(void) { + int err = bt_le_scan_start(BT_LE_SCAN_PASSIVE, device_found); + if (err) { + printk("Scanning failed to start (err %d)\n", err); + return; + } + printk("Scanning started\n"); +} + +static uint8_t read_battery_level_cb(struct bt_conn *conn, uint8_t err, + struct bt_gatt_read_params *params, + const void *data, uint16_t length) { + if (err) { + printk("Read failed (err %d)\n", err); + } else if (data && length >= 1) { + uint8_t level = ((const uint8_t *)data)[0]; + printk("Battery Level: %d\n", level); + } else { + printk("Read returned no data\n"); + } + + /* Disconnect after reading */ + bt_conn_disconnect(conn, BT_HCI_ERR_REMOTE_USER_TERM_CONN); + + return BT_GATT_ITER_STOP; +} + +static uint8_t discover_char_cb(struct bt_conn *conn, + const struct bt_gatt_attr *attr, + struct bt_gatt_discover_params *params) { + if (!attr) { + printk("Characteristic discovery complete\n"); + return BT_GATT_ITER_STOP; + } + + struct bt_gatt_chrc *chrc = (struct bt_gatt_chrc *)attr->user_data; + + if (bt_uuid_cmp(chrc->uuid, &bat_level_uuid.uuid) == 0) { + bat_level_handle = chrc->value_handle; + printk("Found Battery Level characteristic, handle: %u\n", bat_level_handle); + + /* Read the battery level */ + read_params.func = read_battery_level_cb; + read_params.handle_count = 1; + read_params.single.handle = bat_level_handle; + read_params.single.offset = 0; + + int err = bt_gatt_read(conn, &read_params); + if (err) { + printk("Read request failed (err %d)\n", err); + } + return BT_GATT_ITER_STOP; + } + + return BT_GATT_ITER_CONTINUE; +} + +static uint8_t discover_service_cb(struct bt_conn *conn, + const struct bt_gatt_attr *attr, + struct bt_gatt_discover_params *params) { + if (!attr) { + printk("Service discovery complete, BAS not found\n"); + bt_conn_disconnect(conn, BT_HCI_ERR_REMOTE_USER_TERM_CONN); + return BT_GATT_ITER_STOP; + } + + printk("Found Battery Service, handle: %u\n", attr->handle); + + /* Now discover characteristics within this service */ + discover_params.uuid = &bat_level_uuid.uuid; + discover_params.start_handle = attr->handle + 1; + discover_params.end_handle = 0xFFFF; + discover_params.type = BT_GATT_DISCOVER_CHARACTERISTIC; + discover_params.func = discover_char_cb; + + int err = bt_gatt_discover(conn, &discover_params); + if (err) { + printk("Characteristic discovery failed (err %d)\n", err); + } + + return BT_GATT_ITER_STOP; +} + +static void connected(struct bt_conn *conn, uint8_t err) { + char addr[BT_ADDR_LE_STR_LEN]; + bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr)); + + if (err) { + printk("Failed to connect to %s (%u)\n", addr, err); + bt_conn_unref(default_conn); + default_conn = NULL; + start_scan(); + return; + } + + if (conn != default_conn) { + return; + } + + printk("Connected: %s\n", addr); + + /* Discover Battery Service */ + discover_params.uuid = &bas_uuid.uuid; + discover_params.start_handle = BT_ATT_FIRST_ATTRIBUTE_HANDLE; + discover_params.end_handle = BT_ATT_LAST_ATTRIBUTE_HANDLE; + discover_params.type = BT_GATT_DISCOVER_PRIMARY; + discover_params.func = discover_service_cb; + + err = bt_gatt_discover(conn, &discover_params); + if (err) { + printk("Service discovery failed (err %d)\n", err); + } +} + +static void disconnected(struct bt_conn *conn, uint8_t reason) { + char addr[BT_ADDR_LE_STR_LEN]; + + if (conn != default_conn) { + return; + } + + bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr)); + printk("Disconnected: %s (reason 0x%02x)\n", addr, reason); + + bt_conn_unref(default_conn); + default_conn = NULL; +} + +BT_CONN_CB_DEFINE(conn_callbacks) = { + .connected = connected, + .disconnected = disconnected, +}; + +int main(void) { + int err = bt_enable(NULL); + if (err) { + printk("Bluetooth init failed (err %d)\n", err); + return 0; + } + + printk("Bluetooth initialized\n"); + start_scan(); + return 0; +} diff --git a/ports/zephyr-cp/tests/bsim/samples/central_nus_client/CMakeLists.txt b/ports/zephyr-cp/tests/bsim/samples/central_nus_client/CMakeLists.txt new file mode 100644 index 00000000000..d5deacef980 --- /dev/null +++ b/ports/zephyr-cp/tests/bsim/samples/central_nus_client/CMakeLists.txt @@ -0,0 +1,9 @@ +# SPDX-License-Identifier: MIT + +cmake_minimum_required(VERSION 3.20.0) +find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE}) +project(central_nus_client) + +target_sources(app PRIVATE + src/main.c +) diff --git a/ports/zephyr-cp/tests/bsim/samples/central_nus_client/prj.conf b/ports/zephyr-cp/tests/bsim/samples/central_nus_client/prj.conf new file mode 100644 index 00000000000..56a790677be --- /dev/null +++ b/ports/zephyr-cp/tests/bsim/samples/central_nus_client/prj.conf @@ -0,0 +1,4 @@ +CONFIG_BT=y +CONFIG_BT_CENTRAL=y +CONFIG_BT_GATT_CLIENT=y +CONFIG_LOG=y diff --git a/ports/zephyr-cp/tests/bsim/samples/central_nus_client/src/main.c b/ports/zephyr-cp/tests/bsim/samples/central_nus_client/src/main.c new file mode 100644 index 00000000000..9825a3e7a5e --- /dev/null +++ b/ports/zephyr-cp/tests/bsim/samples/central_nus_client/src/main.c @@ -0,0 +1,302 @@ +/* + * SPDX-FileCopyrightText: 2026 Scott Shawcroft for Adafruit Industries + * SPDX-License-Identifier: MIT + * + * Zephyr BLE central that connects to a device named "CPNUS", + * discovers Nordic UART Service (NUS), writes to the RX characteristic, + * subscribes to TX notifications, receives data, and disconnects. + * + * NUS UUIDs: + * Service: 6E400001-B5A3-F393-E0A9-E50E24DCCA9E + * TX (peripheral→central, notify): 6E400003-B5A3-F393-E0A9-E50E24DCCA9E + * RX (central→peripheral, write): 6E400002-B5A3-F393-E0A9-E50E24DCCA9E + */ + +#include +#include + +#include +#include + +#include +#include +#include +#include + +static struct bt_conn *default_conn; +static struct bt_gatt_discover_params discover_params; + +/* Real NUS 128-bit UUIDs in little-endian byte order. + * These match the standard Nordic UART Service UUIDs: + * Service: 6E400001-B5A3-F393-E0A9-E50E24DCCA9E + * TX: 6E400003-B5A3-F393-E0A9-E50E24DCCA9E + * RX: 6E400002-B5A3-F393-E0A9-E50E24DCCA9E + */ +static struct bt_uuid_128 nus_service_uuid = BT_UUID_INIT_128( + 0x9E, 0xCA, 0xDC, 0x24, 0x0E, 0xE5, 0xA9, 0xE0, + 0x93, 0xF3, 0xA3, 0xB5, 0x01, 0x00, 0x40, 0x6E); +static struct bt_uuid_128 nus_tx_uuid = BT_UUID_INIT_128( + 0x9E, 0xCA, 0xDC, 0x24, 0x0E, 0xE5, 0xA9, 0xE0, + 0x93, 0xF3, 0xA3, 0xB5, 0x03, 0x00, 0x40, 0x6E); +static struct bt_uuid_128 nus_rx_uuid = BT_UUID_INIT_128( + 0x9E, 0xCA, 0xDC, 0x24, 0x0E, 0xE5, 0xA9, 0xE0, + 0x93, 0xF3, 0xA3, 0xB5, 0x02, 0x00, 0x40, 0x6E); + +static uint16_t tx_handle; +static uint16_t rx_handle; +static bool tx_notify_enabled; +static bool rx_written; +static bool received; +static uint8_t received_data[32]; +static uint16_t received_len; + +static void start_scan(void); + +/* Check if advertisement data contains a name */ +static bool ad_has_name(struct net_buf_simple *ad, const char *name) { + size_t name_len = strlen(name); + + while (ad->len > 1) { + uint8_t field_len = net_buf_simple_pull_u8(ad); + if (field_len == 0 || field_len > ad->len) { + break; + } + uint8_t type = net_buf_simple_pull_u8(ad); + field_len--; + + if ((type == BT_DATA_NAME_COMPLETE || type == BT_DATA_NAME_SHORTENED) && + field_len == name_len && + memcmp(ad->data, name, name_len) == 0) { + return true; + } + net_buf_simple_pull(ad, field_len); + } + return false; +} + +static void device_found(const bt_addr_le_t *addr, int8_t rssi, uint8_t type, + struct net_buf_simple *ad) { + if (default_conn) { + return; + } + + /* Only interested in connectable devices */ + if (type != BT_GAP_ADV_TYPE_ADV_IND && + type != BT_GAP_ADV_TYPE_ADV_DIRECT_IND) { + return; + } + + /* Clone ad data so we can parse it */ + struct net_buf_simple ad_copy; + uint8_t ad_buf[64]; + size_t copy_len = ad->len < sizeof(ad_buf) ? ad->len : sizeof(ad_buf); + memcpy(ad_buf, ad->data, copy_len); + net_buf_simple_init_with_data(&ad_copy, ad_buf, copy_len); + + if (!ad_has_name(&ad_copy, "CPNUS")) { + return; + } + + char addr_str[BT_ADDR_LE_STR_LEN]; + bt_addr_le_to_str(addr, addr_str, sizeof(addr_str)); + printk("Found CPNUS device: %s (RSSI %d)\n", addr_str, rssi); + + if (bt_le_scan_stop()) { + return; + } + + int err = bt_conn_le_create(addr, BT_CONN_LE_CREATE_CONN, + BT_LE_CONN_PARAM_DEFAULT, &default_conn); + if (err) { + printk("Create conn failed (%d)\n", err); + start_scan(); + } +} + +static void start_scan(void) { + int err = bt_le_scan_start(BT_LE_SCAN_PASSIVE, device_found); + if (err) { + printk("Scanning failed to start (err %d)\n", err); + return; + } + printk("Scanning started\n"); +} + +/* TX notification callback */ +static uint8_t on_tx_notify(struct bt_conn *conn, + struct bt_gatt_subscribe_params *params, + const void *data, uint16_t length) { + if (data) { + memcpy(received_data, data, length < sizeof(received_data) ? + length : sizeof(received_data)); + received_len = length; + received = true; + printk("NUS: received '"); + for (uint16_t i = 0; i < received_len; i++) { + printk("%c", received_data[i]); + } + printk("'\n"); + + /* Disconnect after receiving response */ + bt_conn_disconnect(conn, BT_HCI_ERR_REMOTE_USER_TERM_CONN); + } + return BT_GATT_ITER_CONTINUE; +} + +static struct bt_gatt_subscribe_params tx_subscribe_params; + +/* Step 5: Subscribe to TX notifications */ +static void subscribe_tx(struct bt_conn *conn) { + tx_subscribe_params.notify = on_tx_notify; + tx_subscribe_params.value = BT_GATT_CCC_NOTIFY; + tx_subscribe_params.value_handle = tx_handle; + tx_subscribe_params.ccc_handle = tx_handle + 1; + + int err = bt_gatt_subscribe(conn, &tx_subscribe_params); + if (err) { + printk("TX subscribe failed (err %d)\n", err); + bt_conn_disconnect(conn, BT_HCI_ERR_REMOTE_USER_TERM_CONN); + } else { + tx_notify_enabled = true; + printk("TX notify enabled\n"); + } +} + +/* Step 4: Write to RX characteristic (central→peripheral) using write-without-response */ +static void write_rx(struct bt_conn *conn) { + static uint8_t data[] = "Hello"; + + int err = bt_gatt_write_without_response(conn, rx_handle, + data, 5, false); + if (err) { + printk("RX write request failed (err %d)\n", err); + bt_conn_disconnect(conn, BT_HCI_ERR_REMOTE_USER_TERM_CONN); + return; + } + rx_written = true; + printk("RX write complete\n"); + + /* Now subscribe to TX to receive the response */ + subscribe_tx(conn); +} + +/* Step 3: Discover characteristics to find TX and RX handles */ +static uint8_t discover_char_cb(struct bt_conn *conn, + const struct bt_gatt_attr *attr, + struct bt_gatt_discover_params *params) { + if (!attr) { + printk("Characteristic discovery complete\n"); + if (rx_handle == 0 || tx_handle == 0) { + printk("NUS characteristics not found\n"); + bt_conn_disconnect(conn, BT_HCI_ERR_REMOTE_USER_TERM_CONN); + return BT_GATT_ITER_STOP; + } + if (rx_handle) { + printk("Writing to RX...\n"); + write_rx(conn); + } + return BT_GATT_ITER_STOP; + } + + struct bt_gatt_chrc *chrc = (struct bt_gatt_chrc *)attr->user_data; + + if (bt_uuid_cmp(chrc->uuid, &nus_rx_uuid.uuid) == 0) { + rx_handle = chrc->value_handle; + printk("Found NUS RX, handle: %u\n", rx_handle); + } else if (bt_uuid_cmp(chrc->uuid, &nus_tx_uuid.uuid) == 0) { + tx_handle = chrc->value_handle; + printk("Found NUS TX, handle: %u\n", tx_handle); + } + + return BT_GATT_ITER_CONTINUE; +} + +/* Step 2: Discover characteristics within the NUS service */ +static uint8_t discover_service_cb(struct bt_conn *conn, + const struct bt_gatt_attr *attr, + struct bt_gatt_discover_params *params) { + if (!attr) { + printk("Service discovery complete, NUS not found\n"); + bt_conn_disconnect(conn, BT_HCI_ERR_REMOTE_USER_TERM_CONN); + return BT_GATT_ITER_STOP; + } + + printk("Found NUS, handle: %u\n", attr->handle); + + /* Discover characteristics within this service */ + discover_params.uuid = NULL; + discover_params.start_handle = attr->handle + 1; + discover_params.end_handle = 0xFFFF; + discover_params.type = BT_GATT_DISCOVER_CHARACTERISTIC; + discover_params.func = discover_char_cb; + + int err = bt_gatt_discover(conn, &discover_params); + if (err) { + printk("Char discovery failed (err %d)\n", err); + } + + return BT_GATT_ITER_STOP; +} + +/* Step 1: Connected - discover NUS */ +static void connected(struct bt_conn *conn, uint8_t err) { + char addr[BT_ADDR_LE_STR_LEN]; + bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr)); + + if (err) { + printk("Failed to connect to %s (%u)\n", addr, err); + bt_conn_unref(default_conn); + default_conn = NULL; + start_scan(); + return; + } + + if (conn != default_conn) { + return; + } + + printk("Connected: %s\n", addr); + + /* Discover NUS */ + discover_params.uuid = &nus_service_uuid.uuid; + discover_params.start_handle = BT_ATT_FIRST_ATTRIBUTE_HANDLE; + discover_params.end_handle = BT_ATT_LAST_ATTRIBUTE_HANDLE; + discover_params.type = BT_GATT_DISCOVER_PRIMARY; + discover_params.func = discover_service_cb; + + err = bt_gatt_discover(conn, &discover_params); + if (err) { + printk("Service discovery failed (err %d)\n", err); + } +} + +static void disconnected(struct bt_conn *conn, uint8_t reason) { + char addr[BT_ADDR_LE_STR_LEN]; + + if (conn != default_conn) { + return; + } + + bt_addr_le_to_str(bt_conn_get_dst(conn), addr, sizeof(addr)); + printk("Disconnected: %s (reason 0x%02x)\n", addr, reason); + + bt_conn_unref(default_conn); + default_conn = NULL; +} + +BT_CONN_CB_DEFINE(conn_callbacks) = { + .connected = connected, + .disconnected = disconnected, +}; + +int main(void) { + int err = bt_enable(NULL); + if (err) { + printk("Bluetooth init failed (err %d)\n", err); + return 0; + } + + printk("Bluetooth initialized\n"); + start_scan(); + return 0; +} diff --git a/ports/zephyr-cp/tests/bsim/samples/observer/CMakeLists.txt b/ports/zephyr-cp/tests/bsim/samples/observer/CMakeLists.txt new file mode 100644 index 00000000000..59d999d7052 --- /dev/null +++ b/ports/zephyr-cp/tests/bsim/samples/observer/CMakeLists.txt @@ -0,0 +1,10 @@ +# SPDX-License-Identifier: Apache-2.0 + +cmake_minimum_required(VERSION 3.20.0) +find_package(Zephyr REQUIRED HINTS $ENV{ZEPHYR_BASE}) +project(observer) + +target_sources(app PRIVATE + src/main.c + src/observer.c +) diff --git a/ports/zephyr-cp/tests/bsim/samples/observer/prj.conf b/ports/zephyr-cp/tests/bsim/samples/observer/prj.conf new file mode 100644 index 00000000000..a328b3700a9 --- /dev/null +++ b/ports/zephyr-cp/tests/bsim/samples/observer/prj.conf @@ -0,0 +1,2 @@ +CONFIG_BT=y +CONFIG_BT_OBSERVER=y diff --git a/ports/zephyr-cp/tests/bsim/samples/observer/src/main.c b/ports/zephyr-cp/tests/bsim/samples/observer/src/main.c new file mode 100644 index 00000000000..db8ce6bab95 --- /dev/null +++ b/ports/zephyr-cp/tests/bsim/samples/observer/src/main.c @@ -0,0 +1,28 @@ +/* + * Copyright (c) 2022 Nordic Semiconductor ASA + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include +#include + +int observer_start(void); + +int main(void) { + int err; + + printk("Starting Observer Demo\n"); + + /* Initialize the Bluetooth Subsystem */ + err = bt_enable(NULL); + if (err) { + printk("Bluetooth init failed (err %d)\n", err); + return 0; + } + + (void)observer_start(); + + printk("Exiting %s thread.\n", __func__); + return 0; +} diff --git a/ports/zephyr-cp/tests/bsim/samples/observer/src/observer.c b/ports/zephyr-cp/tests/bsim/samples/observer/src/observer.c new file mode 100644 index 00000000000..fc896bf593d --- /dev/null +++ b/ports/zephyr-cp/tests/bsim/samples/observer/src/observer.c @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2022 Nordic Semiconductor ASA + * Copyright (c) 2015-2016 Intel Corporation + * + * SPDX-License-Identifier: Apache-2.0 + */ + +#include +#include +#include + +static void device_found(const bt_addr_le_t *addr, int8_t rssi, uint8_t type, + struct net_buf_simple *ad) { + printk("Device found: %s (RSSI %d), type %u, AD data len %u\n", + bt_addr_le_str(addr), rssi, type, ad->len); +} + +#if defined(CONFIG_BT_EXT_ADV) +#define NAME_LEN 30 + +static bool data_cb(struct bt_data *data, void *user_data) { + char *name = user_data; + uint8_t len; + + switch (data->type) { + case BT_DATA_NAME_SHORTENED: + case BT_DATA_NAME_COMPLETE: + len = MIN(data->data_len, NAME_LEN - 1); + (void)memcpy(name, data->data, len); + name[len] = '\0'; + return false; + default: + return true; + } +} + +static const char *phy2str(uint8_t phy) { + switch (phy) { + case BT_GAP_LE_PHY_NONE: + return "No packets"; + case BT_GAP_LE_PHY_1M: + return "LE 1M"; + case BT_GAP_LE_PHY_2M: + return "LE 2M"; + case BT_GAP_LE_PHY_CODED: + return "LE Coded"; + default: + return "Unknown"; + } +} + +static void scan_recv(const struct bt_le_scan_recv_info *info, + struct net_buf_simple *buf) { + char name[NAME_LEN]; + uint8_t data_status; + uint16_t data_len; + + (void)memset(name, 0, sizeof(name)); + + data_len = buf->len; + bt_data_parse(buf, data_cb, name); + + data_status = BT_HCI_LE_ADV_EVT_TYPE_DATA_STATUS(info->adv_props); + + printk("[DEVICE]: %s, AD evt type %u, Tx Pwr: %i, RSSI %i " + "Data status: %u, AD data len: %u Name: %s " + "C:%u S:%u D:%u SR:%u E:%u Pri PHY: %s, Sec PHY: %s, " + "Interval: 0x%04x (%u ms), SID: %u\n", + bt_addr_le_str(info->addr), info->adv_type, info->tx_power, info->rssi, + data_status, data_len, name, + (info->adv_props & BT_GAP_ADV_PROP_CONNECTABLE) != 0, + (info->adv_props & BT_GAP_ADV_PROP_SCANNABLE) != 0, + (info->adv_props & BT_GAP_ADV_PROP_DIRECTED) != 0, + (info->adv_props & BT_GAP_ADV_PROP_SCAN_RESPONSE) != 0, + (info->adv_props & BT_GAP_ADV_PROP_EXT_ADV) != 0, + phy2str(info->primary_phy), phy2str(info->secondary_phy), + info->interval, info->interval * 5 / 4, info->sid); +} + +static struct bt_le_scan_cb scan_callbacks = { + .recv = scan_recv, +}; +#endif /* CONFIG_BT_EXT_ADV */ + +static int scan_start(void) { + /* 30 ms continuous active scanning. Duplicate filtering is disabled so + * that updated advertisements from the same device (e.g. when user + * code replaces the workflow advert) are reported again. + */ + struct bt_le_scan_param scan_param = { + .type = BT_LE_SCAN_TYPE_ACTIVE, + .options = 0, + .interval = BT_GAP_SCAN_FAST_INTERVAL_MIN, + .window = BT_GAP_SCAN_FAST_WINDOW, + }; + int err; + + #if defined(CONFIG_BT_EXT_ADV) + scan_param.options |= BT_LE_SCAN_OPT_CODED; + #endif /* CONFIG_BT_EXT_ADV */ + +scan_start_retry: + printk("Starting scanning...\n"); + err = bt_le_scan_start(&scan_param, device_found); + if (err) { + if ((scan_param.options & BT_LE_SCAN_OPT_CODED) != 0U) { + printk("Failed to start scanning with Coded PHY (err %d), retrying " + "without...\n", err); + + scan_param.options &= ~BT_LE_SCAN_OPT_CODED; + + goto scan_start_retry; + } + + printk("Start scanning failed (err %d)\n", err); + + return err; + } + + printk("success.\n"); + + return 0; +} + +int observer_start(void) { + int err; + + #if defined(CONFIG_BT_EXT_ADV) + bt_le_scan_cb_register(&scan_callbacks); + printk("Registered scan callbacks\n"); + #endif /* CONFIG_BT_EXT_ADV */ + + err = scan_start(); + if (err != 0) { + return err; + } + + return 0; +} diff --git a/ports/zephyr-cp/tests/bsim/test_bsim_basics.py b/ports/zephyr-cp/tests/bsim/test_bsim_basics.py new file mode 100644 index 00000000000..12165750274 --- /dev/null +++ b/ports/zephyr-cp/tests/bsim/test_bsim_basics.py @@ -0,0 +1,55 @@ +# SPDX-FileCopyrightText: 2025 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""Basic BabbleSim connectivity tests for bsim.""" + +import pytest + +from .conftest import get_library_files + +BSIM_CODE = """\ +print("bsim ready") +""" + + +@pytest.mark.circuitpy_drive({"code.py": BSIM_CODE}) +@pytest.mark.circuitpy_drive({"code.py": BSIM_CODE}) +@pytest.mark.duration(20) +def test_bsim_dual_instance_connect(bsim_phy, circuitpython1, circuitpython2, board): + """Run two bsim instances on the same sim id and verify UART output.""" + + # Wait for both devices to complete before checking output. + circuitpython1.wait_until_done() + circuitpython2.wait_until_done() + + output0 = circuitpython1.serial.all_output + output1 = circuitpython2.serial.all_output + + assert f"Board ID:{board}" in output0 + assert f"Board ID:{board}" in output1 + assert "bsim ready" in output0 + assert "bsim ready" in output1 + + +# --- adafruit_ble library import --- + +BSIM_BLE_IMPORT_CODE = """\ +import adafruit_ble + +print("adafruit_ble version", adafruit_ble.__version__) +print("adafruit_ble repo", adafruit_ble.__repo__) +print("done") +""" + + +@pytest.mark.circuitpy_drive( + {"code.py": BSIM_BLE_IMPORT_CODE, **get_library_files("adafruit_ble")} +) +def test_bsim_ble_library_import(bsim_phy, circuitpython): + """Import adafruit_ble from CIRCUITPY and verify basic attributes.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "adafruit_ble version" in output + assert "adafruit_ble repo" in output + assert "done" in output diff --git a/ports/zephyr-cp/tests/bsim/test_bsim_ble_adapter.py b/ports/zephyr-cp/tests/bsim/test_bsim_ble_adapter.py new file mode 100644 index 00000000000..29092b0641c --- /dev/null +++ b/ports/zephyr-cp/tests/bsim/test_bsim_ble_adapter.py @@ -0,0 +1,149 @@ +# SPDX-FileCopyrightText: 2026 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""BLE adapter state tests for bsim.""" + +import pytest + + +# --- Enable/disable cycle --- + +BSIM_ENABLE_DISABLE_CODE = """\ +import _bleio + +adapter = _bleio.adapter + +# Check initial state (should be enabled after boot) +print("enabled start", adapter.enabled) + +# Disable +adapter.enabled = False +print("enabled false", adapter.enabled) + +# Re-enable +adapter.enabled = True +print("enabled true", adapter.enabled) + +# Verify it reports as enabled +print("enabled final", adapter.enabled) +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": BSIM_ENABLE_DISABLE_CODE}) +def test_bsim_adapter_enable_disable(bsim_phy, circuitpython): + """Toggle adapter.enabled and verify state.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "enabled start True" in output + assert "enabled false False" in output + assert "enabled true True" in output + assert "enabled final True" in output + assert "done" in output + + +# --- Disable stops advertising --- + +BSIM_DISABLE_STOPS_ADV_CODE = """\ +import _bleio + +adapter = _bleio.adapter + +name = b"CPADV" +advertisement = bytes((2, 0x01, 0x06, len(name) + 1, 0x09)) + name + +adapter.start_advertising(advertisement, connectable=False) +print("advertising", adapter.advertising) + +adapter.enabled = False +print("advertising after disable", adapter.advertising) + +adapter.enabled = True +print("advertising after enable", adapter.advertising) +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": BSIM_DISABLE_STOPS_ADV_CODE}) +def test_bsim_adapter_disable_stops_advertising(bsim_phy, circuitpython): + """Disabling the adapter stops advertising.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "advertising True" in output + assert "advertising after disable False" in output + assert "advertising after enable False" in output + assert "done" in output + + +# --- Adapter state across soft reload --- + +BSIM_ENABLE_RELOAD_CODE = """\ +import time +import _bleio + +adapter = _bleio.adapter + +print("enabled", adapter.enabled) +print("advertising", adapter.advertising) +print("connected", adapter.connected) +print("done") +# The sim exits right after the second run's VM cleanup (port_resets). Give the +# UART time to deliver the lines above to the pty before that happens. +time.sleep(0.5) +""" + + +@pytest.mark.port_resets(3) +@pytest.mark.duration(30) +@pytest.mark.circuitpy_drive({"code.py": BSIM_ENABLE_RELOAD_CODE}) +def test_bsim_adapter_state_after_reload(bsim_phy, circuitpython): + """Adapter state is consistent across a soft reload. + + The BLE workflow is advertising on this device, and `import _bleio` must not + disturb it, so adapter.advertising reads True on both runs (as on nordic). + """ + circuitpython.serial.wait_for("done") + circuitpython.serial.wait_for("Press any key to enter the REPL") + circuitpython.serial.write("\x04") + + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert output.count("enabled True") >= 2 + assert output.count("advertising True") >= 2 + assert output.count("connected False") >= 2 + + +# --- Adapter name truncation --- + +BSIM_NAME_TRUNCATION_CODE = """\ +import _bleio + +adapter = _bleio.adapter + +# Set a very long name +long_name = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%" +adapter.name = long_name + +# Read back — should be truncated to fit CONFIG_BT_DEVICE_NAME_MAX +name = adapter.name +print("name len", len(name)) +print("name", name) +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": BSIM_NAME_TRUNCATION_CODE}) +def test_bsim_adapter_name_truncation(bsim_phy, circuitpython): + """Very long adapter.name is truncated to fit Zephyr limit.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "name len" in output + # Should be truncated — length must be less than input (72 chars) + name_line = [l for l in output.split("\n") if "name len" in l][0] + name_len = int(name_line.split()[-1]) + assert name_len < 72 + assert "done" in output diff --git a/ports/zephyr-cp/tests/bsim/test_bsim_ble_advertising.py b/ports/zephyr-cp/tests/bsim/test_bsim_ble_advertising.py new file mode 100644 index 00000000000..fe2d66881e7 --- /dev/null +++ b/ports/zephyr-cp/tests/bsim/test_bsim_ble_advertising.py @@ -0,0 +1,262 @@ +# SPDX-FileCopyrightText: 2025 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""BLE advertising tests for bsim.""" + +import logging +import re + +import pytest + + +logger = logging.getLogger(__name__) + +BSIM_ADV_CODE = """\ +import _bleio +import time + +name = b"CPADV" +advertisement = bytes((2, 0x01, 0x06, len(name) + 1, 0x09)) + name + +adapter = _bleio.adapter +print("adv start") +adapter.start_advertising(advertisement, connectable=False) +print("adv started") +time.sleep(4) +adapter.stop_advertising() +print("adv stop") +""" + +BSIM_ADV_INTERRUPT_RELOAD_CODE = """\ +import _bleio +import time + +name = b"CPADV" +advertisement = bytes((2, 0x01, 0x06, len(name) + 1, 0x09)) + name + +adapter = _bleio.adapter +print("adv run start") +adapter.start_advertising(advertisement, connectable=False) +print("adv running") +time.sleep(10) +adapter.stop_advertising() +print("adv run done") +""" + + +BSIM_TX_POWER_DEFAULT_CODE = """\ +import _bleio +import time + +adapter = _bleio.adapter + +name = b"CPTXPWR" +advertisement = bytes((2, 0x01, 0x06, len(name) + 1, 0x09)) + name + +print("advertising default") +adapter.start_advertising(advertisement) +time.sleep(4) +adapter.stop_advertising() +print("done") +""" + +BSIM_TX_POWER_LOW_CODE = """\ +import _bleio +import time + +adapter = _bleio.adapter + +name = b"CPTXPWR" +advertisement = bytes((2, 0x01, 0x06, len(name) + 1, 0x09)) + name + +print("advertising low") +adapter.start_advertising(advertisement, tx_power=-20) +time.sleep(4) +adapter.stop_advertising() +print("done") +""" + + +# Advertiser: primary advert carries a distinctive marker; the scan response +# carries a different marker. If the adapter merges them they'd arrive as one +# entry, but the adapter does not merge — they come as separate ScanEntry +# objects distinguished by `scan_response`. +BSIM_ADVERT_SCAN_RESPONSE_ADV_CODE = """\ +import _bleio +import time + +adapter = _bleio.adapter + +name = b"ADVADV" +advertisement = bytes((2, 0x01, 0x06, len(name) + 1, 0x09)) + name + +sname = b"SCANRSP" +scan_response = bytes((len(sname) + 1, 0x09)) + sname + +print("adv start") +adapter.start_advertising(advertisement, scan_response=scan_response, connectable=True) +time.sleep(10) +adapter.stop_advertising() +print("adv done") +""" + +BSIM_ADVERT_SCAN_RESPONSE_SCAN_CODE = """\ +import _bleio + +adapter = _bleio.adapter +print("scan start") +saw_primary = False +saw_scan_response = False +for entry in adapter.start_scan(active=True, timeout=12.0): + data = entry.advertisement_bytes + if b"ADVADV" in data and not entry.scan_response: + saw_primary = True + print("primary") + if b"SCANRSP" in data and entry.scan_response: + saw_scan_response = True + print("scan_response") + if saw_primary and saw_scan_response: + print("both") + break +adapter.stop_scan() +print("scan done", saw_primary, saw_scan_response) +""" + +# Disable the workflow on the advertiser so only its custom advert is on air. +BSIM_ADVERT_SCAN_RESPONSE_SETTINGS = "CIRCUITPY_BLE_WORKFLOW = false\n" + + +@pytest.mark.zephyr_sample("tests/bsim/samples/observer") +@pytest.mark.circuitpy_drive({"code.py": BSIM_ADV_CODE}) +@pytest.mark.duration(60) +def test_bsim_advertise_and_scan(bsim_phy, circuitpython, zephyr_sample): + """Advertise from CircuitPython and verify Zephyr observer sees traffic.""" + observer = zephyr_sample + + circuitpython.wait_until_done() + + cp_output = circuitpython.serial.all_output + observer_output = observer.serial.all_output + assert "adv start" in cp_output + assert "adv started" in cp_output + assert "adv stop" in cp_output + assert "Device found:" in observer_output + assert "AD data len 10" in observer_output + + +@pytest.mark.zephyr_sample("tests/bsim/samples/observer") +@pytest.mark.port_resets(3) +@pytest.mark.duration(60) +@pytest.mark.circuitpy_drive({"code.py": BSIM_ADV_INTERRUPT_RELOAD_CODE}) +def test_bsim_advertise_ctrl_c_reload(bsim_phy, circuitpython, zephyr_sample): + """Ensure advertising resumes after Ctrl-C and a reload.""" + observer = zephyr_sample + + circuitpython.serial.wait_for("adv running") + observer.serial.wait_for("Device found:") + observer_count_before = observer.serial.all_output.count("Device found:") + + circuitpython.serial.write("\x03") + # Real AES for the link layer adds CPU overhead that can delay the + # interpreter noticing SIGINT beyond the default wait_for timeout. + circuitpython.serial.wait_for("KeyboardInterrupt", timeout=20) + + circuitpython.serial.write("\x04") + circuitpython.wait_until_done() + + cp_output = circuitpython.serial.all_output + observer_output = observer.serial.all_output + logger.info(observer_output) + logger.info(cp_output) + + assert "adv run start" in cp_output + assert "KeyboardInterrupt" in cp_output + assert cp_output.count("adv running") >= 2 + assert cp_output.count("adv run done") >= 1 + assert observer_output.count("Device found:") >= observer_count_before + 1 + assert "Already advertising" not in cp_output + + +@pytest.mark.zephyr_sample("tests/bsim/samples/observer") +@pytest.mark.duration(40) +@pytest.mark.circuitpy_drive({"code.py": BSIM_TX_POWER_DEFAULT_CODE}) +def test_bsim_tx_power_default_rssi(board, bsim_phy, circuitpython, zephyr_sample): + """Verify default TX power produces expected RSSI.""" + observer = zephyr_sample + + circuitpython.wait_until_done() + + cp_output = circuitpython.serial.all_output + obs_output = observer.serial.all_output + + assert "advertising default" in cp_output + assert "done" in cp_output + + # Observer: "Device found: (RSSI ), type , AD data len " + # Advertisement is 12 bytes: flags (3) + name (9). + # With 40 dB channel attenuation and 0 dBm TX → RSSI ~ -39. + expected_rssi = -39 + rssi_pattern = re.compile(r"RSSI (-?\d+)\), type \d+, AD data len 12") + all_rssi = [int(m.group(1)) for m in rssi_pattern.finditer(obs_output)] + logger.info("RSSI values: %s", all_rssi) + + assert len(all_rssi) > 0, "Observer saw no advertisements" + assert all_rssi[0] == expected_rssi, f"Expected RSSI {expected_rssi}, got {all_rssi[0]}" + + +@pytest.mark.zephyr_sample("tests/bsim/samples/observer") +@pytest.mark.duration(40) +@pytest.mark.circuitpy_drive({"code.py": BSIM_TX_POWER_LOW_CODE}) +def test_bsim_tx_power_low_rssi(bsim_phy, circuitpython, zephyr_sample): + """Verify low TX power reduces RSSI.""" + observer = zephyr_sample + + circuitpython.wait_until_done() + + cp_output = circuitpython.serial.all_output + obs_output = observer.serial.all_output + + assert "advertising low" in cp_output + assert "done" in cp_output + + # With 40 dB channel attenuation and -20 dBm TX → RSSI ~ -59 + rssi_pattern = re.compile(r"RSSI (-?\d+)\), type \d+, AD data len 12") + all_rssi = [int(m.group(1)) for m in rssi_pattern.finditer(obs_output)] + logger.info("RSSI values: %s", all_rssi) + + assert len(all_rssi) > 0, "Observer saw no advertisements" + assert all_rssi[0] < -39, f"Expected lower RSSI with -20 dBm TX, got {all_rssi[0]}" + + +@pytest.mark.duration(20) +@pytest.mark.circuitpy_drive( + { + "code.py": BSIM_ADVERT_SCAN_RESPONSE_ADV_CODE, + "settings.toml": BSIM_ADVERT_SCAN_RESPONSE_SETTINGS, + } +) +@pytest.mark.circuitpy_drive({"code.py": BSIM_ADVERT_SCAN_RESPONSE_SCAN_CODE}) +def test_bsim_scan_response_not_merged(bsim_phy, circuitpython1, circuitpython2): + """The adapter does not merge advertisement and scan response. + + The advertiser sends a primary advert (marker "ADVADV") and a scan + response (marker "SCANRSP") as separate packets. With duplicate filtering + disabled and no merging in the adapter, the scanner observes them as two + distinct ScanEntry objects: one with scan_response=False (the primary + advert) and one with scan_response=True (the scan response). + """ + scanner = circuitpython2 + + scanner.wait_until_done() + + scanner_output = scanner.serial.all_output + assert "primary" in scanner_output, ( + f"primary advert entry not observed separately: {scanner_output}" + ) + assert "scan_response" in scanner_output, ( + f"scan response entry not observed separately: {scanner_output}" + ) + assert "both" in scanner_output, ( + f"did not observe both advert and scan response: {scanner_output}" + ) + assert "scan done True True" in scanner_output, f"scan did not confirm both: {scanner_output}" diff --git a/ports/zephyr-cp/tests/bsim/test_bsim_ble_connect.py b/ports/zephyr-cp/tests/bsim/test_bsim_ble_connect.py new file mode 100644 index 00000000000..5a52e03a151 --- /dev/null +++ b/ports/zephyr-cp/tests/bsim/test_bsim_ble_connect.py @@ -0,0 +1,118 @@ +# SPDX-FileCopyrightText: 2026 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""BLE central connection tests for bsim.""" + +import pytest + + +BSIM_CONNECT_CODE = """\ +import _bleio +import time + +adapter = _bleio.adapter + +print("connect start") +target = None +for entry in adapter.start_scan(timeout=6.0, active=True): + if entry.connectable: + target = entry.address + print("found target") + break +adapter.stop_scan() +print("have target", target is not None) + +if target is None: + raise RuntimeError("No connectable target found") + +connection = adapter.connect(target, timeout=5.0) +print("connected", connection.connected, adapter.connected, len(adapter.connections)) +connection.disconnect() + +for _ in range(40): + if not connection.connected and not adapter.connected: + break + time.sleep(0.1) + +print("disconnected", connection.connected, adapter.connected, len(adapter.connections)) +""" + +BSIM_RECONNECT_CODE = """\ +import _bleio +import time + +adapter = _bleio.adapter + +print("run start") +target = None +for entry in adapter.start_scan(timeout=6.0, active=True): + if entry.connectable: + target = entry.address + print("run found target") + break +adapter.stop_scan() +print("run have target", target is not None) + +if target is None: + raise RuntimeError("No connectable target found") + +connection = adapter.connect(target, timeout=5.0) +print("run connected", connection.connected, adapter.connected, len(adapter.connections)) +connection.disconnect() + +for _ in range(50): + if not connection.connected and not adapter.connected and len(adapter.connections) == 0: + break + time.sleep(0.1) + +print("run disconnected", connection.connected, adapter.connected, len(adapter.connections)) +""" + + +@pytest.mark.zephyr_sample("bluetooth/peripheral") +@pytest.mark.duration(14) +@pytest.mark.circuitpy_drive({"code.py": BSIM_CONNECT_CODE}) +def test_bsim_connect_zephyr_peripheral(bsim_phy, circuitpython, zephyr_sample): + """Connect to the Zephyr peripheral sample and disconnect cleanly.""" + peripheral = zephyr_sample + + circuitpython.wait_until_done() + + cp_output = circuitpython.serial.all_output + peripheral_output = peripheral.serial.all_output + + assert "connect start" in cp_output + assert "found target" in cp_output + assert "have target True" in cp_output + assert "connected True True 1" in cp_output + assert "disconnected False False 0" in cp_output + + assert "Advertising successfully started" in peripheral_output + assert "Connected" in peripheral_output + + +@pytest.mark.zephyr_sample("bluetooth/peripheral_sc_only") +@pytest.mark.port_resets(3) +@pytest.mark.duration(26) +@pytest.mark.circuitpy_drive({"code.py": BSIM_RECONNECT_CODE}) +def test_bsim_reconnect_zephyr_peripheral(bsim_phy, circuitpython, zephyr_sample): + """Connect/disconnect, soft reload, then connect/disconnect again.""" + peripheral = zephyr_sample + + circuitpython.serial.wait_for("run disconnected") + circuitpython.serial.wait_for("Press any key to enter the REPL") + circuitpython.serial.write("\x04") + + circuitpython.wait_until_done() + + cp_output = circuitpython.serial.all_output + peripheral_output = peripheral.serial.all_output + + assert cp_output.count("run start") >= 2 + assert cp_output.count("run found target") >= 2 + assert cp_output.count("run have target True") >= 2 + assert cp_output.count("run connected True True 1") >= 2 + assert cp_output.count("run disconnected False False 0") >= 2 + + assert "Advertising successfully started" in peripheral_output + assert peripheral_output.count("Connected") >= 2 diff --git a/ports/zephyr-cp/tests/bsim/test_bsim_ble_descriptor.py b/ports/zephyr-cp/tests/bsim/test_bsim_ble_descriptor.py new file mode 100644 index 00000000000..6d5cf418147 --- /dev/null +++ b/ports/zephyr-cp/tests/bsim/test_bsim_ble_descriptor.py @@ -0,0 +1,131 @@ +# SPDX-FileCopyrightText: 2026 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""BLE descriptor tests for bsim.""" + +import pytest + +# =================================================================== +# Server: characteristic with user_description +# =================================================================== + +BSIM_DESC_SERVER_CODE = """\ +import _bleio +import time + +adapter = _bleio.adapter + +svc = _bleio.Service(_bleio.UUID(0x180F)) +char = _bleio.Characteristic.add_to_service( + svc, _bleio.UUID(0x2A19), + properties=_bleio.Characteristic.READ, + read_perm=_bleio.Attribute.OPEN, + write_perm=_bleio.Attribute.NO_ACCESS, + max_length=1, fixed_length=True, initial_value=bytes([75]), + user_description="Battery Level", +) +print("service created") + +# Check local descriptors list +descs = char.descriptors +print("num descriptors", len(descs)) +for d in descs: + print("desc uuid", d.uuid.uuid16) + print("desc value", list(d.value)) + +name = b"CPDESC" +advertisement = bytes((2, 0x01, 0x06, len(name) + 1, 0x09)) + name +adapter.start_advertising(advertisement, connectable=True) + +for _ in range(80): + if adapter.connected: + break + time.sleep(0.1) +print("connected", adapter.connected) + +for _ in range(80): + if not adapter.connected: + break + time.sleep(0.1) +print("done") +""" + +# =================================================================== +# Client: connects and reads the remote user description +# =================================================================== + +BSIM_DESC_CLIENT_CODE = """\ +import _bleio +import time + +adapter = _bleio.adapter + +print("client start") +target = None +for entry in adapter.start_scan(timeout=6.0, active=True): + if entry.connectable and b"CPDESC" in entry.advertisement_bytes: + target = entry.address + print("found server") + break +adapter.stop_scan() +print("have target", target is not None) + +if target is None: + raise RuntimeError("No server found") + +connection = adapter.connect(target, timeout=5.0) +print("connected", connection.connected) + +services = connection.discover_remote_services([_bleio.UUID(0x180F)]) +char = services[0].characteristics[0] + +print("char value", list(char.value)) + +descs = char.descriptors +print("num descriptors", len(descs)) +for d in descs: + print("desc uuid", hex(d.uuid.uuid16)) + print("desc value", list(d.value)) + +connection.disconnect() + +timeout = time.monotonic() + 4.0 +while connection.connected and time.monotonic() < timeout: + time.sleep(0.1) +print("done") +""" + + +@pytest.mark.duration(30) +@pytest.mark.circuitpy_drive({"code.py": BSIM_DESC_SERVER_CODE}) +@pytest.mark.circuitpy_drive({"code.py": BSIM_DESC_CLIENT_CODE}) +def test_bsim_descriptor_user_description(bsim_phy, circuitpython1, circuitpython2): + """Server creates a characteristic with user_description; + client discovers the service and reads the descriptor.""" + server = circuitpython1 + client = circuitpython2 + + client.wait_until_done() + server.wait_until_done() + + server_output = server.serial.all_output + client_output = client.serial.all_output + + # Server: user_description creates a CUD descriptor (0x2901) on the characteristic + assert "service created" in server_output + assert "num descriptors 1" in server_output + assert "desc uuid 10497" in server_output # 0x2901 + assert ( + "desc value [66, 97, 116, 116, 101, 114, 121, 32, 76, 101, 118, 101, 108]" in server_output + ) + assert "connected True" in server_output + + # Client: discovers and reads the remote descriptor + assert "found server" in client_output + assert "char value [75]" in client_output + assert "num descriptors 1" in client_output + assert "desc uuid 0x2901" in client_output + assert ( + "desc value [66, 97, 116, 116, 101, 114, 121, 32, 76, 101, 118, 101, 108]" in client_output + ) + assert "done" in client_output diff --git a/ports/zephyr-cp/tests/bsim/test_bsim_ble_name.py b/ports/zephyr-cp/tests/bsim/test_bsim_ble_name.py new file mode 100644 index 00000000000..b64fb2125f1 --- /dev/null +++ b/ports/zephyr-cp/tests/bsim/test_bsim_ble_name.py @@ -0,0 +1,126 @@ +# SPDX-FileCopyrightText: 2026 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""BLE adapter name tests for bsim. + +Covers reading the default adapter name (derived from the device address), +setting a custom name and reading it back, and verifying the default name is +re-applied every time the adapter is re-enabled. +""" + +import re + +import pytest + + +# The address prints as
in big-endian/expected order. +# The default name is "CIRCUITPY" plus the last two octets (ee, ff) concatenated +# without colons, e.g. an address of
-> "CIRCUITPYd224". +ADDRESS_RE = re.compile( + r"
" +) + +# Strip ANSI/OSC escape sequences (e.g. terminal title updates) and carriage +# returns that CircuitPython interleaves with code.py output. +_ANSI_RE = re.compile(r"\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b\[[0-9;?]*[A-Za-z]") + + +def _clean(output: str) -> str: + return _ANSI_RE.sub("", output).replace("\r", "") + + +def _expected_default_name(address_repr: str) -> str: + m = ADDRESS_RE.search(address_repr) + assert m is not None, f"unexpected address repr: {address_repr!r}" + return "CIRCUITPY" + m.group(5) + m.group(6) + + +# --- Default name is derived from the adapter address --- + +BSIM_DEFAULT_NAME_CODE = """\ +import _bleio + +adapter = _bleio.adapter +adapter.enabled = True +print("default name", adapter.name) +print("address", adapter.address) +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": BSIM_DEFAULT_NAME_CODE}) +def test_bsim_default_name_matches_address(bsim_phy, circuitpython): + """The default name is CIRCUITPY plus the last two address octets.""" + circuitpython.wait_until_done() + + output = _clean(circuitpython.serial.all_output) + name = re.search(r"(?m)^default name (\S+)$", output).group(1) + address_repr = re.search(r"(?m)^address (.+)$", output).group(1).strip() + + assert name == _expected_default_name(address_repr) + assert re.search(r"(?m)^done$", output) is not None + + +# --- Set a custom name and read it back --- + +BSIM_SET_NAME_CODE = """\ +import _bleio + +adapter = _bleio.adapter +adapter.enabled = True +adapter.name = "CPNAME" +print("name", adapter.name) +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": BSIM_SET_NAME_CODE}) +def test_bsim_set_name(bsim_phy, circuitpython): + """Set the BLE name and read it back on bsim.""" + circuitpython.wait_until_done() + + output = _clean(circuitpython.serial.all_output) + assert re.search(r"(?m)^name CPNAME$", output) is not None + assert re.search(r"(?m)^done$", output) is not None + + +# --- Re-enabling the adapter restores the default name --- + +BSIM_NAME_RESET_ON_ENABLE_CODE = """\ +import _bleio + +adapter = _bleio.adapter + +adapter.enabled = True +print("default", adapter.name) + +adapter.name = "CUSTOM" +print("custom", adapter.name) + +# Re-enabling re-applies the default name derived from the address. +adapter.enabled = False +adapter.enabled = True +print("reset", adapter.name) +print("address", adapter.address) +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": BSIM_NAME_RESET_ON_ENABLE_CODE}) +def test_bsim_name_resets_on_enable(bsim_phy, circuitpython): + """Disabling and re-enabling the adapter restores the default name.""" + circuitpython.wait_until_done() + + output = _clean(circuitpython.serial.all_output) + default_name = re.search(r"(?m)^default (\S+)$", output).group(1) + assert re.search(r"(?m)^custom CUSTOM$", output) is not None + reset_name = re.search(r"(?m)^reset (\S+)$", output).group(1) + address_repr = re.search(r"(?m)^address (.+)$", output).group(1).strip() + + # The custom name is gone and the address-derived default is back. + assert reset_name != "CUSTOM" + assert reset_name == _expected_default_name(address_repr) + # The re-applied default matches the boot-time default. + assert reset_name == default_name + assert re.search(r"(?m)^done$", output) is not None diff --git a/ports/zephyr-cp/tests/bsim/test_bsim_ble_nus.py b/ports/zephyr-cp/tests/bsim/test_bsim_ble_nus.py new file mode 100644 index 00000000000..1336d37fbd0 --- /dev/null +++ b/ports/zephyr-cp/tests/bsim/test_bsim_ble_nus.py @@ -0,0 +1,183 @@ +# SPDX-FileCopyrightText: 2026 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""Nordic UART Service (NUS) tests for bsim — using adafruit_ble library.""" + +import pytest + +from .conftest import get_library_files + +_ADAFRUIT_BLE = get_library_files("adafruit_ble") + +# ---- Test 1: CP peripheral hosts NUS, Zephyr central writes and reads ---- + +BSIM_NUS_PERIPHERAL_CODE = """\ +import time +from adafruit_ble import BLERadio +from adafruit_ble.advertising.standard import ProvideServicesAdvertisement +from adafruit_ble.services.nordic import UARTService + +ble = BLERadio() +uart = UARTService() +print("service created") + +advertisement = ProvideServicesAdvertisement(uart) +advertisement.complete_name = "CPNUS" +ble.start_advertising(advertisement) +print("advertising") + +for _ in range(80): + if ble.connected: + break + time.sleep(0.1) +print("connected", ble.connected) + +# Wait for data to arrive from central +data = uart.read(5) +print("received", data) + +# Send a response back +uart.write(b"World") +print("sent response") + +time.sleep(1.0) + +for _ in range(80): + if not ble.connected: + break + time.sleep(0.1) +print("done") +""" + + +@pytest.mark.zephyr_sample("tests/bsim/samples/central_nus_client") +@pytest.mark.duration(14) +@pytest.mark.circuitpy_drive( + { + "code.py": BSIM_NUS_PERIPHERAL_CODE, + "settings.toml": "CIRCUITPY_BLE_WORKFLOW = false\n", + **_ADAFRUIT_BLE, + } +) +def test_bsim_nus_peripheral(bsim_phy, circuitpython, zephyr_sample): + """CP hosts NUS peripheral; Zephyr central writes to RX, reads TX notifications.""" + circuitpython.wait_until_done() + + cp_output = circuitpython.serial.all_output + sample_output = zephyr_sample.serial.all_output + + assert "service created" in cp_output + assert "connected True" in cp_output + assert "received" in cp_output + assert "sent response" in cp_output + assert "NUS: received 'World'" in sample_output + + +# ---- Test 2: CP-to-CP NUS (peripheral + central) ---- + +BSIM_NUS_SERVER_CODE = """\ +import time +from adafruit_ble import BLERadio +from adafruit_ble.advertising.standard import ProvideServicesAdvertisement +from adafruit_ble.services.nordic import UARTService + +ble = BLERadio() +uart = UARTService() +print("service created") + +advertisement = ProvideServicesAdvertisement(uart) +advertisement.complete_name = "CP2CP" +ble.start_advertising(advertisement) +print("advertising") + +for _ in range(80): + if ble.connected: + break + time.sleep(0.1) +print("connected", ble.connected) + +# Read incoming data from central +data = uart.read(6) +print("received", data) + +# Respond back +uart.write(b"OK!") +print("sent response") + +for _ in range(80): + if not ble.connected: + break + time.sleep(0.1) +print("done") +""" + +BSIM_NUS_CLIENT_CODE = """\ +import time +from adafruit_ble import BLERadio +from adafruit_ble.advertising.standard import ProvideServicesAdvertisement +from adafruit_ble.services.nordic import UARTService + +ble = BLERadio() + +print("client start") +target = None +for adv in ble.start_scan(ProvideServicesAdvertisement, timeout=8.0): + if adv.connectable and adv.complete_name == "CP2CP": + target = adv + print("found server") + break +ble.stop_scan() +print("have target", target is not None) + +if target is None: + raise RuntimeError("No server found") + +connection = ble.connect(target, timeout=5.0) +print("connected", connection.connected) + +uart = connection[UARTService] +print("discovered services", 1) + +# Write to server +uart.write(b"Hello!") +print("wrote to rx") + +data = uart.read(3) +print("received", data) + +connection.disconnect() + +timeout = time.monotonic() + 4.0 +while connection.connected and time.monotonic() < timeout: + time.sleep(0.1) +print("done") +""" + + +@pytest.mark.duration(30) +@pytest.mark.circuitpy_drive({"code.py": BSIM_NUS_SERVER_CODE, **_ADAFRUIT_BLE}) +@pytest.mark.circuitpy_drive({"code.py": BSIM_NUS_CLIENT_CODE, **_ADAFRUIT_BLE}) +def test_bsim_nus_cp_to_cp(bsim_phy, circuitpython1, circuitpython2): + """CP peripheral hosts NUS; CP central writes to RX, reads TX via notifications.""" + server = circuitpython1 + client = circuitpython2 + + client.wait_until_done() + server.wait_until_done() + + server_output = server.serial.all_output + client_output = client.serial.all_output + + assert "service created" in server_output + assert "connected True" in server_output + assert "received" in server_output + assert "sent response" in server_output + + assert "client start" in client_output + assert "found server" in client_output + assert "have target True" in client_output + assert "connected True" in client_output + assert "discovered services 1" in client_output + assert "wrote to rx" in client_output + assert "received b'OK!'" in client_output + assert "done" in client_output diff --git a/ports/zephyr-cp/tests/bsim/test_bsim_ble_packet_buffer.py b/ports/zephyr-cp/tests/bsim/test_bsim_ble_packet_buffer.py new file mode 100644 index 00000000000..d5ff222ff5d --- /dev/null +++ b/ports/zephyr-cp/tests/bsim/test_bsim_ble_packet_buffer.py @@ -0,0 +1,1140 @@ +# SPDX-FileCopyrightText: 2026 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""PacketBuffer tests for bsim.""" + +import re + +import pytest + + +# ---- Test 1: Server-side PacketBuffer incoming (WRITE characteristic) ---- + +BSIM_PB_SERVER_IN_CODE = """\ +import _bleio +import time + +adapter = _bleio.adapter + +svc = _bleio.Service(_bleio.UUID(0xFFE0)) +char = _bleio.Characteristic.add_to_service( + svc, _bleio.UUID(0xFFE1), + properties=_bleio.Characteristic.WRITE, + read_perm=_bleio.Attribute.NO_ACCESS, + write_perm=_bleio.Attribute.OPEN, + max_length=20, fixed_length=False, +) + +# Wrap in PacketBuffer for incoming packets +pb = _bleio.PacketBuffer(char, buffer_size=4, max_packet_size=20) +print("service created") + +name = b"CPPBIN" +advertisement = bytes((2, 0x01, 0x06, len(name) + 1, 0x09)) + name +adapter.start_advertising(advertisement, connectable=True) +print("advertising") + +for _ in range(80): + if adapter.connected: + break + time.sleep(0.1) +print("connected", adapter.connected) + +# Read first incoming packet +data = bytearray(20) +n = 0 +deadline = time.monotonic() + 5.0 +while n == 0 and time.monotonic() < deadline: + n = pb.readinto(data) + if n == 0: + time.sleep(0.05) +print("packet1", data[:n]) + +# Read second incoming packet +n2 = 0 +deadline2 = time.monotonic() + 5.0 +while n2 == 0 and time.monotonic() < deadline2: + n2 = pb.readinto(data) + if n2 == 0: + time.sleep(0.05) +print("packet2", data[:n2]) + +for _ in range(80): + if not adapter.connected: + break + time.sleep(0.1) +print("done") +""" + +BSIM_PB_CLIENT_IN_CODE = """\ +import _bleio +import time + +adapter = _bleio.adapter + +target = None +for entry in adapter.start_scan(timeout=6.0, active=True): + if entry.connectable and b"CPPBIN" in entry.advertisement_bytes: + target = entry.address + print("found server") + break +adapter.stop_scan() + +connection = adapter.connect(target, timeout=5.0) +print("connected", connection.connected) + +services = connection.discover_remote_services([_bleio.UUID(0xFFE0)]) +print("discovered services", len(services)) + +remote_char = services[0].characteristics[0] +print("found char") + +# Write two packets +remote_char.value = bytes([0x01, 0x02, 0x03, 0x04]) +print("wrote packet1") + +time.sleep(0.3) + +remote_char.value = bytes([0xAA, 0xBB, 0xCC, 0xDD, 0xEE]) +print("wrote packet2") + +time.sleep(0.5) + +connection.disconnect() + +timeout = time.monotonic() + 4.0 +while connection.connected and time.monotonic() < timeout: + time.sleep(0.1) +print("done") +""" + + +@pytest.mark.duration(25) +@pytest.mark.circuitpy_drive({"code.py": BSIM_PB_SERVER_IN_CODE}) +@pytest.mark.circuitpy_drive({"code.py": BSIM_PB_CLIENT_IN_CODE}) +def test_bsim_packet_buffer_server_incoming(bsim_phy, circuitpython1, circuitpython2): + """PacketBuffer on server-side WRITE characteristic receives framed packets.""" + server = circuitpython1 + client = circuitpython2 + + client.wait_until_done() + server.wait_until_done() + + server_output = server.serial.all_output + client_output = client.serial.all_output + + assert "service created" in server_output + assert "connected True" in server_output + assert "packet1" in server_output + assert "packet2" in server_output + assert "done" in server_output + + assert "found server" in client_output + assert "wrote packet1" in client_output + assert "wrote packet2" in client_output + + +# ---- Test 2: Server-side PacketBuffer write/flush (NOTIFY response) ---- + +BSIM_PB_BIDI_SERVER_CODE = """\ +import _bleio +import time + +adapter = _bleio.adapter + +svc = _bleio.Service(_bleio.UUID(0xFFE0)) +char = _bleio.Characteristic.add_to_service( + svc, _bleio.UUID(0xFFE1), + properties=_bleio.Characteristic.WRITE | _bleio.Characteristic.NOTIFY, + read_perm=_bleio.Attribute.NO_ACCESS, + write_perm=_bleio.Attribute.OPEN, + max_length=20, fixed_length=False, +) + +# Wrap in PacketBuffer for incoming packets and outgoing notifications +pb = _bleio.PacketBuffer(char, buffer_size=4, max_packet_size=20) +print("service created") + +name = b"CPPBBI" +advertisement = bytes((2, 0x01, 0x06, len(name) + 1, 0x09)) + name +adapter.start_advertising(advertisement, connectable=True) +print("advertising") + +for _ in range(80): + if adapter.connected: + break + time.sleep(0.1) +print("connected", adapter.connected) + +# Read incoming packet from client +data = bytearray(20) +n = 0 +deadline = time.monotonic() + 5.0 +while n == 0 and time.monotonic() < deadline: + n = pb.readinto(data) + if n == 0: + time.sleep(0.05) +print("received", data[:n]) + +# Write response back (via NOTIFY) — sends immediately via completion callback +pb.write(bytes([0x52, 0x45, 0x53, 0x50])) # "RESP" +print("sent response") + +for _ in range(80): + if not adapter.connected: + break + time.sleep(0.1) +print("done") +""" + +BSIM_PB_BIDI_CLIENT_CODE = """\ +import _bleio +import time + +adapter = _bleio.adapter + +target = None +for entry in adapter.start_scan(timeout=6.0, active=True): + if entry.connectable and b"CPPBBI" in entry.advertisement_bytes: + target = entry.address + print("found server") + break +adapter.stop_scan() + +connection = adapter.connect(target, timeout=5.0) +print("connected", connection.connected) + +services = connection.discover_remote_services([_bleio.UUID(0xFFE0)]) +print("discovered services", len(services)) + +remote_char = services[0].characteristics[0] +print("found char, props", remote_char.properties) + +# Write a packet to the server +remote_char.value = bytes([0x48, 0x45, 0x4C, 0x4C, 0x4F]) # "HELLO" +print("wrote hello") + +connection.disconnect() + +timeout = time.monotonic() + 4.0 +while connection.connected and time.monotonic() < timeout: + time.sleep(0.1) +print("done") +""" + + +@pytest.mark.duration(20) +@pytest.mark.circuitpy_drive({"code.py": BSIM_PB_BIDI_SERVER_CODE}) +@pytest.mark.circuitpy_drive({"code.py": BSIM_PB_BIDI_CLIENT_CODE}) +def test_bsim_packet_buffer_bidirectional(bsim_phy, circuitpython1, circuitpython2): + """Bidirectional PacketBuffer: server receives WRITE, sends NOTIFY response.""" + server = circuitpython1 + client = circuitpython2 + + client.wait_until_done() + server.wait_until_done() + + server_output = server.serial.all_output + client_output = client.serial.all_output + + assert "service created" in server_output + assert "connected True" in server_output + assert "received" in server_output + assert "sent response" in server_output + assert "done" in server_output + + assert "found server" in client_output + assert "wrote hello" in client_output + assert "done" in client_output + + +# ---- Test 3: PacketBuffer with multiple queued incoming packets ---- + +BSIM_PB_QUEUE_SERVER_CODE = """\ +import _bleio +import time + +adapter = _bleio.adapter + +svc = _bleio.Service(_bleio.UUID(0xFFE0)) +char = _bleio.Characteristic.add_to_service( + svc, _bleio.UUID(0xFFE1), + properties=_bleio.Characteristic.WRITE, + read_perm=_bleio.Attribute.NO_ACCESS, + write_perm=_bleio.Attribute.OPEN, + max_length=20, fixed_length=False, +) + +# Small buffer: only 1 packet, small max_packet_size +pb = _bleio.PacketBuffer(char, buffer_size=1, max_packet_size=10) +print("service created") + +name = b"CPPBQU" +advertisement = bytes((2, 0x01, 0x06, len(name) + 1, 0x09)) + name +adapter.start_advertising(advertisement, connectable=True) +print("advertising") + +for _ in range(80): + if adapter.connected: + break + time.sleep(0.1) +print("connected", adapter.connected) + +# Wait for client to send all packets +time.sleep(1.0) + +# Read packets - with buffer_size=1, oldest packets are dropped +data = bytearray(20) + +n1 = pb.readinto(data) +print("pkt1", data[:n1]) + +n2 = pb.readinto(data) +print("pkt2", data[:n2]) + +for _ in range(80): + if not adapter.connected: + break + time.sleep(0.1) +print("done") +""" + +BSIM_PB_QUEUE_CLIENT_CODE = """\ +import _bleio +import time + +adapter = _bleio.adapter + +target = None +for entry in adapter.start_scan(timeout=6.0, active=True): + if entry.connectable and b"CPPBQU" in entry.advertisement_bytes: + target = entry.address + print("found server") + break +adapter.stop_scan() + +connection = adapter.connect(target, timeout=5.0) +print("connected", connection.connected) + +services = connection.discover_remote_services([_bleio.UUID(0xFFE0)]) +remote_char = services[0].characteristics[0] + +# Write 3 packets quickly (buffer only holds 2, so oldest should be dropped) +remote_char.value = bytes([0x01, 0x02, 0x03]) +print("wrote pkt1") + +time.sleep(0.1) + +remote_char.value = bytes([0x04, 0x05, 0x06]) +print("wrote pkt2") + +time.sleep(0.1) + +remote_char.value = bytes([0x07, 0x08, 0x09]) +print("wrote pkt3") + +time.sleep(0.5) + +connection.disconnect() + +timeout = time.monotonic() + 4.0 +while connection.connected and time.monotonic() < timeout: + time.sleep(0.1) +print("done") +""" + + +@pytest.mark.duration(30) +@pytest.mark.circuitpy_drive({"code.py": BSIM_PB_QUEUE_SERVER_CODE}) +@pytest.mark.circuitpy_drive({"code.py": BSIM_PB_QUEUE_CLIENT_CODE}) +def test_bsim_packet_buffer_queue(bsim_phy, circuitpython1, circuitpython2): + """PacketBuffer queues multiple packets; oldest dropped when buffer full.""" + server = circuitpython1 + client = circuitpython2 + + client.wait_until_done() + server.wait_until_done() + + server_output = server.serial.all_output + client_output = client.serial.all_output + + assert "service created" in server_output + assert "connected True" in server_output + # With buffer_size=1, only the last packet(s) remain + assert "pkt1" in server_output + assert "pkt2" in server_output + assert "done" in server_output + + assert "wrote pkt1" in client_output + assert "wrote pkt2" in client_output + assert "wrote pkt3" in client_output + + +# ---- Test 4: readinto with buffer too small returns negative ---- + +BSIM_PB_OVERFLOW_SERVER_CODE = """\ +import _bleio +import time + +adapter = _bleio.adapter + +svc = _bleio.Service(_bleio.UUID(0xFFE0)) +char = _bleio.Characteristic.add_to_service( + svc, _bleio.UUID(0xFFE1), + properties=_bleio.Characteristic.WRITE, + read_perm=_bleio.Attribute.NO_ACCESS, + write_perm=_bleio.Attribute.OPEN, + max_length=20, fixed_length=False, +) + +pb = _bleio.PacketBuffer(char, buffer_size=4, max_packet_size=20) +print("service created") + +name = b"CPPBOV" +advertisement = bytes((2, 0x01, 0x06, len(name) + 1, 0x09)) + name +adapter.start_advertising(advertisement, connectable=True) + +for _ in range(80): + if adapter.connected: + break + time.sleep(0.1) +print("connected", adapter.connected) + +# Try to read a 5-byte packet into a 3-byte buffer -> ValueError +try: + data = bytearray(3) + n = 0 + deadline = time.monotonic() + 5.0 + while n == 0 and time.monotonic() < deadline: + n = pb.readinto(data) + if n == 0: + time.sleep(0.05) + print("unexpected success", n) +except ValueError as e: + print("valueerror", e) + +time.sleep(0.5) +for _ in range(80): + if not adapter.connected: + break + time.sleep(0.1) +print("done") +""" + +BSIM_PB_OVERFLOW_CLIENT_CODE = """\ +import _bleio +import time + +adapter = _bleio.adapter + +target = None +for entry in adapter.start_scan(timeout=6.0, active=True): + if entry.connectable and b"CPPBOV" in entry.advertisement_bytes: + target = entry.address + break +adapter.stop_scan() + +connection = adapter.connect(target, timeout=5.0) + +services = connection.discover_remote_services([_bleio.UUID(0xFFE0)]) +remote_char = services[0].characteristics[0] + +# Write a 5-byte packet, but server only has a 3-byte read buffer +remote_char.value = bytes([0x01, 0x02, 0x03, 0x04, 0x05]) +print("wrote 5 bytes") + +time.sleep(0.5) +connection.disconnect() + +timeout = time.monotonic() + 4.0 +while connection.connected and time.monotonic() < timeout: + time.sleep(0.1) +print("done") +""" + + +@pytest.mark.duration(25) +@pytest.mark.circuitpy_drive({"code.py": BSIM_PB_OVERFLOW_SERVER_CODE}) +@pytest.mark.circuitpy_drive({"code.py": BSIM_PB_OVERFLOW_CLIENT_CODE}) +def test_bsim_packet_buffer_readinto_overflow(bsim_phy, circuitpython1, circuitpython2): + """readinto returns negative when packet is larger than buffer.""" + server = circuitpython1 + client = circuitpython2 + + client.wait_until_done() + server.wait_until_done() + + server_output = server.serial.all_output + client_output = client.serial.all_output + + assert "service created" in server_output + assert "valueerror" in server_output + + assert "wrote 5 bytes" in client_output + + +# ---- Test 5: write() with header kwarg ---- + +BSIM_PB_HEADER_SERVER_CODE = """\ +import _bleio +import time + +adapter = _bleio.adapter + +svc = _bleio.Service(_bleio.UUID(0xFFE0)) +char = _bleio.Characteristic.add_to_service( + svc, _bleio.UUID(0xFFE1), + properties=_bleio.Characteristic.WRITE | _bleio.Characteristic.NOTIFY, + read_perm=_bleio.Attribute.NO_ACCESS, + write_perm=_bleio.Attribute.OPEN, + max_length=20, fixed_length=False, +) + +pb = _bleio.PacketBuffer(char, buffer_size=4, max_packet_size=20) +print("service created") + +name = b"CPPBHD" +advertisement = bytes((2, 0x01, 0x06, len(name) + 1, 0x09)) + name +adapter.start_advertising(advertisement, connectable=True) + +for _ in range(80): + if adapter.connected: + break + time.sleep(0.1) +print("connected", adapter.connected) + +# Read an incoming packet +data = bytearray(20) +n = 0 +deadline = time.monotonic() + 5.0 +while n == 0 and time.monotonic() < deadline: + n = pb.readinto(data) + if n == 0: + time.sleep(0.05) +print("received", data[:n]) + +# Response: write body with a header — header goes at start of packet +pb.write(bytes([0x42, 0x4F, 0x44, 0x59]), header=bytes([0x48, 0x44])) # "HD" + "BODY" +print("sent with header") + +for _ in range(80): + if not adapter.connected: + break + time.sleep(0.1) +print("done") +""" + +BSIM_PB_HEADER_CLIENT_CODE = """\ +import _bleio +import time + +adapter = _bleio.adapter + +target = None +for entry in adapter.start_scan(timeout=6.0, active=True): + if entry.connectable and b"CPPBHD" in entry.advertisement_bytes: + target = entry.address + break +adapter.stop_scan() + +connection = adapter.connect(target, timeout=5.0) + +services = connection.discover_remote_services([_bleio.UUID(0xFFE0)]) +remote_char = services[0].characteristics[0] + +# Write a packet to trigger the server's response +remote_char.value = bytes([0x47, 0x4F]) +print("wrote trigger") + +connection.disconnect() + +timeout = time.monotonic() + 4.0 +while connection.connected and time.monotonic() < timeout: + time.sleep(0.1) +print("done") +""" + + +@pytest.mark.duration(25) +@pytest.mark.circuitpy_drive({"code.py": BSIM_PB_HEADER_SERVER_CODE}) +@pytest.mark.circuitpy_drive({"code.py": BSIM_PB_HEADER_CLIENT_CODE}) +def test_bsim_packet_buffer_write_header(bsim_phy, circuitpython1, circuitpython2): + """write() header kwarg prepends to packet body.""" + server = circuitpython1 + client = circuitpython2 + + client.wait_until_done() + server.wait_until_done() + + server_output = server.serial.all_output + client_output = client.serial.all_output + + assert "service created" in server_output + assert "received" in server_output + assert "sent with header" in server_output + + assert "wrote trigger" in client_output + + +# ---- Test 6: incoming_packet_length / outgoing_packet_length ---- + +BSIM_PB_LENGTHS_CODE = """\ +import _bleio + +svc = _bleio.Service(_bleio.UUID(0xFFE0)) +char = _bleio.Characteristic.add_to_service( + svc, _bleio.UUID(0xFFE1), + properties=_bleio.Characteristic.WRITE | _bleio.Characteristic.NOTIFY, + read_perm=_bleio.Attribute.NO_ACCESS, + write_perm=_bleio.Attribute.OPEN, + max_length=20, fixed_length=False, +) + +pb = _bleio.PacketBuffer(char, buffer_size=2, max_packet_size=15) + +# incoming_packet_length reflects the max we can receive (characteristic max_length) +print("incoming", pb.incoming_packet_length) +# outgoing_packet_length requires a connection to know the negotiated ATT MTU, +# so without one it raises ValueError (server-side NOTIFY is MTU-bounded). +try: + print("outgoing", pb.outgoing_packet_length) +except ValueError as e: + print("outgoing valueerror", e) +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": BSIM_PB_LENGTHS_CODE}) +def test_bsim_packet_buffer_packet_lengths(bsim_phy, circuitpython): + """incoming_packet_length and outgoing_packet_length properties.""" + circuitpython.wait_until_done() + output = circuitpython.serial.all_output + + # Server-side local characteristic: + # incoming = max_length = 20 + # outgoing requires a connection to know the ATT MTU, so it raises without one. + assert "incoming 20" in output + assert "outgoing valueerror" in output + assert "done" in output + + +# ---- Test 7: disconnect / reconnect, conn tracking ---- + +BSIM_PB_RECONNECT_SERVER_CODE = """\ +import _bleio +import time + +adapter = _bleio.adapter + +svc = _bleio.Service(_bleio.UUID(0xFFE0)) +char = _bleio.Characteristic.add_to_service( + svc, _bleio.UUID(0xFFE1), + properties=_bleio.Characteristic.WRITE | _bleio.Characteristic.NOTIFY, + read_perm=_bleio.Attribute.NO_ACCESS, + write_perm=_bleio.Attribute.OPEN, + max_length=20, fixed_length=False, +) + +pb = _bleio.PacketBuffer(char, buffer_size=4, max_packet_size=20) +print("service created") + +name = b"CPPBRC" +advertisement = bytes((2, 0x01, 0x06, len(name) + 1, 0x09)) + name +adapter.start_advertising(advertisement, connectable=True) + +# First connection +for _ in range(80): + if adapter.connected: + break + time.sleep(0.1) +print("connected1", adapter.connected) + +# Read first packet +data = bytearray(20) +n = 0 +deadline = time.monotonic() + 5.0 +while n == 0 and time.monotonic() < deadline: + n = pb.readinto(data) + if n == 0: + time.sleep(0.05) +print("packet1", data[:n]) + +# Send a response to confirm the tracked conn works +pb.write(bytes([0x41, 0x43, 0x4B])) # "ACK" +print("sent ack1") + +# Wait for disconnect +for _ in range(80): + if not adapter.connected: + break + time.sleep(0.1) +print("disconnected") + +# Start advertising again for second connection +adapter.start_advertising(advertisement, connectable=True) + +# Second connection +for _ in range(80): + if adapter.connected: + break + time.sleep(0.1) +print("connected2", adapter.connected) + +# Read second packet (should track new conn) +n2 = 0 +deadline2 = time.monotonic() + 5.0 +while n2 == 0 and time.monotonic() < deadline2: + n2 = pb.readinto(data) + if n2 == 0: + time.sleep(0.05) +print("packet2", data[:n2]) + +pb.write(bytes([0x41, 0x43, 0x4B])) # "ACK" +print("sent ack2") + +for _ in range(80): + if not adapter.connected: + break + time.sleep(0.1) +print("done") +""" + +BSIM_PB_RECONNECT_CLIENT_CODE = """\ +import _bleio +import time + +adapter = _bleio.adapter + +# First connection +target = None +for entry in adapter.start_scan(timeout=6.0, active=True): + if entry.connectable and b"CPPBRC" in entry.advertisement_bytes: + target = entry.address + break +adapter.stop_scan() + +connection = adapter.connect(target, timeout=5.0) +print("connected1", connection.connected) + +services = connection.discover_remote_services([_bleio.UUID(0xFFE0)]) +remote_char = services[0].characteristics[0] + +# Write first packet +remote_char.value = bytes([0x46, 0x49, 0x52, 0x53, 0x54]) # "FIRST" +print("wrote first") + +time.sleep(0.5) + +# Disconnect +connection.disconnect() +timeout = time.monotonic() + 4.0 +while connection.connected and time.monotonic() < timeout: + time.sleep(0.1) +print("disconnected") + +# Wait for server to re-advertise +time.sleep(0.5) + +# Second connection +target = None +for entry in adapter.start_scan(timeout=6.0, active=True): + if entry.connectable and b"CPPBRC" in entry.advertisement_bytes: + target = entry.address + break +adapter.stop_scan() + +connection = adapter.connect(target, timeout=5.0) +print("connected2", connection.connected) + +services = connection.discover_remote_services([_bleio.UUID(0xFFE0)]) +remote_char = services[0].characteristics[0] + +# Write second packet +remote_char.value = bytes([0x53, 0x45, 0x43, 0x4E, 0x44]) # "SECOND" +print("wrote second") + +time.sleep(0.5) +connection.disconnect() + +timeout = time.monotonic() + 4.0 +while connection.connected and time.monotonic() < timeout: + time.sleep(0.1) +print("done") +""" + + +@pytest.mark.duration(30) +@pytest.mark.circuitpy_drive( + {"code.py": BSIM_PB_RECONNECT_SERVER_CODE, "settings.toml": "CIRCUITPY_BLE_WORKFLOW = false\n"} +) +@pytest.mark.circuitpy_drive( + {"code.py": BSIM_PB_RECONNECT_CLIENT_CODE, "settings.toml": "CIRCUITPY_BLE_WORKFLOW = false\n"} +) +def test_bsim_packet_buffer_reconnect(bsim_phy, circuitpython1, circuitpython2): + """PacketBuffer tracks conn through disconnect / reconnect.""" + server = circuitpython1 + client = circuitpython2 + + client.wait_until_done() + server.wait_until_done() + + server_output = server.serial.all_output + client_output = client.serial.all_output + + assert "service created" in server_output + assert "connected1 True" in server_output + assert "packet1" in server_output + assert "sent ack1" in server_output + assert "disconnected" in server_output + assert "connected2 True" in server_output + assert "packet2" in server_output + assert "sent ack2" in server_output + + assert "wrote first" in client_output + assert "wrote second" in client_output + + +# ---- Test 8: outgoing_packet_length bounded by negotiated MTU ---- +# +# Regression test for the "No ATT channel for MTU" bug. The server-side +# PacketBuffer's outgoing_packet_length must be bounded by the negotiated +# ATT MTU (ATT_MTU - 3), not just max_packet_size. Without that bounding, +# the workflow packs a notification larger than the MTU and bt_gatt_notify_cb +# fails silently ("No ATT channel for MTU"), so the client never receives it. +# +# The characteristic is configured with max_length=600 and max_packet_size=600, +# deliberately larger than any plausible negotiated ATT MTU (the stack supports +# up to CONFIG_BT_L2CAP_TX_MTU = 515, payload 512). So without the fix, +# outgoing_packet_length returns 600 and the 600-byte notification always +# exceeds the MTU and is dropped — regardless of whether an MTU exchange +# happened. With the fix, outgoing_packet_length is ATT_MTU - 3 (≤ 512) and the +# notification fits and is delivered. + +BSIM_PB_MTU_SERVER_CODE = """\ +import _bleio +import time + +adapter = _bleio.adapter + +svc = _bleio.Service(_bleio.UUID(0xFFE0)) +char = _bleio.Characteristic.add_to_service( + svc, _bleio.UUID(0xFFE1), + properties=_bleio.Characteristic.WRITE | _bleio.Characteristic.NOTIFY, + read_perm=_bleio.Attribute.NO_ACCESS, + write_perm=_bleio.Attribute.OPEN, + max_length=600, fixed_length=False, +) + +# max_packet_size deliberately larger than any negotiated ATT MTU so that an +# unbounded outgoing_packet_length always produces an oversized, undeliverable +# notification regardless of MTU-exchange timing. +pb = _bleio.PacketBuffer(char, buffer_size=4, max_packet_size=600) +print("service created") + +name = b"CPPBMT" +advertisement = bytes((2, 0x01, 0x06, len(name) + 1, 0x09)) + name +adapter.start_advertising(advertisement, connectable=True) +print("advertising") + +for _ in range(80): + if adapter.connected: + break + time.sleep(0.1) +print("connected", adapter.connected) + +# Wait for the client to subscribe (CCCD write) and send a trigger write. +data = bytearray(600) +n = 0 +deadline = time.monotonic() + 5.0 +while n == 0 and time.monotonic() < deadline: + n = pb.readinto(data) + if n == 0: + time.sleep(0.05) +print("trigger", data[:n]) + +# The negotiated ATT MTU determines the largest notification payload. The +# connection's max_packet_length is ATT_MTU - 3. +conn = adapter.connections[0] +mtu_payload = conn.max_packet_length +print("mtu_payload", mtu_payload) + +# outgoing_packet_length must be bounded by the MTU, not max_packet_size. +opl = pb.outgoing_packet_length +print("outgoing", opl) + +# Send a response sized exactly to outgoing_packet_length, like the BLE +# file-transfer workflow does. With the fix this fits the MTU and is delivered. +response = bytes([0xAA]) * opl +pb.write(response) +print("sent", len(response)) + +for _ in range(80): + if not adapter.connected: + break + time.sleep(0.1) +print("done") +""" + +BSIM_PB_MTU_CLIENT_CODE = """\ +import _bleio +import time + +adapter = _bleio.adapter + +target = None +for entry in adapter.start_scan(timeout=6.0, active=True): + if entry.connectable and b"CPPBMT" in entry.advertisement_bytes: + target = entry.address + print("found server") + break +adapter.stop_scan() + +connection = adapter.connect(target, timeout=5.0) +print("connected", connection.connected) + +services = connection.discover_remote_services([_bleio.UUID(0xFFE0)]) +remote_char = services[0].characteristics[0] +print("found char, props", remote_char.properties) + +# Creating a client-side PacketBuffer on a NOTIFY characteristic writes the +# CCCD to subscribe, which gives the server a connection to notify. +client_pb = _bleio.PacketBuffer(remote_char, buffer_size=4, max_packet_size=600) +print("subscribed") + +# Trigger the server's response with a direct write. +remote_char.value = b"GO" +print("wrote trigger") + +# Read the notification response. Without the MTU fix the server sends an +# oversized notification that the ATT layer drops, so this times out. +buf = bytearray(600) +n = 0 +deadline = time.monotonic() + 5.0 +while n == 0 and time.monotonic() < deadline: + n = client_pb.readinto(buf) + if n == 0: + time.sleep(0.05) +if n > 0: + print("received_ok", n, bytes(buf[:n])) +else: + print("received_none") + +time.sleep(0.5) +connection.disconnect() + +timeout = time.monotonic() + 4.0 +while connection.connected and time.monotonic() < timeout: + time.sleep(0.1) +print("done") +""" + + +@pytest.mark.duration(30) +@pytest.mark.circuitpy_drive({"code.py": BSIM_PB_MTU_SERVER_CODE}) +@pytest.mark.circuitpy_drive({"code.py": BSIM_PB_MTU_CLIENT_CODE}) +def test_bsim_packet_buffer_outgoing_mtu_bounded(bsim_phy, circuitpython1, circuitpython2): + """Server-side outgoing_packet_length is bounded by the negotiated ATT MTU. + + Without the fix, outgoing_packet_length returns max_packet_size (200) and + the resulting notification exceeds the bsim default ATT MTU (23), so the + ATT layer drops it ("No ATT channel for MTU") and the client receives + nothing. With the fix, outgoing_packet_length is ATT_MTU - 3 (20) and the + notification is delivered to the client. + """ + server = circuitpython1 + client = circuitpython2 + + client.wait_until_done() + server.wait_until_done() + + server_output = server.serial.all_output + client_output = client.serial.all_output + + assert "service created" in server_output + assert "connected True" in server_output + assert "trigger" in server_output + + # outgoing_packet_length must not exceed the connection's MTU-derived + # max_packet_length. Without the fix this is 200 vs 20. + mtu_match = re.search(r"mtu_payload (\d+)", server_output) + outgoing_match = re.search(r"outgoing (\d+)", server_output) + assert mtu_match is not None, f"mtu_payload not printed: {server_output}" + assert outgoing_match is not None, f"outgoing not printed: {server_output}" + mtu_payload = int(mtu_match.group(1)) + outgoing = int(outgoing_match.group(1)) + assert outgoing <= mtu_payload, ( + f"outgoing_packet_length {outgoing} exceeds MTU payload {mtu_payload}; " + "notifications this size would be dropped by the ATT layer" + ) + assert outgoing < 600, f"outgoing_packet_length {outgoing} not bounded below max_packet_size" + + # The notification sized to outgoing_packet_length must actually arrive. + assert "received_ok" in client_output, ( + f"client never received the notification (MTU-bound bug): {client_output}" + ) + assert "received_none" not in client_output + + received_match = re.search(r"received_ok (\d+)", client_output) + assert received_match is not None + received = int(received_match.group(1)) + assert received == outgoing, f"client received {received} bytes, server sent {outgoing}" + + +# ---- Test: client-side PacketBuffer write (remote WRITE_NO_RESPONSE) ---- +# +# Covers the client-side write path in common_hal_bleio_packet_buffer_write +# (the is_remote branch): a CP central wraps a remote characteristic in a +# _bleio.PacketBuffer and writes to it via pb.write(...), which must reach the +# peripheral's server-side PacketBuffer. This mirrors how the BLE file-transfer +# library sends commands (raw.write). It also exercises the header+data combine +# in the client write path via pb.write(data, header=...). +# +# The characteristic uses WRITE_NO_RESPONSE | NOTIFY with open permissions, so +# no pairing is required and the test runs on both bsim boards. + +BSIM_PB_CLIENT_WRITE_SERVER_CODE = """\ +import _bleio +import time + +adapter = _bleio.adapter + +svc = _bleio.Service(_bleio.UUID(0xFFE0)) +char = _bleio.Characteristic.add_to_service( + svc, _bleio.UUID(0xFFE1), + properties=_bleio.Characteristic.WRITE_NO_RESPONSE | _bleio.Characteristic.NOTIFY, + read_perm=_bleio.Attribute.OPEN, + write_perm=_bleio.Attribute.OPEN, + max_length=20, fixed_length=False, +) + +# Server-side PacketBuffer: reads incoming WRITE_NO_RESPONSE, echoes via NOTIFY. +pb = _bleio.PacketBuffer(char, buffer_size=4, max_packet_size=20) +print("service created") + +name = b"CPPBCW" +advertisement = bytes((2, 0x01, 0x06, len(name) + 1, 0x09)) + name +adapter.start_advertising(advertisement, connectable=True) +print("advertising") + +for _ in range(80): + if adapter.connected: + break + time.sleep(0.1) +print("connected", adapter.connected) + +data = bytearray(20) +for _ in range(2): + n = 0 + deadline = time.monotonic() + 5.0 + while n == 0 and time.monotonic() < deadline: + n = pb.readinto(data) + if n == 0: + time.sleep(0.05) + print("received", bytes(data[:n])) + # Echo the packet straight back over NOTIFY. + pb.write(bytes(data[:n])) + print("echoed", bytes(data[:n])) + +for _ in range(80): + if not adapter.connected: + break + time.sleep(0.1) +print("done") +""" + +BSIM_PB_CLIENT_WRITE_CLIENT_CODE = """\ +import _bleio +import time + +adapter = _bleio.adapter + +target = None +for entry in adapter.start_scan(timeout=6.0, active=True): + if entry.connectable and b"CPPBCW" in entry.advertisement_bytes: + target = entry.address + print("found server") + break +adapter.stop_scan() + +connection = adapter.connect(target, timeout=5.0) +print("connected", connection.connected) + +services = connection.discover_remote_services([_bleio.UUID(0xFFE0)]) +print("discovered services", len(services)) + +remote_char = services[0].characteristics[0] +print("found char, props", remote_char.properties) + +# Client-side PacketBuffer on the remote characteristic: subscribes to NOTIFY +# (readinto) and writes to the remote (pb.write -> client-side write path). +cpb = _bleio.PacketBuffer(remote_char, buffer_size=4, max_packet_size=20) + +# Write 1: plain write (no header) — exercises bt_gatt_write_without_response. +cpb.write(b"PING") +print("wrote ping") + +# Write 2: write with a header — exercises the header+data combine in the +# client write path. "B" + "ODY" is sent as a single "BODY" packet. +cpb.write(b"ODY", header=b"B") +print("wrote body with header") + +# Read both NOTIFY echoes back. +buf = bytearray(20) +for _ in range(2): + n = 0 + deadline = time.monotonic() + 5.0 + while n == 0 and time.monotonic() < deadline: + n = cpb.readinto(buf) + if n == 0: + time.sleep(0.05) + print("client received", bytes(buf[:n])) + +connection.disconnect() + +timeout = time.monotonic() + 4.0 +while connection.connected and time.monotonic() < timeout: + time.sleep(0.1) +print("done") +""" + + +@pytest.mark.duration(35) +@pytest.mark.circuitpy_drive({"code.py": BSIM_PB_CLIENT_WRITE_SERVER_CODE}) +@pytest.mark.circuitpy_drive({"code.py": BSIM_PB_CLIENT_WRITE_CLIENT_CODE}) +def test_bsim_packet_buffer_client_write(bsim_phy, circuitpython1, circuitpython2): + """A CP central writes to a remote characteristic via a client-side + PacketBuffer (pb.write), and the peripheral echoes it back over NOTIFY. + + Covers the client-side write path (remote WRITE_NO_RESPONSE), including the + header+data combine, mirroring how the BLE file-transfer library sends + commands. + """ + server = circuitpython1 + client = circuitpython2 + + client.wait_until_done() + server.wait_until_done() + + server_output = server.serial.all_output + client_output = client.serial.all_output + + # Server received both client writes (plain + header-combined). + assert "received b'PING'" in server_output, ( + f"server never received the plain client write: {server_output}" + ) + assert "received b'BODY'" in server_output, ( + f"server never received the header-combined client write: {server_output}" + ) + assert "echoed b'PING'" in server_output + assert "echoed b'BODY'" in server_output + assert "done" in server_output + + # Client wrote both and got both echoes back over NOTIFY. + assert "wrote ping" in client_output, f"client plain write did not complete: {client_output}" + assert "wrote body with header" in client_output, ( + f"client header write did not complete: {client_output}" + ) + # Be vague here because PING and BODY may be in separate packets or merged. + assert "b'PING" in client_output, f"client never received the PING echo: {client_output}" + assert "BODY'" in client_output, f"client never received the BODY echo: {client_output}" + assert "done" in client_output diff --git a/ports/zephyr-cp/tests/bsim/test_bsim_ble_pairing.py b/ports/zephyr-cp/tests/bsim/test_bsim_ble_pairing.py new file mode 100644 index 00000000000..850b2fc8957 --- /dev/null +++ b/ports/zephyr-cp/tests/bsim/test_bsim_ble_pairing.py @@ -0,0 +1,364 @@ +# SPDX-FileCopyrightText: 2025 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""BLE pairing tests for the bsim boards.""" + +import pytest + +BSIM_PERIPHERAL_CODE = """\ +import _bleio +import time + +adapter = _bleio.adapter + +name = b"PAIRPERIPH" +advertisement = bytes((2, 0x01, 0x06, len(name) + 1, 0x09)) + name + +print("peripheral start") +adapter.start_advertising(advertisement, connectable=True) +print("peripheral advertising", adapter.advertising) + +# Wait for connection +timeout = time.monotonic() + 12.0 +while not adapter.connected and time.monotonic() < timeout: + time.sleep(0.01) + +if not adapter.connected: + print("peripheral connect timed out") + raise SystemExit(1) + +print("peripheral connected", adapter.connected) + +# Wait for pairing to complete (central initiates it) +# The peripheral's SMP module responds automatically. +timeout = time.monotonic() + 10.0 +paired = False +while time.monotonic() < timeout: + if adapter.connected and len(adapter.connections) > 0: + conn = adapter.connections[0] + if conn.paired: + paired = True + break + time.sleep(0.1) + +print("peripheral paired", paired) + +# Wait for disconnect +timeout = time.monotonic() + 10.0 +while adapter.connected and time.monotonic() < timeout: + time.sleep(0.1) + +print("peripheral disconnected", adapter.connected, len(adapter.connections)) +""" + +BSIM_CENTRAL_CODE = """\ +import _bleio +import time + +adapter = _bleio.adapter + +print("central start") +target = None +for entry in adapter.start_scan(timeout=8.0, active=True): + if entry.connectable and b"PAIRPERIPH" in entry.advertisement_bytes: + target = entry.address + print("central found target") + break +adapter.stop_scan() +print("central have target", target is not None) + +if target is None: + raise RuntimeError("No connectable target found") + +connection = adapter.connect(target, timeout=5.0) +print("central connected", connection.connected, adapter.connected, len(adapter.connections)) + +# Pair with the peripheral (Just Works pairing) +connection.pair() +print("central paired", connection.paired) + +# Disconnect cleanly +connection.disconnect() + +timeout = time.monotonic() + 4.0 +while (connection.connected or adapter.connected) and time.monotonic() < timeout: + time.sleep(0.1) + +print("central disconnected", connection.connected, adapter.connected, len(adapter.connections)) +""" + + +@pytest.mark.duration(22) +@pytest.mark.circuitpy_drive( + {"code.py": BSIM_PERIPHERAL_CODE, "settings.toml": "CIRCUITPY_BLE_WORKFLOW = false\n"} +) +@pytest.mark.circuitpy_drive( + {"code.py": BSIM_CENTRAL_CODE, "settings.toml": "CIRCUITPY_BLE_WORKFLOW = false\n"} +) +def test_bsim_pairing_cp_to_cp(bsim_phy, board, circuitpython1, circuitpython2): + """Two CP instances: device 0 peripheral, device 1 central pairs to it.""" + peripheral = circuitpython1 + central = circuitpython2 + + central.wait_until_done() + peripheral.wait_until_done() + + periph_output = peripheral.serial.all_output + central_output = central.serial.all_output + + # Peripheral assertions + assert "peripheral start" in periph_output + assert "peripheral advertising True" in periph_output + assert "peripheral connected True" in periph_output + assert "peripheral paired True" in periph_output + assert "peripheral disconnected False 0" in periph_output + + # Central assertions + assert "central start" in central_output + assert "central found target" in central_output + assert "central have target True" in central_output + assert "central connected True True 1" in central_output + assert "central paired True" in central_output + assert "central disconnected False False 0" in central_output + + +BSIM_CENTRAL_PAIRED_PROPERTY_CODE = """\ +import _bleio +import time + +adapter = _bleio.adapter + +print("central start") +target = None +for entry in adapter.start_scan(timeout=8.0, active=True): + if entry.connectable and b"PAIRPERIPH" in entry.advertisement_bytes: + target = entry.address + print("central found target") + break +adapter.stop_scan() + +if target is None: + raise RuntimeError("No connectable target found") + +connection = adapter.connect(target, timeout=5.0) +print("central connected", connection.connected) + +# Check paired is False before pairing +print("central paired before", connection.paired) + +connection.pair() +print("central paired after", connection.paired) + +connection.disconnect() + +timeout = time.monotonic() + 4.0 +while (connection.connected or adapter.connected) and time.monotonic() < timeout: + time.sleep(0.1) + +print("central disconnected", connection.connected) +""" + + +@pytest.mark.duration(22) +@pytest.mark.circuitpy_drive( + {"code.py": BSIM_PERIPHERAL_CODE, "settings.toml": "CIRCUITPY_BLE_WORKFLOW = false\n"} +) +@pytest.mark.circuitpy_drive( + { + "code.py": BSIM_CENTRAL_PAIRED_PROPERTY_CODE, + "settings.toml": "CIRCUITPY_BLE_WORKFLOW = false\n", + } +) +def test_bsim_pairing_paired_property(bsim_phy, board, circuitpython1, circuitpython2): + """Verify connection.paired transitions from False to True after pairing.""" + peripheral = circuitpython1 + central = circuitpython2 + + central.wait_until_done() + peripheral.wait_until_done() + + periph_output = peripheral.serial.all_output + central_output = central.serial.all_output + + assert "peripheral paired True" in periph_output + + assert "central paired before False" in central_output + assert "central paired after True" in central_output + assert "central disconnected False" in central_output + + +BSIM_PERIPHERAL_BOND_CODE = """\ +import _bleio +import time + +adapter = _bleio.adapter + +name = b"BONDPERIPH" +advertisement = bytes((2, 0x01, 0x06, len(name) + 1, 0x09)) + name + +print("peripheral start") + +# First connection - pair +adapter.start_advertising(advertisement, connectable=True) +print("peripheral advertising", adapter.advertising) + +timeout = time.monotonic() + 12.0 +while not adapter.connected and time.monotonic() < timeout: + time.sleep(0.01) + +if not adapter.connected: + print("peripheral connect1 timed out") + raise SystemExit(1) + +print("peripheral connected1", adapter.connected) + +# Wait for pairing +timeout = time.monotonic() + 10.0 +paired = False +while time.monotonic() < timeout: + if adapter.connected and len(adapter.connections) > 0: + conn = adapter.connections[0] + if conn.paired: + paired = True + break + time.sleep(0.1) + +print("peripheral paired1", paired) + +# Wait for disconnect +timeout = time.monotonic() + 10.0 +while adapter.connected and time.monotonic() < timeout: + time.sleep(0.1) + +print("peripheral disconnected1", adapter.connected, len(adapter.connections)) + +# Second connection - bond should persist through storage. +# Calling pair() uses the stored bond keys without re-pairing. +time.sleep(0.5) +adapter.start_advertising(advertisement, connectable=True) +print("peripheral advertising2", adapter.advertising) + +timeout = time.monotonic() + 12.0 +while not adapter.connected and time.monotonic() < timeout: + time.sleep(0.01) + +if not adapter.connected: + print("peripheral connect2 timed out") + raise SystemExit(1) + +print("peripheral connected2", adapter.connected) + +# Request security to restore bond encryption +conn = adapter.connections[0] +conn.pair() +print("peripheral paired2", conn.paired) + +# Wait for disconnect +timeout = time.monotonic() + 10.0 +while adapter.connected and time.monotonic() < timeout: + time.sleep(0.1) + +print("peripheral disconnected2", adapter.connected) +""" + +BSIM_CENTRAL_BOND_CODE = """\ +import _bleio +import time + +adapter = _bleio.adapter + +print("central start") +target_addr = None +for entry in adapter.start_scan(timeout=8.0, active=True): + if entry.connectable and b"BONDPERIPH" in entry.advertisement_bytes: + target_addr = entry.address + print("central found target") + break +adapter.stop_scan() +print("central have target", target_addr is not None) + +if target_addr is None: + raise RuntimeError("No connectable target found") + +# First connection - pair +connection = adapter.connect(target_addr, timeout=5.0) +print("central connected1", connection.connected, adapter.connected, len(adapter.connections)) + +print("central paired before1", connection.paired) +connection.pair() +print("central paired after1", connection.paired) + +connection.disconnect() + +timeout = time.monotonic() + 4.0 +while (connection.connected or adapter.connected) and time.monotonic() < timeout: + time.sleep(0.1) + +print("central disconnected1", connection.connected, adapter.connected) + +# Second connection - bond should be restored from storage. +# Calling pair() uses the stored bond keys without re-pairing. +time.sleep(1.0) +connection2 = adapter.connect(target_addr, timeout=5.0) +print("central connected2", connection2.connected, adapter.connected, len(adapter.connections)) + +connection2.pair() +print("central paired bond", connection2.paired) + +connection2.disconnect() + +timeout = time.monotonic() + 4.0 +while (connection2.connected or adapter.connected) and time.monotonic() < timeout: + time.sleep(0.1) + +print("central disconnected2", connection2.connected, adapter.connected) +""" + + +@pytest.mark.duration(35) +@pytest.mark.circuitpy_drive( + {"code.py": BSIM_PERIPHERAL_BOND_CODE, "settings.toml": "CIRCUITPY_BLE_WORKFLOW = false\n"} +) +@pytest.mark.circuitpy_drive( + {"code.py": BSIM_CENTRAL_BOND_CODE, "settings.toml": "CIRCUITPY_BLE_WORKFLOW = false\n"} +) +def test_bsim_bonding_persistence(bsim_phy, board, circuitpython1, circuitpython2): + """Verify bonds are saved to storage and survive disconnect/reconnect. + + Central pairs with peripheral, disconnects, then reconnects. + On the second connection the bond should be restored from storage + and connection.paired should be True without calling pair() again. + """ + peripheral = circuitpython1 + central = circuitpython2 + + central.wait_until_done() + peripheral.wait_until_done() + + periph_output = peripheral.serial.all_output + central_output = central.serial.all_output + + # Peripheral assertions - first connection + assert "peripheral start" in periph_output + assert "peripheral advertising True" in periph_output + assert "peripheral connected1 True" in periph_output + assert "peripheral paired1 True" in periph_output + assert "peripheral disconnected1 False 0" in periph_output + # Peripheral - second connection (private advertising, bond restored from storage) + assert "peripheral advertising2 True" in periph_output + assert "peripheral connected2 True" in periph_output + assert "peripheral paired2 True" in periph_output + assert "peripheral disconnected2 False" in periph_output + + # Central assertions - first connection + assert "central start" in central_output + assert "central found target" in central_output + assert "central have target True" in central_output + assert "central connected1 True True 1" in central_output + assert "central paired before1 False" in central_output + assert "central paired after1 True" in central_output + assert "central disconnected1 False False" in central_output + # Central - second connection (bond restored from storage) + assert "central connected2 True True 1" in central_output + assert "central paired bond True" in central_output + assert "central disconnected2 False False" in central_output diff --git a/ports/zephyr-cp/tests/bsim/test_bsim_ble_peripheral.py b/ports/zephyr-cp/tests/bsim/test_bsim_ble_peripheral.py new file mode 100644 index 00000000000..ff99b789f0c --- /dev/null +++ b/ports/zephyr-cp/tests/bsim/test_bsim_ble_peripheral.py @@ -0,0 +1,121 @@ +# SPDX-FileCopyrightText: 2026 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""BLE peripheral connection tests for bsim.""" + +import pytest + + +BSIM_PERIPHERAL_CODE = """\ +import _bleio +import time +import sys + +adapter = _bleio.adapter + +name = b"CPPERIPH" +advertisement = bytes((2, 0x01, 0x06, len(name) + 1, 0x09)) + name + +print("peripheral start") +adapter.start_advertising(advertisement, connectable=True) +print("advertising", adapter.advertising) + +was_connected = False +timeout = time.monotonic() + 8.0 +while not was_connected and time.monotonic() < timeout: + time.sleep(0.01) + was_connected = adapter.connected + +if not was_connected: + print("connect timed out") + sys.exit(-1) + +print("connected", was_connected, "advertising", adapter.advertising) + +if was_connected: + timeout = time.monotonic() + 8.0 + while adapter.connected and time.monotonic() < timeout: + time.sleep(0.1) + +print("disconnected", adapter.connected, len(adapter.connections)) +""" + +BSIM_CENTRAL_CODE = """\ +import _bleio +import time + +adapter = _bleio.adapter + +print("central start") +target = None +for entry in adapter.start_scan(timeout=6.0, active=True): + if entry.connectable and b"CPPERIPH" in entry.advertisement_bytes: + target = entry.address + print("found peripheral") + break +adapter.stop_scan() +print("have target", target is not None) + +if target is None: + raise RuntimeError("No connectable peripheral found") + +connection = adapter.connect(target, timeout=5.0) +print("connected", connection.connected, adapter.connected, len(adapter.connections)) +connection.disconnect() + +timeout = time.monotonic() + 4.0 +while (connection.connected or adapter.connected) and time.monotonic() < timeout: + time.sleep(0.1) + +print("disconnected", connection.connected, adapter.connected, len(adapter.connections)) +""" + + +@pytest.mark.zephyr_sample("bluetooth/central") +@pytest.mark.duration(14) +@pytest.mark.circuitpy_drive( + {"code.py": BSIM_PERIPHERAL_CODE, "settings.toml": "CIRCUITPY_BLE_WORKFLOW = false\n"} +) +def test_bsim_peripheral_zephyr_central(bsim_phy, circuitpython, zephyr_sample): + """Advertise as connectable from CP; Zephyr central connects and disconnects.""" + central = zephyr_sample + + circuitpython.wait_until_done() + + cp_output = circuitpython.serial.all_output + central_output = central.serial.all_output + + assert "peripheral start" in cp_output + assert "advertising True" in cp_output + assert "connected True advertising False" in cp_output + assert "disconnected False 0" in cp_output + + assert "Scanning successfully started" in central_output + assert "Connected:" in central_output + assert "Disconnected:" in central_output + + +@pytest.mark.duration(20) +@pytest.mark.circuitpy_drive({"code.py": BSIM_PERIPHERAL_CODE}) +@pytest.mark.circuitpy_drive({"code.py": BSIM_CENTRAL_CODE}) +def test_bsim_peripheral_cp_central(bsim_phy, circuitpython1, circuitpython2): + """Two CP instances: device 0 peripheral, device 1 central.""" + peripheral = circuitpython1 + central = circuitpython2 + + central.wait_until_done() + peripheral.wait_until_done() + + periph_output = peripheral.serial.all_output + central_output = central.serial.all_output + + assert "peripheral start" in periph_output + assert "advertising True" in periph_output + assert "connected True advertising False" in periph_output + assert "disconnected False 0" in periph_output + + assert "central start" in central_output + assert "found peripheral" in central_output + assert "have target True" in central_output + assert "connected True True 1" in central_output + assert "disconnected False False 0" in central_output diff --git a/ports/zephyr-cp/tests/bsim/test_bsim_ble_scan.py b/ports/zephyr-cp/tests/bsim/test_bsim_ble_scan.py new file mode 100644 index 00000000000..15de1787cdc --- /dev/null +++ b/ports/zephyr-cp/tests/bsim/test_bsim_ble_scan.py @@ -0,0 +1,161 @@ +# SPDX-FileCopyrightText: 2025 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""BLE scanning tests for bsim.""" + +import pytest + + +BSIM_SCAN_CODE = """\ +import _bleio + +adapter = _bleio.adapter +print("scan start") +scan = adapter.start_scan(timeout=4.0, active=True) +found = False +for entry in scan: + if b"zephyrproject" in entry.advertisement_bytes: + print("found beacon") + found = True + break +adapter.stop_scan() +print("scan done", found) +""" + +BSIM_SCAN_RELOAD_CODE = """\ +import _bleio +import time + +adapter = _bleio.adapter + +print("scan run start") +found = False +for entry in adapter.start_scan(active=True): + if b"zephyrproject" in entry.advertisement_bytes: + print("found beacon run") + found = True + break +adapter.stop_scan() +print("scan run done", found) +""" + +BSIM_SCAN_RELOAD_NO_STOP_CODE = """\ +import _bleio +import time + +adapter = _bleio.adapter + +print("scan run start") +found = False +for entry in adapter.start_scan(active=True): + if b"zephyrproject" in entry.advertisement_bytes: + print("found beacon run") + found = True + break +print("scan run done", found) +""" + +BSIM_SCAN_ENTRY_PROPS_CODE = """\ +import _bleio + +adapter = _bleio.adapter +print("scan start") +found = None +for entry in adapter.start_scan(timeout=4.0, active=True): + if b"zephyrproject" in entry.advertisement_bytes: + found = entry + break +adapter.stop_scan() + +if found is not None: + print("rssi", found.rssi <= 0 and found.rssi > -100) + print("connectable", found.connectable) + print("scan_response", found.scan_response) + print("address_bytes", len(found.address.address_bytes)) + print("address_type", found.address.type in (0, 1, 2, 3)) + print("adv_bytes_type", isinstance(found.advertisement_bytes, bytes)) +else: + print("no entry found") +print("done") +""" + +BSIM_SCAN_PASSIVE_CODE = """\ +import _bleio + +adapter = _bleio.adapter +print("scan passive start") +found = False +for entry in adapter.start_scan(timeout=4.0, active=False): + if b"zephyrproject" in entry.advertisement_bytes: + print("found beacon passive") + found = True + break +adapter.stop_scan() +print("scan passive done", found) +""" + + +@pytest.mark.zephyr_sample("bluetooth/beacon") +@pytest.mark.circuitpy_drive({"code.py": BSIM_SCAN_CODE}) +def test_bsim_scan_zephyr_beacon(bsim_phy, circuitpython, zephyr_sample): + """Scan for Zephyr beacon sample advertisement using bsim.""" + _ = zephyr_sample + + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "scan start" in output + assert "found beacon" in output + assert "scan done True" in output + + +@pytest.mark.zephyr_sample("bluetooth/beacon") +@pytest.mark.port_resets(3) +@pytest.mark.duration(20) +@pytest.mark.circuitpy_drive({"code.py": BSIM_SCAN_RELOAD_CODE}) +def test_bsim_scan_zephyr_beacon_reload(bsim_phy, circuitpython, zephyr_sample): + """Scan for Zephyr beacon, soft reload, and scan again.""" + _ = zephyr_sample + + circuitpython.serial.wait_for("scan run done") + circuitpython.serial.wait_for("Press any key to enter the REPL") + circuitpython.serial.write("\x04") + + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert output.count("scan run start") >= 2 + assert output.count("found beacon run") >= 2 + assert output.count("scan run done True") >= 2 + + +@pytest.mark.zephyr_sample("bluetooth/beacon") +@pytest.mark.circuitpy_drive({"code.py": BSIM_SCAN_ENTRY_PROPS_CODE}) +def test_bsim_scan_entry_properties(bsim_phy, circuitpython, zephyr_sample): + """Verify ScanEntry properties: rssi, connectable, scan_response, address, advertisement_bytes.""" + _ = zephyr_sample + + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "rssi True" in output + assert "connectable False" in output # beacon is non-connectable + assert "scan_response False" in output + assert "address_bytes 6" in output + assert "address_type True" in output + assert "adv_bytes_type True" in output + assert "done" in output + + +@pytest.mark.zephyr_sample("bluetooth/beacon") +@pytest.mark.circuitpy_drive({"code.py": BSIM_SCAN_PASSIVE_CODE}) +def test_bsim_scan_passive(bsim_phy, circuitpython, zephyr_sample): + """Passive scan finds Zephyr beacon.""" + _ = zephyr_sample + + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "scan passive start" in output + assert "found beacon passive" in output + assert "scan passive done True" in output diff --git a/ports/zephyr-cp/tests/bsim/test_bsim_ble_service.py b/ports/zephyr-cp/tests/bsim/test_bsim_ble_service.py new file mode 100644 index 00000000000..1d4174835d0 --- /dev/null +++ b/ports/zephyr-cp/tests/bsim/test_bsim_ble_service.py @@ -0,0 +1,715 @@ +# SPDX-FileCopyrightText: 2026 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""BLE GATT service tests for bsim.""" + +import pytest + +from .conftest import get_library_files + +_ADAFRUIT_BLE = get_library_files("adafruit_ble") + +# --------------------------------------------------------------------------- +# Shared service libraries +# --------------------------------------------------------------------------- + +BATTERY_LIB = """ +from adafruit_ble.services import Service +from adafruit_ble.characteristics import Characteristic, Attribute +from adafruit_ble.uuid import StandardUUID + + +class BatteryService(Service): + uuid = StandardUUID(0x180F) + level = Characteristic( + uuid=StandardUUID(0x2A19), + properties=Characteristic.READ | Characteristic.WRITE, + read_perm=Attribute.OPEN, + write_perm=Attribute.OPEN, + max_length=1, + fixed_length=True, + initial_value=bytes([75]), + )""" + +HEART_RATE_LIB = """ +from adafruit_ble.services import Service +from adafruit_ble.characteristics import Characteristic, Attribute +from adafruit_ble.uuid import StandardUUID + + +class HeartRateService(Service): + uuid = StandardUUID(0x180D) + measurement = Characteristic( + uuid=StandardUUID(0x2A37), + properties=Characteristic.READ, + read_perm=Attribute.OPEN, + write_perm=Attribute.NO_ACCESS, + max_length=2, + fixed_length=True, + initial_value=bytes([0, 72]), + )""" + +# =================================================================== +# Test 1: Battery Service (Zephyr central) +# =================================================================== + +BSIM_SERVICE_CODE = """\ +import time +from adafruit_ble import BLERadio +from adafruit_ble.advertising.standard import ProvideServicesAdvertisement +from battery_service import BatteryService + +ble = BLERadio() +svc = BatteryService() +print("service created") + +advertisement = ProvideServicesAdvertisement(svc) +ble.start_advertising(advertisement) +print("advertising") + +for _ in range(80): + if ble.connected: + break + time.sleep(0.1) +print("connected", ble.connected) + +for _ in range(80): + if not ble.connected: + break + time.sleep(0.1) +print("done") +""" + + +@pytest.mark.zephyr_sample("tests/bsim/samples/central_battery_client") +@pytest.mark.duration(14) +@pytest.mark.circuitpy_drive( + { + "code.py": BSIM_SERVICE_CODE, + "settings.toml": "CIRCUITPY_BLE_WORKFLOW = false\n", + "battery_service.py": BATTERY_LIB, + **_ADAFRUIT_BLE, + } +) +def test_bsim_service_battery(bsim_phy, circuitpython, zephyr_sample): + """CP hosts BatteryService; Zephyr central reads battery level.""" + circuitpython.wait_until_done() + + cp_output = circuitpython.serial.all_output + sample_output = zephyr_sample.serial.all_output + + assert "service created" in cp_output + assert "connected True" in cp_output + assert "Battery Level: 75" in sample_output + + +# =================================================================== +# Test 2: CP client reads/writes CP peripheral +# =================================================================== + +BSIM_SERVER_CODE = """\ +import time +from adafruit_ble import BLERadio +from adafruit_ble.advertising.standard import ProvideServicesAdvertisement +from battery_service import BatteryService + +ble = BLERadio() +svc = BatteryService() +print("service created") + +advertisement = ProvideServicesAdvertisement(svc) +ble.start_advertising(advertisement) +print("advertising") + +for _ in range(80): + if ble.connected: + break + time.sleep(0.1) +print("connected", ble.connected) + +for _ in range(80): + if not ble.connected: + break + time.sleep(0.1) + +print("final value", list(svc.level)) +print("done") +""" + +BSIM_CLIENT_CODE = """\ +import time +from adafruit_ble import BLERadio +from adafruit_ble.advertising.standard import ProvideServicesAdvertisement +from battery_service import BatteryService + +ble = BLERadio() + +print("client start") +target = None +for adv in ble.start_scan(ProvideServicesAdvertisement, timeout=6.0): + if adv.connectable: + target = adv + print("found server") + break +ble.stop_scan() +print("have target", target is not None) + +if target is None: + raise RuntimeError("No server found") + +connection = ble.connect(target, timeout=5.0) +print("connected", connection.connected) + +svc = connection[BatteryService] +print("discovered services", 1) +print("discovered chars", 1) # BatteryService has one characteristic + +print("battery level", list(svc.level)) + +# Write a new value +svc.level = bytes([42]) +print("wrote new value") + +time.sleep(0.5) + +connection.disconnect() + +timeout = time.monotonic() + 4.0 +while connection.connected and time.monotonic() < timeout: + time.sleep(0.1) + +print("disconnected", not connection.connected) +""" + + +@pytest.mark.duration(30) +@pytest.mark.circuitpy_drive( + {"code.py": BSIM_SERVER_CODE, "battery_service.py": BATTERY_LIB, **_ADAFRUIT_BLE} +) +@pytest.mark.circuitpy_drive( + {"code.py": BSIM_CLIENT_CODE, "battery_service.py": BATTERY_LIB, **_ADAFRUIT_BLE} +) +def test_bsim_service_cp_client(bsim_phy, circuitpython1, circuitpython2): + """CP peripheral hosts BatteryService; CP central discovers, reads, and writes.""" + server = circuitpython1 + client = circuitpython2 + + client.wait_until_done() + server.wait_until_done() + + server_output = server.serial.all_output + client_output = client.serial.all_output + + assert "service created" in server_output + assert "connected True" in server_output + assert "final value [42]" in server_output + + assert "client start" in client_output + assert "found server" in client_output + assert "discovered services 1" in client_output + assert "discovered chars 1" in client_output + assert "battery level [75]" in client_output + assert "wrote new value" in client_output + assert "disconnected True" in client_output + + +# =================================================================== +# Test 3: Discover all services (no whitelist) +# =================================================================== + +BSIM_DISCOVER_ALL_SERVER_CODE = """\ +import time +from adafruit_ble import BLERadio +from adafruit_ble.advertising.standard import ProvideServicesAdvertisement +from battery_service import BatteryService +from heart_rate import HeartRateService + +ble = BLERadio() +bas = BatteryService() +hrs = HeartRateService() +print("services created") + +advertisement = ProvideServicesAdvertisement(bas, hrs) +ble.start_advertising(advertisement) + +for _ in range(80): + if ble.connected: + break + time.sleep(0.1) +print("connected", ble.connected) + +for _ in range(80): + if not ble.connected: + break + time.sleep(0.1) +print("done") +""" + +BSIM_DISCOVER_ALL_CLIENT_CODE = """\ +import time +from adafruit_ble import BLERadio +from adafruit_ble.advertising.standard import ProvideServicesAdvertisement +from battery_service import BatteryService +from heart_rate import HeartRateService + +ble = BLERadio() + +print("client start") +target = None +for adv in ble.start_scan(ProvideServicesAdvertisement, timeout=8.0): + if adv.connectable: + target = adv + print("found server") + break +ble.stop_scan() +print("have target", target is not None) + +if target is None: + raise RuntimeError("No server found") + +connection = ble.connect(target, timeout=5.0) +print("connected", connection.connected) + +# Discover ALL services (no whitelist) — use _bleio directly. +all_services = connection._bleio_connection.discover_remote_services() +print("total services", len(all_services)) + +# Filter to our two known UUIDs (ignore GATT/GAP services the stack may expose) +user_svcs = [s for s in all_services if s.uuid.uuid16 in (0x180F, 0x180D)] +print("user services", len(user_svcs)) + +uuids = sorted([s.uuid.uuid16 for s in user_svcs]) +print("service uuids", uuids) + +# Now read characteristics via adafruit_ble Service bindings. +if BatteryService in connection: + bas = connection[BatteryService] + print("char", hex(0x2a19), list(bas.level)) + +if HeartRateService in connection: + hrs = connection[HeartRateService] + print("char", hex(0x2a37), list(hrs.measurement)) + +connection.disconnect() + +timeout = time.monotonic() + 4.0 +while connection.connected and time.monotonic() < timeout: + time.sleep(0.1) +print("done") +""" + + +@pytest.mark.duration(35) +@pytest.mark.circuitpy_drive( + { + "code.py": BSIM_DISCOVER_ALL_SERVER_CODE, + "battery_service.py": BATTERY_LIB, + "heart_rate.py": HEART_RATE_LIB, + **_ADAFRUIT_BLE, + } +) +@pytest.mark.circuitpy_drive( + { + "code.py": BSIM_DISCOVER_ALL_CLIENT_CODE, + "battery_service.py": BATTERY_LIB, + "heart_rate.py": HEART_RATE_LIB, + **_ADAFRUIT_BLE, + } +) +def test_bsim_service_discover_all(bsim_phy, circuitpython1, circuitpython2): + """Discover all services without a UUID whitelist, verify two user services found.""" + server = circuitpython1 + client = circuitpython2 + + client.wait_until_done() + server.wait_until_done() + + client_output = client.serial.all_output + + assert "user services 2" in client_output + assert "service uuids [6157, 6159]" in client_output # 0x180D=6157, 0x180F=6159 + assert "char 0x2a37 [0, 72]" in client_output + assert "char 0x2a19 [75]" in client_output + + +# =================================================================== +# Test 4: Write-no-response (uses MultiService from multi_service module) +# =================================================================== + +MULTI_LIB = """ +from adafruit_ble.services import Service +from adafruit_ble.characteristics import Characteristic, Attribute +from adafruit_ble.uuid import StandardUUID + + +class MultiService(Service): + uuid = StandardUUID(0x180F) + char_a = Characteristic( + uuid=StandardUUID(0x2A19), + properties=Characteristic.READ, + read_perm=Attribute.OPEN, + write_perm=Attribute.NO_ACCESS, + max_length=1, + fixed_length=True, + initial_value=bytes([10]), + ) + char_b = Characteristic( + uuid=StandardUUID(0x2A1A), + properties=Characteristic.READ | Characteristic.WRITE_NO_RESPONSE, + read_perm=Attribute.OPEN, + write_perm=Attribute.OPEN, + max_length=1, + fixed_length=True, + initial_value=bytes([20]), + ) + char_c = Characteristic( + uuid=StandardUUID(0x2A1B), + properties=Characteristic.READ, + read_perm=Attribute.OPEN, + write_perm=Attribute.NO_ACCESS, + max_length=1, + fixed_length=True, + initial_value=bytes([30]), + )""" + + +BSIM_MULTI_CHAR_SERVER_CODE = """\ +import time +from adafruit_ble import BLERadio +from adafruit_ble.advertising.standard import ProvideServicesAdvertisement +from multi_service import MultiService + +ble = BLERadio() +svc = MultiService() +# Force binding +svc.char_a +svc.char_b +svc.char_c +print("service created") + +advertisement = ProvideServicesAdvertisement(svc) +ble.start_advertising(advertisement) + +for _ in range(80): + if ble.connected: + break + time.sleep(0.1) +print("connected", ble.connected) + +for _ in range(80): + if not ble.connected: + break + time.sleep(0.1) + +print("char_b final", list(svc.char_b)) +print("done") +""" + +BSIM_WRITE_NR_CLIENT_CODE = """\ +import time +from adafruit_ble import BLERadio +from adafruit_ble.advertising.standard import ProvideServicesAdvertisement +from multi_service import MultiService + +ble = BLERadio() + +target = None +for adv in ble.start_scan(ProvideServicesAdvertisement, timeout=6.0): + if adv.connectable: + target = adv + break +ble.stop_scan() + +if target is None: + raise RuntimeError("No server found") + +connection = ble.connect(target, timeout=5.0) + +svc = connection[MultiService] + +print("initial", list(svc.char_b)) + +# Write-no-response +svc.char_b = bytes([99]) +print("wrote wnr") + +# Give the server time to process the write +time.sleep(0.5) + +connection.disconnect() + +timeout = time.monotonic() + 4.0 +while connection.connected and time.monotonic() < timeout: + time.sleep(0.1) +print("done") +""" + + +@pytest.mark.duration(25) +@pytest.mark.circuitpy_drive( + {"code.py": BSIM_MULTI_CHAR_SERVER_CODE, "multi_service.py": MULTI_LIB, **_ADAFRUIT_BLE} +) +@pytest.mark.circuitpy_drive( + {"code.py": BSIM_WRITE_NR_CLIENT_CODE, "multi_service.py": MULTI_LIB, **_ADAFRUIT_BLE} +) +def test_bsim_service_write_no_response(bsim_phy, circuitpython1, circuitpython2): + """Client writes a characteristic using WRITE_NO_RESPONSE.""" + server = circuitpython1 + client = circuitpython2 + + client.wait_until_done() + server.wait_until_done() + + server_output = server.serial.all_output + client_output = client.serial.all_output + + assert "char_b final [99]" in server_output + assert "initial [20]" in client_output + assert "wrote wnr" in client_output + + +# =================================================================== +# Test 5: Multiple characteristics on one service +# =================================================================== + +BSIM_MULTI_CHAR_CLIENT_CODE = """\ +import time +from adafruit_ble import BLERadio +from adafruit_ble.advertising.standard import ProvideServicesAdvertisement +from multi_service import MultiService + +ble = BLERadio() + +target = None +for adv in ble.start_scan(ProvideServicesAdvertisement, timeout=6.0): + if adv.connectable: + target = adv + break +ble.stop_scan() + +if target is None: + raise RuntimeError("No server found") + +connection = ble.connect(target, timeout=5.0) + +svc = connection[MultiService] +print("num chars", 3) + +# Read each characteristic +print("char", hex(0x2A19), list(svc.char_a)) +print("char", hex(0x2A1A), list(svc.char_b)) +print("char", hex(0x2A1B), list(svc.char_c)) + +# Write to the second characteristic +svc.char_b = bytes([77]) +print("wrote 0x2a1a") + +time.sleep(0.5) + +connection.disconnect() + +timeout = time.monotonic() + 4.0 +while connection.connected and time.monotonic() < timeout: + time.sleep(0.1) +print("done") +""" + + +@pytest.mark.duration(25) +@pytest.mark.circuitpy_drive( + {"code.py": BSIM_MULTI_CHAR_SERVER_CODE, "multi_service.py": MULTI_LIB, **_ADAFRUIT_BLE} +) +@pytest.mark.circuitpy_drive( + {"code.py": BSIM_MULTI_CHAR_CLIENT_CODE, "multi_service.py": MULTI_LIB, **_ADAFRUIT_BLE} +) +def test_bsim_service_multi_char(bsim_phy, circuitpython1, circuitpython2): + """Service with three characteristics: discover all, read each, write one.""" + server = circuitpython1 + client = circuitpython2 + + client.wait_until_done() + server.wait_until_done() + + server_output = server.serial.all_output + client_output = client.serial.all_output + + assert "num chars 3" in client_output + assert "char 0x2a19 [10]" in client_output + assert "char 0x2a1a [20]" in client_output + assert "char 0x2a1b [30]" in client_output + assert "wrote 0x2a1a" in client_output + assert "char_b final [77]" in server_output + + +# =================================================================== +# Test 6: 128-bit custom UUID +# =================================================================== + +CUSTOM_LIB = """ +from adafruit_ble.services import Service +from adafruit_ble.characteristics import Characteristic, Attribute +from adafruit_ble.uuid import VendorUUID + + +class CustomService(Service): + uuid = VendorUUID("12345678-1234-5678-1234-56789abcdef0") + data = Characteristic( + uuid=VendorUUID("12345678-1234-5678-1234-56789abcdef1"), + properties=Characteristic.READ | Characteristic.WRITE, + read_perm=Attribute.OPEN, + write_perm=Attribute.OPEN, + max_length=4, + fixed_length=False, + initial_value=bytes([0xDE, 0xAD]), + )""" + +BSIM_CUSTOM_UUID_SERVER_CODE = """\ +import time +from adafruit_ble import BLERadio +from adafruit_ble.advertising.standard import ProvideServicesAdvertisement +from custom_service import CustomService + +ble = BLERadio() +svc = CustomService() +print("service created") + +advertisement = ProvideServicesAdvertisement(svc) +ble.start_advertising(advertisement) + +for _ in range(80): + if ble.connected: + break + time.sleep(0.1) +print("connected", ble.connected) + +for _ in range(80): + if not ble.connected: + break + time.sleep(0.1) + +print("final value", list(svc.data)) +print("done") +""" + +BSIM_CUSTOM_UUID_CLIENT_CODE = """\ +import time +from adafruit_ble import BLERadio +from adafruit_ble.advertising.standard import ProvideServicesAdvertisement +from custom_service import CustomService + +ble = BLERadio() + +target = None +for adv in ble.start_scan(ProvideServicesAdvertisement, timeout=6.0): + if adv.connectable: + target = adv + break +ble.stop_scan() + +if target is None: + raise RuntimeError("No server found") + +connection = ble.connect(target, timeout=5.0) + +svc = connection[CustomService] +print("discovered services", 1) + +print("char value", list(svc.data)) + +svc.data = bytes([0xBE, 0xEF]) +print("wrote custom") + +time.sleep(0.5) + +connection.disconnect() + +timeout = time.monotonic() + 4.0 +while connection.connected and time.monotonic() < timeout: + time.sleep(0.1) +print("done") +""" + + +@pytest.mark.duration(25) +@pytest.mark.circuitpy_drive( + {"code.py": BSIM_CUSTOM_UUID_SERVER_CODE, "custom_service.py": CUSTOM_LIB, **_ADAFRUIT_BLE} +) +@pytest.mark.circuitpy_drive( + {"code.py": BSIM_CUSTOM_UUID_CLIENT_CODE, "custom_service.py": CUSTOM_LIB, **_ADAFRUIT_BLE} +) +def test_bsim_service_custom_uuid(bsim_phy, circuitpython1, circuitpython2): + """128-bit custom UUID service: discover, read, and write.""" + server = circuitpython1 + client = circuitpython2 + + client.wait_until_done() + server.wait_until_done() + + server_output = server.serial.all_output + client_output = client.serial.all_output + + assert "discovered services 1" in client_output + assert "char value [222, 173]" in client_output # 0xDE, 0xAD + assert "wrote custom" in client_output + assert "final value [190, 239]" in server_output # 0xBE, 0xEF + + +# =================================================================== +# Test 7: Empty discovery result +# =================================================================== + +BSIM_EMPTY_DISC_CLIENT_CODE = """\ +import time +from adafruit_ble import BLERadio +from adafruit_ble.advertising.standard import ProvideServicesAdvertisement +from heart_rate import HeartRateService + +ble = BLERadio() + +target = None +for adv in ble.start_scan(ProvideServicesAdvertisement, timeout=6.0): + if adv.connectable: + target = adv + print("found server") + break +ble.stop_scan() +print("have target", target is not None) + +if target is None: + raise RuntimeError("No server found") + +connection = ble.connect(target, timeout=5.0) +print("connected", connection.connected) + +# Ask for Heart Rate Service which doesn't exist on this server +found = HeartRateService in connection +print("found services", 1 if found else 0) + +connection.disconnect() + +timeout = time.monotonic() + 4.0 +while connection.connected and time.monotonic() < timeout: + time.sleep(0.1) +print("done") +""" + + +@pytest.mark.duration(30) +@pytest.mark.circuitpy_drive( + {"code.py": BSIM_CUSTOM_UUID_SERVER_CODE, "custom_service.py": CUSTOM_LIB, **_ADAFRUIT_BLE} +) +@pytest.mark.circuitpy_drive( + {"code.py": BSIM_EMPTY_DISC_CLIENT_CODE, "heart_rate.py": HEART_RATE_LIB, **_ADAFRUIT_BLE} +) +def test_bsim_service_empty_discovery(bsim_phy, circuitpython1, circuitpython2): + """Filter for a UUID that doesn't exist, verify empty tuple returned.""" + server = circuitpython1 + client = circuitpython2 + + client.wait_until_done() + server.wait_until_done() + + client_output = client.serial.all_output + + assert "found services 0" in client_output + assert "done" in client_output diff --git a/ports/zephyr-cp/tests/bsim/test_bsim_ble_uuid.py b/ports/zephyr-cp/tests/bsim/test_bsim_ble_uuid.py new file mode 100644 index 00000000000..9dcf3b13847 --- /dev/null +++ b/ports/zephyr-cp/tests/bsim/test_bsim_ble_uuid.py @@ -0,0 +1,331 @@ +# SPDX-FileCopyrightText: 2026 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""BLE UUID tests for bsim.""" + +import pytest + + +# --- 16-bit UUIDs --- + +BSIM_UUID_16BIT_CODE = """\ +import _bleio + +u16 = _bleio.UUID(0x180F) +print("uuid16", u16.uuid16) +print("size", u16.size) +print("str", str(u16)) +print("repr", repr(u16)) +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": BSIM_UUID_16BIT_CODE}) +def test_bsim_uuid_16bit_basic(bsim_phy, circuitpython): + """Construct a 16-bit UUID and verify all properties.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "uuid16 6159" in output # 0x180F = 6159 + assert "size 16" in output + assert "UUID(0x180f)" in output + assert "done" in output + + +BSIM_UUID_16BIT_EQ_CODE = """\ +import _bleio + +a = _bleio.UUID(0x180F) +b = _bleio.UUID(0x180F) +c = _bleio.UUID(0x180D) + +print("eq_same", a == b) +print("eq_diff", a == c) +print("neq_diff", a != c) +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": BSIM_UUID_16BIT_EQ_CODE}) +def test_bsim_uuid_16bit_equality(bsim_phy, circuitpython): + """16-bit UUID equality: same value is equal, different values are not.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "eq_same True" in output + assert "eq_diff False" in output + assert "neq_diff True" in output + assert "done" in output + + +BSIM_UUID_16BIT_HASH_CODE = """\ +import _bleio + +a = _bleio.UUID(0x180F) +b = _bleio.UUID(0x180F) + +# Same UUID should hash the same +print("hash_same", hash(a) == hash(b)) + +# Can be used as dict keys +d = {a: "battery"} +print("dict_lookup", d[_bleio.UUID(0x180F)]) +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": BSIM_UUID_16BIT_HASH_CODE}) +def test_bsim_uuid_16bit_hash(bsim_phy, circuitpython): + """16-bit UUID can be hashed and used as dict keys.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "hash_same True" in output + assert "dict_lookup battery" in output + assert "done" in output + + +BSIM_UUID_16BIT_PACK_CODE = """\ +import _bleio + +u16 = _bleio.UUID(0x180F) +buf = bytearray(4) +u16.pack_into(buf) +print("packed", list(buf[:2])) +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": BSIM_UUID_16BIT_PACK_CODE}) +def test_bsim_uuid_16bit_pack_into(bsim_phy, circuitpython): + """pack_into for 16-bit UUID writes 2 bytes in little-endian.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + # 0x180F in little-endian: byte[0]=0x0F, byte[1]=0x18 + assert "packed [15, 24]" in output # 0x0F=15, 0x18=24 + assert "done" in output + + +BSIM_UUID_16BIT_PACK_OFFSET_CODE = """\ +import _bleio + +u16 = _bleio.UUID(0x2A19) +buf = bytearray(6) +u16.pack_into(buf, offset=4) +print("packed", list(buf)) +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": BSIM_UUID_16BIT_PACK_OFFSET_CODE}) +def test_bsim_uuid_16bit_pack_into_offset(bsim_phy, circuitpython): + """pack_into with offset writes at the correct position.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + # 0x2A19 = 10777, little-endian: [0x19, 0x2A] = [25, 42] + assert "packed [0, 0, 0, 0, 25, 42]" in output + assert "done" in output + + +# --- 128-bit UUID string parsing --- + +BSIM_UUID_128BIT_STR_CODE = """\ +import _bleio + +u128 = _bleio.UUID("12345678-1234-5678-1234-56789abcdef0") +print("uuid16", u128.uuid16) +print("size", u128.size) +print("uuid128_len", len(u128.uuid128)) +# Bytes 12-13 are zeroed by shared-bindings (extracted as uuid16) +# First 4 bytes of uuid128 are [f0, de, bc, 9a] in LE +print("bytes_0_3", list(u128.uuid128[:4])) +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": BSIM_UUID_128BIT_STR_CODE}) +def test_bsim_uuid_128bit_string(bsim_phy, circuitpython): + """Construct a 128-bit UUID from a hex string.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "size 128" in output + # uuid16 extracted from bytes 12-13: 0x5678 = 22136 + assert "uuid16 22136" in output + assert "uuid128_len 16" in output + # Bytes 12-13 are restored from uuid16 by common_hal_bleio_uuid_construct + # First 4 bytes of uuid128 are [f0, de, bc, 9a] in LE + assert "bytes_0_3 [240, 222, 188, 154]" in output + assert "done" in output + + +# --- 128-bit UUID bytes construction --- + +BSIM_UUID_128BIT_BYTES_CODE = """\ +import _bleio + +raw = bytes([0xf0, 0xde, 0xbc, 0x9a, 0x78, 0x56, 0x34, 0x12, + 0x34, 0x12, 0x78, 0x56, 0x34, 0x12, 0x78, 0x56]) +u128 = _bleio.UUID(raw) +print("size", u128.size) +# uuid16 extracted from raw[12:14] = [0x34, 0x12] → 0x1234 = 4660 +print("uuid16", u128.uuid16) +print("uuid128_len", len(u128.uuid128)) +# Bytes 12-13 are restored from uuid16 by common_hal_bleio_uuid_construct +print("bytes_12_13", list(u128.uuid128[12:14])) +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": BSIM_UUID_128BIT_BYTES_CODE}) +def test_bsim_uuid_128bit_bytes(bsim_phy, circuitpython): + """Construct a 128-bit UUID from a 16-byte buffer.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "size 128" in output + assert "uuid16 4660" in output + assert "uuid128_len 16" in output + # Bytes 12-13 restored from uuid16: 0x1234 → [0x34, 0x12] = [52, 18] + assert "bytes_12_13 [52, 18]" in output + assert "done" in output + + +# --- 128-bit UUID equality --- + +BSIM_UUID_128BIT_EQ_CODE = """\ +import _bleio + +a = _bleio.UUID("12345678-1234-5678-1234-56789abcdef0") +b = _bleio.UUID("12345678-1234-5678-1234-56789abcdef0") +c = _bleio.UUID("00000000-0000-1000-8000-00805f9b34fb") + +print("eq_same", a == b) +print("eq_diff", a == c) +print("neq_diff", a != c) +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": BSIM_UUID_128BIT_EQ_CODE}) +def test_bsim_uuid_128bit_equality(bsim_phy, circuitpython): + """128-bit UUID equality: same bytes equal, different not.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "eq_same True" in output + assert "eq_diff False" in output + assert "neq_diff True" in output + assert "done" in output + + +# --- 16-bit vs 128-bit UUID equality (should not be equal even if same value) --- + +BSIM_UUID_CROSS_SIZE_EQ_CODE = """\ +import _bleio + +# 0x180F as 16-bit +u16 = _bleio.UUID(0x180F) + +# 0x180F expanded to 128-bit base UUID +# Bluetooth base: 00000000-0000-1000-8000-00805F9B34FB +# With 0x180F: 0000180F-0000-1000-8000-00805F9B34FB +u128 = _bleio.UUID("0000180f-0000-1000-8000-00805f9b34fb") + +print("size_16", u16.size) +print("size_128", u128.size) +# Per spec, 16-bit and 128-bit are NOT equal even if values match +print("cross_eq", u16 == u128) +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": BSIM_UUID_CROSS_SIZE_EQ_CODE}) +def test_bsim_uuid_cross_size_equality(bsim_phy, circuitpython): + """16-bit and 128-bit UUIDs are not equal even with same value.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "size_16 16" in output + assert "size_128 128" in output + assert "cross_eq False" in output + assert "done" in output + + +# --- Invalid UUID string --- + +BSIM_UUID_INVALID_STR_CODE = """\ +import _bleio + +try: + u = _bleio.UUID("not-a-uuid") + print("should not reach") +except ValueError as e: + print("value_error", "not" in str(e) or "UUID" in str(e)) +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": BSIM_UUID_INVALID_STR_CODE}) +def test_bsim_uuid_invalid_string(bsim_phy, circuitpython): + """Invalid UUID string raises ValueError.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "value_error True" in output + assert "done" in output + + +# --- UUID 128-bit: uuid128 property works, uuid16 returns 16-bit part --- + +BSIM_UUID_128BIT_PROPS_CODE = """\ +import _bleio + +u128 = _bleio.UUID("12345678-1234-5678-1234-56789abcdef0") +print("size", u128.size) +# uuid128 returns 16 bytes (bytes 12-13 are restored from uuid16) +b = u128.uuid128 +print("uuid128_len", len(b)) +# uuid16 is the 16-bit part from bytes 12-13, extracted and then restored +print("uuid16", u128.uuid16) +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": BSIM_UUID_128BIT_PROPS_CODE}) +def test_bsim_uuid_128bit_properties(bsim_phy, circuitpython): + """128-bit UUID exposes uuid128 bytes and uuid16 from bytes 12-13.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "size 128" in output + assert "uuid128_len 16" in output + assert "uuid16 22136" in output + assert "done" in output + + +# --- 16-bit uuid128 raises AttributeError --- + +BSIM_UUID_16BIT_NO_UUID128_CODE = """\ +import _bleio + +u16 = _bleio.UUID(0x180F) +try: + _ = u16.uuid128 + print("should not reach") +except AttributeError: + print("attr_error ok") +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": BSIM_UUID_16BIT_NO_UUID128_CODE}) +def test_bsim_uuid_16bit_no_uuid128(bsim_phy, circuitpython): + """Accessing uuid128 on a 16-bit UUID raises AttributeError.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "attr_error ok" in output + assert "done" in output diff --git a/ports/zephyr-cp/tests/bsim/test_bsim_ble_workflow_advertising.py b/ports/zephyr-cp/tests/bsim/test_bsim_ble_workflow_advertising.py new file mode 100644 index 00000000000..a6e9bc6e0dd --- /dev/null +++ b/ports/zephyr-cp/tests/bsim/test_bsim_ble_workflow_advertising.py @@ -0,0 +1,112 @@ +# SPDX-FileCopyrightText: 2026 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""Advertising test for the supervisor BLE workflow (bsim). + +The supervisor's built-in BLE workflow (file-transfer + serial services and +advertising) starts automatically at boot, independent of user code. One +CircuitPython device runs an idle code.py so its workflow advertises; a second +CircuitPython device scans with the adafruit_ble library and verifies the +workflow's advertisement carries the File Transfer service UUID (0xFEBB) and +the CIRCUITPY device name. + +The second device disables its own workflow via settings.toml so only the +first device advertises. +""" + +import logging +import re + +import pytest + +from .conftest import get_library_files + +logger = logging.getLogger(__name__) + +_ADAFRUIT_BLE = get_library_files("adafruit_ble") + +# Device 1: idle code.py. The supervisor workflow advertises during the sleep. +WORKFLOW_IDLE_CODE = """\ +import time +time.sleep(15) +""" + +# Device 2: scan for the workflow advertisement. The workflow puts the +# File Transfer service UUID (0xFEBB) in the primary advertisement and the full +# "CIRCUITPYxxxx" name in the scan response, so those arrive as separate +# Advertisement objects (service list vs. scan response). +SCANNER_CODE = """\ +import time +from adafruit_ble import BLERadio +from adafruit_ble.advertising import Advertisement +from adafruit_ble.advertising.standard import ProvideServicesAdvertisement +from adafruit_ble.uuid import StandardUUID + +ble = BLERadio() +print("scan start") +found_ft = False +found_name = False +ft_rssi = None +for adv in ble.start_scan(ProvideServicesAdvertisement, Advertisement, timeout=15, active=True): + if isinstance(adv, ProvideServicesAdvertisement) and StandardUUID(0xFEBB) in adv.services: + found_ft = True + ft_rssi = adv.rssi + print("ft_uuid febb") + name = adv.complete_name or adv.short_name or "" + if name: + found_name = True + print("cp_name", name) + if found_ft and found_name: + print("workflow found") + print("ft_rssi", ft_rssi) + break +ble.stop_scan() +print("scan done", found_ft, found_name, ft_rssi) +""" + +# Disable the workflow on the scanner so it doesn't advertise alongside device 1. +SCANNER_SETTINGS = "CIRCUITPY_BLE_WORKFLOW = false\n" + + +@pytest.mark.duration(20) +@pytest.mark.circuitpy_drive({"code.py": WORKFLOW_IDLE_CODE}) +@pytest.mark.circuitpy_drive( + { + "code.py": SCANNER_CODE, + "settings.toml": SCANNER_SETTINGS, + **_ADAFRUIT_BLE, + } +) +def test_bsim_workflow_advertises(bsim_phy, circuitpython1, circuitpython2): + """The supervisor BLE workflow advertises 0xFEBB and the CIRCUITPY name.""" + workflow = circuitpython1 + scanner = circuitpython2 + + scanner.wait_until_done() + + scanner_output = scanner.serial.all_output + assert "ft_uuid febb" in scanner_output, ( + f"File Transfer service UUID 0xFEBB not observed: {scanner_output}" + ) + # The device name currently advertises as the controller default ("Zephyr"); + # the CIRCUITPY name is configured separately, at which point this will + # observe the full "CIRCUITPY..." name. Either way a name must be present. + assert "cp_name" in scanner_output, f"device name not observed: {scanner_output}" + assert "workflow found" in scanner_output, ( + f"workflow advertisement not fully observed: {scanner_output}" + ) + + # The workflow advertises its public advert at reduced TX power (-20 dBm), + # so with the 40 dB channel attenuation the RSSI is ~ -59, well below the + # 0 dBm baseline of -39 seen for user advertisements. + rssi_match = re.search(r"ft_rssi (-?\d+)", scanner_output) + assert rssi_match, f"ft_rssi not observed: {scanner_output}" + ft_rssi = int(rssi_match.group(1)) + logger.info("workflow ft_rssi: %d", ft_rssi) + assert ft_rssi < -39, f"Expected reduced-TX-power RSSI (< -39), got {ft_rssi}" + + # The workflow device should not have entered safe mode. + workflow_output = workflow.serial.all_output + assert "safe mode" not in workflow_output.lower(), ( + f"workflow device entered safe mode: {workflow_output}" + ) diff --git a/ports/zephyr-cp/tests/bsim/test_bsim_ble_workflow_file_transfer.py b/ports/zephyr-cp/tests/bsim/test_bsim_ble_workflow_file_transfer.py new file mode 100644 index 00000000000..a7c383febe1 --- /dev/null +++ b/ports/zephyr-cp/tests/bsim/test_bsim_ble_workflow_file_transfer.py @@ -0,0 +1,102 @@ +# SPDX-FileCopyrightText: 2026 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""File Transfer service test for the supervisor BLE workflow (bsim). + +A second CircuitPython device connects to the supervisor's BLE workflow +(advertised with the File Transfer service UUID 0xFEBB), pairs, and uses the +Adafruit_CircuitPython_BLE_File_Transfer library to list the workflow device's +root directory. +""" + +import pytest + +from .conftest import get_library_files + +_ADAFRUIT_BLE = get_library_files("adafruit_ble") +_ADAFRUIT_BLE_FILE_TRANSFER = get_library_files("adafruit_ble_file_transfer") + +# Device 1: idle code.py; its workflow exposes the File Transfer service. +WORKFLOW_IDLE_CODE = """\ +import time +time.sleep(25) +""" + +# Device 2: connect, pair, and listdir("/") over the File Transfer service. +CLIENT_CODE = """\ +import time +from adafruit_ble import BLERadio +from adafruit_ble.advertising.standard import ProvideServicesAdvertisement +from adafruit_ble.uuid import StandardUUID +from adafruit_ble_file_transfer import FileTransferService, FileTransferClient + +ble = BLERadio() + +# Wait for the workflow device's file transfer server to finish starting up +# before scanning. +time.sleep(5) +print("scan start") +target = None +for adv in ble.start_scan(ProvideServicesAdvertisement, timeout=15, active=True): + if StandardUUID(0xFEBB) in adv.services: + target = adv + print("found workflow") + break +ble.stop_scan() +if target is None: + print("no workflow") + raise SystemExit(1) + +connection = ble.connect(target, timeout=10) +print("connected", connection.connected) +connection.pair() +print("paired", connection.paired) + +service = connection[FileTransferService] +print("ft version", service.version) +client = FileTransferClient(service) + +entries = client.listdir("/") +names = [e[0] for e in entries] +print("ft names", names) +if "code.py" in names: + print("ft code.py listed") +print("ft done") +connection.disconnect() +""" + +CLIENT_SETTINGS = "CIRCUITPY_BLE_WORKFLOW = false\n" + + +@pytest.mark.duration(30) +@pytest.mark.circuitpy_drive({"code.py": WORKFLOW_IDLE_CODE}) +@pytest.mark.circuitpy_drive( + { + "code.py": CLIENT_CODE, + "settings.toml": CLIENT_SETTINGS, + **_ADAFRUIT_BLE_FILE_TRANSFER, + **_ADAFRUIT_BLE, + } +) +def test_bsim_workflow_file_transfer(board, bsim_phy, circuitpython1, circuitpython2): + """The supervisor BLE workflow's File Transfer service can list files.""" + workflow = circuitpython1 + client = circuitpython2 + + client.wait_until_done() + + client_output = client.serial.all_output + assert "found workflow" in client_output, f"client never found the workflow: {client_output}" + assert "paired True" in client_output, f"pairing did not succeed: {client_output}" + assert "ft version 4" in client_output, ( + f"File Transfer version characteristic is not 4: {client_output}" + ) + assert "ft code.py listed" in client_output, ( + f"listdir did not include code.py: {client_output}" + ) + assert "ft done" in client_output, f"file transfer did not complete: {client_output}" + + workflow_output = workflow.serial.all_output + assert "safe mode" not in workflow_output.lower(), ( + f"workflow device entered safe mode: {workflow_output}" + ) diff --git a/ports/zephyr-cp/tests/bsim/test_bsim_ble_workflow_nus.py b/ports/zephyr-cp/tests/bsim/test_bsim_ble_workflow_nus.py new file mode 100644 index 00000000000..ebc0bbcc69c --- /dev/null +++ b/ports/zephyr-cp/tests/bsim/test_bsim_ble_workflow_nus.py @@ -0,0 +1,146 @@ +# SPDX-FileCopyrightText: 2026 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""Serial (Nordic-UART-style) service test for the supervisor BLE workflow +(bsim). + +The supervisor's BLE workflow exposes a CircuitPython serial service whose RX +characteristic accepts console stdin (write, encrypted) and whose TX +characteristic emits console stdout via notifications (encrypted). One +CircuitPython device runs code.py that reads a line with `input()` and echoes +it back with `print()`; a second CircuitPython device connects, pairs, +subscribes to TX, writes a line to RX, and verifies the echo comes back over TX. +""" + +import pytest + +from .conftest import get_library_files + +_ADAFRUIT_BLE = get_library_files("adafruit_ble") + +# Device 1: read a line from console stdin (BLE RX) and echo it to console +# stdout (mirrored to BLE TX). `input()` blocks until the central writes, so the +# device stays alive for the exchange. +WORKFLOW_CODE = """\ +import time +print("nus ready") +try: + line = input() +except EOFError: + line = "" +print("nus_echo:" + line) +# Keep the VM alive briefly so the BLE TX notification carrying the echo is +# actually transmitted over the link before the device exits. Without this the +# notification is queued but never sent because the process shuts down right +# after code.py finishes. +time.sleep(3) +""" + +# Device 2: connect, pair, discover the CircuitPython serial service, subscribe +# to TX, write a line to RX, and read the echo back over TX. +CLIENT_CODE = """\ +import time +import _bleio +from adafruit_ble import BLERadio +from adafruit_ble.advertising.standard import ProvideServicesAdvertisement +from adafruit_ble.uuid import StandardUUID + +ble = BLERadio() + +# Wait for the workflow device's serial service to finish starting up +# before scanning. Connecting too soon after the workflow's BLE init races +# with a Zephyr connection-parameter update and the link drops shortly +# after pairing. +time.sleep(5) +print("scan start") +target = None +for adv in ble.start_scan(ProvideServicesAdvertisement, timeout=15, active=True): + if StandardUUID(0xFEBB) in adv.services: + target = adv + print("found workflow") + break +ble.stop_scan() +if target is None: + print("no workflow") + raise SystemExit(1) + +connection = ble.connect(target, timeout=10) +print("connected", connection.connected) +connection.pair() +print("paired", connection.paired) + +# CircuitPython serial service UUID (128-bit, "nhtyPtiucriC" base + 0x0001). +serial_uuid = _bleio.UUID(b"nhtyPtiucriC\\x01\\x00\\xaf\\xad") +services = connection._bleio_connection.discover_remote_services([serial_uuid]) +svc = services[0] +print("serial service", svc.uuid.uuid16) + +rx_char = None +tx_char = None +for ch in svc.characteristics: + if ch.uuid.uuid16 == 0x0002: + rx_char = ch + elif ch.uuid.uuid16 == 0x0003: + tx_char = ch +print("rx", rx_char is not None, "tx", tx_char is not None) + +# Subscribe to TX notifications (client-side PacketBuffer writes the CCCD). +tx_pb = _bleio.PacketBuffer(tx_char, buffer_size=4, max_packet_size=128) + +# Write a line to RX (console stdin). RX has WRITE_NO_RESPONSE, so `.value =` +# does a GATT write without response. +rx_char.value = b"ZZZ\\r" +print("rx written") + +buf = bytearray(128) +got = b"" +deadline = time.monotonic() + 10 +while time.monotonic() < deadline: + n = tx_pb.readinto(buf) + if n: + got += bytes(buf[:n]) + if b"nus_echo:ZZZ" in got: + print("nus_received nus_echo:ZZZ") + break +print("nus done", b"nus_echo:ZZZ" in got) +connection.disconnect() +""" + +CLIENT_SETTINGS = "CIRCUITPY_BLE_WORKFLOW = false\n" + + +@pytest.mark.duration(30) +@pytest.mark.circuitpy_drive({"code.py": WORKFLOW_CODE}) +@pytest.mark.circuitpy_drive( + { + "code.py": CLIENT_CODE, + "settings.toml": CLIENT_SETTINGS, + **_ADAFRUIT_BLE, + } +) +def test_bsim_workflow_nus(board, bsim_phy, circuitpython1, circuitpython2): + """The supervisor BLE workflow's serial service echoes console I/O over BLE.""" + workflow = circuitpython1 + client = circuitpython2 + + client.wait_until_done() + + client_output = client.serial.all_output + assert "found workflow" in client_output, f"client never found the workflow: {client_output}" + assert "paired True" in client_output, f"pairing did not succeed: {client_output}" + assert "serial service 1" in client_output, ( + f"CircuitPython serial service not discovered: {client_output}" + ) + assert "rx True tx True" in client_output, ( + f"RX/TX characteristics not discovered: {client_output}" + ) + assert "rx written" in client_output, f"RX write failed: {client_output}" + assert "nus_received nus_echo:ZZZ" in client_output, ( + f"echo 'nus_echo:ZZZ' never received over TX: {client_output}" + ) + assert "nus done True" in client_output, f"echo not confirmed: {client_output}" + + workflow_output = workflow.serial.all_output + assert "safe mode" not in workflow_output.lower(), ( + f"workflow device entered safe mode: {workflow_output}" + ) diff --git a/ports/zephyr-cp/tests/bsim/test_bsim_ble_workflow_reload.py b/ports/zephyr-cp/tests/bsim/test_bsim_ble_workflow_reload.py new file mode 100644 index 00000000000..cc56b1108e3 --- /dev/null +++ b/ports/zephyr-cp/tests/bsim/test_bsim_ble_workflow_reload.py @@ -0,0 +1,190 @@ +# SPDX-FileCopyrightText: 2026 Dan Halbert for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""The supervisor BLE workflow connection survives a VM reload (bsim). + +A second CircuitPython device connects to the workflow, pairs, and lists the +root directory. The test then interrupts the workflow device's code.py and +reloads it with Ctrl-D, the same path as typing at the "Press any key" prompt +or saving a file from the web editor. The connection must stay up and file +transfer must still work afterwards. + +In the variant where code.py created a `_bleio.Service`, that service must be +gone from the GATT table after the reload, while the workflow connection still +survives: Zephyr can unregister services individually, so no stack restart is +needed. +""" + +import pytest + +from .conftest import get_library_files + +_ADAFRUIT_BLE = get_library_files("adafruit_ble") +_ADAFRUIT_BLE_FILE_TRANSFER = get_library_files("adafruit_ble_file_transfer") + +# Device 1, plain: idle code.py until the test interrupts it. +WORKFLOW_IDLE_CODE = """\ +import supervisor +import time +print("run", supervisor.runtime.run_reason) +print("workflow ready") +# Idle in short sleeps: on zephyr-cp a Ctrl-C from the UART console is only +# noticed when the current time.sleep() ends, so keep each one brief. +while True: + time.sleep(0.5) +""" + +# Device 1, with a user service: create a Battery Service only on the first +# run, so that after the reload it must have been removed by the supervisor, +# not recreated by code.py. +WORKFLOW_SERVICE_CODE = """\ +import supervisor +import time +import _bleio +print("run", supervisor.runtime.run_reason) +if supervisor.runtime.run_reason == supervisor.RunReason.STARTUP: + service = _bleio.Service(_bleio.UUID(0x180F)) + _bleio.Characteristic.add_to_service( + service, _bleio.UUID(0x2A19), + properties=_bleio.Characteristic.READ, + read_perm=_bleio.Attribute.OPEN, + write_perm=_bleio.Attribute.NO_ACCESS, + max_length=1, fixed_length=True, initial_value=b"\\x64", + ) + print("user service created") +print("workflow ready") +# Idle in short sleeps: on zephyr-cp a Ctrl-C from the UART console is only +# noticed when the current time.sleep() ends, so keep each one brief. +while True: + time.sleep(0.5) +""" + +# Device 2: connect, pair, list files, report whether the Battery Service is +# present, then wait through the reload and do it all again on the same +# connection. +CLIENT_CODE = """\ +import time +import _bleio +from adafruit_ble import BLERadio +from adafruit_ble.advertising.standard import ProvideServicesAdvertisement +from adafruit_ble.uuid import StandardUUID +from adafruit_ble_file_transfer import FileTransferService, FileTransferClient + +BATTERY = _bleio.UUID(0x180F) + +ble = BLERadio() + +# Wait for the workflow device's file transfer server to finish starting up +# before scanning. +time.sleep(5) +print("scan start") +target = None +for adv in ble.start_scan(ProvideServicesAdvertisement, timeout=15, active=True): + if StandardUUID(0xFEBB) in adv.services: + target = adv + print("found workflow") + break +ble.stop_scan() +if target is None: + print("no workflow") + raise SystemExit(1) + +connection = ble.connect(target, timeout=10) +print("connected", connection.connected) +connection.pair() +print("paired", connection.paired) + +def battery_present(): + services = connection._bleio_connection.discover_remote_services() + return any(s.uuid == BATTERY for s in services) + +def list_root(tag): + service = connection[FileTransferService] + client = FileTransferClient(service) + names = [e[0] for e in client.listdir("/")] + print("ft names", tag, names) + print("ft code.py listed", tag, "code.py" in names) + +print("battery before", battery_present()) +list_root("before") +print("client ready for reload") + +# The test reloads the workflow device now. Give it time to come back. +time.sleep(20) +print("still connected", connection.connected) +list_root("after") +print("battery after", battery_present()) +print("client done") +connection.disconnect() +""" + +CLIENT_SETTINGS = "CIRCUITPY_BLE_WORKFLOW = false\n" + +CLIENT_DRIVE = { + "code.py": CLIENT_CODE, + "settings.toml": CLIENT_SETTINGS, + **_ADAFRUIT_BLE_FILE_TRANSFER, + **_ADAFRUIT_BLE, +} + + +def _reload_workflow_and_check(workflow, client): + client.serial.wait_for("client ready for reload", timeout=90) + + # Interrupt code.py, then reload from the "Press any key" prompt. Before the + # fix, the first byte at that prompt restarted the BLE stack and dropped the + # workflow connection. + workflow.serial.write("\x03") + workflow.serial.wait_for("KeyboardInterrupt", timeout=30) + workflow.serial.write("\x04") + workflow.serial.wait_for("RunReason.REPL_RELOAD", timeout=30) + + client.serial.wait_for("client done", timeout=90) + + client_output = client.serial.all_output + assert "paired True" in client_output, f"pairing did not succeed: {client_output}" + assert "ft code.py listed before True" in client_output, ( + f"listdir before reload did not include code.py: {client_output}" + ) + assert "still connected True" in client_output, ( + f"workflow connection did not survive the reload: {client_output}" + ) + assert "ft code.py listed after True" in client_output, ( + f"listdir after reload did not include code.py: {client_output}" + ) + + workflow_output = workflow.serial.all_output + assert "safe mode" not in workflow_output.lower(), ( + f"workflow device entered safe mode: {workflow_output}" + ) + return client_output + + +@pytest.mark.port_resets(3) +@pytest.mark.duration(90) +@pytest.mark.circuitpy_drive({"code.py": WORKFLOW_IDLE_CODE}) +@pytest.mark.circuitpy_drive(CLIENT_DRIVE) +def test_bsim_workflow_reload_keeps_connection(board, bsim_phy, circuitpython1, circuitpython2): + """A Ctrl-D reload with no user services leaves the workflow connection up.""" + client_output = _reload_workflow_and_check(circuitpython1, circuitpython2) + assert "battery before False" in client_output + assert "battery after False" in client_output + + +@pytest.mark.port_resets(3) +@pytest.mark.duration(90) +@pytest.mark.circuitpy_drive({"code.py": WORKFLOW_SERVICE_CODE}) +@pytest.mark.circuitpy_drive(CLIENT_DRIVE) +def test_bsim_workflow_reload_removes_user_service( + board, bsim_phy, circuitpython1, circuitpython2 +): + """A reload removes a user-created service without dropping the connection.""" + workflow = circuitpython1 + client_output = _reload_workflow_and_check(workflow, circuitpython2) + assert "user service created" in workflow.serial.all_output + assert "battery before True" in client_output, ( + f"client did not see the user service before the reload: {client_output}" + ) + assert "battery after False" in client_output, ( + f"user service still present after the reload: {client_output}" + ) diff --git a/ports/zephyr-cp/tests/conftest.py b/ports/zephyr-cp/tests/conftest.py new file mode 100644 index 00000000000..8b71196226f --- /dev/null +++ b/ports/zephyr-cp/tests/conftest.py @@ -0,0 +1,562 @@ +# SPDX-FileCopyrightText: 2025 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""Pytest fixtures for CircuitPython native_sim testing.""" + +import logging +import os +import posixpath +import subprocess +from pathlib import Path + +import pytest +import serial + +from .perfetto_input_trace import write_input_trace + +from perfetto.trace_processor import TraceProcessor + +from . import NativeSimProcess + +logger = logging.getLogger(__name__) + + +def pytest_addoption(parser): + parser.addoption( + "--update-goldens", + action="store_true", + default=False, + help="Overwrite golden images with captured output instead of comparing.", + ) + + +def pytest_configure(config): + config.addinivalue_line( + "markers", "circuitpy_drive(files): run CircuitPython with files in the flash image" + ) + config.addinivalue_line( + "markers", "disable_i2c_devices(*names): disable native_sim I2C emulator devices" + ) + config.addinivalue_line( + "markers", "circuitpython_board(board_id): which board id to use in the test" + ) + config.addinivalue_line( + "markers", + "zephyr_sample(sample, board='nrf52_bsim', device_id=1): build and run a Zephyr sample for bsim tests", + ) + config.addinivalue_line( + "markers", + "duration(seconds): native_sim timeout and bsim PHY simulation duration", + ) + config.addinivalue_line( + "markers", + "port_resets(count): stop native_sim after count port_reset()s (default: 2)", + ) + config.addinivalue_line( + "markers", + "input_trace(trace): inject input signal trace data into native_sim", + ) + config.addinivalue_line( + "markers", + "native_sim_rt: run native_sim in realtime mode (-rt instead of -no-rt)", + ) + config.addinivalue_line( + "markers", + "display(capture_times_ns=None): run test with SDL display; " + "capture_times_ns is a list of nanosecond timestamps for trace-triggered captures", + ) + config.addinivalue_line( + "markers", + "display_pixel_format(format): override the display pixel format " + "(e.g. 'RGB_565', 'ARGB_8888')", + ) + config.addinivalue_line( + "markers", + "display_mono_vtiled(value): override the mono vtiled screen_info flag (True or False)", + ) + config.addinivalue_line( + "markers", + "flash_config(erase_block_size=N, total_size=N): override flash simulator parameters", + ) + config.addinivalue_line( + "markers", + "fat_filesystem_only: skip the test on littlefs filesystem boards", + ) + config.addinivalue_line( + "markers", + "native_sim_args(*args): extra command-line args passed to native_sim", + ) + + +ZEPHYR_CP = Path(__file__).parent.parent +BUILD_DIR = ZEPHYR_CP / "build-native_native_sim" +BINARY = BUILD_DIR / "zephyr-cp/zephyr/zephyr.exe" + +# Boards parameterized by the filesystem tests. native_native_sim mounts a +# FAT filesystem; native_native_sim_lfs mounts littlefs. +FILESYSTEM_SIMULATORS = ["native_native_sim", "native_native_sim_lfs"] + +# Boards whose flash image is a FAT drive that can be populated from the host +# with mtools. +FAT_FILESYSTEM_BOARDS = { + "native_native_sim", + "native_native_sim_lvgl", + "native_native_sim_lvgl_asan", + "native_native_sim_asan", + "native_nrf5340bsim", + "native_nrf54lm20bsim", +} + +# Boards whose flash image holds a littlefs filesystem. Their images are +# populated from the host with littlefs-python, using geometry that matches +# the board overlay and supervisor/shared/filesystem.c: FILESYSTEM_BLOCK_SIZE +# (512) byte blocks over the filesystem partition, with the partition's last +# erase page left out because the supervisor flash cache uses it as its +# scratch page (see supervisor_flash_get_block_count()). +DEFAULT_ERASE_PAGE_SIZE = 4096 +LITTLEFS_FILESYSTEM_BOARDS = { + "native_native_sim_lfs": { + "partition_size": 2032 * 1024, + "erase_page_size": DEFAULT_ERASE_PAGE_SIZE, + "block_size": 512, + }, +} + + +def _iter_uart_tx_slices(trace_file: Path) -> list[tuple[int, int, str, str]]: + """Return UART TX slices as (timestamp_ns, duration_ns, text, device_name).""" + tp = TraceProcessor(file_path=str(trace_file)) + result = tp.query( + """ + SELECT s.ts, s.dur, s.name, dev.name AS device_name + FROM slice s + JOIN track tx ON s.track_id = tx.id + JOIN track dev ON tx.parent_id = dev.id + JOIN track uart ON dev.parent_id = uart.id + WHERE tx.name = "TX" AND uart.name = "UART" + ORDER BY s.ts + """ + ) + return [ + (int(row.ts), int(row.dur or 0), row.name or "", row.device_name or "UART") + for row in result + ] + + +def log_uart_trace_output(trace_file: Path) -> None: + """Log UART TX output from Perfetto trace with timestamps for line starts.""" + if not logger.isEnabledFor(logging.INFO): + return + slices = _iter_uart_tx_slices(trace_file) + if not slices: + return + + buffers: dict[str, list[str]] = {} + line_start_ts: dict[str, int | None] = {} + + for ts, dur, text, device in slices: + if device not in buffers: + buffers[device] = [] + line_start_ts[device] = None + + if not text: + continue + + char_step = dur / max(len(text), 1) if dur > 0 else 0.0 + for idx, ch in enumerate(text): + if line_start_ts[device] is None: + line_start_ts[device] = int(ts + idx * char_step) + buffers[device].append(ch) + if ch == "\n": + line_text = "".join(buffers[device]).rstrip("\n") + logger.info( + "UART trace %s @%d ns: %s", + device, + line_start_ts[device], + repr(line_text), + ) + buffers[device] = [] + line_start_ts[device] = None + + for device, buf in buffers.items(): + if buf: + logger.info( + "UART trace %s @%d ns (partial): %s", + device, + line_start_ts[device] or 0, + repr("".join(buf)), + ) + + +# Native_sim boards each test runs against: the FAT legacy-compositor default, +# the LVGL-compositor build, the littlefs build, and ASan builds of both +# compositors, so compositor, filesystem and memory errors all fail tests. +NATIVE_BOARDS = [ + "native_native_sim", + "native_native_sim_lvgl", + "native_native_sim_lvgl_asan", + "native_native_sim_lfs", + "native_native_sim_asan", +] + + +@pytest.fixture(params=NATIVE_BOARDS) +def board(request): + board_marker = request.node.get_closest_marker("circuitpython_board") + if board_marker is not None: + return board_marker.args[0] + # Support indirect parametrization, e.g. + # @pytest.mark.parametrize("board", FILESYSTEM_SIMULATORS, indirect=True) + if hasattr(request, "param"): + return request.param + return "native_native_sim" + + +def _lfs_geometry(board, erase_page_size): + """Return (block_size, block_count) matching what CircuitPython mounts.""" + geometry = LITTLEFS_FILESYSTEM_BOARDS[board] + block_size = geometry["block_size"] + page_size = max(erase_page_size, block_size) + # The last whole erase page of the partition is the supervisor flash + # cache's scratch page, so littlefs only gets the blocks before it. + last_page_start = (geometry["partition_size"] // page_size - 1) * page_size + return block_size, last_page_start // block_size + + +def _populate_lfs_drive(flash, files, board, erase_page_size): + """Copy files onto a littlefs flash image with littlefs-python.""" + from littlefs import LittleFS + from littlefs.context import UserContextFile + + block_size, block_count = _lfs_geometry(board, erase_page_size) + # The fresh image is all erased bytes, so the initial mount fails and + # LittleFS formats it. This matches what CircuitPython does on a blank + # flash, minus the boot files, which are added below. + fs = LittleFS( + context=UserContextFile(str(flash)), + block_size=block_size, + block_count=block_count, + ) + for name, content in files.items(): + parent = posixpath.dirname(name) + if parent: + fs.makedirs(parent, exist_ok=True) + mode = "wb" if isinstance(content, bytes) else "wt" + with fs.open(f"/{name}", mode) as f: + f.write(content) + fs.context.close() + + +def read_lfs_file_from_flash(flash_file, path, board, erase_page_size): + """Extract a file from the littlefs filesystem in the flash image.""" + from littlefs import LittleFS + from littlefs.context import UserContextFile + + block_size, block_count = _lfs_geometry(board, erase_page_size) + fs = LittleFS( + context=UserContextFile(str(flash_file)), + block_size=block_size, + block_count=block_count, + ) + with fs.open(f"/{path}", "rb") as f: + content = f.read() + fs.context.close() + return content.decode() + + +@pytest.fixture(autouse=True) +def _skip_fat_filesystem_only_tests(request, board): + """Honor the ``fat_filesystem_only`` marker on littlefs boards.""" + if request.node.get_closest_marker("fat_filesystem_only") is None: + return + if board in LITTLEFS_FILESYSTEM_BOARDS: + pytest.skip("test requires the FAT filesystem build") + + +@pytest.fixture +def native_sim_binary(request, board): + """Return path to native_sim binary, skip if not built.""" + build_dir = ZEPHYR_CP / f"build-{board}" + binary = build_dir / "zephyr-cp/zephyr/zephyr.exe" + + if not binary.exists(): + pytest.skip(f"binary not built: {binary}") + return binary + + +@pytest.fixture +def native_sim_env() -> dict[str, str]: + env = {} + # Always pick the video driver explicitly. Always using dummy works in a + # bubblewrap sandbox and avoids GL teardown issues on GitHub Actions. + if not os.environ.get("SDL_VIDEODRIVER"): + env["SDL_VIDEODRIVER"] = "dummy" + return env + + +PIXEL_FORMAT_BITMASK = { + "RGB_888": 1 << 0, + "MONO01": 1 << 1, + "MONO10": 1 << 2, + "ARGB_8888": 1 << 3, + "RGB_565": 1 << 4, + "BGR_565": 1 << 5, + "L_8": 1 << 6, + "AL_88": 1 << 7, +} + + +@pytest.fixture +def pixel_format(request) -> str: + """Indirect-parametrize fixture: adds display_pixel_format marker.""" + fmt = request.param + request.node.add_marker(pytest.mark.display_pixel_format(fmt)) + return fmt + + +@pytest.fixture +def sim_id(request) -> str: + return request.node.nodeid.replace("/", "_") + + +def _populate_drive(flash, files, board, tmp_path, index, erase_page_size): + """Copy files onto the flash image with the host tool matching the board's + filesystem, if any were requested.""" + if files is None: + return + if board in LITTLEFS_FILESYSTEM_BOARDS: + _populate_lfs_drive(flash, files, board, erase_page_size) + else: + _populate_fat_drive(flash, files, board, tmp_path, index) + + +def _populate_fat_drive(flash, files, board, tmp_path, index): + """Copy files onto a FAT flash image with mtools.""" + if board not in FAT_FILESYSTEM_BOARDS: + pytest.skip( + f"cannot preload files onto {board}: only FAT filesystem images " + "can be built from the host" + ) + subprocess.run(["mformat", "-i", str(flash), "::"], check=True) + tmp_drive = tmp_path / f"drive{index}" + tmp_drive.mkdir(exist_ok=True) + + fat_dirs_created = set() + for name, content in files.items(): + src = tmp_drive / name + src.parent.mkdir(parents=True, exist_ok=True) + if isinstance(content, bytes): + src.write_bytes(content) + else: + src.write_text(content) + # Create parent directories on the FAT image. + fat_dir = Path(name).parent + for fat_part in [*reversed(fat_dir.parents), fat_dir]: + if fat_part == Path("."): + continue + fat_path = "::" + str(fat_part) + if fat_path not in fat_dirs_created: + subprocess.run(["mmd", "-i", str(flash), fat_path], check=True) + fat_dirs_created.add(fat_path) + subprocess.run(["mcopy", "-i", str(flash), str(src), f"::{name}"], check=True) + + +@pytest.fixture +def circuitpython(request, board, sim_id, native_sim_binary, native_sim_env, tmp_path): + """Run CircuitPython with given code string and return PTY output.""" + + instance_count = 1 + if "circuitpython1" in request.fixturenames and "circuitpython2" in request.fixturenames: + instance_count = 2 + + drives = list(request.node.iter_markers_with_node("circuitpy_drive")) + if len(drives) != instance_count: + raise RuntimeError(f"not enough drives for {instance_count} instances") + + input_trace_markers = list(request.node.iter_markers_with_node("input_trace")) + if len(input_trace_markers) > 1: + raise RuntimeError("expected at most one input_trace marker") + + input_trace = None + if input_trace_markers and len(input_trace_markers[0][1].args) == 1: + input_trace = input_trace_markers[0][1].args[0] + + input_trace_file = None + if input_trace is not None: + input_trace_file = tmp_path / "input.perfetto" + write_input_trace(input_trace_file, input_trace) + + marker = request.node.get_closest_marker("duration") + if marker is None: + timeout = 10 + else: + timeout = marker.args[0] + + resets_marker = request.node.get_closest_marker("port_resets") + # Main does one reset on start up and then one on each VM clean up. It also + # does one after printing the safe mode message. + if resets_marker is None: + port_resets = 2 + else: + port_resets = int(resets_marker.args[0]) + + display_marker = request.node.get_closest_marker("display") + if display_marker is None: + display_marker = request.node.get_closest_marker("display_capture") + + capture_times_ns = None + if display_marker is not None: + capture_times_ns = display_marker.kwargs.get("capture_times_ns", None) + + pixel_format_marker = request.node.get_closest_marker("display_pixel_format") + pixel_format = None + if pixel_format_marker is not None and pixel_format_marker.args: + pixel_format = pixel_format_marker.args[0] + + mono_vtiled_marker = request.node.get_closest_marker("display_mono_vtiled") + mono_vtiled = None + if mono_vtiled_marker is not None and mono_vtiled_marker.args: + mono_vtiled = mono_vtiled_marker.args[0] + + # If capture_times_ns is set, merge display_capture track into input trace. + if capture_times_ns is not None: + if input_trace is None: + input_trace = {} + else: + input_trace = dict(input_trace) + input_trace["display_capture"] = list(capture_times_ns) + if input_trace_file is None: + input_trace_file = tmp_path / "input.perfetto" + write_input_trace(input_trace_file, input_trace) + + use_realtime = request.node.get_closest_marker("native_sim_rt") is not None + + flash_config_marker = request.node.get_closest_marker("flash_config") + flash_total_size = 2 * 1024 * 1024 # default 2MB + flash_erase_block_size = None + flash_write_block_size = None + if flash_config_marker: + flash_total_size = flash_config_marker.kwargs.get("total_size", flash_total_size) + flash_erase_block_size = flash_config_marker.kwargs.get("erase_block_size", None) + flash_write_block_size = flash_config_marker.kwargs.get("write_block_size", None) + # The littlefs image geometry must match the erase page size the + # simulator will run with, which the flash_config marker can override. + populate_erase_page_size = ( + flash_erase_block_size if flash_erase_block_size is not None else DEFAULT_ERASE_PAGE_SIZE + ) + + procs = [] + for i in range(instance_count): + flash = tmp_path / f"flash-{i}.bin" + flash.write_bytes(b"\xff" * flash_total_size) + files = None + if len(drives[i][1].args) == 1: + files = drives[i][1].args[0] + _populate_drive(flash, files, board, tmp_path, i, populate_erase_page_size) + + trace_file = tmp_path / f"trace-{i}.perfetto" + + if "bsim" in board: + # nRF54 bsim boards use RRAMC (--flash), others use NVMC (--flash_app) + flash_arg = "--flash" if "nrf54" in board else "--flash_app" + cmd = [str(native_sim_binary), f"{flash_arg}={flash}"] + if instance_count > 1: + cmd.append("-disconnect_on_exit=1") + # nRF54 bsim boards: console UART is SERIAL20 (bsim instance 1), others use instance 0 + uart_n = "1" if "nrf54" in board else "0" + cmd.extend( + ( + f"-s={sim_id}", + f"-d={i}", + f"-uart{uart_n}_pty", + f"-uart{uart_n}_pty_wait_for_readers", + "-uart_pty_wait", + # Use the real AES implementation (libCryptov1.so) for the + # link layer instead of BabbleSim's plain-text stand-in. + # The nRF54L HW models route AES through several different + # stand-ins (ECB/CCM copy the data, CRACEN scrambles it), + # which are not consistent with each other, so LE + # encryption only works with real AES. Zephyr's own bsim + # encryption tests pass -RealEncryption=1 for the same + # reason. + "-RealEncryption=1", + f"--port-resets={port_resets}", + ) + ) + else: + cmd = [str(native_sim_binary), f"--flash={flash}"] + realtime_flag = "-rt" if use_realtime else "-no-rt" + cmd.extend( + ( + realtime_flag, + "-display_headless", + "-i2s_earless", + "-wait_uart", + f"--port-resets={port_resets}", + ) + ) + # Capture tests hold their last frame forever; stop the simulator at the + # test's duration in simulated time instead of waiting out the timeout. + if capture_times_ns and not use_realtime: + cmd.append(f"-stop_at={timeout}") + + # Always preserve retained memory (e.g. the safe-mode saved word) in + # in case of reboot. + cmd.append(f"--retained-memory={tmp_path / f'retained-{i}.bin'}") + + if flash_erase_block_size is not None: + cmd.append(f"--flash_erase_block_size={flash_erase_block_size}") + if flash_write_block_size is not None: + cmd.append(f"--flash_write_block_size={flash_write_block_size}") + if flash_config_marker and "total_size" in flash_config_marker.kwargs: + cmd.append(f"--flash_total_size={flash_total_size}") + + if input_trace_file is not None: + cmd.append(f"--input-trace={input_trace_file}") + + marker = request.node.get_closest_marker("disable_i2c_devices") + if marker and len(marker.args) > 0: + for device in marker.args: + cmd.append(f"--disable-i2c={device}") + + marker = request.node.get_closest_marker("native_sim_args") + if marker and len(marker.args) > 0: + cmd.extend(marker.args) + + if pixel_format is not None: + cmd.append(f"--display_pixel_format={PIXEL_FORMAT_BITMASK[pixel_format]}") + + if mono_vtiled is not None: + cmd.append(f"--display_mono_vtiled={'true' if mono_vtiled else 'false'}") + + env = os.environ.copy() + env.update(native_sim_env) + + capture_png_pattern = None + if capture_times_ns is not None: + if instance_count == 1: + capture_png_pattern = str(tmp_path / "frame_%d.png") + else: + capture_png_pattern = str(tmp_path / f"frame-{i}_%d.png") + cmd.append(f"--display_capture_png={capture_png_pattern}") + + logger.info("Running: %s", " ".join(cmd)) + proc = NativeSimProcess(cmd, timeout, trace_file, env, flash_file=flash) + proc.display_dump = None + proc._capture_png_pattern = capture_png_pattern + proc._capture_count = len(capture_times_ns) if capture_times_ns is not None else 0 + procs.append(proc) + if instance_count == 1: + yield procs[0] + else: + yield procs + for i, proc in enumerate(procs): + if instance_count > 1: + print(f"---------- Instance {i} -----------") + proc.shutdown() + + print("All serial output:") + print(proc.serial.all_output) + print() + print("All debug serial output:") + print(proc.debug_serial.all_output) diff --git a/ports/zephyr-cp/tests/docs/babblesim.md b/ports/zephyr-cp/tests/docs/babblesim.md new file mode 100644 index 00000000000..75d45079b2e --- /dev/null +++ b/ports/zephyr-cp/tests/docs/babblesim.md @@ -0,0 +1,81 @@ +# BabbleSim testing + +This document describes how to build and run CircuitPython tests against the +BabbleSim (bsim) nRF5340 board. + +## Board target + +We use the Zephyr BabbleSim board for the nRF5340 application core: + +- Zephyr board: `nrf5340bsim/nrf5340/cpuapp` +- CircuitPython board alias: `native_nrf5340bsim` + +The tests expect two bsim instances to run in the same simulation, which allows +future BLE/802.15.4 multi-node tests. + +## Prerequisites + +BabbleSim needs to be available to Zephyr. Either: + +- Use the repo-provided `tools/bsim` checkout (if present) +- Or set environment variables: + +``` +export BSIM_COMPONENTS_PATH=/path/to/bsim/components +export BSIM_OUT_PATH=/path/to/bsim +``` + +## Build + +``` +CCACHE_TEMPDIR=/tmp/ccache-tmp make -j BOARD=native_nrf5340bsim +``` + +If you do not use ccache, you can omit `CCACHE_TEMPDIR`. + +## Run the bsim test + +``` +pytest tests/test_bsim_basics.py -v +``` + +## BLE scan + advertising tests + +The BLE tests run multiple bsim instances and build Zephyr samples on-demand: + +- `tests/test_bsim_ble_scan.py` scans for the Zephyr beacon sample +- `tests/test_bsim_ble_advertising.py` advertises from CircuitPython while the + Zephyr observer sample scans + +The fixtures build the Zephyr samples if missing: + +- Beacon: `zephyr/samples/bluetooth/beacon` (board `nrf52_bsim`) +- Observer: `zephyr/samples/bluetooth/observer` (board `nrf52_bsim`) + +Run the tests with: + +``` +pytest tests/test_bsim_ble_scan.py -v +pytest tests/test_bsim_ble_advertising.py -v +``` + +## Pytest markers + +For bsim-specific test tuning: + +- `@pytest.mark.duration(seconds)` controls simulation runtime/timeout. + +Example: + +```py +pytestmark = pytest.mark.duration(30.0) +``` + +## Notes + +- The bsim test spawns two instances that share a sim id. It only checks UART + output for now, but is the base for BLE/Thread multi-node tests. +- The BLE tests rely on the sysbuild HCI IPC net-core image for the nRF5340 + simulator (enabled via `sysbuild.conf`). +- The board uses a custom devicetree overlay to provide the SRAM region and + CircuitPython flash partition expected by the port. diff --git a/ports/zephyr-cp/tests/docs/i2c_emulator_cmdline_control.md b/ports/zephyr-cp/tests/docs/i2c_emulator_cmdline_control.md new file mode 100644 index 00000000000..8ee2925915c --- /dev/null +++ b/ports/zephyr-cp/tests/docs/i2c_emulator_cmdline_control.md @@ -0,0 +1,306 @@ +# Command-Line Control of Emulated I2C Devices in native_sim + +This document describes an approach for enabling/disabling emulated I2C devices +at runtime via command-line options in Zephyr's native_sim environment. + +## Background + +Zephyr's I2C emulation framework (`zephyr,i2c-emul-controller`) provides: + +1. **Bus emulation** - Fake I2C controller that routes transfers to emulated devices +2. **Device emulators** - Software implementations of I2C peripherals (sensors, etc.) +3. **Backend APIs** - Test interfaces for manipulating emulator state + +However, there's no built-in mechanism to enable/disable emulated devices from the +command line. This capability would be useful for: + +- Testing device hot-plug scenarios +- Simulating hardware failures +- Testing error handling paths in CircuitPython + +## Relevant Zephyr APIs + +### I2C Emulator Structure + +From `include/zephyr/drivers/i2c_emul.h`: + +```c +struct i2c_emul { + sys_snode_t node; + const struct emul *target; + const struct i2c_emul_api *api; + struct i2c_emul_api *mock_api; // If non-NULL, takes precedence + uint16_t addr; +}; + +struct i2c_emul_api { + i2c_emul_transfer_t transfer; +}; +``` + +Key insight: The `mock_api` field allows overriding the normal transfer function. +If `mock_api->transfer()` returns `-ENOSYS`, it falls back to the real API. + +### Command-Line Registration + +From `boards/native/native_sim/cmdline.h`: + +```c +void native_add_command_line_opts(struct args_struct_t *args); +``` + +### Emulator Lookup + +From `include/zephyr/drivers/emul.h`: + +```c +const struct emul *emul_get_binding(const char *name); +``` + +## Implementation Approach + +### 1. Create a Disabled Device Registry + +Track which devices are "disabled" (should NACK all transactions): + +```c +// i2c_emul_cmdline.c + +#include +#include +#include +#include "nsi_cmdline.h" + +#define MAX_DISABLED_DEVICES 16 + +static struct { + const char *name; + const struct emul *emul; + struct i2c_emul_api mock_api; + struct i2c_emul_api *original_mock_api; + bool disabled; +} disabled_devices[MAX_DISABLED_DEVICES]; + +static int num_disabled_devices = 0; +``` + +### 2. Mock Transfer Function + +Return `-EIO` (simulates NACK) when device is disabled: + +```c +static int disabled_device_transfer(const struct emul *target, + struct i2c_msg *msgs, + int num_msgs, + int addr) +{ + // Find this device in our registry + for (int i = 0; i < num_disabled_devices; i++) { + if (disabled_devices[i].emul == target) { + if (disabled_devices[i].disabled) { + // Device is disabled - simulate NACK + return -EIO; + } + break; + } + } + // Fall back to normal emulator behavior + return -ENOSYS; +} +``` + +### 3. Enable/Disable Functions + +```c +int i2c_emul_cmdline_disable_device(const char *name) +{ + const struct emul *emul = emul_get_binding(name); + if (!emul || emul->bus_type != EMUL_BUS_TYPE_I2C) { + return -ENODEV; + } + + // Find or create registry entry + int idx = -1; + for (int i = 0; i < num_disabled_devices; i++) { + if (disabled_devices[i].emul == emul) { + idx = i; + break; + } + } + + if (idx < 0) { + if (num_disabled_devices >= MAX_DISABLED_DEVICES) { + return -ENOMEM; + } + idx = num_disabled_devices++; + disabled_devices[idx].name = name; + disabled_devices[idx].emul = emul; + disabled_devices[idx].mock_api.transfer = disabled_device_transfer; + + // Save and replace mock_api + disabled_devices[idx].original_mock_api = emul->bus.i2c->mock_api; + emul->bus.i2c->mock_api = &disabled_devices[idx].mock_api; + } + + disabled_devices[idx].disabled = true; + return 0; +} + +int i2c_emul_cmdline_enable_device(const char *name) +{ + for (int i = 0; i < num_disabled_devices; i++) { + if (strcmp(disabled_devices[i].name, name) == 0) { + disabled_devices[i].disabled = false; + return 0; + } + } + return -ENODEV; +} +``` + +### 4. Command-Line Option Registration + +```c +static char *disabled_device_args[MAX_DISABLED_DEVICES]; +static int num_disabled_device_args = 0; + +static void cmd_disable_i2c_device(char *argv, int offset) +{ + ARG_UNUSED(offset); + if (num_disabled_device_args < MAX_DISABLED_DEVICES) { + disabled_device_args[num_disabled_device_args++] = argv; + } +} + +static struct args_struct_t i2c_emul_args[] = { + { + .option = "disable-i2c", + .name = "device_name", + .type = 's', + .call_when_found = cmd_disable_i2c_device, + .descript = "Disable an emulated I2C device (can be repeated)" + }, + ARG_TABLE_ENDMARKER +}; + +static void register_cmdline_opts(void) +{ + native_add_command_line_opts(i2c_emul_args); +} + +// Hook into native_sim initialization +NATIVE_TASK(register_cmdline_opts, PRE_BOOT_1, 0); + +static void apply_disabled_devices(void) +{ + for (int i = 0; i < num_disabled_device_args; i++) { + int rc = i2c_emul_cmdline_disable_device(disabled_device_args[i]); + if (rc != 0) { + printk("Warning: Failed to disable I2C device '%s': %d\n", + disabled_device_args[i], rc); + } + } +} + +// Apply after emulators are initialized +NATIVE_TASK(apply_disabled_devices, PRE_BOOT_3, 0); +``` + +### 5. Usage + +After building with this code: + +```bash +# Disable a sensor at startup +./build/zephyr/zephyr.exe --disable-i2c=bmi160@68 + +# Disable multiple devices +./build/zephyr/zephyr.exe --disable-i2c=bmi160@68 --disable-i2c=sht4x@44 +``` + +## Runtime Control Extension + +For runtime enable/disable (not just at startup), you could: + +### Option A: Use a Named Pipe / FIFO + +```c +// Create a FIFO that accepts commands +// "disable bmi160@68" or "enable bmi160@68" +static void *cmdline_control_thread(void *arg) +{ + int fd = open("/tmp/i2c_emul_control", O_RDONLY); + char buf[256]; + while (read(fd, buf, sizeof(buf)) > 0) { + if (strncmp(buf, "disable ", 8) == 0) { + i2c_emul_cmdline_disable_device(buf + 8); + } else if (strncmp(buf, "enable ", 7) == 0) { + i2c_emul_cmdline_enable_device(buf + 7); + } + } + return NULL; +} +``` + +### Option B: Signal Handler + +Use `SIGUSR1`/`SIGUSR2` with a config file that specifies which device to toggle. + +### Option C: Shared Memory + +Map a shared memory region that external tools can write to for device state. + +## Integration with CircuitPython Tests + +For pytest-based tests, you could: + +```python +import subprocess +import os + +class NativeSimProcess: + def __init__(self, exe_path): + self.exe_path = exe_path + self.control_fifo = "/tmp/i2c_emul_control" + + def start(self, disabled_devices=None): + args = [self.exe_path] + if disabled_devices: + for dev in disabled_devices: + args.extend(["--disable-i2c", dev]) + self.proc = subprocess.Popen(args, ...) + + def disable_device(self, name): + """Runtime disable via FIFO""" + with open(self.control_fifo, 'w') as f: + f.write(f"disable {name}\n") + + def enable_device(self, name): + """Runtime enable via FIFO""" + with open(self.control_fifo, 'w') as f: + f.write(f"enable {name}\n") +``` + +## Alternative: Device Tree Approach + +For compile-time configuration, use device tree overlays: + +```dts +// boards/native_sim_no_bmi160.overlay +&bmi160 { + status = "disabled"; +}; +``` + +Build separate variants: +```bash +west build -b native_sim -- -DDTC_OVERLAY_FILE=boards/native_sim_no_bmi160.overlay +``` + +## References + +- Zephyr I2C Emulation: `zephyr/drivers/i2c/i2c_emul.c` +- Emulator Framework: `zephyr/doc/hardware/emulator/bus_emulators.rst` +- Native Sim Docs: `zephyr/boards/native/native_sim/doc/index.rst` +- Command-line handling: `zephyr/boards/native/native_sim/cmdline.c` +- Example mock API usage: `zephyr/tests/drivers/sensor/bmi160/src/i2c.c` diff --git a/ports/zephyr-cp/tests/docs/web_workflow.md b/ports/zephyr-cp/tests/docs/web_workflow.md new file mode 100644 index 00000000000..eb6742b8a3e --- /dev/null +++ b/ports/zephyr-cp/tests/docs/web_workflow.md @@ -0,0 +1,37 @@ +# Web Workflow native_sim Tests + +These tests validate CircuitPython's web workflow support in the Zephyr native_sim port, including filesystem write behavior with and without USB-style write protection. + +## Coverage + +- `test_web_workflow_hostnetwork`: Verifies the web workflow HTTP server responds and enforces authentication (`/edit/` returns `401 Unauthorized`). +- `test_web_workflow_write_code_py_conflict`: Exercises a write attempt while the filesystem is protected (no `boot.py` remount). The DELETE request should return `409 Conflict`. +- `test_web_workflow_write_code_py_remount`: Uses a `boot.py` remount to allow CircuitPython to write. A PUT request updates `code.py`, and a subsequent GET verifies the contents. + +## Filesystem Setup + +The tests create a flash image with: + +- `settings.toml` containing `CIRCUITPY_WEB_API_PASSWORD="testpass"` so the web workflow starts using the on-device settings file. +- `boot.py` (for the remount test only) with: + ```python + import storage + storage.remount("/", readonly=False) + ``` + This disables concurrent write protection so the web workflow can write to CIRCUITPY. + +## Running the Tests + +Build native_sim (if needed): + +```bash +make BOARD=native_native_sim +``` + +Run the tests: + +```bash +pytest -q ports/zephyr-cp/tests/test_web_workflow.py::test_web_workflow_hostnetwork -vv +pytest -q ports/zephyr-cp/tests/test_web_workflow.py::test_web_workflow_write_code_py_conflict -vv +pytest -q ports/zephyr-cp/tests/test_web_workflow.py::test_web_workflow_write_code_py_remount -vv +``` diff --git a/ports/zephyr-cp/tests/lvfontio/golden/lvfontio_terminal_320x240.png b/ports/zephyr-cp/tests/lvfontio/golden/lvfontio_terminal_320x240.png new file mode 100644 index 00000000000..3cf0d3d75f2 Binary files /dev/null and b/ports/zephyr-cp/tests/lvfontio/golden/lvfontio_terminal_320x240.png differ diff --git a/ports/zephyr-cp/tests/lvfontio/unifont-16.0.02-ja.bin b/ports/zephyr-cp/tests/lvfontio/unifont-16.0.02-ja.bin new file mode 100644 index 00000000000..a219b2d7312 Binary files /dev/null and b/ports/zephyr-cp/tests/lvfontio/unifont-16.0.02-ja.bin differ diff --git a/ports/zephyr-cp/tests/perfetto_input_trace.py b/ports/zephyr-cp/tests/perfetto_input_trace.py new file mode 100644 index 00000000000..494c9cdcadf --- /dev/null +++ b/ports/zephyr-cp/tests/perfetto_input_trace.py @@ -0,0 +1,159 @@ +# SPDX-FileCopyrightText: 2026 Scott Shawcroft for Adafruit Industries LLC +# SPDX-License-Identifier: MIT + +"""Utilities for creating Perfetto input trace files for native_sim tests. + +This module can be used directly from Python or from the command line: + + python -m tests.perfetto_input_trace input_trace.json output.perfetto + +Input JSON format — counter tracks use [timestamp, value] pairs, instant +tracks use bare timestamps: + +{ + "gpio_emul.01": [[8000000000, 0], [9000000000, 1], [10000000000, 0]], + "display_capture": [500000000, 1000000000] +} +""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import Mapping, Sequence + +# Counter tracks: list of (timestamp, value) pairs. +# Instant tracks: list of timestamps (bare ints). +InputTraceData = Mapping[str, Sequence[tuple[int, int] | int]] + + +def _load_perfetto_pb2(): + from perfetto.protos.perfetto.trace import perfetto_trace_pb2 as perfetto_pb2 + + return perfetto_pb2 + + +def _is_instant_track(events: Sequence) -> bool: + """Return True if *events* is a list of bare timestamps (instant track).""" + if not events: + return False + return isinstance(events[0], int) + + +def build_input_trace(trace_data: InputTraceData, *, sequence_id: int = 1): + """Build a Perfetto Trace protobuf for input replay counter and instant tracks.""" + perfetto_pb2 = _load_perfetto_pb2() + trace = perfetto_pb2.Trace() + + seq_incremental_state_cleared = 1 + seq_needs_incremental_state = 2 + + for idx, (track_name, events) in enumerate(trace_data.items()): + track_uuid = 1001 + idx + instant = _is_instant_track(events) + + desc_packet = trace.packet.add() + desc_packet.timestamp = 0 + desc_packet.trusted_packet_sequence_id = sequence_id + if idx == 0: + desc_packet.sequence_flags = seq_incremental_state_cleared + desc_packet.track_descriptor.uuid = track_uuid + desc_packet.track_descriptor.name = track_name + if not instant: + desc_packet.track_descriptor.counter.unit = ( + perfetto_pb2.CounterDescriptor.Unit.UNIT_COUNT + ) + + if instant: + for ts in events: + event_packet = trace.packet.add() + event_packet.timestamp = ts + event_packet.trusted_packet_sequence_id = sequence_id + event_packet.sequence_flags = seq_needs_incremental_state + event_packet.track_event.type = perfetto_pb2.TrackEvent.Type.TYPE_INSTANT + event_packet.track_event.track_uuid = track_uuid + else: + for ts, value in events: + event_packet = trace.packet.add() + event_packet.timestamp = ts + event_packet.trusted_packet_sequence_id = sequence_id + event_packet.sequence_flags = seq_needs_incremental_state + event_packet.track_event.type = perfetto_pb2.TrackEvent.Type.TYPE_COUNTER + event_packet.track_event.track_uuid = track_uuid + event_packet.track_event.counter_value = value + + return trace + + +def write_input_trace( + trace_file: Path, trace_data: InputTraceData, *, sequence_id: int = 1 +) -> None: + """Write input replay data to a Perfetto trace file.""" + trace = build_input_trace(trace_data, sequence_id=sequence_id) + trace_file.parent.mkdir(parents=True, exist_ok=True) + trace_file.write_bytes(trace.SerializeToString()) + + +def _parse_trace_json(data: object) -> dict[str, list[tuple[int, int]] | list[int]]: + if not isinstance(data, dict): + raise ValueError("top-level JSON value must be an object") + + parsed: dict[str, list[tuple[int, int]] | list[int]] = {} + for track_name, events in data.items(): + if not isinstance(track_name, str): + raise ValueError("track names must be strings") + if not isinstance(events, list): + raise ValueError(f"track {track_name!r} must map to a list of events") + + if not events: + parsed[track_name] = [] + continue + + # Distinguish instant (bare ints) vs counter ([ts, value] pairs). + if isinstance(events[0], (int, float)): + parsed[track_name] = [int(ts) for ts in events] + else: + parsed_events: list[tuple[int, int]] = [] + for event in events: + if not isinstance(event, (list, tuple)) or len(event) != 2: + raise ValueError( + f"track {track_name!r} events must be [timestamp, value] pairs " + "or bare timestamps" + ) + timestamp_ns, value = event + parsed_events.append((int(timestamp_ns), int(value))) + parsed[track_name] = parsed_events + + return parsed + + +def _build_arg_parser() -> argparse.ArgumentParser: + parser = argparse.ArgumentParser( + description="Generate a Perfetto input trace file used by native_sim --input-trace" + ) + parser.add_argument("input_json", type=Path, help="Path to input trace JSON") + parser.add_argument("output_trace", type=Path, help="Output .perfetto file path") + parser.add_argument( + "--sequence-id", + type=int, + default=1, + help="trusted_packet_sequence_id to use (default: 1)", + ) + return parser + + +def main(argv: Sequence[str] | None = None) -> int: + parser = _build_arg_parser() + args = parser.parse_args(argv) + + trace_json = json.loads(args.input_json.read_text()) + trace_data = _parse_trace_json(trace_json) + write_input_trace(args.output_trace, trace_data, sequence_id=args.sequence_id) + + print(f"Wrote {args.output_trace} ({len(trace_data)} tracks)") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/ports/zephyr-cp/tests/test_adafruit_bus_device.py b/ports/zephyr-cp/tests/test_adafruit_bus_device.py new file mode 100644 index 00000000000..3022838506e --- /dev/null +++ b/ports/zephyr-cp/tests/test_adafruit_bus_device.py @@ -0,0 +1,236 @@ +# SPDX-FileCopyrightText: 2026 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""Test adafruit_bus_device.i2c_device.I2CDevice against the AT24 EEPROM emulator.""" + +import pytest + + +PROBE_OK_CODE = """\ +import board +from adafruit_bus_device.i2c_device import I2CDevice + +i2c = board.I2C() +device = I2CDevice(i2c, 0x50) +print(f"device created: {type(device).__name__}") +i2c.deinit() +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": PROBE_OK_CODE}) +def test_i2cdevice_probe_success(circuitpython): + """Constructing I2CDevice with probe=True succeeds when AT24 is present at 0x50.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "device created: I2CDevice" in output + assert "done" in output + + +PROBE_FAIL_CODE = """\ +import board +from adafruit_bus_device.i2c_device import I2CDevice + +i2c = board.I2C() +try: + device = I2CDevice(i2c, 0x51) + print("unexpected_success") +except ValueError as e: + print(f"probe_failed: {e}") +except OSError as e: + print(f"probe_failed: {e}") +i2c.deinit() +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": PROBE_FAIL_CODE}) +def test_i2cdevice_probe_failure(circuitpython): + """Constructing I2CDevice with probe=True raises when no device responds.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "probe_failed" in output + assert "unexpected_success" not in output + assert "done" in output + + +PROBE_DISABLED_CODE = """\ +import board +from adafruit_bus_device.i2c_device import I2CDevice + +i2c = board.I2C() +# probe=False should not raise even without a device at this address +device = I2CDevice(i2c, 0x51, probe=False) +print(f"device created: {type(device).__name__}") +i2c.deinit() +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": PROBE_DISABLED_CODE}) +def test_i2cdevice_probe_disabled(circuitpython): + """Constructing I2CDevice with probe=False succeeds regardless of device presence.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "device created: I2CDevice" in output + assert "done" in output + + +READ_CODE = """\ +import board +from adafruit_bus_device.i2c_device import I2CDevice + +i2c = board.I2C() +device = I2CDevice(i2c, 0x50) + +# Read first byte by writing the memory address, then reading. +buf = bytearray(1) +with device: + device.write(bytes([0x00])) + device.readinto(buf) +print(f"AT24 byte 0: 0x{buf[0]:02X}") +if buf[0] == 0xFF: + print("eeprom_valid") +i2c.deinit() +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": READ_CODE}) +def test_i2cdevice_write_then_readinto_separate(circuitpython): + """write() followed by readinto() inside a single context manager block reads EEPROM data.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "AT24 byte 0: 0xFF" in output + assert "eeprom_valid" in output + assert "done" in output + + +WRITE_THEN_READINTO_CODE = """\ +import board +from adafruit_bus_device.i2c_device import I2CDevice + +i2c = board.I2C() +device = I2CDevice(i2c, 0x50) + +out_buf = bytes([0x00]) +in_buf = bytearray(4) +with device: + device.write_then_readinto(out_buf, in_buf) +print(f"first 4 bytes: {[hex(b) for b in in_buf]}") +if all(b == 0xFF for b in in_buf): + print("eeprom_valid") +i2c.deinit() +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": WRITE_THEN_READINTO_CODE}) +def test_i2cdevice_write_then_readinto_atomic(circuitpython): + """write_then_readinto() performs an atomic write+read against the EEPROM.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "first 4 bytes:" in output + assert "eeprom_valid" in output + assert "done" in output + + +WRITE_READBACK_CODE = """\ +import board +import time +from adafruit_bus_device.i2c_device import I2CDevice + +i2c = board.I2C() +device = I2CDevice(i2c, 0x50) + +# Write four bytes starting at EEPROM address 0x10. +payload = bytes([0xDE, 0xAD, 0xBE, 0xEF]) +with device: + device.write(bytes([0x10]) + payload) + +# EEPROM needs a moment to commit the write internally. +time.sleep(0.01) + +readback = bytearray(4) +with device: + device.write_then_readinto(bytes([0x10]), readback) +print(f"readback: {[hex(b) for b in readback]}") +if bytes(readback) == payload: + print("readback_ok") +i2c.deinit() +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": WRITE_READBACK_CODE}) +def test_i2cdevice_write_then_read_roundtrip(circuitpython): + """Writing bytes to the EEPROM and reading them back returns the written values.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "readback_ok" in output + assert "done" in output + + +SLICE_CODE = """\ +import board +from adafruit_bus_device.i2c_device import I2CDevice + +i2c = board.I2C() +device = I2CDevice(i2c, 0x50) + +# Use start/end kwargs to send only a slice of the outgoing buffer. +out = bytearray([0xAA, 0x00, 0xBB]) +dest = bytearray(4) +with device: + # Only send the middle byte (the memory address 0x00). + device.write_then_readinto(out, dest, out_start=1, out_end=2, in_start=0, in_end=2) +print(f"partial read: {[hex(b) for b in dest]}") +# Only the first two entries should have been written by the read. +if dest[0] == 0xFF and dest[1] == 0xFF and dest[2] == 0x00 and dest[3] == 0x00: + print("slice_ok") +i2c.deinit() +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": SLICE_CODE}) +def test_i2cdevice_buffer_slices(circuitpython): + """write_then_readinto honors out_start/out_end and in_start/in_end bounds.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "slice_ok" in output + assert "done" in output + + +DISABLED_CODE = """\ +import board +from adafruit_bus_device.i2c_device import I2CDevice + +i2c = board.I2C() +try: + device = I2CDevice(i2c, 0x50) + print("unexpected_success") +except (ValueError, OSError) as e: + print(f"probe_failed: {e}") +i2c.deinit() +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": DISABLED_CODE}) +@pytest.mark.disable_i2c_devices("eeprom@50") +def test_i2cdevice_probe_fails_when_device_disabled(circuitpython): + """Probe fails when the AT24 emulator device is disabled on the bus.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "probe_failed" in output + assert "unexpected_success" not in output + assert "done" in output diff --git a/ports/zephyr-cp/tests/test_aesio.py b/ports/zephyr-cp/tests/test_aesio.py new file mode 100644 index 00000000000..3ae016ac8e3 --- /dev/null +++ b/ports/zephyr-cp/tests/test_aesio.py @@ -0,0 +1,223 @@ +# SPDX-FileCopyrightText: 2026 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""Test the aesio module.""" + +import pytest + +from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes + + +KEY = b"Sixteen byte key" +PLAINTEXT = b"CircuitPython!!!" # 16 bytes + + +ECB_CODE = """\ +import aesio + +key = b'Sixteen byte key' +inp = b'CircuitPython!!!' +outp = bytearray(len(inp)) +cipher = aesio.AES(key, aesio.MODE_ECB) +cipher.encrypt_into(inp, outp) +print(f"ciphertext_hex: {outp.hex()}") + +decrypted = bytearray(len(outp)) +cipher.decrypt_into(bytes(outp), decrypted) +print(f"decrypted: {bytes(decrypted)}") +print(f"match: {bytes(decrypted) == inp}") +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": ECB_CODE}) +def test_aesio_ecb(circuitpython): + """AES-ECB round-trips and matches CPython cryptography's output.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + encryptor = Cipher(algorithms.AES(KEY), modes.ECB()).encryptor() + expected_hex = (encryptor.update(PLAINTEXT) + encryptor.finalize()).hex() + assert f"ciphertext_hex: {expected_hex}" in output + assert "match: True" in output + assert "done" in output + + +IV = b"InitializationVe" # 16 bytes +CBC_PLAINTEXT = b"CircuitPython!!!" * 2 # 32 bytes, multiple of 16 +CTR_PLAINTEXT = b"CircuitPython is fun to use!" # 28 bytes, arbitrary length + + +CBC_CODE = """\ +import aesio + +key = b'Sixteen byte key' +iv = b'InitializationVe' +inp = b'CircuitPython!!!' * 2 +outp = bytearray(len(inp)) +cipher = aesio.AES(key, aesio.MODE_CBC, iv) +print(f"mode: {cipher.mode}") +cipher.encrypt_into(inp, outp) +print(f"ciphertext_hex: {outp.hex()}") + +# Re-create cipher to reset IV state for decryption. +cipher2 = aesio.AES(key, aesio.MODE_CBC, iv) +decrypted = bytearray(len(outp)) +cipher2.decrypt_into(bytes(outp), decrypted) +print(f"match: {bytes(decrypted) == inp}") +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": CBC_CODE}) +def test_aesio_cbc(circuitpython): + """AES-CBC round-trips and matches CPython cryptography's output.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + encryptor = Cipher(algorithms.AES(KEY), modes.CBC(IV)).encryptor() + expected_hex = (encryptor.update(CBC_PLAINTEXT) + encryptor.finalize()).hex() + assert "mode: 2" in output + assert f"ciphertext_hex: {expected_hex}" in output + assert "match: True" in output + assert "done" in output + + +CTR_CODE = """\ +import aesio + +key = b'Sixteen byte key' +iv = b'InitializationVe' +inp = b'CircuitPython is fun to use!' +outp = bytearray(len(inp)) +cipher = aesio.AES(key, aesio.MODE_CTR, iv) +print(f"mode: {cipher.mode}") +cipher.encrypt_into(inp, outp) +print(f"ciphertext_hex: {outp.hex()}") + +cipher2 = aesio.AES(key, aesio.MODE_CTR, iv) +decrypted = bytearray(len(outp)) +cipher2.decrypt_into(bytes(outp), decrypted) +print(f"decrypted: {bytes(decrypted)}") +print(f"match: {bytes(decrypted) == inp}") +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": CTR_CODE}) +def test_aesio_ctr(circuitpython): + """AES-CTR handles arbitrary-length buffers and matches CPython output.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + encryptor = Cipher(algorithms.AES(KEY), modes.CTR(IV)).encryptor() + expected_hex = (encryptor.update(CTR_PLAINTEXT) + encryptor.finalize()).hex() + assert "mode: 6" in output + assert f"ciphertext_hex: {expected_hex}" in output + assert "match: True" in output + assert "done" in output + + +REKEY_CODE = """\ +import aesio + +key1 = b'Sixteen byte key' +key2 = b'Another 16 byte!' +inp = b'CircuitPython!!!' + +cipher = aesio.AES(key1, aesio.MODE_ECB) +out1 = bytearray(16) +cipher.encrypt_into(inp, out1) +print(f"ct1_hex: {out1.hex()}") + +cipher.rekey(key2) +out2 = bytearray(16) +cipher.encrypt_into(inp, out2) +print(f"ct2_hex: {out2.hex()}") +print(f"different: {bytes(out1) != bytes(out2)}") +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": REKEY_CODE}) +def test_aesio_rekey(circuitpython): + """rekey() switches the active key; ciphertexts match CPython for both keys.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + enc1 = Cipher(algorithms.AES(b"Sixteen byte key"), modes.ECB()).encryptor() + ct1 = (enc1.update(PLAINTEXT) + enc1.finalize()).hex() + enc2 = Cipher(algorithms.AES(b"Another 16 byte!"), modes.ECB()).encryptor() + ct2 = (enc2.update(PLAINTEXT) + enc2.finalize()).hex() + assert f"ct1_hex: {ct1}" in output + assert f"ct2_hex: {ct2}" in output + assert "different: True" in output + assert "done" in output + + +MODE_PROPERTY_CODE = """\ +import aesio + +key = b'Sixteen byte key' +iv = b'InitializationVe' +cipher = aesio.AES(key, aesio.MODE_ECB) +print(f"initial: {cipher.mode}") +print(f"ECB={aesio.MODE_ECB} CBC={aesio.MODE_CBC} CTR={aesio.MODE_CTR}") + +for name, m in (("ECB", aesio.MODE_ECB), ("CBC", aesio.MODE_CBC), ("CTR", aesio.MODE_CTR)): + cipher.mode = m + print(f"set_{name}: {cipher.mode}") + +try: + cipher.mode = 99 +except NotImplementedError as e: + print(f"bad_mode: NotImplementedError") +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": MODE_PROPERTY_CODE}) +def test_aesio_mode_property(circuitpython): + """The mode property is readable, writable, and rejects unsupported values.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "initial: 1" in output + assert "ECB=1 CBC=2 CTR=6" in output + assert "set_ECB: 1" in output + assert "set_CBC: 2" in output + assert "set_CTR: 6" in output + assert "bad_mode: NotImplementedError" in output + assert "done" in output + + +KEY_LENGTHS_CODE = """\ +import aesio + +inp = b'CircuitPython!!!' +for key in (b'A' * 16, b'B' * 24, b'C' * 32): + cipher = aesio.AES(key, aesio.MODE_ECB) + out = bytearray(16) + cipher.encrypt_into(inp, out) + print(f"len{len(key)}: {out.hex()}") + +try: + aesio.AES(b'too short', aesio.MODE_ECB) +except ValueError: + print("bad_key: ValueError") +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": KEY_LENGTHS_CODE}) +def test_aesio_key_lengths(circuitpython): + """AES-128/192/256 keys all work and match CPython; bad key length raises.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + for key in (b"A" * 16, b"B" * 24, b"C" * 32): + encryptor = Cipher(algorithms.AES(key), modes.ECB()).encryptor() + expected = (encryptor.update(PLAINTEXT) + encryptor.finalize()).hex() + assert f"len{len(key)}: {expected}" in output + assert "bad_key: ValueError" in output + assert "done" in output diff --git a/ports/zephyr-cp/tests/test_analogio.py b/ports/zephyr-cp/tests/test_analogio.py new file mode 100644 index 00000000000..5a249f118cd --- /dev/null +++ b/ports/zephyr-cp/tests/test_analogio.py @@ -0,0 +1,230 @@ +# SPDX-FileCopyrightText: 2026 Scott Shawcroft for Adafruit Industries LLC +# SPDX-License-Identifier: MIT + +"""Test analogio functionality on native_sim.""" + +import re + +import pytest +from perfetto.trace_processor import TraceProcessor + + +ANALOGIO_TRACE_CODE = """\ +import time +import analogio +import microcontroller + +adc0 = analogio.AnalogIn(microcontroller.pin.P_00) +adc1 = analogio.AnalogIn(microcontroller.pin.P_01) +adc2 = analogio.AnalogIn(microcontroller.pin.P_02) + +print(f"t0 {adc0.value} {adc1.value} {adc2.value}") + +time.sleep(2.2) +print(f"t1 {adc0.value} {adc1.value} {adc2.value}") + +time.sleep(0.5) +print(f"t2 {adc0.value} {adc1.value} {adc2.value}") + +time.sleep(0.6) +print(f"t3 {adc0.value} {adc1.value} {adc2.value}") + +time.sleep(1.0) +print(f"t4 {adc0.value} {adc1.value} {adc2.value}") +print("done") +""" + + +ANALOGIO_INPUT_TRACE = { + # Counter tracks carry millivolts, the same unit the Zephyr ADC emul's + # value functions use. Trace timestamps are absolute simulated time; the + # simulator boots at ~2s, and code.py reads at ~2.0s (t0), ~4.2s (t1), + # ~4.7s (t2), ~5.3s (t3) and ~6.3s (t4). The step lands before t3 so all + # channels read full scale from t3 on. AnalogIn reports 16-bit codes + # relative to the 3300 mV internal reference. + "adc.0": [ + (3_000_000_000, 660), # 1/5 of full scale + (5_000_000_000, 3300), + ], + "adc.1": [ + (3_500_000_000, 1320), # 2/5 + (5_000_000_000, 3300), + ], + "adc.2": [ + (4_000_000_000, 1980), # 3/5 + (5_000_000_000, 3300), + ], +} + + +def _code_of_mv(mv: int) -> int: + """Code AnalogIn reports for an input in millivolts: the ADC emul converts + the voltage through the 3300 mV internal reference to the read's bit + depth, truncating like a real converter.""" + return (mv * 65535) // 3300 + + +def _raw14_of_mv(mv: int) -> int: + """Raw 14-bit code the ADC emul reports for an input in millivolts when + --adc-resolution narrows the emulated converter to 14 bits.""" + return (mv * 16383) // 3300 + + +def _mirror_top_bits(raw: int, bits: int) -> int: + """16-bit code a raw *bits*-bit reading is expanded to: the top bits are + replicated into the bottom (atmel-samd style), so zero and full scale are + preserved.""" + shift = 16 - bits + return (raw << shift) | (raw >> (bits - shift)) + + +def _scale_bits(value: int, from_bits: int, to_bits: int) -> int: + from_max = (1 << from_bits) - 1 + to_max = (1 << to_bits) - 1 + return (value * to_max + (from_max // 2)) // from_max + + +def _mv_of_code(code: int, bits: int = 16) -> int: + """Millivolts the DAC track records for a written code at *bits* + resolution: the emulated DAC converts the quantized code through the + 3300 mV reference with the same rounding a converter applies.""" + out_max = (1 << bits) - 1 + return (code * 3300 + out_max // 2) // out_max + + +@pytest.mark.duration(12.0) +@pytest.mark.circuitpy_drive({"code.py": ANALOGIO_TRACE_CODE}) +@pytest.mark.input_trace(ANALOGIO_INPUT_TRACE) +def test_analogio_reads_trace_millivolts(circuitpython): + """ADC values from the trace read as 16-bit codes relative to the reference.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + + t0 = re.search(r"t0 (\d+) (\d+) (\d+)", output) + t1 = re.search(r"t1 (\d+) (\d+) (\d+)", output) + t2 = re.search(r"t2 (\d+) (\d+) (\d+)", output) + t3 = re.search(r"t3 (\d+) (\d+) (\d+)", output) + t4 = re.search(r"t4 (\d+) (\d+) (\d+)", output) + + assert t0 is not None + assert t1 is not None + assert t2 is not None + assert t3 is not None + assert t4 is not None + assert "done" in output + + t0_values = tuple(int(v) for v in t0.groups()) + t1_values = tuple(int(v) for v in t1.groups()) + t2_values = tuple(int(v) for v in t2.groups()) + t3_values = tuple(int(v) for v in t3.groups()) + t4_values = tuple(int(v) for v in t4.groups()) + + expected_mid = (_code_of_mv(660), _code_of_mv(1320), _code_of_mv(1980)) + expected_max = (65535, 65535, 65535) + + assert t0_values == (0, 0, 0) + assert t1_values == expected_mid + assert t2_values == expected_mid + assert t3_values == expected_max + assert t4_values == expected_max + + +@pytest.mark.duration(12.0) +@pytest.mark.native_sim_args("--adc-resolution=14") +@pytest.mark.circuitpy_drive({"code.py": ANALOGIO_TRACE_CODE}) +@pytest.mark.input_trace(ANALOGIO_INPUT_TRACE) +def test_analogio_14bit_reads_mirror_top_bits(circuitpython): + """Reads from a narrowed emulated ADC (like CircuitPython's 14-bit SAADC + hardware reads) stretch to the 16-bit contract by replicating the top + bits into the bottom (atmel-samd style), not by scaling.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + + t1 = re.search(r"t1 (\d+) (\d+) (\d+)", output) + t3 = re.search(r"t3 (\d+) (\d+) (\d+)", output) + assert t1 is not None and t3 is not None + assert "done" in output + + t1_values = tuple(int(v) for v in t1.groups()) + t3_values = tuple(int(v) for v in t3.groups()) + + expected_mid = tuple(_mirror_top_bits(_raw14_of_mv(mv), 14) for mv in (660, 1320, 1980)) + assert t1_values == expected_mid + # The mirroring keeps zero and full scale exact. + assert t3_values == (65535, 65535, 65535) + # And the mirrored codes differ from plain scaling, so the test can tell + # the two apart: 1320 mV reads 6553 *at 14 bits* -> 26213 mirrored instead + # of the scaled 26214. + assert t1_values[1] == 26213 + + +ANALOGOUT_TRACE_CODE = """\ +import time +import analogio +import microcontroller + +out = analogio.AnalogOut(microcontroller.pin.P_00) +out.value = 0 + +time.sleep(0.1) +out.value = 12345 + +time.sleep(0.1) +out.value = 65535 + +print("done") +""" + + +def _parse_counter_track(trace_file, track_name: str) -> list[tuple[int, int]]: + tp = TraceProcessor(file_path=str(trace_file)) + result = tp.query( + f''' + SELECT c.ts, c.value + FROM counter c + JOIN track t ON c.track_id = t.id + WHERE t.name = "{track_name}" + ORDER BY c.ts + ''' + ) + return [(int(row.ts), int(row.value)) for row in result] + + +@pytest.mark.duration(8.0) +@pytest.mark.circuitpy_drive({"code.py": ANALOGOUT_TRACE_CODE}) +def test_analogout_writes_counter_trace(circuitpython): + """Writes appear on the track as millivolts through the 3300 mV reference.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "done" in output + + trace = _parse_counter_track(circuitpython.trace_file, "dac.0") + values = [value for _ts, value in trace] + + half_scale_mv = _mv_of_code(12345) + full_scale_mv = _mv_of_code(65535) + assert full_scale_mv == 3300 + assert int(half_scale_mv) in values + assert int(full_scale_mv) in values + assert values.index(half_scale_mv) < values.index(full_scale_mv) + + +@pytest.mark.duration(8.0) +@pytest.mark.native_sim_args("--dac-resolution=8") +@pytest.mark.circuitpy_drive({"code.py": ANALOGOUT_TRACE_CODE}) +def test_analogout_resolution_override(circuitpython): + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "done" in output + + trace = _parse_counter_track(circuitpython.trace_file, "dac.0") + values = [value for _ts, value in trace] + + # The quantized 8-bit code maps to a different millivolt value than the + # unquantized 16-bit code (621 vs 622), so the override is observable. + assert _mv_of_code(_scale_bits(12345, 16, 8), 8) in values + assert _mv_of_code(_scale_bits(65535, 16, 8), 8) in values diff --git a/ports/zephyr-cp/tests/test_async_spi.py b/ports/zephyr-cp/tests/test_async_spi.py new file mode 100644 index 00000000000..55f3d5eeb15 --- /dev/null +++ b/ports/zephyr-cp/tests/test_async_spi.py @@ -0,0 +1,113 @@ +# SPDX-FileCopyrightText: 2026 Vladimir Smitka +# SPDX-License-Identifier: MIT + +"""async_spi.SPI on native_sim, through the SPI loopback device.""" + +from pathlib import Path + +import pytest + +# The asyncio library is not frozen on native_sim, so the test puts it on the drive. +FROZEN = Path(__file__).resolve().parents[3] / "frozen" +ASYNCIO_LIB = { + f"lib/asyncio/{path.name}": path.read_text() + for path in (FROZEN / "Adafruit_CircuitPython_asyncio" / "asyncio").glob("*.py") +} +ASYNCIO_LIB["lib/adafruit_ticks.py"] = ( + FROZEN / "Adafruit_CircuitPython_Ticks" / "adafruit_ticks.py" +).read_text() + +LOOPBACK_CODE = """\ +import asyncio +import async_spi +import microcontroller + + +async def ticker(count): + while True: + count[0] += 1 + await asyncio.sleep(0) + + +async def main(): + spi = async_spi.SPI(microcontroller.pin.P_02, MOSI=microcontroller.pin.P_03, MISO=microcontroller.pin.P_00) + await spi.lock.__aenter__() # held for the whole test, as busio's try_lock would be + spi.configure(baudrate=1_000_000) + print("frequency", spi.frequency) + bad = 0 + for n in (1, 32, 4096): + out = bytes(i * 7 & 0xFF for i in range(n)) + inb = bytearray(n) + await spi.write_readinto(out, inb) + if inb != out: + bad += 1 + print("write_readinto", n, "differs") + await spi.readinto(inb, write_value=0xA5) + if inb != b"\\xa5" * n: + bad += 1 + print("readinto", n, "differs") + await spi.write(out) + + # Another task keeps running around the transfers. + count = [0] + task = asyncio.create_task(ticker(count)) + for _ in range(10): + await spi.write_readinto(out, inb) + await asyncio.sleep(0) + task.cancel() + print("ticker ran", count[0], "times") + + # A cancelled transfer leaves the bus usable. + task = asyncio.create_task(spi.write(out)) + await asyncio.sleep(0) + task.cancel() + try: + await task + except asyncio.CancelledError: + pass + await spi.write_readinto(out, inb) + if inb != out: + bad += 1 + print("after cancel differs") + + try: + await spi.write(123) + except TypeError: + print("bad argument raised") + spi.deinit() + try: + await spi.write(out) + except ValueError: + print("deinit raised") + with async_spi.SPI(microcontroller.pin.P_02, MOSI=microcontroller.pin.P_03, MISO=microcontroller.pin.P_00) as spi2: + try: + await spi2.readinto(inb, end=8) + except RuntimeError: + print("no lock raised") + async with spi2.lock: + await spi2.readinto(inb, end=8, write_value=0x5A) + if inb[:8] != b"\\x5a" * 8: + bad += 1 + print("second bus differs") + print("bad", bad) + print("done") + + +asyncio.run(main()) +""" + + +@pytest.mark.circuitpy_drive({"code.py": LOOPBACK_CODE, **ASYNCIO_LIB}) +def test_async_spi_loopback(circuitpython): + """Awaited transfers come back through the loopback, with cancel and deinit.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "differs" not in output + # 10 transfers of 4 KB at 1 MHz take about 330 ms; the ticker runs many times in that. + ticker = int(output.split("ticker ran ")[1].split()[0]) + assert ticker > 20, ticker + assert "bad argument raised" in output + assert "deinit raised" in output + assert "bad 0" in output + assert "done" in output diff --git a/ports/zephyr-cp/tests/test_audiobusio.py b/ports/zephyr-cp/tests/test_audiobusio.py new file mode 100644 index 00000000000..67bfd61f69d --- /dev/null +++ b/ports/zephyr-cp/tests/test_audiobusio.py @@ -0,0 +1,290 @@ +# SPDX-FileCopyrightText: 2026 Scott Shawcroft for Adafruit Industries LLC +# SPDX-License-Identifier: MIT + +"""Test audiobusio I2SOut functionality on native_sim.""" + +from pathlib import Path + +import pytest +from perfetto.trace_processor import TraceProcessor + + +I2S_PLAY_CODE = """\ +import array +import math +import audiocore +import board +import time + +# Generate a 440 Hz sine wave, 16-bit signed stereo at 16000 Hz +sample_rate = 16000 +length = sample_rate // 440 # ~36 samples per period +values = [] +for i in range(length): + v = int(math.sin(math.pi * 2 * i / length) * 30000) + values.append(v) # left + values.append(v) # right + +sample = audiocore.RawSample( + array.array("h", values), + sample_rate=sample_rate, + channel_count=2, +) + +dac = board.I2SOUT() +print("playing") +dac.play(sample, loop=True) +time.sleep(0.5) +dac.stop() +print("stopped") +print("done") +""" + + +def parse_i2s_trace(trace_file: Path, track_name: str) -> list[tuple[int, int]]: + """Parse I2S counter trace from Perfetto trace file.""" + tp = TraceProcessor(file_path=str(trace_file)) + result = tp.query( + f""" + SELECT c.ts, c.value + FROM counter c + JOIN track t ON c.track_id = t.id + WHERE t.name LIKE "%{track_name}" + ORDER BY c.ts + """ + ) + return [(int(row.ts), int(row.value)) for row in result] + + +@pytest.mark.duration(10) +@pytest.mark.circuitpy_drive({"code.py": I2S_PLAY_CODE}) +def test_i2s_play_and_stop(circuitpython): + """Test I2SOut play and stop produce expected output and correct waveform traces.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "playing" in output + assert "stopped" in output + assert "done" in output + + # Check that Perfetto trace has I2S counter tracks with data + left_trace = parse_i2s_trace(circuitpython.trace_file, "Left") + right_trace = parse_i2s_trace(circuitpython.trace_file, "Right") + + # Should have counter events (initial zero + audio data) + assert len(left_trace) > 10, f"Expected many Left channel events, got {len(left_trace)}" + assert len(right_trace) > 10, f"Expected many Right channel events, got {len(right_trace)}" + + # Verify timestamps are spread out (not all the same) + left_timestamps = [ts for ts, _ in left_trace] + assert left_timestamps[-1] > left_timestamps[1], "Timestamps should increase over time" + time_span_ns = left_timestamps[-1] - left_timestamps[1] + # We play for 0.5s, so span should be at least 100ms + assert time_span_ns > 100_000_000, f"Expected >100ms time span, got {time_span_ns / 1e6:.1f}ms" + + # Audio data should contain non-zero values (sine wave) + # Skip the initial zero value + left_values = [v for _, v in left_trace if v != 0] + right_values = [v for _, v in right_trace if v != 0] + assert len(left_values) > 5, "Left channel has too few non-zero values" + assert len(right_values) > 5, "Right channel has too few non-zero values" + + # Sine wave should have both positive and negative values + assert any(v > 0 for v in left_values), "Left channel has no positive values" + assert any(v < 0 for v in left_values), "Left channel has no negative values" + + # Verify amplitude is in the expected range (we generate with amplitude 30000) + max_left = max(left_values) + min_left = min(left_values) + assert max_left > 20000, f"Left max {max_left} too low, expected >20000" + assert min_left < -20000, f"Left min {min_left} too high, expected <-20000" + + # Left and right should match (we write the same value to both channels) + # Compare a subset of matching timestamps + left_by_ts = dict(left_trace) + right_by_ts = dict(right_trace) + common_ts = sorted(set(left_by_ts.keys()) & set(right_by_ts.keys())) + mismatches = 0 + for ts in common_ts[:100]: + if left_by_ts[ts] != right_by_ts[ts]: + mismatches += 1 + assert mismatches == 0, ( + f"{mismatches} L/R mismatches in first {min(100, len(common_ts))} common timestamps" + ) + + +I2S_PLAY_NO_STOP_CODE = """\ +import array +import math +import audiocore +import board +import time + +sample_rate = 16000 +length = sample_rate // 440 +values = [] +for i in range(length): + v = int(math.sin(math.pi * 2 * i / length) * 30000) + values.append(v) + values.append(v) + +sample = audiocore.RawSample( + array.array("h", values), + sample_rate=sample_rate, + channel_count=2, +) + +dac = board.I2SOUT() +dac.play(sample, loop=True) +print("playing") +time.sleep(0.2) +# Exit without calling dac.stop() — reset_port should clean up +print("exiting") +""" + + +@pytest.mark.duration(15) +@pytest.mark.port_resets(3) +@pytest.mark.circuitpy_drive({"code.py": I2S_PLAY_NO_STOP_CODE}) +def test_i2s_stops_on_code_exit(circuitpython): + """Test I2S is stopped by reset_port when code.py exits without explicit stop.""" + # First run: plays audio then exits without stopping + circuitpython.serial.wait_for("exiting") + circuitpython.serial.wait_for("Press any key to enter the REPL") + # Trigger soft reload + circuitpython.serial.write("\x04") + + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + # Should see "playing" and "exiting" at least twice (once per run) + assert output.count("playing") >= 2 + assert output.count("exiting") >= 2 + + +I2S_PAUSE_RESUME_CODE = """\ +import array +import math +import audiocore +import board +import time + +sample_rate = 16000 +length = sample_rate // 440 +values = [] +for i in range(length): + v = int(math.sin(math.pi * 2 * i / length) * 30000) + values.append(v) + values.append(v) + +sample = audiocore.RawSample( + array.array("h", values), + sample_rate=sample_rate, + channel_count=2, +) + +dac = board.I2SOUT() +dac.play(sample, loop=True) +print("playing") +time.sleep(0.2) + +dac.pause() +print("paused") +assert dac.paused +time.sleep(0.1) + +dac.resume() +print("resumed") +assert not dac.paused +time.sleep(0.2) + +dac.stop() +print("done") +""" + + +@pytest.mark.duration(10) +@pytest.mark.circuitpy_drive({"code.py": I2S_PAUSE_RESUME_CODE}) +def test_i2s_pause_resume(circuitpython): + """Test I2SOut pause and resume work correctly.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "playing" in output + assert "paused" in output + assert "resumed" in output + assert "done" in output + + +I2S_PLAY_LOOP_FALSE_CODE = """\ +import array +import math +import audiocore +import board +import time + +# 440 Hz sine, 16-bit signed stereo at 16000 Hz, several periods. +sample_rate = 16000 +length = sample_rate // 440 +periods = 10 +values = [] +for _ in range(periods): + for i in range(length): + v = int(math.sin(math.pi * 2 * i / length) * 30000) + values.append(v) # left + values.append(v) # right + +# Default single_buffer=True: get_buffer returns the whole buffer together with +# GET_BUFFER_DONE on the very first call. With loop=False that buffer used to be +# discarded before being copied, producing silence (issue #10539). +sample = audiocore.RawSample( + array.array("h", values), + sample_rate=sample_rate, + channel_count=2, +) + +dac = board.I2SOUT() +print("playing") +dac.play(sample, loop=False) +time.sleep(0.5) +# Stop explicitly so this test does not depend on `playing` clearing on its own. +dac.stop() +print("done") +""" + + +@pytest.mark.duration(10) +@pytest.mark.circuitpy_drive({"code.py": I2S_PLAY_LOOP_FALSE_CODE}) +def test_i2s_play_non_looping_single_buffer(circuitpython): + """A single-buffer RawSample played with loop=False must be heard, not dropped. + + Regression test for #10539: the final buffer, returned together with + GET_BUFFER_DONE, was discarded before being copied, so a single-buffer + sample (whole buffer + DONE on the first get_buffer call) produced silence. + """ + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "playing" in output + assert "done" in output + + left_trace = parse_i2s_trace(circuitpython.trace_file, "Left") + right_trace = parse_i2s_trace(circuitpython.trace_file, "Right") + + # The sine wave must actually reach the I2S output. On the bug every value is + # zero (silence) because the sole buffer was dropped. + left_values = [v for _, v in left_trace if v != 0] + right_values = [v for _, v in right_trace if v != 0] + assert len(left_values) > 5, "Left channel is silent; non-looping sample was dropped" + assert len(right_values) > 5, "Right channel is silent; non-looping sample was dropped" + + # A sine wave has both positive and negative excursions at the expected amplitude. + assert max(left_values) > 20000, f"Left max {max(left_values)} too low" + assert min(left_values) < -20000, f"Left min {min(left_values)} too high" + + # We wrote the same value to both channels. + left_by_ts = dict(left_trace) + right_by_ts = dict(right_trace) + common_ts = sorted(set(left_by_ts) & set(right_by_ts)) + mismatches = sum(1 for ts in common_ts[:100] if left_by_ts[ts] != right_by_ts[ts]) + assert mismatches == 0, f"{mismatches} L/R mismatches in first common timestamps" diff --git a/ports/zephyr-cp/tests/test_basics.py b/ports/zephyr-cp/tests/test_basics.py new file mode 100644 index 00000000000..f86668d8368 --- /dev/null +++ b/ports/zephyr-cp/tests/test_basics.py @@ -0,0 +1,161 @@ +# SPDX-FileCopyrightText: 2025 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""Test basic native_sim functionality.""" + +import time + +import pytest + + +@pytest.mark.circuitpy_drive(None) +def test_blank_flash_hello_world(board, circuitpython): + """Test that an erased flash shows code.py output header.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert f"Board ID:{board}" in output + assert "UID:" in output + assert "code.py output:" in output + assert "Hello World" in output + assert "done" in output + + +# --- PTY Input Tests --- + + +INPUT_CODE = """\ +import sys + +print("ready") +char = sys.stdin.read(1) +print(f"received: {repr(char)}") +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": INPUT_CODE}) +def test_basic_serial_input(circuitpython): + """Test reading single character from serial via PTY write.""" + circuitpython.serial.wait_for("ready") + circuitpython.serial.write("A") + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "ready" in output + assert "received: 'A'" in output + assert "done" in output + + +INPUT_FUNC_CODE = """\ +print("ready") +name = input("Enter name: ") +print(f"hello {name}") +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": INPUT_FUNC_CODE}) +def test_input_function(circuitpython): + """Test the built-in input() function with PTY input.""" + circuitpython.serial.wait_for("Enter name:") + circuitpython.serial.write("World\r") + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "ready" in output + assert "Enter name:" in output + assert "hello World" in output + assert "done" in output + + +INTERRUPT_CODE = """\ +import time + +print("starting") +for i in range(100): + print(f"loop {i}") + time.sleep(0.1) +print("completed") +""" + + +@pytest.mark.circuitpy_drive({"code.py": INTERRUPT_CODE}) +def test_ctrl_c_interrupt(circuitpython): + """Test sending Ctrl+C (0x03) to interrupt running code.""" + circuitpython.serial.wait_for("loop 5") + circuitpython.serial.write("\x03") + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "starting" in output + assert "loop 5" in output + assert "KeyboardInterrupt" in output + assert "completed" not in output + + +INTERRUPT_SLEEP_CODE = """\ +import time + +print("starting") +time.sleep(30) +print("completed") +""" + + +# Real time so the 30 second sleep would actually take 30 seconds if Ctrl+C +# did not cut it short. +@pytest.mark.circuitpy_drive({"code.py": INTERRUPT_SLEEP_CODE}) +@pytest.mark.native_sim_rt +@pytest.mark.duration(10) +def test_ctrl_c_interrupts_long_sleep(circuitpython): + """Ctrl+C must cut a time.sleep() short instead of waiting it out.""" + circuitpython.serial.wait_for("starting") + # Make sure the VM is inside time.sleep(30) before interrupting it. + time.sleep(0.5) + start = time.monotonic() + circuitpython.serial.write("\x03") + circuitpython.wait_until_done() + elapsed = time.monotonic() - start + + output = circuitpython.serial.all_output + assert "KeyboardInterrupt" in output + assert "completed" not in output + assert elapsed < 5, f"Ctrl+C took {elapsed:.1f}s to interrupt time.sleep(30)" + + +@pytest.mark.circuitpy_drive({"code.py": 'print("spinning")\nwhile True:\n pass\n'}) +@pytest.mark.duration(10) +def test_ctrl_c_after_unread_input(circuitpython): + """Ctrl+C must still interrupt when the console queue is full of unread input.""" + circuitpython.serial.wait_for("spinning") + circuitpython.serial.write("x" * 200) + time.sleep(0.5) + circuitpython.serial.write("\x03") + circuitpython.wait_until_done() + assert "KeyboardInterrupt" in circuitpython.serial.all_output + + +RELOAD_CODE = """\ +print("first run") +import time +time.sleep(1) +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": RELOAD_CODE}) +@pytest.mark.port_resets(3) +def test_ctrl_d_soft_reload(circuitpython): + """Test sending Ctrl+D (0x04) to trigger soft reload.""" + circuitpython.serial.wait_for("first run") + circuitpython.serial.write("\x04") + circuitpython.wait_until_done() + + # Should see "first run" appear multiple times due to reload + # or see a soft reboot message + output = circuitpython.serial.all_output + assert "first run" in output + # The soft reload should restart the code before "done" is printed + assert "done" in output + assert output.count("first run") > 1 diff --git a/ports/zephyr-cp/tests/test_bitbangio.py b/ports/zephyr-cp/tests/test_bitbangio.py new file mode 100644 index 00000000000..1a69a32d5ac --- /dev/null +++ b/ports/zephyr-cp/tests/test_bitbangio.py @@ -0,0 +1,199 @@ +# SPDX-FileCopyrightText: 2026 Dan Halbert for Adafruit Industries LLC +# SPDX-License-Identifier: MIT + +"""Test bitbangio functionality on native_sim. + +I2C is only tested with no device on the bus. gpio_emul has no open-drain +mode, so digitalio emulates it by reconfiguring the pin, which the GPIO trace +does not record. gpio_emul also forces a pulled-up input high on every +reconfigure, so a test can't inject an ACK or clock stretching. +""" + +from pathlib import Path + +import pytest +from perfetto.trace_processor import TraceProcessor + + +def parse_gpio_trace(trace_file: Path, pin_name: str) -> list[tuple[int, int]]: + """Return (timestamp_ns, value) for every change of a GPIO trace track.""" + tp = TraceProcessor(file_path=str(trace_file)) + result = tp.query( + f''' + SELECT c.ts, c.value + FROM counter c + JOIN track t ON c.track_id = t.id + WHERE t.name = "{pin_name}" + ORDER BY c.ts + ''' + ) + return [(row.ts, int(row.value)) for row in result] + + +def value_at(trace: list[tuple[int, int]], ts: int) -> int: + """Return the traced value in effect at ts.""" + value = 0 + for event_ts, event_value in trace: + if event_ts > ts: + break + value = event_value + return value + + +SPI_WRITE_CODE = """\ +import bitbangio +import microcontroller + +spi = bitbangio.SPI( + microcontroller.pin.P_01, MOSI=microcontroller.pin.P_02, MISO=microcontroller.pin.P_03 +) +while not spi.try_lock(): + pass +spi.configure(baudrate=100_000, polarity=0, phase=0) +spi.write(b"\\xa5\\x3c") +spi.unlock() +spi.deinit() +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": SPI_WRITE_CODE}) +def test_bitbangio_spi_write(circuitpython): + """SPI.write() clocks out the bytes MSB first at the configured baudrate.""" + circuitpython.wait_until_done() + assert "done" in circuitpython.serial.all_output + + clock = parse_gpio_trace(circuitpython.trace_file, "gpio_emul.01") + mosi = parse_gpio_trace(circuitpython.trace_file, "gpio_emul.02") + + # (rise, fall) timestamps of each clock pulse, skipping the initial value at ts=0. + pulses = [] + level = 0 + rise = None + for ts, value in clock: + if ts == 0 or value == level: + continue + level = value + if value: + rise = ts + elif rise is not None: + pulses.append((rise, ts)) + assert len(pulses) == 16, f"Expected 16 clock pulses, got {len(pulses)}" + + # Mode 0: MOSI is sampled on the rising edge. + bits = [value_at(mosi, rise) for rise, _ in pulses] + data = bytes(int("".join(str(b) for b in bits[i : i + 8]), 2) for i in (0, 8)) + assert data == b"\xa5\x3c" + + # 100 kHz is a 5 us half period. Without a working common_hal_mcu_delay_us(), + # simulated time would not advance and every edge would share a timestamp. + for rise, fall in pulses: + assert 4_000 <= fall - rise <= 6_000, f"high time {fall - rise} ns" + for (rise1, _), (rise2, _) in zip(pulses[:8], pulses[1:8]): + assert 9_000 <= rise2 - rise1 <= 11_000, f"period {rise2 - rise1} ns" + + +SPI_READ_CODE = """\ +import time +import bitbangio +import microcontroller + +spi = bitbangio.SPI( + microcontroller.pin.P_01, MOSI=microcontroller.pin.P_02, MISO=microcontroller.pin.P_03 +) +while not spi.try_lock(): + pass +spi.configure(baudrate=100_000) +buf = bytearray(2) +spi.readinto(buf) +print("before", buf.hex()) +# The input trace drives MISO high at 3.0 s. +time.sleep(4.0) +spi.readinto(buf) +print("after", buf.hex()) +spi.unlock() +spi.deinit() +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": SPI_READ_CODE}) +@pytest.mark.input_trace({"gpio_emul.03": [(3_000_000_000, 1)]}) +def test_bitbangio_spi_readinto(circuitpython): + """SPI.readinto() samples the MISO pin.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "before 0000" in output + assert "after ffff" in output + assert "done" in output + + +I2C_CODE = """\ +import bitbangio +import microcontroller + +i2c = bitbangio.I2C(microcontroller.pin.P_04, microcontroller.pin.P_05, frequency=100_000) +while not i2c.try_lock(): + pass +print("scan", i2c.scan()) +try: + i2c.writeto(0x26, b"\\x01") + print("writeto succeeded") +except OSError as e: + print("writeto OSError", e.errno) +i2c.unlock() +i2c.deinit() +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": I2C_CODE}) +def test_bitbangio_i2c_no_device(circuitpython): + """With nothing on the bus, every address NACKs.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "scan []" in output + # MP_ENODEV + assert "writeto OSError 19" in output + assert "done" in output + + +DEINIT_THEN_GC_CODE = """\ +import gc +import bitbangio +import digitalio +import microcontroller + +p = microcontroller.pin +spi = bitbangio.SPI(p.P_01, MOSI=p.P_02, MISO=p.P_03) +spi.deinit() +# The I2C pin objects can reuse the blocks the SPI freed. +i2c = bitbangio.I2C(p.P_04, p.P_05) +spi = None +# Runs the SPI's finaliser, which calls deinit() again. +gc.collect() +try: + digitalio.DigitalInOut(p.P_04) + print("P_04 released") +except ValueError: + print("P_04 still claimed") +i2c.try_lock() +print("scan", i2c.scan()) +i2c.unlock() +i2c.deinit() +i2c.deinit() +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": DEINIT_THEN_GC_CODE}) +def test_bitbangio_finaliser_after_deinit(circuitpython): + """A finaliser running after deinit() leaves other objects' pins alone.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "P_04 still claimed" in output + assert "scan []" in output + assert "done" in output diff --git a/ports/zephyr-cp/tests/test_bitmaptools.py b/ports/zephyr-cp/tests/test_bitmaptools.py new file mode 100644 index 00000000000..6473aead8d9 --- /dev/null +++ b/ports/zephyr-cp/tests/test_bitmaptools.py @@ -0,0 +1,106 @@ +# SPDX-FileCopyrightText: 2026 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""bitmaptools writes to a Bitmap that a TileGrid is showing. + +bitmaptools writes pixels directly and then reports the changed rectangle through the +Bitmap dirty API. Both compositors have to pick that rectangle up and redraw the part of +the TileGrid it reaches. +""" + +import pytest +from PIL import Image + +_SCENE = """\ +import board +import bitmaptools +import displayio +import time + +display = board.DISPLAY + +palette = displayio.Palette(4) +palette[0] = 0x000000 +palette[1] = 0xFF0000 +palette[2] = 0x00FF00 +palette[3] = 0x0000FF + +bitmap = displayio.Bitmap(40, 40, 4) +bitmap.fill(0) + +group = displayio.Group() +group.append(displayio.TileGrid(bitmap, pixel_shader=palette, x=40, y=40)) + +display.auto_refresh = False +display.root_group = group +display.refresh() +print('first') +time.sleep(10) + +# A filled rectangle, a line and a blit. Each reports its changed area before it +# writes the pixels, as bitmaptools does. +bitmaptools.fill_region(bitmap, 0, 0, 20, 10, 1) +bitmaptools.draw_line(bitmap, 0, 20, 39, 20, 2) +source = displayio.Bitmap(10, 10, 4) +source.fill(3) +bitmaptools.blit(bitmap, source, x=25, y=25) +display.refresh() +print('second') +while True: + time.sleep(1) +""" + +RED = (255, 0, 0) +GREEN = (0, 255, 0) +BLUE = (0, 0, 255) +BLACK = (0, 0, 0) + + +def _expected(width, height, changed): + frame = [[BLACK] * width for _ in range(height)] + if not changed: + return frame + # fill_region(bitmap, 0, 0, 20, 10, 1) + for y in range(40, 50): + for x in range(40, 60): + frame[y][x] = RED + # draw_line(bitmap, 0, 20, 39, 20, 2) + for x in range(40, 80): + frame[60][x] = GREEN + # blit(bitmap, source, x=25, y=25) + for y in range(65, 75): + for x in range(65, 75): + frame[y][x] = BLUE + return frame + + +def _compare(path, changed): + with Image.open(path) as img: + rgb = img.convert("RGB") + expected = _expected(rgb.width, rgb.height, changed) + mismatches = [] + for y in range(rgb.height): + for x in range(rgb.width): + actual = rgb.getpixel((x, y)) + if actual != expected[y][x]: + mismatches.append((x, y, expected[y][x], actual)) + assert not mismatches, f"{len(mismatches)} pixels differ, first: {mismatches[:8]}" + + +@pytest.mark.circuitpy_drive({"code.py": _SCENE}) +@pytest.mark.display(capture_times_ns=[8_000_000_000, 20_000_000_000]) +@pytest.mark.duration(24) +def test_bitmaptools_render(board, circuitpython): + """bitmaptools changes on a displayed Bitmap reach both compositors.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "first" in output + assert "second" in output + + captures = circuitpython.display_capture_paths() + if len(captures) < 2 or not captures[1].exists(): + pytest.skip("display capture was not produced") + + _compare(captures[0], changed=False) + _compare(captures[1], changed=True) diff --git a/ports/zephyr-cp/tests/test_busio_uart.py b/ports/zephyr-cp/tests/test_busio_uart.py new file mode 100644 index 00000000000..b8a9cc32756 --- /dev/null +++ b/ports/zephyr-cp/tests/test_busio_uart.py @@ -0,0 +1,28 @@ +# SPDX-FileCopyrightText: 2026 Mikey Sklar for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""busio.UART on native_sim, through board.UART() on the second PTY UART.""" + +import pytest + +TIMEOUT_CODE = """\ +import board + +uart = board.UART() +for t in (0.5, 2, 0): + uart.timeout = t + print("timeout", uart.timeout) +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": TIMEOUT_CODE}) +def test_uart_timeout_reads_back_in_seconds(circuitpython): + """timeout reads back the seconds it was set to, not raw kernel ticks.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "timeout 0.5" in output + assert "timeout 2.0" in output + assert "timeout 0.0" in output + assert "done" in output diff --git a/ports/zephyr-cp/tests/test_digitalio.py b/ports/zephyr-cp/tests/test_digitalio.py new file mode 100644 index 00000000000..22c64f7b83f --- /dev/null +++ b/ports/zephyr-cp/tests/test_digitalio.py @@ -0,0 +1,171 @@ +# SPDX-FileCopyrightText: 2026 Scott Shawcroft for Adafruit Industries LLC +# SPDX-License-Identifier: MIT + +"""Test digitalio functionality on native_sim.""" + +import re +from pathlib import Path + +import pytest +from perfetto.trace_processor import TraceProcessor + + +DIGITALIO_INPUT_TRACE_READ_CODE = """\ +import time +import digitalio +import microcontroller + +pin = digitalio.DigitalInOut(microcontroller.pin.P_01) +pin.direction = digitalio.Direction.INPUT + +start = time.monotonic() +last = pin.value +print(f"t_abs={time.monotonic():.3f} initial={last}") + +# Poll long enough to observe a high pulse injected through input trace. +while time.monotonic() - start < 8.0: + value = pin.value + if value != last: + print(f"t_abs={time.monotonic():.3f} edge={value}") + last = value + time.sleep(0.05) + +print(f"t_abs={time.monotonic():.3f} done") +""" + + +DIGITALIO_INPUT_TRACE = { + "gpio_emul.01": [ + (8_000_000_000, 0), + (9_000_000_000, 1), + (10_000_000_000, 0), + ], +} + + +@pytest.mark.duration(14.0) +@pytest.mark.circuitpy_drive({"code.py": DIGITALIO_INPUT_TRACE_READ_CODE}) +@pytest.mark.input_trace(DIGITALIO_INPUT_TRACE) +def test_digitalio_reads_input_trace(circuitpython): + """Test DigitalInOut input reads values injected via input trace.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + + initial_match = re.search(r"t_abs=([0-9]+\.[0-9]+) initial=False", output) + edge_match = re.search(r"t_abs=([0-9]+\.[0-9]+) edge=True", output) + done_match = re.search(r"t_abs=([0-9]+\.[0-9]+) done", output) + + assert initial_match is not None + assert edge_match is not None + assert done_match is not None + + initial_abs = float(initial_match.group(1)) + edge_abs = float(edge_match.group(1)) + done_abs = float(done_match.group(1)) + + # Input trace edge is at 9.0s for gpio_emul.01. + assert 8.5 <= edge_abs <= 9.5 + assert initial_abs <= edge_abs <= done_abs + + +BLINK_CODE = """\ +import time +import board +import digitalio + +led = digitalio.DigitalInOut(board.LED) +led.direction = digitalio.Direction.OUTPUT + +for i in range(3): + print(f"LED on {i}") + led.value = True + time.sleep(0.1) + print(f"LED off {i}") + led.value = False + time.sleep(0.1) + +print("done") +""" + + +def parse_gpio_trace(trace_file: Path, pin_name: str = "gpio_emul.00") -> list[tuple[int, int]]: + """Parse GPIO trace from Perfetto trace file.""" + tp = TraceProcessor(file_path=str(trace_file)) + result = tp.query( + f''' + SELECT c.ts, c.value + FROM counter c + JOIN track t ON c.track_id = t.id + WHERE t.name = "{pin_name}" + ORDER BY c.ts + ''' + ) + return [(row.ts, int(row.value)) for row in result] + + +@pytest.mark.circuitpy_drive({"code.py": BLINK_CODE}) +def test_digitalio_blink_output(circuitpython): + """Test blink program produces expected output and GPIO traces.""" + circuitpython.wait_until_done() + + # Check serial output + output = circuitpython.serial.all_output + assert "LED on 0" in output + assert "LED off 0" in output + assert "LED on 2" in output + assert "LED off 2" in output + assert "done" in output + + # Check GPIO traces - LED is on gpio_emul.00 + gpio_trace = parse_gpio_trace(circuitpython.trace_file, "gpio_emul.00") + + # Deduplicate by timestamp (keep last value at each timestamp) + by_timestamp = {} + for ts, val in gpio_trace: + by_timestamp[ts] = val + sorted_trace = sorted(by_timestamp.items()) + + # Find transition points (where value changes), skipping initialization at ts=0 + transitions = [] + for i in range(1, len(sorted_trace)): + prev_ts, prev_val = sorted_trace[i - 1] + curr_ts, curr_val = sorted_trace[i] + if prev_val != curr_val and curr_ts > 0: + transitions.append((curr_ts, curr_val)) + + # We expect at least 6 transitions (3 on + 3 off) from the blink loop + assert len(transitions) >= 6, f"Expected at least 6 transitions, got {len(transitions)}" + + # Verify timing between consecutive transitions + # Each sleep is 0.1s = 100ms = 100,000,000 ns + expected_interval_ns = 100_000_000 + tolerance_ns = 20_000_000 # 20ms tolerance + + # Find a sequence of 6 consecutive transitions with ~100ms intervals (the blink loop) + # This filters out initialization and cleanup noise + blink_transitions = [] + for i in range(len(transitions) - 1): + interval = transitions[i + 1][0] - transitions[i][0] + if abs(interval - expected_interval_ns) < tolerance_ns: + if not blink_transitions: + blink_transitions.append(transitions[i]) + blink_transitions.append(transitions[i + 1]) + elif blink_transitions: + # Found end of blink sequence + break + + assert len(blink_transitions) >= 6, ( + f"Expected at least 6 blink transitions with ~100ms intervals, got {len(blink_transitions)}" + ) + + # Verify timing between blink transitions + for i in range(1, min(6, len(blink_transitions))): + prev_ts = blink_transitions[i - 1][0] + curr_ts = blink_transitions[i][0] + interval = curr_ts - prev_ts + assert abs(interval - expected_interval_ns) < tolerance_ns, ( + f"Transition interval {interval / 1_000_000:.1f}ms deviates from " + f"expected {expected_interval_ns / 1_000_000:.1f}ms by more than " + f"{tolerance_ns / 1_000_000:.1f}ms tolerance" + ) diff --git a/ports/zephyr-cp/tests/test_displayio_background.py b/ports/zephyr-cp/tests/test_displayio_background.py new file mode 100644 index 00000000000..f1563e619a1 --- /dev/null +++ b/ports/zephyr-cp/tests/test_displayio_background.py @@ -0,0 +1,89 @@ +# SPDX-FileCopyrightText: 2026 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""The undrawn display background is black, including after a display is re-created. + +LVGL fills its bottom layer with white wherever nothing else covers an area, so +the LVGL compositor makes each display's screen opaque black. That setup used +to run once, for whichever screen existed at the time. Display classes +(BusDisplay, FramebufferDisplay) delete and re-create the LVGL display when +they are constructed, so the screen of the next one came up white. + +This draws a red square on a black screen, releases the display, creates a new +one and draws the same scene again, then checks a captured frame from each +display. A compositor that doesn't style the re-created screen fails on the +second capture. +""" + +import pytest +from PIL import Image + + +BACKGROUND_CODE = """\ +import board +import displayio +import time +import zephyr_display + + +def draw(display): + # A 16-bit bitmap needs no palette, so the square shows the same color before + # and after the display is re-created. + bitmap = displayio.Bitmap(8, 8, 65536) + for y in range(8): + for x in range(8): + bitmap[x, y] = 0xF800 + group = displayio.Group() + group.append(displayio.TileGrid(bitmap, + pixel_shader=displayio.ColorConverter(input_colorspace=displayio.Colorspace.RGB565), + x=16, y=16)) + display.auto_refresh = False + display.root_group = group + display.refresh() + + +display = board.DISPLAY +draw(display) +print('first') +time.sleep(10) + +displayio.release_displays() +display = zephyr_display.Display(auto_refresh=False) +draw(display) +print('second') + +while True: + time.sleep(1) +""" + + +def _assert_black_background(path, index): + with Image.open(path) as img: + rgb = img.convert("RGB") + background = rgb.getpixel((0, 0)) + assert background == (0, 0, 0), ( + f"capture {index}: undrawn background is {background}, expected black" + ) + square = rgb.getpixel((16, 16)) + assert square == (255, 0, 0), ( + f"capture {index}: the TileGrid didn't draw at (16, 16): got {square}" + ) + + +@pytest.mark.circuitpy_drive({"code.py": BACKGROUND_CODE}) +@pytest.mark.display(capture_times_ns=[6_000_000_000, 16_000_000_000]) +@pytest.mark.duration(20) +def test_background_is_black_after_display_recreate(circuitpython): + """A re-created display still has a black background.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "first" in output + assert "second" in output + + captures = circuitpython.display_capture_paths() + if len(captures) < 2 or not captures[1].exists(): + pytest.skip("display capture was not produced") + + _assert_black_background(captures[0], 0) + _assert_black_background(captures[1], 1) diff --git a/ports/zephyr-cp/tests/test_displayio_fractional.py b/ports/zephyr-cp/tests/test_displayio_fractional.py new file mode 100644 index 00000000000..669b55e3208 --- /dev/null +++ b/ports/zephyr-cp/tests/test_displayio_fractional.py @@ -0,0 +1,258 @@ +# SPDX-FileCopyrightText: 2026 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""Fractional Group scaling in the LVGL compositor.""" + +import pytest +from PIL import Image + + +FRACTIONAL_SCENE = """\ +import board +import displayio +import time + +minimum = displayio.Group(scale=1 / 256) +assert minimum.scale == 1 / 256 +minimum.scale = 1 +minimum.scale = 1 / 256 +assert minimum.scale == 1 / 256 +requested = displayio.Group(scale=1.1) +assert requested.scale == 1.1 +# Readback follows sub-Q8 changes too, so animations cannot stick at one step. +next_scale = 1.1 + 1 / 4096 +requested.scale = next_scale +assert requested.scale == next_scale +try: + displayio.Group(scale=1 / 512) +except ValueError: + pass +else: + raise AssertionError('constructor accepted scale below Q8 minimum') +try: + minimum.scale = 1 / 512 +except ValueError: + pass +else: + raise AssertionError('setter accepted scale below Q8 minimum') + +palette = displayio.Palette(4) +palette[0] = 0xFF0000 +palette[1] = 0x00FF00 +palette[2] = 0x00FF00 +palette[3] = 0xFFFFFF +checker = displayio.Bitmap(4, 4, 4) +for y in range(4): + for x in range(4): + checker[x, y] = 1 if (x + y) % 2 else 2 + +outer = displayio.Group(scale=1.25, x=11, y=17) +inner = displayio.Group(scale=1.2, x=2, y=1) +inner.append(displayio.TileGrid(checker, pixel_shader=palette)) +outer.append(inner) +assert outer.scale == 1.25 +assert inner.scale == 1.2 + +rgb565 = displayio.Bitmap(4, 4, 65536) +for y in range(4): + for x in range(4): + rgb565[x, y] = 0xF800 if x < 2 else 0x07E0 +converter = displayio.ColorConverter(input_colorspace=displayio.Colorspace.RGB565) +direct = displayio.TileGrid(rgb565, pixel_shader=converter, x=30, y=0) +outer.append(direct) + +root = displayio.Group() +root.append(outer) +display = board.DISPLAY +display.auto_refresh = False +display.root_group = root +display.refresh() +print('first') +time.sleep(5) + +# Exercise a live scale change, movement, palette update and direct-pixel update. +inner.scale = 1.25 +assert inner.scale == 1.25 +inner.x = 3 +palette[1] = 0xFF00FF +palette[2] = 0xFF00FF +rgb565[0, 0] = 0x001F +display.refresh() +print('second') +while True: + time.sleep(1) +""" + +RED = (255, 0, 0) +GREEN = (0, 255, 0) +BLUE = (0, 0, 255) +MAGENTA = (255, 0, 255) +BLACK = (0, 0, 0) + + +def _expected(width, height, changed): + frame = Image.new("RGB", (width, height), BLACK) + inner_scale = 400 if changed else 384 # Q8: 1.25 * 1.25 or 1.25 * 1.2 + + def draw(x0, y0, scale, color_at): + # CircuitPython duplicates the bottom/right source pixels into one + # pixel of padding, so LVGL's center-based extent includes the edges. + w = (4 * scale + 128) // 256 + h = w + for y in range(h): + for x in range(w): + sx = x * 256 // scale + sy = y * 256 // scale + frame.putpixel((x0 + x, y0 + y), color_at(sx, sy)) + + inner_x = 11 + ((3 if changed else 2) * 320 + 128) // 256 + inner_y = 17 + (320 + 128) // 256 + draw(inner_x, inner_y, inner_scale, lambda x, y: MAGENTA if changed else GREEN) + + direct_x = 11 + (30 * 320 + 128) // 256 + draw( + direct_x, + 17, + 320, + lambda x, y: BLUE if changed and (x, y) == (0, 0) else RED if x < 2 else GREEN, + ) + return frame + + +@pytest.mark.parametrize( + "board", ["native_native_sim_lvgl", "native_native_sim_lvgl_asan"], indirect=True +) +@pytest.mark.circuitpy_drive({"code.py": FRACTIONAL_SCENE}) +@pytest.mark.display(capture_times_ns=[4_000_000_000, 9_000_000_000]) +@pytest.mark.duration(11) +def test_displayio_fractional_group(circuitpython): + """Fractional Q8 scales render and invalidate indexed/direct TileGrids.""" + circuitpython.wait_until_done() + output = circuitpython.serial.all_output + assert "first" in output + assert "second" in output + + captures = circuitpython.display_capture_paths() + if len(captures) < 2 or not captures[1].exists(): + pytest.skip("display capture was not produced") + + for path, changed in ((captures[0], False), (captures[1], True)): + with Image.open(path) as image: + actual = image.convert("RGB") + expected = _expected(actual.width, actual.height, changed) + mismatches = [] + for y in range(actual.height): + for x in range(actual.width): + if actual.getpixel((x, y)) != expected.getpixel((x, y)): + mismatches.append((x, y, expected.getpixel((x, y)), actual.getpixel((x, y)))) + assert not mismatches, f"{len(mismatches)} pixels differ, first: {mismatches[:8]}" + + with Image.open(captures[0]) as image: + first_direct_pixel = image.convert("RGB").getpixel((49, 17)) + with Image.open(captures[1]) as image: + second_direct_pixel = image.convert("RGB").getpixel((49, 17)) + assert first_direct_pixel != BLACK + assert second_direct_pixel != BLACK + assert first_direct_pixel != second_direct_pixel + + +VECTOR_SCENE = """\ +import board +import displayio +import time +import vectorio + +palette = displayio.Palette(3) +palette[0] = 0x000000 +palette[1] = 0x00FF00 +palette[2] = 0x0000FF + +group = displayio.Group(scale=0.5, x=10, y=20) +rectangle = vectorio.Rectangle(pixel_shader=palette, width=8, height=4, color_index=1) +polygon = vectorio.Polygon(pixel_shader=palette, points=[(0, 0), (7, 0), (0, 3)], + x=12, color_index=2) +group.append(rectangle) +group.append(polygon) +root = displayio.Group() +root.append(group) + +assert rectangle.contains(10, 20) +assert rectangle.contains(13, 21) +assert not rectangle.contains(14, 20) + +display = board.DISPLAY +display.auto_refresh = False +display.root_group = root +display.refresh() +print('first') +time.sleep(5) + +# Exercise both the style-drawn shape and the polygon mask at a new fractional scale. +group.scale = 1.5 +assert rectangle.contains(21, 25) +assert not rectangle.contains(22, 20) +display.refresh() +print('second') +while True: + time.sleep(1) +""" + + +def _polygon_covered(x, y): + points = ((0, 0), (7, 0), (0, 3)) + winding = 0 + x1, y1 = points[0] + for x2, y2 in points[1:] + points[:1]: + side = (x - x1) * (y2 - y1) - (y - y1) * (x2 - x1) + if y1 <= y: + if y2 > y and side < 0: + winding += 1 + elif y2 <= y and side > 0: + winding -= 1 + x1, y1 = x2, y2 + return winding != 0 + + +def _expected_vectors(scale): + frame = Image.new("RGB", (320, 240), BLACK) + scale_q8 = int(scale * 256) + + def scaled(value): + return (value * scale_q8 + 128) // 256 + + for y in range(scaled(4)): + for x in range(scaled(8)): + frame.putpixel((10 + x, 20 + y), GREEN) + + polygon_x = 10 + scaled(12) + for y in range(scaled(4)): + source_y = y * 256 // scale_q8 + for x in range(scaled(8)): + source_x = x * 256 // scale_q8 + if _polygon_covered(source_x, source_y): + frame.putpixel((polygon_x + x, 20 + y), BLUE) + return frame + + +@pytest.mark.parametrize( + "board", ["native_native_sim_lvgl", "native_native_sim_lvgl_asan"], indirect=True +) +@pytest.mark.circuitpy_drive({"code.py": VECTOR_SCENE}) +@pytest.mark.display(capture_times_ns=[4_000_000_000, 9_000_000_000]) +@pytest.mark.duration(11) +def test_displayio_fractional_vector_shapes(circuitpython): + """Fractional scales work for style-drawn shapes and polygon masks.""" + circuitpython.wait_until_done() + output = circuitpython.serial.all_output + assert "first" in output + assert "second" in output + + captures = circuitpython.display_capture_paths() + if len(captures) < 2 or not captures[1].exists(): + pytest.skip("display capture was not produced") + + for path, scale in ((captures[0], 0.5), (captures[1], 1.5)): + with Image.open(path) as image: + actual = image.convert("RGB") + expected = _expected_vectors(scale) + assert actual.tobytes() == expected.tobytes() diff --git a/ports/zephyr-cp/tests/test_displayio_group.py b/ports/zephyr-cp/tests/test_displayio_group.py new file mode 100644 index 00000000000..8cc538b98f8 --- /dev/null +++ b/ports/zephyr-cp/tests/test_displayio_group.py @@ -0,0 +1,135 @@ +# SPDX-FileCopyrightText: 2026 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""Integer Group scaling in the LVGL compositor.""" + +import pytest +from PIL import Image + + +GROUP_SCALE_SCENE = """\ +import board +import displayio +import time + +palette = displayio.Palette(4) +palette[0] = 0x000000 +palette[1] = 0xFF0000 +palette[2] = 0x00FF00 +palette[3] = 0x0000FF + + +def solid(width, height, color_index): + bitmap = displayio.Bitmap(width, height, 4) + for y in range(height): + for x in range(width): + bitmap[x, y] = color_index + return bitmap + + +root = displayio.Group() + +# A default Group must retain 1x scale. Q8 conversion must not be applied twice +# to a Group that has already been through the Python constructor. +default = displayio.Group(x=5, y=7) +default.append(displayio.TileGrid(solid(4, 3, 1), pixel_shader=palette)) +root.append(default) + +# Integer scaling must produce whole pixels without resampling. +scaled = displayio.Group(scale=2, x=20, y=5) +scaled.append(displayio.TileGrid(solid(2, 2, 2), pixel_shader=palette)) +root.append(scaled) + +display = board.DISPLAY +display.auto_refresh = False +display.root_group = root +display.refresh() + +# Append after the Group is attached to exercise the adoption path separately +# from the root-attachment path used above. +scaled.append(displayio.TileGrid(solid(2, 1, 3), pixel_shader=palette, x=4, y=0)) +display.refresh() +print('ready') + +while True: + time.sleep(1) +""" + + +@pytest.mark.parametrize( + "board", ["native_native_sim_lvgl", "native_native_sim_lvgl_asan"], indirect=True +) +@pytest.mark.circuitpy_drive({"code.py": GROUP_SCALE_SCENE}) +@pytest.mark.display(capture_times_ns=[4_000_000_000]) +@pytest.mark.duration(7) +def test_displayio_integer_group_scale(circuitpython): + """Default, integer and post-attachment Group scales retain all pixels.""" + circuitpython.wait_until_done() + assert "ready" in circuitpython.serial.all_output + + captures = circuitpython.display_capture_paths() + if not captures or not captures[0].exists(): + pytest.skip("display capture was not produced") + + with Image.open(captures[0]) as image: + actual = image.convert("RGB") + expected = Image.new("RGB", actual.size, (0, 0, 0)) + + def draw(x0, y0, width, height, color): + for y in range(y0, y0 + height): + for x in range(x0, x0 + width): + expected.putpixel((x, y), color) + + draw(5, 7, 4, 3, (255, 0, 0)) + draw(20, 5, 4, 4, (0, 255, 0)) + draw(28, 5, 4, 2, (0, 0, 255)) + + mismatches = [] + for y in range(actual.height): + for x in range(actual.width): + actual_pixel = actual.getpixel((x, y)) + expected_pixel = expected.getpixel((x, y)) + if actual_pixel != expected_pixel: + mismatches.append((x, y, expected_pixel, actual_pixel)) + assert not mismatches, f"{len(mismatches)} pixels differ, first: {mismatches[:8]}" + + +SUPERVISOR_SPLASH_SCENE = """\ +import time + +# Leave the supervisor's static splash Group attached. In particular, don't replace +# it with a Python-created Group, whose constructor already converts scale to Q8. +while True: + time.sleep(1) +""" + + +@pytest.mark.parametrize( + "board", ["native_native_sim_lvgl", "native_native_sim_lvgl_asan"], indirect=True +) +@pytest.mark.circuitpy_drive({"code.py": SUPERVISOR_SPLASH_SCENE}) +@pytest.mark.display(capture_times_ns=[4_000_000_000]) +@pytest.mark.duration(7) +def test_supervisor_splash_group_scale(circuitpython): + """The static supervisor splash renders Blinka at native_sim's 1x scale.""" + circuitpython.wait_until_done() + captures = circuitpython.display_capture_paths() + if not captures or not captures[0].exists(): + pytest.skip("display capture was not produced") + + with Image.open(captures[0]) as image: + actual = image.convert("RGB") + + # Blinka is a 12x12 TileGrid in the static splash Group. Native_sim selects + # scale 1 for its 320-pixel display. A raw 1 was interpreted as Q8 1 / 256 + # and clipped the grid to zero size. Use Blinka's unique chromatic colors so + # white terminal text in the same region cannot make this test pass. + logo = [] + for y in range(24): + for x in range(24): + pixel = actual.getpixel((x, y)) + if pixel not in ((0, 0, 0), (255, 255, 255)): + logo.append((x, y)) + assert len(logo) > 50, "the supervisor splash is missing Blinka's colored pixels" + assert max(x for x, y in logo) == 11, "Blinka has the wrong horizontal extent" + assert max(y for x, y in logo) == 11, "Blinka has the wrong vertical extent" diff --git a/ports/zephyr-cp/tests/test_displayio_lvgl_dirty.py b/ports/zephyr-cp/tests/test_displayio_lvgl_dirty.py new file mode 100644 index 00000000000..9122eef163c --- /dev/null +++ b/ports/zephyr-cp/tests/test_displayio_lvgl_dirty.py @@ -0,0 +1,74 @@ +# SPDX-FileCopyrightText: 2026 Mikey Sklar for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +"""How much of the screen the LVGL compositor redraws for a bitmap change.""" + +import re + +import pytest + + +@pytest.fixture +def board(): + return "native_native_sim_lvgl" + + +DIRTY_CODE = """\ +import bitmaptools +import board +import displayio + +display = board.DISPLAY +display.auto_refresh = False +print("size", display.width, display.height) + +for kind in ("rgb565", "palette"): + if kind == "rgb565": + bitmap = displayio.Bitmap(display.width, display.height, 65535) + shader = displayio.ColorConverter(input_colorspace=displayio.Colorspace.RGB565) + else: + bitmap = displayio.Bitmap(display.width, display.height, 256) + shader = displayio.Palette(256) + group = displayio.Group() + group.append(displayio.TileGrid(bitmap, pixel_shader=shader)) + display.root_group = group + display.refresh() + + bitmap[10, 20] = 1 + display.refresh() + + bitmaptools.fill_region(bitmap, 100, 50, 120, 70, 2) + display.refresh() + + for i in range(40): + bitmap[200 + i, 100 + i] = 3 + display.refresh() + print("done", kind) +""" + + +def _dirty_areas(output): + return [ + tuple(int(v) for v in m) for m in re.findall(r"lvgl dirty (\d+) (\d+) (\d+) (\d+)", output) + ] + + +@pytest.mark.circuitpy_drive({"code.py": DIRTY_CODE}) +@pytest.mark.duration(15) +def test_bitmap_writes_redraw_only_what_changed(circuitpython): + """One-cell TileGrids redraw only the written pixels, for direct and composed sources.""" + circuitpython.wait_until_done() + output = circuitpython.serial.all_output + assert "done rgb565" in output + assert "done palette" in output + width, height = (int(v) for v in re.search(r"size (\d+) (\d+)", output).groups()) + + areas = _dirty_areas(circuitpython.debug_serial.all_output) + # Per source kind: showing the group redraws the whole screen, then one pixel, a 20x20 + # square, and a diagonal of 40 single-pixel writes redrawn as its bounding box. + screen = (0, 0, width - 1, height - 1) + expected = [screen, (10, 20, 10, 20), (100, 50, 119, 69), (200, 100, 239, 139)] * 2 + assert any(areas[i : i + len(expected)] == expected for i in range(len(areas))), ( + f"expected {expected} in {areas}" + ) diff --git a/ports/zephyr-cp/tests/test_displayio_lvgl_lifecycle.py b/ports/zephyr-cp/tests/test_displayio_lvgl_lifecycle.py new file mode 100644 index 00000000000..e89c55f2d80 --- /dev/null +++ b/ports/zephyr-cp/tests/test_displayio_lvgl_lifecycle.py @@ -0,0 +1,355 @@ +# SPDX-FileCopyrightText: 2026 Scott Shawcroft for Adafruit Industries +# +# SPDX-License-Identifier: MIT + +"""LVGL allocation lifetimes, including recovery from allocation/validation failures.""" + +import pytest +from PIL import Image + + +@pytest.fixture(params=["native_native_sim_lvgl", "native_native_sim_lvgl_asan"]) +def board(request): + return request.param + + +def _pixel(path, xy): + assert path.exists(), f"display capture missing: {path}" + with Image.open(path) as image: + return image.convert("RGB").getpixel(xy) + + +POLYGON_OOM_CODE = """\ +import board +import displayio +import time +import vectorio + +display = board.DISPLAY +display.auto_refresh = False +palette = displayio.Palette(1) +palette[0] = 0xffffff +polygon = vectorio.Polygon(pixel_shader=palette, + points=[(0, 0), (4, 0), (0, 4)], x=20, y=20) +group = displayio.Group() +group.append(polygon) +display.root_group = group +display.refresh() +# A 6001x6001 A8 mask cannot fit in the native LVGL board's 16 MiB heap. +# The old mask must no longer be the image source if its replacement fails. +polygon.points = [(0, 0), (6000, 0), (0, 6000)] +display.refresh() +print('oom refresh survived') +time.sleep(10) +polygon.points = [(0, 0), (4, 0), (0, 4)] +display.refresh() +print('mask recovered') +while True: + time.sleep(1) +""" + + +@pytest.mark.circuitpy_drive({"code.py": POLYGON_OOM_CODE}) +@pytest.mark.display(capture_times_ns=[6_000_000_000, 16_000_000_000]) +@pytest.mark.duration(20) +def test_polygon_mask_allocation_failure(circuitpython): + circuitpython.wait_until_done() + assert "oom refresh survived" in circuitpython.serial.all_output + assert "mask recovered" in circuitpython.serial.all_output + before, after = circuitpython.display_capture_paths() + assert _pixel(before, (21, 21)) == (0, 0, 0) + assert _pixel(after, (21, 21)) == (255, 255, 255) + + +BITMAP_DEINIT_CODE = """\ +import board +import displayio +import time + +display = board.DISPLAY +display.auto_refresh = False +group = displayio.Group() +bitmaps = [] +# Exercise direct sources, converted/cached sources and composed indexed sources. +for i, colorspace in enumerate((displayio.Colorspace.RGB565, + displayio.Colorspace.RGB565_SWAPPED, None)): + bitmap = displayio.Bitmap(64, 64, 2 if colorspace is None else 65536) + if colorspace is None: + shader = displayio.Palette(2) + shader[1] = 0xff0000 + bitmap.fill(1) + else: + shader = displayio.ColorConverter(input_colorspace=colorspace) + bitmap.fill(0xf800 if i == 0 else 0x00f8) + bitmaps.append(bitmap) + group.append(displayio.TileGrid(bitmap, pixel_shader=shader, x=i * 80)) +display.root_group = group +display.refresh() +time.sleep(10) +for bitmap in bitmaps: + bitmap.deinit() + bitmap.deinit() # teardown is idempotent +# Reuse freed GC storage: a stale direct source would now show someone else's pixels. +reused = [displayio.Bitmap(64, 64, 65536) for _ in range(4)] +for bitmap in reused: + bitmap.fill(0x07e0) +display.refresh() +print('deinit refreshed') +while True: + time.sleep(1) +""" + + +@pytest.mark.circuitpy_drive({"code.py": BITMAP_DEINIT_CODE}) +@pytest.mark.display(capture_times_ns=[6_000_000_000, 16_000_000_000]) +@pytest.mark.duration(20) +def test_deinitialized_bitmap_drops_borrowed_pixels(circuitpython): + circuitpython.wait_until_done() + assert "deinit refreshed" in circuitpython.serial.all_output + before, after = circuitpython.display_capture_paths() + for x in (1, 81, 161): + assert _pixel(before, (x, 1)) == (255, 0, 0) + assert _pixel(after, (x, 1)) == (0, 0, 0) + + +GROUP_ERROR_CODE = """\ +import board +import displayio +import time + +display = board.DISPLAY +palette = displayio.Palette(1) +palette[0] = 0xff0000 +bitmap = displayio.Bitmap(32, 32, 1) +grid = displayio.TileGrid(bitmap, pixel_shader=palette) +group = displayio.Group() +group.append(grid) +display.root_group = group +display.refresh() +time.sleep(10) +other = displayio.Group() +member = displayio.Group() +other.append(member) +for invalid in (object(), member): + try: + group[0] = invalid + raise AssertionError('assignment should have failed') + except ValueError: + pass + assert group[0] is grid +# Assigning the existing member to itself is a no-op, not a failed adoption. +group[0] = grid +palette[0] = 0x00ff00 +# Do NOT manually refresh: the workqueue must be able to acquire the LVGL mutex. +print('rejected replacements') +while True: + time.sleep(1) +""" + + +@pytest.mark.circuitpy_drive({"code.py": GROUP_ERROR_CODE}) +@pytest.mark.display(capture_times_ns=[6_000_000_000, 16_000_000_000]) +@pytest.mark.duration(20) +def test_failed_group_assignment_preserves_mirror_and_unlocks(circuitpython): + circuitpython.wait_until_done() + assert "rejected replacements" in circuitpython.serial.all_output + before, after = circuitpython.display_capture_paths() + assert _pixel(before, (1, 1)) == (255, 0, 0) + assert _pixel(after, (1, 1)) == (0, 255, 0) + + +DISPLAY_RECREATE_CODE = """\ +import board +import displayio +import gc +import zephyr_display + +display = board.DISPLAY +for i in range(1200): + displayio.release_displays() + display = zephyr_display.Display(auto_refresh=False) + if i % 50 == 0: + gc.collect() +# Leaking one 320x24 RGB565 rendering buffer per recreation exhausts 16 MiB. +group = displayio.Group() +bitmap = displayio.Bitmap(4, 4, 65536) +bitmap.fill(0xf800) +group.append(displayio.TileGrid(bitmap, pixel_shader=displayio.ColorConverter( + input_colorspace=displayio.Colorspace.RGB565))) +display.root_group = group +display.refresh() +print('recreated 1200 displays') +""" + + +@pytest.mark.circuitpy_drive({"code.py": DISPLAY_RECREATE_CODE}) +@pytest.mark.duration(60) +def test_display_recreation_releases_port_allocations(circuitpython): + circuitpython.wait_until_done() + assert "recreated 1200 displays" in circuitpython.serial.all_output + + +TILEGRID_CHURN_CODE = """\ +import board +import displayio +import gc + +display = board.DISPLAY +display.auto_refresh = False +group = displayio.Group() +display.root_group = group +bitmap = displayio.Bitmap(2, 1, 2) +bitmap[1, 0] = 1 +palette = displayio.Palette(2) +palette[1] = 0xff0000 +for i in range(550): + grid = displayio.TileGrid(bitmap, pixel_shader=palette, width=512, height=512, + tile_width=1, tile_height=1) + group.append(grid) + display.refresh() + group.pop() + del grid + gc.collect() +# Each discarded grid used a 32 KiB port-heap dirty-cell bitset. If those leaked, +# the next, larger composed grid cannot allocate its buffer. Same-sized grids +# can still draw with no bitset when that allocation fails, so require more buffer +# space than one iteration did and check pixels, not just that the loop finished. +grid = displayio.TileGrid(bitmap, pixel_shader=palette, width=512, height=1024, + tile_width=1, tile_height=1) +grid[0] = 1 +group.append(grid) +display.refresh() +print('tilegrid churn survived') +import time +while True: + time.sleep(1) +""" + + +@pytest.mark.circuitpy_drive({"code.py": TILEGRID_CHURN_CODE}) +@pytest.mark.display(capture_times_ns=[80_000_000_000]) +@pytest.mark.duration(90) +def test_discarded_tilegrids_release_dirty_cell_bits(circuitpython): + circuitpython.wait_until_done() + assert "tilegrid churn survived" in circuitpython.serial.all_output + (capture,) = circuitpython.display_capture_paths() + assert _pixel(capture, (0, 0)) == (255, 0, 0) + + +DIRECT_UPDATE_CODE = """\ +import board +import displayio +import time + +display = board.DISPLAY +display.auto_refresh = False +bitmap = displayio.Bitmap(16, 16, 65536) +bitmap.fill(0x00f8) # byte-swapped RGB565 red +shader = displayio.ColorConverter(input_colorspace=displayio.Colorspace.RGB565_SWAPPED) +group = displayio.Group() +group.append(displayio.TileGrid(bitmap, pixel_shader=shader)) +display.root_group = group +display.refresh() +time.sleep(10) +bitmap.fill(0xe007) # byte-swapped RGB565 green +display.refresh() +print('direct source updated') +while True: + time.sleep(1) +""" + + +@pytest.mark.circuitpy_drive({"code.py": DIRECT_UPDATE_CODE}) +@pytest.mark.display(capture_times_ns=[6_000_000_000, 16_000_000_000]) +@pytest.mark.duration(20) +def test_direct_source_updates_drop_cached_conversion(circuitpython): + circuitpython.wait_until_done() + assert "direct source updated" in circuitpython.serial.all_output + before, after = circuitpython.display_capture_paths() + assert _pixel(before, (1, 1)) == (255, 0, 0) + assert _pixel(after, (1, 1)) == (0, 255, 0) + + +BUSDISPLAY_CLEANUP_CODE = """\ +import board +import busdisplay +import digitalio +import displayio +import fourwire +from microcontroller import pin + +displayio.release_displays() +bus = fourwire.FourWire(board.SPI(), command=pin.P_10, chip_select=pin.P_11) +# An unsupported format must not leave the static display slot occupied. +try: + busdisplay.BusDisplay(bus, b'', width=32, height=32, color_depth=1) + raise AssertionError('packed format should have been rejected') +except NotImplementedError: + pass +# Buffers for this display exceed the native simulator's 1 MiB port heap. +# This fails after acquiring the backlight and creating an LVGL display. +try: + busdisplay.BusDisplay(bus, b'', width=60000, height=32, color_depth=32, + backlight_pin=pin.P_12, auto_refresh=False) + raise AssertionError('oversized buffers should have been rejected') +except MemoryError: + pass +backlight = digitalio.DigitalInOut(pin.P_12) +backlight.deinit() +# Both the slot and the bus must still be usable after failed construction. +display = busdisplay.BusDisplay(bus, b'', width=32, height=32, + backlight_pin=pin.P_12, auto_refresh=False) +displayio.release_displays() +backlight = digitalio.DigitalInOut(pin.P_12) +backlight.deinit() +print('busdisplay cleanup survived') +""" + + +@pytest.mark.circuitpy_drive({"code.py": BUSDISPLAY_CLEANUP_CODE}) +@pytest.mark.duration(20) +def test_busdisplay_failed_construct_and_release_free_resources(circuitpython): + circuitpython.wait_until_done() + assert "busdisplay cleanup survived" in circuitpython.serial.all_output + + +BUSDISPLAY_ROTATION_CODE = """\ +import board +import busdisplay +import displayio +import fourwire +from microcontroller import pin + +displayio.release_displays() +bus = fourwire.FourWire(board.SPI(), command=pin.P_10, chip_select=pin.P_11) +display = busdisplay.BusDisplay(bus, b'', width=64, height=32, rotation=90, + auto_refresh=False) +print('start', display.width, display.height, display.rotation) + +bitmap = displayio.Bitmap(16, 16, 1) +bitmap.fill(1) +palette = displayio.Palette(1) +palette[0] = 0xff0000 +group = displayio.Group() +group.append(displayio.TileGrid(bitmap, pixel_shader=palette)) +display.root_group = group +display.refresh() + +for rotation in (180, 270, 0): + display.rotation = rotation + display.refresh() + print('rotated', display.width, display.height, display.rotation) +print('busdisplay rotation survived') +""" + + +@pytest.mark.circuitpy_drive({"code.py": BUSDISPLAY_ROTATION_CODE}) +@pytest.mark.duration(20) +def test_busdisplay_rotation_dimensions_and_flush(circuitpython): + circuitpython.wait_until_done() + output = circuitpython.serial.all_output + assert "start 32 64 90" in output + assert "rotated 64 32 180" in output + assert "rotated 32 64 270" in output + assert "rotated 64 32 0" in output + assert "busdisplay rotation survived" in output diff --git a/ports/zephyr-cp/tests/test_displayio_ondiskbitmap.py b/ports/zephyr-cp/tests/test_displayio_ondiskbitmap.py new file mode 100644 index 00000000000..a87e598efd3 --- /dev/null +++ b/ports/zephyr-cp/tests/test_displayio_ondiskbitmap.py @@ -0,0 +1,228 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""OnDiskBitmap rendering on both displayio compositors. + +The BMPs are generated here and copied onto the simulated drive. The expected +frame is computed from the same pixel descriptions, so the legacy scanline +compositor and the LVGL compositor's OnDiskBitmap image decoder are checked +against an independent model. Only fully saturated colors are used so the +result doesn't depend on the display's pixel format. +""" + +import struct + +import pytest +from PIL import Image + +_DISPLAY_HELPER = """\ +import board +display = board.DISPLAY +""" + +_CODE = ( + _DISPLAY_HELPER + + """\ +import displayio +import time + +group = displayio.Group() + +# 8 bit indexed, bottom-up rows. +quad = displayio.OnDiskBitmap('/quad.bmp') +group.append(displayio.TileGrid(quad, pixel_shader=quad.pixel_shader, x=10, y=10)) + +# A sprite sheet with two 4x4 tiles. +sheet = displayio.OnDiskBitmap('/sheet.bmp') +sheet_grid = displayio.TileGrid(sheet, pixel_shader=sheet.pixel_shader, + width=2, height=1, tile_width=4, tile_height=4, x=10, y=40) +sheet_grid[1] = 1 +group.append(sheet_grid) + +# 16 bit 565 with explicit bitfields. +rgb565 = displayio.OnDiskBitmap('/rgb565.bmp') +group.append(displayio.TileGrid(rgb565, pixel_shader=rgb565.pixel_shader, x=40, y=10)) + +# 16 bit 555 (the BI_RGB default). +rgb555 = displayio.OnDiskBitmap('/rgb555.bmp') +group.append(displayio.TileGrid(rgb555, pixel_shader=rgb555.pixel_shader, x=70, y=10)) + +# 24 bit BGR. +rgb888 = displayio.OnDiskBitmap('/rgb888.bmp') +group.append(displayio.TileGrid(rgb888, pixel_shader=rgb888.pixel_shader, x=100, y=10)) + +# 8 bit indexed, top-down rows (negative height). +topdown = displayio.OnDiskBitmap('/topdown.bmp') +group.append(displayio.TileGrid(topdown, pixel_shader=topdown.pixel_shader, x=130, y=10)) + +display.auto_refresh = False +display.root_group = group +display.refresh() +print('first') +time.sleep(10) + +# Palette changes have to reach the image decoder. +quad.pixel_shader[0] = 0xFF00FF +display.refresh() +print('second') +while True: + time.sleep(1) +""" +) + +RED = (255, 0, 0) +GREEN = (0, 255, 0) +BLUE = (0, 0, 255) +WHITE = (255, 255, 255) +MAGENTA = (255, 0, 255) +BLACK = (0, 0, 0) + + +def _bmp(width, height, bpp, rows, palette=None, top_down=False, bitfields=None): + """Build a BMP. rows are top to bottom; pixels are palette indices, 16 bit + values, or (r, g, b) tuples for 24/32 bit.""" + row_bytes = ((width * bpp + 31) // 32) * 4 + pixels = bytearray() + for row in rows if top_down else reversed(rows): + out = bytearray(row_bytes) + if bpp == 8: + out[:width] = bytes(row) + elif bpp == 16: + for x, value in enumerate(row): + out[x * 2 : x * 2 + 2] = struct.pack("= 2 else 0) + (1 if x >= 2 else 0)] + + draw(10, 10, 4, 4, quad) + draw(10, 40, 8, 4, lambda x, y: RED if x < 4 else GREEN) + + draw(40, 10, 4, 4, lambda x, y: RED if x < 2 else GREEN) + draw(70, 10, 4, 4, lambda x, y: RED if x < 2 else BLUE) + draw(100, 10, 4, 4, lambda x, y: BLUE if x < 2 else WHITE) + + def unchanged_quad(x, y): + return _QUAD_PALETTE[(2 if y >= 2 else 0) + (1 if x >= 2 else 0)] + + draw(130, 10, 4, 4, unchanged_quad) + + return frame + + +def _compare(path, changed): + with Image.open(path) as img: + rgb = img.convert("RGB") + expected = _expected(rgb.width, rgb.height, changed) + mismatches = [] + for y in range(rgb.height): + for x in range(rgb.width): + actual = rgb.getpixel((x, y)) + if actual != expected[y][x]: + mismatches.append((x, y, expected[y][x], actual)) + assert not mismatches, f"{len(mismatches)} pixels differ, first: {mismatches[:8]}" + + +_CODE_FILE = {"code.py": _CODE, **_FILES} + + +@pytest.mark.parametrize( + "board", ["native_native_sim_lvgl", "native_native_sim_lvgl_asan"], indirect=True +) +@pytest.mark.circuitpy_drive(_CODE_FILE) +@pytest.mark.display(capture_times_ns=[8_000_000_000, 20_000_000_000]) +@pytest.mark.duration(24) +def test_ondiskbitmap_render(circuitpython): + """Indexed, 16 bit and 24 bit BMPs render, including top-down rows and tiles.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "first" in output + assert "second" in output + + captures = circuitpython.display_capture_paths() + if len(captures) < 2 or not captures[1].exists(): + pytest.skip("display capture was not produced") + + _compare(captures[0], changed=False) + _compare(captures[1], changed=True) diff --git a/ports/zephyr-cp/tests/test_displayio_primary.py b/ports/zephyr-cp/tests/test_displayio_primary.py new file mode 100644 index 00000000000..dcd24854427 --- /dev/null +++ b/ports/zephyr-cp/tests/test_displayio_primary.py @@ -0,0 +1,46 @@ +# SPDX-FileCopyrightText: 2026 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""A display created when no primary display is set becomes the primary display. + +The supervisor keeps only the primary display across the end of a VM. If a +display created by user code (a USB video framebuffer, for example) didn't +default to primary, it was released when code.py finished and the terminal and +REPL had nowhere to draw. +""" + +import pytest + + +PRIMARY_CODE = """\ +import board +import displayio +import supervisor +import time +import zephyr_display + +print('board primary:', supervisor.runtime.display is board.DISPLAY) + +displayio.release_displays() +print('released:', supervisor.runtime.display is None) + +display = zephyr_display.Display() +print('new primary:', supervisor.runtime.display is display) +print('done') + +while True: + time.sleep(1) +""" + + +@pytest.mark.circuitpy_drive({"code.py": PRIMARY_CODE}) +@pytest.mark.duration(8) +def test_display_defaults_to_primary(circuitpython): + """Releasing and re-creating the display leaves the new one primary.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "board primary: True" in output + assert "released: True" in output + assert "new primary: True" in output + assert "done" in output diff --git a/ports/zephyr-cp/tests/test_displayio_tilegrid.py b/ports/zephyr-cp/tests/test_displayio_tilegrid.py new file mode 100644 index 00000000000..b55233ba266 --- /dev/null +++ b/ports/zephyr-cp/tests/test_displayio_tilegrid.py @@ -0,0 +1,631 @@ +# SPDX-FileCopyrightText: 2026 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""displayio TileGrid rendering on both displayio compositors. + +The scene exercises indexed bitmaps with palettes, which the LVGL compositor +hands to LVGL as indexed images whose palette is kept separately and shared +between the TileGrids that use it, and the cases that go through its custom +decoder (scaled groups and OnDiskBitmaps). The expected frame is computed here +from the same description, so both compositors are checked against an +independent model instead of a golden image. Only fully saturated colors are used so the result doesn't depend on the +display's pixel format. +""" + +import re + +import pytest +from PIL import Image + +_DISPLAY_HELPER = """\ +import board +display = board.DISPLAY +""" + +_SCENE_TEMPLATE = ( + _DISPLAY_HELPER + + """\ +import displayio +import time + +palette = displayio.Palette(4) +palette[0] = 0xFF0000 +palette[1] = 0x00FF00 +palette[2] = 0x0000FF +palette[3] = 0xFFFFFF + +group = displayio.Group() + +# Four vertical color bands in a 2 bit bitmap. +bands = displayio.Bitmap(40, 20, 4) +for y in range(bands.height): + for x in range(bands.width): + bands[x, y] = (x * 4) // bands.width +group.append(displayio.TileGrid(bands, pixel_shader=palette, x=10, y=10)) + +# A sprite sheet with two 8x8 tiles: tile 0 green, tile 1 blue with a white dot. +sheet = displayio.Bitmap(16, 8, 4) +for y in range(8): + for x in range(16): + sheet[x, y] = 1 if x < 8 else 2 +sheet[9, 1] = 3 +sheet_grid = displayio.TileGrid(sheet, pixel_shader=palette, width=3, height=1, + tile_width=8, tile_height=8, x=100, y=10) +sheet_grid[0] = 1 +sheet_grid[1] = 0 +sheet_grid[2] = 1 +group.append(sheet_grid) + +# Transparency: a white square partially covered by a sprite whose index 0 is +# transparent. +white = displayio.Bitmap(30, 30, 2) +white_palette = displayio.Palette(2) +white_palette[0] = 0xFFFFFF +white_palette[1] = 0xFFFFFF +group.append(displayio.TileGrid(white, pixel_shader=white_palette, x=200, y=10)) +overlay_palette = displayio.Palette(2) +overlay_palette[0] = 0x000000 +overlay_palette[1] = 0xFF0000 +overlay_palette.make_transparent(0) +overlay = displayio.Bitmap(10, 10, 2) +for y in range(10): + for x in range(5, 10): + overlay[x, y] = 1 +group.append(displayio.TileGrid(overlay, pixel_shader=overlay_palette, x=210, y=20)) + +# An 8 bit bitmap with a large palette. +big_palette = displayio.Palette(256) +for i in range(256): + big_palette[i] = 0x000000 +big_palette[200] = 0x00FFFF +big_palette[201] = 0xFFFF00 +eight = displayio.Bitmap(20, 10, 256) +for y in range(10): + for x in range(20): + eight[x, y] = 200 if x < 10 else 201 +group.append(displayio.TileGrid(eight, pixel_shader=big_palette, x=10, y=100)) + +{scaled}# One bitmap shown with two different palettes. +other_palette = displayio.Palette(4) +other_palette[0] = 0xFF00FF +other_palette[1] = 0x00FFFF +other_palette[2] = 0xFFFF00 +other_palette[3] = 0x000000 +group.append(displayio.TileGrid(bands, pixel_shader=other_palette, x=10, y=150)) +# A second TileGrid with the same alternate palette shares its LVGL palette. +group.append(displayio.TileGrid(bands, pixel_shader=other_palette, x=10, y=180)) + +# A 16 bit bitmap with a pass-through ColorConverter. +rgb565 = displayio.Bitmap(10, 10, 65536) +for y in range(10): + for x in range(10): + rgb565[x, y] = 0xF800 if x < 5 else 0x07E0 +group.append(displayio.TileGrid(rgb565, + pixel_shader=displayio.ColorConverter(input_colorspace=displayio.Colorspace.RGB565), + x=250, y=100)) + +# Nested groups with a TileGrid and a vectorio shape; the inner group moves later. +import vectorio +checker = displayio.Bitmap(4, 4, 4) +for y in range(4): + for x in range(4): + checker[x, y] = 1 if (x + y) % 2 else 2 +outer = displayio.Group(x=10, y=0) +inner = displayio.Group(x=60, y=200) +inner.append(displayio.TileGrid(checker, pixel_shader=palette, x=5, y=5)) +inner.append(vectorio.Rectangle(pixel_shader=palette, width=6, height=4, x=20, y=0, + color_index=2)) +outer.append(inner) +group.append(outer) + +# A sprite that is moved many times before the frame is captured. +mover = displayio.TileGrid(bands, pixel_shader=palette, x=0, y=0) +group.append(mover) + +display.auto_refresh = False +display.root_group = group +display.refresh() +for i in range(200): + mover.x = 150 + (i % 20) + mover.y = 150 + (i % 10) + display.refresh() +mover.x = 160 +mover.y = 200 +display.refresh() +print('first') +time.sleep(10) + +# Content changes after the first frame. +palette[3] = 0xFF00FF +bands[0, 0] = 3 +sheet_grid[1] = 1 +# The two alternate-palette TileGrids share one LVGL palette, so the Palette change +# reaches both, and the pixel change reaches every grid drawing the bitmap. +other_palette[3] = 0x00FF00 +bands[39, 19] = 2 +# A direct-color bitmap has no palette, only its own pixels. +rgb565[0, 0] = 0x001F +inner.x = 80 +display.refresh() +print('second') +while True: + time.sleep(1) +""" +) + +_SCALED_GROUP = """\ +# A scaled group. +small = displayio.Bitmap(4, 4, 4) +for y in range(4): + for x in range(4): + small[x, y] = 1 if (x + y) % 2 else 2 +scaled = displayio.Group(scale=2, x=100, y=100) +scaled.append(displayio.TileGrid(small, pixel_shader=palette, x=2, y=1)) +group.append(scaled) + +""" + +SCENE_CODE = _SCENE_TEMPLATE.replace("{scaled}", "") +SCALED_SCENE_CODE = _SCENE_TEMPLATE.replace("{scaled}", _SCALED_GROUP) + +RED = (255, 0, 0) +GREEN = (0, 255, 0) +BLUE = (0, 0, 255) +WHITE = (255, 255, 255) +BLACK = (0, 0, 0) +MAGENTA = (255, 0, 255) +CYAN = (0, 255, 255) +YELLOW = (255, 255, 0) + + +def _expected(width, height, changed, scaled): + frame = [[BLACK] * width for _ in range(height)] + + def draw(x0, y0, w, h, color_at, scale=1): + for y in range(h * scale): + for x in range(w * scale): + color = color_at(x // scale, y // scale) + if color is not None: + frame[y0 + y][x0 + x] = color + + palette = [RED, GREEN, BLUE, MAGENTA if changed else WHITE] + other = [MAGENTA, CYAN, YELLOW, GREEN if changed else BLACK] + + def bands(colors): + def color_at(x, y): + if changed and (x, y) == (0, 0): + return colors[3] + if changed and (x, y) == (39, 19): + return colors[2] + return colors[(x * 4) // 40] + + return color_at + + draw(10, 10, 40, 20, bands(palette)) + + tiles = [1, 1 if changed else 0, 1] + + def sheet(x, y): + tile = tiles[x // 8] + sx = (x % 8) + tile * 8 + if (sx, y) == (9, 1): + return palette[3] + return palette[1] if sx < 8 else palette[2] + + draw(100, 10, 24, 8, sheet) + + draw(200, 10, 30, 30, lambda x, y: WHITE) + draw(210, 20, 10, 10, lambda x, y: RED if x >= 5 else None) + + draw(10, 100, 20, 10, lambda x, y: CYAN if x < 10 else YELLOW) + + if scaled: + draw( + 104, + 102, + 4, + 4, + lambda x, y: palette[1] if (x + y) % 2 else palette[2], + scale=2, + ) + + draw( + 250, + 100, + 10, + 10, + lambda x, y: BLUE if changed and (x, y) == (0, 0) else RED if x < 5 else GREEN, + ) + + inner_x = 10 + (80 if changed else 60) + draw(inner_x + 5, 205, 4, 4, lambda x, y: palette[1] if (x + y) % 2 else palette[2]) + draw(inner_x + 20, 200, 6, 4, lambda x, y: palette[2]) + + draw(10, 150, 40, 20, bands(other)) + draw(10, 180, 40, 20, bands(other)) + + draw(160, 200, 40, 20, bands(palette)) + return frame + + +def _compare(path, changed, scaled=False): + with Image.open(path) as img: + rgb = img.convert("RGB") + expected = _expected(rgb.width, rgb.height, changed, scaled) + mismatches = [] + for y in range(rgb.height): + for x in range(rgb.width): + actual = rgb.getpixel((x, y)) + if actual != expected[y][x]: + mismatches.append((x, y, expected[y][x], actual)) + assert not mismatches, f"{len(mismatches)} pixels differ, first: {mismatches[:8]}" + + +@pytest.mark.circuitpy_drive({"code.py": SCENE_CODE}) +@pytest.mark.display(capture_times_ns=[8_000_000_000, 20_000_000_000]) +@pytest.mark.duration(24) +def test_tilegrid_render(circuitpython): + """Indexed bitmaps, sprite sheets, transparency and updates render exactly.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "first" in output + assert "second" in output + + captures = circuitpython.display_capture_paths() + if len(captures) < 2 or not captures[1].exists(): + pytest.skip("display capture was not produced") + + _compare(captures[0], changed=False) + _compare(captures[1], changed=True) + + +@pytest.mark.circuitpy_drive({"code.py": SCALED_SCENE_CODE}) +@pytest.mark.display(capture_times_ns=[8_000_000_000, 20_000_000_000]) +@pytest.mark.duration(24) +def test_tilegrid_render_scaled_group(request, board, circuitpython): + """A TileGrid in a scaled group is scaled by whole pixels from its corner.""" + if board.startswith("native_native_sim_lvgl"): + # LVGL scales images about pixel centers ((w - 1) * scale wide) and resamples, + # so it doesn't reproduce displayio's whole pixel scaling yet. + request.applymarker(pytest.mark.xfail(reason="LVGL image scaling isn't pixel exact")) + circuitpython.wait_until_done() + + captures = circuitpython.display_capture_paths() + if len(captures) < 2 or not captures[1].exists(): + pytest.skip("display capture was not produced") + + _compare(captures[0], changed=False, scaled=True) + _compare(captures[1], changed=True, scaled=True) + + +# Nonconsecutive atlas tiles are essential here: overflow from tile N looks correct +# when the next displayed tile happens to be N + 1 (as in an alphabet test). +CROPPED_ATLAS_CODE = """\ +import board +import displayio +import time + +display = board.DISPLAY +palette = displayio.Palette(4) +for i, color in enumerate((0xFF0000, 0x00FF00, 0x0000FF, 0xFFFFFF)): + palette[i] = color +sheet = displayio.Bitmap(12, 10, 4) +for y in range(10): + for x in range(12): + sheet[x, y] = (x // 3 + 2 * (y // 5)) % 4 +root = displayio.Group() +grids = [] +for scale, y in ((1, 8), (2, 50), (3, 110)): + group = displayio.Group(scale=scale, x=8, y=y) + grid = displayio.TileGrid(sheet, pixel_shader=palette, width=5, height=3, + tile_width=3, tile_height=5, x=1, y=1) + for i in range(15): + grid[i] = (7 - i * 3) % 8 + group.append(grid) + # Single-cell TileGrids use a separate LVGL path. Leave space around the sprite + # so drawing outside its rectangle cannot be hidden by neighboring cells. + sprite = displayio.TileGrid(sheet, pixel_shader=palette, + tile_width=3, tile_height=5, default_tile=2, x=30, y=1) + group.append(sprite) + root.append(group) + grids.append((grid, sprite)) +display.auto_refresh = False +display.root_group = root +display.refresh() +print('first') +time.sleep(10) +for grid, sprite in grids: + for i in range(15): + grid[i] = (i * 5 + 1) % 8 + sprite[0] = 5 +display.refresh() +print('second') +while True: + time.sleep(1) +""" + + +def _cropped_atlas_expected(width, height, changed): + frame = Image.new("RGB", (width, height), BLACK) + colors = (RED, GREEN, BLUE, WHITE) + + def tile(x0, y0, index, scale): + for y in range(5 * scale): + for x in range(3 * scale): + color = colors[(index % 4 + 2 * (index // 4)) % 4] + frame.putpixel((x0 + x, y0 + y), color) + + for scale, y0 in ((1, 8), (2, 50), (3, 110)): + for i in range(15): + index = (i * 5 + 1) % 8 if changed else (7 - i * 3) % 8 + tile(8 + (1 + i % 5 * 3) * scale, y0 + (1 + i // 5 * 5) * scale, index, scale) + tile(8 + 30 * scale, y0 + scale, 5 if changed else 2, scale) + return frame + + +@pytest.mark.circuitpy_drive({"code.py": CROPPED_ATLAS_CODE}) +@pytest.mark.display(capture_times_ns=[8_000_000_000, 20_000_000_000]) +@pytest.mark.duration(24) +def test_tilegrid_scaled_atlas_clipping(circuitpython): + """Scaled atlas windows never draw neighboring tiles outside their cells.""" + circuitpython.wait_until_done() + captures = circuitpython.display_capture_paths() + if len(captures) < 2 or not captures[1].exists(): + pytest.skip("display capture was not produced") + for path, changed in ((captures[0], False), (captures[1], True)): + with Image.open(path) as image: + actual = image.convert("RGB") + expected = _cropped_atlas_expected(actual.width, actual.height, changed) + # Check the entire exterior and the center of every cell. Zephyr's older + # LVGL has a separate nearest-neighbor rounding bug at tile edges; this + # regression isolates clipping rather than depending on that sampler fix. + checked = { + (x, y) + for y in range(actual.height) + for x in range(actual.width) + if expected.getpixel((x, y)) == BLACK + } + for scale, y0 in ((1, 8), (2, 50), (3, 110)): + for i in range(15): + checked.add((8 + (2 + i % 5 * 3) * scale, y0 + (3 + i // 5 * 5) * scale)) + checked.add((8 + 31 * scale, y0 + 3 * scale)) + mismatches = [ + (x, y, expected.getpixel((x, y)), actual.getpixel((x, y))) + for x, y in sorted(checked) + if actual.getpixel((x, y)) != expected.getpixel((x, y)) + ] + assert not mismatches, f"{len(mismatches)} pixels differ, first: {mismatches[:8]}" + + +UNSUPPORTED_CODE = """\ +import displayio + +bitmap = displayio.Bitmap(4, 4, 65536) +try: + displayio.TileGrid(bitmap, pixel_shader=displayio.ColorConverter()) + print('converting shader: ok') +except NotImplementedError: + print('converting shader: NotImplementedError') +print('done') +""" + + +@pytest.mark.circuitpy_drive({"code.py": UNSUPPORTED_CODE}) +@pytest.mark.parametrize( + "board", ["native_native_sim_lvgl", "native_native_sim_lvgl_asan"], indirect=True +) +@pytest.mark.duration(10) +def test_tilegrid_unsupported(circuitpython): + """Combinations LVGL can't draw directly raise NotImplementedError.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "converting shader: NotImplementedError" in output + assert "done" in output + + +VIEW_LIFECYCLE_CODE = """\ +import board +import displayio +import time + +display = board.DISPLAY + +def split_bands(): + bitmap = displayio.Bitmap(8, 8, 4) + for y in range(8): + for x in range(8): + bitmap[x, y] = 1 if x < 4 else 2 + return bitmap + +first = split_bands() +second = displayio.Bitmap(8, 8, 4) +for y in range(8): + for x in range(8): + second[x, y] = 3 + +canonical = displayio.Palette(4) +canonical[1] = 0x00FF00 +canonical[2] = 0x0000FF +canonical[3] = 0xFFFFFF +alternate = displayio.Palette(4) +alternate[1] = 0xFFFF00 +alternate[2] = 0x00FFFF +third = displayio.Palette(4) +third[1] = 0xFF00FF +third[2] = 0x00FF00 + +group = displayio.Group() +canonical_grid = displayio.TileGrid(first, pixel_shader=canonical, x=0, y=0) +copy_a = displayio.TileGrid(first, pixel_shader=alternate, x=20, y=0) +copy_b = displayio.TileGrid(first, pixel_shader=alternate, x=40, y=0) +second_grid = displayio.TileGrid(second, pixel_shader=canonical, x=0, y=20) +for grid in (canonical_grid, copy_a, copy_b, second_grid): + group.append(grid) + +display.auto_refresh = False +display.root_group = group +display.refresh() +print('first') +time.sleep(10) + +# Drop one of the two users of the shared LVGL palette. +group.remove(copy_b) +# Point the second grid at the first bitmap; both are 8x8. +second_grid.bitmap = first +# Give the canonical grid another palette. +canonical_grid.pixel_shader = third +# Change the shared bitmap and the remaining copy's palette. +first[0, 0] = 2 +alternate[1] = 0x000000 +display.refresh() +print('second') +while True: + time.sleep(1) +""" + + +def _lifecycle_expected(width, height, changed): + frame = [[BLACK] * width for _ in range(height)] + + def draw(x0, y0, colors): + for y in range(8): + for x in range(8): + frame[y0 + y][x0 + x] = colors[0] if x < 4 else colors[1] + + if not changed: + draw(0, 0, (GREEN, BLUE)) + draw(20, 0, (YELLOW, CYAN)) + draw(40, 0, (YELLOW, CYAN)) + draw(0, 20, (WHITE, WHITE)) + return frame + + # The canonical grid switched to the third palette, and pixel (0, 0) now holds index 2. + draw(0, 0, (MAGENTA, GREEN)) + frame[0][0] = GREEN + # The removed grid leaves a hole; the other copy uses its changed palette. + draw(20, 0, (BLACK, CYAN)) + frame[0][20] = CYAN + # The second grid now shows the first bitmap with the canonical palette, including the + # changed pixel. + draw(0, 20, (GREEN, BLUE)) + frame[20][0] = BLUE + return frame + + +@pytest.mark.circuitpy_drive({"code.py": VIEW_LIFECYCLE_CODE}) +@pytest.mark.display(capture_times_ns=[8_000_000_000, 20_000_000_000]) +@pytest.mark.duration(24) +def test_tilegrid_view_lifecycle(circuitpython): + """Shared images survive detaching one user, and bitmap/palette swaps rebind cleanly.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "first" in output + assert "second" in output + + captures = circuitpython.display_capture_paths() + if len(captures) < 2 or not captures[1].exists(): + pytest.skip("display capture was not produced") + + for path, changed in ((captures[0], False), (captures[1], True)): + with Image.open(path) as img: + rgb = img.convert("RGB") + expected = _lifecycle_expected(rgb.width, rgb.height, changed) + mismatches = [] + for y in range(rgb.height): + for x in range(rgb.width): + actual = rgb.getpixel((x, y)) + if actual != expected[y][x]: + mismatches.append((x, y, expected[y][x], actual)) + assert not mismatches, f"{len(mismatches)} pixels differ, first: {mismatches[:8]}" + + +# Scrolling is not a Python-visible TileGrid property, but the terminal scrolls its TileGrid +# by moving the wrapped window over the tile matrix instead of moving tiles. So writing a +# fifth line into a four line terminal shifts the visible content up by exactly one cell row: +# the first three rows of the scrolled frame must equal the last three rows of the frame +# before it, and the bottom row must hold the new line. The wrapped window is two row runs +# once the terminal has scrolled. +SCROLL_CODE = """\ +import board +import displayio +import terminalio +import time + +display = board.DISPLAY + +font = terminalio.FONT +cell_width, cell_height = font.get_bounding_box() +palette = displayio.Palette(2) +palette[0] = 0x000000 +palette[1] = 0xFFFFFF + +group = displayio.Group() +grid = displayio.TileGrid(font.bitmap, pixel_shader=palette, width=4, height=4, + tile_width=cell_width, tile_height=cell_height, x=4, y=4) +group.append(grid) +terminal = terminalio.Terminal(grid, font) + +display.auto_refresh = False +display.root_group = group +# Fill the terminal without going past the last row, so this frame doesn't scroll yet. +terminal.write("aa\\r\\nbb\\r\\ncc\\r\\ndd") +display.refresh() +print('filled', cell_width, cell_height) +time.sleep(2) + +# Moving to the row below the last one makes the terminal scroll by one line. +terminal.write("\\r\\nee") +display.refresh() +print('scrolled') +time.sleep(2) +while True: + time.sleep(1) +""" + + +@pytest.mark.circuitpy_drive({"code.py": SCROLL_CODE}) +@pytest.mark.display(capture_times_ns=[4_000_000_000, 8_000_000_000]) +@pytest.mark.duration(14) +def test_tilegrid_scroll(circuitpython): + """A terminal scroll shifts the visible tile rows and wraps the window.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "scrolled" in output + match = re.search(r"filled (\d+) (\d+)", output) + assert match, "the scene didn't report the font's cell size" + cell_w = int(match.group(1)) + cell_h = int(match.group(2)) + + captures = circuitpython.display_capture_paths() + if len(captures) < 2 or not captures[1].exists(): + pytest.skip("display capture was not produced") + + with Image.open(captures[0]) as img: + filled = img.convert("RGB") + with Image.open(captures[1]) as img: + scrolled = img.convert("RGB") + + origin_x = 4 + origin_y = 4 + width = 4 * cell_w + # Row j of the filled frame is row j - 1 of the scrolled one, for every row but the last. + for row in range(1, 4): + for y in range(cell_h): + for x in range(width): + before = filled.getpixel((origin_x + x, origin_y + row * cell_h + y)) + after = scrolled.getpixel((origin_x + x, origin_y + (row - 1) * cell_h + y)) + assert before == after, f"row {row - 1} did not shift up (x={x}, y={y})" + + # The new line landed on the bottom row. + bottom = origin_y + 3 * cell_h + changed = any( + scrolled.getpixel((origin_x + x, bottom + y)) + != filled.getpixel((origin_x + x, bottom + y)) + for y in range(cell_h) + for x in range(width) + ) + assert changed, "the new line did not appear at the bottom of the scrolled frame" diff --git a/ports/zephyr-cp/tests/test_filesystem.py b/ports/zephyr-cp/tests/test_filesystem.py new file mode 100644 index 00000000000..2e149dcfe99 --- /dev/null +++ b/ports/zephyr-cp/tests/test_filesystem.py @@ -0,0 +1,144 @@ +# SPDX-FileCopyrightText: 2026 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""Filesystem tests that run against every filesystem the port supports. + +Each test is parameterized over the two native_sim builds so the same +expectations are checked against the FAT filesystem (``native_native_sim``) +and littlefs (``native_native_sim_lfs``). These tests boot from an erased +flash image so they see the filesystem that CircuitPython creates itself, +not one preloaded from the host (see ``conftest`` for that). +""" + +import time + +import pytest + +from .conftest import FILESYSTEM_SIMULATORS + + +def _enter_repl(circuitpython): + """Run the default code.py, then enter the REPL from the reload prompt.""" + circuitpython.serial.wait_for("Press any key to enter the REPL") + circuitpython.serial.write("\r") + circuitpython.serial.wait_for(">>>") + + +def _repl(circuitpython, line): + """Send one line to the REPL and give it time to echo and run.""" + # The native sim console needs CR, not LF, to submit the line. + circuitpython.serial.write(line.rstrip("\n") + "\r") + time.sleep(0.5) + + +@pytest.mark.parametrize("board", FILESYSTEM_SIMULATORS, indirect=True) +@pytest.mark.circuitpy_drive(None) +@pytest.mark.duration(30) +@pytest.mark.port_resets(6) +def test_fresh_filesystem_defaults(circuitpython): + """An erased flash image gets a filesystem with the default files.""" + _enter_repl(circuitpython) + + _repl(circuitpython, "import os\n") + _repl(circuitpython, "entries = os.listdir('/')\n") + _repl(circuitpython, "print('code.py:', 'code.py' in entries)\n") + circuitpython.serial.wait_for("code.py: True") + _repl(circuitpython, "print('lib:', 'lib' in entries)\n") + circuitpython.serial.wait_for("lib: True") + + +@pytest.mark.parametrize("board", FILESYSTEM_SIMULATORS, indirect=True) +@pytest.mark.circuitpy_drive(None) +@pytest.mark.duration(60) +@pytest.mark.port_resets(6) +def test_filesystem_write_read_delete(circuitpython): + """Files survive write, close, reopen and delete.""" + _enter_repl(circuitpython) + + _repl(circuitpython, "with open('/fs_test.txt', 'w') as f:\n") + _repl(circuitpython, " f.write('hello filesystem')\n") + _repl(circuitpython, "\n") + _repl(circuitpython, "print('read:', open('/fs_test.txt').read())\n") + circuitpython.serial.wait_for("read: hello filesystem") + + _repl(circuitpython, "import os\n") + _repl(circuitpython, "print('exists:', 'fs_test.txt' in os.listdir('/'))\n") + circuitpython.serial.wait_for("exists: True") + + _repl(circuitpython, "os.remove('/fs_test.txt')\n") + _repl(circuitpython, "print('exists:', 'fs_test.txt' in os.listdir('/'))\n") + circuitpython.serial.wait_for("exists: False") + + +@pytest.mark.parametrize("board", FILESYSTEM_SIMULATORS, indirect=True) +@pytest.mark.circuitpy_drive(None) +@pytest.mark.duration(60) +@pytest.mark.port_resets(6) +def test_filesystem_mkdir_rename_stat(circuitpython): + """Directories, renames and os.stat work.""" + _enter_repl(circuitpython) + + _repl(circuitpython, "import os\n") + _repl(circuitpython, "os.mkdir('/subdir')\n") + _repl(circuitpython, "with open('/moved.txt', 'w') as f:\n") + _repl(circuitpython, " f.write('moved')\n") + _repl(circuitpython, "\n") + _repl(circuitpython, "os.rename('/moved.txt', '/subdir/renamed.txt')\n") + _repl(circuitpython, "print('dir:', 'subdir' in os.listdir('/'))\n") + circuitpython.serial.wait_for("dir: True") + _repl(circuitpython, "print('renamed:', open('/subdir/renamed.txt').read())\n") + circuitpython.serial.wait_for("renamed: moved") + _repl(circuitpython, "print('stat size:', os.stat('/subdir/renamed.txt')[6])\n") + circuitpython.serial.wait_for("stat size: 5") + + +@pytest.mark.parametrize("board", FILESYSTEM_SIMULATORS, indirect=True) +@pytest.mark.circuitpy_drive(None) +@pytest.mark.duration(60) +@pytest.mark.port_resets(6) +def test_storage_remount(circuitpython): + """storage.remount('/') toggles writability on the root filesystem.""" + _enter_repl(circuitpython) + + _repl(circuitpython, "import storage\n") + _repl(circuitpython, "storage.remount('/', readonly=False)\n") + _repl(circuitpython, "with open('/remount.txt', 'w') as f:\n") + _repl(circuitpython, " f.write('writable')\n") + _repl(circuitpython, "\n") + _repl(circuitpython, "print('read:', open('/remount.txt').read())\n") + circuitpython.serial.wait_for("read: writable") + + _repl(circuitpython, "storage.remount('/', readonly=True)\n") + _repl(circuitpython, "try:\n") + _repl(circuitpython, " with open('/remount2.txt', 'w') as f:\n") + _repl(circuitpython, " f.write('nope')\n") + _repl(circuitpython, " print('unexpected: write succeeded')\n") + _repl(circuitpython, "except OSError as e:\n") + _repl(circuitpython, " print('caught OSError:', e.errno)\n") + _repl(circuitpython, "\n") + circuitpython.serial.wait_for("caught OSError:") + + _repl(circuitpython, "import os\n") + _repl(circuitpython, "print('blocked:', 'remount2.txt' in os.listdir('/'))\n") + circuitpython.serial.wait_for("blocked: False") + + +@pytest.mark.parametrize("board", FILESYSTEM_SIMULATORS, indirect=True) +@pytest.mark.circuitpy_drive(None) +@pytest.mark.duration(120) +@pytest.mark.port_resets(8) +def test_filesystem_persists_across_reset(circuitpython): + """Files written before microcontroller.reset() survive the reboot.""" + _enter_repl(circuitpython) + + _repl(circuitpython, "with open('/persist.txt', 'w') as f:\n") + _repl(circuitpython, " f.write('still here')\n") + _repl(circuitpython, "\n") + _repl(circuitpython, "import microcontroller\n") + _repl(circuitpython, "microcontroller.reset()\n") + + assert circuitpython.reconnect_serial(timeout=30), "simulator did not reboot" + + _enter_repl(circuitpython) + _repl(circuitpython, "print('persisted:', open('/persist.txt').read())\n") + circuitpython.serial.wait_for("persisted: still here") diff --git a/ports/zephyr-cp/tests/test_flash.py b/ports/zephyr-cp/tests/test_flash.py new file mode 100644 index 00000000000..8e81491ba24 --- /dev/null +++ b/ports/zephyr-cp/tests/test_flash.py @@ -0,0 +1,373 @@ +# SPDX-FileCopyrightText: 2025 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""Test flash filesystem with various erase block sizes.""" + +import subprocess + +import pytest + +from .conftest import ( + DEFAULT_ERASE_PAGE_SIZE, + LITTLEFS_FILESYSTEM_BOARDS, + read_lfs_file_from_flash, +) + + +def read_file_from_flash(flash_file, path, board, erase_page_size=DEFAULT_ERASE_PAGE_SIZE): + """Extract a file from the flash image using the board's filesystem tool.""" + if board in LITTLEFS_FILESYSTEM_BOARDS: + return read_lfs_file_from_flash(flash_file, path, board, erase_page_size) + result = subprocess.run( + ["mcopy", "-i", str(flash_file), f"::{path}", "-"], + capture_output=True, + ) + if result.returncode != 0: + raise FileNotFoundError( + f"Failed to read ::{path} from {flash_file}: {result.stderr.decode()}" + ) + return result.stdout.decode() + + +WRITE_READ_CODE = """\ +import storage +storage.remount("/", readonly=False) +with open("/test.txt", "w") as f: + f.write("hello flash") +with open("/test.txt", "r") as f: + content = f.read() +print(f"content: {content}") +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": WRITE_READ_CODE}) +def test_flash_default_erase_size(circuitpython, board): + """Test filesystem write/read with default 4KB erase blocks.""" + circuitpython.wait_until_done() + output = circuitpython.serial.all_output + assert "content: hello flash" in output + assert "done" in output + + content = read_file_from_flash(circuitpython.flash_file, "test.txt", board) + assert content == "hello flash" + + +@pytest.mark.circuitpy_drive({"code.py": WRITE_READ_CODE}) +@pytest.mark.flash_config(erase_block_size=65536) +def test_flash_64k_erase_blocks(circuitpython, board): + """Test filesystem write/read with 64KB erase blocks (128 blocks per page).""" + circuitpython.wait_until_done() + output = circuitpython.serial.all_output + assert "content: hello flash" in output + assert "done" in output + + content = read_file_from_flash( + circuitpython.flash_file, "test.txt", board, erase_page_size=65536 + ) + assert content == "hello flash" + + +@pytest.mark.circuitpy_drive({"code.py": WRITE_READ_CODE}) +@pytest.mark.flash_config(erase_block_size=262144, total_size=4 * 1024 * 1024) +def test_flash_256k_erase_blocks(circuitpython, board): + """Test filesystem write/read with 256KB erase blocks (like RA8D1 OSPI).""" + circuitpython.wait_until_done() + output = circuitpython.serial.all_output + assert "content: hello flash" in output + assert "done" in output + + content = read_file_from_flash( + circuitpython.flash_file, "test.txt", board, erase_page_size=262144 + ) + assert content == "hello flash" + + +MULTI_FILE_CODE = """\ +import storage +storage.remount("/", readonly=False) +for i in range(5): + name = f"/file{i}.txt" + with open(name, "w") as f: + f.write(f"data{i}" * 100) +print("multi_file_ok") +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": MULTI_FILE_CODE}) +@pytest.mark.flash_config(erase_block_size=262144, total_size=4 * 1024 * 1024) +def test_flash_256k_multi_file(circuitpython, board): + """Test multiple file writes with 256KB erase blocks to exercise cache flushing.""" + circuitpython.wait_until_done() + output = circuitpython.serial.all_output + assert "multi_file_ok" in output + + for i in range(5): + content = read_file_from_flash( + circuitpython.flash_file, + f"file{i}.txt", + board, + erase_page_size=262144, + ) + assert content == f"data{i}" * 100, f"file{i}.txt mismatch" + + +EXISTING_DATA_CODE = """\ +import storage +storage.remount("/", readonly=False) + +# Write a file to populate the erase page. +original_data = "A" * 4000 +with open("/original.txt", "w") as f: + f.write(original_data) + +# Force a flush so the data is written to flash. +storage.remount("/", readonly=True) +storage.remount("/", readonly=False) + +# Now write a small new file. This updates filesystem metadata and +# directory entries that share an erase page with original.txt, +# exercising the read-modify-write cycle on the cached page. +with open("/small.txt", "w") as f: + f.write("tiny") + +# Read back original to check it survived. +with open("/original.txt", "r") as f: + readback = f.read() +if readback == original_data: + print("existing_data_ok") +else: + print(f"MISMATCH: got {len(readback)} bytes") +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": EXISTING_DATA_CODE}) +@pytest.mark.flash_config(erase_block_size=262144, total_size=4 * 1024 * 1024) +def test_flash_256k_existing_data_survives(circuitpython, board): + """Test that existing data in an erase page survives when new data is written. + + With 256KB erase blocks (512 blocks per page), writing to any block in + the page triggers an erase-rewrite of the entire page. Existing blocks + must be preserved through the read-modify-write cycle. + """ + circuitpython.wait_until_done() + output = circuitpython.serial.all_output + assert "existing_data_ok" in output + + # Verify both files survived on the actual flash image. + original = read_file_from_flash( + circuitpython.flash_file, "original.txt", board, erase_page_size=262144 + ) + assert original == "A" * 4000, f"original.txt corrupted: got {len(original)} bytes" + + small = read_file_from_flash( + circuitpython.flash_file, "small.txt", board, erase_page_size=262144 + ) + assert small == "tiny" + + +OVERWRITE_CODE = """\ +import storage +storage.remount("/", readonly=False) +with open("/overwrite.txt", "w") as f: + f.write("first version") +with open("/overwrite.txt", "w") as f: + f.write("second version") +print("overwrite_ok") +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": OVERWRITE_CODE}) +@pytest.mark.flash_config(erase_block_size=262144, total_size=4 * 1024 * 1024) +def test_flash_256k_overwrite(circuitpython, board): + """Test overwriting a file with 256KB erase blocks to exercise erase-rewrite cycle.""" + circuitpython.wait_until_done() + output = circuitpython.serial.all_output + assert "overwrite_ok" in output + + content = read_file_from_flash( + circuitpython.flash_file, "overwrite.txt", board, erase_page_size=262144 + ) + assert content == "second version" + + +PAGE_CHANGE_CODE = """\ +import board +import storage +import time +# The display's auto refresh keeps the supervisor tick running, which would +# flush the cache whether or not the filesystem is marked dirty. +board.DISPLAY.auto_refresh = False +storage.remount("/", readonly=False) +# Program the sectors first. Writes to erased flash skip the page cache. +with open("/data.bin", "wb") as f: + f.write(bytes(16384)) +# Overwrite one sector, then one three pages later, so the last write moves +# the flash cache to a new page. Don't flush or close the file. +f = open("/data.bin", "r+b") +f.write(b"A" * 512) +f.seek(12288) +f.write(b"Z" * 512) +# The background flush runs after 1000 supervisor ticks. native_sim's 100 Hz +# kernel tick makes that about 10 seconds. +time.sleep(15) +print("slept") +while True: + time.sleep(1) +""" + + +@pytest.mark.circuitpy_drive({"code.py": PAGE_CHANGE_CODE}) +@pytest.mark.fat_filesystem_only +def test_flash_background_flush_after_page_change(circuitpython): + """Test that the background flush writes the page cached by a page change. + + The file is never flushed or closed, so only the background flush can + write the last sector before the simulator is stopped. + """ + circuitpython.serial.wait_for("slept") + circuitpython.shutdown() + + assert b"Z" * 512 in circuitpython.flash_file.read_bytes() + + +LFS_PAGE_CHANGE_CODE = """\ +import board +import os +import storage +import time +# The display's auto refresh keeps the supervisor tick running, which would +# flush the cache whether or not the filesystem is marked dirty. +board.DISPLAY.auto_refresh = False +storage.remount("/", readonly=False) +# littlefs writes new data to unused blocks, and writes to erased flash skip +# the page cache. Fill the free space and free it again so they don't. +f = open("/burn.bin", "wb") +chunk = bytes(8192) +try: + while True: + f.write(chunk) +except OSError: + pass +f.close() +os.remove("/burn.bin") +# Creating the file syncs, so the cache holds the metadata page. The first +# block of the file is on another page, so writing it changes pages. Don't +# flush or close the file. +f = open("/z.bin", "wb") +f.write(b"Z" * 512) +# The background flush runs after 1000 supervisor ticks. native_sim's 100 Hz +# kernel tick makes that about 10 seconds. +time.sleep(15) +print("slept") +while True: + time.sleep(1) +""" + + +@pytest.mark.circuitpy_drive({"code.py": LFS_PAGE_CHANGE_CODE}) +@pytest.mark.parametrize("board", ["native_native_sim_lfs"], indirect=True) +def test_flash_background_flush_after_page_change_lfs(circuitpython): + """Test that the background flush writes the page cached by a littlefs write. + + littlefs marks the filesystem dirty before writing, so the page change + must not clear the dirty flag. The file is never flushed or closed, so + only the background flush can write the block before the simulator is + stopped. + """ + circuitpython.serial.wait_for("slept") + circuitpython.shutdown() + + assert b"Z" * 512 in circuitpython.flash_file.read_bytes() + + +SCRATCH_PAGE_CODE = """\ +import gc +import storage +storage.remount("/", readonly=False) + +# Open the files and build their contents first: nothing that allocates can +# run once the heap is full. +names = ("/scratch0.txt", "/scratch1.txt", "/scratch2.txt", "/scratch3.txt") +chunks = (b"A" * 300, b"B" * 300, b"C" * 300, b"D" * 300) +files = [open(name, "wb") for name in names] + +# Fill the heap so flash.c can't allocate its RAM cache and stages writes in +# the scratch page instead. +filler = [] +for size in (65536, 4096, 512, 64): + while True: + try: + filler.append(bytearray(size)) + except MemoryError: + break + +# Each flush() rewrites the directory block, and appends rewrite the FAT, so +# the same blocks are written again while their page is in the scratch page. +for _ in range(8): + for i in range(4): + files[i].write(chunks[i]) + files[i].flush() +for f in files: + f.close() + +filler = None +gc.collect() +ok = True +for i in range(4): + with open(names[i], "rb") as f: + if f.read() != chunks[i] * 8: + ok = False + print("MISMATCH", names[i]) +if ok: + print("scratch_page_ok") +print("done") +""" + + +def check_scratch_page_run(circuitpython, board, erase_page_size): + """Check a SCRATCH_PAGE_CODE run, on the console and in the flash image.""" + circuitpython.wait_until_done() + output = circuitpython.serial.all_output + debug_output = circuitpython.debug_serial.all_output + assert "Unable to allocate ram cache" in debug_output, "scratch page path not taken" + assert "Erase of" not in debug_output + assert "flash write failed" not in debug_output + assert "scratch_page_ok" in output + + for i, letter in enumerate("ABCD"): + content = read_file_from_flash( + circuitpython.flash_file, f"scratch{i}.txt", board, erase_page_size=erase_page_size + ) + assert content == letter * 300 * 8, f"scratch{i}.txt mismatch" + + +@pytest.mark.parametrize("board", ["native_native_sim", "native_native_sim_asan"], indirect=True) +@pytest.mark.circuitpy_drive({"code.py": SCRATCH_PAGE_CODE}) +@pytest.mark.flash_config(erase_block_size=16384) +def test_flash_scratch_page_rewrites(circuitpython, board): + """Test rewriting blocks while writes are staged in the scratch page. + + The flash simulator rejects writes to flash that isn't erased, so a block + programmed twice without an erase fails instead of silently corrupting. + 16KB erase blocks make the RAM cache too big to allocate from a full heap, + and evenly divide the 0x1fc000 filesystem partition. (littlefs doesn't + stage writes in the scratch page.) + """ + check_scratch_page_run(circuitpython, board, erase_page_size=16384) + + +@pytest.mark.parametrize("board", ["native_native_sim", "native_native_sim_asan"], indirect=True) +@pytest.mark.circuitpy_drive({"code.py": SCRATCH_PAGE_CODE}) +@pytest.mark.flash_config(erase_block_size=65536) +def test_flash_scratch_page_partial_last_page(circuitpython, board): + """Test the scratch page when the partition doesn't end on a page boundary. + + The 0x1fc000 filesystem partition isn't a multiple of 64KB, so its last + page is partial and can't be erased. The scratch page must be the last + whole page instead. + """ + check_scratch_page_run(circuitpython, board, erase_page_size=65536) diff --git a/ports/zephyr-cp/tests/test_getpass.py b/ports/zephyr-cp/tests/test_getpass.py new file mode 100644 index 00000000000..541d91078b3 --- /dev/null +++ b/ports/zephyr-cp/tests/test_getpass.py @@ -0,0 +1,182 @@ +# SPDX-FileCopyrightText: 2026 Tim Cocks for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""Test the getpass core module.""" + +import pytest + + +DEFAULT_PROMPT_CODE = """\ +import getpass + +print("ready") +pw = getpass.getpass() +print(f"got: {pw}") +print(f"length: {len(pw)}") +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": DEFAULT_PROMPT_CODE}) +def test_getpass_default_prompt(circuitpython): + """getpass() with no args prints 'Password: ' and returns the typed string.""" + circuitpython.serial.wait_for("ready") + circuitpython.serial.wait_for("Password:") + circuitpython.serial.write("hunter2\r") + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "Password:" in output + assert "got: hunter2" in output + assert "length: 7" in output + assert "done" in output + + +CUSTOM_PROMPT_CODE = """\ +import getpass + +print("ready") +pw = getpass.getpass("Enter secret: ") +print(f"got: {pw}") +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": CUSTOM_PROMPT_CODE}) +def test_getpass_custom_prompt(circuitpython): + """A user-supplied prompt string is written before reading input.""" + circuitpython.serial.wait_for("Enter secret:") + circuitpython.serial.write("s3cr3t\r") + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "Enter secret:" in output + assert "got: s3cr3t" in output + assert "done" in output + + +NO_ECHO_CODE = """\ +import getpass + +print("ready") +pw = getpass.getpass("Pwd: ") +print("---boundary---") +print(f"got: {pw}") +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": NO_ECHO_CODE}) +def test_getpass_does_not_echo(circuitpython): + """Characters typed during getpass are not echoed back to the terminal.""" + circuitpython.serial.wait_for("Pwd:") + secret = "TopSecret123" + circuitpython.serial.write(secret + "\r") + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + # Split around the boundary: nothing typed should appear before it, + # but the printed value appears after. + pre, _, post = output.partition("---boundary---") + assert secret not in pre + assert f"got: {secret}" in post + assert "done" in post + + +BACKSPACE_CODE = """\ +import getpass + +print("ready") +pw = getpass.getpass("P: ") +print(f"got: {pw}") +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": BACKSPACE_CODE}) +def test_getpass_backspace(circuitpython): + """Backspace (0x7f) removes the previous character from the buffer.""" + circuitpython.serial.wait_for("P:") + # Type "abcX", then backspace, then "d" -> "abcd" + circuitpython.serial.write("abcX\x7fd\r") + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "got: abcd" in output + assert "done" in output + + +CTRL_C_CODE = """\ +import getpass + +print("ready") +try: + getpass.getpass("Pwd: ") + print("no exception") +except KeyboardInterrupt: + print("interrupted") +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": CTRL_C_CODE}) +def test_getpass_ctrl_c_raises_keyboard_interrupt(circuitpython): + """Sending Ctrl+C while getpass is reading raises KeyboardInterrupt.""" + circuitpython.serial.wait_for("Pwd:") + circuitpython.serial.write("\x03") + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "interrupted" in output + assert "no exception" not in output + assert "done" in output + + +CTRL_D_EMPTY_CODE = """\ +import getpass + +print("ready") +try: + getpass.getpass("Pwd: ") + print("no exception") +except EOFError: + print("eof") +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": CTRL_D_EMPTY_CODE}) +def test_getpass_ctrl_d_empty_raises_eof(circuitpython): + """Ctrl+D with an empty buffer raises EOFError.""" + circuitpython.serial.wait_for("Pwd:") + circuitpython.serial.write("\x04") + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "eof" in output + assert "no exception" not in output + assert "done" in output + + +EMPTY_INPUT_CODE = """\ +import getpass + +print("ready") +pw = getpass.getpass("Pwd: ") +print(f"length: {len(pw)}") +print(f"empty: {pw == ''}") +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": EMPTY_INPUT_CODE}) +def test_getpass_empty_input(circuitpython): + """Pressing return immediately yields an empty string.""" + circuitpython.serial.wait_for("Pwd:") + circuitpython.serial.write("\r") + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "length: 0" in output + assert "empty: True" in output + assert "done" in output diff --git a/ports/zephyr-cp/tests/test_hashlib.py b/ports/zephyr-cp/tests/test_hashlib.py new file mode 100644 index 00000000000..94463ba1e99 --- /dev/null +++ b/ports/zephyr-cp/tests/test_hashlib.py @@ -0,0 +1,152 @@ +# SPDX-FileCopyrightText: 2026 Tim Cocks for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""Test the hashlib module against CPython hashlib.""" + +import hashlib + +import pytest + + +SHORT_DATA = b"CircuitPython!" +CHUNK_A = b"Hello, " +CHUNK_B = b"CircuitPython world!" +LONG_DATA = b"The quick brown fox jumps over the lazy dog." * 64 + + +SHA256_CODE = """\ +import hashlib + +h = hashlib.new("sha256", b"CircuitPython!") +print(f"digest_size: {h.digest_size}") +print(f"digest_hex: {h.digest().hex()}") +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": SHA256_CODE}) +def test_hashlib_sha256_basic(circuitpython): + """sha256 digest on a small buffer matches CPython hashlib.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + expected = hashlib.sha256(SHORT_DATA).hexdigest() + assert "digest_size: 32" in output + assert f"digest_hex: {expected}" in output + assert "done" in output + + +SHA1_CODE = """\ +import hashlib + +h = hashlib.new("sha1", b"CircuitPython!") +print(f"digest_size: {h.digest_size}") +print(f"digest_hex: {h.digest().hex()}") +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": SHA1_CODE}) +def test_hashlib_sha1_basic(circuitpython): + """sha1 digest on a small buffer matches CPython hashlib.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + expected = hashlib.sha1(SHORT_DATA).hexdigest() + assert "digest_size: 20" in output + assert f"digest_hex: {expected}" in output + assert "done" in output + + +UPDATE_CODE = """\ +import hashlib + +h = hashlib.new("sha256") +h.update(b"Hello, ") +h.update(b"CircuitPython world!") +print(f"chunked_hex: {h.digest().hex()}") + +h2 = hashlib.new("sha256", b"Hello, CircuitPython world!") +print(f"oneshot_hex: {h2.digest().hex()}") +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": UPDATE_CODE}) +def test_hashlib_sha256_update_chunks(circuitpython): + """Multiple update() calls produce the same digest as a single buffer, and match CPython.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + expected = hashlib.sha256(CHUNK_A + CHUNK_B).hexdigest() + assert f"chunked_hex: {expected}" in output + assert f"oneshot_hex: {expected}" in output + assert "done" in output + + +LONG_CODE = """\ +import hashlib + +data = b"The quick brown fox jumps over the lazy dog." * 64 +h = hashlib.new("sha256", data) +print(f"sha256_hex: {h.digest().hex()}") + +h1 = hashlib.new("sha1", data) +print(f"sha1_hex: {h1.digest().hex()}") +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": LONG_CODE}) +def test_hashlib_long_input(circuitpython): + """Digests of a multi-block input match CPython for both sha1 and sha256.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert f"sha256_hex: {hashlib.sha256(LONG_DATA).hexdigest()}" in output + assert f"sha1_hex: {hashlib.sha1(LONG_DATA).hexdigest()}" in output + assert "done" in output + + +EMPTY_CODE = """\ +import hashlib + +h = hashlib.new("sha256", b"") +print(f"empty256: {h.digest().hex()}") + +h = hashlib.new("sha1", b"") +print(f"empty1: {h.digest().hex()}") +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": EMPTY_CODE}) +def test_hashlib_empty_input(circuitpython): + """Empty-input digests match CPython well-known values.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert f"empty256: {hashlib.sha256(b'').hexdigest()}" in output + assert f"empty1: {hashlib.sha1(b'').hexdigest()}" in output + assert "done" in output + + +BAD_ALGO_CODE = """\ +import hashlib + +try: + hashlib.new("md5", b"data") +except ValueError: + print("bad_algo: ValueError") +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": BAD_ALGO_CODE}) +def test_hashlib_unsupported_algorithm(circuitpython): + """Unsupported algorithm names raise ValueError.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "bad_algo: ValueError" in output + assert "done" in output diff --git a/ports/zephyr-cp/tests/test_i2c.py b/ports/zephyr-cp/tests/test_i2c.py new file mode 100644 index 00000000000..ec5229faa2f --- /dev/null +++ b/ports/zephyr-cp/tests/test_i2c.py @@ -0,0 +1,102 @@ +# SPDX-FileCopyrightText: 2025 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""Test I2C functionality on native_sim.""" + +import pytest + +I2C_SCAN_CODE = """\ +import board + +i2c = board.I2C() +while not i2c.try_lock(): + pass +devices = i2c.scan() +print(f"I2C devices: {[hex(d) for d in devices]}") +i2c.unlock() +i2c.deinit() +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": I2C_SCAN_CODE}) +def test_i2c_scan(circuitpython): + """Test I2C bus scanning finds emulated devices. + + The AT24 EEPROM emulator responds to zero-length probe writes, + so it should appear in scan results at address 0x50. + """ + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "I2C devices:" in output + # AT24 EEPROM should be at address 0x50 + assert "0x50" in output + assert "done" in output + + +AT24_READ_CODE = """\ +import board + +i2c = board.I2C() +while not i2c.try_lock(): + pass + +# AT24 EEPROM at address 0x50 +AT24_ADDR = 0x50 + +# Read first byte from address 0 +result = bytearray(1) +try: + i2c.writeto_then_readfrom(AT24_ADDR, bytes([0x00]), result) + value = result[0] + print(f"AT24 byte 0: 0x{value:02X}") + # Fresh EEPROM should be 0xFF + if value == 0xFF: + print("eeprom_valid") + else: + print(f"unexpected value: expected 0xFF, got 0x{value:02X}") +except OSError as e: + print(f"I2C error: {e}") + +i2c.unlock() +i2c.deinit() +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": AT24_READ_CODE}) +def test_i2c_at24_read(circuitpython): + """Test reading from AT24 EEPROM emulator.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "AT24 byte 0: 0xFF" in output + assert "eeprom_valid" in output + assert "done" in output + + +@pytest.mark.circuitpy_drive({"code.py": I2C_SCAN_CODE}) +@pytest.mark.disable_i2c_devices("eeprom@50") +def test_i2c_device_disabled(circuitpython): + """Test that disabled I2C device doesn't appear in scan.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "I2C devices:" in output + # AT24 at 0x50 should NOT appear when disabled + assert "0x50" not in output + assert "done" in output + + +@pytest.mark.circuitpy_drive({"code.py": AT24_READ_CODE}) +@pytest.mark.disable_i2c_devices("eeprom@50") +def test_i2c_device_disabled_communication_fails(circuitpython): + """Test that communication with disabled I2C device fails.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + # Should get an I2C error when trying to communicate + assert "I2C error" in output + assert "eeprom_valid" not in output + assert "done" in output diff --git a/ports/zephyr-cp/tests/test_keypad.py b/ports/zephyr-cp/tests/test_keypad.py new file mode 100644 index 00000000000..8deb182fd6a --- /dev/null +++ b/ports/zephyr-cp/tests/test_keypad.py @@ -0,0 +1,100 @@ +# SPDX-FileCopyrightText: 2026 Dan Halbert for Adafruit Industries LLC +# SPDX-License-Identifier: MIT + +"""Test keypad functionality on native_sim.""" + +import re + +import pytest + + +KEYS_CODE = """\ +import time +import keypad +import microcontroller + +keys = keypad.Keys( + (microcontroller.pin.P_01, microcontroller.pin.P_02), + value_when_pressed={value_when_pressed}, + pull=True, +) +event = keypad.Event() +print(f"t_abs={{time.monotonic():.3f}} start") + +while time.monotonic() < 7.0: + if keys.events.get_into(event): + print( + f"t_abs={{time.monotonic():.3f}} key={{event.key_number}} " + f"pressed={{event.pressed}} ts={{event.timestamp}}" + ) + time.sleep(0.01) + +print(f"t_abs={{time.monotonic():.3f}} done") +""" + + +def keys_trace(pressed: int) -> dict: + """Press and release key 0 at 4.0-4.5 s, then key 1 at 5.0-5.5 s.""" + released = 1 - pressed + return { + "gpio_emul.01": [ + (4_000_000_000, pressed), + (4_500_000_000, released), + ], + "gpio_emul.02": [ + (5_000_000_000, pressed), + (5_500_000_000, released), + ], + } + + +# (key_number, pressed, trace time in seconds) +EXPECTED_EVENTS = [ + (0, True, 4.0), + (0, False, 4.5), + (1, True, 5.0), + (1, False, 5.5), +] + +EVENT_RE = re.compile(r"t_abs=([0-9.]+) key=(\d+) pressed=(True|False) ts=(\d+)") + + +def check_keys_events(output: str) -> None: + start_match = re.search(r"t_abs=([0-9.]+) start", output) + assert start_match is not None + # The trace only reaches pins that are already inputs. + assert float(start_match.group(1)) < 4.0 + + events = [ + (float(t_abs), int(key), pressed == "True", int(ts)) + for t_abs, key, pressed, ts in EVENT_RE.findall(output) + ] + assert [(key, pressed) for _, key, pressed, _ in events] == [ + (key, pressed) for key, pressed, _ in EXPECTED_EVENTS + ] + + # Seen within one scan interval plus one poll of the trace edge. + for (t_abs, _, _, _), (_, _, trace_time) in zip(events, EXPECTED_EVENTS): + assert trace_time <= t_abs <= trace_time + 0.1 + + # Event timestamps are in ms; each key is held for 500 ms. + for press, release in ((events[0], events[1]), (events[2], events[3])): + assert abs((release[3] - press[3]) - 500) <= 50 + + assert "done" in output + + +@pytest.mark.circuitpy_drive({"code.py": KEYS_CODE.format(value_when_pressed=False)}) +@pytest.mark.input_trace(keys_trace(pressed=0)) +def test_keypad_keys_active_low(circuitpython): + """Keys with pull-ups reports presses when a trace pulls the pins low.""" + circuitpython.wait_until_done() + check_keys_events(circuitpython.serial.all_output) + + +@pytest.mark.circuitpy_drive({"code.py": KEYS_CODE.format(value_when_pressed=True)}) +@pytest.mark.input_trace(keys_trace(pressed=1)) +def test_keypad_keys_active_high(circuitpython): + """Keys with pull-downs reports presses when a trace drives the pins high.""" + circuitpython.wait_until_done() + check_keys_events(circuitpython.serial.all_output) diff --git a/ports/zephyr-cp/tests/test_lvfontio.py b/ports/zephyr-cp/tests/test_lvfontio.py new file mode 100644 index 00000000000..c79bbfed591 --- /dev/null +++ b/ports/zephyr-cp/tests/test_lvfontio.py @@ -0,0 +1,155 @@ +# SPDX-FileCopyrightText: 2025 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""lvfontio OnDiskFont tests that run against every filesystem the port supports. + +The font file is preloaded onto the simulated CIRCUITPY drive with the +``circuitpy_drive`` marker, so the same expectations run against FAT +(``native_native_sim``) and littlefs (``native_native_sim_lfs``). This checks +that OnDiskFont's supervisor filesystem API usage works on both. +""" + +import shutil +from pathlib import Path + +import pytest +from PIL import Image + +from .conftest import FILESYSTEM_SIMULATORS + +FONT = (Path(__file__).parent / "lvfontio" / "unifont-16.0.02-ja.bin").read_bytes() + +# あ in UTF-8: full-width (16px advance) glyph found through the fmt 0 (sparse) +# cmap subtable, unlike ASCII which comes from the fmt 2 (range) subtable. + +CODE = """\ +import displayio +import lvfontio +import terminalio + +font = lvfontio.OnDiskFont("/fonts/unifont-ja.bin", max_glyphs=8) +w, h = font.get_bounding_box() +print("bbox:", w, h) +print("bitmap:", font.bitmap.width, font.bitmap.height) + +# Render through terminalio to force glyph caching, which reads the font file +# via the supervisor filesystem API. The kana is full-width and occupies two +# adjacent cache slots. +grid = displayio.TileGrid( + font.bitmap, + pixel_shader=displayio.Palette(2), + width=8, + height=1, + tile_width=w, + tile_height=h, +) +terminal = terminalio.Terminal(grid, font) +terminal.write("AあB") +print("tiles:", [grid[x, 0] for x in range(4)]) + +lit = 0 +for y in range(font.bitmap.height): + for x in range(font.bitmap.width): + if font.bitmap[x, y]: + lit += 1 +print("lit pixels:", lit) + +try: + lvfontio.OnDiskFont("/fonts/missing.fnt") + print("missing: no error") +except ValueError: + print("missing: ValueError") +print("done") +""" + + +@pytest.mark.parametrize("board", FILESYSTEM_SIMULATORS, indirect=True) +@pytest.mark.circuitpy_drive({"code.py": CODE, "fonts/unifont-ja.bin": FONT}) +@pytest.mark.duration(30) +def test_ondiskfont_render(circuitpython): + """OnDiskFont loads, caches glyphs and renders text from the filesystem.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "bbox: 8 16" in output + # The glyph cache is 8 slots of 8px; the font is 16px tall. + assert "bitmap: 64 16" in output + # ASCII 'A' cached in one slot; the full-width kana needed two adjacent + # slots and shifted the next glyph over by two. + assert "tiles: [1, 2, 3, 4]" in output + # Glyph bitmaps were actually read from the font file. + assert "lit pixels: 0" not in output + assert "missing: ValueError" in output + assert "done" in output + + +DISPLAY_CODE = """\ +import board +import displayio +import lvfontio +import terminalio +import time + +font = lvfontio.OnDiskFont("/fonts/unifont-ja.bin", max_glyphs=8) +w, h = font.get_bounding_box() +palette = displayio.Palette(2) +palette[1] = 0xFFFFFF +root = displayio.Group() +grid = displayio.TileGrid( + font.bitmap, + pixel_shader=palette, + width=8, + height=1, + tile_width=w, + tile_height=h, + x=8, + y=24, +) +root.append(grid) +# Replacing the root group hides the console; the frame is then just the +# rendered text, independent of the console boot output. +board.DISPLAY.root_group = root +terminal = terminalio.Terminal(grid, font) +terminal.write("AあB") +print("done") +while True: + time.sleep(1) +""" + + +def _read_image(path): + with Image.open(path) as img: + rgb = img.convert("RGB") + return rgb.width, rgb.height, rgb.tobytes() + + +@pytest.mark.parametrize("board", FILESYSTEM_SIMULATORS, indirect=True) +@pytest.mark.circuitpy_drive({"code.py": DISPLAY_CODE, "fonts/unifont-ja.bin": FONT}) +@pytest.mark.display(capture_times_ns=[4_000_000_000]) +@pytest.mark.duration(8) +def test_ondiskfont_display_golden(request, circuitpython): + """Rendered lvfontio text on the display matches the golden image. + + The code.py replaces the console root group, so the captured frame is + exactly the 'AあB' text rendered from the font file through the + supervisor filesystem API — independent of console output. + """ + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "done" in output + + captures = circuitpython.display_capture_paths() + if not captures or not captures[0].exists(): + pytest.skip("display capture was not produced") + + golden_path = Path(__file__).parent / "lvfontio" / "golden" / "lvfontio_terminal_320x240.png" + if request.config.getoption("--update-goldens"): + golden_path.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(captures[0], golden_path) + return + + gw, gh, gpx = _read_image(golden_path) + dw, dh, dpx = _read_image(captures[0]) + assert (dw, dh) == (gw, gh) + assert gpx == dpx, "captured frame does not match the golden image" diff --git a/ports/zephyr-cp/tests/test_msgpack.py b/ports/zephyr-cp/tests/test_msgpack.py new file mode 100644 index 00000000000..800652af578 --- /dev/null +++ b/ports/zephyr-cp/tests/test_msgpack.py @@ -0,0 +1,184 @@ +# SPDX-FileCopyrightText: 2026 Tim Cocks for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""Test the msgpack module.""" + +import pytest + + +ROUNDTRIP_CODE = """\ +import msgpack +from io import BytesIO + +obj = {"list": [True, False, None, 1, 3.125], "str": "blah"} +b = BytesIO() +msgpack.pack(obj, b) +encoded = b.getvalue() +print(f"encoded_len: {len(encoded)}") +print(f"encoded_hex: {encoded.hex()}") + +b.seek(0) +decoded = msgpack.unpack(b) +print(f"decoded: {decoded}") +print(f"match: {decoded == obj}") +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": ROUNDTRIP_CODE}) +def test_msgpack_roundtrip(circuitpython): + """Pack and unpack a dict containing the basic msgpack types.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "match: True" in output + assert "done" in output + + +USE_LIST_CODE = """\ +import msgpack +from io import BytesIO + +b = BytesIO() +msgpack.pack([1, 2, 3], b) + +b.seek(0) +as_list = msgpack.unpack(b) +print(f"as_list: {as_list} type={type(as_list).__name__}") + +b.seek(0) +as_tuple = msgpack.unpack(b, use_list=False) +print(f"as_tuple: {as_tuple} type={type(as_tuple).__name__}") +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": USE_LIST_CODE}) +def test_msgpack_use_list(circuitpython): + """use_list=False should return a tuple instead of a list.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "as_list: [1, 2, 3] type=list" in output + assert "as_tuple: (1, 2, 3) type=tuple" in output + assert "done" in output + + +EXTTYPE_CODE = """\ +from msgpack import pack, unpack, ExtType +from io import BytesIO + +class MyClass: + def __init__(self, val): + self.value = val + +data = MyClass(b"my_value") + +def encoder(obj): + if isinstance(obj, MyClass): + return ExtType(1, obj.value) + return f"no encoder for {obj}" + +def decoder(code, data): + if code == 1: + return MyClass(data) + return f"no decoder for type {code}" + +buf = BytesIO() +pack(data, buf, default=encoder) +buf.seek(0) +decoded = unpack(buf, ext_hook=decoder) +print(f"decoded_type: {type(decoded).__name__}") +print(f"decoded_value: {decoded.value}") +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": EXTTYPE_CODE}) +def test_msgpack_exttype(circuitpython): + """ExtType with a custom encoder/decoder should round-trip.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "decoded_type: MyClass" in output + assert "decoded_value: b'my_value'" in output + assert "done" in output + + +EXTTYPE_PROPS_CODE = """\ +from msgpack import ExtType + +e = ExtType(5, b"hello") +print(f"code: {e.code}") +print(f"data: {e.data}") + +e.code = 10 +print(f"new_code: {e.code}") + +try: + ExtType(128, b"x") +except (ValueError, OverflowError) as ex: + print(f"range_error: {type(ex).__name__}") + +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": EXTTYPE_PROPS_CODE}) +def test_msgpack_exttype_properties(circuitpython): + """ExtType exposes code/data as read/write properties and rejects out-of-range codes.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "code: 5" in output + assert "data: b'hello'" in output + assert "new_code: 10" in output + assert "range_error:" in output + assert "done" in output + + +INT_BOUNDARY_CODE = """\ +import msgpack +from io import BytesIO + +CASES = ( + (127, "7f"), + (128, "cc80"), + (255, "ccff"), + (256, "cd0100"), + (65535, "cdffff"), + (65536, "ce00010000"), + (2**32 - 1, "ceffffffff"), + (2**32, "cf0000000100000000"), + (2**64 - 1, "cfffffffffffffffff"), + (-32, "e0"), + (-33, "d0df"), + (-129, "d1ff7f"), + (-32769, "d2ffff7fff"), + (-(2**31) - 1, "d3ffffffff7fffffff"), + (-(2**63), "d38000000000000000"), +) +for value, expected in CASES: + b = BytesIO() + msgpack.pack(value, b) + b.seek(0) + if b.getvalue().hex() != expected or msgpack.unpack(b) != value: + print(f"bad: {value} {b.getvalue().hex()}") + +for value in (2**64, -(2**63) - 1, -(2**64)): + b = BytesIO() + msgpack.pack(value, b, default=lambda obj: "big") + print(f"default: {b.getvalue().hex()}") +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": INT_BOUNDARY_CODE}) +def test_msgpack_int_boundaries(circuitpython): + """Ints use the shortest format, and those beyond 64 bits go to the default handler.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "bad:" not in output + assert output.count("default: a3626967") == 3 + assert "done" in output diff --git a/ports/zephyr-cp/tests/test_nvm.py b/ports/zephyr-cp/tests/test_nvm.py new file mode 100644 index 00000000000..910cf6eb052 --- /dev/null +++ b/ports/zephyr-cp/tests/test_nvm.py @@ -0,0 +1,73 @@ +# SPDX-FileCopyrightText: 2025 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""Test NVM functionality on native_sim.""" + +import pytest + + +NVM_BASIC_CODE = """\ +import microcontroller + +nvm = microcontroller.nvm +print(f"nvm length: {len(nvm)}") + +# Write some bytes +nvm[0] = 42 +nvm[1] = 99 +print(f"nvm[0]: {nvm[0]}") +print(f"nvm[1]: {nvm[1]}") + +# Write a slice +nvm[2:5] = b"\\x01\\x02\\x03" +print(f"nvm[2:5]: {list(nvm[2:5])}") + +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": NVM_BASIC_CODE}) +def test_nvm_read_write(circuitpython): + """Test basic NVM read and write operations.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "nvm length: 8192" in output + assert "nvm[0]: 42" in output + assert "nvm[1]: 99" in output + assert "nvm[2:5]: [1, 2, 3]" in output + assert "done" in output + + +NVM_PERSIST_CODE = """\ +import microcontroller + +nvm = microcontroller.nvm +value = nvm[0] +print(f"nvm[0]: {value}") + +if value == 255: + # First run: write a marker + nvm[0] = 123 + print("wrote marker") +else: + print(f"marker found: {value}") + +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": NVM_PERSIST_CODE}) +@pytest.mark.port_resets(3) +def test_nvm_persists_across_reload(circuitpython): + """Test that NVM data persists across soft reloads.""" + circuitpython.serial.wait_for("wrote marker") + # Trigger soft reload + circuitpython.serial.write("\x04") + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "nvm[0]: 255" in output + assert "wrote marker" in output + assert "marker found: 123" in output + assert "done" in output diff --git a/ports/zephyr-cp/tests/test_os.py b/ports/zephyr-cp/tests/test_os.py new file mode 100644 index 00000000000..0588ee184b9 --- /dev/null +++ b/ports/zephyr-cp/tests/test_os.py @@ -0,0 +1,31 @@ +# SPDX-FileCopyrightText: 2026 Dan Halbert for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""Test the os core module.""" + +import pytest + + +UNAME_CODE = """\ +import os + +u = os.uname() +print(f"sysname: {u.sysname}") +print(f"nodename: {u.nodename}") +print(f"machine: {u.machine}") +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": UNAME_CODE}) +def test_os_uname(circuitpython): + """sysname is "CircuitPython". With no Wi-Fi or Ethernet, nodename is the microcontroller name.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "sysname: CircuitPython" in output + nodename = output.split("nodename: ", 1)[1].split("\n", 1)[0].strip() + assert nodename + # machine is " with ". + assert f" with {nodename}" in output + assert "done" in output diff --git a/ports/zephyr-cp/tests/test_pwmio.py b/ports/zephyr-cp/tests/test_pwmio.py new file mode 100644 index 00000000000..f0a3309e1cf --- /dev/null +++ b/ports/zephyr-cp/tests/test_pwmio.py @@ -0,0 +1,273 @@ +# SPDX-FileCopyrightText: 2026 Dan Halbert for Adafruit Industries LLC +# SPDX-License-Identifier: MIT + +"""Test pwmio on native_sim. + +The emulated PWM controller (adafruit,pwm-emul) has one channel per gpio_emul +pin and two period groups that any channel can join, clocked at 16 MHz. It +records what pwm_set_cycles() receives on the counter tracks "pwm.NN.period" +and "pwm.NN.pulse". The tests check pwmio's own behavior and the grouping +rules every port shares, not any SoC's layout. +""" + +import pytest +from perfetto.trace_processor import TraceProcessor + +CLOCK = 16_000_000 + + +def _track_values(trace_file, track_name: str) -> list[int]: + tp = TraceProcessor(file_path=str(trace_file)) + result = tp.query( + f''' + SELECT c.value + FROM counter c + JOIN track t ON c.track_id = t.id + WHERE t.name = "{track_name}" + ORDER BY c.ts + ''' + ) + return [int(row.value) for row in result] + + +def _pulse(period: int, duty: int) -> int: + return period * duty // 0xFFFF + + +PWMIO_SETTINGS_CODE = """\ +import microcontroller +import pwmio + +pwm = pwmio.PWMOut(microcontroller.pin.P_05, frequency=1000, duty_cycle=0x4000) +print(f"frequency {pwm.frequency}") +pwm.duty_cycle = 0xC000 +pwm.duty_cycle = 0xFFFF +pwm.deinit() +print("done") +""" + + +@pytest.mark.duration(8.0) +@pytest.mark.circuitpy_drive({"code.py": PWMIO_SETTINGS_CODE}) +def test_pwmio_settings(circuitpython): + """Frequency becomes the period, duty the pulse, and deinit stops the output.""" + circuitpython.wait_until_done() + output = circuitpython.serial.all_output + assert "frequency 1000" in output + assert "done" in output + + period = CLOCK // 1000 + trace = circuitpython.trace_file + assert _track_values(trace, "pwm.05.period") == [period] * 4 + assert _track_values(trace, "pwm.05.pulse") == [ + _pulse(period, 0x4000), + _pulse(period, 0xC000), + period, + 0, + ] + + +PWMIO_FREQUENCY_CODE = """\ +import microcontroller +import pwmio + +pwm = pwmio.PWMOut(microcontroller.pin.P_05, frequency=12345) +print(f"frequency {pwm.frequency}") +pwm.deinit() +print("done") +""" + + +@pytest.mark.duration(8.0) +@pytest.mark.circuitpy_drive({"code.py": PWMIO_FREQUENCY_CODE}) +def test_pwmio_frequency_is_actual(circuitpython): + """frequency reports what the period produces, not what was requested.""" + circuitpython.wait_until_done() + output = circuitpython.serial.all_output + assert "done" in output + + period = _track_values(circuitpython.trace_file, "pwm.05.period")[0] + assert period == CLOCK // 12345 + # 16 MHz / 1296 = 12345.7 Hz, reported to the nearest Hz. + assert f"frequency {round(CLOCK / period)}" in output + + +PWMIO_VARIABLE_FREQUENCY_CODE = """\ +import microcontroller +import pwmio + +pwm = pwmio.PWMOut( + microcontroller.pin.P_05, frequency=440, duty_cycle=0x8000, variable_frequency=True +) +pwm.frequency = 880 +print(f"frequency {pwm.frequency}") +print("done") +""" + + +@pytest.mark.duration(8.0) +@pytest.mark.circuitpy_drive({"code.py": PWMIO_VARIABLE_FREQUENCY_CODE}) +def test_pwmio_variable_frequency_change(circuitpython): + """Changing the frequency writes a new period and keeps the duty cycle.""" + circuitpython.wait_until_done() + output = circuitpython.serial.all_output + assert "frequency 880" in output + assert "done" in output + + trace = circuitpython.trace_file + assert _track_values(trace, "pwm.05.period") == [CLOCK // 440, CLOCK // 880] + assert _track_values(trace, "pwm.05.pulse") == [ + _pulse(CLOCK // 440, 0x8000), + _pulse(CLOCK // 880, 0x8000), + ] + + +PWMIO_INVALID_FREQUENCY_CODE = """\ +import microcontroller +import pwmio + +for frequency in (0, 20_000_000): + try: + pwmio.PWMOut(microcontroller.pin.P_05, frequency=frequency) + print(f"{frequency} ok") + except ValueError: + print(f"{frequency} ValueError") +fastest = pwmio.PWMOut(microcontroller.pin.P_05, frequency=8_000_000) +print(f"fastest {fastest.frequency}") +print("done") +""" + + +@pytest.mark.duration(8.0) +@pytest.mark.circuitpy_drive({"code.py": PWMIO_INVALID_FREQUENCY_CODE}) +def test_pwmio_invalid_frequency(circuitpython): + """Frequencies the clock can't produce raise ValueError; the fastest one works.""" + circuitpython.wait_until_done() + output = circuitpython.serial.all_output + assert "0 ValueError" in output + assert "20000000 ValueError" in output + # 16 MHz / 8 MHz = a 2-cycle period, the shortest allowed. + assert "fastest 8000000" in output + assert "done" in output + + +PWMIO_PIN_CLAIM_CODE = """\ +import digitalio +import microcontroller +import pwmio + +p = microcontroller.pin +dio = digitalio.DigitalInOut(p.P_05) +try: + pwmio.PWMOut(p.P_05) + print("over DigitalInOut ok") +except ValueError: + print("over DigitalInOut ValueError") +dio.deinit() + +pwm = pwmio.PWMOut(p.P_05, frequency=1000) +try: + pwmio.PWMOut(p.P_05, frequency=1000) + print("second PWMOut ok") +except ValueError: + print("second PWMOut ValueError") +pwm.deinit() + +dio = digitalio.DigitalInOut(p.P_05) +print("DigitalInOut after deinit ok") +dio.deinit() +again = pwmio.PWMOut(p.P_05, frequency=2000) +print(f"PWMOut after deinit {again.frequency}") +print("done") +""" + + +@pytest.mark.duration(8.0) +@pytest.mark.circuitpy_drive({"code.py": PWMIO_PIN_CLAIM_CODE}) +def test_pwmio_pin_claims(circuitpython): + """A PWMOut claims its pin while it lives and releases it on deinit.""" + circuitpython.wait_until_done() + output = circuitpython.serial.all_output + assert "over DigitalInOut ValueError" in output + assert "second PWMOut ValueError" in output + assert "DigitalInOut after deinit ok" in output + assert "PWMOut after deinit 2000" in output + assert "done" in output + + +PWMIO_GROUPS_CODE = """\ +import microcontroller +import pwmio + +p = microcontroller.pin +shared = [pwmio.PWMOut(pin, frequency=1000) for pin in (p.P_05, p.P_06, p.P_07)] +other = pwmio.PWMOut(p.P_08, frequency=2000) +print("two groups ok") +try: + pwmio.PWMOut(p.P_09, frequency=3000) + print("third frequency ok") +except RuntimeError: + print("third frequency RuntimeError") +for pwm in shared: + pwm.deinit() +third = pwmio.PWMOut(p.P_09, frequency=3000) +print("third frequency after deinit ok") +print("done") +""" + + +@pytest.mark.duration(8.0) +@pytest.mark.circuitpy_drive({"code.py": PWMIO_GROUPS_CODE}) +def test_pwmio_same_frequency_shares_a_group(circuitpython): + """Equal frequencies share a group; with every group taken a new frequency fails + until a group is freed.""" + circuitpython.wait_until_done() + output = circuitpython.serial.all_output + assert "two groups ok" in output + assert "third frequency RuntimeError" in output + assert "third frequency after deinit ok" in output + assert "done" in output + + trace = circuitpython.trace_file + for pin in (5, 6, 7): + assert _track_values(trace, f"pwm.{pin:02}.period")[0] == CLOCK // 1000 + assert _track_values(trace, "pwm.08.period")[0] == CLOCK // 2000 + assert _track_values(trace, "pwm.09.period") == [CLOCK // 3000] + + +PWMIO_VARIABLE_EXCLUSIVE_CODE = """\ +import microcontroller +import pwmio + +p = microcontroller.pin +var = pwmio.PWMOut(p.P_05, frequency=440, variable_frequency=True) +other = pwmio.PWMOut(p.P_06, frequency=440) +print("other ok") +try: + pwmio.PWMOut(p.P_07, frequency=300) + print("300 ok") +except RuntimeError: + print("300 RuntimeError") +joins = pwmio.PWMOut(p.P_08, frequency=440) +print("joins ok") +var.deinit() +after = pwmio.PWMOut(p.P_09, frequency=300) +print("300 after deinit ok") +print("done") +""" + + +@pytest.mark.duration(8.0) +@pytest.mark.circuitpy_drive({"code.py": PWMIO_VARIABLE_EXCLUSIVE_CODE}) +def test_pwmio_variable_frequency_has_own_group(circuitpython): + """A variable-frequency PWMOut shares its group with nobody.""" + circuitpython.wait_until_done() + output = circuitpython.serial.all_output + # The 440 Hz fixed-frequency PWMOut can't join the variable one's group. + assert "other ok" in output + # Both groups are taken. + assert "300 RuntimeError" in output + # Another fixed 440 Hz PWMOut joins the fixed 440 Hz group. + assert "joins ok" in output + assert "300 after deinit ok" in output + assert "done" in output diff --git a/ports/zephyr-cp/tests/test_reset.py b/ports/zephyr-cp/tests/test_reset.py new file mode 100644 index 00000000000..af64cee726d --- /dev/null +++ b/ports/zephyr-cp/tests/test_reset.py @@ -0,0 +1,39 @@ +# SPDX-FileCopyrightText: 2025 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""Test that a plain microcontroller.reset() reboots back into CircuitPython. + +This is like the safe-mode test (test_saved_word.py) but without changing the +run mode: no sentinel is armed, so the reboot should be a normal boot that +runs code.py again instead of entering safe mode. +""" + +import pytest + + +RESET_CODE = """\ +import microcontroller +reason = microcontroller.cpu.reset_reason +print("reset reason:", reason) +if reason == microcontroller.ResetReason.POWER_ON: + print("resetting") + microcontroller.reset() +else: + print("not resetting") +""" + + +@pytest.mark.circuitpy_drive({"code.py": RESET_CODE}) +@pytest.mark.duration(30) +@pytest.mark.port_resets(4) # Two startups and two code.py +def test_plain_reset_reboots_into_circuitpython(circuitpython): + """microcontroller.reset() reboots into code.py and reports a software reset.""" + circuitpython.serial.wait_for("resetting", timeout=30) + + assert circuitpython.reconnect_serial(timeout=30), "simulator did not reboot" + + circuitpython.serial.wait_for("not resetting", timeout=30) + + all_output = circuitpython.serial.all_output + assert "reset reason: microcontroller.ResetReason.SOFTWARE" in all_output + assert "Running in safe mode" not in all_output diff --git a/ports/zephyr-cp/tests/test_rotaryio.py b/ports/zephyr-cp/tests/test_rotaryio.py new file mode 100644 index 00000000000..e9a5c1913cb --- /dev/null +++ b/ports/zephyr-cp/tests/test_rotaryio.py @@ -0,0 +1,132 @@ +# SPDX-FileCopyrightText: 2026 Scott Shawcroft for Adafruit Industries LLC +# SPDX-License-Identifier: MIT + +"""Test rotaryio functionality on native_sim.""" + +import pytest + + +ROTARY_CODE_5S = """\ +import time +import microcontroller +import rotaryio + +encoder = rotaryio.IncrementalEncoder(microcontroller.pin.P_01, microcontroller.pin.P_02) + +time.sleep(5.0) # Sleep long enough for trace events to complete +print(f"position={encoder.position}") +print("done") +""" + + +ROTARY_CODE_7S = """\ +import time +import microcontroller +import rotaryio + +encoder = rotaryio.IncrementalEncoder(microcontroller.pin.P_01, microcontroller.pin.P_02) + +time.sleep(7.0) # Sleep long enough for trace events to complete +print(f"position={encoder.position}") +print("done") +""" + + +CLOCKWISE_TRACE = { + "gpio_emul.01": [ + (4_000_000_000, 0), # 4.0s: initial state (low) + (4_100_000_000, 1), # 4.1s: A goes high (A leads) + (4_300_000_000, 0), # 4.3s: A goes low + ], + "gpio_emul.02": [ + (4_000_000_000, 0), # 4.0s: initial state (low) + (4_200_000_000, 1), # 4.2s: B goes high (B follows) + (4_400_000_000, 0), # 4.4s: B goes low + ], +} + +COUNTERCLOCKWISE_TRACE = { + "gpio_emul.01": [ + (4_000_000_000, 0), # 4.0s: initial state (low) + (4_200_000_000, 1), # 4.2s: A goes high (A follows) + (4_400_000_000, 0), # 4.4s: A goes low + ], + "gpio_emul.02": [ + (4_000_000_000, 0), # 4.0s: initial state (low) + (4_100_000_000, 1), # 4.1s: B goes high (B leads) + (4_300_000_000, 0), # 4.3s: B goes low + ], +} + +BOTH_DIRECTIONS_TRACE = { + "gpio_emul.01": [ + (4_000_000_000, 0), # Initial state + # First clockwise detent + (4_100_000_000, 1), # A rises (leads) + (4_300_000_000, 0), # A falls + # Second clockwise detent + (4_500_000_000, 1), # A rises (leads) + (4_700_000_000, 0), # A falls + # First counter-clockwise detent + (5_000_000_000, 1), # A rises (follows) + (5_200_000_000, 0), # A falls + # Second counter-clockwise detent + (5_400_000_000, 1), # A rises (follows) + (5_600_000_000, 0), # A falls + # Third counter-clockwise detent + (5_800_000_000, 1), # A rises (follows) + (6_000_000_000, 0), # A falls + ], + "gpio_emul.02": [ + (4_000_000_000, 0), # Initial state + # First clockwise detent + (4_200_000_000, 1), # B rises (follows) + (4_400_000_000, 0), # B falls + # Second clockwise detent + (4_600_000_000, 1), # B rises (follows) + (4_800_000_000, 0), # B falls + # First counter-clockwise detent + (4_900_000_000, 1), # B rises (leads) + (5_100_000_000, 0), # B falls + # Second counter-clockwise detent + (5_300_000_000, 1), # B rises (leads) + (5_500_000_000, 0), # B falls + # Third counter-clockwise detent + (5_700_000_000, 1), # B rises (leads) + (5_900_000_000, 0), # B falls + ], +} + + +@pytest.mark.circuitpy_drive({"code.py": ROTARY_CODE_5S}) +@pytest.mark.input_trace(CLOCKWISE_TRACE) +def test_rotaryio_incrementalencoder_clockwise(circuitpython): + """Test clockwise rotation increments position.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "position=1" in output + assert "done" in output + + +@pytest.mark.circuitpy_drive({"code.py": ROTARY_CODE_5S}) +@pytest.mark.input_trace(COUNTERCLOCKWISE_TRACE) +def test_rotaryio_incrementalencoder_counterclockwise(circuitpython): + """Test counter-clockwise rotation decrements position.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "position=-1" in output + assert "done" in output + + +@pytest.mark.duration(12.0) +@pytest.mark.circuitpy_drive({"code.py": ROTARY_CODE_7S}) +@pytest.mark.input_trace(BOTH_DIRECTIONS_TRACE) +def test_rotaryio_incrementalencoder_both_directions(circuitpython): + """Test rotation in both directions: 2 clockwise, then 3 counter-clockwise.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "position=-1" in output + assert "done" in output diff --git a/ports/zephyr-cp/tests/test_rtc.py b/ports/zephyr-cp/tests/test_rtc.py new file mode 100644 index 00000000000..f0d85ae68a7 --- /dev/null +++ b/ports/zephyr-cp/tests/test_rtc.py @@ -0,0 +1,47 @@ +# SPDX-FileCopyrightText: 2026 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""Test the rtc module against native_sim's emulated RTC. + +On a fresh boot the RTC has never been set (the emulated driver has no +battery backup), so reading it must give the start of the CircuitPython +epoch, 2000-01-01, rather than an error. Setting the datetime must update +what time.localtime() reports, and the RTC must advance on its own. +""" + +import pytest + + +RTC_SET_CODE = """\ +import rtc +import time + +r = rtc.RTC() + +t = time.localtime() +print("UNSET:", t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec) + +r.datetime = time.struct_time((2025, 7, 4, 12, 34, 56, 4, -1, -1)) + +t = time.localtime() +print("SET:", t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec) + +time.sleep(2) +t = time.localtime() +print("ADVANCED:", t.tm_year, (t.tm_hour, t.tm_min, t.tm_sec) != (12, 34, 56)) + +try: + r.calibration = 1 +except NotImplementedError: + print("CALIBRATION NOT SUPPORTED") +""" + + +@pytest.mark.circuitpy_drive({"code.py": RTC_SET_CODE}) +@pytest.mark.duration(30) +def test_rtc_set_and_get(circuitpython): + """Setting rtc.RTC().datetime updates time.localtime() and advances.""" + circuitpython.serial.wait_for("UNSET: 2000 1 1", timeout=30) + circuitpython.serial.wait_for("SET: 2025 7 4 12 34 56", timeout=30) + circuitpython.serial.wait_for("ADVANCED: 2025 True", timeout=30) + circuitpython.serial.wait_for("CALIBRATION NOT SUPPORTED", timeout=30) diff --git a/ports/zephyr-cp/tests/test_saved_word.py b/ports/zephyr-cp/tests/test_saved_word.py new file mode 100644 index 00000000000..ac615f87247 --- /dev/null +++ b/ports/zephyr-cp/tests/test_saved_word.py @@ -0,0 +1,35 @@ +# SPDX-FileCopyrightText: 2025 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""Test that the safe-mode saved word survives a hard reboot on native_sim/bsim.""" + +import pytest + + +SAFE_MODE_RESET_CODE = """\ +import microcontroller +if microcontroller.cpu.reset_reason == microcontroller.ResetReason.POWER_ON: + microcontroller.on_next_reset(microcontroller.RunMode.SAFE_MODE) + print("resetting") + microcontroller.reset() +else: + print("not resetting") +""" + + +@pytest.mark.circuitpy_drive({"code.py": SAFE_MODE_RESET_CODE}) +@pytest.mark.duration(30) +@pytest.mark.port_resets(4) +def test_saved_word_survives_reboot_into_safe_mode(circuitpython): + """The saved word persists across a hard reboot and triggers safe mode.""" + circuitpython.serial.wait_for("resetting", timeout=30) + + # microcontroller.reset() re-execs the process; the UART PTY is O_CLOEXEC so + # a new one is opened after reboot. Reconnect to it. + assert circuitpython.reconnect_serial(timeout=30), "simulator did not reboot" + + # The next boot restores the saved word (the SAFE_MODE sentinel) and enters + # safe mode instead of running code.py. + circuitpython.serial.wait_for("Running in safe mode", timeout=30) + + assert "Running in safe mode" in circuitpython.serial.all_output diff --git a/ports/zephyr-cp/tests/test_spi.py b/ports/zephyr-cp/tests/test_spi.py new file mode 100644 index 00000000000..6ccfd4ec1a0 --- /dev/null +++ b/ports/zephyr-cp/tests/test_spi.py @@ -0,0 +1,54 @@ +# SPDX-FileCopyrightText: 2026 Vladimir Smitka +# SPDX-License-Identifier: MIT + +"""busio.SPI on native_sim, through the SPI loopback device.""" + +import pytest + +LOOPBACK_CODE = """\ +import board + +spi = board.SPI() +while not spi.try_lock(): + pass +spi.configure(baudrate=1_000_000) +bad = 0 +for n in (1, 31, 32, 33, 4096): + out = bytes(i * 7 & 0xFF for i in range(n)) + inb = bytearray(n) + spi.write_readinto(out, inb) + if inb != out: + bad += 1 + print("write_readinto", n, "differs") + spi.readinto(inb, write_value=0xA5) + if inb != b"\\xa5" * n: + bad += 1 + print("readinto 0xA5", n, "differs") + spi.readinto(inb) + if inb != bytes(n): + bad += 1 + print("readinto 0", n, "differs") + spi.write(out) +out = bytes(range(64)) +inb = bytearray(64) +spi.write_readinto(out, inb, out_start=8, out_end=40, in_start=8, in_end=40) +if inb[8:40] != out[8:40] or any(inb[:8]) or any(inb[40:]): + bad += 1 + print("slices differ") +spi.unlock() +spi.deinit() +print("frequency", spi.frequency if False else "ok") +print("bad", bad) +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": LOOPBACK_CODE}) +def test_spi_loopback(circuitpython): + """Blocking transfers come back through the loopback, including slices and reads.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "differs" not in output + assert "bad 0" in output + assert "done" in output diff --git a/ports/zephyr-cp/tests/test_ssl.py b/ports/zephyr-cp/tests/test_ssl.py new file mode 100644 index 00000000000..f091a2de6ce --- /dev/null +++ b/ports/zephyr-cp/tests/test_ssl.py @@ -0,0 +1,42 @@ +# SPDX-FileCopyrightText: 2025 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""Test ssl against a real server.""" + +import pytest + +CODE = """\ +import hostnetwork, socketpool, ssl + +pool = socketpool.SocketPool(hostnetwork.HostNetwork()) +print("start") +context = ssl.create_default_context() +sock = context.wrap_socket( + pool.socket(pool.AF_INET, pool.SOCK_STREAM), + server_hostname="www.adafruit.com", +) +sock.settimeout(30) +sock.connect(("www.adafruit.com", 443)) +print("connected") +sock.send(b"GET /api/quotes.php HTTP/1.0\\r\\nHost: www.adafruit.com\\r\\n\\r\\n") +buf = bytearray(1024) +n = sock.recv_into(buf) +print(bytes(buf[:n])) +sock.close() +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": CODE}) +@pytest.mark.duration(90) +def test_https_fetch(board, circuitpython): + """Fetch a page over TLS from the device.""" + circuitpython.serial.wait_for("start") + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "Traceback" not in output + assert "connected" in output + assert "HTTP/1.1 200 OK" in output + assert '"text"' in output # a quote from /api/quotes.php + assert "done" in output diff --git a/ports/zephyr-cp/tests/test_storage.py b/ports/zephyr-cp/tests/test_storage.py new file mode 100644 index 00000000000..002170f3266 --- /dev/null +++ b/ports/zephyr-cp/tests/test_storage.py @@ -0,0 +1,164 @@ +# SPDX-FileCopyrightText: 2026 Tim Cocks for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""Test the `storage` core module on native_sim.""" + +import pytest + + +REMOUNT_READWRITE_CODE = """\ +import storage +storage.remount("/", readonly=False) +with open("/rw.txt", "w") as f: + f.write("writable") +with open("/rw.txt", "r") as f: + print(f"content: {f.read()}") +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": REMOUNT_READWRITE_CODE}) +def test_storage_remount_readwrite(circuitpython): + """remount with readonly=False allows writes to /.""" + circuitpython.wait_until_done() + output = circuitpython.serial.all_output + assert "content: writable" in output + assert "done" in output + + +REMOUNT_READONLY_CODE = """\ +import storage +storage.remount("/", readonly=True) +try: + with open("/should_fail.txt", "w") as f: + f.write("nope") + print("unexpected: write succeeded") +except OSError as e: + print(f"caught OSError: errno={e.errno}") +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": REMOUNT_READONLY_CODE}) +def test_storage_remount_readonly_blocks_writes(circuitpython): + """remount with readonly=True prevents writes to /.""" + circuitpython.wait_until_done() + output = circuitpython.serial.all_output + assert "caught OSError" in output + assert "unexpected: write succeeded" not in output + assert "done" in output + + +GETMOUNT_CODE = """\ +import storage +mount = storage.getmount("/") +print(f"type: {type(mount).__name__}") +print(f"readonly: {mount.readonly}") +# label attribute should be accessible +print(f"label: {mount.label!r}") +print("done") +""" + + +@pytest.mark.fat_filesystem_only +@pytest.mark.circuitpy_drive({"code.py": GETMOUNT_CODE}) +def test_storage_getmount(circuitpython): + """getmount('/') returns the VfsFat object for the root mount.""" + circuitpython.wait_until_done() + output = circuitpython.serial.all_output + assert "type: VfsFat" in output + assert "readonly:" in output + assert "label:" in output + assert "done" in output + + +GETMOUNT_MISSING_CODE = """\ +import storage +try: + storage.getmount("/does_not_exist") + print("unexpected: getmount succeeded") +except OSError as e: + print(f"caught OSError: errno={e.errno}") +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": GETMOUNT_MISSING_CODE}) +def test_storage_getmount_missing(circuitpython): + """getmount on an unmounted path raises OSError.""" + circuitpython.wait_until_done() + output = circuitpython.serial.all_output + assert "caught OSError" in output + assert "unexpected: getmount succeeded" not in output + assert "done" in output + + +REMOUNT_PERSISTS_CODE = """\ +import storage +storage.remount("/", readonly=False) +with open("/persist.txt", "w") as f: + f.write("across-reload") +print("wrote persist.txt") +""" + +REMOUNT_PERSISTS_READ_CODE = """\ +with open("/persist.txt", "r") as f: + print(f"readback: {f.read()}") +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": REMOUNT_PERSISTS_CODE}) +@pytest.mark.port_resets(3) +def test_storage_remount_persists_across_reload(circuitpython): + """Data written after remount(readonly=False) persists across soft reload.""" + circuitpython.serial.wait_for("wrote persist.txt") + # Replace code.py via raw REPL-style approach: write new file then reload. + # Simpler: just trigger a soft reload and check the file is still there. + circuitpython.serial.write("\x04") + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "wrote persist.txt" in output + + +LABEL_CODE = """\ +import storage +storage.remount("/", readonly=False) +mount = storage.getmount("/") +mount.label = "CIRCUITPY" +print(f"label: {mount.label!r}") +print("done") +""" + + +@pytest.mark.fat_filesystem_only +@pytest.mark.circuitpy_drive({"code.py": LABEL_CODE}) +def test_storage_set_label(circuitpython): + """VfsFat.label can be set when mounted read-write.""" + circuitpython.wait_until_done() + output = circuitpython.serial.all_output + assert "label: 'CIRCUITPY'" in output + assert "done" in output + + +UMOUNT_MISSING_CODE = """\ +import storage +# Unmounting an unmounted path should raise. +try: + storage.umount("/not_mounted") + print("unexpected: umount succeeded") +except OSError as e: + print(f"umount OSError: errno={e.errno}") +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": UMOUNT_MISSING_CODE}) +def test_storage_umount_missing(circuitpython): + """umount on an unmounted path raises OSError.""" + circuitpython.wait_until_done() + output = circuitpython.serial.all_output + assert "umount OSError" in output + assert "unexpected:" not in output + assert "done" in output diff --git a/ports/zephyr-cp/tests/test_touchio.py b/ports/zephyr-cp/tests/test_touchio.py new file mode 100644 index 00000000000..cd2ec0a62b8 --- /dev/null +++ b/ports/zephyr-cp/tests/test_touchio.py @@ -0,0 +1,100 @@ +# SPDX-FileCopyrightText: 2026 Dan Halbert for Adafruit Industries LLC +# SPDX-License-Identifier: MIT + +"""Test touchio functionality on native_sim. + +touchio charges the pin, switches it to an input, and counts until it reads +back discharged. gpio_emul has no RC model: an input reads whatever value was +last set, so the count is either 0 or the 10000-tick timeout. A pin held at its +charge level by an input trace stands in for a touch. +""" + +import re + +import pytest + + +TOUCH_CODE = """\ +import time +import microcontroller +import touchio + +touch = touchio.TouchIn(microcontroller.pin.P_01) +print(f"t_abs={time.monotonic():.3f} threshold={touch.threshold}") + + +def report(): + print(f"t_abs={time.monotonic():.3f} raw={touch.raw_value} value={touch.value}") + + +report() +# Read only between trace edges, so each edge lands while the pin is an input. +for until in (4.5, 5.5): + while time.monotonic() < until: + time.sleep(0.05) + report() + +print("done") +""" + +TOUCH_TRACE = { + "gpio_emul.01": [ + (4_000_000_000, 1), # 4.0s: touched + (5_000_000_000, 0), # 5.0s: released + ], +} + +REPORT_RE = re.compile(r"t_abs=([0-9.]+) raw=(\d+) value=(True|False)") + + +@pytest.mark.circuitpy_drive({"code.py": TOUCH_CODE}) +@pytest.mark.input_trace(TOUCH_TRACE) +def test_touchio_touch_and_release(circuitpython): + """TouchIn reads touched while a trace holds the pin high.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + threshold_match = re.search(r"t_abs=([0-9.]+) threshold=(\d+)", output) + assert threshold_match is not None + # The trace only reaches pins that are already inputs. + assert float(threshold_match.group(1)) < 4.0 + # Untouched raw reading of 0 gives a threshold of 0 * 1.05 + 100. + assert int(threshold_match.group(2)) == 100 + + reports = [(int(raw), value == "True") for _, raw, value in REPORT_RE.findall(output)] + assert reports == [(0, False), (10000, True), (0, False)] + assert "done" in output + + +NO_PULL_CODE = """\ +import digitalio +import microcontroller +import touchio + +# Nothing pulls P_01 up, so it never charges low. +try: + touchio.TouchIn(microcontroller.pin.P_01, pull=digitalio.Pull.UP) +except ValueError as e: + print(f"pull up: {e}") + +# Leave P_02 high, as if nothing pulled it down. +with digitalio.DigitalInOut(microcontroller.pin.P_02) as pin: + pin.switch_to_input(pull=digitalio.Pull.UP) +try: + touchio.TouchIn(microcontroller.pin.P_02) +except ValueError as e: + print(f"pull down: {e}") + +print("done") +""" + + +@pytest.mark.circuitpy_drive({"code.py": NO_PULL_CODE}) +def test_touchio_missing_pull_resistor(circuitpython): + """TouchIn raises ValueError when the pin never discharges.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "pull up: No pullup on pin; 1Mohm recommended" in output + assert "pull down: No pulldown on pin; 1Mohm recommended" in output + assert "done" in output diff --git a/ports/zephyr-cp/tests/test_vectorio.py b/ports/zephyr-cp/tests/test_vectorio.py new file mode 100644 index 00000000000..657bbddef45 --- /dev/null +++ b/ports/zephyr-cp/tests/test_vectorio.py @@ -0,0 +1,735 @@ +# SPDX-FileCopyrightText: 2026 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""vectorio tests that run against both displayio compositors. + +native_sim is built twice: once with the legacy scanline compositor +(``native_native_sim``) and once with the LVGL compositor +(``native_native_sim_lvgl``). vectorio has an implementation for each one, so +these tests check that the LVGL implementation behaves like the legacy one: the +same API, the same shapes in the same place and the same pixels on the screen. + +The golden image was captured from the legacy compositor and is compared by +both. The only pixels that are not compared are the ones along the outline of +the circle: LVGL draws a circle as a rounded rectangle and its rasterizer +supersamples the curve, so the outline is a blend of the shape and the +background there while the legacy compositor fills whole pixels. The band +around the outline is skipped, everything else has to match exactly. + +Three differences between the two implementations are known and are not tested +here: + +- LVGL antialiases the outline of a circle, the legacy compositor does not. +- The legacy compositor does not scale vectorio shapes with the scale of the + group they are in, while the LVGL one does. A shape in a scaled group is + therefore bigger on an LVGL display. +- An outline color index that names a transparent palette entry leaves the + outline band unpainted on the legacy compositor, while LVGL treats it as no + outline and lets the fill reach the edge. Set outline_color_index to None to + remove an outline instead of making its palette entry transparent. +""" + +import math +import shutil +from pathlib import Path + +import pytest +from PIL import Image + +_DISPLAY_HELPER = """\ +import board +display = board.DISPLAY +""" + +# The scene both compositors render. The shapes are placed so that none of them +# overlap and so that the circle is far away from the other two. +SCENE_CODE = ( + _DISPLAY_HELPER + + """\ +import displayio +import time +import vectorio + +palette = displayio.Palette(4) +palette[0] = 0x000000 +palette[1] = 0xFF0000 +palette[2] = 0x00FF00 +palette[3] = 0x0000FF + +group = displayio.Group() + +circle = vectorio.Circle(pixel_shader=palette, radius=20, x=40, y=40, color_index=1) +group.append(circle) + +rectangle = vectorio.Rectangle( + pixel_shader=palette, width=40, height=20, x=100, y=40, color_index=2 +) +group.append(rectangle) + +polygon = vectorio.Polygon( + pixel_shader=palette, + points=[(0, 0), (40, 10), (20, 40)], + x=180, + y=40, + color_index=3, +) +group.append(polygon) + +# Replacing the root group hides the console so the frame only has the shapes. +display.auto_refresh = False +display.root_group = group +display.refresh() +print('rendered') +while True: + time.sleep(1) +""" +) + +# The scene with the rectangle moved and the circle hidden. It is captured twice: +# once before the move and once after it. +MOVE_CODE = ( + _DISPLAY_HELPER + + """\ +import displayio +import time +import vectorio + +palette = displayio.Palette(4) +palette[0] = 0x000000 +palette[1] = 0xFF0000 +palette[2] = 0x00FF00 +palette[3] = 0x0000FF + +group = displayio.Group() + +circle = vectorio.Circle(pixel_shader=palette, radius=20, x=40, y=40, color_index=1) +circle.hidden = True +group.append(circle) + +rectangle = vectorio.Rectangle( + pixel_shader=palette, width=40, height=20, x=100, y=40, color_index=2 +) +group.append(rectangle) + +display.auto_refresh = False +display.root_group = group +display.refresh() +print('first') +time.sleep(2) +rectangle.x = 160 +display.refresh() +print('second') +while True: + time.sleep(1) +""" +) + +API_CODE = """\ +import displayio +import vectorio + +palette = displayio.Palette(4) +palette[0] = 0x000000 +palette[1] = 0xFF0000 +palette[2] = 0x00FF00 +palette[3] = 0x0000FF + +circle = vectorio.Circle(pixel_shader=palette, radius=10, x=20, y=20) +rectangle = vectorio.Rectangle(pixel_shader=palette, width=30, height=20, x=5, y=5) +polygon = vectorio.Polygon(pixel_shader=palette, points=[(0, 0), (10, 0), (0, 10)]) + +print('circle', circle.x, circle.y, circle.radius, circle.color_index) +print('rectangle', rectangle.x, rectangle.y, rectangle.width, rectangle.height) +print('polygon', polygon.points, polygon.color_index) + +# The circle is centered on its position and covers the pixels whose center is +# within the radius. +print('circle contains', circle.contains(20, 20), circle.contains(30, 20), + circle.contains(31, 20), circle.contains(20, 31)) + +# The rectangle's position is its top left corner. +print('rectangle contains', rectangle.contains(5, 5), rectangle.contains(34, 24), + rectangle.contains(35, 24), rectangle.contains(4, 5)) + +# The polygon's points are relative to its position. +print('polygon contains', polygon.contains(0, 0), polygon.contains(5, 1), + polygon.contains(9, 9)) + +# Moving a shape moves its coverage with it. +circle.x = 50 +print('moved circle contains', circle.contains(60, 20), circle.contains(20, 20)) + +# The color index selects the palette entry. +circle.color_index = 2 +print('color index', circle.color_index) + +# A shape can only be in one group. +group = displayio.Group() +group.append(circle) +print('in group', len(group)) +other = displayio.Group() +try: + other.append(circle) + print('second group: no error') +except ValueError as e: + print('second group: ValueError') +print('done') +""" + + +def _read_image(path): + with Image.open(path) as img: + rgb = img.convert("RGB") + return rgb.width, rgb.height, rgb.tobytes() + + +def _pixel_at(image, x, y): + return tuple(image.getpixel((x, y))) + + +def _circle_outline_band(width, height, center_x, center_y, radius): + """Return the pixels LVGL may antialias when it draws a circle. + + LVGL draws the circle as a rounded rectangle and supersamples the curve, so + the pixels along the outline are a blend of the shape and the background + while the legacy compositor fills whole pixels. The pixels inside the + outline are filled completely by both and the pixels outside it are not + touched by either, so only the outline itself is skipped. + """ + band = set() + for y in range(height): + for x in range(width): + distance = math.hypot(x - center_x, y - center_y) + if radius - 1 < distance <= radius + 1.5: + band.add((x, y)) + return band + + +@pytest.mark.circuitpy_drive({"code.py": API_CODE}) +@pytest.mark.duration(15) +def test_vectorio_api(circuitpython): + """The vectorio API behaves the same on both compositors.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "circle 20 20 10 0" in output + assert "rectangle 5 5 30 20" in output + assert "polygon [(0, 0), (10, 0), (0, 10)] 0" in output + # The circle covers the pixels whose center is within the radius. + assert "circle contains True True False False" in output + # The rectangle's position is its top left corner. + assert "rectangle contains True True False False" in output + assert "polygon contains True True False" in output + # Moving a shape moves its coverage with it. + assert "moved circle contains True False" in output + assert "color index 2" in output + assert "in group 1" in output + assert "second group: ValueError" in output + assert "done" in output + + +@pytest.mark.circuitpy_drive({"code.py": SCENE_CODE}) +@pytest.mark.display(capture_times_ns=[4_000_000_000]) +@pytest.mark.duration(8) +def test_vectorio_render_golden(request, circuitpython): + """The shapes are rendered exactly like the legacy compositor renders them.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "rendered" in output + + captures = circuitpython.display_capture_paths() + if not captures or not captures[0].exists(): + pytest.skip("display capture was not produced") + + golden = Path(__file__).parent / "vectorio" / "golden" / "vectorio_shapes_320x240.png" + if request.config.getoption("--update-goldens"): + golden.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(captures[0], golden) + return + + gw, gh, gpx = _read_image(golden) + dw, dh, dpx = _read_image(captures[0]) + assert (dw, dh) == (gw, gh) + + band = _circle_outline_band(dw, dh, 40, 40, 20) + mismatches = [] + for y in range(dh): + for x in range(dw): + if (x, y) in band: + continue + i = (y * dw + x) * 3 + if gpx[i : i + 3] != dpx[i : i + 3]: + mismatches.append((x, y, tuple(gpx[i : i + 3]), tuple(dpx[i : i + 3]))) + assert not mismatches, f"{len(mismatches)} pixels differ, first: {mismatches[:5]}" + + +@pytest.mark.circuitpy_drive({"code.py": MOVE_CODE}) +@pytest.mark.display(capture_times_ns=[8_000_000_000, 10_000_000_000, 12_000_000_000]) +@pytest.mark.duration(16) +def test_vectorio_move_and_hide(circuitpython): + """Moving a shape updates the screen and a hidden shape is not drawn.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "first" in output + assert "second" in output + + captures = circuitpython.display_capture_paths() + if not captures or not captures[-1].exists(): + pytest.skip("display capture was not produced") + + # The last capture is the one taken after the shape was moved. + with Image.open(captures[-1]) as img: + after = img.convert("RGB") + + green = (0, 255, 0) + black = (0, 0, 0) + + # The hidden circle is not drawn at all. + assert _pixel_at(after, 40, 40) == black + # After the move the rectangle is at its new position and the old one is + # cleared again. + assert _pixel_at(after, 110, 45) == black + assert _pixel_at(after, 160, 45) == green + + +# Corner radius, outlines and the geometry that display_shapes needs. Both +# compositors answer contains() from the same coverage test, so this is the same +# on both even though they rasterize differently. +ROUNDED_CODE = """\ +import displayio +import vectorio + +palette = displayio.Palette(4) +palette[0] = 0x000000 +palette[1] = 0xFF0000 +palette[2] = 0x00FF00 +palette[3] = 0x0000FF + +# A shape's position is its top left corner, so contains() at (10 + dx, 10 + dy) +# asks about the shape's own pixel (dx, dy). +rectangle = vectorio.Rectangle(pixel_shader=palette, width=80, height=40, x=10, y=10, + radius=12, color_index=1, outline_width=4, outline_color_index=2) +print('defaults', rectangle.radius, rectangle.outline_width, + rectangle.outline_color_index, rectangle.color_index) + +# The corners are cut out of the coverage: the corner pixel is not covered, and +# the middle of each side still is. +print('corners', rectangle.contains(10, 10), rectangle.contains(12, 12), + rectangle.contains(18, 18), rectangle.contains(10, 30), rectangle.contains(89, 30)) + +# Radius and outline width must not exceed half of the shortest side. Invalid +# construction and assignments raise ValueError and leave existing values unchanged. +try: + vectorio.Rectangle(pixel_shader=palette, width=20, height=20, radius=11) +except ValueError: + print('constructor radius limit: ValueError') +try: + vectorio.Rectangle(pixel_shader=palette, width=20, height=20, outline_width=11) +except ValueError: + print('constructor outline limit: ValueError') +try: + rectangle.radius = 21 +except ValueError: + print('radius limit: ValueError') +try: + rectangle.outline_width = 21 +except ValueError: + print('outline limit: ValueError') +try: + rectangle.width = 20 +except ValueError: + print('resize limit: ValueError') +print('limits', rectangle.radius, rectangle.outline_width, rectangle.width) + +# The outline is inside the bounds, so it covers the same pixels whether it is set +# or not: contains() only answers coverage, not which color the pixel gets. +rectangle.outline_width = 4 +print('band', rectangle.contains(11, 30), rectangle.contains(13, 30), + rectangle.contains(14, 30), rectangle.contains(14, 14), rectangle.contains(18, 18)) +rectangle.outline_color_index = None +print('no outline color', rectangle.contains(11, 30), rectangle.outline_color_index) +rectangle.outline_color_index = 2 + +# Zero outline width is the same coverage with no outline at all. +rectangle.outline_width = 0 +print('no outline', rectangle.contains(11, 30), rectangle.outline_width) + +# A transparent palette entry draws nothing, which is how a shape gets a +# transparent fill. +palette.make_transparent(1) +print('transparent fill', rectangle.contains(50, 30)) + +# The circle ring behaves the same way. Its outline cannot be wider than its +# radius, and shrinking the radius cannot invalidate an existing outline. +try: + vectorio.Circle(pixel_shader=palette, radius=20, outline_width=21) +except ValueError: + print('circle constructor outline limit: ValueError') +circle = vectorio.Circle(pixel_shader=palette, radius=20, x=100, y=100, + color_index=2, outline_width=4, outline_color_index=3) +try: + circle.outline_width = 21 +except ValueError: + print('circle outline limit: ValueError') +try: + circle.radius = 3 +except ValueError: + print('circle resize limit: ValueError') +print('circle limits', circle.radius, circle.outline_width) +# The maximum itself is valid. +circle.outline_width = circle.radius +circle.outline_width = 4 +print('ring', circle.outline_width, circle.outline_color_index, + circle.contains(100, 84), circle.contains(100, 100), + circle.contains(100, 79), circle.contains(100, 121)) +circle.outline_width = 0 +print('no ring', circle.contains(100, 84)) +print('done') +""" + +SUBCLASS_CODE = ( + _DISPLAY_HELPER + + """\ +import displayio +import time +import vectorio + + +class RoundRect(vectorio.Rectangle): + \"\"\"A display_shapes style rounded rectangle built on vectorio.Rectangle.\"\"\" + + def __init__(self, x, y, width, height, r, *, fill=None, outline=None, stroke=1): + if width <= 0 or height <= 0: + raise ValueError("dimensions must be larger than 0") + if r > min(width, height) / 2: + raise ValueError("radius cannot exceed half of the smaller side") + self._palette = displayio.Palette(2) + self._palette.make_transparent(0) + self._palette.make_transparent(1) + super().__init__(pixel_shader=self._palette, width=width, height=height, x=x, y=y, + color_index=0, radius=r, outline_width=stroke, outline_color_index=1) + self.fill = fill + self.outline = outline + + @property + def fill(self): + return None if self._palette.is_transparent(0) else self._palette[0] + + @fill.setter + def fill(self, color): + if color is None: + self._palette.make_transparent(0) + else: + self._palette[0] = color + self._palette.make_opaque(0) + + @property + def outline(self): + return None if self._palette.is_transparent(1) else self._palette[1] + + @outline.setter + def outline(self, color): + if color is None: + self._palette.make_transparent(1) + else: + self._palette[1] = color + self._palette.make_opaque(1) + + +# Use display_shapes.RoundRect's default one-pixel stroke, not only the thicker +# outlines exercised by the native API and rendering tests. +round_rect = RoundRect(10, 10, 80, 40, 12, fill=0xFF0000, outline=0x00FF00) +print('size', round_rect.x, round_rect.y, round_rect.width, round_rect.height) +print('shape', round_rect.radius, round_rect.outline_width, + round_rect.outline_color_index, round_rect.color_index) +print('colors', hex(round_rect.fill), hex(round_rect.outline)) +print('shader', round_rect.pixel_shader is round_rect._palette) + +# Everything inherited from VectorShape resolves through the native Rectangle. +print('contains', round_rect.contains(50, 30), round_rect.contains(10, 10)) +print('location', round_rect.location) +round_rect.x = 30 +round_rect.width = 100 +round_rect.radius = 20 +print('mutated', round_rect.x, round_rect.width, round_rect.radius, round_rect.location) +round_rect.hidden = True +print('hidden', round_rect.hidden) +round_rect.hidden = False +round_rect.fill = None +print('cleared', round_rect.fill, round_rect.contains(50, 30)) + +group = displayio.Group() +group.append(round_rect) +print('in group', len(group)) +other = displayio.Group() +try: + other.append(round_rect) +except ValueError: + print('second group: ValueError') + + +class SubclassedCircle(vectorio.Circle): + pass + + +class SubclassedPolygon(vectorio.Polygon): + pass + + +# Exercise the native-base conversion for every vectorio shape, not only Rectangle. +circle = SubclassedCircle(pixel_shader=round_rect._palette, radius=20, x=150, y=100, + color_index=0, outline_width=4, outline_color_index=1) +polygon = SubclassedPolygon(pixel_shader=round_rect._palette, + points=[(0, 0), (40, 0), (0, 40)], x=220, y=100, color_index=0) +print('other shapes', circle.radius, circle.outline_width, circle.outline_color_index, + polygon.points, polygon.color_index) +circle.radius = 22 +circle.outline_width = 3 +polygon.points = [(0, 0), (50, 0), (0, 40)] +polygon.color_index = 1 +print('other mutations', circle.radius, circle.outline_width, polygon.points, + polygon.color_index, circle.contains(150, 100), polygon.contains(225, 105)) + +# Until super().__init__() runs, the instance has no native Rectangle. Native properties, +# inherited VectorShape properties and Group.append() must raise instead of treating the +# Python instance as a native shape. +class EarlyAccess(vectorio.Rectangle): + def __init__(self, palette): + self.early = [] + for name, attempt in ( + ('radius', lambda: self.radius), + ('x', lambda: self.x), + ('append', lambda: displayio.Group().append(self)), + ): + try: + attempt() + self.early.append(name + ' ok') + except Exception as e: + self.early.append(name + ' ' + type(e).__name__) + super().__init__(pixel_shader=palette, width=20, height=20, radius=5) + + +early = EarlyAccess(round_rect._palette) +print('early access', ', '.join(early.early), early.radius) + + +# An __init__() that never calls super().__init__() gets its native Rectangle built +# afterwards from the constructor's arguments. +class NoSuperInit(vectorio.Rectangle): + def __init__(self, **kwargs): + pass + + +late = NoSuperInit(pixel_shader=round_rect._palette, width=20, height=20, radius=5) +print('no super init', late.width, late.radius) + +# Restore the rectangle after the API checks and render all three Python subclasses. This +# verifies that Group's protocol lookup reaches the native wrapper on both compositors. +round_rect.x = 10 +round_rect.width = 80 +round_rect.radius = 12 +round_rect.fill = 0xFF0000 +group.append(circle) +group.append(polygon) +display.auto_refresh = False +display.root_group = group +display.refresh() +print('done') +print('rendered') +while True: + time.sleep(1) +""" +) + +ROUNDED_SCENE_CODE = ( + _DISPLAY_HELPER + + """\ +import displayio +import time +import vectorio + +palette = displayio.Palette(4) +palette.make_transparent(0) +palette[1] = 0xFF0000 +palette[2] = 0x00FF00 +palette[3] = 0x0000FF + +group = displayio.Group() + +# Rounded rectangle with a 4 pixel outline: x 10..89, y 10..49, radius 12. +rectangle = vectorio.Rectangle(pixel_shader=palette, width=80, height=40, x=10, y=10, + radius=12, color_index=1, outline_width=4, outline_color_index=2) +group.append(rectangle) + +# A hollow one: transparent fill, so only the outline is drawn. +hollow = vectorio.Rectangle(pixel_shader=palette, width=80, height=40, x=110, y=10, + radius=12, color_index=0, outline_width=4, outline_color_index=2) +group.append(hollow) + +# No outline color means no outline, so the fill reaches the edge. +invisible = vectorio.Rectangle(pixel_shader=palette, width=80, height=40, x=210, y=10, + radius=12, color_index=1, outline_width=4) +group.append(invisible) + +# A ring: center (40, 110), radius 20, 4 pixels thick. +circle = vectorio.Circle(pixel_shader=palette, radius=20, x=40, y=110, + color_index=1, outline_width=4, outline_color_index=2) +group.append(circle) + +display.auto_refresh = False +display.root_group = group +display.refresh() +print('rendered') +while True: + time.sleep(1) +""" +) + + +@pytest.mark.circuitpy_drive({"code.py": ROUNDED_CODE}) +@pytest.mark.duration(15) +def test_vectorio_radius_and_outline_api(circuitpython): + """Radius, outline width and outline color index are the same on both compositors.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "defaults 12 4 2 1" in output + # Covered: the flat sides and the diagonal inside the corner arc. Not + # covered: the corner pixel and everything a pixel beyond the shape. + assert "corners False False True True True" in output + # The corner radius and outline width are validated instead of clamped. A + # resize that would make either one too large is rejected too. + assert "constructor radius limit: ValueError" in output + assert "constructor outline limit: ValueError" in output + assert "radius limit: ValueError" in output + assert "outline limit: ValueError" in output + assert "resize limit: ValueError" in output + assert "limits 12 4 80" in output + # The 4 pixel outline band is the outline, and the fill starts inside it. An + # outline covers the same pixels as the fill it replaces. + assert "band True True True True True" in output + assert "no outline color True None" in output + assert "no outline True 0" in output + assert "transparent fill True" in output + # The ring covers radius-4..radius, the fill covers everything inside. + assert "circle constructor outline limit: ValueError" in output + assert "circle outline limit: ValueError" in output + assert "circle resize limit: ValueError" in output + assert "circle limits 20 4" in output + assert "ring 4 3 True True False False" in output + assert "no ring True" in output + assert "done" in output + + +@pytest.mark.circuitpy_drive({"code.py": SUBCLASS_CODE}) +@pytest.mark.display(capture_times_ns=[4_000_000_000]) +@pytest.mark.duration(8) +def test_vectorio_python_subclass(circuitpython): + """Python subclasses of all vectorio shapes work as rendered group members.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "size 10 10 80 40" in output + assert "shape 12 1 1 0" in output + assert "colors 0xff0000 0xff00" in output + assert "shader True" in output + assert "contains True False" in output + assert "location (10, 10)" in output + assert "mutated 30 100 20 (30, 10)" in output + assert "hidden True" in output + assert "cleared None True" in output + assert "in group 1" in output + assert "second group: ValueError" in output + assert "other shapes 20 4 1 [(0, 0), (40, 0), (0, 40)] 0" in output + assert "other mutations 22 3 [(0, 0), (50, 0), (0, 40)] 1 True True" in output + # Before super().__init__(), every entry point raises instead of reading the instance + # as a native shape. Without super().__init__(), the native base is built afterwards. + assert ( + "early access radius NotImplementedError, x NotImplementedError, " + "append NotImplementedError 5" in output + ) + assert "no super init 20 5" in output + assert "done" in output + assert "rendered" in output + + captures = circuitpython.display_capture_paths() + if not captures or not captures[0].exists(): + pytest.skip("display capture was not produced") + + with Image.open(captures[0]) as img: + frame = img.convert("RGB") + + red = (255, 0, 0) + green = (0, 255, 0) + black = (0, 0, 0) + + # The subclassed rounded rectangle renders with its inherited native geometry. + assert _pixel_at(frame, 50, 30) == red + assert _pixel_at(frame, 50, 10) == green + assert _pixel_at(frame, 10, 10) == black + # Circle and Polygon subclasses also reach their native draw protocols. + assert _pixel_at(frame, 150, 100) == red + assert _pixel_at(frame, 150, 79) == green + assert _pixel_at(frame, 225, 105) == green + assert _pixel_at(frame, 260, 135) == black + + +@pytest.mark.circuitpy_drive({"code.py": ROUNDED_SCENE_CODE}) +@pytest.mark.display(capture_times_ns=[4_000_000_000]) +@pytest.mark.duration(8) +def test_vectorio_radius_and_outline_render(circuitpython): + """Rounded corners and outlines are drawn inside the shape's bounds.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "rendered" in output + + captures = circuitpython.display_capture_paths() + if not captures or not captures[0].exists(): + pytest.skip("display capture was not produced") + + with Image.open(captures[0]) as img: + frame = img.convert("RGB") + + red = (255, 0, 0) + green = (0, 255, 0) + black = (0, 0, 0) + + def pixel(x, y): + return tuple(frame.getpixel((x, y))) + + # The fill is the whole rectangle less the outline band. + assert pixel(50, 30) == red + # The outline is inside the bounds: 4 pixels in on every flat side, so it + # never makes the rectangle bigger. + assert pixel(50, 10) == green + assert pixel(50, 13) == green + assert pixel(50, 14) == red + assert pixel(10, 30) == green + assert pixel(13, 30) == green + assert pixel(14, 30) == red + # The corner is round: well outside the arc is background and the diagonal + # inside the arc is outline. + assert pixel(10, 10) == black + assert pixel(12, 12) == black + assert pixel(14, 14) == green + assert pixel(18, 18) == red + + # A transparent fill leaves only the outline. + assert pixel(150, 30) == black + assert pixel(150, 11) == green + assert pixel(111, 30) == green + assert pixel(110, 10) == black + + # A transparent outline color draws no outline, so the fill reaches the edge. + assert pixel(250, 10) == red + assert pixel(211, 30) == red + assert pixel(210, 10) == black + + # The ring is inside the circle's radius. + assert pixel(40, 110) == red + assert pixel(40, 97) == red + assert pixel(40, 92) == green + assert pixel(40, 89) == black diff --git a/ports/zephyr-cp/tests/test_watchdog.py b/ports/zephyr-cp/tests/test_watchdog.py new file mode 100644 index 00000000000..514ddcc4eb9 --- /dev/null +++ b/ports/zephyr-cp/tests/test_watchdog.py @@ -0,0 +1,71 @@ +# SPDX-FileCopyrightText: 2026 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""Test the watchdog module against native_sim's counter-based watchdog. + +The native_sim devicetree aliases watchdog0 to a zephyr,counter-watchdog +device built on the simulator's counter, which supports the expiry callback, +so the RAISE behavior can be exercised: an expired watchdog must raise +watchdog.WatchDogTimeout instead of resetting the simulator. RESET mode resets +the simulator, which boots straight back into CircuitPython. +""" + +import pytest + + +RAISE_MODE_CODE = """\ +import microcontroller +import watchdog +import time + +wdt = microcontroller.watchdog +wdt.timeout = 1.0 +wdt.mode = watchdog.WatchDogMode.RAISE +print("EXPIRING") +try: + while True: + time.sleep(10) +except watchdog.WatchDogTimeout: + print("CAUGHT:", wdt.timeout) +except Exception as e: + print("OTHER:", type(e)) +""" + + +@pytest.mark.circuitpy_drive({"code.py": RAISE_MODE_CODE}) +@pytest.mark.duration(30) +def test_watchdog_raise_mode(circuitpython): + """An expired watchdog in RAISE mode raises WatchDogTimeout.""" + circuitpython.serial.wait_for("EXPIRING", timeout=30) + circuitpython.serial.wait_for("CAUGHT: 1.0", timeout=30) + + +RESET_MODE_CODE = """\ +import microcontroller +import watchdog +import time + +wdt = microcontroller.watchdog +wdt.timeout = 1.0 +wdt.mode = watchdog.WatchDogMode.RESET +print("ARMED") +try: + while True: + time.sleep(10) +except watchdog.WatchDogTimeout: + print("UNREACHABLE: caught in RESET mode") +""" + + +@pytest.mark.circuitpy_drive({"code.py": RESET_MODE_CODE}) +@pytest.mark.duration(30) +@pytest.mark.port_resets(3) +def test_watchdog_reset_mode(circuitpython): + """An expired watchdog in RESET mode reboots the simulator into CircuitPython.""" + circuitpython.serial.wait_for("ARMED", timeout=30) + assert circuitpython.reconnect_serial(timeout=30), "simulator did not reboot" + + circuitpython.serial.wait_for("ARMED", timeout=30) + + all_output = circuitpython.serial.all_output + assert "UNREACHABLE" not in all_output diff --git a/ports/zephyr-cp/tests/test_web_workflow.py b/ports/zephyr-cp/tests/test_web_workflow.py new file mode 100644 index 00000000000..d3a00782a33 --- /dev/null +++ b/ports/zephyr-cp/tests/test_web_workflow.py @@ -0,0 +1,142 @@ +# SPDX-FileCopyrightText: 2026 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""Tests for web workflow on native_sim.""" + +from __future__ import annotations + +import json +import re + +import pytest +import requests + + +pytestmark = pytest.mark.native_sim_rt + +WEB_WORKFLOW_PORT = 8090 +WEB_WORKFLOW_PASSWORD = "testpass" + +WEB_WORKFLOW_CODE = """\ +import time + +# Keep the VM alive while the web workflow starts. +time.sleep(3) +""" + +WEB_WORKFLOW_UPDATED_CODE = """\ +print("updated") +""" + +WEB_WORKFLOW_SETTINGS = f"""\ +CIRCUITPY_WEB_API_PASSWORD="{WEB_WORKFLOW_PASSWORD}" +CIRCUITPY_WEB_API_PORT={WEB_WORKFLOW_PORT} +""" + +WEB_WORKFLOW_SETTINGS_PORT_80 = f"""\ +CIRCUITPY_WEB_API_PASSWORD="{WEB_WORKFLOW_PASSWORD}" +CIRCUITPY_WEB_API_PORT=80 +""" + +WEB_WORKFLOW_BOOT = """\ +import storage + +storage.remount("/", readonly=False) +""" + + +@pytest.mark.circuitpy_drive( + { + "code.py": WEB_WORKFLOW_CODE, + "settings.toml": WEB_WORKFLOW_SETTINGS, + } +) +def test_web_workflow_hostnetwork(circuitpython): + """Ensure web workflow responds over hostnetwork.""" + circuitpython.serial.wait_for(f"127.0.0.1:{WEB_WORKFLOW_PORT}") + response = requests.get(f"http://127.0.0.1:{WEB_WORKFLOW_PORT}/edit/", timeout=1.0) + + assert response.status_code == 401 + + +@pytest.mark.circuitpy_drive( + { + "code.py": WEB_WORKFLOW_CODE, + "settings.toml": WEB_WORKFLOW_SETTINGS, + } +) +def test_web_workflow_version_json_hostnetwork_ip_and_port(circuitpython): + """Ensure /cp/version.json reports hostnetwork endpoint with configured port.""" + circuitpython.serial.wait_for(f"127.0.0.1:{WEB_WORKFLOW_PORT}") + response = requests.get( + f"http://127.0.0.1:{WEB_WORKFLOW_PORT}/cp/version.json", + auth=("", WEB_WORKFLOW_PASSWORD), + timeout=1.0, + ) + + assert response.status_code == 200 + + payload = json.loads(response.text) + assert payload["ip"] == "127.0.0.1" + assert payload["port"] == WEB_WORKFLOW_PORT + + +@pytest.mark.circuitpy_drive( + { + "code.py": WEB_WORKFLOW_CODE, + "settings.toml": WEB_WORKFLOW_SETTINGS, + } +) +def test_web_workflow_status_line_hostnetwork_non_default_port(circuitpython): + """Status line should include hostnetwork IP and non-default port.""" + circuitpython.wait_until_done() + output = circuitpython.serial.all_output + + # Remove ANSI control sequences before matching. + output = re.sub(r"\x1b\[[0-9;]*[A-Za-z]", "", output) + assert "127.0.0.1:8090" in output + + +@pytest.mark.circuitpy_drive( + { + "code.py": WEB_WORKFLOW_CODE, + "settings.toml": WEB_WORKFLOW_SETTINGS_PORT_80, + } +) +def test_web_workflow_status_line_hostnetwork_default_port(circuitpython): + """Status line should show IP without :80 for default HTTP port.""" + circuitpython.wait_until_done() + output = circuitpython.serial.all_output + + output = re.sub(r"\x1b\[[0-9;]*[A-Za-z]", "", output) + assert "127.0.0.1" in output + assert "127.0.0.1:80" not in output + + +@pytest.mark.circuitpy_drive( + { + "boot.py": WEB_WORKFLOW_BOOT, + "code.py": WEB_WORKFLOW_CODE, + "settings.toml": WEB_WORKFLOW_SETTINGS, + } +) +def test_web_workflow_write_code_py_remount(circuitpython): + """Ensure web workflow can update code.py after remounting.""" + circuitpython.serial.wait_for(f"127.0.0.1:{WEB_WORKFLOW_PORT}") + body = WEB_WORKFLOW_UPDATED_CODE.encode("utf-8") + + response = requests.put( + f"http://127.0.0.1:{WEB_WORKFLOW_PORT}/fs/code.py", + auth=("", WEB_WORKFLOW_PASSWORD), + data=body, + timeout=1.0, + ) + assert response.status_code in (201, 204) + + response = requests.get( + f"http://127.0.0.1:{WEB_WORKFLOW_PORT}/fs/code.py", + auth=("", WEB_WORKFLOW_PASSWORD), + timeout=1.0, + ) + assert response.status_code == 200 + assert WEB_WORKFLOW_UPDATED_CODE in response.text diff --git a/ports/zephyr-cp/tests/test_zlib.py b/ports/zephyr-cp/tests/test_zlib.py new file mode 100644 index 00000000000..bd89d8e1c25 --- /dev/null +++ b/ports/zephyr-cp/tests/test_zlib.py @@ -0,0 +1,110 @@ +# SPDX-FileCopyrightText: 2026 Tim Cocks for Adafruit Industries +# SPDX-License-Identifier: MIT + +"""Test the zlib module against CPython zlib. + +CircuitPython's zlib only implements ``decompress``; these tests compress data +with CPython and verify the zephyr-cp port decodes it back to the same bytes. +""" + +import zlib + +import pytest + + +PLAIN_TEXT = b"CircuitPython running on Zephyr says hello!" +REPEATED_TEXT = b"The quick brown fox jumps over the lazy dog. " * 32 +BINARY_BLOB = bytes(range(256)) * 4 + + +def _make_code(compressed: bytes, wbits: int, expected_len: int) -> str: + return ( + "import zlib\n" + f"compressed = {compressed!r}\n" + f"out = zlib.decompress(compressed, {wbits})\n" + f'print(f"out_len: {{len(out)}}")\n' + f'print(f"expected_len: {expected_len}")\n' + 'print(f"out_hex: {out.hex()}")\n' + 'print("done")\n' + ) + + +ZLIB_COMPRESSED = zlib.compress(PLAIN_TEXT) +ZLIB_CODE = _make_code(ZLIB_COMPRESSED, wbits=15, expected_len=len(PLAIN_TEXT)) + + +@pytest.mark.circuitpy_drive({"code.py": ZLIB_CODE}) +def test_zlib_decompress_zlib_format(circuitpython): + """Data produced by CPython zlib.compress() round-trips through CircuitPython zlib.decompress().""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert f"out_len: {len(PLAIN_TEXT)}" in output + assert f"out_hex: {PLAIN_TEXT.hex()}" in output + assert "done" in output + + +REPEATED_COMPRESSED = zlib.compress(REPEATED_TEXT) +REPEATED_CODE = _make_code(REPEATED_COMPRESSED, wbits=15, expected_len=len(REPEATED_TEXT)) + + +@pytest.mark.circuitpy_drive({"code.py": REPEATED_CODE}) +def test_zlib_decompress_repeated(circuitpython): + """Highly-compressible repeated input decompresses correctly (back-references).""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert f"out_len: {len(REPEATED_TEXT)}" in output + # Repeated text has many back-references; shrinks a lot. + assert len(REPEATED_COMPRESSED) < len(REPEATED_TEXT) // 4 + assert f"out_hex: {REPEATED_TEXT.hex()}" in output + assert "done" in output + + +BINARY_COMPRESSED = zlib.compress(BINARY_BLOB) +BINARY_CODE = _make_code(BINARY_COMPRESSED, wbits=15, expected_len=len(BINARY_BLOB)) + + +@pytest.mark.circuitpy_drive({"code.py": BINARY_CODE}) +def test_zlib_decompress_binary_bytes(circuitpython): + """Decompression preserves every byte value (0x00-0xFF).""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert f"out_len: {len(BINARY_BLOB)}" in output + assert f"out_hex: {BINARY_BLOB.hex()}" in output + assert "done" in output + + +# Raw DEFLATE stream (no zlib header/trailer). +_raw_compressor = zlib.compressobj(wbits=-15) +RAW_COMPRESSED = _raw_compressor.compress(PLAIN_TEXT) + _raw_compressor.flush() +RAW_CODE = _make_code(RAW_COMPRESSED, wbits=-15, expected_len=len(PLAIN_TEXT)) + + +@pytest.mark.circuitpy_drive({"code.py": RAW_CODE}) +def test_zlib_decompress_raw_deflate(circuitpython): + """Raw DEFLATE streams (wbits=-15) decompress to the original bytes.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert f"out_len: {len(PLAIN_TEXT)}" in output + assert f"out_hex: {PLAIN_TEXT.hex()}" in output + assert "done" in output + + +# Gzip wrapper (wbits=31). +_gzip_compressor = zlib.compressobj(wbits=31) +GZIP_COMPRESSED = _gzip_compressor.compress(PLAIN_TEXT) + _gzip_compressor.flush() +GZIP_CODE = _make_code(GZIP_COMPRESSED, wbits=31, expected_len=len(PLAIN_TEXT)) + + +@pytest.mark.circuitpy_drive({"code.py": GZIP_CODE}) +def test_zlib_decompress_gzip_format(circuitpython): + """Gzip-wrapped streams (wbits=31) decompress to the original bytes.""" + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert f"out_len: {len(PLAIN_TEXT)}" in output + assert f"out_hex: {PLAIN_TEXT.hex()}" in output + assert "done" in output diff --git a/ports/zephyr-cp/tests/vectorio/golden/vectorio_shapes_320x240.png b/ports/zephyr-cp/tests/vectorio/golden/vectorio_shapes_320x240.png new file mode 100644 index 00000000000..5ad281784f8 Binary files /dev/null and b/ports/zephyr-cp/tests/vectorio/golden/vectorio_shapes_320x240.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/README.md b/ports/zephyr-cp/tests/zephyr_display/README.md new file mode 100644 index 00000000000..419fe386950 --- /dev/null +++ b/ports/zephyr-cp/tests/zephyr_display/README.md @@ -0,0 +1,47 @@ +# Zephyr Display Golden Tests + +This directory contains native_sim golden-image tests for the Zephyr-specific `zephyr_display` path. + +## What is tested + +- `board.DISPLAY` is present and usable. +- CircuitPython terminal/console tilegrids are attached to the default display root group. +- Deterministic console terminal output matches a checked-in golden image. +- `terminalio.Terminal` output matches checked-in golden images at 90, 180 and 270 degree rotations. +- `zephyr_display` pixel format constants are exposed. +- `displayio` rendering produces expected stripe colors at sampled pixel locations. + +## Files + +- `test_zephyr_display.py` – pytest tests. +- `golden/terminal_console_output_320x240.png` – console terminal output golden reference image. +- `golden/terminal_rotated_{90,180,270}_320x240.png` – rotated terminal golden reference images. + +## How capture works + +These tests use trace-driven SDL display capture triggered by Perfetto instant events: + +- `--input-trace=` provides a Perfetto trace containing a `"display_capture"` track + with instant events at the desired capture timestamps. +- `--display_capture_png=` specifies the output PNG pattern (may contain `%d` for + a sequence number). +- `--display_headless` runs SDL in headless/hidden-window mode (always enabled for native_sim tests). + +The test harness sets these flags automatically when tests use +`@pytest.mark.display(capture_times_ns=[...])`. + +## Regenerating the console golden image + +```bash +rm -rf /tmp/zephyr-display-golden +pytest -q ports/zephyr-cp/tests/zephyr_display/test_zephyr_display.py::test_console_output_golden \ + --basetemp=/tmp/zephyr-display-golden +cp /tmp/zephyr-display-golden/test_console_output_golden0/frame_0.png \ + ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240.png +``` + +## Running the tests + +```bash +pytest -q ports/zephyr-cp/tests/zephyr_display/test_zephyr_display.py +``` diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/color_gradient_320x240.png b/ports/zephyr-cp/tests/zephyr_display/golden/color_gradient_320x240.png new file mode 100644 index 00000000000..5739b8ee156 Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/color_gradient_320x240.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/color_gradient_320x240_AL_88.png b/ports/zephyr-cp/tests/zephyr_display/golden/color_gradient_320x240_AL_88.png new file mode 100644 index 00000000000..6bdb72b802c Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/color_gradient_320x240_AL_88.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/color_gradient_320x240_ARGB_8888.png b/ports/zephyr-cp/tests/zephyr_display/golden/color_gradient_320x240_ARGB_8888.png new file mode 100644 index 00000000000..90b422792db Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/color_gradient_320x240_ARGB_8888.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/color_gradient_320x240_BGR_565.png b/ports/zephyr-cp/tests/zephyr_display/golden/color_gradient_320x240_BGR_565.png new file mode 100644 index 00000000000..5739b8ee156 Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/color_gradient_320x240_BGR_565.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/color_gradient_320x240_L_8.png b/ports/zephyr-cp/tests/zephyr_display/golden/color_gradient_320x240_L_8.png new file mode 100644 index 00000000000..6bdb72b802c Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/color_gradient_320x240_L_8.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/color_gradient_320x240_MONO01.png b/ports/zephyr-cp/tests/zephyr_display/golden/color_gradient_320x240_MONO01.png new file mode 100644 index 00000000000..b22de4417ab Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/color_gradient_320x240_MONO01.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/color_gradient_320x240_MONO10.png b/ports/zephyr-cp/tests/zephyr_display/golden/color_gradient_320x240_MONO10.png new file mode 100644 index 00000000000..b22de4417ab Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/color_gradient_320x240_MONO10.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/color_gradient_320x240_RGB_565.png b/ports/zephyr-cp/tests/zephyr_display/golden/color_gradient_320x240_RGB_565.png new file mode 100644 index 00000000000..5739b8ee156 Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/color_gradient_320x240_RGB_565.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/color_gradient_320x240_RGB_888.png b/ports/zephyr-cp/tests/zephyr_display/golden/color_gradient_320x240_RGB_888.png new file mode 100644 index 00000000000..c4301da47c5 Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/color_gradient_320x240_RGB_888.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_00_320x240.png b/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_00_320x240.png new file mode 100644 index 00000000000..8f7fc051365 Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_00_320x240.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_01_320x240.png b/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_01_320x240.png new file mode 100644 index 00000000000..67d17856c7d Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_01_320x240.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_02_320x240.png b/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_02_320x240.png new file mode 100644 index 00000000000..99c832b68ec Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_02_320x240.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_03_320x240.png b/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_03_320x240.png new file mode 100644 index 00000000000..38f403a2ad3 Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_03_320x240.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_04_320x240.png b/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_04_320x240.png new file mode 100644 index 00000000000..2a6649a0014 Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_04_320x240.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_05_320x240.png b/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_05_320x240.png new file mode 100644 index 00000000000..507a9290937 Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_05_320x240.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_06_320x240.png b/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_06_320x240.png new file mode 100644 index 00000000000..217b98f680b Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_06_320x240.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_07_320x240.png b/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_07_320x240.png new file mode 100644 index 00000000000..507a9290937 Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_07_320x240.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_08_320x240.png b/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_08_320x240.png new file mode 100644 index 00000000000..2a6649a0014 Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_08_320x240.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_09_320x240.png b/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_09_320x240.png new file mode 100644 index 00000000000..38f403a2ad3 Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_09_320x240.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_10_320x240.png b/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_10_320x240.png new file mode 100644 index 00000000000..99c832b68ec Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_10_320x240.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_11_320x240.png b/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_11_320x240.png new file mode 100644 index 00000000000..67d17856c7d Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_11_320x240.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_12_320x240.png b/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_12_320x240.png new file mode 100644 index 00000000000..8f7fc051365 Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/gifio_frame_12_320x240.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/jpegio_test_pattern_320x240.png b/ports/zephyr-cp/tests/zephyr_display/golden/jpegio_test_pattern_320x240.png new file mode 100644 index 00000000000..4987b76ff80 Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/jpegio_test_pattern_320x240.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240.mask.png b/ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240.mask.png new file mode 100644 index 00000000000..c675e2e5fa7 Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240.mask.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240.png b/ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240.png new file mode 100644 index 00000000000..77577a65601 Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240_AL_88.png b/ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240_AL_88.png new file mode 100644 index 00000000000..f9ceedebe4a Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240_AL_88.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240_ARGB_8888.png b/ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240_ARGB_8888.png new file mode 100644 index 00000000000..90b422792db Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240_ARGB_8888.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240_BGR_565.png b/ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240_BGR_565.png new file mode 100644 index 00000000000..77577a65601 Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240_BGR_565.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240_L_8.png b/ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240_L_8.png new file mode 100644 index 00000000000..f9ceedebe4a Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240_L_8.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240_MONO01.png b/ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240_MONO01.png new file mode 100644 index 00000000000..59928bcd107 Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240_MONO01.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240_MONO01_no_vtiled.png b/ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240_MONO01_no_vtiled.png new file mode 100644 index 00000000000..59928bcd107 Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240_MONO01_no_vtiled.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240_MONO10.png b/ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240_MONO10.png new file mode 100644 index 00000000000..59928bcd107 Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240_MONO10.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240_MONO10_no_vtiled.png b/ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240_MONO10_no_vtiled.png new file mode 100644 index 00000000000..59928bcd107 Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240_MONO10_no_vtiled.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240_RGB_565.png b/ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240_RGB_565.png new file mode 100644 index 00000000000..77577a65601 Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240_RGB_565.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240_RGB_888.png b/ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240_RGB_888.png new file mode 100644 index 00000000000..28d51925cae Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/terminal_console_output_320x240_RGB_888.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/terminal_rotated_180_320x240.png b/ports/zephyr-cp/tests/zephyr_display/golden/terminal_rotated_180_320x240.png new file mode 100644 index 00000000000..e1caef2f3c6 Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/terminal_rotated_180_320x240.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/terminal_rotated_270_320x240.png b/ports/zephyr-cp/tests/zephyr_display/golden/terminal_rotated_270_320x240.png new file mode 100644 index 00000000000..ed6a08fedb7 Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/terminal_rotated_270_320x240.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/golden/terminal_rotated_90_320x240.png b/ports/zephyr-cp/tests/zephyr_display/golden/terminal_rotated_90_320x240.png new file mode 100644 index 00000000000..b31594281be Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/golden/terminal_rotated_90_320x240.png differ diff --git a/ports/zephyr-cp/tests/zephyr_display/test.gif b/ports/zephyr-cp/tests/zephyr_display/test.gif new file mode 100644 index 00000000000..4f96816a1f0 Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/test.gif differ diff --git a/ports/zephyr-cp/tests/zephyr_display/test.jpg b/ports/zephyr-cp/tests/zephyr_display/test.jpg new file mode 100644 index 00000000000..488357f506a Binary files /dev/null and b/ports/zephyr-cp/tests/zephyr_display/test.jpg differ diff --git a/ports/zephyr-cp/tests/zephyr_display/test_gifio.py b/ports/zephyr-cp/tests/zephyr_display/test_gifio.py new file mode 100644 index 00000000000..a7ae91d4fdf --- /dev/null +++ b/ports/zephyr-cp/tests/zephyr_display/test_gifio.py @@ -0,0 +1,206 @@ +# SPDX-FileCopyrightText: 2026 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +import shutil +from pathlib import Path + +import pytest +from PIL import Image + + +_TEST_GIF_PATH = Path(__file__).parent / "test.gif" +_TEST_GIF_BYTES = _TEST_GIF_PATH.read_bytes() + + +def _read_image(path: Path) -> tuple[int, int, bytes]: + with Image.open(path) as img: + rgb = img.convert("RGB") + return rgb.width, rgb.height, rgb.tobytes() + + +def _golden_compare_or_update(request, captures, golden_path): + if not captures or not captures[0].exists(): + pytest.skip("display capture was not produced") + + if request.config.getoption("--update-goldens"): + golden_path.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(captures[0], golden_path) + return + + gw, gh, gpx = _read_image(golden_path) + dw, dh, dpx = _read_image(captures[0]) + assert (dw, dh) == (gw, gh) + assert gpx == dpx + + +GIFIO_METADATA_CODE = """\ +import gifio + +odg = gifio.OnDiskGif('/test.gif') +print('size', odg.width, odg.height) +print('frame_count', odg.frame_count) +print('duration', round(odg.duration, 3)) +print('min_delay', round(odg.min_delay, 3)) +print('max_delay', round(odg.max_delay, 3)) + +delay = odg.next_frame() +print('delay', round(delay, 3)) + +bitmap = odg.bitmap +print('bitmap_size', bitmap.width, bitmap.height) + +for i in range(min(odg.width, 8)): + print('px', i, hex(bitmap[i, 0])) + +odg.deinit() +print('deinited') + +try: + odg.next_frame() +except Exception as e: + print('after_deinit', type(e).__name__) + +print('done') +""" + + +GIFIO_DECODE_CODE = """\ +import board +import displayio +import time +from gifio import OnDiskGif + +odg = OnDiskGif('/test.gif') +print('size', odg.width, odg.height) +print('frame_count', odg.frame_count) + +scale = 10 +tg = displayio.TileGrid( + odg.bitmap, + pixel_shader=displayio.ColorConverter( + input_colorspace=displayio.Colorspace.RGB565_SWAPPED + ), +) +g = displayio.Group(scale=scale) +g.x = (board.DISPLAY.width - odg.width * scale) // 2 +g.y = (board.DISPLAY.height - odg.height * scale) // 2 +g.append(tg) + +board.DISPLAY.auto_refresh = False +board.DISPLAY.root_group = g + +# Pin the render loop to a known point in simulated time so that the +# capture_times_ns schedule below lands on each GIF frame while it is on screen. +LOOP_START = 10.0 +FRAME_HOLD = 2.0 +while time.monotonic() < LOOP_START: + time.sleep(0.05) +print('loop_start', round(time.monotonic(), 3)) + +for frame_index in range(odg.frame_count): + odg.next_frame() + board.DISPLAY.refresh() + print('rendered', frame_index, round(time.monotonic(), 3)) + # Hold this frame on screen; the capture for this frame is scheduled + # for the middle of this window. + target = LOOP_START + (frame_index + 1) * FRAME_HOLD + while time.monotonic() < target: + time.sleep(0.05) + +print('done') +while True: + time.sleep(1) +""" + + +# Keep these in sync with LOOP_START / FRAME_HOLD in GIFIO_DECODE_CODE. +_DECODE_LOOP_START_S = 10.0 +_DECODE_FRAME_HOLD_S = 2.0 +_DECODE_FRAME_COUNT = 13 +# Capture at the midpoint of each frame's hold window. +_DECODE_CAPTURE_TIMES_NS = [ + int( + (_DECODE_LOOP_START_S + i * _DECODE_FRAME_HOLD_S + _DECODE_FRAME_HOLD_S / 2) + * 1_000_000_000 + ) + for i in range(_DECODE_FRAME_COUNT) +] + + +GIFIO_WRITER_CODE = """\ +import displayio +import gifio +import os + +width, height = 8, 4 +buf = bytearray(width * height * 2) +for i in range(width * height): + # RGB565 gradient + value = (i * 0x0841) & 0xFFFF + buf[2 * i] = (value >> 8) & 0xFF + buf[2 * i + 1] = value & 0xFF + +path = '/out.gif' +with gifio.GifWriter(path, width, height, displayio.Colorspace.RGB565, loop=True) as writer: + writer.add_frame(buf, 0.1) + writer.add_frame(buf, 0.2) + +size = os.stat(path)[6] +print('wrote_size', size) + +with open(path, 'rb') as f: + header = f.read(6) +print('header', header) + +print('done') +""" + + +_GIFIO_METADATA_DRIVE = {"code.py": GIFIO_METADATA_CODE, "test.gif": _TEST_GIF_BYTES} +_GIFIO_DECODE_DRIVE = {"code.py": GIFIO_DECODE_CODE, "test.gif": _TEST_GIF_BYTES} +_GIFIO_WRITER_DRIVE = {"code.py": GIFIO_WRITER_CODE} + + +@pytest.mark.circuitpy_drive(_GIFIO_METADATA_DRIVE) +def test_gifio_metadata(circuitpython): + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "size 16 16" in output + assert "frame_count 13" in output + assert "bitmap_size 16 16" in output + assert "min_delay 0.08" in output + assert "max_delay 0.08" in output + # 13 frames * 0.08s = 1.04s + assert "duration 1.04" in output + assert "delay 0.08" in output + assert "deinited" in output + # Using a deinited OnDiskGif should raise an exception. + assert "after_deinit" in output + assert "done" in output + + +@pytest.mark.circuitpy_drive(_GIFIO_DECODE_DRIVE) +@pytest.mark.display(capture_times_ns=_DECODE_CAPTURE_TIMES_NS) +@pytest.mark.duration(60) +def test_gifio_decode(request, board, circuitpython): + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "size 16 16" in output + assert "frame_count 13" in output + for frame_index in range(_DECODE_FRAME_COUNT): + assert f"rendered {frame_index}" in output + assert "done" in output + + if board.startswith("native_native_sim_lvgl"): + # The frames are decoded correctly, but LVGL scales the TileGrid about pixel + # centers and resamples, so it doesn't match displayio's whole-pixel scaling. + request.applymarker(pytest.mark.xfail(reason="LVGL image scaling isn't pixel exact")) + + captures = circuitpython.display_capture_paths() + assert len(captures) == _DECODE_FRAME_COUNT + golden_dir = Path(__file__).parent / "golden" + for frame_index, capture in enumerate(captures): + golden = golden_dir / f"gifio_frame_{frame_index:02d}_320x240.png" + _golden_compare_or_update(request, [capture], golden) diff --git a/ports/zephyr-cp/tests/zephyr_display/test_jpegio.py b/ports/zephyr-cp/tests/zephyr_display/test_jpegio.py new file mode 100644 index 00000000000..ad03845e36f --- /dev/null +++ b/ports/zephyr-cp/tests/zephyr_display/test_jpegio.py @@ -0,0 +1,92 @@ +# SPDX-FileCopyrightText: 2026 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +import shutil +from pathlib import Path + +import pytest +from PIL import Image + + +_TEST_JPG_PATH = Path(__file__).parent / "test.jpg" +_TEST_JPG_BYTES = _TEST_JPG_PATH.read_bytes() + + +def _read_image(path: Path) -> tuple[int, int, bytes]: + with Image.open(path) as img: + rgb = img.convert("RGB") + return rgb.width, rgb.height, rgb.tobytes() + + +def _golden_compare_or_update(request, captures, golden_path): + if not captures or not captures[0].exists(): + pytest.skip("display capture was not produced") + + if request.config.getoption("--update-goldens"): + golden_path.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(captures[0], golden_path) + return + + gw, gh, gpx = _read_image(golden_path) + dw, dh, dpx = _read_image(captures[0]) + assert (dw, dh) == (gw, gh) + assert gpx == dpx + + +JPEGIO_DECODE_CODE = """\ +import board +import displayio +import time +from jpegio import JpegDecoder + +decoder = JpegDecoder() +width, height = decoder.open("/test.jpg") +print('size', width, height) + +bitmap = displayio.Bitmap(width, height, 65535) +decoder.decode(bitmap) + +for i in range(min(width, 8)): + print('px', i, hex(bitmap[i, 0])) + +scale = 10 +tg = displayio.TileGrid( + bitmap, + pixel_shader=displayio.ColorConverter( + input_colorspace=displayio.Colorspace.RGB565_SWAPPED + ), +) +g = displayio.Group(scale=scale) +g.x = (board.DISPLAY.width - width * scale) // 2 +g.y = (board.DISPLAY.height - height * scale) // 2 +g.append(tg) + +board.DISPLAY.auto_refresh = False +board.DISPLAY.root_group = g +board.DISPLAY.refresh() +print('rendered') +while True: + time.sleep(1) +""" + + +_JPEGIO_DRIVE = {"code.py": JPEGIO_DECODE_CODE, "test.jpg": _TEST_JPG_BYTES} + + +@pytest.mark.circuitpy_drive(_JPEGIO_DRIVE) +@pytest.mark.display(capture_times_ns=[14_000_000_000]) +@pytest.mark.duration(18) +def test_jpegio_decode(request, board, circuitpython): + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "size 20 20" in output + assert "rendered" in output + + if board.startswith("native_native_sim_lvgl"): + # The image is decoded correctly, but LVGL scales it about pixel centers and + # resamples, so it doesn't match displayio's whole-pixel scaling. + request.applymarker(pytest.mark.xfail(reason="LVGL image scaling isn't pixel exact")) + + golden = Path(__file__).parent / "golden" / "jpegio_test_pattern_320x240.png" + _golden_compare_or_update(request, circuitpython.display_capture_paths(), golden) diff --git a/ports/zephyr-cp/tests/zephyr_display/test_zephyr_display.py b/ports/zephyr-cp/tests/zephyr_display/test_zephyr_display.py new file mode 100644 index 00000000000..362459b199f --- /dev/null +++ b/ports/zephyr-cp/tests/zephyr_display/test_zephyr_display.py @@ -0,0 +1,513 @@ +# SPDX-FileCopyrightText: 2026 Scott Shawcroft for Adafruit Industries +# SPDX-License-Identifier: MIT + +import colorsys +import shutil +import struct +from pathlib import Path + +import pytest +from PIL import Image + + +def _read_image(path: Path) -> tuple[int, int, bytes]: + """Read an image file and return (width, height, RGB bytes).""" + with Image.open(path) as img: + rgb = img.convert("RGB") + return rgb.width, rgb.height, rgb.tobytes() + + +def _read_mask(golden_path: Path) -> bytes | None: + """Load the companion mask PNG for a golden image, if it exists. + + Non-zero pixels are masked (skipped during comparison). + """ + mask_path = golden_path.with_suffix(".mask.png") + if not mask_path.exists(): + return None + with Image.open(mask_path) as img: + return img.convert("L").tobytes() + + +def _assert_pixels_equal_masked( + golden_pixels: bytes, actual_pixels: bytes, mask: bytes | None = None +): + """Assert pixels match, skipping positions where the mask is non-zero.""" + assert len(golden_pixels) == len(actual_pixels) + for i in range(0, len(golden_pixels), 3): + if mask is not None and mask[i // 3] != 0: + continue + if golden_pixels[i : i + 3] != actual_pixels[i : i + 3]: + pixel = i // 3 + assert False, ( + f"Pixel {pixel} mismatch: " + f"golden={tuple(golden_pixels[i : i + 3])} " + f"actual={tuple(actual_pixels[i : i + 3])}" + ) + + +BOARD_DISPLAY_AVAILABLE_CODE = """\ +import board +print(hasattr(board, 'DISPLAY')) +print(type(board.DISPLAY).__name__) +print(board.DISPLAY.width, board.DISPLAY.height) +print('done') +""" + + +@pytest.mark.circuitpy_drive({"code.py": BOARD_DISPLAY_AVAILABLE_CODE}) +@pytest.mark.display +@pytest.mark.duration(8) +def test_board_display_available(circuitpython): + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "True" in output + assert "Display" in output + assert "320 240" in output + assert "done" in output + + +CONSOLE_TERMINAL_PRESENT_CODE = """\ +import board + +root = board.DISPLAY.root_group +has_terminal_tilegrids = ( + type(root).__name__ == 'Group' and + len(root) >= 2 and + type(root[0]).__name__ == 'TileGrid' and + type(root[-1]).__name__ == 'TileGrid' +) +print('has_terminal_tilegrids:', has_terminal_tilegrids) +print('done') +""" + + +@pytest.mark.circuitpy_drive({"code.py": CONSOLE_TERMINAL_PRESENT_CODE}) +@pytest.mark.display +@pytest.mark.duration(8) +def test_console_terminal_present_by_default(circuitpython): + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "has_terminal_tilegrids: True" in output + assert "done" in output + + +CONSOLE_OUTPUT_GOLDEN_CODE = """\ +import time +time.sleep(0.25) +print('done') +while True: + time.sleep(1) +""" + + +def _golden_compare_or_update(request, captures, golden_path, mask_path=None): + """Compare captured PNG against golden, or update golden if --update-goldens. + + mask_path overrides the default companion mask lookup (golden.mask.png). + """ + if not captures or not captures[0].exists(): + pytest.skip("display capture was not produced") + + if request.config.getoption("--update-goldens"): + golden_path.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(captures[0], golden_path) + return + + gw, gh, gpx = _read_image(golden_path) + dw, dh, dpx = _read_image(captures[0]) + if mask_path is not None: + mask = _read_mask(mask_path) + else: + mask = _read_mask(golden_path) + + assert (dw, dh) == (gw, gh) + _assert_pixels_equal_masked(gpx, dpx, mask) + + +@pytest.mark.circuitpy_drive({"code.py": CONSOLE_OUTPUT_GOLDEN_CODE}) +@pytest.mark.display(capture_times_ns=[4_000_000_000]) +@pytest.mark.duration(8) +def test_console_output_golden(request, circuitpython): + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "done" in output + + golden = Path(__file__).parent / "golden" / "terminal_console_output_320x240.png" + _golden_compare_or_update(request, circuitpython.display_capture_paths(), golden) + + +PIXEL_FORMATS = ["ARGB_8888", "RGB_888", "RGB_565", "BGR_565", "L_8", "AL_88", "MONO01", "MONO10"] + +# Shared mask: the same screen regions vary regardless of pixel format. +_CONSOLE_GOLDEN_MASK = Path(__file__).parent / "golden" / "terminal_console_output_320x240.png" + + +@pytest.mark.circuitpy_drive({"code.py": CONSOLE_OUTPUT_GOLDEN_CODE}) +@pytest.mark.display(capture_times_ns=[4_000_000_000]) +@pytest.mark.duration(8) +@pytest.mark.parametrize( + "pixel_format", + PIXEL_FORMATS, + indirect=True, +) +def test_console_output_golden_pixel_format(pixel_format, request, circuitpython): + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "done" in output + + golden_name = f"terminal_console_output_320x240_{pixel_format}.png" + golden = Path(__file__).parent / "golden" / golden_name + _golden_compare_or_update( + request, circuitpython.display_capture_paths(), golden, _CONSOLE_GOLDEN_MASK + ) + + +ROTATED_TERMINAL_CODE = """\ +import board +import displayio +import terminalio +import time +import zephyr_display + +displayio.release_displays() +display = zephyr_display.Display(auto_refresh=False) + +font = terminalio.FONT +cell_width, cell_height = font.get_bounding_box() +palette = displayio.Palette(2) +palette[0] = 0x000000 +palette[1] = 0xFFFFFF +group = displayio.Group() +grid = displayio.TileGrid(font.bitmap, pixel_shader=palette, width=20, height=10, + tile_width=cell_width, tile_height=cell_height) +group.append(grid) +terminal = terminalio.Terminal(grid, font) +terminal.write("ROTATED\\r\\nTERMINAL\\r\\n{rotation} DEG") + +display.root_group = group +display.rotation = {rotation} +display.refresh() +print('shown', display.rotation, display.width, display.height) +while True: + time.sleep(1) +""" + + +@pytest.fixture(params=[90, 180, 270]) +def terminal_rotation(request): + """Add a drive whose code sets the display to this rotation.""" + rotation = request.param + request.node.add_marker( + pytest.mark.circuitpy_drive({"code.py": ROTATED_TERMINAL_CODE.format(rotation=rotation)}) + ) + return rotation + + +@pytest.mark.display(capture_times_ns=[4_000_000_000]) +@pytest.mark.duration(8) +def test_terminal_rotated(terminal_rotation, request, circuitpython): + circuitpython.wait_until_done() + + width, height = (240, 320) if terminal_rotation in (90, 270) else (320, 240) + output = circuitpython.serial.all_output + assert f"shown {terminal_rotation} {width} {height}" in output + + golden = Path(__file__).parent / "golden" / f"terminal_rotated_{terminal_rotation}_320x240.png" + _golden_compare_or_update(request, circuitpython.display_capture_paths(), golden) + + +MONO_NO_VTILED_FORMATS = ["MONO01", "MONO10"] + + +@pytest.mark.circuitpy_drive({"code.py": CONSOLE_OUTPUT_GOLDEN_CODE}) +@pytest.mark.display(capture_times_ns=[4_000_000_000]) +@pytest.mark.display_mono_vtiled(False) +@pytest.mark.duration(8) +@pytest.mark.parametrize( + "pixel_format", + MONO_NO_VTILED_FORMATS, + indirect=True, +) +def test_console_output_golden_mono_no_vtiled(pixel_format, request, circuitpython): + circuitpython.wait_until_done() + + output = circuitpython.serial.all_output + assert "done" in output + + golden_name = f"terminal_console_output_320x240_{pixel_format}_no_vtiled.png" + golden = Path(__file__).parent / "golden" / golden_name + _golden_compare_or_update( + request, circuitpython.display_capture_paths(), golden, _CONSOLE_GOLDEN_MASK + ) + + +MONO_PARTIAL_UPDATE_CODE = """\ +import displayio +import time +import vectorio +import zephyr_display + +displayio.release_displays() +display = zephyr_display.Display(auto_refresh=False) +palette = displayio.Palette(1) +palette[0] = 0xFFFFFF +square = vectorio.Rectangle(pixel_shader=palette, width=6, height=6, x=3, y=3) +group = displayio.Group() +group.append(square) +display.root_group = group +display.refresh() +time.sleep(0.5) +square.x = 11 +square.y = 13 +display.refresh() +print("moved") +while True: + time.sleep(1) +""" + + +@pytest.mark.circuitpy_drive({"code.py": MONO_PARTIAL_UPDATE_CODE}) +@pytest.mark.display(capture_times_ns=[4_000_000_000]) +@pytest.mark.duration(6) +@pytest.mark.parametrize( + "vtiled", + [ + pytest.param(True, marks=pytest.mark.display_mono_vtiled(True)), + pytest.param(False, marks=pytest.mark.display_mono_vtiled(False)), + ], +) +@pytest.mark.parametrize("pixel_format", MONO_NO_VTILED_FORMATS, indirect=True) +def test_mono_partial_update_unaligned(pixel_format, vtiled, circuitpython): + """Check that moving a square off the 8 pixel grid redraws the whole square.""" + circuitpython.wait_until_done() + assert "moved" in circuitpython.serial.all_output + + image = Image.open(circuitpython.display_capture_paths()[0]).convert("L") + wrong_pixels = [] + for y in range(24): + for x in range(24): + expected_white = 11 <= x < 17 and 13 <= y < 19 + if (image.getpixel((x, y)) > 127) != expected_white: + wrong_pixels.append((x, y)) + assert not wrong_pixels + + +def _generate_gradient_bmp(width, height): + """Generate a 24-bit BMP with HSL color gradient. + + Hue sweeps left to right, lightness goes from black (bottom) to white (top), + saturation is 1.0. + """ + row_size = width * 3 + row_padding = (4 - (row_size % 4)) % 4 + padded_row_size = row_size + row_padding + pixel_data_size = padded_row_size * height + file_size = 14 + 40 + pixel_data_size + + header = struct.pack( + "<2sIHHI", + b"BM", + file_size, + 0, + 0, + 14 + 40, + ) + info = struct.pack( + " + +#include "supervisor/usb.h" + +static inline bool tud_connected(void) { + return usb_connected(); +} diff --git a/ports/zephyr-cp/zephyr-config/west.yml b/ports/zephyr-cp/zephyr-config/west.yml index 01712e864e0..10e7ae00b61 100644 --- a/ports/zephyr-cp/zephyr-config/west.yml +++ b/ports/zephyr-cp/zephyr-config/west.yml @@ -1,7 +1,62 @@ manifest: + group-filter: + - +babblesim + # TF-M and friends, no CircuitPython board builds with them. + - -tee projects: + - name: nrf_hw_models + url: https://github.com/tannewt/ext_nRF_hw_models + revision: 41cb69cd08848cc31e91ed62d01d397511981919 + path: modules/bsim_hw_models/nrf_hw_models + - name: mcuboot + url: https://github.com/adafruit/adaboot + revision: 587d61102408c6dc0cef1db180b9516d16d59e68 + path: bootloader/mcuboot - name: zephyr url: https://github.com/adafruit/zephyr - revision: circuitpython + revision: 87f27e4e1ce528367de5936cd4ee9fa4c32d42a8 clone-depth: 100 - import: true + import: + # Skip what no CircuitPython board can use, so west update fetches about + # half of the projects. Boards come from adafruit, nordic, nxp, + # raspberrypi, renesas, silabs, st and wch; the Pico W's CYW43 is in hal_infineon. + name-blocklist: + # HALs of vendors without a board here + - hal_adi + - hal_afbr + - hal_ambiq + - hal_atmel + - hal_bouffalolab + - hal_espressif + - hal_ethos_u + - hal_gigadevice + - hal_intel + - hal_microchip + - hal_nuvoton + - hal_openisa + - hal_quicklogic + - hal_realtek + - hal_sifli + - hal_tdk + - hal_telink + - hal_ti + - hal_wurthelektronik + - hal_xtensa + # libraries the port never enables + - acpica + - cmsis-dsp + - cmsis-nn + - dhara + - liblc3 + - libmctp + - libsbc + - lora-basics-modem + - loramac-node + - mipi-sys-t + - mldsa-native + - net-tools + - openthread + - percepio + - reqmgmt + - uoscore-uedhoc + - zephyr-xenlib diff --git a/ports/zephyr-cp/zephyr_main.c b/ports/zephyr-cp/zephyr_main.c index 8b8877c7b11..9954340b08e 100644 --- a/ports/zephyr-cp/zephyr_main.c +++ b/ports/zephyr-cp/zephyr_main.c @@ -1,8 +1,43 @@ #include +#include +#include + extern int circuitpython_main(void); +// Note: __has_feature must only be evaluated in a nested #if guarded by +// defined(__has_feature); older GCC versions fail to parse it otherwise. +#if defined(__has_feature) +#if __has_feature(address_sanitizer) +#define CP_HAS_ASAN 1 +#endif +#endif +#if defined(__SANITIZE_ADDRESS__) || defined(CP_HAS_ASAN) +// ASAN's stack-use-after-return detection (on by default in recent runtimes) +// moves C locals into "fake stack" frames on the heap. The GC scans the real +// machine stack for live object pointers, so with fake stacks enabled it misses +// pointers held in C frames and collects still-referenced objects, corrupting +// the heap. GCC's instrumentation consults this global at every instrumented +// function entry, so clearing it from a constructor disables only that check; +// all other ASAN checks stay enabled. +extern char __asan_option_detect_stack_use_after_return; +__attribute__((constructor)) static void cp_disable_asan_fake_stack(void) { + __asan_option_detect_stack_use_after_return = 0; +} +#endif + +// The reset cause read and cleared at boot, consumed by +// common-hal/microcontroller (nRF RESETREAS bits are sticky otherwise). +uint32_t cp_reset_cause = 0; + int main(void) { + // Read and clear the reset cause early: nRF's RESETREAS bits are sticky + // and would otherwise mask later causes in every subsequent get_reset_cause + // (e.g. a watchdog reset would keep reporting an older pin reset). Stash + // the value for get_reset_reason() and print it once as a boot diagnostic. + if (hwinfo_get_reset_cause(&cp_reset_cause) == 0) { + hwinfo_clear_reset_cause(); + } // Use a unique name for CP main so that the linker needs to look in libcircuitpython.a return circuitpython_main(); } diff --git a/py/argcheck.c b/py/argcheck.c index 9302dec96c3..155e29bdc15 100644 --- a/py/argcheck.c +++ b/py/argcheck.c @@ -170,13 +170,13 @@ void mp_arg_parse_all_kw_array(size_t n_pos, size_t n_kw, const mp_obj_t *args, } #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE -NORETURN void mp_arg_error_terse_mismatch(void) { +MP_NORETURN void mp_arg_error_terse_mismatch(void) { mp_raise_TypeError(MP_ERROR_TEXT("argument num/types mismatch")); } #endif #if MICROPY_CPYTHON_COMPAT -NORETURN void mp_arg_error_unimpl_kw(void) { +MP_NORETURN void mp_arg_error_unimpl_kw(void) { mp_raise_NotImplementedError(MP_ERROR_TEXT("keyword argument(s) not implemented - use normal args instead")); } #endif @@ -312,6 +312,6 @@ mp_int_t mp_arg_validate_type_int(mp_obj_t obj, qstr arg_name) { return an_int; } -NORETURN void mp_arg_error_invalid(qstr arg_name) { +MP_NORETURN void mp_arg_error_invalid(qstr arg_name) { mp_raise_ValueError_varg(MP_ERROR_TEXT("Invalid %q"), arg_name); } diff --git a/py/asmarm.c b/py/asmarm.c index 60064907012..15bc73b61ec 100644 --- a/py/asmarm.c +++ b/py/asmarm.c @@ -36,7 +36,7 @@ #include "py/asmarm.h" -#define SIGNED_FIT24(x) (((x) & 0xff800000) == 0) || (((x) & 0xff000000) == 0xff000000) +#define REG_TEMP ASM_ARM_REG_R8 // Insert word into instruction flow static void emit(asm_arm_t *as, uint op) { @@ -168,13 +168,23 @@ void asm_arm_entry(asm_arm_t *as, int num_locals) { emit_al(as, asm_arm_op_push(as->push_reglist | 1 << ASM_ARM_REG_LR)); if (as->stack_adjust > 0) { - emit_al(as, asm_arm_op_sub_imm(ASM_ARM_REG_SP, ASM_ARM_REG_SP, as->stack_adjust)); + if (as->stack_adjust < 0x100) { + emit_al(as, asm_arm_op_sub_imm(ASM_ARM_REG_SP, ASM_ARM_REG_SP, as->stack_adjust)); + } else { + asm_arm_mov_reg_i32_optimised(as, REG_TEMP, as->stack_adjust); + emit_al(as, asm_arm_op_sub_reg(ASM_ARM_REG_SP, ASM_ARM_REG_SP, REG_TEMP)); + } } } void asm_arm_exit(asm_arm_t *as) { if (as->stack_adjust > 0) { - emit_al(as, asm_arm_op_add_imm(ASM_ARM_REG_SP, ASM_ARM_REG_SP, as->stack_adjust)); + if (as->stack_adjust < 0x100) { + emit_al(as, asm_arm_op_add_imm(ASM_ARM_REG_SP, ASM_ARM_REG_SP, as->stack_adjust)); + } else { + asm_arm_mov_reg_i32_optimised(as, REG_TEMP, as->stack_adjust); + emit_al(as, asm_arm_op_add_reg(ASM_ARM_REG_SP, ASM_ARM_REG_SP, REG_TEMP)); + } } emit_al(as, asm_arm_op_pop(as->push_reglist | (1 << ASM_ARM_REG_PC))); @@ -282,8 +292,15 @@ 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) { - // add rd, sp, #local_num*4 - emit_al(as, asm_arm_op_add_imm(rd, ASM_ARM_REG_SP, local_num << 2)); + if (local_num >= 0x40) { + // mov temp, #local_num*4 + // add rd, sp, temp + asm_arm_mov_reg_i32_optimised(as, REG_TEMP, local_num << 2); + emit_al(as, asm_arm_op_add_reg(rd, ASM_ARM_REG_SP, REG_TEMP)); + } else { + // add rd, sp, #local_num*4 + 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) { @@ -316,39 +333,92 @@ void asm_arm_asr_reg_reg(asm_arm_t *as, uint rd, uint rs) { emit_al(as, 0x1a00050 | (rd << 12) | (rs << 8) | rd); } -void asm_arm_ldr_reg_reg(asm_arm_t *as, uint rd, uint rn, uint byte_offset) { - // ldr rd, [rn, #off] - emit_al(as, 0x5900000 | (rn << 16) | (rd << 12) | byte_offset); +void asm_arm_ldr_reg_reg_offset(asm_arm_t *as, uint rd, uint rn, uint byte_offset) { + if (byte_offset < 0x1000) { + // ldr rd, [rn, #off] + emit_al(as, 0x5900000 | (rn << 16) | (rd << 12) | byte_offset); + } else { + // mov temp, #off + // ldr rd, [rn, temp] + asm_arm_mov_reg_i32_optimised(as, REG_TEMP, byte_offset); + emit_al(as, 0x7900000 | (rn << 16) | (rd << 12) | REG_TEMP); + } } -void asm_arm_ldrh_reg_reg(asm_arm_t *as, uint rd, uint rn) { - // ldrh rd, [rn] - emit_al(as, 0x1d000b0 | (rn << 16) | (rd << 12)); +void asm_arm_ldrh_reg_reg_reg(asm_arm_t *as, uint rd, uint rm, uint rn) { + // ldrh doesn't support scaled register index + emit_al(as, 0x1a00080 | (REG_TEMP << 12) | rn); // mov temp, rn, lsl #1 + emit_al(as, 0x19000b0 | (rm << 16) | (rd << 12) | REG_TEMP); // ldrh rd, [rm, temp]; } void asm_arm_ldrh_reg_reg_offset(asm_arm_t *as, uint rd, uint rn, uint byte_offset) { - // ldrh rd, [rn, #off] - emit_al(as, 0x1f000b0 | (rn << 16) | (rd << 12) | ((byte_offset & 0xf0) << 4) | (byte_offset & 0xf)); + if (byte_offset < 0x100) { + // ldrh rd, [rn, #off] + emit_al(as, 0x1d000b0 | (rn << 16) | (rd << 12) | ((byte_offset & 0xf0) << 4) | (byte_offset & 0xf)); + } else { + // mov temp, #off + // ldrh rd, [rn, temp] + asm_arm_mov_reg_i32_optimised(as, REG_TEMP, byte_offset); + emit_al(as, 0x19000b0 | (rn << 16) | (rd << 12) | REG_TEMP); + } +} + +void asm_arm_ldrb_reg_reg_reg(asm_arm_t *as, uint rd, uint rm, uint rn) { + // ldrb rd, [rm, rn] + emit_al(as, 0x7d00000 | (rm << 16) | (rd << 12) | rn); } -void asm_arm_ldrb_reg_reg(asm_arm_t *as, uint rd, uint rn) { - // ldrb rd, [rn] - emit_al(as, 0x5d00000 | (rn << 16) | (rd << 12)); +void asm_arm_ldrb_reg_reg_offset(asm_arm_t *as, uint rd, uint rn, uint byte_offset) { + if (byte_offset < 0x1000) { + // ldrb rd, [rn, #off] + emit_al(as, 0x5d00000 | (rn << 16) | (rd << 12) | byte_offset); + } else { + // mov temp, #off + // ldrb rd, [rn, temp] + asm_arm_mov_reg_i32_optimised(as, REG_TEMP, byte_offset); + emit_al(as, 0x7d00000 | (rn << 16) | (rd << 12) | REG_TEMP); + } } -void asm_arm_str_reg_reg(asm_arm_t *as, uint rd, uint rm, uint byte_offset) { - // str rd, [rm, #off] - emit_al(as, 0x5800000 | (rm << 16) | (rd << 12) | byte_offset); +void asm_arm_ldr_reg_reg_reg(asm_arm_t *as, uint rd, uint rm, uint rn) { + // ldr rd, [rm, rn, lsl #2] + emit_al(as, 0x7900100 | (rm << 16) | (rd << 12) | rn); +} + +void asm_arm_str_reg_reg_offset(asm_arm_t *as, uint rd, uint rm, uint byte_offset) { + if (byte_offset < 0x1000) { + // str rd, [rm, #off] + emit_al(as, 0x5800000 | (rm << 16) | (rd << 12) | byte_offset); + } else { + // mov temp, #off + // str rd, [rm, temp] + asm_arm_mov_reg_i32_optimised(as, REG_TEMP, byte_offset); + emit_al(as, 0x7800000 | (rm << 16) | (rd << 12) | REG_TEMP); + } } -void asm_arm_strh_reg_reg(asm_arm_t *as, uint rd, uint rm) { - // strh rd, [rm] - emit_al(as, 0x1c000b0 | (rm << 16) | (rd << 12)); +void asm_arm_strh_reg_reg_offset(asm_arm_t *as, uint rd, uint rn, uint byte_offset) { + if (byte_offset < 0x100) { + // strh rd, [rn, #off] + emit_al(as, 0x1c000b0 | (rn << 16) | (rd << 12) | ((byte_offset & 0xf0) << 4) | (byte_offset & 0xf)); + } else { + // mov temp, #off + // strh rd, [rn, temp] + asm_arm_mov_reg_i32_optimised(as, REG_TEMP, byte_offset); + emit_al(as, 0x18000b0 | (rn << 16) | (rd << 12) | REG_TEMP); + } } -void asm_arm_strb_reg_reg(asm_arm_t *as, uint rd, uint rm) { - // strb rd, [rm] - emit_al(as, 0x5c00000 | (rm << 16) | (rd << 12)); +void asm_arm_strb_reg_reg_offset(asm_arm_t *as, uint rd, uint rm, uint byte_offset) { + if (byte_offset < 0x1000) { + // strb rd, [rm, #off] + emit_al(as, 0x5c00000 | (rm << 16) | (rd << 12) | byte_offset); + } else { + // mov temp, #off + // strb rd, [rm, temp] + asm_arm_mov_reg_i32_optimised(as, REG_TEMP, byte_offset); + emit_al(as, 0x7c00000 | (rm << 16) | (rd << 12) | REG_TEMP); + } } void asm_arm_str_reg_reg_reg(asm_arm_t *as, uint rd, uint rm, uint rn) { @@ -358,8 +428,8 @@ void asm_arm_str_reg_reg_reg(asm_arm_t *as, uint rd, uint rm, uint rn) { void asm_arm_strh_reg_reg_reg(asm_arm_t *as, uint rd, uint rm, uint rn) { // strh doesn't support scaled register index - emit_al(as, 0x1a00080 | (ASM_ARM_REG_R8 << 12) | rn); // mov r8, rn, lsl #1 - emit_al(as, 0x18000b0 | (rm << 16) | (rd << 12) | ASM_ARM_REG_R8); // strh rd, [rm, r8] + emit_al(as, 0x1a00080 | (REG_TEMP << 12) | rn); // mov temp, rn, lsl #1 + emit_al(as, 0x18000b0 | (rm << 16) | (rd << 12) | REG_TEMP); // strh rd, [rm, temp] } void asm_arm_strb_reg_reg_reg(asm_arm_t *as, uint rd, uint rm, uint rn) { @@ -374,7 +444,7 @@ void asm_arm_bcc_label(asm_arm_t *as, int cond, uint label) { rel -= 8; // account for instruction prefetch, PC is 8 bytes ahead of this instruction rel >>= 2; // in ARM mode the branch target is 32-bit aligned, so the 2 LSB are omitted - if (SIGNED_FIT24(rel)) { + if (MP_FIT_SIGNED(24, rel)) { emit(as, cond | 0xa000000 | (rel & 0xffffff)); } else { printf("asm_arm_bcc: branch does not fit in 24 bits\n"); diff --git a/py/asmarm.h b/py/asmarm.h index a0e057fce44..7a68e4c640f 100644 --- a/py/asmarm.h +++ b/py/asmarm.h @@ -50,21 +50,21 @@ #define ASM_ARM_REG_LR (ASM_ARM_REG_R14) #define ASM_ARM_REG_PC (ASM_ARM_REG_R15) -#define ASM_ARM_CC_EQ (0x0 << 28) -#define ASM_ARM_CC_NE (0x1 << 28) -#define ASM_ARM_CC_CS (0x2 << 28) -#define ASM_ARM_CC_CC (0x3 << 28) -#define ASM_ARM_CC_MI (0x4 << 28) -#define ASM_ARM_CC_PL (0x5 << 28) -#define ASM_ARM_CC_VS (0x6 << 28) -#define ASM_ARM_CC_VC (0x7 << 28) -#define ASM_ARM_CC_HI (0x8 << 28) -#define ASM_ARM_CC_LS (0x9 << 28) -#define ASM_ARM_CC_GE (0xa << 28) -#define ASM_ARM_CC_LT (0xb << 28) -#define ASM_ARM_CC_GT (0xc << 28) -#define ASM_ARM_CC_LE (0xd << 28) -#define ASM_ARM_CC_AL (0xe << 28) +#define ASM_ARM_CC_EQ (0x0u << 28) +#define ASM_ARM_CC_NE (0x1u << 28) +#define ASM_ARM_CC_CS (0x2u << 28) +#define ASM_ARM_CC_CC (0x3u << 28) +#define ASM_ARM_CC_MI (0x4u << 28) +#define ASM_ARM_CC_PL (0x5u << 28) +#define ASM_ARM_CC_VS (0x6u << 28) +#define ASM_ARM_CC_VC (0x7u << 28) +#define ASM_ARM_CC_HI (0x8u << 28) +#define ASM_ARM_CC_LS (0x9u << 28) +#define ASM_ARM_CC_GE (0xau << 28) +#define ASM_ARM_CC_LT (0xbu << 28) +#define ASM_ARM_CC_GT (0xcu << 28) +#define ASM_ARM_CC_LE (0xdu << 28) +#define ASM_ARM_CC_AL (0xeu << 28) typedef struct _asm_arm_t { mp_asm_base_t base; @@ -109,13 +109,18 @@ void asm_arm_lsr_reg_reg(asm_arm_t *as, uint rd, uint rs); void asm_arm_asr_reg_reg(asm_arm_t *as, uint rd, uint rs); // memory -void asm_arm_ldr_reg_reg(asm_arm_t *as, uint rd, uint rn, uint byte_offset); -void asm_arm_ldrh_reg_reg(asm_arm_t *as, uint rd, uint rn); +void asm_arm_ldr_reg_reg_offset(asm_arm_t *as, uint rd, uint rn, uint byte_offset); void asm_arm_ldrh_reg_reg_offset(asm_arm_t *as, uint rd, uint rn, uint byte_offset); -void asm_arm_ldrb_reg_reg(asm_arm_t *as, uint rd, uint rn); -void asm_arm_str_reg_reg(asm_arm_t *as, uint rd, uint rm, uint byte_offset); -void asm_arm_strh_reg_reg(asm_arm_t *as, uint rd, uint rm); -void asm_arm_strb_reg_reg(asm_arm_t *as, uint rd, uint rm); +void asm_arm_ldrb_reg_reg_offset(asm_arm_t *as, uint rd, uint rn, uint byte_offset); +void asm_arm_str_reg_reg_offset(asm_arm_t *as, uint rd, uint rm, uint byte_offset); +void asm_arm_strh_reg_reg_offset(asm_arm_t *as, uint rd, uint rm, uint byte_offset); +void asm_arm_strb_reg_reg_offset(asm_arm_t *as, uint rd, uint rm, uint byte_offset); + +// load from array +void asm_arm_ldr_reg_reg_reg(asm_arm_t *as, uint rd, uint rm, uint rn); +void asm_arm_ldrh_reg_reg_reg(asm_arm_t *as, uint rd, uint rm, uint rn); +void asm_arm_ldrb_reg_reg_reg(asm_arm_t *as, uint rd, uint rm, uint rn); + // store to array void asm_arm_str_reg_reg_reg(asm_arm_t *as, uint rd, uint rm, uint rn); void asm_arm_strh_reg_reg_reg(asm_arm_t *as, uint rd, uint rm, uint rn); @@ -160,12 +165,12 @@ void asm_arm_bx_reg(asm_arm_t *as, uint reg_src); // 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_T asm_arm_t +#define ASM_END_PASS asm_arm_end_pass +#define ASM_ENTRY(as, num_locals, name) asm_arm_entry((as), (num_locals)) +#define ASM_EXIT asm_arm_exit -#define ASM_JUMP asm_arm_b_label +#define ASM_JUMP asm_arm_b_label #define ASM_JUMP_IF_REG_ZERO(as, reg, label, bool_test) \ do { \ asm_arm_cmp_reg_i8(as, reg, 0); \ @@ -203,18 +208,30 @@ void asm_arm_bx_reg(asm_arm_t *as, uint reg_src); #define ASM_SUB_REG_REG(as, reg_dest, reg_src) asm_arm_sub_reg_reg_reg((as), (reg_dest), (reg_dest), (reg_src)) #define ASM_MUL_REG_REG(as, reg_dest, reg_src) asm_arm_mul_reg_reg_reg((as), (reg_dest), (reg_dest), (reg_src)) -#define ASM_LOAD_REG_REG(as, reg_dest, reg_base) asm_arm_ldr_reg_reg((as), (reg_dest), (reg_base), 0) -#define ASM_LOAD_REG_REG_OFFSET(as, reg_dest, reg_base, word_offset) asm_arm_ldr_reg_reg((as), (reg_dest), (reg_base), 4 * (word_offset)) -#define ASM_LOAD8_REG_REG(as, reg_dest, reg_base) asm_arm_ldrb_reg_reg((as), (reg_dest), (reg_base)) -#define ASM_LOAD16_REG_REG(as, reg_dest, reg_base) asm_arm_ldrh_reg_reg((as), (reg_dest), (reg_base)) -#define ASM_LOAD16_REG_REG_OFFSET(as, reg_dest, reg_base, uint16_offset) asm_arm_ldrh_reg_reg_offset((as), (reg_dest), (reg_base), 2 * (uint16_offset)) -#define ASM_LOAD32_REG_REG(as, reg_dest, reg_base) asm_arm_ldr_reg_reg((as), (reg_dest), (reg_base), 0) - -#define ASM_STORE_REG_REG(as, reg_value, reg_base) asm_arm_str_reg_reg((as), (reg_value), (reg_base), 0) -#define ASM_STORE_REG_REG_OFFSET(as, reg_dest, reg_base, word_offset) asm_arm_str_reg_reg((as), (reg_dest), (reg_base), 4 * (word_offset)) -#define ASM_STORE8_REG_REG(as, reg_value, reg_base) asm_arm_strb_reg_reg((as), (reg_value), (reg_base)) -#define ASM_STORE16_REG_REG(as, reg_value, reg_base) asm_arm_strh_reg_reg((as), (reg_value), (reg_base)) -#define ASM_STORE32_REG_REG(as, reg_value, reg_base) asm_arm_str_reg_reg((as), (reg_value), (reg_base), 0) +#define ASM_LOAD_REG_REG_OFFSET(as, reg_dest, reg_base, word_offset) ASM_LOAD32_REG_REG_OFFSET((as), (reg_dest), (reg_base), (word_offset)) +#define ASM_LOAD8_REG_REG(as, reg_dest, reg_base) ASM_LOAD8_REG_REG_OFFSET((as), (reg_dest), (reg_base), 0) +#define ASM_LOAD8_REG_REG_OFFSET(as, reg_dest, reg_base, byte_offset) asm_arm_ldrb_reg_reg_offset((as), (reg_dest), (reg_base), (byte_offset)) +#define ASM_LOAD16_REG_REG(as, reg_dest, reg_base) ASM_LOAD16_REG_REG_OFFSET((as), (reg_dest), (reg_base), 0) +#define ASM_LOAD16_REG_REG_OFFSET(as, reg_dest, reg_base, halfword_offset) asm_arm_ldrh_reg_reg_offset((as), (reg_dest), (reg_base), 2 * (halfword_offset)) +#define ASM_LOAD32_REG_REG(as, reg_dest, reg_base) ASM_LOAD32_REG_REG_OFFSET((as), (reg_dest), (reg_base), 0) +#define ASM_LOAD32_REG_REG_OFFSET(as, reg_dest, reg_base, word_offset) asm_arm_ldr_reg_reg_offset((as), (reg_dest), (reg_base), 4 * (word_offset)) + +#define ASM_STORE_REG_REG_OFFSET(as, reg_value, reg_base, word_offset) ASM_STORE32_REG_REG_OFFSET((as), (reg_value), (reg_base), (word_offset)) +#define ASM_STORE8_REG_REG(as, reg_value, reg_base) ASM_STORE8_REG_REG_OFFSET((as), (reg_value), (reg_base), 0) +#define ASM_STORE8_REG_REG_OFFSET(as, reg_value, reg_base, byte_offset) asm_arm_strb_reg_reg_offset((as), (reg_value), (reg_base), (byte_offset)) +#define ASM_STORE16_REG_REG(as, reg_value, reg_base) ASM_STORE16_REG_REG_OFFSET((as), (reg_value), (reg_base), 0) +#define ASM_STORE16_REG_REG_OFFSET(as, reg_value, reg_base, halfword_offset) asm_arm_strh_reg_reg_offset((as), (reg_value), (reg_base), 2 * (halfword_offset)) +#define ASM_STORE32_REG_REG(as, reg_value, reg_base) ASM_STORE32_REG_REG_OFFSET((as), (reg_value), (reg_base), 0) +#define ASM_STORE32_REG_REG_OFFSET(as, reg_value, reg_base, word_offset) asm_arm_str_reg_reg_offset((as), (reg_value), (reg_base), 4 * (word_offset)) + +#define ASM_LOAD8_REG_REG_REG(as, reg_dest, reg_base, reg_index) asm_arm_ldrb_reg_reg_reg((as), (reg_dest), (reg_base), (reg_index)) +#define ASM_LOAD16_REG_REG_REG(as, reg_dest, reg_base, reg_index) asm_arm_ldrh_reg_reg_reg((as), (reg_dest), (reg_base), (reg_index)) +#define ASM_LOAD32_REG_REG_REG(as, reg_dest, reg_base, reg_index) asm_arm_ldr_reg_reg_reg((as), (reg_dest), (reg_base), (reg_index)) +#define ASM_STORE8_REG_REG_REG(as, reg_val, reg_base, reg_index) asm_arm_strb_reg_reg_reg((as), (reg_val), (reg_base), (reg_index)) +#define ASM_STORE16_REG_REG_REG(as, reg_val, reg_base, reg_index) asm_arm_strh_reg_reg_reg((as), (reg_val), (reg_base), (reg_index)) +#define ASM_STORE32_REG_REG_REG(as, reg_val, reg_base, reg_index) asm_arm_str_reg_reg_reg((as), (reg_val), (reg_base), (reg_index)) + +#define ASM_CLR_REG(as, reg_dest) asm_arm_eor_reg_reg_reg((as), (reg_dest), (reg_dest), (reg_dest)) #endif // GENERIC_ASM_API diff --git a/py/asmbase.c b/py/asmbase.c index cf64e3f3d05..07dbf4430f9 100644 --- a/py/asmbase.c +++ b/py/asmbase.c @@ -30,6 +30,7 @@ #include "py/obj.h" #include "py/misc.h" #include "py/asmbase.h" +#include "py/persistentcode.h" #if MICROPY_EMIT_MACHINE_CODE @@ -52,7 +53,7 @@ void mp_asm_base_start_pass(mp_asm_base_t *as, int pass) { } else { // allocating executable RAM is platform specific MP_PLAT_ALLOC_EXEC(as->code_offset, (void **)&as->code_base, &as->code_size); - assert(as->code_base != NULL); + assert(as->code_size == 0 || as->code_base != NULL); } as->pass = pass; as->suppress = false; @@ -91,12 +92,17 @@ void mp_asm_base_label_assign(mp_asm_base_t *as, size_t label) { } else { // ensure label offset has not changed from PASS_COMPUTE to PASS_EMIT assert(as->label_offsets[label] == as->code_offset); + #if MICROPY_DYNAMIC_COMPILER && MICROPY_EMIT_NATIVE_DEBUG + if (mp_dynamic_compiler.native_arch == MP_NATIVE_ARCH_DEBUG) { + mp_printf(MICROPY_EMIT_NATIVE_DEBUG_PRINTER, "label(label_%u)\n", (unsigned int)label); + } + #endif } } // align must be a multiple of 2 void mp_asm_base_align(mp_asm_base_t *as, unsigned int align) { - as->code_offset = (as->code_offset + align - 1) & (~(align - 1)); + as->code_offset = (as->code_offset + align - 1) & (~(size_t)(align - 1)); } // this function assumes a little endian machine diff --git a/py/asmbase.h b/py/asmbase.h index 352d2f54cc8..461393fe77f 100644 --- a/py/asmbase.h +++ b/py/asmbase.h @@ -27,6 +27,7 @@ #define MICROPY_INCLUDED_PY_ASMBASE_H #include +#include #include #define MP_ASM_PASS_COMPUTE (1) diff --git a/py/asmrv32.c b/py/asmrv32.c new file mode 100644 index 00000000000..53481d1d0f3 --- /dev/null +++ b/py/asmrv32.c @@ -0,0 +1,675 @@ +/* + * This file is part of the MicroPython project, https://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2024 Alessandro Gatti + * + * 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/emit.h" +#include "py/misc.h" +#include "py/mpconfig.h" + +// wrapper around everything in this file +#if MICROPY_EMIT_RV32 + +#include "py/asmrv32.h" +#include "py/mpstate.h" +#include "py/persistentcode.h" + +#if MICROPY_DEBUG_VERBOSE +#define DEBUG_PRINT (1) +#define DEBUG_printf DEBUG_printf +#else +#define DEBUG_printf(...) (void)0 +#endif + +#define INTERNAL_TEMPORARY ASM_RV32_REG_S0 + +#define FIT_UNSIGNED(value, bits) (((value) & ~((1U << (bits)) - 1)) == 0) +#define FIT_SIGNED(value, bits) \ + ((((value) & ~((1U << ((bits) - 1)) - 1)) == 0) || \ + (((value) & ~((1U << ((bits) - 1)) - 1)) == ~((1U << ((bits) - 1)) - 1))) + +static bool asm_rv32_allow_zba_opcodes(void) { + return asm_rv32_allowed_extensions() & RV32_EXT_ZBA; +} + +static bool asm_rv32_allow_zcmp_opcodes(void) { + return asm_rv32_allowed_extensions() & RV32_EXT_ZCMP; +} + +/////////////////////////////////////////////////////////////////////////////// + +void asm_rv32_emit_word_opcode(asm_rv32_t *state, mp_uint_t word) { + uint8_t *cursor = mp_asm_base_get_cur_to_write_bytes(&state->base, sizeof(uint32_t)); + if (cursor == NULL) { + return; + } + + #if MP_ENDIANNESS_LITTLE + cursor[0] = word & 0xFF; + cursor[1] = (word >> 8) & 0xFF; + cursor[2] = (word >> 16) & 0xFF; + cursor[3] = (word >> 24) & 0xFF; + #else + cursor[0] = (word >> 24) & 0xFF; + cursor[1] = (word >> 16) & 0xFF; + cursor[2] = (word >> 8) & 0xFF; + cursor[3] = word & 0xFF; + #endif +} + +void asm_rv32_emit_halfword_opcode(asm_rv32_t *state, mp_uint_t word) { + uint8_t *cursor = mp_asm_base_get_cur_to_write_bytes(&state->base, sizeof(uint16_t)); + if (cursor == NULL) { + return; + } + + #if MP_ENDIANNESS_LITTLE + cursor[0] = word & 0xFF; + cursor[1] = (word >> 8) & 0xFF; + #else + cursor[0] = (word >> 8) & 0xFF; + cursor[1] = word & 0xFF; + #endif +} + +/////////////////////////////////////////////////////////////////////////////// + +static void split_immediate(mp_int_t immediate, mp_uint_t *upper, mp_uint_t *lower) { + assert(upper != NULL && "Upper pointer is NULL."); + assert(lower != NULL && "Lower pointer is NULL."); + + mp_uint_t unsigned_immediate = *((mp_uint_t *)&immediate); + *upper = unsigned_immediate & 0xFFFFF000; + *lower = unsigned_immediate & 0x00000FFF; + + // Turn the lower half from unsigned to signed. + if ((*lower & 0x800) != 0) { + *upper += 0x1000; + } +} + +static void load_upper_immediate(asm_rv32_t *state, mp_uint_t rd, mp_uint_t immediate) { + // if immediate fits in 17 bits and is ≠ 0: + // c.lui rd, HI(immediate) + // else: + // lui rd, HI(immediate) + if (FIT_SIGNED(immediate, 17) && ((immediate >> 12) != 0)) { + asm_rv32_opcode_clui(state, rd, immediate); + } else { + asm_rv32_opcode_lui(state, rd, immediate); + } +} + +static void load_lower_immediate(asm_rv32_t *state, mp_uint_t rd, mp_uint_t immediate) { + // WARNING: This must be executed on a register that has either been + // previously cleared or was the target of a LUI/C.LUI or + // AUIPC opcode. + + if (immediate == 0) { + return; + } + + // if LO(immediate) fits in 6 bits: + // c.addi rd, LO(immediate) + // else: + // addi rd, rd, LO(immediate) + if (FIT_SIGNED(immediate, 6)) { + asm_rv32_opcode_caddi(state, rd, immediate); + } else { + asm_rv32_opcode_addi(state, rd, rd, immediate); + } +} + +static void load_full_immediate(asm_rv32_t *state, mp_uint_t rd, mp_int_t immediate) { + mp_uint_t upper = 0; + mp_uint_t lower = 0; + split_immediate(immediate, &upper, &lower); + + // if immediate fits in 17 bits: + // c.lui rd, HI(immediate) + // else: + // lui rd, HI(immediate) + // if LO(immediate) fits in 6 bits && LO(immediate) != 0: + // c.addi rd, LO(immediate) + // else: + // addi rd, rd, LO(immediate) + load_upper_immediate(state, rd, upper); + load_lower_immediate(state, rd, lower); +} + +void asm_rv32_emit_optimised_load_immediate(asm_rv32_t *state, mp_uint_t rd, mp_int_t immediate) { + if (FIT_SIGNED(immediate, 6)) { + // c.li rd, immediate + asm_rv32_opcode_cli(state, rd, immediate); + return; + } + + if (FIT_SIGNED(immediate, 12)) { + // addi rd, zero, immediate + asm_rv32_opcode_addi(state, rd, ASM_RV32_REG_ZERO, immediate); + return; + } + + load_full_immediate(state, rd, immediate); +} + +// RV32 does not have dedicated push/pop opcodes, so series of loads and +// stores are generated in their place. + +static void emit_registers_store(asm_rv32_t *state, mp_uint_t registers_mask) { + mp_uint_t offset = 0; + for (mp_uint_t register_index = 0; register_index < RV32_AVAILABLE_REGISTERS_COUNT; register_index++) { + if (registers_mask & (1U << register_index)) { + assert(FIT_UNSIGNED(offset >> 2, 6) && "Registers save stack offset out of range."); + // c.swsp register, offset + asm_rv32_opcode_cswsp(state, register_index, offset); + offset += sizeof(uint32_t); + } + } +} + +static void emit_registers_load(asm_rv32_t *state, mp_uint_t registers_mask) { + mp_uint_t offset = 0; + for (mp_uint_t register_index = 0; register_index < RV32_AVAILABLE_REGISTERS_COUNT; register_index++) { + if (registers_mask & (1U << register_index)) { + assert(FIT_UNSIGNED(offset >> 2, 6) && "Registers load stack offset out of range."); + // c.lwsp register, offset + asm_rv32_opcode_clwsp(state, register_index, offset); + offset += sizeof(uint32_t); + } + } +} + +static void adjust_stack(asm_rv32_t *state, mp_int_t stack_size) { + if (stack_size == 0) { + return; + } + + if (FIT_SIGNED(stack_size, 6)) { + // c.addi sp, stack_size + asm_rv32_opcode_caddi(state, ASM_RV32_REG_SP, stack_size); + return; + } + + if (FIT_SIGNED(stack_size, 12)) { + // addi sp, sp, stack_size + asm_rv32_opcode_addi(state, ASM_RV32_REG_SP, ASM_RV32_REG_SP, stack_size); + return; + } + + // WARNING: If REG_TEMP0 is not set to a caller-saved register, then this + // bit has to be rewritten to avoid clobbering the temporary + // register when performing the stack adjustment. + + MP_STATIC_ASSERT(((REG_TEMP0 >= ASM_RV32_REG_T0) && (REG_TEMP0 <= ASM_RV32_REG_T2)) || \ + ((REG_TEMP0 >= ASM_RV32_REG_A0) && (REG_TEMP0 <= ASM_RV32_REG_A7)) || \ + ((REG_TEMP0 >= ASM_RV32_REG_T3) && (REG_TEMP0 <= ASM_RV32_REG_T6))); + + // li temporary, stack_size + // c.add sp, temporary + load_full_immediate(state, REG_TEMP0, stack_size); + asm_rv32_opcode_cadd(state, ASM_RV32_REG_SP, REG_TEMP0); +} + +// Generate a generic function entry prologue code sequence, setting up the +// stack to hold all the tainted registers and an arbitrary amount of space +// for locals. +static void emit_function_prologue(asm_rv32_t *state, mp_uint_t registers) { + mp_uint_t registers_count = mp_popcount(registers); + state->stack_size = (registers_count + state->locals_count) * sizeof(uint32_t); + mp_uint_t old_saved_registers_mask = state->saved_registers_mask; + // Move stack pointer up. + adjust_stack(state, -state->stack_size); + // Store registers at the top of the saved stack area. + emit_registers_store(state, registers); + state->locals_stack_offset = registers_count * sizeof(uint32_t); + state->saved_registers_mask = old_saved_registers_mask; +} + +// Restore registers and reset the stack pointer to its initial value. +static void emit_function_epilogue(asm_rv32_t *state, mp_uint_t registers) { + mp_uint_t old_saved_registers_mask = state->saved_registers_mask; + // Restore registers from the top of the stack area. + emit_registers_load(state, registers); + // Move stack pointer down. + adjust_stack(state, state->stack_size); + state->saved_registers_mask = old_saved_registers_mask; +} + +static mp_uint_t compute_zcmp_sequence_length(mp_uint_t registers) { + // Can only handle RA and S0..S11 and must have at least one entry. + assert((registers != 0) && (registers & (~0x0FFC0302U)) == 0 && "Invalid Zcmp registers set."); + mp_uint_t length = 32 - mp_clz(((registers & 0x00000002) >> 1) | ((registers & 0x00000300) >> 7) | ((registers & 0x0FFC0000) >> 15)); + return length == 12 ? 13 : length; +} + +#define EMIT_ASSERT(state, condition, message) assert((((state)->base.pass != MP_ASM_PASS_EMIT) ? true : (condition)) && (message)) + +static void emit_compressed_function_prologue(asm_rv32_t *state, mp_uint_t registers_mask) { + mp_uint_t sequence_length = compute_zcmp_sequence_length(registers_mask); + mp_uint_t allocated_stack = (sequence_length + 3) & (mp_uint_t)-4; + EMIT_ASSERT(state, allocated_stack >= sequence_length, "Incorrect allocated stack calculation."); + mp_uint_t tail_slack = allocated_stack - sequence_length; + mp_uint_t locals_left = (state->locals_count < tail_slack) ? 0 : (state->locals_count - tail_slack); + mp_uint_t adjustment_chunks = MIN(3, locals_left / 4); + EMIT_ASSERT(state, (adjustment_chunks * 4) <= locals_left, "Incorrect adjustment chunks rounding."); + locals_left -= adjustment_chunks * 4; + EMIT_ASSERT(state, locals_left <= (MP_INT_MAX / sizeof(uint32_t)), "Too many locals."); + mp_int_t stack_size = (mp_int_t)(locals_left * sizeof(uint32_t)); + asm_rv32_opcode_cmpush(state, MIN(3 + sequence_length, 15), adjustment_chunks); + // CM.PUSH allocates a stack block and then puts the registers *at the end* + // of the block, so for example "CM.PUSH {RA, S0-S11}, -64" will put RA at + // SP + 60, not at SP + 0. + adjust_stack(state, -stack_size); + // The stack size is expressed in bytes and as a multiple of 4, hence the + // bottom two bits are not used. Since there can be up to three adjustment + // chunks, that number can be expressed in two bits, fitting nicely in the + // existing variable. + state->stack_size = ((mp_uint_t)stack_size) | adjustment_chunks; +} + +static void emit_compressed_function_epilogue(asm_rv32_t *state, mp_uint_t registers_mask) { + mp_uint_t sequence_length = compute_zcmp_sequence_length(registers_mask); + mp_uint_t stack_size = state->stack_size & (mp_uint_t)(~0x03U); + adjust_stack(state, stack_size); + asm_rv32_opcode_cmpopret(state, MIN(3 + sequence_length, 15), state->stack_size & 0x03); +} + +static bool calculate_displacement_for_label(asm_rv32_t *state, mp_uint_t label, ptrdiff_t *displacement) { + assert(displacement != NULL && "Displacement pointer is NULL"); + + mp_uint_t label_offset = state->base.label_offsets[label]; + *displacement = (ptrdiff_t)(label_offset - state->base.code_offset); + return (label_offset != (mp_uint_t)-1) && (*displacement < 0); +} + +/////////////////////////////////////////////////////////////////////////////// + +void asm_rv32_entry(asm_rv32_t *state, mp_uint_t locals) { + state->locals_count = locals; + state->saved_registers_mask |= (1U << REG_FUN_TABLE) | (1U << REG_LOCAL_1) | \ + (1U << REG_LOCAL_2) | (1U << REG_LOCAL_3); + if (asm_rv32_allow_zcmp_opcodes()) { + emit_compressed_function_prologue(state, state->saved_registers_mask); + } else { + emit_function_prologue(state, state->saved_registers_mask); + } +} + +void asm_rv32_exit(asm_rv32_t *state) { + if (asm_rv32_allow_zcmp_opcodes()) { + emit_compressed_function_epilogue(state, state->saved_registers_mask); + } else { + emit_function_epilogue(state, state->saved_registers_mask); + // c.jr ra + asm_rv32_opcode_cjr(state, ASM_RV32_REG_RA); + } +} + +void asm_rv32_end_pass(asm_rv32_t *state) { + (void)state; +} + +void asm_rv32_emit_call_ind(asm_rv32_t *state, mp_uint_t index) { + mp_uint_t offset = index * ASM_WORD_SIZE; + state->saved_registers_mask |= (1U << ASM_RV32_REG_RA); + + if (RV32_IS_IN_C_REGISTER_WINDOW(REG_FUN_TABLE) && RV32_IS_IN_C_REGISTER_WINDOW(INTERNAL_TEMPORARY) && FIT_UNSIGNED(offset, 6)) { + state->saved_registers_mask |= (1U << INTERNAL_TEMPORARY); + // c.lw temporary, offset(fun_table) + // c.jalr temporary + asm_rv32_opcode_clw(state, RV32_MAP_IN_C_REGISTER_WINDOW(INTERNAL_TEMPORARY), RV32_MAP_IN_C_REGISTER_WINDOW(REG_FUN_TABLE), offset); + asm_rv32_opcode_cjalr(state, INTERNAL_TEMPORARY); + return; + } + + if (FIT_UNSIGNED(offset, 11)) { + // lw temporary, offset(fun_table) + // c.jalr temporary + asm_rv32_opcode_lw(state, REG_TEMP2, REG_FUN_TABLE, offset); + asm_rv32_opcode_cjalr(state, REG_TEMP2); + return; + } + + mp_uint_t upper = 0; + mp_uint_t lower = 0; + split_immediate(offset, &upper, &lower); + + // lui temporary, HI(index) ; Or c.lui if possible + // c.add temporary, fun_table + // lw temporary, LO(index)(temporary) + // c.jalr temporary + load_upper_immediate(state, REG_TEMP2, upper); + asm_rv32_opcode_cadd(state, REG_TEMP2, REG_FUN_TABLE); + asm_rv32_opcode_lw(state, REG_TEMP2, REG_TEMP2, lower); + asm_rv32_opcode_cjalr(state, REG_TEMP2); +} + +void asm_rv32_emit_jump_if_reg_eq(asm_rv32_t *state, mp_uint_t rs1, mp_uint_t rs2, mp_uint_t label) { + ptrdiff_t displacement = 0; + bool can_emit_short_jump = calculate_displacement_for_label(state, label, &displacement); + + if (can_emit_short_jump && FIT_SIGNED(displacement, 13)) { + // beq rs1, rs2, displacement + asm_rv32_opcode_beq(state, rs1, rs2, displacement); + return; + } + + // Compensate for the initial BNE opcode. + displacement -= ASM_WORD_SIZE; + + mp_uint_t upper = 0; + mp_uint_t lower = 0; + split_immediate(displacement, &upper, &lower); + + // bne rs1, rs2, 12 ; PC + 0 + // auipc temporary, HI(displacement) ; PC + 4 + // jalr zero, temporary, LO(displacement) ; PC + 8 + // ... ; PC + 12 + asm_rv32_opcode_bne(state, rs1, rs2, 12); + asm_rv32_opcode_auipc(state, REG_TEMP2, upper); + asm_rv32_opcode_jalr(state, ASM_RV32_REG_ZERO, REG_TEMP2, lower); +} + +void asm_rv32_emit_jump_if_reg_nonzero(asm_rv32_t *state, mp_uint_t rs, mp_uint_t label) { + ptrdiff_t displacement = 0; + bool can_emit_short_jump = calculate_displacement_for_label(state, label, &displacement); + + if (can_emit_short_jump && FIT_SIGNED(displacement, 8) && RV32_IS_IN_C_REGISTER_WINDOW(rs)) { + // c.bnez rs', displacement + asm_rv32_opcode_cbnez(state, RV32_MAP_IN_C_REGISTER_WINDOW(rs), displacement); + return; + } + + if (can_emit_short_jump && FIT_SIGNED(displacement, 13)) { + // bne rs, zero, displacement + asm_rv32_opcode_bne(state, rs, ASM_RV32_REG_ZERO, displacement); + return; + } + + // if rs1 in C window and displacement is negative: + // c.beqz rs', 10 ; PC + 0 + // auipc temporary, HI(displacement) ; PC + 2 + // jalr zero, temporary, LO(displacement) ; PC + 6 + // ... ; PC + 10 + // else: + // beq rs, zero, 12 ; PC + 0 + // auipc temporary, HI(displacement) ; PC + 4 + // jalr zero, temporary, LO(displacement) ; PC + 8 + // ... ; PC + 12 + + if (can_emit_short_jump && RV32_IS_IN_C_REGISTER_WINDOW(rs)) { + asm_rv32_opcode_cbeqz(state, RV32_MAP_IN_C_REGISTER_WINDOW(rs), 10); + // Compensate for the C.BEQZ opcode. + displacement -= ASM_HALFWORD_SIZE; + } else { + asm_rv32_opcode_beq(state, rs, ASM_RV32_REG_ZERO, 12); + // Compensate for the BEQ opcode. + displacement -= ASM_WORD_SIZE; + } + + mp_uint_t upper = 0; + mp_uint_t lower = 0; + split_immediate(displacement, &upper, &lower); + asm_rv32_opcode_auipc(state, REG_TEMP2, upper); + asm_rv32_opcode_jalr(state, ASM_RV32_REG_ZERO, REG_TEMP2, lower); +} + +void asm_rv32_emit_mov_local_reg(asm_rv32_t *state, mp_uint_t local, mp_uint_t rs) { + mp_uint_t offset = state->locals_stack_offset + (local * ASM_WORD_SIZE); + + if (FIT_UNSIGNED(offset >> 2, 6)) { + // c.swsp rs, offset + asm_rv32_opcode_cswsp(state, rs, offset); + return; + } + + if (FIT_UNSIGNED(offset, 11)) { + // sw rs, offset(sp) + asm_rv32_opcode_sw(state, rs, ASM_RV32_REG_SP, offset); + return; + } + + mp_uint_t upper = 0; + mp_uint_t lower = 0; + split_immediate(offset, &upper, &lower); + + // lui temporary, HI(offset) ; Or c.lui if possible + // c.add temporary, sp + // sw rs, LO(offset)(temporary) + load_upper_immediate(state, REG_TEMP2, upper); + asm_rv32_opcode_cadd(state, REG_TEMP2, ASM_RV32_REG_SP); + asm_rv32_opcode_sw(state, rs, REG_TEMP2, lower); +} + +void asm_rv32_emit_mov_reg_local(asm_rv32_t *state, mp_uint_t rd, mp_uint_t local) { + mp_uint_t offset = state->locals_stack_offset + (local * ASM_WORD_SIZE); + + if (FIT_UNSIGNED(offset >> 2, 6)) { + // c.lwsp rd, offset + asm_rv32_opcode_clwsp(state, rd, offset); + return; + } + + if (FIT_UNSIGNED(offset, 11)) { + // lw rd, offset(sp) + asm_rv32_opcode_lw(state, rd, ASM_RV32_REG_SP, offset); + return; + } + + mp_uint_t upper = 0; + mp_uint_t lower = 0; + split_immediate(offset, &upper, &lower); + + // lui rd, HI(offset) ; Or c.lui if possible + // c.add rd, sp + // lw rd, LO(offset)(rd) + load_upper_immediate(state, rd, upper); + asm_rv32_opcode_cadd(state, rd, ASM_RV32_REG_SP); + asm_rv32_opcode_lw(state, rd, rd, lower); +} + +void asm_rv32_emit_mov_reg_local_addr(asm_rv32_t *state, mp_uint_t rd, mp_uint_t local) { + mp_uint_t offset = state->locals_stack_offset + (local * ASM_WORD_SIZE); + + if (FIT_UNSIGNED(offset, 10) && offset != 0 && RV32_IS_IN_C_REGISTER_WINDOW(rd)) { + // c.addi4spn rd', offset + asm_rv32_opcode_caddi4spn(state, RV32_MAP_IN_C_REGISTER_WINDOW(rd), offset); + return; + } + + if (FIT_UNSIGNED(offset, 11)) { + // addi rd, sp, offset + asm_rv32_opcode_addi(state, rd, ASM_RV32_REG_SP, offset); + return; + } + + // li rd, offset + // c.add rd, sp + load_full_immediate(state, rd, offset); + asm_rv32_opcode_cadd(state, rd, ASM_RV32_REG_SP); +} + +// ((word: 4) << 8) | ((halfword: 4) << 4) | (byte: 4) +#define RV32_LOAD_OPCODE_FT3(size) ((0x0254 >> (size << 2)) & 0x0F) + +void asm_rv32_emit_load_reg_reg_offset(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs, int32_t offset, mp_uint_t operation_size) { + assert(operation_size <= 2 && "Operation size value out of range."); + + int32_t scaled_offset = offset << operation_size; + + if (scaled_offset >= 0 && operation_size == 2 && RV32_IS_IN_C_REGISTER_WINDOW(rd) && RV32_IS_IN_C_REGISTER_WINDOW(rs) && MP_FIT_UNSIGNED(6, scaled_offset)) { + // c.lw rd', offset(rs') + asm_rv32_opcode_clw(state, RV32_MAP_IN_C_REGISTER_WINDOW(rd), RV32_MAP_IN_C_REGISTER_WINDOW(rs), scaled_offset); + return; + } + + if (MP_FIT_SIGNED(12, scaled_offset)) { + // lbu|lhu|lw rd, offset(rs) + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_I(0x03, RV32_LOAD_OPCODE_FT3(operation_size), rd, rs, scaled_offset)); + return; + } + + mp_uint_t upper = 0; + mp_uint_t lower = 0; + split_immediate(scaled_offset, &upper, &lower); + + // lui rd, HI(offset) ; Or c.lui if possible + // c.add rd, rs + // lbu|lhu|lw rd, LO(offset)(rd) + load_upper_immediate(state, rd, upper); + asm_rv32_opcode_cadd(state, rd, rs); + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_I(0x03, RV32_LOAD_OPCODE_FT3(operation_size), rd, rd, lower)); +} + +void asm_rv32_emit_jump(asm_rv32_t *state, mp_uint_t label) { + ptrdiff_t displacement = 0; + bool can_emit_short_jump = calculate_displacement_for_label(state, label, &displacement); + + if (can_emit_short_jump && FIT_SIGNED(displacement, 12)) { + // c.j displacement + asm_rv32_opcode_cj(state, displacement); + return; + } + + mp_uint_t upper = 0; + mp_uint_t lower = 0; + split_immediate(displacement, &upper, &lower); + + // auipc temporary, HI(displacement) + // jalr zero, temporary, LO(displacement) + asm_rv32_opcode_auipc(state, REG_TEMP2, upper); + asm_rv32_opcode_jalr(state, ASM_RV32_REG_ZERO, REG_TEMP2, lower); +} + +void asm_rv32_emit_store_reg_reg_offset(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs, int32_t offset, mp_uint_t operation_size) { + assert(operation_size <= 2 && "Operation size value out of range."); + + int32_t scaled_offset = offset << operation_size; + + if (scaled_offset >= 0 && operation_size == 2 && RV32_IS_IN_C_REGISTER_WINDOW(rd) && RV32_IS_IN_C_REGISTER_WINDOW(rs) && MP_FIT_UNSIGNED(6, scaled_offset)) { + // c.sw rd', offset(rs') + asm_rv32_opcode_csw(state, RV32_MAP_IN_C_REGISTER_WINDOW(rd), RV32_MAP_IN_C_REGISTER_WINDOW(rs), scaled_offset); + return; + } + + if (MP_FIT_SIGNED(12, scaled_offset)) { + // sb|sh|sw rd, offset(rs) + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_S(0x23, operation_size, rs, rd, scaled_offset)); + return; + } + + mp_uint_t upper = 0; + mp_uint_t lower = 0; + split_immediate(scaled_offset, &upper, &lower); + + // lui temporary, HI(offset) ; Or c.lui if possible + // c.add temporary, rs + // sb|sh|sw rd, LO(offset)(temporary) + load_upper_immediate(state, REG_TEMP2, upper); + asm_rv32_opcode_cadd(state, REG_TEMP2, rs); + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_S(0x23, operation_size, REG_TEMP2, rd, lower)); +} + +void asm_rv32_emit_mov_reg_pcrel(asm_rv32_t *state, mp_uint_t rd, mp_uint_t label) { + ptrdiff_t displacement = (ptrdiff_t)(state->base.label_offsets[label] - state->base.code_offset); + mp_uint_t upper = 0; + mp_uint_t lower = 0; + split_immediate(displacement, &upper, &lower); + + // auipc rd, HI(relative) + // addi rd, rd, LO(relative) + asm_rv32_opcode_auipc(state, rd, upper); + asm_rv32_opcode_addi(state, rd, rd, lower); +} + +void asm_rv32_emit_optimised_xor(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs) { + if (rs == rd) { + // c.li rd, 0 + asm_rv32_opcode_cli(state, rd, 0); + return; + } + + // xor rd, rd, rs + asm_rv32_opcode_xor(state, rd, rd, rs); +} + +// WARNING: The scaled offset will be stored in REG_TEMP2. +static void asm_rv32_fix_up_scaled_reg_reg_reg(asm_rv32_t *state, mp_uint_t rs1, mp_uint_t rs2, mp_uint_t operation_size) { + assert(operation_size <= 2 && "Operation size value out of range."); + + if (operation_size > 0 && asm_rv32_allow_zba_opcodes()) { + // sh{1,2}add rs1, rs2, rs1 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_R(0x33, 1 << operation_size, 0x10, REG_TEMP2, rs2, rs1)); + } else { + if (operation_size > 0) { + asm_rv32_opcode_slli(state, REG_TEMP2, rs2, operation_size); + asm_rv32_opcode_cadd(state, REG_TEMP2, rs1); + } else { + asm_rv32_opcode_add(state, REG_TEMP2, rs1, rs2); + } + } +} + +void asm_rv32_emit_load_reg_reg_reg(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs1, mp_uint_t rs2, mp_uint_t operation_size) { + asm_rv32_fix_up_scaled_reg_reg_reg(state, rs1, rs2, operation_size); + asm_rv32_emit_load_reg_reg_offset(state, rd, REG_TEMP2, 0, operation_size); +} + +void asm_rv32_emit_store_reg_reg_reg(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs1, mp_uint_t rs2, mp_uint_t operation_size) { + asm_rv32_fix_up_scaled_reg_reg_reg(state, rs1, rs2, operation_size); + asm_rv32_emit_store_reg_reg_offset(state, rd, REG_TEMP2, 0, operation_size); +} + +void asm_rv32_meta_comparison_eq(asm_rv32_t *state, mp_uint_t rs1, mp_uint_t rs2, mp_uint_t rd) { + // sub rd, rs1, rs2 + // sltiu rd, rd, 1 + asm_rv32_opcode_sub(state, rd, rs1, rs2); + asm_rv32_opcode_sltiu(state, rd, rd, 1); +} + +void asm_rv32_meta_comparison_ne(asm_rv32_t *state, mp_uint_t rs1, mp_uint_t rs2, mp_uint_t rd) { + // sub rd, rs1, rs2 + // sltu rd, zero, rd + asm_rv32_opcode_sub(state, rd, rs1, rs2); + asm_rv32_opcode_sltu(state, rd, ASM_RV32_REG_ZERO, rd); +} + +void asm_rv32_meta_comparison_lt(asm_rv32_t *state, mp_uint_t rs1, mp_uint_t rs2, mp_uint_t rd, bool unsigned_comparison) { + // slt|sltu rd, rs1, rs2 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_R(0x33, (0x02 | (unsigned_comparison ? 1 : 0)), 0x00, rd, rs1, rs2)); +} + +void asm_rv32_meta_comparison_le(asm_rv32_t *state, mp_uint_t rs1, mp_uint_t rs2, mp_uint_t rd, bool unsigned_comparison) { + // slt[u] rd, rs2, rs1 + // xori rd, rd, 1 + asm_rv32_meta_comparison_lt(state, rs2, rs1, rd, unsigned_comparison); + asm_rv32_opcode_xori(state, rd, rd, 1); +} + +#endif // MICROPY_EMIT_RV32 diff --git a/py/asmrv32.h b/py/asmrv32.h new file mode 100644 index 00000000000..f71fe72706a --- /dev/null +++ b/py/asmrv32.h @@ -0,0 +1,867 @@ +/* + * This file is part of the MicroPython project, https://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2024 Alessandro Gatti + * + * 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_PY_ASMRV32_H +#define MICROPY_INCLUDED_PY_ASMRV32_H + +#include + +#include "py/asmbase.h" +#include "py/emit.h" +#include "py/misc.h" +#include "py/persistentcode.h" + +#define ASM_RV32_REG_X0 (0) // Zero +#define ASM_RV32_REG_X1 (1) // RA +#define ASM_RV32_REG_X2 (2) // SP +#define ASM_RV32_REG_X3 (3) // GP +#define ASM_RV32_REG_X4 (4) // TP +#define ASM_RV32_REG_X5 (5) // T0 +#define ASM_RV32_REG_X6 (6) // T1 +#define ASM_RV32_REG_X7 (7) // T2 +#define ASM_RV32_REG_X8 (8) // S0 +#define ASM_RV32_REG_X9 (9) // S1 +#define ASM_RV32_REG_X10 (10) // A0 +#define ASM_RV32_REG_X11 (11) // A1 +#define ASM_RV32_REG_X12 (12) // A2 +#define ASM_RV32_REG_X13 (13) // A3 +#define ASM_RV32_REG_X14 (14) // A4 +#define ASM_RV32_REG_X15 (15) // A5 +#define ASM_RV32_REG_X16 (16) // A6 +#define ASM_RV32_REG_X17 (17) // A7 +#define ASM_RV32_REG_X18 (18) // S2 +#define ASM_RV32_REG_X19 (19) // S3 +#define ASM_RV32_REG_X20 (20) // S4 +#define ASM_RV32_REG_X21 (21) // S5 +#define ASM_RV32_REG_X22 (22) // S6 +#define ASM_RV32_REG_X23 (23) // S7 +#define ASM_RV32_REG_X24 (24) // S8 +#define ASM_RV32_REG_X25 (25) // S9 +#define ASM_RV32_REG_X26 (26) // S10 +#define ASM_RV32_REG_X27 (27) // S11 +#define ASM_RV32_REG_X28 (28) // T3 +#define ASM_RV32_REG_X29 (29) // T4 +#define ASM_RV32_REG_X30 (30) // T5 +#define ASM_RV32_REG_X31 (31) // T6 + +// Alternate register names. + +#define ASM_RV32_REG_ZERO (ASM_RV32_REG_X0) +#define ASM_RV32_REG_RA (ASM_RV32_REG_X1) +#define ASM_RV32_REG_SP (ASM_RV32_REG_X2) +#define ASM_RV32_REG_GP (ASM_RV32_REG_X3) +#define ASM_RV32_REG_TP (ASM_RV32_REG_X4) +#define ASM_RV32_REG_A0 (ASM_RV32_REG_X10) +#define ASM_RV32_REG_A1 (ASM_RV32_REG_X11) +#define ASM_RV32_REG_A2 (ASM_RV32_REG_X12) +#define ASM_RV32_REG_A3 (ASM_RV32_REG_X13) +#define ASM_RV32_REG_A4 (ASM_RV32_REG_X14) +#define ASM_RV32_REG_A5 (ASM_RV32_REG_X15) +#define ASM_RV32_REG_A6 (ASM_RV32_REG_X16) +#define ASM_RV32_REG_A7 (ASM_RV32_REG_X17) +#define ASM_RV32_REG_T0 (ASM_RV32_REG_X5) +#define ASM_RV32_REG_T1 (ASM_RV32_REG_X6) +#define ASM_RV32_REG_T2 (ASM_RV32_REG_X7) +#define ASM_RV32_REG_T3 (ASM_RV32_REG_X28) +#define ASM_RV32_REG_T4 (ASM_RV32_REG_X29) +#define ASM_RV32_REG_T5 (ASM_RV32_REG_X30) +#define ASM_RV32_REG_T6 (ASM_RV32_REG_X31) +#define ASM_RV32_REG_FP (ASM_RV32_REG_X8) +#define ASM_RV32_REG_S0 (ASM_RV32_REG_X8) +#define ASM_RV32_REG_S1 (ASM_RV32_REG_X9) +#define ASM_RV32_REG_S2 (ASM_RV32_REG_X18) +#define ASM_RV32_REG_S3 (ASM_RV32_REG_X19) +#define ASM_RV32_REG_S4 (ASM_RV32_REG_X20) +#define ASM_RV32_REG_S5 (ASM_RV32_REG_X21) +#define ASM_RV32_REG_S6 (ASM_RV32_REG_X22) +#define ASM_RV32_REG_S7 (ASM_RV32_REG_X23) +#define ASM_RV32_REG_S8 (ASM_RV32_REG_X24) +#define ASM_RV32_REG_S9 (ASM_RV32_REG_X25) +#define ASM_RV32_REG_S10 (ASM_RV32_REG_X26) +#define ASM_RV32_REG_S11 (ASM_RV32_REG_X27) + +#define RV32_AVAILABLE_REGISTERS_COUNT 32 +#define RV32_MAP_IN_C_REGISTER_WINDOW(register_number) \ + ((register_number) - ASM_RV32_REG_X8) +#define RV32_IS_IN_C_REGISTER_WINDOW(register_number) \ + (((register_number) >= ASM_RV32_REG_X8) && ((register_number) <= ASM_RV32_REG_X15)) + +typedef struct _asm_rv32_t { + // Opaque emitter state. + mp_asm_base_t base; + // Which registers are tainted and need saving/restoring. + mp_uint_t saved_registers_mask; + // How many locals must be stored on the stack. + mp_uint_t locals_count; + // The computed function stack size. + mp_uint_t stack_size; + // The stack offset where stack-based locals start to be stored. + mp_uint_t locals_stack_offset; +} asm_rv32_t; + +enum { + RV32_EXT_NONE = 0, + RV32_EXT_ZBA = 1 << 0, + RV32_EXT_ZCMP = 1 << 1, + + RV32_EXT_ALL = RV32_EXT_ZBA | RV32_EXT_ZCMP +}; + +typedef struct _asm_rv32_backend_options_t { + // This is a bitmask holding a combination of RV32_EXT_* entries. + uint8_t allowed_extensions; +} asm_rv32_backend_options_t; + +void asm_rv32_entry(asm_rv32_t *state, mp_uint_t locals); +void asm_rv32_exit(asm_rv32_t *state); +void asm_rv32_end_pass(asm_rv32_t *state); + +//////////////////////////////////////////////////////////////////////////////// + +#define RV32_ENCODE_TYPE_B(op, ft3, rs1, rs2, imm) \ + ((op & 0x7F) | ((ft3 & 0x07) << 12) | ((imm & 0x800) >> 4) | \ + ((imm & 0x1E) << 7) | ((rs1 & 0x1F) << 15) | ((rs2 & 0x1F) << 20) | \ + ((imm & 0x7E0) << 20) | ((imm & 0x1000) << 19)) + +#define RV32_ENCODE_TYPE_CSRI(op, ft3, rd, csr, imm) \ + ((op & 0x7F) | ((rd & 0x1F) << 7) | ((ft3 & 0x07) << 12) | \ + ((csr & 0xFFF) << 20) | ((imm & 0x1F) << 15)) + +#define RV32_ENCODE_TYPE_I(op, ft3, rd, rs, imm) \ + ((op & 0x7F) | ((rd & 0x1F) << 7) | ((ft3 & 0x07) << 12) | \ + ((rs & 0x1F) << 15) | ((imm & 0xFFF) << 20)) + +#define RV32_ENCODE_TYPE_J(op, rd, imm) \ + ((op & 0x7F) | ((rd & 0x1F) << 7) | (imm & 0xFF000) | \ + ((imm & 0x800) << 9) | ((imm & 0x7FE) << 20) | ((imm & 0x100000) << 11)) + +#define RV32_ENCODE_TYPE_R(op, ft3, ft7, rd, rs1, rs2) \ + ((op & 0x7F) | ((rd & 0x1F) << 7) | ((ft3 & 0x07) << 12) | \ + ((rs1 & 0x1F) << 15) | ((rs2 & 0x1F) << 20) | ((ft7 & 0x7F) << 25)) + +#define RV32_ENCODE_TYPE_S(op, ft3, rs1, rs2, imm) \ + ((op & 0x7F) | ((imm & 0x1F) << 7) | ((ft3 & 0x07) << 12) | \ + ((rs1 & 0x1F) << 15) | ((rs2 & 0x1F) << 20) | ((imm & 0xFE0) << 20)) + +#define RV32_ENCODE_TYPE_CA(op, ft6, ft2, rd, rs) \ + ((op & 0x03) | ((ft6 & 0x3F) << 10) | ((ft2 & 0x03) << 5) | \ + ((rd & 0x03) << 7) | ((rs & 0x03) << 2)) + +#define RV32_ENCODE_TYPE_U(op, rd, imm) \ + ((op & 0x7F) | ((rd & 0x1F) << 7) | (imm & 0xFFFFF000)) + +#define RV32_ENCODE_TYPE_CB(op, ft3, rs, imm) \ + ((op & 0x03) | ((ft3 & 0x07) << 13) | ((rs & 0x07) << 7) | \ + (((imm) & 0xE0) << 5) | (((imm) & 0x1F) << 2)) + +#define RV32_ENCODE_TYPE_CI(op, ft3, rd, imm) \ + ((op & 0x03) | ((ft3 & 0x07) << 13) | ((rd & 0x1F) << 7) | \ + (((imm) & 0x20) << 7) | (((imm) & 0x1F) << 2)) + +#define RV32_ENCODE_TYPE_CIW(op, ft3, rd, imm) \ + ((op & 0x03) | ((ft3 & 0x07) << 13) | ((rd & 0x07) << 2) | \ + ((imm & 0x3C0) << 1) | ((imm & 0x30) << 7) | \ + ((imm & 0x08) << 2) | ((imm & 0x04) << 4)) + +#define RV32_ENCODE_TYPE_CJ(op, ft3, imm) \ + ((op & 0x03) | ((ft3 & 0x07) << 13) | ((imm & 0x0E) << 2) | \ + ((imm & 0x300) << 1) | ((imm & 0x800) << 1) | ((imm & 0x400) >> 2) | \ + ((imm & 0x80) >> 1) | ((imm & 0x40) << 1) | ((imm & 0x20) >> 3) | \ + ((imm & 0x10) << 7)) + +#define RV32_ENCODE_TYPE_CL(op, ft3, rd, rs, imm) \ + ((op & 0x03) | ((ft3 & 0x07) << 13) | ((rd & 0x07) << 2) | \ + ((rs & 0x07) << 7) | ((imm & 0x40) >> 1) | ((imm & 0x38) << 7) | \ + ((imm & 0x04) << 4)) + +#define RV32_ENCODE_TYPE_CMPP(op, ft6, ft2, rlist, imm) \ + ((op & 0x03) | ((ft6 & 0x3F) << 10) | ((ft2 & 0x03) << 8) | \ + ((rlist & 0x0F) << 4) | ((imm & 0x03) << 2)) + +#define RV32_ENCODE_TYPE_CMMV(op, ft6, ft2, r1s, r2s) \ + ((op & 0x03) | ((ft6 & 0x3F) << 10) | ((ft2 & 0x03) << 5) | \ + ((((r1s >= ASM_RV32_REG_S0 && r1s <= ASM_RV32_REG_S1) ? \ + (r1s - ASM_RV32_REG_S0) : (r1s - ASM_RV32_REG_S2 + 2)) & 0x07) << 7) | \ + ((((r2s >= ASM_RV32_REG_S0 && r2s <= ASM_RV32_REG_S1) ? \ + (r2s - ASM_RV32_REG_S0) : (r2s - ASM_RV32_REG_S2 + 2)) & 0x07) << 2)) + + +#define RV32_ENCODE_TYPE_CR(op, ft4, rs1, rs2) \ + ((op & 0x03) | ((rs2 & 0x1F) << 2) | ((rs1 & 0x1F) << 7) | ((ft4 & 0x0F) << 12)) + +#define RV32_ENCODE_TYPE_CS(op, ft3, rd, rs, imm) \ + ((op & 0x03) | ((ft3 & 0x07) << 13) | ((rd & 0x07) << 2) | \ + ((rs & 0x07) << 7) | ((imm & 0x40) >> 1) | ((imm & 0x38) << 7) | \ + ((imm & 0x04) << 4)) + +#define RV32_ENCODE_TYPE_CSS(op, ft3, rs, imm) \ + ((op & 0x03) | ((ft3 & 0x07) << 13) | ((rs & 0x1F) << 2) | ((imm) & 0x3F) << 7) + +void asm_rv32_emit_word_opcode(asm_rv32_t *state, mp_uint_t opcode); +void asm_rv32_emit_halfword_opcode(asm_rv32_t *state, mp_uint_t opcode); + +// ADD RD, RS1, RS2 +static inline void asm_rv32_opcode_add(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs1, mp_uint_t rs2) { + // R: 0000000 ..... ..... 000 ..... 0110011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_R(0x33, 0x00, 0x00, rd, rs1, rs2)); +} + +// ADDI RD, RS, IMMEDIATE +static inline void asm_rv32_opcode_addi(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs, mp_int_t immediate) { + // I: ............ ..... 000 ..... 0010011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_I(0x13, 0x00, rd, rs, immediate)); +} + +// AND RD, RS1, RS2 +static inline void asm_rv32_opcode_and(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs1, mp_uint_t rs2) { + // R: 0000000 ..... ..... 111 ..... 0110011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_R(0x33, 0x07, 0x00, rd, rs1, rs2)); +} + +// ANDI RD, RS, IMMEDIATE +static inline void asm_rv32_opcode_andi(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs, mp_int_t immediate) { + // I: ............ ..... 111 ..... 0010011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_I(0x13, 0x07, rd, rs, immediate)); +} + +// AUIPC RD, offset +static inline void asm_rv32_opcode_auipc(asm_rv32_t *state, mp_uint_t rd, mp_int_t offset) { + // U: .................... ..... 0010111 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_U(0x17, rd, offset)); +} + +// BEQ RS1, RS2, OFFSET +static inline void asm_rv32_opcode_beq(asm_rv32_t *state, mp_uint_t rs1, mp_uint_t rs2, mp_int_t offset) { + // B: . ...... ..... ..... 000 .... . 1100011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_B(0x63, 0x00, rs1, rs2, offset)); +} + +// BGE RS1, RS2, OFFSET +static inline void asm_rv32_opcode_bge(asm_rv32_t *state, mp_uint_t rs1, mp_uint_t rs2, mp_int_t offset) { + // B: . ...... ..... ..... 101 .... . 1100011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_B(0x63, 0x05, rs1, rs2, offset)); +} + +// BGEU RS1, RS2, OFFSET +static inline void asm_rv32_opcode_bgeu(asm_rv32_t *state, mp_uint_t rs1, mp_uint_t rs2, mp_int_t offset) { + // B: . ...... ..... ..... 111 .... . 1100011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_B(0x63, 0x07, rs1, rs2, offset)); +} + +// BLT RS1, RS2, OFFSET +static inline void asm_rv32_opcode_blt(asm_rv32_t *state, mp_uint_t rs1, mp_uint_t rs2, mp_int_t offset) { + // B: . ...... ..... ..... 100 .... . 1100011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_B(0x63, 0x04, rs1, rs2, offset)); +} + +// BLTU RS1, RS2, OFFSET +static inline void asm_rv32_opcode_bltu(asm_rv32_t *state, mp_uint_t rs1, mp_uint_t rs2, mp_int_t offset) { + // B: . ...... ..... ..... 110 .... . 1100011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_B(0x63, 0x06, rs1, rs2, offset)); +} + +// BNE RS1, RS2, OFFSET +static inline void asm_rv32_opcode_bne(asm_rv32_t *state, mp_uint_t rs1, mp_uint_t rs2, mp_int_t offset) { + // B: . ...... ..... ..... 001 .... . 1100011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_B(0x63, 0x01, rs1, rs2, offset)); +} + +// C.ADD RD, RS +static inline void asm_rv32_opcode_cadd(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs) { + // CR: 1001 ..... ..... 10 + asm_rv32_emit_halfword_opcode(state, RV32_ENCODE_TYPE_CR(0x02, 0x09, rd, rs)); +} + +// C.ADDI RD, IMMEDIATE +static inline void asm_rv32_opcode_caddi(asm_rv32_t *state, mp_uint_t rd, mp_int_t immediate) { + // CI: 000 . ..... ..... 01 + asm_rv32_emit_halfword_opcode(state, RV32_ENCODE_TYPE_CI(0x01, 0x00, rd, immediate)); +} + +// C.ADDI4SPN RD', IMMEDIATE +static inline void asm_rv32_opcode_caddi4spn(asm_rv32_t *state, mp_uint_t rd, mp_uint_t immediate) { + // CIW: 000 ........ ... 00 + asm_rv32_emit_halfword_opcode(state, RV32_ENCODE_TYPE_CIW(0x00, 0x00, rd, immediate)); +} + +// C.AND RD', RS' +static inline void asm_rv32_opcode_cand(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs) { + // CA: 100011 ... 11 ... 01 + asm_rv32_emit_halfword_opcode(state, RV32_ENCODE_TYPE_CA(0x01, 0x23, 0x03, rd, rs)); +} + +// C.ANDI RD', IMMEDIATE +static inline void asm_rv32_opcode_candi(asm_rv32_t *state, mp_uint_t rd, mp_int_t immediate) { + // CB: 100 . 10 ... ..... 01 + asm_rv32_emit_halfword_opcode(state, RV32_ENCODE_TYPE_CB(0x01, 0x04, rd, + (((immediate & 0x20) << 2) | (immediate & 0x1F) | 0x40))); +} + +// C.BEQZ RS', IMMEDIATE +static inline void asm_rv32_opcode_cbeqz(asm_rv32_t *state, mp_uint_t rs, mp_int_t offset) { + // CB: 110 ... ... ..... 01 + asm_rv32_emit_halfword_opcode(state, RV32_ENCODE_TYPE_CB(0x01, 0x06, rs, + (((offset & 0x100) >> 1) | ((offset & 0xC0) >> 3) | ((offset & 0x20) >> 5) | + ((offset & 0x18) << 2) | (offset & 0x06)))); +} + +// C.BNEZ RS', IMMEDIATE +static inline void asm_rv32_opcode_cbnez(asm_rv32_t *state, mp_uint_t rs, mp_int_t offset) { + // CB: 111 ... ... ..... 01 + asm_rv32_emit_halfword_opcode(state, RV32_ENCODE_TYPE_CB(0x01, 0x07, rs, + (((offset & 0x100) >> 1) | ((offset & 0xC0) >> 3) | ((offset & 0x20) >> 5) | + ((offset & 0x18) << 2) | (offset & 0x06)))); +} + +// C.EBREAK +static inline void asm_rv32_opcode_cebreak(asm_rv32_t *state) { + // CA: 100 1 00000 00000 10 + asm_rv32_emit_halfword_opcode(state, 0x9002); +} + +// C.J OFFSET +static inline void asm_rv32_opcode_cj(asm_rv32_t *state, mp_int_t offset) { + // CJ: 101 ........... 01 + asm_rv32_emit_halfword_opcode(state, RV32_ENCODE_TYPE_CJ(0x01, 0x05, offset)); +} + +// C.JAL OFFSET +static inline void asm_rv32_opcode_cjal(asm_rv32_t *state, mp_int_t offset) { + // CJ: 001 ........... 01 + asm_rv32_emit_halfword_opcode(state, RV32_ENCODE_TYPE_CJ(0x01, 0x01, offset)); +} + +// C.JALR RS +static inline void asm_rv32_opcode_cjalr(asm_rv32_t *state, mp_uint_t rs) { + // CR: 1001 ..... 00000 10 + asm_rv32_emit_halfword_opcode(state, RV32_ENCODE_TYPE_CR(0x02, 0x09, rs, 0)); +} + +// C.JR RS +static inline void asm_rv32_opcode_cjr(asm_rv32_t *state, mp_uint_t rs) { + // CR: 1000 ..... 00000 10 + asm_rv32_emit_halfword_opcode(state, RV32_ENCODE_TYPE_CR(0x02, 0x08, rs, 0)); +} + +// C.LI RD, IMMEDIATE +static inline void asm_rv32_opcode_cli(asm_rv32_t *state, mp_uint_t rd, mp_int_t immediate) { + // CI: 010 . ..... ..... 01 + asm_rv32_emit_halfword_opcode(state, RV32_ENCODE_TYPE_CI(0x01, 0x02, rd, immediate)); +} + +// C.LUI RD, IMMEDIATE +static inline void asm_rv32_opcode_clui(asm_rv32_t *state, mp_uint_t rd, mp_int_t immediate) { + // CI: 011 . ..... ..... 01 + asm_rv32_emit_halfword_opcode(state, RV32_ENCODE_TYPE_CI(0x01, 0x03, rd, immediate >> 12)); +} + +// C.LW RD', OFFSET(RS') +static inline void asm_rv32_opcode_clw(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs, mp_int_t offset) { + // CL: 010 ... ... .. ... 00 + asm_rv32_emit_halfword_opcode(state, RV32_ENCODE_TYPE_CL(0x00, 0x02, rd, rs, offset)); +} + +// C.LWSP RD, OFFSET +static inline void asm_rv32_opcode_clwsp(asm_rv32_t *state, mp_uint_t rd, mp_uint_t offset) { + // CI: 010 . ..... ..... 10 + asm_rv32_emit_halfword_opcode(state, RV32_ENCODE_TYPE_CI(0x02, 0x02, rd, ((offset & 0xC0) >> 6) | (offset & 0x3C))); +} + +// C.MV RD, RS +static inline void asm_rv32_opcode_cmv(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs) { + // CR: 1000 ..... ..... 10 + asm_rv32_emit_halfword_opcode(state, RV32_ENCODE_TYPE_CR(0x02, 0x08, rd, rs)); +} + +// C.NOP +static inline void asm_rv32_opcode_cnop(asm_rv32_t *state) { + // CI: 000 . 00000 ..... 01 + asm_rv32_emit_halfword_opcode(state, 0x0001); +} + +// C.OR RD', RS' +static inline void asm_rv32_opcode_cor(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs) { + // CA: 100011 ... 10 ... 01 + asm_rv32_emit_halfword_opcode(state, RV32_ENCODE_TYPE_CA(0x01, 0x23, 0x02, rd, rs)); +} + +// C.SLLI RD, IMMEDIATE +static inline void asm_rv32_opcode_cslli(asm_rv32_t *state, mp_uint_t rd, mp_int_t immediate) { + // CI: 000 . ..... ..... 10 + asm_rv32_emit_halfword_opcode(state, RV32_ENCODE_TYPE_CI(0x02, 0x00, rd, immediate)); +} + +// C.SRAI RD, IMMEDIATE +static inline void asm_rv32_opcode_csrai(asm_rv32_t *state, mp_uint_t rd, mp_int_t immediate) { + // CB: 100 . 01 ... ..... 01 + asm_rv32_emit_halfword_opcode(state, RV32_ENCODE_TYPE_CB(0x01, 0x04, rd, + (((immediate & 0x20) << 2) | (immediate & 0x1F) | 0x20))); +} + +// C.SRLI RD, IMMEDIATE +static inline void asm_rv32_opcode_csrli(asm_rv32_t *state, mp_uint_t rd, mp_int_t immediate) { + // CB: 100 . 00 ... ..... 01 + asm_rv32_emit_halfword_opcode(state, RV32_ENCODE_TYPE_CB(0x01, 0x04, rd, + (((immediate & 0x20) << 2) | (immediate & 0x1F)))); +} + +// C.SUB RD', RS' +static inline void asm_rv32_opcode_csub(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs) { + // CA: 100011 ... 00 ... 01 + asm_rv32_emit_halfword_opcode(state, RV32_ENCODE_TYPE_CA(0x01, 0x23, 0x00, rd, rs)); +} + +// C.SW RS1', OFFSET(RS2') +static inline void asm_rv32_opcode_csw(asm_rv32_t *state, mp_uint_t rs1, mp_uint_t rs2, mp_int_t offset) { + // CS: 110 ... ... .. ... 00 + asm_rv32_emit_halfword_opcode(state, RV32_ENCODE_TYPE_CL(0x00, 0x06, rs1, rs2, offset)); +} + +// C.SWSP RS, OFFSET +static inline void asm_rv32_opcode_cswsp(asm_rv32_t *state, mp_uint_t rs, mp_uint_t offset) { + // CSS: 010 ...... ..... 10 + asm_rv32_emit_halfword_opcode(state, RV32_ENCODE_TYPE_CSS(0x02, 0x06, rs, ((offset & 0xC0) >> 6) | (offset & 0x3C))); +} + +// C.XOR RD', RS' +static inline void asm_rv32_opcode_cxor(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs) { + // CA: 100011 ... 01 ... 01 + asm_rv32_emit_halfword_opcode(state, RV32_ENCODE_TYPE_CA(0x01, 0x23, 0x01, rd, rs)); +} + +// CM.MVA01S R1S', R2S' +static inline void asm_rv32_opcode_cmmva01s(asm_rv32_t *state, mp_uint_t r1s, mp_uint_t r2s) { + // CMMV: 101011 ... 11 ... 10 + asm_rv32_emit_halfword_opcode(state, RV32_ENCODE_TYPE_CMMV(0x02, 0x2B, 0x03, r1s, r2s)); +} + +// CM.MVSA01 R1S', R2S' +static inline void asm_rv32_opcode_cmmvsa01(asm_rv32_t *state, mp_uint_t r1s, mp_uint_t r2s) { + // CMMV: 101011 ... 01 ... 10 + asm_rv32_emit_halfword_opcode(state, RV32_ENCODE_TYPE_CMMV(0x02, 0x2B, 0x01, r1s, r2s)); +} + +// CM.POP {REG_LIST}, IMMEDIATE +static inline void asm_rv32_opcode_cmpop(asm_rv32_t *state, mp_uint_t reg_list, mp_uint_t immediate) { + // CMPP: 10111010 .... .. 10 + asm_rv32_emit_halfword_opcode(state, RV32_ENCODE_TYPE_CMPP(0x02, 0x2E, 0x02, reg_list, immediate)); +} + +// CM.POPRET {REG_LIST}, IMMEDIATE +static inline void asm_rv32_opcode_cmpopret(asm_rv32_t *state, mp_uint_t reg_list, mp_uint_t immediate) { + // CMPP: 10111110 .... .. 10 + asm_rv32_emit_halfword_opcode(state, RV32_ENCODE_TYPE_CMPP(0x02, 0x2F, 0x02, reg_list, immediate)); +} + +// CM.POPRETZ {REG_LIST}, IMMEDIATE +static inline void asm_rv32_opcode_cmpopretz(asm_rv32_t *state, mp_uint_t reg_list, mp_uint_t immediate) { + // CMPP: 10111100 .... .. 10 + asm_rv32_emit_halfword_opcode(state, RV32_ENCODE_TYPE_CMPP(0x02, 0x2F, 0x00, reg_list, immediate)); +} + +// CM.PUSH {REG_LIST}, -IMMEDIATE +static inline void asm_rv32_opcode_cmpush(asm_rv32_t *state, mp_uint_t reg_list, mp_uint_t immediate) { + // CMPP: 10111000 .... .. 10 + asm_rv32_emit_halfword_opcode(state, RV32_ENCODE_TYPE_CMPP(0x02, 0x2E, 0x00, reg_list, immediate)); +} + +// CSRRC RD, RS, IMMEDIATE +static inline void asm_rv32_opcode_csrrc(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs, mp_int_t immediate) { + // I: ............ ..... 011 ..... 1110011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_I(0x73, 0x03, rd, rs, immediate)); +} + +// CSRRS RD, RS, IMMEDIATE +static inline void asm_rv32_opcode_csrrs(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs, mp_int_t immediate) { + // I: ............ ..... 010 ..... 1110011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_I(0x73, 0x02, rd, rs, immediate)); +} + +// CSRRW RD, RS, IMMEDIATE +static inline void asm_rv32_opcode_csrrw(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs, mp_int_t immediate) { + // I: ............ ..... 001 ..... 1110011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_I(0x73, 0x01, rd, rs, immediate)); +} + +// CSRRCI RD, CSR, IMMEDIATE +static inline void asm_rv32_opcode_csrrci(asm_rv32_t *state, mp_uint_t rd, mp_uint_t csr, mp_int_t immediate) { + // CSRI: ............ ..... 111 ..... 1110011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_CSRI(0x73, 0x07, rd, csr, immediate)); +} + +// CSRRSI RD, CSR, IMMEDIATE +static inline void asm_rv32_opcode_csrrsi(asm_rv32_t *state, mp_uint_t rd, mp_uint_t csr, mp_int_t immediate) { + // CSRI: ............ ..... 110 ..... 1110011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_CSRI(0x73, 0x06, rd, csr, immediate)); +} + +// CSRRWI RD, CSR, IMMEDIATE +static inline void asm_rv32_opcode_csrrwi(asm_rv32_t *state, mp_uint_t rd, mp_uint_t csr, mp_int_t immediate) { + // CSRI: ............ ..... 101 ..... 1110011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_CSRI(0x73, 0x05, rd, csr, immediate)); +} + +// DIV RD, RS1, RS2 +static inline void asm_rv32_opcode_div(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs1, mp_uint_t rs2) { + // R: 0000001 ..... ..... 100 ..... 0110011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_R(0x33, 0x04, 0x01, rd, rs1, rs2)); +} + +// DIVU RD, RS1, RS2 +static inline void asm_rv32_opcode_divu(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs1, mp_uint_t rs2) { + // R: 0000001 ..... ..... 101 ..... 0110011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_R(0x33, 0x05, 0x01, rd, rs1, rs2)); +} + +// EBREAK +static inline void asm_rv32_opcode_ebreak(asm_rv32_t *state) { + // I: 000000000001 00000 000 00000 1110011 + asm_rv32_emit_word_opcode(state, 0x100073); +} + +// ECALL +static inline void asm_rv32_opcode_ecall(asm_rv32_t *state) { + // I: 000000000000 00000 000 00000 1110011 + asm_rv32_emit_word_opcode(state, 0x73); +} + +// JAL RD, OFFSET +static inline void asm_rv32_opcode_jal(asm_rv32_t *state, mp_uint_t rd, mp_int_t offset) { + // J: ......................... 1101111 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_J(0x6F, rd, offset)); +} + +// JALR RD, RS, OFFSET +static inline void asm_rv32_opcode_jalr(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs, mp_int_t offset) { + // I: ............ ..... 000 ..... 1100111 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_I(0x67, 0x00, rd, rs, offset)); +} + +// LB RD, OFFSET(RS) +static inline void asm_rv32_opcode_lb(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs, mp_int_t offset) { + // I: ............ ..... 000 ..... 0000011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_I(0x03, 0x00, rd, rs, offset)); +} + +// LBU RD, OFFSET(RS) +static inline void asm_rv32_opcode_lbu(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs, mp_int_t offset) { + // I: ............ ..... 100 ..... 0000011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_I(0x03, 0x04, rd, rs, offset)); +} + +// LH RD, OFFSET(RS) +static inline void asm_rv32_opcode_lh(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs, mp_int_t offset) { + // I: ............ ..... 001 ..... 0000011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_I(0x03, 0x01, rd, rs, offset)); +} + +// LHU RD, OFFSET(RS) +static inline void asm_rv32_opcode_lhu(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs, mp_int_t offset) { + // I: ............ ..... 101 ..... 0000011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_I(0x03, 0x05, rd, rs, offset)); +} + +// LUI RD, IMMEDIATE +static inline void asm_rv32_opcode_lui(asm_rv32_t *state, mp_uint_t rd, mp_int_t immediate) { + // U: .................... ..... 0110111 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_U(0x37, rd, immediate)); +} + +// LW RD, OFFSET(RS) +static inline void asm_rv32_opcode_lw(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs, mp_int_t offset) { + // I: ............ ..... 010 ..... 0000011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_I(0x03, 0x02, rd, rs, offset)); +} + +// MUL RD, RS1, RS2 +static inline void asm_rv32_opcode_mul(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs1, mp_uint_t rs2) { + // R: 0000001 ..... ..... 000 ..... 0110011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_R(0x33, 0x00, 0x01, rd, rs1, rs2)); +} + +// MULH RD, RS1, RS2 +static inline void asm_rv32_opcode_mulh(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs1, mp_uint_t rs2) { + // R: 0000001 ..... ..... 001 ..... 0110011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_R(0x33, 0x01, 0x01, rd, rs1, rs2)); +} + +// MULHSU RD, RS1, RS2 +static inline void asm_rv32_opcode_mulhsu(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs1, mp_uint_t rs2) { + // R: 0000001 ..... ..... 010 ..... 0110011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_R(0x33, 0x02, 0x01, rd, rs1, rs2)); +} + +// MULHU RD, RS1, RS2 +static inline void asm_rv32_opcode_mulhu(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs1, mp_uint_t rs2) { + // R: 0000001 ..... ..... 011 ..... 0110011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_R(0x33, 0x03, 0x01, rd, rs1, rs2)); +} + +// OR RD, RS1, RS2 +static inline void asm_rv32_opcode_or(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs1, mp_uint_t rs2) { + // R: 0000000 ..... ..... 110 ..... 0110011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_R(0x33, 0x06, 0x00, rd, rs1, rs2)); +} + +// ORI RD, RS, IMMEDIATE +static inline void asm_rv32_opcode_ori(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs, mp_int_t immediate) { + // I: ............ ..... 110 ..... 0010011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_I(0x13, 0x06, rd, rs, immediate)); +} + +// REM RD, RS1, RS2 +static inline void asm_rv32_opcode_rem(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs1, mp_uint_t rs2) { + // R: 0000001 ..... ..... 110 ..... 0110011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_R(0x33, 0x06, 0x01, rd, rs1, rs2)); +} + +// REMU RD, RS1, RS2 +static inline void asm_rv32_opcode_remu(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs1, mp_uint_t rs2) { + // R: 0000001 ..... ..... 111 ..... 0110011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_R(0x33, 0x07, 0x01, rd, rs1, rs2)); +} + +// SH1ADD RD, RS1, RS2 +static inline void asm_rv32_opcode_sh1add(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs1, mp_uint_t rs2) { + // R: 0010000 ..... ..... 010 ..... 0110011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_R(0x33, 0x02, 0x10, rd, rs1, rs2)); +} + +// SH2ADD RD, RS1, RS2 +static inline void asm_rv32_opcode_sh2add(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs1, mp_uint_t rs2) { + // R: 0010000 ..... ..... 100 ..... 0110011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_R(0x33, 0x04, 0x10, rd, rs1, rs2)); +} + +// SH3ADD RD, RS1, RS2 +static inline void asm_rv32_opcode_sh3add(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs1, mp_uint_t rs2) { + // R: 0010000 ..... ..... 110 ..... 0110011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_R(0x33, 0x06, 0x10, rd, rs1, rs2)); +} + +// SLL RD, RS1, RS2 +static inline void asm_rv32_opcode_sll(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs1, mp_uint_t rs2) { + // R: 0000000 ..... ..... 001 ..... 0110011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_R(0x33, 0x01, 0x00, rd, rs1, rs2)); +} + +// SLLI RD, RS, IMMEDIATE +static inline void asm_rv32_opcode_slli(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs, mp_int_t immediate) { + // I: 0000000..... ..... 001 ..... 0010011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_I(0x13, 0x01, rd, rs, immediate & 0x1F)); +} + +// SLT RD, RS1, RS2 +static inline void asm_rv32_opcode_slt(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs1, mp_uint_t rs2) { + // R: 0000000 ..... ..... 010 ..... 0110011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_R(0x33, 0x02, 0x00, rd, rs1, rs2)); +} + +// SLTI RD, RS, IMMEDIATE +static inline void asm_rv32_opcode_slti(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs, mp_int_t immediate) { + // I: ............ ..... 010 ..... 0010011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_I(0x13, 0x02, rd, rs, immediate)); +} + +// SLTIU RD, RS, IMMEDIATE +static inline void asm_rv32_opcode_sltiu(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs, mp_int_t immediate) { + // I: ............ ..... 011 ..... 0010011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_I(0x13, 0x03, rd, rs, immediate)); +} + +// SLTU RD, RS1, RS2 +static inline void asm_rv32_opcode_sltu(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs1, mp_uint_t rs2) { + // R: 0000000 ..... ..... 011 ..... 0110011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_R(0x33, 0x03, 0x00, rd, rs1, rs2)); +} + +// SRA RD, RS1, RS2 +static inline void asm_rv32_opcode_sra(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs1, mp_uint_t rs2) { + // R: 0100000 ..... ..... 101 ..... 0110011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_R(0x33, 0x05, 0x20, rd, rs1, rs2)); +} + +// SRAI RD, RS, IMMEDIATE +static inline void asm_rv32_opcode_srai(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs, mp_int_t immediate) { + // I: 0100000..... ..... 101 ..... 0010011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_I(0x13, 0x05, rd, rs, ((immediate & 0x1F) | 0x400))); +} + +// SRL RD, RS1, RS2 +static inline void asm_rv32_opcode_srl(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs1, mp_uint_t rs2) { + // R: 0000000 ..... ..... 101 ..... 0110011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_R(0x33, 0x05, 0x00, rd, rs1, rs2)); +} + +// SRLI RD, RS, IMMEDIATE +static inline void asm_rv32_opcode_srli(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs, mp_int_t immediate) { + // I: 0000000..... ..... 101 ..... 0010011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_I(0x13, 0x05, rd, rs, immediate & 0x1F)); +} + +// SUB RD, RS1, RS2 +static inline void asm_rv32_opcode_sub(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs1, mp_uint_t rs2) { + // R: 0100000 ..... ..... 000 ..... 0110011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_R(0x33, 0x00, 0x20, rd, rs1, rs2)); +} + +// SB RS2, OFFSET(RS1) +static inline void asm_rv32_opcode_sb(asm_rv32_t *state, mp_uint_t rs2, mp_uint_t rs1, mp_int_t offset) { + // S: ....... ..... ..... 000 ..... 0100011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_S(0x23, 0x00, rs1, rs2, offset)); +} + +// SH RS2, OFFSET(RS1) +static inline void asm_rv32_opcode_sh(asm_rv32_t *state, mp_uint_t rs2, mp_uint_t rs1, mp_int_t offset) { + // S: ....... ..... ..... 001 ..... 0100011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_S(0x23, 0x01, rs1, rs2, offset)); +} + +// SW RS2, OFFSET(RS1) +static inline void asm_rv32_opcode_sw(asm_rv32_t *state, mp_uint_t rs2, mp_uint_t rs1, mp_int_t offset) { + // S: ....... ..... ..... 010 ..... 0100011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_S(0x23, 0x02, rs1, rs2, offset)); +} + +// XOR RD, RS1, RS2 +static inline void asm_rv32_opcode_xor(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs1, mp_uint_t rs2) { + // R: 0000000 ..... ..... 100 ..... 0110011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_R(0x33, 0x04, 0x00, rd, rs1, rs2)); +} + +// XORI RD, RS, IMMEDIATE +static inline void asm_rv32_opcode_xori(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs, mp_int_t immediate) { + // I: ............ ..... 100 ..... 0010011 + asm_rv32_emit_word_opcode(state, RV32_ENCODE_TYPE_I(0x13, 0x04, rd, rs, immediate)); +} + +#define MICROPY_RV32_EXTENSIONS \ + ((MICROPY_EMIT_RV32_ZBA ? RV32_EXT_ZBA : 0) | \ + (MICROPY_EMIT_RV32_ZCMP ? RV32_EXT_ZCMP : 0)) + +static inline uint8_t asm_rv32_allowed_extensions(void) { + uint8_t extensions = MICROPY_RV32_EXTENSIONS; + #if MICROPY_DYNAMIC_COMPILER + if (mp_dynamic_compiler.backend_options != NULL) { + extensions |= ((asm_rv32_backend_options_t *)mp_dynamic_compiler.backend_options)->allowed_extensions; + } + #endif + return extensions; +} + +#define ASM_WORD_SIZE (4) +#define ASM_HALFWORD_SIZE (2) + +#define REG_RET ASM_RV32_REG_A0 +#define REG_ARG_1 ASM_RV32_REG_A0 +#define REG_ARG_2 ASM_RV32_REG_A1 +#define REG_ARG_3 ASM_RV32_REG_A2 +#define REG_ARG_4 ASM_RV32_REG_A3 +#define REG_TEMP0 ASM_RV32_REG_A4 +#define REG_TEMP1 ASM_RV32_REG_A5 +#define REG_TEMP2 ASM_RV32_REG_A6 +#define REG_FUN_TABLE ASM_RV32_REG_S1 +#define REG_LOCAL_1 ASM_RV32_REG_S3 +#define REG_LOCAL_2 ASM_RV32_REG_S2 +#define REG_LOCAL_3 ASM_RV32_REG_S4 +#define REG_ZERO ASM_RV32_REG_ZERO + +void asm_rv32_meta_comparison_eq(asm_rv32_t *state, mp_uint_t rs1, mp_uint_t rs2, mp_uint_t rd); +void asm_rv32_meta_comparison_ne(asm_rv32_t *state, mp_uint_t rs1, mp_uint_t rs2, mp_uint_t rd); +void asm_rv32_meta_comparison_lt(asm_rv32_t *state, mp_uint_t rs1, mp_uint_t rs2, mp_uint_t rd, bool unsigned_comparison); +void asm_rv32_meta_comparison_le(asm_rv32_t *state, mp_uint_t rs1, mp_uint_t rs2, mp_uint_t rd, bool unsigned_comparison); + +void asm_rv32_emit_optimised_load_immediate(asm_rv32_t *state, mp_uint_t rd, mp_int_t immediate); +void asm_rv32_emit_load_reg_reg_reg(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs1, mp_uint_t rs2, mp_uint_t operation_size); +void asm_rv32_emit_store_reg_reg_reg(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs1, mp_uint_t rs2, mp_uint_t operation_size); + +#ifdef GENERIC_ASM_API + +void asm_rv32_emit_call_ind(asm_rv32_t *state, mp_uint_t index); +void asm_rv32_emit_jump(asm_rv32_t *state, mp_uint_t label); +void asm_rv32_emit_jump_if_reg_eq(asm_rv32_t *state, mp_uint_t rs1, mp_uint_t rs2, mp_uint_t label); +void asm_rv32_emit_jump_if_reg_nonzero(asm_rv32_t *state, mp_uint_t rs, mp_uint_t label); +void asm_rv32_emit_load_reg_reg_offset(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs, int32_t offset, mp_uint_t operation_size); +void asm_rv32_emit_mov_local_reg(asm_rv32_t *state, mp_uint_t local, mp_uint_t rs); +void asm_rv32_emit_mov_reg_local_addr(asm_rv32_t *state, mp_uint_t rd, mp_uint_t local); +void asm_rv32_emit_mov_reg_local(asm_rv32_t *state, mp_uint_t rd, mp_uint_t local); +void asm_rv32_emit_mov_reg_pcrel(asm_rv32_t *state, mp_uint_t rd, mp_uint_t label); +void asm_rv32_emit_optimised_xor(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs); +void asm_rv32_emit_store_reg_reg_offset(asm_rv32_t *state, mp_uint_t source, mp_uint_t base, int32_t offset, mp_uint_t operation_size); + +#define ASM_T asm_rv32_t +#define ASM_ENTRY(state, labels, name) asm_rv32_entry(state, labels) +#define ASM_EXIT(state) asm_rv32_exit(state) +#define ASM_END_PASS(state) asm_rv32_end_pass(state) + +#define ASM_ADD_REG_REG(state, rd, rs) asm_rv32_opcode_cadd(state, rd, rs) +#define ASM_AND_REG_REG(state, rd, rs) asm_rv32_opcode_and(state, rd, rs, rd) +#define ASM_ASR_REG_REG(state, rd, rs) asm_rv32_opcode_sra(state, rd, rd, rs) +#define ASM_CALL_IND(state, index) asm_rv32_emit_call_ind(state, index) +#define ASM_JUMP(state, label) asm_rv32_emit_jump(state, label) +#define ASM_JUMP_IF_REG_EQ(state, rs1, rs2, label) asm_rv32_emit_jump_if_reg_eq(state, rs1, rs2, label) +#define ASM_JUMP_IF_REG_NONZERO(state, rs, label, bool_test) asm_rv32_emit_jump_if_reg_nonzero(state, rs, label) +#define ASM_JUMP_IF_REG_ZERO(state, rs, label, bool_test) asm_rv32_emit_jump_if_reg_eq(state, rs, ASM_RV32_REG_ZERO, label) +#define ASM_JUMP_REG(state, rs) asm_rv32_opcode_cjr(state, rs) +#define ASM_LOAD_REG_REG_OFFSET(state, rd, rs, offset) ASM_LOAD32_REG_REG_OFFSET(state, rd, rs, offset) +#define ASM_LOAD8_REG_REG(state, rd, rs) ASM_LOAD8_REG_REG_OFFSET(state, rd, rs, 0) +#define ASM_LOAD16_REG_REG(state, rd, rs) ASM_LOAD16_REG_REG_OFFSET(state, rd, rs, 0) +#define ASM_LOAD32_REG_REG(state, rd, rs) ASM_LOAD32_REG_REG_OFFSET(state, rd, rs, 0) +#define ASM_LOAD8_REG_REG_OFFSET(state, rd, rs, offset) asm_rv32_emit_load_reg_reg_offset(state, rd, rs, offset, 0) +#define ASM_LOAD16_REG_REG_OFFSET(state, rd, rs, offset) asm_rv32_emit_load_reg_reg_offset(state, rd, rs, offset, 1) +#define ASM_LOAD32_REG_REG_OFFSET(state, rd, rs, offset) asm_rv32_emit_load_reg_reg_offset(state, rd, rs, offset, 2) +#define ASM_LSL_REG_REG(state, rd, rs) asm_rv32_opcode_sll(state, rd, rd, rs) +#define ASM_LSR_REG_REG(state, rd, rs) asm_rv32_opcode_srl(state, rd, rd, rs) +#define ASM_MOV_LOCAL_REG(state, local, rs) asm_rv32_emit_mov_local_reg(state, local, rs) +#define ASM_MOV_REG_IMM(state, rd, imm) asm_rv32_emit_optimised_load_immediate(state, rd, imm) +#define ASM_MOV_REG_LOCAL_ADDR(state, rd, local) asm_rv32_emit_mov_reg_local_addr(state, rd, local) +#define ASM_MOV_REG_LOCAL(state, rd, local) asm_rv32_emit_mov_reg_local(state, rd, local) +#define ASM_MOV_REG_PCREL(state, rd, label) asm_rv32_emit_mov_reg_pcrel(state, rd, label) +#define ASM_MOV_REG_REG(state, rd, rs) asm_rv32_opcode_cmv(state, rd, rs) +#define ASM_MUL_REG_REG(state, rd, rs) asm_rv32_opcode_mul(state, rd, rd, rs) +#define ASM_NEG_REG(state, rd) asm_rv32_opcode_sub(state, rd, ASM_RV32_REG_ZERO, rd) +#define ASM_NOT_REG(state, rd) asm_rv32_opcode_xori(state, rd, rd, -1) +#define ASM_OR_REG_REG(state, rd, rs) asm_rv32_opcode_or(state, rd, rd, rs) +#define ASM_STORE_REG_REG_OFFSET(state, rd, rs, offset) ASM_STORE32_REG_REG_OFFSET(state, rd, rs, offset) +#define ASM_STORE8_REG_REG(state, rs1, rs2) ASM_STORE8_REG_REG_OFFSET(state, rs1, rs2, 0) +#define ASM_STORE16_REG_REG(state, rs1, rs2) ASM_STORE16_REG_REG_OFFSET(state, rs1, rs2, 0) +#define ASM_STORE32_REG_REG(state, rs1, rs2) ASM_STORE32_REG_REG_OFFSET(state, rs1, rs2, 0) +#define ASM_STORE8_REG_REG_OFFSET(state, rd, rs, offset) asm_rv32_emit_store_reg_reg_offset(state, rd, rs, offset, 0) +#define ASM_STORE16_REG_REG_OFFSET(state, rd, rs, offset) asm_rv32_emit_store_reg_reg_offset(state, rd, rs, offset, 1) +#define ASM_STORE32_REG_REG_OFFSET(state, rd, rs, offset) asm_rv32_emit_store_reg_reg_offset(state, rd, rs, offset, 2) +#define ASM_SUB_REG_REG(state, rd, rs) asm_rv32_opcode_sub(state, rd, rd, rs) +#define ASM_XOR_REG_REG(state, rd, rs) asm_rv32_emit_optimised_xor(state, rd, rs) +#define ASM_CLR_REG(state, rd) asm_rv32_emit_optimised_xor(state, rd, rd) +#define ASM_LOAD8_REG_REG_REG(state, rd, rs1, rs2) asm_rv32_emit_load_reg_reg_reg(state, rd, rs1, rs2, 0) +#define ASM_LOAD16_REG_REG_REG(state, rd, rs1, rs2) asm_rv32_emit_load_reg_reg_reg(state, rd, rs1, rs2, 1) +#define ASM_LOAD32_REG_REG_REG(state, rd, rs1, rs2) asm_rv32_emit_load_reg_reg_reg(state, rd, rs1, rs2, 2) +#define ASM_STORE8_REG_REG_REG(state, rd, rs1, rs2) asm_rv32_emit_store_reg_reg_reg(state, rd, rs1, rs2, 0) +#define ASM_STORE16_REG_REG_REG(state, rd, rs1, rs2) asm_rv32_emit_store_reg_reg_reg(state, rd, rs1, rs2, 1) +#define ASM_STORE32_REG_REG_REG(state, rd, rs1, rs2) asm_rv32_emit_store_reg_reg_reg(state, rd, rs1, rs2, 2) + +#endif + +#endif // MICROPY_INCLUDED_PY_ASMRV32_H diff --git a/py/asmthumb.c b/py/asmthumb.c index 0df79e5fd62..4226ae28127 100644 --- a/py/asmthumb.c +++ b/py/asmthumb.c @@ -35,25 +35,8 @@ #include "py/mpstate.h" #include "py/asmthumb.h" +#include "py/misc.h" -#ifdef _MSC_VER -#include - -static uint32_t mp_clz(uint32_t x) { - unsigned long lz = 0; - return _BitScanReverse(&lz, x) ? (sizeof(x) * 8 - 1) - lz : 0; -} - -static uint32_t mp_ctz(uint32_t x) { - unsigned long tz = 0; - return _BitScanForward(&tz, x) ? tz : 0; -} -#else -#define mp_clz(x) __builtin_clz(x) -#define mp_ctz(x) __builtin_ctz(x) -#endif - -#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) @@ -68,12 +51,6 @@ static uint32_t mp_ctz(uint32_t x) { #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)) - -#define OP_LDRH_W_HI(reg_base) (0xf8b0 | (reg_base)) -#define OP_LDRH_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); } @@ -269,7 +246,7 @@ void asm_thumb_mov_reg_reg(asm_thumb_t *as, uint reg_dest, uint reg_src) { void asm_thumb_mov_reg_i16(asm_thumb_t *as, uint mov_op, uint reg_dest, int i16_src) { assert(reg_dest < ASM_THUMB_REG_R15); // mov[wt] reg_dest, #i16_src - asm_thumb_op32(as, mov_op | ((i16_src >> 1) & 0x0400) | ((i16_src >> 12) & 0xf), ((i16_src << 4) & 0x7000) | (reg_dest << 8) | (i16_src & 0xff)); + asm_thumb_op32(as, mov_op | ((i16_src >> 1) & 0x0400) | ((i16_src >> 12) & 0xf), (((uint16_t)i16_src << 4) & 0x7000) | (reg_dest << 8) | (i16_src & 0xff)); } static void asm_thumb_mov_rlo_i16(asm_thumb_t *as, uint rlo_dest, int i16_src) { @@ -290,9 +267,8 @@ bool asm_thumb_b_n_label(asm_thumb_t *as, uint label) { #define OP_BCC_N(cond, byte_offset) (0xd000 | ((cond) << 8) | (((byte_offset) >> 1) & 0x00ff)) -// all these bit-arithmetic operations need coverage testing! -#define OP_BCC_W_HI(cond, byte_offset) (0xf000 | ((cond) << 6) | (((byte_offset) >> 10) & 0x0400) | (((byte_offset) >> 14) & 0x003f)) -#define OP_BCC_W_LO(byte_offset) (0x8000 | ((byte_offset) & 0x2000) | (((byte_offset) >> 1) & 0x0fff)) +#define OP_BCC_W_HI(cond, byte_offset) (0xf000 | ((cond) << 6) | (((byte_offset) >> 10) & 0x0400) | (((byte_offset) >> 12) & 0x003f)) +#define OP_BCC_W_LO(byte_offset) (0x8000 | (((byte_offset) >> 5) & 0x2000) | (((byte_offset) >> 8) & 0x0800) | (((byte_offset) >> 1) & 0x07ff)) bool asm_thumb_bcc_nw_label(asm_thumb_t *as, int cond, uint label, bool wide) { mp_uint_t dest = get_label_dest(as, label); @@ -448,11 +424,6 @@ void asm_thumb_mov_reg_pcrel(asm_thumb_t *as, uint rlo_dest, uint label) { asm_thumb_add_reg_reg(as, rlo_dest, ASM_THUMB_REG_R15); // 2 bytes } -// ARMv7-M only -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)); -} - // emits code for: reg_dest = reg_base + offset << offset_shift static void asm_thumb_add_reg_reg_offset(asm_thumb_t *as, uint reg_dest, uint reg_base, uint offset, uint offset_shift) { if (reg_dest < ASM_THUMB_REG_R8 && reg_base < ASM_THUMB_REG_R8) { @@ -466,12 +437,12 @@ static void asm_thumb_add_reg_reg_offset(asm_thumb_t *as, uint reg_dest, uint re asm_thumb_lsl_rlo_rlo_i5(as, reg_dest, reg_dest, offset_shift); asm_thumb_add_rlo_rlo_rlo(as, reg_dest, reg_dest, reg_base); } else if (reg_dest != reg_base) { - asm_thumb_mov_rlo_i16(as, reg_dest, offset << offset_shift); - asm_thumb_add_rlo_rlo_rlo(as, reg_dest, reg_dest, reg_dest); + asm_thumb_mov_reg_i32_optimised(as, reg_dest, offset << offset_shift); + asm_thumb_add_rlo_rlo_rlo(as, reg_dest, reg_dest, reg_base); } else { uint reg_other = reg_dest ^ 7; asm_thumb_op16(as, OP_PUSH_RLIST((1 << reg_other))); - asm_thumb_mov_rlo_i16(as, reg_other, offset << offset_shift); + asm_thumb_mov_reg_i32_optimised(as, reg_other, offset << offset_shift); asm_thumb_add_rlo_rlo_rlo(as, reg_dest, reg_dest, reg_other); asm_thumb_op16(as, OP_POP_RLIST((1 << reg_other))); } @@ -480,30 +451,50 @@ static void asm_thumb_add_reg_reg_offset(asm_thumb_t *as, uint reg_dest, uint re } } -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 if (asm_thumb_allow_armv7m(as)) { - asm_thumb_ldr_reg_reg_i12(as, reg_dest, reg_base, word_offset); +#define OP_LDR_STR_W_HI(operation_size, reg) ((0xf880 | (operation_size) << 5) | (reg)) +#define OP_LDR_STR_W_LO(reg, imm12) (((reg) << 12) | (imm12)) + +#define OP_LDR 0x01 +#define OP_STR 0x00 + +#define OP_LDR_W 0x10 +#define OP_STR_W 0x00 + +static const uint8_t OP_LDR_STR_TABLE[3] = { + 0x0E, 0x10, 0x0C +}; + +void asm_thumb_load_reg_reg_offset(asm_thumb_t *as, uint reg_dest, uint reg_base, uint offset, uint operation_size) { + assert(operation_size <= 2 && "Operation size out of range."); + + if (MP_FIT_UNSIGNED(5, offset) && (reg_dest < ASM_THUMB_REG_R8) && (reg_base < ASM_THUMB_REG_R8)) { + // Can use T1 encoding + asm_thumb_op16(as, ((OP_LDR_STR_TABLE[operation_size] | OP_LDR) << 11) | (offset << 6) | (reg_base << 3) | reg_dest); + } else if (asm_thumb_allow_armv7m(as) && MP_FIT_UNSIGNED(12, offset << operation_size)) { + // Can use T3 encoding + asm_thumb_op32(as, (OP_LDR_STR_W_HI(operation_size, reg_base) | OP_LDR_W), OP_LDR_STR_W_LO(reg_dest, (offset << operation_size))); } else { - asm_thumb_add_reg_reg_offset(as, reg_dest, reg_base, word_offset - 31, 2); - asm_thumb_ldr_rlo_rlo_i5(as, reg_dest, reg_dest, 31); + // Must use the generic sequence + asm_thumb_add_reg_reg_offset(as, reg_dest, reg_base, offset - 31, operation_size); + asm_thumb_op16(as, ((OP_LDR_STR_TABLE[operation_size] | OP_LDR) << 11) | (31 << 6) | (reg_dest << 3) | (reg_dest)); } } -// ARMv7-M only -static inline void asm_thumb_ldrh_reg_reg_i12(asm_thumb_t *as, uint reg_dest, uint reg_base, uint uint16_offset) { - asm_thumb_op32(as, OP_LDRH_W_HI(reg_base), OP_LDRH_W_LO(reg_dest, uint16_offset * 2)); -} +void asm_thumb_store_reg_reg_offset(asm_thumb_t *as, uint reg_src, uint reg_base, uint offset, uint operation_size) { + assert(operation_size <= 2 && "Operation size out of range."); -void asm_thumb_ldrh_reg_reg_i12_optimised(asm_thumb_t *as, uint reg_dest, uint reg_base, uint uint16_offset) { - if (reg_dest < ASM_THUMB_REG_R8 && reg_base < ASM_THUMB_REG_R8 && UNSIGNED_FIT5(uint16_offset)) { - asm_thumb_ldrh_rlo_rlo_i5(as, reg_dest, reg_base, uint16_offset); - } else if (asm_thumb_allow_armv7m(as)) { - asm_thumb_ldrh_reg_reg_i12(as, reg_dest, reg_base, uint16_offset); + if (MP_FIT_UNSIGNED(5, offset) && (reg_src < ASM_THUMB_REG_R8) && (reg_base < ASM_THUMB_REG_R8)) { + // Can use T1 encoding + asm_thumb_op16(as, ((OP_LDR_STR_TABLE[operation_size] | OP_STR) << 11) | (offset << 6) | (reg_base << 3) | reg_src); + } else if (asm_thumb_allow_armv7m(as) && MP_FIT_UNSIGNED(12, offset << operation_size)) { + // Can use T3 encoding + asm_thumb_op32(as, (OP_LDR_STR_W_HI(operation_size, reg_base) | OP_STR_W), OP_LDR_STR_W_LO(reg_src, (offset << operation_size))); } else { - asm_thumb_add_reg_reg_offset(as, reg_dest, reg_base, uint16_offset - 31, 1); - asm_thumb_ldrh_rlo_rlo_i5(as, reg_dest, reg_dest, 31); + // Must use the generic sequence + asm_thumb_op16(as, OP_PUSH_RLIST(1 << reg_base)); + asm_thumb_add_reg_reg_offset(as, reg_base, reg_base, offset - 31, operation_size); + asm_thumb_op16(as, ((OP_LDR_STR_TABLE[operation_size] | OP_STR) << 11) | (31 << 6) | (reg_base << 3) | reg_src); + asm_thumb_op16(as, OP_POP_RLIST(1 << reg_base)); } } @@ -511,6 +502,7 @@ void asm_thumb_ldrh_reg_reg_i12_optimised(asm_thumb_t *as, uint reg_dest, uint r #define OP_BW_HI(byte_offset) (0xf000 | (((byte_offset) >> 12) & 0x07ff)) #define OP_BW_LO(byte_offset) (0xb800 | (((byte_offset) >> 1) & 0x07ff)) +// In Thumb1 mode, this may clobber r1. void asm_thumb_b_label(asm_thumb_t *as, uint label) { mp_uint_t dest = get_label_dest(as, label); mp_int_t rel = dest - as->base.code_offset; @@ -530,19 +522,40 @@ void asm_thumb_b_label(asm_thumb_t *as, uint label) { if (asm_thumb_allow_armv7m(as)) { asm_thumb_op32(as, OP_BW_HI(rel), OP_BW_LO(rel)); } else { + // this code path has to be the same instruction size irrespective of the value of rel + bool need_align = as->base.code_offset & 2u; if (SIGNED_FIT12(rel)) { - // this code path has to be the same number of instructions irrespective of rel asm_thumb_op16(as, OP_B_N(rel)); - } else { asm_thumb_op16(as, ASM_THUMB_OP_NOP); - if (dest != (mp_uint_t)-1) { - // we have an actual branch > 12 bits; this is not handled yet - mp_raise_NotImplementedError(MP_ERROR_TEXT("native method too big")); + asm_thumb_op16(as, ASM_THUMB_OP_NOP); + asm_thumb_op16(as, ASM_THUMB_OP_NOP); + if (need_align) { + asm_thumb_op16(as, ASM_THUMB_OP_NOP); } + } else { + // do a large jump using: + // (nop) + // ldr r1, [pc, _data] + // add pc, r1 + // _data: .word rel + // + // note: can't use r0 as a temporary because native code can have the return value + // in that register and use a large jump to get to the exit point of the function + + rel -= 2; // account for the "ldr r1, [pc, _data]" + if (need_align) { + asm_thumb_op16(as, ASM_THUMB_OP_NOP); + rel -= 2; // account for this nop + } + asm_thumb_ldr_rlo_pcrel_i8(as, ASM_THUMB_REG_R1, 0); + asm_thumb_add_reg_reg(as, ASM_THUMB_REG_R15, ASM_THUMB_REG_R1); + asm_thumb_op16(as, rel & 0xffff); + asm_thumb_op16(as, rel >> 16); } } } +// In Thumb1 mode, this may clobber r1. void asm_thumb_bcc_label(asm_thumb_t *as, int cond, uint label) { mp_uint_t dest = get_label_dest(as, label); mp_int_t rel = dest - as->base.code_offset; @@ -563,8 +576,15 @@ void asm_thumb_bcc_label(asm_thumb_t *as, int cond, uint label) { asm_thumb_op32(as, OP_BCC_W_HI(cond, rel), OP_BCC_W_LO(rel)); } else { // reverse the sense of the branch to jump over a longer branch - asm_thumb_op16(as, OP_BCC_N(cond ^ 1, 0)); + size_t code_offset_start = as->base.code_offset; + byte *c = asm_thumb_get_cur_to_write_bytes(as, 2); asm_thumb_b_label(as, label); + size_t bytes_to_skip = as->base.code_offset - code_offset_start; + uint16_t op = OP_BCC_N(cond ^ 1, bytes_to_skip - 4); + if (c != NULL) { + c[0] = op; + c[1] = op >> 8; + } } } @@ -585,7 +605,7 @@ void asm_thumb_b_rel12(asm_thumb_t *as, int rel) { 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_load_reg_reg_offset(as, reg_temp, ASM_THUMB_REG_FUN_TABLE, fun_id, 2); asm_thumb_op16(as, OP_BLX(reg_temp)); } diff --git a/py/asmthumb.h b/py/asmthumb.h index 0584ed3227a..229912c5385 100644 --- a/py/asmthumb.h +++ b/py/asmthumb.h @@ -251,6 +251,50 @@ 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 7: load/store with register offset +// FORMAT 8: load/store sign-extended byte/halfword + +#define ASM_THUMB_FORMAT_7_LDR (0x5800) +#define ASM_THUMB_FORMAT_7_STR (0x5000) +#define ASM_THUMB_FORMAT_7_WORD_TRANSFER (0x0000) +#define ASM_THUMB_FORMAT_7_BYTE_TRANSFER (0x0400) +#define ASM_THUMB_FORMAT_8_LDRH (0x5A00) +#define ASM_THUMB_FORMAT_8_STRH (0x5200) + +#define ASM_THUMB_FORMAT_7_8_ENCODE(op, rlo_dest, rlo_base, rlo_index) \ + ((op) | ((rlo_index) << 6) | ((rlo_base) << 3) | ((rlo_dest))) + +static inline void asm_thumb_format_7_8(asm_thumb_t *as, uint op, uint rlo_dest, uint rlo_base, uint rlo_index) { + assert(rlo_dest < ASM_THUMB_REG_R8); + assert(rlo_base < ASM_THUMB_REG_R8); + assert(rlo_index < ASM_THUMB_REG_R8); + asm_thumb_op16(as, ASM_THUMB_FORMAT_7_8_ENCODE(op, rlo_dest, rlo_base, rlo_index)); +} + +static inline void asm_thumb_ldrb_rlo_rlo_rlo(asm_thumb_t *as, uint rlo_dest, uint rlo_base, uint rlo_index) { + asm_thumb_format_7_8(as, ASM_THUMB_FORMAT_7_LDR | ASM_THUMB_FORMAT_7_BYTE_TRANSFER, rlo_dest, rlo_base, rlo_index); +} + +static inline void asm_thumb_ldrh_rlo_rlo_rlo(asm_thumb_t *as, uint rlo_dest, uint rlo_base, uint rlo_index) { + asm_thumb_format_7_8(as, ASM_THUMB_FORMAT_8_LDRH, rlo_dest, rlo_base, rlo_index); +} + +static inline void asm_thumb_ldr_rlo_rlo_rlo(asm_thumb_t *as, uint rlo_dest, uint rlo_base, uint rlo_index) { + asm_thumb_format_7_8(as, ASM_THUMB_FORMAT_7_LDR | ASM_THUMB_FORMAT_7_WORD_TRANSFER, rlo_dest, rlo_base, rlo_index); +} + +static inline void asm_thumb_strb_rlo_rlo_rlo(asm_thumb_t *as, uint rlo_src, uint rlo_base, uint rlo_index) { + asm_thumb_format_7_8(as, ASM_THUMB_FORMAT_7_STR | ASM_THUMB_FORMAT_7_BYTE_TRANSFER, rlo_src, rlo_base, rlo_index); +} + +static inline void asm_thumb_strh_rlo_rlo_rlo(asm_thumb_t *as, uint rlo_dest, uint rlo_base, uint rlo_index) { + asm_thumb_format_7_8(as, ASM_THUMB_FORMAT_8_STRH, rlo_dest, rlo_base, rlo_index); +} + +static inline void asm_thumb_str_rlo_rlo_rlo(asm_thumb_t *as, uint rlo_src, uint rlo_base, uint rlo_index) { + asm_thumb_format_7_8(as, ASM_THUMB_FORMAT_7_STR | ASM_THUMB_FORMAT_7_WORD_TRANSFER, rlo_src, rlo_base, rlo_index); +} + // FORMAT 9: load/store with immediate offset // For word transfers the offset must be aligned, and >>2 @@ -273,24 +317,6 @@ static inline void asm_thumb_format_9_10(asm_thumb_t *as, uint op, uint rlo_dest 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 uint16_offset) { - asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_10_STRH, rlo_src, rlo_base, uint16_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 uint16_offset) { - asm_thumb_format_9_10(as, ASM_THUMB_FORMAT_10_LDRH, rlo_dest, rlo_base, uint16_offset); -} static inline void asm_thumb_lsl_rlo_rlo_i5(asm_thumb_t *as, uint rlo_dest, uint rlo_src, uint shift) { asm_thumb_format_1(as, ASM_THUMB_FORMAT_1_LSL, rlo_dest, rlo_src, shift); } @@ -338,8 +364,10 @@ void asm_thumb_mov_reg_local(asm_thumb_t *as, uint rlo_dest, int local_num); // 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 word_offset); // convenience -void asm_thumb_ldrh_reg_reg_i12_optimised(asm_thumb_t *as, uint reg_dest, uint reg_base, uint uint16_offset); // convenience +// Generate optimised load dest, [src, #offset] sequence +void asm_thumb_load_reg_reg_offset(asm_thumb_t *as, uint reg_dest, uint reg_base, uint offset, uint operation_size); +// Generate optimised store src, [dest, #offset] sequence +void asm_thumb_store_reg_reg_offset(asm_thumb_t *as, uint reg_src, uint reg_base, uint offset, uint operation_size); 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 @@ -376,12 +404,12 @@ void asm_thumb_b_rel12(asm_thumb_t *as, int rel); #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_T asm_thumb_t +#define ASM_END_PASS asm_thumb_end_pass +#define ASM_ENTRY(as, num_locals, name) asm_thumb_entry((as), (num_locals)) +#define ASM_EXIT asm_thumb_exit -#define ASM_JUMP asm_thumb_b_label +#define ASM_JUMP asm_thumb_b_label #define ASM_JUMP_IF_REG_ZERO(as, reg, label, bool_test) \ do { \ asm_thumb_cmp_rlo_i8(as, reg, 0); \ @@ -419,18 +447,50 @@ void asm_thumb_b_rel12(asm_thumb_t *as, int rel); #define ASM_SUB_REG_REG(as, reg_dest, reg_src) asm_thumb_sub_rlo_rlo_rlo((as), (reg_dest), (reg_dest), (reg_src)) #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_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_LOAD16_REG_REG_OFFSET(as, reg_dest, reg_base, uint16_offset) asm_thumb_ldrh_reg_reg_i12_optimised((as), (reg_dest), (reg_base), (uint16_offset)) -#define ASM_LOAD32_REG_REG(as, reg_dest, reg_base) asm_thumb_ldr_rlo_rlo_i5((as), (reg_dest), (reg_base), 0) - -#define ASM_STORE_REG_REG(as, reg_src, reg_base) asm_thumb_str_rlo_rlo_i5((as), (reg_src), (reg_base), 0) -#define ASM_STORE_REG_REG_OFFSET(as, reg_src, reg_base, word_offset) asm_thumb_str_rlo_rlo_i5((as), (reg_src), (reg_base), (word_offset)) -#define ASM_STORE8_REG_REG(as, reg_src, reg_base) asm_thumb_strb_rlo_rlo_i5((as), (reg_src), (reg_base), 0) -#define ASM_STORE16_REG_REG(as, reg_src, reg_base) asm_thumb_strh_rlo_rlo_i5((as), (reg_src), (reg_base), 0) -#define ASM_STORE32_REG_REG(as, reg_src, reg_base) asm_thumb_str_rlo_rlo_i5((as), (reg_src), (reg_base), 0) +#define ASM_LOAD_REG_REG_OFFSET(as, reg_dest, reg_base, word_offset) ASM_LOAD32_REG_REG_OFFSET((as), (reg_dest), (reg_base), (word_offset)) +#define ASM_LOAD8_REG_REG(as, reg_dest, reg_base) ASM_LOAD8_REG_REG_OFFSET((as), (reg_dest), (reg_base), 0) +#define ASM_LOAD8_REG_REG_OFFSET(as, reg_dest, reg_base, byte_offset) asm_thumb_load_reg_reg_offset((as), (reg_dest), (reg_base), (byte_offset), 0) +#define ASM_LOAD16_REG_REG(as, reg_dest, reg_base) ASM_LOAD16_REG_REG_OFFSET((as), (reg_dest), (reg_base), 0) +#define ASM_LOAD16_REG_REG_OFFSET(as, reg_dest, reg_base, halfword_offset) asm_thumb_load_reg_reg_offset((as), (reg_dest), (reg_base), (halfword_offset), 1) +#define ASM_LOAD32_REG_REG(as, reg_dest, reg_base) ASM_LOAD32_REG_REG_OFFSET((as), (reg_dest), (reg_base), 0) +#define ASM_LOAD32_REG_REG_OFFSET(as, reg_dest, reg_base, word_offset) asm_thumb_load_reg_reg_offset((as), (reg_dest), (reg_base), (word_offset), 2) + +#define ASM_STORE_REG_REG_OFFSET(as, reg_src, reg_base, word_offset) ASM_STORE32_REG_REG_OFFSET((as), (reg_src), (reg_base), (word_offset)) +#define ASM_STORE8_REG_REG(as, reg_src, reg_base) ASM_STORE8_REG_REG_OFFSET((as), (reg_src), (reg_base), 0) +#define ASM_STORE8_REG_REG_OFFSET(as, reg_src, reg_base, byte_offset) asm_thumb_store_reg_reg_offset((as), (reg_src), (reg_base), (byte_offset), 0) +#define ASM_STORE16_REG_REG(as, reg_src, reg_base) ASM_STORE16_REG_REG_OFFSET((as), (reg_src), (reg_base), 0) +#define ASM_STORE16_REG_REG_OFFSET(as, reg_src, reg_base, halfword_offset) asm_thumb_store_reg_reg_offset((as), (reg_src), (reg_base), (halfword_offset), 1) +#define ASM_STORE32_REG_REG(as, reg_src, reg_base) ASM_STORE32_REG_REG_OFFSET((as), (reg_src), (reg_base), 0) +#define ASM_STORE32_REG_REG_OFFSET(as, reg_src, reg_base, word_offset) asm_thumb_store_reg_reg_offset((as), (reg_src), (reg_base), (word_offset), 2) + +#define ASM_LOAD8_REG_REG_REG(as, reg_dest, reg_base, reg_index) asm_thumb_ldrb_rlo_rlo_rlo((as), (reg_dest), (reg_base), (reg_index)) +#define ASM_LOAD16_REG_REG_REG(as, reg_dest, reg_base, reg_index) \ + do { \ + asm_thumb_lsl_rlo_rlo_i5((as), REG_TEMP2, (reg_index), 1); \ + asm_thumb_ldrh_rlo_rlo_rlo((as), (reg_dest), (reg_base), REG_TEMP2); \ + } while (0) +#define ASM_LOAD32_REG_REG_REG(as, reg_dest, reg_base, reg_index) \ + do { \ + asm_thumb_lsl_rlo_rlo_i5((as), REG_TEMP2, (reg_index), 2); \ + asm_thumb_ldr_rlo_rlo_rlo((as), (reg_dest), (reg_base), REG_TEMP2); \ + } while (0) +#define ASM_STORE8_REG_REG_REG(as, reg_val, reg_base, reg_index) asm_thumb_strb_rlo_rlo_rlo((as), (reg_val), (reg_base), (reg_index)) +#define ASM_STORE16_REG_REG_REG(as, reg_val, reg_base, reg_index) \ + do { \ + asm_thumb_op16((as), 0xB400 | (1 << reg_index)); \ + asm_thumb_lsl_rlo_rlo_i5((as), (reg_index), (reg_index), 1); \ + asm_thumb_strh_rlo_rlo_rlo((as), (reg_val), (reg_base), (reg_index)); \ + asm_thumb_op16((as), 0xBC00 | (1 << reg_index)); \ + } while (0) +#define ASM_STORE32_REG_REG_REG(as, reg_val, reg_base, reg_index) \ + do { \ + asm_thumb_op16((as), 0xB400 | (1 << reg_index)); \ + asm_thumb_lsl_rlo_rlo_i5((as), (reg_index), (reg_index), 2); \ + asm_thumb_str_rlo_rlo_rlo((as), (reg_val), (reg_base), (reg_index)); \ + asm_thumb_op16((as), 0xBC00 | (1 << reg_index)); \ + } while (0) + +#define ASM_CLR_REG(as, reg_dest) asm_thumb_mov_rlo_i8((as), (reg_dest), 0) #endif // GENERIC_ASM_API diff --git a/py/asmx64.h b/py/asmx64.h index 03070b5f63d..8e2c2679428 100644 --- a/py/asmx64.h +++ b/py/asmx64.h @@ -155,12 +155,12 @@ void asm_x64_call_ind(asm_x64_t *as, size_t fun_id, int temp_r32); // 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_T asm_x64_t +#define ASM_END_PASS asm_x64_end_pass +#define ASM_ENTRY(as, num_locals, name) asm_x64_entry((as), (num_locals)) +#define ASM_EXIT asm_x64_exit -#define ASM_JUMP asm_x64_jmp_label +#define ASM_JUMP asm_x64_jmp_label #define ASM_JUMP_IF_REG_ZERO(as, reg, label, bool_test) \ do { \ if (bool_test) { \ @@ -206,18 +206,23 @@ void asm_x64_call_ind(asm_x64_t *as, size_t fun_id, int temp_r32); #define ASM_SUB_REG_REG(as, reg_dest, reg_src) asm_x64_sub_r64_r64((as), (reg_dest), (reg_src)) #define ASM_MUL_REG_REG(as, reg_dest, reg_src) asm_x64_mul_r64_r64((as), (reg_dest), (reg_src)) -#define ASM_LOAD_REG_REG(as, reg_dest, reg_base) asm_x64_mov_mem64_to_r64((as), (reg_base), 0, (reg_dest)) -#define ASM_LOAD_REG_REG_OFFSET(as, reg_dest, reg_base, word_offset) asm_x64_mov_mem64_to_r64((as), (reg_base), 8 * (word_offset), (reg_dest)) -#define ASM_LOAD8_REG_REG(as, reg_dest, reg_base) asm_x64_mov_mem8_to_r64zx((as), (reg_base), 0, (reg_dest)) -#define ASM_LOAD16_REG_REG(as, reg_dest, reg_base) asm_x64_mov_mem16_to_r64zx((as), (reg_base), 0, (reg_dest)) -#define ASM_LOAD16_REG_REG_OFFSET(as, reg_dest, reg_base, uint16_offset) asm_x64_mov_mem16_to_r64zx((as), (reg_base), 2 * (uint16_offset), (reg_dest)) -#define ASM_LOAD32_REG_REG(as, reg_dest, reg_base) asm_x64_mov_mem32_to_r64zx((as), (reg_base), 0, (reg_dest)) - -#define ASM_STORE_REG_REG(as, reg_src, reg_base) asm_x64_mov_r64_to_mem64((as), (reg_src), (reg_base), 0) -#define ASM_STORE_REG_REG_OFFSET(as, reg_src, reg_base, word_offset) asm_x64_mov_r64_to_mem64((as), (reg_src), (reg_base), 8 * (word_offset)) -#define ASM_STORE8_REG_REG(as, reg_src, reg_base) asm_x64_mov_r8_to_mem8((as), (reg_src), (reg_base), 0) -#define ASM_STORE16_REG_REG(as, reg_src, reg_base) asm_x64_mov_r16_to_mem16((as), (reg_src), (reg_base), 0) -#define ASM_STORE32_REG_REG(as, reg_src, reg_base) asm_x64_mov_r32_to_mem32((as), (reg_src), (reg_base), 0) +#define ASM_LOAD_REG_REG_OFFSET(as, reg_dest, reg_base, qword_offset) asm_x64_mov_mem64_to_r64((as), (reg_base), 8 * (qword_offset), (reg_dest)) +#define ASM_LOAD8_REG_REG(as, reg_dest, reg_base) ASM_LOAD8_REG_REG_OFFSET((as), (reg_dest), (reg_base), 0) +#define ASM_LOAD8_REG_REG_OFFSET(as, reg_dest, reg_base, byte_offset) asm_x64_mov_mem8_to_r64zx((as), (reg_base), (byte_offset), (reg_dest)) +#define ASM_LOAD16_REG_REG(as, reg_dest, reg_base) ASM_LOAD16_REG_REG_OFFSET((as), (reg_dest), (reg_base), 0) +#define ASM_LOAD16_REG_REG_OFFSET(as, reg_dest, reg_base, word_offset) asm_x64_mov_mem16_to_r64zx((as), (reg_base), 2 * (word_offset), (reg_dest)) +#define ASM_LOAD32_REG_REG(as, reg_dest, reg_base) ASM_LOAD32_REG_REG_OFFSET((as), (reg_dest), (reg_base), 0) +#define ASM_LOAD32_REG_REG_OFFSET(as, reg_dest, reg_base, dword_offset) asm_x64_mov_mem32_to_r64zx((as), (reg_base), 4 * (dword_offset), (reg_dest)) + +#define ASM_STORE_REG_REG_OFFSET(as, reg_src, reg_base, qword_offset) asm_x64_mov_r64_to_mem64((as), (reg_src), (reg_base), 8 * (qword_offset)) +#define ASM_STORE8_REG_REG(as, reg_src, reg_base) ASM_STORE8_REG_REG_OFFSET((as), (reg_src), (reg_base), 0) +#define ASM_STORE8_REG_REG_OFFSET(as, reg_src, reg_base, byte_offset) asm_x64_mov_r8_to_mem8((as), (reg_src), (reg_base), (byte_offset)) +#define ASM_STORE16_REG_REG(as, reg_src, reg_base) ASM_STORE16_REG_REG_OFFSET((as), (reg_src), (reg_base), 0) +#define ASM_STORE16_REG_REG_OFFSET(as, reg_src, reg_base, word_offset) asm_x64_mov_r16_to_mem16((as), (reg_src), (reg_base), 2 * (word_offset)) +#define ASM_STORE32_REG_REG(as, reg_src, reg_base) ASM_STORE32_REG_REG_OFFSET((as), (reg_src), (reg_base), 0) +#define ASM_STORE32_REG_REG_OFFSET(as, reg_src, reg_base, dword_offset) asm_x64_mov_r32_to_mem32((as), (reg_src), (reg_base), 4 * (dword_offset)) + +#define ASM_CLR_REG(as, reg_dest) asm_x64_xor_r64_r64((as), (reg_dest), (reg_dest)) #endif // GENERIC_ASM_API diff --git a/py/asmx86.h b/py/asmx86.h index 7796d697626..3d95dbee733 100644 --- a/py/asmx86.h +++ b/py/asmx86.h @@ -150,12 +150,12 @@ void asm_x86_call_ind(asm_x86_t *as, size_t fun_id, mp_uint_t n_args, int temp_r // 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_T asm_x86_t +#define ASM_END_PASS asm_x86_end_pass +#define ASM_ENTRY(as, num_locals, name) asm_x86_entry((as), (num_locals)) +#define ASM_EXIT asm_x86_exit -#define ASM_JUMP asm_x86_jmp_label +#define ASM_JUMP asm_x86_jmp_label #define ASM_JUMP_IF_REG_ZERO(as, reg, label, bool_test) \ do { \ if (bool_test) { \ @@ -201,18 +201,23 @@ void asm_x86_call_ind(asm_x86_t *as, size_t fun_id, mp_uint_t n_args, int temp_r #define ASM_SUB_REG_REG(as, reg_dest, reg_src) asm_x86_sub_r32_r32((as), (reg_dest), (reg_src)) #define ASM_MUL_REG_REG(as, reg_dest, reg_src) asm_x86_mul_r32_r32((as), (reg_dest), (reg_src)) -#define ASM_LOAD_REG_REG(as, reg_dest, reg_base) asm_x86_mov_mem32_to_r32((as), (reg_base), 0, (reg_dest)) -#define ASM_LOAD_REG_REG_OFFSET(as, reg_dest, reg_base, word_offset) asm_x86_mov_mem32_to_r32((as), (reg_base), 4 * (word_offset), (reg_dest)) -#define ASM_LOAD8_REG_REG(as, reg_dest, reg_base) asm_x86_mov_mem8_to_r32zx((as), (reg_base), 0, (reg_dest)) -#define ASM_LOAD16_REG_REG(as, reg_dest, reg_base) asm_x86_mov_mem16_to_r32zx((as), (reg_base), 0, (reg_dest)) -#define ASM_LOAD16_REG_REG_OFFSET(as, reg_dest, reg_base, uint16_offset) asm_x86_mov_mem16_to_r32zx((as), (reg_base), 2 * (uint16_offset), (reg_dest)) -#define ASM_LOAD32_REG_REG(as, reg_dest, reg_base) asm_x86_mov_mem32_to_r32((as), (reg_base), 0, (reg_dest)) - -#define ASM_STORE_REG_REG(as, reg_src, reg_base) asm_x86_mov_r32_to_mem32((as), (reg_src), (reg_base), 0) -#define ASM_STORE_REG_REG_OFFSET(as, reg_src, reg_base, word_offset) asm_x86_mov_r32_to_mem32((as), (reg_src), (reg_base), 4 * (word_offset)) -#define ASM_STORE8_REG_REG(as, reg_src, reg_base) asm_x86_mov_r8_to_mem8((as), (reg_src), (reg_base), 0) -#define ASM_STORE16_REG_REG(as, reg_src, reg_base) asm_x86_mov_r16_to_mem16((as), (reg_src), (reg_base), 0) -#define ASM_STORE32_REG_REG(as, reg_src, reg_base) asm_x86_mov_r32_to_mem32((as), (reg_src), (reg_base), 0) +#define ASM_LOAD_REG_REG_OFFSET(as, reg_dest, reg_base, dword_offset) ASM_LOAD32_REG_REG_OFFSET((as), (reg_dest), (reg_base), (dword_offset)) +#define ASM_LOAD8_REG_REG(as, reg_dest, reg_base) ASM_LOAD8_REG_REG_OFFSET((as), (reg_dest), (reg_base), 0) +#define ASM_LOAD8_REG_REG_OFFSET(as, reg_dest, reg_base, byte_offset) asm_x86_mov_mem8_to_r32zx((as), (reg_base), (byte_offset), (reg_dest)) +#define ASM_LOAD16_REG_REG(as, reg_dest, reg_base) ASM_LOAD16_REG_REG_OFFSET((as), (reg_dest), (reg_base), 0) +#define ASM_LOAD16_REG_REG_OFFSET(as, reg_dest, reg_base, word_offset) asm_x86_mov_mem16_to_r32zx((as), (reg_base), 2 * (word_offset), (reg_dest)) +#define ASM_LOAD32_REG_REG(as, reg_dest, reg_base) ASM_LOAD32_REG_REG_OFFSET((as), (reg_dest), (reg_base), 0) +#define ASM_LOAD32_REG_REG_OFFSET(as, reg_dest, reg_base, dword_offset) asm_x86_mov_mem32_to_r32((as), (reg_base), 4 * (dword_offset), (reg_dest)) + +#define ASM_STORE_REG_REG_OFFSET(as, reg_src, reg_base, dword_offset) ASM_STORE32_REG_REG_OFFSET((as), (reg_src), (reg_base), (dword_offset)) +#define ASM_STORE8_REG_REG(as, reg_src, reg_base) ASM_STORE8_REG_REG_OFFSET((as), (reg_src), (reg_base), 0) +#define ASM_STORE8_REG_REG_OFFSET(as, reg_src, reg_base, byte_offset) asm_x86_mov_r8_to_mem8((as), (reg_src), (reg_base), (byte_offset)) +#define ASM_STORE16_REG_REG(as, reg_src, reg_base) ASM_STORE16_REG_REG_OFFSET((as), (reg_src), (reg_base), 0) +#define ASM_STORE16_REG_REG_OFFSET(as, reg_src, reg_base, word_offset) asm_x86_mov_r16_to_mem16((as), (reg_src), (reg_base), 2 * (word_offset)) +#define ASM_STORE32_REG_REG(as, reg_src, reg_base) ASM_STORE32_REG_REG_OFFSET((as), (reg_src), (reg_base), 0) +#define ASM_STORE32_REG_REG_OFFSET(as, reg_src, reg_base, dword_offset) asm_x86_mov_r32_to_mem32((as), (reg_src), (reg_base), 4 * (dword_offset)) + +#define ASM_CLR_REG(as, reg_dest) asm_x86_xor_r32_r32((as), (reg_dest), (reg_dest)) #endif // GENERIC_ASM_API diff --git a/py/asmxtensa.c b/py/asmxtensa.c index 0fbe351dcf3..18aea4ea29d 100644 --- a/py/asmxtensa.c +++ b/py/asmxtensa.c @@ -34,9 +34,20 @@ #include "py/asmxtensa.h" +#if N_XTENSAWIN +#define REG_TEMP ASM_XTENSA_REG_TEMPORARY_WIN +#else +#define REG_TEMP ASM_XTENSA_REG_TEMPORARY +#endif + #define WORD_SIZE (4) +#define SIGNED_FIT6(x) ((((x) & 0xffffffe0) == 0) || (((x) & 0xffffffe0) == 0xffffffe0)) #define SIGNED_FIT8(x) ((((x) & 0xffffff80) == 0) || (((x) & 0xffffff80) == 0xffffff80)) #define SIGNED_FIT12(x) ((((x) & 0xfffff800) == 0) || (((x) & 0xfffff800) == 0xfffff800)) +#define SIGNED_FIT18(x) ((((x) & 0xfffe0000) == 0) || (((x) & 0xfffe0000) == 0xfffe0000)) + +#define ET_OUT_OF_RANGE MP_ERROR_TEXT("ERROR: xtensa %q out of range") +#define ET_NOT_ALIGNED MP_ERROR_TEXT("ERROR: %q %q not word-aligned") void asm_xtensa_end_pass(asm_xtensa_t *as) { as->num_const = as->cur_const; @@ -47,9 +58,9 @@ void asm_xtensa_end_pass(asm_xtensa_t *as) { if (as->base.pass == MP_ASM_PASS_EMIT) { uint8_t *d = as->base.code_base; printf("XTENSA ASM:"); - for (int i = 0; i < ((as->base.code_size + 15) & ~15); ++i) { + for (size_t i = 0; i < ((as->base.code_size + 15) & ~15); ++i) { if (i % 16 == 0) { - printf("\n%08x:", (uint32_t)&d[i]); + printf("\n%p:", &d[i]); } if (i % 2 == 0) { printf(" "); @@ -62,10 +73,12 @@ void asm_xtensa_end_pass(asm_xtensa_t *as) { } 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); + if (as->num_const > 0) { + // 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); + } // adjust the stack-pointer to store a0, a12, a13, a14, a15 and locals, 16-byte aligned as->stack_adjust = (((ASM_XTENSA_NUM_REGS_SAVED + num_locals) * WORD_SIZE) + 15) & ~15; @@ -102,10 +115,12 @@ void asm_xtensa_exit(asm_xtensa_t *as) { } void asm_xtensa_entry_win(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); + if (as->num_const > 0) { + // 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->stack_adjust = 32 + ((((ASM_XTENSA_NUM_REGS_SAVED_WIN + num_locals) * WORD_SIZE) + 15) & ~15); asm_xtensa_op_entry(as, ASM_XTENSA_REG_A1, as->stack_adjust); @@ -146,22 +161,60 @@ void asm_xtensa_j_label(asm_xtensa_t *as, uint label) { asm_xtensa_op_j(as, rel); } +static bool calculate_branch_displacement(asm_xtensa_t *as, uint label, ptrdiff_t *displacement) { + assert(displacement != NULL && "Displacement pointer is NULL"); + + uint32_t label_offset = get_label_dest(as, label); + *displacement = (ptrdiff_t)(label_offset - as->base.code_offset - 4); + return (label_offset != (uint32_t)-1) && (*displacement < 0); +} + void asm_xtensa_bccz_reg_label(asm_xtensa_t *as, uint cond, uint reg, uint label) { - uint32_t dest = get_label_dest(as, label); - int32_t rel = dest - as->base.code_offset - 4; - if (as->base.pass == MP_ASM_PASS_EMIT && !SIGNED_FIT12(rel)) { - printf("ERROR: xtensa bccz out of range\n"); + ptrdiff_t rel = 0; + bool can_emit_short_jump = calculate_branch_displacement(as, label, &rel); + + if (can_emit_short_jump && SIGNED_FIT12(rel)) { + // Backwards BCCZ opcodes with an offset that fits in 12 bits can + // be emitted without any change. + asm_xtensa_op_bccz(as, cond, reg, rel); + return; + } + + // Range is effectively extended to 18 bits, as a more complex jump code + // sequence is emitted. + if (as->base.pass == MP_ASM_PASS_EMIT && !SIGNED_FIT18(rel - 6)) { + mp_raise_msg_varg(&mp_type_RuntimeError, ET_OUT_OF_RANGE, MP_QSTR_bccz); } - asm_xtensa_op_bccz(as, cond, reg, rel); + + // ~BCCZ skip ; +0 <- Condition is flipped here (EQ -> NE, etc.) + // J addr ; +3 + // skip: ; +6 + asm_xtensa_op_bccz(as, cond ^ 1, reg, 6 - 4); + asm_xtensa_op_j(as, rel - 3); } void asm_xtensa_bcc_reg_reg_label(asm_xtensa_t *as, uint cond, uint reg1, uint reg2, uint label) { - uint32_t dest = get_label_dest(as, label); - int32_t rel = dest - as->base.code_offset - 4; - if (as->base.pass == MP_ASM_PASS_EMIT && !SIGNED_FIT8(rel)) { - printf("ERROR: xtensa bcc out of range\n"); + ptrdiff_t rel = 0; + bool can_emit_short_jump = calculate_branch_displacement(as, label, &rel); + + if (can_emit_short_jump && SIGNED_FIT8(rel)) { + // Backwards BCC opcodes with an offset that fits in 8 bits can + // be emitted without any change. + asm_xtensa_op_bcc(as, cond, reg1, reg2, rel); + return; } - asm_xtensa_op_bcc(as, cond, reg1, reg2, rel); + + // Range is effectively extended to 18 bits, as a more complex jump code + // sequence is emitted. + if (as->base.pass == MP_ASM_PASS_EMIT && !SIGNED_FIT18(rel - 6)) { + mp_raise_msg_varg(&mp_type_RuntimeError, ET_OUT_OF_RANGE, MP_QSTR_bcc); + } + + // ~BCC skip ; +0 <- Condition is flipped here (EQ -> NE, etc.) + // J addr ; +3 + // skip: ; +6 + asm_xtensa_op_bcc(as, cond ^ 8, reg1, reg2, 6 - 4); + asm_xtensa_op_j(as, rel - 3); } // convenience function; reg_dest must be different from reg_src[12] @@ -179,6 +232,8 @@ size_t asm_xtensa_mov_reg_i32(asm_xtensa_t *as, uint reg_dest, uint32_t i32) { // store the constant in the table if (as->const_table != NULL) { as->const_table[as->cur_const] = i32; + } else { + assert((as->base.pass != MP_ASM_PASS_EMIT) && "Constants table was not built."); } ++as->cur_const; return loc; @@ -240,17 +295,53 @@ void asm_xtensa_l32i_optimised(asm_xtensa_t *as, uint reg_dest, uint reg_base, u } else if (word_offset < 256) { asm_xtensa_op_l32i(as, reg_dest, reg_base, word_offset); } else { - mp_raise_msg(&mp_type_RuntimeError, MP_ERROR_TEXT("asm overflow")); + asm_xtensa_mov_reg_i32_optimised(as, reg_dest, word_offset * 4); + asm_xtensa_op_add_n(as, reg_dest, reg_base, reg_dest); + asm_xtensa_op_l32i_n(as, reg_dest, reg_dest, 0); } } -void asm_xtensa_s32i_optimised(asm_xtensa_t *as, uint reg_src, uint reg_base, uint word_offset) { - if (word_offset < 16) { - asm_xtensa_op_s32i_n(as, reg_src, reg_base, word_offset); - } else if (word_offset < 256) { - asm_xtensa_op_s32i(as, reg_src, reg_base, word_offset); +void asm_xtensa_load_reg_reg_offset(asm_xtensa_t *as, uint reg_dest, uint reg_base, uint offset, uint operation_size) { + assert(operation_size <= 2 && "Operation size value out of range."); + + if (operation_size == 2 && MP_FIT_UNSIGNED(4, offset)) { + asm_xtensa_op_l32i_n(as, reg_dest, reg_base, offset); + return; + } + + if (MP_FIT_UNSIGNED(8, offset)) { + asm_xtensa_op24(as, ASM_XTENSA_ENCODE_RRI8(2, operation_size, reg_base, reg_dest, offset)); + return; + } + + asm_xtensa_mov_reg_i32_optimised(as, reg_dest, offset << operation_size); + asm_xtensa_op_add_n(as, reg_dest, reg_base, reg_dest); + if (operation_size == 2) { + asm_xtensa_op_l32i_n(as, reg_dest, reg_dest, 0); + } else { + asm_xtensa_op24(as, ASM_XTENSA_ENCODE_RRI8(2, operation_size, reg_dest, reg_dest, 0)); + } +} + +void asm_xtensa_store_reg_reg_offset(asm_xtensa_t *as, uint reg_src, uint reg_base, uint offset, uint operation_size) { + assert(operation_size <= 2 && "Operation size value out of range."); + + if (operation_size == 2 && MP_FIT_UNSIGNED(4, offset)) { + asm_xtensa_op_s32i_n(as, reg_src, reg_base, offset); + return; + } + + if (MP_FIT_UNSIGNED(8, offset)) { + asm_xtensa_op24(as, ASM_XTENSA_ENCODE_RRI8(2, 0x04 | operation_size, reg_base, reg_src, offset)); + return; + } + + asm_xtensa_mov_reg_i32_optimised(as, REG_TEMP, offset << operation_size); + asm_xtensa_op_add_n(as, REG_TEMP, reg_base, REG_TEMP); + if (operation_size == 2) { + asm_xtensa_op_s32i_n(as, reg_src, REG_TEMP, 0); } else { - mp_raise_msg(&mp_type_RuntimeError, MP_ERROR_TEXT("asm overflow")); + asm_xtensa_op24(as, ASM_XTENSA_ENCODE_RRI8(2, 0x04 | operation_size, REG_TEMP, reg_src, 0)); } } @@ -264,4 +355,47 @@ void asm_xtensa_call_ind_win(asm_xtensa_t *as, uint idx) { asm_xtensa_op_callx8(as, ASM_XTENSA_REG_A8); } +void asm_xtensa_bit_branch(asm_xtensa_t *as, mp_uint_t reg, mp_uint_t bit, mp_uint_t label, mp_uint_t condition) { + uint32_t dest = get_label_dest(as, label); + int32_t rel = dest - as->base.code_offset - 4; + if (as->base.pass == MP_ASM_PASS_EMIT && !SIGNED_FIT8(rel)) { + mp_raise_msg_varg(&mp_type_RuntimeError, ET_OUT_OF_RANGE, MP_QSTR_bit_branch); + } + asm_xtensa_op24(as, ASM_XTENSA_ENCODE_RRI8(7, condition | ((bit >> 4) & 0x01), reg, bit & 0x0F, rel & 0xFF)); +} + +void asm_xtensa_call0(asm_xtensa_t *as, mp_uint_t label) { + uint32_t dest = get_label_dest(as, label); + int32_t rel = dest - as->base.code_offset - 3; + if (as->base.pass == MP_ASM_PASS_EMIT) { + if ((dest & 0x03) != 0) { + mp_raise_msg_varg(&mp_type_RuntimeError, ET_NOT_ALIGNED, MP_QSTR_call0, MP_QSTR_target); + } + if ((rel & 0x03) != 0) { + mp_raise_msg_varg(&mp_type_RuntimeError, ET_NOT_ALIGNED, MP_QSTR_call0, MP_QSTR_location); + } + if (!SIGNED_FIT18(rel)) { + mp_raise_msg_varg(&mp_type_RuntimeError, ET_OUT_OF_RANGE, MP_QSTR_call0); + } + } + asm_xtensa_op_call0(as, rel); +} + +void asm_xtensa_l32r(asm_xtensa_t *as, mp_uint_t reg, mp_uint_t label) { + uint32_t dest = get_label_dest(as, label); + int32_t rel = dest - as->base.code_offset; + if (as->base.pass == MP_ASM_PASS_EMIT) { + if ((dest & 0x03) != 0) { + mp_raise_msg_varg(&mp_type_RuntimeError, ET_NOT_ALIGNED, MP_QSTR_l32r, MP_QSTR_target); + } + if ((rel & 0x03) != 0) { + mp_raise_msg_varg(&mp_type_RuntimeError, ET_NOT_ALIGNED, MP_QSTR_l32r, MP_QSTR_location); + } + if (!SIGNED_FIT18(rel) || (rel >= 0)) { + mp_raise_msg_varg(&mp_type_RuntimeError, ET_OUT_OF_RANGE, MP_QSTR_l32r); + } + } + asm_xtensa_op_l32r(as, reg, as->base.code_offset, dest); +} + #endif // MICROPY_EMIT_XTENSA || MICROPY_EMIT_INLINE_XTENSA || MICROPY_EMIT_XTENSAWIN diff --git a/py/asmxtensa.h b/py/asmxtensa.h index c3c8f225f37..1002511ddcc 100644 --- a/py/asmxtensa.h +++ b/py/asmxtensa.h @@ -64,9 +64,11 @@ #define ASM_XTENSA_REG_A14 (14) #define ASM_XTENSA_REG_A15 (15) -// for bccz +// for bccz and bcci #define ASM_XTENSA_CCZ_EQ (0) #define ASM_XTENSA_CCZ_NE (1) +#define ASM_XTENSA_CCZ_LT (2) +#define ASM_XTENSA_CCZ_GE (3) // for bcc and setcc #define ASM_XTENSA_CC_NONE (0) @@ -143,6 +145,14 @@ static inline void asm_xtensa_op_addi(asm_xtensa_t *as, uint reg_dest, uint reg_ asm_xtensa_op24(as, ASM_XTENSA_ENCODE_RRI8(2, 12, reg_src, reg_dest, imm8 & 0xff)); } +static inline void asm_xtensa_op_addx2(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, 9, reg_dest, reg_src_a, reg_src_b)); +} + +static inline void asm_xtensa_op_addx4(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, 10, reg_dest, reg_src_a, reg_src_b)); +} + static inline void asm_xtensa_op_and(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, 1, reg_dest, reg_src_a, reg_src_b)); } @@ -283,15 +293,24 @@ 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_l32i_optimised(asm_xtensa_t *as, uint reg_dest, uint reg_base, uint word_offset); -void asm_xtensa_s32i_optimised(asm_xtensa_t *as, uint reg_src, uint reg_base, uint word_offset); +void asm_xtensa_load_reg_reg_offset(asm_xtensa_t *as, uint reg_dest, uint reg_base, uint offset, uint operation_size); +void asm_xtensa_store_reg_reg_offset(asm_xtensa_t *as, uint reg_src, uint reg_base, uint offset, uint operation_size); void asm_xtensa_call_ind(asm_xtensa_t *as, uint idx); void asm_xtensa_call_ind_win(asm_xtensa_t *as, uint idx); +void asm_xtensa_bit_branch(asm_xtensa_t *as, mp_uint_t reg, mp_uint_t bit, mp_uint_t label, mp_uint_t condition); +void asm_xtensa_immediate_branch(asm_xtensa_t *as, mp_uint_t reg, mp_uint_t immediate, mp_uint_t label, mp_uint_t cond); +void asm_xtensa_call0(asm_xtensa_t *as, mp_uint_t label); +void asm_xtensa_l32r(asm_xtensa_t *as, mp_uint_t reg, mp_uint_t label); // Holds a pointer to mp_fun_table #define ASM_XTENSA_REG_FUN_TABLE ASM_XTENSA_REG_A15 #define ASM_XTENSA_REG_FUN_TABLE_WIN ASM_XTENSA_REG_A7 +// Internal temporary register (currently aliased to REG_ARG_5 for xtensa, +// and to REG_TEMP2 for xtensawin). +#define ASM_XTENSA_REG_TEMPORARY ASM_XTENSA_REG_A6 +#define ASM_XTENSA_REG_TEMPORARY_WIN ASM_XTENSA_REG_A12 + // CIRCUITPY-CHANGE: prevent #if warning #if defined(GENERIC_ASM_API) && GENERIC_ASM_API @@ -322,9 +341,9 @@ void asm_xtensa_call_ind_win(asm_xtensa_t *as, uint idx); #define ASM_NUM_REGS_SAVED ASM_XTENSA_NUM_REGS_SAVED #define REG_FUN_TABLE ASM_XTENSA_REG_FUN_TABLE -#define ASM_ENTRY(as, nlocal) asm_xtensa_entry((as), (nlocal)) -#define ASM_EXIT(as) asm_xtensa_exit((as)) -#define ASM_CALL_IND(as, idx) asm_xtensa_call_ind((as), (idx)) +#define ASM_ENTRY(as, nlocal, name) asm_xtensa_entry((as), (nlocal)) +#define ASM_EXIT(as) asm_xtensa_exit((as)) +#define ASM_CALL_IND(as, idx) asm_xtensa_call_ind((as), (idx)) #else // Configuration for windowed calls with window size 8 @@ -352,9 +371,9 @@ void asm_xtensa_call_ind_win(asm_xtensa_t *as, uint idx); #define ASM_NUM_REGS_SAVED ASM_XTENSA_NUM_REGS_SAVED_WIN #define REG_FUN_TABLE ASM_XTENSA_REG_FUN_TABLE_WIN -#define ASM_ENTRY(as, nlocal) asm_xtensa_entry_win((as), (nlocal)) -#define ASM_EXIT(as) asm_xtensa_exit_win((as)) -#define ASM_CALL_IND(as, idx) asm_xtensa_call_ind_win((as), (idx)) +#define ASM_ENTRY(as, nlocal, name) asm_xtensa_entry_win((as), (nlocal)) +#define ASM_EXIT(as) asm_xtensa_exit_win((as)) +#define ASM_CALL_IND(as, idx) asm_xtensa_call_ind_win((as), (idx)) #endif @@ -400,16 +419,53 @@ void asm_xtensa_call_ind_win(asm_xtensa_t *as, uint idx); #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)) -#define ASM_LOAD_REG_REG_OFFSET(as, reg_dest, reg_base, word_offset) asm_xtensa_l32i_optimised((as), (reg_dest), (reg_base), (word_offset)) -#define ASM_LOAD8_REG_REG(as, reg_dest, reg_base) asm_xtensa_op_l8ui((as), (reg_dest), (reg_base), 0) -#define ASM_LOAD16_REG_REG(as, reg_dest, reg_base) asm_xtensa_op_l16ui((as), (reg_dest), (reg_base), 0) -#define ASM_LOAD16_REG_REG_OFFSET(as, reg_dest, reg_base, uint16_offset) asm_xtensa_op_l16ui((as), (reg_dest), (reg_base), (uint16_offset)) -#define ASM_LOAD32_REG_REG(as, reg_dest, reg_base) asm_xtensa_op_l32i_n((as), (reg_dest), (reg_base), 0) +#define ASM_LOAD_REG_REG_OFFSET(as, reg_dest, reg_base, word_offset) ASM_LOAD32_REG_REG_OFFSET((as), (reg_dest), (reg_base), (word_offset)) +#define ASM_LOAD8_REG_REG(as, reg_dest, reg_base) ASM_LOAD8_REG_REG_OFFSET((as), (reg_dest), (reg_base), 0) +#define ASM_LOAD8_REG_REG_OFFSET(as, reg_dest, reg_base, byte_offset) asm_xtensa_load_reg_reg_offset((as), (reg_dest), (reg_base), (byte_offset), 0) +#define ASM_LOAD8_REG_REG_REG(as, reg_dest, reg_base, reg_index) \ + do { \ + asm_xtensa_op_add_n((as), (reg_base), (reg_index), (reg_base)); \ + asm_xtensa_op_l8ui((as), (reg_dest), (reg_base), 0); \ + } while (0) +#define ASM_LOAD16_REG_REG(as, reg_dest, reg_base) ASM_LOAD16_REG_REG_OFFSET((as), (reg_dest), (reg_base), 0) +#define ASM_LOAD16_REG_REG_OFFSET(as, reg_dest, reg_base, halfword_offset) asm_xtensa_load_reg_reg_offset((as), (reg_dest), (reg_base), (halfword_offset), 1) +#define ASM_LOAD16_REG_REG_REG(as, reg_dest, reg_base, reg_index) \ + do { \ + asm_xtensa_op_addx2((as), (reg_base), (reg_index), (reg_base)); \ + asm_xtensa_op_l16ui((as), (reg_dest), (reg_base), 0); \ + } while (0) +#define ASM_LOAD32_REG_REG(as, reg_dest, reg_base) ASM_LOAD32_REG_REG_OFFSET((as), (reg_dest), (reg_base), 0) +#define ASM_LOAD32_REG_REG_OFFSET(as, reg_dest, reg_base, word_offset) asm_xtensa_load_reg_reg_offset((as), (reg_dest), (reg_base), (word_offset), 2) +#define ASM_LOAD32_REG_REG_REG(as, reg_dest, reg_base, reg_index) \ + do { \ + asm_xtensa_op_addx4((as), (reg_base), (reg_index), (reg_base)); \ + asm_xtensa_op_l32i_n((as), (reg_dest), (reg_base), 0); \ + } while (0) + +#define ASM_STORE_REG_REG_OFFSET(as, reg_dest, reg_base, word_offset) ASM_STORE32_REG_REG_OFFSET((as), (reg_dest), (reg_base), (word_offset)) +#define ASM_STORE8_REG_REG(as, reg_src, reg_base) ASM_STORE8_REG_REG_OFFSET((as), (reg_src), (reg_base), 0) +#define ASM_STORE8_REG_REG_OFFSET(as, reg_src, reg_base, byte_offset) asm_xtensa_store_reg_reg_offset((as), (reg_src), (reg_base), (byte_offset), 0) +#define ASM_STORE8_REG_REG_REG(as, reg_val, reg_base, reg_index) \ + do { \ + asm_xtensa_op_add_n((as), (reg_base), (reg_index), (reg_base)); \ + asm_xtensa_op_s8i((as), (reg_val), (reg_base), 0); \ + } while (0) +#define ASM_STORE16_REG_REG(as, reg_src, reg_base) ASM_STORE16_REG_REG_OFFSET((as), (reg_src), (reg_base), 0) +#define ASM_STORE16_REG_REG_OFFSET(as, reg_src, reg_base, halfword_offset) asm_xtensa_store_reg_reg_offset((as), (reg_src), (reg_base), (halfword_offset), 1) +#define ASM_STORE16_REG_REG_REG(as, reg_val, reg_base, reg_index) \ + do { \ + asm_xtensa_op_addx2((as), (reg_base), (reg_index), (reg_base)); \ + asm_xtensa_op_s16i((as), (reg_val), (reg_base), 0); \ + } while (0) +#define ASM_STORE32_REG_REG(as, reg_src, reg_base) ASM_STORE32_REG_REG_OFFSET((as), (reg_src), (reg_base), 0) +#define ASM_STORE32_REG_REG_OFFSET(as, reg_dest, reg_base, word_offset) asm_xtensa_store_reg_reg_offset((as), (reg_dest), (reg_base), (word_offset), 2) +#define ASM_STORE32_REG_REG_REG(as, reg_val, reg_base, reg_index) \ + do { \ + asm_xtensa_op_addx4((as), (reg_base), (reg_index), (reg_base)); \ + asm_xtensa_op_s32i_n((as), (reg_val), (reg_base), 0); \ + } while (0) -#define ASM_STORE_REG_REG_OFFSET(as, reg_dest, reg_base, word_offset) asm_xtensa_s32i_optimised((as), (reg_dest), (reg_base), (word_offset)) -#define ASM_STORE8_REG_REG(as, reg_src, reg_base) asm_xtensa_op_s8i((as), (reg_src), (reg_base), 0) -#define ASM_STORE16_REG_REG(as, reg_src, reg_base) asm_xtensa_op_s16i((as), (reg_src), (reg_base), 0) -#define ASM_STORE32_REG_REG(as, reg_src, reg_base) asm_xtensa_op_s32i_n((as), (reg_src), (reg_base), 0) +#define ASM_CLR_REG(as, reg_dest) asm_xtensa_op_movi_n((as), (reg_dest), 0) #endif // GENERIC_ASM_API diff --git a/py/bc.c b/py/bc.c index c2956030e38..fcd8d8e1337 100644 --- a/py/bc.c +++ b/py/bc.c @@ -88,7 +88,7 @@ const byte *mp_decode_uint_skip(const byte *ptr) { return ptr; } -static NORETURN void fun_pos_args_mismatch(mp_obj_fun_bc_t *f, size_t expected, size_t given) { +static MP_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 // generic message, used also for other argument issues (void)f; @@ -104,7 +104,7 @@ static NORETURN void fun_pos_args_mismatch(mp_obj_fun_bc_t *f, size_t expected, // CIRCUITPY-CHANGE: more specific mp_raise routine mp_raise_TypeError_varg( MP_ERROR_TEXT("%q() takes %d positional arguments but %d were given"), - mp_obj_fun_get_name(MP_OBJ_FROM_PTR(f)), expected, given); + mp_obj_fun_bc_get_name(f), expected, given); #endif } @@ -336,7 +336,7 @@ void mp_setup_code_state(mp_code_state_t *code_state, size_t n_args, size_t n_kw mp_setup_code_state_helper(code_state, n_args, n_kw, args); } -#if MICROPY_EMIT_NATIVE +#if MICROPY_ENABLE_NATIVE_CODE // On entry code_state should be allocated somewhere (stack/heap) and // contain the following valid entries: // - code_state->fun_bc should contain a pointer to the function object diff --git a/py/bc.h b/py/bc.h index 007897a028e..3b7a6fe1c96 100644 --- a/py/bc.h +++ b/py/bc.h @@ -226,6 +226,7 @@ typedef struct _mp_compiled_module_t { bool has_native; size_t n_qstr; size_t n_obj; + size_t arch_flags; #endif } mp_compiled_module_t; @@ -302,37 +303,49 @@ static inline void mp_module_context_alloc_tables(mp_module_context_t *context, #if MICROPY_EMIT_BYTECODE_USES_QSTR_TABLE size_t nq = (n_qstr * sizeof(qstr_short_t) + sizeof(mp_uint_t) - 1) / sizeof(mp_uint_t); size_t no = n_obj; - mp_uint_t *mem = m_new(mp_uint_t, nq + no); + // CIRCUITPY-CHANGE + mp_uint_t *mem = (mp_uint_t *)m_malloc_items(nq + no); context->constants.qstr_table = (qstr_short_t *)mem; context->constants.obj_table = (mp_obj_t *)(mem + nq); #else if (n_obj == 0) { context->constants.obj_table = NULL; } else { - context->constants.obj_table = m_new(mp_obj_t, n_obj); + // CIRCUITPY-CHANGE + context->constants.obj_table = m_malloc_items(n_obj); } #endif } +typedef struct _mp_code_lineinfo_t { + size_t bc_increment; + size_t line_increment; +} mp_code_lineinfo_t; + +static inline mp_code_lineinfo_t mp_bytecode_decode_lineinfo(const byte **line_info) { + mp_code_lineinfo_t result; + size_t c = (*line_info)[0]; + if ((c & 0x80) == 0) { + // 0b0LLBBBBB encoding + result.bc_increment = c & 0x1f; + result.line_increment = c >> 5; + *line_info += 1; + } else { + // 0b1LLLBBBB 0bLLLLLLLL encoding (l's LSB in second byte) + result.bc_increment = c & 0xf; + result.line_increment = ((c << 4) & 0x700) | (*line_info)[1]; + *line_info += 2; + } + return result; +} + static inline size_t mp_bytecode_get_source_line(const byte *line_info, const byte *line_info_top, size_t bc_offset) { size_t source_line = 1; while (line_info < line_info_top) { - size_t c = *line_info; - size_t b, l; - if ((c & 0x80) == 0) { - // 0b0LLBBBBB encoding - b = c & 0x1f; - l = c >> 5; - line_info += 1; - } else { - // 0b1LLLBBBB 0bLLLLLLLL encoding (l's LSB in second byte) - b = c & 0xf; - l = ((c << 4) & 0x700) | line_info[1]; - line_info += 2; - } - if (bc_offset >= b) { - bc_offset -= b; - source_line += l; + mp_code_lineinfo_t decoded = mp_bytecode_decode_lineinfo(&line_info); + if (bc_offset >= decoded.bc_increment) { + bc_offset -= decoded.bc_increment; + source_line += decoded.line_increment; } else { // found source line corresponding to bytecode offset break; diff --git a/py/binary.c b/py/binary.c index 75dfc19925f..1ef38d5b3b1 100644 --- a/py/binary.c +++ b/py/binary.c @@ -42,6 +42,12 @@ #define alignof(type) offsetof(struct { char c; type t; }, t) #endif +// MicroPython V1.x truncates integers when writing into arrays, +// MicroPython V2 will raise OverflowError in these cases, same as CPython +// CIRCUITPY-CHANGE: CircuitPython raises OverflowError like CPython, +// rather than truncating like MicroPython V1.x. +#define OVERFLOW_CHECKS (1) + size_t mp_binary_get_size(char struct_type, char val_type, size_t *palign) { size_t size = 0; int align = 1; @@ -71,8 +77,7 @@ size_t mp_binary_get_size(char struct_type, char val_type, size_t *palign) { case 'Q': size = 8; break; - // CIRCUITPY-CHANGE: non-standard typecodes can be turned off - #if MICROPY_NONSTANDARD_TYPECODES + #if MICROPY_PY_STRUCT_UNSAFE_TYPECODES case 'P': case 'O': case 'S': @@ -86,10 +91,13 @@ size_t mp_binary_get_size(char struct_type, char val_type, size_t *palign) { // CIRCUITPY-CHANGE: compiler determines size size = sizeof(float); break; + // CIRCUITPY-CHANGE: 'd' is optional + #if MICROPY_PY_DOUBLE_TYPECODE case 'd': // CIRCUITPY-CHANGE: compiler determines size size = sizeof(double); break; + #endif } break; case '@': { @@ -128,8 +136,7 @@ size_t mp_binary_get_size(char struct_type, char val_type, size_t *palign) { align = alignof(long long); size = sizeof(long long); break; - // CIRCUITPY-CHANGE: non-standard typecodes can be turned off - #if MICROPY_NONSTANDARD_TYPECODES + #if MICROPY_PY_STRUCT_UNSAFE_TYPECODES case 'P': case 'O': case 'S': @@ -145,10 +152,13 @@ size_t mp_binary_get_size(char struct_type, char val_type, size_t *palign) { align = alignof(float); size = sizeof(float); break; + // CIRCUITPY-CHANGE: 'd' is optional + #if MICROPY_PY_DOUBLE_TYPECODE case 'd': align = alignof(double); size = sizeof(double); break; + #endif } } } @@ -208,7 +218,7 @@ static float mp_decode_half_float(uint16_t hf) { ++e; } - fpu.i = ((hf & 0x8000) << 16) | (e << 23) | (m << 13); + fpu.i = ((hf & 0x8000u) << 16) | (e << 23) | (m << 13); return fpu.f; } @@ -289,18 +299,20 @@ mp_obj_t mp_binary_get_val_array(char typecode, void *p, size_t index) { #if MICROPY_PY_BUILTINS_FLOAT case 'f': return mp_obj_new_float_from_f(((float *)p)[index]); + // CIRCUITPY-CHANGE: 'd' is optional + #if MICROPY_PY_DOUBLE_TYPECODE case 'd': return mp_obj_new_float_from_d(((double *)p)[index]); #endif - // CIRCUITPY-CHANGE: non-standard typecodes can be turned off - #if MICROPY_NONSTANDARD_TYPECODES - // Extension to CPython: array of objects + #endif + // Extension to CPython: array of objects + #if MICROPY_PY_STRUCT_UNSAFE_TYPECODES case 'O': 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 + #endif } return MP_OBJ_NEW_SMALL_INT(val); } @@ -350,14 +362,11 @@ mp_obj_t mp_binary_get_val(char struct_type, char val_type, byte *p_base, byte * long long val = mp_binary_get_int(size, is_signed(val_type), (struct_type == '>'), p); - // CIRCUITPY-CHANGE: non-standard typecodes can be turned off - if (MICROPY_NONSTANDARD_TYPECODES && (val_type == 'O')) { + if (MICROPY_PY_STRUCT_UNSAFE_TYPECODES && val_type == 'O') { return (mp_obj_t)(mp_uint_t)val; - #if MICROPY_NONSTANDARD_TYPECODES - } else if (val_type == 'S') { + } else if (MICROPY_PY_STRUCT_UNSAFE_TYPECODES && val_type == 'S') { const char *s_val = (const char *)(uintptr_t)(mp_uint_t)val; - return mp_obj_new_str(s_val, strlen(s_val)); - #endif + return mp_obj_new_str_from_cstr(s_val); #if MICROPY_PY_BUILTINS_FLOAT } else if (val_type == 'e') { return mp_obj_new_float_from_f(mp_decode_half_float(val)); @@ -367,6 +376,8 @@ mp_obj_t mp_binary_get_val(char struct_type, char val_type, byte *p_base, byte * float f; } fpu = {val}; return mp_obj_new_float_from_f(fpu.f); + // CIRCUITPY-CHANGE: 'd' is optional + #if MICROPY_PY_DOUBLE_TYPECODE } else if (val_type == 'd') { union { uint64_t i; @@ -374,6 +385,7 @@ mp_obj_t mp_binary_get_val(char struct_type, char val_type, byte *p_base, byte * } fpu = {val}; return mp_obj_new_float_from_d(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); @@ -389,7 +401,21 @@ mp_obj_t mp_binary_get_val(char struct_type, char val_type, byte *p_base, byte * } } -void mp_binary_set_int(size_t val_sz, bool big_endian, byte *dest, mp_uint_t val) { +void mp_binary_set_int(size_t dest_sz, byte *dest, size_t val_sz, mp_uint_t val, bool big_endian) { + if (dest_sz > val_sz) { + // zero/sign extension if needed + int c = ((mp_int_t)val < 0) ? 0xff : 0x00; + memset(dest, c, dest_sz); + + // big endian: write val_sz bytes at end of 'dest' + if (big_endian) { + dest += dest_sz - val_sz; + } + } else if (dest_sz < val_sz) { + // truncate 'val' into 'dest' + val_sz = dest_sz; + } + if (MP_ENDIANNESS_LITTLE && !big_endian) { memcpy(dest, &val, val_sz); } else if (MP_ENDIANNESS_BIG && big_endian) { @@ -426,8 +452,7 @@ void mp_binary_set_val(char struct_type, char val_type, mp_obj_t val_in, byte *p mp_uint_t val; switch (val_type) { - // CIRCUITPY-CHANGE: non-standard typecodes can be turned off - #if MICROPY_NONSTANDARD_TYPECODES + #if MICROPY_PY_STRUCT_UNSAFE_TYPECODES case 'O': val = (mp_uint_t)val_in; break; @@ -445,6 +470,8 @@ void mp_binary_set_val(char struct_type, char val_type, mp_obj_t val_in, byte *p val = fp_sp.i; break; } + // CIRCUITPY-CHANGE + #if MICROPY_PY_DOUBLE_TYPECODE case 'd': { union { uint64_t i64; @@ -456,134 +483,159 @@ void mp_binary_set_val(char struct_type, char val_type, mp_obj_t val_in, byte *p val = fp_dp.i64; } else { int be = struct_type == '>'; - mp_binary_set_int(sizeof(uint32_t), be, p, fp_dp.i32[MP_ENDIANNESS_BIG ^ be]); + mp_binary_set_int(sizeof(uint32_t), p, sizeof(uint32_t), fp_dp.i32[MP_ENDIANNESS_BIG ^ be], be); + // Now fall through and copy the second word, below p += sizeof(uint32_t); + size = sizeof(uint32_t); val = fp_dp.i32[MP_ENDIANNESS_LITTLE ^ be]; } break; } #endif - default: { - // CIRCUITPY-CHANGE: add overflow checks - bool signed_type = is_signed(val_type); + #endif + default: + // Typecode is a standard integer #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE if (mp_obj_is_exact_type(val_in, &mp_type_int)) { - // It's a longint. - mp_obj_int_buffer_overflow_check(val_in, size, signed_type); - mp_obj_int_to_bytes_impl(val_in, struct_type == '>', size, p); + #if !OVERFLOW_CHECKS + if (size <= sizeof(mp_uint_t)) { + // Aligned store; byte-wise path corrupts word-only registers. + val = mp_obj_int_get_truncated(val_in); + break; + } + #endif + mp_obj_int_to_bytes(val_in, size, p, struct_type == '>', is_signed(val_type), OVERFLOW_CHECKS); return; } #endif - // CIRCUITPY-CHANGE: add overflow checks - { - val = mp_obj_get_int(val_in); - // Small int checking is separate, to be fast. - mp_small_int_buffer_overflow_check(val, size, signed_type); - // zero/sign extend if needed - if (MP_BYTES_PER_OBJ_WORD < 8 && size > sizeof(val)) { - int c = (is_signed(val_type) && (mp_int_t)val < 0) ? 0xff : 0x00; - memset(p, c, size); - if (struct_type == '>') { - p += size - sizeof(val); - } - } - break; - } - } + val = mp_obj_get_int(val_in); + #if OVERFLOW_CHECKS + // CIRCUITPY-CHANGE: small ints are checked too. + mp_small_int_buffer_overflow_check(val, size, is_signed(val_type)); + #endif + break; // Fall through to mp_binary_set_int } - mp_binary_set_int(MIN((size_t)size, sizeof(val)), struct_type == '>', p, val); + mp_binary_set_int(size, p, sizeof(val), val, struct_type == '>'); } +static void mp_binary_set_val_array_from_int(char typecode, void *p, size_t index, mp_int_t val); + void mp_binary_set_val_array(char typecode, void *p, size_t index, mp_obj_t val_in) { switch (typecode) { #if MICROPY_PY_BUILTINS_FLOAT case 'f': ((float *)p)[index] = mp_obj_get_float_to_f(val_in); break; + // CIRCUITPY-CHANGE: 'd' is optional + #if MICROPY_PY_DOUBLE_TYPECODE case 'd': ((double *)p)[index] = mp_obj_get_float_to_d(val_in); break; #endif - // CIRCUITPY-CHANGE: non-standard typecodes can be turned off - #if MICROPY_NONSTANDARD_TYPECODES + #endif + #if MICROPY_PY_STRUCT_UNSAFE_TYPECODES // Extension to CPython: array of objects case 'O': ((mp_obj_t *)p)[index] = val_in; break; #endif - default: { - // CIRCUITPY-CHANGE: add overflow checks - size_t size = mp_binary_get_size('@', typecode, NULL); - bool signed_type = is_signed(typecode); - + // In all remaining cases the type code is an integer + default: #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE if (mp_obj_is_exact_type(val_in, &mp_type_int)) { - // 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_t size = mp_binary_get_size('@', typecode, NULL); + #if !OVERFLOW_CHECKS + if (size <= sizeof(mp_int_t)) { + // Aligned store; byte-wise path corrupts word-only registers. + mp_binary_set_val_array_from_int(typecode, p, index, + mp_obj_int_get_truncated(val_in)); + return; + } + #endif + p = (uint8_t *)p + index * size; + byte *dest; + #if OVERFLOW_CHECKS + // If mp_obj_int_to_bytes() might overflow then need to write into a temporary buffer first + assert(size <= sizeof(uint64_t)); + uint64_t temp_buf; + dest = (uint8_t *)&temp_buf; + #else + dest = p; + #endif + mp_obj_int_to_bytes(val_in, size, dest, MP_ENDIANNESS_BIG, is_signed(typecode), OVERFLOW_CHECKS); + #if OVERFLOW_CHECKS + memcpy(p, dest, size); + #endif return; } #endif - // CIRCUITPY-CHANGE: add overflow checks - mp_int_t val = mp_obj_get_int(val_in); - // Small int checking is separate, to be fast. - mp_small_int_buffer_overflow_check(val, size, signed_type); - mp_binary_set_val_array_from_int(typecode, p, index, val); - } + mp_binary_set_val_array_from_int(typecode, p, index, mp_obj_get_int(val_in)); } } -void mp_binary_set_val_array_from_int(char typecode, void *p, size_t index, mp_int_t val) { +#if OVERFLOW_CHECKS +#define SET_VAL_AS(TYPE, IS_SIGNED) do { \ + TYPE tmp = val; \ + if ((mp_int_t)tmp == val && (IS_SIGNED || val >= 0)) { \ + ((TYPE *)p)[index] = tmp; \ + } else { \ + goto raise; \ + } \ +} while (0) +#else +#define SET_VAL_AS(TYPE, _IS_SIGNED) do { \ + ((TYPE *)p)[index] = val; \ +} while (0) +#endif + +static void mp_binary_set_val_array_from_int(char typecode, void *p, size_t index, mp_int_t val) { switch (typecode) { case 'b': - ((signed char *)p)[index] = val; + SET_VAL_AS(signed char, true); break; case BYTEARRAY_TYPECODE: case 'B': - ((unsigned char *)p)[index] = val; + SET_VAL_AS(unsigned char, false); break; case 'h': - ((short *)p)[index] = val; + SET_VAL_AS(short, true); break; case 'H': - ((unsigned short *)p)[index] = val; + SET_VAL_AS(unsigned short, false); break; case 'i': - ((int *)p)[index] = val; + SET_VAL_AS(int, true); break; case 'I': - ((unsigned int *)p)[index] = val; + SET_VAL_AS(unsigned int, false); break; case 'l': - ((long *)p)[index] = val; + SET_VAL_AS(long, true); break; case 'L': - ((unsigned long *)p)[index] = val; + SET_VAL_AS(unsigned long, false); break; #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE case 'q': - ((long long *)p)[index] = val; + SET_VAL_AS(long long, true); break; case 'Q': - ((unsigned long long *)p)[index] = val; + SET_VAL_AS(unsigned long long, false); break; #endif - #if MICROPY_PY_BUILTINS_FLOAT - case 'f': - ((float *)p)[index] = (float)val; - break; - case 'd': - ((double *)p)[index] = (double)val; - break; - #endif - // CIRCUITPY-CHANGE: non-standard typecodes can be turned off - #if MICROPY_NONSTANDARD_TYPECODES - // Extension to CPython: array of pointers + // Extension to CPython: array of pointers + #if MICROPY_PY_STRUCT_UNSAFE_TYPECODES case 'P': ((void **)p)[index] = (void *)(uintptr_t)val; break; - #endif + #endif } + + return; + + #if OVERFLOW_CHECKS +raise: + mp_raise_msg(&mp_type_OverflowError, MP_ERROR_TEXT("integer out of range")); + #endif } diff --git a/py/binary.h b/py/binary.h index 5c645bcaaa9..851dc50110e 100644 --- a/py/binary.h +++ b/py/binary.h @@ -37,10 +37,9 @@ size_t mp_binary_get_size(char struct_type, char val_type, size_t *palign); mp_obj_t mp_binary_get_val_array(char typecode, void *p, size_t index); void mp_binary_set_val_array(char typecode, void *p, size_t index, mp_obj_t val_in); -void mp_binary_set_val_array_from_int(char typecode, void *p, size_t index, mp_int_t val); mp_obj_t mp_binary_get_val(char struct_type, char val_type, byte *p_base, byte **ptr); void mp_binary_set_val(char struct_type, char val_type, mp_obj_t val_in, byte *p_base, byte **ptr); long long mp_binary_get_int(size_t size, bool is_signed, bool big_endian, const byte *src); -void mp_binary_set_int(size_t val_sz, bool big_endian, byte *dest, mp_uint_t val); +void mp_binary_set_int(size_t dest_sz, byte *dest, size_t val_sz, mp_uint_t val, bool big_endian); #endif // MICROPY_INCLUDED_PY_BINARY_H diff --git a/py/builtin.h b/py/builtin.h index 81d0789802b..388bc847005 100644 --- a/py/builtin.h +++ b/py/builtin.h @@ -126,6 +126,8 @@ MP_DECLARE_CONST_FUN_OBJ_2(mp_op_getitem_obj); MP_DECLARE_CONST_FUN_OBJ_3(mp_op_setitem_obj); MP_DECLARE_CONST_FUN_OBJ_2(mp_op_delitem_obj); +MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(mp_sys_exit_obj); + // Modules needed by the runtime. extern const mp_obj_dict_t mp_module_builtins_globals; extern const mp_obj_module_t mp_module___main__; @@ -136,6 +138,7 @@ extern const mp_obj_module_t mp_module_sys; extern const mp_obj_module_t mp_module_errno; extern const mp_obj_module_t mp_module_uctypes; extern const mp_obj_module_t mp_module_machine; +extern const mp_obj_module_t mp_module_math; extern const char MICROPY_PY_BUILTINS_HELP_TEXT[]; diff --git a/py/builtinevex.c b/py/builtinevex.c index e25cbd4d085..74a46404926 100644 --- a/py/builtinevex.c +++ b/py/builtinevex.c @@ -26,6 +26,7 @@ #include +#include "py/objcode.h" #include "py/objfun.h" #include "py/compile.h" #include "py/runtime.h" @@ -33,17 +34,6 @@ #if MICROPY_PY_BUILTINS_COMPILE -typedef struct _mp_obj_code_t { - mp_obj_base_t base; - mp_obj_t module_fun; -} mp_obj_code_t; - -static MP_DEFINE_CONST_OBJ_TYPE( - mp_type_code, - MP_QSTR_code, - MP_TYPE_FLAG_NONE - ); - static mp_obj_t code_execute(mp_obj_code_t *self, mp_obj_dict_t *globals, mp_obj_dict_t *locals) { // save context nlr_jump_callback_node_globals_locals_t ctx; @@ -57,19 +47,28 @@ static mp_obj_t code_execute(mp_obj_code_t *self, mp_obj_dict_t *globals, mp_obj // set exception handler to restore context if an exception is raised nlr_push_jump_callback(&ctx.callback, mp_globals_locals_set_from_nlr_jump_callback); + #if MICROPY_PY_BUILTINS_CODE >= MICROPY_PY_BUILTINS_CODE_BASIC + mp_module_context_t *module_context = m_new_obj(mp_module_context_t); + module_context->module.base.type = &mp_type_module; + module_context->module.globals = globals; + module_context->constants = *mp_code_get_constants(self); + mp_obj_t module_fun = mp_make_function_from_proto_fun(mp_code_get_proto_fun(self), module_context, NULL); + #else // The call to mp_parse_compile_execute() in mp_builtin_compile() below passes // NULL for the globals, so repopulate that entry now with the correct globals. + mp_obj_t module_fun = self->module_fun; if (mp_obj_is_type(self->module_fun, &mp_type_fun_bc) #if MICROPY_EMIT_NATIVE || mp_obj_is_type(self->module_fun, &mp_type_fun_native) #endif ) { - mp_obj_fun_bc_t *fun_bc = MP_OBJ_TO_PTR(self->module_fun); + mp_obj_fun_bc_t *fun_bc = MP_OBJ_TO_PTR(module_fun); ((mp_module_context_t *)fun_bc->context)->module.globals = globals; } + #endif // execute code - mp_obj_t ret = mp_call_function_0(self->module_fun); + mp_obj_t ret = mp_call_function_0(module_fun); // deregister exception handler and restore context nlr_pop_jump_callback(true); @@ -108,9 +107,29 @@ static mp_obj_t mp_builtin_compile(size_t n_args, const mp_obj_t *args) { mp_raise_ValueError(MP_ERROR_TEXT("bad compile mode")); } - mp_obj_code_t *code = mp_obj_malloc(mp_obj_code_t, &mp_type_code); - code->module_fun = mp_parse_compile_execute(lex, parse_input_kind, NULL, NULL); - return MP_OBJ_FROM_PTR(code); + #if MICROPY_PY_BUILTINS_CODE >= MICROPY_PY_BUILTINS_CODE_BASIC + + mp_parse_tree_t parse_tree = mp_parse(lex, parse_input_kind); + mp_module_context_t ctx; + ctx.module.globals = NULL; + mp_compiled_module_t cm; + cm.context = &ctx; + mp_compile_to_raw_code(&parse_tree, lex->source_name, parse_input_kind == MP_PARSE_SINGLE_INPUT, &cm); + + #if MICROPY_PY_BUILTINS_CODE >= MICROPY_PY_BUILTINS_CODE_FULL + mp_module_context_t *ctx_ptr = m_new_obj(mp_module_context_t); + *ctx_ptr = ctx; + return mp_obj_new_code(ctx_ptr, cm.rc, true); + #else + return mp_obj_new_code(ctx.constants, cm.rc); + #endif + + #else + + mp_obj_t module_fun = mp_parse_compile_execute(lex, parse_input_kind, NULL, NULL); + return mp_obj_new_code(module_fun); + + #endif } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin_compile_obj, 3, 6, mp_builtin_compile); diff --git a/py/builtinhelp.c b/py/builtinhelp.c index d041d6915a6..d3d7aa402c8 100644 --- a/py/builtinhelp.c +++ b/py/builtinhelp.c @@ -31,10 +31,19 @@ #include "genhdr/mpversion.h" #include "py/builtin.h" #include "py/mpconfig.h" +#include "py/objlist.h" #include "py/objmodule.h" #if MICROPY_PY_BUILTINS_HELP +#if MICROPY_PY_BUILTINS_HELP_NUM_COLUMNS <= 0 +#error "MICROPY_PY_BUILTINS_HELP_NUM_COLUMNS must be more than 0" +#endif + +#if MICROPY_PY_BUILTINS_HELP_COLUMN_WIDTH <= 0 +#error "MICROPY_PY_BUILTINS_HELP_COLUMN_WIDTH must be more than 0" +#endif + const char mp_help_default_text[] = "Welcome to MicroPython!\n" "\n" @@ -98,12 +107,10 @@ static void mp_help_print_modules(void) { 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) - #define COLUMN_WIDTH (18) size_t len; mp_obj_t *items; mp_obj_list_get(list, &len, &items); - unsigned int num_rows = (len + NUM_COLUMNS - 1) / NUM_COLUMNS; + unsigned int num_rows = (len + MICROPY_PY_BUILTINS_HELP_NUM_COLUMNS - 1) / MICROPY_PY_BUILTINS_HELP_NUM_COLUMNS; for (unsigned int i = 0; i < num_rows; ++i) { unsigned int j = i; for (;;) { @@ -112,9 +119,9 @@ static void mp_help_print_modules(void) { if (j >= len) { break; } - int gap = COLUMN_WIDTH - l; + int gap = MICROPY_PY_BUILTINS_HELP_COLUMN_WIDTH - l; while (gap < 1) { - gap += COLUMN_WIDTH; + gap += MICROPY_PY_BUILTINS_HELP_COLUMN_WIDTH; } while (gap--) { mp_print_str(MP_PYTHON_PRINTER, " "); @@ -162,9 +169,8 @@ static void mp_help_print_obj(const mp_obj_t obj) { } if (map != NULL) { for (uint i = 0; i < map->alloc; i++) { - mp_obj_t key = map->table[i].key; - if (key != MP_OBJ_NULL) { - mp_help_print_info_about_object(key, map->table[i].value); + if (mp_map_slot_is_filled(map, i)) { + mp_help_print_info_about_object(map->table[i].key, map->table[i].value); } } } diff --git a/py/builtinimport.c b/py/builtinimport.c index 17b3f11c4a0..681ce1458d3 100644 --- a/py/builtinimport.c +++ b/py/builtinimport.c @@ -77,20 +77,39 @@ static mp_import_stat_t stat_path(vstr_t *path) { // argument. This is the logic that makes .py files take precedent over .mpy // files. This uses stat_path above, rather than mp_import_stat directly, so // that the .frozen path prefix is handled. +// CIRCUITPY-CHANGE: builds that can load native code also try ..mpy +// between .py and .mpy. static mp_import_stat_t stat_file_py_or_mpy(vstr_t *path) { mp_import_stat_t stat = stat_path(path); if (stat == MP_IMPORT_STAT_FILE) { return stat; } + #if MICROPY_PERSISTENT_CODE_LOAD || MICROPY_PERSISTENT_CODE_LOAD_NATIVE + size_t base_len = path->len - 3; // drop ".py" + #endif + + #if MICROPY_PERSISTENT_CODE_LOAD_NATIVE + // CIRCUITPY-CHANGE: try '..mpy' first, where is the mpy-cross -march + // name of this build. path is a fixed MICROPY_ALLOC_PATH_MAX buffer, so skip the + // probe when the longer name (plus NUL) would not fit rather than let vstr raise. + if (base_len + sizeof("." MPY_FEATURE_ARCH_NAME ".mpy") <= path->alloc) { + path->len = base_len; + vstr_add_str(path, "." MPY_FEATURE_ARCH_NAME ".mpy"); + if (stat_path(path) == MP_IMPORT_STAT_FILE) { + return MP_IMPORT_STAT_FILE; + } + } + #endif + #if MICROPY_PERSISTENT_CODE_LOAD - // Didn't find .py -- try the .mpy instead by inserting an 'm' into the '.py'. + // Didn't find .py -- try the .mpy instead. // Note: There's no point doing this if it's a frozen path, but adding the check // would be extra code, and no harm letting mp_find_frozen_module fail instead. - vstr_ins_byte(path, path->len - 2, 'm'); - stat = stat_path(path); - if (stat == MP_IMPORT_STAT_FILE) { - return stat; + path->len = base_len; + vstr_add_str(path, ".mpy"); + if (stat_path(path) == MP_IMPORT_STAT_FILE) { + return MP_IMPORT_STAT_FILE; } #endif @@ -105,7 +124,26 @@ static mp_import_stat_t stat_module(vstr_t *path) { mp_import_stat_t stat = stat_path(path); DEBUG_printf("stat %s: %d\n", vstr_str(path), stat); if (stat == MP_IMPORT_STAT_DIR) { - return stat; + // CIRCUITPY-CHANGE: match CPython import precedence. A regular + // package (directory with __init__.py/.mpy) takes precedence, then a + // sibling .py/.mpy module, and only then a namespace package + // (directory without __init__). See + // https://docs.python.org/3/reference/import.html#regular-packages + size_t orig_len = path->len; + vstr_add_str(path, PATH_SEP_CHAR "__init__.py"); + mp_import_stat_t init_stat = stat_file_py_or_mpy(path); + path->len = orig_len; + if (init_stat == MP_IMPORT_STAT_FILE) { + return MP_IMPORT_STAT_DIR; + } + + vstr_add_str(path, ".py"); + mp_import_stat_t file_stat = stat_file_py_or_mpy(path); + if (file_stat == MP_IMPORT_STAT_FILE) { + return file_stat; + } + path->len = orig_len; + return MP_IMPORT_STAT_DIR; } // Not a directory, add .py and try as a file. @@ -118,7 +156,7 @@ static mp_import_stat_t stat_module(vstr_t *path) { // path (i.e. "/mod_name(.py)"). static mp_import_stat_t stat_top_level(qstr mod_name, vstr_t *dest) { DEBUG_printf("stat_top_level: '%s'\n", qstr_str(mod_name)); - #if MICROPY_PY_SYS + #if MICROPY_PY_SYS && MICROPY_PY_SYS_PATH size_t path_num; mp_obj_t *path_items; mp_obj_get_array(mp_sys_path, &path_num, &path_items); @@ -155,7 +193,7 @@ static mp_import_stat_t stat_top_level(qstr mod_name, vstr_t *dest) { #if MICROPY_MODULE_FROZEN_STR || MICROPY_ENABLE_COMPILER static void do_load_from_lexer(mp_module_context_t *context, mp_lexer_t *lex) { - #if MICROPY_PY___FILE__ + #if MICROPY_MODULE___FILE__ qstr source_name = lex->source_name; mp_store_attr(MP_OBJ_FROM_PTR(&context->module), MP_QSTR___file__, MP_OBJ_NEW_QSTR(source_name)); #endif @@ -168,7 +206,7 @@ static void do_load_from_lexer(mp_module_context_t *context, mp_lexer_t *lex) { #if (MICROPY_HAS_FILE_READER && MICROPY_PERSISTENT_CODE_LOAD) || MICROPY_MODULE_FROZEN_MPY static void do_execute_proto_fun(const mp_module_context_t *context, mp_proto_fun_t proto_fun, qstr source_name) { - #if MICROPY_PY___FILE__ + #if MICROPY_MODULE___FILE__ mp_store_attr(MP_OBJ_FROM_PTR(&context->module), MP_QSTR___file__, MP_OBJ_NEW_QSTR(source_name)); #else (void)source_name; @@ -227,7 +265,7 @@ static void do_load(mp_module_context_t *module_obj, vstr_t *file) { if (frozen_type == MP_FROZEN_MPY) { const mp_frozen_module_t *frozen = modref; module_obj->constants = frozen->constants; - #if MICROPY_PY___FILE__ + #if MICROPY_MODULE___FILE__ qstr frozen_file_qstr = qstr_from_str(file_str + frozen_path_prefix_len); #else qstr frozen_file_qstr = MP_QSTRnull; @@ -240,7 +278,9 @@ static void do_load(mp_module_context_t *module_obj, vstr_t *file) { #endif // MICROPY_MODULE_FROZEN + #if MICROPY_ENABLE_COMPILER || (MICROPY_PERSISTENT_CODE_LOAD && MICROPY_HAS_FILE_READER) qstr file_qstr = qstr_from_str(file_str); + #endif // If we support loading .mpy files then check if the file extension is of // the correct format and, if so, load and execute the file. @@ -270,7 +310,7 @@ static void do_load(mp_module_context_t *module_obj, vstr_t *file) { // Convert a relative (to the current module) import, going up "level" levels, // into an absolute import. -static void evaluate_relative_import(mp_int_t level, const char **module_name, size_t *module_name_len) { +static void evaluate_relative_import(mp_int_t level, const char **module_name, size_t *module_name_len, mp_obj_t globals) { // What we want to do here is to take the name of the current module, // remove trailing components, and concatenate the passed-in // module name. @@ -279,7 +319,7 @@ static void evaluate_relative_import(mp_int_t level, const char **module_name, s // module's position in the package hierarchy." // http://legacy.python.org/dev/peps/pep-0328/#relative-imports-and-name - mp_obj_t current_module_name_obj = mp_obj_dict_get(MP_OBJ_FROM_PTR(mp_globals_get()), MP_OBJ_NEW_QSTR(MP_QSTR___name__)); + mp_obj_t current_module_name_obj = mp_obj_dict_get(globals, MP_OBJ_NEW_QSTR(MP_QSTR___name__)); assert(current_module_name_obj != MP_OBJ_NULL); #if MICROPY_MODULE_OVERRIDE_MAIN_IMPORT && MICROPY_CPYTHON_COMPAT @@ -287,12 +327,12 @@ static void evaluate_relative_import(mp_int_t level, const char **module_name, s // This is a module loaded by -m command-line switch (e.g. unix port), // and so its __name__ has been set to "__main__". Get its real name // that we stored during import in the __main__ attribute. - current_module_name_obj = mp_obj_dict_get(MP_OBJ_FROM_PTR(mp_globals_get()), MP_OBJ_NEW_QSTR(MP_QSTR___main__)); + current_module_name_obj = mp_obj_dict_get(globals, MP_OBJ_NEW_QSTR(MP_QSTR___main__)); } #endif // If we have a __path__ in the globals dict, then we're a package. - bool is_pkg = mp_map_lookup(&mp_globals_get()->map, MP_OBJ_NEW_QSTR(MP_QSTR___path__), MP_MAP_LOOKUP); + bool is_pkg = mp_map_lookup(mp_obj_dict_get_map(globals), MP_OBJ_NEW_QSTR(MP_QSTR___path__), MP_MAP_LOOKUP); #if DEBUG_PRINT DEBUG_printf("Current module/package: "); @@ -370,7 +410,7 @@ static mp_obj_t process_import_at_level(qstr full_mod_name, qstr level_mod_name, // Immediately return if the module at this level is already loaded. mp_map_elem_t *elem; - #if MICROPY_PY_SYS + #if MICROPY_PY_SYS && MICROPY_PY_SYS_PATH // If sys.path is empty, the intention is to force using a built-in. This // means we should also ignore any loaded modules with the same name // which may have come from the filesystem. @@ -406,6 +446,7 @@ static mp_obj_t process_import_at_level(qstr full_mod_name, qstr level_mod_name, // all the locations in sys.path. stat = stat_top_level(level_mod_name, &path); + #if MICROPY_HAVE_REGISTERED_EXTENSIBLE_MODULES // If filesystem failed, now try and see if it matches an extensible // built-in module. if (stat == MP_IMPORT_STAT_NO_EXIST) { @@ -414,6 +455,7 @@ static mp_obj_t process_import_at_level(qstr full_mod_name, qstr level_mod_name, return module_obj; } } + #endif } else { DEBUG_printf("Searching for sub-module\n"); @@ -451,7 +493,9 @@ static mp_obj_t process_import_at_level(qstr full_mod_name, qstr level_mod_name, if (stat == MP_IMPORT_STAT_NO_EXIST) { // Not found -- fail. - #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE + // CIRCUITPY-CHANGE: always the use more verbose error message that names missing module. + // Otherwise `import a` where `a` imports `b`, but `b` is missing will give a confusing error. + #if 0 && (MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE) mp_raise_msg(&mp_type_ImportError, MP_ERROR_TEXT("module not found")); #else mp_raise_msg_varg(&mp_type_ImportError, MP_ERROR_TEXT("no module named '%q'"), full_mod_name); @@ -575,10 +619,19 @@ mp_obj_t mp_builtin___import___default(size_t n_args, const mp_obj_t *args) { const char *module_name = mp_obj_str_get_data(module_name_obj, &module_name_len); if (level != 0) { + // This is the dict with all global symbols. + mp_obj_t globals = MP_OBJ_FROM_PTR(mp_globals_get()); + if (n_args >= 2 && args[1] != mp_const_none) { + globals = args[1]; + if (!mp_obj_is_type(globals, &mp_type_dict)) { + mp_raise_TypeError(NULL); + } + } + // Turn "foo.bar" with level=3 into ".foo.bar". // Current module name is extracted from globals().__name__. - evaluate_relative_import(level, &module_name, &module_name_len); // module_name is now an absolute module path. + evaluate_relative_import(level, &module_name, &module_name_len, globals); } if (module_name_len == 0) { @@ -654,11 +707,13 @@ mp_obj_t mp_builtin___import___default(size_t n_args, const mp_obj_t *args) { if (module_obj != MP_OBJ_NULL) { return module_obj; } + #if MICROPY_HAVE_REGISTERED_EXTENSIBLE_MODULES // Now try as an extensible built-in (e.g. `time`). module_obj = mp_module_get_builtin(module_name_qstr, true); if (module_obj != MP_OBJ_NULL) { return module_obj; } + #endif // Couldn't find the module, so fail #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE diff --git a/py/circuitpy_defns.mk b/py/circuitpy_defns.mk old mode 100644 new mode 100755 index 2e7bba09d01..085331a3f8b --- a/py/circuitpy_defns.mk +++ b/py/circuitpy_defns.mk @@ -104,6 +104,9 @@ endif ifeq ($(CIRCUITPY_AESIO),1) SRC_PATTERNS += aesio/% endif +ifeq ($(CIRCUITPY_AIRLIFT),1) +SRC_PATTERNS += _airlift/% +endif ifeq ($(CIRCUITPY_ALARM),1) SRC_PATTERNS += alarm/__init__.c alarm/SleepMemory.c alarm/pin/% alarm/time/% endif @@ -116,12 +119,18 @@ endif ifeq ($(CIRCUITPY_ANALOGIO),1) SRC_PATTERNS += analogio/% endif +ifeq ($(CIRCUITPY_ASYNC_SPI),1) +SRC_PATTERNS += async_spi/% +endif ifeq ($(CIRCUITPY_ATEXIT),1) SRC_PATTERNS += atexit/% endif ifeq ($(CIRCUITPY_AUDIOBUSIO),1) SRC_PATTERNS += audiobusio/% endif +ifeq ($(CIRCUITPY_AUDIOI2SIN),1) +SRC_PATTERNS += audioi2sin/% +endif ifeq ($(CIRCUITPY_AUDIOIO),1) SRC_PATTERNS += audioio/% endif @@ -137,12 +146,24 @@ endif ifeq ($(CIRCUITPY_AUDIOFILTERS),1) SRC_PATTERNS += audiofilters/% endif +ifeq ($(CIRCUITPY_AUDIOFREEVERB),1) +SRC_PATTERNS += audiofreeverb/% +endif ifeq ($(CIRCUITPY_AUDIOMIXER),1) SRC_PATTERNS += audiomixer/% endif ifeq ($(CIRCUITPY_AUDIOMP3),1) SRC_PATTERNS += audiomp3/% endif +ifeq ($(CIRCUITPY_AUDIOSPEED),1) +SRC_PATTERNS += audiospeed/% +endif +ifeq ($(CIRCUITPY_AUDIOTAP),1) +SRC_PATTERNS += audiotap/% +endif +ifeq ($(CIRCUITPY_AUDIOFILEWRITER),1) +SRC_PATTERNS += audiofilewriter/% +endif ifeq ($(CIRCUITPY_AURORA_EPAPER),1) SRC_PATTERNS += aurora_epaper/% endif @@ -162,7 +183,7 @@ endif ifeq ($(CIRCUITPY_BITOPS),1) SRC_PATTERNS += bitops/% endif -ifeq ($(CIRCUITPY_BLEIO),1) +ifeq ($(CIRCUITPY_BLEIO_NATIVE),1) SRC_PATTERNS += _bleio/% endif ifeq ($(CIRCUITPY_BOARD),1) @@ -186,6 +207,9 @@ endif ifeq ($(CIRCUITPY_CODEOP),1) SRC_PATTERNS += codeop/% endif +ifeq ($(CIRCUITPY_CRYPTOGRAPHY),1) +SRC_PATTERNS += cryptography/% +endif ifeq ($(CIRCUITPY_COUNTIO),1) SRC_PATTERNS += countio/% endif @@ -198,9 +222,18 @@ endif ifeq ($(CIRCUITPY_DISPLAYIO),1) SRC_PATTERNS += displayio/% endif +ifeq ($(CIRCUITPY_DOTCLOCKFRAMEBUFFER),1) +SRC_PATTERNS += dotclockframebuffer/% +endif +ifeq ($(CIRCUITPY_DUALBANK),1) +SRC_PATTERNS += dualbank/% +endif ifeq ($(CIRCUITPY__EVE),1) SRC_PATTERNS += _eve/% endif +ifeq ($(CIRCUITPY_EMMCIO),1) +SRC_PATTERNS += emmcio/% +endif ifeq ($(CIRCUITPY_EPAPERDISPLAY),1) SRC_PATTERNS += epaperdisplay/% endif @@ -216,6 +249,9 @@ endif ifeq ($(CIRCUITPY_ESPULP),1) SRC_PATTERNS += espulp/% endif +ifeq ($(CIRCUITPY_MII),1) +SRC_PATTERNS += mii/% +endif ifeq ($(CIRCUITPY_FLOPPYIO),1) SRC_PATTERNS += floppyio/% endif @@ -240,15 +276,24 @@ endif ifeq ($(CIRCUITPY_GNSS),1) SRC_PATTERNS += gnss/% endif +ifeq ($(CIRCUITPY_HARDWAREKEY),1) +SRC_PATTERNS += hardwarekey/% +endif ifeq ($(CIRCUITPY_HASHLIB),1) SRC_PATTERNS += hashlib/% endif +ifeq ($(CIRCUITPY_HMAC),1) +SRC_PATTERNS += hmac/% +endif ifeq ($(CIRCUITPY_I2CDISPLAYBUS),1) SRC_PATTERNS += i2cdisplaybus/% endif ifeq ($(CIRCUITPY_I2CTARGET),1) SRC_PATTERNS += i2ctarget/% endif +ifeq ($(CIRCUITPY_I2CIOEXPANDER),1) +SRC_PATTERNS += i2cioexpander/% +endif ifeq ($(CIRCUITPY_IMAGECAPTURE),1) SRC_PATTERNS += imagecapture/% endif @@ -276,6 +321,12 @@ endif ifeq ($(CIRCUITPY_MAX3421E),1) SRC_PATTERNS += max3421e/% endif +ifeq ($(CIRCUITPY_MCP4822),1) +SRC_PATTERNS += mcp4822/% +endif +ifeq ($(CIRCUITPY_MDNS),1) +SRC_PATTERNS += mdns/% +endif ifeq ($(CIRCUITPY_MEMORYMAP),1) SRC_PATTERNS += memorymap/% endif @@ -285,8 +336,11 @@ endif ifeq ($(CIRCUITPY_MICROCONTROLLER),1) SRC_PATTERNS += microcontroller/% endif -ifeq ($(CIRCUITPY_MDNS),1) -SRC_PATTERNS += mdns/% +ifeq ($(CIRCUITPY_MIPICSI),1) +SRC_PATTERNS += mipicsi/% +endif +ifeq ($(CIRCUITPY_MIPIDSI),1) +SRC_PATTERNS += mipidsi/% endif ifeq ($(CIRCUITPY_MSGPACK),1) SRC_PATTERNS += msgpack/% @@ -303,9 +357,6 @@ endif ifeq ($(CIRCUITPY_OS),1) SRC_PATTERNS += os/% endif -ifeq ($(CIRCUITPY_DUALBANK),1) -SRC_PATTERNS += dualbank/% -endif ifeq ($(CIRCUITPY_PARALLELDISPLAYBUS),1) SRC_PATTERNS += paralleldisplaybus/% endif @@ -339,11 +390,14 @@ endif ifeq ($(CIRCUITPY_RANDOM),1) SRC_PATTERNS += random/% endif +ifeq ($(CIRCUITPY_RCLCPY),1) +SRC_PATTERNS += rclcpy/% +endif ifeq ($(CIRCUITPY_RGBMATRIX),1) SRC_PATTERNS += rgbmatrix/% endif -ifeq ($(CIRCUITPY_DOTCLOCKFRAMEBUFFER),1) -SRC_PATTERNS += dotclockframebuffer/% +ifeq ($(CIRCUITPY_QSPIBUS),1) +SRC_PATTERNS += qspibus/% endif ifeq ($(CIRCUITPY_RP2PIO),1) SRC_PATTERNS += rp2pio/% @@ -378,6 +432,12 @@ endif ifeq ($(CIRCUITPY_STAGE),1) SRC_PATTERNS += _stage/% endif +ifeq ($(CIRCUITPY_PICOGAME),1) +SRC_PATTERNS += picogame/% +endif +ifeq ($(CIRCUITPY_PICOGAME3D),1) +SRC_PATTERNS += picogame3d/% +endif ifeq ($(CIRCUITPY_STORAGE),1) SRC_PATTERNS += storage/% endif @@ -396,6 +456,9 @@ endif ifeq ($(CIRCUITPY_FONTIO),1) SRC_PATTERNS += fontio/% endif +ifeq ($(CIRCUITPY_LVFONTIO),1) +SRC_PATTERNS += lvfontio/% +endif ifeq ($(CIRCUITPY_TILEPALETTEMAPPER),1) SRC_PATTERNS += tilepalettemapper/% endif @@ -423,9 +486,18 @@ endif ifeq ($(CIRCUITPY_USB_VIDEO),1) SRC_PATTERNS += usb_video/% endif +ifeq ($(CIRCUITPY_USB_AUDIO),1) +SRC_PATTERNS += usb_audio/% +endif ifeq ($(CIRCUITPY_USB_HOST),1) SRC_PATTERNS += usb_host/% endif +ifeq ($(CIRCUITPY_USB_HOST_AUDIO),1) +SRC_PATTERNS += usb_host_audio/% +endif +ifeq ($(CIRCUITPY_USB_HOST_BULK),1) +SRC_PATTERNS += usb_host_bulk/% +endif ifeq ($(CIRCUITPY_USB_MIDI),1) SRC_PATTERNS += usb_midi/% endif @@ -441,6 +513,9 @@ endif ifeq ($(CIRCUITPY_VIDEOCORE),1) SRC_PATTERNS += videocore/% endif +ifeq ($(CIRCUITPY_VIDEOGIF),1) +SRC_PATTERNS += videogif/% +endif ifeq ($(CIRCUITPY_WARNINGS),1) SRC_PATTERNS += warnings/% endif @@ -450,6 +525,9 @@ endif ifeq ($(CIRCUITPY_WIFI),1) SRC_PATTERNS += wifi/% endif +ifeq ($(CIRCUITPY_WIZNET),1) +SRC_PATTERNS += wiznet/% +endif ifeq ($(CIRCUITPY_ZLIB),1) SRC_PATTERNS += zlib/% endif @@ -478,16 +556,19 @@ SRC_COMMON_HAL_ALL = \ analogio/AnalogIn.c \ analogio/AnalogOut.c \ analogio/__init__.c \ + async_spi/SPI.c \ + async_spi/__init__.c \ audiobusio/I2SOut.c \ audiobusio/PDMIn.c \ audiobusio/__init__.c \ + audioi2sin/I2SIn.c \ + audioi2sin/__init__.c \ audioio/AudioOut.c \ audioio/__init__.c \ audiopwmio/PWMAudioOut.c \ audiopwmio/__init__.c \ board/__init__.c \ busio/I2C.c \ - busio/SPI.c \ busio/UART.c \ busio/__init__.c \ camera/__init__.c \ @@ -502,6 +583,12 @@ SRC_COMMON_HAL_ALL = \ dotclockframebuffer/DotClockFramebuffer.c \ dotclockframebuffer/__init__.c \ dualbank/__init__.c \ + emmcio/EMMC.c \ + emmcio/__init__.c \ + mii/MDIO.c \ + mii/Ethernet.c \ + mii/RMII.c \ + mii/__init__.c \ floppyio/__init__.c \ frequencyio/FrequencyIn.c \ frequencyio/__init__.c \ @@ -514,6 +601,8 @@ SRC_COMMON_HAL_ALL = \ i2ctarget/I2CTarget.c \ i2ctarget/__init__.c \ max3421e/Max3421E.c \ + mcp4822/__init__.c \ + mcp4822/MCP4822.c \ memorymap/__init__.c \ memorymap/AddressRange.c \ microcontroller/__init__.c \ @@ -522,6 +611,11 @@ SRC_COMMON_HAL_ALL = \ mdns/__init__.c \ mdns/Server.c \ mdns/RemoteService.c \ + mipicsi/__init__.c \ + mipicsi/Camera.c \ + mipidsi/Bus.c \ + mipidsi/Display.c \ + mipidsi/__init__.c \ neopixel_write/__init__.c \ nvm/ByteArray.c \ nvm/__init__.c \ @@ -534,6 +628,11 @@ SRC_COMMON_HAL_ALL = \ pulseio/__init__.c \ pwmio/PWMOut.c \ pwmio/__init__.c \ + qspibus/QSPIBus.c \ + qspibus/__init__.c \ + rclcpy/__init__.c \ + rclcpy/Node.c \ + rclcpy/Publisher.c \ rgbmatrix/RGBMatrix.c \ rgbmatrix/__init__.c \ rotaryio/IncrementalEncoder.c \ @@ -542,6 +641,9 @@ SRC_COMMON_HAL_ALL = \ rtc/__init__.c \ sdioio/SDCard.c \ sdioio/__init__.c \ + cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c \ + hardwarekey/HardwareKey.c \ + hardwarekey/__init__.c \ socketpool/__init__.c \ socketpool/SocketPool.c \ socketpool/Socket.c \ @@ -549,6 +651,8 @@ SRC_COMMON_HAL_ALL = \ spitarget/__init__.c \ usb_host/__init__.c \ usb_host/Port.c \ + usb_host_bulk/__init__.c \ + usb_host_bulk/InStream.c \ watchdog/WatchDogMode.c \ watchdog/WatchDogTimer.c \ watchdog/__init__.c \ @@ -558,38 +662,68 @@ SRC_COMMON_HAL_ALL = \ wifi/ScannedNetworks.c \ wifi/__init__.c \ -ifeq ($(CIRCUITPY_BLEIO_HCI),1) -# Helper code for _bleio HCI. -SRC_C += \ - common-hal/_bleio/att.c \ - common-hal/_bleio/hci.c \ +SRC_COMMON_HAL = $(filter $(SRC_PATTERNS), $(SRC_COMMON_HAL_ALL)) +ifeq ($(CIRCUITPY_BLEIO_HCI),1) +# HCI device-specific HAL and helper sources. +SRC_DEVICES_HAL += \ + _bleio/att.c \ + _bleio/hci.c \ + _bleio/Adapter.c \ + _bleio/Attribute.c \ + _bleio/Characteristic.c \ + _bleio/CharacteristicBuffer.c \ + _bleio/Connection.c \ + _bleio/Descriptor.c \ + _bleio/PacketBuffer.c \ + _bleio/Service.c \ + _bleio/UUID.c \ + _bleio/__init__.c +# HCI device-specific bindings. +SRC_DEVICES_BINDINGS += \ + supervisor/bluetooth.c endif -SRC_COMMON_HAL = $(filter $(SRC_PATTERNS), $(SRC_COMMON_HAL_ALL)) - # These don't have corresponding files in each port but are still located in # shared-bindings to make it clear what the contents of the modules are. # All possible sources are listed here, and are filtered by SRC_PATTERNS. SRC_BINDINGS_ENUMS = \ $(filter $(SRC_PATTERNS), \ + picogame/Bitmap.c \ + picogame/Sprite.c \ + picogame/StripDraw.c \ + picogame/Triangles.c \ + picogame/Framebuffer.c \ _bleio/Address.c \ _bleio/Attribute.c \ _bleio/ScanEntry.c \ _eve/__init__.c \ __future__/__init__.c \ + busdisplay/BusDisplay.c \ camera/ImageFormat.c \ + epaperdisplay/EPaperDisplay.c \ canio/Match.c \ codeop/__init__.c \ countio/Edge.c \ + digitalio/DigitalInOutProtocol.c \ digitalio/Direction.c \ digitalio/DriveMode.c \ digitalio/Pull.c \ + displayio/Bitmap.c \ + displayio/ColorConverter.c \ + displayio/Group.c \ + displayio/OnDiskBitmap.c \ + displayio/Palette.c \ + displayio/TileGrid.c \ + displayio/__init__.c \ displayio/Colorspace.c \ fontio/Glyph.c \ + framebufferio/FramebufferDisplay.c \ imagecapture/ParallelImageCapture.c \ locale/__init__.c \ math/__init__.c \ + mipicsi/BayerOrder.c \ + mipicsi/PixelFormat.c \ microcontroller/ResetReason.c \ microcontroller/RunMode.c \ msgpack/__init__.c \ @@ -597,13 +731,34 @@ $(filter $(SRC_PATTERNS), \ paralleldisplaybus/__init__.c \ qrio/PixelPolicy.c \ qrio/QRInfo.c \ + rgbmatrix/RowAddressMode.c \ supervisor/RunReason.c \ supervisor/Runtime.c \ supervisor/StatusBar.c \ + vectorio/VectorShape.c \ + videogif/__init__.c \ wifi/AuthMode.c \ wifi/Packet.c \ + wifi/PowerManagement.c \ ) +ifeq ($(CIRCUITPY_BLEIO_HCI),1) +# Common _bleio bindings used by HCI. +SRC_BINDINGS_ENUMS += \ + _bleio/Address.c \ + _bleio/Adapter.c \ + _bleio/Attribute.c \ + _bleio/Characteristic.c \ + _bleio/CharacteristicBuffer.c \ + _bleio/Connection.c \ + _bleio/Descriptor.c \ + _bleio/PacketBuffer.c \ + _bleio/ScanEntry.c \ + _bleio/Service.c \ + _bleio/UUID.c \ + _bleio/__init__.c +endif + ifeq ($(CIRCUITPY_SAFEMODE_PY),1) SRC_BINDINGS_ENUMS += \ supervisor/SafeModeReason.c @@ -613,6 +768,7 @@ SRC_BINDINGS_ENUMS += \ util.c SRC_SHARED_MODULE_ALL = \ + _airlift/__init__.c \ _bleio/Address.c \ _bleio/Attribute.c \ _bleio/ScanEntry.c \ @@ -625,18 +781,39 @@ SRC_SHARED_MODULE_ALL = \ _stage/Layer.c \ _stage/Text.c \ _stage/__init__.c \ + picogame/__init__.c \ + picogame/Scene.c \ + picogame/Tilemap.c \ + picogame/Particles.c \ + picogame/Canvas.c \ + picogame3d/__init__.c \ aesio/__init__.c \ aesio/aes.c \ atexit/__init__.c \ audiocore/RawSample.c \ audiocore/WaveFile.c \ audiocore/__init__.c \ + audiospeed/Resampler.c \ + audiospeed/SpeedChanger.c \ + audiospeed/__init__.c \ + audiotap/LevelReader.c \ + audiotap/Tap.c \ + audiotap/__init__.c \ audiodelays/Echo.c \ + audiodelays/Chorus.c \ + audiodelays/Flanger.c \ audiodelays/PitchShift.c \ + audiodelays/GranularPitchShift.c \ + audiodelays/MultiTapDelay.c \ audiodelays/__init__.c \ audiofilters/Distortion.c \ audiofilters/Filter.c \ + audiofilters/Phaser.c \ audiofilters/__init__.c \ + audiofreeverb/__init__.c \ + audiofreeverb/Freeverb.c \ + audiofilewriter/AudioFileWriter.c \ + audiofilewriter/__init__.c \ audioio/__init__.c \ audiomixer/Mixer.c \ audiomixer/MixerVoice.c \ @@ -657,27 +834,23 @@ SRC_SHARED_MODULE_ALL = \ adafruit_bus_device/i2c_device/I2CDevice.c \ adafruit_bus_device/spi_device/SPIDevice.c \ busdisplay/__init__.c \ - busdisplay/BusDisplay.c \ canio/Match.c \ canio/Message.c \ canio/RemoteTransmissionRequest.c \ - displayio/Bitmap.c \ - displayio/ColorConverter.c \ - displayio/Group.c \ - displayio/OnDiskBitmap.c \ - displayio/Palette.c \ - displayio/TileGrid.c \ - displayio/area.c \ - displayio/__init__.c \ dotclockframebuffer/__init__.c \ + emmcio/__init__.c \ epaperdisplay/__init__.c \ epaperdisplay/EPaperDisplay.c \ + i2cioexpander/IOExpander.c \ + i2cioexpander/IOPin.c \ + i2cioexpander/__init__.c \ floppyio/__init__.c \ fontio/BuiltinFont.c \ fontio/__init__.c \ + lvfontio/OnDiskFont.c\ + lvfontio/__init__.c \ fourwire/__init__.c \ fourwire/FourWire.c \ - framebufferio/FramebufferDisplay.c \ framebufferio/__init__.c \ getpass/__init__.c \ gifio/__init__.c \ @@ -719,6 +892,19 @@ SRC_SHARED_MODULE_ALL = \ rotaryio/IncrementalEncoder.c \ sdcardio/SDCard.c \ sdcardio/__init__.c \ + cryptography/__init__.c \ + cryptography/exceptions/__init__.c \ + cryptography/hazmat/__init__.c \ + cryptography/hazmat/primitives/__init__.c \ + cryptography/hazmat/primitives/asymmetric/__init__.c \ + cryptography/hazmat/primitives/asymmetric/ec/__init__.c \ + cryptography/hazmat/primitives/asymmetric/ec/EllipticCurvePublicKey.c \ + cryptography/hazmat/primitives/asymmetric/padding/__init__.c \ + cryptography/hazmat/primitives/asymmetric/rsa/__init__.c \ + cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c \ + cryptography/hazmat/primitives/asymmetric/utils/__init__.c \ + cryptography/hazmat/primitives/hashes/__init__.c \ + hardwarekey/HardwareKey.c \ sharpdisplay/SharpMemoryFramebuffer.c \ sharpdisplay/__init__.c \ socket/__init__.c \ @@ -727,7 +913,6 @@ SRC_SHARED_MODULE_ALL = \ supervisor/__init__.c \ supervisor/StatusBar.c \ synthio/Biquad.c \ - synthio/BlockBiquad.c \ synthio/LFO.c \ synthio/Math.c \ synthio/MidiTrack.c \ @@ -745,19 +930,83 @@ SRC_SHARED_MODULE_ALL = \ usb/core/__init__.c \ usb/core/Device.c \ usb/util/__init__.c \ + usb_host_audio/USBIn.c \ + usb_host_audio/__init__.c \ ustack/__init__.c \ vectorio/Circle.c \ vectorio/Polygon.c \ vectorio/Rectangle.c \ - vectorio/VectorShape.c \ vectorio/__init__.c \ + videocore/VideoBuffer.c \ + videocore/__init__.c \ + videogif/GifDecoder.c \ warnings/__init__.c \ watchdog/__init__.c \ zlib/__init__.c \ +# The displayio and vectorio implementation sources live in one of the two backend +# directories. vectorio's shape math (Circle, Polygon, Rectangle) is backend agnostic and +# lives in shared-module/vectorio/ directly. +ifeq ($(CIRCUITPY_DISPLAYIO_LVGL),1) +SRC_SHARED_MODULE_INTERNAL += \ +$(filter $(SRC_PATTERNS), \ + displayio/lvgl/Bitmap.c \ + displayio/lvgl/ColorConverter.c \ + displayio/lvgl/Group.c \ + displayio/lvgl/ImageRoot.c \ + displayio/lvgl/OnDiskBitmap.c \ + displayio/lvgl/Palette.c \ + busdisplay/lvgl/BusDisplay.c \ + displayio/lvgl/TileGrid.c \ + displayio/legacy/__init__.c \ + epaperdisplay/lvgl/EPaperDisplay.c \ + framebufferio/lvgl/FramebufferDisplay.c \ + vectorio/lvgl/VectorShape.c \ + videocore/lvgl/VideoBuffer.c \ +) +else +SRC_SHARED_MODULE_INTERNAL += \ +$(filter $(SRC_PATTERNS), \ + busdisplay/legacy/BusDisplay.c \ + displayio/legacy/__init__.c \ + displayio/legacy/Bitmap.c \ + displayio/legacy/ColorConverter.c \ + displayio/legacy/display_core_scanline.c \ + displayio/legacy/Group.c \ + displayio/legacy/OnDiskBitmap.c \ + displayio/legacy/Palette.c \ + displayio/legacy/TileGrid.c \ + epaperdisplay/legacy/EPaperDisplay.c \ + framebufferio/legacy/FramebufferDisplay.c \ + vectorio/legacy/VectorShape.c \ + videocore/legacy/VideoBuffer.c \ +) +endif + # All possible sources are listed here, and are filtered by SRC_PATTERNS. SRC_SHARED_MODULE = $(filter $(SRC_PATTERNS), $(SRC_SHARED_MODULE_ALL)) +SRC_COMMON_HAL_EXPANDED = $(addprefix shared-bindings/, $(SRC_COMMON_HAL)) \ + $(addprefix shared-bindings/, $(SRC_BINDINGS_ENUMS)) \ + $(addprefix common-hal/, $(SRC_COMMON_HAL)) \ + $(addprefix devices/ble_hci/common-hal/, $(SRC_DEVICES_HAL)) \ + $(addprefix devices/ble_hci/, $(SRC_DEVICES_BINDINGS)) + +SRC_SHARED_MODULE_EXPANDED = $(addprefix shared-bindings/, $(SRC_SHARED_MODULE)) \ + $(addprefix shared-module/, $(SRC_SHARED_MODULE)) \ + $(addprefix shared-module/, $(SRC_SHARED_MODULE_INTERNAL)) + +# There may be duplicates between SRC_COMMON_HAL_EXPANDED and SRC_SHARED_MODULE_EXPANDED, +# because a few modules have files both in common-hal/ and shared-module/. +# Doing a $(sort ...) removes duplicates as part of sorting. +SRC_COMMON_HAL_SHARED_MODULE_EXPANDED = $(sort $(SRC_COMMON_HAL_EXPANDED) $(SRC_SHARED_MODULE_EXPANDED)) + +# The port provides vector code for audiomixer. +ifeq ($(CIRCUITPY_AUDIOMIXER_USE_PORT_MIX),1) +SRC_COMMON_HAL_ALL += \ + audiomixer/__init__.c +endif + # Use the native touchio if requested. This flag is set conditionally in, say, mpconfigport.h. # The presence of common-hal/touchio/* does not imply it's available for all chips in a port, # so there is an explicit flag. For example, SAMD21 touchio is native, but SAMD51 is not. @@ -771,6 +1020,20 @@ SRC_SHARED_MODULE_ALL += \ touchio/__init__.c endif +# The strip-rendering Display backend sends through the display bus; nothing port-specific. +ifeq ($(CIRCUITPY_PICOGAME_FAST_DISPLAY),1) +SRC_SHARED_MODULE_ALL += picogame/Display.c +endif + +# On a port with async SPI, busio.SPI is shared code on top of common-hal/async_spi. +ifeq ($(CIRCUITPY_ASYNC_SPI),1) +SRC_SHARED_MODULE_ALL += \ + busio/SPI.c +else +SRC_COMMON_HAL_ALL += \ + busio/SPI.c +endif + ifeq ($(CIRCUITPY_SSL_MBEDTLS),0) SRC_COMMON_HAL_ALL += \ ssl/__init__.c \ @@ -789,11 +1052,15 @@ SRC_SHARED_MODULE_ALL += \ keypad_demux/DemuxKeyMatrix.c endif -# If supporting _bleio via HCI, make devices/ble_hci/common-hal/_bleio be includable, -# and use C source files in devices/ble_hci/common-hal. ifeq ($(CIRCUITPY_BLEIO_HCI),1) +# Add HCI device-specific includes to search path. INC += -I$(TOP)/devices/ble_hci -DEVICES_MODULES += $(TOP)/devices/ble_hci +# Add HCI shared modules to build. +SRC_SHARED_MODULE += \ + _bleio/Address.c \ + _bleio/Attribute.c \ + _bleio/ScanEntry.c \ + _bleio/ScanResults.c endif ifeq ($(CIRCUITPY_AUDIOMP3),1) @@ -825,7 +1092,7 @@ ifeq ($(CIRCUITPY_GIFIO),1) SRC_MOD += $(addprefix lib/AnimatedGIF/, \ gif.c \ ) -$(BUILD)/lib/AnimatedGIF/gif.o: CFLAGS += -DCIRCUITPY +$(BUILD)/lib/AnimatedGIF/gif.o: CFLAGS += -DCIRCUITPY -Wno-unused-but-set-variable endif ifeq ($(CIRCUITPY_JPEGIO),1) @@ -833,16 +1100,85 @@ SRC_MOD += lib/tjpgd/src/tjpgd.c $(BUILD)/lib/tjpgd/src/tjpgd.o: CFLAGS += -Wno-shadow -Wno-cast-align endif +# A port adds its own PSA drivers to mbedtls's dispatch layer by setting +# MBEDTLS_DRIVER_PATCH (in mpconfigport.mk) to a patch against mbedtls's driver +# wrapper templates and PSA context header. They are copied to the build directory +# and patched with no fuzz, so an mbedtls update that moves the patched code stops +# the build here. The patched header shadows mbedtls's own for every file, and is +# made before anything is compiled. +ifneq ($(MBEDTLS_DRIVER_PATCH),) +MBEDTLS_DISPATCH := $(BUILD)/psa_dispatch +MBEDTLS_DISPATCH_STAMP := $(MBEDTLS_DISPATCH)/.patched +MBEDTLS_WRAPPERS_ARGS := --template-dir $(MBEDTLS_DISPATCH)/driver_templates +CFLAGS += -I$(MBEDTLS_DISPATCH)/include +QSTR_GLOBAL_REQUIREMENTS += $(MBEDTLS_DISPATCH_STAMP) + +MBEDTLS_DISPATCH_TEMPLATES := $(wildcard $(TOP)/lib/mbedtls/tf-psa-crypto/scripts/data_files/driver_templates/*) +MBEDTLS_DISPATCH_CONTEXTS := $(TOP)/lib/mbedtls/tf-psa-crypto/include/psa/crypto_driver_contexts_primitives.h + +$(MBEDTLS_DISPATCH_STAMP): $(MBEDTLS_DRIVER_PATCH) $(MBEDTLS_DISPATCH_TEMPLATES) $(MBEDTLS_DISPATCH_CONTEXTS) + $(STEPECHO) "PATCH $<" + $(Q)rm -rf $(MBEDTLS_DISPATCH) + $(Q)mkdir -p $(MBEDTLS_DISPATCH)/driver_templates $(MBEDTLS_DISPATCH)/include/psa + $(Q)cp $(MBEDTLS_DISPATCH_TEMPLATES) $(MBEDTLS_DISPATCH)/driver_templates/ + $(Q)cp $(MBEDTLS_DISPATCH_CONTEXTS) $(MBEDTLS_DISPATCH)/include/psa/ + $(Q)patch -s -F0 -p1 -d $(MBEDTLS_DISPATCH) < $< + $(Q)touch $@ +endif + ifeq ($(CIRCUITPY_HASHLIB_MBEDTLS_ONLY),1) -SRC_MOD += $(addprefix lib/mbedtls/library/, \ - sha1.c \ - sha256.c \ - sha512.c \ - platform_util.c \ - ) +# mbedtls 4.x moved the crypto implementations out of lib/mbedtls/library into the +# tf-psa-crypto submodule and made the legacy mbedtls_sha256_*() headers private, so +# hashlib goes through the PSA hash API. That needs the PSA core, whose driver dispatch +# layer is generated rather than shipped -- see the same rule in ports/raspberrypi/Makefile. +SRC_MOD += \ + $(addprefix lib/mbedtls/tf-psa-crypto/core/, \ + psa_crypto.c \ + psa_crypto_client.c \ + psa_crypto_slot_management.c \ + psa_util.c \ + ) \ + $(addprefix lib/mbedtls/tf-psa-crypto/drivers/builtin/src/, \ + psa_crypto_hash.c \ + psa_util_internal.c \ + sha1.c \ + sha256.c \ + ) \ + $(addprefix lib/mbedtls/tf-psa-crypto/platform/, \ + platform.c \ + platform_util.c \ + ) \ + lib/mbedtls/tf-psa-crypto/utilities/constant_time.c \ + lib/mbedtls_config/hashlib_psa_port.c + +MBEDTLS_HASHLIB_GEN := $(BUILD)/tf-psa-crypto +MBEDTLS_HASHLIB_WRAPPERS_H := $(MBEDTLS_HASHLIB_GEN)/psa_crypto_driver_wrappers.h +MBEDTLS_HASHLIB_WRAPPERS_C := $(MBEDTLS_HASHLIB_GEN)/psa_crypto_driver_wrappers_no_static.c +SRC_MOD += $(MBEDTLS_HASHLIB_WRAPPERS_C:$(BUILD)/%=%) + +# The script writes both files at once; naming both as targets would run it twice. +$(MBEDTLS_HASHLIB_WRAPPERS_C): $(MBEDTLS_HASHLIB_WRAPPERS_H) + @true + +$(MBEDTLS_HASHLIB_WRAPPERS_H): $(TOP)/lib/mbedtls/tf-psa-crypto/scripts/generate_driver_wrappers.py $(MBEDTLS_DISPATCH_STAMP) + $(STEPECHO) "GEN $@" + $(Q)mkdir -p $(MBEDTLS_HASHLIB_GEN) + $(Q)PYTHONPATH=$(TOP)/lib/mbedtls/framework/scripts $(PYTHON) $< $(MBEDTLS_WRAPPERS_ARGS) $(MBEDTLS_HASHLIB_GEN) + +# psa_crypto.c and friends #include the generated header. +$(addprefix $(BUILD)/, $(SRC_MOD:.c=.o)): $(MBEDTLS_HASHLIB_WRAPPERS_H) + CFLAGS += \ - -isystem $(TOP)/lib/mbedtls/include \ - -DMBEDTLS_CONFIG_FILE='"$(TOP)/lib/mbedtls_config/mbedtls_config_hashlib.h"' \ + -I$(MBEDTLS_HASHLIB_GEN) \ + -isystem $(TOP)/lib/mbedtls/tf-psa-crypto/include \ + -isystem $(TOP)/lib/mbedtls/tf-psa-crypto/drivers/builtin/include \ + -isystem $(TOP)/lib/mbedtls/tf-psa-crypto/drivers/builtin/src \ + -isystem $(TOP)/lib/mbedtls/tf-psa-crypto/core \ + -isystem $(TOP)/lib/mbedtls/tf-psa-crypto/dispatch \ + -isystem $(TOP)/lib/mbedtls/tf-psa-crypto/extras \ + -isystem $(TOP)/lib/mbedtls/tf-psa-crypto/platform \ + -isystem $(TOP)/lib/mbedtls/tf-psa-crypto/utilities \ + -DTF_PSA_CRYPTO_CONFIG_FILE='"$(TOP)/lib/mbedtls_config/tf_psa_crypto_config_hashlib.h"' \ endif @@ -856,6 +1192,12 @@ SRC_COMMON_HAL_ALL += \ hashlib/__init__.c endif +ifeq ($(CIRCUITPY_HMAC),1) +SRC_SHARED_MODULE_ALL += \ + hmac/HMAC.c \ + hmac/__init__.c +endif + ifeq ($(CIRCUITPY_RGBMATRIX),1) SRC_MOD += $(addprefix lib/protomatter/src/, \ core.c \ @@ -875,19 +1217,21 @@ $(BUILD)/lib/uzlib/tinflate.o: CFLAGS += -Wno-missing-braces -Wno-missing-protot endif # All possible sources are listed here, and are filtered by SRC_PATTERNS. -SRC_SHARED_MODULE_INTERNAL = \ +# area.c is shared by both compositors (vectorio needs the area helpers) so it is +# always compiled. +SRC_SHARED_MODULE_INTERNAL += \ $(filter $(SRC_PATTERNS), \ + _airlift/network.c \ + _airlift/socketpool.c \ + _airlift/transport.c \ displayio/bus_core.c \ displayio/display_core.c \ - os/getenv.c \ + displayio/area.c \ + epaperdisplay/epaper_core.c \ + epaperdisplay/lag_drive.c \ usb/utf16le.c \ ) -SRC_COMMON_HAL_INTERNAL = \ -$(filter $(SRC_PATTERNS), \ - _bleio/ \ -) - ifeq ($(INTERNAL_LIBM),1) SRC_LIBM = \ $(addprefix lib/,\ @@ -930,7 +1274,6 @@ endif # Sources used in all ports except unix. SRC_CIRCUITPY_COMMON = \ - shared/libc/string0.c \ shared/readline/readline.c \ lib/oofatfs/ff.c \ lib/oofatfs/ffunicode.c \ @@ -942,6 +1285,10 @@ SRC_CIRCUITPY_COMMON = \ shared/runtime/stdout_helpers.c \ shared/runtime/sys_stdio_mphal.c +ifeq ($(CIRCUITPY_LIBC_STRING0),1) +SRC_CIRCUITPY_COMMON += shared/libc/string0.c +endif + ifeq ($(CIRCUITPY_QRIO),1) SRC_CIRCUITPY_COMMON += lib/quirc/lib/decode.c lib/quirc/lib/identify.c lib/quirc/lib/quirc.c lib/quirc/lib/version_db.c $(BUILD)/lib/quirc/lib/%.o: CFLAGS += -Wno-type-limits -Wno-shadow -Wno-sign-compare -include shared-module/qrio/quirc_alloc.h diff --git a/py/circuitpy_mkenv.mk b/py/circuitpy_mkenv.mk index 7bdf943a14d..6416d6bd19c 100644 --- a/py/circuitpy_mkenv.mk +++ b/py/circuitpy_mkenv.mk @@ -43,6 +43,10 @@ ifneq ($(VALID_BOARD),) include boards/$(BOARD)/mpconfigboard.mk endif +# user-specific settings that mpconfigport does not override +# (i.e. mpconfigport.mk uses "foo ?= bar") +-include user_pre_mpconfigport.mk + # Port-specific include mpconfigport.mk @@ -52,6 +56,10 @@ ifneq ($(VALID_BOARD),) include $(TOP)/py/circuitpy_mpconfig.mk endif +# user-specific overrides of hard-coded settings +# (i.e. xxx.mk uses "foo = bar") +-include user_post_mpconfigport.mk + # qstr definitions (must come before including py.mk) QSTR_DEFS = qstrdefsport.h @@ -62,3 +70,6 @@ include $(TOP)/supervisor/supervisor.mk # Include make rules and variables common across CircuitPython builds. include $(TOP)/py/circuitpy_defns.mk + +# user specific +-include user_post_circuitpy_defns.mk diff --git a/py/circuitpy_mpconfig.h b/py/circuitpy_mpconfig.h index 42e6f1841a4..af59cf39dca 100644 --- a/py/circuitpy_mpconfig.h +++ b/py/circuitpy_mpconfig.h @@ -17,6 +17,10 @@ // Always 1: defined in circuitpy_mpconfig.mk // #define CIRCUITPY (1) +#ifndef MP_SSIZE_MAX +#define MP_SSIZE_MAX (0x7fffffff) +#endif + // REPR_C encodes qstrs, 31-bit ints, and 30-bit floats in a single 32-bit word. #ifndef MICROPY_OBJ_REPR #define MICROPY_OBJ_REPR (MICROPY_OBJ_REPR_C) @@ -37,13 +41,34 @@ extern void common_hal_mcu_enable_interrupts(void); // MicroPython-only options not used by CircuitPython, but present in various files // inherited from MicroPython, especially in extmod/ #define MICROPY_ENABLE_DYNRUNTIME (0) +#define MICROPY_HW_ENABLE_USB (0) #define MICROPY_HW_ENABLE_USB_RUNTIME_DEVICE (0) #define MICROPY_PY_BLUETOOTH (0) #define MICROPY_PY_LWIP_SLIP (0) #define MICROPY_PY_OS_DUPTERM (0) +#define MICROPY_PYEXEC_COMPILE_ONLY (0) #define MICROPY_ROM_TEXT_COMPRESSION (0) +#ifndef MICROPY_VFS_LFS1 #define MICROPY_VFS_LFS1 (0) +#endif +#ifndef MICROPY_VFS_LFS2 #define MICROPY_VFS_LFS2 (0) +#endif + +// CIRCUITPY-CHANGE: Compile-time choice of the CIRCUITPY filesystem. When 1, +// the supervisor mounts littlefs instead of FAT on the block device returned +// by supervisor_flash_*. Ports set this (and MICROPY_VFS_LFS2) from their +// board configuration; the default remains FAT. +#ifndef CIRCUITPY_FILESYSTEM_LITTLEFS +#define CIRCUITPY_FILESYSTEM_LITTLEFS (0) +#endif + +// Always turn on exit code handling +#define MICROPY_PYEXEC_ENABLE_EXIT_CODE_HANDLING (1) + +#ifndef MICROPY_GCREGS_SETJMP +#define MICROPY_GCREGS_SETJMP (0) +#endif // Sorted alphabetically for easy finding. // @@ -62,9 +87,12 @@ extern void common_hal_mcu_enable_interrupts(void); #define MICROPY_EMIT_X64 (0) #define MICROPY_ENABLE_DOC_STRING (0) #define MICROPY_ENABLE_FINALISER (1) +#define MICROPY_ENABLE_SELECTIVE_COLLECT (1) #define MICROPY_ENABLE_GC (1) #define MICROPY_ENABLE_PYSTACK (1) -#define MICROPY_TRACKED_ALLOC (CIRCUITPY_SSL_MBEDTLS) +// mbedtls allocates through m_tracked_calloc/m_tracked_free. hashlib-only ports need +// them too as of mbedtls 4.x: hashlib uses mbedtls_md_*(), which allocates on the heap. +#define MICROPY_TRACKED_ALLOC (CIRCUITPY_SSL_MBEDTLS || CIRCUITPY_HASHLIB_MBEDTLS_ONLY) #define MICROPY_ENABLE_SOURCE_LINE (1) #define MICROPY_EPOCH_IS_1970 (1) #define MICROPY_ERROR_REPORTING (CIRCUITPY_FULL_BUILD ? MICROPY_ERROR_REPORTING_NORMAL : MICROPY_ERROR_REPORTING_TERSE) @@ -82,7 +110,6 @@ extern void common_hal_mcu_enable_interrupts(void); #define MICROPY_MEM_STATS (0) #define MICROPY_MODULE_BUILTIN_INIT (1) #define MICROPY_MODULE_BUILTIN_SUBPACKAGES (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_OPT_LOAD_ATTR_FAST_PATH (CIRCUITPY_OPT_LOAD_ATTR_FAST_PATH) @@ -90,6 +117,10 @@ extern void common_hal_mcu_enable_interrupts(void); #define MICROPY_OPT_MPZ_BITWISE (0) #define MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE (CIRCUITPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE) #define MICROPY_PERSISTENT_CODE_LOAD (1) +// The ROM-reader half of MicroPython's VFS ROM support: .mpy data referenced in place, no ROM VFS. +#define MICROPY_VFS_ROM (CIRCUITPY_STORAGE_MAP_IMPORT) +#define MICROPY_VFS_ROM_IOCTL (0) +#define MICROPY_PERSISTENT_CODE_LOAD_NATIVE (CIRCUITPY_LOAD_NATIVE || CIRCUITPY_ENABLE_MPY_NATIVE) #define MICROPY_PY_ARRAY (CIRCUITPY_ARRAY) #define MICROPY_PY_ARRAY_SLICE_ASSIGN (1) @@ -135,13 +166,20 @@ extern void common_hal_mcu_enable_interrupts(void); #define MICROPY_PY_RE (CIRCUITPY_RE) // Supplanted by shared-bindings/struct #define MICROPY_PY_STRUCT (0) +#define MICROPY_PY_STRUCT_UNSAFE_TYPECODES (0) #define MICROPY_PY_SYS (CIRCUITPY_SYS) #define MICROPY_PY_SYS_MAXSIZE (1) #define MICROPY_PY_SYS_STDFILES (1) #define MICROPY_PY_UCTYPES (0) #define MICROPY_PY___FILE__ (1) +#if CIRCUITPY_FULL_BUILD +#ifndef MICROPY_QSTR_BYTES_IN_HASH #define MICROPY_QSTR_BYTES_IN_HASH (1) +#endif +#else +#define MICROPY_QSTR_BYTES_IN_HASH (0) +#endif #define MICROPY_REPL_AUTO_INDENT (1) #define MICROPY_REPL_EVENT_DRIVEN (0) #define MICROPY_STACK_CHECK (1) @@ -169,6 +207,9 @@ extern void common_hal_mcu_enable_interrupts(void); #define FILESYSTEM_BLOCK_SIZE (512) #define MICROPY_VFS (1) +// CIRCUITPY-CHANGE: CircuitPython's flash/SD block devices are native +// (supervisor/shared/flash.c sets MP_BLOCKDEV_FLAG_NATIVE). +#define MICROPY_VFS_BLOCKDEV_NATIVE (1) #define MICROPY_VFS_FAT (MICROPY_VFS) #define MICROPY_READER_VFS (MICROPY_VFS) @@ -176,26 +217,16 @@ extern void common_hal_mcu_enable_interrupts(void); #define BYTES_PER_WORD (4) +// Bit 0 of a code pointer selects the Thumb instruction set. +#if defined(__thumb__) #define MICROPY_MAKE_POINTER_CALLABLE(p) ((void *)((mp_uint_t)(p) | 1)) +#else +#define MICROPY_MAKE_POINTER_CALLABLE(p) ((void *)(p)) +#endif // Track stack usage. Expose results via ustack module. #define MICROPY_MAX_STACK_USAGE (0) -#define UINT_FMT "%u" -#define INT_FMT "%d" -#ifdef __LP64__ -typedef long mp_int_t; // must be pointer size -typedef unsigned long mp_uint_t; // must be pointer size -#else -// These are definitions for machines where sizeof(int) == sizeof(void*), -// regardless of actual size. -typedef int mp_int_t; // must be pointer size -typedef unsigned int mp_uint_t; // must be pointer size -#endif -#if __GNUC__ >= 10 // on recent gcc versions we can check that this is so -_Static_assert(sizeof(mp_int_t) == sizeof(void *)); -_Static_assert(sizeof(mp_uint_t) == sizeof(void *)); -#endif typedef long mp_off_t; #define MP_PLAT_PRINT_STRN(str, len) mp_hal_stdout_tx_strn_cooked(str, len) @@ -228,6 +259,11 @@ typedef long mp_off_t; #define MICROPY_CPYTHON_EXCEPTION_CHAIN (CIRCUITPY_FULL_BUILD) #endif +// Allow %e/%f/%g in mp_printf(). +#ifndef MICROPY_PRINTF_FLOAT +#define MICROPY_PRINTF_FLOAT (CIRCUITPY_FULL_BUILD && MICROPY_PY_BUILTINS_FLOAT) +#endif + #define MICROPY_PY_BUILTINS_POW3 (CIRCUITPY_BUILTINS_POW3) #define MICROPY_PY_FSTRINGS (1) #define MICROPY_MODULE_WEAK_LINKS (0) @@ -257,6 +293,14 @@ typedef long mp_off_t; #define MICROPY_PY_COLLECTIONS_DEQUE_SUBSCR (CIRCUITPY_FULL_BUILD) #endif +#ifndef MICROPY_PY_DELATTR_SETATTR +#define MICROPY_PY_DELATTR_SETATTR (CIRCUITPY_FULL_BUILD) +#endif + +#ifndef MICROPY_PY_DOUBLE_TYPECODE +#define MICROPY_PY_DOUBLE_TYPECODE (CIRCUITPY_FULL_BUILD ? 1 : 0) +#endif + #ifndef MICROPY_PY_FUNCTION_ATTRS #define MICROPY_PY_FUNCTION_ATTRS (CIRCUITPY_FULL_BUILD) #endif @@ -287,12 +331,10 @@ typedef long mp_off_t; #ifdef LONGINT_IMPL_MPZ #define MICROPY_LONGINT_IMPL (MICROPY_LONGINT_IMPL_MPZ) -#define MP_SSIZE_MAX (0x7fffffff) #endif #ifdef LONGINT_IMPL_LONGLONG #define MICROPY_LONGINT_IMPL (MICROPY_LONGINT_IMPL_LONGLONG) -#define MP_SSIZE_MAX (0x7fffffff) #endif #ifndef MICROPY_PY_REVERSE_SPECIAL_METHODS @@ -305,10 +347,17 @@ typedef long mp_off_t; // Default board buses. +#ifndef CIRCUITPY_MUTABLE_BOARD +#define CIRCUITPY_MUTABLE_BOARD (0) +#endif + #ifndef CIRCUITPY_BOARD_I2C #if defined(DEFAULT_I2C_BUS_SCL) && defined(DEFAULT_I2C_BUS_SDA) #define CIRCUITPY_BOARD_I2C (1) #define CIRCUITPY_BOARD_I2C_PIN {{.scl = DEFAULT_I2C_BUS_SCL, .sda = DEFAULT_I2C_BUS_SDA}} +#ifndef CIRCUITPY_BOARD_I2C_SPEED +#define CIRCUITPY_BOARD_I2C_SPEED (100000) +#endif #else #define CIRCUITPY_BOARD_I2C (0) #endif @@ -333,6 +382,9 @@ typedef long mp_off_t; #endif +// For easy debugging printf's. +#define PLAT_PRINTF(...) mp_printf(&mp_plat_print, __VA_ARGS__) + #if MICROPY_PY_ASYNC_AWAIT && !CIRCUITPY_TRACEBACK #error CIRCUITPY_ASYNCIO requires CIRCUITPY_TRACEBACK #endif @@ -344,6 +396,7 @@ typedef long mp_off_t; #define CIRCUITPY_CONSOLE_UART (1) #ifndef CIRCUITPY_CONSOLE_UART_BAUDRATE #define CIRCUITPY_CONSOLE_UART_BAUDRATE (115200) +#endif #if !defined(CIRCUITPY_CONSOLE_UART_PRINTF) #define CIRCUITPY_CONSOLE_UART_PRINTF(...) mp_printf(&console_uart_print, __VA_ARGS__) #endif @@ -353,13 +406,22 @@ typedef long mp_off_t; #if !defined(CIRCUITPY_CONSOLE_UART_TIMESTAMP) #define CIRCUITPY_CONSOLE_UART_TIMESTAMP (0) #endif -#endif #else #define CIRCUITPY_CONSOLE_UART (0) #define CIRCUITPY_CONSOLE_UART_PRINTF(...) (void)0 #define CIRCUITPY_CONSOLE_UART_HEXDUMP(...) (void)0 #endif +// Normally set from CIRCUITPY_BUSIO_SPI_ASYNC in the .mk files. +#ifndef CIRCUITPY_BUSIO_SPI_ASYNC +#define CIRCUITPY_BUSIO_SPI_ASYNC (0) +#endif + +// Normally set from CIRCUITPY_EPAPERDISPLAY_FAST in the .mk files. zephyr-cp doesn't set it. +#ifndef CIRCUITPY_EPAPERDISPLAY_FAST +#define CIRCUITPY_EPAPERDISPLAY_FAST (0) +#endif + // These CIRCUITPY_xxx values should all be defined in the *.mk files as being on or off. // So if any are not defined in *.mk, they'll throw an error here. @@ -368,14 +430,13 @@ typedef long mp_off_t; #define CIRCUITPY_DISPLAY_LIMIT (1) #endif -// Framebuffer area size in bytes. Rounded down to power of four for alignment. +// Normally set from CIRCUITPY_DISPLAY_AREA_BUFFER_SIZE in the .mk files. #ifndef CIRCUITPY_DISPLAY_AREA_BUFFER_SIZE -#define CIRCUITPY_DISPLAY_AREA_BUFFER_SIZE (128) +#define CIRCUITPY_DISPLAY_AREA_BUFFER_SIZE (512) #endif #else #define CIRCUITPY_DISPLAY_LIMIT (0) -#define CIRCUITPY_DISPLAY_AREA_BUFFER_SIZE (0) #endif // This is not a top-level module; it's microcontroller.nvm. @@ -392,6 +453,19 @@ extern const struct _mp_obj_module_t nvm_module; #define ULAB_NUMPY_HAS_RANDOM_MODULE (0) #endif +// The scipy.integrate module is about 6 kB. +#ifndef ULAB_SCIPY_HAS_INTEGRATE_MODULE +#define ULAB_SCIPY_HAS_INTEGRATE_MODULE (0) +#endif + +// The ndarray modulo operators are about 4 kB. +#ifndef NDARRAY_HAS_BINARY_OP_MODULO +#define NDARRAY_HAS_BINARY_OP_MODULO (0) +#endif +#ifndef NDARRAY_HAS_INPLACE_MODULO +#define NDARRAY_HAS_INPLACE_MODULO (0) +#endif + #if CIRCUITPY_ULAB // ulab requires reverse special methods #if defined(MICROPY_PY_REVERSE_SPECIAL_METHODS) && !MICROPY_PY_REVERSE_SPECIAL_METHODS @@ -441,6 +515,11 @@ void background_callback_run_all(void); #define MICROPY_VM_HOOK_LOOP RUN_BACKGROUND_TASKS; #define MICROPY_VM_HOOK_RETURN RUN_BACKGROUND_TASKS; +#define MICROPY_INTERNAL_EVENT_HOOK (RUN_BACKGROUND_TASKS) + +#ifndef CIRCUITPY_AUDIOMIXER_USE_PORT_MIX +#define CIRCUITPY_AUDIOMIXER_USE_PORT_MIX (0) +#endif // CIRCUITPY_AUTORELOAD_DELAY_MS = 0 will completely disable autoreload. #ifndef CIRCUITPY_AUTORELOAD_DELAY_MS @@ -452,7 +531,7 @@ void background_callback_run_all(void); #endif #ifndef CIRCUITPY_PYSTACK_SIZE -#define CIRCUITPY_PYSTACK_SIZE 1536 +#define CIRCUITPY_PYSTACK_SIZE 2048 #endif // The VM heap starts at this size and doubles in size as needed until it runs @@ -480,6 +559,12 @@ void background_callback_run_all(void); #define CIRCUITPY_STATUS_LED_POWER_INVERTED (0) #endif +// Byte order of the status NeoPixel. Most WS2812s take GRB. Boards whose LED takes RGB set +// this to STATUS_NEOPIXEL_ORDER_RGB, from supervisor/shared/status_leds.h. +#ifndef MICROPY_HW_NEOPIXEL_ORDER +#define MICROPY_HW_NEOPIXEL_ORDER (STATUS_NEOPIXEL_ORDER_GRB) +#endif + #define CIRCUITPY_BOOT_OUTPUT_FILE "/boot_out.txt" #ifndef CIRCUITPY_BOOT_COUNTER @@ -501,6 +586,23 @@ void background_callback_run_all(void); // USB settings +#ifndef CIRCUITPY_SDCARD_USB +#if CIRCUITPY_USB_DEVICE +#define CIRCUITPY_SDCARD_USB (CIRCUITPY_SDCARDIO && CIRCUITPY_USB_MSC) +// Default value of CIRCUITPY_SDCARD_USB in settings.toml. +#ifndef CIRCUITPY_SDCARD_USB_DEFAULT +// True for most boards. +#define CIRCUITPY_SDCARD_USB_DEFAULT (true) +#endif +#else +#define CIRCUITPY_SDCARD_USB (0) +#endif +#endif + +#if CIRCUITPY_SDCARD_USB && !(CIRCUITPY_SDCARDIO) +#error CIRCUITPY_SDCARD_USB requires CIRCUITPY_SDCARDIO +#endif + // Debug level for TinyUSB. Only outputs over debug UART so it doesn't cause // additional USB logging. #ifndef CIRCUITPY_DEBUG_TINYUSB @@ -511,10 +613,41 @@ void background_callback_run_all(void); #define CIRCUITPY_USB_DEVICE_INSTANCE 0 #endif +#ifndef CIRCUITPY_USB_DEVICE_HIGH_SPEED +#define CIRCUITPY_USB_DEVICE_HIGH_SPEED 0 +#endif + #ifndef CIRCUITPY_USB_HOST_INSTANCE #define CIRCUITPY_USB_HOST_INSTANCE -1 #endif +#ifndef CIRCUITPY_USB_HOST_HIGH_SPEED +#define CIRCUITPY_USB_HOST_HIGH_SPEED 0 +#endif + +// The host controller keeps receiving isochronous IN packets between +// transfers, in a buffer from common_hal_usb_host_port_claim_iso_buffer(), and +// hands them over as records: a little endian uint16_t length, then the +// packet. +#ifndef CIRCUITPY_USB_HOST_ISO_RECORDS +#define CIRCUITPY_USB_HOST_ISO_RECORDS (0) +#endif + +// The port runs tuh_task() in a task of its own rather than from +// usb_background(), so that it runs while the VM is busy. +#ifndef CIRCUITPY_USB_HOST_TASK +#define CIRCUITPY_USB_HOST_TASK (0) +#endif + +// usb_host_bulk takes a usb.core.Device and uses TinyUSB host calls. +#if CIRCUITPY_USB_HOST_BULK && !(CIRCUITPY_USB_HOST && CIRCUITPY_PYUSB) +#error CIRCUITPY_USB_HOST_BULK requires CIRCUITPY_USB_HOST and CIRCUITPY_PYUSB +#endif + +#if CIRCUITPY_PICOGAME3D && !CIRCUITPY_PICOGAME +#error CIRCUITPY_PICOGAME3D requires CIRCUITPY_PICOGAME +#endif + // If the port requires certain USB endpoint numbers, define these in mpconfigport.h. #ifndef USB_CDC_EP_NUM_NOTIFICATION @@ -614,7 +747,7 @@ void background_callback_run_all(void); // Align the internal sector buffer. Useful when it is passed into TinyUSB for // loads. #ifndef MICROPY_FATFS_WINDOW_ALIGNMENT -#define MICROPY_FATFS_WINDOW_ALIGNMENT CIRCUITPY_TUSB_MEM_ALIGN +#define MICROPY_FATFS_WINDOW_ALIGNMENT 64 // Espressif is strictest #endif #define FF_FS_CASE_INSENSITIVE_COMPARISON_ASCII_ONLY (1) @@ -628,13 +761,29 @@ void background_callback_run_all(void); #define MICROPY_PY_BUILTINS_COMPILE (1) #ifndef CIRCUITPY_MIN_GCC_VERSION -#define CIRCUITPY_MIN_GCC_VERSION 13 +#define CIRCUITPY_MIN_GCC_VERSION 14 #endif #ifndef CIRCUITPY_SAVES_PARTITION_SIZE #define CIRCUITPY_SAVES_PARTITION_SIZE 0 #endif +// Boards that have a boot button connected to a GPIO pin should set +// CIRCUITPY_BOOT_BUTTON_NO_GPIO to 1. +#ifndef CIRCUITPY_BOOT_BUTTON_NO_GPIO +#define CIRCUITPY_BOOT_BUTTON_NO_GPIO (0) +#endif +#if defined(CIRCUITPY_BOOT_BUTTON) && CIRCUITPY_BOOT_BUTTON_NO_GPIO +#error "CIRCUITPY_BOOT_BUTTON and CIRCUITPY_BOOT_BUTTON_NO_GPIO are mutually exclusive" +#endif + +// Boards that define CIRCUITPY_BOOT_BUTTON can set +// CIRCUITPY_BOOT_BUTTON_ACTIVE_HIGH to 1 when the button pin reads high while +// pressed. The default is active-low (the pin reads low while pressed). +#ifndef CIRCUITPY_BOOT_BUTTON_ACTIVE_HIGH +#define CIRCUITPY_BOOT_BUTTON_ACTIVE_HIGH (0) +#endif + #if defined(__GNUC__) && !defined(__ZEPHYR__) #if __GNUC__ < CIRCUITPY_MIN_GCC_VERSION // (the 3 level scheme here is required to get expansion & stringization diff --git a/py/circuitpy_mpconfig.mk b/py/circuitpy_mpconfig.mk old mode 100644 new mode 100755 index 831c1ec245f..b92ae6c1284 --- a/py/circuitpy_mpconfig.mk +++ b/py/circuitpy_mpconfig.mk @@ -62,6 +62,15 @@ CFLAGS += -DCIRCUITPY_FULL_BUILD=$(CIRCUITPY_FULL_BUILD) # increased build time CIRCUITPY_MESSAGE_COMPRESSION_LEVEL ?= 9 +# By default, use our copy of TLSF. Some vendor SDKs may provide their own +# implementation of TLSF, which can be used instead by setting CIRCUITPY_LIB_TLSF=0. +CIRCUITPY_LIB_TLSF ?= 1 + +# By default, use our copy of string0 (memcpy and friends) because it is optimized. Some vendor SDKs +# or ROMs may provide their own implementation of string0, which can be used instead by setting +# CIRCUITPY_LIBC_STRING0=0. +CIRCUITPY_LIBC_STRING0 ?= 1 + # Reduce the size of in-flash properties. Requires support in the .ld linker # file, so not enabled by default. CIRCUITPY_OPTIMIZE_PROPERTY_FLASH_SIZE ?= 0 @@ -90,14 +99,28 @@ CFLAGS += -DMICROPY_PY_SELECT_SELECT=$(MICROPY_PY_SELECT_SELECT) CIRCUITPY_AESIO ?= $(CIRCUITPY_FULL_BUILD) CFLAGS += -DCIRCUITPY_AESIO=$(CIRCUITPY_AESIO) +# An ESP32 co-processor running nina-fw, shared by the core and ESP32SPI (`_airlift`). +# Not part of CIRCUITPY_NETWORK, which would also turn on ssl, ipaddress and so on. +CIRCUITPY_AIRLIFT ?= 0 +CFLAGS += -DCIRCUITPY_AIRLIFT=$(CIRCUITPY_AIRLIFT) + # TODO: CIRCUITPY_ALARM will gradually be added to as many ports as possible # so make this 1 or CIRCUITPY_FULL_BUILD eventually CIRCUITPY_ALARM ?= 0 CFLAGS += -DCIRCUITPY_ALARM=$(CIRCUITPY_ALARM) +# Whether `alarm.exit_and_deep_sleep_until_alarms()` supports `preserve_dios`. +CIRCUITPY_ALARM_PRESERVE_DIOS ?= 0 +CFLAGS += -DCIRCUITPY_ALARM_PRESERVE_DIOS=$(CIRCUITPY_ALARM_PRESERVE_DIOS) + CIRCUITPY_ALARM_TOUCH ?= $(CIRCUITPY_ALARM) CFLAGS += -DCIRCUITPY_ALARM_TOUCH=$(CIRCUITPY_ALARM_TOUCH) +# Enable DMA buffer management for platforms where not all memory is DMA-capable +# Platforms with PSRAM or other non-DMA memory should set this to 0 +CIRCUITPY_ALL_MEMORY_DMA_CAPABLE ?= 1 +CFLAGS += -DCIRCUITPY_ALL_MEMORY_DMA_CAPABLE=$(CIRCUITPY_ALL_MEMORY_DMA_CAPABLE) + CIRCUITPY_ANALOGBUFIO ?= 0 CFLAGS += -DCIRCUITPY_ANALOGBUFIO=$(CIRCUITPY_ANALOGBUFIO) @@ -107,6 +130,10 @@ CFLAGS += -DCIRCUITPY_ANALOGIO=$(CIRCUITPY_ANALOGIO) CIRCUITPY_ARRAY ?= 1 CFLAGS += -DCIRCUITPY_ARRAY=$(CIRCUITPY_ARRAY) +# A port with async SPI: the async_spi module, and busio.SPI built on the same implementation. +CIRCUITPY_ASYNC_SPI ?= 0 +CFLAGS += -DCIRCUITPY_ASYNC_SPI=$(CIRCUITPY_ASYNC_SPI) + CIRCUITPY_ATEXIT ?= $(CIRCUITPY_FULL_BUILD) CFLAGS += -DCIRCUITPY_ATEXIT=$(CIRCUITPY_ATEXIT) @@ -121,6 +148,10 @@ CFLAGS += -DCIRCUITPY_AUDIOBUSIO_I2SOUT=$(CIRCUITPY_AUDIOBUSIO_I2SOUT) CIRCUITPY_AUDIOBUSIO_PDMIN ?= $(CIRCUITPY_AUDIOBUSIO) CFLAGS += -DCIRCUITPY_AUDIOBUSIO_PDMIN=$(CIRCUITPY_AUDIOBUSIO_PDMIN) +# I2S audio input (separate core module `audioi2sin`). +CIRCUITPY_AUDIOI2SIN ?= 0 +CFLAGS += -DCIRCUITPY_AUDIOI2SIN=$(CIRCUITPY_AUDIOI2SIN) + CIRCUITPY_AUDIOIO ?= $(CIRCUITPY_FULL_BUILD) CFLAGS += -DCIRCUITPY_AUDIOIO=$(CIRCUITPY_AUDIOIO) @@ -133,6 +164,10 @@ CFLAGS += -DCIRCUITPY_AUDIOCORE=$(CIRCUITPY_AUDIOCORE) CIRCUITPY_AUDIOMIXER ?= $(CIRCUITPY_AUDIOCORE) CFLAGS += -DCIRCUITPY_AUDIOMIXER=$(CIRCUITPY_AUDIOMIXER) +# Mix 16-bit audio with the port's vector code. Ports that have it turn it on. +CIRCUITPY_AUDIOMIXER_USE_PORT_MIX ?= 0 +CFLAGS += -DCIRCUITPY_AUDIOMIXER_USE_PORT_MIX=$(CIRCUITPY_AUDIOMIXER_USE_PORT_MIX) + ifndef CIRCUITPY_AUDIOCORE_DEBUG CIRCUITPY_AUDIOCORE_DEBUG ?= 0 endif @@ -141,11 +176,21 @@ CFLAGS += -DCIRCUITPY_AUDIOCORE_DEBUG=$(CIRCUITPY_AUDIOCORE_DEBUG) CIRCUITPY_AUDIOMP3 ?= $(call enable-if-all,$(CIRCUITPY_FULL_BUILD) $(CIRCUITPY_AUDIOCORE)) CFLAGS += -DCIRCUITPY_AUDIOMP3=$(CIRCUITPY_AUDIOMP3) +CIRCUITPY_AUDIOSPEED ?= 0 +CFLAGS += -DCIRCUITPY_AUDIOSPEED=$(CIRCUITPY_AUDIOSPEED) + CIRCUITPY_AUDIOEFFECTS ?= 0 CIRCUITPY_AUDIODELAYS ?= $(CIRCUITPY_AUDIOEFFECTS) CFLAGS += -DCIRCUITPY_AUDIODELAYS=$(CIRCUITPY_AUDIODELAYS) CIRCUITPY_AUDIOFILTERS ?= $(CIRCUITPY_AUDIOEFFECTS) CFLAGS += -DCIRCUITPY_AUDIOFILTERS=$(CIRCUITPY_AUDIOFILTERS) +CIRCUITPY_AUDIOFREEVERB ?= $(CIRCUITPY_AUDIOEFFECTS) +CFLAGS += -DCIRCUITPY_AUDIOFREEVERB=$(CIRCUITPY_AUDIOFREEVERB) +CIRCUITPY_AUDIOTAP ?= $(CIRCUITPY_AUDIOEFFECTS) +CFLAGS += -DCIRCUITPY_AUDIOTAP=$(CIRCUITPY_AUDIOTAP) + +CIRCUITPY_AUDIOFILEWRITER ?= 0 +CFLAGS += -DCIRCUITPY_AUDIOFILEWRITER=$(CIRCUITPY_AUDIOFILEWRITER) CIRCUITPY_AURORA_EPAPER ?= 0 CFLAGS += -DCIRCUITPY_AURORA_EPAPER=$(CIRCUITPY_AURORA_EPAPER) @@ -162,12 +207,19 @@ CFLAGS += -DCIRCUITPY_BITBANGIO=$(CIRCUITPY_BITBANGIO) CIRCUITPY_BITOPS ?= 0 CFLAGS += -DCIRCUITPY_BITOPS=$(CIRCUITPY_BITOPS) -# _bleio can be supported on most any board via HCI +# _bleio defaults to HCI serial for all full builds. CIRCUITPY_BLEIO_HCI ?= $(CIRCUITPY_FULL_BUILD) CFLAGS += -DCIRCUITPY_BLEIO_HCI=$(CIRCUITPY_BLEIO_HCI) -# Explicitly enabled for boards that support _bleio. -CIRCUITPY_BLEIO ?= $(CIRCUITPY_BLEIO_HCI) +# Native (i.e., on SoC or board) BLE support is off by default. +CIRCUITPY_BLEIO_NATIVE ?= 0 +CFLAGS += -DCIRCUITPY_BLEIO_NATIVE=$(CIRCUITPY_BLEIO_NATIVE) + +ifeq ($(CIRCUITPY_BLEIO_HCI)$(CIRCUITPY_BLEIO_NATIVE),11) +$(error "CIRCUITPY_BLEIO_HCI and CIRCUITPY_BLEIO_NATIVE cannot both be enabled") +endif + +CIRCUITPY_BLEIO ?= $(call enable-if-any,$(CIRCUITPY_BLEIO_HCI) $(CIRCUITPY_BLEIO_NATIVE)) CFLAGS += -DCIRCUITPY_BLEIO=$(CIRCUITPY_BLEIO) CIRCUITPY_BLE_FILE_SERVICE ?= 0 @@ -194,6 +246,11 @@ CFLAGS += -DCIRCUITPY_BUSIO_I2C=$(CIRCUITPY_BUSIO_I2C) CIRCUITPY_BUSIO_SPI ?= $(CIRCUITPY_BUSIO) CFLAGS += -DCIRCUITPY_BUSIO_SPI=$(CIRCUITPY_BUSIO_SPI) +# The port implements common_hal_busio_spi_write_start() and common_hal_busio_spi_end(), so a +# display on a FourWire bus can send one strip while the next is being composited. +CIRCUITPY_BUSIO_SPI_ASYNC ?= $(CIRCUITPY_ASYNC_SPI) +CFLAGS += -DCIRCUITPY_BUSIO_SPI_ASYNC=$(CIRCUITPY_BUSIO_SPI_ASYNC) + CIRCUITPY_BUSIO_UART ?= $(CIRCUITPY_BUSIO) CFLAGS += -DCIRCUITPY_BUSIO_UART=$(CIRCUITPY_BUSIO_UART) @@ -212,12 +269,21 @@ CFLAGS += -DCIRCUITPY_COLLECTIONS=$(CIRCUITPY_COLLECTIONS) CIRCUITPY_COMPUTED_GOTO_SAVE_SPACE ?= 0 CFLAGS += -DCIRCUITPY_COMPUTED_GOTO_SAVE_SPACE=$(CIRCUITPY_COMPUTED_GOTO_SAVE_SPACE) +CIRCUITPY_CRYPTOGRAPHY ?= 0 +CFLAGS += -DCIRCUITPY_CRYPTOGRAPHY=$(CIRCUITPY_CRYPTOGRAPHY) + CIRCUITPY_CYW43 ?= 0 CFLAGS += -DCIRCUITPY_CYW43=$(CIRCUITPY_CYW43) CIRCUITPY_DIGITALIO ?= 1 CFLAGS += -DCIRCUITPY_DIGITALIO=$(CIRCUITPY_DIGITALIO) +# Enable the DigitalInOut protocol on the native DigitalInOut type. +# This allows other C code to use DigitalInOut objects polymorphically. +# Disable on small builds to save space. +CIRCUITPY_DIGITALINOUT_PROTOCOL ?= $(CIRCUITPY_FULL_BUILD) +CFLAGS += -DCIRCUITPY_DIGITALINOUT_PROTOCOL=$(CIRCUITPY_DIGITALINOUT_PROTOCOL) + CIRCUITPY_COPROC ?= 0 CFLAGS += -DCIRCUITPY_COPROC=$(CIRCUITPY_COPROC) @@ -227,15 +293,34 @@ CFLAGS += -DCIRCUITPY_COUNTIO=$(CIRCUITPY_COUNTIO) CIRCUITPY_DISPLAYIO ?= $(CIRCUITPY_FULL_BUILD) CFLAGS += -DCIRCUITPY_DISPLAYIO=$(CIRCUITPY_DISPLAYIO) +# Select the displayio compositing core implementation: 0 = legacy scanline core (default), +# 1 = LVGL-based core (shared-module/displayio/lvgl). The LVGL variant requires LVGL be +# available to the port at build time. +CIRCUITPY_DISPLAYIO_LVGL ?= 0 +CFLAGS += -DCIRCUITPY_DISPLAYIO_LVGL=$(CIRCUITPY_DISPLAYIO_LVGL) + +# Stack bytes a display refresh composes at once. Bigger means fewer, larger pieces per refresh. +CIRCUITPY_DISPLAY_AREA_BUFFER_SIZE ?= 512 +CFLAGS += -DCIRCUITPY_DISPLAY_AREA_BUFFER_SIZE=$(CIRCUITPY_DISPLAY_AREA_BUFFER_SIZE) + CIRCUITPY_BUSDISPLAY ?= $(CIRCUITPY_DISPLAYIO) CFLAGS += -DCIRCUITPY_BUSDISPLAY=$(CIRCUITPY_BUSDISPLAY) CIRCUITPY_FOURWIRE ?= $(CIRCUITPY_DISPLAYIO) CFLAGS += -DCIRCUITPY_FOURWIRE=$(CIRCUITPY_FOURWIRE) +# QSPI bus protocol for quad-SPI displays (like RM690B0) +CIRCUITPY_QSPIBUS ?= 0 +CFLAGS += -DCIRCUITPY_QSPIBUS=$(CIRCUITPY_QSPIBUS) + CIRCUITPY_EPAPERDISPLAY ?= $(CIRCUITPY_DISPLAYIO) CFLAGS += -DCIRCUITPY_EPAPERDISPLAY=$(CIRCUITPY_EPAPERDISPLAY) +# Fast e-paper updates: EPaperDisplay's write_previous_ram_command, fast, lag_frames +# and clean(). Ports and boards short on flash turn it off. +CIRCUITPY_EPAPERDISPLAY_FAST ?= $(CIRCUITPY_EPAPERDISPLAY) +CFLAGS += -DCIRCUITPY_EPAPERDISPLAY_FAST=$(CIRCUITPY_EPAPERDISPLAY_FAST) + CIRCUITPY_I2CDISPLAYBUS ?= $(CIRCUITPY_DISPLAYIO) CFLAGS += -DCIRCUITPY_I2CDISPLAYBUS=$(CIRCUITPY_I2CDISPLAYBUS) @@ -259,19 +344,32 @@ CFLAGS += -DCIRCUITPY_BITMAPTOOLS=$(CIRCUITPY_BITMAPTOOLS) CFLAGS += -DCIRCUITPY_FRAMEBUFFERIO=$(CIRCUITPY_FRAMEBUFFERIO) CFLAGS += -DCIRCUITPY_VECTORIO=$(CIRCUITPY_VECTORIO) +# Faster bitmaptools.rotozoom for unrotated exact scales. Costs about 1 KB of flash, so +# ports turn it on. +CIRCUITPY_BITMAPTOOLS_FAST_ROTOZOOM ?= 0 +CFLAGS += -DCIRCUITPY_BITMAPTOOLS_FAST_ROTOZOOM=$(CIRCUITPY_BITMAPTOOLS_FAST_ROTOZOOM) + CIRCUITPY_DUALBANK ?= 0 CFLAGS += -DCIRCUITPY_DUALBANK=$(CIRCUITPY_DUALBANK) +# eMMC block device. Only nordic implements it. +CIRCUITPY_EMMCIO ?= 0 +CFLAGS += -DCIRCUITPY_EMMCIO=$(CIRCUITPY_EMMCIO) + +# Mount the eMMC at boot and expose it over USB MSC. +CIRCUITPY_EMMC_USB ?= $(CIRCUITPY_EMMCIO) +CFLAGS += -DCIRCUITPY_EMMC_USB=$(CIRCUITPY_EMMC_USB) + # Enabled micropython.native decorator (experimental) CIRCUITPY_ENABLE_MPY_NATIVE ?= 0 CFLAGS += -DCIRCUITPY_ENABLE_MPY_NATIVE=$(CIRCUITPY_ENABLE_MPY_NATIVE) -CIRCUITPY_OS_GETENV ?= $(CIRCUITPY_FULL_BUILD) -CFLAGS += -DCIRCUITPY_OS_GETENV=$(CIRCUITPY_OS_GETENV) - CIRCUITPY_ERRNO ?= $(CIRCUITPY_FULL_BUILD) CFLAGS += -DCIRCUITPY_ERRNO=$(CIRCUITPY_ERRNO) +CIRCUITPY_MII ?= 0 +CFLAGS += -DCIRCUITPY_MII=$(CIRCUITPY_MII) + # Espressif specific modules. # Assume not an Espressif build. CIRCUITPY_ESPIDF ?= 0 @@ -320,9 +418,21 @@ CFLAGS += -DCIRCUITPY_HASHLIB_MBEDTLS=$(CIRCUITPY_HASHLIB_MBEDTLS) CIRCUITPY_HASHLIB_MBEDTLS_ONLY ?= $(call enable-if-all,$(CIRCUITPY_HASHLIB_MBEDTLS) $(call enable-if-not,$(CIRCUITPY_SSL))) CFLAGS += -DCIRCUITPY_HASHLIB_MBEDTLS_ONLY=$(CIRCUITPY_HASHLIB_MBEDTLS_ONLY) +# hmac: CPython-compatible HMAC, backed by PSA Crypto. Available wherever a full PSA +# crypto build with HMAC is already present (SSL builds, espressif's ESP-IDF mbedtls); +# the HASHLIB_MBEDTLS_ONLY subset does not include the PSA MAC driver yet. +CIRCUITPY_HMAC ?= $(call enable-if-all,$(CIRCUITPY_HASHLIB_MBEDTLS) $(call enable-if-not,$(CIRCUITPY_HASHLIB_MBEDTLS_ONLY))) +CFLAGS += -DCIRCUITPY_HMAC=$(CIRCUITPY_HMAC) + +# Always zero because it is for Zephyr only +CFLAGS += -DCIRCUITPY_HOSTNETWORK=0 + CIRCUITPY_I2CTARGET ?= $(CIRCUITPY_FULL_BUILD) CFLAGS += -DCIRCUITPY_I2CTARGET=$(CIRCUITPY_I2CTARGET) +CIRCUITPY_I2CIOEXPANDER ?= 0 +CFLAGS += -DCIRCUITPY_I2CIOEXPANDER=$(CIRCUITPY_I2CIOEXPANDER) + CIRCUITPY_IMAGECAPTURE ?= 0 CFLAGS += -DCIRCUITPY_IMAGECAPTURE=$(CIRCUITPY_IMAGECAPTURE) @@ -334,7 +444,7 @@ CFLAGS += -DCIRCUITPY_IO=$(CIRCUITPY_IO) CIRCUITPY_IO_IOBASE ?= $(call enable-if-all,$(CIRCUITPY_IO) $(CIRCUITPY_JPEGIO)) CFLAGS += -DCIRCUITPY_IO_IOBASE=$(CIRCUITPY_IO_IOBASE) -CIRCUITPY_IPADDRESS ?= $(CIRCUITPY_WIFI) +CIRCUITPY_IPADDRESS ?= $(CIRCUITPY_NETWORK) CFLAGS += -DCIRCUITPY_IPADDRESS=$(CIRCUITPY_IPADDRESS) CIRCUITPY_IS31FL3741 ?= 0 @@ -343,6 +453,14 @@ CFLAGS += -DCIRCUITPY_IS31FL3741=$(CIRCUITPY_IS31FL3741) CIRCUITPY_JPEGIO ?= $(CIRCUITPY_BITMAPTOOLS) CFLAGS += -DCIRCUITPY_JPEGIO=$(CIRCUITPY_JPEGIO) +# Port provides a hardware JPEG decode path for jpegio. +CIRCUITPY_JPEGIO_HW ?= 0 +CFLAGS += -DCIRCUITPY_JPEGIO_HW=$(CIRCUITPY_JPEGIO_HW) + +# A port can supply a faster JPEG decoder. Off unless the port turns it on. +CIRCUITPY_JPEGIO_FAST ?= 0 +CFLAGS += -DCIRCUITPY_JPEGIO_FAST=$(CIRCUITPY_JPEGIO_FAST) + CIRCUITPY_JSON ?= $(CIRCUITPY_FULL_BUILD) CFLAGS += -DCIRCUITPY_JSON=$(CIRCUITPY_JSON) @@ -361,6 +479,9 @@ CFLAGS += -DCIRCUITPY_KEYPAD_SHIFTREGISTERKEYS=$(CIRCUITPY_KEYPAD_SHIFTREGISTERK CIRCUITPY_KEYPAD_DEMUX ?= $(CIRCUITPY_KEYPAD) CFLAGS += -DCIRCUITPY_KEYPAD_DEMUX=$(CIRCUITPY_KEYPAD_DEMUX) +CIRCUITPY_LOAD_NATIVE ?= 0 +CFLAGS += -DCIRCUITPY_LOAD_NATIVE=$(CIRCUITPY_LOAD_NATIVE) + CIRCUITPY_LOCALE ?= $(CIRCUITPY_FULL_BUILD) CFLAGS += -DCIRCUITPY_LOCALE=$(CIRCUITPY_LOCALE) @@ -370,6 +491,10 @@ CFLAGS += -DCIRCUITPY_MATH=$(CIRCUITPY_MATH) CIRCUITPY_MAX3421E ?= 0 CFLAGS += -DCIRCUITPY_MAX3421E=$(CIRCUITPY_MAX3421E) +# mdns requires the wifi module, so it can only default on with wifi. +CIRCUITPY_MDNS ?= $(CIRCUITPY_WIFI) +CFLAGS += -DCIRCUITPY_MDNS=$(CIRCUITPY_MDNS) + CIRCUITPY_MEMORYMAP ?= 0 CFLAGS += -DCIRCUITPY_MEMORYMAP=$(CIRCUITPY_MEMORYMAP) @@ -379,12 +504,19 @@ CFLAGS += -DCIRCUITPY_MEMORYMONITOR=$(CIRCUITPY_MEMORYMONITOR) CIRCUITPY_MICROCONTROLLER ?= 1 CFLAGS += -DCIRCUITPY_MICROCONTROLLER=$(CIRCUITPY_MICROCONTROLLER) -CIRCUITPY_MDNS ?= $(CIRCUITPY_WIFI) -CFLAGS += -DCIRCUITPY_MDNS=$(CIRCUITPY_MDNS) +CIRCUITPY_MIPICSI ?= 0 +CFLAGS += -DCIRCUITPY_MIPICSI=$(CIRCUITPY_MIPICSI) + +CIRCUITPY_MIPIDSI ?= 0 +CFLAGS += -DCIRCUITPY_MIPIDSI=$(CIRCUITPY_MIPIDSI) CIRCUITPY_MSGPACK ?= $(CIRCUITPY_FULL_BUILD) CFLAGS += -DCIRCUITPY_MSGPACK=$(CIRCUITPY_MSGPACK) +# True for any port that provides native networking, wifi or wired ethernet. +CIRCUITPY_NETWORK ?= $(call enable-if-any,$(CIRCUITPY_WIFI) $(CIRCUITPY_MII)) +CFLAGS += -DCIRCUITPY_NETWORK=$(CIRCUITPY_NETWORK) + CIRCUITPY_NEOPIXEL_WRITE ?= 1 CFLAGS += -DCIRCUITPY_NEOPIXEL_WRITE=$(CIRCUITPY_NEOPIXEL_WRITE) @@ -410,6 +542,8 @@ CFLAGS += -DCIRCUITPY_PEW=$(CIRCUITPY_PEW) # Only for RP2 chips. Assume not a raspberrypi build. CIRCUITPY_PICODVI ?= 0 CFLAGS += -DCIRCUITPY_PICODVI=$(CIRCUITPY_PICODVI) +CIRCUITPY_PICODVI_AUDIOOUT ?= 0 +CFLAGS += -DCIRCUITPY_PICODVI_AUDIOOUT=$(CIRCUITPY_PICODVI_AUDIOOUT) CIRCUITPY_PIXELBUF ?= $(CIRCUITPY_FULL_BUILD) CFLAGS += -DCIRCUITPY_PIXELBUF=$(CIRCUITPY_PIXELBUF) @@ -445,6 +579,9 @@ CFLAGS += -DCIRCUITPY_RAINBOWIO=$(CIRCUITPY_RAINBOWIO) CIRCUITPY_RANDOM ?= 1 CFLAGS += -DCIRCUITPY_RANDOM=$(CIRCUITPY_RANDOM) +CIRCUITPY_RCLCPY ?= 0 +CFLAGS += -DCIRCUITPY_RCLCPY=$(CIRCUITPY_RCLCPY) + CIRCUITPY_RE ?= $(CIRCUITPY_FULL_BUILD) CFLAGS += -DCIRCUITPY_RE=$(CIRCUITPY_RE) @@ -491,12 +628,20 @@ CFLAGS += -DCIRCUITPY_SDCARDIO=$(CIRCUITPY_SDCARDIO) CIRCUITPY_SDIOIO ?= 0 CFLAGS += -DCIRCUITPY_SDIOIO=$(CIRCUITPY_SDIOIO) -CIRCUITPY_SERIAL_BLE ?= 0 -CFLAGS += -DCIRCUITPY_SERIAL_BLE=$(CIRCUITPY_SERIAL_BLE) +# hardwarekey: cryptographic operations with hardware-held, non-readable keys. +# Off unless a port provides a common-hal/hardwarekey backend. +CIRCUITPY_HARDWAREKEY ?= 0 +CFLAGS += -DCIRCUITPY_HARDWAREKEY=$(CIRCUITPY_HARDWAREKEY) + +CIRCUITPY_BLE_SERIAL_SERVICE ?= 0 +CFLAGS += -DCIRCUITPY_BLE_SERIAL_SERVICE=$(CIRCUITPY_BLE_SERIAL_SERVICE) CIRCUITPY_SETTABLE_PROCESSOR_FREQUENCY?= 0 CFLAGS += -DCIRCUITPY_SETTABLE_PROCESSOR_FREQUENCY=$(CIRCUITPY_SETTABLE_PROCESSOR_FREQUENCY) +CIRCUITPY_SETTINGS_TOML ?= $(CIRCUITPY_FULL_BUILD) +CFLAGS += -DCIRCUITPY_SETTINGS_TOML=$(CIRCUITPY_SETTINGS_TOML) + CIRCUITPY_SHARPDISPLAY ?= $(CIRCUITPY_FRAMEBUFFERIO) CFLAGS += -DCIRCUITPY_SHARPDISPLAY=$(CIRCUITPY_SHARPDISPLAY) @@ -505,7 +650,7 @@ CFLAGS += -DCIRCUITPY_SHARPDISPLAY=$(CIRCUITPY_SHARPDISPLAY) CIRCUITPY_SKIP_SAFE_MODE_WAIT ?= 0 CFLAGS += -DCIRCUITPY_SKIP_SAFE_MODE_WAIT=$(CIRCUITPY_SKIP_SAFE_MODE_WAIT) -CIRCUITPY_SOCKETPOOL ?= $(CIRCUITPY_WIFI) +CIRCUITPY_SOCKETPOOL ?= $(CIRCUITPY_NETWORK) CFLAGS += -DCIRCUITPY_SOCKETPOOL=$(CIRCUITPY_SOCKETPOOL) CIRCUITPY_SPITARGET ?= 0 @@ -514,7 +659,7 @@ CFLAGS += -DCIRCUITPY_SPITARGET=$(CIRCUITPY_SPITARGET) CIRCUITPY_SOCKETPOOL_IPV6 ?= 0 CFLAGS += -DCIRCUITPY_SOCKETPOOL_IPV6=$(CIRCUITPY_SOCKETPOOL_IPV6) -CIRCUITPY_SSL ?= $(CIRCUITPY_WIFI) +CIRCUITPY_SSL ?= $(CIRCUITPY_NETWORK) CFLAGS += -DCIRCUITPY_SSL=$(CIRCUITPY_SSL) CIRCUITPY_SSL_MBEDTLS ?= 0 @@ -524,6 +669,31 @@ CFLAGS += -DCIRCUITPY_SSL_MBEDTLS=$(CIRCUITPY_SSL_MBEDTLS) CIRCUITPY_STAGE ?= 0 CFLAGS += -DCIRCUITPY_STAGE=$(CIRCUITPY_STAGE) +# PicoPad 2D game engine (off by default). +CIRCUITPY_PICOGAME ?= 0 +CFLAGS += -DCIRCUITPY_PICOGAME=$(CIRCUITPY_PICOGAME) +# The strip-rendering Display backend. It is worth building where busio sends asynchronously +# (the next strip is composed while the previous one is on the wire), so that is the default; +# a board can turn it off to save flash, or on without async busio for RGB444 alone. +ifeq ($(CIRCUITPY_PICOGAME),1) +CIRCUITPY_PICOGAME_FAST_DISPLAY ?= $(CIRCUITPY_BUSIO_SPI_ASYNC) +else +CIRCUITPY_PICOGAME_FAST_DISPLAY ?= 0 +endif +CFLAGS += -DCIRCUITPY_PICOGAME_FAST_DISPLAY=$(CIRCUITPY_PICOGAME_FAST_DISPLAY) +# Does this board's panel controller support 12-bit RGB444 (COLMOD)? A capability flag the +# board declares (ST7789/ST7735 = 1, ILI9341 = 0); exposed as picogame.RGB444_SUPPORTED so +# a game can enable Display(rgb444=...) only where it works. Default 0 (safe RGB565). +CIRCUITPY_PICOGAME_RGB444 ?= 0 +CFLAGS += -DCIRCUITPY_PICOGAME_RGB444=$(CIRCUITPY_PICOGAME_RGB444) +# Full-frame RAM-framebuffer render backend for scanout-buffer platforms (RP2350 DVI/HSTX +# boards like the Fruit Jam). Off by default so flash-tight SPI-only boards don't carry it. +CIRCUITPY_PICOGAME_FRAMEBUFFER ?= 0 +CFLAGS += -DCIRCUITPY_PICOGAME_FRAMEBUFFER=$(CIRCUITPY_PICOGAME_FRAMEBUFFER) +# Perspective and 3D drawing for picogame canvases (mode7, road, raycast, project). +CIRCUITPY_PICOGAME3D ?= $(CIRCUITPY_PICOGAME) +CFLAGS += -DCIRCUITPY_PICOGAME3D=$(CIRCUITPY_PICOGAME3D) + CIRCUITPY_STATUS_BAR ?= 1 CFLAGS += -DCIRCUITPY_STATUS_BAR=$(CIRCUITPY_STATUS_BAR) @@ -533,6 +703,16 @@ CFLAGS += -DCIRCUITPY_STORAGE=$(CIRCUITPY_STORAGE) CIRCUITPY_STORAGE_EXTEND ?= $(CIRCUITPY_DUALBANK) CFLAGS += -DCIRCUITPY_STORAGE_EXTEND=$(CIRCUITPY_STORAGE_EXTEND) +# storage.map_file(): read a file straight out of memory-mapped flash. A port whose CIRCUITPY drive +# is memory-mapped implements port_internal_flash_xip_address() and turns this on; turning it on +# without that function is a link error, not a silent no-op. +CIRCUITPY_STORAGE_MAP_FILE ?= 0 +CFLAGS += -DCIRCUITPY_STORAGE_MAP_FILE=$(CIRCUITPY_STORAGE_MAP_FILE) + +# Import a CIRCUITPY .mpy from its flash runs: its bytecode and strings stay in flash. +CIRCUITPY_STORAGE_MAP_IMPORT ?= $(CIRCUITPY_STORAGE_MAP_FILE) +CFLAGS += -DCIRCUITPY_STORAGE_MAP_IMPORT=$(CIRCUITPY_STORAGE_MAP_IMPORT) + CIRCUITPY_STRUCT ?= 1 CFLAGS += -DCIRCUITPY_STRUCT=$(CIRCUITPY_STRUCT) @@ -555,10 +735,17 @@ CFLAGS += -DCIRCUITPY_TERMINALIO=$(CIRCUITPY_TERMINALIO) CIRCUITPY_TERMINALIO_VT100 ?= $(CIRCUITPY_TERMINALIO) CFLAGS += -DCIRCUITPY_TERMINALIO_VT100=$(CIRCUITPY_TERMINALIO_VT100) -CIRCUITPY_FONTIO ?= $(call enable-if-all,$(CIRCUITPY_DISPLAYIO) $(CIRCUITPY_TERMINALIO)) +CIRCUITPY_FONTIO ?= $(CIRCUITPY_TERMINALIO) CFLAGS += -DCIRCUITPY_FONTIO=$(CIRCUITPY_FONTIO) +CIRCUITPY_LVFONTIO ?= $(CIRCUITPY_TERMINALIO) +CFLAGS += -DCIRCUITPY_LVFONTIO=$(CIRCUITPY_LVFONTIO) + CIRCUITPY_TILEPALETTEMAPPER ?= $(CIRCUITPY_DISPLAYIO) +# tilepalettemapper uses the scanline palette conversion API. +ifeq ($(CIRCUITPY_DISPLAYIO_LVGL),1) +CIRCUITPY_TILEPALETTEMAPPER = 0 +endif CFLAGS += -DCIRCUITPY_TILEPALETTEMAPPER=$(CIRCUITPY_TILEPALETTEMAPPER) CIRCUITPY_TIME ?= 1 @@ -619,6 +806,9 @@ CFLAGS += -DCIRCUITPY_USB_HID_ENABLED_DEFAULT=$(CIRCUITPY_USB_HID_ENABLED_DEFAUL CIRCUITPY_USB_VIDEO ?= 0 CFLAGS += -DCIRCUITPY_USB_VIDEO=$(CIRCUITPY_USB_VIDEO) +CIRCUITPY_USB_AUDIO ?= 0 +CFLAGS += -DCIRCUITPY_USB_AUDIO=$(CIRCUITPY_USB_AUDIO) + CIRCUITPY_USB_HOST ?= 0 CFLAGS += -DCIRCUITPY_USB_HOST=$(CIRCUITPY_USB_HOST) @@ -655,6 +845,15 @@ CFLAGS += -DCIRCUITPY_USB_HOST=$(CIRCUITPY_USB_HOST) CIRCUITPY_PYUSB ?= $(call enable-if-any,$(CIRCUITPY_USB_HOST) $(CIRCUITPY_MAX3421E)) CFLAGS += -DCIRCUITPY_PYUSB=$(CIRCUITPY_PYUSB) +# Needs a host controller that buffers isochronous IN packets, such as +# Pico-PIO-USB with PIO_USB_HOST_ISOCHRONOUS set. +CIRCUITPY_USB_HOST_AUDIO ?= 0 +CFLAGS += -DCIRCUITPY_USB_HOST_AUDIO=$(CIRCUITPY_USB_HOST_AUDIO) + +# Continuous bulk transfers on PIO USB host ports. Opt-in per board. +CIRCUITPY_USB_HOST_BULK ?= 0 +CFLAGS += -DCIRCUITPY_USB_HOST_BULK=$(CIRCUITPY_USB_HOST_BULK) + CIRCUITPY_USB_KEYBOARD_WORKFLOW ?= $(call enable-if-any,$(CIRCUITPY_USB_HOST) $(CIRCUITPY_MAX3421E)) CFLAGS += -DCIRCUITPY_USB_KEYBOARD_WORKFLOW=$(CIRCUITPY_USB_KEYBOARD_WORKFLOW) @@ -662,6 +861,9 @@ CFLAGS += -DCIRCUITPY_USB_KEYBOARD_WORKFLOW=$(CIRCUITPY_USB_KEYBOARD_WORKFLOW) CIRCUITPY_USTACK ?= 0 CFLAGS += -DCIRCUITPY_USTACK=$(CIRCUITPY_USTACK) +# Zephyr display integration is only built by ports/zephyr-cp. +CFLAGS += -DCIRCUITPY_ZEPHYR_DISPLAY=0 + # for decompressing utilities CIRCUITPY_ZLIB ?= $(CIRCUITPY_FULL_BUILD) CFLAGS += -DCIRCUITPY_ZLIB=$(CIRCUITPY_ZLIB) @@ -670,15 +872,20 @@ CFLAGS += -DCIRCUITPY_ZLIB=$(CIRCUITPY_ZLIB) CIRCUITPY_ULAB ?= $(CIRCUITPY_FULL_BUILD) CFLAGS += -DCIRCUITPY_ULAB=$(CIRCUITPY_ULAB) -# whether to use -Os optimization on files in ulab +# Enabling this compiles ulab with -Os and uses function-pointer dispatch for +# ndarray binary operators. This saves about 4 kB of flash but makes +# element-wise array arithmetic roughly 1.5x slower. CIRCUITPY_ULAB_OPTIMIZE_SIZE ?= 0 -# CIRCUITPY_VIDEOCORE is handled in the broadcom tree. -# Only for Broadcom chips. -# Assume not a Broadcom build. +# Video pipeline: playing video sources into framebuffers or plain buffers. +# A source can be a port's camera, such as mipicsi, or a GIF file with videogif. CIRCUITPY_VIDEOCORE ?= 0 CFLAGS += -DCIRCUITPY_VIDEOCORE=$(CIRCUITPY_VIDEOCORE) +# Animated GIF files as a videocore video source. Shares gifio's decoder. +CIRCUITPY_VIDEOGIF ?= $(call enable-if-all,$(CIRCUITPY_VIDEOCORE) $(CIRCUITPY_GIFIO)) +CFLAGS += -DCIRCUITPY_VIDEOGIF=$(CIRCUITPY_VIDEOGIF) + CIRCUITPY_WARNINGS ?= $(CIRCUITPY_FULL_BUILD) CFLAGS += -DCIRCUITPY_WARNINGS=$(CIRCUITPY_WARNINGS) @@ -689,15 +896,15 @@ CFLAGS += -DCIRCUITPY_WATCHDOG=$(CIRCUITPY_WATCHDOG) CIRCUITPY_WIFI ?= 0 CFLAGS += -DCIRCUITPY_WIFI=$(CIRCUITPY_WIFI) -CIRCUITPY_WEB_WORKFLOW ?= $(CIRCUITPY_WIFI) +CIRCUITPY_WIZNET ?= 0 +CFLAGS += -DCIRCUITPY_WIZNET=$(CIRCUITPY_WIZNET) + +CIRCUITPY_WEB_WORKFLOW ?= $(CIRCUITPY_NETWORK) CFLAGS += -DCIRCUITPY_WEB_WORKFLOW=$(CIRCUITPY_WEB_WORKFLOW) CIRCUITPY_WIFI_RADIO_SETTABLE_MAC_ADDRESS?= 1 CFLAGS += -DCIRCUITPY_WIFI_RADIO_SETTABLE_MAC_ADDRESS=$(CIRCUITPY_WIFI_RADIO_SETTABLE_MAC_ADDRESS) -CIRCUITPY_WIFI_RADIO_SETTABLE_LISTEN_INTERVAL?= 0 -CFLAGS += -DCIRCUITPY_WIFI_RADIO_SETTABLE_LISTEN_INTERVAL=$(CIRCUITPY_WIFI_RADIO_SETTABLE_LISTEN_INTERVAL) - # tinyusb port tailored configuration CIRCUITPY_TUSB_MEM_ALIGN ?= 4 CFLAGS += -DCIRCUITPY_TUSB_MEM_ALIGN=$(CIRCUITPY_TUSB_MEM_ALIGN) @@ -710,7 +917,7 @@ CIRCUITPY_SWO_TRACE ?= 0 CFLAGS += -DCIRCUITPY_SWO_TRACE=$(CIRCUITPY_SWO_TRACE) # Check for a minimum GCC version during build (set to 0 to disable) -CIRCUITPY_MIN_GCC_VERSION ?= 13 +CIRCUITPY_MIN_GCC_VERSION ?= 14 CFLAGS += -DCIRCUITPY_MIN_GCC_VERSION=$(CIRCUITPY_MIN_GCC_VERSION) # Define an equivalent for MICROPY_LONGINT_IMPL, to pass to $(MPY-TOOL) in py/mkrules.mk diff --git a/py/compile.c b/py/compile.c index 085c342605d..468f133927f 100644 --- a/py/compile.c +++ b/py/compile.c @@ -102,6 +102,9 @@ static const emit_method_table_t *emit_native_table[] = { &emit_native_thumb_method_table, &emit_native_xtensa_method_table, &emit_native_xtensawin_method_table, + &emit_native_rv32_method_table, + NULL, + &emit_native_debug_method_table, }; #elif MICROPY_EMIT_NATIVE @@ -118,6 +121,10 @@ static const emit_method_table_t *emit_native_table[] = { #define NATIVE_EMITTER(f) emit_native_xtensa_##f #elif MICROPY_EMIT_XTENSAWIN #define NATIVE_EMITTER(f) emit_native_xtensawin_##f +#elif MICROPY_EMIT_RV32 +#define NATIVE_EMITTER(f) emit_native_rv32_##f +#elif MICROPY_EMIT_NATIVE_DEBUG +#define NATIVE_EMITTER(f) emit_native_debug_##f #else #error "unknown native emitter" #endif @@ -140,7 +147,8 @@ static const emit_inline_asm_method_table_t *emit_asm_table[] = { &emit_inline_thumb_method_table, &emit_inline_thumb_method_table, &emit_inline_xtensa_method_table, - NULL, + &emit_inline_xtensa_method_table, + &emit_inline_rv32_method_table, }; #elif MICROPY_EMIT_INLINE_ASM @@ -151,6 +159,9 @@ static const emit_inline_asm_method_table_t *emit_asm_table[] = { #elif MICROPY_EMIT_INLINE_XTENSA #define ASM_DECORATOR_QSTR MP_QSTR_asm_xtensa #define ASM_EMITTER(f) emit_inline_xtensa_##f +#elif MICROPY_EMIT_INLINE_RV32 +#define ASM_DECORATOR_QSTR MP_QSTR_asm_rv32 +#define ASM_EMITTER(f) emit_inline_rv32_##f #else #error "unknown asm emitter" #endif @@ -823,8 +834,22 @@ static qstr compile_classdef_helper(compiler_t *comp, mp_parse_node_struct_t *pn return cscope->simple_name; } +// CIRCUITPY-CHANGE: returns true for native or viper with optional=True +static bool compile_decorator_optional(mp_parse_node_t pn_trailer) { + if (MP_PARSE_NODE_IS_NULL(pn_trailer)) { + return false; + } + mp_parse_node_t pn_arg = ((mp_parse_node_struct_t *)pn_trailer)->nodes[0]; + if (!MP_PARSE_NODE_IS_STRUCT_KIND(pn_arg, PN_argument)) { + return false; + } + mp_parse_node_struct_t *pns_arg = (mp_parse_node_struct_t *)pn_arg; + return MP_PARSE_NODE_IS_ID(pns_arg->nodes[0]) && MP_PARSE_NODE_LEAF_ARG(pns_arg->nodes[0]) == MP_QSTR_optional + && MP_PARSE_NODE_IS_TOKEN_KIND(pns_arg->nodes[1], MP_TOKEN_KW_TRUE); +} + // returns true if it was a built-in decorator (even if the built-in had an error) -static bool compile_built_in_decorator(compiler_t *comp, size_t name_len, mp_parse_node_t *name_nodes, uint *emit_options) { +static bool compile_built_in_decorator(compiler_t *comp, size_t name_len, mp_parse_node_t *name_nodes, mp_parse_node_t pn_trailer, uint *emit_options) { if (MP_PARSE_NODE_LEAF_ARG(name_nodes[0]) != MP_QSTR_micropython) { return false; } @@ -835,6 +860,11 @@ static bool compile_built_in_decorator(compiler_t *comp, size_t name_len, mp_par } qstr attr = MP_PARSE_NODE_LEAF_ARG(name_nodes[1]); + // CIRCUITPY-CHANGE: optional=True compiles as bytecode where native code can't be emitted + bool optional = false; + if (attr == MP_QSTR_native || attr == MP_QSTR_viper) { + optional = compile_decorator_optional(pn_trailer); + } if (attr == MP_QSTR_bytecode) { *emit_options = MP_EMIT_OPT_BYTECODE; #if MICROPY_EMIT_NATIVE @@ -842,6 +872,12 @@ static bool compile_built_in_decorator(compiler_t *comp, size_t name_len, mp_par *emit_options = MP_EMIT_OPT_NATIVE_PYTHON; } else if (attr == MP_QSTR_viper) { *emit_options = MP_EMIT_OPT_VIPER; + #else + } else if (attr == MP_QSTR_native || attr == MP_QSTR_viper) { + // CIRCUITPY-CHANGE: no native emitter on the board, so optional=True stays bytecode + if (!optional) { + compile_syntax_error(comp, name_nodes[1], MP_ERROR_TEXT("invalid micropython decorator")); + } #endif #if MICROPY_EMIT_INLINE_ASM #if MICROPY_DYNAMIC_COMPILER @@ -849,6 +885,8 @@ static bool compile_built_in_decorator(compiler_t *comp, size_t name_len, mp_par *emit_options = MP_EMIT_OPT_ASM; } else if (attr == MP_QSTR_asm_xtensa) { *emit_options = MP_EMIT_OPT_ASM; + } else if (attr == MP_QSTR_asm_rv32) { + *emit_options = MP_EMIT_OPT_ASM; #else } else if (attr == ASM_DECORATOR_QSTR) { *emit_options = MP_EMIT_OPT_ASM; @@ -861,7 +899,12 @@ static bool compile_built_in_decorator(compiler_t *comp, size_t name_len, mp_par #if MICROPY_EMIT_NATIVE && MICROPY_DYNAMIC_COMPILER if (*emit_options == MP_EMIT_OPT_NATIVE_PYTHON || *emit_options == MP_EMIT_OPT_VIPER) { if (emit_native_table[mp_dynamic_compiler.native_arch] == NULL) { - compile_syntax_error(comp, name_nodes[1], MP_ERROR_TEXT("invalid arch")); + // CIRCUITPY-CHANGE: no native emitter for this arch + if (optional) { + *emit_options = MP_EMIT_OPT_BYTECODE; + } else { + compile_syntax_error(comp, name_nodes[1], MP_ERROR_TEXT("invalid arch")); + } } } else if (*emit_options == MP_EMIT_OPT_ASM) { if (emit_asm_table[mp_dynamic_compiler.native_arch] == NULL) { @@ -870,6 +913,11 @@ static bool compile_built_in_decorator(compiler_t *comp, size_t name_len, mp_par } #endif + #if MICROPY_EMIT_NATIVE && !MICROPY_DYNAMIC_COMPILER + // CIRCUITPY-CHANGE: this build has an emitter, so native code is always emitted + (void)optional; + #endif + return true; } @@ -892,7 +940,7 @@ static void compile_decorated(compiler_t *comp, mp_parse_node_struct_t *pns) { size_t name_len = mp_parse_node_extract_list(&pns_decorator->nodes[0], PN_dotted_name, &name_nodes); // check for built-in decorators - if (compile_built_in_decorator(comp, name_len, name_nodes, &emit_options)) { + if (compile_built_in_decorator(comp, name_len, name_nodes, pns_decorator->nodes[1], &emit_options)) { // this was a built-in num_built_in_decorators += 1; @@ -1894,19 +1942,7 @@ static void compile_async_with_stmt_helper(compiler_t *comp, size_t n, mp_parse_ // 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); - - // Detect if TOS an exception or not - EMIT(dup_top); - EMIT_LOAD_GLOBAL(MP_QSTR_BaseException); - 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 + EMIT_ARG(async_with_setup_finally, l_aexit_no_exc, l_finally_block, l_ret_unwind_jump); // Handle case 2: call __aexit__ and either swallow or re-raise the exception // Stack: (..., ctx_mgr, exc) @@ -1932,6 +1968,7 @@ static void compile_async_with_stmt_helper(compiler_t *comp, size_t n, mp_parse_ 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 + // Stack: (..., None) EMIT_ARG(jump, l_end); EMIT_ARG(adjust_stack_size, 2); @@ -1941,6 +1978,8 @@ static void compile_async_with_stmt_helper(compiler_t *comp, size_t n, mp_parse_ EMIT(rot_three); EMIT(rot_three); EMIT_ARG(label_assign, l_aexit_no_exc); + // We arrive here from either case 1 (a jump) or case 3 (fall through) + // Stack: case 1: (..., None, ctx_mgr) or case 3: (..., X, INT, ctx_mgr) EMIT_ARG(load_method, MP_QSTR___aexit__, false); EMIT_ARG(load_const_tok, MP_TOKEN_KW_NONE); EMIT(dup_top); @@ -1948,6 +1987,7 @@ static void compile_async_with_stmt_helper(compiler_t *comp, size_t n, mp_parse_ EMIT_ARG(call_method, 3, 0, 0); compile_yield_from(comp); EMIT(pop_top); + // Stack: case 1: (..., None) or case 3: (..., X, INT) EMIT_ARG(adjust_stack_size, -1); // End of "finally" block @@ -2418,6 +2458,14 @@ static void compile_trailer_paren_helper(compiler_t *comp, mp_parse_node_t pn_ar compile_syntax_error(comp, (mp_parse_node_t)pns_arg, MP_ERROR_TEXT("* arg after **")); return; } + if (n_keyword) { + // Support for *arg after kwarg is a CPython feature omitted + // from MicroPython in order to reduce code size. See + // https://github.com/micropython/micropython/issues/11439 for + // more info. + compile_syntax_error(comp, (mp_parse_node_t)pns_arg, MP_ERROR_TEXT("* arg after kwarg")); + return; + } #if MICROPY_DYNAMIC_COMPILER if (i >= (size_t)mp_dynamic_compiler.small_int_bits - 1) #else @@ -3291,7 +3339,9 @@ static void compile_scope_inline_asm(compiler_t *comp, scope_t *scope, pass_kind } // check structure of parse node - assert(MP_PARSE_NODE_IS_STRUCT(pns2->nodes[0])); + if (!MP_PARSE_NODE_IS_STRUCT(pns2->nodes[0])) { + goto not_an_instruction; + } if (!MP_PARSE_NODE_IS_NULL(pns2->nodes[1])) { goto not_an_instruction; } @@ -3481,7 +3531,7 @@ static void scope_compute_things(scope_t *scope) { } } -#if !MICROPY_PERSISTENT_CODE_SAVE +#if !MICROPY_EXPOSE_MP_COMPILE_TO_RAW_CODE static #endif void mp_compile_to_raw_code(mp_parse_tree_t *parse_tree, qstr source_file, bool is_repl, mp_compiled_module_t *cm) { @@ -3562,7 +3612,7 @@ void mp_compile_to_raw_code(mp_parse_tree_t *parse_tree, qstr source_file, bool // TODO this can be improved by calculating it during SCOPE pass // but that requires some other structural changes to the asm emitters #if MICROPY_DYNAMIC_COMPILER - if (mp_dynamic_compiler.native_arch == MP_NATIVE_ARCH_XTENSA) + if (mp_dynamic_compiler.native_arch == MP_NATIVE_ARCH_XTENSA || mp_dynamic_compiler.native_arch == MP_NATIVE_ARCH_XTENSAWIN) #endif { compile_scope_inline_asm(comp, s, MP_PASS_CODE_SIZE); @@ -3583,6 +3633,13 @@ void mp_compile_to_raw_code(mp_parse_tree_t *parse_tree, qstr source_file, bool case MP_EMIT_OPT_NATIVE_PYTHON: case MP_EMIT_OPT_VIPER: if (emit_native == NULL) { + // The check looks like this to work around a false + // warning in GCC 13 (and possibly later), where it + // assumes that the check will always fail. + if ((uintptr_t)NATIVE_EMITTER_TABLE == (uintptr_t)NULL) { + comp->compile_error = mp_obj_new_exception_msg(&mp_type_NotImplementedError, MP_ERROR_TEXT("cannot emit native code for this architecture")); + goto emit_finished; + } emit_native = NATIVE_EMITTER(new)(&comp->emit_common, &comp->compile_error, &comp->next_label, max_num_labels); } comp->emit_method_table = NATIVE_EMITTER_TABLE; @@ -3615,6 +3672,10 @@ void mp_compile_to_raw_code(mp_parse_tree_t *parse_tree, qstr source_file, bool } } + #if MICROPY_EMIT_NATIVE +emit_finished: + #endif + if (comp->compile_error != MP_OBJ_NULL) { // if there is no line number for the error then use the line // number for the start of this scope @@ -3646,7 +3707,7 @@ void mp_compile_to_raw_code(mp_parse_tree_t *parse_tree, qstr source_file, bool #if MICROPY_DEBUG_PRINTERS // now that the module context is valid, the raw codes can be printed - if (mp_verbose_flag >= 2) { + if (MP_STATE_VM(mp_verbose_flag) >= 2) { for (scope_t *s = comp->scope_head; s != NULL; s = s->next) { mp_raw_code_t *rc = s->raw_code; if (rc->kind == MP_CODE_BYTECODE) { diff --git a/py/compile.h b/py/compile.h index f9970a521d6..64afc487d7c 100644 --- a/py/compile.h +++ b/py/compile.h @@ -30,6 +30,9 @@ #include "py/parse.h" #include "py/emitglue.h" +// Whether mp_compile_to_raw_code is exposed as a public function. +#define MICROPY_EXPOSE_MP_COMPILE_TO_RAW_CODE (MICROPY_PY_BUILTINS_CODE >= MICROPY_PY_BUILTINS_CODE_BASIC || MICROPY_PERSISTENT_CODE_SAVE) + #if MICROPY_COMP_ALLOW_TOP_LEVEL_AWAIT // set to `true` to allow top-level await expressions extern bool mp_compile_allow_top_level_await; @@ -40,7 +43,7 @@ extern bool mp_compile_allow_top_level_await; // mp_globals_get() will be used for the context mp_obj_t mp_compile(mp_parse_tree_t *parse_tree, qstr source_file, bool is_repl); -#if MICROPY_PERSISTENT_CODE_SAVE +#if MICROPY_EXPOSE_MP_COMPILE_TO_RAW_CODE // this has the same semantics as mp_compile void mp_compile_to_raw_code(mp_parse_tree_t *parse_tree, qstr source_file, bool is_repl, mp_compiled_module_t *cm); #endif diff --git a/py/cstack.c b/py/cstack.c new file mode 100644 index 00000000000..fe4b16d652a --- /dev/null +++ b/py/cstack.c @@ -0,0 +1,57 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2014 Paul Sokolovsky + * Copryight (c) 2024 Angus Gratton + * + * 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 "py/cstack.h" + +void mp_cstack_init_with_sp_here(size_t stack_size) { + #if __GNUC__ >= 13 + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wdangling-pointer" + #endif + volatile int stack_dummy; + mp_cstack_init_with_top((void *)&stack_dummy, stack_size); + #if __GNUC__ >= 13 + #pragma GCC diagnostic pop + #endif +} + +mp_uint_t mp_cstack_usage(void) { + // Assumes descending stack + volatile int stack_dummy; + return MP_STATE_THREAD(stack_top) - (char *)&stack_dummy; +} + +#if MICROPY_STACK_CHECK + +void mp_cstack_check(void) { + if (mp_cstack_usage() >= MP_STATE_THREAD(stack_limit)) { + mp_raise_recursion_depth(); + } +} + +#endif // MICROPY_STACK_CHECK diff --git a/py/cstack.h b/py/cstack.h new file mode 100644 index 00000000000..bcd919d31f9 --- /dev/null +++ b/py/cstack.h @@ -0,0 +1,63 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2014 Paul Sokolovsky + * Copyright (c) 2024 Angus Gratton + * + * 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_PY_CSTACK_H +#define MICROPY_INCLUDED_PY_CSTACK_H + +#include "py/mpstate.h" + +// Both init functions below accept the full stack size. Set the +// MICROPY_STACK_CHECK_MARGIN to the number of bytes subtracted to account +// for stack usage between checks. + +void mp_cstack_init_with_sp_here(size_t stack_size); + +static inline void mp_cstack_init_with_top(void *top, size_t stack_size) { + MP_STATE_THREAD(stack_top) = (char *)top; + + #if MICROPY_STACK_CHECK + assert(stack_size > MICROPY_STACK_CHECK_MARGIN); // Should be enforced by port + MP_STATE_THREAD(stack_limit) = stack_size - MICROPY_STACK_CHECK_MARGIN; + #else + (void)stack_size; + #endif +} + +mp_uint_t mp_cstack_usage(void); + +#if MICROPY_STACK_CHECK + +void mp_cstack_check(void); + +#else + +static inline void mp_cstack_check(void) { + // No-op when stack checking is disabled +} + +#endif + +#endif // MICROPY_INCLUDED_PY_CSTACK_H diff --git a/py/dynruntime.h b/py/dynruntime.h index 44f6d05ccb6..9eea5ca6e5c 100644 --- a/py/dynruntime.h +++ b/py/dynruntime.h @@ -28,6 +28,14 @@ // This header file contains definitions to dynamically implement the static // MicroPython runtime API defined in py/obj.h and py/runtime.h. +// +// All of the symbols made available in this header are overriding those defined +// in py/obj.h and py/runtime.h. This is done with macros. For macros that +// would be too complicated (usually more than a single expression), they call a +// static-inline function for the implementation. This function has the same +// name as the macro (hence the same name as a public API function) but with +// "_dyn" appended. For example, the m_malloc() macro calls the m_malloc_dyn() +// static-inline function. #include "py/binary.h" #include "py/nativeglue.h" @@ -39,6 +47,10 @@ #error "dynruntime.h included in non-dynamic-module build." #endif +#if MICROPY_MALLOC_USES_ALLOCATED_SIZE +#error "MICROPY_MALLOC_USES_ALLOCATED_SIZE must be disable in a dynamic-module build." +#endif + #undef MP_ROM_QSTR #undef MP_OBJ_QSTR_VALUE #undef MP_OBJ_NEW_QSTR @@ -52,13 +64,32 @@ /******************************************************************************/ // Memory allocation +#define m_malloc_fail(num_bytes) (m_malloc_fail_dyn((num_bytes))) #define m_malloc(n) (m_malloc_dyn((n))) #define m_free(ptr) (m_free_dyn((ptr))) #define m_realloc(ptr, new_num_bytes) (m_realloc_dyn((ptr), (new_num_bytes))) +#define m_realloc_maybe(ptr, new_num_bytes, allow_move) (m_realloc_maybe_dyn((ptr), (new_num_bytes), (allow_move))) + +static MP_NORETURN inline void m_malloc_fail_dyn(size_t num_bytes) { + mp_fun_table.raise_msg_str( + mp_fun_table.load_global(MP_QSTR_MemoryError), + "memory allocation failed"); +} + +static inline void *m_realloc_maybe_dyn(void *ptr, size_t new_num_bytes, bool allow_move) { + return mp_fun_table.realloc_(ptr, new_num_bytes, allow_move); +} + +static inline void *m_realloc_checked_dyn(void *ptr, size_t new_num_bytes, bool allow_move) { + ptr = m_realloc_maybe(ptr, new_num_bytes, allow_move); + if (ptr == NULL && new_num_bytes != 0) { + m_malloc_fail(new_num_bytes); + } + return ptr; +} static inline void *m_malloc_dyn(size_t n) { - // TODO won't raise on OOM - return mp_fun_table.realloc_(NULL, n, false); + return m_realloc_checked_dyn(NULL, n, false); } static inline void m_free_dyn(void *ptr) { @@ -66,8 +97,7 @@ static inline void m_free_dyn(void *ptr) { } static inline void *m_realloc_dyn(void *ptr, size_t new_num_bytes) { - // TODO won't raise on OOM - return mp_fun_table.realloc_(ptr, new_num_bytes, true); + return m_realloc_checked_dyn(ptr, new_num_bytes, true); } /******************************************************************************/ @@ -259,7 +289,7 @@ static inline void *mp_obj_malloc_helper_dyn(size_t num_bytes, const mp_obj_type #define nlr_raise(o) (mp_raise_dyn(o)) #define mp_raise_type_arg(type, arg) (mp_raise_dyn(mp_obj_new_exception_arg1_dyn((type), (arg)))) -// CIRCUITPY-CHANGE: use str +// CIRCUITPY-CHANGE: use mp_raise_msg_str #define mp_raise_msg(type, msg) (mp_fun_table.raise_msg_str((type), (msg))) #define mp_raise_OSError(er) (mp_raise_OSError_dyn(er)) #define mp_raise_NotImplementedError(msg) (mp_raise_msg(&mp_type_NotImplementedError, (msg))) @@ -271,14 +301,14 @@ static inline mp_obj_t mp_obj_new_exception_arg1_dyn(const mp_obj_type_t *exc_ty return mp_call_function_n_kw(MP_OBJ_FROM_PTR(exc_type), 1, 0, &args[0]); } -static NORETURN inline void mp_raise_dyn(mp_obj_t o) { +static MP_NORETURN inline void mp_raise_dyn(mp_obj_t o) { mp_fun_table.raise(o); for (;;) { } } // CIRCUITPY-CHANGE: new routine -static NORETURN inline void mp_raise_arg1(const mp_obj_type_t *exc_type, mp_obj_t arg) { +static MP_NORETURN inline void mp_raise_arg1(const mp_obj_type_t *exc_type, mp_obj_t arg) { mp_fun_table.raise(mp_obj_new_exception_arg1_dyn(exc_type, arg)); for (;;) { } diff --git a/py/dynruntime.mk b/py/dynruntime.mk index 62db43ad149..cab609b13b0 100644 --- a/py/dynruntime.mk +++ b/py/dynruntime.mk @@ -1,7 +1,8 @@ # Makefile fragment for generating native .mpy files from C source # MPY_DIR must be set to the top of the MicroPython source tree -BUILD ?= build +BUILD ?= build-$(ARCH) +CC = $(CROSS)gcc ECHO = @echo RM = /bin/rm @@ -29,85 +30,195 @@ CFLAGS += -Wall -Werror -DNDEBUG CFLAGS += -DNO_QSTR CFLAGS += -DMICROPY_ENABLE_DYNRUNTIME CFLAGS += -DMP_CONFIGFILE='<$(CONFIG_H)>' -CFLAGS += -fpic -fno-common -CFLAGS += -U _FORTIFY_SOURCE # prevent use of __*_chk libc functions -#CFLAGS += -fdata-sections -ffunction-sections + +CFLAGS_ARCH += -fpic -fno-common +CFLAGS_ARCH += -U_FORTIFY_SOURCE # prevent use of __*_chk libc functions +#CFLAGS_ARCH += -fdata-sections -ffunction-sections MPY_CROSS_FLAGS += -march=$(ARCH) SRC_O += $(addprefix $(BUILD)/, $(patsubst %.c,%.o,$(filter %.c,$(SRC))) $(patsubst %.S,%.o,$(filter %.S,$(SRC)))) SRC_MPY += $(addprefix $(BUILD)/, $(patsubst %.py,%.mpy,$(filter %.py,$(SRC)))) +CLEAN_EXTRA += $(MOD).mpy .mpy_ld_cache-$(ARCH) + ################################################################################ # Architecture configuration ifeq ($(ARCH),x86) # x86 -CROSS = -CFLAGS += -m32 -fno-stack-protector +CROSS = i686-linux-gnu- +CFLAGS_ARCH += -fno-stack-protector MICROPY_FLOAT_IMPL ?= double else ifeq ($(ARCH),x64) # x64 -CROSS = -CFLAGS += -fno-stack-protector +CROSS = x86_64-linux-gnu- +CFLAGS_ARCH += -fno-stack-protector MICROPY_FLOAT_IMPL ?= double else ifeq ($(ARCH),armv6m) # thumb CROSS = arm-none-eabi- -CFLAGS += -mthumb -mcpu=cortex-m0 -MICROPY_FLOAT_IMPL ?= none +CFLAGS_ARCH += -mthumb -mcpu=cortex-m0 +MICROPY_FLOAT_IMPL ?= float else ifeq ($(ARCH),armv7m) # thumb CROSS = arm-none-eabi- -CFLAGS += -mthumb -mcpu=cortex-m3 -MICROPY_FLOAT_IMPL ?= none +CFLAGS_ARCH += -mthumb -mcpu=cortex-m3 +MICROPY_FLOAT_IMPL ?= float else ifeq ($(ARCH),armv7emsp) # thumb CROSS = arm-none-eabi- -CFLAGS += -mthumb -mcpu=cortex-m4 -CFLAGS += -mfpu=fpv4-sp-d16 -mfloat-abi=hard +CFLAGS_ARCH += -mthumb -mcpu=cortex-m4 +CFLAGS_ARCH += -mfpu=fpv4-sp-d16 -mfloat-abi=hard MICROPY_FLOAT_IMPL ?= float else ifeq ($(ARCH),armv7emdp) # thumb CROSS = arm-none-eabi- -CFLAGS += -mthumb -mcpu=cortex-m7 -CFLAGS += -mfpu=fpv5-d16 -mfloat-abi=hard +CFLAGS_ARCH += -mthumb -mcpu=cortex-m7 +CFLAGS_ARCH += -mfpu=fpv5-d16 -mfloat-abi=hard MICROPY_FLOAT_IMPL ?= double else ifeq ($(ARCH),xtensa) # xtensa CROSS = xtensa-lx106-elf- -CFLAGS += -mforce-l32 +CFLAGS_ARCH += -mforce-l32 MICROPY_FLOAT_IMPL ?= none else ifeq ($(ARCH),xtensawin) # xtensawin CROSS = xtensa-esp32-elf- -CFLAGS += MICROPY_FLOAT_IMPL ?= float +else ifeq ($(ARCH),rv32imc) + +# rv32imc +CROSS = riscv64-unknown-elf- +CFLAGS_ARCH += -march=rv32imac -mabi=ilp32 -mno-relax +MICROPY_FLOAT_IMPL ?= none +PICOLIBC_BASE := riscv64-unknown-elf +PICOLIBC_TARGET := rv32imac/ilp32 + +else ifeq ($(ARCH),rv64imc) + +# rv64imc +CROSS = riscv64-unknown-elf- +CFLAGS_ARCH += -march=rv64imac -mabi=lp64 -mno-relax +MICROPY_FLOAT_IMPL ?= none +PICOLIBC_BASE := riscv64-unknown-elf +PICOLIBC_TARGET := rv64imac/lp64 + else $(error architecture '$(ARCH)' not supported) endif -MICROPY_FLOAT_IMPL_UPPER = $(shell echo $(MICROPY_FLOAT_IMPL) | tr '[:lower:]' '[:upper:]') -CFLAGS += -DMICROPY_FLOAT_IMPL=MICROPY_FLOAT_IMPL_$(MICROPY_FLOAT_IMPL_UPPER) +ifneq ($(findstring -musl,$(shell $(CC) -dumpmachine)),) +USE_MUSL := 1 +endif + +ifeq ($(ARCH),$(filter $(ARCH),rv32imc rv64imc)) +# If Picolibc is available then select it explicitly. Ubuntu 24.04 ships its +# bare metal RISC-V toolchain with Picolibc rather than Newlib, and the default +# is "nosys" so a value must be provided. To avoid having per-distro +# workarounds, always select Picolibc if available. +PICOLIBC_SPECS := $(shell $(CC) --print-file-name=picolibc.specs) +ifneq ($(PICOLIBC_SPECS),picolibc.specs) +# LLVM toolchains supporting more than one target seem to ignore the `-march` +# flag passed when looking up the specs file, so if your system has Picolibc +# libraries for more than one architectures supported by the compiler the +# lookup will return the first available file. +# +# For example, on Ubuntu 24.02 if you have both `picolibc-aarch64-linux-gnu` +# and `picolibc-riscv64-unknown-elf` packages installed, the Qualcomm LLVM +# toolchain (which supports both AArch64 and RISC-V 64) will always return the +# AArch64 picolibc specs even when building for RISC-V. +ifeq ($(shell grep -q "$(PICOLIBC_BASE)" "$(PICOLIBC_SPECS)"; echo $$?),0) +CFLAGS_ARCH += -specs=$(PICOLIBC_SPECS) +USE_PICOLIBC := 1 +endif +endif +endif +MICROPY_FLOAT_IMPL_UPPER = $(shell echo $(MICROPY_FLOAT_IMPL) | tr '[:lower:]' '[:upper:]') +CFLAGS += $(CFLAGS_ARCH) -DMICROPY_FLOAT_IMPL=MICROPY_FLOAT_IMPL_$(MICROPY_FLOAT_IMPL_UPPER) CFLAGS += $(CFLAGS_EXTRA) +ifeq ($(LINK_RUNTIME),1) +# All of these picolibc-specific directives are here to work around a +# limitation of Ubuntu 24.04's RISC-V bare metal toolchain. In short, the +# specific version of GCC in use (10.2.0) does not seem to take into account +# extra paths provided by an explicitly passed specs file when performing name +# resolution via `--print-file-name`. +# +# If Picolibc is used and libc.a fails to resolve, then said file's path will +# be computed by searching the Picolibc libraries root for a libc.a file in a +# subdirectory whose path is built using the current `-march` and `-mabi` +# flags that are passed to GCC. The `PICOLIBC_ROOT` environment variable is +# checked to override the starting point for the library file search, and if +# it is not set then the default value is used, assuming that this is running +# on an Ubuntu 24.04 machine. +# +# This should be revised when the CI base image is updated to a newer Ubuntu +# version (that hopefully contains a newer RISC-V compiler) or to another Linux +# distribution. +ifeq ($(USE_PICOLIBC),1) +LIBM_NAME := libc.a +else ifeq ($(USE_MUSL),1) +LIBM_NAME := libc.a +else +LIBM_NAME := libm.a +endif +# Clang will output the path to libclang_rt.builtins.a instead. The problem is +# that some symbols are duplicated between the builtins library and libc.a. In +# these cases let's leave it to the user to figure out how to handle this for +# the time being. +TOOLCHAIN_LIBGCC := $(realpath $(shell $(CC) $(CFLAGS) --print-libgcc-file-name)) +ifneq ($(findstring clang,$(shell $(CC) --version)),clang) +LIBGCC_PATH = $(TOOLCHAIN_LIBGCC) +else +ifneq ($(LINK_CLANG_CLANGRT),0) +LIBGCC_PATH = $(TOOLCHAIN_LIBGCC) +else +LIBGCC_PATH = +endif +endif +LIBM_PATH := $(realpath $(shell $(CC) $(CFLAGS) --print-file-name=$(LIBM_NAME))) +ifeq ($(USE_PICOLIBC),1) +ifeq ($(LIBM_PATH),) +PICOLIBC_ROOT ?= /usr/lib/picolibc/$(PICOLIBC_BASE)/lib +LIBM_PATH := $(PICOLIBC_ROOT)/$(PICOLIBC_TARGET)/$(LIBM_NAME) +endif +endif +ifneq ($(LINK_CLANG_LIBC),) +ifeq ($(findstring clang,$(shell $(CC) --version)),clang) +LIBC_PATH := $(realpath $(shell $(CC) $(CFLAGS) --print-file-name=libc.a)) +else +LIBC_PATH = +endif +else +LIBC_PATH = +endif +MPY_LD_FLAGS += $(addprefix -l, $(LIBGCC_PATH) $(LIBM_PATH) $(LIBC_PATH)) +endif +ifneq ($(MPY_EXTERN_SYM_FILE),) +MPY_LD_FLAGS += --externs "$(realpath $(MPY_EXTERN_SYM_FILE))" +endif +ifneq ($(ARCH_FLAGS),) +MPY_LD_FLAGS += --arch-flags "$(ARCH_FLAGS)" +endif + ################################################################################ # Build rules @@ -132,12 +243,12 @@ $(CONFIG_H): $(SRC) # Build .o from .c source files $(BUILD)/%.o: %.c $(CONFIG_H) Makefile $(ECHO) "CC $<" - $(Q)$(CROSS)gcc $(CFLAGS) -o $@ -c $< + $(Q)$(CC) $(CFLAGS) -o $@ -c $< # Build .o from .S source files $(BUILD)/%.o: %.S $(CONFIG_H) Makefile $(ECHO) "AS $<" - $(Q)$(CROSS)gcc $(CFLAGS) -o $@ -c $< + $(Q)$(CC) $(CFLAGS) -o $@ -c $< # Build .mpy from .py source files $(BUILD)/%.mpy: %.py @@ -145,11 +256,11 @@ $(BUILD)/%.mpy: %.py $(Q)$(MPY_CROSS) $(MPY_CROSS_FLAGS) -o $@ $< # Build native .mpy from object files -$(BUILD)/$(MOD).native.mpy: $(SRC_O) +$(BUILD)/$(MOD).mpy: $(SRC_O) $(ECHO) "LINK $<" - $(Q)$(MPY_LD) --arch $(ARCH) --qstrs $(CONFIG_H) -o $@ $^ + $(Q)$(MPY_LD) --arch $(ARCH) --qstrs $(CONFIG_H) $(MPY_LD_FLAGS) -o $@ $^ # Build final .mpy from all intermediate .mpy files -$(MOD).mpy: $(BUILD)/$(MOD).native.mpy $(SRC_MPY) +$(MOD).mpy: $(BUILD)/$(MOD).mpy $(SRC_MPY) $(ECHO) "GEN $@" $(Q)$(MPY_TOOL) --merge -o $@ $^ diff --git a/py/emit.h b/py/emit.h index 26f978ba598..033ac9c763b 100644 --- a/py/emit.h +++ b/py/emit.h @@ -144,6 +144,9 @@ typedef struct _emit_method_table_t { void (*unwind_jump)(emit_t *emit, mp_uint_t label, mp_uint_t except_depth); void (*setup_block)(emit_t *emit, mp_uint_t label, int kind); void (*with_cleanup)(emit_t *emit, mp_uint_t label); + #if MICROPY_PY_ASYNC_AWAIT + void (*async_with_setup_finally)(emit_t *emit, mp_uint_t label_aexit_no_exc, mp_uint_t label_finally_block, mp_uint_t label_ret_unwind_jump); + #endif void (*end_finally)(emit_t *emit); void (*get_iter)(emit_t *emit, bool use_stack); void (*for_iter)(emit_t *emit, mp_uint_t label); @@ -201,6 +204,8 @@ extern const emit_method_table_t emit_native_thumb_method_table; extern const emit_method_table_t emit_native_arm_method_table; extern const emit_method_table_t emit_native_xtensa_method_table; extern const emit_method_table_t emit_native_xtensawin_method_table; +extern const emit_method_table_t emit_native_rv32_method_table; +extern const emit_method_table_t emit_native_debug_method_table; extern const mp_emit_method_table_id_ops_t mp_emit_bc_method_table_load_id_ops; extern const mp_emit_method_table_id_ops_t mp_emit_bc_method_table_store_id_ops; @@ -213,6 +218,8 @@ emit_t *emit_native_thumb_new(mp_emit_common_t *emit_common, mp_obj_t *error_slo emit_t *emit_native_arm_new(mp_emit_common_t *emit_common, mp_obj_t *error_slot, uint *label_slot, mp_uint_t max_num_labels); emit_t *emit_native_xtensa_new(mp_emit_common_t *emit_common, mp_obj_t *error_slot, uint *label_slot, mp_uint_t max_num_labels); emit_t *emit_native_xtensawin_new(mp_emit_common_t *emit_common, mp_obj_t *error_slot, uint *label_slot, mp_uint_t max_num_labels); +emit_t *emit_native_rv32_new(mp_emit_common_t *emit_common, mp_obj_t *error_slot, uint *label_slot, mp_uint_t max_num_labels); +emit_t *emit_native_debug_new(mp_emit_common_t *emit_common, 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); @@ -223,6 +230,8 @@ void emit_native_thumb_free(emit_t *emit); void emit_native_arm_free(emit_t *emit); void emit_native_xtensa_free(emit_t *emit); void emit_native_xtensawin_free(emit_t *emit); +void emit_native_rv32_free(emit_t *emit); +void emit_native_debug_free(emit_t *emit); void mp_emit_bc_start_pass(emit_t *emit, pass_kind_t pass, scope_t *scope); bool mp_emit_bc_end_pass(emit_t *emit); @@ -258,6 +267,9 @@ void mp_emit_bc_jump_if_or_pop(emit_t *emit, bool cond, mp_uint_t label); void mp_emit_bc_unwind_jump(emit_t *emit, mp_uint_t label, mp_uint_t except_depth); void mp_emit_bc_setup_block(emit_t *emit, mp_uint_t label, int kind); void mp_emit_bc_with_cleanup(emit_t *emit, mp_uint_t label); +#if MICROPY_PY_ASYNC_AWAIT +void mp_emit_bc_async_with_setup_finally(emit_t *emit, mp_uint_t label_aexit_no_exc, mp_uint_t label_finally_block, mp_uint_t label_ret_unwind_jump); +#endif void mp_emit_bc_end_finally(emit_t *emit); void mp_emit_bc_get_iter(emit_t *emit, bool use_stack); void mp_emit_bc_for_iter(emit_t *emit, mp_uint_t label); @@ -295,12 +307,15 @@ typedef struct _emit_inline_asm_method_table_t { void (*op)(emit_inline_asm_t *emit, qstr op, mp_uint_t n_args, mp_parse_node_t *pn_args); } emit_inline_asm_method_table_t; +extern const emit_inline_asm_method_table_t emit_inline_rv32_method_table; extern const emit_inline_asm_method_table_t emit_inline_thumb_method_table; extern const emit_inline_asm_method_table_t emit_inline_xtensa_method_table; +emit_inline_asm_t *emit_inline_rv32_new(mp_uint_t max_num_labels); emit_inline_asm_t *emit_inline_thumb_new(mp_uint_t max_num_labels); emit_inline_asm_t *emit_inline_xtensa_new(mp_uint_t max_num_labels); +void emit_inline_rv32_free(emit_inline_asm_t *emit); void emit_inline_thumb_free(emit_inline_asm_t *emit); void emit_inline_xtensa_free(emit_inline_asm_t *emit); diff --git a/py/emitbc.c b/py/emitbc.c index 05754cfabf6..5f133ab070b 100644 --- a/py/emitbc.c +++ b/py/emitbc.c @@ -83,7 +83,8 @@ emit_t *emit_bc_new(mp_emit_common_t *emit_common) { void emit_bc_set_max_num_labels(emit_t *emit, mp_uint_t max_num_labels) { emit->max_num_labels = max_num_labels; - emit->label_offsets = m_new(size_t, emit->max_num_labels); + // CIRCUITPY-CHANGE: Don't collect the label offsets + emit->label_offsets = m_malloc_without_collect(sizeof(size_t) * emit->max_num_labels); } void emit_bc_free(emit_t *emit) { @@ -373,7 +374,8 @@ bool mp_emit_bc_end_pass(emit_t *emit) { // calculate size of total code-info + bytecode, in bytes emit->code_info_size = emit->code_info_offset; emit->bytecode_size = emit->bytecode_offset; - emit->code_base = m_new0(byte, emit->code_info_size + emit->bytecode_size); + // CIRCUITPY-CHANGE: Don't collect the bytecode or code info. + emit->code_base = m_malloc_without_collect(sizeof(byte) * (emit->code_info_size + emit->bytecode_size)); } else if (emit->pass == MP_PASS_EMIT) { // Code info and/or bytecode can shrink during this pass. @@ -430,6 +432,12 @@ void mp_emit_bc_set_source_line(emit_t *emit, mp_uint_t source_line) { // If we compile with -O3, don't store line numbers. return; } + #if MICROPY_DYNAMIC_COMPILER + if (!mp_dynamic_compiler.include_source_lines) { + // Don't store line numbers if explicitly disabled. + return; + } + #endif if (source_line > emit->last_source_line) { mp_uint_t bytes_to_skip = emit->bytecode_offset - emit->last_source_line_offset; mp_uint_t lines_to_skip = source_line - emit->last_source_line; @@ -666,6 +674,27 @@ void mp_emit_bc_with_cleanup(emit_t *emit, mp_uint_t label) { mp_emit_bc_adjust_stack_size(emit, -4); } +#if MICROPY_PY_ASYNC_AWAIT +void mp_emit_bc_async_with_setup_finally(emit_t *emit, mp_uint_t label_aexit_no_exc, mp_uint_t label_finally_block, mp_uint_t label_ret_unwind_jump) { + // The async-with body has executed and no exception was raised, the execution fell through to this point. + // Stack: (..., ctx_mgr) + + // Finish async-with body and prepare to enter "finally" block. + mp_emit_bc_load_const_tok(emit, MP_TOKEN_KW_NONE); // to tell end_finally there's no exception + mp_emit_bc_rot_two(emit); + mp_emit_bc_jump(emit, label_aexit_no_exc); // jump to code to call __aexit__ + + // Start of "finally" block which is entered via one of: an exception propagating out, a return, an unwind jump. + mp_emit_bc_label_assign(emit, label_finally_block); + + // Detect which case we have by the TOS being an exception or not. + mp_emit_bc_dup_top(emit); + mp_emit_bc_load_global(emit, MP_QSTR_BaseException, MP_EMIT_IDOP_GLOBAL_GLOBAL); + mp_emit_bc_binary_op(emit, MP_BINARY_OP_EXCEPTION_MATCH); + mp_emit_bc_pop_jump_if(emit, false, label_ret_unwind_jump); // if not an exception then we have return or unwind jump. +} +#endif + void mp_emit_bc_end_finally(emit_t *emit) { emit_write_bytecode_byte(emit, -1, MP_BC_END_FINALLY); } @@ -773,10 +802,10 @@ static void emit_bc_call_function_method_helper(emit_t *emit, int stack_adj, mp_ // each positional arg is one object, each kwarg is two objects, the key // and the value and one extra object for the star args bitmap. stack_adj -= (int)n_positional + 2 * (int)n_keyword + 1; - emit_write_bytecode_byte_uint(emit, stack_adj, bytecode_base + 1, (n_keyword << 8) | n_positional); // TODO make it 2 separate uints? + emit_write_bytecode_byte_uint(emit, stack_adj, bytecode_base + 1, (n_keyword << 8) | n_positional); } else { stack_adj -= (int)n_positional + 2 * (int)n_keyword; - emit_write_bytecode_byte_uint(emit, stack_adj, bytecode_base, (n_keyword << 8) | n_positional); // TODO make it 2 separate uints? + emit_write_bytecode_byte_uint(emit, stack_adj, bytecode_base, (n_keyword << 8) | n_positional); } } @@ -862,6 +891,9 @@ const emit_method_table_t emit_bc_method_table = { mp_emit_bc_unwind_jump, mp_emit_bc_setup_block, mp_emit_bc_with_cleanup, + #if MICROPY_PY_ASYNC_AWAIT + mp_emit_bc_async_with_setup_finally, + #endif mp_emit_bc_end_finally, mp_emit_bc_get_iter, mp_emit_bc_for_iter, diff --git a/py/emitcommon.c b/py/emitcommon.c index a9eb6e2021f..1369c544c54 100644 --- a/py/emitcommon.c +++ b/py/emitcommon.c @@ -25,6 +25,7 @@ */ #include +#include #include "py/emit.h" #include "py/nativeglue.h" @@ -72,7 +73,25 @@ static bool strictly_equal(mp_obj_t a, mp_obj_t b) { } return true; } else { - return mp_obj_equal(a, b); + if (!mp_obj_equal(a, b)) { + return false; + } + #if MICROPY_PY_BUILTINS_FLOAT && MICROPY_COMP_CONST_FLOAT + if (a_type == &mp_type_float) { + mp_float_t a_val = mp_obj_float_get(a); + // CIRCUITPY-CHANGE: ignore float equal warning + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wfloat-equal" + if (a_val == (mp_float_t)0.0) { + // Although 0.0 == -0.0, they are not strictly_equal and + // must be stored as two different constants in .mpy files + mp_float_t b_val = mp_obj_float_get(b); + return signbit(a_val) == signbit(b_val); + } + #pragma GCC diagnostic pop + } + #endif + return true; } } diff --git a/py/emitglue.c b/py/emitglue.c index 8ab624ee7cf..3b479079af0 100644 --- a/py/emitglue.c +++ b/py/emitglue.c @@ -32,6 +32,7 @@ #include #include "py/emitglue.h" +#include "py/mphal.h" #include "py/runtime0.h" #include "py/bc.h" #include "py/objfun.h" @@ -49,10 +50,6 @@ #define DEBUG_OP_printf(...) (void)0 #endif -#if MICROPY_DEBUG_PRINTERS -mp_uint_t mp_verbose_flag = 0; -#endif - mp_raw_code_t *mp_emit_glue_new_raw_code(void) { mp_raw_code_t *rc = m_new0(mp_raw_code_t, 1); rc->kind = MP_CODE_RESERVED; @@ -97,7 +94,7 @@ void mp_emit_glue_assign_bytecode(mp_raw_code_t *rc, const byte *code, #endif } -#if MICROPY_EMIT_MACHINE_CODE +#if MICROPY_EMIT_INLINE_ASM || MICROPY_ENABLE_NATIVE_CODE void mp_emit_glue_assign_native(mp_raw_code_t *rc, mp_raw_code_kind_t kind, const void *fun_data, mp_uint_t fun_len, mp_raw_code_t **children, #if MICROPY_PERSISTENT_CODE_SAVE @@ -112,7 +109,7 @@ void mp_emit_glue_assign_native(mp_raw_code_t *rc, mp_raw_code_kind_t kind, cons // Some architectures require flushing/invalidation of the I/D caches, // so that the generated native code which was created in data RAM will // be available for execution from instruction RAM. - #if MICROPY_EMIT_THUMB || MICROPY_EMIT_INLINE_THUMB + #if defined(__thumb__) || defined(__thumb2__) // CIRCUITPY-CHANGE: prevent warning #if defined(__ICACHE_PRESENT) && __ICACHE_PRESENT == 1 // Flush D-cache, so the code emitted is stored in RAM. @@ -120,10 +117,10 @@ void mp_emit_glue_assign_native(mp_raw_code_t *rc, mp_raw_code_kind_t kind, cons // Invalidate I-cache, so the newly-created code is reloaded from RAM. SCB_InvalidateICache(); #endif - #elif MICROPY_EMIT_ARM - #if (defined(__linux__) && defined(__GNUC__)) || __ARM_ARCH == 7 - __builtin___clear_cache((void *)fun_data, (uint8_t *)fun_data + fun_len); #elif defined(__arm__) + #if (defined(__linux__) && defined(__GNUC__)) || __ARM_ARCH == 7 + __builtin___clear_cache((void *)fun_data, (char *)fun_data + fun_len); + #else // Flush I-cache and D-cache. asm volatile ( "0:" @@ -133,6 +130,9 @@ void mp_emit_glue_assign_native(mp_raw_code_t *rc, mp_raw_code_kind_t kind, cons "mcr p15, 0, r0, c7, c7, 0\n" // invalidate I-cache and D-cache : : : "r0", "cc"); #endif + #elif defined(__riscv) && defined(MP_HAL_CLEAN_DCACHE) + // Flush the D-cache. + MP_HAL_CLEAN_DCACHE(fun_data, fun_len); #endif rc->kind = kind; @@ -168,7 +168,7 @@ void mp_emit_glue_assign_native(mp_raw_code_t *rc, mp_raw_code_kind_t kind, cons } DEBUG_printf("\n"); - #ifdef WRITE_CODE + #if WRITE_CODE FILE *fp_write_code = fopen("out-code", "wb"); fwrite(fun_data, fun_len, 1, fp_write_code); fclose(fp_write_code); @@ -189,7 +189,7 @@ mp_obj_t mp_make_function_from_proto_fun(mp_proto_fun_t proto_fun, const mp_modu // def_kw_args must be MP_OBJ_NULL or a dict assert(def_args == NULL || def_args[1] == MP_OBJ_NULL || mp_obj_is_type(def_args[1], &mp_type_dict)); - #if MICROPY_MODULE_FROZEN_MPY + #if MICROPY_MODULE_FROZEN_MPY || MICROPY_PY_FUNCTION_ATTRS_CODE if (mp_proto_fun_is_bytecode(proto_fun)) { const uint8_t *bc = proto_fun; mp_obj_t fun = mp_obj_new_fun_bc(def_args, bc, context, NULL); @@ -215,7 +215,7 @@ mp_obj_t mp_make_function_from_proto_fun(mp_proto_fun_t proto_fun, const mp_modu // make the function, depending on the raw code kind mp_obj_t fun; switch (rc->kind) { - #if MICROPY_EMIT_NATIVE + #if MICROPY_ENABLE_NATIVE_CODE case MP_CODE_NATIVE_PY: fun = mp_obj_new_fun_native(def_args, rc->fun_data, context, rc->children); // Check for a generator function, and if so change the type of the object diff --git a/py/emitglue.h b/py/emitglue.h index d19503b823f..674807910c1 100644 --- a/py/emitglue.h +++ b/py/emitglue.h @@ -83,7 +83,7 @@ typedef struct _mp_raw_code_t { #if MICROPY_PERSISTENT_CODE_SAVE uint32_t fun_data_len; // for mp_raw_code_save uint16_t n_children; - #if MICROPY_EMIT_MACHINE_CODE + #if MICROPY_EMIT_INLINE_ASM || MICROPY_ENABLE_NATIVE_CODE uint16_t prelude_offset; #endif #if MICROPY_PY_SYS_SETTRACE @@ -116,7 +116,7 @@ typedef struct _mp_raw_code_truncated_t { #if MICROPY_PERSISTENT_CODE_SAVE uint32_t fun_data_len; uint16_t n_children; - #if MICROPY_EMIT_MACHINE_CODE + #if MICROPY_EMIT_INLINE_ASM || MICROPY_ENABLE_NATIVE_CODE uint16_t prelude_offset; #endif #if MICROPY_PY_SYS_SETTRACE diff --git a/py/emitinlinerv32.c b/py/emitinlinerv32.c new file mode 100644 index 00000000000..b175ae0ddc8 --- /dev/null +++ b/py/emitinlinerv32.c @@ -0,0 +1,958 @@ +/* + * This file is part of the MicroPython project, https://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2024 Alessandro Gatti + * + * 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 +#include +#include + +#include "py/emit.h" +#include "py/misc.h" + +#if MICROPY_EMIT_INLINE_RV32 + +#include "py/asmrv32.h" + +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" +#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" +#undef DEF_RULE +#undef DEF_RULE_NC +} pn_kind_t; + +struct _emit_inline_asm_t { + asm_rv32_t as; + uint16_t pass; + mp_obj_t *error_slot; + mp_uint_t max_num_labels; + qstr *label_lookup; +}; + +static const qstr_short_t REGISTERS_QSTR_TABLE[] = { + MP_QSTR_zero, MP_QSTR_ra, MP_QSTR_sp, MP_QSTR_gp, MP_QSTR_tp, MP_QSTR_t0, MP_QSTR_t1, MP_QSTR_t2, + MP_QSTR_s0, MP_QSTR_s1, MP_QSTR_a0, MP_QSTR_a1, MP_QSTR_a2, MP_QSTR_a3, MP_QSTR_a4, MP_QSTR_a5, + MP_QSTR_a6, MP_QSTR_a7, MP_QSTR_s2, MP_QSTR_s3, MP_QSTR_s4, MP_QSTR_s5, MP_QSTR_s6, MP_QSTR_s7, + MP_QSTR_s8, MP_QSTR_s9, MP_QSTR_s10, MP_QSTR_s11, MP_QSTR_t3, MP_QSTR_t4, MP_QSTR_t5, MP_QSTR_t6, + MP_QSTR_x0, MP_QSTR_x1, MP_QSTR_x2, MP_QSTR_x3, MP_QSTR_x4, MP_QSTR_x5, MP_QSTR_x6, MP_QSTR_x7, + MP_QSTR_x8, MP_QSTR_x9, MP_QSTR_x10, MP_QSTR_x11, MP_QSTR_x12, MP_QSTR_x13, MP_QSTR_x14, MP_QSTR_x15, + MP_QSTR_x16, MP_QSTR_x17, MP_QSTR_x18, MP_QSTR_x19, MP_QSTR_x20, MP_QSTR_x21, MP_QSTR_x22, MP_QSTR_x23, + MP_QSTR_x24, MP_QSTR_x25, MP_QSTR_x26, MP_QSTR_x27, MP_QSTR_x28, MP_QSTR_x29, MP_QSTR_x30, MP_QSTR_x31, +}; + +//////////////////////////////////////////////////////////////////////////////// + +static inline void emit_inline_rv32_error_msg(emit_inline_asm_t *emit, mp_rom_error_text_t msg) { + *emit->error_slot = mp_obj_new_exception_msg(&mp_type_SyntaxError, msg); +} + +static inline void emit_inline_rv32_error_exc(emit_inline_asm_t *emit, mp_obj_t exc) { + *emit->error_slot = exc; +} + +emit_inline_asm_t *emit_inline_rv32_new(mp_uint_t max_num_labels) { + emit_inline_asm_t *emit = m_new_obj(emit_inline_asm_t); + memset(&emit->as, 0, sizeof(emit->as)); + mp_asm_base_init(&emit->as.base, max_num_labels); + emit->max_num_labels = max_num_labels; + emit->label_lookup = m_new(qstr, max_num_labels); + return emit; +} + +void emit_inline_rv32_free(emit_inline_asm_t *emit) { + m_del(qstr, emit->label_lookup, emit->max_num_labels); + mp_asm_base_deinit(&emit->as.base, false); + m_del_obj(emit_inline_asm_t, emit); +} + +static void emit_inline_rv32_start_pass(emit_inline_asm_t *emit, pass_kind_t pass, mp_obj_t *error_slot) { + emit->pass = pass; + emit->error_slot = error_slot; + if (emit->pass == MP_PASS_CODE_SIZE) { + memset(emit->label_lookup, 0, emit->max_num_labels * sizeof(qstr)); + } + mp_asm_base_start_pass(&emit->as.base, pass == MP_PASS_EMIT ? MP_ASM_PASS_EMIT : MP_ASM_PASS_COMPUTE); +} + +static void emit_inline_rv32_end_pass(emit_inline_asm_t *emit, mp_uint_t type_sig) { + // c.jr ra + asm_rv32_opcode_cjr(&emit->as, ASM_RV32_REG_RA); + asm_rv32_end_pass(&emit->as); +} + +static bool parse_register_node(mp_parse_node_t node, mp_uint_t *register_number, bool compressed) { + assert(register_number != NULL && "Register number pointer is NULL."); + + if (!MP_PARSE_NODE_IS_ID(node)) { + return false; + } + + qstr node_qstr = MP_PARSE_NODE_LEAF_ARG(node); + for (mp_uint_t index = 0; index < MP_ARRAY_SIZE(REGISTERS_QSTR_TABLE); index++) { + if (node_qstr == REGISTERS_QSTR_TABLE[index]) { + mp_uint_t number = index % RV32_AVAILABLE_REGISTERS_COUNT; + if (!compressed || (compressed && RV32_IS_IN_C_REGISTER_WINDOW(number))) { + *register_number = compressed ? RV32_MAP_IN_C_REGISTER_WINDOW(number) : number; + return true; + } + break; + } + } + + return false; +} + +static mp_uint_t lookup_label(emit_inline_asm_t *emit, mp_parse_node_t node, qstr *qstring) { + assert(qstring && "qstring pointer is NULL"); + + *qstring = MP_PARSE_NODE_LEAF_ARG(node); + for (mp_uint_t label = 0; label < emit->max_num_labels; label++) { + if (emit->label_lookup[label] == *qstring) { + return label; + } + } + + return emit->max_num_labels; +} + +static inline ptrdiff_t label_code_offset(emit_inline_asm_t *emit, mp_uint_t label_index) { + return emit->as.base.label_offsets[label_index] - emit->as.base.code_offset; +} + +static mp_uint_t emit_inline_rv32_count_params(emit_inline_asm_t *emit, mp_uint_t parameters_count, mp_parse_node_t *parameter_nodes) { + // TODO: Raise this up to 8? RV32I has 8 A-registers that are meant to + // be used for passing arguments. + + if (parameters_count > 4) { + emit_inline_rv32_error_msg(emit, MP_ERROR_TEXT("can only have up to 4 parameters for RV32 assembly")); + return 0; + } + + mp_uint_t register_index = 0; + for (mp_uint_t index = 0; index < parameters_count; index++) { + bool valid_register = parse_register_node(parameter_nodes[index], ®ister_index, false); + if (!valid_register || (register_index != (ASM_RV32_REG_A0 + index))) { + emit_inline_rv32_error_msg(emit, MP_ERROR_TEXT("parameters must be registers in sequence a0 to a3")); + return 0; + } + } + + return parameters_count; +} + +static bool emit_inline_rv32_label(emit_inline_asm_t *emit, mp_uint_t label_num, qstr label_id) { + assert(label_num < emit->max_num_labels); + if (emit->pass == MP_PASS_CODE_SIZE) { + for (mp_uint_t index = 0; index < emit->max_num_labels; index++) { + if (emit->label_lookup[index] == label_id) { + return false; + } + } + } + emit->label_lookup[label_num] = label_id; + mp_asm_base_label_assign(&emit->as.base, label_num); + return true; +} + +typedef enum { + CALL_RRR, // Opcode Register, Register, Register + CALL_RR, // Opcode Register, Register + CALL_RRI, // Opcode Register, Register, Immediate + CALL_RRL, // Opcode Register, Register, Label + CALL_RI, // Opcode Register, Immediate + CALL_L, // Opcode Label + CALL_R, // Opcode Register + CALL_RL, // Opcode Register, Label + CALL_N, // Opcode + CALL_RII, // Opcode Register, Register, Immediate + CALL_RIR, // Opcode Register, Immediate(Register) + CALL_COUNT +} call_convention_t; + +#define N 0 // No argument +#define R 1 // Register +#define I 2 // Immediate +#define L 3 // Label +#define C (1 << 2) // Compressed register +#define U (1 << 2) // Unsigned immediate +#define Z (1 << 3) // Non-zero + +typedef void (*call_ri_t)(asm_rv32_t *state, mp_uint_t rd, mp_int_t immediate); +typedef void (*call_rri_t)(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs1, mp_int_t immediate); +typedef void (*call_rii_t)(asm_rv32_t *state, mp_uint_t rd, mp_uint_t immediate1, mp_int_t immediate2); +typedef void (*call_rrr_t)(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs1, mp_uint_t rs2); +typedef void (*call_rr_t)(asm_rv32_t *state, mp_uint_t rd, mp_uint_t rs); +typedef void (*call_i_t)(asm_rv32_t *state, mp_int_t immediate); +typedef void (*call_r_t)(asm_rv32_t *state, mp_uint_t rd); +typedef void (*call_n_t)(asm_rv32_t *state); + +typedef struct _opcode_t { + qstr_short_t qstring; + uint16_t argument1_mask : 4; + uint16_t argument2_mask : 4; + uint16_t argument3_mask : 4; + uint16_t parse_nodes : 2; + // 2 bits available here + uint32_t calling_convention : 4; + uint32_t argument1_kind : 4; + uint32_t argument1_shift : 4; + uint32_t argument2_kind : 4; + uint32_t argument2_shift : 4; + uint32_t argument3_kind : 4; + uint32_t argument3_shift : 4; + uint32_t required_extensions : 1; + // 3 bits available here + void *emitter; +} opcode_t; + +#define opcode_li asm_rv32_emit_optimised_load_immediate + +static void opcode_la(asm_rv32_t *state, mp_uint_t rd, mp_int_t displacement) { + // This cannot be optimised for size, otherwise label addresses would move around. + mp_uint_t upper = (mp_uint_t)displacement & 0xFFFFF000; + mp_uint_t lower = (mp_uint_t)displacement & 0x00000FFF; + if ((lower & 0x800) != 0) { + upper += 0x1000; + } + asm_rv32_opcode_auipc(state, rd, upper); + asm_rv32_opcode_addi(state, rd, rd, lower); +} + +#define RC (R | C) +#define IU (I | U) +#define IZ (I | Z) +#define IUZ (I | U | Z) + +#define MASK_NOT_USED 0 + +enum { + MASK_FFFFFFFF, + MASK_00000FFF, + MASK_FFFFF000, + MASK_00001FFE, + MASK_0000001F, + MASK_FFFFFFFE, + MASK_0000003F, + MASK_0000FF00, + MASK_000003FC, + MASK_000001FE, + MASK_00000FFE, + MASK_FFFFFFFA, + MASK_0001F800, + MASK_0000007C, + MASK_000000FC, + MASK_001FFFFE, +}; + +static const uint32_t OPCODE_MASKS[] = { + [MASK_FFFFFFFF] = 0xFFFFFFFF, + [MASK_00000FFF] = 0x00000FFF, + [MASK_FFFFF000] = 0xFFFFF000, + [MASK_00001FFE] = 0x00001FFE, + [MASK_0000001F] = 0x0000001F, + [MASK_FFFFFFFE] = 0xFFFFFFFE, + [MASK_0000003F] = 0x0000003F, + [MASK_0000FF00] = 0x0000FF00, + [MASK_000003FC] = 0x000003FC, + [MASK_000001FE] = 0x000001FE, + [MASK_00000FFE] = 0x00000FFE, + [MASK_FFFFFFFA] = 0xFFFFFFFA, + [MASK_0001F800] = 0x0001F800, + [MASK_0000007C] = 0x0000007C, + [MASK_000000FC] = 0x000000FC, + [MASK_001FFFFE] = 0x001FFFFE, +}; + +static const opcode_t OPCODES[] = { + { MP_QSTR_add, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_FFFFFFFF, 3, CALL_RRR, R, 0, R, 0, R, 0, RV32_EXT_NONE, asm_rv32_opcode_add }, + { MP_QSTR_addi, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_00000FFF, 3, CALL_RRI, R, 0, R, 0, I, 0, RV32_EXT_NONE, asm_rv32_opcode_addi }, + { MP_QSTR_and_, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_FFFFFFFF, 3, CALL_RRR, R, 0, R, 0, R, 0, RV32_EXT_NONE, asm_rv32_opcode_and }, + { MP_QSTR_andi, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_00000FFF, 3, CALL_RRI, R, 0, R, 0, I, 0, RV32_EXT_NONE, asm_rv32_opcode_andi }, + { MP_QSTR_auipc, MASK_FFFFFFFF, MASK_FFFFF000, MASK_NOT_USED, 2, CALL_RI, R, 0, I, 12, N, 0, RV32_EXT_NONE, asm_rv32_opcode_auipc }, + { MP_QSTR_beq, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_00001FFE, 3, CALL_RRL, R, 0, R, 0, L, 0, RV32_EXT_NONE, asm_rv32_opcode_beq }, + { MP_QSTR_bge, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_00001FFE, 3, CALL_RRL, R, 0, R, 0, L, 0, RV32_EXT_NONE, asm_rv32_opcode_bge }, + { MP_QSTR_bgeu, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_00001FFE, 3, CALL_RRL, R, 0, R, 0, L, 0, RV32_EXT_NONE, asm_rv32_opcode_bgeu }, + { MP_QSTR_blt, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_00001FFE, 3, CALL_RRL, R, 0, R, 0, L, 0, RV32_EXT_NONE, asm_rv32_opcode_blt }, + { MP_QSTR_bltu, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_00001FFE, 3, CALL_RRL, R, 0, R, 0, L, 0, RV32_EXT_NONE, asm_rv32_opcode_bltu }, + { MP_QSTR_bne, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_00001FFE, 3, CALL_RRL, R, 0, R, 0, L, 0, RV32_EXT_NONE, asm_rv32_opcode_bne }, + { MP_QSTR_csrrc, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_00000FFF, 3, CALL_RRI, R, 0, R, 0, IU, 0, RV32_EXT_NONE, asm_rv32_opcode_csrrc }, + { MP_QSTR_csrrs, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_00000FFF, 3, CALL_RRI, R, 0, R, 0, IU, 0, RV32_EXT_NONE, asm_rv32_opcode_csrrs }, + { MP_QSTR_csrrw, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_00000FFF, 3, CALL_RRI, R, 0, R, 0, IU, 0, RV32_EXT_NONE, asm_rv32_opcode_csrrw }, + { MP_QSTR_csrrci, MASK_FFFFFFFF, MASK_00000FFF, MASK_0000001F, 3, CALL_RII, R, 0, IU, 0, IU, 0, RV32_EXT_NONE, asm_rv32_opcode_csrrci }, + { MP_QSTR_csrrsi, MASK_FFFFFFFF, MASK_00000FFF, MASK_0000001F, 3, CALL_RII, R, 0, IU, 0, IU, 0, RV32_EXT_NONE, asm_rv32_opcode_csrrsi }, + { MP_QSTR_csrrwi, MASK_FFFFFFFF, MASK_00000FFF, MASK_0000001F, 3, CALL_RII, R, 0, IU, 0, IU, 0, RV32_EXT_NONE, asm_rv32_opcode_csrrwi }, + { MP_QSTR_c_add, MASK_FFFFFFFE, MASK_FFFFFFFE, MASK_NOT_USED, 2, CALL_RR, R, 0, R, 0, N, 0, RV32_EXT_NONE, asm_rv32_opcode_cadd }, + { MP_QSTR_c_addi, MASK_FFFFFFFE, MASK_0000003F, MASK_NOT_USED, 2, CALL_RI, R, 0, IZ, 0, N, 0, RV32_EXT_NONE, asm_rv32_opcode_caddi }, + { MP_QSTR_c_addi4spn, MASK_0000FF00, MASK_000003FC, MASK_NOT_USED, 2, CALL_RI, R, 0, IUZ, 0, N, 0, RV32_EXT_NONE, asm_rv32_opcode_caddi4spn }, + { MP_QSTR_c_and, MASK_0000FF00, MASK_0000FF00, MASK_NOT_USED, 2, CALL_RR, RC, 0, RC, 0, N, 0, RV32_EXT_NONE, asm_rv32_opcode_cand }, + { MP_QSTR_c_andi, MASK_0000FF00, MASK_0000003F, MASK_NOT_USED, 2, CALL_RI, RC, 0, I, 0, N, 0, RV32_EXT_NONE, asm_rv32_opcode_candi }, + { MP_QSTR_c_beqz, MASK_0000FF00, MASK_000001FE, MASK_NOT_USED, 2, CALL_RL, RC, 0, L, 0, N, 0, RV32_EXT_NONE, asm_rv32_opcode_cbeqz }, + { MP_QSTR_c_bnez, MASK_0000FF00, MASK_000001FE, MASK_NOT_USED, 2, CALL_RL, RC, 0, L, 0, N, 0, RV32_EXT_NONE, asm_rv32_opcode_cbnez }, + { MP_QSTR_c_ebreak, MASK_NOT_USED, MASK_NOT_USED, MASK_NOT_USED, 0, CALL_N, N, 0, N, 0, N, 0, RV32_EXT_NONE, asm_rv32_opcode_cebreak }, + { MP_QSTR_c_j, MASK_00000FFE, MASK_NOT_USED, MASK_NOT_USED, 1, CALL_L, L, 0, N, 0, N, 0, RV32_EXT_NONE, asm_rv32_opcode_cj }, + { MP_QSTR_c_jal, MASK_00000FFE, MASK_NOT_USED, MASK_NOT_USED, 1, CALL_L, L, 0, N, 0, N, 0, RV32_EXT_NONE, asm_rv32_opcode_cjal }, + { MP_QSTR_c_jalr, MASK_FFFFFFFE, MASK_NOT_USED, MASK_NOT_USED, 1, CALL_R, R, 0, N, 0, N, 0, RV32_EXT_NONE, asm_rv32_opcode_cjalr }, + { MP_QSTR_c_jr, MASK_FFFFFFFE, MASK_NOT_USED, MASK_NOT_USED, 1, CALL_R, R, 0, N, 0, N, 0, RV32_EXT_NONE, asm_rv32_opcode_cjr }, + { MP_QSTR_c_li, MASK_FFFFFFFE, MASK_0000003F, MASK_NOT_USED, 2, CALL_RI, R, 0, I, 0, N, 0, RV32_EXT_NONE, asm_rv32_opcode_cli }, + { MP_QSTR_c_lui, MASK_FFFFFFFA, MASK_0001F800, MASK_NOT_USED, 2, CALL_RI, R, 0, IUZ, 12, N, 0, RV32_EXT_NONE, asm_rv32_opcode_clui }, + { MP_QSTR_c_lw, MASK_0000FF00, MASK_0000007C, MASK_0000FF00, 2, CALL_RIR, RC, 0, I, 0, RC, 0, RV32_EXT_NONE, asm_rv32_opcode_clw }, + { MP_QSTR_c_lwsp, MASK_FFFFFFFE, MASK_000000FC, MASK_NOT_USED, 2, CALL_RI, R, 0, I, 0, N, 0, RV32_EXT_NONE, asm_rv32_opcode_clwsp }, + { MP_QSTR_c_mv, MASK_FFFFFFFE, MASK_FFFFFFFE, MASK_NOT_USED, 2, CALL_RR, R, 0, R, 0, N, 0, RV32_EXT_NONE, asm_rv32_opcode_cmv }, + { MP_QSTR_c_nop, MASK_NOT_USED, MASK_NOT_USED, MASK_NOT_USED, 0, CALL_N, N, 0, N, 0, N, 0, RV32_EXT_NONE, asm_rv32_opcode_cnop }, + { MP_QSTR_c_or, MASK_0000FF00, MASK_0000FF00, MASK_NOT_USED, 2, CALL_RR, RC, 0, RC, 0, N, 0, RV32_EXT_NONE, asm_rv32_opcode_cor }, + { MP_QSTR_c_slli, MASK_FFFFFFFE, MASK_0000001F, MASK_NOT_USED, 2, CALL_RI, R, 0, IU, 0, N, 0, RV32_EXT_NONE, asm_rv32_opcode_cslli }, + { MP_QSTR_c_srai, MASK_0000FF00, MASK_0000001F, MASK_NOT_USED, 2, CALL_RI, RC, 0, IU, 0, N, 0, RV32_EXT_NONE, asm_rv32_opcode_csrai }, + { MP_QSTR_c_srli, MASK_0000FF00, MASK_0000001F, MASK_NOT_USED, 2, CALL_RI, RC, 0, IU, 0, N, 0, RV32_EXT_NONE, asm_rv32_opcode_csrli }, + { MP_QSTR_c_sub, MASK_0000FF00, MASK_0000FF00, MASK_NOT_USED, 2, CALL_RR, RC, 0, RC, 0, N, 0, RV32_EXT_NONE, asm_rv32_opcode_csub }, + { MP_QSTR_c_sw, MASK_0000FF00, MASK_0000007C, MASK_0000FF00, 2, CALL_RIR, RC, 0, I, 0, RC, 0, RV32_EXT_NONE, asm_rv32_opcode_csw }, + { MP_QSTR_c_swsp, MASK_FFFFFFFF, MASK_000000FC, MASK_NOT_USED, 2, CALL_RI, R, 0, I, 0, N, 0, RV32_EXT_NONE, asm_rv32_opcode_cswsp }, + { MP_QSTR_c_xor, MASK_0000FF00, MASK_0000FF00, MASK_NOT_USED, 2, CALL_RR, RC, 0, RC, 0, N, 0, RV32_EXT_NONE, asm_rv32_opcode_cxor }, + { MP_QSTR_div, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_FFFFFFFF, 3, CALL_RRR, R, 0, R, 0, R, 0, RV32_EXT_NONE, asm_rv32_opcode_div }, + { MP_QSTR_divu, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_FFFFFFFF, 3, CALL_RRR, R, 0, R, 0, R, 0, RV32_EXT_NONE, asm_rv32_opcode_divu }, + { MP_QSTR_ebreak, MASK_NOT_USED, MASK_NOT_USED, MASK_NOT_USED, 0, CALL_N, N, 0, N, 0, N, 0, RV32_EXT_NONE, asm_rv32_opcode_ebreak }, + { MP_QSTR_ecall, MASK_NOT_USED, MASK_NOT_USED, MASK_NOT_USED, 0, CALL_N, N, 0, N, 0, N, 0, RV32_EXT_NONE, asm_rv32_opcode_ecall }, + { MP_QSTR_jal, MASK_FFFFFFFF, MASK_001FFFFE, MASK_NOT_USED, 2, CALL_RL, R, 0, L, 0, N, 0, RV32_EXT_NONE, asm_rv32_opcode_jal }, + { MP_QSTR_jalr, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_00000FFF, 3, CALL_RRI, R, 0, R, 0, I, 0, RV32_EXT_NONE, asm_rv32_opcode_jalr }, + { MP_QSTR_la, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_NOT_USED, 2, CALL_RL, R, 0, L, 0, N, 0, RV32_EXT_NONE, opcode_la }, + { MP_QSTR_lb, MASK_FFFFFFFF, MASK_00000FFF, MASK_FFFFFFFF, 2, CALL_RIR, R, 0, I, 0, R, 0, RV32_EXT_NONE, asm_rv32_opcode_lb }, + { MP_QSTR_lbu, MASK_FFFFFFFF, MASK_00000FFF, MASK_FFFFFFFF, 2, CALL_RIR, R, 0, I, 0, R, 0, RV32_EXT_NONE, asm_rv32_opcode_lbu }, + { MP_QSTR_lh, MASK_FFFFFFFF, MASK_00000FFF, MASK_FFFFFFFF, 2, CALL_RIR, R, 0, I, 0, R, 0, RV32_EXT_NONE, asm_rv32_opcode_lh }, + { MP_QSTR_lhu, MASK_FFFFFFFF, MASK_00000FFF, MASK_FFFFFFFF, 2, CALL_RIR, R, 0, I, 0, R, 0, RV32_EXT_NONE, asm_rv32_opcode_lhu }, + { MP_QSTR_li, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_NOT_USED, 2, CALL_RI, R, 0, I, 0, N, 0, RV32_EXT_NONE, opcode_li }, + { MP_QSTR_lui, MASK_FFFFFFFF, MASK_FFFFF000, MASK_NOT_USED, 2, CALL_RI, R, 0, I, 12, N, 0, RV32_EXT_NONE, asm_rv32_opcode_lui }, + { MP_QSTR_lw, MASK_FFFFFFFF, MASK_00000FFF, MASK_FFFFFFFF, 2, CALL_RIR, R, 0, I, 0, R, 0, RV32_EXT_NONE, asm_rv32_opcode_lw }, + { MP_QSTR_mv, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_NOT_USED, 2, CALL_RR, R, 0, R, 0, N, 0, RV32_EXT_NONE, asm_rv32_opcode_cmv }, + { MP_QSTR_mul, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_FFFFFFFF, 3, CALL_RRR, R, 0, R, 0, R, 0, RV32_EXT_NONE, asm_rv32_opcode_mul }, + { MP_QSTR_mulh, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_FFFFFFFF, 3, CALL_RRR, R, 0, R, 0, R, 0, RV32_EXT_NONE, asm_rv32_opcode_mulh }, + { MP_QSTR_mulhsu, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_FFFFFFFF, 3, CALL_RRR, R, 0, R, 0, R, 0, RV32_EXT_NONE, asm_rv32_opcode_mulhsu }, + { MP_QSTR_mulhu, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_FFFFFFFF, 3, CALL_RRR, R, 0, R, 0, R, 0, RV32_EXT_NONE, asm_rv32_opcode_mulhu }, + { MP_QSTR_or_, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_FFFFFFFF, 3, CALL_RRR, R, 0, R, 0, R, 0, RV32_EXT_NONE, asm_rv32_opcode_or }, + { MP_QSTR_ori, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_00000FFF, 3, CALL_RRI, R, 0, R, 0, I, 0, RV32_EXT_NONE, asm_rv32_opcode_ori }, + { MP_QSTR_rem, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_FFFFFFFF, 3, CALL_RRR, R, 0, R, 0, R, 0, RV32_EXT_NONE, asm_rv32_opcode_rem }, + { MP_QSTR_remu, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_FFFFFFFF, 3, CALL_RRR, R, 0, R, 0, R, 0, RV32_EXT_NONE, asm_rv32_opcode_remu }, + { MP_QSTR_sb, MASK_FFFFFFFF, MASK_00000FFF, MASK_FFFFFFFF, 2, CALL_RIR, R, 0, I, 0, R, 0, RV32_EXT_NONE, asm_rv32_opcode_sb }, + { MP_QSTR_sh, MASK_FFFFFFFF, MASK_00000FFF, MASK_FFFFFFFF, 2, CALL_RIR, R, 0, I, 0, R, 0, RV32_EXT_NONE, asm_rv32_opcode_sh }, + { MP_QSTR_sh1add, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_FFFFFFFF, 3, CALL_RRR, R, 0, R, 0, R, 0, RV32_EXT_ZBA, asm_rv32_opcode_sh1add }, + { MP_QSTR_sh2add, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_FFFFFFFF, 3, CALL_RRR, R, 0, R, 0, R, 0, RV32_EXT_ZBA, asm_rv32_opcode_sh2add }, + { MP_QSTR_sh3add, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_FFFFFFFF, 3, CALL_RRR, R, 0, R, 0, R, 0, RV32_EXT_ZBA, asm_rv32_opcode_sh3add }, + { MP_QSTR_sll, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_FFFFFFFF, 3, CALL_RRR, R, 0, R, 0, R, 0, RV32_EXT_NONE, asm_rv32_opcode_sll }, + { MP_QSTR_slli, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_0000001F, 3, CALL_RRI, R, 0, R, 0, IU, 0, RV32_EXT_NONE, asm_rv32_opcode_slli }, + { MP_QSTR_slt, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_FFFFFFFF, 3, CALL_RRR, R, 0, R, 0, R, 0, RV32_EXT_NONE, asm_rv32_opcode_slt }, + { MP_QSTR_slti, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_00000FFF, 3, CALL_RRI, R, 0, R, 0, I, 0, RV32_EXT_NONE, asm_rv32_opcode_slti }, + { MP_QSTR_sltiu, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_00000FFF, 3, CALL_RRI, R, 0, R, 0, I, 0, RV32_EXT_NONE, asm_rv32_opcode_sltiu }, + { MP_QSTR_sltu, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_FFFFFFFF, 3, CALL_RRR, R, 0, R, 0, R, 0, RV32_EXT_NONE, asm_rv32_opcode_sltu }, + { MP_QSTR_sra, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_FFFFFFFF, 3, CALL_RRR, R, 0, R, 0, R, 0, RV32_EXT_NONE, asm_rv32_opcode_sra }, + { MP_QSTR_srai, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_0000001F, 3, CALL_RRI, R, 0, R, 0, IU, 0, RV32_EXT_NONE, asm_rv32_opcode_srai }, + { MP_QSTR_srl, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_FFFFFFFF, 3, CALL_RRR, R, 0, R, 0, R, 0, RV32_EXT_NONE, asm_rv32_opcode_srl }, + { MP_QSTR_srli, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_0000001F, 3, CALL_RRI, R, 0, R, 0, IU, 0, RV32_EXT_NONE, asm_rv32_opcode_srli }, + { MP_QSTR_sub, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_FFFFFFFF, 3, CALL_RRR, R, 0, R, 0, R, 0, RV32_EXT_NONE, asm_rv32_opcode_sub }, + { MP_QSTR_sw, MASK_FFFFFFFF, MASK_00000FFF, MASK_FFFFFFFF, 2, CALL_RIR, R, 0, I, 0, R, 0, RV32_EXT_NONE, asm_rv32_opcode_sw }, + { MP_QSTR_xor, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_FFFFFFFF, 3, CALL_RRR, R, 0, R, 0, R, 0, RV32_EXT_NONE, asm_rv32_opcode_xor }, + { MP_QSTR_xori, MASK_FFFFFFFF, MASK_FFFFFFFF, MASK_00000FFF, 3, CALL_RRI, R, 0, R, 0, I, 0, RV32_EXT_NONE, asm_rv32_opcode_xori }, +}; + +#undef RC +#undef IU +#undef IZ +#undef IUZ + +// These two checks assume the bitmasks are contiguous. + +static bool is_in_signed_mask(uint32_t mask, mp_uint_t value) { + uint32_t leading_zeroes = mp_clz(mask); + if (leading_zeroes == 0) { + return true; + } + mp_uint_t positive_mask = ~(mask & ~(1U << (31 - leading_zeroes))); + if ((value & positive_mask) == 0) { + return true; + } + mp_uint_t negative_mask = ~(mask >> 1); + mp_uint_t trailing_zeroes = mp_ctz(mask); + if (trailing_zeroes > 0) { + mp_uint_t trailing_mask = (1U << trailing_zeroes) - 1; + if ((value & trailing_mask) != 0) { + return false; + } + negative_mask &= ~trailing_mask; + } + return (value & negative_mask) == negative_mask; +} + +static inline bool is_in_unsigned_mask(mp_uint_t mask, mp_uint_t value) { + return (value & ~mask) == 0; +} + +static bool validate_integer(mp_uint_t value, mp_uint_t mask, mp_uint_t flags) { + if (flags & U) { + if (!is_in_unsigned_mask(mask, value)) { + return false; + } + } else { + if (!is_in_signed_mask(mask, value)) { + return false; + } + } + + if ((flags & Z) && (value == 0)) { + return false; + } + + return true; +} + +#define ET_WRONG_ARGUMENT_KIND MP_ERROR_TEXT("opcode '%q' argument %d: expecting %q") +#define ET_WRONG_ARGUMENTS_COUNT MP_ERROR_TEXT("opcode '%q': expecting %d arguments") +#define ET_OUT_OF_RANGE MP_ERROR_TEXT("opcode '%q' argument %d: out of range") + +static bool serialise_argument(emit_inline_asm_t *emit, const opcode_t *opcode, mp_parse_node_t node, mp_uint_t node_index, mp_uint_t *serialised) { + assert((node_index < 3) && "Invalid argument node number."); + assert(serialised && "Serialised value pointer is NULL."); + + uint32_t kind = 0; + uint32_t shift = 0; + uint32_t mask = 0; + + switch (node_index) { + case 0: + kind = opcode->argument1_kind; + shift = opcode->argument1_shift; + mask = OPCODE_MASKS[opcode->argument1_mask]; + break; + + case 1: + kind = opcode->argument2_kind; + shift = opcode->argument2_shift; + mask = OPCODE_MASKS[opcode->argument2_mask]; + break; + + case 2: + kind = opcode->argument3_kind; + shift = opcode->argument3_shift; + mask = OPCODE_MASKS[opcode->argument3_mask]; + break; + + default: + break; + } + + mp_uint_t serialised_value = 0; + + switch (kind & 0x03) { + case N: + assert(mask == OPCODE_MASKS[MASK_NOT_USED] && "Invalid mask index for missing operand."); + break; + + case R: { + mp_uint_t register_index; + if (!parse_register_node(node, ®ister_index, false)) { + emit_inline_rv32_error_exc(emit, + mp_obj_new_exception_msg_varg(&mp_type_SyntaxError, + ET_WRONG_ARGUMENT_KIND, opcode->qstring, node_index + 1, MP_QSTR_register)); + return false; + } + + if ((mask & (1U << register_index)) == 0) { + emit_inline_rv32_error_exc(emit, + mp_obj_new_exception_msg_varg(&mp_type_SyntaxError, + MP_ERROR_TEXT("opcode '%q' argument %d: unknown register"), + opcode->qstring, node_index + 1)); + return false; + } + + serialised_value = (kind & C) ? RV32_MAP_IN_C_REGISTER_WINDOW(register_index) : register_index; + } + break; + + case I: { + mp_obj_t object; + if (!mp_parse_node_get_int_maybe(node, &object)) { + emit_inline_rv32_error_exc(emit, + mp_obj_new_exception_msg_varg(&mp_type_SyntaxError, + ET_WRONG_ARGUMENT_KIND, opcode->qstring, node_index + 1, MP_QSTR_integer)); + return false; + } + + mp_uint_t immediate = ((mp_uint_t)mp_obj_get_int_truncated(object)) << shift; + if (kind & U) { + if (!is_in_unsigned_mask(mask, immediate)) { + goto out_of_range; + } + } else { + if (!is_in_signed_mask(mask, immediate)) { + goto out_of_range; + } + } + + if ((kind & Z) && (immediate == 0)) { + goto zero_immediate; + } + + serialised_value = immediate; + } + break; + + case L: { + if (!MP_PARSE_NODE_IS_ID(node)) { + emit_inline_rv32_error_exc(emit, + mp_obj_new_exception_msg_varg(&mp_type_SyntaxError, + ET_WRONG_ARGUMENT_KIND, opcode->qstring, node_index + 1, MP_QSTR_label)); + return false; + } + + qstr qstring; + mp_uint_t label_index = lookup_label(emit, node, &qstring); + if (label_index >= emit->max_num_labels && emit->pass == MP_PASS_EMIT) { + emit_inline_rv32_error_exc(emit, + mp_obj_new_exception_msg_varg(&mp_type_SyntaxError, + MP_ERROR_TEXT("opcode '%q' argument %d: undefined label '%q'"), + opcode->qstring, node_index + 1, qstring)); + return false; + } + + mp_uint_t displacement = (mp_uint_t)(label_code_offset(emit, label_index)); + if (kind & U) { + if (!is_in_unsigned_mask(mask, displacement)) { + goto out_of_range; + } + } else { + if (!is_in_signed_mask(mask, displacement)) { + goto out_of_range; + } + } + + serialised_value = displacement; + } + break; + + default: + assert(!"Unknown argument kind"); + MP_UNREACHABLE; + break; + } + + *serialised = serialised_value; + return true; + +out_of_range: + emit_inline_rv32_error_exc(emit, + mp_obj_new_exception_msg_varg(&mp_type_SyntaxError, ET_OUT_OF_RANGE, opcode->qstring, node_index + 1)); + return false; + +zero_immediate: + emit_inline_rv32_error_exc(emit, + mp_obj_new_exception_msg_varg(&mp_type_SyntaxError, + MP_ERROR_TEXT("opcode '%q' argument %d: must not be zero"), + opcode->qstring, node_index + 1)); + return false; +} + +static bool serialise_register_offset_node(emit_inline_asm_t *emit, const opcode_t *opcode_data, mp_parse_node_t node, mp_uint_t node_index, mp_uint_t *offset, mp_uint_t *base) { + assert(offset && "Attempting to store the offset value into NULL."); + assert(base && "Attempting to store the base register into NULL."); + + if (!MP_PARSE_NODE_IS_STRUCT_KIND(node, PN_atom_expr_normal) && !MP_PARSE_NODE_IS_STRUCT_KIND(node, PN_factor_2)) { + goto invalid_structure; + } + mp_parse_node_struct_t *node_struct = (mp_parse_node_struct_t *)node; + bool negative = false; + if (MP_PARSE_NODE_IS_STRUCT_KIND(node, PN_factor_2)) { + if (MP_PARSE_NODE_IS_TOKEN_KIND(node_struct->nodes[0], MP_TOKEN_OP_MINUS)) { + negative = true; + } else { + if (!MP_PARSE_NODE_IS_TOKEN_KIND(node_struct->nodes[0], MP_TOKEN_OP_PLUS)) { + goto invalid_structure; + } + } + if (!MP_PARSE_NODE_IS_STRUCT_KIND(node_struct->nodes[1], PN_atom_expr_normal)) { + goto invalid_structure; + } + node_struct = (mp_parse_node_struct_t *)node_struct->nodes[1]; + } + + if (negative) { + // If the value is negative, RULE_atom_expr_normal's first token will be the + // offset stripped of its negative marker; range check will then fail if the + // default method is used, so a custom check is used instead. + mp_obj_t object; + if (!mp_parse_node_get_int_maybe(node_struct->nodes[0], &object)) { + emit_inline_rv32_error_exc(emit, + mp_obj_new_exception_msg_varg(&mp_type_SyntaxError, ET_WRONG_ARGUMENT_KIND, opcode_data->qstring, 2, MP_QSTR_integer)); + return false; + } + mp_uint_t value = mp_obj_get_int_truncated(object); + value = (~value + 1) & (mp_uint_t)-1; + if (!validate_integer(value << opcode_data->argument2_shift, OPCODE_MASKS[opcode_data->argument2_mask], opcode_data->argument2_kind)) { + emit_inline_rv32_error_exc(emit, + mp_obj_new_exception_msg_varg(&mp_type_SyntaxError, ET_OUT_OF_RANGE, opcode_data->qstring, 2)); + return false; + } + *offset = value; + } else { + if (!serialise_argument(emit, opcode_data, node_struct->nodes[0], 1, offset)) { + return false; + } + } + + node_struct = (mp_parse_node_struct_t *)node_struct->nodes[1]; + if (!serialise_argument(emit, opcode_data, node_struct->nodes[0], 2, base)) { + return false; + } + return true; + +invalid_structure: + emit_inline_rv32_error_exc(emit, + mp_obj_new_exception_msg_varg(&mp_type_SyntaxError, + ET_WRONG_ARGUMENT_KIND, opcode_data->qstring, node_index + 1, MP_QSTR_offset)); + return false; +} + +static void handle_opcode(emit_inline_asm_t *emit, const opcode_t *opcode_data, mp_uint_t *arguments) { + switch (opcode_data->calling_convention) { + case CALL_RRR: + ((call_rrr_t)opcode_data->emitter)(&emit->as, arguments[0], arguments[1], arguments[2]); + break; + + case CALL_RR: + ((call_rr_t)opcode_data->emitter)(&emit->as, arguments[0], arguments[1]); + break; + + case CALL_RRI: + ((call_rri_t)opcode_data->emitter)(&emit->as, arguments[0], arguments[1], arguments[2]); + break; + + case CALL_RI: + ((call_ri_t)opcode_data->emitter)(&emit->as, arguments[0], arguments[1]); + break; + + case CALL_R: + ((call_r_t)opcode_data->emitter)(&emit->as, arguments[0]); + break; + + case CALL_RRL: + ((call_rri_t)opcode_data->emitter)(&emit->as, arguments[0], arguments[1], (ptrdiff_t)arguments[2]); + break; + + case CALL_RL: + ((call_ri_t)opcode_data->emitter)(&emit->as, arguments[0], (ptrdiff_t)arguments[1]); + break; + + case CALL_L: + ((call_i_t)opcode_data->emitter)(&emit->as, (ptrdiff_t)arguments[0]); + break; + + case CALL_N: + ((call_n_t)opcode_data->emitter)(&emit->as); + break; + + case CALL_RII: + ((call_rii_t)opcode_data->emitter)(&emit->as, arguments[0], arguments[1], arguments[2]); + break; + + case CALL_RIR: + // The last two arguments indices are swapped on purpose. + ((call_rri_t)opcode_data->emitter)(&emit->as, arguments[0], arguments[2], arguments[1]); + break; + + default: + assert(!"Unhandled call convention."); + MP_UNREACHABLE; + break; + } +} + +static bool extract_register_list(emit_inline_asm_t *emit, qstr opcode, mp_parse_node_t node, mp_uint_t *reglist) { + assert(reglist != NULL && "Register list pointer is NULL."); + + // As per §28.9, valid register list values are as follows: + // + // {ra}, {ra, s0}, {ra, s0-s1}, {ra, s0-s2}, ..., {ra, s0-s8}, + // {ra, s0-s9}, {ra, s0-s11} + // + // {ra, s0-s10} is *not* valid + + // case 1: {ra} + // PN_atom_brace { ID("ra") } + // + // case 2: {ra,s0} -> + // PN_atom_brace { PN_dictorsetmaker { ID("ra") + // PN_dictorsetmaker_list { ID("s0") } } } + // + // case 3: {ra,s0-s1} -> + // PN_atom_brace { PN_dictorsetmaker { ID("ra") + // PN_dictorsetmaker_list { PN_arith_expr { + // ID("s0") TOKEN(MP_TOKEN_OP_MINUS) ID("s1") } } } } + + if (!MP_PARSE_NODE_IS_STRUCT_KIND(node, PN_atom_brace) || + MP_PARSE_NODE_STRUCT_NUM_NODES((mp_parse_node_struct_t *)node) != 1) { + return false; + } + + mp_parse_node_struct_t *nodes = (mp_parse_node_struct_t *)node; + mp_uint_t register_id = 0; + + if (MP_PARSE_NODE_IS_ID(nodes->nodes[0])) { + if (!parse_register_node(nodes->nodes[0], ®ister_id, false)) { + return false; + } + *reglist = 4; + return register_id == ASM_RV32_REG_RA; + } + + if (!MP_PARSE_NODE_IS_STRUCT_KIND(nodes->nodes[0], PN_dictorsetmaker) || + MP_PARSE_NODE_STRUCT_NUM_NODES((mp_parse_node_struct_t *)nodes->nodes[0]) != 2) { + return false; + } + nodes = (mp_parse_node_struct_t *)nodes->nodes[0]; + if (!MP_PARSE_NODE_IS_ID(nodes->nodes[0]) || + !MP_PARSE_NODE_IS_STRUCT_KIND(nodes->nodes[1], PN_dictorsetmaker_list) || + !parse_register_node(nodes->nodes[0], ®ister_id, false) || + register_id != ASM_RV32_REG_RA) { + return false; + } + mp_parse_node_t *list_nodes; + size_t list_nodes_count = mp_parse_node_extract_list(&nodes->nodes[1], PN_dictorsetmaker_list2, &list_nodes); + if (list_nodes_count != 1 || !MP_PARSE_NODE_IS_STRUCT_KIND(list_nodes[0], PN_dictorsetmaker_list)) { + return false; + } + nodes = (mp_parse_node_struct_t *)list_nodes[0]; + if (MP_PARSE_NODE_STRUCT_NUM_NODES(nodes) != 1) { + return false; + } + if (MP_PARSE_NODE_IS_ID(nodes->nodes[0])) { + if (!parse_register_node(nodes->nodes[0], ®ister_id, false) || + register_id != ASM_RV32_REG_S0) { + return false; + } + *reglist = 5; + return true; + } + + if (MP_PARSE_NODE_IS_STRUCT_KIND(nodes->nodes[0], PN_arith_expr)) { + nodes = (mp_parse_node_struct_t *)nodes->nodes[0]; + if (MP_PARSE_NODE_STRUCT_NUM_NODES(nodes) != 3 || + !MP_PARSE_NODE_IS_ID(nodes->nodes[0]) || + !MP_PARSE_NODE_IS_TOKEN_KIND(nodes->nodes[1], MP_TOKEN_OP_MINUS) || + !MP_PARSE_NODE_IS_ID(nodes->nodes[2])) { + return false; + } + if (!parse_register_node(nodes->nodes[0], ®ister_id, false) || + register_id != ASM_RV32_REG_S0) { + return false; + } + if (!parse_register_node(nodes->nodes[2], ®ister_id, false) || + register_id == ASM_RV32_REG_S10) { + return false; + } + if (register_id == ASM_RV32_REG_S1) { + *reglist = 6; + return true; + } + if (register_id >= ASM_RV32_REG_S2 && register_id <= ASM_RV32_REG_S11) { + *reglist = 7 + MIN(register_id, ASM_RV32_REG_S10) - ASM_RV32_REG_S2; + return true; + } + } + + return false; +} + +static const qstr_short_t ZCMP_OPCODE_NAMES[] = { + MP_QSTR_cm_push, MP_QSTR_cm_pop, MP_QSTR_cm_popret, + MP_QSTR_cm_popretz, MP_QSTR_cm_mva01s, MP_QSTR_cm_mvsa01, +}; + +static const void *ZCMP_OPCODE_HANDLERS[] = { + asm_rv32_opcode_cmpush, asm_rv32_opcode_cmpop, + asm_rv32_opcode_cmpopret, asm_rv32_opcode_cmpopretz, + asm_rv32_opcode_cmmva01s, asm_rv32_opcode_cmmvsa01, +}; + +typedef void (*call_xi_t)(asm_rv32_t *state, mp_uint_t register_list, mp_int_t adjustment); +typedef void (*call_ss_t)(asm_rv32_t *state, mp_uint_t r1, mp_uint_t r2); + +static bool handle_zcmp_opcode(emit_inline_asm_t *emit, qstr opcode, mp_parse_node_t *argument_nodes) { + mp_uint_t argument_index = 0; + + for (size_t index = 0; index < MP_ARRAY_SIZE(ZCMP_OPCODE_NAMES); index++) { + if (ZCMP_OPCODE_NAMES[index] != opcode) { + continue; + } + const void *handler = ZCMP_OPCODE_HANDLERS[index]; + if (opcode == MP_QSTR_cm_mva01s || opcode == MP_QSTR_cm_mvsa01) { + mp_uint_t register_lhs = 0; + mp_uint_t register_rhs = 0; + + if (!parse_register_node(argument_nodes[0], ®ister_lhs, false) || + ((1U << register_lhs) & 0x00FC0300) == 0) { + goto invalid_s_register; + } + + if (!parse_register_node(argument_nodes[1], ®ister_rhs, false) || + ((1U << register_rhs) & 0x00FC0300) == 0) { + argument_index = 1; + goto invalid_s_register; + } + + if (register_lhs == register_rhs) { + emit_inline_rv32_error_exc(emit, + mp_obj_new_exception_msg_varg(&mp_type_SyntaxError, + MP_ERROR_TEXT("opcode '%q': registers must be different"), + opcode)); + return false; + } + + ((call_ss_t)handler)(&emit->as, register_lhs, register_rhs); + return true; + } + + mp_uint_t register_list; + if (!extract_register_list(emit, opcode, argument_nodes[0], ®ister_list)) { + emit_inline_rv32_error_exc(emit, + mp_obj_new_exception_msg_varg(&mp_type_SyntaxError, + MP_ERROR_TEXT("opcode '%q': malformed register list"), + opcode)); + return false; + } + + mp_obj_t stack_adjustment_object; + if (!mp_parse_node_get_int_maybe(argument_nodes[1], &stack_adjustment_object)) { + emit_inline_rv32_error_exc(emit, + mp_obj_new_exception_msg_varg(&mp_type_SyntaxError, + ET_WRONG_ARGUMENT_KIND, opcode, 2, MP_QSTR_integer)); + return false; + } + mp_int_t stack_adjustment = mp_obj_get_int(stack_adjustment_object); + // Either 0, 16, 32, or 48. + if ((abs((int32_t)stack_adjustment) & ~0x30U) != 0 || + ((opcode == MP_QSTR_cm_push) && stack_adjustment > 0) || + ((opcode != MP_QSTR_cm_push) && stack_adjustment < 0)) { + emit_inline_rv32_error_exc(emit, + mp_obj_new_exception_msg_varg(&mp_type_SyntaxError, + MP_ERROR_TEXT("opcode '%q': invalid stack adjustment"), + opcode)); + return false; + } + ((call_xi_t)handler)(&emit->as, register_list, abs((int32_t)stack_adjustment)); + return true; + } + + return false; + +invalid_s_register: + emit_inline_rv32_error_exc(emit, + mp_obj_new_exception_msg_varg(&mp_type_SyntaxError, + MP_ERROR_TEXT("opcode '%q' argument %d: wrong register(s)"), + opcode, argument_index + 1)); + return false; +} + +static void emit_inline_rv32_opcode(emit_inline_asm_t *emit, qstr opcode, mp_uint_t arguments_count, mp_parse_node_t *argument_nodes) { + const opcode_t *opcode_data = NULL; + for (mp_uint_t index = 0; index < MP_ARRAY_SIZE(OPCODES); index++) { + if (OPCODES[index].qstring == opcode) { + opcode_data = &OPCODES[index]; + break; + } + } + + if ((asm_rv32_allowed_extensions() & RV32_EXT_ZCMP) && !opcode_data && (arguments_count == 2) && handle_zcmp_opcode(emit, opcode, argument_nodes)) { + return; + } + + if (!opcode_data || (asm_rv32_allowed_extensions() & opcode_data->required_extensions) != opcode_data->required_extensions) { + emit_inline_rv32_error_exc(emit, mp_obj_new_exception_msg_varg(&mp_type_SyntaxError, + MP_ERROR_TEXT("invalid RV32 instruction '%q'"), opcode)); + return; + } + + assert((opcode_data->argument1_mask < MP_ARRAY_SIZE(OPCODE_MASKS)) && "Argument #1 opcode mask index out of bounds."); + assert((opcode_data->argument2_mask < MP_ARRAY_SIZE(OPCODE_MASKS)) && "Argument #2 opcode mask index out of bounds."); + assert((opcode_data->argument3_mask < MP_ARRAY_SIZE(OPCODE_MASKS)) && "Argument #3 opcode mask index out of bounds."); + assert((opcode_data->calling_convention < CALL_COUNT) && "Calling convention index out of bounds."); + mp_uint_t serialised_arguments[3] = { 0 }; + if (arguments_count != opcode_data->parse_nodes) { + emit_inline_rv32_error_exc(emit, + mp_obj_new_exception_msg_varg(&mp_type_SyntaxError, + ET_WRONG_ARGUMENTS_COUNT, opcode, opcode_data->parse_nodes)); + return; + } + + if (opcode_data->parse_nodes >= 1 && !serialise_argument(emit, opcode_data, argument_nodes[0], 0, &serialised_arguments[0])) { + return; + } + if (opcode_data->calling_convention == CALL_RIR) { + // "register, offset(base)" calls require some preprocessing to + // split the offset and base nodes - not to mention that if the offset + // is negative, the parser won't see the offset as a single node but as + // a sequence of the minus sign token followed by the number itself. + + if (!serialise_register_offset_node(emit, opcode_data, argument_nodes[1], 1, &serialised_arguments[1], &serialised_arguments[2])) { + return; + } + } else { + if (opcode_data->parse_nodes >= 2 && !serialise_argument(emit, opcode_data, argument_nodes[1], 1, &serialised_arguments[1])) { + return; + } + if (opcode_data->parse_nodes >= 3 && !serialise_argument(emit, opcode_data, argument_nodes[2], 2, &serialised_arguments[2])) { + return; + } + } + + handle_opcode(emit, opcode_data, serialised_arguments); +} + +#undef N +#undef R +#undef I +#undef L +#undef C +#undef U + +const emit_inline_asm_method_table_t emit_inline_rv32_method_table = { + #if MICROPY_DYNAMIC_COMPILER + emit_inline_rv32_new, + emit_inline_rv32_free, + #endif + + emit_inline_rv32_start_pass, + emit_inline_rv32_end_pass, + emit_inline_rv32_count_params, + emit_inline_rv32_label, + emit_inline_rv32_opcode, +}; + +#endif // MICROPY_EMIT_INLINE_RV32 diff --git a/py/emitinlinethumb.c b/py/emitinlinethumb.c index 7818bb4f46d..9c82921edfc 100644 --- a/py/emitinlinethumb.c +++ b/py/emitinlinethumb.c @@ -150,27 +150,27 @@ 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"}, - {2, "r2\0"}, - {3, "r3\0"}, - {4, "r4\0"}, - {5, "r5\0"}, - {6, "r6\0"}, - {7, "r7\0"}, - {8, "r8\0"}, - {9, "r9\0"}, - {10, "r10"}, - {11, "r11"}, - {12, "r12"}, - {13, "r13"}, - {14, "r14"}, - {15, "r15"}, - {10, "sl\0"}, - {11, "fp\0"}, - {13, "sp\0"}, - {14, "lr\0"}, - {15, "pc\0"}, + {0, {'r', '0' }}, + {1, {'r', '1' }}, + {2, {'r', '2' }}, + {3, {'r', '3' }}, + {4, {'r', '4' }}, + {5, {'r', '5' }}, + {6, {'r', '6' }}, + {7, {'r', '7' }}, + {8, {'r', '8' }}, + {9, {'r', '9' }}, + {10, {'r', '1', '0' }}, + {11, {'r', '1', '1' }}, + {12, {'r', '1', '2' }}, + {13, {'r', '1', '3' }}, + {14, {'r', '1', '4' }}, + {15, {'r', '1', '5' }}, + {10, {'s', 'l' }}, + {11, {'f', 'p' }}, + {13, {'s', 'p' }}, + {14, {'l', 'r' }}, + {15, {'p', 'c' }}, }; #define MAX_SPECIAL_REGISTER_NAME_LENGTH 7 @@ -364,24 +364,15 @@ 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; -static const cc_name_t cc_name_table[] = { - { ASM_THUMB_CC_EQ, "eq" }, - { ASM_THUMB_CC_NE, "ne" }, - { ASM_THUMB_CC_CS, "cs" }, - { ASM_THUMB_CC_CC, "cc" }, - { ASM_THUMB_CC_MI, "mi" }, - { ASM_THUMB_CC_PL, "pl" }, - { ASM_THUMB_CC_VS, "vs" }, - { ASM_THUMB_CC_VC, "vc" }, - { ASM_THUMB_CC_HI, "hi" }, - { ASM_THUMB_CC_LS, "ls" }, - { ASM_THUMB_CC_GE, "ge" }, - { ASM_THUMB_CC_LT, "lt" }, - { ASM_THUMB_CC_GT, "gt" }, - { ASM_THUMB_CC_LE, "le" }, +#define ENCODE_CC(c1, c2) (((uint16_t)(c1) << 8) | (uint16_t)(c2)) + +// Positions in the table match the condition code value. +static const uint16_t CONDITION_CODES[] = { + ENCODE_CC('e', 'q'), ENCODE_CC('n', 'e'), ENCODE_CC('c', 's'), + ENCODE_CC('c', 'c'), ENCODE_CC('m', 'i'), ENCODE_CC('p', 'l'), + ENCODE_CC('v', 's'), ENCODE_CC('v', 'c'), ENCODE_CC('h', 'i'), + ENCODE_CC('l', 's'), ENCODE_CC('g', 'e'), ENCODE_CC('l', 't'), + ENCODE_CC('g', 't'), ENCODE_CC('l', 'e'), }; typedef struct _format_4_op_t { byte op; @@ -389,21 +380,21 @@ typedef struct _format_4_op_t { byte op; } 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" }, - { X(ASM_THUMB_FORMAT_4_LSL), "lsl" }, - { X(ASM_THUMB_FORMAT_4_LSR), "lsr" }, - { X(ASM_THUMB_FORMAT_4_ASR), "asr" }, - { X(ASM_THUMB_FORMAT_4_ADC), "adc" }, - { X(ASM_THUMB_FORMAT_4_SBC), "sbc" }, - { X(ASM_THUMB_FORMAT_4_ROR), "ror" }, - { X(ASM_THUMB_FORMAT_4_TST), "tst" }, - { X(ASM_THUMB_FORMAT_4_NEG), "neg" }, - { X(ASM_THUMB_FORMAT_4_CMP), "cmp" }, - { X(ASM_THUMB_FORMAT_4_CMN), "cmn" }, - { X(ASM_THUMB_FORMAT_4_ORR), "orr" }, - { X(ASM_THUMB_FORMAT_4_MUL), "mul" }, - { X(ASM_THUMB_FORMAT_4_BIC), "bic" }, - { X(ASM_THUMB_FORMAT_4_MVN), "mvn" }, + { X(ASM_THUMB_FORMAT_4_EOR), {'e', 'o', 'r' }}, + { X(ASM_THUMB_FORMAT_4_LSL), {'l', 's', 'l' }}, + { X(ASM_THUMB_FORMAT_4_LSR), {'l', 's', 'r' }}, + { X(ASM_THUMB_FORMAT_4_ASR), {'a', 's', 'r' }}, + { X(ASM_THUMB_FORMAT_4_ADC), {'a', 'd', 'c' }}, + { X(ASM_THUMB_FORMAT_4_SBC), {'s', 'b', 'c' }}, + { X(ASM_THUMB_FORMAT_4_ROR), {'r', 'o', 'r' }}, + { X(ASM_THUMB_FORMAT_4_TST), {'t', 's', 't' }}, + { X(ASM_THUMB_FORMAT_4_NEG), {'n', 'e', 'g' }}, + { X(ASM_THUMB_FORMAT_4_CMP), {'c', 'm', 'p' }}, + { X(ASM_THUMB_FORMAT_4_CMN), {'c', 'm', 'n' }}, + { X(ASM_THUMB_FORMAT_4_ORR), {'o', 'r', 'r' }}, + { X(ASM_THUMB_FORMAT_4_MUL), {'m', 'u', 'l' }}, + { X(ASM_THUMB_FORMAT_4_BIC), {'b', 'i', 'c' }}, + { X(ASM_THUMB_FORMAT_4_MVN), {'m', 'v', 'n' }}, }; #undef X @@ -428,10 +419,10 @@ typedef struct _format_vfp_op_t { char name[3]; } format_vfp_op_t; static const format_vfp_op_t format_vfp_op_table[] = { - { 0x30, "add" }, - { 0x34, "sub" }, - { 0x20, "mul" }, - { 0x80, "div" }, + { 0x30, {'a', 'd', 'd' }}, + { 0x34, {'s', 'u', 'b' }}, + { 0x20, {'m', 'u', 'l' }}, + { 0x80, {'d', 'i', 'v' }}, }; // shorthand alias for whether we allow ARMv7-M instructions @@ -574,9 +565,11 @@ static void emit_inline_thumb_op(emit_inline_asm_t *emit, qstr op, mp_uint_t n_a || (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]) { - cc = cc_name_table[i].cc; + uint16_t condition_code = ENCODE_CC(op_str[1], op_str[2]); + for (size_t i = 0; i < MP_ARRAY_SIZE(CONDITION_CODES); ++i) { + if (condition_code == CONDITION_CODES[i]) { + cc = i; + break; } } if (cc == (mp_uint_t)-1) { @@ -592,12 +585,14 @@ static void emit_inline_thumb_op(emit_inline_asm_t *emit, qstr op, mp_uint_t n_a } } else if (ARMV7M && op_str[0] == 'i' && op_str[1] == 't') { const char *arg_str = get_arg_str(pn_args[0]); + if (strlen(arg_str) != 2) { + goto unknown_op; + } mp_uint_t cc = -1; - for (mp_uint_t i = 0; i < MP_ARRAY_SIZE(cc_name_table); i++) { - if (arg_str[0] == cc_name_table[i].name[0] - && arg_str[1] == cc_name_table[i].name[1] - && arg_str[2] == '\0') { - cc = cc_name_table[i].cc; + uint16_t condition_code = ENCODE_CC(arg_str[0], arg_str[1]); + for (size_t i = 0; i < MP_ARRAY_SIZE(CONDITION_CODES); ++i) { + if (condition_code == CONDITION_CODES[i]) { + cc = i; break; } } diff --git a/py/emitinlinextensa.c b/py/emitinlinextensa.c index 57056d597aa..c58754d47c3 100644 --- a/py/emitinlinextensa.c +++ b/py/emitinlinextensa.c @@ -35,6 +35,18 @@ #if MICROPY_EMIT_INLINE_XTENSA +#include "py/persistentcode.h" + +static inline bool emit_windowed_code() { + #if MICROPY_DYNAMIC_COMPILER + return mp_dynamic_compiler.native_arch == MP_NATIVE_ARCH_XTENSAWIN; + #elif MICROPY_EMIT_XTENSAWIN + return true; + #else + return false; + #endif +} + struct _emit_inline_asm_t { asm_xtensa_t as; uint16_t pass; @@ -73,11 +85,19 @@ static void emit_inline_xtensa_start_pass(emit_inline_asm_t *emit, pass_kind_t p memset(emit->label_lookup, 0, emit->max_num_labels * sizeof(qstr)); } mp_asm_base_start_pass(&emit->as.base, pass == MP_PASS_EMIT ? MP_ASM_PASS_EMIT : MP_ASM_PASS_COMPUTE); - asm_xtensa_entry(&emit->as, 0); + if (emit_windowed_code()) { + asm_xtensa_entry_win(&emit->as, 0); + } else { + asm_xtensa_entry(&emit->as, 0); + } } static void emit_inline_xtensa_end_pass(emit_inline_asm_t *emit, mp_uint_t type_sig) { - asm_xtensa_exit(&emit->as); + if (emit_windowed_code()) { + asm_xtensa_exit_win(&emit->as); + } else { + asm_xtensa_exit(&emit->as); + } asm_xtensa_end_pass(&emit->as); } @@ -115,50 +135,21 @@ 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; -static const reg_name_t reg_name_table[] = { - {0, "a0\0"}, - {1, "a1\0"}, - {2, "a2\0"}, - {3, "a3\0"}, - {4, "a4\0"}, - {5, "a5\0"}, - {6, "a6\0"}, - {7, "a7\0"}, - {8, "a8\0"}, - {9, "a9\0"}, - {10, "a10"}, - {11, "a11"}, - {12, "a12"}, - {13, "a13"}, - {14, "a14"}, - {15, "a15"}, +static const qstr_short_t REGISTERS[16] = { + MP_QSTR_a0, MP_QSTR_a1, MP_QSTR_a2, MP_QSTR_a3, MP_QSTR_a4, MP_QSTR_a5, MP_QSTR_a6, MP_QSTR_a7, + MP_QSTR_a8, MP_QSTR_a9, MP_QSTR_a10, MP_QSTR_a11, MP_QSTR_a12, MP_QSTR_a13, MP_QSTR_a14, MP_QSTR_a15 }; -// return empty string in case of error, so we can attempt to parse the string -// without a special check if it was in fact a string -static const char *get_arg_str(mp_parse_node_t pn) { - if (MP_PARSE_NODE_IS_ID(pn)) { - qstr qst = MP_PARSE_NODE_LEAF_ARG(pn); - return qstr_str(qst); - } else { - return ""; - } -} - static mp_uint_t get_arg_reg(emit_inline_asm_t *emit, const char *op, mp_parse_node_t pn) { - const char *reg_str = get_arg_str(pn); - for (mp_uint_t i = 0; i < MP_ARRAY_SIZE(reg_name_table); i++) { - const reg_name_t *r = ®_name_table[i]; - if (reg_str[0] == r->name[0] - && reg_str[1] == r->name[1] - && reg_str[2] == r->name[2] - && (reg_str[2] == '\0' || reg_str[3] == '\0')) { - return r->reg; + if (MP_PARSE_NODE_IS_ID(pn)) { + qstr node_qstr = MP_PARSE_NODE_LEAF_ARG(pn); + for (size_t i = 0; i < MP_ARRAY_SIZE(REGISTERS); i++) { + if (node_qstr == REGISTERS[i]) { + return i; + } } } + emit_inline_xtensa_error_exc(emit, mp_obj_new_exception_msg_varg(&mp_type_SyntaxError, MP_ERROR_TEXT("'%s' expects a register"), op)); @@ -197,127 +188,273 @@ static int get_arg_label(emit_inline_asm_t *emit, const char *op, mp_parse_node_ return 0; } -#define RRR (0) -#define RRI8 (1) -#define RRI8_B (2) - -typedef struct _opcode_table_3arg_t { - uint16_t name; // actually a qstr, which should fit in 16 bits - uint8_t type; - uint8_t a0 : 4; - uint8_t a1 : 4; -} opcode_table_3arg_t; - -static const opcode_table_3arg_t opcode_table_3arg[] = { - // arithmetic opcodes: reg, reg, reg - {MP_QSTR_and_, RRR, 0, 1}, - {MP_QSTR_or_, RRR, 0, 2}, - {MP_QSTR_xor, RRR, 0, 3}, - {MP_QSTR_add, RRR, 0, 8}, - {MP_QSTR_sub, RRR, 0, 12}, - {MP_QSTR_mull, RRR, 2, 8}, - - // load/store/addi opcodes: reg, reg, imm - // upper nibble of type encodes the range of the immediate arg - {MP_QSTR_l8ui, RRI8 | 0x10, 2, 0}, - {MP_QSTR_l16ui, RRI8 | 0x30, 2, 1}, - {MP_QSTR_l32i, RRI8 | 0x50, 2, 2}, - {MP_QSTR_s8i, RRI8 | 0x10, 2, 4}, - {MP_QSTR_s16i, RRI8 | 0x30, 2, 5}, - {MP_QSTR_s32i, RRI8 | 0x50, 2, 6}, - {MP_QSTR_l16si, RRI8 | 0x30, 2, 9}, - {MP_QSTR_addi, RRI8 | 0x00, 2, 12}, - - // branch opcodes: reg, reg, label - {MP_QSTR_ball, RRI8_B, ASM_XTENSA_CC_ALL, 0}, - {MP_QSTR_bany, RRI8_B, ASM_XTENSA_CC_ANY, 0}, - {MP_QSTR_bbc, RRI8_B, ASM_XTENSA_CC_BC, 0}, - {MP_QSTR_bbs, RRI8_B, ASM_XTENSA_CC_BS, 0}, - {MP_QSTR_beq, RRI8_B, ASM_XTENSA_CC_EQ, 0}, - {MP_QSTR_bge, RRI8_B, ASM_XTENSA_CC_GE, 0}, - {MP_QSTR_bgeu, RRI8_B, ASM_XTENSA_CC_GEU, 0}, - {MP_QSTR_blt, RRI8_B, ASM_XTENSA_CC_LT, 0}, - {MP_QSTR_bnall, RRI8_B, ASM_XTENSA_CC_NALL, 0}, - {MP_QSTR_bne, RRI8_B, ASM_XTENSA_CC_NE, 0}, - {MP_QSTR_bnone, RRI8_B, ASM_XTENSA_CC_NONE, 0}, +static const qstr_short_t BRANCH_OPCODE_NAMES[] = { + MP_QSTR_bnone, MP_QSTR_beq, MP_QSTR_blt, MP_QSTR_bltu, MP_QSTR_ball, + MP_QSTR_bbc, MP_QSTR_, MP_QSTR_, MP_QSTR_bany, MP_QSTR_bne, + MP_QSTR_bge, MP_QSTR_bgeu, MP_QSTR_bnall, MP_QSTR_bbs, +}; + +#define RRR_R0 (1 << 4) +#define RRR_R1 (2 << 4) +#define RRR_R2 (3 << 4) + +#define RRR (0) +#define RRI8 (1) +#define RRRN (2) + +static const struct opcode_entry_t { + qstr_short_t name; + uint16_t operands : 2; + uint16_t op2 : 4; + uint16_t op1 : 4; + uint16_t op0 : 4; + // 2 bits available here + uint32_t r : 6; + uint32_t s : 6; + uint32_t t : 6; + uint32_t shift : 3; + uint32_t kind : 2; + // 9 bits available here +} OPCODE_TABLE[] = { + { MP_QSTR_abs_, 2, 6, 0, 0, RRR_R0, 1, RRR_R1, 0, RRR }, + { MP_QSTR_add, 3, 8, 0, 0, RRR_R0, RRR_R1, RRR_R2, 0, RRR }, + { MP_QSTR_add_n, 3, 0, 0, 10, RRR_R0, RRR_R1, RRR_R2, 0, RRRN }, + { MP_QSTR_addi, 3, 0, 0, 2, 12, RRR_R1, RRR_R0, 0, RRI8 }, + { MP_QSTR_addx2, 3, 9, 0, 0, RRR_R0, RRR_R1, RRR_R2, 0, RRR }, + { MP_QSTR_addx4, 3, 10, 0, 0, RRR_R0, RRR_R1, RRR_R2, 0, RRR }, + { MP_QSTR_addx8, 3, 11, 0, 0, RRR_R0, RRR_R1, RRR_R2, 0, RRR }, + { MP_QSTR_and_, 3, 1, 0, 0, RRR_R0, RRR_R1, RRR_R2, 0, RRR }, + { MP_QSTR_callx0, 1, 0, 0, 0, 0, RRR_R0, 12, 0, RRR }, + { MP_QSTR_jx, 1, 0, 0, 0, 0, RRR_R0, 10, 0, RRR }, + { MP_QSTR_l16si, 3, 0, 0, 2, 9, RRR_R1, RRR_R0, 3, RRI8 }, + { MP_QSTR_l16ui, 3, 0, 0, 2, 1, RRR_R1, RRR_R0, 3, RRI8 }, + { MP_QSTR_l32i, 3, 0, 0, 2, 2, RRR_R1, RRR_R0, 5, RRI8 }, + { MP_QSTR_l8ui, 3, 0, 0, 2, 0, RRR_R1, RRR_R0, 1, RRI8 }, + { MP_QSTR_mov, 2, 0, 0, 13, 0, RRR_R1, RRR_R0, 0, RRRN }, + { MP_QSTR_mov_n, 2, 0, 0, 13, 0, RRR_R1, RRR_R0, 0, RRRN }, + { MP_QSTR_mull, 3, 8, 2, 0, RRR_R0, RRR_R1, RRR_R2, 0, RRR }, + { MP_QSTR_neg, 2, 6, 0, 0, RRR_R0, 0, RRR_R1, 0, RRR }, + { MP_QSTR_nop, 0, 0, 0, 0, 2, 0, 15, 0, RRR }, + { MP_QSTR_nop_n, 0, 0, 0, 13, 15, 0, 3, 0, RRRN }, + { MP_QSTR_nsa, 2, 4, 0, 0, 14, RRR_R1, RRR_R0, 0, RRR }, + { MP_QSTR_nsau, 2, 4, 0, 0, 15, RRR_R1, RRR_R0, 0, RRR }, + { MP_QSTR_or_, 3, 2, 0, 0, RRR_R0, RRR_R1, RRR_R2, 0, RRR }, + { MP_QSTR_ret, 0, 0, 0, 13, 15, 0, 0, 0, RRRN }, + { MP_QSTR_ret_n, 0, 0, 0, 13, 15, 0, 0, 0, RRRN }, + { MP_QSTR_s16i, 3, 0, 0, 2, 5, RRR_R1, RRR_R0, 3, RRI8 }, + { MP_QSTR_s32i, 3, 0, 0, 2, 6, RRR_R1, RRR_R0, 5, RRI8 }, + { MP_QSTR_s8i, 3, 0, 0, 2, 4, RRR_R1, RRR_R0, 1, RRI8 }, + { MP_QSTR_sll, 2, 10, 1, 0, RRR_R0, RRR_R1, 0, 0, RRR }, + { MP_QSTR_sra, 2, 11, 1, 0, RRR_R0, 0, RRR_R1, 0, RRR }, + { MP_QSTR_src, 3, 8, 1, 0, RRR_R0, RRR_R1, RRR_R2, 0, RRR }, + { MP_QSTR_srl, 2, 9, 1, 0, RRR_R0, 0, RRR_R1, 0, RRR }, + { MP_QSTR_ssa8b, 1, 4, 0, 0, 3, RRR_R0, 0, 0, RRR }, + { MP_QSTR_ssa8l, 1, 4, 0, 0, 2, RRR_R0, 0, 0, RRR }, + { MP_QSTR_ssl, 1, 4, 0, 0, 1, RRR_R0, 0, 0, RRR }, + { MP_QSTR_ssr, 1, 4, 0, 0, 0, RRR_R0, 0, 0, RRR }, + { MP_QSTR_sub, 3, 12, 0, 0, RRR_R0, RRR_R1, RRR_R2, 0, RRR }, + { MP_QSTR_subx2, 3, 13, 0, 0, RRR_R0, RRR_R1, RRR_R2, 0, RRR }, + { MP_QSTR_subx4, 3, 14, 0, 0, RRR_R0, RRR_R1, RRR_R2, 0, RRR }, + { MP_QSTR_subx8, 3, 15, 0, 0, RRR_R0, RRR_R1, RRR_R2, 0, RRR }, + { MP_QSTR_xor, 3, 3, 0, 0, RRR_R0, RRR_R1, RRR_R2, 0, RRR }, + #if MICROPY_EMIT_INLINE_XTENSA_UNCOMMON_OPCODES + { MP_QSTR_dsync, 0, 0, 0, 0, 2, 0, 3, 0, RRR }, + { MP_QSTR_esync, 0, 0, 0, 0, 2, 0, 2, 0, RRR }, + { MP_QSTR_extw, 0, 0, 0, 0, 2, 0, 13, 0, RRR }, + { MP_QSTR_ill, 0, 0, 0, 0, 2, 0, 0, 0, RRR }, + { MP_QSTR_ill_n, 0, 0, 0, 13, 15, 0, 6, 0, RRRN }, + { MP_QSTR_isync, 0, 0, 0, 0, 2, 0, 0, 0, RRR }, + { MP_QSTR_memw, 0, 0, 0, 0, 2, 0, 12, 0, RRR }, + { MP_QSTR_rer, 2, 4, 0, 0, 6, RRR_R1, RRR_R0, 0, RRR }, + { MP_QSTR_rsync, 0, 0, 0, 0, 2, 0, 1, 0, RRR }, + { MP_QSTR_wer, 2, 4, 0, 0, 7, RRR_R1, RRR_R0, 0, RRR }, + #endif +}; + +// The index of the first four qstrs matches the CCZ condition value to be +// embedded into the opcode. +static const qstr_short_t BCCZ_OPCODES[] = { + MP_QSTR_beqz, MP_QSTR_bnez, MP_QSTR_bltz, MP_QSTR_bgez, + MP_QSTR_beqz_n, MP_QSTR_bnez_n }; 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); - if (n_args == 0) { - if (op == MP_QSTR_ret_n) { - asm_xtensa_op_ret_n(&emit->as); - } else { - goto unknown_op; + for (size_t index = 0; index < MP_ARRAY_SIZE(OPCODE_TABLE); index++) { + const struct opcode_entry_t *entry = &OPCODE_TABLE[index]; + if (entry->name == op) { + if (n_args != entry->operands) { + goto unknown_op; + } + + uint32_t opcode = ((entry->r & 0x0F) << 12) | ((entry->s & 0x0F) << 8) | ((entry->t & 0x0F) << 4) | entry->op0; + if (entry->kind == RRR) { + opcode |= (entry->op2 << 20) | (entry->op1 << 16); + } else if (entry->kind == RRI8) { + int min = 0; + int max = 0; + int shift = entry->shift; + if (shift > 0) { + shift >>= 1; + max = 0xFF << shift; + } else { + min = -128; + max = 127; + } + uint32_t immediate = get_arg_i(emit, op_str, pn_args[2], min, max); + opcode |= ((immediate >> shift) & 0xFF) << 16; + } + if (entry->r >= RRR_R0) { + opcode |= get_arg_reg(emit, op_str, pn_args[(entry->r >> 4) - 1]) << 12; + } + if (entry->s >= RRR_R0) { + opcode |= get_arg_reg(emit, op_str, pn_args[(entry->s >> 4) - 1]) << 8; + } + if (entry->t >= RRR_R0) { + opcode |= get_arg_reg(emit, op_str, pn_args[(entry->t >> 4) - 1]) << 4; + } + if (entry->kind == RRRN) { + assert((opcode >> 16) == 0 && "Stray bits in narrow opcode"); + asm_xtensa_op16(&emit->as, (uint16_t)(opcode & 0xFFFF)); + } else { + asm_xtensa_op24(&emit->as, opcode); + } + return; } + } - } else if (n_args == 1) { - if (op == MP_QSTR_callx0) { - uint r0 = get_arg_reg(emit, op_str, pn_args[0]); - asm_xtensa_op_callx0(&emit->as, r0); - } else if (op == MP_QSTR_j) { + if (n_args == 1) { + if (op == MP_QSTR_j) { int label = get_arg_label(emit, op_str, pn_args[0]); asm_xtensa_j_label(&emit->as, label); - } else if (op == MP_QSTR_jx) { - uint r0 = get_arg_reg(emit, op_str, pn_args[0]); - asm_xtensa_op_jx(&emit->as, r0); + } else if (op == MP_QSTR_ssai) { + mp_uint_t sa = get_arg_i(emit, op_str, pn_args[0], 0, 31); + asm_xtensa_op24(&emit->as, ASM_XTENSA_ENCODE_RRR(0, 0, 4, 4, sa & 0x0F, (sa >> 4) & 0x01)); + } else if (op == MP_QSTR_call0) { + mp_uint_t label = get_arg_label(emit, op_str, pn_args[0]); + asm_xtensa_call0(&emit->as, label); + #if MICROPY_EMIT_INLINE_XTENSA_UNCOMMON_OPCODES + } else if (op == MP_QSTR_fsync) { + mp_uint_t imm3 = get_arg_i(emit, op_str, pn_args[0], 0, 7); + asm_xtensa_op24(&emit->as, ASM_XTENSA_ENCODE_RRR(0, 0, 0, 2, 8 | imm3, 0)); + #endif } else { goto unknown_op; } - } else if (n_args == 2) { uint r0 = get_arg_reg(emit, op_str, pn_args[0]); - if (op == MP_QSTR_beqz) { - int label = get_arg_label(emit, op_str, pn_args[1]); - asm_xtensa_bccz_reg_label(&emit->as, ASM_XTENSA_CCZ_EQ, r0, label); - } else if (op == MP_QSTR_bnez) { - int label = get_arg_label(emit, op_str, pn_args[1]); - asm_xtensa_bccz_reg_label(&emit->as, ASM_XTENSA_CCZ_NE, r0, label); - } else if (op == MP_QSTR_mov || op == MP_QSTR_mov_n) { - // we emit mov.n for both "mov" and "mov_n" opcodes - uint r1 = get_arg_reg(emit, op_str, pn_args[1]); - asm_xtensa_op_mov_n(&emit->as, r0, r1); - } else if (op == MP_QSTR_movi) { + for (size_t index = 0; index < MP_ARRAY_SIZE(BCCZ_OPCODES); index++) { + if (op == BCCZ_OPCODES[index]) { + mp_uint_t label = get_arg_label(emit, op_str, pn_args[1]); + asm_xtensa_bccz_reg_label(&emit->as, index & 0x03, r0, label); + return; + } + } + if (op == MP_QSTR_movi) { // for convenience we emit l32r if the integer doesn't fit in movi uint32_t imm = get_arg_i(emit, op_str, pn_args[1], 0, 0); asm_xtensa_mov_reg_i32(&emit->as, r0, imm); - } else { + } else if (op == MP_QSTR_l32r) { + mp_uint_t label = get_arg_label(emit, op_str, pn_args[1]); + asm_xtensa_l32r(&emit->as, r0, label); + } else if (op == MP_QSTR_movi_n) { + mp_int_t imm = get_arg_i(emit, op_str, pn_args[1], -32, 95); + asm_xtensa_op_movi_n(&emit->as, r0, imm); + } else + #if MICROPY_EMIT_INLINE_XTENSA_UNCOMMON_OPCODES + if (op == MP_QSTR_rsr) { + mp_uint_t sr = get_arg_i(emit, op_str, pn_args[1], 0, 255); + asm_xtensa_op24(&emit->as, ASM_XTENSA_ENCODE_RSR(0, 3, 0, sr, r0)); + } else if (op == MP_QSTR_rur) { + mp_uint_t imm8 = get_arg_i(emit, op_str, pn_args[1], 0, 255); + asm_xtensa_op24(&emit->as, ASM_XTENSA_ENCODE_RRR(0, 3, 14, r0, (imm8 >> 4) & 0x0F, imm8 & 0x0F)); + } else if (op == MP_QSTR_wsr) { + mp_uint_t sr = get_arg_i(emit, op_str, pn_args[1], 0, 255); + asm_xtensa_op24(&emit->as, ASM_XTENSA_ENCODE_RSR(0, 3, 1, sr, r0)); + } else if (op == MP_QSTR_wur) { + mp_uint_t sr = get_arg_i(emit, op_str, pn_args[1], 0, 255); + asm_xtensa_op24(&emit->as, ASM_XTENSA_ENCODE_RSR(0, 3, 15, sr, r0)); + } else if (op == MP_QSTR_xsr) { + mp_uint_t sr = get_arg_i(emit, op_str, pn_args[1], 0, 255); + asm_xtensa_op24(&emit->as, ASM_XTENSA_ENCODE_RSR(0, 1, 6, sr, r0)); + } else + #endif + { goto unknown_op; } - } else if (n_args == 3) { - // search table for 3 arg instructions - for (uint i = 0; i < MP_ARRAY_SIZE(opcode_table_3arg); i++) { - const opcode_table_3arg_t *o = &opcode_table_3arg[i]; - if (op == o->name) { - uint r0 = get_arg_reg(emit, op_str, pn_args[0]); - uint r1 = get_arg_reg(emit, op_str, pn_args[1]); - if (o->type == RRR) { - uint r2 = get_arg_reg(emit, op_str, pn_args[2]); - asm_xtensa_op24(&emit->as, ASM_XTENSA_ENCODE_RRR(0, o->a0, o->a1, r0, r1, r2)); - } else if (o->type == RRI8_B) { - int label = get_arg_label(emit, op_str, pn_args[2]); - asm_xtensa_bcc_reg_reg_label(&emit->as, o->a0, r0, r1, label); - } else { - int shift, min, max; - if ((o->type & 0xf0) == 0) { - shift = 0; - min = -128; - max = 127; - } else { - shift = (o->type & 0xf0) >> 5; - min = 0; - max = 0xff << shift; - } - uint32_t imm = get_arg_i(emit, op_str, pn_args[2], min, max); - asm_xtensa_op24(&emit->as, ASM_XTENSA_ENCODE_RRI8(o->a0, o->a1, r1, r0, (imm >> shift) & 0xff)); - } + for (size_t index = 0; index < MP_ARRAY_SIZE(BRANCH_OPCODE_NAMES); index++) { + if (BRANCH_OPCODE_NAMES[index] == op) { + int r0 = get_arg_reg(emit, op_str, pn_args[0]); + int r1 = get_arg_reg(emit, op_str, pn_args[1]); + int label = get_arg_label(emit, op_str, pn_args[2]); + asm_xtensa_bcc_reg_reg_label(&emit->as, index, r0, r1, label); return; } } - goto unknown_op; + + if (op == MP_QSTR_addi_n) { + mp_uint_t r0 = get_arg_reg(emit, op_str, pn_args[0]); + mp_uint_t r1 = get_arg_reg(emit, op_str, pn_args[1]); + mp_int_t imm4 = get_arg_i(emit, op_str, pn_args[2], -1, 15); + asm_xtensa_op16(&emit->as, ASM_XTENSA_ENCODE_RRRN(11, r0, r1, (imm4 != 0 ? imm4 : -1))); + } else if (op == MP_QSTR_addmi) { + mp_uint_t r0 = get_arg_reg(emit, op_str, pn_args[0]); + mp_uint_t r1 = get_arg_reg(emit, op_str, pn_args[1]); + mp_int_t imm8 = get_arg_i(emit, op_str, pn_args[2], -128 * 256, 127 * 256); + if ((imm8 & 0xFF) != 0) { + emit_inline_xtensa_error_exc(emit, mp_obj_new_exception_msg_varg(&mp_type_SyntaxError, MP_ERROR_TEXT("%d is not a multiple of %d"), imm8, 256)); + } else { + asm_xtensa_op24(&emit->as, ASM_XTENSA_ENCODE_RRI8(2, 13, r1, r0, imm8 >> 8)); + } + } else if (op == MP_QSTR_bbci) { + mp_uint_t r0 = get_arg_reg(emit, op_str, pn_args[0]); + mp_uint_t bit = get_arg_i(emit, op_str, pn_args[1], 0, 31); + mp_int_t label = get_arg_label(emit, op_str, pn_args[2]); + asm_xtensa_bit_branch(&emit->as, r0, bit, label, 6); + } else if (op == MP_QSTR_bbsi) { + mp_uint_t r0 = get_arg_reg(emit, op_str, pn_args[0]); + mp_uint_t bit = get_arg_i(emit, op_str, pn_args[1], 0, 31); + mp_uint_t label = get_arg_label(emit, op_str, pn_args[2]); + asm_xtensa_bit_branch(&emit->as, r0, bit, label, 14); + } else if (op == MP_QSTR_slli) { + mp_uint_t r0 = get_arg_reg(emit, op_str, pn_args[0]); + mp_uint_t r1 = get_arg_reg(emit, op_str, pn_args[1]); + mp_uint_t bits = 32 - get_arg_i(emit, op_str, pn_args[2], 1, 31); + asm_xtensa_op24(&emit->as, ASM_XTENSA_ENCODE_RRR(0, 1, 0 | ((bits >> 4) & 0x01), r0, r1, bits & 0x0F)); + } else if (op == MP_QSTR_srai) { + mp_uint_t r0 = get_arg_reg(emit, op_str, pn_args[0]); + mp_uint_t r1 = get_arg_reg(emit, op_str, pn_args[1]); + mp_uint_t bits = get_arg_i(emit, op_str, pn_args[2], 0, 31); + asm_xtensa_op24(&emit->as, ASM_XTENSA_ENCODE_RRR(0, 1, 2 | ((bits >> 4) & 0x01), r0, bits & 0x0F, r1)); + } else if (op == MP_QSTR_srli) { + mp_uint_t r0 = get_arg_reg(emit, op_str, pn_args[0]); + mp_uint_t r1 = get_arg_reg(emit, op_str, pn_args[1]); + mp_uint_t bits = get_arg_i(emit, op_str, pn_args[2], 0, 15); + asm_xtensa_op24(&emit->as, ASM_XTENSA_ENCODE_RRR(0, 1, 4, r0, bits, r1)); + } else if (op == MP_QSTR_l32i_n) { + mp_uint_t r0 = get_arg_reg(emit, op_str, pn_args[0]); + mp_uint_t r1 = get_arg_reg(emit, op_str, pn_args[1]); + mp_uint_t imm = get_arg_i(emit, op_str, pn_args[2], 0, 60); + if ((imm & 0x03) != 0) { + emit_inline_xtensa_error_exc(emit, mp_obj_new_exception_msg_varg(&mp_type_SyntaxError, MP_ERROR_TEXT("%d is not a multiple of %d"), imm, 4)); + } else { + asm_xtensa_op_l32i_n(&emit->as, r0, r1, imm >> 2); + } + } else if (op == MP_QSTR_s32i_n) { + mp_uint_t r0 = get_arg_reg(emit, op_str, pn_args[0]); + mp_uint_t r1 = get_arg_reg(emit, op_str, pn_args[1]); + mp_uint_t imm = get_arg_i(emit, op_str, pn_args[2], 0, 60); + if ((imm & 0x03) != 0) { + emit_inline_xtensa_error_exc(emit, mp_obj_new_exception_msg_varg(&mp_type_SyntaxError, MP_ERROR_TEXT("%d is not a multiple of %d"), imm, 4)); + } else { + asm_xtensa_op_s32i_n(&emit->as, r0, r1, imm >> 2); + } + } else { + goto unknown_op; + } } else { goto unknown_op; diff --git a/py/emitnative.c b/py/emitnative.c index 4789d3f5781..9ac62f6d362 100644 --- a/py/emitnative.c +++ b/py/emitnative.c @@ -60,28 +60,40 @@ #endif // CIRCUITPY-CHANGE: force definitions -#ifndef N_X64 -#define N_X64 (0) +#ifndef N_ARM +#define N_ARM (0) #endif -#ifndef N_X86 -#define N_X86 (0) +#ifndef N_DEBUG +#define N_DEBUG (0) +#endif + +#ifndef N_NLR_SETJMP +#define N_NLR_SETJMP (0) +#endif + +#ifndef N_RV32 +#define N_RV32 (0) #endif #ifndef N_THUMB #define N_THUMB (0) #endif -#ifndef N_ARM -#define N_ARM (0) +#ifndef N_X64 +#define N_X64 (0) +#endif + +#ifndef N_X86 +#define N_X86 (0) #endif #ifndef N_XTENSA #define N_XTENSA (0) #endif -#ifndef N_NLR_SETJMP -#define N_NLR_SETJMP (0) +#ifndef N_XTENSAWIN +#define N_XTENSAWIN (0) #endif #ifndef N_PRELUDE_AS_BYTES_OBJ @@ -89,7 +101,7 @@ #endif // wrapper around everything in this file -#if N_X64 || N_X86 || N_THUMB || N_ARM || N_XTENSA || N_XTENSAWIN +#if N_X64 || N_X86 || N_THUMB || N_ARM || N_XTENSA || N_XTENSAWIN || N_RV32 || N_DEBUG // C stack layout for native functions: // 0: nlr_buf_t [optional] @@ -159,6 +171,7 @@ // Whether a slot is needed to store LOCAL_IDX_EXC_HANDLER_UNWIND #define NEED_EXC_HANDLER_UNWIND(emit) ((emit)->scope->exc_stack_size > 0) +#define NEED_THROW_VAL(emit) ((emit)->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR) // 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 @@ -169,6 +182,7 @@ #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) (SIZEOF_NLR_BUF + 1) // this needs a dedicated variable outside nlr_buf_t +#define LOCAL_IDX_THROW_VAL(emit) (SIZEOF_NLR_BUF + 2) // needs a dedicated variable outside nlr_buf_t, following inject_exc in py/vm.c #define LOCAL_IDX_RET_VAL(emit) (SIZEOF_NLR_BUF) // needed when NEED_GLOBAL_EXC_HANDLER is true #define LOCAL_IDX_FUN_OBJ(emit) ((emit)->code_state_start + OFFSETOF_CODE_STATE_FUN_BC) #define LOCAL_IDX_OLD_GLOBALS(emit) ((emit)->code_state_start + OFFSETOF_CODE_STATE_IP) @@ -232,6 +246,7 @@ typedef enum { VTYPE_BUILTIN_CAST = 0x70 | MP_NATIVE_TYPE_OBJ, } vtype_kind_t; +#if MICROPY_ERROR_REPORTING != MICROPY_ERROR_REPORTING_NONE static qstr vtype_to_qstr(vtype_kind_t vtype) { switch (vtype) { case VTYPE_PYOBJ: @@ -255,6 +270,7 @@ static qstr vtype_to_qstr(vtype_kind_t vtype) { return MP_QSTR_None; } } +#endif typedef struct _stack_info_t { vtype_kind_t vtype; @@ -310,12 +326,28 @@ struct _emit_t { ASM_T *as; }; +#ifdef REG_ZERO +#define ASM_MOV_LOCAL_MP_OBJ_NULL(as, local_num, reg_temp) \ + ASM_MOV_LOCAL_REG(as, local_num, REG_ZERO) +#else +#define REG_ZERO REG_TEMP0 +#define ASM_MOV_LOCAL_MP_OBJ_NULL(as, local_num, reg_temp) \ + ASM_CLR_REG(as, reg_temp); \ + ASM_MOV_LOCAL_REG(as, local_num, reg_temp) +#endif + static void emit_load_reg_with_object(emit_t *emit, int reg, mp_obj_t obj); static void emit_native_global_exc_entry(emit_t *emit); static void emit_native_global_exc_exit(emit_t *emit); static void emit_native_load_const_obj(emit_t *emit, mp_obj_t obj); emit_t *EXPORT_FUN(new)(mp_emit_common_t * emit_common, mp_obj_t *error_slot, uint *label_slot, mp_uint_t max_num_labels) { + // Generated code performing exception handling assumes that MP_OBJ_NULL + // equals to 0 to simplify some checks, leveraging dedicated opcodes for + // comparisons against 0. If this assumption does not hold true anymore + // then generated code won't work correctly. + MP_STATIC_ASSERT(MP_OBJ_NULL == 0); + emit_t *emit = m_new0(emit_t, 1); emit->emit_common = emit_common; emit->error_slot = error_slot; @@ -372,11 +404,14 @@ static void emit_native_mov_reg_state_addr(emit_t *emit, int reg_dest, int local static void emit_native_mov_reg_qstr(emit_t *emit, int arg_reg, qstr qst) { #if MICROPY_PERSISTENT_CODE_SAVE ASM_LOAD16_REG_REG_OFFSET(emit->as, arg_reg, REG_QSTR_TABLE, mp_emit_common_use_qstr(emit->emit_common, qst)); + #elif defined(ASM_MOV_REG_QSTR) + ASM_MOV_REG_QSTR(emit->as, arg_reg, qst); #else ASM_MOV_REG_IMM(emit->as, arg_reg, qst); #endif } +// This function may clobber REG_TEMP0 (and `reg_dest` can be REG_TEMP0). static void emit_native_mov_reg_qstr_obj(emit_t *emit, int reg_dest, qstr qst) { #if MICROPY_PERSISTENT_CODE_SAVE emit_load_reg_with_object(emit, reg_dest, MP_OBJ_NEW_QSTR(qst)); @@ -439,6 +474,30 @@ static void emit_native_start_pass(emit_t *emit, pass_kind_t pass, scope_t *scop emit->stack_info[i].vtype = VTYPE_UNBOUND; } + char *qualified_name = NULL; + + #if N_DEBUG + scope_t *current_scope = scope; + vstr_t *qualified_name_vstr = vstr_new(qstr_len(current_scope->simple_name)); + size_t fragment_length = 0; + const byte *fragment_pointer; + for (;;) { + fragment_pointer = qstr_data(current_scope->simple_name, &fragment_length); + vstr_hint_size(qualified_name_vstr, fragment_length); + memmove(qualified_name_vstr->buf + fragment_length, qualified_name_vstr->buf, qualified_name_vstr->len); + memcpy(qualified_name_vstr->buf, fragment_pointer, fragment_length); + qualified_name_vstr->len += fragment_length; + if (current_scope->parent == NULL || current_scope->parent->simple_name == MP_QSTR__lt_module_gt_) { + break; + } + vstr_ins_char(qualified_name_vstr, 0, '.'); + current_scope = current_scope->parent; + } + qualified_name = vstr_null_terminated_str(qualified_name_vstr); + #else + (void)qualified_name; + #endif + mp_asm_base_start_pass(&emit->as->base, pass == MP_PASS_EMIT ? MP_ASM_PASS_EMIT : MP_ASM_PASS_COMPUTE); // generate code for entry to function @@ -448,7 +507,9 @@ static void emit_native_start_pass(emit_t *emit, pass_kind_t pass, scope_t *scop if (NEED_GLOBAL_EXC_HANDLER(emit)) { emit->code_state_start = SIZEOF_NLR_BUF; // for nlr_buf_t emit->code_state_start += 1; // for return_value - if (NEED_EXC_HANDLER_UNWIND(emit)) { + if (NEED_THROW_VAL(emit)) { + emit->code_state_start += 2; + } else if (NEED_EXC_HANDLER_UNWIND(emit)) { emit->code_state_start += 1; } } @@ -483,7 +544,7 @@ static void emit_native_start_pass(emit_t *emit, pass_kind_t pass, scope_t *scop } // Entry to function - ASM_ENTRY(emit->as, emit->stack_start + emit->n_state - num_locals_in_regs); + ASM_ENTRY(emit->as, emit->stack_start + emit->n_state - num_locals_in_regs, qualified_name); #if N_X86 asm_x86_mov_arg_to_r32(emit->as, 0, REG_PARENT_ARG_1); @@ -554,7 +615,7 @@ static void emit_native_start_pass(emit_t *emit, pass_kind_t pass, scope_t *scop if (emit->scope->scope_flags & MP_SCOPE_FLAG_GENERATOR) { mp_asm_base_data(&emit->as->base, ASM_WORD_SIZE, (uintptr_t)emit->start_offset); - ASM_ENTRY(emit->as, emit->code_state_start); + ASM_ENTRY(emit->as, emit->code_state_start, qualified_name); // Reset the state size for the state pointed to by REG_GENERATOR_STATE emit->code_state_start = 0; @@ -567,11 +628,11 @@ static void emit_native_start_pass(emit_t *emit, pass_kind_t pass, scope_t *scop ASM_MOV_REG_REG(emit->as, REG_GENERATOR_STATE, REG_PARENT_ARG_1); #endif - // Put throw value into LOCAL_IDX_EXC_VAL slot, for yield/yield-from + // Put throw value into LOCAL_IDX_THROW_VAL slot, for yield/yield-from #if N_X86 asm_x86_mov_arg_to_r32(emit->as, 1, REG_PARENT_ARG_2); #endif - ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_VAL(emit), REG_PARENT_ARG_2); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_THROW_VAL(emit), REG_PARENT_ARG_2); // 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)); @@ -586,7 +647,7 @@ static void emit_native_start_pass(emit_t *emit, pass_kind_t pass, scope_t *scop emit->stack_start = emit->code_state_start + SIZEOF_CODE_STATE; // Allocate space on C-stack for code_state structure, which includes state - ASM_ENTRY(emit->as, emit->stack_start + emit->n_state); + ASM_ENTRY(emit->as, emit->stack_start + emit->n_state, qualified_name); // Prepare incoming arguments for call to mp_setup_code_state @@ -652,6 +713,10 @@ static void emit_native_start_pass(emit_t *emit, pass_kind_t pass, scope_t *scop } } } + + #if N_DEBUG + vstr_free(qualified_name_vstr); + #endif } static inline void emit_native_write_code_info_byte(emit_t *emit, byte val) { @@ -1120,7 +1185,7 @@ static void emit_native_leave_exc_stack(emit_t *emit, bool start_of_handler) { // Optimisation: PC is already cleared by global exc handler return; } - ASM_XOR_REG_REG(emit->as, REG_RET, REG_RET); + ASM_CLR_REG(emit->as, REG_RET); } else { // Found new active handler, get its PC ASM_MOV_REG_PCREL(emit->as, REG_RET, e->label); @@ -1135,6 +1200,7 @@ static exc_stack_entry_t *emit_native_pop_exc_stack(emit_t *emit) { return e; } +// This function will clobber REG_TEMP0 (and `reg` can be REG_TEMP0). static void emit_load_reg_with_object(emit_t *emit, int reg, mp_obj_t obj) { emit->scope->scope_flags |= MP_SCOPE_FLAG_HASCONSTS; size_t table_off = mp_emit_common_use_const_obj(emit->emit_common, obj); @@ -1163,7 +1229,7 @@ static void emit_native_label_assign(emit_t *emit, mp_uint_t 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); + emit_access_stack(emit, 1, &vtype, REG_TEMP0); ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_VAL(emit), REG_TEMP0); } @@ -1216,8 +1282,11 @@ static void emit_native_global_exc_entry(emit_t *emit) { 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); + ASM_MOV_LOCAL_MP_OBJ_NULL(emit->as, LOCAL_IDX_EXC_HANDLER_UNWIND(emit), REG_ZERO); + + // clear nlr.ret_val, because it's passed to mp_native_raise regardless + // of whether there was an exception or not + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_VAL(emit), REG_ZERO); // Put PC of start code block into REG_LOCAL_1 ASM_MOV_REG_PCREL(emit->as, REG_LOCAL_1, start_label); @@ -1233,8 +1302,7 @@ static void emit_native_global_exc_entry(emit_t *emit) { 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_MOV_LOCAL_MP_OBJ_NULL(emit->as, LOCAL_IDX_EXC_HANDLER_PC(emit), REG_ZERO); ASM_JUMP_REG(emit->as, REG_LOCAL_1); // Global exception handler: check for valid exception handler @@ -1274,8 +1342,9 @@ static void emit_native_global_exc_entry(emit_t *emit) { // 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)); + // Check LOCAL_IDX_THROW_VAL for any injected value + ASM_MOV_REG_LOCAL(emit->as, REG_ARG_1, LOCAL_IDX_THROW_VAL(emit)); + ASM_MOV_LOCAL_MP_OBJ_NULL(emit->as, LOCAL_IDX_THROW_VAL(emit), REG_ARG_2); emit_call(emit, MP_F_NATIVE_RAISE); } } @@ -1403,9 +1472,9 @@ 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); - emit_load_reg_with_object(emit, REG_RET, obj); - emit_post_push_reg(emit, VTYPE_PYOBJ, REG_RET); + need_reg_single(emit, REG_TEMP0, 0); + emit_load_reg_with_object(emit, REG_TEMP0, obj); + emit_post_push_reg(emit, VTYPE_PYOBJ, REG_TEMP0); } static void emit_native_load_null(emit_t *emit) { @@ -1483,6 +1552,7 @@ static void emit_native_load_attr(emit_t *emit, qstr qst) { } static void emit_native_load_method(emit_t *emit, qstr qst, bool is_super) { + DEBUG_printf("load_method(%s, %d)\n", qstr_str(qst), is_super); if (is_super) { emit_get_stack_pointer_to_reg_for_pop(emit, REG_ARG_2, 3); // arg2 = dest ptr emit_get_stack_pointer_to_reg_for_push(emit, REG_ARG_2, 2); // arg2 = dest ptr @@ -1541,57 +1611,50 @@ static void emit_native_load_subscr(emit_t *emit) { switch (vtype_base) { case VTYPE_PTR8: { // pointer to 8-bit memory - // TODO optimise to use thumb ldrb r1, [r2, r3] + #ifdef ASM_LOAD8_REG_REG_OFFSET + ASM_LOAD8_REG_REG_OFFSET(emit->as, REG_RET, reg_base, index_value); + #else if (index_value != 0) { // index is non-zero - #if N_THUMB - if (index_value > 0 && index_value < 32) { - asm_thumb_ldrb_rlo_rlo_i5(emit->as, REG_RET, reg_base, index_value); - break; - } - #endif need_reg_single(emit, reg_index, 0); ASM_MOV_REG_IMM(emit->as, reg_index, index_value); ASM_ADD_REG_REG(emit->as, reg_index, reg_base); // add index to base reg_base = reg_index; } ASM_LOAD8_REG_REG(emit->as, REG_RET, reg_base); // load from (base+index) + #endif break; } case VTYPE_PTR16: { // pointer to 16-bit memory + #ifdef ASM_LOAD16_REG_REG_OFFSET + ASM_LOAD16_REG_REG_OFFSET(emit->as, REG_RET, reg_base, index_value); + #else if (index_value != 0) { // index is a non-zero immediate - #if N_THUMB - if (index_value > 0 && index_value < 32) { - asm_thumb_ldrh_rlo_rlo_i5(emit->as, REG_RET, reg_base, index_value); - break; - } - #endif need_reg_single(emit, reg_index, 0); ASM_MOV_REG_IMM(emit->as, reg_index, index_value << 1); ASM_ADD_REG_REG(emit->as, reg_index, reg_base); // add 2*index to base reg_base = reg_index; } ASM_LOAD16_REG_REG(emit->as, REG_RET, reg_base); // load from (base+2*index) + #endif break; } case VTYPE_PTR32: { // pointer to 32-bit memory + #ifdef ASM_LOAD32_REG_REG_OFFSET + ASM_LOAD32_REG_REG_OFFSET(emit->as, REG_RET, reg_base, index_value); + #else if (index_value != 0) { // index is a non-zero immediate - #if N_THUMB - if (index_value > 0 && index_value < 32) { - asm_thumb_ldr_rlo_rlo_i5(emit->as, REG_RET, reg_base, index_value); - break; - } - #endif need_reg_single(emit, reg_index, 0); 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; } ASM_LOAD32_REG_REG(emit->as, REG_RET, reg_base); // load from (base+4*index) + #endif break; } default: @@ -1612,25 +1675,36 @@ static void emit_native_load_subscr(emit_t *emit) { switch (vtype_base) { case VTYPE_PTR8: { // pointer to 8-bit memory - // TODO optimise to use thumb ldrb r1, [r2, r3] + #ifdef ASM_LOAD8_REG_REG_REG + ASM_LOAD8_REG_REG_REG(emit->as, REG_RET, REG_ARG_1, reg_index); + #else ASM_ADD_REG_REG(emit->as, REG_ARG_1, reg_index); // add index to base ASM_LOAD8_REG_REG(emit->as, REG_RET, REG_ARG_1); // store value to (base+index) + #endif break; } case VTYPE_PTR16: { // pointer to 16-bit memory + #ifdef ASM_LOAD16_REG_REG_REG + ASM_LOAD16_REG_REG_REG(emit->as, REG_RET, REG_ARG_1, reg_index); + #else ASM_ADD_REG_REG(emit->as, REG_ARG_1, reg_index); // add index to base ASM_ADD_REG_REG(emit->as, REG_ARG_1, reg_index); // add index to base ASM_LOAD16_REG_REG(emit->as, REG_RET, REG_ARG_1); // load from (base+2*index) + #endif break; } case VTYPE_PTR32: { // pointer to word-size memory + #ifdef ASM_LOAD32_REG_REG_REG + ASM_LOAD32_REG_REG_REG(emit->as, REG_RET, REG_ARG_1, reg_index); + #else ASM_ADD_REG_REG(emit->as, REG_ARG_1, reg_index); // add index to base ASM_ADD_REG_REG(emit->as, REG_ARG_1, reg_index); // add index to base ASM_ADD_REG_REG(emit->as, REG_ARG_1, reg_index); // add index to base ASM_ADD_REG_REG(emit->as, REG_ARG_1, reg_index); // add index to base ASM_LOAD32_REG_REG(emit->as, REG_RET, REG_ARG_1); // load from (base+4*index) + #endif break; } default: @@ -1773,63 +1847,47 @@ static void emit_native_store_subscr(emit_t *emit) { switch (vtype_base) { case VTYPE_PTR8: { // pointer to 8-bit memory - // TODO optimise to use thumb strb r1, [r2, r3] + #ifdef ASM_STORE8_REG_REG_OFFSET + ASM_STORE8_REG_REG_OFFSET(emit->as, reg_value, reg_base, index_value); + #else if (index_value != 0) { // index is non-zero - #if N_THUMB - if (index_value > 0 && index_value < 32) { - asm_thumb_strb_rlo_rlo_i5(emit->as, reg_value, reg_base, index_value); - break; - } - #endif ASM_MOV_REG_IMM(emit->as, reg_index, index_value); - #if N_ARM - asm_arm_strb_reg_reg_reg(emit->as, reg_value, reg_base, reg_index); - return; - #endif ASM_ADD_REG_REG(emit->as, reg_index, reg_base); // add index to base reg_base = reg_index; } ASM_STORE8_REG_REG(emit->as, reg_value, reg_base); // store value to (base+index) + #endif break; } case VTYPE_PTR16: { // pointer to 16-bit memory + #ifdef ASM_STORE16_REG_REG_OFFSET + ASM_STORE16_REG_REG_OFFSET(emit->as, reg_value, reg_base, index_value); + #else if (index_value != 0) { // index is a non-zero immediate - #if N_THUMB - if (index_value > 0 && index_value < 32) { - asm_thumb_strh_rlo_rlo_i5(emit->as, reg_value, reg_base, index_value); - break; - } - #endif ASM_MOV_REG_IMM(emit->as, reg_index, index_value << 1); ASM_ADD_REG_REG(emit->as, reg_index, reg_base); // add 2*index to base reg_base = reg_index; } ASM_STORE16_REG_REG(emit->as, reg_value, reg_base); // store value to (base+2*index) + #endif break; } case VTYPE_PTR32: { // pointer to 32-bit memory + #ifdef ASM_STORE32_REG_REG_OFFSET + ASM_STORE32_REG_REG_OFFSET(emit->as, reg_value, reg_base, index_value); + #else if (index_value != 0) { // index is a non-zero immediate - #if N_THUMB - if (index_value > 0 && index_value < 32) { - asm_thumb_str_rlo_rlo_i5(emit->as, reg_value, reg_base, index_value); - break; - } - #endif - #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; } ASM_STORE32_REG_REG(emit->as, reg_value, reg_base); // store value to (base+4*index) + #endif break; } default: @@ -1860,37 +1918,36 @@ static void emit_native_store_subscr(emit_t *emit) { switch (vtype_base) { case VTYPE_PTR8: { // pointer to 8-bit memory - // TODO optimise to use thumb strb r1, [r2, r3] - #if N_ARM - asm_arm_strb_reg_reg_reg(emit->as, reg_value, REG_ARG_1, reg_index); - break; - #endif + #ifdef ASM_STORE8_REG_REG_REG + ASM_STORE8_REG_REG_REG(emit->as, reg_value, REG_ARG_1, reg_index); + #else ASM_ADD_REG_REG(emit->as, REG_ARG_1, reg_index); // add index to base ASM_STORE8_REG_REG(emit->as, reg_value, REG_ARG_1); // store value to (base+index) + #endif break; } case VTYPE_PTR16: { // pointer to 16-bit memory - #if N_ARM - asm_arm_strh_reg_reg_reg(emit->as, reg_value, REG_ARG_1, reg_index); - break; - #endif + #ifdef ASM_STORE16_REG_REG_REG + ASM_STORE16_REG_REG_REG(emit->as, reg_value, REG_ARG_1, reg_index); + #else ASM_ADD_REG_REG(emit->as, REG_ARG_1, reg_index); // add index to base ASM_ADD_REG_REG(emit->as, REG_ARG_1, reg_index); // add index to base ASM_STORE16_REG_REG(emit->as, reg_value, REG_ARG_1); // store value to (base+2*index) + #endif break; } case VTYPE_PTR32: { // pointer to 32-bit memory - #if N_ARM - asm_arm_str_reg_reg_reg(emit->as, reg_value, REG_ARG_1, reg_index); - break; - #endif + #ifdef ASM_STORE32_REG_REG_REG + ASM_STORE32_REG_REG_REG(emit->as, reg_value, REG_ARG_1, reg_index); + #else ASM_ADD_REG_REG(emit->as, REG_ARG_1, reg_index); // add index to base ASM_ADD_REG_REG(emit->as, REG_ARG_1, reg_index); // add index to base ASM_ADD_REG_REG(emit->as, REG_ARG_1, reg_index); // add index to base ASM_ADD_REG_REG(emit->as, REG_ARG_1, reg_index); // add index to base ASM_STORE32_REG_REG(emit->as, reg_value, REG_ARG_1); // store value to (base+4*index) + #endif break; } default: @@ -1926,7 +1983,7 @@ static void emit_native_delete_attr(emit_t *emit, qstr qst) { vtype_kind_t vtype_base; emit_pre_pop_reg(emit, &vtype_base, REG_ARG_1); // arg1 = base assert(vtype_base == VTYPE_PYOBJ); - ASM_XOR_REG_REG(emit->as, REG_ARG_3, REG_ARG_3); // arg3 = value (null for delete) + ASM_CLR_REG(emit->as, REG_ARG_3); // arg3 = value (null for delete) emit_call_with_qstr_arg(emit, MP_F_STORE_ATTR, qst, REG_ARG_2); // arg2 = attribute name emit_post(emit); } @@ -2072,7 +2129,7 @@ static void emit_native_unwind_jump(emit_t *emit, mp_uint_t label, mp_uint_t exc // 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); + ASM_CLR_REG(emit->as, REG_RET); } else { ASM_MOV_REG_PCREL(emit->as, REG_RET, e->label); } @@ -2133,6 +2190,7 @@ static void emit_native_setup_with(emit_t *emit, mp_uint_t label) { } static void emit_native_setup_block(emit_t *emit, mp_uint_t label, int kind) { + DEBUG_printf("setup_block(%d, %d)\n", (int)label, kind); if (kind == MP_EMIT_SETUP_BLOCK_WITH) { emit_native_setup_with(emit, label); } else { @@ -2202,14 +2260,39 @@ static void emit_native_with_cleanup(emit_t *emit, mp_uint_t label) { // Replace exception with MP_OBJ_NULL. emit_native_label_assign(emit, *emit->label_slot); - ASM_MOV_REG_IMM(emit->as, REG_TEMP0, (mp_uint_t)MP_OBJ_NULL); - ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_VAL(emit), REG_TEMP0); + ASM_MOV_LOCAL_MP_OBJ_NULL(emit->as, LOCAL_IDX_EXC_VAL(emit), REG_TEMP0); // end of with cleanup nlr_catch block emit_native_label_assign(emit, *emit->label_slot + 1); // Exception is in nlr_buf.ret_val slot + adjust_stack(emit, 1); +} + +#if MICROPY_PY_ASYNC_AWAIT +static void emit_native_async_with_setup_finally(emit_t *emit, mp_uint_t label_aexit_no_exc, mp_uint_t label_finally_block, mp_uint_t label_ret_unwind_jump) { + // The async-with body has executed and no exception was raised, the execution fell through to this point. + // Stack: (..., ctx_mgr) + + // Insert a dummy value into the stack so the stack has the same layout to execute the code starting at label_aexit_no_exc + emit_native_adjust_stack_size(emit, 1); // push dummy value, it won't ever be used + emit_native_rot_two(emit); + emit_native_load_const_tok(emit, MP_TOKEN_KW_NONE); // to tell end_finally there's no exception + emit_native_rot_two(emit); + // Stack: (..., , None, ctx_mgr) + emit_native_jump(emit, label_aexit_no_exc); // jump to code to call __aexit__ + emit_native_adjust_stack_size(emit, -1); + + // Start of "finally" block which is entered via one of: an exception propagating out, a return, an unwind jump. + emit_native_label_assign(emit, label_finally_block); + + // Detect which case we have by the local exception slot holding an exception or not. + emit_pre_pop_discard(emit); + ASM_MOV_REG_LOCAL(emit->as, REG_ARG_1, LOCAL_IDX_EXC_VAL(emit)); // get exception + emit_post_push_reg(emit, VTYPE_PYOBJ, REG_ARG_1); + ASM_JUMP_IF_REG_ZERO(emit->as, REG_ARG_1, label_ret_unwind_jump, false); // if not an exception then we have return or unwind jump. } +#endif static void emit_native_end_finally(emit_t *emit) { // logic: @@ -2217,7 +2300,9 @@ 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 - emit_native_pre(emit); + DEBUG_printf("end_finally\n"); + + emit_pre_pop_discard(emit); ASM_MOV_REG_LOCAL(emit->as, REG_ARG_1, LOCAL_IDX_EXC_VAL(emit)); emit_call(emit, MP_F_NATIVE_RAISE); @@ -2241,6 +2326,8 @@ static void emit_native_get_iter(emit_t *emit, bool use_stack) { // perhaps the difficult one, as we want to rewrite for loops using native code // in cases where we iterate over a Python object, can we use normal runtime calls? + DEBUG_printf("get_iter(%d)\n", use_stack); + vtype_kind_t vtype; emit_pre_pop_reg(emit, &vtype, REG_ARG_1); assert(vtype == VTYPE_PYOBJ); @@ -2280,8 +2367,7 @@ static void emit_native_for_iter_end(emit_t *emit) { static void emit_native_pop_except_jump(emit_t *emit, mp_uint_t label, bool within_exc_handler) { if (within_exc_handler) { // Cancel any active exception so subsequent handlers don't see it - ASM_MOV_REG_IMM(emit->as, REG_TEMP0, (mp_uint_t)MP_OBJ_NULL); - ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_EXC_VAL(emit), REG_TEMP0); + ASM_MOV_LOCAL_MP_OBJ_NULL(emit->as, LOCAL_IDX_EXC_VAL(emit), REG_TEMP0); } else { emit_native_leave_exc_stack(emit, false); } @@ -2294,22 +2380,23 @@ static void emit_native_unary_op(emit_t *emit, mp_unary_op_t op) { if (op == MP_UNARY_OP_POSITIVE) { // No-operation, just leave the argument on the stack. } else if (op == MP_UNARY_OP_NEGATIVE) { - int reg = REG_RET; - emit_pre_pop_reg_flexible(emit, &vtype, ®, reg, reg); - ASM_NEG_REG(emit->as, reg); - emit_post_push_reg(emit, vtype, reg); + emit_pre_pop_reg(emit, &vtype, REG_RET); + ASM_NEG_REG(emit->as, REG_RET); + emit_post_push_reg(emit, vtype, REG_RET); } else if (op == MP_UNARY_OP_INVERT) { + emit_pre_pop_reg(emit, &vtype, REG_RET); #ifdef ASM_NOT_REG - int reg = REG_RET; - emit_pre_pop_reg_flexible(emit, &vtype, ®, reg, reg); - ASM_NOT_REG(emit->as, reg); + ASM_NOT_REG(emit->as, REG_RET); #else - int reg = REG_RET; - emit_pre_pop_reg_flexible(emit, &vtype, ®, REG_ARG_1, reg); - ASM_MOV_REG_IMM(emit->as, REG_ARG_1, -1); - ASM_XOR_REG_REG(emit->as, reg, REG_ARG_1); + #if REG_RET != REG_ARG_1 + int reg = REG_ARG_1; + #else + int reg = REG_ARG_2; + #endif + ASM_MOV_REG_IMM(emit->as, reg, -1); + ASM_XOR_REG_REG(emit->as, REG_RET, reg); #endif - emit_post_push_reg(emit, vtype, reg); + emit_post_push_reg(emit, vtype, REG_RET); } else { EMIT_NATIVE_VIPER_TYPE_ERROR(emit, MP_ERROR_TEXT("'not' not implemented"), mp_binary_op_method_name[op]); @@ -2429,7 +2516,7 @@ static void emit_native_binary_op(emit_t *emit, mp_binary_op_t op) { #if N_X64 asm_x64_xor_r64_r64(emit->as, REG_RET, REG_RET); asm_x64_cmp_r64_with_r64(emit->as, reg_rhs, REG_ARG_2); - static byte ops[6 + 6] = { + static const byte ops[6 + 6] = { // unsigned ASM_X64_CC_JB, ASM_X64_CC_JA, @@ -2449,7 +2536,7 @@ static void emit_native_binary_op(emit_t *emit, mp_binary_op_t op) { #elif N_X86 asm_x86_xor_r32_r32(emit->as, REG_RET, REG_RET); asm_x86_cmp_r32_with_r32(emit->as, reg_rhs, REG_ARG_2); - static byte ops[6 + 6] = { + static const byte ops[6 + 6] = { // unsigned ASM_X86_CC_JB, ASM_X86_CC_JA, @@ -2469,7 +2556,7 @@ static void emit_native_binary_op(emit_t *emit, mp_binary_op_t op) { #elif N_THUMB asm_thumb_cmp_rlo_rlo(emit->as, REG_ARG_2, reg_rhs); if (asm_thumb_allow_armv7m(emit->as)) { - static uint16_t ops[6 + 6] = { + static const uint16_t ops[6 + 6] = { // unsigned ASM_THUMB_OP_ITE_CC, ASM_THUMB_OP_ITE_HI, @@ -2489,7 +2576,7 @@ static void emit_native_binary_op(emit_t *emit, mp_binary_op_t op) { asm_thumb_mov_rlo_i8(emit->as, REG_RET, 1); asm_thumb_mov_rlo_i8(emit->as, REG_RET, 0); } else { - static uint16_t ops[6 + 6] = { + static const uint16_t ops[6 + 6] = { // unsigned ASM_THUMB_CC_CC, ASM_THUMB_CC_HI, @@ -2512,7 +2599,7 @@ static void emit_native_binary_op(emit_t *emit, mp_binary_op_t op) { } #elif N_ARM asm_arm_cmp_reg_reg(emit->as, REG_ARG_2, reg_rhs); - static uint ccs[6 + 6] = { + static const uint ccs[6 + 6] = { // unsigned ASM_ARM_CC_CC, ASM_ARM_CC_HI, @@ -2530,7 +2617,7 @@ static void emit_native_binary_op(emit_t *emit, mp_binary_op_t op) { }; asm_arm_setcc_reg(emit->as, REG_RET, ccs[op_idx]); #elif N_XTENSA || N_XTENSAWIN - static uint8_t ccs[6 + 6] = { + static const uint8_t ccs[6 + 6] = { // unsigned ASM_XTENSA_CC_LTU, 0x80 | ASM_XTENSA_CC_LTU, // for GTU we'll swap args @@ -2552,6 +2639,38 @@ static void emit_native_binary_op(emit_t *emit, mp_binary_op_t op) { } else { asm_xtensa_setcc_reg_reg_reg(emit->as, cc & ~0x80, REG_RET, reg_rhs, REG_ARG_2); } + #elif N_RV32 + (void)op_idx; + switch (op) { + case MP_BINARY_OP_LESS: + asm_rv32_meta_comparison_lt(emit->as, REG_ARG_2, reg_rhs, REG_RET, vtype_lhs == VTYPE_UINT); + break; + + case MP_BINARY_OP_MORE: + asm_rv32_meta_comparison_lt(emit->as, reg_rhs, REG_ARG_2, REG_RET, vtype_lhs == VTYPE_UINT); + break; + + case MP_BINARY_OP_EQUAL: + asm_rv32_meta_comparison_eq(emit->as, REG_ARG_2, reg_rhs, REG_RET); + break; + + case MP_BINARY_OP_LESS_EQUAL: + asm_rv32_meta_comparison_le(emit->as, REG_ARG_2, reg_rhs, REG_RET, vtype_lhs == VTYPE_UINT); + break; + + case MP_BINARY_OP_MORE_EQUAL: + asm_rv32_meta_comparison_le(emit->as, reg_rhs, REG_ARG_2, REG_RET, vtype_lhs == VTYPE_UINT); + break; + + case MP_BINARY_OP_NOT_EQUAL: + asm_rv32_meta_comparison_ne(emit->as, reg_rhs, REG_ARG_2, REG_RET); + break; + + default: + break; + } + #elif N_DEBUG + asm_debug_setcc_reg_reg_reg(emit->as, op_idx, REG_RET, REG_ARG_2, reg_rhs); #else #error not implemented #endif @@ -2792,6 +2911,7 @@ static void emit_native_call_function(emit_t *emit, mp_uint_t n_positional, mp_u } static void emit_native_call_method(emit_t *emit, mp_uint_t n_positional, mp_uint_t n_keyword, mp_uint_t star_flags) { + DEBUG_printf("call_method(%d, %d, %d)\n", n_positional, n_keyword, star_flags); if (star_flags) { emit_get_stack_pointer_to_reg_for_pop(emit, REG_ARG_3, n_positional + 2 * n_keyword + 3); // pointer to args emit_call_with_2_imm_args(emit, MP_F_CALL_METHOD_N_KW_VAR, 1, REG_ARG_1, n_positional | (n_keyword << 8), REG_ARG_2); @@ -2858,8 +2978,10 @@ static void emit_native_return_value(emit_t *emit) { } static void emit_native_raise_varargs(emit_t *emit, mp_uint_t n_args) { - (void)n_args; - assert(n_args == 1); + DEBUG_printf("raise_varargs(%d)\n", n_args); + if (n_args != 1) { + mp_raise_NotImplementedError(MP_ERROR_TEXT("native raise")); + } vtype_kind_t vtype_exc; emit_pre_pop_reg(emit, &vtype_exc, REG_ARG_1); // arg1 = object to raise if (vtype_exc != VTYPE_PYOBJ) { @@ -2873,6 +2995,8 @@ static void emit_native_raise_varargs(emit_t *emit, mp_uint_t n_args) { static void emit_native_yield(emit_t *emit, int kind) { // Note: 1 (yield) or 3 (yield from) labels are reserved for this function, starting at *emit->label_slot + DEBUG_printf("yield(%d)\n", kind); + if (emit->do_viper_types) { mp_raise_NotImplementedError(MP_ERROR_TEXT("native yield")); } @@ -2928,18 +3052,21 @@ static void emit_native_yield(emit_t *emit, int kind) { 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)); + // Check LOCAL_IDX_THROW_VAL for any injected value + ASM_MOV_REG_LOCAL(emit->as, REG_ARG_1, LOCAL_IDX_THROW_VAL(emit)); + ASM_MOV_LOCAL_MP_OBJ_NULL(emit->as, LOCAL_IDX_THROW_VAL(emit), REG_ARG_2); 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 + ASM_MOV_REG_LOCAL(emit->as, REG_ARG_3, LOCAL_IDX_THROW_VAL(emit)); // throw_value + ASM_MOV_REG_IMM(emit->as, REG_ARG_2, (mp_uint_t)MP_OBJ_NULL); + ASM_MOV_LOCAL_REG(emit->as, LOCAL_IDX_THROW_VAL(emit), REG_ARG_2); 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); @@ -2963,7 +3090,6 @@ static void emit_native_start_except_handler(emit_t *emit) { } static void emit_native_end_except_handler(emit_t *emit) { - adjust_stack(emit, -1); // pop the exception (end_finally didn't use it) } const emit_method_table_t EXPORT_FUN(method_table) = { @@ -3012,6 +3138,9 @@ const emit_method_table_t EXPORT_FUN(method_table) = { emit_native_unwind_jump, emit_native_setup_block, emit_native_with_cleanup, + #if MICROPY_PY_ASYNC_AWAIT + emit_native_async_with_setup_finally, + #endif emit_native_end_finally, emit_native_get_iter, emit_native_for_iter, diff --git a/py/emitndebug.c b/py/emitndebug.c new file mode 100644 index 00000000000..27c3bbdcef7 --- /dev/null +++ b/py/emitndebug.c @@ -0,0 +1,284 @@ +// native-debug specific stuff + +#include "py/mpconfig.h" + +#if MICROPY_EMIT_NATIVE_DEBUG + +#include "py/asmbase.h" +#include "py/nativeglue.h" + +#define asm_debug_printf(as, fmt, ...) \ + do { \ + if (as->base.pass == MP_ASM_PASS_EMIT) { \ + if (fmt[0] != 'E') { \ + mp_printf(MICROPY_EMIT_NATIVE_DEBUG_PRINTER, " "); \ + } \ + if (as->base.suppress) { \ + mp_printf(MICROPY_EMIT_NATIVE_DEBUG_PRINTER, "dead_code "); \ + } \ + mp_printf(MICROPY_EMIT_NATIVE_DEBUG_PRINTER, fmt, __VA_ARGS__); \ + } \ + } while (0) + +enum { + ASM_DEBUG_REG_R00, + ASM_DEBUG_REG_R01, + ASM_DEBUG_REG_R02, + ASM_DEBUG_REG_R03, + ASM_DEBUG_REG_R04, + ASM_DEBUG_REG_R05, + ASM_DEBUG_REG_R06, + ASM_DEBUG_REG_R07, + ASM_DEBUG_REG_R08, + ASM_DEBUG_REG_R09, + ASM_DEBUG_REG_R10, + ASM_DEBUG_REG_R11, +}; + +typedef struct _asm_debug_t { + mp_asm_base_t base; +} asm_debug_t; + +static const char *const reg_name_table[] = { + "r_ret", + "r_arg1", + "r_arg2", + "r_arg3", + "r_arg4", + "r_temp0", + "r_temp1", + "r_temp2", + "r_local1", + "r_local2", + "r_local3", + "r_fun_table", +}; + +static const char *const fun_name_table[MP_F_NUMBER_OF] = { + [MP_F_CONVERT_OBJ_TO_NATIVE] = "convert_obj_to_native", + [MP_F_CONVERT_NATIVE_TO_OBJ] = "convert_native_to_obj", + [MP_F_NATIVE_SWAP_GLOBALS] = "native_swap_globals", + [MP_F_LOAD_NAME] = "load_name", + [MP_F_LOAD_GLOBAL] = "load_global", + [MP_F_LOAD_BUILD_CLASS] = "load_build_class", + [MP_F_LOAD_ATTR] = "load_attr", + [MP_F_LOAD_METHOD] = "load_method", + [MP_F_LOAD_SUPER_METHOD] = "load_super_method", + [MP_F_STORE_NAME] = "store_name", + [MP_F_STORE_GLOBAL] = "store_global", + [MP_F_STORE_ATTR] = "store_attr", + [MP_F_OBJ_SUBSCR] = "obj_subscr", + [MP_F_OBJ_IS_TRUE] = "obj_is_true", + [MP_F_UNARY_OP] = "unary_op", + [MP_F_BINARY_OP] = "binary_op", + [MP_F_BUILD_TUPLE] = "build_tuple", + [MP_F_BUILD_LIST] = "build_list", + [MP_F_BUILD_MAP] = "build_map", + [MP_F_BUILD_SET] = "build_set", + [MP_F_STORE_SET] = "store_set", + [MP_F_LIST_APPEND] = "list_append", + [MP_F_STORE_MAP] = "store_map", + [MP_F_MAKE_FUNCTION_FROM_PROTO_FUN] = "make_function_from_proto_fun", + [MP_F_NATIVE_CALL_FUNCTION_N_KW] = "native_call_function_n_kw", + [MP_F_CALL_METHOD_N_KW] = "call_method_n_kw", + [MP_F_CALL_METHOD_N_KW_VAR] = "call_method_n_kw_var", + [MP_F_NATIVE_GETITER] = "native_getiter", + [MP_F_NATIVE_ITERNEXT] = "native_iternext", + [MP_F_NLR_PUSH] = "nlr_push", + [MP_F_NLR_POP] = "nlr_pop", + [MP_F_NATIVE_RAISE] = "native_raise", + [MP_F_IMPORT_NAME] = "import_name", + [MP_F_IMPORT_FROM] = "import_from", + [MP_F_IMPORT_ALL] = "import_all", + [MP_F_NEW_SLICE] = "new_slice", + [MP_F_UNPACK_SEQUENCE] = "unpack_sequence", + [MP_F_UNPACK_EX] = "unpack_ex", + [MP_F_DELETE_NAME] = "delete_name", + [MP_F_DELETE_GLOBAL] = "delete_global", + [MP_F_NEW_CLOSURE] = "new_closure", + [MP_F_ARG_CHECK_NUM_SIG] = "arg_check_num_sig", + [MP_F_SETUP_CODE_STATE] = "setup_code_state", + [MP_F_SMALL_INT_FLOOR_DIVIDE] = "small_int_floor_divide", + [MP_F_SMALL_INT_MODULO] = "small_int_modulo", + [MP_F_NATIVE_YIELD_FROM] = "native_yield_from", + [MP_F_SETJMP] = "setjmp", +}; + +static void asm_debug_end_pass(asm_debug_t *as) { + (void)as; +} + +static void asm_debug_entry(asm_debug_t *as, int num_locals, char *name) { + asm_debug_printf(as, "ENTRY(%s, num_locals=%d)\n", name != NULL ? name : "?", num_locals); +} + +static void asm_debug_exit(asm_debug_t *as) { + asm_debug_printf(as, "EXIT(%u)\n", 0); +} + +static void asm_debug_fun(asm_debug_t *as, const char *op, int fun_idx) { + asm_debug_printf(as, "%s(%s)\n", op, fun_name_table[fun_idx]); +} + +static void asm_debug_reg(asm_debug_t *as, const char *op, int reg) { + asm_debug_printf(as, "%s(%s)\n", op, reg_name_table[reg]); +} + +static void asm_debug_label(asm_debug_t *as, const char *op, unsigned int label) { + asm_debug_printf(as, "%s(label_%u)\n", op, label); +} + +static void asm_debug_reg_imm(asm_debug_t *as, const char *op, int reg, int imm) { + asm_debug_printf(as, "%s(%s, %d=0x%x)\n", op, reg_name_table[reg], imm, imm); +} + +#if !MICROPY_PERSISTENT_CODE_SAVE +static void asm_debug_reg_qstr(asm_debug_t *as, const char *op, int reg, int qst) { + asm_debug_printf(as, "%s(%s, %q)\n", op, reg_name_table[reg], (qstr)qst); +} +#endif + +static void asm_debug_reg_reg(asm_debug_t *as, const char *op, int reg1, int reg2) { + asm_debug_printf(as, "%s(%s, %s)\n", op, reg_name_table[reg1], reg_name_table[reg2]); +} + +static void asm_debug_reg_local(asm_debug_t *as, const char *op, int reg, unsigned int local) { + asm_debug_printf(as, "%s(%s, local_%u)\n", op, reg_name_table[reg], local); +} + +static void asm_debug_reg_label(asm_debug_t *as, const char *op, int reg, unsigned int label) { + asm_debug_printf(as, "%s(%s, label_%u)\n", op, reg_name_table[reg], label); +} + +static void asm_debug_local_reg(asm_debug_t *as, const char *op, int local, int reg) { + asm_debug_printf(as, "%s(local_%d, %s)\n", op, local, reg_name_table[reg]); +} + +static void asm_debug_reg_label_bool(asm_debug_t *as, const char *op, int reg, unsigned int label, bool b) { + asm_debug_printf(as, "%s(%s, label_%u, %s)\n", op, reg_name_table[reg], label, b ? "true" : "false"); +} + +static void asm_debug_reg_reg_offset(asm_debug_t *as, const char *op, int reg1, int reg2, int offset) { + asm_debug_printf(as, "%s(%s, %s, %d)\n", op, reg_name_table[reg1], reg_name_table[reg2], offset); +} + +static void asm_debug_reg_reg_label(asm_debug_t *as, const char *op, int reg1, int reg2, unsigned int label) { + asm_debug_printf(as, "%s(%s, %s, label_%u)\n", op, reg_name_table[reg1], reg_name_table[reg2], label); +} + +static void asm_debug_setcc_reg_reg_reg(asm_debug_t *as, int op, int reg1, int reg2, int reg3) { + asm_debug_printf(as, "setcc(%d, %s, %s, %s)\n", op, reg_name_table[reg1], reg_name_table[reg2], reg_name_table[reg3]); +} + +// The following macros provide a (mostly) arch-independent API to +// generate native code, and are used by the native emitter. + +#define ASM_WORD_SIZE (8) + +#define REG_RET ASM_DEBUG_REG_R00 +#define REG_ARG_1 ASM_DEBUG_REG_R01 +#define REG_ARG_2 ASM_DEBUG_REG_R02 +#define REG_ARG_3 ASM_DEBUG_REG_R03 +#define REG_ARG_4 ASM_DEBUG_REG_R04 + +#define REG_TEMP0 ASM_DEBUG_REG_R05 +#define REG_TEMP1 ASM_DEBUG_REG_R06 +#define REG_TEMP2 ASM_DEBUG_REG_R07 + +#define REG_LOCAL_1 ASM_DEBUG_REG_R08 +#define REG_LOCAL_2 ASM_DEBUG_REG_R09 +#define REG_LOCAL_3 ASM_DEBUG_REG_R10 +#define REG_LOCAL_NUM (3) + +// Holds a pointer to mp_fun_table +#define REG_FUN_TABLE ASM_DEBUG_REG_R11 + +#define ASM_T asm_debug_t +#define ASM_END_PASS asm_debug_end_pass +#define ASM_ENTRY(as, num_locals, name) \ + asm_debug_entry(as, num_locals, name) +#define ASM_EXIT(as) \ + asm_debug_exit(as) + +#define ASM_JUMP(as, label) \ + asm_debug_label(as, "jump", label) +#define ASM_JUMP_IF_REG_ZERO(as, reg, label, bool_test) \ + asm_debug_reg_label_bool(as, "jump_if_reg_zero", reg, label, bool_test) +#define ASM_JUMP_IF_REG_NONZERO(as, reg, label, bool_test) \ + asm_debug_reg_label_bool(as, "jump_if_reg_nonzero", reg, label, bool_test) +#define ASM_JUMP_IF_REG_EQ(as, reg1, reg2, label) \ + asm_debug_reg_reg_label(as, "jump_if_reg_eq", reg1, reg2, label) +#define ASM_JUMP_REG(as, reg) \ + asm_debug_reg(as, "jump_reg", reg) +#define ASM_CALL_IND(as, idx) \ + asm_debug_fun(as, "call_ind", idx) + +#define ASM_MOV_LOCAL_REG(as, local_num, reg_src) \ + asm_debug_local_reg(as, "mov_local_reg", local_num, reg_src) +#define ASM_MOV_REG_IMM(as, reg_dest, imm) \ + asm_debug_reg_imm(as, "mov_reg_imm", reg_dest, imm) +#define ASM_MOV_REG_QSTR(as, reg_dest, qst) \ + asm_debug_reg_qstr(as, "mov_reg_qstr", reg_dest, qst) +#define ASM_MOV_REG_LOCAL(as, reg_dest, local_num) \ + asm_debug_reg_local(as, "mov_reg_local", reg_dest, local_num) +#define ASM_MOV_REG_REG(as, reg_dest, reg_src) \ + asm_debug_reg_reg(as, "mov_reg_reg", reg_dest, reg_src) +#define ASM_MOV_REG_LOCAL_ADDR(as, reg_dest, local_num) \ + asm_debug_reg_local(as, "mov_reg_local_addr", reg_dest, local_num) +#define ASM_MOV_REG_PCREL(as, reg_dest, label) \ + asm_debug_reg_label(as, "mov_reg_pcrel", reg_dest, label) + +#define ASM_NOT_REG(as, reg_dest) \ + asm_debug_reg(as, "not", reg_dest) +#define ASM_NEG_REG(as, reg_dest) \ + asm_debug_reg(as, "neg", reg_dest) +#define ASM_LSL_REG_REG(as, reg_dest, reg_src) \ + asm_debug_reg_reg(as, "lsl", reg_dest, reg_src) +#define ASM_LSR_REG_REG(as, reg_dest, reg_src) \ + asm_debug_reg_reg(as, "lsr", reg_dest, reg_src) +#define ASM_ASR_REG_REG(as, reg_dest, reg_src) \ + asm_debug_reg_reg(as, "asr", reg_dest, reg_src) +#define ASM_OR_REG_REG(as, reg_dest, reg_src) \ + asm_debug_reg_reg(as, "or", reg_dest, reg_src) +#define ASM_XOR_REG_REG(as, reg_dest, reg_src) \ + asm_debug_reg_reg(as, "xor", reg_dest, reg_src) +#define ASM_AND_REG_REG(as, reg_dest, reg_src) \ + asm_debug_reg_reg(as, "and", reg_dest, reg_src) +#define ASM_ADD_REG_REG(as, reg_dest, reg_src) \ + asm_debug_reg_reg(as, "add", reg_dest, reg_src) +#define ASM_SUB_REG_REG(as, reg_dest, reg_src) \ + asm_debug_reg_reg(as, "sub", reg_dest, reg_src) +#define ASM_MUL_REG_REG(as, reg_dest, reg_src) \ + asm_debug_reg_reg(as, "mul", reg_dest, reg_src) + +#define ASM_LOAD_REG_REG_OFFSET(as, reg_dest, reg_base, word_offset) \ + asm_debug_reg_reg_offset(as, "load", reg_dest, reg_base, word_offset) +#define ASM_LOAD8_REG_REG(as, reg_dest, reg_base) \ + asm_debug_reg_reg(as, "load8", reg_dest, reg_base) +#define ASM_LOAD16_REG_REG(as, reg_dest, reg_base) \ + asm_debug_reg_reg(as, "load16", reg_dest, reg_base) +#define ASM_LOAD16_REG_REG_OFFSET(as, reg_dest, reg_base, uint16_offset) \ + asm_debug_reg_reg_offset(as, "load16", reg_dest, reg_base, uint16_offset) +#define ASM_LOAD32_REG_REG(as, reg_dest, reg_base) \ + asm_debug_reg_reg(as, "load32", reg_dest, reg_base) + +#define ASM_STORE_REG_REG_OFFSET(as, reg_src, reg_base, word_offset) \ + asm_debug_reg_reg_offset(as, "store", reg_src, reg_base, word_offset) +#define ASM_STORE8_REG_REG(as, reg_src, reg_base) \ + asm_debug_reg_reg(as, "store8", reg_src, reg_base) +#define ASM_STORE16_REG_REG(as, reg_src, reg_base) \ + asm_debug_reg_reg(as, "store16", reg_src, reg_base) +#define ASM_STORE32_REG_REG(as, reg_src, reg_base) \ + asm_debug_reg_reg(as, "store32", reg_src, reg_base) + +#define ASM_CLR_REG(as, reg_dest) \ + asm_debug_reg(as, "clr", reg_dest) + +// Word indices of REG_LOCAL_x in nlr_buf_t +#define NLR_BUF_IDX_LOCAL_1 (5) // rbx + +#define N_DEBUG (1) +#define EXPORT_FUN(name) emit_native_debug_##name +#include "py/emitnative.c" + +#endif diff --git a/py/emitnrv32.c b/py/emitnrv32.c new file mode 100644 index 00000000000..4a441000931 --- /dev/null +++ b/py/emitnrv32.c @@ -0,0 +1,44 @@ +/* + * This file is part of the MicroPython project, https://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2024 Alessandro Gatti + * + * 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. + */ + +// RISC-V RV32 specific stuff + +#include "py/mpconfig.h" + +#if MICROPY_EMIT_RV32 + +// this is defined so that the assembler exports generic assembler API macros +#define GENERIC_ASM_API (1) +#include "py/asmrv32.h" + +// Word indices of REG_LOCAL_x in nlr_buf_t +#define NLR_BUF_IDX_LOCAL_1 (6) // S3 + +#define N_RV32 (1) +#define EXPORT_FUN(name) emit_native_rv32_##name +#include "py/emitnative.c" + +#endif diff --git a/py/formatfloat.c b/py/formatfloat.c index b4348122ff4..1ea34f84bf7 100644 --- a/py/formatfloat.c +++ b/py/formatfloat.c @@ -33,394 +33,537 @@ #include #include #include "py/formatfloat.h" +#include "py/parsenum.h" /*********************************************************************** Routine for converting a arbitrary floating point number into a string. - The code in this function was inspired from Fred Bayer's pdouble.c. - Since pdouble.c was released as Public Domain, I'm releasing this - code as public domain as well. + The code in this function was inspired from Dave Hylands's previous + version, which was itself inspired from Fred Bayer's pdouble.c. The original code can be found in https://github.com/dhylands/format-float - Dave Hylands - ***********************************************************************/ -#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT -// 1 sign bit, 8 exponent bits, and 23 mantissa bits. -// exponent values 0 and 255 are reserved, exponent can be 1 to 254. -// exponent is stored with a bias of 127. -// The min and max floats are on the order of 1x10^37 and 1x10^-37 - -#define FPTYPE float -#define FPCONST(x) x##F -#define FPROUND_TO_ONE 0.9999995F -#define FPDECEXP 32 -#define FPMIN_BUF_SIZE 6 // +9e+99 +// Float formatting debug code is intended for use in ports/unix only, +// as it uses the libc float printing function as a reference. +#define DEBUG_FLOAT_FORMATTING 0 + +#if DEBUG_FLOAT_FORMATTING +#define DEBUG_PRINTF(...) fprintf(stderr, __VA_ARGS__) +#else +#define DEBUG_PRINTF(...) +#endif + +#if MICROPY_FLOAT_FORMAT_IMPL == MICROPY_FLOAT_FORMAT_IMPL_EXACT || MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE +#define MP_FFUINT_FMT "%lu" +#else +#define MP_FFUINT_FMT "%u" +#endif + +static inline int fp_expval(mp_float_t x) { + mp_float_union_t fb = { x }; + return (int)fb.p.exp - MP_FLOAT_EXP_OFFSET; +} -#define FLT_SIGN_MASK 0x80000000 +#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE -static inline int fp_signbit(float x) { - mp_float_union_t fb = {x}; - return fb.i & FLT_SIGN_MASK; +static inline int fp_isless1(mp_float_t x) { + return x < 1.0; } -#define fp_isnan(x) isnan(x) -#define fp_isinf(x) isinf(x) -static inline int fp_iszero(float x) { - mp_float_union_t fb = {x}; - return fb.i == 0; + +static inline int fp_iszero(mp_float_t x) { + return x == 0.0; } -static inline int fp_isless1(float x) { - mp_float_union_t fb = {x}; + +#if MICROPY_FLOAT_FORMAT_IMPL != MICROPY_FLOAT_FORMAT_IMPL_APPROX +static inline int fp_equal(mp_float_t x, mp_float_t y) { + return x == y; +} +#else +static inline mp_float_t fp_diff(mp_float_t x, mp_float_t y) { + return x - y; +} +#endif + +#elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT + +// The functions below are roughly equivalent to the ones above, +// but they are optimized to reduce code footprint by skipping +// handling for special values such as nan, inf, +/-0.0 +// for ports where FP support is done in software. +// +// They also take into account lost bits of REPR_C as needed. + +static inline int fp_isless1(mp_float_t x) { + mp_float_union_t fb = { x }; return fb.i < 0x3f800000; } -#elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE +static inline int fp_iszero(mp_float_t x) { + mp_float_union_t x_check = { x }; + return !x_check.i; // this is valid for REPR_C as well +} -// CIRCUITPY-CHANGE: prevent warnings -#pragma GCC diagnostic ignored "-Wfloat-equal" -#define FPTYPE double -#define FPCONST(x) x -#define FPROUND_TO_ONE 0.999999999995 -#define FPDECEXP 256 -#define FPMIN_BUF_SIZE 7 // +9e+199 -#define fp_signbit(x) signbit(x) -#define fp_isnan(x) isnan(x) -#define fp_isinf(x) isinf(x) -#define fp_iszero(x) (x == 0) -#define fp_isless1(x) (x < 1.0) +#if MICROPY_FLOAT_FORMAT_IMPL != MICROPY_FLOAT_FORMAT_IMPL_APPROX +static inline int fp_equal(mp_float_t x, mp_float_t y) { + mp_float_union_t x_check = { x }; + mp_float_union_t y_check = { y }; + #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C + return (x_check.i & ~3) == (y_check.i & ~3); + #else + return x_check.i == y_check.i; + #endif +} +#else +static inline mp_float_t fp_diff(mp_float_t x, mp_float_t y) { + #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C + mp_float_union_t x_check = { x }; + mp_float_union_t y_check = { y }; + x_check.i &= ~3; + y_check.i &= ~3; + return x_check.f - y_check.f; + #else + return x - y; + #endif +} +#endif -#endif // MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT/DOUBLE +#endif -static inline int fp_expval(FPTYPE x) { - mp_float_union_t fb = {x}; - return (int)((fb.i >> MP_FLOAT_FRAC_BITS) & (~(0xFFFFFFFF << MP_FLOAT_EXP_BITS))) - MP_FLOAT_EXP_OFFSET; +#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT +#define FPMIN_BUF_SIZE 6 // +9e+99 +#define MAX_MANTISSA_DIGITS (9) +#define SAFE_MANTISSA_DIGITS (6) +#elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE +#define FPMIN_BUF_SIZE 7 // +9e+199 +#define MAX_MANTISSA_DIGITS (19) +#define SAFE_MANTISSA_DIGITS (16) +#endif + +// Internal formatting flags +#define FMT_MODE_E 0x01 // render using scientific notation (%e) +#define FMT_MODE_G 0x02 // render using general format (%g) +#define FMT_MODE_F 0x04 // render using using expanded fixed-point format (%f) +#define FMT_E_CASE 0x20 // don't change this value (used for case conversion!) + +static char *mp_prepend_zeros(char *s, int cnt) { + *s++ = '0'; + *s++ = '.'; + while (cnt > 0) { + *s++ = '0'; + cnt--; + } + return s; } -int mp_format_float(FPTYPE f, char *buf, size_t buf_size, char fmt, int prec, char sign) { +// Helper to convert a decimal mantissa (provided as an mp_large_float_uint_t) to string +static int mp_format_mantissa(mp_large_float_uint_t mantissa, mp_large_float_uint_t mantissa_cap, char *buf, char *s, + int num_digits, int max_exp_zeros, int trailing_zeros, int dec, int e, int fmt_flags) { - char *s = buf; + DEBUG_PRINTF("mantissa=" MP_FFUINT_FMT " exp=%d (cap=" MP_FFUINT_FMT "):\n", mantissa, e, mantissa_cap); - if (buf_size <= FPMIN_BUF_SIZE) { - // FPMIN_BUF_SIZE is the minimum size needed to store any FP number. - // If the buffer does not have enough room for this (plus null terminator) - // then don't try to format the float. + if (mantissa) { + // If rounding/searching created an extra digit or removed too many, fix mantissa first + if (mantissa >= mantissa_cap) { + if (fmt_flags & FMT_MODE_F) { + assert(e >= 0); + num_digits++; + dec++; + } else { + mantissa /= 10; + e++; + } + } + } - if (buf_size >= 2) { - *s++ = '?'; + // When 'g' format is used, replace small exponents by explicit zeros + if ((fmt_flags & FMT_MODE_G) && e != 0) { + if (e >= 0) { + // If 0 < e < max_exp_zeros, expand positive exponent into trailing zeros + if (e < max_exp_zeros) { + dec += e; + if (dec >= num_digits) { + trailing_zeros = dec - (num_digits - 1); + } + e = 0; + } + } else { + // If -4 <= e < 0, expand negative exponent without losing significant digits + if (e >= -4) { + int cnt = 0; + while (e < 0 && !(mantissa % 10)) { + mantissa /= 10; + cnt++; + e++; + } + num_digits -= cnt; + s = mp_prepend_zeros(s, cnt - e - 1); + dec = 255; + e = 0; + } } - if (buf_size >= 1) { - *s = '\0'; + } + + // Convert the integer mantissa to string + for (int digit = num_digits - 1; digit >= 0; digit--) { + int digit_ofs = (digit > dec ? digit + 1 : digit); + s[digit_ofs] = '0' + (int)(mantissa % 10); + mantissa /= 10; + } + int dot = (dec >= 255); + if (dec + 1 < num_digits) { + dot = 1; + s++; + s[dec] = '.'; + } + s += num_digits; + #if DEBUG_FLOAT_FORMATTING + *s = 0; + DEBUG_PRINTF(" = %s exp=%d num_digits=%d zeros=%d dec=%d\n", buf, e, num_digits, trailing_zeros, dec); + #endif + + // Append or remove trailing zeros, as required by format + if (trailing_zeros) { + dec -= num_digits - 1; + while (trailing_zeros--) { + if (!dec--) { + *s++ = '.'; + dot = 1; + } + *s++ = '0'; } - return buf_size >= 2; } - if (fp_signbit(f) && !fp_isnan(f)) { - *s++ = '-'; - f = -f; - } else { - if (sign) { - *s++ = sign; + if (fmt_flags & FMT_MODE_G) { + // 'g' format requires to remove trailing zeros after decimal point + if (dot) { + while (s[-1] == '0') { + s--; + } + if (s[-1] == '.') { + s--; + } + } + } + + // Append the exponent if needed + if (((e != 0) || (fmt_flags & FMT_MODE_E)) && !(fmt_flags & FMT_MODE_F)) { + *s++ = 'E' | (fmt_flags & FMT_E_CASE); + if (e >= 0) { + *s++ = '+'; + } else { + *s++ = '-'; + e = -e; } + if (e >= 100) { + *s++ = '0' + (e / 100); + } + *s++ = '0' + ((e / 10) % 10); + *s++ = '0' + (e % 10); } + *s = '\0'; + DEBUG_PRINTF(" ===> %s\n", buf); - // buf_remaining contains bytes available for digits and exponent. - // It is buf_size minus room for the sign and null byte. - int buf_remaining = buf_size - 1 - (s - buf); + return s - buf; +} +// minimal value expected for buf_size, to avoid checking everywhere for overflow +#define MIN_BUF_SIZE (MAX_MANTISSA_DIGITS + 10) + +int mp_format_float(mp_float_t f_entry, char *buf_entry, size_t buf_size, char fmt, int prec, char sign) { + assert(buf_size >= MIN_BUF_SIZE); + + // Handle sign + mp_float_t f = f_entry; + char *buf = buf_entry; + if (signbit(f_entry) && !isnan(f_entry)) { + f = -f; + sign = '-'; + } + if (sign) { + *buf++ = sign; + buf_size--; + } + + // Handle inf/nan + char uc = fmt & 0x20; { - char uc = fmt & 0x20; - if (fp_isinf(f)) { + char *s = buf; + if (isinf(f)) { *s++ = 'I' ^ uc; *s++ = 'N' ^ uc; *s++ = 'F' ^ uc; goto ret; - } else if (fp_isnan(f)) { + } else if (isnan(f)) { *s++ = 'N' ^ uc; *s++ = 'A' ^ uc; *s++ = 'N' ^ uc; ret: *s = '\0'; - return s - buf; + return s - buf_entry; } } + // Decode format character + int fmt_flags = (unsigned char)uc; // setup FMT_E_CASE, clear all other bits + char lofmt = (char)(fmt | 0x20); // fmt in lowercase + if (lofmt == 'f') { + fmt_flags |= FMT_MODE_F; + } else if (lofmt == 'g') { + fmt_flags |= FMT_MODE_G; + } else { + fmt_flags |= FMT_MODE_E; + } + + // When precision is unspecified, default to 6 if (prec < 0) { prec = 6; } - char e_char = 'E' | (fmt & 0x20); // e_char will match case of fmt - fmt |= 0x20; // Force fmt to be lowercase - char org_fmt = fmt; - if (fmt == 'g' && prec == 0) { - prec = 1; + // Use high precision for `repr`, but switch to exponent mode + // after 16 digits in any case to match CPython behaviour + int max_exp_zeros = (prec < (int)buf_size - 3 ? prec : (int)buf_size - 3); + if (prec == MP_FLOAT_REPR_PREC) { + prec = MAX_MANTISSA_DIGITS; + max_exp_zeros = 16; } - int e; - int dec = 0; - char e_sign = '\0'; - int num_digits = 0; - int signed_e = 0; - // Approximate power of 10 exponent from binary exponent. - // abs(e_guess) is lower bound on abs(power of 10 exponent). - int e_guess = (int)(fp_expval(f) * FPCONST(0.3010299956639812)); // 1/log2(10). - if (fp_iszero(f)) { - e = 0; - if (fmt == 'f') { - // Truncate precision to prevent buffer overflow - if (prec + 2 > buf_remaining) { - prec = buf_remaining - 2; - } - num_digits = prec + 1; - } else { - // Truncate precision to prevent buffer overflow - if (prec + 6 > buf_remaining) { - prec = buf_remaining - 6; - } - if (fmt == 'e') { - e_sign = '+'; - } + // Precompute the exact decimal exponent of f, such that + // abs(e) is lower bound on abs(power of 10 exponent). + int e = 0; + if (!fp_iszero(f)) { + // Approximate power of 10 exponent from binary exponent. + e = (int)(fp_expval(f) * MICROPY_FLOAT_CONST(0.3010299956639812)); // 1/log2(10). + int positive_exp = !fp_isless1(f); + mp_float_t u_base = (mp_float_t)mp_decimal_exp((mp_large_float_t)1.0, e + positive_exp); + while ((f >= u_base) == positive_exp) { + e += (positive_exp ? 1 : -1); + u_base = (mp_float_t)mp_decimal_exp((mp_large_float_t)1.0, e + positive_exp); } - } else if (fp_isless1(f)) { - FPTYPE f_entry = f; // Save f in case we go to 'f' format. - // Build negative exponent - e = -e_guess; - FPTYPE u_base = MICROPY_FLOAT_C_FUN(pow)(10, -e); - while (u_base > f) { - ++e; - u_base = MICROPY_FLOAT_C_FUN(pow)(10, -e); - } - // Normalize out the inferred unit. Use divide because - // pow(10, e) * pow(10, -e) is slightly < 1 for some e in float32 - // (e.g. print("%.12f" % ((1e13) * (1e-13)))) - f /= u_base; - - // If the user specified 'g' format, and e is <= 4, then we'll switch - // to the fixed format ('f') - - if (fmt == 'f' || (fmt == 'g' && e <= 4)) { - fmt = 'f'; - dec = 0; + } - if (org_fmt == 'g') { - prec += (e - 1); - } + // For 'e' format, prec is # digits after the decimal + // For 'f' format, prec is # digits after the decimal + // For 'g' format, prec is the max number of significant digits + // + // For 'e' & 'g' format, there will be a single digit before the decimal + // For 'f' format, zeros must be expanded instead of using an exponent. + // Make sure there is enough room in the buffer for them, or switch to format 'g'. + if ((fmt_flags & FMT_MODE_F) && e > 0) { + int req_size = e + prec + 2; + if (req_size > (int)buf_size) { + fmt_flags ^= FMT_MODE_F; + fmt_flags |= FMT_MODE_G; + prec++; + } + } - // truncate precision to prevent buffer overflow - if (prec + 2 > buf_remaining) { - prec = buf_remaining - 2; + // To work independently of the format, we precompute: + // - the max number of significant digits to produce + // - the number of leading zeros to prepend (mode f only) + // - the number of trailing zeros to append + int max_digits = prec; + int lead_zeros = 0; + int trail_zeros = 0; + if (fmt_flags & FMT_MODE_F) { + if (max_digits > (int)buf_size - 3) { + // cannot satisfy requested number of decimals given buf_size, sorry + max_digits = (int)buf_size - 3; + } + if (e < 0) { + if (max_digits > 2 && e < -2) { + // Insert explicit leading zeros + lead_zeros = (-e < max_digits ? -e : max_digits) - 2; + max_digits -= lead_zeros; + } else { + max_digits++; } - - num_digits = prec; - signed_e = 0; - f = f_entry; - ++num_digits; } else { - // For e & g formats, we'll be printing the exponent, so set the - // sign. - e_sign = '-'; - dec = 0; - - if (prec > (buf_remaining - FPMIN_BUF_SIZE)) { - prec = buf_remaining - FPMIN_BUF_SIZE; - if (fmt == 'g') { - prec++; - } - } - signed_e = -e; + max_digits += e + 1; } } else { - // Build positive exponent. - // We don't modify f at this point to avoid inaccuracies from - // scaling it. Instead, we find the product of powers of 10 - // that is not greater than it, and use that to start the - // mantissa. - e = e_guess; - FPTYPE next_u = MICROPY_FLOAT_C_FUN(pow)(10, e + 1); - while (f >= next_u) { - ++e; - next_u = MICROPY_FLOAT_C_FUN(pow)(10, e + 1); + if (!(fmt_flags & FMT_MODE_G) || max_digits == 0) { + max_digits++; } + } + if (max_digits > MAX_MANTISSA_DIGITS) { + // use trailing zeros to avoid overflowing the mantissa + trail_zeros = max_digits - MAX_MANTISSA_DIGITS; + max_digits = MAX_MANTISSA_DIGITS; + } + int overhead = (fmt_flags & FMT_MODE_F ? 3 : FPMIN_BUF_SIZE + 1); + if (trail_zeros > (int)buf_size - max_digits - overhead) { + // cannot satisfy requested number of decimals given buf_size, sorry + trail_zeros = (int)buf_size - max_digits - overhead; + } - // If the user specified fixed format (fmt == 'f') and e makes the - // number too big to fit into the available buffer, then we'll - // switch to the 'e' format. - - if (fmt == 'f') { - if (e >= buf_remaining) { - fmt = 'e'; - } else if ((e + prec + 2) > buf_remaining) { - prec = buf_remaining - e - 2; - if (prec < 0) { - // This means no decimal point, so we can add one back - // for the decimal. - prec++; - } - } - } - if (fmt == 'e' && prec > (buf_remaining - FPMIN_BUF_SIZE)) { - prec = buf_remaining - FPMIN_BUF_SIZE; - } - if (fmt == 'g') { - // Truncate precision to prevent buffer overflow - if (prec + (FPMIN_BUF_SIZE - 1) > buf_remaining) { - prec = buf_remaining - (FPMIN_BUF_SIZE - 1); - } - } - // If the user specified 'g' format, and e is < prec, then we'll switch - // to the fixed format. + // When the caller asks for more precision than available for sure, + // Look for a shorter (rounded) representation first, and only dig + // into more digits if there is no short representation. + int num_digits = (SAFE_MANTISSA_DIGITS < max_digits ? SAFE_MANTISSA_DIGITS : max_digits); +try_again: + ; - if (fmt == 'g' && e < prec) { - fmt = 'f'; - prec -= (e + 1); - } - if (fmt == 'f') { - dec = e; - num_digits = prec + e + 1; + char *s = buf; + int extra_zeros = trail_zeros + (max_digits - num_digits); + int decexp; + int dec = 0; + + if (fp_iszero(f)) { + // no need for scaling 0.0 + decexp = 0; + } else if (fmt_flags & FMT_MODE_F) { + decexp = num_digits - 1; + if (e < 0) { + // Negative exponent: we keep a single leading zero in the mantissa, + // as using more would waste precious digits needed for accuracy. + if (lead_zeros > 0) { + // We are using leading zeros + s = mp_prepend_zeros(s, lead_zeros); + decexp += lead_zeros + 1; + dec = 255; // no decimal dot + } else { + // Small negative exponent, work directly on the mantissa + dec = 0; + } } else { - e_sign = '+'; + // Positive exponent: we will add trailing zeros separately + decexp -= e; + dec = e; } - signed_e = e; + } else { + decexp = num_digits - e - 1; } - if (prec < 0) { - // This can happen when the prec is trimmed to prevent buffer overflow - prec = 0; + DEBUG_PRINTF("input=%.19g e=%d fmt=%c max_d=%d num_d=%d decexp=%d dec=%d l0=%d r0=%d\n", + (double)f, e, lofmt, max_digits, num_digits, decexp, dec, lead_zeros, extra_zeros); + + // At this point, + // - buf points to beginning of output buffer for the unsigned representation + // - num_digits == the number of mantissa digits to add + // - (dec + 1) == the number of digits to print before adding a decimal point + // - decexp == the power of 10 exponent to apply to f to get the decimal mantissa + // - e == the power of 10 exponent to append ('e' or 'g' format) + mp_large_float_uint_t mantissa_cap = 10; + for (int n = 1; n < num_digits; n++) { + mantissa_cap *= 10; } - // At this point e contains the absolute value of the power of 10 exponent. - // (dec + 1) == the number of dgits before the decimal. - - // For e, prec is # digits after the decimal - // For f, prec is # digits after the decimal - // For g, prec is the max number of significant digits - // - // For e & g there will be a single digit before the decimal - // for f there will be e digits before the decimal - - if (fmt == 'e') { - num_digits = prec + 1; - } else if (fmt == 'g') { - if (prec == 0) { - prec = 1; + // Build the decimal mantissa into a large uint + mp_large_float_uint_t mantissa = 1; + if (sizeof(mp_large_float_t) == sizeof(mp_float_t) && num_digits > SAFE_MANTISSA_DIGITS && decexp > 1) { + // if we don't have large floats, use integer multiply to produce the last digits + if (num_digits > SAFE_MANTISSA_DIGITS + 1 && decexp > 2) { + mantissa = 100; + decexp -= 2; + } else { + mantissa = 10; + decexp -= 1; } - num_digits = prec; } - - int d = 0; - for (int digit_index = signed_e; num_digits >= 0; --digit_index) { - FPTYPE u_base = FPCONST(1.0); - if (digit_index > 0) { - // Generate 10^digit_index for positive digit_index. - u_base = MICROPY_FLOAT_C_FUN(pow)(10, digit_index); - } - for (d = 0; d < 9; ++d) { - if (f < u_base) { - break; - } - f -= u_base; - } - // We calculate one more digit than we display, to use in rounding - // below. So only emit the digit if it's one that we display. - if (num_digits > 0) { - // Emit this number (the leading digit). - *s++ = '0' + d; - if (dec == 0 && prec > 0) { - *s++ = '.'; - } - } - --dec; - --num_digits; - if (digit_index <= 0) { - // Once we get below 1.0, we scale up f instead of calculating - // negative powers of 10 in u_base. This provides better - // renditions of exact decimals like 1/16 etc. - f *= FPCONST(10.0); + mp_large_float_t mantissa_f = mp_decimal_exp((mp_large_float_t)f, decexp); + mantissa *= (mp_large_float_uint_t)(mantissa_f + (mp_large_float_t)0.5); + DEBUG_PRINTF("input=%.19g fmt=%c num_digits=%d dec=%d mantissa=" MP_FFUINT_FMT " r0=%d\n", (double)f, lofmt, num_digits, dec, mantissa, extra_zeros); + + // Finally convert the decimal mantissa to a floating-point string, according to formatting rules + int reprlen = mp_format_mantissa(mantissa, mantissa_cap, buf, s, num_digits, max_exp_zeros, extra_zeros, dec, e, fmt_flags); + assert(reprlen + 1 <= (int)buf_size); + + #if MICROPY_FLOAT_FORMAT_IMPL != MICROPY_FLOAT_FORMAT_IMPL_APPROX + + if (num_digits < max_digits) { + // The initial precision might not be sufficient for an exact representation + // for all numbers. If the result is not exact, restart using next precision. + // parse the resulting number and compare against the original + mp_float_t check; + DEBUG_PRINTF("input=%.19g, compare to float('%s')\n", (double)f, buf); + mp_parse_float_internal(buf, reprlen, &check); + if (!fp_equal(check, f)) { + num_digits++; + DEBUG_PRINTF("Not perfect, retry using more digits (%d)\n", num_digits); + goto try_again; } } - // Rounding. If the next digit to print is >= 5, round up. - if (d >= 5) { - char *rs = s; - rs--; - while (1) { - if (*rs == '.') { - rs--; - continue; - } - if (*rs < '0' || *rs > '9') { - // + or - - rs++; // So we sit on the digit to the right of the sign - break; + + #else + + // The initial decimal mantissa might not have been be completely accurate due + // to the previous loating point operations. The best way to verify this is to + // parse the resulting number and compare against the original + mp_float_t check; + DEBUG_PRINTF("input=%.19g, compare to float('%s')\n", (double)f, buf); + mp_parse_float_internal(buf, reprlen, &check); + mp_float_t diff = fp_diff(check, f); + mp_float_t best_diff = diff; + mp_large_float_uint_t best_mantissa = mantissa; + + if (fp_iszero(diff)) { + // we have a perfect match + DEBUG_PRINTF(MP_FFUINT_FMT ": perfect match (direct)\n", mantissa); + } else { + // In order to get the best possible representation, we will perform a + // dichotomic search for a reversible representation. + // This will also provide optimal rounding on the fly. + unsigned err_range = 1; + if (num_digits > SAFE_MANTISSA_DIGITS) { + err_range <<= 3 * (num_digits - SAFE_MANTISSA_DIGITS); + } + int maxruns = 3 + 3 * (MAX_MANTISSA_DIGITS - SAFE_MANTISSA_DIGITS); + while (maxruns-- > 0) { + // update mantissa according to dichotomic search + if (signbit(diff)) { + mantissa += err_range; + } else { + // mantissa is expected to always have more significant digits than err_range + assert(mantissa >= err_range); + mantissa -= err_range; } - if (*rs < '9') { - (*rs)++; + // retry conversion + reprlen = mp_format_mantissa(mantissa, mantissa_cap, buf, s, num_digits, max_exp_zeros, extra_zeros, dec, e, fmt_flags); + assert(reprlen + 1 <= (int)buf_size); + DEBUG_PRINTF("input=%.19g, compare to float('%s')\n", (double)f, buf); + mp_parse_float_internal(buf, reprlen, &check); + DEBUG_PRINTF("check=%.19g num_digits=%d e=%d mantissa=" MP_FFUINT_FMT "\n", (double)check, num_digits, e, mantissa); + diff = fp_diff(check, f); + if (fp_iszero(diff)) { + // we have a perfect match + DEBUG_PRINTF(MP_FFUINT_FMT ": perfect match\n", mantissa); break; } - *rs = '0'; - if (rs == buf) { - break; + // keep track of our best estimate + mp_float_t delta = MICROPY_FLOAT_C_FUN(fabs)(diff) - MICROPY_FLOAT_C_FUN(fabs)(best_diff); + if (signbit(delta) || (fp_iszero(delta) && !(mantissa % 10u))) { + best_diff = diff; + best_mantissa = mantissa; } - rs--; - } - if (*rs == '0') { - // We need to insert a 1 - if (rs[1] == '.' && fmt != 'f') { - // We're going to round 9.99 to 10.00 - // Move the decimal point - rs[0] = '.'; - rs[1] = '0'; - if (e_sign == '-') { - e--; - if (e == 0) { - e_sign = '+'; - } - } else { - e++; - } + // string repr is not perfect: continue a dichotomic improvement + DEBUG_PRINTF(MP_FFUINT_FMT ": %.19g, err_range=%d\n", mantissa, (double)check, err_range); + if (err_range > 1) { + err_range >>= 1; } else { - // Need at extra digit at the end to make room for the leading '1' - // but if we're at the buffer size limit, just drop the final digit. - if ((size_t)(s + 1 - buf) < buf_size) { - s++; + // We have tried all possible mantissa, without finding a reversible repr. + // Check if we have an alternate precision to try. + if (num_digits < max_digits) { + num_digits++; + DEBUG_PRINTF("Failed to find a perfect match, try with more digits (%d)\n", num_digits); + goto try_again; } + // Otherwise, keep the closest one, which is either the first one or the last one. + if (mantissa == best_mantissa) { + // Last guess is the best one + DEBUG_PRINTF(MP_FFUINT_FMT ": last guess was the best one\n", mantissa); + } else { + // We had a better guess earlier + DEBUG_PRINTF(MP_FFUINT_FMT ": use best guess\n", mantissa); + reprlen = mp_format_mantissa(best_mantissa, mantissa_cap, buf, s, num_digits, max_exp_zeros, extra_zeros, dec, e, fmt_flags); + } + break; } - char *ss = s; - while (ss > rs) { - *ss = ss[-1]; - ss--; - } - *rs = '1'; } } + #endif - // verify that we did not overrun the input buffer so far - assert((size_t)(s + 1 - buf) <= buf_size); - - if (org_fmt == 'g' && prec > 0) { - // Remove trailing zeros and a trailing decimal point - while (s[-1] == '0') { - s--; - } - if (s[-1] == '.') { - s--; - } - } - // Append the exponent - if (e_sign) { - *s++ = e_char; - *s++ = e_sign; - if (FPMIN_BUF_SIZE == 7 && e >= 100) { - *s++ = '0' + (e / 100); - } - *s++ = '0' + ((e / 10) % 10); - *s++ = '0' + (e % 10); - } - *s = '\0'; - - // verify that we did not overrun the input buffer - assert((size_t)(s + 1 - buf) <= buf_size); - - return s - buf; + return buf + reprlen - buf_entry; } #endif // MICROPY_FLOAT_IMPL != MICROPY_FLOAT_IMPL_NONE diff --git a/py/formatfloat.h b/py/formatfloat.h index 9a1643b4ddf..7b1414672b7 100644 --- a/py/formatfloat.h +++ b/py/formatfloat.h @@ -29,6 +29,7 @@ #include "py/mpconfig.h" #if MICROPY_PY_BUILTINS_FLOAT +#define MP_FLOAT_REPR_PREC (99) // magic `prec` value for optimal `repr` behaviour int mp_format_float(mp_float_t f, char *buf, size_t bufSize, char fmt, int prec, char sign); #endif diff --git a/py/gc.c b/py/gc.c index 5375218f3e9..eb057335998 100644 --- a/py/gc.c +++ b/py/gc.c @@ -32,6 +32,12 @@ #include "py/gc.h" #include "py/runtime.h" +#if defined(__ZEPHYR__) +#include +#include +#include +#endif + #if MICROPY_DEBUG_VALGRIND #include #endif @@ -39,10 +45,18 @@ // CIRCUITPY-CHANGE #include "supervisor/shared/safe_mode.h" +#include "supervisor/shared/serial.h" + #if CIRCUITPY_MEMORYMONITOR #include "shared-module/memorymonitor/__init__.h" #endif +#if defined(__ZEPHYR__) && defined(CONFIG_TRACING_PERFETTO) && defined(CONFIG_BOARD_NATIVE_SIM) +#include "perfetto_encoder.h" +#define CIRCUITPY_PERFETTO_VM_HEAP_USED_UUID 0x3001ULL +#define CIRCUITPY_PERFETTO_VM_HEAP_MAX_FREE_UUID 0x3002ULL +#endif + #if MICROPY_ENABLE_GC #if MICROPY_DEBUG_VERBOSE // print debugging info @@ -123,10 +137,33 @@ #define FTB_CLEAR(area, block) do { area->gc_finaliser_table_start[(block) / BLOCKS_PER_FTB] &= (~(1 << ((block) & 7))); } while (0) #endif +// CIRCUITPY-CHANGE: Add selective collect table to skip scanning large buffers without pointers +// CTB = collect table byte +// if set, then the corresponding block should be collected during GC + +#define BLOCKS_PER_CTB (8) + +#define CTB_GET(area, block) ((area->gc_collect_table_start[(block) / BLOCKS_PER_CTB] >> ((block) & 7)) & 1) +#define CTB_SET(area, block) do { area->gc_collect_table_start[(block) / BLOCKS_PER_CTB] |= (1 << ((block) & 7)); } while (0) +#define CTB_CLEAR(area, block) do { area->gc_collect_table_start[(block) / BLOCKS_PER_CTB] &= (~(1 << ((block) & 7))); } while (0) + +#if MICROPY_PY_WEAKREF +// WTB = weakref table byte +// if set, then the corresponding block may have a weakref in MP_STATE_VM(mp_weakref_map). +#define BLOCKS_PER_WTB (8) + +#define WTB_GET(area, block) ((area->gc_weakref_table_start[(block) / BLOCKS_PER_WTB] >> ((block) & 7)) & 1) +#define WTB_SET(area, block) do { area->gc_weakref_table_start[(block) / BLOCKS_PER_WTB] |= (1 << ((block) & 7)); } while (0) +#define WTB_CLEAR(area, block) do { area->gc_weakref_table_start[(block) / BLOCKS_PER_WTB] &= (~(1 << ((block) & 7))); } while (0) +#endif + #if MICROPY_PY_THREAD && !MICROPY_PY_THREAD_GIL -#define GC_ENTER() mp_thread_mutex_lock(&MP_STATE_MEM(gc_mutex), 1) -#define GC_EXIT() mp_thread_mutex_unlock(&MP_STATE_MEM(gc_mutex)) +#define GC_MUTEX_INIT() mp_thread_recursive_mutex_init(&MP_STATE_MEM(gc_mutex)) +#define GC_ENTER() mp_thread_recursive_mutex_lock(&MP_STATE_MEM(gc_mutex), 1) +#define GC_EXIT() mp_thread_recursive_mutex_unlock(&MP_STATE_MEM(gc_mutex)) #else +// Either no threading, or assume callers to gc_collect() hold the GIL +#define GC_MUTEX_INIT() #define GC_ENTER() #define GC_EXIT() #endif @@ -143,54 +180,124 @@ void __attribute__ ((noinline)) gc_log_change(uint32_t start_block, uint32_t len #pragma GCC pop_options #endif +#if defined(__ZEPHYR__) && defined(CONFIG_TRACING_PERFETTO) && defined(CONFIG_BOARD_NATIVE_SIM) +static void gc_perfetto_emit_heap_stats(void) { + if (!perfetto_start()) { + return; + } + gc_info_t info; + gc_info(&info); + perfetto_emit_counter(CIRCUITPY_PERFETTO_VM_HEAP_USED_UUID, (int64_t)info.used); + Z_SPIN_DELAY(1); +} + +static void gc_perfetto_emit_heap_stopped(void) { + if (!perfetto_start()) { + return; + } + perfetto_emit_counter(CIRCUITPY_PERFETTO_VM_HEAP_USED_UUID, 0); + Z_SPIN_DELAY(1); +} +#else +static inline void gc_perfetto_emit_heap_stats(void) { +} + +static inline void gc_perfetto_emit_heap_stopped(void) { +} +#endif + +// Static functions for individual steps of the GC mark/sweep sequence +static void gc_collect_start_common(void); +static void *gc_get_ptr(void **ptrs, int i); +#if MICROPY_GC_SPLIT_HEAP +static void gc_mark_subtree(mp_state_mem_area_t *area, size_t block); +#else +static void gc_mark_subtree(size_t block); +#endif +static void gc_deal_with_stack_overflow(void); +static void gc_sweep_run_finalisers(void); +static void gc_sweep_free_blocks(void); + // TODO waste less memory; currently requires that all entries in alloc_table have a corresponding block in pool static void gc_setup_area(mp_state_mem_area_t *area, void *start, void *end) { - // calculate parameters for GC (T=total, A=alloc table, F=finaliser table, P=pool; all in bytes): - // T = A + F + P + // CIRCUITPY-CHANGE: Updated calculation to include selective collect table + // calculate parameters for GC (T=total, A=alloc table, F=finaliser table, C=collect table, W=weakref table, P=pool; all in bytes): + // T = A + F + C + W + P // F = A * BLOCKS_PER_ATB / BLOCKS_PER_FTB + // C = A * BLOCKS_PER_ATB / BLOCKS_PER_CTB + // W = A * BLOCKS_PER_ATB / BLOCKS_PER_WTB // 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; + + // Calculate the denominator for the alloc table size calculation + size_t bits_per_block = MP_BITS_PER_BYTE / BLOCKS_PER_ATB; // Start with bits for ATB + #if MICROPY_ENABLE_FINALISER - area->gc_alloc_table_byte_len = (total_byte_len - ALLOC_TABLE_GAP_BYTE) - * MP_BITS_PER_BYTE - / ( - MP_BITS_PER_BYTE - + MP_BITS_PER_BYTE * BLOCKS_PER_ATB / BLOCKS_PER_FTB - + MP_BITS_PER_BYTE * BLOCKS_PER_ATB * BYTES_PER_BLOCK - ); - #else - area->gc_alloc_table_byte_len = (total_byte_len - ALLOC_TABLE_GAP_BYTE) / (1 + MP_BITS_PER_BYTE / 2 * BYTES_PER_BLOCK); + bits_per_block += MP_BITS_PER_BYTE / BLOCKS_PER_FTB; // Add bits for FTB #endif - area->gc_alloc_table_start = (byte *)start; + #if MICROPY_ENABLE_SELECTIVE_COLLECT + bits_per_block += MP_BITS_PER_BYTE / BLOCKS_PER_CTB; // Add bits for CTB + #endif - #if MICROPY_ENABLE_FINALISER - size_t gc_finaliser_table_byte_len = (area->gc_alloc_table_byte_len * BLOCKS_PER_ATB + BLOCKS_PER_FTB - 1) / BLOCKS_PER_FTB; - area->gc_finaliser_table_start = area->gc_alloc_table_start + area->gc_alloc_table_byte_len + ALLOC_TABLE_GAP_BYTE; + #if MICROPY_PY_WEAKREF + bits_per_block += MP_BITS_PER_BYTE / BLOCKS_PER_WTB; // Add bits for WTB #endif + bits_per_block += MP_BITS_PER_BYTE * BYTES_PER_BLOCK; // Add bits for the block itself + + // Calculate the allocation table size + size_t available_bits = (total_byte_len - ALLOC_TABLE_GAP_BYTE) * MP_BITS_PER_BYTE; + size_t blocks = available_bits / bits_per_block; + area->gc_alloc_table_byte_len = blocks / BLOCKS_PER_ATB; + + // Set up all the table pointers + area->gc_alloc_table_start = (byte *)start; + byte *next_table = area->gc_alloc_table_start + area->gc_alloc_table_byte_len + ALLOC_TABLE_GAP_BYTE; + + // Total number of blocks in the pool size_t gc_pool_block_len = area->gc_alloc_table_byte_len * BLOCKS_PER_ATB; - area->gc_pool_start = (byte *)end - gc_pool_block_len * BYTES_PER_BLOCK; - area->gc_pool_end = end; + // Calculate table sizes and set start pointers #if MICROPY_ENABLE_FINALISER - assert(area->gc_pool_start >= area->gc_finaliser_table_start + gc_finaliser_table_byte_len); + size_t gc_finaliser_table_byte_len = (gc_pool_block_len + BLOCKS_PER_FTB - 1) / BLOCKS_PER_FTB; + area->gc_finaliser_table_start = next_table; + next_table += gc_finaliser_table_byte_len; #endif - #if MICROPY_ENABLE_FINALISER - // clear ATB's and FTB's - memset(area->gc_alloc_table_start, 0, gc_finaliser_table_byte_len + area->gc_alloc_table_byte_len + ALLOC_TABLE_GAP_BYTE); - #else - // clear ATB's - memset(area->gc_alloc_table_start, 0, area->gc_alloc_table_byte_len + ALLOC_TABLE_GAP_BYTE); + #if MICROPY_ENABLE_SELECTIVE_COLLECT + size_t gc_collect_table_byte_len = (gc_pool_block_len + BLOCKS_PER_CTB - 1) / BLOCKS_PER_CTB; + area->gc_collect_table_start = next_table; + next_table += gc_collect_table_byte_len; + #endif + + #if MICROPY_PY_WEAKREF + size_t gc_weakref_table_byte_len = (gc_pool_block_len + BLOCKS_PER_WTB - 1) / BLOCKS_PER_WTB; + area->gc_weakref_table_start = next_table; + next_table += gc_weakref_table_byte_len; #endif + // Set pool pointers + area->gc_pool_start = (byte *)end - gc_pool_block_len * BYTES_PER_BLOCK; + area->gc_pool_end = end; + + // Verify enough space between last table and start of pool + assert(area->gc_pool_start >= next_table); + + // Clear all tables + size_t tables_size = next_table - area->gc_alloc_table_start; + memset(area->gc_alloc_table_start, 0, tables_size); + area->gc_last_free_atb_index = 0; area->gc_last_used_block = 0; #if MICROPY_GC_SPLIT_HEAP area->next = NULL; + + // Update the global min/max region that covers all heaps + MP_STATE_MEM(area_pool_min) = MIN(MP_STATE_MEM(area_pool_min), area->gc_pool_start); + MP_STATE_MEM(area_pool_max) = MAX(MP_STATE_MEM(area_pool_max), area->gc_pool_end); #endif DEBUG_printf("GC layout:\n"); @@ -204,6 +311,18 @@ static void gc_setup_area(mp_state_mem_area_t *area, void *start, void *end) { gc_finaliser_table_byte_len, gc_finaliser_table_byte_len * BLOCKS_PER_FTB); #endif + #if MICROPY_ENABLE_SELECTIVE_COLLECT + DEBUG_printf(" collect table at %p, length " UINT_FMT " bytes, " + UINT_FMT " blocks\n", area->gc_collect_table_start, + gc_collect_table_byte_len, + gc_collect_table_byte_len * BLOCKS_PER_CTB); + #endif + #if MICROPY_PY_WEAKREF + DEBUG_printf(" weakref table at %p, length " UINT_FMT " bytes, " + UINT_FMT " blocks\n", area->gc_weakref_table_start, + gc_weakref_table_byte_len, + gc_weakref_table_byte_len * BLOCKS_PER_WTB); + #endif DEBUG_printf(" pool at %p, length " UINT_FMT " bytes, " UINT_FMT " blocks\n", area->gc_pool_start, gc_pool_block_len * BYTES_PER_BLOCK, gc_pool_block_len); @@ -214,6 +333,13 @@ void gc_init(void *start, void *end) { 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); + #if MICROPY_GC_SPLIT_HEAP + // Note: min/max are deliberately swapped here, gc_setup_area() will update them to + // the correct values for the min/max of the first actual pool region + MP_STATE_MEM(area_pool_min) = end; + MP_STATE_MEM(area_pool_max) = start; + #endif + gc_setup_area(&MP_STATE_MEM(area), start, end); // set last free ATB index to start of heap @@ -233,9 +359,8 @@ void gc_init(void *start, void *end) { MP_STATE_MEM(gc_alloc_amount) = 0; #endif - #if MICROPY_PY_THREAD && !MICROPY_PY_THREAD_GIL - mp_thread_mutex_init(&MP_STATE_MEM(gc_mutex)); - #endif + GC_MUTEX_INIT(); + gc_perfetto_emit_heap_stats(); } #if MICROPY_GC_SPLIT_HEAP @@ -261,16 +386,51 @@ void gc_add(void *start, void *end) { } #if MICROPY_GC_SPLIT_HEAP_AUTO +// CIRCUITPY-CHANGE: Added function to compute heap size with selective collect table +static size_t compute_heap_size(size_t total_blocks) { + // Round up to the nearest multiple of BLOCKS_PER_ATB. Partial ATB blocks aren't supported and + // will result in a heap that is too small. + total_blocks = ((total_blocks + BLOCKS_PER_ATB - 1) / BLOCKS_PER_ATB) * BLOCKS_PER_ATB; + size_t atb_bytes = (total_blocks + BLOCKS_PER_ATB - 1) / BLOCKS_PER_ATB; + size_t ftb_bytes = 0; + size_t ctb_bytes = 0; + size_t wtb_bytes = 0; + #if MICROPY_ENABLE_FINALISER + ftb_bytes = (total_blocks + BLOCKS_PER_FTB - 1) / BLOCKS_PER_FTB; + #endif + #if MICROPY_ENABLE_SELECTIVE_COLLECT + ctb_bytes = (total_blocks + BLOCKS_PER_CTB - 1) / BLOCKS_PER_CTB; + #endif + #if MICROPY_PY_WEAKREF + wtb_bytes = (total_blocks + BLOCKS_PER_WTB - 1) / BLOCKS_PER_WTB; + #endif + size_t pool_bytes = total_blocks * BYTES_PER_BLOCK; + + // Compute bytes needed to build a heap with total_blocks blocks. + size_t total_heap = + sizeof(mp_state_mem_area_t) + + atb_bytes + + ALLOC_TABLE_GAP_BYTE + + ftb_bytes + + ctb_bytes + + wtb_bytes + + pool_bytes + + BYTES_PER_BLOCK; // Extra block of bytes to account for end pointer alignment + + // Round up size to the nearest multiple of BYTES_PER_BLOCK. + total_heap = (total_heap + BYTES_PER_BLOCK - 1) / BYTES_PER_BLOCK; + total_heap *= BYTES_PER_BLOCK; + return total_heap; +} + // Try to automatically add a heap area large enough to fulfill 'failed_alloc'. static bool gc_try_add_heap(size_t failed_alloc) { // 'needed' is the size of a heap large enough to hold failed_alloc, with // the additional metadata overheads as calculated in gc_setup_area(). - // - // Rather than reproduce all of that logic here, we approximate that adding - // (13/512) is enough overhead for sufficiently large heap areas (the - // overhead converges to 3/128, but there's some fixed overhead and some - // rounding up of partial block sizes). - size_t needed = failed_alloc + MAX(2048, failed_alloc * 13 / 512); + // CIRCUITPY-CHANGE: calculation of how much to grow the heap + size_t total_new_blocks = (failed_alloc + BYTES_PER_BLOCK - 1) / BYTES_PER_BLOCK; + // CIRCUITPY-CHANGE + size_t needed = compute_heap_size(total_new_blocks); size_t avail = gc_get_max_new_split(); @@ -314,18 +474,8 @@ static bool gc_try_add_heap(size_t failed_alloc) { total_blocks += area->gc_alloc_table_byte_len * BLOCKS_PER_ATB; } - // Compute bytes needed to build a heap with total_blocks blocks. - size_t total_heap = - total_blocks / BLOCKS_PER_ATB - #if MICROPY_ENABLE_FINALISER - + total_blocks / BLOCKS_PER_FTB - #endif - + total_blocks * BYTES_PER_BLOCK - + ALLOC_TABLE_GAP_BYTE - + sizeof(mp_state_mem_area_t); - - // Round up size to the nearest multiple of BYTES_PER_BLOCK. - total_heap = (total_heap + BYTES_PER_BLOCK - 1) & (~(BYTES_PER_BLOCK - 1)); + // CIRCUITPY-CHANGE + size_t total_heap = compute_heap_size(total_blocks); DEBUG_printf("total_heap " UINT_FMT " bytes\n", total_heap); @@ -336,15 +486,28 @@ static bool gc_try_add_heap(size_t failed_alloc) { DEBUG_printf("MP_PLAT_ALLOC_HEAP " UINT_FMT " = %p\n", to_alloc, new_heap); + // CIRCUITPY-CHANGE: retry with smaller sizes, down to the size this + // allocation needs. + // + // Upstream gives up as soon as the first MP_PLAT_ALLOC_HEAP() fails, on the + // assumption that it only fails if another thread allocated meanwhile or + // gc_get_max_new_split() has a bug. But gc_get_max_new_split() can also + // overestimate the largest free block, for example when it reports the + // total free bytes of a fragmented system heap. A smaller area may then + // still fit, so halve the request until it does or it reaches 'needed'. + while (new_heap == NULL && to_alloc > needed) { + to_alloc = MAX(needed, to_alloc / 2); + new_heap = MP_PLAT_ALLOC_HEAP(to_alloc); + DEBUG_printf("MP_PLAT_ALLOC_HEAP retry " UINT_FMT " = %p\n", + to_alloc, new_heap); + } + + // CIRCUITPY-CHANGE: comment moved to above. if (new_heap == NULL) { - // This should only fail: - // - In a threaded environment if another thread has - // allocated while this function ran. - // - If there is a bug in gc_get_max_new_split(). return false; } - gc_add(new_heap, (void *)new_heap + to_alloc); + gc_add(new_heap, (byte *)new_heap + to_alloc); return true; } @@ -352,11 +515,12 @@ static bool gc_try_add_heap(size_t failed_alloc) { #endif -// CIRCUITPY-CHANGE +// CIRCUITPY-CHANGE: additional function void gc_deinit(void) { // Run any finalisers before we stop using the heap. This will also free // any additional heap areas (but not the first.) gc_sweep_all(); + gc_perfetto_emit_heap_stopped(); memset(&MP_STATE_MEM(area), 0, sizeof(MP_STATE_MEM(area))); } @@ -365,20 +529,23 @@ void gc_lock(void) { // - each thread has its own gc_lock_depth so there are no races between threads; // - a hard interrupt will only change gc_lock_depth during its execution, and // upon return will restore the value of gc_lock_depth. - MP_STATE_THREAD(gc_lock_depth)++; + MP_STATE_THREAD(gc_lock_depth) += (1 << GC_LOCK_DEPTH_SHIFT); } void gc_unlock(void) { // This does not need to be atomic, See comment above in gc_lock. - MP_STATE_THREAD(gc_lock_depth)--; + MP_STATE_THREAD(gc_lock_depth) -= (1 << GC_LOCK_DEPTH_SHIFT); } bool gc_is_locked(void) { return MP_STATE_THREAD(gc_lock_depth) != 0; } -// CIRCUITPY-CHANGE -bool gc_ptr_on_heap(void *ptr) { +// CIRCUITPY-CHANGE: additional function +// In ITCM (RAM, on chips that have it) because background_callback_add_core() can call +// this from an interrupt that fires during a flash write. Code in flash can't run during +// a flash write. +bool PLACE_IN_ITCM(gc_ptr_on_heap)(const void *ptr) { for (mp_state_mem_area_t *area = &MP_STATE_MEM(area); area != NULL; area = NEXT_AREA(area)) { if (ptr >= (void *)area->gc_pool_start // must be above start of pool && ptr < (void *)area->gc_pool_end) { // must be below end of pool @@ -389,12 +556,24 @@ bool gc_ptr_on_heap(void *ptr) { } #if MICROPY_GC_SPLIT_HEAP -// Returns the area to which this pointer belongs, or NULL if it isn't -// allocated on the GC-managed heap. -static inline mp_state_mem_area_t *gc_get_ptr_area(const void *ptr) { - if (((uintptr_t)(ptr) & (BYTES_PER_BLOCK - 1)) != 0) { // must be aligned on a block - return NULL; +static mp_state_mem_area_t *gc_get_ptr_area(const void *ptr); + +// Returns the area to which this arbitrary pointer belongs, or NULL if it isn't +// allocated on the GC-managed heap. Contains "fast path" inline checks for invalid +// data which isn't a pointer to the heap. Equivalent of VERIFY_PTR for the non-split-heap case. +static inline MP_ALWAYSINLINE mp_state_mem_area_t *gc_verify_ptr_get_area(const void *ptr) { + // These inline checks are similar to VERIFY_PTR macro, below + if ((byte *)ptr < MP_STATE_MEM(area_pool_min) || (byte *)ptr > MP_STATE_MEM(area_pool_max)) { + return NULL; // not in the overall pool region + } + if (((uintptr_t)(ptr) & (BYTES_PER_BLOCK - 1)) != 0) { + return NULL; // not aligned on a block boundary } + return gc_get_ptr_area(ptr); +} + +// Returns the area to which a pointer belongs. Assumes pointer is valid to a heap block. +static mp_state_mem_area_t *gc_get_ptr_area(const void *ptr) { for (mp_state_mem_area_t *area = &MP_STATE_MEM(area); area != NULL; area = NEXT_AREA(area)) { if (ptr >= (void *)area->gc_pool_start // must be above start of pool && ptr < (void *)area->gc_pool_end) { // must be below end of pool @@ -403,7 +582,7 @@ static inline mp_state_mem_area_t *gc_get_ptr_area(const void *ptr) { } return NULL; } -#endif +#else // ptr should be of type void* #define VERIFY_PTR(ptr) ( \ @@ -412,19 +591,92 @@ static inline mp_state_mem_area_t *gc_get_ptr_area(const void *ptr) { && ptr < (void *)MP_STATE_MEM(area).gc_pool_end /* must be below end of pool */ \ ) -#ifndef TRACE_MARK +#endif + +#ifdef TRACE_MARK +#error "TRACE_MARK is replaced by TRACE_MARK_R and TRACE_MARK_S" +#endif +// R for root pointer, S for subtree. +#ifndef TRACE_MARK_R +#if DEBUG_PRINT +#define TRACE_MARK_R(block, ptr) DEBUG_printf("gc_mark_r(%p)\n", ptr) +#else +#define TRACE_MARK_R(block, ptr) +#endif +#endif +#ifndef TRACE_MARK_S #if DEBUG_PRINT -#define TRACE_MARK(block, ptr) DEBUG_printf("gc_mark(%p)\n", ptr) +#define TRACE_MARK_S(block, ptr) DEBUG_printf("gc_mark_s(%p)\n", ptr) #else -#define TRACE_MARK(block, ptr) +#define TRACE_MARK_S(block, ptr) #endif #endif +void gc_collect_start(void) { + gc_collect_start_common(); + #if MICROPY_GC_ALLOC_THRESHOLD + MP_STATE_MEM(gc_alloc_amount) = 0; + #endif + + // 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; + 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 *)); + + #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 *)); + #endif +} + +static void gc_collect_start_common(void) { + GC_ENTER(); + assert((MP_STATE_THREAD(gc_lock_depth) & GC_COLLECT_FLAG) == 0); + MP_STATE_THREAD(gc_lock_depth) |= GC_COLLECT_FLAG; + MP_STATE_MEM(gc_stack_overflow) = 0; +} + +void gc_collect_root(void **ptrs, size_t len) { + #if !MICROPY_GC_SPLIT_HEAP + mp_state_mem_area_t *area = &MP_STATE_MEM(area); + #endif + for (size_t i = 0; i < len; i++) { + MICROPY_GC_HOOK_LOOP(i); + void *ptr = gc_get_ptr(ptrs, i); + #if MICROPY_GC_SPLIT_HEAP + mp_state_mem_area_t *area = gc_verify_ptr_get_area(ptr); + if (!area) { + continue; + } + #else + if (!VERIFY_PTR(ptr)) { + continue; + } + #endif + size_t block = BLOCK_FROM_PTR(area, ptr); + if (ATB_GET_KIND(area, block) == AT_HEAD) { + // An unmarked head: mark it, and mark all its children + TRACE_MARK_R(block, ptr); + ATB_HEAD_TO_MARK(area, block); + #if MICROPY_GC_SPLIT_HEAP + gc_mark_subtree(area, block); + #else + gc_mark_subtree(block); + #endif + } + } +} + // Take the given block as the topmost block on the stack. Check all it's // children: mark the unmarked child blocks and put those newly marked // blocks on the stack. When all children have been checked, pop off the // topmost block on the stack and repeat with that one. // CIRCUITPY-CHANGE: We don't instrument these functions because they occur a lot during GC and +// fill up the output buffer quickly. #if MICROPY_GC_SPLIT_HEAP static void MP_NO_INSTRUMENT PLACE_IN_ITCM(gc_mark_subtree)(mp_state_mem_area_t * area, size_t block) #else @@ -447,41 +699,52 @@ static void MP_NO_INSTRUMENT PLACE_IN_ITCM(gc_mark_subtree)(size_t block) // check that the consecutive blocks didn't overflow past the end of the area assert(area->gc_pool_start + (block + n_blocks) * BYTES_PER_BLOCK <= area->gc_pool_end); - // check this block's children - void **ptrs = (void **)PTR_FROM_BLOCK(area, block); - for (size_t i = n_blocks * BYTES_PER_BLOCK / sizeof(void *); i > 0; i--, ptrs++) { - MICROPY_GC_HOOK_LOOP(i); - void *ptr = *ptrs; - // If this is a heap pointer that hasn't been marked, mark it and push - // it's children to the stack. - #if MICROPY_GC_SPLIT_HEAP - mp_state_mem_area_t *ptr_area = gc_get_ptr_area(ptr); - if (!ptr_area) { - // Not a heap-allocated pointer (might even be random data). - continue; - } - #else - if (!VERIFY_PTR(ptr)) { - continue; - } - mp_state_mem_area_t *ptr_area = area; - #endif - size_t ptr_block = BLOCK_FROM_PTR(ptr_area, ptr); - if (ATB_GET_KIND(ptr_area, ptr_block) != AT_HEAD) { - // This block is already marked. - continue; - } - // An unmarked head. Mark it, and push it on gc stack. - TRACE_MARK(ptr_block, ptr); - ATB_HEAD_TO_MARK(ptr_area, ptr_block); - if (sp < MICROPY_ALLOC_GC_STACK_SIZE) { - MP_STATE_MEM(gc_block_stack)[sp] = ptr_block; + // CIRCUITPY-CHANGE + // check if this block should be collected + #if MICROPY_ENABLE_SELECTIVE_COLLECT + bool should_scan = CTB_GET(area, block); + #else + bool should_scan = true; + #endif + + // Only scan the block's children if it's not a leaf + if (should_scan) { + // check this block's children + void **ptrs = (void **)PTR_FROM_BLOCK(area, block); + for (size_t i = n_blocks * BYTES_PER_BLOCK / sizeof(void *); i > 0; i--, ptrs++) { + MICROPY_GC_HOOK_LOOP(i); + void *ptr = *ptrs; + // If this is a heap pointer that hasn't been marked, mark it and push + // it's children to the stack. #if MICROPY_GC_SPLIT_HEAP - MP_STATE_MEM(gc_area_stack)[sp] = ptr_area; + mp_state_mem_area_t *ptr_area = gc_verify_ptr_get_area(ptr); + if (!ptr_area) { + // Not a heap-allocated pointer (might even be random data). + continue; + } + #else + if (!VERIFY_PTR(ptr)) { + continue; + } + mp_state_mem_area_t *ptr_area = area; #endif - sp += 1; - } else { - MP_STATE_MEM(gc_stack_overflow) = 1; + size_t ptr_block = BLOCK_FROM_PTR(ptr_area, ptr); + if (ATB_GET_KIND(ptr_area, ptr_block) != AT_HEAD) { + // This block is already marked. + continue; + } + // An unmarked head. Mark it, and push it on gc stack. + TRACE_MARK_S(ptr_block, ptr); + ATB_HEAD_TO_MARK(ptr_area, ptr_block); + if (sp < MICROPY_ALLOC_GC_STACK_SIZE) { + MP_STATE_MEM(gc_block_stack)[sp] = ptr_block; + #if MICROPY_GC_SPLIT_HEAP + MP_STATE_MEM(gc_area_stack)[sp] = ptr_area; + #endif + sp += 1; + } else { + MP_STATE_MEM(gc_stack_overflow) = 1; + } } } @@ -499,6 +762,29 @@ static void MP_NO_INSTRUMENT PLACE_IN_ITCM(gc_mark_subtree)(size_t block) } } +void gc_sweep_all(void) { + gc_collect_start_common(); + gc_collect_end(); +} + +void gc_collect_end(void) { + gc_deal_with_stack_overflow(); + gc_sweep_run_finalisers(); + gc_sweep_free_blocks(); + #if MICROPY_GC_SPLIT_HEAP + MP_STATE_MEM(gc_last_free_area) = &MP_STATE_MEM(area); + #endif + for (mp_state_mem_area_t *area = &MP_STATE_MEM(area); area != NULL; area = NEXT_AREA(area)) { + area->gc_last_free_atb_index = 0; + } + MP_STATE_THREAD(gc_lock_depth) &= ~GC_COLLECT_FLAG; + GC_EXIT(); + #if MICROPY_PY_WEAKREF + gc_weakref_sweep(); + #endif + gc_perfetto_emit_heap_stats(); +} + static void gc_deal_with_stack_overflow(void) { while (MP_STATE_MEM(gc_stack_overflow)) { MP_STATE_MEM(gc_stack_overflow) = 0; @@ -520,29 +806,24 @@ static void gc_deal_with_stack_overflow(void) { } } -static void gc_sweep(void) { - #if MICROPY_PY_GC_COLLECT_RETVAL - MP_STATE_MEM(gc_collected) = 0; - #endif - // free unmarked heads and their tails - int free_tail = 0; - #if MICROPY_GC_SPLIT_HEAP_AUTO - mp_state_mem_area_t *prev_area = NULL; +// Run finalisers for all to-be-freed blocks +static void gc_sweep_run_finalisers(void) { + #if MICROPY_ENABLE_FINALISER || MICROPY_PY_WEAKREF + #if MICROPY_ENABLE_FINALISER && MICROPY_PY_WEAKREF + MP_STATIC_ASSERT(BLOCKS_PER_FTB == BLOCKS_PER_WTB); #endif - for (mp_state_mem_area_t *area = &MP_STATE_MEM(area); area != NULL; area = NEXT_AREA(area)) { - size_t end_block = area->gc_alloc_table_byte_len * BLOCKS_PER_ATB; - if (area->gc_last_used_block < end_block) { - end_block = area->gc_last_used_block + 1; - } - - size_t last_used_block = 0; - - for (size_t block = 0; block < end_block; block++) { - MICROPY_GC_HOOK_LOOP(block); - switch (ATB_GET_KIND(area, block)) { - case AT_HEAD: - #if MICROPY_ENABLE_FINALISER - if (FTB_GET(area, block)) { + for (const mp_state_mem_area_t *area = &MP_STATE_MEM(area); area != NULL; area = NEXT_AREA(area)) { + assert(area->gc_last_used_block <= area->gc_alloc_table_byte_len * BLOCKS_PER_ATB); + // Small speed optimisation: skip over empty FTB blocks + size_t ftb_end = area->gc_last_used_block / BLOCKS_PER_FTB; // index is inclusive + for (size_t ftb_idx = 0; ftb_idx <= ftb_end; ftb_idx++) { + #if MICROPY_ENABLE_FINALISER + byte ftb = area->gc_finaliser_table_start[ftb_idx]; + size_t block = ftb_idx * BLOCKS_PER_FTB; + while (ftb) { + MICROPY_GC_HOOK_LOOP(block); + if (ftb & 1) { // FTB_GET(area, block) shortcut + if (ATB_GET_KIND(area, block) == AT_HEAD) { mp_obj_base_t *obj = (mp_obj_base_t *)PTR_FROM_BLOCK(area, block); if (obj->type != NULL) { // if the object has a type then see if it has a __del__ method @@ -562,9 +843,54 @@ static void gc_sweep(void) { // clear finaliser flag FTB_CLEAR(area, block); } - #endif + } + ftb >>= 1; + block++; + } + #endif + #if MICROPY_PY_WEAKREF + byte wtb = area->gc_weakref_table_start[ftb_idx]; + block = ftb_idx * BLOCKS_PER_WTB; + while (wtb) { + MICROPY_GC_HOOK_LOOP(block); + if (wtb & 1) { // WTB_GET(area, block) shortcut + if (ATB_GET_KIND(area, block) == AT_HEAD) { + mp_obj_base_t *obj = (mp_obj_base_t *)PTR_FROM_BLOCK(area, block); + gc_weakref_about_to_be_freed(obj); + WTB_CLEAR(area, block); + } + } + wtb >>= 1; + block++; + } + #endif + } + } + #endif // MICROPY_ENABLE_FINALISER || MICROPY_PY_WEAKREF +} + +// Free unmarked heads and their tails +static void gc_sweep_free_blocks(void) { + #if MICROPY_PY_GC_COLLECT_RETVAL + MP_STATE_MEM(gc_collected) = 0; + #endif + int free_tail = 0; + #if MICROPY_GC_SPLIT_HEAP_AUTO + mp_state_mem_area_t *prev_area = NULL; + #endif + + for (mp_state_mem_area_t *area = &MP_STATE_MEM(area); area != NULL; area = NEXT_AREA(area)) { + size_t last_used_block = 0; + // CIRCUITPY-CHANGE: last_used_block is also 0 when only the first block is in use + bool any_used = false; + assert(area->gc_last_used_block <= area->gc_alloc_table_byte_len * BLOCKS_PER_ATB); + + for (size_t block = 0; block <= area->gc_last_used_block; block++) { + MICROPY_GC_HOOK_LOOP(block); + switch (ATB_GET_KIND(area, block)) { + case AT_HEAD: free_tail = 1; - DEBUG_printf("gc_sweep(%p)\n", (void *)PTR_FROM_BLOCK(area, block)); + DEBUG_printf("gc_sweep_free_blocks(%p)\n", (void *)PTR_FROM_BLOCK(area, block)); #if MICROPY_PY_GC_COLLECT_RETVAL MP_STATE_MEM(gc_collected)++; #endif @@ -579,6 +905,7 @@ static void gc_sweep(void) { #endif } else { last_used_block = block; + any_used = true; } break; @@ -586,6 +913,7 @@ static void gc_sweep(void) { ATB_MARK_TO_HEAD(area, block); free_tail = 0; last_used_block = block; + any_used = true; break; } } @@ -594,41 +922,20 @@ static void gc_sweep(void) { #if MICROPY_GC_SPLIT_HEAP_AUTO // Free any empty area, aside from the first one - if (last_used_block == 0 && prev_area != NULL) { - DEBUG_printf("gc_sweep free empty area %p\n", area); + if (!any_used && prev_area != NULL) { + DEBUG_printf("gc_sweep_free_blocks free empty area %p\n", area); NEXT_AREA(prev_area) = NEXT_AREA(area); MP_PLAT_FREE_HEAP(area); area = prev_area; } prev_area = area; + #else + (void)any_used; #endif } } -void gc_collect_start(void) { - GC_ENTER(); - MP_STATE_THREAD(gc_lock_depth)++; - #if MICROPY_GC_ALLOC_THRESHOLD - MP_STATE_MEM(gc_alloc_amount) = 0; - #endif - MP_STATE_MEM(gc_stack_overflow) = 0; - - // 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; - 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 *)); - - #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 *)); - #endif -} - -// CIRCUITPY-CHANGE +// CIRCUITPY-CHANGE: add function void gc_collect_ptr(void *ptr) { void *ptrs[1] = { ptr }; gc_collect_root(ptrs, 1); @@ -650,56 +957,6 @@ static void *MP_NO_INSTRUMENT PLACE_IN_ITCM(gc_get_ptr)(void **ptrs, int i) { return ptrs[i]; } -void gc_collect_root(void **ptrs, size_t len) { - #if !MICROPY_GC_SPLIT_HEAP - mp_state_mem_area_t *area = &MP_STATE_MEM(area); - #endif - for (size_t i = 0; i < len; i++) { - MICROPY_GC_HOOK_LOOP(i); - void *ptr = gc_get_ptr(ptrs, i); - #if MICROPY_GC_SPLIT_HEAP - mp_state_mem_area_t *area = gc_get_ptr_area(ptr); - if (!area) { - continue; - } - #else - if (!VERIFY_PTR(ptr)) { - continue; - } - #endif - size_t block = BLOCK_FROM_PTR(area, ptr); - if (ATB_GET_KIND(area, block) == AT_HEAD) { - // An unmarked head: mark it, and mark all its children - ATB_HEAD_TO_MARK(area, block); - #if MICROPY_GC_SPLIT_HEAP - gc_mark_subtree(area, block); - #else - gc_mark_subtree(block); - #endif - } - } -} - -void gc_collect_end(void) { - gc_deal_with_stack_overflow(); - gc_sweep(); - #if MICROPY_GC_SPLIT_HEAP - MP_STATE_MEM(gc_last_free_area) = &MP_STATE_MEM(area); - #endif - for (mp_state_mem_area_t *area = &MP_STATE_MEM(area); area != NULL; area = NEXT_AREA(area)) { - area->gc_last_free_atb_index = 0; - } - MP_STATE_THREAD(gc_lock_depth)--; - GC_EXIT(); -} - -void gc_sweep_all(void) { - GC_ENTER(); - MP_STATE_THREAD(gc_lock_depth)++; - MP_STATE_MEM(gc_stack_overflow) = 0; - gc_collect_end(); -} - void gc_info(gc_info_t *info) { GC_ENTER(); info->total = 0; @@ -773,7 +1030,46 @@ void gc_info(gc_info_t *info) { GC_EXIT(); } -// CIRCUITPY-CHANGE: C code may be used when the VM heap isn't active. This +// Fast version of gc_info that only computes total/used/free. +void gc_info_fast(gc_info_t *info) { + GC_ENTER(); + memset(info, 0, sizeof(*info)); + const uint8_t lut[16] = {2, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0}; + for (mp_state_mem_area_t *area = &MP_STATE_MEM(area); area != NULL; area = NEXT_AREA(area)) { + size_t free_blocks = 0; + info->total += area->gc_pool_end - area->gc_pool_start; + for (size_t i = 0; i < area->gc_alloc_table_byte_len; i++) { + uint8_t atb = area->gc_alloc_table_start[i]; + free_blocks += lut[atb & 0xF] + lut[atb >> 4]; + } + info->free += free_blocks; + } + info->free *= BYTES_PER_BLOCK; + info->used = info->total - info->free; + GC_EXIT(); +} + +#if MICROPY_PY_WEAKREF +// Mark the GC heap pointer as having a weakref. +void gc_weakref_mark(void *ptr) { + mp_state_mem_area_t *area; + #if MICROPY_GC_SPLIT_HEAP + area = gc_get_ptr_area(ptr); + assert(area); + #else + assert(VERIFY_PTR(ptr)); + area = &MP_STATE_MEM(area); + #endif + + size_t block = BLOCK_FROM_PTR(area, ptr); + assert(ATB_GET_KIND(area, block) == AT_HEAD); + + WTB_SET(area, block); +} +#endif + +// CIRCUITPY-CHANGE: New function. +// C code may be used when the VM heap isn't active. This function // allows that code to test if it is. It can use the outer pool if needed. bool gc_alloc_possible(void) { return MP_STATE_MEM(area).gc_pool_start != 0; @@ -944,6 +1240,20 @@ void *gc_alloc(size_t n_bytes, unsigned int alloc_flags) { (void)has_finaliser; #endif + // CIRCUITPY-CHANGE + #if MICROPY_ENABLE_SELECTIVE_COLLECT + bool do_not_collect = (alloc_flags & GC_ALLOC_FLAG_DO_NOT_COLLECT) != 0; + GC_ENTER(); + if (do_not_collect) { + // Mark as not to be collected + CTB_CLEAR(area, start_block); + } else { + // By default, all blocks should be collected + CTB_SET(area, start_block); + } + GC_EXIT(); + #endif + #if EXTENSIVE_HEAP_PROFILING gc_dump_alloc_table(&mp_plat_print); #endif @@ -953,26 +1263,21 @@ void *gc_alloc(size_t n_bytes, unsigned int alloc_flags) { memorymonitor_track_allocation(end_block - start_block + 1); #endif - return ret_ptr; -} - -/* -void *gc_alloc(mp_uint_t n_bytes) { - return _gc_alloc(n_bytes, false); -} + gc_perfetto_emit_heap_stats(); -void *gc_alloc_with_finaliser(mp_uint_t n_bytes) { - return _gc_alloc(n_bytes, true); + return ret_ptr; } -*/ // force the freeing of a piece of memory // TODO: freeing here does not call finaliser void gc_free(void *ptr) { - if (MP_STATE_THREAD(gc_lock_depth) > 0) { - // Cannot free while the GC is locked. However free is an optimisation - // to reclaim the memory immediately, this means it will now be left - // until the next collection. + // Cannot free while the GC is locked, unless we're only doing a gc sweep. + // However free is an optimisation to reclaim the memory immediately, this + // means it will now be left until the next collection. + // + // (We have the optimisation to free immediately from inside a gc sweep so + // that finalisers can free more memory when trying to avoid MemoryError.) + if (MP_STATE_THREAD(gc_lock_depth) & ~GC_COLLECT_FLAG) { return; } @@ -1002,12 +1307,18 @@ void gc_free(void *ptr) { #endif size_t block = BLOCK_FROM_PTR(area, ptr); - assert(ATB_GET_KIND(area, block) == AT_HEAD); + assert(ATB_GET_KIND(area, block) == AT_HEAD + || (ATB_GET_KIND(area, block) == AT_MARK && (MP_STATE_THREAD(gc_lock_depth) & GC_COLLECT_FLAG))); #if MICROPY_ENABLE_FINALISER FTB_CLEAR(area, block); #endif + #if MICROPY_PY_WEAKREF + // Objects that have a weak reference should not be explicitly freed. + assert(!WTB_GET(area, block)); + #endif + #if MICROPY_GC_SPLIT_HEAP if (MP_STATE_MEM(gc_last_free_area) != area) { // We freed something but it isn't the current area. Reset the @@ -1040,6 +1351,7 @@ void gc_free(void *ptr) { } while (ATB_GET_KIND(area, block) == AT_TAIL); GC_EXIT(); + gc_perfetto_emit_heap_stats(); #if EXTENSIVE_HEAP_PROFILING gc_dump_alloc_table(&mp_plat_print); @@ -1078,39 +1390,11 @@ size_t gc_nbytes(const void *ptr) { return 0; } -#if 0 -// old, simple realloc that didn't expand memory in place -void *gc_realloc(void *ptr, mp_uint_t n_bytes) { - mp_uint_t n_existing = gc_nbytes(ptr); - if (n_bytes <= n_existing) { - return ptr; - } else { - bool has_finaliser; - if (ptr == NULL) { - has_finaliser = false; - } else { - #if MICROPY_ENABLE_FINALISER - has_finaliser = FTB_GET(BLOCK_FROM_PTR((mp_uint_t)ptr)); - #else - has_finaliser = false; - #endif - } - void *ptr2 = gc_alloc(n_bytes, has_finaliser); - if (ptr2 == NULL) { - return ptr2; - } - memcpy(ptr2, ptr, n_existing); - gc_free(ptr); - return ptr2; - } -} - -#else // Alternative gc_realloc impl - void *gc_realloc(void *ptr_in, size_t n_bytes, bool allow_move) { // check for pure allocation if (ptr_in == NULL) { - return gc_alloc(n_bytes, false); + // CIRCUITPY-CHANGE + return gc_alloc(n_bytes, 0); } // check for pure free @@ -1208,6 +1492,8 @@ void *gc_realloc(void *ptr_in, size_t n_bytes, bool allow_move) { memorymonitor_track_allocation(new_blocks); #endif + gc_perfetto_emit_heap_stats(); + return ptr_in; } @@ -1245,13 +1531,24 @@ void *gc_realloc(void *ptr_in, size_t n_bytes, bool allow_move) { memorymonitor_track_allocation(new_blocks); #endif + gc_perfetto_emit_heap_stats(); + return ptr_in; } + uint8_t alloc_flags = 0; #if MICROPY_ENABLE_FINALISER - bool ftb_state = FTB_GET(area, block); - #else - bool ftb_state = false; + // CIRCUITPY-CHANGE for selective collect + if (FTB_GET(area, block)) { + alloc_flags |= GC_ALLOC_FLAG_HAS_FINALISER; + } + #endif + + // CIRCUITPY-CHANGE for selective collect + #if MICROPY_ENABLE_SELECTIVE_COLLECT + if (!CTB_GET(area, block)) { + alloc_flags |= GC_ALLOC_FLAG_DO_NOT_COLLECT; + } #endif GC_EXIT(); @@ -1262,7 +1559,8 @@ void *gc_realloc(void *ptr_in, size_t n_bytes, bool allow_move) { } // can't resize inplace; try to find a new contiguous chain - void *ptr_out = gc_alloc(n_bytes, ftb_state); + // CIRCUITPY-CHANGE + void *ptr_out = gc_alloc(n_bytes, alloc_flags); // check that the alloc succeeded if (ptr_out == NULL) { @@ -1274,7 +1572,6 @@ void *gc_realloc(void *ptr_in, size_t n_bytes, bool allow_move) { gc_free(ptr_in); return ptr_out; } -#endif // Alternative gc_realloc impl void gc_dump_info(const mp_print_t *print) { gc_info_t info; @@ -1308,7 +1605,7 @@ void gc_dump_alloc_table(const mp_print_t *print) { } if (bl2 - bl >= 2 * DUMP_BYTES_PER_LINE) { // there are at least 2 lines containing only free blocks, so abbreviate their printing - mp_printf(print, "\n (%u lines all free)", (uint)(bl2 - bl) / DUMP_BYTES_PER_LINE); + mp_printf(print, "\n (%u lines all free)", (uint)((bl2 - bl) / DUMP_BYTES_PER_LINE)); bl = bl2 & (~(DUMP_BYTES_PER_LINE - 1)); if (bl >= area->gc_alloc_table_byte_len * BLOCKS_PER_ATB) { // got to end of heap @@ -1351,7 +1648,7 @@ void gc_dump_alloc_table(const mp_print_t *print) { break; } */ - /* this prints the uPy object type of the head block */ + /* this prints the MicroPython object type of the head block */ case AT_HEAD: { // CIRCUITPY-CHANGE: compiler warning avoidance #pragma GCC diagnostic push @@ -1422,41 +1719,4 @@ void gc_dump_alloc_table(const mp_print_t *print) { GC_EXIT(); } -#if 0 -// For testing the GC functions -void gc_test(void) { - mp_uint_t len = 500; - mp_uint_t *heap = malloc(len); - gc_init(heap, heap + len / sizeof(mp_uint_t)); - void *ptrs[100]; - { - mp_uint_t **p = gc_alloc(16, false); - p[0] = gc_alloc(64, false); - p[1] = gc_alloc(1, false); - p[2] = gc_alloc(1, false); - p[3] = gc_alloc(1, false); - mp_uint_t ***p2 = gc_alloc(16, false); - p2[0] = p; - p2[1] = p; - ptrs[0] = p2; - } - 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; - } - } - - printf("Before GC:\n"); - gc_dump_alloc_table(&mp_plat_print); - printf("Starting GC...\n"); - gc_collect_start(); - gc_collect_root(ptrs, sizeof(ptrs) / sizeof(void *)); - gc_collect_end(); - printf("After GC:\n"); - gc_dump_alloc_table(&mp_plat_print); -} -#endif - #endif // MICROPY_ENABLE_GC diff --git a/py/gc.h b/py/gc.h index 5f4b18f7e64..0f693d49222 100644 --- a/py/gc.h +++ b/py/gc.h @@ -71,8 +71,17 @@ bool gc_alloc_possible(void); // Use this function to sweep the whole heap and run all finalisers void gc_sweep_all(void); +// These functions are used to manage weakrefs. +void gc_weakref_mark(void *ptr); +void gc_weakref_about_to_be_freed(void *ptr); +void gc_weakref_sweep(void); + enum { GC_ALLOC_FLAG_HAS_FINALISER = 1, + // CIRCUITPY-CHANGE + #if MICROPY_ENABLE_SELECTIVE_COLLECT + GC_ALLOC_FLAG_DO_NOT_COLLECT = 2, + #endif }; void *gc_alloc(size_t n_bytes, unsigned int alloc_flags); @@ -83,7 +92,7 @@ void *gc_realloc(void *ptr, size_t n_bytes, bool allow_move); // CIRCUITPY-CHANGE // True if the pointer is on the MP heap. Doesn't require that it is the start // of a block. -bool gc_ptr_on_heap(void *ptr); +bool gc_ptr_on_heap(const void *ptr); typedef struct _gc_info_t { size_t total; @@ -99,6 +108,7 @@ typedef struct _gc_info_t { } gc_info_t; void gc_info(gc_info_t *info); +void gc_info_fast(gc_info_t *info); void gc_dump_info(const mp_print_t *print); void gc_dump_alloc_table(const mp_print_t *print); diff --git a/py/lexer.c b/py/lexer.c index bff8e637656..22ff4d2cd3a 100644 --- a/py/lexer.c +++ b/py/lexer.c @@ -35,11 +35,8 @@ #if MICROPY_ENABLE_COMPILER #define TAB_SIZE (8) - -// TODO seems that CPython allows NULL byte in the input stream -// don't know if that's intentional or not, but we don't allow it - -#define MP_LEXER_EOF ((unichar)MP_READER_EOF) +#define MP_LEXER_EOF ('\0') +#define MP_LEXER_INVALID_BYTE ('\1') #define CUR_CHAR(lex) ((lex)->chr0) static bool is_end(mp_lexer_t *lex) { @@ -62,7 +59,11 @@ static bool is_char_or3(mp_lexer_t *lex, byte c1, byte c2, byte c3) { return lex->chr0 == c1 || lex->chr0 == c2 || lex->chr0 == c3; } -#if MICROPY_PY_FSTRINGS +#if MICROPY_PY_TSTRINGS +static bool is_char_or5(mp_lexer_t *lex, byte c1, byte c2, byte c3, byte c4, byte c5) { + return lex->chr0 == c1 || lex->chr0 == c2 || lex->chr0 == c3 || lex->chr0 == c4 || lex->chr0 == c5; +} +#elif MICROPY_PY_FSTRINGS static bool is_char_or4(mp_lexer_t *lex, byte c1, byte c2, byte c3, byte c4) { return lex->chr0 == c1 || lex->chr0 == c2 || lex->chr0 == c3 || lex->chr0 == c4; } @@ -111,7 +112,11 @@ 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_PY_FSTRINGS + #if MICROPY_PY_TSTRINGS + || (is_char_or5(lex, 'r', 'u', 'b', 'f', 't') && is_char_following_or(lex, '\'', '\"')) + || (((is_char_and(lex, 'r', 'f') || is_char_and(lex, 'f', 'r') || is_char_and(lex, 'r', 't') || is_char_and(lex, 't', 'r')) + && is_char_following_following_or(lex, '\'', '\"'))) + #elif MICROPY_PY_FSTRINGS || (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, '\'', '\"'))) @@ -148,45 +153,51 @@ static void next_char(mp_lexer_t *lex) { lex->chr0 = lex->chr1; lex->chr1 = lex->chr2; - // and add the next byte from either the fstring args or the reader + // and add the next byte from either inject_chrs or the reader + mp_uint_t chr2; +fetch_next_byte: #if MICROPY_PY_FSTRINGS - if (lex->fstring_args_idx) { - // if there are saved chars, then we're currently injecting fstring args - if (lex->fstring_args_idx < lex->fstring_args.len) { - lex->chr2 = lex->fstring_args.buf[lex->fstring_args_idx++]; - } else { - // no more fstring arg bytes - lex->chr2 = '\0'; - } - - if (lex->chr0 == '\0') { - // consumed all fstring data, restore saved input queue - lex->chr0 = lex->chr0_saved; - lex->chr1 = lex->chr1_saved; - lex->chr2 = lex->chr2_saved; - // stop consuming fstring arg data - vstr_reset(&lex->fstring_args); - lex->fstring_args_idx = 0; + if (lex->inject_chrs_idx) { + // if there are saved chars, then we're currently injecting them + chr2 = lex->inject_chrs.buf[lex->inject_chrs_idx++]; + if (lex->inject_chrs_idx >= lex->inject_chrs.len) { + // consumed all injected characters, switch back to the input stream + vstr_reset(&lex->inject_chrs); + lex->inject_chrs_idx = 0; } } else #endif { - lex->chr2 = lex->reader.readbyte(lex->reader.data); + // get next byte from the reader + chr2 = lex->reader.readbyte(lex->reader.data); + + // convert stream mp_uint_t value to lexer uint8_t value: + // - MP_READER_EOF indicates end-of-stream, for which lexer uses MP_LEXER_EOF + // - MP_LEXER_EOF is not allowed in the input stream, as is converted to + // MP_LEXER_INVALID_BYTE so it's not interpreted as end-of-stream + // - all other byte values (1 through 255 inclusive) are passed through as-is + if (chr2 == MP_READER_EOF) { + chr2 = MP_LEXER_EOF; + } else if (chr2 == MP_LEXER_EOF) { + chr2 = MP_LEXER_INVALID_BYTE; + } } if (lex->chr1 == '\r') { // CR is a new line, converted to LF lex->chr1 = '\n'; - if (lex->chr2 == '\n') { + if (chr2 == '\n') { // CR LF is a single new line, throw out the extra LF - lex->chr2 = lex->reader.readbyte(lex->reader.data); + goto fetch_next_byte; } } // check if we need to insert a newline at end of file - if (lex->chr2 == MP_LEXER_EOF && lex->chr1 != MP_LEXER_EOF && lex->chr1 != '\n') { - lex->chr2 = '\n'; + if (chr2 == MP_LEXER_EOF && lex->chr1 != MP_LEXER_EOF && lex->chr1 != '\n') { + chr2 = '\n'; } + + lex->chr2 = chr2; } static void indent_push(mp_lexer_t *lex, size_t indent) { @@ -228,7 +239,6 @@ static const char *const tok_enc = "=e=" // = == "!."; // start of special cases: != . ... -// TODO static assert that number of tokens is less than 256 so we can safely make this table with byte sized entries static const uint8_t tok_enc_kind[] = { MP_TOKEN_DEL_PAREN_OPEN, MP_TOKEN_DEL_PAREN_CLOSE, MP_TOKEN_DEL_BRACKET_OPEN, MP_TOKEN_DEL_BRACKET_CLOSE, @@ -310,7 +320,7 @@ static bool get_hex(mp_lexer_t *lex, size_t num_digits, mp_uint_t *result) { return true; } -static void parse_string_literal(mp_lexer_t *lex, bool is_raw, bool is_fstring) { +static void parse_string_literal(mp_lexer_t *lex, bool is_raw, bool is_fstring, bool is_tstring) { // get first quoting character char quote_char = '\''; if (is_char(lex, '\"')) { @@ -334,26 +344,61 @@ static void parse_string_literal(mp_lexer_t *lex, bool is_raw, bool is_fstring) #if MICROPY_PY_FSTRINGS if (is_fstring) { // assume there's going to be interpolation, so prep the injection data - // fstring_args_idx==0 && len(fstring_args)>0 means we're extracting the args. - // only when fstring_args_idx>0 will we consume the arg data - // note: lex->fstring_args will be empty already (it's reset when finished) - vstr_add_str(&lex->fstring_args, ".format("); + // len(fstring_args)>0 means we're extracting the args. + // lex->fstring_args is reset when finished, so at this point there are two cases: + // - lex->fstring_args is empty: start of a new f-string + // - lex->fstring_args is non-empty: concatenation of adjacent f-strings + if (vstr_len(&lex->fstring_args) == 0) { + vstr_add_str(&lex->fstring_args, ".format("); + } + } + #endif + #if MICROPY_PY_TSTRINGS + if (is_tstring) { + if (vstr_len(&lex->fstring_args) == 0) { + vstr_add_byte(&lex->vstr, '('); + vstr_add_byte(&lex->vstr, '('); + for (size_t q = 0; q < num_quotes; ++q) { + vstr_add_byte(&lex->vstr, quote_char); + } + } } #endif + #if MICROPY_PY_TSTRINGS + size_t tstring_num_interpolations = 0; + size_t end_of_format_index = 0; + size_t nested_formatting_in_tstring = 0; + bool nested_formatting_needs_fstring = false; + #endif + while (!is_end(lex) && (num_quotes > 1 || !is_char(lex, '\n')) && n_closing < num_quotes) { if (is_char(lex, quote_char)) { n_closing += 1; vstr_add_char(&lex->vstr, CUR_CHAR(lex)); + #if MICROPY_PY_TSTRINGS + } else if (is_tstring && is_char(lex, '\n')) { + // handle multi-line t-strings + vstr_add_byte(&lex->vstr, '\\'); + vstr_add_byte(&lex->vstr, 'n'); + #endif } else { n_closing = 0; #if MICROPY_PY_FSTRINGS - while (is_fstring && is_char(lex, '{')) { + while ((is_fstring || is_tstring) && is_char(lex, '{')) { + #if MICROPY_PY_TSTRINGS + if (nested_formatting_in_tstring) { + ++nested_formatting_in_tstring; + break; + } + #endif next_char(lex); if (is_char(lex, '{')) { // "{{" is passed through unchanged to be handled by str.format - vstr_add_byte(&lex->vstr, '{'); + if (!is_tstring) { + vstr_add_byte(&lex->vstr, '{'); + } next_char(lex); } else { // wrap each argument in (), e.g. @@ -390,23 +435,102 @@ static void parse_string_literal(mp_lexer_t *lex, bool is_raw, bool is_fstring) vstr_add_byte(&lex->fstring_args, c); next_char(lex); } + #if MICROPY_PY_TSTRINGS + bool was_debug = false; + #endif if (lex->fstring_args.buf[lex->fstring_args.len - 1] == '=') { // if the last character of the arg was '=', then inject "arg=" before the '{'. // f'{a=}' --> 'a={}'.format(a) vstr_add_strn(&lex->vstr, lex->fstring_args.buf + i, lex->fstring_args.len - i); // remove the trailing '=' lex->fstring_args.len--; + #if MICROPY_PY_TSTRINGS + was_debug = true; + #endif + } + #if MICROPY_PY_TSTRINGS + if (is_tstring) { + // truncate trailing spaces + while (lex->fstring_args.len && unichar_isspace(lex->fstring_args.buf[lex->fstring_args.len - 1])) { + lex->fstring_args.len--; + } + } + #endif + if (lex->fstring_args.len == i) { + // empty format, eg f'{}' + // (should apply to both f-strings and t-strings, needs test) + lex->tok_kind = MP_TOKEN_MALFORMED_FSTRING; } // close the paren-wrapped arg to .format(). vstr_add_byte(&lex->fstring_args, ')'); // comma-separate args to .format(). vstr_add_byte(&lex->fstring_args, ','); + #if MICROPY_PY_TSTRINGS + if (is_tstring) { + // start the interpolation part + + // duplicate expression to a string + vstr_add_byte(&lex->fstring_args, quote_char); + size_t nn = lex->fstring_args.len - i - 3; + for (size_t j = 0; j < nn; ++j) { + byte b = lex->fstring_args.buf[i + j]; + if (b == quote_char) { + vstr_add_byte(&lex->fstring_args, '\\'); + } else if (b == '\\') { + vstr_add_byte(&lex->fstring_args, '\\'); + } + vstr_add_byte(&lex->fstring_args, b); + } + vstr_add_byte(&lex->fstring_args, quote_char); + vstr_add_byte(&lex->fstring_args, ','); + + // start next part of string as next __template__ argument + for (size_t q = 0; q < num_quotes; ++q) { + vstr_add_byte(&lex->vstr, quote_char); + } + vstr_add_byte(&lex->vstr, ','); + for (size_t q = 0; q < num_quotes; ++q) { + vstr_add_byte(&lex->vstr, quote_char); + } + + // process conv and format spec + if (is_char(lex, '!')) { + next_char(lex); + vstr_add_byte(&lex->fstring_args, quote_char); + vstr_add_byte(&lex->fstring_args, CUR_CHAR(lex)); + next_char(lex); + vstr_add_byte(&lex->fstring_args, quote_char); + vstr_add_byte(&lex->fstring_args, ','); + } else if (was_debug && !is_char(lex, ':')) { + vstr_add_str(&lex->fstring_args, "'r',"); + } else { + vstr_add_str(&lex->fstring_args, "None,"); + } + + // start format str + if (is_char(lex, ':')) { + next_char(lex); + } + nested_formatting_in_tstring = 1; + end_of_format_index = lex->vstr.len; + } + #endif } vstr_add_byte(&lex->vstr, '{'); + goto continue_outer; } #endif - if (is_char(lex, '\\')) { + if (is_tstring && is_char(lex, '\\')) { + // it'll be reparsed as a string + vstr_add_byte(&lex->vstr, '\\'); + if (is_raw) { + vstr_add_byte(&lex->vstr, '\\'); + } else { + next_char(lex); + vstr_add_byte(&lex->vstr, CUR_CHAR(lex)); + } + } else if (is_char(lex, '\\')) { next_char(lex); unichar c = CUR_CHAR(lex); if (is_raw) { @@ -414,11 +538,9 @@ static void parse_string_literal(mp_lexer_t *lex, bool is_raw, bool is_fstring) vstr_add_char(&lex->vstr, '\\'); } else { 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 + // backslash escape the newline, just ignore it + goto continue_parsing_string_literal; case '\\': break; case '\'': @@ -489,33 +611,61 @@ static void parse_string_literal(mp_lexer_t *lex, bool is_raw, bool is_fstring) break; } } - if (c != MP_LEXER_EOF) { - #if MICROPY_PY_BUILTINS_STR_UNICODE - if (c < 0x110000 && lex->tok_kind == MP_TOKEN_STRING) { - // Valid unicode character in a str object. - vstr_add_char(&lex->vstr, c); - } else if (c < 0x100 && lex->tok_kind == MP_TOKEN_BYTES) { - // Valid byte in a bytes object. - vstr_add_byte(&lex->vstr, c); - } - #else - if (c < 0x100) { - // Without unicode everything is just added as an 8-bit byte. - vstr_add_byte(&lex->vstr, c); - } - #endif - else { - // Character out of range; this raises a generic SyntaxError. - lex->tok_kind = MP_TOKEN_INVALID; + #if MICROPY_PY_BUILTINS_STR_UNICODE + if (c < 0x110000 && lex->tok_kind == MP_TOKEN_STRING) { + // Valid unicode character in a str object. + vstr_add_char(&lex->vstr, c); + } else if (c < 0x100 && lex->tok_kind == MP_TOKEN_BYTES) { + // Valid byte in a bytes object. + vstr_add_byte(&lex->vstr, c); + } + #else + if (c < 0x100) { + // Without unicode everything is just added as an 8-bit byte. + vstr_add_byte(&lex->vstr, c); + } + #endif + else { + // Character out of range; this raises a generic SyntaxError. + lex->tok_kind = MP_TOKEN_INVALID; + } + #if MICROPY_PY_TSTRINGS + } else if (is_tstring && nested_formatting_in_tstring && is_char(lex, '}')) { + if (--nested_formatting_in_tstring > 0) { + nested_formatting_needs_fstring = true; + vstr_add_byte(&lex->vstr, CUR_CHAR(lex)); + } else { + // finished the current interpolation + ++tstring_num_interpolations; + if (nested_formatting_needs_fstring) { + vstr_add_byte(&lex->fstring_args, 'f'); + nested_formatting_needs_fstring = false; } + vstr_add_byte(&lex->fstring_args, quote_char); + vstr_add_strn(&lex->fstring_args, lex->vstr.buf + end_of_format_index + 1, lex->vstr.len - end_of_format_index - 1); + lex->vstr.len = end_of_format_index; + vstr_add_byte(&lex->fstring_args, quote_char); + vstr_add_byte(&lex->fstring_args, ','); } + #endif } else { // Add the "character" as a byte so that we remain 8-bit clean. // This way, strings are parsed correctly whether or not they contain utf-8 chars. vstr_add_byte(&lex->vstr, CUR_CHAR(lex)); + #if MICROPY_PY_TSTRINGS + if (is_tstring && is_char_and(lex, '}', '}')) { + next_char(lex); + } else if (is_tstring && is_char(lex, '}')) { + lex->tok_kind = MP_TOKEN_MALFORMED_FSTRING; + } + #endif } } + continue_parsing_string_literal: next_char(lex); + #if MICROPY_PY_FSTRINGS + continue_outer:; + #endif } // check we got the required end quotes @@ -523,8 +673,23 @@ static void parse_string_literal(mp_lexer_t *lex, bool is_raw, bool is_fstring) lex->tok_kind = MP_TOKEN_LONELY_STRING_OPEN; } - // cut off the end quotes from the token text - vstr_cut_tail_bytes(&lex->vstr, n_closing); + #if MICROPY_PY_TSTRINGS + if (is_tstring) { + if (nested_formatting_in_tstring > 0) { + lex->tok_kind = MP_TOKEN_MALFORMED_FSTRING; + } + + if (1 + tstring_num_interpolations * 4 > 255) { + // too many arguments for function call, so wrap interpolations in a tuple + vstr_ins_byte(&lex->fstring_args, 0, '('); + vstr_add_byte(&lex->fstring_args, ')'); + } + } else + #endif + { + // cut off the end quotes from the token text + vstr_cut_tail_bytes(&lex->vstr, n_closing); + } } // This function returns whether it has crossed a newline or not. @@ -556,23 +721,6 @@ static bool skip_whitespace(mp_lexer_t *lex, bool stop_at_newline) { } void mp_lexer_to_next(mp_lexer_t *lex) { - #if MICROPY_PY_FSTRINGS - if (lex->fstring_args.len && lex->fstring_args_idx == 0) { - // moving onto the next token means the literal string is complete. - // switch into injecting the format args. - vstr_add_byte(&lex->fstring_args, ')'); - lex->chr0_saved = lex->chr0; - lex->chr1_saved = lex->chr1; - lex->chr2_saved = lex->chr2; - lex->chr0 = lex->fstring_args.buf[0]; - lex->chr1 = lex->fstring_args.buf[1]; - lex->chr2 = lex->fstring_args.buf[2]; - // we've already extracted 3 chars, but setting this non-zero also - // means we'll start consuming the fstring data - lex->fstring_args_idx = 3; - } - #endif - // start new token text vstr_reset(&lex->vstr); @@ -632,11 +780,16 @@ 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_PY_TSTRINGS + bool had_tstring = false; + #endif + // Loop to accumulate string/bytes literals do { // parse type codes bool is_raw = false; bool is_fstring = false; + bool is_tstring = false; mp_token_kind_t kind = MP_TOKEN_STRING; int n_char = 0; if (is_char(lex, 'u')) { @@ -656,22 +809,42 @@ void mp_lexer_to_next(mp_lexer_t *lex) { n_char = 2; } #if MICROPY_PY_FSTRINGS - if (is_char_following(lex, 'f')) { - // raw-f-strings unsupported, immediately return (invalid) token. - lex->tok_kind = MP_TOKEN_FSTRING_RAW; - break; + else if (is_char_following(lex, 'f')) { + is_fstring = true; + n_char = 2; + } + #endif + #if MICROPY_PY_TSTRINGS + else if (is_char_following(lex, 't')) { + is_tstring = true; + n_char = 2; } #endif } #if MICROPY_PY_FSTRINGS else if (is_char(lex, 'f')) { + is_fstring = true; + n_char = 1; if (is_char_following(lex, 'r')) { - // raw-f-strings unsupported, immediately return (invalid) token. - lex->tok_kind = MP_TOKEN_FSTRING_RAW; - break; + is_raw = true; + n_char = 2; } + } + #endif + #if MICROPY_PY_TSTRINGS + else if (is_char(lex, 't')) { + is_tstring = true; n_char = 1; - is_fstring = true; + if (is_char_following(lex, 'r')) { + is_raw = true; + n_char = 2; + } + } + #endif + + #if MICROPY_PY_TSTRINGS + if (is_tstring) { + had_tstring = true; } #endif @@ -692,13 +865,52 @@ void mp_lexer_to_next(mp_lexer_t *lex) { } // Parse the literal - parse_string_literal(lex, is_raw, is_fstring); + parse_string_literal(lex, is_raw, is_fstring, is_tstring); // Skip whitespace so we can check if there's another string following skip_whitespace(lex, true); } while (is_string_or_bytes(lex)); + #if MICROPY_PY_TSTRINGS + if (had_tstring) { + vstr_add_byte(&lex->vstr, ','); + vstr_add_byte(&lex->vstr, ')'); + vstr_add_byte(&lex->vstr, ','); + vstr_ins_strn(&lex->fstring_args, 0, lex->vstr.buf, lex->vstr.len); + if (lex->tok_kind > MP_TOKEN_MALFORMED_FSTRING) { + // next token is __template__ for the function + lex->tok_kind = MP_TOKEN_NAME; + vstr_reset(&lex->vstr); + vstr_add_str(&lex->vstr, "__template__"); + } + } + #endif + + #if MICROPY_PY_FSTRINGS + if (lex->fstring_args.len) { + // If there was an f-string then it's now complete. + // Switch into injecting the format args. + vstr_add_byte(&lex->fstring_args, ')'); + if (lex->inject_chrs_idx == 0) { + // switch from stream to inject_chrs + char *s = vstr_add_len(&lex->inject_chrs, 3); + s[0] = lex->chr0; + s[1] = lex->chr1; + s[2] = lex->chr2; + } else { + // already consuming from inject_chrs, rewind cached chars to insert new ones + assert(lex->inject_chrs_idx >= 3); + lex->inject_chrs_idx -= 3; + } + vstr_ins_strn(&lex->inject_chrs, lex->inject_chrs_idx, lex->fstring_args.buf, lex->fstring_args.len); + vstr_reset(&lex->fstring_args); + lex->chr0 = lex->inject_chrs.buf[lex->inject_chrs_idx++]; + lex->chr1 = lex->inject_chrs.buf[lex->inject_chrs_idx++]; + lex->chr2 = lex->inject_chrs.buf[lex->inject_chrs_idx++]; + } + #endif + } else if (is_head_of_identifier(lex)) { lex->tok_kind = MP_TOKEN_NAME; @@ -772,6 +984,9 @@ void mp_lexer_to_next(mp_lexer_t *lex) { } else { // search for encoded delimiter or operator + // assert that the token enum value fits in a byte, so they all fit in tok_enc_kind + MP_STATIC_ASSERT(MP_TOKEN_NUMBER_OF <= 256); + const char *t = tok_enc; size_t tok_enc_index = 0; for (; *t != 0 && !is_char(lex, *t); t += 1) { @@ -853,8 +1068,9 @@ mp_lexer_t *mp_lexer_new(qstr src_name, mp_reader_t reader) { lex->indent_level = m_new(uint16_t, lex->alloc_indent_level); vstr_init(&lex->vstr, 32); #if MICROPY_PY_FSTRINGS + vstr_init(&lex->inject_chrs, 0); + lex->inject_chrs_idx = 0; vstr_init(&lex->fstring_args, 0); - lex->fstring_args_idx = 0; #endif // store sentinel for first indentation level @@ -911,6 +1127,7 @@ void mp_lexer_free(mp_lexer_t *lex) { lex->reader.close(lex->reader.data); vstr_clear(&lex->vstr); #if MICROPY_PY_FSTRINGS + vstr_clear(&lex->inject_chrs); vstr_clear(&lex->fstring_args); #endif m_del(uint16_t, lex->indent_level, lex->alloc_indent_level); diff --git a/py/lexer.h b/py/lexer.h index 2d9d0447b8b..b1257d55948 100644 --- a/py/lexer.h +++ b/py/lexer.h @@ -46,7 +46,6 @@ typedef enum _mp_token_kind_t { MP_TOKEN_LONELY_STRING_OPEN, #if MICROPY_PY_FSTRINGS MP_TOKEN_MALFORMED_FSTRING, - MP_TOKEN_FSTRING_RAW, #endif MP_TOKEN_NEWLINE, @@ -153,6 +152,8 @@ typedef enum _mp_token_kind_t { MP_TOKEN_DEL_SEMICOLON, MP_TOKEN_DEL_EQUAL, MP_TOKEN_DEL_MINUS_MORE, + + MP_TOKEN_NUMBER_OF, } mp_token_kind_t; // this data structure is exposed for efficiency @@ -161,10 +162,8 @@ typedef struct _mp_lexer_t { qstr source_name; // name of source mp_reader_t reader; // stream source - unichar chr0, chr1, chr2; // current cached characters from source - #if MICROPY_PY_FSTRINGS - unichar chr0_saved, chr1_saved, chr2_saved; // current cached characters from alt source - #endif + uint32_t chr0; // first cached byte from source (32-bits for efficient access) + uint8_t chr1, chr2; // subsequent cached bytes from source size_t line; // current source line size_t column; // current source column @@ -181,8 +180,9 @@ typedef struct _mp_lexer_t { mp_token_kind_t tok_kind; // token kind vstr_t vstr; // token data #if MICROPY_PY_FSTRINGS + vstr_t inject_chrs; // characters currently being injected into the stream + size_t inject_chrs_idx; // current index into inject_chrs vstr_t fstring_args; // extracted arguments to pass to .format() - size_t fstring_args_idx; // how many bytes of fstring_args have been read #endif } mp_lexer_t; diff --git a/py/make_root_pointers.py b/py/make_root_pointers.py index efe398b8227..5da343c1270 100644 --- a/py/make_root_pointers.py +++ b/py/make_root_pointers.py @@ -6,8 +6,6 @@ "struct _mp_state_vm_t" in py/mpstate.h """ -from __future__ import print_function - import argparse import io import re diff --git a/py/makecompresseddata.py b/py/makecompresseddata.py index 1bce3e8e837..a6fa7db00b2 100644 --- a/py/makecompresseddata.py +++ b/py/makecompresseddata.py @@ -1,5 +1,3 @@ -from __future__ import print_function - import collections import re import sys diff --git a/py/makemoduledefs.py b/py/makemoduledefs.py index 29162ab387c..c8fdc21f6fb 100644 --- a/py/makemoduledefs.py +++ b/py/makemoduledefs.py @@ -14,8 +14,6 @@ the built-in version. """ -from __future__ import print_function - import sys import re import io @@ -87,19 +85,25 @@ def generate_module_table_header(modules): ) ) + # There should always be at least one module (__main__ in runtime.c) + assert mod_defs + print("\n#define MICROPY_REGISTERED_MODULES \\") for mod_def in sorted(mod_defs): print(" {mod_def} \\".format(mod_def=mod_def)) - print("// MICROPY_REGISTERED_MODULES") - print("\n#define MICROPY_REGISTERED_EXTENSIBLE_MODULES \\") + # There are not necessarily any extensible modules (e.g., bare-arm or minimal x86) + print("\n#define MICROPY_HAVE_REGISTERED_EXTENSIBLE_MODULES ", len(extensible_mod_defs)) - for mod_def in sorted(extensible_mod_defs): - print(" {mod_def} \\".format(mod_def=mod_def)) + if extensible_mod_defs: + print("\n#define MICROPY_REGISTERED_EXTENSIBLE_MODULES \\") + + for mod_def in sorted(extensible_mod_defs): + print(" {mod_def} \\".format(mod_def=mod_def)) - print("// MICROPY_REGISTERED_EXTENSIBLE_MODULES") + print("// MICROPY_REGISTERED_EXTENSIBLE_MODULES") def generate_module_delegations(delegations): diff --git a/py/makeqstrdata.py b/py/makeqstrdata.py index d56417b6859..b8613f2a1b3 100644 --- a/py/makeqstrdata.py +++ b/py/makeqstrdata.py @@ -1,36 +1,54 @@ """ Process raw qstr file and output qstr data with length, hash and data bytes. -This script works with Python 2.7, 3.3 and 3.4. - -CIRCUITPY-CHANGE: -For documentation about the format of compressed translated strings, see -supervisor/shared/translate/translate.h +This script works with Python 3.3+. """ -from __future__ import print_function - - import re import sys -# CIRCUITPY-CHANGE -if hasattr(sys.stdout, "reconfigure"): - sys.stdout.reconfigure(encoding="utf-8") - sys.stderr.reconfigure(errors="backslashreplace") - -# Python 2/3 compatibility: -# - iterating through bytes is different -# - codepoint2name lives in a different module -import platform - -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": - bytes_cons = bytes - from html.entities import codepoint2name -# end compatibility code +bytes_cons = bytes + +# fmt: off +codepoint2name = { + 198: "AElig", 193: "Aacute", 194: "Acirc", 192: "Agrave", 913: "Alpha", 197: "Aring", 195: "Atilde", + 196: "Auml", 914: "Beta", 199: "Ccedil", 935: "Chi", 8225: "Dagger", 916: "Delta", 208: "ETH", + 201: "Eacute", 202: "Ecirc", 200: "Egrave", 917: "Epsilon", 919: "Eta", 203: "Euml", 915: "Gamma", + 205: "Iacute", 206: "Icirc", 204: "Igrave", 921: "Iota", 207: "Iuml", 922: "Kappa", 923: "Lambda", + 924: "Mu", 209: "Ntilde", 925: "Nu", 338: "OElig", 211: "Oacute", 212: "Ocirc", 210: "Ograve", + 937: "Omega", 927: "Omicron", 216: "Oslash", 213: "Otilde", 214: "Ouml", 934: "Phi", 928: "Pi", + 8243: "Prime", 936: "Psi", 929: "Rho", 352: "Scaron", 931: "Sigma", 222: "THORN", 932: "Tau", + 920: "Theta", 218: "Uacute", 219: "Ucirc", 217: "Ugrave", 933: "Upsilon", 220: "Uuml", 926: "Xi", + 221: "Yacute", 376: "Yuml", 918: "Zeta", 225: "aacute", 226: "acirc", 180: "acute", 230: "aelig", + 224: "agrave", 8501: "alefsym", 945: "alpha", 38: "amp", 8743: "and", 8736: "ang", 229: "aring", + 8776: "asymp", 227: "atilde", 228: "auml", 8222: "bdquo", 946: "beta", 166: "brvbar", 8226: "bull", + 8745: "cap", 231: "ccedil", 184: "cedil", 162: "cent", 967: "chi", 710: "circ", 9827: "clubs", + 8773: "cong", 169: "copy", 8629: "crarr", 8746: "cup", 164: "curren", 8659: "dArr", 8224: "dagger", + 8595: "darr", 176: "deg", 948: "delta", 9830: "diams", 247: "divide", 233: "eacute", 234: "ecirc", + 232: "egrave", 8709: "empty", 8195: "emsp", 8194: "ensp", 949: "epsilon", 8801: "equiv", 951: "eta", + 240: "eth", 235: "euml", 8364: "euro", 8707: "exist", 402: "fnof", 8704: "forall", 189: "frac12", + 188: "frac14", 190: "frac34", 8260: "frasl", 947: "gamma", 8805: "ge", 62: "gt", 8660: "hArr", + 8596: "harr", 9829: "hearts", 8230: "hellip", 237: "iacute", 238: "icirc", 161: "iexcl", 236: "igrave", + 8465: "image", 8734: "infin", 8747: "int", 953: "iota", 191: "iquest", 8712: "isin", 239: "iuml", + 954: "kappa", 8656: "lArr", 955: "lambda", 9001: "lang", 171: "laquo", 8592: "larr", 8968: "lceil", + 8220: "ldquo", 8804: "le", 8970: "lfloor", 8727: "lowast", 9674: "loz", 8206: "lrm", 8249: "lsaquo", + 8216: "lsquo", 60: "lt", 175: "macr", 8212: "mdash", 181: "micro", 183: "middot", 8722: "minus", + 956: "mu", 8711: "nabla", 160: "nbsp", 8211: "ndash", 8800: "ne", 8715: "ni", 172: "not", 8713: "notin", # codespell:ignore notin + 8836: "nsub", 241: "ntilde", 957: "nu", 243: "oacute", 244: "ocirc", 339: "oelig", 242: "ograve", + 8254: "oline", 969: "omega", 959: "omicron", 8853: "oplus", 8744: "or", 170: "ordf", 186: "ordm", + 248: "oslash", 245: "otilde", 8855: "otimes", 246: "ouml", 182: "para", 8706: "part", 8240: "permil", + 8869: "perp", 966: "phi", 960: "pi", 982: "piv", 177: "plusmn", 163: "pound", 8242: "prime", + 8719: "prod", 8733: "prop", 968: "psi", 34: "quot", 8658: "rArr", 8730: "radic", 9002: "rang", + 187: "raquo", 8594: "rarr", 8969: "rceil", 8221: "rdquo", 8476: "real", 174: "reg", 8971: "rfloor", + 961: "rho", 8207: "rlm", 8250: "rsaquo", 8217: "rsquo", 8218: "sbquo", 353: "scaron", 8901: "sdot", + 167: "sect", 173: "shy", 963: "sigma", 962: "sigmaf", 8764: "sim", 9824: "spades", 8834: "sub", + 8838: "sube", 8721: "sum", 8835: "sup", 185: "sup1", 178: "sup2", 179: "sup3", 8839: "supe", + 223: "szlig", 964: "tau", 8756: "there4", 952: "theta", 977: "thetasym", 8201: "thinsp", 254: "thorn", + 732: "tilde", 215: "times", 8482: "trade", 8657: "uArr", 250: "uacute", 8593: "uarr", 251: "ucirc", + 249: "ugrave", 168: "uml", 978: "upsih", 965: "upsilon", 252: "uuml", 8472: "weierp", 958: "xi", + 253: "yacute", 165: "yen", 255: "yuml", 950: "zeta", 8205: "zwj", 8204: "zwnj" +} +# fmt: on codepoint2name[ord("-")] = "hyphen" @@ -305,6 +323,9 @@ "", } +# Matches any string that needs no escaping (alphanum + _ only) +RE_NO_ESCAPE = re.compile(r"^[a-zA-Z0-9_]$") + # this must match the equivalent function in qstr.c def compute_hash(qstr, bytes_hash): @@ -317,15 +338,17 @@ def compute_hash(qstr, bytes_hash): def qstr_escape(qst): - def esc_char(m): - c = ord(m.group(0)) + def esc_char(c): + if RE_NO_ESCAPE.match(c): + return c + c = ord(c) try: name = codepoint2name[c] except KeyError: name = "0x%02x" % c return "_" + name + "_" - return re.sub(r"[^A-Za-z0-9_]", esc_char, qst) + return "".join(map(esc_char, qst)) static_qstr_list_ident = list(map(qstr_escape, static_qstr_list)) @@ -411,7 +434,15 @@ def escape_bytes(qstr, qbytes): return "".join(("\\x%02x" % b) for b in qbytes) -def make_bytes(cfg_bytes_len, cfg_bytes_hash, qstr): +# CIRCUITPY-CHANGE: the ROM pools store their strings in one NUL-separated blob per +# pool, addressed by 16-bit offsets. Each QDEF line carries the string's offset within +# its pool's blob as the fourth field. The blob is assembled by the C preprocessor +# concatenating the QDEF string literals in file order, so the offsets here must be +# the running total of (len + 1) in emission order for each pool. +QSTR_BLOB_MAX = 1 << 16 + + +def make_bytes(cfg_bytes_len, cfg_bytes_hash, qstr, offset): qbytes = bytes_cons(qstr, "utf8") qlen = len(qbytes) qhash = compute_hash(qbytes, cfg_bytes_hash) @@ -419,7 +450,8 @@ def make_bytes(cfg_bytes_len, cfg_bytes_hash, qstr): print("qstr is too long:", qstr) assert False qdata = escape_bytes(qstr, qbytes) - return '%d, %d, "%s"' % (qhash, qlen, qdata) + # CIRCUITPY-CHANGE: emit the blob offset; the caller advances it by qlen + 1 + return '%d, %d, %d, "%s"' % (qhash, qlen, offset, qdata), qlen + 1 # CIRCUITPY-CHANGE: add translations @@ -432,12 +464,19 @@ def print_qstr_data(qcfgs, qstrs, translations): print("// This file was automatically generated by makeqstrdata.py") print("") + # CIRCUITPY-CHANGE: running blob offset for each ROM pool + offsets = [0, 0] + # add NULL qstr with no hash or data - print('QDEF0(MP_QSTRnull, 0, 0, "")') + # CIRCUITPY-CHANGE: offset field; the null qstr occupies one NUL byte of the blob + print('QDEF0(MP_QSTRnull, 0, 0, 0, "")') + offsets[0] += 1 # add static qstrs to the first unsorted pool for qstr in static_qstr_list: - qbytes = make_bytes(cfg_bytes_len, cfg_bytes_hash, qstr) + # CIRCUITPY-CHANGE: pass and advance the blob offset + qbytes, size = make_bytes(cfg_bytes_len, cfg_bytes_hash, qstr, offsets[0]) + offsets[0] += size print("QDEF0(MP_QSTR_%s, %s)" % (qstr_escape(qstr), qbytes)) # CIRCUITPY-CHANGE: track total qstr size @@ -446,13 +485,22 @@ def print_qstr_data(qcfgs, qstrs, translations): # add remaining qstrs to the sorted (by value) pool (unless they're in # unsorted_qstr_list, in which case add them to the unsorted pool) for ident, qstr in sorted(qstrs.values(), key=lambda x: x[1]): - qbytes = make_bytes(cfg_bytes_len, cfg_bytes_hash, qstr) pool = 0 if qstr in unsorted_qstr_list else 1 + # CIRCUITPY-CHANGE: pass and advance the blob offset + qbytes, size = make_bytes(cfg_bytes_len, cfg_bytes_hash, qstr, offsets[pool]) + offsets[pool] += size print("QDEF%d(MP_QSTR_%s, %s)" % (pool, ident, qbytes)) # CIRCUITPY-CHANGE: track total qstr size total_qstr_size += len(qstr) + # CIRCUITPY-CHANGE: offsets are stored as uint16_t (qstr_offset_t in py/qstr.h), + # including the trailing end-of-blob entry + for pool, total in enumerate(offsets): + if total >= QSTR_BLOB_MAX: + print("qstr blob for pool %d is too large: %d bytes" % (pool, total), file=sys.stderr) + assert False + # CIRCUITPY-CHANGE: translations print( "// Enumerate translated texts but don't actually include translations. Instead, the linker will link them in." diff --git a/py/makeqstrdefs.py b/py/makeqstrdefs.py index a4039857694..3bc81bf5961 100644 --- a/py/makeqstrdefs.py +++ b/py/makeqstrdefs.py @@ -2,11 +2,9 @@ This script processes the output from the C preprocessor and extracts all qstr. Each qstr is transformed into a qstr definition of the form 'Q(...)'. -This script works with Python 3.x (CIRCUITPY-CHANGE: not 2.x) +This script works with Python 3.3+. """ -from __future__ import print_function - import io import os import re @@ -96,10 +94,36 @@ def preprocess(): except OSError: pass + # These regex's are used to filter the preprocessed data, keeping only those lines + # that are subsequently needed by the `process_file` step. The regexs are kept + # short so they are as efficient as possible. (The stm32 port needs symbols of the + # form `micropy_hw_xxx` so they are also kept.) + re_line_file = re.compile(rb"^#(?:line)?\s+\d+\s\"") + re_mp_info = re.compile(rb"MP_COMP|MP_QSTR|MP_REGI|micropy_hw") + def pp(flags): def run(files): try: - return subprocess.check_output(args.pp + flags + files) + filtered_lines = [] + cmd = args.pp + flags + files + with subprocess.Popen(cmd, stdout=subprocess.PIPE) as proc: + for line in proc.stdout: + if line.isspace(): + pass + elif re_line_file.match(line): + # CIRCUITPY-CHANGE: keep every file marker, not just + # the one preceding an MP symbol. CircuitPython + # attributes MP_COMPRESSED_ROM_TEXT found in headers + # to the enclosing C source, so process_file needs + # the C source markers even when the symbol itself + # comes from a header. + filtered_lines.append(line) + elif re_mp_info.search(line): + filtered_lines.append(line) + proc.wait() + if proc.returncode: + raise PreprocessorError("command failed: " + " ".join(cmd)) + return b"".join(filtered_lines) except subprocess.CalledProcessError as er: raise PreprocessorError(str(er)) @@ -139,6 +163,7 @@ def qstr_unescape(qstr): return qstr +# CIRCUITPY-CHANGE: output_filename as an arg def process_file(f, output_filename=None): # match gcc-like output (# n "file") and msvc-like output (#line n "file") re_line = re.compile(r"^#(?:line)?\s+\d+\s\"([^\"]+)\"") @@ -292,6 +317,7 @@ class Args: args.input_filename = sys.argv[3] # Unused for command=cat args.output_dir = sys.argv[4] args.output_file = None if len(sys.argv) == 5 else sys.argv[5] # Unused for command=split + # CIRCUITPY-CHANGE if args.output_file == "_": args.output_file = None @@ -306,6 +332,7 @@ class Args: if args.command == "split": with io.open(args.input_filename, encoding="utf-8") as infile: + # CIRCUITPY-CHANGE: pass output_file process_file(infile, args.output_file) if args.command == "cat": diff --git a/py/maketranslationdata.py b/py/maketranslationdata.py index 3933387b645..14bd7a25e89 100644 --- a/py/maketranslationdata.py +++ b/py/maketranslationdata.py @@ -6,13 +6,13 @@ supported CPython version are unintended. For documentation about the format of compressed translated strings, see -supervisor/shared/translate/translate.h +supervisor/shared/translate/compressed_string.h """ from __future__ import print_function import bisect -from dataclasses import dataclass +from dataclasses import dataclass, field import re import sys @@ -73,6 +73,102 @@ '"': '\\"', } +# Symbol values with a special meaning, as characters. Must match +# translation_symbol_t in supervisor/shared/translate/compressed_string.h. +SYMBOL_QSTR = "\1" +SYMBOL_RARE_INDEX = "\2" +SYMBOL_RARE_RAW = "\3" +RESERVED_CHARS = {SYMBOL_QSTR, SYMBOL_RARE_INDEX, SYMBOL_RARE_RAW} + +# The first non-ASCII symbol value in the dense alphabet. +ALPHABET_BASE = 0x80 + +# Huffman codes are chosen per "class" of the previously decoded character. +# These base classes are fixed in the C decoder (translate.c, base_class()) and +# must match translation_class_t in supervisor/shared/translate/compressed_string.h; +# the generator collapses them with class_map[] into TRANSLATION_CLASSES tables. +CLASS_START_OR_SPACE = 0 +CLASS_LOWER = 1 +CLASS_UPPER = 2 +CLASS_DIGIT = 3 +CLASS_OTHER = 4 +CLASS_PERCENT = 5 +CLASS_NON_ASCII = 6 +NUM_BASE_CLASSES = 7 +# Presets to try. Each is the list of Huffman tables to build, each table +# naming the base classes that share it. class_map_for() turns one into the +# class_map[] the decoder uses. +CLASS_PRESETS = ( + # one table: the tables cost more than they save + [ + [ + CLASS_START_OR_SPACE, + CLASS_LOWER, + CLASS_UPPER, + CLASS_DIGIT, + CLASS_OTHER, + CLASS_PERCENT, + CLASS_NON_ASCII, + ] + ], + # space, letter, other + [ + [CLASS_START_OR_SPACE], + [CLASS_LOWER, CLASS_UPPER, CLASS_NON_ASCII], + [CLASS_DIGIT, CLASS_OTHER, CLASS_PERCENT], + ], + # non-ASCII shares the lowercase table + [ + [CLASS_START_OR_SPACE], + [CLASS_LOWER, CLASS_NON_ASCII], + [CLASS_UPPER], + [CLASS_DIGIT], + [CLASS_OTHER], + [CLASS_PERCENT], + ], + # non-ASCII has its own table + [ + [CLASS_START_OR_SPACE], + [CLASS_LOWER], + [CLASS_UPPER], + [CLASS_DIGIT], + [CLASS_OTHER], + [CLASS_PERCENT], + [CLASS_NON_ASCII], + ], +) + + +def class_map_for(preset): + """class_map[] for a preset: base class -> index of the table it uses.""" + class_map = [None] * NUM_BASE_CLASSES + for table, classes in enumerate(preset): + for cls in classes: + assert class_map[cls] is None, f"class {cls} in two tables" + class_map[cls] = table + assert None not in class_map, "every base class needs a table" + return tuple(class_map) + + +def base_class(c): + """Class of the character preceding the next symbol; None means start of string. + Computed on the (possibly remapped) character: remapped characters are >= 0x80 + exactly when the original is, which is all the classification looks at.""" + if c is None or c == " ": + return CLASS_START_OR_SPACE + o = ord(c) + if 0x61 <= o <= 0x7A: + return CLASS_LOWER + if 0x41 <= o <= 0x5A: + return CLASS_UPPER + if 0x30 <= o <= 0x39: + return CLASS_DIGIT + if o == 0x25: # '%' + return CLASS_PERCENT + if o >= 0x80: + return CLASS_NON_ASCII + return CLASS_OTHER + # this must match the equivalent function in qstr.c def compute_hash(qstr, bytes_hash): @@ -140,100 +236,183 @@ def iter_substrings(s, minlen, maxlen): yield s[begin : begin + n] -translation_requires_uint16 = {"cs", "ja", "ko", "pl", "tr", "zh_Latn_pinyin"} +# Non-ASCII characters that do not get a dense symbol are "rare". While the text +# is being processed they are remapped into two private-use ranges so that they +# stay single characters: those used more than once become an index into +# rare_chars[], those used once are coded as a raw 16-bit code point. +RARE_IDX_BASE = 0xF0000 +RARE_RAW_BASE = 0x100000 +RARE_SPLIT = re.compile("[\U000f0000-\U0010ffff]") +# Dense alphabet sizes to try when a language has more non-ASCII characters +# than fit; the rest of the code points go to the dictionary. +DENSE_ALPHABET_TRIES = (32, 48, 64, 80) -def compute_unicode_offset(texts): - all_ch = set(" ".join(texts)) - ch_160 = sorted(c for c in all_ch if 160 <= ord(c) < 255) - ch_256 = sorted(c for c in all_ch if 255 < ord(c)) - if not ch_256: - return 0, 0 - min_256 = ord(min(ch_256)) - span = ord(max(ch_256)) - ord(min(ch_256)) + 1 +@dataclass +class EncodingTable: + # One entry per class table: list of symbols in canonical order. + values: list + # One entry per class table: list of code-length counts, padded to lengths_row. + lengths: list + lengths_row: int + class_map: tuple + # Per class table: symbol -> canonical code (string of '0'/'1'). + canonical: list + # Dictionary words, in remapped characters, sorted by length. + words: list + word_start: int + # Dense alphabet: index -> original character. + alphabet: list + # Rare characters coded by index -> original character. + rare_idx_chars: list + rare_index_bits: int + # Original character -> remapped character (identity for ASCII). + remap: dict + translation_qstr_bits: int + qstrs: dict + qstrs_inv: dict + # Remapped text -> token list used to encode it. A token is a str (character + # or word) or a ("q", qstr) tuple. + tokens: dict = field(default_factory=dict) - if ch_160: - max_160 = ord(max(ch_160)) + 1 - else: - max_160 = max(160, 255 - span) - if max_160 + span > 256: - return 0, 0 +def remap_text(text, remap): + return "".join(remap.get(c, c) for c in text) - offstart = max_160 - offset = min_256 - max_160 - return offstart, offset +def is_qstr(token): + return isinstance(token, tuple) -@dataclass -class EncodingTable: - values: object - lengths: object - words: object - canonical: object - extractor: object - apply_offset: object - remove_offset: object - translation_qstr_bits: int - qstrs: object - qstrs_inv: object +def is_rare(token): + return len(token) == 1 and ord(token) >= RARE_IDX_BASE -def compute_huffman_coding(qstrs, translation_name, translations, f, compression_level): - # possible future improvement: some languages are better when consider len(k) > 2. try both? - qstrs = dict((k, v) for k, v in qstrs.items() if len(k) > 3) - qstr_strs = list(qstrs.keys()) - texts = [t[1] for t in translations] - words = [] - start_unused = 0x80 - end_unused = 0xFF - max_ord = 0 - offstart, offset = compute_unicode_offset(texts) - - def apply_offset(c): - oc = ord(c) - if oc >= offstart: - oc += offset - return chr(oc) - - def remove_offset(c): - oc = ord(c) - if oc >= offstart: - oc = oc - offset - try: - return chr(oc) - except Exception as e: - raise ValueError(f"remove_offset {offstart=} {oc=}") from e +def token_len(token): + return len(token[1]) if is_qstr(token) else len(token) + + +def token_symbol(token): + """The Huffman symbol a token is coded as. qstrs and rare characters are + coded as an escape symbol followed by a fixed number of bits.""" + if is_qstr(token): + return SYMBOL_QSTR + if is_rare(token): + return SYMBOL_RARE_RAW if ord(token) >= RARE_RAW_BASE else SYMBOL_RARE_INDEX + return token - for text in texts: - for c in text: - c = remove_offset(c) - ord_c = ord(c) - max_ord = max(ord_c, max_ord) - if 0x80 <= ord_c < 0xFF: - end_unused = min(ord_c, end_unused) - max_words = end_unused - 0x80 - if compression_level < 5: - max_words = 0 - - bits_per_codepoint = 16 if max_ord > 255 else 8 - values_type = "uint16_t" if max_ord > 255 else "uint8_t" - translation_name = translation_name.split("/")[-1].split(".")[0] - if max_ord > 255 and translation_name not in translation_requires_uint16: - raise ValueError( - f"Translation {translation_name} expected to fit in 8 bits but required 16 bits" - ) - # Prune the qstrs to only those that appear in the texts - qstr_counters = collections.Counter() - qstr_extractor = TextSplitter(qstr_strs) - for t in texts: - for qstr in qstr_extractor.iter(t): - if qstr in qstr_strs: - qstr_counters[qstr] += 1 - qstr_strs = list(qstr_counters.keys()) +def token_extra_bits(token, qstr_bits, rare_index_bits): + """Fixed-width bits that follow the token's Huffman symbol.""" + if is_qstr(token): + return qstr_bits + if is_rare(token): + return 16 if ord(token) >= RARE_RAW_BASE else rare_index_bits + return 0 + +def code_lengths(counter): + """Huffman code lengths for a symbol counter. A lone symbol gets a 1-bit code.""" + if len(counter) == 1: + return {next(iter(counter)): 1} + cb = huffman.codebook(counter.items()) + return {k: len(v) for k, v in cb.items()} + + +def canonical_codes(lengths): + """Canonical Huffman codes from a symbol -> length dict. + Returns (values in canonical order, per-length counts, symbol -> code).""" + if not lengths: + return [], [], {} + values = [] + length_count = collections.Counter() + canonical = {} + renumbered = 0 + last_length = None + for atom, length in sorted(lengths.items(), key=lambda x: (x[1], x[0])): + values.append(atom) + length_count[length] += 1 + if last_length: + renumbered <<= length - last_length + canonical[atom] = "{0:0{width}b}".format(renumbered, width=length) + renumbered += 1 + last_length = length + counts = [length_count.get(i, 0) for i in range(1, max(length_count) + 2)] + return values, counts, canonical + + +def parse_optimal( + text, + lens, + class_map, + words_by_first, + qstrs_by_first, + qstr_bits, + rare_index_bits, + unknown_len=32, +): + """Tokenize text with the fewest bits given per-class code lengths. + Symbols missing from a class table are allowed at a penalty so a parse always exists.""" + n = len(text) + best = [math.inf] * (n + 1) + back = [None] * (n + 1) + best[0] = 0 + for i in range(n): + if best[i] == math.inf: + continue + table = lens[class_map[base_class(text[i - 1] if i else None)]] + c = text[i] + cands = [c] + for w in words_by_first.get(c, ()): + if text.startswith(w, i): + cands.append(w) + for q in qstrs_by_first.get(c, ()): + if text.startswith(q, i): + cands.append(("q", q)) + for tok in cands: + cost = table.get(token_symbol(tok), unknown_len) + cost += token_extra_bits(tok, qstr_bits, rare_index_bits) + j = i + token_len(tok) + if best[i] + cost < best[j]: + best[j] = best[i] + cost + back[j] = tok + out = [] + i = n + while i > 0: + tok = back[i] + out.append(tok) + i -= token_len(tok) + out.reverse() + return out + + +def tally(texts, tokens, class_map): + """Symbol counts per class table for the given tokenizations.""" + counts = collections.defaultdict(collections.Counter) + for text in texts: + pos = 0 + for tok in tokens[text]: + cls = class_map[base_class(text[pos - 1] if pos else None)] + counts[cls][token_symbol(tok)] += 1 + pos += token_len(tok) + return counts + + +def encoded_bits(text, tokens, lens, class_map, qstr_bits, rare_index_bits): + bits = 0 + pos = 0 + for tok in tokens: + cls = class_map[base_class(text[pos - 1] if pos else None)] + bits += lens[cls][token_symbol(tok)] + bits += token_extra_bits(tok, qstr_bits, rare_index_bits) + pos += token_len(tok) + return bits + + +def find_words(texts, qstrs, qstr_strs, max_words): + """Greedy dictionary search: repeatedly add the 2- to 11-gram estimated to + save the most bits until the dictionary is full or nothing pays off.""" + words = [] while len(words) < max_words: # Until the dictionary is filled to capacity, use a heuristic to find # the best "word" (2- to 11-gram) to add to it. @@ -248,7 +427,7 @@ def remove_offset(c): for t in texts: for atom in extractor.iter(t): if atom in qstrs: - atom = "\1" + atom = SYMBOL_QSTR counter[atom] += 1 cb = huffman.codebook(counter.items()) lengths = sorted(dict((v, len(cb[k])) for k, v in counter.items()).items()) @@ -284,15 +463,18 @@ def est_len(occ): # The difference between the two is the estimated net savings, in bits. def est_net_savings(s, occ): savings = occ * (bit_length(s) - est_len(occ)) - cost = len(s) * bits_per_codepoint + 24 + cost = len(s) * 8 + 24 return savings - cost counter = collections.Counter() for t in texts: for found, word in extractor.iter_words(t): if not found: - for substr in iter_substrings(word, minlen=2, maxlen=11): - counter[substr] += 1 + # Words are stored as 8-bit symbols, so they cannot contain + # rare (escaped) characters: split around them. + for piece in RARE_SPLIT.split(word): + for substr in iter_substrings(piece, minlen=2, maxlen=11): + counter[substr] += 1 # Score the candidates we found. This is a semi-empirical formula that # attempts to model the number of bits saved as closely as possible. @@ -319,90 +501,239 @@ def est_net_savings(s, occ): word = scores[0][0] words.append(word) + return words + + +def compute_huffman_coding(qstrs, translation_name, translations, f, compression_level): + # possible future improvement: some languages are better when consider len(k) > 2. try both? + qstrs = dict((k, v) for k, v in qstrs.items() if len(k) > 3) + all_qstr_strs = list(qstrs.keys()) + original_texts = [t[1] for t in translations] + + for text in original_texts: + bad = RESERVED_CHARS.intersection(text) + if bad: + raise ValueError(f"Translation contains reserved character {bad!r}: {text!r}") + if any(ord(c) >= RARE_IDX_BASE for c in text): + raise ValueError(f"Translation contains private-use character: {text!r}") + + max_translation_encoded_length = max(len(t.encode("utf-8")) for t in original_texts) + encoded_length_bits = max_translation_encoded_length.bit_length() + use_qstrs = compression_level > 3 + + # Non-ASCII characters by decreasing frequency. The most frequent ones are + # renumbered from 0x80 (the dense alphabet), so that all symbols fit in 8 + # bits; the rest are escaped. + hi_count = collections.Counter(c for t in original_texts for c in t if ord(c) >= 0x80) + hi_chars = [c for c, _ in hi_count.most_common()] + if len(hi_chars) <= 0x7F: + dense_tries = (len(hi_chars),) + else: + dense_tries = DENSE_ALPHABET_TRIES + + def encode(dense_count): + alphabet = hi_chars[:dense_count] + rare = hi_chars[dense_count:] + rare_idx_chars = [c for c in rare if hi_count[c] > 1] + rare_raw_chars = [c for c in rare if hi_count[c] == 1] + rare_index_bits = (len(rare_idx_chars) - 1).bit_length() if rare_idx_chars else 0 + remap = {c: chr(ALPHABET_BASE + i) for i, c in enumerate(alphabet)} + remap.update({c: chr(RARE_IDX_BASE + i) for i, c in enumerate(rare_idx_chars)}) + remap.update({c: chr(RARE_RAW_BASE + i) for i, c in enumerate(rare_raw_chars)}) + word_start = ALPHABET_BASE + len(alphabet) + max_words = 0x100 - word_start if compression_level >= 5 else 0 + + texts = [remap_text(t, remap) for t in original_texts] + + # Prune the qstrs to only those that appear in the texts + qstr_counters = collections.Counter() + qstr_extractor = TextSplitter(all_qstr_strs) + for t in texts: + for qstr in qstr_extractor.iter(t): + if qstr in qstrs: + qstr_counters[qstr] += 1 + qstr_strs = list(qstr_counters.keys()) + + words = find_words(texts, qstrs, qstr_strs, max_words) + + # Now that the dictionary is fixed, find the tokenization of each string + # that takes the fewest bits, with Huffman codes chosen per class of the + # previous character. Code lengths and tokenization depend on each other, + # so iterate a few rounds from the greedy tokenization; the final + # tokenization and the codes built from it are what get emitted, so they + # are always consistent. + dp_qstrs = qstr_strs if use_qstrs else [] + # Upper bound on the qstr index width while parsing; the real width is computed below. + est_qstr_bits = max([0] + [qstrs[q] for q in dp_qstrs]).bit_length() + words_by_first = collections.defaultdict(list) + for w in words: + words_by_first[w[0]].append(w) + qstrs_by_first = collections.defaultdict(list) + for q in dp_qstrs: + qstrs_by_first[q[0]].append(q) + + greedy = TextSplitter(words + dp_qstrs) + greedy_tokens = {} + for t in texts: + greedy_tokens[t] = [("q", a) if a in qstrs else a for a in greedy.iter(t)] + + def table_bytes(class_map, counts, used_words): + nclasses = max(class_map) + 1 + row = max(max(code_lengths(cn).values()) for cn in counts.values()) + 1 + n = sum(len(cn) for cn in counts.values()) # values + n += nclasses * row # lengths + n += 2 * (nclasses + 1) # values_offset + n += NUM_BASE_CLASSES # class_map + n += sum(len(w) for w in used_words) # words + if used_words: + n += len(used_words[-1]) - len(used_words[0]) + 1 # wlencount + n += 2 * len(alphabet) + n += 2 * len(rare_idx_chars) + return n + + best = None + for preset in CLASS_PRESETS: + class_map = class_map_for(preset) + tokens = greedy_tokens + counts = tally(texts, tokens, class_map) + lens = {cls: code_lengths(cn) for cls, cn in counts.items()} + for _ in range(3): + tokens = { + t: parse_optimal( + t, + lens, + class_map, + words_by_first, + qstrs_by_first, + est_qstr_bits, + rare_index_bits, + ) + for t in texts + } + counts = tally(texts, tokens, class_map) + lens = {cls: code_lengths(cn) for cls, cn in counts.items()} + used_symbols = set().union(*counts.values()) + used_words = sorted((w for w in words if w in used_symbols), key=len) + size = table_bytes(class_map, counts, used_words) + sum( + ( + encoded_length_bits + + encoded_bits(t, tokens[t], lens, class_map, est_qstr_bits, rare_index_bits) + + 7 + ) + // 8 + for t in texts + ) + if best is None or size < best[0]: + best = (size, class_map, tokens, lens, used_words) + size, class_map, tokens, lens, words = best + return size, dict( + class_map=class_map, + tokens=tokens, + lens=lens, + words=words, + alphabet=alphabet, + rare_idx_chars=rare_idx_chars, + rare_raw_chars=rare_raw_chars, + rare_index_bits=rare_index_bits, + remap=remap, + word_start=word_start, + ) - splitters = words[:] - if compression_level > 3: - splitters.extend(qstr_strs) + size, r = min((encode(k) for k in dense_tries), key=lambda x: x[0]) + class_map = r["class_map"] + tokens = r["tokens"] + lens = r["lens"] + words = r["words"] + alphabet = r["alphabet"] + rare_idx_chars = r["rare_idx_chars"] + rare_raw_chars = r["rare_raw_chars"] + rare_index_bits = r["rare_index_bits"] + remap = r["remap"] + word_start = r["word_start"] - words.sort(key=len) - extractor = TextSplitter(splitters) - counter = collections.Counter() used_qstr = 0 - for t in texts: - for atom in extractor.iter(t): - if atom in qstrs: - used_qstr = max(used_qstr, qstrs[atom]) - atom = "\1" - counter[atom] += 1 - cb = huffman.codebook(counter.items()) + for toks in tokens.values(): + for tok in toks: + if is_qstr(tok): + used_qstr = max(used_qstr, qstrs[tok[1]]) + translation_qstr_bits = used_qstr.bit_length() - word_start = start_unused word_end = word_start + len(words) - 1 - f.write(f"// # words {len(words)}\n") - f.write(f"// words {words}\n") - - values = [] - length_count = {} - renumbered = 0 - last_length = None - canonical = {} - for atom, code in sorted(cb.items(), key=lambda x: (len(x[1]), x[0])): - if atom in qstr_strs: - atom = "\1" - values.append(atom) - length = len(code) - if length not in length_count: - length_count[length] = 0 - length_count[length] += 1 - if last_length: - renumbered <<= length - last_length - # print(f"atom={repr(atom)} code={code}", file=sys.stderr) - canonical[atom] = "{0:0{width}b}".format(renumbered, width=length) - if len(atom) > 1: - o = words.index(atom) + 0x80 - s = "".join(C_ESCAPES.get(ch1, ch1) for ch1 in atom) - f.write(f"// {o} {s} {counter[atom]} {canonical[atom]} {renumbered}\n") - else: - s = C_ESCAPES.get(atom, atom) - canonical[atom] = "{0:0{width}b}".format(renumbered, width=length) - o = ord(atom) - f.write(f"// {o} {s} {counter[atom]} {canonical[atom]} {renumbered}\n") - renumbered += 1 - last_length = length - lengths = bytearray() - f.write(f"// length count {length_count}\n") + word_code = {w: chr(word_start + i) for i, w in enumerate(words)} - for i in range(1, max(length_count) + 2): - lengths.append(length_count.get(i, 0)) - f.write(f"// values {values} lengths {len(lengths)} {lengths}\n") + def symbol_value(sym): + return ord(word_code.get(sym, sym)) - f.write(f"// {values} {lengths}\n") - values = [(atom if len(atom) == 1 else chr(0x80 + words.index(atom))) for atom in values] - max_translation_encoded_length = max( - len(translation.encode("utf-8")) for (original, translation) in translations - ) + nclasses = max(class_map) + 1 + values = [] + lengths_rows = [] + canonical = [] + for cls in range(nclasses): + # Symbols are ordered by (length, value) so that the C decoder's canonical + # walk lands on the same index. + table = lens.get(cls, {}) + by_value = {chr(symbol_value(s)): l for s, l in table.items()} + v, counts_row, canon = canonical_codes(by_value) + values.append([ord(x) for x in v]) + lengths_rows.append(counts_row) + canonical.append({s: canon[chr(symbol_value(s))] for s in table}) + lengths_row = max(1, max(len(r) for r in lengths_rows)) + lengths_rows = [r + [0] * (lengths_row - len(r)) for r in lengths_rows] + assert all(len(code) >= 1 for canon in canonical for code in canon.values()) + assert all(v < 0x100 for vs in values for v in vs) + + unmap = {v: k for k, v in remap.items()} + f.write(f"// # words {len(words)}\n") + f.write("// words {}\n".format([remap_text(w, unmap) for w in words])) + f.write(f"// # alphabet {len(alphabet)}\n") + f.write(f"// # rare chars by index {len(rare_idx_chars)}, raw {len(rare_raw_chars)}\n") + f.write(f"// class_map {class_map} tables {nclasses}\n") + for cls in range(nclasses): + f.write(f"// class {cls}: {len(values[cls])} symbols, lengths {lengths_rows[cls]}\n") maxlen = len(words[-1]) if words else 0 minlen = len(words[0]) if words else 0 wlencount = [len([None for w in words if len(w) == l]) for l in range(minlen, maxlen + 1)] - translation_qstr_bits = used_qstr.bit_length() - - f.write("typedef {} mchar_t;\n".format(values_type)) - f.write("const uint8_t lengths[] = {{ {} }};\n".format(", ".join(map(str, lengths)))) + f.write("#define compress_max_length_bits ({})\n".format(encoded_length_bits)) + f.write("#define TRANSLATION_CLASSES {}\n".format(nclasses)) + f.write("#define LENGTHS_ROW {}\n".format(lengths_row)) f.write( - "const mchar_t values[] = {{ {} }};\n".format( - ", ".join(str(ord(remove_offset(u))) for u in values) + "const uint8_t class_map[{}] = {{ {} }};\n".format( + NUM_BASE_CLASSES, ", ".join(map(str, class_map)) ) ) f.write( - "#define compress_max_length_bits ({})\n".format( - max_translation_encoded_length.bit_length() + "const uint8_t lengths[] = {{ {} }};\n".format( + ", ".join(str(x) for row in lengths_rows for x in row) ) ) + offsets = [0] + for v in values: + offsets.append(offsets[-1] + len(v)) f.write( - "const mchar_t words[] = {{ {} }};\n".format( - ", ".join(str(ord(remove_offset(c))) for w in words for c in w) + "const uint16_t values_offset[{}] = {{ {} }};\n".format( + nclasses + 1, ", ".join(map(str, offsets)) + ) + ) + f.write( + "const uint8_t values[] = {{ {} }};\n".format(", ".join(str(x) for v in values for x in v)) + ) + f.write("#define alphabet_size {}\n".format(len(alphabet))) + f.write( + "const uint16_t alphabet[] = {{ {} }};\n".format(", ".join(str(ord(c)) for c in alphabet)) + ) + f.write("#define rare_index_count {}\n".format(len(rare_idx_chars))) + f.write("#define rare_index_bits {}\n".format(rare_index_bits)) + f.write("#define rare_raw_count {}\n".format(len(rare_raw_chars))) + f.write( + "const uint16_t rare_chars[] = {{ {} }};\n".format( + ", ".join(str(ord(c)) for c in rare_idx_chars) + ) + ) + f.write( + "const uint8_t words[] = {{ {} }};\n".format( + ", ".join(str(ord(c)) for w in words for c in w) ) ) f.write("const uint8_t wlencount[] = {{ {} }};\n".format(", ".join(str(p) for p in wlencount))) @@ -410,30 +741,33 @@ def est_net_savings(s, occ): f.write("#define word_end {}\n".format(word_end)) f.write("#define minlen {}\n".format(minlen)) f.write("#define maxlen {}\n".format(maxlen)) - f.write("#define translation_offstart {}\n".format(offstart)) - f.write("#define translation_offset {}\n".format(offset)) f.write("#define translation_qstr_bits {}\n".format(translation_qstr_bits)) qstrs_inv = dict((v, k) for k, v in qstrs.items()) return EncodingTable( values, - lengths, - words, + lengths_rows, + lengths_row, + class_map, canonical, - extractor, - apply_offset, - remove_offset, + words, + word_start, + alphabet, + rare_idx_chars, + rare_index_bits, + remap, translation_qstr_bits, qstrs, qstrs_inv, + tokens, ) def decompress(encoding_table, encoded, encoded_length_bits): - qstrs_inv = encoding_table.qstrs_inv - values = encoding_table.values - lengths = encoding_table.lengths - words = encoding_table.words + """Decode as the C decoder does (translate.c). Returns the original text.""" + et = encoding_table + alphabet_size = len(et.alphabet) + word_end = et.word_start + len(et.words) - 1 def bititer(): for byte in encoded: @@ -449,10 +783,25 @@ def getnbits(n): return bits dec = [] + last = None length = getnbits(encoded_length_bits) + decoded = 0 + + def emit_char(c): + nonlocal last, decoded + dec.append(c) + decoded += len(c.encode("utf-8")) + last = c[-1] - i = 0 - while i < length: + def emit(u): + if ALPHABET_BASE <= u < ALPHABET_BASE + alphabet_size: + emit_char(et.alphabet[u - ALPHABET_BASE]) + else: + emit_char(chr(u)) + + while decoded < length: + cls = et.class_map[base_class(last)] + lengths = et.lengths[cls] bits = 0 bit_length = 0 max_code = lengths[0] @@ -461,28 +810,33 @@ def getnbits(n): bits = (bits << 1) | nextbit() bit_length += 1 if max_code > 0 and bits < max_code: - # print('{0:0{width}b}'.format(bits, width=bit_length)) break max_code = (max_code << 1) + lengths[bit_length] searched_length += lengths[bit_length] - - v = values[searched_length + bits - max_code] - if v == chr(1): - qstr_idx = getnbits(encoding_table.translation_qstr_bits) - v = qstrs_inv[qstr_idx] - elif v >= chr(0x80) and v < chr(0x80 + len(words)): - v = words[ord(v) - 0x80] - i += len(v.encode("utf-8")) - dec.append(v) + v = et.values[cls][searched_length + bits - max_code] + if v == 1: + qstr_idx = getnbits(et.translation_qstr_bits) + emit_char(et.qstrs_inv[qstr_idx]) + elif v == 2: + emit_char(et.rare_idx_chars[getnbits(et.rare_index_bits)]) + elif v == 3: + emit_char(chr(getnbits(16))) + elif et.word_start <= v <= word_end: + for c in et.words[v - et.word_start]: + emit(ord(c)) + else: + emit(v) return "".join(dec) def compress(encoding_table, decompressed, encoded_length_bits, len_translation_encoded): + """Encode a translation using the tokenization chosen in compute_huffman_coding().""" if not isinstance(decompressed, str): raise TypeError() - qstrs = encoding_table.qstrs - canonical = encoding_table.canonical - extractor = encoding_table.extractor + et = encoding_table + text = remap_text(decompressed, et.remap) + tokens = et.tokens[text] + unmap = {v: k for k, v in et.remap.items()} enc = 1 @@ -494,17 +848,25 @@ def put_bits(enc, b, n): enc = put_bit(enc, b & (1 << i)) return enc + def put_code(enc, cls, sym): + for b in et.canonical[cls][sym]: + enc = put_bit(enc, b == "1") + return enc + enc = put_bits(enc, len_translation_encoded, encoded_length_bits) - for atom in extractor.iter(decompressed): - if atom in qstrs: - can = canonical["\1"] - else: - can = canonical[atom] - for b in can: - enc = put_bit(enc, b == "1") - if atom in qstrs: - enc = put_bits(enc, qstrs[atom], encoding_table.translation_qstr_bits) + pos = 0 + for tok in tokens: + cls = et.class_map[base_class(text[pos - 1] if pos else None)] + enc = put_code(enc, cls, token_symbol(tok)) + if is_qstr(tok): + enc = put_bits(enc, et.qstrs[tok[1]], et.translation_qstr_bits) + elif is_rare(tok): + if ord(tok) >= RARE_RAW_BASE: + enc = put_bits(enc, ord(unmap[tok]), 16) + else: + enc = put_bits(enc, ord(tok) - RARE_IDX_BASE, et.rare_index_bits) + pos += token_len(tok) while enc.bit_length() % 8 != 1: enc = put_bit(enc, 0) @@ -527,11 +889,24 @@ def esc_char(m): def parse_qstrs(infile): r = {} - rx = re.compile(r'QDEF[01]\([A-Za-z0-9_]+,\s*\d+,\s*\d+,\s*(?P"(?:[^"\\\\]*|\\.)")\)') + rx = re.compile( + # QDEFn(ident, hash, len, blob_offset, "str") + r'QDEF(?P[01])\([A-Za-z0-9_]+,\s*\d+,\s*\d+,\s*\d+,\s*(?P"(?:[^"\\\\]|\\.)*")\)' + ) content = infile.read() - for i, mat in enumerate(rx.findall(content, re.M)): - mat = eval(mat) - r[mat] = i + matches = rx.finditer(content) + qdef0_qstrs = [] + qdef1_qstrs = [] + for match in matches: + qstr = eval(match.group("cstr")) + if match.group("pool") == "0": + qdef0_qstrs.append(qstr) + else: + qdef1_qstrs.append(qstr) + for i, qstr in enumerate(qdef0_qstrs): + r[qstr] = i + for i, qstr in enumerate(qdef1_qstrs, start=len(qdef0_qstrs)): + r[qstr] = i return r diff --git a/py/makeversionhdr.py b/py/makeversionhdr.py index 4b45aa6d601..94321ef0bad 100644 --- a/py/makeversionhdr.py +++ b/py/makeversionhdr.py @@ -5,8 +5,6 @@ This script works with Python 3.7 and newer """ -from __future__ import print_function - import argparse import sys import os @@ -43,8 +41,8 @@ def make_version_header(repo_path, filename): build_date = datetime.date.today() if "SOURCE_DATE_EPOCH" in os.environ: - build_date = datetime.datetime.utcfromtimestamp( - int(os.environ["SOURCE_DATE_EPOCH"]) + build_date = datetime.datetime.fromtimestamp( + int(os.environ["SOURCE_DATE_EPOCH"]), datetime.timezone.utc ).date() # Generate the file with the git and version info diff --git a/py/malloc.c b/py/malloc.c index 60f0df7455d..5882a463323 100644 --- a/py/malloc.c +++ b/py/malloc.c @@ -24,6 +24,7 @@ * THE SOFTWARE. */ +#include #include #include #include @@ -69,6 +70,11 @@ #error MICROPY_ENABLE_FINALISER requires MICROPY_ENABLE_GC #endif +// CIRCUITPY-CHANGE: Add selective collect support to malloc to optimize GC for large buffers +#if MICROPY_ENABLE_SELECTIVE_COLLECT +#error MICROPY_ENABLE_SELECTIVE_COLLECT requires MICROPY_ENABLE_GC +#endif + static void *realloc_ext(void *ptr, size_t n_bytes, bool allow_move) { if (allow_move) { return realloc(ptr, n_bytes); @@ -82,9 +88,26 @@ static void *realloc_ext(void *ptr, size_t n_bytes, bool allow_move) { #endif // MICROPY_ENABLE_GC -void *m_malloc(size_t num_bytes) { - void *ptr = malloc(num_bytes); - if (ptr == NULL && num_bytes != 0) { +// CIRCUITPY-CHANGE: Add malloc helper to factor out flag handling and allow combinations. +void *m_malloc_helper(size_t num_bytes, uint8_t flags) { + void *ptr; + #if MICROPY_ENABLE_GC + uint8_t gc_flags = 0; + #if MICROPY_ENABLE_SELECTIVE_COLLECT + if ((flags & M_MALLOC_COLLECT) == 0) { + gc_flags |= GC_ALLOC_FLAG_DO_NOT_COLLECT; + } + #endif + #if MICROPY_ENABLE_FINALISER + if ((flags & M_MALLOC_WITH_FINALISER) != 0) { + gc_flags |= GC_ALLOC_FLAG_HAS_FINALISER; + } + #endif + ptr = gc_alloc(num_bytes, gc_flags); + #else + ptr = malloc(num_bytes); + #endif + if (ptr == NULL && num_bytes != 0 && (flags & M_MALLOC_RAISE_ERROR)) { m_malloc_fail(num_bytes); } #if MICROPY_MEM_STATS @@ -92,44 +115,49 @@ void *m_malloc(size_t num_bytes) { MP_STATE_MEM(current_bytes_allocated) += num_bytes; UPDATE_PEAK(); #endif + // If this config is set then the GC clears all memory, so we don't need to. + #if !MICROPY_GC_CONSERVATIVE_CLEAR + if (flags & M_MALLOC_ENSURE_ZEROED) { + memset(ptr, 0, num_bytes); + } + #endif DEBUG_printf("malloc %d : %p\n", num_bytes, ptr); return ptr; } +void *m_malloc(size_t num_bytes) { + // CIRCUITPY-CHANGE: use helper + return m_malloc_helper(num_bytes, M_MALLOC_RAISE_ERROR | M_MALLOC_COLLECT); +} + void *m_malloc_maybe(size_t num_bytes) { - void *ptr = malloc(num_bytes); - #if MICROPY_MEM_STATS - MP_STATE_MEM(total_bytes_allocated) += num_bytes; - MP_STATE_MEM(current_bytes_allocated) += num_bytes; - UPDATE_PEAK(); - #endif - DEBUG_printf("malloc %d : %p\n", num_bytes, ptr); - return ptr; + // CIRCUITPY-CHANGE: use helper + return m_malloc_helper(num_bytes, M_MALLOC_COLLECT); } #if MICROPY_ENABLE_FINALISER void *m_malloc_with_finaliser(size_t num_bytes) { - void *ptr = malloc_with_finaliser(num_bytes); - if (ptr == NULL && num_bytes != 0) { - m_malloc_fail(num_bytes); - } - #if MICROPY_MEM_STATS - MP_STATE_MEM(total_bytes_allocated) += num_bytes; - MP_STATE_MEM(current_bytes_allocated) += num_bytes; - UPDATE_PEAK(); - #endif - DEBUG_printf("malloc %d : %p\n", num_bytes, ptr); - return ptr; + // CIRCUITPY-CHANGE: use helper + return m_malloc_helper(num_bytes, M_MALLOC_COLLECT | M_MALLOC_WITH_FINALISER); } #endif void *m_malloc0(size_t num_bytes) { - void *ptr = m_malloc(num_bytes); - // If this config is set then the GC clears all memory, so we don't need to. - #if !MICROPY_GC_CONSERVATIVE_CLEAR - memset(ptr, 0, num_bytes); - #endif - return ptr; + // CIRCUITPY-CHANGE: use helper + return m_malloc_helper(num_bytes, + (MICROPY_GC_CONSERVATIVE_CLEAR ? 0 : M_MALLOC_ENSURE_ZEROED) + | M_MALLOC_RAISE_ERROR | M_MALLOC_COLLECT); +} + +// CIRCUITPY-CHANGE: add selective collect +void *m_malloc_without_collect(size_t num_bytes) { + return m_malloc_helper(num_bytes, M_MALLOC_RAISE_ERROR); +} + +// CIRCUITPY-CHANGE: add selective collect +void *m_malloc_maybe_without_collect(size_t num_bytes) { + + return m_malloc_helper(num_bytes, 0); } #if MICROPY_MALLOC_USES_ALLOCATED_SIZE @@ -209,6 +237,31 @@ void m_free(void *ptr) #if MICROPY_TRACKED_ALLOC +#if MICROPY_PY_THREAD && !MICROPY_PY_THREAD_GIL +// If there's no GIL, use the GC recursive mutex to protect the tracked node linked list +// under m_tracked_head. +// +// (For ports with GIL, the expectation is to only call tracked alloc functions +// while holding the GIL.) + +static inline void m_tracked_node_lock(void) { + mp_thread_recursive_mutex_lock(&MP_STATE_MEM(gc_mutex), 1); +} + +static inline void m_tracked_node_unlock(void) { + mp_thread_recursive_mutex_unlock(&MP_STATE_MEM(gc_mutex)); +} + +#else + +static inline void m_tracked_node_lock(void) { +} + +static inline void m_tracked_node_unlock(void) { +} + +#endif + #define MICROPY_TRACKED_ALLOC_STORE_SIZE (!MICROPY_ENABLE_GC) typedef struct _m_tracked_node_t { @@ -220,8 +273,18 @@ typedef struct _m_tracked_node_t { uint8_t data[]; } m_tracked_node_t; +// Helper to get data size of a tracked node, abstracting MICROPY_TRACKED_ALLOC_STORE_SIZE. +static inline size_t get_tracked_node_size(m_tracked_node_t *node) { + #if MICROPY_TRACKED_ALLOC_STORE_SIZE + return node->size; + #else + return gc_nbytes(node) - sizeof(m_tracked_node_t); + #endif +} + #if MICROPY_DEBUG_VERBOSE static size_t m_tracked_count_links(size_t *nb) { + m_tracked_node_lock(); m_tracked_node_t *node = MP_STATE_VM(m_tracked_head); size_t n = 0; *nb = 0; @@ -234,6 +297,7 @@ static size_t m_tracked_count_links(size_t *nb) { #endif node = node->next; } + m_tracked_node_unlock(); return n; } #endif @@ -248,12 +312,14 @@ void *m_tracked_calloc(size_t nmemb, size_t size) { size_t n = m_tracked_count_links(&nb); DEBUG_printf("m_tracked_calloc(%u, %u) -> (%u;%u) %p\n", (int)nmemb, (int)size, (int)n, (int)nb, node); #endif + m_tracked_node_lock(); if (MP_STATE_VM(m_tracked_head) != NULL) { MP_STATE_VM(m_tracked_head)->prev = node; } node->prev = NULL; node->next = MP_STATE_VM(m_tracked_head); MP_STATE_VM(m_tracked_head) = node; + m_tracked_node_unlock(); #if MICROPY_TRACKED_ALLOC_STORE_SIZE node->size = nmemb * size; #endif @@ -263,6 +329,42 @@ void *m_tracked_calloc(size_t nmemb, size_t size) { return &node->data[0]; } +void *m_tracked_realloc(void *ptr_in, size_t n_bytes) { + // Handle pure allocation + if (ptr_in == NULL) { + return m_tracked_calloc(1, n_bytes); + } + + // Handle pure free + if (n_bytes == 0) { + m_tracked_free(ptr_in); + return NULL; + } + // To keep the implementation simple, we always allocate a new buffer and copy the old data into it. + // This could be optimised if faster performance or lower worst-case memory usage is required. + + // Get old size + // CIRCUITPY-CHANGE: cast to avoid compiler warning + m_tracked_node_t *old_node = (m_tracked_node_t *)(void *)((uint8_t *)ptr_in - sizeof(m_tracked_node_t)); + size_t old_size = get_tracked_node_size(old_node); + + // Allocate new buffer + void *new_ptr = m_tracked_calloc(1, n_bytes); + if (new_ptr == NULL) { + // Allocation failed, return NULL but leave original pointer intact + return NULL; + } + + // Copy data (minimum of old and new size) + size_t copy_size = MIN(old_size, n_bytes); + memcpy(new_ptr, ptr_in, copy_size); + + // Free old buffer + m_tracked_free(ptr_in); + + return new_ptr; +} + void m_tracked_free(void *ptr_in) { if (ptr_in == NULL) { return; @@ -271,15 +373,12 @@ void m_tracked_free(void *ptr_in) { m_tracked_node_t *node = (m_tracked_node_t *)(void *)((uint8_t *)ptr_in - sizeof(m_tracked_node_t)); #if MICROPY_DEBUG_VERBOSE size_t data_bytes; - #if MICROPY_TRACKED_ALLOC_STORE_SIZE - data_bytes = node->size; - #else - data_bytes = gc_nbytes(node); - #endif + data_bytes = get_tracked_node_size(node); size_t nb; size_t n = m_tracked_count_links(&nb); DEBUG_printf("m_tracked_free(%p, [%p, %p], nbytes=%u, links=%u;%u)\n", node, node->prev, node->next, (int)data_bytes, (int)n, (int)nb); - #endif + #endif // MICROPY_DEBUG_VERBOSE + m_tracked_node_lock(); if (node->next != NULL) { node->next->prev = node->prev; } @@ -288,6 +387,7 @@ void m_tracked_free(void *ptr_in) { } else { MP_STATE_VM(m_tracked_head) = node->next; } + m_tracked_node_unlock(); m_free(node #if MICROPY_MALLOC_USES_ALLOCATED_SIZE #if MICROPY_TRACKED_ALLOC_STORE_SIZE diff --git a/py/manifest.cmake b/py/manifest.cmake new file mode 100644 index 00000000000..446fb063b7e --- /dev/null +++ b/py/manifest.cmake @@ -0,0 +1,73 @@ +# Extract c_module() entries from MICROPY_FROZEN_MANIFEST and append them to +# USER_C_MODULES. Included from py/usermod.cmake; the port must have resolved +# MICROPY_FROZEN_MANIFEST (and any board-config default / cmake-command-line +# override) before usermod.cmake runs. +# +# Also sets default MICROPY_MANIFEST_* path variables that are forwarded to +# makemanifest.py here for c_module extraction and again from py/mkrules.cmake +# for the frozen content generation step, so both passes substitute the same +# values into manifest path expressions. + +if(MICROPY_FROZEN_MANIFEST) + # Set default path variables to be passed to makemanifest.py. These are + # available in path substitutions inside the manifest. Additional variables + # can be set per-board in mpconfigboard.cmake or on the cmake command line. + # MICROPY_LIB_DIR is set in py.cmake (included before usermod.cmake). + if(NOT DEFINED MICROPY_MANIFEST_PORT_DIR) + set(MICROPY_MANIFEST_PORT_DIR ${MICROPY_PORT_DIR}) + endif() + if(NOT DEFINED MICROPY_MANIFEST_BOARD_DIR) + set(MICROPY_MANIFEST_BOARD_DIR ${MICROPY_BOARD_DIR}) + endif() + if(NOT DEFINED MICROPY_MANIFEST_MPY_DIR) + set(MICROPY_MANIFEST_MPY_DIR ${MICROPY_DIR}) + endif() + if(NOT DEFINED MICROPY_MANIFEST_MPY_LIB_DIR) + set(MICROPY_MANIFEST_MPY_LIB_DIR ${MICROPY_LIB_DIR}) + endif() + + # Find all MICROPY_MANIFEST_* variables and turn them into command line + # arguments. Stored in MICROPY_MAKEMANIFEST_ARGS (outside the + # MICROPY_MANIFEST_ namespace) so it doesn't self-match the regex above + # on subsequent cmake configures. + get_cmake_property(_manifest_vars VARIABLES) + list(FILTER _manifest_vars INCLUDE REGEX "MICROPY_MANIFEST_.*") + set(MICROPY_MAKEMANIFEST_ARGS) + foreach(_manifest_var IN LISTS _manifest_vars) + list(APPEND MICROPY_MAKEMANIFEST_ARGS "-v") + string(REGEX REPLACE "MICROPY_MANIFEST_(.*)" "\\1" _manifest_var_name ${_manifest_var}) + list(APPEND MICROPY_MAKEMANIFEST_ARGS "${_manifest_var_name}=${${_manifest_var}}") + endforeach() + + # Skip extraction during UPDATE_SUBMODULES (require() would fail) and when + # micropython-lib is not initialised. Matches py/manifest.mk behaviour: + # warn and continue with an empty c_module list rather than fatal. + if(EXISTS ${MICROPY_FROZEN_MANIFEST} AND NOT UPDATE_SUBMODULES) + if(EXISTS ${MICROPY_LIB_DIR}/README.md) + if(NOT Python3_EXECUTABLE) + find_package(Python3 REQUIRED COMPONENTS Interpreter) + endif() + + execute_process( + COMMAND "${Python3_EXECUTABLE}" "${MICROPY_DIR}/tools/makemanifest.py" + --list-c-modules ${MICROPY_MAKEMANIFEST_ARGS} "${MICROPY_FROZEN_MANIFEST}" + OUTPUT_VARIABLE MANIFEST_C_MODULES + ERROR_VARIABLE MANIFEST_ERROR + OUTPUT_STRIP_TRAILING_WHITESPACE + RESULT_VARIABLE MANIFEST_RESULT + ) + + if(NOT MANIFEST_RESULT EQUAL 0) + message(FATAL_ERROR "Failed to extract C modules from manifest: ${MICROPY_FROZEN_MANIFEST}\nError: ${MANIFEST_ERROR}") + endif() + + if(MANIFEST_C_MODULES) + string(REPLACE "\n" ";" MANIFEST_C_MODULES_LIST "${MANIFEST_C_MODULES}") + list(APPEND USER_C_MODULES ${MANIFEST_C_MODULES_LIST}) + list(REMOVE_DUPLICATES USER_C_MODULES) + endif() + else() + message(WARNING "c_module() extraction skipped: micropython-lib not initialised, run 'make BOARD=${MICROPY_BOARD} submodules'") + endif() + endif() +endif() diff --git a/py/manifest.mk b/py/manifest.mk new file mode 100644 index 00000000000..43ad64be34e --- /dev/null +++ b/py/manifest.mk @@ -0,0 +1,58 @@ +# Manifest processing for freeze(), require(), include(), and c_module(). +# This file handles both C module extraction and frozen Python content generation. + +ifneq ($(FROZEN_MANIFEST),) + +# Set default path variables to be passed to makemanifest.py. These will be +# available in path substitutions. Additional variables can be set per-board +# in mpconfigboard.mk or on the make command line. +MICROPY_MANIFEST_PORT_DIR ?= $(CURDIR) +MICROPY_MANIFEST_BOARD_DIR ?= $(BOARD_DIR) +MICROPY_MANIFEST_MPY_DIR ?= $(TOP) +MICROPY_MANIFEST_MPY_LIB_DIR ?= $(MPY_LIB_DIR) + +# Find all MICROPY_MANIFEST_* variables and turn them into command line +# arguments. Values must not contain whitespace (GNU make word-splits). +MANIFEST_VARIABLES = $(foreach var,$(filter MICROPY_MANIFEST_%, $(.VARIABLES)),-v "$(subst MICROPY_MANIFEST_,,$(var))=$($(var))") + +# Skip c_module extraction for targets that don't need a build. +MANIFEST_NON_BUILD_GOALS := clean clean-prog submodules help print-cfg print-def +MANIFEST_GOALS := $(filter-out $(MANIFEST_NON_BUILD_GOALS),$(or $(MAKECMDGOALS),build)) + +# Extract C module paths up front so downstream rules see them. Skipped when +# micropython-lib isn't initialised (require() would fail) or for non-build +# targets. $(shell) collapses newlines, so c_module() paths cannot contain +# whitespace on the make side (the cmake side handles it correctly). +MANIFEST_C_MODULES := +ifneq ($(MANIFEST_GOALS),) +ifeq ($(wildcard $(FROZEN_MANIFEST)),$(FROZEN_MANIFEST)) +ifeq ($(wildcard $(MPY_LIB_DIR)/README.md),$(MPY_LIB_DIR)/README.md) +MANIFEST_C_MODULES := $(shell $(MAKE_MANIFEST) --list-c-modules $(MANIFEST_VARIABLES) $(FROZEN_MANIFEST)) +# Treat a populated, non-zero .SHELLSTATUS as failure. GNU make < 4.2 (eg +# macOS 3.81) leaves .SHELLSTATUS empty, in which case skip the check; an +# empty filter result means "succeed (status was 0, or unavailable)". +ifneq ($(filter-out 0,$(.SHELLSTATUS)),) +$(error makemanifest.py --list-c-modules failed (exit $(.SHELLSTATUS)) for $(FROZEN_MANIFEST)) +endif +else +$(warning c_module() extraction skipped: micropython-lib not initialised, run 'make submodules') +endif +endif +endif + +# Merge manifest c_modules into USER_C_MODULES. $(sort) also de-duplicates; +# this changes USER_C_MODULES iteration order vs cmake's list(REMOVE_DUPLICATES) +# which preserves first occurrence. Module include order should not be +# behaviour-sensitive so this is acceptable. +USER_C_MODULES := $(sort $(USER_C_MODULES) $(MANIFEST_C_MODULES)) + +# Frozen content rule, requires $(BUILD) and other variables from the port. +ifdef BUILD +# CIRCUITPY-CHANGE: FROZEN_MANIFEST is generated into $(BUILD) during the build +# (py/circuitpy_mpconfig.mk), so it must be a prerequisite here. +$(BUILD)/frozen_content.c: FORCE $(BUILD)/genhdr/qstrdefs.generated.h $(BUILD)/genhdr/root_pointers.h $(FROZEN_MANIFEST) | $(MICROPY_MPYCROSS_DEPENDENCY) + $(Q)test -e "$(MPY_LIB_DIR)/README.md" || (echo -e $(HELP_MPY_LIB_SUBMODULE); false) + $(Q)$(MAKE_MANIFEST) -o $@ $(MANIFEST_VARIABLES) -b "$(BUILD)" $(if $(MPY_CROSS_FLAGS),-f"$(MPY_CROSS_FLAGS)",) --mpy-tool-flags="$(MPY_TOOL_FLAGS)" $(FROZEN_MANIFEST) +endif + +endif # FROZEN_MANIFEST diff --git a/py/map.c b/py/map.c index d40e3dc4d02..c434e0d0cdd 100644 --- a/py/map.c +++ b/py/map.c @@ -86,13 +86,17 @@ static size_t get_hash_alloc_greater_or_equal_to(size_t x) { /******************************************************************************/ /* map */ +// CIRCUITPY-CHANGE: Helper for allocating tables of elements +#define malloc_table(num) m_new0(mp_map_elem_t, num) + void mp_map_init(mp_map_t *map, size_t n) { if (n == 0) { map->alloc = 0; map->table = NULL; } else { map->alloc = n; - map->table = m_new0(mp_map_elem_t, map->alloc); + // CIRCUITPY-CHANGE + map->table = malloc_table(map->alloc); } map->used = 0; map->all_keys_are_qstrs = 1; @@ -133,7 +137,8 @@ static void mp_map_rehash(mp_map_t *map) { size_t new_alloc = get_hash_alloc_greater_or_equal_to(map->alloc + 1); DEBUG_printf("mp_map_rehash(%p): " UINT_FMT " -> " UINT_FMT "\n", map, old_alloc, new_alloc); mp_map_elem_t *old_table = map->table; - mp_map_elem_t *new_table = m_new0(mp_map_elem_t, new_alloc); + // CIRCUITPY-CHANGE + mp_map_elem_t *new_table = malloc_table(new_alloc); // If we reach this point, table resizing succeeded, now we can edit the old map. map->alloc = new_alloc; map->used = 0; @@ -329,7 +334,8 @@ mp_map_elem_t *MICROPY_WRAP_MP_MAP_LOOKUP(mp_map_lookup)(mp_map_t * map, mp_obj_ void mp_set_init(mp_set_t *set, size_t n) { set->alloc = n; set->used = 0; - set->table = m_new0(mp_obj_t, set->alloc); + // CIRCUITPY-CHANGE + set->table = m_malloc_items0(set->alloc); } static void mp_set_rehash(mp_set_t *set) { @@ -337,7 +343,8 @@ static void mp_set_rehash(mp_set_t *set) { mp_obj_t *old_table = set->table; set->alloc = get_hash_alloc_greater_or_equal_to(set->alloc + 1); set->used = 0; - set->table = m_new0(mp_obj_t, set->alloc); + // CIRCUITPY-CHANGE + set->table = m_malloc_items0(set->alloc); for (size_t i = 0; i < old_alloc; i++) { if (old_table[i] != MP_OBJ_NULL && old_table[i] != MP_OBJ_SENTINEL) { mp_set_lookup(set, old_table[i], MP_MAP_LOOKUP_ADD_IF_NOT_FOUND); diff --git a/py/misc.h b/py/misc.h index 769d12ddbee..a7498e66d17 100644 --- a/py/misc.h +++ b/py/misc.h @@ -26,6 +26,9 @@ #ifndef MICROPY_INCLUDED_PY_MISC_H #define MICROPY_INCLUDED_PY_MISC_H +#include +#include "py/mpconfig.h" + // a mini library of useful types and functions /** types *******************************************************/ @@ -33,13 +36,25 @@ #include #include #include - -// CIRCUITPY-CHANGE: include directly instead of depending on previous includes -#include "mpconfig.h" +// CIRCUITPY-CHANGE: #ifdef instead of #if +#ifdef __cplusplus // Required on at least one compiler to get ULLONG_MAX +#include +#else +#include +#endif typedef unsigned char byte; typedef unsigned int uint; +#ifndef __has_builtin +#define __has_builtin(x) (0) +#endif +#ifndef __has_feature +// This macro is supported by Clang and gcc>=14 +#define __has_feature(x) (0) +#endif + + /** generic ops *************************************************/ #ifndef MIN @@ -54,7 +69,15 @@ typedef unsigned int uint; #define MP_STRINGIFY(x) MP_STRINGIFY_HELPER(x) // Static assertion macro +// CIRCUITPY-CHANGE: defined() +#if defined(__cplusplus) +#define MP_STATIC_ASSERT(cond) static_assert((cond), #cond) +#elif __GNUC__ >= 5 || __STDC_VERSION__ >= 201112L +#define MP_STATIC_ASSERT(cond) _Static_assert((cond), #cond) +#else #define MP_STATIC_ASSERT(cond) ((void)sizeof(char[1 - 2 * !(cond)])) +#endif + // In C++ things like comparing extern const pointers are not constant-expressions so cannot be used // in MP_STATIC_ASSERT. Note that not all possible compiler versions will reject this. Some gcc versions // do, others only with -Werror=vla, msvc always does. @@ -63,7 +86,11 @@ typedef unsigned int uint; #if defined(_MSC_VER) || defined(__cplusplus) #define MP_STATIC_ASSERT_NONCONSTEXPR(cond) ((void)1) #else -#define MP_STATIC_ASSERT_NONCONSTEXPR(cond) MP_STATIC_ASSERT(cond) +// CIRCUITPY-CHANGE: defined() +#if defined(__clang__) +#pragma GCC diagnostic ignored "-Wgnu-folding-constant" +#endif +#define MP_STATIC_ASSERT_NONCONSTEXPR(cond) ((void)sizeof(char[1 - 2 * !(cond)])) #endif // Round-up integer division @@ -74,6 +101,15 @@ typedef unsigned int uint; // TODO make a lazy m_renew that can increase by a smaller amount than requested (but by at least 1 more element) +// CIRCUITPY-CHANGE: new wrappers for selective collect, and use of m_malloc_helper() +// The following are convenience wrappers for m_malloc_helper and can save space at the call sites. +// m_malloc and m_new allocate space that is collected and does not have a finaliser. Use +// m_malloc_without_collect() if the space will not contain pointers to other heap allocations. It +// will still be marked and swept but not scanned for other pointers. +// Use m_malloc_items() to allocate space for mp_obj_ts that will be collected. +// Use mp_obj_malloc*() to allocate space for objects (aka structs with a type pointer) that will be +// collected. + #define m_new(type, num) ((type *)(m_malloc(sizeof(type) * (num)))) #define m_new_maybe(type, num) ((type *)(m_malloc_maybe(sizeof(type) * (num)))) #define m_new0(type, num) ((type *)(m_malloc0(sizeof(type) * (num)))) @@ -95,10 +131,25 @@ typedef unsigned int uint; #endif #define m_del_obj(type, ptr) (m_del(type, ptr, 1)) +#define m_malloc_items(num) m_malloc(sizeof(mp_obj_t) * (num)) +#define m_malloc_items0(num) m_malloc0(sizeof(mp_obj_t) * (num)) + +// Flags for m_malloc_helper +#define M_MALLOC_ENSURE_ZEROED (1 << 0) +#define M_MALLOC_RAISE_ERROR (1 << 1) +#define M_MALLOC_COLLECT (1 << 2) +#define M_MALLOC_WITH_FINALISER (1 << 3) + +void *m_malloc_helper(size_t num_bytes, uint8_t flags); void *m_malloc(size_t num_bytes); void *m_malloc_maybe(size_t num_bytes); void *m_malloc_with_finaliser(size_t num_bytes); void *m_malloc0(size_t num_bytes); + +// CIRCUITPY-CHANGE: _without_collect +void *m_malloc_without_collect(size_t num_bytes); +void *m_malloc_maybe_without_collect(size_t num_bytes); + #if MICROPY_MALLOC_USES_ALLOCATED_SIZE void *m_realloc(void *ptr, size_t old_num_bytes, size_t new_num_bytes); void *m_realloc_maybe(void *ptr, size_t old_num_bytes, size_t new_num_bytes, bool allow_move); @@ -108,12 +159,13 @@ void *m_realloc(void *ptr, size_t new_num_bytes); void *m_realloc_maybe(void *ptr, size_t new_num_bytes, bool allow_move); void m_free(void *ptr); #endif -NORETURN void m_malloc_fail(size_t num_bytes); +MP_NORETURN void m_malloc_fail(size_t num_bytes); #if MICROPY_TRACKED_ALLOC // These alloc/free functions track the pointers in a linked list so the GC does not reclaim // them. They can be used by code that requires traditional C malloc/free semantics. void *m_tracked_calloc(size_t nmemb, size_t size); +void *m_tracked_realloc(void *ptr_in, size_t n_bytes); void m_tracked_free(void *ptr_in); #endif @@ -131,7 +183,7 @@ size_t m_get_peak_bytes_allocated(void); // align ptr to the nearest multiple of "alignment" #define MP_ALIGN(ptr, alignment) (void *)(((uintptr_t)(ptr) + ((alignment) - 1)) & ~((alignment) - 1)) -// CIRCUITPY-CHANGE +// CIRCUITPY-CHANGE: addition #define sizeof_field(TYPE, MEMBER) sizeof((((TYPE *)0)->MEMBER)) /** unichar / UTF-8 *********************************************/ @@ -214,33 +266,31 @@ void vstr_add_byte(vstr_t *vstr, byte v); void vstr_add_char(vstr_t *vstr, unichar chr); void vstr_add_str(vstr_t *vstr, const char *str); void vstr_add_strn(vstr_t *vstr, const char *str, size_t len); -void vstr_ins_byte(vstr_t *vstr, size_t byte_pos, byte b); -void vstr_ins_char(vstr_t *vstr, size_t char_pos, unichar chr); +char *vstr_ins_blank_bytes(vstr_t *vstr, size_t byte_pos, size_t byte_len); +static inline void vstr_ins_byte(vstr_t *vstr, size_t byte_pos, byte b) { + char *s = vstr_ins_blank_bytes(vstr, byte_pos, 1); + *s = b; +} +static inline void vstr_ins_char(vstr_t *vstr, size_t char_pos, unichar chr) { + // TODO UNICODE + char *s = vstr_ins_blank_bytes(vstr, char_pos, 1); + *s = (char)chr; +} +static inline void vstr_ins_strn(vstr_t *vstr, size_t byte_pos, const char *str, size_t len) { + char *s = vstr_ins_blank_bytes(vstr, byte_pos, len); + memcpy(s, str, len); +} void vstr_cut_head_bytes(vstr_t *vstr, size_t bytes_to_cut); void vstr_cut_tail_bytes(vstr_t *vstr, size_t bytes_to_cut); void vstr_cut_out_bytes(vstr_t *vstr, size_t byte_pos, size_t bytes_to_cut); void vstr_printf(vstr_t *vstr, const char *fmt, ...); - -/** non-dynamic size-bounded variable buffer/string *************/ - -#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; } -#define CHECKBUF_APPEND_0(buf) { *buf##_p = 0; } -#define CHECKBUF_LEN(buf) (buf##_p - buf) - #ifdef va_start void vstr_vprintf(vstr_t *vstr, const char *fmt, va_list ap); #endif -// Debugging helpers -int DEBUG_printf(const char *fmt, ...); +/** debugging helpers *******************************************/ -extern mp_uint_t mp_verbose_flag; +int DEBUG_printf(const char *fmt, ...); /** float internals *************/ @@ -278,6 +328,25 @@ typedef union _mp_float_union_t { mp_float_uint_t i; } mp_float_union_t; +#if MICROPY_FLOAT_FORMAT_IMPL == MICROPY_FLOAT_FORMAT_IMPL_EXACT + +#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT +// Exact float conversion requires using internally a bigger sort of floating point +typedef double mp_large_float_t; +#elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE +typedef long double mp_large_float_t; +#endif +// Always use a 64 bit mantissa for formatting and parsing +typedef uint64_t mp_large_float_uint_t; + +#else // MICROPY_FLOAT_FORMAT_IMPL != MICROPY_FLOAT_FORMAT_IMPL_EXACT + +// No bigger floating points +typedef mp_float_t mp_large_float_t; +typedef mp_float_uint_t mp_large_float_uint_t; + +#endif + #endif // MICROPY_PY_BUILTINS_FLOAT /** ROM string compression *************/ @@ -343,4 +412,204 @@ typedef const char *mp_rom_error_text_t; // For now, forward directly to MP_COMPRESSED_ROM_TEXT. #define MP_ERROR_TEXT(x) (mp_rom_error_text_t)MP_COMPRESSED_ROM_TEXT(x) +// Portable implementations of CLZ and CTZ intrinsics +#ifdef _MSC_VER +#include + +static inline uint32_t mp_clz(uint32_t x) { + unsigned long lz = 0; + return _BitScanReverse(&lz, x) ? (sizeof(x) * 8 - 1) - lz : 0; +} + +static inline uint32_t mp_clzl(unsigned long x) { + unsigned long lz = 0; + return _BitScanReverse(&lz, x) ? (sizeof(x) * 8 - 1) - lz : 0; +} + +#ifdef _WIN64 +static inline uint32_t mp_clzll(unsigned long long x) { + unsigned long lz = 0; + return _BitScanReverse64(&lz, x) ? (sizeof(x) * 8 - 1) - lz : 0; +} +#else +// Microsoft don't ship _BitScanReverse64 on Win32, so emulate it +static inline uint32_t mp_clzll(unsigned long long x) { + unsigned long h = x >> 32; + return h ? mp_clzl(h) : (mp_clzl((unsigned long)x) + 32); +} +#endif + +static inline uint32_t mp_ctz(uint32_t x) { + unsigned long tz = 0; + return _BitScanForward(&tz, x) ? tz : 0; +} + +static inline uint32_t mp_popcount(uint32_t x) { + return __popcnt(x); +} +#else // _MSC_VER +#define mp_clz(x) __builtin_clz(x) +#define mp_clzl(x) __builtin_clzl(x) +#define mp_clzll(x) __builtin_clzll(x) +#define mp_ctz(x) __builtin_ctz(x) +#if __has_builtin(__builtin_popcount) +#define mp_popcount(x) __builtin_popcount(x) +#else +static inline uint32_t mp_popcount(uint32_t x) { + x = x - ((x >> 1) & 0x55555555); + x = (x & 0x33333333) + ((x >> 2) & 0x33333333); + x = (x + (x >> 4)) & 0x0F0F0F0F; + return (x * 0x01010101) >> 24; +} +#endif // __has_builtin(__builtin_popcount) +#endif // _MSC_VER + +#define MP_FIT_UNSIGNED(bits, value) (((value) & (~0U << (bits))) == 0) +#define MP_FIT_SIGNED(bits, value) \ + (MP_FIT_UNSIGNED(((bits) - 1), (value)) || \ + (((value) & (~0U << ((bits) - 1))) == (~0U << ((bits) - 1)))) + +// mp_int_t can be larger than long, i.e. Windows 64-bit, nan-box variants +static inline uint32_t mp_clz_mpi(mp_int_t x) { + #ifdef __XC16__ + mp_uint_t mask = MP_OBJ_WORD_MSBIT_HIGH; + mp_uint_t zeroes = 0; + while (mask != 0) { + if (mask & (mp_uint_t)x) { + break; + } + zeroes++; + mask >>= 1; + } + return zeroes; + #else + #if MP_INT_MAX == INT_MAX + return mp_clz((unsigned)x); + #elif MP_INT_MAX == LONG_MAX + return mp_clzl((unsigned long)x); + #elif MP_INT_MAX == LLONG_MAX + return mp_clzll((unsigned long long)x); + #else + #error Unexpected MP_INT_MAX value + #endif + #endif +} + +// Overflow-checked operations + +// Integer overflow builtins were added to GCC 5, but __has_builtin only in GCC 10 +// +// Note that the builtins has a defined result when overflow occurs, whereas the custom +// functions below don't update the result if an overflow would occur (to avoid UB). +#define MP_GCC_HAS_BUILTIN_OVERFLOW (__GNUC__ >= 5) + +#if MICROPY_USE_GCC_MUL_OVERFLOW_INTRINSIC + +#define mp_mul_ull_overflow __builtin_umulll_overflow +#define mp_mul_ll_overflow __builtin_smulll_overflow +static inline bool mp_mul_mp_int_t_overflow(mp_int_t x, mp_int_t y, mp_int_t *res) { + // __builtin_mul_overflow is a type-generic function, this inline ensures the argument + // types are checked to match mp_int_t. + return __builtin_mul_overflow(x, y, res); +} + +#else + +bool mp_mul_ll_overflow(long long int x, long long int y, long long int *res); +bool mp_mul_mp_int_t_overflow(mp_int_t x, mp_int_t y, mp_int_t *res); +static inline bool mp_mul_ull_overflow(unsigned long long int x, unsigned long long int y, unsigned long long int *res) { + if (y > 0 && x > (ULLONG_MAX / y)) { + return true; // overflow + } + *res = x * y; + return false; +} + +#endif + +#if __has_builtin(__builtin_saddll_overflow) || MP_GCC_HAS_BUILTIN_OVERFLOW +#define mp_add_ll_overflow __builtin_saddll_overflow +#else +static inline bool mp_add_ll_overflow(long long int lhs, long long int rhs, long long int *res) { + bool overflow; + + if (rhs > 0) { + overflow = (lhs > LLONG_MAX - rhs); + } else { + overflow = (lhs < LLONG_MIN - rhs); + } + + if (!overflow) { + *res = lhs + rhs; + } + + return overflow; +} +#endif + +#if __has_builtin(__builtin_ssubll_overflow) || MP_GCC_HAS_BUILTIN_OVERFLOW +#define mp_sub_ll_overflow __builtin_ssubll_overflow +#else +static inline bool mp_sub_ll_overflow(long long int lhs, long long int rhs, long long int *res) { + bool overflow; + + if (rhs > 0) { + overflow = (lhs < LLONG_MIN + rhs); + } else { + overflow = (lhs > LLONG_MAX + rhs); + } + + if (!overflow) { + *res = lhs - rhs; + } + + return overflow; +} +#endif + + +// Helper macros for detecting if sanitizers are enabled +// +// Use sparingly, not for masking issues reported by sanitizers! +// +// Can be detected automatically in Clang and gcc>=14, need to be +// set manually otherwise. +#ifndef MP_UBSAN +#define MP_UBSAN __has_feature(undefined_behavior_sanitizer) +#endif + +#ifndef MP_ASAN +#define MP_ASAN __has_feature(address_sanitizer) +#endif + +#ifndef MP_SANITIZER_BUILD +#define MP_SANITIZER_BUILD (MP_UBSAN || MP_ASAN) +#endif + +// halfword/word/longword swapping macros + +#if __has_builtin(__builtin_bswap16) +#define MP_BSWAP16(x) __builtin_bswap16(x) +#else +#define MP_BSWAP16(x) ((uint16_t)((((x) & 0xFF) << 8) | (((x) >> 8) & 0xFF))) +#endif + +#if __has_builtin(__builtin_bswap32) +#define MP_BSWAP32(x) __builtin_bswap32(x) +#else +#define MP_BSWAP32(x) \ + ((uint32_t)((((x) & 0xFF) << 24) | (((x) & 0xFF00) << 8) | \ + (((x) >> 8) & 0xFF00) | (((x) >> 24) & 0xFF))) +#endif + +#if __has_builtin(__builtin_bswap64) +#define MP_BSWAP64(x) __builtin_bswap64(x) +#else +#define MP_BSWAP64(x) \ + ((uint64_t)((((x) & 0xFF) << 56) | (((x) & 0xFF00) << 40) | \ + (((x) & 0xFF0000) << 24) | (((x) & 0xFF000000) << 8) | \ + (((x) >> 8) & 0xFF000000) | (((x) >> 24) & 0xFF0000) | \ + (((x) >> 40) & 0xFF00) | (((x) >> 56) & 0xFF))) +#endif + #endif // MICROPY_INCLUDED_PY_MISC_H diff --git a/py/mkrules.cmake b/py/mkrules.cmake index bfc56abfe80..0903f81d897 100644 --- a/py/mkrules.cmake +++ b/py/mkrules.cmake @@ -14,11 +14,34 @@ set(MICROPY_MODULEDEFS "${MICROPY_GENHDR_DIR}/moduledefs.h") set(MICROPY_ROOT_POINTERS_SPLIT "${MICROPY_GENHDR_DIR}/root_pointers.split") set(MICROPY_ROOT_POINTERS_COLLECTED "${MICROPY_GENHDR_DIR}/root_pointers.collected") set(MICROPY_ROOT_POINTERS "${MICROPY_GENHDR_DIR}/root_pointers.h") +set(MICROPY_COMPRESSED_SPLIT "${MICROPY_GENHDR_DIR}/compressed.split") +set(MICROPY_COMPRESSED_COLLECTED "${MICROPY_GENHDR_DIR}/compressed.collected") +set(MICROPY_COMPRESSED_DATA "${MICROPY_GENHDR_DIR}/compressed.data.h") if(NOT MICROPY_PREVIEW_VERSION_2) set(MICROPY_PREVIEW_VERSION_2 0) endif() +# Set the board name. +if(MICROPY_BOARD) + if(MICROPY_BOARD_VARIANT) + set(MICROPY_BOARD_BUILD_NAME ${MICROPY_BOARD}-${MICROPY_BOARD_VARIANT}) + else() + set(MICROPY_BOARD_BUILD_NAME ${MICROPY_BOARD}) + endif() + + target_compile_definitions(${MICROPY_TARGET} PRIVATE + MICROPY_BOARD_BUILD_NAME="${MICROPY_BOARD_BUILD_NAME}" + ) +endif() + +# Need to do this before extracting MICROPY_CPP_DEF below. +if(MICROPY_ROM_TEXT_COMPRESSION) + target_compile_definitions(${MICROPY_TARGET} PUBLIC + MICROPY_ROM_TEXT_COMPRESSION=\(1\) + ) +endif() + # Need to do this before extracting MICROPY_CPP_DEF below. Rest of frozen # manifest handling is at the end of this file. if(MICROPY_FROZEN_MANIFEST) @@ -53,6 +76,15 @@ foreach(_arg ${MICROPY_CPP_DEF}) endforeach() list(APPEND MICROPY_CPP_FLAGS ${MICROPY_CPP_FLAGS_EXTRA}) +# Include anything passed in via CFLAGS_EXTRA +# in both MICROPY_CPP_FLAGS and CMAKE_C_FLAGS +if(DEFINED ENV{CFLAGS_EXTRA}) + set(CFLAGS_EXTRA $ENV{CFLAGS_EXTRA}) + string(APPEND CMAKE_C_FLAGS " ${CFLAGS_EXTRA}") # ... not a list + separate_arguments(CFLAGS_EXTRA) + list(APPEND MICROPY_CPP_FLAGS ${CFLAGS_EXTRA}) # ... a list +endif() + find_package(Python3 REQUIRED COMPONENTS Interpreter) target_sources(${MICROPY_TARGET} PRIVATE @@ -62,6 +94,18 @@ target_sources(${MICROPY_TARGET} PRIVATE ${MICROPY_ROOT_POINTERS} ) +if(MICROPY_ROM_TEXT_COMPRESSION) + target_sources(${MICROPY_TARGET} PRIVATE + ${MICROPY_COMPRESSED_DATA} + ) +endif() + +# Ensure genhdr directory is removed on clean + +set_property(TARGET ${MICROPY_TARGET} APPEND PROPERTY ADDITIONAL_CLEAN_FILES + "${MICROPY_GENHDR_DIR}" +) + # Command to force the build of another command # Generate mpversion.h @@ -175,28 +219,56 @@ add_custom_command( DEPENDS ${MICROPY_ROOT_POINTERS_COLLECTED} ${MICROPY_PY_DIR}/make_root_pointers.py ) +# Generate compressed.data.h + +add_custom_command( + OUTPUT ${MICROPY_COMPRESSED_SPLIT} + COMMAND ${Python3_EXECUTABLE} ${MICROPY_PY_DIR}/makeqstrdefs.py split compress ${MICROPY_QSTRDEFS_LAST} ${MICROPY_GENHDR_DIR}/compress _ + COMMAND touch ${MICROPY_COMPRESSED_SPLIT} + DEPENDS ${MICROPY_QSTRDEFS_LAST} + VERBATIM + COMMAND_EXPAND_LISTS +) + +add_custom_command( + OUTPUT ${MICROPY_COMPRESSED_COLLECTED} + COMMAND ${Python3_EXECUTABLE} ${MICROPY_PY_DIR}/makeqstrdefs.py cat compress _ ${MICROPY_GENHDR_DIR}/compress ${MICROPY_COMPRESSED_COLLECTED} + BYPRODUCTS "${MICROPY_COMPRESSED_COLLECTED}.hash" + DEPENDS ${MICROPY_COMPRESSED_SPLIT} + VERBATIM + COMMAND_EXPAND_LISTS +) + +add_custom_command( + OUTPUT ${MICROPY_COMPRESSED_DATA} + COMMAND ${Python3_EXECUTABLE} ${MICROPY_PY_DIR}/makecompresseddata.py ${MICROPY_COMPRESSED_COLLECTED} > ${MICROPY_COMPRESSED_DATA} + DEPENDS ${MICROPY_COMPRESSED_COLLECTED} ${MICROPY_PY_DIR}/makecompresseddata.py +) + # Build frozen code if enabled if(MICROPY_FROZEN_MANIFEST) set(MICROPY_FROZEN_CONTENT "${CMAKE_BINARY_DIR}/frozen_content.c") + set_property(TARGET ${MICROPY_TARGET} APPEND PROPERTY ADDITIONAL_CLEAN_FILES + "${CMAKE_BINARY_DIR}/frozen_mpy" + ) + target_sources(${MICROPY_TARGET} PRIVATE ${MICROPY_FROZEN_CONTENT} ) # Note: target_compile_definitions already added earlier. - if(NOT MICROPY_LIB_DIR) - string(CONCAT GIT_SUBMODULES "${GIT_SUBMODULES} " lib/micropython-lib) - set(MICROPY_LIB_DIR ${MICROPY_DIR}/lib/micropython-lib) + # Ensure micropython-lib is included in submodule updates, but only when + # MICROPY_LIB_DIR points at the in-tree submodule location; a user + # overriding MICROPY_LIB_DIR to an out-of-tree checkout shouldn't have + # the submodule updated. + if(MICROPY_LIB_DIR STREQUAL "${MICROPY_DIR}/lib/micropython-lib") + list(APPEND GIT_SUBMODULES lib/micropython-lib) endif() - if(ECHO_SUBMODULES) - # No-op, we're just doing submodule/variant discovery. - # Note: All the following rules are safe to run in discovery mode even - # though the submodule might not be available as they do not directly depend - # on anything from the submodule. - elseif(NOT EXISTS ${MICROPY_LIB_DIR}/README.md) + if(NOT UPDATE_SUBMODULES AND NOT EXISTS ${MICROPY_LIB_DIR}/README.md) message(FATAL_ERROR " micropython-lib not initialized.\n Run 'make BOARD=${MICROPY_BOARD} submodules'") endif() @@ -209,9 +281,13 @@ if(MICROPY_FROZEN_MANIFEST) if(NOT MICROPY_MAKE_EXECUTABLE) set(MICROPY_MAKE_EXECUTABLE make) endif() + # Clear FROZEN_MANIFEST/USER_C_MODULES in the mpy-cross sub-make so a + # shell-env FROZEN_MANIFEST=... doesn't leak in and trigger + # manifest.mk against the wrong cwd. mkrules.mk does the same for the + # make-based port path. add_custom_command( OUTPUT ${MICROPY_MPYCROSS_DEPENDENCY} - COMMAND ${MICROPY_MAKE_EXECUTABLE} -C ${MICROPY_DIR}/mpy-cross + COMMAND ${MICROPY_MAKE_EXECUTABLE} -C ${MICROPY_DIR}/mpy-cross USER_C_MODULES= FROZEN_MANIFEST= ) endif() @@ -221,27 +297,13 @@ if(MICROPY_FROZEN_MANIFEST) set(MICROPY_CROSS_FLAGS "-f${MICROPY_CROSS_FLAGS}") endif() - # Set default path variables to be passed to makemanifest.py. These will - # be available in path substitutions. Additional variables can be set - # per-board in mpconfigboard.cmake. - set(MICROPY_MANIFEST_PORT_DIR ${MICROPY_PORT_DIR}) - set(MICROPY_MANIFEST_BOARD_DIR ${MICROPY_BOARD_DIR}) - set(MICROPY_MANIFEST_MPY_DIR ${MICROPY_DIR}) - set(MICROPY_MANIFEST_MPY_LIB_DIR ${MICROPY_LIB_DIR}) - - # Find all MICROPY_MANIFEST_* variables and turn them into command line arguments. - get_cmake_property(_manifest_vars VARIABLES) - list(FILTER _manifest_vars INCLUDE REGEX "MICROPY_MANIFEST_.*") - foreach(_manifest_var IN LISTS _manifest_vars) - list(APPEND _manifest_var_args "-v") - string(REGEX REPLACE "MICROPY_MANIFEST_(.*)" "\\1" _manifest_var_name ${_manifest_var}) - list(APPEND _manifest_var_args "${_manifest_var_name}=${${_manifest_var}}") - endforeach() - + # MICROPY_MAKEMANIFEST_ARGS is populated by py/manifest.cmake (included via + # py/usermod.cmake before this file). Reuse that list so both the c_module + # extraction pass and the frozen content step substitute the same values. add_custom_target( BUILD_FROZEN_CONTENT ALL BYPRODUCTS ${MICROPY_FROZEN_CONTENT} - COMMAND ${Python3_EXECUTABLE} ${MICROPY_DIR}/tools/makemanifest.py -o ${MICROPY_FROZEN_CONTENT} ${_manifest_var_args} -b "${CMAKE_BINARY_DIR}" ${MICROPY_CROSS_FLAGS} --mpy-tool-flags=${MICROPY_MPY_TOOL_FLAGS} ${MICROPY_FROZEN_MANIFEST} + COMMAND ${Python3_EXECUTABLE} ${MICROPY_DIR}/tools/makemanifest.py -o ${MICROPY_FROZEN_CONTENT} ${MICROPY_MAKEMANIFEST_ARGS} -b "${CMAKE_BINARY_DIR}" ${MICROPY_CROSS_FLAGS} --mpy-tool-flags=${MICROPY_MPY_TOOL_FLAGS} ${MICROPY_FROZEN_MANIFEST} DEPENDS ${MICROPY_QSTRDEFS_GENERATED} ${MICROPY_ROOT_POINTERS} @@ -250,12 +312,29 @@ if(MICROPY_FROZEN_MANIFEST) ) endif() -# Update submodules -if(ECHO_SUBMODULES) - # If cmake is run with GIT_SUBMODULES defined on command line, process the port / board - # settings then print the final GIT_SUBMODULES variable and exit. - # Note: the GIT_SUBMODULES is done via echo rather than message, as message splits - # the output onto multiple lines - execute_process(COMMAND ${CMAKE_COMMAND} -E echo "GIT_SUBMODULES=${GIT_SUBMODULES}") - message(FATAL_ERROR "Done") +# Update submodules, this is invoked on some ports via 'make submodules'. +# +# Note: This logic has a Makefile equivalent in py/mkrules.mk +if(UPDATE_SUBMODULES AND GIT_SUBMODULES) + macro(run_git) + execute_process(COMMAND git ${ARGV} WORKING_DIRECTORY ${MICROPY_DIR} + RESULT_VARIABLE RES) + endmacro() + + list(JOIN GIT_SUBMODULES " " GIT_SUBMODULES_MSG) + message("Updating submodules: ${GIT_SUBMODULES_MSG}") + run_git(submodule sync ${GIT_SUBMODULES}) + if(RES EQUAL 0) + # If available, do blobless partial clones of submodules to save time and space. + # A blobless partial clone lazily fetches data as needed, but has all the metadata available (tags, etc.). + run_git(submodule update --init --filter=blob:none ${GIT_SUBMODULES}) + # Fallback to standard submodule update if blobless isn't available (earlier than git 2.36.0) + if (NOT RES EQUAL 0) + run_git(submodule update --init ${GIT_SUBMODULES}) + endif() + endif() + + if (NOT RES EQUAL 0) + message(FATAL_ERROR "Submodule update failed") + endif() endif() diff --git a/py/mkrules.mk b/py/mkrules.mk index 058f5a9ee50..fe4bf9a3d16 100644 --- a/py/mkrules.mk +++ b/py/mkrules.mk @@ -11,6 +11,7 @@ ifeq ($(MICROPY_PREVIEW_VERSION_2),1) CFLAGS += -DMICROPY_PREVIEW_VERSION_2=1 endif +# CIRCUITPY-CHANGE: point to CircuitPython documentation HELP_BUILD_ERROR ?= "See \033[1;31mhttps://learn.adafruit.com/building-circuitpython; Adafruit Discord \#circuitpython-dev\033[0m" HELP_MPY_LIB_SUBMODULE ?= "\033[1;31mError: micropython-lib submodule is not initialized.\033[0m Run 'make submodules'" @@ -27,10 +28,35 @@ OBJ_EXTRA_ORDER_DEPS += $(HEADER_BUILD)/compressed.data.h CFLAGS += -DMICROPY_ROM_TEXT_COMPRESSION=1 endif +# Set the variant or board name. +ifneq ($(VARIANT),) +CFLAGS += -DMICROPY_BOARD_BUILD_NAME=\"$(VARIANT)\" +else ifneq ($(BOARD),) +ifeq ($(BOARD_VARIANT),) +CFLAGS += -DMICROPY_BOARD_BUILD_NAME=\"$(BOARD)\" +else +CFLAGS += -DMICROPY_BOARD_BUILD_NAME=\"$(BOARD)-$(BOARD_VARIANT)\" +endif +endif + +# Add default C++ compiler flags based on CFLAGS. For use with C++ user modules. +# CIRCUITPY-CHANGE: CircuitPython enables C-only warnings that g++ rejects, in +# py/circuitpy_defns.mk and in the port Makefiles, so strip those too. +CXXFLAGS += $(filter-out -std=c11 -std=c99 -std=gnu11 -std=gnu99 -Werror-implicit-function-declaration -Werror=missing-prototypes -Werror=old-style-definition -Wmissing-prototypes -Wnested-externs -Wold-style-definition -Wstrict-prototypes,$(CFLAGS) $(CXXFLAGS_MOD)) + +# Add LDFLAGS to link libstdc++ on bare metal ports. Added only if a port has +# -nostdlib in LDFLAGS and C++ source files are provided. +ifneq ($(findstring nostdlib,"$(LDFLAGS)"),) +ifneq ($(SRC_CXX)$(SRC_USERMOD_CXX)$(SRC_USERMOD_LIB_CXX),) +LIBSTDCPP_FILE_NAME = "$(shell $(CXX) $(CXXFLAGS) -print-file-name=libstdc++.a)" +LDFLAGS += -L"$(shell dirname $(LIBSTDCPP_FILE_NAME))" +endif +endif + # QSTR generation uses the same CFLAGS, with these modifications. QSTR_GEN_FLAGS = -DNO_QSTR # Note: := to force evaluation immediately. -QSTR_GEN_CFLAGS := $(CFLAGS) +QSTR_GEN_CFLAGS := $(filter-out -g%,$(CFLAGS)) QSTR_GEN_CFLAGS += $(QSTR_GEN_FLAGS) QSTR_GEN_CXXFLAGS := $(CXXFLAGS) QSTR_GEN_CXXFLAGS += $(QSTR_GEN_FLAGS) @@ -51,13 +77,13 @@ QSTR_GEN_CXXFLAGS += $(QSTR_GEN_FLAGS) # can be located. By following this scheme, it allows a single build rule # to be used to compile all .c files. +vpath %.S . $(TOP) $(USER_C_MODULES) $(USERMOD_DIR_PARENTS) # CIRCUITPY-CHANGE: use STEPECHO -vpath %.S . $(TOP) $(USER_C_MODULES) $(BUILD)/%.o: %.S $(STEPECHO) "CC $<" $(Q)$(CC) $(CFLAGS) -c -o $@ $< -vpath %.s . $(TOP) $(USER_C_MODULES) +vpath %.s . $(TOP) $(USER_C_MODULES) $(USERMOD_DIR_PARENTS) $(BUILD)/%.o: %.s $(STEPECHO) "AS $<" $(Q)$(AS) $(AFLAGS) -o $@ $< @@ -87,12 +113,12 @@ $(Q)$(CXX) $(CXXFLAGS) -c -MD -MF $(@:.o=.d) -o $@ $< || (echo -e $(HELP_BUILD_E $(RM) -f $(@:.o=.d) endef -# CIRCUITPY-CHANGE: add $(DEVICES_MODULES) and $(BUILD) -vpath %.c . $(TOP) $(USER_C_MODULES) $(DEVICES_MODULES) $(BUILD) +# CIRCUITPY-CHANGE: add $(BUILD) +vpath %.c . $(TOP) $(USER_C_MODULES) $(USERMOD_DIR_PARENTS) $(BUILD) $(BUILD)/%.o: %.c $(call compile_c) -vpath %.cpp . $(TOP) $(USER_C_MODULES) +vpath %.cpp . $(TOP) $(USER_C_MODULES) $(USERMOD_DIR_PARENTS) $(BUILD)/%.o: %.cpp $(call compile_cxx) @@ -101,6 +127,14 @@ $(BUILD)/%.pp: %.c $(STEPECHO) "PreProcess $<" $(Q)$(CPP) $(CFLAGS) -Wp,-C,-dD,-dI -o $@ $< +.PHONY: $(BUILD)/%.sz +$(BUILD)/%.sz: $(BUILD)/%.o + $(Q)$(SIZE) $< + +# Special case for compiling auto-generated source files. +$(BUILD)/%.o: $(BUILD)/%.c + $(call compile_c) + # The following rule uses | to create an order only prerequisite. Order only # prerequisites only get built if they don't exist. They don't cause timestamp # checking to be performed. @@ -168,7 +202,7 @@ $(HEADER_BUILD)/compressed.collected: $(HEADER_BUILD)/compressed.split # will be created if they don't exist. OBJ_DIRS = $(sort $(dir $(OBJ))) $(OBJ): | $(OBJ_DIRS) -// CIRCUITPY-CHANGE: use $(Q) +# CIRCUITPY-CHANGE: use $(Q) $(OBJ_DIRS): $(Q)$(MKDIR) -p $@ @@ -176,9 +210,12 @@ $(HEADER_BUILD): $(Q)$(MKDIR) -p $@ ifneq ($(MICROPY_MPYCROSS_DEPENDENCY),) -# to automatically build mpy-cross, if needed +# Build mpy-cross automatically if needed. Clear USER_C_MODULES and +# FROZEN_MANIFEST so a port build with either set doesn't leak them into the +# mpy-cross sub-make and cause manifest.mk there to parse the port's manifest +# from the wrong cwd. $(MICROPY_MPYCROSS_DEPENDENCY): - $(MAKE) -C "$(abspath $(dir $@)..)" + $(MAKE) -C "$(abspath $(dir $@)..)" USER_C_MODULES= FROZEN_MANIFEST= endif ifneq ($(FROZEN_DIR),) @@ -200,12 +237,6 @@ endif CFLAGS += -DMICROPY_QSTR_EXTRA_POOL=mp_qstr_frozen_const_pool CFLAGS += -DMICROPY_MODULE_FROZEN_MPY CFLAGS += -DMICROPY_MODULE_FROZEN_STR - -# CIRCUITPY-CHANGE: FROZEN_MANIFEST is constructed at build time -# to build frozen_content.c from a manifest -$(BUILD)/frozen_content.c: FORCE $(BUILD)/genhdr/qstrdefs.generated.h $(BUILD)/genhdr/root_pointers.h $(FROZEN_MANIFEST) | $(MICROPY_MPYCROSS_DEPENDENCY) - $(Q)test -e "$(MPY_LIB_DIR)/README.md" || (echo -e $(HELP_MPY_LIB_SUBMODULE); false) - $(Q)$(MAKE_MANIFEST) -o $@ -v "MPY_DIR=$(TOP)" -v "MPY_LIB_DIR=$(MPY_LIB_DIR)" -v "PORT_DIR=$(shell pwd)" -v "BOARD_DIR=$(BOARD_DIR)" -b "$(BUILD)" $(if $(MPY_CROSS_FLAGS),-f"$(MPY_CROSS_FLAGS)",) --mpy-tool-flags="$(MPY_TOOL_FLAGS)" $(FROZEN_MANIFEST) endif ifneq ($(PROG),) @@ -224,7 +255,7 @@ $(BUILD)/$(PROG): $(OBJ) $(ECHO) "LINK $@" # Do not pass COPT here - it's *C* compiler optimizations. For example, # we may want to compile using Thumb, but link with non-Thumb libc. - $(Q)$(CC) -o $@ $^ $(LIB) $(LDFLAGS) + $(Q)$(CC) -o $@ $^ $(LIBS) $(LDFLAGS) ifndef DEBUG ifdef STRIP $(Q)$(STRIP) $(STRIPFLAGS_EXTRA) $@ @@ -240,11 +271,17 @@ clean-prog: .PHONY: clean-prog endif +# If available, do blobless partial clones of submodules to save time and space. +# A blobless partial clone lazily fetches data as needed, but has all the metadata available (tags, etc.). +# Fallback to standard submodule update if blobless isn't available (earlier than 2.36.0) +# +# Note: This target has a CMake equivalent in py/mkrules.cmake submodules: $(ECHO) "Updating submodules: $(GIT_SUBMODULES)" ifneq ($(GIT_SUBMODULES),) - $(Q)git submodule sync $(addprefix $(TOP)/,$(GIT_SUBMODULES)) - $(Q)git submodule update --init $(addprefix $(TOP)/,$(GIT_SUBMODULES)) + $(Q)cd $(TOP) && git submodule sync $(GIT_SUBMODULES) + $(Q)cd $(TOP) && git submodule update --init --filter=blob:none $(GIT_SUBMODULES) 2>/dev/null || \ + git submodule update --init $(GIT_SUBMODULES) endif .PHONY: submodules diff --git a/py/modbuiltins.c b/py/modbuiltins.c index cdeacc25f71..327783996fb 100644 --- a/py/modbuiltins.c +++ b/py/modbuiltins.c @@ -138,7 +138,7 @@ static mp_obj_t mp_builtin_chr(mp_obj_t o_in) { #if MICROPY_PY_BUILTINS_STR_UNICODE mp_uint_t c = mp_obj_get_int(o_in); if (c >= 0x110000) { - mp_raise_ValueError(MP_ERROR_TEXT("chr() arg not in range(0x110000)")); + mp_raise_ValueError(MP_ERROR_TEXT("char not in range(0x110000)")); } VSTR_FIXED(buf, 4); vstr_add_char(&buf, c); @@ -155,6 +155,7 @@ static mp_obj_t mp_builtin_chr(mp_obj_t o_in) { } MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_chr_obj, mp_builtin_chr); +#if MICROPY_PY_BUILTINS_DIR static mp_obj_t mp_builtin_dir(size_t n_args, const mp_obj_t *args) { mp_obj_t dir = mp_obj_new_list(0, NULL); if (n_args == 0) { @@ -188,6 +189,7 @@ static mp_obj_t mp_builtin_dir(size_t n_args, const mp_obj_t *args) { return dir; } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin_dir_obj, 0, 1, mp_builtin_dir); +#endif static mp_obj_t mp_builtin_divmod(mp_obj_t o1_in, mp_obj_t o2_in) { return mp_binary_op(MP_BINARY_OP_DIVMOD, o1_in, o2_in); @@ -366,18 +368,21 @@ static mp_obj_t mp_builtin_ord(mp_obj_t o_in) { 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]); - default: - #if !MICROPY_PY_BUILTINS_POW3 - mp_raise_NotImplementedError(MP_ERROR_TEXT("3-arg pow() not supported")); - #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 - return mp_obj_int_pow3(args[0], args[1], args[2]); - #endif + // Treat pow(x, y, None) as pow(x, y), matching CPython. + if (n_args == 2 + #if MICROPY_PY_BUILTINS_POW3 + || args[2] == mp_const_none + #endif + ) { + return mp_binary_op(MP_BINARY_OP_POWER, args[0], args[1]); } + #if !MICROPY_PY_BUILTINS_POW3 + mp_raise_NotImplementedError(MP_ERROR_TEXT("3-arg pow() not supported")); + #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 + return mp_obj_int_pow3(args[0], args[1], args[2]); + #endif } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin_pow_obj, 2, 3, mp_builtin_pow); @@ -607,6 +612,9 @@ MP_DEFINE_CONST_FUN_OBJ_0(mp_builtin_locals_obj, mp_builtin_locals); // These are defined in terms of MicroPython API functions right away MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_id_obj, mp_obj_id); MP_DEFINE_CONST_FUN_OBJ_1(mp_builtin_len_obj, mp_obj_len); +#if MICROPY_PY_TSTRINGS +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin___template___obj, 1, MP_OBJ_FUN_ARGS_MAX, mp_obj_new_template); +#endif static const mp_rom_map_elem_t mp_module_builtins_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_builtins) }, @@ -615,6 +623,9 @@ static const mp_rom_map_elem_t mp_module_builtins_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___build_class__), MP_ROM_PTR(&mp_builtin___build_class___obj) }, { MP_ROM_QSTR(MP_QSTR___import__), MP_ROM_PTR(&mp_builtin___import___obj) }, { MP_ROM_QSTR(MP_QSTR___repl_print__), MP_ROM_PTR(&mp_builtin___repl_print___obj) }, + #if MICROPY_PY_TSTRINGS + { MP_ROM_QSTR(MP_QSTR___template__), MP_ROM_PTR(&mp_builtin___template___obj) }, + #endif // built-in types { MP_ROM_QSTR(MP_QSTR_bool), MP_ROM_PTR(&mp_type_bool) }, @@ -686,7 +697,9 @@ static const mp_rom_map_elem_t mp_module_builtins_globals_table[] = { #if MICROPY_CPYTHON_COMPAT { MP_ROM_QSTR(MP_QSTR_delattr), MP_ROM_PTR(&mp_builtin_delattr_obj) }, #endif + #if MICROPY_PY_BUILTINS_DIR { MP_ROM_QSTR(MP_QSTR_dir), MP_ROM_PTR(&mp_builtin_dir_obj) }, + #endif { MP_ROM_QSTR(MP_QSTR_divmod), MP_ROM_PTR(&mp_builtin_divmod_obj) }, #if MICROPY_PY_BUILTINS_EVAL_EXEC { MP_ROM_QSTR(MP_QSTR_eval), MP_ROM_PTR(&mp_builtin_eval_obj) }, diff --git a/py/moderrno.c b/py/moderrno.c index 140ae1cc0a6..8ea6cdfd65c 100644 --- a/py/moderrno.c +++ b/py/moderrno.c @@ -36,6 +36,7 @@ // specific port's needs. If it's not defined then we provide a default. #ifndef MICROPY_PY_ERRNO_LIST // CIRCUITPY-CHANGE: add ENOSPC and EROFS, because they are in mp_common_errno_to_str(). +// CIRCUITPY-CHANGE: docs/library/errno.rst lists these names. Update it if this list changes. #define MICROPY_PY_ERRNO_LIST \ X(EPERM) \ X(ENOENT) \ @@ -44,6 +45,7 @@ X(EAGAIN) \ X(ENOMEM) \ X(EACCES) \ + X(EBUSY) \ X(EEXIST) \ X(ENODEV) \ X(EISDIR) \ diff --git a/py/modio.c b/py/modio.c index d3e563dbcf4..fdee484376f 100644 --- a/py/modio.c +++ b/py/modio.c @@ -63,6 +63,10 @@ static mp_uint_t iobase_read_write(mp_obj_t obj, void *buf, mp_uint_t size, int } mp_int_t ret = mp_obj_get_int(ret_obj); if (ret >= 0) { + if ((mp_uint_t)ret > size) { + *errcode = MP_EIO; + return MP_STREAM_ERROR; + } return ret; } else { *errcode = -ret; @@ -169,12 +173,13 @@ static mp_obj_t bufwriter_flush(mp_obj_t self_in) { int err; mp_uint_t out_sz = mp_stream_write_exactly(self->stream, self->buf, self->len, &err); (void)out_sz; - // TODO: try to recover from a case of non-blocking stream, e.g. move - // remaining chunk to the beginning of buffer. - assert(out_sz == self->len); - self->len = 0; if (err != 0) { mp_raise_OSError(err); + } else { + // TODO: try to recover from a case of non-blocking stream, e.g. move + // remaining chunk to the beginning of buffer. + assert(out_sz == self->len); + self->len = 0; } } diff --git a/py/modmath.c b/py/modmath.c index 701da796bce..2a9ed1b7f22 100644 --- a/py/modmath.c +++ b/py/modmath.c @@ -37,7 +37,7 @@ #define MP_PI_4 MICROPY_FLOAT_CONST(0.78539816339744830962) #define MP_3_PI_4 MICROPY_FLOAT_CONST(2.35619449019234492885) -static NORETURN void math_error(void) { +static MP_NORETURN void math_error(void) { mp_raise_ValueError(MP_ERROR_TEXT("math domain error")); } @@ -99,12 +99,16 @@ mp_float_t MICROPY_FLOAT_C_FUN(log2)(mp_float_t x) { MATH_FUN_1(sqrt, sqrt) // pow(x, y): returns x to the power of y #if MICROPY_PY_MATH_POW_FIX_NAN -mp_float_t pow_func(mp_float_t x, mp_float_t y) { +mp_float_t MICROPY_FLOAT_C_FUN(pow_func)(mp_float_t x, mp_float_t y) { // pow(base, 0) returns 1 for any base, even when base is NaN // pow(+1, exponent) returns 1 for any exponent, even when exponent is NaN if (x == MICROPY_FLOAT_CONST(1.0) || y == MICROPY_FLOAT_CONST(0.0)) { return MICROPY_FLOAT_CONST(1.0); } + // pow(base, NaN) returns NaN for any other value of base + if (isnan(y)) { + return y; + } return MICROPY_FLOAT_C_FUN(pow)(x, y); } MATH_FUN_2(pow, pow_func) @@ -161,6 +165,11 @@ MATH_FUN_2(atan2, atan2) MATH_FUN_1_TO_INT(ceil, ceil) // copysign(x, y) static mp_float_t MICROPY_FLOAT_C_FUN(copysign_func)(mp_float_t x, mp_float_t y) { + #if MICROPY_PY_MATH_COPYSIGN_FIX_NAN + if (isnan(y)) { + y = 0.0; + } + #endif return MICROPY_FLOAT_C_FUN(copysign)(x, y); } MATH_FUN_2(copysign, copysign_func) @@ -196,7 +205,17 @@ MATH_FUN_1(erf, erf) // erfc(x): return the complementary error function of x MATH_FUN_1(erfc, erfc) // gamma(x): return the gamma function of x +#if MICROPY_PY_MATH_GAMMA_FIX_NEGINF +static mp_float_t MICROPY_FLOAT_C_FUN(tgamma_func)(mp_float_t x) { + if (isinf(x) && x < 0) { + math_error(); + } + return MICROPY_FLOAT_C_FUN(tgamma)(x); +} +MATH_FUN_1(gamma, tgamma_func) +#else MATH_FUN_1(gamma, tgamma) +#endif // lgamma(x): return the natural logarithm of the gamma function of x MATH_FUN_1(lgamma, lgamma) #endif diff --git a/py/modmicropython.c b/py/modmicropython.c index 4a0e2cf44ff..5e1b3253427 100644 --- a/py/modmicropython.c +++ b/py/modmicropython.c @@ -27,7 +27,7 @@ #include #include "py/builtin.h" -#include "py/stackctrl.h" +#include "py/cstack.h" #include "py/runtime.h" #include "py/gc.h" #include "py/mphal.h" @@ -78,9 +78,9 @@ mp_obj_t mp_micropython_mem_info(size_t n_args, const mp_obj_t *args) { #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)); + mp_cstack_usage(), (mp_uint_t)MP_STATE_THREAD(stack_limit)); #else - mp_printf(&mp_plat_print, "stack: " UINT_FMT "\n", mp_stack_usage()); + mp_printf(&mp_plat_print, "stack: " UINT_FMT "\n", mp_cstack_usage()); #endif #if MICROPY_ENABLE_GC gc_dump_info(&mp_plat_print); @@ -100,7 +100,7 @@ static mp_obj_t mp_micropython_qstr_info(size_t n_args, const mp_obj_t *args) { 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); mp_printf(&mp_plat_print, "qstr pool: n_pool=%u, n_qstr=%u, n_str_data_bytes=%u, n_total_bytes=%u\n", - n_pool, n_qstr, n_str_data_bytes, n_total_bytes); + (uint)n_pool, (uint)n_qstr, (uint)n_str_data_bytes, (uint)n_total_bytes); if (n_args == 1) { // arg given means dump qstr data qstr_dump_data(); @@ -113,7 +113,7 @@ static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_micropython_qstr_info_obj, 0, 1, m #if MICROPY_PY_MICROPYTHON_STACK_USE static mp_obj_t mp_micropython_stack_use(void) { - return MP_OBJ_NEW_SMALL_INT(mp_stack_usage()); + return MP_OBJ_NEW_SMALL_INT(mp_cstack_usage()); } static MP_DEFINE_CONST_FUN_OBJ_0(mp_micropython_stack_use_obj, mp_micropython_stack_use); #endif @@ -136,13 +136,13 @@ static MP_DEFINE_CONST_FUN_OBJ_0(mp_micropython_heap_lock_obj, mp_micropython_he static mp_obj_t mp_micropython_heap_unlock(void) { gc_unlock(); - return MP_OBJ_NEW_SMALL_INT(MP_STATE_THREAD(gc_lock_depth)); + return MP_OBJ_NEW_SMALL_INT(MP_STATE_THREAD(gc_lock_depth) >> GC_LOCK_DEPTH_SHIFT); } static MP_DEFINE_CONST_FUN_OBJ_0(mp_micropython_heap_unlock_obj, mp_micropython_heap_unlock); #if MICROPY_PY_MICROPYTHON_HEAP_LOCKED static mp_obj_t mp_micropython_heap_locked(void) { - return MP_OBJ_NEW_SMALL_INT(MP_STATE_THREAD(gc_lock_depth)); + return MP_OBJ_NEW_SMALL_INT(MP_STATE_THREAD(gc_lock_depth) >> GC_LOCK_DEPTH_SHIFT); } static MP_DEFINE_CONST_FUN_OBJ_0(mp_micropython_heap_locked_obj, mp_micropython_heap_locked); #endif @@ -163,13 +163,35 @@ static MP_DEFINE_CONST_FUN_OBJ_1(mp_micropython_kbd_intr_obj, mp_micropython_kbd #endif #if MICROPY_ENABLE_SCHEDULER + +#if MICROPY_KBD_EXCEPTION && MICROPY_SCHEDULER_STATIC_NODES +static mp_sched_node_t mp_keyboard_interrupt_sched_node; +static void mp_sched_keyboard_interrupt_wrapper(mp_sched_node_t *node) { + mp_sched_keyboard_interrupt(); +} +#endif + static mp_obj_t mp_micropython_schedule(mp_obj_t function, mp_obj_t arg) { + #if MICROPY_KBD_EXCEPTION + if (function == MP_OBJ_FROM_PTR(&mp_micropython_kbd_intr_obj)) { + #if MICROPY_SCHEDULER_STATIC_NODES + // Allow calling `micropython.schedule(micropython.kbd_intr, None)` as a + // special case to schedule a keyboard interrupt. + mp_sched_schedule_node(&mp_keyboard_interrupt_sched_node, mp_sched_keyboard_interrupt_wrapper); + return mp_const_none; + #else + // Signal that passing `micropython.kbd_intr` is not supported. + mp_raise_ValueError(NULL); + #endif + } + #endif if (!mp_sched_schedule(function, arg)) { mp_raise_msg(&mp_type_RuntimeError, MP_ERROR_TEXT("schedule queue full")); } return mp_const_none; } static MP_DEFINE_CONST_FUN_OBJ_2(mp_micropython_schedule_obj, mp_micropython_schedule); + #endif static const mp_rom_map_elem_t mp_module_micropython_globals_table[] = { @@ -213,6 +235,9 @@ static const mp_rom_map_elem_t mp_module_micropython_globals_table[] = { #if CIRCUITPY_MICROPYTHON_ADVANCED && MICROPY_KBD_EXCEPTION { MP_ROM_QSTR(MP_QSTR_kbd_intr), MP_ROM_PTR(&mp_micropython_kbd_intr_obj) }, #endif + #if MICROPY_PY_MICROPYTHON_RINGIO + { MP_ROM_QSTR(MP_QSTR_RingIO), MP_ROM_PTR(&mp_type_ringio) }, + #endif #if MICROPY_ENABLE_SCHEDULER { MP_ROM_QSTR(MP_QSTR_schedule), MP_ROM_PTR(&mp_micropython_schedule_obj) }, #endif diff --git a/py/modstring.c b/py/modstring.c new file mode 100644 index 00000000000..26e0c2d83cb --- /dev/null +++ b/py/modstring.c @@ -0,0 +1,56 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2026 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 "py/obj.h" + +#if MICROPY_PY_TSTRINGS + +static const mp_rom_map_elem_t mp_module_string_templatelib_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_string_dot_templatelib) }, + { MP_ROM_QSTR(MP_QSTR_Template), MP_ROM_PTR(&mp_type_template) }, + { MP_ROM_QSTR(MP_QSTR_Interpolation), MP_ROM_PTR(&mp_type_interpolation) }, +}; +static MP_DEFINE_CONST_DICT(mp_module_string_templatelib_globals, mp_module_string_templatelib_globals_table); + +static const mp_obj_module_t mp_module_string_templatelib = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&mp_module_string_templatelib_globals, +}; + +static const mp_rom_map_elem_t mp_module_string_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_string) }, + { MP_ROM_QSTR(MP_QSTR_templatelib), MP_ROM_PTR(&mp_module_string_templatelib) }, +}; +static MP_DEFINE_CONST_DICT(mp_module_string_globals, mp_module_string_globals_table); + +const mp_obj_module_t mp_module_string = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&mp_module_string_globals, +}; + +MP_REGISTER_EXTENSIBLE_MODULE(MP_QSTR_string, mp_module_string); + +#endif // MICROPY_PY_TSTRINGS diff --git a/py/modsys.c b/py/modsys.c index 2bb2606a062..bbae93d0c3f 100644 --- a/py/modsys.c +++ b/py/modsys.c @@ -26,6 +26,7 @@ */ #include "py/builtin.h" +#include "py/objexcept.h" #include "py/objlist.h" #include "py/objmodule.h" #include "py/objtuple.h" @@ -94,13 +95,44 @@ static const MP_DEFINE_STR_OBJ(mp_sys_implementation_machine_obj, MICROPY_BANNER MP_ROM_PTR(&mp_sys_implementation_machine_obj) #if MICROPY_PERSISTENT_CODE_LOAD +// Note: Adding architecture flags to _mpy will break if the flags information +// takes up more bits than what is available in a small-int value. +#if MICROPY_EMIT_RV32 +#include "py/asmrv32.h" +#define MPY_FILE_ARCH_FLAGS (MICROPY_RV32_EXTENSIONS << 16) +#else +#define MPY_FILE_ARCH_FLAGS (0) +#endif #define SYS_IMPLEMENTATION_ELEMS__MPY \ - , MP_ROM_INT(MPY_FILE_HEADER_INT) + , MP_ROM_INT(MPY_FILE_HEADER_INT | MPY_FILE_ARCH_FLAGS) #else #define SYS_IMPLEMENTATION_ELEMS__MPY #endif #if MICROPY_PY_ATTRTUPLE + +#if defined(MICROPY_BOARD_BUILD_NAME) +static const MP_DEFINE_STR_OBJ(mp_sys_implementation__build_obj, MICROPY_BOARD_BUILD_NAME); +#define MICROPY_BOARD_BUILD (1) +#define SYS_IMPLEMENTATION_ELEMS__BUILD \ + , MP_ROM_PTR(&mp_sys_implementation__build_obj) +#else +#define MICROPY_BOARD_BUILD (0) +#define SYS_IMPLEMENTATION_ELEMS__BUILD +#endif + +#if MICROPY_PY_THREAD +#if MICROPY_PY_THREAD_GIL +#define SYS_IMPLEMENTATION_ELEMS__THREAD \ + , MP_ROM_QSTR(MP_QSTR_GIL) +#else +#define SYS_IMPLEMENTATION_ELEMS__THREAD \ + , MP_ROM_QSTR(MP_QSTR_unsafe) +#endif +#else +#define SYS_IMPLEMENTATION_ELEMS__THREAD +#endif + #if MICROPY_PREVIEW_VERSION_2 #define SYS_IMPLEMENTATION_ELEMS__V2 \ , MP_ROM_TRUE @@ -115,6 +147,12 @@ static const qstr impl_fields[] = { #if MICROPY_PERSISTENT_CODE_LOAD MP_QSTR__mpy, #endif + #if defined(MICROPY_BOARD_BUILD_NAME) + MP_QSTR__build, + #endif + #if MICROPY_PY_THREAD + MP_QSTR__thread, + #endif #if MICROPY_PREVIEW_VERSION_2 MP_QSTR__v2, #endif @@ -122,19 +160,21 @@ static const qstr impl_fields[] = { static MP_DEFINE_ATTRTUPLE( mp_sys_implementation_obj, impl_fields, - 3 + MICROPY_PERSISTENT_CODE_LOAD + MICROPY_PREVIEW_VERSION_2, + 3 + MICROPY_PERSISTENT_CODE_LOAD + MICROPY_BOARD_BUILD + MICROPY_PY_THREAD + MICROPY_PREVIEW_VERSION_2, SYS_IMPLEMENTATION_ELEMS_BASE SYS_IMPLEMENTATION_ELEMS__MPY + SYS_IMPLEMENTATION_ELEMS__BUILD + SYS_IMPLEMENTATION_ELEMS__THREAD SYS_IMPLEMENTATION_ELEMS__V2 ); #else static const mp_rom_obj_tuple_t mp_sys_implementation_obj = { {&mp_type_tuple}, 3 + MICROPY_PERSISTENT_CODE_LOAD, - // Do not include SYS_IMPLEMENTATION_ELEMS__V2 because - // SYS_IMPLEMENTATION_ELEMS__MPY may be empty if + // Do not include SYS_IMPLEMENTATION_ELEMS__BUILD, SYS_IMPLEMENTATION_ELEMS__THREAD + // or SYS_IMPLEMENTATION_ELEMS__V2 because SYS_IMPLEMENTATION_ELEMS__MPY may be empty if // MICROPY_PERSISTENT_CODE_LOAD is disabled, which means they'll share - // the same index. Cannot query _v2 if MICROPY_PY_ATTRTUPLE is + // the same index. Cannot query _build, _thread or _v2 if MICROPY_PY_ATTRTUPLE is // disabled. { SYS_IMPLEMENTATION_ELEMS_BASE @@ -170,29 +210,7 @@ static mp_obj_t mp_sys_exit(size_t n_args, const mp_obj_t *args) { } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_sys_exit_obj, 0, 1, mp_sys_exit); -static mp_obj_t mp_sys_print_exception(size_t n_args, const mp_obj_t *args) { - // CIRCUITPY-CHANGE - #if CIRCUITPY_WARNINGS - warnings_warn(&mp_type_FutureWarning, MP_ERROR_TEXT("%q moved from %q to %q"), MP_QSTR_print_exception, MP_QSTR_sys, MP_QSTR_traceback); - #endif - - #if MICROPY_PY_IO && MICROPY_PY_SYS_STDFILES - void *stream_obj = &mp_sys_stdout_obj; - if (n_args > 1) { - mp_get_stream_raise(args[1], MP_STREAM_OP_WRITE); - stream_obj = MP_OBJ_TO_PTR(args[1]); - } - - mp_print_t print = {stream_obj, mp_stream_write_adaptor}; - mp_obj_print_exception(&print, args[0]); - #else - (void)n_args; - mp_obj_print_exception(&mp_plat_print, args[0]); - #endif - - return mp_const_none; -} -MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_sys_print_exception_obj, 1, 2, mp_sys_print_exception); +// CIRCUITPY-CHANGE: Removed print_exception because it isn't in CPython. #if MICROPY_PY_SYS_EXC_INFO static mp_obj_t mp_sys_exc_info(void) { @@ -209,7 +227,8 @@ static mp_obj_t mp_sys_exc_info(void) { t->items[0] = MP_OBJ_FROM_PTR(mp_obj_get_type(cur_exc)); t->items[1] = cur_exc; // CIRCUITPY-CHANGE: has traceback obj - t->items[2] = mp_obj_exception_get_traceback_obj(cur_exc); + mp_obj_exception_t *native_exc = mp_obj_exception_get_native(cur_exc); + t->items[2] = native_exc->traceback; return MP_OBJ_FROM_PTR(t); } MP_DEFINE_CONST_FUN_OBJ_0(mp_sys_exc_info_obj, mp_sys_exc_info); @@ -347,8 +366,6 @@ static const mp_rom_map_elem_t mp_module_sys_globals_table[] = { /* * Extensions to CPython */ - - { MP_ROM_QSTR(MP_QSTR_print_exception), MP_ROM_PTR(&mp_sys_print_exception_obj) }, #if MICROPY_PY_SYS_ATEXIT { MP_ROM_QSTR(MP_QSTR_atexit), MP_ROM_PTR(&mp_sys_atexit_obj) }, #endif diff --git a/py/modthread.c b/py/modthread.c index 188449802fd..1b792eaeb77 100644 --- a/py/modthread.c +++ b/py/modthread.c @@ -28,7 +28,6 @@ #include #include "py/runtime.h" -#include "py/stackctrl.h" #if MICROPY_PY_THREAD diff --git a/py/modweakref.c b/py/modweakref.c new file mode 100644 index 00000000000..3360a4e2095 --- /dev/null +++ b/py/modweakref.c @@ -0,0 +1,314 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2026 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 "py/gc.h" +#include "py/runtime.h" + +#if MICROPY_PY_WEAKREF + +// Macros to obfuscate a heap pointer as a small integer object. +#define PTR_TO_INT_OBJ(ptr) (MP_OBJ_NEW_SMALL_INT(((uintptr_t)ptr) >> 1)) +#define PTR_FROM_INT_OBJ(obj) ((void *)(MP_OBJ_SMALL_INT_VALUE((obj)) << 1)) + +// Macros to convert between a weak reference and a heap pointer. +#define WEAK_REFERENCE_FROM_HEAP_PTR(ptr) PTR_TO_INT_OBJ(ptr) +#define WEAK_REFERENCE_TO_HEAP_PTR(weak_ref) PTR_FROM_INT_OBJ(weak_ref) + +// Macros to manage ref-finalizer linked-list pointers. +// - mp_obj_ref_t is obfuscated as a small integer object so it's not traced by the GC. +// - mp_obj_finalize_t is stored as-is so it is traced by the GC. +#define REF_FIN_LIST_OBJ_IS_FIN(r) (!mp_obj_is_small_int((r))) +#define REF_FIN_LIST_OBJ_TO_PTR(r) ((mp_obj_ref_t *)(mp_obj_is_small_int((r)) ? PTR_FROM_INT_OBJ((r)) : MP_OBJ_TO_PTR((r)))) +#define REF_FIN_LIST_OBJ_FROM_REF(r) (PTR_TO_INT_OBJ((r))) +#define REF_FIN_LIST_OBJ_FROM_FIN(r) (MP_OBJ_FROM_PTR((r))) +#define REF_FIN_LIST_OBJ_TAIL (PTR_TO_INT_OBJ(NULL)) + +// weakref.ref() instance. +typedef struct _mp_obj_ref_t { + mp_obj_base_t base; + mp_obj_t ref_fin_next; + mp_obj_t obj_weak_ref; + mp_obj_t callback; +} mp_obj_ref_t; + +// weakref.finalize() instance. +// This is an extension of weakref.ref() and shares a lot of code with it. +typedef struct _mp_obj_finalize_t { + mp_obj_ref_t base; + size_t n_args; + size_t n_kw; + mp_obj_t *args; +} mp_obj_finalize_t; + +static const mp_obj_type_t mp_type_ref; +static const mp_obj_type_t mp_type_finalize; + +static mp_obj_t ref___del__(mp_obj_t self_in); + +void gc_weakref_about_to_be_freed(void *ptr) { + mp_obj_t idx = WEAK_REFERENCE_FROM_HEAP_PTR(ptr); + mp_map_elem_t *elem = mp_map_lookup(&MP_STATE_VM(mp_weakref_map), idx, MP_MAP_LOOKUP); + if (elem != NULL) { + // Mark element as being freed. + elem->key = mp_const_none; + } +} + +void gc_weakref_sweep(void) { + mp_map_t *map = &MP_STATE_VM(mp_weakref_map); + for (size_t i = 0; i < map->alloc; i++) { + if (map->table[i].key == mp_const_none) { + // Element was just freed, so call all the registered callbacks. + --map->used; + map->table[i].key = MP_OBJ_SENTINEL; + mp_obj_ref_t *ref = REF_FIN_LIST_OBJ_TO_PTR(map->table[i].value); + map->table[i].value = MP_OBJ_NULL; + while (ref != NULL) { + // Invalidate the weak reference. + assert(ref->obj_weak_ref != mp_const_none); + ref->obj_weak_ref = mp_const_none; + + // Call any registered callbacks. + if (ref->callback != mp_const_none) { + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + if (ref->base.type == &mp_type_ref) { + // weakref.ref() type. + mp_call_function_1(ref->callback, MP_OBJ_FROM_PTR(ref)); + } else { + // weakref.finalize() type. + mp_obj_finalize_t *fin = (mp_obj_finalize_t *)ref; + mp_call_function_n_kw(fin->base.callback, fin->n_args, fin->n_kw, fin->args); + } + nlr_pop(); + } else { + mp_printf(MICROPY_ERROR_PRINTER, "Unhandled exception in weakref callback:\n"); + mp_obj_print_exception(MICROPY_ERROR_PRINTER, MP_OBJ_FROM_PTR(nlr.ret_val)); + } + } + + // Unlink the node. + mp_obj_ref_t *ref_fin_next = REF_FIN_LIST_OBJ_TO_PTR(ref->ref_fin_next); + ref->ref_fin_next = REF_FIN_LIST_OBJ_TAIL; + ref = ref_fin_next; + } + } + } +} + +static mp_obj_t mp_obj_ref_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { + if (type == &mp_type_ref) { + // weakref.ref() type. + mp_arg_check_num(n_args, n_kw, 1, 2, false); + } else { + // weakref.finalize() type. + mp_arg_check_num(n_args, n_kw, 2, MP_OBJ_FUN_ARGS_MAX, true); + } + + // Validate the input object can have a weakref. + void *ptr = NULL; + if (mp_obj_is_obj(args[0])) { + ptr = MP_OBJ_TO_PTR(args[0]); + if (gc_nbytes(ptr) == 0) { + ptr = NULL; + } + } + if (ptr == NULL) { + mp_raise_TypeError(MP_ERROR_TEXT("not a heap object")); + } + + // Create or get the entry in mp_weakref_map corresponding to this object. + mp_obj_t obj_weak_reference = WEAK_REFERENCE_FROM_HEAP_PTR(ptr); + mp_map_elem_t *elem = mp_map_lookup(&MP_STATE_VM(mp_weakref_map), obj_weak_reference, MP_MAP_LOOKUP_ADD_IF_NOT_FOUND); + if (elem->value == MP_OBJ_NULL) { + // This heap object does not have any existing weakref's, so initialise it. + elem->value = REF_FIN_LIST_OBJ_TAIL; + gc_weakref_mark(ptr); + } + + mp_obj_ref_t *self; + if (type == &mp_type_ref) { + // Create a new weakref.ref() object. + self = mp_obj_malloc_with_finaliser(mp_obj_ref_t, type); + // Link this new ref into the list of all refs/finalizers pointing to this object. + // To ensure it will *NOT* be traced by the GC (the user must manually hold onto it), + // store an integer version of the object after any weakref.finalize() objects (so + // the weakref.finalize() objects continue to be traced by the GC). + mp_obj_t *link = &elem->value; + while (REF_FIN_LIST_OBJ_IS_FIN(*link)) { + link = &REF_FIN_LIST_OBJ_TO_PTR(*link)->ref_fin_next; + } + self->ref_fin_next = *link; + *link = REF_FIN_LIST_OBJ_FROM_REF(self); + } else { + // Create a new weakref.finalize() object. + mp_obj_finalize_t *self_fin = mp_obj_malloc(mp_obj_finalize_t, type); + self_fin->n_args = n_args - 2; + self_fin->n_kw = n_kw; + size_t n_args_kw = self_fin->n_args + self_fin->n_kw * 2; + if (n_args_kw == 0) { + self_fin->args = NULL; + } else { + self_fin->args = m_new(mp_obj_t, n_args_kw); + memcpy(self_fin->args, args + 2, n_args_kw * sizeof(mp_obj_t)); + } + self = &self_fin->base; + // Link this new finalizer into the list of all refs/finalizers pointing to this object. + // To ensure it will be traced by the GC, store its pointer at the start of the list. + self->ref_fin_next = elem->value; + elem->value = REF_FIN_LIST_OBJ_FROM_FIN(self_fin); + } + + // Populate the object weak reference, and the callback. + self->obj_weak_ref = obj_weak_reference; + if (n_args > 1) { + self->callback = args[1]; + } else { + self->callback = mp_const_none; + } + + return MP_OBJ_FROM_PTR(self); +} + +static mp_obj_t mp_obj_ref_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { + mp_obj_ref_t *self = MP_OBJ_TO_PTR(self_in); + if (self->obj_weak_ref == mp_const_none) { + return mp_const_none; + } + if (self->base.type == &mp_type_ref) { + // weakref.ref() type. + return MP_OBJ_FROM_PTR(WEAK_REFERENCE_TO_HEAP_PTR(self->obj_weak_ref)); + } else { + // weakref.finalize() type. + mp_obj_finalize_t *self_fin = MP_OBJ_TO_PTR(self_in); + ref___del__(self_in); + return mp_call_function_n_kw(self_fin->base.callback, self_fin->n_args, self_fin->n_kw, self_fin->args); + } +} + +static mp_obj_t ref___del__(mp_obj_t self_in) { + mp_obj_ref_t *self = MP_OBJ_TO_PTR(self_in); + mp_map_elem_t *elem = mp_map_lookup(&MP_STATE_VM(mp_weakref_map), self->obj_weak_ref, MP_MAP_LOOKUP); + if (elem != NULL) { + for (mp_obj_t *link = &elem->value; REF_FIN_LIST_OBJ_TO_PTR(*link) != NULL; link = &REF_FIN_LIST_OBJ_TO_PTR(*link)->ref_fin_next) { + if (self == REF_FIN_LIST_OBJ_TO_PTR(*link)) { + // Unlink and clear this node. + *link = self->ref_fin_next; + self->ref_fin_next = REF_FIN_LIST_OBJ_TAIL; + self->obj_weak_ref = mp_const_none; + break; + } + } + } + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(ref___del___obj, ref___del__); + +static mp_obj_t finalize_peek_detach_helper(mp_obj_t self_in, bool detach) { + mp_obj_finalize_t *self = MP_OBJ_TO_PTR(self_in); + if (self->base.obj_weak_ref == mp_const_none) { + return mp_const_none; + } + mp_obj_t tuple[4] = { + MP_OBJ_FROM_PTR(WEAK_REFERENCE_TO_HEAP_PTR(self->base.obj_weak_ref)), + self->base.callback, + mp_obj_new_tuple(self->n_args, self->args), + mp_obj_dict_make_new(&mp_type_dict, 0, self->n_kw, self->args + self->n_args), + }; + if (detach) { + ref___del__(self_in); + } + return mp_obj_new_tuple(MP_ARRAY_SIZE(tuple), tuple); +} + +static mp_obj_t finalize_peek(mp_obj_t self_in) { + return finalize_peek_detach_helper(self_in, false); +} +static MP_DEFINE_CONST_FUN_OBJ_1(finalize_peek_obj, finalize_peek); + +static mp_obj_t finalize_detach(mp_obj_t self_in) { + return finalize_peek_detach_helper(self_in, true); +} +static MP_DEFINE_CONST_FUN_OBJ_1(finalize_detach_obj, finalize_detach); + +static void mp_obj_finalize_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { + if (dest[0] != MP_OBJ_NULL) { + // Store/delete attribute, unsupported. + return; + } + + if (attr == MP_QSTR_alive) { + mp_obj_finalize_t *self = MP_OBJ_TO_PTR(self_in); + dest[0] = mp_obj_new_bool(self->base.obj_weak_ref != mp_const_none); + return; + } else if (attr == MP_QSTR_peek) { + dest[0] = MP_OBJ_FROM_PTR(&finalize_peek_obj); + dest[1] = self_in; + } else if (attr == MP_QSTR_detach) { + dest[0] = MP_OBJ_FROM_PTR(&finalize_detach_obj); + dest[1] = self_in; + } +} + +static const mp_rom_map_elem_t ref_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&ref___del___obj) }, +}; +static MP_DEFINE_CONST_DICT(ref_locals_dict, ref_locals_dict_table); + +static MP_DEFINE_CONST_OBJ_TYPE( + mp_type_ref, + MP_QSTR_ref, + MP_TYPE_FLAG_NONE, + make_new, mp_obj_ref_make_new, + call, mp_obj_ref_call, + locals_dict, &ref_locals_dict + ); + +static MP_DEFINE_CONST_OBJ_TYPE( + mp_type_finalize, + MP_QSTR_finalize, + MP_TYPE_FLAG_NONE, + make_new, mp_obj_ref_make_new, + call, mp_obj_ref_call, + attr, mp_obj_finalize_attr + ); + +static const mp_rom_map_elem_t mp_module_weakref_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_weakref) }, + { MP_ROM_QSTR(MP_QSTR_ref), MP_ROM_PTR(&mp_type_ref) }, + { MP_ROM_QSTR(MP_QSTR_finalize), MP_ROM_PTR(&mp_type_finalize) }, +}; +static MP_DEFINE_CONST_DICT(mp_module_weakref_globals, mp_module_weakref_globals_table); + +const mp_obj_module_t mp_module_weakref = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&mp_module_weakref_globals, +}; + +MP_REGISTER_ROOT_POINTER(mp_map_t mp_weakref_map); +MP_REGISTER_MODULE(MP_QSTR_weakref, mp_module_weakref); + +#endif // MICROPY_PY_WEAKREF diff --git a/py/mpconfig.h b/py/mpconfig.h index 60e7afe52f9..92c94af05eb 100644 --- a/py/mpconfig.h +++ b/py/mpconfig.h @@ -26,6 +26,15 @@ #ifndef MICROPY_INCLUDED_PY_MPCONFIG_H #define MICROPY_INCLUDED_PY_MPCONFIG_H +#include +#include + +#if defined(__cplusplus) // Required on at least one compiler to get ULLONG_MAX +#include +#else +#include +#endif + // CIRCUITPY-CHANGE // Is this a CircuitPython build? #ifndef CIRCUITPY @@ -40,7 +49,7 @@ // as well as a fallback to generate MICROPY_GIT_TAG if the git repo or tags // are unavailable. #define MICROPY_VERSION_MAJOR 1 -#define MICROPY_VERSION_MINOR 23 +#define MICROPY_VERSION_MINOR 29 #define MICROPY_VERSION_MICRO 0 #define MICROPY_VERSION_PRERELEASE 0 @@ -173,6 +182,81 @@ #define MICROPY_OBJ_IMMEDIATE_OBJS (MICROPY_OBJ_REPR != MICROPY_OBJ_REPR_D) #endif +// Definition of the `mp_int_t` and `mp_uint_t` types and associated macros. +// Normally, it suffices for the platform to do nothing: A type as wide +// as a pointer is chosen, unless nanboxing (REPR_D) is selected, in +// which case a 64-bit type is chosen to match the assumed size of +// double-precision floats. +// +// In the case of exceptions, the port, board, or variant must define +// MP_INT_TYPE as MP_INT_TYPE_OTHER and provide all the typedefs and +// defines. +#define MP_INT_TYPE_INTPTR (0) +#define MP_INT_TYPE_INT64 (1) +#define MP_INT_TYPE_OTHER (2) + +#if !defined(MP_INT_TYPE) +#if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_D +#define MP_INT_TYPE (MP_INT_TYPE_INT64) +#else +#define MP_INT_TYPE (MP_INT_TYPE_INTPTR) +#endif +#endif + +#if MP_INT_TYPE == MP_INT_TYPE_INTPTR +typedef intptr_t mp_int_t; +// Use size_t so kw-function signatures and other size-typed APIs match without +// triggering -Wincompatible-pointer-types under newer GCCs where size_t and +// uintptr_t are distinct types of the same width (e.g. picolibc on 32-bit ARM). +typedef size_t mp_uint_t; +#define MP_INT_MAX INTPTR_MAX +#define MP_INT_MIN INTPTR_MIN +#define MP_UINT_MAX SIZE_MAX +#elif MP_INT_TYPE == MP_INT_TYPE_INT64 +typedef int64_t mp_int_t; +typedef uint64_t mp_uint_t; +#define MP_INT_MAX INT64_MAX +#define MP_INT_MIN INT64_MIN +#define MP_UINT_MAX INT64_UMAX +#endif + +// mp_printf format support for mp_int_t. In the unusual case that MP_INT_MAX doesn't +// match any of the standard C types (int/long/long long), provide all 3 +// macros. Otherwise, rely on these automatic definitions. +#if !defined(INT_FMT) +#if MP_INT_MAX == INT_MAX +#define INT_FMT "%d" +#define UINT_FMT "%u" +#define HEX_FMT "%x" +#elif MP_INT_MAX == LONG_MAX +#define INT_FMT "%ld" +#define UINT_FMT "%lu" +#define HEX_FMT "%lx" +#elif MP_INT_MAX == LLONG_MAX +#define INT_FMT "%lld" +#define UINT_FMT "%llu" +#define HEX_FMT "%llx" +#else +#error Unexpected MP_INT_MAX value +#endif +#endif + +// mp_printf format support for size_t. In the unusual case that SIZE_MAX doesn't +// match any of the standard C types (int/long/long long), provide a +// macro. Otherwise, rely on these automatic definitions. +#if !defined(SIZE_FMT) +#if SIZE_MAX == UINT_MAX +#define SIZE_FMT "%u" +#elif SIZE_MAX == ULONG_MAX +#define SIZE_FMT "%lu" +#elif SIZE_MAX == ULLONG_MAX +#define SIZE_FMT "%llu" +#else +#error Unexpected SIZE_MAX value +#endif +#endif + + /*****************************************************************************/ /* Memory allocation policy */ @@ -342,6 +426,11 @@ #define MICROPY_PERSISTENT_CODE_LOAD (0) #endif +// Whether to support loading of persistent native code +#ifndef MICROPY_PERSISTENT_CODE_LOAD_NATIVE +#define MICROPY_PERSISTENT_CODE_LOAD_NATIVE (MICROPY_EMIT_MACHINE_CODE) +#endif + // Whether to support saving of persistent code, i.e. for mpy-cross to // generate .mpy files. Enabling this enables additional metadata on raw code // objects which is also required for sys.settrace. @@ -354,10 +443,15 @@ #define MICROPY_PERSISTENT_CODE_SAVE_FILE (0) #endif +// Whether to support converting functions to persistent code (bytes) +#ifndef MICROPY_PERSISTENT_CODE_SAVE_FUN +#define MICROPY_PERSISTENT_CODE_SAVE_FUN (MICROPY_PY_MARSHAL) +#endif + // Whether generated code can persist independently of the VM/runtime instance // This is enabled automatically when needed by other features #ifndef MICROPY_PERSISTENT_CODE -#define MICROPY_PERSISTENT_CODE (MICROPY_PERSISTENT_CODE_LOAD || MICROPY_PERSISTENT_CODE_SAVE || MICROPY_MODULE_FROZEN_MPY) +#define MICROPY_PERSISTENT_CODE (MICROPY_PERSISTENT_CODE_LOAD || MICROPY_PERSISTENT_CODE_LOAD_NATIVE || MICROPY_PERSISTENT_CODE_SAVE || MICROPY_MODULE_FROZEN_MPY) #endif // Whether bytecode uses a qstr_table to map internal qstr indices in the bytecode @@ -385,7 +479,11 @@ // Whether to emit ARMv7-M instruction support in thumb native code #ifndef MICROPY_EMIT_THUMB_ARMV7M +#if defined(__ARM_ARCH_ISA_THUMB) && __ARM_ARCH_ISA_THUMB == 2 #define MICROPY_EMIT_THUMB_ARMV7M (1) +#else +#define MICROPY_EMIT_THUMB_ARMV7M (0) +#endif #endif // Whether to enable the thumb inline assembler @@ -395,7 +493,11 @@ // Whether to enable float support in the Thumb2 inline assembler #ifndef MICROPY_EMIT_INLINE_THUMB_FLOAT +#if defined(__ARM_ARCH_ISA_THUMB) && __ARM_ARCH_ISA_THUMB == 2 && defined(__ARM_FP) #define MICROPY_EMIT_INLINE_THUMB_FLOAT (1) +#else +#define MICROPY_EMIT_INLINE_THUMB_FLOAT (0) +#endif #endif // Whether to emit ARM native code @@ -413,36 +515,63 @@ #define MICROPY_EMIT_INLINE_XTENSA (0) #endif +// Whether to support uncommon Xtensa inline assembler opcodes +#ifndef MICROPY_EMIT_INLINE_XTENSA_UNCOMMON_OPCODES +#define MICROPY_EMIT_INLINE_XTENSA_UNCOMMON_OPCODES (0) +#endif + // Whether to emit Xtensa-Windowed native code #ifndef MICROPY_EMIT_XTENSAWIN #define MICROPY_EMIT_XTENSAWIN (0) #endif +// Whether to emit RISC-V RV32 native code +#ifndef MICROPY_EMIT_RV32 +#define MICROPY_EMIT_RV32 (0) +#endif + +// Whether to emit RISC-V RV32 Zba opcodes in native code +#ifndef MICROPY_EMIT_RV32_ZBA +#define MICROPY_EMIT_RV32_ZBA (0) +#endif + +// Whether to emit RISC-V RV32 Zcmp opcodes in native code +#ifndef MICROPY_EMIT_RV32_ZCMP +#define MICROPY_EMIT_RV32_ZCMP (0) +#endif + +// Whether to enable the RISC-V RV32 inline assembler +#ifndef MICROPY_EMIT_INLINE_RV32 +#define MICROPY_EMIT_INLINE_RV32 (0) +#endif + +// Whether to enable the human-readable native instructions emitter +#ifndef MICROPY_EMIT_NATIVE_DEBUG +#define MICROPY_EMIT_NATIVE_DEBUG (0) +#endif + // Convenience definition for whether any native emitter is enabled -#define MICROPY_EMIT_NATIVE (MICROPY_EMIT_X64 || MICROPY_EMIT_X86 || MICROPY_EMIT_THUMB || MICROPY_EMIT_ARM || MICROPY_EMIT_XTENSA || MICROPY_EMIT_XTENSAWIN) +#define MICROPY_EMIT_NATIVE (MICROPY_EMIT_X64 || MICROPY_EMIT_X86 || MICROPY_EMIT_THUMB || MICROPY_EMIT_ARM || MICROPY_EMIT_XTENSA || MICROPY_EMIT_XTENSAWIN || MICROPY_EMIT_RV32 || MICROPY_EMIT_NATIVE_DEBUG) // Some architectures cannot read byte-wise from executable memory. In this case // the prelude for a native function (which usually sits after the machine code) // must be separated and placed somewhere where it can be read byte-wise. +// CIRCUITPY-CHANGE: also when only loading native code on windowed Xtensa. +#if defined(__XTENSA_WINDOWED_ABI__) +#define MICROPY_EMIT_NATIVE_PRELUDE_SEPARATE_FROM_MACHINE_CODE (MICROPY_EMIT_XTENSAWIN || MICROPY_PERSISTENT_CODE_LOAD_NATIVE) +#else #define MICROPY_EMIT_NATIVE_PRELUDE_SEPARATE_FROM_MACHINE_CODE (MICROPY_EMIT_XTENSAWIN) +#endif // Convenience definition for whether any inline assembler emitter is enabled -#define MICROPY_EMIT_INLINE_ASM (MICROPY_EMIT_INLINE_THUMB || MICROPY_EMIT_INLINE_XTENSA) +#define MICROPY_EMIT_INLINE_ASM (MICROPY_EMIT_INLINE_THUMB || MICROPY_EMIT_INLINE_XTENSA || MICROPY_EMIT_INLINE_RV32) // Convenience definition for whether any native or inline assembler emitter is enabled #define MICROPY_EMIT_MACHINE_CODE (MICROPY_EMIT_NATIVE || MICROPY_EMIT_INLINE_ASM) -// Whether native relocatable code loaded from .mpy files is explicitly tracked -// so that the GC cannot reclaim it. Needed on architectures that allocate -// executable memory on the MicroPython heap and don't explicitly track this -// data some other way. -#ifndef MICROPY_PERSISTENT_CODE_TRACK_RELOC_CODE -#if !MICROPY_EMIT_MACHINE_CODE || defined(MP_PLAT_ALLOC_EXEC) || defined(MP_PLAT_COMMIT_EXEC) -#define MICROPY_PERSISTENT_CODE_TRACK_RELOC_CODE (0) -#else -#define MICROPY_PERSISTENT_CODE_TRACK_RELOC_CODE (1) -#endif -#endif +// Convenience definition for whether native code has to be dealt with (either +// generated or loaded from a file). This does not cover inline asm code. +#define MICROPY_ENABLE_NATIVE_CODE (MICROPY_EMIT_NATIVE || MICROPY_PERSISTENT_CODE_LOAD_NATIVE) /*****************************************************************************/ /* Compiler configuration */ @@ -489,6 +618,13 @@ #define MICROPY_COMP_CONST (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_CORE_FEATURES) #endif +// Whether to enable float constant folding like 1.2+3.4 (when MICROPY_COMP_CONST_FOLDING is also enabled) +// and constant optimisation like id = const(1.2) (when MICROPY_COMP_CONST is also enabled) +// and constant lookup like math.inf (when MICROPY_COMP_MODULE_CONST is also enabled) +#ifndef MICROPY_COMP_CONST_FLOAT +#define MICROPY_COMP_CONST_FLOAT (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_CORE_FEATURES) +#endif + // Whether to enable optimisation of: a, b = c, d // Costs 124 bytes (Thumb2) #ifndef MICROPY_COMP_DOUBLE_TUPLE_ASSIGN @@ -712,6 +848,20 @@ #define MICROPY_STACK_CHECK (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_EXTRA_FEATURES) #endif +// Additional margin between the places in the runtime where Python stack is +// checked and the actual end of the C stack. Needs to be large enough to avoid +// overflows from function calls made between checks. +#ifndef MICROPY_STACK_CHECK_MARGIN +#define MICROPY_STACK_CHECK_MARGIN (0) +#endif + +// The size of a separate stack used for hard IRQ handlers, which should be +// checked instead of the main stack when running a hard callback. 0 implies +// there is no separate ISR stack to check. +#ifndef MICROPY_STACK_SIZE_HARD_IRQ +#define MICROPY_STACK_SIZE_HARD_IRQ (0) +#endif + // Whether to have an emergency exception buffer #ifndef MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF #define MICROPY_ENABLE_EMERGENCY_EXCEPTION_BUF (0) @@ -877,10 +1027,36 @@ typedef double mp_float_t; #define MICROPY_PY_BUILTINS_FLOAT (0) #endif +// CIRCUITPY-CHANGE: whether mp_printf() supports %e, %f and %g +#ifndef MICROPY_PRINTF_FLOAT +#define MICROPY_PRINTF_FLOAT (MICROPY_PY_BUILTINS_FLOAT) +#endif + #ifndef MICROPY_PY_BUILTINS_COMPLEX #define MICROPY_PY_BUILTINS_COMPLEX (MICROPY_PY_BUILTINS_FLOAT) #endif +// Float to string conversion implementations +// +// Note that the EXACT method is only available if the compiler supports +// floating points larger than mp_float_t: +// - with MICROPY_FLOAT_IMPL_FLOAT, the compiler needs to support `double` +// - with MICROPY_FLOAT_IMPL_DOUBLE, the compiler needs to support `long double` +// +#define MICROPY_FLOAT_FORMAT_IMPL_BASIC (0) // smallest code, but inexact +#define MICROPY_FLOAT_FORMAT_IMPL_APPROX (1) // slightly bigger, almost perfect +#define MICROPY_FLOAT_FORMAT_IMPL_EXACT (2) // bigger code, and 100% exact repr + +#ifndef MICROPY_FLOAT_FORMAT_IMPL +#if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT +#define MICROPY_FLOAT_FORMAT_IMPL (MICROPY_FLOAT_FORMAT_IMPL_APPROX) +#elif defined(__SIZEOF_LONG_DOUBLE__) && __SIZEOF_LONG_DOUBLE__ > __SIZEOF_DOUBLE__ +#define MICROPY_FLOAT_FORMAT_IMPL (MICROPY_FLOAT_FORMAT_IMPL_EXACT) +#else +#define MICROPY_FLOAT_FORMAT_IMPL (MICROPY_FLOAT_FORMAT_IMPL_APPROX) +#endif +#endif + // Whether to use the native _Float16 for 16-bit float support #ifndef MICROPY_FLOAT_USE_NATIVE_FLT16 #ifdef __FLT16_MAX__ @@ -913,6 +1089,64 @@ typedef double mp_float_t; #define MICROPY_FULL_CHECKS (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_CORE_FEATURES) #endif +// Ports can choose to use timestamps based on 2000-01-01 or 1970-01-01 +// Default is timestamps based on 2000-01-01 +#if !defined(MICROPY_EPOCH_IS_2000) && !defined(MICROPY_EPOCH_IS_1970) +#define MICROPY_EPOCH_IS_2000 (1) +#define MICROPY_EPOCH_IS_1970 (0) +#elif !defined(MICROPY_EPOCH_IS_1970) +#define MICROPY_EPOCH_IS_1970 (1 - (MICROPY_EPOCH_IS_2000)) +#elif !defined(MICROPY_EPOCH_IS_2000) +#define MICROPY_EPOCH_IS_2000 (1 - (MICROPY_EPOCH_IS_1970)) +#endif + +// To maintain reasonable compatibility with CPython on embedded systems, +// and avoid breaking anytime soon, time functions are defined to work +// at least between 1970 and 2099 (included) on any machine. +// +// Specific ports can enable extended date support +// - after 2099 using MICROPY_TIME_SUPPORT_Y2100_AND_BEYOND +// - before 1970 using MICROPY_TIME_SUPPORT_Y1969_AND_BEFORE +// The largest possible range is year 1600 to year 3000 +// +// By default, extended date support is only enabled for machines using 64 bit pointers, +// but it can be enabled by specific ports +#ifndef MICROPY_TIME_SUPPORT_Y1969_AND_BEFORE +#if MP_SSIZE_MAX > 2147483647 +#define MICROPY_TIME_SUPPORT_Y1969_AND_BEFORE (1) +#else +#define MICROPY_TIME_SUPPORT_Y1969_AND_BEFORE (0) +#endif +#endif + +// When support for dates <1970 is enabled, supporting >=2100 does not cost anything +#ifndef MICROPY_TIME_SUPPORT_Y2100_AND_BEYOND +#define MICROPY_TIME_SUPPORT_Y2100_AND_BEYOND (MICROPY_TIME_SUPPORT_Y1969_AND_BEFORE) +#endif + +// The type to be used to represent platform-specific timestamps depends on the choices above +#define MICROPY_TIMESTAMP_IMPL_LONG_LONG (0) +#define MICROPY_TIMESTAMP_IMPL_UINT (1) +#define MICROPY_TIMESTAMP_IMPL_TIME_T (2) + +#ifndef MICROPY_TIMESTAMP_IMPL +#if MICROPY_TIME_SUPPORT_Y2100_AND_BEYOND || MICROPY_TIME_SUPPORT_Y1969_AND_BEFORE || MICROPY_EPOCH_IS_2000 +#define MICROPY_TIMESTAMP_IMPL (MICROPY_TIMESTAMP_IMPL_LONG_LONG) +#else +#define MICROPY_TIMESTAMP_IMPL (MICROPY_TIMESTAMP_IMPL_UINT) +#endif +#endif + +// `mp_timestamp_t` is the type that should be used by the port +// to represent timestamps, and is referenced to the platform epoch +#if MICROPY_TIMESTAMP_IMPL == MICROPY_TIMESTAMP_IMPL_LONG_LONG +typedef long long mp_timestamp_t; +#elif MICROPY_TIMESTAMP_IMPL == MICROPY_TIMESTAMP_IMPL_UINT +typedef mp_uint_t mp_timestamp_t; +#elif MICROPY_TIMESTAMP_IMPL == MICROPY_TIMESTAMP_IMPL_TIME_T +typedef time_t mp_timestamp_t; +#endif + // Whether POSIX-semantics non-blocking streams are supported #ifndef MICROPY_STREAMS_NON_BLOCK #define MICROPY_STREAMS_NON_BLOCK (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_EXTRA_FEATURES) @@ -924,6 +1158,22 @@ typedef double mp_float_t; #define MICROPY_STREAMS_POSIX_API (0) #endif +// Whether to delegate error raising to stream implementations using the +// MP_STREAM_RAISE_ERROR ioctl to support raising more detailed messages. +#ifndef MICROPY_STREAMS_DELEGATE_ERROR +#define MICROPY_STREAMS_DELEGATE_ERROR (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_EXTRA_FEATURES) +#endif + +// Whether to process __all__ when importing all public symbols from a module. +#ifndef MICROPY_MODULE___ALL__ +#define MICROPY_MODULE___ALL__ (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_BASIC_FEATURES) +#endif + +// Whether to set __file__ on imported modules. +#ifndef MICROPY_MODULE___FILE__ +#define MICROPY_MODULE___FILE__ (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_CORE_FEATURES) +#endif + // Whether modules can use MP_REGISTER_MODULE_DELEGATION() to delegate failed // attribute lookups to a custom handler function. #ifndef MICROPY_MODULE_ATTR_DELEGATION @@ -948,7 +1198,7 @@ typedef double mp_float_t; // have __init__ methods. Instead, the top-level package's __init__ should // initialise all sub-packages. #ifndef MICROPY_MODULE_BUILTIN_SUBPACKAGES -#define MICROPY_MODULE_BUILTIN_SUBPACKAGES (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_EVERYTHING) +#define MICROPY_MODULE_BUILTIN_SUBPACKAGES (MICROPY_PY_TSTRINGS || MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_EVERYTHING) #endif // Whether to support module-level __getattr__ (see PEP 562) @@ -1011,6 +1261,16 @@ typedef double mp_float_t; #define MICROPY_ENABLE_VM_ABORT (0) #endif +// Whether to handle abort behavior in pyexec code +#ifndef MICROPY_PYEXEC_ENABLE_VM_ABORT +#define MICROPY_PYEXEC_ENABLE_VM_ABORT (0) +#endif + +// Whether to set exit codes according to the exit reason (keyboard interrupt, crash, normal exit, ...) +#ifndef MICROPY_PYEXEC_ENABLE_EXIT_CODE_HANDLING +#define MICROPY_PYEXEC_ENABLE_EXIT_CODE_HANDLING (0) +#endif + // Support for internal scheduler #ifndef MICROPY_ENABLE_SCHEDULER #define MICROPY_ENABLE_SCHEDULER (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_EXTRA_FEATURES) @@ -1031,11 +1291,31 @@ typedef double mp_float_t; #define MICROPY_VFS (0) #endif +// Whether to include support for fast native block devices. +#ifndef MICROPY_VFS_BLOCKDEV_NATIVE +#define MICROPY_VFS_BLOCKDEV_NATIVE (0) +#endif + +// Whether to include support for writable filesystems. +#ifndef MICROPY_VFS_WRITABLE +#define MICROPY_VFS_WRITABLE (1) +#endif + +// Whether to enable the mp_vfs_rom_ioctl C function, and vfs.rom_ioctl Python function +#ifndef MICROPY_VFS_ROM_IOCTL +#define MICROPY_VFS_ROM_IOCTL (MICROPY_VFS_ROM) +#endif + // Support for VFS POSIX component, to mount a POSIX filesystem within VFS #ifndef MICROPY_VFS_POSIX #define MICROPY_VFS_POSIX (0) #endif +// Whether to include support for writable POSIX filesystems. +#ifndef MICROPY_VFS_POSIX_WRITABLE +#define MICROPY_VFS_POSIX_WRITABLE (1) +#endif + // Support for VFS FAT component, to mount a FAT filesystem within VFS #ifndef MICROPY_VFS_FAT #define MICROPY_VFS_FAT (0) @@ -1051,6 +1331,11 @@ typedef double mp_float_t; #define MICROPY_VFS_LFS2 (0) #endif +// Support for ROMFS. +#ifndef MICROPY_VFS_ROM +#define MICROPY_VFS_ROM (0) +#endif + /*****************************************************************************/ /* Fine control over Python builtins, classes, modules, etc */ @@ -1066,7 +1351,20 @@ typedef double mp_float_t; #define MICROPY_PY_FUNCTION_ATTRS (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_EXTRA_FEATURES) #endif -// Whether to support the descriptors __get__, __set__, __delete__ +// Whether to implement the __code__ attribute on functions, and function constructor +#ifndef MICROPY_PY_FUNCTION_ATTRS_CODE +#define MICROPY_PY_FUNCTION_ATTRS_CODE (MICROPY_PY_MARSHAL || MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_FULL_FEATURES) +#endif + +// Whether bound_method can just use == (feature disabled), or requires a call to +// mp_obj_equal (feature enabled), to test equality of the self and meth entities. +// This is only needed if objects and functions can be identical without being the +// same thing, eg when using an object proxy. +#ifndef MICROPY_PY_BOUND_METHOD_FULL_EQUALITY_CHECK +#define MICROPY_PY_BOUND_METHOD_FULL_EQUALITY_CHECK (0) +#endif + +// Whether to support the descriptors __get__, __set__, __delete__, __set_name__ // This costs some code size and makes load/store/delete of instance // attributes slower for the classes that use this feature #ifndef MICROPY_PY_DESCRIPTORS @@ -1090,6 +1388,12 @@ typedef double mp_float_t; #define MICROPY_PY_FSTRINGS (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_EXTRA_FEATURES) #endif +// Support for template strings, t-strings (see PEP 750, Python 3.14+) +// Requires MICROPY_PY_FSTRINGS to be enabled. +#ifndef MICROPY_PY_TSTRINGS +#define MICROPY_PY_TSTRINGS (MICROPY_PY_FSTRINGS && MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_FULL_FEATURES) +#endif + // Support for assignment expressions with := (see PEP 572, Python 3.8+) #ifndef MICROPY_PY_ASSIGN_EXPR #define MICROPY_PY_ASSIGN_EXPR (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_CORE_FEATURES) @@ -1116,7 +1420,7 @@ typedef double mp_float_t; // Whether str object is proper unicode #ifndef MICROPY_PY_BUILTINS_STR_UNICODE -#define MICROPY_PY_BUILTINS_STR_UNICODE (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_EXTRA_FEATURES) +#define MICROPY_PY_BUILTINS_STR_UNICODE (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_BASIC_FEATURES) #endif // Whether to check for valid UTF-8 when converting bytes to str @@ -1124,6 +1428,11 @@ typedef double mp_float_t; #define MICROPY_PY_BUILTINS_STR_UNICODE_CHECK (MICROPY_PY_BUILTINS_STR_UNICODE) #endif +// Whether bytes.decode() supports the 'ignore' and 'replace' error handlers +#ifndef MICROPY_PY_BUILTINS_BYTES_DECODE_ERRORS +#define MICROPY_PY_BUILTINS_BYTES_DECODE_ERRORS (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_EXTRA_FEATURES) +#endif + // Whether str.center() method provided #ifndef MICROPY_PY_BUILTINS_STR_CENTER #define MICROPY_PY_BUILTINS_STR_CENTER (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_EXTRA_FEATURES) @@ -1154,6 +1463,15 @@ typedef double mp_float_t; #define MICROPY_PY_BUILTINS_BYTEARRAY (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_CORE_FEATURES) #endif +// Whether to support code objects, and how many features they have +#define MICROPY_PY_BUILTINS_CODE_NONE (0) +#define MICROPY_PY_BUILTINS_CODE_MINIMUM (1) +#define MICROPY_PY_BUILTINS_CODE_BASIC (2) +#define MICROPY_PY_BUILTINS_CODE_FULL (3) +#ifndef MICROPY_PY_BUILTINS_CODE +#define MICROPY_PY_BUILTINS_CODE (MICROPY_PY_SYS_SETTRACE ? MICROPY_PY_BUILTINS_CODE_FULL : (MICROPY_PY_FUNCTION_ATTRS_CODE ? MICROPY_PY_BUILTINS_CODE_BASIC : (MICROPY_PY_BUILTINS_COMPILE ? MICROPY_PY_BUILTINS_CODE_MINIMUM : MICROPY_PY_BUILTINS_CODE_NONE))) +#endif + // Whether to support dict.fromkeys() class method #ifndef MICROPY_PY_BUILTINS_DICT_FROMKEYS #define MICROPY_PY_BUILTINS_DICT_FROMKEYS (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_CORE_FEATURES) @@ -1166,7 +1484,7 @@ typedef double mp_float_t; // Whether to support memoryview.itemsize attribute #ifndef MICROPY_PY_BUILTINS_MEMORYVIEW_ITEMSIZE -#define MICROPY_PY_BUILTINS_MEMORYVIEW_ITEMSIZE (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_EVERYTHING) +#define MICROPY_PY_BUILTINS_MEMORYVIEW_ITEMSIZE (MICROPY_PY_MACHINE_MEM_BACKUP || MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_BASIC_FEATURES) #endif // Whether to support set object @@ -1216,7 +1534,7 @@ typedef double mp_float_t; // Support for calling next() with second argument #ifndef MICROPY_PY_BUILTINS_NEXT2 -#define MICROPY_PY_BUILTINS_NEXT2 (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_EVERYTHING) +#define MICROPY_PY_BUILTINS_NEXT2 (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_BASIC_FEATURES) #endif // Whether to support rounding of integers (incl bignum); eg round(123,-1)=120 @@ -1224,6 +1542,11 @@ typedef double mp_float_t; #define MICROPY_PY_BUILTINS_ROUND_INT (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_EXTRA_FEATURES) #endif +// Whether to implement dir() to enumerate object fields. +#ifndef MICROPY_PY_BUILTINS_DIR +#define MICROPY_PY_BUILTINS_DIR (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_CORE_FEATURES) +#endif + // Whether to support complete set of special methods for user // classes, or only the most used ones. "Inplace" methods are // controlled by MICROPY_PY_ALL_INPLACE_SPECIAL_METHODS below. @@ -1314,9 +1637,14 @@ typedef double mp_float_t; #define MICROPY_PY_BUILTINS_HELP_MODULES (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_EXTRA_FEATURES) #endif -// Whether to set __file__ for imported modules -#ifndef MICROPY_PY___FILE__ -#define MICROPY_PY___FILE__ (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_CORE_FEATURES) +// Use this to configure output of help('modules') +#ifndef MICROPY_PY_BUILTINS_HELP_NUM_COLUMNS +#define MICROPY_PY_BUILTINS_HELP_NUM_COLUMNS (4) +#endif + +// Use this to configure output of help('modules') +#ifndef MICROPY_PY_BUILTINS_HELP_COLUMN_WIDTH +#define MICROPY_PY_BUILTINS_HELP_COLUMN_WIDTH (18) #endif // Whether to provide mem-info related functions in micropython module @@ -1334,6 +1662,11 @@ typedef double mp_float_t; #define MICROPY_PY_MICROPYTHON_HEAP_LOCKED (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_EVERYTHING) #endif +// Support for micropython.RingIO() +#ifndef MICROPY_PY_MICROPYTHON_RINGIO +#define MICROPY_PY_MICROPYTHON_RINGIO (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_EXTRA_FEATURES) +#endif + // Whether to provide "array" module. Note that large chunk of the // underlying code is shared with "bytearray" builtin type, so to // get real savings, it should be disabled too. @@ -1383,6 +1716,11 @@ typedef double mp_float_t; #define MICROPY_PY_COLLECTIONS_NAMEDTUPLE__ASDICT (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_EVERYTHING) #endif +// Whether to provide "marshal" module +#ifndef MICROPY_PY_MARSHAL +#define MICROPY_PY_MARSHAL (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_EVERYTHING) +#endif + // Whether to provide "math" module #ifndef MICROPY_PY_MATH #define MICROPY_PY_MATH (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_CORE_FEATURES) @@ -1424,10 +1762,16 @@ typedef double mp_float_t; #endif // Whether to provide fix for pow(1, NaN) and pow(NaN, 0), which both should be 1 not NaN. +// Also fixes pow(base, NaN) to return NaN for other values of base. #ifndef MICROPY_PY_MATH_POW_FIX_NAN #define MICROPY_PY_MATH_POW_FIX_NAN (0) #endif +// Whether to provide fix for gamma(-inf) to raise ValueError +#ifndef MICROPY_PY_MATH_GAMMA_FIX_NEGINF +#define MICROPY_PY_MATH_GAMMA_FIX_NEGINF (0) +#endif + // Whether to provide "cmath" module #ifndef MICROPY_PY_CMATH #define MICROPY_PY_CMATH (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_EXTRA_FEATURES) @@ -1455,7 +1799,7 @@ typedef double mp_float_t; // Whether to provide "io.IOBase" class to support user streams #ifndef MICROPY_PY_IO_IOBASE -#define MICROPY_PY_IO_IOBASE (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_EXTRA_FEATURES) +#define MICROPY_PY_IO_IOBASE (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_CORE_FEATURES) #endif // Whether to provide "io.BytesIO" class @@ -1473,15 +1817,16 @@ typedef double mp_float_t; #define MICROPY_PY_STRUCT (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_CORE_FEATURES) #endif -// CIRCUITPY-CHANGE -// Whether to provide non-standard typecodes in "struct" module -#ifndef MICROPY_NONSTANDARD_TYPECODES -#define MICROPY_NONSTANDARD_TYPECODES (1) +// Whether struct module provides unsafe and non-standard typecodes O, P, S. +// These typecodes are not in CPython and can cause crashes by accessing arbitrary +// memory. +#ifndef MICROPY_PY_STRUCT_UNSAFE_TYPECODES +#define MICROPY_PY_STRUCT_UNSAFE_TYPECODES (1) #endif // Whether to provide "sys" module #ifndef MICROPY_PY_SYS -#define MICROPY_PY_SYS (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_CORE_FEATURES) +#define MICROPY_PY_SYS (1) #endif // Whether to initialise "sys.path" and "sys.argv" to their defaults in mp_init() @@ -1605,7 +1950,7 @@ typedef double mp_float_t; // implementation). This is present for compatibility but can be disabled to // save space. #ifndef MICROPY_PY_SELECT_SELECT -#define MICROPY_PY_SELECT_SELECT (1) +#define MICROPY_PY_SELECT_SELECT (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_EXTRA_FEATURES) #endif // Whether to provide the "time" module @@ -1650,12 +1995,26 @@ typedef double mp_float_t; #define MICROPY_PY_THREAD_GIL_VM_DIVISOR (32) #endif +// Is a recursive mutex type in use? +#ifndef MICROPY_PY_THREAD_RECURSIVE_MUTEX +#define MICROPY_PY_THREAD_RECURSIVE_MUTEX (MICROPY_PY_THREAD && !MICROPY_PY_THREAD_GIL) +#endif + +// Whether to provide the "weakref" module. +#ifndef MICROPY_PY_WEAKREF +#define MICROPY_PY_WEAKREF (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_EVERYTHING) +#endif + // Extended modules #ifndef MICROPY_PY_ASYNCIO #define MICROPY_PY_ASYNCIO (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_EXTRA_FEATURES) #endif +#ifndef MICROPY_PY_ASYNCIO_TASK_QUEUE_PUSH_CALLBACK +#define MICROPY_PY_ASYNCIO_TASK_QUEUE_PUSH_CALLBACK (0) +#endif + #ifndef MICROPY_PY_UCTYPES #define MICROPY_PY_UCTYPES (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_EXTRA_FEATURES) #endif @@ -1728,11 +2087,11 @@ typedef double mp_float_t; #endif #ifndef MICROPY_PY_HASHLIB_MD5 -#define MICROPY_PY_HASHLIB_MD5 (0) +#define MICROPY_PY_HASHLIB_MD5 (MICROPY_PY_SSL) #endif #ifndef MICROPY_PY_HASHLIB_SHA1 -#define MICROPY_PY_HASHLIB_SHA1 (0) +#define MICROPY_PY_HASHLIB_SHA1 (MICROPY_PY_SSL) #endif #ifndef MICROPY_PY_HASHLIB_SHA256 @@ -1740,7 +2099,7 @@ typedef double mp_float_t; #endif #ifndef MICROPY_PY_CRYPTOLIB -#define MICROPY_PY_CRYPTOLIB (0) +#define MICROPY_PY_CRYPTOLIB (MICROPY_PY_SSL) #endif // Depends on MICROPY_PY_CRYPTOLIB @@ -1757,6 +2116,7 @@ typedef double mp_float_t; #endif // CIRCUITPY-CHANGE: does not depend on MICROPY_PY_DEFLATE +// Depends on MICROPY_PY_DEFLATE #ifndef MICROPY_PY_BINASCII_CRC32 #define MICROPY_PY_BINASCII_CRC32 (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_EXTRA_FEATURES) #endif @@ -1779,6 +2139,11 @@ typedef double mp_float_t; #define MICROPY_PY_MACHINE_RESET (0) #endif +// Maximum number of arguments for machine.freq() +#ifndef MICROPY_PY_MACHINE_FREQ_NUM_ARGS_MAX +#define MICROPY_PY_MACHINE_FREQ_NUM_ARGS_MAX (1) +#endif + // Whether to include: bitstream #ifndef MICROPY_PY_MACHINE_BITSTREAM #define MICROPY_PY_MACHINE_BITSTREAM (0) @@ -1794,6 +2159,11 @@ typedef double mp_float_t; #define MICROPY_PY_MACHINE_MEMX (MICROPY_PY_MACHINE) #endif +// Whether to provide the "machine.mem_backup" function +#ifndef MICROPY_PY_MACHINE_MEM_BACKUP +#define MICROPY_PY_MACHINE_MEM_BACKUP (0) +#endif + // Whether to provide the "machine.Signal" class #ifndef MICROPY_PY_MACHINE_SIGNAL #define MICROPY_PY_MACHINE_SIGNAL (MICROPY_PY_MACHINE) @@ -1822,6 +2192,12 @@ typedef double mp_float_t; #define MICROPY_PY_MACHINE_SOFTSPI (0) #endif +// Values of SPI.MSB and SPI.LSB constants +#ifndef MICROPY_PY_MACHINE_SPI_MSB +#define MICROPY_PY_MACHINE_SPI_MSB (0) +#define MICROPY_PY_MACHINE_SPI_LSB (1) +#endif + // Whether to provide the "machine.Timer" class #ifndef MICROPY_PY_MACHINE_TIMER #define MICROPY_PY_MACHINE_TIMER (0) @@ -1832,15 +2208,40 @@ typedef double mp_float_t; #define MICROPY_PY_SOCKET_LISTEN_BACKLOG_DEFAULT (2) #endif +// Whether to enable lwIP bindings to be used as the implementation of the `socket` module +#ifndef MICROPY_PY_LWIP +#define MICROPY_PY_LWIP (0) +#endif + +// Whether to support raw sockets via the `socket.SOCK_RAW` constant +#ifndef MICROPY_PY_LWIP_SOCK_RAW +#define MICROPY_PY_LWIP_SOCK_RAW (MICROPY_PY_LWIP) +#endif + #ifndef MICROPY_PY_SSL #define MICROPY_PY_SSL (0) #endif +// CIRCUITPY-CHANGE: avoid undefined warnings +#ifndef MICROPY_PY_SSL_ECDSA_SIGN_ALT +#define MICROPY_PY_SSL_ECDSA_SIGN_ALT (0) +#endif + // Whether to add finaliser code to ssl objects #ifndef MICROPY_PY_SSL_FINALISER #define MICROPY_PY_SSL_FINALISER (MICROPY_ENABLE_FINALISER) #endif +// Whether to add a root pointer for the current ssl object +#ifndef MICROPY_PY_SSL_MBEDTLS_NEED_ACTIVE_CONTEXT +#define MICROPY_PY_SSL_MBEDTLS_NEED_ACTIVE_CONTEXT (MICROPY_PY_SSL_ECDSA_SIGN_ALT) +#endif + +// Whether to support DTLS protocol (non-CPython feature) +#ifndef MICROPY_PY_SSL_DTLS +#define MICROPY_PY_SSL_DTLS (MICROPY_SSL_MBEDTLS && MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_EXTRA_FEATURES) +#endif + // Whether to provide the "vfs" module #ifndef MICROPY_PY_VFS #define MICROPY_PY_VFS (MICROPY_CONFIG_ROM_LEVEL_AT_LEAST_CORE_FEATURES && MICROPY_VFS) @@ -1933,7 +2334,7 @@ typedef double mp_float_t; /*****************************************************************************/ /* Miscellaneous settings */ -// All uPy objects in ROM must be aligned on at least a 4 byte boundary +// All MicroPython objects in ROM must be aligned on at least a 4 byte boundary // so that the small-int/qstr/pointer distinction can be made. For machines // that don't do this (eg 16-bit CPU), define the following macro to something // like __attribute__((aligned(4))). @@ -2008,14 +2409,48 @@ typedef double mp_float_t; #define MICROPY_MAKE_POINTER_CALLABLE(p) (p) #endif -// If these MP_PLAT_*_EXEC macros are overridden then the memory allocated by them -// must be somehow reachable for marking by the GC, since the native code -// generators store pointers to GC managed memory in the code. +// Whether native text/BSS/rodata memory loaded from .mpy files is explicitly tracked +// so that the GC cannot reclaim it. +// +// In general a port should let these options have their defaults, but the defaults here +// can be overridden if needed by defining both MICROPY_PERSISTENT_CODE_TRACK_FUN_DATA +// and MICROPY_PERSISTENT_CODE_TRACK_BSS_RODATA. +#ifndef MICROPY_PERSISTENT_CODE_TRACK_FUN_DATA +#if (MICROPY_EMIT_INLINE_ASM || MICROPY_ENABLE_NATIVE_CODE) && MICROPY_PERSISTENT_CODE_LOAD +// Pointer tracking is required when loading native code is enabled. +#if defined(MP_PLAT_ALLOC_EXEC) || defined(MP_PLAT_COMMIT_EXEC) +// If a port defined a custom allocator or commit function for native text, then the +// text does not need to be tracked (its allocation is managed by the port). But the +// BSS/rodata must be tracked (if there is any) because if there are any pointers to it +// in the function data, they aren't traced by the GC. +#define MICROPY_PERSISTENT_CODE_TRACK_FUN_DATA (0) +#define MICROPY_PERSISTENT_CODE_TRACK_BSS_RODATA (1) +#else +// If a port uses the default allocator (the GC heap) then all native text is allocated +// on the GC heap. But it's not guaranteed that a pointer to the head of the block of +// native text (which may contain multiple native functions) will be retained for the GC +// to trace. This is because native functions can start inside the big block of text +// and so it's possible that the only GC-reachable pointers are pointers inside. +// Therefore the big block is explicitly tracked. If there is any BSS/rodata memory, +// then it does not need to be explicitly tracked because a pointer to it is stored into +// the function text via `mp_native_relocate()`. +#define MICROPY_PERSISTENT_CODE_TRACK_FUN_DATA (1) +#define MICROPY_PERSISTENT_CODE_TRACK_BSS_RODATA (0) +#endif +#else // (MICROPY_EMIT_INLINE_ASM || MICROPY_ENABLE_NATIVE_CODE) && MICROPY_PERSISTENT_CODE_LOAD +// Pointer tracking not needed when loading native code is disabled. +#define MICROPY_PERSISTENT_CODE_TRACK_FUN_DATA (0) +#define MICROPY_PERSISTENT_CODE_TRACK_BSS_RODATA (0) +#endif +#endif + +// If these macros are defined then the memory allocated by them does not need to be +// traced by the GC. But if they are left undefined then the GC heap will be used as +// the allocator and the memory must be traced by the GC. See also above logic for +// enabling MICROPY_PERSISTENT_CODE_TRACK_FUN_DATA and +// MICROPY_PERSISTENT_CODE_TRACK_BSS_RODATA. #ifndef MP_PLAT_ALLOC_EXEC #define MP_PLAT_ALLOC_EXEC(min_size, ptr, size) do { *ptr = m_new(byte, min_size); *size = min_size; } while (0) -#endif - -#ifndef MP_PLAT_FREE_EXEC #define MP_PLAT_FREE_EXEC(ptr, size) m_del(byte, ptr, size) #endif @@ -2038,25 +2473,13 @@ typedef double mp_float_t; #define MP_SSIZE_MAX SSIZE_MAX #endif -// printf format spec to use for mp_int_t and friends -#ifndef INT_FMT -#if defined(__LP64__) -// Archs where mp_int_t == long, long != int -#define UINT_FMT "%lu" -#define INT_FMT "%ld" -#elif defined(_WIN64) -#define UINT_FMT "%llu" -#define INT_FMT "%lld" -#else -// Archs where mp_int_t == int -#define UINT_FMT "%u" -#define INT_FMT "%d" +// Modifier for function which doesn't return +#ifndef MP_NORETURN +#define MP_NORETURN __attribute__((noreturn)) #endif -#endif // INT_FMT -// Modifier for function which doesn't return -#ifndef NORETURN -#define NORETURN __attribute__((noreturn)) +#if !MICROPY_PREVIEW_VERSION_2 +#define NORETURN MP_NORETURN #endif // Modifier for weak functions @@ -2077,6 +2500,12 @@ typedef double mp_float_t; #define MP_INLINE inline MP_NO_INSTRUMENT #endif +// CIRCUITPY-CHANGE +// Modifier for functions whose return value should not be ignored +#ifndef MP_WARN_UNUSED_RESULT +#define MP_WARN_UNUSED_RESULT __attribute__((warn_unused_result)) +#endif + // Modifier for functions which should be never inlined #ifndef MP_NOINLINE #define MP_NOINLINE __attribute__((noinline)) @@ -2122,7 +2551,7 @@ 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_HTOBE16(x) MP_BSWAP16(x) #define MP_BE16TOH(x) MP_HTOBE16(x) #else #define MP_HTOBE16(x) (x) @@ -2132,7 +2561,7 @@ typedef double mp_float_t; #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_HTOBE32(x) MP_BSWAP32(x) #define MP_BE32TOH(x) MP_HTOBE32(x) #else #define MP_HTOBE32(x) (x) @@ -2151,4 +2580,23 @@ typedef double mp_float_t; #define MP_WARN_CAT(x) (NULL) #endif +// If true, use __builtin_mul_overflow (a gcc intrinsic supported by clang) for +// overflow checking when multiplying two small ints. Otherwise, use a portable +// algorithm. +// +// Most MCUs have a 32x32->64 bit multiply instruction, in which case the +// intrinsic is likely to be faster and generate smaller code. The main exception is +// cortex-m0 with __ARM_ARCH_ISA_THUMB == 1. +// +// The intrinsic is in GCC starting with version 5. +#ifndef MICROPY_USE_GCC_MUL_OVERFLOW_INTRINSIC +#if defined(__ARM_ARCH_ISA_THUMB) && (__GNUC__ >= 5) +#define MICROPY_USE_GCC_MUL_OVERFLOW_INTRINSIC (__ARM_ARCH_ISA_THUMB >= 2) +#elif (__GNUC__ >= 5) +#define MICROPY_USE_GCC_MUL_OVERFLOW_INTRINSIC (1) +#else +#define MICROPY_USE_GCC_MUL_OVERFLOW_INTRINSIC (0) +#endif +#endif + #endif // MICROPY_INCLUDED_PY_MPCONFIG_H diff --git a/py/mperrno.h b/py/mperrno.h index 9e4ecd9419c..6c675125f4e 100644 --- a/py/mperrno.h +++ b/py/mperrno.h @@ -143,6 +143,9 @@ #endif +// Type for return values where 0 indicates success and negative values are negated MP_E* error codes. +typedef int mp_negative_errno_t; + #if MICROPY_PY_ERRNO #include "py/obj.h" diff --git a/py/mphal.h b/py/mphal.h index a4f222d0b1e..3907641be83 100644 --- a/py/mphal.h +++ b/py/mphal.h @@ -27,6 +27,7 @@ #define MICROPY_INCLUDED_PY_MPHAL_H #include +#include #include "py/mpconfig.h" #ifdef MICROPY_MPHALPORT_H @@ -88,6 +89,8 @@ mp_uint_t mp_hal_ticks_cpu(void); uint64_t mp_hal_time_ns(void); #endif +// CIRCUITPY-CHANGE: extmod/virtpin.* not used by CircuitPython +#if 0 // If port HAL didn't define its own pin API, use generic // "virtual pin" API from the core. #ifndef mp_hal_pin_obj_t @@ -97,6 +100,7 @@ uint64_t mp_hal_time_ns(void); #define mp_hal_pin_write(pin, v) mp_virtual_pin_write(pin, v) #include "extmod/virtpin.h" #endif +#endif // Event handling and wait-for-event functions. diff --git a/py/mpprint.c b/py/mpprint.c index e4e25f5a82e..6f51777bb0c 100644 --- a/py/mpprint.c +++ b/py/mpprint.c @@ -40,8 +40,20 @@ #include "py/formatfloat.h" #endif -static const char pad_spaces[] = " "; -static const char pad_zeroes[] = "0000000000000000"; +static const char pad_spaces[16] = {' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '}; +#define pad_spaces_size (sizeof(pad_spaces)) +static const char pad_common[23] = {'0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '0', '_', '0', '0', '0', ',', '0', '0'}; +// The contents of pad_common is arranged to provide the following padding +// strings with minimal flash size: +// 0000000000000000 <- pad_zeroes +// 0000_000 <- pad_zeroes_underscore (offset: 12, size 5) +// 000,00 <- pad_zeroes_comma (offset: 17, size 4) +#define pad_zeroes (pad_common + 0) +#define pad_zeroes_size (16) +#define pad_zeroes_underscore (pad_common + 12) +#define pad_zeroes_underscore_size (5) +#define pad_zeroes_comma (pad_common + 17) +#define pad_zeroes_comma_size (4) static void plat_print_strn(void *env, const char *str, size_t len) { (void)env; @@ -58,20 +70,37 @@ int mp_print_str(const mp_print_t *print, const char *str) { return len; } -int mp_print_strn(const mp_print_t *print, const char *str, size_t len, int flags, char fill, int width) { +int mp_print_strn(const mp_print_t *print, const char *str, size_t len, unsigned int flags, char fill, int width) { int left_pad = 0; int right_pad = 0; int pad = width - len; int pad_size; int total_chars_printed = 0; const char *pad_chars; + char grouping = flags >> PF_FLAG_SEP_POS; if (!fill || fill == ' ') { pad_chars = pad_spaces; - pad_size = sizeof(pad_spaces) - 1; - } else if (fill == '0') { + pad_size = pad_spaces_size; + } else if (fill == '0' && !grouping) { pad_chars = pad_zeroes; - pad_size = sizeof(pad_zeroes) - 1; + pad_size = pad_zeroes_size; + } else if (fill == '0') { + if (grouping == '_') { + pad_chars = pad_zeroes_underscore; + pad_size = pad_zeroes_underscore_size; + } else { + pad_chars = pad_zeroes_comma; + pad_size = pad_zeroes_comma_size; + } + // The result will never start with a grouping character. An extra leading zero is added. + // width is dead after this so we can use it in calculation + if (width % pad_size == 0) { + pad++; + width++; + } + // position the grouping character correctly within the pad repetition + pad_chars += pad_size - 1 - width % pad_size; } else { // Other pad characters are fairly unusual, so we'll take the hit // and output them 1 at a time. @@ -201,7 +230,7 @@ static int mp_print_int(const mp_print_t *print, mp_uint_t x, int sgn, int base, return len; } -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) { +int mp_print_mp_int(const mp_print_t *print, mp_obj_t x, unsigned int base, int base_char, int flags, char fill, int width, int prec) { // These are the only values for "base" that are required to be supported by this // function, since Python only allows the user to format integers in these bases. // If needed this function could be generalised to handle other values. @@ -248,10 +277,7 @@ int mp_print_mp_int(const mp_print_t *print, mp_obj_t x, int base, int base_char int prefix_len = prefix - prefix_buf; prefix = prefix_buf; - char comma = '\0'; - if (flags & PF_FLAG_SHOW_COMMA) { - comma = ','; - } + char comma = flags >> PF_FLAG_SEP_POS; // The size of this buffer is rather arbitrary. If it's not large // enough, a dynamic one will be allocated. @@ -340,8 +366,8 @@ int mp_print_mp_int(const mp_print_t *print, mp_obj_t x, int base, int base_char } #if MICROPY_PY_BUILTINS_FLOAT -int mp_print_float(const mp_print_t *print, mp_float_t f, char fmt, int flags, char fill, int width, int prec) { - char buf[32]; +int mp_print_float(const mp_print_t *print, mp_float_t f, char fmt, unsigned int flags, char fill, int width, int prec) { + char buf[36]; char sign = '\0'; int chrs = 0; @@ -352,11 +378,17 @@ int mp_print_float(const mp_print_t *print, mp_float_t f, char fmt, int flags, c sign = ' '; } - int len = mp_format_float(f, buf, sizeof(buf), fmt, prec, sign); + int len = mp_format_float(f, buf, sizeof(buf) - 3, fmt, prec, sign); char *s = buf; - if ((flags & PF_FLAG_ADD_PERCENT) && (size_t)(len + 1) < sizeof(buf)) { + if ((flags & PF_FLAG_ALWAYS_DECIMAL) && strchr(buf, '.') == NULL && strchr(buf, 'e') == NULL && strchr(buf, 'n') == NULL) { + buf[len++] = '.'; + buf[len++] = '0'; + buf[len] = '\0'; + } + + if (flags & PF_FLAG_ADD_PERCENT) { buf[len++] = '%'; buf[len] = '\0'; } @@ -376,14 +408,6 @@ int mp_print_float(const mp_print_t *print, mp_float_t f, char fmt, int flags, c } #endif -// CIRCUITPY-CHANGE -static int print_str_common(const mp_print_t *print, const char *str, int prec, size_t len, int flags, int fill, int width) { - if (prec >= 0 && (size_t)prec < len) { - len = prec; - } - return mp_print_strn(print, str, len, flags, fill, width); -} - int mp_printf(const mp_print_t *print, const char *fmt, ...) { va_list ap; va_start(ap, fmt); @@ -424,8 +448,6 @@ int mp_vprintf(const mp_print_t *print, const char *fmt, va_list args) { 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'; @@ -459,16 +481,36 @@ int mp_vprintf(const mp_print_t *print, const char *fmt, va_list args) { } } - // parse long specifiers (only for LP64 model where they make a difference) - #ifndef __LP64__ - const + // parse long and long long specifiers (only where they make a difference) + #if (MP_INT_MAX > INT_MAX && MP_INT_MAX == LONG_MAX) || defined(MICROPY_UNIX_COVERAGE) + #define SUPPORT_L_FORMAT (1) + #else + #define SUPPORT_L_FORMAT (0) #endif + #if SUPPORT_L_FORMAT bool long_arg = false; + #endif + + #if (MP_INT_MAX > LONG_MAX) || defined(MICROPY_UNIX_COVERAGE) + #define SUPPORT_LL_FORMAT (1) + #else + #define SUPPORT_LL_FORMAT (0) + #endif + #if SUPPORT_LL_FORMAT + bool long_long_arg = false; + #endif + if (*fmt == 'l') { ++fmt; - #ifdef __LP64__ + #if SUPPORT_L_FORMAT long_arg = true; #endif + #if SUPPORT_LL_FORMAT + if (*fmt == 'l') { + ++fmt; + long_long_arg = true; + } + #endif } if (*fmt == '\0') { @@ -492,27 +534,19 @@ int mp_vprintf(const mp_print_t *print, const char *fmt, va_list args) { qstr qst = va_arg(args, qstr); size_t len; const char *str = (const char *)qstr_data(qst, &len); - // CIRCUITPY-CHANGE - chrs += print_str_common(print, str, prec, len, flags, fill, width); - break; - } - // CIRCUITPY-CHANGE: new code to print compressed strings - case 'S': { - mp_rom_error_text_t arg = va_arg(args, mp_rom_error_text_t); - size_t len_with_nul = decompress_length(arg); - size_t len = len_with_nul - 1; - char str[len_with_nul]; - decompress(arg, str); - chrs += print_str_common(print, str, prec, len, flags, fill, width); + if (prec >= 0 && (size_t)prec < len) { + len = prec; + } + chrs += mp_print_strn(print, str, len, flags, fill, width); break; } case 's': { const char *str = va_arg(args, const char *); #ifndef NDEBUG // With debugging enabled, catch printing of null string pointers - if (str == NULL) { - // CIRCUITPY-CHANGE - str = "(null)"; + if (prec != 0 && str == NULL) { + chrs += mp_print_strn(print, "(null)", 6, flags, fill, width); + break; } #endif size_t len = strlen(str); @@ -522,42 +556,60 @@ int mp_vprintf(const mp_print_t *print, const char *fmt, va_list args) { chrs += mp_print_strn(print, str, len, flags, fill, width); break; } - case 'd': { - mp_int_t val; - if (long_arg) { - val = va_arg(args, long int); - } else { - val = va_arg(args, int); - } - chrs += mp_print_int(print, val, 1, 10, 'a', flags, fill, width); - break; - } + case 'd': + case 'p': + case 'P': case 'u': case 'x': case 'X': { - int base = 16 - ((*fmt + 1) & 6); // maps char u/x/X to base 10/16/16 - char fmt_c = (*fmt & 0xf0) - 'P' + 'A'; // maps char u/x/X to char a/a/A + char fmt_chr = *fmt; mp_uint_t val; - if (long_arg) { - val = va_arg(args, unsigned long int); + if (fmt_chr == 'p' || fmt_chr == 'P') { + val = va_arg(args, uintptr_t); + } + #if SUPPORT_LL_FORMAT + else if (long_long_arg) { + val = va_arg(args, unsigned long long); + } + #endif + #if SUPPORT_L_FORMAT + else if (long_arg) { + if (sizeof(long) != sizeof(mp_uint_t) && fmt_chr == 'd') { + val = va_arg(args, long); + } else { + val = va_arg(args, unsigned long); + } + } + #endif + else { + if (sizeof(int) != sizeof(mp_uint_t) && fmt_chr == 'd') { + val = va_arg(args, int); + } else { + val = va_arg(args, unsigned); + } + } + int base; + // Map format char x/p/X/P to a/a/A/A for hex letters. + // It doesn't matter what d/u map to. + char fmt_c = (fmt_chr & 0xf0) - 'P' + 'A'; + if (fmt_chr == 'd' || fmt_chr == 'u') { + base = 10; } else { - val = va_arg(args, unsigned int); + base = 16; + } + // CIRCUITPY-CHANGE: include "0x" for 'p' and 'P'. + if (fmt_chr == 'p' || fmt_chr == 'P') { + #if SUPPORT_INT_BASE_PREFIX + chrs += mp_print_int(print, va_arg(args, unsigned long int), 0, 16, 'a', flags | PF_FLAG_SHOW_PREFIX, fill, width); + #else + chrs += mp_print_strn(print, "0x", 2, flags, fill, width); + #endif } - chrs += mp_print_int(print, val, 0, base, fmt_c, flags, fill, width); + chrs += mp_print_int(print, val, fmt_chr == 'd', base, fmt_c, flags, fill, width); break; } - case 'p': - case 'P': // don't bother to handle upcase for 'P' - // Use unsigned long int to work on both ILP32 and LP64 systems - // CIRCUITPY-CHANGE: print 0x prefix - #if SUPPORT_INT_BASE_PREFIX - chrs += mp_print_int(print, va_arg(args, unsigned long int), 0, 16, 'a', flags | PF_FLAG_SHOW_PREFIX, fill, width); - #else - print->print_strn(print->data, "0x", 2); - chrs += mp_print_int(print, va_arg(args, unsigned long int), 0, 16, 'a', flags, fill, width) + 2; - #endif - break; - #if MICROPY_PY_BUILTINS_FLOAT + // CIRCUITPY-CHANGE: optional + #if MICROPY_PRINTF_FLOAT case 'e': case 'E': case 'f': @@ -572,19 +624,34 @@ int mp_vprintf(const mp_print_t *print, const char *fmt, va_list args) { #endif break; } + // CIRCUITPY-CHANGE: skip the argument so later ones still line up + #elif MICROPY_PY_BUILTINS_FLOAT + case 'e': + case 'E': + case 'f': + case 'F': + case 'g': + case 'G': + (void)va_arg(args, double); + print->print_strn(print->data, "?", 1); + chrs += 1; + 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. - #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); - ++fmt; - assert(*fmt == 'u' || *fmt == 'd' || !"unsupported fmt char"); - chrs += mp_print_int(print, arg_value, *fmt == 'd', 10, 'a', flags, fill, width); + + // CIRCUITPY-CHANGE: new format code to print compressed strings + case 'S': { + mp_rom_error_text_t arg = va_arg(args, mp_rom_error_text_t); + size_t len_with_nul = decompress_length(arg); + size_t len = len_with_nul - 1; + char str[len_with_nul]; + decompress(arg, str); + if (prec >= 0 && (size_t)prec < len) { + len = prec; + } + chrs += mp_print_strn(print, str, len, flags, fill, width); break; } - #endif + default: // if it's not %% then it's an unsupported format character assert(*fmt == '%' || !"unsupported fmt char"); diff --git a/py/mpprint.h b/py/mpprint.h index e883cc27047..614c61ea415 100644 --- a/py/mpprint.h +++ b/py/mpprint.h @@ -31,13 +31,13 @@ #define PF_FLAG_LEFT_ADJUST (0x001) #define PF_FLAG_SHOW_SIGN (0x002) #define PF_FLAG_SPACE_SIGN (0x004) -#define PF_FLAG_NO_TRAILZ (0x008) -#define PF_FLAG_SHOW_PREFIX (0x010) -#define PF_FLAG_SHOW_COMMA (0x020) -#define PF_FLAG_PAD_AFTER_SIGN (0x040) -#define PF_FLAG_CENTER_ADJUST (0x080) -#define PF_FLAG_ADD_PERCENT (0x100) -#define PF_FLAG_SHOW_OCTAL_LETTER (0x200) +#define PF_FLAG_SHOW_PREFIX (0x008) +#define PF_FLAG_PAD_AFTER_SIGN (0x010) +#define PF_FLAG_CENTER_ADJUST (0x020) +#define PF_FLAG_ADD_PERCENT (0x040) +#define PF_FLAG_SHOW_OCTAL_LETTER (0x080) +#define PF_FLAG_ALWAYS_DECIMAL (0x100) +#define PF_FLAG_SEP_POS (9) // must be above all the above PF_FLAGs #if MICROPY_PY_IO && MICROPY_PY_SYS_STDFILES #define MP_PYTHON_PRINTER &mp_sys_stdout_print @@ -69,9 +69,9 @@ extern const mp_print_t mp_sys_stdout_print; #endif int mp_print_str(const mp_print_t *print, const char *str); -int mp_print_strn(const mp_print_t *print, const char *str, size_t len, int flags, char fill, int width); +int mp_print_strn(const mp_print_t *print, const char *str, size_t len, unsigned int flags, char fill, int width); #if MICROPY_PY_BUILTINS_FLOAT -int mp_print_float(const mp_print_t *print, mp_float_t f, char fmt, int flags, char fill, int width, int prec); +int mp_print_float(const mp_print_t *print, mp_float_t f, char fmt, unsigned int flags, char fill, int width, int prec); #endif int mp_printf(const mp_print_t *print, const char *fmt, ...); diff --git a/py/mpstate.h b/py/mpstate.h index 7308e57b581..25685334a4c 100644 --- a/py/mpstate.h +++ b/py/mpstate.h @@ -71,9 +71,18 @@ enum { // This structure contains dynamic configuration for the compiler. #if MICROPY_DYNAMIC_COMPILER typedef struct mp_dynamic_compiler_t { + // This is used to let mpy-cross pass options to the emitter chosen with + // `native_arch`. The main use case for the time being is to give the + // RV32 emitter extended information about which extensions can be + // optionally used, in order to generate code that's better suited for the + // hardware platform the code will run on. + void *backend_options; uint8_t small_int_bits; // must be <= host small_int_bits uint8_t native_arch; uint8_t nlr_buf_num_regs; + #if MICROPY_ENABLE_SOURCE_LINE + bool include_source_lines; + #endif } mp_dynamic_compiler_t; extern mp_dynamic_compiler_t mp_dynamic_compiler; #endif @@ -88,6 +97,18 @@ typedef struct _mp_sched_item_t { mp_obj_t arg; } mp_sched_item_t; +// gc_lock_depth field is a combination of the GC_COLLECT_FLAG +// bit and a lock depth shifted GC_LOCK_DEPTH_SHIFT bits left. +#if MICROPY_ENABLE_FINALISER +#define GC_COLLECT_FLAG 1 +#define GC_LOCK_DEPTH_SHIFT 1 +#else +// If finalisers are disabled then this check doesn't matter, as gc_lock() +// is called anywhere else that heap can't be changed. So save some code size. +#define GC_COLLECT_FLAG 0 +#define GC_LOCK_DEPTH_SHIFT 0 +#endif + // This structure holds information about a single contiguous area of // memory reserved for the memory manager. typedef struct _mp_state_mem_area_t { @@ -100,6 +121,13 @@ typedef struct _mp_state_mem_area_t { #if MICROPY_ENABLE_FINALISER byte *gc_finaliser_table_start; #endif + // CIRCUITPY-CHANGE + #if MICROPY_ENABLE_SELECTIVE_COLLECT + byte *gc_collect_table_start; + #endif + #if MICROPY_PY_WEAKREF + byte *gc_weakref_table_start; + #endif byte *gc_pool_start; byte *gc_pool_end; @@ -116,6 +144,10 @@ typedef struct _mp_state_mem_t { #endif mp_state_mem_area_t area; + #if MICROPY_GC_SPLIT_HEAP + byte *area_pool_min; // Min of all gc_pool_start values across all areas + byte *area_pool_max; // Max of all gc_pool_end values across all areas + #endif int gc_stack_overflow; MICROPY_GC_STACK_ENTRY_TYPE gc_block_stack[MICROPY_ALLOC_GC_STACK_SIZE]; @@ -144,7 +176,7 @@ typedef struct _mp_state_mem_t { #if MICROPY_PY_THREAD && !MICROPY_PY_THREAD_GIL // This is a global mutex used to make the GC thread-safe. - mp_thread_mutex_t gc_mutex; + mp_thread_recursive_mutex_t gc_mutex; #endif } mp_state_mem_t; @@ -229,6 +261,9 @@ typedef struct _mp_state_vm_t { #if MICROPY_EMIT_NATIVE uint8_t default_emit_opt; // one of MP_EMIT_OPT_xxx #endif + #if MICROPY_DEBUG_PRINTERS + mp_uint_t mp_verbose_flag; + #endif #endif // size of the emergency exception buf, if it's dynamically allocated @@ -292,6 +327,7 @@ typedef struct _mp_state_thread_t { #endif // Locking of the GC is done per thread. + // See GC_LOCK_DEPTH_SHIFT for an explanation of this field. uint16_t gc_lock_depth; //////////////////////////////////////////////////////////// @@ -318,6 +354,10 @@ typedef struct _mp_state_thread_t { struct _mp_code_state_t *current_code_state; #endif + #if MICROPY_PY_SSL_MBEDTLS_NEED_ACTIVE_CONTEXT + struct _mp_obj_ssl_context_t *tls_ssl_context; + #endif + // CIRCUITPY-CHANGE #if CIRCUITPY_WARNINGS warnings_action_t warnings_action; @@ -348,4 +388,7 @@ extern mp_state_thread_t *mp_thread_get_state(void); #define mp_thread_is_main_thread() (true) #endif +// CIRCUITPY-CHANGE: defined in main.c +bool vm_is_running(void); + #endif // MICROPY_INCLUDED_PY_MPSTATE_H diff --git a/py/mpthread.h b/py/mpthread.h index f335cc02911..795f230bb4a 100644 --- a/py/mpthread.h +++ b/py/mpthread.h @@ -48,6 +48,12 @@ void mp_thread_mutex_init(mp_thread_mutex_t *mutex); int mp_thread_mutex_lock(mp_thread_mutex_t *mutex, int wait); void mp_thread_mutex_unlock(mp_thread_mutex_t *mutex); +#if MICROPY_PY_THREAD_RECURSIVE_MUTEX +void mp_thread_recursive_mutex_init(mp_thread_recursive_mutex_t *mutex); +int mp_thread_recursive_mutex_lock(mp_thread_recursive_mutex_t *mutex, int wait); +void mp_thread_recursive_mutex_unlock(mp_thread_recursive_mutex_t *mutex); +#endif + #endif // MICROPY_PY_THREAD #if MICROPY_PY_THREAD && MICROPY_PY_THREAD_GIL diff --git a/py/mpz.c b/py/mpz.c index 746c9fe5b69..0da71160feb 100644 --- a/py/mpz.c +++ b/py/mpz.c @@ -688,7 +688,13 @@ static void mpz_need_dig(mpz_t *z, size_t need) { // if z has fixed digit buffer there's not much we can do as the caller will // be expecting a buffer with at least "need" bytes (but it shouldn't happen) assert(!z->fixed_dig); - z->dig = m_renew(mpz_dig_t, z->dig, z->alloc, need); + // CIRCUITPY-CHANGE: Don't scan digits for pointers. m_renew(NULL) would allocate a + // scanned block; once allocated, m_renew keeps the block unscanned. + if (z->dig == NULL) { + z->dig = m_malloc_without_collect(sizeof(mpz_dig_t) * need); + } else { + z->dig = m_renew(mpz_dig_t, z->dig, z->alloc, need); + } z->alloc = need; } } @@ -700,7 +706,8 @@ static mpz_t *mpz_clone(const mpz_t *src) { z->fixed_dig = 0; z->alloc = src->alloc; z->len = src->len; - z->dig = m_new(mpz_dig_t, z->alloc); + // CIRCUITPY-CHANGE: Don't scan digits for pointers. + z->dig = m_malloc_without_collect(sizeof(mpz_dig_t) * z->alloc); memcpy(z->dig, src->dig, src->alloc * sizeof(mpz_dig_t)); return z; } @@ -1360,7 +1367,7 @@ void mpz_pow_inpl(mpz_t *dest, const mpz_t *lhs, const mpz_t *rhs) { can have dest, lhs, rhs the same; mod can't be the same as dest */ void mpz_pow3_inpl(mpz_t *dest, const mpz_t *lhs, const mpz_t *rhs, const mpz_t *mod) { - if (lhs->len == 0 || rhs->neg != 0 || (mod->len == 1 && mod->dig[0] == 1)) { + if (rhs->neg != 0 || (mod->len == 1 && mod->dig[0] == 1)) { mpz_set_from_int(dest, 0); return; } @@ -1368,6 +1375,15 @@ void mpz_pow3_inpl(mpz_t *dest, const mpz_t *lhs, const mpz_t *rhs, const mpz_t mpz_set_from_int(dest, 1); if (rhs->len == 0) { + // Python style modulo: 1 % mod is 1 + mod, as abs(mod) >= 2 here + if (mod->neg) { + mpz_add_inpl(dest, dest, mod); + } + return; + } + + if (lhs->len == 0) { + mpz_set_from_int(dest, 0); return; } @@ -1541,7 +1557,8 @@ mp_int_t mpz_hash(const mpz_t *z) { mp_uint_t val = 0; mpz_dig_t *d = z->dig + z->len; - while (d-- > z->dig) { + while (d > z->dig) { + d--; val = (val << DIG_SIZE) | *d; } @@ -1556,11 +1573,12 @@ bool mpz_as_int_checked(const mpz_t *i, mp_int_t *value) { mp_uint_t val = 0; mpz_dig_t *d = i->dig + i->len; - while (d-- > i->dig) { + while (d > i->dig) { if (val > (~(MP_OBJ_WORD_MSBIT_HIGH) >> DIG_SIZE)) { // will overflow return false; } + d--; val = (val << DIG_SIZE) | *d; } @@ -1581,11 +1599,12 @@ bool mpz_as_uint_checked(const mpz_t *i, mp_uint_t *value) { mp_uint_t val = 0; mpz_dig_t *d = i->dig + i->len; - while (d-- > i->dig) { + while (d > i->dig) { if (val > (~(MP_OBJ_WORD_MSBIT_HIGH) >> (DIG_SIZE - 1))) { // will overflow return false; } + d--; val = (val << DIG_SIZE) | *d; } @@ -1593,46 +1612,56 @@ bool mpz_as_uint_checked(const mpz_t *i, mp_uint_t *value) { return true; } -void mpz_as_bytes(const mpz_t *z, bool big_endian, size_t len, byte *buf) { +bool mpz_as_bytes(const mpz_t *z, bool big_endian, bool as_signed, size_t len, byte *buf) { byte *b = buf; if (big_endian) { b += len; } mpz_dig_t *zdig = z->dig; + byte fill_byte = z->neg ? 0xFF : 0x00; int bits = 0; mpz_dbl_dig_t d = 0; mpz_dbl_dig_t carry = 1; + mpz_dig_t val = 0; + size_t olen = len; // bytes in output buffer for (size_t zlen = z->len; zlen > 0; --zlen) { bits += DIG_SIZE; d = (d << DIG_SIZE) | *zdig++; for (; bits >= 8; bits -= 8, d >>= 8) { - mpz_dig_t val = d; + val = d; if (z->neg) { val = (~val & 0xff) + carry; carry = val >> 8; } + + if (!olen) { + // Buffer is full, only OK if all remaining bytes are zeroes + if ((byte)val != fill_byte) { + return false; + } + continue; + } + if (big_endian) { *--b = val; - if (b == buf) { - return; - } } else { *b++ = val; - if (b == buf + len) { - return; - } } + olen--; } } - // fill remainder of buf with zero/sign extension of the integer - if (big_endian) { - len = b - buf; - } else { - len = buf + len - b; - buf = b; + // Check if the most significant bit is set incorrectly for a signed value + if (olen == 0 && as_signed && ((val & 0x80) != (fill_byte & 0x80))) { + return false; } - memset(buf, z->neg ? 0xff : 0x00, len); + + if (olen > 0) { + // fill remainder of buf with zero/sign extension of the integer + memset(big_endian ? buf : b, fill_byte, olen); + } + + return true; } #if MICROPY_PY_BUILTINS_FLOAT @@ -1640,7 +1669,8 @@ mp_float_t mpz_as_float(const mpz_t *i) { mp_float_t val = 0; mpz_dig_t *d = i->dig + i->len; - while (d-- > i->dig) { + while (d > i->dig) { + d--; val = val * DIG_BASE + *d; } @@ -1670,6 +1700,8 @@ size_t mpz_as_str_inpl(const mpz_t *i, unsigned int base, const char *prefix, ch size_t ilen = i->len; + int n_comma = (base == 10) ? 3 : 4; + char *s = str; if (ilen == 0) { if (prefix) { @@ -1715,7 +1747,7 @@ size_t mpz_as_str_inpl(const mpz_t *i, unsigned int base, const char *prefix, ch break; } } - if (comma && (s - last_comma) == 3) { + if (!done && comma && (s - last_comma) == n_comma) { *s++ = comma; last_comma = s; } diff --git a/py/mpz.h b/py/mpz.h index f205e3cd158..0422b014a33 100644 --- a/py/mpz.h +++ b/py/mpz.h @@ -93,9 +93,9 @@ typedef int8_t mpz_dbl_dig_signed_t; typedef struct _mpz_t { // Zero has neg=0, len=0. Negative zero is not allowed. size_t neg : 1; - size_t fixed_dig : 1; - size_t alloc : (8 * sizeof(size_t) - 2); - size_t len; + size_t fixed_dig : 1; // flag, 'dig' buffer cannot be reallocated + size_t alloc : (8 * sizeof(size_t) - 2); // number of entries allocated in 'dig' + size_t len; // number of entries used in 'dig' mpz_dig_t *dig; } mpz_t; @@ -153,7 +153,8 @@ static inline size_t mpz_num_bits(const mpz_t *z) { 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); -void mpz_as_bytes(const mpz_t *z, bool big_endian, size_t len, byte *buf); +// Returns true if 'z' fit into 'len' bytes of 'buf' without overflowing, 'buf' is truncated otherwise. +bool mpz_as_bytes(const mpz_t *z, bool big_endian, bool as_signed, size_t len, byte *buf); #if MICROPY_PY_BUILTINS_FLOAT mp_float_t mpz_as_float(const mpz_t *z); #endif diff --git a/py/nativeglue.c b/py/nativeglue.c index 3b072ba8c38..c632cd36534 100644 --- a/py/nativeglue.c +++ b/py/nativeglue.c @@ -43,7 +43,7 @@ #define DEBUG_printf(...) (void)0 #endif -#if MICROPY_EMIT_NATIVE +#if MICROPY_ENABLE_NATIVE_CODE int mp_native_type_from_qstr(qstr qst) { switch (qst) { @@ -93,7 +93,7 @@ mp_uint_t mp_native_from_obj(mp_obj_t obj, mp_uint_t type) { #endif -#if MICROPY_EMIT_MACHINE_CODE +#if MICROPY_EMIT_INLINE_ASM || MICROPY_ENABLE_NATIVE_CODE // convert a native value to a MicroPython object based on type mp_obj_t mp_native_to_obj(mp_uint_t val, mp_uint_t type) { @@ -117,7 +117,7 @@ mp_obj_t mp_native_to_obj(mp_uint_t val, mp_uint_t type) { #endif -#if MICROPY_EMIT_NATIVE && !MICROPY_DYNAMIC_COMPILER +#if MICROPY_ENABLE_NATIVE_CODE && !MICROPY_DYNAMIC_COMPILER #if !MICROPY_PY_BUILTINS_SET mp_obj_t mp_obj_new_set(size_t n_args, mp_obj_t *items) { @@ -323,7 +323,11 @@ const mp_fun_table_t mp_fun_table = { mp_printf, mp_vprintf, // CIRCUITPY-CHANGE: mp_raise_msg_str instead of mp_raise_msg + #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_NONE + NULL, + #else mp_raise_msg_str, + #endif mp_obj_get_type, mp_obj_new_str, mp_obj_new_bytes, @@ -359,8 +363,8 @@ const mp_fun_table_t mp_fun_table = { &mp_stream_write_obj, }; -#elif MICROPY_EMIT_NATIVE && MICROPY_DYNAMIC_COMPILER +#elif MICROPY_ENABLE_NATIVE_CODE && MICROPY_DYNAMIC_COMPILER const int mp_fun_table; -#endif // MICROPY_EMIT_NATIVE +#endif // MICROPY_ENABLE_NATIVE_CODE diff --git a/py/nativeglue.h b/py/nativeglue.h index 00ed9f3f4fc..f6ba600c99f 100644 --- a/py/nativeglue.h +++ b/py/nativeglue.h @@ -143,7 +143,7 @@ typedef struct _mp_fun_table_t { int (*printf_)(const mp_print_t *print, const char *fmt, ...); int (*vprintf_)(const mp_print_t *print, const char *fmt, va_list args); #if defined(__GNUC__) - NORETURN // Only certain compilers support no-return attributes in function pointer declarations + MP_NORETURN // Only certain compilers support no-return attributes in function pointer declarations #endif // CIRCUITPY-CHANGE: raise_msg_str instead of raise_msg void (*raise_msg_str)(const mp_obj_type_t *exc_type, const char *msg); @@ -184,9 +184,9 @@ typedef struct _mp_fun_table_t { const mp_obj_fun_builtin_var_t *stream_write_obj; } mp_fun_table_t; -#if (MICROPY_EMIT_NATIVE && !MICROPY_DYNAMIC_COMPILER) || MICROPY_ENABLE_DYNRUNTIME +#if (MICROPY_ENABLE_NATIVE_CODE && !MICROPY_DYNAMIC_COMPILER) || MICROPY_ENABLE_DYNRUNTIME extern const mp_fun_table_t mp_fun_table; -#elif MICROPY_EMIT_NATIVE && MICROPY_DYNAMIC_COMPILER +#elif MICROPY_ENABLE_NATIVE_CODE && MICROPY_DYNAMIC_COMPILER // In dynamic-compiler mode eliminate dependency on entries in mp_fun_table. // This only needs to be an independent pointer, content doesn't matter. extern const int mp_fun_table; diff --git a/py/nlr.c b/py/nlr.c index 516b8b86276..de2a38ceff3 100644 --- a/py/nlr.c +++ b/py/nlr.c @@ -28,8 +28,7 @@ #if !MICROPY_NLR_SETJMP // When not using setjmp, nlr_push_tail is called from inline asm so needs special care -// CIRCUITPY-CHANGE: avoid warning -#if defined(MICROPY_NLR_X86) && MICROPY_NLR_X86 && defined(MICROPY_NLR_OS_WINDOWS) && MICROPY_NLR_OS_WINDOWS +#if MICROPY_NLR_X86 && 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"); #else @@ -82,7 +81,7 @@ void nlr_call_jump_callbacks(nlr_buf_t *nlr) { } #if MICROPY_ENABLE_VM_ABORT -NORETURN void nlr_jump_abort(void) { +MP_NORETURN void nlr_jump_abort(void) { MP_STATE_THREAD(nlr_top) = MP_STATE_VM(nlr_abort); nlr_jump(NULL); } diff --git a/py/nlr.h b/py/nlr.h index 15f883422f5..72ea1368e93 100644 --- a/py/nlr.h +++ b/py/nlr.h @@ -44,6 +44,9 @@ #define MICROPY_NLR_NUM_REGS_MIPS (13) #define MICROPY_NLR_NUM_REGS_XTENSA (10) #define MICROPY_NLR_NUM_REGS_XTENSAWIN (17) +#define MICROPY_NLR_NUM_REGS_RV32I (14) +#define MICROPY_NLR_NUM_REGS_RV64I (14) +#define MICROPY_NLR_NUM_REGS_LOONG64 (13) // *FORMAT-OFF* @@ -99,16 +102,76 @@ #elif defined(__mips__) #define MICROPY_NLR_MIPS (1) #define MICROPY_NLR_NUM_REGS (MICROPY_NLR_NUM_REGS_MIPS) +#elif defined(__riscv) + #if __riscv_xlen == 32 + #define MICROPY_NLR_NUM_REGS (MICROPY_NLR_NUM_REGS_RV32I) + #define MICROPY_NLR_RV32I (1) + #elif __riscv_xlen == 64 + #define MICROPY_NLR_NUM_REGS (MICROPY_NLR_NUM_REGS_RV64I) + #define MICROPY_NLR_RV64I (1) + #else + #error Unsupported RISC-V variant. + #endif +#elif defined(__loongarch__) + #if defined(__loongarch64) + #define MICROPY_NLR_LOONG64 (1) + #define MICROPY_NLR_NUM_REGS (MICROPY_NLR_NUM_REGS_LOONG64) + #else + #error Unsupported Loongarch variant. + #endif #else #define MICROPY_NLR_SETJMP (1) //#warning "No native NLR support for this arch, using setjmp implementation" #endif #endif -// CIRCUITPY-CHANGE -// If MICROPY_NLR_SETJMP is not defined above - define/disable it here -#if !defined(MICROPY_NLR_SETJMP) - #define MICROPY_NLR_SETJMP (0) +// CIRCUITPY-CHANGE: Avoid warnings by defining all these MICROPY_PY_NLR_* macros +#ifndef MICROPY_NLR_AARCH64 +#define MICROPY_NLR_AARCH64 (0) +#endif + +#ifndef MICROPY_NLR_LOONG64 +#define MICROPY_NLR_LOONG64 (0) +#endif + +#ifndef MICROPY_NLR_MIPS +#define MICROPY_NLR_MIPS (0) +#endif + +#ifndef MICROPY_NLR_OS_WINDOWS +#define MICROPY_NLR_OS_WINDOWS (0) +#endif + +#ifndef MICROPY_NLR_POWERPC +#define MICROPY_NLR_POWERPC (0) +#endif + +#ifndef MICROPY_NLR_RV32I +#define MICROPY_NLR_RV32I (0) +#endif + +#ifndef MICROPY_NLR_RV64I +#define MICROPY_NLR_RV64I (0) +#endif + +#ifndef MICROPY_NLR_SETJMP +#define MICROPY_NLR_SETJMP (0) +#endif + +#ifndef MICROPY_NLR_THUMB +#define MICROPY_NLR_THUMB (0) +#endif + +#ifndef MICROPY_NLR_X64 +#define MICROPY_NLR_X64 (0) +#endif + +#ifndef MICROPY_NLR_X86 +#define MICROPY_NLR_X86 (0) +#endif + +#ifndef MICROPY_NLR_XTENSA +#define MICROPY_NLR_XTENSA (0) #endif // *FORMAT-ON* @@ -182,18 +245,18 @@ unsigned int nlr_push(nlr_buf_t *); unsigned int nlr_push_tail(nlr_buf_t *top); void nlr_pop(void); -NORETURN void nlr_jump(void *val); +MP_NORETURN void nlr_jump(void *val); #if MICROPY_ENABLE_VM_ABORT #define nlr_set_abort(buf) MP_STATE_VM(nlr_abort) = buf #define nlr_get_abort() MP_STATE_VM(nlr_abort) -NORETURN void nlr_jump_abort(void); +MP_NORETURN void nlr_jump_abort(void); #endif // This must be implemented by a port. It's called by nlr_jump // if no nlr buf has been pushed. It must not return, but rather // should bail out with a fatal error. -NORETURN void nlr_jump_fail(void *val); +MP_NORETURN void nlr_jump_fail(void *val); // use nlr_raise instead of nlr_jump so that debugging is easier #ifndef MICROPY_DEBUG_NLR diff --git a/py/nlraarch64.c b/py/nlraarch64.c index 898d9e2a765..3318004b5e0 100644 --- a/py/nlraarch64.c +++ b/py/nlraarch64.c @@ -26,8 +26,7 @@ #include "py/mpstate.h" // needed for NLR defs -// CIRCUITPY-CHANGE: avoid warnings -#if defined(MICROPY_NLR_AARCH64) && MICROPY_NLR_AARCH64 +#if MICROPY_NLR_AARCH64 // AArch64 callee-saved registers are x19-x29. // https://en.wikipedia.org/wiki/Calling_convention#ARM_(A64) @@ -57,7 +56,7 @@ __asm( #endif ); -NORETURN void nlr_jump(void *val) { +MP_NORETURN void nlr_jump(void *val) { MP_NLR_JUMP_HEAD(val, top) MP_STATIC_ASSERT(offsetof(nlr_buf_t, regs) == 16); // asm assumes it diff --git a/py/nlrloong64.c b/py/nlrloong64.c new file mode 100644 index 00000000000..7a12b2ec904 --- /dev/null +++ b/py/nlrloong64.c @@ -0,0 +1,80 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2026 Alessandro Gatti + * + * 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/mpstate.h" + +#if MICROPY_NLR_LOONG64 + +__attribute__((used)) unsigned int nlr_push_tail(nlr_buf_t *nlr); + +__asm( + ".globl nlr_push \n" + "nlr_push: \n" + ".cfi_startproc \n" + "st.d $r1, $r4, 16 \n" /* Store RA. */ + "st.d $r23, $r4, 24 \n" /* Store S0. */ + "st.d $r24, $r4, 32 \n" /* Store S1. */ + "st.d $r25, $r4, 40 \n" /* Store S2. */ + "st.d $r26, $r4, 48 \n" /* Store S3. */ + "st.d $r27, $r4, 56 \n" /* Store S4. */ + "st.d $r28, $r4, 64 \n" /* Store S5. */ + "st.d $r29, $r4, 72 \n" /* Store S6. */ + "st.d $r30, $r4, 80 \n" /* Store S7. */ + "st.d $r31, $r4, 88 \n" /* Store S8. */ + "st.d $r22, $r4, 96 \n" /* Store S9. */ + "st.d $r21, $r4, 104 \n" /* Marked as reserved in the ABI. */ + "st.d $r3, $r4, 112 \n" /* Store SP. */ + "b nlr_push_tail \n" /* Jump to the C part. */ + ".cfi_endproc \n" + ); + +MP_NORETURN void nlr_jump(void *val) { + MP_NLR_JUMP_HEAD(val, top) + __asm volatile ( + "add.d $r4, $r0, %0 \n" + "ld.d $r1, $r4, 16 \n" /* Retrieve RA. */ + "ld.d $r23, $r4, 24 \n" /* Retrieve S0. */ + "ld.d $r24, $r4, 32 \n" /* Retrieve S1. */ + "ld.d $r25, $r4, 40 \n" /* Retrieve S2. */ + "ld.d $r26, $r4, 48 \n" /* Retrieve S3. */ + "ld.d $r27, $r4, 56 \n" /* Retrieve S4. */ + "ld.d $r28, $r4, 64 \n" /* Retrieve S5. */ + "ld.d $r29, $r4, 72 \n" /* Retrieve S6. */ + "ld.d $r30, $r4, 80 \n" /* Retrieve S7. */ + "ld.d $r31, $r4, 88 \n" /* Retrieve S8. */ + "ld.d $r22, $r4, 96 \n" /* Retrieve S9. */ + "ld.d $r21, $r4, 104 \n" + "ld.d $r3, $r4, 112 \n" /* Retrieve SP. */ + "addi.d $r4, $r0, 1 \n" /* Return 1 for a non-local return. */ + "ret \n" /* Return. */ + : + : "r" (top) + : "memory" + ); + MP_UNREACHABLE +} + +#endif diff --git a/py/nlrmips.c b/py/nlrmips.c index a60c3abd714..5c55db7e268 100644 --- a/py/nlrmips.c +++ b/py/nlrmips.c @@ -26,8 +26,7 @@ #include "py/mpstate.h" -// CIRCUITPY-CHANGE: avoid warning -#if defined(MICROPY_NLR_MIPS) && MICROPY_NLR_MIPS +#if MICROPY_NLR_MIPS __attribute__((used)) unsigned int nlr_push_tail(nlr_buf_t *nlr); @@ -58,7 +57,7 @@ __asm( ".end nlr_push \n" ); -NORETURN void nlr_jump(void *val) { +MP_NORETURN void nlr_jump(void *val) { MP_NLR_JUMP_HEAD(val, top) __asm( "move $4, %0 \n" diff --git a/py/nlrpowerpc.c b/py/nlrpowerpc.c index ae2f92a0780..cb94473968d 100644 --- a/py/nlrpowerpc.c +++ b/py/nlrpowerpc.c @@ -26,8 +26,7 @@ #include "py/mpstate.h" -// CIRCUITPY-CHANGE: avoid warning -#if defined(MICROPY_NLR_POWERPC) && MICROPY_NLR_POWERPC +#if MICROPY_NLR_POWERPC #undef nlr_push @@ -73,43 +72,44 @@ unsigned int nlr_push(nlr_buf_t *nlr) { "bctr ;" : : "r" (&nlr->regs), "r" (nlr) - : + : "r4" ); return 0; } -NORETURN void nlr_jump(void *val) { +MP_NORETURN void nlr_jump(void *val) { MP_NLR_JUMP_HEAD(val, top) __asm__ volatile ( - "ld 3, 0x0(%0) ;" + "mr 4, %0 ;" + "ld 3, 0x0(4) ;" "cmpdi 3, 0x4eed ; " // Check canary "bne . ; " - "ld 0, 0x08(%0) ;" - "ld 1, 0x10(%0) ;" - "ld 2, 0x18(%0) ;" - "ld 14, 0x20(%0) ;" - "ld 15, 0x28(%0) ;" - "ld 16, 0x30(%0) ;" - "ld 17, 0x38(%0) ;" - "ld 18, 0x40(%0) ;" - "ld 19, 0x48(%0) ;" - "ld 20, 0x50(%0) ;" - "ld 21, 0x58(%0) ;" - "ld 22, 0x60(%0) ;" - "ld 23, 0x68(%0) ;" - "ld 24, 0x70(%0) ;" - "ld 25, 0x78(%0) ;" - "ld 26, 0x80(%0) ;" - "ld 27, 0x88(%0) ;" - "ld 28, 0x90(%0) ;" - "ld 29, 0x98(%0) ;" - "ld 30, 0xA0(%0) ;" - "ld 31, 0xA8(%0) ;" - "ld 3, 0xB0(%0) ;" + "ld 0, 0x08(4) ;" + "ld 1, 0x10(4) ;" + "ld 2, 0x18(4) ;" + "ld 14, 0x20(4) ;" + "ld 15, 0x28(4) ;" + "ld 16, 0x30(4) ;" + "ld 17, 0x38(4) ;" + "ld 18, 0x40(4) ;" + "ld 19, 0x48(4) ;" + "ld 20, 0x50(4) ;" + "ld 21, 0x58(4) ;" + "ld 22, 0x60(4) ;" + "ld 23, 0x68(4) ;" + "ld 24, 0x70(4) ;" + "ld 25, 0x78(4) ;" + "ld 26, 0x80(4) ;" + "ld 27, 0x88(4) ;" + "ld 28, 0x90(4) ;" + "ld 29, 0x98(4) ;" + "ld 30, 0xA0(4) ;" + "ld 31, 0xA8(4) ;" + "ld 3, 0xB0(4) ;" "mtcr 3 ;" - "ld 3, 0xB8(%0) ;" + "ld 3, 0xB8(4) ;" "mtlr 3 ; " "li 3, 1;" "blr ;" @@ -162,43 +162,44 @@ unsigned int nlr_push(nlr_buf_t *nlr) { "bctr ;" : : "r" (&nlr->regs), "r" (nlr) - : + : "r4" ); return 0; } -NORETURN void nlr_jump(void *val) { +MP_NORETURN void nlr_jump(void *val) { MP_NLR_JUMP_HEAD(val, top) __asm__ volatile ( - "l 3, 0x0(%0) ;" + "mr 4, %0 ;" + "l 3, 0x0(4) ;" "cmpdi 3, 0x4eed ; " // Check canary "bne . ; " - "l 0, 0x04(%0) ;" - "l 1, 0x08(%0) ;" - "l 2, 0x0c(%0) ;" - "l 14, 0x10(%0) ;" - "l 15, 0x14(%0) ;" - "l 16, 0x18(%0) ;" - "l 17, 0x1c(%0) ;" - "l 18, 0x20(%0) ;" - "l 19, 0x24(%0) ;" - "l 20, 0x28(%0) ;" - "l 21, 0x2c(%0) ;" - "l 22, 0x30(%0) ;" - "l 23, 0x34(%0) ;" - "l 24, 0x38(%0) ;" - "l 25, 0x3c(%0) ;" - "l 26, 0x40(%0) ;" - "l 27, 0x44(%0) ;" - "l 28, 0x48(%0) ;" - "l 29, 0x4c(%0) ;" - "l 30, 0x50(%0) ;" - "l 31, 0x54(%0) ;" - "l 3, 0x58(%0) ;" + "l 0, 0x04(4) ;" + "l 1, 0x08(4) ;" + "l 2, 0x0c(4) ;" + "l 14, 0x10(4) ;" + "l 15, 0x14(4) ;" + "l 16, 0x18(4) ;" + "l 17, 0x1c(4) ;" + "l 18, 0x20(4) ;" + "l 19, 0x24(4) ;" + "l 20, 0x28(4) ;" + "l 21, 0x2c(4) ;" + "l 22, 0x30(4) ;" + "l 23, 0x34(4) ;" + "l 24, 0x38(4) ;" + "l 25, 0x3c(4) ;" + "l 26, 0x40(4) ;" + "l 27, 0x44(4) ;" + "l 28, 0x48(4) ;" + "l 29, 0x4c(4) ;" + "l 30, 0x50(4) ;" + "l 31, 0x54(4) ;" + "l 3, 0x58(4) ;" "mtcr 3 ;" - "l 3, 0x5c(%0) ;" + "l 3, 0x5c(4) ;" "mtlr 3 ; " "li 3, 1;" "blr ;" diff --git a/py/nlrrv32.c b/py/nlrrv32.c new file mode 100644 index 00000000000..565a8629db5 --- /dev/null +++ b/py/nlrrv32.c @@ -0,0 +1,81 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2024 Alessandro Gatti + * + * 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/mpstate.h" + +#if MICROPY_NLR_RV32I + +#undef nlr_push + +__attribute__((naked)) unsigned int nlr_push(nlr_buf_t *nlr) { + __asm volatile ( + "sw x1, 8(x10) \n" // Store RA. + "sw x8, 12(x10) \n" // Store S0. + "sw x9, 16(x10) \n" // Store S1. + "sw x18, 20(x10) \n" // Store S2. + "sw x19, 24(x10) \n" // Store S3. + "sw x20, 28(x10) \n" // Store S4. + "sw x21, 32(x10) \n" // Store S5. + "sw x22, 36(x10) \n" // Store S6. + "sw x23, 40(x10) \n" // Store S7. + "sw x24, 44(x10) \n" // Store S8. + "sw x25, 48(x10) \n" // Store S9. + "sw x26, 52(x10) \n" // Store S10. + "sw x27, 56(x10) \n" // Store S11. + "sw x2, 60(x10) \n" // Store SP. + "jal x0, nlr_push_tail \n" // Jump to the C part. + ); +} + +MP_NORETURN void nlr_jump(void *val) { + MP_NLR_JUMP_HEAD(val, top) + __asm volatile ( + "add x10, x0, %0 \n" // Load nlr_buf address. + "lw x1, 8(x10) \n" // Retrieve RA. + "lw x8, 12(x10) \n" // Retrieve S0. + "lw x9, 16(x10) \n" // Retrieve S1. + "lw x18, 20(x10) \n" // Retrieve S2. + "lw x19, 24(x10) \n" // Retrieve S3. + "lw x20, 28(x10) \n" // Retrieve S4. + "lw x21, 32(x10) \n" // Retrieve S5. + "lw x22, 36(x10) \n" // Retrieve S6. + "lw x23, 40(x10) \n" // Retrieve S7. + "lw x24, 44(x10) \n" // Retrieve S8. + "lw x25, 48(x10) \n" // Retrieve S9. + "lw x26, 52(x10) \n" // Retrieve S10. + "lw x27, 56(x10) \n" // Retrieve S11. + "lw x2, 60(x10) \n" // Retrieve SP. + "addi x10, x0, 1 \n" // Return 1 for a non-local return. + "jalr x0, x1, 0 \n" // Return. + : // Outputs. + : "r" (top) // Inputs. + : "memory" // Clobbered. + ); + + MP_UNREACHABLE +} + +#endif // MICROPY_NLR_RV32I diff --git a/py/nlrrv64.c b/py/nlrrv64.c new file mode 100644 index 00000000000..b7d1467b8f6 --- /dev/null +++ b/py/nlrrv64.c @@ -0,0 +1,81 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2024 Alessandro Gatti + * + * 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/mpstate.h" + +#if MICROPY_NLR_RV64I + +#undef nlr_push + +__attribute__((naked)) unsigned int nlr_push(nlr_buf_t *nlr) { + __asm volatile ( + "sd x1, 16(x10) \n" // Store RA. + "sd x8, 24(x10) \n" // Store S0. + "sd x9, 32(x10) \n" // Store S1. + "sd x18, 40(x10) \n" // Store S2. + "sd x19, 48(x10) \n" // Store S3. + "sd x20, 56(x10) \n" // Store S4. + "sd x21, 64(x10) \n" // Store S5. + "sd x22, 72(x10) \n" // Store S6. + "sd x23, 80(x10) \n" // Store S7. + "sd x24, 88(x10) \n" // Store S8. + "sd x25, 96(x10) \n" // Store S9. + "sd x26, 104(x10) \n" // Store S10. + "sd x27, 112(x10) \n" // Store S11. + "sd x2, 120(x10) \n" // Store SP. + "jal x0, nlr_push_tail \n" // Jump to the C part. + ); +} + +MP_NORETURN void nlr_jump(void *val) { + MP_NLR_JUMP_HEAD(val, top) + __asm volatile ( + "add x10, x0, %0 \n" // Load nlr_buf address. + "ld x1, 16(x10) \n" // Retrieve RA. + "ld x8, 24(x10) \n" // Retrieve S0. + "ld x9, 32(x10) \n" // Retrieve S1. + "ld x18, 40(x10) \n" // Retrieve S2. + "ld x19, 48(x10) \n" // Retrieve S3. + "ld x20, 56(x10) \n" // Retrieve S4. + "ld x21, 64(x10) \n" // Retrieve S5. + "ld x22, 72(x10) \n" // Retrieve S6. + "ld x23, 80(x10) \n" // Retrieve S7. + "ld x24, 88(x10) \n" // Retrieve S8. + "ld x25, 96(x10) \n" // Retrieve S9. + "ld x26, 104(x10) \n" // Retrieve S10. + "ld x27, 112(x10) \n" // Retrieve S11. + "ld x2, 120(x10) \n" // Retrieve SP. + "addi x10, x0, 1 \n" // Return 1 for a non-local return. + "jalr x0, x1, 0 \n" // Return. + : // Outputs. + : "r" (top) // Inputs. + : "memory" // Clobbered. + ); + + MP_UNREACHABLE +} + +#endif // MICROPY_NLR_RV64I diff --git a/py/nlrthumb.c b/py/nlrthumb.c index de4d69eabd1..1791d8b4929 100644 --- a/py/nlrthumb.c +++ b/py/nlrthumb.c @@ -26,8 +26,7 @@ #include "py/mpstate.h" -// CIRCUITPY-CHANGE: avoid warning -#if defined(MICROPY_NLR_THUMB) && MICROPY_NLR_THUMB +#if MICROPY_NLR_THUMB #undef nlr_push @@ -37,8 +36,7 @@ // For reference, arm/thumb callee save regs are: // r4-r11, r13=sp -// CIRCUITPY-CHANGE: added returns_twice -__attribute__((naked, returns_twice)) unsigned int nlr_push(nlr_buf_t *nlr) { +__attribute__((naked)) unsigned int nlr_push(nlr_buf_t *nlr) { // If you get a linker error here, indicating that a relocation doesn't // fit, try the following (in that order): @@ -93,6 +91,10 @@ __attribute__((naked, returns_twice)) unsigned int nlr_push(nlr_buf_t *nlr) { "b nlr_push_tail \n" // do the rest in C #endif #endif + // CIRCUITPY-CHANGE: add input and clobbers to prevent smashing registers. + : // output operands + : "r" (nlr) // input operands + : "r1", "r2", "r3" // clobbers ); #if !defined(__clang__) && defined(__GNUC__) && (__GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8)) @@ -102,7 +104,7 @@ __attribute__((naked, returns_twice)) unsigned int nlr_push(nlr_buf_t *nlr) { #endif } -NORETURN void nlr_jump(void *val) { +MP_NORETURN void nlr_jump(void *val) { MP_NLR_JUMP_HEAD(val, top) __asm volatile ( @@ -142,7 +144,8 @@ NORETURN void nlr_jump(void *val) { "bx lr \n" // return : // output operands : "r" (top) // input operands - : "memory" // clobbered registers + // CIRCUITPY-CHANGE: better comment + : "memory" // clobbers ); MP_UNREACHABLE diff --git a/py/nlrx64.c b/py/nlrx64.c index 63586a2199f..51224729fc9 100644 --- a/py/nlrx64.c +++ b/py/nlrx64.c @@ -26,8 +26,7 @@ #include "py/mpstate.h" -// CIRCUITPY-CHANGE: avoid warning -#if defined(MICROPY_NLR_X64) && MICROPY_NLR_X64 +#if MICROPY_NLR_X64 #undef nlr_push @@ -101,7 +100,7 @@ unsigned int nlr_push(nlr_buf_t *nlr) { #endif } -NORETURN void nlr_jump(void *val) { +MP_NORETURN void nlr_jump(void *val) { MP_NLR_JUMP_HEAD(val, top) __asm volatile ( diff --git a/py/nlrx86.c b/py/nlrx86.c index a2ce8424f9c..82e139dd8e8 100644 --- a/py/nlrx86.c +++ b/py/nlrx86.c @@ -26,39 +26,49 @@ #include "py/mpstate.h" -// CIRCUITPY-CHANGE: avoid warning -#if defined(MICROPY_NLR_X86) && MICROPY_NLR_X86 +#if MICROPY_NLR_X86 #undef nlr_push // For reference, x86 callee save regs are: // ebx, esi, edi, ebp, esp, eip -// CIRCUITPY-CHANGE: avoid warning -#if defined(MICROPY_NLR_OS_WINDOWS) && MICROPY_NLR_OS_WINDOWS +#if MICROPY_NLR_OS_WINDOWS 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 #if !defined(__clang__) && defined(__GNUC__) && __GNUC__ >= 8 -// Since gcc 8.0 the naked attribute is supported -#define USE_NAKED (1) -#define UNDO_PRELUDE (0) +// Since gcc 8.0 the naked and no-sanitize attributes are supported + #define NLR_PUSH_ATTRIBUTE __attribute__((naked, no_sanitize("unreachable"))) + #define UNDO_PRELUDE (0) + #define ARG_USED(x) (void)x; + #define NLR_UNREACHABLE __builtin_unreachable(); #elif defined(__ZEPHYR__) || defined(__ANDROID__) // Zephyr and Android use a different calling convention by default -#define USE_NAKED (0) -#define UNDO_PRELUDE (0) + #define NLR_PUSH_ATTRIBUTE /* NOTHING */ + #define UNDO_PRELUDE (0) + #define ARG_USED(x) (void)x; + #define NLR_UNREACHABLE return 0; +#elif defined(__clang__) +// clang on Ubuntu 24.04 enables -fsanitize=unreachable by default, but this +// destroys the content of the ebx register. + #define NLR_PUSH_ATTRIBUTE __attribute__((naked, no_sanitize("unreachable"))) + #define UNDO_PRELUDE (0) + #define ARG_USED(x) /* NOTHING */ + #define NLR_UNREACHABLE /* NOTHING */ #else -#define USE_NAKED (0) -#define UNDO_PRELUDE (1) +// gcc before 8 unavoidably emits a 'push %ebp' prologue instruction + #define NLR_PUSH_ATTRIBUTE /* NOTHING */ + #define UNDO_PRELUDE (1) + #define ARG_USED(x) (void)x; + #define NLR_UNREACHABLE return 0; #endif -#if USE_NAKED -__attribute__((naked)) -#endif +NLR_PUSH_ATTRIBUTE unsigned int nlr_push(nlr_buf_t *nlr) { - (void)nlr; + ARG_USED(nlr) __asm volatile ( #if UNDO_PRELUDE @@ -75,12 +85,10 @@ unsigned int nlr_push(nlr_buf_t *nlr) { "jmp nlr_push_tail \n" // do the rest in C ); - #if !USE_NAKED - return 0; // needed to silence compiler warning - #endif + NLR_UNREACHABLE } -NORETURN void nlr_jump(void *val) { +MP_NORETURN void nlr_jump(void *val) { MP_NLR_JUMP_HEAD(val, top) __asm volatile ( diff --git a/py/nlrxtensa.c b/py/nlrxtensa.c index 62e799dbdca..2d1bf35e381 100644 --- a/py/nlrxtensa.c +++ b/py/nlrxtensa.c @@ -26,8 +26,7 @@ #include "py/mpstate.h" -// CIRCUITPY-CHANGE: avoid warning -#if defined(MICROPY_NLR_XTENSA) && MICROPY_NLR_XTENSA +#if MICROPY_NLR_XTENSA #undef nlr_push @@ -56,7 +55,7 @@ unsigned int nlr_push(nlr_buf_t *nlr) { return 0; // needed to silence compiler warning } -NORETURN void nlr_jump(void *val) { +MP_NORETURN void nlr_jump(void *val) { MP_NLR_JUMP_HEAD(val, top) __asm volatile ( diff --git a/py/obj.c b/py/obj.c index a825efc3c5a..b65ac53d23a 100644 --- a/py/obj.c +++ b/py/obj.c @@ -31,6 +31,7 @@ // CIRCUITPY-CHANGE #include "shared/runtime/interrupt_char.h" +#include "py/misc.h" #include "py/obj.h" #include "py/objtype.h" #include "py/objint.h" @@ -38,7 +39,7 @@ // CIRCUITPY-CHANGE #include "py/qstr.h" #include "py/runtime.h" -#include "py/stackctrl.h" +#include "py/cstack.h" #include "py/stream.h" // for mp_obj_print // CIRCUITPY-CHANGE @@ -46,7 +47,8 @@ // Allocates an object and also sets type, for mp_obj_malloc{,_var} macros. MP_NOINLINE void *mp_obj_malloc_helper(size_t num_bytes, const mp_obj_type_t *type) { - mp_obj_base_t *base = (mp_obj_base_t *)m_malloc(num_bytes); + // CIRCUITPY-CHANGE + mp_obj_base_t *base = (mp_obj_base_t *)m_malloc_helper(num_bytes, M_MALLOC_RAISE_ERROR | M_MALLOC_COLLECT); base->type = type; return base; } @@ -54,7 +56,8 @@ MP_NOINLINE void *mp_obj_malloc_helper(size_t num_bytes, const mp_obj_type_t *ty #if MICROPY_ENABLE_FINALISER // Allocates an object and also sets type, for mp_obj_malloc{,_var}_with_finaliser macros. MP_NOINLINE void *mp_obj_malloc_with_finaliser_helper(size_t num_bytes, const mp_obj_type_t *type) { - mp_obj_base_t *base = (mp_obj_base_t *)m_malloc_with_finaliser(num_bytes); + // CIRCUITPY-CHANGE + mp_obj_base_t *base = (mp_obj_base_t *)m_malloc_helper(num_bytes, M_MALLOC_RAISE_ERROR | M_MALLOC_COLLECT | M_MALLOC_WITH_FINALISER); base->type = type; return base; } @@ -125,7 +128,7 @@ const char *mp_obj_get_type_str(mp_const_obj_t o_in) { void mp_obj_print_helper(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind) { // There can be data structures nested too deep, or just recursive - MP_STACK_CHECK(); + mp_cstack_check(); // CIRCUITPY-CHANGE #ifdef RUN_BACKGROUND_TASKS RUN_BACKGROUND_TASKS; @@ -154,7 +157,7 @@ void mp_obj_print_helper(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t if (MP_OBJ_TYPE_HAS_SLOT(type, print)) { MP_OBJ_TYPE_GET_SLOT(type, print)((mp_print_t *)print, o_in, kind); } else { - mp_printf(print, "<%q>", type->name); + mp_printf(print, "<%q>", (qstr)type->name); } } @@ -414,6 +417,36 @@ mp_int_t mp_obj_get_int(mp_const_obj_t arg) { return val; } +#if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE +mp_uint_t mp_obj_get_uint(mp_const_obj_t arg) { + if (!mp_obj_is_exact_type(arg, &mp_type_int)) { + mp_obj_t as_int = mp_unary_op(MP_UNARY_OP_INT_MAYBE, (mp_obj_t)arg); + if (as_int == MP_OBJ_NULL) { + mp_raise_TypeError_int_conversion(arg); + } + arg = as_int; + } + return mp_obj_int_get_uint_checked(arg); +} + +long long mp_obj_get_ll(mp_const_obj_t arg) { + if (!mp_obj_is_exact_type(arg, &mp_type_int)) { + mp_obj_t as_int = mp_unary_op(MP_UNARY_OP_INT_MAYBE, (mp_obj_t)arg); + if (as_int == MP_OBJ_NULL) { + mp_raise_TypeError_int_conversion(arg); + } + arg = as_int; + } + if (mp_obj_is_small_int(arg)) { + return MP_OBJ_SMALL_INT_VALUE(arg); + } else { + long long res; + mp_obj_int_to_bytes((mp_obj_t)arg, sizeof(res), (byte *)&res, MP_ENDIANNESS_BIG, false, false); + return res; + } +} +#endif + mp_int_t mp_obj_get_int_truncated(mp_const_obj_t arg) { if (mp_obj_is_int(arg)) { return mp_obj_int_get_truncated(arg); diff --git a/py/obj.h b/py/obj.h index 255a00b314f..368ac96dbd2 100644 --- a/py/obj.h +++ b/py/obj.h @@ -117,7 +117,7 @@ extern const struct _mp_obj_float_t mp_const_float_inf_obj; extern const struct _mp_obj_float_t mp_const_float_nan_obj; #endif -#define mp_obj_is_float(o) mp_obj_is_type((o), &mp_type_float) +#define mp_obj_is_float(o) mp_obj_is_exact_type((o), &mp_type_float) mp_float_t mp_obj_float_get(mp_obj_t self_in); mp_obj_t mp_obj_new_float(mp_float_t value); #endif @@ -162,7 +162,7 @@ extern const struct _mp_obj_float_t mp_const_float_inf_obj; extern const struct _mp_obj_float_t mp_const_float_nan_obj; #endif -#define mp_obj_is_float(o) mp_obj_is_type((o), &mp_type_float) +#define mp_obj_is_float(o) mp_obj_is_exact_type((o), &mp_type_float) mp_float_t mp_obj_float_get(mp_obj_t self_in); mp_obj_t mp_obj_new_float(mp_float_t value); #endif @@ -184,12 +184,15 @@ static inline bool mp_obj_is_small_int(mp_const_obj_t o) { #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)) +#include +// note: MP_OBJ_NEW_CONST_FLOAT should be a MP_ROM_PTR but that macro isn't available yet +#define MP_OBJ_NEW_CONST_FLOAT(f) ((mp_obj_t)((((((uint64_t)f) & ~3) | 2) + 0x80800000) & 0xffffffff)) +#define mp_const_float_e MP_OBJ_NEW_CONST_FLOAT(0x402df854) +#define mp_const_float_pi MP_OBJ_NEW_CONST_FLOAT(0x40490fdb) +#define mp_const_float_nan MP_OBJ_NEW_CONST_FLOAT(0x7fc00000) #if MICROPY_PY_MATH_CONSTANTS -#define mp_const_float_tau MP_ROM_PTR((mp_obj_t)(((0x40c90fdb & ~3) | 2) + 0x80800000)) -#define mp_const_float_inf MP_ROM_PTR((mp_obj_t)(((0x7f800000 & ~3) | 2) + 0x80800000)) -#define mp_const_float_nan MP_ROM_PTR((mp_obj_t)(((0xffc00000 & ~3) | 2) + 0x80800000)) +#define mp_const_float_tau MP_OBJ_NEW_CONST_FLOAT(0x40c90fdb) +#define mp_const_float_inf MP_OBJ_NEW_CONST_FLOAT(0x7f800000) #endif static inline bool mp_obj_is_float(mp_const_obj_t o) { @@ -202,15 +205,23 @@ static inline mp_float_t mp_obj_float_get(mp_const_obj_t o) { union { mp_float_t f; mp_uint_t u; - } num = {.u = ((mp_uint_t)o - 0x80800000) & ~3}; + } num = {.u = ((mp_uint_t)o - 0x80800000u) & ~3u}; + // Rather than always truncating toward zero, which creates a strong + // bias, copy the two previous bits to fill in the two missing bits. + // This appears to be a pretty good heuristic. + num.u |= (num.u >> 2) & 3u; return num.f; } static inline mp_obj_t mp_obj_new_float(mp_float_t f) { + if (isnan(f)) { + // prevent creation of bad nanboxed pointers via array.array or struct + return mp_const_float_nan; + } union { mp_float_t f; mp_uint_t u; } num = {.f = f}; - return (mp_obj_t)(((num.u & ~0x3) | 2) + 0x80800000); + return (mp_obj_t)(((num.u & ~0x3u) | 2u) + 0x80800000u); } #endif @@ -256,8 +267,10 @@ static inline bool mp_obj_is_immediate_obj(mp_const_obj_t o) { #error MICROPY_OBJ_REPR_D requires MICROPY_FLOAT_IMPL_DOUBLE #endif +#include #define mp_const_float_e {((mp_obj_t)((uint64_t)0x4005bf0a8b145769 + 0x8004000000000000))} #define mp_const_float_pi {((mp_obj_t)((uint64_t)0x400921fb54442d18 + 0x8004000000000000))} +#define mp_const_float_nan {((mp_obj_t)((uint64_t)0x7ff8000000000000 + 0x8004000000000000))} #if MICROPY_PY_MATH_CONSTANTS #define mp_const_float_tau {((mp_obj_t)((uint64_t)0x401921fb54442d18 + 0x8004000000000000))} #define mp_const_float_inf {((mp_obj_t)((uint64_t)0x7ff0000000000000 + 0x8004000000000000))} @@ -275,6 +288,13 @@ static inline mp_float_t mp_obj_float_get(mp_const_obj_t o) { return num.f; } static inline mp_obj_t mp_obj_new_float(mp_float_t f) { + if (isnan(f)) { + // prevent creation of bad nanboxed pointers via array.array or struct + struct { + uint64_t r; + } num = mp_const_float_nan; + return num.r; + } union { mp_float_t f; uint64_t r; @@ -370,25 +390,25 @@ typedef struct _mp_rom_obj_t { mp_const_obj_t o; } mp_rom_obj_t; #define MP_DEFINE_CONST_FUN_OBJ_0(obj_name, fun_name) \ const mp_obj_fun_builtin_fixed_t obj_name = \ - {{&mp_type_fun_builtin_0}, .fun._0 = fun_name} + {.base = {.type = &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} + {.base = {.type = &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} + {.base = {.type = &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} + {.base = {.type = &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}, MP_OBJ_FUN_MAKE_SIG(n_args_min, MP_OBJ_FUN_ARGS_MAX, false), .fun.var = fun_name} + {.base = {.type = &mp_type_fun_builtin_var}, .sig = 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}, MP_OBJ_FUN_MAKE_SIG(n_args_min, n_args_max, false), .fun.var = fun_name} + {.base = {.type = &mp_type_fun_builtin_var}, .sig = 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}, MP_OBJ_FUN_MAKE_SIG(n_args_min, MP_OBJ_FUN_ARGS_MAX, true), .fun.kw = fun_name} + {.base = {.type = &mp_type_fun_builtin_var}, .sig = MP_OBJ_FUN_MAKE_SIG(n_args_min, MP_OBJ_FUN_ARGS_MAX, true), .fun = {.kw = fun_name}} // CIRCUITPY-CHANGE #define MP_DEFINE_CONST_PROP_GET(obj_name, fun_name) \ @@ -515,9 +535,7 @@ static inline bool mp_map_slot_is_filled(const mp_map_t *map, size_t pos) { 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); -mp_map_t *mp_map_new(size_t n); void mp_map_deinit(mp_map_t *map); -void mp_map_free(mp_map_t *map); mp_map_elem_t *mp_map_lookup(mp_map_t *map, mp_obj_t index, mp_map_lookup_kind_t lookup_kind); void mp_map_clear(mp_map_t *map); void mp_map_dump(mp_map_t *map); @@ -548,9 +566,16 @@ typedef mp_obj_t (*mp_fun_3_t)(mp_obj_t, mp_obj_t, mp_obj_t); typedef mp_obj_t (*mp_fun_var_t)(size_t n, const mp_obj_t *); // mp_fun_kw_t takes mp_map_t* (and not const mp_map_t*) to ease passing // this arg to mp_map_lookup(). +// Note that the mp_obj_t* array will contain all arguments, positional and keyword, with the keyword +// ones starting at offset n, like: arg0 arg1 ... arg key0 value0 key1 value1 ..., and the mp_map_t* +// gets those same keyword arguments but as a map for convenience; see fun_builtin_var_call. typedef mp_obj_t (*mp_fun_kw_t)(size_t n, const mp_obj_t *, mp_map_t *); // Flags for type behaviour (mp_obj_type_t.flags) +// If MP_TYPE_FLAG_IS_SUBCLASSED is set, then subclasses of this class have been created. +// Mutations to this class that would require updating all subclasses must be rejected. +// If MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS is set, then attribute lookups involving this +// class need to additionally check for special accessor methods, such as from descriptors. // If MP_TYPE_FLAG_EQ_NOT_REFLEXIVE is clear then __eq__ is reflexive (A==A returns True). // If MP_TYPE_FLAG_EQ_CHECKS_OTHER_TYPE is clear then the type can't be equal to an // instance of any different class that also clears this flag. If this flag is set @@ -568,6 +593,8 @@ typedef mp_obj_t (*mp_fun_kw_t)(size_t n, const mp_obj_t *, mp_map_t *); // If MP_TYPE_FLAG_ITER_IS_STREAM is set then the type implicitly gets a "return self" // getiter, and mp_stream_unbuffered_iter for iternext. // If MP_TYPE_FLAG_INSTANCE_TYPE is set then this is an instance type (i.e. defined in Python). +// If MP_TYPE_FLAG_SUBSCR_ALLOWS_STACK_SLICE is set then the "subscr" slot allows a stack +// allocated slice to be passed in (no references to it will be retained after the call). #define MP_TYPE_FLAG_NONE (0x0000) #define MP_TYPE_FLAG_IS_SUBCLASSED (0x0001) #define MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS (0x0002) @@ -581,8 +608,9 @@ typedef mp_obj_t (*mp_fun_kw_t)(size_t n, const mp_obj_t *, mp_map_t *); #define MP_TYPE_FLAG_ITER_IS_CUSTOM (0x0100) #define MP_TYPE_FLAG_ITER_IS_STREAM (MP_TYPE_FLAG_ITER_IS_ITERNEXT | MP_TYPE_FLAG_ITER_IS_CUSTOM) #define MP_TYPE_FLAG_INSTANCE_TYPE (0x0200) +#define MP_TYPE_FLAG_SUBSCR_ALLOWS_STACK_SLICE (0x0400) // CIRCUITPY-CHANGE: check for valid types in json dumps -#define MP_TYPE_FLAG_PRINT_JSON (0x0400) +#define MP_TYPE_FLAG_PRINT_JSON (0x0800) typedef enum { PRINT_STR = 0, @@ -783,25 +811,6 @@ typedef struct _mp_obj_full_type_t { #define _MP_OBJ_TYPE_SLOT_TYPE_parent (const void *) #define _MP_OBJ_TYPE_SLOT_TYPE_locals_dict (struct _mp_obj_dict_t *) -// Implementation of MP_DEFINE_CONST_OBJ_TYPE for each number of arguments. -// Do not use these directly, instead use MP_DEFINE_CONST_OBJ_TYPE. -// Generated with: -// for i in range(13): -// print(f"#define MP_DEFINE_CONST_OBJ_TYPE_NARGS_{i}(_struct_type, _typename, _name, _flags{''.join(f', f{j+1}, v{j+1}' for j in range(i))}) const _struct_type _typename = {{ .base = {{ &mp_type_type }}, .flags = _flags, .name = _name{''.join(f', .slot_index_##f{j+1} = {j+1}' for j in range(i))}{', .slots = { ' + ''.join(f'v{j+1}, ' for j in range(i)) + '}' if i else '' } }}") -#define MP_DEFINE_CONST_OBJ_TYPE_NARGS_0(_struct_type, _typename, _name, _flags) const _struct_type _typename = { .base = { &mp_type_type }, .flags = _flags, .name = _name } -#define MP_DEFINE_CONST_OBJ_TYPE_NARGS_1(_struct_type, _typename, _name, _flags, f1, v1) const _struct_type _typename = { .base = { &mp_type_type }, .flags = _flags, .name = _name, .slot_index_##f1 = 1, .slots = { v1, } } -#define MP_DEFINE_CONST_OBJ_TYPE_NARGS_2(_struct_type, _typename, _name, _flags, f1, v1, f2, v2) const _struct_type _typename = { .base = { &mp_type_type }, .flags = _flags, .name = _name, .slot_index_##f1 = 1, .slot_index_##f2 = 2, .slots = { v1, v2, } } -#define MP_DEFINE_CONST_OBJ_TYPE_NARGS_3(_struct_type, _typename, _name, _flags, f1, v1, f2, v2, f3, v3) const _struct_type _typename = { .base = { &mp_type_type }, .flags = _flags, .name = _name, .slot_index_##f1 = 1, .slot_index_##f2 = 2, .slot_index_##f3 = 3, .slots = { v1, v2, v3, } } -#define MP_DEFINE_CONST_OBJ_TYPE_NARGS_4(_struct_type, _typename, _name, _flags, f1, v1, f2, v2, f3, v3, f4, v4) const _struct_type _typename = { .base = { &mp_type_type }, .flags = _flags, .name = _name, .slot_index_##f1 = 1, .slot_index_##f2 = 2, .slot_index_##f3 = 3, .slot_index_##f4 = 4, .slots = { v1, v2, v3, v4, } } -#define MP_DEFINE_CONST_OBJ_TYPE_NARGS_5(_struct_type, _typename, _name, _flags, f1, v1, f2, v2, f3, v3, f4, v4, f5, v5) const _struct_type _typename = { .base = { &mp_type_type }, .flags = _flags, .name = _name, .slot_index_##f1 = 1, .slot_index_##f2 = 2, .slot_index_##f3 = 3, .slot_index_##f4 = 4, .slot_index_##f5 = 5, .slots = { v1, v2, v3, v4, v5, } } -#define MP_DEFINE_CONST_OBJ_TYPE_NARGS_6(_struct_type, _typename, _name, _flags, f1, v1, f2, v2, f3, v3, f4, v4, f5, v5, f6, v6) const _struct_type _typename = { .base = { &mp_type_type }, .flags = _flags, .name = _name, .slot_index_##f1 = 1, .slot_index_##f2 = 2, .slot_index_##f3 = 3, .slot_index_##f4 = 4, .slot_index_##f5 = 5, .slot_index_##f6 = 6, .slots = { v1, v2, v3, v4, v5, v6, } } -#define MP_DEFINE_CONST_OBJ_TYPE_NARGS_7(_struct_type, _typename, _name, _flags, f1, v1, f2, v2, f3, v3, f4, v4, f5, v5, f6, v6, f7, v7) const _struct_type _typename = { .base = { &mp_type_type }, .flags = _flags, .name = _name, .slot_index_##f1 = 1, .slot_index_##f2 = 2, .slot_index_##f3 = 3, .slot_index_##f4 = 4, .slot_index_##f5 = 5, .slot_index_##f6 = 6, .slot_index_##f7 = 7, .slots = { v1, v2, v3, v4, v5, v6, v7, } } -#define MP_DEFINE_CONST_OBJ_TYPE_NARGS_8(_struct_type, _typename, _name, _flags, f1, v1, f2, v2, f3, v3, f4, v4, f5, v5, f6, v6, f7, v7, f8, v8) const _struct_type _typename = { .base = { &mp_type_type }, .flags = _flags, .name = _name, .slot_index_##f1 = 1, .slot_index_##f2 = 2, .slot_index_##f3 = 3, .slot_index_##f4 = 4, .slot_index_##f5 = 5, .slot_index_##f6 = 6, .slot_index_##f7 = 7, .slot_index_##f8 = 8, .slots = { v1, v2, v3, v4, v5, v6, v7, v8, } } -#define MP_DEFINE_CONST_OBJ_TYPE_NARGS_9(_struct_type, _typename, _name, _flags, f1, v1, f2, v2, f3, v3, f4, v4, f5, v5, f6, v6, f7, v7, f8, v8, f9, v9) const _struct_type _typename = { .base = { &mp_type_type }, .flags = _flags, .name = _name, .slot_index_##f1 = 1, .slot_index_##f2 = 2, .slot_index_##f3 = 3, .slot_index_##f4 = 4, .slot_index_##f5 = 5, .slot_index_##f6 = 6, .slot_index_##f7 = 7, .slot_index_##f8 = 8, .slot_index_##f9 = 9, .slots = { v1, v2, v3, v4, v5, v6, v7, v8, v9, } } -#define MP_DEFINE_CONST_OBJ_TYPE_NARGS_10(_struct_type, _typename, _name, _flags, f1, v1, f2, v2, f3, v3, f4, v4, f5, v5, f6, v6, f7, v7, f8, v8, f9, v9, f10, v10) const _struct_type _typename = { .base = { &mp_type_type }, .flags = _flags, .name = _name, .slot_index_##f1 = 1, .slot_index_##f2 = 2, .slot_index_##f3 = 3, .slot_index_##f4 = 4, .slot_index_##f5 = 5, .slot_index_##f6 = 6, .slot_index_##f7 = 7, .slot_index_##f8 = 8, .slot_index_##f9 = 9, .slot_index_##f10 = 10, .slots = { v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, } } -#define MP_DEFINE_CONST_OBJ_TYPE_NARGS_11(_struct_type, _typename, _name, _flags, f1, v1, f2, v2, f3, v3, f4, v4, f5, v5, f6, v6, f7, v7, f8, v8, f9, v9, f10, v10, f11, v11) const _struct_type _typename = { .base = { &mp_type_type }, .flags = _flags, .name = _name, .slot_index_##f1 = 1, .slot_index_##f2 = 2, .slot_index_##f3 = 3, .slot_index_##f4 = 4, .slot_index_##f5 = 5, .slot_index_##f6 = 6, .slot_index_##f7 = 7, .slot_index_##f8 = 8, .slot_index_##f9 = 9, .slot_index_##f10 = 10, .slot_index_##f11 = 11, .slots = { v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, } } -#define MP_DEFINE_CONST_OBJ_TYPE_NARGS_12(_struct_type, _typename, _name, _flags, f1, v1, f2, v2, f3, v3, f4, v4, f5, v5, f6, v6, f7, v7, f8, v8, f9, v9, f10, v10, f11, v11, f12, v12) const _struct_type _typename = { .base = { &mp_type_type }, .flags = _flags, .name = _name, .slot_index_##f1 = 1, .slot_index_##f2 = 2, .slot_index_##f3 = 3, .slot_index_##f4 = 4, .slot_index_##f5 = 5, .slot_index_##f6 = 6, .slot_index_##f7 = 7, .slot_index_##f8 = 8, .slot_index_##f9 = 9, .slot_index_##f10 = 10, .slot_index_##f11 = 11, .slot_index_##f12 = 12, .slots = { v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, } } - // Because the mp_obj_type_t instances are in (zero-initialised) ROM, we take // slot_index_foo=0 to mean that the slot is unset. This also simplifies checking // if the slot is set. That means that we need to store index+1 in slot_index_foo @@ -815,6 +824,34 @@ typedef struct _mp_obj_full_type_t { #define MP_OBJ_TYPE_OFFSETOF_SLOT(f) (offsetof(mp_obj_type_t, slot_index_##f)) #define MP_OBJ_TYPE_HAS_SLOT_BY_OFFSET(t, offset) (*(uint8_t *)((char *)(t) + (offset)) != 0) +// Implementation of MP_DEFINE_CONST_OBJ_TYPE for each number of arguments. +// Do not use these directly, instead use MP_DEFINE_CONST_OBJ_TYPE. +// Generated with: +// for i in range(13): +// args = ['_struct_type', '_typename', '_name', '_flags'] +// struct = ['.base = { &mp_type_type }', '.flags = _flags', '.name = _name'] +// slots = [] +// for j in range(i): +// args += [f"f{j+1}", f"v{j+1}"] +// struct += [f".slot_index_##f{j+1} = {j+1}"] +// slots += [f"(const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f{j+1} v{j+1}"] +// if slots: +// struct += [f".slots = {{ {', '.join(slots)} }}"] +// print(f"#define MP_DEFINE_CONST_OBJ_TYPE_NARGS_{i}({', '.join(args)}) const _struct_type _typename = {{ {', '.join(struct)} }}") +#define MP_DEFINE_CONST_OBJ_TYPE_NARGS_0(_struct_type, _typename, _name, _flags) const _struct_type _typename = { .base = { &mp_type_type }, .flags = _flags, .name = _name } +#define MP_DEFINE_CONST_OBJ_TYPE_NARGS_1(_struct_type, _typename, _name, _flags, f1, v1) const _struct_type _typename = { .base = { &mp_type_type }, .flags = _flags, .name = _name, .slot_index_##f1 = 1, .slots = { (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f1 v1 } } +#define MP_DEFINE_CONST_OBJ_TYPE_NARGS_2(_struct_type, _typename, _name, _flags, f1, v1, f2, v2) const _struct_type _typename = { .base = { &mp_type_type }, .flags = _flags, .name = _name, .slot_index_##f1 = 1, .slot_index_##f2 = 2, .slots = { (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f1 v1, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f2 v2 } } +#define MP_DEFINE_CONST_OBJ_TYPE_NARGS_3(_struct_type, _typename, _name, _flags, f1, v1, f2, v2, f3, v3) const _struct_type _typename = { .base = { &mp_type_type }, .flags = _flags, .name = _name, .slot_index_##f1 = 1, .slot_index_##f2 = 2, .slot_index_##f3 = 3, .slots = { (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f1 v1, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f2 v2, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f3 v3 } } +#define MP_DEFINE_CONST_OBJ_TYPE_NARGS_4(_struct_type, _typename, _name, _flags, f1, v1, f2, v2, f3, v3, f4, v4) const _struct_type _typename = { .base = { &mp_type_type }, .flags = _flags, .name = _name, .slot_index_##f1 = 1, .slot_index_##f2 = 2, .slot_index_##f3 = 3, .slot_index_##f4 = 4, .slots = { (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f1 v1, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f2 v2, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f3 v3, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f4 v4 } } +#define MP_DEFINE_CONST_OBJ_TYPE_NARGS_5(_struct_type, _typename, _name, _flags, f1, v1, f2, v2, f3, v3, f4, v4, f5, v5) const _struct_type _typename = { .base = { &mp_type_type }, .flags = _flags, .name = _name, .slot_index_##f1 = 1, .slot_index_##f2 = 2, .slot_index_##f3 = 3, .slot_index_##f4 = 4, .slot_index_##f5 = 5, .slots = { (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f1 v1, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f2 v2, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f3 v3, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f4 v4, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f5 v5 } } +#define MP_DEFINE_CONST_OBJ_TYPE_NARGS_6(_struct_type, _typename, _name, _flags, f1, v1, f2, v2, f3, v3, f4, v4, f5, v5, f6, v6) const _struct_type _typename = { .base = { &mp_type_type }, .flags = _flags, .name = _name, .slot_index_##f1 = 1, .slot_index_##f2 = 2, .slot_index_##f3 = 3, .slot_index_##f4 = 4, .slot_index_##f5 = 5, .slot_index_##f6 = 6, .slots = { (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f1 v1, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f2 v2, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f3 v3, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f4 v4, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f5 v5, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f6 v6 } } +#define MP_DEFINE_CONST_OBJ_TYPE_NARGS_7(_struct_type, _typename, _name, _flags, f1, v1, f2, v2, f3, v3, f4, v4, f5, v5, f6, v6, f7, v7) const _struct_type _typename = { .base = { &mp_type_type }, .flags = _flags, .name = _name, .slot_index_##f1 = 1, .slot_index_##f2 = 2, .slot_index_##f3 = 3, .slot_index_##f4 = 4, .slot_index_##f5 = 5, .slot_index_##f6 = 6, .slot_index_##f7 = 7, .slots = { (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f1 v1, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f2 v2, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f3 v3, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f4 v4, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f5 v5, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f6 v6, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f7 v7 } } +#define MP_DEFINE_CONST_OBJ_TYPE_NARGS_8(_struct_type, _typename, _name, _flags, f1, v1, f2, v2, f3, v3, f4, v4, f5, v5, f6, v6, f7, v7, f8, v8) const _struct_type _typename = { .base = { &mp_type_type }, .flags = _flags, .name = _name, .slot_index_##f1 = 1, .slot_index_##f2 = 2, .slot_index_##f3 = 3, .slot_index_##f4 = 4, .slot_index_##f5 = 5, .slot_index_##f6 = 6, .slot_index_##f7 = 7, .slot_index_##f8 = 8, .slots = { (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f1 v1, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f2 v2, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f3 v3, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f4 v4, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f5 v5, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f6 v6, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f7 v7, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f8 v8 } } +#define MP_DEFINE_CONST_OBJ_TYPE_NARGS_9(_struct_type, _typename, _name, _flags, f1, v1, f2, v2, f3, v3, f4, v4, f5, v5, f6, v6, f7, v7, f8, v8, f9, v9) const _struct_type _typename = { .base = { &mp_type_type }, .flags = _flags, .name = _name, .slot_index_##f1 = 1, .slot_index_##f2 = 2, .slot_index_##f3 = 3, .slot_index_##f4 = 4, .slot_index_##f5 = 5, .slot_index_##f6 = 6, .slot_index_##f7 = 7, .slot_index_##f8 = 8, .slot_index_##f9 = 9, .slots = { (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f1 v1, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f2 v2, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f3 v3, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f4 v4, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f5 v5, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f6 v6, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f7 v7, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f8 v8, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f9 v9 } } +#define MP_DEFINE_CONST_OBJ_TYPE_NARGS_10(_struct_type, _typename, _name, _flags, f1, v1, f2, v2, f3, v3, f4, v4, f5, v5, f6, v6, f7, v7, f8, v8, f9, v9, f10, v10) const _struct_type _typename = { .base = { &mp_type_type }, .flags = _flags, .name = _name, .slot_index_##f1 = 1, .slot_index_##f2 = 2, .slot_index_##f3 = 3, .slot_index_##f4 = 4, .slot_index_##f5 = 5, .slot_index_##f6 = 6, .slot_index_##f7 = 7, .slot_index_##f8 = 8, .slot_index_##f9 = 9, .slot_index_##f10 = 10, .slots = { (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f1 v1, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f2 v2, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f3 v3, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f4 v4, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f5 v5, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f6 v6, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f7 v7, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f8 v8, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f9 v9, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f10 v10 } } +#define MP_DEFINE_CONST_OBJ_TYPE_NARGS_11(_struct_type, _typename, _name, _flags, f1, v1, f2, v2, f3, v3, f4, v4, f5, v5, f6, v6, f7, v7, f8, v8, f9, v9, f10, v10, f11, v11) const _struct_type _typename = { .base = { &mp_type_type }, .flags = _flags, .name = _name, .slot_index_##f1 = 1, .slot_index_##f2 = 2, .slot_index_##f3 = 3, .slot_index_##f4 = 4, .slot_index_##f5 = 5, .slot_index_##f6 = 6, .slot_index_##f7 = 7, .slot_index_##f8 = 8, .slot_index_##f9 = 9, .slot_index_##f10 = 10, .slot_index_##f11 = 11, .slots = { (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f1 v1, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f2 v2, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f3 v3, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f4 v4, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f5 v5, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f6 v6, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f7 v7, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f8 v8, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f9 v9, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f10 v10, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f11 v11 } } +#define MP_DEFINE_CONST_OBJ_TYPE_NARGS_12(_struct_type, _typename, _name, _flags, f1, v1, f2, v2, f3, v3, f4, v4, f5, v5, f6, v6, f7, v7, f8, v8, f9, v9, f10, v10, f11, v11, f12, v12) const _struct_type _typename = { .base = { &mp_type_type }, .flags = _flags, .name = _name, .slot_index_##f1 = 1, .slot_index_##f2 = 2, .slot_index_##f3 = 3, .slot_index_##f4 = 4, .slot_index_##f5 = 5, .slot_index_##f6 = 6, .slot_index_##f7 = 7, .slot_index_##f8 = 8, .slot_index_##f9 = 9, .slot_index_##f10 = 10, .slot_index_##f11 = 11, .slot_index_##f12 = 12, .slots = { (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f1 v1, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f2 v2, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f3 v3, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f4 v4, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f5 v5, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f6 v6, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f7 v7, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f8 v8, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f9 v9, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f10 v10, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f11 v11, (const void *)_MP_OBJ_TYPE_SLOT_TYPE_##f12 v12 } } + // Workaround for https://docs.microsoft.com/en-us/cpp/preprocessor/preprocessor-experimental-overview?view=msvc-160#macro-arguments-are-unpacked #define MP_DEFINE_CONST_OBJ_TYPE_EXPAND(x) x @@ -823,7 +860,7 @@ typedef struct _mp_obj_full_type_t { #define MP_DEFINE_CONST_OBJ_TYPE_NARGS(_1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13, _14, _15, _16, _17, _18, _19, _20, _21, _22, _23, _24, _25, _26, _27, _28, N, ...) MP_DEFINE_CONST_OBJ_TYPE_NARGS_##N // This macros is used to define a object type in ROM. -// Invoke as MP_DEFINE_CONST_OBJ_TYPE(_typename, _name, _flags, _make_new [, slot, func]*) +// Invoke as MP_DEFINE_CONST_OBJ_TYPE(_typename, _name, _flags, [, slot, func]*) // It uses the number of arguments to select which MP_DEFINE_CONST_OBJ_TYPE_* // macro to use based on the number of arguments. It works by shifting the // numeric values 12, 11, ... 0 by the number of arguments, such that the @@ -838,12 +875,14 @@ extern const mp_obj_type_t mp_type_NoneType; extern const mp_obj_type_t mp_type_bool; extern const mp_obj_type_t mp_type_int; extern const mp_obj_type_t mp_type_str; +extern const mp_obj_type_t mp_type_template; +extern const mp_obj_type_t mp_type_interpolation; extern const mp_obj_type_t mp_type_bytes; extern const mp_obj_type_t mp_type_bytearray; extern const mp_obj_type_t mp_type_memoryview; extern const mp_obj_type_t mp_type_float; extern const mp_obj_type_t mp_type_complex; -// CIRCUITPY-CHANGE +// CIRCUITPY-CHANGE: add traceback support extern const mp_obj_type_t mp_type_traceback; extern const mp_obj_type_t mp_type_tuple; extern const mp_obj_type_t mp_type_list; @@ -878,6 +917,7 @@ extern const mp_obj_type_t mp_type_fun_bc; extern const mp_obj_type_t mp_type_fun_native; extern const mp_obj_type_t mp_type_fun_viper; extern const mp_obj_type_t mp_type_fun_asm; +extern const mp_obj_type_t mp_type_code; 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; @@ -885,6 +925,7 @@ extern const mp_obj_type_t mp_type_bound_meth; extern const mp_obj_type_t mp_type_property; extern const mp_obj_type_t mp_type_stringio; extern const mp_obj_type_t mp_type_bytesio; +extern const mp_obj_type_t mp_type_ringio; extern const mp_obj_type_t mp_type_reversed; extern const mp_obj_type_t mp_type_polymorph_iter; #if MICROPY_ENABLE_FINALISER @@ -903,7 +944,7 @@ extern const mp_obj_type_t mp_type_ImportError; extern const mp_obj_type_t mp_type_IndentationError; extern const mp_obj_type_t mp_type_IndexError; extern const mp_obj_type_t mp_type_KeyboardInterrupt; -// CIRCUITPY-CHANGE +// CIRCUITPY-CHANGE: add ReloadException extern const mp_obj_type_t mp_type_ReloadException; extern const mp_obj_type_t mp_type_KeyError; extern const mp_obj_type_t mp_type_LookupError; @@ -911,9 +952,9 @@ extern const mp_obj_type_t mp_type_MemoryError; extern const mp_obj_type_t mp_type_NameError; extern const mp_obj_type_t mp_type_NotImplementedError; extern const mp_obj_type_t mp_type_OSError; -// CIRCUITPY-CHANGE +// CIRCUITPY-CHANGE: add ConnectionError extern const mp_obj_type_t mp_type_ConnectionError; -// CIRCUITPY-CHANGE +// CIRCUITPY-CHANGE: add BrokenPipeError extern const mp_obj_type_t mp_type_BrokenPipeError; extern const mp_obj_type_t mp_type_OverflowError; extern const mp_obj_type_t mp_type_RuntimeError; @@ -921,6 +962,7 @@ extern const mp_obj_type_t mp_type_StopAsyncIteration; extern const mp_obj_type_t mp_type_StopIteration; extern const mp_obj_type_t mp_type_SyntaxError; extern const mp_obj_type_t mp_type_SystemExit; +// CIRCUITPY-CHANGE: add TimeoutError extern const mp_obj_type_t mp_type_TimeoutError; extern const mp_obj_type_t mp_type_TypeError; extern const mp_obj_type_t mp_type_UnicodeError; @@ -985,11 +1027,11 @@ void *mp_obj_malloc_helper(size_t num_bytes, const mp_obj_type_t *type); // Object allocation macros for allocating objects that have a finaliser. #if MICROPY_ENABLE_FINALISER #define mp_obj_malloc_with_finaliser(struct_type, obj_type) ((struct_type *)mp_obj_malloc_with_finaliser_helper(sizeof(struct_type), obj_type)) -#define mp_obj_malloc_var_with_finaliser(struct_type, var_type, var_num, obj_type) ((struct_type *)mp_obj_malloc_with_finaliser_helper(sizeof(struct_type) + sizeof(var_type) * (var_num), obj_type)) +#define mp_obj_malloc_var_with_finaliser(struct_type, var_field, var_type, var_num, obj_type) ((struct_type *)mp_obj_malloc_with_finaliser_helper(offsetof(struct_type, var_field) + sizeof(var_type) * (var_num), obj_type)) void *mp_obj_malloc_with_finaliser_helper(size_t num_bytes, const mp_obj_type_t *type); #else #define mp_obj_malloc_with_finaliser(struct_type, obj_type) mp_obj_malloc(struct_type, obj_type) -#define mp_obj_malloc_var_with_finaliser(struct_type, var_type, var_num, obj_type) mp_obj_malloc_var(struct_type, var_type, var_num, obj_type) +#define mp_obj_malloc_var_with_finaliser(struct_type, var_field, var_type, var_num, obj_type) mp_obj_malloc_var(struct_type, var_field, var_type, var_num, obj_type) #endif // These macros are derived from more primitive ones and are used to @@ -1009,8 +1051,13 @@ void *mp_obj_malloc_with_finaliser_helper(size_t num_bytes, const mp_obj_type_t MP_STATIC_ASSERT_NONCONSTEXPR((t) != &mp_type_str), assert((t) != &mp_type_str), \ MP_STATIC_ASSERT_NONCONSTEXPR((t) != &mp_type_NoneType), assert((t) != &mp_type_NoneType), \ 1) +#if MICROPY_PY_BUILTINS_FLOAT +#define mp_type_assert_not_float(t) (MP_STATIC_ASSERT_NONCONSTEXPR((t) != &mp_type_float), assert((t) != &mp_type_float), 1) +#else +#define mp_type_assert_not_float(t) (1) +#endif -#define mp_obj_is_type(o, t) (mp_type_assert_not_bool_int_str_nonetype(t) && mp_obj_is_exact_type(o, t)) +#define mp_obj_is_type(o, t) (mp_type_assert_not_bool_int_str_nonetype(t) && mp_type_assert_not_float(t) && mp_obj_is_exact_type(o, t)) #if MICROPY_OBJ_IMMEDIATE_OBJS // bool's are immediates, not real objects, so test for the 2 possible values. #define mp_obj_is_bool(o) ((o) == mp_const_false || (o) == mp_const_true) @@ -1026,7 +1073,6 @@ bool mp_obj_is_dict_or_ordereddict(mp_obj_t o); // type check is done on iter method to allow tuple, namedtuple, attrtuple #define mp_obj_is_tuple_compatible(o) (MP_OBJ_TYPE_GET_SLOT_OR_NULL(mp_obj_get_type(o), iter) == mp_obj_tuple_getiter) -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; } @@ -1037,6 +1083,7 @@ mp_obj_t mp_obj_new_int_from_str_len(const char **str, size_t len, bool neg, uns 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); // will check utf-8 (raises UnicodeError) +mp_obj_t mp_obj_new_str_from_cstr(const char *str); // // accepts null-terminated string, will check utf-8 (raises UnicodeError) mp_obj_t mp_obj_new_str_via_qstr(const char *data, size_t len); // input data must be valid utf-8 mp_obj_t mp_obj_new_str_from_vstr(vstr_t *vstr); // will check utf-8 (raises UnicodeError) #if MICROPY_PY_BUILTINS_STR_UNICODE && MICROPY_PY_BUILTINS_STR_UNICODE_CHECK @@ -1046,12 +1093,15 @@ mp_obj_t mp_obj_new_str_from_utf8_vstr(vstr_t *vstr); // input data must be vali #endif mp_obj_t mp_obj_new_bytes_from_vstr(vstr_t *vstr); mp_obj_t mp_obj_new_bytes(const byte *data, size_t len); -// CIRCUITPY-CHANGE +// CIRCUITPY-CHANGE: new routine mp_obj_t mp_obj_new_bytes_of_zeros(size_t len); mp_obj_t mp_obj_new_bytearray(size_t n, const void *items); -// CIRCUITPY-CHANGE +// CIRCUITPY-CHANGE: new routine mp_obj_t mp_obj_new_bytearray_of_zeros(size_t n); mp_obj_t mp_obj_new_bytearray_by_ref(size_t n, void *items); +#if MICROPY_PY_TSTRINGS +mp_obj_t mp_obj_new_template(size_t n_args, const mp_obj_t *args); +#endif #if MICROPY_PY_BUILTINS_FLOAT 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); @@ -1085,7 +1135,7 @@ mp_obj_t mp_obj_new_memoryview(byte typecode, size_t nitems, void *items); const mp_obj_type_t *mp_obj_get_type(mp_const_obj_t o_in); const char *mp_obj_get_type_str(mp_const_obj_t o_in); -// CIRCUITPY-CHANGE +// CIRCUITPY-CHANGE: new routine #define mp_obj_get_type_qstr(o_in) (mp_obj_get_type((o_in))->name) bool mp_obj_is_subclass_fast(mp_const_obj_t object, mp_const_obj_t classinfo); // arguments should be type objects mp_obj_t mp_obj_cast_to_native_base(mp_obj_t self_in, mp_const_obj_t native_type); @@ -1093,7 +1143,7 @@ mp_obj_t mp_obj_cast_to_native_base(mp_obj_t self_in, mp_const_obj_t native_type void mp_obj_print_helper(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind); void mp_obj_print(mp_obj_t o, mp_print_kind_t kind); void mp_obj_print_exception(const mp_print_t *print, mp_obj_t exc); -// CIRCUITPY-CHANGE +// CIRCUITPY-CHANGE: new routine void mp_obj_print_exception_with_limit(const mp_print_t *print, mp_obj_t exc, mp_int_t limit); bool mp_obj_is_true(mp_obj_t arg); @@ -1107,6 +1157,8 @@ static inline bool mp_obj_is_integer(mp_const_obj_t o) { } mp_int_t mp_obj_get_int(mp_const_obj_t arg); +mp_uint_t mp_obj_get_uint(mp_const_obj_t arg); +long long mp_obj_get_ll(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); #if MICROPY_PY_BUILTINS_FLOAT @@ -1156,7 +1208,7 @@ bool mp_obj_exception_match(mp_obj_t exc, mp_const_obj_t exc_type); void mp_obj_exception_clear_traceback(mp_obj_t self_in); void mp_obj_exception_add_traceback(mp_obj_t self_in, qstr file, size_t line, qstr block); void mp_obj_exception_get_traceback(mp_obj_t self_in, size_t *n, size_t **values); -// CIRCUITPY-CHANGE +// CIRCUITPY-CHANGE: new routine mp_obj_t mp_obj_exception_get_traceback_obj(mp_obj_t self_in); mp_obj_t mp_obj_exception_get_value(mp_obj_t self_in); mp_obj_t mp_obj_exception_make_new(const mp_obj_type_t *type_in, size_t n_args, size_t n_kw, const mp_obj_t *args); @@ -1227,21 +1279,6 @@ mp_obj_t mp_obj_complex_binary_op(mp_binary_op_t op, mp_float_t lhs_real, mp_flo #define mp_obj_is_float(o) (false) #endif -// tuple -void mp_obj_tuple_get(mp_obj_t self_in, size_t *len, mp_obj_t **items); -void mp_obj_tuple_del(mp_obj_t self_in); -mp_int_t mp_obj_tuple_hash(mp_obj_t self_in); - -// list -// CIRCUITPY-CHANGE -mp_obj_t mp_obj_list_clear(mp_obj_t self_in); -mp_obj_t mp_obj_list_append(mp_obj_t self_in, mp_obj_t arg); -mp_obj_t mp_obj_list_remove(mp_obj_t self_in, mp_obj_t value); -void mp_obj_list_get(mp_obj_t self_in, size_t *len, mp_obj_t **items); -void mp_obj_list_set_len(mp_obj_t self_in, size_t len); -void mp_obj_list_store(mp_obj_t self_in, mp_obj_t index, mp_obj_t value); -mp_obj_t mp_obj_list_sort(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs); - // dict typedef struct _mp_obj_dict_t { mp_obj_base_t base; @@ -1298,7 +1335,6 @@ typedef struct _mp_obj_fun_builtin_var_t { } fun; } mp_obj_fun_builtin_var_t; -qstr mp_obj_fun_get_name(mp_const_obj_t fun); mp_obj_t mp_identity(mp_obj_t self); MP_DECLARE_CONST_FUN_OBJ_1(mp_identity_obj); @@ -1313,9 +1349,6 @@ typedef struct _mp_obj_module_t { mp_obj_base_t base; mp_obj_dict_t *globals; } mp_obj_module_t; -static inline mp_obj_dict_t *mp_obj_module_get_globals(mp_obj_t module) { - return ((mp_obj_module_t *)MP_OBJ_TO_PTR(module))->globals; -} // staticmethod and classmethod types; defined here so we can make const versions // this structure is used for instances of both staticmethod and classmethod @@ -1329,7 +1362,7 @@ typedef struct _mp_rom_obj_static_class_method_t { } mp_rom_obj_static_class_method_t; // property -// CIRCUITPY-CHANGE +// CIRCUITPY-CHANGE: extra args const mp_obj_t *mp_obj_property_get(mp_obj_t self_in, size_t *n_proxy); // sequence helpers @@ -1347,7 +1380,7 @@ bool mp_seq_cmp_bytes(mp_uint_t op, const byte *data1, size_t len1, const byte * bool mp_seq_cmp_objs(mp_uint_t op, const mp_obj_t *items1, size_t len1, const mp_obj_t *items2, size_t len2); mp_obj_t mp_seq_index_obj(const mp_obj_t *items, size_t len, size_t n_args, const mp_obj_t *args); 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); +mp_obj_t mp_seq_extract_slice(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)) @@ -1362,6 +1395,8 @@ mp_obj_t mp_seq_extract_slice(size_t len, const mp_obj_t *seq, mp_bound_slice_t 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)); +#if !MICROPY_PREVIEW_VERSION_2 + // Provide translation for legacy API #define MP_OBJ_IS_SMALL_INT mp_obj_is_small_int #define MP_OBJ_IS_QSTR mp_obj_is_qstr @@ -1374,4 +1409,6 @@ mp_obj_t mp_seq_extract_slice(size_t len, const mp_obj_t *seq, mp_bound_slice_t #define MP_MAP_SLOT_IS_FILLED mp_map_slot_is_filled #define MP_SET_SLOT_IS_FILLED mp_set_slot_is_filled +#endif + #endif // MICROPY_INCLUDED_PY_OBJ_H diff --git a/py/objarray.c b/py/objarray.c index 3ab982184f9..f22cbb9fbe8 100644 --- a/py/objarray.c +++ b/py/objarray.c @@ -105,23 +105,40 @@ static mp_obj_array_t *array_new(char typecode, size_t n) { mp_raise_ValueError(MP_ERROR_TEXT("bad typecode")); } int typecode_size = mp_binary_get_size('@', typecode, NULL); - mp_obj_array_t *o = m_new_obj(mp_obj_array_t); + + // CIRCUITPY-CHANGE: refactor to use m_obj_malloc() + const mp_obj_type_t *type; #if MICROPY_PY_BUILTINS_BYTEARRAY && MICROPY_PY_ARRAY - o->base.type = (typecode == BYTEARRAY_TYPECODE) ? &mp_type_bytearray : &mp_type_array; + type = (typecode == BYTEARRAY_TYPECODE) ? &mp_type_bytearray : &mp_type_array; #elif MICROPY_PY_BUILTINS_BYTEARRAY - o->base.type = &mp_type_bytearray; + type = &mp_type_bytearray; #else - o->base.type = &mp_type_array; + type = &mp_type_array; #endif + mp_obj_array_t *o = mp_obj_malloc(mp_obj_array_t, type); o->typecode = typecode; o->free = 0; o->len = n; - o->items = m_new(byte, typecode_size * o->len); + // CIRCUITPY-CHANGE + o->items = m_malloc_without_collect(typecode_size * o->len); return o; } #endif #if MICROPY_PY_BUILTINS_BYTEARRAY || MICROPY_PY_ARRAY +static void array_extend_impl(mp_obj_array_t *array, mp_obj_t arg, char typecode, size_t len) { + mp_obj_t iterable = mp_getiter(arg, NULL); + mp_obj_t item; + size_t i = 0; + while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) { + if (len == 0) { + array_append(MP_OBJ_FROM_PTR(array), item); + } else { + mp_binary_set_val_array(typecode, array->items, i++, item); + } + } +} + static mp_obj_t array_construct(char typecode, mp_obj_t initializer) { // bytearrays can be raw-initialised from anything with the buffer protocol // other arrays can only be raw-initialised from bytes and bytearray objects @@ -154,18 +171,7 @@ static mp_obj_t array_construct(char typecode, mp_obj_t initializer) { } mp_obj_array_t *array = array_new(typecode, len); - - mp_obj_t iterable = mp_getiter(initializer, NULL); - mp_obj_t item; - size_t i = 0; - while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) { - if (len == 0) { - array_append(MP_OBJ_FROM_PTR(array), item); - } else { - mp_binary_set_val_array(typecode, array->items, i++, item); - } - } - + array_extend_impl(array, initializer, typecode, len); return MP_OBJ_FROM_PTR(array); } #endif @@ -205,7 +211,10 @@ static mp_obj_t bytearray_make_new(const mp_obj_type_t *type_in, size_t n_args, // 1 arg, an integer: construct a blank bytearray of that length mp_uint_t len = mp_obj_get_int(args[0]); mp_obj_array_t *o = array_new(BYTEARRAY_TYPECODE, len); + // If this config is set then the GC clears all memory, so we don't need to. + #if !MICROPY_GC_CONSERVATIVE_CLEAR memset(o->items, 0, len); + #endif return MP_OBJ_FROM_PTR(o); } else { // 1 arg: construct the bytearray from that @@ -225,7 +234,8 @@ static mp_obj_t bytearray_make_new(const mp_obj_type_t *type_in, size_t n_args, #if MICROPY_PY_BUILTINS_MEMORYVIEW 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); + // CIRCUITPY-CHANGE + mp_obj_array_t *self = mp_obj_malloc(mp_obj_array_t, &mp_type_memoryview); mp_obj_memoryview_init(self, typecode, 0, nitems, items); return MP_OBJ_FROM_PTR(self); } @@ -293,7 +303,7 @@ static void memoryview_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { mp_obj_array_t *self = MP_OBJ_TO_PTR(self_in); dest[0] = MP_OBJ_NEW_SMALL_INT(mp_binary_get_size('@', self->typecode & TYPECODE_MASK, NULL)); } - // CIRCUITPY-CHANGE: prevent warning + // CIRCUITPY-CHANGE: add MICROPY_CPYTHON_COMPAT #if MICROPY_PY_BUILTINS_BYTES_HEX || MICROPY_CPYTHON_COMPAT else { // Need to forward to locals dict. @@ -467,8 +477,9 @@ static mp_obj_t array_append(mp_obj_t self_in, mp_obj_t arg) { if (self->free == 0) { size_t item_sz = mp_binary_get_size('@', self->typecode, NULL); // TODO: alloc policy - self->free = 8; - self->items = m_renew(byte, self->items, item_sz * self->len, item_sz * (self->len + self->free)); + size_t add_cnt = 8; + self->items = m_renew(byte, self->items, item_sz * self->len, item_sz * (self->len + add_cnt)); + self->free = add_cnt; mp_seq_clear(self->items, self->len + 1, self->len + self->free, item_sz); } mp_binary_set_val_array(self->typecode, self->items, self->len, arg); @@ -487,39 +498,42 @@ static mp_obj_t array_extend(mp_obj_t self_in, mp_obj_t arg_in) { // allow to extend by anything that has the buffer protocol (extension to CPython) mp_buffer_info_t arg_bufinfo; - // CIRCUITPY-CHANGE: allow appending an iterable - if (mp_get_buffer(arg_in, &arg_bufinfo, MP_BUFFER_READ)) { - size_t sz = mp_binary_get_size('@', self->typecode, NULL); - - // convert byte count to element count - size_t len = arg_bufinfo.len / sz; - - // make sure we have enough room to extend - // TODO: alloc policy; at the moment we go conservative - if (self->free < len) { - self->items = m_renew(byte, self->items, (self->len + self->free) * sz, (self->len + len) * sz); - self->free = 0; - } else { - self->free -= len; - } + if (!mp_get_buffer(arg_in, &arg_bufinfo, MP_BUFFER_READ)) { + array_extend_impl(self, arg_in, 0, 0); + return mp_const_none; + } - // extend - mp_seq_copy((byte *)self->items + self->len * sz, arg_bufinfo.buf, len * sz, byte); - self->len += len; - } else { - // Otherwise argument must be an iterable of items to append - mp_obj_t iterable = mp_getiter(arg_in, NULL); - mp_obj_t item; - while ((item = mp_iternext(iterable)) != MP_OBJ_STOP_ITERATION) { - array_append(self_in, item); + size_t sz = mp_binary_get_size('@', self->typecode, NULL); + + // convert byte count to element count + size_t len = arg_bufinfo.len / sz; + + // make sure we have enough room to extend + // TODO: alloc policy; at the moment we go conservative + if (self->free < len) { + self->items = m_renew(byte, self->items, (self->len + self->free) * sz, (self->len + len) * sz); + self->free = 0; + + if (self_in == arg_in) { + // Get arg_bufinfo again in case self->items has moved + // + // (Note not possible to handle case that arg_in is a memoryview into self) + mp_get_buffer_raise(arg_in, &arg_bufinfo, MP_BUFFER_READ); } + } else { + self->free -= len; } + + // extend + mp_seq_copy((byte *)self->items + self->len * sz, arg_bufinfo.buf, len * sz, byte); + self->len += len; + return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_2(mp_obj_array_extend_obj, array_extend); #endif -// CIRCUITPY-CHANGE: buffer_finder used belo +// CIRCUITPY-CHANGE: buffer_finder used below #if MICROPY_PY_BUILTINS_BYTEARRAY && MICROPY_CPYTHON_COMPAT static mp_obj_t buffer_finder(size_t n_args, const mp_obj_t *args, int direction, bool is_index) { mp_check_self(mp_obj_is_type(args[0], &mp_type_bytearray)); @@ -558,7 +572,6 @@ static mp_obj_t buffer_finder(size_t n_args, const mp_obj_t *args, int direction } return MP_OBJ_NEW_SMALL_INT(p - (const byte *)haystack_bufinfo.buf); } - // CIRCUITPY-CHANGE: provides find, rfind, index static mp_obj_t buffer_find(size_t n_args, const mp_obj_t *args) { return buffer_finder(n_args, args, 1, false); @@ -661,7 +674,7 @@ static mp_obj_t array_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj_t value mp_seq_replace_slice_no_grow(dest_items, o->len, slice.start, slice.stop, src_items + src_offs, src_len, item_sz); // CIRCUITPY-CHANGE - #if MICROPY_NONSTANDARD_TYPECODES + #if MICROPY_PY_STRUCT_UNSAFE_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); @@ -684,7 +697,8 @@ static mp_obj_t array_subscr(mp_obj_t self_in, mp_obj_t index_in, mp_obj_t value if (slice.start > memview_offset_max) { mp_raise_msg(&mp_type_OverflowError, MP_ERROR_TEXT("memoryview offset too large")); } - res = m_new_obj(mp_obj_array_t); + // CIRCUITPY-CHANGE + res = mp_obj_malloc(mp_obj_array_t, &mp_type_memoryview); *res = *o; res->memview_offset += slice.start; res->len = slice.stop - slice.start; @@ -796,7 +810,7 @@ MP_DEFINE_CONST_OBJ_TYPE( MP_DEFINE_CONST_OBJ_TYPE( mp_type_bytearray, MP_QSTR_bytearray, - MP_TYPE_FLAG_EQ_CHECKS_OTHER_TYPE | MP_TYPE_FLAG_ITER_IS_GETITER, + MP_TYPE_FLAG_EQ_CHECKS_OTHER_TYPE | MP_TYPE_FLAG_ITER_IS_GETITER | MP_TYPE_FLAG_SUBSCR_ALLOWS_STACK_SLICE, make_new, bytearray_make_new, print, array_print, iter, array_iterator_new, @@ -835,7 +849,7 @@ MP_DEFINE_CONST_DICT(memoryview_locals_dict, memoryview_locals_dict_table); MP_DEFINE_CONST_OBJ_TYPE( mp_type_memoryview, MP_QSTR_memoryview, - MP_TYPE_FLAG_EQ_CHECKS_OTHER_TYPE | MP_TYPE_FLAG_ITER_IS_GETITER, + MP_TYPE_FLAG_EQ_CHECKS_OTHER_TYPE | MP_TYPE_FLAG_ITER_IS_GETITER | MP_TYPE_FLAG_SUBSCR_ALLOWS_STACK_SLICE, make_new, memoryview_make_new, iter, array_iterator_new, unary_op, array_unary_op, diff --git a/py/objarray.h b/py/objarray.h index 4a0e8a983fe..bb7a514b979 100644 --- a/py/objarray.h +++ b/py/objarray.h @@ -53,6 +53,10 @@ typedef struct _mp_obj_array_t { } mp_obj_array_t; #if MICROPY_PY_BUILTINS_MEMORYVIEW + +#define MP_DEFINE_MEMORYVIEW_OBJ(obj_name, typecode, offset, len, ptr) \ + mp_obj_array_t obj_name = {{&mp_type_memoryview}, (typecode), (offset), (len), (ptr)} + static inline void mp_obj_memoryview_init(mp_obj_array_t *self, size_t typecode, size_t offset, size_t len, void *items) { self->base.type = &mp_type_memoryview; self->typecode = typecode; @@ -60,6 +64,7 @@ static inline void mp_obj_memoryview_init(mp_obj_array_t *self, size_t typecode, self->len = len; self->items = items; } + #endif #if MICROPY_PY_ARRAY || MICROPY_PY_BUILTINS_BYTEARRAY diff --git a/py/objboundmeth.c b/py/objboundmeth.c index e3503ff154a..6df67f7bf9e 100644 --- a/py/objboundmeth.c +++ b/py/objboundmeth.c @@ -102,7 +102,11 @@ static mp_obj_t bound_meth_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_ } mp_obj_bound_meth_t *lhs = MP_OBJ_TO_PTR(lhs_in); mp_obj_bound_meth_t *rhs = MP_OBJ_TO_PTR(rhs_in); + #if MICROPY_PY_BOUND_METHOD_FULL_EQUALITY_CHECK + return mp_obj_new_bool(mp_obj_equal(lhs->self, rhs->self) && mp_obj_equal(lhs->meth, rhs->meth)); + #else return mp_obj_new_bool(lhs->self == rhs->self && lhs->meth == rhs->meth); + #endif } #if MICROPY_PY_FUNCTION_ATTRS diff --git a/py/objcell.c b/py/objcell.c index 95966c7917c..5c030c7405a 100644 --- a/py/objcell.c +++ b/py/objcell.c @@ -30,7 +30,7 @@ static void cell_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind) { (void)kind; mp_obj_cell_t *o = MP_OBJ_TO_PTR(o_in); - mp_printf(print, "obj); + mp_printf(print, "obj); if (o->obj == MP_OBJ_NULL) { mp_print_str(print, "(nil)"); } else { diff --git a/py/objclosure.c b/py/objclosure.c index 3ba507b9593..5235312b519 100644 --- a/py/objclosure.c +++ b/py/objclosure.c @@ -50,7 +50,8 @@ static mp_obj_t closure_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const return mp_call_function_n_kw(self->fun, self->n_closed + n_args, n_kw, args2); } else { // use heap to allocate temporary args array - mp_obj_t *args2 = m_new(mp_obj_t, n_total); + // CIRCUITPY-CHANGE + mp_obj_t *args2 = m_malloc_items(n_total); memcpy(args2, self->closed, self->n_closed * sizeof(mp_obj_t)); memcpy(args2 + self->n_closed, args, (n_args + 2 * n_kw) * sizeof(mp_obj_t)); mp_obj_t res = mp_call_function_n_kw(self->fun, self->n_closed + n_args, n_kw, args2); diff --git a/py/objcode.c b/py/objcode.c new file mode 100644 index 00000000000..09904f10f36 --- /dev/null +++ b/py/objcode.c @@ -0,0 +1,246 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2025 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 "py/objcode.h" + +#if MICROPY_PY_BUILTINS_CODE == MICROPY_PY_BUILTINS_CODE_NONE + +// Code object not implemented at this configuration level. + +#elif MICROPY_PY_BUILTINS_CODE <= MICROPY_PY_BUILTINS_CODE_BASIC + +MP_DEFINE_CONST_OBJ_TYPE( + mp_type_code, + MP_QSTR_code, + MP_TYPE_FLAG_NONE + ); + +#elif MICROPY_PY_BUILTINS_CODE <= MICROPY_PY_BUILTINS_CODE_FULL + +#include "py/profile.h" + +static void code_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind) { + (void)kind; + mp_obj_code_t *o = MP_OBJ_TO_PTR(o_in); + const mp_raw_code_t *rc = o->rc; + const mp_bytecode_prelude_t *prelude = &rc->prelude; + mp_printf(print, + "", + MP_CODE_QSTR_MAP(o->context, prelude->qstr_block_name_idx), + o, + MP_CODE_QSTR_MAP(o->context, 0), + rc->line_of_definition + ); +} + +static mp_obj_tuple_t *code_consts(const mp_module_context_t *context, const mp_raw_code_t *rc) { + mp_obj_tuple_t *consts = MP_OBJ_TO_PTR(mp_obj_new_tuple(rc->n_children + 1, NULL)); + + size_t const_no = 0; + for (size_t i = 0; i < rc->n_children; ++i) { + mp_obj_t code = mp_obj_new_code(context, rc->children[i], true); + consts->items[const_no++] = code; + } + consts->items[const_no++] = mp_const_none; + + return consts; +} + +#if !MICROPY_PREVIEW_VERSION_2 +static mp_obj_t raw_code_lnotab(const mp_raw_code_t *rc) { + // const mp_bytecode_prelude_t *prelude = &rc->prelude; + uint start = 0; + uint stop = rc->fun_data_len - start; + + uint last_lineno = mp_prof_bytecode_lineno(rc, start); + uint lasti = 0; + + const uint buffer_chunk_size = (stop - start) >> 2; // heuristic magic + uint buffer_size = buffer_chunk_size; + byte *buffer = m_new(byte, buffer_size); + uint buffer_index = 0; + + for (uint i = start; i < stop; ++i) { + uint lineno = mp_prof_bytecode_lineno(rc, i); + size_t line_diff = lineno - last_lineno; + if (line_diff > 0) { + uint instr_diff = (i - start) - lasti; + + assert(instr_diff < 256); + assert(line_diff < 256); + + if (buffer_index + 2 > buffer_size) { + buffer = m_renew(byte, buffer, buffer_size, buffer_size + buffer_chunk_size); + buffer_size = buffer_size + buffer_chunk_size; + } + last_lineno = lineno; + lasti = i - start; + buffer[buffer_index++] = instr_diff; + buffer[buffer_index++] = line_diff; + } + } + + mp_obj_t o = mp_obj_new_bytes(buffer, buffer_index); + m_del(byte, buffer, buffer_size); + return o; +} +#endif + +static mp_obj_t code_colines_iter(mp_obj_t); +static mp_obj_t code_colines_next(mp_obj_t); +typedef struct _mp_obj_colines_iter_t { + mp_obj_base_t base; + mp_fun_1_t iternext; + const mp_raw_code_t *rc; + mp_uint_t bc; + mp_uint_t source_line; + const byte *ci; +} mp_obj_colines_iter_t; + +static mp_obj_t code_colines_iter(mp_obj_t self_in) { + mp_obj_code_t *self = MP_OBJ_TO_PTR(self_in); + mp_obj_colines_iter_t *iter = mp_obj_malloc(mp_obj_colines_iter_t, &mp_type_polymorph_iter); + iter->iternext = code_colines_next; + iter->rc = self->rc; + iter->bc = 0; + iter->source_line = 1; + iter->ci = self->rc->prelude.line_info; + return MP_OBJ_FROM_PTR(iter); +} +static MP_DEFINE_CONST_FUN_OBJ_1(code_colines_obj, code_colines_iter); + +static mp_obj_t code_colines_next(mp_obj_t iter_in) { + mp_obj_colines_iter_t *iter = MP_OBJ_TO_PTR(iter_in); + const byte *ci_end = iter->rc->prelude.line_info_top; + + mp_uint_t start = iter->bc; + mp_uint_t line_no = iter->source_line; + bool another = true; + + while (another && iter->ci < ci_end) { + another = false; + mp_code_lineinfo_t decoded = mp_bytecode_decode_lineinfo(&iter->ci); + iter->bc += decoded.bc_increment; + iter->source_line += decoded.line_increment; + + if (decoded.bc_increment == 0) { + line_no = iter->source_line; + another = true; + } else if (decoded.line_increment == 0) { + another = true; + } + } + + if (another) { + mp_uint_t prelude_size = (iter->rc->prelude.opcodes - (const byte *)iter->rc->fun_data); + mp_uint_t bc_end = iter->rc->fun_data_len - prelude_size; + if (iter->bc >= bc_end) { + return MP_OBJ_STOP_ITERATION; + } else { + iter->bc = bc_end; + } + } + + mp_uint_t end = iter->bc; + mp_obj_t next[3] = {MP_OBJ_NEW_SMALL_INT(start), MP_OBJ_NEW_SMALL_INT(end), MP_OBJ_NEW_SMALL_INT(line_no)}; + + return mp_obj_new_tuple(MP_ARRAY_SIZE(next), next); +} + +static void code_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { + if (dest[0] != MP_OBJ_NULL) { + // not load attribute + return; + } + mp_obj_code_t *o = MP_OBJ_TO_PTR(self_in); + const mp_raw_code_t *rc = o->rc; + const mp_bytecode_prelude_t *prelude = &rc->prelude; + switch (attr) { + case MP_QSTR_co_code: + dest[0] = mp_obj_new_bytes( + (void *)prelude->opcodes, + rc->fun_data_len - (prelude->opcodes - (const byte *)rc->fun_data) + ); + break; + case MP_QSTR_co_consts: + dest[0] = MP_OBJ_FROM_PTR(code_consts(o->context, rc)); + break; + case MP_QSTR_co_filename: + dest[0] = MP_OBJ_NEW_QSTR(MP_CODE_QSTR_MAP(o->context, 0)); + break; + case MP_QSTR_co_firstlineno: + dest[0] = MP_OBJ_NEW_SMALL_INT(mp_prof_bytecode_lineno(rc, 0)); + break; + case MP_QSTR_co_name: + dest[0] = MP_OBJ_NEW_QSTR(MP_CODE_QSTR_MAP(o->context, prelude->qstr_block_name_idx)); + break; + case MP_QSTR_co_names: + dest[0] = MP_OBJ_FROM_PTR(o->dict_locals); + break; + #if !MICROPY_PREVIEW_VERSION_2 + case MP_QSTR_co_lnotab: + if (!o->lnotab) { + o->lnotab = raw_code_lnotab(rc); + } + dest[0] = o->lnotab; + break; + #endif + case MP_QSTR_co_lines: + dest[0] = MP_OBJ_FROM_PTR(&code_colines_obj); + dest[1] = self_in; + break; + } +} + +MP_DEFINE_CONST_OBJ_TYPE( + mp_type_code, + MP_QSTR_code, + MP_TYPE_FLAG_NONE, + print, code_print, + attr, code_attr + ); + +mp_obj_t mp_obj_new_code(const mp_module_context_t *context, const mp_raw_code_t *rc, bool result_required) { + mp_obj_code_t *o; + if (result_required) { + o = m_new_obj(mp_obj_code_t); + } else { + o = m_new_obj_maybe(mp_obj_code_t); + if (o == NULL) { + return MP_OBJ_NULL; + } + } + o->base.type = &mp_type_code; + o->context = context; + o->rc = rc; + o->dict_locals = mp_locals_get(); // this is a wrong! how to do this properly? + #if !MICROPY_PREVIEW_VERSION_2 + o->lnotab = MP_OBJ_NULL; + #endif + return MP_OBJ_FROM_PTR(o); +} + +#endif diff --git a/py/objcode.h b/py/objcode.h new file mode 100644 index 00000000000..7be15e23f52 --- /dev/null +++ b/py/objcode.h @@ -0,0 +1,100 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2025 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. + */ +#ifndef MICROPY_INCLUDED_PY_OBJCODE_H +#define MICROPY_INCLUDED_PY_OBJCODE_H + +#include "py/bc.h" + +#if MICROPY_PY_BUILTINS_CODE == MICROPY_PY_BUILTINS_CODE_NONE + +// Code object not implemented at this configuration level. + +#elif MICROPY_PY_BUILTINS_CODE <= MICROPY_PY_BUILTINS_CODE_MINIMUM + +typedef struct _mp_obj_code_t { + mp_obj_base_t base; + mp_obj_t module_fun; +} mp_obj_code_t; + +static inline mp_obj_t mp_obj_new_code(mp_obj_t module_fun) { + mp_obj_code_t *code = mp_obj_malloc(mp_obj_code_t, &mp_type_code); + code->module_fun = module_fun; + return MP_OBJ_FROM_PTR(code); +} + +#elif MICROPY_PY_BUILTINS_CODE <= MICROPY_PY_BUILTINS_CODE_BASIC + +typedef struct _mp_obj_code_t { + mp_obj_base_t base; + mp_module_constants_t constants; + const void *proto_fun; +} mp_obj_code_t; + +static inline mp_obj_t mp_obj_new_code(const mp_module_constants_t constants, const void *proto_fun) { + mp_obj_code_t *code = mp_obj_malloc(mp_obj_code_t, &mp_type_code); + code->constants = constants; + code->proto_fun = proto_fun; + return MP_OBJ_FROM_PTR(code); +} + +static inline const mp_module_constants_t *mp_code_get_constants(mp_obj_code_t *self) { + return &self->constants; +} + +static inline const void *mp_code_get_proto_fun(mp_obj_code_t *self) { + return self->proto_fun; +} + +#elif MICROPY_PY_BUILTINS_CODE <= MICROPY_PY_BUILTINS_CODE_FULL + +#include "py/emitglue.h" + +#define MP_CODE_QSTR_MAP(context, idx) ((qstr)(context->constants.qstr_table[idx])) + +typedef struct _mp_obj_code_t { + mp_obj_base_t base; + const mp_module_context_t *context; + const mp_raw_code_t *rc; + mp_obj_dict_t *dict_locals; + #if !MICROPY_PREVIEW_VERSION_2 + mp_obj_t lnotab; + #endif +} mp_obj_code_t; + +mp_obj_t mp_obj_new_code(const mp_module_context_t *context, const mp_raw_code_t *rc, bool result_required); + +static inline const mp_module_constants_t *mp_code_get_constants(mp_obj_code_t *self) { + return &self->context->constants; +} + +static inline const void *mp_code_get_proto_fun(mp_obj_code_t *self) { + // A mp_raw_code_t is always a proto_fun (but not the other way around). + return self->rc; +} + +#endif + +#endif // MICROPY_INCLUDED_PY_OBJCODE_H diff --git a/py/objcomplex.c b/py/objcomplex.c index d7287efdc13..88f4444f09e 100644 --- a/py/objcomplex.c +++ b/py/objcomplex.c @@ -49,29 +49,18 @@ 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 - char buf[16]; - #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C - const int precision = 6; - #else - const int precision = 7; - #endif - #else - char buf[32]; - const int precision = 16; - #endif - if (o->real == 0) { - mp_format_float(o->imag, buf, sizeof(buf), 'g', precision, '\0'); - mp_printf(print, "%sj", buf); + const char *suffix; + int flags = 0; + if (o->real != 0) { + mp_print_str(print, "("); + mp_print_float(print, o->real, 'g', 0, '\0', -1, MP_FLOAT_REPR_PREC); + flags = PF_FLAG_SHOW_SIGN; + suffix = "j)"; } else { - mp_format_float(o->real, buf, sizeof(buf), 'g', precision, '\0'); - mp_printf(print, "(%s", buf); - if (o->imag >= 0 || isnan(o->imag)) { - mp_print_str(print, "+"); - } - mp_format_float(o->imag, buf, sizeof(buf), 'g', precision, '\0'); - mp_printf(print, "%sj)", buf); + suffix = "j"; } + mp_print_float(print, o->imag, 'g', flags, '\0', -1, MP_FLOAT_REPR_PREC); + mp_print_str(print, suffix); } static mp_obj_t complex_make_new(const mp_obj_type_t *type_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { diff --git a/py/objdeque.c b/py/objdeque.c index 583537017fd..4e1ee82e9d4 100644 --- a/py/objdeque.c +++ b/py/objdeque.c @@ -46,6 +46,11 @@ static mp_obj_t mp_obj_deque_extend(mp_obj_t self_in, mp_obj_t arg_in); static mp_obj_t mp_obj_new_deque_it(mp_obj_t deque, mp_obj_iter_buf_t *iter_buf); #endif +// CIRCUITPY-CHANGE +static mp_obj_deque_t *native_deque(mp_obj_t self_in) { + return MP_OBJ_TO_PTR(mp_obj_cast_to_native_base(self_in, MP_OBJ_FROM_PTR(&mp_type_deque))); +} + static mp_obj_t deque_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, 2, 3, false); @@ -58,7 +63,8 @@ static mp_obj_t deque_make_new(const mp_obj_type_t *type, size_t n_args, size_t mp_obj_deque_t *o = mp_obj_malloc(mp_obj_deque_t, type); o->alloc = maxlen + 1; o->i_get = o->i_put = 0; - o->items = m_new0(mp_obj_t, o->alloc); + // CIRCUITPY-CHANGE + o->items = m_malloc_items(o->alloc); if (n_args > 2) { o->flags = mp_obj_get_int(args[2]); @@ -78,7 +84,8 @@ static size_t deque_len(mp_obj_deque_t *self) { } static mp_obj_t deque_unary_op(mp_unary_op_t op, mp_obj_t self_in) { - mp_obj_deque_t *self = MP_OBJ_TO_PTR(self_in); + // CIRCUITPY-CHANGE + mp_obj_deque_t *self = native_deque(self_in); switch (op) { case MP_UNARY_OP_BOOL: return mp_obj_new_bool(self->i_get != self->i_put); @@ -97,7 +104,8 @@ static mp_obj_t deque_unary_op(mp_unary_op_t op, mp_obj_t self_in) { } static mp_obj_t mp_obj_deque_append(mp_obj_t self_in, mp_obj_t arg) { - mp_obj_deque_t *self = MP_OBJ_TO_PTR(self_in); + // CIRCUITPY-CHANGE + mp_obj_deque_t *self = native_deque(self_in); size_t new_i_put = self->i_put + 1; if (new_i_put == self->alloc) { @@ -122,7 +130,8 @@ static mp_obj_t mp_obj_deque_append(mp_obj_t self_in, mp_obj_t arg) { static MP_DEFINE_CONST_FUN_OBJ_2(deque_append_obj, mp_obj_deque_append); static mp_obj_t mp_obj_deque_appendleft(mp_obj_t self_in, mp_obj_t arg) { - mp_obj_deque_t *self = MP_OBJ_TO_PTR(self_in); + // CIRCUITPY-CHANGE + mp_obj_deque_t *self = native_deque(self_in); size_t new_i_get = self->i_get - 1; if (self->i_get == 0) { @@ -161,7 +170,8 @@ static mp_obj_t mp_obj_deque_extend(mp_obj_t self_in, mp_obj_t arg_in) { static MP_DEFINE_CONST_FUN_OBJ_2(deque_extend_obj, mp_obj_deque_extend); static mp_obj_t deque_popleft(mp_obj_t self_in) { - mp_obj_deque_t *self = MP_OBJ_TO_PTR(self_in); + // CIRCUITPY-CHANGE + mp_obj_deque_t *self = native_deque(self_in); if (self->i_get == self->i_put) { mp_raise_msg(&mp_type_IndexError, MP_ERROR_TEXT("empty")); @@ -179,7 +189,8 @@ static mp_obj_t deque_popleft(mp_obj_t self_in) { static MP_DEFINE_CONST_FUN_OBJ_1(deque_popleft_obj, deque_popleft); static mp_obj_t deque_pop(mp_obj_t self_in) { - mp_obj_deque_t *self = MP_OBJ_TO_PTR(self_in); + // CIRCUITPY-CHANGE + mp_obj_deque_t *self = native_deque(self_in); if (self->i_get == self->i_put) { mp_raise_msg(&mp_type_IndexError, MP_ERROR_TEXT("empty")); @@ -204,11 +215,12 @@ static mp_obj_t deque_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { // delete not supported, fall back to mp_obj_subscr() error message return MP_OBJ_NULL; } - mp_obj_deque_t *self = MP_OBJ_TO_PTR(self_in); + // CIRCUITPY-CHANGE + mp_obj_deque_t *self = native_deque(self_in); size_t offset = mp_get_index(self->base.type, deque_len(self), index, false); size_t index_val = self->i_get + offset; - if (index_val > self->alloc) { + if (index_val >= self->alloc) { index_val -= self->alloc; } @@ -225,7 +237,8 @@ static mp_obj_t deque_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { #if 0 static mp_obj_t deque_clear(mp_obj_t self_in) { - mp_obj_deque_t *self = MP_OBJ_TO_PTR(self_in); + // CIRCUITPY-CHANGE + mp_obj_deque_t *self = native_deque(self_in); self->i_get = self->i_put = 0; mp_seq_clear(self->items, 0, self->alloc, sizeof(*self->items)); return mp_const_none; @@ -263,7 +276,7 @@ static MP_DEFINE_CONST_DICT(deque_locals_dict, deque_locals_dict_table); MP_DEFINE_CONST_OBJ_TYPE( mp_type_deque, MP_QSTR_deque, - MP_TYPE_FLAG_ITER_IS_GETITER, + DEQUE_TYPE_FLAGS, make_new, deque_make_new, unary_op, deque_unary_op, DEQUE_TYPE_SUBSCR @@ -285,7 +298,8 @@ typedef struct _mp_obj_deque_it_t { static mp_obj_t deque_it_iternext(mp_obj_t self_in) { mp_obj_deque_it_t *self = MP_OBJ_TO_PTR(self_in); - mp_obj_deque_t *deque = MP_OBJ_TO_PTR(self->deque); + // CIRCUITPY-CHANGE + mp_obj_deque_t *deque = native_deque(self->deque); if (self->cur != deque->i_put) { mp_obj_t o_out = deque->items[self->cur]; if (++self->cur == deque->alloc) { @@ -297,9 +311,10 @@ static mp_obj_t deque_it_iternext(mp_obj_t self_in) { } } -static mp_obj_t mp_obj_new_deque_it(mp_obj_t deque, mp_obj_iter_buf_t *iter_buf) { - mp_obj_deque_t *deque_ = MP_OBJ_TO_PTR(deque); - size_t i_get = deque_->i_get; +static mp_obj_t mp_obj_new_deque_it(mp_obj_t deque_in, mp_obj_iter_buf_t *iter_buf) { + // CIRCUITPY-CHANGE + mp_obj_deque_t *deque = native_deque(deque_in); + size_t i_get = deque->i_get; assert(sizeof(mp_obj_deque_it_t) <= sizeof(mp_obj_iter_buf_t)); mp_obj_deque_it_t *o = (mp_obj_deque_it_t *)iter_buf; o->base.type = &mp_type_polymorph_iter; diff --git a/py/objdict.c b/py/objdict.c index 7094a1c1f99..d459d1ae486 100644 --- a/py/objdict.c +++ b/py/objdict.c @@ -101,7 +101,7 @@ static void dict_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_ #endif } if (MICROPY_PY_COLLECTIONS_ORDEREDDICT && self->base.type != &mp_type_dict && kind != PRINT_JSON) { - mp_printf(print, "%q(", self->base.type->name); + mp_printf(print, "%q(", (qstr)self->base.type->name); } mp_print_str(print, "{"); size_t cur = 0; @@ -616,7 +616,8 @@ static mp_obj_t dict_view_unary_op(mp_unary_op_t op, mp_obj_t o_in) { if (op == MP_UNARY_OP_HASH && o->kind == MP_DICT_VIEW_VALUES) { return MP_OBJ_NEW_SMALL_INT((mp_uint_t)o_in); } - return MP_OBJ_NULL; + // delegate all other ops to dict unary op handler + return dict_unary_op(op, o->dict); } static mp_obj_t dict_view_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) { @@ -747,7 +748,8 @@ void mp_obj_dict_init(mp_obj_dict_t *dict, size_t n_args) { } mp_obj_t mp_obj_new_dict(size_t n_args) { - mp_obj_dict_t *o = m_new_obj(mp_obj_dict_t); + // CIRCUITPY-CHANGE: Use mp_obj_malloc because it is a Python object + mp_obj_dict_t *o = mp_obj_malloc(mp_obj_dict_t, &mp_type_dict); mp_obj_dict_init(o, n_args); return MP_OBJ_FROM_PTR(o); } diff --git a/py/objexcept.c b/py/objexcept.c index 70fdc15df4e..6efb0f50672 100644 --- a/py/objexcept.c +++ b/py/objexcept.c @@ -31,8 +31,6 @@ #include #include "py/objlist.h" -// CIRCUITPY-CHANGE -#include "py/objnamedtuple.h" #include "py/objstr.h" #include "py/objtuple.h" #include "py/objtype.h" @@ -168,7 +166,7 @@ void mp_obj_exception_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kin mp_print_kind_t k = kind & ~PRINT_EXC_SUBCLASS; bool is_subclass = kind & PRINT_EXC_SUBCLASS; if (!is_subclass && (k == PRINT_REPR || k == PRINT_EXC)) { - mp_print_str(print, qstr_str(o->base.type->name)); + mp_print_str(print, mp_obj_get_type_str(o_in)); } if (k == PRINT_EXC) { @@ -612,7 +610,14 @@ bool mp_obj_is_exception_type(mp_obj_t self_in) { // return true if the given object is an instance of an exception type bool mp_obj_is_exception_instance(mp_obj_t self_in) { - return mp_obj_is_exception_type(MP_OBJ_FROM_PTR(mp_obj_get_type(self_in))); + if (mp_obj_is_native_exception_instance(self_in)) { + return true; + } + if (!mp_obj_is_exception_type(MP_OBJ_FROM_PTR(mp_obj_get_type(self_in)))) { + return false; + } + mp_obj_instance_t *self = MP_OBJ_TO_PTR(self_in); + return self->subobj[0] != MP_OBJ_FROM_PTR((void *)&mp_native_base_init_wrapper_obj); } // Return true if exception (type or instance) is a subclass of given @@ -729,126 +734,3 @@ void mp_obj_exception_get_traceback(mp_obj_t self_in, size_t *n, size_t **values *values = self->traceback->data; } } - -// CIRCUITPY-CHANGE: here until end -#if MICROPY_PY_SYS_EXC_INFO -static const mp_obj_namedtuple_type_t code_type_obj = { - NAMEDTUPLE_TYPE_BASE_AND_SLOTS(MP_QSTR_code), - .n_fields = 15, - .fields = { - MP_QSTR_co_argcount, - MP_QSTR_co_kwonlyargcount, - MP_QSTR_co_nlocals, - MP_QSTR_co_stacksize, - MP_QSTR_co_flags, - MP_QSTR_co_code, - MP_QSTR_co_consts, - MP_QSTR_co_names, - MP_QSTR_co_varnames, - MP_QSTR_co_freevars, - MP_QSTR_co_cellvars, - MP_QSTR_co_filename, - MP_QSTR_co_name, - MP_QSTR_co_firstlineno, - MP_QSTR_co_lnotab, - }, -}; - -static mp_obj_t code_make_new(qstr file, qstr block) { - mp_obj_t elems[15] = { - mp_obj_new_int(0), // co_argcount - mp_obj_new_int(0), // co_kwonlyargcount - mp_obj_new_int(0), // co_nlocals - mp_obj_new_int(0), // co_stacksize - mp_obj_new_int(0), // co_flags - mp_obj_new_bytearray(0, NULL), // co_code - mp_obj_new_tuple(0, NULL), // co_consts - mp_obj_new_tuple(0, NULL), // co_names - mp_obj_new_tuple(0, NULL), // co_varnames - mp_obj_new_tuple(0, NULL), // co_freevars - mp_obj_new_tuple(0, NULL), // co_cellvars - MP_OBJ_NEW_QSTR(file), // co_filename - MP_OBJ_NEW_QSTR(block), // co_name - mp_obj_new_int(1), // co_firstlineno - mp_obj_new_bytearray(0, NULL), // co_lnotab - }; - - return namedtuple_make_new((const mp_obj_type_t *)&code_type_obj, 15, 0, elems); -} - -static const mp_obj_namedtuple_type_t frame_type_obj = { - NAMEDTUPLE_TYPE_BASE_AND_SLOTS(MP_QSTR_frame), - .n_fields = 8, - .fields = { - MP_QSTR_f_back, - MP_QSTR_f_builtins, - MP_QSTR_f_code, - MP_QSTR_f_globals, - MP_QSTR_f_lasti, - MP_QSTR_f_lineno, - MP_QSTR_f_locals, - MP_QSTR_f_trace, - }, -}; - -static mp_obj_t frame_make_new(mp_obj_t f_code, int f_lineno) { - mp_obj_t elems[8] = { - mp_const_none, // f_back - mp_obj_new_dict(0), // f_builtins - f_code, // f_code - mp_obj_new_dict(0), // f_globals - mp_obj_new_int(0), // f_lasti - mp_obj_new_int(f_lineno), // f_lineno - mp_obj_new_dict(0), // f_locals - mp_const_none, // f_trace - }; - - return namedtuple_make_new((const mp_obj_type_t *)&frame_type_obj, 8, 0, elems); -} - -static const mp_obj_namedtuple_type_t traceback_type_obj = { - NAMEDTUPLE_TYPE_BASE_AND_SLOTS(MP_QSTR_traceback), - .n_fields = 4, - .fields = { - MP_QSTR_tb_frame, - MP_QSTR_tb_lasti, - MP_QSTR_tb_lineno, - MP_QSTR_tb_next, - }, -}; - -static mp_obj_t traceback_from_values(size_t *values, mp_obj_t tb_next) { - int lineno = values[1]; - - mp_obj_t elems[4] = { - frame_make_new(code_make_new(values[0], values[2]), lineno), - mp_obj_new_int(0), - mp_obj_new_int(lineno), - tb_next, - }; - - return namedtuple_make_new((const mp_obj_type_t *)&traceback_type_obj, 4, 0, elems); -}; - -mp_obj_t mp_obj_exception_get_traceback_obj(mp_obj_t self_in) { - mp_obj_exception_t *self = MP_OBJ_TO_PTR(self_in); - - if (!mp_obj_is_exception_instance(self)) { - return mp_const_none; - } - - size_t n, *values; - mp_obj_exception_get_traceback(self, &n, &values); - if (n == 0) { - return mp_const_none; - } - - mp_obj_t tb_next = mp_const_none; - - for (size_t i = 0; i < n; i += 3) { - tb_next = traceback_from_values(&values[i], tb_next); - } - - return tb_next; -} -#endif diff --git a/py/objfloat.c b/py/objfloat.c index 6f248cdadfc..ecc0f61a6ab 100644 --- a/py/objfloat.c +++ b/py/objfloat.c @@ -34,6 +34,11 @@ #if MICROPY_PY_BUILTINS_FLOAT +// Workaround a bug in Windows SDK version 10.0.26100.0, where NAN is no longer constant. +#if defined(_MSC_VER) && !defined(_UCRT_NOISY_NAN) +#define _UCRT_NOISY_NAN +#endif + #include #include "py/formatfloat.h" @@ -109,23 +114,7 @@ mp_int_t mp_float_hash(mp_float_t src) { 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 - char buf[16]; - #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_C - const int precision = 6; - #else - const int precision = 7; - #endif - #else - char buf[32]; - const int precision = 16; - #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) { - // Python floats always have decimal point (unless inf or nan) - mp_print_str(print, ".0"); - } + mp_print_float(print, o_val, 'g', PF_FLAG_ALWAYS_DECIMAL, '\0', -1, MP_FLOAT_REPR_PREC); } static mp_obj_t float_make_new(const mp_obj_type_t *type_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { @@ -198,9 +187,8 @@ MP_DEFINE_CONST_OBJ_TYPE( #if MICROPY_OBJ_REPR != MICROPY_OBJ_REPR_C && MICROPY_OBJ_REPR != MICROPY_OBJ_REPR_D mp_obj_t mp_obj_new_float(mp_float_t value) { - // Don't use mp_obj_malloc here to avoid extra function call overhead. - mp_obj_float_t *o = m_new_obj(mp_obj_float_t); - o->base.type = &mp_type_float; + // CIRCUITPY-CHANGE: Use mp_obj_malloc because it is a Python object + mp_obj_float_t *o = mp_obj_malloc(mp_obj_float_t, &mp_type_float); o->value = value; return MP_OBJ_FROM_PTR(o); } @@ -318,6 +306,10 @@ mp_obj_t mp_obj_float_binary_op(mp_binary_op_t op, mp_float_t lhs_val, mp_obj_t lhs_val = MICROPY_FLOAT_CONST(1.0); break; } + if (isnan(rhs_val)) { + lhs_val = rhs_val; + break; + } #endif lhs_val = MICROPY_FLOAT_C_FUN(pow)(lhs_val, rhs_val); break; diff --git a/py/objfun.c b/py/objfun.c index a552c5531b0..6392a6c8730 100644 --- a/py/objfun.c +++ b/py/objfun.c @@ -28,11 +28,13 @@ #include #include +#include "py/emitglue.h" +#include "py/objcode.h" #include "py/objtuple.h" #include "py/objfun.h" #include "py/runtime.h" #include "py/bc.h" -#include "py/stackctrl.h" +#include "py/cstack.h" #if MICROPY_DEBUG_VERBOSE // print debugging info #define DEBUG_PRINT (1) @@ -110,7 +112,9 @@ static mp_obj_t fun_builtin_var_call(mp_obj_t self_in, size_t n_args, size_t n_k if (self->sig & 1) { // function allows keywords - // we create a map directly from the given args array + // we create a map directly from the given args array; self->fun.kw does still + // expect args to have both positional and keyword arguments, ordered as: + // arg0 arg1 ... arg key0 value0 key1 value1 ... key value mp_map_t kw_args; mp_map_init_fixed_table(&kw_args, n_kw, args + n_args); @@ -131,11 +135,10 @@ MP_DEFINE_CONST_OBJ_TYPE( /******************************************************************************/ /* byte code functions */ -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); +qstr mp_obj_fun_bc_get_name(const mp_obj_fun_bc_t *fun) { const byte *bc = fun->bytecode; - #if MICROPY_EMIT_NATIVE + #if MICROPY_ENABLE_NATIVE_CODE if (fun->base.type == &mp_type_fun_native || fun->base.type == &mp_type_native_gen_wrap) { bc = mp_obj_fun_native_get_prelude_ptr(fun); } @@ -152,11 +155,36 @@ qstr mp_obj_fun_get_name(mp_const_obj_t fun_in) { return name; } +#if MICROPY_PY_FUNCTION_ATTRS_CODE +static mp_obj_t fun_bc_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { + (void)type; + mp_arg_check_num(n_args, n_kw, 2, 2, false); + + if (!mp_obj_is_type(args[0], &mp_type_code)) { + mp_raise_TypeError(NULL); + } + if (!mp_obj_is_type(args[1], &mp_type_dict)) { + mp_raise_TypeError(NULL); + } + + mp_obj_code_t *code = MP_OBJ_TO_PTR(args[0]); + mp_obj_t globals = args[1]; + + mp_module_context_t *module_context = m_new_obj(mp_module_context_t); + module_context->module.base.type = &mp_type_module; + module_context->module.globals = MP_OBJ_TO_PTR(globals); + module_context->constants = *mp_code_get_constants(code); + + return mp_make_function_from_proto_fun(mp_code_get_proto_fun(code), module_context, NULL); +} +#endif + #if MICROPY_CPYTHON_COMPAT static void fun_bc_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind) { (void)kind; mp_obj_fun_bc_t *o = MP_OBJ_TO_PTR(o_in); - mp_printf(print, "", mp_obj_fun_get_name(o_in), o); + // CIRCUITPY-CHANGE: %p already prints "0x", so don't include it explicitly. + mp_printf(print, "", mp_obj_fun_bc_get_name(o), o); } #endif @@ -197,7 +225,7 @@ static void dump_args(const mp_obj_t *a, size_t sz) { #if MICROPY_STACKLESS mp_code_state_t *mp_obj_fun_bc_prepare_codestate(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { - MP_STACK_CHECK(); + mp_cstack_check(); mp_obj_fun_bc_t *self = MP_OBJ_TO_PTR(self_in); size_t n_state, state_size; @@ -229,7 +257,7 @@ mp_code_state_t *mp_obj_fun_bc_prepare_codestate(mp_obj_t self_in, size_t n_args // CIRCUITPY-CHANGE: PLACE_IN_ITCM static mp_obj_t PLACE_IN_ITCM(fun_bc_call)(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { - MP_STACK_CHECK(); + mp_cstack_check(); DEBUG_printf("Input n_args: " UINT_FMT ", n_kw: " UINT_FMT "\n", n_args, n_kw); DEBUG_printf("Input pos args: "); @@ -335,16 +363,48 @@ void mp_obj_fun_bc_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { // not load attribute return; } + const mp_obj_fun_bc_t *self = MP_OBJ_TO_PTR(self_in); if (attr == MP_QSTR___name__) { - dest[0] = MP_OBJ_NEW_QSTR(mp_obj_fun_get_name(self_in)); + dest[0] = MP_OBJ_NEW_QSTR(mp_obj_fun_bc_get_name(self)); } if (attr == MP_QSTR___globals__) { - mp_obj_fun_bc_t *self = MP_OBJ_TO_PTR(self_in); dest[0] = MP_OBJ_FROM_PTR(self->context->module.globals); } + #if MICROPY_PY_FUNCTION_ATTRS_CODE + if (attr == MP_QSTR___code__) { + if (self->base.type == &mp_type_fun_bc + || self->base.type == &mp_type_gen_wrap) { + #if MICROPY_PY_BUILTINS_CODE <= MICROPY_PY_BUILTINS_CODE_BASIC + #if MICROPY_PERSISTENT_CODE_SAVE + #error "MICROPY_PERSISTENT_CODE_SAVE can't be enabled at this level of MICROPY_PY_BUILTINS_CODE" + #endif + mp_proto_fun_t proto_fun; + if (self->child_table != NULL) { + mp_raw_code_truncated_t *rc = m_new0(mp_raw_code_truncated_t, 1); + rc->kind = MP_CODE_BYTECODE; + rc->is_generator = self->base.type == &mp_type_gen_wrap; + rc->fun_data = self->bytecode; + rc->children = (mp_raw_code_t **)self->child_table; + proto_fun = rc; + } else { + proto_fun = self->bytecode; + } + dest[0] = mp_obj_new_code(self->context->constants, proto_fun); + #else + dest[0] = mp_obj_new_code(self->context, self->rc, true); + #endif + } + } + #endif } #endif +#if MICROPY_PY_FUNCTION_ATTRS_CODE +#define FUN_BC_MAKE_NEW make_new, fun_bc_make_new, +#else +#define FUN_BC_MAKE_NEW +#endif + #if MICROPY_CPYTHON_COMPAT #define FUN_BC_TYPE_PRINT print, fun_bc_print, #else @@ -361,6 +421,7 @@ MP_DEFINE_CONST_OBJ_TYPE( mp_type_fun_bc, MP_QSTR_function, MP_TYPE_FLAG_BINDS_SELF, + FUN_BC_MAKE_NEW FUN_BC_TYPE_PRINT FUN_BC_TYPE_ATTR call, fun_bc_call @@ -398,11 +459,11 @@ mp_obj_t mp_obj_new_fun_bc(const mp_obj_t *def_args, const byte *code, const mp_ /******************************************************************************/ /* native functions */ -#if MICROPY_EMIT_NATIVE +#if MICROPY_ENABLE_NATIVE_CODE // CIRCUITPY-CHANGE: PLACE_IN_ITCM static mp_obj_t PLACE_IN_ITCM(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_cstack_check(); mp_obj_fun_bc_t *self = MP_OBJ_TO_PTR(self_in); mp_call_fun_t fun = mp_obj_fun_native_get_function_start(self); return fun(self_in, n_args, n_kw, args); @@ -428,15 +489,11 @@ MP_DEFINE_CONST_OBJ_TYPE( call, fun_native_call ); -#endif // MICROPY_EMIT_NATIVE - /******************************************************************************/ /* viper functions */ -#if MICROPY_EMIT_NATIVE - 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_STACK_CHECK(); + mp_cstack_check(); mp_obj_fun_bc_t *self = MP_OBJ_TO_PTR(self_in); mp_call_fun_t fun = MICROPY_MAKE_POINTER_CALLABLE((void *)self->bytecode); return fun(self_in, n_args, n_kw, args); @@ -449,7 +506,7 @@ MP_DEFINE_CONST_OBJ_TYPE( call, fun_viper_call ); -#endif // MICROPY_EMIT_NATIVE +#endif // MICROPY_ENABLE_NATIVE_CODE /******************************************************************************/ /* inline assembler functions */ diff --git a/py/objfun.h b/py/objfun.h index 4059343983c..0fcc25ff09c 100644 --- a/py/objfun.h +++ b/py/objfun.h @@ -51,9 +51,10 @@ typedef struct _mp_obj_fun_asm_t { } mp_obj_fun_asm_t; mp_obj_t mp_obj_new_fun_bc(const mp_obj_t *def_args, const byte *code, const mp_module_context_t *cm, struct _mp_raw_code_t *const *raw_code_table); +qstr mp_obj_fun_bc_get_name(const mp_obj_fun_bc_t *fun); void mp_obj_fun_bc_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest); -#if MICROPY_EMIT_NATIVE +#if MICROPY_ENABLE_NATIVE_CODE static inline mp_obj_t mp_obj_new_fun_native(const mp_obj_t *def_args, const void *fun_data, const mp_module_context_t *mc, struct _mp_raw_code_t *const *child_table) { mp_obj_fun_bc_t *o = (mp_obj_fun_bc_t *)MP_OBJ_TO_PTR(mp_obj_new_fun_bc(def_args, (const byte *)fun_data, mc, child_table)); diff --git a/py/objgenerator.c b/py/objgenerator.c index fa59313998f..83cf6715bbc 100644 --- a/py/objgenerator.c +++ b/py/objgenerator.c @@ -33,7 +33,7 @@ #include "py/objstr.h" #include "py/objgenerator.h" #include "py/objfun.h" -#include "py/stackctrl.h" +#include "py/cstack.h" // Instance of GeneratorExit exception - needed by generator.close() // CIRCUITPY-CHANGE: https://github.com/adafruit/circuitpython/pull/7069 fix @@ -114,7 +114,7 @@ MP_DEFINE_CONST_OBJ_TYPE( /******************************************************************************/ // native generator wrapper -#if MICROPY_EMIT_NATIVE +#if MICROPY_ENABLE_NATIVE_CODE // Based on mp_obj_gen_instance_t. typedef struct _mp_obj_gen_instance_native_t { @@ -184,7 +184,7 @@ MP_DEFINE_CONST_OBJ_TYPE( ); #endif -#endif // MICROPY_EMIT_NATIVE +#endif // MICROPY_ENABLE_NATIVE_CODE /******************************************************************************/ /* generator instance */ @@ -192,7 +192,7 @@ MP_DEFINE_CONST_OBJ_TYPE( 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); - mp_printf(print, "", mp_obj_fun_get_name(MP_OBJ_FROM_PTR(self->code_state.fun_bc)), self); + mp_printf(print, "", mp_obj_fun_bc_get_name(self->code_state.fun_bc), self); } // CIRCUITPY-CHANGE @@ -200,12 +200,12 @@ static void gen_instance_print(const mp_print_t *print, mp_obj_t self_in, mp_pri static void coro_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); - mp_printf(print, "", mp_obj_fun_get_name(MP_OBJ_FROM_PTR(self->code_state.fun_bc)), self); + mp_printf(print, "", mp_obj_fun_bc_get_name(self->code_state.fun_bc), self); } #endif mp_vm_return_kind_t mp_obj_gen_resume(mp_obj_t self_in, mp_obj_t send_value, mp_obj_t throw_value, mp_obj_t *ret_val) { - MP_STACK_CHECK(); + mp_cstack_check(); // CIRCUITPY-CHANGE // note that self may have as its type either gen or coro, // both of which are stored as an mp_obj_gen_instance_t . @@ -237,7 +237,7 @@ mp_vm_return_kind_t mp_obj_gen_resume(mp_obj_t self_in, mp_obj_t send_value, mp_ // If the generator is started, allow sending a value. void *state_start = self->code_state.state - 1; - #if MICROPY_EMIT_NATIVE + #if MICROPY_ENABLE_NATIVE_CODE if (self->code_state.exc_sp_idx == MP_CODE_STATE_EXC_SP_IDX_SENTINEL) { state_start = ((mp_obj_gen_instance_native_t *)self)->code_state.state - 1; } @@ -259,7 +259,7 @@ mp_vm_return_kind_t mp_obj_gen_resume(mp_obj_t self_in, mp_obj_t send_value, mp_ mp_vm_return_kind_t ret_kind; - #if MICROPY_EMIT_NATIVE + #if MICROPY_ENABLE_NATIVE_CODE if (self->code_state.exc_sp_idx == MP_CODE_STATE_EXC_SP_IDX_SENTINEL) { // A native generator. typedef uintptr_t (*mp_fun_native_gen_t)(void *, mp_obj_t); @@ -297,7 +297,7 @@ mp_vm_return_kind_t mp_obj_gen_resume(mp_obj_t self_in, mp_obj_t send_value, mp_ case MP_VM_RETURN_EXCEPTION: { self->code_state.ip = 0; - #if MICROPY_EMIT_NATIVE + #if MICROPY_ENABLE_NATIVE_CODE if (self->code_state.exc_sp_idx == MP_CODE_STATE_EXC_SP_IDX_SENTINEL) { *ret_val = ((mp_obj_gen_instance_native_t *)self)->code_state.state[0]; } else diff --git a/py/objint.c b/py/objint.c index cc7a7745176..e8f7f51052a 100644 --- a/py/objint.c +++ b/py/objint.c @@ -30,7 +30,7 @@ #include "py/parsenum.h" #include "py/smallint.h" -#include "py/objint.h" +#include "py/objint_impl.h" #include "py/objstr.h" #include "py/runtime.h" #include "py/binary.h" @@ -55,7 +55,7 @@ static mp_obj_t mp_obj_int_make_new(const mp_obj_type_t *type_in, size_t n_args, return o; } else if (mp_get_buffer(args[0], &bufinfo, MP_BUFFER_READ)) { // a textual representation, parse it - return mp_parse_num_integer(bufinfo.buf, bufinfo.len, 0, NULL); + return mp_parse_num_integer(bufinfo.buf, bufinfo.len, 10, NULL); #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])); @@ -99,8 +99,8 @@ static mp_fp_as_int_class_t mp_classify_fp_as_int(mp_float_t val) { #elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE e = u.i[MP_ENDIANNESS_LITTLE]; #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) + #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 @@ -117,9 +117,15 @@ static mp_fp_as_int_class_t mp_classify_fp_as_int(mp_float_t val) { } // 8 * sizeof(uintptr_t) counts the number of bits for a small int // TODO provide a way to configure this properly + #if MICROPY_OBJ_REPR == MICROPY_OBJ_REPR_B + if (e <= ((8 * sizeof(uintptr_t) + MP_FLOAT_EXP_BIAS - 4) << MP_FLOAT_EXP_SHIFT_I32)) { + return MP_FP_CLASS_FIT_SMALLINT; + } + #else if (e <= ((8 * sizeof(uintptr_t) + MP_FLOAT_EXP_BIAS - 3) << MP_FLOAT_EXP_SHIFT_I32)) { return MP_FP_CLASS_FIT_SMALLINT; } + #endif #if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_LONGLONG if (e <= (((sizeof(long long) * MP_BITS_PER_BYTE) + MP_FLOAT_EXP_BIAS - 2) << MP_FLOAT_EXP_SHIFT_I32)) { return MP_FP_CLASS_FIT_LONGINT; @@ -201,17 +207,17 @@ static const uint8_t log_base2_floor[] = { 3, 3, 3, 3, 3, 3, 3, 4, /* if needed, these are the values for higher bases - 4, 4, 4, 4, - 4, 4, 4, 4, - 4, 4, 4, 4, - 4, 4, 4, 5 + 4, 4, 4, 4, + 4, 4, 4, 4, + 4, 4, 4, 4, + 4, 4, 4, 5 */ }; size_t mp_int_format_size(size_t num_bits, int base, const char *prefix, char comma) { assert(2 <= base && base <= 16); size_t num_digits = num_bits / log_base2_floor[base - 1] + 1; - size_t num_commas = comma ? num_digits / 3 : 0; + size_t num_commas = comma ? (base == 10 ? num_digits / 3 : num_digits / 4): 0; size_t prefix_len = prefix ? strlen(prefix) : 0; return num_digits + num_commas + prefix_len + 2; // +1 for sign, +1 for null byte } @@ -249,10 +255,11 @@ char *mp_obj_int_formatted(char **buf, size_t *buf_size, size_t *fmt_size, mp_co char sign = '\0'; if (num < 0) { - num = -num; + num = -(fmt_uint_t)num; sign = '-'; } + int n_comma = (base == 10) ? 3 : 4; size_t needed_size = mp_int_format_size(sizeof(fmt_int_t) * 8, base, prefix, comma); if (needed_size > *buf_size) { *buf = m_new(char, needed_size); @@ -277,7 +284,7 @@ char *mp_obj_int_formatted(char **buf, size_t *buf_size, size_t *fmt_size, mp_co c += '0'; } *(--b) = c; - if (comma && num != 0 && b > str && (last_comma - b) == 3) { + if (comma && num != 0 && b > str && (last_comma - b) == n_comma) { *(--b) = comma; last_comma = b; } @@ -302,74 +309,9 @@ char *mp_obj_int_formatted(char **buf, size_t *buf_size, size_t *fmt_size, mp_co return b; } -// CIRCUITPY-CHANGE: more thorough checking -#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) { - 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)); - - if (mp_binary_op(MP_BINARY_OP_LESS, self_in, edge) == mp_const_true) { - // and >= -2**(bits - 1) - edge = mp_unary_op(MP_UNARY_OP_NEGATIVE, edge); - if (mp_binary_op(MP_BINARY_OP_MORE_EQUAL, self_in, edge) == mp_const_true) { - return; - } - } - } else { - // self must be >= 0 - 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)); - - if (mp_binary_op(MP_BINARY_OP_LESS, self_in, edge) == mp_const_true) { - return; - } - } - } - - mp_raise_OverflowError_varg(MP_ERROR_TEXT("value must fit in %d byte(s)"), nbytes); -} - -#endif // MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE - +// CIRCUITPY-CHANGE: also called from py/binary.c, so not static here. void mp_small_int_buffer_overflow_check(mp_int_t val, size_t nbytes, bool is_signed) { - // Fast path for zero. - if (val == 0) { - return; - } - - // Trying to store negative values in unsigned bytes falls through to failure. - if (is_signed || val >= 0) { - - if (nbytes >= sizeof(val)) { - // All non-negative N bit signed integers fit in an unsigned N bit integer. - // This case prevents shifting too far below. - return; - } - - if (is_signed) { - mp_int_t edge = ((mp_int_t)1 << (nbytes * 8 - 1)); - if (-edge <= val && val < edge) { - return; - } - // Out of range, fall through to failure. - } else { - // Unsigned. We already know val >= 0. - mp_int_t edge = ((mp_int_t)1 << (nbytes * 8)); - if (val < edge) { - return; - } - } - // Fall through to failure. - } - - mp_raise_OverflowError_varg(MP_ERROR_TEXT("value must fit in %d byte(s)"), nbytes); + mp_obj_small_int_buffer_overflow_check(val, nbytes, is_signed); } #if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_NONE @@ -440,6 +382,10 @@ mp_int_t mp_obj_int_get_checked(mp_const_obj_t self_in) { return MP_OBJ_SMALL_INT_VALUE(self_in); } +void mp_obj_int_to_bytes(mp_obj_t self_in, size_t buf_len, byte *buf, bool big_endian, bool is_signed, bool overflow_check) { + mp_obj_small_int_to_bytes(MP_OBJ_SMALL_INT_VALUE(self_in), buf_len, buf, big_endian, is_signed, overflow_check); +} + #endif // MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_NONE // This dispatcher function is expected to be independent of the implementation of long int @@ -449,7 +395,7 @@ mp_obj_t mp_obj_int_binary_op_extra_cases(mp_binary_op_t op, mp_obj_t lhs_in, mp // false acts as 0 return mp_binary_op(op, lhs_in, MP_OBJ_NEW_SMALL_INT(0)); } else if (rhs_in == mp_const_true) { - // true acts as 0 + // true acts as 1 return mp_binary_op(op, lhs_in, MP_OBJ_NEW_SMALL_INT(1)); } else if (op == MP_BINARY_OP_MULTIPLY) { if (mp_obj_is_str_or_bytes(rhs_in) || mp_obj_is_type(rhs_in, &mp_type_tuple) || mp_obj_is_type(rhs_in, &mp_type_list)) { @@ -532,54 +478,35 @@ static mp_obj_t int_from_bytes(size_t n_args, const mp_obj_t *pos_args, mp_map_t static MP_DEFINE_CONST_FUN_OBJ_KW(int_from_bytes_fun_obj, 2, int_from_bytes); static MP_DEFINE_CONST_CLASSMETHOD_OBJ(int_from_bytes_obj, MP_ROM_PTR(&int_from_bytes_fun_obj)); -// CIRCUITPY-CHANGE: supports signed static mp_obj_t int_to_bytes(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { enum { ARG_length, ARG_byteorder, ARG_signed }; static const mp_arg_t allowed_args[] = { - { MP_QSTR_length, MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = 0} }, - // CIRCUITPY-CHANGE: not required and given a default value. - { MP_QSTR_byteorder, MP_ARG_OBJ, {.u_obj = MP_OBJ_NEW_QSTR(MP_QSTR_big)} }, + { MP_QSTR_length, MP_ARG_INT, { .u_int = 1 } }, + { MP_QSTR_byteorder, MP_ARG_OBJ, { .u_rom_obj = MP_ROM_QSTR(MP_QSTR_big) } }, { MP_QSTR_signed, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, }; 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_int_t len = args[ARG_length].u_int; - if (len < 0) { + mp_obj_t self = pos_args[0]; + + mp_int_t dlen = args[ARG_length].u_int; + if (dlen < 0) { mp_raise_ValueError(NULL); } - mp_obj_t self = pos_args[0]; - bool big_endian = args[ARG_byteorder].u_obj != MP_OBJ_NEW_QSTR(MP_QSTR_little); - bool signed_ = args[ARG_signed].u_bool; - vstr_t vstr; - vstr_init_len(&vstr, len); + vstr_init_len(&vstr, dlen); byte *data = (byte *)vstr.buf; - memset(data, 0, len); - #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE - if (!mp_obj_is_small_int(self)) { - mp_obj_int_buffer_overflow_check(self, len, signed_); - mp_obj_int_to_bytes_impl(self, big_endian, len, data); - } else - #endif - { - mp_int_t val = MP_OBJ_SMALL_INT_VALUE(self); - // Small int checking is separate, to be fast. - mp_small_int_buffer_overflow_check(val, len, signed_); - size_t l = MIN((size_t)len, sizeof(val)); - if (val < 0) { - // Sign extend negative numbers. - memset(data, -1, len); - } - mp_binary_set_int(l, big_endian, data + (big_endian ? (len - l) : 0), val); - } + bool big_endian = args[ARG_byteorder].u_obj != MP_OBJ_NEW_QSTR(MP_QSTR_little); + bool signed_ = args[ARG_signed].u_bool; + + mp_obj_int_to_bytes(self, dlen, data, big_endian, signed_, true); return mp_obj_new_bytes_from_vstr(&vstr); } -// CIRCUITPY-CHANGE: only two required args. -static MP_DEFINE_CONST_FUN_OBJ_KW(int_to_bytes_obj, 2, int_to_bytes); +static MP_DEFINE_CONST_FUN_OBJ_KW(int_to_bytes_obj, 1, int_to_bytes); static const mp_rom_map_elem_t int_locals_dict_table[] = { // CIRCUITPY-CHANGE diff --git a/py/objint.h b/py/objint.h index b081d659051..94c53190d8b 100644 --- a/py/objint.h +++ b/py/objint.h @@ -53,18 +53,17 @@ char *mp_obj_int_formatted(char **buf, size_t *buf_size, size_t *fmt_size, mp_co 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); -// CIRCUITPY-CHANGE -#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 - -void mp_small_int_buffer_overflow_check(mp_int_t val, size_t nbytes, bool is_signed); mp_int_t mp_obj_int_hash(mp_obj_t self_in); // CIRCUITPY-CHANGE mp_obj_t mp_obj_int_bit_length_impl(mp_obj_t self_in); mp_obj_t mp_obj_int_from_bytes_impl(bool big_endian, size_t len, const byte *buf); -void mp_obj_int_to_bytes_impl(mp_obj_t self_in, bool big_endian, size_t len, byte *buf); +// Write an integer to a byte sequence. +// If overflow_check is true, raises OverflowError if 'self_in' doesn't fit. If false, truncate to fit. +void mp_obj_int_to_bytes(mp_obj_t self_in, size_t buf_len, byte *buf, bool big_endian, bool is_signed, bool overflow_check); + +// CIRCUITPY-CHANGE: raises OverflowError if val does not fit in nbytes. +void mp_small_int_buffer_overflow_check(mp_int_t val, size_t nbytes, bool is_signed); 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_t mp_obj_int_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in); diff --git a/py/objint_impl.h b/py/objint_impl.h new file mode 100644 index 00000000000..b1af4d6244d --- /dev/null +++ b/py/objint_impl.h @@ -0,0 +1,98 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2026 Angus Gratton + * + * 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. + */ + +/* This header provides some inline implementations of functions used by multiple objint*.c + files. + + Implementations here should only be called by one of the objint*.c files. If + called from more than one place in a single firmware, place into objint.c and + define in objint.h + */ +#ifndef MICROPY_INCLUDED_PY_OBJINT_IMPL_H +#define MICROPY_INCLUDED_PY_OBJINT_IMPL_H + +#include "py/binary.h" +#include "py/objint.h" +#include "py/runtime.h" + +static void mp_obj_int_raise_to_bytes_overflow_error(size_t nbytes) { + mp_raise_msg_varg(&mp_type_OverflowError, MP_ERROR_TEXT("value would overflow a %d byte buffer"), nbytes); +} + +static void mp_obj_int_raise_unsigned_negative_overflow_error(void) { + mp_raise_msg_varg(&mp_type_OverflowError, MP_ERROR_TEXT("can't convert negative int to unsigned")); +} + +static void mp_obj_small_int_buffer_overflow_check(mp_int_t val, size_t nbytes, bool is_signed) { + // Fast path for zero. + if (val == 0) { + return; + } + + if (!is_signed && val < 0) { + // Trying to store negative values in unsigned bytes + mp_obj_int_raise_unsigned_negative_overflow_error(); + } + + if (nbytes >= sizeof(val)) { + // All N bit small integers fit in an unsigned N bit integer. + // This case prevents shifting too far below. + return; + } + + if (nbytes == 0) { + // Can't fit a non-negative value in 0 bytes (prevents negative left shift, below) + goto raise; + } + + if (is_signed) { + mp_int_t edge = ((mp_int_t)1 << (nbytes * 8 - 1)); + if (-edge <= val && val < edge) { + return; + } + // Out of range, fall through to raise. + } else { + // Unsigned. We already know val >= 0. + mp_int_t edge = ((mp_int_t)1 << (nbytes * 8)); + if (val < edge) { + return; + } + // Fall through to raise. + } + +raise: + mp_obj_int_raise_to_bytes_overflow_error(nbytes); +} + +static inline void mp_obj_small_int_to_bytes(mp_int_t val, size_t buf_len, byte *buf, bool big_endian, bool is_signed, bool overflow_check) { + if (overflow_check) { + mp_obj_small_int_buffer_overflow_check(val, buf_len, is_signed); + } + mp_binary_set_int(buf_len, buf, sizeof(val), val, big_endian); + +} + +#endif // MICROPY_INCLUDED_PY_OBJINT_IMPL_H diff --git a/py/objint_longlong.c b/py/objint_longlong.c index 70d7e2873c5..49ac0b429fc 100644 --- a/py/objint_longlong.c +++ b/py/objint_longlong.c @@ -29,7 +29,7 @@ #include #include "py/smallint.h" -#include "py/objint.h" +#include "py/objint_impl.h" #include "py/runtime.h" #if MICROPY_PY_BUILTINS_FLOAT @@ -43,6 +43,10 @@ const mp_obj_int_t mp_sys_maxsize_obj = {{&mp_type_int}, MP_SSIZE_MAX}; #endif +static void raise_long_long_overflow(void) { + mp_raise_msg(&mp_type_OverflowError, MP_ERROR_TEXT("result overflows long long storage")); +} + // CIRCUITPY-CHANGE: bit_length mp_obj_t mp_obj_int_bit_length_impl(mp_obj_t self_in) { assert(mp_obj_is_type(self_in, &mp_type_int)); @@ -69,24 +73,6 @@ mp_obj_t mp_obj_int_from_bytes_impl(bool big_endian, size_t len, const byte *buf return mp_obj_new_int_from_ll(value); } -void mp_obj_int_to_bytes_impl(mp_obj_t self_in, bool big_endian, size_t len, byte *buf) { - assert(mp_obj_is_exact_type(self_in, &mp_type_int)); - mp_obj_int_t *self = self_in; - long long val = self->val; - if (big_endian) { - byte *b = buf + len; - while (b > buf) { - *--b = val; - val >>= 8; - } - } else { - for (; len > 0; --len) { - *buf++ = val; - val >>= 8; - } - } -} - int mp_obj_int_sign(mp_obj_t self_in) { mp_longint_impl_t val; if (mp_obj_is_small_int(self_in)) { @@ -114,7 +100,6 @@ mp_obj_t mp_obj_int_unary_op(mp_unary_op_t op, mp_obj_t o_in) { // 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: @@ -141,6 +126,8 @@ mp_obj_t mp_obj_int_unary_op(mp_unary_op_t op, mp_obj_t o_in) { mp_obj_t mp_obj_int_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) { long long lhs_val; long long rhs_val; + bool overflow = false; + long long result; if (mp_obj_is_small_int(lhs_in)) { lhs_val = MP_OBJ_SMALL_INT_VALUE(lhs_in); @@ -153,21 +140,41 @@ mp_obj_t mp_obj_int_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_i rhs_val = MP_OBJ_SMALL_INT_VALUE(rhs_in); } else if (mp_obj_is_exact_type(rhs_in, &mp_type_int)) { rhs_val = ((mp_obj_int_t *)rhs_in)->val; + #if MICROPY_PY_BUILTINS_FLOAT + } else if (mp_obj_is_float(rhs_in)) { + return mp_obj_float_binary_op(op, (mp_float_t)lhs_val, rhs_in); + #endif + #if MICROPY_PY_BUILTINS_COMPLEX + } else if (mp_obj_is_type(rhs_in, &mp_type_complex)) { + return mp_obj_complex_binary_op(op, (mp_float_t)lhs_val, 0, rhs_in); + #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 MICROPY_PY_BUILTINS_FLOAT + if (op == MP_BINARY_OP_TRUE_DIVIDE || op == MP_BINARY_OP_INPLACE_TRUE_DIVIDE) { + if (rhs_val == 0) { + goto zero_division; + } + return mp_obj_new_float((mp_float_t)lhs_val / (mp_float_t)rhs_val); + } + #endif + switch (op) { case MP_BINARY_OP_ADD: case MP_BINARY_OP_INPLACE_ADD: - return mp_obj_new_int_from_ll(lhs_val + rhs_val); + overflow = mp_add_ll_overflow(lhs_val, rhs_val, &result); + break; case MP_BINARY_OP_SUBTRACT: case MP_BINARY_OP_INPLACE_SUBTRACT: - return mp_obj_new_int_from_ll(lhs_val - rhs_val); + overflow = mp_sub_ll_overflow(lhs_val, rhs_val, &result); + break; case MP_BINARY_OP_MULTIPLY: case MP_BINARY_OP_INPLACE_MULTIPLY: - return mp_obj_new_int_from_ll(lhs_val * rhs_val); + overflow = mp_mul_ll_overflow(lhs_val, rhs_val, &result); + break; case MP_BINARY_OP_FLOOR_DIVIDE: case MP_BINARY_OP_INPLACE_FLOOR_DIVIDE: if (rhs_val == 0) { @@ -193,9 +200,21 @@ 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_LSHIFT: case MP_BINARY_OP_INPLACE_LSHIFT: - return mp_obj_new_int_from_ll(lhs_val << (int)rhs_val); + if (rhs_val < 0) { + // negative shift not allowed + mp_raise_ValueError(MP_ERROR_TEXT("negative shift count")); + } + overflow = rhs_val >= (long long)(sizeof(long long) * MP_BITS_PER_BYTE) + || lhs_val > (LLONG_MAX >> rhs_val) + || lhs_val < (LLONG_MIN >> rhs_val); + result = (unsigned long long)lhs_val << rhs_val; + break; case MP_BINARY_OP_RSHIFT: case MP_BINARY_OP_INPLACE_RSHIFT: + if ((int)rhs_val < 0) { + // negative shift not allowed + mp_raise_ValueError(MP_ERROR_TEXT("negative shift count")); + } return mp_obj_new_int_from_ll(lhs_val >> (int)rhs_val); case MP_BINARY_OP_POWER: @@ -207,18 +226,18 @@ mp_obj_t mp_obj_int_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_i mp_raise_ValueError(MP_ERROR_TEXT("negative power with no float support")); #endif } - long long ans = 1; - while (rhs_val > 0) { + result = 1; + while (rhs_val > 0 && !overflow) { if (rhs_val & 1) { - ans *= lhs_val; + overflow = mp_mul_ll_overflow(result, lhs_val, &result); } - if (rhs_val == 1) { + if (rhs_val == 1 || overflow) { break; } rhs_val /= 2; - lhs_val *= lhs_val; + overflow = mp_mul_ll_overflow(lhs_val, lhs_val, &lhs_val); } - return mp_obj_new_int_from_ll(ans); + break; } case MP_BINARY_OP_LESS: @@ -236,50 +255,39 @@ mp_obj_t mp_obj_int_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_i return MP_OBJ_NULL; // op not supported } + if (overflow) { + raise_long_long_overflow(); + } + + return mp_obj_new_int_from_ll(result); + zero_division: - mp_raise_ZeroDivisionError(); + mp_raise_msg(&mp_type_ZeroDivisionError, MP_ERROR_TEXT("divide by zero")); } mp_obj_t mp_obj_new_int(mp_int_t value) { - if (MP_SMALL_INT_FITS(value)) { - return MP_OBJ_NEW_SMALL_INT(value); - } return mp_obj_new_int_from_ll(value); } mp_obj_t mp_obj_new_int_from_uint(mp_uint_t value) { - // SMALL_INT accepts only signed numbers, so make sure the input - // value fits completely in the small-int positive range. - if ((value & ~MP_SMALL_INT_POSITIVE_MASK) == 0) { - return MP_OBJ_NEW_SMALL_INT(value); - } return mp_obj_new_int_from_ll(value); } mp_obj_t mp_obj_new_int_from_ll(long long val) { + if ((long long)(mp_int_t)val == val && MP_SMALL_INT_FITS(val)) { + return MP_OBJ_NEW_SMALL_INT(val); + } + mp_obj_int_t *o = mp_obj_malloc(mp_obj_int_t, &mp_type_int); o->val = val; - return o; + return MP_OBJ_FROM_PTR(o); } mp_obj_t mp_obj_new_int_from_ull(unsigned long long val) { - // TODO raise an exception if the unsigned long long won't fit if (val >> (sizeof(unsigned long long) * 8 - 1) != 0) { - mp_raise_msg(&mp_type_OverflowError, MP_ERROR_TEXT("ulonglong too large")); + raise_long_long_overflow(); } - mp_obj_int_t *o = mp_obj_malloc(mp_obj_int_t, &mp_type_int); - o->val = val; - return o; -} - -mp_obj_t mp_obj_new_int_from_str_len(const char **str, size_t len, bool neg, unsigned int base) { - // TODO this does not honor the given length of the string, but it all cases it should anyway be null terminated - // TODO check overflow - mp_obj_int_t *o = mp_obj_malloc(mp_obj_int_t, &mp_type_int); - char *endptr; - o->val = strtoll(*str, &endptr, base); - *str = endptr; - return o; + return mp_obj_new_int_from_ll(val); } mp_int_t mp_obj_int_get_truncated(mp_const_obj_t self_in) { @@ -292,8 +300,33 @@ mp_int_t mp_obj_int_get_truncated(mp_const_obj_t self_in) { } mp_int_t mp_obj_int_get_checked(mp_const_obj_t self_in) { - // TODO: Check overflow - return mp_obj_int_get_truncated(self_in); + if (mp_obj_is_small_int(self_in)) { + return MP_OBJ_SMALL_INT_VALUE(self_in); + } else { + const mp_obj_int_t *self = self_in; + long long value = self->val; + mp_int_t truncated = (mp_int_t)value; + if ((long long)truncated == value) { + return truncated; + } + } + mp_raise_msg(&mp_type_OverflowError, MP_ERROR_TEXT("overflow converting long int to machine word")); +} + +mp_uint_t mp_obj_int_get_uint_checked(mp_const_obj_t self_in) { + if (mp_obj_is_small_int(self_in)) { + if (MP_OBJ_SMALL_INT_VALUE(self_in) >= 0) { + return MP_OBJ_SMALL_INT_VALUE(self_in); + } + } else { + const mp_obj_int_t *self = self_in; + long long value = self->val; + mp_uint_t truncated = (mp_uint_t)value; + if (value >= 0 && (long long)truncated == value) { + return truncated; + } + } + mp_raise_msg(&mp_type_OverflowError, MP_ERROR_TEXT("overflow converting long int to machine word")); } #if MICROPY_PY_BUILTINS_FLOAT @@ -304,4 +337,88 @@ mp_float_t mp_obj_int_as_float_impl(mp_obj_t self_in) { } #endif +// Same as the general mp_small_int_buffer_overflow_check() in objint_impl.h, but using 64-bit integers +static void longint_buffer_overflow_check(mp_longint_impl_t val, size_t nbytes, bool is_signed) { + // Fast path for zero. + if (val == 0) { + return; + } + + if (!is_signed && val < 0) { + // Trying to store negative values in unsigned bytes + mp_obj_int_raise_unsigned_negative_overflow_error(); + } + + if (nbytes >= sizeof(val)) { + // All non-negative N bit signed integers fit in an unsigned N bit integer. + // This case prevents shifting too far below. + return; + } + + if (nbytes == 0) { + // Can't fit a non-zero value in 0 bytes (prevents negative left shift below) + goto raise; + } + + if (is_signed) { + mp_longint_impl_t edge = 1LL << (nbytes * 8 - 1); + if (-edge <= val && val < edge) { + return; + } + // Out of range, fall through to failure. + } else { + // Unsigned. We already know val >= 0. + mp_longint_impl_t edge = 1LL << (nbytes * 8); + if (val < edge) { + return; + } + // Fall through to failure. + } + +raise: + mp_obj_int_raise_to_bytes_overflow_error(nbytes); +} + +static void longint_to_bytes(long long val, bool big_endian, size_t len, byte *buf) { + MP_STATIC_ASSERT(sizeof(mp_uint_t) == 4); + mp_uint_t lower = val; + mp_uint_t upper = (val >> 32); + + if (big_endian) { + if (len > 4) { + // write the least significant 4 bytes at the end + mp_binary_set_int(4, buf + len - 4, sizeof(lower), lower, true); + // write most significant bytes at the start, extending if necessary + mp_binary_set_int(len - 4, buf, sizeof(upper), upper, true); + } else { + mp_binary_set_int(len, buf, sizeof(lower), lower, true); + } + } else { + // write the least significant 4 bytes at the start + mp_binary_set_int(len > 4 ? len - 4 : len, buf, sizeof(lower), lower, false); + if (len > 4) { + // write the most significant bytes at the end, extending if necessary + mp_binary_set_int(len - 4, buf + 4, sizeof(upper), upper, false); + } + } +} + +void mp_obj_int_to_bytes(mp_obj_t self_in, size_t buf_len, byte *buf, bool big_endian, bool is_signed, bool overflow_check) { + mp_longint_impl_t val; + if (mp_obj_is_exact_type(self_in, &mp_type_int)) { + const mp_obj_int_t *self = MP_OBJ_TO_PTR(self_in); + val = self->val; + } else { + // self_in is either a smallint, or another type convertible to mp_int_t (i.e. bool) + val = mp_obj_get_int(self_in); + } + + // Note: to save code size we don't call mp_obj_small_int_to_bytes() here, + // as the longint implementation is very similar + if (overflow_check) { + longint_buffer_overflow_check(val, buf_len, is_signed); + } + longint_to_bytes(val, big_endian, buf_len, buf); +} + #endif diff --git a/py/objint_mpz.c b/py/objint_mpz.c index 7bdeb364d87..f002dfe68a9 100644 --- a/py/objint_mpz.c +++ b/py/objint_mpz.c @@ -30,7 +30,7 @@ #include "py/parsenumbase.h" #include "py/smallint.h" -#include "py/objint.h" +#include "py/objint_impl.h" #include "py/runtime.h" #if MICROPY_PY_BUILTINS_FLOAT @@ -119,12 +119,6 @@ mp_obj_t mp_obj_int_from_bytes_impl(bool big_endian, size_t len, const byte *buf return MP_OBJ_FROM_PTR(o); } -void mp_obj_int_to_bytes_impl(mp_obj_t self_in, bool big_endian, size_t len, byte *buf) { - assert(mp_obj_is_exact_type(self_in, &mp_type_int)); - mp_obj_int_t *self = MP_OBJ_TO_PTR(self_in); - mpz_as_bytes(&self->mpz, big_endian, len, buf); -} - int mp_obj_int_sign(mp_obj_t self_in) { if (mp_obj_is_small_int(self_in)) { mp_int_t val = MP_OBJ_SMALL_INT_VALUE(self_in); @@ -320,6 +314,14 @@ mp_obj_t mp_obj_int_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_i return MP_OBJ_NULL; // op not supported } + // Check if the result fits in a small-int, and if so just return that. + mp_int_t res_small; + if (mpz_as_int_checked(&res->mpz, &res_small)) { + if (MP_SMALL_INT_FITS(res_small)) { + return MP_OBJ_NEW_SMALL_INT(res_small); + } + } + return MP_OBJ_FROM_PTR(res); } else { @@ -356,9 +358,10 @@ static mpz_t *mp_mpz_for_int(mp_obj_t arg, mpz_t *temp) { mp_obj_t mp_obj_int_pow3(mp_obj_t base, mp_obj_t exponent, mp_obj_t modulus) { if (!mp_obj_is_int(base) || !mp_obj_is_int(exponent) || !mp_obj_is_int(modulus)) { mp_raise_TypeError(MP_ERROR_TEXT("pow() with 3 arguments requires integers")); + } else if (modulus == MP_OBJ_NEW_SMALL_INT(0)) { + mp_raise_ValueError(MP_ERROR_TEXT("divide by zero")); } 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_new_mpz(); mpz_t l_temp, r_temp, m_temp; mpz_t *lhs = mp_mpz_for_int(base, &l_temp); @@ -381,7 +384,7 @@ mp_obj_t mp_obj_int_pow3(mp_obj_t base, mp_obj_t exponent, mp_obj_t modulus) { if (mod == &m_temp) { mpz_deinit(mod); } - return result; + return MP_OBJ_FROM_PTR(res_p); } } #endif @@ -438,6 +441,10 @@ mp_int_t mp_obj_int_get_checked(mp_const_obj_t self_in) { const mp_obj_int_t *self = MP_OBJ_TO_PTR(self_in); mp_int_t value; if (mpz_as_int_checked(&self->mpz, &value)) { + // mp_obj_int_t objects should always contain a value that is a large + // integer (if the value fits in a small-int then it should have been + // converted to a small-int object), and so this code-path should never + // be taken in normal circumstances. return value; } else { // overflow @@ -470,4 +477,22 @@ mp_float_t mp_obj_int_as_float_impl(mp_obj_t self_in) { } #endif +void mp_obj_int_to_bytes(mp_obj_t self_in, size_t buf_len, byte *buf, bool big_endian, bool is_signed, bool overflow_check) { + if (mp_obj_is_exact_type(self_in, &mp_type_int)) { + const mp_obj_int_t *self = MP_OBJ_TO_PTR(self_in); + const mpz_t *mpz = &self->mpz; + if (overflow_check && !is_signed && mpz->neg) { + mp_obj_int_raise_unsigned_negative_overflow_error(); + } + if (!mpz_as_bytes(mpz, big_endian, is_signed, buf_len, buf) && overflow_check) { + mp_obj_int_raise_to_bytes_overflow_error(buf_len); + } + } else { + // self_in is either a smallint, or another type convertible to mp_int_t (i.e. bool) + mp_int_t val = mp_obj_get_int(self_in); + mp_obj_small_int_to_bytes(val, buf_len, buf, big_endian, is_signed, overflow_check); + } +} + + #endif diff --git a/py/objlist.c b/py/objlist.c index 2c1545d8777..99060d895e0 100644 --- a/py/objlist.c +++ b/py/objlist.c @@ -29,7 +29,7 @@ #include "py/objlist.h" #include "py/runtime.h" -#include "py/stackctrl.h" +#include "py/cstack.h" static mp_obj_t mp_obj_new_list_iterator(mp_obj_t list, size_t cur, mp_obj_iter_buf_t *iter_buf); static mp_obj_list_t *list_new(size_t n); @@ -39,8 +39,7 @@ static mp_obj_t list_pop(size_t n_args, const mp_obj_t *args); // TODO: Move to mpconfig.h #define LIST_MIN_ALLOC 4 -// CIRCUITPY-CHANGE: native_list() and other changes here for broadcom port -// https://github.com/adafruit/circuitpython/pull/5610 +// CIRCUITPY-CHANGE: native_list() supports list methods on subclasses of list. /******************************************************************************/ /* list */ @@ -118,7 +117,7 @@ static mp_obj_t list_unary_op(mp_unary_op_t op, mp_obj_t self_in) { } static mp_obj_t list_binary_op(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t rhs) { - // CIRCUITPY-CHANGE + // CIRCUITPY-CHANGE: allow subclassing mp_obj_list_t *o = native_list(lhs); switch (op) { case MP_BINARY_OP_ADD: { @@ -142,7 +141,7 @@ static mp_obj_t list_binary_op(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t rhs) { if (n < 0) { n = 0; } - // CIRCUITPY-CHANGE + // CIRCUITPY-CHANGE: overflow check (PR#1279) size_t new_len = mp_seq_multiply_len(o->len, n); mp_obj_list_t *s = list_new(new_len); mp_seq_multiply(o->items, sizeof(*o->items), o->len, n, s->items); @@ -171,76 +170,66 @@ static mp_obj_t list_binary_op(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t rhs) { } static mp_obj_t list_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { - // CIRCUITPY-CHANGE - mp_obj_list_t *self = native_list(self_in); - if (value == MP_OBJ_NULL) { - // delete - #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)) { - mp_raise_NotImplementedError(NULL); + #if MICROPY_PY_BUILTINS_SLICE + if (mp_obj_is_type(index, &mp_type_slice)) { + // CIRCUITPY-CHANGE: handle subclassing + mp_obj_list_t *self = native_list(self_in); + mp_bound_slice_t slice; + bool fast = mp_seq_get_fast_slice_indexes(self->len, index, &slice); + if (value == MP_OBJ_SENTINEL) { + // load + if (!fast) { + return mp_seq_extract_slice(self->items, &slice); } - - mp_int_t len_adj = slice.start - slice.stop; - 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_obj_list_t *res = list_new(slice.stop - slice.start); + mp_seq_copy(res->items, self->items + slice.start, res->len, mp_obj_t); + return MP_OBJ_FROM_PTR(res); + } + // assign/delete + if (value == MP_OBJ_NULL) { + // delete is equivalent to slice assignment of an empty sequence + value = mp_const_empty_tuple; + } + if (!fast) { + mp_raise_NotImplementedError(NULL); + } + size_t value_len; + mp_obj_t *value_items; + mp_obj_get_array(value, &value_len, &value_items); + mp_int_t len_adj = value_len - (slice.stop - slice.start); + if (len_adj > 0) { + if (self->len + len_adj > self->alloc) { + // TODO: Might optimize memory copies here by checking if block can + // be grown inplace or not + self->items = m_renew(mp_obj_t, self->items, self->alloc, self->len + len_adj); + self->alloc = self->len + len_adj; + } + mp_seq_replace_slice_grow_inplace(self->items, self->len, + slice.start, slice.stop, value_items, value_len, len_adj, sizeof(*self->items)); + } else { + mp_seq_replace_slice_no_grow(self->items, self->len, + slice.start, slice.stop, value_items, value_len, 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; + // TODO: apply allocation policy re: alloc_size } - #endif - // CIRCUITPY-CHANGE - mp_obj_t args[2] = {MP_OBJ_FROM_PTR(self), index}; + self->len += len_adj; + return mp_const_none; + } + #endif + if (value == MP_OBJ_NULL) { + // delete + // CIRCUITPY-CHANGE: handle subclassing + mp_obj_t args[2] = {MP_OBJ_FROM_PTR(self_in), index}; list_pop(2, args); return mp_const_none; } else if (value == MP_OBJ_SENTINEL) { // load - #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)) { - return mp_seq_extract_slice(self->len, self->items, &slice); - } - mp_obj_list_t *res = list_new(slice.stop - slice.start); - mp_seq_copy(res->items, self->items + slice.start, res->len, mp_obj_t); - return MP_OBJ_FROM_PTR(res); - } - #endif + // CIRCUITPY-CHANGE: handle subclassing + mp_obj_list_t *self = native_list(self_in); 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 (mp_obj_is_type(index, &mp_type_slice)) { - 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); - if (len_adj > 0) { - if (self->len + len_adj > self->alloc) { - // TODO: Might optimize memory copies here by checking if block can - // be grown inplace or not - self->items = m_renew(mp_obj_t, self->items, self->alloc, self->len + len_adj); - self->alloc = self->len + len_adj; - } - mp_seq_replace_slice_grow_inplace(self->items, self->len, - slice_out.start, slice_out.stop, value_items, value_len, len_adj, sizeof(*self->items)); - } else { - mp_seq_replace_slice_no_grow(self->items, self->len, - slice_out.start, slice_out.stop, value_items, value_len, 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)); - // TODO: apply allocation policy re: alloc_size - } - self->len += len_adj; - return mp_const_none; - } - #endif mp_obj_list_store(self_in, index, value); return mp_const_none; } @@ -252,7 +241,7 @@ static mp_obj_t list_getiter(mp_obj_t o_in, mp_obj_iter_buf_t *iter_buf) { mp_obj_t mp_obj_list_append(mp_obj_t self_in, mp_obj_t arg) { mp_check_self(mp_obj_is_type(self_in, &mp_type_list)); - // CIRCUITPY-CHANGE + // CIRCUITPY-CHANGE: handle subclassing mp_obj_list_t *self = native_list(self_in); if (self->len >= self->alloc) { self->items = m_renew(mp_obj_t, self->items, self->alloc, self->alloc * 2); @@ -266,7 +255,7 @@ mp_obj_t mp_obj_list_append(mp_obj_t self_in, mp_obj_t arg) { static mp_obj_t list_extend(mp_obj_t self_in, mp_obj_t arg_in) { mp_check_self(mp_obj_is_type(self_in, &mp_type_list)); if (mp_obj_is_type(arg_in, &mp_type_list)) { - // CIRCUITPY-CHANGE + // CIRCUITPY-CHANGE: handle subclassing mp_obj_list_t *self = native_list(self_in); mp_obj_list_t *arg = native_list(arg_in); @@ -285,7 +274,7 @@ 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 } -// CIRCUITPY-CHANGE: used elsewhere so not static; impl is different +// CIRCUITPY-CHANGE: provide version for C use outside this file inline mp_obj_t mp_obj_list_pop(mp_obj_list_t *self, size_t index) { if (self->len == 0) { // CIRCUITPY-CHANGE: more specific mp_raise @@ -303,18 +292,28 @@ inline mp_obj_t mp_obj_list_pop(mp_obj_list_t *self, size_t index) { return ret; } -// CIRCUITPY-CHANGE 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 = native_list(args[0]); size_t index = mp_get_index(self->base.type, self->len, n_args == 1 ? MP_OBJ_NEW_SMALL_INT(-1) : args[1], false); + // CIRCUITPY-CHANGE: use factored-out pop code return mp_obj_list_pop(self, index); } +// "head" is actually the *exclusive lower bound* of the range to sort. That is, +// the first element to be sorted is `head[1]`, not `head[0]`. Similarly `tail` +// is an *inclusive upper bound* of the range to sort. That is, the final +// element to sort is `tail[0]`, not `tail[-1]`. +// +// The pivot element is always chosen as `tail[0]`. +// +// These unusual choices allows structuring the partitioning +// process as a do/while loop, which generates smaller code than the equivalent +// code with usual C bounds & a while or for loop. 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) { - mp_obj_t *h = head - 1; + mp_cstack_check(); + while (tail - head > 1) { // So long as at least 2 elements remain + mp_obj_t *h = head; 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 (;;) { @@ -325,19 +324,21 @@ static void mp_quicksort(mp_obj_t *head, mp_obj_t *tail, mp_obj_t key_fn, mp_obj if (h >= t) { break; } + // A pair of objects must be swapped to the other side of the partition mp_obj_t x = h[0]; h[0] = t[0]; t[0] = x; } + // Place the pivot element in the proper position mp_obj_t x = h[0]; h[0] = tail[0]; tail[0] = x; // do the smaller recursive call first, to keep stack within O(log(N)) - if (t - head < tail - h - 1) { + if (t - head < tail - h) { mp_quicksort(head, t, key_fn, binop_less_result); - head = h + 1; + head = h; } else { - mp_quicksort(h + 1, tail, key_fn, binop_less_result); + mp_quicksort(h, tail, key_fn, binop_less_result); tail = t; } } @@ -362,7 +363,7 @@ mp_obj_t mp_obj_list_sort(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_ mp_obj_list_t *self = native_list(pos_args[0]); if (self->len > 1) { - mp_quicksort(self->items, self->items + self->len - 1, + mp_quicksort(self->items - 1, 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); } @@ -370,10 +371,10 @@ mp_obj_t mp_obj_list_sort(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_ return mp_const_none; } -// CIRCUITPY-CHANGE: used elsewhere so not static +// CIRCUITPY-CHANGE: rename and make not static for use elsewhere mp_obj_t mp_obj_list_clear(mp_obj_t self_in) { mp_check_self(mp_obj_is_type(self_in, &mp_type_list)); - // CIRCUITPY-CHANGE + // CIRCUITPY-CHANGE: handle subclassing mp_obj_list_t *self = native_list(self_in); self->len = 0; self->items = m_renew(mp_obj_t, self->items, self->alloc, LIST_MIN_ALLOC); @@ -384,27 +385,28 @@ mp_obj_t mp_obj_list_clear(mp_obj_t self_in) { static mp_obj_t list_copy(mp_obj_t self_in) { mp_check_self(mp_obj_is_type(self_in, &mp_type_list)); - // CIRCUITPY-CHANGE + // CIRCUITPY-CHANGE: handle subclassing mp_obj_list_t *self = native_list(self_in); return mp_obj_new_list(self->len, self->items); } static mp_obj_t list_count(mp_obj_t self_in, mp_obj_t value) { mp_check_self(mp_obj_is_type(self_in, &mp_type_list)); - // CIRCUITPY-CHANGE + // CIRCUITPY-CHANGE: handle subclassing mp_obj_list_t *self = native_list(self_in); return mp_seq_count_obj(self->items, self->len, value); } static mp_obj_t list_index(size_t n_args, const mp_obj_t *args) { mp_check_self(mp_obj_is_type(args[0], &mp_type_list)); - // CIRCUITPY-CHANGE + // CIRCUITPY-CHANGE: handle subclassing mp_obj_list_t *self = native_list(args[0]); return mp_seq_index_obj(self->items, self->len, n_args, args); } -// CIRCUITPY-CHANGE: used elsewhere so not static -inline void mp_obj_list_insert(mp_obj_list_t *self, size_t index, mp_obj_t obj) { +// CIRCUITPY-CHANGE: factor out for C use elsewhere; not meant to emulate Python API +inline void mp_obj_list_insert(mp_obj_list_t *self_in, size_t index, mp_obj_t obj) { + mp_obj_list_t *self = native_list(self_in); mp_obj_list_append(MP_OBJ_FROM_PTR(self), mp_const_none); for (size_t i = self->len - 1; i > index; --i) { @@ -428,7 +430,7 @@ static mp_obj_t list_insert(mp_obj_t self_in, mp_obj_t idx, mp_obj_t obj) { if ((size_t)index > self->len) { index = self->len; } - // CIRCUITPY-CHANGE + // CIRCUITPY-CHANGE: use factored-out insert code mp_obj_list_insert(self, index, obj); return mp_const_none; } @@ -504,12 +506,14 @@ void mp_obj_list_init(mp_obj_list_t *o, size_t n) { o->base.type = &mp_type_list; o->alloc = n < LIST_MIN_ALLOC ? LIST_MIN_ALLOC : n; o->len = n; - o->items = m_new(mp_obj_t, o->alloc); + // CIRCUITPY-CHANGE: Use m_malloc_items because these are mp_obj_t + o->items = m_malloc_items(o->alloc); mp_seq_clear(o->items, n, o->alloc, sizeof(*o->items)); } static mp_obj_list_t *list_new(size_t n) { - mp_obj_list_t *o = m_new_obj(mp_obj_list_t); + // CIRCUITPY-CHANGE: Use mp_obj_malloc because it is a Python object + mp_obj_list_t *o = mp_obj_malloc(mp_obj_list_t, &mp_type_list); mp_obj_list_init(o, n); return o; } @@ -524,27 +528,6 @@ mp_obj_t mp_obj_new_list(size_t n, mp_obj_t *items) { return MP_OBJ_FROM_PTR(o); } -void mp_obj_list_get(mp_obj_t self_in, size_t *len, mp_obj_t **items) { - // CIRCUITPY-CHANGE - mp_obj_list_t *self = native_list(self_in); - *len = self->len; - *items = self->items; -} - -void mp_obj_list_set_len(mp_obj_t self_in, size_t len) { - // trust that the caller knows what it's doing - // TODO realloc if len got much smaller than alloc - mp_obj_list_t *self = MP_OBJ_TO_PTR(self_in); - self->len = len; -} - -void mp_obj_list_store(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { - // CIRCUITPY-CHANGE - mp_obj_list_t *self = native_list(self_in); - size_t i = mp_get_index(self->base.type, self->len, index, false); - self->items[i] = value; -} - /******************************************************************************/ /* list iterator */ @@ -576,3 +559,22 @@ mp_obj_t mp_obj_new_list_iterator(mp_obj_t list, size_t cur, mp_obj_iter_buf_t * o->cur = cur; return MP_OBJ_FROM_PTR(o); } + +mp_obj_list_t *mp_obj_list_optional_arg(mp_obj_t arg_in, size_t min_len) { + if (arg_in == MP_OBJ_NULL || arg_in == mp_const_none) { + return MP_OBJ_TO_PTR(mp_obj_new_list(min_len, NULL)); + } else { + return mp_obj_list_ensure(arg_in, min_len); + } +} + +mp_obj_list_t *mp_obj_list_ensure(mp_obj_t in, size_t min_len) { + if (!mp_obj_is_type(in, &mp_type_list)) { + mp_raise_TypeError(NULL); + } + mp_obj_list_t *list = MP_OBJ_TO_PTR(in); + if (list->len < min_len) { + mp_raise_ValueError(NULL); + } + return list; +} diff --git a/py/objlist.h b/py/objlist.h index 3fd49baf29f..6d5b3107443 100644 --- a/py/objlist.h +++ b/py/objlist.h @@ -37,8 +37,41 @@ typedef struct _mp_obj_list_t { void mp_obj_list_init(mp_obj_list_t *o, size_t n); mp_obj_t mp_obj_list_make_new(const mp_obj_type_t *type_in, size_t n_args, size_t n_kw, const mp_obj_t *args); +mp_obj_t mp_obj_list_append(mp_obj_t self_in, mp_obj_t arg); +mp_obj_t mp_obj_list_sort(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs); +mp_obj_t mp_obj_list_remove(mp_obj_t self_in, mp_obj_t value); +// CIRCUITPY-CHANGE: public routine +mp_obj_t mp_obj_list_clear(mp_obj_t self_in); // CIRCUITPY-CHANGE: new public functions 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); +static inline void mp_obj_list_get(mp_obj_t self_in, size_t *len, mp_obj_t **items) { + // CIRCUITPY-CHANGE: handle subclassing + mp_obj_list_t *self = (mp_obj_list_t *)MP_OBJ_TO_PTR(mp_obj_cast_to_native_base(self_in, MP_OBJ_FROM_PTR(&mp_type_list))); + *len = self->len; + *items = self->items; +} + +static inline void mp_obj_list_set_len(mp_obj_t self_in, size_t len) { + // trust that the caller knows what it's doing + // TODO realloc if len got much smaller than alloc + mp_obj_list_t *self = (mp_obj_list_t *)MP_OBJ_TO_PTR(self_in); + self->len = len; +} + +static inline void mp_obj_list_store(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { + // CIRCUITPY-CHANGE: handle subclassing + mp_obj_list_t *self = (mp_obj_list_t *)MP_OBJ_TO_PTR(mp_obj_cast_to_native_base(self_in, MP_OBJ_FROM_PTR(&mp_type_list))); + size_t i = mp_get_index(self->base.type, self->len, index, false); + self->items[i] = value; +} + +// Helper function for pattern of an optional argument which can be a list of a specified size, and is +// allocated on-demand otherwise +mp_obj_list_t *mp_obj_list_optional_arg(mp_obj_t arg_in, size_t min_len); + +// Ensure provided object is a list of minimum length min_len. Raises TypeError & ValueError otherwise. +mp_obj_list_t *mp_obj_list_ensure(mp_obj_t in, size_t min_len); + #endif // MICROPY_INCLUDED_PY_OBJLIST_H diff --git a/py/objmap.c b/py/objmap.c index 1911a7510ab..d8042f867c7 100644 --- a/py/objmap.c +++ b/py/objmap.c @@ -50,7 +50,8 @@ static mp_obj_t map_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_ static mp_obj_t map_iternext(mp_obj_t self_in) { mp_check_self(mp_obj_is_type(self_in, &mp_type_map)); mp_obj_map_t *self = MP_OBJ_TO_PTR(self_in); - mp_obj_t *nextses = m_new(mp_obj_t, self->n_iters); + // CIRCUITPY-CHANGE: Use m_malloc_items because it is an array of objects + mp_obj_t *nextses = m_malloc_items(self->n_iters); for (size_t i = 0; i < self->n_iters; i++) { mp_obj_t next = mp_iternext(self->iters[i]); diff --git a/py/objmodule.c b/py/objmodule.c index 3ccd31b23af..84b6a10f9ab 100644 --- a/py/objmodule.c +++ b/py/objmodule.c @@ -34,11 +34,6 @@ #include "py/runtime.h" #include "py/builtin.h" -// CIRCUITPY-CHANGE -#if CIRCUITPY_WARNINGS -#include "shared-module/warnings/__init__.h" -#endif - static void module_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { (void)kind; mp_obj_module_t *self = MP_OBJ_TO_PTR(self_in); @@ -49,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_MODULE___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); @@ -134,8 +129,8 @@ mp_obj_t mp_obj_new_module(qstr module_name) { } // create new module object - mp_module_context_t *o = m_new_obj(mp_module_context_t); - o->module.base.type = &mp_type_module; + // CIRCUITPY-CHANGE: Use mp_obj_malloc because it is a Python object + mp_module_context_t *o = mp_obj_malloc(mp_module_context_t, &mp_type_module); o->module.globals = MP_OBJ_TO_PTR(mp_obj_new_dict(MICROPY_MODULE_DICT_SIZE)); // store __name__ entry in the module @@ -157,11 +152,13 @@ static const mp_rom_map_elem_t mp_builtin_module_table[] = { }; MP_DEFINE_CONST_MAP(mp_builtin_module_map, mp_builtin_module_table); +#if MICROPY_HAVE_REGISTERED_EXTENSIBLE_MODULES static const mp_rom_map_elem_t mp_builtin_extensible_module_table[] = { // built-in modules declared with MP_REGISTER_EXTENSIBLE_MODULE() MICROPY_REGISTERED_EXTENSIBLE_MODULES }; MP_DEFINE_CONST_MAP(mp_builtin_extensible_module_map, mp_builtin_extensible_module_table); +#endif #if MICROPY_MODULE_ATTR_DELEGATION && defined(MICROPY_MODULE_DELEGATIONS) typedef struct _mp_module_delegation_entry_t { @@ -178,13 +175,13 @@ static const mp_module_delegation_entry_t mp_builtin_module_delegation_table[] = // Attempts to find (and initialise) a built-in, otherwise returns // MP_OBJ_NULL. mp_obj_t mp_module_get_builtin(qstr module_name, bool extensible) { - // CIRCUITPY-CHANGE - #if CIRCUITPY_PARALLELDISPLAYBUS && CIRCUITPY_WARNINGS - if (module_name == MP_QSTR_paralleldisplay) { - warnings_warn(&mp_type_FutureWarning, MP_ERROR_TEXT("%q renamed %q"), MP_QSTR_paralleldisplay, MP_QSTR_paralleldisplaybus); - } + #if MICROPY_HAVE_REGISTERED_EXTENSIBLE_MODULES + const mp_map_t *map = extensible ? &mp_builtin_extensible_module_map : &mp_builtin_module_map; + #else + const mp_map_t *map = &mp_builtin_module_map; #endif - mp_map_elem_t *elem = mp_map_lookup((mp_map_t *)(extensible ? &mp_builtin_extensible_module_map : &mp_builtin_module_map), MP_OBJ_NEW_QSTR(module_name), MP_MAP_LOOKUP); + mp_map_elem_t *elem = mp_map_lookup((mp_map_t *)map, MP_OBJ_NEW_QSTR(module_name), MP_MAP_LOOKUP); + if (!elem) { #if MICROPY_PY_SYS // Special case for sys, which isn't extensible but can always be @@ -194,6 +191,7 @@ mp_obj_t mp_module_get_builtin(qstr module_name, bool extensible) { } #endif + #if MICROPY_HAVE_REGISTERED_EXTENSIBLE_MODULES if (extensible) { // At this point we've already tried non-extensible built-ins, the // filesystem, and now extensible built-ins. No match, so fail @@ -210,6 +208,7 @@ mp_obj_t mp_module_get_builtin(qstr module_name, bool extensible) { // the old behaviour of the u-prefix being used to force a built-in // import. // CIRCUITPY-CHANGE: Don't look for `ufoo`. + #endif return MP_OBJ_NULL; } diff --git a/py/objmodule.h b/py/objmodule.h index 8b14cd9fc3d..4724270a11c 100644 --- a/py/objmodule.h +++ b/py/objmodule.h @@ -32,13 +32,23 @@ // Only include module definitions when not doing qstr extraction, because the // qstr extraction stage also generates this module definition header file. #include "genhdr/moduledefs.h" +// CIRCUITPY-CHANGE: avoid undef warning +#else +#define MICROPY_HAVE_REGISTERED_EXTENSIBLE_MODULES (0) #endif extern const mp_map_t mp_builtin_module_map; + +#if MICROPY_HAVE_REGISTERED_EXTENSIBLE_MODULES extern const mp_map_t mp_builtin_extensible_module_map; +#endif mp_obj_t mp_module_get_builtin(qstr module_name, bool extensible); void mp_module_generic_attr(qstr attr, mp_obj_t *dest, const uint16_t *keys, mp_obj_t *values); +static inline mp_obj_dict_t *mp_obj_module_get_globals(mp_obj_t module) { + return ((mp_obj_module_t *)MP_OBJ_TO_PTR(module))->globals; +} + #endif // MICROPY_INCLUDED_PY_OBJMODULE_H diff --git a/py/objnamedtuple.c b/py/objnamedtuple.c index b6bbe6e05d8..d687dbfda59 100644 --- a/py/objnamedtuple.c +++ b/py/objnamedtuple.c @@ -73,7 +73,7 @@ MP_DEFINE_CONST_FUN_OBJ_1(namedtuple_asdict_obj, namedtuple_asdict); void namedtuple_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind) { (void)kind; mp_obj_namedtuple_t *o = MP_OBJ_TO_PTR(o_in); - mp_printf(print, "%q", o->tuple.base.type->name); + mp_printf(print, "%q", (qstr)o->tuple.base.type->name); const qstr *fields = ((mp_obj_namedtuple_type_t *)o->tuple.base.type)->fields; mp_obj_attrtuple_print_helper(print, fields, &o->tuple); } diff --git a/py/objproperty.c b/py/objproperty.c index a3a13a71bb3..96563f6dba3 100644 --- a/py/objproperty.c +++ b/py/objproperty.c @@ -57,7 +57,8 @@ static mp_obj_t property_make_new(const mp_obj_type_t *type, size_t n_args, size } 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); + // CIRCUITPY-CHANGE: Use mp_obj_malloc because it is a Python object + mp_obj_property_t *p2 = mp_obj_malloc(mp_obj_property_t, &mp_type_property); *p2 = *(mp_obj_property_t *)MP_OBJ_TO_PTR(self_in); p2->proxy[0] = getter; return MP_OBJ_FROM_PTR(p2); @@ -66,7 +67,8 @@ static mp_obj_t property_getter(mp_obj_t self_in, mp_obj_t getter) { 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); + // CIRCUITPY-CHANGE: Use mp_obj_malloc because it is a Python object + mp_obj_property_t *p2 = mp_obj_malloc(mp_obj_property_t, &mp_type_property); *p2 = *(mp_obj_property_t *)MP_OBJ_TO_PTR(self_in); p2->proxy[1] = setter; return MP_OBJ_FROM_PTR(p2); @@ -75,7 +77,8 @@ static mp_obj_t property_setter(mp_obj_t self_in, mp_obj_t setter) { 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); + // CIRCUITPY-CHANGE: Use mp_obj_malloc because it is a Python object + mp_obj_property_t *p2 = mp_obj_malloc(mp_obj_property_t, &mp_type_property); *p2 = *(mp_obj_property_t *)MP_OBJ_TO_PTR(self_in); p2->proxy[2] = deleter; return MP_OBJ_FROM_PTR(p2); diff --git a/py/objrange.c b/py/objrange.c index 8793040eab0..dea9fe5f296 100644 --- a/py/objrange.c +++ b/py/objrange.c @@ -33,7 +33,6 @@ typedef struct _mp_obj_range_it_t { mp_obj_base_t base; - // TODO make these values generic objects or something mp_int_t cur; mp_int_t stop; mp_int_t step; @@ -42,9 +41,9 @@ typedef struct _mp_obj_range_it_t { static mp_obj_t range_it_iternext(mp_obj_t o_in) { mp_obj_range_it_t *o = MP_OBJ_TO_PTR(o_in); if ((o->step > 0 && o->cur < o->stop) || (o->step < 0 && o->cur > o->stop)) { - mp_obj_t o_out = MP_OBJ_NEW_SMALL_INT(o->cur); + mp_int_t cur = o->cur; o->cur += o->step; - return o_out; + return mp_obj_new_int(cur); } else { return MP_OBJ_STOP_ITERATION; } @@ -72,7 +71,6 @@ static mp_obj_t mp_obj_new_range_iterator(mp_int_t cur, mp_int_t stop, mp_int_t typedef struct _mp_obj_range_t { mp_obj_base_t base; - // TODO make these values generic objects or something mp_int_t start; mp_int_t stop; mp_int_t step; @@ -135,7 +133,7 @@ static mp_obj_t range_unary_op(mp_unary_op_t op, mp_obj_t self_in) { case MP_UNARY_OP_BOOL: return mp_obj_new_bool(len > 0); case MP_UNARY_OP_LEN: - return MP_OBJ_NEW_SMALL_INT(len); + return mp_obj_new_int(len); default: return MP_OBJ_NULL; // op not supported } @@ -167,20 +165,16 @@ static mp_obj_t range_subscr(mp_obj_t self_in, mp_obj_t index, mp_obj_t value) { #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); + mp_obj_slice_indices(index, len, &slice); mp_obj_range_t *o = mp_obj_malloc(mp_obj_range_t, &mp_type_range); o->start = self->start + slice.start * self->step; o->stop = self->start + slice.stop * self->step; o->step = slice.step * self->step; - if (slice.step < 0) { - // Negative slice steps have inclusive stop, so adjust for exclusive - o->stop -= self->step; - } return MP_OBJ_FROM_PTR(o); } #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); + return mp_obj_new_int(self->start + index_val * self->step); } else { return MP_OBJ_NULL; // op not supported } diff --git a/py/objringio.c b/py/objringio.c new file mode 100644 index 00000000000..0025b26be3b --- /dev/null +++ b/py/objringio.c @@ -0,0 +1,127 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2024 Andrew Leech + * + * 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 "ringbuf.h" +#include "py/mpconfig.h" + +#if MICROPY_PY_MICROPYTHON_RINGIO + +#include "py/runtime.h" +#include "py/stream.h" + +typedef struct _micropython_ringio_obj_t { + mp_obj_base_t base; + ringbuf_t ringbuffer; +} micropython_ringio_obj_t; + +static mp_obj_t micropython_ringio_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, 1, 1, false); + mp_buffer_info_t bufinfo = {NULL, 0, 0}; + + if (!mp_get_buffer(args[0], &bufinfo, MP_BUFFER_RW)) { + bufinfo.len = mp_obj_get_int(args[0]) + 1; + bufinfo.buf = m_new(uint8_t, bufinfo.len); + } + if (bufinfo.len < 2 || bufinfo.len > UINT16_MAX) { + mp_raise_ValueError(NULL); + } + micropython_ringio_obj_t *self = mp_obj_malloc(micropython_ringio_obj_t, type); + self->ringbuffer.buf = bufinfo.buf; + self->ringbuffer.size = bufinfo.len; + self->ringbuffer.iget = self->ringbuffer.iput = 0; + return MP_OBJ_FROM_PTR(self); +} + +static mp_uint_t micropython_ringio_read(mp_obj_t self_in, void *buf_in, mp_uint_t size, int *errcode) { + micropython_ringio_obj_t *self = MP_OBJ_TO_PTR(self_in); + size = MIN(size, ringbuf_avail(&self->ringbuffer)); + ringbuf_memcpy_get_internal(&(self->ringbuffer), buf_in, size); + *errcode = 0; + return size; +} + +static mp_uint_t micropython_ringio_write(mp_obj_t self_in, const void *buf_in, mp_uint_t size, int *errcode) { + micropython_ringio_obj_t *self = MP_OBJ_TO_PTR(self_in); + size = MIN(size, ringbuf_free(&self->ringbuffer)); + ringbuf_memcpy_put_internal(&(self->ringbuffer), buf_in, size); + *errcode = 0; + return size; +} + +static mp_uint_t micropython_ringio_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) { + micropython_ringio_obj_t *self = MP_OBJ_TO_PTR(self_in); + switch (request) { + case MP_STREAM_POLL: { + mp_uint_t ret = 0; + if ((arg & MP_STREAM_POLL_RD) && ringbuf_avail(&self->ringbuffer) > 0) { + ret |= MP_STREAM_POLL_RD; + } + if ((arg & MP_STREAM_POLL_WR) && ringbuf_free(&self->ringbuffer) > 0) { + ret |= MP_STREAM_POLL_WR; + } + return ret; + } + case MP_STREAM_CLOSE: + return 0; + } + *errcode = MP_EINVAL; + return MP_STREAM_ERROR; +} + +static mp_obj_t micropython_ringio_any(mp_obj_t self_in) { + micropython_ringio_obj_t *self = MP_OBJ_TO_PTR(self_in); + return MP_OBJ_NEW_SMALL_INT(ringbuf_avail(&self->ringbuffer)); +} +static MP_DEFINE_CONST_FUN_OBJ_1(micropython_ringio_any_obj, micropython_ringio_any); + +static const mp_rom_map_elem_t micropython_ringio_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_any), MP_ROM_PTR(µpython_ringio_any_obj) }, + { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) }, + { MP_ROM_QSTR(MP_QSTR_readline), MP_ROM_PTR(&mp_stream_unbuffered_readline_obj) }, + { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&mp_stream_readinto_obj) }, + { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) }, + { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&mp_stream_close_obj) }, + +}; +static MP_DEFINE_CONST_DICT(micropython_ringio_locals_dict, micropython_ringio_locals_dict_table); + +static const mp_stream_p_t ringio_stream_p = { + .read = micropython_ringio_read, + .write = micropython_ringio_write, + .ioctl = micropython_ringio_ioctl, + .is_text = false, +}; + +MP_DEFINE_CONST_OBJ_TYPE( + mp_type_ringio, + MP_QSTR_RingIO, + MP_TYPE_FLAG_NONE, + make_new, micropython_ringio_make_new, + protocol, &ringio_stream_p, + locals_dict, µpython_ringio_locals_dict + ); + +#endif // MICROPY_PY_MICROPYTHON_RINGIO diff --git a/py/objstr.c b/py/objstr.c index 342affb514d..a157228c363 100644 --- a/py/objstr.c +++ b/py/objstr.c @@ -32,7 +32,8 @@ #include "py/objstr.h" #include "py/objlist.h" #include "py/runtime.h" -#include "py/stackctrl.h" +#include "py/cstack.h" +#include "py/objtuple.h" // CIRCUITPY-CHANGE const char nibble_to_hex_upper[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', @@ -46,7 +47,7 @@ static mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_ #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); +static MP_NORETURN void bad_implicit_conversion(mp_obj_t self_in); static mp_obj_t mp_obj_new_str_type_from_vstr(const mp_obj_type_t *type, vstr_t *vstr); @@ -74,6 +75,34 @@ static void check_is_str_or_bytes(mp_obj_t self_in) { mp_check_self(mp_obj_is_str_or_bytes(self_in)); } +static mp_obj_t make_empty_str_of_type(const mp_obj_type_t *type) { + if (type == &mp_type_str) { + return MP_OBJ_NEW_QSTR(MP_QSTR_); // empty str + } else { + return mp_const_empty_bytes; + } +} + +static const byte *get_substring_data(const mp_obj_t obj, size_t n_args, const mp_obj_t *args, size_t *len) { + // Get substring data from obj, using args[0,1] to specify start and end indices. + GET_STR_DATA_LEN(obj, str, str_len); + if (n_args > 0) { + const mp_obj_type_t *self_type = mp_obj_get_type(obj); + const byte *end = str + str_len; + if (n_args > 1 && args[1] != mp_const_none) { + end = str_index_to_ptr(self_type, str, str_len, args[1], true); + } + if (args[0] != mp_const_none) { + str = str_index_to_ptr(self_type, str, str_len, args[0], true); + } + str_len = MAX(end - str, 0); + } + if (len) { + *len = str_len; + } + return str; +} + /******************************************************************************/ /* str */ @@ -165,6 +194,80 @@ static void str_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t } } +#if MICROPY_PY_BUILTINS_STR_UNICODE_CHECK && MICROPY_PY_BUILTINS_BYTES_DECODE_ERRORS +// Build a new string from data containing invalid UTF-8 or ASCII, either skipping the +// invalid bytes (errors=="ignore") or replacing them with U+FFFD +// (errors=="replace"). +static mp_obj_t str_from_invalid(mp_encoding_t encoding, const mp_obj_type_t *type, const byte *str_data, size_t str_len, qstr errors) { + bool do_replace = (errors == MP_QSTR_replace); + bool is_utf8 = (encoding == MP_ENCODING_UTF8); + vstr_t vstr; + vstr_init(&vstr, str_len); + const byte *p = str_data; + const byte *end = str_data + str_len; + + while (p < end) { + byte c = *p; + if (c < 0x80) { + // Valid ASCII + vstr_add_byte(&vstr, c); + p++; + } else if (is_utf8 && c >= 0xc0 && c < 0xf8) { + // Potential multi-byte sequence + uint8_t need = (0xe5 >> ((c >> 3) & 0x6)) & 3; + const byte *seq_start = p; + p++; + + // Check continuation bytes + uint8_t got = 0; + while (got < need && p < end && UTF8_IS_CONT(*p)) { + got++; + p++; + } + + if (got == need) { + // Valid complete sequence, decode and add the character + unichar ch = *seq_start & (0x7f >> need); + for (uint8_t i = 0; i < need; i++) { + ch = (ch << 6) | (seq_start[i + 1] & 0x3f); + } + vstr_add_char(&vstr, ch); + } else if (do_replace) { + // Invalid or incomplete sequence - replace with U+FFFD + vstr_add_char(&vstr, 0xFFFD); + } + // For 'ignore' mode, do nothing (skip invalid bytes) + } else if (do_replace) { + // Invalid start byte or non-ascii char - replace with U+FFFD + vstr_add_char(&vstr, 0xFFFD); + p++; + } else { + // Invalid start byte or non-ascii char - skip for 'ignore' mode + p++; + } + } + + return mp_obj_new_str_type_from_vstr(type, &vstr); +} +#endif // MICROPY_PY_BUILTINS_STR_UNICODE_CHECK && MICROPY_PY_BUILTINS_BYTES_DECODE_ERRORS + +#if MICROPY_PY_BUILTINS_STR_UNICODE_CHECK +static mp_encoding_t parse_encoding_arg(qstr encoding) { + // CIRCUITPY-CHANGE: also accept "UTF-8", which is commonly used. + if (encoding == MP_QSTR_utf_hyphen_8 || encoding == MP_QSTR_UTF_hyphen_8 || encoding == MP_QSTR_utf8) { + return MP_ENCODING_UTF8; + } + if (encoding == MP_QSTR_ascii) { + return MP_ENCODING_ASCII; + } + #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE + mp_raise_type(&mp_type_LookupError); + #else + mp_raise_msg_varg(&mp_type_LookupError, MP_ERROR_TEXT("unknown encoding: %q"), encoding); + #endif +} +#endif + mp_obj_t mp_obj_str_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { #if MICROPY_CPYTHON_COMPAT if (n_kw != 0) { @@ -186,36 +289,61 @@ mp_obj_t mp_obj_str_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_ return mp_obj_new_str_type_from_vstr(type, &vstr); } - default: // 2 or 3 args - // TODO: validate 2nd/3rd args + default: { // 2 or 3 args + // Extract the source data. + const byte *str_data; + size_t str_len; if (mp_obj_is_type(args[0], &mp_type_bytes)) { - GET_STR_DATA_LEN(args[0], str_data, str_len); - GET_STR_HASH(args[0], str_hash); - if (str_hash == 0) { - str_hash = qstr_compute_hash(str_data, str_len); + // Immutable bytes can be referenced directly (zero-copy); + GET_STR_DATA_LEN(args[0], bytes_data, bytes_len); + str_data = bytes_data; + str_len = bytes_len; + } else { + // any other buffer object is mutable sob its data must be copied. + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ); + str_data = bufinfo.buf; + str_len = bufinfo.len; + } + + #if MICROPY_PY_BUILTINS_STR_UNICODE_CHECK + mp_encoding_t encoding = parse_encoding_arg(mp_obj_str_get_qstr(args[1])); + if (!unicode_encoding_check(encoding, str_data, str_len)) { + #if MICROPY_PY_BUILTINS_BYTES_DECODE_ERRORS + // Check if error handler is specified (3rd argument) + qstr errors = MP_QSTR_; // default to "" + if (n_args >= 3 && args[2] != mp_const_none) { + errors = mp_obj_str_get_qstr(args[2]); } - #if MICROPY_PY_BUILTINS_STR_UNICODE_CHECK - if (!utf8_check(str_data, str_len)) { - mp_raise_msg(&mp_type_UnicodeError, NULL); + if (errors == MP_QSTR_ignore || errors == MP_QSTR_replace) { + return str_from_invalid(encoding, type, str_data, str_len, errors); } - #endif + #endif // MICROPY_PY_BUILTINS_BYTES_DECODE_ERRORS + mp_raise_msg(&mp_type_UnicodeError, NULL); + } + #endif // MICROPY_PY_BUILTINS_STR_UNICODE_CHECK - // Check if a qstr with this data already exists - qstr q = qstr_find_strn((const char *)str_data, str_len); - if (q != MP_QSTRnull) { - return MP_OBJ_NEW_QSTR(q); - } + // Check if a qstr with this data already exists + qstr q = qstr_find_strn((const char *)str_data, str_len); + if (q != MP_QSTRnull) { + return MP_OBJ_NEW_QSTR(q); + } - mp_obj_str_t *o = MP_OBJ_TO_PTR(mp_obj_new_str_copy(type, NULL, str_len)); - o->data = str_data; - o->hash = str_hash; - return MP_OBJ_FROM_PTR(o); - } else { - mp_buffer_info_t bufinfo; - mp_get_buffer_raise(args[0], &bufinfo, MP_BUFFER_READ); - // This will utf-8 check the input. - return mp_obj_new_str(bufinfo.buf, bufinfo.len); + if (!mp_obj_is_type(args[0], &mp_type_bytes)) { + // Source is a mutable buffer: copy the data. + return mp_obj_new_str_copy(type, str_data, str_len); + } + + // Source is immutable bytes: reference its data without copying. + GET_STR_HASH(args[0], str_hash); + if (str_hash == 0) { + str_hash = qstr_compute_hash(str_data, str_len); } + mp_obj_str_t *o = MP_OBJ_TO_PTR(mp_obj_new_str_copy(type, NULL, str_len)); + o->data = str_data; + o->hash = str_hash; + return MP_OBJ_FROM_PTR(o); + } } } @@ -246,11 +374,20 @@ static mp_obj_t bytes_make_new(const mp_obj_type_t *type_in, size_t n_args, size mp_raise_TypeError(MP_ERROR_TEXT("string argument without an encoding")); #endif } + GET_STR_DATA_LEN(args[0], str_data, str_len); GET_STR_HASH(args[0], str_hash); if (str_hash == 0) { str_hash = qstr_compute_hash(str_data, str_len); } + + #if MICROPY_PY_BUILTINS_STR_UNICODE_CHECK + mp_encoding_t encoding = parse_encoding_arg(mp_obj_str_get_qstr(args[1])); + if (encoding == MP_ENCODING_ASCII && !unicode_encoding_check(MP_ENCODING_ASCII, str_data, str_len)) { + mp_raise_msg(&mp_type_UnicodeError, NULL); + } + #endif + mp_obj_str_t *o = MP_OBJ_TO_PTR(mp_obj_new_str_copy(&mp_type_bytes, NULL, str_len)); o->data = str_data; o->hash = str_hash; @@ -268,7 +405,10 @@ static mp_obj_t bytes_make_new(const mp_obj_type_t *type_in, size_t n_args, size } vstr_t vstr; vstr_init_len(&vstr, len); + // If this config is set then the GC clears all memory, so we don't need to. + #if !MICROPY_GC_CONSERVATIVE_CLEAR memset(vstr.buf, 0, len); + #endif return mp_obj_new_bytes_from_vstr(&vstr); } @@ -352,8 +492,7 @@ mp_obj_t mp_obj_str_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_i mp_obj_t *args = &rhs_in; size_t n_args = 1; mp_obj_t dict = MP_OBJ_NULL; - if (mp_obj_is_type(rhs_in, &mp_type_tuple)) { - // TODO: Support tuple subclasses? + if (mp_obj_is_tuple_compatible(rhs_in)) { mp_obj_tuple_get(rhs_in, &n_args, &args); } else if (mp_obj_is_type(rhs_in, &mp_type_dict)) { dict = rhs_in; @@ -375,11 +514,7 @@ mp_obj_t mp_obj_str_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_i return MP_OBJ_NULL; // op not supported } if (n <= 0) { - if (lhs_type == &mp_type_str) { - return MP_OBJ_NEW_QSTR(MP_QSTR_); // empty str - } else { - return mp_const_empty_bytes; - } + return make_empty_str_of_type(lhs_type); } // CIRCUITPY-CHANGE: more careful checking of length size_t new_len = mp_seq_multiply_len(lhs_len, n); @@ -760,11 +895,29 @@ static mp_obj_t str_finder(size_t n_args, const mp_obj_t *args, int direction, b const mp_obj_type_t *self_type = mp_obj_get_type(args[0]); check_is_str_or_bytes(args[0]); - // check argument type - str_check_arg_type(self_type, args[1]); - GET_STR_DATA_LEN(args[0], haystack, haystack_len); - GET_STR_DATA_LEN(args[1], needle, needle_len); + + mp_int_t val; + byte needle_data; + const byte *needle; + size_t needle_len; + if (self_type != &mp_type_str && mp_obj_get_int_maybe(args[1], &val)) { + // Allow {bytes/bytearray}.{find,index}(int). + #if MICROPY_FULL_CHECKS + if (val < 0 || val > 255) { + mp_raise_ValueError(MP_ERROR_TEXT("bytes value out of range")); + } + #endif + needle_data = val; + needle = &needle_data; + needle_len = 1; + } else { + // check argument type + str_check_arg_type(self_type, args[1]); + GET_STR_DATA_LEN(args[1], needle_tmp, needle_len_tmp); + needle = needle_tmp; + needle_len = needle_len_tmp; + } const byte *start = haystack; const byte *end = haystack + haystack_len; @@ -819,37 +972,34 @@ static mp_obj_t str_rindex(size_t n_args, const mp_obj_t *args) { } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rindex_obj, 2, 4, str_rindex); -// TODO: (Much) more variety in args -static mp_obj_t str_startswith(size_t n_args, const mp_obj_t *args) { - const mp_obj_type_t *self_type = mp_obj_get_type(args[0]); - GET_STR_DATA_LEN(args[0], str, str_len); - size_t prefix_len; - const char *prefix = mp_obj_str_get_data(args[1], &prefix_len); - const byte *start = str; - if (n_args > 2) { - start = str_index_to_ptr(self_type, str, str_len, args[2], true); +static mp_obj_t str_startendswith(size_t n_args, const mp_obj_t *args, bool ends_with) { + size_t str_len; + const byte *str = get_substring_data(args[0], n_args - 2, args + 2, &str_len); + mp_obj_t *prefixes = (mp_obj_t *)&args[1]; + size_t n_prefixes = 1; + if (mp_obj_is_type(args[1], &mp_type_tuple)) { + mp_obj_tuple_get(args[1], &n_prefixes, &prefixes); } - if (prefix_len + (start - str) > str_len) { - return mp_const_false; + size_t prefix_len; + for (size_t i = 0; i < n_prefixes; i++) { + const char *prefix = mp_obj_str_get_data(prefixes[i], &prefix_len); + const byte *s = str + (ends_with ? str_len - prefix_len : 0); + if (prefix_len <= str_len && memcmp(s, prefix, prefix_len) == 0) { + return mp_const_true; + } } - return mp_obj_new_bool(memcmp(start, prefix, prefix_len) == 0); + return mp_const_false; } -MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_startswith_obj, 2, 3, str_startswith); -static mp_obj_t str_endswith(size_t n_args, const mp_obj_t *args) { - GET_STR_DATA_LEN(args[0], str, str_len); - size_t suffix_len; - const char *suffix = mp_obj_str_get_data(args[1], &suffix_len); - if (n_args > 2) { - mp_raise_NotImplementedError(MP_ERROR_TEXT("start/end indices")); - } +static mp_obj_t str_startswith(size_t n_args, const mp_obj_t *args) { + return str_startendswith(n_args, args, false); +} +MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_startswith_obj, 2, 4, str_startswith); - if (suffix_len > str_len) { - return mp_const_false; - } - return mp_obj_new_bool(memcmp(str + (str_len - suffix_len), suffix, suffix_len) == 0); +static mp_obj_t str_endswith(size_t n_args, const mp_obj_t *args) { + return str_startendswith(n_args, args, true); } -MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_endswith_obj, 2, 3, str_endswith); +MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_endswith_obj, 2, 4, str_endswith); enum { LSTRIP, RSTRIP, STRIP }; @@ -903,11 +1053,7 @@ static mp_obj_t str_uni_strip(int type, size_t n_args, const mp_obj_t *args) { if (!first_good_char_pos_set) { // string is all whitespace, return '' - if (self_type == &mp_type_str) { - return MP_OBJ_NEW_QSTR(MP_QSTR_); - } else { - return mp_const_empty_bytes; - } + return make_empty_str_of_type(self_type); } assert(last_good_char_pos >= first_good_char_pos); @@ -941,14 +1087,33 @@ MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(str_rstrip_obj, 1, 2, str_rstrip); static mp_obj_t str_center(mp_obj_t str_in, mp_obj_t width_in) { GET_STR_DATA_LEN(str_in, str, str_len); mp_uint_t width = mp_obj_get_int(width_in); + + #if MICROPY_PY_BUILTINS_STR_UNICODE + // Get character count (not byte count) for proper Unicode handling + size_t char_len = utf8_charlen(str, str_len); + if (char_len >= width) { + return str_in; + } + // Calculate padding: width is in characters, need to convert to bytes for allocation + mp_uint_t padding_chars = width - char_len; + // Padding is always spaces (1 byte each), plus the original string bytes + mp_uint_t total_bytes = padding_chars + str_len; + #else + // Non-Unicode build: byte length equals character length if (str_len >= width) { return str_in; } + mp_uint_t total_bytes = width; + #endif // MICROPY_PY_BUILTINS_STR_UNICODE vstr_t vstr; - vstr_init_len(&vstr, width); - memset(vstr.buf, ' ', width); + vstr_init_len(&vstr, total_bytes); + memset(vstr.buf, ' ', total_bytes); + #if MICROPY_PY_BUILTINS_STR_UNICODE + int left = padding_chars / 2; + #else int left = (width - str_len) / 2; + #endif // MICROPY_PY_BUILTINS_STR_UNICODE memcpy(vstr.buf + left, str, str_len); return mp_obj_new_str_type_from_vstr(mp_obj_get_type(str_in), &vstr); } @@ -1001,7 +1166,7 @@ static mp_obj_t arg_as_int(mp_obj_t arg) { #endif #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE -static NORETURN void terse_str_format_value_error(void) { +static MP_NORETURN void terse_str_format_value_error(void) { mp_raise_ValueError(MP_ERROR_TEXT("bad format string")); } #else @@ -1009,6 +1174,23 @@ static NORETURN void terse_str_format_value_error(void) { #define terse_str_format_value_error() #endif +// Print the character with the code point given by the integer object arg. +// Used by both the str.format and the modulo (%c) formatters. +static void mp_print_char(const mp_print_t *print, mp_obj_t arg, unsigned int flags, char fill, int width) { + #if MICROPY_FULL_CHECKS + mp_uint_t c = mp_obj_get_int(arg); + if (c >= 0x110000) { + mp_raise_msg(&mp_type_OverflowError, MP_ERROR_TEXT("char not in range(0x110000)")); + } + VSTR_FIXED(ch_vstr, 4); + vstr_add_char(&ch_vstr, c); + mp_print_strn(print, ch_vstr.buf, ch_vstr.len, flags, fill, width); + #else + char ch = mp_obj_get_int(arg); + mp_print_strn(print, &ch, 1, flags, fill, width); + #endif +} + static vstr_t mp_obj_str_format_helper(const char *str, const char *top, int *arg_i, size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) { vstr_t vstr; mp_print_t print; @@ -1188,7 +1370,7 @@ static vstr_t mp_obj_str_format_helper(const char *str, const char *top, int *ar int width = -1; int precision = -1; char type = '\0'; - int flags = 0; + unsigned int flags = 0; if (format_spec) { // The format specifier (from http://docs.python.org/2/library/string.html#formatspec) @@ -1202,7 +1384,7 @@ static vstr_t mp_obj_str_format_helper(const char *str, const char *top, int *ar // type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%" // recursively call the formatter to format any nested specifiers - MP_STACK_CHECK(); + mp_cstack_check(); vstr_t format_spec_vstr = mp_obj_str_format_helper(format_spec, str, arg_i, n_args, args, kwargs); const char *s = vstr_null_terminated_str(&format_spec_vstr); const char *stop = s + format_spec_vstr.len; @@ -1233,8 +1415,9 @@ static vstr_t mp_obj_str_format_helper(const char *str, const char *top, int *ar } } s = str_to_int(s, stop, &width); - if (*s == ',') { - flags |= PF_FLAG_SHOW_COMMA; + if (*s == ',' || *s == '_') { + MP_STATIC_ASSERT((unsigned)'_' << PF_FLAG_SEP_POS >> PF_FLAG_SEP_POS == '_'); + flags |= (unsigned)*s << PF_FLAG_SEP_POS; s++; } if (*s == '.') { @@ -1301,13 +1484,12 @@ static vstr_t mp_obj_str_format_helper(const char *str, const char *top, int *ar continue; case 'c': { - char ch = mp_obj_get_int(arg); - mp_print_strn(&print, &ch, 1, flags, fill, width); + mp_print_char(&print, arg, flags, fill, width); continue; } case '\0': // No explicit format type implies 'd' - case 'n': // I don't think we support locales in uPy so use 'd' + case 'n': // I don't think we support locales in MicroPython so use 'd' case 'd': mp_print_mp_int(&print, arg, 10, 'a', flags, fill, width, 0); continue; @@ -1503,8 +1685,7 @@ static mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_ // Dictionary value lookup if (*str == '(') { if (dict == MP_OBJ_NULL) { - // CIRCUITPY-CHANGE: clearer message - mp_raise_TypeError(MP_ERROR_TEXT("format requires a dict")); + mp_raise_TypeError(MP_ERROR_TEXT("format needs a dict")); } arg_i = 1; // we used up the single dict argument const byte *key = ++str; @@ -1585,8 +1766,7 @@ static mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_ if (arg == MP_OBJ_NULL) { if (arg_i >= n_args) { not_enough_args: - // CIRCUITPY-CHANGE: clearer message - mp_raise_TypeError(MP_ERROR_TEXT("not enough arguments for format string")); + mp_raise_TypeError(MP_ERROR_TEXT("format string needs more arguments")); } arg = args[arg_i++]; } @@ -1596,16 +1776,13 @@ static mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_ size_t slen; const char *s = mp_obj_str_get_data(arg, &slen); if (slen != 1) { - // CIRCUITPY-CHANGE: clearer message - mp_raise_TypeError(MP_ERROR_TEXT("%%c requires int or char")); + mp_raise_TypeError(MP_ERROR_TEXT("%%c needs int or char")); } mp_print_strn(&print, s, 1, flags, ' ', width); } else if (arg_looks_integer(arg)) { - char ch = mp_obj_get_int(arg); - mp_print_strn(&print, &ch, 1, flags, ' ', width); + mp_print_char(&print, arg, flags, ' ', width); } else { - // CIRCUITPY-CHANGE: clearer message - mp_raise_TypeError(MP_ERROR_TEXT("%%c requires int or char")); + mp_raise_TypeError(MP_ERROR_TEXT("%%c needs int or char")); } break; @@ -1677,8 +1854,7 @@ static mp_obj_t str_modulo_format(mp_obj_t pattern, size_t n_args, const mp_obj_ if (dict == MP_OBJ_NULL && arg_i != n_args) { // NOTE: if `dict` exists, then `n_args` is 1 and the dict is always consumed; either // positionally, or as a map of named args, even if none were actually referenced. - // CIRCUITPY-CHANGE: clearer message - mp_raise_TypeError(MP_ERROR_TEXT("not all arguments converted during string formatting")); + mp_raise_TypeError(MP_ERROR_TEXT("format string didn't convert all arguments")); } return mp_obj_new_str_type_from_vstr(is_bytes ? &mp_type_bytes : &mp_type_str, &vstr); @@ -1845,15 +2021,9 @@ static mp_obj_t str_partitioner(mp_obj_t self_in, mp_obj_t arg, int direction) { } mp_obj_t result[3]; - if (self_type == &mp_type_str) { - result[0] = MP_OBJ_NEW_QSTR(MP_QSTR_); - result[1] = MP_OBJ_NEW_QSTR(MP_QSTR_); - result[2] = MP_OBJ_NEW_QSTR(MP_QSTR_); - } else { - result[0] = mp_const_empty_bytes; - result[1] = mp_const_empty_bytes; - result[2] = mp_const_empty_bytes; - } + result[0] = make_empty_str_of_type(self_type); + result[1] = make_empty_str_of_type(self_type); + result[2] = make_empty_str_of_type(self_type); if (direction > 0) { result[0] = self_in; @@ -1972,6 +2142,7 @@ MP_DEFINE_CONST_FUN_OBJ_1(str_islower_obj, str_islower); #if MICROPY_CPYTHON_COMPAT // These methods are superfluous in the presence of str() and bytes() // constructors. + // TODO: should accept kwargs too static mp_obj_t bytes_decode(size_t n_args, const mp_obj_t *args) { mp_obj_t new_args[2]; @@ -2010,7 +2181,7 @@ mp_obj_t mp_obj_bytes_hex(size_t n_args, const mp_obj_t *args, const mp_obj_type // Code below assumes non-zero buffer length when computing size with // separator, so handle the zero-length case here. if (bufinfo.len == 0) { - return mp_const_empty_bytes; + return make_empty_str_of_type(type); } vstr_t vstr; @@ -2044,27 +2215,21 @@ mp_obj_t mp_obj_bytes_fromhex(mp_obj_t type_in, mp_obj_t data) { mp_buffer_info_t bufinfo; mp_get_buffer_raise(data, &bufinfo, MP_BUFFER_READ); - if ((bufinfo.len & 1) != 0) { - mp_raise_ValueError(MP_ERROR_TEXT("odd-length string")); - } vstr_t vstr; vstr_init_len(&vstr, bufinfo.len / 2); byte *in = bufinfo.buf, *out = (byte *)vstr.buf; - byte hex_byte = 0; - for (mp_uint_t i = bufinfo.len; i--;) { - byte hex_ch = *in++; - if (unichar_isxdigit(hex_ch)) { - hex_byte += unichar_xdigit_value(hex_ch); - } else { - mp_raise_ValueError(MP_ERROR_TEXT("non-hex digit found")); + byte *in_end = in + bufinfo.len; + mp_uint_t ch1, ch2; + while (in < in_end) { + if (unichar_isspace(ch1 = *in++)) { + continue; // Skip whitespace between hex digit pairs } - if (i & 1) { - hex_byte <<= 4; - } else { - *out++ = hex_byte; - hex_byte = 0; + if (in == in_end || !unichar_isxdigit(ch1) || !unichar_isxdigit(ch2 = *in++)) { + mp_raise_ValueError(MP_ERROR_TEXT("non-hex digit")); } + *out++ = (byte)((unichar_xdigit_value(ch1) << 4) | unichar_xdigit_value(ch2)); } + vstr.len = out - (byte *)vstr.buf; // Length may be shorter due to whitespace in input return mp_obj_new_str_type_from_vstr(MP_OBJ_TO_PTR(type_in), &vstr); } @@ -2243,7 +2408,8 @@ mp_obj_t mp_obj_new_str_copy(const mp_obj_type_t *type, const byte *data, size_t o->len = len; if (data) { o->hash = qstr_compute_hash(data, len); - byte *p = m_new(byte, len + 1); + // CIRCUITPY-CHANGE: Don't scan string data for pointers. + byte *p = m_malloc_without_collect(sizeof(byte) * (len + 1)); o->data = p; memcpy(p, data, len * sizeof(byte)); p[len] = '\0'; // for now we add null for compatibility with C ASCIIZ strings @@ -2308,7 +2474,7 @@ static mp_obj_t mp_obj_new_str_type_from_vstr(const mp_obj_type_t *type, vstr_t mp_obj_t mp_obj_new_str_from_vstr(vstr_t *vstr) { #if MICROPY_PY_BUILTINS_STR_UNICODE && MICROPY_PY_BUILTINS_STR_UNICODE_CHECK - if (!utf8_check((byte *)vstr->buf, vstr->len)) { + if (!unicode_encoding_check(MP_ENCODING_UTF8, (byte *)vstr->buf, vstr->len)) { mp_raise_msg(&mp_type_UnicodeError, NULL); } #endif // MICROPY_PY_BUILTINS_STR_UNICODE && MICROPY_PY_BUILTINS_STR_UNICODE_CHECK @@ -2328,7 +2494,7 @@ mp_obj_t mp_obj_new_bytes_from_vstr(vstr_t *vstr) { mp_obj_t mp_obj_new_str(const char *data, size_t len) { #if MICROPY_PY_BUILTINS_STR_UNICODE && MICROPY_PY_BUILTINS_STR_UNICODE_CHECK - if (!utf8_check((byte *)data, len)) { + if (!unicode_encoding_check(MP_ENCODING_UTF8, (byte *)data, len)) { mp_raise_msg(&mp_type_UnicodeError, NULL); } #endif @@ -2342,6 +2508,10 @@ mp_obj_t mp_obj_new_str(const char *data, size_t len) { } } +mp_obj_t mp_obj_new_str_from_cstr(const char *str) { + return mp_obj_new_str(str, strlen(str)); +} + 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); @@ -2385,7 +2555,7 @@ bool mp_obj_str_equal(mp_obj_t s1, mp_obj_t s2) { } } -static NORETURN void bad_implicit_conversion(mp_obj_t self_in) { +static MP_NORETURN void bad_implicit_conversion(mp_obj_t self_in) { #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE mp_raise_TypeError(MP_ERROR_TEXT("can't convert to str implicitly")); #else diff --git a/py/objstringio.c b/py/objstringio.c index 25e04cb4c69..a5dbc74ab07 100644 --- a/py/objstringio.c +++ b/py/objstringio.c @@ -83,7 +83,8 @@ static mp_uint_t stringio_read(mp_obj_t o_in, void *buf, mp_uint_t size, int *er static void stringio_copy_on_write(mp_obj_stringio_t *o) { const void *buf = o->vstr->buf; - o->vstr->buf = m_new(char, o->vstr->len); + // CIRCUITPY-CHANGE: Don't scan string data for pointers. + o->vstr->buf = m_malloc_without_collect(sizeof(char) * o->vstr->len); o->vstr->fixed_buf = false; o->ref_obj = MP_OBJ_NULL; memcpy(o->vstr->buf, buf, o->vstr->len); diff --git a/py/objstrunicode.c b/py/objstrunicode.c index a158b912365..6dbdccb77fa 100644 --- a/py/objstrunicode.c +++ b/py/objstrunicode.c @@ -57,11 +57,11 @@ static void uni_print_quoted(const mp_print_t *print, const byte *str_data, uint mp_printf(print, "%c", quote_char); const byte *s = str_data, *top = str_data + str_len; while (s < top) { + const byte *seq_start = s; unichar ch; ch = utf8_get_char(s); - // CIRCUITPY-CHANGE: print printable Unicode chars - const byte *start = s; s = utf8_next_char(s); + size_t seq_len = s - seq_start; if (ch == quote_char) { mp_printf(print, "\\%c", quote_char); } else if (ch == '\\') { @@ -79,12 +79,15 @@ static void uni_print_quoted(const mp_print_t *print, const byte *str_data, uint mp_printf(print, "\\x%02x", ch); } else if ((0x2000 <= ch && ch <= 0x200f) || ch == 0x2028 || ch == 0x2029 || ch == 0xffff) { mp_printf(print, "\\u%04x", ch); - } else if (ch == 0x1ffff) { + } else if (ch >= 0xd800 && ch < 0xe000) { + // Surrogate (0xD800-0xDFFF) - output as \uXXXX escape. + mp_printf(print, "\\u%04x", ch); + } else if (ch == 0x1ffff || ch >= 0x110000) { + // Invalid - output as \UXXXXXXXX escape. mp_printf(print, "\\U%08x", ch); } else { - // Print the full character out. - int width = s - start; - mp_print_strn(print, (const char *)start, width, 0, ' ', width); + // CIRCUITPY-CHANGE: print printable Unicode chars out in full. + mp_print_strn(print, (const char *)seq_start, seq_len, 0, ' ', seq_len); } } mp_printf(print, "%c", quote_char); diff --git a/py/objtemplate.c b/py/objtemplate.c new file mode 100644 index 00000000000..86451350a21 --- /dev/null +++ b/py/objtemplate.c @@ -0,0 +1,395 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2025 Koudai Aono + * Copyright (c) 2026 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 "py/runtime.h" + +#if MICROPY_PY_TSTRINGS + +typedef struct _mp_obj_template_t { + mp_obj_base_t base; + mp_obj_t strings; + mp_obj_t interpolations; +} mp_obj_template_t; + +typedef struct _mp_obj_interpolation_t { + mp_obj_base_t base; + mp_obj_t value; + mp_obj_t expression; + mp_obj_t conversion; + mp_obj_t format_spec; +} mp_obj_interpolation_t; + +static mp_obj_t mp_obj_new_interpolation(mp_obj_t value, mp_obj_t expr, mp_obj_t conv, mp_obj_t spec); + +static mp_obj_t mp_obj_template_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, MP_OBJ_FUN_ARGS_MAX, false); + + mp_obj_t strings_obj; + mp_obj_t interpolations_obj; + + if (n_args == 0) { + mp_obj_t empty = MP_OBJ_NEW_QSTR(MP_QSTR_); + strings_obj = mp_obj_new_tuple(1, &empty); + interpolations_obj = mp_obj_new_tuple(0, NULL); + } else { + size_t n_interpolations = 0; + size_t n_str_args = 0; + for (size_t i = 0; i < n_args; i++) { + if (mp_obj_is_exact_type(args[i], &mp_type_interpolation)) { + n_interpolations++; + } else if (mp_obj_is_str(args[i])) { + n_str_args++; + } else { + mp_raise_TypeError(MP_ERROR_TEXT("expected str or Interpolation")); + } + } + + if (n_interpolations == 0) { + if (n_str_args == 1) { + strings_obj = mp_obj_new_tuple(1, &args[0]); + } else { + size_t total_len = 0; + for (size_t i = 0; i < n_args; i++) { + size_t str_len; + (void)mp_obj_str_get_data(args[i], &str_len); + total_len += str_len; + } + vstr_t vstr; + vstr_init(&vstr, total_len); + for (size_t i = 0; i < n_args; i++) { + size_t str_len; + const char *str_data = mp_obj_str_get_data(args[i], &str_len); + vstr_add_strn(&vstr, str_data, str_len); + } + mp_obj_t str_items[1]; + str_items[0] = mp_obj_new_str_from_vstr(&vstr); + strings_obj = mp_obj_new_tuple(1, str_items); + } + interpolations_obj = mp_obj_new_tuple(0, NULL); + } else { + size_t n_strings = n_interpolations + 1; + mp_obj_tuple_t *strings_tuple = mp_obj_malloc_var(mp_obj_tuple_t, items, mp_obj_t, n_strings, &mp_type_tuple); + mp_obj_tuple_t *interpolations_tuple = mp_obj_malloc_var(mp_obj_tuple_t, items, mp_obj_t, n_interpolations, &mp_type_tuple); + strings_tuple->len = n_strings; + interpolations_tuple->len = n_interpolations; + + size_t string_idx = 0; + size_t interp_idx = 0; + mp_obj_t current_str = MP_OBJ_NULL; + bool current_vstr_active = false; + vstr_t current_vstr = {0}; + + for (size_t i = 0; i <= n_args; i++) { + if (i == n_args || mp_obj_is_exact_type(args[i], &mp_type_interpolation)) { + mp_obj_t out_str; + if (current_vstr_active) { + out_str = mp_obj_new_str_from_vstr(¤t_vstr); + current_vstr_active = false; + } else if (current_str != MP_OBJ_NULL) { + out_str = current_str; + } else { + out_str = MP_OBJ_NEW_QSTR(MP_QSTR_); + } + strings_tuple->items[string_idx++] = out_str; + current_str = MP_OBJ_NULL; + if (i < n_args) { + interpolations_tuple->items[interp_idx++] = args[i]; + } + } else { + size_t str_len; + const char *str_data = mp_obj_str_get_data(args[i], &str_len); + if (current_vstr_active) { + vstr_add_strn(¤t_vstr, str_data, str_len); + } else if (current_str == MP_OBJ_NULL) { + current_str = args[i]; + } else { + size_t prev_len; + const char *prev_data = mp_obj_str_get_data(current_str, &prev_len); + vstr_init(¤t_vstr, prev_len + str_len); + vstr_add_strn(¤t_vstr, prev_data, prev_len); + vstr_add_strn(¤t_vstr, str_data, str_len); + current_vstr_active = true; + current_str = MP_OBJ_NULL; + } + } + } + + strings_obj = MP_OBJ_FROM_PTR(strings_tuple); + interpolations_obj = MP_OBJ_FROM_PTR(interpolations_tuple); + } + } + + mp_obj_template_t *self = mp_obj_malloc(mp_obj_template_t, type); + self->strings = strings_obj; + self->interpolations = interpolations_obj; + return MP_OBJ_FROM_PTR(self); +} + +static void mp_obj_template_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { + (void)kind; + mp_obj_template_t *self = MP_OBJ_TO_PTR(self_in); + mp_printf(print, "%q(%q=", (qstr)MP_QSTR_Template, (qstr)MP_QSTR_strings); + mp_obj_print_helper(print, self->strings, PRINT_REPR); + mp_printf(print, ", %q=", (qstr)MP_QSTR_interpolations); + mp_obj_print_helper(print, self->interpolations, PRINT_REPR); + mp_print_str(print, ")"); +} + +static mp_obj_t mp_obj_template_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_obj_t rhs_in) { + mp_obj_template_t *lhs = MP_OBJ_TO_PTR(lhs_in); + + switch (op) { + case MP_BINARY_OP_ADD: { + if (!mp_obj_is_exact_type(rhs_in, &mp_type_template)) { + return MP_OBJ_NULL; // op not supported + } + + mp_obj_template_t *rhs = MP_OBJ_TO_PTR(rhs_in); + + mp_obj_tuple_t *lhs_strings = MP_OBJ_TO_PTR(lhs->strings); + mp_obj_tuple_t *lhs_interps = MP_OBJ_TO_PTR(lhs->interpolations); + mp_obj_tuple_t *rhs_strings = MP_OBJ_TO_PTR(rhs->strings); + mp_obj_tuple_t *rhs_interps = MP_OBJ_TO_PTR(rhs->interpolations); + + size_t new_strings_len = lhs_strings->len + rhs_strings->len - 1; + size_t new_interps_len = lhs_interps->len + rhs_interps->len; + + // Create tuples directly to avoid GC issues. + mp_obj_tuple_t *new_strings_tuple = mp_obj_malloc_var(mp_obj_tuple_t, items, mp_obj_t, new_strings_len, &mp_type_tuple); + mp_obj_tuple_t *new_interps_tuple = mp_obj_malloc_var(mp_obj_tuple_t, items, mp_obj_t, new_interps_len, &mp_type_tuple); + new_strings_tuple->len = new_strings_len; + new_interps_tuple->len = new_interps_len; + + // Copy all but the last string from lhs. + for (size_t i = 0; i < lhs_strings->len - 1; i++) { + new_strings_tuple->items[i] = lhs_strings->items[i]; + } + + // Merge last string from lhs with first string from rhs. + size_t lhs_last_len, rhs_first_len; + const char *lhs_last_str = mp_obj_str_get_data(lhs_strings->items[lhs_strings->len - 1], &lhs_last_len); + const char *rhs_first_str = mp_obj_str_get_data(rhs_strings->items[0], &rhs_first_len); + + vstr_t vstr; + vstr_init(&vstr, lhs_last_len + rhs_first_len); + vstr_add_strn(&vstr, lhs_last_str, lhs_last_len); + vstr_add_strn(&vstr, rhs_first_str, rhs_first_len); + new_strings_tuple->items[lhs_strings->len - 1] = mp_obj_new_str_from_vstr(&vstr); + + // Copy remaining strings from rhs. + for (size_t i = 1; i < rhs_strings->len; i++) { + new_strings_tuple->items[lhs_strings->len - 1 + i] = rhs_strings->items[i]; + } + + // Copy interpolations from both sides. + for (size_t i = 0; i < lhs_interps->len; i++) { + new_interps_tuple->items[i] = lhs_interps->items[i]; + } + + for (size_t i = 0; i < rhs_interps->len; i++) { + new_interps_tuple->items[lhs_interps->len + i] = rhs_interps->items[i]; + } + + mp_obj_template_t *result = mp_obj_malloc(mp_obj_template_t, &mp_type_template); + result->strings = MP_OBJ_FROM_PTR(new_strings_tuple); + result->interpolations = MP_OBJ_FROM_PTR(new_interps_tuple); + return MP_OBJ_FROM_PTR(result); + } + + default: + return MP_OBJ_NULL; // op not supported + } +} + +static void mp_obj_template_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { + mp_obj_template_t *self = MP_OBJ_TO_PTR(self_in); + + if (dest[0] == MP_OBJ_NULL) { + // Load attribute. + if (attr == MP_QSTR_strings) { + dest[0] = self->strings; + } else if (attr == MP_QSTR_interpolations) { + dest[0] = self->interpolations; + } else if (attr == MP_QSTR_values) { + mp_obj_tuple_t *interps = MP_OBJ_TO_PTR(self->interpolations); + mp_obj_tuple_t *values_tuple = MP_OBJ_TO_PTR(mp_obj_new_tuple(interps->len, NULL)); + for (size_t i = 0; i < interps->len; i++) { + mp_obj_interpolation_t *interp = MP_OBJ_TO_PTR(interps->items[i]); + values_tuple->items[i] = interp->value; + } + dest[0] = MP_OBJ_FROM_PTR(values_tuple); + } + } +} + +typedef struct _mp_obj_template_iter_t { + mp_obj_base_t base; + mp_fun_1_t iternext; + mp_obj_t template; + size_t index; +} mp_obj_template_iter_t; + +static mp_obj_t template_iter_iternext(mp_obj_t self_in) { + mp_obj_template_iter_t *self = MP_OBJ_TO_PTR(self_in); + mp_obj_template_t *tmpl = MP_OBJ_TO_PTR(self->template); + mp_obj_tuple_t *strings = MP_OBJ_TO_PTR(tmpl->strings); + mp_obj_tuple_t *interps = MP_OBJ_TO_PTR(tmpl->interpolations); + + while (self->index < strings->len + interps->len) { + if ((self->index & 1) == 0) { + // A string. + mp_obj_t str_obj = strings->items[self->index++ / 2]; + size_t str_len; + mp_obj_str_get_data(str_obj, &str_len); + if (str_len > 0) { + return str_obj; + } + } else { + // An interpolation. + return interps->items[self->index++ / 2]; + } + } + + return MP_OBJ_STOP_ITERATION; +} + +static mp_obj_t mp_obj_template_iter(mp_obj_t self_in, mp_obj_iter_buf_t *iter_buf) { + assert(sizeof(mp_obj_template_iter_t) <= sizeof(mp_obj_iter_buf_t)); + mp_obj_template_iter_t *iter = (mp_obj_template_iter_t *)iter_buf; + iter->base.type = &mp_type_polymorph_iter; + iter->iternext = template_iter_iternext; + iter->template = self_in; + iter->index = 0; + return MP_OBJ_FROM_PTR(iter); +} + +MP_DEFINE_CONST_OBJ_TYPE( + mp_type_template, + MP_QSTR_Template, + MP_TYPE_FLAG_NONE, + make_new, mp_obj_template_make_new, + print, mp_obj_template_print, + binary_op, mp_obj_template_binary_op, + attr, mp_obj_template_attr, + iter, mp_obj_template_iter + ); + +mp_obj_t mp_obj_new_template(size_t n_args, const mp_obj_t *args) { + mp_obj_template_t *o = mp_obj_malloc(mp_obj_template_t, &mp_type_template); + o->strings = args[0]; + if (n_args == 2) { + // Unpack interpolations from second argument (which is a tuple). + mp_obj_t *iargs; + mp_obj_get_array(args[1], &n_args, &iargs); + args = iargs; + } else { + // Unpack interpolations directly from arguments. + --n_args; + ++args; + } + size_t n_interpolations = n_args / 4; + mp_obj_tuple_t *interpolations = MP_OBJ_TO_PTR(mp_obj_new_tuple(n_interpolations, NULL)); + for (size_t i = 0; i < n_interpolations; ++i) { + interpolations->items[i] = mp_obj_new_interpolation(args[i * 4], args[i * 4 + 1], args[i * 4 + 2], args[i * 4 + 3]); + } + o->interpolations = MP_OBJ_FROM_PTR(interpolations); + return MP_OBJ_FROM_PTR(o); +} + +///////////////////////////////////////////////////////////////// + +static mp_obj_t mp_obj_interpolation_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_value, ARG_expression, ARG_conversion, ARG_format_spec }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_value, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_expression, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_QSTR(MP_QSTR_)} }, + { MP_QSTR_conversion, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} }, + { MP_QSTR_format_spec, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_QSTR(MP_QSTR_)} }, + }; + + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + mp_obj_interpolation_t *self = mp_obj_malloc(mp_obj_interpolation_t, &mp_type_interpolation); + self->value = args[ARG_value].u_obj; + self->expression = args[ARG_expression].u_obj; + self->conversion = args[ARG_conversion].u_obj; + self->format_spec = args[ARG_format_spec].u_obj; + + return MP_OBJ_FROM_PTR(self); +} + +static void mp_obj_interpolation_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { + (void)kind; + mp_obj_interpolation_t *self = MP_OBJ_TO_PTR(self_in); + mp_printf(print, "%q(", (qstr)MP_QSTR_Interpolation); + mp_obj_print_helper(print, self->value, PRINT_REPR); + mp_print_str(print, ", "); + mp_obj_print_helper(print, self->expression, PRINT_REPR); + mp_print_str(print, ", "); + mp_obj_print_helper(print, self->conversion, PRINT_REPR); + mp_print_str(print, ", "); + mp_obj_print_helper(print, self->format_spec, PRINT_REPR); + mp_print_str(print, ")"); +} + +static void mp_obj_interpolation_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { + mp_obj_interpolation_t *self = MP_OBJ_TO_PTR(self_in); + + if (dest[0] == MP_OBJ_NULL) { + // load attribute + if (attr == MP_QSTR_value) { + dest[0] = self->value; + } else if (attr == MP_QSTR_expression) { + dest[0] = self->expression; + } else if (attr == MP_QSTR_conversion) { + dest[0] = self->conversion; + } else if (attr == MP_QSTR_format_spec) { + dest[0] = self->format_spec; + } + } +} + +static mp_obj_t mp_obj_new_interpolation(mp_obj_t value, mp_obj_t expression, mp_obj_t conversion, mp_obj_t format_spec) { + mp_obj_interpolation_t *o = mp_obj_malloc(mp_obj_interpolation_t, &mp_type_interpolation); + o->value = value; + o->expression = expression; + o->conversion = conversion; + o->format_spec = format_spec; + return MP_OBJ_FROM_PTR(o); +} + +MP_DEFINE_CONST_OBJ_TYPE( + mp_type_interpolation, + MP_QSTR_Interpolation, + MP_TYPE_FLAG_NONE, + make_new, mp_obj_interpolation_make_new, + print, mp_obj_interpolation_print, + attr, mp_obj_interpolation_attr + ); + +#endif // MICROPY_PY_TSTRINGS diff --git a/py/objtuple.c b/py/objtuple.c index ec1545abb84..6808f6c6e0a 100644 --- a/py/objtuple.c +++ b/py/objtuple.c @@ -31,9 +31,6 @@ #include "py/objtuple.h" #include "py/runtime.h" -// type check is done on getiter method to allow tuple, namedtuple, attrtuple -#define mp_obj_is_tuple_compatible(o) (MP_OBJ_TYPE_GET_SLOT_OR_NULL(mp_obj_get_type(o), iter) == mp_obj_tuple_getiter) - /******************************************************************************/ /* tuple */ @@ -86,7 +83,8 @@ static mp_obj_t mp_obj_tuple_make_new(const mp_obj_type_t *type_in, size_t n_arg size_t alloc = 4; size_t len = 0; - mp_obj_t *items = m_new(mp_obj_t, alloc); + // CIRCUITPY-CHANGE + mp_obj_t *items = m_malloc_items(alloc); mp_obj_t iterable = mp_getiter(args[0], NULL); mp_obj_t item; @@ -106,20 +104,27 @@ static mp_obj_t mp_obj_tuple_make_new(const mp_obj_type_t *type_in, size_t n_arg } } +static mp_obj_tuple_t *tuple_subclass_helper(mp_obj_t obj) { + assert(obj != MP_OBJ_NULL); + const mp_obj_type_t *tuple_type = mp_obj_get_type(obj); + if (MP_OBJ_TYPE_GET_SLOT_OR_NULL(tuple_type, iter) != mp_obj_tuple_getiter) { + // Slow path for user subclasses + obj = mp_obj_cast_to_native_base(obj, MP_OBJ_FROM_PTR(&mp_type_tuple)); + if (obj == MP_OBJ_NULL) { + return NULL; + } + } + return MP_OBJ_TO_PTR(obj); +} + // Don't pass MP_BINARY_OP_NOT_EQUAL here static mp_obj_t tuple_cmp_helper(mp_uint_t op, mp_obj_t self_in, mp_obj_t another_in) { mp_check_self(mp_obj_is_tuple_compatible(self_in)); - const mp_obj_type_t *another_type = mp_obj_get_type(another_in); mp_obj_tuple_t *self = MP_OBJ_TO_PTR(self_in); - if (MP_OBJ_TYPE_GET_SLOT_OR_NULL(another_type, iter) != mp_obj_tuple_getiter) { - // Slow path for user subclasses - another_in = mp_obj_cast_to_native_base(another_in, MP_OBJ_FROM_PTR(&mp_type_tuple)); - if (another_in == MP_OBJ_NULL) { - return MP_OBJ_NULL; - } + mp_obj_tuple_t *another = tuple_subclass_helper(another_in); + if (!another) { + return MP_OBJ_NULL; } - mp_obj_tuple_t *another = MP_OBJ_TO_PTR(another_in); - return mp_obj_new_bool(mp_seq_cmp_objs(op, self->items, self->len, another->items, another->len)); } @@ -148,10 +153,10 @@ mp_obj_t mp_obj_tuple_binary_op(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t rhs) { switch (op) { case MP_BINARY_OP_ADD: case MP_BINARY_OP_INPLACE_ADD: { - if (!mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(rhs)), MP_OBJ_FROM_PTR(&mp_type_tuple))) { + mp_obj_tuple_t *p = tuple_subclass_helper(rhs); + if (!p) { return MP_OBJ_NULL; // op not supported } - mp_obj_tuple_t *p = MP_OBJ_TO_PTR(rhs); mp_obj_tuple_t *s = MP_OBJ_TO_PTR(mp_obj_new_tuple(o->len + p->len, NULL)); mp_seq_cat(s->items, o->items, o->len, p->items, p->len, mp_obj_t); return MP_OBJ_FROM_PTR(s); @@ -249,6 +254,9 @@ MP_DEFINE_CONST_OBJ_TYPE( // the zero-length tuple const mp_obj_tuple_t mp_const_empty_tuple_obj = {{&mp_type_tuple}, 0}; +// CIRCUITPY-CHANGE: No change here, but implementation was copied for +// mp_obj_new_port_tuple in supervisor/shared/port.c, which allocates using port_malloc(). +// Change that to match if this changes. mp_obj_t mp_obj_new_tuple(size_t n, const mp_obj_t *items) { if (n == 0) { return mp_const_empty_tuple; @@ -263,19 +271,6 @@ mp_obj_t mp_obj_new_tuple(size_t n, const mp_obj_t *items) { return MP_OBJ_FROM_PTR(o); } -void mp_obj_tuple_get(mp_obj_t self_in, size_t *len, mp_obj_t **items) { - assert(mp_obj_is_tuple_compatible(self_in)); - mp_obj_tuple_t *self = MP_OBJ_TO_PTR(self_in); - *len = self->len; - *items = &self->items[0]; -} - -void mp_obj_tuple_del(mp_obj_t self_in) { - assert(mp_obj_is_type(self_in, &mp_type_tuple)); - mp_obj_tuple_t *self = MP_OBJ_TO_PTR(self_in); - m_del_var(mp_obj_tuple_t, items, mp_obj_t, self->len, self); -} - /******************************************************************************/ /* tuple iterator */ diff --git a/py/objtuple.h b/py/objtuple.h index e2d010e6c5a..f0b081faad6 100644 --- a/py/objtuple.h +++ b/py/objtuple.h @@ -28,6 +28,9 @@ #include "py/obj.h" +// type check is done on getiter method to allow tuple, namedtuple, attrtuple +#define mp_obj_is_tuple_compatible(o) (MP_OBJ_TYPE_GET_SLOT_OR_NULL(mp_obj_get_type(o), iter) == mp_obj_tuple_getiter) + typedef struct _mp_obj_tuple_t { mp_obj_base_t base; size_t len; @@ -49,6 +52,13 @@ mp_obj_t mp_obj_tuple_binary_op(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t rhs); mp_obj_t mp_obj_tuple_subscr(mp_obj_t base, mp_obj_t index, mp_obj_t value); mp_obj_t mp_obj_tuple_getiter(mp_obj_t o_in, mp_obj_iter_buf_t *iter_buf); +static inline void mp_obj_tuple_get(mp_obj_t self_in, size_t *len, mp_obj_t **items) { + assert(mp_obj_is_tuple_compatible(self_in)); + mp_obj_tuple_t *self = (mp_obj_tuple_t *)MP_OBJ_TO_PTR(self_in); + *len = self->len; + *items = &self->items[0]; +} + extern const mp_obj_type_t mp_type_attrtuple; // CIRCUITPY-CHANGE @@ -57,7 +67,7 @@ extern const mp_obj_type_t mp_type_attrtuple; #define MP_DEFINE_ATTRTUPLE(tuple_obj_name, fields, nitems, ...) \ const mp_rom_obj_tuple_t tuple_obj_name = { \ - .base = {&mp_type_attrtuple}, \ + .base = {.type = &mp_type_attrtuple}, \ .len = nitems, \ .items = { __VA_ARGS__, MP_ROM_PTR((void *)fields) } \ } diff --git a/py/objtype.c b/py/objtype.c index c2ef10ee9ee..e0b35a55d33 100644 --- a/py/objtype.c +++ b/py/objtype.c @@ -44,6 +44,8 @@ #define ENABLE_SPECIAL_ACCESSORS \ (MICROPY_PY_DESCRIPTORS || MICROPY_PY_DELATTR_SETATTR || MICROPY_PY_BUILTINS_PROPERTY) +static mp_obj_t mp_obj_new_type(qstr name, mp_obj_t bases_tuple, mp_obj_t locals_dict); +static mp_obj_t mp_obj_is_subclass(mp_obj_t object, mp_obj_t classinfo); static mp_obj_t static_class_method_make_new(const mp_obj_type_t *self_in, size_t n_args, size_t n_kw, const mp_obj_t *args); /******************************************************************************/ @@ -83,7 +85,7 @@ static int instance_count_native_bases(const mp_obj_type_t *type, const mp_obj_t } // CIRCUITPY-CHANGE: support superclass constructors that take kw args -// This wrapper function is allows a subclass of a native type to call the +// This wrapper function allows a subclass of a native type to call the // __init__() method (corresponding to type->make_new) of the native type. static mp_obj_t native_base_init_wrapper(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { mp_obj_instance_t *self = MP_OBJ_TO_PTR(pos_args[0]); @@ -96,7 +98,8 @@ static mp_obj_t native_base_init_wrapper(size_t n_args, const mp_obj_t *pos_args pos_args++; n_args--; - mp_obj_t *args2 = m_new(mp_obj_t, n_args + 2 * n_kw); + // CIRCUITPY-CHANGE + mp_obj_t *args2 = m_malloc_items(n_args + 2 * n_kw); // copy in args memcpy(args2, pos_args, n_args * sizeof(mp_obj_t)); // copy in kwargs @@ -109,7 +112,7 @@ static mp_obj_t native_base_init_wrapper(size_t n_args, const mp_obj_t *pos_args return mp_const_none; } -static MP_DEFINE_CONST_FUN_OBJ_KW(native_base_init_wrapper_obj, 1, native_base_init_wrapper); +MP_DEFINE_CONST_FUN_OBJ_KW(mp_native_base_init_wrapper_obj, 1, native_base_init_wrapper); #if !MICROPY_CPYTHON_COMPAT static @@ -123,7 +126,7 @@ mp_obj_instance_t *mp_obj_new_instance(const mp_obj_type_t *class, const mp_obj_ // object. It doesn't matter which object, so long as it can be uniquely // distinguished from a native class that is initialised. if (num_native_bases != 0) { - o->subobj[0] = MP_OBJ_FROM_PTR(&native_base_init_wrapper_obj); + o->subobj[0] = MP_OBJ_FROM_PTR(&mp_native_base_init_wrapper_obj); } return o; } @@ -134,7 +137,7 @@ mp_obj_instance_t *mp_obj_new_instance(const mp_obj_type_t *class, const mp_obj_ // code so it must call this method to ensure that the given object has been __init__'d and is // valid. void mp_obj_assert_native_inited(mp_obj_t native_object) { - if (native_object == MP_OBJ_FROM_PTR(&native_base_init_wrapper_obj)) { + if (native_object == MP_OBJ_FROM_PTR(&mp_native_base_init_wrapper_obj)) { mp_raise_NotImplementedError(MP_ERROR_TEXT("Call super().__init__() before accessing native object.")); } } @@ -340,7 +343,8 @@ static mp_obj_t mp_obj_instance_make_new(const mp_obj_type_t *self, size_t n_arg mp_obj_t args2[1] = {MP_OBJ_FROM_PTR(self)}; new_ret = mp_call_function_n_kw(init_fn[0], 1, 0, args2); } else { - mp_obj_t *args2 = m_new(mp_obj_t, 1 + n_args + 2 * n_kw); + // CIRCUITPY-CHANGE + mp_obj_t *args2 = m_malloc_items(1 + n_args + 2 * n_kw); args2[0] = MP_OBJ_FROM_PTR(self); memcpy(args2 + 1, args, (n_args + 2 * n_kw) * sizeof(mp_obj_t)); new_ret = mp_call_function_n_kw(init_fn[0], n_args + 1, n_kw, args2); @@ -371,7 +375,8 @@ static mp_obj_t mp_obj_instance_make_new(const mp_obj_type_t *self, size_t n_arg if (n_args == 0 && n_kw == 0) { init_ret = mp_call_method_n_kw(0, 0, init_fn); } else { - mp_obj_t *args2 = m_new(mp_obj_t, 2 + n_args + 2 * n_kw); + // CIRCUITPY-CHANGE + mp_obj_t *args2 = m_malloc_items(2 + n_args + 2 * n_kw); args2[0] = init_fn[0]; args2[1] = init_fn[1]; memcpy(args2 + 2, args, (n_args + 2 * n_kw) * sizeof(mp_obj_t)); @@ -390,7 +395,7 @@ static mp_obj_t mp_obj_instance_make_new(const mp_obj_type_t *self, size_t n_arg // If the type had a native base that was not explicitly initialised // (constructed) by the Python __init__() method then construct it now. - if (native_base != NULL && o->subobj[0] == MP_OBJ_FROM_PTR(&native_base_init_wrapper_obj)) { + if (native_base != NULL && o->subobj[0] == MP_OBJ_FROM_PTR(&mp_native_base_init_wrapper_obj)) { o->subobj[0] = MP_OBJ_TYPE_GET_SLOT(native_base, make_new)(native_base, n_args, n_kw, args); } @@ -685,6 +690,13 @@ static void mp_obj_instance_load_attr(mp_obj_t self_in, qstr attr, mp_obj_t *des // try __getattr__ if (attr != MP_QSTR___getattr__) { + #if MICROPY_PY_DESCRIPTORS + // With descriptors enabled, don't delegate lookups of __get__/__set__/__delete__/__set_name__. + if (attr == MP_QSTR___get__ || attr == MP_QSTR___set__ || attr == MP_QSTR___delete__ || attr == MP_QSTR___set_name__) { + return; + } + #endif + #if MICROPY_PY_DELATTR_SETATTR // If the requested attr is __setattr__/__delattr__ then don't delegate the lookup // to __getattr__. If we followed CPython's behaviour then __setattr__/__delattr__ @@ -904,7 +916,8 @@ mp_obj_t mp_obj_instance_call(mp_obj_t self_in, size_t n_args, size_t n_kw, cons #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE mp_raise_TypeError(MP_ERROR_TEXT("object not callable")); #else - mp_raise_TypeError_varg(MP_ERROR_TEXT("'%q' object is not callable"), + // CIRCUITPY-CHANGE: use more specific raise + mp_raise_TypeError_varg(MP_ERROR_TEXT("'%q' object isn't callable"), mp_obj_get_type_qstr(self_in)); #endif } @@ -984,7 +997,7 @@ static bool check_for_special_accessors(mp_obj_t key, mp_obj_t value) { #endif #if MICROPY_PY_DESCRIPTORS static const uint8_t to_check[] = { - MP_QSTR___get__, MP_QSTR___set__, MP_QSTR___delete__, + MP_QSTR___get__, MP_QSTR___set__, MP_QSTR___delete__, // not needed for MP_QSTR___set_name__ though }; for (size_t i = 0; i < MP_ARRAY_SIZE(to_check); ++i) { mp_obj_t dest_temp[2]; @@ -998,10 +1011,52 @@ static bool check_for_special_accessors(mp_obj_t key, mp_obj_t value) { } #endif +#if MICROPY_PY_DESCRIPTORS +// Shared data layout for the __set_name__ call and a linked list of calls to be made. +typedef union _setname_list_t setname_list_t; +union _setname_list_t { + mp_obj_t call[4]; + struct { + mp_obj_t _meth; + mp_obj_t _self; + setname_list_t *next; // can use the "owner" argument position temporarily for the linked list + mp_obj_t _name; + }; +}; + +// Append any `__set_name__` method on `value` to the setname list, with its per-attr args +static setname_list_t *setname_maybe_bind_append(setname_list_t *tail, mp_obj_t name, mp_obj_t value) { + // make certain our type-punning is safe: + MP_STATIC_ASSERT_NONCONSTEXPR(offsetof(setname_list_t, next) == offsetof(setname_list_t, call[2])); + + // tail is a blank list entry + mp_load_method_maybe(value, MP_QSTR___set_name__, tail->call); + if (tail->call[1] != MP_OBJ_NULL) { + // Each time a __set_name__ is found, leave it in-place in the former tail and allocate a new tail + tail->next = m_new_obj(setname_list_t); + tail->next->next = NULL; + tail->call[3] = name; + return tail->next; + } else { + return tail; + } +} + +// Execute the captured `__set_name__` calls, destroying the setname list in the process. +static inline void setname_consume_call_all(setname_list_t *head, mp_obj_t owner) { + setname_list_t *next; + while ((next = head->next) != NULL) { + head->call[2] = owner; + mp_call_method_n_kw(2, 0, head->call); + head = next; + } +} +#endif + static void type_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { (void)kind; mp_obj_type_t *self = MP_OBJ_TO_PTR(self_in); - mp_printf(print, "", self->name); + mp_printf(print, "", (qstr)self->name); } static mp_obj_t type_make_new(const mp_obj_type_t *type_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { @@ -1031,11 +1086,10 @@ static mp_obj_t type_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp if (!MP_OBJ_TYPE_HAS_SLOT(self, make_new)) { #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE - // CIRCUITPY-CHANGE: error message change - mp_raise_TypeError(MP_ERROR_TEXT("cannot create instance")); + mp_raise_TypeError(MP_ERROR_TEXT("can't create instance")); #else - // CIRCUITPY-CHANGE: error message change - mp_raise_TypeError_varg(MP_ERROR_TEXT("cannot create '%q' instances"), self->name); + // CIRCUITPY-CHANGE: more specific mp_raise + mp_raise_TypeError_varg(MP_ERROR_TEXT("can't create '%q' instances"), self->name); #endif } @@ -1148,7 +1202,7 @@ MP_DEFINE_CONST_OBJ_TYPE( attr, type_attr ); -mp_obj_t mp_obj_new_type(qstr name, mp_obj_t bases_tuple, mp_obj_t locals_dict) { +static mp_obj_t mp_obj_new_type(qstr name, mp_obj_t bases_tuple, mp_obj_t locals_dict) { // Verify input objects have expected type if (!mp_obj_is_type(bases_tuple, &mp_type_tuple)) { mp_raise_TypeError(NULL); @@ -1176,12 +1230,11 @@ 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 (!MP_OBJ_TYPE_HAS_SLOT(t, make_new)) { #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE - // CIRCUITPY-CHANGE: error message change - mp_raise_TypeError(MP_ERROR_TEXT("type is not an acceptable base type")); + mp_raise_TypeError(MP_ERROR_TEXT("type isn't an acceptable base type")); #else - // CIRCUITPY-CHANGE: error message change + // CIRCUITPY-CHANGE: more specific mp_raise mp_raise_TypeError_varg( - MP_ERROR_TEXT("type '%q' is not an acceptable base type"), t->name); + MP_ERROR_TEXT("type '%q' isn't an acceptable base type"), t->name); #endif } #if ENABLE_SPECIAL_ACCESSORS @@ -1191,6 +1244,7 @@ mp_obj_t mp_obj_new_type(qstr name, mp_obj_t bases_tuple, mp_obj_t locals_dict) base_flags |= t->flags & MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS; if (mp_obj_is_instance_type(t)) { t->flags |= MP_TYPE_FLAG_IS_SUBCLASSED; + base_flags |= t->flags & MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS; } #endif } @@ -1241,20 +1295,38 @@ mp_obj_t mp_obj_new_type(qstr name, mp_obj_t bases_tuple, mp_obj_t locals_dict) } } + #if MICROPY_PY_DESCRIPTORS + // To avoid any dynamic allocations when no __set_name__ exists, + // the head of this list is kept on the stack (marked blank with `next = NULL`). + setname_list_t setname_list = { .next = NULL }; + setname_list_t *setname_tail = &setname_list; + #endif + #if ENABLE_SPECIAL_ACCESSORS - // Check if the class has any special accessor methods - if (!(o->flags & MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS)) { - for (size_t i = 0; i < locals_ptr->map.alloc; i++) { - if (mp_map_slot_is_filled(&locals_ptr->map, i)) { - const mp_map_elem_t *elem = &locals_ptr->map.table[i]; - if (check_for_special_accessors(elem->key, elem->value)) { - o->flags |= MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS; - break; - } + // Check if the class has any special accessor methods, + // and accumulate bound __set_name__ methods that need to be called + for (size_t i = 0; i < locals_ptr->map.alloc; i++) { + #if !MICROPY_PY_DESCRIPTORS + // __set_name__ needs to scan the entire locals map, can't early-terminate + if (o->flags & MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS) { + break; + } + #endif + + if (mp_map_slot_is_filled(&locals_ptr->map, i)) { + const mp_map_elem_t *elem = &locals_ptr->map.table[i]; + + if (!(o->flags & MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS) // elidable when the early-termination check is enabled + && check_for_special_accessors(elem->key, elem->value)) { + o->flags |= MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS; } + + #if MICROPY_PY_DESCRIPTORS + setname_tail = setname_maybe_bind_append(setname_tail, elem->key, elem->value); + #endif } } - #endif + #endif // ENABLE_SPECIAL_ACCESSORS const mp_obj_type_t *native_base; size_t num_native_bases = instance_count_native_bases(o, &native_base); @@ -1262,8 +1334,7 @@ mp_obj_t mp_obj_new_type(qstr name, mp_obj_t bases_tuple, mp_obj_t locals_dict) mp_raise_TypeError(MP_ERROR_TEXT("multiple bases have instance lay-out conflict")); } - mp_map_t *locals_map = &MP_OBJ_TYPE_GET_SLOT(o, locals_dict)->map; - mp_map_elem_t *elem = mp_map_lookup(locals_map, MP_OBJ_NEW_QSTR(MP_QSTR___new__), MP_MAP_LOOKUP); + mp_map_elem_t *elem = mp_map_lookup(&locals_ptr->map, MP_OBJ_NEW_QSTR(MP_QSTR___new__), MP_MAP_LOOKUP); if (elem != NULL) { // __new__ slot exists; check if it is a function if (mp_obj_is_fun(elem->value)) { @@ -1272,6 +1343,10 @@ mp_obj_t mp_obj_new_type(qstr name, mp_obj_t bases_tuple, mp_obj_t locals_dict) } } + #if MICROPY_PY_DESCRIPTORS + setname_consume_call_all(&setname_list, MP_OBJ_FROM_PTR(o)); + #endif + return MP_OBJ_FROM_PTR(o); } @@ -1299,10 +1374,20 @@ static mp_obj_t super_make_new(const mp_obj_type_t *type_in, size_t n_args, size // 0 arguments are turned into 2 in the compiler // 1 argument is not yet implemented mp_arg_check_num(n_args, n_kw, 2, 2, false); + + // CIRCUITPY-CHANGE: check type of first arg if (!mp_obj_is_type(args[0], &mp_type_type)) { - // CIRCUITPY-CHANGE: error message mp_raise_TypeError(MP_ERROR_TEXT("first argument to super() must be type")); } + + // Per CPython: "If the second argument is an object, isinstance(obj, type) must be true. + // If the second argument is a type, issubclass(type2, type) must be true (this is useful for classmethods)." + const mp_obj_type_t *second_arg_type = mp_obj_get_type(args[1]); + mp_obj_t second_arg_obj = second_arg_type == &mp_type_type ? args[1] : MP_OBJ_FROM_PTR(second_arg_type); + if (mp_obj_is_subclass(second_arg_obj, args[0]) == mp_const_false) { + mp_raise_TypeError(NULL); + } + mp_obj_super_t *o = m_new_obj(mp_obj_super_t); *o = (mp_obj_super_t) {{type_in}, args[0], args[1]}; return MP_OBJ_FROM_PTR(o); @@ -1362,7 +1447,7 @@ static void super_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { if (dest[0] != MP_OBJ_NULL) { if (dest[0] == MP_OBJ_SENTINEL) { // Looked up native __init__ so defer to it - dest[0] = MP_OBJ_FROM_PTR(&native_base_init_wrapper_obj); + dest[0] = MP_OBJ_FROM_PTR(&mp_native_base_init_wrapper_obj); dest[1] = self->obj; // CIRCUITPY-CHANGE: better support for properties } else { @@ -1513,13 +1598,15 @@ mp_obj_t mp_obj_cast_to_native_base(mp_obj_t self_in, mp_const_obj_t native_type /******************************************************************************/ // staticmethod and classmethod types (probably should go in a different file) -static mp_obj_t static_class_method_make_new(const mp_obj_type_t *self, size_t n_args, size_t n_kw, const mp_obj_t *args) { - assert(self == &mp_type_staticmethod || self == &mp_type_classmethod); +// CIRCUITPY-CHANGE: better arg name +static mp_obj_t static_class_method_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { + assert(type == &mp_type_staticmethod || type == &mp_type_classmethod); mp_arg_check_num(n_args, n_kw, 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]}; + // CIRCUITPY-CHANGE: Use mp_obj_malloc because it is a Python object + mp_obj_static_class_method_t *o = mp_obj_malloc(mp_obj_static_class_method_t, type); + o->fun = args[0]; return MP_OBJ_FROM_PTR(o); } diff --git a/py/objtype.h b/py/objtype.h index 07a8e1cffd9..098b7699da9 100644 --- a/py/objtype.h +++ b/py/objtype.h @@ -55,4 +55,7 @@ mp_obj_t mp_obj_instance_getiter(mp_obj_t self_in, mp_obj_iter_buf_t *iter_buf); // CIRCUITPY-CHANGE: addition void mp_obj_assert_native_inited(mp_obj_t native_object); +// upstream v1.28: exposed so py/objexcept.c can reference it directly +MP_DECLARE_CONST_FUN_OBJ_KW(mp_native_base_init_wrapper_obj); + #endif // MICROPY_INCLUDED_PY_OBJTYPE_H diff --git a/py/objzip.c b/py/objzip.c index dd2b39ee071..300448b665f 100644 --- a/py/objzip.c +++ b/py/objzip.c @@ -50,19 +50,20 @@ static mp_obj_t zip_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_ static mp_obj_t zip_iternext(mp_obj_t self_in) { mp_check_self(mp_obj_is_type(self_in, &mp_type_zip)); mp_obj_zip_t *self = MP_OBJ_TO_PTR(self_in); - if (self->n_iters == 0) { - return MP_OBJ_STOP_ITERATION; - } - mp_obj_tuple_t *tuple = MP_OBJ_TO_PTR(mp_obj_new_tuple(self->n_iters, NULL)); - + mp_obj_tuple_t *tuple = NULL; for (size_t i = 0; i < self->n_iters; i++) { mp_obj_t next = mp_iternext(self->iters[i]); if (next == MP_OBJ_STOP_ITERATION) { - mp_obj_tuple_del(MP_OBJ_FROM_PTR(tuple)); return MP_OBJ_STOP_ITERATION; } + if (tuple == NULL) { + tuple = MP_OBJ_TO_PTR(mp_obj_new_tuple(self->n_iters, NULL)); + } tuple->items[i] = next; } + if (tuple == NULL) { + return MP_OBJ_STOP_ITERATION; + } return MP_OBJ_FROM_PTR(tuple); } diff --git a/py/parse.c b/py/parse.c index 9721532afd6..203527c782d 100644 --- a/py/parse.c +++ b/py/parse.c @@ -341,18 +341,34 @@ static uint8_t peek_rule(parser_t *parser, size_t n) { } #endif -bool mp_parse_node_get_int_maybe(mp_parse_node_t pn, mp_obj_t *o) { +#if MICROPY_COMP_CONST_FOLDING || MICROPY_EMIT_INLINE_ASM +static bool mp_parse_node_get_number_maybe(mp_parse_node_t pn, mp_obj_t *o) { if (MP_PARSE_NODE_IS_SMALL_INT(pn)) { *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; *o = mp_parse_node_extract_const_object(pns); - return mp_obj_is_int(*o); + return mp_obj_is_int(*o) + #if MICROPY_COMP_CONST_FLOAT + || mp_obj_is_float(*o) + #endif + ; } else { return false; } } +#endif + +#if MICROPY_EMIT_INLINE_ASM +bool mp_parse_node_get_int_maybe(mp_parse_node_t pn, mp_obj_t *o) { + return mp_parse_node_get_number_maybe(pn, o) + #if MICROPY_COMP_CONST_FLOAT + && mp_obj_is_int(*o) + #endif + ; +} +#endif #if MICROPY_COMP_CONST_TUPLE || MICROPY_COMP_CONST static bool mp_parse_node_is_const(mp_parse_node_t pn) { @@ -480,10 +496,10 @@ void mp_parse_node_print(const mp_print_t *print, mp_parse_node_t pn, size_t ind uintptr_t arg = MP_PARSE_NODE_LEAF_ARG(pn); switch (MP_PARSE_NODE_LEAF_KIND(pn)) { case MP_PARSE_NODE_ID: - mp_printf(print, "id(%s)\n", qstr_str(arg)); + mp_printf(print, "id(%q)\n", (qstr)arg); break; case MP_PARSE_NODE_STRING: - mp_printf(print, "str(%s)\n", qstr_str(arg)); + mp_printf(print, "str(%q)\n", (qstr)arg); break; default: assert(MP_PARSE_NODE_LEAF_KIND(pn) == MP_PARSE_NODE_TOKEN); @@ -647,18 +663,32 @@ static const mp_rom_map_elem_t mp_constants_table[] = { #if MICROPY_PY_UCTYPES { MP_ROM_QSTR(MP_QSTR_uctypes), MP_ROM_PTR(&mp_module_uctypes) }, #endif + #if MICROPY_PY_BUILTINS_FLOAT && MICROPY_PY_MATH && MICROPY_COMP_CONST_FLOAT + { MP_ROM_QSTR(MP_QSTR_math), MP_ROM_PTR(&mp_module_math) }, + #endif // Extra constants as defined by a port MICROPY_PORT_CONSTANTS }; static MP_DEFINE_CONST_MAP(mp_constants_map, mp_constants_table); #endif -// CIRCUITPY-CHANGE: avoid compiler warning -#if defined(MICROPY_COMP_CONST_FOLDING_COMPILER_WORKAROUND) && MICROPY_COMP_CONST_FOLDING_COMPILER_WORKAROUND -// Some versions of the xtensa-esp32-elf-gcc compiler generate wrong code if this -// function is static, so provide a hook for them to work around this problem. -MP_NOINLINE -#endif +static bool binary_op_maybe(mp_binary_op_t op, mp_obj_t lhs, mp_obj_t rhs, mp_obj_t *res) { + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + mp_obj_t tmp = mp_binary_op(op, lhs, rhs); + nlr_pop(); + #if MICROPY_PY_BUILTINS_COMPLEX + if (mp_obj_is_type(tmp, &mp_type_complex)) { + return false; + } + #endif + *res = tmp; + return true; + } else { + return false; + } +} + static bool fold_logical_constants(parser_t *parser, uint8_t rule_id, size_t *num_args) { if (rule_id == RULE_or_test || rule_id == RULE_and_test) { @@ -717,7 +747,7 @@ static bool fold_logical_constants(parser_t *parser, uint8_t rule_id, size_t *nu } static bool fold_constants(parser_t *parser, uint8_t rule_id, size_t num_args) { - // this code does folding of arbitrary integer expressions, eg 1 + 2 * 3 + 4 + // this code does folding of arbitrary numeric expressions, eg 1 + 2 * 3 + 4 // it does not do partial folding, eg 1 + 2 + x -> 3 + x mp_obj_t arg0; @@ -727,7 +757,7 @@ static bool fold_constants(parser_t *parser, uint8_t rule_id, size_t num_args) { || rule_id == RULE_power) { // folding for binary ops: | ^ & ** mp_parse_node_t pn = peek_result(parser, num_args - 1); - if (!mp_parse_node_get_int_maybe(pn, &arg0)) { + if (!mp_parse_node_get_number_maybe(pn, &arg0)) { return false; } mp_binary_op_t op; @@ -743,58 +773,45 @@ static bool fold_constants(parser_t *parser, uint8_t rule_id, size_t num_args) { for (ssize_t i = num_args - 2; i >= 0; --i) { pn = peek_result(parser, i); mp_obj_t arg1; - if (!mp_parse_node_get_int_maybe(pn, &arg1)) { + if (!mp_parse_node_get_number_maybe(pn, &arg1)) { return false; } - if (op == MP_BINARY_OP_POWER && mp_obj_int_sign(arg1) < 0) { - // ** can't have negative rhs + if (!binary_op_maybe(op, arg0, arg1, &arg0)) { return false; } - arg0 = mp_binary_op(op, arg0, arg1); } } else if (rule_id == RULE_shift_expr || 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)) { + if (!mp_parse_node_get_number_maybe(pn, &arg0)) { return false; } for (ssize_t i = num_args - 2; i >= 1; i -= 2) { pn = peek_result(parser, i - 1); mp_obj_t arg1; - if (!mp_parse_node_get_int_maybe(pn, &arg1)) { + if (!mp_parse_node_get_number_maybe(pn, &arg1)) { return false; } mp_token_kind_t tok = MP_PARSE_NODE_LEAF_ARG(peek_result(parser, i)); - if (tok == MP_TOKEN_OP_AT || tok == MP_TOKEN_OP_SLASH) { - // Can't fold @ or / - return false; - } mp_binary_op_t op = MP_BINARY_OP_LSHIFT + (tok - MP_TOKEN_OP_DBL_LESS); - int rhs_sign = mp_obj_int_sign(arg1); - if (op <= MP_BINARY_OP_RSHIFT) { - // << and >> can't have negative rhs - if (rhs_sign < 0) { - return false; - } - } else if (op >= MP_BINARY_OP_FLOOR_DIVIDE) { - // % and // can't have zero rhs - if (rhs_sign == 0) { - return false; - } + if (!binary_op_maybe(op, arg0, arg1, &arg0)) { + return false; } - arg0 = mp_binary_op(op, arg0, arg1); } } else if (rule_id == RULE_factor_2) { // folding for unary ops: + - ~ mp_parse_node_t pn = peek_result(parser, 0); - if (!mp_parse_node_get_int_maybe(pn, &arg0)) { + if (!mp_parse_node_get_number_maybe(pn, &arg0)) { return false; } mp_token_kind_t tok = MP_PARSE_NODE_LEAF_ARG(peek_result(parser, 1)); mp_unary_op_t op; if (tok == MP_TOKEN_OP_TILDE) { + if (!mp_obj_is_int(arg0)) { + return false; + } op = MP_UNARY_OP_INVERT; } else { assert(tok == MP_TOKEN_OP_PLUS || tok == MP_TOKEN_OP_MINUS); // should be @@ -808,50 +825,54 @@ static bool fold_constants(parser_t *parser, uint8_t rule_id, size_t num_args) { 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))) { - // this node is of the form = + // this node is of the form = or : = 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) - ) { - // code to assign dynamic constants: id = const(value) - - // get the id - 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]; - if (!mp_parse_node_is_const(pn_value)) { - mp_obj_t exc = mp_obj_new_exception_msg(&mp_type_SyntaxError, - MP_ERROR_TEXT("not a constant")); - mp_obj_exception_add_traceback(exc, parser->lexer->source_name, - ((mp_parse_node_struct_t *)pn1)->source_line, MP_QSTRnull); - nlr_raise(exc); - } - mp_obj_t value = mp_parse_node_convert_to_obj(pn_value); - - // store the value in the table of dynamic constants - mp_map_elem_t *elem = mp_map_lookup(&parser->consts, MP_OBJ_NEW_QSTR(id), MP_MAP_LOOKUP_ADD_IF_NOT_FOUND); - assert(elem->value == MP_OBJ_NULL); - elem->value = value; - - // If the constant starts with an underscore then treat it as a private - // variable and don't emit any code to store the value to the id. - if (qstr_str(id)[0] == '_') { - pop_result(parser); // pop const(value) - pop_result(parser); // pop id - push_result_rule(parser, 0, RULE_pass_stmt, 0); // replace with "pass" - return true; + if (MP_PARSE_NODE_IS_ID(pn0)) { + if (MP_PARSE_NODE_IS_STRUCT_KIND(pn1, RULE_annassign)) { + // extract annassign rhs + pn1 = ((mp_parse_node_struct_t *)pn1)->nodes[1]; } + if (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)) { + // code to assign dynamic constants: id = const(value) + + // get the id + 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]; + if (!mp_parse_node_is_const(pn_value)) { + mp_obj_t exc = mp_obj_new_exception_msg(&mp_type_SyntaxError, + MP_ERROR_TEXT("not a constant")); + mp_obj_exception_add_traceback(exc, parser->lexer->source_name, + ((mp_parse_node_struct_t *)pn1)->source_line, MP_QSTRnull); + nlr_raise(exc); + } + mp_obj_t value = mp_parse_node_convert_to_obj(pn_value); + + // store the value in the table of dynamic constants + mp_map_elem_t *elem = mp_map_lookup(&parser->consts, MP_OBJ_NEW_QSTR(id), MP_MAP_LOOKUP_ADD_IF_NOT_FOUND); + assert(elem->value == MP_OBJ_NULL); + elem->value = value; + + // If the constant starts with an underscore then treat it as a private + // variable and don't emit any code to store the value to the id. + if (qstr_str(id)[0] == '_') { + pop_result(parser); // pop const(value) + pop_result(parser); // pop id + push_result_rule(parser, 0, RULE_pass_stmt, 0); // replace with "pass" + return true; + } - // replace const(value) with value - pop_result(parser); - push_result_node(parser, pn_value); + // replace const(value) with value + pop_result(parser); + push_result_node(parser, pn_value); - // finished folding this assignment, but we still want it to be part of the tree - return false; + // finished folding this assignment, but we still want it to be part of the tree + return false; + } } } return false; @@ -866,7 +887,7 @@ static bool fold_constants(parser_t *parser, uint8_t rule_id, size_t num_args) { return false; } // id1.id2 - // look it up in constant table, see if it can be replaced with an integer + // look it up in constant table, see if it can be replaced with an integer or a float 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); @@ -877,7 +898,7 @@ static bool fold_constants(parser_t *parser, uint8_t rule_id, size_t num_args) { } mp_obj_t dest[2]; mp_load_method_maybe(elem->value, q_attr, dest); - if (!(dest[0] != MP_OBJ_NULL && mp_obj_is_int(dest[0]) && dest[1] == MP_OBJ_NULL)) { + if (!(dest[0] != MP_OBJ_NULL && (mp_obj_is_int(dest[0]) || mp_obj_is_float(dest[0])) && dest[1] == MP_OBJ_NULL)) { return false; } arg0 = dest[0]; @@ -1378,9 +1399,6 @@ mp_parse_tree_t mp_parse(mp_lexer_t *lex, mp_parse_input_kind_t input_kind) { } else if (lex->tok_kind == MP_TOKEN_MALFORMED_FSTRING) { exc = mp_obj_new_exception_msg(&mp_type_SyntaxError, MP_ERROR_TEXT("malformed f-string")); - } else if (lex->tok_kind == MP_TOKEN_FSTRING_RAW) { - exc = mp_obj_new_exception_msg(&mp_type_SyntaxError, - MP_ERROR_TEXT("raw f-strings are not supported")); #endif } else { exc = mp_obj_new_exception_msg(&mp_type_SyntaxError, diff --git a/py/parsenum.c b/py/parsenum.c index 67ac12d1907..c52f040e1a2 100644 --- a/py/parsenum.c +++ b/py/parsenum.c @@ -28,6 +28,7 @@ #include #include "py/runtime.h" +#include "py/misc.h" #include "py/parsenumbase.h" #include "py/parsenum.h" #include "py/smallint.h" @@ -36,7 +37,7 @@ #include #endif -static NORETURN void raise_exc(mp_obj_t exc, mp_lexer_t *lex) { +static MP_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) { @@ -46,6 +47,27 @@ static NORETURN void raise_exc(mp_obj_t exc, mp_lexer_t *lex) { nlr_raise(exc); } +#if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_LONGLONG +// For the common small integer parsing case, we parse directly to mp_int_t and +// check that the value doesn't overflow a smallint (in which case we fail over +// to bigint parsing if supported) +typedef mp_int_t parsed_int_t; + +#define PARSED_INT_MUL_OVERFLOW mp_mul_mp_int_t_overflow +#define PARSED_INT_FITS MP_SMALL_INT_FITS +#else +// In the special case where bigint support is long long, we save code size by +// parsing directly to long long and then return either a bigint or smallint +// from the same result. +// +// To avoid pulling in (slow) signed 64-bit math routines we do the initial +// parsing to an unsigned long long and only convert to signed at the end. +typedef unsigned long long parsed_int_t; + +#define PARSED_INT_MUL_OVERFLOW mp_mul_ull_overflow +#define PARSED_INT_FITS(I) ((I) <= (unsigned long long)LLONG_MAX + 1) +#endif + mp_obj_t mp_parse_num_integer(const char *restrict str_, size_t len, int base, mp_lexer_t *lex) { const byte *restrict str = (const byte *)str_; const byte *restrict top = str + len; @@ -77,7 +99,7 @@ mp_obj_t mp_parse_num_integer(const char *restrict str_, size_t len, int base, m str += mp_parse_num_base((const char *)str, top - str, &base); // string should be an integer number - mp_int_t int_val = 0; + parsed_int_t parsed_val = 0; const byte *restrict str_val_start = str; for (; str < top; str++) { // get next digit as a value @@ -99,25 +121,32 @@ mp_obj_t mp_parse_num_integer(const char *restrict str_, size_t len, int base, m break; } - // add next digi and check for overflow - if (mp_small_int_mul_overflow(int_val, base)) { + // add next digit and check for overflow + if (PARSED_INT_MUL_OVERFLOW(parsed_val, base, &parsed_val)) { goto overflow; } - int_val = int_val * base + dig; - if (!MP_SMALL_INT_FITS(int_val)) { + parsed_val += dig; + if (!PARSED_INT_FITS(parsed_val)) { goto overflow; } } - // negate value if needed - if (neg) { - int_val = -int_val; + #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_LONGLONG + // The PARSED_INT_FITS check above ensures parsed_val fits in small int representation + ret_val = MP_OBJ_NEW_SMALL_INT(neg ? (-parsed_val) : parsed_val); +have_ret_val: + #else + // The PARSED_INT_FITS check above ensures parsed_val won't overflow signed long long + long long signed_val = -parsed_val; + if (!neg) { + if (signed_val == LLONG_MIN) { + goto overflow; + } + signed_val = -signed_val; } + ret_val = mp_obj_new_int_from_ll(signed_val); // Could be large or small int + #endif - // create the small int - ret_val = MP_OBJ_NEW_SMALL_INT(int_val); - -have_ret_val: // check we parsed something if (str == str_val_start) { goto value_error; @@ -136,6 +165,7 @@ mp_obj_t mp_parse_num_integer(const char *restrict str_, size_t len, int base, m return ret_val; overflow: + #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_LONGLONG // reparse using long int { const char *s2 = (const char *)str_val_start; @@ -143,6 +173,9 @@ mp_obj_t mp_parse_num_integer(const char *restrict str_, size_t len, int base, m str = (const byte *)s2; goto have_ret_val; } + #else + mp_raise_msg(&mp_type_OverflowError, MP_ERROR_TEXT("result overflows long long storage")); + #endif value_error: { @@ -152,13 +185,13 @@ mp_obj_t mp_parse_num_integer(const char *restrict str_, size_t len, int base, m 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, - MP_ERROR_TEXT("invalid syntax for integer with base %d"), base); + MP_ERROR_TEXT("invalid syntax for integer with base %d"), base == 1 ? 0 : 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_printf(&print, "invalid syntax for integer with base %d: ", base == 1 ? 0 : 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_utf8_vstr(&vstr)); @@ -167,6 +200,8 @@ mp_obj_t mp_parse_num_integer(const char *restrict str_, size_t len, int base, m } } +#if MICROPY_PY_BUILTINS_FLOAT + enum { REAL_IMAG_STATE_START = 0, REAL_IMAG_STATE_HAVE_REAL = 1, @@ -179,41 +214,175 @@ typedef enum { PARSE_DEC_IN_EXP, } parse_dec_in_t; -#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 -// 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). +// MANTISSA_MAX is used to retain precision while not overflowing mantissa +#define MANTISSA_MAX (sizeof(mp_large_float_uint_t) == 8 ? 0x1999999999999998ULL : 0x19999998U) + +// MAX_EXACT_POWER_OF_5 is the largest value of x so that 5^x can be stored exactly in a float #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_FLOAT -#define DEC_VAL_MAX 1e20F -#define SMALL_NORMAL_VAL (1e-37F) -#define SMALL_NORMAL_EXP (-37) -#define EXACT_POWER_OF_10 (9) +#define MAX_EXACT_POWER_OF_5 (10) #elif MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE -#define DEC_VAL_MAX 1e200 -#define SMALL_NORMAL_VAL (1e-307) -#define SMALL_NORMAL_EXP (-307) -#define EXACT_POWER_OF_10 (22) +#define MAX_EXACT_POWER_OF_5 (22) #endif +// Helper to compute `num * (10.0 ** dec_exp)` +mp_large_float_t mp_decimal_exp(mp_large_float_t num, int dec_exp) { + // CIRCUITPY-CHANGE: ignore float equal warning + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wfloat-equal" + if (dec_exp == 0 || num == (mp_large_float_t)(0.0)) { + return num; + } + #pragma GCC diagnostic pop + + #if MICROPY_FLOAT_FORMAT_IMPL == MICROPY_FLOAT_FORMAT_IMPL_EXACT + + // If the assert below fails, it means you have chosen MICROPY_FLOAT_FORMAT_IMPL_EXACT + // manually on a platform where `larger floats` are not supported, which would + // result in inexact conversions. To fix this issue, change your `mpconfigport.h` + // and select MICROPY_FLOAT_FORMAT_IMPL_APPROX instead + assert(sizeof(mp_large_float_t) > sizeof(mp_float_t)); + + // Perform power using simple multiplications, to avoid + // dependency to higher-precision pow() function + int neg_exp = (dec_exp < 0); + if (neg_exp) { + dec_exp = -dec_exp; + } + mp_large_float_t res = num; + mp_large_float_t expo = (mp_large_float_t)10.0; + while (dec_exp) { + if (dec_exp & 1) { + if (neg_exp) { + res /= expo; + } else { + res *= expo; + } + } + dec_exp >>= 1; + if (dec_exp) { + expo *= expo; + } + } + return res; + + #else + // MICROPY_FLOAT_FORMAT_IMPL != MICROPY_FLOAT_FORMAT_IMPL_EXACT + + mp_float_union_t res = {num}; + // Multiply first by (2.0 ** dec_exp) via the exponent + // - this will ensure that the result of `pow()` is always in mp_float_t range + // when the result is expected to be in mp_float_t range (e.g. during format) + // - we don't need to care about p.exp overflow, as (5.0 ** dec_exp) will anyway + // force the final result toward the proper edge if needed (0.0 or inf) + res.p.exp += dec_exp; + // Use positive exponents when they are more precise then negative + if (dec_exp < 0 && dec_exp >= -MAX_EXACT_POWER_OF_5) { + res.f /= MICROPY_FLOAT_C_FUN(pow)(5, -dec_exp); + } else { + res.f *= MICROPY_FLOAT_C_FUN(pow)(5, dec_exp); + } + return (mp_large_float_t)res.f; + + #endif +} + + // Break out inner digit accumulation routine to ease trailing zero deferral. -static void accept_digit(mp_float_t *p_dec_val, int dig, int *p_exp_extra, int in) { +static mp_large_float_uint_t accept_digit(mp_large_float_uint_t p_mantissa, unsigned int dig, int *p_exp_extra, int in) { // Core routine to ingest an additional digit. - if (*p_dec_val < DEC_VAL_MAX) { + if (p_mantissa < MANTISSA_MAX) { // dec_val won't overflow so keep accumulating - *p_dec_val = 10 * *p_dec_val + dig; if (in == PARSE_DEC_IN_FRAC) { --(*p_exp_extra); } + return 10u * p_mantissa + dig; } else { // dec_val might overflow and we anyway can't represent more digits // of precision, so ignore the digit and just adjust the exponent if (in == PARSE_DEC_IN_INTG) { ++(*p_exp_extra); } + return p_mantissa; + } +} + +// Helper to parse an unsigned decimal number into a mp_float_t +const char *mp_parse_float_internal(const char *str, size_t len, mp_float_t *res) { + const char *top = str + len; + + parse_dec_in_t in = PARSE_DEC_IN_INTG; + bool exp_neg = false; + mp_large_float_uint_t mantissa = 0; + int exp_val = 0; + int exp_extra = 0; + int trailing_zeros_intg = 0, trailing_zeros_frac = 0; + while (str < top) { + unsigned int dig = *str++; + if ('0' <= dig && dig <= '9') { + dig -= '0'; + if (in == PARSE_DEC_IN_EXP) { + // don't overflow exp_val when adding next digit, instead just truncate + // it and the resulting float will still be correct, either inf or 0.0 + // (use INT_MAX/2 to allow adding exp_extra at the end without overflow) + if (exp_val < (INT_MAX / 2 - 9) / 10) { + exp_val = 10 * exp_val + dig; + } + } else { + if (dig == 0 || mantissa >= MANTISSA_MAX) { + // Defer treatment of zeros in fractional part. If nothing comes afterwards, ignore them. + // Also, once we reach MANTISSA_MAX, treat every additional digit as a trailing zero. + if (in == PARSE_DEC_IN_INTG) { + ++trailing_zeros_intg; + } else { + ++trailing_zeros_frac; + } + } else { + // Time to un-defer any trailing zeros. Intg zeros first. + while (trailing_zeros_intg) { + mantissa = accept_digit(mantissa, 0, &exp_extra, PARSE_DEC_IN_INTG); + --trailing_zeros_intg; + } + while (trailing_zeros_frac) { + mantissa = accept_digit(mantissa, 0, &exp_extra, PARSE_DEC_IN_FRAC); + --trailing_zeros_frac; + } + mantissa = accept_digit(mantissa, dig, &exp_extra, in); + } + } + } else if (in == PARSE_DEC_IN_INTG && dig == '.') { + in = PARSE_DEC_IN_FRAC; + } else if (in != PARSE_DEC_IN_EXP && ((dig | 0x20) == 'e')) { + in = PARSE_DEC_IN_EXP; + if (str < top) { + if (str[0] == '+') { + str++; + } else if (str[0] == '-') { + str++; + exp_neg = true; + } + } + if (str == top) { + return NULL; + } + } else if (dig == '_') { + continue; + } else { + // unknown character + str--; + break; + } } + + // work out the exponent + if (exp_neg) { + exp_val = -exp_val; + } + exp_val += exp_extra + trailing_zeros_intg; + + // At this point, we just need to multiply the mantissa by its base 10 exponent. + *res = (mp_float_t)mp_decimal_exp(mantissa, exp_val); + + return str; } #endif // MICROPY_PY_BUILTINS_FLOAT @@ -227,13 +396,13 @@ mp_obj_t mp_parse_num_float(const char *str, size_t len, bool allow_imag, mp_lex const char *top = str + len; mp_float_t dec_val = 0; - bool dec_neg = false; #if MICROPY_PY_BUILTINS_COMPLEX unsigned int real_imag_state = REAL_IMAG_STATE_START; mp_float_t dec_real = 0; -parse_start: +parse_start:; #endif + bool dec_neg = false; // skip leading space for (; str < top && unichar_isspace(*str); str++) { @@ -252,109 +421,23 @@ mp_obj_t mp_parse_num_float(const char *str, size_t len, bool allow_imag, mp_lex const char *str_val_start = str; // determine what the string is - if (str < top && (str[0] | 0x20) == 'i') { - // string starts with 'i', should be 'inf' or 'infinity' (case insensitive) - if (str + 2 < top && (str[1] | 0x20) == 'n' && (str[2] | 0x20) == 'f') { - // inf - str += 3; - 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; - } - } - } else if (str < top && (str[0] | 0x20) == 'n') { - // string starts with 'n', should be 'nan' (case insensitive) - if (str + 2 < top && (str[1] | 0x20) == 'a' && (str[2] | 0x20) == 'n') { - // NaN - str += 3; - dec_val = MICROPY_FLOAT_C_FUN(nan)(""); + if (str + 2 < top && (str[0] | 0x20) == 'i' && (str[1] | 0x20) == 'n' && (str[2] | 0x20) == 'f') { + // 'inf' or 'infinity' (case insensitive) + str += 3; + 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; } + } else if (str + 2 < top && (str[0] | 0x20) == 'n' && (str[1] | 0x20) == 'a' && (str[2] | 0x20) == 'n') { + // 'nan' (case insensitive) + str += 3; + dec_val = MICROPY_FLOAT_C_FUN(nan)(""); } else { // string should be a decimal number - parse_dec_in_t in = PARSE_DEC_IN_INTG; - bool exp_neg = false; - int exp_val = 0; - int exp_extra = 0; - int trailing_zeros_intg = 0, trailing_zeros_frac = 0; - while (str < top) { - unsigned int dig = *str++; - if ('0' <= dig && dig <= '9') { - dig -= '0'; - if (in == PARSE_DEC_IN_EXP) { - // don't overflow exp_val when adding next digit, instead just truncate - // it and the resulting float will still be correct, either inf or 0.0 - // (use INT_MAX/2 to allow adding exp_extra at the end without overflow) - if (exp_val < (INT_MAX / 2 - 9) / 10) { - exp_val = 10 * exp_val + dig; - } - } else { - if (dig == 0 || dec_val >= DEC_VAL_MAX) { - // Defer treatment of zeros in fractional part. If nothing comes afterwards, ignore them. - // Also, once we reach DEC_VAL_MAX, treat every additional digit as a trailing zero. - if (in == PARSE_DEC_IN_INTG) { - ++trailing_zeros_intg; - } else { - ++trailing_zeros_frac; - } - } else { - // Time to un-defer any trailing zeros. Intg zeros first. - while (trailing_zeros_intg) { - accept_digit(&dec_val, 0, &exp_extra, PARSE_DEC_IN_INTG); - --trailing_zeros_intg; - } - while (trailing_zeros_frac) { - accept_digit(&dec_val, 0, &exp_extra, PARSE_DEC_IN_FRAC); - --trailing_zeros_frac; - } - accept_digit(&dec_val, dig, &exp_extra, in); - } - } - } else if (in == PARSE_DEC_IN_INTG && dig == '.') { - in = PARSE_DEC_IN_FRAC; - } else if (in != PARSE_DEC_IN_EXP && ((dig | 0x20) == 'e')) { - in = PARSE_DEC_IN_EXP; - if (str < top) { - if (str[0] == '+') { - str++; - } else if (str[0] == '-') { - str++; - exp_neg = true; - } - } - if (str == top) { - goto value_error; - } - } else if (dig == '_') { - continue; - } else { - // unknown character - str--; - break; - } - } - - // work out the exponent - if (exp_neg) { - exp_val = -exp_val; - } - - // apply the exponent, making sure it's not a subnormal value - exp_val += exp_extra + trailing_zeros_intg; - if (exp_val < SMALL_NORMAL_EXP) { - exp_val -= SMALL_NORMAL_EXP; - dec_val *= SMALL_NORMAL_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); + str = mp_parse_float_internal(str, top - str, &dec_val); + if (!str) { + goto value_error; } } diff --git a/py/parsenum.h b/py/parsenum.h index f444632d230..d532cb194a5 100644 --- a/py/parsenum.h +++ b/py/parsenum.h @@ -34,6 +34,11 @@ mp_obj_t mp_parse_num_integer(const char *restrict str, size_t len, int base, mp_lexer_t *lex); +#if MICROPY_PY_BUILTINS_FLOAT +mp_large_float_t mp_decimal_exp(mp_large_float_t num, int dec_exp); +const char *mp_parse_float_internal(const char *str, size_t len, mp_float_t *res); +#endif + #if MICROPY_PY_BUILTINS_COMPLEX mp_obj_t mp_parse_num_decimal(const char *str, size_t len, bool allow_imag, bool force_complex, mp_lexer_t *lex); diff --git a/py/parsenumbase.c b/py/parsenumbase.c index 94523a666d3..fbf07a11958 100644 --- a/py/parsenumbase.c +++ b/py/parsenumbase.c @@ -30,35 +30,28 @@ // find real radix base, and strip preceding '0x', '0o' and '0b' // puts base in *base, and returns number of bytes to skip the prefix +// in base-0, puts 1 in *base to indicate a number that starts with 0, to provoke a +// ValueError if it's not all-digits-zero. size_t mp_parse_num_base(const char *str, size_t len, int *base) { const byte *p = (const byte *)str; if (len <= 1) { goto no_prefix; } unichar c = *(p++); - if ((*base == 0 || *base == 16) && c == '0') { - c = *(p++); - if ((c | 32) == 'x') { + if (c == '0') { + c = *(p++) | 32; + int b = *base; + if (c == 'x' && (b == 0 || b == 16)) { *base = 16; - } else if (*base == 0 && (c | 32) == 'o') { + } else if (c == 'o' && (b == 0 || b == 8)) { *base = 8; - } else if (*base == 0 && (c | 32) == 'b') { + } else if (c == 'b' && (b == 0 || b == 2)) { *base = 2; } else { - if (*base == 0) { - *base = 10; - } - p -= 2; - } - } else if (*base == 8 && c == '0') { - c = *(p++); - if ((c | 32) != 'o') { - p -= 2; - } - } else if (*base == 2 && c == '0') { - c = *(p++); - if ((c | 32) != 'b') { p -= 2; + if (b == 0) { + *base = 1; + } } } else { p--; diff --git a/py/persistentcode.c b/py/persistentcode.c index 09beeef4518..6ff7c479058 100644 --- a/py/persistentcode.c +++ b/py/persistentcode.c @@ -39,6 +39,10 @@ #if MICROPY_PERSISTENT_CODE_LOAD || MICROPY_PERSISTENT_CODE_SAVE #include "py/smallint.h" +// CIRCUITPY-CHANGE +#if CIRCUITPY_STORAGE_MAP_IMPORT +#include "shared-bindings/storage/__init__.h" +#endif // makeqstrdata.py has a fixed list of qstrs at the start that we can assume // are available with know indices on all MicroPython implementations, and @@ -63,6 +67,10 @@ typedef struct _bytecode_prelude_t { uint code_info_size; } bytecode_prelude_t; +#if MICROPY_EMIT_RV32 +#include "py/asmrv32.h" +#endif + #endif // MICROPY_PERSISTENT_CODE_LOAD || MICROPY_PERSISTENT_CODE_SAVE #if MICROPY_PERSISTENT_CODE_LOAD @@ -72,7 +80,21 @@ typedef struct _bytecode_prelude_t { static int read_byte(mp_reader_t *reader); static size_t read_uint(mp_reader_t *reader); -#if MICROPY_EMIT_MACHINE_CODE +#if MICROPY_EMIT_INLINE_ASM || MICROPY_ENABLE_NATIVE_CODE + +#if MICROPY_PERSISTENT_CODE_TRACK_FUN_DATA || MICROPY_PERSISTENT_CODE_TRACK_BSS_RODATA + +// An mp_obj_list_t that tracks native text/BSS/rodata to prevent the GC from reclaiming them. +MP_REGISTER_ROOT_POINTER(mp_obj_t persistent_code_root_pointers); + +static void track_root_pointer(void *ptr) { + if (MP_STATE_PORT(persistent_code_root_pointers) == MP_OBJ_NULL) { + MP_STATE_PORT(persistent_code_root_pointers) = mp_obj_new_list(0, NULL); + } + mp_obj_list_append(MP_STATE_PORT(persistent_code_root_pointers), MP_OBJ_FROM_PTR(ptr)); +} + +#endif typedef struct _reloc_info_t { mp_reader_t *reader; @@ -174,6 +196,15 @@ static qstr load_qstr(mp_reader_t *reader) { return len >> 1; } len >>= 1; + + #if MICROPY_VFS_ROM + // If possible, create the qstr from the memory-mapped string data. + const uint8_t *memmap = mp_reader_try_read_rom(reader, len + 1); + if (memmap != NULL) { + return qstr_from_strn_static((const char *)memmap, len); + } + #endif + char *str = m_new(char, len); read_bytes(reader, (byte *)str, len); read_byte(reader); // read and discard null terminator @@ -182,9 +213,27 @@ static qstr load_qstr(mp_reader_t *reader) { return qst; } +#if MICROPY_VFS_ROM +// Create a str/bytes object that can forever reference the given data. +static mp_obj_t mp_obj_new_str_static(const mp_obj_type_t *type, const byte *data, size_t len) { + if (type == &mp_type_str) { + qstr q = qstr_find_strn((const char *)data, len); + if (q != MP_QSTRnull) { + return MP_OBJ_NEW_QSTR(q); + } + } + assert(data[len] == '\0'); + mp_obj_str_t *o = mp_obj_malloc(mp_obj_str_t, type); + o->len = len; + o->hash = qstr_compute_hash(data, len); + o->data = data; + return MP_OBJ_FROM_PTR(o); +} +#endif + static mp_obj_t load_obj(mp_reader_t *reader) { byte obj_type = read_byte(reader); - #if MICROPY_EMIT_MACHINE_CODE + #if MICROPY_EMIT_INLINE_ASM || MICROPY_ENABLE_NATIVE_CODE if (obj_type == MP_PERSISTENT_OBJ_FUN_TABLE) { return MP_OBJ_FROM_PTR(&mp_fun_table); } else @@ -199,6 +248,8 @@ static mp_obj_t load_obj(mp_reader_t *reader) { return MP_OBJ_FROM_PTR(&mp_const_ellipsis_obj); } else { size_t len = read_uint(reader); + + // Handle empty bytes object, and tuple objects. if (len == 0 && obj_type == MP_PERSISTENT_OBJ_BYTES) { read_byte(reader); // skip null terminator return mp_const_empty_bytes; @@ -209,11 +260,31 @@ static mp_obj_t load_obj(mp_reader_t *reader) { } return MP_OBJ_FROM_PTR(tuple); } + + // Read in the object's data, either from ROM or into RAM. + const uint8_t *memmap = NULL; vstr_t vstr; - vstr_init_len(&vstr, len); - read_bytes(reader, (byte *)vstr.buf, len); + #if MICROPY_VFS_ROM + memmap = mp_reader_try_read_rom(reader, len); + vstr.buf = (void *)memmap; + vstr.len = len; + #endif + if (memmap == NULL) { + // Data could not be memory-mapped, so allocate it in RAM and read it in. + vstr_init_len(&vstr, len); + read_bytes(reader, (byte *)vstr.buf, len); + } + + // Create and return the object. if (obj_type == MP_PERSISTENT_OBJ_STR || obj_type == MP_PERSISTENT_OBJ_BYTES) { - read_byte(reader); // skip null terminator + read_byte(reader); // skip null terminator (it needs to be there for ROM str objects) + #if MICROPY_VFS_ROM + if (memmap != NULL) { + // Create a str/bytes that references the memory-mapped data. + const mp_obj_type_t *t = obj_type == MP_PERSISTENT_OBJ_STR ? &mp_type_str : &mp_type_bytes; + return mp_obj_new_str_static(t, memmap, len); + } + #endif if (obj_type == MP_PERSISTENT_OBJ_STR) { return mp_obj_new_str_from_utf8_vstr(&vstr); } else { @@ -235,14 +306,14 @@ static mp_raw_code_t *load_raw_code(mp_reader_t *reader, mp_module_context_t *co bool has_children = !!(kind_len & 4); size_t fun_data_len = kind_len >> 3; - #if !MICROPY_EMIT_MACHINE_CODE + #if !(MICROPY_EMIT_INLINE_ASM || MICROPY_ENABLE_NATIVE_CODE) if (kind != MP_CODE_BYTECODE) { mp_raise_ValueError(MP_ERROR_TEXT("incompatible .mpy file")); } #endif uint8_t *fun_data = NULL; - #if MICROPY_EMIT_MACHINE_CODE + #if MICROPY_EMIT_INLINE_ASM || MICROPY_ENABLE_NATIVE_CODE size_t prelude_offset = 0; mp_uint_t native_scope_flags = 0; mp_uint_t native_n_pos_args = 0; @@ -250,12 +321,19 @@ static mp_raw_code_t *load_raw_code(mp_reader_t *reader, mp_module_context_t *co #endif if (kind == MP_CODE_BYTECODE) { - // Allocate memory for the bytecode - fun_data = m_new(uint8_t, fun_data_len); - // Load bytecode - read_bytes(reader, fun_data, fun_data_len); + #if MICROPY_VFS_ROM + // Try to reference memory-mapped data for the bytecode. + fun_data = (uint8_t *)mp_reader_try_read_rom(reader, fun_data_len); + #endif - #if MICROPY_EMIT_MACHINE_CODE + if (fun_data == NULL) { + // Allocate memory for the bytecode. + fun_data = m_new(uint8_t, fun_data_len); + // Load bytecode. + read_bytes(reader, fun_data, fun_data_len); + } + + #if MICROPY_EMIT_INLINE_ASM || MICROPY_ENABLE_NATIVE_CODE } else { // Allocate memory for native data and load it size_t fun_alloc; @@ -282,7 +360,7 @@ static mp_raw_code_t *load_raw_code(mp_reader_t *reader, mp_module_context_t *co size_t n_children = 0; mp_raw_code_t **children = NULL; - #if MICROPY_EMIT_MACHINE_CODE + #if MICROPY_EMIT_INLINE_ASM || MICROPY_ENABLE_NATIVE_CODE // Load optional BSS/rodata for viper. uint8_t *rodata = NULL; uint8_t *bss = NULL; @@ -306,11 +384,10 @@ static mp_raw_code_t *load_raw_code(mp_reader_t *reader, mp_module_context_t *co read_bytes(reader, rodata, rodata_size); } - // Viper code with BSS/rodata should not have any children. - // Reuse the children pointer to reference the BSS/rodata - // memory so that it is not reclaimed by the GC. - assert(!has_children); - children = (void *)data; + #if MICROPY_PERSISTENT_CODE_TRACK_BSS_RODATA + // Track the BSS/rodata memory so it's not reclaimed by the GC. + track_root_pointer(data); + #endif } } #endif @@ -338,9 +415,9 @@ static mp_raw_code_t *load_raw_code(mp_reader_t *reader, mp_module_context_t *co #endif scope_flags); - #if MICROPY_EMIT_MACHINE_CODE + #if MICROPY_EMIT_INLINE_ASM || MICROPY_ENABLE_NATIVE_CODE } else { - const uint8_t *prelude_ptr; + const uint8_t *prelude_ptr = NULL; #if MICROPY_EMIT_NATIVE_PRELUDE_SEPARATE_FROM_MACHINE_CODE if (kind == MP_CODE_NATIVE_PY) { // Executable code cannot be accessed byte-wise on this architecture, so copy @@ -353,22 +430,17 @@ static mp_raw_code_t *load_raw_code(mp_reader_t *reader, mp_module_context_t *co // Relocate and commit code to executable address space reloc_info_t ri = {reader, context, rodata, bss}; + #if MICROPY_PERSISTENT_CODE_TRACK_FUN_DATA + if (native_scope_flags & MP_SCOPE_FLAG_VIPERRELOC) { + // Track the function data memory so it's not reclaimed by the GC. + track_root_pointer(fun_data); + } + #endif #if defined(MP_PLAT_COMMIT_EXEC) void *opt_ri = (native_scope_flags & MP_SCOPE_FLAG_VIPERRELOC) ? &ri : NULL; fun_data = MP_PLAT_COMMIT_EXEC(fun_data, fun_data_len, opt_ri); #else if (native_scope_flags & MP_SCOPE_FLAG_VIPERRELOC) { - #if MICROPY_PERSISTENT_CODE_TRACK_RELOC_CODE - // If native code needs relocations then it's not guaranteed that a pointer to - // the head of `buf` (containing the machine code) will be retained for the GC - // to trace. This is because native functions can start inside `buf` and so - // it's possible that the only GC-reachable pointers are pointers inside `buf`. - // So put this `buf` on a list of reachable root pointers. - if (MP_STATE_PORT(track_reloc_code_list) == MP_OBJ_NULL) { - MP_STATE_PORT(track_reloc_code_list) = mp_obj_new_list(0, NULL); - } - mp_obj_list_append(MP_STATE_PORT(track_reloc_code_list), MP_OBJ_FROM_PTR(fun_data)); - #endif // Do the relocations. mp_native_relocate(&ri, fun_data, (uintptr_t)fun_data); } @@ -409,13 +481,16 @@ void mp_raw_code_load(mp_reader_t *reader, mp_compiled_module_t *cm) { read_bytes(reader, header, sizeof(header)); byte arch = MPY_FEATURE_DECODE_ARCH(header[2]); // CIRCUITPY-CHANGE: 'C', not 'M' + if (header[0] == 'M') { + mp_raise_ValueError(MP_ERROR_TEXT("MicroPython .mpy file; use CircuitPython mpy-cross")); + } if (header[0] != 'C' || header[1] != MPY_VERSION || (arch != MP_NATIVE_ARCH_NONE && MPY_FEATURE_DECODE_SUB_VERSION(header[2]) != MPY_SUB_VERSION) || header[3] > MP_SMALL_INT_BITS) { mp_raise_ValueError(MP_ERROR_TEXT("incompatible .mpy file")); } - if (MPY_FEATURE_DECODE_ARCH(header[2]) != MP_NATIVE_ARCH_NONE) { + if (arch != MP_NATIVE_ARCH_NONE) { if (!MPY_FEATURE_ARCH_TEST(arch)) { if (MPY_FEATURE_ARCH_TEST(MP_NATIVE_ARCH_NONE)) { // On supported ports this can be resolved by enabling feature, eg @@ -427,6 +502,23 @@ void mp_raw_code_load(mp_reader_t *reader, mp_compiled_module_t *cm) { } } + size_t arch_flags = 0; + if (MPY_FEATURE_ARCH_FLAGS_TEST(header[2])) { + #if MICROPY_EMIT_RV32 + arch_flags = read_uint(reader); + + if (MPY_FEATURE_ARCH_TEST(MP_NATIVE_ARCH_RV32IMC)) { + if ((arch_flags & (size_t)asm_rv32_allowed_extensions()) != arch_flags) { + mp_raise_ValueError(MP_ERROR_TEXT("incompatible .mpy file")); + } + } else + #endif + { + (void)arch_flags; + mp_raise_ValueError(MP_ERROR_TEXT("incompatible .mpy file")); + } + } + size_t n_qstr = read_uint(reader); size_t n_obj = read_uint(reader); mp_module_context_alloc_tables(cm->context, n_qstr, n_obj); @@ -448,6 +540,7 @@ void mp_raw_code_load(mp_reader_t *reader, mp_compiled_module_t *cm) { cm->has_native = MPY_FEATURE_DECODE_ARCH(header[2]) != MP_NATIVE_ARCH_NONE; cm->n_qstr = n_qstr; cm->n_obj = n_obj; + cm->arch_flags = arch_flags; #endif // Deregister exception handler and close the reader. @@ -464,7 +557,13 @@ void mp_raw_code_load_mem(const byte *buf, size_t len, mp_compiled_module_t *con void mp_raw_code_load_file(qstr filename, mp_compiled_module_t *context) { mp_reader_t reader; - mp_reader_new_file(&reader, filename); + // CIRCUITPY-CHANGE: read a CIRCUITPY .mpy from its flash runs, so its data stays in flash + #if CIRCUITPY_STORAGE_MAP_IMPORT + if (!storage_map_file_reader(&reader, filename)) + #endif + { + mp_reader_new_file(&reader, filename); + } mp_raw_code_load(&reader, context); } @@ -472,7 +571,7 @@ void mp_raw_code_load_file(qstr filename, mp_compiled_module_t *context) { #endif // MICROPY_PERSISTENT_CODE_LOAD -#if MICROPY_PERSISTENT_CODE_SAVE +#if MICROPY_PERSISTENT_CODE_SAVE || MICROPY_PERSISTENT_CODE_SAVE_FUN #include "py/objstr.h" @@ -480,9 +579,8 @@ static void mp_print_bytes(mp_print_t *print, const byte *data, size_t len) { print->print_strn(print->data, (const char *)data, len); } -#define BYTES_FOR_INT ((MP_BYTES_PER_OBJ_WORD * 8 + 6) / 7) static void mp_print_uint(mp_print_t *print, size_t n) { - byte buf[BYTES_FOR_INT]; + byte buf[MP_ENCODE_UINT_MAX_BYTES]; byte *p = buf + sizeof(buf); *--p = n & 0x7f; n >>= 7; @@ -570,6 +668,10 @@ static void save_obj(mp_print_t *print, mp_obj_t o) { } } +#endif // MICROPY_PERSISTENT_CODE_SAVE || MICROPY_PERSISTENT_CODE_SAVE_FUN + +#if MICROPY_PERSISTENT_CODE_SAVE + static void save_raw_code(mp_print_t *print, const mp_raw_code_t *rc) { // Save function kind and data length mp_print_uint(print, (rc->fun_data_len << 3) | ((rc->n_children != 0) << 2) | (rc->kind - MP_CODE_BYTECODE)); @@ -613,7 +715,7 @@ void mp_raw_code_save(mp_compiled_module_t *cm, mp_print_t *print) { byte header[4] = { 'C', MPY_VERSION, - cm->has_native ? MPY_FEATURE_ENCODE_SUB_VERSION(MPY_SUB_VERSION) | MPY_FEATURE_ENCODE_ARCH(MPY_FEATURE_ARCH_DYNAMIC) : 0, + (cm->arch_flags != 0 ? MPY_FEATURE_ARCH_FLAGS : 0) | (cm->has_native ? MPY_FEATURE_ENCODE_SUB_VERSION(MPY_SUB_VERSION) | MPY_FEATURE_ENCODE_ARCH(MPY_FEATURE_ARCH_DYNAMIC) : 0), #if MICROPY_DYNAMIC_COMPILER mp_dynamic_compiler.small_int_bits, #else @@ -622,6 +724,10 @@ void mp_raw_code_save(mp_compiled_module_t *cm, mp_print_t *print) { }; mp_print_bytes(print, header, sizeof(header)); + if (cm->arch_flags) { + mp_print_uint(print, cm->arch_flags); + } + // Number of entries in constant table. mp_print_uint(print, cm->n_qstr); mp_print_uint(print, cm->n_obj); @@ -640,6 +746,8 @@ void mp_raw_code_save(mp_compiled_module_t *cm, mp_print_t *print) { save_raw_code(print, cm->rc); } +#endif // MICROPY_PERSISTENT_CODE_SAVE + #if MICROPY_PERSISTENT_CODE_SAVE_FILE #include @@ -670,7 +778,245 @@ void mp_raw_code_save_file(mp_compiled_module_t *cm, qstr filename) { #endif // MICROPY_PERSISTENT_CODE_SAVE_FILE -#endif // MICROPY_PERSISTENT_CODE_SAVE +#if MICROPY_PERSISTENT_CODE_SAVE_FUN + +#include "py/bc0.h" +#include "py/objfun.h" +#include "py/smallint.h" +#include "py/gc.h" + +#define MP_BC_OPCODE_HAS_SIGNED_OFFSET(opcode) (MP_BC_UNWIND_JUMP <= (opcode) && (opcode) <= MP_BC_POP_JUMP_IF_FALSE) + +typedef struct _bit_vector_t { + size_t max_bit_set; + size_t alloc; + uintptr_t *bits; +} bit_vector_t; + +static void bit_vector_init(bit_vector_t *self) { + self->max_bit_set = 0; + self->alloc = 1; + self->bits = m_new(uintptr_t, self->alloc); +} + +static void bit_vector_clear(bit_vector_t *self) { + m_del(uintptr_t, self->bits, self->alloc); +} + +static bool bit_vector_is_set(bit_vector_t *self, size_t index) { + const size_t bits_size = sizeof(*self->bits) * MP_BITS_PER_BYTE; + return index / bits_size < self->alloc + && (self->bits[index / bits_size] & ((uintptr_t)1 << (index % bits_size))) != 0; +} + +static void bit_vector_set(bit_vector_t *self, size_t index) { + const size_t bits_size = sizeof(*self->bits) * MP_BITS_PER_BYTE; + self->max_bit_set = MAX(self->max_bit_set, index); + if (index / bits_size >= self->alloc) { + size_t new_alloc = self->alloc * 2; + self->bits = m_renew(uintptr_t, self->bits, self->alloc, new_alloc); + self->alloc = new_alloc; + } + self->bits[index / bits_size] |= (uintptr_t)1 << (index % bits_size); +} + +typedef struct _mp_opcode_t { + uint8_t opcode; + uint8_t format; + uint8_t size; + mp_int_t arg; + uint8_t extra_arg; +} mp_opcode_t; + +static mp_opcode_t mp_opcode_decode(const uint8_t *ip) { + const uint8_t *ip_start = ip; + uint8_t opcode = *ip++; + uint8_t opcode_format = MP_BC_FORMAT(opcode); + mp_uint_t arg = 0; + uint8_t extra_arg = 0; + if (opcode_format == MP_BC_FORMAT_QSTR || opcode_format == MP_BC_FORMAT_VAR_UINT) { + arg = *ip & 0x7f; + if (opcode == MP_BC_LOAD_CONST_SMALL_INT && (arg & 0x40) != 0) { + arg |= (mp_uint_t)(-1) << 7; + } + while ((*ip & 0x80) != 0) { + arg = (arg << 7) | (*++ip & 0x7f); + } + ++ip; + } else if (opcode_format == MP_BC_FORMAT_OFFSET) { + if ((*ip & 0x80) == 0) { + arg = *ip++; + if (MP_BC_OPCODE_HAS_SIGNED_OFFSET(opcode)) { + arg -= 0x40; + } + } else { + arg = (ip[0] & 0x7f) | (ip[1] << 7); + ip += 2; + if (MP_BC_OPCODE_HAS_SIGNED_OFFSET(opcode)) { + arg -= 0x4000; + } + } + } + if ((opcode & MP_BC_MASK_EXTRA_BYTE) == 0) { + extra_arg = *ip++; + } + + mp_opcode_t op = { opcode, opcode_format, ip - ip_start, arg, extra_arg }; + return op; +} + +typedef struct _mp_raw_code_simplified_t { + const uint8_t *fun_data; + struct _mp_raw_code_simplified_t *children; + size_t fun_data_len; + size_t n_children; +} mp_raw_code_simplified_t; + +static void proto_fun_to_raw_code_simplified(const void *proto_fun, bit_vector_t *qstr_table_used, bit_vector_t *obj_table_used, mp_raw_code_simplified_t *rcs) { + const uint8_t *fun_data; + mp_raw_code_t **children; + if (mp_proto_fun_is_bytecode(proto_fun)) { + fun_data = proto_fun; + children = NULL; + } else { + const mp_raw_code_t *rc = proto_fun; + if (rc->kind != MP_CODE_BYTECODE) { + mp_raise_ValueError(MP_ERROR_TEXT("function must be bytecode")); + } + fun_data = rc->fun_data; + children = rc->children; + } + + const uint8_t *fun_data_top = fun_data + gc_nbytes(fun_data); + + // Extract function information. + const byte *ip = fun_data; + MP_BC_PRELUDE_SIG_DECODE(ip); + MP_BC_PRELUDE_SIZE_DECODE(ip); + + const byte *ip_names = ip; + mp_uint_t simple_name = mp_decode_uint(&ip_names); + bit_vector_set(qstr_table_used, simple_name); + for (size_t i = 0; i < n_pos_args + n_kwonly_args; ++i) { + mp_uint_t arg_name = mp_decode_uint(&ip_names); + bit_vector_set(qstr_table_used, arg_name); + } + + // Skip pass source code info and cell info. + // Then ip points to the start of the opcodes. + ip += n_info + n_cell; + + // Decode bytecode. + size_t n_children = 0; + while (ip < fun_data_top) { + mp_opcode_t op = mp_opcode_decode(ip); + if (op.opcode == MP_BC_BASE_RESERVED) { + // End of opcodes. + fun_data_top = ip; + } else if (op.format == MP_BC_FORMAT_QSTR) { + bit_vector_set(qstr_table_used, op.arg); + } else if (op.opcode == MP_BC_LOAD_CONST_OBJ) { + bit_vector_set(obj_table_used, op.arg); + } else if (op.opcode == MP_BC_MAKE_FUNCTION + || op.opcode == MP_BC_MAKE_FUNCTION_DEFARGS + || op.opcode == MP_BC_MAKE_CLOSURE + || op.opcode == MP_BC_MAKE_CLOSURE_DEFARGS) { + if ((mp_uint_t)op.arg + 1 > n_children) { + n_children = (mp_uint_t)op.arg + 1; + } + } + ip += op.size; + } + + rcs->fun_data = fun_data; + rcs->fun_data_len = fun_data_top - fun_data; + rcs->n_children = n_children; + rcs->children = NULL; + + if (n_children) { + rcs->children = m_new(mp_raw_code_simplified_t, n_children); + for (size_t i = 0; i < n_children; ++i) { + proto_fun_to_raw_code_simplified(children[i], qstr_table_used, obj_table_used, &rcs->children[i]); + } + } +} + +static void save_raw_code_simplified(mp_print_t *print, const mp_raw_code_simplified_t *rcs) { + // Save function kind and data length. + mp_print_uint(print, rcs->fun_data_len << 3 | (rcs->n_children != 0) << 2); + + // Save function code. + mp_print_bytes(print, rcs->fun_data, rcs->fun_data_len); + + // Save (and free) children. + if (rcs->n_children) { + mp_print_uint(print, rcs->n_children); + for (size_t i = 0; i < rcs->n_children; ++i) { + save_raw_code_simplified(print, &rcs->children[i]); + } + m_del(mp_raw_code_simplified_t, rcs->children, rcs->n_children); + } +} + +mp_obj_t mp_raw_code_save_fun_to_bytes(const mp_module_constants_t *consts, mp_proto_fun_t proto_fun) { + // Track the qstrs used by the function. + bit_vector_t qstr_table_used; + bit_vector_init(&qstr_table_used); + + // Track the objects used by the function. + bit_vector_t obj_table_used; + bit_vector_init(&obj_table_used); + + #if MICROPY_PY_BUILTINS_CODE >= MICROPY_PY_BUILTINS_CODE_FULL + // Make sure the filename appears in the qstr table. + bit_vector_set(&qstr_table_used, 0); + #endif + + // Convert function into a simplified raw code tree. + mp_raw_code_simplified_t rcs; + proto_fun_to_raw_code_simplified(proto_fun, &qstr_table_used, &obj_table_used, &rcs); + + mp_print_t print; + vstr_t vstr; + vstr_init_print(&vstr, 64, &print); + + // Start with .mpy header. + const uint8_t header[4] = { 'M', MPY_VERSION, 0, MP_SMALL_INT_BITS }; + mp_print_bytes(&print, header, sizeof(header)); + + // Number of entries in constant table. + mp_print_uint(&print, qstr_table_used.max_bit_set + 1); + mp_print_uint(&print, obj_table_used.max_bit_set + 1); + + // Save qstrs. + for (size_t i = 0; i <= qstr_table_used.max_bit_set; ++i) { + if (bit_vector_is_set(&qstr_table_used, i)) { + save_qstr(&print, consts->qstr_table[i]); + } else { + save_qstr(&print, MP_QSTR_); + } + } + + // Save constant objects. + for (size_t i = 0; i <= obj_table_used.max_bit_set; ++i) { + if (bit_vector_is_set(&obj_table_used, i)) { + save_obj(&print, consts->obj_table[i]); + } else { + save_obj(&print, mp_const_none); + } + } + + bit_vector_clear(&qstr_table_used); + bit_vector_clear(&obj_table_used); + + // Save the bytecode data (also free the simplified raw code tree at the same time). + save_raw_code_simplified(&print, &rcs); + + // Create and return bytes representing the .mpy data. + return mp_obj_new_bytes_from_vstr(&vstr); +} + +#endif // MICROPY_PERSISTENT_CODE_SAVE_FUN #if MICROPY_PERSISTENT_CODE_TRACK_RELOC_CODE // An mp_obj_list_t that tracks relocated native code to prevent the GC from reclaiming them. diff --git a/py/persistentcode.h b/py/persistentcode.h index d2b310f241f..4dbdacafd3e 100644 --- a/py/persistentcode.h +++ b/py/persistentcode.h @@ -30,6 +30,11 @@ #include "py/reader.h" #include "py/emitglue.h" +// CIRCUITPY-CHANGE: Avoid undefined warnings +#ifndef MICROPY_PERSISTENT_CODE_TRACK_RELOC_CODE +#define MICROPY_PERSISTENT_CODE_TRACK_RELOC_CODE (0) +#endif + // The current version of .mpy files. A bytecode-only .mpy file can be loaded // as long as MPY_VERSION matches, but a native .mpy (i.e. one with an arch // set) must also match MPY_SUB_VERSION. This allows 3 additional updates to @@ -45,32 +50,59 @@ // Macros to encode/decode native architecture to/from the feature byte #define MPY_FEATURE_ENCODE_ARCH(arch) ((arch) << 2) -#define MPY_FEATURE_DECODE_ARCH(feat) ((feat) >> 2) +#define MPY_FEATURE_DECODE_ARCH(feat) (((feat) >> 2) & 0x2F) // Define the host architecture -#if MICROPY_EMIT_X86 - #define MPY_FEATURE_ARCH (MP_NATIVE_ARCH_X86) -#elif MICROPY_EMIT_X64 - #define MPY_FEATURE_ARCH (MP_NATIVE_ARCH_X64) -#elif MICROPY_EMIT_THUMB - #if defined(__thumb2__) - #if defined(__ARM_FP) && (__ARM_FP & 8) == 8 - #define MPY_FEATURE_ARCH (MP_NATIVE_ARCH_ARMV7EMDP) - #elif defined(__ARM_FP) && (__ARM_FP & 4) == 4 - #define MPY_FEATURE_ARCH (MP_NATIVE_ARCH_ARMV7EMSP) +// CIRCUITPY-CHANGE: MPY_FEATURE_ARCH_NAME, the mpy-cross -march name of the host architecture +#if MICROPY_PERSISTENT_CODE_LOAD_NATIVE + #if defined(__i386__) || defined(_M_IX86) + #define MPY_FEATURE_ARCH (MP_NATIVE_ARCH_X86) + #define MPY_FEATURE_ARCH_NAME "x86" + #elif defined(__x86_64__) || defined(_M_X64) + #define MPY_FEATURE_ARCH (MP_NATIVE_ARCH_X64) + #define MPY_FEATURE_ARCH_NAME "x64" + #elif defined(__thumb2__) || defined(__thumb__) + #if defined(__thumb2__) + #if defined(__ARM_FP) && (__ARM_FP & 8) == 8 + #define MPY_FEATURE_ARCH (MP_NATIVE_ARCH_ARMV7EMDP) + #define MPY_FEATURE_ARCH_NAME "armv7emdp" + #elif defined(__ARM_FP) && (__ARM_FP & 4) == 4 + #define MPY_FEATURE_ARCH (MP_NATIVE_ARCH_ARMV7EMSP) + #define MPY_FEATURE_ARCH_NAME "armv7emsp" + #else + #define MPY_FEATURE_ARCH (MP_NATIVE_ARCH_ARMV7EM) + #define MPY_FEATURE_ARCH_NAME "armv7em" + #endif + #else + #define MPY_FEATURE_ARCH (MP_NATIVE_ARCH_ARMV6M) + #define MPY_FEATURE_ARCH_NAME "armv6m" + #endif + #define MPY_FEATURE_ARCH_TEST(x) (MP_NATIVE_ARCH_ARMV6M <= (x) && (x) <= MPY_FEATURE_ARCH) + #elif defined(__arm__) + #define MPY_FEATURE_ARCH (MP_NATIVE_ARCH_ARMV6) + #define MPY_FEATURE_ARCH_NAME "armv6" + #elif defined(__xtensa__) + #include + #if XCHAL_HAVE_WINDOWED + #define MPY_FEATURE_ARCH (MP_NATIVE_ARCH_XTENSAWIN) + #define MPY_FEATURE_ARCH_NAME "xtensawin" #else - #define MPY_FEATURE_ARCH (MP_NATIVE_ARCH_ARMV7EM) + #define MPY_FEATURE_ARCH (MP_NATIVE_ARCH_XTENSA) + #define MPY_FEATURE_ARCH_NAME "xtensa" + #endif + #elif defined(__riscv) + #if __riscv_xlen == 32 + #define MPY_FEATURE_ARCH (MP_NATIVE_ARCH_RV32IMC) + #define MPY_FEATURE_ARCH_NAME "rv32imc" + #elif __riscv_xlen == 64 + #define MPY_FEATURE_ARCH (MP_NATIVE_ARCH_RV64IMC) + #define MPY_FEATURE_ARCH_NAME "rv64imc" + #else + #error "Unsupported RISC-V architecture." #endif #else - #define MPY_FEATURE_ARCH (MP_NATIVE_ARCH_ARMV6M) + #error "Unsupported native architecture." #endif - #define MPY_FEATURE_ARCH_TEST(x) (MP_NATIVE_ARCH_ARMV6M <= (x) && (x) <= MPY_FEATURE_ARCH) -#elif MICROPY_EMIT_ARM - #define MPY_FEATURE_ARCH (MP_NATIVE_ARCH_ARMV6) -#elif MICROPY_EMIT_XTENSA - #define MPY_FEATURE_ARCH (MP_NATIVE_ARCH_XTENSA) -#elif MICROPY_EMIT_XTENSAWIN - #define MPY_FEATURE_ARCH (MP_NATIVE_ARCH_XTENSAWIN) #else #define MPY_FEATURE_ARCH (MP_NATIVE_ARCH_NONE) #endif @@ -83,6 +115,10 @@ #define MPY_FILE_HEADER_INT (MPY_VERSION \ | (MPY_FEATURE_ENCODE_SUB_VERSION(MPY_SUB_VERSION) | MPY_FEATURE_ENCODE_ARCH(MPY_FEATURE_ARCH)) << 8) +// Architecture-specific flags are present in the .mpy file +#define MPY_FEATURE_ARCH_FLAGS (0x40) +#define MPY_FEATURE_ARCH_FLAGS_TEST(x) (((x) & MPY_FEATURE_ARCH_FLAGS) == MPY_FEATURE_ARCH_FLAGS) + enum { MP_NATIVE_ARCH_NONE = 0, MP_NATIVE_ARCH_X86, @@ -95,6 +131,9 @@ enum { MP_NATIVE_ARCH_ARMV7EMDP, MP_NATIVE_ARCH_XTENSA, MP_NATIVE_ARCH_XTENSAWIN, + MP_NATIVE_ARCH_RV32IMC, + MP_NATIVE_ARCH_RV64IMC, + MP_NATIVE_ARCH_DEBUG, // this entry should always be last }; enum { @@ -117,6 +156,7 @@ void mp_raw_code_load_file(qstr filename, mp_compiled_module_t *ctx); void mp_raw_code_save(mp_compiled_module_t *cm, mp_print_t *print); void mp_raw_code_save_file(mp_compiled_module_t *cm, qstr filename); +mp_obj_t mp_raw_code_save_fun_to_bytes(const mp_module_constants_t *consts, mp_proto_fun_t proto_fun); void mp_native_relocate(void *reloc, uint8_t *text, uintptr_t reloc_text); diff --git a/py/profile.c b/py/profile.c index 92f414ace7c..0523a1806e7 100644 --- a/py/profile.c +++ b/py/profile.c @@ -38,9 +38,8 @@ #endif #define prof_trace_cb MP_STATE_THREAD(prof_trace_callback) -#define QSTR_MAP(context, idx) (context->constants.qstr_table[idx]) -static uint mp_prof_bytecode_lineno(const mp_raw_code_t *rc, size_t bc) { +uint mp_prof_bytecode_lineno(const mp_raw_code_t *rc, size_t bc) { const mp_bytecode_prelude_t *prelude = &rc->prelude; return mp_bytecode_get_source_line(prelude->line_info, prelude->line_info_top, bc); } @@ -68,137 +67,6 @@ void mp_prof_extract_prelude(const byte *bytecode, mp_bytecode_prelude_t *prelud prelude->line_info = ip; } -/******************************************************************************/ -// code object - -static void code_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t kind) { - (void)kind; - mp_obj_code_t *o = MP_OBJ_TO_PTR(o_in); - const mp_raw_code_t *rc = o->rc; - const mp_bytecode_prelude_t *prelude = &rc->prelude; - mp_printf(print, - "", - QSTR_MAP(o->context, prelude->qstr_block_name_idx), - o, - QSTR_MAP(o->context, 0), - rc->line_of_definition - ); -} - -static mp_obj_tuple_t *code_consts(const mp_module_context_t *context, const mp_raw_code_t *rc) { - mp_obj_tuple_t *consts = MP_OBJ_TO_PTR(mp_obj_new_tuple(rc->n_children + 1, NULL)); - - size_t const_no = 0; - for (size_t i = 0; i < rc->n_children; ++i) { - mp_obj_t code = mp_obj_new_code(context, rc->children[i]); - if (code == MP_OBJ_NULL) { - m_malloc_fail(sizeof(mp_obj_code_t)); - } - consts->items[const_no++] = code; - } - consts->items[const_no++] = mp_const_none; - - return consts; -} - -static mp_obj_t raw_code_lnotab(const mp_raw_code_t *rc) { - // const mp_bytecode_prelude_t *prelude = &rc->prelude; - uint start = 0; - uint stop = rc->fun_data_len - start; - - uint last_lineno = mp_prof_bytecode_lineno(rc, start); - uint lasti = 0; - - const uint buffer_chunk_size = (stop - start) >> 2; // heuristic magic - uint buffer_size = buffer_chunk_size; - byte *buffer = m_new(byte, buffer_size); - uint buffer_index = 0; - - for (uint i = start; i < stop; ++i) { - uint lineno = mp_prof_bytecode_lineno(rc, i); - size_t line_diff = lineno - last_lineno; - if (line_diff > 0) { - uint instr_diff = (i - start) - lasti; - - assert(instr_diff < 256); - assert(line_diff < 256); - - if (buffer_index + 2 > buffer_size) { - buffer = m_renew(byte, buffer, buffer_size, buffer_size + buffer_chunk_size); - buffer_size = buffer_size + buffer_chunk_size; - } - last_lineno = lineno; - lasti = i - start; - buffer[buffer_index++] = instr_diff; - buffer[buffer_index++] = line_diff; - } - } - - mp_obj_t o = mp_obj_new_bytes(buffer, buffer_index); - m_del(byte, buffer, buffer_size); - return o; -} - -static void code_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) { - if (dest[0] != MP_OBJ_NULL) { - // not load attribute - return; - } - mp_obj_code_t *o = MP_OBJ_TO_PTR(self_in); - const mp_raw_code_t *rc = o->rc; - const mp_bytecode_prelude_t *prelude = &rc->prelude; - switch (attr) { - case MP_QSTR_co_code: - dest[0] = mp_obj_new_bytes( - (void *)prelude->opcodes, - rc->fun_data_len - (prelude->opcodes - (const byte *)rc->fun_data) - ); - break; - case MP_QSTR_co_consts: - dest[0] = MP_OBJ_FROM_PTR(code_consts(o->context, rc)); - break; - case MP_QSTR_co_filename: - dest[0] = MP_OBJ_NEW_QSTR(QSTR_MAP(o->context, 0)); - break; - case MP_QSTR_co_firstlineno: - dest[0] = MP_OBJ_NEW_SMALL_INT(mp_prof_bytecode_lineno(rc, 0)); - break; - case MP_QSTR_co_name: - dest[0] = MP_OBJ_NEW_QSTR(QSTR_MAP(o->context, prelude->qstr_block_name_idx)); - break; - case MP_QSTR_co_names: - dest[0] = MP_OBJ_FROM_PTR(o->dict_locals); - break; - case MP_QSTR_co_lnotab: - if (!o->lnotab) { - o->lnotab = raw_code_lnotab(rc); - } - dest[0] = o->lnotab; - break; - } -} - -MP_DEFINE_CONST_OBJ_TYPE( - mp_type_settrace_codeobj, - MP_QSTR_code, - MP_TYPE_FLAG_NONE, - print, code_print, - attr, code_attr - ); - -mp_obj_t mp_obj_new_code(const mp_module_context_t *context, const mp_raw_code_t *rc) { - mp_obj_code_t *o = m_new_obj_maybe(mp_obj_code_t); - if (o == NULL) { - return MP_OBJ_NULL; - } - o->base.type = &mp_type_settrace_codeobj; - o->context = context; - o->rc = rc; - o->dict_locals = mp_locals_get(); // this is a wrong! how to do this properly? - o->lnotab = MP_OBJ_NULL; - return MP_OBJ_FROM_PTR(o); -} - /******************************************************************************/ // frame object @@ -211,9 +79,9 @@ static void frame_print(const mp_print_t *print, mp_obj_t o_in, mp_print_kind_t mp_printf(print, "", frame, - QSTR_MAP(code->context, 0), - frame->lineno, - QSTR_MAP(code->context, prelude->qstr_block_name_idx) + MP_CODE_QSTR_MAP(code->context, 0), + (int)frame->lineno, + MP_CODE_QSTR_MAP(code->context, prelude->qstr_block_name_idx) ); } @@ -265,7 +133,7 @@ mp_obj_t mp_obj_new_frame(const mp_code_state_t *code_state) { return MP_OBJ_NULL; } - mp_obj_code_t *code = o->code = MP_OBJ_TO_PTR(mp_obj_new_code(code_state->fun_bc->context, code_state->fun_bc->rc)); + mp_obj_code_t *code = o->code = MP_OBJ_TO_PTR(mp_obj_new_code(code_state->fun_bc->context, code_state->fun_bc->rc, false)); if (code == NULL) { return MP_OBJ_NULL; } @@ -305,7 +173,7 @@ static mp_obj_t mp_prof_callback_invoke(mp_obj_t callback, prof_callback_args_t mp_prof_is_executing = false; if (MP_STATE_THREAD(mp_pending_exception) != MP_OBJ_NULL) { - mp_handle_pending(true); + mp_handle_pending(MP_HANDLE_PENDING_CALLBACKS_AND_EXCEPTIONS); } return top; } diff --git a/py/profile.h b/py/profile.h index 7f3f9140346..db72b9f0768 100644 --- a/py/profile.h +++ b/py/profile.h @@ -28,20 +28,12 @@ #define MICROPY_INCLUDED_PY_PROFILING_H #include "py/emitglue.h" +#include "py/objcode.h" #if MICROPY_PY_SYS_SETTRACE #define mp_prof_is_executing MP_STATE_THREAD(prof_callback_is_executing) -typedef struct _mp_obj_code_t { - // TODO this was 4 words - mp_obj_base_t base; - const mp_module_context_t *context; - const mp_raw_code_t *rc; - mp_obj_dict_t *dict_locals; - mp_obj_t lnotab; -} mp_obj_code_t; - typedef struct _mp_obj_frame_t { mp_obj_base_t base; const mp_code_state_t *code_state; @@ -53,9 +45,9 @@ typedef struct _mp_obj_frame_t { bool trace_opcodes; } mp_obj_frame_t; +uint mp_prof_bytecode_lineno(const mp_raw_code_t *rc, size_t bc); void mp_prof_extract_prelude(const byte *bytecode, mp_bytecode_prelude_t *prelude); -mp_obj_t mp_obj_new_code(const mp_module_context_t *mc, const mp_raw_code_t *rc); mp_obj_t mp_obj_new_frame(const mp_code_state_t *code_state); // This is the implementation for the sys.settrace diff --git a/py/py.cmake b/py/py.cmake index 1cbbe08f013..9d4fa15bd41 100644 --- a/py/py.cmake +++ b/py/py.cmake @@ -4,11 +4,18 @@ set(MICROPY_PY_DIR "${MICROPY_DIR}/py") list(APPEND MICROPY_INC_CORE "${MICROPY_DIR}") +# Set MICROPY_LIB_DIR default if not already set by the port. +# This needs to happen before usermod.cmake is included (for c_module() in manifests). +if(NOT MICROPY_LIB_DIR) + set(MICROPY_LIB_DIR ${MICROPY_DIR}/lib/micropython-lib) +endif() + # All py/ source files set(MICROPY_SOURCE_PY ${MICROPY_PY_DIR}/argcheck.c ${MICROPY_PY_DIR}/asmarm.c ${MICROPY_PY_DIR}/asmbase.c + ${MICROPY_PY_DIR}/asmrv32.c ${MICROPY_PY_DIR}/asmthumb.c ${MICROPY_PY_DIR}/asmx64.c ${MICROPY_PY_DIR}/asmx86.c @@ -19,12 +26,16 @@ set(MICROPY_SOURCE_PY ${MICROPY_PY_DIR}/builtinhelp.c ${MICROPY_PY_DIR}/builtinimport.c ${MICROPY_PY_DIR}/compile.c + ${MICROPY_PY_DIR}/cstack.c ${MICROPY_PY_DIR}/emitbc.c ${MICROPY_PY_DIR}/emitcommon.c ${MICROPY_PY_DIR}/emitglue.c + ${MICROPY_PY_DIR}/emitinlinerv32.c ${MICROPY_PY_DIR}/emitinlinethumb.c ${MICROPY_PY_DIR}/emitinlinextensa.c ${MICROPY_PY_DIR}/emitnarm.c + ${MICROPY_PY_DIR}/emitndebug.c + ${MICROPY_PY_DIR}/emitnrv32.c ${MICROPY_PY_DIR}/emitnthumb.c ${MICROPY_PY_DIR}/emitnx64.c ${MICROPY_PY_DIR}/emitnx86.c @@ -44,17 +55,23 @@ set(MICROPY_SOURCE_PY ${MICROPY_PY_DIR}/modio.c ${MICROPY_PY_DIR}/modmath.c ${MICROPY_PY_DIR}/modmicropython.c + ${MICROPY_PY_DIR}/modstring.c ${MICROPY_PY_DIR}/modstruct.c ${MICROPY_PY_DIR}/modsys.c ${MICROPY_PY_DIR}/modthread.c ${MICROPY_PY_DIR}/moderrno.c + ${MICROPY_PY_DIR}/modweakref.c ${MICROPY_PY_DIR}/mpprint.c ${MICROPY_PY_DIR}/mpstate.c ${MICROPY_PY_DIR}/mpz.c ${MICROPY_PY_DIR}/nativeglue.c ${MICROPY_PY_DIR}/nlr.c + ${MICROPY_PY_DIR}/nlraarch64.c + ${MICROPY_PY_DIR}/nlrloong64.c ${MICROPY_PY_DIR}/nlrmips.c ${MICROPY_PY_DIR}/nlrpowerpc.c + ${MICROPY_PY_DIR}/nlrrv32.c + ${MICROPY_PY_DIR}/nlrrv64.c ${MICROPY_PY_DIR}/nlrsetjmp.c ${MICROPY_PY_DIR}/nlrthumb.c ${MICROPY_PY_DIR}/nlrx64.c @@ -65,6 +82,7 @@ set(MICROPY_SOURCE_PY ${MICROPY_PY_DIR}/objattrtuple.c ${MICROPY_PY_DIR}/objbool.c ${MICROPY_PY_DIR}/objboundmeth.c + ${MICROPY_PY_DIR}/objcode.c ${MICROPY_PY_DIR}/objcell.c ${MICROPY_PY_DIR}/objclosure.c ${MICROPY_PY_DIR}/objcomplex.c @@ -90,12 +108,14 @@ set(MICROPY_SOURCE_PY ${MICROPY_PY_DIR}/objproperty.c ${MICROPY_PY_DIR}/objrange.c ${MICROPY_PY_DIR}/objreversed.c + ${MICROPY_PY_DIR}/objringio.c ${MICROPY_PY_DIR}/objset.c ${MICROPY_PY_DIR}/objsingleton.c ${MICROPY_PY_DIR}/objslice.c ${MICROPY_PY_DIR}/objstr.c ${MICROPY_PY_DIR}/objstringio.c ${MICROPY_PY_DIR}/objstrunicode.c + ${MICROPY_PY_DIR}/objtemplate.c # CIRCUITPY-CHANGE: add objtraceback.c ${MICROPY_PY_DIR}/objtraceback.c ${MICROPY_PY_DIR}/objtuple.c diff --git a/py/py.mk b/py/py.mk index bb5d8d2e91b..27d0a4bb34b 100644 --- a/py/py.mk +++ b/py/py.mk @@ -24,14 +24,11 @@ QSTR_GLOBAL_REQUIREMENTS += $(HEADER_BUILD)/mpversion.h # some code is performance bottleneck and compiled with other optimization options CSUPEROPT = -O3 -# Enable building 32-bit code on 64-bit host. -ifeq ($(MICROPY_FORCE_32BIT),1) -CC += -m32 -CXX += -m32 -LD += -m32 -endif - # External modules written in C. + +# Process manifest for C module extraction (appends to USER_C_MODULES). +include $(TOP)/py/manifest.mk + ifneq ($(USER_C_MODULES),) # pre-define USERMOD variables as expanded so that variables are immediate # expanded as they're added to them @@ -39,40 +36,73 @@ ifneq ($(USER_C_MODULES),) # C/C++ files that are included in the QSTR/module build SRC_USERMOD_C := SRC_USERMOD_CXX := -# Other C/C++ files (e.g. libraries or helpers) +# Other C/C++/Assembly files (e.g. libraries or helpers) SRC_USERMOD_LIB_C := SRC_USERMOD_LIB_CXX := +SRC_USERMOD_LIB_ASM := # Optionally set flags CFLAGS_USERMOD := CXXFLAGS_USERMOD := LDFLAGS_USERMOD := +LIBS_USERMOD := # Backwards compatibility with older user c modules that set SRC_USERMOD # added to SRC_USERMOD_C below SRC_USERMOD := -$(foreach module, $(wildcard $(USER_C_MODULES)/*/micropython.mk), \ - $(eval USERMOD_DIR = $(patsubst %/,%,$(dir $(module))))\ - $(info Including User C Module from $(USERMOD_DIR))\ - $(eval include $(module))\ +# For each C module directory, scan for micropython.mk and include it. +# Accumulate USERMOD_DIRS so we can later strip each module's parent path +# from its source files while preserving the module basename in the build +# tree (e.g. build/cexample/foo.o, not build/foo.o, so files that share a +# name across modules don't collide on the same .o target). +USERMOD_DIRS := +$(foreach _UDIR, $(USER_C_MODULES), \ + $(if $(wildcard $(_UDIR)/.),,$(error USER_C_MODULES path doesn't exist: $(abspath $(_UDIR)))) \ + $(foreach module, $(wildcard $(_UDIR)/micropython.mk) $(wildcard $(_UDIR)/*/micropython.mk), \ + $(eval USERMOD_DIR = $(patsubst %/,%,$(dir $(module))))\ + $(eval USERMOD_DIRS += $(USERMOD_DIR))\ + $(info Including User C Module from $(USERMOD_DIR))\ + $(eval include $(module))\ + )\ ) SRC_USERMOD_C += $(SRC_USERMOD) -SRC_USERMOD_PATHFIX_C += $(patsubst $(USER_C_MODULES)/%.c,%.c,$(SRC_USERMOD_C)) -SRC_USERMOD_PATHFIX_CXX += $(patsubst $(USER_C_MODULES)/%.cpp,%.cpp,$(SRC_USERMOD_CXX)) -SRC_USERMOD_PATHFIX_LIB_C += $(patsubst $(USER_C_MODULES)/%.c,%.c,$(SRC_USERMOD_LIB_C)) -SRC_USERMOD_PATHFIX_LIB_CXX += $(patsubst $(USER_C_MODULES)/%.cpp,%.cpp,$(SRC_USERMOD_LIB_CXX)) +# Strip each USERMOD_DIR's leading path from source files, keeping the module +# basename as the leading directory so build outputs land at +# BUILD//.o. Uses per-directory patsubst on the paths as-is +# rather than $(abspath) so a parent directory containing whitespace doesn't +# break word-based patsubst. +SRC_USERMOD_PATHFIX_C := $(SRC_USERMOD_C) +SRC_USERMOD_PATHFIX_CXX := $(SRC_USERMOD_CXX) +SRC_USERMOD_PATHFIX_LIB_C := $(SRC_USERMOD_LIB_C) +SRC_USERMOD_PATHFIX_LIB_CXX := $(SRC_USERMOD_LIB_CXX) +SRC_USERMOD_PATHFIX_LIB_ASM := $(SRC_USERMOD_LIB_ASM) +USERMOD_DIRS := $(sort $(USERMOD_DIRS)) +$(foreach _MDIR, $(USERMOD_DIRS), \ + $(eval _MBASE := $(notdir $(_MDIR))) \ + $(eval SRC_USERMOD_PATHFIX_C := $$(patsubst $(_MDIR)/%,$(_MBASE)/%,$$(SRC_USERMOD_PATHFIX_C))) \ + $(eval SRC_USERMOD_PATHFIX_CXX := $$(patsubst $(_MDIR)/%,$(_MBASE)/%,$$(SRC_USERMOD_PATHFIX_CXX))) \ + $(eval SRC_USERMOD_PATHFIX_LIB_C := $$(patsubst $(_MDIR)/%,$(_MBASE)/%,$$(SRC_USERMOD_PATHFIX_LIB_C))) \ + $(eval SRC_USERMOD_PATHFIX_LIB_CXX := $$(patsubst $(_MDIR)/%,$(_MBASE)/%,$$(SRC_USERMOD_PATHFIX_LIB_CXX))) \ + $(eval SRC_USERMOD_PATHFIX_LIB_ASM := $$(patsubst $(_MDIR)/%,$(_MBASE)/%,$$(SRC_USERMOD_PATHFIX_LIB_ASM))) \ +) + +# Parent directories of each USERMOD_DIR, added to vpath below so paths like +# cexample/foo.c (produced by the patsubst above) resolve to source files. +USERMOD_DIR_PARENTS := $(sort $(foreach _MDIR, $(USERMOD_DIRS), $(patsubst %/,%,$(dir $(_MDIR))))) CFLAGS += $(CFLAGS_USERMOD) CXXFLAGS += $(CXXFLAGS_USERMOD) LDFLAGS += $(LDFLAGS_USERMOD) +LIBS += $(LIBS_USERMOD) SRC_QSTR += $(SRC_USERMOD_PATHFIX_C) $(SRC_USERMOD_PATHFIX_CXX) PY_O += $(addprefix $(BUILD)/, $(SRC_USERMOD_PATHFIX_C:.c=.o)) PY_O += $(addprefix $(BUILD)/, $(SRC_USERMOD_PATHFIX_CXX:.cpp=.o)) PY_O += $(addprefix $(BUILD)/, $(SRC_USERMOD_PATHFIX_LIB_C:.c=.o)) PY_O += $(addprefix $(BUILD)/, $(SRC_USERMOD_PATHFIX_LIB_CXX:.cpp=.o)) +PY_O += $(addprefix $(BUILD)/, $(SRC_USERMOD_PATHFIX_LIB_ASM:.S=.o)) endif # USER_C_MODULES # CIRCUITPY-CHANGE @@ -84,7 +114,9 @@ SRC_QSTR += $(ULAB_SRC_PATHFIX) CFLAGS_MOD += -DCIRCUITPY_ULAB=1 -DMODULE_ULAB_ENABLED=1 -DULAB_HAS_USER_MODULE=0 -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 ifeq ($(CIRCUITPY_ULAB_OPTIMIZE_SIZE),1) -$(BUILD)/extmod/ulab/code/%.o: CFLAGS += -Os +# Function-pointer dispatch for ndarray binary operators saves about 4 kB of +# flash at the cost of roughly 1.5x slower element-wise arithmetic. +$(BUILD)/extmod/ulab/code/%.o: CFLAGS += -Os -DNDARRAY_BINARY_USES_FUN_POINTER=1 endif # CIRCUITPY_ULAB_OPTIMIZE_SIZE endif # CIRCUITPY_ULAB @@ -100,6 +132,9 @@ PY_CORE_O_BASENAME = $(addprefix py/,\ nlrmips.o \ nlrpowerpc.o \ nlrxtensa.o \ + nlrrv32.o \ + nlrrv64.o \ + nlrloong64.o \ nlrsetjmp.o \ malloc.o \ gc.o \ @@ -131,6 +166,10 @@ PY_CORE_O_BASENAME = $(addprefix py/,\ emitnxtensa.o \ emitinlinextensa.o \ emitnxtensawin.o \ + asmrv32.o \ + emitnrv32.o \ + emitinlinerv32.o \ + emitndebug.o \ formatfloat.o \ parsenumbase.o \ parsenum.o \ @@ -143,6 +182,7 @@ PY_CORE_O_BASENAME = $(addprefix py/,\ nativeglue.o \ pairheap.o \ ringbuf.o \ + cstack.o \ stackctrl.o \ argcheck.o \ warning.o \ @@ -155,6 +195,7 @@ PY_CORE_O_BASENAME = $(addprefix py/,\ objboundmeth.o \ objcell.o \ objclosure.o \ + objcode.o \ objcomplex.o \ objdeque.o \ objdict.o \ @@ -178,12 +219,14 @@ PY_CORE_O_BASENAME = $(addprefix py/,\ objnamedtuple.o \ objrange.o \ objreversed.o \ + objringio.o \ objset.o \ objsingleton.o \ objslice.o \ objstr.o \ objstrunicode.o \ objstringio.o \ + objtemplate.o \ objtraceback.o \ objtuple.o \ objtype.o \ @@ -203,10 +246,12 @@ PY_CORE_O_BASENAME = $(addprefix py/,\ modmath.o \ modcmath.o \ modmicropython.o \ + modstring.o \ modstruct.o \ modsys.o \ moderrno.o \ modthread.o \ + modweakref.o \ vm.o \ bc.o \ showbc.o \ @@ -260,6 +305,14 @@ $(HEADER_BUILD)/compressed.data.h: $(HEADER_BUILD)/compressed.collected $(HEADER_BUILD)/$(TRANSLATION).mo: $(TOP)/locale/$(TRANSLATION).po | $(HEADER_BUILD) $(Q)$(PYTHON) $(TOP)/tools/msgfmt.py -o $@ $^ +# Records which TRANSLATION the generated header was built for. It is rewritten +# only when the language changes, so that building another language in the +# same build directory regenerates compressed_translations.generated.h and +# translations-*.c instead of linking one language's strings against another +# language's tables. +$(HEADER_BUILD)/translation.stamp: FORCE | $(HEADER_BUILD) + $(Q)if [ "$$(cat $@ 2>/dev/null)" != "$(TRANSLATION)" ]; then echo "$(TRANSLATION)" > $@; fi + # translations-*.c is generated as a side-effect of building compressed_translations.generated.h # Specifying both in a single rule actually causes the rule to be run twice! # This alternative makes it run just once. @@ -268,7 +321,7 @@ $(HEADER_BUILD)/$(TRANSLATION).mo: $(TOP)/locale/$(TRANSLATION).po | $(HEADER_BU $(PY_BUILD)/translations-$(TRANSLATION).c: $(HEADER_BUILD)/compressed_translations.generated.h @true -$(HEADER_BUILD)/compressed_translations.generated.h: $(PY_SRC)/maketranslationdata.py $(HEADER_BUILD)/$(TRANSLATION).mo $(HEADER_BUILD)/qstrdefs.generated.h +$(HEADER_BUILD)/compressed_translations.generated.h: $(PY_SRC)/maketranslationdata.py $(HEADER_BUILD)/$(TRANSLATION).mo $(HEADER_BUILD)/qstrdefs.generated.h $(HEADER_BUILD)/translation.stamp $(STEPECHO) "GEN $@" $(Q)mkdir -p $(PY_BUILD) $(Q)$(PYTHON) $(PY_SRC)/maketranslationdata.py --compression_filename $(HEADER_BUILD)/compressed_translations.generated.h --translation $(HEADER_BUILD)/$(TRANSLATION).mo --translation_filename $(PY_BUILD)/translations-$(TRANSLATION).c --qstrdefs_filename $(HEADER_BUILD)/qstrdefs.generated.h --compression_level $(CIRCUITPY_MESSAGE_COMPRESSION_LEVEL) $(HEADER_BUILD)/qstrdefs.preprocessed.h @@ -276,7 +329,7 @@ $(HEADER_BUILD)/compressed_translations.generated.h: $(PY_SRC)/maketranslationda PY_CORE_O += $(PY_BUILD)/translations-$(TRANSLATION).o # build a list of registered modules for py/objmodule.c. -$(HEADER_BUILD)/moduledefs.h: $(HEADER_BUILD)/moduledefs.collected +$(HEADER_BUILD)/moduledefs.h: $(HEADER_BUILD)/moduledefs.collected $(PY_SRC)/makemoduledefs.py @$(ECHO) "GEN $@" $(Q)$(PYTHON) $(PY_SRC)/makemoduledefs.py $< > $@ diff --git a/py/pystack.c b/py/pystack.c index dcbef9c1d0c..ec3fe53e35a 100644 --- a/py/pystack.c +++ b/py/pystack.c @@ -26,6 +26,9 @@ #include +// CIRCUITPY-CHANGE: memset +#include + #include "py/runtime.h" #if MICROPY_ENABLE_PYSTACK @@ -38,6 +41,8 @@ void mp_pystack_init(void *start, void *end) { // CIRCUITPY-CHANGE: PLACE_IN_ITCM void *PLACE_IN_ITCM(mp_pystack_alloc)(size_t n_bytes) { + // CIRCUITPY-CHANGE: remember the size before it is rounded up + size_t requested = n_bytes; n_bytes = (n_bytes + (MICROPY_PYSTACK_ALIGN - 1)) & ~(MICROPY_PYSTACK_ALIGN - 1); #if MP_PYSTACK_DEBUG n_bytes += MICROPY_PYSTACK_ALIGN; @@ -48,6 +53,9 @@ void *PLACE_IN_ITCM(mp_pystack_alloc)(size_t n_bytes) { } void *ptr = MP_STATE_THREAD(pystack_cur); MP_STATE_THREAD(pystack_cur) += n_bytes; + // CIRCUITPY-CHANGE: the collector scans the whole pystack. Clear the padding, which the + // caller never writes, so it can't keep a pointer left by an earlier allocation. + memset((uint8_t *)ptr + requested, 0, n_bytes - requested); #if MP_PYSTACK_DEBUG *(size_t *)(MP_STATE_THREAD(pystack_cur) - MICROPY_PYSTACK_ALIGN) = n_bytes; #endif diff --git a/py/qstr.c b/py/qstr.c index 6a5896bdaf4..07caa869a5b 100644 --- a/py/qstr.c +++ b/py/qstr.c @@ -84,8 +84,9 @@ size_t qstr_compute_hash(const byte *data, size_t len) { #if MICROPY_QSTR_BYTES_IN_HASH const qstr_hash_t mp_qstr_const_hashes_static[] = { #ifndef NO_QSTR -#define QDEF0(id, hash, len, str) hash, -#define QDEF1(id, hash, len, str) +// CIRCUITPY-CHANGE: QDEF has an offset argument +#define QDEF0(id, hash, len, offset, str) hash, +#define QDEF1(id, hash, len, offset, str) // CIRCUITPY-CHANGE: translations #define TRANSLATION(id, length, compressed ...) #include "genhdr/qstrdefs.generated.h" @@ -97,18 +98,38 @@ const qstr_hash_t mp_qstr_const_hashes_static[] = { }; #endif -const qstr_len_t mp_qstr_const_lengths_static[] = { +// CIRCUITPY-CHANGE: The ROM pools store their strings in one NUL-separated blob +// per pool instead of a pointer array plus a length array. The blob is built by +// the preprocessor concatenating each QDEF's string literal followed by "\0", in +// file order; makeqstrdata.py computes the matching offsets, which are emitted as +// the QDEF offset argument. The offsets array has one extra trailing entry, the +// total blob length, so that qstr_len() is a difference of adjacent offsets. The +// string literal's own implicit NUL accounts for the "- 1" in sizeof() below. +const char mp_qstr_const_blob_static[] = #ifndef NO_QSTR -#define QDEF0(id, hash, len, str) len, -#define QDEF1(id, hash, len, str) -// CIRCUITPY-CHANGE: translations +#define QDEF0(id, hash, len, offset, str) str "\0" +#define QDEF1(id, hash, len, offset, str) #define TRANSLATION(id, length, compressed ...) #include "genhdr/qstrdefs.generated.h" #undef QDEF0 #undef QDEF1 -// CIRCUITPY-CHANGE: translations #undef TRANSLATION + #else + "" #endif +; + +const qstr_offset_t mp_qstr_const_offsets_static[] = { + #ifndef NO_QSTR +#define QDEF0(id, hash, len, offset, str) offset, +#define QDEF1(id, hash, len, offset, str) +#define TRANSLATION(id, length, compressed ...) + #include "genhdr/qstrdefs.generated.h" +#undef QDEF0 +#undef QDEF1 +#undef TRANSLATION + #endif + sizeof(mp_qstr_const_blob_static) - 1, }; const qstr_pool_t mp_qstr_const_pool_static = { @@ -116,24 +137,14 @@ const qstr_pool_t mp_qstr_const_pool_static = { 0, // no previous pool false, // is_sorted MICROPY_ALLOC_QSTR_ENTRIES_INIT, - MP_QSTRnumber_of_static, // corresponds to number of strings in array just below + MP_QSTRnumber_of_static, // corresponds to number of strings in the blob #if MICROPY_QSTR_BYTES_IN_HASH (qstr_hash_t *)mp_qstr_const_hashes_static, #endif - (qstr_len_t *)mp_qstr_const_lengths_static, - { - #ifndef NO_QSTR -#define QDEF0(id, hash, len, str) str, -#define QDEF1(id, hash, len, str) -// CIRCUITPY-CHANGE: translations -#define TRANSLATION(id, length, compressed ...) - #include "genhdr/qstrdefs.generated.h" -#undef QDEF0 -#undef QDEF1 -// CIRCUITPY-CHANGE: translations -#undef TRANSLATION - #endif - }, + // CIRCUITPY-CHANGE: strings live in the blob; no lengths array or qstrs[] + NULL, // lengths + mp_qstr_const_blob_static, + mp_qstr_const_offsets_static, }; // The next pool is the remainder of the qstrs defined in the firmware. This @@ -141,8 +152,9 @@ const qstr_pool_t mp_qstr_const_pool_static = { #if MICROPY_QSTR_BYTES_IN_HASH const qstr_hash_t mp_qstr_const_hashes[] = { #ifndef NO_QSTR -#define QDEF0(id, hash, len, str) -#define QDEF1(id, hash, len, str) hash, +// CIRCUITPY-CHANGE: QDEF has an offset argument +#define QDEF0(id, hash, len, offset, str) +#define QDEF1(id, hash, len, offset, str) hash, // CIRCUITPY-CHANGE: translations #define TRANSLATION(id, length, compressed ...) #include "genhdr/qstrdefs.generated.h" @@ -154,18 +166,32 @@ const qstr_hash_t mp_qstr_const_hashes[] = { }; #endif -const qstr_len_t mp_qstr_const_lengths[] = { +// CIRCUITPY-CHANGE: blob and offsets, see above +const char mp_qstr_const_blob[] = #ifndef NO_QSTR -#define QDEF0(id, hash, len, str) -#define QDEF1(id, hash, len, str) len, -// CIRCUITPY-CHANGE: translations +#define QDEF0(id, hash, len, offset, str) +#define QDEF1(id, hash, len, offset, str) str "\0" +#define TRANSLATION(id, length, compressed ...) + #include "genhdr/qstrdefs.generated.h" +#undef QDEF0 +#undef QDEF1 +#undef TRANSLATION + #else + "" + #endif +; + +const qstr_offset_t mp_qstr_const_offsets[] = { + #ifndef NO_QSTR +#define QDEF0(id, hash, len, offset, str) +#define QDEF1(id, hash, len, offset, str) offset, #define TRANSLATION(id, length, compressed ...) #include "genhdr/qstrdefs.generated.h" #undef QDEF0 #undef QDEF1 -// CIRCUITPY-CHANGE: translations #undef TRANSLATION #endif + sizeof(mp_qstr_const_blob) - 1, }; const qstr_pool_t mp_qstr_const_pool = { @@ -173,24 +199,14 @@ const qstr_pool_t mp_qstr_const_pool = { MP_QSTRnumber_of_static, true, // is_sorted MICROPY_ALLOC_QSTR_ENTRIES_INIT, - MP_QSTRnumber_of - MP_QSTRnumber_of_static, // corresponds to number of strings in array just below + MP_QSTRnumber_of - MP_QSTRnumber_of_static, // corresponds to number of strings in the blob #if MICROPY_QSTR_BYTES_IN_HASH (qstr_hash_t *)mp_qstr_const_hashes, #endif - (qstr_len_t *)mp_qstr_const_lengths, - { - #ifndef NO_QSTR -#define QDEF0(id, hash, len, str) -#define QDEF1(id, hash, len, str) str, -// CIRCUITPY-CHANGE: translations -#define TRANSLATION(id, length, compressed ...) - #include "genhdr/qstrdefs.generated.h" -#undef QDEF0 -#undef QDEF1 -// CIRCUITPY-CHANGE: translations -#undef TRANSLATION - #endif - }, + // CIRCUITPY-CHANGE: strings live in the blob; no lengths array or qstrs[] + NULL, // lengths + mp_qstr_const_blob, + mp_qstr_const_offsets, }; // If frozen code is enabled, then there is an additional, sorted, ROM pool @@ -228,6 +244,22 @@ static const qstr_pool_t *find_qstr(qstr *q) { return pool; } +// CIRCUITPY-CHANGE: ROM pools keep their strings in a blob addressed by offsets; +// runtime pools keep a pointer array and a length array. See qstr_pool_t. +static inline const char *pool_str(const qstr_pool_t *pool, size_t at) { + if (pool->blob != NULL) { + return pool->blob + pool->offsets[at]; + } + return pool->qstrs[at]; +} + +static inline size_t pool_len(const qstr_pool_t *pool, size_t at) { + if (pool->blob != NULL) { + return pool->offsets[at + 1] - pool->offsets[at] - 1; + } + return pool->lengths[at]; +} + // qstr_mutex must be taken while in this function static qstr qstr_add(mp_uint_t len, const char *q_ptr) { #if MICROPY_QSTR_BYTES_IN_HASH @@ -267,6 +299,9 @@ static qstr qstr_add(mp_uint_t len, const char *q_ptr) { #else pool->lengths = (qstr_len_t *)(pool->qstrs + new_alloc); #endif + // CIRCUITPY-CHANGE: runtime pools use qstrs[] and lengths, not a blob + pool->blob = NULL; + pool->offsets = NULL; 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_alloc; @@ -308,7 +343,8 @@ qstr qstr_find_strn(const char *str, size_t str_len) { if (pool->is_sorted) { while (high - low > 1) { size_t mid = (low + high) / 2; - int cmp = strncmp(str, pool->qstrs[mid], str_len); + // CIRCUITPY-CHANGE: pool accessor + int cmp = strncmp(str, pool_str(pool, mid), str_len); if (cmp <= 0) { high = mid; } else { @@ -323,8 +359,9 @@ qstr qstr_find_strn(const char *str, size_t str_len) { #if MICROPY_QSTR_BYTES_IN_HASH pool->hashes[at] == str_hash && #endif - pool->lengths[at] == str_len - && memcmp(pool->qstrs[at], str, str_len) == 0) { + // CIRCUITPY-CHANGE: pool accessors + pool_len(pool, at) == str_len + && memcmp(pool_str(pool, at), str, str_len) == 0) { return pool->total_prev_len + at; } } @@ -338,7 +375,7 @@ qstr qstr_from_str(const char *str) { return qstr_from_strn(str, strlen(str)); } -qstr qstr_from_strn(const char *str, size_t len) { +static qstr qstr_from_strn_helper(const char *str, size_t len, bool data_is_static) { QSTR_ENTER(); qstr q = qstr_find_strn(str, len); if (q == 0) { @@ -350,6 +387,12 @@ qstr qstr_from_strn(const char *str, size_t len) { mp_raise_msg(&mp_type_RuntimeError, MP_ERROR_TEXT("name too long")); } + if (data_is_static) { + // Given string data will be forever available so use it directly. + assert(str[len] == '\0'); + goto add; + } + // compute number of bytes needed to intern this string size_t n_bytes = len + 1; @@ -372,10 +415,11 @@ 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_maybe(char, al); + // CIRCUITPY-CHANGE: Don't collect the QSTR blocks that only contain a chunk of a string + MP_STATE_VM(qstr_last_chunk) = m_malloc_maybe_without_collect(sizeof(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_maybe(char, n_bytes); + MP_STATE_VM(qstr_last_chunk) = m_malloc_maybe_without_collect(sizeof(char) * n_bytes); if (MP_STATE_VM(qstr_last_chunk) == NULL) { QSTR_EXIT(); m_malloc_fail(n_bytes); @@ -393,35 +437,53 @@ qstr qstr_from_strn(const char *str, size_t len) { // store the interned strings' data memcpy(q_ptr, str, len); q_ptr[len] = '\0'; - q = qstr_add(len, q_ptr); + str = q_ptr; + + add: + q = qstr_add(len, str); } QSTR_EXIT(); return q; } +qstr qstr_from_strn(const char *str, size_t len) { + return qstr_from_strn_helper(str, len, false); +} + +#if MICROPY_VFS_ROM +// Create a new qstr that can forever reference the given string data. +qstr qstr_from_strn_static(const char *str, size_t len) { + return qstr_from_strn_helper(str, len, true); +} +#endif + mp_uint_t qstr_hash(qstr q) { const qstr_pool_t *pool = find_qstr(&q); #if MICROPY_QSTR_BYTES_IN_HASH return pool->hashes[q]; #else - return qstr_compute_hash((byte *)pool->qstrs[q], pool->lengths[q]); + // CIRCUITPY-CHANGE: pool accessors + return qstr_compute_hash((byte *)pool_str(pool, q), pool_len(pool, q)); #endif } size_t qstr_len(qstr q) { const qstr_pool_t *pool = find_qstr(&q); - return pool->lengths[q]; + // CIRCUITPY-CHANGE: pool accessor + return pool_len(pool, q); } const char *qstr_str(qstr q) { const qstr_pool_t *pool = find_qstr(&q); - return pool->qstrs[q]; + // CIRCUITPY-CHANGE: pool accessor + return pool_str(pool, q); } const byte *qstr_data(qstr q, size_t *len) { const qstr_pool_t *pool = find_qstr(&q); - *len = pool->lengths[q]; - return (byte *)pool->qstrs[q]; + // CIRCUITPY-CHANGE: pool accessors + *len = pool_len(pool, q); + return (byte *)pool_str(pool, q); } void qstr_pool_info(size_t *n_pool, size_t *n_qstr, size_t *n_str_data_bytes, size_t *n_total_bytes) { diff --git a/py/qstr.h b/py/qstr.h index 967990beea3..6c6e1a14ff0 100644 --- a/py/qstr.h +++ b/py/qstr.h @@ -38,8 +38,9 @@ // first entry in enum will be MP_QSTRnull=0, which indicates invalid/no qstr enum { #ifndef NO_QSTR -#define QDEF0(id, hash, len, str) id, -#define QDEF1(id, hash, len, str) +// CIRCUITPY-CHANGE: QDEF carries the string's offset within its pool's blob +#define QDEF0(id, hash, len, offset, str) id, +#define QDEF1(id, hash, len, offset, str) // CIRCUITPY-CHANGE #define TRANSLATION(english_id, number) #include "genhdr/qstrdefs.generated.h" @@ -50,8 +51,9 @@ enum { MP_QSTRstart_of_main = MP_QSTRnumber_of_static - 1, // unused but shifts the enum counter back one #ifndef NO_QSTR -#define QDEF0(id, hash, len, str) -#define QDEF1(id, hash, len, str) id, +// CIRCUITPY-CHANGE: QDEF carries the string's offset within its pool's blob +#define QDEF0(id, hash, len, offset, str) +#define QDEF1(id, hash, len, offset, str) id, #define TRANSLATION(english_id, number) #include "genhdr/qstrdefs.generated.h" #undef QDEF0 @@ -82,6 +84,9 @@ typedef uint16_t qstr_len_t; #error unimplemented qstr length decoding #endif +// CIRCUITPY-CHANGE: offset of a string within a ROM pool's blob +typedef uint16_t qstr_offset_t; + typedef struct _qstr_pool_t { const struct _qstr_pool_t *prev; size_t total_prev_len : (8 * sizeof(size_t) - 1); @@ -92,6 +97,12 @@ typedef struct _qstr_pool_t { qstr_hash_t *hashes; #endif qstr_len_t *lengths; + // CIRCUITPY-CHANGE: ROM pools store their strings in one NUL-separated blob. + // When blob is non-NULL, string i is at blob + offsets[i], its length is + // offsets[i + 1] - offsets[i] - 1 (offsets has len + 1 entries), and lengths + // and qstrs[] are unused. Runtime pools have blob == NULL and use lengths and qstrs[]. + const char *blob; + const qstr_offset_t *offsets; const char *qstrs[]; } qstr_pool_t; @@ -107,6 +118,9 @@ qstr qstr_find_strn(const char *str, size_t str_len); // returns MP_QSTRnull if qstr qstr_from_str(const char *str); qstr qstr_from_strn(const char *str, size_t len); +#if MICROPY_VFS_ROM +qstr qstr_from_strn_static(const char *str, size_t len); +#endif mp_uint_t qstr_hash(qstr q); const char *qstr_str(qstr q); diff --git a/py/qstrdefs.h b/py/qstrdefs.h index 01e784efc3a..afa57afa248 100644 --- a/py/qstrdefs.h +++ b/py/qstrdefs.h @@ -68,3 +68,7 @@ Q(utf-8) #if MICROPY_MODULE_FROZEN Q(.frozen) #endif + +#if MICROPY_PY_TSTRINGS +Q(string.templatelib) +#endif diff --git a/py/reader.c b/py/reader.c index 151e04cac2c..f129bcbd1f9 100644 --- a/py/reader.c +++ b/py/reader.c @@ -31,6 +31,10 @@ #include "py/mperrno.h" #include "py/mpthread.h" #include "py/reader.h" +// CIRCUITPY-CHANGE +#if CIRCUITPY_STORAGE_MAP_IMPORT +#include "shared-bindings/storage/__init__.h" +#endif typedef struct _mp_reader_mem_t { size_t free_len; // if >0 mem is freed on close by: m_free(beg, free_len) @@ -50,7 +54,7 @@ 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; - if (reader->free_len > 0) { + if (reader->free_len > 0 && reader->free_len != MP_READER_IS_ROM) { m_del(char, (char *)reader->beg, reader->free_len); } m_del_obj(mp_reader_mem_t, reader); @@ -67,6 +71,25 @@ void mp_reader_new_mem(mp_reader_t *reader, const byte *buf, size_t len, size_t reader->close = mp_reader_mem_close; } +const uint8_t *mp_reader_try_read_rom(mp_reader_t *reader, size_t len) { + // CIRCUITPY-CHANGE: a CIRCUITPY .mpy read from its flash runs + #if CIRCUITPY_STORAGE_MAP_IMPORT + if (reader->readbyte == storage_map_reader_readbyte) { + return storage_map_reader_try_read_rom(reader->data, len); + } + #endif + if (reader->readbyte != mp_reader_mem_readbyte) { + return NULL; + } + mp_reader_mem_t *m = reader->data; + if (m->free_len != MP_READER_IS_ROM) { + return NULL; + } + const uint8_t *data = m->cur; + m->cur += len; + return data; +} + #if MICROPY_READER_POSIX #include diff --git a/py/reader.h b/py/reader.h index 5cb1e67966c..6378457007c 100644 --- a/py/reader.h +++ b/py/reader.h @@ -28,6 +28,10 @@ #include "py/obj.h" +// Pass to the `free_len` argument to `mp_reader_new_mem` to indicate that the data is in ROM. +// This means that the data is addressable and will remain valid at least until a soft reset. +#define MP_READER_IS_ROM ((size_t)-1) + // the readbyte function must return the next byte in the input stream // it must return MP_READER_EOF if end of stream // it can be called again after returning MP_READER_EOF, and in that case must return MP_READER_EOF @@ -43,4 +47,9 @@ void mp_reader_new_mem(mp_reader_t *reader, const byte *buf, size_t len, size_t void mp_reader_new_file(mp_reader_t *reader, qstr filename); void mp_reader_new_file_from_fd(mp_reader_t *reader, int fd, bool close_fd); +// Try to efficiently read the given number of bytes from a ROM-based reader. +// Returns a valid, non-NULL pointer to the requested data if the reader points to ROM. +// Returns NULL if the reader does not point to ROM. +const uint8_t *mp_reader_try_read_rom(mp_reader_t *reader, size_t len); + #endif // MICROPY_INCLUDED_PY_READER_H diff --git a/py/repl.c b/py/repl.c index ed47dbd0c17..bbfdd2ea6a6 100644 --- a/py/repl.c +++ b/py/repl.c @@ -181,8 +181,11 @@ static bool test_qstr(mp_obj_t obj, qstr name) { 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) || - mp_map_lookup((mp_map_t *)&mp_builtin_extensible_module_map, MP_OBJ_NEW_QSTR(name), MP_MAP_LOOKUP); + return mp_map_lookup((mp_map_t *)&mp_builtin_module_map, MP_OBJ_NEW_QSTR(name), MP_MAP_LOOKUP) + #if MICROPY_HAVE_REGISTERED_EXTENSIBLE_MODULES + || mp_map_lookup((mp_map_t *)&mp_builtin_extensible_module_map, MP_OBJ_NEW_QSTR(name), MP_MAP_LOOKUP) + #endif + ; } } @@ -237,6 +240,10 @@ static void print_completions(const mp_print_t *print, for (qstr q = q_first; q <= q_last; ++q) { size_t d_len; const char *d_str = (const char *)qstr_data(q, &d_len); + // filter out words that begin with underscore unless there's already a partial match + if (s_len == 0 && d_str[0] == '_') { + continue; + } 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; @@ -244,7 +251,6 @@ static void print_completions(const mp_print_t *print, 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, " "); } diff --git a/py/ringbuf.c b/py/ringbuf.c index b81f671fdd9..c97b6350db4 100644 --- a/py/ringbuf.c +++ b/py/ringbuf.c @@ -9,6 +9,9 @@ // CIRCUITPY-CHANGE: API and implementation thoroughly reworked // No attempt to have atomic operations. Add guards if atomicity required. +#include + +#include "py/misc.h" #include "ringbuf.h" bool ringbuf_init(ringbuf_t *r, uint8_t *buf, size_t size) { @@ -103,24 +106,41 @@ 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, const 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; - } + size_t n = MIN(bufsize, r->size - r->used); + if (n == 0) { + return 0; + } + // At most two copies: up to the end of buf, then from its start. + size_t first = MIN(n, r->size - r->next_write); + memcpy(r->buf + r->next_write, buf, first); + memcpy(r->buf, buf + first, n - first); + r->next_write += n; + if (r->next_write >= r->size) { + r->next_write -= r->size; } - return bufsize; + r->used += n; + return n; } // 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++) { - int b = ringbuf_get(r); - if (b < 0) { - return i; - } - buf[i] = b; + size_t n = MIN(bufsize, r->used); + if (n == 0) { + return 0; + } + size_t first = MIN(n, r->size - r->next_read); + memcpy(buf, r->buf + r->next_read, first); + memcpy(buf + first, r->buf, n - first); + return ringbuf_discard_n(r, n); +} + +// Drops up to n of the oldest bytes. Returns how many were dropped. +size_t ringbuf_discard_n(ringbuf_t *r, size_t n) { + n = MIN(n, r->used); + r->next_read += n; + if (r->next_read >= r->size) { + r->next_read -= r->size; } - return bufsize; + r->used -= n; + return n; } diff --git a/py/ringbuf.h b/py/ringbuf.h index 52f50cd9c0b..120153093a9 100644 --- a/py/ringbuf.h +++ b/py/ringbuf.h @@ -40,6 +40,7 @@ size_t ringbuf_num_empty(ringbuf_t *r); size_t ringbuf_num_filled(ringbuf_t *r); size_t ringbuf_put_n(ringbuf_t *r, const uint8_t *buf, size_t bufsize); size_t ringbuf_get_n(ringbuf_t *r, uint8_t *buf, size_t bufsize); +size_t ringbuf_discard_n(ringbuf_t *r, size_t n); // Note: big-endian. Return -1 if can't read or write two bytes. int ringbuf_get16(ringbuf_t *r); diff --git a/py/runtime.c b/py/runtime.c index 29fcd04490f..62a7262fee5 100644 --- a/py/runtime.c +++ b/py/runtime.c @@ -45,9 +45,13 @@ #include "py/stream.h" #include "py/runtime.h" #include "py/builtin.h" -#include "py/stackctrl.h" +#include "py/cstack.h" #include "py/gc.h" +#if MICROPY_VFS_ROM && MICROPY_VFS_ROM_IOCTL +#include "extmod/vfs.h" +#endif + // CIRCUITPY-CHANGE #if CIRCUITPY_WARNINGS #include "shared-module/warnings/__init__.h" @@ -112,6 +116,9 @@ void mp_init(void) { #if MICROPY_EMIT_NATIVE MP_STATE_VM(default_emit_opt) = MP_EMIT_OPT_NONE; #endif + #if MICROPY_DEBUG_PRINTERS + MP_STATE_VM(mp_verbose_flag) = 0; + #endif #endif // init global module dict @@ -130,8 +137,8 @@ void mp_init(void) { MP_STATE_VM(mp_module_builtins_override_dict) = NULL; #endif - #if MICROPY_PERSISTENT_CODE_TRACK_RELOC_CODE - MP_STATE_VM(track_reloc_code_list) = MP_OBJ_NULL; + #if (MICROPY_EMIT_INLINE_ASM || MICROPY_ENABLE_NATIVE_CODE) && (MICROPY_PERSISTENT_CODE_TRACK_FUN_DATA || MICROPY_PERSISTENT_CODE_TRACK_BSS_RODATA) + MP_STATE_VM(persistent_code_root_pointers) = MP_OBJ_NULL; #endif #if MICROPY_PY_OS_DUPTERM @@ -187,6 +194,10 @@ void mp_init(void) { MP_STATE_VM(usbd) = MP_OBJ_NULL; #endif + #if MICROPY_PY_WEAKREF + mp_map_init(&MP_STATE_VM(mp_weakref_map), 0); + #endif + #if MICROPY_PY_THREAD_GIL mp_thread_mutex_init(&MP_STATE_VM(gil_mutex)); #endif @@ -197,6 +208,11 @@ void mp_init(void) { #endif MP_THREAD_GIL_ENTER(); + + #if MICROPY_VFS_ROM && MICROPY_VFS_ROM_IOCTL + // Mount ROMFS if it exists. + mp_vfs_mount_romfs_protected(); + #endif } void mp_deinit(void) { @@ -251,8 +267,7 @@ mp_obj_t MICROPY_WRAP_MP_LOAD_GLOBAL(mp_load_global)(qstr qst) { #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE mp_raise_msg(&mp_type_NameError, MP_ERROR_TEXT("name not defined")); #else - // CIRCUITPY-CHANGE: slight message change - mp_raise_msg_varg(&mp_type_NameError, MP_ERROR_TEXT("name '%q' is not defined"), qst); + mp_raise_msg_varg(&mp_type_NameError, MP_ERROR_TEXT("name '%q' isn't defined"), qst); #endif } } @@ -438,7 +453,7 @@ mp_obj_t MICROPY_WRAP_MP_BINARY_OP(mp_binary_op)(mp_binary_op_t op, mp_obj_t lhs // Operations that can overflow: // + result always fits in mp_int_t, then handled by SMALL_INT check // - result always fits in mp_int_t, then handled by SMALL_INT check - // * checked explicitly + // * checked explicitly for fit in mp_int_t, then handled by SMALL_INT check // / if lhs=MIN and rhs=-1; result always fits in mp_int_t, then handled by SMALL_INT check // % if lhs=MIN and rhs=-1; result always fits in mp_int_t, then handled by SMALL_INT check // << checked explicitly @@ -497,30 +512,16 @@ mp_obj_t MICROPY_WRAP_MP_BINARY_OP(mp_binary_op)(mp_binary_op_t op, mp_obj_t lhs break; case MP_BINARY_OP_MULTIPLY: case MP_BINARY_OP_INPLACE_MULTIPLY: { - - // If long long type exists and is larger than mp_int_t, then - // we can use the following code to perform overflow-checked multiplication. - // Otherwise (eg in x64 case) we must use mp_small_int_mul_overflow. - #if 0 - // compute result using long long precision - long long res = (long long)lhs_val * (long long)rhs_val; - if (res > MP_SMALL_INT_MAX || res < MP_SMALL_INT_MIN) { - // result overflowed SMALL_INT, so return higher precision integer - return mp_obj_new_int_from_ll(res); - } else { - // use standard precision - lhs_val = (mp_int_t)res; - } - #endif - - if (mp_small_int_mul_overflow(lhs_val, rhs_val)) { + mp_int_t int_res; + if (mp_mul_mp_int_t_overflow(lhs_val, rhs_val, &int_res)) { // use higher precision lhs = mp_obj_new_int_from_ll(lhs_val); goto generic_binary_op; } else { // use standard precision - return MP_OBJ_NEW_SMALL_INT(lhs_val * rhs_val); + lhs_val = int_res; } + break; } case MP_BINARY_OP_FLOOR_DIVIDE: case MP_BINARY_OP_INPLACE_FLOOR_DIVIDE: @@ -560,19 +561,19 @@ mp_obj_t MICROPY_WRAP_MP_BINARY_OP(mp_binary_op)(mp_binary_op_t op, mp_obj_t lhs mp_int_t ans = 1; while (rhs_val > 0) { if (rhs_val & 1) { - if (mp_small_int_mul_overflow(ans, lhs_val)) { + if (mp_mul_mp_int_t_overflow(ans, lhs_val, &ans)) { goto power_overflow; } - ans *= lhs_val; } if (rhs_val == 1) { break; } rhs_val /= 2; - if (mp_small_int_mul_overflow(lhs_val, lhs_val)) { + mp_int_t int_res; + if (mp_mul_mp_int_t_overflow(lhs_val, lhs_val, &int_res)) { goto power_overflow; } - lhs_val *= lhs_val; + lhs_val = int_res; } lhs_val = ans; } @@ -739,8 +740,8 @@ 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(MP_ERROR_TEXT("object not callable")); #else - // CIRCUITPY-CHANGE: use new raise function and different message - mp_raise_TypeError_varg(MP_ERROR_TEXT("'%q' object is not callable"), mp_obj_get_type_qstr(fun_in)); + // CIRCUITPY-CHANGE: more specific mp_raise + mp_raise_TypeError_varg(MP_ERROR_TEXT("'%q' object isn't callable"), mp_obj_get_type_qstr(fun_in)); #endif } @@ -968,7 +969,7 @@ mp_obj_t mp_call_method_n_kw_var(bool have_self, size_t n_args_n_kw, const mp_ob // unpacked items are stored in reverse order into the array pointed to by items // CIRCUITPY-CHANGE: noline -void __attribute__((noinline, )) mp_unpack_sequence(mp_obj_t seq_in, size_t num, mp_obj_t *items) { +MP_NOINLINE void mp_unpack_sequence(mp_obj_t seq_in, size_t num, mp_obj_t *items) { size_t seq_len; if (mp_obj_is_type(seq_in, &mp_type_tuple) || mp_obj_is_type(seq_in, &mp_type_list)) { mp_obj_t *seq_items; @@ -1293,6 +1294,19 @@ void mp_load_method(mp_obj_t base, qstr attr, mp_obj_t *dest) { mp_raise_msg_varg(&mp_type_AttributeError, MP_ERROR_TEXT("type object '%q' has no attribute '%q'"), ((mp_obj_type_t *)MP_OBJ_TO_PTR(base))->name, attr); + #if MICROPY_MODULE___ALL__ && MICROPY_ERROR_REPORTING >= MICROPY_ERROR_REPORTING_DETAILED + } else if (mp_obj_is_type(base, &mp_type_module)) { + // report errors in __all__ as done by CPython + mp_obj_t dest_name[2]; + qstr module_name = MP_QSTR_; + mp_load_method_maybe(base, MP_QSTR___name__, dest_name); + if (mp_obj_is_qstr(dest_name[0])) { + module_name = mp_obj_str_get_qstr(dest_name[0]); + } + mp_raise_msg_varg(&mp_type_AttributeError, + MP_ERROR_TEXT("module '%q' has no attribute '%q'"), + module_name, attr); + #endif } else { mp_raise_msg_varg(&mp_type_AttributeError, MP_ERROR_TEXT("'%s' object has no attribute '%q'"), @@ -1417,9 +1431,9 @@ mp_obj_t mp_getiter(mp_obj_t o_in, mp_obj_iter_buf_t *iter_buf) { #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE mp_raise_TypeError(MP_ERROR_TEXT("object not iterable")); #else - // CIRCUITPY-CHANGE: raise function + // CIRCUITPY-CHANGE: more specific mp_raise mp_raise_TypeError_varg( - MP_ERROR_TEXT("'%q' object is not iterable"), mp_obj_get_type_qstr(o_in)); + MP_ERROR_TEXT("'%q' object isn't iterable"), mp_obj_get_type_qstr(o_in)); #endif } @@ -1454,8 +1468,8 @@ mp_obj_t mp_iternext_allow_raise(mp_obj_t o_in) { #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE mp_raise_TypeError(MP_ERROR_TEXT("object not an iterator")); #else - // CIRCUITPY-CHANGE: raise function - mp_raise_TypeError_varg(MP_ERROR_TEXT("'%q' object is not an iterator"), + // CIRCUITPY-CHANGE: more specific mp_raise + mp_raise_TypeError_varg(MP_ERROR_TEXT("'%q' object isn't an iterator"), mp_obj_get_type_qstr(o_in)); #endif } @@ -1465,7 +1479,7 @@ mp_obj_t mp_iternext_allow_raise(mp_obj_t o_in) { // will always return MP_OBJ_STOP_ITERATION instead of raising StopIteration() (or any subclass thereof) // may raise other exceptions mp_obj_t mp_iternext(mp_obj_t o_in) { - MP_STACK_CHECK(); // enumerate, filter, map and zip can recursively call mp_iternext + mp_cstack_check(); // enumerate, filter, map and zip can recursively call mp_iternext const mp_obj_type_t *type = mp_obj_get_type(o_in); if (TYPE_HAS_ITERNEXT(type)) { MP_STATE_THREAD(stop_iteration_arg) = MP_OBJ_NULL; @@ -1492,8 +1506,8 @@ mp_obj_t mp_iternext(mp_obj_t o_in) { #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE mp_raise_TypeError(MP_ERROR_TEXT("object not an iterator")); #else - // CIRCUITPY-CHANGE: raise function - mp_raise_TypeError_varg(MP_ERROR_TEXT("'%q' object is not an iterator"), + // CIRCUITPY-CHANGE: more specific mp_raise + mp_raise_TypeError_varg(MP_ERROR_TEXT("'%q' object isn't an iterator"), mp_obj_get_type_qstr(o_in)); #endif } @@ -1597,7 +1611,7 @@ mp_obj_t mp_make_raise_obj(mp_obj_t o) { } if (mp_obj_is_exception_instance(o)) { - // o is an instance of an exception, so use it as the exception + // o is a fully-constructed instance of an exception, so use it as the exception return o; } else { // o cannot be used as an exception, so return a type error (which will be raised by the caller) @@ -1611,7 +1625,7 @@ mp_obj_t mp_import_name(qstr name, mp_obj_t fromlist, mp_obj_t level) { // build args array mp_obj_t args[5]; args[0] = MP_OBJ_NEW_QSTR(name); - args[1] = mp_const_none; // TODO should be globals + args[1] = MP_OBJ_FROM_PTR(mp_globals_get()); // globals of the current context args[2] = mp_const_none; // TODO should be locals args[3] = fromlist; args[4] = level; @@ -1631,20 +1645,17 @@ mp_obj_t mp_import_name(qstr name, mp_obj_t fromlist, mp_obj_t level) { } // CIRCUITPY-CHANGE: noinline -mp_obj_t __attribute__((noinline, )) mp_import_from(mp_obj_t module, qstr name) { +MP_NOINLINE mp_obj_t mp_import_from(mp_obj_t module, qstr name) { DEBUG_printf("import from %p %s\n", module, qstr_str(name)); mp_obj_t dest[2]; mp_load_method_maybe(module, name, dest); - if (dest[1] != MP_OBJ_NULL) { - // Hopefully we can't import bound method from an object - import_error: - mp_raise_msg_varg(&mp_type_ImportError, MP_ERROR_TEXT("can't import name %q"), name); - } - - if (dest[0] != MP_OBJ_NULL) { + // Importing a bound method from a class instance. + return mp_obj_new_bound_meth(dest[0], dest[1]); + } else if (dest[0] != MP_OBJ_NULL) { + // Importing a function or attribute. return dest[0]; } @@ -1677,33 +1688,46 @@ mp_obj_t __attribute__((noinline, )) mp_import_from(mp_obj_t module, qstr name) goto import_error; #endif + +import_error: + mp_raise_msg_varg(&mp_type_ImportError, MP_ERROR_TEXT("can't import name %q"), name); } void mp_import_all(mp_obj_t module) { DEBUG_printf("import all %p\n", module); - // CIRCUITPY-CHANGE: displayio name changes; remove in 10.0 - #if CIRCUITPY_DISPLAYIO && CIRCUITPY_WARNINGS - if (module == &displayio_module) { - #if CIRCUITPY_BUSDISPLAY - warnings_warn(&mp_type_FutureWarning, MP_ERROR_TEXT("%q moved from %q to %q"), MP_QSTR_Display, MP_QSTR_displayio, MP_QSTR_busdisplay); - warnings_warn(&mp_type_FutureWarning, MP_ERROR_TEXT("%q renamed %q"), MP_QSTR_Display, MP_QSTR_BusDisplay); - #endif - #if CIRCUITPY_EPAPERDISPLAY - warnings_warn(&mp_type_FutureWarning, MP_ERROR_TEXT("%q moved from %q to %q"), MP_QSTR_EPaperDisplay, MP_QSTR_displayio, MP_QSTR_epaperdisplay); - #endif - #if CIRCUITPY_FOURWIRE - warnings_warn(&mp_type_FutureWarning, MP_ERROR_TEXT("%q moved from %q to %q"), MP_QSTR_FourWire, MP_QSTR_displayio, MP_QSTR_fourwire); - #endif - #if CIRCUITPY_I2CDISPLAYBUS - warnings_warn(&mp_type_FutureWarning, MP_ERROR_TEXT("%q moved from %q to %q"), MP_QSTR_I2CDisplay, MP_QSTR_displayio, MP_QSTR_i2cdisplaybus); - warnings_warn(&mp_type_FutureWarning, MP_ERROR_TEXT("%q renamed %q"), MP_QSTR_I2CDisplay, MP_QSTR_I2CDisplayBus); - #endif + mp_obj_t dest[2]; + + #if MICROPY_MODULE___ALL__ + mp_load_method_protected(module, MP_QSTR___all__, dest, false); + if (dest[0] != MP_OBJ_NULL) { + // When __all__ is defined, we must explicitly load all specified + // symbols, possibly invoking the module __getattr__ function + size_t len; + mp_obj_t *items; + mp_obj_get_array(dest[0], &len, &items); + for (size_t i = 0; i < len; i++) { + qstr qname = mp_obj_str_get_qstr(items[i]); + mp_load_method(module, qname, dest); + mp_store_name(qname, dest[0]); + } + return; } #endif - // TODO: Support __all__ - mp_map_t *map = &mp_obj_module_get_globals(module)->map; + #if MICROPY_CPYTHON_COMPAT + // Load the dict from the module. In MicroPython, if __dict__ is + // available then it always returns a native mp_obj_dict_t instance. + mp_load_method(module, MP_QSTR___dict__, dest); + #else + // Without MICROPY_CPYTHON_COMPAT __dict__ is not available, so just + // assume the given module is actually an mp_obj_module_t instance. + dest[0] = MP_OBJ_FROM_PTR(mp_obj_module_get_globals(module)); + #endif + + // By default, the set of public names includes all names found in the module's + // namespace which do not begin with an underscore character ('_') + mp_map_t *map = mp_obj_dict_get_map(dest[0]); for (size_t i = 0; i < map->alloc; i++) { if (mp_map_slot_is_filled(map, i)) { // Entry in module global scope may be generated programmatically @@ -1738,10 +1762,13 @@ mp_obj_t mp_parse_compile_execute(mp_lexer_t *lex, mp_parse_input_kind_t parse_i mp_obj_t module_fun = mp_compile(&parse_tree, source_name, parse_input_kind == MP_PARSE_SINGLE_INPUT); mp_obj_t ret; - if (MICROPY_PY_BUILTINS_COMPILE && globals == NULL) { + #if MICROPY_PY_BUILTINS_COMPILE && MICROPY_PY_BUILTINS_CODE == MICROPY_PY_BUILTINS_CODE_MINIMUM + if (globals == NULL) { // for compile only, return value is the module function ret = module_fun; - } else { + } else + #endif + { // execute module function and get return value ret = mp_call_function_0(module_fun); } @@ -1756,7 +1783,7 @@ mp_obj_t mp_parse_compile_execute(mp_lexer_t *lex, mp_parse_input_kind_t parse_i #endif // MICROPY_ENABLE_COMPILER // CIRCUITPY-CHANGE: MP_COLD -NORETURN MP_COLD void m_malloc_fail(size_t num_bytes) { +MP_COLD MP_NORETURN void m_malloc_fail(size_t num_bytes) { DEBUG_printf("memory allocation failed, allocating %u bytes\n", (uint)num_bytes); #if MICROPY_ENABLE_GC if (gc_is_locked()) { @@ -1770,29 +1797,29 @@ NORETURN MP_COLD void m_malloc_fail(size_t num_bytes) { #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_NONE // CIRCUITPY-CHANGE: MP_COLD -NORETURN MP_COLD void mp_raise_type(const mp_obj_type_t *exc_type) { +MP_COLD MP_NORETURN void mp_raise_type(const mp_obj_type_t *exc_type) { nlr_raise(mp_obj_new_exception(exc_type)); } // CIRCUITPY-CHANGE: MP_COLD -NORETURN MP_COLD void mp_raise_ValueError_no_msg(void) { +MP_COLD MP_NORETURN void mp_raise_ValueError_no_msg(void) { mp_raise_type(&mp_type_ValueError); } // CIRCUITPY-CHANGE: MP_COLD -NORETURN MP_COLD void mp_raise_TypeError_no_msg(void) { +MP_COLD MP_NORETURN void mp_raise_TypeError_no_msg(void) { mp_raise_type(&mp_type_TypeError); } // CIRCUITPY-CHANGE: MP_COLD -NORETURN MP_COLD void mp_raise_NotImplementedError_no_msg(void) { +MP_COLD MP_NORETURN void mp_raise_NotImplementedError_no_msg(void) { mp_raise_type(&mp_type_NotImplementedError); } #else // CIRCUITPY-CHANGE: MP_COLD -NORETURN MP_COLD void mp_raise_msg(const mp_obj_type_t *exc_type, mp_rom_error_text_t msg) { +MP_COLD MP_NORETURN void mp_raise_msg(const mp_obj_type_t *exc_type, mp_rom_error_text_t msg) { if (msg == NULL) { nlr_raise(mp_obj_new_exception(exc_type)); } else { @@ -1801,24 +1828,24 @@ NORETURN MP_COLD void mp_raise_msg(const mp_obj_type_t *exc_type, mp_rom_error_t } // CIRCUITPY-CHANGE: new function for use below. -NORETURN MP_COLD void mp_raise_msg_vlist(const mp_obj_type_t *exc_type, mp_rom_error_text_t fmt, va_list argptr) { +MP_COLD MP_NORETURN void mp_raise_msg_vlist(const mp_obj_type_t *exc_type, mp_rom_error_text_t fmt, va_list argptr) { mp_obj_t exception = mp_obj_new_exception_msg_vlist(exc_type, fmt, argptr); nlr_raise(exception); } // CIRCUITPY-CHANGE: MP_COLD and use mp_raise_msg_vlist() -NORETURN MP_COLD void mp_raise_msg_varg(const mp_obj_type_t *exc_type, mp_rom_error_text_t fmt, ...) { +MP_COLD MP_NORETURN void mp_raise_msg_varg(const mp_obj_type_t *exc_type, mp_rom_error_text_t fmt, ...) { va_list argptr; va_start(argptr, fmt); mp_raise_msg_vlist(exc_type, fmt, argptr); va_end(argptr); } -NORETURN MP_COLD void mp_raise_ValueError(mp_rom_error_text_t msg) { +MP_COLD MP_NORETURN void mp_raise_ValueError(mp_rom_error_text_t msg) { mp_raise_msg(&mp_type_ValueError, msg); } -NORETURN MP_COLD void mp_raise_msg_str(const mp_obj_type_t *exc_type, const char *msg) { +MP_COLD MP_NORETURN void mp_raise_msg_str(const mp_obj_type_t *exc_type, const char *msg) { if (msg == NULL) { nlr_raise(mp_obj_new_exception(exc_type)); } else { @@ -1827,17 +1854,17 @@ NORETURN MP_COLD void mp_raise_msg_str(const mp_obj_type_t *exc_type, const char } // CIRCUITPY-CHANGE: added -NORETURN MP_COLD void mp_raise_AttributeError(mp_rom_error_text_t msg) { +MP_COLD MP_NORETURN void mp_raise_AttributeError(mp_rom_error_text_t msg) { mp_raise_msg(&mp_type_AttributeError, msg); } // CIRCUITPY-CHANGE: added -NORETURN MP_COLD void mp_raise_RuntimeError(mp_rom_error_text_t msg) { +MP_COLD MP_NORETURN void mp_raise_RuntimeError(mp_rom_error_text_t msg) { mp_raise_msg(&mp_type_RuntimeError, msg); } // CIRCUITPY-CHANGE: added -NORETURN MP_COLD void mp_raise_RuntimeError_varg(mp_rom_error_text_t fmt, ...) { +MP_COLD MP_NORETURN void mp_raise_RuntimeError_varg(mp_rom_error_text_t fmt, ...) { va_list argptr; va_start(argptr, fmt); mp_raise_msg_vlist(&mp_type_RuntimeError, fmt, argptr); @@ -1845,17 +1872,17 @@ NORETURN MP_COLD void mp_raise_RuntimeError_varg(mp_rom_error_text_t fmt, ...) { } // CIRCUITPY-CHANGE: added -NORETURN MP_COLD void mp_raise_ImportError(mp_rom_error_text_t msg) { +MP_COLD MP_NORETURN void mp_raise_ImportError(mp_rom_error_text_t msg) { mp_raise_msg(&mp_type_ImportError, msg); } // CIRCUITPY-CHANGE: added -NORETURN MP_COLD void mp_raise_IndexError(mp_rom_error_text_t msg) { +MP_COLD MP_NORETURN void mp_raise_IndexError(mp_rom_error_text_t msg) { mp_raise_msg(&mp_type_IndexError, msg); } // CIRCUITPY-CHANGE: added -NORETURN MP_COLD void mp_raise_IndexError_varg(mp_rom_error_text_t fmt, ...) { +MP_COLD MP_NORETURN void mp_raise_IndexError_varg(mp_rom_error_text_t fmt, ...) { va_list argptr; va_start(argptr, fmt); mp_raise_msg_vlist(&mp_type_IndexError, fmt, argptr); @@ -1863,7 +1890,7 @@ NORETURN MP_COLD void mp_raise_IndexError_varg(mp_rom_error_text_t fmt, ...) { } // CIRCUITPY-CHANGE: added -NORETURN MP_COLD void mp_raise_ValueError_varg(mp_rom_error_text_t fmt, ...) { +MP_COLD MP_NORETURN void mp_raise_ValueError_varg(mp_rom_error_text_t fmt, ...) { va_list argptr; va_start(argptr, fmt); mp_raise_msg_vlist(&mp_type_ValueError, fmt, argptr); @@ -1871,12 +1898,12 @@ NORETURN MP_COLD void mp_raise_ValueError_varg(mp_rom_error_text_t fmt, ...) { } // CIRCUITPY-CHANGE: MP_COLD -NORETURN MP_COLD void mp_raise_TypeError(mp_rom_error_text_t msg) { +MP_COLD MP_NORETURN void mp_raise_TypeError(mp_rom_error_text_t msg) { mp_raise_msg(&mp_type_TypeError, msg); } // CIRCUITPY-CHANGE: added -NORETURN MP_COLD void mp_raise_TypeError_varg(mp_rom_error_text_t fmt, ...) { +MP_COLD MP_NORETURN void mp_raise_TypeError_varg(mp_rom_error_text_t fmt, ...) { va_list argptr; va_start(argptr, fmt); mp_raise_msg_vlist(&mp_type_TypeError, fmt, argptr); @@ -1884,12 +1911,12 @@ NORETURN MP_COLD void mp_raise_TypeError_varg(mp_rom_error_text_t fmt, ...) { } // CIRCUITPY-CHANGE: added -NORETURN MP_COLD void mp_raise_OSError_msg(mp_rom_error_text_t msg) { +MP_COLD MP_NORETURN void mp_raise_OSError_msg(mp_rom_error_text_t msg) { mp_raise_msg(&mp_type_OSError, msg); } // CIRCUITPY-CHANGE: added -NORETURN MP_COLD void mp_raise_OSError_errno_str(int errno_, mp_obj_t str) { +MP_COLD MP_NORETURN void mp_raise_OSError_errno_str(int errno_, mp_obj_t str) { mp_obj_t args[2] = { MP_OBJ_NEW_SMALL_INT(errno_), str, @@ -1898,7 +1925,7 @@ NORETURN MP_COLD void mp_raise_OSError_errno_str(int errno_, mp_obj_t str) { } // CIRCUITPY-CHANGE: added -NORETURN MP_COLD void mp_raise_OSError_msg_varg(mp_rom_error_text_t fmt, ...) { +MP_COLD MP_NORETURN void mp_raise_OSError_msg_varg(mp_rom_error_text_t fmt, ...) { va_list argptr; va_start(argptr, fmt); mp_raise_msg_vlist(&mp_type_OSError, fmt, argptr); @@ -1906,21 +1933,23 @@ NORETURN MP_COLD void mp_raise_OSError_msg_varg(mp_rom_error_text_t fmt, ...) { } // CIRCUITPY-CHANGE: added -NORETURN MP_COLD void mp_raise_ConnectionError(mp_rom_error_text_t msg) { +MP_COLD MP_NORETURN void mp_raise_ConnectionError(mp_rom_error_text_t msg) { mp_raise_msg(&mp_type_ConnectionError, msg); } // CIRCUITPY-CHANGE: added -NORETURN MP_COLD void mp_raise_BrokenPipeError(void) { +MP_COLD MP_NORETURN void mp_raise_BrokenPipeError(void) { mp_raise_type_arg(&mp_type_BrokenPipeError, MP_OBJ_NEW_SMALL_INT(MP_EPIPE)); } -NORETURN MP_COLD void mp_raise_NotImplementedError(mp_rom_error_text_t msg) { +MP_COLD MP_NORETURN void mp_raise_NotImplementedError(mp_rom_error_text_t msg) { mp_raise_msg(&mp_type_NotImplementedError, msg); } +#endif + // CIRCUITPY-CHANGE: added -NORETURN MP_COLD void mp_raise_NotImplementedError_varg(mp_rom_error_text_t fmt, ...) { +MP_COLD MP_NORETURN void mp_raise_NotImplementedError_varg(mp_rom_error_text_t fmt, ...) { va_list argptr; va_start(argptr, fmt); mp_raise_msg_vlist(&mp_type_NotImplementedError, fmt, argptr); @@ -1928,7 +1957,7 @@ NORETURN MP_COLD void mp_raise_NotImplementedError_varg(mp_rom_error_text_t fmt, } // CIRCUITPY-CHANGE: added -NORETURN MP_COLD void mp_raise_OverflowError_varg(mp_rom_error_text_t fmt, ...) { +MP_COLD MP_NORETURN void mp_raise_OverflowError_varg(mp_rom_error_text_t fmt, ...) { va_list argptr; va_start(argptr, fmt); mp_raise_msg_vlist(&mp_type_OverflowError, fmt, argptr); @@ -1936,12 +1965,11 @@ NORETURN MP_COLD void mp_raise_OverflowError_varg(mp_rom_error_text_t fmt, ...) } // CIRCUITPY-CHANGE: MP_COLD -NORETURN MP_COLD void mp_raise_type_arg(const mp_obj_type_t *exc_type, mp_obj_t arg) { +MP_COLD MP_NORETURN void mp_raise_type_arg(const mp_obj_type_t *exc_type, mp_obj_t arg) { nlr_raise(mp_obj_new_exception_arg1(exc_type, arg)); } -// CIRCUITPY-CHANGE: MP_COLD -NORETURN void mp_raise_StopIteration(mp_obj_t arg) { +MP_NORETURN void mp_raise_StopIteration(mp_obj_t arg) { if (arg == MP_OBJ_NULL) { mp_raise_type(&mp_type_StopIteration); } else { @@ -1949,7 +1977,7 @@ NORETURN void mp_raise_StopIteration(mp_obj_t arg) { } } -NORETURN void mp_raise_TypeError_int_conversion(mp_const_obj_t arg) { +MP_NORETURN void mp_raise_TypeError_int_conversion(mp_const_obj_t arg) { #if MICROPY_ERROR_REPORTING <= MICROPY_ERROR_REPORTING_TERSE (void)arg; mp_raise_TypeError(MP_ERROR_TEXT("can't convert to int")); @@ -1960,12 +1988,12 @@ NORETURN void mp_raise_TypeError_int_conversion(mp_const_obj_t arg) { } // CIRCUITPY-CHANGE: MP_COLD -NORETURN MP_COLD void mp_raise_OSError(int errno_) { +MP_COLD MP_NORETURN void mp_raise_OSError(int errno_) { mp_raise_type_arg(&mp_type_OSError, MP_OBJ_NEW_SMALL_INT(errno_)); } // CIRCUITPY-CHANGE: MP_COLD -NORETURN MP_COLD void mp_raise_OSError_with_filename(int errno_, const char *filename) { +MP_COLD MP_NORETURN void mp_raise_OSError_with_filename(int errno_, const char *filename) { vstr_t vstr; vstr_init(&vstr, 32); vstr_printf(&vstr, "can't open %s", filename); @@ -1975,13 +2003,12 @@ NORETURN MP_COLD void mp_raise_OSError_with_filename(int errno_, const char *fil } // CIRCUITPY-CHANGE: added -NORETURN MP_COLD void mp_raise_ZeroDivisionError(void) { +MP_COLD MP_NORETURN void mp_raise_ZeroDivisionError(void) { mp_raise_msg(&mp_type_ZeroDivisionError, MP_ERROR_TEXT("division by zero")); } #if MICROPY_STACK_CHECK || MICROPY_ENABLE_PYSTACK // CIRCUITPY-CHANGE: MP_COLD -NORETURN MP_COLD void mp_raise_recursion_depth(void) { +MP_COLD MP_NORETURN void mp_raise_recursion_depth(void) { mp_raise_RuntimeError(MP_ERROR_TEXT("maximum recursion depth exceeded")); } #endif -#endif diff --git a/py/runtime.h b/py/runtime.h index b92eb23c9d7..38fb05db568 100644 --- a/py/runtime.h +++ b/py/runtime.h @@ -30,18 +30,19 @@ #include "py/mpstate.h" #include "py/pystack.h" -#include "py/stackctrl.h" +#include "py/cstack.h" // CIRCUITPY-CHANGE #include "supervisor/linker.h" #include "supervisor/shared/translate/translate.h" // For use with mp_call_function_1_from_nlr_jump_callback. +// Initialize an nlr_jump_callback_node_call_function_1_t struct for use with +// nlr_push_jump_callback(&ctx.callback, mp_call_function_1_from_nlr_jump_callback); #define MP_DEFINE_NLR_JUMP_CALLBACK_FUNCTION_1(ctx, f, a) \ - nlr_jump_callback_node_call_function_1_t ctx = { \ - .func = (void (*)(void *))(f), \ - .arg = (a), \ - } + nlr_jump_callback_node_call_function_1_t ctx; \ + ctx.func = (void (*)(void *))(f); \ + ctx.arg = (a) typedef enum { MP_VM_RETURN_NORMAL, @@ -58,6 +59,13 @@ typedef enum { MP_ARG_KW_ONLY = 0x200, } mp_arg_flag_t; +// These first two enum values match the original signature of `mp_handle_pending(bool)`. +typedef enum { + MP_HANDLE_PENDING_CALLBACKS_AND_CLEAR_EXCEPTIONS = false, + MP_HANDLE_PENDING_CALLBACKS_AND_EXCEPTIONS = true, + MP_HANDLE_PENDING_CALLBACKS_ONLY, +} mp_handle_pending_behaviour_t; + typedef union _mp_arg_val_t { bool u_bool; mp_int_t u_int; @@ -106,7 +114,8 @@ void mp_sched_keyboard_interrupt(void); #if MICROPY_ENABLE_VM_ABORT void mp_sched_vm_abort(void); #endif -void mp_handle_pending(bool raise_exc); + +void mp_handle_pending(mp_handle_pending_behaviour_t behavior); #if MICROPY_ENABLE_SCHEDULER void mp_sched_lock(void); @@ -134,7 +143,7 @@ void mp_event_wait_indefinite(void); void mp_event_wait_ms(mp_uint_t timeout_ms); // 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); +int mp_print_mp_int(const mp_print_t *print, mp_obj_t x, unsigned 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); static inline void mp_arg_check_num(size_t n_args, size_t n_kw, size_t n_args_min, size_t n_args_max, bool takes_kw) { @@ -142,11 +151,11 @@ static inline void mp_arg_check_num(size_t n_args, size_t n_kw, size_t n_args_mi } 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); +MP_NORETURN void mp_arg_error_terse_mismatch(void); +MP_NORETURN void mp_arg_error_unimpl_kw(void); // CIRCUITPY-CHANGE: arg validation routines -NORETURN void mp_arg_error_invalid(qstr arg_name); +MP_NORETURN void mp_arg_error_invalid(qstr arg_name); mp_int_t mp_arg_validate_int(mp_int_t i, mp_int_t required_i, qstr arg_name); mp_int_t mp_arg_validate_int_min(mp_int_t i, mp_int_t min, qstr arg_name); mp_int_t mp_arg_validate_int_max(mp_int_t i, mp_int_t j, qstr arg_name); @@ -188,16 +197,22 @@ void mp_call_function_1_from_nlr_jump_callback(void *ctx_in); static inline void mp_thread_init_state(mp_state_thread_t *ts, size_t stack_size, mp_obj_dict_t *locals, mp_obj_dict_t *globals) { mp_thread_set_state(ts); - mp_stack_set_top(ts + 1); // need to include ts in root-pointer scan - mp_stack_set_limit(stack_size); + mp_cstack_init_with_top(ts + 1, stack_size); // need to include ts in root-pointer scan // GC starts off unlocked ts->gc_lock_depth = 0; // There are no pending jump callbacks or exceptions yet + ts->nlr_top = NULL; ts->nlr_jump_callback_top = NULL; ts->mp_pending_exception = MP_OBJ_NULL; + #if MICROPY_PY_SYS_SETTRACE + ts->prof_trace_callback = MP_OBJ_NULL; + ts->prof_callback_is_executing = false; + ts->current_code_state = NULL; + #endif + // If locals/globals are not given, inherit from main thread if (locals == NULL) { locals = mp_state_ctx.thread.dict_locals; @@ -275,10 +290,10 @@ mp_obj_t mp_import_from(mp_obj_t module, qstr name); void mp_import_all(mp_obj_t module); #if MICROPY_ERROR_REPORTING == MICROPY_ERROR_REPORTING_NONE -NORETURN void mp_raise_type(const mp_obj_type_t *exc_type); -NORETURN void mp_raise_ValueError_no_msg(void); -NORETURN void mp_raise_TypeError_no_msg(void); -NORETURN void mp_raise_NotImplementedError_no_msg(void); +MP_NORETURN void mp_raise_type(const mp_obj_type_t *exc_type); +MP_NORETURN void mp_raise_ValueError_no_msg(void); +MP_NORETURN void mp_raise_TypeError_no_msg(void); +MP_NORETURN void mp_raise_NotImplementedError_no_msg(void); #define mp_raise_msg(exc_type, msg) mp_raise_type(exc_type) #define mp_raise_msg_varg(exc_type, ...) mp_raise_type(exc_type) #define mp_raise_ValueError(msg) mp_raise_ValueError_no_msg() @@ -286,46 +301,46 @@ NORETURN void mp_raise_NotImplementedError_no_msg(void); #define mp_raise_NotImplementedError(msg) mp_raise_NotImplementedError_no_msg() #else #define mp_raise_type(exc_type) mp_raise_msg(exc_type, NULL) -NORETURN void mp_raise_msg(const mp_obj_type_t *exc_type, mp_rom_error_text_t msg); -NORETURN void mp_raise_msg_varg(const mp_obj_type_t *exc_type, mp_rom_error_text_t fmt, ...); -NORETURN void mp_raise_ValueError(mp_rom_error_text_t msg); -NORETURN void mp_raise_TypeError(mp_rom_error_text_t msg); -NORETURN void mp_raise_NotImplementedError(mp_rom_error_text_t msg); +MP_NORETURN void mp_raise_msg(const mp_obj_type_t *exc_type, mp_rom_error_text_t msg); +MP_NORETURN void mp_raise_msg_varg(const mp_obj_type_t *exc_type, mp_rom_error_text_t fmt, ...); +MP_NORETURN void mp_raise_ValueError(mp_rom_error_text_t msg); +MP_NORETURN void mp_raise_TypeError(mp_rom_error_text_t msg); +MP_NORETURN void mp_raise_NotImplementedError(mp_rom_error_text_t msg); #endif // CIRCUITPY-CHANGE: new mp_raise routines -NORETURN void mp_raise_type_arg(const mp_obj_type_t *exc_type, mp_obj_t arg); -NORETURN void mp_raise_msg(const mp_obj_type_t *exc_type, mp_rom_error_text_t msg); -NORETURN void mp_raise_msg_varg(const mp_obj_type_t *exc_type, mp_rom_error_text_t fmt +MP_NORETURN void mp_raise_type_arg(const mp_obj_type_t *exc_type, mp_obj_t arg); +MP_NORETURN void mp_raise_msg(const mp_obj_type_t *exc_type, mp_rom_error_text_t msg); +MP_NORETURN void mp_raise_msg_varg(const mp_obj_type_t *exc_type, mp_rom_error_text_t fmt , ...); -NORETURN void mp_raise_msg_vlist(const mp_obj_type_t *exc_type, mp_rom_error_text_t fmt, va_list argptr); +MP_NORETURN void mp_raise_msg_vlist(const mp_obj_type_t *exc_type, mp_rom_error_text_t fmt, va_list argptr); // Only use this string version in native mpy files. Otherwise, use the compressed string version. -NORETURN void mp_raise_msg_str(const mp_obj_type_t *exc_type, const char *msg); - -NORETURN void mp_raise_AttributeError(mp_rom_error_text_t msg); -NORETURN void mp_raise_BrokenPipeError(void); -NORETURN void mp_raise_ConnectionError(mp_rom_error_text_t msg); -NORETURN void mp_raise_ImportError(mp_rom_error_text_t msg); -NORETURN void mp_raise_IndexError(mp_rom_error_text_t msg); -NORETURN void mp_raise_IndexError_varg(mp_rom_error_text_t msg, ...); -NORETURN void mp_raise_NotImplementedError(mp_rom_error_text_t msg); -NORETURN void mp_raise_NotImplementedError_varg(mp_rom_error_text_t fmt, ...); -NORETURN void mp_raise_OSError_errno_str(int errno_, mp_obj_t str); -NORETURN void mp_raise_OSError(int errno_); -NORETURN void mp_raise_OSError_msg(mp_rom_error_text_t msg); -NORETURN void mp_raise_OSError_msg_varg(mp_rom_error_text_t fmt, ...); -NORETURN void mp_raise_OSError_with_filename(int errno_, const char *filename); -NORETURN void mp_raise_OverflowError_varg(mp_rom_error_text_t fmt, ...); -NORETURN void mp_raise_recursion_depth(void); -NORETURN void mp_raise_RuntimeError(mp_rom_error_text_t msg); -NORETURN void mp_raise_RuntimeError_varg(mp_rom_error_text_t fmt, ...); -NORETURN void mp_raise_StopIteration(mp_obj_t arg); -NORETURN void mp_raise_TypeError(mp_rom_error_text_t msg); -NORETURN void mp_raise_TypeError_varg(mp_rom_error_text_t fmt, ...); -NORETURN void mp_raise_TypeError_int_conversion(mp_const_obj_t arg); -NORETURN void mp_raise_ValueError(mp_rom_error_text_t msg); -NORETURN void mp_raise_ValueError_varg(mp_rom_error_text_t fmt, ...); -NORETURN void mp_raise_ZeroDivisionError(void); +MP_NORETURN void mp_raise_msg_str(const mp_obj_type_t *exc_type, const char *msg); + +MP_NORETURN void mp_raise_AttributeError(mp_rom_error_text_t msg); +MP_NORETURN void mp_raise_BrokenPipeError(void); +MP_NORETURN void mp_raise_ConnectionError(mp_rom_error_text_t msg); +MP_NORETURN void mp_raise_ImportError(mp_rom_error_text_t msg); +MP_NORETURN void mp_raise_IndexError(mp_rom_error_text_t msg); +MP_NORETURN void mp_raise_IndexError_varg(mp_rom_error_text_t msg, ...); +MP_NORETURN void mp_raise_NotImplementedError(mp_rom_error_text_t msg); +MP_NORETURN void mp_raise_NotImplementedError_varg(mp_rom_error_text_t fmt, ...); +MP_NORETURN void mp_raise_OSError_errno_str(int errno_, mp_obj_t str); +MP_NORETURN void mp_raise_OSError(int errno_); +MP_NORETURN void mp_raise_OSError_msg(mp_rom_error_text_t msg); +MP_NORETURN void mp_raise_OSError_msg_varg(mp_rom_error_text_t fmt, ...); +MP_NORETURN void mp_raise_OSError_with_filename(int errno_, const char *filename); +MP_NORETURN void mp_raise_OverflowError_varg(mp_rom_error_text_t fmt, ...); +MP_NORETURN void mp_raise_recursion_depth(void); +MP_NORETURN void mp_raise_RuntimeError(mp_rom_error_text_t msg); +MP_NORETURN void mp_raise_RuntimeError_varg(mp_rom_error_text_t fmt, ...); +MP_NORETURN void mp_raise_StopIteration(mp_obj_t arg); +MP_NORETURN void mp_raise_TypeError(mp_rom_error_text_t msg); +MP_NORETURN void mp_raise_TypeError_varg(mp_rom_error_text_t fmt, ...); +MP_NORETURN void mp_raise_TypeError_int_conversion(mp_const_obj_t arg); +MP_NORETURN void mp_raise_ValueError(mp_rom_error_text_t msg); +MP_NORETURN void mp_raise_ValueError_varg(mp_rom_error_text_t fmt, ...); +MP_NORETURN void mp_raise_ZeroDivisionError(void); #if MICROPY_BUILTIN_METHOD_CHECK_SELF_ARG #undef mp_check_self diff --git a/py/runtime_utils.c b/py/runtime_utils.c index 98252c31220..33da558e30f 100644 --- a/py/runtime_utils.c +++ b/py/runtime_utils.c @@ -53,3 +53,59 @@ mp_obj_t mp_call_function_2_protected(mp_obj_t fun, mp_obj_t arg1, mp_obj_t arg2 return MP_OBJ_NULL; } } + +#if !MICROPY_USE_GCC_MUL_OVERFLOW_INTRINSIC +bool mp_mul_ll_overflow(long long int x, long long int y, long long int *res) { + bool overflow; + + // Check for multiply overflow; see CERT INT32-C + if (x > 0) { // x is positive + if (y > 0) { // x and y are positive + overflow = (x > (LLONG_MAX / y)); + } else { // x positive, y nonpositive + overflow = (y < (LLONG_MIN / x)); + } // x positive, y nonpositive + } else { // x is nonpositive + if (y > 0) { // x is nonpositive, y is positive + overflow = (x < (LLONG_MIN / y)); + } else { // x and y are nonpositive + overflow = (x != 0 && y < (LLONG_MAX / x)); + } // End if x and y are nonpositive + } // End if x is nonpositive + + if (!overflow) { + *res = x * y; + } + + return overflow; +} + +bool mp_mul_mp_int_t_overflow(mp_int_t x, mp_int_t y, mp_int_t *res) { + // Check for multiply overflow; see CERT INT32-C + if (x > 0) { // x is positive + if (y > 0) { // x and y are positive + if (x > (MP_INT_MAX / y)) { + return true; + } + } else { // x positive, y nonpositive + if (y < (MP_INT_MIN / x)) { + return true; + } + } // x positive, y nonpositive + } else { // x is nonpositive + if (y > 0) { // x is nonpositive, y is positive + if (x < (MP_INT_MIN / y)) { + return true; + } + } else { // x and y are nonpositive + if (x != 0 && y < (MP_INT_MAX / x)) { + return true; + } + } // End if x and y are nonpositive + } // End if x is nonpositive + + // Result doesn't overflow + *res = x * y; + return false; +} +#endif diff --git a/py/scheduler.c b/py/scheduler.c index 91ef7e63b38..e75927dbe0b 100644 --- a/py/scheduler.c +++ b/py/scheduler.c @@ -97,17 +97,21 @@ static inline void mp_sched_run_pending(void) { #if MICROPY_SCHEDULER_STATIC_NODES // Run all pending C callbacks. - while (MP_STATE_VM(sched_head) != NULL) { - mp_sched_node_t *node = MP_STATE_VM(sched_head); - MP_STATE_VM(sched_head) = node->next; - if (MP_STATE_VM(sched_head) == NULL) { - MP_STATE_VM(sched_tail) = NULL; - } - mp_sched_callback_t callback = node->callback; - node->callback = NULL; - MICROPY_END_ATOMIC_SECTION(atomic_state); - callback(node); - atomic_state = MICROPY_BEGIN_ATOMIC_SECTION(); + mp_sched_node_t *original_tail = MP_STATE_VM(sched_tail); + if (original_tail != NULL) { + mp_sched_node_t *node; + do { + node = MP_STATE_VM(sched_head); + MP_STATE_VM(sched_head) = node->next; + if (MP_STATE_VM(sched_head) == NULL) { + MP_STATE_VM(sched_tail) = NULL; + } + mp_sched_callback_t callback = node->callback; + node->callback = NULL; + MICROPY_END_ATOMIC_SECTION(atomic_state); + callback(node); + atomic_state = MICROPY_BEGIN_ATOMIC_SECTION(); + } while (node != original_tail); // Don't execute any callbacks scheduled during this run } #endif @@ -218,24 +222,27 @@ MP_REGISTER_ROOT_POINTER(mp_sched_item_t sched_queue[MICROPY_SCHEDULER_DEPTH]); // Called periodically from the VM or from "waiting" code (e.g. sleep) to // process background tasks and pending exceptions (e.g. KeyboardInterrupt). -void mp_handle_pending(bool raise_exc) { +void mp_handle_pending(mp_handle_pending_behaviour_t behavior) { + bool handle_exceptions = (behavior != MP_HANDLE_PENDING_CALLBACKS_ONLY); + bool raise_exceptions = (behavior == MP_HANDLE_PENDING_CALLBACKS_AND_EXCEPTIONS); + // Handle pending VM abort. #if MICROPY_ENABLE_VM_ABORT - if (MP_STATE_VM(vm_abort) && mp_thread_is_main_thread()) { + if (handle_exceptions && MP_STATE_VM(vm_abort) && mp_thread_is_main_thread()) { MP_STATE_VM(vm_abort) = false; - if (raise_exc && nlr_get_abort() != NULL) { + if (raise_exceptions && nlr_get_abort() != NULL) { nlr_jump_abort(); } } #endif // Handle any pending exception. - if (MP_STATE_THREAD(mp_pending_exception) != MP_OBJ_NULL) { + if (handle_exceptions && MP_STATE_THREAD(mp_pending_exception) != MP_OBJ_NULL) { mp_uint_t atomic_state = MICROPY_BEGIN_ATOMIC_SECTION(); mp_obj_t obj = MP_STATE_THREAD(mp_pending_exception); if (obj != MP_OBJ_NULL) { MP_STATE_THREAD(mp_pending_exception) = MP_OBJ_NULL; - if (raise_exc) { + if (raise_exceptions) { MICROPY_END_ATOMIC_SECTION(atomic_state); nlr_raise(obj); } @@ -245,7 +252,13 @@ void mp_handle_pending(bool raise_exc) { // Handle any pending callbacks. #if MICROPY_ENABLE_SCHEDULER - if (MP_STATE_VM(sched_state) == MP_SCHED_PENDING) { + bool run_scheduler = (MP_STATE_VM(sched_state) == MP_SCHED_PENDING); + #if MICROPY_PY_THREAD && !MICROPY_PY_THREAD_GIL + // Avoid races by running the scheduler on the main thread, only. + // (Not needed if GIL enabled, as GIL ensures thread safety here.) + run_scheduler = run_scheduler && mp_thread_is_main_thread(); + #endif + if (run_scheduler) { mp_sched_run_pending(); } #endif @@ -259,7 +272,7 @@ void mp_event_handle_nowait(void) { #else // Process any port layer (non-blocking) events. MICROPY_INTERNAL_EVENT_HOOK; - mp_handle_pending(true); + mp_handle_pending(MP_HANDLE_PENDING_CALLBACKS_AND_EXCEPTIONS); #endif } @@ -271,10 +284,6 @@ void mp_event_wait_indefinite(void) { MICROPY_EVENT_POLL_HOOK #else mp_event_handle_nowait(); - - // CIRCUITPY-CHANGE: don't starve CircuitPython background tasks - RUN_BACKGROUND_TASKS; - MICROPY_INTERNAL_WFE(-1); #endif } @@ -287,10 +296,6 @@ void mp_event_wait_ms(mp_uint_t timeout_ms) { MICROPY_EVENT_POLL_HOOK #else mp_event_handle_nowait(); - - // CIRCUITPY-CHANGE: don't starve CircuitPython background tasks - RUN_BACKGROUND_TASKS; - MICROPY_INTERNAL_WFE(timeout_ms); #endif } diff --git a/py/sequence.c b/py/sequence.c index cc89d1b0b05..6bbc62f0f7f 100644 --- a/py/sequence.c +++ b/py/sequence.c @@ -34,18 +34,13 @@ #define SWAP(type, var1, var2) { type t = var2; var2 = var1; var1 = t; } // CIRCUITPY-CHANGE: detect sequence overflow -#if __GNUC__ < 5 -// n.b. does not actually detect overflow! -#define __builtin_mul_overflow(a, b, x) (*(x) = (a) * (b), false) -#endif - // Detect when a multiply causes an overflow. size_t mp_seq_multiply_len(size_t item_sz, size_t len) { - size_t new_len; - if (__builtin_mul_overflow(item_sz, len, &new_len)) { + mp_int_t new_len; + if (mp_mul_mp_int_t_overflow(item_sz, len, &new_len)) { mp_raise_msg(&mp_type_OverflowError, MP_ERROR_TEXT("small int overflow")); } - return new_len; + return (size_t)new_len; } // Implements backend of sequence * integer operation. Assumes elements are @@ -78,11 +73,7 @@ bool mp_seq_get_fast_slice_indexes(mp_uint_t len, mp_obj_t slice, mp_bound_slice return indexes->step == 1; } -#endif - -mp_obj_t mp_seq_extract_slice(size_t len, const mp_obj_t *seq, mp_bound_slice_t *indexes) { - (void)len; // TODO can we remove len from the arg list? - +mp_obj_t mp_seq_extract_slice(const mp_obj_t *seq, mp_bound_slice_t *indexes) { mp_int_t start = indexes->start, stop = indexes->stop; mp_int_t step = indexes->step; @@ -102,6 +93,8 @@ mp_obj_t mp_seq_extract_slice(size_t len, const mp_obj_t *seq, mp_bound_slice_t return res; } +#endif + // Special-case comparison function for sequences of bytes // Don't pass MP_BINARY_OP_NOT_EQUAL here bool mp_seq_cmp_bytes(mp_uint_t op, const byte *data1, size_t len1, const byte *data2, size_t len2) { diff --git a/py/showbc.c b/py/showbc.c index 6913d18c1ca..68e2f33138c 100644 --- a/py/showbc.c +++ b/py/showbc.c @@ -99,8 +99,8 @@ void mp_bytecode_print(const mp_print_t *print, const mp_raw_code_t *rc, size_t #else qstr source_file = cm->source_file; #endif - mp_printf(print, "File %s, code block '%s' (descriptor: %p, bytecode @%p %u bytes)\n", - qstr_str(source_file), qstr_str(block_name), rc, ip_start, (unsigned)fun_data_len); + mp_printf(print, "File %q, code block '%q' (descriptor: %p, bytecode @%p %u bytes)\n", + source_file, block_name, rc, ip_start, (unsigned)fun_data_len); // raw bytecode dump size_t prelude_size = ip - ip_start + n_info + n_cell; @@ -121,7 +121,7 @@ void mp_bytecode_print(const mp_print_t *print, const mp_raw_code_t *rc, size_t #if MICROPY_EMIT_BYTECODE_USES_QSTR_TABLE qst = cm->qstr_table[qst]; #endif - mp_printf(print, " %s", qstr_str(qst)); + mp_printf(print, " %q", qst); } mp_printf(print, "\n"); @@ -144,17 +144,9 @@ void mp_bytecode_print(const mp_print_t *print, const mp_raw_code_t *rc, size_t mp_uint_t source_line = 1; mp_printf(print, " bc=" INT_FMT " line=" UINT_FMT "\n", bc, source_line); for (const byte *ci = code_info; ci < line_info_top;) { - if ((ci[0] & 0x80) == 0) { - // 0b0LLBBBBB encoding - bc += ci[0] & 0x1f; - source_line += ci[0] >> 5; - ci += 1; - } else { - // 0b1LLLBBBB 0bLLLLLLLL encoding (l's LSB in second byte) - bc += ci[0] & 0xf; - source_line += ((ci[0] << 4) & 0x700) | ci[1]; - ci += 2; - } + mp_code_lineinfo_t decoded = mp_bytecode_decode_lineinfo(&ci); + bc += decoded.bc_increment; + source_line += decoded.line_increment; mp_printf(print, " bc=" INT_FMT " line=" UINT_FMT "\n", bc, source_line); } } @@ -197,7 +189,7 @@ const byte *mp_bytecode_print_str(const mp_print_t *print, const byte *ip_start, case MP_BC_LOAD_CONST_STRING: DECODE_QSTR; - mp_printf(print, "LOAD_CONST_STRING '%s'", qstr_str(qst)); + mp_printf(print, "LOAD_CONST_STRING '%q'", qst); break; case MP_BC_LOAD_CONST_OBJ: @@ -222,27 +214,27 @@ const byte *mp_bytecode_print_str(const mp_print_t *print, const byte *ip_start, case MP_BC_LOAD_NAME: DECODE_QSTR; - mp_printf(print, "LOAD_NAME %s", qstr_str(qst)); + mp_printf(print, "LOAD_NAME %q", qst); break; case MP_BC_LOAD_GLOBAL: DECODE_QSTR; - mp_printf(print, "LOAD_GLOBAL %s", qstr_str(qst)); + mp_printf(print, "LOAD_GLOBAL %q", qst); break; case MP_BC_LOAD_ATTR: DECODE_QSTR; - mp_printf(print, "LOAD_ATTR %s", qstr_str(qst)); + mp_printf(print, "LOAD_ATTR %q", qst); break; case MP_BC_LOAD_METHOD: DECODE_QSTR; - mp_printf(print, "LOAD_METHOD %s", qstr_str(qst)); + mp_printf(print, "LOAD_METHOD %q", qst); break; case MP_BC_LOAD_SUPER_METHOD: DECODE_QSTR; - mp_printf(print, "LOAD_SUPER_METHOD %s", qstr_str(qst)); + mp_printf(print, "LOAD_SUPER_METHOD %q", qst); break; case MP_BC_LOAD_BUILD_CLASS: @@ -265,17 +257,17 @@ const byte *mp_bytecode_print_str(const mp_print_t *print, const byte *ip_start, case MP_BC_STORE_NAME: DECODE_QSTR; - mp_printf(print, "STORE_NAME %s", qstr_str(qst)); + mp_printf(print, "STORE_NAME %q", qst); break; case MP_BC_STORE_GLOBAL: DECODE_QSTR; - mp_printf(print, "STORE_GLOBAL %s", qstr_str(qst)); + mp_printf(print, "STORE_GLOBAL %q", qst); break; case MP_BC_STORE_ATTR: DECODE_QSTR; - mp_printf(print, "STORE_ATTR %s", qstr_str(qst)); + mp_printf(print, "STORE_ATTR %q", qst); break; case MP_BC_STORE_SUBSCR: @@ -294,12 +286,12 @@ const byte *mp_bytecode_print_str(const mp_print_t *print, const byte *ip_start, case MP_BC_DELETE_NAME: DECODE_QSTR; - mp_printf(print, "DELETE_NAME %s", qstr_str(qst)); + mp_printf(print, "DELETE_NAME %q", qst); break; case MP_BC_DELETE_GLOBAL: DECODE_QSTR; - mp_printf(print, "DELETE_GLOBAL %s", qstr_str(qst)); + mp_printf(print, "DELETE_GLOBAL %q", qst); break; case MP_BC_DUP_TOP: @@ -514,12 +506,12 @@ const byte *mp_bytecode_print_str(const mp_print_t *print, const byte *ip_start, case MP_BC_IMPORT_NAME: DECODE_QSTR; - mp_printf(print, "IMPORT_NAME '%s'", qstr_str(qst)); + mp_printf(print, "IMPORT_NAME '%q'", qst); break; case MP_BC_IMPORT_FROM: DECODE_QSTR; - mp_printf(print, "IMPORT_FROM '%s'", qstr_str(qst)); + mp_printf(print, "IMPORT_FROM '%q'", qst); break; case MP_BC_IMPORT_STAR: @@ -535,10 +527,10 @@ const byte *mp_bytecode_print_str(const mp_print_t *print, const byte *ip_start, mp_printf(print, "STORE_FAST " UINT_FMT, (mp_uint_t)ip[-1] - MP_BC_STORE_FAST_MULTI); } else if (ip[-1] < MP_BC_UNARY_OP_MULTI + MP_UNARY_OP_NUM_BYTECODE) { mp_uint_t op = ip[-1] - MP_BC_UNARY_OP_MULTI; - mp_printf(print, "UNARY_OP " UINT_FMT " %s", op, qstr_str(mp_unary_op_method_name[op])); + mp_printf(print, "UNARY_OP " UINT_FMT " %q", op, (qstr)mp_unary_op_method_name[op]); } else if (ip[-1] < MP_BC_BINARY_OP_MULTI + MP_BINARY_OP_NUM_BYTECODE) { mp_uint_t op = ip[-1] - MP_BC_BINARY_OP_MULTI; - mp_printf(print, "BINARY_OP " UINT_FMT " %s", op, qstr_str(mp_binary_op_method_name[op])); + mp_printf(print, "BINARY_OP " UINT_FMT " %q", op, (qstr)mp_binary_op_method_name[op]); } else { mp_printf(print, "code %p, byte code 0x%02x not implemented\n", ip - 1, ip[-1]); assert(0); diff --git a/py/smallint.c b/py/smallint.c index aa542ca7bf2..eb99b58667a 100644 --- a/py/smallint.c +++ b/py/smallint.c @@ -26,32 +26,6 @@ #include "py/smallint.h" -bool mp_small_int_mul_overflow(mp_int_t x, mp_int_t y) { - // Check for multiply overflow; see CERT INT32-C - if (x > 0) { // x is positive - if (y > 0) { // x and y are positive - if (x > (MP_SMALL_INT_MAX / y)) { - return true; - } - } else { // x positive, y nonpositive - if (y < (MP_SMALL_INT_MIN / x)) { - return true; - } - } // x positive, y nonpositive - } else { // x is nonpositive - if (y > 0) { // x is nonpositive, y is positive - if (x < (MP_SMALL_INT_MIN / y)) { - return true; - } - } else { // x and y are nonpositive - if (x != 0 && y < (MP_SMALL_INT_MAX / x)) { - return true; - } - } // End if x and y are nonpositive - } // End if x is nonpositive - return false; -} - mp_int_t mp_small_int_modulo(mp_int_t dividend, mp_int_t divisor) { // Python specs require that mod has same sign as second operand dividend %= divisor; diff --git a/py/smallint.h b/py/smallint.h index 584e0018d1b..ec5b0af3b28 100644 --- a/py/smallint.h +++ b/py/smallint.h @@ -68,7 +68,6 @@ // The number of bits in a MP_SMALL_INT including the sign bit. #define MP_SMALL_INT_BITS (MP_IMAX_BITS(MP_SMALL_INT_MAX) + 1) -bool mp_small_int_mul_overflow(mp_int_t x, mp_int_t y); mp_int_t mp_small_int_modulo(mp_int_t dividend, mp_int_t divisor); mp_int_t mp_small_int_floor_divide(mp_int_t num, mp_int_t denom); diff --git a/py/stackctrl.c b/py/stackctrl.c index f192fad0534..0372a1db350 100644 --- a/py/stackctrl.c +++ b/py/stackctrl.c @@ -24,7 +24,12 @@ * THE SOFTWARE. */ +// This API is deprecated, please use py/cstack.h instead + #include "py/runtime.h" + +#if !MICROPY_PREVIEW_VERSION_2 + #include "py/stackctrl.h" void mp_stack_ctrl_init(void) { @@ -68,3 +73,5 @@ void PLACE_IN_ITCM(mp_stack_check)(void) { } #endif // MICROPY_STACK_CHECK + +#endif // !MICROPY_PREVIEW_VERSION_2 diff --git a/py/stackctrl.h b/py/stackctrl.h index 63667f8a551..5ff24798103 100644 --- a/py/stackctrl.h +++ b/py/stackctrl.h @@ -26,8 +26,12 @@ #ifndef MICROPY_INCLUDED_PY_STACKCTRL_H #define MICROPY_INCLUDED_PY_STACKCTRL_H +// This API is deprecated, please use py/cstack.h instead + #include "py/mpconfig.h" +#if !MICROPY_PREVIEW_VERSION_2 + void mp_stack_ctrl_init(void); void mp_stack_set_top(void *top); mp_uint_t mp_stack_usage(void); @@ -43,7 +47,9 @@ void mp_stack_check(void); #define mp_stack_set_limit(limit) (void)(limit) #define MP_STACK_CHECK() -#endif +#endif // MICROPY_STACK_CHECK + +#endif // !MICROPY_PREVIEW_VERSION_2 // CIRCUITPY-CHANGE: provide max stack usage #if MICROPY_MAX_STACK_USAGE diff --git a/py/stream.c b/py/stream.c index fbf7fd878a1..d3b0a0d80e2 100644 --- a/py/stream.c +++ b/py/stream.c @@ -107,6 +107,17 @@ const mp_stream_p_t *mp_get_stream_raise(mp_obj_t self_in, int flags) { mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("stream operation not supported")); } +static MP_NORETURN void mp_stream_raise_error(mp_obj_t stream, int error) { + #if MICROPY_STREAMS_DELEGATE_ERROR + const mp_stream_p_t *stream_p = mp_get_stream(stream); + if (stream_p->ioctl != NULL) { + int err; + stream_p->ioctl(stream, MP_STREAM_RAISE_ERROR, error, &err); + } + #endif + mp_raise_OSError(error); +} + 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, @@ -150,7 +161,7 @@ static mp_obj_t stream_read_generic(size_t n_args, const mp_obj_t *args, byte fl } break; } - mp_raise_OSError(error); + mp_stream_raise_error(args[0], error); } if (out_sz < more_bytes) { @@ -218,7 +229,7 @@ static mp_obj_t stream_read_generic(size_t n_args, const mp_obj_t *args, byte fl // this as EOF. return mp_const_none; } - mp_raise_OSError(error); + mp_stream_raise_error(args[0], error); } else { vstr.len = out_sz; if (stream_p->is_text) { @@ -249,7 +260,7 @@ mp_obj_t mp_stream_write(mp_obj_t self_in, const void *buf, size_t len, byte fla // no single byte could be readily written to it." return mp_const_none; } - mp_raise_OSError(error); + mp_stream_raise_error(self_in, error); } else { return MP_OBJ_NEW_SMALL_INT(out_sz); } @@ -260,9 +271,14 @@ void mp_stream_write_adaptor(void *self, const char *buf, size_t len) { mp_stream_write(MP_OBJ_FROM_PTR(self), buf, len, MP_STREAM_RW_WRITE); } -static mp_obj_t stream_write_method(size_t n_args, const mp_obj_t *args) { +static mp_obj_t stream_readinto_write_generic(size_t n_args, const mp_obj_t *args, byte flags) { mp_buffer_info_t bufinfo; - mp_get_buffer_raise(args[1], &bufinfo, MP_BUFFER_READ); + mp_get_buffer_raise(args[1], &bufinfo, (flags & MP_STREAM_RW_WRITE) ? MP_BUFFER_READ : MP_BUFFER_WRITE); + + // CPython extension, allow optional maximum length and offset: + // - stream.operation(buf, max_len) + // - stream.operation(buf, off, max_len) + // Similar to https://docs.python.org/3/library/socket.html#socket.socket.recv_into size_t max_len = (size_t)-1; size_t off = 0; if (n_args == 3) { @@ -275,45 +291,31 @@ 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); + + // Perform the readinto or write operation. + return mp_stream_write(args[0], (byte *)bufinfo.buf + off, MIN(bufinfo.len, max_len), flags); +} + +static mp_obj_t stream_write_method(size_t n_args, const mp_obj_t *args) { + return stream_readinto_write_generic(n_args, args, MP_STREAM_RW_WRITE); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_write_obj, 2, 4, stream_write_method); -static mp_obj_t stream_write1_method(mp_obj_t self_in, mp_obj_t arg) { - mp_buffer_info_t bufinfo; - mp_get_buffer_raise(arg, &bufinfo, MP_BUFFER_READ); - return mp_stream_write(self_in, bufinfo.buf, bufinfo.len, MP_STREAM_RW_WRITE | MP_STREAM_RW_ONCE); +static mp_obj_t stream_write1_method(size_t n_args, const mp_obj_t *args) { + return stream_readinto_write_generic(n_args, args, MP_STREAM_RW_WRITE | MP_STREAM_RW_ONCE); } -MP_DEFINE_CONST_FUN_OBJ_2(mp_stream_write1_obj, stream_write1_method); +MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_write1_obj, 2, 4, stream_write1_method); static mp_obj_t stream_readinto(size_t n_args, const mp_obj_t *args) { - mp_buffer_info_t bufinfo; - mp_get_buffer_raise(args[1], &bufinfo, MP_BUFFER_WRITE); - - // CPython extension: if 2nd arg is provided, that's max len to read, - // instead of full buffer. Similar to - // https://docs.python.org/3/library/socket.html#socket.socket.recv_into - mp_uint_t len = bufinfo.len; - if (n_args > 2) { - len = mp_obj_get_int(args[2]); - if (len > bufinfo.len) { - len = bufinfo.len; - } - } - - int error; - 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; - } - mp_raise_OSError(error); - } else { - return MP_OBJ_NEW_SMALL_INT(out_sz); - } + return stream_readinto_write_generic(n_args, args, MP_STREAM_RW_READ); } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_readinto_obj, 2, 3, stream_readinto); +static mp_obj_t stream_readinto1(size_t n_args, const mp_obj_t *args) { + return stream_readinto_write_generic(n_args, args, MP_STREAM_RW_READ | MP_STREAM_RW_ONCE); +} +MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_readinto1_obj, 2, 3, stream_readinto1); + static mp_obj_t stream_readall(mp_obj_t self_in) { const mp_stream_p_t *stream_p = mp_get_stream(self_in); @@ -335,7 +337,7 @@ static mp_obj_t stream_readall(mp_obj_t self_in) { } break; } - mp_raise_OSError(error); + mp_stream_raise_error(self_in, error); } if (out_sz == 0) { break; @@ -393,7 +395,7 @@ static mp_obj_t stream_unbuffered_readline(size_t n_args, const mp_obj_t *args) goto done; } } - mp_raise_OSError(error); + mp_stream_raise_error(args[0], error); } if (out_sz == 0) { done: @@ -443,7 +445,7 @@ mp_obj_t mp_stream_close(mp_obj_t stream) { int error; mp_uint_t res = stream_p->ioctl(stream, MP_STREAM_CLOSE, 0, &error); if (res == MP_STREAM_ERROR) { - mp_raise_OSError(error); + mp_stream_raise_error(stream, error); } return mp_const_none; } @@ -458,20 +460,20 @@ MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream___exit___obj, 4, 4, mp_stream___ex static mp_obj_t stream_seek(size_t n_args, const mp_obj_t *args) { // TODO: Could be uint64 mp_off_t offset = mp_obj_get_int(args[1]); - int whence = SEEK_SET; + int whence = MP_SEEK_SET; if (n_args == 3) { whence = mp_obj_get_int(args[2]); } // In POSIX, it's error to seek before end of stream, we enforce it here. - if (whence == SEEK_SET && offset < 0) { + if (whence == MP_SEEK_SET && offset < 0) { mp_raise_OSError(MP_EINVAL); } int error; mp_off_t res = mp_stream_seek(args[0], offset, whence, &error); if (res == (mp_off_t)-1) { - mp_raise_OSError(error); + mp_stream_raise_error(args[0], error); } // TODO: Could be uint64 @@ -481,7 +483,7 @@ MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_seek_obj, 2, 3, stream_seek); static mp_obj_t stream_tell(mp_obj_t self) { mp_obj_t offset = MP_OBJ_NEW_SMALL_INT(0); - mp_obj_t whence = MP_OBJ_NEW_SMALL_INT(SEEK_CUR); + mp_obj_t whence = MP_OBJ_NEW_SMALL_INT(MP_SEEK_CUR); const mp_obj_t args[3] = {self, offset, whence}; return stream_seek(3, args); } @@ -493,7 +495,7 @@ mp_obj_t mp_stream_flush(mp_obj_t self) { int error; mp_uint_t res = stream_p->ioctl(self, MP_STREAM_FLUSH, 0, &error); if (res == MP_STREAM_ERROR) { - mp_raise_OSError(error); + mp_stream_raise_error(self, error); } return mp_const_none; } @@ -514,7 +516,7 @@ static mp_obj_t stream_ioctl(size_t n_args, const mp_obj_t *args) { int error; mp_uint_t res = stream_p->ioctl(args[0], mp_obj_get_int(args[1]), val, &error); if (res == MP_STREAM_ERROR) { - mp_raise_OSError(error); + mp_stream_raise_error(args[0], error); } return mp_obj_new_int(res); diff --git a/py/stream.h b/py/stream.h index 5e1cd5d4413..153800c3808 100644 --- a/py/stream.h +++ b/py/stream.h @@ -27,6 +27,7 @@ #ifndef MICROPY_INCLUDED_PY_STREAM_H #define MICROPY_INCLUDED_PY_STREAM_H +#include "py/mpconfig.h" #include "py/obj.h" // CIRCUITPY-CHANGE #include "py/proto.h" @@ -35,17 +36,20 @@ #define MP_STREAM_ERROR ((mp_uint_t)-1) // Stream ioctl request codes -#define MP_STREAM_FLUSH (1) -#define MP_STREAM_SEEK (2) -#define MP_STREAM_POLL (3) -#define MP_STREAM_CLOSE (4) -#define MP_STREAM_TIMEOUT (5) // Get/set timeout (single op) -#define MP_STREAM_GET_OPTS (6) // Get stream options -#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 -#define MP_STREAM_GET_BUFFER_SIZE (11) // Get preferred buffer size for file +#define MP_STREAM_FLUSH (1) +#define MP_STREAM_SEEK (2) +#define MP_STREAM_POLL (3) +#define MP_STREAM_CLOSE (4) +#define MP_STREAM_TIMEOUT (5) // Get/set timeout (single op) +#define MP_STREAM_GET_OPTS (6) // Get stream options +#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 +#define MP_STREAM_GET_BUFFER_SIZE (11) // Get preferred buffer size for file +#if MICROPY_STREAMS_DELEGATE_ERROR +#define MP_STREAM_RAISE_ERROR (12) // Raise an error with detailed error string +#endif // These poll ioctl values are compatible with Linux #define MP_STREAM_POLL_RD (0x0001) @@ -72,8 +76,12 @@ struct mp_stream_seek_t { typedef struct _mp_stream_p_t { // CIRCUITPY-CHANGE MP_PROTOCOL_HEAD - // On error, functions should return MP_STREAM_ERROR and fill in *errcode (values - // are implementation-dependent, but will be exposed to user, e.g. via exception). + // On error, functions should return MP_STREAM_ERROR and fill in *errcode + // (values are are implementation-dependent, but will be exposed to user). + // If MICROPY_STREAMS_DELEGATE_ERROR is enabled and ioctl is not null the + // stream will receive a MP_STREAM_RAISE_ERROR ioctl request with the arg + // containing the errcode, so it may raise a more detailed error. If that + // ioctl returns without raising, an OSError with the errcode will raised. mp_uint_t (*read)(mp_obj_t obj, void *buf, mp_uint_t size, int *errcode); 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); @@ -87,10 +95,11 @@ typedef struct _mp_stream_p_t { MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_read_obj); MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_read1_obj); MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_readinto_obj); +MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_readinto1_obj); MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_unbuffered_readline_obj); MP_DECLARE_CONST_FUN_OBJ_1(mp_stream_unbuffered_readlines_obj); MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_write_obj); -MP_DECLARE_CONST_FUN_OBJ_2(mp_stream_write1_obj); +MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_write1_obj); MP_DECLARE_CONST_FUN_OBJ_1(mp_stream_close_obj); MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream___exit___obj); MP_DECLARE_CONST_FUN_OBJ_VAR_BETWEEN(mp_stream_seek_obj); diff --git a/py/unicode.c b/py/unicode.c index 81a37880f3c..4f6a273fe74 100644 --- a/py/unicode.c +++ b/py/unicode.c @@ -180,7 +180,7 @@ mp_uint_t unichar_xdigit_value(unichar c) { #if MICROPY_PY_BUILTINS_STR_UNICODE -bool utf8_check(const byte *p, size_t len) { +bool unicode_encoding_check(mp_encoding_t encoding, const byte *p, size_t len) { uint8_t need = 0; const byte *end = p + len; for (; p < end; p++) { @@ -193,7 +193,7 @@ bool utf8_check(const byte *p, size_t len) { return 0; } } else { - if (c >= 0xc0) { + if (encoding == MP_ENCODING_UTF8 && c >= 0xc0) { if (c >= 0xf8) { // mismatch return 0; diff --git a/py/unicode.h b/py/unicode.h index c1fb517894f..7b82c466e51 100644 --- a/py/unicode.h +++ b/py/unicode.h @@ -29,7 +29,14 @@ #include "py/mpconfig.h" #include "py/misc.h" +typedef enum { + MP_ENCODING_UTF8, + MP_ENCODING_ASCII, +} mp_encoding_t; + mp_uint_t utf8_ptr_to_index(const byte *s, const byte *ptr); -bool utf8_check(const byte *p, size_t len); + +// Returns true if bytes in buffer 'p' are valid according to encoding. +bool unicode_encoding_check(mp_encoding_t encoding, const byte *p, size_t len); #endif // MICROPY_INCLUDED_PY_UNICODE_H diff --git a/py/usermod.cmake b/py/usermod.cmake index 85327628374..648f315b9d5 100644 --- a/py/usermod.cmake +++ b/py/usermod.cmake @@ -5,6 +5,10 @@ function(usermod_gather_sources SOURCES_VARNAME INCLUDE_DIRECTORIES_VARNAME INCL if (NOT ${LIB} IN_LIST ${INCLUDED_VARNAME}) list(APPEND ${INCLUDED_VARNAME} ${LIB}) + if (NOT TARGET ${LIB}) + return() + endif() + # Gather library sources get_target_property(lib_sources ${LIB} INTERFACE_SOURCES) if (lib_sources) @@ -35,9 +39,26 @@ function(usermod_gather_sources SOURCES_VARNAME INCLUDE_DIRECTORIES_VARNAME INCL endif() endfunction() +# Extract c_module() entries from MICROPY_FROZEN_MANIFEST and merge them into +# USER_C_MODULES, so the loop below picks them up alongside USER_C_MODULES paths +# passed on the cmake command line. The port is responsible for resolving +# MICROPY_FROZEN_MANIFEST (including any board-config defaults) before +# including this file. +include(${MICROPY_DIR}/py/manifest.cmake) + # Include CMake files for user modules. if (USER_C_MODULES) foreach(USER_C_MODULE_PATH ${USER_C_MODULES}) + # If a directory is given, append the micropython.cmake to it. + if (IS_DIRECTORY ${USER_C_MODULE_PATH}) + set(USER_C_MODULE_PATH "${USER_C_MODULE_PATH}/micropython.cmake") + endif() + # Confirm the provided path exists, show abspath if not to make it clearer to fix. + if (NOT EXISTS ${USER_C_MODULE_PATH}) + get_filename_component(USER_C_MODULES_ABS "${USER_C_MODULE_PATH}" ABSOLUTE) + message(FATAL_ERROR "USER_C_MODULES doesn't exist: ${USER_C_MODULES_ABS}") + endif() + message("Including User C Module(s) from ${USER_C_MODULE_PATH}") include(${USER_C_MODULE_PATH}) endforeach() diff --git a/py/verbose.mk b/py/verbose.mk new file mode 100644 index 00000000000..734623a21e8 --- /dev/null +++ b/py/verbose.mk @@ -0,0 +1,16 @@ +# Turn on increased build verbosity by defining BUILD_VERBOSE in your main +# Makefile or in your environment. You can also use V=1 on the make command +# line. + +ifeq ("$(origin V)", "command line") +BUILD_VERBOSE=$(V) +endif +ifndef BUILD_VERBOSE +$(info Use make V=1 or set BUILD_VERBOSE in your environment to increase build verbosity.) +BUILD_VERBOSE = 0 +endif +ifeq ($(BUILD_VERBOSE),0) +Q = @ +else +Q = +endif diff --git a/py/version.py b/py/version.py index 04852af2d1f..7ef2a587628 100755 --- a/py/version.py +++ b/py/version.py @@ -9,19 +9,25 @@ def get_version_info_from_git(repo_path, extra_args=[]): # Note: git describe doesn't work if no tag is available try: git_tag = subprocess.check_output( - # CIRCUITPY-CHANGE + # CIRCUITPY-CHANGE: Ignore MicroPython tags that start with v. + # Also ignore tags that are on merged in branches. [ "git", "describe", "--dirty", "--tags", "--always", + "--first-parent", "--match", - "[1-9].*", + "[!v]*", # This is a glob, not a regex *extra_args, ], cwd=repo_path, - stderr=subprocess.STDOUT, + # CIRCUITPY-CHANGE: Keep stderr out of the tag: e.g. with + # core.fsmonitor=true the daemon can emit a transient IPC + # error to stderr while the command still succeeds, and it + # must not end up inside MICROPY_GIT_TAG. + stderr=subprocess.DEVNULL, universal_newlines=True, ).strip() # CIRCUITPY-CHANGE @@ -37,7 +43,8 @@ def get_version_info_from_git(repo_path, extra_args=[]): git_hash = subprocess.check_output( ["git", "rev-parse", "--short", "HEAD"], cwd=repo_path, - stderr=subprocess.STDOUT, + # CIRCUITPY-CHANGE: same as above; stderr must not become the hash. + stderr=subprocess.DEVNULL, universal_newlines=True, ).strip() except subprocess.CalledProcessError: diff --git a/py/vm.c b/py/vm.c index 6fd17782619..fcb6d9f184e 100644 --- a/py/vm.c +++ b/py/vm.c @@ -205,6 +205,22 @@ static mp_obj_t get_active_exception(mp_exc_stack_t *exc_sp, mp_exc_stack_t *exc return MP_OBJ_NULL; } +#if MICROPY_PY_BUILTINS_SLICE +// This function is marked "no inline" so it doesn't increase the C stack usage of the main VM function. +MP_NOINLINE static mp_obj_t *build_slice_stack_allocated(byte op, mp_obj_t *sp, mp_obj_t step) { + mp_obj_t stop = sp[2]; + mp_obj_t start = sp[1]; + mp_obj_slice_t slice = { .base = { .type = &mp_type_slice }, .start = start, .stop = stop, .step = step }; + if (op == MP_BC_LOAD_SUBSCR) { + SET_TOP(mp_obj_subscr(TOP(), MP_OBJ_FROM_PTR(&slice), MP_OBJ_SENTINEL)); + } else { // MP_BC_STORE_SUBSCR + mp_obj_subscr(TOP(), MP_OBJ_FROM_PTR(&slice), sp[-1]); + sp -= 2; + } + return sp; +} +#endif + // fastn has items in reverse order (fastn[0] is local[0], fastn[-1] is local[1], etc) // sp points to bottom of stack which grows up // returns: @@ -871,9 +887,20 @@ unwind_jump:; // 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)); + if ((*ip == MP_BC_LOAD_SUBSCR || *ip == MP_BC_STORE_SUBSCR) + && (mp_obj_get_type(sp[-2])->flags & MP_TYPE_FLAG_SUBSCR_ALLOWS_STACK_SLICE)) { + // Fast path optimisation for when the BUILD_SLICE is immediately followed + // by a LOAD/STORE_SUBSCR for an accepting type, to avoid needing to allocate + // the slice on the heap. In some cases (e.g. a[1:3] = x) this can result + // in no allocations at all. We can't do this for instance types because + // the get/set/delattr implementation may keep a reference to the slice. + byte op = *ip++; + sp = build_slice_stack_allocated(op, sp - 2, step); + } else { + mp_obj_t stop = POP(); + mp_obj_t start = TOP(); + SET_TOP(mp_obj_new_slice(start, stop, step)); + } DISPATCH(); } #endif @@ -1353,7 +1380,7 @@ unwind_jump:; MICROPY_VM_HOOK_LOOP // Check for pending exceptions or scheduled tasks to run. - // Note: it's safe to just call mp_handle_pending(true), but + // Note: it's safe to just call mp_handle_pending(...), but // we can inline the check for the common case where there is // neither. if ( @@ -1375,7 +1402,7 @@ unwind_jump:; #endif ) { MARK_EXC_IP_SELECTIVE(); - mp_handle_pending(true); + mp_handle_pending(MP_HANDLE_PENDING_CALLBACKS_AND_EXCEPTIONS); } #if MICROPY_PY_THREAD_GIL diff --git a/py/vstr.c b/py/vstr.c index 00972edf897..3d66d535ac2 100644 --- a/py/vstr.c +++ b/py/vstr.c @@ -44,14 +44,15 @@ void vstr_init(vstr_t *vstr, size_t alloc) { } vstr->alloc = alloc; vstr->len = 0; - vstr->buf = m_new(char, vstr->alloc); + // CIRCUITPY-CHANGE: Don't scan string data for pointers. + vstr->buf = m_malloc_without_collect(sizeof(char) * vstr->alloc); vstr->fixed_buf = false; } // 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) { - // CIRCUITPY-CHANGE + // CIRCUITPY-CHANGE: check for invalid length if (len == SIZE_MAX) { m_malloc_fail(len); } @@ -187,33 +188,21 @@ void vstr_add_strn(vstr_t *vstr, const char *str, size_t len) { vstr->len += len; } -static char *vstr_ins_blank_bytes(vstr_t *vstr, size_t byte_pos, size_t byte_len) { +char *vstr_ins_blank_bytes(vstr_t *vstr, size_t byte_pos, size_t byte_len) { size_t l = vstr->len; if (byte_pos > l) { byte_pos = l; } - if (byte_len > 0) { - // ensure room for the new bytes - vstr_ensure_extra(vstr, byte_len); - // copy up the string to make room for the new bytes - memmove(vstr->buf + byte_pos + byte_len, vstr->buf + byte_pos, l - byte_pos); - // increase the length - vstr->len += byte_len; - } + // ensure room for the new bytes + vstr_ensure_extra(vstr, byte_len); + // copy up the string to make room for the new bytes + memmove(vstr->buf + byte_pos + byte_len, vstr->buf + byte_pos, l - byte_pos); + // increase the length + vstr->len += byte_len; + // return a pointer to the location to insert new bytes at return vstr->buf + byte_pos; } -void vstr_ins_byte(vstr_t *vstr, size_t byte_pos, byte b) { - char *s = vstr_ins_blank_bytes(vstr, byte_pos, 1); - *s = b; -} - -void vstr_ins_char(vstr_t *vstr, size_t char_pos, unichar chr) { - // TODO UNICODE - char *s = vstr_ins_blank_bytes(vstr, char_pos, 1); - *s = chr; -} - void vstr_cut_head_bytes(vstr_t *vstr, size_t bytes_to_cut) { vstr_cut_out_bytes(vstr, 0, bytes_to_cut); } diff --git a/pyproject.toml b/pyproject.toml index 0db7eb70a78..fcb6270b2dc 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,35 +1,26 @@ -# SPDX-FileCopyrightText: 2024 Scott Shawcroft for Adafruit Industries -# -# SPDX-License-Identifier: MIT - -[tool.setuptools_scm] # can be empty if no extra settings are needed, presence enables setuptools-scm - -# Ruff settings copied from MicroPython - [tool.ruff] -target-version = "py37" - +target-version = "py312" line-length = 99 -# Exclude third-party code from linting and formatting. Ruff doesn't know how to ignore submodules. -# Exclude the following tests: -# repl_: not real python files -# viper_args: uses f(*) +builtins = [ "const", "execfile", "micropython", "ptr", "ptr8", "ptr16", "ptr32", "uint" ] +# Include Python source files that don't end with .py +extend-include = [ "tools/cc1" ] +# Exclude third-party code from linting and formatting extend-exclude = [ + # CIRCUITPY-CHANGES "extmod/ulab", "frozen", "lib", "ports/analog/msdk", "ports/atmel-samd/asf4", - "ports/broadcom/peripherals", + "ports/espress/tools", "ports/espressif/esp-idf", "ports/espressif/esp-protocols", "ports/raspberrypi/sdk", "ports/silabs/gecko_sdk", "ports/silabs/tools/slc_cli_linux", "ports/stm/st_driver", - "tests/*/repl_*.py", - "tests/micropython/viper_args.py", + "tests/cpydiff/syntax_assign_expr.py", # intentionally incorrect CPython code "tools/adabot", "tools/bitmap_font", "tools/cc1", @@ -40,8 +31,19 @@ extend-exclude = [ ] # Exclude third-party code, and exclude the following tests: # basics: needs careful attention before applying automatic formatting -format.exclude = [ "tests/basics/*.py" ] -lint.extend-select = [ "C9", "PLC" ] +# repl_: not real python files +# tstring: ruff does not support template strings +# viper_args: uses f(*) +format.exclude = [ + "tests/*/repl_*.py", + "tests/basics/*.py", + "tests/cmdline/cmd_compile_only_error.py", + "tests/feature_check/tstring.py", + "tests/micropython/heapalloc_fail_tstring.py", + "tests/micropython/test_normalize_newlines.py", + "tests/micropython/viper_args.py", +] +lint.extend-select = [ "C9", "PLC", "W292" ] lint.ignore = [ "E401", "E402", @@ -51,11 +53,54 @@ lint.ignore = [ "F401", "F403", "F405", - "PLC1901", + "PLC0206", + "PLC0415", # conditional imports are common in MicroPython +] +lint.exclude = [ + # Ruff finds Python SyntaxError in these files + "tests/basics/string_module_tstring.py", + "tests/basics/string_tstring_basic.py", + "tests/basics/string_tstring_basic1.py", + "tests/basics/string_tstring_constructor.py", + "tests/basics/string_tstring_errors1.py", + "tests/basics/string_tstring_format1.py", + "tests/basics/string_tstring_interpolation1.py", + "tests/basics/string_tstring_operations.py", + "tests/basics/string_tstring_parser1.py", + "tests/cmdline/cmd_compile_only_error.py", + "tests/cmdline/repl_autocomplete.py", + "tests/cmdline/repl_autocomplete_underscore.py", + "tests/cmdline/repl_autoindent.py", + "tests/cmdline/repl_basic.py", + "tests/cmdline/repl_cont.py", + "tests/cmdline/repl_ctrl_c_interrupt_execution.py", + "tests/cmdline/repl_emacs_keys.py", + "tests/cmdline/repl_paste.py", + "tests/cmdline/repl_words_move.py", + "tests/feature_check/repl_emacs_check.py", + "tests/feature_check/repl_words_move_check.py", + "tests/feature_check/tstring.py", + "tests/micropython/heapalloc_fail_tstring.py", + "tests/micropython/viper_args.py", ] # manifest.py files are evaluated with some global names pre-defined lint.per-file-ignores."**/manifest.py" = [ "F821" ] lint.per-file-ignores."ports/**/boards/**/manifest_*.py" = [ "F821" ] -# Exclude all tests from linting (does not apply to formatting). +lint.per-file-ignores."ports/cc3200/tools/uniflash.py" = [ "E711" ] +# Exclude all tests from linting. lint.per-file-ignores."tests/**/*.py" = [ "ALL" ] +# Uses assignment expressions. +lint.per-file-ignores."tests/cpydiff/syntax_assign_expr.py" = [ "F821" ] lint.mccabe.max-complexity = 40 + +[tool.codespell] +count = "" +ignore-regex = "\\b[A-Z]{3}\\b" +# CIRCUITPY-CHANGE: aranges +ignore-words-list = "ans,aranges,asend,deques,dout,emac,extint,hsi,iput,mis,notin,numer,ser,shft,synopsys,technic,ure,curren" +quiet-level = 3 +skip = """\ + */build*,./.git,./drivers/cc3100,./lib,./ports/cc3200/FreeRTOS,./ports/cc3200/bootmgr/sl,./ports/cc3200/hal,./ports/c\ + c3200/simplelink,./ports/cc3200/telnet,./ports/esp32/managed_components,./ports/nrf/drivers/bluetooth/s1*,./ports/pso\ + c-edge/boards/*/bsp-cfg,./ports/stm32/usbhost,./tests,ACKNOWLEDGEMENTS,\ + """ diff --git a/requirements-dev.txt b/requirements-dev.txt index 261a5cc2c7f..db61d51ea90 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -3,8 +3,11 @@ cascadetoml jinja2 typer +# for generating mbedtls's PSA driver wrappers (jinja2, above, is also required) +jsonschema + sh -click +click<8.2.0 cpp-coveralls requests @@ -24,6 +27,7 @@ intelhex # for building & testing natmods pyelftools +ar cryptography @@ -40,3 +44,10 @@ setuptools # For zephyr port tomlkit +pytest +pytest-rerunfailures +pytest-xdist +perfetto + +# For littlefs flash image tests on the zephyr port native_simulators +littlefs-python diff --git a/shared-bindings/_airlift/__init__.c b/shared-bindings/_airlift/__init__.c new file mode 100644 index 00000000000..ebeae8b615e --- /dev/null +++ b/shared-bindings/_airlift/__init__.c @@ -0,0 +1,166 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "py/obj.h" +#include "py/runtime.h" + +#include "shared-bindings/_airlift/__init__.h" + +//| """Shared access to an ESP32 co-processor running nina-fw +//| +//| The `_airlift` module lets libraries send commands to the ESP32 that the core +//| also uses, so that user code and the core can use the same co-processor. +//| It is meant for libraries such as ESP32SPI, not for user code. +//| """ +//| +//| MAX_SOCKETS: int +//| """The number of sockets in nina-fw. Commands naming a higher socket are rejected.""" +//| +//| MAX_TRANSFER: int +//| """The longest command, in bytes, that the ESP32 receives intact.""" +//| +//| MAX_READ: int +//| """The largest ``GET_DATABUF_TCP`` read the ESP32 can reply to.""" +//| + +//| def init() -> None: +//| """Claim the ESP32's pins and the board SPI bus, and hard-reset the ESP32. +//| The ESP32 stays claimed across soft reloads. Does nothing if it is already +//| claimed. Raises `ValueError` if a pin is in use. +//| +//| Temporary: the core will claim the ESP32 itself when web workflow is configured.""" +//| ... +//| +static mp_obj_t _airlift_init(void) { + common_hal__airlift_init(); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_0(_airlift_init_obj, _airlift_init); + +//| def active() -> bool: +//| """True if the core has claimed the ESP32 and `transact` can be used.""" +//| ... +//| +static mp_obj_t _airlift_active(void) { + return mp_obj_new_bool(common_hal__airlift_active()); +} +static MP_DEFINE_CONST_FUN_OBJ_0(_airlift_active_obj, _airlift_active); + +//| def reset() -> None: +//| """Hard-reset the ESP32 through its reset pin. This closes every socket and +//| disconnects from WiFi. Takes about 0.75 seconds.""" +//| ... +//| +static mp_obj_t _airlift_reset(void) { + common_hal__airlift_reset(); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_0(_airlift_reset_obj, _airlift_reset); + +//| def release() -> None: +//| """Give up the ESP32's pins, so that code can drive them directly. Does +//| nothing if they aren't claimed.""" +//| ... +//| +static mp_obj_t _airlift_release(void) { + common_hal__airlift_release(); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_0(_airlift_release_obj, _airlift_release); + +//| def transact( +//| cmd: int, +//| params: Optional[Sequence[Union[ReadableBuffer, Sequence[int]]]] = None, +//| *, +//| reply_params: Optional[int] = 1, +//| sent_param_len_16: bool = False, +//| recv_param_len_16: bool = False, +//| ) -> List[bytearray]: +//| """Send one command and return its reply parameters. This has the same +//| contract as ESP32SPI's ``ESP_SPIcontrol._send_command_get_response()``, +//| and raises the same exceptions. +//| +//| :param int cmd: the nina-fw command +//| :param params: the parameters, each a buffer or a sequence of byte values +//| :param int reply_params: how many parameters the reply must have, or ``None`` to accept any number +//| :param bool sent_param_len_16: send each parameter length as 16 bits +//| :param bool recv_param_len_16: read each reply parameter length as 16 bits +//| """ +//| ... +//| +static mp_obj_t _airlift_transact(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_cmd, ARG_params, ARG_reply_params, ARG_sent_param_len_16, ARG_recv_param_len_16 }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_cmd, MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_params, MP_ARG_OBJ, {.u_obj = mp_const_none} }, + { MP_QSTR_reply_params, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = MP_OBJ_NEW_SMALL_INT(1)} }, + { MP_QSTR_sent_param_len_16, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, + { MP_QSTR_recv_param_len_16, MP_ARG_KW_ONLY | 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); + + uint8_t cmd = mp_arg_validate_int_range(args[ARG_cmd].u_int, 0, 255, MP_QSTR_cmd); + int expected_replies = -1; + if (args[ARG_reply_params].u_obj != mp_const_none) { + expected_replies = mp_arg_validate_int_range(mp_obj_get_int(args[ARG_reply_params].u_obj), + 0, 255, MP_QSTR_reply_params); + } + + size_t n_params = 0; + mp_obj_t *items = NULL; + if (args[ARG_params].u_obj != mp_const_none) { + mp_obj_get_array(args[ARG_params].u_obj, &n_params, &items); + } + // ESP32SPI sends at most 5 parameters. + airlift_param_t params[16]; + mp_arg_validate_length_max(n_params, MP_ARRAY_SIZE(params), MP_QSTR_params); + // Parameters given as sequences of ints, such as (socket,), are packed here. + uint8_t packed[64]; + size_t packed_len = 0; + for (size_t i = 0; i < n_params; i++) { + mp_buffer_info_t bufinfo; + if (mp_get_buffer(items[i], &bufinfo, MP_BUFFER_READ)) { + params[i].buf = bufinfo.buf; + params[i].len = bufinfo.len; + continue; + } + size_t len; + mp_obj_t *values; + mp_obj_get_array(items[i], &len, &values); + mp_arg_validate_length_max(packed_len + len, sizeof(packed), MP_QSTR_params); + params[i].buf = packed + packed_len; + params[i].len = len; + for (size_t j = 0; j < len; j++) { + packed[packed_len++] = mp_arg_validate_int_range(mp_obj_get_int(values[j]), 0, 255, MP_QSTR_params); + } + } + + return common_hal__airlift_transact(cmd, params, n_params, args[ARG_sent_param_len_16].u_bool, + expected_replies, args[ARG_recv_param_len_16].u_bool); +} +static MP_DEFINE_CONST_FUN_OBJ_KW(_airlift_transact_obj, 1, _airlift_transact); + +static const mp_rom_map_elem_t _airlift_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR__airlift) }, + { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&_airlift_init_obj) }, + { MP_ROM_QSTR(MP_QSTR_active), MP_ROM_PTR(&_airlift_active_obj) }, + { MP_ROM_QSTR(MP_QSTR_reset), MP_ROM_PTR(&_airlift_reset_obj) }, + { MP_ROM_QSTR(MP_QSTR_release), MP_ROM_PTR(&_airlift_release_obj) }, + { MP_ROM_QSTR(MP_QSTR_transact), MP_ROM_PTR(&_airlift_transact_obj) }, + { MP_ROM_QSTR(MP_QSTR_MAX_SOCKETS), MP_ROM_INT(CIRCUITPY_AIRLIFT_MAX_SOCKETS) }, + { MP_ROM_QSTR(MP_QSTR_MAX_TRANSFER), MP_ROM_INT(AIRLIFT_MAX_TRANSFER) }, + { MP_ROM_QSTR(MP_QSTR_MAX_READ), MP_ROM_INT(AIRLIFT_MAX_READ) }, +}; + +static MP_DEFINE_CONST_DICT(_airlift_module_globals, _airlift_module_globals_table); + +const mp_obj_module_t _airlift_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&_airlift_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR__airlift, _airlift_module); diff --git a/shared-bindings/_airlift/__init__.h b/shared-bindings/_airlift/__init__.h new file mode 100644 index 00000000000..c019bba9210 --- /dev/null +++ b/shared-bindings/_airlift/__init__.h @@ -0,0 +1,22 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include +#include + +#include "py/obj.h" +#include "shared-module/_airlift/transport.h" + +void common_hal__airlift_init(void); +bool common_hal__airlift_active(void); +void common_hal__airlift_reset(void); +void common_hal__airlift_release(void); +// expected_replies < 0 takes the count from the reply. Returns a list of bytearrays. +mp_obj_t common_hal__airlift_transact(uint8_t cmd, const airlift_param_t *params, size_t n_params, + bool param_len_16, int expected_replies, bool reply_len_16); diff --git a/shared-bindings/_bleio/Adapter.c b/shared-bindings/_bleio/Adapter.c index 92b910c8b2e..da8537c931e 100644 --- a/shared-bindings/_bleio/Adapter.c +++ b/shared-bindings/_bleio/Adapter.c @@ -8,11 +8,16 @@ #include #include "py/objproperty.h" +#include "py/objstr.h" #include "py/runtime.h" #include "shared-bindings/_bleio/__init__.h" #include "shared-bindings/_bleio/Address.h" #include "shared-bindings/_bleio/Adapter.h" +#if CIRCUITPY_SETTINGS_TOML +#include "supervisor/shared/settings.h" +#endif + #define ADV_INTERVAL_MIN (0.02f) #define ADV_INTERVAL_MIN_STRING "0.02" #define ADV_INTERVAL_MAX (10.24f) @@ -134,8 +139,11 @@ MP_PROPERTY_GETSET(bleio_adapter_address_obj, //| name: str //| """name of the BLE adapter used once connected. -//| The name is "CIRCUITPY" + the last four hex digits of ``adapter.address``, -//| to make it easy to distinguish multiple CircuitPython boards.""" +//| The default name is "CIRCUITPY" plus the last four hex digits of +//| ``adapter.address``, to make it easy to distinguish multiple +//| CircuitPython boards. Set ``CIRCUITPY_BLE_NAME`` in settings.toml to +//| override it. The default is re-applied each time the adapter is +//| enabled.""" //| static mp_obj_t _bleio_adapter_get_name(mp_obj_t self) { return MP_OBJ_FROM_PTR(common_hal_bleio_adapter_get_name(self)); @@ -153,6 +161,37 @@ MP_PROPERTY_GETSET(bleio_adapter_name_obj, (mp_obj_t)&bleio_adapter_get_name_obj, (mp_obj_t)&bleio_adapter_set_name_obj); +void bleio_adapter_reset_name(bleio_adapter_obj_t *self) { + #if CIRCUITPY_SETTINGS_TOML + // Let the user override the default name from settings.toml. Use the + // allocation-free settings_get_str (not os.getenv), because ports call + // this from common_hal_bleio_adapter_set_enabled() which can run before + // the VM/gc heap is initialized. + char ble_name[32]; + settings_err_t result = settings_get_str("CIRCUITPY_BLE_NAME", ble_name, sizeof(ble_name)); + if (result == SETTINGS_OK) { + common_hal_bleio_adapter_set_name(self, ble_name); + return; + } + #endif + + // Default to "CIRCUITPY" plus the last four hex digits of the adapter + // address so multiple boards are distinguishable. The address bytes are + // little-endian, so address[0] is the least-significant byte. If the port + // cannot provide an address, fall back to the literal "CIRCUITPYxxxx". + char default_ble_name[] = "CIRCUITPYxxxx"; + bleio_address_obj_t *address = common_hal_bleio_adapter_get_address(self); + if (address != NULL) { + uint8_t addr_bytes[NUM_BLEIO_ADDRESS_BYTES]; + common_hal_bleio_address_get_bytes(address, addr_bytes); + default_ble_name[ 9] = nibble_to_hex_lower[addr_bytes[1] >> 4 & 0xf]; + default_ble_name[10] = nibble_to_hex_lower[addr_bytes[1] & 0xf]; + default_ble_name[11] = nibble_to_hex_lower[addr_bytes[0] >> 4 & 0xf]; + default_ble_name[12] = nibble_to_hex_lower[addr_bytes[0] & 0xf]; + } + common_hal_bleio_adapter_set_name(self, default_ble_name); +} + //| def start_advertising( //| self, //| data: ReadableBuffer, @@ -215,7 +254,7 @@ static mp_obj_t bleio_adapter_start_advertising(mp_uint_t n_args, const mp_obj_t args[ARG_interval].u_obj = mp_obj_new_float(ADV_INTERVAL_DEFAULT); } - const mp_float_t interval = mp_obj_get_float(args[ARG_interval].u_obj); + const mp_float_t interval = mp_arg_validate_type_float(args[ARG_interval].u_obj, MP_QSTR_interval); if (interval < ADV_INTERVAL_MIN || interval > ADV_INTERVAL_MAX) { mp_raise_ValueError_varg(MP_ERROR_TEXT("interval must be in range %s-%s"), ADV_INTERVAL_MIN_STRING, ADV_INTERVAL_MAX_STRING); @@ -223,7 +262,7 @@ static mp_obj_t bleio_adapter_start_advertising(mp_uint_t n_args, const mp_obj_t bool connectable = args[ARG_connectable].u_bool; bool anonymous = args[ARG_anonymous].u_bool; - uint32_t timeout = args[ARG_timeout].u_int; + const uint32_t timeout = (uint32_t)mp_arg_validate_int_min(args[ARG_timeout].u_int, 0, MP_QSTR_timeout); if (data_bufinfo.len > 31 && connectable && scan_response_bufinfo.len > 0) { mp_raise_bleio_BluetoothError(MP_ERROR_TEXT("Cannot have scan responses for extended, connectable advertisements.")); } @@ -306,7 +345,7 @@ static mp_obj_t bleio_adapter_start_scan(size_t n_args, const mp_obj_t *pos_args mp_float_t timeout = 0.0f; if (args[ARG_timeout].u_obj != mp_const_none) { - timeout = mp_obj_get_float(args[ARG_timeout].u_obj); + timeout = mp_arg_validate_obj_float_non_negative(args[ARG_timeout].u_obj, 0.0f, MP_QSTR_timeout); } if (args[ARG_interval].u_obj == MP_OBJ_NULL) { @@ -317,7 +356,7 @@ static mp_obj_t bleio_adapter_start_scan(size_t n_args, const mp_obj_t *pos_args args[ARG_window].u_obj = mp_obj_new_float(WINDOW_DEFAULT); } - const mp_float_t interval = mp_obj_get_float(args[ARG_interval].u_obj); + const mp_float_t interval = mp_arg_validate_type_float(args[ARG_interval].u_obj, MP_QSTR_interval); if (interval < INTERVAL_MIN || interval > INTERVAL_MAX) { mp_raise_ValueError_varg(MP_ERROR_TEXT("interval must be in range %s-%s"), INTERVAL_MIN_STRING, INTERVAL_MAX_STRING); } @@ -329,7 +368,7 @@ static mp_obj_t bleio_adapter_start_scan(size_t n_args, const mp_obj_t *pos_args } #pragma GCC diagnostic pop - const mp_float_t window = mp_obj_get_float(args[ARG_window].u_obj); + const mp_float_t window = mp_arg_validate_type_float(args[ARG_window].u_obj, MP_QSTR_window); if (window > interval) { mp_raise_ValueError(MP_ERROR_TEXT("window must be <= interval")); } @@ -339,12 +378,14 @@ static mp_obj_t bleio_adapter_start_scan(size_t n_args, const mp_obj_t *pos_args if (args[ARG_prefixes].u_obj != MP_OBJ_NULL) { mp_get_buffer_raise(args[ARG_prefixes].u_obj, &prefix_bufinfo, MP_BUFFER_READ); // An empty buffer may not be on the heap, but that doesn't matter. - if (prefix_bufinfo.len > 0 && gc_nbytes(prefix_bufinfo.buf) == 0) { + if (prefix_bufinfo.len > 0 && !gc_ptr_on_heap(prefix_bufinfo.buf)) { mp_raise_ValueError(MP_ERROR_TEXT("Prefix buffer must be on the heap")); } } - return common_hal_bleio_adapter_start_scan(self, prefix_bufinfo.buf, prefix_bufinfo.len, args[ARG_extended].u_bool, args[ARG_buffer_size].u_int, timeout, interval, window, args[ARG_minimum_rssi].u_int, args[ARG_active].u_bool); + const mp_int_t buffer_size = mp_arg_validate_int_min(args[ARG_buffer_size].u_int, 1, MP_QSTR_buffer_size); + + return common_hal_bleio_adapter_start_scan(self, prefix_bufinfo.buf, prefix_bufinfo.len, args[ARG_extended].u_bool, buffer_size, timeout, interval, window, args[ARG_minimum_rssi].u_int, args[ARG_active].u_bool); } static MP_DEFINE_CONST_FUN_OBJ_KW(bleio_adapter_start_scan_obj, 1, bleio_adapter_start_scan); @@ -416,7 +457,8 @@ static mp_obj_t bleio_adapter_connect(mp_uint_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); bleio_address_obj_t *address = mp_arg_validate_type(args[ARG_address].u_obj, &bleio_address_type, MP_QSTR_address); - mp_float_t timeout = mp_obj_get_float(args[ARG_timeout].u_obj); + const mp_float_t timeout = + mp_arg_validate_obj_float_non_negative(args[ARG_timeout].u_obj, 0.0f, MP_QSTR_timeout); return common_hal_bleio_adapter_connect(self, address, timeout); } diff --git a/shared-bindings/_bleio/Adapter.h b/shared-bindings/_bleio/Adapter.h index 0bc6f051ff3..1035461d35a 100644 --- a/shared-bindings/_bleio/Adapter.h +++ b/shared-bindings/_bleio/Adapter.h @@ -35,6 +35,13 @@ uint16_t bleio_adapter_get_name(char *buf, uint16_t len); 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); +// Resets the adapter's device name to the default: the CIRCUITPY_BLE_NAME setting value if +// set, otherwise "CIRCUITPY" plus the last four hex digits of the adapter's address (read via +// common_hal_bleio_adapter_get_address). Every port calls this from its +// common_hal_bleio_adapter_set_enabled once the controller is ready, so the default name is +// derived the same way everywhere. +void bleio_adapter_reset_name(bleio_adapter_obj_t *self); + // Returns 0 if ok, otherwise a BLE stack specific error code. extern uint32_t _common_hal_bleio_adapter_start_advertising(bleio_adapter_obj_t *self, bool connectable, bool anonymous, uint32_t timeout, float interval, diff --git a/shared-bindings/_bleio/Address.c b/shared-bindings/_bleio/Address.c index 58f8a8adc1e..ac5c47bec8a 100644 --- a/shared-bindings/_bleio/Address.c +++ b/shared-bindings/_bleio/Address.c @@ -37,20 +37,18 @@ static mp_obj_t bleio_address_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_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); - bleio_address_obj_t *self = mp_obj_malloc(bleio_address_obj_t, &bleio_address_type); - const mp_obj_t address = args[ARG_address].u_obj; mp_buffer_info_t buf_info; mp_get_buffer_raise(address, &buf_info, MP_BUFFER_READ); - if (buf_info.len != NUM_BLEIO_ADDRESS_BYTES) { - mp_raise_ValueError_varg(MP_ERROR_TEXT("Address must be %d bytes long"), NUM_BLEIO_ADDRESS_BYTES); - } + mp_arg_validate_length(buf_info.len, NUM_BLEIO_ADDRESS_BYTES, MP_QSTR_address); - const mp_int_t address_type = args[ARG_address_type].u_int; - if (address_type < BLEIO_ADDRESS_TYPE_MIN || address_type > BLEIO_ADDRESS_TYPE_MAX) { - mp_arg_error_invalid(MP_QSTR_address_type); - } + const mp_int_t address_type = + mp_arg_validate_int_range(args[ARG_address_type].u_int, + BLEIO_ADDRESS_TYPE_MIN, + BLEIO_ADDRESS_TYPE_MAX, + MP_QSTR_address_type); + bleio_address_obj_t *self = mp_obj_malloc(bleio_address_obj_t, &bleio_address_type); common_hal_bleio_address_construct(self, buf_info.buf, address_type); return MP_OBJ_FROM_PTR(self); @@ -110,10 +108,8 @@ static mp_obj_t bleio_address_binary_op(mp_binary_op_t op, mp_obj_t lhs_in, mp_o bleio_address_obj_t *lhs = MP_OBJ_TO_PTR(lhs_in); 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_type(lhs) == - common_hal_bleio_address_get_type(rhs)); + lhs->type == rhs->type && + memcmp(lhs->bytes, rhs->bytes, NUM_BLEIO_ADDRESS_BYTES) == 0); } else { return mp_const_false; @@ -132,13 +128,9 @@ static mp_obj_t bleio_address_unary_op(mp_unary_op_t op, mp_obj_t self_in) { switch (op) { // Two Addresses are equal if their address bytes and address_type are equal case MP_UNARY_OP_HASH: { - mp_obj_t bytes = common_hal_bleio_address_get_address_bytes(MP_OBJ_TO_PTR(self_in)); - GET_STR_HASH(bytes, h); - if (h == 0) { - GET_STR_DATA_LEN(bytes, data, len); - h = qstr_compute_hash(data, len); - } - h ^= common_hal_bleio_address_get_type(MP_OBJ_TO_PTR(self_in)); + bleio_address_obj_t *self = MP_OBJ_TO_PTR(self_in); + mp_int_t h = (mp_int_t)qstr_compute_hash(self->bytes, NUM_BLEIO_ADDRESS_BYTES); + h ^= self->type; return MP_OBJ_NEW_SMALL_INT(h); } default: @@ -148,11 +140,7 @@ static mp_obj_t bleio_address_unary_op(mp_unary_op_t op, mp_obj_t self_in) { static void bleio_address_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { bleio_address_obj_t *self = MP_OBJ_TO_PTR(self_in); - mp_buffer_info_t buf_info; - 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 = self->bytes; mp_printf(print, "
", buf[5], buf[4], buf[3], buf[2], buf[1], buf[0]); } diff --git a/shared-bindings/_bleio/Address.h b/shared-bindings/_bleio/Address.h index c869ccf55cb..a61f28c0369 100644 --- a/shared-bindings/_bleio/Address.h +++ b/shared-bindings/_bleio/Address.h @@ -20,6 +20,10 @@ extern const mp_obj_type_t bleio_address_type; -extern void common_hal_bleio_address_construct(bleio_address_obj_t *self, uint8_t *bytes, uint8_t address_type); +extern void common_hal_bleio_address_construct(bleio_address_obj_t *self, const uint8_t *bytes, uint8_t address_type); extern mp_obj_t common_hal_bleio_address_get_address_bytes(bleio_address_obj_t *self); extern uint8_t common_hal_bleio_address_get_type(bleio_address_obj_t *self); +// Copies the raw address bytes (little-endian BD_ADDR, NUM_BLEIO_ADDRESS_BYTES) +// into the given buffer. Allocation-free, so it is safe to use before the heap +// is initialized (e.g. when deriving the default adapter name). +extern void common_hal_bleio_address_get_bytes(bleio_address_obj_t *self, uint8_t bytes[NUM_BLEIO_ADDRESS_BYTES]); diff --git a/shared-bindings/_bleio/Attribute.h b/shared-bindings/_bleio/Attribute.h index 51278dc0157..60a941a5772 100644 --- a/shared-bindings/_bleio/Attribute.h +++ b/shared-bindings/_bleio/Attribute.h @@ -14,3 +14,7 @@ extern const mp_obj_type_t bleio_attribute_type; extern void common_hal_bleio_attribute_security_mode_check_valid(bleio_attribute_security_mode_t security_mode); + +// True for the security modes that demand a man-in-the-middle-protected (authenticated) +// link: pairing must use numeric comparison or passkey entry, not "Just Works". +extern bool bleio_attribute_security_mode_requires_mitm(bleio_attribute_security_mode_t security_mode); diff --git a/shared-bindings/_bleio/Characteristic.c b/shared-bindings/_bleio/Characteristic.c index 8d6ac43e487..0ed4c2b7eaa 100644 --- a/shared-bindings/_bleio/Characteristic.c +++ b/shared-bindings/_bleio/Characteristic.c @@ -116,9 +116,10 @@ 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(MP_ERROR_TEXT("initial_value length is wrong")); + if (fixed_length) { + mp_arg_validate_length(initial_value_bufinfo.len, max_length, MP_QSTR_initial_value); + } else { + mp_arg_validate_length_max(initial_value_bufinfo.len, max_length, MP_QSTR_initial_value); } const char *user_description = NULL; diff --git a/shared-bindings/_bleio/CharacteristicBuffer.c b/shared-bindings/_bleio/CharacteristicBuffer.c index 5ffff0dcba7..c0561f7f7eb 100644 --- a/shared-bindings/_bleio/CharacteristicBuffer.c +++ b/shared-bindings/_bleio/CharacteristicBuffer.c @@ -56,7 +56,7 @@ static mp_obj_t bleio_characteristic_buffer_make_new(const mp_obj_type_t *type, const mp_int_t buffer_size = mp_arg_validate_int_min(args[ARG_buffer_size].u_int, 1, MP_QSTR_buffer_size); bleio_characteristic_buffer_obj_t *self = - mp_obj_malloc(bleio_characteristic_buffer_obj_t, &bleio_characteristic_buffer_type); + mp_obj_malloc_with_finaliser(bleio_characteristic_buffer_obj_t, &bleio_characteristic_buffer_type); common_hal_bleio_characteristic_buffer_construct(self, characteristic, timeout, buffer_size); @@ -118,7 +118,7 @@ static mp_uint_t bleio_characteristic_buffer_write(mp_obj_t self_in, const void return 0; } -static mp_uint_t bleio_characteristic_buffer_ioctl(mp_obj_t self_in, mp_uint_t request, mp_uint_t arg, int *errcode) { +static mp_uint_t bleio_characteristic_buffer_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) { bleio_characteristic_buffer_obj_t *self = MP_OBJ_TO_PTR(self_in); check_for_deinit(self); raise_error_if_not_connected(self); @@ -184,6 +184,7 @@ static MP_DEFINE_CONST_FUN_OBJ_1(bleio_characteristic_buffer_deinit_obj, bleio_c static const mp_rom_map_elem_t bleio_characteristic_buffer_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&bleio_characteristic_buffer_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&bleio_characteristic_buffer_deinit_obj) }, // Standard stream methods. { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&mp_stream_read_obj) }, diff --git a/shared-bindings/_bleio/Connection.c b/shared-bindings/_bleio/Connection.c index 4a81d753433..743b3d6dacc 100644 --- a/shared-bindings/_bleio/Connection.c +++ b/shared-bindings/_bleio/Connection.c @@ -59,8 +59,10 @@ void bleio_connection_ensure_connected(bleio_connection_obj_t *self) { //| static mp_obj_t bleio_connection_disconnect(mp_obj_t self_in) { bleio_connection_obj_t *self = MP_OBJ_TO_PTR(self_in); - // common_hal_bleio_connection_disconnect() does nothing if already disconnected. - common_hal_bleio_connection_disconnect(self->connection); + // Do nothing if already disconnected. self->connection is NULL after the peer disconnects. + if (common_hal_bleio_connection_get_connected(self)) { + common_hal_bleio_connection_disconnect(self->connection); + } return mp_const_none; } static MP_DEFINE_CONST_FUN_OBJ_1(bleio_connection_disconnect_obj, bleio_connection_disconnect); @@ -165,6 +167,78 @@ MP_PROPERTY_GETTER(bleio_connection_paired_obj, (mp_obj_t)&bleio_connection_get_paired_obj); +//| authenticated: bool +//| """True if the link is encrypted *and* authenticated against +//| man-in-the-middle attacks - i.e. LE Secure Connections numeric comparison (or +//| passkey entry) completed. A plain encrypted-but-unauthenticated ("Just Works") +//| link reads ``False``. +//| +//| Ports that don't implement authenticated pairing always report ``False``, +//| even for a bonded link.""" +static mp_obj_t bleio_connection_get_authenticated(mp_obj_t self_in) { + bleio_connection_obj_t *self = MP_OBJ_TO_PTR(self_in); + + return mp_obj_new_bool(common_hal_bleio_connection_get_authenticated(self)); +} +static MP_DEFINE_CONST_FUN_OBJ_1(bleio_connection_get_authenticated_obj, bleio_connection_get_authenticated); + +MP_PROPERTY_GETTER(bleio_connection_authenticated_obj, + (mp_obj_t)&bleio_connection_get_authenticated_obj); + + +//| numeric_comparison: Optional[int] +//| """When the peer has started LE Secure Connections pairing and is waiting for the +//| user to confirm a 6-digit numeric-comparison value, this is that value (an ``int``, +//| 0-999999); otherwise ``None``. Poll it, show the value to the user, then answer +//| with `confirm_pairing`. This is the peripheral side of pairing: the peer drives +//| the procedure, so unlike `pair` this never blocks. +//| +//| Numeric comparison happens automatically when a central pairs to reach a +//| characteristic whose ``read_perm`` / ``write_perm`` is +//| `Attribute.LESC_ENCRYPT_WITH_MITM`. A peripheral with a display and a button +//| services it roughly like this:: +//| +//| while connection.connected: +//| code = connection.numeric_comparison +//| if code is not None: +//| display.show(f"Pair? {code:06d}") +//| connection.confirm_pairing(accept=button_a.value) +//| if connection.authenticated: +//| break +//| time.sleep(0.1) +//| +//| Only implemented on the espressif port.""" +static mp_obj_t bleio_connection_get_numeric_comparison(mp_obj_t self_in) { + bleio_connection_obj_t *self = MP_OBJ_TO_PTR(self_in); + + return common_hal_bleio_connection_get_numeric_comparison(self); +} +static MP_DEFINE_CONST_FUN_OBJ_1(bleio_connection_get_numeric_comparison_obj, bleio_connection_get_numeric_comparison); + +MP_PROPERTY_GETTER(bleio_connection_numeric_comparison_obj, + (mp_obj_t)&bleio_connection_get_numeric_comparison_obj); + + +//| def confirm_pairing(self, accept: bool) -> None: +//| """Answer a pending numeric-comparison pairing request (see +//| `numeric_comparison`). Pass ``accept=True`` if the value shown on the +//| peer matches the one shown here, ``accept=False`` to reject and abort pairing. +//| +//| :raises ConnectionError: if the connection has dropped. +//| :raises _bleio.BluetoothError: if no numeric-comparison request is pending - +//| nothing was offered on `numeric_comparison`, or it already expired +//| because the peer disconnected or the pairing procedure timed out.""" +//| ... +//| +static mp_obj_t bleio_connection_confirm_pairing(mp_obj_t self_in, mp_obj_t accept_in) { + bleio_connection_obj_t *self = MP_OBJ_TO_PTR(self_in); + + common_hal_bleio_connection_confirm_pairing(self, mp_obj_is_true(accept_in)); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(bleio_connection_confirm_pairing_obj, bleio_connection_confirm_pairing); + + //| connection_interval: float //| """Time between transmissions in milliseconds. Will be multiple of 1.25ms. Lower numbers //| increase speed and decrease latency but increase power consumption. @@ -223,12 +297,15 @@ MP_PROPERTY_GETTER(bleio_connection_max_packet_length_obj, static const mp_rom_map_elem_t bleio_connection_locals_dict_table[] = { // Methods { MP_ROM_QSTR(MP_QSTR_pair), MP_ROM_PTR(&bleio_connection_pair_obj) }, + { MP_ROM_QSTR(MP_QSTR_confirm_pairing), MP_ROM_PTR(&bleio_connection_confirm_pairing_obj) }, { MP_ROM_QSTR(MP_QSTR_disconnect), MP_ROM_PTR(&bleio_connection_disconnect_obj) }, { MP_ROM_QSTR(MP_QSTR_discover_remote_services), MP_ROM_PTR(&bleio_connection_discover_remote_services_obj) }, // Properties { MP_ROM_QSTR(MP_QSTR_connected), MP_ROM_PTR(&bleio_connection_connected_obj) }, { MP_ROM_QSTR(MP_QSTR_paired), MP_ROM_PTR(&bleio_connection_paired_obj) }, + { MP_ROM_QSTR(MP_QSTR_authenticated), MP_ROM_PTR(&bleio_connection_authenticated_obj) }, + { MP_ROM_QSTR(MP_QSTR_numeric_comparison), MP_ROM_PTR(&bleio_connection_numeric_comparison_obj) }, { MP_ROM_QSTR(MP_QSTR_connection_interval), MP_ROM_PTR(&bleio_connection_connection_interval_obj) }, { MP_ROM_QSTR(MP_QSTR_max_packet_length), MP_ROM_PTR(&bleio_connection_max_packet_length_obj) }, }; diff --git a/shared-bindings/_bleio/Connection.h b/shared-bindings/_bleio/Connection.h index 4be4992fb2f..fbc856c7d45 100644 --- a/shared-bindings/_bleio/Connection.h +++ b/shared-bindings/_bleio/Connection.h @@ -18,6 +18,9 @@ void common_hal_bleio_connection_disconnect(bleio_connection_internal_t *self); bool common_hal_bleio_connection_get_connected(bleio_connection_obj_t *self); mp_int_t common_hal_bleio_connection_get_max_packet_length(bleio_connection_internal_t *self); bool common_hal_bleio_connection_get_paired(bleio_connection_obj_t *self); +bool common_hal_bleio_connection_get_authenticated(bleio_connection_obj_t *self); +mp_obj_t common_hal_bleio_connection_get_numeric_comparison(bleio_connection_obj_t *self); +void common_hal_bleio_connection_confirm_pairing(bleio_connection_obj_t *self, bool accept); mp_obj_tuple_t *common_hal_bleio_connection_discover_remote_services(bleio_connection_obj_t *self, mp_obj_t service_uuids_whitelist); mp_float_t common_hal_bleio_connection_get_connection_interval(bleio_connection_internal_t *self); diff --git a/shared-bindings/_bleio/Descriptor.c b/shared-bindings/_bleio/Descriptor.c index 57cc605029f..9e29f57d8dd 100644 --- a/shared-bindings/_bleio/Descriptor.c +++ b/shared-bindings/_bleio/Descriptor.c @@ -99,9 +99,10 @@ 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(MP_ERROR_TEXT("initial_value length is wrong")); + if (fixed_length) { + mp_arg_validate_length(initial_value_bufinfo.len, max_length, MP_QSTR_initial_value); + } else { + mp_arg_validate_length_max(initial_value_bufinfo.len, max_length, MP_QSTR_initial_value); } bleio_descriptor_obj_t *descriptor = mp_obj_malloc(bleio_descriptor_obj_t, &bleio_descriptor_type); diff --git a/shared-bindings/_bleio/PacketBuffer.c b/shared-bindings/_bleio/PacketBuffer.c index 47d71ebd55a..8c633d50ef7 100644 --- a/shared-bindings/_bleio/PacketBuffer.c +++ b/shared-bindings/_bleio/PacketBuffer.c @@ -57,10 +57,13 @@ static mp_obj_t bleio_packet_buffer_make_new(const mp_obj_type_t *type, size_t n 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); + const mp_int_t max_packet_size_int = + mp_arg_validate_type_int(args[ARG_max_packet_size].u_obj, MP_QSTR_max_packet_size); + max_packet_size = + (size_t)mp_arg_validate_int_min(max_packet_size_int, 1, MP_QSTR_max_packet_size); } - bleio_packet_buffer_obj_t *self = mp_obj_malloc(bleio_packet_buffer_obj_t, &bleio_packet_buffer_type); + bleio_packet_buffer_obj_t *self = mp_obj_malloc_with_finaliser(bleio_packet_buffer_obj_t, &bleio_packet_buffer_type); common_hal_bleio_packet_buffer_construct(self, characteristic, buffer_size, max_packet_size); @@ -196,6 +199,7 @@ MP_PROPERTY_GETTER(bleio_packet_buffer_outgoing_packet_length_obj, static const mp_rom_map_elem_t bleio_packet_buffer_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&bleio_packet_buffer_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&bleio_packet_buffer_deinit_obj) }, // Standard stream methods. { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&bleio_packet_buffer_readinto_obj) }, diff --git a/shared-bindings/_bleio/PacketBuffer.h b/shared-bindings/_bleio/PacketBuffer.h index 1a872512da2..24fb24bce78 100644 --- a/shared-bindings/_bleio/PacketBuffer.h +++ b/shared-bindings/_bleio/PacketBuffer.h @@ -6,6 +6,7 @@ #pragma once +#include "shared-bindings/_bleio/Characteristic.h" #include "common-hal/_bleio/PacketBuffer.h" extern const mp_obj_type_t bleio_packet_buffer_type; @@ -21,13 +22,11 @@ void common_hal_bleio_packet_buffer_construct( bleio_packet_buffer_obj_t *self, bleio_characteristic_obj_t *characteristic, size_t buffer_size, size_t max_packet_size); // Allocation free version for BLE workflow use. -#if CIRCUITPY_SERIAL_BLE || CIRCUITPY_BLE_FILE_SERVICE void _common_hal_bleio_packet_buffer_construct( bleio_packet_buffer_obj_t *self, bleio_characteristic_obj_t *characteristic, uint32_t *incoming_buffer, size_t incoming_buffer_size, - uint32_t *outgoing_buffer1, uint32_t *outgoing_buffer2, size_t outgoing_buffer_size, + uint32_t *outgoing_buffer1, uint32_t *outgoing_buffer2, size_t max_packet_size, ble_event_handler_t *static_handler_entry); -#endif mp_int_t common_hal_bleio_packet_buffer_write(bleio_packet_buffer_obj_t *self, const 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); diff --git a/shared-bindings/_bleio/Service.c b/shared-bindings/_bleio/Service.c index cea9a68e694..920d66a3de2 100644 --- a/shared-bindings/_bleio/Service.c +++ b/shared-bindings/_bleio/Service.c @@ -8,6 +8,7 @@ #include "py/objproperty.h" #include "py/runtime.h" +#include "shared-bindings/_bleio/__init__.h" #include "shared-bindings/_bleio/Characteristic.h" #include "shared-bindings/_bleio/Service.h" #include "shared-bindings/_bleio/UUID.h" @@ -45,6 +46,9 @@ static mp_obj_t bleio_service_make_new(const mp_obj_type_t *type, size_t n_args, bleio_service_obj_t *service = mp_obj_malloc_with_finaliser(bleio_service_obj_t, &bleio_service_type); common_hal_bleio_service_construct(service, uuid, is_secondary); + // Remember that there are services that were created by the user. + // bleio_reset() needs this to know what kind of reset to do. + bleio_set_user_services_created(); return MP_OBJ_FROM_PTR(service); } diff --git a/shared-bindings/_bleio/UUID.c b/shared-bindings/_bleio/UUID.c index 2d28d5a9b61..eef8546e253 100644 --- a/shared-bindings/_bleio/UUID.c +++ b/shared-bindings/_bleio/UUID.c @@ -34,20 +34,18 @@ static mp_obj_t bleio_uuid_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { mp_arg_check_num(n_args, n_kw, 1, 1, false); - bleio_uuid_obj_t *self = mp_obj_malloc(bleio_uuid_obj_t, &bleio_uuid_type); - const mp_obj_t value = all_args[0]; uint8_t uuid128[16]; if (mp_obj_is_int(value)) { - mp_int_t uuid16 = mp_obj_get_int(value); - if (uuid16 < 0 || uuid16 > 0xffff) { - mp_raise_ValueError(MP_ERROR_TEXT("UUID integer value must be 0-0xffff")); - } + const mp_int_t uuid16 = + mp_arg_validate_int_range(mp_obj_get_int(value), 0, 0xffff, MP_QSTR_value); // NULL means no 128-bit value. + bleio_uuid_obj_t *self = mp_obj_malloc(bleio_uuid_obj_t, &bleio_uuid_type); common_hal_bleio_uuid_construct(self, uuid16, NULL); + return MP_OBJ_FROM_PTR(self); } else { if (mp_obj_is_str(value)) { // 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' @@ -82,9 +80,7 @@ static mp_obj_t bleio_uuid_make_new(const mp_obj_type_t *type, size_t n_args, si mp_raise_ValueError(MP_ERROR_TEXT("UUID value is not str, int or byte buffer")); } - if (bufinfo.len != 16) { - mp_raise_ValueError(MP_ERROR_TEXT("Byte buffer must be 16 bytes.")); - } + mp_arg_validate_length(bufinfo.len, 16, MP_QSTR_value); memcpy(uuid128, bufinfo.buf, 16); } @@ -93,10 +89,12 @@ static mp_obj_t bleio_uuid_make_new(const mp_obj_type_t *type, size_t n_args, si uint32_t uuid16 = (uuid128[13] << 8) | uuid128[12]; uuid128[12] = 0; uuid128[13] = 0; + + bleio_uuid_obj_t *self = mp_obj_malloc(bleio_uuid_obj_t, &bleio_uuid_type); common_hal_bleio_uuid_construct(self, uuid16, uuid128); - } - return MP_OBJ_FROM_PTR(self); + return MP_OBJ_FROM_PTR(self); + } } //| uuid16: int @@ -171,12 +169,12 @@ static mp_obj_t bleio_uuid_pack_into(mp_uint_t n_args, const mp_obj_t *pos_args, mp_buffer_info_t bufinfo; mp_get_buffer_raise(args[ARG_buffer].u_obj, &bufinfo, MP_BUFFER_WRITE); - size_t offset = args[ARG_offset].u_int; - if (offset + common_hal_bleio_uuid_get_size(self) / 8 > bufinfo.len) { - mp_raise_ValueError(MP_ERROR_TEXT("Buffer + offset too small %d %d %d")); - } + const mp_int_t offset = + mp_arg_validate_int_range(args[ARG_offset].u_int, 0, (mp_int_t)bufinfo.len, MP_QSTR_offset); + const size_t packed_len = common_hal_bleio_uuid_get_size(self) / 8; + mp_arg_validate_length_min(bufinfo.len - (size_t)offset, packed_len, MP_QSTR_buffer); - common_hal_bleio_uuid_pack_into(self, bufinfo.buf + offset); + common_hal_bleio_uuid_pack_into(self, (uint8_t *)bufinfo.buf + (size_t)offset); return mp_const_none; } static MP_DEFINE_CONST_FUN_OBJ_KW(bleio_uuid_pack_into_obj, 1, bleio_uuid_pack_into); diff --git a/shared-bindings/_bleio/__init__.c b/shared-bindings/_bleio/__init__.c index 3bf8c1a2c9c..202542c3d05 100644 --- a/shared-bindings/_bleio/__init__.c +++ b/shared-bindings/_bleio/__init__.c @@ -56,7 +56,7 @@ //| //| MP_DEFINE_BLEIO_EXCEPTION(BluetoothError, Exception) -NORETURN void mp_raise_bleio_BluetoothError(mp_rom_error_text_t fmt, ...) { +MP_NORETURN void mp_raise_bleio_BluetoothError(mp_rom_error_text_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); @@ -72,7 +72,7 @@ NORETURN void mp_raise_bleio_BluetoothError(mp_rom_error_text_t fmt, ...) { //| //| MP_DEFINE_BLEIO_EXCEPTION(RoleError, bleio_BluetoothError) -NORETURN void mp_raise_bleio_RoleError(mp_rom_error_text_t msg) { +MP_NORETURN void mp_raise_bleio_RoleError(mp_rom_error_text_t msg) { mp_raise_msg(&mp_type_bleio_RoleError, msg); } @@ -83,7 +83,7 @@ NORETURN void mp_raise_bleio_RoleError(mp_rom_error_text_t msg) { //| //| MP_DEFINE_BLEIO_EXCEPTION(SecurityError, bleio_BluetoothError) -NORETURN void mp_raise_bleio_SecurityError(mp_rom_error_text_t fmt, ...) { +MP_NORETURN void mp_raise_bleio_SecurityError(mp_rom_error_text_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); @@ -91,6 +91,20 @@ NORETURN void mp_raise_bleio_SecurityError(mp_rom_error_text_t fmt, ...) { nlr_raise(exception); } +static bool _user_services_created; + +bool bleio_get_user_services_created(void) { + return _user_services_created; +} + +void bleio_set_user_services_created(void) { + _user_services_created = true; +} + +void bleio_clear_user_services_created(void) { + _user_services_created = false; +} + // 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. diff --git a/shared-bindings/_bleio/__init__.h b/shared-bindings/_bleio/__init__.h index faf11ea1d06..0e8a9212e6b 100644 --- a/shared-bindings/_bleio/__init__.h +++ b/shared-bindings/_bleio/__init__.h @@ -39,25 +39,31 @@ void bleio_user_reset(void); // Completely resets the BLE stack including BLE connections. void bleio_reset(void); +// True if user code created a local GATT service during this VM run. Set by the +// shared-bindings Service constructor; the supervisor constructs its BLE workflow +// services through common-hal directly and does not set it. User-created services +// can only be removed from the stack's GATT table by a full stack reset, so a +// port's bleio_reset() uses this to decide whether that reset, which drops all +// connections, is needed at all. +bool bleio_get_user_services_created(void); + +// Record that user code created a local GATT service. +void bleio_set_user_services_created(void); + +// Clear the flag reported by bleio_get_user_services_created(). Call after a full +// stack reset, so the next VM run starts out clean. +void bleio_clear_user_services_created(void); + // Init any state needed before calling any bleio functions including those // having to do with bonding. This doesn't enable the BLE adapter though. void common_hal_bleio_init(void); extern mp_obj_t bleio_set_adapter(mp_obj_t adapter_obj); -NORETURN void mp_raise_bleio_BluetoothError(mp_rom_error_text_t msg, ...); -NORETURN void mp_raise_bleio_RoleError(mp_rom_error_text_t msg); -NORETURN void mp_raise_bleio_SecurityError(mp_rom_error_text_t msg, ...); +MP_NORETURN void mp_raise_bleio_BluetoothError(mp_rom_error_text_t msg, ...); +MP_NORETURN void mp_raise_bleio_RoleError(mp_rom_error_text_t msg); +MP_NORETURN void mp_raise_bleio_SecurityError(mp_rom_error_text_t msg, ...); bleio_adapter_obj_t *common_hal_bleio_allocate_adapter_or_raise(void); -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); -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); -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 000e3526ed5..a3914d07f32 100644 --- a/shared-bindings/_eve/__init__.c +++ b/shared-bindings/_eve/__init__.c @@ -970,6 +970,7 @@ static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(vertex2ii_obj, 3, 5, _vertex2ii); { MP_ROM_QSTR(MP_QSTR_PaletteSource), MP_ROM_PTR(&palettesource_obj) }, \ { MP_ROM_QSTR(MP_QSTR_PaletteSourceH), MP_ROM_PTR(&palettesourceh_obj) }, \ { MP_ROM_QSTR(MP_QSTR_PointSize), MP_ROM_PTR(&pointsize_obj) }, \ + { MP_ROM_QSTR(MP_QSTR_Region), MP_ROM_PTR(®ion_obj) }, \ { MP_ROM_QSTR(MP_QSTR_RestoreContext), MP_ROM_PTR(&restorecontext_obj) }, \ { MP_ROM_QSTR(MP_QSTR_Return), MP_ROM_PTR(&return_obj) }, \ { MP_ROM_QSTR(MP_QSTR_SaveContext), MP_ROM_PTR(&savecontext_obj) }, \ @@ -1061,8 +1062,29 @@ static mp_obj_t _pointsize(mp_obj_t self, mp_obj_t a0) { common_hal__eve_PointSize(EVEHAL(self), size); return mp_const_none; } + static MP_DEFINE_CONST_FUN_OBJ_2(pointsize_obj, _pointsize); +//| def Region(self, y: int, h: int, dest: int) -> None: +//| """Specify a cull region in the display list +//| +//| :param int y: Starting Y band in the render buffer. Range 0-63 +//| :param int h: Y height in the render buffer. Range 0-63 +//| :param int dest: destination address in the display list if the raster is outside the region +//| +//| """ +//| ... +//| + +static mp_obj_t _region(size_t n_args, const mp_obj_t *args) { + uint32_t y = mp_obj_get_int_truncated(args[1]); + uint32_t h = mp_obj_get_int_truncated(args[2]); + uint32_t dest = mp_obj_get_int_truncated(args[3]); + common_hal__eve_Region(EVEHAL(args[0]), y, h, dest); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(region_obj, 4, 4, _region); + //| def VertexTranslateX(self, x: float) -> None: //| """Set the vertex transformation's x translation component //| diff --git a/shared-bindings/_eve/__init__.h b/shared-bindings/_eve/__init__.h index e75f8db7928..13ae1b8a6cb 100644 --- a/shared-bindings/_eve/__init__.h +++ b/shared-bindings/_eve/__init__.h @@ -49,6 +49,7 @@ void common_hal__eve_Nop(common_hal__eve_t *eve); void common_hal__eve_PaletteSource(common_hal__eve_t *eve, uint32_t addr); void common_hal__eve_PaletteSourceH(common_hal__eve_t *eve, uint32_t addr); void common_hal__eve_PointSize(common_hal__eve_t *eve, mp_float_t size); +void common_hal__eve_Region(common_hal__eve_t *eve, uint32_t y, uint32_t h, uint32_t dest); void common_hal__eve_RestoreContext(common_hal__eve_t *eve); void common_hal__eve_Return(common_hal__eve_t *eve); void common_hal__eve_SaveContext(common_hal__eve_t *eve); diff --git a/shared-bindings/_pew/PewPew.c b/shared-bindings/_pew/PewPew.c index 42e7f4d372b..18ba850d6da 100644 --- a/shared-bindings/_pew/PewPew.c +++ b/shared-bindings/_pew/PewPew.c @@ -106,8 +106,19 @@ static mp_obj_t pewpew_make_new(const mp_obj_type_t *type, size_t n_args, size_t return MP_OBJ_FROM_PTR(pew); } +static mp_obj_t pewpew_deinit(mp_obj_t self_in) { + // Only the current PewPew owns the timer. An older one that was already + // deinited must not stop its replacement. + if (MP_STATE_VM(pew_singleton) == self_in) { + pew_deinit(); + MP_STATE_VM(pew_singleton) = NULL; + } + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(pewpew_deinit_obj, pewpew_deinit); static const mp_rom_map_elem_t pewpew_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&pewpew_deinit_obj) }, }; static MP_DEFINE_CONST_DICT(pewpew_locals_dict, pewpew_locals_dict_table); diff --git a/shared-bindings/_pew/__init__.c b/shared-bindings/_pew/__init__.c index cfcf627bbcf..7eac3fcf659 100644 --- a/shared-bindings/_pew/__init__.c +++ b/shared-bindings/_pew/__init__.c @@ -43,4 +43,6 @@ const mp_obj_module_t pew_module = { .globals = (mp_obj_dict_t *)&pew_module_globals, }; +MP_REGISTER_MODULE(MP_QSTR__pew, pew_module); + MP_REGISTER_ROOT_POINTER(mp_obj_t pew_singleton); diff --git a/shared-bindings/_pixelmap/PixelMap.c b/shared-bindings/_pixelmap/PixelMap.c index 9e3b9bb0a8d..913603dc3b9 100644 --- a/shared-bindings/_pixelmap/PixelMap.c +++ b/shared-bindings/_pixelmap/PixelMap.c @@ -24,8 +24,8 @@ static mp_obj_t pixelmap_pixelmap_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { enum { ARG_pixelbuf, ARG_indices }; static const mp_arg_t allowed_args[] = { - { MP_QSTR_pixelbuf, MP_ARG_REQUIRED }, - { MP_QSTR_indices, MP_ARG_REQUIRED }, + { MP_QSTR_pixelbuf, MP_ARG_OBJ | MP_ARG_REQUIRED }, + { MP_QSTR_indices, MP_ARG_OBJ | MP_ARG_REQUIRED }, }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; diff --git a/shared-bindings/_stage/Layer.c b/shared-bindings/_stage/Layer.c index de4861a70ee..0d7a1bfbd5e 100644 --- a/shared-bindings/_stage/Layer.c +++ b/shared-bindings/_stage/Layer.c @@ -38,38 +38,38 @@ static mp_obj_t layer_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, 4, 5, false); - layer_obj_t *self = mp_obj_malloc(layer_obj_t, type); - - self->width = mp_obj_get_int(args[0]); - self->height = mp_obj_get_int(args[1]); - self->x = 0; - self->y = 0; - self->frame = 0; - self->rotation = false; + mp_uint_t width = mp_arg_validate_int_min(mp_obj_get_int(args[0]), 0, MP_QSTR_width); + mp_uint_t height = mp_arg_validate_int_min(mp_obj_get_int(args[1]), 0, MP_QSTR_height); - mp_buffer_info_t bufinfo; - mp_get_buffer_raise(args[2], &bufinfo, MP_BUFFER_READ); - self->graphic = bufinfo.buf; - if (bufinfo.len != 2048) { - mp_raise_ValueError(MP_ERROR_TEXT("graphic must be 2048 bytes long")); - } + mp_buffer_info_t graphic_bufinfo; + mp_get_buffer_raise(args[2], &graphic_bufinfo, MP_BUFFER_READ); + mp_arg_validate_length(graphic_bufinfo.len, 2048, MP_QSTR_graphic); - mp_get_buffer_raise(args[3], &bufinfo, MP_BUFFER_READ); - self->palette = bufinfo.buf; - if (bufinfo.len != 32) { - mp_raise_ValueError(MP_ERROR_TEXT("palette must be 32 bytes long")); - } + mp_buffer_info_t palette_bufinfo; + mp_get_buffer_raise(args[3], &palette_bufinfo, MP_BUFFER_READ); + mp_arg_validate_length(palette_bufinfo.len, 32, MP_QSTR_palette); + mp_buffer_info_t map_bufinfo = { .buf = NULL }; if (n_args > 4) { - mp_get_buffer_raise(args[4], &bufinfo, MP_BUFFER_READ); - self->map = bufinfo.buf; - if (bufinfo.len < (self->width * self->height) / 2) { + mp_get_buffer_raise(args[4], &map_bufinfo, MP_BUFFER_READ); + if (map_bufinfo.len < (width * height) / 2) { mp_raise_ValueError(MP_ERROR_TEXT("map buffer too small")); } - } else { - self->map = NULL; } + // Only allocate after validation is finished. + layer_obj_t *self = mp_obj_malloc(layer_obj_t, type); + + self->width = width; + self->height = height; + self->x = 0; + self->y = 0; + self->frame = 0; + self->rotation = false; + self->graphic = graphic_bufinfo.buf; + self->palette = palette_bufinfo.buf; + self->map = map_bufinfo.buf; + return MP_OBJ_FROM_PTR(self); } diff --git a/shared-bindings/_stage/Text.c b/shared-bindings/_stage/Text.c index ecd4f644a78..0013ffb6697 100644 --- a/shared-bindings/_stage/Text.c +++ b/shared-bindings/_stage/Text.c @@ -38,32 +38,32 @@ static mp_obj_t text_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, 5, 5, false); - text_obj_t *self = mp_obj_malloc(text_obj_t, type); + mp_uint_t width = mp_arg_validate_int_min(mp_obj_get_int(args[0]), 0, MP_QSTR_width); + mp_uint_t height = mp_arg_validate_int_min(mp_obj_get_int(args[1]), 0, MP_QSTR_height); - self->width = mp_obj_get_int(args[0]); - self->height = mp_obj_get_int(args[1]); - self->x = 0; - self->y = 0; - - mp_buffer_info_t bufinfo; - mp_get_buffer_raise(args[2], &bufinfo, MP_BUFFER_READ); - self->font = bufinfo.buf; - if (bufinfo.len != 2048) { - mp_raise_ValueError(MP_ERROR_TEXT("font must be 2048 bytes long")); - } + mp_buffer_info_t font_bufinfo; + mp_get_buffer_raise(args[2], &font_bufinfo, MP_BUFFER_READ); + mp_arg_validate_length(font_bufinfo.len, 2048, MP_QSTR_font); - mp_get_buffer_raise(args[3], &bufinfo, MP_BUFFER_READ); - self->palette = bufinfo.buf; - if (bufinfo.len != 32) { - mp_raise_ValueError(MP_ERROR_TEXT("palette must be 32 bytes long")); - } + mp_buffer_info_t palette_bufinfo; + mp_get_buffer_raise(args[3], &palette_bufinfo, MP_BUFFER_READ); + mp_arg_validate_length(palette_bufinfo.len, 32, MP_QSTR_palette); - mp_get_buffer_raise(args[4], &bufinfo, MP_BUFFER_READ); - self->chars = bufinfo.buf; - if (bufinfo.len < self->width * self->height) { + mp_buffer_info_t chars_bufinfo; + mp_get_buffer_raise(args[4], &chars_bufinfo, MP_BUFFER_READ); + if (chars_bufinfo.len < width * height) { mp_raise_ValueError(MP_ERROR_TEXT("chars buffer too small")); } + text_obj_t *self = mp_obj_malloc(text_obj_t, type); + self->width = width; + self->height = height; + self->x = 0; + self->y = 0; + self->font = font_bufinfo.buf; + self->palette = palette_bufinfo.buf; + self->chars = chars_bufinfo.buf; + return MP_OBJ_FROM_PTR(self); } diff --git a/shared-bindings/adafruit_bus_device/i2c_device/I2CDevice.c b/shared-bindings/adafruit_bus_device/i2c_device/I2CDevice.c index 32d418923fb..5fb821ceade 100644 --- a/shared-bindings/adafruit_bus_device/i2c_device/I2CDevice.c +++ b/shared-bindings/adafruit_bus_device/i2c_device/I2CDevice.c @@ -47,8 +47,6 @@ //| ... //| static mp_obj_t adafruit_bus_device_i2cdevice_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { - adafruit_bus_device_i2cdevice_obj_t *self = - mp_obj_malloc(adafruit_bus_device_i2cdevice_obj_t, &adafruit_bus_device_i2cdevice_type); enum { ARG_i2c, ARG_device_address, ARG_probe }; static const mp_arg_t allowed_args[] = { { MP_QSTR_i2c, MP_ARG_REQUIRED | MP_ARG_OBJ }, @@ -60,12 +58,14 @@ static mp_obj_t adafruit_bus_device_i2cdevice_make_new(const mp_obj_type_t *type mp_obj_t *i2c = args[ARG_i2c].u_obj; + adafruit_bus_device_i2cdevice_obj_t *self = + mp_obj_malloc(adafruit_bus_device_i2cdevice_obj_t, &adafruit_bus_device_i2cdevice_type); 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) { common_hal_adafruit_bus_device_i2cdevice_probe_for_device(self); } - return (mp_obj_t)self; + return MP_OBJ_FROM_PTR(self); } //| def __enter__(self) -> I2CDevice: diff --git a/shared-bindings/adafruit_bus_device/spi_device/SPIDevice.c b/shared-bindings/adafruit_bus_device/spi_device/SPIDevice.c index f62aedc47e3..6f688a92997 100644 --- a/shared-bindings/adafruit_bus_device/spi_device/SPIDevice.c +++ b/shared-bindings/adafruit_bus_device/spi_device/SPIDevice.c @@ -24,6 +24,7 @@ //| spi: busio.SPI, //| chip_select: Optional[digitalio.DigitalInOut] = None, //| *, +//| cs_active_value: bool = False, //| baudrate: int = 100000, //| polarity: int = 0, //| phase: int = 0, @@ -34,7 +35,13 @@ //| //| :param ~busio.SPI spi: The SPI bus the device is on //| :param ~digitalio.DigitalInOut chip_select: The chip select pin object that implements the DigitalInOut API. ``None`` if a chip select pin is not being used. -//| :param bool cs_active_value: Set to true if your device requires CS to be active high. Defaults to false. +//| :param bool cs_active_value: Set to ``True`` if your device requires CS to be active high. Defaults to ``False``. +//| :param int baudrate: the desired clock rate in Hertz. The value is treated as a ceiling: +//| the actual clock rate may be lower due to the granularity of available clock settings, +//| but it will not exceed the given value. +//| :param int polarity: the base state of the clock line (0 or 1) +//| :param int phase: the edge of the clock that data is captured. First (0) +//| or second (1). Rising or falling depends on clock polarity. //| :param int extra_clocks: The minimum number of clock cycles to cycle the bus after CS is high. (Used for SD cards.) //| //| Example:: @@ -59,8 +66,6 @@ //| ... //| static mp_obj_t adafruit_bus_device_spidevice_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { - adafruit_bus_device_spidevice_obj_t *self = - mp_obj_malloc(adafruit_bus_device_spidevice_obj_t, &adafruit_bus_device_spidevice_type); enum { ARG_spi, ARG_chip_select, ARG_cs_active_value, ARG_baudrate, ARG_polarity, ARG_phase, ARG_extra_clocks }; static const mp_arg_t allowed_args[] = { { MP_QSTR_spi, MP_ARG_REQUIRED | MP_ARG_OBJ }, @@ -78,12 +83,11 @@ static mp_obj_t adafruit_bus_device_spidevice_make_new(const mp_obj_type_t *type mp_arg_validate_type_or_none(args[ARG_chip_select].u_obj, &digitalio_digitalinout_type, MP_QSTR_chip_select); - common_hal_adafruit_bus_device_spidevice_construct(MP_OBJ_TO_PTR(self), spi, args[ARG_chip_select].u_obj, args[ARG_cs_active_value].u_bool, args[ARG_baudrate].u_int, args[ARG_polarity].u_int, - args[ARG_phase].u_int, args[ARG_extra_clocks].u_int); - if (args[ARG_chip_select].u_obj != mp_const_none) { - digitalinout_result_t result = common_hal_digitalio_digitalinout_switch_to_output(MP_OBJ_TO_PTR(args[ARG_chip_select].u_obj), - true, DRIVE_MODE_PUSH_PULL); + digitalinout_result_t result = + common_hal_digitalio_digitalinout_switch_to_output(MP_OBJ_TO_PTR(args[ARG_chip_select].u_obj), + !args[ARG_cs_active_value].u_bool, + DRIVE_MODE_PUSH_PULL); #if CIRCUITPY_DIGITALIO_HAVE_INPUT_ONLY if (result == DIGITALINOUT_INPUT_ONLY) { mp_raise_NotImplementedError(MP_ERROR_TEXT("Pin is input only")); @@ -93,7 +97,19 @@ static mp_obj_t adafruit_bus_device_spidevice_make_new(const mp_obj_type_t *type #endif } - return (mp_obj_t)self; + adafruit_bus_device_spidevice_obj_t *self = + mp_obj_malloc(adafruit_bus_device_spidevice_obj_t, &adafruit_bus_device_spidevice_type); + common_hal_adafruit_bus_device_spidevice_construct(MP_OBJ_TO_PTR(self), + spi, + args[ARG_chip_select].u_obj, + args[ARG_cs_active_value].u_bool, + args[ARG_baudrate].u_int, + args[ARG_polarity].u_int, + args[ARG_phase].u_int, + args[ARG_extra_clocks].u_int); + + + return MP_OBJ_FROM_PTR(self); } //| def __enter__(self) -> busio.SPI: diff --git a/shared-bindings/adafruit_pixelbuf/PixelBuf.c b/shared-bindings/adafruit_pixelbuf/PixelBuf.c index cdffbfa627a..66cd8f738b9 100644 --- a/shared-bindings/adafruit_pixelbuf/PixelBuf.c +++ b/shared-bindings/adafruit_pixelbuf/PixelBuf.c @@ -24,14 +24,20 @@ #include "extmod/ulab/code/ndarray.h" #endif -static NORETURN void invalid_byteorder(void) { +static MP_NORETURN void invalid_byteorder(void) { mp_arg_error_invalid(MP_QSTR_byteorder); } 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.""" +//| """A fast RGB[W] pixel buffer for LED and similar devices. +//| +//| Subclasses must define ``_transmit(self, buffer)``, which `show()` +//| calls with a `bytearray` of the bytes to send: the header, the pixel +//| values, and the trailer. ``_transmit()`` is internal, for PixelBuf's +//| use only; user code shows pixels through `show()` and `auto_write`. +//| """ //| //| def __init__( //| self, diff --git a/shared-bindings/aesio/aes.c b/shared-bindings/aesio/aes.c index a6916042fda..eeb685a6652 100644 --- a/shared-bindings/aesio/aes.c +++ b/shared-bindings/aesio/aes.c @@ -55,8 +55,6 @@ static mp_obj_t aesio_aes_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { - aesio_aes_obj_t *self = mp_obj_malloc(aesio_aes_obj_t, &aesio_aes_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, {.u_obj = MP_OBJ_NULL} }, @@ -100,8 +98,14 @@ static mp_obj_t aesio_aes_make_new(const mp_obj_type_t *type, size_t n_args, iv = bufinfo.buf; } - common_hal_aesio_aes_construct(self, key, key_length, iv, mode, - args[ARG_counter].u_int); + int counter = 0; + if (args[ARG_counter].u_obj != MP_OBJ_NULL) { + counter = mp_obj_get_int_truncated(args[ARG_counter].u_obj); + } + + aesio_aes_obj_t *self = mp_obj_malloc(aesio_aes_obj_t, &aesio_aes_type); + common_hal_aesio_aes_construct(self, key, key_length, iv, mode, counter); + return MP_OBJ_FROM_PTR(self); } diff --git a/shared-bindings/alarm/SleepMemory.c b/shared-bindings/alarm/SleepMemory.c index d783983008c..383c2a4e613 100644 --- a/shared-bindings/alarm/SleepMemory.c +++ b/shared-bindings/alarm/SleepMemory.c @@ -12,16 +12,16 @@ #include "shared-bindings/alarm/SleepMemory.h" //| class SleepMemory: -//| """Store raw bytes in RAM that persists during deep sleep. +//| """Store raw bytes in RAM that persists across deep sleep and software resets. //| The class acts as a ``bytearray``. -//| If power is lost, the memory contents are lost. +//| Contents are preserved across ``microcontroller.reset()``, watchdog resets, +//| and deep sleep wake. Contents are lost when power is removed and restored, +//| or on brown-out reset. //| //| Note that this class can't be imported and used directly. The sole //| instance of :class:`SleepMemory` is available at //| :attr:`alarm.sleep_memory`. //| -//| **Limitations:** Not supported on RP2040. -//| //| Usage:: //| //| import alarm diff --git a/shared-bindings/alarm/__init__.c b/shared-bindings/alarm/__init__.c index e9f2db324d5..9f896541d68 100644 --- a/shared-bindings/alarm/__init__.c +++ b/shared-bindings/alarm/__init__.c @@ -122,6 +122,9 @@ MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(alarm_light_sleep_until_alarms_obj, 1, MP_OB //| //| If no alarms are specified, the microcontroller will deep sleep until reset. //| +//| You cannot initiate a deep sleep from the REPL. +//| You must call `exit_and_deep_sleep_until_alarms()` from a program file. +//| //| :param circuitpython_typing.Alarm alarms: the alarms that can wake the microcontroller. //| :param Sequence[digitalio.DigitalInOut] preserve_dios: A sequence of `DigitalInOut` objects //| whose state should be preserved during deep sleep. @@ -134,6 +137,8 @@ MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(alarm_light_sleep_until_alarms_obj, 1, MP_OB //| //| Preserving `DigitalInOut` states during deep sleep can be used to ensure that //| external or on-board devices are powered or unpowered during sleep, among other purposes. +//| Once the board wakes up from deep sleep, the `DigitalInOut` states are no longer preserved +//| and must be restored by your code. //| //| On some microcontrollers, some pins cannot remain in their original state for hardware reasons. //| @@ -151,6 +156,9 @@ MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(alarm_light_sleep_until_alarms_obj, 1, MP_OB //| the connection will be maintained and the system will not go into deep sleep.** //| 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 deep sleep. +//| When the alarm occurs, ``boot.py`` is not run again. A display set as +//| `supervisor.runtime.display ` stays in use, +//| so check that property before creating the display again. //| //| If CircuitPython goes into a true deep sleep, and USB or BLE is reconnected, //| the next deep sleep will still be a true deep sleep. You must do a hard reset @@ -190,6 +198,11 @@ static mp_obj_t alarm_exit_and_deep_sleep_until_alarms(size_t n_args, const mp_o mp_obj_t preserve_dios = args[ARG_preserve_dios].u_obj; const size_t num_dios = (size_t)MP_OBJ_SMALL_INT_VALUE(mp_obj_len(preserve_dios)); + #if !CIRCUITPY_ALARM_PRESERVE_DIOS + if (num_dios > 0) { + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_preserve_dios); + } + #endif digitalio_digitalinout_obj_t *dios_array[num_dios]; for (mp_uint_t i = 0; i < num_dios; i++) { diff --git a/shared-bindings/alarm/__init__.h b/shared-bindings/alarm/__init__.h index af92b381137..5b8823162cc 100644 --- a/shared-bindings/alarm/__init__.h +++ b/shared-bindings/alarm/__init__.h @@ -24,7 +24,14 @@ extern mp_obj_t common_hal_alarm_light_sleep_until_alarms(size_t n_alarms, const // 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, size_t n_dios, digitalio_digitalinout_obj_t **preserve_dios); -extern NORETURN void common_hal_alarm_enter_deep_sleep(void); +extern MP_NORETURN void common_hal_alarm_enter_deep_sleep(void); + +#if CIRCUITPY_ALARM_PRESERVE_DIOS +// Clear any pin preservations set up for deep sleep (real or fake), releasing +// held pins so they can be reset. Only declared on ports that implement +// `preserve_dios`. +extern void common_hal_alarm_clear_pin_preservations(void); +#endif // May be used to re-initialize peripherals like GPIO, if the VM reset returned // them to a default state diff --git a/shared-bindings/alarm/pin/PinAlarm.c b/shared-bindings/alarm/pin/PinAlarm.c index 8d93ca8d0de..1e4e9c348fc 100644 --- a/shared-bindings/alarm/pin/PinAlarm.c +++ b/shared-bindings/alarm/pin/PinAlarm.c @@ -38,11 +38,14 @@ //| that of ``value``. For instance, if ``value`` is set to ``True``, setting ``pull`` //| to ``True`` will enable a pull-down, to hold the pin low normally until an outside signal //| pulls it high. +//| +//| **Limitations:** On RP2xxx boards, the BOOTSEL button cannot be used as a PinAlarm for true deep sleep. +//| Using it to wake from deep sleep causes the board to restart into the UF2 +//| bootloader instead of CircuitPython. //| """ //| ... //| static mp_obj_t alarm_pin_pinalarm_make_new(const mp_obj_type_t *type, mp_uint_t n_args, size_t n_kw, const mp_obj_t *all_args) { - alarm_pin_pinalarm_obj_t *self = mp_obj_malloc(alarm_pin_pinalarm_obj_t, &alarm_pin_pinalarm_type); enum { ARG_pin, ARG_value, ARG_edge, ARG_pull }; static const mp_arg_t allowed_args[] = { { MP_QSTR_pin, MP_ARG_REQUIRED | MP_ARG_OBJ }, @@ -55,6 +58,7 @@ static mp_obj_t alarm_pin_pinalarm_make_new(const mp_obj_type_t *type, mp_uint_t const mcu_pin_obj_t *pin = validate_obj_is_free_pin(args[ARG_pin].u_obj, MP_QSTR_pin); + alarm_pin_pinalarm_obj_t *self = mp_obj_malloc(alarm_pin_pinalarm_obj_t, &alarm_pin_pinalarm_type); common_hal_alarm_pin_pinalarm_construct(self, pin, args[ARG_value].u_bool, diff --git a/shared-bindings/alarm/time/TimeAlarm.c b/shared-bindings/alarm/time/TimeAlarm.c index 0277c22fc44..6b8b25bc303 100644 --- a/shared-bindings/alarm/time/TimeAlarm.c +++ b/shared-bindings/alarm/time/TimeAlarm.c @@ -46,8 +46,6 @@ 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, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { - alarm_time_timealarm_obj_t *self = mp_obj_malloc(alarm_time_timealarm_obj_t, &alarm_time_timealarm_type); - enum { ARG_monotonic_time, ARG_epoch_time }; static const mp_arg_t allowed_args[] = { { MP_QSTR_monotonic_time, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, @@ -69,13 +67,13 @@ static mp_obj_t alarm_time_timealarm_make_new(const mp_obj_type_t *type, monotonic_time = mp_obj_get_float(args[ARG_monotonic_time].u_obj); } - mp_float_t monotonic_time_now = common_hal_time_monotonic_ms() / 1000.0; + mp_float_t monotonic_time_now = uint64_to_float(common_hal_time_monotonic_ms()) / MICROPY_FLOAT_CONST(1000.0); if (have_epoch) { #if MICROPY_LONGINT_IMPL == MICROPY_LONGINT_IMPL_NONE mp_raise_ValueError(MP_ERROR_TEXT("epoch_time not supported on this board")); #else - mp_uint_t epoch_time_secs = mp_obj_int_get_checked(args[ARG_epoch_time].u_obj); + mp_uint_t epoch_time_secs = mp_arg_validate_type_int(args[ARG_epoch_time].u_obj, MP_QSTR_epoch_time); timeutils_struct_time_t tm; struct_time_to_tm(rtc_get_time_source_time(), &tm); @@ -92,6 +90,7 @@ static mp_obj_t alarm_time_timealarm_make_new(const mp_obj_type_t *type, mp_raise_ValueError(MP_ERROR_TEXT("Time is in the past.")); } + alarm_time_timealarm_obj_t *self = mp_obj_malloc(alarm_time_timealarm_obj_t, &alarm_time_timealarm_type); common_hal_alarm_time_timealarm_construct(self, monotonic_time); return MP_OBJ_FROM_PTR(self); diff --git a/shared-bindings/alarm/touch/TouchAlarm.c b/shared-bindings/alarm/touch/TouchAlarm.c index f25e826cff0..09a27bfd29d 100644 --- a/shared-bindings/alarm/touch/TouchAlarm.c +++ b/shared-bindings/alarm/touch/TouchAlarm.c @@ -20,14 +20,12 @@ //| :param microcontroller.Pin pin: The pin to monitor. On some ports, the choice of pin //| may be limited due to hardware restrictions, particularly for deep-sleep alarms. //| -//| **Limitations:** Not available on SAMD, Nordic, or RP2040. +//| **Limitations:** Available only on Espressif ESP32, ESP32-S2, ESP32-S3, and ESP32-P4. //| """ //| ... //| static mp_obj_t alarm_touch_touchalarm_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { - alarm_touch_touchalarm_obj_t *self = mp_obj_malloc(alarm_touch_touchalarm_obj_t, &alarm_touch_touchalarm_type); - enum { ARG_pin }; static const mp_arg_t allowed_args[] = { { MP_QSTR_pin, MP_ARG_REQUIRED | MP_ARG_OBJ }, @@ -38,6 +36,7 @@ static mp_obj_t alarm_touch_touchalarm_make_new(const mp_obj_type_t *type, const mcu_pin_obj_t *pin = validate_obj_is_free_pin(args[ARG_pin].u_obj, MP_QSTR_pin); + alarm_touch_touchalarm_obj_t *self = mp_obj_malloc(alarm_touch_touchalarm_obj_t, &alarm_touch_touchalarm_type); common_hal_alarm_touch_touchalarm_construct(self, pin); return MP_OBJ_FROM_PTR(self); diff --git a/shared-bindings/analogbufio/BufferedIn.c b/shared-bindings/analogbufio/BufferedIn.c index 9a8483220cd..398823809b0 100644 --- a/shared-bindings/analogbufio/BufferedIn.c +++ b/shared-bindings/analogbufio/BufferedIn.c @@ -40,7 +40,12 @@ //| """Create a `BufferedIn` on the given pin and given sample rate. //| //| :param ~microcontroller.Pin pin: the pin to read from -//| :param ~int sample_rate: rate: sampling frequency, in samples per second""" +//| :param ~int sample_rate: rate: sampling frequency, in samples per second +//| +//| **Limitations**: On many boards with a CYW43 radio module, such as Pico W, +//| GPIO29 (often ``board.A3``) is also used to control the CYW43, +//| and is therefore not available to use as the `BufferedIn` pin. +//| """ //| ... //| static mp_obj_t analogbufio_bufferedin_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { @@ -55,10 +60,8 @@ static mp_obj_t analogbufio_bufferedin_make_new(const mp_obj_type_t *type, size_ // Validate Pin const mcu_pin_obj_t *pin = validate_obj_is_free_pin(args[ARG_pin].u_obj, MP_QSTR_pin); - // Create local object - analogbufio_bufferedin_obj_t *self = mp_obj_malloc_with_finaliser(analogbufio_bufferedin_obj_t, &analogbufio_bufferedin_type); - - // Call local interface in ports/common-hal/analogbufio + analogbufio_bufferedin_obj_t *self = + mp_obj_malloc_with_finaliser(analogbufio_bufferedin_obj_t, &analogbufio_bufferedin_type); common_hal_analogbufio_bufferedin_construct(self, pin, args[ARG_sample_rate].u_int); return MP_OBJ_FROM_PTR(self); @@ -123,7 +126,7 @@ static mp_obj_t analogbufio_bufferedin_obj_readinto(size_t n_args, const mp_obj_ mp_obj_t buffer = args[ARG_buffer].u_obj; // Buffer defined and allocated by user mp_buffer_info_t bufinfo; - mp_get_buffer_raise(buffer, &bufinfo, MP_BUFFER_READ); + mp_get_buffer_raise(buffer, &bufinfo, MP_BUFFER_WRITE); uint8_t bytes_per_sample = 1; if (bufinfo.typecode == 'H') { bytes_per_sample = 2; diff --git a/shared-bindings/analogio/AnalogIn.c b/shared-bindings/analogio/AnalogIn.c index b68b044ab52..9ea75fd7004 100644 --- a/shared-bindings/analogio/AnalogIn.c +++ b/shared-bindings/analogio/AnalogIn.c @@ -54,7 +54,7 @@ static mp_obj_t analogio_analogin_make_new(const mp_obj_type_t *type, // 1st argument is the pin const mcu_pin_obj_t *pin = common_hal_analogio_analogin_validate_pin(args[0]); - analogio_analogin_obj_t *self = mp_obj_malloc(analogio_analogin_obj_t, &analogio_analogin_type); + analogio_analogin_obj_t *self = mp_obj_malloc_with_finaliser(analogio_analogin_obj_t, &analogio_analogin_type); common_hal_analogio_analogin_construct(self, pin); return MP_OBJ_FROM_PTR(self); @@ -129,6 +129,7 @@ MP_PROPERTY_GETTER(analogio_analogin_reference_voltage_obj, static const mp_rom_map_elem_t analogio_analogin_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&analogio_analogin_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&analogio_analogin_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, { MP_ROM_QSTR(MP_QSTR_value), MP_ROM_PTR(&analogio_analogin_value_obj)}, diff --git a/shared-bindings/analogio/AnalogOut.c b/shared-bindings/analogio/AnalogOut.c index b9e5824f978..c6b27c7a560 100644 --- a/shared-bindings/analogio/AnalogOut.c +++ b/shared-bindings/analogio/AnalogOut.c @@ -18,8 +18,9 @@ //| class AnalogOut: //| """Output analog values (a specific voltage). //| -//| **Limitations:** Not available on Nordic, RP2040, Spresense, as there is no on-chip DAC. -//| On Espressif, available only on ESP32 and ESP32-S2; other chips do not have a DAC. +//| **Limitations:** Available only on chips with an on-chip DAC: +//| SAMD21, SAMD51, ESP32, ESP32-S2, STM32F405, STM32F407, and EFR32MG24. +//| On Zephyr-based boards, available only if the board defines a DAC. //| On ESP32-S2 boards, GPIO18 (DAC2) is often connected to a pull-up resistor, which causes //| `unexpected output values in the lower part of the output range //| `_. @@ -46,7 +47,7 @@ static mp_obj_t analogio_analogout_make_new(const mp_obj_type_t *type, mp_uint_t const mcu_pin_obj_t *pin = validate_obj_is_free_pin(args[0], MP_QSTR_pin); - analogio_analogout_obj_t *self = mp_obj_malloc(analogio_analogout_obj_t, &analogio_analogout_type); + analogio_analogout_obj_t *self = mp_obj_malloc_with_finaliser(analogio_analogout_obj_t, &analogio_analogout_type); common_hal_analogio_analogout_construct(self, pin); return MP_OBJ_FROM_PTR(self); @@ -104,6 +105,7 @@ MP_PROPERTY_GETSET(analogio_analogout_value_obj, static const mp_rom_map_elem_t analogio_analogout_locals_dict_table[] = { // instance methods { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&analogio_analogout_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&analogio_analogout_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, diff --git a/shared-bindings/async_spi/SPI.c b/shared-bindings/async_spi/SPI.c new file mode 100644 index 00000000000..577e2985746 --- /dev/null +++ b/shared-bindings/async_spi/SPI.c @@ -0,0 +1,287 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +#include + +#include "supervisor/shared/awaitable.h" +#include "py/objproperty.h" +#include "py/runtime.h" + +#include "shared/runtime/buffer_helper.h" +#include "shared/runtime/context_manager_helpers.h" +#include "shared-bindings/async_spi/SPI.h" +#include "shared-bindings/busio/SPI.h" + +#if !CIRCUITPY_BUSIO_SPI +#error "async_spi uses busio.SPI's argument tables" +#endif +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/util.h" + +//| class SPI: +//| """An SPI bus whose transfers are awaited +//| +//| ``write``, ``readinto`` and ``write_readinto`` return awaitables: the transfer runs while +//| other asyncio tasks run. Short transfers, and transfers that cannot use DMA (for example +//| from a buffer in flash), block other tasks until they finish. A transfer's arguments are +//| checked when the result is awaited. A transfer or ``configure()`` needs the bus's `lock` +//| held, so that a transaction of several transfers is not interleaved with another task's.""" +//| +//| def __init__( +//| self, +//| clock: microcontroller.Pin, +//| MOSI: Optional[microcontroller.Pin] = None, +//| MISO: Optional[microcontroller.Pin] = None, +//| ) -> None: +//| """Construct an SPI object on the given pins. +//| +//| :param ~microcontroller.Pin clock: the pin to use for the clock. +//| :param ~microcontroller.Pin MOSI: the Main Out Selected In pin. +//| :param ~microcontroller.Pin MISO: the Main In Selected Out pin.""" +//| ... +//| + +static mp_obj_t async_spi_spi_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_clock, ARG_MOSI, ARG_MISO }; + mp_arg_val_t args[3]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, 3, busio_spi_make_new_args, args); + + const mcu_pin_obj_t *clock = validate_obj_is_free_pin(args[ARG_clock].u_obj, MP_QSTR_clock); + const mcu_pin_obj_t *mosi = validate_obj_is_free_pin_or_none(args[ARG_MOSI].u_obj, MP_QSTR_MOSI); + const mcu_pin_obj_t *miso = validate_obj_is_free_pin_or_none(args[ARG_MISO].u_obj, MP_QSTR_MISO); + if (!miso && !mosi) { + mp_raise_ValueError(MP_ERROR_TEXT("Must provide MISO or MOSI pin")); + } + + async_spi_spi_obj_t *self = mp_obj_malloc_with_finaliser(async_spi_spi_obj_t, &async_spi_spi_type); + common_hal_async_spi_spi_construct(self, clock, mosi, miso); + return MP_OBJ_FROM_PTR(self); +} + +static MP_NOINLINE async_spi_spi_obj_t *checked_spi(mp_obj_t self_in) { + async_spi_spi_obj_t *self = MP_OBJ_TO_PTR(mp_arg_validate_type(self_in, &async_spi_spi_type, MP_QSTR_self)); + if (common_hal_async_spi_spi_deinited(self)) { + raise_deinited_error(); + } + return self; +} + +// For the calls that use the bus. +static MP_NOINLINE async_spi_spi_obj_t *locked_spi(mp_obj_t self_in) { + async_spi_spi_obj_t *self = checked_spi(self_in); + if (!circuitpy_async_lock_held(common_hal_async_spi_spi_get_lock(self))) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Function requires lock")); + } + return self; +} + +//| def deinit(self) -> None: +//| """Turn off the SPI bus. A transfer still running is stopped.""" +//| ... +//| +static mp_obj_t async_spi_spi_obj_deinit(mp_obj_t self_in) { + async_spi_spi_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_async_spi_spi_deinit(self); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(async_spi_spi_deinit_obj, async_spi_spi_obj_deinit); + +//| def __enter__(self) -> SPI: +//| """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.""" +//| ... +//| +// Provided by context manager helper. + +// The awaitable passes the object as mp_obj_t; the common-hal functions take it typed. +static mp_obj_t async_spi_spi_transfer_end(mp_obj_t self_in, void *context, circuitpy_async_flag_t *done) { + return common_hal_async_spi_spi_transfer_end(MP_OBJ_TO_PTR(self_in), context, done); +} +static void async_spi_spi_transfer_cancel(mp_obj_t self_in, void *context, circuitpy_async_flag_t *done) { + common_hal_async_spi_spi_transfer_cancel(MP_OBJ_TO_PTR(self_in), context, done); +} + +//| def configure( +//| self, *, baudrate: int = 100000, polarity: int = 0, phase: int = 0, bits: int = 8 +//| ) -> None: +//| """Configure the SPI bus, as `busio.SPI.configure`. Needs the `lock`.""" +//| ... +//| +static mp_obj_t async_spi_spi_configure(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_baudrate, ARG_polarity, ARG_phase, ARG_bits }; + async_spi_spi_obj_t *self = locked_spi(pos_args[0]); + mp_arg_val_t args[MP_ARRAY_SIZE(busio_spi_configure_args)]; + mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(busio_spi_configure_args), busio_spi_configure_args, args); + + uint8_t polarity = (uint8_t)mp_arg_validate_int_range(args[ARG_polarity].u_int, 0, 1, MP_QSTR_polarity); + uint8_t phase = (uint8_t)mp_arg_validate_int_range(args[ARG_phase].u_int, 0, 1, MP_QSTR_phase); + uint8_t bits = (uint8_t)mp_arg_validate_int_range(args[ARG_bits].u_int, 8, 9, MP_QSTR_bits); + + common_hal_async_spi_spi_configure(self, args[ARG_baudrate].u_int, polarity, phase, bits); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_KW(async_spi_spi_configure_obj, 1, async_spi_spi_configure); + +//| import sys +//| +//| async def write( +//| self, buffer: ReadableBuffer, *, start: int = 0, end: int = sys.maxsize +//| ) -> None: +//| """Write the data in ``buffer[start:end]``. +//| +//| :param ~circuitpython_typing.ReadableBuffer buffer: write out the data in this buffer +//| :param int start: beginning of buffer slice +//| :param int end: end of buffer slice; if not specified, use ``len(buffer)``""" +//| ... +//| +static void *async_spi_spi_write(circuitpy_async_flag_t *done, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_buffer, ARG_start, ARG_end }; + async_spi_spi_obj_t *self = locked_spi(pos_args[0]); + mp_arg_val_t args[MP_ARRAY_SIZE(busio_spi_write_args)]; + mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(busio_spi_write_args), busio_spi_write_args, args); + + size_t len; + uint8_t *data = buffer_slice(args[ARG_buffer].u_obj, args[ARG_start].u_int, args[ARG_end].u_int, + MP_BUFFER_READ, &len); + return common_hal_async_spi_spi_write_start(self, data, len, done); +} +static CIRCUITPY_DEFINE_ASYNC_FUN_OBJ_KW(async_spi_spi_write_obj, 1, async_spi_spi_write, + async_spi_spi_transfer_end, async_spi_spi_transfer_cancel); + +//| async def readinto( +//| self, +//| buffer: WriteableBuffer, +//| *, +//| start: int = 0, +//| end: int = sys.maxsize, +//| write_value: int = 0, +//| ) -> None: +//| """Read into ``buffer[start:end]`` while writing ``write_value`` for each byte read. +//| +//| :param ~circuitpython_typing.WriteableBuffer buffer: read data into this buffer +//| :param int start: beginning of buffer slice +//| :param int end: end of buffer slice; if not specified, use ``len(buffer)`` +//| :param int write_value: value to write while reading""" +//| ... +//| +static void *async_spi_spi_readinto(circuitpy_async_flag_t *done, 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 }; + async_spi_spi_obj_t *self = locked_spi(pos_args[0]); + mp_arg_val_t args[MP_ARRAY_SIZE(busio_spi_readinto_args)]; + mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(busio_spi_readinto_args), busio_spi_readinto_args, args); + + size_t len; + uint8_t *data = buffer_slice(args[ARG_buffer].u_obj, args[ARG_start].u_int, args[ARG_end].u_int, + MP_BUFFER_WRITE, &len); + return common_hal_async_spi_spi_readinto_start(self, data, len, (uint8_t)args[ARG_write_value].u_int, done); +} +static CIRCUITPY_DEFINE_ASYNC_FUN_OBJ_KW(async_spi_spi_readinto_obj, 1, async_spi_spi_readinto, + async_spi_spi_transfer_end, async_spi_spi_transfer_cancel); + +//| async def write_readinto( +//| self, +//| out_buffer: ReadableBuffer, +//| in_buffer: WriteableBuffer, +//| *, +//| out_start: int = 0, +//| out_end: int = sys.maxsize, +//| in_start: int = 0, +//| in_end: int = sys.maxsize, +//| ) -> None: +//| """Write out the data in ``out_buffer`` while simultaneously reading data into ``in_buffer``. +//| The two slices must have the same length. +//| +//| :param ~circuitpython_typing.ReadableBuffer out_buffer: write out the data in this buffer +//| :param ~circuitpython_typing.WriteableBuffer in_buffer: read data into this buffer +//| :param int out_start: beginning of ``out_buffer`` slice +//| :param int out_end: end of ``out_buffer`` slice; if not specified, use ``len(out_buffer)`` +//| :param int in_start: beginning of ``in_buffer`` slice +//| :param int in_end: end of ``in_buffer`` slice; if not specified, use ``len(in_buffer)``""" +//| ... +//| +static void *async_spi_spi_write_readinto(circuitpy_async_flag_t *done, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_out_buffer, ARG_in_buffer, ARG_out_start, ARG_out_end, ARG_in_start, ARG_in_end }; + async_spi_spi_obj_t *self = locked_spi(pos_args[0]); + mp_arg_val_t args[MP_ARRAY_SIZE(busio_spi_write_readinto_args)]; + mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(busio_spi_write_readinto_args), busio_spi_write_readinto_args, args); + + size_t out_len, in_len; + const uint8_t *data_out = buffer_slice(args[ARG_out_buffer].u_obj, args[ARG_out_start].u_int, + args[ARG_out_end].u_int, MP_BUFFER_READ, &out_len); + uint8_t *data_in = buffer_slice(args[ARG_in_buffer].u_obj, args[ARG_in_start].u_int, + args[ARG_in_end].u_int, MP_BUFFER_WRITE, &in_len); + if (out_len != in_len) { + mp_raise_ValueError(MP_ERROR_TEXT("buffer slices must be of equal length")); + } + return common_hal_async_spi_spi_write_readinto_start(self, data_out, data_in, out_len, done); +} +static CIRCUITPY_DEFINE_ASYNC_FUN_OBJ_KW(async_spi_spi_write_readinto_obj, 2, async_spi_spi_write_readinto, + async_spi_spi_transfer_end, async_spi_spi_transfer_cancel); + +//| frequency: int +//| """The actual SPI bus frequency. This may not match the frequency requested +//| due to internal limitations.""" +//| +//| +static mp_obj_t async_spi_spi_get_frequency(mp_obj_t self_in) { + async_spi_spi_obj_t *self = checked_spi(self_in); + return MP_OBJ_NEW_SMALL_INT(common_hal_async_spi_spi_get_frequency(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(async_spi_spi_get_frequency_obj, async_spi_spi_get_frequency); + +MP_PROPERTY_GETTER(async_spi_spi_frequency_obj, + (mp_obj_t)&async_spi_spi_get_frequency_obj); + +//| lock: Lock +//| """The bus's lock. Hold it around a transaction. +//| +//| For example:: +//| +//| async with spi.lock: +//| spi.configure(baudrate=8_000_000) +//| await spi.write(command) +//| await spi.readinto(reply) +//| """ +//| +static mp_obj_t async_spi_spi_get_lock(mp_obj_t self_in) { + async_spi_spi_obj_t *self = checked_spi(self_in); + return MP_OBJ_FROM_PTR(common_hal_async_spi_spi_get_lock(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(async_spi_spi_get_lock_obj, async_spi_spi_get_lock); + +MP_PROPERTY_GETTER(async_spi_spi_lock_obj, + (mp_obj_t)&async_spi_spi_get_lock_obj); + +static const mp_rom_map_elem_t async_spi_spi_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&async_spi_spi_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&async_spi_spi_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, + + { MP_ROM_QSTR(MP_QSTR_configure), MP_ROM_PTR(&async_spi_spi_configure_obj) }, + + { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&async_spi_spi_write_obj) }, + { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&async_spi_spi_readinto_obj) }, + { MP_ROM_QSTR(MP_QSTR_write_readinto), MP_ROM_PTR(&async_spi_spi_write_readinto_obj) }, + + { MP_ROM_QSTR(MP_QSTR_frequency), MP_ROM_PTR(&async_spi_spi_frequency_obj) }, + { MP_ROM_QSTR(MP_QSTR_lock), MP_ROM_PTR(&async_spi_spi_lock_obj) }, +}; +static MP_DEFINE_CONST_DICT(async_spi_spi_locals_dict, async_spi_spi_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + async_spi_spi_type, + MP_QSTR_SPI, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, async_spi_spi_make_new, + locals_dict, &async_spi_spi_locals_dict + ); diff --git a/shared-bindings/async_spi/SPI.h b/shared-bindings/async_spi/SPI.h new file mode 100644 index 00000000000..35a2d6c4519 --- /dev/null +++ b/shared-bindings/async_spi/SPI.h @@ -0,0 +1,53 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" +#include "py/runtime.h" +#include "common-hal/async_spi/SPI.h" +#include "common-hal/microcontroller/Pin.h" +#include "supervisor/shared/async_flag.h" + +extern const mp_obj_type_t async_spi_spi_type; + +void common_hal_async_spi_spi_construct(async_spi_spi_obj_t *self, const mcu_pin_obj_t *clock, + const mcu_pin_obj_t *mosi, const mcu_pin_obj_t *miso); +bool common_hal_async_spi_spi_deinited(async_spi_spi_obj_t *self); +// Stops a running transfer. +void common_hal_async_spi_spi_deinit(async_spi_spi_obj_t *self); +// For busio.SPI built on this implementation (shared-module/busio/SPI.c). +void common_hal_async_spi_spi_mark_deinit(async_spi_spi_obj_t *self); +uint32_t common_hal_async_spi_spi_get_frequency(async_spi_spi_obj_t *self); +circuitpy_async_lock_obj_t *common_hal_async_spi_spi_get_lock(async_spi_spi_obj_t *self); +uint8_t common_hal_async_spi_spi_get_polarity(async_spi_spi_obj_t *self); +uint8_t common_hal_async_spi_spi_get_phase(async_spi_spi_obj_t *self); + +// Each start returns a context for state of that one operation, which end() and cancel() get +// back; NULL when the object holds the state. + +// Applies the settings. The caller holds the lock, so no transfer is running. +void common_hal_async_spi_spi_configure(async_spi_spi_obj_t *self, uint32_t baudrate, + uint8_t polarity, uint8_t phase, uint8_t bits); + +// Each transfer start sets done once the transfer has finished, possibly from an interrupt. The +// buffers must stay valid until done is set. transfer_end() and transfer_cancel() act only on +// the transfer started with done. +void *common_hal_async_spi_spi_write_start(async_spi_spi_obj_t *self, const uint8_t *data, + size_t len, circuitpy_async_flag_t *done); +void *common_hal_async_spi_spi_readinto_start(async_spi_spi_obj_t *self, uint8_t *data, + size_t len, uint8_t write_value, circuitpy_async_flag_t *done); +void *common_hal_async_spi_spi_write_readinto_start(async_spi_spi_obj_t *self, + const uint8_t *data_out, uint8_t *data_in, size_t len, circuitpy_async_flag_t *done); +// Finishes the transfer started with done, once done is set; false if the driver reported an +// error. For busio.SPI, which must not raise from a background callback. +bool common_hal_async_spi_spi_transfer_finish(async_spi_spi_obj_t *self, void *context, + circuitpy_async_flag_t *done); +// The same for an await: raises on an error. +mp_obj_t common_hal_async_spi_spi_transfer_end(async_spi_spi_obj_t *self, void *context, + circuitpy_async_flag_t *done); +void common_hal_async_spi_spi_transfer_cancel(async_spi_spi_obj_t *self, void *context, + circuitpy_async_flag_t *done); diff --git a/shared-bindings/async_spi/__init__.c b/shared-bindings/async_spi/__init__.c new file mode 100644 index 00000000000..7580025c05b --- /dev/null +++ b/shared-bindings/async_spi/__init__.c @@ -0,0 +1,60 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +#include "py/obj.h" +#include "py/runtime.h" + +#include "shared-bindings/async_spi/SPI.h" +#include "supervisor/shared/awaitable.h" + +//| """SPI transfers for asyncio +//| +//| `async_spi.SPI` is an SPI bus whose transfers are awaited. While a transfer runs, other +//| asyncio tasks run too. +//| +//| .. code-block:: python +//| +//| import asyncio +//| import board +//| import async_spi +//| +//| async def main(): +//| spi = async_spi.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO) +//| data = bytearray(512) +//| async with spi.lock: +//| spi.configure(baudrate=8_000_000) +//| await spi.readinto(data) +//| +//| asyncio.run(main()) +//| """ +//| +//| class Lock: +//| """A bus lock for asyncio code, used as ``async with bus.lock:``. Tasks waiting for it +//| get it in the order they asked; a task cancelled while waiting leaves the line.""" +//| +//| async def __aenter__(self) -> Lock: +//| """Waits for the lock and takes it.""" +//| ... +//| +//| def __aexit__(self) -> None: +//| """Hands the lock to the next task waiting, or releases it.""" +//| ... +//| + +static const mp_rom_map_elem_t async_spi_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_async_spi) }, + { MP_ROM_QSTR(MP_QSTR_SPI), MP_ROM_PTR(&async_spi_spi_type) }, + { MP_ROM_QSTR(MP_QSTR_Lock), MP_ROM_PTR(&circuitpy_async_lock_type) }, +}; + +static MP_DEFINE_CONST_DICT(async_spi_module_globals, async_spi_module_globals_table); + +const mp_obj_module_t async_spi_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&async_spi_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_async_spi, async_spi_module); diff --git a/shared-bindings/audiobusio/I2SOut.c b/shared-bindings/audiobusio/I2SOut.c index 9aaf7421c65..7769352a1da 100644 --- a/shared-bindings/audiobusio/I2SOut.c +++ b/shared-bindings/audiobusio/I2SOut.c @@ -25,6 +25,7 @@ //| *, //| main_clock: Optional[microcontroller.Pin] = None, //| left_justified: bool = False, +//| external_clock: bool = False, //| ) -> None: //| """Create a I2SOut object associated with the given pins. //| @@ -34,6 +35,15 @@ //| :param ~microcontroller.Pin main_clock: The main clock pin //| :param bool left_justified: True when data bits are aligned with the word select clock. False //| when they are shifted by one to match classic I2S protocol. +//| :param bool external_clock: True when this object follows an externally supplied clock: +//| ``bit_clock`` and ``word_select`` are inputs driven by something else, another I2S +//| object (the clock source), or a codec, rather than generated by this object. Not +//| supported on all ports. +//| +//| In external clock mode ``bit_clock`` and ``word_select`` do not have to be sequential +//| GPIOs, and they may be shared with another I2S object. `play` cannot retime the bus, so +//| the sample's ``sample_rate`` must equal the external frame rate or the pitch will be +//| wrong. If the incoming clock stops, output stalls with its last sample held. //| //| Simple 8ksps 440 Hz sine wave on `Metro M0 Express `_ //| using `UDA1334 Breakout `_:: @@ -82,24 +92,35 @@ static mp_obj_t audiobusio_i2sout_make_new(const mp_obj_type_t *type, size_t n_a mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_I2SOut); return NULL; // Not reachable. #else - enum { ARG_bit_clock, ARG_word_select, ARG_data, ARG_main_clock, ARG_left_justified }; + enum { ARG_bit_clock, ARG_word_select, ARG_data, ARG_main_clock, ARG_left_justified, ARG_external_clock }; static const mp_arg_t allowed_args[] = { { MP_QSTR_bit_clock, MP_ARG_OBJ | MP_ARG_REQUIRED }, { MP_QSTR_word_select, MP_ARG_OBJ | MP_ARG_REQUIRED }, { MP_QSTR_data, MP_ARG_OBJ | MP_ARG_REQUIRED }, { MP_QSTR_main_clock, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = mp_const_none} }, - { MP_QSTR_left_justified, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_bool = false} }, + { MP_QSTR_left_justified, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = false} }, + { MP_QSTR_external_clock, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = false} }, }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); - const mcu_pin_obj_t *bit_clock = validate_obj_is_free_pin(args[ARG_bit_clock].u_obj, MP_QSTR_bit_clock); - const mcu_pin_obj_t *word_select = validate_obj_is_free_pin(args[ARG_word_select].u_obj, MP_QSTR_word_select); + bool external_clock = args[ARG_external_clock].u_bool; + + // In external clock mode the clock pins are only read, so they may already + // be owned by whatever is driving them; let the port decide if the sharing + // is legal. + const mcu_pin_obj_t *bit_clock = external_clock + ? validate_obj_is_pin(args[ARG_bit_clock].u_obj, MP_QSTR_bit_clock) + : validate_obj_is_free_pin(args[ARG_bit_clock].u_obj, MP_QSTR_bit_clock); + const mcu_pin_obj_t *word_select = external_clock + ? validate_obj_is_pin(args[ARG_word_select].u_obj, MP_QSTR_word_select) + : validate_obj_is_free_pin(args[ARG_word_select].u_obj, MP_QSTR_word_select); const mcu_pin_obj_t *data = validate_obj_is_free_pin(args[ARG_data].u_obj, MP_QSTR_data); const mcu_pin_obj_t *main_clock = validate_obj_is_free_pin_or_none(args[ARG_main_clock].u_obj, MP_QSTR_main_clock); audiobusio_i2sout_obj_t *self = mp_obj_malloc_with_finaliser(audiobusio_i2sout_obj_t, &audiobusio_i2sout_type); - common_hal_audiobusio_i2sout_construct(self, bit_clock, word_select, data, main_clock, args[ARG_left_justified].u_bool); + common_hal_audiobusio_i2sout_construct(self, bit_clock, word_select, data, main_clock, + args[ARG_left_justified].u_bool, external_clock); return MP_OBJ_FROM_PTR(self); #endif @@ -144,6 +165,8 @@ static void check_for_deinit(audiobusio_i2sout_obj_t *self) { //| //| Sample must be an `audiocore.WaveFile`, `audiocore.RawSample`, `audiomixer.Mixer` or `audiomp3.MP3Decoder`. //| +//| Mono samples will be converted to stereo by copying value to both the left channel and the right channel. +//| //| The sample itself should consist of 8 bit or 16 bit samples.""" //| ... //| diff --git a/shared-bindings/audiobusio/I2SOut.h b/shared-bindings/audiobusio/I2SOut.h index a53997ef91b..bc3c944b08d 100644 --- a/shared-bindings/audiobusio/I2SOut.h +++ b/shared-bindings/audiobusio/I2SOut.h @@ -16,7 +16,7 @@ extern const mp_obj_type_t audiobusio_i2sout_type; 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, - const mcu_pin_obj_t *main_clock, bool left_justified); + const mcu_pin_obj_t *main_clock, bool left_justified, bool external_clock); void common_hal_audiobusio_i2sout_deinit(audiobusio_i2sout_obj_t *self); bool common_hal_audiobusio_i2sout_deinited(audiobusio_i2sout_obj_t *self); diff --git a/shared-bindings/audiobusio/PDMIn.c b/shared-bindings/audiobusio/PDMIn.c index 2a3fd3540c3..b4289ed1313 100644 --- a/shared-bindings/audiobusio/PDMIn.c +++ b/shared-bindings/audiobusio/PDMIn.c @@ -11,6 +11,7 @@ #include "py/mphal.h" #include "py/objproperty.h" #include "py/runtime.h" +#include "extmod/vfs.h" #include "shared-bindings/microcontroller/Pin.h" #include "shared-bindings/audiobusio/PDMIn.h" #include "shared-bindings/util.h" @@ -46,9 +47,9 @@ //| to allow microphone to turn on. Most require only 0.01s; some require 0.1s. Longer is safer. //| Must be in range 0.0-1.0 seconds. //| -//| **Limitations:** On SAMD and RP2040, supports only 8 or 16 bit mono input, with 64x oversampling. +//| **Limitations:** On SAMD and RP2xxx, supports only 8 or 16 bit mono input, with 64x oversampling. //| On nRF52840, supports only 16 bit mono input at 16 kHz; oversampling is fixed at 64x. Not provided -//| on nRF52833 for space reasons. Not available on Espressif. +//| on nRF52833 for space reasons. On Espressif, only available on ESP32, ESP32-S3, and ESP32-P4. //| //| For example, to record 8-bit unsigned samples to a buffer:: //| @@ -96,18 +97,17 @@ static mp_obj_t audiobusio_pdmin_make_new(const mp_obj_type_t *type, size_t n_ar const mcu_pin_obj_t *clock_pin = validate_obj_is_free_pin(args[ARG_clock_pin].u_obj, MP_QSTR_clock_pin); const mcu_pin_obj_t *data_pin = validate_obj_is_free_pin(args[ARG_data_pin].u_obj, MP_QSTR_data_pin); - // create PDMIn object from the given pin - audiobusio_pdmin_obj_t *self = mp_obj_malloc_with_finaliser(audiobusio_pdmin_obj_t, &audiobusio_pdmin_type); - - uint32_t sample_rate = args[ARG_sample_rate].u_int; - uint8_t bit_depth = args[ARG_bit_depth].u_int; - if (bit_depth % 8 != 0) { + uint32_t sample_rate = mp_arg_validate_int_min(args[ARG_sample_rate].u_int, 1, MP_QSTR_sample_rate); + mp_int_t requested_bit_depth = args[ARG_bit_depth].u_int; + if (requested_bit_depth != 8 && requested_bit_depth != 16) { mp_raise_ValueError_varg(MP_ERROR_TEXT("%q must be multiple of 8."), MP_QSTR_bit_depth); } - uint8_t oversample = args[ARG_oversample].u_int; - if (oversample % 8 != 0) { + uint8_t bit_depth = requested_bit_depth; + mp_int_t requested_oversample = args[ARG_oversample].u_int; + if (requested_oversample < 8 || requested_oversample > 255 || requested_oversample % 8 != 0) { mp_raise_ValueError_varg(MP_ERROR_TEXT("%q must be multiple of 8."), MP_QSTR_oversample); } + uint8_t oversample = requested_oversample; bool mono = args[ARG_mono].u_bool; mp_float_t startup_delay = (args[ARG_startup_delay].u_obj == MP_OBJ_NULL) @@ -115,6 +115,7 @@ static mp_obj_t audiobusio_pdmin_make_new(const mp_obj_type_t *type, size_t n_ar : mp_obj_get_float(args[ARG_startup_delay].u_obj); mp_arg_validate_float_range(startup_delay, 0.0f, 1.0f, MP_QSTR_startup_delay); + audiobusio_pdmin_obj_t *self = mp_obj_malloc_with_finaliser(audiobusio_pdmin_obj_t, &audiobusio_pdmin_type); common_hal_audiobusio_pdmin_construct(self, clock_pin, data_pin, sample_rate, bit_depth, mono, oversample); @@ -155,11 +156,11 @@ static void check_for_deinit(audiobusio_pdmin_obj_t *self) { // Provided by context manager helper. -//| def record(self, destination: WriteableBuffer, destination_length: int) -> None: +//| def record(self, destination: WriteableBuffer, destination_length: int) -> int: //| """Records destination_length bytes of samples to destination. This is //| blocking. //| -//| An IOError may be raised when the destination is too slow to record the +//| An OSError may be raised when the destination is too slow to record the //| audio at the given rate. For internal flash, writing all 1s to the file //| before recording is recommended to speed up writes. //| @@ -174,24 +175,24 @@ static mp_obj_t audiobusio_pdmin_obj_record(mp_obj_t self_obj, mp_obj_t destinat mp_arg_validate_length_min(length, 0, MP_QSTR_length); mp_buffer_info_t bufinfo; - if (mp_obj_is_type(destination, &mp_type_fileio)) { + if (mp_obj_is_fileio(destination)) { mp_raise_NotImplementedError(MP_ERROR_TEXT("Cannot record to a file")); - } else if (mp_get_buffer(destination, &bufinfo, MP_BUFFER_WRITE)) { - if (bufinfo.len / mp_binary_get_size('@', bufinfo.typecode, NULL) < length) { - mp_raise_ValueError(MP_ERROR_TEXT("Destination capacity is smaller than destination_length.")); - } - uint8_t bit_depth = common_hal_audiobusio_pdmin_get_bit_depth(self); - if (bufinfo.typecode != 'H' && bit_depth == 16) { - mp_raise_ValueError(MP_ERROR_TEXT("destination buffer must be an array of type 'H' for bit_depth = 16")); - } else if (bufinfo.typecode != 'B' && bufinfo.typecode != BYTEARRAY_TYPECODE && bit_depth == 8) { - mp_raise_ValueError(MP_ERROR_TEXT("destination buffer must be a bytearray or array of type 'B' for bit_depth = 8")); - } - // length is the buffer length in slots, not bytes. - uint32_t length_written = - common_hal_audiobusio_pdmin_record_to_buffer(self, bufinfo.buf, length); - return MP_OBJ_NEW_SMALL_INT(length_written); } - return mp_const_none; + + mp_get_buffer_raise(destination, &bufinfo, MP_BUFFER_WRITE); + if (bufinfo.len / mp_binary_get_size('@', bufinfo.typecode, NULL) < length) { + mp_raise_ValueError(MP_ERROR_TEXT("Destination capacity is smaller than destination_length.")); + } + uint8_t bit_depth = common_hal_audiobusio_pdmin_get_bit_depth(self); + if (bufinfo.typecode != 'H' && bit_depth == 16) { + mp_raise_ValueError(MP_ERROR_TEXT("destination buffer must be an array of type 'H' for bit_depth = 16")); + } else if (bufinfo.typecode != 'B' && bufinfo.typecode != BYTEARRAY_TYPECODE && bit_depth == 8) { + mp_raise_ValueError(MP_ERROR_TEXT("destination buffer must be a bytearray or array of type 'B' for bit_depth = 8")); + } + // length is the buffer length in slots, not bytes. + uint32_t length_written = + common_hal_audiobusio_pdmin_record_to_buffer(self, bufinfo.buf, length); + return MP_OBJ_NEW_SMALL_INT(length_written); } MP_DEFINE_CONST_FUN_OBJ_3(audiobusio_pdmin_record_obj, audiobusio_pdmin_obj_record); diff --git a/shared-bindings/audiocore/RawSample.c b/shared-bindings/audiocore/RawSample.c index 30c1d1ad600..7c3fcbb3263 100644 --- a/shared-bindings/audiocore/RawSample.c +++ b/shared-bindings/audiocore/RawSample.c @@ -89,8 +89,8 @@ static mp_obj_t audioio_rawsample_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_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + mp_arg_validate_int_min(args[ARG_sample_rate].u_int, 1, MP_QSTR_sample_rate); - audioio_rawsample_obj_t *self = mp_obj_malloc(audioio_rawsample_obj_t, &audioio_rawsample_type); mp_buffer_info_t bufinfo; mp_get_buffer_raise(args[ARG_buffer].u_obj, &bufinfo, MP_BUFFER_READ); uint8_t bytes_per_sample = 1; @@ -103,9 +103,16 @@ static mp_obj_t audioio_rawsample_make_new(const mp_obj_type_t *type, size_t n_a if (!args[ARG_single_buffer].u_bool && bufinfo.len % (bytes_per_sample * args[ARG_channel_count].u_int * 2) != 0) { mp_raise_ValueError_varg(MP_ERROR_TEXT("Length of %q must be an even multiple of channel_count * type_size"), MP_QSTR_buffer); } - 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, args[ARG_single_buffer].u_bool); + + audioio_rawsample_obj_t *self = mp_obj_malloc_with_finaliser(audioio_rawsample_obj_t, &audioio_rawsample_type); + 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, + args[ARG_single_buffer].u_bool); return MP_OBJ_FROM_PTR(self); } @@ -145,6 +152,7 @@ static MP_DEFINE_CONST_FUN_OBJ_1(audioio_rawsample_deinit_obj, audioio_rawsample static const mp_rom_map_elem_t audioio_rawsample_locals_dict_table[] = { // Methods { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&audioio_rawsample_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&audioio_rawsample_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, diff --git a/shared-bindings/audiocore/WaveFile.c b/shared-bindings/audiocore/WaveFile.c index 4ba7d24bfd2..cba1a9adbfc 100644 --- a/shared-bindings/audiocore/WaveFile.c +++ b/shared-bindings/audiocore/WaveFile.c @@ -12,7 +12,7 @@ #include "shared-bindings/audiocore/WaveFile.h" #include "shared-bindings/audiocore/__init__.h" #include "shared-bindings/util.h" -#include "extmod/vfs_posix.h" +#include "extmod/vfs.h" //| class WaveFile: //| """Load a wave file for audio playback @@ -27,7 +27,8 @@ //| :param Union[str, typing.BinaryIO] file: The name of a wave file (preferred) or an already opened wave file //| :param ~circuitpython_typing.WriteableBuffer buffer: Optional pre-allocated buffer, //| that will be split in half and used for double-buffering of the data. -//| The buffer must be 8 to 1024 bytes long. +//| The buffer must be 8 to 1024 bytes long and a multiple of 8 bytes, so that each half +//| holds a whole number of 32-bit words. //| If not provided, two 256 byte buffers are initially allocated internally. //| //| Playing a wave file from flash:: @@ -60,10 +61,6 @@ static mp_obj_t audioio_wavefile_make_new(const mp_obj_type_t *type, size_t n_ar arg = mp_call_function_2(MP_OBJ_FROM_PTR(&mp_builtin_open_obj), arg, MP_ROM_QSTR(MP_QSTR_rb)); } - audioio_wavefile_obj_t *self = mp_obj_malloc(audioio_wavefile_obj_t, &audioio_wavefile_type); - if (!mp_obj_is_type(arg, &mp_type_vfs_fat_fileio)) { - mp_raise_TypeError(MP_ERROR_TEXT("file must be a file opened in byte mode")); - } uint8_t *buffer = NULL; size_t buffer_size = 0; if (n_args >= 2) { @@ -71,8 +68,13 @@ static mp_obj_t audioio_wavefile_make_new(const mp_obj_type_t *type, size_t n_ar mp_get_buffer_raise(args[1], &bufinfo, MP_BUFFER_WRITE); buffer = bufinfo.buf; buffer_size = mp_arg_validate_length_range(bufinfo.len, 8, 1024, MP_QSTR_buffer); + if (buffer_size % 8 != 0) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("Buffer must be a multiple of %d bytes"), 8); + } } - common_hal_audioio_wavefile_construct(self, MP_OBJ_TO_PTR(arg), + + audioio_wavefile_obj_t *self = mp_obj_malloc_with_finaliser(audioio_wavefile_obj_t, &audioio_wavefile_type); + common_hal_audioio_wavefile_construct(self, arg, buffer, buffer_size); return MP_OBJ_FROM_PTR(self); @@ -118,6 +120,7 @@ static MP_DEFINE_CONST_FUN_OBJ_1(audioio_wavefile_deinit_obj, audioio_wavefile_d static const mp_rom_map_elem_t audioio_wavefile_locals_dict_table[] = { // Methods { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&audioio_wavefile_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&audioio_wavefile_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, diff --git a/shared-bindings/audiocore/WaveFile.h b/shared-bindings/audiocore/WaveFile.h index 5249959a1cc..4a1b6e1436e 100644 --- a/shared-bindings/audiocore/WaveFile.h +++ b/shared-bindings/audiocore/WaveFile.h @@ -7,13 +7,12 @@ #pragma once #include "py/obj.h" -#include "extmod/vfs_fat.h" #include "shared-module/audiocore/WaveFile.h" 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); + mp_obj_t file, uint8_t *buffer, size_t buffer_size); void common_hal_audioio_wavefile_deinit(audioio_wavefile_obj_t *self); diff --git a/shared-bindings/audiocore/__init__.c b/shared-bindings/audiocore/__init__.c index 5cd1fd83f22..2dadc8877f9 100644 --- a/shared-bindings/audiocore/__init__.c +++ b/shared-bindings/audiocore/__init__.c @@ -39,7 +39,7 @@ static mp_obj_t audiocore_get_buffer(mp_obj_t sample_in) { uint8_t bits_per_sample = audiosample_get_bits_per_sample(sample); audiosample_get_buffer_structure(sample, false, &single_buffer, &samples_signed, &max_buffer_length, &spacing); // copies the data because the gc semantics of get_buffer are unclear - void *result_buf = m_malloc(buffer_length); + void *result_buf = m_malloc_without_collect(buffer_length); memcpy(result_buf, buffer, buffer_length); char typecode = (bits_per_sample == 8 && samples_signed) ? 'b' : @@ -145,7 +145,8 @@ MP_DEFINE_CONST_FUN_OBJ_1(audiosample_get_sample_rate_obj, audiosample_obj_get_s static mp_obj_t audiosample_obj_set_sample_rate(mp_obj_t self_in, mp_obj_t sample_rate) { audiosample_base_t *self = MP_OBJ_TO_PTR(self_in); audiosample_check_for_deinit(self); - audiosample_set_sample_rate(audiosample_check(self_in), mp_obj_get_int(sample_rate)); + audiosample_set_sample_rate(audiosample_check(self_in), + (uint32_t)mp_arg_validate_int_min(mp_obj_get_int(sample_rate), 1, MP_QSTR_sample_rate)); return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_2(audiosample_set_sample_rate_obj, audiosample_obj_set_sample_rate); diff --git a/shared-bindings/audiodelays/Chorus.c b/shared-bindings/audiodelays/Chorus.c new file mode 100644 index 00000000000..a08c85241d9 --- /dev/null +++ b/shared-bindings/audiodelays/Chorus.c @@ -0,0 +1,283 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Mark Komus +// +// SPDX-License-Identifier: MIT + +#include + +#include "shared-bindings/audiodelays/Chorus.h" +#include "shared-module/audiodelays/Chorus.h" +#include "shared-bindings/audiocore/__init__.h" + +#include "shared/runtime/context_manager_helpers.h" +#include "py/binary.h" +#include "py/objproperty.h" +#include "py/runtime.h" +#include "shared-bindings/util.h" +#include "shared-module/synthio/block.h" + +//| class Chorus: +//| """An Chorus effect""" +//| +//| def __init__( +//| self, +//| max_delay_ms: int = 50, +//| delay_ms: synthio.BlockInput = 50.0, +//| voices: synthio.BlockInput = 1.0, +//| buffer_size: int = 512, +//| sample_rate: int = 8000, +//| bits_per_sample: int = 16, +//| samples_signed: bool = True, +//| channel_count: int = 1, +//| ) -> None: +//| """Create a Chorus effect by playing the current sample along with one or more samples +//| (the voices) from the delay buffer. The voices played are evenly spaced across the delay +//| buffer. So for 2 voices you would hear the current sample and the one delay milliseconds back. +//| The delay timing of the chorus can be changed at runtime with the delay_ms parameter but the delay +//| can never exceed the max_delay_ms parameter. The maximum delay you can set is limited by available +//| memory. +//| +//| :param int max_delay_ms: The maximum time the chorus can be in milliseconds +//| :param synthio.BlockInput delay_ms: The current time of the chorus delay in milliseconds. Must be less the max_delay_ms. +//| :param synthio.BlockInput voices: The number of voices playing split evenly over the delay buffer. +//| :param synthio.BlockInput mix: How much of the wet audio to include along with the original signal. +//| :param int buffer_size: The total size in bytes of each of the two playback buffers to use +//| :param int sample_rate: The sample rate to be used +//| :param int channel_count: The number of channels the source samples contain. 1 = mono; 2 = stereo. +//| :param int bits_per_sample: The bits per sample of the effect +//| :param bool samples_signed: Effect is signed (True) or unsigned (False) +//| +//| Playing adding an chorus to a synth:: +//| +//| import time +//| import board +//| import audiobusio +//| import synthio +//| import audiodelays +//| +//| audio = audiobusio.I2SOut(bit_clock=board.GP20, word_select=board.GP21, data=board.GP22) +//| synth = synthio.Synthesizer(channel_count=1, sample_rate=44100) +//| chorus = audiodelays.Chorus(max_delay_ms=50, voices=4, delay_ms=5, buffer_size=1024, channel_count=1, sample_rate=44100) +//| chorus.play(synth) +//| audio.play(chorus) +//| +//| note = synthio.Note(261) +//| while True: +//| synth.press(note) +//| time.sleep(0.25) +//| synth.release(note) +//| time.sleep(5)""" +//| ... +//| +static mp_obj_t audiodelays_chorus_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_max_delay_ms, ARG_delay_ms, ARG_voices, ARG_mix, ARG_buffer_size, ARG_sample_rate, ARG_bits_per_sample, ARG_samples_signed, ARG_channel_count, }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_max_delay_ms, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 50 } }, + { MP_QSTR_delay_ms, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_voices, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_mix, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_buffer_size, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 512} }, + { MP_QSTR_sample_rate, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 8000} }, + { MP_QSTR_bits_per_sample, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 16} }, + { MP_QSTR_samples_signed, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = true} }, + { MP_QSTR_channel_count, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 1 } }, + }; + + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + mp_int_t max_delay_ms = mp_arg_validate_int_range(args[ARG_max_delay_ms].u_int, 1, 4000, MP_QSTR_max_delay_ms); + + mp_int_t channel_count = mp_arg_validate_int_range(args[ARG_channel_count].u_int, 1, 2, MP_QSTR_channel_count); + mp_int_t sample_rate = mp_arg_validate_int_min(args[ARG_sample_rate].u_int, 1, MP_QSTR_sample_rate); + mp_int_t bits_per_sample = args[ARG_bits_per_sample].u_int; + if (bits_per_sample != 8 && bits_per_sample != 16) { + mp_raise_ValueError(MP_ERROR_TEXT("bits_per_sample must be 8 or 16")); + } + + audiodelays_chorus_obj_t *self = mp_obj_malloc_with_finaliser(audiodelays_chorus_obj_t, &audiodelays_chorus_type); + common_hal_audiodelays_chorus_construct(self, max_delay_ms, args[ARG_delay_ms].u_obj, args[ARG_voices].u_obj, args[ARG_mix].u_obj, args[ARG_buffer_size].u_int, bits_per_sample, args[ARG_samples_signed].u_bool, channel_count, sample_rate); + + return MP_OBJ_FROM_PTR(self); +} + +//| def deinit(self) -> None: +//| """Deinitialises the Chorus.""" +//| ... +//| +static mp_obj_t audiodelays_chorus_deinit(mp_obj_t self_in) { + audiodelays_chorus_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiodelays_chorus_deinit(self); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_chorus_deinit_obj, audiodelays_chorus_deinit); + +static void check_for_deinit(audiodelays_chorus_obj_t *self) { + audiosample_check_for_deinit(&self->base); +} + +//| def __enter__(self) -> Chorus: +//| """No-op used by Context Managers.""" +//| ... +//| +// Provided by context manager helper. + +//| def __exit__(self) -> None: +//| """Automatically deinitializes when exiting a context. See +//| :ref:`lifetime-and-contextmanagers` for more info.""" +//| ... +//| +static mp_obj_t audiodelays_chorus_obj___exit__(size_t n_args, const mp_obj_t *args) { + (void)n_args; + common_hal_audiodelays_chorus_deinit(args[0]); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(audiodelays_chorus___exit___obj, 4, 4, audiodelays_chorus_obj___exit__); + + +//| delay_ms: synthio.BlockInput +//| """The current time of the chorus delay in milliseconds. Must be less the max_delay_ms.""" +//| +static mp_obj_t audiodelays_chorus_obj_get_delay_ms(mp_obj_t self_in) { + audiodelays_chorus_obj_t *self = MP_OBJ_TO_PTR(self_in); + + return common_hal_audiodelays_chorus_get_delay_ms(self); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_chorus_get_delay_ms_obj, audiodelays_chorus_obj_get_delay_ms); + +static mp_obj_t audiodelays_chorus_obj_set_delay_ms(mp_obj_t self_in, mp_obj_t delay_ms_in) { + audiodelays_chorus_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiodelays_chorus_set_delay_ms(self, delay_ms_in); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiodelays_chorus_set_delay_ms_obj, audiodelays_chorus_obj_set_delay_ms); + +MP_PROPERTY_GETSET(audiodelays_chorus_delay_ms_obj, + (mp_obj_t)&audiodelays_chorus_get_delay_ms_obj, + (mp_obj_t)&audiodelays_chorus_set_delay_ms_obj); + +//| voices: synthio.BlockInput +//| """The number of voices playing split evenly over the delay buffer.""" +static mp_obj_t audiodelays_chorus_obj_get_voices(mp_obj_t self_in) { + return common_hal_audiodelays_chorus_get_voices(self_in); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_chorus_get_voices_obj, audiodelays_chorus_obj_get_voices); + +static mp_obj_t audiodelays_chorus_obj_set_voices(mp_obj_t self_in, mp_obj_t voices_in) { + audiodelays_chorus_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiodelays_chorus_set_voices(self, voices_in); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiodelays_chorus_set_voices_obj, audiodelays_chorus_obj_set_voices); + +MP_PROPERTY_GETSET(audiodelays_chorus_voices_obj, + (mp_obj_t)&audiodelays_chorus_get_voices_obj, + (mp_obj_t)&audiodelays_chorus_set_voices_obj); + +//| mix: synthio.BlockInput +//| """The rate the echo mix between 0 and 1 where 0 is only sample and 1 is all effect.""" +static mp_obj_t audiodelays_chorus_obj_get_mix(mp_obj_t self_in) { + return common_hal_audiodelays_chorus_get_mix(self_in); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_chorus_get_mix_obj, audiodelays_chorus_obj_get_mix); + +static mp_obj_t audiodelays_chorus_obj_set_mix(mp_obj_t self_in, mp_obj_t mix_in) { + audiodelays_chorus_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiodelays_chorus_set_mix(self, mix_in); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiodelays_chorus_set_mix_obj, audiodelays_chorus_obj_set_mix); + +MP_PROPERTY_GETSET(audiodelays_chorus_mix_obj, + (mp_obj_t)&audiodelays_chorus_get_mix_obj, + (mp_obj_t)&audiodelays_chorus_set_mix_obj); + +//| playing: bool +//| """True when the effect is playing a sample. (read-only)""" +//| +static mp_obj_t audiodelays_chorus_obj_get_playing(mp_obj_t self_in) { + audiodelays_chorus_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_bool(common_hal_audiodelays_chorus_get_playing(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_chorus_get_playing_obj, audiodelays_chorus_obj_get_playing); + +MP_PROPERTY_GETTER(audiodelays_chorus_playing_obj, + (mp_obj_t)&audiodelays_chorus_get_playing_obj); + +//| def play(self, sample: circuitpython_typing.AudioSample, *, loop: bool = False) -> Chorus: +//| """Plays the sample once when loop=False and continuously when loop=True. +//| Does not block. Use `playing` to block. +//| +//| The sample must match the encoding settings given in the constructor. +//| +//| :return: The effect object itself. Can be used for chaining, ie: +//| ``audio.play(effect.play(sample))``. +//| :rtype: Chorus""" +//| ... +//| +static mp_obj_t audiodelays_chorus_obj_play(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_sample, ARG_loop }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_sample, MP_ARG_OBJ | MP_ARG_REQUIRED, {} }, + { MP_QSTR_loop, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = false} }, + }; + audiodelays_chorus_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_obj_t sample = args[ARG_sample].u_obj; + common_hal_audiodelays_chorus_play(self, sample, args[ARG_loop].u_bool); + + return MP_OBJ_FROM_PTR(self); +} +MP_DEFINE_CONST_FUN_OBJ_KW(audiodelays_chorus_play_obj, 1, audiodelays_chorus_obj_play); + +//| def stop(self) -> None: +//| """Stops playback of the sample.""" +//| ... +//| +//| +static mp_obj_t audiodelays_chorus_obj_stop(mp_obj_t self_in) { + audiodelays_chorus_obj_t *self = MP_OBJ_TO_PTR(self_in); + + common_hal_audiodelays_chorus_stop(self); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_chorus_stop_obj, audiodelays_chorus_obj_stop); + +static const mp_rom_map_elem_t audiodelays_chorus_locals_dict_table[] = { + // Methods + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&audiodelays_chorus_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&audiodelays_chorus_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&audiodelays_chorus___exit___obj) }, + { MP_ROM_QSTR(MP_QSTR_play), MP_ROM_PTR(&audiodelays_chorus_play_obj) }, + { MP_ROM_QSTR(MP_QSTR_stop), MP_ROM_PTR(&audiodelays_chorus_stop_obj) }, + + // Properties + { MP_ROM_QSTR(MP_QSTR_playing), MP_ROM_PTR(&audiodelays_chorus_playing_obj) }, + { MP_ROM_QSTR(MP_QSTR_delay_ms), MP_ROM_PTR(&audiodelays_chorus_delay_ms_obj) }, + { MP_ROM_QSTR(MP_QSTR_voices), MP_ROM_PTR(&audiodelays_chorus_voices_obj) }, + { MP_ROM_QSTR(MP_QSTR_mix), MP_ROM_PTR(&audiodelays_chorus_mix_obj) }, + AUDIOSAMPLE_FIELDS, +}; +static MP_DEFINE_CONST_DICT(audiodelays_chorus_locals_dict, audiodelays_chorus_locals_dict_table); + +static const audiosample_p_t audiodelays_chorus_proto = { + MP_PROTO_IMPLEMENT(MP_QSTR_protocol_audiosample) + .reset_buffer = (audiosample_reset_buffer_fun)audiodelays_chorus_reset_buffer, + .get_buffer = (audiosample_get_buffer_fun)audiodelays_chorus_get_buffer, +}; + +MP_DEFINE_CONST_OBJ_TYPE( + audiodelays_chorus_type, + MP_QSTR_Chorus, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, audiodelays_chorus_make_new, + locals_dict, &audiodelays_chorus_locals_dict, + protocol, &audiodelays_chorus_proto + ); diff --git a/shared-bindings/audiodelays/Chorus.h b/shared-bindings/audiodelays/Chorus.h new file mode 100644 index 00000000000..63e9ba9c28d --- /dev/null +++ b/shared-bindings/audiodelays/Chorus.h @@ -0,0 +1,32 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Mark Komus +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-module/audiodelays/Chorus.h" + +extern const mp_obj_type_t audiodelays_chorus_type; + +void common_hal_audiodelays_chorus_construct(audiodelays_chorus_obj_t *self, uint32_t max_delay_ms, + mp_obj_t delay_ms, mp_obj_t voices, mp_obj_t mix, + uint32_t buffer_size, uint8_t bits_per_sample, + bool samples_signed, uint8_t channel_count, uint32_t sample_rate); + +void common_hal_audiodelays_chorus_deinit(audiodelays_chorus_obj_t *self); +bool common_hal_audiodelays_chorus_deinited(audiodelays_chorus_obj_t *self); + +mp_obj_t common_hal_audiodelays_chorus_get_delay_ms(audiodelays_chorus_obj_t *self); +void common_hal_audiodelays_chorus_set_delay_ms(audiodelays_chorus_obj_t *self, mp_obj_t delay_ms); + +mp_obj_t common_hal_audiodelays_chorus_get_voices(audiodelays_chorus_obj_t *self); +void common_hal_audiodelays_chorus_set_voices(audiodelays_chorus_obj_t *self, mp_obj_t voices); + +mp_obj_t common_hal_audiodelays_chorus_get_mix(audiodelays_chorus_obj_t *self); +void common_hal_audiodelays_chorus_set_mix(audiodelays_chorus_obj_t *self, mp_obj_t arg); + +bool common_hal_audiodelays_chorus_get_playing(audiodelays_chorus_obj_t *self); +void common_hal_audiodelays_chorus_play(audiodelays_chorus_obj_t *self, mp_obj_t sample, bool loop); +void common_hal_audiodelays_chorus_stop(audiodelays_chorus_obj_t *self); diff --git a/shared-bindings/audiodelays/Echo.c b/shared-bindings/audiodelays/Echo.c index 71e53305557..dc3983fbde7 100644 --- a/shared-bindings/audiodelays/Echo.c +++ b/shared-bindings/audiodelays/Echo.c @@ -17,9 +17,6 @@ #include "shared-bindings/util.h" #include "shared-module/synthio/block.h" -#define DECAY_DEFAULT 0.7f -#define MIX_DEFAULT 0.5f - //| class Echo: //| """An Echo effect""" //| @@ -28,7 +25,8 @@ //| max_delay_ms: int = 500, //| delay_ms: synthio.BlockInput = 250.0, //| decay: synthio.BlockInput = 0.7, -//| mix: synthio.BlockInput = 0.5, +//| filter: Optional[synthio.Biquad | Tuple[synthio.Biquad]] = None, +//| mix: synthio.BlockInput = 0.25, //| buffer_size: int = 512, //| sample_rate: int = 8000, //| bits_per_sample: int = 16, @@ -45,16 +43,19 @@ //| The mix parameter allows you to change how much of the unchanged sample passes through to //| the output to how much of the effect audio you hear as the output. //| -//| :param int max_delay_ms: The maximum time the echo can be in milliseconds +//| :param int max_delay_ms: The maximum time the echo can be in milliseconds. Must be 4000 or less. At sample rates above 131 kHz the limit is lower, for example 2730 at 192 kHz. //| :param synthio.BlockInput delay_ms: The current time of the echo delay in milliseconds. Must be less the max_delay_ms //| :param synthio.BlockInput decay: The rate the echo fades. 0.0 = instant; 1.0 = never. +//| :param Optional[synthio.Biquad|Tuple[synthio.Biquad]] filter: A normalized biquad filter object or tuple of normalized biquad filter objects. A copy of the samples are processed sequentially by each filter before writing into the echo buffer. The original samples are not affected by this argument. //| :param synthio.BlockInput mix: The mix as a ratio of the sample (0.0) to the effect (1.0). //| :param int buffer_size: The total size in bytes of each of the two playback buffers to use //| :param int sample_rate: The sample rate to be used //| :param int channel_count: The number of channels the source samples contain. 1 = mono; 2 = stereo. //| :param int bits_per_sample: The bits per sample of the effect //| :param bool samples_signed: Effect is signed (True) or unsigned (False) -//| :param bool freq_shift: Do echos change frequency as the echo delay changes +//| :param bool freq_shift: Do echoes change frequency as the echo delay changes. The pitch follows the +//| slope of delay_ms, so a `synthio.LFO` with its default triangle waveform holds two steady +//| pitches and jumps between them, while a sine waveform glides. //| //| Playing adding an echo to a synth:: //| @@ -79,11 +80,12 @@ //| ... //| static mp_obj_t audiodelays_echo_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { - enum { ARG_max_delay_ms, ARG_delay_ms, ARG_decay, ARG_mix, ARG_buffer_size, ARG_sample_rate, ARG_bits_per_sample, ARG_samples_signed, ARG_channel_count, ARG_freq_shift, }; + enum { ARG_max_delay_ms, ARG_delay_ms, ARG_decay, ARG_filter, ARG_mix, ARG_buffer_size, ARG_sample_rate, ARG_bits_per_sample, ARG_samples_signed, ARG_channel_count, ARG_freq_shift, }; static const mp_arg_t allowed_args[] = { { MP_QSTR_max_delay_ms, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 500 } }, { MP_QSTR_delay_ms, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_OBJ_NULL} }, { MP_QSTR_decay, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_filter, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_ROM_NONE } }, { MP_QSTR_mix, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_OBJ_NULL} }, { MP_QSTR_buffer_size, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 512} }, { MP_QSTR_sample_rate, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 8000} }, @@ -100,13 +102,15 @@ static mp_obj_t audiodelays_echo_make_new(const mp_obj_type_t *type, size_t n_ar mp_int_t channel_count = mp_arg_validate_int_range(args[ARG_channel_count].u_int, 1, 2, MP_QSTR_channel_count); mp_int_t sample_rate = mp_arg_validate_int_min(args[ARG_sample_rate].u_int, 1, MP_QSTR_sample_rate); + // freq_shift can be turned on later, so this applies either way. + mp_arg_validate_int_max(max_delay_ms, AUDIODELAYS_ECHO_MAX_BUFFER_SAMPLES * 1000 / sample_rate, MP_QSTR_max_delay_ms); mp_int_t bits_per_sample = args[ARG_bits_per_sample].u_int; if (bits_per_sample != 8 && bits_per_sample != 16) { mp_raise_ValueError(MP_ERROR_TEXT("bits_per_sample must be 8 or 16")); } - audiodelays_echo_obj_t *self = mp_obj_malloc(audiodelays_echo_obj_t, &audiodelays_echo_type); - common_hal_audiodelays_echo_construct(self, max_delay_ms, args[ARG_delay_ms].u_obj, args[ARG_decay].u_obj, args[ARG_mix].u_obj, args[ARG_buffer_size].u_int, bits_per_sample, args[ARG_samples_signed].u_bool, channel_count, sample_rate, args[ARG_freq_shift].u_bool); + audiodelays_echo_obj_t *self = mp_obj_malloc_with_finaliser(audiodelays_echo_obj_t, &audiodelays_echo_type); + common_hal_audiodelays_echo_construct(self, max_delay_ms, args[ARG_delay_ms].u_obj, args[ARG_decay].u_obj, args[ARG_filter].u_obj, args[ARG_mix].u_obj, args[ARG_buffer_size].u_int, bits_per_sample, args[ARG_samples_signed].u_bool, channel_count, sample_rate, args[ARG_freq_shift].u_bool); return MP_OBJ_FROM_PTR(self); } @@ -163,7 +167,7 @@ MP_PROPERTY_GETSET(audiodelays_echo_delay_ms_obj, (mp_obj_t)&audiodelays_echo_set_delay_ms_obj); //| decay: synthio.BlockInput -//| """The rate the echo decays between 0 and 1 where 1 is forever and 0 is no echo.""" +//| """The rate the echo fades between 0 and 1 where 0 is instant and 1 is never.""" static mp_obj_t audiodelays_echo_obj_get_decay(mp_obj_t self_in) { return common_hal_audiodelays_echo_get_decay(self_in); } @@ -180,8 +184,31 @@ MP_PROPERTY_GETSET(audiodelays_echo_decay_obj, (mp_obj_t)&audiodelays_echo_get_decay_obj, (mp_obj_t)&audiodelays_echo_set_decay_obj); + +//| filter: synthio.Biquad | Tuple[synthio.Biquad] | None +//| """A normalized biquad filter object or tuple of normalized biquad filter objects. A copy of the samples are processed sequentially by each filter before writing into the echo buffer. The original samples are not affected by this property.""" +//| +static mp_obj_t audiodelays_echo_obj_get_filter(mp_obj_t self_in) { + audiodelays_echo_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return common_hal_audiodelays_echo_get_filter(self); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_echo_get_filter_obj, audiodelays_echo_obj_get_filter); + +static mp_obj_t audiodelays_echo_obj_set_filter(mp_obj_t self_in, mp_obj_t filter_in) { + audiodelays_echo_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiodelays_echo_set_filter(self, filter_in); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiodelays_echo_set_filter_obj, audiodelays_echo_obj_set_filter); + +MP_PROPERTY_GETSET(audiodelays_echo_filter_obj, + (mp_obj_t)&audiodelays_echo_get_filter_obj, + (mp_obj_t)&audiodelays_echo_set_filter_obj); + + //| mix: synthio.BlockInput -//| """The rate the echo mix between 0 and 1 where 0 is only sample and 1 is all effect.""" +//| """The rate the echo mix between 0 and 1 where 0 is only sample, 0.5 is an equal mix of the sample and the effect and 1 is all effect.""" static mp_obj_t audiodelays_echo_obj_get_mix(mp_obj_t self_in) { return common_hal_audiodelays_echo_get_mix(self_in); } @@ -233,11 +260,15 @@ MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_echo_get_playing_obj, audiodelays_echo_obj MP_PROPERTY_GETTER(audiodelays_echo_playing_obj, (mp_obj_t)&audiodelays_echo_get_playing_obj); -//| def play(self, sample: circuitpython_typing.AudioSample, *, loop: bool = False) -> None: +//| def play(self, sample: circuitpython_typing.AudioSample, *, loop: bool = False) -> Echo: //| """Plays the sample once when loop=False and continuously when loop=True. //| Does not block. Use `playing` to block. //| -//| The sample must match the encoding settings given in the constructor.""" +//| The sample must match the encoding settings given in the constructor. +//| +//| :return: The effect object itself. Can be used for chaining, ie: +//| ``audio.play(effect.play(sample))``. +//| :rtype: Echo""" //| ... //| static mp_obj_t audiodelays_echo_obj_play(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { @@ -255,7 +286,7 @@ static mp_obj_t audiodelays_echo_obj_play(size_t n_args, const mp_obj_t *pos_arg mp_obj_t sample = args[ARG_sample].u_obj; common_hal_audiodelays_echo_play(self, sample, args[ARG_loop].u_bool); - return mp_const_none; + return MP_OBJ_FROM_PTR(self); } MP_DEFINE_CONST_FUN_OBJ_KW(audiodelays_echo_play_obj, 1, audiodelays_echo_obj_play); @@ -275,6 +306,7 @@ MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_echo_stop_obj, audiodelays_echo_obj_stop); static const mp_rom_map_elem_t audiodelays_echo_locals_dict_table[] = { // Methods { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&audiodelays_echo_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&audiodelays_echo_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, { MP_ROM_QSTR(MP_QSTR_play), MP_ROM_PTR(&audiodelays_echo_play_obj) }, @@ -284,6 +316,7 @@ static const mp_rom_map_elem_t audiodelays_echo_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_playing), MP_ROM_PTR(&audiodelays_echo_playing_obj) }, { MP_ROM_QSTR(MP_QSTR_delay_ms), MP_ROM_PTR(&audiodelays_echo_delay_ms_obj) }, { MP_ROM_QSTR(MP_QSTR_decay), MP_ROM_PTR(&audiodelays_echo_decay_obj) }, + { MP_ROM_QSTR(MP_QSTR_filter), MP_ROM_PTR(&audiodelays_echo_filter_obj) }, { MP_ROM_QSTR(MP_QSTR_mix), MP_ROM_PTR(&audiodelays_echo_mix_obj) }, { MP_ROM_QSTR(MP_QSTR_freq_shift), MP_ROM_PTR(&audiodelays_echo_freq_shift_obj) }, AUDIOSAMPLE_FIELDS, diff --git a/shared-bindings/audiodelays/Echo.h b/shared-bindings/audiodelays/Echo.h index 83d454ed05c..67b7436b896 100644 --- a/shared-bindings/audiodelays/Echo.h +++ b/shared-bindings/audiodelays/Echo.h @@ -11,7 +11,7 @@ extern const mp_obj_type_t audiodelays_echo_type; void common_hal_audiodelays_echo_construct(audiodelays_echo_obj_t *self, uint32_t max_delay_ms, - mp_obj_t delay_ms, mp_obj_t decay, mp_obj_t mix, + mp_obj_t delay_ms, mp_obj_t decay, mp_obj_t filter, mp_obj_t mix, uint32_t buffer_size, uint8_t bits_per_sample, bool samples_signed, uint8_t channel_count, uint32_t sample_rate, bool freq_shift); @@ -26,6 +26,9 @@ void common_hal_audiodelays_echo_set_freq_shift(audiodelays_echo_obj_t *self, bo mp_obj_t common_hal_audiodelays_echo_get_decay(audiodelays_echo_obj_t *self); void common_hal_audiodelays_echo_set_decay(audiodelays_echo_obj_t *self, mp_obj_t decay); +mp_obj_t common_hal_audiodelays_echo_get_filter(audiodelays_echo_obj_t *self); +void common_hal_audiodelays_echo_set_filter(audiodelays_echo_obj_t *self, mp_obj_t arg); + mp_obj_t common_hal_audiodelays_echo_get_mix(audiodelays_echo_obj_t *self); void common_hal_audiodelays_echo_set_mix(audiodelays_echo_obj_t *self, mp_obj_t arg); diff --git a/shared-bindings/audiodelays/Flanger.c b/shared-bindings/audiodelays/Flanger.c new file mode 100644 index 00000000000..0290c5288e0 --- /dev/null +++ b/shared-bindings/audiodelays/Flanger.c @@ -0,0 +1,390 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include + +#include "shared-bindings/audiodelays/Flanger.h" +#include "shared-module/audiodelays/Flanger.h" +#include "shared-bindings/audiocore/__init__.h" + +#include "shared/runtime/context_manager_helpers.h" +#include "py/binary.h" +#include "py/objproperty.h" +#include "py/runtime.h" +#include "shared-bindings/util.h" +#include "shared-module/synthio/block.h" + +//| class Flanger: +//| """A Flanger effect""" +//| +//| def __init__( +//| self, +//| max_delay_ms: int = 10, +//| min_delay_ms: synthio.BlockInput = 1.0, +//| rate: synthio.BlockInput = 0.5, +//| depth: synthio.BlockInput = 0.5, +//| feedback: synthio.BlockInput = 0.5, +//| mix: synthio.BlockInput = 0.5, +//| invert: bool = False, +//| buffer_size: int = 512, +//| sample_rate: int = 8000, +//| bits_per_sample: int = 16, +//| samples_signed: bool = True, +//| channel_count: int = 1, +//| ) -> None: +//| """Create a Flanger effect by mixing the sample with a copy of itself taken from a very +//| short delay whose length is continuously swept up and down by an internal low frequency +//| oscillator. The moving delay creates a comb filter whose notches sweep through the +//| spectrum, and the ``feedback`` path routes the delayed signal back into the delay line +//| to sharpen those notches into resonant peaks. +//| +//| The delay is swept upwards from ``min_delay_ms`` towards ``max_delay_ms``:: +//| +//| sweep_top = min_delay_ms + depth * (max_delay_ms - min_delay_ms) +//| current_delay = min_delay_ms + triangle_lfo() * (sweep_top - min_delay_ms) +//| +//| where ``triangle_lfo()`` ranges from 0.0 to 1.0 at ``rate`` Hz. Because the sweep runs +//| upwards from a floor rather than around a centre, no combination of ``min_delay_ms`` and +//| ``depth`` can push the delay outside of the buffer. +//| +//| +//| :param int max_delay_ms: The maximum delay the flanger can sweep to in milliseconds, valid range is 1-100. +//| :param synthio.BlockInput min_delay_ms: The shortest delay of the sweep in milliseconds. Clamped between the length of one sample and max_delay_ms. +//| :param synthio.BlockInput rate: The frequency of the sweep in hertz. Clamped between 0.0 and 20.0. A rate of 0.0 holds the delay still. +//| :param synthio.BlockInput depth: How much of the range above min_delay_ms is swept, from 0.0 to 1.0. +//| :param synthio.BlockInput feedback: How much of the delayed signal is fed back into the delay line, from -0.95 to 0.95. Negative values invert the polarity of the feedback. +//| :param synthio.BlockInput mix: How much of the wet audio to include along with the original signal, from 0.0 to 1.0. +//| :param bool invert: Subtract the wet signal from the dry signal instead of adding it, which flips which frequencies cancel. +//| :param int buffer_size: The total size in bytes of each of the two playback buffers to use +//| :param int sample_rate: The sample rate to be used +//| :param int channel_count: The number of channels the source samples contain. 1 = mono; 2 = stereo. +//| :param int bits_per_sample: The bits per sample of the effect +//| :param bool samples_signed: Effect is signed (True) or unsigned (False) +//| +//| Adding a flanger to a synth:: +//| +//| import time +//| import board +//| import audiobusio +//| import synthio +//| import audiodelays +//| +//| audio = audiobusio.I2SOut(board.I2S_BIT_CLOCK, board.I2S_WS, board.I2S_DOUT) +//| synth = synthio.Synthesizer(channel_count=1, sample_rate=44100) +//| flanger = audiodelays.Flanger(max_delay_ms=10, min_delay_ms=1.0, rate=0.3, depth=0.8, +//| feedback=0.7, mix=1.0, buffer_size=1024, +//| channel_count=1, sample_rate=44100) +//| audio.play(flanger.play(synth)) +//| +//| note = synthio.Note(261) +//| while True: +//| synth.press(note) +//| time.sleep(3) +//| synth.release(note) +//| time.sleep(1)""" +//| ... +//| +static mp_obj_t audiodelays_flanger_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_max_delay_ms, ARG_min_delay_ms, ARG_rate, ARG_depth, ARG_feedback, ARG_mix, ARG_invert, ARG_buffer_size, ARG_sample_rate, ARG_bits_per_sample, ARG_samples_signed, ARG_channel_count, }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_max_delay_ms, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 10 } }, + { MP_QSTR_min_delay_ms, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_rate, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_depth, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_feedback, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_mix, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_invert, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = false} }, + { MP_QSTR_buffer_size, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 512} }, + { MP_QSTR_sample_rate, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 8000} }, + { MP_QSTR_bits_per_sample, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 16} }, + { MP_QSTR_samples_signed, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = true} }, + { MP_QSTR_channel_count, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 1 } }, + }; + + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + mp_int_t max_delay_ms = mp_arg_validate_int_range(args[ARG_max_delay_ms].u_int, 1, 100, MP_QSTR_max_delay_ms); + + mp_int_t channel_count = mp_arg_validate_int_range(args[ARG_channel_count].u_int, 1, 2, MP_QSTR_channel_count); + mp_int_t sample_rate = mp_arg_validate_int_min(args[ARG_sample_rate].u_int, 1, MP_QSTR_sample_rate); + mp_int_t bits_per_sample = args[ARG_bits_per_sample].u_int; + if (bits_per_sample != 8 && bits_per_sample != 16) { + mp_raise_ValueError(MP_ERROR_TEXT("bits_per_sample must be 8 or 16")); + } + + audiodelays_flanger_obj_t *self = mp_obj_malloc_with_finaliser(audiodelays_flanger_obj_t, &audiodelays_flanger_type); + common_hal_audiodelays_flanger_construct(self, max_delay_ms, args[ARG_min_delay_ms].u_obj, args[ARG_rate].u_obj, args[ARG_depth].u_obj, args[ARG_feedback].u_obj, args[ARG_mix].u_obj, args[ARG_invert].u_bool, args[ARG_buffer_size].u_int, bits_per_sample, args[ARG_samples_signed].u_bool, channel_count, sample_rate); + + return MP_OBJ_FROM_PTR(self); +} + +//| def deinit(self) -> None: +//| """Deinitialises the Flanger.""" +//| ... +//| +static mp_obj_t audiodelays_flanger_deinit(mp_obj_t self_in) { + audiodelays_flanger_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiodelays_flanger_deinit(self); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_flanger_deinit_obj, audiodelays_flanger_deinit); + +static void check_for_deinit(audiodelays_flanger_obj_t *self) { + audiosample_check_for_deinit(&self->base); +} + +//| def __enter__(self) -> Flanger: +//| """No-op used by Context Managers.""" +//| ... +//| +// Provided by context manager helper. + +//| def __exit__(self) -> None: +//| """Automatically deinitializes when exiting a context. See +//| :ref:`lifetime-and-contextmanagers` for more info.""" +//| ... +//| +static mp_obj_t audiodelays_flanger_obj___exit__(size_t n_args, const mp_obj_t *args) { + (void)n_args; + common_hal_audiodelays_flanger_deinit(args[0]); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(audiodelays_flanger___exit___obj, 4, 4, audiodelays_flanger_obj___exit__); + + +//| min_delay_ms: synthio.BlockInput +//| """The shortest delay of the sweep in milliseconds. This is the floor that the sweep runs +//| upwards from. Clamped between the length of a single sample and ``max_delay_ms``.""" +//| +static mp_obj_t audiodelays_flanger_obj_get_min_delay_ms(mp_obj_t self_in) { + audiodelays_flanger_obj_t *self = MP_OBJ_TO_PTR(self_in); + + return common_hal_audiodelays_flanger_get_min_delay_ms(self); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_flanger_get_min_delay_ms_obj, audiodelays_flanger_obj_get_min_delay_ms); + +static mp_obj_t audiodelays_flanger_obj_set_min_delay_ms(mp_obj_t self_in, mp_obj_t min_delay_ms_in) { + audiodelays_flanger_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiodelays_flanger_set_min_delay_ms(self, min_delay_ms_in); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiodelays_flanger_set_min_delay_ms_obj, audiodelays_flanger_obj_set_min_delay_ms); + +MP_PROPERTY_GETSET(audiodelays_flanger_min_delay_ms_obj, + (mp_obj_t)&audiodelays_flanger_get_min_delay_ms_obj, + (mp_obj_t)&audiodelays_flanger_set_min_delay_ms_obj); + +//| rate: synthio.BlockInput +//| """The frequency of the delay sweep in hertz. Clamped between 0.0 and 20.0. A rate of 0.0 +//| holds the delay still, which leaves a fixed comb filter.""" +//| +static mp_obj_t audiodelays_flanger_obj_get_rate(mp_obj_t self_in) { + return common_hal_audiodelays_flanger_get_rate(self_in); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_flanger_get_rate_obj, audiodelays_flanger_obj_get_rate); + +static mp_obj_t audiodelays_flanger_obj_set_rate(mp_obj_t self_in, mp_obj_t rate_in) { + audiodelays_flanger_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiodelays_flanger_set_rate(self, rate_in); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiodelays_flanger_set_rate_obj, audiodelays_flanger_obj_set_rate); + +MP_PROPERTY_GETSET(audiodelays_flanger_rate_obj, + (mp_obj_t)&audiodelays_flanger_get_rate_obj, + (mp_obj_t)&audiodelays_flanger_set_rate_obj); + +//| depth: synthio.BlockInput +//| """How much of the range between ``min_delay_ms`` and ``max_delay_ms`` the sweep covers, from +//| 0.0 to 1.0. A depth of 0.0 leaves a static short delay.""" +//| +static mp_obj_t audiodelays_flanger_obj_get_depth(mp_obj_t self_in) { + return common_hal_audiodelays_flanger_get_depth(self_in); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_flanger_get_depth_obj, audiodelays_flanger_obj_get_depth); + +static mp_obj_t audiodelays_flanger_obj_set_depth(mp_obj_t self_in, mp_obj_t depth_in) { + audiodelays_flanger_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiodelays_flanger_set_depth(self, depth_in); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiodelays_flanger_set_depth_obj, audiodelays_flanger_obj_set_depth); + +MP_PROPERTY_GETSET(audiodelays_flanger_depth_obj, + (mp_obj_t)&audiodelays_flanger_get_depth_obj, + (mp_obj_t)&audiodelays_flanger_set_depth_obj); + +//| feedback: synthio.BlockInput +//| """How much of the delayed signal is fed back into the delay line, clamped between -0.95 and +//| 0.95. Larger magnitudes give a more resonant, ringing sweep. Negative values invert the +//| polarity of the feedback for the hollower variant.""" +//| +static mp_obj_t audiodelays_flanger_obj_get_feedback(mp_obj_t self_in) { + return common_hal_audiodelays_flanger_get_feedback(self_in); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_flanger_get_feedback_obj, audiodelays_flanger_obj_get_feedback); + +static mp_obj_t audiodelays_flanger_obj_set_feedback(mp_obj_t self_in, mp_obj_t feedback_in) { + audiodelays_flanger_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiodelays_flanger_set_feedback(self, feedback_in); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiodelays_flanger_set_feedback_obj, audiodelays_flanger_obj_set_feedback); + +MP_PROPERTY_GETSET(audiodelays_flanger_feedback_obj, + (mp_obj_t)&audiodelays_flanger_get_feedback_obj, + (mp_obj_t)&audiodelays_flanger_set_feedback_obj); + +//| mix: synthio.BlockInput +//| """How much of the wet audio to include along with the original signal, clamped between 0.0 +//| and 1.0 where 0.0 is only the sample and 1.0 is the full effect.""" +//| +static mp_obj_t audiodelays_flanger_obj_get_mix(mp_obj_t self_in) { + return common_hal_audiodelays_flanger_get_mix(self_in); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_flanger_get_mix_obj, audiodelays_flanger_obj_get_mix); + +static mp_obj_t audiodelays_flanger_obj_set_mix(mp_obj_t self_in, mp_obj_t mix_in) { + audiodelays_flanger_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiodelays_flanger_set_mix(self, mix_in); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiodelays_flanger_set_mix_obj, audiodelays_flanger_obj_set_mix); + +MP_PROPERTY_GETSET(audiodelays_flanger_mix_obj, + (mp_obj_t)&audiodelays_flanger_get_mix_obj, + (mp_obj_t)&audiodelays_flanger_set_mix_obj); + +//| invert: bool +//| """Whether the wet signal is subtracted from the dry signal instead of added to it. This +//| flips which frequencies the comb filter cancels, the same as the polarity switch on a +//| flanger pedal.""" +//| +static mp_obj_t audiodelays_flanger_obj_get_invert(mp_obj_t self_in) { + audiodelays_flanger_obj_t *self = MP_OBJ_TO_PTR(self_in); + return mp_obj_new_bool(common_hal_audiodelays_flanger_get_invert(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_flanger_get_invert_obj, audiodelays_flanger_obj_get_invert); + +static mp_obj_t audiodelays_flanger_obj_set_invert(mp_obj_t self_in, mp_obj_t invert_in) { + audiodelays_flanger_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiodelays_flanger_set_invert(self, mp_obj_is_true(invert_in)); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiodelays_flanger_set_invert_obj, audiodelays_flanger_obj_set_invert); + +MP_PROPERTY_GETSET(audiodelays_flanger_invert_obj, + (mp_obj_t)&audiodelays_flanger_get_invert_obj, + (mp_obj_t)&audiodelays_flanger_set_invert_obj); + +//| lfo_value: float +//| """The current value of the internal LFO that sweeps the delay time, from 0.0 at +//| `min_delay_ms` to 1.0 at the top of the sweep. The LFO only advances while audio is being +//| played. (read-only)""" +//| +static mp_obj_t audiodelays_flanger_obj_get_lfo_value(mp_obj_t self_in) { + audiodelays_flanger_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_float(common_hal_audiodelays_flanger_get_lfo_value(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_flanger_get_lfo_value_obj, audiodelays_flanger_obj_get_lfo_value); + +MP_PROPERTY_GETTER(audiodelays_flanger_lfo_value_obj, + (mp_obj_t)&audiodelays_flanger_get_lfo_value_obj); + +//| playing: bool +//| """True when the effect is playing a sample. (read-only)""" +//| +static mp_obj_t audiodelays_flanger_obj_get_playing(mp_obj_t self_in) { + audiodelays_flanger_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_bool(common_hal_audiodelays_flanger_get_playing(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_flanger_get_playing_obj, audiodelays_flanger_obj_get_playing); + +MP_PROPERTY_GETTER(audiodelays_flanger_playing_obj, + (mp_obj_t)&audiodelays_flanger_get_playing_obj); + +//| def play(self, sample: circuitpython_typing.AudioSample, *, loop: bool = False) -> Flanger: +//| """Plays the sample once when loop=False and continuously when loop=True. +//| Does not block. Use `playing` to block. +//| +//| The sample must match the encoding settings given in the constructor. +//| +//| :return: The effect object itself. Can be used for chaining, ie: +//| ``audio.play(effect.play(sample))``. +//| :rtype: Flanger""" +//| ... +//| +static mp_obj_t audiodelays_flanger_obj_play(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_sample, ARG_loop }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_sample, MP_ARG_OBJ | MP_ARG_REQUIRED, {} }, + { MP_QSTR_loop, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = false} }, + }; + audiodelays_flanger_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_obj_t sample = args[ARG_sample].u_obj; + common_hal_audiodelays_flanger_play(self, sample, args[ARG_loop].u_bool); + + return MP_OBJ_FROM_PTR(self); +} +MP_DEFINE_CONST_FUN_OBJ_KW(audiodelays_flanger_play_obj, 1, audiodelays_flanger_obj_play); + +//| def stop(self) -> None: +//| """Stops playback of the sample.""" +//| ... +//| +//| +static mp_obj_t audiodelays_flanger_obj_stop(mp_obj_t self_in) { + audiodelays_flanger_obj_t *self = MP_OBJ_TO_PTR(self_in); + + common_hal_audiodelays_flanger_stop(self); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_flanger_stop_obj, audiodelays_flanger_obj_stop); + +static const mp_rom_map_elem_t audiodelays_flanger_locals_dict_table[] = { + // Methods + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&audiodelays_flanger_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&audiodelays_flanger_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&audiodelays_flanger___exit___obj) }, + { MP_ROM_QSTR(MP_QSTR_play), MP_ROM_PTR(&audiodelays_flanger_play_obj) }, + { MP_ROM_QSTR(MP_QSTR_stop), MP_ROM_PTR(&audiodelays_flanger_stop_obj) }, + + // Properties + { MP_ROM_QSTR(MP_QSTR_playing), MP_ROM_PTR(&audiodelays_flanger_playing_obj) }, + { MP_ROM_QSTR(MP_QSTR_min_delay_ms), MP_ROM_PTR(&audiodelays_flanger_min_delay_ms_obj) }, + { MP_ROM_QSTR(MP_QSTR_rate), MP_ROM_PTR(&audiodelays_flanger_rate_obj) }, + { MP_ROM_QSTR(MP_QSTR_depth), MP_ROM_PTR(&audiodelays_flanger_depth_obj) }, + { MP_ROM_QSTR(MP_QSTR_feedback), MP_ROM_PTR(&audiodelays_flanger_feedback_obj) }, + { MP_ROM_QSTR(MP_QSTR_mix), MP_ROM_PTR(&audiodelays_flanger_mix_obj) }, + { MP_ROM_QSTR(MP_QSTR_invert), MP_ROM_PTR(&audiodelays_flanger_invert_obj) }, + { MP_ROM_QSTR(MP_QSTR_lfo_value), MP_ROM_PTR(&audiodelays_flanger_lfo_value_obj) }, + AUDIOSAMPLE_FIELDS, +}; +static MP_DEFINE_CONST_DICT(audiodelays_flanger_locals_dict, audiodelays_flanger_locals_dict_table); + +static const audiosample_p_t audiodelays_flanger_proto = { + MP_PROTO_IMPLEMENT(MP_QSTR_protocol_audiosample) + .reset_buffer = (audiosample_reset_buffer_fun)audiodelays_flanger_reset_buffer, + .get_buffer = (audiosample_get_buffer_fun)audiodelays_flanger_get_buffer, +}; + +MP_DEFINE_CONST_OBJ_TYPE( + audiodelays_flanger_type, + MP_QSTR_Flanger, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, audiodelays_flanger_make_new, + locals_dict, &audiodelays_flanger_locals_dict, + protocol, &audiodelays_flanger_proto + ); diff --git a/shared-bindings/audiodelays/Flanger.h b/shared-bindings/audiodelays/Flanger.h new file mode 100644 index 00000000000..f139e842dbd --- /dev/null +++ b/shared-bindings/audiodelays/Flanger.h @@ -0,0 +1,43 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-module/audiodelays/Flanger.h" + +extern const mp_obj_type_t audiodelays_flanger_type; + +void common_hal_audiodelays_flanger_construct(audiodelays_flanger_obj_t *self, uint32_t max_delay_ms, + mp_obj_t min_delay_ms, mp_obj_t rate, mp_obj_t depth, mp_obj_t feedback, mp_obj_t mix, bool invert, + uint32_t buffer_size, uint8_t bits_per_sample, + bool samples_signed, uint8_t channel_count, uint32_t sample_rate); + +void common_hal_audiodelays_flanger_deinit(audiodelays_flanger_obj_t *self); +bool common_hal_audiodelays_flanger_deinited(audiodelays_flanger_obj_t *self); + +mp_obj_t common_hal_audiodelays_flanger_get_min_delay_ms(audiodelays_flanger_obj_t *self); +void common_hal_audiodelays_flanger_set_min_delay_ms(audiodelays_flanger_obj_t *self, mp_obj_t min_delay_ms); + +mp_obj_t common_hal_audiodelays_flanger_get_rate(audiodelays_flanger_obj_t *self); +void common_hal_audiodelays_flanger_set_rate(audiodelays_flanger_obj_t *self, mp_obj_t rate); + +mp_obj_t common_hal_audiodelays_flanger_get_depth(audiodelays_flanger_obj_t *self); +void common_hal_audiodelays_flanger_set_depth(audiodelays_flanger_obj_t *self, mp_obj_t depth); + +mp_obj_t common_hal_audiodelays_flanger_get_feedback(audiodelays_flanger_obj_t *self); +void common_hal_audiodelays_flanger_set_feedback(audiodelays_flanger_obj_t *self, mp_obj_t feedback); + +mp_obj_t common_hal_audiodelays_flanger_get_mix(audiodelays_flanger_obj_t *self); +void common_hal_audiodelays_flanger_set_mix(audiodelays_flanger_obj_t *self, mp_obj_t arg); + +mp_float_t common_hal_audiodelays_flanger_get_lfo_value(audiodelays_flanger_obj_t *self); + +bool common_hal_audiodelays_flanger_get_invert(audiodelays_flanger_obj_t *self); +void common_hal_audiodelays_flanger_set_invert(audiodelays_flanger_obj_t *self, bool invert); + +bool common_hal_audiodelays_flanger_get_playing(audiodelays_flanger_obj_t *self); +void common_hal_audiodelays_flanger_play(audiodelays_flanger_obj_t *self, mp_obj_t sample, bool loop); +void common_hal_audiodelays_flanger_stop(audiodelays_flanger_obj_t *self); diff --git a/shared-bindings/audiodelays/GranularPitchShift.c b/shared-bindings/audiodelays/GranularPitchShift.c new file mode 100644 index 00000000000..9b1acfb6760 --- /dev/null +++ b/shared-bindings/audiodelays/GranularPitchShift.c @@ -0,0 +1,316 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include + +#include "shared-bindings/audiodelays/GranularPitchShift.h" +#include "shared-bindings/audiocore/__init__.h" +#include "shared-module/audiodelays/GranularPitchShift.h" + +#include "shared/runtime/context_manager_helpers.h" +#include "py/binary.h" +#include "py/objproperty.h" +#include "py/runtime.h" +#include "shared-bindings/util.h" +#include "shared-module/synthio/block.h" + +//| class GranularPitchShift: +//| """A granular-synthesis pitch shift effect""" +//| +//| def __init__( +//| self, +//| semitones: synthio.BlockInput = 0.0, +//| mix: synthio.BlockInput = 1.0, +//| grain_size: int = 1024, +//| density: int = 2, +//| spread: float = 0.0, +//| buffer_size: int = 512, +//| sample_rate: int = 8000, +//| bits_per_sample: int = 16, +//| samples_signed: bool = True, +//| channel_count: int = 1, +//| ) -> None: +//| """Create a pitch shift effect that shifts pitch using granular synthesis: a cloud of +//| short, overlapping, individually-enveloped grains resampled from a capture buffer. Unlike +//| `PitchShift` (a single crossfaded window), the overlapping grains tend to sound smoother +//| and less "robotic" at large shifts. This effect introduces a slight delay in the output +//| proportional to ``grain_size``. +//| +//| The mix parameter allows you to change how much of the unchanged sample passes through to +//| the output to how much of the effect audio you hear as the output. +//| +//| :param synthio.BlockInput semitones: The amount of pitch shifting in semitones (1/12th of an octave) +//| :param synthio.BlockInput mix: The mix as a ratio of the sample (0.0) to the effect (1.0) +//| :param int grain_size: The length in samples of each grain +//| :param int density: The number of overlapping grains (overlap factor). Must be between 1 and 8. +//| :param float spread: The amount of random jitter applied to each grain's start position, +//| from 0.0 (deterministic; every grain starts at the same offset) to 1.0 (maximum jitter). +//| Higher values give the classic granular "cloud" texture. Jitter is always backward in +//| time, so it never introduces additional latency beyond ``grain_size``. +//| :param int buffer_size: The total size in bytes of each of the two playback buffers to use +//| :param int sample_rate: The sample rate to be used +//| :param int channel_count: The number of channels the source samples contain. 1 = mono; 2 = stereo. +//| :param int bits_per_sample: The bits per sample of the effect +//| :param bool samples_signed: Effect is signed (True) or unsigned (False) +//| +//| Shifting the pitch of a synth by 5 semitones:: +//| +//| import time +//| import board +//| import audiobusio +//| import synthio +//| import audiodelays +//| from pwmio import PWMOut +//| import adafruit_tlv320 +//| +//| mclk_pwm = PWMOut(board.I2S_MCLK, frequency=15_000_000, duty_cycle=2**15) +//| i2c = board.I2C() +//| dac = adafruit_tlv320.TLV320DAC3100(i2c) +//| dac.configure_clocks(sample_rate=44100, bit_depth=16, mclk_freq=15_000_000) +//| dac.headphone_output = True +//| audio = audiobusio.I2SOut(board.I2S_BCLK, board.I2S_WS, board.I2S_DIN) +//| synth = synthio.Synthesizer(channel_count=1, sample_rate=44100) +//| pitch_shift = audiodelays.GranularPitchShift(semitones=5.0, mix=1.0, spread=0.25, grain_size=2048, density=2, buffer_size=1024, channel_count=1, sample_rate=44100) +//| pitch_shift.play(synth) +//| audio.play(pitch_shift) +//| +//| while True: +//| for notenum in (60, 64, 67, 71): +//| synth.press(notenum) +//| time.sleep(0.25) +//| synth.release_all()""" +//| ... +//| +static mp_obj_t audiodelays_granular_pitch_shift_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_semitones, ARG_mix, ARG_grain_size, ARG_density, ARG_spread, ARG_buffer_size, ARG_sample_rate, ARG_bits_per_sample, ARG_samples_signed, ARG_channel_count, }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_semitones, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_ROM_INT(0)} }, + { MP_QSTR_mix, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_ROM_INT(1)} }, + { MP_QSTR_grain_size, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 1024} }, + { MP_QSTR_density, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 2} }, + { MP_QSTR_spread, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_ROM_INT(0)} }, + { MP_QSTR_buffer_size, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 512} }, + { MP_QSTR_sample_rate, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 8000} }, + { MP_QSTR_bits_per_sample, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 16} }, + { MP_QSTR_samples_signed, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = true} }, + { MP_QSTR_channel_count, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 1 } }, + }; + + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + mp_int_t channel_count = mp_arg_validate_int_range(args[ARG_channel_count].u_int, 1, 2, MP_QSTR_channel_count); + mp_int_t sample_rate = mp_arg_validate_int_min(args[ARG_sample_rate].u_int, 1, MP_QSTR_sample_rate); + mp_int_t grain_size = mp_arg_validate_int_min(args[ARG_grain_size].u_int, 2, MP_QSTR_grain_size); + mp_int_t density = mp_arg_validate_int_range(args[ARG_density].u_int, 1, GRANULAR_MAX_GRAINS, MP_QSTR_density); + mp_int_t bits_per_sample = args[ARG_bits_per_sample].u_int; + if (bits_per_sample != 8 && bits_per_sample != 16) { + mp_raise_ValueError(MP_ERROR_TEXT("bits_per_sample must be 8 or 16")); + } + + audiodelays_granular_pitch_shift_obj_t *self = + mp_obj_malloc_with_finaliser(audiodelays_granular_pitch_shift_obj_t, &audiodelays_granular_pitch_shift_type); + common_hal_audiodelays_granular_pitch_shift_construct(self, + args[ARG_semitones].u_obj, + args[ARG_mix].u_obj, + grain_size, + density, + mp_obj_get_float(args[ARG_spread].u_obj), + args[ARG_buffer_size].u_int, + bits_per_sample, + args[ARG_samples_signed].u_bool, + channel_count, + sample_rate); + + return MP_OBJ_FROM_PTR(self); +} + + +//| def deinit(self) -> None: +//| """Deinitialises the GranularPitchShift.""" +//| ... +//| +static mp_obj_t audiodelays_granular_pitch_shift_deinit(mp_obj_t self_in) { + audiodelays_granular_pitch_shift_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiodelays_granular_pitch_shift_deinit(self); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_granular_pitch_shift_deinit_obj, audiodelays_granular_pitch_shift_deinit); + +static void check_for_deinit(audiodelays_granular_pitch_shift_obj_t *self) { + audiosample_check_for_deinit(&self->base); +} + + +//| def __enter__(self) -> GranularPitchShift: +//| """No-op used by Context Managers.""" +//| ... +//| +// Provided by context manager helper. + +//| def __exit__(self) -> None: +//| """Automatically deinitializes when exiting a context. See +//| :ref:`lifetime-and-contextmanagers` for more info.""" +//| ... +//| +static mp_obj_t audiodelays_granular_pitch_shift_obj___exit__(size_t n_args, const mp_obj_t *args) { + (void)n_args; + common_hal_audiodelays_granular_pitch_shift_deinit(args[0]); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(audiodelays_granular_pitch_shift___exit___obj, 4, 4, audiodelays_granular_pitch_shift_obj___exit__); + + +//| semitones: synthio.BlockInput +//| """The amount of pitch shifting in semitones (1/12th of an octave).""" +//| +static mp_obj_t audiodelays_granular_pitch_shift_obj_get_semitones(mp_obj_t self_in) { + audiodelays_granular_pitch_shift_obj_t *self = MP_OBJ_TO_PTR(self_in); + return common_hal_audiodelays_granular_pitch_shift_get_semitones(self); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_granular_pitch_shift_get_semitones_obj, audiodelays_granular_pitch_shift_obj_get_semitones); + +static mp_obj_t audiodelays_granular_pitch_shift_obj_set_semitones(mp_obj_t self_in, mp_obj_t semitones_in) { + audiodelays_granular_pitch_shift_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiodelays_granular_pitch_shift_set_semitones(self, semitones_in); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiodelays_granular_pitch_shift_set_semitones_obj, audiodelays_granular_pitch_shift_obj_set_semitones); + +MP_PROPERTY_GETSET(audiodelays_granular_pitch_shift_semitones_obj, + (mp_obj_t)&audiodelays_granular_pitch_shift_get_semitones_obj, + (mp_obj_t)&audiodelays_granular_pitch_shift_set_semitones_obj); + + +//| mix: synthio.BlockInput +//| """The output mix between 0 and 1 where 0 is only sample and 1 is all effect.""" +static mp_obj_t audiodelays_granular_pitch_shift_obj_get_mix(mp_obj_t self_in) { + return common_hal_audiodelays_granular_pitch_shift_get_mix(self_in); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_granular_pitch_shift_get_mix_obj, audiodelays_granular_pitch_shift_obj_get_mix); + +static mp_obj_t audiodelays_granular_pitch_shift_obj_set_mix(mp_obj_t self_in, mp_obj_t mix_in) { + audiodelays_granular_pitch_shift_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiodelays_granular_pitch_shift_set_mix(self, mix_in); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiodelays_granular_pitch_shift_set_mix_obj, audiodelays_granular_pitch_shift_obj_set_mix); + +MP_PROPERTY_GETSET(audiodelays_granular_pitch_shift_mix_obj, + (mp_obj_t)&audiodelays_granular_pitch_shift_get_mix_obj, + (mp_obj_t)&audiodelays_granular_pitch_shift_set_mix_obj); + + +//| spread: float +//| """The amount of random jitter applied to each grain's start position, from 0.0 +//| (deterministic) to 1.0 (maximum jitter). Higher values give a thicker granular texture.""" +static mp_obj_t audiodelays_granular_pitch_shift_obj_get_spread(mp_obj_t self_in) { + audiodelays_granular_pitch_shift_obj_t *self = MP_OBJ_TO_PTR(self_in); + return mp_obj_new_float(common_hal_audiodelays_granular_pitch_shift_get_spread(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_granular_pitch_shift_get_spread_obj, audiodelays_granular_pitch_shift_obj_get_spread); + +static mp_obj_t audiodelays_granular_pitch_shift_obj_set_spread(mp_obj_t self_in, mp_obj_t spread_in) { + audiodelays_granular_pitch_shift_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiodelays_granular_pitch_shift_set_spread(self, mp_obj_get_float(spread_in)); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiodelays_granular_pitch_shift_set_spread_obj, audiodelays_granular_pitch_shift_obj_set_spread); + +MP_PROPERTY_GETSET(audiodelays_granular_pitch_shift_spread_obj, + (mp_obj_t)&audiodelays_granular_pitch_shift_get_spread_obj, + (mp_obj_t)&audiodelays_granular_pitch_shift_set_spread_obj); + + +//| playing: bool +//| """True when the effect is playing a sample. (read-only)""" +//| +static mp_obj_t audiodelays_granular_pitch_shift_obj_get_playing(mp_obj_t self_in) { + audiodelays_granular_pitch_shift_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_bool(common_hal_audiodelays_granular_pitch_shift_get_playing(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_granular_pitch_shift_get_playing_obj, audiodelays_granular_pitch_shift_obj_get_playing); + +MP_PROPERTY_GETTER(audiodelays_granular_pitch_shift_playing_obj, + (mp_obj_t)&audiodelays_granular_pitch_shift_get_playing_obj); + + +//| def play(self, sample: circuitpython_typing.AudioSample, *, loop: bool = False) -> GranularPitchShift: +//| """Plays the sample once when loop=False and continuously when loop=True. +//| Does not block. Use `playing` to block. +//| +//| The sample must match the encoding settings given in the constructor. +//| +//| :return: The effect object itself. Can be used for chaining, ie: +//| ``audio.play(effect.play(sample))``. +//| :rtype: GranularPitchShift""" +//| ... +//| +static mp_obj_t audiodelays_granular_pitch_shift_obj_play(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_sample, ARG_loop }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_sample, MP_ARG_OBJ | MP_ARG_REQUIRED, {} }, + { MP_QSTR_loop, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = false} }, + }; + audiodelays_granular_pitch_shift_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_obj_t sample = args[ARG_sample].u_obj; + common_hal_audiodelays_granular_pitch_shift_play(self, sample, args[ARG_loop].u_bool); + + return MP_OBJ_FROM_PTR(self); +} +MP_DEFINE_CONST_FUN_OBJ_KW(audiodelays_granular_pitch_shift_play_obj, 1, audiodelays_granular_pitch_shift_obj_play); + + +//| def stop(self) -> None: +//| """Stops playback of the sample.""" +//| ... +//| +//| +static mp_obj_t audiodelays_granular_pitch_shift_obj_stop(mp_obj_t self_in) { + audiodelays_granular_pitch_shift_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiodelays_granular_pitch_shift_stop(self); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_granular_pitch_shift_stop_obj, audiodelays_granular_pitch_shift_obj_stop); + + +static const mp_rom_map_elem_t audiodelays_granular_pitch_shift_locals_dict_table[] = { + // Methods + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&audiodelays_granular_pitch_shift_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&audiodelays_granular_pitch_shift_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&audiodelays_granular_pitch_shift___exit___obj) }, + { MP_ROM_QSTR(MP_QSTR_play), MP_ROM_PTR(&audiodelays_granular_pitch_shift_play_obj) }, + { MP_ROM_QSTR(MP_QSTR_stop), MP_ROM_PTR(&audiodelays_granular_pitch_shift_stop_obj) }, + + // Properties + { MP_ROM_QSTR(MP_QSTR_playing), MP_ROM_PTR(&audiodelays_granular_pitch_shift_playing_obj) }, + { MP_ROM_QSTR(MP_QSTR_semitones), MP_ROM_PTR(&audiodelays_granular_pitch_shift_semitones_obj) }, + { MP_ROM_QSTR(MP_QSTR_mix), MP_ROM_PTR(&audiodelays_granular_pitch_shift_mix_obj) }, + { MP_ROM_QSTR(MP_QSTR_spread), MP_ROM_PTR(&audiodelays_granular_pitch_shift_spread_obj) }, + AUDIOSAMPLE_FIELDS, +}; +static MP_DEFINE_CONST_DICT(audiodelays_granular_pitch_shift_locals_dict, audiodelays_granular_pitch_shift_locals_dict_table); + +static const audiosample_p_t audiodelays_granular_pitch_shift_proto = { + MP_PROTO_IMPLEMENT(MP_QSTR_protocol_audiosample) + .reset_buffer = (audiosample_reset_buffer_fun)audiodelays_granular_pitch_shift_reset_buffer, + .get_buffer = (audiosample_get_buffer_fun)audiodelays_granular_pitch_shift_get_buffer, +}; + +MP_DEFINE_CONST_OBJ_TYPE( + audiodelays_granular_pitch_shift_type, + MP_QSTR_GranularPitchShift, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, audiodelays_granular_pitch_shift_make_new, + locals_dict, &audiodelays_granular_pitch_shift_locals_dict, + protocol, &audiodelays_granular_pitch_shift_proto + ); diff --git a/shared-bindings/audiodelays/GranularPitchShift.h b/shared-bindings/audiodelays/GranularPitchShift.h new file mode 100644 index 00000000000..e5a518110bd --- /dev/null +++ b/shared-bindings/audiodelays/GranularPitchShift.h @@ -0,0 +1,31 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-module/audiodelays/GranularPitchShift.h" + +extern const mp_obj_type_t audiodelays_granular_pitch_shift_type; + +void common_hal_audiodelays_granular_pitch_shift_construct(audiodelays_granular_pitch_shift_obj_t *self, + mp_obj_t semitones, mp_obj_t mix, uint32_t grain_size, uint32_t density, + mp_float_t spread, uint32_t buffer_size, uint8_t bits_per_sample, bool samples_signed, + uint8_t channel_count, uint32_t sample_rate); + +void common_hal_audiodelays_granular_pitch_shift_deinit(audiodelays_granular_pitch_shift_obj_t *self); + +mp_obj_t common_hal_audiodelays_granular_pitch_shift_get_semitones(audiodelays_granular_pitch_shift_obj_t *self); +void common_hal_audiodelays_granular_pitch_shift_set_semitones(audiodelays_granular_pitch_shift_obj_t *self, mp_obj_t semitones); + +mp_obj_t common_hal_audiodelays_granular_pitch_shift_get_mix(audiodelays_granular_pitch_shift_obj_t *self); +void common_hal_audiodelays_granular_pitch_shift_set_mix(audiodelays_granular_pitch_shift_obj_t *self, mp_obj_t arg); + +mp_float_t common_hal_audiodelays_granular_pitch_shift_get_spread(audiodelays_granular_pitch_shift_obj_t *self); +void common_hal_audiodelays_granular_pitch_shift_set_spread(audiodelays_granular_pitch_shift_obj_t *self, mp_float_t spread); + +bool common_hal_audiodelays_granular_pitch_shift_get_playing(audiodelays_granular_pitch_shift_obj_t *self); +void common_hal_audiodelays_granular_pitch_shift_play(audiodelays_granular_pitch_shift_obj_t *self, mp_obj_t sample, bool loop); +void common_hal_audiodelays_granular_pitch_shift_stop(audiodelays_granular_pitch_shift_obj_t *self); diff --git a/shared-bindings/audiodelays/MultiTapDelay.c b/shared-bindings/audiodelays/MultiTapDelay.c new file mode 100644 index 00000000000..afac5022540 --- /dev/null +++ b/shared-bindings/audiodelays/MultiTapDelay.c @@ -0,0 +1,311 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Cooper Dalrymple +// +// SPDX-License-Identifier: MIT + +#include + +#include "shared-bindings/audiodelays/MultiTapDelay.h" +#include "shared-bindings/audiocore/__init__.h" +#include "shared-module/audiodelays/MultiTapDelay.h" + +#include "shared/runtime/context_manager_helpers.h" +#include "py/binary.h" +#include "py/objproperty.h" +#include "py/runtime.h" +#include "shared-bindings/util.h" +#include "shared-module/synthio/block.h" + +//| class MultiTapDelay: +//| """A delay with multiple buffer positions to create a rhythmic effect.""" +//| +//| def __init__( +//| self, +//| max_delay_ms: int = 500, +//| delay_ms: synthio.BlockInput = 250.0, +//| decay: synthio.BlockInput = 0.7, +//| mix: synthio.BlockInput = 0.25, +//| taps: Optional[Tuple[float|Tuple[float, float], ...]] = None, +//| buffer_size: int = 512, +//| sample_rate: int = 8000, +//| bits_per_sample: int = 16, +//| samples_signed: bool = True, +//| channel_count: int = 1, +//| ) -> None: +//| """Create a delay effect where you hear the original sample play back at varying times, or "taps". +//| These tap positions and levels can be used to create rhythmic effects. +//| The timing of the delay can be changed at runtime with the delay_ms parameter but the delay can +//| never exceed the max_delay_ms parameter. The maximum delay you can set is limited by available +//| memory. +//| +//| Each time the delay plays back the volume is reduced by the decay setting (delay * decay). +//| +//| The mix parameter allows you to change how much of the unchanged sample passes through to +//| the output to how much of the effect audio you hear as the output. +//| +//| :param int max_delay_ms: The maximum time the delay can be in milliseconds. +//| :param float delay_ms: The current time of the delay in milliseconds. Must be less than max_delay_ms. +//| :param synthio.BlockInput decay: The rate the delay fades. 0.0 = instant; 1.0 = never. +//| :param synthio.BlockInput mix: The mix as a ratio of the sample (0.0) to the effect (1.0). +//| :param tuple taps: The positions and levels to tap into the delay buffer. +//| :param int buffer_size: The total size in bytes of each of the two playback buffers to use. +//| :param int sample_rate: The sample rate to be used. +//| :param int channel_count: The number of channels the source samples contain. 1 = mono; 2 = stereo. +//| :param int bits_per_sample: The bits per sample of the effect. +//| :param bool samples_signed: Effect is signed (True) or unsigned (False). +//| +//| Playing adding a multi-tap delay to a synth:: +//| +//| import time +//| import board +//| import audiobusio +//| import synthio +//| import audiodelays +//| +//| audio = audiobusio.I2SOut(bit_clock=board.GP20, word_select=board.GP21, data=board.GP22) +//| synth = synthio.Synthesizer(channel_count=1, sample_rate=44100) +//| effect = audiodelays.MultiTapDelay(max_delay_ms=500, delay_ms=500, decay=0.65, mix=0.5, taps=((2/3, 0.7), 1), buffer_size=1024, channel_count=1, sample_rate=44100) +//| effect.play(synth) +//| audio.play(effect) +//| +//| note = synthio.Note(261) +//| while True: +//| synth.press(note) +//| time.sleep(0.05) +//| synth.release(note) +//| time.sleep(5)""" +//| ... +//| +static mp_obj_t audiodelays_multi_tap_delay_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_max_delay_ms, ARG_delay_ms, ARG_decay, ARG_mix, ARG_taps, ARG_buffer_size, ARG_sample_rate, ARG_bits_per_sample, ARG_samples_signed, ARG_channel_count, }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_max_delay_ms, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 500 } }, + { MP_QSTR_delay_ms, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_ROM_INT(250) } }, + { MP_QSTR_decay, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_mix, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_taps, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = mp_const_none} }, + { MP_QSTR_buffer_size, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 512} }, + { MP_QSTR_sample_rate, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 8000} }, + { MP_QSTR_bits_per_sample, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 16} }, + { MP_QSTR_samples_signed, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = true} }, + { MP_QSTR_channel_count, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 1 } }, + }; + + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + mp_int_t max_delay_ms = mp_arg_validate_int_range(args[ARG_max_delay_ms].u_int, 1, 4000, MP_QSTR_max_delay_ms); + + mp_int_t channel_count = mp_arg_validate_int_range(args[ARG_channel_count].u_int, 1, 2, MP_QSTR_channel_count); + mp_int_t sample_rate = mp_arg_validate_int_min(args[ARG_sample_rate].u_int, 1, MP_QSTR_sample_rate); + mp_int_t bits_per_sample = args[ARG_bits_per_sample].u_int; + if (bits_per_sample != 8 && bits_per_sample != 16) { + mp_raise_ValueError(MP_ERROR_TEXT("bits_per_sample must be 8 or 16")); + } + + audiodelays_multi_tap_delay_obj_t *self = mp_obj_malloc_with_finaliser(audiodelays_multi_tap_delay_obj_t, &audiodelays_multi_tap_delay_type); + common_hal_audiodelays_multi_tap_delay_construct(self, max_delay_ms, args[ARG_delay_ms].u_obj, args[ARG_decay].u_obj, args[ARG_mix].u_obj, args[ARG_taps].u_obj, args[ARG_buffer_size].u_int, bits_per_sample, args[ARG_samples_signed].u_bool, channel_count, sample_rate); + + return MP_OBJ_FROM_PTR(self); +} + +//| def deinit(self) -> None: +//| """Deinitialises the MultiTapDelay.""" +//| ... +//| +static mp_obj_t audiodelays_multi_tap_delay_deinit(mp_obj_t self_in) { + audiodelays_multi_tap_delay_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiodelays_multi_tap_delay_deinit(self); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_multi_tap_delay_deinit_obj, audiodelays_multi_tap_delay_deinit); + +static void check_for_deinit(audiodelays_multi_tap_delay_obj_t *self) { + audiosample_check_for_deinit(&self->base); +} + +//| def __enter__(self) -> MultiTapDelay: +//| """No-op used by Context Managers.""" +//| ... +//| +// Provided by context manager helper. + +//| def __exit__(self) -> None: +//| """Automatically deinitializes when exiting a context. See +//| :ref:`lifetime-and-contextmanagers` for more info.""" +//| ... +//| +// Provided by context manager helper. + + +//| delay_ms: float +//| """Time to delay the incoming signal in milliseconds. Must be less than max_delay_ms.""" +//| +static mp_obj_t audiodelays_multi_tap_delay_obj_get_delay_ms(mp_obj_t self_in) { + audiodelays_multi_tap_delay_obj_t *self = MP_OBJ_TO_PTR(self_in); + return mp_obj_new_float(common_hal_audiodelays_multi_tap_delay_get_delay_ms(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_multi_tap_delay_get_delay_ms_obj, audiodelays_multi_tap_delay_obj_get_delay_ms); + +static mp_obj_t audiodelays_multi_tap_delay_obj_set_delay_ms(mp_obj_t self_in, mp_obj_t delay_ms_in) { + audiodelays_multi_tap_delay_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiodelays_multi_tap_delay_set_delay_ms(self, delay_ms_in); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiodelays_multi_tap_delay_set_delay_ms_obj, audiodelays_multi_tap_delay_obj_set_delay_ms); + +MP_PROPERTY_GETSET(audiodelays_multi_tap_delay_delay_ms_obj, + (mp_obj_t)&audiodelays_multi_tap_delay_get_delay_ms_obj, + (mp_obj_t)&audiodelays_multi_tap_delay_set_delay_ms_obj); + +//| decay: synthio.BlockInput +//| """The rate the echo fades between 0 and 1 where 0 is instant and 1 is never.""" +static mp_obj_t audiodelays_multi_tap_delay_obj_get_decay(mp_obj_t self_in) { + return common_hal_audiodelays_multi_tap_delay_get_decay(self_in); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_multi_tap_delay_get_decay_obj, audiodelays_multi_tap_delay_obj_get_decay); + +static mp_obj_t audiodelays_multi_tap_delay_obj_set_decay(mp_obj_t self_in, mp_obj_t decay_in) { + audiodelays_multi_tap_delay_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiodelays_multi_tap_delay_set_decay(self, decay_in); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiodelays_multi_tap_delay_set_decay_obj, audiodelays_multi_tap_delay_obj_set_decay); + +MP_PROPERTY_GETSET(audiodelays_multi_tap_delay_decay_obj, + (mp_obj_t)&audiodelays_multi_tap_delay_get_decay_obj, + (mp_obj_t)&audiodelays_multi_tap_delay_set_decay_obj); + +//| mix: synthio.BlockInput +//| """The mix of the effect between 0 and 1 where 0 is only sample, 0.5 is an equal mix of the sample and the effect and 1 is all effect.""" +static mp_obj_t audiodelays_multi_tap_delay_obj_get_mix(mp_obj_t self_in) { + return common_hal_audiodelays_multi_tap_delay_get_mix(self_in); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_multi_tap_delay_get_mix_obj, audiodelays_multi_tap_delay_obj_get_mix); + +static mp_obj_t audiodelays_multi_tap_delay_obj_set_mix(mp_obj_t self_in, mp_obj_t mix_in) { + audiodelays_multi_tap_delay_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiodelays_multi_tap_delay_set_mix(self, mix_in); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiodelays_multi_tap_delay_set_mix_obj, audiodelays_multi_tap_delay_obj_set_mix); + +MP_PROPERTY_GETSET(audiodelays_multi_tap_delay_mix_obj, + (mp_obj_t)&audiodelays_multi_tap_delay_get_mix_obj, + (mp_obj_t)&audiodelays_multi_tap_delay_set_mix_obj); + +//| taps: Tuple[float|int|Tuple[float|int, float|int], ...] +//| """The position or position and level of delay taps. +//| The position is a number from 0 (start) to 1 (end) as a relative position in the delay buffer. +//| The level is a number from 0 (silence) to 1 (full volume). +//| If only a float or integer is provided as an element of the tuple, the level is assumed to be 1. +//| When retrieving the value of this property, the level will always be included.""" +//| +static mp_obj_t audiodelays_multi_tap_delay_obj_get_taps(mp_obj_t self_in) { + return common_hal_audiodelays_multi_tap_delay_get_taps(self_in); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_multi_tap_delay_get_taps_obj, audiodelays_multi_tap_delay_obj_get_taps); + +static mp_obj_t audiodelays_multi_tap_delay_obj_set_taps(mp_obj_t self_in, mp_obj_t taps_in) { + audiodelays_multi_tap_delay_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiodelays_multi_tap_delay_set_taps(self, taps_in); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiodelays_multi_tap_delay_set_taps_obj, audiodelays_multi_tap_delay_obj_set_taps); + +MP_PROPERTY_GETSET(audiodelays_multi_tap_delay_taps_obj, + (mp_obj_t)&audiodelays_multi_tap_delay_get_taps_obj, + (mp_obj_t)&audiodelays_multi_tap_delay_set_taps_obj); + + + +//| playing: bool +//| """True when the effect is playing a sample. (read-only)""" +//| +static mp_obj_t audiodelays_multi_tap_delay_obj_get_playing(mp_obj_t self_in) { + audiodelays_multi_tap_delay_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_bool(common_hal_audiodelays_multi_tap_delay_get_playing(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_multi_tap_delay_get_playing_obj, audiodelays_multi_tap_delay_obj_get_playing); + +MP_PROPERTY_GETTER(audiodelays_multi_tap_delay_playing_obj, + (mp_obj_t)&audiodelays_multi_tap_delay_get_playing_obj); + +//| def play(self, sample: circuitpython_typing.AudioSample, *, loop: bool = False) -> MultiTapDelay: +//| """Plays the sample once when loop=False and continuously when loop=True. +//| Does not block. Use `playing` to block. +//| +//| The sample must match the encoding settings given in the constructor. +//| +//| :return: The effect object itself. Can be used for chaining, ie: +//| ``audio.play(effect.play(sample))``. +//| :rtype: MultiTapDelay""" +//| ... +//| +static mp_obj_t audiodelays_multi_tap_delay_obj_play(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_sample, ARG_loop }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_sample, MP_ARG_OBJ | MP_ARG_REQUIRED, {} }, + { MP_QSTR_loop, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = false} }, + }; + audiodelays_multi_tap_delay_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_obj_t sample = args[ARG_sample].u_obj; + common_hal_audiodelays_multi_tap_delay_play(self, sample, args[ARG_loop].u_bool); + + return MP_OBJ_FROM_PTR(self); +} +MP_DEFINE_CONST_FUN_OBJ_KW(audiodelays_multi_tap_delay_play_obj, 1, audiodelays_multi_tap_delay_obj_play); + +//| def stop(self) -> None: +//| """Stops playback of the sample. The echo continues playing.""" +//| ... +//| +//| +static mp_obj_t audiodelays_multi_tap_delay_obj_stop(mp_obj_t self_in) { + audiodelays_multi_tap_delay_obj_t *self = MP_OBJ_TO_PTR(self_in); + + common_hal_audiodelays_multi_tap_delay_stop(self); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_multi_tap_delay_stop_obj, audiodelays_multi_tap_delay_obj_stop); + +static const mp_rom_map_elem_t audiodelays_multi_tap_delay_locals_dict_table[] = { + // Methods + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&audiodelays_multi_tap_delay_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&audiodelays_multi_tap_delay_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, + { MP_ROM_QSTR(MP_QSTR_play), MP_ROM_PTR(&audiodelays_multi_tap_delay_play_obj) }, + { MP_ROM_QSTR(MP_QSTR_stop), MP_ROM_PTR(&audiodelays_multi_tap_delay_stop_obj) }, + + // Properties + { MP_ROM_QSTR(MP_QSTR_playing), MP_ROM_PTR(&audiodelays_multi_tap_delay_playing_obj) }, + { MP_ROM_QSTR(MP_QSTR_delay_ms), MP_ROM_PTR(&audiodelays_multi_tap_delay_delay_ms_obj) }, + { MP_ROM_QSTR(MP_QSTR_decay), MP_ROM_PTR(&audiodelays_multi_tap_delay_decay_obj) }, + { MP_ROM_QSTR(MP_QSTR_mix), MP_ROM_PTR(&audiodelays_multi_tap_delay_mix_obj) }, + { MP_ROM_QSTR(MP_QSTR_taps), MP_ROM_PTR(&audiodelays_multi_tap_delay_taps_obj) }, + AUDIOSAMPLE_FIELDS, +}; +static MP_DEFINE_CONST_DICT(audiodelays_multi_tap_delay_locals_dict, audiodelays_multi_tap_delay_locals_dict_table); + +static const audiosample_p_t audiodelays_multi_tap_delay_proto = { + MP_PROTO_IMPLEMENT(MP_QSTR_protocol_audiosample) + .reset_buffer = (audiosample_reset_buffer_fun)audiodelays_multi_tap_delay_reset_buffer, + .get_buffer = (audiosample_get_buffer_fun)audiodelays_multi_tap_delay_get_buffer, +}; + +MP_DEFINE_CONST_OBJ_TYPE( + audiodelays_multi_tap_delay_type, + MP_QSTR_MultiTapDelay, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, audiodelays_multi_tap_delay_make_new, + locals_dict, &audiodelays_multi_tap_delay_locals_dict, + protocol, &audiodelays_multi_tap_delay_proto + ); diff --git a/shared-bindings/audiodelays/MultiTapDelay.h b/shared-bindings/audiodelays/MultiTapDelay.h new file mode 100644 index 00000000000..6684c16b63f --- /dev/null +++ b/shared-bindings/audiodelays/MultiTapDelay.h @@ -0,0 +1,34 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Cooper Dalrymple +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-module/audiodelays/MultiTapDelay.h" + +extern const mp_obj_type_t audiodelays_multi_tap_delay_type; + +void common_hal_audiodelays_multi_tap_delay_construct(audiodelays_multi_tap_delay_obj_t *self, uint32_t max_delay_ms, + mp_obj_t delay_ms, mp_obj_t decay, mp_obj_t mix, mp_obj_t taps, + uint32_t buffer_size, uint8_t bits_per_sample, bool samples_signed, + uint8_t channel_count, uint32_t sample_rate); + +void common_hal_audiodelays_multi_tap_delay_deinit(audiodelays_multi_tap_delay_obj_t *self); + +mp_float_t common_hal_audiodelays_multi_tap_delay_get_delay_ms(audiodelays_multi_tap_delay_obj_t *self); +void common_hal_audiodelays_multi_tap_delay_set_delay_ms(audiodelays_multi_tap_delay_obj_t *self, mp_obj_t delay_ms); + +mp_obj_t common_hal_audiodelays_multi_tap_delay_get_decay(audiodelays_multi_tap_delay_obj_t *self); +void common_hal_audiodelays_multi_tap_delay_set_decay(audiodelays_multi_tap_delay_obj_t *self, mp_obj_t decay); + +mp_obj_t common_hal_audiodelays_multi_tap_delay_get_mix(audiodelays_multi_tap_delay_obj_t *self); +void common_hal_audiodelays_multi_tap_delay_set_mix(audiodelays_multi_tap_delay_obj_t *self, mp_obj_t mix); + +mp_obj_t common_hal_audiodelays_multi_tap_delay_get_taps(audiodelays_multi_tap_delay_obj_t *self); +void common_hal_audiodelays_multi_tap_delay_set_taps(audiodelays_multi_tap_delay_obj_t *self, mp_obj_t taps); + +bool common_hal_audiodelays_multi_tap_delay_get_playing(audiodelays_multi_tap_delay_obj_t *self); +void common_hal_audiodelays_multi_tap_delay_play(audiodelays_multi_tap_delay_obj_t *self, mp_obj_t sample, bool loop); +void common_hal_audiodelays_multi_tap_delay_stop(audiodelays_multi_tap_delay_obj_t *self); diff --git a/shared-bindings/audiodelays/PitchShift.c b/shared-bindings/audiodelays/PitchShift.c index df2189945aa..098fe7a7dc3 100644 --- a/shared-bindings/audiodelays/PitchShift.c +++ b/shared-bindings/audiodelays/PitchShift.c @@ -94,8 +94,18 @@ static mp_obj_t audiodelays_pitch_shift_make_new(const mp_obj_type_t *type, size mp_raise_ValueError(MP_ERROR_TEXT("bits_per_sample must be 8 or 16")); } - audiodelays_pitch_shift_obj_t *self = mp_obj_malloc(audiodelays_pitch_shift_obj_t, &audiodelays_pitch_shift_type); - common_hal_audiodelays_pitch_shift_construct(self, args[ARG_semitones].u_obj, args[ARG_mix].u_obj, args[ARG_window].u_int, args[ARG_overlap].u_int, args[ARG_buffer_size].u_int, bits_per_sample, args[ARG_samples_signed].u_bool, channel_count, sample_rate); + audiodelays_pitch_shift_obj_t *self = + mp_obj_malloc_with_finaliser(audiodelays_pitch_shift_obj_t, &audiodelays_pitch_shift_type); + common_hal_audiodelays_pitch_shift_construct(self, + args[ARG_semitones].u_obj, + args[ARG_mix].u_obj, + args[ARG_window].u_int, + args[ARG_overlap].u_int, + args[ARG_buffer_size].u_int, + bits_per_sample, + args[ARG_samples_signed].u_bool, + channel_count, + sample_rate); return MP_OBJ_FROM_PTR(self); } @@ -176,6 +186,28 @@ MP_PROPERTY_GETSET(audiodelays_pitch_shift_mix_obj, (mp_obj_t)&audiodelays_pitch_shift_set_mix_obj); +//| freeze: bool +//| """If True, the window buffer won't accept new audio information and will be "frozen" in +//| it's current state, resulting in a sustaining tone. Normal operation is resumed when set to +//| False. If the audio buffer is reset, this value will also be reset to False.""" +static mp_obj_t audiodelays_pitch_shift_obj_get_freeze(mp_obj_t self_in) { + return mp_obj_new_bool(common_hal_audiodelays_pitch_shift_get_freeze(self_in)); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_pitch_shift_get_freeze_obj, audiodelays_pitch_shift_obj_get_freeze); + +static mp_obj_t audiodelays_pitch_shift_obj_set_freeze(mp_obj_t self_in, mp_obj_t freeze_in) { + audiodelays_pitch_shift_obj_t *self = MP_OBJ_TO_PTR(self_in); + bool freeze = mp_obj_is_true(freeze_in); + common_hal_audiodelays_pitch_shift_set_freeze(self, freeze); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiodelays_pitch_shift_set_freeze_obj, audiodelays_pitch_shift_obj_set_freeze); + +MP_PROPERTY_GETSET(audiodelays_pitch_shift_freeze_obj, + (mp_obj_t)&audiodelays_pitch_shift_get_freeze_obj, + (mp_obj_t)&audiodelays_pitch_shift_set_freeze_obj); + + //| playing: bool //| """True when the effect is playing a sample. (read-only)""" //| @@ -190,11 +222,15 @@ MP_PROPERTY_GETTER(audiodelays_pitch_shift_playing_obj, (mp_obj_t)&audiodelays_pitch_shift_get_playing_obj); -//| def play(self, sample: circuitpython_typing.AudioSample, *, loop: bool = False) -> None: +//| def play(self, sample: circuitpython_typing.AudioSample, *, loop: bool = False) -> PitchShift: //| """Plays the sample once when loop=False and continuously when loop=True. //| Does not block. Use `playing` to block. //| -//| The sample must match the encoding settings given in the constructor.""" +//| The sample must match the encoding settings given in the constructor. +//| +//| :return: The effect object itself. Can be used for chaining, ie: +//| ``audio.play(effect.play(sample))``. +//| :rtype: PitchShift""" //| ... //| static mp_obj_t audiodelays_pitch_shift_obj_play(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { @@ -211,7 +247,7 @@ static mp_obj_t audiodelays_pitch_shift_obj_play(size_t n_args, const mp_obj_t * mp_obj_t sample = args[ARG_sample].u_obj; common_hal_audiodelays_pitch_shift_play(self, sample, args[ARG_loop].u_bool); - return mp_const_none; + return MP_OBJ_FROM_PTR(self); } MP_DEFINE_CONST_FUN_OBJ_KW(audiodelays_pitch_shift_play_obj, 1, audiodelays_pitch_shift_obj_play); @@ -232,6 +268,7 @@ MP_DEFINE_CONST_FUN_OBJ_1(audiodelays_pitch_shift_stop_obj, audiodelays_pitch_sh static const mp_rom_map_elem_t audiodelays_pitch_shift_locals_dict_table[] = { // Methods { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&audiodelays_pitch_shift_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&audiodelays_pitch_shift_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&audiodelays_pitch_shift___exit___obj) }, { MP_ROM_QSTR(MP_QSTR_play), MP_ROM_PTR(&audiodelays_pitch_shift_play_obj) }, @@ -241,6 +278,7 @@ static const mp_rom_map_elem_t audiodelays_pitch_shift_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_playing), MP_ROM_PTR(&audiodelays_pitch_shift_playing_obj) }, { MP_ROM_QSTR(MP_QSTR_semitones), MP_ROM_PTR(&audiodelays_pitch_shift_semitones_obj) }, { MP_ROM_QSTR(MP_QSTR_mix), MP_ROM_PTR(&audiodelays_pitch_shift_mix_obj) }, + { MP_ROM_QSTR(MP_QSTR_freeze), MP_ROM_PTR(&audiodelays_pitch_shift_freeze_obj) }, AUDIOSAMPLE_FIELDS, }; static MP_DEFINE_CONST_DICT(audiodelays_pitch_shift_locals_dict, audiodelays_pitch_shift_locals_dict_table); diff --git a/shared-bindings/audiodelays/PitchShift.h b/shared-bindings/audiodelays/PitchShift.h index 78c78b5ea82..5544d1a0aff 100644 --- a/shared-bindings/audiodelays/PitchShift.h +++ b/shared-bindings/audiodelays/PitchShift.h @@ -23,6 +23,9 @@ void common_hal_audiodelays_pitch_shift_set_semitones(audiodelays_pitch_shift_ob mp_obj_t common_hal_audiodelays_pitch_shift_get_mix(audiodelays_pitch_shift_obj_t *self); void common_hal_audiodelays_pitch_shift_set_mix(audiodelays_pitch_shift_obj_t *self, mp_obj_t arg); +bool common_hal_audiodelays_pitch_shift_get_freeze(audiodelays_pitch_shift_obj_t *self); +void common_hal_audiodelays_pitch_shift_set_freeze(audiodelays_pitch_shift_obj_t *self, bool freeze); + bool common_hal_audiodelays_pitch_shift_get_playing(audiodelays_pitch_shift_obj_t *self); void common_hal_audiodelays_pitch_shift_play(audiodelays_pitch_shift_obj_t *self, mp_obj_t sample, bool loop); void common_hal_audiodelays_pitch_shift_stop(audiodelays_pitch_shift_obj_t *self); diff --git a/shared-bindings/audiodelays/__init__.c b/shared-bindings/audiodelays/__init__.c index 58cb9dc70a8..6ee7a82ab79 100644 --- a/shared-bindings/audiodelays/__init__.c +++ b/shared-bindings/audiodelays/__init__.c @@ -11,7 +11,11 @@ #include "shared-bindings/audiodelays/__init__.h" #include "shared-bindings/audiodelays/Echo.h" +#include "shared-bindings/audiodelays/Chorus.h" +#include "shared-bindings/audiodelays/Flanger.h" #include "shared-bindings/audiodelays/PitchShift.h" +#include "shared-bindings/audiodelays/GranularPitchShift.h" +#include "shared-bindings/audiodelays/MultiTapDelay.h" //| """Support for audio delay effects //| @@ -22,7 +26,11 @@ static const mp_rom_map_elem_t audiodelays_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_audiodelays) }, { MP_ROM_QSTR(MP_QSTR_Echo), MP_ROM_PTR(&audiodelays_echo_type) }, + { MP_ROM_QSTR(MP_QSTR_Chorus), MP_ROM_PTR(&audiodelays_chorus_type) }, + { MP_ROM_QSTR(MP_QSTR_Flanger), MP_ROM_PTR(&audiodelays_flanger_type) }, { MP_ROM_QSTR(MP_QSTR_PitchShift), MP_ROM_PTR(&audiodelays_pitch_shift_type) }, + { MP_ROM_QSTR(MP_QSTR_GranularPitchShift), MP_ROM_PTR(&audiodelays_granular_pitch_shift_type) }, + { MP_ROM_QSTR(MP_QSTR_MultiTapDelay), MP_ROM_PTR(&audiodelays_multi_tap_delay_type) }, }; static MP_DEFINE_CONST_DICT(audiodelays_module_globals, audiodelays_module_globals_table); diff --git a/shared-bindings/audiofilewriter/AudioFileWriter.c b/shared-bindings/audiofilewriter/AudioFileWriter.c new file mode 100644 index 00000000000..ea43a847feb --- /dev/null +++ b/shared-bindings/audiofilewriter/AudioFileWriter.c @@ -0,0 +1,248 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include + +#include "shared/runtime/context_manager_helpers.h" +#include "py/objproperty.h" +#include "py/runtime.h" +#include "shared-bindings/audiofilewriter/AudioFileWriter.h" +#include "shared-bindings/util.h" + +// ~1 s of 16 kHz mono 16-bit PCM. Sized to absorb a worst-case SD-write stall. +#define AUDIOFILEWRITER_DEFAULT_BUFFER_SIZE (32 * 1024) + +//| class AudioFileWriter: +//| """Streams an audio source to a ``.wav`` file in the background. +//| +//| ``AudioFileWriter`` is the inverse of `audiocore.WaveFile`: rather than being +//| an audio *source* played by an `audioio.AudioOut`, it is a *sink* that +//| drives an audio source (a microphone, ``synthio``, or an ``audiofilters``/ +//| ``audiodelays``/``audiofreeverb``/``audiospeed`` effect chain) and writes +//| the resulting PCM to a file as a WAV. +//| +//| Recording runs on a background pump paced to the source's real-time rate, +//| so it does not block and does not require a Python read loop.""" +//| +//| def __init__(self, file: Optional[typing.BinaryIO], *, buffer_size: int = 32768) -> None: +//| """Create an ``AudioFileWriter`` that writes to ``file``. +//| +//| :param typing.BinaryIO file: An already-open writable binary stream +//| (a file opened in ``"wb"`` mode, or an `io.BytesIO`). The stream must +//| support seeking so the WAV header sizes can be patched when recording +//| stops. ``AudioFileWriter`` does not close it; the caller owns it. +//| ``None`` writes nothing: the source is still played at its +//| real-time rate, and its audio is dropped. That keeps audio flowing +//| through an `audiotap.Tap` on a board with no audio output. +//| :param int buffer_size: Size in bytes of the internal RAM ring that +//| decouples file-write latency from the source. Larger values tolerate +//| longer write stalls (e.g. a slow SD card) at the cost of RAM. +//| Minimum valid value is ``512``. Must be at least the +//| size of the source buffer. Not used when ``file`` is ``None``. +//| +//| The audio format (sample rate, channel count, bit depth) is taken from +//| the source at `play()` time, so there are no format arguments here. +//| +//| Recording synthio to SD:: +//| +//| import time +//| import synthio +//| from audiofilewriter import AudioFileWriter +//| import storage +//| +//| SAMPLE_RATE = 16000 +//| OUTPUT_PATH = "/sd/demo_file.wav" +//| +//| C_major_scale = [60, 62, 64, 65, 67, 69, 71, 72, 71, 69, 67, 65, 64, 62, 60] +//| synth = synthio.Synthesizer(sample_rate=SAMPLE_RATE) +//| +//| with open(OUTPUT_PATH, "wb") as f: +//| writer = AudioFileWriter(f) +//| writer.play(synth) +//| for note in C_major_scale: +//| synth.press(note) +//| time.sleep(0.1) +//| synth.release(note) +//| time.sleep(0.10) +//| writer.stop() +//| print("Done ->", OUTPUT_PATH) +//| +//| Measuring levels on a USB microphone on the Metro ESP32-P4. +//| The ``adafruit_usb_host_descriptors`` library finds the +//| microphone and its format, and `usb.core` starts its stream; see +//| `usb_host_audio.USBIn`:: +//| +//| import time +//| +//| import adafruit_usb_host_descriptors +//| import audiotap +//| import board +//| import digitalio +//| import usb_host +//| import usb_host_audio +//| from audiofilewriter import AudioFileWriter +//| +//| # The Metro's USB host port isn't started by the board: power it and start it. +//| usb_power = digitalio.DigitalInOut(board.USB_HOST_POWER) +//| usb_power.switch_to_output(value=True) +//| usb_port = usb_host.Port(board.USB_HOST_DP, board.USB_HOST_DM) +//| +//| # Give a microphone that is already plugged in time to enumerate. +//| device = None +//| deadline = time.monotonic() + 3 +//| while device is None and time.monotonic() < deadline: +//| device = adafruit_usb_host_descriptors.find_microphone() +//| time.sleep(0.1) +//| if device is None: +//| raise RuntimeError("Plug a USB microphone or webcam into the USB host port") +//| formats = adafruit_usb_host_descriptors.find_microphone_formats(device) +//| mic_format = adafruit_usb_host_descriptors.choose_microphone_format(formats, sample_rate=48000) +//| sample_rate = mic_format.nearest_rate(48000) +//| +//| device.set_configuration() +//| # SET_INTERFACE to the format's alternate setting starts the stream, then +//| # SET_CUR of the endpoint's sampling frequency picks the rate. +//| device.ctrl_transfer(0x01, 11, mic_format.alternate, mic_format.interface, None) +//| if mic_format.rate_control: +//| device.ctrl_transfer( +//| 0x22, 0x01, 0x0100, mic_format.endpoint, sample_rate.to_bytes(3, "little") +//| ) +//| +//| mic = usb_host_audio.USBIn( +//| device, +//| mic_format.endpoint, +//| sample_rate=sample_rate, +//| channel_count=mic_format.channel_count, +//| bit_depth=8 * mic_format.bytes_per_sample, +//| samples_signed=mic_format.samples_signed, +//| max_packet_size=mic_format.max_packet_size, +//| ) +//| # The tap is only there to measure the levels, so it keeps no audio. +//| tap = audiotap.Tap(capacity=0) +//| levels = audiotap.LevelReader(tap) +//| # No file: fetch buffers through the tap at the microphone's rate and drop them. +//| sink = AudioFileWriter(None) +//| sink.play(tap.play(mic)) +//| +//| while True: +//| print(f"peak {levels.peak:.3f} rms {levels.rms:.3f}") +//| time.sleep(0.5) +//| """ +//| ... +//| +static mp_obj_t audiofilewriter_audiofilewriter_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_file, ARG_buffer_size }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_file, MP_ARG_OBJ | MP_ARG_REQUIRED, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_buffer_size, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = AUDIOFILEWRITER_DEFAULT_BUFFER_SIZE} }, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + // A buffer smaller than one source buffer is useless; require a sane floor. + mp_int_t buffer_size = mp_arg_validate_int_min(args[ARG_buffer_size].u_int, 512, MP_QSTR_buffer_size); + + audiofilewriter_audiofilewriter_obj_t *self = mp_obj_malloc_with_finaliser(audiofilewriter_audiofilewriter_obj_t, &audiofilewriter_audiofilewriter_type); + common_hal_audiofilewriter_audiofilewriter_construct(self, args[ARG_file].u_obj, (uint32_t)buffer_size); + + return MP_OBJ_FROM_PTR(self); +} + +static void check_for_deinit(audiofilewriter_audiofilewriter_obj_t *self) { + if (common_hal_audiofilewriter_audiofilewriter_deinited(self)) { + raise_deinited_error(); + } +} + +//| def deinit(self) -> None: +//| """Stops recording (patching the WAV header) and releases resources.""" +//| ... +//| +static mp_obj_t audiofilewriter_audiofilewriter_deinit(mp_obj_t self_in) { + audiofilewriter_audiofilewriter_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiofilewriter_audiofilewriter_deinit(self); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(audiofilewriter_audiofilewriter_deinit_obj, audiofilewriter_audiofilewriter_deinit); + +//| def __enter__(self) -> AudioFileWriter: +//| """No-op used by Context Managers.""" +//| ... +//| +// Provided by context manager helper. + +//| def __exit__(self) -> None: +//| """Automatically deinitializes when exiting a context. See +//| :ref:`lifetime-and-contextmanagers` for more info.""" +//| ... +//| +// Provided by context manager helper. + +//| def play(self, sample: circuitpython_typing.AudioSample) -> None: +//| """Begin recording ``sample`` to the file. Does not block. +//| +//| Writes a WAV header (in the format of ``sample``) and starts the +//| background pump. ``sample`` must be an 8-bit or 16-bit mono or stereo +//| audio source. Use `playing` to tell when a finite source has finished, +//| or call `stop()` to end recording of a continuous source (e.g. a mic).""" +//| ... +//| +static mp_obj_t audiofilewriter_audiofilewriter_obj_play(mp_obj_t self_in, mp_obj_t sample_in) { + audiofilewriter_audiofilewriter_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + common_hal_audiofilewriter_audiofilewriter_play(self, sample_in); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(audiofilewriter_audiofilewriter_play_obj, audiofilewriter_audiofilewriter_obj_play); + +//| def stop(self) -> None: +//| """Stop recording, flush the RAM ring to the file, and patch the WAV +//| header sizes. The file is left open for the caller to close.""" +//| ... +//| +static mp_obj_t audiofilewriter_audiofilewriter_obj_stop(mp_obj_t self_in) { + audiofilewriter_audiofilewriter_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + common_hal_audiofilewriter_audiofilewriter_stop(self); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(audiofilewriter_audiofilewriter_stop_obj, audiofilewriter_audiofilewriter_obj_stop); + +//| playing: bool +//| """True while recording is in progress. Becomes False on its own when a +//| finite source finishes, or after `stop()`. (read-only)""" +//| +static mp_obj_t audiofilewriter_audiofilewriter_obj_get_playing(mp_obj_t self_in) { + audiofilewriter_audiofilewriter_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_bool(common_hal_audiofilewriter_audiofilewriter_get_playing(self)); +} +static MP_DEFINE_CONST_FUN_OBJ_1(audiofilewriter_audiofilewriter_get_playing_obj, audiofilewriter_audiofilewriter_obj_get_playing); + +MP_PROPERTY_GETTER(audiofilewriter_audiofilewriter_playing_obj, + (mp_obj_t)&audiofilewriter_audiofilewriter_get_playing_obj); + +static const mp_rom_map_elem_t audiofilewriter_audiofilewriter_locals_dict_table[] = { + // Methods + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&audiofilewriter_audiofilewriter_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&audiofilewriter_audiofilewriter_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, + { MP_ROM_QSTR(MP_QSTR_play), MP_ROM_PTR(&audiofilewriter_audiofilewriter_play_obj) }, + { MP_ROM_QSTR(MP_QSTR_stop), MP_ROM_PTR(&audiofilewriter_audiofilewriter_stop_obj) }, + + // Properties + { MP_ROM_QSTR(MP_QSTR_playing), MP_ROM_PTR(&audiofilewriter_audiofilewriter_playing_obj) }, +}; +static MP_DEFINE_CONST_DICT(audiofilewriter_audiofilewriter_locals_dict, audiofilewriter_audiofilewriter_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + audiofilewriter_audiofilewriter_type, + MP_QSTR_AudioFileWriter, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, audiofilewriter_audiofilewriter_make_new, + locals_dict, &audiofilewriter_audiofilewriter_locals_dict + ); diff --git a/shared-bindings/audiofilewriter/AudioFileWriter.h b/shared-bindings/audiofilewriter/AudioFileWriter.h new file mode 100644 index 00000000000..22d456979b9 --- /dev/null +++ b/shared-bindings/audiofilewriter/AudioFileWriter.h @@ -0,0 +1,23 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +#include "shared-module/audiofilewriter/AudioFileWriter.h" + +extern const mp_obj_type_t audiofilewriter_audiofilewriter_type; + +void common_hal_audiofilewriter_audiofilewriter_construct(audiofilewriter_audiofilewriter_obj_t *self, + mp_obj_t file, uint32_t buffer_size); + +void common_hal_audiofilewriter_audiofilewriter_deinit(audiofilewriter_audiofilewriter_obj_t *self); +bool common_hal_audiofilewriter_audiofilewriter_deinited(audiofilewriter_audiofilewriter_obj_t *self); + +void common_hal_audiofilewriter_audiofilewriter_play(audiofilewriter_audiofilewriter_obj_t *self, mp_obj_t sample); +void common_hal_audiofilewriter_audiofilewriter_stop(audiofilewriter_audiofilewriter_obj_t *self); +bool common_hal_audiofilewriter_audiofilewriter_get_playing(audiofilewriter_audiofilewriter_obj_t *self); diff --git a/shared-bindings/audiofilewriter/__init__.c b/shared-bindings/audiofilewriter/__init__.c new file mode 100644 index 00000000000..e67a74b9451 --- /dev/null +++ b/shared-bindings/audiofilewriter/__init__.c @@ -0,0 +1,29 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include + +#include "py/obj.h" +#include "py/runtime.h" + +#include "shared-bindings/audiofilewriter/__init__.h" +#include "shared-bindings/audiofilewriter/AudioFileWriter.h" + +//| """Support for streaming audio to a WAV file""" + +static const mp_rom_map_elem_t audiofilewriter_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_audiofilewriter) }, + { MP_ROM_QSTR(MP_QSTR_AudioFileWriter), MP_ROM_PTR(&audiofilewriter_audiofilewriter_type) }, +}; + +static MP_DEFINE_CONST_DICT(audiofilewriter_module_globals, audiofilewriter_module_globals_table); + +const mp_obj_module_t audiofilewriter_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&audiofilewriter_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_audiofilewriter, audiofilewriter_module); diff --git a/shared-bindings/audiofilewriter/__init__.h b/shared-bindings/audiofilewriter/__init__.h new file mode 100644 index 00000000000..779b49ffd8d --- /dev/null +++ b/shared-bindings/audiofilewriter/__init__.h @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once diff --git a/shared-bindings/audiofilters/Distortion.c b/shared-bindings/audiofilters/Distortion.c index cb888d0c71b..8b15177906c 100644 --- a/shared-bindings/audiofilters/Distortion.c +++ b/shared-bindings/audiofilters/Distortion.c @@ -145,8 +145,21 @@ static mp_obj_t audiofilters_distortion_make_new(const mp_obj_type_t *type, size mode = validate_distortion_mode(args[ARG_mode].u_obj, MP_QSTR_mode); } - audiofilters_distortion_obj_t *self = mp_obj_malloc(audiofilters_distortion_obj_t, &audiofilters_distortion_type); - common_hal_audiofilters_distortion_construct(self, args[ARG_drive].u_obj, args[ARG_pre_gain].u_obj, args[ARG_post_gain].u_obj, mode, args[ARG_soft_clip].u_obj, args[ARG_mix].u_obj, args[ARG_buffer_size].u_int, bits_per_sample, args[ARG_samples_signed].u_bool, channel_count, sample_rate); + audiofilters_distortion_obj_t *self = + mp_obj_malloc_with_finaliser(audiofilters_distortion_obj_t, &audiofilters_distortion_type); + common_hal_audiofilters_distortion_construct(self, + args[ARG_drive].u_obj, + args[ARG_pre_gain].u_obj, + args[ARG_post_gain].u_obj, + mode, + args[ARG_soft_clip].u_bool, + args[ARG_mix].u_obj, + args[ARG_buffer_size].u_int, + bits_per_sample, + args[ARG_samples_signed].u_bool, + channel_count, + sample_rate); + return MP_OBJ_FROM_PTR(self); } @@ -309,11 +322,15 @@ MP_DEFINE_CONST_FUN_OBJ_1(audiofilters_distortion_get_playing_obj, audiofilters_ MP_PROPERTY_GETTER(audiofilters_distortion_playing_obj, (mp_obj_t)&audiofilters_distortion_get_playing_obj); -//| def play(self, sample: circuitpython_typing.AudioSample, *, loop: bool = False) -> None: +//| def play(self, sample: circuitpython_typing.AudioSample, *, loop: bool = False) -> Distortion: //| """Plays the sample once when loop=False and continuously when loop=True. //| Does not block. Use `playing` to block. //| -//| The sample must match the encoding settings given in the constructor.""" +//| The sample must match the encoding settings given in the constructor. +//| +//| :return: The effect object itself. Can be used for chaining, ie: +//| ``audio.play(effect.play(sample))``. +//| :rtype: Distortion""" //| ... //| static mp_obj_t audiofilters_distortion_obj_play(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { @@ -331,7 +348,7 @@ static mp_obj_t audiofilters_distortion_obj_play(size_t n_args, const mp_obj_t * mp_obj_t sample = args[ARG_sample].u_obj; common_hal_audiofilters_distortion_play(self, sample, args[ARG_loop].u_bool); - return mp_const_none; + return MP_OBJ_FROM_PTR(self); } MP_DEFINE_CONST_FUN_OBJ_KW(audiofilters_distortion_play_obj, 1, audiofilters_distortion_obj_play); @@ -351,6 +368,7 @@ MP_DEFINE_CONST_FUN_OBJ_1(audiofilters_distortion_stop_obj, audiofilters_distort static const mp_rom_map_elem_t audiofilters_distortion_locals_dict_table[] = { // Methods { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&audiofilters_distortion_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&audiofilters_distortion_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, { MP_ROM_QSTR(MP_QSTR_play), MP_ROM_PTR(&audiofilters_distortion_play_obj) }, diff --git a/shared-bindings/audiofilters/Filter.c b/shared-bindings/audiofilters/Filter.c index b88dbe9160d..c226b499bfd 100644 --- a/shared-bindings/audiofilters/Filter.c +++ b/shared-bindings/audiofilters/Filter.c @@ -17,14 +17,12 @@ #include "shared-bindings/util.h" #include "shared-module/synthio/block.h" -#define MIX_DEFAULT 1.0f - //| class Filter: //| """A Filter effect""" //| //| def __init__( //| self, -//| filter: Optional[synthio.AnyBiquad | Tuple[synthio.AnyBiquad]] = None, +//| filter: Optional[synthio.Biquad | Tuple[synthio.Biquad]] = None, //| mix: synthio.BlockInput = 1.0, //| buffer_size: int = 512, //| sample_rate: int = 8000, @@ -39,7 +37,7 @@ //| The mix parameter allows you to change how much of the unchanged sample passes through to //| the output to how much of the effect audio you hear as the output. //| -//| :param Optional[synthio.AnyBiquad|Tuple[synthio.AnyBiquad]] filter: A normalized biquad filter object or tuple of normalized biquad filter objects. The sample is processed sequentially by each filter to produce the output samples. +//| :param Optional[synthio.Biquad|Tuple[synthio.Biquad]] filter: A normalized biquad filter object or tuple of normalized biquad filter objects. The sample is processed sequentially by each filter to produce the output samples. //| :param synthio.BlockInput mix: The mix as a ratio of the sample (0.0) to the effect (1.0). //| :param int buffer_size: The total size in bytes of each of the two playback buffers to use //| :param int sample_rate: The sample rate to be used @@ -92,8 +90,15 @@ static mp_obj_t audiofilters_filter_make_new(const mp_obj_type_t *type, size_t n mp_raise_ValueError(MP_ERROR_TEXT("bits_per_sample must be 8 or 16")); } - audiofilters_filter_obj_t *self = mp_obj_malloc(audiofilters_filter_obj_t, &audiofilters_filter_type); - common_hal_audiofilters_filter_construct(self, args[ARG_filter].u_obj, args[ARG_mix].u_obj, args[ARG_buffer_size].u_int, bits_per_sample, args[ARG_samples_signed].u_bool, channel_count, sample_rate); + audiofilters_filter_obj_t *self = mp_obj_malloc_with_finaliser(audiofilters_filter_obj_t, &audiofilters_filter_type); + common_hal_audiofilters_filter_construct(self, + args[ARG_filter].u_obj, + args[ARG_mix].u_obj, + args[ARG_buffer_size].u_int, + bits_per_sample, + args[ARG_samples_signed].u_bool, + channel_count, + sample_rate); return MP_OBJ_FROM_PTR(self); } @@ -127,7 +132,7 @@ static void check_for_deinit(audiofilters_filter_obj_t *self) { // Provided by context manager helper. -//| filter: synthio.AnyBiquad | Tuple[synthio.AnyBiquad] | None +//| filter: synthio.Biquad | Tuple[synthio.Biquad] | None //| """A normalized biquad filter object or tuple of normalized biquad filter objects. The sample is processed sequentially by each filter to produce the output samples.""" //| static mp_obj_t audiofilters_filter_obj_get_filter(mp_obj_t self_in) { @@ -181,11 +186,15 @@ MP_DEFINE_CONST_FUN_OBJ_1(audiofilters_filter_get_playing_obj, audiofilters_filt MP_PROPERTY_GETTER(audiofilters_filter_playing_obj, (mp_obj_t)&audiofilters_filter_get_playing_obj); -//| def play(self, sample: circuitpython_typing.AudioSample, *, loop: bool = False) -> None: +//| def play(self, sample: circuitpython_typing.AudioSample, *, loop: bool = False) -> Filter: //| """Plays the sample once when loop=False and continuously when loop=True. //| Does not block. Use `playing` to block. //| -//| The sample must match the encoding settings given in the constructor.""" +//| The sample must match the encoding settings given in the constructor. +//| +//| :return: The effect object itself. Can be used for chaining, ie: +//| ``audio.play(effect.play(sample))``. +//| :rtype: Filter""" //| ... //| static mp_obj_t audiofilters_filter_obj_play(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { @@ -203,7 +212,7 @@ static mp_obj_t audiofilters_filter_obj_play(size_t n_args, const mp_obj_t *pos_ mp_obj_t sample = args[ARG_sample].u_obj; common_hal_audiofilters_filter_play(self, sample, args[ARG_loop].u_bool); - return mp_const_none; + return MP_OBJ_FROM_PTR(self); } MP_DEFINE_CONST_FUN_OBJ_KW(audiofilters_filter_play_obj, 1, audiofilters_filter_obj_play); @@ -223,6 +232,7 @@ MP_DEFINE_CONST_FUN_OBJ_1(audiofilters_filter_stop_obj, audiofilters_filter_obj_ static const mp_rom_map_elem_t audiofilters_filter_locals_dict_table[] = { // Methods { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&audiofilters_filter_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&audiofilters_filter_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, { MP_ROM_QSTR(MP_QSTR_play), MP_ROM_PTR(&audiofilters_filter_play_obj) }, diff --git a/shared-bindings/audiofilters/Phaser.c b/shared-bindings/audiofilters/Phaser.c new file mode 100644 index 00000000000..b9af2cbc78b --- /dev/null +++ b/shared-bindings/audiofilters/Phaser.c @@ -0,0 +1,301 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Cooper Dalrymple +// +// SPDX-License-Identifier: MIT + +#include + +#include "shared-bindings/audiofilters/Phaser.h" +#include "shared-bindings/audiocore/__init__.h" +#include "shared-module/audiofilters/Phaser.h" + +#include "shared/runtime/context_manager_helpers.h" +#include "py/binary.h" +#include "py/objproperty.h" +#include "py/runtime.h" +#include "shared-bindings/util.h" +#include "shared-module/synthio/block.h" + +//| class Phaser: +//| """A Phaser effect""" +//| +//| def __init__( +//| self, +//| frequency: synthio.BlockInput = 1000.0, +//| feedback: synthio.BlockInput = 0.7, +//| mix: synthio.BlockInput = 1.0, +//| stages: int = 6, +//| buffer_size: int = 512, +//| sample_rate: int = 8000, +//| bits_per_sample: int = 16, +//| samples_signed: bool = True, +//| channel_count: int = 1, +//| ) -> None: +//| """Create a Phaser effect where the original sample is processed through a variable +//| number of all-pass filter stages. This slightly delays the signal so that it is out +//| of phase with the original signal. When the amount of phase is modulated and mixed +//| back into the original signal with the mix parameter, it creates a distinctive +//| phasing sound. +//| +//| :param synthio.BlockInput frequency: The target frequency which is affected by the effect in hz. +//| :param int stages: The number of all-pass filters which will be applied to the signal. +//| :param synthio.BlockInput feedback: The amount that the previous output of the filters is mixed back into their input along with the unprocessed signal. +//| :param synthio.BlockInput mix: The mix as a ratio of the sample (0.0) to the effect (1.0). +//| :param int buffer_size: The total size in bytes of each of the two playback buffers to use +//| :param int sample_rate: The sample rate to be used +//| :param int channel_count: The number of channels the source samples contain. 1 = mono; 2 = stereo. +//| :param int bits_per_sample: The bits per sample of the effect +//| :param bool samples_signed: Effect is signed (True) or unsigned (False) +//| +//| Playing adding a phaser to a synth:: +//| +//| import time +//| import board +//| import audiobusio +//| import audiofilters +//| import synthio +//| +//| audio = audiobusio.I2SOut(bit_clock=board.GP20, word_select=board.GP21, data=board.GP22) +//| synth = synthio.Synthesizer(channel_count=1, sample_rate=44100) +//| effect = audiofilters.Phaser(channel_count=1, sample_rate=44100) +//| effect.frequency = synthio.LFO(offset=1000.0, scale=600.0, rate=0.5) +//| effect.play(synth) +//| audio.play(effect) +//| +//| synth.press(48)""" +//| ... +//| +static mp_obj_t audiofilters_phaser_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_frequency, ARG_feedback, ARG_mix, ARG_stages, ARG_buffer_size, ARG_sample_rate, ARG_bits_per_sample, ARG_samples_signed, ARG_channel_count, }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_frequency, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_ROM_INT(1000) } }, + { MP_QSTR_feedback, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_ROM_NONE } }, + { MP_QSTR_mix, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_ROM_INT(1)} }, + { MP_QSTR_stages, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 6 } }, + { MP_QSTR_buffer_size, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 512} }, + { MP_QSTR_sample_rate, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 8000} }, + { MP_QSTR_bits_per_sample, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 16} }, + { MP_QSTR_samples_signed, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = true} }, + { MP_QSTR_channel_count, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 1 } }, + }; + + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + mp_int_t channel_count = mp_arg_validate_int_range(args[ARG_channel_count].u_int, 1, 2, MP_QSTR_channel_count); + mp_int_t sample_rate = mp_arg_validate_int_min(args[ARG_sample_rate].u_int, 1, MP_QSTR_sample_rate); + mp_int_t bits_per_sample = args[ARG_bits_per_sample].u_int; + if (bits_per_sample != 8 && bits_per_sample != 16) { + mp_raise_ValueError(MP_ERROR_TEXT("bits_per_sample must be 8 or 16")); + } + + audiofilters_phaser_obj_t *self = mp_obj_malloc_with_finaliser(audiofilters_phaser_obj_t, &audiofilters_phaser_type); + common_hal_audiofilters_phaser_construct(self, + args[ARG_frequency].u_obj, + args[ARG_feedback].u_obj, + args[ARG_mix].u_obj, + args[ARG_stages].u_int, + args[ARG_buffer_size].u_int, + bits_per_sample, + args[ARG_samples_signed].u_bool, + channel_count, + sample_rate); + + return MP_OBJ_FROM_PTR(self); +} + +//| def deinit(self) -> None: +//| """Deinitialises the Phaser.""" +//| ... +//| +static mp_obj_t audiofilters_phaser_deinit(mp_obj_t self_in) { + audiofilters_phaser_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiofilters_phaser_deinit(self); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(audiofilters_phaser_deinit_obj, audiofilters_phaser_deinit); + +static void check_for_deinit(audiofilters_phaser_obj_t *self) { + audiosample_check_for_deinit(&self->base); +} + +//| def __enter__(self) -> Phaser: +//| """No-op used by Context Managers.""" +//| ... +//| +// Provided by context manager helper. + +//| def __exit__(self) -> None: +//| """Automatically deinitializes when exiting a context. See +//| :ref:`lifetime-and-contextmanagers` for more info.""" +//| ... +//| +// Provided by context manager helper. + + +//| frequency: synthio.BlockInput +//| """The target frequency in hertz at which the phaser is delaying the signal.""" +static mp_obj_t audiofilters_phaser_obj_get_frequency(mp_obj_t self_in) { + return common_hal_audiofilters_phaser_get_frequency(self_in); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiofilters_phaser_get_frequency_obj, audiofilters_phaser_obj_get_frequency); + +static mp_obj_t audiofilters_phaser_obj_set_frequency(mp_obj_t self_in, mp_obj_t frequency_in) { + audiofilters_phaser_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiofilters_phaser_set_frequency(self, frequency_in); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiofilters_phaser_set_frequency_obj, audiofilters_phaser_obj_set_frequency); + +MP_PROPERTY_GETSET(audiofilters_phaser_frequency_obj, + (mp_obj_t)&audiofilters_phaser_get_frequency_obj, + (mp_obj_t)&audiofilters_phaser_set_frequency_obj); + + +//| feedback: synthio.BlockInput +//| """The amount of which the incoming signal is fed back into the phasing filters from 0.1 to 0.9.""" +static mp_obj_t audiofilters_phaser_obj_get_feedback(mp_obj_t self_in) { + return common_hal_audiofilters_phaser_get_feedback(self_in); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiofilters_phaser_get_feedback_obj, audiofilters_phaser_obj_get_feedback); + +static mp_obj_t audiofilters_phaser_obj_set_feedback(mp_obj_t self_in, mp_obj_t feedback_in) { + audiofilters_phaser_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiofilters_phaser_set_feedback(self, feedback_in); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiofilters_phaser_set_feedback_obj, audiofilters_phaser_obj_set_feedback); + +MP_PROPERTY_GETSET(audiofilters_phaser_feedback_obj, + (mp_obj_t)&audiofilters_phaser_get_feedback_obj, + (mp_obj_t)&audiofilters_phaser_set_feedback_obj); + + +//| mix: synthio.BlockInput +//| """The amount that the effect signal is mixed into the output between 0 and 1 where 0 is only the original sample and 1 is all effect.""" +static mp_obj_t audiofilters_phaser_obj_get_mix(mp_obj_t self_in) { + return common_hal_audiofilters_phaser_get_mix(self_in); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiofilters_phaser_get_mix_obj, audiofilters_phaser_obj_get_mix); + +static mp_obj_t audiofilters_phaser_obj_set_mix(mp_obj_t self_in, mp_obj_t mix_in) { + audiofilters_phaser_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiofilters_phaser_set_mix(self, mix_in); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiofilters_phaser_set_mix_obj, audiofilters_phaser_obj_set_mix); + +MP_PROPERTY_GETSET(audiofilters_phaser_mix_obj, + (mp_obj_t)&audiofilters_phaser_get_mix_obj, + (mp_obj_t)&audiofilters_phaser_set_mix_obj); + + +//| stages: int +//| """The number of allpass filters to pass the signal through. More stages requires more processing but produces a more pronounced effect. Requires a minimum value of 1.""" +static mp_obj_t audiofilters_phaser_obj_get_stages(mp_obj_t self_in) { + return MP_OBJ_NEW_SMALL_INT(common_hal_audiofilters_phaser_get_stages(self_in)); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiofilters_phaser_get_stages_obj, audiofilters_phaser_obj_get_stages); + +static mp_obj_t audiofilters_phaser_obj_set_stages(mp_obj_t self_in, mp_obj_t stages_in) { + audiofilters_phaser_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiofilters_phaser_set_stages(self, mp_obj_get_int(stages_in)); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiofilters_phaser_set_stages_obj, audiofilters_phaser_obj_set_stages); + +MP_PROPERTY_GETSET(audiofilters_phaser_stages_obj, + (mp_obj_t)&audiofilters_phaser_get_stages_obj, + (mp_obj_t)&audiofilters_phaser_set_stages_obj); + + +//| playing: bool +//| """True when the effect is playing a sample. (read-only)""" +//| +static mp_obj_t audiofilters_phaser_obj_get_playing(mp_obj_t self_in) { + audiofilters_phaser_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_bool(common_hal_audiofilters_phaser_get_playing(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiofilters_phaser_get_playing_obj, audiofilters_phaser_obj_get_playing); + +MP_PROPERTY_GETTER(audiofilters_phaser_playing_obj, + (mp_obj_t)&audiofilters_phaser_get_playing_obj); + +//| def play(self, sample: circuitpython_typing.AudioSample, *, loop: bool = False) -> Phaser: +//| """Plays the sample once when loop=False and continuously when loop=True. +//| Does not block. Use `playing` to block. +//| +//| The sample must match the encoding settings given in the constructor. +//| +//| :return: The effect object itself. Can be used for chaining, ie: +//| ``audio.play(effect.play(sample))``. +//| :rtype: Phaser""" +//| ... +//| +static mp_obj_t audiofilters_phaser_obj_play(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_sample, ARG_loop }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_sample, MP_ARG_OBJ | MP_ARG_REQUIRED, {} }, + { MP_QSTR_loop, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = false} }, + }; + audiofilters_phaser_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_obj_t sample = args[ARG_sample].u_obj; + common_hal_audiofilters_phaser_play(self, sample, args[ARG_loop].u_bool); + + return MP_OBJ_FROM_PTR(self); +} +MP_DEFINE_CONST_FUN_OBJ_KW(audiofilters_phaser_play_obj, 1, audiofilters_phaser_obj_play); + +//| def stop(self) -> None: +//| """Stops playback of the sample.""" +//| ... +//| +//| +static mp_obj_t audiofilters_phaser_obj_stop(mp_obj_t self_in) { + audiofilters_phaser_obj_t *self = MP_OBJ_TO_PTR(self_in); + + common_hal_audiofilters_phaser_stop(self); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_1(audiofilters_phaser_stop_obj, audiofilters_phaser_obj_stop); + +static const mp_rom_map_elem_t audiofilters_phaser_locals_dict_table[] = { + // Methods + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&audiofilters_phaser_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&audiofilters_phaser_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, + { MP_ROM_QSTR(MP_QSTR_play), MP_ROM_PTR(&audiofilters_phaser_play_obj) }, + { MP_ROM_QSTR(MP_QSTR_stop), MP_ROM_PTR(&audiofilters_phaser_stop_obj) }, + + // Properties + { MP_ROM_QSTR(MP_QSTR_playing), MP_ROM_PTR(&audiofilters_phaser_playing_obj) }, + { MP_ROM_QSTR(MP_QSTR_frequency), MP_ROM_PTR(&audiofilters_phaser_frequency_obj) }, + { MP_ROM_QSTR(MP_QSTR_feedback), MP_ROM_PTR(&audiofilters_phaser_feedback_obj) }, + { MP_ROM_QSTR(MP_QSTR_mix), MP_ROM_PTR(&audiofilters_phaser_mix_obj) }, + { MP_ROM_QSTR(MP_QSTR_stages), MP_ROM_PTR(&audiofilters_phaser_stages_obj) }, + AUDIOSAMPLE_FIELDS, +}; +static MP_DEFINE_CONST_DICT(audiofilters_phaser_locals_dict, audiofilters_phaser_locals_dict_table); + +static const audiosample_p_t audiofilters_phaser_proto = { + MP_PROTO_IMPLEMENT(MP_QSTR_protocol_audiosample) + .reset_buffer = (audiosample_reset_buffer_fun)audiofilters_phaser_reset_buffer, + .get_buffer = (audiosample_get_buffer_fun)audiofilters_phaser_get_buffer, +}; + +MP_DEFINE_CONST_OBJ_TYPE( + audiofilters_phaser_type, + MP_QSTR_Phaser, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, audiofilters_phaser_make_new, + locals_dict, &audiofilters_phaser_locals_dict, + protocol, &audiofilters_phaser_proto + ); diff --git a/shared-bindings/audiofilters/Phaser.h b/shared-bindings/audiofilters/Phaser.h new file mode 100644 index 00000000000..dbab22f5710 --- /dev/null +++ b/shared-bindings/audiofilters/Phaser.h @@ -0,0 +1,34 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Cooper Dalrymple +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-module/audiofilters/Phaser.h" + +extern const mp_obj_type_t audiofilters_phaser_type; + +void common_hal_audiofilters_phaser_construct(audiofilters_phaser_obj_t *self, + mp_obj_t frequency, mp_obj_t feedback, mp_obj_t mix, uint8_t stages, + uint32_t buffer_size, uint8_t bits_per_sample, bool samples_signed, + uint8_t channel_count, uint32_t sample_rate); + +void common_hal_audiofilters_phaser_deinit(audiofilters_phaser_obj_t *self); + +mp_obj_t common_hal_audiofilters_phaser_get_frequency(audiofilters_phaser_obj_t *self); +void common_hal_audiofilters_phaser_set_frequency(audiofilters_phaser_obj_t *self, mp_obj_t arg); + +mp_obj_t common_hal_audiofilters_phaser_get_feedback(audiofilters_phaser_obj_t *self); +void common_hal_audiofilters_phaser_set_feedback(audiofilters_phaser_obj_t *self, mp_obj_t arg); + +mp_obj_t common_hal_audiofilters_phaser_get_mix(audiofilters_phaser_obj_t *self); +void common_hal_audiofilters_phaser_set_mix(audiofilters_phaser_obj_t *self, mp_obj_t arg); + +uint8_t common_hal_audiofilters_phaser_get_stages(audiofilters_phaser_obj_t *self); +void common_hal_audiofilters_phaser_set_stages(audiofilters_phaser_obj_t *self, uint8_t arg); + +bool common_hal_audiofilters_phaser_get_playing(audiofilters_phaser_obj_t *self); +void common_hal_audiofilters_phaser_play(audiofilters_phaser_obj_t *self, mp_obj_t sample, bool loop); +void common_hal_audiofilters_phaser_stop(audiofilters_phaser_obj_t *self); diff --git a/shared-bindings/audiofilters/__init__.c b/shared-bindings/audiofilters/__init__.c index 7a17ec655e6..ae43af9bfef 100644 --- a/shared-bindings/audiofilters/__init__.c +++ b/shared-bindings/audiofilters/__init__.c @@ -12,6 +12,7 @@ #include "shared-bindings/audiofilters/__init__.h" #include "shared-bindings/audiofilters/Distortion.h" #include "shared-bindings/audiofilters/Filter.h" +#include "shared-bindings/audiofilters/Phaser.h" //| """Support for audio filter effects //| @@ -23,6 +24,7 @@ static const mp_rom_map_elem_t audiofilters_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_audiofilters) }, { MP_ROM_QSTR(MP_QSTR_Filter), MP_ROM_PTR(&audiofilters_filter_type) }, { MP_ROM_QSTR(MP_QSTR_Distortion), MP_ROM_PTR(&audiofilters_distortion_type) }, + { MP_ROM_QSTR(MP_QSTR_Phaser), MP_ROM_PTR(&audiofilters_phaser_type) }, // Enum-like Classes. { MP_ROM_QSTR(MP_QSTR_DistortionMode), MP_ROM_PTR(&audiofilters_distortion_mode_type) }, diff --git a/shared-bindings/audiofreeverb/Freeverb.c b/shared-bindings/audiofreeverb/Freeverb.c new file mode 100644 index 00000000000..4b04a3497df --- /dev/null +++ b/shared-bindings/audiofreeverb/Freeverb.c @@ -0,0 +1,326 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Mark Komus +// +// SPDX-License-Identifier: MIT + +#include + +#include "shared-bindings/audiofreeverb/Freeverb.h" +#include "shared-bindings/audiocore/__init__.h" +#include "shared-module/audiofreeverb/Freeverb.h" + +#include "shared/runtime/context_manager_helpers.h" +#include "py/binary.h" +#include "py/objproperty.h" +#include "py/runtime.h" +#include "shared-bindings/util.h" +#include "shared-module/synthio/block.h" + +//| class Freeverb: +//| """An Freeverb effect""" +//| +//| def __init__( +//| self, +//| roomsize: synthio.BlockInput = 0.5, +//| damp: synthio.BlockInput = 0.5, +//| pre_filter: Optional[synthio.Biquad | Tuple[synthio.Biquad]] = None, +//| post_filter: Optional[synthio.Biquad | Tuple[synthio.Biquad]] = None, +//| mix: synthio.BlockInput = 0.5, +//| buffer_size: int = 512, +//| sample_rate: int = 8000, +//| bits_per_sample: int = 16, +//| samples_signed: bool = True, +//| channel_count: int = 1, +//| ) -> None: +//| """Create a Reverb effect simulating the audio taking place in a large room where you get echos +//| off of various surfaces at various times. The size of the room can be adjusted as well as how +//| much the higher frequencies get absorbed by the walls. +//| +//| The mix parameter allows you to change how much of the unchanged sample passes through to +//| the output to how much of the effect audio you hear as the output. +//| +//| :param synthio.BlockInput roomsize: The size of the room. 0.0 = smallest; 1.0 = largest. +//| :param synthio.BlockInput damp: How much the walls absorb. 0.0 = least; 1.0 = most. +//| :param Optional[synthio.Biquad|Tuple[synthio.Biquad]] pre_filter: A normalized biquad filter object or tuple of normalized biquad filter objects. The sample is processed sequentially by each "Pre-EQ" filter before being fed to the reverb effect. +//| :param Optional[synthio.Biquad|Tuple[synthio.Biquad]] post_filter: A normalized biquad filter object or tuple of normalized biquad filter objects. The output of the reverb effect is processed sequentially by each "Post-EQ" filter before being mixed with the original sample. +//| :param synthio.BlockInput mix: The mix as a ratio of the sample (0.0) to the effect (1.0). +//| :param int buffer_size: The total size in bytes of each of the two playback buffers to use +//| :param int sample_rate: The sample rate to be used +//| :param int channel_count: The number of channels the source samples contain. 1 = mono; 2 = stereo. +//| :param int bits_per_sample: The bits per sample of the effect. Freeverb requires 16 bits. +//| :param bool samples_signed: Effect is signed (True) or unsigned (False). Freeverb requires signed (True). +//| +//| Playing adding reverb to a synth:: +//| +//| import time +//| import board +//| import audiobusio +//| import synthio +//| import audiofreeverb +//| +//| audio = audiobusio.I2SOut(bit_clock=board.GP20, word_select=board.GP21, data=board.GP22) +//| synth = synthio.Synthesizer(channel_count=1, sample_rate=44100) +//| reverb = audiofreeverb.Freeverb(roomsize=0.7, damp=0.3, buffer_size=1024, channel_count=1, sample_rate=44100, mix=0.7) +//| reverb.play(synth) +//| audio.play(reverb) +//| +//| note = synthio.Note(261) +//| while True: +//| synth.press(note) +//| time.sleep(0.55) +//| synth.release(note) +//| time.sleep(5)""" +//| ... +//| +static mp_obj_t audiofreeverb_freeverb_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_roomsize, ARG_damp, ARG_pre_filter, ARG_post_filter, ARG_mix, ARG_buffer_size, ARG_sample_rate, ARG_bits_per_sample, ARG_samples_signed, ARG_channel_count, }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_roomsize, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_damp, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_pre_filter, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_ROM_NONE } }, + { MP_QSTR_post_filter, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_ROM_NONE } }, + { MP_QSTR_mix, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_buffer_size, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 512} }, + { MP_QSTR_sample_rate, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 8000} }, + { MP_QSTR_bits_per_sample, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 16} }, + { MP_QSTR_samples_signed, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = true} }, + { MP_QSTR_channel_count, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 1 } }, + }; + + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + mp_int_t channel_count = mp_arg_validate_int_range(args[ARG_channel_count].u_int, 1, 2, MP_QSTR_channel_count); + mp_int_t sample_rate = mp_arg_validate_int_min(args[ARG_sample_rate].u_int, 1, MP_QSTR_sample_rate); + if (args[ARG_samples_signed].u_bool != true) { + mp_raise_ValueError(MP_ERROR_TEXT("samples_signed must be true")); + } + mp_int_t bits_per_sample = args[ARG_bits_per_sample].u_int; + if (bits_per_sample != 16) { + mp_raise_ValueError(MP_ERROR_TEXT("bits_per_sample must be 16")); + } + + audiofreeverb_freeverb_obj_t *self = mp_obj_malloc_with_finaliser(audiofreeverb_freeverb_obj_t, &audiofreeverb_freeverb_type); + common_hal_audiofreeverb_freeverb_construct(self, args[ARG_roomsize].u_obj, args[ARG_damp].u_obj, args[ARG_pre_filter].u_obj, args[ARG_post_filter].u_obj, args[ARG_mix].u_obj, args[ARG_buffer_size].u_int, bits_per_sample, args[ARG_samples_signed].u_bool, channel_count, sample_rate); + + return MP_OBJ_FROM_PTR(self); +} + +//| def deinit(self) -> None: +//| """Deinitialises the Freeverb.""" +//| ... +//| +static mp_obj_t audiofreeverb_freeverb_deinit(mp_obj_t self_in) { + audiofreeverb_freeverb_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiofreeverb_freeverb_deinit(self); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(audiofreeverb_freeverb_deinit_obj, audiofreeverb_freeverb_deinit); + +static void check_for_deinit(audiofreeverb_freeverb_obj_t *self) { + audiosample_check_for_deinit(&self->base); +} + +//| def __enter__(self) -> Freeverb: +//| """No-op used by Context Managers.""" +//| ... +//| +// Provided by context manager helper. + +//| def __exit__(self) -> None: +//| """Automatically deinitializes when exiting a context. See +//| :ref:`lifetime-and-contextmanagers` for more info.""" +//| ... +//| +// Provided by context manager helper. + +//| roomsize: synthio.BlockInput +//| """Apparent size of the room 0.0-1.0""" +static mp_obj_t audiofreeverb_freeverb_obj_get_roomsize(mp_obj_t self_in) { + return common_hal_audiofreeverb_freeverb_get_roomsize(self_in); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiofreeverb_freeverb_get_roomsize_obj, audiofreeverb_freeverb_obj_get_roomsize); + +static mp_obj_t audiofreeverb_freeverb_obj_set_roomsize(mp_obj_t self_in, mp_obj_t roomsize) { + audiofreeverb_freeverb_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiofreeverb_freeverb_set_roomsize(self, roomsize); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiofreeverb_freeverb_set_roomsize_obj, audiofreeverb_freeverb_obj_set_roomsize); + +MP_PROPERTY_GETSET(audiofreeverb_freeverb_roomsize_obj, + (mp_obj_t)&audiofreeverb_freeverb_get_roomsize_obj, + (mp_obj_t)&audiofreeverb_freeverb_set_roomsize_obj); + +//| damp: synthio.BlockInput +//| """How much the high frequencies are dampened in the area. 0.0-1.0""" +static mp_obj_t audiofreeverb_freeverb_obj_get_damp(mp_obj_t self_in) { + return common_hal_audiofreeverb_freeverb_get_damp(self_in); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiofreeverb_freeverb_get_damp_obj, audiofreeverb_freeverb_obj_get_damp); + +static mp_obj_t audiofreeverb_freeverb_obj_set_damp(mp_obj_t self_in, mp_obj_t damp) { + audiofreeverb_freeverb_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiofreeverb_freeverb_set_damp(self, damp); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiofreeverb_freeverb_set_damp_obj, audiofreeverb_freeverb_obj_set_damp); + +MP_PROPERTY_GETSET(audiofreeverb_freeverb_damp_obj, + (mp_obj_t)&audiofreeverb_freeverb_get_damp_obj, + (mp_obj_t)&audiofreeverb_freeverb_set_damp_obj); + + +//| pre_filter: synthio.Biquad | Tuple[synthio.Biquad] | None +//| """A normalized biquad filter object or tuple of normalized biquad filter objects. The sample is processed sequentially by each "Pre-EQ" filter before being fed to the reverb effect.""" +//| +static mp_obj_t audiofreeverb_freeverb_obj_get_pre_filter(mp_obj_t self_in) { + audiofreeverb_freeverb_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return common_hal_audiofreeverb_freeverb_get_pre_filter(self); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiofreeverb_freeverb_get_pre_filter_obj, audiofreeverb_freeverb_obj_get_pre_filter); + +static mp_obj_t audiofreeverb_freeverb_obj_set_pre_filter(mp_obj_t self_in, mp_obj_t filter_in) { + audiofreeverb_freeverb_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiofreeverb_freeverb_set_pre_filter(self, filter_in); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiofreeverb_freeverb_set_pre_filter_obj, audiofreeverb_freeverb_obj_set_pre_filter); + +MP_PROPERTY_GETSET(audiofreeverb_freeverb_pre_filter_obj, + (mp_obj_t)&audiofreeverb_freeverb_get_pre_filter_obj, + (mp_obj_t)&audiofreeverb_freeverb_set_pre_filter_obj); + + +//| post_filter: synthio.Biquad | Tuple[synthio.Biquad] | None +//| """A normalized biquad filter object or tuple of normalized biquad filter objects. The output of the reverb effect is processed sequentially by each "Post-EQ" filter before being mixed with the original sample.""" +//| +static mp_obj_t audiofreeverb_freeverb_obj_get_post_filter(mp_obj_t self_in) { + audiofreeverb_freeverb_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return common_hal_audiofreeverb_freeverb_get_post_filter(self); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiofreeverb_freeverb_get_post_filter_obj, audiofreeverb_freeverb_obj_get_post_filter); + +static mp_obj_t audiofreeverb_freeverb_obj_set_post_filter(mp_obj_t self_in, mp_obj_t filter_in) { + audiofreeverb_freeverb_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiofreeverb_freeverb_set_post_filter(self, filter_in); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiofreeverb_freeverb_set_post_filter_obj, audiofreeverb_freeverb_obj_set_post_filter); + +MP_PROPERTY_GETSET(audiofreeverb_freeverb_post_filter_obj, + (mp_obj_t)&audiofreeverb_freeverb_get_post_filter_obj, + (mp_obj_t)&audiofreeverb_freeverb_set_post_filter_obj); + + +//| mix: synthio.BlockInput +//| """The rate the reverb mix between 0 and 1 where 0 is only sample and 1 is all effect.""" +static mp_obj_t audiofreeverb_freeverb_obj_get_mix(mp_obj_t self_in) { + return common_hal_audiofreeverb_freeverb_get_mix(self_in); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiofreeverb_freeverb_get_mix_obj, audiofreeverb_freeverb_obj_get_mix); + +static mp_obj_t audiofreeverb_freeverb_obj_set_mix(mp_obj_t self_in, mp_obj_t mix_in) { + audiofreeverb_freeverb_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiofreeverb_freeverb_set_mix(self, mix_in); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiofreeverb_freeverb_set_mix_obj, audiofreeverb_freeverb_obj_set_mix); + +MP_PROPERTY_GETSET(audiofreeverb_freeverb_mix_obj, + (mp_obj_t)&audiofreeverb_freeverb_get_mix_obj, + (mp_obj_t)&audiofreeverb_freeverb_set_mix_obj); + +//| playing: bool +//| """True when the effect is playing a sample. (read-only)""" +//| +static mp_obj_t audiofreeverb_freeverb_obj_get_playing(mp_obj_t self_in) { + audiofreeverb_freeverb_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_bool(common_hal_audiofreeverb_freeverb_get_playing(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiofreeverb_freeverb_get_playing_obj, audiofreeverb_freeverb_obj_get_playing); + +MP_PROPERTY_GETTER(audiofreeverb_freeverb_playing_obj, + (mp_obj_t)&audiofreeverb_freeverb_get_playing_obj); + +//| def play(self, sample: circuitpython_typing.AudioSample, *, loop: bool = False) -> Freeverb: +//| """Plays the sample once when loop=False and continuously when loop=True. +//| Does not block. Use `playing` to block. +//| +//| The sample must match the encoding settings given in the constructor. +//| +//| :return: The effect object itself. Can be used for chaining, ie: +//| ``audio.play(effect.play(sample))``. +//| :rtype: Freeverb""" +//| ... +//| +static mp_obj_t audiofreeverb_freeverb_obj_play(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_sample, ARG_loop }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_sample, MP_ARG_OBJ | MP_ARG_REQUIRED, {} }, + { MP_QSTR_loop, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = false} }, + }; + audiofreeverb_freeverb_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_obj_t sample = args[ARG_sample].u_obj; + common_hal_audiofreeverb_freeverb_play(self, sample, args[ARG_loop].u_bool); + + return MP_OBJ_FROM_PTR(self); +} +MP_DEFINE_CONST_FUN_OBJ_KW(audiofreeverb_freeverb_play_obj, 1, audiofreeverb_freeverb_obj_play); + +//| def stop(self) -> None: +//| """Stops playback of the sample. The reverb continues playing.""" +//| ... +//| +//| +static mp_obj_t audiofreeverb_freeverb_obj_stop(mp_obj_t self_in) { + audiofreeverb_freeverb_obj_t *self = MP_OBJ_TO_PTR(self_in); + + common_hal_audiofreeverb_freeverb_stop(self); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_1(audiofreeverb_freeverb_stop_obj, audiofreeverb_freeverb_obj_stop); + +static const mp_rom_map_elem_t audiofreeverb_freeverb_locals_dict_table[] = { + // Methods + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&audiofreeverb_freeverb_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&audiofreeverb_freeverb_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, + { MP_ROM_QSTR(MP_QSTR_play), MP_ROM_PTR(&audiofreeverb_freeverb_play_obj) }, + { MP_ROM_QSTR(MP_QSTR_stop), MP_ROM_PTR(&audiofreeverb_freeverb_stop_obj) }, + + // Properties + { MP_ROM_QSTR(MP_QSTR_playing), MP_ROM_PTR(&audiofreeverb_freeverb_playing_obj) }, + { MP_ROM_QSTR(MP_QSTR_roomsize), MP_ROM_PTR(&audiofreeverb_freeverb_roomsize_obj) }, + { MP_ROM_QSTR(MP_QSTR_damp), MP_ROM_PTR(&audiofreeverb_freeverb_damp_obj) }, + { MP_ROM_QSTR(MP_QSTR_pre_filter), MP_ROM_PTR(&audiofreeverb_freeverb_pre_filter_obj) }, + { MP_ROM_QSTR(MP_QSTR_post_filter), MP_ROM_PTR(&audiofreeverb_freeverb_post_filter_obj) }, + { MP_ROM_QSTR(MP_QSTR_mix), MP_ROM_PTR(&audiofreeverb_freeverb_mix_obj) }, + AUDIOSAMPLE_FIELDS, +}; +static MP_DEFINE_CONST_DICT(audiofreeverb_freeverb_locals_dict, audiofreeverb_freeverb_locals_dict_table); + +static const audiosample_p_t audiofreeverb_freeverb_proto = { + MP_PROTO_IMPLEMENT(MP_QSTR_protocol_audiosample) + .reset_buffer = (audiosample_reset_buffer_fun)audiofreeverb_freeverb_reset_buffer, + .get_buffer = (audiosample_get_buffer_fun)audiofreeverb_freeverb_get_buffer, +}; + +MP_DEFINE_CONST_OBJ_TYPE( + audiofreeverb_freeverb_type, + MP_QSTR_freeverb, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, audiofreeverb_freeverb_make_new, + locals_dict, &audiofreeverb_freeverb_locals_dict, + protocol, &audiofreeverb_freeverb_proto + ); diff --git a/shared-bindings/audiofreeverb/Freeverb.h b/shared-bindings/audiofreeverb/Freeverb.h new file mode 100644 index 00000000000..7eed9775006 --- /dev/null +++ b/shared-bindings/audiofreeverb/Freeverb.h @@ -0,0 +1,38 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Mark Komus +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-module/audiofreeverb/Freeverb.h" + +extern const mp_obj_type_t audiofreeverb_freeverb_type; + +void common_hal_audiofreeverb_freeverb_construct(audiofreeverb_freeverb_obj_t *self, + mp_obj_t roomsize, mp_obj_t damp, mp_obj_t pre_filter, mp_obj_t post_filter, mp_obj_t mix, + uint32_t buffer_size, uint8_t bits_per_sample, bool samples_signed, + uint8_t channel_count, uint32_t sample_rate); + +void common_hal_audiofreeverb_freeverb_deinit(audiofreeverb_freeverb_obj_t *self); +bool common_hal_audiofreeverb_freeverb_deinited(audiofreeverb_freeverb_obj_t *self); + +mp_obj_t common_hal_audiofreeverb_freeverb_get_roomsize(audiofreeverb_freeverb_obj_t *self); +void common_hal_audiofreeverb_freeverb_set_roomsize(audiofreeverb_freeverb_obj_t *self, mp_obj_t feedback); + +mp_obj_t common_hal_audiofreeverb_freeverb_get_damp(audiofreeverb_freeverb_obj_t *self); +void common_hal_audiofreeverb_freeverb_set_damp(audiofreeverb_freeverb_obj_t *self, mp_obj_t damp); + +mp_obj_t common_hal_audiofreeverb_freeverb_get_pre_filter(audiofreeverb_freeverb_obj_t *self); +void common_hal_audiofreeverb_freeverb_set_pre_filter(audiofreeverb_freeverb_obj_t *self, mp_obj_t arg); + +mp_obj_t common_hal_audiofreeverb_freeverb_get_post_filter(audiofreeverb_freeverb_obj_t *self); +void common_hal_audiofreeverb_freeverb_set_post_filter(audiofreeverb_freeverb_obj_t *self, mp_obj_t arg); + +mp_obj_t common_hal_audiofreeverb_freeverb_get_mix(audiofreeverb_freeverb_obj_t *self); +void common_hal_audiofreeverb_freeverb_set_mix(audiofreeverb_freeverb_obj_t *self, mp_obj_t mix); + +bool common_hal_audiofreeverb_freeverb_get_playing(audiofreeverb_freeverb_obj_t *self); +void common_hal_audiofreeverb_freeverb_play(audiofreeverb_freeverb_obj_t *self, mp_obj_t sample, bool loop); +void common_hal_audiofreeverb_freeverb_stop(audiofreeverb_freeverb_obj_t *self); diff --git a/shared-bindings/audiofreeverb/__init__.c b/shared-bindings/audiofreeverb/__init__.c new file mode 100644 index 00000000000..cb8c979c8cf --- /dev/null +++ b/shared-bindings/audiofreeverb/__init__.c @@ -0,0 +1,34 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Mark Komus +// +// SPDX-License-Identifier: MIT + +#include + +#include "py/obj.h" +#include "py/runtime.h" + +#include "shared-bindings/audiofreeverb/__init__.h" +#include "shared-bindings/audiofreeverb/Freeverb.h" + + +//| """Support for audio freeverb effect +//| +//| The `audiofreeverb` module contains classes to provide access to audio freeverb effects. +//| +//| """ + +static const mp_rom_map_elem_t audiofreeverb_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_audiofreeverb) }, + { MP_ROM_QSTR(MP_QSTR_Freeverb), MP_ROM_PTR(&audiofreeverb_freeverb_type) }, +}; + +static MP_DEFINE_CONST_DICT(audiofreeverb_module_globals, audiofreeverb_module_globals_table); + +const mp_obj_module_t audiofreeverb_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&audiofreeverb_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_audiofreeverb, audiofreeverb_module); diff --git a/shared-bindings/audiofreeverb/__init__.h b/shared-bindings/audiofreeverb/__init__.h new file mode 100644 index 00000000000..66463561f54 --- /dev/null +++ b/shared-bindings/audiofreeverb/__init__.h @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Mark Komus +// +// SPDX-License-Identifier: MIT + +#pragma once diff --git a/shared-bindings/audioi2sin/I2SIn.c b/shared-bindings/audioi2sin/I2SIn.c new file mode 100644 index 00000000000..c06c042730b --- /dev/null +++ b/shared-bindings/audioi2sin/I2SIn.c @@ -0,0 +1,362 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include + +#include "extmod/vfs_fat.h" +#include "extmod/vfs.h" +#include "shared/runtime/context_manager_helpers.h" +#include "py/binary.h" +#include "py/mphal.h" +#include "py/objproperty.h" +#include "py/runtime.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/audioi2sin/I2SIn.h" +#include "shared-bindings/audiocore/__init__.h" +#include "shared-module/audiocore/__init__.h" +#include "shared-bindings/util.h" + +//| class I2SIn: +//| """Record an input I2S audio stream from an external I2S source such as a MEMS microphone.""" +//| +//| def __init__( +//| self, +//| bit_clock: microcontroller.Pin, +//| word_select: microcontroller.Pin, +//| data: microcontroller.Pin, +//| *, +//| main_clock: Optional[microcontroller.Pin] = None, +//| sample_rate: int = 16000, +//| bit_depth: int = 16, +//| output_bit_depth: Optional[int] = None, +//| mono: bool = True, +//| left_justified: bool = False, +//| samples_signed: bool = True, +//| external_clock: bool = False, +//| ) -> None: +//| """Create an I2SIn object associated with the given pins. This allows you to +//| record audio signals from an external I2S source (e.g. an I2S MEMS microphone +//| like the SPH0645LM4H or INMP441). +//| +//| The pin signature mirrors `audiobusio.I2SOut` so users can swap classes; +//| recording parameters mirror `audiobusio.PDMIn`. +//| +//| :param ~microcontroller.Pin bit_clock: The bit clock (or serial clock) pin +//| :param ~microcontroller.Pin word_select: The word select (or left/right clock) pin +//| :param ~microcontroller.Pin data: The data input pin +//| :param ~microcontroller.Pin main_clock: The main clock pin. Not all ports support this. +//| :param int sample_rate: Target sample rate of the resulting samples. Check `sample_rate` for actual value. +//| :param int bit_depth: Number of bits per sample on the I2S bus. Must be 8, 16, 24, or +//| 32. 8-bit only supported on espressif. The destination buffer typecode is determined +//| by ``output_bit_depth`` (or ``bit_depth`` when ``output_bit_depth`` is ``None``): +//| +//| +----------------+------------------+----------------------+ +//| | samples_signed | output_bit_depth | Required typecode(s) | +//| +================+==================+======================+ +//| | True | 24 or 32 | ``'i'`` | +//| +----------------+------------------+----------------------+ +//| | True | 16 | ``'h'`` | +//| +----------------+------------------+----------------------+ +//| | True | 8 | ``'b'`` or BYTEARRAY | +//| +----------------+------------------+----------------------+ +//| | False | 24 or 32 | ``'I'`` | +//| +----------------+------------------+----------------------+ +//| | False | 16 | ``'H'`` | +//| +----------------+------------------+----------------------+ +//| | False | 8 | ``'B'`` or BYTEARRAY | +//| +----------------+------------------+----------------------+ +//| +//| Note that 24-bit samples from mics like the SPH0645LM4H / INMP441 are +//| transported in 32-bit slots, so use ``bit_depth=32`` and an ``'I'`` buffer. +//| :param int output_bit_depth: If set, recorded samples are rescaled from +//| ``bit_depth`` to this width before being written to the destination buffer +//| (8, 16, 24, or 32). Widening bit-replicates so full-scale input maps to +//| full-scale output (e.g. 16-bit ``0xFFFF`` -> 24-bit ``0xFFFFFF``); narrowing +//| arithmetic-shifts the value right (sign-preserving when ``samples_signed`` is +//| True). When ``None`` (the default) the destination buffer holds samples at +//| ``bit_depth`` (a 24-bit sample still occupies a 32-bit ``'i'``/``'I'`` slot, +//| sign-extended without rescaling). +//| :param bool mono: True when capturing a single channel of audio, captures two channels otherwise. +//| :param bool left_justified: True when data bits are aligned with the word select clock. False +//| when they are shifted by one to match classic I2S protocol. Set True for mics like the SPH0645LM4H. +//| :param bool samples_signed: Samples are signed (True) or unsigned (False). I2S mics deliver signed +//| two's-complement PCM natively; set False to have the recorded samples converted to unsigned PCM +//| (the top/sign bit is flipped, matching the WAV convention for unsigned samples). +//| :param bool external_clock: True when this object follows an externally supplied clock: +//| ``bit_clock`` and ``word_select`` are inputs driven by something else. Like an +//| `audiobusio.I2SOut` object (the clock source), or a codec, rather than generated by +//| this object. Not supported on all ports. +//| +//| In external clock mode ``bit_clock`` and ``word_select`` do not have to be sequential +//| GPIOs, and they may be shared with another I2S object. ``sample_rate`` becomes a +//| declaration rather than a measurement: the real rate is whatever the external word select +//| runs at, and `sample_rate` still reports the declared value. If the incoming clock stops, +//| `record` blocks (interruptible with Ctrl-C). +//| +//| Example, recording 16-bit mono samples from an INMP441:: +//| +//| import array +//| import audioi2sin +//| import board +//| +//| buf = array.array("h", [0] * 16000) +//| with audioi2sin.I2SIn(board.D9, board.D10, board.D11, +//| sample_rate=16000, bit_depth=16) as mic: +//| mic.record(buf, len(buf)) +//| +//| """ +//| ... +//| +static mp_obj_t audioi2sin_i2sin_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + #if !CIRCUITPY_AUDIOI2SIN + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_I2SIn); + return NULL; // Not reachable. + #else + enum { ARG_bit_clock, ARG_word_select, ARG_data, ARG_main_clock, + ARG_sample_rate, ARG_bit_depth, ARG_output_bit_depth, + ARG_mono, ARG_left_justified, ARG_samples_signed, + ARG_external_clock }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_bit_clock, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_word_select, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_data, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_main_clock, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, + { MP_QSTR_sample_rate, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 16000} }, + { MP_QSTR_bit_depth, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 16} }, + { MP_QSTR_output_bit_depth, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, + { MP_QSTR_mono, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = true} }, + { MP_QSTR_left_justified, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, + { MP_QSTR_samples_signed, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = true} }, + { MP_QSTR_external_clock, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + bool external_clock = args[ARG_external_clock].u_bool; + + // In external clock mode the clock pins are only read, so they may already + // be owned by whatever is driving them; let the port decide if the sharing + // is legal. + const mcu_pin_obj_t *bit_clock = external_clock + ? validate_obj_is_pin(args[ARG_bit_clock].u_obj, MP_QSTR_bit_clock) + : validate_obj_is_free_pin(args[ARG_bit_clock].u_obj, MP_QSTR_bit_clock); + const mcu_pin_obj_t *word_select = external_clock + ? validate_obj_is_pin(args[ARG_word_select].u_obj, MP_QSTR_word_select) + : validate_obj_is_free_pin(args[ARG_word_select].u_obj, MP_QSTR_word_select); + const mcu_pin_obj_t *data = validate_obj_is_free_pin(args[ARG_data].u_obj, MP_QSTR_data); + const mcu_pin_obj_t *main_clock = validate_obj_is_free_pin_or_none(args[ARG_main_clock].u_obj, MP_QSTR_main_clock); + + uint32_t sample_rate = (uint32_t)mp_arg_validate_int_min(args[ARG_sample_rate].u_int, 1, MP_QSTR_sample_rate); + uint8_t bit_depth = args[ARG_bit_depth].u_int; + if (bit_depth != 8 && bit_depth != 16 && bit_depth != 24 && bit_depth != 32) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("%q must be 8, 16, 24, or 32"), MP_QSTR_bit_depth); + } + uint8_t output_bit_depth; + mp_obj_t output_bit_depth_obj = args[ARG_output_bit_depth].u_obj; + if (output_bit_depth_obj == mp_const_none) { + output_bit_depth = bit_depth; + } else { + mp_int_t v = mp_obj_get_int(output_bit_depth_obj); + if (v != 8 && v != 16 && v != 24 && v != 32) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("%q must be 8, 16, 24, or 32"), MP_QSTR_output_bit_depth); + } + output_bit_depth = (uint8_t)v; + } + bool mono = args[ARG_mono].u_bool; + bool left_justified = args[ARG_left_justified].u_bool; + bool samples_signed = args[ARG_samples_signed].u_bool; + + audioi2sin_i2sin_obj_t *self = mp_obj_malloc_with_finaliser(audioi2sin_i2sin_obj_t, &audioi2sin_i2sin_type); + common_hal_audioi2sin_i2sin_construct(self, bit_clock, word_select, data, main_clock, + sample_rate, bit_depth, output_bit_depth, mono, left_justified, samples_signed, + external_clock); + + return MP_OBJ_FROM_PTR(self); + #endif +} + +#if CIRCUITPY_AUDIOI2SIN +//| def deinit(self) -> None: +//| """Deinitialises the I2SIn and releases any hardware resources for reuse.""" +//| ... +//| +static mp_obj_t audioi2sin_i2sin_deinit(mp_obj_t self_in) { + audioi2sin_i2sin_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audioi2sin_i2sin_deinit(self); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(audioi2sin_i2sin_deinit_obj, audioi2sin_i2sin_deinit); + +static void check_for_deinit(audioi2sin_i2sin_obj_t *self) { + if (common_hal_audioi2sin_i2sin_deinited(self)) { + raise_deinited_error(); + } +} + +//| def __enter__(self) -> I2SIn: +//| """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.""" +//| ... +//| +// Provided by context manager helper. + +//| def record(self, destination: WriteableBuffer, destination_length: int) -> int: +//| """Records destination_length samples to destination. This is blocking. +//| +//| :return: The number of samples recorded. If this is less than ``destination_length``, +//| some samples were missed due to processing time.""" +//| ... +//| +static mp_obj_t audioi2sin_i2sin_obj_record(mp_obj_t self_obj, mp_obj_t destination, mp_obj_t destination_length) { + audioi2sin_i2sin_obj_t *self = MP_OBJ_TO_PTR(self_obj); + check_for_deinit(self); + uint32_t length = mp_arg_validate_type_int(destination_length, MP_QSTR_length); + mp_arg_validate_length_min(length, 0, MP_QSTR_length); + + mp_buffer_info_t bufinfo; + if (mp_obj_is_fileio(destination)) { + mp_raise_NotImplementedError(MP_ERROR_TEXT("Cannot record to a file")); + } + mp_get_buffer_raise(destination, &bufinfo, MP_BUFFER_WRITE); + if (bufinfo.len / mp_binary_get_size('@', bufinfo.typecode, NULL) < length) { + mp_raise_ValueError(MP_ERROR_TEXT("Destination capacity is smaller than destination_length.")); + } + uint8_t output_bit_depth = self->base.bits_per_sample; + char error_type = ' '; + bool samples_signed = common_hal_audioi2sin_i2sin_get_samples_signed(self); + if (samples_signed) { + if ((output_bit_depth == 24 || output_bit_depth == 32) && bufinfo.typecode != 'i') { + error_type = 'i'; + } else if (output_bit_depth == 16 && bufinfo.typecode != 'h') { + error_type = 'h'; + } else if (output_bit_depth == 8 && bufinfo.typecode != 'b' && bufinfo.typecode != BYTEARRAY_TYPECODE) { + error_type = 'b'; // NOTE: Not identifying as bytearray + } + } else { + if ((output_bit_depth == 24 || output_bit_depth == 32) && bufinfo.typecode != 'I') { + error_type = 'I'; + } else if (output_bit_depth == 16 && bufinfo.typecode != 'H') { + error_type = 'H'; + } else if (output_bit_depth == 8 && bufinfo.typecode != 'B' && bufinfo.typecode != BYTEARRAY_TYPECODE) { + error_type = 'B'; + } + } + if (error_type != ' ') { + mp_raise_TypeError_varg( + MP_ERROR_TEXT("invalid destination buffer, must be an array of type: %c"), + error_type + ); + } + uint32_t length_written = + common_hal_audioi2sin_i2sin_record_to_buffer(self, bufinfo.buf, length); + return MP_OBJ_NEW_SMALL_INT(length_written); +} +MP_DEFINE_CONST_FUN_OBJ_3(audioi2sin_i2sin_record_obj, audioi2sin_i2sin_obj_record); + +//| sample_rate: int +//| """The configured (nominal) sample rate, in Hz. This is the rate reported to +//| the audio pipeline so it matches the output/consumer it is played into. The +//| true capture rate may differ from this by a fraction of a Hz due to internal +//| clock limitations.""" +//| +//| bits_per_sample: int +//| """The number of bits per sample as it is streamed through the audio pipeline. +//| (read-only)""" +//| +//| channel_count: int +//| """The number of channels (1 for mono, 2 for stereo). (read-only)""" +//| + +//| bit_depth: int +//| """The actual bit depth of the recording. (read-only)""" +//| +//| +static mp_obj_t audioi2sin_i2sin_obj_get_bit_depth(mp_obj_t self_in) { + audioi2sin_i2sin_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return MP_OBJ_NEW_SMALL_INT(common_hal_audioi2sin_i2sin_get_bit_depth(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(audioi2sin_i2sin_get_bit_depth_obj, audioi2sin_i2sin_obj_get_bit_depth); + +MP_PROPERTY_GETTER(audioi2sin_i2sin_bit_depth_obj, + (mp_obj_t)&audioi2sin_i2sin_get_bit_depth_obj); + + +//| samples_signed: bool +//| """True if recorded samples are signed PCM, False for unsigned. (read-only)""" +//| +//| +static mp_obj_t audioi2sin_i2sin_obj_get_samples_signed(mp_obj_t self_in) { + audioi2sin_i2sin_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_bool(common_hal_audioi2sin_i2sin_get_samples_signed(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(audioi2sin_i2sin_get_samples_signed_obj, audioi2sin_i2sin_obj_get_samples_signed); + +MP_PROPERTY_GETTER(audioi2sin_i2sin_samples_signed_obj, + (mp_obj_t)&audioi2sin_i2sin_get_samples_signed_obj); + + +//| overflow: bool +//| """True if samples were dropped because they were not read fast enough, +//| since the last time this was checked. (read-only) +//| +//| Reading this clears the flag, so it reports whether an overflow happened +//| in the interval since the previous read rather than at any time in the +//| past. `record` and streaming playback both set it; a streaming consumer +//| has no other way to notice it is falling behind. +//| +//| Not all ports can detect overflow; those report False always.""" +//| +//| +static mp_obj_t audioi2sin_i2sin_obj_get_overflow(mp_obj_t self_in) { + audioi2sin_i2sin_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_bool(common_hal_audioi2sin_i2sin_get_overflow(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(audioi2sin_i2sin_get_overflow_obj, audioi2sin_i2sin_obj_get_overflow); + +MP_PROPERTY_GETTER(audioi2sin_i2sin_overflow_obj, + (mp_obj_t)&audioi2sin_i2sin_get_overflow_obj); + +static const mp_rom_map_elem_t audioi2sin_i2sin_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&audioi2sin_i2sin_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&audioi2sin_i2sin_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, + { MP_ROM_QSTR(MP_QSTR_record), MP_ROM_PTR(&audioi2sin_i2sin_record_obj) }, + // sample_rate / bits_per_sample / channel_count come from the audiosample + // protocol's shared property getters. + AUDIOSAMPLE_FIELDS, + { MP_ROM_QSTR(MP_QSTR_bit_depth), MP_ROM_PTR(&audioi2sin_i2sin_bit_depth_obj) }, + { MP_ROM_QSTR(MP_QSTR_samples_signed), MP_ROM_PTR(&audioi2sin_i2sin_samples_signed_obj) }, + { MP_ROM_QSTR(MP_QSTR_overflow), MP_ROM_PTR(&audioi2sin_i2sin_overflow_obj) }, +}; +static MP_DEFINE_CONST_DICT(audioi2sin_i2sin_locals_dict, audioi2sin_i2sin_locals_dict_table); + +static const audiosample_p_t audioi2sin_i2sin_proto = { + MP_PROTO_IMPLEMENT(MP_QSTR_protocol_audiosample) + .reset_buffer = (audiosample_reset_buffer_fun)common_hal_audioi2sin_i2sin_reset_buffer, + .get_buffer = (audiosample_get_buffer_fun)common_hal_audioi2sin_i2sin_get_buffer, +}; +#endif // CIRCUITPY_AUDIOI2SIN + +MP_DEFINE_CONST_OBJ_TYPE( + audioi2sin_i2sin_type, + MP_QSTR_I2SIn, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, audioi2sin_i2sin_make_new + #if CIRCUITPY_AUDIOI2SIN + , locals_dict, &audioi2sin_i2sin_locals_dict + , protocol, &audioi2sin_i2sin_proto + #endif + ); diff --git a/shared-bindings/audioi2sin/I2SIn.h b/shared-bindings/audioi2sin/I2SIn.h new file mode 100644 index 00000000000..25f5489015d --- /dev/null +++ b/shared-bindings/audioi2sin/I2SIn.h @@ -0,0 +1,45 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-bindings/microcontroller/Pin.h" + +#if CIRCUITPY_AUDIOI2SIN +#include "common-hal/audioi2sin/I2SIn.h" +#include "shared-module/audiocore/__init__.h" +#endif + +extern const mp_obj_type_t audioi2sin_i2sin_type; + +#if CIRCUITPY_AUDIOI2SIN +void common_hal_audioi2sin_i2sin_construct(audioi2sin_i2sin_obj_t *self, + const mcu_pin_obj_t *bit_clock, const mcu_pin_obj_t *word_select, + const mcu_pin_obj_t *data, const mcu_pin_obj_t *main_clock, + uint32_t sample_rate, uint8_t bit_depth, uint8_t output_bit_depth, + bool mono, bool left_justified, bool samples_signed, + bool external_clock); +void common_hal_audioi2sin_i2sin_deinit(audioi2sin_i2sin_obj_t *self); +bool common_hal_audioi2sin_i2sin_deinited(audioi2sin_i2sin_obj_t *self); +uint32_t common_hal_audioi2sin_i2sin_record_to_buffer(audioi2sin_i2sin_obj_t *self, + void *buffer, uint32_t length); +uint8_t common_hal_audioi2sin_i2sin_get_bit_depth(audioi2sin_i2sin_obj_t *self); +uint32_t common_hal_audioi2sin_i2sin_get_sample_rate(audioi2sin_i2sin_obj_t *self); +bool common_hal_audioi2sin_i2sin_get_samples_signed(audioi2sin_i2sin_obj_t *self); +// Reads and clears the sticky "samples were dropped" flag. +bool common_hal_audioi2sin_i2sin_get_overflow(audioi2sin_i2sin_obj_t *self); + +// audiosample protocol: streaming source support. fill_buffer converts the +// frames currently available from the live mic into `buffer` (output depth, +// interleaved), padding with silence on underrun; it never blocks. +void common_hal_audioi2sin_i2sin_fill_buffer(audioi2sin_i2sin_obj_t *self, + uint8_t *buffer, uint32_t frames); +void common_hal_audioi2sin_i2sin_reset_buffer(audioi2sin_i2sin_obj_t *self, + bool single_channel_output, uint8_t channel); +audioio_get_buffer_result_t common_hal_audioi2sin_i2sin_get_buffer( + audioi2sin_i2sin_obj_t *self, bool single_channel_output, uint8_t channel, + uint8_t **buffer, uint32_t *buffer_length); +#endif diff --git a/shared-bindings/audioi2sin/__init__.c b/shared-bindings/audioi2sin/__init__.c new file mode 100644 index 00000000000..45ba16cb01a --- /dev/null +++ b/shared-bindings/audioi2sin/__init__.c @@ -0,0 +1,38 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include + +#include "py/obj.h" +#include "py/runtime.h" + +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/audioi2sin/__init__.h" +#include "shared-bindings/audioi2sin/I2SIn.h" + +//| """Support for recording audio from an I2S input source. +//| +//| The `audioi2sin` module contains the `I2SIn` class for recording audio +//| from an external I2S source such as a MEMS microphone (e.g. SPH0645LM4H +//| or INMP441). +//| +//| All classes change hardware state and should be deinitialized when they +//| are no longer needed. To do so, either call :py:meth:`!deinit` or use a +//| context manager.""" + +static const mp_rom_map_elem_t audioi2sin_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_audioi2sin) }, + { MP_ROM_QSTR(MP_QSTR_I2SIn), MP_ROM_PTR(&audioi2sin_i2sin_type) }, +}; + +static MP_DEFINE_CONST_DICT(audioi2sin_module_globals, audioi2sin_module_globals_table); + +const mp_obj_module_t audioi2sin_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&audioi2sin_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_audioi2sin, audioi2sin_module); diff --git a/shared-bindings/audioi2sin/__init__.h b/shared-bindings/audioi2sin/__init__.h new file mode 100644 index 00000000000..779b49ffd8d --- /dev/null +++ b/shared-bindings/audioi2sin/__init__.h @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once diff --git a/shared-bindings/audioio/AudioOut.c b/shared-bindings/audioio/AudioOut.c index 82aecefa370..8ea068ceb8f 100644 --- a/shared-bindings/audioio/AudioOut.c +++ b/shared-bindings/audioio/AudioOut.c @@ -103,7 +103,10 @@ static mp_obj_t audioio_audioout_make_new(const mp_obj_type_t *type, size_t n_ar // create AudioOut object from the given pin audioio_audioout_obj_t *self = mp_obj_malloc_with_finaliser(audioio_audioout_obj_t, &audioio_audioout_type); - common_hal_audioio_audioout_construct(self, left_channel_pin, right_channel_pin, args[ARG_quiescent_value].u_int); + common_hal_audioio_audioout_construct(self, + left_channel_pin, + right_channel_pin, + args[ARG_quiescent_value].u_int); return MP_OBJ_FROM_PTR(self); } diff --git a/shared-bindings/audiomixer/Mixer.c b/shared-bindings/audiomixer/Mixer.c index dda6d06bd50..ac87bb850a6 100644 --- a/shared-bindings/audiomixer/Mixer.c +++ b/shared-bindings/audiomixer/Mixer.c @@ -85,7 +85,7 @@ static mp_obj_t audiomixer_mixer_make_new(const mp_obj_type_t *type, size_t n_ar mp_raise_ValueError(MP_ERROR_TEXT("bits_per_sample must be 8 or 16")); } audiomixer_mixer_obj_t *self = - mp_obj_malloc_var(audiomixer_mixer_obj_t, voice, mp_obj_t, voice_count, &audiomixer_mixer_type); + mp_obj_malloc_var_with_finaliser(audiomixer_mixer_obj_t, voice, mp_obj_t, voice_count, &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; v < voice_count; v++) { @@ -160,13 +160,17 @@ MP_PROPERTY_GETTER(audiomixer_mixer_voice_obj, //| def play( //| self, sample: circuitpython_typing.AudioSample, *, voice: int = 0, loop: bool = False -//| ) -> None: +//| ) -> Mixer: //| """Plays the sample once when loop=False and continuously when loop=True. //| Does not block. Use `playing` to block. //| //| Sample must be an `audiocore.WaveFile`, `audiocore.RawSample`, `audiomixer.Mixer` or `audiomp3.MP3Decoder`. //| -//| The sample must match the Mixer's encoding settings given in the constructor.""" +//| The sample must match the Mixer's encoding settings given in the constructor. +//| +//| :return: The mixer object itself. Can be used for chaining, ie: +//| ``audio.play(mixer.play(sample))``. +//| :rtype: Chorus""" //| ... //| static mp_obj_t audiomixer_mixer_obj_play(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { @@ -181,15 +185,13 @@ static mp_obj_t audiomixer_mixer_obj_play(size_t n_args, const mp_obj_t *pos_arg 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); - uint8_t v = args[ARG_voice].u_int; - if (v > (self->voice_count - 1)) { - mp_arg_error_invalid(MP_QSTR_voice); - } + uint8_t v = mp_arg_validate_int_range(args[ARG_voice].u_int, 0, self->voice_count - 1, + MP_QSTR_voice); audiomixer_mixervoice_obj_t *voice = MP_OBJ_TO_PTR(self->voice[v]); mp_obj_t sample = args[ARG_sample].u_obj; common_hal_audiomixer_mixervoice_play(voice, sample, args[ARG_loop].u_bool); - return mp_const_none; + return MP_OBJ_FROM_PTR(self); } MP_DEFINE_CONST_FUN_OBJ_KW(audiomixer_mixer_play_obj, 1, audiomixer_mixer_obj_play); @@ -208,10 +210,8 @@ static mp_obj_t audiomixer_mixer_obj_stop_voice(size_t n_args, const mp_obj_t *p 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); - uint8_t v = args[ARG_voice].u_int; - if (v > (self->voice_count - 1)) { - mp_arg_error_invalid(MP_QSTR_voice); - } + uint8_t v = mp_arg_validate_int_range(args[ARG_voice].u_int, 0, self->voice_count - 1, + MP_QSTR_voice); audiomixer_mixervoice_obj_t *voice = MP_OBJ_TO_PTR(self->voice[v]); common_hal_audiomixer_mixervoice_stop(voice); return mp_const_none; @@ -222,6 +222,7 @@ MP_DEFINE_CONST_FUN_OBJ_KW(audiomixer_mixer_stop_voice_obj, 1, audiomixer_mixer_ static const mp_rom_map_elem_t audiomixer_mixer_locals_dict_table[] = { // Methods { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&audiomixer_mixer_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&audiomixer_mixer_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, { MP_ROM_QSTR(MP_QSTR_play), MP_ROM_PTR(&audiomixer_mixer_play_obj) }, diff --git a/shared-bindings/audiomixer/MixerVoice.c b/shared-bindings/audiomixer/MixerVoice.c index 90ee8777344..4957fab3884 100644 --- a/shared-bindings/audiomixer/MixerVoice.c +++ b/shared-bindings/audiomixer/MixerVoice.c @@ -29,8 +29,8 @@ // TODO: support mono or stereo voices static mp_obj_t audiomixer_mixervoice_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { mp_arg_check_num(n_args, n_kw, 0, 0, false); - audiomixer_mixervoice_obj_t *self = mp_obj_malloc(audiomixer_mixervoice_obj_t, &audiomixer_mixervoice_type); + audiomixer_mixervoice_obj_t *self = mp_obj_malloc(audiomixer_mixervoice_obj_t, &audiomixer_mixervoice_type); common_hal_audiomixer_mixervoice_construct(self); return MP_OBJ_FROM_PTR(self); @@ -81,6 +81,19 @@ static mp_obj_t audiomixer_mixervoice_obj_stop(size_t n_args, const mp_obj_t *po } MP_DEFINE_CONST_FUN_OBJ_KW(audiomixer_mixervoice_stop_obj, 1, audiomixer_mixervoice_obj_stop); +//| def end(self) -> None: +//| """ Sets looping to False if sample is playing. This allows the looped +//| sample to complete its current playback and end further looping """ +//| ... +//| +static mp_obj_t audiomixer_mixervoice_obj_end(mp_obj_t self_in) { + audiomixer_mixervoice_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiomixer_mixervoice_end(self); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_1(audiomixer_mixervoice_end_obj, audiomixer_mixervoice_obj_end); + + //| level: synthio.BlockInput //| """The volume level of a voice, as a floating point number between 0 and 1. If your board //| does not support synthio, this property will only accept a float value. @@ -101,6 +114,31 @@ MP_PROPERTY_GETSET(audiomixer_mixervoice_level_obj, (mp_obj_t)&audiomixer_mixervoice_get_level_obj, (mp_obj_t)&audiomixer_mixervoice_set_level_obj); +//| panning: synthio.BlockInput +//| """Defines the channel(s) in which the voice appears, as a floating point number between +//| -1 and 1. If your board does not support synthio, this property will only accept a float +//| value. This property is ignored if ``audiomixer.Mixer.channel_count=1``. +//| +//| -1 is left channel only, 0 is both channels, and 1 is right channel. For fractional values, +//| the note plays at full amplitude in one channel and partial amplitude in the other channel. +//| For instance -.5 plays at full amplitude in the left channel and 1/2 amplitude in the right +//| channel.""" +static mp_obj_t audiomixer_mixervoice_obj_get_panning(mp_obj_t self_in) { + return common_hal_audiomixer_mixervoice_get_panning(self_in); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiomixer_mixervoice_get_panning_obj, audiomixer_mixervoice_obj_get_panning); + +static mp_obj_t audiomixer_mixervoice_obj_set_panning(mp_obj_t self_in, mp_obj_t panning_in) { + audiomixer_mixervoice_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiomixer_mixervoice_set_panning(self, panning_in); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiomixer_mixervoice_set_panning_obj, audiomixer_mixervoice_obj_set_panning); + +MP_PROPERTY_GETSET(audiomixer_mixervoice_panning_obj, + (mp_obj_t)&audiomixer_mixervoice_get_panning_obj, + (mp_obj_t)&audiomixer_mixervoice_set_panning_obj); + //| loop: bool //| """Get or set the loop status of the currently playing sample.""" static mp_obj_t audiomixer_mixervoice_obj_get_loop(mp_obj_t self_in) { @@ -140,10 +178,12 @@ static const mp_rom_map_elem_t audiomixer_mixervoice_locals_dict_table[] = { // Methods { MP_ROM_QSTR(MP_QSTR_play), MP_ROM_PTR(&audiomixer_mixervoice_play_obj) }, { MP_ROM_QSTR(MP_QSTR_stop), MP_ROM_PTR(&audiomixer_mixervoice_stop_obj) }, + { MP_ROM_QSTR(MP_QSTR_end), MP_ROM_PTR(&audiomixer_mixervoice_end_obj) }, // Properties { MP_ROM_QSTR(MP_QSTR_playing), MP_ROM_PTR(&audiomixer_mixervoice_playing_obj) }, { MP_ROM_QSTR(MP_QSTR_level), MP_ROM_PTR(&audiomixer_mixervoice_level_obj) }, + { MP_ROM_QSTR(MP_QSTR_panning), MP_ROM_PTR(&audiomixer_mixervoice_panning_obj) }, { MP_ROM_QSTR(MP_QSTR_loop), MP_ROM_PTR(&audiomixer_mixervoice_loop_obj) }, }; static MP_DEFINE_CONST_DICT(audiomixer_mixervoice_locals_dict, audiomixer_mixervoice_locals_dict_table); diff --git a/shared-bindings/audiomixer/MixerVoice.h b/shared-bindings/audiomixer/MixerVoice.h index cf6643d995c..89c87218e7c 100644 --- a/shared-bindings/audiomixer/MixerVoice.h +++ b/shared-bindings/audiomixer/MixerVoice.h @@ -14,9 +14,13 @@ 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_reset_buffer(audiomixer_mixervoice_obj_t *self); void common_hal_audiomixer_mixervoice_stop(audiomixer_mixervoice_obj_t *self); +void common_hal_audiomixer_mixervoice_end(audiomixer_mixervoice_obj_t *self); mp_obj_t common_hal_audiomixer_mixervoice_get_level(audiomixer_mixervoice_obj_t *self); void common_hal_audiomixer_mixervoice_set_level(audiomixer_mixervoice_obj_t *self, mp_obj_t gain); +mp_obj_t common_hal_audiomixer_mixervoice_get_panning(audiomixer_mixervoice_obj_t *self); +void common_hal_audiomixer_mixervoice_set_panning(audiomixer_mixervoice_obj_t *self, mp_obj_t value); bool common_hal_audiomixer_mixervoice_get_playing(audiomixer_mixervoice_obj_t *self); diff --git a/shared-bindings/audiomp3/MP3Decoder.c b/shared-bindings/audiomp3/MP3Decoder.c index ff6c77e8572..433b308c156 100644 --- a/shared-bindings/audiomp3/MP3Decoder.c +++ b/shared-bindings/audiomp3/MP3Decoder.c @@ -91,8 +91,6 @@ static mp_obj_t audiomp3_mp3file_make_new(const mp_obj_type_t *type, size_t n_ar stream = mp_call_function_2(MP_OBJ_FROM_PTR(&mp_builtin_open_obj), stream, MP_ROM_QSTR(MP_QSTR_rb)); } - audiomp3_mp3file_obj_t *self = mp_obj_malloc_with_finaliser(audiomp3_mp3file_obj_t, &audiomp3_mp3file_type); - const mp_stream_p_t *stream_p = mp_get_stream_raise(stream, MP_STREAM_OP_READ); if (stream_p->is_text) { @@ -106,6 +104,8 @@ static mp_obj_t audiomp3_mp3file_make_new(const mp_obj_type_t *type, size_t n_ar buffer = bufinfo.buf; buffer_size = bufinfo.len; } + + audiomp3_mp3file_obj_t *self = mp_obj_malloc_with_finaliser(audiomp3_mp3file_obj_t, &audiomp3_mp3file_type); common_hal_audiomp3_mp3file_construct(self, stream, buffer, buffer_size); return MP_OBJ_FROM_PTR(self); diff --git a/shared-bindings/audiomp3/MP3Decoder.h b/shared-bindings/audiomp3/MP3Decoder.h index 0b485b4bca1..e316b061248 100644 --- a/shared-bindings/audiomp3/MP3Decoder.h +++ b/shared-bindings/audiomp3/MP3Decoder.h @@ -19,5 +19,5 @@ void common_hal_audiomp3_mp3file_construct(audiomp3_mp3file_obj_t *self, void common_hal_audiomp3_mp3file_set_file(audiomp3_mp3file_obj_t *self, mp_obj_t stream); void common_hal_audiomp3_mp3file_deinit(audiomp3_mp3file_obj_t *self); -float common_hal_audiomp3_mp3file_get_rms_level(audiomp3_mp3file_obj_t *self); +mp_float_t common_hal_audiomp3_mp3file_get_rms_level(audiomp3_mp3file_obj_t *self); uint32_t common_hal_audiomp3_mp3file_get_samples_decoded(audiomp3_mp3file_obj_t *self); diff --git a/shared-bindings/audiopwmio/PWMAudioOut.c b/shared-bindings/audiopwmio/PWMAudioOut.c index 3c961433641..5b8d071924b 100644 --- a/shared-bindings/audiopwmio/PWMAudioOut.c +++ b/shared-bindings/audiopwmio/PWMAudioOut.c @@ -100,8 +100,10 @@ static mp_obj_t audiopwmio_pwmaudioout_make_new(const mp_obj_type_t *type, size_ // create AudioOut object from the given pin // The object is created with a finaliser as some ports use these (rather than 'reset' functions) // to ensure resources are collected at interpreter shutdown. - audiopwmio_pwmaudioout_obj_t *self = mp_obj_malloc_with_finaliser(audiopwmio_pwmaudioout_obj_t, &audiopwmio_pwmaudioout_type); - common_hal_audiopwmio_pwmaudioout_construct(self, left_channel_pin, right_channel_pin, args[ARG_quiescent_value].u_int); + audiopwmio_pwmaudioout_obj_t *self = + mp_obj_malloc_with_finaliser(audiopwmio_pwmaudioout_obj_t, &audiopwmio_pwmaudioout_type); + common_hal_audiopwmio_pwmaudioout_construct(self, + left_channel_pin, right_channel_pin, args[ARG_quiescent_value].u_int); return MP_OBJ_FROM_PTR(self); } diff --git a/shared-bindings/audiospeed/Resampler.c b/shared-bindings/audiospeed/Resampler.c new file mode 100644 index 00000000000..58e2a04944a --- /dev/null +++ b/shared-bindings/audiospeed/Resampler.c @@ -0,0 +1,114 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Cooper Dalrymple +// +// SPDX-License-Identifier: MIT + +#include + +#include "shared/runtime/context_manager_helpers.h" +#include "py/objproperty.h" +#include "py/runtime.h" +#include "shared-bindings/audiospeed/Resampler.h" +#include "shared-bindings/audiocore/__init__.h" +#include "shared-bindings/util.h" +#include "shared-module/audiospeed/Resampler.h" + +//| class Resampler: +//| """Wraps an audio sample to match it to the destination sample rate.""" +//| +//| def __init__(self) -> None: +//| """Create a Resampler that wraps ``source``. +//| +//| :param audiosample source: The audio source to resample. +//| +//| Playing a wave file through a mixer with half the sample rate:: +//| +//| import board +//| import audiocore +//| import audiomixer +//| import audiospeed +//| import audioio +//| +//| wav = audiocore.WaveFile("sample.wav") +//| resampler = audiospeed.Resampler(wav) +//| mixer = audiomixer.Mixer( +//| channel_count=wav.channel_count, +//| bits_per_sample=wav.bits_per_sample, +//| sample_rate=wav.sample_rate // 2, +//| ) +//| audio = audioio.AudioOut(board.A0) +//| audio.play(mixer) +//| mixer.play(resampler) +//| """ +//| ... +//| +static mp_obj_t audiospeed_resampler_make_new(const mp_obj_type_t *type, + size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_source }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_source, MP_ARG_REQUIRED | MP_ARG_OBJ }, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + // Validate source implements audiosample protocol + mp_obj_t source = args[ARG_source].u_obj; + audiosample_check(source); + + audiospeed_resampler_obj_t *self = mp_obj_malloc_with_finaliser(audiospeed_resampler_obj_t, &audiospeed_resampler_type); + common_hal_audiospeed_resampler_construct(self, source); + return MP_OBJ_FROM_PTR(self); +} + +//| def deinit(self) -> None: +//| """Deinitialises the Resampler and releases all memory resources for reuse.""" +//| ... +//| +static mp_obj_t audiospeed_resampler_deinit(mp_obj_t self_in) { + audiospeed_resampler_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiospeed_resampler_deinit(self); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(audiospeed_resampler_deinit_obj, audiospeed_resampler_deinit); + +//| rate: float +//| """Playback speed multiplier.""" +//| +static mp_obj_t audiospeed_resampler_obj_get_rate(mp_obj_t self_in) { + audiospeed_resampler_obj_t *self = MP_OBJ_TO_PTR(self_in); + audiosample_check_for_deinit(&self->base.base); + return common_hal_audiospeed_resampler_get_rate(self); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiospeed_resampler_get_rate_obj, audiospeed_resampler_obj_get_rate); + +MP_PROPERTY_GETTER(audiospeed_resampler_rate_obj, + (mp_obj_t)&audiospeed_resampler_get_rate_obj); + +static const mp_rom_map_elem_t audiospeed_resampler_locals_dict_table[] = { + // Methods + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&audiospeed_resampler_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&audiospeed_resampler_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, + + // Properties + { MP_ROM_QSTR(MP_QSTR_rate), MP_ROM_PTR(&audiospeed_resampler_rate_obj) }, + AUDIOSAMPLE_FIELDS, +}; +static MP_DEFINE_CONST_DICT(audiospeed_resampler_locals_dict, audiospeed_resampler_locals_dict_table); + +static const audiosample_p_t audiospeed_resampler_proto = { + MP_PROTO_IMPLEMENT(MP_QSTR_protocol_audiosample) + .reset_buffer = (audiosample_reset_buffer_fun)audiospeed_resampler_reset_buffer, + .get_buffer = (audiosample_get_buffer_fun)audiospeed_resampler_get_buffer, +}; + +MP_DEFINE_CONST_OBJ_TYPE( + audiospeed_resampler_type, + MP_QSTR_Resampler, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, audiospeed_resampler_make_new, + locals_dict, &audiospeed_resampler_locals_dict, + protocol, &audiospeed_resampler_proto + ); diff --git a/shared-bindings/audiospeed/Resampler.h b/shared-bindings/audiospeed/Resampler.h new file mode 100644 index 00000000000..7a744474bd1 --- /dev/null +++ b/shared-bindings/audiospeed/Resampler.h @@ -0,0 +1,18 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Cooper Dalrymple +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-module/audiospeed/Resampler.h" + +extern const mp_obj_type_t audiospeed_resampler_type; + +void common_hal_audiospeed_resampler_construct(audiospeed_resampler_obj_t *self, mp_obj_t source); +void common_hal_audiospeed_resampler_deinit(audiospeed_resampler_obj_t *self); + +mp_obj_t common_hal_audiospeed_resampler_get_rate(audiospeed_resampler_obj_t *self); + +void audiospeed_resampler_set_sample_rate(audiospeed_resampler_obj_t *self, uint32_t sample_rate); diff --git a/shared-bindings/audiospeed/SpeedChanger.c b/shared-bindings/audiospeed/SpeedChanger.c new file mode 100644 index 00000000000..7cf8d06362c --- /dev/null +++ b/shared-bindings/audiospeed/SpeedChanger.c @@ -0,0 +1,124 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tod Kurt +// +// SPDX-License-Identifier: MIT + +#include + +#include "shared/runtime/context_manager_helpers.h" +#include "py/objproperty.h" +#include "py/runtime.h" +#include "shared-bindings/audiospeed/SpeedChanger.h" +#include "shared-bindings/audiocore/__init__.h" +#include "shared-bindings/util.h" +#include "shared-module/audiospeed/__init__.h" +#include "shared-module/audiospeed/SpeedChanger.h" + +//| class SpeedChanger: +//| """Wraps an audio sample to play it back at a different speed. +//| +//| Uses nearest-neighbor resampling with a fixed-point phase accumulator +//| for CPU-efficient variable-speed playback.""" +//| +//| def __init__(self, source: circuitpython_typing.AudioSample, rate: float = 1.0) -> None: +//| """Create a SpeedChanger that wraps ``source``. +//| +//| :param audiosample source: The audio source to resample. +//| :param float rate: Playback speed multiplier. 1.0 = normal, 2.0 = double speed, +//| 0.5 = half speed. Must be positive. +//| +//| Playing a wave file at 1.5x speed:: +//| +//| import board +//| import audiocore +//| import audiospeed +//| import audioio +//| +//| wav = audiocore.WaveFile("drum.wav") +//| fast = audiospeed.SpeedChanger(wav, rate=1.5) +//| audio = audioio.AudioOut(board.A0) +//| audio.play(fast) +//| +//| # Change speed during playback: +//| fast.rate = 2.0 # double speed +//| fast.rate = 0.5 # half speed +//| """ +//| ... +//| +static mp_obj_t audiospeed_speedchanger_make_new(const mp_obj_type_t *type, + size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_source, ARG_rate }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_source, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_rate, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} }, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + // Validate source implements audiosample protocol + mp_obj_t source = args[ARG_source].u_obj; + audiosample_check(source); + + audiospeed_speedchanger_obj_t *self = mp_obj_malloc_with_finaliser(audiospeed_speedchanger_obj_t, &audiospeed_speedchanger_type); + common_hal_audiospeed_speedchanger_construct(self, source, args[ARG_rate].u_obj); + return MP_OBJ_FROM_PTR(self); +} + +//| def deinit(self) -> None: +//| """Deinitialises the SpeedChanger and releases all memory resources for reuse.""" +//| ... +//| +static mp_obj_t audiospeed_speedchanger_deinit(mp_obj_t self_in) { + audiospeed_speedchanger_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiospeed_speedchanger_deinit(self); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(audiospeed_speedchanger_deinit_obj, audiospeed_speedchanger_deinit); + +//| rate: float +//| """Playback speed multiplier. Can be changed during playback.""" +//| +static mp_obj_t audiospeed_speedchanger_obj_get_rate(mp_obj_t self_in) { + audiospeed_speedchanger_obj_t *self = MP_OBJ_TO_PTR(self_in); + audiosample_check_for_deinit(&self->base); + return common_hal_audiospeed_speedchanger_get_rate(self); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiospeed_speedchanger_get_rate_obj, audiospeed_speedchanger_obj_get_rate); + +static mp_obj_t audiospeed_speedchanger_obj_set_rate(mp_obj_t self_in, mp_obj_t rate_obj) { + audiospeed_speedchanger_obj_t *self = MP_OBJ_TO_PTR(self_in); + audiosample_check_for_deinit(&self->base); + common_hal_audiospeed_speedchanger_set_rate(self, rate_obj); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(audiospeed_speedchanger_set_rate_obj, audiospeed_speedchanger_obj_set_rate); + +MP_PROPERTY_GETSET(audiospeed_speedchanger_rate_obj, + (mp_obj_t)&audiospeed_speedchanger_get_rate_obj, + (mp_obj_t)&audiospeed_speedchanger_set_rate_obj); + +static const mp_rom_map_elem_t audiospeed_speedchanger_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&audiospeed_speedchanger_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&audiospeed_speedchanger_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, + { MP_ROM_QSTR(MP_QSTR_rate), MP_ROM_PTR(&audiospeed_speedchanger_rate_obj) }, + AUDIOSAMPLE_FIELDS, +}; +static MP_DEFINE_CONST_DICT(audiospeed_speedchanger_locals_dict, audiospeed_speedchanger_locals_dict_table); + +static const audiosample_p_t audiospeed_speedchanger_proto = { + MP_PROTO_IMPLEMENT(MP_QSTR_protocol_audiosample) + .reset_buffer = (audiosample_reset_buffer_fun)audiospeed_speedchanger_reset_buffer, + .get_buffer = (audiosample_get_buffer_fun)audiospeed_speedchanger_get_buffer, +}; + +MP_DEFINE_CONST_OBJ_TYPE( + audiospeed_speedchanger_type, + MP_QSTR_SpeedChanger, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, audiospeed_speedchanger_make_new, + locals_dict, &audiospeed_speedchanger_locals_dict, + protocol, &audiospeed_speedchanger_proto + ); diff --git a/shared-bindings/audiospeed/SpeedChanger.h b/shared-bindings/audiospeed/SpeedChanger.h new file mode 100644 index 00000000000..bc0b166b612 --- /dev/null +++ b/shared-bindings/audiospeed/SpeedChanger.h @@ -0,0 +1,18 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tod Kurt +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-module/audiospeed/SpeedChanger.h" + +extern const mp_obj_type_t audiospeed_speedchanger_type; + +void common_hal_audiospeed_speedchanger_construct(audiospeed_speedchanger_obj_t *self, + mp_obj_t source, mp_obj_t rate_obj); +void common_hal_audiospeed_speedchanger_deinit(audiospeed_speedchanger_obj_t *self); + +void common_hal_audiospeed_speedchanger_set_rate(audiospeed_speedchanger_obj_t *self, mp_obj_t rate_obj); +mp_obj_t common_hal_audiospeed_speedchanger_get_rate(audiospeed_speedchanger_obj_t *self); diff --git a/shared-bindings/audiospeed/__init__.c b/shared-bindings/audiospeed/__init__.c new file mode 100644 index 00000000000..3eca41e6467 --- /dev/null +++ b/shared-bindings/audiospeed/__init__.c @@ -0,0 +1,30 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tod Kurt +// +// SPDX-License-Identifier: MIT + +#include + +#include "py/obj.h" +#include "py/runtime.h" + +#include "shared-bindings/audiospeed/Resampler.h" +#include "shared-bindings/audiospeed/SpeedChanger.h" + +//| """Audio processing tools""" + +static const mp_rom_map_elem_t audiospeed_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_audiospeed) }, + { MP_ROM_QSTR(MP_QSTR_Resampler), MP_ROM_PTR(&audiospeed_resampler_type) }, + { MP_ROM_QSTR(MP_QSTR_SpeedChanger), MP_ROM_PTR(&audiospeed_speedchanger_type) }, +}; + +static MP_DEFINE_CONST_DICT(audiospeed_module_globals, audiospeed_module_globals_table); + +const mp_obj_module_t audiospeed_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&audiospeed_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_audiospeed, audiospeed_module); diff --git a/shared-bindings/audiospeed/__init__.h b/shared-bindings/audiospeed/__init__.h new file mode 100644 index 00000000000..c4a52e5819d --- /dev/null +++ b/shared-bindings/audiospeed/__init__.h @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tod Kurt +// +// SPDX-License-Identifier: MIT + +#pragma once diff --git a/shared-bindings/audiotap/LevelReader.c b/shared-bindings/audiotap/LevelReader.c new file mode 100644 index 00000000000..ff856b4adc1 --- /dev/null +++ b/shared-bindings/audiotap/LevelReader.c @@ -0,0 +1,133 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include + +#include "shared-bindings/audiotap/LevelReader.h" +#include "shared-bindings/audiotap/Tap.h" + +#include "shared/runtime/context_manager_helpers.h" +#include "py/objproperty.h" +#include "py/runtime.h" +#include "shared-bindings/util.h" + +//| class LevelReader: +//| """Measures the peak and RMS levels of the audio that passes through a `Tap`""" +//| +//| def __init__(self, tap: Tap) -> None: +//| """Create a LevelReader that measures the audio passing through ``tap``. +//| +//| The levels are measured on all of the audio that passes through the +//| tap, whether or not it is read with `Tap.readinto`, so a tap made +//| with a ``capacity`` of 0 can be used for levels alone. +//| +//| A tap can have one LevelReader at a time. `deinit` it to detach it +//| from the tap. +//| +//| :param Tap tap: The tap whose audio is measured. +//| +//| """ +//| ... +//| +static mp_obj_t audiotap_levelreader_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_tap, }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_tap, MP_ARG_OBJ | MP_ARG_REQUIRED, {} }, + }; + + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + audiotap_tap_obj_t *tap = MP_OBJ_TO_PTR(mp_arg_validate_type(args[ARG_tap].u_obj, &audiotap_tap_type, MP_QSTR_tap)); + + audiotap_levelreader_obj_t *self = mp_obj_malloc(audiotap_levelreader_obj_t, &audiotap_levelreader_type); + common_hal_audiotap_levelreader_construct(self, tap); + + return MP_OBJ_FROM_PTR(self); +} + +//| def deinit(self) -> None: +//| """Detaches the LevelReader from its tap, which stops measuring levels.""" +//| ... +//| +static mp_obj_t audiotap_levelreader_deinit(mp_obj_t self_in) { + audiotap_levelreader_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiotap_levelreader_deinit(self); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(audiotap_levelreader_deinit_obj, audiotap_levelreader_deinit); + +static void check_for_deinit(audiotap_levelreader_obj_t *self) { + if (common_hal_audiotap_levelreader_deinited(self)) { + raise_deinited_error(); + } +} + +//| def __enter__(self) -> LevelReader: +//| """No-op used by Context Managers.""" +//| ... +//| +// Provided by context manager helper. + +//| def __exit__(self) -> None: +//| """Automatically deinitializes when exiting a context. See +//| :ref:`lifetime-and-contextmanagers` for more info.""" +//| ... +//| +// Provided by context manager helper. + +//| peak: float +//| """The largest magnitude of the audio that passed through the tap since +//| this was last read, from 0.0 to 1.0 of full scale. Reading this starts a +//| new measurement. 0.0 when no audio passed through. The channels of +//| stereo audio are measured together. (read-only)""" +//| +static mp_obj_t audiotap_levelreader_obj_get_peak(mp_obj_t self_in) { + audiotap_levelreader_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_float(common_hal_audiotap_levelreader_get_peak(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiotap_levelreader_get_peak_obj, audiotap_levelreader_obj_get_peak); + +MP_PROPERTY_GETTER(audiotap_levelreader_peak_obj, + (mp_obj_t)&audiotap_levelreader_get_peak_obj); + +//| rms: float +//| """The RMS level of the audio that passed through the tap since this was +//| last read, from 0.0 to 1.0 of full scale. Reading this starts a new +//| measurement, separate from `peak`'s. 0.0 when no audio passed through. +//| The channels of stereo audio are measured together. (read-only)""" +//| +//| +static mp_obj_t audiotap_levelreader_obj_get_rms(mp_obj_t self_in) { + audiotap_levelreader_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_float(common_hal_audiotap_levelreader_get_rms(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiotap_levelreader_get_rms_obj, audiotap_levelreader_obj_get_rms); + +MP_PROPERTY_GETTER(audiotap_levelreader_rms_obj, + (mp_obj_t)&audiotap_levelreader_get_rms_obj); + +static const mp_rom_map_elem_t audiotap_levelreader_locals_dict_table[] = { + // Methods + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&audiotap_levelreader_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, + + // Properties + { MP_ROM_QSTR(MP_QSTR_peak), MP_ROM_PTR(&audiotap_levelreader_peak_obj) }, + { MP_ROM_QSTR(MP_QSTR_rms), MP_ROM_PTR(&audiotap_levelreader_rms_obj) }, +}; +static MP_DEFINE_CONST_DICT(audiotap_levelreader_locals_dict, audiotap_levelreader_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + audiotap_levelreader_type, + MP_QSTR_LevelReader, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, audiotap_levelreader_make_new, + locals_dict, &audiotap_levelreader_locals_dict + ); diff --git a/shared-bindings/audiotap/LevelReader.h b/shared-bindings/audiotap/LevelReader.h new file mode 100644 index 00000000000..2a81daa3a4c --- /dev/null +++ b/shared-bindings/audiotap/LevelReader.h @@ -0,0 +1,18 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-module/audiotap/LevelReader.h" + +extern const mp_obj_type_t audiotap_levelreader_type; + +void common_hal_audiotap_levelreader_construct(audiotap_levelreader_obj_t *self, audiotap_tap_obj_t *tap); +void common_hal_audiotap_levelreader_deinit(audiotap_levelreader_obj_t *self); +bool common_hal_audiotap_levelreader_deinited(audiotap_levelreader_obj_t *self); + +mp_float_t common_hal_audiotap_levelreader_get_peak(audiotap_levelreader_obj_t *self); +mp_float_t common_hal_audiotap_levelreader_get_rms(audiotap_levelreader_obj_t *self); diff --git a/shared-bindings/audiotap/Tap.c b/shared-bindings/audiotap/Tap.c new file mode 100644 index 00000000000..5f40994b3dc --- /dev/null +++ b/shared-bindings/audiotap/Tap.c @@ -0,0 +1,326 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include + +#include "shared-bindings/audiotap/Tap.h" +#include "shared-bindings/audiocore/__init__.h" + +#include "shared/runtime/context_manager_helpers.h" +#include "py/binary.h" +#include "py/objproperty.h" +#include "py/runtime.h" +#include "shared-bindings/util.h" + +//| class Tap: +//| """Passes audio through unchanged and keeps a copy that the program can read""" +//| +//| def __init__(self, capacity: float = 0.1) -> None: +//| """Create a Tap. It plays a sample like the effects in `audiofilters` +//| and `audiodelays` do, so it can go anywhere in an audio chain. Whatever +//| plays the tap gets the sample's audio unchanged. +//| +//| As the audio passes through, the tap keeps up to ``capacity`` seconds +//| of it in a buffer, which `readinto` copies out of without waiting. +//| The program can look at the audio this way, at the point in the +//| chain where the tap is, while it plays. To measure its peak and RMS +//| levels as well, attach a `LevelReader` to the tap. +//| +//| The tap takes its sample rate, channel count, bits per sample and +//| signedness from the first sample it plays, and allocates the buffer +//| then. So `play` a sample with the tap before anything plays the tap. +//| +//| The tap only sees audio that is played through it: something, such +//| as an `audiomixer.Mixer` voice playing to an audio output, must play +//| it or a chain that it is part of. To look at audio without hearing +//| it, play it at a ``level`` of 0. When its sample is stopped or ends, +//| the tap plays silence and keeps nothing. +//| +//| When the program reads too slowly, the buffer fills up, the tap keeps +//| the audio it has and drops the newer audio until there is room +//| again, and `overflow` turns True. The audio that passes through is +//| never affected. +//| +//| :param float capacity: How many seconds of audio are kept for +//| `readinto`. 0 keeps none, for a tap that is only measured by a +//| `LevelReader`. +//| +//| Showing the level of a USB microphone while it is heard through the +//| DVI output, and keeping the audio for a spectrum display. The +//| ``adafruit_usb_host_descriptors`` library finds the microphone and +//| its format, and `usb.core` starts its stream; see +//| `usb_host_audio.USBIn`. DVI audio plays at 32, 44.1 or 48 kHz, so an +//| `audiospeed.Resampler` converts other sample rates:: +//| +//| import array +//| import time +//| +//| import adafruit_usb_host_descriptors +//| import audiomixer +//| import audiospeed +//| import audiotap +//| import displayio +//| import supervisor +//| import usb_host_audio +//| import vectorio +//| +//| device = adafruit_usb_host_descriptors.find_microphone() +//| if device is None: +//| raise RuntimeError("Plug a USB microphone or webcam into the USB host port") +//| formats = adafruit_usb_host_descriptors.find_microphone_formats(device) +//| mic_format = adafruit_usb_host_descriptors.choose_microphone_format(formats, sample_rate=48000) +//| sample_rate = mic_format.nearest_rate(48000) +//| +//| device.set_configuration() +//| # SET_INTERFACE to the format's alternate setting starts the stream, then +//| # SET_CUR of the endpoint's sampling frequency picks the rate. +//| device.ctrl_transfer(0x01, 11, mic_format.alternate, mic_format.interface, None) +//| if mic_format.rate_control: +//| device.ctrl_transfer( +//| 0x22, 0x01, 0x0100, mic_format.endpoint, sample_rate.to_bytes(3, "little") +//| ) +//| +//| mic = usb_host_audio.USBIn( +//| device, +//| mic_format.endpoint, +//| sample_rate=sample_rate, +//| channel_count=mic_format.channel_count, +//| bit_depth=8 * mic_format.bytes_per_sample, +//| samples_signed=mic_format.samples_signed, +//| max_packet_size=mic_format.max_packet_size, +//| ) +//| # Keep a quarter second, more than arrives between reads of the loop below. +//| tap = audiotap.Tap(capacity=0.25) +//| levels = audiotap.LevelReader(tap) +//| mixer = audiomixer.Mixer(voice_count=1, sample_rate=48000, channel_count=mic.channel_count) +//| supervisor.runtime.audio.play(mixer) +//| mixer.voice[0].play(audiospeed.Resampler(tap.play(mic))) +//| +//| # Bars for the peak (top) and RMS (bottom) levels. Showing them hides the +//| # console, whose scrolling stalls the microphone's stream. print() still +//| # goes to the serial console. +//| display = supervisor.runtime.display +//| palette = displayio.Palette(1) +//| palette[0] = 0x00FF00 +//| peak_bar = vectorio.Rectangle(pixel_shader=palette, width=1, height=40, x=0, y=60) +//| rms_bar = vectorio.Rectangle(pixel_shader=palette, width=1, height=40, x=0, y=140) +//| meter = displayio.Group() +//| meter.append(peak_bar) +//| meter.append(rms_bar) +//| display.root_group = meter +//| +//| samples = array.array("h", [0] * 1024) +//| while True: +//| # Read the audio that is waiting. A spectrum display would use these samples. +//| while tap.available >= len(samples): +//| tap.readinto(samples) +//| peak = levels.peak +//| rms = levels.rms +//| peak_bar.width = max(1, int(peak * display.width)) +//| rms_bar.width = max(1, int(rms * display.width)) +//| print(f"peak {peak:.3f} rms {rms:.3f}") +//| time.sleep(0.1)""" +//| ... +//| +static mp_obj_t audiotap_tap_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_capacity, }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_capacity, MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, + }; + + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + mp_float_t capacity = (args[ARG_capacity].u_obj == MP_OBJ_NULL) + ? MICROPY_FLOAT_CONST(0.1) + : mp_obj_get_float(args[ARG_capacity].u_obj); + mp_arg_validate_float_range(capacity, 0, 60, MP_QSTR_capacity); + + audiotap_tap_obj_t *self = mp_obj_malloc_with_finaliser(audiotap_tap_obj_t, &audiotap_tap_type); + common_hal_audiotap_tap_construct(self, capacity); + + return MP_OBJ_FROM_PTR(self); +} + +//| def deinit(self) -> None: +//| """Deinitialises the Tap.""" +//| ... +//| +static mp_obj_t audiotap_tap_deinit(mp_obj_t self_in) { + audiotap_tap_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_audiotap_tap_deinit(self); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(audiotap_tap_deinit_obj, audiotap_tap_deinit); + +static void check_for_deinit(audiotap_tap_obj_t *self) { + audiosample_check_for_deinit(&self->base); +} + +//| def __enter__(self) -> Tap: +//| """No-op used by Context Managers.""" +//| ... +//| +// Provided by context manager helper. + +//| def __exit__(self) -> None: +//| """Automatically deinitializes when exiting a context. See +//| :ref:`lifetime-and-contextmanagers` for more info.""" +//| ... +//| +// Provided by context manager helper. + +//| playing: bool +//| """True when the tap is playing a sample. (read-only)""" +//| +static mp_obj_t audiotap_tap_obj_get_playing(mp_obj_t self_in) { + audiotap_tap_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_bool(common_hal_audiotap_tap_get_playing(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiotap_tap_get_playing_obj, audiotap_tap_obj_get_playing); + +MP_PROPERTY_GETTER(audiotap_tap_playing_obj, + (mp_obj_t)&audiotap_tap_get_playing_obj); + +//| available: int +//| """The number of samples waiting to be read with `readinto`. (read-only)""" +//| +static mp_obj_t audiotap_tap_obj_get_available(mp_obj_t self_in) { + audiotap_tap_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_int_from_uint(common_hal_audiotap_tap_get_available(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiotap_tap_get_available_obj, audiotap_tap_obj_get_available); + +MP_PROPERTY_GETTER(audiotap_tap_available_obj, + (mp_obj_t)&audiotap_tap_get_available_obj); + +//| overflow: bool +//| """True if audio was dropped since the last time this was checked, +//| because `readinto` did not keep up. Reading this clears it. (read-only)""" +//| +static mp_obj_t audiotap_tap_obj_get_overflow(mp_obj_t self_in) { + audiotap_tap_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_bool(common_hal_audiotap_tap_get_overflow(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(audiotap_tap_get_overflow_obj, audiotap_tap_obj_get_overflow); + +MP_PROPERTY_GETTER(audiotap_tap_overflow_obj, + (mp_obj_t)&audiotap_tap_get_overflow_obj); + +//| def readinto(self, buffer: WriteableBuffer) -> int: +//| """Copies the oldest audio waiting into ``buffer`` and returns the number +//| of samples copied, which is 0 when none is waiting. Does not wait for +//| audio. Copies whole frames only: a stereo frame is two samples, left +//| then right. +//| +//| The samples are copied as they are played, so ``buffer`` is +//| usually an ``array.array`` of typecode ``'h'`` for 16 bit signed +//| samples. A ``bytearray`` works for any format and holds half as +//| many 16 bit samples as its length. To read into part of a buffer, +//| pass a slice of a ``memoryview`` of it.""" +//| ... +//| +static mp_obj_t audiotap_tap_obj_readinto(mp_obj_t self_in, mp_obj_t buffer_in) { + audiotap_tap_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(buffer_in, &bufinfo, MP_BUFFER_WRITE); + uint32_t length = bufinfo.len / (self->base.bits_per_sample / 8); + return mp_obj_new_int_from_uint(common_hal_audiotap_tap_readinto(self, bufinfo.buf, length)); +} +MP_DEFINE_CONST_FUN_OBJ_2(audiotap_tap_readinto_obj, audiotap_tap_obj_readinto); + +//| def clear(self) -> None: +//| """Discards the audio waiting, so that `readinto` returns only audio +//| that passes through after this. Use it to skip ahead to the live +//| audio, for example after an `overflow`.""" +//| ... +//| +static mp_obj_t audiotap_tap_obj_clear(mp_obj_t self_in) { + audiotap_tap_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + common_hal_audiotap_tap_clear(self); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_1(audiotap_tap_clear_obj, audiotap_tap_obj_clear); + +//| def play(self, sample: circuitpython_typing.AudioSample, *, loop: bool = False) -> Tap: +//| """Plays the sample once when loop=False and continuously when loop=True. +//| Does not block. Use `playing` to block. +//| +//| The first sample sets the tap's format. Later samples must match it. +//| +//| :return: The tap itself. Can be used for chaining, ie: +//| ``audio.play(tap.play(sample))``. +//| :rtype: Tap""" +//| ... +//| +static mp_obj_t audiotap_tap_obj_play(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_sample, ARG_loop }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_sample, MP_ARG_OBJ | MP_ARG_REQUIRED, {} }, + { MP_QSTR_loop, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = false} }, + }; + audiotap_tap_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); + + common_hal_audiotap_tap_play(self, args[ARG_sample].u_obj, args[ARG_loop].u_bool); + + return MP_OBJ_FROM_PTR(self); +} +MP_DEFINE_CONST_FUN_OBJ_KW(audiotap_tap_play_obj, 1, audiotap_tap_obj_play); + +//| def stop(self) -> None: +//| """Stops playback of the sample. The audio already kept can still be read.""" +//| ... +//| +//| +static mp_obj_t audiotap_tap_obj_stop(mp_obj_t self_in) { + audiotap_tap_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + common_hal_audiotap_tap_stop(self); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_1(audiotap_tap_stop_obj, audiotap_tap_obj_stop); + +static const mp_rom_map_elem_t audiotap_tap_locals_dict_table[] = { + // Methods + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&audiotap_tap_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&audiotap_tap_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, + { MP_ROM_QSTR(MP_QSTR_play), MP_ROM_PTR(&audiotap_tap_play_obj) }, + { MP_ROM_QSTR(MP_QSTR_stop), MP_ROM_PTR(&audiotap_tap_stop_obj) }, + { MP_ROM_QSTR(MP_QSTR_readinto), MP_ROM_PTR(&audiotap_tap_readinto_obj) }, + { MP_ROM_QSTR(MP_QSTR_clear), MP_ROM_PTR(&audiotap_tap_clear_obj) }, + + // Properties + { MP_ROM_QSTR(MP_QSTR_playing), MP_ROM_PTR(&audiotap_tap_playing_obj) }, + { MP_ROM_QSTR(MP_QSTR_available), MP_ROM_PTR(&audiotap_tap_available_obj) }, + { MP_ROM_QSTR(MP_QSTR_overflow), MP_ROM_PTR(&audiotap_tap_overflow_obj) }, + AUDIOSAMPLE_FIELDS, +}; +static MP_DEFINE_CONST_DICT(audiotap_tap_locals_dict, audiotap_tap_locals_dict_table); + +static const audiosample_p_t audiotap_tap_proto = { + MP_PROTO_IMPLEMENT(MP_QSTR_protocol_audiosample) + .reset_buffer = (audiosample_reset_buffer_fun)audiotap_tap_reset_buffer, + .get_buffer = (audiosample_get_buffer_fun)audiotap_tap_get_buffer, +}; + +MP_DEFINE_CONST_OBJ_TYPE( + audiotap_tap_type, + MP_QSTR_Tap, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, audiotap_tap_make_new, + locals_dict, &audiotap_tap_locals_dict, + protocol, &audiotap_tap_proto + ); diff --git a/shared-bindings/audiotap/Tap.h b/shared-bindings/audiotap/Tap.h new file mode 100644 index 00000000000..1d7b440417a --- /dev/null +++ b/shared-bindings/audiotap/Tap.h @@ -0,0 +1,25 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-module/audiotap/Tap.h" + +extern const mp_obj_type_t audiotap_tap_type; + +void common_hal_audiotap_tap_construct(audiotap_tap_obj_t *self, mp_float_t capacity); + +void common_hal_audiotap_tap_deinit(audiotap_tap_obj_t *self); + +bool common_hal_audiotap_tap_get_playing(audiotap_tap_obj_t *self); +void common_hal_audiotap_tap_play(audiotap_tap_obj_t *self, mp_obj_t sample, bool loop); +void common_hal_audiotap_tap_stop(audiotap_tap_obj_t *self); + +uint32_t common_hal_audiotap_tap_get_available(audiotap_tap_obj_t *self); +// Copies at most length samples, in whole frames. Returns the number copied. +uint32_t common_hal_audiotap_tap_readinto(audiotap_tap_obj_t *self, uint8_t *buffer, uint32_t length); +void common_hal_audiotap_tap_clear(audiotap_tap_obj_t *self); +bool common_hal_audiotap_tap_get_overflow(audiotap_tap_obj_t *self); diff --git a/shared-bindings/audiotap/__init__.c b/shared-bindings/audiotap/__init__.c new file mode 100644 index 00000000000..617f1139766 --- /dev/null +++ b/shared-bindings/audiotap/__init__.c @@ -0,0 +1,36 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include + +#include "py/obj.h" +#include "py/runtime.h" + +#include "shared-bindings/audiotap/LevelReader.h" +#include "shared-bindings/audiotap/Tap.h" + +//| """Look at audio as it plays +//| +//| The `audiotap` module contains `Tap`, which goes into an audio chain like +//| the effects in `audiofilters` and `audiodelays`. Audio passes through it +//| unchanged, and the program can read a copy of it, for waveforms, spectrum +//| analysis or recording, while it plays. A `LevelReader` attached to a tap +//| measures the peak and RMS levels of its audio, for meters.""" + +static const mp_rom_map_elem_t audiotap_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_audiotap) }, + { MP_ROM_QSTR(MP_QSTR_LevelReader), MP_ROM_PTR(&audiotap_levelreader_type) }, + { MP_ROM_QSTR(MP_QSTR_Tap), MP_ROM_PTR(&audiotap_tap_type) }, +}; + +static MP_DEFINE_CONST_DICT(audiotap_module_globals, audiotap_module_globals_table); + +const mp_obj_module_t audiotap_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&audiotap_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_audiotap, audiotap_module); diff --git a/shared-bindings/aurora_epaper/aurora_framebuffer.c b/shared-bindings/aurora_epaper/aurora_framebuffer.c index f1bb1693284..9595d7c6015 100644 --- a/shared-bindings/aurora_epaper/aurora_framebuffer.c +++ b/shared-bindings/aurora_epaper/aurora_framebuffer.c @@ -64,7 +64,7 @@ //| ) -> None: //| """Create a framebuffer for the Aurora CoG display. //| -//| .. note:: Displays of size 1.9" and 2.6" are not tested, and may exibit unexpected behavior. +//| .. note:: Displays of size 1.9" and 2.6" are not tested, and may exhibit unexpected behavior. //| //| :param busio.SPI spi_bus: The SPI bus that the display is connected to //| :param microcontroller.Pin chip_select: The pin connected to the displays chip select input @@ -175,6 +175,7 @@ MP_PROPERTY_GETSET(aurora_epaper_framebuffer_free_bus_obj, static const mp_rom_map_elem_t aurora_epaper_framebuffer_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&aurora_epaper_framebuffer_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&aurora_epaper_framebuffer_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR_set_temperature), MP_ROM_PTR(&aurora_epaper_frambuffer_set_temperature_obj) }, { MP_ROM_QSTR(MP_QSTR_free_bus), MP_ROM_PTR(&aurora_epaper_framebuffer_free_bus_obj) }, }; diff --git a/shared-bindings/bitbangio/I2C.c b/shared-bindings/bitbangio/I2C.c index d1a200d39b5..b3908cdde0a 100644 --- a/shared-bindings/bitbangio/I2C.c +++ b/shared-bindings/bitbangio/I2C.c @@ -22,8 +22,8 @@ //| //| def __init__( //| self, -//| scl: microcontroller.Pin, -//| sda: microcontroller.Pin, +//| scl: Union[microcontroller.Pin, digitalio.DigitalInOutProtocol], +//| sda: Union[microcontroller.Pin, digitalio.DigitalInOutProtocol], //| *, //| frequency: int = 400000, //| timeout: int = 255, @@ -40,8 +40,8 @@ //| bit unpacking. Instead, use an existing driver or make one with //| :ref:`Register ` data descriptors. //| -//| :param ~microcontroller.Pin scl: The clock pin -//| :param ~microcontroller.Pin sda: The data pin +//| :param ~microcontroller.Pin scl: The clock pin or DigitalInOut object +//| :param ~microcontroller.Pin sda: The data pin or DigitalInOut object //| :param int frequency: The clock frequency of the bus //| :param int timeout: The maximum clock stretching timeout in microseconds""" //| ... @@ -57,12 +57,12 @@ 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_kw_array(n_args, n_kw, all_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, MP_QSTR_scl); - const mcu_pin_obj_t *sda = validate_obj_is_free_pin(args[ARG_sda].u_obj, MP_QSTR_sda); + mp_int_t frequency = mp_arg_validate_int_min(args[ARG_frequency].u_int, 1, MP_QSTR_frequency); bitbangio_i2c_obj_t *self = mp_obj_malloc_with_finaliser(bitbangio_i2c_obj_t, &bitbangio_i2c_type); - shared_module_bitbangio_i2c_construct(self, scl, sda, args[ARG_frequency].u_int, args[ARG_timeout].u_int); - return (mp_obj_t)self; + shared_module_bitbangio_i2c_construct(self, args[ARG_scl].u_obj, args[ARG_sda].u_obj, frequency, args[ARG_timeout].u_int); + + return MP_OBJ_FROM_PTR(self); } //| def deinit(self) -> None: @@ -354,6 +354,7 @@ MP_DEFINE_CONST_FUN_OBJ_KW(bitbangio_i2c_writeto_then_readfrom_obj, 1, bitbangio static const mp_rom_map_elem_t bitbangio_i2c_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&bitbangio_i2c_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&bitbangio_i2c_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, { MP_ROM_QSTR(MP_QSTR_probe), MP_ROM_PTR(&bitbangio_i2c_probe_obj) }, diff --git a/shared-bindings/bitbangio/I2C.h b/shared-bindings/bitbangio/I2C.h index 022be3692a6..cc9cd21b601 100644 --- a/shared-bindings/bitbangio/I2C.h +++ b/shared-bindings/bitbangio/I2C.h @@ -16,8 +16,8 @@ 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, + mp_obj_t scl, + mp_obj_t sda, uint32_t frequency, uint32_t us_timeout); diff --git a/shared-bindings/bitbangio/SPI.c b/shared-bindings/bitbangio/SPI.c index 8938ae4898d..21ad75be1d4 100644 --- a/shared-bindings/bitbangio/SPI.c +++ b/shared-bindings/bitbangio/SPI.c @@ -33,9 +33,9 @@ //| //| def __init__( //| self, -//| clock: microcontroller.Pin, -//| MOSI: Optional[microcontroller.Pin] = None, -//| MISO: Optional[microcontroller.Pin] = None, +//| clock: Union[microcontroller.Pin, digitalio.DigitalInOutProtocol], +//| MOSI: Optional[Union[microcontroller.Pin, digitalio.DigitalInOutProtocol]] = None, +//| MISO: Optional[Union[microcontroller.Pin, digitalio.DigitalInOutProtocol]] = None, //| ) -> None: //| """Construct an SPI object on the given pins. //| @@ -48,9 +48,9 @@ //| :ref:`Register ` data descriptors. //| //| -//| :param ~microcontroller.Pin clock: the pin to use for the clock. -//| :param ~microcontroller.Pin MOSI: the Main Out Selected In pin. -//| :param ~microcontroller.Pin MISO: the Main In Selected Out pin.""" +//| :param ~microcontroller.Pin clock: the pin to use for the clock or DigitalInOut object +//| :param ~microcontroller.Pin MOSI: the Main Out Selected In pin or DigitalInOut object +//| :param ~microcontroller.Pin MISO: the Main In Selected Out pin or DigitalInOut object""" //| ... //| @@ -65,13 +65,9 @@ static mp_obj_t bitbangio_spi_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_kw_array(n_args, n_kw, all_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, MP_QSTR_clock); - const mcu_pin_obj_t *mosi = validate_obj_is_free_pin_or_none(args[ARG_MOSI].u_obj, MP_QSTR_mosi); - const mcu_pin_obj_t *miso = validate_obj_is_free_pin_or_none(args[ARG_MISO].u_obj, MP_QSTR_miso); - - bitbangio_spi_obj_t *self = mp_obj_malloc(bitbangio_spi_obj_t, &bitbangio_spi_type); - shared_module_bitbangio_spi_construct(self, clock, mosi, miso); - return (mp_obj_t)self; + bitbangio_spi_obj_t *self = mp_obj_malloc_with_finaliser(bitbangio_spi_obj_t, &bitbangio_spi_type); + shared_module_bitbangio_spi_construct(self, args[ARG_clock].u_obj, args[ARG_MOSI].u_obj, args[ARG_MISO].u_obj); + return MP_OBJ_FROM_PTR(self); } //| def deinit(self) -> None: @@ -137,12 +133,13 @@ static mp_obj_t bitbangio_spi_configure(size_t n_args, const mp_obj_t *pos_args, 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); + uint32_t baudrate = (uint32_t)mp_arg_validate_int_min(args[ARG_baudrate].u_int, 1, MP_QSTR_baudrate); uint8_t polarity = (uint8_t)mp_arg_validate_int_range(args[ARG_polarity].u_int, 0, 1, MP_QSTR_polarity); uint8_t phase = (uint8_t)mp_arg_validate_int_range(args[ARG_phase].u_int, 0, 1, MP_QSTR_phase); uint8_t bits = (uint8_t)mp_arg_validate_int_range(args[ARG_bits].u_int, 8, 9, MP_QSTR_bits); - shared_module_bitbangio_spi_configure(self, args[ARG_baudrate].u_int, polarity, phase, bits); + shared_module_bitbangio_spi_configure(self, baudrate, polarity, phase, bits); return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_KW(bitbangio_spi_configure_obj, 1, bitbangio_spi_configure); @@ -385,6 +382,7 @@ MP_DEFINE_CONST_FUN_OBJ_KW(bitbangio_spi_write_readinto_obj, 1, bitbangio_spi_wr static const mp_rom_map_elem_t bitbangio_spi_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&bitbangio_spi_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&bitbangio_spi_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, diff --git a/shared-bindings/bitbangio/SPI.h b/shared-bindings/bitbangio/SPI.h index dbe821683b0..19ec05152ad 100644 --- a/shared-bindings/bitbangio/SPI.h +++ b/shared-bindings/bitbangio/SPI.h @@ -16,8 +16,7 @@ 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); + mp_obj_t clock, mp_obj_t mosi, mp_obj_t miso); extern void shared_module_bitbangio_spi_deinit(bitbangio_spi_obj_t *self); extern bool shared_module_bitbangio_spi_deinited(bitbangio_spi_obj_t *self); diff --git a/shared-bindings/bitmapfilter/__init__.c b/shared-bindings/bitmapfilter/__init__.c index 7c5344dde11..8d01ad482b2 100644 --- a/shared-bindings/bitmapfilter/__init__.c +++ b/shared-bindings/bitmapfilter/__init__.c @@ -137,7 +137,7 @@ static mp_obj_t bitmapfilter_morph(size_t n_args, const mp_obj_t *pos_args, mp_m mp_float_t m = get_m(args[ARG_mul].u_obj, weight_sum); shared_module_bitmapfilter_morph(bitmap, mask, sq_n_weights / 2, iweights, m, b, - args[ARG_threshold].u_bool, args[ARG_offset].u_bool, args[ARG_invert].u_bool); + args[ARG_threshold].u_bool, args[ARG_offset].u_int, args[ARG_invert].u_bool); return args[ARG_bitmap].u_obj; } MP_DEFINE_CONST_FUN_OBJ_KW(bitmapfilter_morph_obj, 0, bitmapfilter_morph); diff --git a/shared-bindings/bitmaptools/__init__.c b/shared-bindings/bitmaptools/__init__.c index 9d655c3f90b..a56075344e8 100644 --- a/shared-bindings/bitmaptools/__init__.c +++ b/shared-bindings/bitmaptools/__init__.c @@ -185,8 +185,8 @@ static mp_obj_t bitmaptools_obj_rotozoom(size_t n_args, const mp_obj_t *pos_args ARG_angle, ARG_scale, ARG_skip_index}; static const mp_arg_t allowed_args[] = { - {MP_QSTR_dest_bitmap, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL}}, - {MP_QSTR_source_bitmap, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL}}, + {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 @@ -206,9 +206,9 @@ static mp_obj_t bitmaptools_obj_rotozoom(size_t n_args, const mp_obj_t *pos_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); - displayio_bitmap_t *destination = MP_OBJ_TO_PTR(args[ARG_dest_bitmap].u_obj); // the destination bitmap + displayio_bitmap_t *destination = MP_OBJ_TO_PTR(mp_arg_validate_type(args[ARG_dest_bitmap].u_obj, &displayio_bitmap_type, MP_QSTR_dest_bitmap)); // the destination bitmap - displayio_bitmap_t *source = MP_OBJ_TO_PTR(args[ARG_source_bitmap].u_obj); // the source bitmap + displayio_bitmap_t *source = MP_OBJ_TO_PTR(mp_arg_validate_type(args[ARG_source_bitmap].u_obj, &displayio_bitmap_type, MP_QSTR_source_bitmap)); // 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) { @@ -311,6 +311,7 @@ MAKE_ENUM_TYPE(bitmaptools, BlendMode, bitmaptools_blendmode); //| blendmode: Optional[BlendMode] = BlendMode.Normal, //| skip_source1_index: Union[int, None] = None, //| skip_source2_index: Union[int, None] = None, +//| mask: Optional[displayio.Bitmap] = None, //| ) -> None: //| """Alpha blend the two source bitmaps into the destination. //| @@ -326,6 +327,11 @@ MAKE_ENUM_TYPE(bitmaptools, BlendMode, bitmaptools_blendmode); //| :param bitmaptools.BlendMode blendmode: The blend mode to use. Default is Normal. //| :param int skip_source1_index: Bitmap palette or luminance index in source_bitmap_1 that will not be blended, set to None to blend all pixels //| :param int skip_source2_index: Bitmap palette or luminance index in source_bitmap_2 that will not be blended, set to None to blend all pixels +//| :param displayio.Bitmap mask: Optional 8-bits-per-value grayscale mask bitmap controlling per-pixel opacity of ``source_bitmap_2``. +//| The mask must have the same width and height as the other bitmaps and a ``bits_per_value`` of 8. A mask value of 0 +//| means ``source_bitmap_2`` is fully transparent at that pixel (only ``source_bitmap_1`` contributes); a value of 255 means +//| ``source_bitmap_2`` is fully opaque at that pixel (subject to ``factor2``). Intermediate values scale ``factor2`` linearly. +//| Pass ``None`` to disable per-pixel masking. //| //| For the L8 colorspace, the bitmaps must have a bits-per-value of 8. //| For the RGB colorspaces, they must have a bits-per-value of 16.""" @@ -333,7 +339,7 @@ MAKE_ENUM_TYPE(bitmaptools, BlendMode, bitmaptools_blendmode); //| static mp_obj_t bitmaptools_alphablend(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - enum {ARG_dest_bitmap, ARG_source_bitmap_1, ARG_source_bitmap_2, ARG_colorspace, ARG_factor_1, ARG_factor_2, ARG_blendmode, ARG_skip_source1_index, ARG_skip_source2_index}; + enum {ARG_dest_bitmap, ARG_source_bitmap_1, ARG_source_bitmap_2, ARG_colorspace, ARG_factor_1, ARG_factor_2, ARG_blendmode, ARG_skip_source1_index, ARG_skip_source2_index, ARG_mask}; static const mp_arg_t allowed_args[] = { {MP_QSTR_dest_bitmap, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = NULL}}, @@ -345,6 +351,7 @@ static mp_obj_t bitmaptools_alphablend(size_t n_args, const mp_obj_t *pos_args, {MP_QSTR_blendmode, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = (void *)&bitmaptools_blendmode_Normal_obj}}, {MP_QSTR_skip_source1_index, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, {MP_QSTR_skip_source2_index, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, + {MP_QSTR_mask, MP_ARG_KW_ONLY | 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); @@ -411,13 +418,64 @@ static mp_obj_t bitmaptools_alphablend(size_t n_args, const mp_obj_t *pos_args, skip_source2_index_none = false; } + displayio_bitmap_t *mask = NULL; + if (args[ARG_mask].u_obj != mp_const_none) { + mask = MP_OBJ_TO_PTR(mp_arg_validate_type(args[ARG_mask].u_obj, &displayio_bitmap_type, MP_QSTR_mask)); + if (mask->width != destination->width || mask->height != destination->height) { + mp_raise_ValueError(MP_ERROR_TEXT("Mask bitmap size must match the other bitmaps")); + } + if (mask->bits_per_value != 8) { + mp_raise_ValueError(MP_ERROR_TEXT("Mask bitmap must have 8 bits per pixel")); + } + } + common_hal_bitmaptools_alphablend(destination, source1, source2, colorspace, factor1, factor2, blendmode, skip_source1_index, - skip_source1_index_none, skip_source2_index, skip_source2_index_none); + skip_source1_index_none, skip_source2_index, skip_source2_index_none, mask); return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_KW(bitmaptools_alphablend_obj, 0, bitmaptools_alphablend); +//| def replace_color( +//| dest_bitmap: displayio.Bitmap, old_color: int, new_color: int +//| ) -> None: +//| """Replace any pixels of ``old_color`` with ``new_color`` in the ``bitmap`` +//| +//| :param displayio.Bitmap bitmap: Bitmap that will be changed +//| :param int old_color: Bitmap palette index that will overwritten +//| :param int new_color: Bitmap palette index that will get put in the bitmap""" +//| ... +//| +//| +static mp_obj_t bitmaptools_obj_replace_color(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum {ARG_bitmap, ARG_old_color, ARG_new_color}; + + static const mp_arg_t allowed_args[] = { + {MP_QSTR_bitmap, MP_ARG_REQUIRED | MP_ARG_OBJ}, + {MP_QSTR_old_color, MP_ARG_REQUIRED | MP_ARG_INT}, + {MP_QSTR_new_color, 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(mp_arg_validate_type(args[ARG_bitmap].u_obj, &displayio_bitmap_type, MP_QSTR_bitmap)); + + uint32_t old_color, new_color, color_depth; + old_color = args[ARG_old_color].u_int; + new_color = args[ARG_new_color].u_int; + + color_depth = (1 << destination->bits_per_value); + if (color_depth <= old_color || color_depth <= new_color) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("%q out of range"), MP_QSTR_color); + } + + common_hal_bitmaptools_replace_color(destination, old_color, new_color); + + return mp_const_none; +} + +MP_DEFINE_CONST_FUN_OBJ_KW(bitmaptools_replace_color_obj, 0, bitmaptools_obj_replace_color); + //| def fill_region( //| dest_bitmap: displayio.Bitmap, x1: int, y1: int, x2: int, y2: int, value: int //| ) -> None: @@ -438,14 +496,14 @@ static mp_obj_t bitmaptools_obj_fill_region(size_t n_args, const mp_obj_t *pos_a enum {ARG_dest_bitmap, ARGS_X1_Y1_X2_Y2, ARG_value}; static const mp_arg_t allowed_args[] = { - {MP_QSTR_dest_bitmap, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL}}, + {MP_QSTR_dest_bitmap, MP_ARG_REQUIRED | MP_ARG_OBJ}, ALLOWED_ARGS_X1_Y1_X2_Y2(MP_ARG_REQUIRED, MP_ARG_REQUIRED), - {MP_QSTR_value, MP_ARG_REQUIRED | MP_ARG_INT, {.u_obj = MP_OBJ_NULL}}, + {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 + displayio_bitmap_t *destination = MP_OBJ_TO_PTR(mp_arg_validate_type(args[ARG_dest_bitmap].u_obj, &displayio_bitmap_type, MP_QSTR_dest_bitmap)); // the destination bitmap uint32_t value, color_depth; value = args[ARG_value].u_int; @@ -487,10 +545,10 @@ static mp_obj_t bitmaptools_obj_boundary_fill(size_t n_args, const mp_obj_t *pos enum {ARG_dest_bitmap, ARG_x, ARG_y, ARG_fill_color_value, ARG_replaced_color_value}; static const mp_arg_t allowed_args[] = { - {MP_QSTR_dest_bitmap, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL}}, - {MP_QSTR_x, MP_ARG_REQUIRED | MP_ARG_INT, {.u_obj = MP_OBJ_NULL}}, - {MP_QSTR_y, MP_ARG_REQUIRED | MP_ARG_INT, {.u_obj = MP_OBJ_NULL}}, - {MP_QSTR_fill_color_value, MP_ARG_REQUIRED | MP_ARG_INT, {.u_obj = MP_OBJ_NULL}}, + {MP_QSTR_dest_bitmap, MP_ARG_REQUIRED | MP_ARG_OBJ}, + {MP_QSTR_x, MP_ARG_REQUIRED | MP_ARG_INT}, + {MP_QSTR_y, MP_ARG_REQUIRED | MP_ARG_INT}, + {MP_QSTR_fill_color_value, MP_ARG_REQUIRED | MP_ARG_INT}, {MP_QSTR_replaced_color_value, MP_ARG_INT, {.u_int = INT_MAX} }, }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; @@ -548,17 +606,17 @@ static mp_obj_t bitmaptools_obj_draw_line(size_t n_args, const mp_obj_t *pos_arg 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, {.u_obj = MP_OBJ_NULL}}, - {MP_QSTR_x1, MP_ARG_REQUIRED | MP_ARG_INT, {.u_obj = MP_OBJ_NULL}}, - {MP_QSTR_y1, MP_ARG_REQUIRED | MP_ARG_INT, {.u_obj = MP_OBJ_NULL}}, - {MP_QSTR_x2, MP_ARG_REQUIRED | MP_ARG_INT, {.u_obj = MP_OBJ_NULL}}, - {MP_QSTR_y2, MP_ARG_REQUIRED | MP_ARG_INT, {.u_obj = MP_OBJ_NULL}}, - {MP_QSTR_value, MP_ARG_REQUIRED | MP_ARG_INT, {.u_obj = MP_OBJ_NULL}}, + {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 + displayio_bitmap_t *destination = MP_OBJ_TO_PTR(mp_arg_validate_type(args[ARG_dest_bitmap].u_obj, &displayio_bitmap_type, MP_QSTR_dest_bitmap)); // the destination bitmap uint32_t value, color_depth; value = args[ARG_value].u_int; @@ -635,16 +693,16 @@ static mp_obj_t bitmaptools_obj_draw_polygon(size_t n_args, const mp_obj_t *pos_ enum {ARG_dest_bitmap, ARG_xs, ARG_ys, ARG_value, ARG_close}; static const mp_arg_t allowed_args[] = { - {MP_QSTR_dest_bitmap, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL}}, - {MP_QSTR_xs, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL}}, - {MP_QSTR_ys, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL}}, - {MP_QSTR_value, MP_ARG_REQUIRED | MP_ARG_INT, {.u_obj = MP_OBJ_NULL}}, + {MP_QSTR_dest_bitmap, MP_ARG_REQUIRED | MP_ARG_OBJ}, + {MP_QSTR_xs, MP_ARG_REQUIRED | MP_ARG_OBJ}, + {MP_QSTR_ys, MP_ARG_REQUIRED | MP_ARG_OBJ}, + {MP_QSTR_value, MP_ARG_REQUIRED | MP_ARG_INT}, {MP_QSTR_close, MP_ARG_BOOL, {.u_bool = true}}, }; 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 *destination = MP_OBJ_TO_PTR(mp_arg_validate_type(args[ARG_dest_bitmap].u_obj, &displayio_bitmap_type, MP_QSTR_dest_bitmap)); // the destination bitmap mp_buffer_info_t xs_buf, ys_buf; mp_get_buffer_raise(args[ARG_xs].u_obj, &xs_buf, MP_BUFFER_READ); @@ -691,7 +749,7 @@ MP_DEFINE_CONST_FUN_OBJ_KW(bitmaptools_draw_polygon_obj, 0, bitmaptools_obj_draw //| available 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 +//| are not specified, or are given as None, 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``. @@ -717,9 +775,9 @@ MP_DEFINE_CONST_FUN_OBJ_KW(bitmaptools_draw_polygon_obj, 0, bitmaptools_obj_draw 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, ARGS_X1_Y1_X2_Y2, ARG_skip_index }; static const mp_arg_t allowed_args[] = { - { MP_QSTR_bitmap, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, - { MP_QSTR_data, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, - ALLOWED_ARGS_X1_Y1_X2_Y2(0, MP_ARG_REQUIRED), + { MP_QSTR_bitmap, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_data, MP_ARG_REQUIRED | MP_ARG_OBJ }, + ALLOWED_ARGS_X1_Y1_X2_Y2(0, 0), { MP_QSTR_skip_index, MP_ARG_OBJ, {.u_obj = mp_const_none } }, }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; @@ -782,9 +840,9 @@ MP_DEFINE_CONST_FUN_OBJ_KW(bitmaptools_arrayblit_obj, 0, bitmaptools_arrayblit); 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, {.u_obj = MP_OBJ_NULL} }, - { MP_QSTR_file, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, - { MP_QSTR_bits_per_pixel, MP_ARG_REQUIRED | MP_ARG_INT, {.u_obj = MP_OBJ_NULL} }, + { 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 } }, @@ -873,9 +931,9 @@ MAKE_ENUM_TYPE(bitmaptools, DitherAlgorithm, bitmaptools_dither_algorithm); static mp_obj_t bitmaptools_dither(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { enum { ARG_dest_bitmap, ARG_source_bitmap, ARG_source_colorspace, ARG_algorithm }; static const mp_arg_t allowed_args[] = { - { MP_QSTR_dest_bitmap, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, - { MP_QSTR_source_bitmap, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, - { MP_QSTR_source_colorspace, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_dest_bitmap, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_source_bitmap, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_source_colorspace, MP_ARG_REQUIRED | MP_ARG_OBJ }, { MP_QSTR_algorithm, MP_ARG_OBJ, { .u_obj = MP_ROM_PTR((void *)&dither_algorithm_Atkinson_obj) } }, }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; @@ -977,7 +1035,7 @@ static mp_obj_t bitmaptools_obj_draw_circle(size_t n_args, const mp_obj_t *pos_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); - displayio_bitmap_t *destination = MP_OBJ_TO_PTR(args[ARG_dest_bitmap].u_obj); // the destination bitmap + displayio_bitmap_t *destination = MP_OBJ_TO_PTR(mp_arg_validate_type(args[ARG_dest_bitmap].u_obj, &displayio_bitmap_type, MP_QSTR_dest_bitmap)); // the destination bitmap uint32_t value, color_depth; value = args[ARG_value].u_int; @@ -1038,10 +1096,10 @@ MP_DEFINE_CONST_FUN_OBJ_KW(bitmaptools_draw_circle_obj, 0, bitmaptools_obj_draw_ static mp_obj_t bitmaptools_obj_blit(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { enum {ARG_destination, ARG_source, ARG_x, ARG_y, ARG_x1, ARG_y1, ARG_x2, ARG_y2, ARG_skip_source_index, ARG_skip_dest_index}; static const mp_arg_t allowed_args[] = { - {MP_QSTR_dest_bitmap, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, - {MP_QSTR_source_bitmap, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, - {MP_QSTR_x, MP_ARG_REQUIRED | MP_ARG_INT, {.u_obj = MP_OBJ_NULL} }, - {MP_QSTR_y, MP_ARG_REQUIRED | MP_ARG_INT, {.u_obj = MP_OBJ_NULL} }, + {MP_QSTR_dest_bitmap, MP_ARG_REQUIRED | MP_ARG_OBJ }, + {MP_QSTR_source_bitmap, MP_ARG_REQUIRED | MP_ARG_OBJ }, + {MP_QSTR_x, MP_ARG_REQUIRED | MP_ARG_INT }, + {MP_QSTR_y, MP_ARG_REQUIRED | MP_ARG_INT }, ALLOWED_ARGS_X1_Y1_X2_Y2(0, 0), {MP_QSTR_skip_source_index, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, {MP_QSTR_skip_dest_index, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, @@ -1103,6 +1161,7 @@ static const mp_rom_map_elem_t bitmaptools_module_globals_table[] = { { 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_alphablend), MP_ROM_PTR(&bitmaptools_alphablend_obj) }, + { MP_ROM_QSTR(MP_QSTR_replace_color), MP_ROM_PTR(&bitmaptools_replace_color_obj) }, { MP_ROM_QSTR(MP_QSTR_fill_region), MP_ROM_PTR(&bitmaptools_fill_region_obj) }, { MP_ROM_QSTR(MP_QSTR_boundary_fill), MP_ROM_PTR(&bitmaptools_boundary_fill_obj) }, { MP_ROM_QSTR(MP_QSTR_draw_line), MP_ROM_PTR(&bitmaptools_draw_line_obj) }, diff --git a/shared-bindings/bitmaptools/__init__.h b/shared-bindings/bitmaptools/__init__.h index 2d9b22e216e..20236983bac 100644 --- a/shared-bindings/bitmaptools/__init__.h +++ b/shared-bindings/bitmaptools/__init__.h @@ -42,6 +42,9 @@ void common_hal_bitmaptools_fill_region(displayio_bitmap_t *destination, int16_t x2, int16_t y2, uint32_t value); +void common_hal_bitmaptools_replace_color(displayio_bitmap_t *destination, + uint32_t old_color, uint32_t new_color); + void common_hal_bitmaptools_boundary_fill(displayio_bitmap_t *destination, int16_t x, int16_t y, uint32_t fill_color_value, uint32_t replaced_color_value); @@ -66,7 +69,8 @@ void common_hal_bitmaptools_arrayblit(displayio_bitmap_t *self, void *data, int void common_hal_bitmaptools_dither(displayio_bitmap_t *dest_bitmap, displayio_bitmap_t *source_bitmap, displayio_colorspace_t colorspace, bitmaptools_dither_algorithm_t algorithm); void common_hal_bitmaptools_alphablend(displayio_bitmap_t *destination, displayio_bitmap_t *source1, displayio_bitmap_t *source2, displayio_colorspace_t colorspace, mp_float_t factor1, mp_float_t factor2, - bitmaptools_blendmode_t blendmode, uint32_t skip_source1_index, bool skip_source1_index_none, uint32_t skip_source2_index, bool skip_source2_index_none); + bitmaptools_blendmode_t blendmode, uint32_t skip_source1_index, bool skip_source1_index_none, uint32_t skip_source2_index, bool skip_source2_index_none, + displayio_bitmap_t *mask); typedef struct { union { @@ -80,8 +84,8 @@ typedef struct { #define ARGS_X1_Y1_X2_Y2 ARG_x1, ARG_y1, ARG_x2, ARG_y2 #define ALLOWED_ARGS_X1_Y1_X2_Y2(if_required1, if_required2) \ {MP_QSTR_x1, if_required1 | MP_ARG_OBJ, {.u_obj = MP_ROM_INT(0)}}, \ - {MP_QSTR_y1, if_required2 | MP_ARG_OBJ, {.u_obj = MP_ROM_INT(0)}}, \ - {MP_QSTR_x2, if_required1 | MP_ARG_OBJ, {.u_obj = MP_ROM_NONE}}, \ + {MP_QSTR_y1, if_required1 | MP_ARG_OBJ, {.u_obj = MP_ROM_INT(0)}}, \ + {MP_QSTR_x2, if_required2 | MP_ARG_OBJ, {.u_obj = MP_ROM_NONE}}, \ {MP_QSTR_y2, if_required2 | MP_ARG_OBJ, {.u_obj = MP_ROM_NONE}} bitmaptools_rect_t bitmaptools_validate_coord_range_pair(const mp_arg_val_t in[4], int width, int height); diff --git a/shared-bindings/board/__init__.h b/shared-bindings/board/__init__.h index 7c9a59d2dbd..2df4af70593 100644 --- a/shared-bindings/board/__init__.h +++ b/shared-bindings/board/__init__.h @@ -11,22 +11,33 @@ #include "shared-bindings/microcontroller/Pin.h" // for the pin definitions +// A port can inject board.EFUSE_KEY* (or other hardware key) entries into +// every board's globals table by defining CIRCUITPY_BOARD_HARDWARE_KEYS (a +// comma-terminated list of { MP_ROM_QSTR(...), MP_ROM_PTR(...) } pairs). +#if CIRCUITPY_HARDWAREKEY +#include "common-hal/hardwarekey/board.h" +#endif +#ifndef CIRCUITPY_BOARD_HARDWARE_KEYS +#define CIRCUITPY_BOARD_HARDWARE_KEYS +#endif + +#if CIRCUITPY_MUTABLE_BOARD +extern mp_obj_dict_t board_module_globals; +#else extern const mp_obj_dict_t board_module_globals; +#endif static const MP_DEFINE_STR_OBJ(board_module_id_obj, CIRCUITPY_BOARD_ID); -bool common_hal_board_is_i2c(mp_obj_t obj); mp_obj_t common_hal_board_get_i2c(const mp_int_t instance); mp_obj_t common_hal_board_create_i2c(const mp_int_t instance); mp_obj_t board_i2c(size_t n_args, const mp_obj_t *args); MP_DECLARE_CONST_FUN_OBJ_0(board_i2c_obj); -bool common_hal_board_is_spi(mp_obj_t obj); mp_obj_t common_hal_board_get_spi(const mp_int_t instance); mp_obj_t common_hal_board_create_spi(const mp_int_t instance); mp_obj_t board_spi(size_t n_args, const mp_obj_t *args); MP_DECLARE_CONST_FUN_OBJ_0(board_spi_obj); -bool common_hal_board_is_uart(mp_obj_t obj); mp_obj_t common_hal_board_get_uart(const mp_int_t instance); mp_obj_t common_hal_board_create_uart(const mp_int_t instance); mp_obj_t board_uart(size_t n_args, const mp_obj_t *args); @@ -40,4 +51,10 @@ MP_DECLARE_CONST_FUN_OBJ_0(board_uart_obj); #define CIRCUITPYTHON_BOARD_DICT_STANDARD_ITEMS \ { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_board) }, \ - { MP_ROM_QSTR(MP_QSTR_board_id), MP_ROM_PTR(&board_module_id_obj) }, + { MP_ROM_QSTR(MP_QSTR_board_id), MP_ROM_PTR(&board_module_id_obj) }, \ + CIRCUITPY_BOARD_HARDWARE_KEYS + +#define CIRCUITPYTHON_MUTABLE_BOARD_DICT_STANDARD_ITEMS \ + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_board) }, \ + { MP_ROM_QSTR(MP_QSTR_board_id), MP_OBJ_FROM_PTR(&board_module_id_obj) }, \ + CIRCUITPY_BOARD_HARDWARE_KEYS diff --git a/shared-bindings/busdisplay/BusDisplay.c b/shared-bindings/busdisplay/BusDisplay.c index 297a8690577..c8d9a56993b 100644 --- a/shared-bindings/busdisplay/BusDisplay.c +++ b/shared-bindings/busdisplay/BusDisplay.c @@ -13,10 +13,15 @@ #include "py/objproperty.h" #include "py/objtype.h" #include "py/runtime.h" +#include "shared-bindings/displayio/__init__.h" #include "shared-bindings/displayio/Group.h" #include "shared-bindings/microcontroller/Pin.h" #include "shared-bindings/util.h" +#if CIRCUITPY_VIDEOCORE +#include "shared-module/videocore/__init__.h" +#endif #include "shared-module/displayio/__init__.h" +#include "shared-module/displayio/bus_core.h" //| import displayio //| import fourwire @@ -34,8 +39,9 @@ //| """Manage updating a display over a display bus //| //| This initializes a display and connects it into CircuitPython. Unlike other -//| objects in CircuitPython, display objects live until `displayio.release_displays()` -//| is called. This is done so that CircuitPython can use the display itself. +//| objects in CircuitPython, a display stays active after your code finishes if it is +//| `supervisor.runtime.display `, so that CircuitPython can use it. Otherwise, it is released +//| when your code finishes. //| //| Most people should not use this class directly. Use a specific display driver instead that will //| contain the initialization sequence at minimum.""" @@ -122,7 +128,6 @@ //| :param int native_frames_per_second: Number of display refreshes per second that occur with the given init_sequence. //| :param bool backlight_on_high: If True, pulling the backlight pin high turns the backlight on. //| :param bool SH1107_addressing: Special quirk for SH1107, use upper/lower column set and page set -//| :param int set_vertical_scroll: This parameter is accepted but ignored for backwards compatibility. It will be removed in a future release. //| :param int backlight_pwm_frequency: The frequency to use to drive the PWM for backlight brightness control. Default is 50000. //| """ //| ... @@ -133,7 +138,7 @@ static mp_obj_t busdisplay_busdisplay_make_new(const mp_obj_type_t *type, size_t 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_backlight_pin, ARG_brightness_command, ARG_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_backlight_pwm_frequency }; @@ -154,7 +159,6 @@ static mp_obj_t busdisplay_busdisplay_make_new(const mp_obj_type_t *type, size_t { MP_QSTR_set_column_command, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0x2a} }, { MP_QSTR_set_row_command, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0x2b} }, { MP_QSTR_write_ram_command, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0x2c} }, - { MP_QSTR_set_vertical_scroll, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0x0} }, { MP_QSTR_backlight_pin, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = mp_const_none} }, { MP_QSTR_brightness_command, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = NO_BRIGHTNESS_COMMAND} }, { MP_QSTR_brightness, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_OBJ_NEW_SMALL_INT(1)} }, @@ -190,6 +194,9 @@ static mp_obj_t busdisplay_busdisplay_make_new(const mp_obj_type_t *type, size_t mp_raise_ValueError_varg(MP_ERROR_TEXT("%q must be 1 when %q is True"), MP_QSTR_color_depth, MP_QSTR_SH1107_addressing); } + // Check the bus before taking a display slot: construct would raise after the slot is in use. + displayio_display_bus_validate(display_bus); + primary_display_t *disp = allocate_display_or_raise(); busdisplay_busdisplay_obj_t *self = &disp->display; @@ -221,12 +228,40 @@ static mp_obj_t busdisplay_busdisplay_make_new(const mp_obj_type_t *type, size_t } // Helper to ensure we have the native super class instead of a subclass. +// Raises if the display has been released. static busdisplay_busdisplay_obj_t *native_display(mp_obj_t display_obj) { mp_obj_t native_display = mp_obj_cast_to_native_base(display_obj, &busdisplay_busdisplay_type); + if (native_display == MP_OBJ_NULL) { + raise_deinited_error(); + } mp_obj_assert_native_inited(native_display); - return MP_OBJ_TO_PTR(native_display); + busdisplay_busdisplay_obj_t *self = MP_OBJ_TO_PTR(native_display); + if (self->base.type != &busdisplay_busdisplay_type) { + raise_deinited_error(); + } + return self; } +//| def deinit(self) -> None: +//| """Release the display and its display bus, so their pins can be used again. +//| The display bus is not released if another display still uses it. +//| A `busio.SPI` or `busio.I2C` object that you passed to the display bus is not deinitialized. +//| +//| To release a built-in display, or a display kept from an earlier run, +//| use ``supervisor.runtime.display.deinit()``. +//| As of CircuitPython 11.0.0, this replaces `displayio.release_displays()`, which is deprecated. +//| """ +//| ... +//| +static mp_obj_t busdisplay_busdisplay_obj_deinit(mp_obj_t self_in) { + mp_obj_t native_display = mp_obj_cast_to_native_base(self_in, &busdisplay_busdisplay_type); + if (native_display != MP_OBJ_NULL) { + common_hal_displayio_deinit_display(native_display); + } + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_1(busdisplay_busdisplay_deinit_obj, busdisplay_busdisplay_obj_deinit); + // Undocumented show() implementation with a friendly error message. static mp_obj_t busdisplay_busdisplay_obj_show(mp_obj_t self_in, mp_obj_t group_in) { mp_raise_AttributeError(MP_ERROR_TEXT(".show(x) removed. Use .root_group = x")); @@ -410,6 +445,12 @@ static mp_obj_t busdisplay_busdisplay_obj_set_root_group(mp_obj_t self_in, mp_ob displayio_group_t *group = NULL; if (group_in != mp_const_none) { group = MP_OBJ_TO_PTR(native_group(group_in)); + #if CIRCUITPY_VIDEOCORE + // Validate that draw protocol layers (e.g. a VideoBuffer) fit the + // display they will render on. + videocore_validate_root_group(group_in, self_in, + common_hal_busdisplay_busdisplay_get_rotation(self)); + #endif } common_hal_busdisplay_busdisplay_set_root_group(self, group); @@ -443,6 +484,15 @@ static mp_obj_t busdisplay_busdisplay_obj_fill_row(size_t n_args, const mp_obj_t mp_int_t y = args[ARG_y].u_int; mp_obj_t *result = args[ARG_buffer].u_obj; + #if CIRCUITPY_DISPLAYIO_LVGL + // LVGL renders into its own draw buffers, so there is no CPU-readable row to + // return. Keep the API available and report that this backend can't do it. + (void)self; + (void)y; + (void)result; + mp_raise_NotImplementedError(MP_ERROR_TEXT("Operation or feature not supported")); + #else + mp_buffer_info_t bufinfo; mp_get_buffer_raise(result, &bufinfo, MP_BUFFER_WRITE); @@ -479,10 +529,12 @@ static mp_obj_t busdisplay_busdisplay_obj_fill_row(size_t n_args, const mp_obj_t } else { mp_raise_ValueError(MP_ERROR_TEXT("Buffer too small")); } + #endif } MP_DEFINE_CONST_FUN_OBJ_KW(busdisplay_busdisplay_fill_row_obj, 1, busdisplay_busdisplay_obj_fill_row); static const mp_rom_map_elem_t busdisplay_busdisplay_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&busdisplay_busdisplay_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR_show), MP_ROM_PTR(&busdisplay_busdisplay_show_obj) }, { MP_ROM_QSTR(MP_QSTR_refresh), MP_ROM_PTR(&busdisplay_busdisplay_refresh_obj) }, { MP_ROM_QSTR(MP_QSTR_fill_row), MP_ROM_PTR(&busdisplay_busdisplay_fill_row_obj) }, diff --git a/shared-bindings/busio/I2C.c b/shared-bindings/busio/I2C.c index 8aa35ec6e07..c2288135da2 100644 --- a/shared-bindings/busio/I2C.c +++ b/shared-bindings/busio/I2C.c @@ -67,7 +67,7 @@ static mp_obj_t busio_i2c_make_new(const mp_obj_type_t *type, size_t n_args, siz busio_i2c_obj_t *self = mp_obj_malloc_with_finaliser(busio_i2c_obj_t, &busio_i2c_type); common_hal_busio_i2c_construct(self, scl, sda, args[ARG_frequency].u_int, args[ARG_timeout].u_int); - return (mp_obj_t)self; + return MP_OBJ_FROM_PTR(self); #else mp_raise_NotImplementedError(NULL); #endif // CIRCUITPY_BUSIO_I2C @@ -106,15 +106,19 @@ static void check_for_deinit(busio_i2c_obj_t *self) { // Provided by context manager helper. static void check_lock(busio_i2c_obj_t *self) { - asm (""); + __asm__ (""); if (!common_hal_busio_i2c_has_lock(self)) { mp_raise_RuntimeError(MP_ERROR_TEXT("Function requires lock")); } } -//| def probe(self, address: int) -> List[int]: +//| def probe(self, address: int) -> bool: //| """Check if a device at the specified address responds. //| +//| **Limitations:** On Zephyr-based nRF boards, `probe()` does not work reliably +//| at 400 kHz. Use 100 kHz. +//| See `#11604 `_. +//| //| :param int address: 7-bit device address //| :return: ``True`` if a device at ``address`` responds; ``False`` otherwise //| :rtype: bool""" @@ -134,6 +138,10 @@ MP_DEFINE_CONST_FUN_OBJ_2(busio_i2c_probe_obj, busio_i2c_probe); //| """Scan all I2C addresses between 0x08 and 0x77 inclusive and return a //| list of those that respond. //| +//| **Limitations:** On Zephyr-based nRF boards, `scan()` does not work reliably +//| at 400 kHz. Use 100 kHz. +//| See `#11604 `_. +//| //| :return: List of device ids on the I2C bus //| :rtype: list""" //| ... @@ -157,6 +165,12 @@ MP_DEFINE_CONST_FUN_OBJ_1(busio_i2c_scan_obj, busio_i2c_scan); //| def try_lock(self) -> bool: //| """Attempts to grab the I2C lock. Returns True on success. //| +//| .. warning:: Ideally, release the lock with `unlock()` as soon as you are done with the bus. +//| Use :class:`~adafruit_bus_device.I2CDevice`, which holds the lock only +//| during each transaction. +//| On Espressif boards, holding the lock for a long time while using WiFi +//| can starve the WiFi and USB tasks, and the board may hang or restart in safe mode. +//| //| :return: True when lock has been grabbed //| :rtype: bool""" //| ... @@ -228,10 +242,10 @@ static mp_obj_t busio_i2c_readfrom_into(size_t n_args, const mp_obj_t *pos_args, start *= stride_in_bytes; length *= stride_in_bytes; - uint8_t status = + mp_negative_errno_t status = common_hal_busio_i2c_read(self, args[ARG_address].u_int, ((uint8_t *)bufinfo.buf) + start, length); if (status != 0) { - mp_raise_OSError(status); + mp_raise_OSError(-status); } return mp_const_none; @@ -290,11 +304,11 @@ static mp_obj_t busio_i2c_writeto(size_t n_args, const mp_obj_t *pos_args, mp_ma length *= stride_in_bytes; // do the transfer - uint8_t status = + mp_negative_errno_t status = common_hal_busio_i2c_write(self, args[ARG_address].u_int, ((uint8_t *)bufinfo.buf) + start, length); if (status != 0) { - mp_raise_OSError(status); + mp_raise_OSError(-status); } return mp_const_none; @@ -369,7 +383,7 @@ static mp_obj_t busio_i2c_writeto_then_readfrom(size_t n_args, const mp_obj_t *p int32_t in_start = args[ARG_in_start].u_int; const int32_t in_end = args[ARG_in_end].u_int; normalize_buffer_bounds(&in_start, in_end, &in_length); - mp_arg_validate_length_min(in_length, 1, MP_QSTR_out_buffer); + mp_arg_validate_length_min(in_length, 1, MP_QSTR_in_buffer); // Treat start and length in terms of bytes from now on. out_start *= out_stride_in_bytes; @@ -377,10 +391,10 @@ static mp_obj_t busio_i2c_writeto_then_readfrom(size_t n_args, const mp_obj_t *p in_start *= in_stride_in_bytes; in_length *= in_stride_in_bytes; - uint8_t status = common_hal_busio_i2c_write_read(self, args[ARG_address].u_int, + mp_negative_errno_t status = common_hal_busio_i2c_write_read(self, args[ARG_address].u_int, ((uint8_t *)out_bufinfo.buf) + out_start, out_length, ((uint8_t *)in_bufinfo.buf) + in_start, in_length); if (status != 0) { - mp_raise_OSError(status); + mp_raise_OSError(-status); } return mp_const_none; diff --git a/shared-bindings/busio/I2C.h b/shared-bindings/busio/I2C.h index 55f2d0f0108..0ac2d4665dc 100644 --- a/shared-bindings/busio/I2C.h +++ b/shared-bindings/busio/I2C.h @@ -7,6 +7,7 @@ #pragma once #include "py/obj.h" +#include "py/mperrno.h" #include "common-hal/microcontroller/Pin.h" #include "common-hal/busio/I2C.h" @@ -35,18 +36,15 @@ extern void common_hal_busio_i2c_unlock(busio_i2c_obj_t *self); // Probe the bus to see if a device acknowledges the given address. 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, +// Write to the device and return 0 on success or a negative error code from mperrno.h +extern mp_negative_errno_t common_hal_busio_i2c_write(busio_i2c_obj_t *self, uint16_t address, const uint8_t *data, size_t len); // 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, +// success or a negative error code from mperrno.h +extern mp_negative_errno_t common_hal_busio_i2c_read(busio_i2c_obj_t *self, uint16_t address, uint8_t *data, size_t len); // Do a write and then a read in the same I2C transaction. -uint8_t common_hal_busio_i2c_write_read(busio_i2c_obj_t *self, uint16_t address, +mp_negative_errno_t common_hal_busio_i2c_write_read(busio_i2c_obj_t *self, uint16_t address, uint8_t *out_data, size_t out_len, uint8_t *in_data, size_t in_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/SPI.c b/shared-bindings/busio/SPI.c index 0c8ae1bfdd7..e876e7c2094 100644 --- a/shared-bindings/busio/SPI.c +++ b/shared-bindings/busio/SPI.c @@ -9,17 +9,16 @@ #include +#include "py/mperrno.h" +#include "py/objproperty.h" +#include "py/runtime.h" #include "shared-bindings/microcontroller/Pin.h" #include "shared-bindings/busio/SPI.h" #include "shared-bindings/util.h" - #include "shared/runtime/buffer_helper.h" #include "shared/runtime/context_manager_helpers.h" -#include "py/binary.h" -#include "py/mperrno.h" -#include "py/objproperty.h" -#include "py/runtime.h" - +#include "shared/runtime/interrupt_char.h" +#include "supervisor/shared/tick.h" //| class SPI: //| """A 3-4 wire serial protocol @@ -85,19 +84,22 @@ //| +#if CIRCUITPY_BUSIO_SPI +// async_spi.SPI takes the same arguments and uses these tables too. +const mp_arg_t busio_spi_make_new_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_half_duplex, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = false} }, +}; +#endif + // TODO(tannewt): Support LSB SPI. static mp_obj_t busio_spi_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { #if CIRCUITPY_BUSIO_SPI - busio_spi_obj_t *self = mp_obj_malloc(busio_spi_obj_t, &busio_spi_type); enum { ARG_clock, ARG_MOSI, ARG_MISO, ARG_half_duplex }; - 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_half_duplex, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = false} }, - }; - mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; - mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + mp_arg_val_t args[MP_ARRAY_SIZE(busio_spi_make_new_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(busio_spi_make_new_args), busio_spi_make_new_args, args); const mcu_pin_obj_t *clock = validate_obj_is_free_pin(args[ARG_clock].u_obj, MP_QSTR_clock); const mcu_pin_obj_t *mosi = validate_obj_is_free_pin_or_none(args[ARG_MOSI].u_obj, MP_QSTR_mosi); @@ -107,6 +109,7 @@ static mp_obj_t busio_spi_make_new(const mp_obj_type_t *type, size_t n_args, siz mp_raise_ValueError(MP_ERROR_TEXT("Must provide MISO or MOSI pin")); } + busio_spi_obj_t *self = mp_obj_malloc_with_finaliser(busio_spi_obj_t, &busio_spi_type); common_hal_busio_spi_construct(self, clock, mosi, miso, args[ARG_half_duplex].u_bool); return MP_OBJ_FROM_PTR(self); #else @@ -140,7 +143,7 @@ MP_DEFINE_CONST_FUN_OBJ_1(busio_spi_deinit_obj, busio_spi_obj_deinit); // Provided by context manager helper. static void check_lock(busio_spi_obj_t *self) { - asm (""); + __asm__ (""); if (!common_hal_busio_spi_has_lock(self)) { mp_raise_RuntimeError(MP_ERROR_TEXT("Function requires lock")); } @@ -157,9 +160,12 @@ static void check_for_deinit(busio_spi_obj_t *self) { //| ) -> None: //| """Configures the SPI bus. The SPI object must be locked. //| -//| :param int baudrate: the desired clock rate in Hertz. The actual clock rate may be higher or lower -//| due to the granularity of available clock settings. +//| :param int baudrate: the desired clock rate in Hertz. The value is treated as a ceiling: +//| the actual clock rate may be lower due to the granularity of available clock settings, +//| but it will not exceed the given value. //| Check the `frequency` attribute for the actual clock rate. +//| **Limitations**: On Zephyr, the ceiling behavior may be violated, and +//| the `frequency` value does not reflect the actual baudrate. //| :param int polarity: the base state of the clock line (0 or 1) //| :param int phase: the edge of the clock that data is captured. First (0) //| or second (1). Rising or falling depends on clock polarity. @@ -168,29 +174,24 @@ static void check_for_deinit(busio_spi_obj_t *self) { //| .. note:: On the SAMD21, it is possible to set the baudrate to 24 MHz, but that //| speed is not guaranteed to work. 12 MHz is the next available lower speed, and is //| within spec for the SAMD21. -//| -//| .. note:: On the nRF52840, these baudrates are available: 125kHz, 250kHz, 1MHz, 2MHz, 4MHz, -//| and 8MHz. -//| If you pick a a baudrate other than one of these, the nearest lower -//| baudrate will be chosen, with a minimum of 125kHz. -//| Two SPI objects may be created, except on the Circuit Playground Bluefruit, -//| which allows only one (to allow for an additional I2C object).""" +//| """ //| ... //| +const mp_arg_t busio_spi_configure_args[] = { + { MP_QSTR_baudrate, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 100000} }, + { MP_QSTR_polarity, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_phase, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_bits, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 8} }, +}; + static mp_obj_t busio_spi_configure(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { enum { ARG_baudrate, ARG_polarity, ARG_phase, ARG_bits }; - static const mp_arg_t allowed_args[] = { - { MP_QSTR_baudrate, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 100000} }, - { MP_QSTR_polarity, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, - { MP_QSTR_phase, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, - { MP_QSTR_bits, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 8} }, - }; busio_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_arg_val_t args[MP_ARRAY_SIZE(busio_spi_configure_args)]; + mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(busio_spi_configure_args), busio_spi_configure_args, args); uint8_t polarity = (uint8_t)mp_arg_validate_int_range(args[ARG_polarity].u_int, 0, 1, MP_QSTR_polarity); uint8_t phase = (uint8_t)mp_arg_validate_int_range(args[ARG_phase].u_int, 0, 1, MP_QSTR_phase); @@ -207,6 +208,12 @@ MP_DEFINE_CONST_FUN_OBJ_KW(busio_spi_configure_obj, 1, busio_spi_configure); //| def try_lock(self) -> bool: //| """Attempts to grab the SPI lock. Returns True on success. //| +//| .. warning:: Ideally, release the lock with `unlock()` as soon as you are done with the bus. +//| Use :class:`~adafruit_bus_device.SPIDevice`, which holds the lock only +//| during each transaction. +//| On Espressif boards, holding the lock for a long time while using WiFi +//| can starve the WiFi and USB tasks, and the board may hang or restart in safe mode. +//| //| :return: True when lock has been grabbed //| :rtype: bool""" //| ... @@ -248,36 +255,28 @@ MP_DEFINE_CONST_FUN_OBJ_1(busio_spi_unlock_obj, busio_spi_obj_unlock); //| ... //| +const mp_arg_t busio_spi_write_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} }, +}; + static mp_obj_t busio_spi_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[] = { - { 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} }, - }; busio_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[ARG_buffer].u_obj, &bufinfo, MP_BUFFER_READ); - // Compute bounds in terms of elements, not bytes. - int stride_in_bytes = mp_binary_get_size('@', bufinfo.typecode, NULL); - int32_t start = args[ARG_start].u_int; - size_t length = bufinfo.len / stride_in_bytes; - normalize_buffer_bounds(&start, args[ARG_end].u_int, &length); - - // Treat start and length in terms of bytes from now on. - start *= stride_in_bytes; - length *= stride_in_bytes; + mp_arg_val_t args[MP_ARRAY_SIZE(busio_spi_write_args)]; + mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(busio_spi_write_args), busio_spi_write_args, args); + size_t length; + uint8_t *data = buffer_slice(args[ARG_buffer].u_obj, args[ARG_start].u_int, args[ARG_end].u_int, + MP_BUFFER_READ, &length); if (length == 0) { 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, data, length); if (!ok) { mp_raise_OSError(MP_EIO); } @@ -314,37 +313,29 @@ MP_DEFINE_CONST_FUN_OBJ_KW(busio_spi_write_obj, 1, busio_spi_write); //| ... //| +const mp_arg_t busio_spi_readinto_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} }, +}; + static mp_obj_t busio_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} }, - }; busio_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[ARG_buffer].u_obj, &bufinfo, MP_BUFFER_WRITE); - // Compute bounds in terms of elements, not bytes. - int stride_in_bytes = mp_binary_get_size('@', bufinfo.typecode, NULL); - int32_t start = args[ARG_start].u_int; - size_t length = bufinfo.len / stride_in_bytes; - normalize_buffer_bounds(&start, args[ARG_end].u_int, &length); - - // Treat start and length in terms of bytes from now on. - start *= stride_in_bytes; - length *= stride_in_bytes; + mp_arg_val_t args[MP_ARRAY_SIZE(busio_spi_readinto_args)]; + mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(busio_spi_readinto_args), busio_spi_readinto_args, args); + size_t length; + uint8_t *data = buffer_slice(args[ARG_buffer].u_obj, args[ARG_start].u_int, args[ARG_end].u_int, + MP_BUFFER_WRITE, &length); if (length == 0) { 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, data, length, args[ARG_write_value].u_int); if (!ok) { mp_raise_OSError(MP_EIO); } @@ -389,41 +380,28 @@ MP_DEFINE_CONST_FUN_OBJ_KW(busio_spi_readinto_obj, 1, busio_spi_readinto); //| ... //| +const mp_arg_t busio_spi_write_readinto_args[] = { + { MP_QSTR_out_buffer, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_in_buffer, 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} }, +}; + static mp_obj_t busio_spi_write_readinto(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { enum { ARG_out_buffer, ARG_in_buffer, ARG_out_start, ARG_out_end, ARG_in_start, ARG_in_end }; - static const mp_arg_t allowed_args[] = { - { MP_QSTR_out_buffer, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, - { MP_QSTR_in_buffer, 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} }, - }; busio_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 buf_out_info; - mp_get_buffer_raise(args[ARG_out_buffer].u_obj, &buf_out_info, MP_BUFFER_READ); - int out_stride_in_bytes = mp_binary_get_size('@', buf_out_info.typecode, NULL); - int32_t out_start = args[ARG_out_start].u_int; - size_t out_length = buf_out_info.len / out_stride_in_bytes; - 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_in_buffer].u_obj, &buf_in_info, MP_BUFFER_WRITE); - int in_stride_in_bytes = mp_binary_get_size('@', buf_in_info.typecode, NULL); - int32_t in_start = args[ARG_in_start].u_int; - size_t in_length = buf_in_info.len / in_stride_in_bytes; - normalize_buffer_bounds(&in_start, args[ARG_in_end].u_int, &in_length); - - // Treat start and length in terms of bytes from now on. - out_start *= out_stride_in_bytes; - out_length *= out_stride_in_bytes; - in_start *= in_stride_in_bytes; - in_length *= in_stride_in_bytes; + mp_arg_val_t args[MP_ARRAY_SIZE(busio_spi_write_readinto_args)]; + mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(busio_spi_write_readinto_args), busio_spi_write_readinto_args, args); + + size_t out_length, in_length; + const uint8_t *data_out = buffer_slice(args[ARG_out_buffer].u_obj, args[ARG_out_start].u_int, + args[ARG_out_end].u_int, MP_BUFFER_READ, &out_length); + uint8_t *data_in = buffer_slice(args[ARG_in_buffer].u_obj, args[ARG_in_start].u_int, + args[ARG_in_end].u_int, MP_BUFFER_WRITE, &in_length); if (out_length != in_length) { mp_raise_ValueError(MP_ERROR_TEXT("buffer slices must be of equal length")); @@ -433,10 +411,7 @@ static mp_obj_t busio_spi_write_readinto(size_t n_args, const mp_obj_t *pos_args return mp_const_none; } - 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); + bool ok = common_hal_busio_spi_transfer(self, data_out, data_in, out_length); if (!ok) { mp_raise_OSError(MP_EIO); } @@ -445,9 +420,14 @@ static mp_obj_t busio_spi_write_readinto(size_t n_args, const mp_obj_t *pos_args MP_DEFINE_CONST_FUN_OBJ_KW(busio_spi_write_readinto_obj, 1, busio_spi_write_readinto); //| frequency: int -//| """The actual SPI bus frequency. This may not match the frequency requested -//| due to internal limitations.""" +//| """The actual SPI bus frequency. This may be lower than the frequency requested +//| due to internal limitations, but it will not be higher. //| +//| **Limitations**: On Zephyr, the returned value does not reflect the actual baudrate, +//| because there is `no way to fetch the actual chosen frequency +//| `_. +//| In addition, on Zephyr, the ceiling behavior described in `configure` may be violated. +//| """ //| static mp_obj_t busio_spi_obj_get_frequency(mp_obj_t self_in) { @@ -466,6 +446,7 @@ MP_PROPERTY_GETTER(busio_spi_frequency_obj, static const mp_rom_map_elem_t busio_spi_locals_dict_table[] = { #if CIRCUITPY_BUSIO_SPI { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&busio_spi_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&busio_spi_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, @@ -493,3 +474,17 @@ MP_DEFINE_CONST_OBJ_TYPE( busio_spi_obj_t *validate_obj_is_spi_bus(mp_obj_t obj, qstr arg_name) { return mp_arg_validate_type(obj, &busio_spi_type, arg_name); } + +// Wait as long as needed for the lock. This is used by SD card access from USB. +// The default implementation is to busy-wait while running the background tasks. espressif is different. +bool common_hal_busio_spi_wait_for_lock(busio_spi_obj_t *self, uint32_t timeout_ms) { + uint64_t deadline = supervisor_ticks_ms64() + timeout_ms; + while (supervisor_ticks_ms64() < deadline && + !mp_hal_is_interrupted()) { + if (common_hal_busio_spi_try_lock(self)) { + return true; + } + RUN_BACKGROUND_TASKS; + } + return false; +} diff --git a/shared-bindings/busio/SPI.h b/shared-bindings/busio/SPI.h index 69e582411a1..aefddf69e8d 100644 --- a/shared-bindings/busio/SPI.h +++ b/shared-bindings/busio/SPI.h @@ -7,6 +7,8 @@ #pragma once #include "py/obj.h" +#include "py/runtime.h" +#include "supervisor/shared/async_flag.h" #include "common-hal/microcontroller/Pin.h" #include "common-hal/busio/SPI.h" @@ -14,6 +16,13 @@ // Type object used in Python. Should be shared between ports. extern const mp_obj_type_t busio_spi_type; +// Argument tables, also used by async_spi.SPI, which takes the same arguments. +extern const mp_arg_t busio_spi_make_new_args[4]; // clock, MOSI, MISO, half_duplex +extern const mp_arg_t busio_spi_configure_args[4]; +extern const mp_arg_t busio_spi_write_args[3]; +extern const mp_arg_t busio_spi_readinto_args[4]; +extern const mp_arg_t busio_spi_write_readinto_args[6]; + // 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, @@ -22,6 +31,10 @@ extern void common_hal_busio_spi_construct(busio_spi_obj_t *self, extern void common_hal_busio_spi_deinit(busio_spi_obj_t *self); extern bool common_hal_busio_spi_deinited(busio_spi_obj_t *self); +// Mark as deinit without deiniting. This is used by displayio after copying the +// object elsewhere and prevents the heap from deiniting the object. +extern void common_hal_busio_spi_mark_deinit(busio_spi_obj_t *self); + extern bool common_hal_busio_spi_configure(busio_spi_obj_t *self, uint32_t baudrate, uint8_t polarity, uint8_t phase, uint8_t bits); extern bool common_hal_busio_spi_try_lock(busio_spi_obj_t *self); @@ -31,6 +44,17 @@ extern void common_hal_busio_spi_unlock(busio_spi_obj_t *self); // Writes out the given data. extern bool common_hal_busio_spi_write(busio_spi_obj_t *self, const uint8_t *data, size_t len); +#if CIRCUITPY_BUSIO_SPI_ASYNC +// Start writing data and return, possibly before it has been sent. *done is set once it has been +// sent, at the latest by common_hal_busio_spi_end(). data must stay valid and unchanged, and +// the bus must not be used, until then. +extern void common_hal_busio_spi_write_start(busio_spi_obj_t *self, const uint8_t *data, size_t len, + circuitpy_async_flag_t *done); +// Finish the transfer started by a common_hal_busio_spi_*_start(), waiting if needed. Returns +// at once if there is none. +extern void common_hal_busio_spi_end(busio_spi_obj_t *self); +#endif + // Reads in len bytes while outputting the byte write_value. extern bool common_hal_busio_spi_read(busio_spi_obj_t *self, uint8_t *data, size_t len, uint8_t write_value); @@ -46,7 +70,8 @@ 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); -// This is used by the supervisor to claim SPI devices indefinitely. -extern void common_hal_busio_spi_never_reset(busio_spi_obj_t *self); - extern busio_spi_obj_t *validate_obj_is_spi_bus(mp_obj_t obj_in, qstr arg_name); + +// Wait as long as needed for the lock. This is used by SD card access from USB. +// For most ports, busy-wait while running the background tasks. +MP_WEAK bool common_hal_busio_spi_wait_for_lock(busio_spi_obj_t *self, uint32_t timeout_ms); diff --git a/shared-bindings/busio/UART.c b/shared-bindings/busio/UART.c index 5f1d301b675..f579d15ae38 100644 --- a/shared-bindings/busio/UART.c +++ b/shared-bindings/busio/UART.c @@ -77,8 +77,8 @@ //| *New in CircuitPython 4.0:* ``timeout`` has incompatibly changed units from milliseconds to seconds. //| The new upper limit on ``timeout`` is meant to catch mistaken use of milliseconds. //| -//| **Limitations:** RS485 is not supported on SAMD, Nordic, Broadcom, Spresense, or STM. -//| On i.MX and Raspberry Pi RP2040, RS485 support is implemented in software: +//| **Limitations:** RS485 is available only on Espressif, i.MX, and Raspberry Pi RP2xxx. +//| On i.MX and RP2xxx, RS485 support is implemented in software: //| The timing for the ``rs485_dir`` pin signal is done on a best-effort basis, and may not meet //| RS485 specifications intermittently. //| """ @@ -157,7 +157,7 @@ static mp_obj_t busio_uart_make_new(const mp_obj_type_t *type, size_t n_args, si common_hal_busio_uart_construct(self, tx, rx, rts, cts, rs485_dir, rs485_invert, args[ARG_baudrate].u_int, bits, parity, stop, timeout, buffer_size, NULL, false); - return (mp_obj_t)self; + return MP_OBJ_FROM_PTR(self); #else mp_raise_NotImplementedError(NULL); #endif // CIRCUITPY_BUSIO_UART @@ -277,7 +277,7 @@ static mp_uint_t busio_uart_write(mp_obj_t self_in, const void *buf_in, mp_uint_ return common_hal_busio_uart_write(self, buf, size, errcode); } -static mp_uint_t busio_uart_ioctl(mp_obj_t self_in, mp_uint_t request, mp_uint_t arg, int *errcode) { +static mp_uint_t busio_uart_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) { busio_uart_obj_t *self = native_uart(self_in); check_for_deinit(self); mp_uint_t ret; @@ -368,14 +368,14 @@ static mp_obj_t busio_uart_obj_reset_input_buffer(mp_obj_t self_in) { return mp_const_none; } static MP_DEFINE_CONST_FUN_OBJ_1(busio_uart_reset_input_buffer_obj, busio_uart_obj_reset_input_buffer); -//| class Parity: -//| """Enum-like class to define the parity used to verify correct data transfer.""" +//| class Parity: +//| """Enum-like class to define the parity used to verify correct data transfer.""" //| -//| ODD: int -//| """Total number of ones should be odd.""" +//| ODD: int +//| """Total number of ones should be odd.""" //| -//| EVEN: int -//| """Total number of ones should be even.""" +//| EVEN: int +//| """Total number of ones should be even.""" //| //| const mp_obj_type_t busio_uart_parity_type; diff --git a/shared-bindings/busio/UART.h b/shared-bindings/busio/UART.h index c8e6755c129..2bbf6a3f7b6 100644 --- a/shared-bindings/busio/UART.h +++ b/shared-bindings/busio/UART.h @@ -46,5 +46,3 @@ extern void common_hal_busio_uart_set_timeout(busio_uart_obj_t *self, mp_float_t extern uint32_t common_hal_busio_uart_rx_characters_available(busio_uart_obj_t *self); extern void common_hal_busio_uart_clear_rx_buffer(busio_uart_obj_t *self); extern bool common_hal_busio_uart_ready_to_tx(busio_uart_obj_t *self); - -extern void common_hal_busio_uart_never_reset(busio_uart_obj_t *self); diff --git a/shared-bindings/camera/Camera.c b/shared-bindings/camera/Camera.c index 6f42fa08bcf..67e7091e01a 100644 --- a/shared-bindings/camera/Camera.c +++ b/shared-bindings/camera/Camera.c @@ -41,10 +41,10 @@ //| ... //| static mp_obj_t camera_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { - camera_obj_t *self = mp_obj_malloc(camera_obj_t, &camera_type); // No arguments mp_arg_check_num(n_args, n_kw, 0, 0, false); + camera_obj_t *self = mp_obj_malloc_with_finaliser(camera_obj_t, &camera_type); common_hal_camera_construct(self); return MP_OBJ_FROM_PTR(self); } @@ -99,6 +99,7 @@ MP_DEFINE_CONST_FUN_OBJ_KW(camera_take_picture_obj, 1, camera_obj_take_picture); static const mp_rom_map_elem_t camera_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&camera_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&camera_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR_take_picture), MP_ROM_PTR(&camera_take_picture_obj) }, }; static MP_DEFINE_CONST_DICT(camera_locals_dict, camera_locals_dict_table); diff --git a/shared-bindings/canio/CAN.c b/shared-bindings/canio/CAN.c index ff46eb26da2..6979922a94f 100644 --- a/shared-bindings/canio/CAN.c +++ b/shared-bindings/canio/CAN.c @@ -64,7 +64,7 @@ static mp_obj_t canio_can_make_new(const mp_obj_type_t *type, size_t n_args, siz mp_raise_ValueError(MP_ERROR_TEXT("tx and rx cannot both be None")); } - canio_can_obj_t *self = mp_obj_malloc(canio_can_obj_t, &canio_can_type); + canio_can_obj_t *self = mp_obj_malloc_with_finaliser(canio_can_obj_t, &canio_can_type); common_hal_canio_can_construct(self, tx_pin, rx_pin, args[ARG_baudrate].u_int, args[ARG_loopback].u_bool, args[ARG_silent].u_bool); common_hal_canio_can_auto_restart_set(self, args[ARG_auto_restart].u_bool); @@ -224,8 +224,7 @@ static mp_obj_t canio_can_listen(size_t n_args, const mp_obj_t *pos_args, mp_map } float timeout = args[ARG_timeout].u_obj ? mp_obj_get_float(args[ARG_timeout].u_obj) : 10.0f; - canio_listener_obj_t *listener = m_new_obj(canio_listener_obj_t); - listener->base.type = &canio_listener_type; + canio_listener_obj_t *listener = mp_obj_malloc_with_finaliser(canio_listener_obj_t, &canio_listener_type); common_hal_canio_listener_construct(listener, self, nmatch, matches, timeout); return listener; } @@ -326,6 +325,7 @@ static const mp_rom_map_elem_t canio_can_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_auto_restart), MP_ROM_PTR(&canio_can_auto_restart_obj) }, { MP_ROM_QSTR(MP_QSTR_baudrate), MP_ROM_PTR(&canio_can_baudrate_obj) }, { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&canio_can_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&canio_can_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR_listen), MP_ROM_PTR(&canio_can_listen_obj) }, { MP_ROM_QSTR(MP_QSTR_loopback), MP_ROM_PTR(&canio_can_loopback_obj) }, { MP_ROM_QSTR(MP_QSTR_receive_error_count), MP_ROM_PTR(&canio_can_receive_error_count_obj) }, diff --git a/shared-bindings/canio/CAN.h b/shared-bindings/canio/CAN.h index cb795315346..6e446ec2292 100644 --- a/shared-bindings/canio/CAN.h +++ b/shared-bindings/canio/CAN.h @@ -29,4 +29,3 @@ 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_restart(canio_can_obj_t *self); void common_hal_canio_can_send(canio_can_obj_t *self, mp_obj_t message); -void common_hal_canio_reset(void); diff --git a/shared-bindings/canio/Listener.c b/shared-bindings/canio/Listener.c index 0fd53eecbef..ccdc77e372a 100644 --- a/shared-bindings/canio/Listener.c +++ b/shared-bindings/canio/Listener.c @@ -148,6 +148,7 @@ static const mp_rom_map_elem_t canio_listener_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&canio_listener_enter_obj) }, { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&canio_listener_exit_obj) }, { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&canio_listener_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&canio_listener_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR_in_waiting), MP_ROM_PTR(&canio_listener_in_waiting_obj) }, { MP_ROM_QSTR(MP_QSTR_receive), MP_ROM_PTR(&canio_listener_receive_obj) }, { MP_ROM_QSTR(MP_QSTR_timeout), MP_ROM_PTR(&canio_listener_timeout_obj) }, diff --git a/shared-bindings/canio/Match.c b/shared-bindings/canio/Match.c index 5e44a7ce4ed..e7c3dba42aa 100644 --- a/shared-bindings/canio/Match.c +++ b/shared-bindings/canio/Match.c @@ -47,7 +47,8 @@ static mp_obj_t canio_match_make_new(const mp_obj_type_t *type, size_t n_args, s canio_match_obj_t *self = mp_obj_malloc(canio_match_obj_t, &canio_match_type); common_hal_canio_match_construct(self, id, mask, args[ARG_extended].u_bool); - return self; + + return MP_OBJ_FROM_PTR(self); } //| id: int diff --git a/shared-bindings/canio/Message.c b/shared-bindings/canio/Message.c index c40892b5edb..848b5b15e43 100644 --- a/shared-bindings/canio/Message.c +++ b/shared-bindings/canio/Message.c @@ -41,7 +41,8 @@ static mp_obj_t canio_message_make_new(const mp_obj_type_t *type, size_t n_args, canio_message_obj_t *self = mp_obj_malloc(canio_message_obj_t, &canio_message_type); common_hal_canio_message_construct(self, args[ARG_id].u_int, data.buf, data.len, args[ARG_extended].u_bool); - return self; + + return MP_OBJ_FROM_PTR(self); } //| id: int diff --git a/shared-bindings/canio/RemoteTransmissionRequest.c b/shared-bindings/canio/RemoteTransmissionRequest.c index 966fee71215..bdc91c494a4 100644 --- a/shared-bindings/canio/RemoteTransmissionRequest.c +++ b/shared-bindings/canio/RemoteTransmissionRequest.c @@ -42,7 +42,8 @@ static mp_obj_t canio_remote_transmission_request_make_new(const mp_obj_type_t * canio_remote_transmission_request_obj_t *self = mp_obj_malloc(canio_remote_transmission_request_obj_t, &canio_remote_transmission_request_type); common_hal_canio_remote_transmission_request_construct(self, args[ARG_id].u_int, length, args[ARG_extended].u_bool); - return self; + + return MP_OBJ_FROM_PTR(self); } diff --git a/shared-bindings/canio/__init__.c b/shared-bindings/canio/__init__.c index c65b119ff24..2300a6652dd 100644 --- a/shared-bindings/canio/__init__.c +++ b/shared-bindings/canio/__init__.c @@ -36,7 +36,7 @@ //| //| Other implementations of the CAN device may exist (for instance, attached //| via an SPI bus). If so their constructor arguments may differ, but -//| otherwise we encourage implementors to follow the API that the core uses. +//| otherwise we encourage implementers to follow the API that the core uses. //| //| For more information on working with this module, refer to //| `this Learn Guide on using it `_. diff --git a/shared-bindings/countio/Counter.c b/shared-bindings/countio/Counter.c index c2e3ddc7404..9c03098e72b 100644 --- a/shared-bindings/countio/Counter.c +++ b/shared-bindings/countio/Counter.c @@ -47,7 +47,7 @@ //| pin_counter.reset() //| print(pin_counter.count) //| -//| **Limitations:** On RP2040, `Counter` uses the PWM peripheral, and +//| **Limitations:** On RP2xxx, `Counter` uses the PWM peripheral, and //| is limited to using PWM channel B pins due to hardware restrictions. //| See the pin assignments for your board to see which pins can be used. //| """ @@ -66,8 +66,8 @@ static mp_obj_t countio_counter_make_new(const mp_obj_type_t *type, size_t n_arg const mcu_pin_obj_t *pin = validate_obj_is_free_pin(args[ARG_pin].u_obj, MP_QSTR_pin); const countio_edge_t edge = validate_edge(args[ARG_edge].u_obj, MP_QSTR_edge); const digitalio_pull_t pull = validate_pull(args[ARG_pull].u_obj, MP_QSTR_pull); - countio_counter_obj_t *self = mp_obj_malloc_with_finaliser(countio_counter_obj_t, &countio_counter_type); + countio_counter_obj_t *self = mp_obj_malloc_with_finaliser(countio_counter_obj_t, &countio_counter_type); common_hal_countio_counter_construct(self, pin, edge, pull); return MP_OBJ_FROM_PTR(self); diff --git a/shared-bindings/countio/Edge.c b/shared-bindings/countio/Edge.c index 9ace6a923ff..7453720d12a 100644 --- a/shared-bindings/countio/Edge.c +++ b/shared-bindings/countio/Edge.c @@ -30,7 +30,7 @@ MAKE_ENUM_VALUE(countio_edge_type, edge, RISE_AND_FALL, EDGE_RISE_AND_FALL); //| RISE_AND_FALL: Edge //| """Count the rising and falling edges. //| -//| **Limitations:** ``RISE_AND_FALL`` is not available to RP2040 due to hardware limitations. +//| **Limitations:** ``RISE_AND_FALL`` is not available on RP2xxx due to hardware limitations. //| """ //| //| diff --git a/shared-bindings/cryptography/__init__.c b/shared-bindings/cryptography/__init__.c new file mode 100644 index 00000000000..bab002774ab --- /dev/null +++ b/shared-bindings/cryptography/__init__.c @@ -0,0 +1,36 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#include "py/obj.h" +#include "py/runtime.h" + +#include "shared-bindings/cryptography/__init__.h" +#include "shared-bindings/cryptography/exceptions/__init__.h" +#include "shared-bindings/cryptography/hazmat/__init__.h" + +//| """A subset of PyCA's `cryptography `_ package +//| +//| ``cryptography``'s nesting is mirrored module-for-module (``cryptography.hazmat.primitives.asymmetric.rsa``, +//| not a flattened equivalent) so that code written against this module is, +//| as far as it goes, portable to CPython unchanged. Only the pieces this +//| board's hardware can actually back are present -- today, just +//| `DigitalSignatureKey` for the Digital Signature peripheral. +//| """ +//| + +static mp_rom_map_elem_t cryptography_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR_cryptography) }, + { MP_ROM_QSTR(MP_QSTR_exceptions), MP_OBJ_FROM_PTR(&cryptography_exceptions_module) }, + { MP_ROM_QSTR(MP_QSTR_hazmat), MP_OBJ_FROM_PTR(&cryptography_hazmat_module) }, +}; +static MP_DEFINE_CONST_DICT(cryptography_module_globals, cryptography_module_globals_table); + +const mp_obj_module_t cryptography_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&cryptography_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_cryptography, cryptography_module); diff --git a/shared-bindings/cryptography/__init__.h b/shared-bindings/cryptography/__init__.h new file mode 100644 index 00000000000..459b9fc64f4 --- /dev/null +++ b/shared-bindings/cryptography/__init__.h @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#pragma once diff --git a/shared-bindings/cryptography/exceptions/__init__.c b/shared-bindings/cryptography/exceptions/__init__.c new file mode 100644 index 00000000000..dfffdae6d52 --- /dev/null +++ b/shared-bindings/cryptography/exceptions/__init__.c @@ -0,0 +1,59 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#include + +#include "py/objexcept.h" +#include "py/runtime.h" + +#include "shared-bindings/cryptography/exceptions/__init__.h" + +//| """Exceptions +//| +//| A subset of :py:mod:`cryptography.exceptions`: just `InvalidSignature`, so +//| that code written against this module can use +//| ``except cryptography.exceptions.InvalidSignature:`` unchanged on CPython. +//| """ +//| + +//| class InvalidSignature(Exception): +//| """Raised by +//| :py:meth:`cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey.verify` +//| when a signature does not verify, or is malformed. Mirrors +//| :py:class:`cryptography.exceptions.InvalidSignature`.""" +//| +//| ... +//| +MP_DEFINE_CONST_OBJ_TYPE( + mp_type_cryptography_InvalidSignature, + MP_QSTR_InvalidSignature, + MP_TYPE_FLAG_NONE, + make_new, mp_obj_exception_make_new, + print, mp_obj_exception_print, + attr, mp_obj_exception_attr, + parent, &mp_type_Exception + ); + +MP_NORETURN void mp_raise_cryptography_InvalidSignature(mp_rom_error_text_t fmt, ...) { + va_list argptr; + va_start(argptr, fmt); + mp_obj_t exception = mp_obj_new_exception_msg_vlist(&mp_type_cryptography_InvalidSignature, fmt, argptr); + va_end(argptr); + nlr_raise(exception); +} + +static mp_rom_map_elem_t cryptography_exceptions_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR_cryptography_dot_exceptions) }, + { MP_ROM_QSTR(MP_QSTR_InvalidSignature), MP_ROM_PTR(&mp_type_cryptography_InvalidSignature) }, +}; +static MP_DEFINE_CONST_DICT(cryptography_exceptions_module_globals, cryptography_exceptions_module_globals_table); + +const mp_obj_module_t cryptography_exceptions_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&cryptography_exceptions_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_cryptography_dot_exceptions, cryptography_exceptions_module); diff --git a/shared-bindings/cryptography/exceptions/__init__.h b/shared-bindings/cryptography/exceptions/__init__.h new file mode 100644 index 00000000000..91c6dd6d3ec --- /dev/null +++ b/shared-bindings/cryptography/exceptions/__init__.h @@ -0,0 +1,15 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +extern const mp_obj_module_t cryptography_exceptions_module; + +extern const mp_obj_type_t mp_type_cryptography_InvalidSignature; + +MP_NORETURN void mp_raise_cryptography_InvalidSignature(mp_rom_error_text_t fmt, ...); diff --git a/shared-bindings/cryptography/hazmat/__init__.c b/shared-bindings/cryptography/hazmat/__init__.c new file mode 100644 index 00000000000..71431f6a1b9 --- /dev/null +++ b/shared-bindings/cryptography/hazmat/__init__.c @@ -0,0 +1,31 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#include "py/obj.h" +#include "py/runtime.h" + +#include "shared-bindings/cryptography/hazmat/__init__.h" +#include "shared-bindings/cryptography/hazmat/primitives/__init__.h" + +//| """Hazardous materials +//| +//| A subset of :py:mod:`cryptography.hazmat`, named for the real module's own +//| warning that misusing what is here can silently produce insecure results. +//| """ +//| + +static mp_rom_map_elem_t cryptography_hazmat_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR_cryptography_dot_hazmat) }, + { MP_ROM_QSTR(MP_QSTR_primitives), MP_OBJ_FROM_PTR(&cryptography_hazmat_primitives_module) }, +}; +static MP_DEFINE_CONST_DICT(cryptography_hazmat_module_globals, cryptography_hazmat_module_globals_table); + +const mp_obj_module_t cryptography_hazmat_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&cryptography_hazmat_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_cryptography_dot_hazmat, cryptography_hazmat_module); diff --git a/shared-bindings/cryptography/hazmat/__init__.h b/shared-bindings/cryptography/hazmat/__init__.h new file mode 100644 index 00000000000..323befacd98 --- /dev/null +++ b/shared-bindings/cryptography/hazmat/__init__.h @@ -0,0 +1,11 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +extern const mp_obj_module_t cryptography_hazmat_module; diff --git a/shared-bindings/cryptography/hazmat/primitives/__init__.c b/shared-bindings/cryptography/hazmat/primitives/__init__.c new file mode 100644 index 00000000000..01012a0996f --- /dev/null +++ b/shared-bindings/cryptography/hazmat/primitives/__init__.c @@ -0,0 +1,32 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#include "py/obj.h" +#include "py/runtime.h" + +#include "shared-bindings/cryptography/hazmat/primitives/__init__.h" +#include "shared-bindings/cryptography/hazmat/primitives/asymmetric/__init__.h" +#include "shared-bindings/cryptography/hazmat/primitives/hashes/__init__.h" + +//| """Cryptographic primitives +//| +//| A subset of :py:mod:`cryptography.hazmat.primitives`. +//| """ +//| + +static mp_rom_map_elem_t cryptography_hazmat_primitives_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR_cryptography_dot_hazmat_dot_primitives) }, + { MP_ROM_QSTR(MP_QSTR_asymmetric), MP_OBJ_FROM_PTR(&cryptography_hazmat_primitives_asymmetric_module) }, + { MP_ROM_QSTR(MP_QSTR_hashes), MP_OBJ_FROM_PTR(&cryptography_hazmat_primitives_hashes_module) }, +}; +static MP_DEFINE_CONST_DICT(cryptography_hazmat_primitives_module_globals, cryptography_hazmat_primitives_module_globals_table); + +const mp_obj_module_t cryptography_hazmat_primitives_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&cryptography_hazmat_primitives_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_cryptography_dot_hazmat_dot_primitives, cryptography_hazmat_primitives_module); diff --git a/shared-bindings/cryptography/hazmat/primitives/__init__.h b/shared-bindings/cryptography/hazmat/primitives/__init__.h new file mode 100644 index 00000000000..56ac24849c0 --- /dev/null +++ b/shared-bindings/cryptography/hazmat/primitives/__init__.h @@ -0,0 +1,11 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +extern const mp_obj_module_t cryptography_hazmat_primitives_module; diff --git a/shared-bindings/cryptography/hazmat/primitives/asymmetric/__init__.c b/shared-bindings/cryptography/hazmat/primitives/asymmetric/__init__.c new file mode 100644 index 00000000000..1b9aa1a0f0d --- /dev/null +++ b/shared-bindings/cryptography/hazmat/primitives/asymmetric/__init__.c @@ -0,0 +1,36 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#include "py/obj.h" +#include "py/runtime.h" + +#include "shared-bindings/cryptography/hazmat/primitives/asymmetric/__init__.h" +#include "shared-bindings/cryptography/hazmat/primitives/asymmetric/ec/__init__.h" +#include "shared-bindings/cryptography/hazmat/primitives/asymmetric/padding/__init__.h" +#include "shared-bindings/cryptography/hazmat/primitives/asymmetric/rsa/__init__.h" +#include "shared-bindings/cryptography/hazmat/primitives/asymmetric/utils/__init__.h" + +//| """Asymmetric-key primitives +//| +//| A subset of :py:mod:`cryptography.hazmat.primitives.asymmetric`. +//| """ +//| + +static mp_rom_map_elem_t cryptography_hazmat_primitives_asymmetric_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR_cryptography_dot_hazmat_dot_primitives_dot_asymmetric) }, + { MP_ROM_QSTR(MP_QSTR_ec), MP_OBJ_FROM_PTR(&cryptography_hazmat_primitives_asymmetric_ec_module) }, + { MP_ROM_QSTR(MP_QSTR_padding), MP_OBJ_FROM_PTR(&cryptography_hazmat_primitives_asymmetric_padding_module) }, + { MP_ROM_QSTR(MP_QSTR_rsa), MP_OBJ_FROM_PTR(&cryptography_hazmat_primitives_asymmetric_rsa_module) }, + { MP_ROM_QSTR(MP_QSTR_utils), MP_OBJ_FROM_PTR(&cryptography_hazmat_primitives_asymmetric_utils_module) }, +}; +static MP_DEFINE_CONST_DICT(cryptography_hazmat_primitives_asymmetric_module_globals, cryptography_hazmat_primitives_asymmetric_module_globals_table); + +const mp_obj_module_t cryptography_hazmat_primitives_asymmetric_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&cryptography_hazmat_primitives_asymmetric_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_cryptography_dot_hazmat_dot_primitives_dot_asymmetric, cryptography_hazmat_primitives_asymmetric_module); diff --git a/shared-bindings/cryptography/hazmat/primitives/asymmetric/__init__.h b/shared-bindings/cryptography/hazmat/primitives/asymmetric/__init__.h new file mode 100644 index 00000000000..b1dd729c7d3 --- /dev/null +++ b/shared-bindings/cryptography/hazmat/primitives/asymmetric/__init__.h @@ -0,0 +1,11 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +extern const mp_obj_module_t cryptography_hazmat_primitives_asymmetric_module; diff --git a/shared-bindings/cryptography/hazmat/primitives/asymmetric/ec/EllipticCurvePublicKey.c b/shared-bindings/cryptography/hazmat/primitives/asymmetric/ec/EllipticCurvePublicKey.c new file mode 100644 index 00000000000..4c5ab19fde4 --- /dev/null +++ b/shared-bindings/cryptography/hazmat/primitives/asymmetric/ec/EllipticCurvePublicKey.c @@ -0,0 +1,173 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#include "py/objproperty.h" +#include "py/runtime.h" + +#include "shared-bindings/cryptography/hazmat/primitives/asymmetric/ec/EllipticCurvePublicKey.h" +#include "shared-bindings/cryptography/hazmat/primitives/asymmetric/ec/__init__.h" +#include "shared-bindings/cryptography/hazmat/primitives/asymmetric/utils/__init__.h" +#include "shared-bindings/cryptography/hazmat/primitives/hashes/__init__.h" + +//| class EllipticCurvePublicKey: +//| """An elliptic-curve public key, usable to verify signatures made by +//| the matching private key. This class cannot be instantiated directly +//| -- get one from `from_encoded_point()`. +//| +//| Mirrors the method shape of +//| :py:class:`cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey` +//| (``verify``, ``public_bytes``, ``curve``, ``key_size``), but not +//| every method on that class -- there is intentionally no +//| ``public_numbers()``; only the raw-point `public_bytes` encoding this +//| module already stores is supported. +//| """ +//| + +//| @classmethod +//| def from_encoded_point(cls, curve: object, data: ReadableBuffer) -> EllipticCurvePublicKey: +//| """Build a public key from an uncompressed SEC1 point. Mirrors +//| :py:meth:`cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey.from_encoded_point`. +//| +//| :param ec.SECP256R1 curve: must be `SECP256R1` -- the only curve supported +//| :param ~circuitpython_typing.ReadableBuffer data: a 65-byte uncompressed +//| point, ``0x04 || X || Y`` +//| :raises ValueError: if ``data`` is not a valid point for ``curve`` +//| """ +//| ... +static mp_obj_t cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_from_encoded_point(mp_obj_t cls_in, mp_obj_t curve_in, mp_obj_t data_in) { + if (!mp_obj_is_type(curve_in, &cryptography_hazmat_primitives_asymmetric_ec_secp256r1_type)) { + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("Only %q supported"), MP_QSTR_SECP256R1); + } + + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(data_in, &bufinfo, MP_BUFFER_READ); + + cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_obj_t *self = + mp_obj_malloc(cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_obj_t, + &cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_type); + common_hal_cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_construct(self, + curve_in, bufinfo.buf, bufinfo.len); + return MP_OBJ_FROM_PTR(self); +} +static MP_DEFINE_CONST_FUN_OBJ_3(cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_from_encoded_point_fun_obj, cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_from_encoded_point); +static MP_DEFINE_CONST_CLASSMETHOD_OBJ(cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_from_encoded_point_obj, MP_ROM_PTR(&cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_from_encoded_point_fun_obj)); + +//| curve: object +//| """The curve this key was constructed for -- always `SECP256R1`. +//| Mirrors +//| :py:attr:`cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey.curve`. +//| (read-only)""" +static mp_obj_t cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_get_curve(mp_obj_t self_in) { + cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_obj_t *self = MP_OBJ_TO_PTR(self_in); + return self->curve; +} +MP_DEFINE_CONST_FUN_OBJ_1(cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_get_curve_obj, cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_get_curve); +MP_PROPERTY_GETTER(cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_curve_obj, (mp_obj_t)&cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_get_curve_obj); + +//| key_size: int +//| """``256``. Mirrors +//| :py:attr:`cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey.key_size`. +//| (read-only)""" +static mp_obj_t cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_get_key_size(mp_obj_t self_in) { + return MP_OBJ_NEW_SMALL_INT(256); +} +MP_DEFINE_CONST_FUN_OBJ_1(cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_get_key_size_obj, cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_get_key_size); +MP_PROPERTY_GETTER(cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_key_size_obj, (mp_obj_t)&cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_get_key_size_obj); + +//| def verify( +//| self, +//| signature: ReadableBuffer, +//| data: ReadableBuffer, +//| signature_algorithm: object, +//| ) -> None: +//| """Verify ``signature`` over ``data``. Mirrors +//| :py:meth:`cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey.verify`. +//| +//| :param ~circuitpython_typing.ReadableBuffer signature: a DER-encoded +//| ECDSA signature (the ``(r, s)`` pair ASN.1-wrapped, as real PyCA +//| produces/expects -- not the raw ``r || s`` some hardware, e.g. +//| ATECC608-family chips, outputs natively. Use +//| `utils.encode_dss_signature` to convert +//| :param ~circuitpython_typing.ReadableBuffer data: the SHA-256 digest +//| already computed over the signed message (see ``signature_algorithm``) +//| :param ec.ECDSA signature_algorithm: must be +//| ``ECDSA(utils.Prehashed(hashes.SHA256))`` -- the only combination +//| supported. ``data`` is never hashed by this method; the caller +//| must already have a digest +//| :raises cryptography.exceptions.InvalidSignature: if ``signature`` +//| is malformed, or does not verify against ``data`` +//| """ +//| ... +static mp_obj_t cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_verify(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_signature, ARG_data, ARG_signature_algorithm }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_signature, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_data, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_signature_algorithm, MP_ARG_REQUIRED | MP_ARG_OBJ }, + }; + cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]); + + 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); + + if (!mp_obj_is_type(args[ARG_signature_algorithm].u_obj, &cryptography_hazmat_primitives_asymmetric_ec_ecdsa_type)) { + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("Only %q supported"), MP_QSTR_ECDSA); + } + cryptography_hazmat_primitives_asymmetric_ec_ecdsa_obj_t *ecdsa = MP_OBJ_TO_PTR(args[ARG_signature_algorithm].u_obj); + if (!mp_obj_is_type(ecdsa->algorithm, &cryptography_hazmat_primitives_asymmetric_utils_prehashed_type)) { + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("Only %q supported"), MP_QSTR_Prehashed_space_SHA256); + } + cryptography_hazmat_primitives_asymmetric_utils_prehashed_obj_t *prehashed = MP_OBJ_TO_PTR(ecdsa->algorithm); + if (!mp_obj_is_type(prehashed->algorithm, &cryptography_hazmat_primitives_hashes_sha256_type)) { + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("Only %q supported"), MP_QSTR_Prehashed_space_SHA256); + } + + mp_buffer_info_t sig_bufinfo; + mp_get_buffer_raise(args[ARG_signature].u_obj, &sig_bufinfo, MP_BUFFER_READ); + mp_buffer_info_t data_bufinfo; + mp_get_buffer_raise(args[ARG_data].u_obj, &data_bufinfo, MP_BUFFER_READ); + + common_hal_cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_verify(self, + sig_bufinfo.buf, sig_bufinfo.len, data_bufinfo.buf, data_bufinfo.len); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_KW(cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_verify_obj, 1, cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_verify); + +//| def public_bytes(self, encoding: object, format: object) -> bytes: +//| """Return the raw point this key was constructed from. Mirrors +//| :py:meth:`cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey.public_bytes`, +//| restricted to the one encoding this module ever stores -- there is +//| no ``serialization`` module here to construct any other +//| ``encoding``/``format`` value with, so both arguments are accepted +//| for call-shape compatibility and ignored; the result is always the +//| same as the ``data`` originally passed to `from_encoded_point` +//| (uncompressed SEC1, ``0x04 || X || Y``). +//| +//| :param object encoding: ignored +//| :param object format: ignored +//| """ +//| ... +static mp_obj_t cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_public_bytes(mp_obj_t self_in, mp_obj_t encoding_in, mp_obj_t format_in) { + cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_obj_t *self = MP_OBJ_TO_PTR(self_in); + return mp_obj_new_bytes(self->point, sizeof(self->point)); +} +static MP_DEFINE_CONST_FUN_OBJ_3(cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_public_bytes_obj, cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_public_bytes); + +static const mp_rom_map_elem_t cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_from_encoded_point), MP_ROM_PTR(&cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_from_encoded_point_obj) }, + { MP_ROM_QSTR(MP_QSTR_curve), MP_ROM_PTR(&cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_curve_obj) }, + { MP_ROM_QSTR(MP_QSTR_key_size), MP_ROM_PTR(&cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_key_size_obj) }, + { MP_ROM_QSTR(MP_QSTR_verify), MP_ROM_PTR(&cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_verify_obj) }, + { MP_ROM_QSTR(MP_QSTR_public_bytes), MP_ROM_PTR(&cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_public_bytes_obj) }, +}; +static MP_DEFINE_CONST_DICT(cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_locals_dict, cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_type, + MP_QSTR_EllipticCurvePublicKey, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + locals_dict, &cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_locals_dict + ); diff --git a/shared-bindings/cryptography/hazmat/primitives/asymmetric/ec/EllipticCurvePublicKey.h b/shared-bindings/cryptography/hazmat/primitives/asymmetric/ec/EllipticCurvePublicKey.h new file mode 100644 index 00000000000..4f5d0bda86a --- /dev/null +++ b/shared-bindings/cryptography/hazmat/primitives/asymmetric/ec/EllipticCurvePublicKey.h @@ -0,0 +1,15 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +// Object struct and the common_hal_* accessors. +#include "shared-module/cryptography/hazmat/primitives/asymmetric/ec/EllipticCurvePublicKey.h" + +// Type object used in Python. Shared between ports. +extern const mp_obj_type_t cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_type; diff --git a/shared-bindings/cryptography/hazmat/primitives/asymmetric/ec/__init__.c b/shared-bindings/cryptography/hazmat/primitives/asymmetric/ec/__init__.c new file mode 100644 index 00000000000..e7b2a2e7f75 --- /dev/null +++ b/shared-bindings/cryptography/hazmat/primitives/asymmetric/ec/__init__.c @@ -0,0 +1,131 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#include "py/obj.h" +#include "py/objproperty.h" +#include "py/runtime.h" + +#include "shared-bindings/cryptography/hazmat/primitives/asymmetric/ec/EllipticCurvePublicKey.h" +#include "shared-bindings/cryptography/hazmat/primitives/asymmetric/ec/__init__.h" + +//| """Elliptic-curve keys +//| +//| A subset of :py:mod:`cryptography.hazmat.primitives.asymmetric.ec`: +//| P-256 (secp256r1) signature *verification* only -- there is no private-key +//| type here, since verifying a signature against a known public key needs +//| no secret material and no hardware peripheral. +//| """ +//| + +//| class SECP256R1: +//| """The NIST P-256 (secp256r1) curve -- the only curve this module +//| supports. Mirrors the one PyCA curve class this module implements: +//| :py:class:`cryptography.hazmat.primitives.asymmetric.ec.SECP256R1`.""" +//| +//| def __init__(self) -> None: +//| ... +//| +static mp_obj_t cryptography_hazmat_primitives_asymmetric_ec_secp256r1_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + mp_arg_check_num(n_args, n_kw, 0, 0, false); + return MP_OBJ_FROM_PTR(&cryptography_hazmat_primitives_asymmetric_ec_secp256r1_obj); +} + +//| name: str +//| """``"secp256r1"``. Mirrors +//| :py:attr:`cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve.name`. +//| (read-only)""" +static mp_obj_t cryptography_hazmat_primitives_asymmetric_ec_secp256r1_get_name(mp_obj_t self_in) { + return MP_OBJ_NEW_QSTR(MP_QSTR_secp256r1); +} +MP_DEFINE_CONST_FUN_OBJ_1(cryptography_hazmat_primitives_asymmetric_ec_secp256r1_get_name_obj, cryptography_hazmat_primitives_asymmetric_ec_secp256r1_get_name); +MP_PROPERTY_GETTER(cryptography_hazmat_primitives_asymmetric_ec_secp256r1_name_obj, (mp_obj_t)&cryptography_hazmat_primitives_asymmetric_ec_secp256r1_get_name_obj); + +//| key_size: int +//| """``256``. Mirrors +//| :py:attr:`cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve.key_size`. +//| (read-only)""" +static mp_obj_t cryptography_hazmat_primitives_asymmetric_ec_secp256r1_get_key_size(mp_obj_t self_in) { + return MP_OBJ_NEW_SMALL_INT(256); +} +MP_DEFINE_CONST_FUN_OBJ_1(cryptography_hazmat_primitives_asymmetric_ec_secp256r1_get_key_size_obj, cryptography_hazmat_primitives_asymmetric_ec_secp256r1_get_key_size); +MP_PROPERTY_GETTER(cryptography_hazmat_primitives_asymmetric_ec_secp256r1_key_size_obj, (mp_obj_t)&cryptography_hazmat_primitives_asymmetric_ec_secp256r1_get_key_size_obj); + +static const mp_rom_map_elem_t cryptography_hazmat_primitives_asymmetric_ec_secp256r1_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_name), MP_ROM_PTR(&cryptography_hazmat_primitives_asymmetric_ec_secp256r1_name_obj) }, + { MP_ROM_QSTR(MP_QSTR_key_size), MP_ROM_PTR(&cryptography_hazmat_primitives_asymmetric_ec_secp256r1_key_size_obj) }, +}; +static MP_DEFINE_CONST_DICT(cryptography_hazmat_primitives_asymmetric_ec_secp256r1_locals_dict, cryptography_hazmat_primitives_asymmetric_ec_secp256r1_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + cryptography_hazmat_primitives_asymmetric_ec_secp256r1_type, + MP_QSTR_SECP256R1, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, cryptography_hazmat_primitives_asymmetric_ec_secp256r1_make_new, + locals_dict, &cryptography_hazmat_primitives_asymmetric_ec_secp256r1_locals_dict + ); +const mp_obj_base_t cryptography_hazmat_primitives_asymmetric_ec_secp256r1_obj = { &cryptography_hazmat_primitives_asymmetric_ec_secp256r1_type }; + +//| class ECDSA: +//| """Parameterizes `EllipticCurvePublicKey.verify` with the digest +//| algorithm a signature was computed over. Mirrors +//| :py:class:`cryptography.hazmat.primitives.asymmetric.ec.ECDSA`. +//| +//| Only ``algorithm=utils.Prehashed(hashes.SHA256)`` is supported -- +//| `verify` hashes nothing itself; the caller must already have a +//| SHA-256 digest in hand.""" +//| +//| def __init__(self, algorithm: object) -> None: +//| """ +//| :param object algorithm: must be `utils.Prehashed` wrapping +//| `hashes.SHA256` -- the only combination supported +//| """ +//| ... +static mp_obj_t cryptography_hazmat_primitives_asymmetric_ec_ecdsa_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + mp_arg_check_num(n_args, n_kw, 1, 1, false); + cryptography_hazmat_primitives_asymmetric_ec_ecdsa_obj_t *self = + mp_obj_malloc(cryptography_hazmat_primitives_asymmetric_ec_ecdsa_obj_t, type); + self->algorithm = all_args[0]; + return MP_OBJ_FROM_PTR(self); +} + +//| algorithm: object +//| """The algorithm passed to the constructor. Mirrors +//| :py:attr:`cryptography.hazmat.primitives.asymmetric.ec.ECDSA.algorithm`. +//| (read-only)""" +static mp_obj_t cryptography_hazmat_primitives_asymmetric_ec_ecdsa_get_algorithm(mp_obj_t self_in) { + cryptography_hazmat_primitives_asymmetric_ec_ecdsa_obj_t *self = MP_OBJ_TO_PTR(self_in); + return self->algorithm; +} +MP_DEFINE_CONST_FUN_OBJ_1(cryptography_hazmat_primitives_asymmetric_ec_ecdsa_get_algorithm_obj, cryptography_hazmat_primitives_asymmetric_ec_ecdsa_get_algorithm); +MP_PROPERTY_GETTER(cryptography_hazmat_primitives_asymmetric_ec_ecdsa_algorithm_obj, (mp_obj_t)&cryptography_hazmat_primitives_asymmetric_ec_ecdsa_get_algorithm_obj); + +static const mp_rom_map_elem_t cryptography_hazmat_primitives_asymmetric_ec_ecdsa_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_algorithm), MP_ROM_PTR(&cryptography_hazmat_primitives_asymmetric_ec_ecdsa_algorithm_obj) }, +}; +static MP_DEFINE_CONST_DICT(cryptography_hazmat_primitives_asymmetric_ec_ecdsa_locals_dict, cryptography_hazmat_primitives_asymmetric_ec_ecdsa_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + cryptography_hazmat_primitives_asymmetric_ec_ecdsa_type, + MP_QSTR_ECDSA, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, cryptography_hazmat_primitives_asymmetric_ec_ecdsa_make_new, + locals_dict, &cryptography_hazmat_primitives_asymmetric_ec_ecdsa_locals_dict + ); + +static mp_rom_map_elem_t cryptography_hazmat_primitives_asymmetric_ec_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR_cryptography_dot_hazmat_dot_primitives_dot_asymmetric_dot_ec) }, + { MP_ROM_QSTR(MP_QSTR_SECP256R1), MP_ROM_PTR(&cryptography_hazmat_primitives_asymmetric_ec_secp256r1_type) }, + { MP_ROM_QSTR(MP_QSTR_ECDSA), MP_ROM_PTR(&cryptography_hazmat_primitives_asymmetric_ec_ecdsa_type) }, + { MP_ROM_QSTR(MP_QSTR_EllipticCurvePublicKey), MP_ROM_PTR(&cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_type) }, +}; +static MP_DEFINE_CONST_DICT(cryptography_hazmat_primitives_asymmetric_ec_module_globals, cryptography_hazmat_primitives_asymmetric_ec_module_globals_table); + +const mp_obj_module_t cryptography_hazmat_primitives_asymmetric_ec_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&cryptography_hazmat_primitives_asymmetric_ec_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_cryptography_dot_hazmat_dot_primitives_dot_asymmetric_dot_ec, cryptography_hazmat_primitives_asymmetric_ec_module); diff --git a/shared-bindings/cryptography/hazmat/primitives/asymmetric/ec/__init__.h b/shared-bindings/cryptography/hazmat/primitives/asymmetric/ec/__init__.h new file mode 100644 index 00000000000..02537d47568 --- /dev/null +++ b/shared-bindings/cryptography/hazmat/primitives/asymmetric/ec/__init__.h @@ -0,0 +1,27 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +extern const mp_obj_module_t cryptography_hazmat_primitives_asymmetric_ec_module; + +// SECP256R1 is a plain constant, like padding.PKCS1v15 and hashes.SHA256: no +// real parameters, so make_new() just validates there are none and hands +// back the one singleton -- it still needs a make_new (unlike those two) +// because real PyCA code always calls `ec.SECP256R1()`. +extern const mp_obj_type_t cryptography_hazmat_primitives_asymmetric_ec_secp256r1_type; +extern const mp_obj_base_t cryptography_hazmat_primitives_asymmetric_ec_secp256r1_obj; + +// ECDSA takes a real parameter (the hash/Prehashed algorithm), so it's a +// constructible type, same shape as padding.OAEP. +extern const mp_obj_type_t cryptography_hazmat_primitives_asymmetric_ec_ecdsa_type; + +typedef struct { + mp_obj_base_t base; + mp_obj_t algorithm; +} cryptography_hazmat_primitives_asymmetric_ec_ecdsa_obj_t; diff --git a/shared-bindings/cryptography/hazmat/primitives/asymmetric/padding/__init__.c b/shared-bindings/cryptography/hazmat/primitives/asymmetric/padding/__init__.c new file mode 100644 index 00000000000..65f5abe45e4 --- /dev/null +++ b/shared-bindings/cryptography/hazmat/primitives/asymmetric/padding/__init__.c @@ -0,0 +1,100 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#include "py/obj.h" +#include "py/runtime.h" + +#include "shared-bindings/cryptography/hazmat/primitives/asymmetric/padding/__init__.h" +#include "shared-bindings/cryptography/hazmat/primitives/hashes/__init__.h" + +//| """Asymmetric padding +//| +//| A subset of :py:mod:`cryptography.hazmat.primitives.asymmetric.padding`: +//| the padding markers used to parameterize signing/decryption elsewhere, for +//| example +//| :py:meth:`cryptography.hazmat.primitives.asymmetric.rsa.DigitalSignatureKey.sign()` / +//| :py:meth:`cryptography.hazmat.primitives.asymmetric.rsa.DigitalSignatureKey.decrypt()`. +//| It does no cryptography itself and holds no key material; it exists only +//| so those operations can take explicit ``padding``/``algorithm`` arguments +//| instead of baking one fixed combination into a method name. +//| +//| `PKCS1v15` is a fixed, stateless constant (compare with ``is``; there is +//| nothing to configure, so there is nothing to construct). `OAEP` is a real +//| class since it actually takes a parameter. +//| """ +//| + +//| PKCS1v15: object +//| """PKCS#1 v1.5 padding, for either signing (RSASSA-PKCS1-v1_5) or +//| decryption (RSAES-PKCS1-v1_5, the older, legacy encryption padding; prefer +//| `OAEP` for new designs). Mirrors +//| :py:class:`cryptography.hazmat.primitives.asymmetric.padding.PKCS1v15`, which is +//| likewise used for both operations.""" +MP_DEFINE_CONST_OBJ_TYPE( + cryptography_hazmat_primitives_asymmetric_padding_pkcs1v15_type, + MP_QSTR_PKCS1v15, + MP_TYPE_FLAG_NONE + ); +const mp_obj_base_t cryptography_hazmat_primitives_asymmetric_padding_pkcs1v15_obj = { &cryptography_hazmat_primitives_asymmetric_padding_pkcs1v15_type }; + +//| class OAEP: +//| """RSAES-OAEP decryption padding. Only ``algorithm=hashes.SHA256`` and +//| ``label=None`` are supported today -- an actual driver may use the same hash +//| for both the OAEP digest and its MGF1 mask, and may not support a label. +//| Mirrors the one supported combination of +//| :py:class:`cryptography.hazmat.primitives.asymmetric.padding.OAEP`. +//| +//| Whether `OAEP` is actually usable depends on the operation it's passed to -- +//| see e.g. +//| :py:meth:`cryptography.hazmat.primitives.asymmetric.rsa.DigitalSignatureKey.decrypt()`.""" +//| +//| def __init__(self, algorithm: object, *, label: Optional[ReadableBuffer] = None) -> None: +//| """ +//| :param object algorithm: must be `hashes.SHA256` -- the only hash algorithm supported +//| :param Optional[~circuitpython_typing.ReadableBuffer] label: must be omitted or +//| ``None`` -- a label is not supported +//| """ +//| ... +static mp_obj_t cryptography_hazmat_primitives_asymmetric_padding_oaep_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_algorithm, ARG_label }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_algorithm, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_label, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, + }; + mp_arg_check_num(n_args, n_kw, 1, 1, true); + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + if (!mp_obj_is_type(args[ARG_algorithm].u_obj, &cryptography_hazmat_primitives_hashes_sha256_type)) { + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("Only %q supported"), MP_QSTR_SHA256); + } + if (args[ARG_label].u_obj != mp_const_none) { + mp_raise_NotImplementedError(MP_ERROR_TEXT("label is not supported")); + } + + return MP_OBJ_FROM_PTR(&cryptography_hazmat_primitives_asymmetric_padding_oaep_singleton); +} +MP_DEFINE_CONST_OBJ_TYPE( + cryptography_hazmat_primitives_asymmetric_padding_oaep_type, + MP_QSTR_OAEP, + MP_TYPE_FLAG_NONE, + make_new, cryptography_hazmat_primitives_asymmetric_padding_oaep_make_new + ); +const mp_obj_base_t cryptography_hazmat_primitives_asymmetric_padding_oaep_singleton = { &cryptography_hazmat_primitives_asymmetric_padding_oaep_type }; + +static mp_rom_map_elem_t cryptography_hazmat_primitives_asymmetric_padding_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR_cryptography_dot_hazmat_dot_primitives_dot_asymmetric_dot_padding) }, + { MP_ROM_QSTR(MP_QSTR_PKCS1v15), MP_ROM_PTR(&cryptography_hazmat_primitives_asymmetric_padding_pkcs1v15_obj) }, + { MP_ROM_QSTR(MP_QSTR_OAEP), MP_ROM_PTR(&cryptography_hazmat_primitives_asymmetric_padding_oaep_type) }, +}; +static MP_DEFINE_CONST_DICT(cryptography_hazmat_primitives_asymmetric_padding_module_globals, cryptography_hazmat_primitives_asymmetric_padding_module_globals_table); + +const mp_obj_module_t cryptography_hazmat_primitives_asymmetric_padding_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&cryptography_hazmat_primitives_asymmetric_padding_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_cryptography_dot_hazmat_dot_primitives_dot_asymmetric_dot_padding, cryptography_hazmat_primitives_asymmetric_padding_module); diff --git a/shared-bindings/cryptography/hazmat/primitives/asymmetric/padding/__init__.h b/shared-bindings/cryptography/hazmat/primitives/asymmetric/padding/__init__.h new file mode 100644 index 00000000000..58fb8f5453e --- /dev/null +++ b/shared-bindings/cryptography/hazmat/primitives/asymmetric/padding/__init__.h @@ -0,0 +1,21 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +extern const mp_obj_module_t cryptography_hazmat_primitives_asymmetric_padding_module; + +// PKCS1v15 is a plain constant: no parameters, nothing to construct, so +// *_obj is the only thing exposed under that name (the type itself isn't +// reachable, so it can't be called). OAEP takes a real parameter, so it +// stays a constructible type; *_singleton is what its make_new() returns +// after validating arguments. +extern const mp_obj_type_t cryptography_hazmat_primitives_asymmetric_padding_pkcs1v15_type; +extern const mp_obj_base_t cryptography_hazmat_primitives_asymmetric_padding_pkcs1v15_obj; +extern const mp_obj_type_t cryptography_hazmat_primitives_asymmetric_padding_oaep_type; +extern const mp_obj_base_t cryptography_hazmat_primitives_asymmetric_padding_oaep_singleton; diff --git a/shared-bindings/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c b/shared-bindings/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c new file mode 100644 index 00000000000..64ec34a13b7 --- /dev/null +++ b/shared-bindings/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c @@ -0,0 +1,183 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#include "py/objproperty.h" +#include "py/objstr.h" +#include "py/runtime.h" + +#include "shared-bindings/cryptography/hazmat/primitives/asymmetric/padding/__init__.h" +#include "shared-bindings/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.h" +#include "shared-bindings/cryptography/hazmat/primitives/hashes/__init__.h" +#include "shared-bindings/hardwarekey/HardwareKey.h" + +//| class DigitalSignatureKey: +//| """An RSA private key usable for signing and decryption, backed by a +//| Digital Signature hardware peripheral. The private key is never returned +//| or exposed; every operation runs entirely inside the peripheral. +//| +//| This class cannot be instantiated directly -- get one from +//| `load_digital_signature_key()`. +//| +//| `sign()` / `decrypt()` mirror the method shape of +//| :py:class:`cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey` +//| (``sign``, ``decrypt``, ``key_size``), but this is not a drop-in +//| implementation of that interface: there is intentionally no +//| ``public_key()``, ``private_numbers()``, or ``private_bytes()`` -- the key +//| material never leaves the Digital Signature peripheral, so there is no +//| honest way to implement key-material export. +//| +//| Reusing one RSA key under more than one algorithm is a real cryptographic +//| risk (arithmetic relations between operations under different algorithms +//| can be exploitable), not just an inconvenience -- so a `DigitalSignatureKey` +//| commits to whichever of `sign()` or `decrypt()` (and, for `decrypt()`, which +//| padding) it's first called with, for the rest of its lifetime. A later call +//| requesting a different algorithm raises `ValueError`; call +//| `load_digital_signature_key()` again for a fresh key committed to nothing yet. +//| """ +//| + +static void cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { + cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_obj_t *self = MP_OBJ_TO_PTR(self_in); + hardwarekey_hardwarekey_obj_t *source_key = MP_OBJ_TO_PTR(self->source_key); + if (source_key->name != MP_QSTRnull) { + mp_printf(print, "", source_key->name); + } else { + mp_printf(print, "", (int)source_key->key_slot); + } +} + +//| key_size: int +//| """The RSA modulus size in bits (e.g. 2048, 3072). Signatures are +//| ``key_size // 8`` bytes long. Mirrors +//| :py:attr:`cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey.key_size`. +//| (read-only)""" +static mp_obj_t cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_get_key_size(mp_obj_t self_in) { + cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_obj_t *self = MP_OBJ_TO_PTR(self_in); + return MP_OBJ_NEW_SMALL_INT(common_hal_cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_get_key_size(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_get_key_size_obj, cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_get_key_size); +MP_PROPERTY_GETTER(cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_key_size_obj, (mp_obj_t)&cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_get_key_size_obj); + +//| def sign( +//| self, +//| data: ReadableBuffer, +//| padding: object, +//| algorithm: object, +//| ) -> bytes: +//| """Sign ``data`` and return the signature (``key_size // 8`` bytes). +//| Mirrors +//| :py:meth:`cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey.sign`, +//| with the peripheral's one supported combination. +//| +//| :param ~circuitpython_typing.ReadableBuffer data: the message to sign +//| :param padding.PKCS1v15 padding: must be +//| `padding.PKCS1v15` -- the only padding the Digital +//| Signature peripheral supports +//| :param hashes.SHA256 algorithm: must be +//| `hashes.SHA256` -- the only hash algorithm the Digital +//| Signature peripheral supports +//| """ +//| ... +static mp_obj_t cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_sign(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_data, ARG_padding, ARG_algorithm }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_data, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_padding, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_algorithm, MP_ARG_REQUIRED | MP_ARG_OBJ }, + }; + cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]); + + 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); + + if (!mp_obj_is_type(args[ARG_padding].u_obj, &cryptography_hazmat_primitives_asymmetric_padding_pkcs1v15_type) || + !mp_obj_is_type(args[ARG_algorithm].u_obj, &cryptography_hazmat_primitives_hashes_sha256_type)) { + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("Only %q supported"), MP_QSTR_PKCS1v15_space_and_space_SHA256); + } + + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(args[ARG_data].u_obj, &bufinfo, MP_BUFFER_READ); + + size_t sig_len = common_hal_cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_get_key_size(self) / 8; + mp_obj_t result = mp_obj_new_bytes_of_zeros(sig_len); + mp_obj_str_t *result_bytes = MP_OBJ_TO_PTR(result); + + common_hal_cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_sign(self, bufinfo.buf, bufinfo.len, + (uint8_t *)result_bytes->data, sig_len); + return result; +} +static MP_DEFINE_CONST_FUN_OBJ_KW(cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_sign_obj, 1, cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_sign); + +//| def decrypt( +//| self, +//| ciphertext: ReadableBuffer, +//| padding: object, +//| ) -> bytes: +//| """Decrypt ``ciphertext`` (``key_size // 8`` bytes) and return the +//| recovered plaintext. Mirrors +//| :py:meth:`cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey.decrypt`. +//| +//| Subject to the same one-algorithm-per-lifetime rule as `sign()` -- +//| using `padding.PKCS1v15` here after using +//| `padding.OAEP` (or vice versa), or after calling `sign()`, +//| raises `ValueError`. +//| +//| :param ~circuitpython_typing.ReadableBuffer ciphertext: the ciphertext to decrypt +//| :param padding.PKCS1v15 padding: RSAES-PKCS1-v1_5 padding -- the +//| older, legacy scheme; prefer `padding.OAEP` for new designs +//| :param padding.OAEP padding: RSAES-OAEP padding. Only usable in a +//| build with TLS 1.3 support enabled -- raises `NotImplementedError` otherwise +//| """ +//| ... +static mp_obj_t cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_decrypt(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_ciphertext, ARG_padding }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_ciphertext, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_padding, MP_ARG_REQUIRED | MP_ARG_OBJ }, + }; + cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]); + + 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); + + psa_algorithm_t alg; + if (mp_obj_is_type(args[ARG_padding].u_obj, &cryptography_hazmat_primitives_asymmetric_padding_pkcs1v15_type)) { + alg = PSA_ALG_RSA_PKCS1V15_CRYPT; + } else if (mp_obj_is_type(args[ARG_padding].u_obj, &cryptography_hazmat_primitives_asymmetric_padding_oaep_type)) { + alg = PSA_ALG_RSA_OAEP(PSA_ALG_SHA_256); + } else { + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("Only %q supported"), MP_QSTR_PKCS1v15_space_or_space_OAEP); + } + + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(args[ARG_ciphertext].u_obj, &bufinfo, MP_BUFFER_READ); + + size_t max_len = common_hal_cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_get_key_size(self) / 8; + uint8_t *plaintext = m_new(uint8_t, max_len); + size_t output_len = 0; + common_hal_cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_decrypt(self, alg, bufinfo.buf, bufinfo.len, + plaintext, max_len, &output_len); + + mp_obj_t result = mp_obj_new_bytes(plaintext, output_len); + m_del(uint8_t, plaintext, max_len); + return result; +} +static MP_DEFINE_CONST_FUN_OBJ_KW(cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_decrypt_obj, 1, cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_decrypt); + +static const mp_rom_map_elem_t cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_key_size), MP_ROM_PTR(&cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_key_size_obj) }, + { MP_ROM_QSTR(MP_QSTR_sign), MP_ROM_PTR(&cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_sign_obj) }, + { MP_ROM_QSTR(MP_QSTR_decrypt), MP_ROM_PTR(&cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_decrypt_obj) }, +}; +static MP_DEFINE_CONST_DICT(cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_locals_dict, cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_type, + MP_QSTR_DigitalSignatureKey, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + print, cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_print, + locals_dict, &cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_locals_dict + ); diff --git a/shared-bindings/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.h b/shared-bindings/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.h new file mode 100644 index 00000000000..9f186f80008 --- /dev/null +++ b/shared-bindings/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.h @@ -0,0 +1,15 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +// Object struct and the common_hal_* accessors. +#include "shared-module/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.h" + +// Type object used in Python. Shared between ports. +extern const mp_obj_type_t cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_type; diff --git a/shared-bindings/cryptography/hazmat/primitives/asymmetric/rsa/__init__.c b/shared-bindings/cryptography/hazmat/primitives/asymmetric/rsa/__init__.c new file mode 100644 index 00000000000..3ffe7d7b14f --- /dev/null +++ b/shared-bindings/cryptography/hazmat/primitives/asymmetric/rsa/__init__.c @@ -0,0 +1,72 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#include "py/obj.h" +#include "py/runtime.h" + +#include "shared-bindings/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.h" +#include "shared-bindings/cryptography/hazmat/primitives/asymmetric/rsa/__init__.h" +#include "shared-bindings/hardwarekey/HardwareKey.h" + +//| """RSA keys +//| +//| A subset of :py:mod:`cryptography.hazmat.primitives.asymmetric.rsa`: a +//| hardware-backed private-key type for the Digital Signature peripheral. +//| """ +//| + +//| def load_digital_signature_key( +//| key: hardwarekey.HardwareKey, ds_params: ReadableBuffer +//| ) -> DigitalSignatureKey: +//| """Make a Digital Signature hardware key usable for signing and +//| decryption. Mirrors +//| :py:func:`cryptography.hazmat.primitives.serialization.load_pem_private_key`: +//| a blob of key material in, a ready-to-use private-key object out. +//| +//| :param hardwarekey.HardwareKey key: must have `hardwarekey.HardwareKey.purpose` == +//| `hardwarekey.Purpose.HMAC_DOWN_DIGITAL_SIGNATURE` +//| :param ~circuitpython_typing.ReadableBuffer ds_params: the encrypted Digital +//| Signature parameter block for this RSA key, produced at provisioning +//| time by vendor tooling (never by this module). On espressif this is the +//| raw ``esp_ds_data_t`` structure. Not secret -- it is only usable +//| together with this slot's eFuse key -- so it is fine to keep in a plain +//| file, e.g. on the ``CIRCUITPY`` filesystem. +//| :raises ValueError: if `key`'s purpose is wrong, or ``ds_params`` is malformed +//| """ +//| ... +static mp_obj_t cryptography_hazmat_primitives_asymmetric_rsa_load_digital_signature_key(mp_obj_t key_in, mp_obj_t ds_params_in) { + hardwarekey_hardwarekey_obj_t *key = + mp_arg_validate_type(key_in, &hardwarekey_hardwarekey_type, MP_QSTR_key); + if (common_hal_hardwarekey_hardwarekey_get_purpose(key) != HARDWAREKEY_PURPOSE_DS) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("key does not have the expected %q purpose"), + MP_QSTR_HMAC_DOWN_DIGITAL_SIGNATURE); + } + + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(ds_params_in, &bufinfo, MP_BUFFER_READ); + + cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_obj_t *self = + mp_obj_malloc(cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_obj_t, + &cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_type); + self->source_key = key_in; + common_hal_cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_construct(self, key, bufinfo.buf, bufinfo.len); + return MP_OBJ_FROM_PTR(self); +} +MP_DEFINE_CONST_FUN_OBJ_2(cryptography_hazmat_primitives_asymmetric_rsa_load_digital_signature_key_obj, cryptography_hazmat_primitives_asymmetric_rsa_load_digital_signature_key); + +static mp_rom_map_elem_t cryptography_hazmat_primitives_asymmetric_rsa_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR_cryptography_dot_hazmat_dot_primitives_dot_asymmetric_dot_rsa) }, + { MP_ROM_QSTR(MP_QSTR_DigitalSignatureKey), MP_ROM_PTR(&cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_type) }, + { MP_ROM_QSTR(MP_QSTR_load_digital_signature_key), MP_ROM_PTR(&cryptography_hazmat_primitives_asymmetric_rsa_load_digital_signature_key_obj) }, +}; +static MP_DEFINE_CONST_DICT(cryptography_hazmat_primitives_asymmetric_rsa_module_globals, cryptography_hazmat_primitives_asymmetric_rsa_module_globals_table); + +const mp_obj_module_t cryptography_hazmat_primitives_asymmetric_rsa_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&cryptography_hazmat_primitives_asymmetric_rsa_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_cryptography_dot_hazmat_dot_primitives_dot_asymmetric_dot_rsa, cryptography_hazmat_primitives_asymmetric_rsa_module); diff --git a/shared-bindings/cryptography/hazmat/primitives/asymmetric/rsa/__init__.h b/shared-bindings/cryptography/hazmat/primitives/asymmetric/rsa/__init__.h new file mode 100644 index 00000000000..2e471a4fc3f --- /dev/null +++ b/shared-bindings/cryptography/hazmat/primitives/asymmetric/rsa/__init__.h @@ -0,0 +1,16 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +#include "shared-bindings/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.h" + +extern const mp_obj_module_t cryptography_hazmat_primitives_asymmetric_rsa_module; + +// The module-level loader function (rsa.load_digital_signature_key()). +extern const mp_obj_fun_builtin_fixed_t cryptography_hazmat_primitives_asymmetric_rsa_load_digital_signature_key_obj; diff --git a/shared-bindings/cryptography/hazmat/primitives/asymmetric/utils/__init__.c b/shared-bindings/cryptography/hazmat/primitives/asymmetric/utils/__init__.c new file mode 100644 index 00000000000..e8b509e4678 --- /dev/null +++ b/shared-bindings/cryptography/hazmat/primitives/asymmetric/utils/__init__.c @@ -0,0 +1,154 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#include "py/objint.h" +#include "py/objproperty.h" +#include "py/runtime.h" + +#include "mbedtls/psa_util.h" + +#include "shared-bindings/cryptography/hazmat/primitives/asymmetric/utils/__init__.h" + +// P-256 only: each of r and s is 32 bytes, raw r||s is 64 bytes. +#define P256_KEY_BITS 256 +#define P256_COORD_LEN 32 +#define P256_RAW_SIG_LEN 64 + +//| """Signature/key encoding helpers +//| +//| A subset of :py:mod:`cryptography.hazmat.primitives.asymmetric.utils`: +//| `Prehashed`, plus the ECDSA DER<->(r, s) conversion functions, for +//| adapting hardware (e.g. ATECC608-family chips) that natively produces raw +//| ``r || s`` rather than the DER real PyCA's ECDSA uses. +//| """ +//| + +//| class Prehashed: +//| """Marks an algorithm as already applied -- `ec.EllipticCurvePublicKey.verify` +//| never hashes ``data`` itself when its ``signature_algorithm.algorithm`` +//| is one of these. Mirrors +//| :py:class:`cryptography.hazmat.primitives.asymmetric.utils.Prehashed`.""" +//| +//| def __init__(self, algorithm: object) -> None: +//| """ +//| :param object algorithm: must be `hashes.SHA256` -- the only hash +//| algorithm supported +//| """ +//| ... +static mp_obj_t cryptography_hazmat_primitives_asymmetric_utils_prehashed_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + mp_arg_check_num(n_args, n_kw, 1, 1, false); + cryptography_hazmat_primitives_asymmetric_utils_prehashed_obj_t *self = + mp_obj_malloc(cryptography_hazmat_primitives_asymmetric_utils_prehashed_obj_t, type); + self->algorithm = all_args[0]; + return MP_OBJ_FROM_PTR(self); +} + +//| algorithm: object +//| """The algorithm passed to the constructor. Mirrors +//| :py:attr:`cryptography.hazmat.primitives.asymmetric.utils.Prehashed._algorithm`. +//| (read-only)""" +static mp_obj_t cryptography_hazmat_primitives_asymmetric_utils_prehashed_get_algorithm(mp_obj_t self_in) { + cryptography_hazmat_primitives_asymmetric_utils_prehashed_obj_t *self = MP_OBJ_TO_PTR(self_in); + return self->algorithm; +} +MP_DEFINE_CONST_FUN_OBJ_1(cryptography_hazmat_primitives_asymmetric_utils_prehashed_get_algorithm_obj, cryptography_hazmat_primitives_asymmetric_utils_prehashed_get_algorithm); +MP_PROPERTY_GETTER(cryptography_hazmat_primitives_asymmetric_utils_prehashed_algorithm_obj, (mp_obj_t)&cryptography_hazmat_primitives_asymmetric_utils_prehashed_get_algorithm_obj); + +//| digest_size: int +//| """``32`` -- the digest size of `hashes.SHA256`, the only algorithm +//| supported. Mirrors +//| :py:attr:`cryptography.hazmat.primitives.asymmetric.utils.Prehashed.digest_size`. +//| (read-only)""" +static mp_obj_t cryptography_hazmat_primitives_asymmetric_utils_prehashed_get_digest_size(mp_obj_t self_in) { + return MP_OBJ_NEW_SMALL_INT(32); +} +MP_DEFINE_CONST_FUN_OBJ_1(cryptography_hazmat_primitives_asymmetric_utils_prehashed_get_digest_size_obj, cryptography_hazmat_primitives_asymmetric_utils_prehashed_get_digest_size); +MP_PROPERTY_GETTER(cryptography_hazmat_primitives_asymmetric_utils_prehashed_digest_size_obj, (mp_obj_t)&cryptography_hazmat_primitives_asymmetric_utils_prehashed_get_digest_size_obj); + +static const mp_rom_map_elem_t cryptography_hazmat_primitives_asymmetric_utils_prehashed_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_algorithm), MP_ROM_PTR(&cryptography_hazmat_primitives_asymmetric_utils_prehashed_algorithm_obj) }, + { MP_ROM_QSTR(MP_QSTR_digest_size), MP_ROM_PTR(&cryptography_hazmat_primitives_asymmetric_utils_prehashed_digest_size_obj) }, +}; +static MP_DEFINE_CONST_DICT(cryptography_hazmat_primitives_asymmetric_utils_prehashed_locals_dict, cryptography_hazmat_primitives_asymmetric_utils_prehashed_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + cryptography_hazmat_primitives_asymmetric_utils_prehashed_type, + MP_QSTR_Prehashed, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, cryptography_hazmat_primitives_asymmetric_utils_prehashed_make_new, + locals_dict, &cryptography_hazmat_primitives_asymmetric_utils_prehashed_locals_dict + ); + +//| def encode_dss_signature(r: int, s: int) -> bytes: +//| """DER-encode a raw ``(r, s)`` ECDSA signature pair -- the format +//| hardware (e.g. ATECC608-family chips) natively produces, and the +//| format `ec.EllipticCurvePublicKey.verify` does *not* accept directly. +//| Mirrors +//| :py:func:`cryptography.hazmat.primitives.asymmetric.utils.encode_dss_signature`, +//| restricted to P-256-sized ``r``/``s`` (each at most 32 bytes unsigned). +//| +//| :param int r: the signature's ``r`` value +//| :param int s: the signature's ``s`` value +//| """ +//| ... +static mp_obj_t cryptography_hazmat_primitives_asymmetric_utils_encode_dss_signature(mp_obj_t r_in, mp_obj_t s_in) { + uint8_t raw_sig[P256_RAW_SIG_LEN]; + mp_obj_int_to_bytes(r_in, P256_COORD_LEN, raw_sig, true, false, true); + mp_obj_int_to_bytes(s_in, P256_COORD_LEN, raw_sig + P256_COORD_LEN, true, false, true); + + uint8_t der_sig[MBEDTLS_ECDSA_MAX_LEN]; + size_t der_len = 0; + int ret = mbedtls_ecdsa_raw_to_der(P256_KEY_BITS, raw_sig, sizeof(raw_sig), der_sig, sizeof(der_sig), &der_len); + if (ret != 0) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("Invalid %q"), MP_QSTR_signature); + } + return mp_obj_new_bytes(der_sig, der_len); +} +MP_DEFINE_CONST_FUN_OBJ_2(cryptography_hazmat_primitives_asymmetric_utils_encode_dss_signature_obj, cryptography_hazmat_primitives_asymmetric_utils_encode_dss_signature); + +//| def decode_dss_signature(signature: ReadableBuffer) -> Tuple[int, int]: +//| """The inverse of `encode_dss_signature`: split a DER-encoded ECDSA +//| signature back into its raw ``(r, s)`` pair. Mirrors +//| :py:func:`cryptography.hazmat.primitives.asymmetric.utils.decode_dss_signature`, +//| restricted to P-256-sized signatures. +//| +//| :param ~circuitpython_typing.ReadableBuffer signature: a DER-encoded ECDSA signature +//| :raises ValueError: if ``signature`` is not a well-formed DER ECDSA signature +//| """ +//| ... +static mp_obj_t cryptography_hazmat_primitives_asymmetric_utils_decode_dss_signature(mp_obj_t signature_in) { + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(signature_in, &bufinfo, MP_BUFFER_READ); + + uint8_t raw_sig[P256_RAW_SIG_LEN]; + size_t raw_len = 0; + int ret = mbedtls_ecdsa_der_to_raw(P256_KEY_BITS, bufinfo.buf, bufinfo.len, raw_sig, sizeof(raw_sig), &raw_len); + if (ret != 0 || raw_len != P256_RAW_SIG_LEN) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("Invalid %q"), MP_QSTR_signature); + } + + mp_obj_t items[2] = { + mp_obj_int_from_bytes_impl(true, P256_COORD_LEN, raw_sig), + mp_obj_int_from_bytes_impl(true, P256_COORD_LEN, raw_sig + P256_COORD_LEN), + }; + return mp_obj_new_tuple(2, items); +} +MP_DEFINE_CONST_FUN_OBJ_1(cryptography_hazmat_primitives_asymmetric_utils_decode_dss_signature_obj, cryptography_hazmat_primitives_asymmetric_utils_decode_dss_signature); + +static mp_rom_map_elem_t cryptography_hazmat_primitives_asymmetric_utils_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR_cryptography_dot_hazmat_dot_primitives_dot_asymmetric_dot_utils) }, + { MP_ROM_QSTR(MP_QSTR_Prehashed), MP_ROM_PTR(&cryptography_hazmat_primitives_asymmetric_utils_prehashed_type) }, + { MP_ROM_QSTR(MP_QSTR_encode_dss_signature), MP_ROM_PTR(&cryptography_hazmat_primitives_asymmetric_utils_encode_dss_signature_obj) }, + { MP_ROM_QSTR(MP_QSTR_decode_dss_signature), MP_ROM_PTR(&cryptography_hazmat_primitives_asymmetric_utils_decode_dss_signature_obj) }, +}; +static MP_DEFINE_CONST_DICT(cryptography_hazmat_primitives_asymmetric_utils_module_globals, cryptography_hazmat_primitives_asymmetric_utils_module_globals_table); + +const mp_obj_module_t cryptography_hazmat_primitives_asymmetric_utils_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&cryptography_hazmat_primitives_asymmetric_utils_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_cryptography_dot_hazmat_dot_primitives_dot_asymmetric_dot_utils, cryptography_hazmat_primitives_asymmetric_utils_module); diff --git a/shared-bindings/cryptography/hazmat/primitives/asymmetric/utils/__init__.h b/shared-bindings/cryptography/hazmat/primitives/asymmetric/utils/__init__.h new file mode 100644 index 00000000000..2eb0a2bd4cb --- /dev/null +++ b/shared-bindings/cryptography/hazmat/primitives/asymmetric/utils/__init__.h @@ -0,0 +1,20 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +extern const mp_obj_module_t cryptography_hazmat_primitives_asymmetric_utils_module; + +// Prehashed takes a real parameter (the hash algorithm), same shape as +// padding.OAEP / ec.ECDSA. +extern const mp_obj_type_t cryptography_hazmat_primitives_asymmetric_utils_prehashed_type; + +typedef struct { + mp_obj_base_t base; + mp_obj_t algorithm; +} cryptography_hazmat_primitives_asymmetric_utils_prehashed_obj_t; diff --git a/shared-bindings/cryptography/hazmat/primitives/hashes/__init__.c b/shared-bindings/cryptography/hazmat/primitives/hashes/__init__.c new file mode 100644 index 00000000000..0e3524b1a76 --- /dev/null +++ b/shared-bindings/cryptography/hazmat/primitives/hashes/__init__.c @@ -0,0 +1,43 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#include "py/obj.h" +#include "py/runtime.h" + +#include "shared-bindings/cryptography/hazmat/primitives/hashes/__init__.h" + +//| """Hash algorithms +//| +//| A subset of :py:mod:`cryptography.hazmat.primitives.hashes`: the hash +//| algorithm markers used to parameterize signing/decryption elsewhere, for +//| example +//| :py:meth:`cryptography.hazmat.primitives.asymmetric.rsa.DigitalSignatureKey.sign()`. +//| It does no hashing itself. +//| """ +//| + +//| SHA256: object +//| """The SHA-256 hash algorithm. Mirrors +//| :py:class:`cryptography.hazmat.primitives.hashes.SHA256`.""" +MP_DEFINE_CONST_OBJ_TYPE( + cryptography_hazmat_primitives_hashes_sha256_type, + MP_QSTR_SHA256, + MP_TYPE_FLAG_NONE + ); +const mp_obj_base_t cryptography_hazmat_primitives_hashes_sha256_obj = { &cryptography_hazmat_primitives_hashes_sha256_type }; + +static mp_rom_map_elem_t cryptography_hazmat_primitives_hashes_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR_cryptography_dot_hazmat_dot_primitives_dot_hashes) }, + { MP_ROM_QSTR(MP_QSTR_SHA256), MP_ROM_PTR(&cryptography_hazmat_primitives_hashes_sha256_obj) }, +}; +static MP_DEFINE_CONST_DICT(cryptography_hazmat_primitives_hashes_module_globals, cryptography_hazmat_primitives_hashes_module_globals_table); + +const mp_obj_module_t cryptography_hazmat_primitives_hashes_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&cryptography_hazmat_primitives_hashes_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_cryptography_dot_hazmat_dot_primitives_dot_hashes, cryptography_hazmat_primitives_hashes_module); diff --git a/shared-bindings/cryptography/hazmat/primitives/hashes/__init__.h b/shared-bindings/cryptography/hazmat/primitives/hashes/__init__.h new file mode 100644 index 00000000000..fa3fbd36b77 --- /dev/null +++ b/shared-bindings/cryptography/hazmat/primitives/hashes/__init__.h @@ -0,0 +1,17 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +extern const mp_obj_module_t cryptography_hazmat_primitives_hashes_module; + +// SHA256 is a plain constant: no parameters, nothing to construct, so +// *_obj is the only thing exposed under that name (the type itself isn't +// reachable, so it can't be called). +extern const mp_obj_type_t cryptography_hazmat_primitives_hashes_sha256_type; +extern const mp_obj_base_t cryptography_hazmat_primitives_hashes_sha256_obj; diff --git a/shared-bindings/digitalio/DigitalInOut.c b/shared-bindings/digitalio/DigitalInOut.c index a29fdcc371c..0eb6f0d93ab 100644 --- a/shared-bindings/digitalio/DigitalInOut.c +++ b/shared-bindings/digitalio/DigitalInOut.c @@ -17,6 +17,7 @@ #include "shared-bindings/microcontroller/Pin.h" #include "shared-bindings/digitalio/DigitalInOut.h" +#include "shared-bindings/digitalio/DigitalInOutProtocol.h" #include "shared-bindings/digitalio/Direction.h" #include "shared-bindings/digitalio/DriveMode.h" #include "shared-bindings/digitalio/Pull.h" @@ -70,10 +71,10 @@ static mp_obj_t digitalio_digitalinout_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, 1, 1, false); - digitalio_digitalinout_obj_t *self = mp_obj_malloc(digitalio_digitalinout_obj_t, &digitalio_digitalinout_type); - const mcu_pin_obj_t *pin = common_hal_digitalio_validate_pin(args[0]); - common_hal_digitalio_digitalinout_construct(self, pin); + + digitalio_digitalinout_obj_t *self = mp_obj_malloc_with_finaliser(digitalio_digitalinout_obj_t, &digitalio_digitalinout_type); + check_result(common_hal_digitalio_digitalinout_construct(self, pin)); return MP_OBJ_FROM_PTR(self); } @@ -133,6 +134,8 @@ static mp_obj_t digitalio_digitalinout_switch_to_output(size_t n_args, const mp_ digitalio_drive_mode_t drive_mode = DRIVE_MODE_PUSH_PULL; if (args[ARG_drive_mode].u_rom_obj == MP_ROM_PTR(&digitalio_drive_mode_open_drain_obj)) { drive_mode = DRIVE_MODE_OPEN_DRAIN; + } else if (args[ARG_drive_mode].u_rom_obj != MP_ROM_PTR(&digitalio_drive_mode_push_pull_obj)) { + mp_arg_error_invalid(MP_QSTR_drive_mode); } // do the transfer check_result(common_hal_digitalio_digitalinout_switch_to_output(self, args[ARG_value].u_bool, drive_mode)); @@ -190,9 +193,9 @@ static mp_obj_t digitalio_digitalinout_obj_get_direction(mp_obj_t self_in) { check_for_deinit(self); digitalio_direction_t direction = common_hal_digitalio_digitalinout_get_direction(self); if (direction == DIRECTION_INPUT) { - return (mp_obj_t)&digitalio_direction_input_obj; + return MP_OBJ_FROM_PTR(&digitalio_direction_input_obj); } - return (mp_obj_t)&digitalio_direction_output_obj; + return MP_OBJ_FROM_PTR(&digitalio_direction_output_obj); } MP_DEFINE_CONST_FUN_OBJ_1(digitalio_digitalinout_get_direction_obj, digitalio_digitalinout_obj_get_direction); @@ -254,9 +257,9 @@ static mp_obj_t digitalio_digitalinout_obj_get_drive_mode(mp_obj_t self_in) { } digitalio_drive_mode_t drive_mode = common_hal_digitalio_digitalinout_get_drive_mode(self); if (drive_mode == DRIVE_MODE_PUSH_PULL) { - return (mp_obj_t)&digitalio_drive_mode_push_pull_obj; + return MP_OBJ_FROM_PTR(&digitalio_drive_mode_push_pull_obj); } - return (mp_obj_t)&digitalio_drive_mode_open_drain_obj; + return MP_OBJ_FROM_PTR(&digitalio_drive_mode_open_drain_obj); } MP_DEFINE_CONST_FUN_OBJ_1(digitalio_digitalinout_get_drive_mode_obj, digitalio_digitalinout_obj_get_drive_mode); @@ -270,6 +273,8 @@ static mp_obj_t digitalio_digitalinout_obj_set_drive_mode(mp_obj_t self_in, mp_o digitalio_drive_mode_t c_drive_mode = DRIVE_MODE_PUSH_PULL; if (drive_mode == MP_ROM_PTR(&digitalio_drive_mode_open_drain_obj)) { c_drive_mode = DRIVE_MODE_OPEN_DRAIN; + } else if (drive_mode != MP_ROM_PTR(&digitalio_drive_mode_push_pull_obj)) { + mp_arg_error_invalid(MP_QSTR_drive_mode); } check_result(common_hal_digitalio_digitalinout_set_drive_mode(self, c_drive_mode)); return mp_const_none; @@ -327,6 +332,7 @@ MP_PROPERTY_GETSET(digitalio_digitalio_pull_obj, static const mp_rom_map_elem_t digitalio_digitalinout_locals_dict_table[] = { // instance methods { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&digitalio_digitalinout_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&digitalio_digitalinout_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, { MP_ROM_QSTR(MP_QSTR_switch_to_output), MP_ROM_PTR(&digitalio_digitalinout_switch_to_output_obj) }, @@ -341,12 +347,91 @@ static const mp_rom_map_elem_t digitalio_digitalinout_locals_dict_table[] = { static MP_DEFINE_CONST_DICT(digitalio_digitalinout_locals_dict, digitalio_digitalinout_locals_dict_table); +// Protocol implementation - thin wrappers to match protocol signature +void digitalinout_deinit(mp_obj_t self_in) { + digitalio_digitalinout_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_digitalio_digitalinout_deinit(self); +} + +bool digitalinout_deinited(mp_obj_t self_in) { + digitalio_digitalinout_obj_t *self = MP_OBJ_TO_PTR(self_in); + return common_hal_digitalio_digitalinout_deinited(self); +} + +digitalinout_result_t digitalinout_switch_to_input(mp_obj_t self_in, digitalio_pull_t pull) { + digitalio_digitalinout_obj_t *self = MP_OBJ_TO_PTR(self_in); + return common_hal_digitalio_digitalinout_switch_to_input(self, pull); +} + +digitalinout_result_t digitalinout_switch_to_output(mp_obj_t self_in, bool value, digitalio_drive_mode_t drive_mode) { + digitalio_digitalinout_obj_t *self = MP_OBJ_TO_PTR(self_in); + return common_hal_digitalio_digitalinout_switch_to_output(self, value, drive_mode); +} + +digitalio_direction_t digitalinout_get_direction(mp_obj_t self_in) { + digitalio_digitalinout_obj_t *self = MP_OBJ_TO_PTR(self_in); + return common_hal_digitalio_digitalinout_get_direction(self); +} + +mp_negative_errno_t digitalinout_set_value(mp_obj_t self_in, bool value) { + digitalio_digitalinout_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_digitalio_digitalinout_set_value(self, value); + return 0; +} + +mp_negative_errno_t digitalinout_get_value(mp_obj_t self_in, bool *value) { + digitalio_digitalinout_obj_t *self = MP_OBJ_TO_PTR(self_in); + *value = common_hal_digitalio_digitalinout_get_value(self); + return 0; +} + +digitalinout_result_t digitalinout_set_drive_mode(mp_obj_t self_in, digitalio_drive_mode_t drive_mode) { + digitalio_digitalinout_obj_t *self = MP_OBJ_TO_PTR(self_in); + return common_hal_digitalio_digitalinout_set_drive_mode(self, drive_mode); +} + +digitalio_drive_mode_t digitalinout_get_drive_mode(mp_obj_t self_in) { + digitalio_digitalinout_obj_t *self = MP_OBJ_TO_PTR(self_in); + return common_hal_digitalio_digitalinout_get_drive_mode(self); +} + +digitalinout_result_t digitalinout_set_pull(mp_obj_t self_in, digitalio_pull_t pull) { + digitalio_digitalinout_obj_t *self = MP_OBJ_TO_PTR(self_in); + return common_hal_digitalio_digitalinout_set_pull(self, pull); +} + +digitalio_pull_t digitalinout_get_pull(mp_obj_t self_in) { + digitalio_digitalinout_obj_t *self = MP_OBJ_TO_PTR(self_in); + return common_hal_digitalio_digitalinout_get_pull(self); +} + +#if CIRCUITPY_DIGITALINOUT_PROTOCOL +static const digitalinout_p_t digitalinout_digitalinout_proto = { + MP_PROTO_IMPLEMENT(MP_QSTR_DigitalInOut) + .deinit = digitalinout_deinit, + .deinited = digitalinout_deinited, + .switch_to_input = digitalinout_switch_to_input, + .switch_to_output = digitalinout_switch_to_output, + .get_direction = digitalinout_get_direction, + .get_value = digitalinout_get_value, + .set_value = digitalinout_set_value, + .get_drive_mode = digitalinout_get_drive_mode, + .set_drive_mode = digitalinout_set_drive_mode, + .get_pull = digitalinout_get_pull, + .set_pull = digitalinout_set_pull, +}; +#endif + MP_DEFINE_CONST_OBJ_TYPE( digitalio_digitalinout_type, MP_QSTR_DigitalInOut, MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, make_new, digitalio_digitalinout_make_new, locals_dict, &digitalio_digitalinout_locals_dict + #if CIRCUITPY_DIGITALINOUT_PROTOCOL + , + protocol, &digitalinout_digitalinout_proto + #endif ); // Helper for validating digitalio.DigitalInOut arguments diff --git a/shared-bindings/digitalio/DigitalInOut.h b/shared-bindings/digitalio/DigitalInOut.h index f030e27a60b..7b7249efba4 100644 --- a/shared-bindings/digitalio/DigitalInOut.h +++ b/shared-bindings/digitalio/DigitalInOut.h @@ -28,6 +28,9 @@ typedef enum { #endif } digitalinout_result_t; +// Include protocol after types are defined +#include "shared-bindings/digitalio/DigitalInOutProtocol.h" + typedef enum { DIGITALINOUT_REG_READ, DIGITALINOUT_REG_WRITE, @@ -49,8 +52,20 @@ digitalinout_result_t common_hal_digitalio_digitalinout_set_drive_mode(digitalio digitalio_drive_mode_t common_hal_digitalio_digitalinout_get_drive_mode(digitalio_digitalinout_obj_t *self); digitalinout_result_t 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); volatile uint32_t *common_hal_digitalio_digitalinout_get_reg(digitalio_digitalinout_obj_t *self, digitalinout_reg_op_t op, uint32_t *mask); bool common_hal_digitalio_has_reg_op(digitalinout_reg_op_t op); + +// Protocol wrapper functions - always available for direct calls +void digitalinout_deinit(mp_obj_t self_in); +bool digitalinout_deinited(mp_obj_t self_in); +digitalinout_result_t digitalinout_switch_to_input(mp_obj_t self_in, digitalio_pull_t pull); +digitalinout_result_t digitalinout_switch_to_output(mp_obj_t self_in, bool value, digitalio_drive_mode_t drive_mode); +digitalio_direction_t digitalinout_get_direction(mp_obj_t self_in); +mp_negative_errno_t digitalinout_set_value(mp_obj_t self_in, bool value); +mp_negative_errno_t digitalinout_get_value(mp_obj_t self_in, bool *value); +digitalinout_result_t digitalinout_set_drive_mode(mp_obj_t self_in, digitalio_drive_mode_t drive_mode); +digitalio_drive_mode_t digitalinout_get_drive_mode(mp_obj_t self_in); +digitalinout_result_t digitalinout_set_pull(mp_obj_t self_in, digitalio_pull_t pull); +digitalio_pull_t digitalinout_get_pull(mp_obj_t self_in); diff --git a/shared-bindings/digitalio/DigitalInOutProtocol.c b/shared-bindings/digitalio/DigitalInOutProtocol.c new file mode 100644 index 00000000000..48b428ad463 --- /dev/null +++ b/shared-bindings/digitalio/DigitalInOutProtocol.c @@ -0,0 +1,397 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/digitalio/DigitalInOut.h" +#include "shared-bindings/digitalio/DigitalInOutProtocol.h" + +#include "py/obj.h" +#include "py/objtype.h" +#include "py/proto.h" +#include "py/runtime.h" +#include "py/nlr.h" +#include "py/gc.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/digitalio/Direction.h" +#include "shared-bindings/digitalio/DriveMode.h" +#include "shared-bindings/digitalio/Pull.h" +#include "shared-bindings/util.h" +#include "supervisor/port_heap.h" + +//| from typing import Protocol, Optional +//| +//| class DigitalInOutProtocol(Protocol): +//| """Protocol for digital input/output pin control. +//| +//| Any object that implements this protocol can be used as a digital pin, +//| providing compatibility with code expecting a `digitalio.DigitalInOut`. +//| """ +//| +//| def deinit(self) -> None: +//| """Deinitialize the pin and release hardware resources.""" +//| ... +//| +//| def deinited(self) -> bool: +//| """Check whether the pin has been deinitialized. +//| +//| :return: True if deinitialized, False otherwise +//| """ +//| ... +//| +//| def switch_to_input(self, pull: Optional[digitalio.Pull] = None) -> None: +//| """Configure the pin as a digital input. +//| +//| :param pull: Pull resistor configuration (UP, DOWN, or None) +//| """ +//| ... +//| +//| def switch_to_output( +//| self, +//| value: bool = False, +//| drive_mode: digitalio.DriveMode = digitalio.DriveMode.PUSH_PULL +//| ) -> None: +//| """Configure the pin as a digital output. +//| +//| :param value: Initial output value (default False) +//| :param drive_mode: Output drive mode (PUSH_PULL or OPEN_DRAIN) +//| """ +//| ... +//| +//| @property +//| def direction(self) -> digitalio.Direction: +//| """The pin direction (INPUT or OUTPUT).""" +//| ... +//| +//| @direction.setter +//| def direction(self, value: digitalio.Direction) -> None: +//| ... +//| +//| @property +//| def value(self) -> bool: +//| """The digital logic level of the pin.""" +//| ... +//| +//| @value.setter +//| def value(self, val: bool) -> None: +//| ... +//| +//| @property +//| def pull(self) -> Optional[digitalio.Pull]: +//| """The pull resistor configuration for inputs (UP, DOWN, or None).""" +//| ... +//| +//| @pull.setter +//| def pull(self, pul: Optional[digitalio.Pull]) -> None: +//| ... +//| +//| @property +//| def drive_mode(self) -> digitalio.DriveMode: +//| """The drive mode for outputs (PUSH_PULL or OPEN_DRAIN).""" +//| ... +//| +//| @drive_mode.setter +//| def drive_mode(self, mode: digitalio.DriveMode) -> None: +//| ... +//| +// C Implementation Notes: +// ----------------------- +// For C implementations, define a digitalinout_p_t protocol structure and assign it +// to your type's protocol field in MP_DEFINE_CONST_OBJ_TYPE. +// +// Example: +// static const digitalinout_p_t my_type_proto = { +// MP_PROTO_IMPLEMENT(MP_QSTR_DigitalInOut) +// .construct = my_construct_func, +// .deinit = my_deinit_func, +// .deinited = my_deinited_func, +// .switch_to_input = my_switch_to_input_func, +// .switch_to_output = my_switch_to_output_func, +// .get_direction = my_get_direction_func, +// .get_value = my_get_value_func, +// .set_value = my_set_value_func, +// .get_drive_mode = my_get_drive_mode_func, +// .set_drive_mode = my_set_drive_mode_func, +// .get_pull = my_get_pull_func, +// .set_pull = my_set_pull_func, +// }; +// +// MP_DEFINE_CONST_OBJ_TYPE( +// my_type, +// MP_QSTR_MyType, +// MP_TYPE_FLAG_NONE, +// make_new, my_make_new, +// protocol, &my_type_proto +// ); +// +// See shared-bindings/digitalio/DigitalInOut.c for a complete example. +// + +#if CIRCUITPY_DIGITALINOUT_PROTOCOL +static void check_object_has_method(mp_obj_t obj, qstr method_name) { + mp_obj_t dest[2]; + mp_load_method_protected(obj, method_name, dest, true); + if (dest[0] == MP_OBJ_NULL) { + mp_raise_TypeError_varg(MP_ERROR_TEXT("%q object missing '%q' method"), MP_OBJ_TO_PTR(obj), method_name); + } +} + +static void check_object_has_attr(mp_obj_t obj, qstr attr_name) { + mp_obj_t dest[2]; + mp_load_method_protected(obj, attr_name, dest, true); + if (dest[0] == MP_OBJ_NULL) { + mp_raise_TypeError_varg(MP_ERROR_TEXT("%q object missing '%q' attribute"), MP_OBJ_TO_PTR(obj), attr_name); + } +} +#endif + +mp_obj_t digitalinout_protocol_from_pin( + mp_obj_t pin_or_dio, + qstr arg_name, + bool allow_none, + bool use_port_allocation, + bool *out_owns_pin) { + + *out_owns_pin = false; + + // Handle None case + if (allow_none && pin_or_dio == mp_const_none) { + return mp_const_none; + } + + // Check if it's a Pin + if (mp_obj_is_type(pin_or_dio, &mcu_pin_type)) { + // Validate the pin is free + const mcu_pin_obj_t *pin; + if (allow_none) { + pin = validate_obj_is_free_pin_or_none(pin_or_dio, arg_name); + if (pin == NULL) { + return mp_const_none; + } + } else { + pin = validate_obj_is_free_pin(pin_or_dio, arg_name); + } + + // Allocate and construct a DigitalInOut object + // Use port_malloc if GC is not available or if forced + digitalio_digitalinout_obj_t *dio; + if (use_port_allocation) { + dio = port_malloc(sizeof(digitalio_digitalinout_obj_t), false); + } else { + dio = m_malloc(sizeof(digitalio_digitalinout_obj_t)); + } + dio->base.type = &digitalio_digitalinout_type; + mp_obj_t dio_obj = MP_OBJ_FROM_PTR(dio); + *out_owns_pin = true; + + digitalinout_result_t result = common_hal_digitalio_digitalinout_construct(dio_obj, pin); + if (result != DIGITALINOUT_OK) { + // Free the allocation on error + if (use_port_allocation) { + port_free(dio); + } + mp_raise_ValueError_varg(MP_ERROR_TEXT("%q init failed"), arg_name); + } + return dio_obj; + } + + #if CIRCUITPY_DIGITALINOUT_PROTOCOL + // Check if it natively implements the DigitalInOutProtocol + const digitalinout_p_t *proto = mp_proto_get(MP_QSTR_DigitalInOut, pin_or_dio); + if (proto != NULL) { + // Native protocol support - use it directly + return pin_or_dio; + } + + // Verify the object has the required methods/attributes + check_object_has_method(pin_or_dio, MP_QSTR_deinit); + check_object_has_method(pin_or_dio, MP_QSTR_switch_to_input); + check_object_has_method(pin_or_dio, MP_QSTR_switch_to_output); + check_object_has_attr(pin_or_dio, MP_QSTR_deinited); + check_object_has_attr(pin_or_dio, MP_QSTR_direction); + check_object_has_attr(pin_or_dio, MP_QSTR_value); + check_object_has_attr(pin_or_dio, MP_QSTR_drive_mode); + check_object_has_attr(pin_or_dio, MP_QSTR_pull); + + // Object has all required attributes - use it as DigitalInOutProtocol + return pin_or_dio; + #else + mp_raise_TypeError_varg(MP_ERROR_TEXT("'%q' object does not support '%q'"), + mp_obj_get_type_qstr(pin_or_dio), MP_QSTR_DigitalInOut); + #endif +} + +// These functions are only used when CIRCUITPY_DIGITALINOUT_PROTOCOL is enabled. +// Otherwise, the digitalinout_* functions are called directly. +#if CIRCUITPY_DIGITALINOUT_PROTOCOL +void digitalinout_protocol_deinit(mp_obj_t self) { + const digitalinout_p_t *proto = mp_proto_get(MP_QSTR_protocol_digitalinout, self); + if (proto && proto->deinit) { + proto->deinit(self); + return; + } + + // Fallback to Python method call + mp_obj_t dest[2]; + mp_load_method_maybe(self, MP_QSTR_deinit, dest); + if (dest[0] != MP_OBJ_NULL) { + mp_call_method_n_kw(0, 0, dest); + return; + } +} + +bool digitalinout_protocol_deinited(mp_obj_t self) { + const digitalinout_p_t *proto = mp_proto_get(MP_QSTR_DigitalInOut, self); + if (proto && proto->deinited) { + return proto->deinited(self); + } + + // Try as attribute + mp_obj_t attr = mp_load_attr(self, MP_QSTR_deinited); + return mp_obj_is_true(attr); +} + +digitalinout_result_t digitalinout_protocol_switch_to_input(mp_obj_t self, digitalio_pull_t pull) { + const digitalinout_p_t *proto = mp_proto_get(MP_QSTR_DigitalInOut, self); + if (proto && proto->switch_to_input) { + return proto->switch_to_input(self, pull); + } + + // Fallback to Python method call + mp_obj_t dest[3]; + mp_load_method_maybe(self, MP_QSTR_switch_to_input, dest); + if (dest[0] != MP_OBJ_NULL) { + mp_obj_t pull_obj = mp_const_none; + if (pull == PULL_UP) { + pull_obj = MP_OBJ_FROM_PTR(&digitalio_pull_up_obj); + } else if (pull == PULL_DOWN) { + pull_obj = MP_OBJ_FROM_PTR(&digitalio_pull_down_obj); + } + dest[2] = pull_obj; + mp_call_method_n_kw(1, 0, dest); + return DIGITALINOUT_OK; + } + + return DIGITALINOUT_PIN_BUSY; +} + +digitalinout_result_t digitalinout_protocol_switch_to_output(mp_obj_t self, bool value, digitalio_drive_mode_t drive_mode) { + const digitalinout_p_t *proto = mp_proto_get(MP_QSTR_DigitalInOut, self); + if (proto && proto->switch_to_output) { + return proto->switch_to_output(self, value, drive_mode); + } + + // Fallback to Python method call + mp_obj_t dest[4]; + mp_load_method_maybe(self, MP_QSTR_switch_to_output, dest); + if (dest[0] != MP_OBJ_NULL) { + dest[2] = mp_obj_new_bool(value); + dest[3] = (drive_mode == DRIVE_MODE_PUSH_PULL) ? + MP_OBJ_FROM_PTR(&digitalio_drive_mode_push_pull_obj) : + MP_OBJ_FROM_PTR(&digitalio_drive_mode_open_drain_obj); + mp_call_method_n_kw(2, 0, dest); + return DIGITALINOUT_OK; + } + + mp_raise_TypeError(MP_ERROR_TEXT("object does not support DigitalInOut protocol")); +} + +digitalio_direction_t digitalinout_protocol_get_direction(mp_obj_t self) { + const digitalinout_p_t *proto = mp_proto_get(MP_QSTR_DigitalInOut, self); + if (proto && proto->get_direction) { + return proto->get_direction(self); + } + + // Fallback to Python attribute access + mp_obj_t direction = mp_load_attr(self, MP_QSTR_direction); + if (direction == MP_ROM_PTR(&digitalio_direction_input_obj)) { + return DIRECTION_INPUT; + } + return DIRECTION_OUTPUT; +} + +mp_negative_errno_t digitalinout_protocol_set_value(mp_obj_t self, bool value) { + const digitalinout_p_t *proto = mp_proto_get(MP_QSTR_DigitalInOut, self); + if (proto && proto->set_value) { + return proto->set_value(self, value); + } + + // Fallback to Python attribute assignment + mp_store_attr(self, MP_QSTR_value, mp_obj_new_bool(value)); + return 0; +} + +mp_negative_errno_t digitalinout_protocol_get_value(mp_obj_t self, bool *value) { + const digitalinout_p_t *proto = mp_proto_get(MP_QSTR_DigitalInOut, self); + if (proto && proto->get_value) { + return proto->get_value(self, value); + } + + // Fallback to Python attribute access + *value = mp_obj_is_true(mp_load_attr(self, MP_QSTR_value)); + return 0; +} + +digitalinout_result_t digitalinout_protocol_set_drive_mode(mp_obj_t self, digitalio_drive_mode_t drive_mode) { + const digitalinout_p_t *proto = mp_proto_get(MP_QSTR_DigitalInOut, self); + if (proto && proto->set_drive_mode) { + return proto->set_drive_mode(self, drive_mode); + } + + // Fallback to Python attribute assignment + mp_obj_t drive_mode_obj = (drive_mode == DRIVE_MODE_PUSH_PULL) ? + MP_OBJ_FROM_PTR(&digitalio_drive_mode_push_pull_obj) : + MP_OBJ_FROM_PTR(&digitalio_drive_mode_open_drain_obj); + mp_store_attr(self, MP_QSTR_drive_mode, drive_mode_obj); + return DIGITALINOUT_OK; +} + +digitalio_drive_mode_t digitalinout_protocol_get_drive_mode(mp_obj_t self) { + const digitalinout_p_t *proto = mp_proto_get(MP_QSTR_DigitalInOut, self); + if (proto && proto->get_drive_mode) { + return proto->get_drive_mode(self); + } + + // Fallback to Python attribute access + mp_obj_t drive_mode = mp_load_attr(self, MP_QSTR_drive_mode); + if (drive_mode == MP_ROM_PTR(&digitalio_drive_mode_open_drain_obj)) { + return DRIVE_MODE_OPEN_DRAIN; + } + return DRIVE_MODE_PUSH_PULL; +} + +digitalinout_result_t digitalinout_protocol_set_pull(mp_obj_t self, digitalio_pull_t pull) { + const digitalinout_p_t *proto = mp_proto_get(MP_QSTR_DigitalInOut, self); + if (proto && proto->set_pull) { + return proto->set_pull(self, pull); + } + + // Fallback to Python attribute assignment + mp_obj_t pull_obj = mp_const_none; + if (pull == PULL_UP) { + pull_obj = MP_OBJ_FROM_PTR(&digitalio_pull_up_obj); + } else if (pull == PULL_DOWN) { + pull_obj = MP_OBJ_FROM_PTR(&digitalio_pull_down_obj); + } + mp_store_attr(self, MP_QSTR_pull, pull_obj); + return DIGITALINOUT_OK; +} + +digitalio_pull_t digitalinout_protocol_get_pull(mp_obj_t self) { + const digitalinout_p_t *proto = mp_proto_get(MP_QSTR_DigitalInOut, self); + if (proto && proto->get_pull) { + return proto->get_pull(self); + } + + // Fallback to Python attribute access + mp_obj_t pull = mp_load_attr(self, MP_QSTR_pull); + if (pull == MP_OBJ_FROM_PTR(&digitalio_pull_up_obj)) { + return PULL_UP; + } else if (pull == MP_OBJ_FROM_PTR(&digitalio_pull_down_obj)) { + return PULL_DOWN; + } + return PULL_NONE; +} + +#endif // CIRCUITPY_DIGITALINOUT_PROTOCOL diff --git a/shared-bindings/digitalio/DigitalInOutProtocol.h b/shared-bindings/digitalio/DigitalInOutProtocol.h new file mode 100644 index 00000000000..6cb92a3735f --- /dev/null +++ b/shared-bindings/digitalio/DigitalInOutProtocol.h @@ -0,0 +1,83 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include + +#include "py/obj.h" +#include "py/proto.h" +#include "py/mperrno.h" +#include "shared-bindings/digitalio/Direction.h" +#include "shared-bindings/digitalio/DriveMode.h" +#include "shared-bindings/digitalio/Pull.h" + +// Protocol structure for DigitalInOut implementations +// Note: mcu_pin_obj_t and digitalinout_result_t are defined by files that include this header +typedef struct _digitalinout_p_t { + MP_PROTOCOL_HEAD // MP_QSTR_DigitalInOut + void (*deinit)(mp_obj_t self); + bool (*deinited)(mp_obj_t self); + digitalinout_result_t (*switch_to_input)(mp_obj_t self, digitalio_pull_t pull); + digitalinout_result_t (*switch_to_output)(mp_obj_t self, bool value, digitalio_drive_mode_t drive_mode); + digitalio_direction_t (*get_direction)(mp_obj_t self); + mp_negative_errno_t (*set_value)(mp_obj_t self, bool value); // Return 0 if ok + mp_negative_errno_t (*get_value)(mp_obj_t self, bool *value); // Return 0 if ok + digitalinout_result_t (*set_drive_mode)(mp_obj_t self, digitalio_drive_mode_t drive_mode); + digitalio_drive_mode_t (*get_drive_mode)(mp_obj_t self); + digitalinout_result_t (*set_pull)(mp_obj_t self, digitalio_pull_t pull); + digitalio_pull_t (*get_pull)(mp_obj_t self); +} digitalinout_p_t; + +// Protocol helper functions +// These functions work with any object that implements the DigitalInOut protocol, +// either through native C protocol or Python attributes/methods. + +// Converts a Pin or DigitalInOutProtocol to a DigitalInOutProtocol object. +// If pin_or_dio is a Pin, allocates and initializes a DigitalInOut object. +// If pin_or_dio is already a DigitalInOutProtocol, returns it directly. +// If allow_none is true and pin_or_dio is None, returns None. +// If force_port_allocation is true, uses port_malloc instead of GC allocation. +// Sets *out_owns_pin to true if a new DigitalInOut was allocated (caller must deinit and free). +// Returns the DigitalInOutProtocol object to use. +// Raises an exception on error. +// Note: To free allocated objects, deinit first, then use gc_ptr_on_heap() to determine +// if port_free() should be called (if not on heap) or let GC handle it (if on heap). +mp_obj_t digitalinout_protocol_from_pin( + mp_obj_t pin_or_dio, + qstr arg_name, + bool allow_none, + bool force_port_allocation, + bool *out_owns_pin); + +#if CIRCUITPY_DIGITALINOUT_PROTOCOL +// Protocol helper functions that do protocol lookup or Python fallback +void digitalinout_protocol_deinit(mp_obj_t self); +bool digitalinout_protocol_deinited(mp_obj_t self); +digitalinout_result_t digitalinout_protocol_switch_to_input(mp_obj_t self, digitalio_pull_t pull); +digitalinout_result_t digitalinout_protocol_switch_to_output(mp_obj_t self, bool value, digitalio_drive_mode_t drive_mode); +digitalio_direction_t digitalinout_protocol_get_direction(mp_obj_t self); +mp_negative_errno_t digitalinout_protocol_set_value(mp_obj_t self, bool value); +mp_negative_errno_t digitalinout_protocol_get_value(mp_obj_t self, bool *value); +digitalinout_result_t digitalinout_protocol_set_drive_mode(mp_obj_t self, digitalio_drive_mode_t drive_mode); +digitalio_drive_mode_t digitalinout_protocol_get_drive_mode(mp_obj_t self); +digitalinout_result_t digitalinout_protocol_set_pull(mp_obj_t self, digitalio_pull_t pull); +digitalio_pull_t digitalinout_protocol_get_pull(mp_obj_t self); +#else +// When protocol is disabled, map directly to native DigitalInOut functions +#define digitalinout_protocol_deinit digitalinout_deinit +#define digitalinout_protocol_deinited digitalinout_deinited +#define digitalinout_protocol_switch_to_input digitalinout_switch_to_input +#define digitalinout_protocol_switch_to_output digitalinout_switch_to_output +#define digitalinout_protocol_get_direction digitalinout_get_direction +#define digitalinout_protocol_set_value digitalinout_set_value +#define digitalinout_protocol_get_value digitalinout_get_value +#define digitalinout_protocol_set_drive_mode digitalinout_set_drive_mode +#define digitalinout_protocol_get_drive_mode digitalinout_get_drive_mode +#define digitalinout_protocol_set_pull digitalinout_set_pull +#define digitalinout_protocol_get_pull digitalinout_get_pull +#endif diff --git a/shared-bindings/displayio/Bitmap.c b/shared-bindings/displayio/Bitmap.c index e543687901a..90f05106821 100644 --- a/shared-bindings/displayio/Bitmap.c +++ b/shared-bindings/displayio/Bitmap.c @@ -37,7 +37,10 @@ //| //| :param int width: The number of values wide //| :param int height: The number of values high -//| :param int value_count: The number of possible pixel values.""" +//| :param int value_count: The minimum number of pixel values to store, from 1 to 65536. Storage is +//| rounded up to 1, 2, 4, 8 or 16 bits per value, so any value that fits in ``bits_per_value`` can be +//| stored, even one that is ``value_count`` or higher. When a `displayio.Palette` is the pixel shader, +//| a pixel past the end of the palette is transparent.""" //| ... //| static mp_obj_t displayio_bitmap_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { @@ -55,7 +58,7 @@ static mp_obj_t displayio_bitmap_make_new(const mp_obj_type_t *type, size_t n_ar } } - displayio_bitmap_t *self = mp_obj_malloc(displayio_bitmap_t, &displayio_bitmap_type); + displayio_bitmap_t *self = mp_obj_malloc_with_finaliser(displayio_bitmap_t, &displayio_bitmap_type); common_hal_displayio_bitmap_construct(self, width, height, bits); return MP_OBJ_FROM_PTR(self); @@ -232,14 +235,11 @@ static mp_obj_t displayio_bitmap_obj_dirty(size_t n_args, const mp_obj_t *pos_ar 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); + displayio_bitmap_set_dirty(self, + args[ARG_x1].u_int, + args[ARG_y1].u_int, + args[ARG_x2].u_int == -1 ? self->width : args[ARG_x2].u_int, + args[ARG_y2].u_int == -1 ? self->height : args[ARG_y2].u_int); return mp_const_none; } @@ -264,6 +264,7 @@ static const mp_rom_map_elem_t displayio_bitmap_locals_dict_table[] = { { 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) }, { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&displayio_bitmap_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&displayio_bitmap_deinit_obj) }, }; static MP_DEFINE_CONST_DICT(displayio_bitmap_locals_dict, displayio_bitmap_locals_dict_table); diff --git a/shared-bindings/displayio/ColorConverter.c b/shared-bindings/displayio/ColorConverter.c index e2721cfdef2..bfd037016d4 100644 --- a/shared-bindings/displayio/ColorConverter.c +++ b/shared-bindings/displayio/ColorConverter.c @@ -39,7 +39,6 @@ static mp_obj_t displayio_colorconverter_make_new(const mp_obj_type_t *type, siz mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); displayio_colorconverter_t *self = mp_obj_malloc(displayio_colorconverter_t, &displayio_colorconverter_type); - 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, MP_QSTR_input_colorspace)); return MP_OBJ_FROM_PTR(self); diff --git a/shared-bindings/displayio/Colorspace.c b/shared-bindings/displayio/Colorspace.c index f6592024fa3..77ad6d18098 100644 --- a/shared-bindings/displayio/Colorspace.c +++ b/shared-bindings/displayio/Colorspace.c @@ -20,6 +20,7 @@ MAKE_ENUM_VALUE(displayio_colorspace_type, displayio_colorspace, BGR565_SWAPPED, MAKE_ENUM_VALUE(displayio_colorspace_type, displayio_colorspace, BGR555, DISPLAYIO_COLORSPACE_BGR555); MAKE_ENUM_VALUE(displayio_colorspace_type, displayio_colorspace, BGR555_SWAPPED, DISPLAYIO_COLORSPACE_BGR555_SWAPPED); MAKE_ENUM_VALUE(displayio_colorspace_type, displayio_colorspace, L8, DISPLAYIO_COLORSPACE_L8); +MAKE_ENUM_VALUE(displayio_colorspace_type, displayio_colorspace, L1, DISPLAYIO_COLORSPACE_L1); //| class Colorspace: //| """The colorspace for a `ColorConverter` to operate in""" @@ -39,6 +40,10 @@ MAKE_ENUM_VALUE(displayio_colorspace_type, displayio_colorspace, L8, DISPLAYIO_C //| 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""" //| +//| L1: Colorspace +//| """The 1-bit black and white colorspace. 8 pixels are packed into each byte, with the leftmost pixel in +//| the top bit. 1 is white and 0 is black.""" +//| //| MAKE_ENUM_MAP(displayio_colorspace) { MAKE_ENUM_MAP_ENTRY(displayio_colorspace, RGB888), @@ -51,6 +56,7 @@ MAKE_ENUM_MAP(displayio_colorspace) { MAKE_ENUM_MAP_ENTRY(displayio_colorspace, BGR555), MAKE_ENUM_MAP_ENTRY(displayio_colorspace, BGR555_SWAPPED), MAKE_ENUM_MAP_ENTRY(displayio_colorspace, L8), + MAKE_ENUM_MAP_ENTRY(displayio_colorspace, L1), }; static MP_DEFINE_CONST_DICT(displayio_colorspace_locals_dict, displayio_colorspace_locals_table); diff --git a/shared-bindings/displayio/Group.c b/shared-bindings/displayio/Group.c index e5f5f039789..a78b61f4ff4 100644 --- a/shared-bindings/displayio/Group.c +++ b/shared-bindings/displayio/Group.c @@ -17,11 +17,12 @@ //| class Group: //| """Manage a group of sprites and groups and how they are inter-related.""" //| -//| def __init__(self, *, scale: int = 1, x: int = 0, y: int = 0) -> None: +//| def __init__(self, *, scale: int | float = 1, x: int = 0, y: int = 0) -> None: //| """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. +//| leads to a layer's pixel being 2x2 pixels when in the group. The LVGL compositor also +//| supports fractional scales. //| -//| :param int scale: Scale of layer pixels in one dimension. +//| :param int | float 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.""" //| ... @@ -29,14 +30,14 @@ static mp_obj_t displayio_group_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { enum { ARG_scale, ARG_x, ARG_y }; static const mp_arg_t allowed_args[] = { - { MP_QSTR_scale, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 1} }, + { MP_QSTR_scale, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_rom_obj = MP_ROM_INT(1)} }, { MP_QSTR_x, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0} }, { MP_QSTR_y, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0} }, }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); - mp_int_t scale = mp_arg_validate_int_range(args[ARG_scale].u_int, 1, 32767, MP_QSTR_scale); + mp_obj_t scale = args[ARG_scale].u_obj; displayio_group_t *self = mp_obj_malloc(displayio_group_t, &displayio_group_type); common_hal_displayio_group_construct(self, scale, args[ARG_x].u_int, args[ARG_y].u_int); @@ -75,21 +76,21 @@ MP_PROPERTY_GETSET(displayio_group_hidden_obj, (mp_obj_t)&displayio_group_get_hidden_obj, (mp_obj_t)&displayio_group_set_hidden_obj); -//| scale: int +//| scale: int | float //| """Scales each pixel within the Group in both directions. For example, when scale=2 each pixel -//| will be represented by 2x2 pixels.""" +//| will be represented by 2x2 pixels. The LVGL compositor also supports fractional scales. +//| Different hardware can accelerate different fractional scales. It will pick the closest scale +//| that doesn't go over the given scale. Reading this property returns the requested scale.""" static mp_obj_t displayio_group_obj_get_scale(mp_obj_t self_in) { displayio_group_t *self = native_group(self_in); - return MP_OBJ_NEW_SMALL_INT(common_hal_displayio_group_get_scale(self)); + return common_hal_displayio_group_get_scale(self); } MP_DEFINE_CONST_FUN_OBJ_1(displayio_group_get_scale_obj, displayio_group_obj_get_scale); static mp_obj_t displayio_group_obj_set_scale(mp_obj_t self_in, mp_obj_t scale_obj) { displayio_group_t *self = native_group(self_in); - mp_int_t scale = mp_arg_validate_int_min(mp_obj_get_int(scale_obj), 1, MP_QSTR_scale); - - common_hal_displayio_group_set_scale(self, scale); + common_hal_displayio_group_set_scale(self, scale_obj); return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_2(displayio_group_set_scale_obj, displayio_group_obj_set_scale); @@ -317,12 +318,14 @@ static mp_obj_t group_subscr(mp_obj_t self_in, mp_obj_t index_obj, mp_obj_t valu //| 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); + mp_obj_t *args = m_malloc_items(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, args, kw_args); + mp_obj_t res = mp_obj_list_sort(n_args, args, kw_args); + m_del(mp_obj_t, args, n_args); + return res; } MP_DEFINE_CONST_FUN_OBJ_KW(displayio_group_sort_obj, 1, displayio_group_obj_sort); @@ -348,5 +351,6 @@ MP_DEFINE_CONST_OBJ_TYPE( locals_dict, &displayio_group_locals_dict, subscr, group_subscr, unary_op, group_unary_op, - iter, mp_obj_generic_subscript_getiter + iter, mp_obj_generic_subscript_getiter, + protocol, DISPLAYIO_GROUP_LVGL_PROTOCOL ); diff --git a/shared-bindings/displayio/Group.h b/shared-bindings/displayio/Group.h index 2eb25215961..0cae6b4e789 100644 --- a/shared-bindings/displayio/Group.h +++ b/shared-bindings/displayio/Group.h @@ -12,9 +12,10 @@ extern const mp_obj_type_t displayio_group_type; displayio_group_t *native_group(mp_obj_t group_obj); -void common_hal_displayio_group_construct(displayio_group_t *self, uint32_t scale, mp_int_t x, mp_int_t y); -uint32_t common_hal_displayio_group_get_scale(displayio_group_t *self); -void common_hal_displayio_group_set_scale(displayio_group_t *self, uint32_t scale); +// scale may be an int or float, depending on the implementation. +void common_hal_displayio_group_construct(displayio_group_t *self, mp_obj_t scale, mp_int_t x, mp_int_t y); +mp_obj_t common_hal_displayio_group_get_scale(displayio_group_t *self); +void common_hal_displayio_group_set_scale(displayio_group_t *self, mp_obj_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); diff --git a/shared-bindings/displayio/OnDiskBitmap.c b/shared-bindings/displayio/OnDiskBitmap.c index cd2161fd3b0..2169e78a9f9 100644 --- a/shared-bindings/displayio/OnDiskBitmap.c +++ b/shared-bindings/displayio/OnDiskBitmap.c @@ -9,9 +9,12 @@ #include #include "py/runtime.h" +#include "extmod/vfs.h" #include "py/objproperty.h" +#include "shared/runtime/context_manager_helpers.h" #include "shared-bindings/displayio/OnDiskBitmap.h" +#include "shared-bindings/util.h" //| class OnDiskBitmap: //| """Loads values straight from disk. This minimizes memory use but can lead to @@ -47,40 +50,64 @@ //| while True: //| pass""" //| -//| def __init__(self, file: Union[str, typing.BinaryIO]) -> None: +//| def __init__(self, file: str) -> None: //| """Create an OnDiskBitmap object with the given file. //| -//| :param file file: The name of the bitmap file. For backwards compatibility, a file opened in binary mode may also be passed. +//| :param str file: The name of the bitmap file. //| -//| Older versions of CircuitPython required a file opened in binary -//| mode. CircuitPython 7.0 modified OnDiskBitmap so that it takes a -//| filename instead, and opens the file internally. A future version -//| of CircuitPython will remove the ability to pass in an opened file. +//| CircuitPython 11 no longer accepts a file opened in binary mode. Pass the filename instead. +//| OnDiskBitmap opens the file itself and keeps it open until `deinit()` or +//| until the object is garbage collected. //| """ //| ... //| static mp_obj_t displayio_ondiskbitmap_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { mp_arg_check_num(n_args, n_kw, 1, 1, false); - mp_obj_t arg = all_args[0]; - - if (mp_obj_is_str(arg)) { - arg = mp_call_function_2(MP_OBJ_FROM_PTR(&mp_builtin_open_obj), arg, MP_ROM_QSTR(MP_QSTR_rb)); - } - if (!mp_obj_is_type(arg, &mp_type_fileio)) { - mp_raise_TypeError(MP_ERROR_TEXT("file must be a file opened in byte mode")); - } + mp_obj_t filename = mp_arg_validate_type_string(all_args[0], MP_QSTR_file); + mp_obj_t file = mp_call_function_2(MP_OBJ_FROM_PTR(&mp_builtin_open_obj), filename, MP_ROM_QSTR(MP_QSTR_rb)); displayio_ondiskbitmap_t *self = mp_obj_malloc(displayio_ondiskbitmap_t, &displayio_ondiskbitmap_type); - common_hal_displayio_ondiskbitmap_construct(self, MP_OBJ_TO_PTR(arg)); + common_hal_displayio_ondiskbitmap_construct(self, file); return MP_OBJ_FROM_PTR(self); } +static void check_for_deinit(displayio_ondiskbitmap_t *self) { + if (common_hal_displayio_ondiskbitmap_deinited(self)) { + raise_deinited_error(); + } +} + +//| def deinit(self) -> None: +//| """Close the file. The object can no longer be used. If a `TileGrid` still shows +//| this bitmap, areas redrawn after this use color 0, so remove the `TileGrid` first.""" +//| ... +//| +static mp_obj_t displayio_ondiskbitmap_obj_deinit(mp_obj_t self_in) { + displayio_ondiskbitmap_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_displayio_ondiskbitmap_deinit(self); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(displayio_ondiskbitmap_deinit_obj, displayio_ondiskbitmap_obj_deinit); + +//| def __enter__(self) -> OnDiskBitmap: +//| """No-op used by Context Managers.""" +//| ... +//| +// Provided by context manager helper. + +//| def __exit__(self) -> None: +//| """Automatically deinitializes the object when exiting a context. See +//| :ref:`lifetime-and-contextmanagers` for more info.""" +//| ... +//| +// Provided by context manager helper. + //| width: int //| """Width of the bitmap. (read only)""" static mp_obj_t displayio_ondiskbitmap_obj_get_width(mp_obj_t self_in) { displayio_ondiskbitmap_t *self = MP_OBJ_TO_PTR(self_in); - + check_for_deinit(self); return MP_OBJ_NEW_SMALL_INT(common_hal_displayio_ondiskbitmap_get_width(self)); } @@ -93,7 +120,7 @@ MP_PROPERTY_GETTER(displayio_ondiskbitmap_width_obj, //| """Height of the bitmap. (read only)""" static mp_obj_t displayio_ondiskbitmap_obj_get_height(mp_obj_t self_in) { displayio_ondiskbitmap_t *self = MP_OBJ_TO_PTR(self_in); - + check_for_deinit(self); return MP_OBJ_NEW_SMALL_INT(common_hal_displayio_ondiskbitmap_get_height(self)); } @@ -110,6 +137,7 @@ MP_PROPERTY_GETTER(displayio_ondiskbitmap_height_obj, //| static mp_obj_t displayio_ondiskbitmap_obj_get_pixel_shader(mp_obj_t self_in) { displayio_ondiskbitmap_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); return common_hal_displayio_ondiskbitmap_get_pixel_shader(self); } @@ -119,6 +147,9 @@ MP_PROPERTY_GETTER(displayio_ondiskbitmap_pixel_shader_obj, (mp_obj_t)&displayio_ondiskbitmap_get_pixel_shader_obj); static const mp_rom_map_elem_t displayio_ondiskbitmap_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&displayio_ondiskbitmap_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, { MP_ROM_QSTR(MP_QSTR_height), MP_ROM_PTR(&displayio_ondiskbitmap_height_obj) }, { MP_ROM_QSTR(MP_QSTR_pixel_shader), MP_ROM_PTR(&displayio_ondiskbitmap_pixel_shader_obj) }, { MP_ROM_QSTR(MP_QSTR_width), MP_ROM_PTR(&displayio_ondiskbitmap_width_obj) }, diff --git a/shared-bindings/displayio/OnDiskBitmap.h b/shared-bindings/displayio/OnDiskBitmap.h index 229b428df85..fbfc112eaa8 100644 --- a/shared-bindings/displayio/OnDiskBitmap.h +++ b/shared-bindings/displayio/OnDiskBitmap.h @@ -7,11 +7,13 @@ #pragma once #include "shared-module/displayio/OnDiskBitmap.h" -#include "extmod/vfs_fat.h" +#include "extmod/vfs.h" 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, mp_obj_t file); +void common_hal_displayio_ondiskbitmap_deinit(displayio_ondiskbitmap_t *self); +bool common_hal_displayio_ondiskbitmap_deinited(displayio_ondiskbitmap_t *self); uint32_t common_hal_displayio_ondiskbitmap_get_pixel(displayio_ondiskbitmap_t *bitmap, int16_t x, int16_t y); diff --git a/shared-bindings/displayio/TileGrid.c b/shared-bindings/displayio/TileGrid.c index 8a9b2e5e0d3..2a1cf254b43 100644 --- a/shared-bindings/displayio/TileGrid.c +++ b/shared-bindings/displayio/TileGrid.c @@ -17,7 +17,7 @@ #include "shared-bindings/displayio/ColorConverter.h" #include "shared-bindings/displayio/OnDiskBitmap.h" #include "shared-bindings/displayio/Palette.h" -#ifdef CIRCUITPY_TILEPALETTEMAPPER +#if CIRCUITPY_TILEPALETTEMAPPER #include "shared-bindings/tilepalettemapper/TilePaletteMapper.h" #endif @@ -49,7 +49,7 @@ void displayio_tilegrid_validate_pixel_shader(mp_obj_t pixel_shader) { //| self, //| bitmap: Union[Bitmap, OnDiskBitmap], //| *, -//| pixel_shader: Union[ColorConverter, Palette], +//| pixel_shader: Union[ColorConverter, Palette, tilepalettemapper.TilePaletteMapper], //| width: int = 1, //| height: int = 1, //| tile_width: Optional[int] = None, @@ -62,12 +62,13 @@ void displayio_tilegrid_validate_pixel_shader(mp_obj_t pixel_shader) { //| convert the value and its location to a display native pixel color. This may be a simple color //| palette lookup, a gradient, a pattern or a color transformer. //| -//| To save RAM usage, tile values are only allowed in the range from 0 to 255 inclusive (single byte values). +//| When the total number of tiles is 256 or less, tile values are stored as single bytes (uint8_t). +//| When the total number of tiles is more than 256, tile values are stored as double bytes (uint16_t). //| //| tile_width and tile_height match the height of the bitmap by default. //| //| :param Bitmap,OnDiskBitmap bitmap: The bitmap storing one or more tiles. -//| :param ColorConverter,Palette pixel_shader: The pixel shader that produces colors from values +//| :param ColorConverter,Palette,tilepalettemapper.TilePaletteMapper pixel_shader: The pixel shader that produces colors from values //| :param int width: Width of the grid in tiles. //| :param int height: Height of the grid in tiles. //| :param int tile_width: Width of a single tile in pixels. Defaults to the full Bitmap and must evenly divide into the Bitmap's dimensions. @@ -132,6 +133,7 @@ static mp_obj_t displayio_tilegrid_make_new(const mp_obj_type_t *type, size_t n_ bitmap_width / tile_width, bitmap_height / tile_height, pixel_shader, args[ARG_width].u_int, args[ARG_height].u_int, tile_width, tile_height, x, y, args[ARG_default_tile].u_int); + return MP_OBJ_FROM_PTR(self); } @@ -329,7 +331,7 @@ static mp_obj_t displayio_tilegrid_obj_contains(mp_obj_t self_in, mp_obj_t touch } MP_DEFINE_CONST_FUN_OBJ_2(displayio_tilegrid_contains_obj, displayio_tilegrid_obj_contains); -//| pixel_shader: Union[ColorConverter, Palette] +//| pixel_shader: Union[ColorConverter, Palette, tilepalettemapper.TilePaletteMapper] //| """The pixel shader of the tilegrid.""" static mp_obj_t displayio_tilegrid_obj_get_pixel_shader(mp_obj_t self_in) { displayio_tilegrid_t *self = native_tilegrid(self_in); @@ -453,7 +455,7 @@ static mp_obj_t tilegrid_subscr(mp_obj_t self_in, mp_obj_t index_obj, mp_obj_t v return MP_OBJ_NULL; // op not supported } else { mp_int_t value = mp_obj_get_int(value_obj); - mp_arg_validate_int_range(value, 0, 255, MP_QSTR_tile); + mp_arg_validate_int_range(value, 0, self->tiles_in_bitmap - 1, MP_QSTR_tile); common_hal_displayio_tilegrid_set_tile(self, x, y, value); } @@ -485,5 +487,6 @@ MP_DEFINE_CONST_OBJ_TYPE( MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, make_new, displayio_tilegrid_make_new, locals_dict, &displayio_tilegrid_locals_dict, - subscr, tilegrid_subscr + subscr, tilegrid_subscr, + protocol, DISPLAYIO_TILEGRID_LVGL_PROTOCOL ); diff --git a/shared-bindings/displayio/TileGrid.h b/shared-bindings/displayio/TileGrid.h index 19af39fadeb..521ee34583c 100644 --- a/shared-bindings/displayio/TileGrid.h +++ b/shared-bindings/displayio/TileGrid.h @@ -10,10 +10,13 @@ extern const mp_obj_type_t displayio_tilegrid_type; +// Raises TypeError if pixel_shader isn't a Palette, ColorConverter or TilePaletteMapper. +void displayio_tilegrid_validate_pixel_shader(mp_obj_t pixel_shader); + 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 tile_width, uint16_t tile_height, uint16_t x, uint16_t y, uint16_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); @@ -43,9 +46,9 @@ uint16_t common_hal_displayio_tilegrid_get_height(displayio_tilegrid_t *self); uint16_t common_hal_displayio_tilegrid_get_tile_width(displayio_tilegrid_t *self); uint16_t common_hal_displayio_tilegrid_get_tile_height(displayio_tilegrid_t *self); -uint8_t common_hal_displayio_tilegrid_get_tile(displayio_tilegrid_t *self, uint16_t x, uint16_t y); -void common_hal_displayio_tilegrid_set_tile(displayio_tilegrid_t *self, uint16_t x, uint16_t y, uint8_t tile_index); +uint16_t common_hal_displayio_tilegrid_get_tile(displayio_tilegrid_t *self, uint16_t x, uint16_t y); +void common_hal_displayio_tilegrid_set_tile(displayio_tilegrid_t *self, uint16_t x, uint16_t y, uint16_t tile_index); // Private API for scrolling the TileGrid. void common_hal_displayio_tilegrid_set_top_left(displayio_tilegrid_t *self, uint16_t x, uint16_t y); -void common_hal_displayio_tilegrid_set_all_tiles(displayio_tilegrid_t *self, uint8_t tile_index); +void common_hal_displayio_tilegrid_set_all_tiles(displayio_tilegrid_t *self, uint16_t tile_index); diff --git a/shared-bindings/displayio/__init__.c b/shared-bindings/displayio/__init__.c index e0c35d3bce4..289fc99acd9 100644 --- a/shared-bindings/displayio/__init__.c +++ b/shared-bindings/displayio/__init__.c @@ -52,7 +52,6 @@ //| rgbmatrix.RGBMatrix //| | is31fl3741.IS31FL3741_FrameBuffer //| | sharpdisplay.SharpMemoryFramebuffer -//| | videocore.Framebuffer //| | picodvi.Framebuffer //| | aurora_epaper.AuroraMemoryFramebuffer //| ) @@ -78,12 +77,29 @@ //| release the builtin display on boards that have one. You will need to reinitialize it yourself //| afterwards. This may take seconds to complete if an active EPaperDisplay is refreshing. //| -//| Use this once in your code.py if you initialize a display. Place it right before the -//| initialization so the display is active as long as possible.""" +//| .. deprecated:: 11.0.0 +//| Call ``deinit()`` on the display instead. To release a built-in display or a display +//| kept from an earlier run, use ``supervisor.runtime.display.deinit()``. +//| ``release_displays()`` will be removed in a future major release. +//| +//| Displays that are not `supervisor.runtime.display ` are released automatically when your code +//| finishes. Use this before initializing a display if one may still be active, such as a builtin +//| display or a display from an earlier run. +//| +//| Once you release a builtin display (one that is initialized automatically, not by user code), +//| the display will remain released even if you restart the CircuitPython VM, for instance by typing ctrl-D. +//| The display is not re-initialized until you do a hard reset or manually initialize it again. +//| +//| If an EPaperDisplay using ``lag_frames`` can't get its bus, this waits up to 30 seconds and then +//| raises `RuntimeError` with every display left as it was, so you can free the bus and call it again. +//| """ //| ... //| //| static mp_obj_t displayio_release_displays(void) { + #if CIRCUITPY_EPAPERDISPLAY_FAST + displayio_prepare_release_displays(); + #endif common_hal_displayio_release_displays(); return mp_const_none; } diff --git a/shared-bindings/displayio/__init__.h b/shared-bindings/displayio/__init__.h index 88e9650cf44..4d9fa5d75d7 100644 --- a/shared-bindings/displayio/__init__.h +++ b/shared-bindings/displayio/__init__.h @@ -20,15 +20,30 @@ typedef enum displayio_colorspace { DISPLAYIO_COLORSPACE_BGR565_SWAPPED, DISPLAYIO_COLORSPACE_BGR555_SWAPPED, DISPLAYIO_COLORSPACE_L8, + DISPLAYIO_COLORSPACE_L1, } displayio_colorspace_t; void common_hal_displayio_release_displays(void); + +// Release one display and its bus. +// +// display is the native display object (not a Python subclass instance). +// - Does nothing if display is not an active display. +// - The bus is not released if another display still uses it. +// - If display is the primary display, the primary display is cleared +// and the terminal is stopped. +// +// Raises RuntimeError, with nothing released, if an EPaperDisplay using +// lag_frames can't get its bus. +void common_hal_displayio_deinit_display(mp_obj_t display); mp_obj_t common_hal_displayio_get_primary_display(void); void common_hal_displayio_set_primary_display(mp_obj_t o); void common_hal_displayio_auto_primary_display(void); +bool common_hal_displayio_primary_display_set_by_user(void); extern const mp_obj_type_t displayio_colorspace_type; extern const cp_enum_obj_t displayio_colorspace_RGB888_obj; +extern const cp_enum_obj_t displayio_colorspace_RGB565_obj; // Used in the various bus displays: BusDisplay, EPaperDisplay and ParallelDisplay @@ -49,4 +64,5 @@ typedef bool (*display_bus_begin_transaction)(mp_obj_t bus); typedef void (*display_bus_send)(mp_obj_t bus, display_byte_type_t byte_type, display_chip_select_behavior_t chip_select, const uint8_t *data, uint32_t data_length); typedef void (*display_bus_end_transaction)(mp_obj_t bus); +typedef void (*display_bus_flush)(mp_obj_t bus); typedef void (*display_bus_collect_ptrs)(mp_obj_t bus); diff --git a/shared-bindings/dotclockframebuffer/DotClockFramebuffer.c b/shared-bindings/dotclockframebuffer/DotClockFramebuffer.c index faa0c21b097..c6069afe814 100644 --- a/shared-bindings/dotclockframebuffer/DotClockFramebuffer.c +++ b/shared-bindings/dotclockframebuffer/DotClockFramebuffer.c @@ -46,21 +46,15 @@ //| ) -> None: //| """Create a DotClockFramebuffer object associated with the given pins. //| -//| The 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. +//| The pins are then in use by the display until your code finishes or +//| the display's ``deinit()`` is called. If the display is +//| `supervisor.runtime.display `, they stay in use after your code finishes, so CircuitPython can +//| use the display. In that case, check `supervisor.runtime.display ` before creating the display +//| again, or call ``supervisor.runtime.display.deinit()`` first. //| //| When a board has dedicated dot clock framebuffer pins and/or timings, they are intended to be used in the constructor with ``**`` dictionary unpacking like so: //| ``DotClockFramebuffer(**board.TFT_PINS, **board.TFT_TIMINGS)`` //| -//| On Espressif-family microcontrollers, this driver requires that the -//| ``CIRCUITPY_RESERVED_PSRAM`` in ``settings.toml`` be large enough to hold the -//| framebuffer. Generally, boards with built-in displays or display connectors -//| will have a default setting that is large enough for typical use. If the -//| constructor raises a MemoryError or an IDFError, this probably indicates the -//| setting is too small and should be increased. -//| //| TFT connection parameters: //| //| :param microcontroller.Pin de: The "data enable" input to the display diff --git a/shared-bindings/dotclockframebuffer/__init__.c b/shared-bindings/dotclockframebuffer/__init__.c index b8dbf8c1897..700cd067178 100644 --- a/shared-bindings/dotclockframebuffer/__init__.c +++ b/shared-bindings/dotclockframebuffer/__init__.c @@ -104,7 +104,7 @@ static mp_obj_t ioexpander_send_init_sequence(size_t n_args, const mp_obj_t *pos mp_arg_validate_int_range(cs_bit, 0, max_bit, MP_QSTR_cs_bit); mp_arg_validate_int_range(mosi_bit, 0, max_bit, MP_QSTR_mosi_bit); mp_arg_validate_int_range(clk_bit, 0, max_bit, MP_QSTR_clk_bit); - mp_arg_validate_int_range(gpio_data, 0, (1 << (max_bit * 8)) - 1, MP_QSTR_gpio_data); + mp_arg_validate_int_range(gpio_data, 0, (1 << (gpio_data_len * 8)) - 1, MP_QSTR_gpio_data); mp_int_t reset_mask = 0; if (args[ARG_reset_bit].u_obj != MP_ROM_NONE) { mp_int_t reset_bit = mp_arg_validate_int_range(mp_arg_validate_type_int(args[ARG_reset_bit].u_obj, MP_QSTR_reset_bit), 0, max_bit, MP_QSTR_reset_bit); diff --git a/shared-bindings/dualbank/__init__.c b/shared-bindings/dualbank/__init__.c index 2c00a5b0100..160ce4947a7 100644 --- a/shared-bindings/dualbank/__init__.c +++ b/shared-bindings/dualbank/__init__.c @@ -34,7 +34,7 @@ //| This module is unavailable as the flash is only large enough for one app partition. //| //| Boards with flash ``>2MB``: -//| This module is enabled/disabled at runtime based on whether the ``CIRCUITPY`` drive +//| This module is enabled/disabled at runtime based on whether the **CIRCUITPY** drive //| is extended or not. See `storage.erase_filesystem()` for more information. //| //| .. code-block:: python diff --git a/shared-bindings/emmcio/EMMC.c b/shared-bindings/emmcio/EMMC.c new file mode 100644 index 00000000000..25b0467d5e3 --- /dev/null +++ b/shared-bindings/emmcio/EMMC.c @@ -0,0 +1,486 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "py/obj.h" +#include "py/objproperty.h" +#include "py/runtime.h" +#include "py/mperrno.h" +#include "py/mphal.h" + +#include "extmod/vfs.h" + +#include "shared-bindings/emmcio/EMMC.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/util.h" +#include "shared/runtime/context_manager_helpers.h" +#include "common-hal/emmcio/EMMC.h" + +static void check_for_deinit(emmcio_emmc_obj_t *self) { + if (common_hal_emmcio_emmc_deinited(self)) { + raise_deinited_error(); + } +} + +//| class EMMC: +//| """eMMC as a block device""" +//| +//| def __init__( +//| self, +//| *, +//| clock: microcontroller.Pin, +//| command: microcontroller.Pin, +//| data: microcontroller.Pin, +//| reset: Optional[microcontroller.Pin] = None, +//| vccq: Optional[microcontroller.Pin] = None, +//| high_speed: bool = False, +//| write_enabled: bool = False, +//| ) -> None: +//| """Power up the card and make it ready for block access. +//| +//| Only one `EMMC` object may exist at a time. Call `deinit()`, or use +//| the object as a context manager, to release the card and its pins. +//| +//| :param ~microcontroller.Pin clock: the card's CLK pin +//| :param ~microcontroller.Pin command: the card's CMD pin +//| :param ~microcontroller.Pin data: the card's DAT0 pin. The bus is +//| 1-bit, so this is a single pin. +//| :param ~microcontroller.Pin reset: the card's RST_n pin, if the board +//| wires one +//| :param ~microcontroller.Pin vccq: a pin gating the card's I/O rail, +//| if the board has one +//| :param bool high_speed: Run the bus at its faster clock rate. Raises +//| an `OSError` if the card will not make the switch. +//| :param bool write_enabled: Allow `writeblocks()`. When `False`, the +//| object is read-only and every write path refuses. +//| +//| :raises ValueError: if the pins are unusable or already in use, or +//| if the card is owned by the USB drive. +//| :raises OSError: if the card does not come up. ``emmcio failure: n`` +//| names the MMC command that did not answer (``8`` being the +//| extended CSD), and ``high_speed failure: n`` how far the switch +//| got: ``0`` the card does not advertise 52 MHz, ``1`` no CMD6 +//| response, ``2`` the card never released DAT0, ``3`` it never came +//| back to the transfer state, ``4`` the EXT_CSD readback did not +//| take, ``5`` the 32 MHz smoke test failed, ``7`` the card rejected +//| HS_TIMING. +//| +//| Mount the card's filesystem:: +//| +//| import board +//| import emmcio +//| import storage +//| +//| emmc = emmcio.EMMC( +//| clock=board.EMMC_CLK, +//| command=board.EMMC_CMD, +//| data=board.EMMC_DAT0, +//| reset=board.EMMC_RESET, +//| vccq=board.EMMC_VCCQ, +//| high_speed=True, +//| write_enabled=True, +//| ) +//| storage.mount(storage.VfsFat(emmc), "/sd") +//| """ +//| ... +//| +static mp_obj_t emmcio_emmc_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_clock, ARG_command, ARG_data, ARG_reset, ARG_vccq, ARG_high_speed, ARG_write_enabled }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_clock, MP_ARG_REQUIRED | MP_ARG_KW_ONLY | MP_ARG_OBJ }, + { MP_QSTR_command, MP_ARG_REQUIRED | MP_ARG_KW_ONLY | MP_ARG_OBJ }, + { MP_QSTR_data, MP_ARG_REQUIRED | MP_ARG_KW_ONLY | MP_ARG_OBJ }, + { MP_QSTR_reset, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, + { MP_QSTR_vccq, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, + { MP_QSTR_high_speed, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, + { MP_QSTR_write_enabled, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + const mcu_pin_obj_t *clock = validate_obj_is_pin(args[ARG_clock].u_obj, MP_QSTR_clock); + const mcu_pin_obj_t *command = validate_obj_is_pin(args[ARG_command].u_obj, MP_QSTR_command); + const mcu_pin_obj_t *data = validate_obj_is_pin(args[ARG_data].u_obj, MP_QSTR_data); + const mcu_pin_obj_t *reset = validate_obj_is_pin_or_none(args[ARG_reset].u_obj, MP_QSTR_reset); + const mcu_pin_obj_t *vccq = validate_obj_is_pin_or_none(args[ARG_vccq].u_obj, MP_QSTR_vccq); + + // Every line is a separate net, so two of them being the same pin is a + // wiring mistake, not a configuration. + const mcu_pin_obj_t *pins[] = { clock, command, data, reset, vccq }; + const qstr names[] = { MP_QSTR_clock, MP_QSTR_command, MP_QSTR_data, MP_QSTR_reset, MP_QSTR_vccq }; + for (size_t i = 0; i < MP_ARRAY_SIZE(pins); i++) { + for (size_t j = i + 1; j < MP_ARRAY_SIZE(pins); j++) { + if (pins[i] != NULL && pins[i] == pins[j]) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("%q and %q must be different"), + names[i], names[j]); + } + } + } + + emmcio_emmc_obj_t *self = mp_obj_malloc_with_finaliser(emmcio_emmc_obj_t, &emmcio_emmc_type); + // An OSError means the card itself did not come up; a ValueError means the + // wiring or the hardware is unusable. + int detail = 0; + switch (common_hal_emmcio_emmc_construct(self, clock, command, data, reset, vccq, + args[ARG_high_speed].u_bool, args[ARG_write_enabled].u_bool, &detail)) { + case EMMCIO_OK: + break; + case EMMCIO_ERR_PIN_PORT: + mp_raise_ValueError_varg(MP_ERROR_TEXT("Invalid %q pin"), (qstr)detail); + break; + case EMMCIO_ERR_SPI_IN_USE: + mp_raise_ValueError(MP_ERROR_TEXT("SPI peripheral in use")); + break; + case EMMCIO_ERR_PIN_IN_USE: + mp_raise_ValueError(MP_ERROR_TEXT("Hardware in use, try alternative pins")); + break; + case EMMCIO_ERR_USB_OWNED: + mp_raise_ValueError_varg(MP_ERROR_TEXT("%q in use"), MP_QSTR_emmcio); + break; + case EMMCIO_ERR_IN_USE: + mp_raise_ValueError(MP_ERROR_TEXT("Peripheral in use")); + break; + case EMMCIO_ERR_INIT: + mp_raise_OSError_msg_varg(MP_ERROR_TEXT("%q failure: %d"), MP_QSTR_emmcio, detail); + break; + case EMMCIO_ERR_HIGH_SPEED: + mp_raise_OSError_msg_varg(MP_ERROR_TEXT("%q failure: %d"), MP_QSTR_high_speed, detail); + break; + } + return MP_OBJ_FROM_PTR(self); +} + +//| def deinit(self) -> None: +//| """Release the card and the pins it uses. Any further use of this +//| object raises a `ValueError`.""" +//| ... +//| +static mp_obj_t emmcio_emmc_deinit(mp_obj_t self_in) { + common_hal_emmcio_emmc_deinit(MP_OBJ_TO_PTR(self_in)); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(emmcio_emmc_deinit_obj, emmcio_emmc_deinit); + +//| def __enter__(self) -> EMMC: +//| """No-op used by Context Managers.""" +//| ... +//| +//| def __exit__(self) -> None: +//| """Automatically deinitializes the hardware when exiting a context. See +//| :ref:`lifetime-and-contextmanagers` for more info.""" +//| ... +//| +static mp_obj_t emmcio_emmc_obj___exit__(size_t n_args, const mp_obj_t *args) { + return emmcio_emmc_deinit(args[0]); +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(emmcio_emmc___exit___obj, 4, 4, emmcio_emmc_obj___exit__); + +#define CHUNK_BLOCKS 64u + +static int emmc_read_chunked(emmcio_emmc_obj_t *self, uint8_t *out, mp_uint_t start, mp_uint_t count, bool from_vm) { + mp_uint_t total = common_hal_emmcio_emmc_get_block_count(self); + if (count == 0 || start >= total || count > total - start) { + return -MP_EINVAL; + } + for (mp_uint_t done = 0; done < count;) { + mp_uint_t run = MIN(CHUNK_BLOCKS, count - done); + bool ok = false; + for (int attempt = 0; attempt < 3 && !ok; attempt++) { + ok = common_hal_emmcio_emmc_readblocks(start + done, out + done * EMMC_BLOCK_SIZE, run); + } + if (!ok) { + return -MP_EIO; + } + done += run; + RUN_BACKGROUND_TASKS; + if (from_vm) { + mp_handle_pending(true); + } + } + return 0; +} + +//| def readblocks(self, start_block: int, buf: WriteableBuffer) -> None: +//| """Read into ``buf`` starting at ``start_block``. +//| +//| :param int start_block: the first block to read +//| :param WriteableBuffer buf: a buffer whose length is a non-zero +//| multiple of `block_size` +//| +//| :raises ValueError: if ``buf`` is the wrong length, or the requested +//| blocks run past the end of the card. +//| :raises OSError: if the card fails to deliver the data.""" +//| ... +//| +static mp_obj_t emmcio_emmc_readblocks(mp_obj_t self_in, mp_obj_t start_in, mp_obj_t buf_in) { + emmcio_emmc_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(buf_in, &bufinfo, MP_BUFFER_WRITE); + if (bufinfo.len == 0 || (bufinfo.len % EMMC_BLOCK_SIZE) != 0) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("Buffer must be a multiple of %d bytes"), 512); + } + mp_uint_t start = mp_obj_get_int_truncated(start_in); + mp_uint_t count = bufinfo.len / EMMC_BLOCK_SIZE; + mp_uint_t total = common_hal_emmcio_emmc_get_block_count(self); + if (start >= total || count > total - start) { + mp_raise_ValueError(MP_ERROR_TEXT("address out of range")); + } + + int err = emmc_read_chunked(self, bufinfo.buf, start, count, true); + if (err != 0) { + mp_raise_OSError(-err); + } + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_3(emmcio_emmc_readblocks_obj, emmcio_emmc_readblocks); + +static int emmc_write_chunked(emmcio_emmc_obj_t *self, const uint8_t *src, mp_uint_t start, mp_uint_t count, bool from_vm) { + mp_uint_t total = common_hal_emmcio_emmc_get_block_count(self); + if (count == 0 || start >= total || count > total - start) { + return -MP_EINVAL; + } + for (mp_uint_t done = 0; done < count;) { + mp_uint_t run = MIN(CHUNK_BLOCKS, count - done); + bool ok = false; + for (int attempt = 0; attempt < 3 && !ok; attempt++) { + ok = common_hal_emmcio_emmc_writeblocks(start + done, src + done * EMMC_BLOCK_SIZE, run); + } + if (!ok) { + return -MP_EIO; + } + done += run; + RUN_BACKGROUND_TASKS; + if (from_vm) { + mp_handle_pending(true); + } + } + return 0; +} + +//| def writeblocks(self, start_block: int, buf: ReadableBuffer) -> None: +//| """Write ``buf`` to the card starting at ``start_block``. +//| +//| :param int start_block: the first block to write +//| :param ReadableBuffer buf: a buffer whose length is a non-zero +//| multiple of `block_size` +//| +//| :raises RuntimeError: if this object was not constructed with +//| ``write_enabled=True``. +//| :raises ValueError: if ``buf`` is the wrong length, or the requested +//| blocks run past the end of the card. +//| :raises OSError: if the write fails.""" +//| ... +//| +static mp_obj_t emmcio_emmc_writeblocks(mp_obj_t self_in, mp_obj_t start_in, mp_obj_t buf_in) { + emmcio_emmc_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + if (!self->write_enabled) { + mp_raise_msg(&mp_type_RuntimeError, + MP_ERROR_TEXT("Read-only")); + } + + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(buf_in, &bufinfo, MP_BUFFER_READ); + if (bufinfo.len == 0 || (bufinfo.len % EMMC_BLOCK_SIZE) != 0) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("Buffer must be a multiple of %d bytes"), 512); + } + mp_uint_t start = mp_obj_get_int_truncated(start_in); + mp_uint_t count = bufinfo.len / EMMC_BLOCK_SIZE; + mp_uint_t total = common_hal_emmcio_emmc_get_block_count(self); + if (start >= total || count > total - start) { + mp_raise_ValueError(MP_ERROR_TEXT("address out of range")); + } + + int err = emmc_write_chunked(self, bufinfo.buf, start, count, true); + if (err != 0) { + mp_raise_OSError(-err); + } + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_3(emmcio_emmc_writeblocks_obj, emmcio_emmc_writeblocks); + +//| def ioctl(self, op: int, arg: int) -> Optional[int]: +//| """Perform a block-device control operation, as required by the +//| block-device protocol. Returns `None` for operations this device does +//| not implement.""" +//| ... +//| +static mp_obj_t emmcio_emmc_ioctl(mp_obj_t self_in, mp_obj_t op_in, mp_obj_t arg_in) { + emmcio_emmc_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + uint32_t out = 0; + if (!common_hal_emmcio_emmc_ioctl(mp_obj_get_int_truncated(op_in), + mp_obj_get_int_truncated(arg_in), &out)) { + return mp_const_none; + } + return mp_obj_new_int_from_uint(out); +} +static MP_DEFINE_CONST_FUN_OBJ_3(emmcio_emmc_ioctl_obj, emmcio_emmc_ioctl); + +mp_uint_t emmcio_emmc_readblocks_native(mp_obj_t self_in, uint8_t *buf, + uint32_t start_block, uint32_t nblocks) { + emmcio_emmc_obj_t *self = MP_OBJ_TO_PTR(self_in); + if (common_hal_emmcio_emmc_deinited(self)) { + return -MP_ENODEV; + } + return emmc_read_chunked(self, buf, start_block, nblocks, false); +} + +mp_uint_t emmcio_emmc_writeblocks_native(mp_obj_t self_in, const uint8_t *buf, + uint32_t start_block, uint32_t nblocks) { + emmcio_emmc_obj_t *self = MP_OBJ_TO_PTR(self_in); + if (common_hal_emmcio_emmc_deinited(self)) { + return -MP_ENODEV; + } + + if (!self->write_enabled) { + return -MP_EROFS; + } + return emmc_write_chunked(self, buf, start_block, nblocks, false); +} + +bool emmcio_emmc_ioctl_native(mp_obj_t self_in, uint32_t cmd, uint32_t arg, + size_t *out_value) { + + (void)self_in; + uint32_t out = 0; + bool ok = common_hal_emmcio_emmc_ioctl(cmd, arg, &out); + *out_value = out; + return ok; +} + +bool emmcio_emmc_is_write_enabled(mp_obj_t self_in) { + emmcio_emmc_obj_t *self = MP_OBJ_TO_PTR(self_in); + return !common_hal_emmcio_emmc_deinited(self) && self->write_enabled; +} + +//| def read_ext_csd(self) -> bytes: +//| """Read the card's 512-byte extended CSD register.""" +//| ... +//| +static mp_obj_t emmcio_emmc_read_ext_csd(mp_obj_t self_in) { + emmcio_emmc_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + + uint8_t ext_csd[EMMC_BLOCK_SIZE]; + if (!common_hal_emmcio_emmc_read_ext_csd(ext_csd)) { + mp_raise_OSError(MP_EIO); + } + return mp_obj_new_bytes(ext_csd, sizeof(ext_csd)); +} +static MP_DEFINE_CONST_FUN_OBJ_1(emmcio_emmc_read_ext_csd_obj, emmcio_emmc_read_ext_csd); + +//| def status(self) -> int: +//| """Read the card's 32-bit status register.""" +//| ... +//| +static mp_obj_t emmcio_emmc_status(mp_obj_t self_in) { + emmcio_emmc_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + + uint8_t r1[6]; + if (!common_hal_emmcio_emmc_read_status(r1)) { + mp_raise_OSError(MP_EIO); + } + uint32_t status = ((uint32_t)r1[1] << 24) | ((uint32_t)r1[2] << 16) | + ((uint32_t)r1[3] << 8) | (uint32_t)r1[4]; + return mp_obj_new_int_from_uint(status); +} +static MP_DEFINE_CONST_FUN_OBJ_1(emmcio_emmc_status_obj, emmcio_emmc_status); + +//| count: int +//| """The number of blocks on the card.""" +//| +static mp_obj_t emmcio_emmc_get_count(mp_obj_t self_in) { + emmcio_emmc_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_int_from_uint(common_hal_emmcio_emmc_get_block_count(self)); +} +static MP_DEFINE_CONST_FUN_OBJ_1(emmcio_emmc_get_count_obj, emmcio_emmc_get_count); +MP_PROPERTY_GETTER(emmcio_emmc_count_obj, (mp_obj_t)&emmcio_emmc_get_count_obj); + +//| block_size: int +//| """The size of one block, in bytes.""" +//| +static mp_obj_t emmcio_emmc_get_block_size(mp_obj_t self_in) { + return MP_OBJ_NEW_SMALL_INT(EMMC_BLOCK_SIZE); +} +static MP_DEFINE_CONST_FUN_OBJ_1(emmcio_emmc_get_block_size_obj, emmcio_emmc_get_block_size); +MP_PROPERTY_GETTER(emmcio_emmc_block_size_obj, (mp_obj_t)&emmcio_emmc_get_block_size_obj); + +//| cid: bytes +//| """The card's 16-byte identification register.""" +//| +static mp_obj_t emmcio_emmc_get_cid(mp_obj_t self_in) { + emmcio_emmc_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_bytes(common_hal_emmcio_emmc_get_cid(self), 16); +} +static MP_DEFINE_CONST_FUN_OBJ_1(emmcio_emmc_get_cid_obj, emmcio_emmc_get_cid); +MP_PROPERTY_GETTER(emmcio_emmc_cid_obj, (mp_obj_t)&emmcio_emmc_get_cid_obj); + +//| write_enabled: bool +//| """Whether `writeblocks()` is permitted on this object.""" +//| +static mp_obj_t emmcio_emmc_get_write_enabled(mp_obj_t self_in) { + emmcio_emmc_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_bool(self->write_enabled); +} +static MP_DEFINE_CONST_FUN_OBJ_1(emmcio_emmc_get_write_enabled_obj, emmcio_emmc_get_write_enabled); +MP_PROPERTY_GETTER(emmcio_emmc_write_enabled_obj, (mp_obj_t)&emmcio_emmc_get_write_enabled_obj); + +//| high_speed: bool +//| """Whether the card is running at its faster clock rate.""" +//| +static mp_obj_t emmcio_emmc_get_high_speed(mp_obj_t self_in) { + emmcio_emmc_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_bool(common_hal_emmcio_emmc_get_high_speed(self)); +} +static MP_DEFINE_CONST_FUN_OBJ_1(emmcio_emmc_get_high_speed_obj, emmcio_emmc_get_high_speed); +MP_PROPERTY_GETTER(emmcio_emmc_high_speed_obj, (mp_obj_t)&emmcio_emmc_get_high_speed_obj); + +//| frequency: int +//| """The bus clock rate in Hz.""" +//| +static mp_obj_t emmcio_emmc_get_frequency(mp_obj_t self_in) { + emmcio_emmc_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_int_from_uint(common_hal_emmcio_emmc_get_frequency(self)); +} +static MP_DEFINE_CONST_FUN_OBJ_1(emmcio_emmc_get_frequency_obj, emmcio_emmc_get_frequency); +MP_PROPERTY_GETTER(emmcio_emmc_frequency_obj, (mp_obj_t)&emmcio_emmc_get_frequency_obj); + +static const mp_rom_map_elem_t emmcio_emmc_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&emmcio_emmc_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&emmcio_emmc_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&emmcio_emmc___exit___obj) }, + + { MP_ROM_QSTR(MP_QSTR_readblocks), MP_ROM_PTR(&emmcio_emmc_readblocks_obj) }, + { MP_ROM_QSTR(MP_QSTR_writeblocks), MP_ROM_PTR(&emmcio_emmc_writeblocks_obj) }, + { MP_ROM_QSTR(MP_QSTR_ioctl), MP_ROM_PTR(&emmcio_emmc_ioctl_obj) }, + { MP_ROM_QSTR(MP_QSTR_read_ext_csd), MP_ROM_PTR(&emmcio_emmc_read_ext_csd_obj) }, + { MP_ROM_QSTR(MP_QSTR_status), MP_ROM_PTR(&emmcio_emmc_status_obj) }, + + { MP_ROM_QSTR(MP_QSTR_count), MP_ROM_PTR(&emmcio_emmc_count_obj) }, + { MP_ROM_QSTR(MP_QSTR_high_speed), MP_ROM_PTR(&emmcio_emmc_high_speed_obj) }, + { MP_ROM_QSTR(MP_QSTR_frequency), MP_ROM_PTR(&emmcio_emmc_frequency_obj) }, + { MP_ROM_QSTR(MP_QSTR_block_size), MP_ROM_PTR(&emmcio_emmc_block_size_obj) }, + { MP_ROM_QSTR(MP_QSTR_cid), MP_ROM_PTR(&emmcio_emmc_cid_obj) }, + { MP_ROM_QSTR(MP_QSTR_write_enabled), MP_ROM_PTR(&emmcio_emmc_write_enabled_obj) }, +}; +static MP_DEFINE_CONST_DICT(emmcio_emmc_locals_dict, emmcio_emmc_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + emmcio_emmc_type, + MP_QSTR_EMMC, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + locals_dict, &emmcio_emmc_locals_dict, + make_new, emmcio_emmc_make_new + ); diff --git a/shared-bindings/emmcio/EMMC.h b/shared-bindings/emmcio/EMMC.h new file mode 100644 index 00000000000..1adfdcafef2 --- /dev/null +++ b/shared-bindings/emmcio/EMMC.h @@ -0,0 +1,47 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +#define EMMC_BLOCK_SIZE 512u + +extern const mp_obj_type_t emmcio_emmc_type; + +// Why bring-up failed. The binding turns these into exceptions; the automount +// path just gives up. +typedef enum { + EMMCIO_OK = 0, + EMMCIO_ERR_PIN_PORT, // detail: qstr of the pin the port cannot drive + EMMCIO_ERR_SPI_IN_USE, + EMMCIO_ERR_PIN_IN_USE, + EMMCIO_ERR_USB_OWNED, + EMMCIO_ERR_IN_USE, + EMMCIO_ERR_INIT, // detail: the MMC command that did not answer + EMMCIO_ERR_HIGH_SPEED, // detail: the switch step it stopped at +} emmcio_construct_result_t; + +// ---- native block-device protocol ----------------------------------------- +// +// The same shape sdcardio and sdioio present, so extmod/vfs_blockdev.c can +// bypass the Python method call. + +// 0 on success, negative errno on failure. Never raises. +mp_uint_t emmcio_emmc_readblocks_native(mp_obj_t self_in, uint8_t *buf, + uint32_t start_block, uint32_t nblocks); + +// 0 on success, -MP_EROFS on an object without write_enabled=True, other +// negative errno on failure. Never raises. +mp_uint_t emmcio_emmc_writeblocks_native(mp_obj_t self_in, const uint8_t *buf, + uint32_t start_block, uint32_t nblocks); + +// false = op not implemented, the caller turns that into None. +bool emmcio_emmc_ioctl_native(mp_obj_t self_in, uint32_t cmd, uint32_t arg, + size_t *out_value); + +// Whether this object may write at all +bool emmcio_emmc_is_write_enabled(mp_obj_t self_in); diff --git a/shared-bindings/emmcio/__init__.c b/shared-bindings/emmcio/__init__.c new file mode 100644 index 00000000000..2caf1f8aeb3 --- /dev/null +++ b/shared-bindings/emmcio/__init__.c @@ -0,0 +1,32 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "py/obj.h" +#include "py/runtime.h" + +#include "shared-bindings/emmcio/EMMC.h" + +//| """Block device access to the on-board eMMC +//| +//| The `emmcio` module exposes an eMMC chip as a block device. +//| It provides no filesystem of its own: to read files, hand an `EMMC` +//| object to `storage.VfsFat` and mount it. +//| +//| """ +//| + +static const mp_rom_map_elem_t emmcio_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_emmcio) }, + { MP_ROM_QSTR(MP_QSTR_EMMC), MP_ROM_PTR(&emmcio_emmc_type) }, +}; +static MP_DEFINE_CONST_DICT(emmcio_module_globals, emmcio_module_globals_table); + +const mp_obj_module_t emmcio_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&emmcio_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_emmcio, emmcio_module); diff --git a/shared-bindings/emmcio/__init__.h b/shared-bindings/emmcio/__init__.h new file mode 100644 index 00000000000..efe68c01b70 --- /dev/null +++ b/shared-bindings/emmcio/__init__.h @@ -0,0 +1,11 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Clear module state on every VM reset. The card's rail has already been cut +// by then, so the state must not pretend to survive. +void emmcio_reset(void); diff --git a/shared-bindings/epaperdisplay/EPaperDisplay.c b/shared-bindings/epaperdisplay/EPaperDisplay.c index 0d558a13196..d2e2cb1c45b 100644 --- a/shared-bindings/epaperdisplay/EPaperDisplay.c +++ b/shared-bindings/epaperdisplay/EPaperDisplay.c @@ -13,10 +13,12 @@ #include "py/objproperty.h" #include "py/objtype.h" #include "py/runtime.h" +#include "shared-bindings/displayio/__init__.h" #include "shared-bindings/displayio/Group.h" #include "shared-bindings/microcontroller/Pin.h" #include "shared-bindings/util.h" #include "shared-module/displayio/__init__.h" +#include "shared-module/displayio/bus_core.h" //| from busdisplay import _DisplayBus //| @@ -25,8 +27,9 @@ //| """Manage updating an epaper display over a display bus //| //| This initializes an epaper display and connects it into CircuitPython. Unlike other -//| objects in CircuitPython, EPaperDisplay objects live until `displayio.release_displays()` -//| is called. This is done so that CircuitPython can use the display itself. +//| objects in CircuitPython, a EPaperDisplay stays active after your code finishes if it is +//| `supervisor.runtime.display `, so that CircuitPython can use it. Otherwise, it is released +//| when your code finishes. //| //| Most people should not use this class directly. Use a specific display driver instead that will //| contain the startup and shutdown sequences at minimum. @@ -53,7 +56,9 @@ //| black_bits_inverted: bool = False, //| write_color_ram_command: Optional[int] = None, //| color_bits_inverted: bool = False, +//| write_previous_ram_command: Optional[int] = None, //| highlight_color: int = 0x000000, +//| highlight_color2: int = 0x000000, //| refresh_display_command: Union[int, circuitpython_typing.ReadableBuffer], //| refresh_time: float = 40, //| busy_pin: Optional[microcontroller.Pin] = None, @@ -62,9 +67,12 @@ //| always_toggle_chip_select: bool = False, //| grayscale: bool = False, //| advanced_color_epaper: bool = False, +//| spectra6: bool = False, //| two_byte_sequence_length: bool = False, //| start_up_time: float = 0, //| address_little_endian: bool = False, +//| lag_frames: int = 0, +//| clean_sequence: Optional[ReadableBuffer] = None, //| ) -> None: //| """Create a EPaperDisplay object on the given display bus (`fourwire.FourWire` or `paralleldisplaybus.ParallelBus`). //| @@ -76,6 +84,31 @@ //| the parameters specifies the delay duration in milliseconds. The value 0xff will lead to an //| extra long 500 ms delay instead of 255 ms. The next byte will begin a new command definition. //| +//| To drive the display fast, set ``lag_frames`` to at least 1. Each frame is then compared +//| against a reference frame ``lag_frames`` refreshes back, kept in the RAM that +//| ``write_previous_ram_command`` writes, and only pixels that differ are driven. The +//| ``start_sequence`` must load a LUT with a short period that nudges a pixel one step toward +//| its current value when the two RAMs differ and doesn't drive it when they match. The LUT period sets the refresh rate: shorter is faster. +//| ``lag_frames`` sets how many nudges each change gets. For example, with ``lag_frames`` = 5, +//| a white pixel that changes to black is driven toward black for 5 refreshes, until the change +//| reaches the reference frame. +//| +//| ``lag_frames`` > 0 stores that many frames, ``lag_frames * width * height / 8`` bytes outside +//| the VM heap, until the display is released. Each refresh sends the current frame and the +//| reference frame, but only inside the union of the stored frames' dirty boxes. ``refresh()`` +//| returns as soon as the update starts, so poll ``busy`` before the next one. If the image stops +//| changing, call ``refresh()`` ``lag_frames`` more times to finish the drive. The display is +//| reset and sent the ``start_sequence`` only before the first refresh, and the ``stop_sequence`` +//| when it is released. +//| +//| Fast updates need ``write_previous_ram_command``, ``busy_pin``, ``clean_sequence``, a non-empty +//| ``stop_sequence``, the window commands and a monochrome display. Not available on boards +//| without fast e-paper support. +//| +//| .. warning:: ``lag_frames`` and ``write_previous_ram_command`` allow updates much faster than panel makers' +//| limits on refresh rate. Fast updates need a balanced waveform, and long-term wear on the panel +//| is unknown. +//| //| :param display_bus: The bus that the display is connected to //| :type _DisplayBus: fourwire.FourWire or paralleldisplaybus.ParallelBus //| :param ~circuitpython_typing.ReadableBuffer start_sequence: Byte-packed command sequence. @@ -95,7 +128,15 @@ //| :param bool black_bits_inverted: True if 0 bits are used to show black pixels. Otherwise, 1 means to show black. //| :param int write_color_ram_command: Command used to write pixels values into the update region //| :param bool color_bits_inverted: True if 0 bits are used to show the color. Otherwise, 1 means to show color. +//| :param int write_previous_ram_command: Command used to write the same pixel values again after each refresh, +//| into the RAM the LUT pairs with the black RAM, such as the SSD1680 RAM 0x26. The LUT decides what each pair +//| of bits does. It must treat this RAM as the previous image. +//| When set, ``refresh()`` waits for the display to finish updating before it returns. +//| Requires a non-empty ``stop_sequence``. +//| Leave ``write_color_ram_command`` as None when it writes the same RAM, or it will overwrite the previous image. +//| Not accepted on boards without fast e-paper support. //| :param int highlight_color: RGB888 of source color to highlight with third ePaper color. +//| :param int highlight_color2: RGB888 of source color to highlight with fourth ePaper color. //| :param int refresh_display_command: Command used to start a display refresh. Single int or byte-packed command sequence //| :param float refresh_time: Time it takes to refresh the display before the stop_sequence should be sent. Ignored when busy_pin is provided. //| :param microcontroller.Pin busy_pin: Pin used to signify the display is busy @@ -104,9 +145,17 @@ //| :param bool always_toggle_chip_select: When True, chip select is toggled every byte //| :param bool grayscale: When true, the color ram is the low bit of 2-bit grayscale //| :param bool advanced_color_epaper: When true, the display is a 7-color advanced color epaper (ACeP) +//| :param bool spectra6: When true, the display is a 6-color spectra6 epaper //| :param bool two_byte_sequence_length: When true, use two bytes to define sequence length //| :param float start_up_time: Time to wait after reset before sending commands //| :param bool address_little_endian: Send the least significant byte (not bit) of multi-byte addresses first. Ignored when ram is addressed with one byte +//| :param int lag_frames: How many refreshes back the reference frame is, 0 to 32. 0, the +//| default, turns fast updates off. More gives darker motion with more smear and uses more memory. +//| :param ~circuitpython_typing.ReadableBuffer clean_sequence: Byte-packed commands for a full refresh, such as +//| one using the waveform stored in the display, for use when both RAM planes are white. It runs before the +//| first fast update. When the display is released or the code stops, the display finishes +//| its drive, goes white and runs this and the ``stop_sequence``. Display drivers should provide it. +//| It is only used with fast updates. //| """ //| ... //| @@ -115,10 +164,14 @@ static mp_obj_t epaperdisplay_epaperdisplay_make_new(const mp_obj_type_t *type, ARG_ram_width, ARG_ram_height, ARG_colstart, ARG_rowstart, ARG_rotation, ARG_set_column_window_command, ARG_set_row_window_command, ARG_set_current_column_command, ARG_set_current_row_command, ARG_write_black_ram_command, ARG_black_bits_inverted, - ARG_write_color_ram_command, ARG_color_bits_inverted, ARG_highlight_color, + ARG_write_color_ram_command, ARG_color_bits_inverted, ARG_highlight_color, ARG_highlight_color2, ARG_refresh_display_command, ARG_refresh_time, ARG_busy_pin, ARG_busy_state, - ARG_seconds_per_frame, ARG_always_toggle_chip_select, ARG_grayscale, ARG_advanced_color_epaper, - ARG_two_byte_sequence_length, ARG_start_up_time, ARG_address_little_endian }; + ARG_seconds_per_frame, ARG_always_toggle_chip_select, ARG_grayscale, ARG_advanced_color_epaper, ARG_spectra6, + ARG_two_byte_sequence_length, ARG_start_up_time, ARG_address_little_endian, + #if CIRCUITPY_EPAPERDISPLAY_FAST + ARG_write_previous_ram_command, ARG_lag_frames, ARG_clean_sequence, + #endif + }; static const mp_arg_t allowed_args[] = { { MP_QSTR_display_bus, MP_ARG_REQUIRED | MP_ARG_OBJ }, { MP_QSTR_start_sequence, MP_ARG_REQUIRED | MP_ARG_OBJ }, @@ -139,6 +192,7 @@ static mp_obj_t epaperdisplay_epaperdisplay_make_new(const mp_obj_type_t *type, { MP_QSTR_write_color_ram_command, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = mp_const_none} }, { MP_QSTR_color_bits_inverted, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = false} }, { MP_QSTR_highlight_color, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0x000000} }, + { MP_QSTR_highlight_color2, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0x000000} }, { MP_QSTR_refresh_display_command, MP_ARG_OBJ | MP_ARG_REQUIRED }, { MP_QSTR_refresh_time, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_OBJ_NEW_SMALL_INT(40)} }, { MP_QSTR_busy_pin, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = mp_const_none} }, @@ -147,9 +201,15 @@ static mp_obj_t epaperdisplay_epaperdisplay_make_new(const mp_obj_type_t *type, { MP_QSTR_always_toggle_chip_select, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = false} }, { MP_QSTR_grayscale, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = false} }, { MP_QSTR_advanced_color_epaper, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = false} }, + { MP_QSTR_spectra6, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = false} }, { MP_QSTR_two_byte_sequence_length, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = false} }, { MP_QSTR_start_up_time, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_OBJ_NEW_SMALL_INT(0)} }, { MP_QSTR_address_little_endian, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = false} }, + #if CIRCUITPY_EPAPERDISPLAY_FAST + { MP_QSTR_write_previous_ram_command, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = mp_const_none} }, + { MP_QSTR_lag_frames, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0} }, + { MP_QSTR_clean_sequence, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = mp_const_none} }, + #endif }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); @@ -160,6 +220,16 @@ static mp_obj_t epaperdisplay_epaperdisplay_make_new(const mp_obj_type_t *type, mp_get_buffer_raise(args[ARG_start_sequence].u_obj, &start_bufinfo, MP_BUFFER_READ); mp_buffer_info_t stop_bufinfo; mp_get_buffer_raise(args[ARG_stop_sequence].u_obj, &stop_bufinfo, MP_BUFFER_READ); + #if CIRCUITPY_EPAPERDISPLAY_FAST + mp_int_t lag_frames = mp_arg_validate_int_range(args[ARG_lag_frames].u_int, 0, 32, MP_QSTR_lag_frames); + bool fast = lag_frames > 0; + // A reset can follow these displays' last RAM write, and SSD168x controllers only commit the + // last byte when another command arrives. + if (stop_bufinfo.len == 0 && + (fast || args[ARG_write_previous_ram_command].u_obj != mp_const_none)) { + mp_arg_error_invalid(MP_QSTR_stop_sequence); + } + #endif const mcu_pin_obj_t *busy_pin = validate_obj_is_free_pin_or_none(args[ARG_busy_pin].u_obj, MP_QSTR_busy_pin); @@ -169,6 +239,35 @@ static mp_obj_t epaperdisplay_epaperdisplay_make_new(const mp_obj_type_t *type, mp_raise_ValueError(MP_ERROR_TEXT("Display rotation must be in 90 degree increments")); } + #if CIRCUITPY_EPAPERDISPLAY_FAST + if (fast) { + // Each one a driver can leave out by mistake names itself. The rest are the display type. + qstr missing = MP_QSTRnull; + if (args[ARG_busy_pin].u_obj == mp_const_none) { + missing = MP_QSTR_busy_pin; + } else if (args[ARG_clean_sequence].u_obj == mp_const_none) { + missing = MP_QSTR_clean_sequence; + } else if (args[ARG_write_previous_ram_command].u_obj == mp_const_none) { + missing = MP_QSTR_write_previous_ram_command; + } else if (args[ARG_set_column_window_command].u_int == NO_COMMAND) { + missing = MP_QSTR_set_column_window_command; + } else if (args[ARG_set_row_window_command].u_int == NO_COMMAND) { + missing = MP_QSTR_set_row_window_command; + } else if (args[ARG_write_color_ram_command].u_obj != mp_const_none || + args[ARG_highlight_color].u_int != 0 || args[ARG_highlight_color2].u_int != 0 || + args[ARG_grayscale].u_bool || args[ARG_advanced_color_epaper].u_bool || + args[ARG_spectra6].u_bool) { + missing = MP_QSTR_lag_frames; + } + if (missing != MP_QSTRnull) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("Invalid %q"), missing); + } + } + #endif // CIRCUITPY_EPAPERDISPLAY_FAST + + // Check the bus before taking a display slot: construct would raise after the slot is in use. + displayio_display_bus_validate(display_bus); + primary_display_t *disp = allocate_display_or_raise(); epaperdisplay_epaperdisplay_obj_t *self = &disp->epaper_display; @@ -178,9 +277,16 @@ static mp_obj_t epaperdisplay_epaperdisplay_make_new(const mp_obj_type_t *type, mp_int_t write_color_ram_command = NO_COMMAND; mp_int_t highlight_color = args[ARG_highlight_color].u_int; + mp_int_t highlight_color2 = args[ARG_highlight_color2].u_int; if (args[ARG_write_color_ram_command].u_obj != mp_const_none) { write_color_ram_command = mp_obj_get_int(args[ARG_write_color_ram_command].u_obj); } + #if CIRCUITPY_EPAPERDISPLAY_FAST + mp_int_t write_previous_ram_command = NO_COMMAND; + if (args[ARG_write_previous_ram_command].u_obj != mp_const_none) { + write_previous_ram_command = mp_obj_get_int(args[ARG_write_previous_ram_command].u_obj); + } + #endif bool two_byte_sequence_length = args[ARG_two_byte_sequence_length].u_bool; @@ -190,7 +296,7 @@ static mp_obj_t epaperdisplay_epaperdisplay_make_new(const mp_obj_type_t *type, size_t refresh_buf_len = 0; mp_int_t refresh_command; if (mp_obj_get_int_maybe(refresh_obj, &refresh_command)) { - uint8_t *command_buf = m_malloc(3); + uint8_t *command_buf = m_malloc_without_collect(3); command_buf[0] = refresh_command; command_buf[1] = 0; command_buf[2] = 0; @@ -204,30 +310,98 @@ static mp_obj_t epaperdisplay_epaperdisplay_make_new(const mp_obj_type_t *type, } self->base.type = &epaperdisplay_epaperdisplay_type; - common_hal_epaperdisplay_epaperdisplay_construct( - self, - display_bus, - start_bufinfo.buf, start_bufinfo.len, start_up_time, stop_bufinfo.buf, stop_bufinfo.len, - args[ARG_width].u_int, args[ARG_height].u_int, args[ARG_ram_width].u_int, args[ARG_ram_height].u_int, - args[ARG_colstart].u_int, args[ARG_rowstart].u_int, rotation, - args[ARG_set_column_window_command].u_int, args[ARG_set_row_window_command].u_int, - args[ARG_set_current_column_command].u_int, args[ARG_set_current_row_command].u_int, - args[ARG_write_black_ram_command].u_int, args[ARG_black_bits_inverted].u_bool, write_color_ram_command, - args[ARG_color_bits_inverted].u_bool, highlight_color, refresh_buf, refresh_buf_len, refresh_time, - busy_pin, args[ARG_busy_state].u_bool, seconds_per_frame, - args[ARG_always_toggle_chip_select].u_bool, args[ARG_grayscale].u_bool, args[ARG_advanced_color_epaper].u_bool, - two_byte_sequence_length, args[ARG_address_little_endian].u_bool - ); + epaperdisplay_construct_args_t construct_args = EPAPERDISPLAY_CONSTRUCT_ARGS_DEFAULTS; + construct_args.bus = display_bus; + construct_args.start_sequence = start_bufinfo.buf; + construct_args.start_sequence_len = start_bufinfo.len; + construct_args.start_up_time = start_up_time; + construct_args.stop_sequence = stop_bufinfo.buf; + construct_args.stop_sequence_len = stop_bufinfo.len; + construct_args.width = args[ARG_width].u_int; + construct_args.height = args[ARG_height].u_int; + construct_args.ram_width = args[ARG_ram_width].u_int; + construct_args.ram_height = args[ARG_ram_height].u_int; + construct_args.colstart = args[ARG_colstart].u_int; + construct_args.rowstart = args[ARG_rowstart].u_int; + construct_args.rotation = rotation; + construct_args.set_column_window_command = args[ARG_set_column_window_command].u_int; + construct_args.set_row_window_command = args[ARG_set_row_window_command].u_int; + construct_args.set_current_column_command = args[ARG_set_current_column_command].u_int; + construct_args.set_current_row_command = args[ARG_set_current_row_command].u_int; + construct_args.write_black_ram_command = args[ARG_write_black_ram_command].u_int; + construct_args.black_bits_inverted = args[ARG_black_bits_inverted].u_bool; + construct_args.write_color_ram_command = write_color_ram_command; + construct_args.color_bits_inverted = args[ARG_color_bits_inverted].u_bool; + #if CIRCUITPY_EPAPERDISPLAY_FAST + construct_args.write_previous_ram_command = write_previous_ram_command; + #endif + construct_args.highlight_color = highlight_color; + construct_args.highlight_color2 = highlight_color2; + construct_args.refresh_sequence = refresh_buf; + construct_args.refresh_sequence_len = refresh_buf_len; + construct_args.refresh_time = refresh_time; + construct_args.busy_pin = busy_pin; + construct_args.busy_state = args[ARG_busy_state].u_bool; + construct_args.seconds_per_frame = seconds_per_frame; + construct_args.always_toggle_chip_select = args[ARG_always_toggle_chip_select].u_bool; + construct_args.grayscale = args[ARG_grayscale].u_bool; + construct_args.acep = args[ARG_advanced_color_epaper].u_bool; + construct_args.spectra6 = args[ARG_spectra6].u_bool; + construct_args.two_byte_sequence_length = two_byte_sequence_length; + construct_args.address_little_endian = args[ARG_address_little_endian].u_bool; + #if CIRCUITPY_EPAPERDISPLAY_FAST + construct_args.fast = fast; + construct_args.lag_frames = lag_frames; + if (args[ARG_clean_sequence].u_obj != mp_const_none) { + mp_buffer_info_t clean_bufinfo; + mp_get_buffer_raise(args[ARG_clean_sequence].u_obj, &clean_bufinfo, MP_BUFFER_READ); + construct_args.clean_sequence = clean_bufinfo.buf; + construct_args.clean_sequence_len = clean_bufinfo.len; + } + #endif + common_hal_epaperdisplay_epaperdisplay_construct(self, &construct_args); return self; } // Helper to ensure we have the native super class instead of a subclass. +// Raises if the display has been released. static epaperdisplay_epaperdisplay_obj_t *native_display(mp_obj_t display_obj) { mp_obj_t native_display = mp_obj_cast_to_native_base(display_obj, &epaperdisplay_epaperdisplay_type); + if (native_display == MP_OBJ_NULL) { + raise_deinited_error(); + } mp_obj_assert_native_inited(native_display); - return MP_OBJ_TO_PTR(native_display); + epaperdisplay_epaperdisplay_obj_t *self = MP_OBJ_TO_PTR(native_display); + if (self->base.type != &epaperdisplay_epaperdisplay_type) { + raise_deinited_error(); + } + return self; +} + +//| def deinit(self) -> None: +//| """Release the display and its display bus, so their pins can be used again. +//| The display bus is not released if another display still uses it. +//| A `busio.SPI` or `busio.I2C` object that you passed to the display bus is not deinitialized. +//| +//| If a refresh is in progress, this waits for it to finish, which may take seconds. +//| If the display uses ``lag_frames`` and can't get its bus, this waits up to 30 seconds. +//| It then raises `RuntimeError` and leaves the display as it was. +//| +//| To release a built-in display, or a display kept from an earlier run, +//| use ``supervisor.runtime.display.deinit()``. +//| As of CircuitPython 11.0.0, this replaces `displayio.release_displays()`, which is deprecated. +//| """ +//| ... +//| +static mp_obj_t epaperdisplay_epaperdisplay_obj_deinit(mp_obj_t self_in) { + mp_obj_t native_display = mp_obj_cast_to_native_base(self_in, &epaperdisplay_epaperdisplay_type); + if (native_display != MP_OBJ_NULL) { + common_hal_displayio_deinit_display(native_display); + } + return mp_const_none; } +MP_DEFINE_CONST_FUN_OBJ_1(epaperdisplay_epaperdisplay_deinit_obj, epaperdisplay_epaperdisplay_obj_deinit); // Undocumented show() implementation with a friendly error message. static mp_obj_t epaperdisplay_epaperdisplay_obj_show(mp_obj_t self_in, mp_obj_t group_in) { @@ -237,16 +411,38 @@ static mp_obj_t epaperdisplay_epaperdisplay_obj_show(mp_obj_t self_in, mp_obj_t MP_DEFINE_CONST_FUN_OBJ_2(epaperdisplay_epaperdisplay_show_obj, epaperdisplay_epaperdisplay_obj_show); //| def update_refresh_mode( -//| self, start_sequence: ReadableBuffer, seconds_per_frame: float = 180 +//| self, +//| start_sequence: ReadableBuffer, +//| seconds_per_frame: float = 180, +//| *, +//| refresh_sequence: Optional[ReadableBuffer] = None, //| ) -> None: //| """Updates the ``start_sequence`` and ``seconds_per_frame`` parameters to enable -//| varying the refresh mode of the display.""" +//| varying the refresh mode of the display. With fast updates (``lag_frames`` > 0), the display is +//| reset and sent the new ``start_sequence`` before the next refresh. +//| +//| :param ReadableBuffer start_sequence: Byte sequence sent to initialize the display before each refresh. +//| :param float seconds_per_frame: Minimum number of seconds between refreshes. +//| :param ReadableBuffer refresh_sequence: Byte sequence sent to start a refresh. +//| Pass it when switching between the stored waveform and a fast LUT, since they +//| start a refresh differently. On the SSD1683, a fast LUT in RAM needs ``0x22 0x0C`` +//| before ``0x20``, and the stored waveform needs only ``0x20``. +//| It uses the same format as ``start_sequence``. +//| When it is None, the current refresh sequence is kept. Not accepted on boards +//| without fast e-paper support.""" //| static mp_obj_t epaperdisplay_epaperdisplay_update_refresh_mode(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - enum { ARG_start_sequence, ARG_seconds_per_frame }; + enum { ARG_start_sequence, ARG_seconds_per_frame, + #if CIRCUITPY_EPAPERDISPLAY_FAST + ARG_refresh_sequence, + #endif + }; static const mp_arg_t allowed_args[] = { { MP_QSTR_start_sequence, MP_ARG_REQUIRED | MP_ARG_OBJ }, { MP_QSTR_seconds_per_frame, MP_ARG_OBJ, {.u_obj = MP_OBJ_NEW_SMALL_INT(180)} }, + #if CIRCUITPY_EPAPERDISPLAY_FAST + { MP_QSTR_refresh_sequence, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, + #endif }; epaperdisplay_epaperdisplay_obj_t *self = native_display(pos_args[0]); mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; @@ -257,27 +453,88 @@ static mp_obj_t epaperdisplay_epaperdisplay_update_refresh_mode(size_t n_args, c mp_get_buffer_raise(args[ARG_start_sequence].u_obj, &start_sequence, MP_BUFFER_READ); float seconds_per_frame = mp_obj_get_float(args[ARG_seconds_per_frame].u_obj); + mp_buffer_info_t *refresh_sequence_ptr = NULL; + #if CIRCUITPY_EPAPERDISPLAY_FAST + mp_buffer_info_t refresh_sequence; + if (args[ARG_refresh_sequence].u_obj != mp_const_none) { + mp_get_buffer_raise(args[ARG_refresh_sequence].u_obj, &refresh_sequence, MP_BUFFER_READ); + refresh_sequence_ptr = &refresh_sequence; + } + #endif + // Update parameters - epaperdisplay_epaperdisplay_change_refresh_mode_parameters(self, &start_sequence, seconds_per_frame); + epaperdisplay_epaperdisplay_change_refresh_mode_parameters(self, &start_sequence, refresh_sequence_ptr, seconds_per_frame); return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_KW(epaperdisplay_epaperdisplay_update_refresh_mode_obj, 1, epaperdisplay_epaperdisplay_update_refresh_mode); //| def refresh(self) -> None: //| """Refreshes the display immediately or raises an exception if too soon. Use -//| ``time.sleep(display.time_to_refresh)`` to sleep until a refresh can occur.""" +//| ``time.sleep(display.time_to_refresh)`` to sleep until a refresh can occur. +//| +//| This returns when the update starts, not when it finishes. Before removing power from +//| the display, wait until ``busy`` is False. If the display has a ``busy_pin``, +//| `alarm.exit_and_deep_sleep_until_alarms()` waits for the update to finish by itself. +//| +//| The minimum time between refreshes is ``seconds_per_frame``, 180 by default. With +//| fast updates, set it to 0 and poll ``busy`` instead. The first refresh also runs the +//| ``clean_sequence``, which takes seconds, and an interrupt during it raises when it +//| ends.""" //| ... //| static mp_obj_t epaperdisplay_epaperdisplay_obj_refresh(mp_obj_t self_in) { epaperdisplay_epaperdisplay_obj_t *self = native_display(self_in); bool ok = common_hal_epaperdisplay_epaperdisplay_refresh(self); if (!ok) { + #if CIRCUITPY_EPAPERDISPLAY_FAST + if (common_hal_epaperdisplay_epaperdisplay_has_lag_frames(self)) { + // Interrupted is not too soon: raise what interrupted it. + mp_handle_pending(true); + } + #endif mp_raise_RuntimeError(MP_ERROR_TEXT("Refresh too soon")); } return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_1(epaperdisplay_epaperdisplay_refresh_obj, epaperdisplay_epaperdisplay_obj_refresh); +#if CIRCUITPY_EPAPERDISPLAY_FAST +//| def clean(self, frames: int = 8, *, full: bool = False) -> None: +//| """Remove ghosting from a display using fast updates, with balanced drive. Not available +//| on boards without fast e-paper support. +//| +//| All pixels go to white for ``lag_frames`` frames to get to a white steady state. If ``full`` is True, +//| the ``clean_sequence`` is sent, followed by the ``start_sequence``. Then every pixel is +//| driven ``frames`` updates toward black and ``frames`` updates toward white. This blocks, +//| but a playing video keeps decoding. The next ``refresh()`` draws everything again. +//| +//| :param int frames: Updates in each direction. 0 skips the wipe. +//| :param bool full: Also do a full refresh with ``clean_sequence``.""" +//| ... +//| +static mp_obj_t epaperdisplay_epaperdisplay_clean(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_frames, ARG_full }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_frames, MP_ARG_INT, {.u_int = 8} }, + { MP_QSTR_full, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, + }; + epaperdisplay_epaperdisplay_obj_t *self = native_display(pos_args[0]); + 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); + if (!common_hal_epaperdisplay_epaperdisplay_has_lag_frames(self)) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Invalid state")); + } + mp_int_t frames = mp_arg_validate_int_range(args[ARG_frames].u_int, 0, 255, MP_QSTR_frames); + if (!common_hal_epaperdisplay_epaperdisplay_clean(self, frames, args[ARG_full].u_bool)) { + // Interrupted is not too soon: raise what interrupted it. + mp_handle_pending(true); + mp_raise_RuntimeError(MP_ERROR_TEXT("Refresh too soon")); + } + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_KW(epaperdisplay_epaperdisplay_clean_obj, 1, epaperdisplay_epaperdisplay_clean); +#endif // CIRCUITPY_EPAPERDISPLAY_FAST + //| time_to_refresh: float //| """Time, in fractional seconds, until the ePaper display can be refreshed.""" static mp_obj_t epaperdisplay_epaperdisplay_obj_get_time_to_refresh(mp_obj_t self_in) { @@ -296,7 +553,8 @@ MP_PROPERTY_GETTER(epaperdisplay_epaperdisplay_time_to_refresh_obj, //| busy: bool //| """True when the display is refreshing. This uses the ``busy_pin`` when available or the -//| ``refresh_time`` otherwise.""" +//| ``refresh_time`` otherwise. With fast updates, a panel still busy after 30 seconds is +//| given up on, so this goes False and the next ``refresh()`` resets the panel and cleans it.""" static mp_obj_t epaperdisplay_epaperdisplay_obj_get_busy(mp_obj_t self_in) { epaperdisplay_epaperdisplay_obj_t *self = native_display(self_in); return mp_obj_new_bool(common_hal_epaperdisplay_epaperdisplay_get_busy(self)); @@ -389,9 +647,13 @@ MP_PROPERTY_GETSET(epaperdisplay_epaperdisplay_root_group_obj, (mp_obj_t)&epaperdisplay_epaperdisplay_set_root_group_obj); static const mp_rom_map_elem_t epaperdisplay_epaperdisplay_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&epaperdisplay_epaperdisplay_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR_show), MP_ROM_PTR(&epaperdisplay_epaperdisplay_show_obj) }, { MP_ROM_QSTR(MP_QSTR_update_refresh_mode), MP_ROM_PTR(&epaperdisplay_epaperdisplay_update_refresh_mode_obj) }, { MP_ROM_QSTR(MP_QSTR_refresh), MP_ROM_PTR(&epaperdisplay_epaperdisplay_refresh_obj) }, + #if CIRCUITPY_EPAPERDISPLAY_FAST + { MP_ROM_QSTR(MP_QSTR_clean), MP_ROM_PTR(&epaperdisplay_epaperdisplay_clean_obj) }, + #endif { MP_ROM_QSTR(MP_QSTR_width), MP_ROM_PTR(&epaperdisplay_epaperdisplay_width_obj) }, { MP_ROM_QSTR(MP_QSTR_height), MP_ROM_PTR(&epaperdisplay_epaperdisplay_height_obj) }, diff --git a/shared-bindings/epaperdisplay/EPaperDisplay.h b/shared-bindings/epaperdisplay/EPaperDisplay.h index d4475e0a6aa..21359ee4bc8 100644 --- a/shared-bindings/epaperdisplay/EPaperDisplay.h +++ b/shared-bindings/epaperdisplay/EPaperDisplay.h @@ -15,22 +15,108 @@ extern const mp_obj_type_t epaperdisplay_epaperdisplay_type; #define NO_COMMAND 0x100 +typedef struct epaperdisplay_construct_args_t { + mp_obj_t bus; + const uint8_t *start_sequence; + uint16_t start_sequence_len; + mp_float_t start_up_time; + 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; + uint16_t write_previous_ram_command; + uint32_t highlight_color; + uint32_t highlight_color2; + const uint8_t *refresh_sequence; + uint16_t refresh_sequence_len; + 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 acep; + bool spectra6; + bool two_byte_sequence_length; + bool address_little_endian; + bool fast; + uint8_t lag_frames; + const uint8_t *clean_sequence; + uint32_t clean_sequence_len; +} epaperdisplay_construct_args_t; + +#define EPAPERDISPLAY_CONSTRUCT_ARGS_DEFAULTS { \ + .bus = mp_const_none, \ + .start_sequence = NULL, \ + .start_sequence_len = 0, \ + .start_up_time = 0.0, \ + .stop_sequence = NULL, \ + .stop_sequence_len = 0, \ + .width = 0, \ + .height = 0, \ + .ram_width = 0, \ + .ram_height = 0, \ + .colstart = 0, \ + .rowstart = 0, \ + .rotation = 0, \ + .set_column_window_command = NO_COMMAND, \ + .set_row_window_command = NO_COMMAND, \ + .set_current_column_command = NO_COMMAND, \ + .set_current_row_command = NO_COMMAND, \ + .write_black_ram_command = NO_COMMAND, \ + .black_bits_inverted = false, \ + .write_color_ram_command = NO_COMMAND, \ + .color_bits_inverted = false, \ + .write_previous_ram_command = NO_COMMAND, \ + .highlight_color = 0x000000, \ + .highlight_color2 = 0x000000, \ + .refresh_sequence = NULL, \ + .refresh_sequence_len = 0, \ + .refresh_time = 0.0, \ + .busy_pin = NULL, \ + .busy_state = false, \ + .seconds_per_frame = 0.0, \ + .always_toggle_chip_select = false, \ + .grayscale = false, \ + .acep = false, \ + .spectra6 = false, \ + .two_byte_sequence_length = false, \ + .address_little_endian = false, \ + .fast = false, \ + .lag_frames = 0, \ + .clean_sequence = NULL, \ + .clean_sequence_len = 0 \ +} + void common_hal_epaperdisplay_epaperdisplay_construct(epaperdisplay_epaperdisplay_obj_t *self, - mp_obj_t bus, const uint8_t *start_sequence, uint16_t start_sequence_len, mp_float_t start_up_time, - 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, - const uint8_t *refresh_sequence, uint16_t refresh_sequence_len, 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 acep, bool two_byte_sequence_length, - bool address_little_endian); + const epaperdisplay_construct_args_t *args); bool common_hal_epaperdisplay_epaperdisplay_refresh(epaperdisplay_epaperdisplay_obj_t *self); +#if CIRCUITPY_EPAPERDISPLAY_FAST +// Lag drive only. Brings every pixel to white with balanced drive. When full, sends the clean +// sequence and the start sequence. Then wipes each pixel frames toward black and frames toward +// white. Blocks with background tasks running. The next refresh redraws the whole display. +// Doesn't allocate. Holds any interrupt until it ends. Returns false, with any owed drive still +// owed, if the bus can't be had. +bool common_hal_epaperdisplay_epaperdisplay_clean(epaperdisplay_epaperdisplay_obj_t *self, uint8_t frames, bool full); +// True when lag driving is configured for the display. +bool common_hal_epaperdisplay_epaperdisplay_has_lag_frames(epaperdisplay_epaperdisplay_obj_t *self); +#endif + mp_obj_t common_hal_epaperdisplay_epaperdisplay_get_root_group(epaperdisplay_epaperdisplay_obj_t *self); bool common_hal_epaperdisplay_epaperdisplay_set_root_group(epaperdisplay_epaperdisplay_obj_t *self, displayio_group_t *root_group); diff --git a/shared-bindings/floppyio/__init__.c b/shared-bindings/floppyio/__init__.c index 09034b4675d..f32a0759953 100644 --- a/shared-bindings/floppyio/__init__.c +++ b/shared-bindings/floppyio/__init__.c @@ -147,10 +147,10 @@ static mp_obj_t floppyio_mfm_readinto(size_t n_args, const mp_obj_t *pos_args, m mp_buffer_info_t bufinfo_validity; uint8_t validity_buf[n_sectors]; if (args[ARG_validity].u_obj) { - mp_get_buffer_raise(args[ARG_validity].u_obj, &bufinfo_validity, MP_BUFFER_READ); + mp_get_buffer_raise(args[ARG_validity].u_obj, &bufinfo_validity, MP_BUFFER_WRITE); mp_arg_validate_length_min(bufinfo_validity.len, n_sectors, MP_QSTR_validity); if (args[ARG_clear_validity].u_bool) { - memset(validity_buf, 0, sizeof(validity_buf)); + memset(bufinfo_validity.buf, 0, n_sectors); } } else { bufinfo_validity.buf = &validity_buf; diff --git a/shared-bindings/fourwire/FourWire.c b/shared-bindings/fourwire/FourWire.c index 083cf21a003..e77947c4550 100644 --- a/shared-bindings/fourwire/FourWire.c +++ b/shared-bindings/fourwire/FourWire.c @@ -30,19 +30,20 @@ //| self, //| spi_bus: busio.SPI, //| *, -//| command: Optional[microcontroller.Pin], -//| chip_select: Optional[microcontroller.Pin], -//| reset: Optional[microcontroller.Pin] = None, +//| command: Optional[Union[microcontroller.Pin, digitalio.DigitalInOutProtocol]] = None, +//| chip_select: Optional[Union[microcontroller.Pin, digitalio.DigitalInOutProtocol]] = None, +//| reset: Optional[Union[microcontroller.Pin, digitalio.DigitalInOutProtocol]] = None, //| baudrate: int = 24000000, //| polarity: int = 0, //| phase: int = 0, //| ) -> None: //| """Create a FourWire object associated with the given pins. //| -//| 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. +//| The SPI bus and pins are then in use by the display until your code finishes or +//| the display's ``deinit()`` is called. If the display is +//| `supervisor.runtime.display `, they stay in use after your code finishes, so CircuitPython can +//| use the display. In that case, check `supervisor.runtime.display ` before creating the display +//| again, or call ``supervisor.runtime.display.deinit()`` first. //| //| If the ``command`` pin is not specified, a 9-bit SPI mode will be simulated by adding a //| data/command bit to every bit being transmitted, and splitting the resulting data back @@ -73,20 +74,17 @@ static mp_obj_t fourwire_fourwire_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_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); - const mcu_pin_obj_t *command = validate_obj_is_free_pin_or_none(args[ARG_command].u_obj, MP_QSTR_command); - const mcu_pin_obj_t *chip_select = validate_obj_is_free_pin_or_none(args[ARG_chip_select].u_obj, MP_QSTR_chip_select); - const mcu_pin_obj_t *reset = validate_obj_is_free_pin_or_none(args[ARG_reset].u_obj, MP_QSTR_reset); - mp_obj_t spi = mp_arg_validate_type(args[ARG_spi_bus].u_obj, &busio_spi_type, MP_QSTR_spi_bus); - fourwire_fourwire_obj_t *self = &allocate_display_bus_or_raise()->fourwire_bus; - self->base.type = &fourwire_fourwire_type; - uint8_t polarity = (uint8_t)mp_arg_validate_int_range(args[ARG_polarity].u_int, 0, 1, MP_QSTR_polarity); uint8_t phase = (uint8_t)mp_arg_validate_int_range(args[ARG_phase].u_int, 0, 1, MP_QSTR_phase); + // Validate everything before taking a display bus slot. + fourwire_fourwire_obj_t *self = &allocate_display_bus_or_raise()->fourwire_bus; + self->base.type = &fourwire_fourwire_type; + common_hal_fourwire_fourwire_construct(self, - MP_OBJ_TO_PTR(spi), command, chip_select, reset, args[ARG_baudrate].u_int, polarity, phase); + MP_OBJ_TO_PTR(spi), args[ARG_command].u_obj, args[ARG_chip_select].u_obj, args[ARG_reset].u_obj, args[ARG_baudrate].u_int, polarity, phase); return self; } diff --git a/shared-bindings/fourwire/FourWire.h b/shared-bindings/fourwire/FourWire.h index 515a466b4b9..bbb407de027 100644 --- a/shared-bindings/fourwire/FourWire.h +++ b/shared-bindings/fourwire/FourWire.h @@ -16,8 +16,8 @@ extern const mp_obj_type_t fourwire_fourwire_type; void common_hal_fourwire_fourwire_construct(fourwire_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, + busio_spi_obj_t *spi, mp_obj_t command, + mp_obj_t chip_select, mp_obj_t reset, uint32_t baudrate, uint8_t polarity, uint8_t phase); void common_hal_fourwire_fourwire_deinit(fourwire_fourwire_obj_t *self); @@ -32,6 +32,12 @@ void common_hal_fourwire_fourwire_send(mp_obj_t self, display_byte_type_t byte_t void common_hal_fourwire_fourwire_end_transaction(mp_obj_t self); +#if CIRCUITPY_BUSIO_SPI_ASYNC +void common_hal_fourwire_fourwire_send_async(mp_obj_t self, display_byte_type_t byte_type, + display_chip_select_behavior_t chip_select, const uint8_t *data, uint32_t data_length); +void common_hal_fourwire_fourwire_flush(mp_obj_t self); +#endif + // The FourWire object always lives off the MP heap. So, code must collect any pointers // back to the MP heap manually. Otherwise they'll get freed. void common_hal_fourwire_fourwire_collect_ptrs(mp_obj_t obj); diff --git a/shared-bindings/framebufferio/FramebufferDisplay.c b/shared-bindings/framebufferio/FramebufferDisplay.c index 71ce18a1b4b..888e57d5a27 100644 --- a/shared-bindings/framebufferio/FramebufferDisplay.c +++ b/shared-bindings/framebufferio/FramebufferDisplay.c @@ -13,18 +13,24 @@ #include "py/binary.h" #include "py/objproperty.h" #include "py/objtype.h" +#include "py/proto.h" #include "py/runtime.h" +#include "shared-bindings/displayio/__init__.h" #include "shared-bindings/displayio/Group.h" #include "shared-bindings/microcontroller/Pin.h" #include "shared-bindings/util.h" +#if CIRCUITPY_VIDEOCORE +#include "shared-module/videocore/__init__.h" +#endif #include "shared-module/displayio/__init__.h" //| class FramebufferDisplay: //| """Manage updating a display with framebuffer in RAM //| //| This initializes a display and connects it into CircuitPython. Unlike other -//| objects in CircuitPython, Display objects live until `displayio.release_displays()` -//| is called. This is done so that CircuitPython can use the display itself.""" +//| objects in CircuitPython, a FramebufferDisplay stays active after your code finishes if it is +//| `supervisor.runtime.display `, so that CircuitPython can use it. Otherwise, it is released +//| when your code finishes.""" //| //| def __init__( //| self, @@ -35,7 +41,9 @@ //| ) -> None: //| """Create a Display object with the given framebuffer (a buffer, array, ulab.array, etc) //| -//| :param ~circuitpython_typing.FrameBuffer framebuffer: The framebuffer that the display is connected to +//| :param ~circuitpython_typing.FrameBuffer framebuffer: The framebuffer that the display is connected to. +//| If it is an instance of a Python subclass of a native framebuffer type, the +//| display uses the native object and does not keep the subclass instance. //| :param bool auto_refresh: Automatically refresh the screen //| :param int rotation: The rotation of the display in degrees clockwise. Must be in 90 degree increments (0, 90, 180, 270) //| """ @@ -53,12 +61,27 @@ static mp_obj_t framebufferio_framebufferdisplay_make_new(const mp_obj_type_t *t mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); mp_obj_t framebuffer = args[ARG_framebuffer].u_obj; + // Use the native object behind a Python subclass. The framebuffer protocol + // functions expect it, and the native object (not the heap instance) is + // what stays alive with the display after the VM ends. + // Instances only inherit the protocol from a native base, so subobj[0] + // exists when the protocol does. + if (mp_obj_is_instance_type(mp_obj_get_type(framebuffer)) && + mp_proto_get(MP_QSTR_protocol_framebuffer, framebuffer) != NULL) { + mp_obj_instance_t *instance = MP_OBJ_TO_PTR(framebuffer); + framebuffer = instance->subobj[0]; + mp_obj_assert_native_inited(framebuffer); + } mp_int_t rotation = args[ARG_rotation].u_int; if (rotation % 90 != 0) { mp_raise_ValueError(MP_ERROR_TEXT("Display rotation must be in 90 degree increments")); } + // Check the framebuffer before taking a display slot: construct would raise after the slot + // is in use. + mp_proto_get_or_throw(MP_QSTR_protocol_framebuffer, framebuffer); + primary_display_t *disp = allocate_display_or_raise(); framebufferio_framebufferdisplay_obj_t *self = &disp->framebuffer_display; self->base.type = &framebufferio_framebufferdisplay_type; @@ -73,11 +96,37 @@ 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. +// Raises if the display has been released. static framebufferio_framebufferdisplay_obj_t *native_display(mp_obj_t display_obj) { mp_obj_t native_display = mp_obj_cast_to_native_base(display_obj, &framebufferio_framebufferdisplay_type); + if (native_display == MP_OBJ_NULL) { + raise_deinited_error(); + } mp_obj_assert_native_inited(native_display); - return MP_OBJ_TO_PTR(native_display); + framebufferio_framebufferdisplay_obj_t *self = MP_OBJ_TO_PTR(native_display); + if (self->base.type != &framebufferio_framebufferdisplay_type) { + raise_deinited_error(); + } + return self; +} + +//| def deinit(self) -> None: +//| """Release the display and deinitialize its framebuffer, so their pins can be used again. +//| +//| To release a built-in display, or a display kept from an earlier run, +//| use ``supervisor.runtime.display.deinit()``. +//| As of CircuitPython 11.0.0, this replaces `displayio.release_displays()`, which is deprecated. +//| """ +//| ... +//| +static mp_obj_t framebufferio_framebufferdisplay_obj_deinit(mp_obj_t self_in) { + mp_obj_t native_display = mp_obj_cast_to_native_base(self_in, &framebufferio_framebufferdisplay_type); + if (native_display != MP_OBJ_NULL) { + common_hal_displayio_deinit_display(native_display); + } + return mp_const_none; } +MP_DEFINE_CONST_FUN_OBJ_1(framebufferio_framebufferdisplay_deinit_obj, framebufferio_framebufferdisplay_obj_deinit); // Undocumented show() implementation with a friendly error message. static mp_obj_t framebufferio_framebufferdisplay_obj_show(mp_obj_t self_in, mp_obj_t group_in) { @@ -265,6 +314,15 @@ static mp_obj_t framebufferio_framebufferdisplay_obj_fill_row(size_t n_args, con mp_int_t y = args[ARG_y].u_int; mp_obj_t *result = args[ARG_buffer].u_obj; + #if CIRCUITPY_DISPLAYIO_LVGL + // LVGL renders into its own draw buffers, so there is no CPU-readable row to + // return. Keep the API available and report that this backend can't do it. + (void)self; + (void)y; + (void)result; + mp_raise_NotImplementedError(MP_ERROR_TEXT("Operation or feature not supported")); + #else + mp_buffer_info_t bufinfo; mp_get_buffer_raise(result, &bufinfo, MP_BUFFER_WRITE); @@ -304,6 +362,7 @@ static mp_obj_t framebufferio_framebufferdisplay_obj_fill_row(size_t n_args, con } else { mp_raise_ValueError(MP_ERROR_TEXT("Buffer too small")); } + #endif } MP_DEFINE_CONST_FUN_OBJ_KW(framebufferio_framebufferdisplay_fill_row_obj, 1, framebufferio_framebufferdisplay_obj_fill_row); @@ -325,6 +384,12 @@ static mp_obj_t framebufferio_framebufferdisplay_obj_set_root_group(mp_obj_t sel displayio_group_t *group = NULL; if (group_in != mp_const_none) { group = MP_OBJ_TO_PTR(native_group(group_in)); + #if CIRCUITPY_VIDEOCORE + // Validate that draw protocol layers (e.g. a VideoBuffer) fit the + // display they will render on. + videocore_validate_root_group(group_in, self_in, + common_hal_framebufferio_framebufferdisplay_get_rotation(self)); + #endif } bool ok = common_hal_framebufferio_framebufferdisplay_set_root_group(self, group); @@ -340,6 +405,7 @@ MP_PROPERTY_GETSET(framebufferio_framebufferdisplay_root_group_obj, (mp_obj_t)&framebufferio_framebufferdisplay_set_root_group_obj); static const mp_rom_map_elem_t framebufferio_framebufferdisplay_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&framebufferio_framebufferdisplay_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR_show), MP_ROM_PTR(&framebufferio_framebufferdisplay_show_obj) }, { MP_ROM_QSTR(MP_QSTR_refresh), MP_ROM_PTR(&framebufferio_framebufferdisplay_refresh_obj) }, { MP_ROM_QSTR(MP_QSTR_fill_row), MP_ROM_PTR(&framebufferio_framebufferdisplay_fill_row_obj) }, diff --git a/shared-bindings/gifio/GifWriter.c b/shared-bindings/gifio/GifWriter.c index f649a9299c0..047916aceb9 100644 --- a/shared-bindings/gifio/GifWriter.c +++ b/shared-bindings/gifio/GifWriter.c @@ -54,7 +54,7 @@ static mp_obj_t gifio_gifwriter_make_new(const mp_obj_type_t *type, size_t n_arg own_file = true; } - gifio_gifwriter_t *self = mp_obj_malloc(gifio_gifwriter_t, &gifio_gifwriter_type); + gifio_gifwriter_t *self = mp_obj_malloc_with_finaliser(gifio_gifwriter_t, &gifio_gifwriter_type); shared_module_gifio_gifwriter_construct( self, file, @@ -138,6 +138,7 @@ static const mp_rom_map_elem_t gifio_gifwriter_locals_table[] = { { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&gifio_gifwriter_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&gifio_gifwriter_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR_add_frame), MP_ROM_PTR(&gifio_gifwriter_add_frame_obj) }, }; diff --git a/shared-bindings/gifio/OnDiskGif.c b/shared-bindings/gifio/OnDiskGif.c index 092d9dd19cf..f13d740e141 100644 --- a/shared-bindings/gifio/OnDiskGif.c +++ b/shared-bindings/gifio/OnDiskGif.c @@ -9,6 +9,7 @@ #include #include "py/runtime.h" +#include "extmod/vfs.h" #include "py/objproperty.h" #include "shared/runtime/context_manager_helpers.h" #include "shared-bindings/util.h" @@ -96,9 +97,8 @@ //| //| If the image is too large it will be cropped at the bottom and right when displayed. //| -//| **Limitations**: The image width is limited to 320 pixels at present. `ValueError` -//| will be raised if the image is too wide. The height -//| is not limited but images that are too large will cause a memory exception. +//| **Limitations**: The width and height are not limited, but images that are too +//| large will cause a memory exception. //| """ //| ... //| @@ -112,17 +112,17 @@ static mp_obj_t gifio_ondiskgif_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_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); - mp_obj_t filename = all_args[0]; + mp_obj_t filename = args[ARG_filename].u_obj; if (mp_obj_is_str(filename)) { filename = mp_call_function_2(MP_OBJ_FROM_PTR(&mp_builtin_open_obj), filename, MP_ROM_QSTR(MP_QSTR_rb)); } - if (!mp_obj_is_type(filename, &mp_type_fileio)) { + if (!mp_obj_is_fileio(filename)) { mp_raise_TypeError(MP_ERROR_TEXT("file must be a file opened in byte mode")); } gifio_ondiskgif_t *self = mp_obj_malloc(gifio_ondiskgif_t, &gifio_ondiskgif_type); - common_hal_gifio_ondiskgif_construct(self, MP_OBJ_TO_PTR(filename), args[ARG_use_palette].u_bool); + common_hal_gifio_ondiskgif_construct(self, filename, args[ARG_use_palette].u_bool); return MP_OBJ_FROM_PTR(self); } diff --git a/shared-bindings/gifio/OnDiskGif.h b/shared-bindings/gifio/OnDiskGif.h index 96e4cf08341..69833145c06 100644 --- a/shared-bindings/gifio/OnDiskGif.h +++ b/shared-bindings/gifio/OnDiskGif.h @@ -7,11 +7,11 @@ #pragma once #include "shared-module/gifio/OnDiskGif.h" -#include "extmod/vfs_fat.h" +#include "extmod/vfs.h" extern const mp_obj_type_t gifio_ondiskgif_type; -void common_hal_gifio_ondiskgif_construct(gifio_ondiskgif_t *self, pyb_file_obj_t *file, bool use_palette); +void common_hal_gifio_ondiskgif_construct(gifio_ondiskgif_t *self, mp_obj_t file, bool use_palette); uint32_t common_hal_gifio_ondiskgif_get_pixel(gifio_ondiskgif_t *bitmap, int16_t x, int16_t y); diff --git a/shared-bindings/gnss/GNSS.c b/shared-bindings/gnss/GNSS.c index 95c3ed975d5..996931b66a9 100644 --- a/shared-bindings/gnss/GNSS.c +++ b/shared-bindings/gnss/GNSS.c @@ -38,7 +38,6 @@ //| ... //| static mp_obj_t gnss_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { - gnss_obj_t *self = mp_obj_malloc(gnss_obj_t, &gnss_type); enum { ARG_system }; static const mp_arg_t allowed_args[] = { { MP_QSTR_system, MP_ARG_REQUIRED | MP_ARG_OBJ }, @@ -63,7 +62,9 @@ static mp_obj_t gnss_make_new(const mp_obj_type_t *type, size_t n_args, size_t n mp_raise_TypeError(MP_ERROR_TEXT("System entry must be gnss.SatelliteSystem")); } + gnss_obj_t *self = mp_obj_malloc_with_finaliser(gnss_obj_t, &gnss_type); common_hal_gnss_construct(self, selection); + return MP_OBJ_FROM_PTR(self); } @@ -163,6 +164,7 @@ MP_PROPERTY_GETTER(gnss_fix_obj, static const mp_rom_map_elem_t gnss_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&gnss_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&gnss_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR_update), MP_ROM_PTR(&gnss_update_obj) }, { MP_ROM_QSTR(MP_QSTR_latitude), MP_ROM_PTR(&gnss_latitude_obj) }, diff --git a/shared-bindings/hardwarekey/HardwareKey.c b/shared-bindings/hardwarekey/HardwareKey.c new file mode 100644 index 00000000000..7d49076ed17 --- /dev/null +++ b/shared-bindings/hardwarekey/HardwareKey.c @@ -0,0 +1,106 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#include "py/objproperty.h" +#include "py/objstr.h" +#include "py/runtime.h" + +#include "shared-bindings/hardwarekey/__init__.h" +#include "shared-bindings/hardwarekey/HardwareKey.h" + +//| class HardwareKey: +//| """A key held in a hardware key store, usable but not readable. +//| +//| This class cannot be instantiated. Every hardware key slot the board has +//| is exposed as a fixed `HardwareKey` in :mod:`board` -- for example +//| ``board.EFUSE_KEY0`` -- just like pins. A slot with no key burned into it +//| still has a `HardwareKey` object; its `purpose` is `hardwarekey.Purpose.UNUSED`. +//| +//| Compute a MAC with a key by passing it to `hmac.new()` in place of a +//| ``bytes`` key, or turn a Digital Signature key into a +//| :py:class:`cryptography.hazmat.primitives.asymmetric.rsa.DigitalSignatureKey` +//| with :py:func:`cryptography.hazmat.primitives.asymmetric.rsa.load_digital_signature_key()`. +//| +//| On espressif the slots are the eFuse key blocks (``BLOCK_KEY0`` - +//| ``BLOCK_KEY5``); a slot is usable only if its block was burned with +//| purpose ``HMAC_UP`` or ``HMAC_DOWN_DIGITAL_SIGNATURE``.""" +//| + +static void hardwarekey_hardwarekey_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { + hardwarekey_hardwarekey_obj_t *self = MP_OBJ_TO_PTR(self_in); + if (self->name != MP_QSTRnull) { + mp_printf(print, "", self->name); + } else { + mp_printf(print, "", (int)self->key_slot); + } +} + +//| def __bool__(self) -> bool: +//| """``False`` if `purpose` is `hardwarekey.Purpose.UNUSED`, ``True`` otherwise. +//| This lets you write ``if key:`` to check whether a slot is usable.""" +//| ... +static mp_obj_t hardwarekey_hardwarekey_unary_op(mp_unary_op_t op, mp_obj_t self_in) { + hardwarekey_hardwarekey_obj_t *self = MP_OBJ_TO_PTR(self_in); + switch (op) { + case MP_UNARY_OP_BOOL: + return mp_obj_new_bool(common_hal_hardwarekey_hardwarekey_get_purpose(self) != HARDWAREKEY_PURPOSE_UNUSED); + default: + return MP_OBJ_NULL; // op not supported + } +} + +//| key_slot: int +//| """The port-defined key identifier this handle is bound to. On espressif, +//| the eFuse key block index. (read-only)""" +static mp_obj_t hardwarekey_hardwarekey_get_key_slot(mp_obj_t self_in) { + hardwarekey_hardwarekey_obj_t *self = MP_OBJ_TO_PTR(self_in); + return MP_OBJ_NEW_SMALL_INT(common_hal_hardwarekey_hardwarekey_get_key_slot(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(hardwarekey_hardwarekey_get_key_slot_obj, hardwarekey_hardwarekey_get_key_slot); +MP_PROPERTY_GETTER(hardwarekey_hardwarekey_key_slot_obj, (mp_obj_t)&hardwarekey_hardwarekey_get_key_slot_obj); + +//| purpose: Purpose +//| """What this key slot is provisioned for -- `hardwarekey.Purpose.HMAC_UP`, +//| `hardwarekey.Purpose.HMAC_DOWN_DIGITAL_SIGNATURE`, or `hardwarekey.Purpose.UNUSED`. +//| (read-only)""" +static mp_obj_t hardwarekey_hardwarekey_get_purpose(mp_obj_t self_in) { + hardwarekey_hardwarekey_obj_t *self = MP_OBJ_TO_PTR(self_in); + return cp_enum_find(&hardwarekey_purpose_type, common_hal_hardwarekey_hardwarekey_get_purpose(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(hardwarekey_hardwarekey_get_purpose_obj, hardwarekey_hardwarekey_get_purpose); +MP_PROPERTY_GETTER(hardwarekey_hardwarekey_purpose_obj, (mp_obj_t)&hardwarekey_hardwarekey_get_purpose_obj); + +//| exportable: bool +//| """Whether the raw key bytes can ever leave the hardware. Always +//| informational. +//| +//| On espressif this is ``False`` once the key block's ``RD_DIS`` eFuse +//| bit is set (which ``espefuse.py`` does by default). It is meant for +//| manufacturing-time self-test code to confirm a key block was burned as +//| expected. (read-only)""" +//| +static mp_obj_t hardwarekey_hardwarekey_get_exportable(mp_obj_t self_in) { + hardwarekey_hardwarekey_obj_t *self = MP_OBJ_TO_PTR(self_in); + return mp_obj_new_bool(common_hal_hardwarekey_hardwarekey_get_exportable(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(hardwarekey_hardwarekey_get_exportable_obj, hardwarekey_hardwarekey_get_exportable); +MP_PROPERTY_GETTER(hardwarekey_hardwarekey_exportable_obj, (mp_obj_t)&hardwarekey_hardwarekey_get_exportable_obj); + +static const mp_rom_map_elem_t hardwarekey_hardwarekey_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_key_slot), MP_ROM_PTR(&hardwarekey_hardwarekey_key_slot_obj) }, + { MP_ROM_QSTR(MP_QSTR_purpose), MP_ROM_PTR(&hardwarekey_hardwarekey_purpose_obj) }, + { MP_ROM_QSTR(MP_QSTR_exportable), MP_ROM_PTR(&hardwarekey_hardwarekey_exportable_obj) }, +}; +static MP_DEFINE_CONST_DICT(hardwarekey_hardwarekey_locals_dict, hardwarekey_hardwarekey_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + hardwarekey_hardwarekey_type, + MP_QSTR_HardwareKey, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + print, hardwarekey_hardwarekey_print, + unary_op, hardwarekey_hardwarekey_unary_op, + locals_dict, &hardwarekey_hardwarekey_locals_dict + ); diff --git a/shared-bindings/hardwarekey/HardwareKey.h b/shared-bindings/hardwarekey/HardwareKey.h new file mode 100644 index 00000000000..91bdfd3c633 --- /dev/null +++ b/shared-bindings/hardwarekey/HardwareKey.h @@ -0,0 +1,15 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +// Object struct and the common_hal_* accessors. +#include "shared-module/hardwarekey/HardwareKey.h" + +// Type object used in Python. Shared between ports. +extern const mp_obj_type_t hardwarekey_hardwarekey_type; diff --git a/shared-bindings/hardwarekey/__init__.c b/shared-bindings/hardwarekey/__init__.c new file mode 100644 index 00000000000..7d1dce17bd1 --- /dev/null +++ b/shared-bindings/hardwarekey/__init__.c @@ -0,0 +1,73 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#include "py/enum.h" +#include "py/obj.h" + +#include "shared-bindings/hardwarekey/__init__.h" +#include "shared-bindings/hardwarekey/HardwareKey.h" + +//| """Cryptographic operations with keys held in hardware +//| +//| The ``hardwarekey`` module exposes keys that live in a hardware key store -- +//| eFuse, a key manager, a secure element -- and can be *used* but never read +//| back. Application code can compute a MAC, sign, or decrypt with the key; +//| there is no API to read the raw key bytes, and no API to write or burn keys. +//| Provisioning a key is a manufacturing-time step done with vendor tools (for +//| example ``espefuse.py`` on Espressif chips). +//| +//| `HardwareKey` objects are not created by application code. Every hardware key +//| slot the board has is exposed as a fixed object in :mod:`board` (for example +//| ``board.EFUSE_KEY0``), in the same way that pins are. Compute a MAC with one +//| by passing it to `hmac.new()`; turn a Digital Signature key into a +//| :py:class:`cryptography.hazmat.primitives.asymmetric.rsa.DigitalSignatureKey` +//| with :py:func:`cryptography.hazmat.primitives.asymmetric.rsa.load_digital_signature_key()`. +//| """ + +MAKE_ENUM_VALUE(hardwarekey_purpose_type, hardwarekey_purpose, HMAC_UP, HARDWAREKEY_PURPOSE_HMAC); +MAKE_ENUM_VALUE(hardwarekey_purpose_type, hardwarekey_purpose, HMAC_DOWN_DIGITAL_SIGNATURE, HARDWAREKEY_PURPOSE_DS); +MAKE_ENUM_VALUE(hardwarekey_purpose_type, hardwarekey_purpose, UNUSED, HARDWAREKEY_PURPOSE_UNUSED); + +//| class Purpose: +//| """What a hardware key slot is provisioned for. Instances are singletons; +//| compare with ``is``.""" +//| +//| HMAC_UP: object +//| """The slot holds an HMAC key. It can be used with `hmac.new()`.""" +//| +//| HMAC_DOWN_DIGITAL_SIGNATURE: object +//| """The slot holds the key for a Digital Signature (RSA) key. Turn it into a +//| :py:class:`cryptography.hazmat.primitives.asymmetric.rsa.DigitalSignatureKey` +//| with :py:func:`cryptography.hazmat.primitives.asymmetric.rsa.load_digital_signature_key()`.""" +//| +//| UNUSED: object +//| """No key is burned into the slot (or it is burned for something this module +//| does not expose). The slot's `HardwareKey` still exists but cannot be used.""" +//| +MAKE_ENUM_MAP(hardwarekey_purpose) { + MAKE_ENUM_MAP_ENTRY(hardwarekey_purpose, HMAC_UP), + MAKE_ENUM_MAP_ENTRY(hardwarekey_purpose, HMAC_DOWN_DIGITAL_SIGNATURE), + MAKE_ENUM_MAP_ENTRY(hardwarekey_purpose, UNUSED), +}; +static MP_DEFINE_CONST_DICT(hardwarekey_purpose_locals_dict, hardwarekey_purpose_locals_table); + +MAKE_PRINTER(hardwarekey, hardwarekey_purpose); + +MAKE_ENUM_TYPE(hardwarekey, Purpose, hardwarekey_purpose); + +static const mp_rom_map_elem_t hardwarekey_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_hardwarekey) }, + { MP_ROM_QSTR(MP_QSTR_HardwareKey), MP_ROM_PTR(&hardwarekey_hardwarekey_type) }, + { MP_ROM_QSTR(MP_QSTR_Purpose), MP_ROM_PTR(&hardwarekey_purpose_type) }, +}; +static MP_DEFINE_CONST_DICT(hardwarekey_module_globals, hardwarekey_module_globals_table); + +const mp_obj_module_t hardwarekey_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&hardwarekey_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_hardwarekey, hardwarekey_module); diff --git a/shared-bindings/hardwarekey/__init__.h b/shared-bindings/hardwarekey/__init__.h new file mode 100644 index 00000000000..2f7a72b3e31 --- /dev/null +++ b/shared-bindings/hardwarekey/__init__.h @@ -0,0 +1,14 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/enum.h" +#include "py/obj.h" + +#include "shared-module/hardwarekey/HardwareKey.h" + +extern const mp_obj_type_t hardwarekey_purpose_type; diff --git a/shared-bindings/hashlib/__init__.c b/shared-bindings/hashlib/__init__.c index bfe19dee107..430c2f14cc1 100644 --- a/shared-bindings/hashlib/__init__.c +++ b/shared-bindings/hashlib/__init__.c @@ -20,7 +20,8 @@ //| //| def new(name: str, data: bytes = b"") -> hashlib.Hash: //| """Returns a Hash object setup for the named algorithm. Raises ValueError when the named -//| algorithm is unsupported. +//| algorithm is unsupported. Supported algorithms for ``name`` are ``'md5'``, ``'sha1'``, and +//| ``'sha256'``. //| //| :return: a hash object for the given algorithm //| :rtype: hashlib.Hash""" diff --git a/shared-bindings/hmac/HMAC.c b/shared-bindings/hmac/HMAC.c new file mode 100644 index 00000000000..a5beeba8378 --- /dev/null +++ b/shared-bindings/hmac/HMAC.c @@ -0,0 +1,140 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#include + +#include "shared-bindings/hmac/HMAC.h" + +#include "py/objproperty.h" +#include "py/objstr.h" +#include "py/runtime.h" + +//| class HMAC: +//| """An HMAC object, in progress. Created by `hmac.new()`; it has no user-visible +//| constructor.""" +//| + +//| def update(self, msg: ReadableBuffer) -> None: +//| """Feed more data into the HMAC. +//| +//| Raises `RuntimeError` if called after `digest()` or `hexdigest()` -- unlike +//| CPython's ``hmac``, this cannot be resumed once a digest has been taken.""" +//| ... +mp_obj_t hmac_hmac_update(mp_obj_t self_in, mp_obj_t buf_in) { + mp_check_self(mp_obj_is_type(self_in, &hmac_hmac_type)); + hmac_hmac_obj_t *self = MP_OBJ_TO_PTR(self_in); + + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(buf_in, &bufinfo, MP_BUFFER_READ); + + common_hal_hmac_update(self, bufinfo.buf, bufinfo.len); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(hmac_hmac_update_obj, hmac_hmac_update); + +//| def digest(self) -> bytes: +//| """Return the HMAC of the data fed so far, as ``digest_size`` bytes. +//| +//| The first call finishes the underlying MAC computation and caches the +//| result; later calls just return the cached bytes. `update()` can no +//| longer be called after this, unlike CPython's ``hmac``.""" +//| ... +static mp_obj_t hmac_hmac_digest(mp_obj_t self_in) { + mp_check_self(mp_obj_is_type(self_in, &hmac_hmac_type)); + hmac_hmac_obj_t *self = MP_OBJ_TO_PTR(self_in); + + size_t size = common_hal_hmac_get_digest_size(self); + mp_obj_t obj = mp_obj_new_bytes_of_zeros(size); + mp_obj_str_t *o = MP_OBJ_TO_PTR(obj); + + common_hal_hmac_digest(self, (uint8_t *)o->data, size); + return obj; +} +static MP_DEFINE_CONST_FUN_OBJ_1(hmac_hmac_digest_obj, hmac_hmac_digest); + +//| def hexdigest(self) -> str: +//| """Like `digest()` but returns the MAC as a string of hexadecimal digits.""" +//| ... +static mp_obj_t hmac_hmac_hexdigest(mp_obj_t self_in) { + mp_check_self(mp_obj_is_type(self_in, &hmac_hmac_type)); + hmac_hmac_obj_t *self = MP_OBJ_TO_PTR(self_in); + + size_t size = common_hal_hmac_get_digest_size(self); + uint8_t digest[PSA_HASH_MAX_SIZE]; + common_hal_hmac_digest(self, digest, size); + + vstr_t vstr; + vstr_init_len(&vstr, size * 2); + for (size_t i = 0; i < size; i++) { + vstr.buf[i * 2] = nibble_to_hex_lower[digest[i] >> 4]; + vstr.buf[i * 2 + 1] = nibble_to_hex_lower[digest[i] & 0xf]; + } + return mp_obj_new_str_from_vstr(&vstr); +} +static MP_DEFINE_CONST_FUN_OBJ_1(hmac_hmac_hexdigest_obj, hmac_hmac_hexdigest); + +//| def copy(self) -> HMAC: +//| """Not supported; always raises `NotImplementedError`. +//| +//| PSA Crypto's multipart MAC API has no way to duplicate an in-progress MAC +//| operation (unlike a plain hash, which can be cloned), so this HMAC object +//| cannot be copied.""" +//| ... +static mp_obj_t hmac_hmac_copy(mp_obj_t self_in) { + mp_check_self(mp_obj_is_type(self_in, &hmac_hmac_type)); + mp_raise_NotImplementedError(NULL); +} +static MP_DEFINE_CONST_FUN_OBJ_1(hmac_hmac_copy_obj, hmac_hmac_copy); + +//| digest_size: int +//| """The size of the MAC in bytes (32 for sha256, 20 for sha1). (read-only)""" +static mp_obj_t hmac_hmac_get_digest_size(mp_obj_t self_in) { + mp_check_self(mp_obj_is_type(self_in, &hmac_hmac_type)); + hmac_hmac_obj_t *self = MP_OBJ_TO_PTR(self_in); + return MP_OBJ_NEW_SMALL_INT(common_hal_hmac_get_digest_size(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(hmac_hmac_get_digest_size_obj, hmac_hmac_get_digest_size); +MP_PROPERTY_GETTER(hmac_hmac_digest_size_obj, (mp_obj_t)&hmac_hmac_get_digest_size_obj); + +//| block_size: int +//| """The internal block size of the hash algorithm in bytes. (read-only)""" +static mp_obj_t hmac_hmac_get_block_size(mp_obj_t self_in) { + mp_check_self(mp_obj_is_type(self_in, &hmac_hmac_type)); + hmac_hmac_obj_t *self = MP_OBJ_TO_PTR(self_in); + return MP_OBJ_NEW_SMALL_INT(common_hal_hmac_get_block_size(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(hmac_hmac_get_block_size_obj, hmac_hmac_get_block_size); +MP_PROPERTY_GETTER(hmac_hmac_block_size_obj, (mp_obj_t)&hmac_hmac_get_block_size_obj); + +//| name: str +//| """The canonical name of this HMAC, e.g. ``"hmac-sha256"``. (read-only)""" +//| +static mp_obj_t hmac_hmac_get_name(mp_obj_t self_in) { + mp_check_self(mp_obj_is_type(self_in, &hmac_hmac_type)); + hmac_hmac_obj_t *self = MP_OBJ_TO_PTR(self_in); + const char *name = common_hal_hmac_get_name(self); + return mp_obj_new_str(name, strlen(name)); +} +MP_DEFINE_CONST_FUN_OBJ_1(hmac_hmac_get_name_obj, hmac_hmac_get_name); +MP_PROPERTY_GETTER(hmac_hmac_name_obj, (mp_obj_t)&hmac_hmac_get_name_obj); + +static const mp_rom_map_elem_t hmac_hmac_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_update), MP_ROM_PTR(&hmac_hmac_update_obj) }, + { MP_ROM_QSTR(MP_QSTR_digest), MP_ROM_PTR(&hmac_hmac_digest_obj) }, + { MP_ROM_QSTR(MP_QSTR_hexdigest), MP_ROM_PTR(&hmac_hmac_hexdigest_obj) }, + { MP_ROM_QSTR(MP_QSTR_copy), MP_ROM_PTR(&hmac_hmac_copy_obj) }, + { MP_ROM_QSTR(MP_QSTR_digest_size), MP_ROM_PTR(&hmac_hmac_digest_size_obj) }, + { MP_ROM_QSTR(MP_QSTR_block_size), MP_ROM_PTR(&hmac_hmac_block_size_obj) }, + { MP_ROM_QSTR(MP_QSTR_name), MP_ROM_PTR(&hmac_hmac_name_obj) }, +}; +static MP_DEFINE_CONST_DICT(hmac_hmac_locals_dict, hmac_hmac_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + hmac_hmac_type, + MP_QSTR_HMAC, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + locals_dict, &hmac_hmac_locals_dict + ); diff --git a/shared-bindings/hmac/HMAC.h b/shared-bindings/hmac/HMAC.h new file mode 100644 index 00000000000..49006a131ec --- /dev/null +++ b/shared-bindings/hmac/HMAC.h @@ -0,0 +1,25 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +#include "shared-module/hmac/__init__.h" + +extern const mp_obj_type_t hmac_hmac_type; + +// Shared with __init__.c so hmac.new() can feed the initial msg argument. +mp_obj_t hmac_hmac_update(mp_obj_t self_in, mp_obj_t buf_in); + +void common_hal_hmac_new(hmac_hmac_obj_t *self, const uint8_t *key, size_t key_len, + psa_key_id_t borrowed_key_id, psa_algorithm_t hash_alg); +void common_hal_hmac_update(hmac_hmac_obj_t *self, const uint8_t *data, size_t data_len); +void common_hal_hmac_digest(hmac_hmac_obj_t *self, uint8_t *out, size_t out_len); +size_t common_hal_hmac_get_digest_size(hmac_hmac_obj_t *self); +size_t common_hal_hmac_get_block_size(hmac_hmac_obj_t *self); +// Returns "hmac-sha256" / "hmac-sha1" for the .name property (CPython format). +const char *common_hal_hmac_get_name(hmac_hmac_obj_t *self); diff --git a/shared-bindings/hmac/__init__.c b/shared-bindings/hmac/__init__.c new file mode 100644 index 00000000000..696b611f472 --- /dev/null +++ b/shared-bindings/hmac/__init__.c @@ -0,0 +1,148 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#include "py/obj.h" +#include "py/objstr.h" +#include "py/runtime.h" + +#include "shared-bindings/hmac/__init__.h" +#include "shared-bindings/hmac/HMAC.h" +#include "shared-module/hmac/__init__.h" + +#if CIRCUITPY_HARDWAREKEY +#include "shared-bindings/hardwarekey/HardwareKey.h" +#endif + +//| """Keyed hashing for message authentication +//| +//| |see_cpython_module| :mod:`cpython:hmac`. +//| +//| The key may be a ``bytes``-like object or, where the port provides them, a +//| ``hardwarekey.HardwareKey`` -- so the same code works with a key in flash +//| during development and a key held in hardware in production. The one +//| exception: an empty message raises `ValueError` with a +//| ``hardwarekey.HardwareKey`` (a hardware driver limitation), where it is +//| valid with a ``bytes`` key. +//| +//| Only ``"sha256"`` and ``"sha1"`` are supported for ``digestmod``. +//| """ +//| + +static psa_algorithm_t hash_alg_from_digestmod(mp_obj_t digestmod) { + const char *name = mp_obj_str_get_str(digestmod); + psa_algorithm_t hash_alg; + if (!hmac_hash_alg_from_name(name, &hash_alg)) { + mp_raise_ValueError(MP_ERROR_TEXT("Unsupported hash algorithm")); + } + return hash_alg; +} + +static hmac_hmac_obj_t *hmac_new_internal(mp_obj_t key_in, psa_algorithm_t hash_alg) { + hmac_hmac_obj_t *self = mp_obj_malloc(hmac_hmac_obj_t, &hmac_hmac_type); + + #if CIRCUITPY_HARDWAREKEY + if (mp_obj_is_type(key_in, &hardwarekey_hardwarekey_type)) { + hardwarekey_hardwarekey_obj_t *key = MP_OBJ_TO_PTR(key_in); + if (common_hal_hardwarekey_hardwarekey_get_purpose(key) != HARDWAREKEY_PURPOSE_HMAC) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("key does not have the expected %q purpose"), MP_QSTR_HMAC_UP); + } + psa_key_id_t key_id = common_hal_hardwarekey_hardwarekey_get_key_id(key); + common_hal_hmac_new(self, NULL, 0, key_id, hash_alg); + return self; + } + #endif + + mp_buffer_info_t keyinfo; + mp_get_buffer_raise(key_in, &keyinfo, MP_BUFFER_READ); + + common_hal_hmac_new(self, keyinfo.buf, keyinfo.len, 0, hash_alg); + return self; +} + +//| def new( +//| key: ReadableBuffer | hardwarekey.HardwareKey, +//| msg: ReadableBuffer = b"", +//| digestmod: str = ..., +//| ) -> HMAC: +//| """Create a new HMAC object. +//| +//| :param key: the secret key -- a ``bytes``-like object, or a +//| ``hardwarekey.HardwareKey`` on ports that provide it +//| :param ReadableBuffer msg: initial data to authenticate; add more with `HMAC.update()` +//| :param str digestmod: the digest name, ``"sha256"`` or ``"sha1"``. Required. +//| """ +//| ... +//| +static mp_obj_t hmac_new(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_key, ARG_msg, ARG_digestmod }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_key, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_msg, MP_ARG_OBJ, {.u_obj = mp_const_none} }, + { MP_QSTR_digestmod, MP_ARG_REQUIRED | MP_ARG_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); + + psa_algorithm_t hash_alg = hash_alg_from_digestmod(args[ARG_digestmod].u_obj); + hmac_hmac_obj_t *self = hmac_new_internal(args[ARG_key].u_obj, hash_alg); + + if (args[ARG_msg].u_obj != mp_const_none) { + hmac_hmac_update(MP_OBJ_FROM_PTR(self), args[ARG_msg].u_obj); + } + return MP_OBJ_FROM_PTR(self); +} +static MP_DEFINE_CONST_FUN_OBJ_KW(hmac_new_obj, 1, hmac_new); + +//| def digest( +//| key: ReadableBuffer | hardwarekey.HardwareKey, msg: ReadableBuffer, digest: str +//| ) -> bytes: +//| """Return the HMAC of ``msg`` under ``key`` for the named ``digest``, in one call. +//| +//| Equivalent to ``new(key, msg, digestmod=digest).digest()`` but does not build an +//| intermediate object.""" +//| ... +//| +static mp_obj_t hmac_digest(mp_obj_t key_in, mp_obj_t msg_in, mp_obj_t digest_in) { + psa_algorithm_t hash_alg = hash_alg_from_digestmod(digest_in); + hmac_hmac_obj_t *self = hmac_new_internal(key_in, hash_alg); + hmac_hmac_update(MP_OBJ_FROM_PTR(self), msg_in); + + size_t size = common_hal_hmac_get_digest_size(self); + mp_obj_t obj = mp_obj_new_bytes_of_zeros(size); + mp_obj_str_t *o = MP_OBJ_TO_PTR(obj); + common_hal_hmac_digest(self, (uint8_t *)o->data, size); + return obj; +} +static MP_DEFINE_CONST_FUN_OBJ_3(hmac_digest_obj, hmac_digest); + +//| def compare_digest(a: ReadableBuffer, b: ReadableBuffer) -> bool: +//| """Return ``a == b`` using a constant-time comparison, to avoid leaking timing +//| information about a MAC check.""" +//| ... +//| +static mp_obj_t hmac_compare_digest(mp_obj_t a_in, mp_obj_t b_in) { + mp_buffer_info_t a, b; + mp_get_buffer_raise(a_in, &a, MP_BUFFER_READ); + mp_get_buffer_raise(b_in, &b, MP_BUFFER_READ); + return mp_obj_new_bool(common_hal_hmac_compare_digest(a.buf, a.len, b.buf, b.len)); +} +static MP_DEFINE_CONST_FUN_OBJ_2(hmac_compare_digest_obj, hmac_compare_digest); + +static const mp_rom_map_elem_t hmac_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_hmac) }, + { MP_ROM_QSTR(MP_QSTR_new), MP_ROM_PTR(&hmac_new_obj) }, + { MP_ROM_QSTR(MP_QSTR_digest), MP_ROM_PTR(&hmac_digest_obj) }, + { MP_ROM_QSTR(MP_QSTR_compare_digest), MP_ROM_PTR(&hmac_compare_digest_obj) }, + { MP_ROM_QSTR(MP_QSTR_HMAC), MP_ROM_PTR(&hmac_hmac_type) }, +}; +static MP_DEFINE_CONST_DICT(hmac_module_globals, hmac_module_globals_table); + +const mp_obj_module_t hmac_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&hmac_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_hmac, hmac_module); diff --git a/shared-bindings/hmac/__init__.h b/shared-bindings/hmac/__init__.h new file mode 100644 index 00000000000..9ea3521ab1e --- /dev/null +++ b/shared-bindings/hmac/__init__.h @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-bindings/hmac/HMAC.h" diff --git a/shared-bindings/i2cdisplaybus/I2CDisplayBus.c b/shared-bindings/i2cdisplaybus/I2CDisplayBus.c index 8633f166805..3b9b7d4f13d 100644 --- a/shared-bindings/i2cdisplaybus/I2CDisplayBus.c +++ b/shared-bindings/i2cdisplaybus/I2CDisplayBus.c @@ -34,10 +34,11 @@ //| ) -> None: //| """Create a I2CDisplayBus object associated with the given I2C bus and reset pin. //| -//| 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. +//| The I2C bus and pins are then in use by the display until your code finishes or +//| the display's ``deinit()`` is called. If the display is +//| `supervisor.runtime.display `, they stay in use after your code finishes, so CircuitPython can +//| use the display. In that case, check `supervisor.runtime.display ` before creating the display +//| again, or call ``supervisor.runtime.display.deinit()`` first. //| //| :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 diff --git a/shared-bindings/i2cioexpander/IOExpander.c b/shared-bindings/i2cioexpander/IOExpander.c new file mode 100644 index 00000000000..d75022c87e8 --- /dev/null +++ b/shared-bindings/i2cioexpander/IOExpander.c @@ -0,0 +1,261 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include + +#include "py/obj.h" +#include "py/objproperty.h" +#include "py/runtime.h" + +#include "shared-bindings/i2cioexpander/IOExpander.h" +#include "shared-bindings/busio/I2C.h" +#include "shared-bindings/util.h" +#include "shared/runtime/context_manager_helpers.h" + +//| class IOExpander: +//| """Control a generic I2C-based GPIO expander +//| +//| IOExpander provides a simple interface to I2C-based GPIO expanders that +//| use basic register reads and writes for control. The expander provides +//| individual pins through the `pins` attribute that implement the +//| DigitalInOutProtocol. +//| """ +//| +//| def __init__( +//| self, +//| i2c: busio.I2C, +//| address: int, +//| num_pins: int, +//| set_value_reg: Optional[int] = None, +//| get_value_reg: Optional[int] = None, +//| set_direction_reg: Optional[int] = None, +//| ) -> None: +//| """Initialize an I2C GPIO expander +//| +//| :param busio.I2C i2c: The I2C bus the expander is connected to +//| :param int address: The I2C device address +//| :param int num_pins: The number of GPIO pins (8 or 16) +//| :param int set_value_reg: Register address to write pin values (optional) +//| :param int get_value_reg: Register address to read pin values (optional) +//| :param int set_direction_reg: Register address to set pin directions (optional) +//| """ +//| ... + +static void check_for_deinit(i2cioexpander_ioexpander_obj_t *self) { + if (common_hal_i2cioexpander_ioexpander_deinited(self)) { + raise_deinited_error(); + } +} + +static mp_obj_t i2cioexpander_ioexpander_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_i2c, ARG_address, ARG_num_pins, ARG_set_value_reg, ARG_get_value_reg, ARG_set_direction_reg }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_i2c, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_address, MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_num_pins, MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_set_value_reg, MP_ARG_OBJ, {.u_obj = mp_const_none} }, + { MP_QSTR_get_value_reg, MP_ARG_OBJ, {.u_obj = mp_const_none} }, + { MP_QSTR_set_direction_reg, MP_ARG_OBJ, {.u_obj = mp_const_none} }, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + // Validate I2C object + mp_obj_t i2c = mp_arg_validate_type(args[ARG_i2c].u_obj, &busio_i2c_type, MP_QSTR_i2c); + + // Validate address + int address = args[ARG_address].u_int; + if (address < 0 || address > 0x7F) { + mp_raise_ValueError(MP_ERROR_TEXT("address out of range")); + } + + // Validate num_pins + int num_pins = args[ARG_num_pins].u_int; + if (num_pins != 8 && num_pins != 16) { + mp_raise_ValueError(MP_ERROR_TEXT("num_pins must be 8 or 16")); + } + + // Convert and validate register parameters + uint16_t set_value_reg = NO_REGISTER; + if (args[ARG_set_value_reg].u_obj != mp_const_none) { + mp_int_t reg = mp_obj_get_int(args[ARG_set_value_reg].u_obj); + mp_arg_validate_int_range(reg, 0, 255, MP_QSTR_set_value_reg); + set_value_reg = reg; + } + + uint16_t get_value_reg = NO_REGISTER; + if (args[ARG_get_value_reg].u_obj != mp_const_none) { + mp_int_t reg = mp_obj_get_int(args[ARG_get_value_reg].u_obj); + mp_arg_validate_int_range(reg, 0, 255, MP_QSTR_get_value_reg); + get_value_reg = reg; + } + + uint16_t set_direction_reg = NO_REGISTER; + if (args[ARG_set_direction_reg].u_obj != mp_const_none) { + mp_int_t reg = mp_obj_get_int(args[ARG_set_direction_reg].u_obj); + mp_arg_validate_int_range(reg, 0, 255, MP_QSTR_set_direction_reg); + set_direction_reg = reg; + } + + i2cioexpander_ioexpander_obj_t *self = + mp_obj_malloc_with_finaliser(i2cioexpander_ioexpander_obj_t, &i2cioexpander_ioexpander_type); + common_hal_i2cioexpander_ioexpander_construct( + self, + i2c, + address, + num_pins, + set_value_reg, + get_value_reg, + set_direction_reg); + + return MP_OBJ_FROM_PTR(self); +} + +//| def deinit(self) -> None: +//| """Deinitialize the expander. No further operations are possible.""" +//| ... +static mp_obj_t i2cioexpander_ioexpander_deinit(mp_obj_t self_in) { + i2cioexpander_ioexpander_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_i2cioexpander_ioexpander_deinit(self); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(i2cioexpander_ioexpander_deinit_obj, i2cioexpander_ioexpander_deinit); + +//| def __enter__(self) -> IOExpander: +//| """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 i2cioexpander_ioexpander___exit__(size_t n_args, const mp_obj_t *args) { + (void)n_args; + common_hal_i2cioexpander_ioexpander_deinit(MP_OBJ_TO_PTR(args[0])); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(i2cioexpander_ioexpander___exit___obj, 4, 4, i2cioexpander_ioexpander___exit__); + +//| @property +//| def input_value(self) -> int: +//| """Read the live value of all pins at once. Returns an integer where each +//| bit represents a pin's current state.""" +//| ... +static mp_obj_t i2cioexpander_ioexpander_obj_get_input_value(mp_obj_t self_in) { + i2cioexpander_ioexpander_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + size_t value; + mp_negative_errno_t result = common_hal_i2cioexpander_ioexpander_get_input_value(self, &value); + if (result != 0) { + mp_raise_OSError(-result); + } + return MP_OBJ_NEW_SMALL_INT(value); +} +MP_DEFINE_CONST_FUN_OBJ_1(i2cioexpander_ioexpander_get_input_value_obj, i2cioexpander_ioexpander_obj_get_input_value); + +MP_PROPERTY_GETTER(i2cioexpander_ioexpander_input_value_obj, + (mp_obj_t)&i2cioexpander_ioexpander_get_input_value_obj); + +//| @property +//| def output_value(self) -> int: +//| """Get or set the cached output value. Reading returns the last value written, +//| not the live pin state. Writing updates the output pins.""" +//| ... +//| @output_value.setter +//| def output_value(self, val: int) -> None: ... +static mp_obj_t i2cioexpander_ioexpander_obj_get_output_value(mp_obj_t self_in) { + i2cioexpander_ioexpander_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + size_t value; + common_hal_i2cioexpander_ioexpander_get_output_value(self, &value); + return mp_obj_new_int(value); +} +MP_DEFINE_CONST_FUN_OBJ_1(i2cioexpander_ioexpander_get_output_value_obj, i2cioexpander_ioexpander_obj_get_output_value); + +static mp_obj_t i2cioexpander_ioexpander_obj_set_output_value(mp_obj_t self_in, mp_obj_t value) { + i2cioexpander_ioexpander_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + mp_negative_errno_t result = common_hal_i2cioexpander_ioexpander_set_output_value(self, mp_obj_get_int(value)); + if (result != 0) { + mp_raise_OSError(-result); + } + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(i2cioexpander_ioexpander_set_output_value_obj, i2cioexpander_ioexpander_obj_set_output_value); + +MP_PROPERTY_GETSET(i2cioexpander_ioexpander_output_value_obj, + (mp_obj_t)&i2cioexpander_ioexpander_get_output_value_obj, + (mp_obj_t)&i2cioexpander_ioexpander_set_output_value_obj); + +//| @property +//| def output_mask(self) -> int: +//| """Get or set which pins are configured as outputs. Each bit in the mask +//| represents a pin: 1 for output, 0 for input.""" +//| ... +//| @output_mask.setter +//| def output_mask(self, val: int) -> None: ... +static mp_obj_t i2cioexpander_ioexpander_obj_get_output_mask(mp_obj_t self_in) { + i2cioexpander_ioexpander_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + size_t output_mask; + common_hal_i2cioexpander_ioexpander_get_output_mask(self, &output_mask); + return mp_obj_new_int(output_mask); +} +MP_DEFINE_CONST_FUN_OBJ_1(i2cioexpander_ioexpander_get_output_mask_obj, i2cioexpander_ioexpander_obj_get_output_mask); + +static mp_obj_t i2cioexpander_ioexpander_obj_set_output_mask(mp_obj_t self_in, mp_obj_t value) { + i2cioexpander_ioexpander_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + mp_negative_errno_t result = common_hal_i2cioexpander_ioexpander_set_output_mask(self, mp_obj_get_int(value)); + if (result != 0) { + mp_raise_OSError(-result); + } + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(i2cioexpander_ioexpander_set_output_mask_obj, i2cioexpander_ioexpander_obj_set_output_mask); + +MP_PROPERTY_GETSET(i2cioexpander_ioexpander_output_mask_obj, + (mp_obj_t)&i2cioexpander_ioexpander_get_output_mask_obj, + (mp_obj_t)&i2cioexpander_ioexpander_set_output_mask_obj); + +//| @property +//| def pins(self) -> Tuple[IOPin, ...]: +//| """A tuple of `IOPin` objects that implement the DigitalInOutProtocol. +//| Each pin can be used like a digitalio.DigitalInOut object.""" +//| ... +static mp_obj_t i2cioexpander_ioexpander_obj_get_pins(mp_obj_t self_in) { + i2cioexpander_ioexpander_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return common_hal_i2cioexpander_ioexpander_get_pins(self); +} +MP_DEFINE_CONST_FUN_OBJ_1(i2cioexpander_ioexpander_get_pins_obj, i2cioexpander_ioexpander_obj_get_pins); + +MP_PROPERTY_GETTER(i2cioexpander_ioexpander_pins_obj, + (mp_obj_t)&i2cioexpander_ioexpander_get_pins_obj); + +static const mp_rom_map_elem_t i2cioexpander_ioexpander_locals_dict_table[] = { + // Methods + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&i2cioexpander_ioexpander_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&i2cioexpander_ioexpander_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&i2cioexpander_ioexpander___exit___obj) }, + + // Properties + { MP_ROM_QSTR(MP_QSTR_input_value), MP_ROM_PTR(&i2cioexpander_ioexpander_input_value_obj) }, + { MP_ROM_QSTR(MP_QSTR_output_value), MP_ROM_PTR(&i2cioexpander_ioexpander_output_value_obj) }, + { MP_ROM_QSTR(MP_QSTR_output_mask), MP_ROM_PTR(&i2cioexpander_ioexpander_output_mask_obj) }, + { MP_ROM_QSTR(MP_QSTR_pins), MP_ROM_PTR(&i2cioexpander_ioexpander_pins_obj) }, +}; +static MP_DEFINE_CONST_DICT(i2cioexpander_ioexpander_locals_dict, i2cioexpander_ioexpander_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + i2cioexpander_ioexpander_type, + MP_QSTR_IOExpander, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, i2cioexpander_ioexpander_make_new, + locals_dict, &i2cioexpander_ioexpander_locals_dict + ); diff --git a/shared-bindings/i2cioexpander/IOExpander.h b/shared-bindings/i2cioexpander/IOExpander.h new file mode 100644 index 00000000000..5c93c6250cc --- /dev/null +++ b/shared-bindings/i2cioexpander/IOExpander.h @@ -0,0 +1,34 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" +#include "shared-module/i2cioexpander/IOExpander.h" + +extern const mp_obj_type_t i2cioexpander_ioexpander_type; + +void common_hal_i2cioexpander_ioexpander_construct( + i2cioexpander_ioexpander_obj_t *self, + mp_obj_t i2c, + uint8_t address, + uint8_t num_pins, + uint16_t set_value_reg, + uint16_t get_value_reg, + uint16_t set_direction_reg); + +void common_hal_i2cioexpander_ioexpander_deinit(i2cioexpander_ioexpander_obj_t *self); +bool common_hal_i2cioexpander_ioexpander_deinited(i2cioexpander_ioexpander_obj_t *self); + +mp_negative_errno_t common_hal_i2cioexpander_ioexpander_get_input_value(i2cioexpander_ioexpander_obj_t *self, size_t *value); +// No error return because this returns a cached value. +void common_hal_i2cioexpander_ioexpander_get_output_value(i2cioexpander_ioexpander_obj_t *self, size_t *value); +mp_negative_errno_t common_hal_i2cioexpander_ioexpander_set_output_value(i2cioexpander_ioexpander_obj_t *self, size_t value); + +void common_hal_i2cioexpander_ioexpander_get_output_mask(i2cioexpander_ioexpander_obj_t *self, size_t *mask); +mp_negative_errno_t common_hal_i2cioexpander_ioexpander_set_output_mask(i2cioexpander_ioexpander_obj_t *self, size_t mask); + +mp_obj_t common_hal_i2cioexpander_ioexpander_get_pins(i2cioexpander_ioexpander_obj_t *self); diff --git a/shared-bindings/i2cioexpander/IOPin.c b/shared-bindings/i2cioexpander/IOPin.c new file mode 100644 index 00000000000..bba229bd31e --- /dev/null +++ b/shared-bindings/i2cioexpander/IOPin.c @@ -0,0 +1,326 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/i2cioexpander/IOPin.h" +#include "shared-module/i2cioexpander/IOPin.h" + +#include "py/objproperty.h" +#include "py/runtime.h" +#include "shared-bindings/digitalio/DigitalInOut.h" +#include "shared-bindings/digitalio/DigitalInOutProtocol.h" +#include "shared-bindings/digitalio/Direction.h" +#include "shared-bindings/digitalio/DriveMode.h" +#include "shared-bindings/digitalio/Pull.h" +#include "shared-bindings/util.h" + +static void check_result(digitalinout_result_t result) { + switch (result) { + case DIGITALINOUT_OK: + return; + case DIGITALINOUT_PIN_BUSY: + mp_raise_ValueError_varg(MP_ERROR_TEXT("%q in use"), MP_QSTR_Pin); + #if CIRCUITPY_DIGITALIO_HAVE_INPUT_ONLY + case DIGITALINOUT_INPUT_ONLY: + mp_raise_ValueError_varg(MP_ERROR_TEXT("Invalid %q"), MP_QSTR_direction); + #endif + #if CIRCUITPY_DIGITALIO_HAVE_INVALID_PULL + case DIGITALINOUT_INVALID_PULL: + mp_raise_ValueError_varg(MP_ERROR_TEXT("Invalid %q"), MP_QSTR_pull); + #endif + #if CIRCUITPY_DIGITALIO_HAVE_INVALID_DRIVE_MODE + case DIGITALINOUT_INVALID_DRIVE_MODE: + mp_raise_ValueError_varg(MP_ERROR_TEXT("Invalid %q"), MP_QSTR_drive_mode); + #endif + } +} + +static inline void check_for_deinit(i2cioexpander_iopin_obj_t *self) { + if (common_hal_i2cioexpander_iopin_deinited(self)) { + raise_deinited_error(); + } +} +//| class IOPin: +//| """Control a single pin on an `IOExpander` in the same way as `DigitalInOut`. +//| +//| Not constructed directly. Get from `IOExpander.pins` instead. +//| """ +//| + +//| def switch_to_output( +//| self, value: bool = False, drive_mode: digitalio.DriveMode = digitalio.DriveMode.PUSH_PULL +//| ) -> None: +//| """Set the drive mode and value and then switch to writing out digital values. +//| +//| :param bool value: default value to set upon switching +//| :param digitalio.DriveMode drive_mode: drive mode for the output""" +//| ... +static mp_obj_t i2cioexpander_iopin_switch_to_output(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_value, ARG_drive_mode }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_value, MP_ARG_BOOL, {.u_bool = false} }, + { MP_QSTR_drive_mode, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_PTR(&digitalio_drive_mode_push_pull_obj)} }, + }; + i2cioexpander_iopin_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); + + digitalio_drive_mode_t drive_mode = DRIVE_MODE_PUSH_PULL; + if (args[ARG_drive_mode].u_rom_obj == MP_ROM_PTR(&digitalio_drive_mode_open_drain_obj)) { + drive_mode = DRIVE_MODE_OPEN_DRAIN; + } + check_result(common_hal_i2cioexpander_iopin_switch_to_output(self, args[ARG_value].u_bool, drive_mode)); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_KW(i2cioexpander_iopin_switch_to_output_obj, 1, i2cioexpander_iopin_switch_to_output); + +//| def switch_to_input(self, pull: Optional[digitalio.Pull] = None) -> None: +//| """Set the pull and then switch to read in digital values. +//| +//| :param digitalio.Pull pull: pull configuration for the input""" +//| ... +static mp_obj_t i2cioexpander_iopin_switch_to_input(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_pull }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_pull, MP_ARG_OBJ, {.u_rom_obj = mp_const_none} }, + }; + i2cioexpander_iopin_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); + + check_result(common_hal_i2cioexpander_iopin_switch_to_input(self, validate_pull(args[ARG_pull].u_rom_obj, MP_QSTR_pull))); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_KW(i2cioexpander_iopin_switch_to_input_obj, 1, i2cioexpander_iopin_switch_to_input); + +//| direction: digitalio.Direction +//| """The direction of the pin.""" +static mp_obj_t i2cioexpander_iopin_obj_get_direction(mp_obj_t self_in) { + i2cioexpander_iopin_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + digitalio_direction_t direction = common_hal_i2cioexpander_iopin_get_direction(self); + if (direction == DIRECTION_INPUT) { + return MP_OBJ_FROM_PTR(&digitalio_direction_input_obj); + } + return MP_OBJ_FROM_PTR(&digitalio_direction_output_obj); +} +MP_DEFINE_CONST_FUN_OBJ_1(i2cioexpander_iopin_get_direction_obj, i2cioexpander_iopin_obj_get_direction); + +static mp_obj_t i2cioexpander_iopin_obj_set_direction(mp_obj_t self_in, mp_obj_t value) { + i2cioexpander_iopin_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + if (value == MP_ROM_PTR(&digitalio_direction_input_obj)) { + check_result(common_hal_i2cioexpander_iopin_switch_to_input(self, PULL_NONE)); + } else if (value == MP_ROM_PTR(&digitalio_direction_output_obj)) { + check_result(common_hal_i2cioexpander_iopin_switch_to_output(self, false, DRIVE_MODE_PUSH_PULL)); + } else { + mp_arg_error_invalid(MP_QSTR_direction); + } + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(i2cioexpander_iopin_set_direction_obj, i2cioexpander_iopin_obj_set_direction); + +MP_PROPERTY_GETSET(i2cioexpander_iopin_direction_obj, + (mp_obj_t)&i2cioexpander_iopin_get_direction_obj, + (mp_obj_t)&i2cioexpander_iopin_set_direction_obj); + +//| value: bool +//| """The digital logic level of the pin.""" +static mp_obj_t i2cioexpander_iopin_obj_get_value(mp_obj_t self_in) { + i2cioexpander_iopin_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + bool value; + mp_negative_errno_t res = common_hal_i2cioexpander_iopin_get_value(self, &value); + if (res != 0) { + mp_raise_OSError(-res); + } + return mp_obj_new_bool(value); +} +MP_DEFINE_CONST_FUN_OBJ_1(i2cioexpander_iopin_get_value_obj, i2cioexpander_iopin_obj_get_value); + +static mp_obj_t i2cioexpander_iopin_obj_set_value(mp_obj_t self_in, mp_obj_t value) { + i2cioexpander_iopin_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + if (common_hal_i2cioexpander_iopin_get_direction(self) == DIRECTION_INPUT) { + mp_raise_AttributeError(MP_ERROR_TEXT("Cannot set value when direction is input.")); + return mp_const_none; + } + mp_negative_errno_t res = common_hal_i2cioexpander_iopin_set_value(self, mp_obj_is_true(value)); + if (res != 0) { + mp_raise_OSError(-res); + } + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(i2cioexpander_iopin_set_value_obj, i2cioexpander_iopin_obj_set_value); + +MP_PROPERTY_GETSET(i2cioexpander_iopin_value_obj, + (mp_obj_t)&i2cioexpander_iopin_get_value_obj, + (mp_obj_t)&i2cioexpander_iopin_set_value_obj); + +//| drive_mode: digitalio.DriveMode +//| """The pin drive mode.""" +static mp_obj_t i2cioexpander_iopin_obj_get_drive_mode(mp_obj_t self_in) { + i2cioexpander_iopin_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + if (common_hal_i2cioexpander_iopin_get_direction(self) == DIRECTION_INPUT) { + mp_raise_AttributeError(MP_ERROR_TEXT("Drive mode not used when direction is input.")); + return mp_const_none; + } + digitalio_drive_mode_t drive_mode = common_hal_i2cioexpander_iopin_get_drive_mode(self); + if (drive_mode == DRIVE_MODE_PUSH_PULL) { + return MP_OBJ_FROM_PTR(&digitalio_drive_mode_push_pull_obj); + } + return MP_OBJ_FROM_PTR(&digitalio_drive_mode_open_drain_obj); +} +MP_DEFINE_CONST_FUN_OBJ_1(i2cioexpander_iopin_get_drive_mode_obj, i2cioexpander_iopin_obj_get_drive_mode); + +static mp_obj_t i2cioexpander_iopin_obj_set_drive_mode(mp_obj_t self_in, mp_obj_t drive_mode) { + i2cioexpander_iopin_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + if (common_hal_i2cioexpander_iopin_get_direction(self) == DIRECTION_INPUT) { + mp_raise_AttributeError(MP_ERROR_TEXT("Drive mode not used when direction is input.")); + return mp_const_none; + } + digitalio_drive_mode_t c_drive_mode = DRIVE_MODE_PUSH_PULL; + if (drive_mode == MP_ROM_PTR(&digitalio_drive_mode_open_drain_obj)) { + c_drive_mode = DRIVE_MODE_OPEN_DRAIN; + } + check_result(common_hal_i2cioexpander_iopin_set_drive_mode(self, c_drive_mode)); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(i2cioexpander_iopin_set_drive_mode_obj, i2cioexpander_iopin_obj_set_drive_mode); + +MP_PROPERTY_GETSET(i2cioexpander_iopin_drive_mode_obj, + (mp_obj_t)&i2cioexpander_iopin_get_drive_mode_obj, + (mp_obj_t)&i2cioexpander_iopin_set_drive_mode_obj); + +//| pull: Optional[digitalio.Pull] +//| """The pin pull direction.""" +static mp_obj_t i2cioexpander_iopin_obj_get_pull(mp_obj_t self_in) { + i2cioexpander_iopin_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + if (common_hal_i2cioexpander_iopin_get_direction(self) == DIRECTION_OUTPUT) { + mp_raise_AttributeError(MP_ERROR_TEXT("Pull not used when direction is output.")); + return mp_const_none; + } + digitalio_pull_t pull = common_hal_i2cioexpander_iopin_get_pull(self); + if (pull == PULL_UP) { + return MP_OBJ_FROM_PTR(&digitalio_pull_up_obj); + } else if (pull == PULL_DOWN) { + return MP_OBJ_FROM_PTR(&digitalio_pull_down_obj); + } + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_1(i2cioexpander_iopin_get_pull_obj, i2cioexpander_iopin_obj_get_pull); + +static mp_obj_t i2cioexpander_iopin_obj_set_pull(mp_obj_t self_in, mp_obj_t pull_obj) { + i2cioexpander_iopin_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + if (common_hal_i2cioexpander_iopin_get_direction(self) == DIRECTION_OUTPUT) { + mp_raise_AttributeError(MP_ERROR_TEXT("Pull not used when direction is output.")); + return mp_const_none; + } + check_result(common_hal_i2cioexpander_iopin_set_pull(self, validate_pull(pull_obj, MP_QSTR_pull))); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(i2cioexpander_iopin_set_pull_obj, i2cioexpander_iopin_obj_set_pull); + +MP_PROPERTY_GETSET(i2cioexpander_iopin_pull_obj, + (mp_obj_t)&i2cioexpander_iopin_get_pull_obj, + (mp_obj_t)&i2cioexpander_iopin_set_pull_obj); + +// Protocol implementation for DigitalInOutProtocol +static void iopin_protocol_deinit(mp_obj_t self_in) { + i2cioexpander_iopin_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_i2cioexpander_iopin_deinit(self); +} + +static bool iopin_protocol_deinited(mp_obj_t self_in) { + i2cioexpander_iopin_obj_t *self = MP_OBJ_TO_PTR(self_in); + return common_hal_i2cioexpander_iopin_deinited(self); +} + +static digitalinout_result_t iopin_protocol_switch_to_input(mp_obj_t self_in, digitalio_pull_t pull) { + i2cioexpander_iopin_obj_t *self = MP_OBJ_TO_PTR(self_in); + return common_hal_i2cioexpander_iopin_switch_to_input(self, pull); +} + +static digitalinout_result_t iopin_protocol_switch_to_output(mp_obj_t self_in, bool value, digitalio_drive_mode_t drive_mode) { + i2cioexpander_iopin_obj_t *self = MP_OBJ_TO_PTR(self_in); + return common_hal_i2cioexpander_iopin_switch_to_output(self, value, drive_mode); +} + +static digitalio_direction_t iopin_protocol_get_direction(mp_obj_t self_in) { + i2cioexpander_iopin_obj_t *self = MP_OBJ_TO_PTR(self_in); + return common_hal_i2cioexpander_iopin_get_direction(self); +} + +static mp_negative_errno_t iopin_protocol_get_value(mp_obj_t self_in, bool *value) { + i2cioexpander_iopin_obj_t *self = MP_OBJ_TO_PTR(self_in); + return common_hal_i2cioexpander_iopin_get_value(self, value); +} + +static mp_negative_errno_t iopin_protocol_set_value(mp_obj_t self_in, bool value) { + i2cioexpander_iopin_obj_t *self = MP_OBJ_TO_PTR(self_in); + return common_hal_i2cioexpander_iopin_set_value(self, value); +} + +static digitalio_drive_mode_t iopin_protocol_get_drive_mode(mp_obj_t self_in) { + i2cioexpander_iopin_obj_t *self = MP_OBJ_TO_PTR(self_in); + return common_hal_i2cioexpander_iopin_get_drive_mode(self); +} + +static digitalinout_result_t iopin_protocol_set_drive_mode(mp_obj_t self_in, digitalio_drive_mode_t drive_mode) { + i2cioexpander_iopin_obj_t *self = MP_OBJ_TO_PTR(self_in); + return common_hal_i2cioexpander_iopin_set_drive_mode(self, drive_mode); +} + +static digitalio_pull_t iopin_protocol_get_pull(mp_obj_t self_in) { + i2cioexpander_iopin_obj_t *self = MP_OBJ_TO_PTR(self_in); + return common_hal_i2cioexpander_iopin_get_pull(self); +} + +static digitalinout_result_t iopin_protocol_set_pull(mp_obj_t self_in, digitalio_pull_t pull) { + i2cioexpander_iopin_obj_t *self = MP_OBJ_TO_PTR(self_in); + return common_hal_i2cioexpander_iopin_set_pull(self, pull); +} + +static const digitalinout_p_t iopin_digitalinout_p = { + MP_PROTO_IMPLEMENT(MP_QSTR_DigitalInOut) + .deinit = iopin_protocol_deinit, + .deinited = iopin_protocol_deinited, + .switch_to_input = iopin_protocol_switch_to_input, + .switch_to_output = iopin_protocol_switch_to_output, + .get_direction = iopin_protocol_get_direction, + .get_value = iopin_protocol_get_value, + .set_value = iopin_protocol_set_value, + .get_drive_mode = iopin_protocol_get_drive_mode, + .set_drive_mode = iopin_protocol_set_drive_mode, + .get_pull = iopin_protocol_get_pull, + .set_pull = iopin_protocol_set_pull, +}; + +static const mp_rom_map_elem_t i2cioexpander_iopin_locals_dict_table[] = { + // Methods + { MP_ROM_QSTR(MP_QSTR_switch_to_input), MP_ROM_PTR(&i2cioexpander_iopin_switch_to_input_obj) }, + { MP_ROM_QSTR(MP_QSTR_switch_to_output), MP_ROM_PTR(&i2cioexpander_iopin_switch_to_output_obj) }, + + // Properties + { MP_ROM_QSTR(MP_QSTR_direction), MP_ROM_PTR(&i2cioexpander_iopin_direction_obj) }, + { MP_ROM_QSTR(MP_QSTR_value), MP_ROM_PTR(&i2cioexpander_iopin_value_obj) }, + { MP_ROM_QSTR(MP_QSTR_drive_mode), MP_ROM_PTR(&i2cioexpander_iopin_drive_mode_obj) }, + { MP_ROM_QSTR(MP_QSTR_pull), MP_ROM_PTR(&i2cioexpander_iopin_pull_obj) }, +}; +static MP_DEFINE_CONST_DICT(i2cioexpander_iopin_locals_dict, i2cioexpander_iopin_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + i2cioexpander_iopin_type, + MP_QSTR_IOPin, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + protocol, &iopin_digitalinout_p, + locals_dict, &i2cioexpander_iopin_locals_dict + ); diff --git a/shared-bindings/i2cioexpander/IOPin.h b/shared-bindings/i2cioexpander/IOPin.h new file mode 100644 index 00000000000..c8155c71aa1 --- /dev/null +++ b/shared-bindings/i2cioexpander/IOPin.h @@ -0,0 +1,46 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" +#include "shared-module/i2cioexpander/IOPin.h" + +extern const mp_obj_type_t i2cioexpander_iopin_type; + +mp_negative_errno_t i2cioexpander_iopin_construct( + i2cioexpander_iopin_obj_t *self, + i2cioexpander_ioexpander_obj_t *expander, + uint8_t pin_number); + +void common_hal_i2cioexpander_iopin_deinit(i2cioexpander_iopin_obj_t *self); +bool common_hal_i2cioexpander_iopin_deinited(i2cioexpander_iopin_obj_t *self); + +digitalinout_result_t common_hal_i2cioexpander_iopin_switch_to_input( + i2cioexpander_iopin_obj_t *self, + digitalio_pull_t pull); + +digitalinout_result_t common_hal_i2cioexpander_iopin_switch_to_output( + i2cioexpander_iopin_obj_t *self, + bool value, + digitalio_drive_mode_t drive_mode); + +digitalio_direction_t common_hal_i2cioexpander_iopin_get_direction(i2cioexpander_iopin_obj_t *self); + +mp_negative_errno_t common_hal_i2cioexpander_iopin_set_value(i2cioexpander_iopin_obj_t *self, bool value); +mp_negative_errno_t common_hal_i2cioexpander_iopin_get_value(i2cioexpander_iopin_obj_t *self, bool *value); + +digitalinout_result_t common_hal_i2cioexpander_iopin_set_drive_mode( + i2cioexpander_iopin_obj_t *self, + digitalio_drive_mode_t drive_mode); + +digitalio_drive_mode_t common_hal_i2cioexpander_iopin_get_drive_mode(i2cioexpander_iopin_obj_t *self); + +digitalinout_result_t common_hal_i2cioexpander_iopin_set_pull( + i2cioexpander_iopin_obj_t *self, + digitalio_pull_t pull); + +digitalio_pull_t common_hal_i2cioexpander_iopin_get_pull(i2cioexpander_iopin_obj_t *self); diff --git a/shared-bindings/i2cioexpander/__init__.c b/shared-bindings/i2cioexpander/__init__.c new file mode 100644 index 00000000000..106c45c3768 --- /dev/null +++ b/shared-bindings/i2cioexpander/__init__.c @@ -0,0 +1,49 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include + +#include "py/obj.h" +#include "py/runtime.h" + +#include "shared-bindings/i2cioexpander/__init__.h" +#include "shared-bindings/i2cioexpander/IOExpander.h" + +//| """Support for I2C-based GPIO expanders +//| +//| The `i2cioexpander` module contains classes to support I2C-based GPIO expanders +//| that can be controlled via simple register reads and writes. +//| +//| All classes change hardware state and should be deinitialized when they +//| are no longer needed if the program continues after use. To do so, either +//| call :py:meth:`!deinit` or use a context manager. See +//| :ref:`lifetime-and-contextmanagers` for more info. +//| +//| Example:: +//| +//| import board +//| import busio +//| import i2cioexpander +//| +//| i2c = busio.I2C(board.SCL, board.SDA) +//| expander = i2cioexpander.IOExpander(i2c, 0x20, 8, 0x01, 0x00, 0x03) +//| pin0 = expander.pins[0] +//| pin0.switch_to_output(value=True) +//| """ + +static const mp_rom_map_elem_t i2cioexpander_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_i2cioexpander) }, + { MP_ROM_QSTR(MP_QSTR_IOExpander), MP_ROM_PTR(&i2cioexpander_ioexpander_type) }, +}; + +static MP_DEFINE_CONST_DICT(i2cioexpander_module_globals, i2cioexpander_module_globals_table); + +const mp_obj_module_t i2cioexpander_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&i2cioexpander_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_i2cioexpander, i2cioexpander_module); diff --git a/shared-bindings/i2cioexpander/__init__.h b/shared-bindings/i2cioexpander/__init__.h new file mode 100644 index 00000000000..e0d06686868 --- /dev/null +++ b/shared-bindings/i2cioexpander/__init__.h @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Nothing now. diff --git a/shared-bindings/i2ctarget/I2CTarget.c b/shared-bindings/i2ctarget/I2CTarget.c index 728d9f60e27..603080779c8 100644 --- a/shared-bindings/i2ctarget/I2CTarget.c +++ b/shared-bindings/i2ctarget/I2CTarget.c @@ -21,12 +21,13 @@ static mp_obj_t mp_obj_new_i2ctarget_i2c_target_request(i2ctarget_i2c_target_obj_t *target, uint8_t address, bool is_read, bool is_restart) { i2ctarget_i2c_target_request_obj_t *self = - mp_obj_malloc(i2ctarget_i2c_target_request_obj_t, &i2ctarget_i2c_target_request_type); + mp_obj_malloc_with_finaliser(i2ctarget_i2c_target_request_obj_t, &i2ctarget_i2c_target_request_type); self->target = target; self->address = address; self->is_read = is_read; self->is_restart = is_restart; - return (mp_obj_t)self; + + return MP_OBJ_FROM_PTR(self); } //| class I2CTarget: @@ -50,7 +51,6 @@ static mp_obj_t mp_obj_new_i2ctarget_i2c_target_request(i2ctarget_i2c_target_obj //| ... //| static mp_obj_t i2ctarget_i2c_target_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { - i2ctarget_i2c_target_obj_t *self = mp_obj_malloc_with_finaliser(i2ctarget_i2c_target_obj_t, &i2ctarget_i2c_target_type); enum { ARG_scl, ARG_sda, ARG_addresses, ARG_smbus }; static const mp_arg_t allowed_args[] = { { MP_QSTR_scl, MP_ARG_REQUIRED | MP_ARG_OBJ }, @@ -78,8 +78,10 @@ static mp_obj_t i2ctarget_i2c_target_make_new(const mp_obj_type_t *type, size_t mp_raise_ValueError(MP_ERROR_TEXT("addresses is empty")); } + i2ctarget_i2c_target_obj_t *self = mp_obj_malloc_with_finaliser(i2ctarget_i2c_target_obj_t, &i2ctarget_i2c_target_type); common_hal_i2ctarget_i2c_target_construct(self, scl, sda, addresses, i, args[ARG_smbus].u_bool); - return (mp_obj_t)self; + + return MP_OBJ_FROM_PTR(self); } //| def deinit(self) -> None: @@ -200,7 +202,7 @@ static MP_DEFINE_CONST_DICT(i2ctarget_i2c_target_locals_dict, i2ctarget_i2c_targ MP_DEFINE_CONST_OBJ_TYPE( i2ctarget_i2c_target_type, MP_QSTR_I2CTarget, - MP_TYPE_FLAG_NONE, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, make_new, i2ctarget_i2c_target_make_new, locals_dict, &i2ctarget_i2c_target_locals_dict ); @@ -222,23 +224,50 @@ static mp_obj_t i2ctarget_i2c_target_request_make_new(const mp_obj_type_t *type, return mp_obj_new_i2ctarget_i2c_target_request(args[0], mp_obj_get_int(args[1]), mp_obj_is_true(args[2]), mp_obj_is_true(args[3])); } -//| def __enter__(self) -> I2CTargetRequest: -//| """No-op used in Context Managers.""" -//| ... -//| -// Provided by context manager helper. +static void target_request_check_for_deinit(i2ctarget_i2c_target_request_obj_t *self) { + if (self->target == NULL) { + raise_deinited_error(); + } + check_for_deinit(self->target); +} -//| def __exit__(self) -> None: -//| """Close the request.""" +//| def deinit(self) -> None: +//| """Disconnects from parent `I2CTarget`. +//| Called by `__exit__()` to indicate the `I2CTargetRequest` is no longer useful.""" //| ... //| -// Provided by context manager helper. +static mp_obj_t i2ctarget_i2c_target_request_deinit(mp_obj_t self_in) { + i2ctarget_i2c_target_request_obj_t *self = MP_OBJ_TO_PTR(self_in); + target_request_check_for_deinit(self); + + i2ctarget_i2c_target_obj_t *target = self->target; + + // Deinit I2CTargetRequest first in case _close() fails. + self->target = NULL; + + common_hal_i2ctarget_i2c_target_close(target); + + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_1(i2ctarget_i2c_target_request_deinit_obj, i2ctarget_i2c_target_request_deinit); + +// The finaliser. Unlike deinit(), do nothing if the request or its target is already deinited: +// the target may have been finalised first. +static mp_obj_t i2ctarget_i2c_target_request_del(mp_obj_t self_in) { + i2ctarget_i2c_target_request_obj_t *self = MP_OBJ_TO_PTR(self_in); + if (self->target == NULL || common_hal_i2ctarget_i2c_target_deinited(self->target)) { + self->target = NULL; + return mp_const_none; + } + return i2ctarget_i2c_target_request_deinit(self_in); +} +static MP_DEFINE_CONST_FUN_OBJ_1(i2ctarget_i2c_target_request_del_obj, i2ctarget_i2c_target_request_del); //| address: int //| """The I2C address of the request.""" static mp_obj_t i2ctarget_i2c_target_request_get_address(mp_obj_t self_in) { i2ctarget_i2c_target_request_obj_t *self = MP_OBJ_TO_PTR(self_in); - check_for_deinit(self->target); + target_request_check_for_deinit(self); return mp_obj_new_int(self->address); } @@ -248,7 +277,7 @@ MP_DEFINE_CONST_PROP_GET(i2ctarget_i2c_target_request_address_obj, i2ctarget_i2c //| """The I2C main controller is reading from this target.""" static mp_obj_t i2ctarget_i2c_target_request_get_is_read(mp_obj_t self_in) { i2ctarget_i2c_target_request_obj_t *self = MP_OBJ_TO_PTR(self_in); - check_for_deinit(self->target); + target_request_check_for_deinit(self); return mp_obj_new_bool(self->is_read); } @@ -259,7 +288,7 @@ MP_DEFINE_CONST_PROP_GET(i2ctarget_i2c_target_request_is_read_obj, i2ctarget_i2c //| static mp_obj_t i2ctarget_i2c_target_request_get_is_restart(mp_obj_t self_in) { i2ctarget_i2c_target_request_obj_t *self = MP_OBJ_TO_PTR(self_in); - check_for_deinit(self->target); + target_request_check_for_deinit(self); return mp_obj_new_bool(self->is_restart); } @@ -276,7 +305,7 @@ MP_DEFINE_CONST_PROP_GET(i2ctarget_i2c_target_request_is_restart_obj, i2ctarget_ //| static mp_obj_t i2ctarget_i2c_target_request_read(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { i2ctarget_i2c_target_request_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]); - check_for_deinit(self->target); + target_request_check_for_deinit(self); enum { ARG_n, ARG_ack }; static const mp_arg_t allowed_args[] = { @@ -335,7 +364,7 @@ MP_DEFINE_CONST_FUN_OBJ_KW(i2ctarget_i2c_target_request_read_obj, 1, i2ctarget_i //| static mp_obj_t i2ctarget_i2c_target_request_write(mp_obj_t self_in, mp_obj_t buf_in) { i2ctarget_i2c_target_request_obj_t *self = MP_OBJ_TO_PTR(self_in); - check_for_deinit(self->target); + target_request_check_for_deinit(self); if (!self->is_read) { mp_raise_OSError(MP_EACCES); @@ -370,7 +399,7 @@ static MP_DEFINE_CONST_FUN_OBJ_2(i2ctarget_i2c_target_request_write_obj, i2ctarg //| static mp_obj_t i2ctarget_i2c_target_request_ack(uint n_args, const mp_obj_t *args) { i2ctarget_i2c_target_request_obj_t *self = MP_OBJ_TO_PTR(args[0]); - check_for_deinit(self->target); + target_request_check_for_deinit(self); bool ack = (n_args == 1) ? true : mp_obj_is_true(args[1]); @@ -383,25 +412,29 @@ static mp_obj_t i2ctarget_i2c_target_request_ack(uint n_args, const mp_obj_t *ar } MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(i2ctarget_i2c_target_request_ack_obj, 1, 2, i2ctarget_i2c_target_request_ack); -static mp_obj_t i2ctarget_i2c_target_request_close(mp_obj_t self_in) { - i2ctarget_i2c_target_request_obj_t *self = MP_OBJ_TO_PTR(self_in); - check_for_deinit(self->target); +//| def __enter__(self) -> I2CTargetRequest: +//| """No-op used in Context Managers.""" +//| ... +//| +// Provided by context manager helper. - common_hal_i2ctarget_i2c_target_close(self->target); - return mp_const_none; -} -static MP_DEFINE_CONST_FUN_OBJ_1(i2ctarget_i2c_target_request_close_obj, i2ctarget_i2c_target_request_close); +//| def __exit__(self) -> None: +//| """Close and deinit the request.""" +//| ... +//| +// Provided by context manager helper. static const mp_rom_map_elem_t i2ctarget_i2c_target_request_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&i2ctarget_i2c_target_request_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&i2ctarget_i2c_target_request_del_obj) }, { MP_ROM_QSTR(MP_QSTR_address), MP_ROM_PTR(&i2ctarget_i2c_target_request_address_obj) }, { MP_ROM_QSTR(MP_QSTR_is_read), MP_ROM_PTR(&i2ctarget_i2c_target_request_is_read_obj) }, { MP_ROM_QSTR(MP_QSTR_is_restart), MP_ROM_PTR(&i2ctarget_i2c_target_request_is_restart_obj) }, { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&i2ctarget_i2c_target_request_read_obj) }, { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&i2ctarget_i2c_target_request_write_obj) }, { MP_ROM_QSTR(MP_QSTR_ack), MP_ROM_PTR(&i2ctarget_i2c_target_request_ack_obj) }, - { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&i2ctarget_i2c_target_request_close_obj) }, }; static MP_DEFINE_CONST_DICT(i2ctarget_i2c_target_request_locals_dict, i2ctarget_i2c_target_request_locals_dict_table); diff --git a/shared-bindings/imagecapture/ParallelImageCapture.c b/shared-bindings/imagecapture/ParallelImageCapture.c index 866edb489ce..025a2a225fb 100644 --- a/shared-bindings/imagecapture/ParallelImageCapture.c +++ b/shared-bindings/imagecapture/ParallelImageCapture.c @@ -48,17 +48,16 @@ static mp_obj_t imagecapture_parallelimagecapture_make_new(const mp_obj_type_t * MP_STATIC_ASSERT(MP_ARRAY_SIZE(allowed_args) == NUM_ARGS); mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); - uint8_t pins[32]; + const mcu_pin_obj_t *pins[32]; uint8_t pin_count; - validate_pins(MP_QSTR_data, pins, MP_ARRAY_SIZE(pins), args[ARG_data_pins].u_obj, &pin_count); + validate_list_is_free_pins(MP_QSTR_data, pins, MP_ARRAY_SIZE(pins), args[ARG_data_pins].u_obj, &pin_count); const mcu_pin_obj_t *clock = validate_obj_is_free_pin(args[ARG_clock].u_obj, MP_QSTR_clock); const mcu_pin_obj_t *vsync = validate_obj_is_free_pin_or_none(args[ARG_vsync].u_obj, MP_QSTR_vsync); const mcu_pin_obj_t *href = validate_obj_is_free_pin_or_none(args[ARG_href].u_obj, MP_QSTR_href); imagecapture_parallelimagecapture_obj_t *self = - mp_obj_malloc(imagecapture_parallelimagecapture_obj_t, &imagecapture_parallelimagecapture_type); - + mp_obj_malloc_with_finaliser(imagecapture_parallelimagecapture_obj_t, &imagecapture_parallelimagecapture_type); common_hal_imagecapture_parallelimagecapture_construct(self, pins, pin_count, clock, vsync, href); return self; @@ -159,6 +158,7 @@ static MP_DEFINE_CONST_FUN_OBJ_1(imagecapture_parallelimagecapture_deinit_obj, i 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___del__), 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(&default___exit___obj) }, diff --git a/shared-bindings/imagecapture/ParallelImageCapture.h b/shared-bindings/imagecapture/ParallelImageCapture.h index fddd2cb2763..ed782e246d4 100644 --- a/shared-bindings/imagecapture/ParallelImageCapture.h +++ b/shared-bindings/imagecapture/ParallelImageCapture.h @@ -13,7 +13,7 @@ extern const mp_obj_type_t imagecapture_parallelimagecapture_type; // if only the first element of data_pins is non-NULL, the pins are sequential in microcontroller pin numbering. void common_hal_imagecapture_parallelimagecapture_construct(imagecapture_parallelimagecapture_obj_t *self, - const uint8_t data_pins[], + const mcu_pin_obj_t **data_pins, uint8_t data_count, const mcu_pin_obj_t *data_clock, const mcu_pin_obj_t *vertical_sync, diff --git a/shared-bindings/ipaddress/IPv4Address.c b/shared-bindings/ipaddress/IPv4Address.c index 5aab02e9f5c..6c11f528506 100644 --- a/shared-bindings/ipaddress/IPv4Address.c +++ b/shared-bindings/ipaddress/IPv4Address.c @@ -38,8 +38,10 @@ static mp_obj_t ipaddress_ipv4address_make_new(const mp_obj_type_t *type, size_t uint32_t value; uint8_t *buf = NULL; - if (mp_obj_get_int_maybe(address, (mp_int_t *)&value)) { + mp_int_t int_value; + if (mp_obj_get_int_maybe(address, &int_value)) { // We're done. + value = (uint32_t)int_value; buf = (uint8_t *)&value; } else if (mp_obj_is_str(address)) { GET_STR_DATA_LEN(address, str_data, str_len); @@ -49,17 +51,17 @@ static mp_obj_t ipaddress_ipv4address_make_new(const mp_obj_type_t *type, size_t buf = (uint8_t *)&value; } else { mp_buffer_info_t buf_info; - if (mp_get_buffer(address, &buf_info, MP_BUFFER_READ)) { - if (buf_info.len != 4) { - mp_raise_ValueError_varg(MP_ERROR_TEXT("Address must be %d bytes long"), 4); - } - buf = buf_info.buf; + if (!mp_get_buffer(address, &buf_info, MP_BUFFER_READ)) { + mp_arg_error_invalid(MP_QSTR_address); + } + if (buf_info.len != 4) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("Address must be %d bytes long"), 4); } + buf = buf_info.buf; } ipaddress_ipv4address_obj_t *self = mp_obj_malloc(ipaddress_ipv4address_obj_t, &ipaddress_ipv4address_type); - common_hal_ipaddress_ipv4address_construct(self, buf, 4); return MP_OBJ_FROM_PTR(self); diff --git a/shared-bindings/ipaddress/__init__.c b/shared-bindings/ipaddress/__init__.c index 60bc6226ba1..db8d22948a1 100644 --- a/shared-bindings/ipaddress/__init__.c +++ b/shared-bindings/ipaddress/__init__.c @@ -30,7 +30,7 @@ bool ipaddress_parse_ipv4address(const char *str_data, size_t str_len, uint32_t period_count++; } } - if (period_count > 3) { + if (period_count != 3) { return false; } @@ -50,7 +50,13 @@ bool ipaddress_parse_ipv4address(const char *str_data, size_t str_len, uint32_t } last_period = period_index[i] + 1; if (ip_out != NULL) { + if (!mp_obj_is_small_int(octet)) { + return false; + } mp_int_t int_octet = MP_OBJ_SMALL_INT_VALUE(octet); + if (int_octet < 0 || int_octet > 255) { + return false; + } *ip_out |= int_octet << (i * 8); } } diff --git a/shared-bindings/is31fl3741/FrameBuffer.c b/shared-bindings/is31fl3741/FrameBuffer.c index b59c7360f8b..7f0422ed20e 100644 --- a/shared-bindings/is31fl3741/FrameBuffer.c +++ b/shared-bindings/is31fl3741/FrameBuffer.c @@ -66,26 +66,43 @@ static mp_obj_t is31fl3741_framebuffer_make_new(const mp_obj_type_t *type, size_ mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); - is31fl3741_framebuffer_obj_t *self = &allocate_display_bus_or_raise()->is31fl3741; - self->base.type = &is31fl3741_framebuffer_type; + // Validate everything before taking a display bus slot. Once the slot has a type, + // release_displays() deinits it, even if construct never ran. + is31fl3741_IS31FL3741_obj_t *is31 = MP_OBJ_TO_PTR(mp_arg_validate_type(args[ARG_is31].u_obj, &is31fl3741_IS31FL3741_type, MP_QSTR_is31)); + if (common_hal_is31fl3741_IS31FL3741_deinited(is31)) { + raise_deinited_error(); + } if (args[ARG_width].u_int <= 0) { mp_raise_ValueError(MP_ERROR_TEXT("width must be greater than zero")); } - self->scale = args[ARG_scale].u_bool; - if (self->scale) { + bool scale = args[ARG_scale].u_bool; + int scale_width = args[ARG_width].u_int; + int scale_height = args[ARG_height].u_int; + if (scale) { if (((args[ARG_height].u_int % 3) != 0) || ((args[ARG_width].u_int % 3) != 0)) { mp_raise_ValueError(MP_ERROR_TEXT("Scale dimensions must divide by 3")); } - self->scale_width = args[ARG_width].u_int / 3; - self->scale_height = args[ARG_height].u_int / 3; - } else { - self->scale_width = args[ARG_width].u_int; - self->scale_height = args[ARG_height].u_int; + scale_width /= 3; + scale_height /= 3; } + size_t mapping_len; + mp_obj_t *mapping_items; + mp_arg_validate_type(args[ARG_mapping].u_obj, &mp_type_tuple, MP_QSTR_mapping); + mp_obj_tuple_get(args[ARG_mapping].u_obj, &mapping_len, &mapping_items); + if (mapping_len != (size_t)(scale_width * scale_height * 3)) { + mp_raise_ValueError(MP_ERROR_TEXT("LED mappings must match display size")); + } + + is31fl3741_framebuffer_obj_t *self = &allocate_display_bus_or_raise()->is31fl3741; + self->base.type = &is31fl3741_framebuffer_type; + + self->scale = scale; + self->scale_width = scale_width; + self->scale_height = scale_height; self->auto_gamma = args[ARG_gamma].u_bool; mp_obj_t framebuffer = args[ARG_framebuffer].u_obj; @@ -121,7 +138,7 @@ static mp_obj_t is31fl3741_framebuffer_deinit(mp_obj_t self_in) { static MP_DEFINE_CONST_FUN_OBJ_1(is31fl3741_framebuffer_deinit_obj, is31fl3741_framebuffer_deinit); static void check_for_deinit(is31fl3741_framebuffer_obj_t *self) { - if (self->framebuffer == NULL) { + if (self->framebuffer == NULL || common_hal_is31fl3741_IS31FL3741_deinited(self->is31fl3741)) { raise_deinited_error(); } } @@ -198,6 +215,7 @@ MP_PROPERTY_GETTER(is31fl3741_framebuffer_height_obj, static const mp_rom_map_elem_t is31fl3741_framebuffer_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&is31fl3741_framebuffer_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&is31fl3741_framebuffer_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR_brightness), MP_ROM_PTR(&is31fl3741_framebuffer_brightness_obj) }, { MP_ROM_QSTR(MP_QSTR_refresh), MP_ROM_PTR(&is31fl3741_framebuffer_refresh_obj) }, { MP_ROM_QSTR(MP_QSTR_width), MP_ROM_PTR(&is31fl3741_framebuffer_width_obj) }, diff --git a/shared-bindings/is31fl3741/IS31FL3741.c b/shared-bindings/is31fl3741/IS31FL3741.c index 0c6b3479b04..a7c118d7281 100644 --- a/shared-bindings/is31fl3741/IS31FL3741.c +++ b/shared-bindings/is31fl3741/IS31FL3741.c @@ -37,8 +37,7 @@ static mp_obj_t is31fl3741_IS31FL3741_make_new(const mp_obj_type_t *type, size_t mp_obj_t i2c = mp_arg_validate_type(args[ARG_i2c].u_obj, &busio_i2c_type, MP_QSTR_i2c_bus); - is31fl3741_IS31FL3741_obj_t *self = mp_obj_malloc(is31fl3741_IS31FL3741_obj_t, &is31fl3741_IS31FL3741_type); - + is31fl3741_IS31FL3741_obj_t *self = mp_obj_malloc_with_finaliser(is31fl3741_IS31FL3741_obj_t, &is31fl3741_IS31FL3741_type); common_hal_is31fl3741_IS31FL3741_construct(self, MP_OBJ_TO_PTR(i2c), args[ARG_addr].u_int @@ -61,6 +60,12 @@ static mp_obj_t is31fl3741_IS31FL3741_deinit(mp_obj_t self_in) { } static MP_DEFINE_CONST_FUN_OBJ_1(is31fl3741_IS31FL3741_deinit_obj, is31fl3741_IS31FL3741_deinit); +static void check_for_deinit(is31fl3741_IS31FL3741_obj_t *self) { + if (common_hal_is31fl3741_IS31FL3741_deinited(self)) { + raise_deinited_error(); + } +} + //| def reset(self) -> None: //| """Resets the IS31FL3741 chip.""" //| ... @@ -68,6 +73,7 @@ static MP_DEFINE_CONST_FUN_OBJ_1(is31fl3741_IS31FL3741_deinit_obj, is31fl3741_IS //| static mp_obj_t is31fl3741_IS31FL3741_reset(mp_obj_t self_in) { is31fl3741_IS31FL3741_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); common_hal_is31fl3741_send_reset(self); return mp_const_none; } @@ -80,6 +86,7 @@ MP_DEFINE_CONST_FUN_OBJ_1(is31fl3741_IS31FL3741_reset_obj, is31fl3741_IS31FL3741 //| static mp_obj_t is31fl3741_IS31FL3741_enable(mp_obj_t self_in) { is31fl3741_IS31FL3741_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); common_hal_is31fl3741_send_enable(self); return mp_const_none; } @@ -94,6 +101,7 @@ MP_DEFINE_CONST_FUN_OBJ_1(is31fl3741_IS31FL3741_enable_obj, is31fl3741_IS31FL374 //| static mp_obj_t is31fl3741_IS31FL3741_set_global_current(mp_obj_t self_in, mp_obj_t value) { is31fl3741_IS31FL3741_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); mp_int_t current = mp_obj_get_int(value); common_hal_is31fl3741_set_current(self, current); return mp_const_none; @@ -113,6 +121,7 @@ MP_DEFINE_CONST_FUN_OBJ_2(is31fl3741_IS31FL3741_set_global_current_obj, is31fl37 //| static mp_obj_t is31fl3741_IS31FL3741_set_led(size_t n_args, const mp_obj_t *args) { is31fl3741_IS31FL3741_obj_t *self = MP_OBJ_TO_PTR(args[0]); + check_for_deinit(self); mp_int_t led = mp_obj_get_int(args[1]); mp_int_t value = mp_obj_get_int(args[2]); mp_int_t page = mp_obj_get_int(args[3]); @@ -132,6 +141,7 @@ MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(is31fl3741_IS31FL3741_set_led_obj, 4, 4, is3 //| static mp_obj_t is31fl3741_IS31FL3741_write(mp_obj_t self_in, mp_obj_t mapping, mp_obj_t buffer) { is31fl3741_IS31FL3741_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); if (!mp_obj_is_tuple_compatible(mapping)) { mp_raise_ValueError(MP_ERROR_TEXT("Mapping must be a tuple")); } @@ -150,6 +160,7 @@ MP_DEFINE_CONST_FUN_OBJ_3(is31fl3741_IS31FL3741_write_obj, is31fl3741_IS31FL3741 static const mp_rom_map_elem_t is31fl3741_IS31FL3741_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&is31fl3741_IS31FL3741_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&is31fl3741_IS31FL3741_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR_write), (mp_obj_t)&is31fl3741_IS31FL3741_write_obj }, { MP_ROM_QSTR(MP_QSTR_reset), (mp_obj_t)&is31fl3741_IS31FL3741_reset_obj }, { MP_ROM_QSTR(MP_QSTR_enable), (mp_obj_t)&is31fl3741_IS31FL3741_enable_obj }, diff --git a/shared-bindings/is31fl3741/IS31FL3741.h b/shared-bindings/is31fl3741/IS31FL3741.h index 5c6447f78f9..514eee9114f 100644 --- a/shared-bindings/is31fl3741/IS31FL3741.h +++ b/shared-bindings/is31fl3741/IS31FL3741.h @@ -13,6 +13,8 @@ extern const mp_obj_type_t is31fl3741_IS31FL3741_type; void common_hal_is31fl3741_IS31FL3741_construct(is31fl3741_IS31FL3741_obj_t *self, busio_i2c_obj_t *i2c, uint8_t addr); void common_hal_is31fl3741_IS31FL3741_deinit(is31fl3741_IS31FL3741_obj_t *); +bool common_hal_is31fl3741_IS31FL3741_deinited(is31fl3741_IS31FL3741_obj_t *self); +void common_hal_is31fl3741_IS31FL3741_mark_deinit(is31fl3741_IS31FL3741_obj_t *self); void common_hal_is31fl3741_write(is31fl3741_IS31FL3741_obj_t *is31, const mp_obj_t *mapping, const uint8_t *pixels, size_t numBytes); diff --git a/shared-bindings/jpegio/JpegDecoder.c b/shared-bindings/jpegio/JpegDecoder.c index 13287a23650..57141af7d1e 100644 --- a/shared-bindings/jpegio/JpegDecoder.c +++ b/shared-bindings/jpegio/JpegDecoder.c @@ -23,28 +23,39 @@ //| Example:: //| //| from jpegio import JpegDecoder -//| from displayio import Bitmap +//| from displayio import Bitmap, TileGrid, ColorConverter, Colorspace +//| import supervisor //| //| decoder = JpegDecoder() //| width, height = decoder.open("/sd/example.jpg") //| bitmap = Bitmap(width, height, 65535) //| decoder.decode(bitmap) -//| # .. do something with bitmap +//| tg = TileGrid(bitmap, pixel_shader=ColorConverter(input_colorspace=Colorspace.RGB565_SWAPPED)) +//| supervisor.runtime.display.root_group = tg +//| while True: +//| pass +//| //| """ //| -//| def __init__(self) -> None: -//| """Create a JpegDecoder""" +//| def __init__(self, *, software_ok: bool = True) -> None: +//| """Create a JpegDecoder +//| +//| :param bool software_ok: If True, `decode` uses the software decoder when the JPEG +//| decoder peripheral cannot decode the image. If False, `decode` raises `ValueError` +//| instead, including on chips without the peripheral. +//| """ //| ... //| static mp_obj_t jpegio_jpegdecoder_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_software_ok }; static const mp_arg_t allowed_args[] = { + { MP_QSTR_software_ok, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = true} }, }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); - jpegio_jpegdecoder_obj_t *self = mp_obj_malloc(jpegio_jpegdecoder_obj_t, &jpegio_jpegdecoder_type); - self->base.type = &jpegio_jpegdecoder_type; - common_hal_jpegio_jpegdecoder_construct(self); + jpegio_jpegdecoder_obj_t *self = mp_obj_malloc_with_finaliser(jpegio_jpegdecoder_obj_t, &jpegio_jpegdecoder_type); + common_hal_jpegio_jpegdecoder_construct(self, args[ARG_software_ok].u_bool); return MP_OBJ_FROM_PTR(self); } @@ -120,6 +131,17 @@ MP_DEFINE_CONST_FUN_OBJ_2(jpegio_jpegdecoder_open_obj, jpegio_jpegdecoder_open); //| possible to repeatedly ``decode`` the same jpeg data, even if it is to //| select different scales or crop regions from it. //| +//| On chips with a JPEG decoder peripheral (ESP32-P4 and ESP32-S31), ``decode`` +//| uses the peripheral for baseline color JPEGs when the data was opened from a +//| buffer in DMA-capable memory, ``scale`` is 0, ``bitmap`` holds 16-bit values, +//| and no skip index is given. It is fastest when ``bitmap`` is exactly the image +//| size and the whole image is decoded at 0,0. Colors may differ slightly from the +//| software decoder's. Other images, and data opened from a file or stream, use +//| the software decoder, or raise `ValueError` if ``software_ok`` is False. +//| +//| Some builds use a faster decoder for common JPEG types. Colors may differ slightly +//| between decoders. +//| //| :param Bitmap bitmap: Optional output buffer //| :param int scale: Scale factor from 0 to 3, inclusive. //| :param int x: Horizontal pixel location in bitmap where source_bitmap upper-left @@ -137,7 +159,7 @@ MP_DEFINE_CONST_FUN_OBJ_2(jpegio_jpegdecoder_open_obj, jpegio_jpegdecoder_open); //| """ //| //| -static mp_obj_t jpegio_jpegdecoder_decode(mp_uint_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { +static mp_obj_t jpegio_jpegdecoder_decode(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { jpegio_jpegdecoder_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]); enum { ARG_bitmap, ARG_scale, ARG_x, ARG_y, ARGS_X1_Y1_X2_Y2, ARG_skip_source_index, ARG_skip_dest_index }; @@ -191,9 +213,22 @@ static mp_obj_t jpegio_jpegdecoder_decode(mp_uint_t n_args, const mp_obj_t *pos_ } static MP_DEFINE_CONST_FUN_OBJ_KW(jpegio_jpegdecoder_decode_obj, 1, jpegio_jpegdecoder_decode); +//| def deinit(self) -> None: +//| """Release any hardware decoder this object holds. Also called when the object is collected.""" +//| ... +//| +static mp_obj_t jpegio_jpegdecoder_deinit(mp_obj_t self_in) { + jpegio_jpegdecoder_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_jpegio_jpegdecoder_deinit(self); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(jpegio_jpegdecoder_deinit_obj, jpegio_jpegdecoder_deinit); + static const mp_rom_map_elem_t jpegio_jpegdecoder_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_open), MP_ROM_PTR(&jpegio_jpegdecoder_open_obj) }, { MP_ROM_QSTR(MP_QSTR_decode), MP_ROM_PTR(&jpegio_jpegdecoder_decode_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&jpegio_jpegdecoder_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&jpegio_jpegdecoder_deinit_obj) }, }; static MP_DEFINE_CONST_DICT(jpegio_jpegdecoder_locals_dict, jpegio_jpegdecoder_locals_dict_table); diff --git a/shared-bindings/jpegio/JpegDecoder.h b/shared-bindings/jpegio/JpegDecoder.h index 560586a871e..98e7216d74a 100644 --- a/shared-bindings/jpegio/JpegDecoder.h +++ b/shared-bindings/jpegio/JpegDecoder.h @@ -15,7 +15,8 @@ extern const mp_obj_type_t jpegio_jpegdecoder_type; typedef struct jpegio_jpegdecoder_obj jpegio_jpegdecoder_obj_t; -void common_hal_jpegio_jpegdecoder_construct(jpegio_jpegdecoder_obj_t *self); +void common_hal_jpegio_jpegdecoder_construct(jpegio_jpegdecoder_obj_t *self, bool software_ok); +void common_hal_jpegio_jpegdecoder_deinit(jpegio_jpegdecoder_obj_t *self); void common_hal_jpegio_jpegdecoder_close(jpegio_jpegdecoder_obj_t *self); mp_obj_t common_hal_jpegio_jpegdecoder_set_source_buffer(jpegio_jpegdecoder_obj_t *self, mp_obj_t jpeg_data); mp_obj_t common_hal_jpegio_jpegdecoder_set_source_file(jpegio_jpegdecoder_obj_t *self, mp_obj_t file_obj); diff --git a/shared-bindings/keypad/Event.c b/shared-bindings/keypad/Event.c index 51e446e8362..f83e01e785e 100644 --- a/shared-bindings/keypad/Event.c +++ b/shared-bindings/keypad/Event.c @@ -26,7 +26,6 @@ //| ... //| static mp_obj_t keypad_event_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { - keypad_event_obj_t *self = mp_obj_malloc(keypad_event_obj_t, &keypad_event_type); enum { ARG_key_number, ARG_pressed, ARG_timestamp }; static const mp_arg_t allowed_args[] = { { MP_QSTR_key_number, MP_ARG_INT, {.u_int = 0} }, @@ -45,7 +44,9 @@ static mp_obj_t keypad_event_make_new(const mp_obj_type_t *type, size_t n_args, } (void)mp_obj_get_int_truncated(timestamp); // ensure that timestamp is an integer + keypad_event_obj_t *self = mp_obj_malloc(keypad_event_obj_t, &keypad_event_type); common_hal_keypad_event_construct(self, key_number, args[ARG_pressed].u_bool, timestamp); + return MP_OBJ_FROM_PTR(self); } diff --git a/shared-bindings/keypad/EventQueue.h b/shared-bindings/keypad/EventQueue.h index 893165e3220..02c3414b076 100644 --- a/shared-bindings/keypad/EventQueue.h +++ b/shared-bindings/keypad/EventQueue.h @@ -11,7 +11,7 @@ extern const mp_obj_type_t keypad_eventqueue_type; -void common_hal_keypad_eventqueue_construct(keypad_eventqueue_obj_t *self, size_t max_events); +void common_hal_keypad_eventqueue_construct(keypad_eventqueue_obj_t *self, size_t max_events, bool use_gc_allocator); void common_hal_keypad_eventqueue_clear(keypad_eventqueue_obj_t *self); size_t common_hal_keypad_eventqueue_get_length(keypad_eventqueue_obj_t *self); diff --git a/shared-bindings/keypad/KeyMatrix.c b/shared-bindings/keypad/KeyMatrix.c index 8303645f201..262c86fd77e 100644 --- a/shared-bindings/keypad/KeyMatrix.c +++ b/shared-bindings/keypad/KeyMatrix.c @@ -67,13 +67,20 @@ //| in the respective state for ``debounce_threshold`` times on average. //| Successive measurements are spaced apart by ``interval`` seconds. //| The default is 1, which resolves immediately. The maximum is 127. +//| +//| .. warning:: On Raspberry Pi RP2350, using ``columns_to_anodes=False`` +//| normally depends on the internal pull-down resistors. +//| This will not work, due to an RP2350 issue. +//| The easiest fix is simply to swap the ``row_pins`` and ```column_pins`` and to set +//| ``columns_to_anodes=True``. This requires no external components. +//| An alternative is to add external pull-downs of 8.2 kohms or less, but that will draw more current. +//| See the Warning in `digitalio` for more information. //| """ //| ... //| static mp_obj_t keypad_keymatrix_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { #if CIRCUITPY_KEYPAD_KEYMATRIX - keypad_keymatrix_obj_t *self = mp_obj_malloc(keypad_keymatrix_obj_t, &keypad_keymatrix_type); enum { ARG_row_pins, ARG_column_pins, ARG_columns_to_anodes, ARG_interval, ARG_max_events, ARG_debounce_threshold }; static const mp_arg_t allowed_args[] = { { MP_QSTR_row_pins, MP_ARG_REQUIRED | MP_ARG_OBJ }, @@ -115,7 +122,9 @@ static mp_obj_t keypad_keymatrix_make_new(const mp_obj_type_t *type, size_t n_ar column_pins_array[column] = pin; } + keypad_keymatrix_obj_t *self = mp_obj_malloc_with_finaliser(keypad_keymatrix_obj_t, &keypad_keymatrix_type); common_hal_keypad_keymatrix_construct(self, num_row_pins, row_pins_array, num_column_pins, column_pins_array, args[ARG_columns_to_anodes].u_bool, interval, max_events, debounce_threshold); + return MP_OBJ_FROM_PTR(self); #else mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_KeyMatrix); @@ -186,7 +195,7 @@ static mp_obj_t keypad_keymatrix_key_number_to_row_column(mp_obj_t self_in, mp_o const mp_uint_t key_number = (mp_uint_t)mp_arg_validate_int_range( mp_obj_get_int(key_number_in), - 0, (mp_int_t)common_hal_keypad_generic_get_key_count(self), + 0, (mp_int_t)common_hal_keypad_generic_get_key_count(self) - 1, MP_QSTR_key_number); mp_uint_t row; @@ -212,10 +221,10 @@ static mp_obj_t keypad_keymatrix_row_column_to_key_number(mp_obj_t self_in, mp_o check_for_deinit(self); const mp_uint_t row = (mp_uint_t)mp_arg_validate_int_range( - mp_obj_get_int(row_in), 0, (mp_int_t)common_hal_keypad_keymatrix_get_row_count(self), MP_QSTR_row); + mp_obj_get_int(row_in), 0, (mp_int_t)common_hal_keypad_keymatrix_get_row_count(self) - 1, MP_QSTR_row); const mp_int_t column = (mp_uint_t)mp_arg_validate_int_range( - mp_obj_get_int(column_in), 0, (mp_int_t)common_hal_keypad_keymatrix_get_column_count(self), MP_QSTR_column); + mp_obj_get_int(column_in), 0, (mp_int_t)common_hal_keypad_keymatrix_get_column_count(self) - 1, MP_QSTR_column); return MP_OBJ_NEW_SMALL_INT( (mp_int_t)common_hal_keypad_keymatrix_row_column_to_key_number(self, row, column)); @@ -230,6 +239,7 @@ MP_DEFINE_CONST_FUN_OBJ_3(keypad_keymatrix_row_column_to_key_number_obj, keypad_ static const mp_rom_map_elem_t keypad_keymatrix_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&keypad_keymatrix_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&keypad_keymatrix_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, diff --git a/shared-bindings/keypad/Keys.c b/shared-bindings/keypad/Keys.c index 10ac81cf1fb..0570e735f16 100644 --- a/shared-bindings/keypad/Keys.c +++ b/shared-bindings/keypad/Keys.c @@ -69,13 +69,18 @@ //| in the respective state for ``debounce_threshold`` times on average. //| Successive measurements are spaced apart by ``interval`` seconds. //| The default is 1, which resolves immediately. The maximum is 127. +//| +//| .. warning:: On Raspberry Pi RP2350, using ``value_when_pressed=True`` and ``pull=True``, +//| to enable using the internal pull-down resistor, will not work, due to an RP2350 +//| hardware issue. Instead, wire the switch to be ``value_when_pressed=False``, or add +//| an external pull-down resistor of 8.2 kohms or less. +//| See the Warning in `digitalio` for more information. //| """ //| ... //| static mp_obj_t keypad_keys_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { #if CIRCUITPY_KEYPAD_KEYS - keypad_keys_obj_t *self = mp_obj_malloc(keypad_keys_obj_t, &keypad_keys_type); enum { ARG_pins, ARG_value_when_pressed, ARG_pull, ARG_interval, ARG_max_events, ARG_debounce_threshold }; static const mp_arg_t allowed_args[] = { { MP_QSTR_pins, MP_ARG_REQUIRED | MP_ARG_OBJ }, @@ -106,6 +111,7 @@ static mp_obj_t keypad_keys_make_new(const mp_obj_type_t *type, size_t n_args, s validate_obj_is_free_pin(mp_obj_subscr(pins, MP_OBJ_NEW_SMALL_INT(i), MP_OBJ_SENTINEL), MP_QSTR_pin); } + keypad_keys_obj_t *self = mp_obj_malloc_with_finaliser(keypad_keys_obj_t, &keypad_keys_type); common_hal_keypad_keys_construct(self, num_pins, pins_array, value_when_pressed, args[ARG_pull].u_bool, interval, max_events, debounce_threshold); return MP_OBJ_FROM_PTR(self); @@ -164,6 +170,7 @@ MP_DEFINE_CONST_FUN_OBJ_1(keypad_keys_deinit_obj, keypad_keys_deinit); //| static const mp_rom_map_elem_t keypad_keys_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&keypad_keys_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&keypad_keys_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, diff --git a/shared-bindings/keypad/ShiftRegisterKeys.c b/shared-bindings/keypad/ShiftRegisterKeys.c index 1347735b5d2..fa3b39ab63b 100644 --- a/shared-bindings/keypad/ShiftRegisterKeys.c +++ b/shared-bindings/keypad/ShiftRegisterKeys.c @@ -88,8 +88,6 @@ static mp_obj_t keypad_shiftregisterkeys_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { #if CIRCUITPY_KEYPAD_SHIFTREGISTERKEYS - keypad_shiftregisterkeys_obj_t *self = - mp_obj_malloc(keypad_shiftregisterkeys_obj_t, &keypad_shiftregisterkeys_type); enum { ARG_clock, ARG_data, ARG_latch, ARG_value_to_latch, ARG_key_count, ARG_value_when_pressed, ARG_interval, ARG_max_events, ARG_debounce_threshold }; static const mp_arg_t allowed_args[] = { { MP_QSTR_clock, MP_ARG_KW_ONLY | MP_ARG_REQUIRED | MP_ARG_OBJ }, @@ -160,6 +158,8 @@ static mp_obj_t keypad_shiftregisterkeys_make_new(const mp_obj_type_t *type, siz const size_t max_events = (size_t)mp_arg_validate_int_min(args[ARG_max_events].u_int, 1, MP_QSTR_max_events); const uint8_t debounce_threshold = (uint8_t)mp_arg_validate_int_range(args[ARG_debounce_threshold].u_int, 1, 127, MP_QSTR_debounce_threshold); + keypad_shiftregisterkeys_obj_t *self = + mp_obj_malloc_with_finaliser(keypad_shiftregisterkeys_obj_t, &keypad_shiftregisterkeys_type); common_hal_keypad_shiftregisterkeys_construct( self, clock, num_data_pins, data_pins_array, latch, value_to_latch, num_key_counts, key_count_array, value_when_pressed, interval, max_events, debounce_threshold); @@ -219,6 +219,7 @@ MP_DEFINE_CONST_FUN_OBJ_1(keypad_shiftregisterkeys_deinit_obj, keypad_shiftregis static const mp_rom_map_elem_t keypad_shiftregisterkeys_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&keypad_shiftregisterkeys_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&keypad_shiftregisterkeys_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, diff --git a/shared-bindings/keypad/__init__.c b/shared-bindings/keypad/__init__.c index b29de197262..b182e977829 100644 --- a/shared-bindings/keypad/__init__.c +++ b/shared-bindings/keypad/__init__.c @@ -65,7 +65,7 @@ MP_PROPERTY_GETTER(keypad_generic_events_obj, //| due to a GPIO hardware issue that causes excessive leakage current (~120uA). //| A pin can read as high even when driven or pulled low, if the input signal is high //| impedance or if an attached pull-down resistor is too weak (has too high a value). -//| See the warning in `digitalio` for more information. +//| See the warnings in `keypad.Keys`, `keypad.KeyMatrix`, and `digitalio` for workarounds and more information. //| //| .. jinja //| """ diff --git a/shared-bindings/keypad_demux/DemuxKeyMatrix.c b/shared-bindings/keypad_demux/DemuxKeyMatrix.c index d76a20aec9d..9d25ddc44cf 100644 --- a/shared-bindings/keypad_demux/DemuxKeyMatrix.c +++ b/shared-bindings/keypad_demux/DemuxKeyMatrix.c @@ -80,7 +80,6 @@ //| static mp_obj_t keypad_demux_demuxkeymatrix_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { - keypad_demux_demuxkeymatrix_obj_t *self = mp_obj_malloc(keypad_demux_demuxkeymatrix_obj_t, &keypad_demux_demuxkeymatrix_type); enum { ARG_row_addr_pins, ARG_column_pins, ARG_columns_to_anodes, ARG_transpose, ARG_interval, ARG_max_events, ARG_debounce_threshold }; static const mp_arg_t allowed_args[] = { { MP_QSTR_row_addr_pins, MP_ARG_REQUIRED | MP_ARG_OBJ }, @@ -123,7 +122,10 @@ static mp_obj_t keypad_demux_demuxkeymatrix_make_new(const mp_obj_type_t *type, column_pins_array[column] = pin; } - common_hal_keypad_demux_demuxkeymatrix_construct(self, num_row_addr_pins, row_addr_pins_array, num_column_pins, column_pins_array, args[ARG_columns_to_anodes].u_bool, args[ARG_transpose].u_bool, interval, max_events, debounce_threshold); + keypad_demux_demuxkeymatrix_obj_t *self = mp_obj_malloc_with_finaliser(keypad_demux_demuxkeymatrix_obj_t, &keypad_demux_demuxkeymatrix_type); + // Last arg is use_gc_allocator, true during VM use. + common_hal_keypad_demux_demuxkeymatrix_construct(self, num_row_addr_pins, row_addr_pins_array, num_column_pins, column_pins_array, args[ARG_columns_to_anodes].u_bool, args[ARG_transpose].u_bool, interval, max_events, debounce_threshold, true); + return MP_OBJ_FROM_PTR(self); } @@ -189,7 +191,7 @@ static mp_obj_t keypad_demux_demuxkeymatrix_key_number_to_row_column(mp_obj_t se const mp_uint_t key_number = (mp_uint_t)mp_arg_validate_int_range( mp_obj_get_int(key_number_in), - 0, (mp_int_t)common_hal_keypad_generic_get_key_count(self), + 0, (mp_int_t)common_hal_keypad_generic_get_key_count(self) - 1, MP_QSTR_key_number); mp_uint_t row; @@ -215,10 +217,10 @@ static mp_obj_t keypad_demux_demuxkeymatrix_row_column_to_key_number(mp_obj_t se check_for_deinit(self); const mp_uint_t row = (mp_uint_t)mp_arg_validate_int_range( - mp_obj_get_int(row_in), 0, (mp_int_t)common_hal_keypad_demux_demuxkeymatrix_get_row_count(self), MP_QSTR_row); + mp_obj_get_int(row_in), 0, (mp_int_t)common_hal_keypad_demux_demuxkeymatrix_get_row_count(self) - 1, MP_QSTR_row); const mp_int_t column = (mp_uint_t)mp_arg_validate_int_range( - mp_obj_get_int(column_in), 0, (mp_int_t)common_hal_keypad_demux_demuxkeymatrix_get_column_count(self), MP_QSTR_column); + mp_obj_get_int(column_in), 0, (mp_int_t)common_hal_keypad_demux_demuxkeymatrix_get_column_count(self) - 1, MP_QSTR_column); return MP_OBJ_NEW_SMALL_INT( (mp_int_t)common_hal_keypad_demux_demuxkeymatrix_row_column_to_key_number(self, row, column)); @@ -233,6 +235,7 @@ MP_DEFINE_CONST_FUN_OBJ_3(keypad_demux_demuxkeymatrix_row_column_to_key_number_o static const mp_rom_map_elem_t keypad_demux_demuxkeymatrix_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&keypad_demux_demuxkeymatrix_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&keypad_demux_demuxkeymatrix_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, diff --git a/shared-bindings/keypad_demux/DemuxKeyMatrix.h b/shared-bindings/keypad_demux/DemuxKeyMatrix.h index 8bdaa597dc0..25d36283e90 100644 --- a/shared-bindings/keypad_demux/DemuxKeyMatrix.h +++ b/shared-bindings/keypad_demux/DemuxKeyMatrix.h @@ -11,7 +11,7 @@ extern const mp_obj_type_t keypad_demux_demuxkeymatrix_type; -void common_hal_keypad_demux_demuxkeymatrix_construct(keypad_demux_demuxkeymatrix_obj_t *self, mp_uint_t num_row_addr_pins, const mcu_pin_obj_t *row_addr_pins[], mp_uint_t num_column_pins, const mcu_pin_obj_t *column_pins[], bool columns_to_anodes, bool transpose, mp_float_t interval, size_t max_events, uint8_t debounce_threshold); +void common_hal_keypad_demux_demuxkeymatrix_construct(keypad_demux_demuxkeymatrix_obj_t *self, mp_uint_t num_row_addr_pins, const mcu_pin_obj_t *row_addr_pins[], mp_uint_t num_column_pins, const mcu_pin_obj_t *column_pins[], bool columns_to_anodes, bool transpose, mp_float_t interval, size_t max_events, uint8_t debounce_threshold, bool use_gc_allocator); void common_hal_keypad_demux_demuxkeymatrix_deinit(keypad_demux_demuxkeymatrix_obj_t *self); diff --git a/shared-bindings/lvfontio/OnDiskFont.c b/shared-bindings/lvfontio/OnDiskFont.c new file mode 100644 index 00000000000..3a50ea9aedf --- /dev/null +++ b/shared-bindings/lvfontio/OnDiskFont.c @@ -0,0 +1,98 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/lvfontio/OnDiskFont.h" + +#include + +#include "shared/runtime/context_manager_helpers.h" +#include "py/binary.h" +#include "py/objproperty.h" +#include "py/objstr.h" +#include "py/runtime.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/util.h" + +//| class OnDiskFont: +//| """A font built into CircuitPython for use with LVGL. +//| +//| There is an in-browser converter here: https://lvgl.io/tools/fontconverter +//| +//| The format is documented here: https://github.com/lvgl/lv_font_conv/tree/master/doc""" +//| +//| def __init__(self, file_path: str, max_glyphs: int = 100) -> None: +//| """Create a OnDiskFont by loading an LVGL font file from the filesystem. +//| +//| :param str file_path: The path to the font file +//| :param int max_glyphs: Maximum number of glyphs to cache at once +//| """ +//| ... +//| + +//| bitmap: displayio.Bitmap +//| """Bitmap containing all font glyphs starting with ASCII and followed by unicode. This is useful for use with LVGL.""" +//| +static mp_obj_t lvfontio_ondiskfont_obj_get_bitmap(mp_obj_t self_in) { + lvfontio_ondiskfont_t *self = MP_OBJ_TO_PTR(self_in); + return common_hal_lvfontio_ondiskfont_get_bitmap(self); +} +MP_DEFINE_CONST_FUN_OBJ_1(lvfontio_ondiskfont_get_bitmap_obj, lvfontio_ondiskfont_obj_get_bitmap); + +MP_PROPERTY_GETTER(lvfontio_ondiskfont_bitmap_obj, + (mp_obj_t)&lvfontio_ondiskfont_get_bitmap_obj); + +//| def get_bounding_box(self) -> Tuple[int, int]: +//| """Returns the maximum bounds of all glyphs in the font in a tuple of two values: width, height.""" +//| ... +//| +//| +static mp_obj_t lvfontio_ondiskfont_obj_get_bounding_box(mp_obj_t self_in) { + lvfontio_ondiskfont_t *self = MP_OBJ_TO_PTR(self_in); + + return common_hal_lvfontio_ondiskfont_get_bounding_box(self); +} +MP_DEFINE_CONST_FUN_OBJ_1(lvfontio_ondiskfont_get_bounding_box_obj, lvfontio_ondiskfont_obj_get_bounding_box); + +static const mp_rom_map_elem_t lvfontio_ondiskfont_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_bitmap), MP_ROM_PTR(&lvfontio_ondiskfont_bitmap_obj) }, + { MP_ROM_QSTR(MP_QSTR_get_bounding_box), MP_ROM_PTR(&lvfontio_ondiskfont_get_bounding_box_obj) }, +}; +static MP_DEFINE_CONST_DICT(lvfontio_ondiskfont_locals_dict, lvfontio_ondiskfont_locals_dict_table); + +static mp_obj_t lvfontio_ondiskfont_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_file_path, ARG_max_glyphs }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_file_path, MP_ARG_OBJ | MP_ARG_REQUIRED }, + { MP_QSTR_max_glyphs, MP_ARG_INT, {.u_int = 100} }, + }; + + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + // Allocate the BuiltinFont object + lvfontio_ondiskfont_t *self = m_new_obj(lvfontio_ondiskfont_t); + self->base.type = &lvfontio_ondiskfont_type; + + // Extract arguments + mp_obj_t file_path_obj = args[ARG_file_path].u_obj; + mp_uint_t max_glyphs = args[ARG_max_glyphs].u_int; + + // Get the C string from the Python string + const char *file_path = mp_obj_str_get_str(file_path_obj); + + // Always use GC allocator for Python-created objects + common_hal_lvfontio_ondiskfont_construct(self, file_path, max_glyphs, true); + + return MP_OBJ_FROM_PTR(self); +} + +MP_DEFINE_CONST_OBJ_TYPE( + lvfontio_ondiskfont_type, + MP_QSTR_OnDiskFont, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, lvfontio_ondiskfont_make_new, + locals_dict, &lvfontio_ondiskfont_locals_dict + ); diff --git a/shared-bindings/lvfontio/OnDiskFont.h b/shared-bindings/lvfontio/OnDiskFont.h new file mode 100644 index 00000000000..d7dac6ac678 --- /dev/null +++ b/shared-bindings/lvfontio/OnDiskFont.h @@ -0,0 +1,22 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-module/lvfontio/OnDiskFont.h" + +extern const mp_obj_type_t lvfontio_ondiskfont_type; + +mp_obj_t common_hal_lvfontio_ondiskfont_get_bitmap(const lvfontio_ondiskfont_t *self); +mp_obj_t common_hal_lvfontio_ondiskfont_get_bounding_box(const lvfontio_ondiskfont_t *self); +void common_hal_lvfontio_ondiskfont_get_dimensions(const lvfontio_ondiskfont_t *self, uint16_t *width, uint16_t *height); + +// Function prototypes +void common_hal_lvfontio_ondiskfont_construct(lvfontio_ondiskfont_t *self, const char *file_path, uint16_t max_glyphs, bool use_gc_allocator); +void common_hal_lvfontio_ondiskfont_deinit(lvfontio_ondiskfont_t *self); +bool common_hal_lvfontio_ondiskfont_deinited(lvfontio_ondiskfont_t *self); +int16_t common_hal_lvfontio_ondiskfont_cache_glyph(lvfontio_ondiskfont_t *self, uint32_t codepoint, bool *is_full_width); +void common_hal_lvfontio_ondiskfont_release_glyph(lvfontio_ondiskfont_t *self, uint32_t slot); diff --git a/shared-bindings/lvfontio/__init__.c b/shared-bindings/lvfontio/__init__.c new file mode 100644 index 00000000000..ec5f3522799 --- /dev/null +++ b/shared-bindings/lvfontio/__init__.c @@ -0,0 +1,33 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include + +#include "py/obj.h" +#include "py/runtime.h" + +#include "shared-bindings/lvfontio/__init__.h" +#include "shared-bindings/lvfontio/OnDiskFont.h" + +//| """Core font related data structures for LVGL +//| +//| .. note:: This module is intended only for low-level usage with LVGL. +//| +//| """ + +static const mp_rom_map_elem_t lvfontio_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_lvfontio) }, + { MP_ROM_QSTR(MP_QSTR_OnDiskFont), MP_ROM_PTR(&lvfontio_ondiskfont_type) }, +}; + +static MP_DEFINE_CONST_DICT(lvfontio_module_globals, lvfontio_module_globals_table); + +const mp_obj_module_t lvfontio_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&lvfontio_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_lvfontio, lvfontio_module); diff --git a/shared-bindings/lvfontio/__init__.h b/shared-bindings/lvfontio/__init__.h new file mode 100644 index 00000000000..b56388fa8ae --- /dev/null +++ b/shared-bindings/lvfontio/__init__.h @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once diff --git a/shared-bindings/math/__init__.c b/shared-bindings/math/__init__.c index 54fe53280ca..000b93a2c44 100644 --- a/shared-bindings/math/__init__.c +++ b/shared-bindings/math/__init__.c @@ -26,16 +26,47 @@ //| """ //| -static NORETURN void math_error(void) { +static MP_NORETURN void math_error(void) { mp_raise_ValueError(MP_ERROR_TEXT("math domain error")); } +// A NaN or infinite result from finite arguments is a domain error, as in +// py/modmath.c. +static mp_obj_t math_generic_1(mp_obj_t x_obj, mp_float_t (*f)(mp_float_t)) { + mp_float_t x = mp_obj_get_float(x_obj); + mp_float_t ans = f(x); + if ((isnan(ans) && !isnan(x)) || (isinf(ans) && !isinf(x))) { + math_error(); + } + return mp_obj_new_float(ans); +} + +static mp_obj_t math_generic_2(mp_obj_t x_obj, mp_obj_t y_obj, mp_float_t (*f)(mp_float_t, mp_float_t)) { + mp_float_t x = mp_obj_get_float(x_obj); + mp_float_t y = mp_obj_get_float(y_obj); + mp_float_t ans = f(x, y); + if ((isnan(ans) && !isnan(x) && !isnan(y)) || (isinf(ans) && !isinf(x) && !isinf(y))) { + math_error(); + } + return mp_obj_new_float(ans); +} + #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_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); #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_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); + +#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) { \ + 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); #define MATH_FUN_1_TO_BOOL(py_name, c_name) \ @@ -310,9 +341,18 @@ MATH_FUN_2(atan2, atan2) MATH_FUN_1_TO_INT(ceil, ceil) -MATH_FUN_2(copysign, copysign) +// fabs and copysign are compiler builtins. Call them directly so they are +// inlined: through a function pointer they reach the libm symbol, and +// pico-sdk's copysignf returns nan for a nan y. +static mp_float_t MICROPY_FLOAT_C_FUN(copysign_func)(mp_float_t x, mp_float_t y) { + return MICROPY_FLOAT_C_FUN(copysign)(x, y); +} +MATH_FUN_2(copysign, copysign_func) -MATH_FUN_1(fabs, fabs) +static mp_float_t MICROPY_FLOAT_C_FUN(fabs_func)(mp_float_t x) { + return MICROPY_FLOAT_C_FUN(fabs)(x); +} +MATH_FUN_1(fabs, fabs_func) MATH_FUN_1_TO_INT(floor, floor) // TODO: delegate to x.__floor__() if x is not a float @@ -326,7 +366,7 @@ MATH_FUN_1_TO_BOOL(isnan, isnan) MATH_FUN_1_TO_INT(trunc, trunc) -MATH_FUN_2(ldexp, ldexp) +MATH_FUN_2_FLT_INT(ldexp, ldexp) #if MICROPY_PY_MATH_SPECIAL_FUNCTIONS //| def erf(x: float) -> float: @@ -420,7 +460,7 @@ static mp_obj_t mp_math_log(size_t n_args, const mp_obj_t *args) { #pragma GCC diagnostic ignored "-Wfloat-equal" } else if (base == (mp_float_t)1.0) { #pragma GCC diagnostic pop - math_error(); + mp_raise_ZeroDivisionError(); } return mp_obj_new_float(l / MICROPY_FLOAT_C_FUN(log)(base)); } diff --git a/shared-bindings/mcp4822/MCP4822.c b/shared-bindings/mcp4822/MCP4822.c new file mode 100644 index 00000000000..f192caf4052 --- /dev/null +++ b/shared-bindings/mcp4822/MCP4822.c @@ -0,0 +1,243 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tod Kurt +// +// SPDX-License-Identifier: MIT + +#include + +#include "shared/runtime/context_manager_helpers.h" +#include "py/binary.h" +#include "py/objproperty.h" +#include "py/runtime.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/mcp4822/MCP4822.h" +#include "shared-bindings/util.h" + +//| class MCP4822: +//| """Output audio to an MCP4822 dual-channel 12-bit SPI DAC.""" +//| +//| def __init__( +//| self, +//| clock: microcontroller.Pin, +//| mosi: microcontroller.Pin, +//| cs: microcontroller.Pin, +//| *, +//| gain: int = 1, +//| ) -> None: +//| """Create an MCP4822 object associated with the given SPI pins. +//| +//| :param ~microcontroller.Pin clock: The SPI clock (SCK) pin +//| :param ~microcontroller.Pin mosi: The SPI data (SDI/MOSI) pin +//| :param ~microcontroller.Pin cs: The chip select (CS) pin +//| :param int gain: DAC output gain, 1 for 1x (0-2.048V) or 2 for 2x (0-4.096V). Default 1. +//| +//| Simple 8ksps 440 Hz sine wave:: +//| +//| import mcp4822 +//| import audiocore +//| import board +//| import array +//| import time +//| import math +//| +//| length = 8000 // 440 +//| sine_wave = array.array("H", [0] * length) +//| for i in range(length): +//| sine_wave[i] = int(math.sin(math.pi * 2 * i / length) * (2 ** 15) + 2 ** 15) +//| +//| sine_wave = audiocore.RawSample(sine_wave, sample_rate=8000) +//| dac = mcp4822.MCP4822(clock=board.GP18, mosi=board.GP19, cs=board.GP21) +//| dac.play(sine_wave, loop=True) +//| time.sleep(1) +//| dac.stop() +//| +//| Playing a wave file from flash:: +//| +//| import board +//| import audiocore +//| import mcp4822 +//| +//| f = open("sound.wav", "rb") +//| wav = audiocore.WaveFile(f) +//| +//| dac = mcp4822.MCP4822(clock=board.GP18, mosi=board.GP19, cs=board.GP21) +//| dac.play(wav) +//| while dac.playing: +//| pass""" +//| ... +//| +static mp_obj_t mcp4822_mcp4822_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_clock, ARG_mosi, ARG_cs, ARG_gain }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_clock, MP_ARG_OBJ | MP_ARG_KW_ONLY | MP_ARG_REQUIRED }, + { MP_QSTR_mosi, MP_ARG_OBJ | MP_ARG_KW_ONLY | MP_ARG_REQUIRED }, + { MP_QSTR_cs, MP_ARG_OBJ | MP_ARG_KW_ONLY | MP_ARG_REQUIRED }, + { MP_QSTR_gain, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 1} }, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_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, MP_QSTR_clock); + const mcu_pin_obj_t *mosi = validate_obj_is_free_pin(args[ARG_mosi].u_obj, MP_QSTR_mosi); + const mcu_pin_obj_t *cs = validate_obj_is_free_pin(args[ARG_cs].u_obj, MP_QSTR_cs); + const mp_int_t gain = mp_arg_validate_int_range(args[ARG_gain].u_int, 1, 2, MP_QSTR_gain); + + mcp4822_mcp4822_obj_t *self = mp_obj_malloc_with_finaliser(mcp4822_mcp4822_obj_t, &mcp4822_mcp4822_type); + common_hal_mcp4822_mcp4822_construct(self, clock, mosi, cs, (uint8_t)gain); + + return MP_OBJ_FROM_PTR(self); +} + +static void check_for_deinit(mcp4822_mcp4822_obj_t *self) { + if (common_hal_mcp4822_mcp4822_deinited(self)) { + raise_deinited_error(); + } +} + +//| def deinit(self) -> None: +//| """Deinitialises the MCP4822 and releases any hardware resources for reuse.""" +//| ... +//| +static mp_obj_t mcp4822_mcp4822_deinit(mp_obj_t self_in) { + mcp4822_mcp4822_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_mcp4822_mcp4822_deinit(self); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(mcp4822_mcp4822_deinit_obj, mcp4822_mcp4822_deinit); + +//| def __enter__(self) -> MCP4822: +//| """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.""" +//| ... +//| +// Provided by context manager helper. + +//| def play(self, sample: circuitpython_typing.AudioSample, *, loop: bool = False) -> None: +//| """Plays the sample once when loop=False and continuously when loop=True. +//| Does not block. Use `playing` to block. +//| +//| Sample must be an `audiocore.WaveFile`, `audiocore.RawSample`, `audiomixer.Mixer` or `audiomp3.MP3Decoder`. +//| +//| The sample itself should consist of 8 bit or 16 bit samples.""" +//| ... +//| +static mp_obj_t mcp4822_mcp4822_obj_play(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_sample, ARG_loop }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_sample, MP_ARG_OBJ | MP_ARG_REQUIRED }, + { MP_QSTR_loop, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = false} }, + }; + mcp4822_mcp4822_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_obj_t sample = args[ARG_sample].u_obj; + common_hal_mcp4822_mcp4822_play(self, sample, args[ARG_loop].u_bool); + + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_KW(mcp4822_mcp4822_play_obj, 1, mcp4822_mcp4822_obj_play); + +//| def stop(self) -> None: +//| """Stops playback.""" +//| ... +//| +static mp_obj_t mcp4822_mcp4822_obj_stop(mp_obj_t self_in) { + mcp4822_mcp4822_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + common_hal_mcp4822_mcp4822_stop(self); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_1(mcp4822_mcp4822_stop_obj, mcp4822_mcp4822_obj_stop); + +//| playing: bool +//| """True when the audio sample is being output. (read-only)""" +//| +static mp_obj_t mcp4822_mcp4822_obj_get_playing(mp_obj_t self_in) { + mcp4822_mcp4822_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_bool(common_hal_mcp4822_mcp4822_get_playing(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(mcp4822_mcp4822_get_playing_obj, mcp4822_mcp4822_obj_get_playing); + +MP_PROPERTY_GETTER(mcp4822_mcp4822_playing_obj, + (mp_obj_t)&mcp4822_mcp4822_get_playing_obj); + +//| def pause(self) -> None: +//| """Stops playback temporarily while remembering the position. Use `resume` to resume playback.""" +//| ... +//| +static mp_obj_t mcp4822_mcp4822_obj_pause(mp_obj_t self_in) { + mcp4822_mcp4822_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + + if (!common_hal_mcp4822_mcp4822_get_playing(self)) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Not playing")); + } + common_hal_mcp4822_mcp4822_pause(self); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_1(mcp4822_mcp4822_pause_obj, mcp4822_mcp4822_obj_pause); + +//| def resume(self) -> None: +//| """Resumes sample playback after :py:func:`pause`.""" +//| ... +//| +static mp_obj_t mcp4822_mcp4822_obj_resume(mp_obj_t self_in) { + mcp4822_mcp4822_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + + if (common_hal_mcp4822_mcp4822_get_paused(self)) { + common_hal_mcp4822_mcp4822_resume(self); + } + + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_1(mcp4822_mcp4822_resume_obj, mcp4822_mcp4822_obj_resume); + +//| paused: bool +//| """True when playback is paused. (read-only)""" +//| +//| +static mp_obj_t mcp4822_mcp4822_obj_get_paused(mp_obj_t self_in) { + mcp4822_mcp4822_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_bool(common_hal_mcp4822_mcp4822_get_paused(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(mcp4822_mcp4822_get_paused_obj, mcp4822_mcp4822_obj_get_paused); + +MP_PROPERTY_GETTER(mcp4822_mcp4822_paused_obj, + (mp_obj_t)&mcp4822_mcp4822_get_paused_obj); + +static const mp_rom_map_elem_t mcp4822_mcp4822_locals_dict_table[] = { + // Methods + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&mcp4822_mcp4822_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&mcp4822_mcp4822_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, + { MP_ROM_QSTR(MP_QSTR_play), MP_ROM_PTR(&mcp4822_mcp4822_play_obj) }, + { MP_ROM_QSTR(MP_QSTR_stop), MP_ROM_PTR(&mcp4822_mcp4822_stop_obj) }, + { MP_ROM_QSTR(MP_QSTR_pause), MP_ROM_PTR(&mcp4822_mcp4822_pause_obj) }, + { MP_ROM_QSTR(MP_QSTR_resume), MP_ROM_PTR(&mcp4822_mcp4822_resume_obj) }, + + // Properties + { MP_ROM_QSTR(MP_QSTR_playing), MP_ROM_PTR(&mcp4822_mcp4822_playing_obj) }, + { MP_ROM_QSTR(MP_QSTR_paused), MP_ROM_PTR(&mcp4822_mcp4822_paused_obj) }, +}; +static MP_DEFINE_CONST_DICT(mcp4822_mcp4822_locals_dict, mcp4822_mcp4822_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + mcp4822_mcp4822_type, + MP_QSTR_MCP4822, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, mcp4822_mcp4822_make_new, + locals_dict, &mcp4822_mcp4822_locals_dict + ); diff --git a/shared-bindings/mcp4822/MCP4822.h b/shared-bindings/mcp4822/MCP4822.h new file mode 100644 index 00000000000..b129aec3061 --- /dev/null +++ b/shared-bindings/mcp4822/MCP4822.h @@ -0,0 +1,25 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tod Kurt +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "common-hal/mcp4822/MCP4822.h" +#include "common-hal/microcontroller/Pin.h" + +extern const mp_obj_type_t mcp4822_mcp4822_type; + +void common_hal_mcp4822_mcp4822_construct(mcp4822_mcp4822_obj_t *self, + const mcu_pin_obj_t *clock, const mcu_pin_obj_t *mosi, + const mcu_pin_obj_t *cs, uint8_t gain); + +void common_hal_mcp4822_mcp4822_deinit(mcp4822_mcp4822_obj_t *self); +bool common_hal_mcp4822_mcp4822_deinited(mcp4822_mcp4822_obj_t *self); +void common_hal_mcp4822_mcp4822_play(mcp4822_mcp4822_obj_t *self, mp_obj_t sample, bool loop); +void common_hal_mcp4822_mcp4822_stop(mcp4822_mcp4822_obj_t *self); +bool common_hal_mcp4822_mcp4822_get_playing(mcp4822_mcp4822_obj_t *self); +void common_hal_mcp4822_mcp4822_pause(mcp4822_mcp4822_obj_t *self); +void common_hal_mcp4822_mcp4822_resume(mcp4822_mcp4822_obj_t *self); +bool common_hal_mcp4822_mcp4822_get_paused(mcp4822_mcp4822_obj_t *self); diff --git a/shared-bindings/mcp4822/__init__.c b/shared-bindings/mcp4822/__init__.c new file mode 100644 index 00000000000..bac2136d9e7 --- /dev/null +++ b/shared-bindings/mcp4822/__init__.c @@ -0,0 +1,36 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tod Kurt +// +// SPDX-License-Identifier: MIT + +#include + +#include "py/obj.h" +#include "py/runtime.h" + +#include "shared-bindings/mcp4822/__init__.h" +#include "shared-bindings/mcp4822/MCP4822.h" + +//| """Audio output via MCP4822 dual-channel 12-bit SPI DAC. +//| +//| The `mcp4822` module provides the `MCP4822` class for non-blocking +//| audio playback through the Microchip MCP4822 SPI DAC using PIO and DMA. +//| +//| All classes change hardware state and should be deinitialized when they +//| are no longer needed. To do so, either call :py:meth:`!deinit` or use a +//| context manager.""" + +static const mp_rom_map_elem_t mcp4822_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_mcp4822) }, + { MP_ROM_QSTR(MP_QSTR_MCP4822), MP_ROM_PTR(&mcp4822_mcp4822_type) }, +}; + +static MP_DEFINE_CONST_DICT(mcp4822_module_globals, mcp4822_module_globals_table); + +const mp_obj_module_t mcp4822_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&mcp4822_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_mcp4822, mcp4822_module); diff --git a/shared-bindings/mcp4822/__init__.h b/shared-bindings/mcp4822/__init__.h new file mode 100644 index 00000000000..c4a52e5819d --- /dev/null +++ b/shared-bindings/mcp4822/__init__.h @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tod Kurt +// +// SPDX-License-Identifier: MIT + +#pragma once diff --git a/shared-bindings/mdns/RemoteService.c b/shared-bindings/mdns/RemoteService.c index b3ee3d7f7b7..b00313729fc 100644 --- a/shared-bindings/mdns/RemoteService.c +++ b/shared-bindings/mdns/RemoteService.c @@ -93,18 +93,6 @@ MP_DEFINE_CONST_FUN_OBJ_1(mdns_remoteservice_get_ipv4_address_obj, _mdns_remotes MP_PROPERTY_GETTER(mdns_remoteservice_ipv4_address_obj, (mp_obj_t)&mdns_remoteservice_get_ipv4_address_obj); -//| def __del__(self) -> None: -//| """Deletes the RemoteService object.""" -//| ... -//| -//| -static mp_obj_t mdns_remoteservice_obj_deinit(mp_obj_t self_in) { - mdns_remoteservice_obj_t *self = MP_OBJ_TO_PTR(self_in); - common_hal_mdns_remoteservice_deinit(self); - return mp_const_none; -} -static MP_DEFINE_CONST_FUN_OBJ_1(mdns_remoteservice_deinit_obj, mdns_remoteservice_obj_deinit); - static const mp_rom_map_elem_t mdns_remoteservice_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_hostname), MP_ROM_PTR(&mdns_remoteservice_hostname_obj) }, { MP_ROM_QSTR(MP_QSTR_instance_name), MP_ROM_PTR(&mdns_remoteservice_instance_name_obj) }, @@ -112,8 +100,6 @@ static const mp_rom_map_elem_t mdns_remoteservice_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_protocol), MP_ROM_PTR(&mdns_remoteservice_protocol_obj) }, { MP_ROM_QSTR(MP_QSTR_port), MP_ROM_PTR(&mdns_remoteservice_port_obj) }, { MP_ROM_QSTR(MP_QSTR_ipv4_address), MP_ROM_PTR(&mdns_remoteservice_ipv4_address_obj) }, - - { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&mdns_remoteservice_deinit_obj) }, }; static MP_DEFINE_CONST_DICT(mdns_remoteservice_locals_dict, mdns_remoteservice_locals_dict_table); diff --git a/shared-bindings/mdns/RemoteService.h b/shared-bindings/mdns/RemoteService.h index a5ffe897e4e..c7efa64083d 100644 --- a/shared-bindings/mdns/RemoteService.h +++ b/shared-bindings/mdns/RemoteService.h @@ -19,7 +19,6 @@ const char *common_hal_mdns_remoteservice_get_instance_name(mdns_remoteservice_o const char *common_hal_mdns_remoteservice_get_hostname(mdns_remoteservice_obj_t *self); mp_int_t common_hal_mdns_remoteservice_get_port(mdns_remoteservice_obj_t *self); mp_obj_t common_hal_mdns_remoteservice_get_ipv4_address(mdns_remoteservice_obj_t *self); -void common_hal_mdns_remoteservice_deinit(mdns_remoteservice_obj_t *self); // For internal use. uint32_t mdns_remoteservice_get_ipv4_address(mdns_remoteservice_obj_t *self); diff --git a/shared-bindings/mdns/Server.c b/shared-bindings/mdns/Server.c index 86fb2eb6d7a..1c16348d425 100644 --- a/shared-bindings/mdns/Server.c +++ b/shared-bindings/mdns/Server.c @@ -150,7 +150,14 @@ static mp_obj_t _mdns_server_find(mp_uint_t n_args, const mp_obj_t *pos_args, mp } static MP_DEFINE_CONST_FUN_OBJ_KW(mdns_server_find_obj, 1, _mdns_server_find); -//| def advertise_service(self, *, service_type: str, protocol: str, port: int) -> None: +//| def advertise_service( +//| self, +//| *, +//| service_type: str, +//| protocol: str, +//| port: int, +//| txt_records: Optional[Sequence[str]] = None, +//| ) -> None: //| """Respond to queries for the given service with the given port. //| //| ``service_type`` and ``protocol`` can only occur on one port. Any call after the first @@ -158,8 +165,8 @@ static MP_DEFINE_CONST_FUN_OBJ_KW(mdns_server_find_obj, 1, _mdns_server_find); //| //| If web workflow is active, the port it uses can't also be used to advertise a service. //| -//| **Limitations**: Publishing up to 32 TXT records is only supported on the RP2040 Pico W board at -//| this time. +//| **Limitations**: Publishing TXT records (up to 32) is supported only on RP2xxx. +//| There is currently no TXT record support on Espressif boards. //| //| :param str service_type: The service type such as "_http" //| :param str protocol: The service protocol such as "_tcp" diff --git a/shared-bindings/memorymap/AddressRange.c b/shared-bindings/memorymap/AddressRange.c index efc55ad37d7..5f7ee0deb95 100644 --- a/shared-bindings/memorymap/AddressRange.c +++ b/shared-bindings/memorymap/AddressRange.c @@ -92,7 +92,6 @@ static mp_obj_t memorymap_addressrange_make_new(const mp_obj_type_t *type, size_ } memorymap_addressrange_obj_t *self = mp_obj_malloc(memorymap_addressrange_obj_t, &memorymap_addressrange_type); - common_hal_memorymap_addressrange_construct(self, (uint8_t *)start, length); return MP_OBJ_FROM_PTR(self); diff --git a/shared-bindings/memorymonitor/AllocationAlarm.c b/shared-bindings/memorymonitor/AllocationAlarm.c index 5475e2d7db4..00cfbbd9fe1 100644 --- a/shared-bindings/memorymonitor/AllocationAlarm.c +++ b/shared-bindings/memorymonitor/AllocationAlarm.c @@ -48,7 +48,6 @@ static mp_obj_t memorymonitor_allocationalarm_make_new(const mp_obj_type_t *type memorymonitor_allocationalarm_obj_t *self = mp_obj_malloc(memorymonitor_allocationalarm_obj_t, &memorymonitor_allocationalarm_type); - common_hal_memorymonitor_allocationalarm_construct(self, minimum_block_count); return MP_OBJ_FROM_PTR(self); diff --git a/shared-bindings/memorymonitor/AllocationSize.c b/shared-bindings/memorymonitor/AllocationSize.c index 3113d6ed191..6a647765eb0 100644 --- a/shared-bindings/memorymonitor/AllocationSize.c +++ b/shared-bindings/memorymonitor/AllocationSize.c @@ -43,7 +43,7 @@ //| static mp_obj_t memorymonitor_allocationsize_make_new(const mp_obj_type_t *type, size_t n_args, const mp_obj_t *all_args, mp_map_t *kw_args) { memorymonitor_allocationsize_obj_t *self = - m_new_obj(memorymonitor_allocationsize_obj_t, &memorymonitor_allocationsize_type); + mp_obj_malloc(memorymonitor_allocationsize_obj_t, &memorymonitor_allocationsize_type); common_hal_memorymonitor_allocationsize_construct(self); diff --git a/shared-bindings/memorymonitor/__init__.c b/shared-bindings/memorymonitor/__init__.c index 64d0140ff79..e364344b363 100644 --- a/shared-bindings/memorymonitor/__init__.c +++ b/shared-bindings/memorymonitor/__init__.c @@ -25,7 +25,7 @@ //| MP_DEFINE_MEMORYMONITOR_EXCEPTION(AllocationError, Exception) -NORETURN void mp_raise_memorymonitor_AllocationError(mp_rom_error_text_t fmt, ...) { +MP_NORETURN void mp_raise_memorymonitor_AllocationError(mp_rom_error_text_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); diff --git a/shared-bindings/memorymonitor/__init__.h b/shared-bindings/memorymonitor/__init__.h index 28480bea7b5..5f141b924d0 100644 --- a/shared-bindings/memorymonitor/__init__.h +++ b/shared-bindings/memorymonitor/__init__.h @@ -23,4 +23,4 @@ void memorymonitor_exception_print(const mp_print_t *print, mp_obj_t o_in, mp_pr extern const mp_obj_type_t mp_type_memorymonitor_AllocationError; -NORETURN void mp_raise_memorymonitor_AllocationError(mp_rom_error_text_t msg, ...); +MP_NORETURN void mp_raise_memorymonitor_AllocationError(mp_rom_error_text_t msg, ...); diff --git a/shared-bindings/microcontroller/Pin.c b/shared-bindings/microcontroller/Pin.c index e74d54b0770..1fa2366b5f3 100644 --- a/shared-bindings/microcontroller/Pin.c +++ b/shared-bindings/microcontroller/Pin.c @@ -167,22 +167,14 @@ void assert_pin_free(const mcu_pin_obj_t *pin) { } } -void validate_pins(qstr what, uint8_t *pin_nos, mp_int_t max_pins, mp_obj_t seq, uint8_t *count_out) { - const 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++) { - pin_nos[i] = common_hal_mcu_pin_number(pins[i]); - } -} - -NORETURN void raise_ValueError_invalid_pin(void) { +MP_NORETURN void raise_ValueError_invalid_pin(void) { mp_arg_error_invalid(MP_QSTR_pin); } -NORETURN void raise_ValueError_invalid_pins(void) { +MP_NORETURN void raise_ValueError_invalid_pins(void) { mp_arg_error_invalid(MP_QSTR_pins); } -NORETURN void raise_ValueError_invalid_pin_name(qstr pin_name) { +MP_NORETURN void raise_ValueError_invalid_pin_name(qstr pin_name) { mp_raise_ValueError_varg(MP_ERROR_TEXT("Invalid %q pin"), pin_name); } diff --git a/shared-bindings/microcontroller/Pin.h b/shared-bindings/microcontroller/Pin.h index 1245b5f23e4..f197f60b189 100644 --- a/shared-bindings/microcontroller/Pin.h +++ b/shared-bindings/microcontroller/Pin.h @@ -20,19 +20,13 @@ const mcu_pin_obj_t *validate_obj_is_free_pin_or_none(mp_obj_t obj, qstr arg_nam void validate_no_duplicate_pins(mp_obj_t seq, qstr arg_name); void validate_no_duplicate_pins_2(mp_obj_t seq1, mp_obj_t seq2, qstr arg_name1, qstr arg_name2); void validate_list_is_free_pins(qstr what, const mcu_pin_obj_t **pins_out, mp_int_t max_pins, mp_obj_t seq, uint8_t *count_out); -void validate_pins(qstr what, uint8_t *pin_nos, mp_int_t max_pins, mp_obj_t seq, uint8_t *count_out); -NORETURN void raise_ValueError_invalid_pin(void); -NORETURN void raise_ValueError_invalid_pins(void); -NORETURN void raise_ValueError_invalid_pin_name(qstr pin_name); +MP_NORETURN void raise_ValueError_invalid_pin(void); +MP_NORETURN void raise_ValueError_invalid_pins(void); +MP_NORETURN void raise_ValueError_invalid_pin_name(qstr pin_name); void assert_pin_free(const mcu_pin_obj_t *pin); bool common_hal_mcu_pin_is_free(const mcu_pin_obj_t *pin); -void common_hal_never_reset_pin(const mcu_pin_obj_t *pin); -void common_hal_reset_pin(const mcu_pin_obj_t *pin); -uint8_t common_hal_mcu_pin_number(const mcu_pin_obj_t *pin); -void common_hal_mcu_pin_claim(const mcu_pin_obj_t *pin); -void common_hal_mcu_pin_claim_number(uint8_t pin_no); void common_hal_mcu_pin_reset_number(uint8_t pin_no); void shared_bindings_microcontroller_pin_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind); diff --git a/shared-bindings/microcontroller/Processor.c b/shared-bindings/microcontroller/Processor.c index a3518ab754f..e0fd68be2ad 100644 --- a/shared-bindings/microcontroller/Processor.c +++ b/shared-bindings/microcontroller/Processor.c @@ -17,6 +17,8 @@ #include "py/mperrno.h" #include "py/objtype.h" #include "py/objproperty.h" +#include "py/objstr.h" +#include "py/persistentcode.h" #include "py/runtime.h" @@ -44,11 +46,41 @@ //| ... //| +//| architecture: Optional[str] +//| """The native ``.mpy`` architecture this build can load, as a `str`. (read-only) +//| +//| This is the name ``mpy-cross`` takes for ``-march``, such as ``"armv6m"``, +//| ``"armv7emsp"``, ``"xtensawin"`` or ``"rv32imc"``. +//| +//| Is `None` if this build cannot load native code from ``.mpy`` files. +//| """ +#if MICROPY_PERSISTENT_CODE_LOAD_NATIVE +static const MP_DEFINE_STR_OBJ(mcu_processor_architecture_str_obj, MPY_FEATURE_ARCH_NAME); +#endif + +static mp_obj_t mcu_processor_get_architecture(mp_obj_t self) { + #if MICROPY_PERSISTENT_CODE_LOAD_NATIVE + return MP_OBJ_FROM_PTR(&mcu_processor_architecture_str_obj); + #else + return mp_const_none; + #endif +} + +MP_DEFINE_CONST_FUN_OBJ_1(mcu_processor_get_architecture_obj, mcu_processor_get_architecture); + +MP_PROPERTY_GETTER(mcu_processor_architecture_obj, + (mp_obj_t)&mcu_processor_get_architecture_obj); + //| frequency: int //| """The CPU operating frequency in Hertz. //| //| **Limitations:** On most boards, ``frequency`` is read-only. Setting -//| the ``frequency`` is possible on RP2040 boards, some ESP32 boards and some i.MX boards. +//| the ``frequency`` is possible on RP2040 and RP2350 boards, some ESP32 boards and some +//| i.MX boards. +//| +//| .. note:: On RP2040, the flash clock is the CPU frequency divided by an +//| even number, and is at most 62.5 MHz. So some frequencies just above +//| 125 MHz, such as 150 MHz, run Python code more slowly than 125 MHz. //| //| .. warning:: Overclocking likely voids your warranties and may reduce //| the lifetime of the chip. @@ -100,7 +132,8 @@ MP_PROPERTY_GETTER(mcu_processor_reset_reason_obj, //| //| Is `None` if the temperature is not available. //| -//| **Limitations:** Not available on ESP32 or ESP32-S3. On small SAMD21 builds without external flash, +//| **Limitations:** Not available on ESP32, MAX32, Spresense, STM chips other than STM32F4, +//| or Zephyr-based boards. On small SAMD21 builds without external flash, //| the reported temperature has reduced accuracy and precision, to save code space. //| """ static mp_obj_t mcu_processor_get_temperature(mp_obj_t self) { @@ -143,6 +176,7 @@ MP_PROPERTY_GETTER(mcu_processor_voltage_obj, (mp_obj_t)&mcu_processor_get_voltage_obj); static const mp_rom_map_elem_t mcu_processor_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_architecture), MP_ROM_PTR(&mcu_processor_architecture_obj) }, { MP_ROM_QSTR(MP_QSTR_frequency), MP_ROM_PTR(&mcu_processor_frequency_obj) }, { MP_ROM_QSTR(MP_QSTR_reset_reason), MP_ROM_PTR(&mcu_processor_reset_reason_obj) }, { MP_ROM_QSTR(MP_QSTR_temperature), MP_ROM_PTR(&mcu_processor_temperature_obj) }, diff --git a/shared-bindings/microcontroller/ResetReason.c b/shared-bindings/microcontroller/ResetReason.c index e16e8a056fb..46eb23e36aa 100644 --- a/shared-bindings/microcontroller/ResetReason.c +++ b/shared-bindings/microcontroller/ResetReason.c @@ -9,14 +9,14 @@ #include "shared-bindings/microcontroller/ResetReason.h" -MAKE_ENUM_VALUE(mcu_reset_reason_type, reset_reason, POWER_ON, RESET_REASON_POWER_ON); -MAKE_ENUM_VALUE(mcu_reset_reason_type, reset_reason, BROWNOUT, RESET_REASON_BROWNOUT); -MAKE_ENUM_VALUE(mcu_reset_reason_type, reset_reason, SOFTWARE, RESET_REASON_SOFTWARE); -MAKE_ENUM_VALUE(mcu_reset_reason_type, reset_reason, DEEP_SLEEP_ALARM, RESET_REASON_DEEP_SLEEP_ALARM); -MAKE_ENUM_VALUE(mcu_reset_reason_type, reset_reason, RESET_PIN, RESET_REASON_RESET_PIN); -MAKE_ENUM_VALUE(mcu_reset_reason_type, reset_reason, WATCHDOG, RESET_REASON_WATCHDOG); -MAKE_ENUM_VALUE(mcu_reset_reason_type, reset_reason, UNKNOWN, RESET_REASON_UNKNOWN); -MAKE_ENUM_VALUE(mcu_reset_reason_type, reset_reason, RESCUE_DEBUG, RESET_REASON_RESCUE_DEBUG); +MAKE_ENUM_VALUE(mcu_reset_reason_type, reset_reason, POWER_ON, MCU_RESET_REASON_POWER_ON); +MAKE_ENUM_VALUE(mcu_reset_reason_type, reset_reason, BROWNOUT, MCU_RESET_REASON_BROWNOUT); +MAKE_ENUM_VALUE(mcu_reset_reason_type, reset_reason, SOFTWARE, MCU_RESET_REASON_SOFTWARE); +MAKE_ENUM_VALUE(mcu_reset_reason_type, reset_reason, DEEP_SLEEP_ALARM, MCU_RESET_REASON_DEEP_SLEEP_ALARM); +MAKE_ENUM_VALUE(mcu_reset_reason_type, reset_reason, RESET_PIN, MCU_RESET_REASON_RESET_PIN); +MAKE_ENUM_VALUE(mcu_reset_reason_type, reset_reason, WATCHDOG, MCU_RESET_REASON_WATCHDOG); +MAKE_ENUM_VALUE(mcu_reset_reason_type, reset_reason, UNKNOWN, MCU_RESET_REASON_UNKNOWN); +MAKE_ENUM_VALUE(mcu_reset_reason_type, reset_reason, RESCUE_DEBUG, MCU_RESET_REASON_RESCUE_DEBUG); //| class ResetReason: //| """The reason the microcontroller was last reset""" diff --git a/shared-bindings/microcontroller/ResetReason.h b/shared-bindings/microcontroller/ResetReason.h index 61ff80639a6..772d7ff4ba4 100644 --- a/shared-bindings/microcontroller/ResetReason.h +++ b/shared-bindings/microcontroller/ResetReason.h @@ -10,14 +10,14 @@ #include "py/enum.h" typedef enum { - RESET_REASON_POWER_ON, - RESET_REASON_BROWNOUT, - RESET_REASON_SOFTWARE, - RESET_REASON_DEEP_SLEEP_ALARM, - RESET_REASON_RESET_PIN, - RESET_REASON_WATCHDOG, - RESET_REASON_UNKNOWN, - RESET_REASON_RESCUE_DEBUG, + MCU_RESET_REASON_POWER_ON, + MCU_RESET_REASON_BROWNOUT, + MCU_RESET_REASON_SOFTWARE, + MCU_RESET_REASON_DEEP_SLEEP_ALARM, + MCU_RESET_REASON_RESET_PIN, + MCU_RESET_REASON_WATCHDOG, + MCU_RESET_REASON_UNKNOWN, + MCU_RESET_REASON_RESCUE_DEBUG, } mcu_reset_reason_t; extern const mp_obj_type_t mcu_reset_reason_type; diff --git a/shared-bindings/microcontroller/__init__.h b/shared-bindings/microcontroller/__init__.h index a94cca7b697..5c5902ff965 100644 --- a/shared-bindings/microcontroller/__init__.h +++ b/shared-bindings/microcontroller/__init__.h @@ -20,7 +20,7 @@ extern void common_hal_mcu_disable_interrupts(void); extern void common_hal_mcu_enable_interrupts(void); extern void common_hal_mcu_on_next_reset(mcu_runmode_t runmode); -extern void common_hal_mcu_reset(void); +MP_NORETURN extern void common_hal_mcu_reset(void); extern const mp_obj_dict_t mcu_pin_globals; diff --git a/shared-bindings/mii/Ethernet.c b/shared-bindings/mii/Ethernet.c new file mode 100644 index 00000000000..a1ff4430f93 --- /dev/null +++ b/shared-bindings/mii/Ethernet.c @@ -0,0 +1,381 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/mii/Ethernet.h" + +#include + +#include "py/runtime.h" +#include "py/objproperty.h" +#include "shared-bindings/mii/RMII.h" +#include "shared-bindings/microcontroller/Pin.h" + +#define MAC_ADDRESS_LENGTH 6 + +static bool hostname_valid(const char *ptr, size_t len) { + int partlen = 0; + while (len) { + char c = *ptr++; + len--; + if (c == '.') { + if (partlen == 0 || partlen > 63) { + return false; + } + partlen = 0; + continue; + } + partlen++; + if (c == '-') { + if (partlen == 1) { + return false; // part cannot begin with a dash + } + continue; + } else if ( + (c >= 'a' && c <= 'z') || + (c >= 'A' && c <= 'Z') || + (c >= '0' && c <= '9')) { + continue; + } + return false; + } + // check length of last part + return !(partlen > 63); +} + +//| class Ethernet: +//| """Wired ethernet interface. +//| +//| Boards with onboard ethernet PHYs provide it as ``board.ETHERNET`` or another distinguishing name. +//| +//| Further interfaces can be created by wiring an external +//| PHY over a variant of the media independent interface (MII) bus. See other classes in this module for supported MII variants. +//| The interface is enabled and DHCP is started automatically. +//| """ +//| +//| def __init__( +//| self, +//| rmii: mii.RMII, +//| ) -> None: +//| """Create another ethernet interface driving the PHY wired to ``rmii``. +//| +//| Only Espressif ports support this; Zephyr ports only serve the +//| interface from the devicetree, available as ``board.ETHERNET``, +//| and raise NotImplementedError here.""" +//| ... +//| + +//| enabled: bool +//| """``True`` when the ethernet interface is enabled. +//| If you set the value to ``False``, any open sockets will be closed. +//| """ +static mp_obj_t mii_ethernet_get_enabled(mp_obj_t self) { + return mp_obj_new_bool(common_hal_mii_ethernet_get_enabled(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(mii_ethernet_get_enabled_obj, mii_ethernet_get_enabled); + +static mp_obj_t mii_ethernet_set_enabled(mp_obj_t self, mp_obj_t value) { + const bool enabled = mp_obj_is_true(value); + common_hal_mii_ethernet_set_enabled(self, enabled); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(mii_ethernet_set_enabled_obj, mii_ethernet_set_enabled); + +MP_PROPERTY_GETSET(mii_ethernet_enabled_obj, + (mp_obj_t)&mii_ethernet_get_enabled_obj, + (mp_obj_t)&mii_ethernet_set_enabled_obj); + +//| connected: bool +//| """``True`` when the ethernet cable is plugged in and link is up. (read-only)""" +static mp_obj_t mii_ethernet_get_connected(mp_obj_t self) { + return mp_obj_new_bool(common_hal_mii_ethernet_get_connected(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(mii_ethernet_get_connected_obj, mii_ethernet_get_connected); + +MP_PROPERTY_GETTER(mii_ethernet_connected_obj, + (mp_obj_t)&mii_ethernet_get_connected_obj); + +//| hostname: Union[str, ReadableBuffer] +//| """Hostname for the ethernet interface. When the hostname is altered after the interface +//| is started the changes would only be reflected once the interface restarts.""" +static mp_obj_t mii_ethernet_get_hostname(mp_obj_t self_in) { + mii_ethernet_obj_t *self = MP_OBJ_TO_PTR(self_in); + return common_hal_mii_ethernet_get_hostname(self); +} +MP_DEFINE_CONST_FUN_OBJ_1(mii_ethernet_get_hostname_obj, mii_ethernet_get_hostname); + +static mp_obj_t mii_ethernet_set_hostname(mp_obj_t self_in, mp_obj_t hostname_in) { + mp_buffer_info_t hostname; + mp_get_buffer_raise(hostname_in, &hostname, MP_BUFFER_READ); + + mp_arg_validate_length_range(hostname.len, 1, 253, MP_QSTR_hostname); + + if (!hostname_valid(hostname.buf, hostname.len)) { + mp_raise_ValueError(MP_ERROR_TEXT("invalid hostname")); + } + + mii_ethernet_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_mii_ethernet_set_hostname(self, hostname.buf); + + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(mii_ethernet_set_hostname_obj, mii_ethernet_set_hostname); + +MP_PROPERTY_GETSET(mii_ethernet_hostname_obj, + (mp_obj_t)&mii_ethernet_get_hostname_obj, + (mp_obj_t)&mii_ethernet_set_hostname_obj); + +//| mac_address: bytes +//| """MAC address of the ethernet interface. (read-only, 6 bytes)""" +static mp_obj_t mii_ethernet_get_mac_address(mp_obj_t self_in) { + mii_ethernet_obj_t *self = MP_OBJ_TO_PTR(self_in); + return MP_OBJ_FROM_PTR(common_hal_mii_ethernet_get_mac_address(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(mii_ethernet_get_mac_address_obj, mii_ethernet_get_mac_address); + +MP_PROPERTY_GETTER(mii_ethernet_mac_address_obj, + (mp_obj_t)&mii_ethernet_get_mac_address_obj); + +//| link_speed: int +//| """Link speed in Mbps (10, 100, 1000, etc.) when connected, 0 otherwise. (read-only)""" +static mp_obj_t mii_ethernet_get_link_speed(mp_obj_t self_in) { + mii_ethernet_obj_t *self = MP_OBJ_TO_PTR(self_in); + return MP_OBJ_NEW_SMALL_INT(common_hal_mii_ethernet_get_link_speed(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(mii_ethernet_get_link_speed_obj, mii_ethernet_get_link_speed); + +MP_PROPERTY_GETTER(mii_ethernet_link_speed_obj, + (mp_obj_t)&mii_ethernet_get_link_speed_obj); + +//| full_duplex: bool +//| """``True`` if the link is full duplex, ``False`` if half duplex. (read-only)""" +static mp_obj_t mii_ethernet_get_full_duplex(mp_obj_t self_in) { + mii_ethernet_obj_t *self = MP_OBJ_TO_PTR(self_in); + return mp_obj_new_bool(common_hal_mii_ethernet_get_full_duplex(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(mii_ethernet_get_full_duplex_obj, mii_ethernet_get_full_duplex); + +MP_PROPERTY_GETTER(mii_ethernet_full_duplex_obj, + (mp_obj_t)&mii_ethernet_get_full_duplex_obj); + +//| ipv4_address: Optional[ipaddress.IPv4Address] +//| """IP v4 address when connected. None otherwise. (read-only)""" +static mp_obj_t mii_mii_get_ipv4_address(mp_obj_t self) { + return common_hal_mii_mii_get_ipv4_address(self); +} +MP_DEFINE_CONST_FUN_OBJ_1(mii_mii_get_ipv4_address_obj, mii_mii_get_ipv4_address); + +MP_PROPERTY_GETTER(mii_ethernet_ipv4_address_obj, + (mp_obj_t)&mii_mii_get_ipv4_address_obj); + +//| ipv4_gateway: Optional[ipaddress.IPv4Address] +//| """IP v4 gateway address when connected. None otherwise. (read-only)""" +static mp_obj_t mii_ethernet_get_ipv4_gateway(mp_obj_t self) { + return common_hal_mii_ethernet_get_ipv4_gateway(self); +} +MP_DEFINE_CONST_FUN_OBJ_1(mii_ethernet_get_ipv4_gateway_obj, mii_ethernet_get_ipv4_gateway); + +MP_PROPERTY_GETTER(mii_ethernet_ipv4_gateway_obj, + (mp_obj_t)&mii_ethernet_get_ipv4_gateway_obj); + +//| ipv4_subnet: Optional[ipaddress.IPv4Address] +//| """IP v4 subnet mask when connected. None otherwise. (read-only)""" +static mp_obj_t mii_ethernet_get_ipv4_subnet(mp_obj_t self) { + return common_hal_mii_ethernet_get_ipv4_subnet(self); +} +MP_DEFINE_CONST_FUN_OBJ_1(mii_ethernet_get_ipv4_subnet_obj, mii_ethernet_get_ipv4_subnet); + +MP_PROPERTY_GETTER(mii_ethernet_ipv4_subnet_obj, + (mp_obj_t)&mii_ethernet_get_ipv4_subnet_obj); + +//| ipv4_dns: ipaddress.IPv4Address +//| """IP v4 address of the DNS server to be used.""" +static mp_obj_t mii_ethernet_get_ipv4_dns(mp_obj_t self) { + return common_hal_mii_ethernet_get_ipv4_dns(self); +} +MP_DEFINE_CONST_FUN_OBJ_1(mii_ethernet_get_ipv4_dns_obj, mii_ethernet_get_ipv4_dns); + +static mp_obj_t mii_ethernet_set_ipv4_dns(mp_obj_t self, mp_obj_t ipv4_dns_addr) { + common_hal_mii_ethernet_set_ipv4_dns(self, ipv4_dns_addr); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(mii_ethernet_set_ipv4_dns_obj, mii_ethernet_set_ipv4_dns); + +MP_PROPERTY_GETSET(mii_ethernet_ipv4_dns_obj, + (mp_obj_t)&mii_ethernet_get_ipv4_dns_obj, + (mp_obj_t)&mii_ethernet_set_ipv4_dns_obj); + +//| addresses: Sequence[str] +//| """Address(es) of the interface when connected. Empty sequence when not connected. (read-only)""" +static mp_obj_t mii_ethernet_get_addresses(mp_obj_t self) { + return common_hal_mii_ethernet_get_addresses(self); +} +MP_DEFINE_CONST_FUN_OBJ_1(mii_ethernet_get_addresses_obj, mii_ethernet_get_addresses); + +MP_PROPERTY_GETTER(mii_ethernet_addresses_obj, + (mp_obj_t)&mii_ethernet_get_addresses_obj); + +//| dns: Sequence[str] +//| """Address of the DNS server to be used.""" +//| +static mp_obj_t mii_ethernet_get_dns(mp_obj_t self) { + return common_hal_mii_ethernet_get_dns(self); +} +MP_DEFINE_CONST_FUN_OBJ_1(mii_ethernet_get_dns_obj, mii_ethernet_get_dns); + +static mp_obj_t mii_ethernet_set_dns(mp_obj_t self, mp_obj_t dns_addr) { + common_hal_mii_ethernet_set_dns(self, dns_addr); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(mii_ethernet_set_dns_obj, mii_ethernet_set_dns); + +MP_PROPERTY_GETSET(mii_ethernet_dns_obj, + (mp_obj_t)&mii_ethernet_get_dns_obj, + (mp_obj_t)&mii_ethernet_set_dns_obj); + +//| def set_ipv4_address( +//| self, +//| *, +//| ipv4: ipaddress.IPv4Address, +//| netmask: ipaddress.IPv4Address, +//| gateway: ipaddress.IPv4Address, +//| ipv4_dns: Optional[ipaddress.IPv4Address], +//| ) -> None: +//| """Sets the IP v4 address of the interface. Must include the netmask and gateway. +//| DNS address is optional. Setting the address manually will stop the DHCP client.""" +//| ... +//| +static mp_obj_t mii_ethernet_set_ipv4_address(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_ipv4, ARG_netmask, ARG_gateway, ARG_ipv4_dns }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_ipv4, MP_ARG_REQUIRED | MP_ARG_KW_ONLY | MP_ARG_OBJ, }, + { MP_QSTR_netmask, MP_ARG_REQUIRED | MP_ARG_KW_ONLY | MP_ARG_OBJ, }, + { MP_QSTR_gateway, MP_ARG_REQUIRED | MP_ARG_KW_ONLY | MP_ARG_OBJ, }, + { MP_QSTR_ipv4_dns, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_OBJ_NULL} }, + }; + + mii_ethernet_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]); + 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); + + common_hal_mii_ethernet_set_ipv4_address(self, args[ARG_ipv4].u_obj, args[ARG_netmask].u_obj, args[ARG_gateway].u_obj, args[ARG_ipv4_dns].u_obj); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_KW(mii_ethernet_set_ipv4_address_obj, 1, mii_ethernet_set_ipv4_address); + +//| def start_dhcp(self, *, ipv4: bool = True, ipv6: bool = False) -> None: +//| """Starts the DHCP client. +//| +//| By default, calling this function starts DHCP for IPv4 networks but not +//| IPv6 networks. When the ``ipv4`` and ``ipv6`` arguments are `False` +//| then the corresponding DHCP client is stopped if it was active. +//| """ +//| ... +//| +static mp_obj_t mii_ethernet_start_dhcp_client(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_ipv4, ARG_ipv6 }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_ipv4, MP_ARG_KW_ONLY | MP_ARG_BOOL, { .u_bool = true } }, + { MP_QSTR_ipv6, MP_ARG_KW_ONLY | MP_ARG_BOOL, { .u_bool = false } }, + }; + + mii_ethernet_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]); + 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); + + common_hal_mii_ethernet_start_dhcp_client(self, args[ARG_ipv4].u_bool, args[ARG_ipv6].u_bool); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_KW(mii_ethernet_start_dhcp_client_obj, 1, mii_ethernet_start_dhcp_client); + +//| def stop_dhcp(self) -> None: +//| """Stops the DHCP client. Needed to assign a static IP address.""" +//| ... +//| +static mp_obj_t mii_ethernet_stop_dhcp_client(mp_obj_t self) { + common_hal_mii_ethernet_stop_dhcp_client(self); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_1(mii_ethernet_stop_dhcp_client_obj, mii_ethernet_stop_dhcp_client); + +//| def ping( +//| self, ip: ipaddress.IPv4Address, *, timeout: Optional[float] = 0.5 +//| ) -> Optional[float]: +//| """Ping an IP to test connectivity. Returns echo time in seconds. +//| Returns None when it times out.""" +//| ... +//| +//| +static mp_obj_t mii_ethernet_ping(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_ip, ARG_timeout }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_ip, MP_ARG_REQUIRED | MP_ARG_OBJ, }, + { MP_QSTR_timeout, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, + }; + + mii_ethernet_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]); + 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_float_t timeout = 0.5; + if (args[ARG_timeout].u_obj != mp_const_none) { + timeout = mp_obj_get_float(args[ARG_timeout].u_obj); + } + + mp_int_t time_ms = common_hal_mii_ethernet_ping(self, args[ARG_ip].u_obj, timeout); + if (time_ms == -1) { + return mp_const_none; + } + + return mp_obj_new_float(time_ms / 1000.0); +} +static MP_DEFINE_CONST_FUN_OBJ_KW(mii_ethernet_ping_obj, 1, mii_ethernet_ping); + +static mp_obj_t mii_ethernet_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + mp_arg_check_num(n_args, n_kw, 1, 1, false); + + mp_arg_validate_type(all_args[0], &mii_rmii_type, MP_QSTR_rmii); + mii_rmii_obj_t *rmii = MP_OBJ_TO_PTR(all_args[0]); + + mii_ethernet_obj_t *self = mp_obj_malloc(mii_ethernet_obj_t, &mii_ethernet_type); + common_hal_mii_ethernet_construct(self, rmii); + return MP_OBJ_FROM_PTR(self); +} + +static const mp_rom_map_elem_t mii_ethernet_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_enabled), MP_ROM_PTR(&mii_ethernet_enabled_obj) }, + { MP_ROM_QSTR(MP_QSTR_connected), MP_ROM_PTR(&mii_ethernet_connected_obj) }, + + { MP_ROM_QSTR(MP_QSTR_hostname), MP_ROM_PTR(&mii_ethernet_hostname_obj) }, + { MP_ROM_QSTR(MP_QSTR_mac_address), MP_ROM_PTR(&mii_ethernet_mac_address_obj) }, + + { MP_ROM_QSTR(MP_QSTR_link_speed), MP_ROM_PTR(&mii_ethernet_link_speed_obj) }, + { MP_ROM_QSTR(MP_QSTR_full_duplex), MP_ROM_PTR(&mii_ethernet_full_duplex_obj) }, + + { MP_ROM_QSTR(MP_QSTR_start_dhcp), MP_ROM_PTR(&mii_ethernet_start_dhcp_client_obj) }, + { MP_ROM_QSTR(MP_QSTR_stop_dhcp), MP_ROM_PTR(&mii_ethernet_stop_dhcp_client_obj) }, + + { MP_ROM_QSTR(MP_QSTR_ipv4_dns), MP_ROM_PTR(&mii_ethernet_ipv4_dns_obj) }, + { MP_ROM_QSTR(MP_QSTR_ipv4_gateway), MP_ROM_PTR(&mii_ethernet_ipv4_gateway_obj) }, + { MP_ROM_QSTR(MP_QSTR_ipv4_subnet), MP_ROM_PTR(&mii_ethernet_ipv4_subnet_obj) }, + { MP_ROM_QSTR(MP_QSTR_ipv4_address), MP_ROM_PTR(&mii_ethernet_ipv4_address_obj) }, + + { MP_ROM_QSTR(MP_QSTR_set_ipv4_address), MP_ROM_PTR(&mii_ethernet_set_ipv4_address_obj) }, + + { MP_ROM_QSTR(MP_QSTR_addresses), MP_ROM_PTR(&mii_ethernet_addresses_obj) }, + { MP_ROM_QSTR(MP_QSTR_dns), MP_ROM_PTR(&mii_ethernet_dns_obj) }, + + { MP_ROM_QSTR(MP_QSTR_ping), MP_ROM_PTR(&mii_ethernet_ping_obj) }, +}; + +static MP_DEFINE_CONST_DICT(mii_ethernet_locals_dict, mii_ethernet_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + mii_ethernet_type, + MP_QSTR_Ethernet, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, &mii_ethernet_make_new, + locals_dict, &mii_ethernet_locals_dict + ); diff --git a/shared-bindings/mii/Ethernet.h b/shared-bindings/mii/Ethernet.h new file mode 100644 index 00000000000..90d4bf1c912 --- /dev/null +++ b/shared-bindings/mii/Ethernet.h @@ -0,0 +1,45 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include + +#include "common-hal/mii/Ethernet.h" + +#include "py/objstr.h" + +extern const mp_obj_type_t mii_ethernet_type; + +extern bool common_hal_mii_ethernet_get_enabled(mii_ethernet_obj_t *self); +extern void common_hal_mii_ethernet_set_enabled(mii_ethernet_obj_t *self, bool enabled); + +extern bool common_hal_mii_ethernet_get_connected(mii_ethernet_obj_t *self); + +extern mp_obj_t common_hal_mii_ethernet_get_hostname(mii_ethernet_obj_t *self); +extern void common_hal_mii_ethernet_set_hostname(mii_ethernet_obj_t *self, const char *hostname); + +extern mp_obj_t common_hal_mii_ethernet_get_mac_address(mii_ethernet_obj_t *self); + +extern mp_int_t common_hal_mii_ethernet_get_link_speed(mii_ethernet_obj_t *self); +extern bool common_hal_mii_ethernet_get_full_duplex(mii_ethernet_obj_t *self); + +extern void common_hal_mii_ethernet_start_dhcp_client(mii_ethernet_obj_t *self, bool ipv4, bool ipv6); +extern void common_hal_mii_ethernet_stop_dhcp_client(mii_ethernet_obj_t *self); + +extern mp_obj_t common_hal_mii_ethernet_get_ipv4_dns(mii_ethernet_obj_t *self); +extern void common_hal_mii_ethernet_set_ipv4_dns(mii_ethernet_obj_t *self, mp_obj_t ipv4_dns_addr); +extern mp_obj_t common_hal_mii_ethernet_get_ipv4_gateway(mii_ethernet_obj_t *self); +extern mp_obj_t common_hal_mii_ethernet_get_ipv4_subnet(mii_ethernet_obj_t *self); +extern mp_obj_t common_hal_mii_mii_get_ipv4_address(mii_ethernet_obj_t *self); + +extern mp_obj_t common_hal_mii_ethernet_get_addresses(mii_ethernet_obj_t *self); +extern mp_obj_t common_hal_mii_ethernet_get_dns(mii_ethernet_obj_t *self); +extern void common_hal_mii_ethernet_set_dns(mii_ethernet_obj_t *self, mp_obj_t dns_addr); + +extern void common_hal_mii_ethernet_set_ipv4_address(mii_ethernet_obj_t *self, mp_obj_t ipv4, mp_obj_t netmask, mp_obj_t gateway, mp_obj_t ipv4_dns_addr); + +extern mp_int_t common_hal_mii_ethernet_ping(mii_ethernet_obj_t *self, mp_obj_t ip_address, mp_float_t timeout); diff --git a/shared-bindings/mii/MDIO.c b/shared-bindings/mii/MDIO.c new file mode 100644 index 00000000000..2a87f65f9ba --- /dev/null +++ b/shared-bindings/mii/MDIO.c @@ -0,0 +1,60 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/mii/MDIO.h" + +#include "py/runtime.h" +#include "shared-bindings/microcontroller/Pin.h" + +//| class MDIO: +//| """Management data input/output (MDIO) bus wiring. +//| +//| MDIO is the two wire management bus used to configure Ethernet PHYs +//| over an `mii` variant. ``mdc`` is the management data clock and +//| ``mdio`` is the bidirectional management data line. Configuration +//| commands on the bus address a PHY by a number between 0 and 31, so, +//| like I2C, multiple PHYs can share one bus. +//| """ +//| +//| def __init__( +//| self, +//| mdc: microcontroller.Pin, +//| mdio: microcontroller.Pin, +//| ) -> None: +//| """Create the MDIO bus on the given clock and data pins.""" +//| ... +//| +//| +static mp_obj_t mii_mdio_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_mdc, ARG_mdio }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_mdc, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_mdio, MP_ARG_REQUIRED | MP_ARG_OBJ }, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + const mcu_pin_obj_t *mdc = validate_obj_is_free_pin(args[ARG_mdc].u_obj, MP_QSTR_mdc); + const mcu_pin_obj_t *mdio = validate_obj_is_free_pin(args[ARG_mdio].u_obj, MP_QSTR_mdio); + + mii_mdio_obj_t *self = m_new_obj(mii_mdio_obj_t); + self->base.type = &mii_mdio_type; + common_hal_mii_mdio_construct(self, mdc, mdio); + return MP_OBJ_FROM_PTR(self); +} + +static const mp_rom_map_elem_t mii_mdio_locals_dict_table[] = { + // No public members; the bus is handed to the mii variants. +}; +static MP_DEFINE_CONST_DICT(mii_mdio_locals_dict, mii_mdio_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + mii_mdio_type, + MP_QSTR_MDIO, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, &mii_mdio_make_new, + locals_dict, &mii_mdio_locals_dict + ); diff --git a/shared-bindings/mii/MDIO.h b/shared-bindings/mii/MDIO.h new file mode 100644 index 00000000000..e727192ec1b --- /dev/null +++ b/shared-bindings/mii/MDIO.h @@ -0,0 +1,11 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "common-hal/mii/MDIO.h" + +extern const mp_obj_type_t mii_mdio_type; diff --git a/shared-bindings/mii/RMII.c b/shared-bindings/mii/RMII.c new file mode 100644 index 00000000000..96c85bedb49 --- /dev/null +++ b/shared-bindings/mii/RMII.c @@ -0,0 +1,104 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/mii/RMII.h" + +#include "py/runtime.h" +#include "shared-bindings/mii/MDIO.h" +#include "shared-bindings/microcontroller/Pin.h" + +//| class RMII: +//| """Reduced media independent interface (RMII) bus wiring for the built-in ethernet MAC. +//| +//| RMII is a pin-reduced variant of the media independent interface (MII) family: it +//| shifts two data bits on a pair of pins at a 50 MHz reference clock instead of +//| running a wider bus more slowly, saving pins on microcontrollers. The PHY sends +//| data to the MAC over ``rxd0`` and ``rxd1`` and marks received bytes with +//| ``rx_dv`` (receive data valid). The MAC sends data back over ``txd0`` and ``txd1`` +//| and frames it with ``tx_en`` (transmit enable). ``refclk`` is the 50 MHz reference +//| clock, usually driven by an oscillator on the PHY. +//| +//| The PHY is configured over an `mii.MDIO` management bus, which may be shared +//| between interfaces; pass it as ``mdio``. ``device`` selects the PHY's MDIO +//| address (0-31) on that bus, so that two `mii.Ethernet` interfaces on chips +//| with more than one MAC can share it. Optionally, pass ``reset`` wired to +//| the PHY's active-low reset, if it has one. +//| +//| Not all chips can route RMII signals freely: ports that can't (or +//| Zephyr ports, which take their wiring from the devicetree) raise +//| NotImplementedError. +//| """ +//| + +//| def __init__( +//| self, +//| mdio: mii.MDIO, +//| device: int, +//| rxd0: microcontroller.Pin, +//| rxd1: microcontroller.Pin, +//| rx_dv: microcontroller.Pin, +//| txd0: microcontroller.Pin, +//| txd1: microcontroller.Pin, +//| tx_en: microcontroller.Pin, +//| refclk: microcontroller.Pin, +//| reset: Optional[microcontroller.Pin] = None, +//| ) -> None: +//| """Create the RMII bus on the given `mii.MDIO` management bus, with the PHY +//| at its MDIO ``device`` address, and the given data signals.""" +//| ... +//| +//| +static mp_obj_t mii_rmii_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_mdio, ARG_device, ARG_rxd0, ARG_rxd1, ARG_rx_dv, ARG_txd0, ARG_txd1, ARG_tx_en, ARG_refclk, ARG_reset }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_mdio, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_device, MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_rxd0, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_rxd1, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_rx_dv, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_txd0, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_txd1, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_tx_en, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_refclk, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_reset, MP_ARG_KW_ONLY | MP_ARG_OBJ, { .u_obj = mp_const_none } }, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + mp_arg_validate_type(args[ARG_mdio].u_obj, &mii_mdio_type, MP_QSTR_mdio); + mii_mdio_obj_t *mdio = MP_OBJ_TO_PTR(args[ARG_mdio].u_obj); + (void)mp_arg_validate_int_range(args[ARG_device].u_int, 0, 31, MP_QSTR_device); + const mcu_pin_obj_t *rxd0 = validate_obj_is_free_pin(args[ARG_rxd0].u_obj, MP_QSTR_rxd0); + const mcu_pin_obj_t *rxd1 = validate_obj_is_free_pin(args[ARG_rxd1].u_obj, MP_QSTR_rxd1); + const mcu_pin_obj_t *rx_dv = validate_obj_is_free_pin(args[ARG_rx_dv].u_obj, MP_QSTR_rx_dv); + const mcu_pin_obj_t *txd0 = validate_obj_is_free_pin(args[ARG_txd0].u_obj, MP_QSTR_txd0); + const mcu_pin_obj_t *txd1 = validate_obj_is_free_pin(args[ARG_txd1].u_obj, MP_QSTR_txd1); + const mcu_pin_obj_t *tx_en = validate_obj_is_free_pin(args[ARG_tx_en].u_obj, MP_QSTR_tx_en); + const mcu_pin_obj_t *refclk = validate_obj_is_free_pin(args[ARG_refclk].u_obj, MP_QSTR_refclk); + const mcu_pin_obj_t *reset = NULL; + if (args[ARG_reset].u_obj != mp_const_none) { + reset = validate_obj_is_free_pin(args[ARG_reset].u_obj, MP_QSTR_reset); + } + + mii_rmii_obj_t *self = m_new_obj(mii_rmii_obj_t); + self->base.type = &mii_rmii_type; + common_hal_mii_rmii_construct(self, mdio, (uint32_t)args[ARG_device].u_int, + rxd0, rxd1, rx_dv, txd0, txd1, tx_en, refclk, reset); + return MP_OBJ_FROM_PTR(self); +} + +static const mp_rom_map_elem_t mii_rmii_locals_dict_table[] = { + // No public members; the bus is handed to mii.Ethernet. +}; +static MP_DEFINE_CONST_DICT(mii_rmii_locals_dict, mii_rmii_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + mii_rmii_type, + MP_QSTR_RMII, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, &mii_rmii_make_new, + locals_dict, &mii_rmii_locals_dict + ); diff --git a/shared-bindings/mii/RMII.h b/shared-bindings/mii/RMII.h new file mode 100644 index 00000000000..cb44aa6e1f0 --- /dev/null +++ b/shared-bindings/mii/RMII.h @@ -0,0 +1,11 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "common-hal/mii/RMII.h" + +extern const mp_obj_type_t mii_rmii_type; diff --git a/shared-bindings/mii/__init__.c b/shared-bindings/mii/__init__.c new file mode 100644 index 00000000000..f838af07380 --- /dev/null +++ b/shared-bindings/mii/__init__.c @@ -0,0 +1,37 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/mii/__init__.h" +#include "shared-bindings/mii/MDIO.h" +#include "shared-bindings/mii/Ethernet.h" +#include "shared-bindings/mii/RMII.h" + +//| """ +//| Media-independent interface (MII) is a family of standards to connect an Ethernet medium access control (MAC) peripheral to an Ethernet physical transceiver (PHY). Different versions have different pinouts depending on the pin count and Ethernet speed. Reduced pin count variants like reduced media-independent interface (RMII) and reduced gigabit media-independent interface (RGMII) are often used in microcontrollers to save pin count. +//| +//| A portion of the pins in MII are for the Management Data Input/Output (MDIO) which is used to configure the PHY. Like I2C, multiple PHYs can share an MDIO because the commands include an address. This module splits the Management Data Input/Output (MDIO) definition from the MII portion because the MDIO bus can be shared between PHYs. +//| +//| See: https://en.wikipedia.org/wiki/Media-independent_interface +//| """ +//| + +static const mp_rom_map_elem_t mii_module_globals_table[] = { + // Name + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_mii) }, + + // Classes + { MP_ROM_QSTR(MP_QSTR_MDIO), MP_ROM_PTR(&mii_mdio_type) }, + { MP_ROM_QSTR(MP_QSTR_Ethernet), MP_ROM_PTR(&mii_ethernet_type) }, + { MP_ROM_QSTR(MP_QSTR_RMII), MP_ROM_PTR(&mii_rmii_type) }, +}; +static MP_DEFINE_CONST_DICT(mii_module_globals, mii_module_globals_table); + +const mp_obj_module_t mii_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&mii_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_mii, mii_module); diff --git a/shared-bindings/mii/__init__.h b/shared-bindings/mii/__init__.h new file mode 100644 index 00000000000..3343215c114 --- /dev/null +++ b/shared-bindings/mii/__init__.h @@ -0,0 +1,42 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "common-hal/mii/Ethernet.h" + +void mii_user_reset(void); + +// Cross-translation-unit API implemented by each port's common-hal/ethernet +// for supervisor/shared/web_workflow.c. They all operate on the board's +// instance, which board code registers via mii_set_default_instance(); +// user-constructed interfaces are separate objects. + +// The board's ethernet instance as an mp_obj_t for SocketPool, or NULL when +// the board never set one. +mp_obj_t mii_get_default_instance(void); + +// Raw uint32_t IPv4 address of the interface, in network byte order, or 0 +// when the interface has none. +uint32_t mii_get_ipv4_address(void); + +// Raw hostname of the network interface as configured for the interface's +// DHCP request (option 12). Never allocates. The returned pointer points into +// storage owned by the port and stays valid until the hostname is replaced, +// so use it promptly rather than holding onto it. +const char *mii_get_hostname_raw(void); + +// Gets the hostname that common_hal_mii_ethernet_construct() gives the Ethernet +// interface. Can be called before common_hal_mii_ethernet_construct() runs. +// Writes the hostname to buf as a NUL-terminated string, truncated to fit in +// buf_size bytes. If there is no default hostname, writes "". Never allocates +// or raises. +void mii_get_default_hostname(char *buf, size_t buf_size); + +// Blocks until the interface has an IPv4 address (DHCP lease or static), or +// 20s pass, or a hard interrupt arrives. Returns immediately when the +// interface cannot ever get one (down, disabled or no link). +void mii_wait_for_lease(void); diff --git a/shared-bindings/mipicsi/BayerOrder.c b/shared-bindings/mipicsi/BayerOrder.c new file mode 100644 index 00000000000..3d57a534265 --- /dev/null +++ b/shared-bindings/mipicsi/BayerOrder.c @@ -0,0 +1,54 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include + +#include "py/enum.h" +#include "py/obj.h" +#include "py/runtime.h" + +#include "shared-bindings/mipicsi/__init__.h" + +//| class BayerOrder: +//| """The Bayer element order of a sensor's RAW output, in the sequence a 2x2 +//| pixel block transmits (top-left first, reading order)""" +//| +//| BGGR: BayerOrder +//| """The first element is Blue, then Green. The next row starts with +//| Green, then Red""" +//| +//| GBRG: BayerOrder +//| """The first element is Green, then Blue. The next row starts with +//| Red, then Green""" +//| +//| GRBG: BayerOrder +//| """The first element is Green, then Red. The next row starts with +//| Blue, then Green""" +//| +//| RGGB: BayerOrder +//| """The first element is Red, then Green. The next row starts with +//| Green, then Blue""" +//| + +MAKE_ENUM_VALUE(mipicsi_bayer_order_type, bayer_order, BGGR, MIPICSI_BAYER_ORDER_BGGR); +MAKE_ENUM_VALUE(mipicsi_bayer_order_type, bayer_order, GBRG, MIPICSI_BAYER_ORDER_GBRG); +MAKE_ENUM_VALUE(mipicsi_bayer_order_type, bayer_order, GRBG, MIPICSI_BAYER_ORDER_GRBG); +MAKE_ENUM_VALUE(mipicsi_bayer_order_type, bayer_order, RGGB, MIPICSI_BAYER_ORDER_RGGB); + +MAKE_ENUM_MAP(mipicsi_bayer_order) { + MAKE_ENUM_MAP_ENTRY(bayer_order, BGGR), + MAKE_ENUM_MAP_ENTRY(bayer_order, GBRG), + MAKE_ENUM_MAP_ENTRY(bayer_order, GRBG), + MAKE_ENUM_MAP_ENTRY(bayer_order, RGGB), +}; + +static MP_DEFINE_CONST_DICT(mipicsi_bayer_order_locals_dict, mipicsi_bayer_order_locals_table); +MAKE_PRINTER(mipicsi, mipicsi_bayer_order); +MAKE_ENUM_TYPE(mipicsi, BayerOrder, mipicsi_bayer_order); + +mipicsi_bayer_order_t validate_bayer_order(mp_obj_t obj, qstr arg_name) { + return cp_enum_value(&mipicsi_bayer_order_type, obj, arg_name); +} diff --git a/shared-bindings/mipicsi/Camera.c b/shared-bindings/mipicsi/Camera.c new file mode 100644 index 00000000000..7cce73e9ff9 --- /dev/null +++ b/shared-bindings/mipicsi/Camera.c @@ -0,0 +1,245 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Jeff Epler for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include + +#include "py/mphal.h" +#include "py/obj.h" +#include "py/objproperty.h" +#include "py/runtime.h" + +#include "shared-bindings/displayio/Bitmap.h" +#include "shared-bindings/mipicsi/__init__.h" +#include "shared-bindings/mipicsi/Camera.h" +#include "shared-bindings/util.h" +#include "shared/runtime/context_manager_helpers.h" + +#if CIRCUITPY_VIDEOCORE +#include "shared-module/videocore/__init__.h" +#endif + +//| class Camera: +//| """Receive frames from a camera sensor on a MIPI CSI-2 interface +//| +//| The camera sensor is configured separately (typically over I2C) to +//| transmit frames. Use the dedicated MIPI CSI-2 receiver pins. +//| +//| The sensor object must implement ``circuitpython_typing.CameraSensor``, +//| which has these properties: +//| +//| * ``width`` and ``height``: the image size in pixels +//| * ``pixel_format``: the `PixelFormat` the sensor transmits +//| * ``lane_bit_rate_mbps``: the bit rate of each data lane +//| * ``data_lanes``: the number of data lanes used, 1 or 2 +//| * ``bayer_order``: the `BayerOrder` of RAW data +//| +//| and these methods: +//| +//| * ``_start()``: start transmitting frames +//| * ``_stop()``: stop transmitting frames +//| +//| ``_start()`` and ``_stop()`` are internal. The camera calls them when +//| streaming starts and stops; user code should not call them. +//| +//| The sensor's properties are validated when the Camera is created and +//| are validated again when `videocore.VideoBuffer.play()` is called. The +//| sensor may change its configuration while it is not playing. +//| +//| The sensor sets the image size and format, and the receiver, such as +//| `videocore.VideoBuffer`, is set up to match when playing starts. The +//| sensor's mode should not change between ``_start()`` and ``_stop()`` +//| calls. (The sensor class should raise an exception when it is +//| attempted.) To use a new mode, stop playing, change the sensor, and +//| play again. +//| +//| Camera objects implement the internal videosource protocol, so a +//| `videocore.VideoBuffer` can stream their frames into a framebuffer. +//| """ +//| +//| def __init__( +//| self, +//| sensor: circuitpython_typing.CameraSensor, +//| *, +//| output_format: Optional[PixelFormat] = None, +//| ) -> None: +//| """ +//| Configure and initialize the MIPI CSI-2 camera receiver +//| +//| .. code-block:: python +//| +//| sensor = sc2336.SC2336(i2c) +//| camera = mipicsi.Camera(sensor) +//| +//| :param sensor: A camera sensor to receive frames from. The receiver +//| is configured to match the sensor's current mode. The sensor +//| starts streaming when a `videocore.VideoBuffer` plays the +//| camera. +//| :param output_format: The format of the captured frames. Defaults +//| to the sensor's ``pixel_format``. When different, frames are +//| converted as they are captured, for example from RAW10 to +//| `PixelFormat.RGB565`. Not all conversions are supported. +//| """ +//| +// Read and validate the sensor's parameters. mp_load_attr raises +// AttributeError for missing ones. +static void mipicsi_camera_load_sensor_params( + mp_obj_t sensor, + mipicsi_sensor_params_t *params) { + params->pixel_format = validate_pixel_format(mp_load_attr(sensor, MP_QSTR_pixel_format), MP_QSTR_pixel_format); + params->width = mp_arg_validate_int_min(mp_obj_get_int(mp_load_attr(sensor, MP_QSTR_width)), 1, MP_QSTR_width); + params->height = mp_arg_validate_int_min(mp_obj_get_int(mp_load_attr(sensor, MP_QSTR_height)), 1, MP_QSTR_height); + params->lane_bit_rate_mbps = mp_arg_validate_int_min(mp_obj_get_int(mp_load_attr(sensor, MP_QSTR_lane_bit_rate_mbps)), 1, MP_QSTR_lane_bit_rate_mbps); + params->data_lanes = mp_arg_validate_int_range(mp_obj_get_int(mp_load_attr(sensor, MP_QSTR_data_lanes)), 1, 2, MP_QSTR_data_lanes); + params->bayer_order = validate_bayer_order(mp_load_attr(sensor, MP_QSTR_bayer_order), MP_QSTR_bayer_order); +} + +static mp_obj_t mipicsi_camera_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + mp_arg_check_num(n_args, n_kw, 1, 1, true); + mp_obj_t sensor = all_args[0]; + + enum { ARG_output_format, NUM_ARGS }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_output_format, MP_ARG_OBJ | MP_ARG_KW_ONLY, { .u_obj = MP_ROM_NONE } }, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + MP_STATIC_ASSERT(MP_ARRAY_SIZE(allowed_args) == NUM_ARGS); + mp_arg_parse_all_kw_array(0, n_kw, all_args + 1, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + // Validate the sensor now so mistakes show up early. play() reads the + // parameters again since the sensor may change between streams. + mipicsi_sensor_params_t params; + mipicsi_camera_load_sensor_params(sensor, ¶ms); + mipicsi_pixel_format_t output_format = params.pixel_format; + if (args[ARG_output_format].u_obj != mp_const_none) { + output_format = validate_pixel_format(args[ARG_output_format].u_obj, MP_QSTR_output_format); + } + + // Validate the sensor contract methods (_start/_stop) exist now too, + // since the camera drives them from C as the stream starts and stops. + mp_obj_t validated[2]; + mp_load_method(sensor, MP_QSTR__start, validated); + mp_load_method(sensor, MP_QSTR__stop, validated); + + mipicsi_camera_obj_t *self = mp_obj_malloc_with_finaliser(mipicsi_camera_obj_t, &mipicsi_camera_type); + common_hal_mipicsi_camera_construct(self, output_format); + // The sensor isn't started until a VideoBuffer plays the camera. + common_hal_mipicsi_camera_set_sensor(self, sensor); + return MP_OBJ_FROM_PTR(self); +} + +//| def deinit(self) -> None: +//| """Deinitialises the camera receiver and releases all memory resources for reuse.""" +//| ... +//| +static mp_obj_t mipicsi_camera_deinit(mp_obj_t self_in) { + mipicsi_camera_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_mipicsi_camera_deinit(self); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(mipicsi_camera_deinit_obj, mipicsi_camera_deinit); + +//| def __enter__(self) -> Camera: +//| """No-op used by Context Managers.""" +//| ... +//| +//| def __exit__(self) -> None: +//| """Automatically deinitializes the hardware when exiting a context. See +//| :ref:`lifetime-and-contextmanagers` for more info.""" +//| ... +//| +//| + +static const mp_rom_map_elem_t mipicsi_camera_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&mipicsi_camera_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&mipicsi_camera_deinit_obj) }, +}; + +static MP_DEFINE_CONST_DICT(mipicsi_camera_locals_dict, mipicsi_camera_locals_dict_table); + +#if CIRCUITPY_VIDEOCORE +// Implementation of the videocore videosource protocol so a VideoBuffer can +// tell the Camera where to put frames. + +static void check_for_deinit(mipicsi_camera_obj_t *self) { + if (common_hal_mipicsi_camera_deinited(self)) { + raise_deinited_error(); + } +} + +static void mipicsi_camera_play(mp_obj_t self_in, bool paused) { + mipicsi_camera_obj_t *self = MP_OBJ_TO_PTR(mp_obj_cast_to_native_base(self_in, &mipicsi_camera_type)); + check_for_deinit(self); + // Reread the sensor's mode; it may change between streams. The sensor + // starts even when paused; only the receiver waits. + mipicsi_sensor_params_t params; + mipicsi_camera_load_sensor_params(common_hal_mipicsi_camera_get_sensor(self), ¶ms); + common_hal_mipicsi_camera_videosource_play(self, ¶ms, paused); +} + +static void mipicsi_camera_stop(mp_obj_t self_in) { + mipicsi_camera_obj_t *self = MP_OBJ_TO_PTR(mp_obj_cast_to_native_base(self_in, &mipicsi_camera_type)); + common_hal_mipicsi_camera_videosource_stop(self); +} + +static void mipicsi_camera_pause(mp_obj_t self_in) { + mipicsi_camera_obj_t *self = MP_OBJ_TO_PTR(mp_obj_cast_to_native_base(self_in, &mipicsi_camera_type)); + common_hal_mipicsi_camera_videosource_pause(self); +} + +static void mipicsi_camera_resume(mp_obj_t self_in) { + mipicsi_camera_obj_t *self = MP_OBJ_TO_PTR(mp_obj_cast_to_native_base(self_in, &mipicsi_camera_type)); + common_hal_mipicsi_camera_videosource_resume(self); +} + +static bool mipicsi_camera_set_destination(mp_obj_t self_in, const videocore_destination_t *dest, + videocore_on_frame_fun on_frame, void *ctx) { + mipicsi_camera_obj_t *self = MP_OBJ_TO_PTR(mp_obj_cast_to_native_base(self_in, &mipicsi_camera_type)); + return common_hal_mipicsi_camera_set_destination(self, dest->base, dest->stride, on_frame, ctx); +} + +static mp_int_t mipicsi_camera_get_width(mp_obj_t self_in) { + return common_hal_mipicsi_camera_get_width(mp_obj_cast_to_native_base(self_in, &mipicsi_camera_type)); +} + +static mp_int_t mipicsi_camera_get_height(mp_obj_t self_in) { + return common_hal_mipicsi_camera_get_height(mp_obj_cast_to_native_base(self_in, &mipicsi_camera_type)); +} + +static mp_int_t mipicsi_camera_get_bits_per_pixel(mp_obj_t self_in) { + return common_hal_mipicsi_camera_get_bits_per_pixel(mp_obj_cast_to_native_base(self_in, &mipicsi_camera_type)); +} + +static const videosource_p_t mipicsi_camera_videosource_protocol = { + MP_PROTO_IMPLEMENT(MP_QSTR_protocol_videosource) + .play = mipicsi_camera_play, + .pause = mipicsi_camera_pause, + .resume = mipicsi_camera_resume, + .stop = mipicsi_camera_stop, + .set_destination = mipicsi_camera_set_destination, + .get_width = mipicsi_camera_get_width, + .get_height = mipicsi_camera_get_height, + .get_bits_per_pixel = mipicsi_camera_get_bits_per_pixel, +}; + +MP_DEFINE_CONST_OBJ_TYPE( + mipicsi_camera_type, + MP_QSTR_Camera, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, mipicsi_camera_make_new, + locals_dict, &mipicsi_camera_locals_dict, + protocol, &mipicsi_camera_videosource_protocol + ); +#else +MP_DEFINE_CONST_OBJ_TYPE( + mipicsi_camera_type, + MP_QSTR_Camera, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, mipicsi_camera_make_new, + locals_dict, &mipicsi_camera_locals_dict + ); +#endif diff --git a/shared-bindings/mipicsi/Camera.h b/shared-bindings/mipicsi/Camera.h new file mode 100644 index 00000000000..c43f08590ea --- /dev/null +++ b/shared-bindings/mipicsi/Camera.h @@ -0,0 +1,65 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Jeff Epler for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +#include "common-hal/mipicsi/Camera.h" +#include "shared-bindings/mipicsi/__init__.h" + +extern const mp_obj_type_t mipicsi_camera_type; + +// Record the output format (possibly the sensor's). No hardware is created +// here: that happens in play(). +void common_hal_mipicsi_camera_construct( + mipicsi_camera_obj_t *self, + mipicsi_pixel_format_t output_format); + +// Remember the sensor. Its mode is read at play time. +void common_hal_mipicsi_camera_set_sensor(mipicsi_camera_obj_t *self, mp_obj_t sensor); +// The sensor passed to set_sensor. Only valid while not deinited. +mp_obj_t common_hal_mipicsi_camera_get_sensor(mipicsi_camera_obj_t *self); + +// Videosource protocol play step: create the receiver hardware for the +// sensor's current mode (params) and start the sensor. Raises if the port +// can't convert params->pixel_format to the output format. When paused is +// true, no frames are captured until resume(). +void common_hal_mipicsi_camera_videosource_play( + mipicsi_camera_obj_t *self, + const mipicsi_sensor_params_t *params, + bool paused); + +// Videosource protocol stop step: tear down the receiver and stop the +// sensor. May raise. +void common_hal_mipicsi_camera_videosource_stop(mipicsi_camera_obj_t *self); + +// Videosource protocol pause step: stop capturing frames but keep the +// receiver, ISP and sensor running. +void common_hal_mipicsi_camera_videosource_pause(mipicsi_camera_obj_t *self); + +// Videosource protocol resume step: capture again into the latest +// destination. May raise. +void common_hal_mipicsi_camera_videosource_resume(mipicsi_camera_obj_t *self); + +void common_hal_mipicsi_camera_deinit(mipicsi_camera_obj_t *self); +bool common_hal_mipicsi_camera_deinited(mipicsi_camera_obj_t *self); + +// Stream frames contiguously into base. base must be cache-line aligned and +// stride must equal the frame's row size; the caller checks the fit. +// Returns false, rather than raising, when the destination isn't usable. +bool common_hal_mipicsi_camera_set_destination( + mipicsi_camera_obj_t *self, + uint8_t *base, + size_t stride, + videocore_on_frame_fun on_frame, + void *ctx); + +mipicsi_pixel_format_t common_hal_mipicsi_camera_get_pixel_format(mipicsi_camera_obj_t *self); +mipicsi_pixel_format_t common_hal_mipicsi_camera_get_output_format(mipicsi_camera_obj_t *self); +mp_int_t common_hal_mipicsi_camera_get_width(mipicsi_camera_obj_t *self); +mp_int_t common_hal_mipicsi_camera_get_height(mipicsi_camera_obj_t *self); +mp_int_t common_hal_mipicsi_camera_get_bits_per_pixel(mipicsi_camera_obj_t *self); diff --git a/shared-bindings/mipicsi/PixelFormat.c b/shared-bindings/mipicsi/PixelFormat.c new file mode 100644 index 00000000000..84340019745 --- /dev/null +++ b/shared-bindings/mipicsi/PixelFormat.c @@ -0,0 +1,66 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Jeff Epler for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include + +#include "py/enum.h" +#include "py/obj.h" +#include "py/runtime.h" + +#include "shared-bindings/mipicsi/__init__.h" + +//| class PixelFormat: +//| """Format of the data in the captured frames. The camera sensor must be +//| configured (typically over I2C) to transmit the corresponding MIPI CSI-2 +//| data type.""" +//| +//| RGB565: PixelFormat +//| """A 16-bit format with 5 bits of Red, 6 bits of Green, and 5 bits of Blue (MIPI data type ``RGB565``)""" +//| +//| RGB888: PixelFormat +//| """A 24-bit format with 8 bits of Red, Green and Blue (MIPI data type ``RGB888``)""" +//| +//| GRAYSCALE: PixelFormat +//| """An 8-bit format with 8 bits of luminance (MIPI data types for 8-bit grayscale)""" +//| +//| YUV422: PixelFormat +//| """A 16-bit YUV 4:2:2 format, in the byte order the sensor transmits (MIPI data type ``YUV422 8-bit``)""" +//| +//| RAW8: PixelFormat +//| """8 bits per pixel of raw Bayer data (MIPI data type ``RAW8``)""" +//| +//| RAW10: PixelFormat +//| """10 bits per pixel of raw Bayer data (MIPI data type ``RAW10``)""" +//| +//| RAW12: PixelFormat +//| """12 bits per pixel of raw Bayer data (MIPI data type ``RAW12``)""" +//| + +MAKE_ENUM_VALUE(mipicsi_pixel_format_type, pixel_format, RGB565, MIPICSI_FORMAT_RGB565); +MAKE_ENUM_VALUE(mipicsi_pixel_format_type, pixel_format, RGB888, MIPICSI_FORMAT_RGB888); +MAKE_ENUM_VALUE(mipicsi_pixel_format_type, pixel_format, GRAYSCALE, MIPICSI_FORMAT_GRAYSCALE); +MAKE_ENUM_VALUE(mipicsi_pixel_format_type, pixel_format, YUV422, MIPICSI_FORMAT_YUV422); +MAKE_ENUM_VALUE(mipicsi_pixel_format_type, pixel_format, RAW8, MIPICSI_FORMAT_RAW8); +MAKE_ENUM_VALUE(mipicsi_pixel_format_type, pixel_format, RAW10, MIPICSI_FORMAT_RAW10); +MAKE_ENUM_VALUE(mipicsi_pixel_format_type, pixel_format, RAW12, MIPICSI_FORMAT_RAW12); + +MAKE_ENUM_MAP(mipicsi_pixel_format) { + MAKE_ENUM_MAP_ENTRY(pixel_format, RGB565), + MAKE_ENUM_MAP_ENTRY(pixel_format, RGB888), + MAKE_ENUM_MAP_ENTRY(pixel_format, GRAYSCALE), + MAKE_ENUM_MAP_ENTRY(pixel_format, YUV422), + MAKE_ENUM_MAP_ENTRY(pixel_format, RAW8), + MAKE_ENUM_MAP_ENTRY(pixel_format, RAW10), + MAKE_ENUM_MAP_ENTRY(pixel_format, RAW12), +}; + +static MP_DEFINE_CONST_DICT(mipicsi_pixel_format_locals_dict, mipicsi_pixel_format_locals_table); +MAKE_PRINTER(mipicsi, mipicsi_pixel_format); +MAKE_ENUM_TYPE(mipicsi, PixelFormat, mipicsi_pixel_format); + +mipicsi_pixel_format_t validate_pixel_format(mp_obj_t obj, qstr arg_name) { + return cp_enum_value(&mipicsi_pixel_format_type, obj, arg_name); +} diff --git a/shared-bindings/mipicsi/__init__.c b/shared-bindings/mipicsi/__init__.c new file mode 100644 index 00000000000..5ea37fa72ec --- /dev/null +++ b/shared-bindings/mipicsi/__init__.c @@ -0,0 +1,48 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Jeff Epler for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include + +#include "py/enum.h" +#include "py/obj.h" +#include "py/runtime.h" + +#include "shared-bindings/mipicsi/__init__.h" +#include "shared-bindings/mipicsi/Camera.h" + +//| """Support for MIPI CSI-2 camera interfaces +//| +//| Captures image frames from camera sensors attached to a MIPI CSI-2 +//| receiver, such as the one in the ESP32-P4. The camera sensor itself is +//| configured separately (typically over I2C); this module only receives +//| the image data the sensor transmits. +//| +//| By default, captured frames are in the same format the sensor sends, +//| described by `PixelFormat`. For example, an RGB565 sensor gives RGB565 +//| frames. RAW formats contain Bayer data, with the color order given by +//| `BayerOrder`. +//| +//| `mipicsi.Camera` may be able to convert the format as it receives a +//| frame. To do this, pass the desired ``output_format`` when creating the +//| Camera. An exception will be raised if it cannot be done in hardware +//| without another buffer. +//| """ + +static const mp_rom_map_elem_t mipicsi_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_mipicsi) }, + { MP_ROM_QSTR(MP_QSTR_PixelFormat), MP_ROM_PTR(&mipicsi_pixel_format_type) }, + { MP_ROM_QSTR(MP_QSTR_BayerOrder), MP_ROM_PTR(&mipicsi_bayer_order_type) }, + { MP_ROM_QSTR(MP_QSTR_Camera), MP_ROM_PTR(&mipicsi_camera_type) }, +}; + +static MP_DEFINE_CONST_DICT(mipicsi_module_globals, mipicsi_module_globals_table); + +const mp_obj_module_t mipicsi_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&mipicsi_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_mipicsi, mipicsi_module); diff --git a/shared-bindings/mipicsi/__init__.h b/shared-bindings/mipicsi/__init__.h new file mode 100644 index 00000000000..5892379ce88 --- /dev/null +++ b/shared-bindings/mipicsi/__init__.h @@ -0,0 +1,33 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Jeff Epler for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/enum.h" + +extern const mp_obj_type_t mipicsi_pixel_format_type; +extern const mp_obj_type_t mipicsi_bayer_order_type; +extern const cp_enum_obj_t pixel_format_RGB565_obj; + +typedef enum { + MIPICSI_FORMAT_RAW8, + MIPICSI_FORMAT_RAW10, + MIPICSI_FORMAT_RAW12, + MIPICSI_FORMAT_RGB565, + MIPICSI_FORMAT_RGB888, + MIPICSI_FORMAT_YUV422, + MIPICSI_FORMAT_GRAYSCALE, +} mipicsi_pixel_format_t; + +typedef enum { + MIPICSI_BAYER_ORDER_BGGR, + MIPICSI_BAYER_ORDER_GBRG, + MIPICSI_BAYER_ORDER_GRBG, + MIPICSI_BAYER_ORDER_RGGB, +} mipicsi_bayer_order_t; + +mipicsi_pixel_format_t validate_pixel_format(mp_obj_t obj, qstr arg_name); +mipicsi_bayer_order_t validate_bayer_order(mp_obj_t obj, qstr arg_name); diff --git a/shared-bindings/mipidsi/Bus.c b/shared-bindings/mipidsi/Bus.c new file mode 100644 index 00000000000..2f704f47708 --- /dev/null +++ b/shared-bindings/mipidsi/Bus.c @@ -0,0 +1,125 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "py/obj.h" +#include "py/objproperty.h" +#include "py/runtime.h" + +#include "shared-bindings/mipidsi/Bus.h" +#include "shared-bindings/util.h" +#include "shared/runtime/context_manager_helpers.h" + +//| class Bus: +//| def __init__( +//| self, +//| *, +//| minimum_frequency: int = 500_000_000, +//| num_lanes: int = 2, +//| ) -> None: +//| """Create a MIPI DSI Bus object. +//| +//| This creates a DSI bus interface. The specific pins used are determined by the board. +//| DSI supports 1-4 data lanes. +//| +//| The lane bit rate is a bandwidth floor, not an exact clock. The bus runs at a +//| rate the PHY can generate that is at least ``minimum_frequency``, choosing one +//| close to it. Rates within 1 kHz of the minimum count, since the PHY and the +//| reported pixel clock are quantized. The actual rate can be read back from +//| `frequency`. +//| +//| :param int minimum_frequency: the minimum lane bit rate in Hz (default 500 MHz) +//| :param int num_lanes: the number of data lanes to use (default 2, range 1-4) +//| :raises ValueError: if the PHY cannot reach ``minimum_frequency`` +//| """ +//| +// +// +// All MCUs we support only have one DSI bus but it can be shared between multiple displays. One +// display may live longer than the VM, so we need to allocate the bus outside the VM. To simplify +// memory tracking, we use a global object for the bus. +// +static mipidsi_bus_obj_t _mipidsi_bus_obj; + +static mp_obj_t mipidsi_bus_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_minimum_frequency, ARG_num_lanes }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_minimum_frequency, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 500000000} }, + { MP_QSTR_num_lanes, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 2} }, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + _mipidsi_bus_obj.base.type = &mipidsi_bus_type; + mipidsi_bus_obj_t *self = &_mipidsi_bus_obj; + + mp_uint_t minimum_frequency = (mp_uint_t)mp_arg_validate_int_min(args[ARG_minimum_frequency].u_int, 1, MP_QSTR_minimum_frequency); + uint8_t num_lanes = (uint8_t)mp_arg_validate_int_range(args[ARG_num_lanes].u_int, 1, 4, MP_QSTR_num_lanes); + + common_hal_mipidsi_bus_construct(self, minimum_frequency, num_lanes); + + return MP_OBJ_FROM_PTR(self); +} + +//| def deinit(self) -> None: +//| """Free the resources (pins, timers, etc.) associated with this +//| `mipidsi.Bus` instance. After deinitialization, no further operations +//| may be performed.""" +//| ... +//| +static mp_obj_t mipidsi_bus_deinit(mp_obj_t self_in) { + mipidsi_bus_obj_t *self = (mipidsi_bus_obj_t *)self_in; + common_hal_mipidsi_bus_deinit(self); + return mp_const_none; +} + +static MP_DEFINE_CONST_FUN_OBJ_1(mipidsi_bus_deinit_obj, mipidsi_bus_deinit); + +static void check_for_deinit(mipidsi_bus_obj_t *self) { + if (common_hal_mipidsi_bus_deinited(self)) { + raise_deinited_error(); + } +} + +//| frequency: int +//| """The lane bit rate the bus actually runs at, in Hz. This is at least the +//| ``minimum_frequency`` passed to the constructor, up to the 1 kHz rounding +//| tolerance, but can be higher because the PHY PLL only produces certain rates.""" +static mp_obj_t mipidsi_bus_get_frequency(mp_obj_t self_in) { + mipidsi_bus_obj_t *self = (mipidsi_bus_obj_t *)self_in; + check_for_deinit(self); + return mp_obj_new_int_from_uint(common_hal_mipidsi_bus_get_frequency(self)); +} +static MP_DEFINE_CONST_FUN_OBJ_1(mipidsi_bus_get_frequency_obj, mipidsi_bus_get_frequency); +MP_PROPERTY_GETTER(mipidsi_bus_frequency_obj, + (mp_obj_t)&mipidsi_bus_get_frequency_obj); + +//| num_lanes: int +//| """The number of data lanes the bus uses.""" +//| +static mp_obj_t mipidsi_bus_get_num_lanes(mp_obj_t self_in) { + mipidsi_bus_obj_t *self = (mipidsi_bus_obj_t *)self_in; + check_for_deinit(self); + return MP_OBJ_NEW_SMALL_INT(common_hal_mipidsi_bus_get_num_lanes(self)); +} +static MP_DEFINE_CONST_FUN_OBJ_1(mipidsi_bus_get_num_lanes_obj, mipidsi_bus_get_num_lanes); +MP_PROPERTY_GETTER(mipidsi_bus_num_lanes_obj, + (mp_obj_t)&mipidsi_bus_get_num_lanes_obj); + +static const mp_rom_map_elem_t mipidsi_bus_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&mipidsi_bus_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&mipidsi_bus_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR_frequency), MP_ROM_PTR(&mipidsi_bus_frequency_obj) }, + { MP_ROM_QSTR(MP_QSTR_num_lanes), MP_ROM_PTR(&mipidsi_bus_num_lanes_obj) }, +}; +static MP_DEFINE_CONST_DICT(mipidsi_bus_locals_dict, mipidsi_bus_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + mipidsi_bus_type, + MP_QSTR_Bus, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, mipidsi_bus_make_new, + locals_dict, &mipidsi_bus_locals_dict + ); diff --git a/shared-bindings/mipidsi/Bus.h b/shared-bindings/mipidsi/Bus.h new file mode 100644 index 00000000000..66d73e9355c --- /dev/null +++ b/shared-bindings/mipidsi/Bus.h @@ -0,0 +1,17 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "common-hal/mipidsi/Bus.h" + +extern const mp_obj_type_t mipidsi_bus_type; + +void common_hal_mipidsi_bus_construct(mipidsi_bus_obj_t *self, mp_uint_t minimum_frequency, uint8_t num_lanes); +void common_hal_mipidsi_bus_deinit(mipidsi_bus_obj_t *self); +bool common_hal_mipidsi_bus_deinited(mipidsi_bus_obj_t *self); +mp_uint_t common_hal_mipidsi_bus_get_frequency(mipidsi_bus_obj_t *self); +uint8_t common_hal_mipidsi_bus_get_num_lanes(mipidsi_bus_obj_t *self); diff --git a/shared-bindings/mipidsi/Display.c b/shared-bindings/mipidsi/Display.c new file mode 100644 index 00000000000..dd102397412 --- /dev/null +++ b/shared-bindings/mipidsi/Display.c @@ -0,0 +1,330 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "py/obj.h" +#include "py/objproperty.h" +#include "py/runtime.h" +#include "py/objtype.h" + +#include "shared-bindings/mipidsi/Display.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/util.h" +#include "shared-module/displayio/__init__.h" +#include "shared-module/framebufferio/FramebufferDisplay.h" + +//| class Display: +//| def __init__( +//| self, +//| bus: Bus, +//| init_sequence: ReadableBuffer, +//| *, +//| width: int, +//| height: int, +//| hsync_pulse_width: int, +//| hsync_back_porch: int, +//| hsync_front_porch: int, +//| vsync_pulse_width: int, +//| vsync_back_porch: int, +//| vsync_front_porch: int, +//| pixel_clock_frequency: int, +//| virtual_channel: int = 0, +//| rotation: int = 0, +//| color_depth: int = 16, +//| backlight_pin: Optional[microcontroller.Pin] = None, +//| brightness: float = 1.0, +//| native_frames_per_second: int = 60, +//| backlight_on_high: bool = True, +//| low_power_blanking: bool = True, +//| ) -> None: +//| """Create a MIPI DSI Display object connected to the given bus. +//| +//| This allocates a framebuffer and configures the DSI display to use the +//| specified virtual channel for communication. +//| +//| The framebuffer pixel format varies depending on color_depth: +//| +//| * 16 - Each two bytes is a pixel in RGB565 format. +//| * 24 - Each three bytes is a pixel in RGB888 format. +//| +//| A Display is often used in conjunction with a +//| `framebufferio.FramebufferDisplay`. +//| +//| Drivers for DSI bridges can subclass Display. Set up the bridge before +//| calling ``super().__init__()``, which starts DSI video. +//| +//| :param Bus bus: the DSI bus to use +//| :param ~circuitpython_typing.ReadableBuffer init_sequence: Byte-packed initialization sequence for the display +//| :param int width: the width of the framebuffer in pixels +//| :param int height: the height of the framebuffer in pixels +//| :param int hsync_pulse_width: horizontal sync pulse width in pixel clocks +//| :param int hsync_back_porch: horizontal back porch in pixel clocks +//| :param int hsync_front_porch: horizontal front porch in pixel clocks +//| :param int vsync_pulse_width: vertical sync pulse width in lines +//| :param int vsync_back_porch: vertical back porch in lines +//| :param int vsync_front_porch: vertical front porch in lines +//| :param int pixel_clock_frequency: pixel clock frequency in Hz. The clock actually +//| generated can differ; read it back from `pixel_clock_frequency`. +//| :param int virtual_channel: the DSI virtual channel (0-3) +//| :param int rotation: the rotation of the display in degrees clockwise (0, 90, 180, 270) +//| :param int color_depth: the color depth of the framebuffer in bits (16 or 24) +//| :param microcontroller.Pin backlight_pin: Pin connected to the display's backlight +//| :param float brightness: Initial display brightness (0.0 to 1.0) +//| :param int native_frames_per_second: Number of display refreshes per second +//| :param bool backlight_on_high: If True, pulling the backlight pin high turns the backlight on +//| :param bool low_power_blanking: If True, the DSI lanes may drop to low power mode +//| during blanking. Set False to keep them in high speed mode, which bridges +//| that regenerate the pixel clock from the DSI clock (such as the LT8912B) need. +//| """ +//| + +static mp_obj_t mipidsi_display_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_bus, ARG_init_sequence, ARG_width, ARG_height, ARG_hsync_pulse_width, ARG_hsync_back_porch, + ARG_hsync_front_porch, ARG_vsync_pulse_width, ARG_vsync_back_porch, ARG_vsync_front_porch, + ARG_pixel_clock_frequency, ARG_virtual_channel, ARG_rotation, + ARG_color_depth, ARG_backlight_pin, ARG_brightness, ARG_native_frames_per_second, + ARG_backlight_on_high, ARG_low_power_blanking }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_bus, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_init_sequence, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_width, MP_ARG_KW_ONLY | MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_height, MP_ARG_KW_ONLY | MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_hsync_pulse_width, MP_ARG_KW_ONLY | MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_hsync_back_porch, MP_ARG_KW_ONLY | MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_hsync_front_porch, MP_ARG_KW_ONLY | MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_vsync_pulse_width, MP_ARG_KW_ONLY | MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_vsync_back_porch, MP_ARG_KW_ONLY | MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_vsync_front_porch, MP_ARG_KW_ONLY | MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_pixel_clock_frequency, MP_ARG_KW_ONLY | MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_virtual_channel, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_rotation, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_color_depth, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 16} }, + { MP_QSTR_backlight_pin, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = mp_const_none} }, + { MP_QSTR_brightness, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_OBJ_NEW_SMALL_INT(1)} }, + { MP_QSTR_native_frames_per_second, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 60} }, + { MP_QSTR_backlight_on_high, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = true} }, + { MP_QSTR_low_power_blanking, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = true} }, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + mipidsi_bus_obj_t *bus = mp_arg_validate_type(args[ARG_bus].u_obj, &mipidsi_bus_type, MP_QSTR_bus); + + 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, MP_QSTR_backlight_pin); + + mp_float_t brightness = mp_obj_get_float(args[ARG_brightness].u_obj); + + mp_int_t rotation = args[ARG_rotation].u_int; + if (rotation % 90 != 0) { + mp_raise_ValueError(MP_ERROR_TEXT("Display rotation must be in 90 degree increments")); + } + + mp_uint_t virtual_channel = (mp_uint_t)mp_arg_validate_int_range(args[ARG_virtual_channel].u_int, 0, 3, MP_QSTR_virtual_channel); + mp_uint_t width = (mp_uint_t)mp_arg_validate_int_min(args[ARG_width].u_int, 0, MP_QSTR_width); + mp_uint_t height = (mp_uint_t)mp_arg_validate_int_min(args[ARG_height].u_int, 0, MP_QSTR_height); + mp_uint_t color_depth = args[ARG_color_depth].u_int; + + if (color_depth != 16 && color_depth != 24) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("Invalid %q"), MP_QSTR_color_depth); + } + + // Validate everything before taking a display bus slot. + mipidsi_display_obj_t *self = &allocate_display_bus_or_raise()->mipidsi; + self->base.type = &mipidsi_display_type; + + common_hal_mipidsi_display_construct(self, bus, bufinfo.buf, bufinfo.len, virtual_channel, width, height, + rotation, color_depth, MP_OBJ_TO_PTR(backlight_pin), brightness, + args[ARG_native_frames_per_second].u_int, + args[ARG_backlight_on_high].u_bool, + args[ARG_hsync_pulse_width].u_int, + args[ARG_hsync_back_porch].u_int, + args[ARG_hsync_front_porch].u_int, + args[ARG_vsync_pulse_width].u_int, + args[ARG_vsync_back_porch].u_int, + args[ARG_vsync_front_porch].u_int, + args[ARG_pixel_clock_frequency].u_int, + args[ARG_low_power_blanking].u_bool); + + return MP_OBJ_FROM_PTR(self); +} + +// Helper to ensure we have the native super class instead of a subclass. +static mipidsi_display_obj_t *native_display(mp_obj_t display_obj) { + mp_obj_t native_display = mp_obj_cast_to_native_base(display_obj, &mipidsi_display_type); + mp_obj_assert_native_inited(native_display); + return MP_OBJ_TO_PTR(native_display); +} + +//| def deinit(self) -> None: +//| """Free the resources (pins, timers, etc.) associated with this +//| `mipidsi.Display` instance. After deinitialization, no further operations +//| may be performed.""" +//| ... +//| +static mp_obj_t mipidsi_display_deinit(mp_obj_t self_in) { + mipidsi_display_obj_t *self = native_display(self_in); + common_hal_mipidsi_display_deinit(self); + return mp_const_none; +} + +static MP_DEFINE_CONST_FUN_OBJ_1(mipidsi_display_deinit_obj, mipidsi_display_deinit); + +static void check_for_deinit(mipidsi_display_obj_t *self) { + if (common_hal_mipidsi_display_deinited(self)) { + raise_deinited_error(); + } +} + +//| width: int +//| """The width of the framebuffer, in pixels.""" +static mp_obj_t mipidsi_display_get_width(mp_obj_t self_in) { + mipidsi_display_obj_t *self = native_display(self_in); + check_for_deinit(self); + return MP_OBJ_NEW_SMALL_INT(common_hal_mipidsi_display_get_width(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(mipidsi_display_get_width_obj, mipidsi_display_get_width); +MP_PROPERTY_GETTER(mipidsi_display_width_obj, + (mp_obj_t)&mipidsi_display_get_width_obj); + +//| height: int +//| """The height of the framebuffer, in pixels.""" +//| +//| +static mp_obj_t mipidsi_display_get_height(mp_obj_t self_in) { + mipidsi_display_obj_t *self = native_display(self_in); + check_for_deinit(self); + return MP_OBJ_NEW_SMALL_INT(common_hal_mipidsi_display_get_height(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(mipidsi_display_get_height_obj, mipidsi_display_get_height); + +MP_PROPERTY_GETTER(mipidsi_display_height_obj, + (mp_obj_t)&mipidsi_display_get_height_obj); + +//| color_depth: int +//| """The color depth of the framebuffer.""" +static mp_obj_t mipidsi_display_get_color_depth(mp_obj_t self_in) { + mipidsi_display_obj_t *self = native_display(self_in); + check_for_deinit(self); + return MP_OBJ_NEW_SMALL_INT(common_hal_mipidsi_display_get_color_depth(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(mipidsi_display_get_color_depth_obj, mipidsi_display_get_color_depth); +MP_PROPERTY_GETTER(mipidsi_display_color_depth_obj, + (mp_obj_t)&mipidsi_display_get_color_depth_obj); + +//| pixel_clock_frequency: int +//| """The pixel clock frequency the DSI host actually generates, in Hz. This +//| can differ from the requested frequency when the clock source cannot divide +//| down to it exactly.""" +static mp_obj_t mipidsi_display_get_pixel_clock_frequency(mp_obj_t self_in) { + mipidsi_display_obj_t *self = native_display(self_in); + check_for_deinit(self); + return mp_obj_new_int_from_uint(common_hal_mipidsi_display_get_pixel_clock_frequency(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(mipidsi_display_get_pixel_clock_frequency_obj, mipidsi_display_get_pixel_clock_frequency); +MP_PROPERTY_GETTER(mipidsi_display_pixel_clock_frequency_obj, + (mp_obj_t)&mipidsi_display_get_pixel_clock_frequency_obj); + + +static const mp_rom_map_elem_t mipidsi_display_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&mipidsi_display_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&mipidsi_display_deinit_obj) }, + + { MP_ROM_QSTR(MP_QSTR_width), MP_ROM_PTR(&mipidsi_display_width_obj) }, + { MP_ROM_QSTR(MP_QSTR_height), MP_ROM_PTR(&mipidsi_display_height_obj) }, + { MP_ROM_QSTR(MP_QSTR_color_depth), MP_ROM_PTR(&mipidsi_display_color_depth_obj) }, + { MP_ROM_QSTR(MP_QSTR_pixel_clock_frequency), MP_ROM_PTR(&mipidsi_display_pixel_clock_frequency_obj) }, +}; +static MP_DEFINE_CONST_DICT(mipidsi_display_locals_dict, mipidsi_display_locals_dict_table); + +static void mipidsi_display_get_bufinfo(mp_obj_t self_in, mp_buffer_info_t *bufinfo) { + common_hal_mipidsi_display_get_buffer(self_in, bufinfo, 0); +} + +static float mipidsi_display_get_brightness_proto(mp_obj_t self_in) { + return common_hal_mipidsi_display_get_brightness(self_in); +} + +static bool mipidsi_display_set_brightness_proto(mp_obj_t self_in, mp_float_t value) { + common_hal_mipidsi_display_set_brightness(self_in, value); + return true; +} + +// These versions exist so that the prototype matches the protocol, +// avoiding a type cast that can hide errors +static void mipidsi_display_swapbuffers(mp_obj_t self_in, uint8_t *dirty_row_bitmap) { + common_hal_mipidsi_display_refresh_rows(self_in, dirty_row_bitmap); +} + +static void mipidsi_display_deinit_proto(mp_obj_t self_in) { + common_hal_mipidsi_display_deinit(self_in); +} + +static void mipidsi_display_set_frame_callback(mp_obj_t self_in, framebuffer_frame_callback_t cb, void *data) { + common_hal_mipidsi_display_set_frame_callback(self_in, cb, data); +} + +static int mipidsi_display_get_width_proto(mp_obj_t self_in) { + return common_hal_mipidsi_display_get_width(self_in); +} + +static int mipidsi_display_get_height_proto(mp_obj_t self_in) { + return common_hal_mipidsi_display_get_height(self_in); +} + +static int mipidsi_display_get_color_depth_proto(mp_obj_t self_in) { + return common_hal_mipidsi_display_get_color_depth(self_in); +} + +static bool mipidsi_display_get_grayscale_proto(mp_obj_t self_in) { + return common_hal_mipidsi_display_get_grayscale(self_in); +} + +static int mipidsi_display_get_bytes_per_cell_proto(mp_obj_t self_in) { + return 1; +} + +static int mipidsi_display_get_native_frames_per_second_proto(mp_obj_t self_in) { + return common_hal_mipidsi_display_get_native_frames_per_second(self_in); +} + +static bool mipidsi_display_get_pixels_in_byte_share_row_proto(mp_obj_t self_in) { + return true; +} + +static int mipidsi_display_get_row_stride_proto(mp_obj_t self_in) { + return common_hal_mipidsi_display_get_row_stride(self_in); +} + +static const framebuffer_p_t mipidsi_display_proto = { + MP_PROTO_IMPLEMENT(MP_QSTR_protocol_framebuffer) + .get_bufinfo = mipidsi_display_get_bufinfo, + .set_brightness = mipidsi_display_set_brightness_proto, + .get_brightness = mipidsi_display_get_brightness_proto, + .get_width = mipidsi_display_get_width_proto, + .get_height = mipidsi_display_get_height_proto, + .get_color_depth = mipidsi_display_get_color_depth_proto, + .get_grayscale = mipidsi_display_get_grayscale_proto, + .get_row_stride = mipidsi_display_get_row_stride_proto, + .get_bytes_per_cell = mipidsi_display_get_bytes_per_cell_proto, + .get_native_frames_per_second = mipidsi_display_get_native_frames_per_second_proto, + .get_pixels_in_byte_share_row = mipidsi_display_get_pixels_in_byte_share_row_proto, + .swapbuffers = mipidsi_display_swapbuffers, + .deinit = mipidsi_display_deinit_proto, + .set_frame_callback = mipidsi_display_set_frame_callback, +}; + +MP_DEFINE_CONST_OBJ_TYPE( + mipidsi_display_type, + MP_QSTR_Display, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + locals_dict, &mipidsi_display_locals_dict, + make_new, mipidsi_display_make_new, + buffer, common_hal_mipidsi_display_get_buffer, + protocol, &mipidsi_display_proto + ); diff --git a/shared-bindings/mipidsi/Display.h b/shared-bindings/mipidsi/Display.h new file mode 100644 index 00000000000..981bde4da12 --- /dev/null +++ b/shared-bindings/mipidsi/Display.h @@ -0,0 +1,54 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "common-hal/mipidsi/Display.h" +#include "shared-bindings/mipidsi/Bus.h" +#include "common-hal/microcontroller/Pin.h" + +extern const mp_obj_type_t mipidsi_display_type; + +void common_hal_mipidsi_display_construct(mipidsi_display_obj_t *self, + mipidsi_bus_obj_t *bus, + const uint8_t *init_sequence, + size_t init_sequence_len, + mp_uint_t virtual_channel, + mp_uint_t width, + mp_uint_t height, + mp_int_t rotation, + mp_uint_t color_depth, + const mcu_pin_obj_t *backlight_pin, + mp_float_t brightness, + mp_uint_t native_frames_per_second, + bool backlight_on_high, + mp_uint_t hsync_pulse_width, + mp_uint_t hsync_back_porch, + mp_uint_t hsync_front_porch, + mp_uint_t vsync_pulse_width, + mp_uint_t vsync_back_porch, + mp_uint_t vsync_front_porch, + mp_uint_t pixel_clock_frequency, + bool low_power_blanking); +void common_hal_mipidsi_display_deinit(mipidsi_display_obj_t *self); +bool common_hal_mipidsi_display_deinited(mipidsi_display_obj_t *self); +void common_hal_mipidsi_display_refresh(mipidsi_display_obj_t *self); +void common_hal_mipidsi_display_set_frame_callback(mipidsi_display_obj_t *self, framebuffer_frame_callback_t cb, void *data); +// Make the rows marked in dirty_row_bitmap (one bit per row, LSB first) visible to the +// display. NULL refreshes every row. This backs the framebuffer protocol's swapbuffers +// callback (mipidsi_display_swapbuffers in Display.c), which FramebufferDisplay calls +// during refresh with the rows it just redrew. +void common_hal_mipidsi_display_refresh_rows(mipidsi_display_obj_t *self, const uint8_t *dirty_row_bitmap); +mp_float_t common_hal_mipidsi_display_get_brightness(mipidsi_display_obj_t *self); +bool common_hal_mipidsi_display_set_brightness(mipidsi_display_obj_t *self, mp_float_t brightness); +int common_hal_mipidsi_display_get_width(mipidsi_display_obj_t *self); +int common_hal_mipidsi_display_get_height(mipidsi_display_obj_t *self); +int common_hal_mipidsi_display_get_row_stride(mipidsi_display_obj_t *self); +int common_hal_mipidsi_display_get_color_depth(mipidsi_display_obj_t *self); +mp_uint_t common_hal_mipidsi_display_get_pixel_clock_frequency(mipidsi_display_obj_t *self); +int common_hal_mipidsi_display_get_native_frames_per_second(mipidsi_display_obj_t *self); +bool common_hal_mipidsi_display_get_grayscale(mipidsi_display_obj_t *self); +mp_int_t common_hal_mipidsi_display_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags); diff --git a/shared-bindings/mipidsi/__init__.c b/shared-bindings/mipidsi/__init__.c new file mode 100644 index 00000000000..0b6b8565929 --- /dev/null +++ b/shared-bindings/mipidsi/__init__.c @@ -0,0 +1,30 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include + +#include "py/obj.h" +#include "py/runtime.h" + +#include "shared-bindings/mipidsi/Bus.h" +#include "shared-bindings/mipidsi/Display.h" + +//| """Low-level routines for interacting with MIPI DSI""" + +static const mp_rom_map_elem_t mipidsi_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_mipidsi) }, + { MP_ROM_QSTR(MP_QSTR_Bus), MP_ROM_PTR(&mipidsi_bus_type) }, + { MP_ROM_QSTR(MP_QSTR_Display), MP_ROM_PTR(&mipidsi_display_type) }, +}; + +static MP_DEFINE_CONST_DICT(mipidsi_module_globals, mipidsi_module_globals_table); + +const mp_obj_module_t mipidsi_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&mipidsi_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_mipidsi, mipidsi_module); diff --git a/shared-bindings/mipidsi/__init__.h b/shared-bindings/mipidsi/__init__.h new file mode 100644 index 00000000000..972a7c082fd --- /dev/null +++ b/shared-bindings/mipidsi/__init__.h @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once diff --git a/shared-bindings/msgpack/ExtType.c b/shared-bindings/msgpack/ExtType.c index f66abda8fa2..c69416f9773 100644 --- a/shared-bindings/msgpack/ExtType.c +++ b/shared-bindings/msgpack/ExtType.c @@ -18,7 +18,6 @@ //| :param bytes data: representation.""" //| static mp_obj_t mod_msgpack_exttype_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { - mod_msgpack_extype_obj_t *self = mp_obj_malloc(mod_msgpack_extype_obj_t, &mod_msgpack_exttype_type); enum { ARG_code, ARG_data }; static const mp_arg_t allowed_args[] = { { MP_QSTR_code, MP_ARG_INT | MP_ARG_REQUIRED }, @@ -28,11 +27,12 @@ static mp_obj_t mod_msgpack_exttype_make_new(const mp_obj_type_t *type, size_t n mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); int code = mp_arg_validate_int_range(args[ARG_code].u_int, 0, 127, MP_QSTR_code); + mp_obj_t data = args[ARG_data].u_obj; + mod_msgpack_extype_obj_t *self = mp_obj_malloc(mod_msgpack_extype_obj_t, &mod_msgpack_exttype_type); self->code = code; - - mp_obj_t data = args[ARG_data].u_obj; self->data = data; + return MP_OBJ_FROM_PTR(self); } diff --git a/shared-bindings/msgpack/__init__.c b/shared-bindings/msgpack/__init__.c index a3e31f23ca6..54ecd51234b 100644 --- a/shared-bindings/msgpack/__init__.c +++ b/shared-bindings/msgpack/__init__.c @@ -19,7 +19,10 @@ //| See https://msgpack.org for details. The module implements a subset of the cpython //| module msgpack-python. //| -//| Not implemented: 64-bit int, uint, float. +//| Ints are packed in the smallest format that holds them, using the unsigned formats for +//| values >= 0. An int that does not fit in 64 bits is passed to ``default``. +//| +//| Floats are always packed in the 32-bit format. //| //| For more information about working with msgpack, //| see `the CPython Library Documentation `_. diff --git a/shared-bindings/nvm/ByteArray.c b/shared-bindings/nvm/ByteArray.c index be01c1f7064..b2783006267 100644 --- a/shared-bindings/nvm/ByteArray.c +++ b/shared-bindings/nvm/ByteArray.c @@ -35,7 +35,7 @@ //| 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); + uint32_t len = common_hal_nvm_bytearray_get_length(self); switch (op) { case MP_UNARY_OP_BOOL: return mp_obj_new_bool(len != 0); diff --git a/shared-bindings/onewireio/OneWire.c b/shared-bindings/onewireio/OneWire.c index a3750ae5e07..fd0135ef6e9 100644 --- a/shared-bindings/onewireio/OneWire.c +++ b/shared-bindings/onewireio/OneWire.c @@ -42,9 +42,9 @@ static mp_obj_t onewireio_onewire_make_new(const mp_obj_type_t *type, size_t n_a mp_arg_parse_all_kw_array(n_args, n_kw, all_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, MP_QSTR_pin); - onewireio_onewire_obj_t *self = mp_obj_malloc(onewireio_onewire_obj_t, &onewireio_onewire_type); - + onewireio_onewire_obj_t *self = mp_obj_malloc_with_finaliser(onewireio_onewire_obj_t, &onewireio_onewire_type); common_hal_onewireio_onewire_construct(self, pin); + return MP_OBJ_FROM_PTR(self); } @@ -125,6 +125,7 @@ MP_DEFINE_CONST_FUN_OBJ_2(onewireio_onewire_write_bit_obj, onewireio_onewire_obj static const mp_rom_map_elem_t onewireio_onewire_locals_dict_table[] = { // Methods { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&onewireio_onewire_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&onewireio_onewire_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, { MP_ROM_QSTR(MP_QSTR_reset), MP_ROM_PTR(&onewireio_onewire_reset_obj) }, diff --git a/shared-bindings/os/__init__.c b/shared-bindings/os/__init__.c index 5e28c02452d..0673ee9f698 100644 --- a/shared-bindings/os/__init__.c +++ b/shared-bindings/os/__init__.c @@ -38,22 +38,51 @@ //| """The type of values that :py:func:`.uname()` returns""" //| //| sysname: str +//| """Always ``"CircuitPython"``.""" //| nodename: str +//| """The network hostname, read each time :py:func:`.uname()` is called. +//| Before Wi-Fi or Ethernet is set up, this is the hostname that the interface will use. +//| For Wi-Fi, that is ``CIRCUITPY_WIFI_HOSTNAME`` from ``settings.toml`` if it is set. +//| Otherwise it is the interface's default hostname. +//| On boards where Wi-Fi runs on a separate co-processor, +//| the hostname before Wi-Fi is set up may not exactly match the one it will use. +//| On boards without Wi-Fi or Ethernet, this is the microcontroller name, such as ``"nRF52840"``.""" //| release: str +//| """The CircuitPython version.""" //| version: str +//| """The CircuitPython build version and build date.""" //| machine: str +//| """The board name and microcontroller name.""" //| //| static const qstr os_uname_info_fields[] = { MP_QSTR_sysname, MP_QSTR_nodename, MP_QSTR_release, MP_QSTR_version, MP_QSTR_machine }; -static const MP_DEFINE_STR_OBJ(os_uname_info_sysname_obj, MICROPY_HW_MCU_NAME); -static const MP_DEFINE_STR_OBJ(os_uname_info_nodename_obj, MICROPY_HW_MCU_NAME); +static const MP_DEFINE_STR_OBJ(os_uname_info_sysname_obj, "CircuitPython"); static const MP_DEFINE_STR_OBJ(os_uname_info_release_obj, MICROPY_VERSION_STRING); static const MP_DEFINE_STR_OBJ(os_uname_info_version_obj, MICROPY_GIT_TAG " on " MICROPY_BUILD_DATE); static const MP_DEFINE_STR_OBJ(os_uname_info_machine_obj, MICROPY_HW_BOARD_NAME " with " MICROPY_HW_MCU_NAME); +#if CIRCUITPY_WIFI || CIRCUITPY_MII +// The hostname can change, so build a new tuple each time. +static mp_obj_t os_uname(void) { + // A hostname has at most 63 characters. + char nodename[64]; + common_hal_os_get_nodename(nodename, sizeof(nodename)); + const mp_obj_t items[] = { + MP_OBJ_FROM_PTR(&os_uname_info_sysname_obj), + mp_obj_new_str(nodename, strlen(nodename)), + MP_OBJ_FROM_PTR(&os_uname_info_release_obj), + MP_OBJ_FROM_PTR(&os_uname_info_version_obj), + MP_OBJ_FROM_PTR(&os_uname_info_machine_obj), + }; + return mp_obj_new_attrtuple(os_uname_info_fields, MP_ARRAY_SIZE(items), items); +} +#else +// Without networking, nodename is always the microcontroller name, so the +// tuple never changes. +static const MP_DEFINE_STR_OBJ(os_uname_info_nodename_obj, MICROPY_HW_MCU_NAME); static MP_DEFINE_ATTRTUPLE( os_uname_info_obj, @@ -67,8 +96,9 @@ static MP_DEFINE_ATTRTUPLE( ); static mp_obj_t os_uname(void) { - return (mp_obj_t)&os_uname_info_obj; + return MP_OBJ_FROM_PTR(&os_uname_info_obj); } +#endif static MP_DEFINE_CONST_FUN_OBJ_0(os_uname_obj, os_uname); //| def chdir(path: str) -> None: @@ -94,11 +124,20 @@ static mp_obj_t os_getcwd(void) { MP_DEFINE_CONST_FUN_OBJ_0(os_getcwd_obj, os_getcwd); //| def getenv(key: str, default: Optional[str] = None) -> Optional[str]: -//| """Get the environment variable value for the given key or return ``default``. +//| """Get the environment variable value for the given ``key`` from the +//| ``/settings.toml`` file. +//| If ``key`` is not present or the value is ill-formed, return the ``default`` value. +//| The value is returned as a string even if it can be parsed as an integer or boolean. +//| No errors are raised if the value is not a valid TOML value; instead the original +//| string is returned, or ``default`` if no value can be retrieved at all. +//| +//| If you want to retrieve the value as a ``str``, ``bool``, or ``int``, use `supervisor.get_setting()`. //| -//| This may load values from disk so cache the result instead of calling this often. +//| The ``settings.toml`` file is re-scanned on every call, +//| so cache the result instead of calling `getenv()` frequently. //| -//| On boards that do not support ``settings.toml`` reading in the core, this function will raise NotImplementedError. +//| On boards that do not support ``settings.toml`` reading in the core, +//| this function will raise NotImplementedError. //| //| .. raw:: html //| @@ -118,7 +157,7 @@ MP_DEFINE_CONST_FUN_OBJ_0(os_getcwd_obj, os_getcwd); //| //| static mp_obj_t os_getenv(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - #if CIRCUITPY_OS_GETENV + #if CIRCUITPY_SETTINGS_TOML enum { ARG_key, ARG_default }; static const mp_arg_t allowed_args[] = { { MP_QSTR_key, MP_ARG_REQUIRED | MP_ARG_OBJ }, @@ -281,7 +320,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_int_t size = mp_arg_validate_int_min(mp_obj_get_int(size_in), 0, MP_QSTR_size); 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)) { mp_raise_NotImplementedError(MP_ERROR_TEXT("No hardware random available")); diff --git a/shared-bindings/os/__init__.h b/shared-bindings/os/__init__.h index 56b643e2edf..f81ed4219e9 100644 --- a/shared-bindings/os/__init__.h +++ b/shared-bindings/os/__init__.h @@ -10,12 +10,22 @@ #include #include "py/objtuple.h" +#include "shared-module/os/__init__.h" void common_hal_os_chdir(const char *path); mp_obj_t common_hal_os_getcwd(void); mp_obj_t common_hal_os_getenv(const char *key, mp_obj_t default_); mp_obj_t common_hal_os_getenv_path(const char *path, const char *key, mp_obj_t default_); +#if CIRCUITPY_WIFI || CIRCUITPY_MII +// Gets the value of os.uname().nodename. That is the network hostname, or the +// hostname the network interface will be given once it is set up, or +// MICROPY_HW_MCU_NAME if there is no hostname. Writes the value to buf as a +// NUL-terminated string, truncated to fit in buf_size bytes. If buf_size is 0, +// writes nothing. Never allocates or raises. +void common_hal_os_get_nodename(char *buf, size_t buf_size); +#endif + 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); diff --git a/shared-bindings/paralleldisplaybus/ParallelBus.c b/shared-bindings/paralleldisplaybus/ParallelBus.c index dfe363bdcb7..a06ded0984d 100644 --- a/shared-bindings/paralleldisplaybus/ParallelBus.c +++ b/shared-bindings/paralleldisplaybus/ParallelBus.c @@ -39,10 +39,11 @@ //| """Create a ParallelBus object associated with the given pins. The bus is inferred from data0 //| by implying the next 7 additional pins on a given GPIO port. //| -//| 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. +//| The parallel bus and pins are then in use by the display until your code finishes or +//| the display's ``deinit()`` is called. If the display is +//| `supervisor.runtime.display `, they stay in use after your code finishes, so CircuitPython can +//| use the display. In that case, check `supervisor.runtime.display ` before creating the display +//| again, or call ``supervisor.runtime.display.deinit()`` first. //| //| :param microcontroller.Pin data_pins: A list of data pins. Specify exactly one of ``data_pins`` or ``data0``. //| :param microcontroller.Pin data0: The first data pin. The rest are implied @@ -75,9 +76,6 @@ static mp_obj_t paralleldisplaybus_parallelbus_make_new(const mp_obj_type_t *typ const mcu_pin_obj_t *read = validate_obj_is_free_pin_or_none(args[ARG_read].u_obj, MP_QSTR_read); const mcu_pin_obj_t *reset = validate_obj_is_free_pin_or_none(args[ARG_reset].u_obj, MP_QSTR_reset); - paralleldisplaybus_parallelbus_obj_t *self = &allocate_display_bus_or_raise()->parallel_bus; - self->base.type = ¶lleldisplaybus_parallelbus_type; - bool specified_data0 = args[ARG_data0].u_obj != mp_const_none; bool specified_data_pins = args[ARG_data_pins].u_obj != mp_const_none; @@ -85,14 +83,26 @@ static mp_obj_t paralleldisplaybus_parallelbus_make_new(const mp_obj_type_t *typ mp_raise_ValueError(MP_ERROR_TEXT("Specify exactly one of data0 or data_pins")); } + uint32_t frequency = (uint32_t)mp_arg_validate_int_min(args[ARG_frequency].u_int, 1, MP_QSTR_frequency); + + // Validate everything before taking a display bus slot. Once the slot has a type, + // release_displays() deinits it, even if construct never ran. + const mcu_pin_obj_t *data0 = NULL; + uint8_t num_pins = 0; + const mcu_pin_obj_t *data_pins[16]; if (specified_data0) { - const mcu_pin_obj_t *data0 = validate_obj_is_free_pin(args[ARG_data0].u_obj, MP_QSTR_data0); - common_hal_paralleldisplaybus_parallelbus_construct(self, data0, command, chip_select, write, read, reset, args[ARG_frequency].u_int); + data0 = validate_obj_is_free_pin(args[ARG_data0].u_obj, MP_QSTR_data0); } else { - uint8_t num_pins; - const mcu_pin_obj_t *data_pins[16]; validate_list_is_free_pins(MP_QSTR_data_pins, data_pins, (mp_int_t)MP_ARRAY_SIZE(data_pins), args[ARG_data_pins].u_obj, &num_pins); - common_hal_paralleldisplaybus_parallelbus_construct_nonsequential(self, num_pins, data_pins, command, chip_select, write, read, reset, args[ARG_frequency].u_int); + } + + paralleldisplaybus_parallelbus_obj_t *self = &allocate_display_bus_or_raise()->parallel_bus; + self->base.type = ¶lleldisplaybus_parallelbus_type; + + if (specified_data0) { + common_hal_paralleldisplaybus_parallelbus_construct(self, data0, command, chip_select, write, read, reset, frequency); + } else { + common_hal_paralleldisplaybus_parallelbus_construct_nonsequential(self, num_pins, data_pins, command, chip_select, write, read, reset, frequency); } return self; } diff --git a/shared-bindings/paralleldisplaybus/__init__.c b/shared-bindings/paralleldisplaybus/__init__.c index 24d968c9e31..19a381570ba 100644 --- a/shared-bindings/paralleldisplaybus/__init__.c +++ b/shared-bindings/paralleldisplaybus/__init__.c @@ -29,6 +29,3 @@ const mp_obj_module_t paralleldisplaybus_module = { }; MP_REGISTER_MODULE(MP_QSTR_paralleldisplaybus, paralleldisplaybus_module); - -// Remove in CircuitPython 10 -MP_REGISTER_MODULE(MP_QSTR_paralleldisplay, paralleldisplaybus_module); diff --git a/shared-bindings/picogame/Bitmap.c b/shared-bindings/picogame/Bitmap.c new file mode 100644 index 00000000000..e03a4703d49 --- /dev/null +++ b/shared-bindings/picogame/Bitmap.c @@ -0,0 +1,244 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT +// +// picogame.Bitmap: pixel data (PAL8 or RGB565) shared by sprites, tilemaps and blits. + +#include "py/runtime.h" +#include "shared-module/picogame/pg_compat.h" +#include "shared-bindings/busdisplay/BusDisplay.h" +#include "shared-bindings/picogame/__init__.h" +#include "shared-bindings/picogame/Bitmap.h" +#include "shared-bindings/picogame/Sprite.h" +#if CIRCUITPY_PICOGAME_FAST_DISPLAY +#include "shared-bindings/picogame/Display.h" // fast DMA backend; absent on portable ports +#include "shared-module/picogame/Display.h" // its struct (pg_get_display unwraps the wrapper) +#endif +#include "shared-bindings/picogame/Scene.h" +#include "shared-bindings/picogame/Tilemap.h" +#include "shared-bindings/picogame/Particles.h" +#include "shared-bindings/picogame/Canvas.h" +#include "shared-bindings/picogame/Framebuffer.h" +#include "shared-module/picogame/__init__.h" +#include "shared-module/picogame/Bitmap.h" +#include "shared-module/picogame/Sprite.h" + +// --------------------------------------------------------------------------- +// Bitmap +// --------------------------------------------------------------------------- + +//| class Bitmap: +//| """An image atlas of one or more frames that all share one size. RGB565 +//| pixel data and palette entries must be in the display's transfer byte +//| order (use :py:func:`rgb565` to build colors); PAL8 pixel data are +//| palette indices. +//| +//| The bitmap references the caller-provided data without copying or modifying +//| it. The backing buffer may live in RAM or in read-only memory.""" +//| +//| def __init__( +//| self, +//| data: ReadableBuffer, +//| width: int, +//| height: int, +//| *, +//| format: int = RGB565, +//| palette: Optional[ReadableBuffer] = None, +//| frames: int = 1, +//| stride: int = 0, +//| transparent: Optional[int] = None, +//| ) -> None: +//| """:param ~circuitpython_typing.ReadableBuffer data: RGB565 pixel data in +//| the display's transfer byte order, or palette indices for ``PAL8`` +//| :param int width: width of one frame in pixels +//| :param int height: height of one frame in pixels +//| :param int format: :py:data:`RGB565` (2 bytes per pixel) or :py:data:`PAL8` +//| (1 byte per pixel, indexing ``palette``) +//| :param ~circuitpython_typing.ReadableBuffer palette: for ``PAL8``, a buffer +//| of transfer-order RGB565 colors, two bytes per entry. Every byte in +//| ``data`` must be a valid palette index, that is, less than +//| ``len(palette) // 2``. +//| :param int frames: number of equal-size frames, laid out left to right in +//| one horizontal atlas +//| :param int stride: distance between two rows in pixels. ``0``, the +//| default, means ``width * frames``; set it explicitly to reference a +//| sub-region of a wider image. +//| :param int transparent: color (``RGB565``) or index (``PAL8``) that is +//| skipped when drawing. Defaults to `None`, fully opaque.""" +//| ... +//| +static mp_obj_t picogame_bitmap_make_new(const mp_obj_type_t *type, size_t n_args, + size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_data, ARG_width, ARG_height, ARG_format, ARG_palette, ARG_frames, ARG_stride, ARG_transparent }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_data, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_width, MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_height, MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_format, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = PICOGAME_FMT_RGB565} }, + { MP_QSTR_palette, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, + { MP_QSTR_frames, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1} }, + { MP_QSTR_stride, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_transparent, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + // bound BEFORE any arithmetic: an unbounded width could overflow width*frames (int32) and wrap + // small, slipping past the size guards below into an undersized buffer (OOB read in the blitter). + mp_int_t width = mp_arg_validate_int_range(args[ARG_width].u_int, 1, 65535, MP_QSTR_width); + mp_int_t height = mp_arg_validate_int_range(args[ARG_height].u_int, 1, 65535, MP_QSTR_height); + mp_int_t frames = mp_arg_validate_int_range(args[ARG_frames].u_int, 1, 255, MP_QSTR_frames); + mp_int_t format = args[ARG_format].u_int; + if (format != PICOGAME_FMT_RGB565 && format != PICOGAME_FMT_PAL8) { + mp_raise_ValueError(MP_ERROR_TEXT("Invalid format")); + } + mp_int_t stride = args[ARG_stride].u_int; + if (stride <= 0) { + stride = width * frames; + } + // stride must hold the whole horizontal atlas, and the dims must fit the uint16_t fields, + // or blits index past a row / the stored stride truncates. + mp_arg_validate_int_max(width * frames, 65535, MP_QSTR_width); + mp_arg_validate_int_max(stride, 65535, MP_QSTR_stride); + mp_arg_validate_int_min(stride, width * frames, MP_QSTR_stride); + + mp_buffer_info_t data_info; + mp_get_buffer_raise(args[ARG_data].u_obj, &data_info, MP_BUFFER_READ); + + const uint16_t *palette = NULL; + mp_obj_t palette_obj = MP_OBJ_NULL; + size_t pal_len = 0; + if (format == PICOGAME_FMT_PAL8) { + if (args[ARG_palette].u_obj == mp_const_none) { + mp_arg_error_invalid(MP_QSTR_palette); // PAL8 needs one + } + mp_buffer_info_t pal_info; + mp_get_buffer_raise(args[ARG_palette].u_obj, &pal_info, MP_BUFFER_READ); + palette = pal_info.buf; + palette_obj = args[ARG_palette].u_obj; + pal_len = pal_info.len; + } + + size_t bpp = (format == PICOGAME_FMT_PAL8) ? 1 : 2; + // 64-bit: stride*height*bpp can exceed 32 bits (stride,height <= 65535) and wrap small in a 32-bit + // size_t, letting a tiny buffer pass this check -> OOB read in the blitter. Compute + compare wide. + uint64_t need = (uint64_t)stride * (uint64_t)height * (uint64_t)bpp; + if ((uint64_t)data_info.len < need) { + mp_raise_ValueError(MP_ERROR_TEXT("buffer too small")); + } + if (format == PICOGAME_FMT_PAL8 && pal_len < 2) { + // Need >=1 entry so pal[0] is valid. Contract (see blitter): PAL8 indices MUST be < palette + // length. The caller may write indices into the (mutable) `data` buffer directly, so we cannot + // validate once here. An out-of-range index is undefined behaviour (reads past the palette: + // usually a garbage colour, but it may fault on some platforms). Per-pixel clamping was dropped + // for speed - see the "restore full bounds-safety" note in the PAL8 blit loop if it's needed. + mp_arg_validate_length_min(pal_len, 1, MP_QSTR_palette); + } + + picogame_bitmap_obj_t *self = mp_obj_malloc(picogame_bitmap_obj_t, type); + self->data_obj = args[ARG_data].u_obj; + self->palette_obj = palette_obj; + self->data = data_info.buf; + self->palette = palette; + self->width = width; + self->height = height; + self->stride = stride; + self->frames = frames; + self->format = format; + // palette length in entries (informational; blitter assumes indices < this - see blit contract). + self->pal_entries = (uint16_t)((pal_len / 2) > 65535 ? 65535 : (pal_len / 2)); + if (args[ARG_transparent].u_obj != mp_const_none) { + mp_int_t t = mp_obj_get_int(args[ARG_transparent].u_obj); + // PAL8 keys are indexes: narrow to 8 bits so every blit path agrees. + self->transparent = (format == PICOGAME_FMT_PAL8) ? (uint8_t)t : (uint16_t)t; + self->has_transparent = true; + } else { + self->transparent = 0; + self->has_transparent = false; + } + return MP_OBJ_FROM_PTR(self); +} + +//| +//| width: int +//| """Width of one frame in pixels. (read-only)""" +//| height: int +//| """Height of one frame in pixels. (read-only)""" +//| frames: int +//| """Number of frames in the atlas. (read-only)""" +static mp_obj_t bitmap_get_width(mp_obj_t self_in) { + return MP_OBJ_NEW_SMALL_INT(((picogame_bitmap_obj_t *)MP_OBJ_TO_PTR(self_in))->width); +} +static MP_DEFINE_CONST_FUN_OBJ_1(bitmap_get_width_obj, bitmap_get_width); +MP_PROPERTY_GETTER(bitmap_width_obj, (mp_obj_t)&bitmap_get_width_obj); + +static mp_obj_t bitmap_get_height(mp_obj_t self_in) { + return MP_OBJ_NEW_SMALL_INT(((picogame_bitmap_obj_t *)MP_OBJ_TO_PTR(self_in))->height); +} +static MP_DEFINE_CONST_FUN_OBJ_1(bitmap_get_height_obj, bitmap_get_height); +MP_PROPERTY_GETTER(bitmap_height_obj, (mp_obj_t)&bitmap_get_height_obj); + +static mp_obj_t bitmap_get_frames(mp_obj_t self_in) { + return MP_OBJ_NEW_SMALL_INT(((picogame_bitmap_obj_t *)MP_OBJ_TO_PTR(self_in))->frames); +} +static MP_DEFINE_CONST_FUN_OBJ_1(bitmap_get_frames_obj, bitmap_get_frames); +MP_PROPERTY_GETTER(bitmap_frames_obj, (mp_obj_t)&bitmap_get_frames_obj); + +//| format: int +//| """:py:data:`RGB565` or :py:data:`PAL8`. (read-only)""" +static mp_obj_t bitmap_get_format(mp_obj_t self_in) { + return MP_OBJ_NEW_SMALL_INT(((picogame_bitmap_obj_t *)MP_OBJ_TO_PTR(self_in))->format); +} +static MP_DEFINE_CONST_FUN_OBJ_1(bitmap_get_format_obj, bitmap_get_format); +MP_PROPERTY_GETTER(bitmap_format_obj, (mp_obj_t)&bitmap_get_format_obj); + +//| stride: int +//| """Row stride in pixels. (read-only)""" +static mp_obj_t bitmap_get_stride(mp_obj_t self_in) { + return MP_OBJ_NEW_SMALL_INT(((picogame_bitmap_obj_t *)MP_OBJ_TO_PTR(self_in))->stride); +} +static MP_DEFINE_CONST_FUN_OBJ_1(bitmap_get_stride_obj, bitmap_get_stride); +MP_PROPERTY_GETTER(bitmap_stride_obj, (mp_obj_t)&bitmap_get_stride_obj); + +//| palette: Optional[ReadableBuffer] +//| """The ``PAL8`` palette buffer this Bitmap was built with, or `None` for +//| ``RGB565``. (read-only)""" +static mp_obj_t bitmap_get_palette(mp_obj_t self_in) { + picogame_bitmap_obj_t *self = MP_OBJ_TO_PTR(self_in); + return (self->palette_obj == MP_OBJ_NULL) ? mp_const_none : self->palette_obj; +} +static MP_DEFINE_CONST_FUN_OBJ_1(bitmap_get_palette_obj, bitmap_get_palette); +MP_PROPERTY_GETTER(bitmap_palette_obj, (mp_obj_t)&bitmap_get_palette_obj); + +//| transparent: Optional[int] +//| """The transparent color or index, or `None` if the Bitmap is fully +//| opaque. (read-only)""" +//| +//| +static mp_obj_t bitmap_get_transparent(mp_obj_t self_in) { + picogame_bitmap_obj_t *self = MP_OBJ_TO_PTR(self_in); + return self->has_transparent ? MP_OBJ_NEW_SMALL_INT(self->transparent) : mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(bitmap_get_transparent_obj, bitmap_get_transparent); +MP_PROPERTY_GETTER(bitmap_transparent_obj, (mp_obj_t)&bitmap_get_transparent_obj); + +static const mp_rom_map_elem_t picogame_bitmap_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_width), MP_ROM_PTR(&bitmap_width_obj) }, + { MP_ROM_QSTR(MP_QSTR_height), MP_ROM_PTR(&bitmap_height_obj) }, + { MP_ROM_QSTR(MP_QSTR_frames), MP_ROM_PTR(&bitmap_frames_obj) }, + { MP_ROM_QSTR(MP_QSTR_format), MP_ROM_PTR(&bitmap_format_obj) }, + { MP_ROM_QSTR(MP_QSTR_stride), MP_ROM_PTR(&bitmap_stride_obj) }, + { MP_ROM_QSTR(MP_QSTR_palette), MP_ROM_PTR(&bitmap_palette_obj) }, + { MP_ROM_QSTR(MP_QSTR_transparent), MP_ROM_PTR(&bitmap_transparent_obj) }, +}; +static MP_DEFINE_CONST_DICT(picogame_bitmap_locals_dict, picogame_bitmap_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + picogame_bitmap_type, + MP_QSTR_Bitmap, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, picogame_bitmap_make_new, + locals_dict, &picogame_bitmap_locals_dict + ); diff --git a/shared-bindings/picogame/Bitmap.h b/shared-bindings/picogame/Bitmap.h new file mode 100644 index 00000000000..44e2a2fb1aa --- /dev/null +++ b/shared-bindings/picogame/Bitmap.h @@ -0,0 +1,11 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-module/picogame/Bitmap.h" + +extern const mp_obj_type_t picogame_bitmap_type; diff --git a/shared-bindings/picogame/Canvas.c b/shared-bindings/picogame/Canvas.c new file mode 100644 index 00000000000..07c225c69e4 --- /dev/null +++ b/shared-bindings/picogame/Canvas.c @@ -0,0 +1,556 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +#include "py/runtime.h" +#include "shared-module/picogame/pg_compat.h" +#include "shared-bindings/picogame/Canvas.h" +#include "shared-bindings/picogame/Bitmap.h" +#if CIRCUITPY_FONTIO +#include "shared-bindings/fontio/BuiltinFont.h" +#endif +#include "shared-module/picogame/Canvas.h" + +//| class Canvas: +//| """A RAM drawing surface composited as a `Scene` layer. Draw primitives +//| into it; only redrawn areas repaint. Colors come from +//| :py:func:`rgb565`.""" +//| +//| def __init__( +//| self, +//| width: int, +//| height: int, +//| *, +//| transparent: Optional[int] = None, +//| buffer: Optional[WriteableBuffer] = None, +//| ) -> None: +//| """:param int width: surface width in pixels +//| :param int height: surface height in pixels +//| :param int transparent: color that is skipped when the canvas is +//| composited; `None` makes every pixel opaque +//| :param ~circuitpython_typing.WriteableBuffer buffer: optional caller-owned +//| pixel buffer of at least ``width * height * 2`` bytes (for example a +//| ``bytearray`` or a writable ``memoryview``). The canvas draws into it +//| instead of allocating its own.""" +//| ... +//| +static mp_obj_t picogame_canvas_make_new(const mp_obj_type_t *type, size_t n_args, + size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_width, ARG_height, ARG_transparent, ARG_buffer }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_width, MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_height, MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_transparent, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, + { MP_QSTR_buffer, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + mp_int_t w = mp_arg_validate_int_range(args[ARG_width].u_int, 1, 1024, MP_QSTR_width); + mp_int_t h = mp_arg_validate_int_range(args[ARG_height].u_int, 1, 1024, MP_QSTR_height); + + picogame_canvas_obj_t *self = mp_obj_malloc(picogame_canvas_obj_t, type); + self->w = w; + self->h = h; + self->x = 0; + self->y = 0; + if (args[ARG_buffer].u_obj != mp_const_none) { + // external buffer (e.g. an arena slice) - draw into it, don't allocate/own it + mp_buffer_info_t bi; + mp_get_buffer_raise(args[ARG_buffer].u_obj, &bi, MP_BUFFER_RW); + if (bi.len < (size_t)w * h * 2) { + mp_raise_ValueError(MP_ERROR_TEXT("buffer too small")); + } + if ((uintptr_t)bi.buf & 1) { // odd byte address -> uint16 pixel stores fault on Cortex-M0+ + mp_raise_ValueError_varg(MP_ERROR_TEXT("Buffer must be a multiple of %d bytes"), 2); + } + self->data = bi.buf; + self->data_obj = args[ARG_buffer].u_obj; // keep the backing object alive (GC-traced) + } else { + // Pure pixel data, no Python pointers -> exempt from the conservative GC scan + // (shorter gc.collect() pauses; a 150x60 canvas is 18 KB the mark phase can skip). + self->data = m_malloc_without_collect((size_t)w * h * sizeof(uint16_t)); + self->data_obj = MP_OBJ_NULL; + } + if (args[ARG_transparent].u_obj != mp_const_none) { + self->transparent = mp_obj_get_int(args[ARG_transparent].u_obj); + self->has_transparent = true; + } else { + self->transparent = 0; + self->has_transparent = false; + } + // clear() marks the surface dirty and reads the accumulator, so reset it on both sides. + picogame_canvas_dirty_reset(self); + picogame_canvas_clear(self, self->has_transparent ? self->transparent : 0); + picogame_canvas_dirty_reset(self); + return MP_OBJ_FROM_PTR(self); +} + +static picogame_canvas_obj_t *cv_self(mp_obj_t o) { + return MP_OBJ_TO_PTR(o); +} + +// Shared int-arg unpacker for the plain drawing trampolines below: every one of them is +// "self + N ints -> void", and the inlined per-wrapper mp_obj_get_int runs cost ~70-120 B +// each at -Os. One loop here + a tiny per-wrapper stub keeps the flash cost per method at +// ~2 calls. n comes from the VAR_BETWEEN exact arity, so v[] is always fully written. +// Call it in its own statement: the order a call's arguments are evaluated in is unspecified, +// so v[] read beside cv_args() in one argument list may be read before it is written. +static picogame_canvas_obj_t *cv_args(const mp_obj_t *a, size_t n, int *v) { + for (size_t i = 1; i < n; i++) { + v[i - 1] = mp_obj_get_int(a[i]); + } + return cv_self(a[0]); +} + +//| def clear(self, color: int) -> None: +//| """Fill the whole surface with ``color``.""" +//| ... +//| +static mp_obj_t canvas_clear(mp_obj_t self_in, mp_obj_t color) { + picogame_canvas_clear(cv_self(self_in), mp_obj_get_int(color)); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(canvas_clear_obj, canvas_clear); + +//| +//| def pixel(self, x: int, y: int, color: int) -> None: +//| """Set a single pixel.""" +//| ... +//| +static mp_obj_t canvas_pixel(size_t n, const mp_obj_t *a) { + int v[3]; + picogame_canvas_obj_t *cv = cv_args(a, n, v); + picogame_canvas_pixel(cv, v[0], v[1], v[2]); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(canvas_pixel_obj, 4, 4, canvas_pixel); + +//| +//| def fill_rect(self, x: int, y: int, w: int, h: int, color: int) -> None: +//| """Fill an axis-aligned rectangle.""" +//| ... +//| +static mp_obj_t canvas_fill_rect(size_t n, const mp_obj_t *a) { + int v[5]; + picogame_canvas_obj_t *cv = cv_args(a, n, v); + picogame_canvas_fill_rect(cv, v[0], v[1], v[2], v[3], v[4]); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(canvas_fill_rect_obj, 6, 6, canvas_fill_rect); + +//| +//| def blit( +//| self, +//| bitmap: Bitmap, +//| x: int, +//| y: int, +//| frame: int = 0, +//| flip_x: bool = False, +//| flip_y: bool = False, +//| ) -> None: +//| """Copy one frame of ``bitmap``, selected by ``frame``, into the canvas +//| at ``(x, y)``, honoring the bitmap's transparent color.""" +//| ... +//| +static mp_obj_t canvas_blit(size_t n, const mp_obj_t *a) { + picogame_bitmap_obj_t *bm = MP_OBJ_TO_PTR( + mp_arg_validate_type(a[1], &picogame_bitmap_type, MP_QSTR_bitmap)); + // Same domain as Sprite.frame (uint8): a negative frame would survive the blitter's + // wrap (C % keeps the sign) and read before the sheet data. + int frame = (n > 4) ? (int)mp_arg_validate_int_range(mp_obj_get_int(a[4]), 0, 255, MP_QSTR_frame) : 0; + bool fx = (n > 5) ? mp_obj_is_true(a[5]) : false; + bool fy = (n > 6) ? mp_obj_is_true(a[6]) : false; + picogame_canvas_blit(cv_self(a[0]), bm, mp_obj_get_int(a[2]), mp_obj_get_int(a[3]), frame, fx, fy); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(canvas_blit_obj, 4, 7, canvas_blit); + + +//| def fill_triangles( +//| self, +//| verts: ReadableBuffer, +//| colors: ReadableBuffer, +//| n: int, +//| x_off: int = 0, +//| y_off: int = 0, +//| ) -> None: +//| """Fill a batch of triangles in one call, which is faster than repeated +//| :py:meth:`fill_triangle` calls for many triangles. +//| +//| :param ~circuitpython_typing.ReadableBuffer verts: ``6 * n`` ``int16`` +//| values: x0, y0, x1, y1, x2, y2 per triangle +//| :param ~circuitpython_typing.ReadableBuffer colors: ``n`` ``uint16`` colors, +//| one per triangle +//| :param int n: number of triangles +//| :param int x_off: added to every x before clipping +//| :param int y_off: added to every y before clipping +//| +//| The offsets translate the whole batch, so one screen-space batch can be +//| replayed into each `StripDraw` view by passing the negated view origin +//| (``x_off=-vx, y_off=-vy``); triangles outside the view are skipped.""" +//| ... +//| +static mp_obj_t canvas_fill_triangles(size_t na, const mp_obj_t *a) { + picogame_canvas_obj_t *cv = cv_self(a[0]); + mp_buffer_info_t vi, ci; + mp_get_buffer_raise(a[1], &vi, MP_BUFFER_READ); + mp_get_buffer_raise(a[2], &ci, MP_BUFFER_READ); + int n = mp_obj_get_int(a[3]); + int xo = na > 4 ? mp_obj_get_int(a[4]) : 0; + int yo = na > 5 ? mp_obj_get_int(a[5]) : 0; + const int16_t *v = vi.buf; + const uint16_t *col = ci.buf; + int cap_v = (int)(vi.len / 12); // 6 int16 = 12 bytes per triangle + int cap_c = (int)(ci.len >> 1); + if (n > cap_v) { + n = cap_v; + } + if (n > cap_c) { + n = cap_c; + } + picogame_fill_triangle_batch(cv, v, col, n, xo, yo); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(canvas_fill_triangles_obj, 4, 6, canvas_fill_triangles); + +//| def vspans( +//| self, +//| x0s: ReadableBuffer, +//| x1s: ReadableBuffer, +//| tops: ReadableBuffer, +//| bots: ReadableBuffer, +//| colors: ReadableBuffer, +//| n: int, +//| x_off: int = 0, +//| y_off: int = 0, +//| ) -> None: +//| """Fill a batch of vertical color spans in one call. Span ``i`` covers +//| columns ``x0s[i]`` through ``x1s[i]`` (exclusive) and rows ``tops[i]`` +//| through ``bots[i]`` (exclusive) in color ``colors[i]``. +//| +//| :param ~circuitpython_typing.ReadableBuffer x0s: ``n`` ``uint16`` left edges +//| :param ~circuitpython_typing.ReadableBuffer x1s: ``n`` ``uint16`` exclusive +//| right edges +//| :param ~circuitpython_typing.ReadableBuffer tops: ``n`` ``uint16`` top rows +//| :param ~circuitpython_typing.ReadableBuffer bots: ``n`` ``uint16`` exclusive +//| bottom rows +//| :param ~circuitpython_typing.ReadableBuffer colors: ``n`` ``uint16`` colors +//| :param int n: number of spans +//| :param int x_off: added to every x before clipping +//| :param int y_off: added to every y before clipping +//| +//| The offsets translate the whole batch, so one screen-space batch (for +//| example `picogame3d.raycast` wall runs) can be replayed into each `StripDraw` view by +//| passing the negated view origin; spans outside the view are skipped.""" +//| ... +//| +static mp_obj_t canvas_vspans(size_t na, const mp_obj_t *a) { + picogame_canvas_obj_t *cv = cv_self(a[0]); + // five equal-shape uint16 arrays in a row: fetch + shortest-length fold in one loop + mp_buffer_info_t bi5[5]; + size_t cap = (size_t)-1; + for (int i = 0; i < 5; i++) { + mp_get_buffer_raise(a[1 + i], &bi5[i], MP_BUFFER_READ); + if (bi5[i].len < cap) { + cap = bi5[i].len; + } + } + int n = mp_obj_get_int(a[6]); + int xo = na > 7 ? mp_obj_get_int(a[7]) : 0; + int yo = na > 8 ? mp_obj_get_int(a[8]) : 0; + if (n > (int)(cap >> 1)) { + n = (int)(cap >> 1); // never read past the shortest array + } + const uint16_t *x0s = bi5[0].buf; + const uint16_t *x1s = bi5[1].buf; + const uint16_t *tops = bi5[2].buf; + const uint16_t *bots = bi5[3].buf; + const uint16_t *cols = bi5[4].buf; + int cw = cv->w, ch = cv->h; + for (int i = 0; i < n; i++) { + int t = tops[i] + yo, b = bots[i] + yo; + if (b <= 0 || t >= ch || b <= t) { + continue; // span outside this band + } + int x0 = x0s[i] + xo, x1 = x1s[i] + xo; + if (x1 <= 0 || x0 >= cw || x1 <= x0) { + continue; + } + picogame_canvas_fill_rect(cv, x0, t, x1 - x0, b - t, cols[i]); + } + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(canvas_vspans_obj, 7, 9, canvas_vspans); + + +//| def rect(self, x: int, y: int, w: int, h: int, color: int) -> None: +//| """Draw a one-pixel rectangle outline.""" +//| ... +//| +static mp_obj_t canvas_rect(size_t n, const mp_obj_t *a) { + int v[5]; + picogame_canvas_obj_t *cv = cv_args(a, n, v); + picogame_canvas_rect(cv, v[0], v[1], v[2], v[3], v[4]); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(canvas_rect_obj, 6, 6, canvas_rect); + +//| +//| def line(self, x0: int, y0: int, x1: int, y1: int, color: int) -> None: +//| """Draw a one-pixel line between two points.""" +//| ... +//| +static mp_obj_t canvas_line(size_t n, const mp_obj_t *a) { + int v[5]; + picogame_canvas_obj_t *cv = cv_args(a, n, v); + picogame_canvas_line(cv, v[0], v[1], v[2], v[3], v[4]); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(canvas_line_obj, 6, 6, canvas_line); + +//| +//| def fill_circle(self, cx: int, cy: int, r: int, color: int) -> None: +//| """Fill a circle of radius ``r`` centered on ``(cx, cy)``.""" +//| ... +//| +static mp_obj_t canvas_fill_circle(size_t n, const mp_obj_t *a) { + int v[4]; + picogame_canvas_obj_t *cv = cv_args(a, n, v); + picogame_canvas_fill_circle(cv, v[0], v[1], v[2], v[3]); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(canvas_fill_circle_obj, 5, 5, canvas_fill_circle); + +//| +//| def circle(self, cx: int, cy: int, r: int, color: int) -> None: +//| """Draw a one-pixel circle outline.""" +//| ... +//| +static mp_obj_t canvas_circle(size_t n, const mp_obj_t *a) { + int v[4]; + picogame_canvas_obj_t *cv = cv_args(a, n, v); + picogame_canvas_circle(cv, v[0], v[1], v[2], v[3]); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(canvas_circle_obj, 5, 5, canvas_circle); + +//| +//| def ring(self, cx: int, cy: int, r: int, thickness: int, color: int) -> None: +//| """Draw a circle outline ``thickness`` pixels wide, grown inwards from radius ``r``.""" +//| ... +//| +static mp_obj_t canvas_ring(size_t n, const mp_obj_t *a) { + int v[5]; + picogame_canvas_obj_t *cv = cv_args(a, n, v); + picogame_canvas_ring(cv, v[0], v[1], v[2], v[3], v[4]); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(canvas_ring_obj, 6, 6, canvas_ring); + +//| +//| def triangle( +//| self, x0: int, y0: int, x1: int, y1: int, x2: int, y2: int, color: int +//| ) -> None: +//| """Draw a one-pixel triangle outline through the three points.""" +//| ... +//| +static mp_obj_t canvas_triangle(size_t n, const mp_obj_t *a) { + int v[7]; + picogame_canvas_obj_t *cv = cv_args(a, n, v); + picogame_canvas_triangle(cv, v[0], v[1], v[2], v[3], v[4], v[5], v[6]); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(canvas_triangle_obj, 8, 8, canvas_triangle); + +//| +//| def fill_triangle( +//| self, x0: int, y0: int, x1: int, y1: int, x2: int, y2: int, color: int +//| ) -> None: +//| """Fill a triangle. See :py:meth:`fill_triangles` to submit a whole batch +//| in one call.""" +//| ... +//| +static mp_obj_t canvas_fill_triangle(size_t n, const mp_obj_t *a) { + int v[7]; + picogame_canvas_obj_t *cv = cv_args(a, n, v); + picogame_canvas_fill_triangle(cv, v[0], v[1], v[2], v[3], v[4], v[5], v[6]); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(canvas_fill_triangle_obj, 8, 8, canvas_fill_triangle); + +//| +//| def ellipse(self, cx: int, cy: int, rx: int, ry: int, color: int) -> None: +//| """Draw a one-pixel ellipse outline with radii ``rx``/``ry``.""" +//| ... +//| +static mp_obj_t canvas_ellipse(size_t n, const mp_obj_t *a) { + int v[5]; + picogame_canvas_obj_t *cv = cv_args(a, n, v); + picogame_canvas_ellipse(cv, v[0], v[1], v[2], v[3], v[4]); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(canvas_ellipse_obj, 6, 6, canvas_ellipse); + +//| +//| def fill_ellipse(self, cx: int, cy: int, rx: int, ry: int, color: int) -> None: +//| """Fill an ellipse with radii ``rx``/``ry``.""" +//| ... +//| +static mp_obj_t canvas_fill_ellipse(size_t n, const mp_obj_t *a) { + int v[5]; + picogame_canvas_obj_t *cv = cv_args(a, n, v); + picogame_canvas_fill_ellipse(cv, v[0], v[1], v[2], v[3], v[4]); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(canvas_fill_ellipse_obj, 6, 6, canvas_fill_ellipse); + +//| +//| def fill_round_rect(self, x: int, y: int, w: int, h: int, r: int, color: int) -> None: +//| """Fill a rectangle with corners rounded to radius ``r``.""" +//| ... +//| +static mp_obj_t canvas_fill_round_rect(size_t n, const mp_obj_t *a) { + int v[6]; + picogame_canvas_obj_t *cv = cv_args(a, n, v); + picogame_canvas_fill_round_rect(cv, v[0], v[1], v[2], v[3], v[4], v[5]); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(canvas_fill_round_rect_obj, 7, 7, canvas_fill_round_rect); + +//| +//| def frame3d(self, x: int, y: int, w: int, h: int, light: int, dark: int) -> None: +//| """Draw a one-pixel bevelled frame: top and left edges in ``light``, bottom and +//| right in ``dark``, giving a raised look (swap the two for a sunken one).""" +//| ... +//| +static mp_obj_t canvas_frame3d(size_t n, const mp_obj_t *a) { + int v[6]; + picogame_canvas_obj_t *cv = cv_args(a, n, v); + picogame_canvas_frame3d(cv, v[0], v[1], v[2], v[3], v[4], v[5]); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(canvas_frame3d_obj, 7, 7, canvas_frame3d); + +//| +//| def text( +//| self, x: int, y: int, s: str, fg: int, font: fontio.BuiltinFont, bg: int | None = None +//| ) -> None: +//| """Draw ``s`` into the surface, rasterizing each glyph from ``font`` as it +//| is drawn; no memory is retained between calls. Only ASCII characters are +//| supported. If ``bg`` is given the glyph background is filled with it, +//| otherwise it is transparent. Inside a `StripDraw` callback the view is a +//| Canvas, so ``view.text(...)`` draws text directly into the frame. +//| Raises :py:class:`NotImplementedError` in builds without `fontio`.""" +//| ... +//| +static mp_obj_t canvas_text(size_t n, const mp_obj_t *a) { + #if CIRCUITPY_FONTIO + const char *s = mp_obj_str_get_str(a[3]); + mp_int_t fg = mp_obj_get_int(a[4]); + const void *font = MP_OBJ_TO_PTR(mp_arg_validate_type(a[5], &fontio_builtinfont_type, MP_QSTR_font)); + bool has_bg = (n >= 7) && (a[6] != mp_const_none); + uint16_t bg = has_bg ? (uint16_t)mp_obj_get_int(a[6]) : 0; + picogame_canvas_text(cv_self(a[0]), mp_obj_get_int(a[1]), mp_obj_get_int(a[2]), + s, (uint16_t)fg, bg, has_bg, font); + return mp_const_none; + #else + mp_raise_NotImplementedError(MP_ERROR_TEXT("Operation or feature not supported")); + #endif +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(canvas_text_obj, 6, 7, canvas_text); + +//| def move(self, x: int, y: int) -> None: +//| """Move the surface's top-left corner to (x, y) and mark both the old and new area dirty.""" +//| ... +//| +static mp_obj_t canvas_move(mp_obj_t self_in, mp_obj_t x_in, mp_obj_t y_in) { + picogame_canvas_obj_t *self = cv_self(self_in); + int nx = mp_obj_get_int(x_in), ny = mp_obj_get_int(y_in); + if (nx == self->x && ny == self->y) { + return mp_const_none; // unchanged -> avoid an avoidable repaint + } + // dirty old + new extents so the move repaints both + picogame_canvas_dirty_union(self, self->x, self->y, self->x + self->w, self->y + self->h); + self->x = nx; + self->y = ny; + picogame_canvas_dirty_union(self, self->x, self->y, self->x + self->w, self->y + self->h); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_3(canvas_move_obj, canvas_move); + +//| +//| x: int +//| """Horizontal position of the canvas top-left corner. (read-only) +//| +//| Set with :py:meth:`move`.""" +//| y: int +//| """Vertical position of the canvas top-left corner. (read-only) +//| +//| Set with :py:meth:`move`.""" +//| width: int +//| """Surface width in pixels. (read-only)""" +//| height: int +//| """Surface height in pixels. (read-only)""" +//| +//| +static mp_obj_t canvas_get_x(mp_obj_t self_in) { + return MP_OBJ_NEW_SMALL_INT(cv_self(self_in)->x); +} +static MP_DEFINE_CONST_FUN_OBJ_1(canvas_get_x_obj, canvas_get_x); +MP_PROPERTY_GETTER(canvas_x_obj, (mp_obj_t)&canvas_get_x_obj); + +static mp_obj_t canvas_get_y(mp_obj_t self_in) { + return MP_OBJ_NEW_SMALL_INT(cv_self(self_in)->y); +} +static MP_DEFINE_CONST_FUN_OBJ_1(canvas_get_y_obj, canvas_get_y); +MP_PROPERTY_GETTER(canvas_y_obj, (mp_obj_t)&canvas_get_y_obj); + +static mp_obj_t canvas_get_width(mp_obj_t self_in) { + return MP_OBJ_NEW_SMALL_INT(cv_self(self_in)->w); +} +static MP_DEFINE_CONST_FUN_OBJ_1(canvas_get_width_obj, canvas_get_width); +MP_PROPERTY_GETTER(canvas_width_obj, (mp_obj_t)&canvas_get_width_obj); + +static mp_obj_t canvas_get_height(mp_obj_t self_in) { + return MP_OBJ_NEW_SMALL_INT(cv_self(self_in)->h); +} +static MP_DEFINE_CONST_FUN_OBJ_1(canvas_get_height_obj, canvas_get_height); +MP_PROPERTY_GETTER(canvas_height_obj, (mp_obj_t)&canvas_get_height_obj); + +static const mp_rom_map_elem_t picogame_canvas_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_clear), MP_ROM_PTR(&canvas_clear_obj) }, + { MP_ROM_QSTR(MP_QSTR_x), MP_ROM_PTR(&canvas_x_obj) }, + { MP_ROM_QSTR(MP_QSTR_y), MP_ROM_PTR(&canvas_y_obj) }, + { MP_ROM_QSTR(MP_QSTR_width), MP_ROM_PTR(&canvas_width_obj) }, + { MP_ROM_QSTR(MP_QSTR_height), MP_ROM_PTR(&canvas_height_obj) }, + { MP_ROM_QSTR(MP_QSTR_pixel), MP_ROM_PTR(&canvas_pixel_obj) }, + { MP_ROM_QSTR(MP_QSTR_fill_rect), MP_ROM_PTR(&canvas_fill_rect_obj) }, + { MP_ROM_QSTR(MP_QSTR_blit), MP_ROM_PTR(&canvas_blit_obj) }, + { MP_ROM_QSTR(MP_QSTR_fill_triangles), MP_ROM_PTR(&canvas_fill_triangles_obj) }, + { MP_ROM_QSTR(MP_QSTR_vspans), MP_ROM_PTR(&canvas_vspans_obj) }, + { MP_ROM_QSTR(MP_QSTR_rect), MP_ROM_PTR(&canvas_rect_obj) }, + { MP_ROM_QSTR(MP_QSTR_line), MP_ROM_PTR(&canvas_line_obj) }, + { MP_ROM_QSTR(MP_QSTR_fill_circle), MP_ROM_PTR(&canvas_fill_circle_obj) }, + { MP_ROM_QSTR(MP_QSTR_circle), MP_ROM_PTR(&canvas_circle_obj) }, + { MP_ROM_QSTR(MP_QSTR_ring), MP_ROM_PTR(&canvas_ring_obj) }, + { MP_ROM_QSTR(MP_QSTR_triangle), MP_ROM_PTR(&canvas_triangle_obj) }, + { MP_ROM_QSTR(MP_QSTR_fill_triangle), MP_ROM_PTR(&canvas_fill_triangle_obj) }, + { MP_ROM_QSTR(MP_QSTR_ellipse), MP_ROM_PTR(&canvas_ellipse_obj) }, + { MP_ROM_QSTR(MP_QSTR_fill_ellipse), MP_ROM_PTR(&canvas_fill_ellipse_obj) }, + { MP_ROM_QSTR(MP_QSTR_fill_round_rect), MP_ROM_PTR(&canvas_fill_round_rect_obj) }, + { MP_ROM_QSTR(MP_QSTR_frame3d), MP_ROM_PTR(&canvas_frame3d_obj) }, + { MP_ROM_QSTR(MP_QSTR_text), MP_ROM_PTR(&canvas_text_obj) }, + { MP_ROM_QSTR(MP_QSTR_move), MP_ROM_PTR(&canvas_move_obj) }, +}; +static MP_DEFINE_CONST_DICT(picogame_canvas_locals_dict, picogame_canvas_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + picogame_canvas_type, + MP_QSTR_Canvas, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, picogame_canvas_make_new, + locals_dict, &picogame_canvas_locals_dict + ); diff --git a/shared-bindings/picogame/Canvas.h b/shared-bindings/picogame/Canvas.h new file mode 100644 index 00000000000..fb37aa9f898 --- /dev/null +++ b/shared-bindings/picogame/Canvas.h @@ -0,0 +1,11 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-module/picogame/Canvas.h" + +extern const mp_obj_type_t picogame_canvas_type; diff --git a/shared-bindings/picogame/Display.c b/shared-bindings/picogame/Display.c new file mode 100644 index 00000000000..b1bdbe6db38 --- /dev/null +++ b/shared-bindings/picogame/Display.c @@ -0,0 +1,128 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +#include "py/runtime.h" // brings in the board config (CIRCUITPY_PICOGAME_FAST_DISPLAY) + +// The fast DMA Display backend is port-specific (needs a common-hal). Ports without it +// (e.g. ESP32) build picogame with this whole type compiled out and use Scene's portable +// bus.send renderer instead - so picogame stays buildable on any CircuitPython port. +#if CIRCUITPY_PICOGAME_FAST_DISPLAY +#include "shared-bindings/picogame/Display.h" +#include "shared-bindings/picogame/Sprite.h" +#include "shared-bindings/busdisplay/BusDisplay.h" +#include "shared-module/picogame/__init__.h" +#include "shared-module/picogame/Display.h" + +//| class Display: +//| """A display backend that wraps an existing :py:class:`~busdisplay.BusDisplay` and +//| renders straight to its bus in double-buffered strips. On a bus that sends +//| asynchronously the next strip is composed while the previous one is on the +//| wire. It reuses the wrapped display's bus, window commands and dimensions. +//| +//| Constructing it raises :py:class:`NotImplementedError` when +//| :py:data:`FAST_DISPLAY_SUPPORTED` is `False`.""" +//| +//| def __init__(self, display: busdisplay.BusDisplay, *, rgb444: bool = False) -> None: +//| """:param ~busdisplay.BusDisplay display: the display to wrap +//| :param bool rgb444: drive the panel in 12-bit RGB444 instead of 16-bit +//| RGB565, reducing bus traffic at the cost of color depth (4,096 colors +//| instead of 65,536). The panel controller must support 12-bit color; +//| ST7789 and ST7735 do, ILI9341 does not. See :py:data:`RGB444_SUPPORTED`.""" +//| ... +//| +static mp_obj_t picogame_display_make_new(const mp_obj_type_t *type, size_t n_args, + size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_display, ARG_rgb444 }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_display, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_rgb444, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + mp_obj_t native = mp_obj_cast_to_native_base(args[ARG_display].u_obj, &busdisplay_busdisplay_type); + // MP_OBJ_NULL for a non-BusDisplay: validate the ORIGINAL object (NULL's type is unreadable). + if (native == MP_OBJ_NULL || !mp_obj_is_type(native, &busdisplay_busdisplay_type)) { + mp_arg_validate_type(args[ARG_display].u_obj, &busdisplay_busdisplay_type, MP_QSTR_display); + } + picogame_display_obj_t *self = mp_obj_malloc(picogame_display_obj_t, type); + common_hal_picogame_display_construct(self, MP_OBJ_TO_PTR(native), args[ARG_rgb444].u_bool); + return MP_OBJ_FROM_PTR(self); +} + +//| def render( +//| self, +//| sprites: List[Sprite], +//| buffer_a: WriteableBuffer, +//| buffer_b: WriteableBuffer, +//| x0: int, +//| y0: int, +//| x1: int, +//| y1: int, +//| *, +//| background: int = 0, +//| ) -> None: +//| """Render ``sprites`` into the screen region from ``(x0, y0)`` up to, but +//| not including, ``(x1, y1)``, and send it strip by strip. ``buffer_a`` and ``buffer_b`` are two +//| equal strip buffers of at least ``(x1 - x0) * 2`` bytes each, used for +//| double buffering. +//| +//| This method accepts sprites only. For mixed layer kinds use a `Scene` or +//| the module-level :py:func:`render`.""" +//| ... +//| +//| +static mp_obj_t picogame_display_render(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_sprites, ARG_buffer_a, ARG_buffer_b, ARG_x0, ARG_y0, ARG_x1, ARG_y1, ARG_background }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_sprites, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_buffer_a, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_buffer_b, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_x0, MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_y0, MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_x1, MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_y1, MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_background, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0} }, + }; + picogame_display_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]); + 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); + + size_t n = 0; + mp_obj_t *items; + mp_obj_get_array(args[ARG_sprites].u_obj, &n, &items); + for (size_t i = 0; i < n; i++) { + mp_arg_validate_type(items[i], &picogame_sprite_type, MP_QSTR_sprite); + } + + mp_buffer_info_t ba, bb; + mp_get_buffer_raise(args[ARG_buffer_a].u_obj, &ba, MP_BUFFER_WRITE); + mp_get_buffer_raise(args[ARG_buffer_b].u_obj, &bb, MP_BUFFER_WRITE); + size_t buf_pixels = (ba.len < bb.len ? ba.len : bb.len) / 2; + + // kinds == NULL: every item is a sprite (the layered path handles this). + common_hal_picogame_display_render(self, items, NULL, n, + (uint16_t *)ba.buf, (uint16_t *)bb.buf, buf_pixels, + args[ARG_x0].u_int, args[ARG_y0].u_int, args[ARG_x1].u_int, args[ARG_y1].u_int, + args[ARG_background].u_int, 0, 0); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_KW(picogame_display_render_obj, 8, picogame_display_render); + +static const mp_rom_map_elem_t picogame_display_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_render), MP_ROM_PTR(&picogame_display_render_obj) }, +}; +static MP_DEFINE_CONST_DICT(picogame_display_locals_dict, picogame_display_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + picogame_display_type, + MP_QSTR_Display, + MP_TYPE_FLAG_NONE, + make_new, picogame_display_make_new, + locals_dict, &picogame_display_locals_dict + ); + +#endif // CIRCUITPY_PICOGAME_FAST_DISPLAY diff --git a/shared-bindings/picogame/Display.h b/shared-bindings/picogame/Display.h new file mode 100644 index 00000000000..f79fbd9ba8c --- /dev/null +++ b/shared-bindings/picogame/Display.h @@ -0,0 +1,13 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +#pragma once + +#if CIRCUITPY_PICOGAME_FAST_DISPLAY +#include "shared-module/picogame/Display.h" +#endif + +extern const mp_obj_type_t picogame_display_type; diff --git a/shared-bindings/picogame/Framebuffer.c b/shared-bindings/picogame/Framebuffer.c new file mode 100644 index 00000000000..51f3b680add --- /dev/null +++ b/shared-bindings/picogame/Framebuffer.c @@ -0,0 +1,170 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT +// +// picogame.Framebuffer: a RAM render target used in place of a BusDisplay. + +#include "py/runtime.h" +#include "shared-module/picogame/pg_compat.h" +#include "shared-bindings/busdisplay/BusDisplay.h" +#include "shared-bindings/picogame/__init__.h" +#include "shared-bindings/picogame/Bitmap.h" +#include "shared-bindings/picogame/Sprite.h" +#if CIRCUITPY_PICOGAME_FAST_DISPLAY +#include "shared-bindings/picogame/Display.h" // fast DMA backend; absent on portable ports +#include "shared-module/picogame/Display.h" // its struct (pg_get_display unwraps the wrapper) +#endif +#include "shared-bindings/picogame/Scene.h" +#include "shared-bindings/picogame/Tilemap.h" +#include "shared-bindings/picogame/Particles.h" +#include "shared-bindings/picogame/Canvas.h" +#include "shared-bindings/picogame/Framebuffer.h" +#include "shared-module/picogame/__init__.h" +#include "shared-module/picogame/Bitmap.h" +#include "shared-module/picogame/Sprite.h" + +#if CIRCUITPY_PICOGAME_FRAMEBUFFER +// --------------------------------------------------------------------------- +// Framebuffer (a RAM render target used in place of a BusDisplay; scanout-buffer +// platforms - WASM playground, desktop sim, FruitJam DVI/HSTX) +// --------------------------------------------------------------------------- +//| class Framebuffer: +//| """A RAM framebuffer render target that a `Scene` or :py:func:`render` can +//| draw into instead of a :py:class:`~busdisplay.BusDisplay`, for example the +//| scanout buffer of a :py:class:`picodvi.Framebuffer`. +//| +//| Constructing it raises :py:class:`NotImplementedError` when +//| :py:data:`FRAMEBUFFER_SUPPORTED` is `False`.""" +//| +//| def __init__( +//| self, +//| buffer: WriteableBuffer, +//| width: int, +//| height: int, +//| *, +//| native_rgb565: bool = False, +//| rgb332: bool = False, +//| ) -> None: +//| """:param ~circuitpython_typing.WriteableBuffer buffer: caller-owned target +//| buffer of at least ``width * height * 2`` bytes, or ``width * height`` +//| bytes with ``rgb332=True`` +//| :param int width: target width in pixels +//| :param int height: target height in pixels +//| :param bool native_rgb565: fill the buffer with native-endian RGB565, the +//| format 16-bit scanout targets expect. By default the buffer holds +//| transfer-order RGB565. +//| :param bool rgb332: fill the buffer with 8-bit RGB332, the format of 8-bit +//| scanout targets +//| +//| ``native_rgb565`` and ``rgb332`` cannot both be true. Bitmaps, palettes and +//| :py:func:`rgb565` values stay transfer-order RGB565 regardless of the +//| output format.""" +//| ... +//| +//| width: int +//| """Target width in pixels. (read-only)""" +//| height: int +//| """Target height in pixels. (read-only)""" +//| +//| +// Static SRAM compose strip (see the scratch comment in make_new). 640*16*2 = 20 KB .bss, +// only on CIRCUITPY_PICOGAME_FRAMEBUFFER builds (fb boards have the SRAM to spare). +#define PICOGAME_FB_SCRATCH_MAX_W 640 +static uint16_t picogame_fb_scratch_sram[PICOGAME_FB_SCRATCH_MAX_W * PICOGAME_FB_SCRATCH_H]; + +static mp_obj_t picogame_framebuffer_make_new(const mp_obj_type_t *type, size_t n_args, + size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_buffer, ARG_width, ARG_height, ARG_native_rgb565, ARG_rgb332 }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_buffer, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_width, MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_height, MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_native_rgb565, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, + { MP_QSTR_rgb332, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + mp_int_t width = mp_arg_validate_int_range(args[ARG_width].u_int, 1, 4096, MP_QSTR_width); + mp_int_t height = mp_arg_validate_int_range(args[ARG_height].u_int, 1, 4096, MP_QSTR_height); + if (args[ARG_native_rgb565].u_bool && args[ARG_rgb332].u_bool) { + mp_arg_error_invalid(MP_QSTR_format); // native_rgb565 and rgb332 are exclusive + } + bool rgb332 = args[ARG_rgb332].u_bool; + + mp_buffer_info_t bi; + mp_get_buffer_raise(args[ARG_buffer].u_obj, &bi, MP_BUFFER_WRITE); + uint64_t need = (uint64_t)width * (uint64_t)height * (rgb332 ? 1u : 2u); + if ((uint64_t)bi.len < need) { + mp_raise_ValueError(MP_ERROR_TEXT("buffer too small")); + } + + picogame_framebuffer_obj_t *self = mp_obj_malloc(picogame_framebuffer_obj_t, type); + self->buffer = args[ARG_buffer].u_obj; + self->fb = (uint16_t *)bi.buf; + self->width = width; + self->height = height; + self->fmt = rgb332 ? PICOGAME_FB_RGB332 + : (args[ARG_native_rgb565].u_bool ? PICOGAME_FB_NATIVE565 : PICOGAME_FB_WIRE565); + // A LIVE scanout buffer (picodvi/HDMI) is read continuously, so picogame_render_framebuffer + // composes each band into this PRIVATE strip and only memcpys the FINISHED band into the fb. + // That serves BOTH targets: (a) native -> also byte-swap the strip so the fb never holds wire + // (no pink); (b) wire -> no swap, but the off-screen compose still stops the beam from sampling + // a half-composited region (background filled, sprite not yet drawn) = no sprite/HUD flicker. + // Always allocated for the FB target; the WASM/sim path (read out after present, not live) just + // pays a small strip + one memcpy. See PICOGAME_FB_SCRATCH_H. + // + // The scratch must be FAST memory: on a PSRAM-heap board (Fruit Jam) a heap bytearray + // lands in external PSRAM and every compose write pays QSPI latency (measured 8.7 vs + // 64+ MB/s SRAM; a full-res StripDraw frame ballooned refresh to ~30-38 ms). One static + // SRAM strip serves every Framebuffer (compose is synchronous) up to 640 px wide; wider + // targets fall back to the heap. + self->scratch_buf = mp_const_none; + self->scratch = NULL; + self->scratch_rows = 0; + { + int rows = PICOGAME_FB_SCRATCH_H; + if (rows > height) { + rows = height; + } + if (width <= PICOGAME_FB_SCRATCH_MAX_W) { + self->scratch = picogame_fb_scratch_sram; + } else { + mp_obj_t sb = mp_obj_new_bytearray_of_zeros((size_t)width * (size_t)rows * 2u); + mp_buffer_info_t sbi; + mp_get_buffer_raise(sb, &sbi, MP_BUFFER_WRITE); + self->scratch_buf = sb; + self->scratch = (uint16_t *)sbi.buf; + } + self->scratch_rows = rows; + } + return MP_OBJ_FROM_PTR(self); +} + +static mp_obj_t picogame_framebuffer_get_width(mp_obj_t self_in) { + return MP_OBJ_NEW_SMALL_INT(((picogame_framebuffer_obj_t *)MP_OBJ_TO_PTR(self_in))->width); +} +static MP_DEFINE_CONST_FUN_OBJ_1(picogame_framebuffer_get_width_obj, picogame_framebuffer_get_width); +MP_PROPERTY_GETTER(picogame_framebuffer_width_obj, (mp_obj_t)&picogame_framebuffer_get_width_obj); + +static mp_obj_t picogame_framebuffer_get_height(mp_obj_t self_in) { + return MP_OBJ_NEW_SMALL_INT(((picogame_framebuffer_obj_t *)MP_OBJ_TO_PTR(self_in))->height); +} +static MP_DEFINE_CONST_FUN_OBJ_1(picogame_framebuffer_get_height_obj, picogame_framebuffer_get_height); +MP_PROPERTY_GETTER(picogame_framebuffer_height_obj, (mp_obj_t)&picogame_framebuffer_get_height_obj); + +static const mp_rom_map_elem_t picogame_framebuffer_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_width), MP_ROM_PTR(&picogame_framebuffer_width_obj) }, + { MP_ROM_QSTR(MP_QSTR_height), MP_ROM_PTR(&picogame_framebuffer_height_obj) }, +}; +static MP_DEFINE_CONST_DICT(picogame_framebuffer_locals_dict, picogame_framebuffer_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + picogame_framebuffer_type, + MP_QSTR_Framebuffer, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, picogame_framebuffer_make_new, + locals_dict, &picogame_framebuffer_locals_dict + ); +#endif // CIRCUITPY_PICOGAME_FRAMEBUFFER diff --git a/shared-bindings/picogame/Framebuffer.h b/shared-bindings/picogame/Framebuffer.h new file mode 100644 index 00000000000..99112b8fa03 --- /dev/null +++ b/shared-bindings/picogame/Framebuffer.h @@ -0,0 +1,11 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-module/picogame/__init__.h" // picogame_framebuffer_obj_t + +extern const mp_obj_type_t picogame_framebuffer_type; diff --git a/shared-bindings/picogame/Particles.c b/shared-bindings/picogame/Particles.c new file mode 100644 index 00000000000..dd7cf05fb8e --- /dev/null +++ b/shared-bindings/picogame/Particles.c @@ -0,0 +1,154 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +#include "py/runtime.h" +#include "shared-module/picogame/pg_compat.h" +#include "shared-bindings/picogame/Particles.h" +#include "shared-module/picogame/Particles.h" + +static void reset_dirty(picogame_particles_obj_t *self) { + // INT32 sentinels (not int16): bbox fields are int32 + positions 24.8, so a big-world emitter past + // +-32767 px must still accumulate. (Matches picogame_dirty_reset; update()/clear() use it too.) + self->cx1 = self->px1 = 0x7fffffff; + self->cy1 = self->py1 = 0x7fffffff; + self->cx2 = self->px2 = -0x7fffffff - 1; + self->cy2 = self->py2 = -0x7fffffff - 1; +} + +//| class Particles: +//| """A pooled particle layer (small moving dots), drawn as one Scene layer. +//| Add it to a Scene, ``emit()`` bursts, and call ``tick()`` each frame.""" +//| +//| def __init__( +//| self, +//| capacity: int, +//| *, +//| size: int = 1, +//| gravity: float = 0.0, +//| fade: bool = False, +//| fade_to: int = 0, +//| stretch: int = 0, +//| ) -> None: +//| """``capacity`` is how many particles may be alive at once; the pool is +//| allocated once here and never grows. If :py:meth:`emit` would exceed it, +//| the excess particles are dropped. +//| +//| ``size`` is the square side of one particle in pixels. ``gravity`` is added to +//| each particle's vertical speed every :py:meth:`tick`. ``fade=True`` dims +//| particles towards the end of their life instead of letting them vanish at full +//| brightness. ``fade_to`` is the colour (from :py:func:`rgb565`) the fade ends at; +//| the default black is the classic dim, a dark red turns white sparks into embers. +//| Giving ``fade_to`` turns ``fade`` on. +//| +//| ``stretch`` draws each particle ``stretch`` more times spread back along its +//| velocity, so a fast particle is a streak one tick long and a slow one stays a +//| dot. ``0`` (the default) draws dots; ``2``..``4`` reads as sparks.""" +//| ... +//| +static mp_obj_t picogame_particles_make_new(const mp_obj_type_t *type, size_t n_args, + size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_capacity, ARG_size, ARG_gravity, ARG_fade, ARG_fade_to, ARG_stretch }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_capacity, MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_size, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1} }, + { MP_QSTR_gravity, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, + { MP_QSTR_fade, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, + { MP_QSTR_fade_to, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_stretch, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + mp_int_t cap = mp_arg_validate_int_range(args[ARG_capacity].u_int, 1, 4096, MP_QSTR_capacity); + mp_int_t size = mp_arg_validate_int_range(args[ARG_size].u_int, 1, 8, MP_QSTR_size); + mp_float_t gravity = (args[ARG_gravity].u_obj == mp_const_none) + ? 0.0f : mp_obj_get_float(args[ARG_gravity].u_obj); + if (gravity > 127.99f) { // clamp to the int16 8.8 range: gravity*256 must fit + gravity = 127.99f; // [-32768, 32767]; |g|>=128 would flip the sign + } else if (gravity < -128.0f) { + gravity = -128.0f; + } + + picogame_particles_obj_t *self = mp_obj_malloc(picogame_particles_obj_t, type); + self->cap = cap; + self->count = 0; + self->size = size; + self->gravity = (int16_t)(gravity * 256); + self->fade_to = (uint16_t)mp_arg_validate_int_range(args[ARG_fade_to].u_int, 0, 0xFFFF, MP_QSTR_fade_to); + self->fade = args[ARG_fade].u_bool || self->fade_to != 0; + self->stretch = (uint8_t)mp_arg_validate_int_range(args[ARG_stretch].u_int, 0, 8, MP_QSTR_stretch); + // Pure numeric arrays, no Python pointers -> exempt from the conservative GC scan + // (shorter gc.collect() pauses; fixed at construction, never m_renew'd). + self->px = m_malloc_without_collect(cap * sizeof(int32_t)); + self->py = m_malloc_without_collect(cap * sizeof(int32_t)); + self->vx = m_malloc_without_collect(cap * sizeof(int16_t)); + self->vy = m_malloc_without_collect(cap * sizeof(int16_t)); + self->life = m_malloc_without_collect(cap * sizeof(uint16_t)); + self->life0 = m_malloc_without_collect(cap * sizeof(uint16_t)); + self->color = m_malloc_without_collect(cap * sizeof(uint16_t)); + reset_dirty(self); + return MP_OBJ_FROM_PTR(self); +} + +//| +//| def emit( +//| self, x: int, y: int, count: int, speed: int = 1, life: int = 30, color: int = 0xFFFF +//| ) -> None: +//| """Spawn ``count`` particles at ``(x, y)``, living ``life`` ticks, in +//| ``color`` (default white). Each particle's horizontal and vertical velocity is chosen +//| independently from ``-speed`` through ``speed`` pixels per tick.""" +//| ... +//| +static mp_obj_t picogame_particles_emit_fun(size_t n_args, const mp_obj_t *args) { + picogame_particles_obj_t *self = MP_OBJ_TO_PTR(args[0]); + int x = mp_obj_get_int(args[1]); + int y = mp_obj_get_int(args[2]); + int count = mp_arg_validate_int_min(mp_obj_get_int(args[3]), 0, MP_QSTR_count); + // speed*256 must fit the int16_t velocity (8.8) -> cap 127; life is stored as uint16_t. + int speed = (n_args > 4) ? mp_arg_validate_int_range(mp_obj_get_int(args[4]), 0, 127, MP_QSTR_speed) : 1; + int life = (n_args > 5) ? mp_arg_validate_int_range(mp_obj_get_int(args[5]), 1, 65535, MP_QSTR_life) : 30; + uint16_t color = (n_args > 6) + ? mp_arg_validate_int_range(mp_obj_get_int(args[6]), 0, 0xFFFF, MP_QSTR_color) : 0xFFFF; + picogame_particles_emit(self, x, y, count, speed, life, color); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(picogame_particles_emit_obj, 4, 7, picogame_particles_emit_fun); + +//| def tick(self) -> None: +//| """Advance all particles one step (movement, gravity, aging).""" +//| ... +//| +static mp_obj_t picogame_particles_tick(mp_obj_t self_in) { + picogame_particles_update(MP_OBJ_TO_PTR(self_in)); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(picogame_particles_tick_obj, picogame_particles_tick); + +//| def clear(self) -> None: +//| """Remove all particles.""" +//| ... +//| +//| +static mp_obj_t picogame_particles_clear_method(mp_obj_t self_in) { + picogame_particles_clear(MP_OBJ_TO_PTR(self_in)); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(picogame_particles_clear_obj, picogame_particles_clear_method); + +static const mp_rom_map_elem_t picogame_particles_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_emit), MP_ROM_PTR(&picogame_particles_emit_obj) }, + { MP_ROM_QSTR(MP_QSTR_tick), MP_ROM_PTR(&picogame_particles_tick_obj) }, + { MP_ROM_QSTR(MP_QSTR_clear), MP_ROM_PTR(&picogame_particles_clear_obj) }, +}; +static MP_DEFINE_CONST_DICT(picogame_particles_locals_dict, picogame_particles_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + picogame_particles_type, + MP_QSTR_Particles, + MP_TYPE_FLAG_NONE, + make_new, picogame_particles_make_new, + locals_dict, &picogame_particles_locals_dict + ); diff --git a/shared-bindings/picogame/Particles.h b/shared-bindings/picogame/Particles.h new file mode 100644 index 00000000000..8f8b37ab819 --- /dev/null +++ b/shared-bindings/picogame/Particles.h @@ -0,0 +1,11 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-module/picogame/Particles.h" + +extern const mp_obj_type_t picogame_particles_type; diff --git a/shared-bindings/picogame/Scene.c b/shared-bindings/picogame/Scene.c new file mode 100644 index 00000000000..772c3cd6cee --- /dev/null +++ b/shared-bindings/picogame/Scene.c @@ -0,0 +1,568 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +#include "py/runtime.h" +#include +#include "shared-module/picogame/pg_compat.h" +#include "py/objtuple.h" +#include "py/objlist.h" +#include "shared-bindings/picogame/Scene.h" +#include "shared-bindings/picogame/__init__.h" +#include "shared-bindings/picogame/Sprite.h" +#include "shared-bindings/picogame/Tilemap.h" +#include "shared-bindings/picogame/Particles.h" +#include "shared-bindings/picogame/Canvas.h" +#include "shared-bindings/picogame/Framebuffer.h" +#include "shared-bindings/busdisplay/BusDisplay.h" +#if CIRCUITPY_PICOGAME_FAST_DISPLAY +#include "shared-bindings/picogame/Display.h" +#endif +#include "shared-module/picogame/Scene.h" +#include "shared-module/picogame/__init__.h" +#include "shared-module/picogame/Tilemap.h" +#include "shared-module/picogame/Particles.h" +#include "shared-module/picogame/Canvas.h" +#if CIRCUITPY_PICOGAME_FAST_DISPLAY +#include "shared-module/picogame/Display.h" +#endif + +#define SCENE_INIT_CAP 8 +#define PICOGAME_MAX_DIRTY_RECTS 6 // separate regions repainted per refresh + +// Classify the `display` arg into a render backend and return the object Scene should +// store: a fast picogame.Display (DMA), a picogame.Framebuffer (RAM scanout buffer, when +// built in), or a plain busdisplay (portable bus.send). Sets *fast / *fb_target +// accordingly; for a busdisplay it accepts a SUBCLASS (e.g. adafruit_st7789.ST7789) by +// casting to its native base and returns that. Raises TypeError otherwise. This is where +// the flag-gated type checks live, so the constructor body stays clean. +static mp_obj_t scene_resolve_target(mp_obj_t disp, bool *fast, bool *fb_target) { + *fast = false; + *fb_target = false; + #if CIRCUITPY_PICOGAME_FAST_DISPLAY + { + // Accept subclasses too (same as the busdisplay path below): resolve to the + // native base object, which the C renderer can safely cast. + mp_obj_t ndisp = mp_obj_cast_to_native_base(disp, &picogame_display_type); + if (ndisp != MP_OBJ_NULL && mp_obj_is_type(ndisp, &picogame_display_type)) { + *fast = true; + return ndisp; + } + } + #endif + #if CIRCUITPY_PICOGAME_FRAMEBUFFER + { + mp_obj_t nfb = mp_obj_cast_to_native_base(disp, &picogame_framebuffer_type); + if (nfb != MP_OBJ_NULL && mp_obj_is_type(nfb, &picogame_framebuffer_type)) { + *fb_target = true; // refresh() composites dirty rects straight into its RAM buffer + return nfb; + } + } + #endif + // Plain busdisplay: accept a subclass by casting to its native base; the portable + // renderer treats self->display as a busdisplay_busdisplay_obj_t directly. + mp_obj_t native = mp_obj_cast_to_native_base(disp, &busdisplay_busdisplay_type); + // MP_OBJ_NULL for a non-BusDisplay: validate the ORIGINAL object (NULL's type is unreadable). + if (native == MP_OBJ_NULL || !mp_obj_is_type(native, &busdisplay_busdisplay_type)) { + mp_arg_validate_type(disp, &busdisplay_busdisplay_type, MP_QSTR_display); + } + return native; +} + +//| class Scene: +//| """A retained-mode scene with dirty-rectangle rendering for a `Display`, +//| :py:class:`~busdisplay.BusDisplay` or `Framebuffer` target. Add layers once +//| (insertion order is bottom to top), mutate them each frame, then call +//| :py:meth:`refresh`; only the regions reported changed are repainted.""" +//| +//| def __init__( +//| self, +//| display: Union[Display, busdisplay.BusDisplay, Framebuffer], +//| buffer_a: Optional[WriteableBuffer] = None, +//| buffer_b: Optional[WriteableBuffer] = None, +//| *, +//| background: int = 0, +//| top: int = 0, +//| bottom: int = 0, +//| left: int = 0, +//| right: int = 0, +//| ) -> None: +//| """:param display: the render target +//| :param ~circuitpython_typing.WriteableBuffer buffer_a: a strip buffer, +//| typically ``display.width * STRIP_H * 2`` bytes. Its size sets the +//| strip height: each strip is ``size // (display.width * 2)`` rows. Two +//| buffers let the next strip be composited while the previous one is +//| being sent. On a `Framebuffer` target there are no strips and the +//| buffers are unused; both default to `None`. +//| :param ~circuitpython_typing.WriteableBuffer buffer_b: the second strip +//| buffer, sized like ``buffer_a`` +//| :param int background: color that exposed areas are cleared to +//| :param int top: rows at the top edge the scene never renders into +//| :param int bottom: rows at the bottom edge the scene never renders into +//| :param int left: columns at the left edge the scene never renders into +//| :param int right: columns at the right edge the scene never renders into +//| +//| The four border insets reserve screen edges for content the application +//| draws itself, for example with :py:func:`render`; the scene renders only +//| the inner rectangle and never repaints the border.""" +//| ... +//| +static mp_obj_t picogame_scene_make_new(const mp_obj_type_t *type, size_t n_args, + size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_display, ARG_buffer_a, ARG_buffer_b, ARG_background, + ARG_top, ARG_bottom, ARG_left, ARG_right }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_display, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_buffer_a, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} }, + { MP_QSTR_buffer_b, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} }, + { MP_QSTR_background, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0} }, + { MP_QSTR_top, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0} }, // reserved border insets: + { MP_QSTR_bottom, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0} }, // the scene renders only the + { MP_QSTR_left, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0} }, // inner play rect; the app + { MP_QSTR_right, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0} }, // owns the border around it + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + // Resolve the render backend (fast Display / Framebuffer / busdisplay) - all the + // flag-gated type checks are concentrated in scene_resolve_target(). + bool fast, fb_target; + mp_obj_t disp = scene_resolve_target(args[ARG_display].u_obj, &fast, &fb_target); + + // The framebuffer path composites directly into the target, so it needs no strip + // buffers; the SPI/DMA paths do. Validate them only when they'll be used. (When + // CIRCUITPY_PICOGAME_FRAMEBUFFER is off, fb_target is always false -> always validated, + // as before.) + if (!fb_target) { + mp_buffer_info_t tmp; + mp_get_buffer_raise(args[ARG_buffer_a].u_obj, &tmp, MP_BUFFER_WRITE); + mp_get_buffer_raise(args[ARG_buffer_b].u_obj, &tmp, MP_BUFFER_WRITE); + } + + picogame_scene_obj_t *self = mp_obj_malloc(picogame_scene_obj_t, type); + self->display = disp; + self->fast = fast; + #if CIRCUITPY_PICOGAME_FRAMEBUFFER + self->fb_target = fb_target; + #endif + self->buf_a = args[ARG_buffer_a].u_obj; + self->buf_b = args[ARG_buffer_b].u_obj; + self->background = args[ARG_background].u_int; + self->count = 0; + self->cap = SCENE_INIT_CAP; + self->items = m_new(mp_obj_t, SCENE_INIT_CAP); + self->kinds = m_new(uint8_t, SCENE_INIT_CAP); + self->snap = m_new(picogame_snapshot_t, SCENE_INIT_CAP); + self->cleared = false; + self->ox = 0; + self->oy = 0; + self->top = args[ARG_top].u_int; + self->bottom = args[ARG_bottom].u_int; + self->left = args[ARG_left].u_int; + self->right = args[ARG_right].u_int; + mp_obj_t zeros[4] = { + MP_OBJ_NEW_SMALL_INT(0), MP_OBJ_NEW_SMALL_INT(0), + MP_OBJ_NEW_SMALL_INT(0), MP_OBJ_NEW_SMALL_INT(0), + }; + self->dirty_rect = mp_obj_new_list(4, zeros); // reused every refresh + return MP_OBJ_FROM_PTR(self); +} + +// On a full repaint, sync sprite snapshots to current and drain the layer +// dirties (tilemap/particles/canvas) so they don't re-report a stale region. +static void snapshot_sync(picogame_scene_obj_t *self) { + int a, b, c, d; + for (uint16_t i = 0; i < self->count; i++) { + uint8_t kind = self->kinds[i] & PICOGAME_KIND_MASK; + if (kind == PICOGAME_KIND_TILEMAP) { + picogame_tilemap_take_dirty(MP_OBJ_TO_PTR(self->items[i]), &a, &b, &c, &d); + } else if (kind == PICOGAME_KIND_PARTICLES) { + picogame_particles_take_dirty(MP_OBJ_TO_PTR(self->items[i]), &a, &b, &c, &d); + } else if (kind == PICOGAME_KIND_CANVAS) { + picogame_canvas_take_dirty(MP_OBJ_TO_PTR(self->items[i]), &a, &b, &c, &d); + } else if (kind == PICOGAME_KIND_STRIPDRAW) { + // Immediate-mode layer: no retained state to snapshot/drain. + } else if (kind == PICOGAME_KIND_TRIANGLES) { + // Screen-space batch: drain the count-set dirty so it doesn't re-report. + int e, f, g, hh; + picogame_dirty_take(&((picogame_triangles_obj_t *)MP_OBJ_TO_PTR(self->items[i]))->dx1, + &e, &f, &g, &hh); + } else { + picogame_sprite_obj_t *s = MP_OBJ_TO_PTR(self->items[i]); + picogame_bitmap_obj_t *bm = s->bitmap; + int ax1, ay1, ax2, ay2; + picogame_sprite_aabb(s, &ax1, &ay1, &ax2, &ay2); + self->snap[i].x = ax1; + self->snap[i].y = ay1; + self->snap[i].w = ax2 - ax1; + self->snap[i].h = ay2 - ay1; + self->snap[i].bitmap = (void *)bm; + self->snap[i].frame = s->frame; + self->snap[i].flags = s->flags; + self->snap[i].scale = s->scale; + self->snap[i].angle = s->angle; + self->snap[i].seq = s->seq; + self->snap[i].dither = s->dither; + self->snap[i].flash_color = s->flash_color; + } + } +} + +//| +//| def add( +//| self, item: Union[Sprite, Tilemap, Canvas, Particles, StripDraw, Triangles], *, fixed: bool = False +//| ) -> Union[Sprite, Tilemap, Canvas, Particles, StripDraw, Triangles]: +//| """Add a layer of any kind, drawn starting with the next refresh; insertion +//| order is bottom to top. Returns the added item. +//| +//| ``fixed=True`` pins the item to the screen so it ignores the view offset +//| set by :py:meth:`set_view`, for example for a HUD over a scrolling world. +//| `StripDraw` and `Triangles` layers always draw in screen coordinates and +//| are unaffected by both ``fixed`` and the view offset.""" +//| ... +//| +static void scene_add_one(picogame_scene_obj_t *self, mp_obj_t item_in, bool fixed) { + uint8_t kind; + kind = picogame_kind_of(item_in); + if (fixed) { + kind |= PICOGAME_KIND_FIXED; + } + if (self->count >= self->cap) { + if (self->cap >= 0x8000) { // next doubling overflows uint16_t -> m_renew(0) shrink + m_malloc_fail((size_t)self->cap * 2); // next doubling overflows the count type + } + uint16_t new_cap = self->cap * 2; + self->items = m_renew(mp_obj_t, self->items, self->cap, new_cap); + self->kinds = m_renew(uint8_t, self->kinds, self->cap, new_cap); + self->snap = m_renew(picogame_snapshot_t, self->snap, self->cap, new_cap); + self->cap = new_cap; + } + self->items[self->count] = item_in; + self->kinds[self->count] = kind; + // Snapshot starts all-zero ("invisible", nothing diffed against garbage - m_renew doesn't + // zero), so a newly added layer is detected as changed and drawn on the next refresh. + memset(&self->snap[self->count], 0, sizeof(picogame_snapshot_t)); + self->count++; + // Honour "drawn on the next refresh" for EVERY kind: the zeroed snapshot covers sprites, + // but a re-add()ed Canvas/Tilemap whose dirty flag was already consumed would otherwise + // stay invisible until some other change. add() is a cold path -> force a full repaint. + self->cleared = false; +} + +static mp_obj_t picogame_scene_add(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_item, ARG_fixed }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_item, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_fixed, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, + }; + 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); + scene_add_one(MP_OBJ_TO_PTR(pos_args[0]), args[ARG_item].u_obj, args[ARG_fixed].u_bool); + return args[ARG_item].u_obj; // constructive: return the added item for `x = scene.add(...)` +} +static MP_DEFINE_CONST_FUN_OBJ_KW(picogame_scene_add_obj, 2, picogame_scene_add); + +//| def add_all(self, items: Iterable[Union[Sprite, Tilemap, Canvas, Particles, StripDraw, Triangles]]) -> None: +//| """Add several layers at once, bottom to top in iteration order.""" +//| ... +//| +static mp_obj_t picogame_scene_add_all(mp_obj_t self_in, mp_obj_t iterable) { + picogame_scene_obj_t *self = MP_OBJ_TO_PTR(self_in); + mp_obj_t iter = mp_getiter(iterable, NULL); + mp_obj_t item; + while ((item = mp_iternext(iter)) != MP_OBJ_STOP_ITERATION) { + scene_add_one(self, item, false); + } + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(picogame_scene_add_all_obj, picogame_scene_add_all); + +//| def remove(self, item: Union[Sprite, Tilemap, Canvas, Particles, StripDraw, Triangles]) -> None: +//| """Remove a previously added item; the draw order of the rest is unchanged. +//| The next refresh repaints the scene, so the item leaves no ghost. The item +//| itself is untouched and may be added again later. Raises +//| :py:class:`ValueError` if the item is not in the scene.""" +//| ... +//| +static mp_obj_t picogame_scene_remove(mp_obj_t self_in, mp_obj_t item_in) { + picogame_scene_obj_t *self = MP_OBJ_TO_PTR(self_in); + for (uint16_t i = 0; i < self->count; i++) { + if (self->items[i] != item_in) { + continue; + } + self->count--; + for (uint16_t j = i; j < self->count; j++) { // keep draw order: shift the tail down + self->items[j] = self->items[j + 1]; + self->kinds[j] = self->kinds[j + 1]; + self->snap[j] = self->snap[j + 1]; + } + self->items[self->count] = mp_const_none; // release the GC reference + self->cleared = false; // full repaint next refresh: background covers where it was + return mp_const_none; + } + mp_arg_error_invalid(MP_QSTR_item); +} +static MP_DEFINE_CONST_FUN_OBJ_2(picogame_scene_remove_obj, picogame_scene_remove); + +//| def invalidate(self) -> None: +//| """Force the scene's whole render area to repaint on the next refresh.""" +//| ... +//| +static mp_obj_t picogame_scene_invalidate(mp_obj_t self_in) { + ((picogame_scene_obj_t *)MP_OBJ_TO_PTR(self_in))->cleared = false; + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(picogame_scene_invalidate_obj, picogame_scene_invalidate); + +//| def set_view(self, ox: int, oy: int) -> None: +//| """Set the screen position ``(ox, oy)`` of scene coordinate ``(0, 0)``: +//| a scene point ``(x, y)`` is drawn at ``(x + ox, y + oy)``. Use a constant +//| offset to center a small scene, or update it each frame to scroll, which +//| repaints the whole render area.""" +//| ... +//| +static mp_obj_t picogame_scene_set_view(mp_obj_t self_in, mp_obj_t ox_in, mp_obj_t oy_in) { + picogame_scene_obj_t *self = MP_OBJ_TO_PTR(self_in); + int ox = mp_obj_get_int(ox_in); + int oy = mp_obj_get_int(oy_in); + if (ox != self->ox || oy != self->oy) { + self->ox = ox; + self->oy = oy; + self->cleared = false; // the whole view shifted -> full repaint next refresh + } + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_3(picogame_scene_set_view_obj, picogame_scene_set_view); + +//| view: Tuple[int, int] +//| """The current view offset ``(ox, oy)`` as set by :py:meth:`set_view`. (read-only)""" +static mp_obj_t picogame_scene_get_view(mp_obj_t self_in) { + picogame_scene_obj_t *self = MP_OBJ_TO_PTR(self_in); + mp_obj_t t[2] = { MP_OBJ_NEW_SMALL_INT(self->ox), MP_OBJ_NEW_SMALL_INT(self->oy) }; + return mp_obj_new_tuple(2, t); +} +static MP_DEFINE_CONST_FUN_OBJ_1(picogame_scene_get_view_obj, picogame_scene_get_view); +MP_PROPERTY_GETTER(picogame_scene_view_obj, (mp_obj_t)&picogame_scene_get_view_obj); + +//| display: Union[Display, busdisplay.BusDisplay, Framebuffer] +//| """The render target this Scene was built with. (read-only)""" +//| +static mp_obj_t picogame_scene_get_display(mp_obj_t self_in) { + return ((picogame_scene_obj_t *)MP_OBJ_TO_PTR(self_in))->display; +} +static MP_DEFINE_CONST_FUN_OBJ_1(picogame_scene_get_display_obj, picogame_scene_get_display); +MP_PROPERTY_GETTER(picogame_scene_display_obj, (mp_obj_t)&picogame_scene_get_display_obj); + +// Compute the frame's dirty rectangles for a WxH target, clipped to the play rect +// [left, w-right) x [top, h-bottom). On the first refresh (or after invalidate) this is +// a single full-screen rect + a snapshot sync; afterwards it diffs against the previous +// frame. Returns the rect count written to `rects` (0 = nothing to repaint). +// Backend-agnostic, so the SPI/fast and framebuffer paths share the exact dirty logic. +static int scene_collect_dirty_rects(picogame_scene_obj_t *self, int w, int h, picogame_rect_t *rects) { + int nr; + if (self->cleared) { + nr = picogame_scene_compute_dirty_rects(self->items, self->kinds, self->snap, + self->count, w, h, self->ox, self->oy, rects, PICOGAME_MAX_DIRTY_RECTS); + if (nr == 0) { + return 0; + } + } else { + rects[0].x1 = 0; + rects[0].y1 = 0; + rects[0].x2 = w; + rects[0].y2 = h; + nr = 1; + snapshot_sync(self); + // NOTE: cleared flips to true only after the RENDER completes (see the callers) - + // the snapshots are already advanced here, so an exception mid-render would + // otherwise leave a partially painted frame that no later refresh repairs. + } + + // Clip every dirty rect to the play rect [left, w-right) x [top, h-bottom); the + // reserved border is the app's, so the scene never paints into it. Drop empty rects. + int pa_x1 = self->left; + int pa_x2 = w - self->right; + int pa_y1 = self->top; + int pa_y2 = h - self->bottom; + int kept = 0; + for (int i = 0; i < nr; i++) { + int rx1 = rects[i].x1 < pa_x1 ? pa_x1 : rects[i].x1; + int rx2 = rects[i].x2 > pa_x2 ? pa_x2 : rects[i].x2; + int ry1 = rects[i].y1 < pa_y1 ? pa_y1 : rects[i].y1; + int ry2 = rects[i].y2 > pa_y2 ? pa_y2 : rects[i].y2; + if (rx1 >= rx2 || ry1 >= ry2) { + continue; + } + rects[kept].x1 = rx1; + rects[kept].y1 = ry1; + rects[kept].x2 = rx2; + rects[kept].y2 = ry2; + kept++; + } + return kept; +} + +// Store the bounding union of `nr` rects into the reusable dirty_rect list (no per-frame +// tuple allocation) and return it. Shared by both refresh backends. +static mp_obj_t scene_store_dirty(picogame_scene_obj_t *self, const picogame_rect_t *rects, int nr, int w, int h) { + int ux1 = w, uy1 = h, ux2 = 0, uy2 = 0; + for (int i = 0; i < nr; i++) { + if (rects[i].x1 < ux1) { + ux1 = rects[i].x1; + } + if (rects[i].y1 < uy1) { + uy1 = rects[i].y1; + } + if (rects[i].x2 > ux2) { + ux2 = rects[i].x2; + } + if (rects[i].y2 > uy2) { + uy2 = rects[i].y2; + } + } + mp_obj_list_store(self->dirty_rect, MP_OBJ_NEW_SMALL_INT(0), MP_OBJ_NEW_SMALL_INT(ux1)); + mp_obj_list_store(self->dirty_rect, MP_OBJ_NEW_SMALL_INT(1), MP_OBJ_NEW_SMALL_INT(uy1)); + mp_obj_list_store(self->dirty_rect, MP_OBJ_NEW_SMALL_INT(2), MP_OBJ_NEW_SMALL_INT(ux2)); + mp_obj_list_store(self->dirty_rect, MP_OBJ_NEW_SMALL_INT(3), MP_OBJ_NEW_SMALL_INT(uy2)); + return self->dirty_rect; +} + +#if CIRCUITPY_PICOGAME_FRAMEBUFFER +// Retained-mode refresh against a RAM framebuffer target (scanout-buffer platforms: +// WASM playground, desktop sim, FruitJam DVI/HSTX). Same dirty-rect logic as the SPI +// path (via the shared helpers), but each rect is composited straight into the target +// with picogame_render_framebuffer - no strip buffers, no bus transaction. A latched +// StripDraw BaseException is re-raised (no bus to close). Self-contained here so +// picogame_scene_refresh() keeps its original SPI/fast shape. +static mp_obj_t scene_refresh_fb(picogame_scene_obj_t *self) { + picogame_framebuffer_obj_t *fbt = MP_OBJ_TO_PTR(self->display); + int w = fbt->width; + int h = fbt->height; + + // Emulated invert (pg.invert on a Framebuffer) just toggled -> recomposite the WHOLE frame so the + // negative flip covers the whole screen, not only this frame's dirty rects (like a panel INVON). + if (picogame_fb_take_invert_dirty()) { + self->cleared = false; + } + + picogame_rect_t rects[PICOGAME_MAX_DIRTY_RECTS]; + int nr = scene_collect_dirty_rects(self, w, h, rects); + if (nr == 0) { + return mp_const_none; + } + + // Snapshots are already advanced; stay in the needs-full-repaint state until the + // render completes, so a BaseException mid-render (Ctrl-C in a StripDraw) leaves a + // scene whose NEXT refresh repaints everything instead of keeping a torn frame. + self->cleared = false; + for (int i = 0; i < nr; i++) { + mp_obj_t exc = picogame_render_framebuffer(fbt->fb, fbt->width, fbt->height, fbt->fmt, + fbt->scratch, fbt->scratch_rows, + self->items, self->kinds, self->count, + rects[i].x1, rects[i].y1, rects[i].x2, rects[i].y2, + self->background, self->ox, self->oy); + if (exc != MP_OBJ_NULL) { + nlr_raise(MP_OBJ_TO_PTR(exc)); // cleared stays false -> full repaint next refresh + } + } + self->cleared = true; + return scene_store_dirty(self, rects, nr, w, h); +} +#endif // CIRCUITPY_PICOGAME_FRAMEBUFFER + +//| def refresh(self) -> Optional[list]: +//| """Repaint the regions changed by the scene's layers since the previous +//| refresh. Returns the bounding dirty rectangle as a list +//| ``[x1, y1, x2, y2]`` with exclusive ``x2``/``y2``, or `None` if nothing +//| changed. The returned list object is reused: read it before the next +//| ``refresh()`` call.""" +//| ... +//| +//| +static mp_obj_t picogame_scene_refresh(mp_obj_t self_in) { + picogame_scene_obj_t *self = MP_OBJ_TO_PTR(self_in); + + #if CIRCUITPY_PICOGAME_FRAMEBUFFER + if (self->fb_target) { + return scene_refresh_fb(self); + } + #endif + + // Resolve the underlying busdisplay from either backend. + busdisplay_busdisplay_obj_t *bd; + #if CIRCUITPY_PICOGAME_FAST_DISPLAY + picogame_display_obj_t *disp = NULL; + if (self->fast) { + disp = MP_OBJ_TO_PTR(self->display); + bd = disp->display; + } else + #endif + { + bd = MP_OBJ_TO_PTR(self->display); + } + int w = bd->core.width; + int h = bd->core.height; + + picogame_rect_t rects[PICOGAME_MAX_DIRTY_RECTS]; + int nr = scene_collect_dirty_rects(self, w, h, rects); + if (nr == 0) { + return mp_const_none; + } + + mp_buffer_info_t a, b; + mp_get_buffer_raise(self->buf_a, &a, MP_BUFFER_WRITE); + mp_get_buffer_raise(self->buf_b, &b, MP_BUFFER_WRITE); + #if CIRCUITPY_PICOGAME_FAST_DISPLAY + size_t buf_pixels = (a.len < b.len ? a.len : b.len) / 2; // fast path double-buffers + #endif + + // Render each dirty rect independently; return their bounding union (kept for + // the existing "dirty WxH" debug prints). + // Snapshots are already advanced; stay in the needs-full-repaint state until the + // render completes, so a BaseException mid-render (Ctrl-C in a StripDraw) leaves a + // scene whose NEXT refresh repaints everything instead of keeping a torn frame. + self->cleared = false; + for (int i = 0; i < nr; i++) { + #if CIRCUITPY_PICOGAME_FAST_DISPLAY + if (self->fast) { + common_hal_picogame_display_render(disp, self->items, self->kinds, self->count, + (uint16_t *)a.buf, (uint16_t *)b.buf, buf_pixels, + rects[i].x1, rects[i].y1, rects[i].x2, rects[i].y2, + self->background, self->ox, self->oy); + } else + #endif + { + // Portable single-buffer bus.send path (any CircuitPython port). + picogame_render_region(bd, self->items, self->kinds, self->count, + (uint16_t *)a.buf, a.len / 2, + rects[i].x1, rects[i].y1, rects[i].x2, rects[i].y2, + self->background, self->ox, self->oy); + } + } + self->cleared = true; + + return scene_store_dirty(self, rects, nr, w, h); +} +static MP_DEFINE_CONST_FUN_OBJ_1(picogame_scene_refresh_obj, picogame_scene_refresh); + +static const mp_rom_map_elem_t picogame_scene_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_add), MP_ROM_PTR(&picogame_scene_add_obj) }, + { MP_ROM_QSTR(MP_QSTR_add_all), MP_ROM_PTR(&picogame_scene_add_all_obj) }, + { MP_ROM_QSTR(MP_QSTR_remove), MP_ROM_PTR(&picogame_scene_remove_obj) }, + { MP_ROM_QSTR(MP_QSTR_refresh), MP_ROM_PTR(&picogame_scene_refresh_obj) }, + { MP_ROM_QSTR(MP_QSTR_invalidate), MP_ROM_PTR(&picogame_scene_invalidate_obj) }, + { MP_ROM_QSTR(MP_QSTR_set_view), MP_ROM_PTR(&picogame_scene_set_view_obj) }, + { MP_ROM_QSTR(MP_QSTR_view), MP_ROM_PTR(&picogame_scene_view_obj) }, + { MP_ROM_QSTR(MP_QSTR_display), MP_ROM_PTR(&picogame_scene_display_obj) }, +}; +static MP_DEFINE_CONST_DICT(picogame_scene_locals_dict, picogame_scene_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + picogame_scene_type, + MP_QSTR_Scene, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, picogame_scene_make_new, + locals_dict, &picogame_scene_locals_dict + ); diff --git a/shared-bindings/picogame/Scene.h b/shared-bindings/picogame/Scene.h new file mode 100644 index 00000000000..733968b06ca --- /dev/null +++ b/shared-bindings/picogame/Scene.h @@ -0,0 +1,11 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-module/picogame/Scene.h" + +extern const mp_obj_type_t picogame_scene_type; diff --git a/shared-bindings/picogame/Sprite.c b/shared-bindings/picogame/Sprite.c new file mode 100644 index 00000000000..07e1b5b7e4e --- /dev/null +++ b/shared-bindings/picogame/Sprite.c @@ -0,0 +1,641 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT +// +// picogame.Sprite: a positioned, animatable instance of a Bitmap. + +#include "py/runtime.h" +#include "shared-module/picogame/pg_compat.h" +#include "shared-bindings/busdisplay/BusDisplay.h" +#include "shared-bindings/picogame/__init__.h" +#include "shared-bindings/picogame/Bitmap.h" +#include "shared-bindings/picogame/Sprite.h" +#if CIRCUITPY_PICOGAME_FAST_DISPLAY +#include "shared-bindings/picogame/Display.h" // fast DMA backend; absent on portable ports +#include "shared-module/picogame/Display.h" // its struct (pg_get_display unwraps the wrapper) +#endif +#include "shared-bindings/picogame/Scene.h" +#include "shared-bindings/picogame/Tilemap.h" +#include "shared-bindings/picogame/Particles.h" +#include "shared-bindings/picogame/Canvas.h" +#include "shared-bindings/picogame/Framebuffer.h" +#include "shared-module/picogame/__init__.h" +#include "shared-module/picogame/Bitmap.h" +#include "shared-module/picogame/Sprite.h" + +// --------------------------------------------------------------------------- +// Sprite +// --------------------------------------------------------------------------- + +// Int pixel/scale -> 24.8 fixed-point. Shift through unsigned so a wild coordinate (e.g. 100_000_000, +// in 32-bit mp_int range but not after <<8) wraps modularly instead of hitting signed-overflow UB. +// Costs nothing over a plain shift; for any real on-screen coordinate the result is identical. +static int32_t pg_int_to_fp8(mp_int_t v) { + return (int32_t)((uint32_t)v << 8); +} + +//| class Sprite: +//| """A positioned, animatable instance of a :py:class:`Bitmap`.""" +//| +//| def __init__( +//| self, +//| bitmap: Bitmap, +//| x: int = 0, +//| y: int = 0, +//| *, +//| frame: int = 0, +//| visible: bool = True, +//| flip_x: bool = False, +//| flip_y: bool = False, +//| ) -> None: +//| """Place ``bitmap`` with its top-left corner at ``(x, y)`` in scene +//| coordinates, showing the frame selected by ``frame``. Scene coordinates +//| follow the view offset, so the sprite moves with a scrolling world. +//| +//| ``visible=False`` creates the sprite without drawing it, for example to +//| pre-allocate a pool of sprites up front. ``flip_x`` and ``flip_y`` mirror +//| the frame at draw time.""" +//| ... +//| +static mp_obj_t picogame_sprite_make_new(const mp_obj_type_t *type, size_t n_args, + size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_bitmap, ARG_x, ARG_y, ARG_frame, ARG_visible, ARG_flip_x, ARG_flip_y }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_bitmap, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_x, MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_y, MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_frame, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_visible, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = true} }, + { MP_QSTR_flip_x, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, + { MP_QSTR_flip_y, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + mp_obj_t bitmap_obj = mp_arg_validate_type(args[ARG_bitmap].u_obj, &picogame_bitmap_type, MP_QSTR_bitmap); + + picogame_sprite_obj_t *self = mp_obj_malloc(picogame_sprite_obj_t, type); + self->bitmap = MP_OBJ_TO_PTR(bitmap_obj); + self->x = pg_int_to_fp8(args[ARG_x].u_int); // pixel -> 24.8 fixed-point (overflow-clamped) + self->y = pg_int_to_fp8(args[ARG_y].u_int); + self->frame = args[ARG_frame].u_int; + self->flags = (args[ARG_visible].u_bool ? PICOGAME_SPR_VISIBLE : 0) + | (args[ARG_flip_x].u_bool ? PICOGAME_SPR_FLIP_X : 0) + | (args[ARG_flip_y].u_bool ? PICOGAME_SPR_FLIP_Y : 0); + self->anchor_x = 0; // default pivot = top-left (0, 0) + self->anchor_y = 0; + self->scale = 256; // 8.8 fixed-point: 256 = 1.0x (no scaling) + self->angle = 0; // no rotation -> axis-aligned fast path + self->flash_color = 0; + self->dither = 0; + self->data = mp_const_none; + self->seq = 0; // dirty-rect change counter (mp_obj_malloc zeroes anyway; explicit) + return MP_OBJ_FROM_PTR(self); +} + +static void set_flag(picogame_sprite_obj_t *self, uint16_t flag, bool on) { + if (on) { + self->flags |= flag; + } else { + self->flags &= ~flag; + } +} + +// shadow / flash / dither are mutually exclusive (one blit effect at a time); setting one ON +// clears the others, so "the last effect you set wins". Turning one OFF clears ONLY its own flag, +// so clearing an effect you never enabled (e.g. spr.flash = 0) can't wipe a different active one. +#define PICOGAME_SPR_FX_MASK (PICOGAME_SPR_SHADOW | PICOGAME_SPR_FLASH | PICOGAME_SPR_DITHER | PICOGAME_SPR_TINT | PICOGAME_SPR_ADD) +static void set_effect(picogame_sprite_obj_t *self, uint16_t flag, bool on) { + if (on) { + self->flags = (uint16_t)((self->flags & ~PICOGAME_SPR_FX_MASK) | flag); + } else { + self->flags &= (uint16_t) ~flag; + } +} + +// Round a float to 24.8 fixed-point (shared by the position/scale/anchor setters so the soft-float +// round sequence is emitted once, not per call site). +static int32_t pg_round_fp8(mp_float_t f) { + return (int32_t)(f * 256 + (f >= 0 ? (mp_float_t)0.5 : (mp_float_t)-0.5)); +} + + +// Accept an int or float and store as 24.8 fixed-point (rounded). Integer fast path avoids +// software float on RP2040 - game code sets x/y (via move/setters) every frame, usually with ints. +static int32_t obj_to_fp(mp_obj_t o) { + if (mp_obj_is_int(o)) { + return pg_int_to_fp8(mp_obj_get_int(o)); + } + mp_float_t f = mp_obj_get_float(o); + return pg_round_fp8(f); +} + +//| +//| frame: int +//| """Which frame of the bitmap's atlas to draw, starting at 0. Stepping this +//| animates the sprite.""" +//| visible: bool +//| """`False` hides the sprite. It stays in the scene and the area under it +//| repaints.""" +//| flip_x: bool +//| """Mirror the frame horizontally at draw time.""" +//| flip_y: bool +//| """Mirror the frame vertically at draw time.""" +//| x: int +//| """Horizontal pixel position in scene coordinates. Setting accepts a float +//| for sub-pixel placement; reading returns the floored pixel.""" +//| y: int +//| """Vertical pixel position in scene coordinates. Setting accepts a float +//| for sub-pixel placement; reading returns the floored pixel.""" +//| fx: float +//| """Horizontal sub-pixel position, for example ``sprite.fx += 2.4``.""" +//| fy: float +//| """Vertical sub-pixel position, for example ``sprite.fy += 2.4``.""" +// FLASH NOTE (property objects vs. a single `attr` handler): Sprite (and the other property-dense +// types) expose each attribute as its own getter/setter + MP_PROPERTY object below - the standard +// CircuitPython shared-bindings idiom (~423 such uses across CP). Collapsing these onto ONE `attr` +// load/store function per type (a qstr switch, like py/objcomplex.c's complex_attr for .real/.imag) +// would save ~3-4 KB of flash across the whole binding layer (Sprite alone ~1.5-2.5 KB). It is a +// valid MicroPython mechanism and would NOT break the .pyi stubs (those are generated from the //| +// comments, not the C property objects). We deliberately KEEP property objects: they are the +// idiomatic, most readable shared-bindings form and keep every type's definition uniform. Revisit +// only if flash becomes critical (then convert Sprite first - the densest cluster - not every type). +static mp_obj_t sprite_get_x(mp_obj_t self_in) { + return MP_OBJ_NEW_SMALL_INT(((picogame_sprite_obj_t *)MP_OBJ_TO_PTR(self_in))->x >> 8); +} +static MP_DEFINE_CONST_FUN_OBJ_1(sprite_get_x_obj, sprite_get_x); +static mp_obj_t sprite_set_x(mp_obj_t self_in, mp_obj_t v) { + ((picogame_sprite_obj_t *)MP_OBJ_TO_PTR(self_in))->x = obj_to_fp(v); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(sprite_set_x_obj, sprite_set_x); +MP_PROPERTY_GETSET(sprite_x_obj, (mp_obj_t)&sprite_get_x_obj, (mp_obj_t)&sprite_set_x_obj); + +static mp_obj_t sprite_get_y(mp_obj_t self_in) { + return MP_OBJ_NEW_SMALL_INT(((picogame_sprite_obj_t *)MP_OBJ_TO_PTR(self_in))->y >> 8); +} +static MP_DEFINE_CONST_FUN_OBJ_1(sprite_get_y_obj, sprite_get_y); +static mp_obj_t sprite_set_y(mp_obj_t self_in, mp_obj_t v) { + ((picogame_sprite_obj_t *)MP_OBJ_TO_PTR(self_in))->y = obj_to_fp(v); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(sprite_set_y_obj, sprite_set_y); +MP_PROPERTY_GETSET(sprite_y_obj, (mp_obj_t)&sprite_get_y_obj, (mp_obj_t)&sprite_set_y_obj); + +static mp_obj_t sprite_get_fx(mp_obj_t self_in) { + return mp_obj_new_float(((picogame_sprite_obj_t *)MP_OBJ_TO_PTR(self_in))->x * (mp_float_t)(1.0 / 256.0)); +} +static MP_DEFINE_CONST_FUN_OBJ_1(sprite_get_fx_obj, sprite_get_fx); +// set_fx is byte-identical to set_x (both store obj_to_fp(v) into ->x) -> reuse set_x's fun obj. +MP_PROPERTY_GETSET(sprite_fx_obj, (mp_obj_t)&sprite_get_fx_obj, (mp_obj_t)&sprite_set_x_obj); + +static mp_obj_t sprite_get_fy(mp_obj_t self_in) { + return mp_obj_new_float(((picogame_sprite_obj_t *)MP_OBJ_TO_PTR(self_in))->y * (mp_float_t)(1.0 / 256.0)); +} +static MP_DEFINE_CONST_FUN_OBJ_1(sprite_get_fy_obj, sprite_get_fy); +// set_fy is byte-identical to set_y -> reuse set_y's fun obj. +MP_PROPERTY_GETSET(sprite_fy_obj, (mp_obj_t)&sprite_get_fy_obj, (mp_obj_t)&sprite_set_y_obj); + +static mp_obj_t sprite_get_frame(mp_obj_t self_in) { + return MP_OBJ_NEW_SMALL_INT(((picogame_sprite_obj_t *)MP_OBJ_TO_PTR(self_in))->frame); +} +static MP_DEFINE_CONST_FUN_OBJ_1(sprite_get_frame_obj, sprite_get_frame); +static mp_obj_t sprite_set_frame(mp_obj_t self_in, mp_obj_t v) { + ((picogame_sprite_obj_t *)MP_OBJ_TO_PTR(self_in))->frame = mp_obj_get_int(v); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(sprite_set_frame_obj, sprite_set_frame); +MP_PROPERTY_GETSET(sprite_frame_obj, (mp_obj_t)&sprite_get_frame_obj, (mp_obj_t)&sprite_set_frame_obj); + +static mp_obj_t sprite_get_visible(mp_obj_t self_in) { + return mp_obj_new_bool((((picogame_sprite_obj_t *)MP_OBJ_TO_PTR(self_in))->flags & PICOGAME_SPR_VISIBLE) != 0); +} +static MP_DEFINE_CONST_FUN_OBJ_1(sprite_get_visible_obj, sprite_get_visible); +static mp_obj_t sprite_set_visible(mp_obj_t self_in, mp_obj_t v) { + set_flag(MP_OBJ_TO_PTR(self_in), PICOGAME_SPR_VISIBLE, mp_obj_is_true(v)); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(sprite_set_visible_obj, sprite_set_visible); +MP_PROPERTY_GETSET(sprite_visible_obj, (mp_obj_t)&sprite_get_visible_obj, (mp_obj_t)&sprite_set_visible_obj); + +static mp_obj_t sprite_get_flip_x(mp_obj_t self_in) { + return mp_obj_new_bool((((picogame_sprite_obj_t *)MP_OBJ_TO_PTR(self_in))->flags & PICOGAME_SPR_FLIP_X) != 0); +} +static MP_DEFINE_CONST_FUN_OBJ_1(sprite_get_flip_x_obj, sprite_get_flip_x); +static mp_obj_t sprite_set_flip_x(mp_obj_t self_in, mp_obj_t v) { + set_flag(MP_OBJ_TO_PTR(self_in), PICOGAME_SPR_FLIP_X, mp_obj_is_true(v)); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(sprite_set_flip_x_obj, sprite_set_flip_x); +MP_PROPERTY_GETSET(sprite_flip_x_obj, (mp_obj_t)&sprite_get_flip_x_obj, (mp_obj_t)&sprite_set_flip_x_obj); + +static mp_obj_t sprite_get_flip_y(mp_obj_t self_in) { + return mp_obj_new_bool((((picogame_sprite_obj_t *)MP_OBJ_TO_PTR(self_in))->flags & PICOGAME_SPR_FLIP_Y) != 0); +} +static MP_DEFINE_CONST_FUN_OBJ_1(sprite_get_flip_y_obj, sprite_get_flip_y); +static mp_obj_t sprite_set_flip_y(mp_obj_t self_in, mp_obj_t v) { + set_flag(MP_OBJ_TO_PTR(self_in), PICOGAME_SPR_FLIP_Y, mp_obj_is_true(v)); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(sprite_set_flip_y_obj, sprite_set_flip_y); +MP_PROPERTY_GETSET(sprite_flip_y_obj, (mp_obj_t)&sprite_get_flip_y_obj, (mp_obj_t)&sprite_set_flip_y_obj); + +//| scale: float +//| """Uniform draw scale using nearest-neighbor sampling. ``1.0`` is native size; +//| fractional values are allowed. The anchor point stays put.""" +static mp_obj_t sprite_get_scale(mp_obj_t self_in) { + return mp_obj_new_float(((picogame_sprite_obj_t *)MP_OBJ_TO_PTR(self_in))->scale * (mp_float_t)(1.0 / 256.0)); +} +static MP_DEFINE_CONST_FUN_OBJ_1(sprite_get_scale_obj, sprite_get_scale); +static mp_obj_t sprite_set_scale(mp_obj_t self_in, mp_obj_t v) { + int q; + if (mp_obj_is_int(v)) { // int fast path (no software float on RP2040) + q = pg_int_to_fp8(mp_obj_get_int(v)); // overflow-clamped <<8 + } else { + mp_float_t f = mp_obj_get_float(v); + q = pg_round_fp8(f); + } + if (q < 1) { + q = 1; + } + if (q > 65535) { + q = 65535; + } + picogame_sprite_obj_t *self = MP_OBJ_TO_PTR(self_in); + self->scale = (uint16_t)q; + self->xf_valid = 0; // affine cache depends on scale + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(sprite_set_scale_obj, sprite_set_scale); +MP_PROPERTY_GETSET(sprite_scale_obj, (mp_obj_t)&sprite_get_scale_obj, (mp_obj_t)&sprite_set_scale_obj); + +//| angle: float +//| """Rotation in degrees about the anchor; ``0`` is unrotated. Values are stored +//| as whole degrees. Rotation uses nearest-neighbor sampling.""" +static mp_obj_t sprite_get_angle(mp_obj_t self_in) { + return mp_obj_new_float((mp_float_t)((picogame_sprite_obj_t *)MP_OBJ_TO_PTR(self_in))->angle); +} +static MP_DEFINE_CONST_FUN_OBJ_1(sprite_get_angle_obj, sprite_get_angle); +static mp_obj_t sprite_set_angle(mp_obj_t self_in, mp_obj_t v) { + int a; + if (mp_obj_is_int(v)) { // int fast path (no software float on RP2040) + a = mp_obj_get_int(v); + } else { + mp_float_t f = mp_obj_get_float(v); + a = (int)(f + (f >= 0 ? (mp_float_t)0.5 : (mp_float_t)-0.5)); + } + a %= 360; + picogame_sprite_obj_t *self = MP_OBJ_TO_PTR(self_in); + self->angle = (int16_t)a; + self->xf_valid = 0; // affine cache depends on angle + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(sprite_set_angle_obj, sprite_set_angle); +MP_PROPERTY_GETSET(sprite_angle_obj, (mp_obj_t)&sprite_get_angle_obj, (mp_obj_t)&sprite_set_angle_obj); + +//| shadow: bool +//| """Draw opaque pixels by darkening the destination instead of writing color, +//| producing a shadow silhouette or a dimming overlay. Mutually exclusive with +//| `flash`, `dither` and `tint`.""" +static mp_obj_t sprite_get_shadow(mp_obj_t self_in) { + return mp_obj_new_bool((((picogame_sprite_obj_t *)MP_OBJ_TO_PTR(self_in))->flags & PICOGAME_SPR_SHADOW) != 0); +} +static MP_DEFINE_CONST_FUN_OBJ_1(sprite_get_shadow_obj, sprite_get_shadow); +static mp_obj_t sprite_set_shadow(mp_obj_t self_in, mp_obj_t v) { + set_effect(MP_OBJ_TO_PTR(self_in), PICOGAME_SPR_SHADOW, mp_obj_is_true(v)); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(sprite_set_shadow_obj, sprite_set_shadow); +MP_PROPERTY_GETSET(sprite_shadow_obj, (mp_obj_t)&sprite_get_shadow_obj, (mp_obj_t)&sprite_set_shadow_obj); + +//| flash: int +//| """Draw opaque pixels as one solid color instead of their own, for example as +//| a brief hit flash. Set to a color from :py:func:`rgb565` to enable, ``0`` to +//| disable. Because ``0`` disables the effect, pure black cannot be the flash +//| color; use a near-black color instead. Mutually exclusive with `shadow`, +//| `dither` and `tint`.""" +static mp_obj_t sprite_get_flash(mp_obj_t self_in) { + picogame_sprite_obj_t *s = MP_OBJ_TO_PTR(self_in); + return MP_OBJ_NEW_SMALL_INT((s->flags & PICOGAME_SPR_FLASH) ? s->flash_color : 0); +} +static MP_DEFINE_CONST_FUN_OBJ_1(sprite_get_flash_obj, sprite_get_flash); +static mp_obj_t sprite_set_flash(mp_obj_t self_in, mp_obj_t v) { + picogame_sprite_obj_t *s = MP_OBJ_TO_PTR(self_in); + // Falsy (None / False / 0) turns flash OFF. A non-zero colour enables it. (You can't flash + // pure black - use a near-black colour if you ever need that; off is the common case.) + if (!mp_obj_is_true(v)) { + set_effect(s, PICOGAME_SPR_FLASH, false); + } else { + s->flash_color = (uint16_t)mp_obj_get_int(v); + set_effect(s, PICOGAME_SPR_FLASH, true); + } + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(sprite_set_flash_obj, sprite_set_flash); +MP_PROPERTY_GETSET(sprite_flash_obj, (mp_obj_t)&sprite_get_flash_obj, (mp_obj_t)&sprite_set_flash_obj); + +//| dither: int +//| """Approximate transparency with an ordered (Bayer) dither pattern; there is +//| no alpha blending. ``0`` is opaque (off), ``8`` is about half transparent and +//| ``16`` is invisible. Mutually exclusive with `shadow`, `flash` and `tint`.""" +static mp_obj_t sprite_get_dither(mp_obj_t self_in) { + picogame_sprite_obj_t *s = MP_OBJ_TO_PTR(self_in); + return MP_OBJ_NEW_SMALL_INT((s->flags & PICOGAME_SPR_DITHER) ? s->dither : 0); +} +static MP_DEFINE_CONST_FUN_OBJ_1(sprite_get_dither_obj, sprite_get_dither); +static mp_obj_t sprite_set_dither(mp_obj_t self_in, mp_obj_t v) { + picogame_sprite_obj_t *s = MP_OBJ_TO_PTR(self_in); + int lv = mp_obj_get_int(v); + if (lv < 0) { + lv = 0; + } + if (lv > 16) { + lv = 16; + } + s->dither = (uint8_t)lv; + set_effect(s, PICOGAME_SPR_DITHER, lv > 0); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(sprite_set_dither_obj, sprite_set_dither); +MP_PROPERTY_GETSET(sprite_dither_obj, (mp_obj_t)&sprite_get_dither_obj, (mp_obj_t)&sprite_set_dither_obj); + +//| tint: int +//| """Multiply opaque pixels by a color from :py:func:`rgb565`, preserving the +//| sprite's shading (unlike `flash`, which replaces it). ``0`` disables, so pure +//| black cannot be the tint color. Mutually exclusive with `shadow`, `flash` +//| and `dither`.""" +static mp_obj_t sprite_get_tint(mp_obj_t self_in) { + picogame_sprite_obj_t *s = MP_OBJ_TO_PTR(self_in); + return MP_OBJ_NEW_SMALL_INT((s->flags & PICOGAME_SPR_TINT) ? s->flash_color : 0); +} +static MP_DEFINE_CONST_FUN_OBJ_1(sprite_get_tint_obj, sprite_get_tint); +static mp_obj_t sprite_set_tint(mp_obj_t self_in, mp_obj_t v) { + picogame_sprite_obj_t *s = MP_OBJ_TO_PTR(self_in); + if (!mp_obj_is_true(v)) { + set_effect(s, PICOGAME_SPR_TINT, false); + } else { + s->flash_color = (uint16_t)mp_obj_get_int(v); // shared colour field with flash + set_effect(s, PICOGAME_SPR_TINT, true); + } + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(sprite_set_tint_obj, sprite_set_tint); +MP_PROPERTY_GETSET(sprite_tint_obj, (mp_obj_t)&sprite_get_tint_obj, (mp_obj_t)&sprite_set_tint_obj); + +//| add: int +//| """Add opaque pixels to what is under them, multiplied by a color from +//| :py:func:`rgb565`, saturating per channel: the sprite is light. A white soft disc +//| bitmap becomes a torch glow, a muzzle flash or a pool of light on the floor, +//| in any color, drawn after the layers it lights. ``0`` disables, so pure black +//| cannot be the color (it would add nothing anyway). Mutually exclusive with +//| `shadow`, `flash`, `dither` and `tint`.""" +static mp_obj_t sprite_get_add(mp_obj_t self_in) { + picogame_sprite_obj_t *s = MP_OBJ_TO_PTR(self_in); + return MP_OBJ_NEW_SMALL_INT((s->flags & PICOGAME_SPR_ADD) ? s->flash_color : 0); +} +static MP_DEFINE_CONST_FUN_OBJ_1(sprite_get_add_obj, sprite_get_add); +static mp_obj_t sprite_set_add(mp_obj_t self_in, mp_obj_t v) { + picogame_sprite_obj_t *s = MP_OBJ_TO_PTR(self_in); + if (!mp_obj_is_true(v)) { + set_effect(s, PICOGAME_SPR_ADD, false); + } else { + s->flash_color = (uint16_t)mp_obj_get_int(v); // shared colour field with flash/tint + set_effect(s, PICOGAME_SPR_ADD, true); + } + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(sprite_set_add_obj, sprite_set_add); +MP_PROPERTY_GETSET(sprite_add_obj, (mp_obj_t)&sprite_get_add_obj, (mp_obj_t)&sprite_set_add_obj); + +//| transpose: bool +//| """Transpose the frame by swapping its x and y axes. Combined with `flip_x` +//| and `flip_y` this yields all 8 orthogonal orientations. Applies only at +//| ``scale == 1.0`` and ``angle == 0``; for rotation combined with scaling use +//| `angle`. The drawn footprint swaps width and height.""" +static mp_obj_t sprite_get_transpose(mp_obj_t self_in) { + return mp_obj_new_bool((((picogame_sprite_obj_t *)MP_OBJ_TO_PTR(self_in))->flags & PICOGAME_SPR_TRANSPOSE) != 0); +} +static MP_DEFINE_CONST_FUN_OBJ_1(sprite_get_transpose_obj, sprite_get_transpose); +static mp_obj_t sprite_set_transpose(mp_obj_t self_in, mp_obj_t v) { + set_flag(MP_OBJ_TO_PTR(self_in), PICOGAME_SPR_TRANSPOSE, mp_obj_is_true(v)); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(sprite_set_transpose_obj, sprite_set_transpose); +MP_PROPERTY_GETSET(sprite_transpose_obj, (mp_obj_t)&sprite_get_transpose_obj, (mp_obj_t)&sprite_set_transpose_obj); + +//| data: Any +//| """Arbitrary per-sprite user payload for game state (default None).""" +static mp_obj_t sprite_get_data(mp_obj_t self_in) { + return ((picogame_sprite_obj_t *)MP_OBJ_TO_PTR(self_in))->data; +} +static MP_DEFINE_CONST_FUN_OBJ_1(sprite_get_data_obj, sprite_get_data); +static mp_obj_t sprite_set_data(mp_obj_t self_in, mp_obj_t v) { + ((picogame_sprite_obj_t *)MP_OBJ_TO_PTR(self_in))->data = v; + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(sprite_set_data_obj, sprite_set_data); +MP_PROPERTY_GETSET(sprite_data_obj, (mp_obj_t)&sprite_get_data_obj, (mp_obj_t)&sprite_set_data_obj); + +//| bitmap: Bitmap +//| """The sprite's source bitmap. Assigning a new one swaps the graphics and may +//| change the sprite's size; the scene repaints both the old and new bounds on +//| the next refresh.""" +static mp_obj_t sprite_get_bitmap(mp_obj_t self_in) { + picogame_sprite_obj_t *self = MP_OBJ_TO_PTR(self_in); + return self->bitmap != NULL ? MP_OBJ_FROM_PTR(self->bitmap) : mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(sprite_get_bitmap_obj, sprite_get_bitmap); +static mp_obj_t sprite_set_bitmap(mp_obj_t self_in, mp_obj_t v) { + picogame_sprite_obj_t *self = MP_OBJ_TO_PTR(self_in); + mp_obj_t bm = mp_arg_validate_type(v, &picogame_bitmap_type, MP_QSTR_bitmap); + self->bitmap = MP_OBJ_TO_PTR(bm); + self->xf_valid = 0; // affine cache depends on bitmap dims + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(sprite_set_bitmap_obj, sprite_set_bitmap); +MP_PROPERTY_GETSET(sprite_bitmap_obj, (mp_obj_t)&sprite_get_bitmap_obj, (mp_obj_t)&sprite_set_bitmap_obj); + +//| anchor: Tuple[float, float] +//| """Pivot as fractions of the bitmap size: ``(0, 0)`` = top-left (default), +//| ``(0.5, 0.5)`` = center, ``(0.5, 1.0)`` = bottom-center. ``x``/``y`` then +//| refer to this point, so rotating frames or swapping to a different size +//| stays aligned. Stored in 1/256 steps.""" +//| +static mp_obj_t sprite_get_anchor(mp_obj_t self_in) { + picogame_sprite_obj_t *self = MP_OBJ_TO_PTR(self_in); + mp_obj_t t[2] = { + mp_obj_new_float(self->anchor_x * (mp_float_t)(1.0 / 256.0)), + mp_obj_new_float(self->anchor_y * (mp_float_t)(1.0 / 256.0)), + }; + return mp_obj_new_tuple(2, t); +} +static MP_DEFINE_CONST_FUN_OBJ_1(sprite_get_anchor_obj, sprite_get_anchor); +static int anchor_to_fp(mp_obj_t o) { + mp_float_t f = mp_obj_get_float(o); + int v = pg_round_fp8(f); + return v < 0 ? 0 : (v > 256 ? 256 : v); +} +static mp_obj_t sprite_set_anchor(mp_obj_t self_in, mp_obj_t v) { + picogame_sprite_obj_t *self = MP_OBJ_TO_PTR(self_in); + size_t len; + mp_obj_t *items; + mp_obj_get_array(v, &len, &items); + mp_arg_validate_length(len, 2, MP_QSTR_anchor); + self->anchor_x = anchor_to_fp(items[0]); + self->anchor_y = anchor_to_fp(items[1]); + self->xf_valid = 0; // affine cache depends on the pivot + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(sprite_set_anchor_obj, sprite_set_anchor); +MP_PROPERTY_GETSET(sprite_anchor_obj, (mp_obj_t)&sprite_get_anchor_obj, (mp_obj_t)&sprite_set_anchor_obj); + +//| def move(self, x: float, y: float) -> None: +//| """Set the sprite position. Accepts floats for sub-pixel placement.""" +//| ... +//| +static mp_obj_t sprite_move(mp_obj_t self_in, mp_obj_t x_in, mp_obj_t y_in) { + picogame_sprite_obj_t *self = MP_OBJ_TO_PTR(self_in); + self->x = obj_to_fp(x_in); + self->y = obj_to_fp(y_in); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_3(sprite_move_obj, sprite_move); + +//| def touch(self) -> None: +//| """Force this sprite to repaint on the next :py:meth:`Scene.refresh` even +//| though none of its tracked properties (position, frame, scale, angle, +//| bitmap) changed. Call it after mutating the bitmap's backing buffer in +//| place, which the dirty-region tracking cannot otherwise detect.""" +//| ... +//| +static mp_obj_t sprite_touch(mp_obj_t self_in) { + ((picogame_sprite_obj_t *)MP_OBJ_TO_PTR(self_in))->seq++; + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(sprite_touch_obj, sprite_touch); + +// Fill (x1,y1,x2,y2) from a Sprite (its drawn aabb), a (x,y) point, or a (x1,y1,x2,y2) rect. +static void pg_obj_to_box(mp_obj_t o, int *x1, int *y1, int *x2, int *y2) { + if (mp_obj_is_type(o, &picogame_sprite_type)) { + picogame_sprite_aabb(MP_OBJ_TO_PTR(o), x1, y1, x2, y2); + return; + } + if (mp_obj_is_type(o, &mp_type_tuple) || mp_obj_is_type(o, &mp_type_list)) { + size_t len; + mp_obj_t *items; + mp_obj_get_array(o, &len, &items); + if (len == 2) { // a point -> a zero-size box + *x1 = *x2 = mp_obj_get_int(items[0]); + *y1 = *y2 = mp_obj_get_int(items[1]); + return; + } + if (len == 4) { // a rect + *x1 = mp_obj_get_int(items[0]); + *y1 = mp_obj_get_int(items[1]); + *x2 = mp_obj_get_int(items[2]); + *y2 = mp_obj_get_int(items[3]); + return; + } + } + mp_raise_msg_varg(&mp_type_TypeError, MP_ERROR_TEXT("%q must be of type %q or %q, not %q"), + MP_QSTR_other, MP_QSTR_Sprite, MP_QSTR_tuple, mp_obj_get_type(o)->name); +} + +//| def overlaps( +//| self, +//| other: Union[Sprite, Tuple[int, int], Tuple[int, int, int, int]], +//| inset: int = 0, +//| ) -> bool: +//| """Return `True` if this sprite's drawn rectangle overlaps ``other``. Bounds +//| are inclusive, so touching edges count as an overlap. ``other`` may be +//| another `Sprite`, a point ``(x, y)`` or a rectangle ``(x1, y1, x2, y2)``. +//| The rectangle accounts for anchor, scale and rotation. ``inset`` shrinks +//| this sprite's rectangle by that many pixels on each side.""" +//| ... +//| +static mp_obj_t sprite_overlaps(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_other, ARG_inset }; + static const mp_arg_t allowed[] = { + { MP_QSTR_other, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_inset, MP_ARG_INT, {.u_int = 0} }, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed)]; + mp_arg_parse_all(n_args - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(allowed), allowed, args); + int ax1, ay1, ax2, ay2, bx1, by1, bx2, by2; + picogame_sprite_aabb(MP_OBJ_TO_PTR(pos_args[0]), &ax1, &ay1, &ax2, &ay2); + pg_obj_to_box(args[ARG_other].u_obj, &bx1, &by1, &bx2, &by2); + int in = args[ARG_inset].u_int; // inset shrinks the CALLER's box (kw or positional) + bool hit = ((ax1 + in) <= bx2) && ((ax2 - in) >= bx1) && + ((ay1 + in) <= by2) && ((ay2 - in) >= by1); + return mp_obj_new_bool(hit); +} +static MP_DEFINE_CONST_FUN_OBJ_KW(sprite_overlaps_obj, 2, sprite_overlaps); + +//| def near(self, other: Union[Sprite, Tuple[int, int]], r: int) -> bool: +//| """Return `True` when the distance between centers is less than ``r`` +//| pixels. ``other`` may be a `Sprite` or a point ``(x, y)``. Centers come +//| from the drawn rectangle, so the test accounts for the anchor.""" +//| ... +//| +//| +static mp_obj_t sprite_near(mp_obj_t self_in, mp_obj_t other_in, mp_obj_t r_in) { + int ax1, ay1, ax2, ay2; + picogame_sprite_aabb(MP_OBJ_TO_PTR(self_in), &ax1, &ay1, &ax2, &ay2); + int acx = (ax1 + ax2) / 2, acy = (ay1 + ay2) / 2, bcx, bcy; + if (mp_obj_is_type(other_in, &picogame_sprite_type)) { + int bx1, by1, bx2, by2; + picogame_sprite_aabb(MP_OBJ_TO_PTR(other_in), &bx1, &by1, &bx2, &by2); + bcx = (bx1 + bx2) / 2; + bcy = (by1 + by2) / 2; + } else { + size_t len; + mp_obj_t *items; + mp_obj_get_array(other_in, &len, &items); + if (len != 2) { + mp_raise_msg_varg(&mp_type_TypeError, MP_ERROR_TEXT("%q must be of type %q or %q, not %q"), + MP_QSTR_other, MP_QSTR_Sprite, MP_QSTR_tuple, mp_obj_get_type(other_in)->name); + } + bcx = mp_obj_get_int(items[0]); + bcy = mp_obj_get_int(items[1]); + } + mp_int_t r = mp_obj_get_int(r_in), dx = acx - bcx, dy = acy - bcy; + return mp_obj_new_bool(dx * dx + dy * dy < r * r); +} +static MP_DEFINE_CONST_FUN_OBJ_3(sprite_near_obj, sprite_near); + +static const mp_rom_map_elem_t picogame_sprite_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_x), MP_ROM_PTR(&sprite_x_obj) }, + { MP_ROM_QSTR(MP_QSTR_y), MP_ROM_PTR(&sprite_y_obj) }, + { MP_ROM_QSTR(MP_QSTR_fx), MP_ROM_PTR(&sprite_fx_obj) }, + { MP_ROM_QSTR(MP_QSTR_fy), MP_ROM_PTR(&sprite_fy_obj) }, + { MP_ROM_QSTR(MP_QSTR_frame), MP_ROM_PTR(&sprite_frame_obj) }, + { MP_ROM_QSTR(MP_QSTR_visible), MP_ROM_PTR(&sprite_visible_obj) }, + { MP_ROM_QSTR(MP_QSTR_flip_x), MP_ROM_PTR(&sprite_flip_x_obj) }, + { MP_ROM_QSTR(MP_QSTR_flip_y), MP_ROM_PTR(&sprite_flip_y_obj) }, + { MP_ROM_QSTR(MP_QSTR_scale), MP_ROM_PTR(&sprite_scale_obj) }, + { MP_ROM_QSTR(MP_QSTR_angle), MP_ROM_PTR(&sprite_angle_obj) }, + { MP_ROM_QSTR(MP_QSTR_shadow), MP_ROM_PTR(&sprite_shadow_obj) }, + { MP_ROM_QSTR(MP_QSTR_flash), MP_ROM_PTR(&sprite_flash_obj) }, + { MP_ROM_QSTR(MP_QSTR_dither), MP_ROM_PTR(&sprite_dither_obj) }, + { MP_ROM_QSTR(MP_QSTR_tint), MP_ROM_PTR(&sprite_tint_obj) }, + { MP_ROM_QSTR(MP_QSTR_add), MP_ROM_PTR(&sprite_add_obj) }, + { MP_ROM_QSTR(MP_QSTR_transpose), MP_ROM_PTR(&sprite_transpose_obj) }, + { MP_ROM_QSTR(MP_QSTR_data), MP_ROM_PTR(&sprite_data_obj) }, + { MP_ROM_QSTR(MP_QSTR_bitmap), MP_ROM_PTR(&sprite_bitmap_obj) }, + { MP_ROM_QSTR(MP_QSTR_anchor), MP_ROM_PTR(&sprite_anchor_obj) }, + { MP_ROM_QSTR(MP_QSTR_overlaps), MP_ROM_PTR(&sprite_overlaps_obj) }, + { MP_ROM_QSTR(MP_QSTR_near), MP_ROM_PTR(&sprite_near_obj) }, + { MP_ROM_QSTR(MP_QSTR_move), MP_ROM_PTR(&sprite_move_obj) }, + { MP_ROM_QSTR(MP_QSTR_touch), MP_ROM_PTR(&sprite_touch_obj) }, +}; +static MP_DEFINE_CONST_DICT(picogame_sprite_locals_dict, picogame_sprite_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + picogame_sprite_type, + MP_QSTR_Sprite, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, picogame_sprite_make_new, + locals_dict, &picogame_sprite_locals_dict + ); diff --git a/shared-bindings/picogame/Sprite.h b/shared-bindings/picogame/Sprite.h new file mode 100644 index 00000000000..97c38c8b762 --- /dev/null +++ b/shared-bindings/picogame/Sprite.h @@ -0,0 +1,11 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-module/picogame/Sprite.h" + +extern const mp_obj_type_t picogame_sprite_type; diff --git a/shared-bindings/picogame/StripDraw.c b/shared-bindings/picogame/StripDraw.c new file mode 100644 index 00000000000..7e307acda20 --- /dev/null +++ b/shared-bindings/picogame/StripDraw.c @@ -0,0 +1,241 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT +// +// picogame.StripDraw: an immediate-mode draw layer that holds no pixel buffer. + +#include "py/runtime.h" +#include "shared-module/picogame/pg_compat.h" +#include "shared-bindings/busdisplay/BusDisplay.h" +#include "shared-bindings/picogame/__init__.h" +#include "shared-bindings/picogame/Bitmap.h" +#include "shared-bindings/picogame/Sprite.h" +#if CIRCUITPY_PICOGAME_FAST_DISPLAY +#include "shared-bindings/picogame/Display.h" // fast DMA backend; absent on portable ports +#include "shared-module/picogame/Display.h" // its struct (pg_get_display unwraps the wrapper) +#endif +#include "shared-bindings/picogame/Scene.h" +#include "shared-bindings/picogame/Tilemap.h" +#include "shared-bindings/picogame/Particles.h" +#include "shared-bindings/picogame/Canvas.h" +#include "shared-bindings/picogame/Framebuffer.h" +#include "shared-bindings/picogame/StripDraw.h" +#include "shared-module/picogame/__init__.h" +#include "shared-module/picogame/Bitmap.h" +#include "shared-module/picogame/Sprite.h" + +// --------------------------------------------------------------------------- +// StripDraw (immediate-mode draw layer; struct in shared-module/picogame/__init__.h) +// --------------------------------------------------------------------------- + +//| class StripDraw: +//| """An immediate-mode draw layer that holds no pixel buffer. On each refresh, +//| for every render strip overlapping its rectangle, ``callback(view, vx, vy, +//| vw, vh)`` is called with a `Canvas` view of the live strip buffer, so the +//| callback draws primitives directly into the frame. StripDraw layers always +//| draw in screen coordinates and ignore the scene's view offset. +//| +//| ``(vx, vy)`` is the view origin in screen coordinates and ``(vw, vh)`` is +//| its size: to draw a screen point ``(sx, sy)``, draw at ``(sx - vx, sy - vy)`` +//| in ``view``. The view may span the full render-region width even when the +//| layer is narrower (the layer's rectangle only limits which rows are drawn), +//| so fill your own rectangle with :py:meth:`Canvas.fill_rect` rather than +//| ``view.clear()``, which fills the whole width. +//| +//| Moving or resizing the layer by assigning :py:attr:`x`, :py:attr:`y`, +//| :py:attr:`width` or :py:attr:`height` can leave the old area stale; call +//| :py:meth:`Scene.invalidate` afterwards for a clean repaint.""" +//| +//| def __init__( +//| self, +//| callback: Callable[[Canvas, int, int, int, int], None], +//| x: int = 0, +//| y: int = 0, +//| width: int = 0, +//| height: int = 0, +//| *, +//| always_dirty: bool = True, +//| ) -> None: +//| """:param callback: called for each overlapping render strip as +//| ``callback(view, vx, vy, vw, vh)`` +//| :param int x: left edge of the layer's screen rectangle +//| :param int y: top edge of the layer's screen rectangle +//| :param int width: rectangle width in pixels +//| :param int height: rectangle height in pixels +//| :param bool always_dirty: when `True` the layer redraws every refresh; +//| when `False`, call :py:meth:`invalidate` after its content changes""" +//| ... +//| +static mp_obj_t picogame_stripdraw_make_new(const mp_obj_type_t *type, size_t n_args, + size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_callback, ARG_x, ARG_y, ARG_width, ARG_height, ARG_always_dirty }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_callback, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_x, MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_y, MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_width, MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_height, MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_always_dirty, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = true} }, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + picogame_stripdraw_obj_t *self = mp_obj_malloc(picogame_stripdraw_obj_t, type); + self->callback = args[ARG_callback].u_obj; + self->x = args[ARG_x].u_int; + self->y = args[ARG_y].u_int; + self->w = args[ARG_width].u_int; + self->h = args[ARG_height].u_int; + self->faulted = false; + self->always_dirty = args[ARG_always_dirty].u_bool; + picogame_dirty_reset(&self->dx1); // render once on first refresh (even when always_dirty=False) + picogame_dirty_union(&self->dx1, self->x, self->y, self->x + self->w, self->y + self->h); + // A buffer-less Canvas reused as the per-strip drawing view: its `data` is + // repointed at the live strip each blit, so no surface RAM is allocated here. + picogame_canvas_obj_t *view = mp_obj_malloc(picogame_canvas_obj_t, &picogame_canvas_type); + view->data = NULL; + view->data_obj = MP_OBJ_NULL; + view->w = 0; + view->h = 0; + view->x = 0; + view->y = 0; + view->transparent = 0; + view->has_transparent = false; + picogame_canvas_dirty_reset(view); + self->view = MP_OBJ_FROM_PTR(view); + return MP_OBJ_FROM_PTR(self); +} + +//| +//| x: int +//| """Left edge of the layer's screen rectangle.""" +//| y: int +//| """Top edge of the layer's screen rectangle.""" +//| width: int +//| """Width of the layer's screen rectangle in pixels.""" +//| height: int +//| """Height of the layer's screen rectangle in pixels.""" +static mp_obj_t sd_get_x(mp_obj_t self_in) { + return MP_OBJ_NEW_SMALL_INT(((picogame_stripdraw_obj_t *)MP_OBJ_TO_PTR(self_in))->x); +} +static MP_DEFINE_CONST_FUN_OBJ_1(sd_get_x_obj, sd_get_x); +static mp_obj_t sd_set_x(mp_obj_t self_in, mp_obj_t v) { + ((picogame_stripdraw_obj_t *)MP_OBJ_TO_PTR(self_in))->x = mp_obj_get_int(v); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(sd_set_x_obj, sd_set_x); +MP_PROPERTY_GETSET(sd_x_obj, (mp_obj_t)&sd_get_x_obj, (mp_obj_t)&sd_set_x_obj); + +static mp_obj_t sd_get_y(mp_obj_t self_in) { + return MP_OBJ_NEW_SMALL_INT(((picogame_stripdraw_obj_t *)MP_OBJ_TO_PTR(self_in))->y); +} +static MP_DEFINE_CONST_FUN_OBJ_1(sd_get_y_obj, sd_get_y); +static mp_obj_t sd_set_y(mp_obj_t self_in, mp_obj_t v) { + ((picogame_stripdraw_obj_t *)MP_OBJ_TO_PTR(self_in))->y = mp_obj_get_int(v); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(sd_set_y_obj, sd_set_y); +MP_PROPERTY_GETSET(sd_y_obj, (mp_obj_t)&sd_get_y_obj, (mp_obj_t)&sd_set_y_obj); + +static mp_obj_t sd_get_width(mp_obj_t self_in) { + return MP_OBJ_NEW_SMALL_INT(((picogame_stripdraw_obj_t *)MP_OBJ_TO_PTR(self_in))->w); +} +static MP_DEFINE_CONST_FUN_OBJ_1(sd_get_width_obj, sd_get_width); +static mp_obj_t sd_set_width(mp_obj_t self_in, mp_obj_t v) { + ((picogame_stripdraw_obj_t *)MP_OBJ_TO_PTR(self_in))->w = mp_obj_get_int(v); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(sd_set_width_obj, sd_set_width); +MP_PROPERTY_GETSET(sd_width_obj, (mp_obj_t)&sd_get_width_obj, (mp_obj_t)&sd_set_width_obj); + +static mp_obj_t sd_get_height(mp_obj_t self_in) { + return MP_OBJ_NEW_SMALL_INT(((picogame_stripdraw_obj_t *)MP_OBJ_TO_PTR(self_in))->h); +} +static MP_DEFINE_CONST_FUN_OBJ_1(sd_get_height_obj, sd_get_height); +static mp_obj_t sd_set_height(mp_obj_t self_in, mp_obj_t v) { + ((picogame_stripdraw_obj_t *)MP_OBJ_TO_PTR(self_in))->h = mp_obj_get_int(v); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(sd_set_height_obj, sd_set_height); +MP_PROPERTY_GETSET(sd_height_obj, (mp_obj_t)&sd_get_height_obj, (mp_obj_t)&sd_set_height_obj); + +//| always_dirty: bool +//| """When `True` (the default) the rectangle repaints every frame, for animated +//| content. When `False` the layer renders once initially and then repaints only +//| after an :py:meth:`invalidate` call or when overlapped by another dirty +//| layer; call :py:meth:`invalidate` after each content change.""" +//| +static mp_obj_t sd_get_always_dirty(mp_obj_t self_in) { + return mp_obj_new_bool(((picogame_stripdraw_obj_t *)MP_OBJ_TO_PTR(self_in))->always_dirty); +} +static MP_DEFINE_CONST_FUN_OBJ_1(sd_get_always_dirty_obj, sd_get_always_dirty); +static mp_obj_t sd_set_always_dirty(mp_obj_t self_in, mp_obj_t v) { + ((picogame_stripdraw_obj_t *)MP_OBJ_TO_PTR(self_in))->always_dirty = mp_obj_is_true(v); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(sd_set_always_dirty_obj, sd_set_always_dirty); +MP_PROPERTY_GETSET(sd_always_dirty_obj, (mp_obj_t)&sd_get_always_dirty_obj, (mp_obj_t)&sd_set_always_dirty_obj); + +//| def invalidate(self, x: int = 0, y: int = 0, w: int = 0, h: int = 0) -> None: +//| """Mark the layer dirty so it repaints on the next refresh; only needed +//| when ``always_dirty`` is `False`. +//| +//| With no arguments the whole layer repaints. To repaint one region, pass +//| all four values as a rectangle in the view-local coordinates the draw +//| callback uses; passing only some of them raises :py:class:`ValueError`. +//| Repeated calls accumulate, and the rectangle is clamped to the layer.""" +//| ... +//| +//| +static mp_obj_t sd_invalidate(size_t n_args, const mp_obj_t *args) { + picogame_stripdraw_obj_t *self = MP_OBJ_TO_PTR(args[0]); + if (n_args != 1 && n_args != 5) { + // A partial rectangle is a bug, not a request for "everything". + mp_arg_error_invalid(MP_QSTR_rect); + } + if (n_args >= 5) { // (x, y, w, h) in view-local coords -> clamped scene rect + int x1 = self->x + mp_obj_get_int(args[1]); + int y1 = self->y + mp_obj_get_int(args[2]); + int x2 = x1 + mp_obj_get_int(args[3]); + int y2 = y1 + mp_obj_get_int(args[4]); + if (x1 < self->x) { + x1 = self->x; + } + if (y1 < self->y) { + y1 = self->y; + } + if (x2 > self->x + self->w) { + x2 = self->x + self->w; + } + if (y2 > self->y + self->h) { + y2 = self->y + self->h; + } + if (x2 > x1 && y2 > y1) { + picogame_dirty_union(&self->dx1, x1, y1, x2, y2); + } + } else { // whole layer + picogame_dirty_union(&self->dx1, self->x, self->y, self->x + self->w, self->y + self->h); + } + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(sd_invalidate_obj, 1, 5, sd_invalidate); + +static const mp_rom_map_elem_t picogame_stripdraw_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_x), MP_ROM_PTR(&sd_x_obj) }, + { MP_ROM_QSTR(MP_QSTR_y), MP_ROM_PTR(&sd_y_obj) }, + { MP_ROM_QSTR(MP_QSTR_width), MP_ROM_PTR(&sd_width_obj) }, + { MP_ROM_QSTR(MP_QSTR_height), MP_ROM_PTR(&sd_height_obj) }, + { MP_ROM_QSTR(MP_QSTR_always_dirty), MP_ROM_PTR(&sd_always_dirty_obj) }, + { MP_ROM_QSTR(MP_QSTR_invalidate), MP_ROM_PTR(&sd_invalidate_obj) }, +}; +static MP_DEFINE_CONST_DICT(picogame_stripdraw_locals_dict, picogame_stripdraw_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + picogame_stripdraw_type, + MP_QSTR_StripDraw, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, picogame_stripdraw_make_new, + locals_dict, &picogame_stripdraw_locals_dict + ); diff --git a/shared-bindings/picogame/StripDraw.h b/shared-bindings/picogame/StripDraw.h new file mode 100644 index 00000000000..68c1506bacf --- /dev/null +++ b/shared-bindings/picogame/StripDraw.h @@ -0,0 +1,11 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +extern const mp_obj_type_t picogame_stripdraw_type; diff --git a/shared-bindings/picogame/Tilemap.c b/shared-bindings/picogame/Tilemap.c new file mode 100644 index 00000000000..a0a307d2f37 --- /dev/null +++ b/shared-bindings/picogame/Tilemap.c @@ -0,0 +1,247 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +#include + +#include "py/runtime.h" +#include "shared-module/picogame/pg_compat.h" +#include "shared-bindings/picogame/Tilemap.h" +#include "shared-bindings/picogame/Bitmap.h" +#include "shared-module/picogame/Tilemap.h" + +//| class Tilemap: +//| """A grid of tile indices into a tileset `Bitmap`, where each bitmap frame +//| is one tile. Add it to a `Scene` as a background layer; setting tiles or +//| moving the map marks only the affected area dirty.""" +//| +//| def __init__(self, tileset: Bitmap, cols: int, rows: int) -> None: +//| """:param Bitmap tileset: the tile images, one frame per tile +//| :param int cols: map width in tiles +//| :param int rows: map height in tiles""" +//| ... +//| +static mp_obj_t picogame_tilemap_make_new(const mp_obj_type_t *type, size_t n_args, + size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_tileset, ARG_cols, ARG_rows }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_tileset, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_cols, MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_rows, MP_ARG_REQUIRED | MP_ARG_INT }, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + mp_obj_t tileset_obj = mp_arg_validate_type(args[ARG_tileset].u_obj, &picogame_bitmap_type, MP_QSTR_tileset); + // Cap cols/rows (not just floor): an unbounded cols*rows overflows the size_t map/orient + // allocation on a 32-bit port, desyncing alloc size from the index space (same family as the + // Bitmap width*frames guard). 1024 each -> product <= 1M, far below SIZE_MAX; oversize maps + // MemoryError at alloc (safe). + mp_int_t map_w = mp_arg_validate_int_range(args[ARG_cols].u_int, 1, 1024, MP_QSTR_cols); + mp_int_t map_h = mp_arg_validate_int_range(args[ARG_rows].u_int, 1, 1024, MP_QSTR_rows); + + mp_obj_t map_obj = mp_obj_new_bytearray_of_zeros((size_t)map_w * map_h); + mp_buffer_info_t mi; + mp_get_buffer_raise(map_obj, &mi, MP_BUFFER_RW); + + picogame_tilemap_obj_t *self = mp_obj_malloc(picogame_tilemap_obj_t, type); + self->tileset = MP_OBJ_TO_PTR(tileset_obj); + self->tileset_obj = tileset_obj; + self->map = mi.buf; + self->map_obj = map_obj; + self->orient = NULL; // orientation plane allocated lazily on first flipped/rotated tile + self->orient_obj = mp_const_none; + self->map_w = map_w; + self->map_h = map_h; + self->x = 0; + self->y = 0; + picogame_tilemap_dirty_reset(self); + return MP_OBJ_FROM_PTR(self); +} + +//| def get_tile(self, tx: int, ty: int) -> int: +//| """Return the tile index at (tx, ty). Out-of-range reads as 0.""" +//| ... +//| +static mp_obj_t picogame_tilemap_get_tile(mp_obj_t self_in, mp_obj_t tx_in, mp_obj_t ty_in) { + picogame_tilemap_obj_t *self = MP_OBJ_TO_PTR(self_in); + int tx = mp_obj_get_int(tx_in); + int ty = mp_obj_get_int(ty_in); + if (tx < 0 || ty < 0 || tx >= self->map_w || ty >= self->map_h) { + return MP_OBJ_NEW_SMALL_INT(0); + } + return MP_OBJ_NEW_SMALL_INT(self->map[(size_t)ty * self->map_w + tx]); +} +static MP_DEFINE_CONST_FUN_OBJ_3(picogame_tilemap_get_tile_obj, picogame_tilemap_get_tile); + +//| def set_tile( +//| self, +//| tx: int, +//| ty: int, +//| value: int, +//| *, +//| flip_x: bool = False, +//| flip_y: bool = False, +//| transpose: bool = False, +//| ) -> None: +//| """Set the tile at ``(tx, ty)`` and mark it dirty. The keyword flags orient +//| the tile at draw time; together they yield all 8 orientations (4 rotations +//| times mirror), so one stored tile can serve as several. The flags can +//| represent the remap table emitted by the ``png2picogame.py --dedup`` +//| tool. Out-of-range writes are ignored.""" +//| ... +//| +static mp_obj_t picogame_tilemap_set_tile(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_tx, ARG_ty, ARG_value, ARG_flip_x, ARG_flip_y, ARG_transpose }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_tx, MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_ty, MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_value, MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_flip_x, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, + { MP_QSTR_flip_y, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, + { MP_QSTR_transpose, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, + }; + 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); + picogame_tilemap_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]); + int tx = args[ARG_tx].u_int; + int ty = args[ARG_ty].u_int; + if (tx < 0 || ty < 0 || tx >= self->map_w || ty >= self->map_h) { + return mp_const_none; + } + size_t off = (size_t)ty * self->map_w + tx; + uint8_t v = args[ARG_value].u_int & 0xff; + uint8_t o = 0; + if (args[ARG_flip_x].u_bool) { + o |= 1; + } + if (args[ARG_flip_y].u_bool) { + o |= 2; + } + if (args[ARG_transpose].u_bool) { + o |= 4; + } + // Allocate the orientation plane lazily - only maps that actually use flips/rotation + // pay the RAM (1 byte/cell). + if (o != 0 && self->orient == NULL) { + mp_obj_t ob = mp_obj_new_bytearray_of_zeros((size_t)self->map_w * self->map_h); + mp_buffer_info_t oi; + mp_get_buffer_raise(ob, &oi, MP_BUFFER_RW); + self->orient = oi.buf; + self->orient_obj = ob; + } + uint8_t old_o = self->orient ? self->orient[off] : 0; + if (self->map[off] != v || old_o != o) { + self->map[off] = v; + if (self->orient) { + self->orient[off] = o; + } + int tw = self->tileset ? self->tileset->width : 0; + int th = self->tileset ? self->tileset->height : 0; + int sx = self->x + tx * tw; + int sy = self->y + ty * th; + picogame_tilemap_dirty_union(self, sx, sy, sx + tw, sy + th); + } + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_KW(picogame_tilemap_set_tile_obj, 4, picogame_tilemap_set_tile); + +//| def move(self, x: int, y: int) -> None: +//| """Move the whole map to pixel (x, y).""" +//| ... +//| +static mp_obj_t picogame_tilemap_move(mp_obj_t self_in, mp_obj_t x_in, mp_obj_t y_in) { + picogame_tilemap_obj_t *self = MP_OBJ_TO_PTR(self_in); + int nx = mp_obj_get_int(x_in), ny = mp_obj_get_int(y_in); + if (nx == self->x && ny == self->y) { + return mp_const_none; // unchanged -> avoid a full-tilemap repaint + } + int ox1, oy1, ox2, oy2; + picogame_tilemap_extent(self, &ox1, &oy1, &ox2, &oy2); + self->x = nx; + self->y = ny; + int nx1, ny1, nx2, ny2; + picogame_tilemap_extent(self, &nx1, &ny1, &nx2, &ny2); + picogame_tilemap_dirty_union(self, ox1, oy1, ox2, oy2); + picogame_tilemap_dirty_union(self, nx1, ny1, nx2, ny2); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_3(picogame_tilemap_move_obj, picogame_tilemap_move); + +//| def fill(self, value: int) -> None: +//| """Set every tile to ``value``.""" +//| ... +//| +static mp_obj_t picogame_tilemap_fill(mp_obj_t self_in, mp_obj_t value_in) { + picogame_tilemap_obj_t *self = MP_OBJ_TO_PTR(self_in); + uint8_t v = mp_obj_get_int(value_in) & 0xff; + size_t total = (size_t)self->map_w * self->map_h; + memset(self->map, v, total); + if (self->orient) { + memset(self->orient, 0, total); // a plain fill clears any per-cell orientation + } + int x1, y1, x2, y2; + picogame_tilemap_extent(self, &x1, &y1, &x2, &y2); + picogame_tilemap_dirty_union(self, x1, y1, x2, y2); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(picogame_tilemap_fill_obj, picogame_tilemap_fill); + +//| x: int +//| """Horizontal position of the map's top-left corner. (read-only) +//| +//| Set with :py:meth:`move`.""" +//| y: int +//| """Vertical position of the map's top-left corner. (read-only) +//| +//| Set with :py:meth:`move`.""" +//| cols: int +//| """Map width in tiles. (read-only)""" +//| rows: int +//| """Map height in tiles. (read-only)""" +//| +//| +static mp_obj_t tilemap_get_x(mp_obj_t self_in) { + return MP_OBJ_NEW_SMALL_INT(((picogame_tilemap_obj_t *)MP_OBJ_TO_PTR(self_in))->x); +} +static MP_DEFINE_CONST_FUN_OBJ_1(tilemap_get_x_obj, tilemap_get_x); +MP_PROPERTY_GETTER(tilemap_x_obj, (mp_obj_t)&tilemap_get_x_obj); + +static mp_obj_t tilemap_get_y(mp_obj_t self_in) { + return MP_OBJ_NEW_SMALL_INT(((picogame_tilemap_obj_t *)MP_OBJ_TO_PTR(self_in))->y); +} +static MP_DEFINE_CONST_FUN_OBJ_1(tilemap_get_y_obj, tilemap_get_y); +MP_PROPERTY_GETTER(tilemap_y_obj, (mp_obj_t)&tilemap_get_y_obj); + +static mp_obj_t tilemap_get_cols(mp_obj_t self_in) { + return MP_OBJ_NEW_SMALL_INT(((picogame_tilemap_obj_t *)MP_OBJ_TO_PTR(self_in))->map_w); +} +static MP_DEFINE_CONST_FUN_OBJ_1(tilemap_get_cols_obj, tilemap_get_cols); +MP_PROPERTY_GETTER(tilemap_cols_obj, (mp_obj_t)&tilemap_get_cols_obj); + +static mp_obj_t tilemap_get_rows(mp_obj_t self_in) { + return MP_OBJ_NEW_SMALL_INT(((picogame_tilemap_obj_t *)MP_OBJ_TO_PTR(self_in))->map_h); +} +static MP_DEFINE_CONST_FUN_OBJ_1(tilemap_get_rows_obj, tilemap_get_rows); +MP_PROPERTY_GETTER(tilemap_rows_obj, (mp_obj_t)&tilemap_get_rows_obj); + +static const mp_rom_map_elem_t picogame_tilemap_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_get_tile), MP_ROM_PTR(&picogame_tilemap_get_tile_obj) }, + { MP_ROM_QSTR(MP_QSTR_set_tile), MP_ROM_PTR(&picogame_tilemap_set_tile_obj) }, + { MP_ROM_QSTR(MP_QSTR_move), MP_ROM_PTR(&picogame_tilemap_move_obj) }, + { MP_ROM_QSTR(MP_QSTR_fill), MP_ROM_PTR(&picogame_tilemap_fill_obj) }, + { MP_ROM_QSTR(MP_QSTR_x), MP_ROM_PTR(&tilemap_x_obj) }, + { MP_ROM_QSTR(MP_QSTR_y), MP_ROM_PTR(&tilemap_y_obj) }, + { MP_ROM_QSTR(MP_QSTR_cols), MP_ROM_PTR(&tilemap_cols_obj) }, + { MP_ROM_QSTR(MP_QSTR_rows), MP_ROM_PTR(&tilemap_rows_obj) }, +}; +static MP_DEFINE_CONST_DICT(picogame_tilemap_locals_dict, picogame_tilemap_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + picogame_tilemap_type, + MP_QSTR_Tilemap, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, picogame_tilemap_make_new, + locals_dict, &picogame_tilemap_locals_dict + ); diff --git a/shared-bindings/picogame/Tilemap.h b/shared-bindings/picogame/Tilemap.h new file mode 100644 index 00000000000..9c1308f9eaa --- /dev/null +++ b/shared-bindings/picogame/Tilemap.h @@ -0,0 +1,11 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-module/picogame/Tilemap.h" + +extern const mp_obj_type_t picogame_tilemap_type; diff --git a/shared-bindings/picogame/Triangles.c b/shared-bindings/picogame/Triangles.c new file mode 100644 index 00000000000..89743291056 --- /dev/null +++ b/shared-bindings/picogame/Triangles.c @@ -0,0 +1,102 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT +// +// picogame.Triangles: a retained screen-space triangle batch rasterised in C. + +#include "py/runtime.h" +#include "shared-module/picogame/pg_compat.h" +#include "shared-bindings/busdisplay/BusDisplay.h" +#include "shared-bindings/picogame/__init__.h" +#include "shared-bindings/picogame/Bitmap.h" +#include "shared-bindings/picogame/Sprite.h" +#if CIRCUITPY_PICOGAME_FAST_DISPLAY +#include "shared-bindings/picogame/Display.h" // fast DMA backend; absent on portable ports +#include "shared-module/picogame/Display.h" // its struct (pg_get_display unwraps the wrapper) +#endif +#include "shared-bindings/picogame/Scene.h" +#include "shared-bindings/picogame/Tilemap.h" +#include "shared-bindings/picogame/Particles.h" +#include "shared-bindings/picogame/Canvas.h" +#include "shared-bindings/picogame/Framebuffer.h" +#include "shared-bindings/picogame/Triangles.h" +#include "shared-module/picogame/__init__.h" +#include "shared-module/picogame/Bitmap.h" +#include "shared-module/picogame/Sprite.h" + +//| class Triangles: +//| """A retained triangle batch drawn as a `Scene` layer. The batch is +//| rasterized directly into each render strip; no per-strip Python runs and no +//| pixel buffer is held. Triangles layers always draw in screen coordinates and +//| ignore the scene's view offset. +//| +//| For each frame: project points with :py:func:`picogame3d.project`, write triangles +//| into the buffers in back-to-front order, set :py:attr:`count`, then call +//| :py:meth:`Scene.refresh`.""" +//| +//| def __init__(self, verts: ReadableBuffer, colors: ReadableBuffer) -> None: +//| """:param ~circuitpython_typing.ReadableBuffer verts: caller-owned buffer of +//| ``int16`` values, six per triangle: x0, y0, x1, y1, x2, y2. Refill it in +//| place each frame. +//| :param ~circuitpython_typing.ReadableBuffer colors: caller-owned buffer of +//| ``uint16`` colors, one per triangle""" +//| ... +//| +static mp_obj_t picogame_triangles_make_new(const mp_obj_type_t *type, size_t n_args, + size_t n_kw, const mp_obj_t *all_args) { + mp_arg_check_num(n_args, n_kw, 2, 2, false); + picogame_triangles_obj_t *self = mp_obj_malloc(picogame_triangles_obj_t, type); + mp_buffer_info_t vi, ci; + mp_get_buffer_raise(all_args[0], &vi, MP_BUFFER_READ); + mp_get_buffer_raise(all_args[1], &ci, MP_BUFFER_READ); + self->verts_obj = all_args[0]; + self->colors_obj = all_args[1]; + self->verts = (const int16_t *)vi.buf; + self->colors = (const uint16_t *)ci.buf; + size_t cap_v = vi.len / 12; // 6 int16 = 12 bytes per triangle + size_t cap_c = ci.len >> 1; + self->cap = (uint16_t)(cap_v < cap_c ? cap_v : cap_c); + self->count = 0; + picogame_dirty_reset(&self->dx1); + return MP_OBJ_FROM_PTR(self); +} + +//| count: int +//| """How many triangles of the batch draw on the next refresh, clamped to the +//| buffer capacity. Assigning marks the layer dirty for a full repaint.""" +//| +//| +static mp_obj_t tri_get_count(mp_obj_t self_in) { + return MP_OBJ_NEW_SMALL_INT(((picogame_triangles_obj_t *)MP_OBJ_TO_PTR(self_in))->count); +} +static MP_DEFINE_CONST_FUN_OBJ_1(tri_get_count_obj, tri_get_count); +static mp_obj_t tri_set_count(mp_obj_t self_in, mp_obj_t v) { + picogame_triangles_obj_t *self = MP_OBJ_TO_PTR(self_in); + int n = mp_obj_get_int(v); + if (n < 0) { + n = 0; + } + if (n > self->cap) { + n = self->cap; + } + self->count = (uint16_t)n; + picogame_dirty_union(&self->dx1, 0, 0, 32767, 32767); // clipped to the play rect later + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(tri_set_count_obj, tri_set_count); +MP_PROPERTY_GETSET(tri_count_obj, (mp_obj_t)&tri_get_count_obj, (mp_obj_t)&tri_set_count_obj); + +static const mp_rom_map_elem_t picogame_triangles_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_count), MP_ROM_PTR(&tri_count_obj) }, +}; +static MP_DEFINE_CONST_DICT(picogame_triangles_locals_dict, picogame_triangles_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + picogame_triangles_type, + MP_QSTR_Triangles, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, picogame_triangles_make_new, + locals_dict, &picogame_triangles_locals_dict + ); diff --git a/shared-bindings/picogame/Triangles.h b/shared-bindings/picogame/Triangles.h new file mode 100644 index 00000000000..86175fcea51 --- /dev/null +++ b/shared-bindings/picogame/Triangles.h @@ -0,0 +1,11 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +extern const mp_obj_type_t picogame_triangles_type; diff --git a/shared-bindings/picogame/__init__.c b/shared-bindings/picogame/__init__.c new file mode 100644 index 00000000000..05a61947bfc --- /dev/null +++ b/shared-bindings/picogame/__init__.c @@ -0,0 +1,680 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT +// +// picogame: 2D game engine bindings for the PicoPad and similar boards. + +#include "py/runtime.h" +#include "shared-module/picogame/pg_compat.h" +#include "shared-bindings/busdisplay/BusDisplay.h" +#include "shared-bindings/picogame/__init__.h" +#include "shared-bindings/picogame/Bitmap.h" +#include "shared-bindings/picogame/Sprite.h" +#include "shared-bindings/picogame/Display.h" +#if CIRCUITPY_PICOGAME_FAST_DISPLAY +#include "shared-module/picogame/Display.h" // its struct (pg_get_display unwraps the wrapper) +#endif +#include "shared-bindings/picogame/Scene.h" +#include "shared-bindings/picogame/Tilemap.h" +#include "shared-bindings/picogame/Particles.h" +#include "shared-bindings/picogame/Canvas.h" +#include "shared-bindings/picogame/Framebuffer.h" +#include "shared-bindings/picogame/StripDraw.h" +#include "shared-bindings/picogame/Triangles.h" +#include "shared-module/picogame/__init__.h" +#include "shared-module/picogame/Bitmap.h" +#include "shared-module/picogame/Sprite.h" + +// --------------------------------------------------------------------------- +// Module-level functions +// --------------------------------------------------------------------------- + +// Cast a (possibly subclassed) BusDisplay arg to its native object, raising if it isn't one. +// Also accepts the pg.Display fast-DMA wrapper (unwrapped to its underlying busdisplay - the +// portable send path): any handle that identifies the panel works wherever a display is +// expected, so the same object a Scene renders through also works for render()/invert(). +// Without this, code holding the wrapper (custom setup, rgb444) worked on ports WITHOUT the +// fast backend and TypeError'd on ports WITH it. +#if CIRCUITPY_PICOGAME_FRAMEBUFFER +// Resolve a Framebuffer, or a subclass of it, to the native object; NULL otherwise. +static picogame_framebuffer_obj_t *pg_fb_native(mp_obj_t obj) { + mp_obj_t nfb = mp_obj_cast_to_native_base(obj, &picogame_framebuffer_type); + if (nfb != MP_OBJ_NULL && mp_obj_is_type(nfb, &picogame_framebuffer_type)) { + return MP_OBJ_TO_PTR(nfb); + } + return NULL; +} +#endif + +static busdisplay_busdisplay_obj_t *pg_get_display(mp_obj_t obj) { + #if CIRCUITPY_PICOGAME_FAST_DISPLAY + if (mp_obj_is_type(obj, &picogame_display_type)) { + return ((picogame_display_obj_t *)MP_OBJ_TO_PTR(obj))->display; + } + #endif + mp_obj_t native = mp_obj_cast_to_native_base(obj, &busdisplay_busdisplay_type); + // The cast yields MP_OBJ_NULL for a non-BusDisplay: validate the ORIGINAL object so the + // error names its real type (reading the type of NULL is a hard fault on RP2350). + if (native == MP_OBJ_NULL || !mp_obj_is_type(native, &busdisplay_busdisplay_type)) { + mp_arg_validate_type(obj, &busdisplay_busdisplay_type, MP_QSTR_display); + } + return MP_OBJ_TO_PTR(native); +} + +//| """Rendering core for games +//| +//| The `picogame` module composites sprites, tilemaps, drawing canvases, +//| particle layers, 3D triangle batches and immediate-mode callbacks into a +//| small reusable strip buffer and sends each strip to the display, so a full-screen game does not +//| need a full-screen buffer. A :py:class:`Scene` tracks what changed and +//| repaints only those regions when :py:meth:`Scene.refresh` is called. +//| +//| A scene targets a :py:class:`~busdisplay.BusDisplay`, an accelerated +//| :py:class:`Display` or a RAM :py:class:`Framebuffer`. picogame drives the +//| display itself, so it requires ``display.auto_refresh = False`` and cannot +//| show displayio groups on the same display at the same time. +//| +//| Most programs start with :py:class:`Scene`, :py:class:`Sprite` and +//| :py:class:`Bitmap`. +//| +//| .. note:: +//| This module is the engine's rendering and compute core and is fully +//| usable on its own. The pure-Python `picogame helper libraries +//| `_ +//| (``picogame_game``, ``picogame_ray`` and others) build a complete game +//| framework on top of it: display, input and audio setup that adapts to +//| the board, game-loop timing, sprite pools and collision helpers, +//| animation, text, HUD and menus, sound effects and music, visual +//| effects, saved games, scene loading and pseudo-3D cameras. A desktop +//| simulator, asset-conversion tools, examples and tutorials live in the +//| `picogame repository `_, with +//| documentation at `picogame.makerclass.cz +//| `_. +//| +//| Example:: +//| +//| import array +//| import board +//| import time +//| +//| import picogame +//| +//| display = board.DISPLAY +//| display.auto_refresh = False +//| +//| size = display.width * picogame.STRIP_H * 2 +//| scene = picogame.Scene(display, bytearray(size), bytearray(size)) +//| +//| # One solid white 8x8 frame. +//| white = picogame.rgb565(255, 255, 255) +//| bitmap = picogame.Bitmap(array.array("H", [white] * 64), 8, 8) +//| player = scene.add(picogame.Sprite(bitmap, x=0, y=display.height // 2)) +//| +//| while True: +//| player.x = (player.x + 1) % display.width +//| scene.refresh() +//| time.sleep(0.02) +//| +//| This moves a white square across the screen, repainting only the pixels +//| that changed each frame.""" +//| +//| RGB565: int +//| """16-bit color bitmap format (transfer byte order).""" +//| PAL8: int +//| """8-bit paletted bitmap format.""" +//| +//| STRIP_H: int +//| """Recommended render-strip height in rows for this build. Sizing a `Scene` +//| strip buffer as ``display.width * STRIP_H * 2`` bytes yields strips this +//| tall.""" +//| +//| API_LEVEL: int +//| """Version of the picogame API. Helper libraries compare this value against +//| the API level they target.""" +//| +//| RGB444_SUPPORTED: bool +//| """Whether `Display` supports ``rgb444=True`` on this board.""" +//| +//| FAST_DISPLAY_SUPPORTED: bool +//| """Whether the `Display` backend is built into this firmware.""" +//| +//| FRAMEBUFFER_SUPPORTED: bool +//| """Whether `Framebuffer` is available on this board.""" +//| +//| +//| def rgb565(r: int, g: int, b: int) -> int: +//| """Build an RGB565 color in the display's transfer byte order from 8-bit +//| components. Every color integer in this module is such a value.""" +//| ... +//| +//| +static mp_obj_t picogame_rgb565(mp_obj_t r_in, mp_obj_t g_in, mp_obj_t b_in) { + int r = mp_obj_get_int(r_in) & 0xff; + int g = mp_obj_get_int(g_in) & 0xff; + int b = mp_obj_get_int(b_in) & 0xff; + uint16_t c = ((r & 0xf8) << 8) | ((g & 0xfc) << 3) | (b >> 3); + uint16_t wire = (uint16_t)((c >> 8) | (c << 8)); + return MP_OBJ_NEW_SMALL_INT(wire); +} +static MP_DEFINE_CONST_FUN_OBJ_3(picogame_rgb565_obj, picogame_rgb565); + +//| def invert( +//| display: Union[Display, busdisplay.BusDisplay, Framebuffer], on: bool +//| ) -> None: +//| """Enable or disable color inversion. +//| +//| Bus displays receive the controller's inversion command (INVON/INVOFF), which +//| takes effect immediately and sends no pixel data; the controller must support +//| it (ST7789 and ST7735 do). A `Framebuffer` target is instead inverted during +//| composition, starting with the next refresh.""" +//| ... +//| +//| +static mp_obj_t picogame_invert(mp_obj_t display_in, mp_obj_t on_in) { + #if CIRCUITPY_PICOGAME_FRAMEBUFFER + // A Framebuffer target (RP2350 DVI, the WASM playground) has no hardware INVON/INVOFF - + // emulate the flash by XORing the composite (mirrors the Scene/render Framebuffer handling). + { + mp_obj_t nfb = mp_obj_cast_to_native_base(display_in, &picogame_framebuffer_type); + if (nfb != MP_OBJ_NULL && mp_obj_is_type(nfb, &picogame_framebuffer_type)) { + picogame_fb_set_invert(mp_obj_is_true(on_in)); + return mp_const_none; + } + } + #endif + picogame_set_invert(pg_get_display(display_in), mp_obj_is_true(on_in)); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(picogame_invert_obj, picogame_invert); + +//| def render( +//| display: Union[Display, busdisplay.BusDisplay, Framebuffer], +//| layers: List[Union[Sprite, Tilemap, Canvas, Particles, StripDraw, Triangles]], +//| buffer: Optional[WriteableBuffer], +//| x0: int, +//| y0: int, +//| x1: int, +//| y1: int, +//| *, +//| background: int = 0, +//| ) -> None: +//| """Render ``layers`` into the screen region from ``(x0, y0)`` up to, but not +//| including, ``(x1, y1)``, and push it to ``display``, without a `Scene`. +//| +//| :param display: the render target +//| :param layers: layers of any kind, drawn bottom to top +//| :param ~circuitpython_typing.WriteableBuffer buffer: a reusable strip buffer of +//| at least ``(x1 - x0) * 2`` bytes; ignored (may be `None`) on a +//| `Framebuffer` target +//| :param int x0: left edge of the region +//| :param int y0: top edge of the region +//| :param int x1: right edge of the region (exclusive) +//| :param int y1: bottom edge of the region (exclusive) +//| :param int background: color the region is cleared to first""" +//| ... +//| +//| + +// Map a layer object to its PICOGAME_KIND_*, or raise the one shared TypeError. Both +// Scene.add() and pg.render() classify through here (one type chain, one message). +uint8_t picogame_kind_of(mp_obj_t o) { + if (mp_obj_is_type(o, &picogame_sprite_type)) { + return PICOGAME_KIND_SPRITE; + } + if (mp_obj_is_type(o, &picogame_stripdraw_type)) { + return PICOGAME_KIND_STRIPDRAW; + } + if (mp_obj_is_type(o, &picogame_tilemap_type)) { + return PICOGAME_KIND_TILEMAP; + } + if (mp_obj_is_type(o, &picogame_particles_type)) { + return PICOGAME_KIND_PARTICLES; + } + if (mp_obj_is_type(o, &picogame_canvas_type)) { + return PICOGAME_KIND_CANVAS; + } + if (mp_obj_is_type(o, &picogame_triangles_type)) { + return PICOGAME_KIND_TRIANGLES; + } + mp_arg_error_invalid(MP_QSTR_item); // the accepted layer types are listed in the docs +} + +static mp_obj_t picogame_render_fun(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_display, ARG_layers, ARG_buffer, ARG_x0, ARG_y0, ARG_x1, ARG_y1, ARG_background }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_display, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_layers, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_buffer, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_x0, MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_y0, MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_x1, MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_y1, MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_background, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0} }, + }; + 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); + + // Accept a picogame.Framebuffer (RAM scanout buffer) as the target too, when built + // in: immediate render composites straight into it (no strip buffer, no bus), so + // pg.render(board.DISPLAY, ...) works when board.DISPLAY is a Framebuffer - the HUD / + // HudBar / immediate-mode path on scanout-buffer platforms. Mirrors the Scene change. + #if CIRCUITPY_PICOGAME_FRAMEBUFFER + picogame_framebuffer_obj_t *fbt = + pg_fb_native(args[ARG_display].u_obj); + busdisplay_busdisplay_obj_t *display = fbt ? NULL : pg_get_display(args[ARG_display].u_obj); + #else + busdisplay_busdisplay_obj_t *display = pg_get_display(args[ARG_display].u_obj); + #endif + + size_t n = 0; + mp_obj_t *items; + mp_obj_get_array(args[ARG_layers].u_obj, &n, &items); + + // Classify items into layer kinds. All-Sprite lists stay on the NULL-kinds fast path (no alloc - + // the common case). Any non-Sprite layer (StripDraw/Canvas/Tilemap/Particles) builds a small kinds + // array so immediate render uses the SAME multi-layer blitter the Scene does - e.g. a StripDraw + // composited straight into the strip with `view.text()` = 0-RAM immediate HUD / text screen. + uint8_t kbuf[16]; + uint8_t *kinds = NULL; + for (size_t i = 0; i < n; i++) { + if (!mp_obj_is_type(items[i], &picogame_sprite_type)) { + kinds = (n <= MP_ARRAY_SIZE(kbuf)) ? kbuf : m_new(uint8_t, n); + break; + } + } + if (kinds != NULL) { + for (size_t i = 0; i < n; i++) { + // (an unknown type raises from kind_of; the GC reclaims a heap `kinds`) + kinds[i] = picogame_kind_of(items[i]); + } + } + + #if CIRCUITPY_PICOGAME_FRAMEBUFFER + if (fbt != NULL) { + // Framebuffer target: composite the region straight into it (no strip buffer, no + // bus). Same compositor as the SPI path; re-raise a latched StripDraw exception. + mp_obj_t exc = picogame_render_framebuffer(fbt->fb, fbt->width, fbt->height, fbt->fmt, + fbt->scratch, fbt->scratch_rows, + items, kinds, n, + args[ARG_x0].u_int, args[ARG_y0].u_int, args[ARG_x1].u_int, args[ARG_y1].u_int, + args[ARG_background].u_int, 0, 0); + if (kinds != NULL && n > MP_ARRAY_SIZE(kbuf)) { + m_del(uint8_t, kinds, n); + } + if (exc != MP_OBJ_NULL) { + nlr_raise(MP_OBJ_TO_PTR(exc)); + } + return mp_const_none; + } + #endif + + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(args[ARG_buffer].u_obj, &bufinfo, MP_BUFFER_WRITE); + + if (kinds == NULL) { + picogame_render(display, items, n, + (uint16_t *)bufinfo.buf, bufinfo.len / 2, + args[ARG_x0].u_int, args[ARG_y0].u_int, args[ARG_x1].u_int, args[ARG_y1].u_int, + args[ARG_background].u_int); + } else { + picogame_render_region(display, items, kinds, n, + (uint16_t *)bufinfo.buf, bufinfo.len / 2, + args[ARG_x0].u_int, args[ARG_y0].u_int, args[ARG_x1].u_int, args[ARG_y1].u_int, + args[ARG_background].u_int, 0, 0); + if (n > MP_ARRAY_SIZE(kbuf)) { + m_del(uint8_t, kinds, n); + } + } + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_KW(picogame_render_obj, 7, picogame_render_fun); + +//| def collide( +//| x1: int, y1: int, x2: int, y2: int, ax1: int, ay1: int, ax2: int = ..., ay2: int = ... +//| ) -> bool: +//| """Return whether an inclusive rectangle overlaps another rectangle or contains +//| a point. Both corners are part of the rectangle, so touching edges count as an +//| overlap. +//| +//| With six arguments, test rectangle ``(x1, y1, x2, y2)`` against the point +//| ``(ax1, ay1)``; with eight, test it against the rectangle +//| ``(ax1, ay1, ax2, ay2)``. +//| +//| Unlike the pixel regions used by `render`, whose upper bounds are excluded, +//| collision bounds are inclusive.""" +//| ... +//| +//| +static mp_obj_t picogame_collide(size_t n_args, const mp_obj_t *args) { + int x1 = mp_obj_get_int(args[0]); + int y1 = mp_obj_get_int(args[1]); + int x2 = mp_obj_get_int(args[2]); + int y2 = mp_obj_get_int(args[3]); + bool hit; + if (n_args == 8) { + int bx1 = mp_obj_get_int(args[4]); + int by1 = mp_obj_get_int(args[5]); + int bx2 = mp_obj_get_int(args[6]); + int by2 = mp_obj_get_int(args[7]); + hit = (x1 <= bx2) && (x2 >= bx1) && (y1 <= by2) && (y2 >= by1); + } else if (n_args == 6) { + int px = mp_obj_get_int(args[4]); + int py = mp_obj_get_int(args[5]); + hit = (px >= x1) && (px <= x2) && (py >= y1) && (py <= y2); + } else { + mp_raise_TypeError(MP_ERROR_TEXT("argument num/types mismatch")); + } + return mp_obj_new_bool(hit); +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(picogame_collide_obj, 6, 8, picogame_collide); + +// ---- procedural value-noise in C (the desktop simulator sim/picogame.py mirrors it) ---- +// The CANONICAL implementation is FIXED-POINT (Q16.16 coords, Q0.16 values), exposed +// under the plain names value2d/value1d/fbm2d/fbm1d (see further down). It benchmarked +// ~1.8x faster than float on-device (0.649 s vs 1.186 s / 5000 fbm2d), so the float +// version was retired (2026-06-18) to free flash for future engine features. +// The float reference is preserved but DISABLED in the `#if 0` below (cf. PicoLibSDK's +// own Noise2D, which is likewise float) - revive by flipping it to `#if 1` and pointing +// the module table at the *_obj names instead of the *_fx_obj ones. +#if 0 // float reference implementation - superseded by the fixed-point path below +static inline float pg_nhash(int32_t x, int32_t y, int32_t seed) { + uint32_t h = (uint32_t)x * 374761393u + (uint32_t)y * 668265263u + (uint32_t)seed * 362437u; + h = (h ^ (h >> 13)) * 1274126177u; + h = h ^ (h >> 16); + return (float)(h & 0xFFFFu) / 65535.0f; +} +static inline float pg_nsmooth(float t) { + return t * t * (3.0f - 2.0f * t); +} +static inline int32_t pg_ifloor(float x) { + int32_t i = (int32_t)x; + return (x < (float)i) ? i - 1 : i; +} +static float pg_value2d(float x, float y, int32_t seed) { + int32_t xi = pg_ifloor(x), yi = pg_ifloor(y); + float xf = x - (float)xi, yf = y - (float)yi; + float a = pg_nhash(xi, yi, seed), b = pg_nhash(xi + 1, yi, seed); + float c = pg_nhash(xi, yi + 1, seed), d = pg_nhash(xi + 1, yi + 1, seed); + float u = pg_nsmooth(xf), v = pg_nsmooth(yf); + return (a * (1.0f - u) + b * u) * (1.0f - v) + (c * (1.0f - u) + d * u) * v; +} +static float pg_value1d(float x, int32_t seed) { + int32_t xi = pg_ifloor(x); + float xf = x - (float)xi; + float a = pg_nhash(xi, 0, seed), b = pg_nhash(xi + 1, 0, seed); + return a + (b - a) * pg_nsmooth(xf); +} + +//| def value2d(x: float, y: float, *, seed: int = 0) -> float: +//| """Smooth 2-D value noise in ``0..1``.""" +//| ... +//| +//| +static mp_obj_t picogame_value2d(size_t n_args, const mp_obj_t *pos, mp_map_t *kw) { + static const mp_arg_t spec[] = { {MP_QSTR_x, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL}}, + {MP_QSTR_y, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL}}, {MP_QSTR_seed, MP_ARG_INT, {.u_int = 0}} }; + mp_arg_val_t a[3]; + mp_arg_parse_all(n_args, pos, kw, 3, spec, a); + return mp_obj_new_float(pg_value2d(mp_obj_get_float(a[0].u_obj), mp_obj_get_float(a[1].u_obj), a[2].u_int)); +} +static MP_DEFINE_CONST_FUN_OBJ_KW(picogame_value2d_obj, 2, picogame_value2d); + +//| def value1d(x: float, *, seed: int = 0) -> float: +//| """Smooth 1-D value noise in ``0..1``.""" +//| ... +static mp_obj_t picogame_value1d(size_t n_args, const mp_obj_t *pos, mp_map_t *kw) { + static const mp_arg_t spec[] = { {MP_QSTR_x, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL}}, + {MP_QSTR_seed, MP_ARG_INT, {.u_int = 0}} }; + mp_arg_val_t a[2]; + mp_arg_parse_all(n_args, pos, kw, 2, spec, a); + return mp_obj_new_float(pg_value1d(mp_obj_get_float(a[0].u_obj), a[1].u_int)); +} +static MP_DEFINE_CONST_FUN_OBJ_KW(picogame_value1d_obj, 1, picogame_value1d); +#endif // float value2d / value1d + +// Shared arg spec for both fbm2d (disabled float) and fbm2d_fx (active fixed-point). +static const mp_arg_t pg_fbm2d_args[] = { + { MP_QSTR_x, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_y, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_octaves, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 4} }, + { MP_QSTR_seed, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0} }, + { MP_QSTR_lacunarity, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_OBJ_NULL} }, + { MP_QSTR_gain, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_OBJ_NULL} }, +}; + +#if 0 // float reference fbm - superseded by the fixed-point path below +//| def fbm2d(x: float, y: float, *, octaves: int = 4, seed: int = 0, lacunarity: float = 2.0, gain: float = 0.5) -> float: +//| """Fractal (fBm) 2-D noise in ``0..1``: ``octaves`` layers of :py:func:`value2d`, each +//| ``lacunarity`` times finer and ``gain`` times weaker than the last.""" +//| ... +static mp_obj_t picogame_fbm2d(size_t n_args, const mp_obj_t *pos, mp_map_t *kw) { + mp_arg_val_t a[6]; + mp_arg_parse_all(n_args, pos, kw, 6, pg_fbm2d_args, a); + float x = mp_obj_get_float(a[0].u_obj), y = mp_obj_get_float(a[1].u_obj); + int octaves = a[2].u_int; + int32_t seed = a[3].u_int; + float lac = (a[4].u_obj == MP_OBJ_NULL) ? 2.0f : mp_obj_get_float(a[4].u_obj); + float gain = (a[5].u_obj == MP_OBJ_NULL) ? 0.5f : mp_obj_get_float(a[5].u_obj); + float total = 0.0f, amp = 1.0f, freq = 1.0f, norm = 0.0f; + for (int i = 0; i < octaves; i++) { + total += amp * pg_value2d(x * freq, y * freq, seed); + norm += amp; + amp *= gain; + freq *= lac; + } + return mp_obj_new_float(norm > 0.0f ? total / norm : 0.0f); +} +static MP_DEFINE_CONST_FUN_OBJ_KW(picogame_fbm2d_obj, 2, picogame_fbm2d); + +//| def fbm1d(x: float, *, octaves: int = 4, seed: int = 0, lacunarity: float = 2.0, gain: float = 0.5) -> float: +//| """Fractal (fBm) 1-D noise in ``0..1``: ``octaves`` layers of +//| :py:func:`value1d`, each ``lacunarity`` times finer and ``gain`` times +//| weaker than the last.""" +//| ... +//| +//| +static mp_obj_t picogame_fbm1d(size_t n_args, const mp_obj_t *pos, mp_map_t *kw) { + static const mp_arg_t spec[] = { {MP_QSTR_x, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL}}, + {MP_QSTR_octaves, MP_ARG_INT, {.u_int = 4}}, {MP_QSTR_seed, MP_ARG_INT, {.u_int = 0}}, + {MP_QSTR_lacunarity, MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL}}, {MP_QSTR_gain, MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL}} }; + mp_arg_val_t a[5]; + mp_arg_parse_all(n_args, pos, kw, 5, spec, a); + float x = mp_obj_get_float(a[0].u_obj); + int octaves = a[1].u_int; + int32_t seed = a[2].u_int; + float lac = (a[3].u_obj == MP_OBJ_NULL) ? 2.0f : mp_obj_get_float(a[3].u_obj); + float gain = (a[4].u_obj == MP_OBJ_NULL) ? 0.5f : mp_obj_get_float(a[4].u_obj); + float total = 0.0f, amp = 1.0f, freq = 1.0f, norm = 0.0f; + for (int i = 0; i < octaves; i++) { + total += amp * pg_value1d(x * freq, seed); + norm += amp; + amp *= gain; + freq *= lac; + } + return mp_obj_new_float(norm > 0.0f ? total / norm : 0.0f); +} +static MP_DEFINE_CONST_FUN_OBJ_KW(picogame_fbm1d_obj, 1, picogame_fbm1d); +#endif // float fbm2d / fbm1d + +// ---- fixed-point (Q16.16 coords, Q0.16 values) noise: the CANONICAL value-noise impl, +// exposed under the plain names value2d/value1d/fbm2d/fbm1d. The inner math is integer +// (float only at the Python boundary); ~1.8x faster than the retired float path. ---- + +// Mix step of the hash. The four corners of a cell differ only by constants +// in the input, so the coordinate part is computed once per cell. +static inline uint32_t pg_nhash_mix(uint32_t h) { + h = (h ^ (h >> 13)) * 1274126177u; + return (h ^ (h >> 16)) & 0xFFFFu; // Q0.16 in [0,1) +} +static inline uint32_t pg_smooth16(uint32_t t) { // t,result Q0.16: t*t*(3-2t) + uint32_t t2 = (t * t) >> 16; // t <= 0xFFFF, so t*t fits uint32 + uint32_t e = (3u << 16) - 2u * t; // e <= 3<<16, i.e. under 2^18 + return (uint32_t)pg_mulshr16(t2, e); // t2 <= 2^16 and e <= 2^24: exact +} +static inline uint32_t pg_lerp16(uint32_t a, uint32_t b, uint32_t u) { + // Unsigned product with a sign split; a negative delta must floor like the old shift. + int32_t d = (int32_t)b - (int32_t)a; + if (d >= 0) { + return a + (((uint32_t)d * u) >> 16); + } + return a - ((((uint32_t)(-d) * u) + 0xFFFFu) >> 16); +} +static uint32_t pg_value2d_fx(int32_t X, int32_t Y, int32_t seed) { // X,Y Q16.16 -> Q0.16 + int32_t xi = X >> 16, yi = Y >> 16; + uint32_t xf = (uint32_t)(X - (xi << 16)), yf = (uint32_t)(Y - (yi << 16)); + uint32_t base = (uint32_t)xi * 374761393u + (uint32_t)yi * 668265263u + (uint32_t)seed * 362437u; + uint32_t a = pg_nhash_mix(base); // (xi, yi) + uint32_t b = pg_nhash_mix(base + 374761393u); // (xi+1, yi) + uint32_t c = pg_nhash_mix(base + 668265263u); // (xi, yi+1) + uint32_t d = pg_nhash_mix(base + 374761393u + 668265263u); + uint32_t u = pg_smooth16(xf), v = pg_smooth16(yf); + return pg_lerp16(pg_lerp16(a, b, u), pg_lerp16(c, d, u), v); +} +// (1-D value noise == the 2-D sampler at Y=0, bit for bit: v = smooth16(0) = 0 makes the +// outer lerp return its first argument, which is exactly lerp(hash(xi,0), hash(xi+1,0), u). +// So the 1-D entry points below just call pg_value2d_fx(X, 0, seed) - no separate kernel.) +#define PG_Q16(f) ((int32_t)((f) * 65536.0f)) + +static mp_obj_t picogame_value2d_fx(size_t n_args, const mp_obj_t *pos, mp_map_t *kw) { + static const mp_arg_t spec[] = { {MP_QSTR_x, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL}}, + {MP_QSTR_y, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL}}, {MP_QSTR_seed, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0}} }; + mp_arg_val_t a[3]; + mp_arg_parse_all(n_args, pos, kw, 3, spec, a); + int32_t v = pg_value2d_fx(PG_Q16(mp_obj_get_float(a[0].u_obj)), PG_Q16(mp_obj_get_float(a[1].u_obj)), a[2].u_int); + return mp_obj_new_float((float)v * (1.0f / 65536.0f)); +} +static MP_DEFINE_CONST_FUN_OBJ_KW(picogame_value2d_fx_obj, 2, picogame_value2d_fx); + +static mp_obj_t picogame_value1d_fx(size_t n_args, const mp_obj_t *pos, mp_map_t *kw) { + static const mp_arg_t spec[] = { {MP_QSTR_x, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL}}, + {MP_QSTR_seed, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0}} }; + mp_arg_val_t a[2]; + mp_arg_parse_all(n_args, pos, kw, 2, spec, a); + int32_t v = pg_value2d_fx(PG_Q16(mp_obj_get_float(a[0].u_obj)), 0, a[1].u_int); + return mp_obj_new_float((float)v * (1.0f / 65536.0f)); +} +static MP_DEFINE_CONST_FUN_OBJ_KW(picogame_value1d_fx_obj, 1, picogame_value1d_fx); + +// Shared fBm octave accumulator (the 1-D entry passes Y=0; sy is then 0 every octave, +// which the value sampler maps to the exact 1-D lattice - see the note above). +static mp_obj_t pg_fbm_eval(int32_t X, int32_t Y, int octaves, int32_t seed, + const mp_arg_val_t *lac, const mp_arg_val_t *gain) { + int32_t lacq = (lac->u_obj == MP_OBJ_NULL) ? (2 << 16) : PG_Q16(mp_obj_get_float(lac->u_obj)); + int32_t gainq = (gain->u_obj == MP_OBJ_NULL) ? (1 << 15) : PG_Q16(mp_obj_get_float(gain->u_obj)); + int32_t amp = 1 << 16, freq = 1 << 16; + int64_t total = 0, norm = 0; + for (int i = 0; i < octaves; i++) { + int32_t sx = (int32_t)(((int64_t)X * freq) >> 16), sy = (int32_t)(((int64_t)Y * freq) >> 16); + total += ((int64_t)amp * pg_value2d_fx(sx, sy, seed)) >> 16; + norm += amp; + amp = (int32_t)(((int64_t)amp * gainq) >> 16); + freq = (int32_t)(((int64_t)freq * lacq) >> 16); + } + return mp_obj_new_float(norm ? (float)total / (float)norm : 0.0f); +} + +static mp_obj_t picogame_fbm2d_fx(size_t n_args, const mp_obj_t *pos, mp_map_t *kw) { + mp_arg_val_t a[6]; + mp_arg_parse_all(n_args, pos, kw, 6, pg_fbm2d_args, a); + return pg_fbm_eval(PG_Q16(mp_obj_get_float(a[0].u_obj)), PG_Q16(mp_obj_get_float(a[1].u_obj)), + a[2].u_int, a[3].u_int, &a[4], &a[5]); +} +static MP_DEFINE_CONST_FUN_OBJ_KW(picogame_fbm2d_fx_obj, 2, picogame_fbm2d_fx); + +static mp_obj_t picogame_fbm1d_fx(size_t n_args, const mp_obj_t *pos, mp_map_t *kw) { + static const mp_arg_t spec[] = { {MP_QSTR_x, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL}}, + {MP_QSTR_octaves, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 4}}, {MP_QSTR_seed, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0}}, + {MP_QSTR_lacunarity, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_OBJ_NULL}}, {MP_QSTR_gain, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = MP_OBJ_NULL}} }; + mp_arg_val_t a[5]; + mp_arg_parse_all(n_args, pos, kw, 5, spec, a); + return pg_fbm_eval(PG_Q16(mp_obj_get_float(a[0].u_obj)), 0, + a[1].u_int, a[2].u_int, &a[3], &a[4]); +} +static MP_DEFINE_CONST_FUN_OBJ_KW(picogame_fbm1d_fx_obj, 1, picogame_fbm1d_fx); + + +// Builds without a given display backend still expose its type: constructing it raises, the same +// way an unsupported rgb444= does, instead of the module changing shape with build flags. +#if !CIRCUITPY_PICOGAME_FAST_DISPLAY || !CIRCUITPY_PICOGAME_FRAMEBUFFER +static mp_obj_t pg_stub_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) { + mp_raise_NotImplementedError(MP_ERROR_TEXT("Operation or feature not supported")); +} +#endif +#if !CIRCUITPY_PICOGAME_FAST_DISPLAY +MP_DEFINE_CONST_OBJ_TYPE(picogame_display_type, MP_QSTR_Display, MP_TYPE_FLAG_NONE, make_new, pg_stub_make_new); +#endif +#if !CIRCUITPY_PICOGAME_FRAMEBUFFER +MP_DEFINE_CONST_OBJ_TYPE(picogame_framebuffer_type, MP_QSTR_Framebuffer, MP_TYPE_FLAG_NONE, make_new, pg_stub_make_new); +#endif + +static const mp_rom_map_elem_t picogame_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_picogame) }, + { MP_ROM_QSTR(MP_QSTR_Bitmap), MP_ROM_PTR(&picogame_bitmap_type) }, + { MP_ROM_QSTR(MP_QSTR_Sprite), MP_ROM_PTR(&picogame_sprite_type) }, + { MP_ROM_QSTR(MP_QSTR_Display), MP_ROM_PTR(&picogame_display_type) }, + { MP_ROM_QSTR(MP_QSTR_Scene), MP_ROM_PTR(&picogame_scene_type) }, + { MP_ROM_QSTR(MP_QSTR_Tilemap), MP_ROM_PTR(&picogame_tilemap_type) }, + { MP_ROM_QSTR(MP_QSTR_Particles), MP_ROM_PTR(&picogame_particles_type) }, + { MP_ROM_QSTR(MP_QSTR_Canvas), MP_ROM_PTR(&picogame_canvas_type) }, + { MP_ROM_QSTR(MP_QSTR_StripDraw), MP_ROM_PTR(&picogame_stripdraw_type) }, + { MP_ROM_QSTR(MP_QSTR_Triangles), MP_ROM_PTR(&picogame_triangles_type) }, + { MP_ROM_QSTR(MP_QSTR_Framebuffer), MP_ROM_PTR(&picogame_framebuffer_type) }, + { MP_ROM_QSTR(MP_QSTR_render), MP_ROM_PTR(&picogame_render_obj) }, + { MP_ROM_QSTR(MP_QSTR_invert), MP_ROM_PTR(&picogame_invert_obj) }, + { MP_ROM_QSTR(MP_QSTR_collide), MP_ROM_PTR(&picogame_collide_obj) }, + // Canonical noise = the fixed-point implementation (float retired; see `#if 0` above). + { MP_ROM_QSTR(MP_QSTR_value2d), MP_ROM_PTR(&picogame_value2d_fx_obj) }, + { MP_ROM_QSTR(MP_QSTR_value1d), MP_ROM_PTR(&picogame_value1d_fx_obj) }, + { MP_ROM_QSTR(MP_QSTR_fbm2d), MP_ROM_PTR(&picogame_fbm2d_fx_obj) }, + { MP_ROM_QSTR(MP_QSTR_fbm1d), MP_ROM_PTR(&picogame_fbm1d_fx_obj) }, + { MP_ROM_QSTR(MP_QSTR_rgb565), MP_ROM_PTR(&picogame_rgb565_obj) }, + { MP_ROM_QSTR(MP_QSTR_RGB565), MP_ROM_INT(PICOGAME_FMT_RGB565) }, + { MP_ROM_QSTR(MP_QSTR_PAL8), MP_ROM_INT(PICOGAME_FMT_PAL8) }, + // Engine API level: bump by 1 whenever the PYTHON-VISIBLE surface grows (new method/property/ + // module function/constant), so picogame-libs can diagnose a too-old firmware up front + // ("needs API_LEVEL >= N") instead of failing later with a random missing attribute. + // Level 1 = the 2026-07 surface (post API-freeze + Canvas.text/Framebuffer/StripDraw + // always_dirty). Older firmwares have no attribute at all -> getattr(pg, "API_LEVEL", 0). + { MP_ROM_QSTR(MP_QSTR_API_LEVEL), MP_ROM_INT(1) }, + // Build-time capability flag: does THIS board's panel controller support 12-bit RGB444 + // (COLMOD)? The board declares it (it knows its controller); a game reads it to enable + // Display(rgb444=...) only where it works - one codebase runs on ST7789 AND ILI9341. + #if CIRCUITPY_PICOGAME_RGB444 + { MP_ROM_QSTR(MP_QSTR_RGB444_SUPPORTED), MP_ROM_TRUE }, + #else + { MP_ROM_QSTR(MP_QSTR_RGB444_SUPPORTED), MP_ROM_FALSE }, + #endif + #if CIRCUITPY_PICOGAME_FAST_DISPLAY + { MP_ROM_QSTR(MP_QSTR_FAST_DISPLAY_SUPPORTED), MP_ROM_TRUE }, + #else + { MP_ROM_QSTR(MP_QSTR_FAST_DISPLAY_SUPPORTED), MP_ROM_FALSE }, + #endif + #if CIRCUITPY_PICOGAME_FRAMEBUFFER + { MP_ROM_QSTR(MP_QSTR_FRAMEBUFFER_SUPPORTED), MP_ROM_TRUE }, + #else + { MP_ROM_QSTR(MP_QSTR_FRAMEBUFFER_SUPPORTED), MP_ROM_FALSE }, + #endif + // Build-time default render-strip height (rows). picogame_game.setup() uses it when strip_h is + // None; games can override per call; a board can override the default in mpconfigboard.h. + // MEASURED (RP2040): with an asynchronous bus send, SMALL strips overlap render+transfer best -> + // 8 is both fastest and least RAM (the two w*strip_h*2 buffers shrink). Without one there is no + // overlap, so a blocking send per strip makes LARGER strips win -> 24. + #ifndef PICOGAME_STRIP_H + #if CIRCUITPY_BUSIO_SPI_ASYNC + #define PICOGAME_STRIP_H 8 + #else + #define PICOGAME_STRIP_H 24 + #endif + #endif + { MP_ROM_QSTR(MP_QSTR_STRIP_H), MP_ROM_INT(PICOGAME_STRIP_H) }, +}; +static MP_DEFINE_CONST_DICT(picogame_module_globals, picogame_module_globals_table); + +const mp_obj_module_t picogame_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&picogame_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_picogame, picogame_module); diff --git a/shared-bindings/picogame/__init__.h b/shared-bindings/picogame/__init__.h new file mode 100644 index 00000000000..9bfca623beb --- /dev/null +++ b/shared-bindings/picogame/__init__.h @@ -0,0 +1,12 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + + +uint8_t picogame_kind_of(mp_obj_t o); diff --git a/shared-bindings/picogame3d/__init__.c b/shared-bindings/picogame3d/__init__.c new file mode 100644 index 00000000000..56244d8e29e --- /dev/null +++ b/shared-bindings/picogame3d/__init__.c @@ -0,0 +1,543 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT +// +// picogame3d: perspective and 3D drawing for picogame canvases. + +#include "py/runtime.h" +#include "shared-module/picogame/pg_compat.h" +#include "shared-bindings/picogame/Bitmap.h" +#include "shared-bindings/picogame/Canvas.h" +#include "shared-module/picogame/__init__.h" +#include "shared-module/picogame3d/__init__.h" + +//| """Perspective and 3D drawing for picogame +//| +//| The `picogame3d` module draws pseudo-3D views into a :py:class:`picogame.Canvas`, +//| including a `picogame.StripDraw` view: a perspective floor (`mode7`), a racing +//| road (`road_edges` and `road`) and grid-map wall rays (`raycast`). `project` +//| batch-projects 3D points for :py:class:`picogame.Triangles` and +//| :py:meth:`picogame.Canvas.fill_triangles`. +//| +//| These are low-level interfaces. The ``picogame_mode7``, ``picogame_road`` and +//| ``picogame_ray`` helper libraries compute their inputs from camera parameters.""" +//| +//| FLOAT: int +//| """``1`` when `project` uses hardware floating point (its buffers are +//| ``float32``), ``0`` when it uses signed 16.16 fixed-point ``int32``.""" +//| + +static picogame_canvas_obj_t *pg3d_canvas(mp_obj_t o) { + return MP_OBJ_TO_PTR(mp_arg_validate_type(o, &picogame_canvas_type, MP_QSTR_canvas)); +} + +//| def mode7( +//| canvas: picogame.Canvas, +//| texture: picogame.Bitmap, +//| horizon: int, +//| y_off: int, +//| z: int, +//| rx0: int, +//| ry0: int, +//| rsx: int, +//| rsy: int, +//| cam_x: int, +//| cam_y: int, +//| ) -> None: +//| """Fill rows of ``canvas`` below ``horizon`` with a perspective projection of +//| ``texture``. The ``picogame_mode7`` helper computes the camera terms from an +//| angle, position and field of view. +//| +//| :param picogame.Canvas canvas: surface to draw into +//| :param picogame.Bitmap texture: texture whose width and height are powers of two +//| :param int horizon: first canvas row to fill +//| :param int y_off: vertical offset of the projection, in rows +//| :param int z: camera height (signed 16.16 fixed-point) +//| :param int rx0: ray x at the left column (signed 16.16 fixed-point) +//| :param int ry0: ray y at the left column (signed 16.16 fixed-point) +//| :param int rsx: per-column ray step x (signed 16.16 fixed-point) +//| :param int rsy: per-column ray step y (signed 16.16 fixed-point) +//| :param int cam_x: camera x position (signed 16.16 fixed-point) +//| :param int cam_y: camera y position (signed 16.16 fixed-point)""" +//| ... +//| +static mp_obj_t picogame3d_mode7_fn(size_t n, const mp_obj_t *a) { + picogame_canvas_obj_t *cv = pg3d_canvas(a[0]); + picogame_bitmap_obj_t *tex = MP_OBJ_TO_PTR( + mp_arg_validate_type(a[1], &picogame_bitmap_type, MP_QSTR_texture)); + picogame3d_mode7(cv, tex, + mp_obj_get_int(a[2]), mp_obj_get_int(a[3]), mp_obj_get_int(a[4]), + mp_obj_get_int(a[5]), mp_obj_get_int(a[6]), mp_obj_get_int(a[7]), + mp_obj_get_int(a[8]), mp_obj_get_int(a[9]), mp_obj_get_int(a[10])); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(picogame3d_mode7_obj, 11, 11, picogame3d_mode7_fn); + +//| def road( +//| canvas: picogame.Canvas, +//| ri0: int, +//| tab: ReadableBuffer, +//| rl: ReadableBuffer, +//| rr: ReadableBuffer, +//| d05_q8: int, +//| d07_q8: int, +//| colors: ReadableBuffer, +//| ) -> None: +//| """Draw one racing-road strip into ``canvas`` from precomputed tables. A +//| low-level interface used by the ``picogame_road`` helper, which builds the tables. +//| +//| :param picogame.Canvas canvas: surface to draw into +//| :param int ri0: road-table row of the canvas's row 0; negative values +//| are sky rows +//| :param ~circuitpython_typing.ReadableBuffer tab: ``int16`` rows of +//| ``edge_w``, ``dash_hw``, ``wb05_q8``, ``wb07_q8``, ``flags`` +//| :param ~circuitpython_typing.ReadableBuffer rl: ``int16`` per-row left +//| edges, as computed by :py:func:`road_edges` +//| :param ~circuitpython_typing.ReadableBuffer rr: ``int16`` per-row right +//| edges +//| :param int d05_q8: scroll phase (Q8 fixed-point) +//| :param int d07_q8: scroll phase (Q8 fixed-point) +//| :param ~circuitpython_typing.ReadableBuffer colors: six ``uint16`` colors, +//| in order: sky, road a, road b, rumble a, rumble b, dash""" +//| ... +//| +static mp_obj_t picogame3d_road_fn(size_t n, const mp_obj_t *a) { + picogame_canvas_obj_t *cv = pg3d_canvas(a[0]); + mp_buffer_info_t tabi, rli, rri, coli; + mp_get_buffer_raise(a[2], &tabi, MP_BUFFER_READ); + mp_get_buffer_raise(a[3], &rli, MP_BUFFER_READ); + mp_get_buffer_raise(a[4], &rri, MP_BUFFER_READ); + mp_get_buffer_raise(a[7], &coli, MP_BUFFER_READ); + int ntab = (int)(tabi.len / (5 * 2)); + int nedge = (int)(rli.len < rri.len ? rli.len : rri.len) / 2; + if (nedge < ntab) { + ntab = nedge; // never read past the shorter per-frame arrays + } + if (ntab <= 0 || coli.len < 6 * 2) { + return mp_const_none; + } + picogame3d_road(cv, mp_obj_get_int(a[1]), + (const int16_t *)tabi.buf, ntab, (const int16_t *)rli.buf, (const int16_t *)rri.buf, + mp_obj_get_int(a[5]), mp_obj_get_int(a[6]), (const uint16_t *)coli.buf); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(picogame3d_road_obj, 8, 8, picogame3d_road_fn); + +#if !CIRCUITPY_PICOGAME3D_FLOAT +// ((int64_t)a * b) >> 16 with two 32-bit multiplies. Exact for |b| <= 65536. +static __attribute__((noinline)) int32_t pg_fmul_basis(int32_t a, int32_t b) { + uint32_t hi = (uint32_t)(a >> 16) * (uint32_t)b; // modulo 2^32 on purpose + uint32_t l = (uint32_t)(a & 0xFFFF); + if (b >= 0) { + return (int32_t)(hi + ((l * (uint32_t)b) >> 16)); + } + return (int32_t)(hi - ((l * (uint32_t)(-b) + 0xFFFFu) >> 16)); +} +#endif + +//| def project( +//| cam: ReadableBuffer, +//| pts: ReadableBuffer, +//| n: int, +//| out_sx: WriteableBuffer, +//| out_sy: WriteableBuffer, +//| ) -> None: +//| """Batch-project ``n`` 3D world points to screen coordinates. +//| +//| When :py:data:`FLOAT` is ``1``, ``cam`` and ``pts`` hold ``float32`` elements; +//| otherwise they hold signed 16.16 fixed-point ``int32`` elements. +//| +//| :param ~circuitpython_typing.ReadableBuffer cam: 15 camera parameters, in order: +//| eye x/y/z, right x/z (the camera cannot roll, so right has no y +//| component), up x/y/z, forward x/y/z, focal length, screen center x/y, +//| near-plane distance +//| :param ~circuitpython_typing.ReadableBuffer pts: ``3 * n`` world coordinates +//| (x, y, z per point) +//| :param int n: number of points; limited to what ``pts``, ``out_sx`` and +//| ``out_sy`` hold +//| :param ~circuitpython_typing.WriteableBuffer out_sx: at least ``n`` ``int16`` +//| values; receives screen x, or the sentinel ``-32768`` for a point behind +//| the near plane +//| :param ~circuitpython_typing.WriteableBuffer out_sy: at least ``n`` ``int16`` +//| values; receives screen y, or ``-32768`` for a point behind the near plane""" +//| ... +//| +// project(cam, pts, n, out_sx, out_sy) - batch perspective projection of `n` 3D points to screen. +// cam = 15 camera params: ex,ey,ez, rx,rz, ux,uy,uz, fx,fy,fz, focal, cx0, cy0, near +// pts = n*3 world coords (x,y,z per point) +// out_sx/out_sy = int16 screen coords; a point behind the near plane gets sentinel -32768 +// On an FPU board (CIRCUITPY_PICOGAME3D_FLOAT) cam/pts are float32; else they are 16.16 fixed int32. +// This is the shared hot path for blocky pseudo-3D (project the 8 corners of each box, then fill). +static mp_obj_t picogame3d_project(size_t n_args, const mp_obj_t *args) { + mp_buffer_info_t ci, pi, xi, yi; + mp_get_buffer_raise(args[0], &ci, MP_BUFFER_READ); + mp_get_buffer_raise(args[1], &pi, MP_BUFFER_READ); + int n = mp_obj_get_int(args[2]); + mp_get_buffer_raise(args[3], &xi, MP_BUFFER_WRITE); + mp_get_buffer_raise(args[4], &yi, MP_BUFFER_WRITE); + int16_t *osx = xi.buf; + int16_t *osy = yi.buf; + mp_arg_validate_length_min(ci.len, 15 * 4, MP_QSTR_cam); + // Never read or write past any buffer: 3 four-byte coordinates per point, one int16 per output. + n = picogame_imin(n, (int)(pi.len / 12)); + n = picogame_imin(n, (int)(picogame_imin(xi.len, yi.len) >> 1)); + #if CIRCUITPY_PICOGAME3D_FLOAT + const float *cam = ci.buf; + const float *pts = pi.buf; + float ex = cam[0], ey = cam[1], ez = cam[2]; + float rx = cam[3], rz = cam[4]; + float ux = cam[5], uy = cam[6], uz = cam[7]; + float fx = cam[8], fy = cam[9], fz = cam[10]; + float focal = cam[11], cx0 = cam[12], cy0 = cam[13], near = cam[14]; + for (int i = 0; i < n; i++) { + float X = pts[i * 3] - ex, Y = pts[i * 3 + 1] - ey, Z = pts[i * 3 + 2] - ez; + float cz = X * fx + Y * fy + Z * fz; + if (cz < near) { + osx[i] = -32768; + osy[i] = -32768; + continue; + } + float k = focal / cz; // hardware divide on an FPU part + osx[i] = (int16_t)(cx0 + (X * rx + Z * rz) * k); + osy[i] = (int16_t)(cy0 - (X * ux + Y * uy + Z * uz) * k); + } + #else + const int32_t *cam = ci.buf; // all values 16.16 + const int32_t *pts = pi.buf; + int32_t ex = cam[0], ey = cam[1], ez = cam[2]; + int32_t rx = cam[3], rz = cam[4]; + int32_t ux = cam[5], uy = cam[6], uz = cam[7]; + int32_t fx = cam[8], fy = cam[9], fz = cam[10]; + int32_t focal = cam[11], cx0 = cam[12], cy0 = cam[13], near = cam[14]; + // Full-precision Q16 dot products (int64 mul per term). A Q8-prescaled-basis/MULS variant was + // ~30% faster, but its error grows with |coord| (~0.2%/axis) and k = focal/cz AMPLIFIES it near + // the near plane - host-measured 23-34 px warps on close fly-bys at a file-browser world scale + // (walls visibly broke). Correctness first: Q16 keeps the worst error a few px at any cz >= near, + // for coords up to +-32k units; still ~4-5x faster than the same math in Python on the M0+. + // FMULB: same result as FMUL for |b| <= 65536 (every basis component), without + // __aeabi_lmul. The products by k keep FMUL because k is not bounded. + #define FMUL(a, b) ((int32_t)(((int64_t)(a) * (b)) >> 16)) + #define FMULB(a, b) pg_fmul_basis((a), (b)) + for (int i = 0; i < n; i++) { + int32_t X = pts[i * 3] - ex, Y = pts[i * 3 + 1] - ey, Z = pts[i * 3 + 2] - ez; + int32_t cz = FMULB(X, fx) + FMULB(Y, fy) + FMULB(Z, fz); + if (cz < near) { + osx[i] = -32768; + osy[i] = -32768; + continue; + } + // focal/cz in 16.16. A 32-bit divide (focal<<8 = Q24, cz>>8 = Q8 -> Q16) is ~4x cheaper than + // an int64 divide on the M0+ (no HW divide) and the lost cz precision costs <0.02 px (host- + // measured). Needs FOCAL < ~250 (focal<<8 in uint32) and near >= 1/256 (cz>>8 nonzero). + int32_t k = (int32_t)(((uint32_t)focal << 8) / (uint32_t)(cz >> 8)); + int32_t rr = FMULB(X, rx) + FMULB(Z, rz); + int32_t uu = FMULB(X, ux) + FMULB(Y, uy) + FMULB(Z, uz); + osx[i] = (int16_t)((cx0 + FMUL(rr, k)) >> 16); + osy[i] = (int16_t)((cy0 - FMUL(uu, k)) >> 16); + } +#undef FMUL +#undef FMULB + #endif + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(picogame3d_project_obj, 5, 5, picogame3d_project); + +//| def raycast( +//| map: ReadableBuffer, +//| mw: int, +//| mh: int, +//| posx: int, +//| posy: int, +//| lrx: int, +//| lry: int, +//| srx: int, +//| sry: int, +//| sh: int, +//| stride: int, +//| ncols: int, +//| wcolors: ReadableBuffer, +//| top: WriteableBuffer, +//| bot: WriteableBuffer, +//| col: WriteableBuffer, +//| dist: WriteableBuffer, +//| runs: Optional[WriteableBuffer] = None, +//| ) -> Optional[int]: +//| """Cast one frame of wall-finding rays across the screen columns of a +//| grid-map view. A low-level interface used by the ``picogame_ray`` helper, +//| which computes these inputs. +//| +//| All fixed-point arguments are signed 16.16 integers. +//| +//| :param ~circuitpython_typing.ReadableBuffer map: at least ``mw * mh`` wall-type +//| bytes, row-major; 0 is empty +//| :param int mw: map width in cells +//| :param int mh: map height in cells +//| :param int posx: camera x position (fixed-point) +//| :param int posy: camera y position (fixed-point) +//| :param int lrx: x of the column-0 ray direction (fixed-point) +//| :param int lry: y of the column-0 ray direction (fixed-point) +//| :param int srx: per-column ray step x (fixed-point) +//| :param int sry: per-column ray step y (fixed-point) +//| :param int sh: screen height in pixels +//| :param int stride: pixel width of one column +//| :param int ncols: number of columns to cast; limited to what the output +//| buffers hold +//| :param ~circuitpython_typing.ReadableBuffer wcolors: two ``uint16`` colors per +//| wall type: near face at ``[type * 2]``, side face at ``[type * 2 + 1]``; +//| at least types 0 and 1, and an unknown type uses type 1 +//| :param ~circuitpython_typing.WriteableBuffer top: at least ``ncols`` ``uint16`` +//| values; receives each column's wall top row +//| :param ~circuitpython_typing.WriteableBuffer bot: at least ``ncols`` ``uint16`` +//| values; receives each column's wall bottom row +//| :param ~circuitpython_typing.WriteableBuffer col: at least ``ncols`` ``uint16`` +//| values; receives each column's wall color +//| :param ~circuitpython_typing.WriteableBuffer dist: at least ``ncols`` ``int32`` +//| values; receives each column's perpendicular distance (fixed-point) +//| :param ~circuitpython_typing.WriteableBuffer runs: optional; at least +//| ``5 * ncols`` ``uint16`` values, laid out as five ``ncols``-long planes +//| (x0s, x1s, tops, bots, colors). When given, adjacent equal columns are +//| merged into wall runs suitable for :py:meth:`picogame.Canvas.vspans` and the +//| run count is returned; otherwise `None` is returned.""" +//| ... +//| +// C DDA wall raycaster for picogame_ray.Raycaster - INTEGER ONLY (16.16 fixed-point, no FPU; the paint, +// temporal invalidate, pose-cache and billboard math stay in Python; Python does the once-per-frame +// trig and passes Q16 ray params). map: read-only bytes, mw*mh wall types (0 = empty). pos*, l*x/l*y +// (leftRay, column 0), s*x/s*y (rayStep per column) are all 16.16. wcolors: uint16[(maxtype+1)*2] - +// [t*2] near, [t*2+1] side colour. top/bot/col: uint16 write buffers (len>=ncols); dist: int32 write +// buffer (perpendicular distance, 16.16). All arithmetic is 32-bit. +// Optional arg 17 (runs - ONE uint16 write buffer, len>=5*ncols, laid out as five ncols-long +// planes [x0s | x1s | tops | bots | colors]): also emit the RLE-MERGED wall runs (adjacent equal +// columns fused; x in PIXELS = column*stride) and return the run count. The planes feed +// Canvas.vspans directly as memoryview slices. This hoists picogame_ray's per-frame Python merge +// loop into the same C pass (measured 2-6.5 ms/frame of interpreted merge at stride=1 on RP2040). +// Callers clamp the LAST run's x1 to the screen width (stride rounding can overshoot by = 1. +static inline uint32_t pg_recip32(uint32_t v) { + return (uint32_t)(0u - v) / v + 1u; +} + +static mp_obj_t picogame3d_raycast(size_t n_args, const mp_obj_t *args) { + mp_buffer_info_t mi, wi, ti, bi, ci, di; + mp_get_buffer_raise(args[0], &mi, MP_BUFFER_READ); + // Non-negative: the DDA below bounds-checks with unsigned compares. + int mw = picogame_imax(mp_obj_get_int(args[1]), 0); + // Unsigned: cells past mw * mh or past the map buffer read as wall. + unsigned cells = (unsigned)picogame_imax(mp_obj_get_int(args[2]), 0) * (unsigned)mw; + int32_t posx = mp_obj_get_int(args[3]); // camera x, 16.16 + int32_t posy = mp_obj_get_int(args[4]); + int32_t rdx = mp_obj_get_int(args[5]); // leftRay x (column 0), 16.16 - accumulates per column + int32_t rdy = mp_obj_get_int(args[6]); + int32_t srx = mp_obj_get_int(args[7]); // rayStep x per column, 16.16 + int32_t sry = mp_obj_get_int(args[8]); + int sh = mp_obj_get_int(args[9]); + int stride = mp_obj_get_int(args[10]); + int ncols = mp_obj_get_int(args[11]); + mp_get_buffer_raise(args[12], &wi, MP_BUFFER_READ); + mp_get_buffer_raise(args[13], &ti, MP_BUFFER_WRITE); + mp_get_buffer_raise(args[14], &bi, MP_BUFFER_WRITE); + mp_get_buffer_raise(args[15], &ci, MP_BUFFER_WRITE); + mp_get_buffer_raise(args[16], &di, MP_BUFFER_WRITE); + uint16_t *r0 = NULL, *r1 = NULL, *rt = NULL, *rb = NULL, *rcol = NULL; + if (n_args >= 18) { // run outputs requested + mp_buffer_info_t q; + mp_get_buffer_raise(args[17], &q, MP_BUFFER_WRITE); + int cap = (int)(q.len / 10); // five uint16 planes + if (ncols > cap) { + ncols = cap; // never write past the run planes + } + r0 = q.buf; + r1 = r0 + cap; + rt = r1 + cap; + rb = rt + cap; + rcol = rb + cap; + } + const uint8_t *map = mi.buf; + const uint16_t *wc = wi.buf; + // An unknown wall type falls back to type 1, so wcolors must hold types 0 and 1. + int wc_types = (int)(mp_arg_validate_length_min(wi.len, 2 * 4, MP_QSTR_wcolors) >> 2); + if (cells > mi.len) { + cells = mi.len; + } + uint16_t *top = ti.buf; + uint16_t *bot = bi.buf; + uint16_t *col = ci.buf; + int32_t *dist_out = di.buf; // perpendicular distance, 16.16 + int half = sh >> 1; + int imapx0 = posx >> 16; + int imapy0 = posy >> 16; + int off0 = imapy0 * mw + imapx0; // every column starts from the same cell + int32_t fracx = posx & 0xFFFF; // fractional part of pos, 16.16 + int32_t fracy = posy & 0xFFFF; + const int32_t DD_CAP = (int32_t)1 << 24; // cap deltaDist so a 64-step accumulation stays in int32 + ncols = picogame_imin(ncols, (int)(picogame_imin(picogame_imin(ti.len, bi.len), ci.len) >> 1)); + ncols = picogame_imin(ncols, (int)(di.len >> 2)); + for (int c = 0; c < ncols; c++) { + int mapx = imapx0; + int mapy = imapy0; + int32_t ax = rdx < 0 ? -rdx : rdx; + int32_t ay = rdy < 0 ? -rdy : rdy; + // deltaDist = 2^32 / |rayDir|, capped at DD_CAP. ax < 256 is exactly the capped + // range, so the test also guards against ax == 0. + int32_t ddx = (ax < 256) ? DD_CAP : (int32_t)pg_recip32((uint32_t)ax); + int32_t ddy = (ay < 256) ? DD_CAP : (int32_t)pg_recip32((uint32_t)ay); + int stepx, stepy; + int32_t sidex, sidey; + // sideDist to the first grid line = (fractional distance) * deltaDist, 16.16 (setup only) + if (rdx < 0) { + stepx = -1; + sidex = pg_mulshr16((uint32_t)fracx, (uint32_t)ddx); + } else { + stepx = 1; + sidex = pg_mulshr16((uint32_t)(65536 - fracx), (uint32_t)ddx); + } + if (rdy < 0) { + stepy = -1; + sidey = pg_mulshr16((uint32_t)fracy, (uint32_t)ddy); + } else { + stepy = 1; + sidey = pg_mulshr16((uint32_t)(65536 - fracy), (uint32_t)ddy); + } + int side = 0; + int cell = 1; + // Linear map offset, stepped with the cell coordinates. + int off = off0; + int stepy_off = stepy * mw; + for (int i = 0; i < 64; i++) { // DDA - pure 32-bit + if (sidex < sidey) { + sidex += ddx; + mapx += stepx; + off += stepx; + side = 0; + } else { + sidey += ddy; + mapy += stepy; + off += stepy_off; + side = 1; + } + // Unsigned compares also reject negative coordinates. + cell = ((unsigned)mapx < (unsigned)mw && (unsigned)off < cells) + ? map[off] : 1; + if (cell) { + break; + } + } + int32_t perp = (side == 0) ? (sidex - ddx) : (sidey - ddy); // perpWallDist, 16.16 + if (perp < 655) { + perp = 655; // ~0.01 in 16.16 + } + int lh = (int)(((int32_t)sh << 16) / perp); // sh / perpWallDist (px); 32-bit (sh<<16 <= ~15.7M) + int t = half - (lh >> 1); + int b = t + lh; + if (t < 0) { + t = 0; + } + if (b > sh) { + b = sh; + } + top[c] = (uint16_t)t; + bot[c] = (uint16_t)b; + int ct = (cell < wc_types) ? cell : 1; // unknown type -> type 1 (matches Python default) + col[c] = wc[ct * 2 + side]; + dist_out[c] = perp; + rdx += srx; // accumulate ray direction for the next column (no overflow) + rdy += sry; + } + if (r0 && ncols > 0) { + // post-pass RLE over the just-written (cache-hot) column arrays: one flush point + int nr = 0; + int rstart = 0; + for (int c = 1; c <= ncols; c++) { + if (c == ncols || top[c] != top[rstart] || bot[c] != bot[rstart] || col[c] != col[rstart]) { + r0[nr] = (uint16_t)(rstart * stride); + r1[nr] = (uint16_t)(c * stride); + rt[nr] = top[rstart]; + rb[nr] = bot[rstart]; + rcol[nr] = col[rstart]; + nr++; + rstart = c; + } + } + return MP_OBJ_NEW_SMALL_INT(nr); + } + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(picogame3d_raycast_obj, 17, 18, picogame3d_raycast); + +//| def road_edges( +//| rl: WriteableBuffer, +//| rr: WriteableBuffer, +//| hw: ReadableBuffer, +//| n: int, +//| cx0: int, +//| dist: int, +//| cfg: ReadableBuffer, +//| ) -> None: +//| """Compute one racing-road frame's left and right edge columns. A low-level +//| interface used by the ``picogame_road`` helper, which packs these inputs. +//| +//| Walks ``n`` screen rows bottom-up, accumulating the road curve, and writes the +//| edge x coordinates into ``rl`` and ``rr``. +//| +//| :param ~circuitpython_typing.WriteableBuffer rl: at least ``n`` ``int16`` values; +//| receives the left edge per row +//| :param ~circuitpython_typing.WriteableBuffer rr: at least ``n`` ``int16`` values; +//| receives the right edge per row +//| :param ~circuitpython_typing.ReadableBuffer hw: at least ``n`` ``int32`` per-row +//| half-widths (signed 16.16 fixed-point) +//| :param int n: number of rows to compute +//| :param int cx0: screen center x including lateral offset (signed 16.16 fixed-point) +//| :param int dist: integer world distance +//| :param ~circuitpython_typing.ReadableBuffer cfg: seven ``int32`` curve parameters, +//| in order: ``f1_q20``, ``f2_q20``, ``amp1k_q16``, ``amp2k_q16``, ``world_step``, +//| ``curve_step``, ``d_row_off``""" +//| ... +//| +// road_edges(rl, rr, hw, n, cx0, dist, cfg) - one racing-road frame's curve accumulator + integer +// edges in one call (the OutRun-genre compute_road loop; core + cfg layout documented in +// shared-module). rl/rr = int16 out, hw = int32 Q16 half-widths, cx0 = Q16 screen centre +// (incl. lateral), dist = integer world distance, cfg = int32[7]. +static mp_obj_t picogame3d_road_edges_fn(size_t n_args, const mp_obj_t *args) { + mp_buffer_info_t rli, rri, hwi, cfgi; + mp_get_buffer_raise(args[0], &rli, MP_BUFFER_WRITE); + mp_get_buffer_raise(args[1], &rri, MP_BUFFER_WRITE); + mp_get_buffer_raise(args[2], &hwi, MP_BUFFER_READ); + mp_get_buffer_raise(args[6], &cfgi, MP_BUFFER_READ); + int n = mp_obj_get_int(args[3]); + int cap = (int)(rli.len < rri.len ? rli.len : rri.len) / 2; + if (n > cap) { + n = cap; + } + if (n > (int)(hwi.len / 4)) { + n = (int)(hwi.len / 4); + } + if (n <= 0 || cfgi.len < 7 * 4) { + return mp_const_none; + } + picogame3d_road_edges((int16_t *)rli.buf, (int16_t *)rri.buf, (const int32_t *)hwi.buf, n, + mp_obj_get_int(args[4]), mp_obj_get_int(args[5]), (const int32_t *)cfgi.buf); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(picogame3d_road_edges_obj, 7, 7, picogame3d_road_edges_fn); + +static const mp_rom_map_elem_t picogame3d_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_picogame3d) }, + { MP_ROM_QSTR(MP_QSTR_mode7), MP_ROM_PTR(&picogame3d_mode7_obj) }, + { MP_ROM_QSTR(MP_QSTR_road), MP_ROM_PTR(&picogame3d_road_obj) }, + { MP_ROM_QSTR(MP_QSTR_road_edges), MP_ROM_PTR(&picogame3d_road_edges_obj) }, + { MP_ROM_QSTR(MP_QSTR_raycast), MP_ROM_PTR(&picogame3d_raycast_obj) }, + { MP_ROM_QSTR(MP_QSTR_project), MP_ROM_PTR(&picogame3d_project_obj) }, + { MP_ROM_QSTR(MP_QSTR_FLOAT), MP_ROM_INT(CIRCUITPY_PICOGAME3D_FLOAT) }, +}; +static MP_DEFINE_CONST_DICT(picogame3d_module_globals, picogame3d_module_globals_table); + +const mp_obj_module_t picogame3d_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&picogame3d_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_picogame3d, picogame3d_module); diff --git a/shared-bindings/ps2io/Ps2.c b/shared-bindings/ps2io/Ps2.c index 8766ea7a2a1..eb61ef07f11 100644 --- a/shared-bindings/ps2io/Ps2.c +++ b/shared-bindings/ps2io/Ps2.c @@ -57,8 +57,7 @@ static mp_obj_t ps2io_ps2_make_new(const mp_obj_type_t *type, size_t n_args, siz const mcu_pin_obj_t *clock_pin = validate_obj_is_free_pin(args[ARG_clock_pin].u_obj, MP_QSTR_clock_pin); const mcu_pin_obj_t *data_pin = validate_obj_is_free_pin(args[ARG_data_pin].u_obj, MP_QSTR_data_pin); - ps2io_ps2_obj_t *self = mp_obj_malloc(ps2io_ps2_obj_t, &ps2io_ps2_type); - + ps2io_ps2_obj_t *self = mp_obj_malloc_with_finaliser(ps2io_ps2_obj_t, &ps2io_ps2_type); common_hal_ps2io_ps2_construct(self, data_pin, clock_pin); return MP_OBJ_FROM_PTR(self); @@ -198,6 +197,7 @@ static mp_obj_t ps2_unary_op(mp_unary_op_t op, mp_obj_t self_in) { static const mp_rom_map_elem_t ps2io_ps2_locals_dict_table[] = { // Methods { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&ps2io_ps2_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&ps2io_ps2_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, { MP_ROM_QSTR(MP_QSTR_popleft), MP_ROM_PTR(&ps2io_ps2_popleft_obj) }, diff --git a/shared-bindings/pulseio/PulseIn.c b/shared-bindings/pulseio/PulseIn.c index d9e6bfd7aec..830f7b7c62c 100644 --- a/shared-bindings/pulseio/PulseIn.c +++ b/shared-bindings/pulseio/PulseIn.c @@ -69,7 +69,6 @@ static mp_obj_t pulseio_pulsein_make_new(const mp_obj_type_t *type, size_t n_arg const mcu_pin_obj_t *pin = validate_obj_is_free_pin(args[ARG_pin].u_obj, MP_QSTR_pin); pulseio_pulsein_obj_t *self = mp_obj_malloc_with_finaliser(pulseio_pulsein_obj_t, &pulseio_pulsein_type); - common_hal_pulseio_pulsein_construct(self, pin, args[ARG_maxlen].u_int, args[ARG_idle_state].u_bool); diff --git a/shared-bindings/pulseio/PulseOut.c b/shared-bindings/pulseio/PulseOut.c index 947aa4b518e..58c98b8e2cc 100644 --- a/shared-bindings/pulseio/PulseOut.c +++ b/shared-bindings/pulseio/PulseOut.c @@ -62,6 +62,7 @@ static mp_obj_t pulseio_pulseout_make_new(const mp_obj_type_t *type, size_t n_ar pulseio_pulseout_obj_t *self = mp_obj_malloc_with_finaliser(pulseio_pulseout_obj_t, &pulseio_pulseout_type); common_hal_pulseio_pulseout_construct(self, pin, frequency, duty_cycle); + return MP_OBJ_FROM_PTR(self); #else mp_raise_NotImplementedError(NULL); diff --git a/shared-bindings/pwmio/PWMOut.c b/shared-bindings/pwmio/PWMOut.c index 97dbd2079f7..7cfb0d8a13f 100644 --- a/shared-bindings/pwmio/PWMOut.c +++ b/shared-bindings/pwmio/PWMOut.c @@ -25,14 +25,8 @@ void common_hal_pwmio_pwmout_raise_error(pwmout_result_t result) { case PWMOUT_INVALID_FREQUENCY: mp_arg_error_invalid(MP_QSTR_frequency); break; - case PWMOUT_INVALID_FREQUENCY_ON_PIN: - mp_arg_error_invalid(MP_QSTR_frequency); - break; - case PWMOUT_VARIABLE_FREQUENCY_NOT_AVAILABLE: - mp_arg_error_invalid(MP_QSTR_variable_frequency); - break; case PWMOUT_INTERNAL_RESOURCES_IN_USE: - mp_raise_RuntimeError(MP_ERROR_TEXT("Internal resource(s) in use")); + mp_raise_RuntimeError(MP_ERROR_TEXT("Conflicting settings for shared resource")); break; default: case PWMOUT_INITIALIZATION_ERROR: @@ -145,7 +139,8 @@ static mp_obj_t pwmio_pwmout_make_new(const mp_obj_type_t *type, size_t n_args, const mcu_pin_obj_t *pin = validate_obj_is_free_pin(parsed_args[ARG_pin].u_obj, MP_QSTR_pin); - uint16_t duty_cycle = parsed_args[ARG_duty_cycle].u_int; + uint16_t duty_cycle = (uint16_t)mp_arg_validate_int_range( + parsed_args[ARG_duty_cycle].u_int, 0, 0xffff, MP_QSTR_duty_cycle); uint32_t frequency = parsed_args[ARG_frequency].u_int; bool variable_frequency = parsed_args[ARG_variable_frequency].u_bool; diff --git a/shared-bindings/pwmio/PWMOut.h b/shared-bindings/pwmio/PWMOut.h index d8bab978228..0a4f099e272 100644 --- a/shared-bindings/pwmio/PWMOut.h +++ b/shared-bindings/pwmio/PWMOut.h @@ -15,8 +15,6 @@ typedef enum pwmout_result_t { PWMOUT_OK, PWMOUT_INVALID_PIN, PWMOUT_INVALID_FREQUENCY, - PWMOUT_INVALID_FREQUENCY_ON_PIN, - PWMOUT_VARIABLE_FREQUENCY_NOT_AVAILABLE, PWMOUT_INTERNAL_RESOURCES_IN_USE, PWMOUT_INITIALIZATION_ERROR, } pwmout_result_t; @@ -35,8 +33,4 @@ extern bool common_hal_pwmio_pwmout_get_variable_frequency(pwmio_pwmout_obj_t *s // Don't use this! It is only used internally for backwards compatibility. extern const mcu_pin_obj_t *common_hal_pwmio_pwmout_get_pin(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); -extern void common_hal_pwmio_pwmout_reset_ok(pwmio_pwmout_obj_t *self); - extern void common_hal_pwmio_pwmout_raise_error(pwmout_result_t result); diff --git a/shared-bindings/qrio/QRDecoder.c b/shared-bindings/qrio/QRDecoder.c index 6a36d8b0265..e8977bc1efe 100644 --- a/shared-bindings/qrio/QRDecoder.c +++ b/shared-bindings/qrio/QRDecoder.c @@ -34,7 +34,7 @@ static mp_obj_t qrio_qrdecoder_make_new(const mp_obj_type_t *type, size_t n_args qrio_qrdecoder_obj_t *self = mp_obj_malloc(qrio_qrdecoder_obj_t, &qrio_qrdecoder_type_obj); shared_module_qrio_qrdecoder_construct(self, args[ARG_width].u_int, args[ARG_height].u_int); - return self; + return MP_OBJ_FROM_PTR(self); } diff --git a/shared-bindings/qspibus/QSPIBus.c b/shared-bindings/qspibus/QSPIBus.c new file mode 100644 index 00000000000..24c3089213f --- /dev/null +++ b/shared-bindings/qspibus/QSPIBus.c @@ -0,0 +1,199 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// SPDX-FileCopyrightText: Copyright (c) 2026 Przemyslaw Patrick Socha +// SPDX-License-Identifier: MIT + +#include + +#include "shared-bindings/qspibus/QSPIBus.h" + +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/util.h" +#include "shared-module/displayio/__init__.h" + +#include "py/binary.h" +#include "py/obj.h" +#include "py/runtime.h" + +static void check_for_deinit(qspibus_qspibus_obj_t *self) { + if (common_hal_qspibus_qspibus_deinited(self)) { + raise_deinited_error(); + } +} + +//| class QSPIBus: +//| """QSPI bus for quad-SPI displays.""" +//| +//| def __init__( +//| self, +//| *, +//| clock: microcontroller.Pin, +//| data0: microcontroller.Pin, +//| data1: microcontroller.Pin, +//| data2: microcontroller.Pin, +//| data3: microcontroller.Pin, +//| cs: microcontroller.Pin, +//| dcx: Optional[microcontroller.Pin] = None, +//| reset: Optional[microcontroller.Pin] = None, +//| frequency: int = 80_000_000, +//| ) -> None: +//| """Create a QSPIBus object for quad-SPI display communication. +//| +//| :param ~microcontroller.Pin clock: QSPI clock pin +//| :param ~microcontroller.Pin data0: QSPI data line 0 +//| :param ~microcontroller.Pin data1: QSPI data line 1 +//| :param ~microcontroller.Pin data2: QSPI data line 2 +//| :param ~microcontroller.Pin data3: QSPI data line 3 +//| :param ~microcontroller.Pin cs: Chip select pin +//| :param ~microcontroller.Pin dcx: Optional data/command select pin. +//| Reserved for future hardware paths. Current ESP32-S3 implementation +//| uses encoded QSPI command words and does not require explicit DCX. +//| :param ~microcontroller.Pin reset: Optional reset pin +//| :param int frequency: Bus frequency in Hz (1-80MHz) +//| """ +//| ... +//| +static mp_obj_t qspibus_qspibus_make_new(const mp_obj_type_t *type, size_t n_args, + size_t n_kw, const mp_obj_t *all_args) { + + enum { ARG_clock, ARG_data0, ARG_data1, ARG_data2, ARG_data3, ARG_cs, ARG_dcx, ARG_reset, ARG_frequency }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_clock, MP_ARG_KW_ONLY | MP_ARG_OBJ | MP_ARG_REQUIRED }, + { MP_QSTR_data0, MP_ARG_KW_ONLY | MP_ARG_OBJ | MP_ARG_REQUIRED }, + { MP_QSTR_data1, MP_ARG_KW_ONLY | MP_ARG_OBJ | MP_ARG_REQUIRED }, + { MP_QSTR_data2, MP_ARG_KW_ONLY | MP_ARG_OBJ | MP_ARG_REQUIRED }, + { MP_QSTR_data3, MP_ARG_KW_ONLY | MP_ARG_OBJ | MP_ARG_REQUIRED }, + { MP_QSTR_cs, MP_ARG_KW_ONLY | MP_ARG_OBJ | MP_ARG_REQUIRED }, + { MP_QSTR_dcx, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, + { MP_QSTR_reset, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, + { MP_QSTR_frequency, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 80000000} }, + }; + + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_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, MP_QSTR_clock); + const mcu_pin_obj_t *data0 = validate_obj_is_free_pin(args[ARG_data0].u_obj, MP_QSTR_data0); + const mcu_pin_obj_t *data1 = validate_obj_is_free_pin(args[ARG_data1].u_obj, MP_QSTR_data1); + const mcu_pin_obj_t *data2 = validate_obj_is_free_pin(args[ARG_data2].u_obj, MP_QSTR_data2); + const mcu_pin_obj_t *data3 = validate_obj_is_free_pin(args[ARG_data3].u_obj, MP_QSTR_data3); + const mcu_pin_obj_t *cs = validate_obj_is_free_pin(args[ARG_cs].u_obj, MP_QSTR_cs); + const mcu_pin_obj_t *dcx = validate_obj_is_free_pin_or_none(args[ARG_dcx].u_obj, MP_QSTR_dcx); + const mcu_pin_obj_t *reset = validate_obj_is_free_pin_or_none(args[ARG_reset].u_obj, MP_QSTR_reset); + + uint32_t frequency = (uint32_t)mp_arg_validate_int_range(args[ARG_frequency].u_int, 1, 80000000, MP_QSTR_frequency); + + qspibus_qspibus_obj_t *self = &allocate_display_bus_or_raise()->qspi_bus; + self->base.type = &qspibus_qspibus_type; + common_hal_qspibus_qspibus_construct(self, clock, data0, data1, data2, data3, cs, dcx, reset, frequency); + + return MP_OBJ_FROM_PTR(self); +} + +//| def reset(self) -> None: +//| """Perform a hardware reset using the reset pin. +//| +//| :raises RuntimeError: if no reset pin was provided at construction. +//| """ +//| ... +//| +static mp_obj_t qspibus_qspibus_obj_reset(mp_obj_t self_in) { + qspibus_qspibus_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + if (!common_hal_qspibus_qspibus_reset(MP_OBJ_FROM_PTR(self))) { + mp_raise_RuntimeError_varg(MP_ERROR_TEXT("No %q pin"), MP_QSTR_reset); + } + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(qspibus_qspibus_reset_obj, qspibus_qspibus_obj_reset); + +//| def send( +//| self, command: int, data: ReadableBuffer, *, toggle_every_byte: bool = False +//| ) -> None: +//| """Sends the given command value followed by the full set of data. Display state, such as +//| vertical scroll, set via ``send`` may or may not be reset once the code is done.""" +//| ... +//| +static mp_obj_t qspibus_qspibus_send(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_command, ARG_data }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_command, MP_ARG_INT | MP_ARG_REQUIRED }, + { MP_QSTR_data, MP_ARG_OBJ | MP_ARG_REQUIRED }, + }; + + 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); + + qspibus_qspibus_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]); + check_for_deinit(self); + + uint8_t command = (uint8_t)mp_arg_validate_int_range(args[ARG_command].u_int, 0, 255, MP_QSTR_command); + + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(args[ARG_data].u_obj, &bufinfo, MP_BUFFER_READ); + + // Flush any pending command from a prior write_command() call. + // begin_transaction() returns false while has_pending_command is set, + // so entering the wait loop without flushing would spin forever. + if (self->has_pending_command) { + common_hal_qspibus_qspibus_write_data(self, NULL, 0); + } + + // Wait for display bus to be available, then acquire transaction. + while (!common_hal_qspibus_qspibus_begin_transaction(MP_OBJ_FROM_PTR(self))) { + RUN_BACKGROUND_TASKS; + } + common_hal_qspibus_qspibus_send(MP_OBJ_FROM_PTR(self), DISPLAY_COMMAND, CHIP_SELECT_UNTOUCHED, &command, 1); + common_hal_qspibus_qspibus_send(MP_OBJ_FROM_PTR(self), DISPLAY_DATA, CHIP_SELECT_UNTOUCHED, ((uint8_t *)bufinfo.buf), bufinfo.len); + common_hal_qspibus_qspibus_end_transaction(MP_OBJ_FROM_PTR(self)); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_KW(qspibus_qspibus_send_obj, 1, qspibus_qspibus_send); + +//| def write_command(self, command: int) -> None: +//| """Stage a command byte for subsequent :py:meth:`write_data`. +//| +//| If a previously staged command had no data, it is sent as +//| a command-only transaction before staging the new one. +//| """ +//| ... +//| +static mp_obj_t qspibus_qspibus_write_command(mp_obj_t self_in, mp_obj_t command_obj) { + qspibus_qspibus_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + + uint8_t command = (uint8_t)mp_arg_validate_int_range(mp_obj_get_int(command_obj), 0, 255, MP_QSTR_command); + common_hal_qspibus_qspibus_write_command(self, command); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(qspibus_qspibus_write_command_obj, qspibus_qspibus_write_command); + +//| def write_data(self, data: ReadableBuffer) -> None: +//| """Send payload bytes for the most recently staged command.""" +//| ... +//| +static mp_obj_t qspibus_qspibus_write_data(mp_obj_t self_in, mp_obj_t data_obj) { + qspibus_qspibus_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(data_obj, &bufinfo, MP_BUFFER_READ); + common_hal_qspibus_qspibus_write_data(self, (const uint8_t *)bufinfo.buf, bufinfo.len); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(qspibus_qspibus_write_data_obj, qspibus_qspibus_write_data); + +static const mp_rom_map_elem_t qspibus_qspibus_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_reset), MP_ROM_PTR(&qspibus_qspibus_reset_obj) }, + { MP_ROM_QSTR(MP_QSTR_send), MP_ROM_PTR(&qspibus_qspibus_send_obj) }, + { MP_ROM_QSTR(MP_QSTR_write_command), MP_ROM_PTR(&qspibus_qspibus_write_command_obj) }, + { MP_ROM_QSTR(MP_QSTR_write_data), MP_ROM_PTR(&qspibus_qspibus_write_data_obj) }, +}; +static MP_DEFINE_CONST_DICT(qspibus_qspibus_locals_dict, qspibus_qspibus_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + qspibus_qspibus_type, + MP_QSTR_QSPIBus, + MP_TYPE_FLAG_NONE, + make_new, qspibus_qspibus_make_new, + locals_dict, &qspibus_qspibus_locals_dict + ); diff --git a/shared-bindings/qspibus/QSPIBus.h b/shared-bindings/qspibus/QSPIBus.h new file mode 100644 index 00000000000..140b639279d --- /dev/null +++ b/shared-bindings/qspibus/QSPIBus.h @@ -0,0 +1,53 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// SPDX-FileCopyrightText: Copyright (c) 2026 Przemyslaw Patrick Socha +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include + +#include "py/obj.h" + +#include "shared-bindings/displayio/__init__.h" + +#include "common-hal/microcontroller/Pin.h" +#include "common-hal/qspibus/QSPIBus.h" + +extern const mp_obj_type_t qspibus_qspibus_type; + +void common_hal_qspibus_qspibus_construct( + qspibus_qspibus_obj_t *self, + const mcu_pin_obj_t *clock, + const mcu_pin_obj_t *data0, + const mcu_pin_obj_t *data1, + const mcu_pin_obj_t *data2, + const mcu_pin_obj_t *data3, + const mcu_pin_obj_t *cs, + const mcu_pin_obj_t *dcx, + const mcu_pin_obj_t *reset, + uint32_t frequency); + +void common_hal_qspibus_qspibus_deinit(qspibus_qspibus_obj_t *self); +bool common_hal_qspibus_qspibus_deinited(qspibus_qspibus_obj_t *self); + +void common_hal_qspibus_qspibus_write_command( + qspibus_qspibus_obj_t *self, + uint8_t command); +void common_hal_qspibus_qspibus_write_data( + qspibus_qspibus_obj_t *self, + const uint8_t *data, + size_t len); + +bool common_hal_qspibus_qspibus_reset(mp_obj_t obj); +bool common_hal_qspibus_qspibus_bus_free(mp_obj_t obj); +bool common_hal_qspibus_qspibus_begin_transaction(mp_obj_t obj); +void common_hal_qspibus_qspibus_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); +void common_hal_qspibus_qspibus_end_transaction(mp_obj_t obj); +void common_hal_qspibus_qspibus_flush(mp_obj_t obj); +void common_hal_qspibus_qspibus_collect_ptrs(mp_obj_t obj); diff --git a/shared-bindings/qspibus/__init__.c b/shared-bindings/qspibus/__init__.c new file mode 100644 index 00000000000..591825c40eb --- /dev/null +++ b/shared-bindings/qspibus/__init__.c @@ -0,0 +1,51 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// SPDX-FileCopyrightText: Copyright (c) 2026 Przemyslaw Patrick Socha +// SPDX-License-Identifier: MIT + +#include "py/obj.h" +#include "py/runtime.h" + +#include "shared-bindings/qspibus/__init__.h" +#include "shared-bindings/qspibus/QSPIBus.h" + +//| """QSPI bus protocol for quad-SPI displays +//| +//| The `qspibus` module provides a low-level QSPI bus interface for displays +//| that use four data lines. It is analogous to `fourwire` for standard SPI. +//| +//| Use :class:`qspibus.QSPIBus` to create a bus instance. +//| +//| Example usage:: +//| +//| import board +//| import qspibus +//| import supervisor +//| +//| if supervisor.runtime.display: +//| supervisor.runtime.display.deinit() +//| +//| bus = qspibus.QSPIBus( +//| clock=board.LCD_CLK, +//| data0=board.LCD_D0, +//| data1=board.LCD_D1, +//| data2=board.LCD_D2, +//| data3=board.LCD_D3, +//| cs=board.LCD_CS, +//| reset=board.LCD_RESET, +//| frequency=80_000_000, +//| ) +//| """ + +static const mp_rom_map_elem_t qspibus_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_qspibus) }, + { MP_ROM_QSTR(MP_QSTR_QSPIBus), MP_ROM_PTR(&qspibus_qspibus_type) }, +}; + +static MP_DEFINE_CONST_DICT(qspibus_module_globals, qspibus_module_globals_table); + +const mp_obj_module_t qspibus_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&qspibus_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_qspibus, qspibus_module); diff --git a/shared-bindings/qspibus/__init__.h b/shared-bindings/qspibus/__init__.h new file mode 100644 index 00000000000..9b4ca243327 --- /dev/null +++ b/shared-bindings/qspibus/__init__.h @@ -0,0 +1,8 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// SPDX-FileCopyrightText: Copyright (c) 2026 Przemyslaw Patrick Socha +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" +#include "shared-bindings/qspibus/QSPIBus.h" diff --git a/shared-bindings/rainbowio/__init__.c b/shared-bindings/rainbowio/__init__.c index a085669d7ff..e02df713eeb 100644 --- a/shared-bindings/rainbowio/__init__.c +++ b/shared-bindings/rainbowio/__init__.c @@ -16,7 +16,8 @@ //| //| def colorwheel(n: float) -> int: //| """C implementation of the common colorwheel() function found in many examples. -//| Returns the colorwheel RGB value as an integer value for n (usable in neopixel and dotstar). +//| Takes a hue, a value between 0-255, and returns an RGB tuple encoded as an +//| integer value (usable in neopixel and dotstar). //| """ //| ... //| diff --git a/shared-bindings/random/__init__.c b/shared-bindings/random/__init__.c index 81201e6f8ab..d3bcd29c9d9 100644 --- a/shared-bindings/random/__init__.c +++ b/shared-bindings/random/__init__.c @@ -116,7 +116,7 @@ static mp_obj_t random_randint(mp_obj_t a_in, mp_obj_t b_in) { if (a > b) { mp_raise_ValueError(NULL); } - return mp_obj_new_int(shared_modules_random_randrange(a, b + 1, 1)); + return mp_obj_new_int(shared_modules_random_randint(a, b)); } static MP_DEFINE_CONST_FUN_OBJ_2(random_randint_obj, random_randint); diff --git a/shared-bindings/random/__init__.h b/shared-bindings/random/__init__.h index 27f255d5d8b..288805b3706 100644 --- a/shared-bindings/random/__init__.h +++ b/shared-bindings/random/__init__.h @@ -13,5 +13,7 @@ void shared_modules_random_seed(mp_uint_t seed); mp_uint_t shared_modules_random_getrandbits(uint8_t n); mp_int_t shared_modules_random_randrange(mp_int_t start, mp_int_t stop, mp_int_t step); +// Returns a random integer in [a, b] inclusive. The caller must ensure a <= b. +mp_int_t shared_modules_random_randint(mp_int_t a, mp_int_t b); mp_float_t shared_modules_random_random(void); mp_float_t shared_modules_random_uniform(mp_float_t a, mp_float_t b); diff --git a/shared-bindings/rclcpy/Node.c b/shared-bindings/rclcpy/Node.c new file mode 100644 index 00000000000..4097fbc1515 --- /dev/null +++ b/shared-bindings/rclcpy/Node.c @@ -0,0 +1,146 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Lucian Copeland +// +// SPDX-License-Identifier: MIT + +#include +#include "shared-bindings/rclcpy/Node.h" +#include "shared-bindings/rclcpy/Publisher.h" +#include "shared-bindings/util.h" +#include "py/objproperty.h" +#include "py/objtype.h" +#include "py/runtime.h" + + +//| class Node: +//| """A ROS2 Node""" +//| +//| def __init__( +//| self, +//| node_name: str, +//| *, +//| namespace: str | None = None, +//| ) -> None: +//| """Create a Node. +//| +//| Creates an instance of a ROS2 Node. Nodes can be used to create other ROS +//| entities like publishers or subscribers. Nodes must have a unique name, and +//| may also be constructed from their class. +//| +//| :param str node_name: The name of the node. Must be a valid ROS 2 node name +//| :param str namespace: The namespace for the node. If None, the node will be +//| created in the root namespace +//| """ +//| ... +//| +static mp_obj_t rclcpy_node_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_node_name, ARG_namespace }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_node_name, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_namespace, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + const char *node_name = mp_obj_str_get_str(args[ARG_node_name].u_obj); + const char *namespace = ""; + if (args[ARG_namespace].u_obj != mp_const_none) { + namespace = mp_obj_str_get_str(args[ARG_namespace].u_obj); + } + + rclcpy_node_obj_t *self = mp_obj_malloc_with_finaliser(rclcpy_node_obj_t, &rclcpy_node_type); + common_hal_rclcpy_node_construct(self, node_name, namespace); + + return MP_OBJ_FROM_PTR(self); +} + +//| def deinit(self) -> None: +//| """Deinitializes the node and frees any hardware or remote agent resources +//| used by it. Deinitialized nodes cannot be used again. +//| """ +//| ... +//| +static mp_obj_t rclcpy_node_obj_deinit(mp_obj_t self_in) { + rclcpy_node_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_rclcpy_node_deinit(self); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_1(rclcpy_node_deinit_obj, rclcpy_node_obj_deinit); + +static void check_for_deinit(rclcpy_node_obj_t *self) { + if (common_hal_rclcpy_node_deinited(self)) { + raise_deinited_error(); + } +} + +//| def create_publisher(self, topic: str) -> Publisher: +//| """Create a publisher for a given topic string. +//| +//| Creates an instance of a ROS2 Publisher. +//| +//| :param str topic: The name of the topic +//| :return: A new Publisher object for the specified topic +//| :rtype: Publisher +//| """ +//| ... +//| +static mp_obj_t rclcpy_node_create_publisher(mp_obj_t self_in, mp_obj_t topic) { + rclcpy_node_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + const char *topic_name = mp_obj_str_get_str(topic); + + rclcpy_publisher_obj_t *publisher = mp_obj_malloc_with_finaliser(rclcpy_publisher_obj_t, &rclcpy_publisher_type); + common_hal_rclcpy_publisher_construct(publisher, self, topic_name); + return MP_OBJ_FROM_PTR(publisher); +} +static MP_DEFINE_CONST_FUN_OBJ_2(rclcpy_node_create_publisher_obj, rclcpy_node_create_publisher); + +//| def get_name(self) -> str: +//| """Get the name of the node. +//| +//| :return: The node's name +//| :rtype: str +//| """ +//| ... +//| +static mp_obj_t rclcpy_node_get_name(mp_obj_t self_in) { + rclcpy_node_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + const char *name_str = common_hal_rclcpy_node_get_name(self); + return mp_obj_new_str(name_str, strlen(name_str)); +} +static MP_DEFINE_CONST_FUN_OBJ_1(rclcpy_node_get_name_obj, rclcpy_node_get_name); + +//| def get_namespace(self) -> str: +//| """Get the namespace of the node. +//| +//| :return: The node's namespace +//| :rtype: str +//| """ +//| ... +//| +static mp_obj_t rclcpy_node_get_namespace(mp_obj_t self_in) { + rclcpy_node_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + const char *namespace_str = common_hal_rclcpy_node_get_namespace(self); + return mp_obj_new_str(namespace_str, strlen(namespace_str)); +} +static MP_DEFINE_CONST_FUN_OBJ_1(rclcpy_node_get_namespace_obj, rclcpy_node_get_namespace); + +static const mp_rom_map_elem_t rclcpy_node_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&rclcpy_node_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&rclcpy_node_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR_create_publisher), MP_ROM_PTR(&rclcpy_node_create_publisher_obj) }, + { MP_ROM_QSTR(MP_QSTR_get_name), MP_ROM_PTR(&rclcpy_node_get_name_obj) }, + { MP_ROM_QSTR(MP_QSTR_get_namespace), MP_ROM_PTR(&rclcpy_node_get_namespace_obj) }, +}; +static MP_DEFINE_CONST_DICT(rclcpy_node_locals_dict, rclcpy_node_locals_dict_table); + + +MP_DEFINE_CONST_OBJ_TYPE( + rclcpy_node_type, + MP_QSTR_Node, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, rclcpy_node_make_new, + locals_dict, &rclcpy_node_locals_dict + ); diff --git a/shared-bindings/rclcpy/Node.h b/shared-bindings/rclcpy/Node.h new file mode 100644 index 00000000000..be0230846f6 --- /dev/null +++ b/shared-bindings/rclcpy/Node.h @@ -0,0 +1,18 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Lucian Copeland +// +// SPDX-License-Identifier: MIT + +#pragma once +#include "common-hal/rclcpy/Node.h" + + +extern const mp_obj_type_t rclcpy_node_type; + +void common_hal_rclcpy_node_construct(rclcpy_node_obj_t *self, + const char *node_name, const char *namespace); +bool common_hal_rclcpy_node_deinited(rclcpy_node_obj_t *self); +void common_hal_rclcpy_node_deinit(rclcpy_node_obj_t *self); +const char *common_hal_rclcpy_node_get_name(rclcpy_node_obj_t *self); +const char *common_hal_rclcpy_node_get_namespace(rclcpy_node_obj_t *self); diff --git a/shared-bindings/rclcpy/Publisher.c b/shared-bindings/rclcpy/Publisher.c new file mode 100644 index 00000000000..be1e229cce4 --- /dev/null +++ b/shared-bindings/rclcpy/Publisher.c @@ -0,0 +1,99 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Lucian Copeland +// +// SPDX-License-Identifier: MIT + +#include +#include "shared-bindings/rclcpy/Publisher.h" +#include "shared-bindings/util.h" +#include "py/objproperty.h" +#include "py/objtype.h" +#include "py/runtime.h" + + +//| class Publisher: +//| """A ROS2 publisher""" +//| +//| def __init__(self) -> None: +//| """Publishers cannot be created directly. +//| +//| Use :meth:`Node.create_publisher` to create a publisher from a node. +//| +//| :raises NotImplementedError: Always, as direct instantiation is not supported +//| """ +//| ... +//| +static mp_obj_t rclcpy_publisher_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + mp_raise_NotImplementedError(MP_ERROR_TEXT("Publishers can only be created from a parent node")); +} + +//| def deinit(self) -> None: +//| """Deinitializes the publisher and frees any hardware or remote agent resources +//| used by it. Deinitialized publishers cannot be used again. +//| """ +//| ... +//| +static mp_obj_t rclcpy_publisher_obj_deinit(mp_obj_t self_in) { + rclcpy_publisher_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_rclcpy_publisher_deinit(self); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_1(rclcpy_publisher_deinit_obj, rclcpy_publisher_obj_deinit); + +static void check_for_deinit(rclcpy_publisher_obj_t *self) { + if (common_hal_rclcpy_publisher_deinited(self)) { + raise_deinited_error(); + } +} + +//| def publish_int32(self, message: int) -> None: +//| """Publish a 32-bit signed integer message to the topic. +//| +//| :param int message: The integer value to publish. Must be within the range +//| of a 32-bit signed integer (-2,147,483,648 to 2,147,483,647) +//| """ +//| ... +//| +static mp_obj_t rclcpy_publisher_publish_int32(mp_obj_t self_in, mp_obj_t in_msg) { + rclcpy_publisher_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + int32_t msg = mp_obj_get_int(in_msg); + common_hal_rclcpy_publisher_publish_int32(self, msg); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(rclcpy_publisher_publish_int32_obj, rclcpy_publisher_publish_int32); + +//| def get_topic_name(self) -> str: +//| """Get the name of the topic this publisher publishes to. +//| +//| :return: The topic name as specified when the publisher was created +//| :rtype: str +//| """ +//| ... +//| +static mp_obj_t rclcpy_publisher_get_topic_name(mp_obj_t self_in) { + rclcpy_publisher_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + const char *topic_str = common_hal_rclcpy_publisher_get_topic_name(self); + return mp_obj_new_str(topic_str, strlen(topic_str)); +} +static MP_DEFINE_CONST_FUN_OBJ_1(rclcpy_publisher_get_topic_name_obj, rclcpy_publisher_get_topic_name); + + +static const mp_rom_map_elem_t rclcpy_publisher_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&rclcpy_publisher_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&rclcpy_publisher_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR_publish_int32), MP_ROM_PTR(&rclcpy_publisher_publish_int32_obj) }, + { MP_ROM_QSTR(MP_QSTR_get_topic_name), MP_ROM_PTR(&rclcpy_publisher_get_topic_name_obj) }, +}; +static MP_DEFINE_CONST_DICT(rclcpy_publisher_locals_dict, rclcpy_publisher_locals_dict_table); + + +MP_DEFINE_CONST_OBJ_TYPE( + rclcpy_publisher_type, + MP_QSTR_Publisher, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, rclcpy_publisher_make_new, + locals_dict, &rclcpy_publisher_locals_dict + ); diff --git a/shared-bindings/rclcpy/Publisher.h b/shared-bindings/rclcpy/Publisher.h new file mode 100644 index 00000000000..21909fe12be --- /dev/null +++ b/shared-bindings/rclcpy/Publisher.h @@ -0,0 +1,18 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Lucian Copeland +// +// SPDX-License-Identifier: MIT + +#pragma once +#include "common-hal/rclcpy/Publisher.h" + + +extern const mp_obj_type_t rclcpy_publisher_type; + +void common_hal_rclcpy_publisher_construct(rclcpy_publisher_obj_t *self, rclcpy_node_obj_t *node, + const char *topic_name); +bool common_hal_rclcpy_publisher_deinited(rclcpy_publisher_obj_t *self); +void common_hal_rclcpy_publisher_deinit(rclcpy_publisher_obj_t *self); +void common_hal_rclcpy_publisher_publish_int32(rclcpy_publisher_obj_t *self, int32_t data); +const char *common_hal_rclcpy_publisher_get_topic_name(rclcpy_publisher_obj_t *self); diff --git a/shared-bindings/rclcpy/__init__.c b/shared-bindings/rclcpy/__init__.c new file mode 100644 index 00000000000..e195294cde6 --- /dev/null +++ b/shared-bindings/rclcpy/__init__.c @@ -0,0 +1,135 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Lucian Copeland +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/rclcpy/__init__.h" +#include "shared-bindings/rclcpy/Node.h" +#include "shared-bindings/rclcpy/Publisher.h" + +#include "py/obj.h" +#include "py/objproperty.h" +#include "py/objstr.h" +#include "py/runtime.h" + +//| """Robot Operating System (ROS2) connectivity through micro-ROS +//| +//| The `rclcpy` module contains basic classes and connectivity options for +//| communicating with a ROS network running on a linux machine, using the +//| eProsima's `micro-ROS client API `_. +//| +//| The underlying micro-ROS system uses a resource-constrained middleware layer +//| (XRCE-DDS) that must be connected to an agent running within ROS2 on a host +//| Linux computer. The API exposed by Circuitpython aims to be close to the +//| standard Python API for ROS2, ``rclpy`` with minor additions to support +//| connecting to this agent. +//| +//| Wifi must be connected before calling any `rclcpy` functions. As with +//| ``rclpy``, the `rclcpy.init()` function must be run before creating any ROS +//| objects. Child objects, such as publishers, must be created by their parent +//| objects. For example:: +//| +//| import os, wifi, time +//| import rclcpy +//| wifi.radio.connect(ssid=os.getenv('CIRCUITPY_WIFI_SSID'), +//| password=os.getenv('CIRCUITPY_WIFI_PASSWORD')) +//| rclcpy.init("192.168.10.111","8888") +//| mynode = rclcpy.Node("foo") +//| mypub = mynode.create_publisher("bar") +//| mypub.publish_int32(42) +//| """ + +//| def init( +//| agent_ip: str, +//| agent_port: str, +//| *, +//| domain_id: int = 0, +//| ) -> None: +//| """Initialize micro-ROS and connect to a micro-ROS agent. +//| +//| This function starts ROS communications and connects to the micro-ROS agent +//| on a linux computer. It must be called before creating ROS objects. +//| +//| :param str agent_ip: The IP address of the micro-ROS agent +//| :param str agent_port: The port number of the micro-ROS agent as a string +//| :param int domain_id: The ROS 2 domain ID for network isolation and organization. +//| Devices with the same domain ID can communicate with each other. +//| """ +//| ... +//| +static mp_obj_t rclcpy_init(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_agent_ip, ARG_agent_port, ARG_domain_id}; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_agent_ip, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_agent_port, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_domain_id, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, + }; + 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 char *agent_ip = mp_obj_str_get_str(args[ARG_agent_ip].u_obj); + const char *agent_port = mp_obj_str_get_str(args[ARG_agent_port].u_obj); + int16_t domain_id = args[ARG_domain_id].u_int; + + common_hal_rclcpy_init(agent_ip, agent_port, domain_id); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_KW(rclcpy_init_obj, 2, rclcpy_init); + + +//| def create_node( +//| node_name: str, +//| *, +//| namespace: str | None = None +//| ) -> Node: +//| """Create a Node. +//| +//| Creates an instance of a ROS2 Node. Nodes can be used to create other ROS +//| entities like publishers or subscribers. Nodes must have a unique name, and +//| may also be constructed from their class. +//| +//| :param str node_name: The name of the node. Must be a valid ROS 2 node name. +//| :param str namespace: The namespace for the node. If None, the node will be +//| created in the root namespace. +//| :return: A new Node object +//| :rtype: Node +//| """ +//| ... +//| +static mp_obj_t rclcpy_create_node(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_node_name, ARG_namespace }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_node_name, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_namespace, MP_ARG_KW_ONLY | 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 char *node_name = mp_obj_str_get_str(args[ARG_node_name].u_obj); + const char *namespace = ""; + if (args[ARG_namespace].u_obj != mp_const_none) { + namespace = mp_obj_str_get_str(args[ARG_namespace].u_obj); + } + + rclcpy_node_obj_t *self = mp_obj_malloc_with_finaliser(rclcpy_node_obj_t, &rclcpy_node_type); + common_hal_rclcpy_node_construct(self, node_name, namespace); + + return MP_OBJ_FROM_PTR(self); +} +static MP_DEFINE_CONST_FUN_OBJ_KW(rclcpy_create_node_obj, 2, rclcpy_create_node); + +static const mp_rom_map_elem_t rclcpy_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_rclcpy) }, + { MP_ROM_QSTR(MP_QSTR_Node), MP_ROM_PTR(&rclcpy_node_type) }, + { MP_ROM_QSTR(MP_QSTR_Publisher), MP_ROM_PTR(&rclcpy_publisher_type) }, + { MP_ROM_QSTR(MP_QSTR_init), MP_ROM_PTR(&rclcpy_init_obj) }, + { MP_ROM_QSTR(MP_QSTR_create_node), MP_ROM_PTR(&rclcpy_create_node_obj) }, +}; + +static MP_DEFINE_CONST_DICT(rclcpy_module_globals, rclcpy_module_globals_table); + +const mp_obj_module_t rclcpy_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&rclcpy_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_rclcpy, rclcpy_module); diff --git a/shared-bindings/rclcpy/__init__.h b/shared-bindings/rclcpy/__init__.h new file mode 100644 index 00000000000..1b473421688 --- /dev/null +++ b/shared-bindings/rclcpy/__init__.h @@ -0,0 +1,12 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Lucian Copeland +// +// SPDX-License-Identifier: MIT + +#pragma once +#include "common-hal/rclcpy/__init__.h" + +void common_hal_rclcpy_init(const char *agent_ip, const char *agent_port, int16_t domain_id); +rclcpy_context_t *common_hal_rclcpy_get_default_context(void); +bool common_hal_rclcpy_default_context_is_initialized(void); diff --git a/shared-bindings/rgbmatrix/RGBMatrix.c b/shared-bindings/rgbmatrix/RGBMatrix.c index 6242f981fdf..29b4a5eac38 100644 --- a/shared-bindings/rgbmatrix/RGBMatrix.c +++ b/shared-bindings/rgbmatrix/RGBMatrix.c @@ -11,6 +11,7 @@ #include "common-hal/rgbmatrix/RGBMatrix.h" #include "shared-bindings/rgbmatrix/RGBMatrix.h" +#include "shared-bindings/rgbmatrix/RowAddressMode.h" #include "shared-bindings/microcontroller/Pin.h" #include "shared-bindings/microcontroller/__init__.h" #include "shared-bindings/util.h" @@ -21,101 +22,6 @@ //| class RGBMatrix: //| """Displays an in-memory framebuffer to a HUB75-style RGB LED matrix.""" //| - -extern Protomatter_core *_PM_protoPtr; - -static uint8_t validate_pin(mp_obj_t obj, qstr arg_name) { - const mcu_pin_obj_t *result = validate_obj_is_free_pin(obj, arg_name); - return common_hal_mcu_pin_number(result); -} - -static void claim_and_never_reset_pin(mp_obj_t pin) { - common_hal_mcu_pin_claim(pin); - common_hal_never_reset_pin(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 < len; i++) { - claim_and_never_reset_pin(mp_obj_subscr(seq, MP_OBJ_NEW_SMALL_INT(i), MP_OBJ_SENTINEL)); - } -} - -static void preflight_pins_or_throw(uint8_t clock_pin, uint8_t *rgb_pins, uint8_t rgb_pin_count, bool allow_inefficient) { - if (rgb_pin_count <= 0 || rgb_pin_count % 6 != 0 || rgb_pin_count > 30) { - mp_raise_ValueError_varg(MP_ERROR_TEXT("The length of rgb_pins must be 6, 12, 18, 24, or 30")); - } - -// Most ports have a strict requirement for how the rgbmatrix pins are laid -// out; these two micros don't. Special-case it here. - #if !defined(CONFIG_IDF_TARGET_ESP32S3) && !defined(CONFIG_IDF_TARGET_ESP32S2) - uint32_t port = clock_pin / 32; - uint32_t bit_mask = 1 << (clock_pin % 32); - - for (uint8_t i = 0; i < rgb_pin_count; i++) { - uint32_t pin_port = rgb_pins[i] / 32; - - if (pin_port != port) { - mp_raise_ValueError_varg( - MP_ERROR_TEXT("rgb_pins[%d] is not on the same port as clock"), i); - } - - uint32_t pin_mask = 1 << (rgb_pins[i] % 32); - if (pin_mask & bit_mask) { - mp_raise_ValueError_varg( - MP_ERROR_TEXT("rgb_pins[%d] duplicates another pin assignment"), i); - } - - bit_mask |= pin_mask; - } - - if (allow_inefficient) { - return; - } - - uint8_t byte_mask = 0; - if (bit_mask & 0x000000FF) { - byte_mask |= 0b0001; - } - if (bit_mask & 0x0000FF00) { - byte_mask |= 0b0010; - } - if (bit_mask & 0x00FF0000) { - byte_mask |= 0b0100; - } - if (bit_mask & 0xFF000000) { - byte_mask |= 0b1000; - } - - uint8_t bytes_per_element = 0xff; - uint8_t ideal_bytes_per_element = (rgb_pin_count + 7) / 8; - - switch (byte_mask) { - case 0b0001: - case 0b0010: - case 0b0100: - case 0b1000: - bytes_per_element = 1; - break; - - case 0b0011: - case 0b1100: - bytes_per_element = 2; - break; - - default: - bytes_per_element = 4; - break; - } - - if (bytes_per_element != ideal_bytes_per_element) { - mp_raise_ValueError_varg( - MP_ERROR_TEXT("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"), - bytes_per_element, ideal_bytes_per_element); - } - #endif -} - //| def __init__( //| self, //| *, @@ -131,13 +37,19 @@ static void preflight_pins_or_throw(uint8_t clock_pin, uint8_t *rgb_pins, uint8_ //| height: int = 0, //| tile: int = 1, //| serpentine: bool = True, +//| row_address_mode: RowAddressMode = RowAddressMode.BINARY, //| ) -> None: //| """Create a RGBMatrix object with the given attributes. The height of //| the display is determined by the number of rgb and address pins and the number of tiles: //| ``len(rgb_pins) // 3 * 2 ** len(address_pins) * abs(tile)``. With 6 RGB pins, 4 //| address lines, and a single matrix, the display will be 32 pixels tall. If the optional height //| parameter is specified and is not 0, it is checked against the calculated -//| height. +//| height. With ``row_address_mode=RowAddressMode.ABC``, ``height`` must be specified. +//| Each panel must have a power-of-two height, from 2 through 64 pixels. +//| Supply exactly three ``addr_pins`` in A, B, C order: A is the row +//| clock, B enables shifting, and C is serial row-selection data. +//| This protocol is separate from the panel's RGB pixel driver; an +//| FM6126A chip or HUB75E connector label does not identify the row mode. //| //| Tiled matrices, those with more than one panel, must be laid out `in a specific order, as detailed in the guide //| `_. @@ -191,13 +103,14 @@ static void preflight_pins_or_throw(uint8_t clock_pin, uint8_t *rgb_pins, uint8_ //| :param digitalio.DigitalInOut output_enable_pin: The matrix's output enable pin //| :param bool doublebuffer: True if the output is double-buffered //| :param Optional[WriteableBuffer] framebuffer: A pre-allocated framebuffer to use. If unspecified, a framebuffer is allocated -//| :param int height: The optional overall height of the whole matrix in pixels. This value is not required because it can be calculated as described above. +//| :param int height: The overall height of the whole matrix in pixels. Required for ABC addressing; otherwise optional and checked against the calculated height. +//| :param RowAddressMode row_address_mode: ``RowAddressMode.BINARY`` for parallel row addresses, or ``RowAddressMode.ABC`` for serial row selection using A, B and C. //| """ //| static mp_obj_t rgbmatrix_rgbmatrix_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { enum { ARG_width, ARG_bit_depth, ARG_rgb_list, ARG_addr_list, - ARG_clock_pin, ARG_latch_pin, ARG_output_enable_pin, ARG_doublebuffer, ARG_framebuffer, ARG_height, ARG_tile, ARG_serpentine }; + ARG_clock_pin, ARG_latch_pin, ARG_output_enable_pin, ARG_doublebuffer, ARG_framebuffer, ARG_height, ARG_tile, ARG_serpentine, ARG_row_address_mode }; static const mp_arg_t allowed_args[] = { { MP_QSTR_width, MP_ARG_INT | MP_ARG_REQUIRED | MP_ARG_KW_ONLY }, { MP_QSTR_bit_depth, MP_ARG_INT | MP_ARG_REQUIRED | MP_ARG_KW_ONLY }, @@ -211,23 +124,23 @@ static mp_obj_t rgbmatrix_rgbmatrix_make_new(const mp_obj_type_t *type, size_t n { MP_QSTR_height, MP_ARG_INT | MP_ARG_KW_ONLY, { .u_int = 0 } }, { MP_QSTR_tile, MP_ARG_INT | MP_ARG_KW_ONLY, { .u_int = 1 } }, { MP_QSTR_serpentine, MP_ARG_BOOL | MP_ARG_KW_ONLY, { .u_bool = true } }, + { MP_QSTR_row_address_mode, MP_ARG_OBJ | MP_ARG_KW_ONLY, { .u_obj = (void *)&rgbmatrix_row_address_mode_BINARY_obj } }, }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); - rgbmatrix_rgbmatrix_obj_t *self = &allocate_display_bus_or_raise()->rgbmatrix; - self->base.type = &rgbmatrix_RGBMatrix_type; + rgbmatrix_rgbmatrix_obj_t *self; uint8_t rgb_count, addr_count; - uint8_t rgb_pins[MP_ARRAY_SIZE(self->rgb_pins)]; - uint8_t addr_pins[MP_ARRAY_SIZE(self->addr_pins)]; - uint8_t clock_pin = validate_pin(args[ARG_clock_pin].u_obj, MP_QSTR_clock_pin); - uint8_t latch_pin = validate_pin(args[ARG_latch_pin].u_obj, MP_QSTR_latch_pin); - uint8_t output_enable_pin = validate_pin(args[ARG_output_enable_pin].u_obj, MP_QSTR_output_enable_pin); + const mcu_pin_obj_t *rgb_pins[MP_ARRAY_SIZE(self->rgb_pins)]; + const mcu_pin_obj_t *addr_pins[MP_ARRAY_SIZE(self->addr_pins)]; + const mcu_pin_obj_t *clock_pin = validate_obj_is_free_pin(args[ARG_clock_pin].u_obj, MP_QSTR_clock_pin); + const mcu_pin_obj_t *latch_pin = validate_obj_is_free_pin(args[ARG_latch_pin].u_obj, MP_QSTR_latch_pin); + const mcu_pin_obj_t *output_enable_pin = validate_obj_is_free_pin(args[ARG_output_enable_pin].u_obj, MP_QSTR_output_enable_pin); mp_int_t bit_depth = mp_arg_validate_int_range(args[ARG_bit_depth].u_int, 1, 6, MP_QSTR_bit_depth); - validate_pins(MP_QSTR_rgb_pins, rgb_pins, MP_ARRAY_SIZE(self->rgb_pins), args[ARG_rgb_list].u_obj, &rgb_count); - validate_pins(MP_QSTR_addr_pins, addr_pins, MP_ARRAY_SIZE(self->addr_pins), args[ARG_addr_list].u_obj, &addr_count); + validate_list_is_free_pins(MP_QSTR_rgb_pins, rgb_pins, MP_ARRAY_SIZE(rgb_pins), args[ARG_rgb_list].u_obj, &rgb_count); + validate_list_is_free_pins(MP_QSTR_addr_pins, addr_pins, MP_ARRAY_SIZE(addr_pins), args[ARG_addr_list].u_obj, &addr_count); if (rgb_count % 6) { mp_raise_ValueError_varg(MP_ERROR_TEXT("Must use a multiple of 6 rgb pins, not %d"), rgb_count); @@ -235,7 +148,27 @@ static mp_obj_t rgbmatrix_rgbmatrix_make_new(const mp_obj_type_t *type, size_t n int tile = mp_arg_validate_int_min(args[ARG_tile].u_int, 1, MP_QSTR_tile); - int computed_height = (rgb_count / 3) * (1 << (addr_count)) * tile; + ProtomatterRowAddressMode row_address_mode = + (ProtomatterRowAddressMode)cp_enum_value(&rgbmatrix_row_address_mode_type, + args[ARG_row_address_mode].u_obj, MP_QSTR_row_address_mode); + uint8_t row_addr_count = addr_count; + if (row_address_mode == PROTOMATTER_ROW_ADDRESS_ABC) { + mp_arg_validate_length(addr_count, 3, MP_QSTR_addr_pins); + mp_int_t height = mp_arg_validate_int_min(args[ARG_height].u_int, 1, MP_QSTR_height); + // ABC has three physical pins regardless of the number of row pairs. + // Match the explicit overall height, including parallel chains and tiles. + for (row_addr_count = 0; row_addr_count <= 5; row_addr_count++) { + int rows = (rgb_count / 3) * (1 << row_addr_count); + if (rows && height % rows == 0 && height / rows == tile) { + break; + } + } + if (row_addr_count > 5) { + mp_arg_error_invalid(MP_QSTR_height); + } + } + + int computed_height = (rgb_count / 3) * (1 << row_addr_count) * tile; if (args[ARG_height].u_int != 0) { if (computed_height != args[ARG_height].u_int) { mp_raise_ValueError_varg( @@ -245,7 +178,9 @@ static mp_obj_t rgbmatrix_rgbmatrix_make_new(const mp_obj_type_t *type, size_t n mp_int_t width = mp_arg_validate_int_min(args[ARG_width].u_int, 1, MP_QSTR_width); - preflight_pins_or_throw(clock_pin, rgb_pins, rgb_count, true); + // Reserve a display bus only after validating constructor arguments. + self = &allocate_display_bus_or_raise()->rgbmatrix; + self->base.type = &rgbmatrix_RGBMatrix_type; common_hal_rgbmatrix_rgbmatrix_construct(self, width, @@ -254,13 +189,8 @@ static mp_obj_t rgbmatrix_rgbmatrix_make_new(const mp_obj_type_t *type, size_t n addr_count, addr_pins, clock_pin, latch_pin, output_enable_pin, args[ARG_doublebuffer].u_bool, - args[ARG_framebuffer].u_obj, tile, args[ARG_serpentine].u_bool, NULL); - - claim_and_never_reset_pins(args[ARG_rgb_list].u_obj); - claim_and_never_reset_pins(args[ARG_addr_list].u_obj); - claim_and_never_reset_pin(args[ARG_clock_pin].u_obj); - claim_and_never_reset_pin(args[ARG_output_enable_pin].u_obj); - claim_and_never_reset_pin(args[ARG_latch_pin].u_obj); + args[ARG_framebuffer].u_obj, tile, args[ARG_serpentine].u_bool, NULL, + row_addr_count, row_address_mode); return MP_OBJ_FROM_PTR(self); } @@ -353,6 +283,7 @@ MP_PROPERTY_GETTER(rgbmatrix_rgbmatrix_height_obj, static const mp_rom_map_elem_t rgbmatrix_rgbmatrix_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&rgbmatrix_rgbmatrix_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&rgbmatrix_rgbmatrix_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR_brightness), MP_ROM_PTR(&rgbmatrix_rgbmatrix_brightness_obj) }, { MP_ROM_QSTR(MP_QSTR_refresh), MP_ROM_PTR(&rgbmatrix_rgbmatrix_refresh_obj) }, { MP_ROM_QSTR(MP_QSTR_width), MP_ROM_PTR(&rgbmatrix_rgbmatrix_width_obj) }, diff --git a/shared-bindings/rgbmatrix/RGBMatrix.h b/shared-bindings/rgbmatrix/RGBMatrix.h index 960abc66a3f..d245f20c32d 100644 --- a/shared-bindings/rgbmatrix/RGBMatrix.h +++ b/shared-bindings/rgbmatrix/RGBMatrix.h @@ -11,7 +11,7 @@ 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_construct(rgbmatrix_rgbmatrix_obj_t *self, int width, int bit_depth, uint8_t rgb_count, const mcu_pin_obj_t **rgb_pins, uint8_t addr_count, const mcu_pin_obj_t **addr_pins, const mcu_pin_obj_t *clock_pin, const mcu_pin_obj_t *latch_pin, const mcu_pin_obj_t *oe_pin, bool doublebuffer, mp_obj_t framebuffer, int8_t tile, bool serpentine, void *timer, uint8_t row_addr_count, ProtomatterRowAddressMode row_address_mode); void common_hal_rgbmatrix_rgbmatrix_deinit(rgbmatrix_rgbmatrix_obj_t *); void rgbmatrix_rgbmatrix_collect_ptrs(rgbmatrix_rgbmatrix_obj_t *); void common_hal_rgbmatrix_rgbmatrix_get_bufinfo(rgbmatrix_rgbmatrix_obj_t *self, mp_buffer_info_t *bufinfo); diff --git a/shared-bindings/rgbmatrix/RowAddressMode.c b/shared-bindings/rgbmatrix/RowAddressMode.c new file mode 100644 index 00000000000..f9c4d3abdbf --- /dev/null +++ b/shared-bindings/rgbmatrix/RowAddressMode.c @@ -0,0 +1,33 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "py/enum.h" +#include "py/obj.h" + +#include "lib/protomatter/src/core.h" + +#include "shared-bindings/rgbmatrix/RowAddressMode.h" + +MAKE_ENUM_VALUE(rgbmatrix_row_address_mode_type, rgbmatrix_row_address_mode, BINARY, PROTOMATTER_ROW_ADDRESS_BINARY); +MAKE_ENUM_VALUE(rgbmatrix_row_address_mode_type, rgbmatrix_row_address_mode, ABC, PROTOMATTER_ROW_ADDRESS_ABC); + +//| class RowAddressMode: +//| """The protocol used to select rows on the matrix.""" +//| +//| BINARY: RowAddressMode +//| """Use parallel binary row addresses.""" +//| +//| ABC: RowAddressMode +//| """Use serial A, B, and C row selection.""" +//| +MAKE_ENUM_MAP(rgbmatrix_row_address_mode) { + MAKE_ENUM_MAP_ENTRY(rgbmatrix_row_address_mode, BINARY), + MAKE_ENUM_MAP_ENTRY(rgbmatrix_row_address_mode, ABC), +}; +static MP_DEFINE_CONST_DICT(rgbmatrix_row_address_mode_locals_dict, rgbmatrix_row_address_mode_locals_table); + +MAKE_PRINTER(rgbmatrix, rgbmatrix_row_address_mode); +MAKE_ENUM_TYPE(rgbmatrix, RowAddressMode, rgbmatrix_row_address_mode); diff --git a/shared-bindings/rgbmatrix/RowAddressMode.h b/shared-bindings/rgbmatrix/RowAddressMode.h new file mode 100644 index 00000000000..d76c9e4aaa7 --- /dev/null +++ b/shared-bindings/rgbmatrix/RowAddressMode.h @@ -0,0 +1,14 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/enum.h" +#include "py/obj.h" + +extern const mp_obj_type_t rgbmatrix_row_address_mode_type; +extern const cp_enum_obj_t rgbmatrix_row_address_mode_BINARY_obj; +extern const cp_enum_obj_t rgbmatrix_row_address_mode_ABC_obj; diff --git a/shared-bindings/rgbmatrix/__init__.c b/shared-bindings/rgbmatrix/__init__.c index f6e0c43fb93..f610967dfd7 100644 --- a/shared-bindings/rgbmatrix/__init__.c +++ b/shared-bindings/rgbmatrix/__init__.c @@ -10,6 +10,7 @@ #include "py/runtime.h" #include "shared-bindings/rgbmatrix/RGBMatrix.h" +#include "shared-bindings/rgbmatrix/RowAddressMode.h" //| """Low-level routines for bitbanged LED matrices //| @@ -20,6 +21,7 @@ static const mp_rom_map_elem_t rgbmatrix_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_rgbmatrix) }, { MP_ROM_QSTR(MP_QSTR_RGBMatrix), MP_ROM_PTR(&rgbmatrix_RGBMatrix_type) }, + { MP_ROM_QSTR(MP_QSTR_RowAddressMode), MP_ROM_PTR(&rgbmatrix_row_address_mode_type) }, }; static MP_DEFINE_CONST_DICT(rgbmatrix_module_globals, rgbmatrix_module_globals_table); diff --git a/shared-bindings/rotaryio/IncrementalEncoder.h b/shared-bindings/rotaryio/IncrementalEncoder.h index 1c60dd69a19..b3ceb3eeb15 100644 --- a/shared-bindings/rotaryio/IncrementalEncoder.h +++ b/shared-bindings/rotaryio/IncrementalEncoder.h @@ -13,11 +13,15 @@ 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 void common_hal_rotaryio_incrementalencoder_mark_deinit(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); + extern mp_int_t common_hal_rotaryio_incrementalencoder_get_divisor(rotaryio_incrementalencoder_obj_t *self); extern void common_hal_rotaryio_incrementalencoder_set_divisor(rotaryio_incrementalencoder_obj_t *self, mp_int_t new_divisor); diff --git a/shared-bindings/rtc/RTC.c b/shared-bindings/rtc/RTC.c index d732ee94d7e..a65db08cbb2 100644 --- a/shared-bindings/rtc/RTC.c +++ b/shared-bindings/rtc/RTC.c @@ -49,7 +49,11 @@ static mp_obj_t rtc_rtc_make_new(const mp_obj_type_t *type, size_t n_args, size_ //| //| current_time = r.datetime //| print(current_time) -//| # struct_time(tm_year=2019, tm_month=5, ...)""" +//| # struct_time(tm_year=2019, tm_month=5, ...) +//| +//| The RTC does not store ``tm_isdst``: it is ignored when setting the time, and it reads back +//| as -1 (unknown). CircuitPython has no time zone or daylight saving time information, so the +//| RTC never adjusts for daylight saving time: it keeps counting from the time you set.""" static mp_obj_t rtc_rtc_obj_get_datetime(mp_obj_t self_in) { timeutils_struct_time_t tm; common_hal_rtc_get_time(&tm); @@ -74,7 +78,7 @@ MP_PROPERTY_GETSET(rtc_rtc_datetime_obj, //| //| A positive value speeds up the clock and a negative value slows it down. //| -//| **Limitations:** Calibration not supported on SAMD, Nordic, RP2040, Spresense, and STM. +//| **Limitations:** Calibration is supported only on SAMD. On other ports, setting it raises `NotImplementedError`. //| //| Range and value is hardware specific, but one step is often approximately 1 ppm:: //| diff --git a/shared-bindings/sdcardio/SDCard.c b/shared-bindings/sdcardio/SDCard.c index e6d8453eae1..506009f64d6 100644 --- a/shared-bindings/sdcardio/SDCard.c +++ b/shared-bindings/sdcardio/SDCard.c @@ -9,7 +9,8 @@ #include "py/objarray.h" #include "shared-bindings/sdcardio/SDCard.h" -#include "shared-module/sdcardio/SDCard.h" +#include "shared-bindings/util.h" + #include "common-hal/busio/SPI.h" #include "shared-bindings/busio/SPI.h" #include "shared-bindings/microcontroller/Pin.h" @@ -24,7 +25,10 @@ //| with ``storage.VfsFat`` to allow file I/O to an SD card.""" //| //| def __init__( -//| self, bus: busio.SPI, cs: microcontroller.Pin, baudrate: int = 8000000 +//| self, +//| bus: busio.SPI, +//| cs: Union[microcontroller.Pin, digitalio.DigitalInOutProtocol], +//| baudrate: int = 8000000 //| ) -> None: //| """Construct an SPI SD Card object with the given properties //| @@ -37,10 +41,18 @@ //| 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. +//| When the SPI bus is shared with other peripherals, every CS pin on +//| the bus must be in a known HIGH (deselected) state before any SPI +//| transaction occurs. This is normally guaranteed by a hardware +//| pull-up on each CS line, but on boards where a co-resident +//| peripheral's CS floats (for example the Feather RP2040 RFM, whose +//| ``RFM_CS`` has no pull-up), that CS must be driven HIGH in +//| software before the SD card is initialized. If any CS is allowed +//| to float low, the SPI bus can be corrupted during SD card init +//| and the card may not be recognized until it is powered off or +//| re-inserted. The order in which peripherals are constructed is +//| secondary; what matters is that all CS lines are HIGH (deselected) +//| before any SPI transaction. //| //| Example usage: //| @@ -52,12 +64,20 @@ //| import sdcardio //| import storage //| +//| # Make sure to make an "sd" folder on CIRCUITPY +//| //| sd = sdcardio.SDCard(board.SPI(), board.SD_CS) //| vfs = storage.VfsFat(sd) //| storage.mount(vfs, '/sd') -//| os.listdir('/sd')""" +//| print(os.listdir('/sd'))""" //| +static void check_for_deinit(sdcardio_sdcard_obj_t *self) { + if (common_hal_sdcardio_sdcard_deinited(self)) { + raise_deinited_error(); + } +} + static mp_obj_t sdcardio_sdcard_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { enum { ARG_spi, ARG_cs, ARG_baudrate, NUM_ARGS }; static const mp_arg_t allowed_args[] = { @@ -70,13 +90,11 @@ static mp_obj_t sdcardio_sdcard_make_new(const mp_obj_type_t *type, size_t n_arg mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); busio_spi_obj_t *spi = validate_obj_is_spi_bus(args[ARG_spi].u_obj, MP_QSTR_spi); - const mcu_pin_obj_t *cs = validate_obj_is_free_pin(args[ARG_cs].u_obj, MP_QSTR_cs); - - sdcardio_sdcard_obj_t *self = mp_obj_malloc(sdcardio_sdcard_obj_t, &sdcardio_SDCard_type); - common_hal_sdcardio_sdcard_construct(self, spi, cs, args[ARG_baudrate].u_int); + sdcardio_sdcard_obj_t *self = mp_obj_malloc_with_finaliser(sdcardio_sdcard_obj_t, &sdcardio_SDCard_type); + common_hal_sdcardio_sdcard_construct(self, spi, args[ARG_cs].u_obj, args[ARG_baudrate].u_int); - return self; + return MP_OBJ_FROM_PTR(self); } @@ -89,6 +107,7 @@ static mp_obj_t sdcardio_sdcard_make_new(const mp_obj_type_t *type, size_t n_arg //| static mp_obj_t sdcardio_sdcard_count(mp_obj_t self_in) { sdcardio_sdcard_obj_t *self = (sdcardio_sdcard_obj_t *)self_in; + check_for_deinit(self); 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); @@ -116,10 +135,12 @@ MP_DEFINE_CONST_FUN_OBJ_1(sdcardio_sdcard_deinit_obj, sdcardio_sdcard_deinit); //| static mp_obj_t _sdcardio_sdcard_readblocks(mp_obj_t self_in, mp_obj_t start_block_in, mp_obj_t buf_in) { + sdcardio_sdcard_obj_t *self = (sdcardio_sdcard_obj_t *)self_in; + check_for_deinit(self); + 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; int result = common_hal_sdcardio_sdcard_readblocks(self, start_block, &bufinfo); if (result < 0) { mp_raise_OSError(-result); @@ -137,6 +158,7 @@ MP_DEFINE_CONST_FUN_OBJ_3(sdcardio_sdcard_readblocks_obj, _sdcardio_sdcard_readb //| static mp_obj_t sdcardio_sdcard_sync(mp_obj_t self_in) { sdcardio_sdcard_obj_t *self = (sdcardio_sdcard_obj_t *)self_in; + check_for_deinit(self); int result = common_hal_sdcardio_sdcard_sync(self); if (result < 0) { mp_raise_OSError(-result); @@ -158,10 +180,12 @@ MP_DEFINE_CONST_FUN_OBJ_1(sdcardio_sdcard_sync_obj, sdcardio_sdcard_sync); //| static mp_obj_t _sdcardio_sdcard_writeblocks(mp_obj_t self_in, mp_obj_t start_block_in, mp_obj_t buf_in) { + sdcardio_sdcard_obj_t *self = (sdcardio_sdcard_obj_t *)self_in; + check_for_deinit(self); + 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; int result = common_hal_sdcardio_sdcard_writeblocks(self, start_block, &bufinfo); if (result < 0) { mp_raise_OSError(-result); @@ -173,6 +197,7 @@ MP_DEFINE_CONST_FUN_OBJ_3(sdcardio_sdcard_writeblocks_obj, _sdcardio_sdcard_writ static const mp_rom_map_elem_t sdcardio_sdcard_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_count), MP_ROM_PTR(&sdcardio_sdcard_count_obj) }, { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&sdcardio_sdcard_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&sdcardio_sdcard_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR_readblocks), MP_ROM_PTR(&sdcardio_sdcard_readblocks_obj) }, { MP_ROM_QSTR(MP_QSTR_sync), MP_ROM_PTR(&sdcardio_sdcard_sync_obj) }, { MP_ROM_QSTR(MP_QSTR_writeblocks), MP_ROM_PTR(&sdcardio_sdcard_writeblocks_obj) }, diff --git a/shared-bindings/sdcardio/SDCard.h b/shared-bindings/sdcardio/SDCard.h index ac27b47aa4d..4251575f8fd 100644 --- a/shared-bindings/sdcardio/SDCard.h +++ b/shared-bindings/sdcardio/SDCard.h @@ -7,17 +7,20 @@ #pragma once +#include "py/mperrno.h" #include "shared-module/sdcardio/SDCard.h" extern const mp_obj_type_t sdcardio_SDCard_type; -void common_hal_sdcardio_sdcard_construct(sdcardio_sdcard_obj_t *self, busio_spi_obj_t *spi, const mcu_pin_obj_t *cs, int baudrate); +void common_hal_sdcardio_sdcard_construct(sdcardio_sdcard_obj_t *self, busio_spi_obj_t *spi, mp_obj_t cs, int baudrate); void common_hal_sdcardio_sdcard_deinit(sdcardio_sdcard_obj_t *self); +bool common_hal_sdcardio_sdcard_deinited(sdcardio_sdcard_obj_t *self); void common_hal_sdcardio_sdcard_check_for_deinit(sdcardio_sdcard_obj_t *self); +void common_hal_sdcardio_sdcard_mark_deinit(sdcardio_sdcard_obj_t *self); int common_hal_sdcardio_sdcard_get_blockcount(sdcardio_sdcard_obj_t *self); -int common_hal_sdcardio_sdcard_readblocks(sdcardio_sdcard_obj_t *self, uint32_t start_block, mp_buffer_info_t *buf); -int common_hal_sdcardio_sdcard_sync(sdcardio_sdcard_obj_t *self); -int common_hal_sdcardio_sdcard_writeblocks(sdcardio_sdcard_obj_t *self, uint32_t start_block, mp_buffer_info_t *buf); +mp_negative_errno_t common_hal_sdcardio_sdcard_readblocks(sdcardio_sdcard_obj_t *self, uint32_t start_block, mp_buffer_info_t *buf); +mp_negative_errno_t common_hal_sdcardio_sdcard_sync(sdcardio_sdcard_obj_t *self); +mp_negative_errno_t common_hal_sdcardio_sdcard_writeblocks(sdcardio_sdcard_obj_t *self, uint32_t start_block, mp_buffer_info_t *buf); // Used by native vfs blockdev. mp_uint_t sdcardio_sdcard_readblocks(mp_obj_t self_in, uint8_t *buf, uint32_t start_block, uint32_t buflen); diff --git a/shared-bindings/sdioio/SDCard.c b/shared-bindings/sdioio/SDCard.c index 98cec5bc11b..4466bc5a290 100644 --- a/shared-bindings/sdioio/SDCard.c +++ b/shared-bindings/sdioio/SDCard.c @@ -55,7 +55,10 @@ //| sd = sdioio.SDCard( //| clock=board.SDIO_CLOCK, //| command=board.SDIO_COMMAND, -//| data=[board.SDIO_DATA], +//| # Note that board.SDIO_DATA is a tuple of four pins, not an individual pin. +//| data=board.SDIO_DATA, +//| # On some boards, the data pins are named individually. Use this line instead. +//| #data=(board.SDIO_DATA0, board.SDIO_DATA1, board.SDIO_DATA2, board.SDIO_DATA3), //| frequency=25000000) //| vfs = storage.VfsFat(sd) //| storage.mount(vfs, '/sd') @@ -64,7 +67,6 @@ //| static mp_obj_t sdioio_sdcard_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { - sdioio_sdcard_obj_t *self = mp_obj_malloc(sdioio_sdcard_obj_t, &sdioio_SDCard_type); enum { ARG_clock, ARG_command, ARG_data, ARG_frequency, NUM_ARGS }; static const mp_arg_t allowed_args[] = { { MP_QSTR_clock, MP_ARG_REQUIRED | MP_ARG_KW_ONLY | MP_ARG_OBJ }, @@ -83,6 +85,7 @@ static mp_obj_t sdioio_sdcard_make_new(const mp_obj_type_t *type, size_t n_args, 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); + sdioio_sdcard_obj_t *self = mp_obj_malloc_with_finaliser(sdioio_sdcard_obj_t, &sdioio_SDCard_type); common_hal_sdioio_sdcard_construct(self, clock, command, num_data, data_pins, args[ARG_frequency].u_int); return MP_OBJ_FROM_PTR(self); } @@ -238,6 +241,7 @@ MP_DEFINE_CONST_FUN_OBJ_1(sdioio_sdcard_deinit_obj, sdioio_sdcard_obj_deinit); static const mp_rom_map_elem_t sdioio_sdcard_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&sdioio_sdcard_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&sdioio_sdcard_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, diff --git a/shared-bindings/sdioio/SDCard.h b/shared-bindings/sdioio/SDCard.h index dfeaf8fca89..40a00dbb738 100644 --- a/shared-bindings/sdioio/SDCard.h +++ b/shared-bindings/sdioio/SDCard.h @@ -7,6 +7,7 @@ #pragma once #include "py/obj.h" +#include "py/mperrno.h" #include "common-hal/microcontroller/Pin.h" #include "common-hal/sdioio/SDCard.h" @@ -35,9 +36,11 @@ 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); -// 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); +// Read or write blocks - returns 0 on success or negative error code from mperrno.h +mp_negative_errno_t common_hal_sdioio_sdcard_readblocks(sdioio_sdcard_obj_t *self, uint32_t start_block, mp_buffer_info_t *bufinfo); +mp_negative_errno_t 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); +// Used by native vfs blockdev. +mp_negative_errno_t sdioio_sdcard_readblocks(mp_obj_t self_in, uint8_t *buf, uint32_t start_block, uint32_t buflen); +mp_negative_errno_t sdioio_sdcard_writeblocks(mp_obj_t self_in, uint8_t *buf, uint32_t start_block, uint32_t buflen); +bool sdioio_sdcard_ioctl(mp_obj_t self_in, size_t cmd, size_t arg, mp_int_t *out_value); diff --git a/shared-bindings/sdioio/__init__.c b/shared-bindings/sdioio/__init__.c index 45f1219f95a..d2e66f9633d 100644 --- a/shared-bindings/sdioio/__init__.c +++ b/shared-bindings/sdioio/__init__.c @@ -15,7 +15,7 @@ //| """Interface to an SD card via the SDIO bus""" static const mp_rom_map_elem_t sdioio_module_globals_table[] = { - { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_sdio) }, + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_sdioio) }, { MP_ROM_QSTR(MP_QSTR_SDCard), MP_ROM_PTR(&sdioio_SDCard_type) }, }; diff --git a/shared-bindings/sharpdisplay/SharpMemoryFramebuffer.c b/shared-bindings/sharpdisplay/SharpMemoryFramebuffer.c index e1e2469e361..5bd66e60347 100644 --- a/shared-bindings/sharpdisplay/SharpMemoryFramebuffer.c +++ b/shared-bindings/sharpdisplay/SharpMemoryFramebuffer.c @@ -18,8 +18,9 @@ //| to make 8-color displays. //| //| This initializes a display and connects it into CircuitPython. Unlike other -//| objects in CircuitPython, Display objects live until `displayio.release_displays()` -//| is called. This is done so that CircuitPython can use the display itself.""" +//| objects in CircuitPython, a display stays active after your code finishes if it is +//| `supervisor.runtime.display `, so that CircuitPython can use it. Otherwise, it is released +//| when your code finishes.""" //| //| def __init__( //| self, @@ -95,6 +96,7 @@ static MP_DEFINE_CONST_FUN_OBJ_1(sharpdisplay_framebuffer_deinit_obj, sharpdispl static const mp_rom_map_elem_t sharpdisplay_framebuffer_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&sharpdisplay_framebuffer_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&sharpdisplay_framebuffer_deinit_obj) }, }; static MP_DEFINE_CONST_DICT(sharpdisplay_framebuffer_locals_dict, sharpdisplay_framebuffer_locals_dict_table); diff --git a/shared-bindings/socketpool/Socket.c b/shared-bindings/socketpool/Socket.c index 5dac9d150e8..862e7657428 100644 --- a/shared-bindings/socketpool/Socket.c +++ b/shared-bindings/socketpool/Socket.c @@ -54,13 +54,22 @@ 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__); +// Raises EBADF (bad file number) if the socket is closed. +static socketpool_socket_obj_t *get_open_socket(mp_obj_t self_in) { + socketpool_socket_obj_t *self = MP_OBJ_TO_PTR(self_in); + if (common_hal_socketpool_socket_get_closed(self)) { + mp_raise_OSError(MP_EBADF); + } + return self; +} + //| 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); + socketpool_socket_obj_t *self = get_open_socket(self_in); mp_obj_t tuple_contents[2]; tuple_contents[0] = MP_OBJ_FROM_PTR(common_hal_socketpool_socket_accept(self, &tuple_contents[1])); @@ -159,7 +168,7 @@ static MP_DEFINE_CONST_FUN_OBJ_2(socketpool_socket_listen_obj, socketpool_socket //| ... //| 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); + socketpool_socket_obj_t *self = get_open_socket(self_in); mp_buffer_info_t bufinfo; mp_get_buffer_raise(data_in, &bufinfo, MP_BUFFER_WRITE); @@ -185,11 +194,7 @@ static MP_DEFINE_CONST_FUN_OBJ_2(socketpool_socket_recvfrom_into_obj, socketpool //| ... //| 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)) { - // Bad file number. - mp_raise_OSError(MP_EBADF); - } + socketpool_socket_obj_t *self = get_open_socket(args[0]); // if (!common_hal_socketpool_socket_get_connected(self)) { // // not connected // mp_raise_OSError(MP_ENOTCONN); @@ -224,11 +229,7 @@ static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(socketpool_socket_recv_into_obj, 2, 3 //| ... //| 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); - } + socketpool_socket_obj_t *self = get_open_socket(self_in); if (!common_hal_socketpool_socket_get_connected(self)) { mp_raise_BrokenPipeError(); } @@ -254,11 +255,7 @@ static MP_DEFINE_CONST_FUN_OBJ_2(socketpool_socket_send_obj, _socketpool_socket_ //| ... //| static mp_obj_t _socketpool_socket_sendall(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); - } + socketpool_socket_obj_t *self = get_open_socket(self_in); if (!common_hal_socketpool_socket_get_connected(self)) { mp_raise_BrokenPipeError(); } @@ -446,7 +443,7 @@ static mp_uint_t socket_write(mp_obj_t self_in, const void *buf, mp_uint_t size, return ret; } -static mp_uint_t socket_ioctl(mp_obj_t self_in, mp_uint_t request, mp_uint_t arg, int *errcode) { +static mp_uint_t socket_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) { socketpool_socket_obj_t *self = MP_OBJ_TO_PTR(self_in); mp_uint_t ret; if (request == MP_STREAM_POLL) { diff --git a/shared-bindings/socketpool/Socket.h b/shared-bindings/socketpool/Socket.h index a883ebd5054..295f86e7371 100644 --- a/shared-bindings/socketpool/Socket.h +++ b/shared-bindings/socketpool/Socket.h @@ -6,6 +6,7 @@ #pragma once +#include "py/mperrno.h" #include "common-hal/socketpool/Socket.h" extern const mp_obj_type_t socketpool_socket_type; diff --git a/shared-bindings/socketpool/SocketPool.c b/shared-bindings/socketpool/SocketPool.c index e139e3a077a..cc816008f0b 100644 --- a/shared-bindings/socketpool/SocketPool.c +++ b/shared-bindings/socketpool/SocketPool.c @@ -17,29 +17,34 @@ #include "shared-bindings/socketpool/SocketPool.h" //| class SocketPool: -//| """A pool of socket resources available for the given radio. Only one -//| SocketPool can be created for each radio. +//| """A pool of socket resources available for the given network interface. More than one +//| SocketPool can be created for a network interface. The sockets of every SocketPool +//| count toward the same limit on open sockets for the given network interface. //| //| SocketPool should be used in place of CPython's socket which provides //| a pool of sockets provided by the underlying OS. //| """ //| -//| def __init__(self, radio: wifi.Radio) -> None: -//| """Create a new SocketPool object for the provided radio +//| def __init__(self, network_interface: Union[wifi.Radio, mii.Ethernet, hostnetwork.HostNetwork]) -> None: +//| """Create a new SocketPool object for the provided network interface //| -//| :param wifi.Radio radio: The (connected) network hardware to associate -//| with this SocketPool; currently, this will always be the object -//| returned by :py:attr:`wifi.radio` +//| The network interface does not need to be connected when the SocketPool is created. +//| It must be connected, or :py:attr:`wifi.radio` must be running an access point, before +//| the SocketPool can communicate over the network. The same SocketPool can be used again +//| after the network interface disconnects and reconnects. +//| +//| :param network_interface: The network interface to associate with this +//| SocketPool, such as :py:attr:`wifi.radio`, an `mii.Ethernet`, or :py:attr:`board.NETWORK`. //| """ //| ... //| static mp_obj_t socketpool_socketpool_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, 1, 1, false); - socketpool_socketpool_obj_t *s = mp_obj_malloc_with_finaliser(socketpool_socketpool_obj_t, &socketpool_socketpool_type); - mp_obj_t radio = args[0]; + mp_obj_t network_interface = args[0]; - common_hal_socketpool_socketpool_construct(s, radio); + socketpool_socketpool_obj_t *s = mp_obj_malloc_with_finaliser(socketpool_socketpool_obj_t, &socketpool_socketpool_type); + common_hal_socketpool_socketpool_construct(s, network_interface); return MP_OBJ_FROM_PTR(s); } @@ -190,16 +195,28 @@ MP_DEFINE_CONST_OBJ_TYPE( locals_dict, &socketpool_socketpool_locals_dict ); -MP_WEAK NORETURN -void common_hal_socketpool_socketpool_raise_gaierror_noname(void) { +MP_WEAK MP_NORETURN +void common_hal_socketpool_socketpool_raise_gaierror(int err) { vstr_t vstr; mp_print_t print; vstr_init_print(&vstr, 64, &print); - mp_printf(&print, "%S", MP_ERROR_TEXT("Name or service not known")); + // Only EAI_NONAME means the name was not found. Other codes cover + // unrelated failures, such as an unsupported family, so use the generic + // message for those rather than one that would be misleading. + if (err == SOCKETPOOL_EAI_NONAME) { + mp_printf(&print, "%S", MP_ERROR_TEXT("Name or service not known")); + } else { + mp_cprintf(&print, MP_ERROR_TEXT("%q failure: %d"), MP_QSTR_getaddrinfo, err); + } mp_obj_t exc_args[] = { - MP_OBJ_NEW_SMALL_INT(SOCKETPOOL_EAI_NONAME), + MP_OBJ_NEW_SMALL_INT(err), mp_obj_new_str_from_vstr(&vstr), }; nlr_raise(mp_obj_new_exception_args(&mp_type_gaierror, MP_ARRAY_SIZE(exc_args), exc_args)); } + +MP_WEAK MP_NORETURN +void common_hal_socketpool_socketpool_raise_gaierror_noname(void) { + common_hal_socketpool_socketpool_raise_gaierror(SOCKETPOOL_EAI_NONAME); +} diff --git a/shared-bindings/socketpool/SocketPool.h b/shared-bindings/socketpool/SocketPool.h index 36035ed00e1..c55ec8df96f 100644 --- a/shared-bindings/socketpool/SocketPool.h +++ b/shared-bindings/socketpool/SocketPool.h @@ -14,7 +14,7 @@ extern const mp_obj_type_t socketpool_socketpool_type; -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 network_interface); socketpool_socket_obj_t *common_hal_socketpool_socket(socketpool_socketpool_obj_t *self, socketpool_socketpool_addressfamily_t family, socketpool_socketpool_sock_t type, int proto); @@ -25,6 +25,7 @@ bool socketpool_socket(socketpool_socketpool_obj_t *self, socketpool_socketpool_addressfamily_t family, socketpool_socketpool_sock_t type, int proto, socketpool_socket_obj_t *sock); -NORETURN void common_hal_socketpool_socketpool_raise_gaierror_noname(void); +MP_NORETURN void common_hal_socketpool_socketpool_raise_gaierror_noname(void); +MP_NORETURN void common_hal_socketpool_socketpool_raise_gaierror(int err); mp_obj_t common_hal_socketpool_getaddrinfo_raise(socketpool_socketpool_obj_t *self, const char *host, int port, int family, int type, int proto, int flags); diff --git a/shared-bindings/spitarget/SPITarget.c b/shared-bindings/spitarget/SPITarget.c index eca92d80027..61e6e90927e 100644 --- a/shared-bindings/spitarget/SPITarget.c +++ b/shared-bindings/spitarget/SPITarget.c @@ -33,7 +33,6 @@ //| ... //| static mp_obj_t spitarget_spi_target_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { - spitarget_spi_target_obj_t *self = mp_obj_malloc(spitarget_spi_target_obj_t, &spitarget_spi_target_type); enum { ARG_sck, ARG_mosi, ARG_miso, ARG_ss }; static const mp_arg_t allowed_args[] = { { MP_QSTR_sck, MP_ARG_REQUIRED | MP_ARG_OBJ }, @@ -49,7 +48,9 @@ static mp_obj_t spitarget_spi_target_make_new(const mp_obj_type_t *type, size_t const mcu_pin_obj_t *miso = validate_obj_is_free_pin(args[ARG_miso].u_obj, MP_QSTR_miso); const mcu_pin_obj_t *ss = validate_obj_is_free_pin(args[ARG_ss].u_obj, MP_QSTR_ss); + spitarget_spi_target_obj_t *self = mp_obj_malloc_with_finaliser(spitarget_spi_target_obj_t, &spitarget_spi_target_type); common_hal_spitarget_spi_target_construct(self, sck, mosi, miso, ss); + return MP_OBJ_FROM_PTR(self); } @@ -171,6 +172,7 @@ static MP_DEFINE_CONST_FUN_OBJ_KW(spitarget_spi_target_wait_transfer_obj, 1, spi static const mp_rom_map_elem_t spitarget_spi_target_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&spitarget_spi_target_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&spitarget_spi_target_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&spitarget_spi_target___exit___obj) }, { MP_ROM_QSTR(MP_QSTR_load_packet), MP_ROM_PTR(&spitarget_spi_target_load_packet_obj) }, diff --git a/shared-bindings/ssl/SSLContext.c b/shared-bindings/ssl/SSLContext.c index 078a716cdb8..367b5f1e893 100644 --- a/shared-bindings/ssl/SSLContext.c +++ b/shared-bindings/ssl/SSLContext.c @@ -16,6 +16,13 @@ #include "shared-bindings/ssl/SSLContext.h" +#if CIRCUITPY_CRYPTOGRAPHY +#include "shared-bindings/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.h" +#endif + +//| import cryptography.hazmat.primitives.asymmetric.rsa +//| +//| //| class SSLContext: //| """Settings related to SSL that can be applied to a socket by wrapping it. //| This is useful to provide SSL certificates to specific connections @@ -26,19 +33,27 @@ static mp_obj_t ssl_sslcontext_make_new(const mp_obj_type_t *type, size_t n_args mp_arg_check_num(n_args, n_kw, 0, 1, false); ssl_sslcontext_obj_t *s = mp_obj_malloc(ssl_sslcontext_obj_t, &ssl_sslcontext_type); - common_hal_ssl_sslcontext_construct(s); return MP_OBJ_FROM_PTR(s); } -//| def load_cert_chain(self, certfile: str, keyfile: str) -> None: +//| def load_cert_chain( +//| self, certfile: str, keyfile: str | cryptography.hazmat.primitives.asymmetric.rsa.DigitalSignatureKey | None = None +//| ) -> None: //| """Load a private key and the corresponding certificate. //| //| The certfile string must be the path to a single file in PEM format //| containing the certificate as well as any number of CA certificates -//| needed to establish the certificate's authenticity. The keyfile string -//| must point to a file containing the private key. +//| needed to establish the certificate's authenticity. +//| +//| ``keyfile`` is either the path to a file containing the private key, or +//| a :py:class:`cryptography.hazmat.primitives.asymmetric.rsa.DigitalSignatureKey` +//| (obtained via :py:func:`cryptography.hazmat.primitives.asymmetric.rsa.load_digital_signature_key()`) +//| whose key never leaves the hardware -- in which case signing during +//| the TLS handshake is done by the hardware and the private key is +//| never exposed. If ``keyfile`` is omitted, the private key is read +//| from ``certfile``. //| """ //| @@ -61,15 +76,31 @@ static mp_obj_t ssl_sslcontext_load_cert_chain(size_t n_args, const mp_obj_t *po 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 cert_buf, key_buf; + mp_buffer_info_t cert_buf, key_buf = { 0 }; + psa_key_id_t hw_key_id = 0; get_file_contents(args[ARG_certfile].u_obj, &cert_buf); - if (args[ARG_keyfile].u_obj != mp_const_none) { - get_file_contents(args[ARG_keyfile].u_obj, &key_buf); + + mp_obj_t keyfile = args[ARG_keyfile].u_obj; + #if CIRCUITPY_CRYPTOGRAPHY + if (mp_obj_is_type(keyfile, &cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_type)) { + cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_obj_t *key = MP_OBJ_TO_PTR(keyfile); + // TLS client-cert auth signs the handshake, so this commits the key to + // signing (see DigitalSignatureKey.sign()'s docstring on the + // one-algorithm-per-lifetime rule) -- raises if this key already + // committed to a different algorithm (e.g. decrypt()). + common_hal_cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_ensure_algorithm(key, + PSA_ALG_RSA_PKCS1V15_SIGN(PSA_ALG_ANY_HASH), + PSA_KEY_USAGE_SIGN_MESSAGE | PSA_KEY_USAGE_SIGN_HASH); + hw_key_id = common_hal_cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_get_key_id(key); + } else + #endif + if (keyfile != mp_const_none) { + get_file_contents(keyfile, &key_buf); } else { key_buf = cert_buf; } - common_hal_ssl_sslcontext_load_cert_chain(self, &cert_buf, &key_buf); + common_hal_ssl_sslcontext_load_cert_chain(self, &cert_buf, &key_buf, hw_key_id); return mp_const_none; } static MP_DEFINE_CONST_FUN_OBJ_KW(ssl_sslcontext_load_cert_chain_obj, 1, ssl_sslcontext_load_cert_chain); diff --git a/shared-bindings/ssl/SSLContext.h b/shared-bindings/ssl/SSLContext.h index e3654e707c2..9b16774326d 100644 --- a/shared-bindings/ssl/SSLContext.h +++ b/shared-bindings/ssl/SSLContext.h @@ -28,4 +28,5 @@ void common_hal_ssl_sslcontext_set_default_verify_paths(ssl_sslcontext_obj_t *se bool common_hal_ssl_sslcontext_get_check_hostname(ssl_sslcontext_obj_t *self); void common_hal_ssl_sslcontext_set_check_hostname(ssl_sslcontext_obj_t *self, bool value); -void common_hal_ssl_sslcontext_load_cert_chain(ssl_sslcontext_obj_t *self, mp_buffer_info_t *cert_buf, mp_buffer_info_t *key_buf); +// hw_key_id nonzero means the private key is an opaque PSA key and key_buf is ignored. +void common_hal_ssl_sslcontext_load_cert_chain(ssl_sslcontext_obj_t *self, mp_buffer_info_t *cert_buf, mp_buffer_info_t *key_buf, psa_key_id_t hw_key_id); diff --git a/shared-bindings/ssl/SSLSocket.c b/shared-bindings/ssl/SSLSocket.c index 92440f9ea30..98f67878d04 100644 --- a/shared-bindings/ssl/SSLSocket.c +++ b/shared-bindings/ssl/SSLSocket.c @@ -106,7 +106,7 @@ static MP_DEFINE_CONST_FUN_OBJ_2(ssl_sslsocket_connect_obj, ssl_sslsocket_connec //| def listen(self, backlog: int) -> None: //| """Set socket to listen for incoming connections //| -//| :param ~int backlog: length of backlog queue for waiting connetions""" +//| :param ~int backlog: length of backlog queue for waiting connections""" //| ... //| static mp_obj_t ssl_sslsocket_listen(mp_obj_t self_in, mp_obj_t backlog_in) { @@ -291,7 +291,7 @@ static mp_uint_t sslsocket_write(mp_obj_t self_in, const void *buf, mp_uint_t si return readwrite_common(self_in, common_hal_ssl_sslsocket_send, buf, size, errorcode); } -static mp_uint_t sslsocket_ioctl(mp_obj_t self_in, mp_uint_t request, mp_uint_t arg, int *errcode) { +static mp_uint_t sslsocket_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) { ssl_sslsocket_obj_t *self = MP_OBJ_TO_PTR(self_in); mp_uint_t ret; if (request == MP_STREAM_POLL) { diff --git a/shared-bindings/ssl/__init__.c b/shared-bindings/ssl/__init__.c index 0d10090e9cb..51a3ad3cfc4 100644 --- a/shared-bindings/ssl/__init__.c +++ b/shared-bindings/ssl/__init__.c @@ -27,9 +27,9 @@ static mp_obj_t ssl_create_default_context(void) { ssl_sslcontext_obj_t *s = mp_obj_malloc(ssl_sslcontext_obj_t, &ssl_sslcontext_type); - common_hal_ssl_create_default_context(s); - return s; + + return MP_OBJ_FROM_PTR(s); } MP_DEFINE_CONST_FUN_OBJ_0(ssl_create_default_context_obj, ssl_create_default_context); diff --git a/shared-bindings/storage/__init__.c b/shared-bindings/storage/__init__.c index 002acaa8f2f..05a96396852 100644 --- a/shared-bindings/storage/__init__.c +++ b/shared-bindings/storage/__init__.c @@ -54,15 +54,11 @@ static mp_obj_t storage_mount(size_t n_args, const mp_obj_t *pos_args, mp_map_t // get the mount point const char *mnt_str = mp_obj_str_get_str(args[ARG_mount_path].u_obj); - // Make sure we're given an object we can mount. - // TODO(tannewt): Make sure we have all the methods we need to operating it - // as a file system. + mp_obj_t vfs_obj = args[ARG_filesystem].u_obj; - mp_obj_t dest[2]; - mp_load_method_maybe(vfs_obj, MP_QSTR_mount, dest); - if (dest[0] == MP_OBJ_NULL) { - mp_raise_ValueError(MP_ERROR_TEXT("filesystem must provide mount method")); - } + + // Currently, the only supported filesystem is VfsFat. + mp_arg_validate_type(vfs_obj, &mp_fat_vfs_type, MP_QSTR_filesystem); common_hal_storage_mount(vfs_obj, mnt_str, args[ARG_readonly].u_bool); @@ -97,6 +93,17 @@ MP_DEFINE_CONST_FUN_OBJ_1(storage_umount_obj, storage_umount); //| ) -> None: //| """Remounts the given path with new parameters. //| +//| This can always be done from ``boot.py``. After boot, `remount()` raises `RuntimeError` +//| if the host computer has write access to the filesystem, if a file on the filesystem +//| is open for writing, or if a workflow file transfer is in progress. +//| Some host OSes allow you to eject a drive which will allow for remounting. +//| +//| If the USB drive has been disabled with `unsafe_disable_usb_drive()`, +//| the new settings remain in effect after a later `enable_usb_drive()`. +//| +//| Remounting after USB is active may take a little time because it "ejects" the drive for one +//| query from the host. These queries happen every second or so. +//| //| :param str mount_path: The path to remount. //| :param bool readonly: True when the filesystem should be readonly to CircuitPython. //| :param bool disable_concurrent_write_protection: When True, the check that makes sure the @@ -136,24 +143,22 @@ static mp_obj_t storage_getmount(const mp_obj_t mnt_in) { MP_DEFINE_CONST_FUN_OBJ_1(storage_getmount_obj, storage_getmount); //| def erase_filesystem(extended: Optional[bool] = None) -> None: -//| """Erase and re-create the ``CIRCUITPY`` filesystem. +//| """Erase and re-create the **CIRCUITPY** filesystem. //| -//| On boards that present USB-visible ``CIRCUITPY`` drive (e.g., SAMD21 and SAMD51), +//| On boards that present USB-visible **CIRCUITPY** drive (e.g., SAMD21 and SAMD51), //| then call `microcontroller.reset()` to restart CircuitPython and have the -//| host computer remount CIRCUITPY. +//| host computer remount **CIRCUITPY**. //| -//| This function can be called from the REPL when ``CIRCUITPY`` +//| This function can be called from the REPL when **CIRCUITPY** //| has become corrupted. //| //| :param bool extended: On boards that support ``dualbank`` module -//| and the ``extended`` parameter, the ``CIRCUITPY`` storage can be +//| and the ``extended`` parameter, the **CIRCUITPY** storage can be //| extended by setting this to `True`. If this isn't provided or //| set to `None` (default), the existing configuration will be used. +//| If no filesystem is present, it will not be extended. //| -//| .. note:: New firmware starts with storage extended. In case of an existing -//| filesystem (e.g. uf2 load), the existing extension setting is preserved. -//| -//| .. warning:: All the data on ``CIRCUITPY`` will be lost, and +//| .. warning:: All the data on **CIRCUITPY** will be lost, and //| CircuitPython will restart on certain boards.""" //| ... //| @@ -183,9 +188,11 @@ static mp_obj_t storage_erase_filesystem(size_t n_args, const mp_obj_t *pos_args MP_DEFINE_CONST_FUN_OBJ_KW(storage_erase_filesystem_obj, 0, storage_erase_filesystem); //| def disable_usb_drive() -> None: -//| """Disable presenting ``CIRCUITPY`` as a USB mass storage device. -//| By default, the device is enabled and ``CIRCUITPY`` is visible. -//| Can be called in ``boot.py``, before USB is connected.""" +//| """Disable presenting **CIRCUITPY** as a USB mass storage device. +//| By default, the device is enabled and **CIRCUITPY** is visible, if USB is available. +//| Must called in ``boot.py``, before USB is connected. +// If you want to disable the USB drive after `boot.py` has run, see `unsafe_disable_usb_drive()`. +//| """ //| ... //| //| @@ -201,15 +208,88 @@ static mp_obj_t storage_disable_usb_drive(void) { } MP_DEFINE_CONST_FUN_OBJ_0(storage_disable_usb_drive_obj, storage_disable_usb_drive); +//| def unsafe_disable_usb_drive() -> None: +//| """Disable presenting **CIRCUITPY** as a USB mass storage device even if in use. +//| By default, the device is enabled and **CIRCUITPY** is visible. +//| After the call, **CIRCUITPY** will be read/write to your code and from the REPL but not appear over USB. +//| +//| Unlike `disable_usb_drive()`, `unsafe_disable_usb_drive()` can be called +//| after ``code.py`` starts or from the REPL, after USB has started. +//| +//| .. warning:: If ``unsafe_disable_usb_drive()`` is called when the host is in the middle of writing **CIRCUITPY**, +//| filesystem corruption can occur. +//| It is similar to the sudden physical removal of a USB drive. +//| Before calling ``unsafe_disable_usb_drive()``, +//| make sure the host has finished any writes to **CIRCUITPY**. +//| +//| * On Windows, do one of these: +//| +//| * Eject ("Safely Remove") the **CIRCUITPY** drive. +//| * Use a "sync" program, such as `Sysinternals Sync `__. +//| * Programmatically call ``_commit()`` or ``_flushall()`` or similar. +//| +//| * On Linux or macOS, do one of these: +//| +//| * Eject (unmount) the **CIRCUITPY** drive. +//| * Type ``sync`` in a terminal. +//| * Programmatically call ``sync()`` or ``fsync()``. +//| +//| * If none of the above are possible or convenient, wait several seconds to allow any writes to complete. +//| This can be unreliable, as the interval to wait depends on the host operating system +//| and how the drive is mounted. +//| In some operating systems, you can specify that the drive be mounted as "sync on write", +//| so that all writes happen immediately. +//| +//| When `unsafe_disable_usb_drive()` is called after USB has started, +//| the **CIRCUITPY** USB drive logical unit (LUN) will report as "not ready", +//| causing the host to unmount it. +//| The drive can be made ready and available again by calling `enable_usb_drive()`. +//| When `unsafe_disable_usb_drive()` is called after ``code.py`` starts or in the REPL, +//| the call will delay 2.5 seconds before returning, +//| so that host has time to detect that the drive is not ready. +//| The host polls the device approximately every one or two seconds. +//| +//| When the USB drive is disabled, **CIRCUITPY** becomes read/write, and can be written +//| from user code or the REPL. This is easier than arranging for a `remount()` in ``boot.py``. +//| Code editors and file uploaders can use this feature to write files via the REPL. +//| The host's previous access to **CIRCUITPY** is remembered, and `enable_usb_drive()` restores it, +//| unless `remount()` is called in the meantime. +//| +//| If `unsafe_disable_usb_drive()` is called in ``boot.py``, it is identical to calling +//| `disable_usb_drive()`. +//| """ +//| ... +//| +//| +static mp_obj_t storage_unsafe_disable_usb_drive(void) { + #if CIRCUITPY_USB_DEVICE && CIRCUITPY_USB_MSC + if (!common_hal_storage_unsafe_disable_usb_drive()) { + #else + if (true) { + #endif + mp_raise_RuntimeError(MP_ERROR_TEXT("Cannot change USB devices now")); + } + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_0(storage_unsafe_disable_usb_drive_obj, storage_unsafe_disable_usb_drive); + //| def enable_usb_drive() -> None: -//| """Enabled presenting ``CIRCUITPY`` as a USB mass storage device. -//| By default, the device is enabled and ``CIRCUITPY`` is visible, -//| so you do not normally need to call this function. -//| Can be called in ``boot.py``, before USB is connected. +//| """Enable presenting **CIRCUITPY** as a USB mass storage device. +//| By default, the device is enabled and **CIRCUITPY** is visible, +//| so you do not normally need to call this function in ``boot.py``. //| -//| If you enable too many devices at once, you will run out of USB endpoints. +//| If you call `enable_usb_drive()` after ``code.py`` starts or in the REPL, +//| you can reverse the effect of a previous `unsafe_disable_usb_drive()`. +//| The **CIRCUITPY** drive will reappear to the host with the same read/write access it had +//| before it was disabled, or with whatever access was set by a `remount()` done while it was disabled. +//| +//| Close any files opened for writing on **CIRCUITPY** before calling `enable_usb_drive()`. +//| If a file is still open for writing, or a workflow file transfer is in progress, +//| `RuntimeError` is raised. +//| +//| If you enable too many USB devices at once, you will run out of USB endpoints. //| The number of available endpoints varies by microcontroller. -//| CircuitPython will go into safe mode after running boot.py to inform you if +//| CircuitPython will go into safe mode after running ``boot.py`` to inform you if //| not enough endpoints are available. //| """ //| ... @@ -227,16 +307,46 @@ static mp_obj_t storage_enable_usb_drive(void) { } MP_DEFINE_CONST_FUN_OBJ_0(storage_enable_usb_drive_obj, storage_enable_usb_drive); + +//| def map_file(file: typing.BinaryIO) -> Tuple[memoryview, ...]: +//| """Map a file on the CIRCUITPY drive straight from flash, without copying it into RAM. +//| Returns one read-only `memoryview` per contiguous run of the file's clusters, in file +//| order. The views stay valid after the file is closed. +//| +//| Until the next reload, opening the file for writing or removing it raises ``OSError`` +//| ``EACCES``. Writing or removing it over the web workflow or BLE stops the program first. +//| A USB host can still rewrite it. +//| +//| File mapping is enabled by default. To disable it, including automatic +//| `displayio.OnDiskBitmap` mapping, set ``CIRCUITPY_STORAGE_MAP_FILE = false`` in +//| ``settings.toml`` and press RESET or power-cycle the board. A reload does not +//| change the boot-time setting. +//| +//| :param typing.BinaryIO file: A file on the CIRCUITPY drive open with ``"rb"`` +//| :raises OSError: ``EINVAL`` if the file is closed or not open for reading only, +//| ``EOPNOTSUPP`` if mapping is disabled in ``settings.toml``, the file is not on a FAT +//| CIRCUITPY drive, or the drive is not memory-mapped, +//| ``EIO`` if its cluster chain is corrupt +//| :raises ~builtins.MemoryError: if the file's cluster map could not be allocated +//| :raises NotImplementedError: on a port whose drive is not memory-mapped""" +//| ... +static mp_obj_t storage_map_file(mp_obj_t file_in) { + return common_hal_storage_map_file(file_in); +} +MP_DEFINE_CONST_FUN_OBJ_1(storage_map_file_obj, storage_map_file); + static const mp_rom_map_elem_t storage_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_storage) }, - { MP_ROM_QSTR(MP_QSTR_mount), MP_ROM_PTR(&storage_mount_obj) }, - { MP_ROM_QSTR(MP_QSTR_umount), MP_ROM_PTR(&storage_umount_obj) }, - { MP_ROM_QSTR(MP_QSTR_remount), MP_ROM_PTR(&storage_remount_obj) }, - { MP_ROM_QSTR(MP_QSTR_getmount), MP_ROM_PTR(&storage_getmount_obj) }, - { MP_ROM_QSTR(MP_QSTR_erase_filesystem), MP_ROM_PTR(&storage_erase_filesystem_obj) }, - { MP_ROM_QSTR(MP_QSTR_disable_usb_drive), MP_ROM_PTR(&storage_disable_usb_drive_obj) }, - { MP_ROM_QSTR(MP_QSTR_enable_usb_drive), MP_ROM_PTR(&storage_enable_usb_drive_obj) }, + { MP_ROM_QSTR(MP_QSTR_mount), MP_ROM_PTR(&storage_mount_obj) }, + { MP_ROM_QSTR(MP_QSTR_umount), MP_ROM_PTR(&storage_umount_obj) }, + { MP_ROM_QSTR(MP_QSTR_remount), MP_ROM_PTR(&storage_remount_obj) }, + { MP_ROM_QSTR(MP_QSTR_getmount), MP_ROM_PTR(&storage_getmount_obj) }, + { MP_ROM_QSTR(MP_QSTR_map_file), MP_ROM_PTR(&storage_map_file_obj) }, + { MP_ROM_QSTR(MP_QSTR_erase_filesystem), MP_ROM_PTR(&storage_erase_filesystem_obj) }, + { MP_ROM_QSTR(MP_QSTR_disable_usb_drive), MP_ROM_PTR(&storage_disable_usb_drive_obj) }, + { MP_ROM_QSTR(MP_QSTR_enable_usb_drive), MP_ROM_PTR(&storage_enable_usb_drive_obj) }, + { MP_ROM_QSTR(MP_QSTR_unsafe_disable_usb_drive), MP_ROM_PTR(&storage_unsafe_disable_usb_drive_obj) }, //| class VfsFat: //| def __init__(self, block_device: BlockDevice) -> None: diff --git a/shared-bindings/storage/__init__.h b/shared-bindings/storage/__init__.h index 7ab5fc97bd7..2f3d3021360 100644 --- a/shared-bindings/storage/__init__.h +++ b/shared-bindings/storage/__init__.h @@ -16,7 +16,40 @@ 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_erase_filesystem(bool extended); +MP_NORETURN void common_hal_storage_erase_filesystem(bool extended); bool common_hal_storage_disable_usb_drive(void); +bool common_hal_storage_unsafe_disable_usb_drive(void); bool common_hal_storage_enable_usb_drive(void); + +mp_obj_t common_hal_storage_map_file(mp_obj_t file); +#if CIRCUITPY_STORAGE_MAP_FILE +struct _fs_user_mount_t; +// Raises OSError if path on vfs is a file mapped since the VM started: a write would change +// bytes in use. +void storage_map_file_check_writable(struct _fs_user_mount_t *vfs, const char *path); +// True if path on vfs is such a file. Does not raise: for the supervisor's file writers. +bool storage_map_file_in_use(struct _fs_user_mount_t *vfs, const char *path); +// Read the mapping setting once after mounting CIRCUITPY, before user code runs. +void storage_map_file_init(void); +void storage_map_file_reset(void); +// A run is a part of a file that lies at consecutive flash addresses. A fragmented file has +// several runs. +// Calls fn for each run of a CIRCUITPY file open for reading, in file order, with the run's first +// drive block. Returns 0, or +// MP_EINVAL (closed or writable), MP_EOPNOTSUPP (mapping disabled or not a mapped CIRCUITPY +// file), MP_ENOMEM (no cluster map) or MP_EIO (bad chain). +typedef void (*storage_map_run_fn_t)(void *ctx, const uint8_t *addr, size_t len, uint32_t block); +int storage_map_runs(mp_obj_t file, storage_map_run_fn_t fn, void *ctx); +#endif +#if CIRCUITPY_STORAGE_MAP_IMPORT +#include "py/reader.h" +// Points reader at filename's flash runs if it is a mapped CIRCUITPY file; false otherwise. +bool storage_map_file_reader(mp_reader_t *reader, qstr filename); +mp_uint_t storage_map_reader_readbyte(void *data); +// Data in flash for the next len bytes if they lie in one run, else NULL and nothing is consumed. +const uint8_t *storage_map_reader_try_read_rom(void *data, size_t len); +// True if writing CIRCUITPY blocks [lba, lba + count) would change an imported .mpy that may +// still run. Call with interrupts disabled: the USB task may run beside the VM. +bool storage_map_import_uses_blocks(uint32_t lba, uint32_t count); +#endif diff --git a/shared-bindings/struct/__init__.c b/shared-bindings/struct/__init__.c index 3f9fd40895e..08f3aa3d307 100644 --- a/shared-bindings/struct/__init__.c +++ b/shared-bindings/struct/__init__.c @@ -24,7 +24,10 @@ //| Supported size/byte order prefixes: *@*, *<*, *>*, *!*. //| //| Supported format codes: *b*, *B*, *x*, *h*, *H*, *i*, *I*, *l*, *L*, *q*, *Q*, -//| *s*, *P*, *f*, *d* (the latter 2 depending on the floating-point support).""" +//| *s*, *P*, *f*, *d* (the latter 2 depending on the floating-point support). +//| +//| **Limitations**: *d* is not available on non-full builds, such as most SAMD21 boards. +//| Using it raises ``ValueError``.""" //| //| diff --git a/shared-bindings/supervisor/Runtime.c b/shared-bindings/supervisor/Runtime.c index 7b497639939..d5bdaf19cde 100644 --- a/shared-bindings/supervisor/Runtime.c +++ b/shared-bindings/supervisor/Runtime.c @@ -20,12 +20,12 @@ #include "supervisor/shared/status_leds.h" #include "supervisor/shared/bluetooth/bluetooth.h" -#if CIRCUITPY_DISPLAYIO -#include "shared-bindings/displayio/__init__.h" +#if CIRCUITPY_USB_DEVICE +#include "supervisor/usb.h" #endif -#if CIRCUITPY_TINYUSB -#include "tusb.h" +#if CIRCUITPY_DISPLAYIO +#include "shared-bindings/displayio/__init__.h" #endif static supervisor_run_reason_t _run_reason; @@ -52,7 +52,7 @@ static supervisor_run_reason_t _run_reason; //| """Returns the USB enumeration status (read-only).""" static mp_obj_t supervisor_runtime_get_usb_connected(mp_obj_t self) { #if CIRCUITPY_USB_DEVICE - return mp_obj_new_bool(tud_ready()); + return mp_obj_new_bool(usb_connected()); #else return mp_const_false; #endif @@ -153,10 +153,13 @@ MP_PROPERTY_GETSET(supervisor_runtime_autoreload_obj, //| ble_workflow: bool //| """Enable/Disable ble workflow until a reset. This prevents BLE advertising outside of the VM and -//| the services used for it.""" +//| the services used for it. +//| If ``CIRCUITPY_BLE_WORKFLOW=false`` is present in ``settings.toml``, setting `ble_workflow` +//| to ``True`` has no effect. +//| """ //| static mp_obj_t supervisor_runtime_get_ble_workflow(mp_obj_t self) { - #if CIRCUITPY_BLE_FILE_SERVICE && CIRCUITPY_SERIAL_BLE + #if CIRCUITPY_BLE_FILE_SERVICE && CIRCUITPY_BLE_SERIAL_SERVICE return mp_obj_new_bool(supervisor_bluetooth_workflow_is_enabled()); #else return mp_const_false; @@ -165,7 +168,7 @@ static mp_obj_t supervisor_runtime_get_ble_workflow(mp_obj_t self) { MP_DEFINE_CONST_FUN_OBJ_1(supervisor_runtime_get_ble_workflow_obj, supervisor_runtime_get_ble_workflow); static mp_obj_t supervisor_runtime_set_ble_workflow(mp_obj_t self, mp_obj_t state_in) { - #if CIRCUITPY_BLE_FILE_SERVICE && CIRCUITPY_SERIAL_BLE + #if CIRCUITPY_BLE_FILE_SERVICE && CIRCUITPY_BLE_SERIAL_SERVICE if (mp_obj_is_true(state_in)) { supervisor_bluetooth_enable_workflow(); } else { @@ -213,14 +216,16 @@ MP_PROPERTY_GETSET(supervisor_runtime_rgb_status_brightness_obj, //| //| If the board has a display that is hard coded, or that was explicitly set //| in boot.py or code.py (including a previous run of code.py), it is -//| available here until it is released with ``displayio.release_displays()``. +//| available here until it is released with ``supervisor.runtime.display.deinit()``. //| //| The display can be of any supported display type, such as `busdisplay.BusDisplay`. +//| A subclass of one, such as a display from a driver library, can also be assigned. +//| Reading the property back then returns the underlying built-in display object. //| //| If no display is configured, this property is `None`. //| -//| In a future release of CircuitPython, any display that is not the primary display -//| will be automatically released at the end of running a code file. +//| Any display that is not the primary display is automatically released at the end of +//| running a code file. //| //| On boards without displayio, this property is present but the value is always `None`.""" //| @@ -240,6 +245,29 @@ MP_PROPERTY_GETSET(supervisor_runtime_display_obj, (mp_obj_t)&supervisor_runtime_set_display_obj); #endif +MP_WEAK mp_obj_t common_hal_supervisor_runtime_get_audio(void) { + return mp_const_none; +} + +//| audio: picodvi.AudioOut | None +//| """The default audio output for the supervisor and user code. +//| +//| On boards with a default DVI display this is a `picodvi.AudioOut` that +//| sends sound over the DVI cable along with the picture. It is `None` when +//| the display did not start, when audio is turned off with +//| ``CIRCUITPY_PICODVI_AUDIO = false`` in ``settings.toml``, or after the +//| display is released, such as with ``supervisor.runtime.display.deinit()``. +//| +//| On boards without such an output, this property is always `None`.""" +//| +static mp_obj_t supervisor_runtime_get_audio(mp_obj_t self) { + return common_hal_supervisor_runtime_get_audio(); +} +MP_DEFINE_CONST_FUN_OBJ_1(supervisor_runtime_get_audio_obj, supervisor_runtime_get_audio); + +MP_PROPERTY_GETTER(supervisor_runtime_audio_obj, + (mp_obj_t)&supervisor_runtime_get_audio_obj); + static const mp_rom_map_elem_t supervisor_runtime_locals_dict_table[] = { { 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) }, @@ -254,6 +282,7 @@ static const mp_rom_map_elem_t supervisor_runtime_locals_dict_table[] = { #else { MP_ROM_QSTR(MP_QSTR_display), MP_ROM_NONE }, #endif + { MP_ROM_QSTR(MP_QSTR_audio), MP_ROM_PTR(&supervisor_runtime_audio_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 index 054281e5490..42cc6f3a979 100644 --- a/shared-bindings/supervisor/Runtime.h +++ b/shared-bindings/supervisor/Runtime.h @@ -23,6 +23,11 @@ bool common_hal_supervisor_runtime_get_serial_connected(void); uint32_t common_hal_supervisor_runtime_get_serial_bytes_available(void); +// Returns the audio output that the supervisor set up along with the boot +// display, or mp_const_none if there is none. The default returns +// mp_const_none; a port overrides it when it has one. Never raises. +mp_obj_t common_hal_supervisor_runtime_get_audio(void); + // TODO: placeholders for future functions // bool common_hal_get_supervisor_runtime_repl_active(void); // bool common_hal_get_supervisor_runtime_usb_enumerated(void); diff --git a/shared-bindings/supervisor/SafeModeReason.c b/shared-bindings/supervisor/SafeModeReason.c index ff85d8a3d5c..1aaa8f834c7 100644 --- a/shared-bindings/supervisor/SafeModeReason.c +++ b/shared-bindings/supervisor/SafeModeReason.c @@ -18,6 +18,7 @@ MAKE_ENUM_VALUE(supervisor_safe_mode_reason_type, safe_mode_reason, FLASH_WRITE_ MAKE_ENUM_VALUE(supervisor_safe_mode_reason_type, safe_mode_reason, GC_ALLOC_OUTSIDE_VM, SAFE_MODE_GC_ALLOC_OUTSIDE_VM); MAKE_ENUM_VALUE(supervisor_safe_mode_reason_type, safe_mode_reason, HARD_FAULT, SAFE_MODE_HARD_FAULT); MAKE_ENUM_VALUE(supervisor_safe_mode_reason_type, safe_mode_reason, INTERRUPT_ERROR, SAFE_MODE_INTERRUPT_ERROR); +MAKE_ENUM_VALUE(supervisor_safe_mode_reason_type, safe_mode_reason, LVGL_OUT_OF_MEMORY, SAFE_MODE_LVGL_OUT_OF_MEMORY); MAKE_ENUM_VALUE(supervisor_safe_mode_reason_type, safe_mode_reason, NLR_JUMP_FAIL, SAFE_MODE_NLR_JUMP_FAIL); MAKE_ENUM_VALUE(supervisor_safe_mode_reason_type, safe_mode_reason, NO_CIRCUITPY, SAFE_MODE_NO_CIRCUITPY); MAKE_ENUM_VALUE(supervisor_safe_mode_reason_type, safe_mode_reason, NO_HEAP, SAFE_MODE_NO_HEAP); @@ -71,6 +72,11 @@ MAKE_ENUM_MAP(supervisor_safe_mode_reason) { //| MAKE_ENUM_MAP_ENTRY(safe_mode_reason, INTERRUPT_ERROR), +//| LVGL_OUT_OF_MEMORY: object +//| """LVGL could not allocate memory.""" +//| + MAKE_ENUM_MAP_ENTRY(safe_mode_reason, LVGL_OUT_OF_MEMORY), + //| NLR_JUMP_FAIL: object //| """An error occurred during exception handling, possibly due to memory corruption.""" //| diff --git a/shared-bindings/supervisor/__init__.c b/shared-bindings/supervisor/__init__.c index 7b1eac7c2a7..eed98d21faa 100644 --- a/shared-bindings/supervisor/__init__.c +++ b/shared-bindings/supervisor/__init__.c @@ -3,6 +3,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2016-2017 Scott Shawcroft for Adafruit Industries // // SPDX-License-Identifier: MIT +#include #include #include "py/obj.h" @@ -20,11 +21,16 @@ #include "supervisor/usb.h" #endif +#if CIRCUITPY_SETTINGS_TOML +#include "supervisor/shared/settings.h" +#endif + #include "shared-bindings/microcontroller/__init__.h" #include "shared-bindings/supervisor/__init__.h" #include "shared-bindings/time/__init__.h" #include "shared-bindings/supervisor/Runtime.h" #include "shared-bindings/supervisor/StatusBar.h" +#include "shared-bindings/util.h" //| """Supervisor settings""" //| @@ -57,6 +63,7 @@ MP_DEFINE_CONST_FUN_OBJ_0(supervisor_reload_obj, supervisor_reload); //| def set_next_code_file( //| filename: Optional[str], //| *, +//| working_directory: Optional[str] = None, //| reload_on_success: bool = False, //| reload_on_error: bool = False, //| sticky_on_success: bool = False, @@ -99,6 +106,7 @@ MP_DEFINE_CONST_FUN_OBJ_0(supervisor_reload_obj, supervisor_reload); static mp_obj_t supervisor_set_next_code_file(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { static const mp_arg_t allowed_args[] = { { MP_QSTR_filename, MP_ARG_REQUIRED | MP_ARG_OBJ, {.u_rom_obj = mp_const_none} }, + { MP_QSTR_working_directory, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = mp_const_none} }, { MP_QSTR_reload_on_success, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, { MP_QSTR_reload_on_error, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, { MP_QSTR_sticky_on_success, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = false} }, @@ -107,6 +115,7 @@ static mp_obj_t supervisor_set_next_code_file(size_t n_args, const mp_obj_t *pos }; struct { mp_arg_val_t filename; + mp_arg_val_t working_directory; mp_arg_val_t reload_on_success; mp_arg_val_t reload_on_error; mp_arg_val_t sticky_on_success; @@ -118,6 +127,11 @@ static mp_obj_t supervisor_set_next_code_file(size_t n_args, const mp_obj_t *pos if (!mp_obj_is_str_or_bytes(filename_obj) && filename_obj != mp_const_none) { mp_raise_TypeError_varg(MP_ERROR_TEXT("%q must be of type %q or %q, not %q"), MP_QSTR_filename, MP_QSTR_str, MP_QSTR_None, mp_obj_get_type(filename_obj)->name); } + + mp_obj_t working_directory_obj = args.working_directory.u_obj; + if (!mp_obj_is_str_or_bytes(working_directory_obj) && working_directory_obj != mp_const_none) { + mp_raise_TypeError_varg(MP_ERROR_TEXT("%q must be of type %q or %q, not %q"), MP_QSTR_working_directory, MP_QSTR_str, MP_QSTR_None, mp_obj_get_type(working_directory_obj)->name); + } if (filename_obj == mp_const_none) { filename_obj = mp_const_empty_bytes; } @@ -139,18 +153,50 @@ static mp_obj_t supervisor_set_next_code_file(size_t n_args, const mp_obj_t *pos } size_t len; const char *filename = mp_obj_str_get_data(filename_obj, &len); + if (!path_exists(filename)) { + mp_raise_ValueError(MP_ERROR_TEXT("File not found")); + } + + size_t working_directory_len = 0; + const char *working_directory = NULL; + if (working_directory_obj != mp_const_none) { + working_directory = mp_obj_str_get_data(working_directory_obj, &working_directory_len); + if (!path_exists(working_directory)) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("Invalid %q"), MP_QSTR_working_directory); + } + } if (next_code_configuration != NULL) { port_free(next_code_configuration); next_code_configuration = NULL; } if (options != 0 || len != 0) { - next_code_configuration = port_malloc(sizeof(supervisor_next_code_info_t) + len + 1, false); + + size_t next_code_size = sizeof(supervisor_next_code_info_t) + len + 1; + if (working_directory_len > 0) { + next_code_size += working_directory_len + 1; + } + next_code_configuration = port_malloc(next_code_size, false); if (next_code_configuration == NULL) { - m_malloc_fail(sizeof(supervisor_next_code_info_t) + len + 1); + m_malloc_fail(next_code_size); } + char *filename_ptr = (char *)next_code_configuration + sizeof(supervisor_next_code_info_t); + + // Copy filename + memcpy(filename_ptr, filename, len); + filename_ptr[len] = '\0'; + + char *working_directory_ptr = NULL; + // Copy working directory after filename if present + if (working_directory_len > 0) { + working_directory_ptr = filename_ptr + len + 1; + memcpy(working_directory_ptr, working_directory, working_directory_len); + working_directory_ptr[working_directory_len] = '\0'; + } + // Set everything up last. We may have raised an exception early and we + // don't want to free the memory if we failed. + next_code_configuration->filename = filename_ptr; + next_code_configuration->working_directory = working_directory_ptr; next_code_configuration->options = options | SUPERVISOR_NEXT_CODE_OPT_NEWLY_SET; - memcpy(&next_code_configuration->filename, filename, len); - next_code_configuration->filename[len] = '\0'; } return mp_const_none; } @@ -318,6 +364,75 @@ static mp_obj_t supervisor_set_usb_identification(size_t n_args, const mp_obj_t } MP_DEFINE_CONST_FUN_OBJ_KW(supervisor_set_usb_identification_obj, 0, supervisor_set_usb_identification); +//| def get_setting(key: str, default: object=None) -> int | float | str | bool: +//| """ +//| Get and parse the value for the given ``key`` from the ``/settings.toml`` file. +//| If ``key`` is not found or ``settings.toml`` is not present, return the ``default`` value. +//| +//| :param str key: The setting key to retrieve +//| :return: The setting value as an ``int``, ``float``, ``str``, or ``bool`` depending on the value in the file +//| +//| :raises ValueError: If the value cannot be parsed as a valid TOML value. +//| +//| The value must be parseable as one of these types: +//| +//| - ``str``: Double-quoted string. +//| The string may include Unicode characters, and ``\\u`` Unicode escapes. Backslash-escaped characters +//| ``\\b``, ``\\r``, ``\\n``, ``\\t``, ``\\v``, ``\\v`` are also allowed. +//| - ``int``: signed or unsigned integer: decimal, or hexadecimal ``0x1F``, octal ``0o17``, +//| or binary ``0b101``. Underscores are allowed: ``1_000``. +//| - ``bool``: lower-case ``true`` or ``false``. +//| The values are returned as Python ``True`` or ``False`` values. +//| - ``float``: signed or unsigned decimal number with a ``.`` or exponent, or ``inf``, ``inf``, ``nan``. +//| +//| Leading zeros are not allowed in integers or in the integer part of floats: +//| ``017`` and ``01.5`` are errors. +//| +//| Example:: +//| +//| # settings.toml: +//| WIDTH = 42 +//| color = "red" +//| DEBUG = true +//| RATIO = 1.5 +//| +//| import supervisor +//| print(supervisor.get_setting("WIDTH")) # prints 42 +//| print(supervisor.get_setting("color")) # prints 'red' +//| print(supervisor.get_setting("DEBUG")) # prints True +//| print(supervisor.get_setting("RATIO")) # prints 1.5 +//| """ +//| ... +//| +static mp_obj_t supervisor_get_setting(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + #if CIRCUITPY_SETTINGS_TOML + enum { ARG_key, ARG_default }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_key, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_default, MP_ARG_OBJ, {.u_rom_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, (mp_arg_val_t *)&args); + + const char *key = mp_obj_str_get_str(args[ARG_key].u_obj); + mp_obj_t value; + settings_err_t result = settings_get_obj(key, &value); + + switch (result) { + case SETTINGS_OK: + return value; + case SETTINGS_ERR_NOT_FOUND: + case SETTINGS_ERR_OPEN: + return args[ARG_default].u_obj; + default: + mp_raise_ValueError_varg(MP_ERROR_TEXT("Invalid %q"), MP_QSTR_value); + } + #else + mp_raise_NotImplementedError(NULL); + #endif +} +MP_DEFINE_CONST_FUN_OBJ_KW(supervisor_get_setting_obj, 1, supervisor_get_setting); + static const mp_rom_map_elem_t supervisor_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_supervisor) }, { MP_ROM_QSTR(MP_QSTR_runtime), MP_ROM_PTR(&common_hal_supervisor_runtime_obj) }, @@ -331,6 +446,7 @@ static const mp_rom_map_elem_t supervisor_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_set_next_code_file), MP_ROM_PTR(&supervisor_set_next_code_file_obj) }, { MP_ROM_QSTR(MP_QSTR_ticks_ms), MP_ROM_PTR(&supervisor_ticks_ms_obj) }, { MP_ROM_QSTR(MP_QSTR_get_previous_traceback), MP_ROM_PTR(&supervisor_get_previous_traceback_obj) }, + { MP_ROM_QSTR(MP_QSTR_get_setting), MP_ROM_PTR(&supervisor_get_setting_obj) }, { MP_ROM_QSTR(MP_QSTR_reset_terminal), MP_ROM_PTR(&supervisor_reset_terminal_obj) }, { MP_ROM_QSTR(MP_QSTR_set_usb_identification), MP_ROM_PTR(&supervisor_set_usb_identification_obj) }, { MP_ROM_QSTR(MP_QSTR_status_bar), MP_ROM_PTR(&shared_module_supervisor_status_bar_obj) }, diff --git a/shared-bindings/supervisor/__init__.h b/shared-bindings/supervisor/__init__.h index c442534072a..4be9667ef56 100644 --- a/shared-bindings/supervisor/__init__.h +++ b/shared-bindings/supervisor/__init__.h @@ -6,6 +6,8 @@ #pragma once +#include +#include // #include "py/mpconfig.h" #include "py/obj.h" @@ -18,7 +20,8 @@ typedef struct { uint8_t options; - char filename[]; + const char *working_directory; + const char *filename; } supervisor_next_code_info_t; extern const super_runtime_obj_t common_hal_supervisor_runtime_obj; diff --git a/shared-bindings/synthio/Biquad.c b/shared-bindings/synthio/Biquad.c index ae035b7dabc..55465fae024 100644 --- a/shared-bindings/synthio/Biquad.c +++ b/shared-bindings/synthio/Biquad.c @@ -1,77 +1,210 @@ // This file is part of the CircuitPython project: https://circuitpython.org // -// SPDX-FileCopyrightText: Copyright (c) 2021 Artyom Skrobov +// SPDX-FileCopyrightText: Copyright (c) 2023 Jeff Epler for Adafruit Industries // // SPDX-License-Identifier: MIT -#include -#include - #include "py/enum.h" -#include "py/mperrno.h" -#include "py/obj.h" -#include "py/objnamedtuple.h" +#include "py/objproperty.h" #include "py/runtime.h" +#include "shared-bindings/synthio/Biquad.h" +#include "shared-bindings/util.h" -#include "shared-bindings/synthio/__init__.h" -#include "shared-bindings/synthio/LFO.h" -#include "shared-bindings/synthio/Math.h" -#include "shared-bindings/synthio/MidiTrack.h" -#include "shared-bindings/synthio/Note.h" -#include "shared-bindings/synthio/Synthesizer.h" - -#include "shared-module/synthio/LFO.h" +//| class FilterMode: +//| """The type of filter""" +//| +//| LOW_PASS: FilterMode +//| """A low-pass filter""" +//| HIGH_PASS: FilterMode +//| """A high-pass filter""" +//| BAND_PASS: FilterMode +//| """A band-pass filter""" +//| NOTCH: FilterMode +//| """A notch filter""" +//| LOW_SHELF: FilterMode +//| """A low shelf filter""" +//| HIGH_SHELF: FilterMode +//| """A high shelf filter""" +//| PEAKING_EQ: FilterMode +//| """A peaking equalizer filter""" +//| +//| -#define default_attack_time (MICROPY_FLOAT_CONST(0.1)) -#define default_decay_time (MICROPY_FLOAT_CONST(0.05)) -#define default_release_time (MICROPY_FLOAT_CONST(0.2)) -#define default_attack_level (MICROPY_FLOAT_CONST(1.)) -#define default_sustain_level (MICROPY_FLOAT_CONST(0.8)) +MAKE_ENUM_VALUE(synthio_filter_mode_type, mode, LOW_PASS, SYNTHIO_LOW_PASS); +MAKE_ENUM_VALUE(synthio_filter_mode_type, mode, HIGH_PASS, SYNTHIO_HIGH_PASS); +MAKE_ENUM_VALUE(synthio_filter_mode_type, mode, BAND_PASS, SYNTHIO_BAND_PASS); +MAKE_ENUM_VALUE(synthio_filter_mode_type, mode, NOTCH, SYNTHIO_NOTCH); +MAKE_ENUM_VALUE(synthio_filter_mode_type, mode, LOW_SHELF, SYNTHIO_LOW_SHELF); +MAKE_ENUM_VALUE(synthio_filter_mode_type, mode, HIGH_SHELF, SYNTHIO_HIGH_SHELF); +MAKE_ENUM_VALUE(synthio_filter_mode_type, mode, PEAKING_EQ, SYNTHIO_PEAKING_EQ); -static const mp_arg_t biquad_properties[] = { - { MP_QSTR_a1, MP_ARG_OBJ | MP_ARG_REQUIRED, {.u_obj = MP_ROM_NONE} }, - { MP_QSTR_a2, MP_ARG_OBJ | MP_ARG_REQUIRED, {.u_obj = MP_ROM_NONE} }, - { MP_QSTR_b0, MP_ARG_OBJ | MP_ARG_REQUIRED, {.u_obj = MP_ROM_NONE} }, - { MP_QSTR_b1, MP_ARG_OBJ | MP_ARG_REQUIRED, {.u_obj = MP_ROM_NONE} }, - { MP_QSTR_b2, MP_ARG_OBJ | MP_ARG_REQUIRED, {.u_obj = MP_ROM_NONE} }, +MAKE_ENUM_MAP(synthio_filter_mode) { + MAKE_ENUM_MAP_ENTRY(mode, LOW_PASS), + MAKE_ENUM_MAP_ENTRY(mode, HIGH_PASS), + MAKE_ENUM_MAP_ENTRY(mode, BAND_PASS), + MAKE_ENUM_MAP_ENTRY(mode, NOTCH), + MAKE_ENUM_MAP_ENTRY(mode, LOW_SHELF), + MAKE_ENUM_MAP_ENTRY(mode, HIGH_SHELF), + MAKE_ENUM_MAP_ENTRY(mode, PEAKING_EQ), }; +static MP_DEFINE_CONST_DICT(synthio_filter_mode_locals_dict, synthio_filter_mode_locals_table); + +MAKE_PRINTER(synthio, synthio_filter_mode); + +MAKE_ENUM_TYPE(synthio, FilterMode, synthio_filter_mode); + +static synthio_filter_mode validate_synthio_filter_mode(mp_obj_t obj, qstr arg_name) { + return cp_enum_value(&synthio_filter_mode_type, obj, arg_name); +} + //| class Biquad: -//| def __init__(self, b0: float, b1: float, b2: float, a1: float, a2: float) -> None: -//| """Construct a normalized biquad filter object. +//| def __init__( +//| self, +//| mode: FilterMode, +//| frequency: BlockInput, +//| Q: BlockInput = 0.7071067811865475, +//| A: BlockInput = None, +//| ) -> None: +//| """Construct a biquad filter object with given settings. //| -//| This implements the "direct form 1" biquad filter, where each coefficient -//| has been pre-divided by a0. +//| ``frequency`` gives the center frequency or corner frequency of the filter, +//| depending on the mode. //| -//| Biquad objects are usually constructed via one of the related methods on a `Synthesizer` object -//| rather than directly from coefficients. +//| ``Q`` gives the gain or sharpness of the filter. //| -//| https://github.com/WebAudio/Audio-EQ-Cookbook/blob/main/Audio-EQ-Cookbook.txt +//| ``A`` controls the gain of peaking and shelving filters according to the +//| formula ``A = 10^(dBgain/40)``. For other filter types it is ignored. //| -//| .. note:: This is deprecated in ``9.x.x`` and will be removed in ``10.0.0``. Use `BlockBiquad` objects instead. -//| """ +//| Since ``frequency`` and ``Q`` are `BlockInput` objects, they can +//| be varied dynamically. Internally, this is evaluated as "direct form 1" +//| biquad filter. //| +//| The internal filter state x[] and y[] is not updated when the filter +//| coefficients change, and there is no theoretical justification for why +//| this should result in a stable filter output. However, in practice, +//| slowly varying the filter's characteristic frequency and sharpness +//| appears to work as you'd expect.""" //| + +static const mp_arg_t biquad_properties[] = { + { MP_QSTR_mode, MP_ARG_OBJ | MP_ARG_REQUIRED, {.u_obj = MP_OBJ_NULL } }, + { MP_QSTR_frequency, MP_ARG_OBJ | MP_ARG_REQUIRED, {.u_obj = MP_OBJ_NULL } }, + { MP_QSTR_Q, MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL } }, + { MP_QSTR_A, MP_ARG_OBJ, {.u_obj = MP_ROM_NONE } }, +}; + static mp_obj_t synthio_biquad_make_new(const mp_obj_type_t *type_in, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_mode, ARG_frequency, ARG_Q }; + mp_arg_val_t args[MP_ARRAY_SIZE(biquad_properties)]; mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(biquad_properties), biquad_properties, args); - for (size_t i = 0; i < MP_ARRAY_SIZE(biquad_properties); i++) { - args[i].u_obj = mp_obj_new_float(mp_arg_validate_type_float(args[i].u_obj, biquad_properties[i].qst)); + if (args[ARG_Q].u_obj == MP_OBJ_NULL) { + args[ARG_Q].u_obj = mp_obj_new_float(MICROPY_FLOAT_CONST(0.7071067811865475)); } - MP_STATIC_ASSERT(sizeof(mp_arg_val_t) == sizeof(mp_obj_t)); - return namedtuple_make_new(type_in, MP_ARRAY_SIZE(args), 0, &args[0].u_obj); + synthio_filter_mode mode = validate_synthio_filter_mode(args[ARG_mode].u_obj, MP_QSTR_mode); + mp_obj_t result = common_hal_synthio_biquad_new(mode); + properties_construct_helper(result, biquad_properties + 1, args + 1, MP_ARRAY_SIZE(biquad_properties) - 1); + return result; } -const mp_obj_namedtuple_type_t synthio_biquad_type_obj = { - NAMEDTUPLE_TYPE_BASE_AND_SLOTS_MAKE_NEW(MP_QSTR_Biquad, synthio_biquad_make_new), - .n_fields = 5, - .fields = { - MP_QSTR_a1, - MP_QSTR_a2, - MP_QSTR_b0, - MP_QSTR_b1, - MP_QSTR_b2, - }, +//| +//| mode: FilterMode +//| """The mode of filter (read-only)""" +static mp_obj_t synthio_biquad_get_mode(mp_obj_t self_in) { + synthio_biquad_t *self = MP_OBJ_TO_PTR(self_in); + return cp_enum_find(&synthio_filter_mode_type, common_hal_synthio_biquad_get_mode(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(synthio_biquad_get_mode_obj, synthio_biquad_get_mode); + +MP_PROPERTY_GETTER(synthio_biquad_mode_obj, + (mp_obj_t)&synthio_biquad_get_mode_obj); + +//| +//| frequency: BlockInput +//| """The central frequency (in Hz) of the filter""" +static mp_obj_t synthio_biquad_get_frequency(mp_obj_t self_in) { + synthio_biquad_t *self = MP_OBJ_TO_PTR(self_in); + return common_hal_synthio_biquad_get_frequency(self); +} +MP_DEFINE_CONST_FUN_OBJ_1(synthio_biquad_get_frequency_obj, synthio_biquad_get_frequency); + +static mp_obj_t synthio_biquad_set_frequency(mp_obj_t self_in, mp_obj_t arg) { + synthio_biquad_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_synthio_biquad_set_frequency(self, arg); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(synthio_biquad_set_frequency_obj, synthio_biquad_set_frequency); +MP_PROPERTY_GETSET(synthio_biquad_frequency_obj, + (mp_obj_t)&synthio_biquad_get_frequency_obj, + (mp_obj_t)&synthio_biquad_set_frequency_obj); + + +//| +//| Q: BlockInput +//| """The sharpness (Q) of the filter""" +//| +static mp_obj_t synthio_biquad_get_Q(mp_obj_t self_in) { + synthio_biquad_t *self = MP_OBJ_TO_PTR(self_in); + return common_hal_synthio_biquad_get_Q(self); +} +MP_DEFINE_CONST_FUN_OBJ_1(synthio_biquad_get_Q_obj, synthio_biquad_get_Q); + +static mp_obj_t synthio_biquad_set_Q(mp_obj_t self_in, mp_obj_t arg) { + synthio_biquad_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_synthio_biquad_set_Q(self, arg); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(synthio_biquad_set_Q_obj, synthio_biquad_set_Q); +MP_PROPERTY_GETSET(synthio_biquad_Q_obj, + (mp_obj_t)&synthio_biquad_get_Q_obj, + (mp_obj_t)&synthio_biquad_set_Q_obj); + +//| +//| A: BlockInput +//| """The gain (A) of the filter +//| +//| This setting only has an effect for peaking and shelving EQ filters. It is related +//| to the filter gain according to the formula ``A = 10^(dBgain/40)``. +//| """ +//| +//| +static mp_obj_t synthio_biquad_get_A(mp_obj_t self_in) { + synthio_biquad_t *self = MP_OBJ_TO_PTR(self_in); + return common_hal_synthio_biquad_get_A(self); +} +MP_DEFINE_CONST_FUN_OBJ_1(synthio_biquad_get_A_obj, synthio_biquad_get_A); + +static mp_obj_t synthio_biquad_set_A(mp_obj_t self_in, mp_obj_t arg) { + synthio_biquad_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_synthio_biquad_set_A(self, arg); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(synthio_biquad_set_A_obj, synthio_biquad_set_A); +MP_PROPERTY_GETSET(synthio_biquad_A_obj, + (mp_obj_t)&synthio_biquad_get_A_obj, + (mp_obj_t)&synthio_biquad_set_A_obj); + +static const mp_rom_map_elem_t synthio_biquad_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR_mode), MP_ROM_PTR(&synthio_biquad_mode_obj) }, + { MP_ROM_QSTR(MP_QSTR_frequency), MP_ROM_PTR(&synthio_biquad_frequency_obj) }, + { MP_ROM_QSTR(MP_QSTR_Q), MP_ROM_PTR(&synthio_biquad_Q_obj) }, + { MP_ROM_QSTR(MP_QSTR_A), MP_ROM_PTR(&synthio_biquad_A_obj) }, }; +static MP_DEFINE_CONST_DICT(synthio_biquad_locals_dict, synthio_biquad_locals_dict_table); + +static void biquad_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { + (void)kind; + properties_print_helper(print, self_in, biquad_properties, MP_ARRAY_SIZE(biquad_properties)); +} + +MP_DEFINE_CONST_OBJ_TYPE( + synthio_biquad_type_obj, + MP_QSTR_Biquad, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, synthio_biquad_make_new, + locals_dict, &synthio_biquad_locals_dict, + print, biquad_print + ); diff --git a/shared-bindings/synthio/Biquad.h b/shared-bindings/synthio/Biquad.h index 2b40960fc5d..616488525f2 100644 --- a/shared-bindings/synthio/Biquad.h +++ b/shared-bindings/synthio/Biquad.h @@ -7,9 +7,27 @@ #pragma once #include "py/obj.h" -#include "py/objnamedtuple.h" -extern const mp_obj_namedtuple_type_t synthio_biquad_type_obj; -mp_obj_t common_hal_synthio_new_lpf(mp_float_t w0, mp_float_t Q); -mp_obj_t common_hal_synthio_new_hpf(mp_float_t w0, mp_float_t Q); -mp_obj_t common_hal_synthio_new_bpf(mp_float_t w0, mp_float_t Q); +extern const mp_obj_type_t synthio_biquad_type_obj; +extern const mp_obj_type_t synthio_filter_mode_type; +typedef struct synthio_biquad synthio_biquad_t; + +typedef enum { + SYNTHIO_LOW_PASS, SYNTHIO_HIGH_PASS, SYNTHIO_BAND_PASS, SYNTHIO_NOTCH, + // filters beyond this line use the "A" parameter (in addition to f0 and Q) + SYNTHIO_PEAKING_EQ, SYNTHIO_LOW_SHELF, SYNTHIO_HIGH_SHELF +} synthio_filter_mode; + + +mp_obj_t common_hal_synthio_biquad_get_A(synthio_biquad_t *self); +void common_hal_synthio_biquad_set_A(synthio_biquad_t *self, mp_obj_t A); + +mp_obj_t common_hal_synthio_biquad_get_Q(synthio_biquad_t *self); +void common_hal_synthio_biquad_set_Q(synthio_biquad_t *self, mp_obj_t Q); + +mp_obj_t common_hal_synthio_biquad_get_frequency(synthio_biquad_t *self); +void common_hal_synthio_biquad_set_frequency(synthio_biquad_t *self, mp_obj_t frequency); + +synthio_filter_mode common_hal_synthio_biquad_get_mode(synthio_biquad_t *self); + +mp_obj_t common_hal_synthio_biquad_new(synthio_filter_mode mode); diff --git a/shared-bindings/synthio/BlockBiquad.c b/shared-bindings/synthio/BlockBiquad.c deleted file mode 100644 index 3e8d76a81a2..00000000000 --- a/shared-bindings/synthio/BlockBiquad.c +++ /dev/null @@ -1,210 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2023 Jeff Epler for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "py/enum.h" -#include "py/objproperty.h" -#include "py/runtime.h" -#include "shared-bindings/synthio/BlockBiquad.h" -#include "shared-bindings/util.h" - -//| class FilterMode: -//| """The type of filter""" -//| -//| LOW_PASS: FilterMode -//| """A low-pass filter""" -//| HIGH_PASS: FilterMode -//| """A high-pass filter""" -//| BAND_PASS: FilterMode -//| """A band-pass filter""" -//| NOTCH: FilterMode -//| """A notch filter""" -//| LOW_SHELF: FilterMode -//| """A low shelf filter""" -//| HIGH_SHELF: FilterMode -//| """A high shelf filter""" -//| PEAKING_EQ: FilterMode -//| """A peaking equalizer filter""" -//| -//| - -MAKE_ENUM_VALUE(synthio_filter_mode_type, mode, LOW_PASS, SYNTHIO_LOW_PASS); -MAKE_ENUM_VALUE(synthio_filter_mode_type, mode, HIGH_PASS, SYNTHIO_HIGH_PASS); -MAKE_ENUM_VALUE(synthio_filter_mode_type, mode, BAND_PASS, SYNTHIO_BAND_PASS); -MAKE_ENUM_VALUE(synthio_filter_mode_type, mode, NOTCH, SYNTHIO_NOTCH); -MAKE_ENUM_VALUE(synthio_filter_mode_type, mode, LOW_SHELF, SYNTHIO_LOW_SHELF); -MAKE_ENUM_VALUE(synthio_filter_mode_type, mode, HIGH_SHELF, SYNTHIO_HIGH_SHELF); -MAKE_ENUM_VALUE(synthio_filter_mode_type, mode, PEAKING_EQ, SYNTHIO_PEAKING_EQ); - -MAKE_ENUM_MAP(synthio_filter_mode) { - MAKE_ENUM_MAP_ENTRY(mode, LOW_PASS), - MAKE_ENUM_MAP_ENTRY(mode, HIGH_PASS), - MAKE_ENUM_MAP_ENTRY(mode, BAND_PASS), - MAKE_ENUM_MAP_ENTRY(mode, NOTCH), - MAKE_ENUM_MAP_ENTRY(mode, LOW_SHELF), - MAKE_ENUM_MAP_ENTRY(mode, HIGH_SHELF), - MAKE_ENUM_MAP_ENTRY(mode, PEAKING_EQ), -}; - -static MP_DEFINE_CONST_DICT(synthio_filter_mode_locals_dict, synthio_filter_mode_locals_table); - -MAKE_PRINTER(synthio, synthio_filter_mode); - -MAKE_ENUM_TYPE(synthio, FilterMode, synthio_filter_mode); - -static synthio_filter_mode validate_synthio_filter_mode(mp_obj_t obj, qstr arg_name) { - return cp_enum_value(&synthio_filter_mode_type, obj, arg_name); -} - -//| class BlockBiquad: -//| def __init__( -//| self, -//| mode: FilterMode, -//| frequency: BlockInput, -//| Q: BlockInput = 0.7071067811865475, -//| A: BlockInput = None, -//| ) -> None: -//| """Construct a biquad filter object with given settings. -//| -//| ``frequency`` gives the center frequency or corner frequency of the filter, -//| depending on the mode. -//| -//| ``Q`` gives the gain or sharpness of the filter. -//| -//| ``A`` controls the gain of peaking and shelving filters according to the -//| formula ``A = 10^(dBgain/40)``. For other filter types it is ignored. -//| -//| Since ``frequency`` and ``Q`` are `BlockInput` objects, they can -//| be varied dynamically. Internally, this is evaluated as "direct form 1" -//| biquad filter. -//| -//| The internal filter state x[] and y[] is not updated when the filter -//| coefficients change, and there is no theoretical justification for why -//| this should result in a stable filter output. However, in practice, -//| slowly varying the filter's characteristic frequency and sharpness -//| appears to work as you'd expect.""" -//| - -static const mp_arg_t block_biquad_properties[] = { - { MP_QSTR_mode, MP_ARG_OBJ | MP_ARG_REQUIRED, {.u_obj = MP_OBJ_NULL } }, - { MP_QSTR_frequency, MP_ARG_OBJ | MP_ARG_REQUIRED, {.u_obj = MP_OBJ_NULL } }, - { MP_QSTR_Q, MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL } }, - { MP_QSTR_A, MP_ARG_OBJ, {.u_obj = MP_ROM_NONE } }, -}; - -static mp_obj_t synthio_block_biquad_make_new(const mp_obj_type_t *type_in, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { - enum { ARG_mode, ARG_frequency, ARG_Q }; - - mp_arg_val_t args[MP_ARRAY_SIZE(block_biquad_properties)]; - mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(block_biquad_properties), block_biquad_properties, args); - - if (args[ARG_Q].u_obj == MP_OBJ_NULL) { - args[ARG_Q].u_obj = mp_obj_new_float(MICROPY_FLOAT_CONST(0.7071067811865475)); - } - - synthio_filter_mode mode = validate_synthio_filter_mode(args[ARG_mode].u_obj, MP_QSTR_mode); - mp_obj_t result = common_hal_synthio_block_biquad_new(mode); - properties_construct_helper(result, block_biquad_properties + 1, args + 1, MP_ARRAY_SIZE(block_biquad_properties) - 1); - return result; -} - -//| -//| mode: FilterMode -//| """The mode of filter (read-only)""" -static mp_obj_t synthio_block_biquad_get_mode(mp_obj_t self_in) { - synthio_block_biquad_t *self = MP_OBJ_TO_PTR(self_in); - return cp_enum_find(&synthio_filter_mode_type, common_hal_synthio_block_biquad_get_mode(self)); -} -MP_DEFINE_CONST_FUN_OBJ_1(synthio_block_biquad_get_mode_obj, synthio_block_biquad_get_mode); - -MP_PROPERTY_GETTER(synthio_block_biquad_mode_obj, - (mp_obj_t)&synthio_block_biquad_get_mode_obj); - -//| -//| frequency: BlockInput -//| """The central frequency (in Hz) of the filter""" -static mp_obj_t synthio_block_biquad_get_frequency(mp_obj_t self_in) { - synthio_block_biquad_t *self = MP_OBJ_TO_PTR(self_in); - return common_hal_synthio_block_biquad_get_frequency(self); -} -MP_DEFINE_CONST_FUN_OBJ_1(synthio_block_biquad_get_frequency_obj, synthio_block_biquad_get_frequency); - -static mp_obj_t synthio_block_biquad_set_frequency(mp_obj_t self_in, mp_obj_t arg) { - synthio_block_biquad_t *self = MP_OBJ_TO_PTR(self_in); - common_hal_synthio_block_biquad_set_frequency(self, arg); - return mp_const_none; -} -MP_DEFINE_CONST_FUN_OBJ_2(synthio_block_biquad_set_frequency_obj, synthio_block_biquad_set_frequency); -MP_PROPERTY_GETSET(synthio_block_biquad_frequency_obj, - (mp_obj_t)&synthio_block_biquad_get_frequency_obj, - (mp_obj_t)&synthio_block_biquad_set_frequency_obj); - - -//| -//| Q: BlockInput -//| """The sharpness (Q) of the filter""" -//| -static mp_obj_t synthio_block_biquad_get_Q(mp_obj_t self_in) { - synthio_block_biquad_t *self = MP_OBJ_TO_PTR(self_in); - return common_hal_synthio_block_biquad_get_Q(self); -} -MP_DEFINE_CONST_FUN_OBJ_1(synthio_block_biquad_get_Q_obj, synthio_block_biquad_get_Q); - -static mp_obj_t synthio_block_biquad_set_Q(mp_obj_t self_in, mp_obj_t arg) { - synthio_block_biquad_t *self = MP_OBJ_TO_PTR(self_in); - common_hal_synthio_block_biquad_set_Q(self, arg); - return mp_const_none; -} -MP_DEFINE_CONST_FUN_OBJ_2(synthio_block_biquad_set_Q_obj, synthio_block_biquad_set_Q); -MP_PROPERTY_GETSET(synthio_block_biquad_Q_obj, - (mp_obj_t)&synthio_block_biquad_get_Q_obj, - (mp_obj_t)&synthio_block_biquad_set_Q_obj); - -//| -//| A: BlockInput -//| """The gain (A) of the filter -//| -//| This setting only has an effect for peaking and shelving EQ filters. It is related -//| to the filter gain according to the formula ``A = 10^(dBgain/40)``. -//| """ -//| -//| -static mp_obj_t synthio_block_biquad_get_A(mp_obj_t self_in) { - synthio_block_biquad_t *self = MP_OBJ_TO_PTR(self_in); - return common_hal_synthio_block_biquad_get_A(self); -} -MP_DEFINE_CONST_FUN_OBJ_1(synthio_block_biquad_get_A_obj, synthio_block_biquad_get_A); - -static mp_obj_t synthio_block_biquad_set_A(mp_obj_t self_in, mp_obj_t arg) { - synthio_block_biquad_t *self = MP_OBJ_TO_PTR(self_in); - common_hal_synthio_block_biquad_set_A(self, arg); - return mp_const_none; -} -MP_DEFINE_CONST_FUN_OBJ_2(synthio_block_biquad_set_A_obj, synthio_block_biquad_set_A); -MP_PROPERTY_GETSET(synthio_block_biquad_A_obj, - (mp_obj_t)&synthio_block_biquad_get_A_obj, - (mp_obj_t)&synthio_block_biquad_set_A_obj); - -static const mp_rom_map_elem_t synthio_block_biquad_locals_dict_table[] = { - { MP_ROM_QSTR(MP_QSTR_mode), MP_ROM_PTR(&synthio_block_biquad_mode_obj) }, - { MP_ROM_QSTR(MP_QSTR_frequency), MP_ROM_PTR(&synthio_block_biquad_frequency_obj) }, - { MP_ROM_QSTR(MP_QSTR_Q), MP_ROM_PTR(&synthio_block_biquad_Q_obj) }, - { MP_ROM_QSTR(MP_QSTR_A), MP_ROM_PTR(&synthio_block_biquad_A_obj) }, -}; -static MP_DEFINE_CONST_DICT(synthio_block_biquad_locals_dict, synthio_block_biquad_locals_dict_table); - -static void block_biquad_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) { - (void)kind; - properties_print_helper(print, self_in, block_biquad_properties, MP_ARRAY_SIZE(block_biquad_properties)); -} - -MP_DEFINE_CONST_OBJ_TYPE( - synthio_block_biquad_type_obj, - MP_QSTR_BlockBiquad, - MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, - make_new, synthio_block_biquad_make_new, - locals_dict, &synthio_block_biquad_locals_dict, - print, block_biquad_print - ); diff --git a/shared-bindings/synthio/BlockBiquad.h b/shared-bindings/synthio/BlockBiquad.h deleted file mode 100644 index 9132bb528f8..00000000000 --- a/shared-bindings/synthio/BlockBiquad.h +++ /dev/null @@ -1,33 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2023 Jeff Epler for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#pragma once - -#include "py/obj.h" - -extern const mp_obj_type_t synthio_block_biquad_type_obj; -extern const mp_obj_type_t synthio_filter_mode_type; -typedef struct synthio_block_biquad synthio_block_biquad_t; - -typedef enum { - SYNTHIO_LOW_PASS, SYNTHIO_HIGH_PASS, SYNTHIO_BAND_PASS, SYNTHIO_NOTCH, - // filters beyond this line use the "A" parameter (in addition to f0 and Q) - SYNTHIO_PEAKING_EQ, SYNTHIO_LOW_SHELF, SYNTHIO_HIGH_SHELF -} synthio_filter_mode; - - -mp_obj_t common_hal_synthio_block_biquad_get_A(synthio_block_biquad_t *self); -void common_hal_synthio_block_biquad_set_A(synthio_block_biquad_t *self, mp_obj_t A); - -mp_obj_t common_hal_synthio_block_biquad_get_Q(synthio_block_biquad_t *self); -void common_hal_synthio_block_biquad_set_Q(synthio_block_biquad_t *self, mp_obj_t Q); - -mp_obj_t common_hal_synthio_block_biquad_get_frequency(synthio_block_biquad_t *self); -void common_hal_synthio_block_biquad_set_frequency(synthio_block_biquad_t *self, mp_obj_t frequency); - -synthio_filter_mode common_hal_synthio_block_biquad_get_mode(synthio_block_biquad_t *self); - -mp_obj_t common_hal_synthio_block_biquad_new(synthio_filter_mode mode); diff --git a/shared-bindings/synthio/LFO.c b/shared-bindings/synthio/LFO.c index ee2d67d3089..2dfae22a577 100644 --- a/shared-bindings/synthio/LFO.c +++ b/shared-bindings/synthio/LFO.c @@ -103,17 +103,17 @@ static mp_obj_t synthio_lfo_make_new(const mp_obj_type_t *type_in, size_t n_args } self->waveform_obj = args[ARG_waveform].u_obj; - mp_obj_t result = MP_OBJ_FROM_PTR(self); - properties_construct_helper(result, lfo_properties + 1, args + 1, MP_ARRAY_SIZE(lfo_properties) - 1); + mp_obj_t self_obj = MP_OBJ_FROM_PTR(self); + properties_construct_helper(self_obj, lfo_properties + 1, args + 1, MP_ARRAY_SIZE(lfo_properties) - 1); // Force computation of the LFO's initial output synthio_global_rate_scale = 0; self->base.last_tick = synthio_global_tick - 1; synthio_block_slot_t slot; - synthio_block_assign_slot(MP_OBJ_FROM_PTR(result), &slot, MP_QSTR_self); + synthio_block_assign_slot(self_obj, &slot, MP_QSTR_self); (void)synthio_block_slot_get(&slot); - return result; + return self_obj; }; //| waveform: Optional[ReadableBuffer] diff --git a/shared-bindings/synthio/Math.c b/shared-bindings/synthio/Math.c index 5e943b44d0f..96857fb3513 100644 --- a/shared-bindings/synthio/Math.c +++ b/shared-bindings/synthio/Math.c @@ -157,10 +157,10 @@ static mp_obj_t synthio_math_make_new_common(mp_arg_val_t args[MP_ARRAY_SIZE(mat self->base.last_tick = synthio_global_tick; - mp_obj_t result = MP_OBJ_FROM_PTR(self); - properties_construct_helper(result, math_properties, args, MP_ARRAY_SIZE(math_properties)); + mp_obj_t self_obj = MP_OBJ_FROM_PTR(self); + properties_construct_helper(self_obj, math_properties, args, MP_ARRAY_SIZE(math_properties)); - return result; + return self_obj; }; //| a: BlockInput diff --git a/shared-bindings/synthio/MidiTrack.c b/shared-bindings/synthio/MidiTrack.c index 9add8f1745c..e2f1434bfac 100644 --- a/shared-bindings/synthio/MidiTrack.c +++ b/shared-bindings/synthio/MidiTrack.c @@ -23,16 +23,25 @@ //| buffer: ReadableBuffer, //| tempo: int, //| *, +//| ticks_per_beat: int = 0, //| sample_rate: int = 11025, //| waveform: Optional[ReadableBuffer] = None, //| envelope: Optional[Envelope] = None, //| ) -> 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. +//| """Create a MidiTrack from the given stream of MIDI events. +//| +//| "Note On" and "Note Off" events are played; a "Note On" with a velocity of zero is +//| treated as a "Note Off", as the MIDI specification allows. Other channel events are +//| skipped, as are System Exclusive and meta events, except that "End of Track" stops +//| playback and "Set Tempo" adjusts it when ``ticks_per_beat`` is known. Events that omit +//| a repeated status byte ("running status") are understood. Channel numbers and key +//| velocities are otherwise ignored. //| //| :param ~circuitpython_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 ticks_per_beat: Ticks per quarter note, from the MIDI file header. When this +//| is 0 (the default) any "Set Tempo" event in the stream is ignored, because its +//| microseconds-per-quarter-note value cannot be converted without it. //| :param int sample_rate: The desired playback sample rate; higher sample rate requires more memory //| :param ReadableBuffer waveform: A single-cycle waveform. Default is a 50% duty cycle square wave. If specified, must be a ReadableBuffer of type 'h' (signed 16 bit) //| :param Envelope envelope: An object that defines the loudness of a note over time. The default envelope provides no ramping, voices turn instantly on and off. @@ -55,10 +64,11 @@ //| ... //| static mp_obj_t synthio_miditrack_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { - enum { ARG_buffer, ARG_tempo, ARG_sample_rate, ARG_waveform, ARG_envelope }; + enum { ARG_buffer, ARG_tempo, ARG_ticks_per_beat, ARG_sample_rate, ARG_waveform, ARG_envelope }; 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_ticks_per_beat, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0} }, { MP_QSTR_sample_rate, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 11025} }, { MP_QSTR_waveform, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = mp_const_none } }, { MP_QSTR_envelope, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = mp_const_none } }, @@ -69,12 +79,12 @@ static mp_obj_t synthio_miditrack_make_new(const mp_obj_type_t *type, size_t n_a mp_buffer_info_t bufinfo; mp_get_buffer_raise(args[ARG_buffer].u_obj, &bufinfo, MP_BUFFER_READ); - synthio_miditrack_obj_t *self = mp_obj_malloc(synthio_miditrack_obj_t, &synthio_miditrack_type); - + synthio_miditrack_obj_t *self = mp_obj_malloc_with_finaliser(synthio_miditrack_obj_t, &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, + mp_arg_validate_int_min(args[ARG_tempo].u_int, 1, MP_QSTR_tempo), + args[ARG_ticks_per_beat].u_int, + mp_arg_validate_int_min(args[ARG_sample_rate].u_int, 1, MP_QSTR_sample_rate), args[ARG_waveform].u_obj, mp_const_none, args[ARG_envelope].u_obj @@ -115,6 +125,27 @@ static void check_for_deinit(synthio_miditrack_obj_t *self) { //| """32 bit value that tells how quickly samples are played in Hertz (cycles per second).""" //| +//| tempo: int +//| """Tempo of the streamed events, in MIDI ticks per second.""" +//| +static mp_obj_t synthio_miditrack_obj_get_tempo(mp_obj_t self_in) { + synthio_miditrack_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_int(common_hal_synthio_miditrack_get_tempo(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(synthio_miditrack_get_tempo_obj, synthio_miditrack_obj_get_tempo); + +static mp_obj_t synthio_miditrack_obj_set_tempo(mp_obj_t self_in, mp_obj_t arg) { + synthio_miditrack_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + common_hal_synthio_miditrack_set_tempo(self, mp_obj_get_int(arg)); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(synthio_miditrack_set_tempo_obj, synthio_miditrack_obj_set_tempo); +MP_PROPERTY_GETSET(synthio_miditrack_tempo_obj, + (mp_obj_t)&synthio_miditrack_get_tempo_obj, + (mp_obj_t)&synthio_miditrack_set_tempo_obj); + //| error_location: Optional[int] //| """Offset, in bytes within the midi data, of a decoding error""" //| @@ -136,11 +167,13 @@ MP_PROPERTY_GETTER(synthio_miditrack_error_location_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___del__), 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(&default___exit___obj) }, // Properties { MP_ROM_QSTR(MP_QSTR_error_location), MP_ROM_PTR(&synthio_miditrack_error_location_obj) }, + { MP_ROM_QSTR(MP_QSTR_tempo), MP_ROM_PTR(&synthio_miditrack_tempo_obj) }, AUDIOSAMPLE_FIELDS, }; static MP_DEFINE_CONST_DICT(synthio_miditrack_locals_dict, synthio_miditrack_locals_dict_table); diff --git a/shared-bindings/synthio/MidiTrack.h b/shared-bindings/synthio/MidiTrack.h index 72b217e9613..48e430156d5 100644 --- a/shared-bindings/synthio/MidiTrack.h +++ b/shared-bindings/synthio/MidiTrack.h @@ -11,7 +11,10 @@ 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, mp_obj_t waveform_obj, mp_obj_t filter_obj, mp_obj_t envelope_obj); +void common_hal_synthio_miditrack_construct(synthio_miditrack_obj_t *self, const uint8_t *buffer, uint32_t len, uint32_t tempo, uint32_t ticks_per_beat, uint32_t sample_rate, mp_obj_t waveform_obj, mp_obj_t filter_obj, mp_obj_t envelope_obj); void common_hal_synthio_miditrack_deinit(synthio_miditrack_obj_t *self); mp_int_t common_hal_synthio_miditrack_get_error_location(synthio_miditrack_obj_t *self); + +mp_int_t common_hal_synthio_miditrack_get_tempo(synthio_miditrack_obj_t *self); +void common_hal_synthio_miditrack_set_tempo(synthio_miditrack_obj_t *self, mp_int_t value); diff --git a/shared-bindings/synthio/Note.c b/shared-bindings/synthio/Note.c index 790e1661835..183c59d5fbd 100644 --- a/shared-bindings/synthio/Note.c +++ b/shared-bindings/synthio/Note.c @@ -42,7 +42,7 @@ static const mp_arg_t note_properties[] = { //| envelope: Optional[Envelope] = None, //| amplitude: BlockInput = 1.0, //| bend: BlockInput = 0.0, -//| filter: Optional[AnyBiquad] = None, +//| filter: Optional[Biquad] = None, //| ring_frequency: float = 0.0, //| ring_bend: float = 0.0, //| ring_waveform: Optional[ReadableBuffer] = None, @@ -61,11 +61,11 @@ static mp_obj_t synthio_note_make_new(const mp_obj_type_t *type_in, size_t n_arg mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(note_properties), note_properties, args); synthio_note_obj_t *self = mp_obj_malloc(synthio_note_obj_t, &synthio_note_type); + mp_obj_t self_obj = MP_OBJ_FROM_PTR(self); - mp_obj_t result = MP_OBJ_FROM_PTR(self); - properties_construct_helper(result, note_properties, args, MP_ARRAY_SIZE(note_properties)); + properties_construct_helper(self_obj, note_properties, args, MP_ARRAY_SIZE(note_properties)); - return result; + return self_obj; }; //| frequency: float @@ -86,7 +86,7 @@ MP_PROPERTY_GETSET(synthio_note_frequency_obj, (mp_obj_t)&synthio_note_get_frequency_obj, (mp_obj_t)&synthio_note_set_frequency_obj); -//| filter: Optional[AnyBiquad] +//| filter: Optional[Biquad] //| """If not None, the output of this Note is filtered according to the provided coefficients. //| //| Construct an appropriate filter by calling a filter-making method on the diff --git a/shared-bindings/synthio/Synthesizer.c b/shared-bindings/synthio/Synthesizer.c index 0cdcc255f48..41f941a1151 100644 --- a/shared-bindings/synthio/Synthesizer.c +++ b/shared-bindings/synthio/Synthesizer.c @@ -61,10 +61,9 @@ static mp_obj_t synthio_synthesizer_make_new(const mp_obj_type_t *type, size_t n mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); - synthio_synthesizer_obj_t *self = mp_obj_malloc(synthio_synthesizer_obj_t, &synthio_synthesizer_type); - + synthio_synthesizer_obj_t *self = mp_obj_malloc_with_finaliser(synthio_synthesizer_obj_t, &synthio_synthesizer_type); common_hal_synthio_synthesizer_construct(self, - args[ARG_sample_rate].u_int, + mp_arg_validate_int_min(args[ARG_sample_rate].u_int, 1, MP_QSTR_sample_rate), args[ARG_channel_count].u_int, args[ARG_waveform].u_obj, args[ARG_envelope].u_obj); @@ -269,6 +268,7 @@ MP_DEFINE_CONST_FUN_OBJ_2(synthio_synthesizer_note_info_obj, synthio_synthesizer //| //| This property is read-only but its contents may be modified by e.g., calling ``synth.blocks.append()`` or ``synth.blocks.remove()``. It is initially an empty list.""" //| +//| static mp_obj_t synthio_synthesizer_obj_get_blocks(mp_obj_t self_in) { synthio_synthesizer_obj_t *self = MP_OBJ_TO_PTR(self_in); check_for_deinit(self); @@ -279,123 +279,6 @@ MP_DEFINE_CONST_FUN_OBJ_1(synthio_synthesizer_get_blocks_obj, synthio_synthesize MP_PROPERTY_GETTER(synthio_synthesizer_blocks_obj, (mp_obj_t)&synthio_synthesizer_get_blocks_obj); -//| max_polyphony: int -//| """Maximum polyphony of the synthesizer (read-only class property)""" -//| - -//| def low_pass_filter(cls, frequency: float, Q: float = 0.7071067811865475) -> Biquad: -//| """Construct a low-pass filter with the given parameters. -//| -//| ``frequency``, called f0 in the cookbook, is the corner frequency in Hz -//| of the filter. -//| -//| ``Q`` controls how peaked the response will be at the cutoff frequency. A large value makes the response more peaked. -//| -//| .. note:: This is deprecated in ``9.x.x`` and will be removed in ``10.0.0``. Use `BlockBiquad` objects instead. -//| """ -//| - -enum passfilter_arg_e { ARG_f0, ARG_Q }; - -// M_PI is not part of the math.h standard and may not be defined -// And by defining our own we can ensure it uses the correct const format. -#define MP_PI MICROPY_FLOAT_CONST(3.14159265358979323846) - -static const mp_arg_t passfilter_properties[] = { - { MP_QSTR_frequency, MP_ARG_OBJ | MP_ARG_REQUIRED, {.u_obj = MP_ROM_NONE} }, - { MP_QSTR_Q, MP_ARG_OBJ, {.u_obj = MP_OBJ_NULL } }, -}; - -static mp_obj_t synthio_synthesizer_lpf(size_t n_pos, const mp_obj_t *pos_args, mp_map_t *kw_args) { - mp_arg_val_t args[MP_ARRAY_SIZE(passfilter_properties)]; - - mp_obj_t self_in = pos_args[0]; - synthio_synthesizer_obj_t *self = MP_OBJ_TO_PTR(self_in); - - mp_arg_parse_all(n_pos - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(passfilter_properties), passfilter_properties, args); - - mp_float_t f0 = mp_arg_validate_type_float(args[ARG_f0].u_obj, MP_QSTR_f0); - mp_float_t Q = - args[ARG_Q].u_obj == MP_OBJ_NULL ? MICROPY_FLOAT_CONST(0.7071067811865475) : - mp_arg_validate_type_float(args[ARG_Q].u_obj, MP_QSTR_Q); - - mp_float_t w0 = f0 / self->synth.base.sample_rate * 2 * MP_PI; - - return common_hal_synthio_new_lpf(w0, Q); - -} - -MP_DEFINE_CONST_FUN_OBJ_KW(synthio_synthesizer_lpf_fun_obj, 1, synthio_synthesizer_lpf); - -//| def high_pass_filter(cls, frequency: float, Q: float = 0.7071067811865475) -> Biquad: -//| """Construct a high-pass filter with the given parameters. -//| -//| ``frequency``, called f0 in the cookbook, is the corner frequency in Hz -//| of the filter. -//| -//| ``Q`` controls how peaked the response will be at the cutoff frequency. A large value makes the response more peaked. -//| -//| .. note:: This is deprecated in ``9.x.x`` and will be removed in ``10.0.0``. Use `BlockBiquad` objects instead. -//| """ -//| - -static mp_obj_t synthio_synthesizer_hpf(size_t n_pos, const mp_obj_t *pos_args, mp_map_t *kw_args) { - mp_arg_val_t args[MP_ARRAY_SIZE(passfilter_properties)]; - - mp_obj_t self_in = pos_args[0]; - synthio_synthesizer_obj_t *self = MP_OBJ_TO_PTR(self_in); - - mp_arg_parse_all(n_pos - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(passfilter_properties), passfilter_properties, args); - - mp_float_t f0 = mp_arg_validate_type_float(args[ARG_f0].u_obj, MP_QSTR_f0); - mp_float_t Q = - args[ARG_Q].u_obj == MP_OBJ_NULL ? MICROPY_FLOAT_CONST(0.7071067811865475) : - mp_arg_validate_type_float(args[ARG_Q].u_obj, MP_QSTR_Q); - - mp_float_t w0 = f0 / self->synth.base.sample_rate * 2 * MP_PI; - - return common_hal_synthio_new_hpf(w0, Q); - -} - -//| def band_pass_filter(cls, frequency: float, Q: float = 0.7071067811865475) -> Biquad: -//| """Construct a band-pass filter with the given parameters. -//| -//| ``frequency``, called f0 in the cookbook, is the center frequency in Hz -//| of the filter. -//| -//| ``Q`` Controls how peaked the response will be at the cutoff frequency. A large value makes the response more peaked. -//| -//| The coefficients are scaled such that the filter has a 0dB peak gain. -//| -//| .. note:: This is deprecated in ``9.x.x`` and will be removed in ``10.0.0``. Use `BlockBiquad` objects instead. -//| """ -//| -//| - -MP_DEFINE_CONST_FUN_OBJ_KW(synthio_synthesizer_hpf_fun_obj, 1, synthio_synthesizer_hpf); - -static mp_obj_t synthio_synthesizer_bpf(size_t n_pos, const mp_obj_t *pos_args, mp_map_t *kw_args) { - mp_arg_val_t args[MP_ARRAY_SIZE(passfilter_properties)]; - - mp_obj_t self_in = pos_args[0]; - synthio_synthesizer_obj_t *self = MP_OBJ_TO_PTR(self_in); - - mp_arg_parse_all(n_pos - 1, pos_args + 1, kw_args, MP_ARRAY_SIZE(passfilter_properties), passfilter_properties, args); - - mp_float_t f0 = mp_arg_validate_type_float(args[ARG_f0].u_obj, MP_QSTR_f0); - mp_float_t Q = - args[ARG_Q].u_obj == MP_OBJ_NULL ? MICROPY_FLOAT_CONST(0.7071067811865475) : - mp_arg_validate_type_float(args[ARG_Q].u_obj, MP_QSTR_Q); - - mp_float_t w0 = f0 / self->synth.base.sample_rate * 2 * MP_PI; - - return common_hal_synthio_new_bpf(w0, Q); - -} - -MP_DEFINE_CONST_FUN_OBJ_KW(synthio_synthesizer_bpf_fun_obj, 1, synthio_synthesizer_bpf); - static const mp_rom_map_elem_t synthio_synthesizer_locals_dict_table[] = { // Methods { MP_ROM_QSTR(MP_QSTR_press), MP_ROM_PTR(&synthio_synthesizer_press_obj) }, @@ -405,12 +288,10 @@ static const mp_rom_map_elem_t synthio_synthesizer_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_release_then_press), MP_ROM_PTR(&synthio_synthesizer_change_obj) }, { MP_ROM_QSTR(MP_QSTR_release_all_then_press), MP_ROM_PTR(&synthio_synthesizer_release_all_then_press_obj) }, { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&synthio_synthesizer_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&synthio_synthesizer_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, - { MP_ROM_QSTR(MP_QSTR_low_pass_filter), MP_ROM_PTR(&synthio_synthesizer_lpf_fun_obj) }, - { MP_ROM_QSTR(MP_QSTR_high_pass_filter), MP_ROM_PTR(&synthio_synthesizer_hpf_fun_obj) }, - { MP_ROM_QSTR(MP_QSTR_band_pass_filter), MP_ROM_PTR(&synthio_synthesizer_bpf_fun_obj) }, // Properties { MP_ROM_QSTR(MP_QSTR_envelope), MP_ROM_PTR(&synthio_synthesizer_envelope_obj) }, { MP_ROM_QSTR(MP_QSTR_max_polyphony), MP_ROM_INT(CIRCUITPY_SYNTHIO_MAX_CHANNELS) }, diff --git a/shared-bindings/synthio/__init__.c b/shared-bindings/synthio/__init__.c index 5972eb2638a..675bf7e1f22 100644 --- a/shared-bindings/synthio/__init__.c +++ b/shared-bindings/synthio/__init__.c @@ -12,12 +12,10 @@ #include "py/obj.h" #include "py/objnamedtuple.h" #include "py/runtime.h" -#include "extmod/vfs_fat.h" -#include "extmod/vfs_posix.h" +#include "py/stream.h" #include "shared-bindings/synthio/__init__.h" #include "shared-bindings/synthio/Biquad.h" -#include "shared-bindings/synthio/BlockBiquad.h" #include "shared-bindings/synthio/LFO.h" #include "shared-bindings/synthio/Math.h" #include "shared-bindings/synthio/MidiTrack.h" @@ -33,7 +31,6 @@ //| """ //| -//| AnyBiquad = Union["Biquad", "BlockBiquad"] //| //| //| class EnvelopeState: @@ -180,6 +177,9 @@ const mp_obj_namedtuple_type_t synthio_envelope_type_obj = { //| """Create an AudioSample from an already opened MIDI file. //| Currently, only single-track MIDI (type 0) is supported. //| +//| The file's tempo map is followed: the track starts at the MIDI default of 120 BPM and +//| each "Set Tempo" event changes the rate from that point on. +//| //| :param typing.BinaryIO file: Already opened MIDI file //| :param int sample_rate: The desired playback sample rate; higher sample rate requires more memory //| :param ReadableBuffer waveform: A single-cycle waveform. Default is a 50% duty cycle square wave. If specified, must be a ReadableBuffer of type 'h' (signed 16 bit) @@ -213,16 +213,23 @@ static mp_obj_t synthio_from_file(size_t n_args, const mp_obj_t *pos_args, mp_ma }; 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_vfs_fat_fileio)) { + mp_int_t sample_rate = mp_arg_validate_int_min(args[ARG_sample_rate].u_int, 1, MP_QSTR_sample_rate); + mp_obj_t file_obj = args[ARG_file].u_obj; + // Any readable, seekable binary stream works, regardless of which + // filesystem it came from. + const mp_stream_p_t *stream_p = mp_get_stream_raise(file_obj, MP_STREAM_OP_READ | MP_STREAM_OP_IOCTL); + if (stream_p->is_text) { mp_raise_TypeError(MP_ERROR_TEXT("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); + int errcode; + if (mp_stream_seek(file_obj, 0, MP_SEEK_SET, &errcode) == (mp_off_t)-1) { + mp_raise_OSError(errcode); + } + mp_uint_t bytes_read = mp_stream_rw(file_obj, chunk_header, sizeof(chunk_header), &errcode, MP_STREAM_RW_READ); + if (bytes_read == MP_STREAM_ERROR) { + mp_raise_OSError(errcode); } if (bytes_read != sizeof(chunk_header) || memcmp(chunk_header, "MThd\0\0\0\6\0\0\0\1", 12)) { @@ -230,43 +237,45 @@ static mp_obj_t synthio_from_file(size_t n_args, const mp_obj_t *pos_args, mp_ma // TODO: for a multi-track MIDI (type 1), return an AudioMixer } - uint16_t tempo; + uint32_t tempo; + uint32_t ticks_per_beat; if (chunk_header[12] & 0x80) { + // SMPTE: frames per second times ticks per frame is already an + // absolute rate, so Set Tempo events do not apply to it tempo = -(int8_t)chunk_header[12] * chunk_header[13]; + ticks_per_beat = 0; } else { - tempo = 2 * ((chunk_header[12] << 8) | chunk_header[13]); + ticks_per_beat = (chunk_header[12] << 8) | chunk_header[13]; + // until a Set Tempo event says otherwise, MIDI defaults to 120 BPM, + // i.e. two quarter notes per second + tempo = 2 * ticks_per_beat; } - if (f_read(&file->fp, chunk_header, 8, &bytes_read) != FR_OK) { - mp_raise_OSError(MP_EIO); + bytes_read = mp_stream_rw(file_obj, chunk_header, 8, &errcode, MP_STREAM_RW_READ); + if (bytes_read == MP_STREAM_ERROR) { + mp_raise_OSError(errcode); } if (bytes_read != 8 || memcmp(chunk_header, "MTrk", 4)) { mp_arg_error_invalid(MP_QSTR_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); - if (f_read(&file->fp, buffer, track_size, &bytes_read) != FR_OK) { - mp_raise_OSError(MP_EIO); + uint8_t *buffer = m_malloc_without_collect(track_size); + bytes_read = mp_stream_rw(file_obj, buffer, track_size, &errcode, MP_STREAM_RW_READ); + if (bytes_read == MP_STREAM_ERROR) { + mp_raise_OSError(errcode); } if (bytes_read != track_size) { mp_arg_error_invalid(MP_QSTR_file); } - synthio_miditrack_obj_t *result = mp_obj_malloc(synthio_miditrack_obj_t, &synthio_miditrack_type); - + synthio_miditrack_obj_t *result = mp_obj_malloc_with_finaliser(synthio_miditrack_obj_t, &synthio_miditrack_type); common_hal_synthio_miditrack_construct(result, buffer, track_size, - tempo, args[ARG_sample_rate].u_int, args[ARG_waveform].u_obj, + tempo, ticks_per_beat, sample_rate, args[ARG_waveform].u_obj, mp_const_none, args[ARG_envelope].u_obj ); - #if MICROPY_MALLOC_USES_ALLOCATED_SIZE - m_free(buffer, track_size); - #else - m_free(buffer); - #endif - return MP_OBJ_FROM_PTR(result); } MP_DEFINE_CONST_FUN_OBJ_KW(synthio_from_file_obj, 1, synthio_from_file); @@ -318,7 +327,6 @@ MP_DEFINE_CONST_FUN_OBJ_VAR(synthio_lfo_tick_obj, 1, synthio_lfo_tick); 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_Biquad), MP_ROM_PTR(&synthio_biquad_type_obj) }, - { MP_ROM_QSTR(MP_QSTR_BlockBiquad), MP_ROM_PTR(&synthio_block_biquad_type_obj) }, { MP_ROM_QSTR(MP_QSTR_FilterMode), MP_ROM_PTR(&synthio_filter_mode_type) }, { MP_ROM_QSTR(MP_QSTR_Math), MP_ROM_PTR(&synthio_math_type) }, { MP_ROM_QSTR(MP_QSTR_MathOperation), MP_ROM_PTR(&synthio_math_operation_type) }, diff --git a/shared-bindings/terminalio/Terminal.c b/shared-bindings/terminalio/Terminal.c index 570449ad424..3cec0489967 100644 --- a/shared-bindings/terminalio/Terminal.c +++ b/shared-bindings/terminalio/Terminal.c @@ -16,19 +16,29 @@ #include "py/stream.h" #include "shared-bindings/fontio/BuiltinFont.h" +#if CIRCUITPY_LVFONTIO +#include "shared-bindings/lvfontio/OnDiskFont.h" +#endif + //| class Terminal: -//| """Display a character stream with a TileGrid +//| """Terminal manages tile indices and cursor position based on VT100 commands. The ``font`` should be +//| a `fontio.BuiltinFont` and the ``scroll_area`` TileGrid's bitmap should match the font's bitmap. +//| +//| Display a character stream with a TileGrid //| //| ASCII control: +//| //| * ``\\r`` - Move cursor to column 1 //| * ``\\n`` - Move cursor down a row //| * ``\\b`` - Move cursor left one if possible //| //| OSC control sequences: +//| //| * ``ESC ] 0; ESC \\`` - Set title bar to //| * ``ESC ] ####; ESC \\`` - Ignored //| //| VT100 control sequences: +//| //| * ``ESC [ K`` - Clear the remainder of the line //| * ``ESC [ 0 K`` - Clear the remainder of the line //| * ``ESC [ 1 K`` - Clear start of the line to cursor @@ -46,16 +56,83 @@ //| * ``ESC [ ## ; ## ; ## m`` - Set the terminal display attributes. //| //| Supported Display attributes: -//| 0 - Reset all attributes -//| Foreground Colors Background Colors -//| 30 - Black 40 - Black -//| 31 - Red 41 - Red -//| 32 - Green 42 - Green -//| 33 - Yellow 43 - Yellow -//| 34 - Blue 44 - Blue -//| 35 - Magenta 45 - Magenta -//| 36 - Cyan 46 - Cyan -//| 37 - White 47 - White +//| +//| +--------+------------+------------+ +//| | Color | Foreground | Background | +//| +========+============+============+ +//| | Reset | 0 | 0 | +//| +--------+------------+------------+ +//| | Black | 30 | 40 | +//| +--------+------------+------------+ +//| | Red | 31 | 41 | +//| +--------+------------+------------+ +//| | Green | 32 | 42 | +//| +--------+------------+------------+ +//| | Yellow | 33 | 43 | +//| +--------+------------+------------+ +//| | Blue | 34 | 44 | +//| +--------+------------+------------+ +//| | Magenta| 35 | 45 | +//| +--------+------------+------------+ +//| | Cyan | 36 | 46 | +//| +--------+------------+------------+ +//| | White | 37 | 47 | +//| +--------+------------+------------+ +//| +//| .. note:: Colors apply to the whole terminal, not to individual characters. They change the +//| ``scroll_area`` palette, so all text changes color at once, including text already on +//| screen. The ``scroll_area`` ``pixel_shader`` must be a `displayio.Palette` with at least +//| 2 colors to use these attributes. +//| +//| For color per character, see the +//| `adafruit_color_terminal `_ +//| library, which uses `tilepalettemapper`. +//| +//| Example Usage: +//| +//| .. code-block:: python +//| +//| import time +//| import displayio +//| import supervisor +//| from displayio import Group, TileGrid +//| from terminalio import FONT, Terminal +//| +//| main_group = Group() +//| display = supervisor.runtime.display +//| font_bb = FONT.get_bounding_box() +//| screen_size = (display.width // font_bb[0], display.height // font_bb[1]) +//| char_size = FONT.get_bounding_box() +//| +//| palette = displayio.Palette(2) +//| palette[0] = 0x000000 +//| palette[1] = 0xffffff +//| +//| tilegrid = TileGrid( +//| bitmap=FONT.bitmap, width=screen_size[0], height=screen_size[1], +//| tile_width=char_size[0], tile_height=char_size[1], pixel_shader=palette) +//| +//| terminal = Terminal(tilegrid, FONT) +//| +//| main_group.append(tilegrid) +//| display.root_group = main_group +//| +//| message = "Hello World\\n" +//| terminal.write(message) +//| +//| print(terminal.cursor_x, terminal.cursor_y) +//| move_cursor = chr(27) + "[10;10H" +//| terminal.write(f"Moving the cursor\\n{move_cursor} To here") +//| +//| cursor_home = chr(27) + f"[{screen_size[1]};0H" +//| terminal.write(cursor_home) +//| i = 1 +//| while True: +//| terminal.write(f"Writing again {i}\\n") +//| i = i + 1 +//| time.sleep(1) +//| +//| //| """ //| //| def __init__( @@ -65,8 +142,6 @@ //| *, //| status_bar: Optional[displayio.TileGrid] = None, //| ) -> None: -//| """Terminal manages tile indices and cursor position based on VT100 commands. The font should be -//| a `fontio.BuiltinFont` and the TileGrid's bitmap should match the font's bitmap.""" //| ... //| @@ -86,14 +161,32 @@ static mp_obj_t terminalio_terminal_make_new(const mp_obj_type_t *type, size_t n status_bar = mp_arg_validate_type(args[ARG_status_bar].u_obj, &displayio_tilegrid_type, MP_QSTR_status_bar); } - fontio_builtinfont_t *font = mp_arg_validate_type(args[ARG_font].u_obj, &fontio_builtinfont_type, MP_QSTR_font); + mp_obj_t font = args[ARG_font].u_obj; - mp_arg_validate_int_min(scroll_area->width_in_tiles, 2, MP_QSTR_scroll_area_width); - mp_arg_validate_int_min(scroll_area->height_in_tiles, 2, MP_QSTR_scroll_area_height); + // Ensure the font is one of the supported types + bool valid_font = false; - terminalio_terminal_obj_t *self = mp_obj_malloc(terminalio_terminal_obj_t, &terminalio_terminal_type); + #if CIRCUITPY_FONTIO + if (mp_obj_is_type(font, &fontio_builtinfont_type)) { + valid_font = true; + } + #endif + + #if CIRCUITPY_LVFONTIO + if (mp_obj_is_type(font, &lvfontio_ondiskfont_type)) { + valid_font = true; + } + #endif + if (!valid_font) { + mp_raise_TypeError_varg(MP_ERROR_TEXT("unsupported %q type"), MP_QSTR_font); + } + + mp_arg_validate_int_min(scroll_area->width_in_tiles * scroll_area->height_in_tiles, 2, MP_QSTR_scroll_area_area); + + terminalio_terminal_obj_t *self = mp_obj_malloc(terminalio_terminal_obj_t, &terminalio_terminal_type); common_hal_terminalio_terminal_construct(self, scroll_area, font, status_bar); + return MP_OBJ_FROM_PTR(self); } @@ -114,7 +207,31 @@ static mp_uint_t terminalio_terminal_write(mp_obj_t self_in, const void *buf_in, return common_hal_terminalio_terminal_write(self, buf, size, errcode); } -static mp_uint_t terminalio_terminal_ioctl(mp_obj_t self_in, mp_uint_t request, mp_uint_t arg, int *errcode) { +//| cursor_x: int +//| """The x position of the cursor.""" +//| +static mp_obj_t terminalio_terminal_obj_get_cursor_x(mp_obj_t self_in) { + terminalio_terminal_obj_t *self = MP_OBJ_TO_PTR(self_in); + return MP_OBJ_NEW_SMALL_INT(common_hal_terminalio_terminal_get_cursor_x(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(terminalio_terminal_get_cursor_x_obj, terminalio_terminal_obj_get_cursor_x); + +MP_PROPERTY_GETTER(terminalio_terminal_cursor_x_obj, + (mp_obj_t)&terminalio_terminal_get_cursor_x_obj); + +//| cursor_y: int +//| """The y position of the cursor.""" +//| +static mp_obj_t terminalio_terminal_obj_get_cursor_y(mp_obj_t self_in) { + terminalio_terminal_obj_t *self = MP_OBJ_TO_PTR(self_in); + return MP_OBJ_NEW_SMALL_INT(common_hal_terminalio_terminal_get_cursor_y(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(terminalio_terminal_get_cursor_y_obj, terminalio_terminal_obj_get_cursor_y); + +MP_PROPERTY_GETTER(terminalio_terminal_cursor_y_obj, + (mp_obj_t)&terminalio_terminal_get_cursor_y_obj); + +static mp_uint_t terminalio_terminal_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) { terminalio_terminal_obj_t *self = MP_OBJ_TO_PTR(self_in); mp_uint_t ret; if (request == MP_STREAM_POLL) { @@ -133,6 +250,8 @@ static mp_uint_t terminalio_terminal_ioctl(mp_obj_t self_in, mp_uint_t request, static const mp_rom_map_elem_t terminalio_terminal_locals_dict_table[] = { // Standard stream methods. { MP_ROM_QSTR(MP_QSTR_write), MP_ROM_PTR(&mp_stream_write_obj) }, + { MP_ROM_QSTR(MP_QSTR_cursor_x), MP_ROM_PTR(&terminalio_terminal_cursor_x_obj) }, + { MP_ROM_QSTR(MP_QSTR_cursor_y), MP_ROM_PTR(&terminalio_terminal_cursor_y_obj) }, }; static MP_DEFINE_CONST_DICT(terminalio_terminal_locals_dict, terminalio_terminal_locals_dict_table); @@ -146,7 +265,7 @@ static const mp_stream_p_t terminalio_terminal_stream_p = { MP_DEFINE_CONST_OBJ_TYPE( terminalio_terminal_type, MP_QSTR_Terminal, - MP_TYPE_FLAG_ITER_IS_ITERNEXT, + MP_TYPE_FLAG_ITER_IS_ITERNEXT | MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, make_new, terminalio_terminal_make_new, locals_dict, (mp_obj_dict_t *)&terminalio_terminal_locals_dict, iter, mp_stream_unbuffered_iter, diff --git a/shared-bindings/terminalio/Terminal.h b/shared-bindings/terminalio/Terminal.h index 893db4d1311..6613500ac2e 100644 --- a/shared-bindings/terminalio/Terminal.h +++ b/shared-bindings/terminalio/Terminal.h @@ -13,10 +13,13 @@ extern const mp_obj_type_t terminalio_terminal_type; extern void common_hal_terminalio_terminal_construct(terminalio_terminal_obj_t *self, - displayio_tilegrid_t *scroll_area, const fontio_builtinfont_t *font, displayio_tilegrid_t *status_bar); + displayio_tilegrid_t *scroll_area, mp_obj_t font, displayio_tilegrid_t *status_bar); // 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); +extern uint16_t common_hal_terminalio_terminal_get_cursor_x(terminalio_terminal_obj_t *self); +extern uint16_t common_hal_terminalio_terminal_get_cursor_y(terminalio_terminal_obj_t *self); + extern bool common_hal_terminalio_terminal_ready_to_tx(terminalio_terminal_obj_t *self); diff --git a/shared-bindings/tilepalettemapper/TilePaletteMapper.c b/shared-bindings/tilepalettemapper/TilePaletteMapper.c index 88189de549d..c22ea47bf26 100644 --- a/shared-bindings/tilepalettemapper/TilePaletteMapper.c +++ b/shared-bindings/tilepalettemapper/TilePaletteMapper.c @@ -12,6 +12,7 @@ #include "shared-bindings/util.h" #include "shared-bindings/displayio/Palette.h" #include "shared-bindings/displayio/ColorConverter.h" +#include "shared-bindings/displayio/TileGrid.h" #include "shared-bindings/tilepalettemapper/TilePaletteMapper.h" //| class TilePaletteMapper: @@ -21,24 +22,21 @@ //| bitmap with a wider array of colors.""" //| //| def __init__( -//| self, palette: displayio.Palette, input_color_count: int, width: int, height: int +//| self, palette: displayio.Palette, input_color_count: int //| ) -> None: //| """Create a TilePaletteMApper object to store a set of color mappings for tiles. //| //| :param Union[displayio.Palette, displayio.ColorConverter] pixel_shader: //| The palette or ColorConverter to get mapped colors from. -//| :param int input_color_count: The number of colors in in the input bitmap. -//| :param int width: The width of the grid in tiles. -//| :param int height: The height of the grid in tiles.""" +//| :param int input_color_count: The number of colors in in the input bitmap.""" //| static mp_obj_t tilepalettemapper_tilepalettemapper_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { - enum { ARG_pixel_shader, ARG_input_color_count, ARG_width, ARG_height }; + enum { ARG_pixel_shader, ARG_input_color_count }; static const mp_arg_t allowed_args[] = { { MP_QSTR_pixel_shader, MP_ARG_OBJ | MP_ARG_REQUIRED }, { MP_QSTR_input_color_count, MP_ARG_INT | MP_ARG_REQUIRED }, - { MP_QSTR_width, MP_ARG_INT | MP_ARG_REQUIRED }, - { MP_QSTR_height, MP_ARG_INT | MP_ARG_REQUIRED }, + }; mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); @@ -46,8 +44,9 @@ static mp_obj_t tilepalettemapper_tilepalettemapper_make_new(const mp_obj_type_t if (!mp_obj_is_type(pixel_shader, &displayio_palette_type) && !mp_obj_is_type(pixel_shader, &displayio_colorconverter_type)) { mp_raise_TypeError_varg(MP_ERROR_TEXT("unsupported %q type"), MP_QSTR_pixel_shader); } + tilepalettemapper_tilepalettemapper_t *self = mp_obj_malloc(tilepalettemapper_tilepalettemapper_t, &tilepalettemapper_tilepalettemapper_type); - common_hal_tilepalettemapper_tilepalettemapper_construct(self, pixel_shader, args[ARG_input_color_count].u_int, args[ARG_width].u_int, args[ARG_height].u_int); + common_hal_tilepalettemapper_tilepalettemapper_construct(self, pixel_shader, args[ARG_input_color_count].u_int); return MP_OBJ_FROM_PTR(self); } @@ -84,9 +83,20 @@ static mp_obj_t tilepalettemapper_tilepalettemapper_obj_get_pixel_shader(mp_obj_ } MP_DEFINE_CONST_FUN_OBJ_1(tilepalettemapper_tilepalettemapper_get_pixel_shader_obj, tilepalettemapper_tilepalettemapper_obj_get_pixel_shader); -MP_PROPERTY_GETTER(tilepalettemapper_tilepalettemapper_palette_obj, +MP_PROPERTY_GETTER(tilepalettemapper_tilepalettemapper_pixel_shader_obj, (mp_obj_t)&tilepalettemapper_tilepalettemapper_get_pixel_shader_obj); +//| tilegrid: displayio.TileGrid +//| """The TileGrid that the TilePaletteMapper is used with.""" +//| +static mp_obj_t tilepalettemapper_tilepalettemapper_obj_get_tilegrid(mp_obj_t self_in) { + tilepalettemapper_tilepalettemapper_t *self = MP_OBJ_TO_PTR(self_in); + return common_hal_tilepalettemapper_tilepalettemapper_get_tilegrid(self); +} +MP_DEFINE_CONST_FUN_OBJ_1(tilepalettemapper_tilepalettemapper_get_tilegrid_obj, tilepalettemapper_tilepalettemapper_obj_get_tilegrid); + +MP_PROPERTY_GETTER(tilepalettemapper_tilepalettemapper_tilegrid_obj, + (mp_obj_t)&tilepalettemapper_tilepalettemapper_get_tilegrid_obj); //| def __getitem__(self, index: Union[Tuple[int, int], int]) -> Tuple[int]: //| """Returns the mapping for the given index. The index can either be an x,y tuple or an int equal @@ -154,7 +164,8 @@ static mp_obj_t tilepalettemapper_subscr(mp_obj_t self_in, mp_obj_t index_obj, m static const mp_rom_map_elem_t tilepalettemapper_tilepalettemapper_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_width), MP_ROM_PTR(&tilepalettemapper_tilepalettemapper_width_obj) }, { MP_ROM_QSTR(MP_QSTR_height), MP_ROM_PTR(&tilepalettemapper_tilepalettemapper_height_obj) }, - { MP_ROM_QSTR(MP_QSTR_palette), MP_ROM_PTR(&tilepalettemapper_tilepalettemapper_palette_obj) }, + { MP_ROM_QSTR(MP_QSTR_pixel_shader), MP_ROM_PTR(&tilepalettemapper_tilepalettemapper_pixel_shader_obj) }, + { MP_ROM_QSTR(MP_QSTR_tilegrid), MP_ROM_PTR(&tilepalettemapper_tilepalettemapper_tilegrid_obj) }, }; static MP_DEFINE_CONST_DICT(tilepalettemapper_tilepalettemapper_locals_dict, tilepalettemapper_tilepalettemapper_locals_dict_table); diff --git a/shared-bindings/tilepalettemapper/TilePaletteMapper.h b/shared-bindings/tilepalettemapper/TilePaletteMapper.h index 3fa1ab1e3a5..ef0d9495917 100644 --- a/shared-bindings/tilepalettemapper/TilePaletteMapper.h +++ b/shared-bindings/tilepalettemapper/TilePaletteMapper.h @@ -8,11 +8,12 @@ extern const mp_obj_type_t tilepalettemapper_tilepalettemapper_type; void common_hal_tilepalettemapper_tilepalettemapper_construct(tilepalettemapper_tilepalettemapper_t *self, - mp_obj_t paltte, uint16_t input_color_count, uint16_t bitmap_width_in_tiles, uint16_t bitmap_height_in_tiles); + mp_obj_t paltte, uint16_t input_color_count); uint16_t common_hal_tilepalettemapper_tilepalettemapper_get_width(tilepalettemapper_tilepalettemapper_t *self); uint16_t common_hal_tilepalettemapper_tilepalettemapper_get_height(tilepalettemapper_tilepalettemapper_t *self); mp_obj_t common_hal_tilepalettemapper_tilepalettemapper_get_pixel_shader(tilepalettemapper_tilepalettemapper_t *self); +mp_obj_t common_hal_tilepalettemapper_tilepalettemapper_get_tilegrid(tilepalettemapper_tilepalettemapper_t *self); mp_obj_t common_hal_tilepalettemapper_tilepalettemapper_get_mapping(tilepalettemapper_tilepalettemapper_t *self, uint16_t x, uint16_t y); void common_hal_tilepalettemapper_tilepalettemapper_set_mapping(tilepalettemapper_tilepalettemapper_t *self, uint16_t x, uint16_t y, size_t len, mp_obj_t *items); diff --git a/shared-bindings/time/__init__.c b/shared-bindings/time/__init__.c index 504cd07d901..55c3f4856e3 100644 --- a/shared-bindings/time/__init__.c +++ b/shared-bindings/time/__init__.c @@ -22,12 +22,12 @@ //| //| //| def monotonic() -> float: -//| """Returns an always increasing value of time with an unknown reference +//| """Returns an always increasing value of time, in fractional seconds, with an unknown reference //| point. Only use it to compare against other values from `time.monotonic()` //| during the same code run. //| //| On most boards, `time.monotonic()` converts a 64-bit millisecond tick counter -//| to a float. Floats on most boards are encoded in 30 bits internally, with +//| to seconds, as a float. Floats on most boards are encoded in 30 bits internally, with //| effectively 22 bits of precision. The float returned by `time.monotonic()` will //| accurately represent time to millisecond precision only up to 2**22 milliseconds //| (about 1.165 hours). @@ -83,6 +83,16 @@ static mp_obj_t struct_time_make_new(const mp_obj_type_t *type, size_t n_args, s } //| class struct_time: +//| tm_year: int +//| tm_mon: int +//| tm_mday: int +//| tm_hour: int +//| tm_min: int +//| tm_sec: int +//| tm_wday: int +//| tm_yday: int +//| tm_isdst: int +//| //| def __init__(self, time_tuple: Sequence[int]) -> None: //| """Structure used to capture a date and time. Can be constructed from a `struct_time`, `tuple`, `list`, or `namedtuple` with 9 elements. //| @@ -196,7 +206,7 @@ MP_DEFINE_CONST_FUN_OBJ_0(time_time_obj, time_time); //| def monotonic_ns() -> int: //| """Return the time of the monotonic clock, which cannot go backward, in nanoseconds. //| Not available on boards without long integer support. -//| Only use it to compare against other values from `time.monotonic()` +//| Only use it to compare against other values from `time.monotonic_ns()` //| during a single code run. //| //| :return: the current time @@ -210,11 +220,13 @@ static mp_obj_t time_monotonic_ns(void) { } MP_DEFINE_CONST_FUN_OBJ_0(time_monotonic_ns_obj, time_monotonic_ns); -//| def localtime(secs: int) -> struct_time: +//| def localtime(secs: Optional[int] = None) -> struct_time: //| """Convert a time expressed in seconds since Jan 1, 1970 to a struct_time in //| local time. If secs is not provided or None, the current time as returned //| by time() is used. //| The earliest date for which it can generate a time is Jan 1, 2000. +//| The latest possible date time is 2038-01-19 03:14:07, which is the largest number of seconds that fits in a +//| signed 32-bit integer. Larger values raise `OverflowError`. //| //| :return: the current time //| :rtype: time.struct_time""" diff --git a/shared-bindings/touchio/TouchIn.c b/shared-bindings/touchio/TouchIn.c index e0d04798588..513e52aa90d 100644 --- a/shared-bindings/touchio/TouchIn.c +++ b/shared-bindings/touchio/TouchIn.c @@ -31,24 +31,32 @@ //| print("touched!")""" //| -//| def __init__(self, pin: microcontroller.Pin) -> None: +//| def __init__(self, pin: microcontroller.Pin, pull: Optional[digitalio.Pull] = None) -> None: //| """Use the TouchIn on the given pin. //| -//| :param ~microcontroller.Pin pin: the pin to read from""" +//| :param ~microcontroller.Pin pin: the pin to read from +//| :param Optional[digitalio.Pull] pull: specify external pull resistor type. If None, assume pull-down or chip-specific implementation that does not require a pull. +//| """ //| ... //| static mp_obj_t touchio_touchin_make_new(const mp_obj_type_t *type, - size_t n_args, size_t n_kw, const mp_obj_t *args) { - // check number of arguments - mp_arg_check_num(n_args, n_kw, 1, 1, false); + size_t n_args, size_t n_kw, const mp_obj_t *all_args) { - // 1st argument is the pin - const mcu_pin_obj_t *pin = validate_obj_is_free_pin(args[0], MP_QSTR_pin); + enum { ARG_pin, ARG_pull }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_pin, MP_ARG_OBJ | MP_ARG_REQUIRED }, + { MP_QSTR_pull, MP_ARG_OBJ, {.u_obj = mp_const_none} }, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); - touchio_touchin_obj_t *self = mp_obj_malloc(touchio_touchin_obj_t, &touchio_touchin_type); - common_hal_touchio_touchin_construct(self, pin); + const mcu_pin_obj_t *pin = validate_obj_is_free_pin(args[ARG_pin].u_obj, MP_QSTR_pin); + const digitalio_pull_t pull = validate_pull(args[ARG_pull].u_obj, MP_QSTR_pull); - return (mp_obj_t)self; + touchio_touchin_obj_t *self = mp_obj_malloc_with_finaliser(touchio_touchin_obj_t, &touchio_touchin_type); + common_hal_touchio_touchin_construct(self, pin, pull); + + return MP_OBJ_FROM_PTR(self); } //| def deinit(self) -> None: @@ -153,6 +161,7 @@ static const mp_rom_map_elem_t touchio_touchin_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&touchio_touchin_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&touchio_touchin_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR_value), MP_ROM_PTR(&touchio_touchin_value_obj)}, { MP_ROM_QSTR(MP_QSTR_raw_value), MP_ROM_PTR(&touchio_touchin_raw_value_obj)}, diff --git a/shared-bindings/touchio/TouchIn.h b/shared-bindings/touchio/TouchIn.h index 0ab51039479..d9b34aa74e5 100644 --- a/shared-bindings/touchio/TouchIn.h +++ b/shared-bindings/touchio/TouchIn.h @@ -7,6 +7,7 @@ #pragma once #include "common-hal/microcontroller/Pin.h" +#include "shared-bindings/digitalio/Pull.h" #if CIRCUITPY_TOUCHIO_USE_NATIVE #include "common-hal/touchio/TouchIn.h" @@ -16,7 +17,7 @@ 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_construct(touchio_touchin_obj_t *self, const mcu_pin_obj_t *pin, digitalio_pull_t pull); 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); diff --git a/shared-bindings/touchio/__init__.c b/shared-bindings/touchio/__init__.c index 82e855b81d3..8f9e56d4bdb 100644 --- a/shared-bindings/touchio/__init__.c +++ b/shared-bindings/touchio/__init__.c @@ -28,8 +28,9 @@ //| For more information about working with the `touchio` module in CircuitPython, //| see `this Learn guide page `_. //| -//| **Limitations**: `touchio` is available on Raspberry Pi RP2040 builds, -//| but not on RP2350, due to GPIO hardware limitations. +//| **Limitations**: `touchio` on RP2350 must have a pull-up resistor to 3.3V +//| instead of ground and set the ``pull=Pull.UP`` parameter when constructing +//| a `TouchIn` object, due to GPIO hardware limitations. //| //| Example:: //| @@ -40,7 +41,8 @@ //| print(touch_pin.value) //| //| This example will initialize the the device, and print the -//| :py:data:`~touchio.TouchIn.value`.""" +//| :py:data:`~touchio.TouchIn.value`. +//| """ static const mp_rom_map_elem_t touchio_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_touchio) }, diff --git a/shared-bindings/traceback/__init__.c b/shared-bindings/traceback/__init__.c index ca1e6fe976a..dcdf2914a4f 100644 --- a/shared-bindings/traceback/__init__.c +++ b/shared-bindings/traceback/__init__.c @@ -36,10 +36,18 @@ static void traceback_exception_common(bool is_print_exception, mp_print_t *prin mp_arg_parse_all(n_args, pos_args, kw_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); mp_obj_t value = args[ARG_value].u_obj; + mp_obj_t tb_obj = args[ARG_tb].u_obj; + + // Both or neither of value and tb must be supplied. + if ((value != MP_OBJ_NULL && tb_obj == MP_OBJ_NULL) || + (value == MP_OBJ_NULL && tb_obj != MP_OBJ_NULL)) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("Supply both or neither of %q and %q"), MP_QSTR_value, MP_QSTR_tb); + } + if (value == MP_OBJ_NULL) { value = args[ARG_exc].u_obj; } - mp_obj_t tb_obj = args[ARG_tb].u_obj; + mp_obj_t limit_obj = args[ARG_limit].u_obj; #if MICROPY_CPYTHON_EXCEPTION_CHAIN bool chain = args[ARG_chain].u_bool; @@ -94,7 +102,18 @@ static void traceback_exception_common(bool is_print_exception, mp_print_t *prin exc->traceback = (mp_obj_traceback_t *)&mp_const_empty_traceback_obj; } - shared_module_traceback_print_exception(MP_OBJ_TO_PTR(value), print, limit); + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + shared_module_traceback_print_exception(MP_OBJ_TO_PTR(value), print, limit); + nlr_pop(); + } else { + exc->traceback = trace_backup; + #if MICROPY_CPYTHON_EXCEPTION_CHAIN + exc->context = context_backup; + exc->cause = cause_backup; + #endif + nlr_jump(nlr.ret_val); + } exc->traceback = trace_backup; #if MICROPY_CPYTHON_EXCEPTION_CHAIN exc->context = context_backup; @@ -105,21 +124,21 @@ static void traceback_exception_common(bool is_print_exception, mp_print_t *prin //| def format_exception( //| exc: BaseException | Type[BaseException], //| /, -//| value: Optional[BaseException] = None, +//| value: BaseException, //| tb: Optional[TracebackType] = None, //| limit: Optional[int] = None, //| chain: Optional[bool] = True, //| ) -> List[str]: //| """Format a stack trace and the exception information. //| -//| If the exception value is passed in ``exc``, then this exception value and its -//| associated traceback are used. This is compatible with CPython 3.10 and newer. +//| If the exception value is passed in ``exc``, and ``value`` and ``tb`` are not supplied, +//| then this exception value and its associated traceback are used. +//| This is compatible with CPython 3.10 and newer. //| -//| If the exception value is passed in ``value``, then any value passed in for -//| ``exc`` is ignored. ``value`` is used as the exception value and the -//| traceback in the ``tb`` argument is used. In this case, if ``tb`` is None, -//| no traceback will be shown. This is compatible with CPython 3.5 and -//| newer. +//| If the exception value is passed in ``value``, then both ``value`` and ``tb`` must be supplied. +//| Any value passed in for ``exc`` is *ignored*. ``value`` is used as the exception value and the +//| traceback in the ``tb`` argument is used. In this case, if ``tb`` is `None`, +//| no traceback will be shown. This is compatible with CPython 3.5 and newer. //| //| The arguments have the same meaning as the corresponding arguments //| to print_exception(). The return value is a list of strings, each @@ -128,8 +147,8 @@ static void traceback_exception_common(bool is_print_exception, mp_print_t *prin //| printed as does print_exception(). //| //| :param exc: The exception. Must be an instance of `BaseException`. Unused if value is specified. -//| :param value: If specified, is used in place of ``exc``. -//| :param TracebackType tb: When value is alsp specified, ``tb`` is used in place of the exception's own traceback. If `None`, the traceback will not be printed. +//| :param value: If specified, is used in place of ``exc``, and ``tb`` must also be specified. +//| :param tb: When ``value`` is also specified, ``tb`` is used in place of the exception's own traceback. If `None`, the traceback will not be printed. //| :param int limit: Print up to limit stack trace entries (starting from the caller’s frame) if limit is positive. //| Otherwise, print the last ``abs(limit)`` entries. If limit is omitted or None, all entries are printed. //| :param bool chain: If `True` then chained exceptions will be printed. @@ -150,7 +169,7 @@ static MP_DEFINE_CONST_FUN_OBJ_KW(traceback_format_exception_obj, 0, traceback_f //| def print_exception( //| exc: BaseException | Type[BaseException], //| /, -//| value: Optional[BaseException] = None, +//| value: BaseException, //| tb: Optional[TracebackType] = None, //| limit: Optional[int] = None, //| file: Optional[io.FileIO] = None, @@ -158,18 +177,18 @@ static MP_DEFINE_CONST_FUN_OBJ_KW(traceback_format_exception_obj, 0, traceback_f //| ) -> None: //| """Prints exception information and stack trace entries. //| -//| If the exception value is passed in ``exc``, then this exception value and its -//| associated traceback are used. This is compatible with CPython 3.10 and newer. +//| If the exception value is passed in ``exc``, and ``value`` and ``tb`` are not supplied, +//| then this exception value and its associated traceback are used. +//| This is compatible with CPython 3.10 and newer. //| -//| If the exception value is passed in ``value``, then any value passed in for -//| ``exc`` is ignored. ``value`` is used as the exception value and the -//| traceback in the ``tb`` argument is used. In this case, if ``tb`` is None, -//| no traceback will be shown. This is compatible with CPython 3.5 and -//| newer. +//| If the exception value is passed in ``value``, then both ``value`` and ``tb`` must be supplied. +//| Any value passed in for ``exc`` is *ignored*. ``value`` is used as the exception value and the +//| traceback in the ``tb`` argument is used. In this case, if ``tb`` is `None`, +//| no traceback will be shown. This is compatible with CPython 3.5 and newer. //| //| :param exc: The exception. Must be an instance of `BaseException`. Unused if value is specified. -//| :param value: If specified, is used in place of ``exc``. -//| :param tb: When value is alsp specified, ``tb`` is used in place of the exception's own traceback. If `None`, the traceback will not be printed. +//| :param value: If specified, is used in place of ``exc``, and ``tb`` must also be specified. +//| :param tb: When ``value`` is also specified, ``tb`` is used in place of the exception's own traceback. If `None`, the traceback will not be printed. //| :param int limit: Print up to limit stack trace entries (starting from the caller’s frame) if limit is positive. //| Otherwise, print the last ``abs(limit)`` entries. If limit is omitted or None, all entries are printed. //| :param io.FileIO file: If file is omitted or `None`, the output goes to `sys.stderr`; otherwise it should be an open diff --git a/shared-bindings/usb/core/Device.c b/shared-bindings/usb/core/Device.c index 683115a8421..bc6c6296899 100644 --- a/shared-bindings/usb/core/Device.c +++ b/shared-bindings/usb/core/Device.c @@ -226,23 +226,35 @@ MP_DEFINE_CONST_FUN_OBJ_KW(usb_core_device_write_obj, 2, usb_core_device_write); //| def read( -//| self, endpoint: int, size_or_buffer: array.array, timeout: Optional[int] = None +//| self, +//| endpoint: int, +//| size_or_buffer: array.array, +//| timeout: Optional[int] = None, +//| *, +//| raise_on_timeout: bool = True, //| ) -> int: //| """Read data from the endpoint. //| //| :param int endpoint: the bEndpointAddress you want to communicate with. //| :param array.array size_or_buffer: the array to read data into. PyUSB also allows size but CircuitPython only support array to force deliberate memory use. //| :param int timeout: Time to wait specified in milliseconds. (Different from most CircuitPython!) +//| :param bool raise_on_timeout: when False, an elapsed timeout returns ``0`` +//| instead of raising `usb.core.USBTimeoutError`. Polling an interrupt +//| endpoint every frame (e.g. a HID gamepad in a game loop) treats "no +//| new report yet" as a normal outcome; the exception object each such +//| poll would otherwise allocate is measurable garbage-collector +//| pressure on small heaps. //| :returns: the number of bytes read //| """ //| ... //| static mp_obj_t usb_core_device_read(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - enum { ARG_endpoint, ARG_size_or_buffer, ARG_timeout }; + enum { ARG_endpoint, ARG_size_or_buffer, ARG_timeout, ARG_raise_on_timeout }; static const mp_arg_t allowed_args[] = { { MP_QSTR_endpoint, MP_ARG_REQUIRED | MP_ARG_INT }, { MP_QSTR_size_or_buffer, MP_ARG_REQUIRED | MP_ARG_OBJ }, { MP_QSTR_timeout, MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_raise_on_timeout, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = true} }, }; usb_core_device_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]); check_for_deinit(self); @@ -252,7 +264,7 @@ static mp_obj_t usb_core_device_read(size_t n_args, const mp_obj_t *pos_args, mp mp_buffer_info_t bufinfo; mp_get_buffer_raise(args[ARG_size_or_buffer].u_obj, &bufinfo, MP_BUFFER_WRITE); - return MP_OBJ_NEW_SMALL_INT(common_hal_usb_core_device_read(self, args[ARG_endpoint].u_int, bufinfo.buf, bufinfo.len, args[ARG_timeout].u_int)); + return MP_OBJ_NEW_SMALL_INT(common_hal_usb_core_device_read(self, args[ARG_endpoint].u_int, bufinfo.buf, bufinfo.len, args[ARG_timeout].u_int, args[ARG_raise_on_timeout].u_bool)); } MP_DEFINE_CONST_FUN_OBJ_KW(usb_core_device_read_obj, 2, usb_core_device_read); diff --git a/shared-bindings/usb/core/Device.h b/shared-bindings/usb/core/Device.h index 28c2cfbe198..5814469240a 100644 --- a/shared-bindings/usb/core/Device.h +++ b/shared-bindings/usb/core/Device.h @@ -25,8 +25,9 @@ mp_obj_t common_hal_usb_core_device_get_port_numbers(usb_core_device_obj_t *self mp_int_t common_hal_usb_core_device_get_speed(usb_core_device_obj_t *self); void common_hal_usb_core_device_set_configuration(usb_core_device_obj_t *self, mp_int_t configuration); +bool common_hal_usb_core_device_open_endpoint(usb_core_device_obj_t *self, mp_int_t endpoint); mp_int_t common_hal_usb_core_device_write(usb_core_device_obj_t *self, mp_int_t endpoint, const uint8_t *buffer, mp_int_t len, mp_int_t timeout); -mp_int_t common_hal_usb_core_device_read(usb_core_device_obj_t *self, mp_int_t endpoint, uint8_t *buffer, mp_int_t len, mp_int_t timeout); +mp_int_t common_hal_usb_core_device_read(usb_core_device_obj_t *self, mp_int_t endpoint, uint8_t *buffer, mp_int_t len, mp_int_t timeout, bool raise_on_timeout); mp_int_t common_hal_usb_core_device_ctrl_transfer(usb_core_device_obj_t *self, mp_int_t bmRequestType, mp_int_t bRequest, mp_int_t wValue, mp_int_t wIndex, diff --git a/shared-bindings/usb/core/__init__.c b/shared-bindings/usb/core/__init__.c index 545e182ea99..d272de119ca 100644 --- a/shared-bindings/usb/core/__init__.c +++ b/shared-bindings/usb/core/__init__.c @@ -30,7 +30,7 @@ //| //| MP_DEFINE_USB_CORE_EXCEPTION(USBError, OSError) -NORETURN void mp_raise_usb_core_USBError(mp_rom_error_text_t fmt, ...) { +MP_NORETURN void mp_raise_usb_core_USBError(mp_rom_error_text_t fmt, ...) { mp_obj_t exception; if (fmt == NULL) { exception = mp_obj_new_exception(&mp_type_usb_core_USBError); @@ -50,7 +50,7 @@ NORETURN void mp_raise_usb_core_USBError(mp_rom_error_text_t fmt, ...) { //| //| MP_DEFINE_USB_CORE_EXCEPTION(USBTimeoutError, usb_core_USBError) -NORETURN void mp_raise_usb_core_USBTimeoutError(void) { +MP_NORETURN void mp_raise_usb_core_USBTimeoutError(void) { mp_raise_type(&mp_type_usb_core_USBTimeoutError); } @@ -89,10 +89,11 @@ static mp_obj_t _next_device(usb_core_devices_obj_t *iter) { // We passed the filters. Now make a properly allocated object to // return to the user. - usb_core_device_obj_t *self = mp_obj_malloc(usb_core_device_obj_t, &usb_core_device_type); - + usb_core_device_obj_t *self = mp_obj_malloc_with_finaliser(usb_core_device_obj_t, &usb_core_device_type); common_hal_usb_core_device_construct(self, i); + iter->next_index = i + 1; + return MP_OBJ_FROM_PTR(self); } // Iter is done. @@ -141,7 +142,7 @@ static mp_obj_t usb_core_find(size_t n_args, const mp_obj_t *pos_args, mp_map_t // Copy the temp iter contents to a heap object before we return it. // We could do this up front but GCC falsely detects that we may return // the stack copy. - usb_core_devices_obj_t *iter = m_new_obj(usb_core_devices_obj_t); + usb_core_devices_obj_t *iter = mp_obj_malloc_with_finaliser(usb_core_devices_obj_t, &usb_core_devices_type); memcpy(iter, &temp_iter, sizeof(usb_core_devices_obj_t)); return MP_OBJ_FROM_PTR(iter); } diff --git a/shared-bindings/usb/core/__init__.h b/shared-bindings/usb/core/__init__.h index 0dc08fae532..adb8430a6c3 100644 --- a/shared-bindings/usb/core/__init__.h +++ b/shared-bindings/usb/core/__init__.h @@ -25,8 +25,8 @@ void usb_core_exception_print(const mp_print_t *print, mp_obj_t o_in, mp_print_k extern const mp_obj_type_t mp_type_usb_core_USBError; extern const mp_obj_type_t mp_type_usb_core_USBTimeoutError; -NORETURN void mp_raise_usb_core_USBError(mp_rom_error_text_t fmt, ...); -NORETURN void mp_raise_usb_core_USBTimeoutError(void); +MP_NORETURN void mp_raise_usb_core_USBError(mp_rom_error_text_t fmt, ...); +MP_NORETURN void mp_raise_usb_core_USBTimeoutError(void); // Find is all Python object oriented so we don't need a separate common-hal API // for it. It uses the device common-hal instead. diff --git a/shared-bindings/usb_audio/USBMicrophone.c b/shared-bindings/usb_audio/USBMicrophone.c new file mode 100644 index 00000000000..c66c78942dd --- /dev/null +++ b/shared-bindings/usb_audio/USBMicrophone.c @@ -0,0 +1,178 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#include + +#include "shared/runtime/context_manager_helpers.h" +#include "py/objproperty.h" +#include "py/runtime.h" +#include "shared-bindings/usb_audio/USBMicrophone.h" +#include "shared-bindings/util.h" +#include "shared-module/usb_audio/__init__.h" +#include "shared-module/usb_audio/usb_audio_descriptors.h" + +//| class USBMicrophone: +//| """Streams an audio sample to the host computer as a USB Audio Class microphone. +//| +//| A ``USBMicrophone`` is a *consumer* of an audio sample, exactly like +//| `audioio.AudioOut`, `audiobusio.I2SOut` and `audiopwmio.PWMAudioOut`. The +//| samples it pulls are streamed to the host PC over USB rather than to a pin, +//| so the board appears as a microphone. +//| +//| You cannot create an instance of `usb_audio.USBMicrophone`. +//| +//| There is a single shared instance, available as ``usb_audio.usb_microphone`` +//| once ``usb_audio.enable()`` has configured an input (microphone) stream in +//| ``boot.py``. Until then ``usb_audio.usb_microphone`` is ``None``.""" +//| + + + +static mp_obj_t usb_audio_usbmicrophone_deinit(mp_obj_t self_in) { + usb_audio_usbmicrophone_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_usb_audio_usbmicrophone_deinit(self); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(usb_audio_usbmicrophone_deinit_obj, usb_audio_usbmicrophone_deinit); + +static void check_for_deinit(usb_audio_usbmicrophone_obj_t *self) { + if (common_hal_usb_audio_usbmicrophone_deinited(self)) { + raise_deinited_error(); + } +} + +//| def __enter__(self) -> USBMicrophone: +//| """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.""" +//| ... +//| +// Provided by context manager helper. + +//| def play(self, sample: circuitpython_typing.AudioSample, *, loop: bool = False) -> None: +//| """Streams the sample to the host once when loop=False and continuously when +//| loop=True. Does not block. Use `playing` to block. +//| +//| Sample must be an `audiocore.WaveFile`, `audiocore.RawSample`, `audiomixer.Mixer`, +//| `audiomp3.MP3Decoder` or `synthio.Synthesizer`.""" +//| ... +//| +static mp_obj_t usb_audio_usbmicrophone_obj_play(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_sample, ARG_loop }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_sample, MP_ARG_OBJ | MP_ARG_REQUIRED }, + { MP_QSTR_loop, MP_ARG_BOOL | MP_ARG_KW_ONLY, {.u_bool = false} }, + }; + usb_audio_usbmicrophone_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); + + common_hal_usb_audio_usbmicrophone_play(self, args[ARG_sample].u_obj, args[ARG_loop].u_bool); + + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_KW(usb_audio_usbmicrophone_play_obj, 1, usb_audio_usbmicrophone_obj_play); + +//| def stop(self) -> None: +//| """Stops streaming and resets to the start of the sample.""" +//| ... +//| +static mp_obj_t usb_audio_usbmicrophone_obj_stop(mp_obj_t self_in) { + usb_audio_usbmicrophone_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + common_hal_usb_audio_usbmicrophone_stop(self); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_1(usb_audio_usbmicrophone_stop_obj, usb_audio_usbmicrophone_obj_stop); + +//| playing: bool +//| """True when an audio sample is being streamed even if `paused`. (read-only)""" +//| +static mp_obj_t usb_audio_usbmicrophone_obj_get_playing(mp_obj_t self_in) { + usb_audio_usbmicrophone_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_bool(common_hal_usb_audio_usbmicrophone_get_playing(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(usb_audio_usbmicrophone_get_playing_obj, usb_audio_usbmicrophone_obj_get_playing); + +MP_PROPERTY_GETTER(usb_audio_usbmicrophone_playing_obj, + (mp_obj_t)&usb_audio_usbmicrophone_get_playing_obj); + +//| def pause(self) -> None: +//| """Stops streaming temporarily while remembering the position. Use `resume` to resume.""" +//| ... +//| +static mp_obj_t usb_audio_usbmicrophone_obj_pause(mp_obj_t self_in) { + usb_audio_usbmicrophone_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + + if (!common_hal_usb_audio_usbmicrophone_get_playing(self)) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Not playing")); + } + common_hal_usb_audio_usbmicrophone_pause(self); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_1(usb_audio_usbmicrophone_pause_obj, usb_audio_usbmicrophone_obj_pause); + +//| def resume(self) -> None: +//| """Resumes streaming after :py:func:`pause`.""" +//| ... +//| +static mp_obj_t usb_audio_usbmicrophone_obj_resume(mp_obj_t self_in) { + usb_audio_usbmicrophone_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + + if (common_hal_usb_audio_usbmicrophone_get_paused(self)) { + common_hal_usb_audio_usbmicrophone_resume(self); + } + + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_1(usb_audio_usbmicrophone_resume_obj, usb_audio_usbmicrophone_obj_resume); + +//| paused: bool +//| """True when streaming is paused. (read-only)""" +//| +//| +static mp_obj_t usb_audio_usbmicrophone_obj_get_paused(mp_obj_t self_in) { + usb_audio_usbmicrophone_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_bool(common_hal_usb_audio_usbmicrophone_get_paused(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(usb_audio_usbmicrophone_get_paused_obj, usb_audio_usbmicrophone_obj_get_paused); + +MP_PROPERTY_GETTER(usb_audio_usbmicrophone_paused_obj, + (mp_obj_t)&usb_audio_usbmicrophone_get_paused_obj); + +static const mp_rom_map_elem_t usb_audio_usbmicrophone_locals_dict_table[] = { + // Methods + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&usb_audio_usbmicrophone_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&usb_audio_usbmicrophone_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, + { MP_ROM_QSTR(MP_QSTR_play), MP_ROM_PTR(&usb_audio_usbmicrophone_play_obj) }, + { MP_ROM_QSTR(MP_QSTR_stop), MP_ROM_PTR(&usb_audio_usbmicrophone_stop_obj) }, + { MP_ROM_QSTR(MP_QSTR_pause), MP_ROM_PTR(&usb_audio_usbmicrophone_pause_obj) }, + { MP_ROM_QSTR(MP_QSTR_resume), MP_ROM_PTR(&usb_audio_usbmicrophone_resume_obj) }, + + // Properties + { MP_ROM_QSTR(MP_QSTR_playing), MP_ROM_PTR(&usb_audio_usbmicrophone_playing_obj) }, + { MP_ROM_QSTR(MP_QSTR_paused), MP_ROM_PTR(&usb_audio_usbmicrophone_paused_obj) }, +}; +static MP_DEFINE_CONST_DICT(usb_audio_usbmicrophone_locals_dict, usb_audio_usbmicrophone_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + usb_audio_USBMicrophone_type, + MP_QSTR_USBMicrophone, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + locals_dict, &usb_audio_usbmicrophone_locals_dict + ); diff --git a/shared-bindings/usb_audio/USBMicrophone.h b/shared-bindings/usb_audio/USBMicrophone.h new file mode 100644 index 00000000000..4fe096778bc --- /dev/null +++ b/shared-bindings/usb_audio/USBMicrophone.h @@ -0,0 +1,21 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-module/usb_audio/USBMicrophone.h" + +extern const mp_obj_type_t usb_audio_USBMicrophone_type; + +void common_hal_usb_audio_usbmicrophone_construct(usb_audio_usbmicrophone_obj_t *self); +void common_hal_usb_audio_usbmicrophone_deinit(usb_audio_usbmicrophone_obj_t *self); +bool common_hal_usb_audio_usbmicrophone_deinited(usb_audio_usbmicrophone_obj_t *self); +void common_hal_usb_audio_usbmicrophone_play(usb_audio_usbmicrophone_obj_t *self, mp_obj_t sample, bool loop); +void common_hal_usb_audio_usbmicrophone_stop(usb_audio_usbmicrophone_obj_t *self); +bool common_hal_usb_audio_usbmicrophone_get_playing(usb_audio_usbmicrophone_obj_t *self); +void common_hal_usb_audio_usbmicrophone_pause(usb_audio_usbmicrophone_obj_t *self); +void common_hal_usb_audio_usbmicrophone_resume(usb_audio_usbmicrophone_obj_t *self); +bool common_hal_usb_audio_usbmicrophone_get_paused(usb_audio_usbmicrophone_obj_t *self); diff --git a/shared-bindings/usb_audio/USBSpeaker.c b/shared-bindings/usb_audio/USBSpeaker.c new file mode 100644 index 00000000000..78c5e6099b9 --- /dev/null +++ b/shared-bindings/usb_audio/USBSpeaker.c @@ -0,0 +1,167 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#include + +#include "shared/runtime/context_manager_helpers.h" +#include "py/objproperty.h" +#include "py/runtime.h" +#include "shared-bindings/usb_audio/USBSpeaker.h" +#include "shared-bindings/audiocore/__init__.h" +#include "shared-bindings/util.h" +#include "shared-module/usb_audio/__init__.h" + +//| class USBSpeaker: +//| """Plays audio streamed from the host computer as a USB Audio Class speaker. +//| +//| A ``USBSpeaker`` is a *source* of audio samples, exactly like +//| `audiocore.RawSample` or `audiocore.WaveFile`. The host PC streams audio to +//| the board over USB, and the ``USBSpeaker`` hands that audio to a consumer +//| such as `audiobusio.I2SOut`, `audiopwmio.PWMAudioOut` or `audioio.AudioOut` +//| (optionally through the effect modules), so the board appears as a speaker. +//| +//| You cannot create an instance of `usb_audio.USBSpeaker`. +//| +//| There is a single shared instance, available as ``usb_audio.usb_speaker`` +//| once ``usb_audio.enable()`` has configured an output (speaker) stream in +//| ``boot.py``. Until then ``usb_audio.usb_speaker`` is ``None``. +//| +//| .. code-block:: py +//| +//| # boot.py +//| import usb_audio +//| usb_audio.enable(sample_rate=16000, channel_count=1, +//| microphone=False, speaker=True) +//| +//| .. code-block:: py +//| +//| # code.py +//| import board +//| import usb_audio +//| import audiobusio +//| +//| spk = usb_audio.usb_speaker +//| out = audiobusio.I2SOut(board.I2S_BIT_CLOCK, board.I2S_WORD_SELECT, board.I2S_DATA) +//| out.play(spk, loop=True) +//| while True: +//| pass +//| +//| """ + +static mp_obj_t usb_audio_usbspeaker_deinit(mp_obj_t self_in) { + usb_audio_usbspeaker_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_usb_audio_usbspeaker_deinit(self); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(usb_audio_usbspeaker_deinit_obj, usb_audio_usbspeaker_deinit); + +static void check_for_deinit(usb_audio_usbspeaker_obj_t *self) { + audiosample_check_for_deinit(&self->base); +} + +//| def read(self, destination: circuitpython_typing.WriteableBuffer, destination_length: int) -> int: +//| """Copies up to ``destination_length`` of the most recent samples streamed +//| from the host into ``destination``, for analysis such as an audio-reactive +//| effect or VU meter. This does not block: it returns whatever the host has +//| delivered so far, which may be fewer than ``destination_length`` samples +//| (or zero when the host is not streaming). +//| +//| ``destination`` must be an ``array.array`` of 16-bit signed samples +//| (typecode ``"h"``), matching the negotiated speaker format. +//| +//| Reading consumes the samples, so a ``USBSpeaker`` being read this way +//| should not also be passed to an output backend's ``play()`` at the same +//| time. +//| +//| :return: The number of samples copied into ``destination``.""" +//| ... +//| +static mp_obj_t usb_audio_usbspeaker_obj_read(mp_obj_t self_in, mp_obj_t destination, mp_obj_t destination_length) { + usb_audio_usbspeaker_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + uint32_t length = mp_arg_validate_type_int(destination_length, MP_QSTR_length); + + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(destination, &bufinfo, MP_BUFFER_WRITE); + // The negotiated speaker format is 16-bit signed PCM, so require a matching + // 'h' array. This keeps the copy a straight memcpy with no conversion. + if (bufinfo.typecode != 'h') { + mp_raise_TypeError(MP_ERROR_TEXT("destination must be an array of type 'h'")); + } + size_t capacity = bufinfo.len / sizeof(int16_t); + if (capacity < length) { + length = capacity; + } + + uint32_t length_read = common_hal_usb_audio_usbspeaker_read(self, bufinfo.buf, length); + return MP_OBJ_NEW_SMALL_INT(length_read); +} +static MP_DEFINE_CONST_FUN_OBJ_3(usb_audio_usbspeaker_read_obj, usb_audio_usbspeaker_obj_read); + +//| def __enter__(self) -> USBSpeaker: +//| """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.""" +//| ... +//| +// Provided by context manager helper. + +//| connected: bool +//| """True while the host is streaming audio to this speaker. (read-only)""" +//| +//| +static mp_obj_t usb_audio_usbspeaker_obj_get_connected(mp_obj_t self_in) { + usb_audio_usbspeaker_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_bool(common_hal_usb_audio_usbspeaker_get_connected(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(usb_audio_usbspeaker_get_connected_obj, usb_audio_usbspeaker_obj_get_connected); + +MP_PROPERTY_GETTER(usb_audio_usbspeaker_connected_obj, + (mp_obj_t)&usb_audio_usbspeaker_get_connected_obj); + +//| sample_rate: int +//| """The sample rate negotiated with the host in ``boot.py``. (read-only)""" +//| +//| bits_per_sample: int +//| """The bit depth negotiated with the host in ``boot.py``. (read-only)""" +//| +//| channel_count: int +//| """The number of channels negotiated with the host in ``boot.py``. (read-only)""" +//| +//| +static const mp_rom_map_elem_t usb_audio_usbspeaker_locals_dict_table[] = { + // Methods + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&usb_audio_usbspeaker_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&usb_audio_usbspeaker_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR_read), MP_ROM_PTR(&usb_audio_usbspeaker_read_obj) }, + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, + + // Properties + { MP_ROM_QSTR(MP_QSTR_connected), MP_ROM_PTR(&usb_audio_usbspeaker_connected_obj) }, + AUDIOSAMPLE_FIELDS, +}; +static MP_DEFINE_CONST_DICT(usb_audio_usbspeaker_locals_dict, usb_audio_usbspeaker_locals_dict_table); + +static const audiosample_p_t usb_audio_usbspeaker_proto = { + MP_PROTO_IMPLEMENT(MP_QSTR_protocol_audiosample) + .reset_buffer = (audiosample_reset_buffer_fun)usb_audio_usbspeaker_reset_buffer, + .get_buffer = (audiosample_get_buffer_fun)usb_audio_usbspeaker_get_buffer, +}; + +MP_DEFINE_CONST_OBJ_TYPE( + usb_audio_USBSpeaker_type, + MP_QSTR_USBSpeaker, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + locals_dict, &usb_audio_usbspeaker_locals_dict, + protocol, &usb_audio_usbspeaker_proto + ); diff --git a/shared-bindings/usb_audio/USBSpeaker.h b/shared-bindings/usb_audio/USBSpeaker.h new file mode 100644 index 00000000000..30d2b0862a3 --- /dev/null +++ b/shared-bindings/usb_audio/USBSpeaker.h @@ -0,0 +1,17 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-module/usb_audio/USBSpeaker.h" + +extern const mp_obj_type_t usb_audio_USBSpeaker_type; + +void common_hal_usb_audio_usbspeaker_construct(usb_audio_usbspeaker_obj_t *self); +void common_hal_usb_audio_usbspeaker_deinit(usb_audio_usbspeaker_obj_t *self); +bool common_hal_usb_audio_usbspeaker_deinited(usb_audio_usbspeaker_obj_t *self); +bool common_hal_usb_audio_usbspeaker_get_connected(usb_audio_usbspeaker_obj_t *self); +uint32_t common_hal_usb_audio_usbspeaker_read(usb_audio_usbspeaker_obj_t *self, void *buffer, uint32_t length); diff --git a/shared-bindings/usb_audio/__init__.c b/shared-bindings/usb_audio/__init__.c new file mode 100644 index 00000000000..31d3ab549fd --- /dev/null +++ b/shared-bindings/usb_audio/__init__.c @@ -0,0 +1,155 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#include "py/obj.h" +#include "py/runtime.h" + +#include "shared-bindings/usb_audio/__init__.h" +#include "shared-bindings/usb_audio/USBMicrophone.h" +#include "shared-bindings/usb_audio/USBSpeaker.h" +#include "shared-module/usb_audio/__init__.h" +#include "shared-module/usb_audio/usb_audio_descriptors.h" + +//| """Stream audio to a host computer via USB +//| +//| This makes your CircuitPython device identify to the host computer as a USB +//| Audio Class (UAC2) microphone: the board is the audio *source* and streams +//| samples to the host over a USB isochronous IN endpoint. +//| +//| This mode requires 2 IN endpoints and 2 interfaces. +//| Generally, microcontrollers have a limit on the number of endpoints. If you exceed the number +//| of endpoints, CircuitPython will automatically enter Safe Mode. Even in this case, you may be +//| able to enable USB audio by also disabling other USB functions, such as +//| `usb_hid` or `usb_midi`. +//| +//| To enable this mode, you must configure the audio format in ``boot.py`` and then +//| use the `usb_microphone` singleton instance in ``code.py``. +//| +//| .. code-block:: py +//| +//| # boot.py +//| import usb_audio +//| usb_audio.enable(sample_rate=16000) +//| +//| .. code-block:: py +//| +//| # code.py +//| import time +//| import usb_audio +//| import synthio +//| +//| # usb_audio.usb_microphone is a singleton instance (created by enable() above), +//| # not a class you construct. It is a consumer of an audio sample, just like +//| # audioio.AudioOut: the samples it pulls are streamed to the host PC instead +//| # of to a pin. +//| mic = usb_audio.usb_microphone +//| synth = synthio.Synthesizer(sample_rate=16000, channel_count=1) +//| mic.play(synth, loop=True) +//| +//| c_major_scale = [60, 62, 64, 65, 67, 69, 71, 72] +//| try: +//| while True: +//| for note in c_major_scale: +//| synth.press(note) +//| time.sleep(0.1) +//| synth.release(note) +//| time.sleep(0.05) +//| except KeyboardInterrupt: +//| pass +//| mic.stop() +//| +//| The ``sample_rate`` and ``channel_count`` of the sample played must match the values passed to `enable`, +//| and the sample must be 16-bit signed; otherwise ``play`` raises a ``ValueError``. +//| +//| This interface is experimental and may change without notice even in stable +//| versions of CircuitPython.""" +//| +//| + +//| usb_microphone: Optional[USBMicrophone] +//| """The shared `USBMicrophone` singleton instance, or ``None`` until +//| ``usb_audio.enable()`` has configured an input (microphone) stream in ``boot.py``. +//| `USBMicrophone` is exposed only as a type; you do not construct it.""" +//| +//| usb_speaker: Optional[USBSpeaker] +//| """The shared `USBSpeaker` singleton instance, or ``None`` until +//| ``usb_audio.enable()`` has configured an output (speaker) stream in ``boot.py``. +//| `USBSpeaker` is exposed only as a type; you do not construct it.""" +//| + +//| def enable( +//| sample_rate: int = 16000, +//| channel_count: int = 1, +//| microphone: bool = True, +//| speaker: bool = False, +//| ) -> None: +//| """Enable the USB audio interface with the given PCM format. +//| +//| This function may only be used from ``boot.py``. +//| +//| :param int sample_rate: Samples per second of the streamed audio. +//| :param int channel_count: Number of channels. Either mono (1) or stereo (2) is supported. +//| :param bool microphone: Present a microphone (audio flows board -> host). Enabled by default. +//| :param bool speaker: Present a speaker (audio flows host -> board). +//| +//| Enabling both ``microphone`` and ``speaker`` presents a combined headset. At +//| least one of the two must be enabled.""" +//| +//| +static mp_obj_t usb_audio_enable(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { ARG_sample_rate, ARG_channel_count, ARG_microphone, ARG_speaker }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_sample_rate, MP_ARG_INT, { .u_int = 16000 } }, + { MP_QSTR_channel_count, MP_ARG_INT, { .u_int = 1 } }, + { MP_QSTR_microphone, MP_ARG_BOOL, { .u_bool = true } }, + { MP_QSTR_speaker, 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); + + mp_int_t sample_rate = mp_arg_validate_int_range(args[ARG_sample_rate].u_int, 1, USB_AUDIO_MAX_SAMPLE_RATE, MP_QSTR_sample_rate); + mp_int_t channel_count = mp_arg_validate_int_range(args[ARG_channel_count].u_int, 1, USB_AUDIO_N_CHANNELS, MP_QSTR_channel_count); + bool microphone = args[ARG_microphone].u_bool; + bool speaker = args[ARG_speaker].u_bool; + + if (!microphone && !speaker) { + mp_raise_ValueError(MP_ERROR_TEXT("At least one of microphone and speaker must be enabled")); + } + + if (!shared_module_usb_audio_enable(sample_rate, channel_count, microphone, speaker)) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Cannot change USB devices now")); + } + + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_KW(usb_audio_enable_obj, 0, usb_audio_enable); + +mp_map_elem_t usb_audio_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_usb_audio) }, + // USBMicrophone and USBSpeaker are the classes, exposed only for typing and + // isinstance() checks; you do not construct them. The usable objects are the + // pre-made singleton instances installed at the usb_microphone / usb_speaker + // attributes below. + { MP_ROM_QSTR(MP_QSTR_USBMicrophone), MP_OBJ_FROM_PTR(&usb_audio_USBMicrophone_type) }, + { MP_ROM_QSTR(MP_QSTR_USBSpeaker), MP_OBJ_FROM_PTR(&usb_audio_USBSpeaker_type) }, + // usb_microphone and usb_speaker are the singleton instances, like + // usb_midi.ports. usb_audio_setup_singletons() replaces these None + // placeholders with the real instances at the start of each VM when the + // matching direction was enabled in boot.py. + { MP_ROM_QSTR(MP_QSTR_usb_microphone), MP_ROM_NONE }, + { MP_ROM_QSTR(MP_QSTR_usb_speaker), MP_ROM_NONE }, + { MP_ROM_QSTR(MP_QSTR_enable), MP_OBJ_FROM_PTR(&usb_audio_enable_obj) }, +}; + +// This isn't const so the singleton instances can be installed dynamically. +MP_DEFINE_MUTABLE_DICT(usb_audio_module_globals, usb_audio_module_globals_table); + +const mp_obj_module_t usb_audio_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&usb_audio_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_usb_audio, usb_audio_module); diff --git a/shared-bindings/usb_audio/__init__.h b/shared-bindings/usb_audio/__init__.h new file mode 100644 index 00000000000..f9ad0eeeb78 --- /dev/null +++ b/shared-bindings/usb_audio/__init__.h @@ -0,0 +1,15 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +#include "shared-module/usb_audio/__init__.h" + +// The module globals dict is mutable so the USBMicrophone and USBSpeaker +// singleton instances can be installed at runtime (see usb_audio_setup_singletons). +extern mp_obj_dict_t usb_audio_module_globals; diff --git a/shared-bindings/usb_cdc/Serial.c b/shared-bindings/usb_cdc/Serial.c index 4d6851351af..9bbc2b78f35 100644 --- a/shared-bindings/usb_cdc/Serial.c +++ b/shared-bindings/usb_cdc/Serial.c @@ -100,7 +100,7 @@ static mp_uint_t usb_cdc_serial_write_stream(mp_obj_t self_in, const void *buf_i 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) { +static mp_uint_t usb_cdc_serial_ioctl_stream(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) { usb_cdc_serial_obj_t *self = MP_OBJ_TO_PTR(self_in); mp_uint_t ret = 0; switch (request) { @@ -194,7 +194,7 @@ MP_DEFINE_CONST_FUN_OBJ_1(usb_cdc_serial_reset_output_buffer_obj, usb_cdc_serial 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); + return (timeout < 0.0f) ? mp_const_none : mp_obj_new_float(timeout); } MP_DEFINE_CONST_FUN_OBJ_1(usb_cdc_serial_get_timeout_obj, usb_cdc_serial_get_timeout); @@ -219,7 +219,7 @@ MP_PROPERTY_GETSET(usb_cdc_serial_timeout_obj, 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); + return (write_timeout < 0.0f) ? mp_const_none : mp_obj_new_float(write_timeout); } MP_DEFINE_CONST_FUN_OBJ_1(usb_cdc_serial_get_write_timeout_obj, usb_cdc_serial_get_write_timeout); diff --git a/shared-bindings/usb_cdc/Serial.h b/shared-bindings/usb_cdc/Serial.h index 30249cef389..091f7514a4f 100644 --- a/shared-bindings/usb_cdc/Serial.h +++ b/shared-bindings/usb_cdc/Serial.h @@ -6,7 +6,11 @@ #pragma once +#if defined(__ZEPHYR__) && __ZEPHYR__ == 1 +#include "common-hal/usb_cdc/Serial.h" +#else #include "shared-module/usb_cdc/Serial.h" +#endif extern const mp_obj_type_t usb_cdc_serial_type; diff --git a/shared-bindings/usb_cdc/__init__.c b/shared-bindings/usb_cdc/__init__.c index 65d343b0351..b6ea1f354b7 100644 --- a/shared-bindings/usb_cdc/__init__.c +++ b/shared-bindings/usb_cdc/__init__.c @@ -89,6 +89,89 @@ static mp_obj_t usb_cdc_enable(size_t n_args, const mp_obj_t *pos_args, mp_map_t } MP_DEFINE_CONST_FUN_OBJ_KW(usb_cdc_enable_obj, 0, usb_cdc_enable); +#if CIRCUITPY_FULL_BUILD +char *custom_usb_cdc_console_control_interface_name = NULL; +char *custom_usb_cdc_console_data_interface_name = NULL; +char *custom_usb_cdc_data_control_interface_name = NULL; +char *custom_usb_cdc_data_data_interface_name = NULL; + +static void set_name(mp_obj_t name_obj, qstr arg_name_qstr, char **custom_name_p) { + if (name_obj != mp_const_none) { + mp_buffer_info_t name; + mp_get_buffer_raise(name_obj, &name, MP_BUFFER_READ); + mp_arg_validate_length_range(name.len, 1, 126, arg_name_qstr); + + if (*custom_name_p == NULL) { + *custom_name_p = port_malloc(sizeof(char) * 128, false); + } + + memcpy(*custom_name_p, name.buf, name.len); + (*custom_name_p)[name.len] = 0; + } +} + +//| def set_names( +//| *, +//| console_control_interface_name: Optional[str] = None, +//| console_data_interface_name: Optional[str] = None, +//| data_control_interface_name: Optional[str] = None, +//| data_data_interface_name: Optional[str] = None, +//| ) -> None: +//| """Override the CDC interface names in the USB Interface Descriptors. +//| +//| Each CDC serial device has a control interface and a data interface. +//| +//| :param Optional[str] console_control_interface_name: an ASCII string (or buffer) of at most 126 characters for the console control interface, or ``None`` to use the default name. +//| :param Optional[str] console_data_interface_name: an ASCII string (or buffer) of at most 126 characters for the console data interface, or ``None`` to use the default name. +//| :param Optional[str] data_control_interface_name: an ASCII string (or buffer) of at most 126 characters for the data-port control interface, or ``None`` to use the default name. +//| :param Optional[str] data_data_interface_name: an ASCII string (or buffer) of at most 126 characters for the data-port data interface, or ``None`` to use the default name. +//| +//| This method must be called in ``boot.py`` to have any effect. +//| +//| Not available on boards without native USB support or on reduced builds. +//| """ +//| ... +//| +//| +static mp_obj_t usb_cdc_set_names(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + enum { + ARG_console_control_interface_name, + ARG_console_data_interface_name, + ARG_data_control_interface_name, + ARG_data_data_interface_name + }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_console_control_interface_name, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = mp_const_none} }, + { MP_QSTR_console_data_interface_name, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = mp_const_none} }, + { MP_QSTR_data_control_interface_name, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_obj = mp_const_none} }, + { MP_QSTR_data_data_interface_name, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_rom_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, (mp_arg_val_t *)&args); + + set_name( + args[ARG_console_control_interface_name].u_obj, + MP_QSTR_console_control_interface_name, + &custom_usb_cdc_console_control_interface_name); + set_name( + args[ARG_console_data_interface_name].u_obj, + MP_QSTR_console_data_interface_name, + &custom_usb_cdc_console_data_interface_name); + set_name( + args[ARG_data_control_interface_name].u_obj, + MP_QSTR_data_control_interface_name, + &custom_usb_cdc_data_control_interface_name); + set_name( + args[ARG_data_data_interface_name].u_obj, + MP_QSTR_data_data_interface_name, + &custom_usb_cdc_data_data_interface_name); + + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_KW(usb_cdc_set_names_obj, 0, usb_cdc_set_names); + +#endif + // The usb_cdc module dict is mutable so that .console and .data may // be set to a Serial or to None depending on whether they are enabled or not. static mp_map_elem_t usb_cdc_module_globals_table[] = { @@ -98,6 +181,9 @@ static mp_map_elem_t usb_cdc_module_globals_table[] = { { MP_ROM_QSTR(MP_QSTR_data), mp_const_none }, { MP_ROM_QSTR(MP_QSTR_disable), MP_OBJ_FROM_PTR(&usb_cdc_disable_obj) }, { MP_ROM_QSTR(MP_QSTR_enable), MP_OBJ_FROM_PTR(&usb_cdc_enable_obj) }, + #if CIRCUITPY_FULL_BUILD + { MP_ROM_QSTR(MP_QSTR_set_names), MP_OBJ_FROM_PTR(&usb_cdc_set_names_obj) }, + #endif }; static MP_DEFINE_MUTABLE_DICT(usb_cdc_module_globals, usb_cdc_module_globals_table); diff --git a/shared-bindings/usb_cdc/__init__.h b/shared-bindings/usb_cdc/__init__.h index 34099f7e8fd..d2665631c0c 100644 --- a/shared-bindings/usb_cdc/__init__.h +++ b/shared-bindings/usb_cdc/__init__.h @@ -6,7 +6,18 @@ #pragma once +#if defined(__ZEPHYR__) && __ZEPHYR__ == 1 +#include "common-hal/usb_cdc/__init__.h" +#else #include "shared-module/usb_cdc/__init__.h" +#endif + +#if CIRCUITPY_FULL_BUILD +extern char *custom_usb_cdc_console_control_interface_name; +extern char *custom_usb_cdc_console_data_interface_name; +extern char *custom_usb_cdc_data_control_interface_name; +extern char *custom_usb_cdc_data_data_interface_name; +#endif // Set the module dict entries. void usb_cdc_set_console(mp_obj_t serial_obj); diff --git a/shared-bindings/usb_hid/Device.c b/shared-bindings/usb_hid/Device.c index 7c9c354e4de..aa8af56a185 100644 --- a/shared-bindings/usb_hid/Device.c +++ b/shared-bindings/usb_hid/Device.c @@ -75,7 +75,6 @@ //| static mp_obj_t usb_hid_device_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { - usb_hid_device_obj_t *self = mp_obj_malloc(usb_hid_device_obj_t, &usb_hid_device_type); enum { ARG_report_descriptor, ARG_usage_page, ARG_usage, ARG_report_ids, ARG_in_report_lengths, ARG_out_report_lengths }; static const mp_arg_t allowed_args[] = { { MP_QSTR_report_descriptor, MP_ARG_KW_ONLY | MP_ARG_REQUIRED | MP_ARG_OBJ }, @@ -98,7 +97,7 @@ static mp_obj_t usb_hid_device_make_new(const mp_obj_type_t *type, size_t n_args const uint16_t usage_page = usage_page_arg; const mp_int_t usage_arg = args[ARG_usage].u_int; - mp_arg_validate_int_range(usage_arg, 1, 0xFFFF, MP_QSTR_usage); + mp_arg_validate_int_range(usage_arg, 0, 0xFFFF, MP_QSTR_usage); const uint16_t usage = usage_arg; mp_obj_t report_ids = args[ARG_report_ids].u_obj; @@ -141,9 +140,10 @@ static mp_obj_t usb_hid_device_make_new(const mp_obj_type_t *type, size_t n_args mp_raise_ValueError_varg(MP_ERROR_TEXT("%q length must be %d"), MP_QSTR_report_id_space_0, 1); } + usb_hid_device_obj_t *self = mp_obj_malloc(usb_hid_device_obj_t, &usb_hid_device_type); common_hal_usb_hid_device_construct( self, descriptor, usage_page, usage, report_ids_count, report_ids_array, in_report_lengths_array, out_report_lengths_array); - return (mp_obj_t)self; + return MP_OBJ_FROM_PTR(self); } @@ -156,6 +156,10 @@ static mp_obj_t usb_hid_device_make_new(const mp_obj_type_t *type, size_t n_args //| The ``report`` itself will be discarded, to prevent unwanted extraneous characters, //| mouse clicks, etc. //| +//| If the host has put the interface in boot protocol, the boot device sends its report +//| without a report ID, and `send_report()` on any other device discards the report, +//| because the host reads only the boot device. +//| //| Note: Host operating systems allow enabling and disabling specific devices //| and kinds of devices to do wakeup. //| The defaults are different for different operating systems. diff --git a/shared-bindings/usb_hid/__init__.c b/shared-bindings/usb_hid/__init__.c index 47f7f03c493..1bedaf3edf0 100644 --- a/shared-bindings/usb_hid/__init__.c +++ b/shared-bindings/usb_hid/__init__.c @@ -25,6 +25,10 @@ //| the `devices` tuple is **replaced** when ``code.py`` starts with a single-element tuple //| containing a `Device` that describes the boot device chosen (keyboard or mouse). //| The request for a boot device overrides any other HID devices. +//| +//| If the host requests a boot device after ``code.py`` has started, `devices` is not replaced. +//| The boot device then sends reports in the boot format, with no report ID, and +//| `Device.send_report()` on any other device does nothing, because the host ignores it. //| """ //| //| diff --git a/shared-bindings/usb_host/Port.c b/shared-bindings/usb_host/Port.c index 41e8513a1e8..2c61e641a05 100644 --- a/shared-bindings/usb_host/Port.c +++ b/shared-bindings/usb_host/Port.c @@ -42,7 +42,7 @@ static mp_obj_t usb_host_port_make_new(const mp_obj_type_t *type, usb_host_port_obj_t *self = common_hal_usb_host_port_construct(dp, dm); - return (mp_obj_t)self; + return MP_OBJ_FROM_PTR(self); } static const mp_rom_map_elem_t usb_host_port_locals_dict_table[] = { diff --git a/shared-bindings/usb_host/Port.h b/shared-bindings/usb_host/Port.h index 803eae8b59f..3958bf3514b 100644 --- a/shared-bindings/usb_host/Port.h +++ b/shared-bindings/usb_host/Port.h @@ -19,3 +19,13 @@ extern const mp_obj_type_t usb_host_port_type; // method to check the internals of the global object against the given arguments // to determine whether to return the singleton or raise an exception. usb_host_port_obj_t *common_hal_usb_host_port_construct(const mcu_pin_obj_t *dp, const mcu_pin_obj_t *dm); + +// Gives the host controller a buffer of at least size bytes for isochronous IN +// packets, which it then keeps between transfers and hands over as +// length-prefixed records, as usb_host_audio needs. Until it is released it +// replaces the buffer set in settings.toml. False when another isochronous +// stream holds the buffer; raises when out of memory. +bool common_hal_usb_host_port_claim_iso_buffer(size_t size); +// Frees the claimed buffer and puts back the one from settings.toml. Call after +// the stream ended. Never raises. +void common_hal_usb_host_port_release_iso_buffer(void); diff --git a/shared-bindings/usb_host_audio/USBIn.c b/shared-bindings/usb_host_audio/USBIn.c new file mode 100644 index 00000000000..dc4bd14a0e4 --- /dev/null +++ b/shared-bindings/usb_host_audio/USBIn.c @@ -0,0 +1,355 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include + +#include "extmod/vfs_fat.h" +#include "shared/runtime/context_manager_helpers.h" +#include "py/binary.h" +#include "py/objproperty.h" +#include "py/runtime.h" +#include "shared-bindings/audiocore/__init__.h" +#include "shared-bindings/usb/core/Device.h" +#include "shared-bindings/usb_host_audio/USBIn.h" +#include "shared-bindings/util.h" +//| import usb.core +//| +//| +//| class USBIn: +//| """Stream or record the audio of a USB microphone on a USB host port.""" +//| +//| def __init__( +//| self, +//| device: usb.core.Device, +//| endpoint: int, +//| *, +//| sample_rate: int, +//| channel_count: int = 1, +//| bit_depth: int = 16, +//| samples_signed: bool = True, +//| max_packet_size: int = 0, +//| buffer_frames: int = 256, +//| iso_buffer_size: int = 16384, +//| ) -> None: +//| """Receive the PCM audio that a USB Audio Class microphone sends on an +//| isochronous IN endpoint. The object can be played like any other audio +//| sample, which makes the microphone the source of an audio effects +//| chain, and it can `record` to a buffer. +//| +//| The constructor does no control transfers. Before calling it, select +//| the alternate setting of the streaming interface that has ``endpoint`` +//| and set the sample rate; the arguments describe the format chosen +//| that way. Do not create a `USBIn` for an interface that is in +//| alternate setting 0. `deinit` selects alternate setting 0 again, so +//| the microphone stops also when a ``with`` block is left by an +//| exception, or when the program ends. +//| +//| On RP2 boards, whose host port is PIO-USB, the host controller buffers +//| the stream between reads, in a buffer of ``iso_buffer_size`` bytes that +//| `USBIn` allocates and `deinit` frees. On Espressif boards, such as the +//| Metro ESP32-P4, ``iso_buffer_size`` is not used. There the USB host +//| runs in a task of its own, so packets keep arriving while Python is +//| busy, such as during an SD card write or a long garbage collection. +//| +//| Audio waits for `record` or playback in a buffer of +//| ``32 * buffer_frames`` frames on Espressif boards and +//| ``8 * buffer_frames`` frames on others. When that fills up, the newest +//| audio is dropped and `overflow` is set. +//| +//| Only one isochronous IN endpoint is received at a time, so only one +//| `USBIn` can stream, and a USB camera cannot stream video meanwhile. +//| Creating a second one raises ``RuntimeError`` while the first is +//| `streaming`, and deinitializes the first when its stream has ended. +//| +//| The microphone's clock is independent of the clock of the audio +//| output. While playing, the drift between them is taken up by +//| stretching a buffer by one frame now and then, which cannot be heard. +//| Only when playback stalls is audio dropped, which sets `overflow`, or a +//| moment of silence played. About ``3 * buffer_frames`` frames of +//| latency are added. +//| +//| :param ~usb.core.Device device: The microphone. Its configuration must be set. +//| :param int endpoint: The address of the isochronous IN endpoint +//| :param int sample_rate: The sample rate that the microphone was set to, in Hz +//| :param int channel_count: The number of channels in the stream +//| :param int bit_depth: The bits per sample in the stream: 8, 16, 24 or 32. 24 +//| and 32 bit samples are narrowed to 16 bit; see `bits_per_sample`. For +//| samples narrower than their bytes, such as 24 bits in 4 bytes, give the +//| size of the bytes. +//| :param bool samples_signed: Samples are signed (True) or unsigned (False). USB +//| audio is signed, except for 8 bit PCM. +//| :param int max_packet_size: The endpoint's ``wMaxPacketSize`` +//| :param int buffer_frames: The number of frames handed to the audio pipeline at a time +//| :param int iso_buffer_size: The size in bytes of the host controller's buffer for +//| the stream, from 2048 to 65536, rounded up to a power of two. It holds the +//| packets that arrive while background tasks don't run, each with 2 bytes of +//| overhead: 16384 is about half a second of 16 kHz mono audio or 80 ms of 48 kHz +//| stereo. Only used on RP2 boards; ignored on the Metro ESP32-P4 and other +//| boards whose host port is the chip's own USB controller. +//| +//| Example, recording a second from the microphone of a Logitech C270 +//| webcam. It streams 16 bit mono on interface 3, alternate setting 1, +//| endpoint 0x86. For another microphone, read these from its +//| configuration descriptor:: +//| +//| import array +//| import usb.core +//| import usb_host_audio +//| +//| device = usb.core.find(idVendor=0x046D, idProduct=0x0825) +//| device.set_configuration() +//| # SET_INTERFACE to alternate setting 1 starts the stream, then +//| # SET_CUR of the endpoint's sampling frequency picks 16 kHz. +//| device.ctrl_transfer(0x01, 11, 1, 3, None) +//| device.ctrl_transfer(0x22, 0x01, 0x0100, 0x86, (16000).to_bytes(3, "little")) +//| +//| samples = array.array("h", [0] * 16000) +//| # Leaving the with block stops the stream. +//| with usb_host_audio.USBIn(device, 0x86, sample_rate=16000, max_packet_size=68) as mic: +//| count = mic.record(samples, len(samples)) +//| print("recorded", count, "samples, peak", max(abs(s) for s in samples)) +//| +//| """ +//| ... +//| +static mp_obj_t usb_host_audio_usbin_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_device, ARG_endpoint, ARG_sample_rate, ARG_channel_count, ARG_bit_depth, + ARG_samples_signed, ARG_max_packet_size, ARG_buffer_frames, ARG_iso_buffer_size }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_device, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_endpoint, MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_sample_rate, MP_ARG_KW_ONLY | MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_channel_count, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1} }, + { MP_QSTR_bit_depth, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 16} }, + { MP_QSTR_samples_signed, MP_ARG_KW_ONLY | MP_ARG_BOOL, {.u_bool = true} }, + { MP_QSTR_max_packet_size, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 0} }, + { MP_QSTR_buffer_frames, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 256} }, + { MP_QSTR_iso_buffer_size, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 16384} }, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + usb_core_device_obj_t *device = mp_arg_validate_type(args[ARG_device].u_obj, &usb_core_device_type, MP_QSTR_device); + if (common_hal_usb_core_device_deinited(device)) { + raise_deinited_error(); + } + mp_int_t endpoint = args[ARG_endpoint].u_int; + if ((endpoint & 0x80) == 0 || (endpoint & 0x7f) == 0 || endpoint > 0x8f) { + mp_arg_error_invalid(MP_QSTR_endpoint); + } + mp_int_t sample_rate = mp_arg_validate_int_min(args[ARG_sample_rate].u_int, 1, MP_QSTR_sample_rate); + mp_int_t channel_count = mp_arg_validate_int_range(args[ARG_channel_count].u_int, 1, 2, MP_QSTR_channel_count); + mp_int_t bit_depth = args[ARG_bit_depth].u_int; + if (bit_depth != 8 && bit_depth != 16 && bit_depth != 24 && bit_depth != 32) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("%q must be 8, 16, 24, or 32"), MP_QSTR_bit_depth); + } + mp_int_t max_packet_size = mp_arg_validate_int_range(args[ARG_max_packet_size].u_int, 0, 1024, MP_QSTR_max_packet_size); + mp_int_t buffer_frames = mp_arg_validate_int_range(args[ARG_buffer_frames].u_int, 32, 4096, MP_QSTR_buffer_frames); + mp_int_t iso_buffer_size = mp_arg_validate_int_range(args[ARG_iso_buffer_size].u_int, 2048, 65536, MP_QSTR_iso_buffer_size); + + usb_host_audio_usbin_obj_t *self = mp_obj_malloc_with_finaliser(usb_host_audio_usbin_obj_t, &usb_host_audio_usbin_type); + common_hal_usb_host_audio_usbin_construct(self, device, endpoint, sample_rate, channel_count, + bit_depth, args[ARG_samples_signed].u_bool, max_packet_size, buffer_frames, iso_buffer_size); + + return MP_OBJ_FROM_PTR(self); +} + +//| def deinit(self) -> None: +//| """Stops the stream and releases the buffers. While the stream is still +//| `streaming`, this selects alternate setting 0 of the endpoint's +//| interface first, which stops the microphone sending.""" +//| ... +//| +static mp_obj_t usb_host_audio_usbin_deinit(mp_obj_t self_in) { + usb_host_audio_usbin_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_usb_host_audio_usbin_deinit(self); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(usb_host_audio_usbin_deinit_obj, usb_host_audio_usbin_deinit); + +static void check_for_deinit(usb_host_audio_usbin_obj_t *self) { + if (common_hal_usb_host_audio_usbin_deinited(self)) { + raise_deinited_error(); + } +} + +//| def __enter__(self) -> USBIn: +//| """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.""" +//| ... +//| +// Provided by context manager helper. + +//| def record(self, destination: WriteableBuffer, destination_length: int) -> int: +//| """Records destination_length samples to destination. This is blocking. +//| A stereo frame is two samples, left then right. +//| +//| ``destination`` is an ``array.array`` of typecode ``'h'`` for +//| `bits_per_sample` 16 (``'H'`` when unsigned), and of typecode ``'b'`` +//| (``'B'`` when unsigned) or a ``bytearray`` for 8. +//| +//| Audio is received between calls too, so that consecutive recordings +//| join up. When more arrived than is buffered, the newest of it was +//| dropped: the recording has the buffered audio, then a gap. +//| +//| :return: The number of samples recorded. If this is less than +//| ``destination_length``, the microphone stopped sending audio.""" +//| ... +//| +static mp_obj_t usb_host_audio_usbin_obj_record(mp_obj_t self_obj, mp_obj_t destination, mp_obj_t destination_length) { + usb_host_audio_usbin_obj_t *self = MP_OBJ_TO_PTR(self_obj); + check_for_deinit(self); + uint32_t length = mp_arg_validate_type_int(destination_length, MP_QSTR_length); + mp_arg_validate_length_min(length, 0, MP_QSTR_length); + + mp_buffer_info_t bufinfo; + if (mp_obj_is_type(destination, &mp_type_fileio)) { + mp_raise_NotImplementedError(MP_ERROR_TEXT("Cannot record to a file")); + } + mp_get_buffer_raise(destination, &bufinfo, MP_BUFFER_WRITE); + if (bufinfo.len / mp_binary_get_size('@', bufinfo.typecode, NULL) < length) { + mp_raise_ValueError(MP_ERROR_TEXT("Destination capacity is smaller than destination_length.")); + } + char error_type = ' '; + if (self->base.bits_per_sample == 16) { + char typecode = self->base.samples_signed ? 'h' : 'H'; + if (bufinfo.typecode != typecode) { + error_type = typecode; + } + } else { + char typecode = self->base.samples_signed ? 'b' : 'B'; + if (bufinfo.typecode != typecode && bufinfo.typecode != BYTEARRAY_TYPECODE) { + error_type = typecode; // NOTE: Not identifying as bytearray + } + } + if (error_type != ' ') { + mp_raise_TypeError_varg( + MP_ERROR_TEXT("invalid destination buffer, must be an array of type: %c"), + error_type + ); + } + uint32_t length_written = + common_hal_usb_host_audio_usbin_record_to_buffer(self, bufinfo.buf, length); + return MP_OBJ_NEW_SMALL_INT(length_written); +} +MP_DEFINE_CONST_FUN_OBJ_3(usb_host_audio_usbin_record_obj, usb_host_audio_usbin_obj_record); + +//| sample_rate: int +//| """The sample rate given to the constructor, in Hz. This is the rate +//| reported to the audio pipeline. The microphone's own clock decides the +//| true rate, which is usually a fraction of a percent off.""" +//| +//| bits_per_sample: int +//| """The number of bits per sample as it is streamed through the audio pipeline +//| and recorded: 8 or 16. (read-only)""" +//| +//| channel_count: int +//| """The number of channels (1 for mono, 2 for stereo). (read-only)""" +//| + +//| bit_depth: int +//| """The number of bits per sample that the microphone sends. (read-only)""" +//| +static mp_obj_t usb_host_audio_usbin_obj_get_bit_depth(mp_obj_t self_in) { + usb_host_audio_usbin_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return MP_OBJ_NEW_SMALL_INT(common_hal_usb_host_audio_usbin_get_bit_depth(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(usb_host_audio_usbin_get_bit_depth_obj, usb_host_audio_usbin_obj_get_bit_depth); + +MP_PROPERTY_GETTER(usb_host_audio_usbin_bit_depth_obj, + (mp_obj_t)&usb_host_audio_usbin_get_bit_depth_obj); + +//| samples_signed: bool +//| """True if the samples are signed PCM, False for unsigned. (read-only)""" +//| +static mp_obj_t usb_host_audio_usbin_obj_get_samples_signed(mp_obj_t self_in) { + usb_host_audio_usbin_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_bool(common_hal_usb_host_audio_usbin_get_samples_signed(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(usb_host_audio_usbin_get_samples_signed_obj, usb_host_audio_usbin_obj_get_samples_signed); + +MP_PROPERTY_GETTER(usb_host_audio_usbin_samples_signed_obj, + (mp_obj_t)&usb_host_audio_usbin_get_samples_signed_obj); + +//| streaming: bool +//| """True while the stream is received. It turns False for good when the +//| microphone stops sending: an alternate setting of the device was +//| selected, its configuration was set again, it was unplugged, or another +//| isochronous stream was started. The object then plays silence and records +//| only what it received before; +//| make a new one after starting the stream again. (read-only) +//| +//| Receiving is not retried, because some devices stop answering control +//| requests when an endpoint of an idle interface is polled.""" +//| +static mp_obj_t usb_host_audio_usbin_obj_get_streaming(mp_obj_t self_in) { + usb_host_audio_usbin_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_bool(common_hal_usb_host_audio_usbin_get_streaming(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(usb_host_audio_usbin_get_streaming_obj, usb_host_audio_usbin_obj_get_streaming); + +MP_PROPERTY_GETTER(usb_host_audio_usbin_streaming_obj, + (mp_obj_t)&usb_host_audio_usbin_get_streaming_obj); + +//| overflow: bool +//| """True if audio was dropped since the last time this was checked: it +//| was not played or recorded fast enough, or the host controller lost +//| packets. (read-only) +//| +//| Reading this clears the flag. Audio that arrives while nothing plays or +//| records also overflows, except that starting playback discards it without +//| setting the flag.""" +//| +//| +static mp_obj_t usb_host_audio_usbin_obj_get_overflow(mp_obj_t self_in) { + usb_host_audio_usbin_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + return mp_obj_new_bool(common_hal_usb_host_audio_usbin_get_overflow(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(usb_host_audio_usbin_get_overflow_obj, usb_host_audio_usbin_obj_get_overflow); + +MP_PROPERTY_GETTER(usb_host_audio_usbin_overflow_obj, + (mp_obj_t)&usb_host_audio_usbin_get_overflow_obj); + +static const mp_rom_map_elem_t usb_host_audio_usbin_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&usb_host_audio_usbin_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&usb_host_audio_usbin_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, + { MP_ROM_QSTR(MP_QSTR_record), MP_ROM_PTR(&usb_host_audio_usbin_record_obj) }, + // sample_rate / bits_per_sample / channel_count come from the audiosample + // protocol's shared property getters. + AUDIOSAMPLE_FIELDS, + { MP_ROM_QSTR(MP_QSTR_bit_depth), MP_ROM_PTR(&usb_host_audio_usbin_bit_depth_obj) }, + { MP_ROM_QSTR(MP_QSTR_samples_signed), MP_ROM_PTR(&usb_host_audio_usbin_samples_signed_obj) }, + { MP_ROM_QSTR(MP_QSTR_streaming), MP_ROM_PTR(&usb_host_audio_usbin_streaming_obj) }, + { MP_ROM_QSTR(MP_QSTR_overflow), MP_ROM_PTR(&usb_host_audio_usbin_overflow_obj) }, +}; +static MP_DEFINE_CONST_DICT(usb_host_audio_usbin_locals_dict, usb_host_audio_usbin_locals_dict_table); + +static const audiosample_p_t usb_host_audio_usbin_proto = { + MP_PROTO_IMPLEMENT(MP_QSTR_protocol_audiosample) + .reset_buffer = (audiosample_reset_buffer_fun)common_hal_usb_host_audio_usbin_reset_buffer, + .get_buffer = (audiosample_get_buffer_fun)common_hal_usb_host_audio_usbin_get_buffer, +}; + +MP_DEFINE_CONST_OBJ_TYPE( + usb_host_audio_usbin_type, + MP_QSTR_USBIn, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, usb_host_audio_usbin_make_new, + locals_dict, &usb_host_audio_usbin_locals_dict, + protocol, &usb_host_audio_usbin_proto + ); diff --git a/shared-bindings/usb_host_audio/USBIn.h b/shared-bindings/usb_host_audio/USBIn.h new file mode 100644 index 00000000000..1477b505d3e --- /dev/null +++ b/shared-bindings/usb_host_audio/USBIn.h @@ -0,0 +1,31 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-module/usb_host_audio/USBIn.h" + +extern const mp_obj_type_t usb_host_audio_usbin_type; + +void common_hal_usb_host_audio_usbin_construct(usb_host_audio_usbin_obj_t *self, + usb_core_device_obj_t *device, uint8_t endpoint, uint32_t sample_rate, + uint8_t channel_count, uint8_t bit_depth, bool samples_signed, + uint16_t max_packet_size, uint32_t buffer_frames, uint32_t iso_buffer_size); +void common_hal_usb_host_audio_usbin_deinit(usb_host_audio_usbin_obj_t *self); +bool common_hal_usb_host_audio_usbin_deinited(usb_host_audio_usbin_obj_t *self); +// length and the return value count samples; a stereo frame is two samples. +uint32_t common_hal_usb_host_audio_usbin_record_to_buffer(usb_host_audio_usbin_obj_t *self, + uint8_t *buffer, uint32_t length); +uint8_t common_hal_usb_host_audio_usbin_get_bit_depth(usb_host_audio_usbin_obj_t *self); +bool common_hal_usb_host_audio_usbin_get_samples_signed(usb_host_audio_usbin_obj_t *self); +bool common_hal_usb_host_audio_usbin_get_streaming(usb_host_audio_usbin_obj_t *self); +bool common_hal_usb_host_audio_usbin_get_overflow(usb_host_audio_usbin_obj_t *self); + +void common_hal_usb_host_audio_usbin_reset_buffer(usb_host_audio_usbin_obj_t *self, + bool single_channel_output, uint8_t channel); +audioio_get_buffer_result_t common_hal_usb_host_audio_usbin_get_buffer( + usb_host_audio_usbin_obj_t *self, bool single_channel_output, uint8_t channel, + uint8_t **buffer, uint32_t *buffer_length); diff --git a/shared-bindings/usb_host_audio/__init__.c b/shared-bindings/usb_host_audio/__init__.c new file mode 100644 index 00000000000..d055a07a301 --- /dev/null +++ b/shared-bindings/usb_host_audio/__init__.c @@ -0,0 +1,40 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include + +#include "py/obj.h" +#include "py/runtime.h" + +#include "shared-bindings/usb_host_audio/__init__.h" +#include "shared-bindings/usb_host_audio/USBIn.h" + +//| """Audio from USB devices connected to a USB host port. +//| +//| The `usb_host_audio` module contains the `USBIn` class, which streams the +//| audio of a USB microphone into the audio pipeline or records it. +//| +//| This module only moves the audio. Finding the microphone, picking one of its +//| formats and starting its stream is done with `usb.core`, for example by the +//| ``adafruit_usb_host_microphone`` library. +//| +//| All classes change hardware state and should be deinitialized when they +//| are no longer needed. To do so, either call :py:meth:`!deinit` or use a +//| context manager.""" + +static const mp_rom_map_elem_t usb_host_audio_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_usb_host_audio) }, + { MP_ROM_QSTR(MP_QSTR_USBIn), MP_ROM_PTR(&usb_host_audio_usbin_type) }, +}; + +static MP_DEFINE_CONST_DICT(usb_host_audio_module_globals, usb_host_audio_module_globals_table); + +const mp_obj_module_t usb_host_audio_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&usb_host_audio_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_usb_host_audio, usb_host_audio_module); diff --git a/shared-bindings/usb_host_audio/__init__.h b/shared-bindings/usb_host_audio/__init__.h new file mode 100644 index 00000000000..779b49ffd8d --- /dev/null +++ b/shared-bindings/usb_host_audio/__init__.h @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once diff --git a/shared-bindings/usb_host_bulk/InStream.c b/shared-bindings/usb_host_bulk/InStream.c new file mode 100644 index 00000000000..803581805c3 --- /dev/null +++ b/shared-bindings/usb_host_bulk/InStream.c @@ -0,0 +1,303 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "py/objproperty.h" +#include "py/runtime.h" +#include "py/stream.h" + +#include "shared/runtime/context_manager_helpers.h" +#include "shared-bindings/usb/core/Device.h" +#include "shared-bindings/usb_host_bulk/InStream.h" +#include "shared-bindings/util.h" + +//| import usb.core +//| +//| +//| class InStream: +//| """Continuously receive from a full-speed bulk IN endpoint in the background. +//| +//| The USB host polls the endpoint every frame, independently of Python, and stores +//| the payload in a ring of ``buffer_size`` bytes in internal SRAM. +//| +//| Reads never block. To wait for data, wrap the stream with ``asyncio.StreamReader`` +//| or poll `in_waiting`. +//| +//| One stream per endpoint can run. They share the bandwidth of +//| their host port. +//| +//| Synchronous example:: +//| +//| import time +//| import usb.core +//| import usb_host_bulk +//| +//| # Replace these with your device's vendor and product IDs. +//| device = usb.core.find(idVendor=0x0BDA, idProduct=0x2838) +//| if device is None: +//| raise RuntimeError("USB device not found") +//| device.set_configuration() +//| # Many devices only start sending after device-specific setup, such as +//| # vendor requests made with device.ctrl_transfer(). Do that here. +//| +//| buf = bytearray(8192) +//| received = 0 +//| report_at = time.monotonic() + 1 +//| with usb_host_bulk.InStream(device, 0x81) as stream: +//| while True: +//| n = stream.readinto(buf) # None while nothing is waiting +//| if n == 0: +//| break # the device stalled or was unplugged +//| if n: +//| received += n # process buf[:n] here +//| if time.monotonic() >= report_at: +//| print("received", received, "bytes, lost packets:", stream.lost_packets) +//| report_at += 1 +//| +//| asyncio example:: +//| +//| import asyncio +//| from asyncio import StreamReader +//| import usb.core +//| import usb_host_bulk +//| +//| # Replace these with your device's vendor and product IDs. +//| device = usb.core.find(idVendor=0x0BDA, idProduct=0x2838) +//| if device is None: +//| raise RuntimeError("USB device not found") +//| device.set_configuration() +//| # Many devices only start sending after device-specific setup, such as +//| # vendor requests made with device.ctrl_transfer(). Do that here. +//| +//| received = 0 +//| +//| async def receive(stream): +//| global received +//| reader = StreamReader(stream) +//| buf = bytearray(8192) +//| while True: +//| n = await reader.readinto(buf) +//| if not n: +//| break # the device stalled or was unplugged +//| received += n # process buf[:n] here +//| +//| async def report(stream): +//| while True: +//| await asyncio.sleep(1) +//| print("received", received, "bytes, lost packets:", stream.lost_packets) +//| +//| async def main(): +//| with usb_host_bulk.InStream(device, 0x81) as stream: +//| reporter = asyncio.create_task(report(stream)) +//| await receive(stream) +//| reporter.cancel() +//| +//| asyncio.run(main()) +//| +//| ``asyncio.StreamReader(stream)`` is a CircuitPython and MicroPython idiom. Import +//| ``StreamReader`` before starting the stream: asyncio loads it on first use, which +//| can take long enough to overflow the ring. Use ``readinto`` rather than +//| ``readexactly`` at high data rates, because ``readexactly`` allocates on every +//| call. +//| """ +//| +//| def __init__( +//| self, device: usb.core.Device, endpoint: int, *, buffer_size: int = 32768 +//| ) -> None: +//| """Open ``endpoint`` on ``device`` and start capturing immediately. +//| +//| :param usb.core.Device device: a configured device (call ``set_configuration()`` first) +//| :param int endpoint: bEndpointAddress of a bulk IN endpoint, 0x81 to 0x8F, with +//| a maximum packet size of 64 bytes or less +//| :param int buffer_size: ring size in bytes, a power of two from 4096 to 65536 +//| """ +//| ... +//| +static mp_obj_t usb_host_bulk_instream_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_device, ARG_endpoint, ARG_buffer_size }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_device, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_endpoint, MP_ARG_REQUIRED | MP_ARG_INT }, + { MP_QSTR_buffer_size, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 32768} }, + }; + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + mp_obj_t device_obj = mp_arg_validate_type(args[ARG_device].u_obj, &usb_core_device_type, MP_QSTR_device); + usb_core_device_obj_t *device = MP_OBJ_TO_PTR(device_obj); + if (common_hal_usb_core_device_deinited(device)) { + raise_deinited_error(); + } + // IN endpoint addresses 1-15; endpoint 0 is control only. + mp_int_t endpoint = mp_arg_validate_int_range(args[ARG_endpoint].u_int, 0x81, 0x8F, MP_QSTR_endpoint); + mp_int_t buffer_size = mp_arg_validate_int_range(args[ARG_buffer_size].u_int, 4096, 65536, MP_QSTR_buffer_size); + if ((buffer_size & (buffer_size - 1)) != 0) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("%q must be power of 2"), MP_QSTR_buffer_size); + } + + usb_host_bulk_instream_obj_t *self = mp_obj_malloc_with_finaliser(usb_host_bulk_instream_obj_t, &usb_host_bulk_instream_type); + common_hal_usb_host_bulk_instream_construct(self, device, endpoint, buffer_size); + return MP_OBJ_FROM_PTR(self); +} + +static void check_for_deinit(usb_host_bulk_instream_obj_t *self) { + if (common_hal_usb_host_bulk_instream_deinited(self)) { + raise_deinited_error(); + } +} + +//| def readinto(self, buf: WriteableBuffer, nbytes: Optional[int] = None) -> Optional[int]: +//| """Copy waiting bytes into ``buf``, at most ``nbytes`` of them if given. +//| +//| Capture ends when the stream is deinited, which drops any bytes not yet read. +//| It also ends on its own when the device stalls the endpoint, is unplugged, or is +//| reconfigured. Bytes captured before that can still be read. +//| +//| :return: the number of bytes copied, ``None`` if nothing is waiting yet, or 0 +//| once capture has ended and nothing is left to read +//| :rtype: int or None""" +//| ... +//| +//| def read(self, nbytes: Optional[int] = None) -> Optional[bytes]: +//| """Same as `readinto`, but allocates and returns ``bytes``: ``None`` if nothing +//| is waiting yet, ``b""`` once capture has ended and nothing is left to read.""" +//| ... +//| + +// Standard stream methods, implemented in py/stream.c on top of this. +static mp_uint_t usb_host_bulk_instream_read_stream(mp_obj_t self_in, void *buf, mp_uint_t size, int *errcode) { + usb_host_bulk_instream_obj_t *self = MP_OBJ_TO_PTR(self_in); + // Look at deinited first: a stream seen deinited here has all of its data + // visible below, so an empty read means the end. + bool deinited = common_hal_usb_host_bulk_instream_deinited(self); + uint32_t count = common_hal_usb_host_bulk_instream_read(self, buf, size); + if (count > 0 || deinited) { + return count; + } + *errcode = MP_EAGAIN; + return MP_STREAM_ERROR; +} + +static mp_uint_t usb_host_bulk_instream_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) { + usb_host_bulk_instream_obj_t *self = MP_OBJ_TO_PTR(self_in); + if (request == MP_STREAM_CLOSE) { + common_hal_usb_host_bulk_instream_deinit(self); + return 0; + } + if (request == MP_STREAM_POLL) { + mp_uint_t flags = arg; + mp_uint_t ret = 0; + // A deinited stream is readable (it returns EOF) so that waiters wake up. + bool deinited = common_hal_usb_host_bulk_instream_deinited(self); + if ((flags & MP_STREAM_POLL_RD) && + (deinited || common_hal_usb_host_bulk_instream_get_in_waiting(self) > 0)) { + ret |= MP_STREAM_POLL_RD; + } + if (deinited) { + ret |= MP_STREAM_POLL_HUP; + } + return ret; + } + *errcode = MP_EINVAL; + return MP_STREAM_ERROR; +} + +//| in_waiting: int +//| """Bytes waiting to be read, including those left when capture ended on its own. +//| (read-only)""" +//| +static mp_obj_t usb_host_bulk_instream_obj_get_in_waiting(mp_obj_t self_in) { + usb_host_bulk_instream_obj_t *self = MP_OBJ_TO_PTR(self_in); + return mp_obj_new_int_from_uint(common_hal_usb_host_bulk_instream_get_in_waiting(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(usb_host_bulk_instream_get_in_waiting_obj, usb_host_bulk_instream_obj_get_in_waiting); + +MP_PROPERTY_GETTER(usb_host_bulk_instream_in_waiting_obj, + (mp_obj_t)&usb_host_bulk_instream_get_in_waiting_obj); + +//| lost_packets: int +//| """Packets dropped because the ring was full, meaning reads were not frequent +//| enough. Zero means the captured stream has no gaps. Readable after `deinit`. +//| (read-only)""" +//| +static mp_obj_t usb_host_bulk_instream_obj_get_lost_packets(mp_obj_t self_in) { + usb_host_bulk_instream_obj_t *self = MP_OBJ_TO_PTR(self_in); + return mp_obj_new_int_from_uint(common_hal_usb_host_bulk_instream_get_lost_packets(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(usb_host_bulk_instream_get_lost_packets_obj, usb_host_bulk_instream_obj_get_lost_packets); + +MP_PROPERTY_GETTER(usb_host_bulk_instream_lost_packets_obj, + (mp_obj_t)&usb_host_bulk_instream_get_lost_packets_obj); + +//| def reset_input_buffer(self) -> None: +//| """Discard every byte waiting in the ring. Raises `ValueError` once the stream +//| is deinited, because no more data will come.""" +//| ... +//| +static mp_obj_t usb_host_bulk_instream_obj_reset_input_buffer(mp_obj_t self_in) { + usb_host_bulk_instream_obj_t *self = MP_OBJ_TO_PTR(self_in); + check_for_deinit(self); + common_hal_usb_host_bulk_instream_reset_input_buffer(self); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(usb_host_bulk_instream_reset_input_buffer_obj, usb_host_bulk_instream_obj_reset_input_buffer); + +//| def deinit(self) -> None: +//| """Stop capture and free the ring, dropping any bytes not yet read.""" +//| ... +//| +static mp_obj_t usb_host_bulk_instream_obj_deinit(mp_obj_t self_in) { + usb_host_bulk_instream_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_usb_host_bulk_instream_deinit(self); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(usb_host_bulk_instream_deinit_obj, usb_host_bulk_instream_obj_deinit); + +//| def __enter__(self) -> InStream: +//| """No-op used by Context Managers.""" +//| ... +//| +// Provided by context manager helper. + +//| def __exit__(self) -> None: +//| """Automatically deinitializes when exiting a context. See +//| :ref:`lifetime-and-contextmanagers` for more info.""" +//| ... +//| +//| +// Provided by context manager helper. + +static const mp_rom_map_elem_t usb_host_bulk_instream_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&usb_host_bulk_instream_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&usb_host_bulk_instream_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, + + // Standard stream methods. + { 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_reset_input_buffer), MP_ROM_PTR(&usb_host_bulk_instream_reset_input_buffer_obj) }, + + // Properties + { MP_ROM_QSTR(MP_QSTR_in_waiting), MP_ROM_PTR(&usb_host_bulk_instream_in_waiting_obj) }, + { MP_ROM_QSTR(MP_QSTR_lost_packets), MP_ROM_PTR(&usb_host_bulk_instream_lost_packets_obj) }, +}; +static MP_DEFINE_CONST_DICT(usb_host_bulk_instream_locals_dict, usb_host_bulk_instream_locals_dict_table); + +static const mp_stream_p_t usb_host_bulk_instream_stream_p = { + .read = usb_host_bulk_instream_read_stream, + .ioctl = usb_host_bulk_instream_ioctl, + .is_text = false, +}; + +MP_DEFINE_CONST_OBJ_TYPE( + usb_host_bulk_instream_type, + MP_QSTR_InStream, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, usb_host_bulk_instream_make_new, + locals_dict, &usb_host_bulk_instream_locals_dict, + protocol, &usb_host_bulk_instream_stream_p + ); diff --git a/shared-bindings/usb_host_bulk/InStream.h b/shared-bindings/usb_host_bulk/InStream.h new file mode 100644 index 00000000000..f62cbc413fc --- /dev/null +++ b/shared-bindings/usb_host_bulk/InStream.h @@ -0,0 +1,42 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include + +#include "common-hal/usb_host_bulk/InStream.h" +#include "shared-module/usb/core/Device.h" + +extern const mp_obj_type_t usb_host_bulk_instream_type; + +void common_hal_usb_host_bulk_instream_construct(usb_host_bulk_instream_obj_t *self, + usb_core_device_obj_t *device, uint8_t endpoint, uint32_t buffer_size); +// Stops capture, waits for the host to let go of the ring, frees it and drops +// the unread bytes. It is also the finaliser. +void common_hal_usb_host_bulk_instream_deinit(usb_host_bulk_instream_obj_t *self); +// A stream that ended without deinit(), because the device stalled the +// endpoint, was unplugged or was reconfigured, is deinited here, keeping its +// unread bytes readable on the VM heap, so this may allocate: call it only +// from the VM. +bool common_hal_usb_host_bulk_instream_deinited(usb_host_bulk_instream_obj_t *self); +uint32_t common_hal_usb_host_bulk_instream_read(usb_host_bulk_instream_obj_t *self, uint8_t *data, uint32_t len); +uint32_t common_hal_usb_host_bulk_instream_get_in_waiting(usb_host_bulk_instream_obj_t *self); +uint32_t common_hal_usb_host_bulk_instream_get_lost_packets(usb_host_bulk_instream_obj_t *self); +void common_hal_usb_host_bulk_instream_reset_input_buffer(usb_host_bulk_instream_obj_t *self); + +// Hooks for usb.core.Device, which must not leave a stream polling an endpoint +// it reconfigures, reads, writes or closes. + +// Stops every stream from device_address. Their unread bytes stay readable. +// Never raises or allocates, so it is safe from TinyUSB callbacks. +void usb_host_bulk_stop_device(uint8_t device_address); +// True while a stream is polling this endpoint. +bool usb_host_bulk_endpoint_busy(uint8_t device_address, uint8_t endpoint); +// Stops the streams opened through this Device object, but not ones opened +// through another Device for the same address. Never raises or allocates. +void usb_host_bulk_device_deinit(usb_core_device_obj_t *device); diff --git a/shared-bindings/usb_host_bulk/__init__.c b/shared-bindings/usb_host_bulk/__init__.c new file mode 100644 index 00000000000..7cb3e4f58ac --- /dev/null +++ b/shared-bindings/usb_host_bulk/__init__.c @@ -0,0 +1,36 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "py/obj.h" +#include "py/runtime.h" + +#include "shared-bindings/usb_host_bulk/__init__.h" +#include "shared-bindings/usb_host_bulk/InStream.h" + +//| """Continuous bulk transfers on USB host ports +//| +//| This module keeps an endpoint busy in the background so that +//| continuously-streaming devices, such as RTL2832U SDR dongles, never overflow. +//| Devices are still found and configured with `usb.core`; `usb_host` manages the +//| host ports themselves. +//| +//| Available only on boards built with the PIO USB host and this feature enabled. +//| """ +//| + +static const mp_rom_map_elem_t usb_host_bulk_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_usb_host_bulk) }, + { MP_ROM_QSTR(MP_QSTR_InStream), MP_ROM_PTR(&usb_host_bulk_instream_type) }, +}; + +static MP_DEFINE_CONST_DICT(usb_host_bulk_module_globals, usb_host_bulk_module_globals_table); + +const mp_obj_module_t usb_host_bulk_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&usb_host_bulk_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_usb_host_bulk, usb_host_bulk_module); diff --git a/shared-bindings/usb_host_bulk/__init__.h b/shared-bindings/usb_host_bulk/__init__.h new file mode 100644 index 00000000000..779b49ffd8d --- /dev/null +++ b/shared-bindings/usb_host_bulk/__init__.h @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once diff --git a/shared-bindings/usb_midi/PortIn.c b/shared-bindings/usb_midi/PortIn.c index d62d0b53af1..3f4b19fdec2 100644 --- a/shared-bindings/usb_midi/PortIn.c +++ b/shared-bindings/usb_midi/PortIn.c @@ -60,7 +60,7 @@ static mp_uint_t usb_midi_portin_read(mp_obj_t self_in, void *buf_in, mp_uint_t return common_hal_usb_midi_portin_read(self, buf, size, errcode); } -static mp_uint_t usb_midi_portin_ioctl(mp_obj_t self_in, mp_uint_t request, mp_uint_t arg, int *errcode) { +static mp_uint_t usb_midi_portin_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) { usb_midi_portin_obj_t *self = MP_OBJ_TO_PTR(self_in); mp_uint_t ret; if (request == MP_STREAM_POLL) { diff --git a/shared-bindings/usb_midi/PortOut.c b/shared-bindings/usb_midi/PortOut.c index 89c83810188..35856ff25fa 100644 --- a/shared-bindings/usb_midi/PortOut.c +++ b/shared-bindings/usb_midi/PortOut.c @@ -42,7 +42,7 @@ static mp_uint_t usb_midi_portout_write(mp_obj_t self_in, const void *buf_in, mp return common_hal_usb_midi_portout_write(self, buf, size, errcode); } -static mp_uint_t usb_midi_portout_ioctl(mp_obj_t self_in, mp_uint_t request, mp_uint_t arg, int *errcode) { +static mp_uint_t usb_midi_portout_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) { usb_midi_portout_obj_t *self = MP_OBJ_TO_PTR(self_in); mp_uint_t ret; if (request == MP_STREAM_POLL) { diff --git a/shared-bindings/usb_video/USBFramebuffer.c b/shared-bindings/usb_video/USBFramebuffer.c index 25151809df5..efff704a876 100644 --- a/shared-bindings/usb_video/USBFramebuffer.c +++ b/shared-bindings/usb_video/USBFramebuffer.c @@ -94,14 +94,17 @@ static void usb_video_uvcframebuffer_get_bufinfo(mp_obj_t self_in, mp_buffer_inf // These version exists so that the prototype matches the protocol, // avoiding a type cast that can hide errors static void usb_video_uvcframebuffer_swapbuffers(mp_obj_t self_in, uint8_t *dirty_row_bitmap) { - (void)dirty_row_bitmap; - shared_module_usb_video_uvcframebuffer_refresh(self_in); + shared_module_usb_video_uvcframebuffer_swapbuffers(self_in, dirty_row_bitmap); } static void usb_video_uvcframebuffer_deinit_proto(mp_obj_t self_in) { /* NOTHING */ } +static void usb_video_uvcframebuffer_set_frame_callback(mp_obj_t self_in, framebuffer_frame_callback_t cb, void *data) { + shared_module_usb_video_uvcframebuffer_set_frame_callback(self_in, cb, data); +} + static int usb_video_uvcframebuffer_get_width_proto(mp_obj_t self_in) { return shared_module_usb_video_uvcframebuffer_get_width(self_in); } @@ -128,6 +131,7 @@ static const framebuffer_p_t usb_video_uvcframebuffer_proto = { .swapbuffers = usb_video_uvcframebuffer_swapbuffers, .deinit = usb_video_uvcframebuffer_deinit_proto, .get_reverse_pixels_in_word = usb_video_uvcframebuffer_get_reverse_pixels_in_word_proto, + .set_frame_callback = usb_video_uvcframebuffer_set_frame_callback, }; static mp_int_t usb_video_uvcframebuffer_get_buffer(mp_obj_t self_in, mp_buffer_info_t *bufinfo, mp_uint_t flags) { diff --git a/shared-bindings/usb_video/USBFramebuffer.h b/shared-bindings/usb_video/USBFramebuffer.h index b974f61578a..eb04fa19816 100644 --- a/shared-bindings/usb_video/USBFramebuffer.h +++ b/shared-bindings/usb_video/USBFramebuffer.h @@ -6,6 +6,8 @@ #pragma once +#include "shared-module/framebufferio/__init__.h" + typedef struct usb_video_uvcframebuffer_obj usb_video_uvcframebuffer_obj_t; extern const mp_obj_type_t usb_video_USBFramebuffer_type; @@ -13,5 +15,8 @@ extern usb_video_uvcframebuffer_obj_t usb_video_uvcframebuffer_singleton_obj; void shared_module_usb_video_uvcframebuffer_get_bufinfo(usb_video_uvcframebuffer_obj_t *self, mp_buffer_info_t *bufinfo); void shared_module_usb_video_uvcframebuffer_refresh(usb_video_uvcframebuffer_obj_t *self); +void shared_module_usb_video_uvcframebuffer_swapbuffers(usb_video_uvcframebuffer_obj_t *self, const uint8_t *dirty_row_bitmap); +void shared_module_usb_video_uvcframebuffer_set_frame_callback(usb_video_uvcframebuffer_obj_t *self, framebuffer_frame_callback_t cb, void *data); +void shared_module_usb_video_uvcframebuffer_frame_boundary(usb_video_uvcframebuffer_obj_t *self); int shared_module_usb_video_uvcframebuffer_get_width(usb_video_uvcframebuffer_obj_t *self); int shared_module_usb_video_uvcframebuffer_get_height(usb_video_uvcframebuffer_obj_t *self); diff --git a/shared-bindings/usb_video/__init__.c b/shared-bindings/usb_video/__init__.c index 06050188d66..cc4add35e80 100644 --- a/shared-bindings/usb_video/__init__.c +++ b/shared-bindings/usb_video/__init__.c @@ -10,6 +10,7 @@ #include "shared-bindings/usb_video/__init__.h" #include "shared-bindings/usb_video/USBFramebuffer.h" #include "shared-module/usb_video/__init__.h" +#include "shared-module/usb_video/uvc_usb_descriptors.h" //| """Allows streaming bitmaps to a host computer via USB //| @@ -36,9 +37,10 @@ //| # code.py //| import usb_video //| import framebufferio -//| import displayio +//| import supervisor //| -//| displayio.release_displays() +//| if supervisor.runtime.display: +//| supervisor.runtime.display.deinit() //| display = framebufferio.FramebufferDisplay(usb_video.USBFramebuffer()) //| //| # ... use the display object with displayio Group and TileGrid objects @@ -48,12 +50,14 @@ //| //| -//| def enable_framebuffer(width: int, height: int) -> None: +//| def enable_framebuffer(width: int, height: int, *, frame_rate: int = 15) -> None: //| """Enable a USB video framebuffer, setting the given width & height //| //| This function may only be used from ``boot.py``. //| -//| Width is rounded up to a multiple of 2. +//| Width is rounded up to a multiple of 2. ``frame_rate`` is the advertised +//| UVC frame rate; uncompressed YUYV uses 2 bytes per pixel, so larger frames +//| need a lower rate to fit in USB high-speed bandwidth. //| //| After boot.py completes, the framebuffer will be allocated. Total storage //| of 4×``width``×``height`` bytes is required, reducing the amount available @@ -63,10 +67,11 @@ //| static mp_obj_t usb_video_enable_framebuffer(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - enum { ARG_width, ARG_height }; + enum { ARG_width, ARG_height, ARG_frame_rate }; static const mp_arg_t allowed_args[] = { { MP_QSTR_width, MP_ARG_REQUIRED | MP_ARG_INT, { .u_int = 0 } }, { MP_QSTR_height, MP_ARG_REQUIRED | MP_ARG_INT, { .u_int = 0 } }, + { MP_QSTR_frame_rate, MP_ARG_KW_ONLY | MP_ARG_INT, { .u_int = DEFAULT_FRAME_RATE } }, }; 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); @@ -74,7 +79,8 @@ static mp_obj_t usb_video_enable_framebuffer(size_t n_args, const mp_obj_t *pos_ // (but note that most devices will not be able to allocate this much memory. uint32_t width = mp_arg_validate_int_range(args[ARG_width].u_int, 0, 32767, MP_QSTR_width); uint32_t height = mp_arg_validate_int_range(args[ARG_height].u_int, 0, 32767, MP_QSTR_height); - if (!shared_module_usb_video_enable(width, height)) { + uint32_t frame_rate = mp_arg_validate_int_range(args[ARG_frame_rate].u_int, 1, 60, MP_QSTR_frame_rate); + if (!shared_module_usb_video_enable(width, height, frame_rate)) { mp_raise_RuntimeError(MP_ERROR_TEXT("Cannot change USB devices now")); } diff --git a/shared-bindings/usb_video/__init__.h b/shared-bindings/usb_video/__init__.h index 634a6f4a2da..19e0eee7392 100644 --- a/shared-bindings/usb_video/__init__.h +++ b/shared-bindings/usb_video/__init__.h @@ -7,6 +7,7 @@ #pragma once #include "shared-module/displayio/Bitmap.h" -bool shared_module_usb_video_enable(mp_int_t frame_width, mp_int_t frame_height); +bool shared_module_usb_video_enable(mp_int_t frame_width, mp_int_t frame_height, mp_int_t frame_rate); bool shared_module_usb_video_disable(void); void shared_module_usb_video_swapbuffers(void); +void shared_module_usb_video_swapbuffers_dirty(const uint8_t *dirty_row_bitmap); diff --git a/shared-bindings/util.c b/shared-bindings/util.c index 0711428b4de..0bcaa2eef41 100644 --- a/shared-bindings/util.c +++ b/shared-bindings/util.c @@ -8,6 +8,8 @@ #include "shared-bindings/util.h" +#include "shared-bindings/os/__init__.h" + // If so, deinit() has already been called on the object, so complain. void raise_deinited_error(void) { mp_raise_ValueError(MP_ERROR_TEXT("Object has been deinitialized and can no longer be used. Create a new object.")); @@ -33,3 +35,16 @@ void properties_construct_helper(mp_obj_t self_in, const mp_arg_t *args, const m } } } + +bool path_exists(const char *path) { + // Use common_hal_os_stat to check if path exists + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + common_hal_os_stat(path); + nlr_pop(); + return true; + } else { + // Path doesn't exist + return false; + } +} diff --git a/shared-bindings/util.h b/shared-bindings/util.h index f1e4dca13aa..11f0a00db71 100644 --- a/shared-bindings/util.h +++ b/shared-bindings/util.h @@ -9,6 +9,7 @@ #include "py/mpprint.h" #include "py/runtime.h" -void raise_deinited_error(void); +MP_NORETURN void raise_deinited_error(void); void properties_print_helper(const mp_print_t *print, mp_obj_t self_in, const mp_arg_t *properties, size_t n_properties); void properties_construct_helper(mp_obj_t self_in, const mp_arg_t *args, const mp_arg_val_t *vals, size_t n_properties); +bool path_exists(const char *path); diff --git a/shared-bindings/vectorio/Circle.c b/shared-bindings/vectorio/Circle.c index 7fb20b59b4d..7965a4e9d54 100644 --- a/shared-bindings/vectorio/Circle.c +++ b/shared-bindings/vectorio/Circle.c @@ -22,6 +22,8 @@ //| radius: int, //| x: int, //| y: int, +//| outline_width: int = 0, +//| outline_color_index: Optional[int] = None, //| ) -> None: //| """Circle is positioned on screen by its center point. //| @@ -30,16 +32,41 @@ //| :param int x: Initial x position of the axis. //| :param int y: Initial y position of the axis. //| :param int color_index: Initial color_index to use when selecting color from the palette. +//| :param int outline_width: The width in pixels of a ring drawn just inside the +//| circle's outer edge, so it never makes the circle bigger. 0 (the default) +//| draws no ring. The width must not exceed the radius. +//| :param Optional[int] outline_color_index: The 0 based palette index of the ring +//| color, or ``None`` (the default) for no ring. Only used when +//| ``outline_width`` is greater than 0. Use ``None`` rather than a transparent +//| palette entry to remove a ring: the two compositors draw a band with a +//| transparent color differently. //| """ //| +// -1 means no outline color, which the shape stores as an unset bias. +static int32_t parse_outline_color_index(mp_obj_t outline_color_index) { + if (outline_color_index == mp_const_none) { + return -1; + } + return mp_arg_validate_int_min(mp_obj_get_int(outline_color_index), 0, MP_QSTR_outline_color_index); +} + +static mp_obj_t outline_color_index_to_obj(int32_t outline_color_index) { + if (outline_color_index < 0) { + return mp_const_none; + } + return mp_obj_new_int(outline_color_index); +} + static mp_obj_t vectorio_circle_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { - enum { ARG_pixel_shader, ARG_radius, ARG_x, ARG_y, ARG_color_index }; + enum { ARG_pixel_shader, ARG_radius, ARG_x, ARG_y, ARG_color_index, ARG_outline_width, ARG_outline_color_index }; static const mp_arg_t allowed_args[] = { { MP_QSTR_pixel_shader, MP_ARG_OBJ | MP_ARG_KW_ONLY | MP_ARG_REQUIRED, { .u_obj = NULL } }, { MP_QSTR_radius, MP_ARG_REQUIRED | MP_ARG_INT, { .u_obj = NULL } }, { MP_QSTR_x, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0} }, { MP_QSTR_y, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0} }, { MP_QSTR_color_index, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0} }, + { MP_QSTR_outline_width, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0} }, + { MP_QSTR_outline_color_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_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); @@ -47,9 +74,13 @@ static mp_obj_t vectorio_circle_make_new(const mp_obj_type_t *type, size_t n_arg mp_int_t radius = args[ARG_radius].u_int; mp_arg_validate_int_min(radius, 1, MP_QSTR_radius); + mp_int_t outline_width = args[ARG_outline_width].u_int; + mp_arg_validate_int_range(outline_width, 0, radius, MP_QSTR_outline_width); + vectorio_circle_t *self = mp_obj_malloc(vectorio_circle_t, &vectorio_circle_type); uint16_t color_index = args[ARG_color_index].u_int; - common_hal_vectorio_circle_construct(self, radius, color_index); + int32_t outline_color_index = parse_outline_color_index(args[ARG_outline_color_index].u_obj); + common_hal_vectorio_circle_construct(self, radius, color_index, outline_width, outline_color_index); // VectorShape parts mp_obj_t pixel_shader = args[ARG_pixel_shader].u_obj; @@ -61,24 +92,56 @@ static mp_obj_t vectorio_circle_make_new(const mp_obj_type_t *type, size_t n_arg return MP_OBJ_FROM_PTR(self); } +// A Python subclass of Circle is an mp_obj_instance_t that holds the native Circle in +// subobj[0], so every entry point below has to see that native object instead of the instance. +// See native_rectangle() in Rectangle.c. +static vectorio_circle_t *native_circle(mp_obj_t self_in) { + mp_obj_t native = mp_obj_cast_to_native_base(self_in, MP_OBJ_FROM_PTR(&vectorio_circle_type)); + if (native == MP_OBJ_NULL) { + return MP_OBJ_TO_PTR(self_in); + } + mp_obj_assert_native_inited(native); + return MP_OBJ_TO_PTR(native); +} + +#if CIRCUITPY_DISPLAYIO_LVGL +static mp_obj_t circle_lvgl_protocol_self(mp_obj_t self_in) { + return common_hal_vectorio_circle_get_draw_protocol(native_circle(self_in)); +} + +static const lvgl_protocol_t circle_lvgl_protocol = { + MP_PROTO_IMPLEMENT(MP_QSTR_protocol_lvgl) + .protocol_self = circle_lvgl_protocol_self, +}; +#define VECTORIO_CIRCLE_PROTOCOL &circle_lvgl_protocol +#else +static mp_obj_t circle_draw_protocol_self(mp_obj_t self_in) { + return common_hal_vectorio_circle_get_draw_protocol(native_circle(self_in)); +} + static const vectorio_draw_protocol_t circle_draw_protocol = { MP_PROTO_IMPLEMENT(MP_QSTR_protocol_draw) - .draw_get_protocol_self = (draw_get_protocol_self_fun)common_hal_vectorio_circle_get_draw_protocol, + .draw_get_protocol_self = circle_draw_protocol_self, .draw_protocol_impl = &vectorio_vector_shape_draw_protocol_impl }; +#define VECTORIO_CIRCLE_PROTOCOL &circle_draw_protocol +#endif //| radius: int //| """The radius of the circle in pixels.""" static mp_obj_t vectorio_circle_obj_get_radius(mp_obj_t self_in) { - vectorio_circle_t *self = MP_OBJ_TO_PTR(self_in); + vectorio_circle_t *self = native_circle(self_in); return mp_obj_new_int(common_hal_vectorio_circle_get_radius(self)); } MP_DEFINE_CONST_FUN_OBJ_1(vectorio_circle_get_radius_obj, vectorio_circle_obj_get_radius); static mp_obj_t vectorio_circle_obj_set_radius(mp_obj_t self_in, mp_obj_t radius) { - vectorio_circle_t *self = MP_OBJ_TO_PTR(self_in); - common_hal_vectorio_circle_set_radius(self, mp_obj_get_int(radius)); + vectorio_circle_t *self = native_circle(self_in); + mp_int_t new_radius = mp_arg_validate_int_min(mp_obj_get_int(radius), 1, MP_QSTR_radius); + // Shrinking the circle must not leave an outline wider than its new radius. + mp_arg_validate_int_range(self->outline_width, 0, new_radius, MP_QSTR_outline_width); + common_hal_vectorio_circle_set_radius(self, new_radius); return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_2(vectorio_circle_set_radius_obj, vectorio_circle_obj_set_radius); @@ -90,13 +153,13 @@ MP_PROPERTY_GETSET(vectorio_circle_radius_obj, //| color_index: int //| """The color_index of the circle as 0 based index of the palette.""" static mp_obj_t vectorio_circle_obj_get_color_index(mp_obj_t self_in) { - vectorio_circle_t *self = MP_OBJ_TO_PTR(self_in); + vectorio_circle_t *self = native_circle(self_in); return mp_obj_new_int(common_hal_vectorio_circle_get_color_index(self)); } MP_DEFINE_CONST_FUN_OBJ_1(vectorio_circle_get_color_index_obj, vectorio_circle_obj_get_color_index); static mp_obj_t vectorio_circle_obj_set_color_index(mp_obj_t self_in, mp_obj_t color_index) { - vectorio_circle_t *self = MP_OBJ_TO_PTR(self_in); + vectorio_circle_t *self = native_circle(self_in); common_hal_vectorio_circle_set_color_index(self, mp_obj_get_int(color_index)); return mp_const_none; } @@ -106,6 +169,49 @@ MP_PROPERTY_GETSET(vectorio_circle_color_index_obj, (mp_obj_t)&vectorio_circle_get_color_index_obj, (mp_obj_t)&vectorio_circle_set_color_index_obj); +//| outline_width: int +//| """The width of the ring in pixels. The ring is drawn inside the circle, so it never +//| changes the circle's size. 0 draws no ring. The width must not exceed the radius.""" +static mp_obj_t vectorio_circle_obj_get_outline_width(mp_obj_t self_in) { + vectorio_circle_t *self = native_circle(self_in); + return mp_obj_new_int(common_hal_vectorio_circle_get_outline_width(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(vectorio_circle_get_outline_width_obj, vectorio_circle_obj_get_outline_width); + +static mp_obj_t vectorio_circle_obj_set_outline_width(mp_obj_t self_in, mp_obj_t outline_width) { + vectorio_circle_t *self = native_circle(self_in); + mp_int_t new_outline_width = mp_arg_validate_int_range(mp_obj_get_int(outline_width), 0, + self->radius, MP_QSTR_outline_width); + common_hal_vectorio_circle_set_outline_width(self, new_outline_width); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(vectorio_circle_set_outline_width_obj, vectorio_circle_obj_set_outline_width); + +MP_PROPERTY_GETSET(vectorio_circle_outline_width_obj, + (mp_obj_t)&vectorio_circle_get_outline_width_obj, + (mp_obj_t)&vectorio_circle_set_outline_width_obj); + +//| outline_color_index: Optional[int] +//| """The 0 based palette index of the ring color, or ``None`` for no ring. Only used when +//| :py:attr:`outline_width` is greater than 0.""" +static mp_obj_t vectorio_circle_obj_get_outline_color_index(mp_obj_t self_in) { + vectorio_circle_t *self = native_circle(self_in); + return outline_color_index_to_obj(common_hal_vectorio_circle_get_outline_color_index(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(vectorio_circle_get_outline_color_index_obj, vectorio_circle_obj_get_outline_color_index); + +static mp_obj_t vectorio_circle_obj_set_outline_color_index(mp_obj_t self_in, mp_obj_t outline_color_index) { + vectorio_circle_t *self = native_circle(self_in); + common_hal_vectorio_circle_set_outline_color_index(self, + parse_outline_color_index(outline_color_index)); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(vectorio_circle_set_outline_color_index_obj, vectorio_circle_obj_set_outline_color_index); + +MP_PROPERTY_GETSET(vectorio_circle_outline_color_index_obj, + (mp_obj_t)&vectorio_circle_get_outline_color_index_obj, + (mp_obj_t)&vectorio_circle_set_outline_color_index_obj); + // Documentation for properties inherited from VectorShape. @@ -135,6 +241,8 @@ static const mp_rom_map_elem_t vectorio_circle_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_y), MP_ROM_PTR(&vectorio_vector_shape_y_obj) }, { MP_ROM_QSTR(MP_QSTR_hidden), MP_ROM_PTR(&vectorio_vector_shape_hidden_obj) }, { MP_ROM_QSTR(MP_QSTR_color_index), MP_ROM_PTR(&vectorio_circle_color_index_obj) }, + { MP_ROM_QSTR(MP_QSTR_outline_width), MP_ROM_PTR(&vectorio_circle_outline_width_obj) }, + { MP_ROM_QSTR(MP_QSTR_outline_color_index), MP_ROM_PTR(&vectorio_circle_outline_color_index_obj) }, { MP_ROM_QSTR(MP_QSTR_location), MP_ROM_PTR(&vectorio_vector_shape_location_obj) }, { MP_ROM_QSTR(MP_QSTR_pixel_shader), MP_ROM_PTR(&vectorio_vector_shape_pixel_shader_obj) }, }; @@ -146,5 +254,5 @@ MP_DEFINE_CONST_OBJ_TYPE( MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, make_new, vectorio_circle_make_new, locals_dict, &vectorio_circle_locals_dict, - protocol, &circle_draw_protocol + protocol, VECTORIO_CIRCLE_PROTOCOL ); diff --git a/shared-bindings/vectorio/Circle.h b/shared-bindings/vectorio/Circle.h index 2c72e81881c..cb1f82a3c66 100644 --- a/shared-bindings/vectorio/Circle.h +++ b/shared-bindings/vectorio/Circle.h @@ -12,7 +12,7 @@ extern const mp_obj_type_t vectorio_circle_type; -void common_hal_vectorio_circle_construct(vectorio_circle_t *self, uint16_t radius, uint16_t color_index); +void common_hal_vectorio_circle_construct(vectorio_circle_t *self, uint16_t radius, uint16_t color_index, uint16_t outline_width, int32_t outline_color_index); void common_hal_vectorio_circle_set_on_dirty(vectorio_circle_t *self, vectorio_event_t notification); @@ -27,4 +27,11 @@ void common_hal_vectorio_circle_set_radius(void *circle, int16_t radius); uint16_t common_hal_vectorio_circle_get_color_index(void *obj); void common_hal_vectorio_circle_set_color_index(void *obj, uint16_t color_index); +uint16_t common_hal_vectorio_circle_get_outline_width(void *obj); +void common_hal_vectorio_circle_set_outline_width(void *obj, uint16_t outline_width); + +// -1 means no outline color was set. +int32_t common_hal_vectorio_circle_get_outline_color_index(void *obj); +void common_hal_vectorio_circle_set_outline_color_index(void *obj, int32_t outline_color_index); + mp_obj_t common_hal_vectorio_circle_get_draw_protocol(void *circle); diff --git a/shared-bindings/vectorio/Polygon.c b/shared-bindings/vectorio/Polygon.c index 0f45da21e61..9f475a9fe41 100644 --- a/shared-bindings/vectorio/Polygon.c +++ b/shared-bindings/vectorio/Polygon.c @@ -69,23 +69,52 @@ static mp_obj_t vectorio_polygon_make_new(const mp_obj_type_t *type, size_t n_ar return MP_OBJ_FROM_PTR(self); } +// A Python subclass of Polygon is an mp_obj_instance_t that holds the native Polygon in +// subobj[0], so every entry point below has to see that native object instead of the instance. +// See native_rectangle() in Rectangle.c. +static vectorio_polygon_t *native_polygon(mp_obj_t self_in) { + mp_obj_t native = mp_obj_cast_to_native_base(self_in, MP_OBJ_FROM_PTR(&vectorio_polygon_type)); + if (native == MP_OBJ_NULL) { + return MP_OBJ_TO_PTR(self_in); + } + mp_obj_assert_native_inited(native); + return MP_OBJ_TO_PTR(native); +} + +#if CIRCUITPY_DISPLAYIO_LVGL +static mp_obj_t polygon_lvgl_protocol_self(mp_obj_t self_in) { + return common_hal_vectorio_polygon_get_draw_protocol(native_polygon(self_in)); +} + +static const lvgl_protocol_t polygon_lvgl_protocol = { + MP_PROTO_IMPLEMENT(MP_QSTR_protocol_lvgl) + .protocol_self = polygon_lvgl_protocol_self, +}; +#define VECTORIO_POLYGON_PROTOCOL &polygon_lvgl_protocol +#else +static mp_obj_t polygon_draw_protocol_self(mp_obj_t self_in) { + return common_hal_vectorio_polygon_get_draw_protocol(native_polygon(self_in)); +} + static const vectorio_draw_protocol_t polygon_draw_protocol = { MP_PROTO_IMPLEMENT(MP_QSTR_protocol_draw) - .draw_get_protocol_self = (draw_get_protocol_self_fun)common_hal_vectorio_polygon_get_draw_protocol, + .draw_get_protocol_self = polygon_draw_protocol_self, .draw_protocol_impl = &vectorio_vector_shape_draw_protocol_impl }; +#define VECTORIO_POLYGON_PROTOCOL &polygon_draw_protocol +#endif //| points: List[Tuple[int, int]] //| """Vertices for the polygon.""" static mp_obj_t vectorio_polygon_obj_get_points(mp_obj_t self_in) { - vectorio_polygon_t *self = MP_OBJ_TO_PTR(self_in); + vectorio_polygon_t *self = native_polygon(self_in); return common_hal_vectorio_polygon_get_points(self); } MP_DEFINE_CONST_FUN_OBJ_1(vectorio_polygon_get_points_obj, vectorio_polygon_obj_get_points); static mp_obj_t vectorio_polygon_obj_set_points(mp_obj_t self_in, mp_obj_t points) { - vectorio_polygon_t *self = MP_OBJ_TO_PTR(self_in); + vectorio_polygon_t *self = native_polygon(self_in); common_hal_vectorio_polygon_set_points(self, points); return mp_const_none; @@ -99,13 +128,13 @@ MP_PROPERTY_GETSET(vectorio_polygon_points_obj, //| color_index: int //| """The color_index of the polygon as 0 based index of the palette.""" static mp_obj_t vectorio_polygon_obj_get_color_index(mp_obj_t self_in) { - vectorio_polygon_t *self = MP_OBJ_TO_PTR(self_in); + vectorio_polygon_t *self = native_polygon(self_in); return mp_obj_new_int(common_hal_vectorio_polygon_get_color_index(self)); } MP_DEFINE_CONST_FUN_OBJ_1(vectorio_polygon_get_color_index_obj, vectorio_polygon_obj_get_color_index); static mp_obj_t vectorio_polygon_obj_set_color_index(mp_obj_t self_in, mp_obj_t color_index) { - vectorio_polygon_t *self = MP_OBJ_TO_PTR(self_in); + vectorio_polygon_t *self = native_polygon(self_in); common_hal_vectorio_polygon_set_color_index(self, mp_obj_get_int(color_index)); return mp_const_none; } @@ -155,5 +184,5 @@ MP_DEFINE_CONST_OBJ_TYPE( MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, make_new, vectorio_polygon_make_new, locals_dict, &vectorio_polygon_locals_dict, - protocol, &polygon_draw_protocol + protocol, VECTORIO_POLYGON_PROTOCOL ); diff --git a/shared-bindings/vectorio/Rectangle.c b/shared-bindings/vectorio/Rectangle.c index 3582b010149..d7fed77a19f 100644 --- a/shared-bindings/vectorio/Rectangle.c +++ b/shared-bindings/vectorio/Rectangle.c @@ -22,6 +22,9 @@ //| height: int, //| x: int, //| y: int, +//| radius: int = 0, +//| outline_width: int = 0, +//| outline_color_index: Optional[int] = None, //| ) -> None: //| """Represents a rectangle by defining its bounds //| @@ -31,10 +34,45 @@ //| :param int x: Initial x position of the top left corner. //| :param int y: Initial y position of the top left corner. //| :param int color_index: Initial color_index to use when selecting color from the palette. +//| :param int radius: The radius of the corners in pixels. 0 (the default) is square +//| corners. The radius must not exceed half of the shortest side. +//| :param int outline_width: The width in pixels of a border drawn just inside the +//| rectangle's bounds, so it never makes the rectangle bigger. 0 (the default) +//| draws no border. The width must not exceed half of the shortest side. +//| :param Optional[int] outline_color_index: The 0 based palette index of the border +//| color, or ``None`` (the default) for no border. Only used when +//| ``outline_width`` is greater than 0. Use ``None`` rather than a transparent +//| palette entry to remove a border: the two compositors draw a band with a +//| transparent color differently. //| """ //| +// -1 means no outline color, which the shape stores as an unset bias. +static int32_t parse_outline_color_index(mp_obj_t outline_color_index) { + if (outline_color_index == mp_const_none) { + return -1; + } + return mp_arg_validate_int_min(mp_obj_get_int(outline_color_index), 0, MP_QSTR_outline_color_index); +} + +static mp_obj_t outline_color_index_to_obj(int32_t outline_color_index) { + if (outline_color_index < 0) { + return mp_const_none; + } + return mp_obj_new_int(outline_color_index); +} + +static mp_int_t half_short_side(mp_int_t width, mp_int_t height) { + return (width < height ? width : height) / 2; +} + +static void validate_radius_and_outline(mp_int_t radius, mp_int_t outline_width, mp_int_t width, mp_int_t height) { + mp_int_t maximum = half_short_side(width, height); + mp_arg_validate_int_range(radius, 0, maximum, MP_QSTR_radius); + mp_arg_validate_int_range(outline_width, 0, maximum, MP_QSTR_outline_width); +} + static mp_obj_t vectorio_rectangle_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { - enum { ARG_pixel_shader, ARG_width, ARG_height, ARG_x, ARG_y, ARG_color_index }; + enum { ARG_pixel_shader, ARG_width, ARG_height, ARG_x, ARG_y, ARG_color_index, ARG_radius, ARG_outline_width, ARG_outline_color_index }; static const mp_arg_t allowed_args[] = { { MP_QSTR_pixel_shader, MP_ARG_OBJ | MP_ARG_KW_ONLY | MP_ARG_REQUIRED, {.u_obj = NULL } }, { MP_QSTR_width, MP_ARG_REQUIRED | MP_ARG_INT, {.u_int = 0 } }, @@ -42,6 +80,9 @@ static mp_obj_t vectorio_rectangle_make_new(const mp_obj_type_t *type, size_t n_ { MP_QSTR_x, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0} }, { MP_QSTR_y, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0} }, { MP_QSTR_color_index, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0} }, + { MP_QSTR_radius, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0} }, + { MP_QSTR_outline_width, MP_ARG_INT | MP_ARG_KW_ONLY, {.u_int = 0} }, + { MP_QSTR_outline_color_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_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); @@ -50,10 +91,14 @@ static mp_obj_t vectorio_rectangle_make_new(const mp_obj_type_t *type, size_t n_ mp_arg_validate_int_min(width, 1, MP_QSTR_width); mp_int_t height = args[ARG_height].u_int; mp_arg_validate_int_min(height, 1, MP_QSTR_height); + mp_int_t radius = args[ARG_radius].u_int; + mp_int_t outline_width = args[ARG_outline_width].u_int; + validate_radius_and_outline(radius, outline_width, width, height); vectorio_rectangle_t *self = mp_obj_malloc(vectorio_rectangle_t, &vectorio_rectangle_type); uint16_t color_index = args[ARG_color_index].u_int; - common_hal_vectorio_rectangle_construct(self, width, height, color_index); + int32_t outline_color_index = parse_outline_color_index(args[ARG_outline_color_index].u_obj); + common_hal_vectorio_rectangle_construct(self, width, height, color_index, radius, outline_width, outline_color_index); // VectorShape parts mp_obj_t pixel_shader = args[ARG_pixel_shader].u_obj; @@ -65,23 +110,55 @@ static mp_obj_t vectorio_rectangle_make_new(const mp_obj_type_t *type, size_t n_ return MP_OBJ_FROM_PTR(self); } +// A Python subclass of Rectangle (a display_shapes RoundRect, for example) is an +// mp_obj_instance_t that holds the native Rectangle in subobj[0], so every entry point below +// has to see that native object instead of the instance. Resolving it here keeps the protocol +// slot on the native type. See displayio.TileGrid for the same pattern. +static vectorio_rectangle_t *native_rectangle(mp_obj_t self_in) { + mp_obj_t native = mp_obj_cast_to_native_base(self_in, MP_OBJ_FROM_PTR(&vectorio_rectangle_type)); + if (native == MP_OBJ_NULL) { + return MP_OBJ_TO_PTR(self_in); + } + mp_obj_assert_native_inited(native); + return MP_OBJ_TO_PTR(native); +} + +#if CIRCUITPY_DISPLAYIO_LVGL +static mp_obj_t rectangle_lvgl_protocol_self(mp_obj_t self_in) { + return common_hal_vectorio_rectangle_get_draw_protocol(native_rectangle(self_in)); +} + +static const lvgl_protocol_t rectangle_lvgl_protocol = { + MP_PROTO_IMPLEMENT(MP_QSTR_protocol_lvgl) + .protocol_self = rectangle_lvgl_protocol_self, +}; +#define VECTORIO_RECTANGLE_PROTOCOL &rectangle_lvgl_protocol +#else +static mp_obj_t rectangle_draw_protocol_self(mp_obj_t self_in) { + return common_hal_vectorio_rectangle_get_draw_protocol(native_rectangle(self_in)); +} + static const vectorio_draw_protocol_t rectangle_draw_protocol = { MP_PROTO_IMPLEMENT(MP_QSTR_protocol_draw) - .draw_get_protocol_self = (draw_get_protocol_self_fun)common_hal_vectorio_rectangle_get_draw_protocol, + .draw_get_protocol_self = rectangle_draw_protocol_self, .draw_protocol_impl = &vectorio_vector_shape_draw_protocol_impl }; +#define VECTORIO_RECTANGLE_PROTOCOL &rectangle_draw_protocol +#endif //| width: int //| """The width of the rectangle in pixels.""" static mp_obj_t vectorio_rectangle_obj_get_width(mp_obj_t self_in) { - vectorio_rectangle_t *self = MP_OBJ_TO_PTR(self_in); + vectorio_rectangle_t *self = native_rectangle(self_in); return mp_obj_new_int(common_hal_vectorio_rectangle_get_width(self)); } MP_DEFINE_CONST_FUN_OBJ_1(vectorio_rectangle_get_width_obj, vectorio_rectangle_obj_get_width); static mp_obj_t vectorio_rectangle_obj_set_width(mp_obj_t self_in, mp_obj_t width) { - vectorio_rectangle_t *self = MP_OBJ_TO_PTR(self_in); - common_hal_vectorio_rectangle_set_width(self, mp_obj_get_int(width)); + vectorio_rectangle_t *self = native_rectangle(self_in); + mp_int_t new_width = mp_arg_validate_int_min(mp_obj_get_int(width), 1, MP_QSTR_width); + validate_radius_and_outline(self->radius, self->outline_width, new_width, self->height); + common_hal_vectorio_rectangle_set_width(self, new_width); return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_2(vectorio_rectangle_set_width_obj, vectorio_rectangle_obj_set_width); @@ -93,14 +170,16 @@ MP_PROPERTY_GETSET(vectorio_rectangle_width_obj, //| height: int //| """The height of the rectangle in pixels.""" static mp_obj_t vectorio_rectangle_obj_get_height(mp_obj_t self_in) { - vectorio_rectangle_t *self = MP_OBJ_TO_PTR(self_in); + vectorio_rectangle_t *self = native_rectangle(self_in); return mp_obj_new_int(common_hal_vectorio_rectangle_get_height(self)); } MP_DEFINE_CONST_FUN_OBJ_1(vectorio_rectangle_get_height_obj, vectorio_rectangle_obj_get_height); static mp_obj_t vectorio_rectangle_obj_set_height(mp_obj_t self_in, mp_obj_t height) { - vectorio_rectangle_t *self = MP_OBJ_TO_PTR(self_in); - common_hal_vectorio_rectangle_set_height(self, mp_obj_get_int(height)); + vectorio_rectangle_t *self = native_rectangle(self_in); + mp_int_t new_height = mp_arg_validate_int_min(mp_obj_get_int(height), 1, MP_QSTR_height); + validate_radius_and_outline(self->radius, self->outline_width, self->width, new_height); + common_hal_vectorio_rectangle_set_height(self, new_height); return mp_const_none; } MP_DEFINE_CONST_FUN_OBJ_2(vectorio_rectangle_set_height_obj, vectorio_rectangle_obj_set_height); @@ -109,16 +188,83 @@ MP_PROPERTY_GETSET(vectorio_rectangle_height_obj, (mp_obj_t)&vectorio_rectangle_get_height_obj, (mp_obj_t)&vectorio_rectangle_set_height_obj); +//| radius: int +//| """The radius of the rectangle's corners in pixels. 0 is square corners. +//| +//| The radius must not exceed half of the shortest side.""" +static mp_obj_t vectorio_rectangle_obj_get_radius(mp_obj_t self_in) { + vectorio_rectangle_t *self = native_rectangle(self_in); + return mp_obj_new_int(common_hal_vectorio_rectangle_get_radius(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(vectorio_rectangle_get_radius_obj, vectorio_rectangle_obj_get_radius); + +static mp_obj_t vectorio_rectangle_obj_set_radius(mp_obj_t self_in, mp_obj_t radius) { + vectorio_rectangle_t *self = native_rectangle(self_in); + mp_int_t new_radius = mp_arg_validate_int_range(mp_obj_get_int(radius), 0, + half_short_side(self->width, self->height), MP_QSTR_radius); + common_hal_vectorio_rectangle_set_radius(self, new_radius); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(vectorio_rectangle_set_radius_obj, vectorio_rectangle_obj_set_radius); + +MP_PROPERTY_GETSET(vectorio_rectangle_radius_obj, + (mp_obj_t)&vectorio_rectangle_get_radius_obj, + (mp_obj_t)&vectorio_rectangle_set_radius_obj); + +//| outline_width: int +//| """The width of the border in pixels. The border is drawn inside the rectangle, so it +//| never changes the rectangle's size. 0 draws no border. The width must not exceed half +//| of the shortest side.""" +static mp_obj_t vectorio_rectangle_obj_get_outline_width(mp_obj_t self_in) { + vectorio_rectangle_t *self = native_rectangle(self_in); + return mp_obj_new_int(common_hal_vectorio_rectangle_get_outline_width(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(vectorio_rectangle_get_outline_width_obj, vectorio_rectangle_obj_get_outline_width); + +static mp_obj_t vectorio_rectangle_obj_set_outline_width(mp_obj_t self_in, mp_obj_t outline_width) { + vectorio_rectangle_t *self = native_rectangle(self_in); + mp_int_t new_outline_width = mp_arg_validate_int_range(mp_obj_get_int(outline_width), 0, + half_short_side(self->width, self->height), MP_QSTR_outline_width); + common_hal_vectorio_rectangle_set_outline_width(self, new_outline_width); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(vectorio_rectangle_set_outline_width_obj, vectorio_rectangle_obj_set_outline_width); + +MP_PROPERTY_GETSET(vectorio_rectangle_outline_width_obj, + (mp_obj_t)&vectorio_rectangle_get_outline_width_obj, + (mp_obj_t)&vectorio_rectangle_set_outline_width_obj); + +//| outline_color_index: Optional[int] +//| """The 0 based palette index of the border color, or ``None`` for no border. Only used +//| when :py:attr:`outline_width` is greater than 0.""" +static mp_obj_t vectorio_rectangle_obj_get_outline_color_index(mp_obj_t self_in) { + vectorio_rectangle_t *self = native_rectangle(self_in); + return outline_color_index_to_obj(common_hal_vectorio_rectangle_get_outline_color_index(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(vectorio_rectangle_get_outline_color_index_obj, vectorio_rectangle_obj_get_outline_color_index); + +static mp_obj_t vectorio_rectangle_obj_set_outline_color_index(mp_obj_t self_in, mp_obj_t outline_color_index) { + vectorio_rectangle_t *self = native_rectangle(self_in); + common_hal_vectorio_rectangle_set_outline_color_index(self, + parse_outline_color_index(outline_color_index)); + return mp_const_none; +} +MP_DEFINE_CONST_FUN_OBJ_2(vectorio_rectangle_set_outline_color_index_obj, vectorio_rectangle_obj_set_outline_color_index); + +MP_PROPERTY_GETSET(vectorio_rectangle_outline_color_index_obj, + (mp_obj_t)&vectorio_rectangle_get_outline_color_index_obj, + (mp_obj_t)&vectorio_rectangle_set_outline_color_index_obj); + //| color_index: int //| """The color_index of the rectangle in 1 based index of the palette.""" static mp_obj_t vectorio_rectangle_obj_get_color_index(mp_obj_t self_in) { - vectorio_rectangle_t *self = MP_OBJ_TO_PTR(self_in); + vectorio_rectangle_t *self = native_rectangle(self_in); return mp_obj_new_int(common_hal_vectorio_rectangle_get_color_index(self)); } MP_DEFINE_CONST_FUN_OBJ_1(vectorio_rectangle_get_color_index_obj, vectorio_rectangle_obj_get_color_index); static mp_obj_t vectorio_rectangle_obj_set_color_index(mp_obj_t self_in, mp_obj_t color_index) { - vectorio_rectangle_t *self = MP_OBJ_TO_PTR(self_in); + vectorio_rectangle_t *self = native_rectangle(self_in); common_hal_vectorio_rectangle_set_color_index(self, mp_obj_get_int(color_index)); return mp_const_none; } @@ -157,6 +303,9 @@ static const mp_rom_map_elem_t vectorio_rectangle_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_color_index), MP_ROM_PTR(&vectorio_rectangle_color_index_obj) }, { MP_ROM_QSTR(MP_QSTR_width), MP_ROM_PTR(&vectorio_rectangle_width_obj) }, { MP_ROM_QSTR(MP_QSTR_height), MP_ROM_PTR(&vectorio_rectangle_height_obj) }, + { MP_ROM_QSTR(MP_QSTR_radius), MP_ROM_PTR(&vectorio_rectangle_radius_obj) }, + { MP_ROM_QSTR(MP_QSTR_outline_width), MP_ROM_PTR(&vectorio_rectangle_outline_width_obj) }, + { MP_ROM_QSTR(MP_QSTR_outline_color_index), MP_ROM_PTR(&vectorio_rectangle_outline_color_index_obj) }, { MP_ROM_QSTR(MP_QSTR_location), MP_ROM_PTR(&vectorio_vector_shape_location_obj) }, { MP_ROM_QSTR(MP_QSTR_pixel_shader), MP_ROM_PTR(&vectorio_vector_shape_pixel_shader_obj) }, }; @@ -168,5 +317,5 @@ MP_DEFINE_CONST_OBJ_TYPE( MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, make_new, vectorio_rectangle_make_new, locals_dict, &vectorio_rectangle_locals_dict, - protocol, &rectangle_draw_protocol + protocol, VECTORIO_RECTANGLE_PROTOCOL ); diff --git a/shared-bindings/vectorio/Rectangle.h b/shared-bindings/vectorio/Rectangle.h index 6831fa21029..dee771c38e8 100644 --- a/shared-bindings/vectorio/Rectangle.h +++ b/shared-bindings/vectorio/Rectangle.h @@ -12,7 +12,7 @@ extern const mp_obj_type_t vectorio_rectangle_type; -void common_hal_vectorio_rectangle_construct(vectorio_rectangle_t *self, uint32_t width, uint32_t height, uint16_t color_index); +void common_hal_vectorio_rectangle_construct(vectorio_rectangle_t *self, uint32_t width, uint32_t height, uint16_t color_index, uint16_t radius, uint16_t outline_width, int32_t outline_color_index); void common_hal_vectorio_rectangle_set_on_dirty(vectorio_rectangle_t *self, vectorio_event_t on_dirty); uint32_t common_hal_vectorio_rectangle_get_pixel(void *rectangle, int16_t x, int16_t y); @@ -29,3 +29,13 @@ void common_hal_vectorio_rectangle_set_color_index(void *obj, uint16_t color_ind int16_t common_hal_vectorio_rectangle_get_height(void *obj); void common_hal_vectorio_rectangle_set_height(void *obj, int16_t height); + +uint16_t common_hal_vectorio_rectangle_get_radius(void *obj); +void common_hal_vectorio_rectangle_set_radius(void *obj, uint16_t radius); + +uint16_t common_hal_vectorio_rectangle_get_outline_width(void *obj); +void common_hal_vectorio_rectangle_set_outline_width(void *obj, uint16_t outline_width); + +// -1 means no outline color was set. +int32_t common_hal_vectorio_rectangle_get_outline_color_index(void *obj); +void common_hal_vectorio_rectangle_set_outline_color_index(void *obj, int32_t outline_color_index); diff --git a/shared-bindings/vectorio/VectorShape.c b/shared-bindings/vectorio/VectorShape.c index 041600bff4e..c6e2949840a 100644 --- a/shared-bindings/vectorio/VectorShape.c +++ b/shared-bindings/vectorio/VectorShape.c @@ -22,6 +22,31 @@ #include "py/objtype.h" #include "py/runtime.h" +#if CIRCUITPY_DISPLAYIO_LVGL +#include "shared-module/displayio/lvgl/lvgl_protocol.h" +#endif + +// The VectorShape wrapper behind a Python-visible shape (Rectangle, Circle or Polygon). A +// shape's compositor state lives in the wrapper, so the properties below are defined on it +// and reach it through the shape's protocol slot: protocol_lvgl's protocol_self() in LVGL +// builds, the draw protocol's draw_get_protocol_self() in legacy builds. +static vectorio_vector_shape_t *_wrapper_shape(mp_obj_t wrapper_shape) { + #if CIRCUITPY_DISPLAYIO_LVGL + const lvgl_protocol_t *protocol = mp_proto_get(MP_QSTR_protocol_lvgl, wrapper_shape); + if (protocol == NULL || protocol->protocol_self == NULL) { + return NULL; + } + return MP_OBJ_TO_PTR(protocol->protocol_self(wrapper_shape)); + #else + const vectorio_draw_protocol_t *draw_protocol = mp_proto_get(MP_QSTR_protocol_draw, + wrapper_shape); + if (draw_protocol == NULL) { + return NULL; + } + return MP_OBJ_TO_PTR(draw_protocol->draw_get_protocol_self(wrapper_shape)); + #endif +} + // shape: The shape implementation to draw. // pixel_shader: The pixel shader that produces colors from values. The shader can be a displayio.Palette(1); it will be asked to color pixel value 0. @@ -37,15 +62,21 @@ mp_obj_t vectorio_vector_shape_make_new(const mp_obj_t shape, const mp_obj_t pix // Wire up shape functions if (mp_obj_is_type(shape, &vectorio_polygon_type)) { ishape.shape = shape; + #if !CIRCUITPY_DISPLAYIO_LVGL ishape.get_area = &common_hal_vectorio_polygon_get_area; + #endif ishape.get_pixel = &common_hal_vectorio_polygon_get_pixel; } else if (mp_obj_is_type(shape, &vectorio_rectangle_type)) { ishape.shape = shape; + #if !CIRCUITPY_DISPLAYIO_LVGL ishape.get_area = &common_hal_vectorio_rectangle_get_area; + #endif ishape.get_pixel = &common_hal_vectorio_rectangle_get_pixel; } else if (mp_obj_is_type(shape, &vectorio_circle_type)) { ishape.shape = shape; + #if !CIRCUITPY_DISPLAYIO_LVGL ishape.get_area = &common_hal_vectorio_circle_get_area; + #endif ishape.get_pixel = &common_hal_vectorio_circle_get_pixel; } else { mp_raise_TypeError_varg(MP_ERROR_TEXT("unsupported %q type"), MP_QSTR_shape); @@ -69,19 +100,24 @@ mp_obj_t vectorio_vector_shape_make_new(const mp_obj_t shape, const mp_obj_t pix } else if (mp_obj_is_type(shape, &vectorio_circle_type)) { common_hal_vectorio_circle_set_on_dirty(self->ishape.shape, on_dirty); } else { - mp_raise_TypeError_varg(MP_ERROR_TEXT("unsupported %q type"), MP_QSTR_shape); + // Already excluded due to previous else-if chain. } return MP_OBJ_FROM_PTR(self); } vectorio_draw_protocol_impl_t vectorio_vector_shape_draw_protocol_impl = { + .draw_set_dirty = (draw_set_dirty_fun)common_hal_vectorio_vector_shape_set_dirty, + .draw_set_in_group = (draw_set_in_group_fun)vectorio_vector_shape_set_in_group, + #if !CIRCUITPY_DISPLAYIO_LVGL + // The scanline compositor asks shapes to fill spans and to track dirty areas. LVGL + // draws and invalidates the shape's mirror object instead, so none of this exists. .draw_fill_area = (draw_fill_area_fun)vectorio_vector_shape_fill_area, .draw_get_dirty_area = (draw_get_dirty_area_fun)vectorio_vector_shape_get_dirty_area, .draw_update_transform = (draw_update_transform_fun)vectorio_vector_shape_update_transform, .draw_finish_refresh = (draw_finish_refresh_fun)vectorio_vector_shape_finish_refresh, .draw_get_refresh_areas = (draw_get_refresh_areas_fun)vectorio_vector_shape_get_refresh_areas, - .draw_set_dirty = (draw_set_dirty_fun)common_hal_vectorio_vector_shape_set_dirty, + #endif }; // Stub checker does not approve of these shared properties. @@ -90,9 +126,7 @@ vectorio_draw_protocol_impl_t vectorio_vector_shape_draw_protocol_impl = { // """true if x,y lies inside the shape.""" // static mp_obj_t vectorio_vector_shape_obj_contains(mp_obj_t wrapper_shape, mp_obj_t x_obj, mp_obj_t y_obj) { - // Relies on the fact that only vector_shape impl gets matched with a VectorShape. - const vectorio_draw_protocol_t *draw_protocol = mp_proto_get(MP_QSTR_protocol_draw, wrapper_shape); - vectorio_vector_shape_t *self = MP_OBJ_TO_PTR(draw_protocol->draw_get_protocol_self(wrapper_shape)); + vectorio_vector_shape_t *self = _wrapper_shape(wrapper_shape); mp_int_t x = mp_obj_get_int(x_obj); mp_int_t y = mp_obj_get_int(y_obj); @@ -105,18 +139,14 @@ MP_DEFINE_CONST_FUN_OBJ_3(vectorio_vector_shape_contains_obj, vectorio_vector_sh // """X position of the center point of the shape in the parent.""" // static mp_obj_t vectorio_vector_shape_obj_get_x(mp_obj_t wrapper_shape) { - // Relies on the fact that only vector_shape impl gets matched with a VectorShape. - const vectorio_draw_protocol_t *draw_protocol = mp_proto_get(MP_QSTR_protocol_draw, wrapper_shape); - vectorio_vector_shape_t *self = MP_OBJ_TO_PTR(draw_protocol->draw_get_protocol_self(wrapper_shape)); + vectorio_vector_shape_t *self = _wrapper_shape(wrapper_shape); return MP_OBJ_NEW_SMALL_INT(common_hal_vectorio_vector_shape_get_x(self)); } MP_DEFINE_CONST_FUN_OBJ_1(vectorio_vector_shape_get_x_obj, vectorio_vector_shape_obj_get_x); static mp_obj_t vectorio_vector_shape_obj_set_x(mp_obj_t wrapper_shape, mp_obj_t x_obj) { - // Relies on the fact that only vector_shape impl gets matched with a VectorShape. - const vectorio_draw_protocol_t *draw_protocol = mp_proto_get(MP_QSTR_protocol_draw, wrapper_shape); - vectorio_vector_shape_t *self = MP_OBJ_TO_PTR(draw_protocol->draw_get_protocol_self(wrapper_shape)); + vectorio_vector_shape_t *self = _wrapper_shape(wrapper_shape); mp_int_t x = mp_obj_get_int(x_obj); common_hal_vectorio_vector_shape_set_x(self, x); @@ -133,18 +163,14 @@ MP_PROPERTY_GETSET(vectorio_vector_shape_x_obj, // """Y position of the center point of the shape in the parent.""" // static mp_obj_t vectorio_vector_shape_obj_get_y(mp_obj_t wrapper_shape) { - // Relies on the fact that only vector_shape impl gets matched with a VectorShape. - const vectorio_draw_protocol_t *draw_protocol = mp_proto_get(MP_QSTR_protocol_draw, wrapper_shape); - vectorio_vector_shape_t *self = MP_OBJ_TO_PTR(draw_protocol->draw_get_protocol_self(wrapper_shape)); + vectorio_vector_shape_t *self = _wrapper_shape(wrapper_shape); return MP_OBJ_NEW_SMALL_INT(common_hal_vectorio_vector_shape_get_y(self)); } MP_DEFINE_CONST_FUN_OBJ_1(vectorio_vector_shape_get_y_obj, vectorio_vector_shape_obj_get_y); static mp_obj_t vectorio_vector_shape_obj_set_y(mp_obj_t wrapper_shape, mp_obj_t y_obj) { - // Relies on the fact that only vector_shape impl gets matched with a VectorShape. - const vectorio_draw_protocol_t *draw_protocol = mp_proto_get(MP_QSTR_protocol_draw, wrapper_shape); - vectorio_vector_shape_t *self = MP_OBJ_TO_PTR(draw_protocol->draw_get_protocol_self(wrapper_shape)); + vectorio_vector_shape_t *self = _wrapper_shape(wrapper_shape); mp_int_t y = mp_obj_get_int(y_obj); common_hal_vectorio_vector_shape_set_y(self, y); @@ -161,18 +187,14 @@ MP_PROPERTY_GETSET(vectorio_vector_shape_y_obj, // """location of the center point of the shape in the parent.""" // static mp_obj_t vectorio_vector_shape_obj_get_location(mp_obj_t wrapper_shape) { - // Relies on the fact that only vector_shape impl gets matched with a VectorShape. - const vectorio_draw_protocol_t *draw_protocol = mp_proto_get(MP_QSTR_protocol_draw, wrapper_shape); - vectorio_vector_shape_t *self = MP_OBJ_TO_PTR(draw_protocol->draw_get_protocol_self(wrapper_shape)); + vectorio_vector_shape_t *self = _wrapper_shape(wrapper_shape); return MP_OBJ_TO_PTR(common_hal_vectorio_vector_shape_get_location(self)); } MP_DEFINE_CONST_FUN_OBJ_1(vectorio_vector_shape_get_location_obj, vectorio_vector_shape_obj_get_location); static mp_obj_t vectorio_vector_shape_obj_set_location(mp_obj_t wrapper_shape, mp_obj_t location_obj) { - // Relies on the fact that only vector_shape impl gets matched with a VectorShape. - const vectorio_draw_protocol_t *draw_protocol = mp_proto_get(MP_QSTR_protocol_draw, wrapper_shape); - vectorio_vector_shape_t *self = MP_OBJ_TO_PTR(draw_protocol->draw_get_protocol_self(wrapper_shape)); + vectorio_vector_shape_t *self = _wrapper_shape(wrapper_shape); common_hal_vectorio_vector_shape_set_location(self, location_obj); return mp_const_none; @@ -189,17 +211,13 @@ MP_PROPERTY_GETSET(vectorio_vector_shape_location_obj, // """Hide the shape or not.""" // static mp_obj_t vectorio_vector_shape_obj_get_hidden(mp_obj_t wrapper_shape) { - // Relies on the fact that only vector_shape impl gets matched with a VectorShape. - const vectorio_draw_protocol_t *draw_protocol = mp_proto_get(MP_QSTR_protocol_draw, wrapper_shape); - vectorio_vector_shape_t *self = MP_OBJ_TO_PTR(draw_protocol->draw_get_protocol_self(wrapper_shape)); + vectorio_vector_shape_t *self = _wrapper_shape(wrapper_shape); return mp_obj_new_bool(common_hal_vectorio_vector_shape_get_hidden(self)); } MP_DEFINE_CONST_FUN_OBJ_1(vectorio_vector_shape_get_hidden_obj, vectorio_vector_shape_obj_get_hidden); static mp_obj_t vectorio_vector_shape_obj_set_hidden(mp_obj_t wrapper_shape, mp_obj_t hidden_obj) { - // Relies on the fact that only vector_shape impl gets matched with a VectorShape. - const vectorio_draw_protocol_t *draw_protocol = mp_proto_get(MP_QSTR_protocol_draw, wrapper_shape); - vectorio_vector_shape_t *self = MP_OBJ_TO_PTR(draw_protocol->draw_get_protocol_self(wrapper_shape)); + vectorio_vector_shape_t *self = _wrapper_shape(wrapper_shape); common_hal_vectorio_vector_shape_set_hidden(self, mp_obj_is_true(hidden_obj)); return mp_const_none; @@ -215,18 +233,14 @@ MP_PROPERTY_GETSET(vectorio_vector_shape_hidden_obj, // """The pixel shader of the shape.""" // static mp_obj_t vectorio_vector_shape_obj_get_pixel_shader(mp_obj_t wrapper_shape) { - // Relies on the fact that only vector_shape impl gets matched with a VectorShape. - const vectorio_draw_protocol_t *draw_protocol = mp_proto_get(MP_QSTR_protocol_draw, wrapper_shape); - vectorio_vector_shape_t *self = MP_OBJ_TO_PTR(draw_protocol->draw_get_protocol_self(wrapper_shape)); + vectorio_vector_shape_t *self = _wrapper_shape(wrapper_shape); return common_hal_vectorio_vector_shape_get_pixel_shader(self); } MP_DEFINE_CONST_FUN_OBJ_1(vectorio_vector_shape_get_pixel_shader_obj, vectorio_vector_shape_obj_get_pixel_shader); static mp_obj_t vectorio_vector_shape_obj_set_pixel_shader(mp_obj_t wrapper_shape, mp_obj_t pixel_shader) { - // Relies on the fact that only vector_shape impl gets matched with a VectorShape. - const vectorio_draw_protocol_t *draw_protocol = mp_proto_get(MP_QSTR_protocol_draw, wrapper_shape); - vectorio_vector_shape_t *self = MP_OBJ_TO_PTR(draw_protocol->draw_get_protocol_self(wrapper_shape)); + vectorio_vector_shape_t *self = _wrapper_shape(wrapper_shape); if (!mp_obj_is_type(pixel_shader, &displayio_palette_type) && !mp_obj_is_type(pixel_shader, &displayio_colorconverter_type)) { mp_raise_TypeError_varg(MP_ERROR_TEXT("unsupported %q type"), MP_QSTR_pixel_shader); @@ -251,5 +265,6 @@ MP_DEFINE_CONST_OBJ_TYPE( vectorio_vector_shape_type, MP_QSTR_VectorShape, MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, - locals_dict, &vectorio_vector_shape_locals_dict + locals_dict, &vectorio_vector_shape_locals_dict, + protocol, VECTORIO_VECTOR_SHAPE_LVGL_PROTOCOL ); diff --git a/shared-bindings/vectorio/VectorShape.h b/shared-bindings/vectorio/VectorShape.h index 9e06a0c146e..7924eb07ba2 100644 --- a/shared-bindings/vectorio/VectorShape.h +++ b/shared-bindings/vectorio/VectorShape.h @@ -43,6 +43,7 @@ mp_obj_t common_hal_vectorio_vector_shape_get_pixel_shader(vectorio_vector_shape void common_hal_vectorio_vector_shape_set_pixel_shader(vectorio_vector_shape_t *self, mp_obj_t pixel_shader); void vectorio_vector_shape_update_transform(vectorio_vector_shape_t *self, displayio_buffer_transform_t *group_transform); +bool vectorio_vector_shape_set_in_group(vectorio_vector_shape_t *self, bool in_group); // Composable property definition for shapes that use VectorShape extern vectorio_draw_protocol_impl_t vectorio_vector_shape_draw_protocol_impl; diff --git a/shared-bindings/vectorio/__init__.h b/shared-bindings/vectorio/__init__.h index c982f63815b..cc9b523ecb1 100644 --- a/shared-bindings/vectorio/__init__.h +++ b/shared-bindings/vectorio/__init__.h @@ -23,6 +23,10 @@ typedef bool (*draw_get_dirty_area_fun)(mp_obj_t draw_protocol_self, displayio_a typedef void (*draw_update_transform_fun)(mp_obj_t draw_protocol_self, displayio_buffer_transform_t *group_transform); typedef void (*draw_finish_refresh_fun)(mp_obj_t draw_protocol_self); typedef void (*draw_set_dirty_fun)(mp_obj_t draw_protocol_self); +// Optional: propagate a group's hidden state to the layer. May be NULL; the +// group then falls back to draw_set_dirty. +typedef void (*draw_set_hidden_fun)(mp_obj_t draw_protocol_self, bool hidden); +typedef bool (*draw_set_in_group_fun)(mp_obj_t draw_protocol_self, bool in_group); typedef displayio_area_t *(*draw_get_refresh_areas_fun)(mp_obj_t draw_protocol_self, displayio_area_t *tail); typedef struct _vectorio_draw_protocol_impl_t { @@ -32,6 +36,9 @@ typedef struct _vectorio_draw_protocol_impl_t { draw_finish_refresh_fun draw_finish_refresh; draw_get_refresh_areas_fun draw_get_refresh_areas; draw_set_dirty_fun draw_set_dirty; + // May be NULL. + draw_set_hidden_fun draw_set_hidden; + draw_set_in_group_fun draw_set_in_group; } vectorio_draw_protocol_impl_t; // Draw protocol diff --git a/shared-bindings/videocore/VideoBuffer.c b/shared-bindings/videocore/VideoBuffer.c new file mode 100644 index 00000000000..08eb830982c --- /dev/null +++ b/shared-bindings/videocore/VideoBuffer.c @@ -0,0 +1,281 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "py/obj.h" +#include "py/objproperty.h" +#include "py/runtime.h" + +#include "shared-bindings/displayio/__init__.h" +#include "shared-bindings/videocore/VideoBuffer.h" +#include "shared-bindings/util.h" +#include "shared/runtime/context_manager_helpers.h" + +//| class VideoBuffer: +//| """Stream a video source into a framebuffer or buffer. +//| +//| A VideoBuffer connects a video source, such as `mipicsi.Camera`, to a +//| target: either a framebuffer, such as `mipidsi.Display`, or a writable +//| buffer such as a ``bytearray``. It is the video counterpart of +//| `audioio.AudioOut`. +//| +//| Add a VideoBuffer to a `displayio.Group` to show it on a display. A +//| framebuffer target only streams while it is shown. +//| +//| Displayio composites the video with the other layers in its Group. On +//| displays that use the LVGL compositor (for example ESP32-P4), LVGL +//| samples the target buffer directly, so no copy is made per frame and +//| widgets can be drawn over a live framebuffer target. On the original +//| scanline compositor a plain buffer is copied into the display instead, +//| and its pixel format must match the display exactly. +//| +//| Implementations may restrict size and position. For example, on +//| ESP32-P4 a framebuffer target must be full width because the DMA can't +//| skip between rows without an intermediate buffer. Setting an +//| unsupported position directly raises an error, but moving a containing +//| Group may give garbled output instead. +//| +//| A framebuffer target is only shown on the display that wraps that +//| framebuffer, and only while that display is unrotated. Assigning a +//| Group that contains one as a rotated display's ``root_group`` raises +//| `ValueError`. +//| +//| When the target is a plain buffer, frames are written with no gap +//| between rows, so each row takes ``width * 2`` bytes for +//| `displayio.Colorspace.RGB565` and ``(width + 7) // 8`` bytes for +//| `displayio.Colorspace.L1`, where each row is padded out to a whole +//| byte. Python code can read the buffer at any time, for example to +//| process or save camera pixels. +//| A Group shows a plain buffer target only when its pixels are 16 bits +//| and the display uses 16-bit color, or its pixels are 1 bit and the +//| display is monochrome with the leftmost pixel in the top bit of each +//| byte, such as `epaperdisplay.EPaperDisplay`. A 1 bit means white. +//| On a tricolor display with separate black and color RAM, a 1 bit video +//| only draws black and white, and a highlight colored layer below it shows +//| through. Other tricolor displays don't draw it. +//| A framebuffer target may use 16, 24 or 32 bits per pixel with the LVGL +//| compositor; the scanline compositor only supports 16-bit pixels. +//| +//| See the `videocore` module overview for complete examples. +//| """ +//| +//| def __init__( +//| self, +//| framebuffer: Union[ +//| circuitpython_typing.FrameBuffer, circuitpython_typing.WriteableBuffer +//| ], +//| *, +//| colorspace: displayio.Colorspace = displayio.Colorspace.RGB565, +//| ) -> None: +//| """Create a VideoBuffer that plays video into the given framebuffer +//| +//| :param framebuffer: The framebuffer to copy video frames into, or a +//| writable buffer such as a ``bytearray`` or ``memoryview``. +//| :param displayio.Colorspace colorspace: The pixel format of a writable +//| buffer: `displayio.Colorspace.RGB565` for color, or +//| `displayio.Colorspace.L1` for black and white. Other colorspaces +//| raise `ValueError`. A framebuffer uses its own color depth instead. +//| """ +//| +static mp_obj_t videocore_videobuffer_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_framebuffer, ARG_colorspace, NUM_ARGS }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_framebuffer, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_colorspace, MP_ARG_OBJ | MP_ARG_KW_ONLY, {.u_obj = (void *)&displayio_colorspace_RGB565_obj} }, + }; + + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + MP_STATIC_ASSERT(MP_ARRAY_SIZE(allowed_args) == NUM_ARGS); + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + const displayio_colorspace_t colorspace = + (displayio_colorspace_t)cp_enum_value(&displayio_colorspace_type, args[ARG_colorspace].u_obj, MP_QSTR_colorspace); + mp_int_t bits_per_pixel; + switch (colorspace) { + case DISPLAYIO_COLORSPACE_RGB565: + bits_per_pixel = 16; + break; + case DISPLAYIO_COLORSPACE_L1: + bits_per_pixel = 1; + break; + default: + mp_arg_error_invalid(MP_QSTR_colorspace); + } + + videocore_videobuffer_obj_t *self = mp_obj_malloc_with_finaliser(videocore_videobuffer_obj_t, &videocore_videobuffer_type); + common_hal_videocore_videobuffer_construct(self, args[ARG_framebuffer].u_obj, bits_per_pixel); + return MP_OBJ_FROM_PTR(self); +} + +//| def play(self, source: circuitpython_typing.VideoSource) -> None: +//| """Begin streaming the given video source into the target. +//| +//| The source streams continuously, writing each new frame where the +//| VideoBuffer tells it to, replacing the previous one. The source can +//| use 1 bit per pixel, or a whole number of bytes per pixel. +//| The source's size and format are then fixed for the duration of the +//| ``play()``; sources that change them require ``stop()`` and a new +//| ``play()``. +//| +//| When the target is a framebuffer, its bits per pixel must match the +//| source and be a whole number of bytes, and the whole frame must fit +//| within the framebuffer at the current ``x``/``y`` position. An +//| exception may be raised if the video can't be played directly into +//| the framebuffer. +//| +//| When the target is a plain buffer, it must be large enough for a +//| whole frame. The LVGL compositor samples the buffer, so it must be +//| 16, 24 or 32 bits per pixel there. +//| +//| :param ~circuitpython_typing.VideoSource source: The video source to +//| play, such as `mipicsi.Camera` or `videogif.GifDecoder` +//| """ +//| +static mp_obj_t videocore_videobuffer_play(mp_obj_t self_in, mp_obj_t source) { + videocore_videobuffer_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_videocore_videobuffer_play(self, source); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(videocore_videobuffer_play_obj, videocore_videobuffer_play); + +//| def stop(self) -> None: +//| """Stop playing the video source.""" +//| ... +//| +static mp_obj_t videocore_videobuffer_stop(mp_obj_t self_in) { + videocore_videobuffer_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_videocore_videobuffer_stop(self); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(videocore_videobuffer_stop_obj, videocore_videobuffer_stop); + +//| playing: bool +//| """True when a video source is being played, False otherwise. It also +//| becomes False when the source has no more frames, such as a GIF that +//| has finished its last loop. The last frame then stays shown until +//| ``stop()`` or the next ``play()``. A framebuffer target also drops it +//| when moved or hidden. (read-only)""" +//| +static mp_obj_t videocore_videobuffer_get_playing(mp_obj_t self_in) { + videocore_videobuffer_obj_t *self = MP_OBJ_TO_PTR(self_in); + return mp_obj_new_bool(common_hal_videocore_videobuffer_get_playing(self)); +} +static MP_DEFINE_CONST_FUN_OBJ_1(videocore_videobuffer_get_playing_obj, videocore_videobuffer_get_playing); +MP_PROPERTY_GETTER(videocore_videobuffer_playing_obj, + (mp_obj_t)&videocore_videobuffer_get_playing_obj); + +//| source: Optional[circuitpython_typing.VideoSource] +//| """The video source being played, or None when not playing. (read-only)""" +//| +static mp_obj_t videocore_videobuffer_get_source(mp_obj_t self_in) { + videocore_videobuffer_obj_t *self = MP_OBJ_TO_PTR(self_in); + return common_hal_videocore_videobuffer_get_source(self); +} +static MP_DEFINE_CONST_FUN_OBJ_1(videocore_videobuffer_get_source_obj, videocore_videobuffer_get_source); +MP_PROPERTY_GETTER(videocore_videobuffer_source_obj, + (mp_obj_t)&videocore_videobuffer_get_source_obj); + +//| x: int +//| """The x position of the video within its Group. Framebuffer targets +//| only support ``x == 0`` and raise `ValueError` otherwise.""" +//| +//| y: int +//| """The y position of the video within its Group.""" +//| +//| +static void videocore_videobuffer_get_position(mp_obj_t self_in, mp_int_t *x, mp_int_t *y) { + videocore_videobuffer_obj_t *self = MP_OBJ_TO_PTR(self_in); + *x = self->x; + *y = self->y; +} + +static mp_obj_t videocore_videobuffer_get_x(mp_obj_t self_in) { + mp_int_t x, y; + videocore_videobuffer_get_position(self_in, &x, &y); + return MP_OBJ_NEW_SMALL_INT(x); +} +static MP_DEFINE_CONST_FUN_OBJ_1(videocore_videobuffer_get_x_obj, videocore_videobuffer_get_x); + +static mp_obj_t videocore_videobuffer_set_x(mp_obj_t self_in, mp_obj_t value) { + videocore_videobuffer_obj_t *self = MP_OBJ_TO_PTR(self_in); + mp_int_t x = mp_obj_get_int(value); + common_hal_videocore_videobuffer_set_position(self, x, self->y); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(videocore_videobuffer_set_x_obj, videocore_videobuffer_set_x); +MP_PROPERTY_GETSET(videocore_videobuffer_x_obj, + (mp_obj_t)&videocore_videobuffer_get_x_obj, + (mp_obj_t)&videocore_videobuffer_set_x_obj); + +static mp_obj_t videocore_videobuffer_get_y(mp_obj_t self_in) { + mp_int_t x, y; + videocore_videobuffer_get_position(self_in, &x, &y); + return MP_OBJ_NEW_SMALL_INT(y); +} +static MP_DEFINE_CONST_FUN_OBJ_1(videocore_videobuffer_get_y_obj, videocore_videobuffer_get_y); + +static mp_obj_t videocore_videobuffer_set_y(mp_obj_t self_in, mp_obj_t value) { + videocore_videobuffer_obj_t *self = MP_OBJ_TO_PTR(self_in); + mp_int_t y = mp_obj_get_int(value); + common_hal_videocore_videobuffer_set_position(self, self->x, y); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_2(videocore_videobuffer_set_y_obj, videocore_videobuffer_set_y); +MP_PROPERTY_GETSET(videocore_videobuffer_y_obj, + (mp_obj_t)&videocore_videobuffer_get_y_obj, + (mp_obj_t)&videocore_videobuffer_set_y_obj); + +//| def deinit(self) -> None: +//| """Stop playing and stop the video source.""" +//| ... +//| +//| def __enter__(self) -> VideoBuffer: +//| """No-op used by Context Managers.""" +//| ... +//| +//| def __exit__(self) -> None: +//| """Automatically deinitializes the hardware when exiting a context. See +//| :ref:`lifetime-and-contextmanagers` for more info.""" +//| ... +//| +static mp_obj_t videocore_videobuffer_deinit(mp_obj_t self_in) { + videocore_videobuffer_obj_t *self = MP_OBJ_TO_PTR(self_in); + common_hal_videocore_videobuffer_stop(self); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(videocore_videobuffer_deinit_obj, videocore_videobuffer_deinit); + +// The finaliser runs during garbage collection and must not raise, so use +// the quiet stop instead of deinit(). +static mp_obj_t videocore_videobuffer___del__(mp_obj_t self_in) { + videocore_videobuffer_obj_t *self = MP_OBJ_TO_PTR(self_in); + videocore_videobuffer_stop_quiet(self); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(videocore_videobuffer___del___obj, videocore_videobuffer___del__); + +static const mp_rom_map_elem_t videocore_videobuffer_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&videocore_videobuffer___del___obj) }, + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&videocore_videobuffer_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR_play), MP_ROM_PTR(&videocore_videobuffer_play_obj) }, + { MP_ROM_QSTR(MP_QSTR_stop), MP_ROM_PTR(&videocore_videobuffer_stop_obj) }, + { MP_ROM_QSTR(MP_QSTR_playing), MP_ROM_PTR(&videocore_videobuffer_playing_obj) }, + { MP_ROM_QSTR(MP_QSTR_source), MP_ROM_PTR(&videocore_videobuffer_source_obj) }, + { MP_ROM_QSTR(MP_QSTR_x), MP_ROM_PTR(&videocore_videobuffer_x_obj) }, + { MP_ROM_QSTR(MP_QSTR_y), MP_ROM_PTR(&videocore_videobuffer_y_obj) }, +}; + +static MP_DEFINE_CONST_DICT(videocore_videobuffer_locals_dict, videocore_videobuffer_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + videocore_videobuffer_type, + MP_QSTR_VideoBuffer, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, videocore_videobuffer_make_new, + locals_dict, &videocore_videobuffer_locals_dict, + protocol, VIDEOCORE_VIDEOBUFFER_PROTOCOL + ); diff --git a/shared-bindings/videocore/VideoBuffer.h b/shared-bindings/videocore/VideoBuffer.h new file mode 100644 index 00000000000..927169bc4b3 --- /dev/null +++ b/shared-bindings/videocore/VideoBuffer.h @@ -0,0 +1,11 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-module/videocore/VideoBuffer.h" + +extern const mp_obj_type_t videocore_videobuffer_type; diff --git a/shared-bindings/videocore/__init__.c b/shared-bindings/videocore/__init__.c new file mode 100644 index 00000000000..2de780cc3da --- /dev/null +++ b/shared-bindings/videocore/__init__.c @@ -0,0 +1,92 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "py/obj.h" +#include "py/runtime.h" + +#include "shared-bindings/videocore/VideoBuffer.h" +#include "shared-bindings/videocore/__init__.h" + +//| """Support for playing video sources +//| +//| This module provides the video pipeline shared between video sources and +//| video outputs. It is the video equivalent of the `audiocore` module. +//| +//| A video source, such as `mipicsi.Camera` or `videogif.GifDecoder`, makes +//| video frames. A `VideoBuffer` plays a video source and tells it where to +//| put each frame: in a display's memory, such as `mipidsi.Display`, or in a +//| ``bytearray`` that a displayio Group shows. +//| +//| Stream a MIPI CSI camera live into the board's display (a MIPI DSI panel +//| on ESP32-P4-Function-EV, for example): +//| +//| .. code-block:: python +//| +//| import board +//| import displayio +//| import mipicsi +//| import sc2336 +//| import videocore +//| +//| display = board.DISPLAY() +//| framebuffer = display.framebuffer +//| sensor = sc2336.SC2336(board.I2C()) +//| sensor.mode = sc2336.Mode.HD_1280x720_RAW10_30FPS +//| # Trim the sensor output to the display size. +//| sensor.width = display.width +//| sensor.height = display.height +//| camera = mipicsi.Camera(sensor, output_format=mipicsi.PixelFormat.RGB565) +//| +//| video = videocore.VideoBuffer(framebuffer) +//| video.play(camera) +//| root = displayio.Group() +//| root.append(video) +//| display.root_group = root +//| +//| Capture a smaller part of the sensor's image into a `bytearray` and let +//| displayio place it in a Group, together with other layers. The scanline +//| compositor bulk copies new frames into the group's area of the display (no +//| color conversion); the LVGL compositor samples the buffer directly: +//| +//| .. code-block:: python +//| +//| import board +//| import displayio +//| import mipicsi +//| import sc2336 +//| import videocore +//| +//| sensor = sc2336.SC2336(board.I2C()) +//| sensor.mode = sc2336.Mode.VGA_640x480_RAW10_50FPS +//| # Trim the sensor output to a 320x240 window. +//| sensor.width = 320 +//| sensor.height = 240 +//| camera = mipicsi.Camera(sensor, output_format=mipicsi.PixelFormat.RGB565) +//| +//| capture = videocore.VideoBuffer(bytearray(320 * 240 * 2)) +//| capture.play(camera) +//| +//| root = displayio.Group() +//| root.append(capture) +//| capture.x = 350 # position of the live video within the group +//| capture.y = 180 +//| board.DISPLAY().root_group = root # live video joins the displayio scene +//| """ +//| + +static const mp_rom_map_elem_t videocore_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_videocore) }, + { MP_ROM_QSTR(MP_QSTR_VideoBuffer), MP_ROM_PTR(&videocore_videobuffer_type) }, +}; + +static MP_DEFINE_CONST_DICT(videocore_module_globals, videocore_module_globals_table); + +const mp_obj_module_t videocore_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&videocore_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_videocore, videocore_module); diff --git a/shared-bindings/videocore/__init__.h b/shared-bindings/videocore/__init__.h new file mode 100644 index 00000000000..d309fcc838b --- /dev/null +++ b/shared-bindings/videocore/__init__.h @@ -0,0 +1,9 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-module/videocore/__init__.h" diff --git a/shared-bindings/videogif/GifDecoder.c b/shared-bindings/videogif/GifDecoder.c new file mode 100644 index 00000000000..11a6b882aca --- /dev/null +++ b/shared-bindings/videogif/GifDecoder.c @@ -0,0 +1,241 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mikey Sklar for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "py/builtin.h" +#include "py/obj.h" +#include "py/objproperty.h" +#include "py/runtime.h" + +#include "shared-bindings/util.h" +#include "shared-bindings/videogif/GifDecoder.h" +#include "shared/runtime/context_manager_helpers.h" + +//| class GifDecoder: +//| """Decode an animated GIF file for video playback. +//| +//| Pass a GifDecoder to ``videocore.VideoBuffer.play()`` to show the GIF +//| on a display or to write its frames into a buffer. +//| +//| Each frame is shown for the time the GIF file gives it. A few cases +//| work the same way as in web browsers: +//| +//| - A frame time of 0 or 0.01 seconds is shown for 0.1 seconds. +//| - A GIF with no loop count plays once. +//| - A loop count of 0 repeats the GIF forever. Any other loop count is +//| the number of extra times to play it, so a loop count of 2 plays the +//| GIF three times. +//| +//| When the GIF finishes its last loop, its last frame stays on the screen +//| and `videocore.VideoBuffer.playing` becomes False. The same happens if +//| a frame or the file can't be read. +//| +//| Frames are decoded in the background, in short breaks between your +//| Python code. When those breaks come late, up to 3 late frames are +//| decoded in one break to catch up. If it is still behind after that, +//| the animation slows down so your Python code still gets time to run. +//| +//| The GIF starts again from its first frame, filled with its background +//| color, at each loop. `videocore.VideoBuffer.play()` always starts it +//| from its first frame. There is no pause and resume. +//| +//| When a VideoBuffer that draws straight into a framebuffer is hidden, +//| the GIF waits and its time does not advance. When the VideoBuffer is +//| shown again or moved, the GIF stops and `videocore.VideoBuffer.playing` +//| becomes False, since the screen under it may have been drawn over. +//| Call `videocore.VideoBuffer.play()` to start it again. +//| +//| When a frame asks for its area to be cleared after it is shown (GIF +//| disposal method 2), that area is filled with the background color. +//| GIFs that ask to restore the previous image (disposal method 3) may +//| show leftover pixels, because that is not supported. +//| +//| Play a GIF in a Group on a display: +//| +//| .. code-block:: python +//| +//| import board +//| import displayio +//| import videocore +//| import videogif +//| +//| gif = videogif.GifDecoder("/animation.gif") +//| video = videocore.VideoBuffer(bytearray(gif.width * gif.height * 2)) +//| video.play(gif) +//| +//| root = displayio.Group() +//| root.append(video) +//| board.DISPLAY.root_group = root +//| while True: +//| pass +//| """ +//| +//| def __init__( +//| self, +//| filename: str, +//| ) -> None: +//| """Open a GIF file so it can be played. +//| +//| :param str filename: The name of a GIF file, such as ``"/animation.gif"``. +//| The GifDecoder closes the file when it is deinitialized. +//| +//| The `videocore.VideoBuffer` playing the GIF sets the pixel format. +//| 16-bit frames are RGB565, in the byte order of the display or +//| framebuffer that shows them. 1-bit frames pack eight pixels into +//| each byte, with the leftmost pixel in the most significant bit. A +//| pixel is white (1) when its brightness is at least 128 out of 255, +//| so a GIF that uses only black and white converts exactly. +//| +//| Raises `ValueError` if the file is not a GIF. +//| """ +//| ... +//| +static mp_obj_t videogif_gifdecoder_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *all_args) { + enum { ARG_filename, NUM_ARGS }; + static const mp_arg_t allowed_args[] = { + { MP_QSTR_filename, MP_ARG_REQUIRED | MP_ARG_OBJ }, + }; + MP_STATIC_ASSERT(MP_ARRAY_SIZE(allowed_args) == NUM_ARGS); + mp_arg_val_t args[MP_ARRAY_SIZE(allowed_args)]; + mp_arg_parse_all_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); + + mp_obj_t filename = mp_arg_validate_type_string(args[ARG_filename].u_obj, MP_QSTR_filename); + mp_obj_t file = mp_call_function_2(MP_OBJ_FROM_PTR(&mp_builtin_open_obj), filename, MP_ROM_QSTR(MP_QSTR_rb)); + + videogif_gifdecoder_obj_t *self = mp_obj_malloc_with_finaliser(videogif_gifdecoder_obj_t, &videogif_gifdecoder_type); + common_hal_videogif_gifdecoder_construct(self, file); + return MP_OBJ_FROM_PTR(self); +} + +static videogif_gifdecoder_obj_t *native_gifdecoder(mp_obj_t self_in) { + return MP_OBJ_TO_PTR(mp_obj_cast_to_native_base(self_in, &videogif_gifdecoder_type)); +} + +static void check_for_deinit(videogif_gifdecoder_obj_t *self) { + if (common_hal_videogif_gifdecoder_deinited(self)) { + raise_deinited_error(); + } +} + +//| def deinit(self) -> None: +//| """Stop playing and free the memory used to decode the GIF. The +//| GifDecoder can't be used after this.""" +//| ... +//| +static mp_obj_t videogif_gifdecoder_deinit(mp_obj_t self_in) { + common_hal_videogif_gifdecoder_deinit(native_gifdecoder(self_in)); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(videogif_gifdecoder_deinit_obj, videogif_gifdecoder_deinit); + +//| def __enter__(self) -> GifDecoder: +//| """No-op used by Context Managers.""" +//| ... +//| +//| def __exit__(self) -> None: +//| """Automatically deinitializes when exiting a context. See +//| :ref:`lifetime-and-contextmanagers` for more info.""" +//| ... +//| + +//| width: int +//| """Width of the GIF in pixels. (read-only)""" +//| +static mp_obj_t videogif_gifdecoder_get_width(mp_obj_t self_in) { + videogif_gifdecoder_obj_t *self = native_gifdecoder(self_in); + check_for_deinit(self); + return MP_OBJ_NEW_SMALL_INT(common_hal_videogif_gifdecoder_get_width(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(videogif_gifdecoder_get_width_obj, videogif_gifdecoder_get_width); + +MP_PROPERTY_GETTER(videogif_gifdecoder_width_obj, + (mp_obj_t)&videogif_gifdecoder_get_width_obj); + +//| height: int +//| """Height of the GIF in pixels. (read-only)""" +//| +//| +static mp_obj_t videogif_gifdecoder_get_height(mp_obj_t self_in) { + videogif_gifdecoder_obj_t *self = native_gifdecoder(self_in); + check_for_deinit(self); + return MP_OBJ_NEW_SMALL_INT(common_hal_videogif_gifdecoder_get_height(self)); +} +MP_DEFINE_CONST_FUN_OBJ_1(videogif_gifdecoder_get_height_obj, videogif_gifdecoder_get_height); + +MP_PROPERTY_GETTER(videogif_gifdecoder_height_obj, + (mp_obj_t)&videogif_gifdecoder_get_height_obj); + +static const mp_rom_map_elem_t videogif_gifdecoder_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&videogif_gifdecoder_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___enter__), MP_ROM_PTR(&default___enter___obj) }, + { MP_ROM_QSTR(MP_QSTR___exit__), MP_ROM_PTR(&default___exit___obj) }, + { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&videogif_gifdecoder_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR_height), MP_ROM_PTR(&videogif_gifdecoder_height_obj) }, + { MP_ROM_QSTR(MP_QSTR_width), MP_ROM_PTR(&videogif_gifdecoder_width_obj) }, +}; +static MP_DEFINE_CONST_DICT(videogif_gifdecoder_locals_dict, videogif_gifdecoder_locals_dict_table); + +// Implementation of the videocore videosource protocol so a VideoBuffer can +// tell the GifDecoder where to put frames. +static void videogif_gifdecoder_play(mp_obj_t self_in, bool paused) { + videogif_gifdecoder_obj_t *self = native_gifdecoder(self_in); + check_for_deinit(self); + common_hal_videogif_gifdecoder_play(self, paused); +} + +static void videogif_gifdecoder_stop(mp_obj_t self_in) { + common_hal_videogif_gifdecoder_stop(native_gifdecoder(self_in)); +} + +static void videogif_gifdecoder_pause(mp_obj_t self_in) { + common_hal_videogif_gifdecoder_pause(native_gifdecoder(self_in)); +} + +static void videogif_gifdecoder_resume(mp_obj_t self_in) { + common_hal_videogif_gifdecoder_resume(native_gifdecoder(self_in)); +} + +static bool videogif_gifdecoder_set_destination(mp_obj_t self_in, const videocore_destination_t *destination, + videocore_on_frame_fun on_frame, void *context) { + return common_hal_videogif_gifdecoder_set_destination(native_gifdecoder(self_in), destination, on_frame, context); +} + +static mp_int_t videogif_gifdecoder_videosource_get_width(mp_obj_t self_in) { + return common_hal_videogif_gifdecoder_get_width(native_gifdecoder(self_in)); +} + +static mp_int_t videogif_gifdecoder_videosource_get_height(mp_obj_t self_in) { + return common_hal_videogif_gifdecoder_get_height(native_gifdecoder(self_in)); +} + +static mp_int_t videogif_gifdecoder_get_bits_per_pixel(mp_obj_t self_in) { + return common_hal_videogif_gifdecoder_get_bits_per_pixel(native_gifdecoder(self_in)); +} + +static bool videogif_gifdecoder_set_bits_per_pixel(mp_obj_t self_in, mp_int_t bits_per_pixel) { + return common_hal_videogif_gifdecoder_set_bits_per_pixel(native_gifdecoder(self_in), bits_per_pixel); +} + +static const videosource_p_t videogif_gifdecoder_videosource_protocol = { + MP_PROTO_IMPLEMENT(MP_QSTR_protocol_videosource) + .play = videogif_gifdecoder_play, + .pause = videogif_gifdecoder_pause, + .resume = videogif_gifdecoder_resume, + .stop = videogif_gifdecoder_stop, + .set_destination = videogif_gifdecoder_set_destination, + .get_width = videogif_gifdecoder_videosource_get_width, + .get_height = videogif_gifdecoder_videosource_get_height, + .get_bits_per_pixel = videogif_gifdecoder_get_bits_per_pixel, + .set_bits_per_pixel = videogif_gifdecoder_set_bits_per_pixel, +}; + +MP_DEFINE_CONST_OBJ_TYPE( + videogif_gifdecoder_type, + MP_QSTR_GifDecoder, + MP_TYPE_FLAG_HAS_SPECIAL_ACCESSORS, + make_new, videogif_gifdecoder_make_new, + locals_dict, &videogif_gifdecoder_locals_dict, + protocol, &videogif_gifdecoder_videosource_protocol + ); diff --git a/shared-bindings/videogif/GifDecoder.h b/shared-bindings/videogif/GifDecoder.h new file mode 100644 index 00000000000..99146c39fd2 --- /dev/null +++ b/shared-bindings/videogif/GifDecoder.h @@ -0,0 +1,37 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mikey Sklar for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-module/videogif/GifDecoder.h" + +extern const mp_obj_type_t videogif_gifdecoder_type; + +// Open the GIF in file, which the constructor opened from its filename. Frames +// are 16-bit until set_bits_per_pixel asks for 1. Raises when the file isn't a +// GIF or is wider than AnimatedGIF supports. +void common_hal_videogif_gifdecoder_construct(videogif_gifdecoder_obj_t *self, mp_obj_t file); +// Stop playing, free the decoder and close the file. Safe to call more than +// once. +void common_hal_videogif_gifdecoder_deinit(videogif_gifdecoder_obj_t *self); +bool common_hal_videogif_gifdecoder_deinited(videogif_gifdecoder_obj_t *self); +mp_int_t common_hal_videogif_gifdecoder_get_width(videogif_gifdecoder_obj_t *self); +mp_int_t common_hal_videogif_gifdecoder_get_height(videogif_gifdecoder_obj_t *self); +mp_int_t common_hal_videogif_gifdecoder_get_bits_per_pixel(videogif_gifdecoder_obj_t *self); +// Decode frames to 1 or 16 bits per pixel from the next play. Returns false +// while playing or for another value. Never raises. +bool common_hal_videogif_gifdecoder_set_bits_per_pixel(videogif_gifdecoder_obj_t *self, + mp_int_t bits_per_pixel); + +// Videosource protocol steps, driven by videocore.VideoBuffer. Frames are +// decoded by the supervisor background tick, never in an interrupt. play +// raises when the decoder is already playing; the others never raise. +void common_hal_videogif_gifdecoder_play(videogif_gifdecoder_obj_t *self, bool paused); +void common_hal_videogif_gifdecoder_stop(videogif_gifdecoder_obj_t *self); +void common_hal_videogif_gifdecoder_pause(videogif_gifdecoder_obj_t *self); +void common_hal_videogif_gifdecoder_resume(videogif_gifdecoder_obj_t *self); +bool common_hal_videogif_gifdecoder_set_destination(videogif_gifdecoder_obj_t *self, + const videocore_destination_t *destination, videocore_on_frame_fun on_frame, void *context); diff --git a/shared-bindings/videogif/__init__.c b/shared-bindings/videogif/__init__.c new file mode 100644 index 00000000000..4128eeadc6a --- /dev/null +++ b/shared-bindings/videogif/__init__.c @@ -0,0 +1,30 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mikey Sklar for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "py/obj.h" +#include "py/runtime.h" + +#include "shared-bindings/videogif/GifDecoder.h" + +//| """Support for playing animated GIF files as video +//| +//| The `videogif` module reads animated GIF files so that a +//| `videocore.VideoBuffer` can play them on a display or into a buffer. +//| """ + +static const mp_rom_map_elem_t videogif_module_globals_table[] = { + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_videogif) }, + { MP_ROM_QSTR(MP_QSTR_GifDecoder), MP_ROM_PTR(&videogif_gifdecoder_type) }, +}; + +static MP_DEFINE_CONST_DICT(videogif_module_globals, videogif_module_globals_table); + +const mp_obj_module_t videogif_module = { + .base = { &mp_type_module }, + .globals = (mp_obj_dict_t *)&videogif_module_globals, +}; + +MP_REGISTER_MODULE(MP_QSTR_videogif, videogif_module); diff --git a/shared-bindings/watchdog/WatchDogTimer.c b/shared-bindings/watchdog/WatchDogTimer.c index dbb91311345..e0f42c549f6 100644 --- a/shared-bindings/watchdog/WatchDogTimer.c +++ b/shared-bindings/watchdog/WatchDogTimer.c @@ -48,9 +48,18 @@ static mp_obj_t watchdog_watchdogtimer_feed(mp_obj_t self_in) { } static MP_DEFINE_CONST_FUN_OBJ_1(watchdog_watchdogtimer_feed_obj, watchdog_watchdogtimer_feed); +static void validate_timeout(mp_float_t timeout) { + // Ports work in whole milliseconds, so anything under 1 ms becomes 0. + // Written as !(... >= 1) so that NaN is rejected too. + if (!(timeout * 1000 >= 1)) { + mp_arg_error_invalid(MP_QSTR_timeout); + } +} + //| timeout: float //| """The maximum number of seconds that can elapse between calls -//| to `feed()`. Setting the timeout will also feed the watchdog.""" +//| to `feed()`. Must be at least 0.001 (1 ms). Setting the timeout will also +//| feed the watchdog.""" static mp_obj_t watchdog_watchdogtimer_obj_get_timeout(mp_obj_t self_in) { watchdog_watchdogtimer_obj_t *self = MP_OBJ_TO_PTR(self_in); return mp_obj_new_float(common_hal_watchdog_get_timeout(self)); @@ -61,7 +70,7 @@ static mp_obj_t watchdog_watchdogtimer_obj_set_timeout(mp_obj_t self_in, mp_obj_ watchdog_watchdogtimer_obj_t *self = MP_OBJ_TO_PTR(self_in); mp_float_t timeout = mp_obj_get_float(timeout_obj); - mp_arg_validate_int_min(timeout, 0, MP_QSTR_timeout); + validate_timeout(timeout); common_hal_watchdog_set_timeout(self, timeout); return mp_const_none; @@ -85,7 +94,8 @@ MP_PROPERTY_GETSET(watchdog_watchdogtimer_timeout_obj, //| watchdog.mode = WatchDogMode.RESET //| //| -//| Once set, the `WatchDogTimer` will perform the specified action if the timer expires.""" +//| Once set, the `WatchDogTimer` will perform the specified action if the timer expires. +//| Set `timeout` first: setting a `WatchDogMode` while `timeout` is less than 0.001 raises `ValueError`.""" //| //| static mp_obj_t watchdog_watchdogtimer_obj_get_mode(mp_obj_t self_in) { @@ -97,6 +107,9 @@ MP_DEFINE_CONST_FUN_OBJ_1(watchdog_watchdogtimer_get_mode_obj, watchdog_watchdog static mp_obj_t watchdog_watchdogtimer_obj_set_mode(mp_obj_t self_in, mp_obj_t obj) { watchdog_watchdogtimer_obj_t *self = MP_OBJ_TO_PTR(self_in); watchdog_watchdogmode_t mode = (obj == mp_const_none) ? WATCHDOGMODE_NONE : cp_enum_value(&watchdog_watchdogmode_type, obj, MP_QSTR_mode); + if (mode != WATCHDOGMODE_NONE) { + validate_timeout(common_hal_watchdog_get_timeout(self)); + } common_hal_watchdog_set_mode(self, mode); return mp_const_none; } diff --git a/shared-bindings/watchdog/WatchDogTimer.h b/shared-bindings/watchdog/WatchDogTimer.h index 44fb32dd522..3cd79b320af 100644 --- a/shared-bindings/watchdog/WatchDogTimer.h +++ b/shared-bindings/watchdog/WatchDogTimer.h @@ -20,6 +20,6 @@ extern void common_hal_watchdog_set_timeout(watchdog_watchdogtimer_obj_t *self, extern mp_float_t common_hal_watchdog_get_timeout(watchdog_watchdogtimer_obj_t *self); extern void common_hal_watchdog_enable(watchdog_watchdogtimer_obj_t *self); -extern void common_hal_watchdog_deinit(watchdog_watchdogtimer_obj_t *self); +extern void common_hal_watchdog_reset(watchdog_watchdogtimer_obj_t *self); extern const mp_obj_type_t watchdog_watchdogtimer_type; diff --git a/shared-bindings/wifi/Monitor.c b/shared-bindings/wifi/Monitor.c index fb09c4b4f77..fc321614d31 100644 --- a/shared-bindings/wifi/Monitor.c +++ b/shared-bindings/wifi/Monitor.c @@ -19,7 +19,11 @@ //| def __init__(self, channel: Optional[int] = 1, queue: Optional[int] = 128) -> None: //| """Initialize `wifi.Monitor` singleton. //| -//| :param int channel: The WiFi channel to scan. +//| :param int channel: The WiFi channel to scan. On dual-band radios, +//| 5 GHz channels (36 and above) may also be given. A channel the +//| radio does not support raises `ValueError`. While the station is +//| connected the radio stays on the station's channel, and +//| `channel` reports that channel. //| :param int queue: The queue size for buffering the packet. //| //| """ @@ -35,12 +39,14 @@ static mp_obj_t wifi_monitor_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_kw_array(n_args, n_kw, all_args, MP_ARRAY_SIZE(allowed_args), allowed_args, args); - mp_int_t channel = mp_arg_validate_int_range(args[ARG_channel].u_int, 1, 13, MP_QSTR_channel); + // 165 is the highest channel in the scan pattern. Channels the radio + // doesn't support are rejected by the port rather than here. + mp_int_t channel = mp_arg_validate_int_range(args[ARG_channel].u_int, 1, 165, MP_QSTR_channel); mp_int_t queue = mp_arg_validate_int_min(args[ARG_queue].u_int, 0, MP_QSTR_queue); wifi_monitor_obj_t *self = MP_STATE_VM(wifi_monitor_singleton); - if (common_hal_wifi_monitor_deinited()) { - self = mp_obj_malloc(wifi_monitor_obj_t, &wifi_monitor_type); + if (self == NULL || common_hal_wifi_monitor_deinited(self)) { + self = mp_obj_malloc_with_finaliser(wifi_monitor_obj_t, &wifi_monitor_type); common_hal_wifi_monitor_construct(self, channel, queue); MP_STATE_VM(wifi_monitor_singleton) = self; } @@ -49,17 +55,16 @@ static mp_obj_t wifi_monitor_make_new(const mp_obj_type_t *type, size_t n_args, } //| channel: int -//| """The WiFi channel to scan.""" +//| """The WiFi channel to scan. A channel the radio does not support raises +//| `ValueError`. While the station is connected the radio stays on the +//| station's channel, and this reports that channel.""" static mp_obj_t wifi_monitor_obj_get_channel(mp_obj_t self_in) { return common_hal_wifi_monitor_get_channel(self_in); } MP_DEFINE_CONST_FUN_OBJ_1(wifi_monitor_get_channel_obj, wifi_monitor_obj_get_channel); static mp_obj_t wifi_monitor_obj_set_channel(mp_obj_t self_in, mp_obj_t channel) { - mp_int_t c = mp_obj_get_int(channel); - if (c < 1 || c > 13) { - mp_raise_ValueError_varg(MP_ERROR_TEXT("%q out of bounds"), MP_QSTR_channel); - } + mp_int_t c = mp_arg_validate_int_range(mp_obj_get_int(channel), 1, 165, MP_QSTR_channel); common_hal_wifi_monitor_set_channel(self_in, c); return mp_const_none; } @@ -104,7 +109,7 @@ MP_DEFINE_CONST_FUN_OBJ_1(wifi_monitor_lost_obj, wifi_monitor_obj_get_lost); //| ... //| static mp_obj_t wifi_monitor_obj_get_queued(mp_obj_t self_in) { - if (common_hal_wifi_monitor_deinited()) { + if (common_hal_wifi_monitor_deinited(self_in)) { return mp_obj_new_int_from_uint(0); } return common_hal_wifi_monitor_get_queued(self_in); @@ -117,7 +122,7 @@ MP_DEFINE_CONST_FUN_OBJ_1(wifi_monitor_queued_obj, wifi_monitor_obj_get_queued); //| //| static mp_obj_t wifi_monitor_obj_get_packet(mp_obj_t self_in) { - if (common_hal_wifi_monitor_deinited()) { + if (common_hal_wifi_monitor_deinited(self_in)) { raise_deinited_error(); } return common_hal_wifi_monitor_get_packet(self_in); @@ -131,6 +136,7 @@ static const mp_rom_map_elem_t wifi_monitor_locals_dict_table[] = { // functions { MP_ROM_QSTR(MP_QSTR_deinit), MP_ROM_PTR(&wifi_monitor_deinit_obj) }, + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&wifi_monitor_deinit_obj) }, { MP_ROM_QSTR(MP_QSTR_lost), MP_ROM_PTR(&wifi_monitor_lost_obj) }, { MP_ROM_QSTR(MP_QSTR_queued), MP_ROM_PTR(&wifi_monitor_queued_obj) }, { MP_ROM_QSTR(MP_QSTR_packet), MP_ROM_PTR(&wifi_monitor_packet_obj) }, diff --git a/shared-bindings/wifi/Monitor.h b/shared-bindings/wifi/Monitor.h index c6a4ae6ecdf..cef14303522 100644 --- a/shared-bindings/wifi/Monitor.h +++ b/shared-bindings/wifi/Monitor.h @@ -13,7 +13,7 @@ extern const mp_obj_type_t wifi_monitor_type; void common_hal_wifi_monitor_construct(wifi_monitor_obj_t *self, uint8_t channel, size_t queue); void common_hal_wifi_monitor_deinit(wifi_monitor_obj_t *self); -bool common_hal_wifi_monitor_deinited(void); +bool common_hal_wifi_monitor_deinited(wifi_monitor_obj_t *self); void common_hal_wifi_monitor_set_channel(wifi_monitor_obj_t *self, uint8_t channel); mp_obj_t common_hal_wifi_monitor_get_channel(wifi_monitor_obj_t *self); diff --git a/shared-bindings/wifi/PowerManagement.c b/shared-bindings/wifi/PowerManagement.c new file mode 100644 index 00000000000..659144b024d --- /dev/null +++ b/shared-bindings/wifi/PowerManagement.c @@ -0,0 +1,50 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Dan Halbert for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "py/enum.h" + +#include "shared-bindings/wifi/PowerManagement.h" + +//| class PowerManagement: +//| """Power-saving options for wifi +//| +//| .. note:: On boards using the CYW43 radio module, the choices below correspond to the +//| power management values defined in the `cyw43` module: +//| `PowerManagement.MIN` is the same as `cyw43.PM_PERFORMANCE`, `PowerManagement.MAX` +//| is the same as `cyw43.PM_AGGRESSIVE`, and `PowerManagement.NONE` is the same as +//| `cyw43.PM_DISABLED`. If a custom value was set with `cyw43.set_power_management()` +//| not corresponding to one of these three values, then `PowerManagement.UNKNOWN` will be returned. +//| """ +//| +//| MIN: PowerManagement +//| """Minimum power management (default). The WiFi station wakes up to receive a beacon every DTIM period. +//| The DTIM period is set by the access point.""" +//| MAX: PowerManagement +//| """Maximum power management, at the expense of some performance. The WiFi station wakes up less often than `MIN`.""" +//| NONE: PowerManagement +//| """No power management: the WiFi station does not sleep.""" +//| UNKNOWN: PowerManagement +//| """Power management setting cannot be determined.""" +//| + +// In order of the enum type. +MAKE_ENUM_VALUE(wifi_power_management_type, power_management, NONE, POWER_MANAGEMENT_NONE); +MAKE_ENUM_VALUE(wifi_power_management_type, power_management, MIN, POWER_MANAGEMENT_MIN); +MAKE_ENUM_VALUE(wifi_power_management_type, power_management, MAX, POWER_MANAGEMENT_MAX); +MAKE_ENUM_VALUE(wifi_power_management_type, power_management, UNKNOWN, POWER_MANAGEMENT_UNKNOWN); + +MAKE_ENUM_MAP(wifi_power_management) { + MAKE_ENUM_MAP_ENTRY(power_management, NONE), + MAKE_ENUM_MAP_ENTRY(power_management, MIN), + MAKE_ENUM_MAP_ENTRY(power_management, MAX), + MAKE_ENUM_MAP_ENTRY(power_management, UNKNOWN), +}; + +static MP_DEFINE_CONST_DICT(wifi_power_management_locals_dict, wifi_power_management_locals_table); + +MAKE_PRINTER(wifi, wifi_power_management); + +MAKE_ENUM_TYPE(wifi, PowerManagement, wifi_power_management); diff --git a/shared-bindings/wifi/PowerManagement.h b/shared-bindings/wifi/PowerManagement.h new file mode 100644 index 00000000000..c933e36df15 --- /dev/null +++ b/shared-bindings/wifi/PowerManagement.h @@ -0,0 +1,19 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Dan Halbert for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/enum.h" + +typedef enum { + POWER_MANAGEMENT_NONE = 0, + POWER_MANAGEMENT_MIN = 1, + POWER_MANAGEMENT_MAX = 2, + // Value can't be determined. + POWER_MANAGEMENT_UNKNOWN = 3, +} wifi_power_management_t; + +extern const mp_obj_type_t wifi_power_management_type; diff --git a/shared-bindings/wifi/Radio.c b/shared-bindings/wifi/Radio.c index 57faa7065d0..5f5861ef2af 100644 --- a/shared-bindings/wifi/Radio.c +++ b/shared-bindings/wifi/Radio.c @@ -6,9 +6,12 @@ #include "shared-bindings/wifi/__init__.h" #include "shared-bindings/wifi/AuthMode.h" +#include "shared-bindings/wifi/Network.h" +#include "shared-bindings/wifi/PowerManagement.h" #include +#include "py/enum.h" #include "py/unicode.h" #include "py/runtime.h" #include "py/objproperty.h" @@ -97,7 +100,20 @@ MP_PROPERTY_GETSET(wifi_radio_enabled_obj, (mp_obj_t)&wifi_radio_get_enabled_obj, (mp_obj_t)&wifi_radio_set_enabled_obj); -//| hostname: Union[str | ReadableBuffer] +//| version: Optional[str] +//| """WiFi co-processor firmware identification, such as ``"esp32c6 ESP-Hosted 2.12.13"``, +//| or ``None`` if the radio is not a separate co-processor or its version cannot be read. +//| (read-only)""" +static mp_obj_t wifi_radio_get_version(mp_obj_t self_in) { + wifi_radio_obj_t *self = MP_OBJ_TO_PTR(self_in); + return common_hal_wifi_radio_get_version(self); +} +MP_DEFINE_CONST_FUN_OBJ_1(wifi_radio_get_version_obj, wifi_radio_get_version); + +MP_PROPERTY_GETTER(wifi_radio_version_obj, + (mp_obj_t)&wifi_radio_get_version_obj); + +//| hostname: Union[str, ReadableBuffer] //| """Hostname for wifi interface. When the hostname is altered after interface started/connected //| the changes would only be reflected once the interface restarts/reconnects.""" static mp_obj_t wifi_radio_get_hostname(mp_obj_t self_in) { @@ -131,7 +147,8 @@ MP_PROPERTY_GETSET(wifi_radio_hostname_obj, //| """MAC address for the station. When the address is altered after interface is connected //| the changes would only be reflected once the interface reconnects. //| -//| **Limitations:** Not settable on RP2040 CYW43 boards, such as Pi Pico W. +//| **Limitations:** Settable on Espressif. +//| Not settable on Raspberry Pi RP2xxx CYW43 boards, such as Pico W and Pico 2 W. //| """ @@ -187,39 +204,44 @@ MP_PROPERTY_GETSET(wifi_radio_tx_power_obj, (mp_obj_t)&wifi_radio_get_tx_power_obj, (mp_obj_t)&wifi_radio_set_tx_power_obj); -//| listen_interval: int -//| """Wifi power save listen interval, in DTIM periods, or 100ms intervals if TWT is supported.""" -static mp_obj_t wifi_radio_get_listen_interval(mp_obj_t self_in) { - #if CIRCUITPY_WIFI_RADIO_SETTABLE_LISTEN_INTERVAL +// TODO: Remove the ESP-Hosted exception below when the upstream bug is fixed. +// https://github.com/espressif/esp-idf/issues/16096 +// https://github.com/adafruit/circuitpython/issues/11682 +//| power_management: PowerManagement +//| """Wifi power management setting. See `wifi.PowerManagement`. The default is `wifi.PowerManagement.MIN`. +//| +//| On Espressif boards whose WiFi runs on an ESP-Hosted co-processor, such as the Metro ESP32-P4, +//| the default is `wifi.PowerManagement.NONE`. This is a temporary workaround for a bug in power +//| save mode; see `#11682 `_. +//| """ +static mp_obj_t wifi_radio_get_power_management(mp_obj_t self_in) { wifi_radio_obj_t *self = MP_OBJ_TO_PTR(self_in); - return mp_obj_new_int(common_hal_wifi_radio_get_listen_interval(self)); - #else - return mp_obj_new_int(0); - #endif + return cp_enum_find(&wifi_power_management_type, common_hal_wifi_radio_get_power_management(self)); } -MP_DEFINE_CONST_FUN_OBJ_1(wifi_radio_get_listen_interval_obj, wifi_radio_get_listen_interval); +MP_DEFINE_CONST_FUN_OBJ_1(wifi_radio_get_power_management_obj, wifi_radio_get_power_management); -static mp_obj_t wifi_radio_set_listen_interval(mp_obj_t self_in, mp_obj_t listen_interval_in) { - #if CIRCUITPY_WIFI_RADIO_SETTABLE_LISTEN_INTERVAL - mp_int_t listen_interval = mp_obj_get_int(listen_interval_in); +static mp_obj_t wifi_radio_set_power_management(mp_obj_t self_in, mp_obj_t power_management_in) { wifi_radio_obj_t *self = MP_OBJ_TO_PTR(self_in); - common_hal_wifi_radio_set_listen_interval(self, listen_interval); - #else - mp_raise_NotImplementedError(NULL); - #endif + wifi_power_management_t power_management = + cp_enum_value(&wifi_power_management_type, power_management_in, MP_QSTR_power_management); + if (power_management == POWER_MANAGEMENT_UNKNOWN) { + mp_arg_error_invalid(MP_QSTR_power_management); + } + common_hal_wifi_radio_set_power_management(self, power_management); return mp_const_none; } -MP_DEFINE_CONST_FUN_OBJ_2(wifi_radio_set_listen_interval_obj, wifi_radio_set_listen_interval); +MP_DEFINE_CONST_FUN_OBJ_2(wifi_radio_set_power_management_obj, wifi_radio_set_power_management); -MP_PROPERTY_GETSET(wifi_radio_listen_interval_obj, - (mp_obj_t)&wifi_radio_get_listen_interval_obj, - (mp_obj_t)&wifi_radio_set_listen_interval_obj); +MP_PROPERTY_GETSET(wifi_radio_power_management_obj, + (mp_obj_t)&wifi_radio_get_power_management_obj, + (mp_obj_t)&wifi_radio_set_power_management_obj); //| mac_address_ap: ReadableBuffer //| """MAC address for the AP. When the address is altered after interface is started //| the changes would only be reflected once the interface restarts. //| -//| **Limitations:** Not settable on RP2040 CYW43 boards, such as Pi Pico W. +//| **Limitations:** Settable on Espressif. +//| Not settable on Raspberry Pi RP2xxx CYW43 boards, such as Pico W and Pico 2 W. //| """ //| static mp_obj_t wifi_radio_get_mac_address_ap(mp_obj_t self_in) { @@ -255,13 +277,16 @@ MP_PROPERTY_GETTER(wifi_radio_mac_address_ap_obj, #endif //| def start_scanning_networks( -//| self, *, start_channel: int = 1, stop_channel: int = 11 +//| self, *, start_channel: int = 1, stop_channel: int = 165 //| ) -> Iterable[Network]: //| """Scans for available wifi networks over the given channel range. Make sure the channels are allowed in your country. //| +//| On dual-band radios, 5 GHz channels (36 and above) may also be given. +//| Channel numbers that the radio does not support are skipped. +//| //| .. note:: //| -//| In the raspberrypi port (RP2040 CYW43), ``start_channel`` and ``stop_channel`` are ignored. +//| In the raspberrypi port (RP2xxx CYW43), ``start_channel`` and ``stop_channel`` are ignored. //| """ //| ... //| @@ -269,17 +294,19 @@ static mp_obj_t wifi_radio_start_scanning_networks(size_t n_args, const mp_obj_t enum { ARG_start_channel, ARG_stop_channel }; static const mp_arg_t allowed_args[] = { { MP_QSTR_start_channel, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 1} }, - { MP_QSTR_stop_channel, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 11} }, + { MP_QSTR_stop_channel, MP_ARG_KW_ONLY | MP_ARG_INT, {.u_int = 165} }, }; wifi_radio_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]); 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); + // 165 is the highest channel in the scan pattern. Channels the radio + // doesn't support are skipped while scanning rather than rejected here. uint8_t start_channel = - (uint8_t)mp_arg_validate_int_range(args[ARG_start_channel].u_int, 1, 14, MP_QSTR_start_channel); + (uint8_t)mp_arg_validate_int_range(args[ARG_start_channel].u_int, 1, 165, MP_QSTR_start_channel); uint8_t stop_channel = - (uint8_t)mp_arg_validate_int_range(args[ARG_stop_channel].u_int, 1, 14, MP_QSTR_stop_channel); + (uint8_t)mp_arg_validate_int_range(args[ARG_stop_channel].u_int, 1, 165, MP_QSTR_stop_channel); // Swap if in reverse order, without complaining. if (start_channel > stop_channel) { uint8_t temp = stop_channel; @@ -326,8 +353,8 @@ MP_DEFINE_CONST_FUN_OBJ_1(wifi_radio_stop_station_obj, wifi_radio_stop_station); //| def start_ap( //| self, -//| ssid: Union[str | ReadableBuffer], -//| password: Union[str | ReadableBuffer] = b"", +//| ssid: Union[str, ReadableBuffer], +//| password: Union[str, ReadableBuffer] = b"", //| *, //| channel: int = 1, //| authmode: Iterable[AuthMode] = (), @@ -337,6 +364,8 @@ MP_DEFINE_CONST_FUN_OBJ_1(wifi_radio_stop_station_obj, wifi_radio_stop_station); //| //| If ``channel`` is given, the access point will use that channel unless //| a station is already operating on a different channel. +//| On dual-band radios, 5 GHz channels (36 and above) may also be given. +//| A channel the radio does not support raises `ValueError`. //| //| If ``authmode`` is not None, the access point will use the given authentication modes. //| If a non-empty password is given, ``authmode`` must not include ``OPEN``. @@ -358,7 +387,8 @@ MP_DEFINE_CONST_FUN_OBJ_1(wifi_radio_stop_station_obj, wifi_radio_stop_station); //| //| .. note:: //| -//| In the raspberrypi port (RP2040 CYW43), ``max_connections`` is ignored. +//| In the raspberrypi port (RP2xxx CYW43), ``max_connections`` is ignored +//| and only 2.4 GHz channels (1-13) are accepted. //| """ //| ... //| @@ -398,7 +428,9 @@ static mp_obj_t wifi_radio_start_ap(size_t n_args, const mp_obj_t *pos_args, mp_ } } - mp_int_t channel = mp_arg_validate_int_range(args[ARG_channel].u_int, 1, 13, MP_QSTR_channel); + // 165 is the highest channel in the scan pattern. Channels the radio + // doesn't support are rejected by the port rather than here. + mp_int_t channel = mp_arg_validate_int_range(args[ARG_channel].u_int, 1, 165, MP_QSTR_channel); if (authmode == AUTHMODE_OPEN && password.len > 0) { mp_raise_ValueError(MP_ERROR_TEXT("AuthMode.OPEN is not used with password")); @@ -439,12 +471,13 @@ MP_PROPERTY_GETTER(wifi_radio_ap_active_obj, //| def connect( //| self, -//| ssid: Union[str | ReadableBuffer], -//| password: Union[str | ReadableBuffer] = b"", +//| ssid: Optional[Union[str, ReadableBuffer]] = None, +//| password: Union[str, ReadableBuffer] = b"", //| *, //| channel: int = 0, -//| bssid: Optional[Union[str | ReadableBuffer]] = None, +//| bssid: Optional[Union[str, ReadableBuffer]] = None, //| timeout: Optional[float] = None, +//| network: Optional[Network] = None, //| ) -> None: //| """Connects to the given ssid and waits for an ip address. Reconnections are handled //| automatically once one connection succeeds. @@ -460,17 +493,22 @@ MP_PROPERTY_GETTER(wifi_radio_ap_active_obj, //| significantly because a full scan doesn't occur. //| //| If ``bssid`` is given and not None, the scan will start at the first channel or the one given and -//| connect to the AP with the given ``bssid`` and ``ssid``.""" +//| connect to the AP with the given ``bssid`` and ``ssid``. +//| +//| If ``network`` is given, it must be a `Network` returned by +//| `start_scanning_networks`. Its ``ssid``, ``bssid`` and ``channel`` are used, so no +//| scan happens. Give either ``ssid`` or ``network``, not both.""" //| ... //| static mp_obj_t wifi_radio_connect(size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { - enum { ARG_ssid, ARG_password, ARG_channel, ARG_bssid, ARG_timeout }; + enum { ARG_ssid, ARG_password, ARG_channel, ARG_bssid, ARG_timeout, ARG_network }; static const mp_arg_t allowed_args[] = { - { MP_QSTR_ssid, MP_ARG_REQUIRED | MP_ARG_OBJ }, + { MP_QSTR_ssid, MP_ARG_OBJ, {.u_obj = mp_const_none} }, { MP_QSTR_password, MP_ARG_OBJ, {.u_obj = mp_const_empty_bytes} }, { 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_const_none} }, { MP_QSTR_timeout, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, + { MP_QSTR_network, MP_ARG_KW_ONLY | MP_ARG_OBJ, {.u_obj = mp_const_none} }, }; wifi_radio_obj_t *self = MP_OBJ_TO_PTR(pos_args[0]); @@ -482,9 +520,27 @@ static mp_obj_t wifi_radio_connect(size_t n_args, const mp_obj_t *pos_args, mp_m timeout = mp_obj_get_float(args[ARG_timeout].u_obj); } + mp_obj_t ssid_obj = args[ARG_ssid].u_obj; + mp_obj_t bssid_obj = args[ARG_bssid].u_obj; + mp_int_t channel = args[ARG_channel].u_int; + + if (args[ARG_network].u_obj != mp_const_none) { + if (ssid_obj != mp_const_none) { + mp_raise_TypeError_varg(MP_ERROR_TEXT("Supply either %q or %q, not both"), MP_QSTR_ssid, MP_QSTR_network); + } + wifi_network_obj_t *network = MP_OBJ_TO_PTR(mp_arg_validate_type(args[ARG_network].u_obj, &wifi_network_type, MP_QSTR_network)); + ssid_obj = common_hal_wifi_network_get_ssid(network); + bssid_obj = common_hal_wifi_network_get_bssid(network); + channel = mp_obj_get_int(common_hal_wifi_network_get_channel(network)); + } + + if (ssid_obj == mp_const_none) { + mp_raise_TypeError_varg(MP_ERROR_TEXT("'%q' argument required"), MP_QSTR_ssid); + } + mp_buffer_info_t ssid; ssid.len = 0; - mp_get_buffer_raise(args[ARG_ssid].u_obj, &ssid, MP_BUFFER_READ); + mp_get_buffer_raise(ssid_obj, &ssid, MP_BUFFER_READ); mp_arg_validate_length_range(ssid.len, 1, 32, MP_QSTR_ssid); mp_buffer_info_t password; @@ -504,14 +560,14 @@ static mp_obj_t wifi_radio_connect(size_t n_args, const mp_obj_t *pos_args, mp_m mp_buffer_info_t bssid; bssid.len = 0; // Should probably make sure bssid is just bytes and not something else too - if (args[ARG_bssid].u_obj != mp_const_none) { - mp_get_buffer_raise(args[ARG_bssid].u_obj, &bssid, MP_BUFFER_READ); + if (bssid_obj != mp_const_none) { + mp_get_buffer_raise(bssid_obj, &bssid, MP_BUFFER_READ); if (bssid.len != MAC_ADDRESS_LENGTH) { mp_raise_ValueError(MP_ERROR_TEXT("Invalid BSSID")); } } - wifi_radio_error_t error = common_hal_wifi_radio_connect(self, ssid.buf, ssid.len, password.buf, password.len, args[ARG_channel].u_int, timeout, bssid.buf, bssid.len); + wifi_radio_error_t error = common_hal_wifi_radio_connect(self, ssid.buf, ssid.len, password.buf, password.len, channel, timeout, bssid.buf, bssid.len); if (error == WIFI_RADIO_ERROR_AUTH_FAIL) { mp_raise_ConnectionError(MP_ERROR_TEXT("Authentication failure")); } else if (error == WIFI_RADIO_ERROR_NO_AP_FOUND) { @@ -588,7 +644,7 @@ MP_PROPERTY_GETTER(wifi_radio_ipv4_subnet_ap_obj, //| //| .. note:: //| -//| In the raspberrypi port (RP2040 CYW43), the access point needs to be started before the IP v4 address can be set. +//| In the raspberrypi port (RP2xxx CYW43), the access point needs to be started before the IP v4 address can be set. //| """ //| ... //| @@ -833,6 +889,7 @@ static MP_DEFINE_CONST_FUN_OBJ_KW(wifi_radio_ping_obj, 1, wifi_radio_ping); static const mp_rom_map_elem_t wifi_radio_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_enabled), MP_ROM_PTR(&wifi_radio_enabled_obj) }, + { MP_ROM_QSTR(MP_QSTR_version), MP_ROM_PTR(&wifi_radio_version_obj) }, { MP_ROM_QSTR(MP_QSTR_hostname), MP_ROM_PTR(&wifi_radio_hostname_obj) }, @@ -868,6 +925,7 @@ static const mp_rom_map_elem_t wifi_radio_locals_dict_table[] = { { MP_ROM_QSTR(MP_QSTR_ipv4_subnet_ap), MP_ROM_PTR(&wifi_radio_ipv4_subnet_ap_obj) }, { MP_ROM_QSTR(MP_QSTR_ipv4_address), MP_ROM_PTR(&wifi_radio_ipv4_address_obj) }, { MP_ROM_QSTR(MP_QSTR_ipv4_address_ap), MP_ROM_PTR(&wifi_radio_ipv4_address_ap_obj) }, + { MP_ROM_QSTR(MP_QSTR_power_management), MP_ROM_PTR(&wifi_radio_power_management_obj) }, { MP_ROM_QSTR(MP_QSTR_set_ipv4_address), MP_ROM_PTR(&wifi_radio_set_ipv4_address_obj) }, { MP_ROM_QSTR(MP_QSTR_set_ipv4_address_ap), MP_ROM_PTR(&wifi_radio_set_ipv4_address_ap_obj) }, diff --git a/shared-bindings/wifi/Radio.h b/shared-bindings/wifi/Radio.h index ac352626dcc..0d1394e680f 100644 --- a/shared-bindings/wifi/Radio.h +++ b/shared-bindings/wifi/Radio.h @@ -8,6 +8,8 @@ #include +#include "shared-bindings/wifi/PowerManagement.h" + #include "common-hal/wifi/Radio.h" #include "py/objstr.h" @@ -62,6 +64,8 @@ typedef enum { extern bool common_hal_wifi_radio_get_enabled(wifi_radio_obj_t *self); extern void common_hal_wifi_radio_set_enabled(wifi_radio_obj_t *self, bool enabled); +extern mp_obj_t common_hal_wifi_radio_get_version(wifi_radio_obj_t *self); + extern mp_obj_t common_hal_wifi_radio_get_hostname(wifi_radio_obj_t *self); extern void common_hal_wifi_radio_set_hostname(wifi_radio_obj_t *self, const char *hostname); @@ -75,8 +79,8 @@ extern void common_hal_wifi_radio_set_mac_address_ap(wifi_radio_obj_t *self, con extern mp_float_t common_hal_wifi_radio_get_tx_power(wifi_radio_obj_t *self); extern void common_hal_wifi_radio_set_tx_power(wifi_radio_obj_t *self, const mp_float_t power); -extern void common_hal_wifi_radio_set_listen_interval(wifi_radio_obj_t *self, const mp_int_t listen_interval); -extern mp_int_t common_hal_wifi_radio_get_listen_interval(wifi_radio_obj_t *self); +extern wifi_power_management_t common_hal_wifi_radio_get_power_management(wifi_radio_obj_t *self); +extern void common_hal_wifi_radio_set_power_management(wifi_radio_obj_t *self, wifi_power_management_t power_management); extern mp_obj_t common_hal_wifi_radio_start_scanning_networks(wifi_radio_obj_t *self, uint8_t start_channel, uint8_t stop_channel); extern void common_hal_wifi_radio_stop_scanning_networks(wifi_radio_obj_t *self); diff --git a/shared-bindings/wifi/__init__.c b/shared-bindings/wifi/__init__.c index 91d317ebd16..2a1c0097080 100644 --- a/shared-bindings/wifi/__init__.c +++ b/shared-bindings/wifi/__init__.c @@ -30,21 +30,22 @@ static MP_DEFINE_CONST_FUN_OBJ_0(wifi___init___obj, wifi___init__); static const mp_rom_map_elem_t wifi_module_globals_table[] = { // Name - { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_wifi) }, + { MP_ROM_QSTR(MP_QSTR___name__), MP_ROM_QSTR(MP_QSTR_wifi) }, // Initialization - { MP_ROM_QSTR(MP_QSTR___init__), MP_ROM_PTR(&wifi___init___obj) }, + { MP_ROM_QSTR(MP_QSTR___init__), MP_ROM_PTR(&wifi___init___obj) }, // Classes - { MP_ROM_QSTR(MP_QSTR_AuthMode), MP_ROM_PTR(&wifi_authmode_type) }, - { MP_ROM_QSTR(MP_QSTR_Monitor), MP_ROM_PTR(&wifi_monitor_type) }, - { MP_ROM_QSTR(MP_QSTR_Network), MP_ROM_PTR(&wifi_network_type) }, - { MP_ROM_QSTR(MP_QSTR_Packet), MP_ROM_PTR(&wifi_packet_type) }, - { MP_ROM_QSTR(MP_QSTR_Radio), MP_ROM_PTR(&wifi_radio_type) }, - { MP_ROM_QSTR(MP_QSTR_Station), MP_ROM_PTR(&wifi_radio_station_type) }, + { MP_ROM_QSTR(MP_QSTR_AuthMode), MP_ROM_PTR(&wifi_authmode_type) }, + { MP_ROM_QSTR(MP_QSTR_Monitor), MP_ROM_PTR(&wifi_monitor_type) }, + { MP_ROM_QSTR(MP_QSTR_Network), MP_ROM_PTR(&wifi_network_type) }, + { MP_ROM_QSTR(MP_QSTR_Packet), MP_ROM_PTR(&wifi_packet_type) }, + { MP_ROM_QSTR(MP_QSTR_PowerManagement), MP_ROM_PTR(&wifi_power_management_type) }, + { MP_ROM_QSTR(MP_QSTR_Radio), MP_ROM_PTR(&wifi_radio_type) }, + { MP_ROM_QSTR(MP_QSTR_Station), MP_ROM_PTR(&wifi_radio_station_type) }, // Properties - { MP_ROM_QSTR(MP_QSTR_radio), MP_ROM_PTR(&common_hal_wifi_radio_obj) }, + { MP_ROM_QSTR(MP_QSTR_radio), MP_ROM_PTR(&common_hal_wifi_radio_obj) }, }; static MP_DEFINE_CONST_DICT(wifi_module_globals, wifi_module_globals_table); diff --git a/shared-bindings/wifi/__init__.h b/shared-bindings/wifi/__init__.h index a1a606e502c..8bad737b25e 100644 --- a/shared-bindings/wifi/__init__.h +++ b/shared-bindings/wifi/__init__.h @@ -14,3 +14,21 @@ void common_hal_wifi_init(bool user_initiated); void common_hal_wifi_gc_collect(void); void wifi_user_reset(void); + +// Raw hostname of the network interface as configured for the interface's +// DHCP request (option 12). Never allocates. The returned pointer points into +// storage owned by the port and stays valid until the hostname is replaced, +// so use it promptly rather than holding onto it. Used by +// supervisor/shared/web_workflow. +const char *wifi_get_hostname_raw(void); + +// True once common_hal_wifi_init() has run, until wifi_reset() undoes it. Some +// ports never undo it. While true, wifi_get_hostname_raw() returns the +// interface's hostname. Never allocates or raises. +bool wifi_is_initialized(void); + +// Gets the hostname that common_hal_wifi_init() sets when +// CIRCUITPY_WIFI_HOSTNAME is not in settings.toml. Can be called before the +// radio is initialized. Writes the hostname to buf as a NUL-terminated string, +// truncated to fit in buf_size bytes. Never allocates or raises. +void wifi_get_default_hostname(char *buf, size_t buf_size); diff --git a/shared-bindings/zlib/__init__.c b/shared-bindings/zlib/__init__.c index a17694d8a2e..f6992418e20 100644 --- a/shared-bindings/zlib/__init__.c +++ b/shared-bindings/zlib/__init__.c @@ -53,7 +53,7 @@ static mp_obj_t zlib_decompress(size_t n_args, const mp_obj_t *args) { mp_int_t wbits = 0; if (n_args > 1) { - wbits = MP_OBJ_SMALL_INT_VALUE(args[1]); + wbits = mp_obj_get_int_truncated(args[1]); } return common_hal_zlib_decompress(args[0], wbits); diff --git a/shared-module/_airlift/__init__.c b/shared-module/_airlift/__init__.c new file mode 100644 index 00000000000..b5b9455468e --- /dev/null +++ b/shared-module/_airlift/__init__.c @@ -0,0 +1,95 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/_airlift/__init__.h" + +#include "py/mperrno.h" +#include "py/objlist.h" +#include "py/runtime.h" + +// Replies to VM commands land here before they are copied into bytearrays. Only +// the VM uses these, so a background command can't overwrite them. +static uint8_t vm_reply_buf[AIRLIFT_MAX_TRANSFER]; +static uint16_t vm_reply_lens[255]; + +void common_hal__airlift_init(void) { + if (!airlift_transport_init()) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("%q in use"), MP_QSTR_pin); + } +} + +bool common_hal__airlift_active(void) { + return airlift_transport_active(); +} + +static void check_active(void) { + if (!airlift_transport_active()) { + mp_raise_OSError(MP_ENODEV); + } +} + +void common_hal__airlift_reset(void) { + check_active(); + airlift_transport_reset(); +} + +void common_hal__airlift_release(void) { + airlift_transport_deinit(); +} + +// Raises the exception type ESP32SPI raises for the same failure, so its error +// handling keeps working. +static void raise_for(airlift_result_t result, uint8_t cmd) { + switch (result) { + case AIRLIFT_OK: + return; + case AIRLIFT_NOT_ACTIVE: + mp_raise_OSError(MP_ENODEV); + case AIRLIFT_BUSY: + mp_raise_OSError(MP_EBUSY); + case AIRLIFT_INTERRUPTED: + // Nothing was sent. Raise the pending KeyboardInterrupt now. + mp_handle_pending(MP_HANDLE_PENDING_CALLBACKS_AND_EXCEPTIONS); + mp_raise_OSError(MP_EINTR); + case AIRLIFT_BAD_SOCKET: + mp_raise_OSError(MP_EBADF); + case AIRLIFT_TOO_BIG: + if (cmd == AIRLIFT_GET_DATABUF_TCP) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("%q must be <= %d"), MP_QSTR_size, AIRLIFT_MAX_READ); + } + mp_raise_ValueError_varg(MP_ERROR_TEXT("%q length must be <= %d"), MP_QSTR_params, AIRLIFT_MAX_TRANSFER); + case AIRLIFT_TIMEOUT_READY: + case AIRLIFT_TIMEOUT_SELECT: + case AIRLIFT_TIMEOUT_START: + mp_raise_msg(&mp_type_TimeoutError, MP_ERROR_TEXT("Operation timed out")); + case AIRLIFT_ERR_RESPONSE: + case AIRLIFT_BAD_REPLY: + mp_raise_msg(&mp_type_BrokenPipeError, MP_ERROR_TEXT("Received response was invalid")); + case AIRLIFT_REPLY_TOO_BIG: + mp_raise_OSError(MP_ENOBUFS); + } +} + +mp_obj_t common_hal__airlift_transact(uint8_t cmd, const airlift_param_t *params, size_t n_params, + bool param_len_16, int expected_replies, bool reply_len_16) { + airlift_reply_t reply = { + .buf = vm_reply_buf, + .buf_len = sizeof(vm_reply_buf), + .lens = vm_reply_lens, + .max_count = MP_ARRAY_SIZE(vm_reply_lens), + }; + airlift_result_t result = airlift_transact(cmd, params, n_params, param_len_16, &reply, + expected_replies, reply_len_16, true); + raise_for(result, cmd); + + mp_obj_list_t *list = MP_OBJ_TO_PTR(mp_obj_new_list(reply.count, NULL)); + size_t offset = 0; + for (size_t i = 0; i < reply.count; i++) { + list->items[i] = mp_obj_new_bytearray(vm_reply_lens[i], vm_reply_buf + offset); + offset += vm_reply_lens[i]; + } + return MP_OBJ_FROM_PTR(list); +} diff --git a/shared-module/_airlift/network.c b/shared-module/_airlift/network.c new file mode 100644 index 00000000000..e1503919e93 --- /dev/null +++ b/shared-module/_airlift/network.c @@ -0,0 +1,206 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include + +#include "shared-module/_airlift/network.h" +#include "shared-module/_airlift/transport.h" + +#include "py/mpconfig.h" +#include "supervisor/shared/tick.h" + +#define JOIN_TIMEOUT_MS (10000) +#define JOIN_POLL_MS (100) +#define REFRESH_MS (1000) +// How often the background tries to rejoin while disconnected. +#define REJOIN_MS (30000) + +static uint8_t status = AIRLIFT_WL_NO_SHIELD; +static uint32_t ipv4_address; +static uint32_t generation; +static uint64_t refreshed_ms; +static bool refreshed; + +// The network from settings.toml. +static char join_ssid[33]; +static char join_password[64]; +// The core's last join attempt: when, in which generation, and how many WiFi +// commands VM code had sent by then. +static uint64_t join_ms; +static uint32_t join_generation; +static uint32_t join_vm_commands; +static bool join_tried; +// A background join was sent and hasn't finished yet. +static bool joining; + +// Sends a command with 8-bit parameter lengths from background context, and +// reads a reply of `expected` parameters into buf. +static airlift_result_t command(uint8_t cmd, const airlift_param_t *params, size_t n_params, + uint8_t *buf, size_t buf_len, uint16_t *lens, int expected) { + airlift_reply_t reply = { + .buf = buf, .buf_len = buf_len, .lens = lens, .max_count = expected, + }; + airlift_result_t result = airlift_transact(cmd, params, n_params, false, &reply, expected, false, false); + if (result == AIRLIFT_OK && (int)reply.count != expected) { + return AIRLIFT_BAD_REPLY; + } + return result; +} + +static const uint8_t ff = 0xff; +static const airlift_param_t ff_param = { .buf = &ff, .len = 1 }; + +static bool read_status(void) { + uint8_t buf[1]; + uint16_t lens[1]; + if (command(AIRLIFT_GET_CONN_STATUS, NULL, 0, buf, sizeof(buf), lens, 1) != AIRLIFT_OK || lens[0] != 1) { + return false; + } + status = buf[0]; + return true; +} + +static void read_address(void) { + uint8_t buf[12]; + uint16_t lens[3]; + ipv4_address = 0; + if (status == AIRLIFT_WL_CONNECTED && + command(AIRLIFT_GET_IPADDR, &ff_param, 1, buf, sizeof(buf), lens, 3) == AIRLIFT_OK && lens[0] == 4) { + memcpy(&ipv4_address, buf, 4); + } +} + +void airlift_network_refresh(bool force) { + if (!airlift_transport_active()) { + status = AIRLIFT_WL_NO_SHIELD; + ipv4_address = 0; + return; + } + uint64_t now = supervisor_ticks_ms64(); + // A hard reset drops the connection, so the cache is stale. + if (!force && refreshed && generation == airlift_transport_generation() && + now - refreshed_ms < REFRESH_MS) { + return; + } + uint32_t gen = airlift_transport_generation(); + if (!read_status()) { + // Leave the cache alone and try again next time. + return; + } + read_address(); + generation = gen; + refreshed_ms = now; + refreshed = true; +} + +uint8_t airlift_network_status(void) { + if (!airlift_transport_active() || generation != airlift_transport_generation()) { + return airlift_transport_active() ? AIRLIFT_WL_IDLE_STATUS : AIRLIFT_WL_NO_SHIELD; + } + return status; +} + +uint32_t airlift_network_ipv4_address(void) { + return airlift_network_status() == AIRLIFT_WL_CONNECTED ? ipv4_address : 0; +} + +static bool connected_to(const char *ssid) { + if (!read_status() || status != AIRLIFT_WL_CONNECTED) { + return false; + } + uint8_t buf[33]; + uint16_t lens[1]; + if (command(AIRLIFT_GET_CURR_SSID, &ff_param, 1, buf, sizeof(buf), lens, 1) != AIRLIFT_OK) { + return false; + } + return lens[0] == strlen(ssid) && memcmp(buf, ssid, lens[0]) == 0; +} + +// Waits without checking for Ctrl-C, running background tasks. +static void pause_ms(uint32_t ms) { + uint64_t start = supervisor_ticks_ms64(); + while (supervisor_ticks_ms64() - start < ms) { + RUN_BACKGROUND_TASKS; + } +} + +// Sends SET_PASSPHRASE (or SET_NET for an open network). Doesn't wait. +static bool start_join(void) { + join_ms = supervisor_ticks_ms64(); + join_generation = airlift_transport_generation(); + join_vm_commands = airlift_transport_vm_network_commands(); + join_tried = true; + airlift_param_t params[2] = { + { .buf = (const uint8_t *)join_ssid, .len = strlen(join_ssid) }, + { .buf = (const uint8_t *)join_password, .len = strlen(join_password) }, + }; + bool open = join_password[0] == '\0'; + uint8_t buf[1]; + uint16_t lens[1]; + return command(open ? AIRLIFT_SET_NET : AIRLIFT_SET_PASSPHRASE, params, open ? 1 : 2, + buf, sizeof(buf), lens, 1) == AIRLIFT_OK && buf[0] == 1; +} + +bool airlift_network_join(const char *ssid, const char *password) { + if (!airlift_transport_active()) { + return false; + } + strncpy(join_ssid, ssid, sizeof(join_ssid) - 1); + strncpy(join_password, password, sizeof(join_password) - 1); + // Joining again, even the same network, drops every open connection. + if (connected_to(ssid)) { + joining = false; + airlift_network_refresh(true); + return true; + } + if (join_tried && join_generation == airlift_transport_generation()) { + // This already failed once since the last reset. Don't hold up every + // VM start for it; let the background try again soon, even if the last + // VM run managed the connection itself. + join_vm_commands = airlift_transport_vm_network_commands(); + join_ms = supervisor_ticks_ms64() - REJOIN_MS; + joining = false; + airlift_network_refresh(true); + return false; + } + joining = false; + if (start_join()) { + // Like ESP32SPI's connect_AP(), wait out failures too: the status passes + // through other values on the way to connected. + uint64_t start = supervisor_ticks_ms64(); + while (supervisor_ticks_ms64() - start < JOIN_TIMEOUT_MS) { + pause_ms(JOIN_POLL_MS); + if (read_status() && status == AIRLIFT_WL_CONNECTED) { + break; + } + } + } + airlift_network_refresh(true); + return airlift_network_status() == AIRLIFT_WL_CONNECTED; +} + +void airlift_network_maintain(void) { + if (!airlift_transport_active() || join_ssid[0] == '\0') { + return; + } + airlift_network_refresh(false); + if (airlift_network_status() == AIRLIFT_WL_CONNECTED) { + joining = false; + return; + } + uint64_t now = supervisor_ticks_ms64(); + bool was_reset = join_generation != airlift_transport_generation(); + if (joining && !was_reset && now - join_ms < JOIN_TIMEOUT_MS) { + return; + } + joining = false; + // Leave the connection to user code that joined or left a network itself, + // until it resets the ESP32 or the VM ends. + bool vm_managed = join_vm_commands != airlift_transport_vm_network_commands(); + if (was_reset || (!vm_managed && now - join_ms >= REJOIN_MS)) { + joining = start_join(); + } +} diff --git a/shared-module/_airlift/network.h b/shared-module/_airlift/network.h new file mode 100644 index 00000000000..817e84c8466 --- /dev/null +++ b/shared-module/_airlift/network.h @@ -0,0 +1,39 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// The ESP32's WiFi connection, as the core sees it. The status and address are +// cached, so the status bar can read them without a SPI round trip. + +#include +#include + +// nina-fw connection status values, as in ESP32SPI. +#define AIRLIFT_WL_IDLE_STATUS (0) +#define AIRLIFT_WL_NO_SSID_AVAIL (1) +#define AIRLIFT_WL_CONNECTED (3) +#define AIRLIFT_WL_CONNECT_FAILED (4) +#define AIRLIFT_WL_DISCONNECTED (6) +#define AIRLIFT_WL_STOPPED (254) +#define AIRLIFT_WL_NO_SHIELD (255) + +// Sets the network the core keeps the ESP32 on. Called at each VM start. Joins +// it unless already connected, waiting up to 10 seconds the first time since +// the last hard reset; after that, airlift_network_maintain() keeps trying in the +// background. Returns true when connected. Never raises. +bool airlift_network_join(const char *ssid, const char *password); +// Called from the background. Rejoins without waiting after a hard reset, and +// every 30 seconds while disconnected, unless VM code has joined or left a +// network itself since the core last tried. +void airlift_network_maintain(void); +// Re-reads the status and address, at most once a second unless forced. Call it +// only where an SPI command may run. +void airlift_network_refresh(bool force); +// The cached status. AIRLIFT_WL_NO_SHIELD when the core doesn't own the ESP32. +uint8_t airlift_network_status(void); +// The cached IPv4 address in network byte order, or 0 when not connected. +uint32_t airlift_network_ipv4_address(void); diff --git a/shared-module/_airlift/socketpool.c b/shared-module/_airlift/socketpool.c new file mode 100644 index 00000000000..2954a6c8da7 --- /dev/null +++ b/shared-module/_airlift/socketpool.c @@ -0,0 +1,730 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "py/mpconfig.h" + +#if CIRCUITPY_SOCKETPOOL + +#include + +#include "shared-module/_airlift/socketpool.h" +#include "shared-module/_airlift/network.h" +#include "shared-module/_airlift/transport.h" + +#include "py/mperrno.h" +#include "py/runtime.h" +#include "shared/runtime/interrupt_char.h" +#include "shared-bindings/socketpool/__init__.h" +#include "shared-bindings/socketpool/Socket.h" +#include "shared-bindings/socketpool/SocketPool.h" +#include "supervisor/port.h" +#include "supervisor/shared/tick.h" +#include "supervisor/workflow.h" + +// Background pass intervals, while a client is connected and while only the +// listening socket is open. +#define POLL_ACTIVE_MS (20) +#define POLL_IDLE_MS (100) +// The idle interval when nina-fw signals data ready on GPIO0. A pass then only +// keeps the WiFi status current. +#define POLL_IDLE_DATA_READY_MS (500) +// Shortest time between passes when data ready rises. +#define POLL_MIN_MS (5) +// How long a socket's connection state is trusted before asking the ESP32 again. +// Web workflow asks several times per pass. +#define CONNECTED_CACHE_MS (10) +// How long to wait before asking the ESP32 for data again, after it had none. +// Without this, a loop polling the serial websocket would keep the bus busy. +#define AVAIL_RETRY_MS (2) +// How long close() waits without progress for the ESP32 to take the rest of the +// TX buffer. +#define DRAIN_TIMEOUT_MS (1000) + +#define TCP_MODE (0) +#define SOCKET_CLOSED (0) +#define SOCKET_ESTABLISHED (4) + +const mp_obj_base_t airlift_socketpool_interface = { &mp_type_object }; + +// The open socket object for each ESP32 socket number. +static socketpool_socket_obj_t *by_num[CIRCUITPY_AIRLIFT_MAX_SOCKETS]; +// Sockets closed when the ESP32 couldn't be reached. They are stopped in the +// next background pass. +static uint8_t stop_pending; +static uint32_t stop_pending_generation; +// A listener the core closed. nina-fw can't stop a listener, so it is left +// running and handed back to the next listen() on the same port. +static uint8_t parked_num = AIRLIFT_NO_SOCKET; +static uint16_t parked_port; +static uint32_t parked_generation; + +static volatile bool poll_wanted; +static volatile uint32_t poll_countdown; +static volatile uint32_t ms_since_pass; +static bool last_data_ready; +static bool tick_enabled; + +static bool is_open(const socketpool_socket_obj_t *self) { + return self->num != AIRLIFT_NO_SOCKET && airlift_transport_active() && + self->generation == airlift_transport_generation(); +} + +// A command can be sent now. It can't while another one is in flight, which +// happens when this is called from a background task run during its waits. +static bool can_transact(void) { + return airlift_transport_active() && !airlift_transport_busy(); +} + +static void set_num(socketpool_socket_obj_t *self, uint8_t num) { + self->num = num; + self->generation = airlift_transport_generation(); + by_num[num] = self; + airlift_transport_set_owned(num, true); +} + +// Forgets the socket number without telling the ESP32. +static void forget(socketpool_socket_obj_t *self) { + if (self->num < CIRCUITPY_AIRLIFT_MAX_SOCKETS && by_num[self->num] == self) { + by_num[self->num] = NULL; + // After a hard reset the number may belong to someone else. + if (self->generation == airlift_transport_generation()) { + airlift_transport_set_owned(self->num, false); + } + } + self->num = AIRLIFT_NO_SOCKET; + self->listening = false; + self->connected = false; + self->connected_valid = false; + self->rx_head = 0; + self->rx_len = 0; + self->tx_len = 0; +} + +// Sends a command about one socket and reads its one-parameter reply. *reply_len +// is the reply's length. +static airlift_result_t command(uint8_t cmd, const airlift_param_t *params, size_t n_params, + bool param_len_16, uint8_t *buf, size_t buf_len, bool reply_len_16, size_t *reply_len) { + uint16_t lens[1]; + airlift_reply_t reply = { .buf = buf, .buf_len = buf_len, .lens = lens, .max_count = 1 }; + airlift_result_t result = airlift_transact(cmd, params, n_params, param_len_16, &reply, 1, + reply_len_16, false); + *reply_len = reply.count == 1 ? lens[0] : 0; + return result; +} + +static airlift_result_t socket_command(uint8_t cmd, uint8_t num, uint8_t *buf, size_t buf_len, + size_t *reply_len) { + airlift_param_t param = { .buf = &num, .len = 1 }; + return command(cmd, ¶m, 1, false, buf, buf_len, false, reply_len); +} + +static uint16_t le16(const uint8_t *buf, size_t len) { + return len >= 2 ? buf[0] | (buf[1] << 8) : (len == 1 ? buf[0] : 0); +} + +static bool stop(uint8_t num) { + uint8_t buf[1]; + size_t len; + return socket_command(AIRLIFT_STOP_CLIENT_TCP, num, buf, sizeof(buf), &len) == AIRLIFT_OK; +} + +// Stops the connection and forgets the number. If the ESP32 can't be reached, +// it is stopped in the next background pass. +static void stop_and_forget(socketpool_socket_obj_t *self) { + uint8_t num = self->num; + bool stopped = can_transact() && stop(num); + forget(self); + if (!stopped) { + // Until then it stays the core's, so airlift_user_reset() doesn't stop it + // after someone else is given it. + airlift_transport_set_owned(num, true); + if (stop_pending == 0) { + stop_pending_generation = airlift_transport_generation(); + } + stop_pending |= 1 << num; + } +} + +// Sends the TX buffer. Returns 0 when it's empty, -MP_EAGAIN if the ESP32 can't +// be reached right now, -MP_ENOBUFS if the ESP32 had no room for all of it (the +// rest stays here), or -MP_ENOTCONN if the connection is gone or was ended +// because the send failed. +static int flush(socketpool_socket_obj_t *self) { + if (self->tx_len == 0) { + return 0; + } + if (!can_transact()) { + return -MP_EAGAIN; + } + airlift_param_t params[2] = { + { .buf = &self->num, .len = 1 }, + { .buf = self->tx, .len = self->tx_len }, + }; + uint8_t buf[2]; + size_t len; + airlift_result_t result = command(AIRLIFT_SEND_DATA_TCP, params, 2, true, buf, sizeof(buf), false, &len); + if (result == AIRLIFT_BUSY) { + return -MP_EAGAIN; + } + // The reply is the count sent. DATA_SENT_TCP isn't asked: it says yes even + // when nothing went out. + size_t sent = result == AIRLIFT_OK ? MIN(le16(buf, len), self->tx_len) : 0; + if (sent == self->tx_len) { + self->tx_len = 0; + return 0; + } + // nina-fw's send doesn't wait for room in its TCP send buffer. + if (sent > 0) { + memmove(self->tx, self->tx + sent, self->tx_len - sent); + self->tx_len -= sent; + return -MP_ENOBUFS; + } + if (result != AIRLIFT_OK) { + // Whether the ESP32 sent any of it is unknown, so the stream may have a + // hole now. End the connection rather than carry on. + self->tx_len = 0; + stop_and_forget(self); + return -MP_ENOTCONN; + } + // Nothing went out: the ESP32 has no room, or the connection is gone. + self->connected_valid = false; + if (common_hal_socketpool_socket_get_connected(self)) { + return -MP_ENOBUFS; + } + self->tx_len = 0; + return -MP_ENOTCONN; +} + +// Sends all of the TX buffer, waiting while the ESP32 has no room for it. +static void drain(socketpool_socket_obj_t *self) { + uint64_t progress_ms = supervisor_ticks_ms64(); + uint16_t left = self->tx_len; + while (flush(self) == -MP_ENOBUFS) { + uint64_t now = supervisor_ticks_ms64(); + if (self->tx_len < left) { + left = self->tx_len; + progress_ms = now; + } else if (now - progress_ms >= DRAIN_TIMEOUT_MS) { + break; + } + port_task_sleep_ms(1); + } +} + +static void flush_all(void) { + for (uint8_t num = 0; num < CIRCUITPY_AIRLIFT_MAX_SOCKETS; num++) { + socketpool_socket_obj_t *sock = by_num[num]; + if (sock != NULL && is_open(sock) && sock->tx_len > 0) { + flush(sock); + } + } +} + +static bool any_client_open(void) { + for (size_t i = 0; i < CIRCUITPY_AIRLIFT_MAX_SOCKETS; i++) { + if (by_num[i] != NULL && is_open(by_num[i]) && !by_num[i]->listening) { + return true; + } + } + return false; +} + +void airlift_socketpool_poll_resume(void) { + if (!tick_enabled) { + supervisor_enable_tick(); + tick_enabled = true; + } + if (any_client_open()) { + poll_countdown = POLL_ACTIVE_MS; + } else if (airlift_transport_has_data_ready()) { + poll_countdown = POLL_IDLE_DATA_READY_MS; + } else { + poll_countdown = POLL_IDLE_MS; + } + ms_since_pass = 0; + poll_wanted = true; +} + +void airlift_socketpool_tick(void) { + if (!poll_wanted) { + return; + } + ms_since_pass++; + if (airlift_transport_has_data_ready()) { + // A pass runs soon after data ready rises. While it stays high, for + // example because user code hasn't read its socket, the usual intervals + // apply, but never the long idle one. + bool ready = airlift_transport_data_ready(); + if (ready && !last_data_ready) { + uint32_t soonest = ms_since_pass >= POLL_MIN_MS ? 1 : POLL_MIN_MS - ms_since_pass; + poll_countdown = MIN(poll_countdown, soonest); + } else if (ready) { + poll_countdown = MIN(poll_countdown, POLL_IDLE_MS); + } + last_data_ready = ready; + } + if (--poll_countdown == 0) { + poll_wanted = false; + supervisor_workflow_request_background(); + } +} + +bool airlift_socketpool_background(void) { + if (!can_transact() || !airlift_transport_bus_free()) { + return false; + } + airlift_network_maintain(); + if (stop_pending_generation != airlift_transport_generation()) { + stop_pending = 0; + } + for (uint8_t num = 0; num < CIRCUITPY_AIRLIFT_MAX_SOCKETS; num++) { + if ((stop_pending & (1 << num)) && stop(num)) { + stop_pending &= ~(1 << num); + airlift_transport_set_owned(num, false); + } + } + // Serial output written by the VM since the last pass. + flush_all(); + return true; +} + +void airlift_socketpool_background_done(void) { + // TCP_NODELAY doesn't send right away (most replies would go out in many + // small pieces), so this sends what the pass left. + if (can_transact()) { + flush_all(); + } +} + +void socketpool_user_reset(void) { + // Python can't make AirLift sockets yet, so there are none to close. +} + +void common_hal_socketpool_socketpool_construct(socketpool_socketpool_obj_t *self, mp_obj_t network_interface) { + if (network_interface != MP_OBJ_FROM_PTR(&airlift_socketpool_interface)) { + mp_arg_error_invalid(MP_QSTR_radio); + } +} + +bool socketpool_socket(socketpool_socketpool_obj_t *self, + socketpool_socketpool_addressfamily_t family, socketpool_socketpool_sock_t type, + int proto, socketpool_socket_obj_t *sock) { + if (family != SOCKETPOOL_AF_INET || type != SOCKETPOOL_SOCK_STREAM) { + return false; + } + sock->base.type = &socketpool_socket_type; + sock->pool = self; + sock->num = AIRLIFT_NO_SOCKET; + sock->type = type; + sock->timeout_ms = (uint32_t)-1; + sock->port = 0; + sock->next_avail_ms = 0; + forget(sock); + return true; +} + +socketpool_socket_obj_t *common_hal_socketpool_socket(socketpool_socketpool_obj_t *self, + socketpool_socketpool_addressfamily_t family, socketpool_socketpool_sock_t type, int proto) { + socketpool_socket_obj_t *sock = mp_obj_malloc_with_finaliser(socketpool_socket_obj_t, &socketpool_socket_type); + if (!socketpool_socket(self, family, type, proto, sock)) { + mp_raise_NotImplementedError(NULL); + } + return sock; +} + +mp_obj_t common_hal_socketpool_getaddrinfo_raise(socketpool_socketpool_obj_t *self, const char *host, int port, int family, int type, int proto, int flags) { + mp_raise_NotImplementedError(NULL); +} + +// Waits for a VM caller with a timeout. Returns false when it's time to give up. +static bool keep_waiting(const socketpool_socket_obj_t *self, uint64_t start) { + if (self->timeout_ms == 0 || mp_hal_is_interrupted()) { + return false; + } + if (self->timeout_ms != (uint32_t)-1 && supervisor_ticks_ms64() - start >= self->timeout_ms) { + return false; + } + RUN_BACKGROUND_TASKS; + return true; +} + +static int try_accept(socketpool_socket_obj_t *self, socketpool_socket_obj_t *accepted) { + // A VM GET_SOCKET is about to use the lowest free number, which is the one + // nina-fw would give a new client. + if (!can_transact() || airlift_transport_vm_allocating()) { + return -MP_EAGAIN; + } + uint8_t buf[2]; + size_t len; + // On a listening socket, AVAIL_DATA_TCP accepts a waiting client, and + // replies with its socket number. + if (socket_command(AIRLIFT_AVAIL_DATA_TCP, self->num, buf, sizeof(buf), &len) != AIRLIFT_OK) { + return -MP_EAGAIN; + } + uint16_t num = le16(buf, len); + if (num >= CIRCUITPY_AIRLIFT_MAX_SOCKETS) { + return -MP_EAGAIN; + } + if (!common_hal_socketpool_socket_get_closed(accepted)) { + common_hal_socketpool_socket_close(accepted); + } + accepted->base.type = &socketpool_socket_type; + accepted->pool = self->pool; + accepted->type = SOCKETPOOL_SOCK_STREAM; + accepted->timeout_ms = self->timeout_ms; + accepted->port = self->port; + accepted->next_avail_ms = 0; + forget(accepted); + set_num(accepted, num); + accepted->connected = true; + accepted->connected_valid = true; + accepted->connected_ms = supervisor_ticks_ms64(); + return 1; +} + +int socketpool_socket_accept(socketpool_socket_obj_t *self, mp_obj_t *peer_out, socketpool_socket_obj_t *accepted) { + if (!is_open(self) || !self->listening) { + return -MP_EBADF; + } + uint64_t start = supervisor_ticks_ms64(); + int result; + while ((result = try_accept(self, accepted)) == -MP_EAGAIN && keep_waiting(self, start)) { + } + // nina-fw doesn't say who the peer is. + if (result > 0 && peer_out != NULL) { + *peer_out = mp_const_none; + } + return result; +} + +socketpool_socket_obj_t *common_hal_socketpool_socket_accept(socketpool_socket_obj_t *self, mp_obj_t *peer_out) { + socketpool_socket_obj_t *accepted = mp_obj_malloc_with_finaliser(socketpool_socket_obj_t, &socketpool_socket_type); + accepted->num = AIRLIFT_NO_SOCKET; + int result = socketpool_socket_accept(self, peer_out, accepted); + if (result < 0) { + m_del_obj(socketpool_socket_obj_t, accepted); + mp_raise_OSError(-result); + } + return accepted; +} + +size_t common_hal_socketpool_socket_bind(socketpool_socket_obj_t *self, const char *host, size_t hostlen, uint32_t port) { + // nina-fw listens on every interface. + self->port = port; + return 0; +} + +void socketpool_socket_close(socketpool_socket_obj_t *self) { + if (!is_open(self)) { + forget(self); + return; + } + uint8_t num = self->num; + if (self->listening) { + // STOP_CLIENT_TCP would free the number but leave the listener + // running, so keep it, still owned, for the next listen() on this port. + if (parked_num != AIRLIFT_NO_SOCKET && parked_generation == airlift_transport_generation()) { + // Only one is kept. The other is stopped at the end of the VM run. + airlift_transport_set_owned(parked_num, false); + airlift_transport_leaked_listener(parked_num); + } + parked_num = num; + parked_port = self->port; + parked_generation = airlift_transport_generation(); + by_num[num] = NULL; + self->num = AIRLIFT_NO_SOCKET; + self->listening = false; + return; + } + // Web workflow closes as soon as a reply is written, so this is often the + // end of it. + drain(self); + // A failed send may have ended it already. + if (is_open(self)) { + stop_and_forget(self); + } +} + +void common_hal_socketpool_socket_close(socketpool_socket_obj_t *self) { + socketpool_socket_close(self); +} + +void common_hal_socketpool_socket_connect(socketpool_socket_obj_t *self, const char *host, size_t hostlen, uint32_t port) { + mp_raise_NotImplementedError(NULL); +} + +bool common_hal_socketpool_socket_get_closed(socketpool_socket_obj_t *self) { + return !is_open(self); +} + +bool common_hal_socketpool_socket_get_connected(socketpool_socket_obj_t *self) { + if (!is_open(self) || self->listening) { + return false; + } + uint64_t now = supervisor_ticks_ms64(); + if ((self->connected_valid && now - self->connected_ms < CONNECTED_CACHE_MS) || !can_transact()) { + return self->connected; + } + uint8_t buf[1]; + size_t len; + if (socket_command(AIRLIFT_GET_CLIENT_STATE_TCP, self->num, buf, sizeof(buf), &len) != AIRLIFT_OK || + len != 1) { + return self->connected; + } + self->connected_ms = now; + self->connected_valid = true; + self->connected = buf[0] == SOCKET_ESTABLISHED; + if (buf[0] == SOCKET_CLOSED) { + // nina-fw 3.1.0 to 3.3.0 don't free the number of a client a server + // accepted when asked its state (3.3.0 frees only clients it connected + // itself), so each client that hangs up first would keep its number + // until a hard reset. Once all six are kept, every new connection is + // reset. STOP_CLIENT_TCP frees it, and does nothing to a free number. + stop_and_forget(self); + } + return self->connected; +} + +mp_uint_t common_hal_socketpool_socket_get_timeout(socketpool_socket_obj_t *self) { + return self->timeout_ms; +} + +mp_int_t common_hal_socketpool_socket_get_type(socketpool_socket_obj_t *self) { + return self->type; +} + +bool common_hal_socketpool_socket_listen(socketpool_socket_obj_t *self, int backlog) { + if (self->type != SOCKETPOOL_SOCK_STREAM || is_open(self) || !can_transact() || + airlift_transport_vm_allocating()) { + return false; + } + if (parked_num != AIRLIFT_NO_SOCKET && parked_generation == airlift_transport_generation() && + parked_port == self->port) { + // Still listening. + set_num(self, parked_num); + self->listening = true; + parked_num = AIRLIFT_NO_SOCKET; + return true; + } + // START_SERVER_TCP before WiFi is up hangs nina-fw until a hard reset. + airlift_network_refresh(false); + if (airlift_network_status() != AIRLIFT_WL_CONNECTED) { + return false; + } + // GET_SOCKET doesn't reserve the number. START_SERVER_TCP does. + uint8_t buf[1]; + size_t len; + if (command(AIRLIFT_GET_SOCKET, NULL, 0, false, buf, sizeof(buf), false, &len) != AIRLIFT_OK || + len != 1 || buf[0] >= CIRCUITPY_AIRLIFT_MAX_SOCKETS) { + return false; + } + uint8_t num = buf[0]; + uint8_t port[2] = { self->port >> 8, self->port & 0xff }; + uint8_t mode = TCP_MODE; + airlift_param_t params[3] = { + { .buf = port, .len = 2 }, + { .buf = &num, .len = 1 }, + { .buf = &mode, .len = 1 }, + }; + // A reply of 0 means the port is in use. + if (command(AIRLIFT_START_SERVER_TCP, params, 3, false, buf, sizeof(buf), false, &len) != AIRLIFT_OK || + len != 1 || buf[0] != 1) { + return false; + } + set_num(self, num); + self->listening = true; + return true; +} + +mp_uint_t common_hal_socketpool_socket_recvfrom_into(socketpool_socket_obj_t *self, + uint8_t *buf, uint32_t len, mp_obj_t *peer_out) { + mp_raise_NotImplementedError(NULL); +} + +// What a read returns when a command fails. Only a busy transport is worth +// trying again; other failures would repeat, and once they reset the ESP32 the +// socket is gone. +static int recv_failed(socketpool_socket_obj_t *self, airlift_result_t result) { + if (result == AIRLIFT_BUSY || result == AIRLIFT_INTERRUPTED) { + return -MP_EAGAIN; + } + return is_open(self) ? -MP_EIO : -MP_ENOTCONN; +} + +// Reads from the ESP32. Large reads go straight into buf; small ones fill the +// RX buffer first. +static int try_recv(socketpool_socket_obj_t *self, uint8_t *buf, uint32_t len) { + if (self->rx_len > 0) { + size_t n = MIN(len, self->rx_len); + memcpy(buf, self->rx + self->rx_head, n); + self->rx_head += n; + self->rx_len -= n; + return n; + } + if (!can_transact()) { + return -MP_EAGAIN; + } + // The peer may be waiting for what's buffered before it sends more. + flush(self); + uint64_t now = supervisor_ticks_ms64(); + if (now < self->next_avail_ms) { + return -MP_EAGAIN; + } + uint8_t avail_buf[2]; + size_t reply_len; + airlift_result_t result = socket_command(AIRLIFT_AVAIL_DATA_TCP, self->num, avail_buf, sizeof(avail_buf), &reply_len); + if (result != AIRLIFT_OK) { + return recv_failed(self, result); + } + uint16_t avail = le16(avail_buf, reply_len); + if (avail == 0) { + self->next_avail_ms = now + AVAIL_RETRY_MS; + return common_hal_socketpool_socket_get_connected(self) ? -MP_EAGAIN : -MP_ENOTCONN; + } + bool direct = len >= AIRLIFT_SOCKET_RX_SIZE; + uint8_t *dest = direct ? buf : self->rx; + uint16_t want = MIN(avail, direct ? MIN(len, AIRLIFT_MAX_READ) : AIRLIFT_SOCKET_RX_SIZE); + uint8_t want_le[2] = { want & 0xff, want >> 8 }; + airlift_param_t params[2] = { + { .buf = &self->num, .len = 1 }, + { .buf = want_le, .len = 2 }, + }; + result = command(AIRLIFT_GET_DATABUF_TCP, params, 2, true, dest, want, true, &reply_len); + if (result != AIRLIFT_OK) { + return recv_failed(self, result); + } + if (reply_len == 0) { + return -MP_EAGAIN; + } + if (direct) { + return reply_len; + } + self->rx_head = 0; + self->rx_len = reply_len; + return try_recv(self, buf, len); +} + +int socketpool_socket_recv_into(socketpool_socket_obj_t *self, const uint8_t *buf, uint32_t len) { + if (!is_open(self) || self->listening) { + return -MP_ENOTCONN; + } + if (len == 0) { + return 0; + } + uint64_t start = supervisor_ticks_ms64(); + int result; + while ((result = try_recv(self, (uint8_t *)buf, len)) == -MP_EAGAIN && keep_waiting(self, start)) { + } + return result; +} + +mp_uint_t common_hal_socketpool_socket_recv_into(socketpool_socket_obj_t *self, const uint8_t *buf, uint32_t len) { + int received = socketpool_socket_recv_into(self, buf, len); + if (received < 0) { + mp_raise_OSError(-received); + } + return received; +} + +int socketpool_socket_send(socketpool_socket_obj_t *self, const uint8_t *buf, uint32_t len) { + if (!is_open(self) || self->listening) { + return -MP_ENOTCONN; + } + size_t total = 0; + while (total < len) { + if (self->tx_len == AIRLIFT_SOCKET_TX_SIZE) { + int result = flush(self); + if (result == -MP_EAGAIN) { + // Another command is in flight (this is a background task run + // during its waits) or another device holds the bus. Waiting + // here would never end, so the rest is dropped. + return len; + } + if (result == -MP_ENOTCONN) { + return result; + } + if (self->tx_len == AIRLIFT_SOCKET_TX_SIZE) { + // The ESP32 has no room yet. The caller tries again. + return total > 0 ? (int)total : -MP_EAGAIN; + } + } + size_t n = MIN(len - total, (size_t)(AIRLIFT_SOCKET_TX_SIZE - self->tx_len)); + memcpy(self->tx + self->tx_len, buf + total, n); + self->tx_len += n; + total += n; + } + return len; +} + +mp_uint_t common_hal_socketpool_socket_send(socketpool_socket_obj_t *self, const uint8_t *buf, uint32_t len) { + int sent = socketpool_socket_send(self, buf, len); + if (sent < 0) { + mp_raise_OSError(-sent); + } + return sent; +} + +mp_uint_t common_hal_socketpool_socket_sendto(socketpool_socket_obj_t *self, + const char *host, size_t hostlen, uint32_t port, const uint8_t *buf, uint32_t len) { + mp_raise_NotImplementedError(NULL); +} + +void common_hal_socketpool_socket_settimeout(socketpool_socket_obj_t *self, uint32_t timeout_ms) { + self->timeout_ms = timeout_ms; +} + +int common_hal_socketpool_socket_setsockopt(socketpool_socket_obj_t *self, int level, int optname, const void *value, size_t optlen) { + if (level != SOCKETPOOL_IPPROTO_TCP || optname != SOCKETPOOL_TCP_NODELAY || optlen != sizeof(int)) { + return -MP_EOPNOTSUPP; + } + // Accepted, but nothing is sent right away: the buffer goes out before + // the next read and at the end of the background pass. + return 0; +} + +bool common_hal_socketpool_readable(socketpool_socket_obj_t *self) { + if (!is_open(self) || self->listening) { + return false; + } + if (self->rx_len > 0) { + return true; + } + flush(self); + uint8_t buf[2]; + size_t len; + return can_transact() && + socket_command(AIRLIFT_AVAIL_DATA_TCP, self->num, buf, sizeof(buf), &len) == AIRLIFT_OK && + le16(buf, len) > 0; +} + +bool common_hal_socketpool_writable(socketpool_socket_obj_t *self) { + return common_hal_socketpool_socket_get_connected(self); +} + +void socketpool_socket_move(socketpool_socket_obj_t *self, socketpool_socket_obj_t *sock) { + *sock = *self; + if (sock->num < CIRCUITPY_AIRLIFT_MAX_SOCKETS && by_num[sock->num] == self) { + by_num[sock->num] = sock; + } + self->num = AIRLIFT_NO_SOCKET; + self->tx_len = 0; + self->rx_len = 0; +} + +void socketpool_socket_reset(socketpool_socket_obj_t *self) { + if (self->base.type == &socketpool_socket_type) { + return; + } + self->base.type = &socketpool_socket_type; + self->num = AIRLIFT_NO_SOCKET; + self->listening = false; + self->connected = false; + self->connected_valid = false; + self->rx_len = 0; + self->tx_len = 0; +} + +#endif // CIRCUITPY_SOCKETPOOL diff --git a/shared-module/_airlift/socketpool.h b/shared-module/_airlift/socketpool.h new file mode 100644 index 00000000000..b3de4755137 --- /dev/null +++ b/shared-module/_airlift/socketpool.h @@ -0,0 +1,74 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// socketpool common-hal on an ESP32 co-processor running nina-fw. Ports include +// this from common-hal/socketpool/{Socket,SocketPool}.h when CIRCUITPY_AIRLIFT is on. +// Only TCP is supported, and only the core uses it for now (web workflow): +// SocketPool() accepts only airlift_socketpool_interface, which Python can't reach. + +#include +#include + +#include "py/obj.h" +#include "shared-module/_airlift/transport.h" + +// Bytes read from the ESP32 at a time. Web workflow reads headers a byte at a time. +#ifndef AIRLIFT_SOCKET_RX_SIZE +#define AIRLIFT_SOCKET_RX_SIZE (512) +#endif +// Small sends are collected here and sent together when full, before a read, +// on close, and at the end of each web workflow background pass. +#ifndef AIRLIFT_SOCKET_TX_SIZE +#define AIRLIFT_SOCKET_TX_SIZE (2048) +#endif + +typedef struct { + mp_obj_base_t base; +} socketpool_socketpool_obj_t; + +typedef struct { + mp_obj_base_t base; + socketpool_socketpool_obj_t *pool; + // When `connected` was last read from the ESP32. + uint64_t connected_ms; + // Don't ask the ESP32 for data again before this, after it last had none. + uint64_t next_avail_ms; + // airlift_transport_generation() when the socket was opened. After a hard + // reset the socket no longer exists. + uint32_t generation; + uint32_t timeout_ms; + uint16_t port; + uint16_t rx_head; + uint16_t rx_len; + uint16_t tx_len; + // The ESP32's socket number, or AIRLIFT_NO_SOCKET when closed. + uint8_t num; + uint8_t type; + bool listening; + bool connected; + bool connected_valid; + uint8_t rx[AIRLIFT_SOCKET_RX_SIZE]; + uint8_t tx[AIRLIFT_SOCKET_TX_SIZE]; +} socketpool_socket_obj_t; + +// The network interface object the core passes to SocketPool's constructor. +extern const mp_obj_base_t airlift_socketpool_interface; + +// AirLift has no callbacks, so web workflow is polled: this schedules its next +// background pass, sooner while a client is connected. +void airlift_socketpool_poll_resume(void); +#define socketpool_socket_poll_resume() airlift_socketpool_poll_resume() +// Called from supervisor_tick() every millisecond. +void airlift_socketpool_tick(void); +// Called at the start of each web workflow background pass. Refreshes the WiFi +// status, sends what's waiting in the TX buffers, and returns false if the ESP32 +// can't be used right now, so the pass should be skipped. +bool airlift_socketpool_background(void); +// Called at the end of each web workflow background pass. Sends what's waiting +// in the TX buffers. +void airlift_socketpool_background_done(void); diff --git a/shared-module/_airlift/transport.c b/shared-module/_airlift/transport.c new file mode 100644 index 00000000000..bf46c328dc5 --- /dev/null +++ b/shared-module/_airlift/transport.c @@ -0,0 +1,645 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include + +#include "shared-module/_airlift/transport.h" + +#include "py/mpconfig.h" +#include "py/obj.h" +#include "shared/runtime/interrupt_char.h" +#include "shared-bindings/board/__init__.h" +#include "shared-bindings/digitalio/DigitalInOut.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "supervisor/shared/tick.h" + +#if CIRCUITPY_TINYUSB +#include "supervisor/usb.h" +#endif + +#ifndef CIRCUITPY_AIRLIFT_SPI_INDEX +#define CIRCUITPY_AIRLIFT_SPI_INDEX (0) +#endif + +#define START_CMD (0xE0) +#define END_CMD (0xEE) +#define ERR_CMD (0xEF) +#define REPLY_FLAG (0x80) + +// The same values as ESP32SPI. +#define SPI_BAUDRATE (8000000) +#define READY_TIMEOUT_MS (10000) +#define SELECT_TIMEOUT_MS (1000) +#define START_TRIES (10) +#define START_RETRY_MS (10) + +// How long a VM caller waits for someone else to unlock the SPI bus. +#define BUS_LOCK_TIMEOUT_MS (1000) +// How long a VM GET_SOCKET holds off the core from taking a socket. +#define VM_ALLOCATING_TIMEOUT_MS (1000) +// How many core commands in a row may get a garbled reply before the ESP is +// reset. +#define CORE_FAILURES_BEFORE_RESET (3) +// How many times a command is sent when the ESP says it arrived garbled. +#define COMMAND_TRIES (2) + +static busio_spi_obj_t *spi; +static digitalio_digitalinout_obj_t cs; +static digitalio_digitalinout_obj_t ready; +static digitalio_digitalinout_obj_t reset; +#ifdef CIRCUITPY_AIRLIFT_GPIO0 +static digitalio_digitalinout_obj_t gpio0; +#endif +static bool active; +static volatile bool busy; +static uint32_t generation; +// Sockets that VM code started a server on since the last hard reset. +static uint8_t vm_listening; +// Sockets the core has open. airlift_user_reset() leaves these alone. +static uint8_t core_owned; +// When VM code last did GET_SOCKET without using the number yet. +static bool vm_allocating; +static uint64_t vm_allocating_ms; +static uint32_t vm_network_commands; +static uint8_t core_failures; + +// Commands are built here and sent with one SPI write, as ESP32SPI does. +static uint8_t tx_buf[AIRLIFT_MAX_TRANSFER]; + +// Web workflow sends its commands from a background task, where +// RUN_BACKGROUND_TASKS does nothing because background tasks don't nest. Run +// USB directly too, so the host doesn't see the board stop answering while the +// ESP takes up to READY_TIMEOUT_MS to reply. +static void run_background_tasks(void) { + RUN_BACKGROUND_TASKS; + #if CIRCUITPY_TINYUSB + usb_background(); + #endif +} + +// Waits without checking for Ctrl-C, running background tasks. +static void pause_ms(uint32_t ms) { + uint64_t start = supervisor_ticks_ms64(); + while (supervisor_ticks_ms64() - start < ms) { + run_background_tasks(); + } +} + +// Waits for the ESP's BUSY/READY line to read `level`. Background tasks run at +// most once per millisecond, so a quick handshake isn't slowed down by them. +static bool wait_ready(bool level, uint32_t timeout_ms, bool interruptible, bool *interrupted) { + uint64_t start = supervisor_ticks_ms64(); + uint64_t last = start; + while (common_hal_digitalio_digitalinout_get_value(&ready) != level) { + uint64_t now = supervisor_ticks_ms64(); + if (now - start >= timeout_ms) { + return false; + } + if (now != last) { + last = now; + if (interruptible && mp_hal_is_interrupted()) { + *interrupted = true; + return false; + } + run_background_tasks(); + } + } + return true; +} + +static airlift_result_t lock_bus(bool wait, bool interruptible) { + if (common_hal_busio_spi_deinited(spi)) { + return AIRLIFT_NOT_ACTIVE; + } + uint64_t start = supervisor_ticks_ms64(); + while (!common_hal_busio_spi_try_lock(spi)) { + if (!wait || supervisor_ticks_ms64() - start >= BUS_LOCK_TIMEOUT_MS) { + return AIRLIFT_BUSY; + } + if (interruptible && mp_hal_is_interrupted()) { + return AIRLIFT_INTERRUPTED; + } + run_background_tasks(); + } + // Other devices on the bus may have changed its settings. + common_hal_busio_spi_configure(spi, SPI_BAUDRATE, 0, 0, 8); + common_hal_digitalio_digitalinout_set_value(&cs, false); + return AIRLIFT_OK; +} + +static void unlock_bus(void) { + common_hal_digitalio_digitalinout_set_value(&cs, true); + common_hal_busio_spi_unlock(spi); +} + +static uint8_t read_byte(void) { + uint8_t b = 0; + common_hal_busio_spi_read(spi, &b, 1, 0); + return b; +} + +static bool check_byte(uint8_t expected) { + return read_byte() == expected; +} + +static void discard(size_t len) { + uint8_t scratch[32]; + while (len > 0) { + size_t n = MIN(len, sizeof(scratch)); + common_hal_busio_spi_read(spi, scratch, n, 0); + len -= n; + } +} + +// Which parameter holds the socket number, or -1 for commands without one. +static int socket_param(uint8_t cmd, size_t n_params) { + switch (cmd) { + case 0x28: // START_SERVER_TCP: [ip,] port, socket, mode + case 0x2D: // START_CLIENT_TCP: [host,] ip, port, socket, mode + return n_params >= 2 ? (int)n_params - 2 : -1; + case 0x29: // GET_STATE_TCP + case 0x2A: // DATA_SENT_TCP + case 0x2B: // AVAIL_DATA_TCP + case 0x2C: // GET_DATA_TCP + case 0x2E: // STOP_CLIENT_TCP + case 0x2F: // GET_CLIENT_STATE_TCP + case 0x39: // SEND_UDP_DATA + case 0x3A: // GET_REMOTE_DATA + case 0x44: // SEND_DATA_TCP + case 0x45: // GET_DATABUF_TCP + case 0x46: // INSERT_DATABUF_TCP + return 0; + default: + return -1; + } +} + +// Checks the command and builds it in tx_buf. Returns its padded length in *len. +static airlift_result_t build_command(uint8_t cmd, const airlift_param_t *params, size_t n_params, + bool param_len_16, size_t *len) { + int sock = socket_param(cmd, n_params); + if (sock >= 0 && (params[sock].len < 1 || params[sock].buf[0] >= CIRCUITPY_AIRLIFT_MAX_SOCKETS)) { + return AIRLIFT_BAD_SOCKET; + } + if (cmd == AIRLIFT_GET_DATABUF_TCP && n_params >= 2 && params[1].len == 2 && + (params[1].buf[0] | (params[1].buf[1] << 8)) > AIRLIFT_MAX_READ) { + return AIRLIFT_TOO_BIG; + } + if (n_params > 255) { + return AIRLIFT_TOO_BIG; + } + // START, cmd, count, the params, END. + size_t packet_len = 4; + for (size_t i = 0; i < n_params; i++) { + if (!param_len_16 && params[i].len > 255) { + return AIRLIFT_TOO_BIG; + } + packet_len += params[i].len + (param_len_16 ? 2 : 1); + } + if (packet_len > AIRLIFT_MAX_TRANSFER) { + return AIRLIFT_TOO_BIG; + } + uint8_t *p = tx_buf; + *p++ = START_CMD; + *p++ = cmd & ~REPLY_FLAG; + *p++ = n_params; + for (size_t i = 0; i < n_params; i++) { + if (param_len_16) { + *p++ = params[i].len >> 8; + } + *p++ = params[i].len & 0xff; + memcpy(p, params[i].buf, params[i].len); + p += params[i].len; + } + *p++ = END_CMD; + // Pad to a multiple of 4. AIRLIFT_MAX_TRANSFER is one, so this still fits. + while ((p - tx_buf) % 4 != 0) { + *p++ = 0; + } + *len = p - tx_buf; + return AIRLIFT_OK; +} + +static airlift_result_t send_command(size_t len, bool from_vm) { + bool interrupted = false; + if (!wait_ready(false, READY_TIMEOUT_MS, from_vm, &interrupted)) { + return interrupted ? AIRLIFT_INTERRUPTED : AIRLIFT_TIMEOUT_READY; + } + airlift_result_t result = lock_bus(from_vm, from_vm); + if (result != AIRLIFT_OK) { + return result; + } + if (!wait_ready(true, SELECT_TIMEOUT_MS, false, NULL)) { + unlock_bus(); + return AIRLIFT_TIMEOUT_SELECT; + } + common_hal_busio_spi_write(spi, tx_buf, len); + unlock_bus(); + return AIRLIFT_OK; +} + +static airlift_result_t read_reply(uint8_t cmd, airlift_reply_t *reply, int expected_replies, + bool reply_len_16) { + // Like ESP32SPI's _wait_spi_char(): a few tries for START_CMD. + for (int tries = 1;; tries++) { + uint8_t b = read_byte(); + if (b == ERR_CMD) { + return AIRLIFT_ERR_RESPONSE; + } + if (b == START_CMD) { + break; + } + if (tries == START_TRIES) { + return AIRLIFT_TIMEOUT_START; + } + pause_ms(START_RETRY_MS); + } + if (!check_byte(cmd | REPLY_FLAG)) { + return AIRLIFT_BAD_REPLY; + } + size_t count; + if (expected_replies >= 0) { + if (!check_byte(expected_replies)) { + return AIRLIFT_BAD_REPLY; + } + count = expected_replies; + } else { + count = read_byte(); + } + bool too_big = false; + size_t used = 0; + reply->count = 0; + for (size_t i = 0; i < count; i++) { + size_t len = read_byte(); + if (reply_len_16) { + len = (len << 8) | read_byte(); + } + // Keep reading a reply that doesn't fit, so the framing stays in step. + if (too_big || i >= reply->max_count || used + len > reply->buf_len) { + too_big = true; + discard(len); + continue; + } + if (len > 0) { + common_hal_busio_spi_read(spi, reply->buf + used, len, 0); + } + reply->lens[i] = len; + used += len; + reply->count++; + } + if (!check_byte(END_CMD)) { + return AIRLIFT_BAD_REPLY; + } + return too_big ? AIRLIFT_REPLY_TOO_BIG : AIRLIFT_OK; +} + +static airlift_result_t receive_reply(uint8_t cmd, airlift_reply_t *reply, int expected_replies, + bool reply_len_16) { + // The command has been sent, so the reply is read even after Ctrl-C. + if (!wait_ready(false, READY_TIMEOUT_MS, false, NULL)) { + return AIRLIFT_TIMEOUT_READY; + } + // Wait for the bus even in the background: the ESP has a reply queued. + airlift_result_t result = lock_bus(true, false); + if (result == AIRLIFT_BUSY) { + // The reply can't be read, so the ESP is out of step. Start it over. + airlift_transport_reset(); + } + if (result != AIRLIFT_OK) { + return result; + } + if (!wait_ready(true, SELECT_TIMEOUT_MS, false, NULL)) { + unlock_bus(); + return AIRLIFT_TIMEOUT_SELECT; + } + result = read_reply(cmd, reply, expected_replies, reply_len_16); + unlock_bus(); + return result; +} + +// Answers a VM command about one of the core's sockets without sending it. +// User code can hold a stale number after nina-fw freed it and gave it to the +// core, and stopping or using it would break the core's connection. To user +// code the socket looks closed. Returns false for commands that can be sent. +static bool guard_core_socket(uint8_t cmd, const airlift_param_t *params, size_t n_params, + airlift_reply_t *reply, airlift_result_t *result) { + int sock = socket_param(cmd, n_params); + if (sock < 0 || params[sock].len < 1 || params[sock].buf[0] >= CIRCUITPY_AIRLIFT_MAX_SOCKETS || + !(core_owned & (1 << params[sock].buf[0]))) { + return false; + } + uint8_t value; + switch (cmd) { + case AIRLIFT_STOP_CLIENT_TCP: + value = 1; // Stopped. + break; + case AIRLIFT_GET_CLIENT_STATE_TCP: + value = 0; // CLOSED. + break; + default: + *result = AIRLIFT_BAD_SOCKET; + return true; + } + if (reply->max_count < 1 || reply->buf_len < 1) { + *result = AIRLIFT_REPLY_TOO_BIG; + return true; + } + reply->buf[0] = value; + reply->lens[0] = 1; + reply->count = 1; + *result = AIRLIFT_OK; + return true; +} + +// The core can't raise, so nothing above it notices an ESP that has stopped +// answering or lost step, and every later command fails the same way. A hard +// reset closes the core's sockets, which web workflow then reopens. None of +// the commands the core sends gets ERR_CMD from a working ESP. +static void check_core_result(airlift_result_t result) { + switch (result) { + case AIRLIFT_OK: + case AIRLIFT_REPLY_TOO_BIG: + core_failures = 0; + return; + case AIRLIFT_TIMEOUT_READY: + case AIRLIFT_TIMEOUT_SELECT: + // It didn't answer for 1-10 s. + core_failures = CORE_FAILURES_BEFORE_RESET; + break; + case AIRLIFT_TIMEOUT_START: + case AIRLIFT_ERR_RESPONSE: + case AIRLIFT_BAD_REPLY: + core_failures++; + break; + default: + // Nothing was sent. + return; + } + if (core_failures >= CORE_FAILURES_BEFORE_RESET) { + airlift_transport_reset(); + } +} + +airlift_result_t airlift_transact(uint8_t cmd, const airlift_param_t *params, size_t n_params, + bool param_len_16, airlift_reply_t *reply, int expected_replies, bool reply_len_16, + bool from_vm) { + if (!active) { + return AIRLIFT_NOT_ACTIVE; + } + if (busy) { + return AIRLIFT_BUSY; + } + size_t len; + airlift_result_t result = build_command(cmd, params, n_params, param_len_16, &len); + if (result != AIRLIFT_OK) { + return result; + } + if (from_vm && guard_core_socket(cmd, params, n_params, reply, &result)) { + return result; + } + busy = true; + for (int tries = 0; tries < COMMAND_TRIES; tries++) { + result = send_command(len, from_vm); + if (result == AIRLIFT_OK) { + result = receive_reply(cmd, reply, expected_replies, reply_len_16); + } + // nina-fw replies ERR_CMD before running anything when the command + // arrived garbled (seen about once in 15000 commands under load), so it is safe to send + // again. tx_buf still holds it. + if (result != AIRLIFT_ERR_RESPONSE) { + break; + } + } + busy = false; + if (!from_vm) { + check_core_result(result); + } + if (from_vm && result == AIRLIFT_OK) { + switch (cmd) { + case AIRLIFT_GET_SOCKET: + vm_allocating = true; + vm_allocating_ms = supervisor_ticks_ms64(); + break; + case AIRLIFT_START_SERVER_TCP: + // build_command() checked the socket number, so it is in range here. + if (n_params >= 2) { + vm_listening |= 1 << params[n_params - 2].buf[0]; + } + MP_FALLTHROUGH; + case AIRLIFT_START_CLIENT_TCP: + case AIRLIFT_STOP_CLIENT_TCP: + vm_allocating = false; + break; + case AIRLIFT_SET_NET: + case AIRLIFT_SET_PASSPHRASE: + case AIRLIFT_SET_AP_NET: + case AIRLIFT_SET_AP_PASSPHRASE: + case AIRLIFT_DISCONNECT: + case AIRLIFT_SET_ENT_ENABLE: + vm_network_commands++; + break; + default: + break; + } + } + return result; +} + +uint32_t airlift_transport_vm_network_commands(void) { + return vm_network_commands; +} + +bool airlift_transport_vm_allocating(void) { + if (vm_allocating && supervisor_ticks_ms64() - vm_allocating_ms >= VM_ALLOCATING_TIMEOUT_MS) { + vm_allocating = false; + } + return vm_allocating; +} + +void airlift_transport_set_owned(uint8_t sock, bool owned) { + if (sock >= CIRCUITPY_AIRLIFT_MAX_SOCKETS) { + return; + } + if (owned) { + core_owned |= 1 << sock; + } else { + core_owned &= ~(1 << sock); + } +} + +void airlift_transport_leaked_listener(uint8_t sock) { + if (sock < CIRCUITPY_AIRLIFT_MAX_SOCKETS) { + vm_listening |= 1 << sock; + } +} + +static bool claim_esp_pin(digitalio_digitalinout_obj_t *dio, const mcu_pin_obj_t *pin) { + dio->base.type = &digitalio_digitalinout_type; + if (common_hal_digitalio_digitalinout_construct(dio, pin) != DIGITALINOUT_OK) { + return false; + } + return true; +} + +typedef struct { + const mcu_pin_obj_t *clock; + const mcu_pin_obj_t *mosi; + const mcu_pin_obj_t *miso; +} spi_pins_t; + +bool airlift_transport_init(void) { + if (active) { + return true; + } + // board.SPI() may already exist; then the ESP shares it with user code. + mp_obj_t board_spi = common_hal_board_get_spi(CIRCUITPY_AIRLIFT_SPI_INDEX); + if (board_spi == NULL || common_hal_busio_spi_deinited(MP_OBJ_TO_PTR(board_spi))) { + static const spi_pins_t spi_pins[] = CIRCUITPY_BOARD_SPI_PIN; + const spi_pins_t *p = &spi_pins[CIRCUITPY_AIRLIFT_SPI_INDEX]; + if (!common_hal_mcu_pin_is_free(p->clock) || !common_hal_mcu_pin_is_free(p->mosi) || + !common_hal_mcu_pin_is_free(p->miso)) { + return false; + } + } + if (!common_hal_mcu_pin_is_free(CIRCUITPY_AIRLIFT_CS) || + !common_hal_mcu_pin_is_free(CIRCUITPY_AIRLIFT_BUSY) || + !common_hal_mcu_pin_is_free(CIRCUITPY_AIRLIFT_RESET)) { + return false; + } + #ifdef CIRCUITPY_AIRLIFT_GPIO0 + if (!common_hal_mcu_pin_is_free(CIRCUITPY_AIRLIFT_GPIO0)) { + return false; + } + #endif + + spi = MP_OBJ_TO_PTR(common_hal_board_create_spi(CIRCUITPY_AIRLIFT_SPI_INDEX)); + claim_esp_pin(&cs, CIRCUITPY_AIRLIFT_CS); + common_hal_digitalio_digitalinout_switch_to_output(&cs, true, DRIVE_MODE_PUSH_PULL); + claim_esp_pin(&ready, CIRCUITPY_AIRLIFT_BUSY); + claim_esp_pin(&reset, CIRCUITPY_AIRLIFT_RESET); + common_hal_digitalio_digitalinout_switch_to_output(&reset, true, DRIVE_MODE_PUSH_PULL); + #ifdef CIRCUITPY_AIRLIFT_GPIO0 + claim_esp_pin(&gpio0, CIRCUITPY_AIRLIFT_GPIO0); + #endif + active = true; + airlift_transport_reset(); + return true; +} + +void airlift_transport_deinit(void) { + if (!active || busy) { + return; + } + active = false; + common_hal_digitalio_digitalinout_deinit(&cs); + common_hal_digitalio_digitalinout_deinit(&ready); + common_hal_digitalio_digitalinout_deinit(&reset); + #ifdef CIRCUITPY_AIRLIFT_GPIO0 + common_hal_digitalio_digitalinout_deinit(&gpio0); + #endif + // The bus stays as board.SPI(). It is released at the next soft reset, + // because airlift_transport_using_spi() no longer claims it. + spi = NULL; + // The core's sockets can't be used any more. + generation++; + core_owned = 0; +} + +void airlift_transport_reset(void) { + if (!active) { + return; + } + // A command started from a background task during the reset would see an ESP + // that isn't running yet. + bool was_busy = busy; + busy = true; + #ifdef CIRCUITPY_AIRLIFT_GPIO0 + // High selects a normal boot rather than the bootloader. + common_hal_digitalio_digitalinout_switch_to_output(&gpio0, true, DRIVE_MODE_PUSH_PULL); + #endif + common_hal_digitalio_digitalinout_set_value(&cs, true); + common_hal_digitalio_digitalinout_set_value(&reset, false); + pause_ms(10); + common_hal_digitalio_digitalinout_set_value(&reset, true); + pause_ms(750); + #ifdef CIRCUITPY_AIRLIFT_GPIO0 + common_hal_digitalio_digitalinout_switch_to_input(&gpio0, PULL_NONE); + #endif + generation++; + vm_listening = 0; + core_owned = 0; + vm_allocating = false; + core_failures = 0; + busy = was_busy; +} + +void airlift_user_reset(void) { + if (!active) { + return; + } + // User code may have exited holding the bus lock. + common_hal_busio_spi_unlock(spi); + vm_allocating = false; + if (vm_listening != 0) { + airlift_transport_reset(); + return; + } + for (uint8_t sock = 0; sock < CIRCUITPY_AIRLIFT_MAX_SOCKETS; sock++) { + if (core_owned & (1 << sock)) { + continue; + } + airlift_param_t param = { .buf = &sock, .len = 1 }; + uint8_t buf[1]; + uint16_t lens[1]; + airlift_reply_t reply = { .buf = buf, .buf_len = sizeof(buf), .lens = lens, .max_count = 1 }; + if (airlift_transact(AIRLIFT_STOP_CLIENT_TCP, ¶m, 1, false, &reply, 1, false, false) != AIRLIFT_OK) { + // Don't wait out a timeout for every socket. A reset closes them all. + airlift_transport_reset(); + return; + } + } +} + +bool airlift_transport_active(void) { + return active; +} + +bool airlift_transport_busy(void) { + return busy; +} + +bool airlift_transport_bus_free(void) { + if (!active || busy || common_hal_busio_spi_deinited(spi) || !common_hal_busio_spi_try_lock(spi)) { + return false; + } + common_hal_busio_spi_unlock(spi); + return true; +} + +bool airlift_transport_has_data_ready(void) { + #ifdef CIRCUITPY_AIRLIFT_GPIO0 + return active; + #else + return false; + #endif +} + +bool airlift_transport_data_ready(void) { + #ifdef CIRCUITPY_AIRLIFT_GPIO0 + // During a reset GPIO0 is an output, held high. + return !active || common_hal_digitalio_digitalinout_get_value(&gpio0); + #else + return true; + #endif +} + +uint32_t airlift_transport_generation(void) { + return generation; +} + +bool airlift_transport_using_spi(const busio_spi_obj_t *bus) { + return active && bus == spi; +} diff --git a/shared-module/_airlift/transport.h b/shared-module/_airlift/transport.h new file mode 100644 index 00000000000..0440bcd6543 --- /dev/null +++ b/shared-module/_airlift/transport.h @@ -0,0 +1,140 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +// Driver for an ESP32 co-processor running nina-fw, spoken to over SPI. The +// framing matches ESP32SPI's _send_command() and _wait_response_cmd(). Only one +// command is in flight at a time; the board SPI lock is held only during each +// half of a command, so other devices on the bus can use it in between. + +#include +#include +#include + +#include "shared-bindings/busio/SPI.h" + +// Number of sockets in nina-fw (CONFIG_LWIP_MAX_SOCKETS). A command naming a +// higher socket hangs nina-fw 3.1.0 until a hard reset. +#ifndef CIRCUITPY_AIRLIFT_MAX_SOCKETS +#define CIRCUITPY_AIRLIFT_MAX_SOCKETS (6) +#endif + +// The ESP32 receives and sends at most this many bytes per SPI transfer. +// Longer commands are silently truncated, and longer replies hang it. +#define AIRLIFT_MAX_TRANSFER (4092) +// GET_DATABUF_TCP reply: START, cmd, 1 param, 16-bit length, data, END. +#define AIRLIFT_MAX_READ (AIRLIFT_MAX_TRANSFER - 6) +// SEND_DATA_TCP command: START, cmd, 2 params, 16-bit length + socket, +// 16-bit length + data, END. +#define AIRLIFT_MAX_SEND (AIRLIFT_MAX_TRANSFER - 9) + +#define AIRLIFT_SET_NET (0x10) +#define AIRLIFT_SET_PASSPHRASE (0x11) +#define AIRLIFT_SET_AP_NET (0x18) +#define AIRLIFT_SET_AP_PASSPHRASE (0x19) +#define AIRLIFT_GET_CONN_STATUS (0x20) +#define AIRLIFT_GET_IPADDR (0x21) +#define AIRLIFT_GET_CURR_SSID (0x23) +#define AIRLIFT_START_SERVER_TCP (0x28) +#define AIRLIFT_AVAIL_DATA_TCP (0x2B) +#define AIRLIFT_START_CLIENT_TCP (0x2D) +#define AIRLIFT_STOP_CLIENT_TCP (0x2E) +#define AIRLIFT_GET_CLIENT_STATE_TCP (0x2F) +#define AIRLIFT_DISCONNECT (0x30) +#define AIRLIFT_GET_SOCKET (0x3F) +#define AIRLIFT_SEND_DATA_TCP (0x44) +#define AIRLIFT_GET_DATABUF_TCP (0x45) +#define AIRLIFT_SET_ENT_ENABLE (0x4F) + +// The socket number GET_SOCKET returns when all are in use, and AVAIL_DATA_TCP +// returns for a listening socket with nobody waiting. +#define AIRLIFT_NO_SOCKET (255) + +typedef struct { + const uint8_t *buf; + size_t len; +} airlift_param_t; + +typedef struct { + uint8_t *buf; // The reply parameters, back to back. + size_t buf_len; + uint16_t *lens; // Length of each reply parameter. + size_t max_count; + size_t count; // Set by airlift_transact(). +} airlift_reply_t; + +typedef enum { + AIRLIFT_OK, + AIRLIFT_NOT_ACTIVE, + // Another command is in flight, or the SPI bus is locked by someone else. + AIRLIFT_BUSY, + // A VM caller was interrupted before anything was sent. + AIRLIFT_INTERRUPTED, + // The command was rejected before sending it. + AIRLIFT_BAD_SOCKET, + AIRLIFT_TOO_BIG, + // BUSY never went low. + AIRLIFT_TIMEOUT_READY, + // BUSY never went high after CS went low. + AIRLIFT_TIMEOUT_SELECT, + // No START_CMD at the start of the reply. + AIRLIFT_TIMEOUT_START, + // The ESP32 replied ERR_CMD. + AIRLIFT_ERR_RESPONSE, + // A framing byte was wrong. + AIRLIFT_BAD_REPLY, + // The reply didn't fit in the airlift_reply_t. It was read and dropped. + AIRLIFT_REPLY_TOO_BIG, +} airlift_result_t; + +// Claims the ESP pins and the board SPI bus, then hard-resets the ESP32. +// Returns false if a pin or the bus is already in use. Never raises. +bool airlift_transport_init(void); +// Releases the pins. The board SPI bus is left to board.SPI(). +void airlift_transport_deinit(void); +// Hard reset through ESP_RESET. Takes about 760 ms. Changes the generation. +void airlift_transport_reset(void); +bool airlift_transport_active(void); +// True from the start of a command's send to the end of its reply. +bool airlift_transport_busy(void); +// False while someone else holds the SPI bus lock. Background callers don't +// wait for it. +bool airlift_transport_bus_free(void); +// Changes on every hard reset, so sockets can tell they no longer exist. +uint32_t airlift_transport_generation(void); +// Whether the board connects GPIO0, which nina-fw drives high while a socket +// has data to read or a listener has a client waiting. +bool airlift_transport_has_data_ready(void); +// The level of that signal; true when the board doesn't connect it. Safe to +// call from an interrupt. +bool airlift_transport_data_ready(void); +bool airlift_transport_using_spi(const busio_spi_obj_t *spi); +// At the end of a VM run, closes the sockets user code left open. nina-fw can't +// close a listening socket, so if user code started a server, the ESP32 is +// hard-reset instead. +void airlift_user_reset(void); + +// Marks a socket number as the core's, so airlift_user_reset() leaves it open. A +// hard reset clears them all. +void airlift_transport_set_owned(uint8_t sock, bool owned); +// Records that the core left a listener running on this socket. nina-fw can't +// stop it, so the ESP32 is hard-reset at the end of the VM run. +void airlift_transport_leaked_listener(uint8_t sock); +// True while VM code has done GET_SOCKET but not yet used the number. GET_SOCKET +// doesn't reserve it, so the core must not take a socket in the meantime. +bool airlift_transport_vm_allocating(void); +// Counts the WiFi join and disconnect commands VM code has sent, so the core +// can tell whether user code is managing the connection itself. +uint32_t airlift_transport_vm_network_commands(void); + +// Sends one command and reads its reply. expected_replies < 0 means take the +// count from the reply. from_vm callers wait for a locked bus and can be +// interrupted, but only before anything is sent. When the ESP32 stops answering +// the core's commands, or garbles three replies in a row, it is hard-reset. +airlift_result_t airlift_transact(uint8_t cmd, const airlift_param_t *params, size_t n_params, + bool param_len_16, airlift_reply_t *reply, int expected_replies, bool reply_len_16, + bool from_vm); diff --git a/shared-module/_bleio/Address.c b/shared-module/_bleio/Address.c index b40abb3d560..5a50ba4f28f 100644 --- a/shared-module/_bleio/Address.c +++ b/shared-module/_bleio/Address.c @@ -7,17 +7,24 @@ #include -#include "py/objstr.h" +#include "py/obj.h" #include "shared-bindings/_bleio/Address.h" #include "shared-module/_bleio/Address.h" -void common_hal_bleio_address_construct(bleio_address_obj_t *self, uint8_t *bytes, uint8_t address_type) { - self->bytes = mp_obj_new_bytes(bytes, NUM_BLEIO_ADDRESS_BYTES); +void common_hal_bleio_address_construct(bleio_address_obj_t *self, const uint8_t *bytes, uint8_t address_type) { + memcpy(self->bytes, bytes, NUM_BLEIO_ADDRESS_BYTES); self->type = address_type; } mp_obj_t common_hal_bleio_address_get_address_bytes(bleio_address_obj_t *self) { - return self->bytes; + // Build a bytes object on demand. Address stores its bytes inline, so this + // is only reached from Python (e.g. ``address.address_bytes``) where the + // heap is available. + return mp_obj_new_bytes(self->bytes, NUM_BLEIO_ADDRESS_BYTES); +} + +void common_hal_bleio_address_get_bytes(bleio_address_obj_t *self, uint8_t bytes[NUM_BLEIO_ADDRESS_BYTES]) { + memcpy(bytes, self->bytes, NUM_BLEIO_ADDRESS_BYTES); } uint8_t common_hal_bleio_address_get_type(bleio_address_obj_t *self) { diff --git a/shared-module/_bleio/Address.h b/shared-module/_bleio/Address.h index 76e7a1177fc..55324770375 100644 --- a/shared-module/_bleio/Address.h +++ b/shared-module/_bleio/Address.h @@ -14,5 +14,8 @@ typedef struct { mp_obj_base_t base; uint8_t type; - mp_obj_t bytes; // a bytes() object + // Little-endian BD_ADDR order: bytes[0] is the least-significant byte. + // Stored inline so an Address can live in static storage (e.g. embedded in + // an adapter) without allocating a separate bytes object. + uint8_t bytes[NUM_BLEIO_ADDRESS_BYTES]; } bleio_address_obj_t; diff --git a/shared-module/_bleio/Attribute.c b/shared-module/_bleio/Attribute.c index b12f2b121de..cfc5999df1e 100644 --- a/shared-module/_bleio/Attribute.c +++ b/shared-module/_bleio/Attribute.c @@ -24,3 +24,14 @@ void common_hal_bleio_attribute_security_mode_check_valid(bleio_attribute_securi break; } } + +bool bleio_attribute_security_mode_requires_mitm(bleio_attribute_security_mode_t security_mode) { + switch (security_mode) { + case SECURITY_MODE_ENC_WITH_MITM: + case SECURITY_MODE_LESC_ENC_WITH_MITM: + case SECURITY_MODE_SIGNED_WITH_MITM: + return true; + default: + return false; + } +} diff --git a/shared-module/_eve/__init__.c b/shared-module/_eve/__init__.c index ecd310b55a3..ca084d9b43b 100644 --- a/shared-module/_eve/__init__.c +++ b/shared-module/_eve/__init__.c @@ -246,6 +246,11 @@ void common_hal__eve_PointSize(common_hal__eve_t *eve, mp_float_t size) { } +void common_hal__eve_Region(common_hal__eve_t *eve, uint32_t y, uint32_t h, uint32_t dest) { + C4(eve, ((52 << 24) | ((y & 0x3f) << 18) | ((h & 0x3f) << 12) | (dest & 0xfff))); +} + + void common_hal__eve_RestoreContext(common_hal__eve_t *eve) { C4(eve, ((35 << 24))); } diff --git a/shared-module/_stage/__init__.c b/shared-module/_stage/__init__.c index c23d0567345..f99cb6156c7 100644 --- a/shared-module/_stage/__init__.c +++ b/shared-module/_stage/__init__.c @@ -26,7 +26,7 @@ void render_stage( area.y1 = y0 * scale; area.x2 = x1 * scale; area.y2 = y1 * scale; - displayio_display_bus_set_region_to_update(&display->bus, &display->core, &area); + displayio_display_bus_set_region_to_update(&display->bus, &display->core.colorspace, &area); while (!displayio_display_bus_begin_transaction(&display->bus)) { RUN_BACKGROUND_TASKS; diff --git a/shared-module/adafruit_bus_device/i2c_device/I2CDevice.c b/shared-module/adafruit_bus_device/i2c_device/I2CDevice.c index e01875452b1..0ed2d35be53 100644 --- a/shared-module/adafruit_bus_device/i2c_device/I2CDevice.c +++ b/shared-module/adafruit_bus_device/i2c_device/I2CDevice.c @@ -24,9 +24,7 @@ void common_hal_adafruit_bus_device_i2cdevice_lock(adafruit_bus_device_i2cdevice while (!mp_obj_is_true(success)) { RUN_BACKGROUND_TASKS; - if (mp_hal_is_interrupted()) { - break; - } + mp_handle_pending(true); success = mp_call_method_n_kw(0, 0, dest); } diff --git a/shared-module/adafruit_pixelbuf/PixelBuf.c b/shared-module/adafruit_pixelbuf/PixelBuf.c index e62730b3cac..155862f17a3 100644 --- a/shared-module/adafruit_pixelbuf/PixelBuf.c +++ b/shared-module/adafruit_pixelbuf/PixelBuf.c @@ -100,7 +100,7 @@ void common_hal_adafruit_pixelbuf_pixelbuf_set_brightness(mp_obj_t self_in, mp_f return; } else { if (self->pre_brightness_buffer == NULL) { - self->pre_brightness_buffer = m_malloc(pixel_len); + self->pre_brightness_buffer = m_malloc_without_collect(pixel_len); memcpy(self->pre_brightness_buffer, self->post_brightness_buffer, pixel_len); } for (size_t i = 0; i < pixel_len; i++) { diff --git a/shared-module/atexit/__init__.c b/shared-module/atexit/__init__.c index 2ed67fd04b7..537a2a9d969 100644 --- a/shared-module/atexit/__init__.c +++ b/shared-module/atexit/__init__.c @@ -28,14 +28,14 @@ void atexit_gc_collect(void) { void shared_module_atexit_register(mp_obj_t *func, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { if (!mp_obj_is_callable(func)) { - mp_raise_TypeError_varg(MP_ERROR_TEXT("'%q' object is not callable"), mp_obj_get_type_qstr(func)); + mp_raise_TypeError_varg(MP_ERROR_TEXT("'%q' object isn't callable"), mp_obj_get_type_qstr(func)); } size_t n_kw_args = (kw_args) ? kw_args->used : 0; atexit_callback_t cb = { .n_pos = 0, .n_kw = 0, .func = func, - .args = (n_args + n_kw_args) ? m_malloc((n_args + (n_kw_args * 2)) * sizeof(mp_obj_t)) : NULL + .args = (n_args + n_kw_args) ? m_malloc_items(n_args + (n_kw_args * 2)) : NULL }; for (; cb.n_pos < n_args; cb.n_pos++) { cb.args[cb.n_pos] = pos_args[cb.n_pos]; diff --git a/shared-module/audiocore/WaveFile.c b/shared-module/audiocore/WaveFile.c index 624541cb144..ada0b1c43d7 100644 --- a/shared-module/audiocore/WaveFile.c +++ b/shared-module/audiocore/WaveFile.c @@ -11,6 +11,7 @@ #include "py/mperrno.h" #include "py/runtime.h" +#include "py/stream.h" #include "shared-module/audiocore/WaveFile.h" #include "shared-bindings/audiocore/__init__.h" @@ -29,47 +30,62 @@ struct wave_format_chunk { uint8_t extended_guid[14]; }; +// Read exactly size bytes from the stream or raise OSError on error or EOF. +static void wavefile_read_exactly(mp_obj_t stream, void *buf, size_t size) { + int errcode = 0; + mp_uint_t bytes_read = mp_stream_rw(stream, buf, size, &errcode, MP_STREAM_RW_READ); + if (errcode != 0) { + mp_raise_OSError(errcode); + } + if (bytes_read != size) { + mp_raise_OSError(MP_EIO); + } +} + +// Seek the stream and raise OSError on failure. Returns the new position. +static mp_off_t wavefile_seek(mp_obj_t stream, mp_off_t offset, int whence) { + int errcode; + mp_off_t position = mp_stream_seek(stream, offset, whence, &errcode); + if (position == (mp_off_t)-1) { + mp_raise_OSError(errcode); + } + return position; +} + void common_hal_audioio_wavefile_construct(audioio_wavefile_obj_t *self, - pyb_file_obj_t *file, + mp_obj_t file, uint8_t *buffer, size_t buffer_size) { + // Make sure the file supports reading and seeking. + mp_get_stream_raise(file, MP_STREAM_OP_READ | MP_STREAM_OP_IOCTL); + // Load the wave self->file = file; uint8_t chunk_header[16]; - f_rewind(&self->file->fp); - UINT bytes_read; - if (f_read(&self->file->fp, chunk_header, 16, &bytes_read) != FR_OK) { - mp_raise_OSError(MP_EIO); - } - if (bytes_read != 16 || - memcmp(chunk_header, "RIFF", 4) != 0 || + wavefile_seek(file, 0, MP_SEEK_SET); + wavefile_read_exactly(file, chunk_header, 16); + if (memcmp(chunk_header, "RIFF", 4) != 0 || memcmp(chunk_header + 8, "WAVEfmt ", 8) != 0) { mp_arg_error_invalid(MP_QSTR_file); } uint32_t format_size; - if (f_read(&self->file->fp, &format_size, 4, &bytes_read) != FR_OK) { - mp_raise_OSError(MP_EIO); - } - if (bytes_read != 4 || - format_size > sizeof(struct wave_format_chunk)) { + wavefile_read_exactly(file, &format_size, 4); + if (format_size > sizeof(struct wave_format_chunk)) { mp_raise_ValueError(MP_ERROR_TEXT("Invalid format chunk size")); } struct wave_format_chunk format; - if (f_read(&self->file->fp, &format, format_size, &bytes_read) != FR_OK) { - mp_raise_OSError(MP_EIO); - } - if (bytes_read != format_size) { - } + wavefile_read_exactly(file, &format, format_size); if ((format_size != 40 && format.audio_format != 1) || format.num_channels > 2 || + format.sample_rate == 0 || format.bits_per_sample > 16 || (format_size == 18 && format.extra_params != 0) || (format_size == 40 && (format.audio_format != 0xfffe || format.extended_audio_format != 1 || format.valid_bits_per_sample != format.bits_per_sample))) { - mp_raise_ValueError(MP_ERROR_TEXT("Unsupported format")); + mp_raise_ValueError(MP_ERROR_TEXT("Format not supported")); } // Get the sample_rate self->base.sample_rate = format.sample_rate; @@ -84,48 +100,38 @@ void common_hal_audioio_wavefile_construct(audioio_wavefile_obj_t *self, bool found_data_chunk = false; while (!found_data_chunk) { - if (f_read(&self->file->fp, &chunk_tag, 4, &bytes_read) != FR_OK) { - mp_raise_OSError(MP_EIO); - } - if (bytes_read != 4) { - mp_raise_OSError(MP_EIO); - } + wavefile_read_exactly(file, chunk_tag, 4); if (memcmp((uint8_t *)chunk_tag, "data", 4) == 0) { found_data_chunk = true; } - if (f_read(&self->file->fp, &chunk_length, 4, &bytes_read) != FR_OK) { - mp_raise_OSError(MP_EIO); - } - if (bytes_read != 4) { - mp_raise_OSError(MP_EIO); - } + wavefile_read_exactly(file, &chunk_length, 4); if (!found_data_chunk) { - if (f_lseek(&self->file->fp, f_tell(&self->file->fp) + chunk_length) != FR_OK) { - mp_raise_OSError(MP_EIO); - } + mp_off_t current_position = wavefile_seek(file, 0, MP_SEEK_CUR); + wavefile_seek(file, current_position + chunk_length, MP_SEEK_SET); } } self->file_length = chunk_length; - self->data_start = self->file->fp.fptr; + self->data_start = wavefile_seek(file, 0, MP_SEEK_CUR); // Try to allocate two buffers, one will be loaded from file and the other // DMAed to DAC. if (buffer_size) { + // buffer_size is a multiple of 8 (checked by the binding) so each half can be padded in place. self->len = buffer_size / 2; self->buffer = buffer; self->second_buffer = buffer + self->len; } else { self->len = 256; - self->buffer = m_malloc(self->len); + self->buffer = m_malloc_without_collect(self->len); if (self->buffer == NULL) { common_hal_audioio_wavefile_deinit(self); m_malloc_fail(self->len); } - self->second_buffer = m_malloc(self->len); + self->second_buffer = m_malloc_without_collect(self->len); if (self->second_buffer == NULL) { common_hal_audioio_wavefile_deinit(self); m_malloc_fail(self->len); @@ -148,7 +154,7 @@ void audioio_wavefile_reset_buffer(audioio_wavefile_obj_t *self, // We don't reset the buffer index in case we're looping and we have an odd number of buffer // loads self->bytes_remaining = self->file_length; - f_lseek(&self->file->fp, self->data_start); + wavefile_seek(self->file, self->data_start, MP_SEEK_SET); self->read_count = 0; self->left_read_count = 0; self->right_read_count = 0; @@ -181,19 +187,21 @@ audioio_get_buffer_result_t audioio_wavefile_get_buffer(audioio_wavefile_obj_t * if (num_bytes_to_load > self->bytes_remaining) { num_bytes_to_load = self->bytes_remaining; } - UINT length_read; + mp_uint_t length_read; if (self->buffer_index % 2 == 1) { *buffer = self->second_buffer; } else { *buffer = self->buffer; } - if (f_read(&self->file->fp, *buffer, num_bytes_to_load, &length_read) != FR_OK || length_read != num_bytes_to_load) { + int errcode = 0; + length_read = mp_stream_rw(self->file, *buffer, num_bytes_to_load, &errcode, MP_STREAM_RW_ONCE); + if (errcode != 0 || length_read != num_bytes_to_load) { return GET_BUFFER_ERROR; } self->bytes_remaining -= length_read; // Pad the last buffer to word align it. if (self->bytes_remaining == 0 && length_read % sizeof(uint32_t) != 0) { - uint32_t pad = length_read % sizeof(uint32_t); + uint32_t pad = sizeof(uint32_t) - length_read % sizeof(uint32_t); length_read += pad; if (self->base.bits_per_sample == 8) { for (uint32_t i = 0; i < pad; i++) { diff --git a/shared-module/audiocore/WaveFile.h b/shared-module/audiocore/WaveFile.h index 74e25ffebfe..49250ca16f4 100644 --- a/shared-module/audiocore/WaveFile.h +++ b/shared-module/audiocore/WaveFile.h @@ -6,7 +6,6 @@ #pragma once -#include "extmod/vfs_fat.h" #include "py/obj.h" #include "shared-module/audiocore/__init__.h" @@ -18,12 +17,12 @@ typedef struct { uint8_t *second_buffer; uint32_t second_buffer_length; uint32_t file_length; // In bytes - uint16_t data_start; // Where the data values start + uint32_t data_start; // Where the data values start uint16_t buffer_index; uint32_t bytes_remaining; uint32_t len; - pyb_file_obj_t *file; + mp_obj_t file; uint32_t read_count; uint32_t left_read_count; diff --git a/shared-module/audiocore/__init__.c b/shared-module/audiocore/__init__.c index bf804031379..97849da3f38 100644 --- a/shared-module/audiocore/__init__.c +++ b/shared-module/audiocore/__init__.c @@ -8,16 +8,30 @@ #include "py/obj.h" #include "py/runtime.h" +#include "shared-bindings/audiocore/__init__.h" #include "shared-bindings/audiocore/RawSample.h" #include "shared-bindings/audiocore/WaveFile.h" #include "shared-module/audiocore/RawSample.h" #include "shared-module/audiocore/WaveFile.h" +#if CIRCUITPY_AUDIOSPEED +#include "shared-bindings/audiospeed/Resampler.h" +#endif + #include "shared-bindings/audiomixer/Mixer.h" #include "shared-module/audiomixer/Mixer.h" +MP_WEAK void audiocore_lock(void) { +} + +MP_WEAK void audiocore_unlock(void) { +} + void audiosample_reset_buffer(mp_obj_t sample_obj, bool single_channel_output, uint8_t audio_channel) { const audiosample_p_t *proto = mp_proto_get_or_throw(MP_QSTR_protocol_audiosample, sample_obj); + if (audiosample_deinited(audiosample_cast_obj(sample_obj))) { + return; + } proto->reset_buffer(MP_OBJ_TO_PTR(sample_obj), single_channel_output, audio_channel); } @@ -26,6 +40,11 @@ audioio_get_buffer_result_t audiosample_get_buffer(mp_obj_t sample_obj, 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); + if (audiosample_deinited(audiosample_cast_obj(sample_obj))) { + *buffer = NULL; + *buffer_length = 0; + return GET_BUFFER_ERROR; + } return proto->get_buffer(MP_OBJ_TO_PTR(sample_obj), single_channel_output, channel, buffer, buffer_length); } @@ -196,12 +215,17 @@ void audiosample_convert_s16s_u8s(uint8_t *buffer_out, const int16_t *buffer_in, } } -void audiosample_must_match(audiosample_base_t *self, mp_obj_t other_in) { +void audiosample_must_match(audiosample_base_t *self, mp_obj_t other_in, bool allow_mono_to_stereo) { const audiosample_base_t *other = audiosample_check(other_in); + audiosample_check_for_deinit(other); + #if !CIRCUITPY_AUDIOSPEED if (other->sample_rate != self->sample_rate) { + #else + if (other->sample_rate != self->sample_rate && !mp_obj_is_type(other_in, &audiospeed_resampler_type)) { + #endif mp_raise_ValueError_varg(MP_ERROR_TEXT("The sample's %q does not match"), MP_QSTR_sample_rate); } - if (other->channel_count != self->channel_count) { + if ((!allow_mono_to_stereo || (allow_mono_to_stereo && self->channel_count != 2)) && other->channel_count != self->channel_count) { mp_raise_ValueError_varg(MP_ERROR_TEXT("The sample's %q does not match"), MP_QSTR_channel_count); } if (other->bits_per_sample != self->bits_per_sample) { @@ -210,4 +234,11 @@ void audiosample_must_match(audiosample_base_t *self, mp_obj_t other_in) { if (other->samples_signed != self->samples_signed) { mp_raise_ValueError_varg(MP_ERROR_TEXT("The sample's %q does not match"), MP_QSTR_signedness); } + + #if CIRCUITPY_AUDIOSPEED + if (mp_obj_is_type(other_in, &audiospeed_resampler_type)) { + audiospeed_resampler_obj_t *other_resampler = MP_OBJ_TO_PTR(other_in); + audiospeed_resampler_set_sample_rate(other_resampler, self->sample_rate); + } + #endif } diff --git a/shared-module/audiocore/__init__.h b/shared-module/audiocore/__init__.h index 875ac90ecc5..6ad24a115b0 100644 --- a/shared-module/audiocore/__init__.h +++ b/shared-module/audiocore/__init__.h @@ -56,6 +56,13 @@ static inline uint8_t audiosample_get_channel_count(audiosample_base_t *self) { return self->channel_count; } +// Ports that fetch sample buffers on their own task, not the CircuitPython task, hold this lock +// while they fetch. Code that changes a sample that may be playing holds it too, so the fetch +// never sees the sample half changed. Calls nest. Never call from an interrupt. The default does +// nothing, for ports that fetch on the CircuitPython task. +void audiocore_lock(void); +void audiocore_unlock(void); + void audiosample_reset_buffer(mp_obj_t sample_obj, bool single_channel_output, uint8_t audio_channel); audioio_get_buffer_result_t audiosample_get_buffer(mp_obj_t sample_obj, bool single_channel_output, @@ -89,7 +96,7 @@ static inline void audiosample_get_buffer_structure_checked(mp_obj_t self_in, bo audiosample_get_buffer_structure(audiosample_check(self_in), single_channel_output, single_buffer, samples_signed, max_buffer_length, spacing); } -void audiosample_must_match(audiosample_base_t *self, mp_obj_t other); +void audiosample_must_match(audiosample_base_t *self, mp_obj_t other, bool allow_mono_to_stereo); 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); @@ -114,3 +121,5 @@ void audiosample_convert_u16m_u8s(uint8_t *buffer_out, const uint16_t *buffer_in void audiosample_convert_u16s_u8s(uint8_t *buffer_out, const uint16_t *buffer_in, size_t nframes); void audiosample_convert_s16m_u8s(uint8_t *buffer_out, const int16_t *buffer_in, size_t nframes); void audiosample_convert_s16s_u8s(uint8_t *buffer_out, const int16_t *buffer_in, size_t nframes); + +#define audiosample_cast_obj(obj) ((audiosample_base_t *)MP_OBJ_TO_PTR(obj)) diff --git a/shared-module/audiodelays/Chorus.c b/shared-module/audiodelays/Chorus.c new file mode 100644 index 00000000000..7033df0e272 --- /dev/null +++ b/shared-module/audiodelays/Chorus.c @@ -0,0 +1,350 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Mark Komus +// +// SPDX-License-Identifier: MIT +#include "shared-bindings/audiodelays/Chorus.h" +#include "shared-bindings/audiocore/__init__.h" + +#include +#include +#include "py/runtime.h" + +void common_hal_audiodelays_chorus_construct(audiodelays_chorus_obj_t *self, uint32_t max_delay_ms, + mp_obj_t delay_ms, mp_obj_t voices, mp_obj_t mix, + uint32_t buffer_size, uint8_t bits_per_sample, + bool samples_signed, uint8_t channel_count, uint32_t sample_rate) { + + // Basic settings every effect and audio sample has + // These are the effects values, not the source sample(s) + self->base.bits_per_sample = bits_per_sample; // Most common is 16, but 8 is also supported in many places + self->base.samples_signed = samples_signed; // Are the samples we provide signed (common is true) + self->base.channel_count = channel_count; // Channels can be 1 for mono or 2 for stereo + self->base.sample_rate = sample_rate; // Sample rate for the effect, this generally needs to match all audio objects + self->base.single_buffer = false; + self->base.max_buffer_length = buffer_size; + + // To smooth things out as CircuitPython is doing other tasks most audio objects have a buffer + // A double buffer is set up here so the audio output can use DMA on buffer 1 while we + // write to and create buffer 2. + // This buffer is what is passed to the audio component that plays the effect. + // Samples are set sequentially. For stereo audio they are passed L/R/L/R/... + self->buffer_len = buffer_size; // in bytes + + self->buffer[0] = m_malloc_without_collect(self->buffer_len); + if (self->buffer[0] == NULL) { + common_hal_audiodelays_chorus_deinit(self); + m_malloc_fail(self->buffer_len); + } + memset(self->buffer[0], 0, self->buffer_len); + + self->buffer[1] = m_malloc_without_collect(self->buffer_len); + if (self->buffer[1] == NULL) { + common_hal_audiodelays_chorus_deinit(self); + m_malloc_fail(self->buffer_len); + } + memset(self->buffer[1], 0, self->buffer_len); + + self->last_buf_idx = 1; // Which buffer to use first, toggle between 0 and 1 + + // Initialize other values most effects will need. + self->sample = NULL; // The current playing sample + self->sample_remaining_buffer = NULL; // Pointer to the start of the sample buffer we have not played + self->sample_buffer_length = 0; // How many samples do we have left to play (these may be 16 bit!) + self->loop = false; // When the sample is done do we loop to the start again or stop (e.g. in a wav file) + self->more_data = false; // Is there still more data to read from the sample or did we finish + + // The below section sets up the chorus effect's starting values. For a different effect this section will change + + // If we did not receive a BlockInput we need to create a default float value + if (voices == MP_OBJ_NULL) { + voices = mp_obj_new_float(MICROPY_FLOAT_CONST(1.0)); + } + synthio_block_assign_slot(voices, &self->voices, MP_QSTR_voices); + + if (delay_ms == MP_OBJ_NULL) { + delay_ms = mp_obj_new_float(MICROPY_FLOAT_CONST(50.0)); + } + synthio_block_assign_slot(delay_ms, &self->delay_ms, MP_QSTR_delay_ms); + + if (mix == MP_OBJ_NULL) { + mix = mp_obj_new_float(MICROPY_FLOAT_CONST(0.5)); + } + synthio_block_assign_slot(mix, &self->mix, MP_QSTR_mix); + + // Many effects may need buffers of what was played this shows how it was done for the chorus + // A maximum length buffer was created and then the current chorus length can be dynamically changes + // without having to reallocate a large chunk of memory. + + // Allocate the chorus buffer for the max possible delay, chorus is always 16-bit + self->max_delay_ms = max_delay_ms; + self->max_chorus_buffer_len = (uint32_t)(self->base.sample_rate / MICROPY_FLOAT_CONST(1000.0) * max_delay_ms * (self->base.channel_count * sizeof(uint16_t))); // bytes + self->chorus_buffer = m_malloc_without_collect(self->max_chorus_buffer_len); + if (self->chorus_buffer == NULL) { + common_hal_audiodelays_chorus_deinit(self); + m_malloc_fail(self->max_chorus_buffer_len); + } + memset(self->chorus_buffer, 0, self->max_chorus_buffer_len); + + // calculate the length of a single sample in milliseconds + self->sample_ms = MICROPY_FLOAT_CONST(1000.0) / self->base.sample_rate; + + // calculate everything needed for the current delay + mp_float_t f_delay_ms = synthio_block_slot_get(&self->delay_ms); + chorus_recalculate_delay(self, f_delay_ms); + + // where we are storing the next chorus sample + self->chorus_buffer_pos = 0; +} + +bool common_hal_audiodelays_chorus_deinited(audiodelays_chorus_obj_t *self) { + if (self->chorus_buffer == NULL) { + return true; + } + return false; +} + +void common_hal_audiodelays_chorus_deinit(audiodelays_chorus_obj_t *self) { + audiosample_mark_deinit(&self->base); + self->chorus_buffer = NULL; + self->buffer[0] = NULL; + self->buffer[1] = NULL; +} + +mp_obj_t common_hal_audiodelays_chorus_get_delay_ms(audiodelays_chorus_obj_t *self) { + return self->delay_ms.obj; +} + +void common_hal_audiodelays_chorus_set_delay_ms(audiodelays_chorus_obj_t *self, mp_obj_t delay_ms) { + synthio_block_assign_slot(delay_ms, &self->delay_ms, MP_QSTR_delay_ms); + + mp_float_t f_delay_ms = synthio_block_slot_get(&self->delay_ms); + + chorus_recalculate_delay(self, f_delay_ms); +} + +void chorus_recalculate_delay(audiodelays_chorus_obj_t *self, mp_float_t f_delay_ms) { + // Require that delay is at least 1 sample long + f_delay_ms = MAX(f_delay_ms, self->sample_ms); + + // Calculate the current chorus buffer length in bytes + uint32_t new_chorus_buffer_len = (uint32_t)(self->base.sample_rate / MICROPY_FLOAT_CONST(1000.0) * f_delay_ms) * (self->base.channel_count * sizeof(uint16_t)); + + if (new_chorus_buffer_len > self->max_chorus_buffer_len) { + new_chorus_buffer_len = self->max_chorus_buffer_len; + } + + self->chorus_buffer_len = new_chorus_buffer_len; + + self->current_delay_ms = f_delay_ms; +} + +mp_obj_t common_hal_audiodelays_chorus_get_voices(audiodelays_chorus_obj_t *self) { + return self->voices.obj; +} + +void common_hal_audiodelays_chorus_set_voices(audiodelays_chorus_obj_t *self, mp_obj_t voices) { + synthio_block_assign_slot(voices, &self->voices, MP_QSTR_voices); +} + +void audiodelays_chorus_reset_buffer(audiodelays_chorus_obj_t *self, + bool single_channel_output, + uint8_t channel) { + + memset(self->buffer[0], 0, self->buffer_len); + memset(self->buffer[1], 0, self->buffer_len); + memset(self->chorus_buffer, 0, self->chorus_buffer_len); +} + +mp_obj_t common_hal_audiodelays_chorus_get_mix(audiodelays_chorus_obj_t *self) { + return self->mix.obj; +} + +void common_hal_audiodelays_chorus_set_mix(audiodelays_chorus_obj_t *self, mp_obj_t arg) { + synthio_block_assign_slot(arg, &self->mix, MP_QSTR_mix); +} + +bool common_hal_audiodelays_chorus_get_playing(audiodelays_chorus_obj_t *self) { + return self->sample != NULL; +} + +void common_hal_audiodelays_chorus_play(audiodelays_chorus_obj_t *self, mp_obj_t sample, bool loop) { + audiosample_must_match(&self->base, sample, false); + + self->sample = sample; + self->loop = loop; + + audiosample_reset_buffer(self->sample, false, 0); + audioio_get_buffer_result_t result = audiosample_get_buffer(self->sample, false, 0, (uint8_t **)&self->sample_remaining_buffer, &self->sample_buffer_length); + + // Track remaining sample length in terms of bytes per sample + self->sample_buffer_length /= (self->base.bits_per_sample / 8); + // Store if we have more data in the sample to retrieve + self->more_data = result == GET_BUFFER_MORE_DATA; + + return; +} + +void common_hal_audiodelays_chorus_stop(audiodelays_chorus_obj_t *self) { + // When the sample is set to stop playing do any cleanup here + // For chorus we clear the sample but the chorus continues until the object reading our effect stops + self->sample = NULL; + return; +} + +audioio_get_buffer_result_t audiodelays_chorus_get_buffer(audiodelays_chorus_obj_t *self, bool single_channel_output, uint8_t channel, + uint8_t **buffer, uint32_t *buffer_length) { + + // Switch our buffers to the other buffer + self->last_buf_idx = !self->last_buf_idx; + + // If we are using 16 bit samples we need a 16 bit pointer, 8 bit needs an 8 bit pointer + int16_t *word_buffer = (int16_t *)self->buffer[self->last_buf_idx]; + int8_t *hword_buffer = self->buffer[self->last_buf_idx]; + uint32_t length = self->buffer_len / (self->base.bits_per_sample / 8); + + // The chorus buffer is always stored as a 16-bit value internally + int16_t *chorus_buffer = (int16_t *)self->chorus_buffer; + uint32_t chorus_buf_len = self->chorus_buffer_len / sizeof(uint16_t); + uint32_t max_chorus_buf_len = self->max_chorus_buffer_len / sizeof(uint16_t); + + // Loop over the entire length of our buffer to fill it, this may require several calls to get data from the sample + while (length != 0) { + // Check if there is no more sample to play, we will either load more data, reset the sample if loop is on or clear the sample + if (self->sample_buffer_length == 0) { + if (!self->more_data) { // The sample has indicated it has no more data to play + if (self->loop && self->sample) { // If we are supposed to loop reset the sample to the start + audiosample_reset_buffer(self->sample, false, 0); + } else { // If we were not supposed to loop the sample, stop playing it but we still need to play the chorus + self->sample = NULL; + } + } + if (self->sample) { + // Load another sample buffer to play + audioio_get_buffer_result_t result = audiosample_get_buffer(self->sample, false, 0, (uint8_t **)&self->sample_remaining_buffer, &self->sample_buffer_length); + if (result == GET_BUFFER_ERROR) { + self->sample = NULL; + self->sample_buffer_length = 0; + self->more_data = false; + } else { + // Track length in terms of words. + self->sample_buffer_length /= (self->base.bits_per_sample / 8); + self->more_data = result == GET_BUFFER_MORE_DATA; + } + } + } + + // Determine how many bytes we can process to our buffer, the less of the sample we have left and our buffer remaining + uint32_t n; + if (self->sample == NULL) { + n = MIN(length, SYNTHIO_MAX_DUR * self->base.channel_count); + } else { + n = MIN(MIN(self->sample_buffer_length, length), SYNTHIO_MAX_DUR * self->base.channel_count); + } + + // get the effect values we need from the BlockInput. These may change at run time so you need to do bounds checking if required + shared_bindings_synthio_lfo_tick(self->base.sample_rate, n / self->base.channel_count); + + int32_t voices = (int32_t)MAX(synthio_block_slot_get(&self->voices), 1.0); + int32_t mix_down_scale = SYNTHIO_MIX_DOWN_SCALE(voices); + mp_float_t mix = synthio_block_slot_get_limited(&self->mix, MICROPY_FLOAT_CONST(0.0), MICROPY_FLOAT_CONST(1.0)); + + mp_float_t f_delay_ms = synthio_block_slot_get(&self->delay_ms); + if (MICROPY_FLOAT_C_FUN(fabs)(self->current_delay_ms - f_delay_ms) >= self->sample_ms) { + chorus_recalculate_delay(self, f_delay_ms); + } + + if (self->sample == NULL) { + if (self->base.samples_signed) { + memset(word_buffer, 0, n * (self->base.bits_per_sample / 8)); + } else { + // For unsigned samples set to the middle which is "quiet" + if (MP_LIKELY(self->base.bits_per_sample == 16)) { + uint16_t *uword_buffer = (uint16_t *)word_buffer; + for (uint32_t i = 0; i < n; i++) { + *uword_buffer++ = 32768; + } + } else { + memset(hword_buffer, 128, n * (self->base.bits_per_sample / 8)); + } + } + } else { + int16_t *sample_src = (int16_t *)self->sample_remaining_buffer; // for 16-bit samples + int8_t *sample_hsrc = (int8_t *)self->sample_remaining_buffer; // for 8-bit samples + + for (uint32_t i = 0; i < n; i++) { + int32_t sample_word = 0; + if (MP_LIKELY(self->base.bits_per_sample == 16)) { + sample_word = sample_src[i]; + } else { + if (self->base.samples_signed) { + sample_word = sample_hsrc[i]; + } else { + // Be careful here changing from an 8 bit unsigned to signed into a 32-bit signed + sample_word = (int8_t)(((uint8_t)sample_hsrc[i]) ^ 0x80); + } + } + + chorus_buffer[self->chorus_buffer_pos++] = (int16_t)sample_word; + + int32_t word = 0; + if (voices == 1) { + word = sample_word; + } else { + int32_t step = chorus_buf_len / (voices - 1) - 1; + int32_t c_pos = self->chorus_buffer_pos - 1; + + for (int32_t v = 0; v < voices; v++) { + if (c_pos < 0) { + c_pos += max_chorus_buf_len; + } + word += chorus_buffer[c_pos]; + + c_pos -= step; + } + + // Dividing would get an average but does not sound as good + // Leaving this here in case someone wants to try an average instead + // word = word / voices; + + word = synthio_mix_down_sample(word, mix_down_scale); + } + + // Add original sample + effect + word = sample_word + (int32_t)(word * mix); + word = synthio_mix_down_sample(word, 2); + + if (MP_LIKELY(self->base.bits_per_sample == 16)) { + word_buffer[i] = word; + if (!self->base.samples_signed) { + word_buffer[i] ^= 0x8000; + } + } else { + int8_t out = word; + if (self->base.samples_signed) { + hword_buffer[i] = out; + } else { + hword_buffer[i] = (uint8_t)out ^ 0x80; + } + } + + if (self->chorus_buffer_pos >= max_chorus_buf_len) { + self->chorus_buffer_pos = 0; + } + } + self->sample_remaining_buffer += (n * (self->base.bits_per_sample / 8)); + self->sample_buffer_length -= n; + } + // Update the remaining length and the buffer positions based on how much we wrote into our buffer + length -= n; + word_buffer += n; + hword_buffer += n; + } + + // Finally pass our buffer and length to the calling audio function + *buffer = (uint8_t *)self->buffer[self->last_buf_idx]; + *buffer_length = self->buffer_len; + + // Chorus always returns more data but some effects may return GET_BUFFER_DONE or GET_BUFFER_ERROR (see audiocore/__init__.h) + return GET_BUFFER_MORE_DATA; +} diff --git a/shared-module/audiodelays/Chorus.h b/shared-module/audiodelays/Chorus.h new file mode 100644 index 00000000000..c2602866ef7 --- /dev/null +++ b/shared-module/audiodelays/Chorus.h @@ -0,0 +1,53 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Mark Komus +// +// SPDX-License-Identifier: MIT +#pragma once + +#include "py/obj.h" + +#include "shared-module/audiocore/__init__.h" +#include "shared-module/synthio/block.h" + +extern const mp_obj_type_t audiodelays_chorus_type; + +typedef struct { + audiosample_base_t base; + uint32_t max_delay_ms; + synthio_block_slot_t delay_ms; + mp_float_t current_delay_ms; + mp_float_t sample_ms; + synthio_block_slot_t voices; + synthio_block_slot_t mix; + + int8_t *buffer[2]; + uint8_t last_buf_idx; + uint32_t buffer_len; // max buffer in bytes + + uint8_t *sample_remaining_buffer; + uint32_t sample_buffer_length; + + bool loop; + bool more_data; + + int8_t *chorus_buffer; + uint32_t chorus_buffer_len; // bytes + uint32_t max_chorus_buffer_len; // bytes + + uint32_t chorus_buffer_pos; // words + + mp_obj_t sample; +} audiodelays_chorus_obj_t; + +void chorus_recalculate_delay(audiodelays_chorus_obj_t *self, mp_float_t f_delay_ms); + +void audiodelays_chorus_reset_buffer(audiodelays_chorus_obj_t *self, + bool single_channel_output, + uint8_t channel); + +audioio_get_buffer_result_t audiodelays_chorus_get_buffer(audiodelays_chorus_obj_t *self, + bool single_channel_output, + uint8_t channel, + uint8_t **buffer, + uint32_t *buffer_length); // length in bytes diff --git a/shared-module/audiodelays/Echo.c b/shared-module/audiodelays/Echo.c index 968c3bbddb6..3f76e465aac 100644 --- a/shared-module/audiodelays/Echo.c +++ b/shared-module/audiodelays/Echo.c @@ -11,7 +11,7 @@ #include void common_hal_audiodelays_echo_construct(audiodelays_echo_obj_t *self, uint32_t max_delay_ms, - mp_obj_t delay_ms, mp_obj_t decay, mp_obj_t mix, + mp_obj_t delay_ms, mp_obj_t decay, mp_obj_t filter, mp_obj_t mix, uint32_t buffer_size, uint8_t bits_per_sample, bool samples_signed, uint8_t channel_count, uint32_t sample_rate, bool freq_shift) { @@ -34,14 +34,14 @@ void common_hal_audiodelays_echo_construct(audiodelays_echo_obj_t *self, uint32_ // Samples are set sequentially. For stereo audio they are passed L/R/L/R/... self->buffer_len = buffer_size; // in bytes - self->buffer[0] = m_malloc(self->buffer_len); + self->buffer[0] = m_malloc_without_collect(self->buffer_len); if (self->buffer[0] == NULL) { common_hal_audiodelays_echo_deinit(self); m_malloc_fail(self->buffer_len); } memset(self->buffer[0], 0, self->buffer_len); - self->buffer[1] = m_malloc(self->buffer_len); + self->buffer[1] = m_malloc_without_collect(self->buffer_len); if (self->buffer[1] == NULL) { common_hal_audiodelays_echo_deinit(self); m_malloc_fail(self->buffer_len); @@ -59,6 +59,8 @@ void common_hal_audiodelays_echo_construct(audiodelays_echo_obj_t *self, uint32_ // The below section sets up the echo effect's starting values. For a different effect this section will change + common_hal_audiodelays_echo_set_filter(self, filter); + // If we did not receive a BlockInput we need to create a default float value if (decay == MP_OBJ_NULL) { decay = mp_obj_new_float(MICROPY_FLOAT_CONST(0.7)); @@ -71,7 +73,7 @@ void common_hal_audiodelays_echo_construct(audiodelays_echo_obj_t *self, uint32_ synthio_block_assign_slot(delay_ms, &self->delay_ms, MP_QSTR_delay_ms); if (mix == MP_OBJ_NULL) { - mix = mp_obj_new_float(MICROPY_FLOAT_CONST(0.5)); + mix = mp_obj_new_float(MICROPY_FLOAT_CONST(0.25)); } synthio_block_assign_slot(mix, &self->mix, MP_QSTR_mix); @@ -82,7 +84,7 @@ void common_hal_audiodelays_echo_construct(audiodelays_echo_obj_t *self, uint32_ // Allocate the echo buffer for the max possible delay, echo is always 16-bit self->max_delay_ms = max_delay_ms; self->max_echo_buffer_len = (uint32_t)(self->base.sample_rate / MICROPY_FLOAT_CONST(1000.0) * max_delay_ms) * (self->base.channel_count * sizeof(uint16_t)); // bytes - self->echo_buffer = m_malloc(self->max_echo_buffer_len); + self->echo_buffer = m_malloc_without_collect(self->max_echo_buffer_len); if (self->echo_buffer == NULL) { common_hal_audiodelays_echo_deinit(self); m_malloc_fail(self->max_echo_buffer_len); @@ -98,15 +100,15 @@ void common_hal_audiodelays_echo_construct(audiodelays_echo_obj_t *self, uint32_ // read is where we read previous echo from delay_ms ago to play back now // write is where the store the latest playing sample to echo back later - self->echo_buffer_read_pos = self->buffer_len / sizeof(uint16_t); - self->echo_buffer_write_pos = 0; + self->echo_buffer_left_pos = 0; - // where we read the previous echo from delay_ms ago to play back now (for freq shift) - self->echo_buffer_left_pos = self->echo_buffer_right_pos = 0; + // use a separate buffer position for the right channel + self->echo_buffer_right_pos = 0; } void common_hal_audiodelays_echo_deinit(audiodelays_echo_obj_t *self) { audiosample_mark_deinit(&self->base); + audiofilters_deinit_filter_chain(&self->filter); self->echo_buffer = NULL; self->buffer[0] = NULL; self->buffer[1] = NULL; @@ -128,30 +130,34 @@ void recalculate_delay(audiodelays_echo_obj_t *self, mp_float_t f_delay_ms) { // Require that delay is at least 1 sample long f_delay_ms = MAX(f_delay_ms, self->sample_ms); + // Calculate the maximum buffer size per channel in bytes + uint32_t max_echo_buffer_len = self->max_echo_buffer_len >> (self->base.channel_count - 1); + if (self->freq_shift) { - // Calculate the rate of iteration over the echo buffer with 8 sub-bits - self->echo_buffer_rate = (uint32_t)MAX(self->max_delay_ms / f_delay_ms * MICROPY_FLOAT_CONST(256.0), MICROPY_FLOAT_CONST(1.0)); - self->echo_buffer_len = self->max_echo_buffer_len; + // Calculate the rate of iteration over the echo buffer in fixed point + mp_float_t rate = self->max_delay_ms / f_delay_ms * (1 << AUDIODELAYS_ECHO_RATE_FRACTION_BITS); + self->echo_buffer_rate = (uint32_t)MAX(rate, MICROPY_FLOAT_CONST(1.0)); + // Only use half of the buffer per channel if stereo + self->echo_buffer_len = max_echo_buffer_len; } else { // Calculate the current echo buffer length in bytes - uint32_t new_echo_buffer_len = (uint32_t)(self->base.sample_rate / MICROPY_FLOAT_CONST(1000.0) * f_delay_ms) * (self->base.channel_count * sizeof(uint16_t)); + uint32_t new_echo_buffer_len = (uint32_t)(self->base.sample_rate / MICROPY_FLOAT_CONST(1000.0) * f_delay_ms) * sizeof(uint16_t); - // Check if our new echo is too long for our maximum buffer - if (new_echo_buffer_len > self->max_echo_buffer_len) { - return; - } else if (new_echo_buffer_len < 0.0) { // or too short! - return; - } - - // If the echo buffer is larger then our audio buffer weird things happen + // Limit to valid range if (new_echo_buffer_len < self->buffer_len) { - return; + // If the echo buffer is smaller than our audio buffer, weird things happen + new_echo_buffer_len = self->buffer_len; + } + if (new_echo_buffer_len > max_echo_buffer_len) { + new_echo_buffer_len = max_echo_buffer_len; } self->echo_buffer_len = new_echo_buffer_len; // Clear the now unused part of the buffer or some weird artifacts appear - memset(self->echo_buffer + self->echo_buffer_len, 0, self->max_echo_buffer_len - self->echo_buffer_len); + for (uint32_t i = 0; i < self->base.channel_count; i++) { + memset(self->echo_buffer + (i * max_echo_buffer_len) + self->echo_buffer_len, 0, max_echo_buffer_len - self->echo_buffer_len); + } } self->current_delay_ms = f_delay_ms; @@ -165,6 +171,14 @@ void common_hal_audiodelays_echo_set_decay(audiodelays_echo_obj_t *self, mp_obj_ synthio_block_assign_slot(decay, &self->decay, MP_QSTR_decay); } +mp_obj_t common_hal_audiodelays_echo_get_filter(audiodelays_echo_obj_t *self) { + return self->filter.obj; +} + +void common_hal_audiodelays_echo_set_filter(audiodelays_echo_obj_t *self, mp_obj_t filter_in) { + audiofilters_assign_filter_chain(&self->filter, filter_in, self->base.channel_count); +} + mp_obj_t common_hal_audiodelays_echo_get_mix(audiodelays_echo_obj_t *self) { return self->mix.obj; } @@ -178,6 +192,12 @@ bool common_hal_audiodelays_echo_get_freq_shift(audiodelays_echo_obj_t *self) { } void common_hal_audiodelays_echo_set_freq_shift(audiodelays_echo_obj_t *self, bool freq_shift) { + // Clear the echo buffer and reset buffer position if changing freq_shift modes + if (self->freq_shift != freq_shift) { + memset(self->echo_buffer, 0, self->max_echo_buffer_len); + self->echo_buffer_left_pos = 0; + self->echo_buffer_right_pos = 0; + } self->freq_shift = freq_shift; uint32_t delay_ms = (uint32_t)synthio_block_slot_get(&self->delay_ms); recalculate_delay(self, delay_ms); @@ -190,6 +210,8 @@ void audiodelays_echo_reset_buffer(audiodelays_echo_obj_t *self, memset(self->buffer[0], 0, self->buffer_len); memset(self->buffer[1], 0, self->buffer_len); memset(self->echo_buffer, 0, self->max_echo_buffer_len); + + audiofilters_reset_filter_chain(&self->filter, self->base.channel_count); } bool common_hal_audiodelays_echo_get_playing(audiodelays_echo_obj_t *self) { @@ -197,7 +219,7 @@ bool common_hal_audiodelays_echo_get_playing(audiodelays_echo_obj_t *self) { } void common_hal_audiodelays_echo_play(audiodelays_echo_obj_t *self, mp_obj_t sample, bool loop) { - audiosample_must_match(&self->base, sample); + audiosample_must_match(&self->base, sample, false); self->sample = sample; self->loop = loop; @@ -252,9 +274,15 @@ audioio_get_buffer_result_t audiodelays_echo_get_buffer(audiodelays_echo_obj_t * if (self->sample) { // Load another sample buffer to play audioio_get_buffer_result_t result = audiosample_get_buffer(self->sample, false, 0, (uint8_t **)&self->sample_remaining_buffer, &self->sample_buffer_length); - // Track length in terms of words. - self->sample_buffer_length /= (self->base.bits_per_sample / 8); - self->more_data = result == GET_BUFFER_MORE_DATA; + if (result == GET_BUFFER_ERROR) { + self->sample = NULL; + self->sample_buffer_length = 0; + self->more_data = false; + } else { + // Track length in terms of words. + self->sample_buffer_length /= (self->base.bits_per_sample / 8); + self->more_data = result == GET_BUFFER_MORE_DATA; + } } } @@ -268,24 +296,21 @@ audioio_get_buffer_result_t audiodelays_echo_get_buffer(audiodelays_echo_obj_t * // get the effect values we need from the BlockInput. These may change at run time so you need to do bounds checking if required shared_bindings_synthio_lfo_tick(self->base.sample_rate, n / self->base.channel_count); - mp_float_t mix = synthio_block_slot_get_limited(&self->mix, MICROPY_FLOAT_CONST(0.0), MICROPY_FLOAT_CONST(1.0)); + mp_float_t mix = synthio_block_slot_get_limited(&self->mix, MICROPY_FLOAT_CONST(0.0), MICROPY_FLOAT_CONST(1.0)) * MICROPY_FLOAT_CONST(2.0); mp_float_t decay = synthio_block_slot_get_limited(&self->decay, MICROPY_FLOAT_CONST(0.0), MICROPY_FLOAT_CONST(1.0)); mp_float_t f_delay_ms = synthio_block_slot_get(&self->delay_ms); - if (MICROPY_FLOAT_C_FUN(fabs)(self->current_delay_ms - f_delay_ms) >= self->sample_ms) { + // With freq_shift any change moves the rate, and recalculating is only a divide. + // Otherwise the length moves by whole samples. + if (self->freq_shift || MICROPY_FLOAT_C_FUN(fabs)(self->current_delay_ms - f_delay_ms) >= self->sample_ms) { recalculate_delay(self, f_delay_ms); } - uint32_t echo_buf_len = self->echo_buffer_len / sizeof(uint16_t); + // Tick biquad filters + audiofilters_tick_filter_chain(&self->filter); - // Set our echo buffer position accounting for stereo - uint32_t echo_buffer_pos = 0; - if (self->freq_shift) { - echo_buffer_pos = self->echo_buffer_left_pos; - if (channel == 1) { - echo_buffer_pos = self->echo_buffer_right_pos; - } - } + uint32_t echo_buf_len = self->echo_buffer_len / sizeof(uint16_t); + uint32_t max_echo_buf_len = (self->max_echo_buffer_len >> (self->base.channel_count - 1)) / sizeof(uint16_t); // If we have no sample keep the echo echoing if (self->sample == NULL) { @@ -309,21 +334,25 @@ audioio_get_buffer_result_t audiodelays_echo_get_buffer(audiodelays_echo_obj_t * int16_t echo, word = 0; uint32_t next_buffer_pos = 0; + // Get our echo buffer position and offset depending on current channel + uint32_t echo_buffer_offset = max_echo_buf_len * ((single_channel_output && channel == 1) || (!single_channel_output && (i % self->base.channel_count) == 1)); + uint32_t echo_buffer_pos = echo_buffer_offset ? self->echo_buffer_right_pos : self->echo_buffer_left_pos; + if (self->freq_shift) { - echo = echo_buffer[echo_buffer_pos >> 8]; + echo = echo_buffer[(echo_buffer_pos >> AUDIODELAYS_ECHO_RATE_FRACTION_BITS) + echo_buffer_offset]; next_buffer_pos = echo_buffer_pos + self->echo_buffer_rate; - for (uint32_t j = echo_buffer_pos >> 8; j < next_buffer_pos >> 8; j++) { - word = (int16_t)(echo_buffer[j % echo_buf_len] * decay); - echo_buffer[j % echo_buf_len] = word; + for (uint32_t j = echo_buffer_pos >> AUDIODELAYS_ECHO_RATE_FRACTION_BITS; j < next_buffer_pos >> AUDIODELAYS_ECHO_RATE_FRACTION_BITS; j++) { + word = (int16_t)(echo_buffer[(j % echo_buf_len) + echo_buffer_offset] * decay); + echo_buffer[(j % echo_buf_len) + echo_buffer_offset] = (int16_t)audiofilters_process_filter_chain(&self->filter, self->base.channel_count, !!echo_buffer_offset, word); } } else { - echo = echo_buffer[self->echo_buffer_read_pos++]; + echo = echo_buffer[echo_buffer_pos + echo_buffer_offset]; word = (int16_t)(echo * decay); - echo_buffer[self->echo_buffer_write_pos++] = word; + echo_buffer[echo_buffer_pos++ + echo_buffer_offset] = (int16_t)audiofilters_process_filter_chain(&self->filter, self->base.channel_count, !!echo_buffer_offset, word); } - word = (int16_t)(echo * mix); + word = (int16_t)(echo * MIN(mix, MICROPY_FLOAT_CONST(1.0))); if (MP_LIKELY(self->base.bits_per_sample == 16)) { word_buffer[i] = word; @@ -338,14 +367,16 @@ audioio_get_buffer_result_t audiodelays_echo_get_buffer(audiodelays_echo_obj_t * } if (self->freq_shift) { - echo_buffer_pos = next_buffer_pos % (echo_buf_len << 8); + echo_buffer_pos = next_buffer_pos % (echo_buf_len << AUDIODELAYS_ECHO_RATE_FRACTION_BITS); + } else if (!self->freq_shift && echo_buffer_pos >= echo_buf_len) { + echo_buffer_pos = 0; + } + + // Update buffer position + if (echo_buffer_offset) { + self->echo_buffer_right_pos = echo_buffer_pos; } else { - if (self->echo_buffer_read_pos >= echo_buf_len) { - self->echo_buffer_read_pos = 0; - } - if (self->echo_buffer_write_pos >= echo_buf_len) { - self->echo_buffer_write_pos = 0; - } + self->echo_buffer_left_pos = echo_buffer_pos; } } } @@ -380,50 +411,56 @@ audioio_get_buffer_result_t audiodelays_echo_get_buffer(audiodelays_echo_obj_t * int32_t echo, word = 0; uint32_t next_buffer_pos = 0; + + // Get our echo buffer position and offset depending on current channel + uint32_t echo_buffer_offset = max_echo_buf_len * ((single_channel_output && channel == 1) || (!single_channel_output && (i % self->base.channel_count) == 1)); + uint32_t echo_buffer_pos = echo_buffer_offset ? self->echo_buffer_right_pos : self->echo_buffer_left_pos; + if (self->freq_shift) { - echo = echo_buffer[echo_buffer_pos >> 8]; + echo = echo_buffer[(echo_buffer_pos >> AUDIODELAYS_ECHO_RATE_FRACTION_BITS) + echo_buffer_offset]; next_buffer_pos = echo_buffer_pos + self->echo_buffer_rate; } else { - echo = echo_buffer[self->echo_buffer_read_pos++]; + echo = echo_buffer[echo_buffer_pos + echo_buffer_offset]; word = (int32_t)(echo * decay + sample_word); } if (MP_LIKELY(self->base.bits_per_sample == 16)) { if (self->freq_shift) { - for (uint32_t j = echo_buffer_pos >> 8; j < next_buffer_pos >> 8; j++) { - word = (int32_t)(echo_buffer[j % echo_buf_len] * decay + sample_word); + for (uint32_t j = echo_buffer_pos >> AUDIODELAYS_ECHO_RATE_FRACTION_BITS; j < next_buffer_pos >> AUDIODELAYS_ECHO_RATE_FRACTION_BITS; j++) { + word = (int32_t)(echo_buffer[(j % echo_buf_len) + echo_buffer_offset] * decay + sample_word); word = synthio_mix_down_sample(word, SYNTHIO_MIX_DOWN_SCALE(2)); - echo_buffer[j % echo_buf_len] = (int16_t)word; + echo_buffer[(j % echo_buf_len) + echo_buffer_offset] = (int16_t)audiofilters_process_filter_chain(&self->filter, self->base.channel_count, !!echo_buffer_offset, word); } } else { word = synthio_mix_down_sample(word, SYNTHIO_MIX_DOWN_SCALE(2)); - echo_buffer[self->echo_buffer_write_pos++] = (int16_t)word; + echo_buffer[echo_buffer_pos++ + echo_buffer_offset] = (int16_t)audiofilters_process_filter_chain(&self->filter, self->base.channel_count, !!echo_buffer_offset, word); } } else { if (self->freq_shift) { - for (uint32_t j = echo_buffer_pos >> 8; j < next_buffer_pos >> 8; j++) { - word = (int32_t)(echo_buffer[j % echo_buf_len] * decay + sample_word); + for (uint32_t j = echo_buffer_pos >> AUDIODELAYS_ECHO_RATE_FRACTION_BITS; j < next_buffer_pos >> AUDIODELAYS_ECHO_RATE_FRACTION_BITS; j++) { + word = (int32_t)(echo_buffer[(j % echo_buf_len) + echo_buffer_offset] * decay + sample_word); // Do not have mix_down for 8 bit so just hard cap samples into 1 byte word = MIN(MAX(word, -128), 127); - echo_buffer[j % echo_buf_len] = (int8_t)word; + echo_buffer[(j % echo_buf_len) + echo_buffer_offset] = (int8_t)audiofilters_process_filter_chain(&self->filter, self->base.channel_count, !!echo_buffer_offset, word); } } else { // Do not have mix_down for 8 bit so just hard cap samples into 1 byte word = MIN(MAX(word, -128), 127); - echo_buffer[self->echo_buffer_write_pos++] = (int8_t)word; + echo_buffer[echo_buffer_pos++ + echo_buffer_offset] = (int8_t)audiofilters_process_filter_chain(&self->filter, self->base.channel_count, !!echo_buffer_offset, word); } } - word = echo + sample_word; + word = (int32_t)((sample_word * MIN(MICROPY_FLOAT_CONST(2.0) - mix, MICROPY_FLOAT_CONST(1.0))) + + (echo * MIN(mix, MICROPY_FLOAT_CONST(1.0)))); word = synthio_mix_down_sample(word, SYNTHIO_MIX_DOWN_SCALE(2)); if (MP_LIKELY(self->base.bits_per_sample == 16)) { - word_buffer[i] = (int16_t)((sample_word * (MICROPY_FLOAT_CONST(1.0) - mix)) + (word * mix)); + word_buffer[i] = (int16_t)word; if (!self->base.samples_signed) { word_buffer[i] ^= 0x8000; } } else { - int8_t mixed = (int16_t)((sample_word * (MICROPY_FLOAT_CONST(1.0) - mix)) + (word * mix)); + int8_t mixed = (int16_t)word; if (self->base.samples_signed) { hword_buffer[i] = mixed; } else { @@ -432,14 +469,16 @@ audioio_get_buffer_result_t audiodelays_echo_get_buffer(audiodelays_echo_obj_t * } if (self->freq_shift) { - echo_buffer_pos = next_buffer_pos % (echo_buf_len << 8); + echo_buffer_pos = next_buffer_pos % (echo_buf_len << AUDIODELAYS_ECHO_RATE_FRACTION_BITS); + } else if (!self->freq_shift && echo_buffer_pos >= echo_buf_len) { + echo_buffer_pos = 0; + } + + // Update buffer position + if (echo_buffer_offset) { + self->echo_buffer_right_pos = echo_buffer_pos; } else { - if (self->echo_buffer_read_pos >= echo_buf_len) { - self->echo_buffer_read_pos = 0; - } - if (self->echo_buffer_write_pos >= echo_buf_len) { - self->echo_buffer_write_pos = 0; - } + self->echo_buffer_left_pos = echo_buffer_pos; } } } @@ -451,14 +490,6 @@ audioio_get_buffer_result_t audiodelays_echo_get_buffer(audiodelays_echo_obj_t * self->sample_remaining_buffer += (n * (self->base.bits_per_sample / 8)); self->sample_buffer_length -= n; } - - if (self->freq_shift) { - if (channel == 0) { - self->echo_buffer_left_pos = echo_buffer_pos; - } else if (channel == 1) { - self->echo_buffer_right_pos = echo_buffer_pos; - } - } } // Finally pass our buffer and length to the calling audio function diff --git a/shared-module/audiodelays/Echo.h b/shared-module/audiodelays/Echo.h index 7f5dbb69f09..1d2a037c204 100644 --- a/shared-module/audiodelays/Echo.h +++ b/shared-module/audiodelays/Echo.h @@ -8,11 +8,18 @@ #include "py/obj.h" #include "shared-module/audiocore/__init__.h" +#include "shared-module/audiofilters/__init__.h" #include "shared-module/synthio/__init__.h" #include "shared-module/synthio/block.h" +#include "shared-module/synthio/Biquad.h" extern const mp_obj_type_t audiodelays_echo_type; +// Fractional bits of the uint32_t position and rate used when freq_shift=True. +#define AUDIODELAYS_ECHO_RATE_FRACTION_BITS 12 +// The largest echo buffer per channel. Position and rate each stay under 2^31 so their sum fits. +#define AUDIODELAYS_ECHO_MAX_BUFFER_SAMPLES ((1 << (31 - AUDIODELAYS_ECHO_RATE_FRACTION_BITS)) - 1) + typedef struct { audiosample_base_t base; uint32_t max_delay_ms; @@ -20,6 +27,7 @@ typedef struct { mp_float_t current_delay_ms; mp_float_t sample_ms; synthio_block_slot_t decay; + audiofilters_filter_chain_t filter; synthio_block_slot_t mix; int8_t *buffer[2]; @@ -37,12 +45,9 @@ typedef struct { uint32_t echo_buffer_len; // bytes uint32_t max_echo_buffer_len; // bytes - uint32_t echo_buffer_read_pos; // words - uint32_t echo_buffer_write_pos; // words - - uint32_t echo_buffer_rate; // words << 8 - uint32_t echo_buffer_left_pos; // words << 8 - uint32_t echo_buffer_right_pos; // words << 8 + uint32_t echo_buffer_left_pos; // words (fixed point when freq_shift=True) + uint32_t echo_buffer_right_pos; // words (fixed point when freq_shift=True) + uint32_t echo_buffer_rate; // words, fixed point mp_obj_t sample; } audiodelays_echo_obj_t; diff --git a/shared-module/audiodelays/Flanger.c b/shared-module/audiodelays/Flanger.c new file mode 100644 index 00000000000..bf281052eca --- /dev/null +++ b/shared-module/audiodelays/Flanger.c @@ -0,0 +1,414 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT +#include "shared-bindings/audiodelays/Flanger.h" +#include "shared-bindings/audiocore/__init__.h" + +#include +#include "py/runtime.h" + +// The largest delay we will ever read, in frames. +#define FLANGER_MAX_DELAY_FRAMES (65535u) + +// Convert a delay in milliseconds to a Q16.16 count of frames, clamped so that both interpolation +// taps always land inside the delay line. +static uint32_t flanger_ms_to_frames_q16(audiodelays_flanger_obj_t *self, mp_float_t ms) { + mp_float_t frames = ms * self->base.sample_rate / MICROPY_FLOAT_CONST(1000.0); + mp_float_t max_frames = (mp_float_t)MIN(self->delay_buffer_frames - 2, FLANGER_MAX_DELAY_FRAMES); + + // A delay of less than one frame would read the frame we are about to overwrite + frames = MIN(MAX(frames, MICROPY_FLOAT_CONST(1.0)), max_frames); + + return (uint32_t)(frames * MICROPY_FLOAT_CONST(65536.0)); +} + +void common_hal_audiodelays_flanger_construct(audiodelays_flanger_obj_t *self, uint32_t max_delay_ms, + mp_obj_t min_delay_ms, mp_obj_t rate, mp_obj_t depth, mp_obj_t feedback, mp_obj_t mix, bool invert, + uint32_t buffer_size, uint8_t bits_per_sample, + bool samples_signed, uint8_t channel_count, uint32_t sample_rate) { + + // Basic format settings every effect and audio sample has + self->base.bits_per_sample = bits_per_sample; + self->base.samples_signed = samples_signed; // Are the samples we provide signed (common is true) + self->base.channel_count = channel_count; // Channels can be 1 for mono or 2 for stereo + self->base.sample_rate = sample_rate; // Sample rate for the effect, this generally needs to match all audio objects + self->base.single_buffer = false; + self->base.max_buffer_length = buffer_size; + + // To smooth things out as CircuitPython is doing other tasks most audio objects have a buffer + // A double buffer is set up here so the audio output can use DMA on buffer 1 while we + // write to and create buffer 2. + // This buffer is what is passed to the audio component that plays the effect. + // Samples are set sequentially. For stereo audio they are passed L/R/L/R/... + self->buffer_len = buffer_size; // in bytes + + self->buffer[0] = m_malloc_maybe_without_collect(self->buffer_len); + if (self->buffer[0] == NULL) { + common_hal_audiodelays_flanger_deinit(self); + m_malloc_fail(self->buffer_len); + } + memset(self->buffer[0], 0, self->buffer_len); + + self->buffer[1] = m_malloc_maybe_without_collect(self->buffer_len); + if (self->buffer[1] == NULL) { + common_hal_audiodelays_flanger_deinit(self); + m_malloc_fail(self->buffer_len); + } + memset(self->buffer[1], 0, self->buffer_len); + + self->last_buf_idx = 1; // Which buffer to use first, toggle between 0 and 1 + + // Initialize other values most effects will need. + self->sample = NULL; // The current playing sample + self->sample_remaining_buffer = NULL; // Pointer to the start of the sample buffer we have not played + self->sample_buffer_length = 0; // How many samples do we have left to play (these may be 16 bit!) + self->loop = false; // When the sample is done do we loop to the start again or stop (e.g. in a wav file) + self->more_data = false; // Is there still more data to read from the sample or did we finish + + // The below section sets up the flanger effect's starting values. + + // If we did not receive a BlockInput we need to create a default float value + if (min_delay_ms == MP_OBJ_NULL) { + min_delay_ms = mp_obj_new_float(MICROPY_FLOAT_CONST(1.0)); + } + synthio_block_assign_slot(min_delay_ms, &self->min_delay_ms, MP_QSTR_min_delay_ms); + + if (rate == MP_OBJ_NULL) { + rate = mp_obj_new_float(MICROPY_FLOAT_CONST(0.5)); + } + synthio_block_assign_slot(rate, &self->rate, MP_QSTR_rate); + + if (depth == MP_OBJ_NULL) { + depth = mp_obj_new_float(MICROPY_FLOAT_CONST(0.5)); + } + synthio_block_assign_slot(depth, &self->depth, MP_QSTR_depth); + + if (feedback == MP_OBJ_NULL) { + feedback = mp_obj_new_float(MICROPY_FLOAT_CONST(0.5)); + } + synthio_block_assign_slot(feedback, &self->feedback, MP_QSTR_feedback); + + if (mix == MP_OBJ_NULL) { + mix = mp_obj_new_float(MICROPY_FLOAT_CONST(0.5)); + } + synthio_block_assign_slot(mix, &self->mix, MP_QSTR_mix); + + self->invert = invert; + self->max_delay_ms = max_delay_ms; + + // calculate the length of a single sample in milliseconds + self->sample_ms = MICROPY_FLOAT_CONST(1000.0) / self->base.sample_rate; + + // Allocate the delay line for the largest delay we can sweep to. It is always 16-bit and each + // channel gets its own contiguous region. The two extra frames are interpolation headroom: at + // the top of the sweep the two taps sit at the far end of the line and without the extra room + // the older of the two would alias onto the frame we are about to write. + self->delay_buffer_frames = (uint32_t)(self->base.sample_rate / MICROPY_FLOAT_CONST(1000.0) * max_delay_ms) + 2; + size_t delay_buffer_size = self->delay_buffer_frames * self->base.channel_count * sizeof(int16_t); + self->delay_buffer = m_malloc_maybe_without_collect(delay_buffer_size); + if (self->delay_buffer == NULL) { + common_hal_audiodelays_flanger_deinit(self); + m_malloc_fail(delay_buffer_size); + } + memset(self->delay_buffer, 0, delay_buffer_size); + + self->delay_buffer_pos[0] = self->delay_buffer_pos[1] = 0; + self->lfo_phase[0] = self->lfo_phase[1] = 0; + self->lfo_phase_inc = 0; +} + +bool common_hal_audiodelays_flanger_deinited(audiodelays_flanger_obj_t *self) { + if (self->delay_buffer == NULL) { + return true; + } + return false; +} + +void common_hal_audiodelays_flanger_deinit(audiodelays_flanger_obj_t *self) { + audiosample_mark_deinit(&self->base); + self->delay_buffer = NULL; + self->buffer[0] = NULL; + self->buffer[1] = NULL; +} + +mp_obj_t common_hal_audiodelays_flanger_get_min_delay_ms(audiodelays_flanger_obj_t *self) { + return self->min_delay_ms.obj; +} + +void common_hal_audiodelays_flanger_set_min_delay_ms(audiodelays_flanger_obj_t *self, mp_obj_t min_delay_ms) { + synthio_block_assign_slot(min_delay_ms, &self->min_delay_ms, MP_QSTR_min_delay_ms); +} + +mp_obj_t common_hal_audiodelays_flanger_get_rate(audiodelays_flanger_obj_t *self) { + return self->rate.obj; +} + +void common_hal_audiodelays_flanger_set_rate(audiodelays_flanger_obj_t *self, mp_obj_t rate) { + synthio_block_assign_slot(rate, &self->rate, MP_QSTR_rate); +} + +mp_obj_t common_hal_audiodelays_flanger_get_depth(audiodelays_flanger_obj_t *self) { + return self->depth.obj; +} + +void common_hal_audiodelays_flanger_set_depth(audiodelays_flanger_obj_t *self, mp_obj_t depth) { + synthio_block_assign_slot(depth, &self->depth, MP_QSTR_depth); +} + +mp_obj_t common_hal_audiodelays_flanger_get_feedback(audiodelays_flanger_obj_t *self) { + return self->feedback.obj; +} + +void common_hal_audiodelays_flanger_set_feedback(audiodelays_flanger_obj_t *self, mp_obj_t feedback) { + synthio_block_assign_slot(feedback, &self->feedback, MP_QSTR_feedback); +} + +mp_obj_t common_hal_audiodelays_flanger_get_mix(audiodelays_flanger_obj_t *self) { + return self->mix.obj; +} + +void common_hal_audiodelays_flanger_set_mix(audiodelays_flanger_obj_t *self, mp_obj_t arg) { + synthio_block_assign_slot(arg, &self->mix, MP_QSTR_mix); +} + +// Fold the sawtooth phase accumulator into a triangle in the range 0 to 65535 +static uint32_t flanger_phase_to_triangle(uint32_t phase) { + uint32_t tri = phase >> 15; + if (tri > 65535) { + tri = 131071 - tri; + } + return tri; +} + +mp_float_t common_hal_audiodelays_flanger_get_lfo_value(audiodelays_flanger_obj_t *self) { + return (mp_float_t)flanger_phase_to_triangle(self->lfo_phase[0]) / MICROPY_FLOAT_CONST(65535.0); +} + +bool common_hal_audiodelays_flanger_get_invert(audiodelays_flanger_obj_t *self) { + return self->invert; +} + +void common_hal_audiodelays_flanger_set_invert(audiodelays_flanger_obj_t *self, bool invert) { + self->invert = invert; +} + +void audiodelays_flanger_reset_buffer(audiodelays_flanger_obj_t *self, + bool single_channel_output, + uint8_t channel) { + + memset(self->buffer[0], 0, self->buffer_len); + memset(self->buffer[1], 0, self->buffer_len); + memset(self->delay_buffer, 0, self->delay_buffer_frames * self->base.channel_count * sizeof(int16_t)); + self->delay_buffer_pos[0] = self->delay_buffer_pos[1] = 0; + self->lfo_phase[0] = self->lfo_phase[1] = 0; +} + +bool common_hal_audiodelays_flanger_get_playing(audiodelays_flanger_obj_t *self) { + return self->sample != NULL; +} + +void common_hal_audiodelays_flanger_play(audiodelays_flanger_obj_t *self, mp_obj_t sample, bool loop) { + audiosample_must_match(&self->base, sample, false); + + self->sample = sample; + self->loop = loop; + + audiosample_reset_buffer(self->sample, false, 0); + audioio_get_buffer_result_t result = audiosample_get_buffer(self->sample, false, 0, (uint8_t **)&self->sample_remaining_buffer, &self->sample_buffer_length); + + // Track remaining sample length in terms of bytes per sample + self->sample_buffer_length /= (self->base.bits_per_sample / 8); + // Store if we have more data in the sample to retrieve + self->more_data = result == GET_BUFFER_MORE_DATA; +} + +void common_hal_audiodelays_flanger_stop(audiodelays_flanger_obj_t *self) { + self->sample = NULL; +} + +audioio_get_buffer_result_t audiodelays_flanger_get_buffer(audiodelays_flanger_obj_t *self, bool single_channel_output, uint8_t channel, + uint8_t **buffer, uint32_t *buffer_length) { + + if (!single_channel_output) { + channel = 0; + } + + // Switch our buffers to the other buffer + self->last_buf_idx = !self->last_buf_idx; + + // If we are using 16 bit samples we need a 16 bit pointer, 8 bit needs an 8 bit pointer + int16_t *word_buffer = (int16_t *)self->buffer[self->last_buf_idx]; + int8_t *hword_buffer = self->buffer[self->last_buf_idx]; + uint32_t length = self->buffer_len / (self->base.bits_per_sample / 8); + + uint8_t channel_count = self->base.channel_count; + uint32_t frames = self->delay_buffer_frames; + + // For single channel output every word in this call belongs to `channel`. Otherwise the + // channels are interleaved and alternate with every word. + bool single_right = single_channel_output && channel == 1 && channel_count == 2; + + // Loop over the entire length of our buffer to fill it, this may require several calls to get data from the sample + while (length != 0) { + // Check if there is no more sample to play, we will either load more data, reset the sample if loop is on or clear the sample + if (self->sample_buffer_length == 0) { + if (!self->more_data) { // The sample has indicated it has no more data to play + if (self->loop && self->sample) { // If we are supposed to loop reset the sample to the start + audiosample_reset_buffer(self->sample, false, 0); + } else { // If we were not supposed to loop the sample, stop playing it + self->sample = NULL; + } + } + if (self->sample) { + // Load another sample buffer to play + audioio_get_buffer_result_t result = audiosample_get_buffer(self->sample, false, 0, (uint8_t **)&self->sample_remaining_buffer, &self->sample_buffer_length); + // Track length in terms of words. + self->sample_buffer_length /= (self->base.bits_per_sample / 8); + self->more_data = result == GET_BUFFER_MORE_DATA; + } + } + + if (self->sample == NULL) { + // tick all block inputs so that anything attached to them stays in sync + shared_bindings_synthio_lfo_tick(self->base.sample_rate, length / channel_count); + (void)synthio_block_slot_get(&self->min_delay_ms); + (void)synthio_block_slot_get(&self->rate); + (void)synthio_block_slot_get(&self->depth); + (void)synthio_block_slot_get(&self->feedback); + (void)synthio_block_slot_get(&self->mix); + + if (self->base.samples_signed) { + memset(word_buffer, 0, length * (self->base.bits_per_sample / 8)); + } else { + // For unsigned samples set to the middle which is "quiet" + if (MP_LIKELY(self->base.bits_per_sample == 16)) { + uint16_t *uword_buffer = (uint16_t *)word_buffer; + while (length--) { + *uword_buffer++ = 32768; + } + } else { + memset(hword_buffer, 128, length * (self->base.bits_per_sample / 8)); + } + } + + length = 0; + } else { + // we have a sample to play and flange + // Determine how many bytes we can process to our buffer, the less of the sample we have left and our buffer remaining + uint32_t num_bytes = MIN(MIN(self->sample_buffer_length, length), SYNTHIO_MAX_DUR * channel_count); + + int16_t *sample_src = (int16_t *)self->sample_remaining_buffer; // for 16-bit samples + int8_t *sample_hsrc = (int8_t *)self->sample_remaining_buffer; // for 8-bit samples + + // get the effect values we need from the BlockInput + shared_bindings_synthio_lfo_tick(self->base.sample_rate, num_bytes / channel_count); + mp_float_t f_min_delay_ms = synthio_block_slot_get_limited(&self->min_delay_ms, self->sample_ms, (mp_float_t)self->max_delay_ms); + mp_float_t f_rate = synthio_block_slot_get_limited(&self->rate, MICROPY_FLOAT_CONST(0.0), MICROPY_FLOAT_CONST(20.0)); + mp_float_t f_depth = synthio_block_slot_get_limited(&self->depth, MICROPY_FLOAT_CONST(0.0), MICROPY_FLOAT_CONST(1.0)); + int32_t feedback = (int32_t)(synthio_block_slot_get_limited(&self->feedback, MICROPY_FLOAT_CONST(-0.95), MICROPY_FLOAT_CONST(0.95)) * 32767); + int32_t mix = (int32_t)(synthio_block_slot_get_limited(&self->mix, MICROPY_FLOAT_CONST(0.0), MICROPY_FLOAT_CONST(1.0)) * 32767); + + // The sweep runs upward from min_delay_ms towards max_delay_ms rather than around a + // centre, so no combination of min_delay_ms and depth can push it out of the delay line. + mp_float_t sweep_top_ms = f_min_delay_ms + f_depth * ((mp_float_t)self->max_delay_ms - f_min_delay_ms); + uint32_t delay_min_q16 = flanger_ms_to_frames_q16(self, f_min_delay_ms); + uint32_t delay_span_q16 = flanger_ms_to_frames_q16(self, sweep_top_ms) - delay_min_q16; + + // How far the LFO advances each frame. A rate at or above half the sample rate is + // meaningless, and clamping there also keeps the conversion inside a uint32_t. + mp_float_t phase_inc = MIN(f_rate / self->base.sample_rate, MICROPY_FLOAT_CONST(0.5)); + self->lfo_phase_inc = (uint32_t)(phase_inc * MICROPY_FLOAT_CONST(4294967296.0)); + + for (uint32_t i = 0; i < num_bytes; i++) { + bool right_channel = single_channel_output ? single_right : ((i % channel_count) == 1); + + int32_t sample_word = 0; + if (MP_LIKELY(self->base.bits_per_sample == 16)) { + sample_word = sample_src[i]; + } else { + if (self->base.samples_signed) { + sample_word = sample_hsrc[i]; + } else { + // changing from an 8 bit unsigned to signed into a 32-bit signed + sample_word = (int8_t)(((uint8_t)sample_hsrc[i]) ^ 0x80); + } + } + + // Advance this channel's LFO by one frame. Each channel has its own accumulator so + // that the sweep runs at `rate` whether the channels arrive interleaved (both + // accumulators step once per frame) or one channel per call. + self->lfo_phase[right_channel] += self->lfo_phase_inc; + + uint32_t tri = flanger_phase_to_triangle(self->lfo_phase[right_channel]); + + // The delay for this frame, in Q16.16 frames + uint32_t delay_q16 = delay_min_q16 + (uint32_t)(((uint64_t)delay_span_q16 * tri) >> 16); + uint32_t delay_int = delay_q16 >> 16; + uint32_t delay_frac = delay_q16 & 0xffff; + + int16_t *line = self->delay_buffer + (right_channel ? frames : 0); + uint32_t w = self->delay_buffer_pos[right_channel]; + + // Two taps straddling the fractional delay, counted back from the write head. + // delay_int is at most frames - 2 so neither index can escape the region. + uint32_t r0 = w + frames - delay_int; + if (r0 >= frames) { + r0 -= frames; + } + uint32_t r1 = r0 ? r0 - 1 : frames - 1; + + // Linear interpolation between them + int32_t s0 = line[r0]; + int32_t s1 = line[r1]; + int32_t wet = s0 + (((s1 - s0) * (int32_t)delay_frac) >> 16); + + // Write the input plus the regenerated signal back into the line + line[w] = synthio_sat16(sample_word + synthio_sat16(wet * feedback, 15), 0); + self->delay_buffer_pos[right_channel] = (w + 1 == frames) ? 0 : w + 1; + + int32_t word; + if (mix <= 328) { // if mix is zero (0.01 in fixed point), pure sample only + // Note that we still ran the delay line above. + word = sample_word; + } else { + int32_t wet_word = synthio_sat16(wet * mix, 15); + // Add (or, inverted, subtract) original sample + effect + word = self->invert ? sample_word - wet_word : sample_word + wet_word; + word = synthio_mix_down_sample(word, SYNTHIO_MIX_DOWN_SCALE(2)); + } + + if (MP_LIKELY(self->base.bits_per_sample == 16)) { + word_buffer[i] = word; + if (!self->base.samples_signed) { + word_buffer[i] ^= 0x8000; + } + } else { + // 8-bit samples have no headroom for synthio_mix_down_sample to work with, so + // clamp instead or the sum of the dry and wet signals wraps around + int8_t out = MIN(MAX(word, -128), 127); + if (self->base.samples_signed) { + hword_buffer[i] = out; + } else { + hword_buffer[i] = (uint8_t)out ^ 0x80; + } + } + } + + // Update the remaining length and the buffer positions based on how much we wrote into our buffer + length -= num_bytes; + word_buffer += num_bytes; + hword_buffer += num_bytes; + self->sample_remaining_buffer += (num_bytes * (self->base.bits_per_sample / 8)); + self->sample_buffer_length -= num_bytes; + } + } + + // Finally pass our buffer and length to the calling audio function + *buffer = (uint8_t *)self->buffer[self->last_buf_idx]; + *buffer_length = self->buffer_len; + + // Flanger always returns more data but some effects may return GET_BUFFER_DONE or GET_BUFFER_ERROR (see audiocore/__init__.h) + return GET_BUFFER_MORE_DATA; +} diff --git a/shared-module/audiodelays/Flanger.h b/shared-module/audiodelays/Flanger.h new file mode 100644 index 00000000000..6e8a37f51e2 --- /dev/null +++ b/shared-module/audiodelays/Flanger.h @@ -0,0 +1,62 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT +#pragma once + +#include "py/obj.h" + +#include "shared-module/audiocore/__init__.h" +#include "shared-module/synthio/block.h" + +extern const mp_obj_type_t audiodelays_flanger_type; + +typedef struct { + audiosample_base_t base; + + // Effect parameters. + synthio_block_slot_t min_delay_ms; // floor of the sweep + synthio_block_slot_t rate; // LFO frequency in Hz + synthio_block_slot_t depth; // 0 to 1, portion of the available range swept + synthio_block_slot_t feedback; // -0.95 to 0.95, regeneration + synthio_block_slot_t mix; // 0 to 1, dry to wet + + uint32_t max_delay_ms; + mp_float_t sample_ms; // length of a single sample in milliseconds + + bool invert; // subtract the wet signal instead of adding it + + int8_t *buffer[2]; + uint8_t last_buf_idx; + uint32_t buffer_len; // max buffer in bytes + + uint8_t *sample_remaining_buffer; + uint32_t sample_buffer_length; + + bool loop; + bool more_data; + + // The delay line is always 16-bit and is split into one contiguous region per channel so + // that read/write positions are plain frame counts and wrapping is a single modulo. + int16_t *delay_buffer; + uint32_t delay_buffer_frames; // frames in each per channel region + uint32_t delay_buffer_pos[2]; // write position in frames, per channel + + // Internal LFO. One phase accumulator per channel so that the sweep advances once per frame + // whether the channels are interleaved in one call or requested one channel at a time. + uint32_t lfo_phase[2]; // Q0.32, wraps naturally + uint32_t lfo_phase_inc; // Q0.32 step per frame, recalculated per chunk from rate + + mp_obj_t sample; +} audiodelays_flanger_obj_t; + +void audiodelays_flanger_reset_buffer(audiodelays_flanger_obj_t *self, + bool single_channel_output, + uint8_t channel); + +audioio_get_buffer_result_t audiodelays_flanger_get_buffer(audiodelays_flanger_obj_t *self, + bool single_channel_output, + uint8_t channel, + uint8_t **buffer, + uint32_t *buffer_length); // length in bytes diff --git a/shared-module/audiodelays/GranularPitchShift.c b/shared-module/audiodelays/GranularPitchShift.c new file mode 100644 index 00000000000..a737307d553 --- /dev/null +++ b/shared-module/audiodelays/GranularPitchShift.c @@ -0,0 +1,478 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT +#include "shared-bindings/audiodelays/GranularPitchShift.h" +#include "shared-bindings/audiocore/__init__.h" + +#include +#include "py/runtime.h" +#include + +void common_hal_audiodelays_granular_pitch_shift_construct(audiodelays_granular_pitch_shift_obj_t *self, + mp_obj_t semitones, mp_obj_t mix, uint32_t grain_size, uint32_t density, + mp_float_t spread, uint32_t buffer_size, uint8_t bits_per_sample, bool samples_signed, + uint8_t channel_count, uint32_t sample_rate) { + + // Basic settings every effect and audio sample has + // These are the effect's values, not the source sample(s) + self->base.bits_per_sample = bits_per_sample; // Most common is 16, but 8 is also supported in many places + self->base.samples_signed = samples_signed; // Are the samples we provide signed + self->base.channel_count = channel_count; // Channels can be 1 for mono or 2 for stereo + self->base.sample_rate = sample_rate; // Sample rate for the effect, this generally needs to match all audio objects + self->base.single_buffer = false; + self->base.max_buffer_length = buffer_size; + + // To smooth things out as CircuitPython is doing other tasks most audio objects have a buffer + // A double buffer is set up here so the audio output can use DMA on buffer 1 while we + // write to and create buffer 2. + // This buffer is what is passed to the audio component that plays the effect. + // Samples are set sequentially. For stereo audio they are passed L/R/L/R/... + self->buffer_len = buffer_size; // in bytes + + self->buffer[0] = m_malloc_without_collect(self->buffer_len); + if (self->buffer[0] == NULL) { + common_hal_audiodelays_granular_pitch_shift_deinit(self); + m_malloc_fail(self->buffer_len); + } + memset(self->buffer[0], 0, self->buffer_len); + + self->buffer[1] = m_malloc_without_collect(self->buffer_len); + if (self->buffer[1] == NULL) { + common_hal_audiodelays_granular_pitch_shift_deinit(self); + m_malloc_fail(self->buffer_len); + } + memset(self->buffer[1], 0, self->buffer_len); + + self->last_buf_idx = 1; // Which buffer to use first, toggle between 0 and 1 + + // Initialize other values most effects will need. + self->sample = NULL; // The current playing sample + self->sample_remaining_buffer = NULL; // Pointer to the start of the sample buffer we have not played + self->sample_buffer_length = 0; // How many samples do we have left to play (these may be 16 bit!) + self->loop = false; // When the sample is done do we loop to the start again or stop (e.g. in a wav file) + self->more_data = false; // Is there still more data to read from the sample or did we finish + + // The below section sets up the effect's starting values. + + synthio_block_assign_slot(semitones, &self->semitones, MP_QSTR_semitones); + synthio_block_assign_slot(mix, &self->mix, MP_QSTR_mix); + + // Grain scheduling parameters. `density` (number of overlapping grains) is + // clamped to the fixed grain pool size so allocation stays deterministic. + self->grain_size = grain_size; + if (density < 1) { + density = 1; + } + if (density > GRANULAR_MAX_GRAINS) { + density = GRANULAR_MAX_GRAINS; + } + self->density = density; + + // Grain-start jitter amount and the PRNG that drives it. Seeded with a fixed + // nonzero constant so xorshift32 never degenerates to the all-zero state and + // the jitter sequence is reproducible from run to run. + common_hal_audiodelays_granular_pitch_shift_set_spread(self, spread); + self->rng_state = 0x1234abcdu; + + // Normalization for the overlap-add gain of the grain envelopes. A Hann + // window overlapped at hop = grain_size / density sums to a constant gain of + // density/2, so we scale the summed grains by 2/density in Q15 to keep the + // output at ~unity. Cap at 1.0 so the degenerate density==1 case (a single + // windowed grain, no overlap partner) is never amplified. + self->grain_gain = (1 << 15) * 2 / density; // 2/density in Q15 + if (self->grain_gain > (1 << 15)) { + self->grain_gain = (1 << 15); + } + + // Capture buffer (the delay line grains read from), stored as 16-bit, + // planar per channel. Length is grain_size * 2 words per channel so a grain + // starting grain_size words behind the write pointer never overruns the live + // write cursor even when reading ahead at a raised pitch + self->capture_len = self->grain_size * 2; // words per channel + uint32_t capture_bytes = self->capture_len * self->base.channel_count * sizeof(int16_t); + self->capture_buffer = m_malloc_without_collect(capture_bytes); + if (self->capture_buffer == NULL) { + common_hal_audiodelays_granular_pitch_shift_deinit(self); + m_malloc_fail(capture_bytes); + } + memset(self->capture_buffer, 0, capture_bytes); + self->write_index = 0; + + // Precompute the grain amplitude envelope: a raised-cosine (Hann) window in + // Q15 (0..32767), indexed directly by a grain's phase. + self->envelope_len = self->grain_size; + uint32_t envelope_bytes = self->envelope_len * sizeof(int16_t); + self->envelope_table = m_malloc_without_collect(envelope_bytes); + if (self->envelope_table == NULL) { + common_hal_audiodelays_granular_pitch_shift_deinit(self); + m_malloc_fail(envelope_bytes); + } + mp_float_t denom = (self->envelope_len > 1) ? (mp_float_t)(self->envelope_len - 1) : MICROPY_FLOAT_CONST(1.0); + for (uint32_t n = 0; n < self->envelope_len; n++) { + mp_float_t w = MICROPY_FLOAT_CONST(0.5) * + (MICROPY_FLOAT_CONST(1.0) - MICROPY_FLOAT_C_FUN(cos)( + MICROPY_FLOAT_CONST(2.0) * MICROPY_FLOAT_CONST(3.14159265358979323846) * (mp_float_t)n / denom)); + self->envelope_table[n] = (int16_t)(w * MICROPY_FLOAT_CONST(32767.0)); + } + + // Deactivate all grains and prime the scheduler so the first grain launches + // immediately on the first output sample. + for (uint32_t i = 0; i < GRANULAR_MAX_GRAINS; i++) { + self->grains[i].active = false; + } + self->samples_until_next_grain = 0; + + // Calculate the fixed-point read-rate increment applied to launched grains. + mp_float_t f_semitones = synthio_block_slot_get(&self->semitones); + granular_pitch_shift_recalculate_rate(self, f_semitones); +} + +void common_hal_audiodelays_granular_pitch_shift_deinit(audiodelays_granular_pitch_shift_obj_t *self) { + audiosample_mark_deinit(&self->base); + self->envelope_table = NULL; + self->capture_buffer = NULL; + self->buffer[0] = NULL; + self->buffer[1] = NULL; +} + +mp_obj_t common_hal_audiodelays_granular_pitch_shift_get_semitones(audiodelays_granular_pitch_shift_obj_t *self) { + return self->semitones.obj; +} + +void common_hal_audiodelays_granular_pitch_shift_set_semitones(audiodelays_granular_pitch_shift_obj_t *self, mp_obj_t semitones_in) { + synthio_block_assign_slot(semitones_in, &self->semitones, MP_QSTR_semitones); + mp_float_t semitones = synthio_block_slot_get(&self->semitones); + granular_pitch_shift_recalculate_rate(self, semitones); +} + +void granular_pitch_shift_recalculate_rate(audiodelays_granular_pitch_shift_obj_t *self, mp_float_t semitones) { + self->read_rate = (uint32_t)(MICROPY_FLOAT_C_FUN(pow)(2.0, semitones / MICROPY_FLOAT_CONST(12.0)) * (1 << GRANULAR_PITCH_READ_SHIFT)); + self->current_semitones = semitones; +} + +mp_obj_t common_hal_audiodelays_granular_pitch_shift_get_mix(audiodelays_granular_pitch_shift_obj_t *self) { + return self->mix.obj; +} + +void common_hal_audiodelays_granular_pitch_shift_set_mix(audiodelays_granular_pitch_shift_obj_t *self, mp_obj_t arg) { + synthio_block_assign_slot(arg, &self->mix, MP_QSTR_mix); +} + +mp_float_t common_hal_audiodelays_granular_pitch_shift_get_spread(audiodelays_granular_pitch_shift_obj_t *self) { + return self->spread; +} + +void common_hal_audiodelays_granular_pitch_shift_set_spread(audiodelays_granular_pitch_shift_obj_t *self, mp_float_t spread) { + if (spread < MICROPY_FLOAT_CONST(0.0)) { + spread = MICROPY_FLOAT_CONST(0.0); + } else if (spread > MICROPY_FLOAT_CONST(1.0)) { + spread = MICROPY_FLOAT_CONST(1.0); + } + self->spread = spread; +} + +void audiodelays_granular_pitch_shift_reset_buffer(audiodelays_granular_pitch_shift_obj_t *self, + bool single_channel_output, + uint8_t channel) { + + memset(self->buffer[0], 0, self->buffer_len); + memset(self->buffer[1], 0, self->buffer_len); + memset(self->capture_buffer, 0, self->capture_len * self->base.channel_count * sizeof(int16_t)); + + // Deactivate all grains and reset the scheduler/write cursor. + for (uint32_t i = 0; i < GRANULAR_MAX_GRAINS; i++) { + self->grains[i].active = false; + } + self->samples_until_next_grain = 0; + self->write_index = 0; +} + +bool common_hal_audiodelays_granular_pitch_shift_get_playing(audiodelays_granular_pitch_shift_obj_t *self) { + return self->sample != NULL; +} + +void common_hal_audiodelays_granular_pitch_shift_play(audiodelays_granular_pitch_shift_obj_t *self, mp_obj_t sample, bool loop) { + audiosample_must_match(&self->base, sample, false); + + self->sample = sample; + self->loop = loop; + + audiosample_reset_buffer(self->sample, false, 0); + audioio_get_buffer_result_t result = audiosample_get_buffer(self->sample, false, 0, (uint8_t **)&self->sample_remaining_buffer, &self->sample_buffer_length); + + // Track remaining sample length in terms of bytes per sample + self->sample_buffer_length /= (self->base.bits_per_sample / 8); + // Store if we have more data in the sample to retrieve + self->more_data = result == GET_BUFFER_MORE_DATA; + + return; +} + +void common_hal_audiodelays_granular_pitch_shift_stop(audiodelays_granular_pitch_shift_obj_t *self) { + // When the sample is set to stop playing do any cleanup here + self->sample = NULL; + return; +} + +// xorshift32 PRNG for grain-start jitter. Kept local to this module so the +// effect doesn't depend on the `random` module being enabled in a build. +static uint32_t granular_pitch_shift_rand(audiodelays_granular_pitch_shift_obj_t *self) { + uint32_t x = self->rng_state; + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + self->rng_state = x; + return x; +} + +// Launch a grain into the first free pool slot, seeded to read from the capture +// buffer starting grain_size words behind the current write cursor (so it reads +// already-captured audio) at the current pitch-shift read rate. When `spread` is +// nonzero the start is jittered up to a further grain_size words backward, which +// is what gives granular synthesis its characteristic "cloud" texture. Jitter is +// always backward (further behind the write cursor), so a grain never reads ahead +// of captured audio and the capture buffer (capture_len == grain_size * 2) is +// never overrun. Grain read state (read_index/phase) is per-frame / +// channel-independent; the per-channel plane offset is applied at read time. +static void granular_pitch_shift_launch_grain(audiodelays_granular_pitch_shift_obj_t *self) { + for (uint32_t g = 0; g < GRANULAR_MAX_GRAINS; g++) { + if (!self->grains[g].active) { + // Backward jitter in [0, spread * grain_size]. Capped at grain_size + // so grain_size + jitter <= capture_len (== grain_size * 2). + uint32_t jitter = 0; + if (self->spread > MICROPY_FLOAT_CONST(0.0)) { + uint32_t max_jitter = (uint32_t)(self->spread * (mp_float_t)self->grain_size); + if (max_jitter > 0) { + jitter = granular_pitch_shift_rand(self) % (max_jitter + 1); + } + } + uint32_t start = (self->write_index + self->capture_len - self->grain_size - jitter) % self->capture_len; + self->grains[g].active = true; + self->grains[g].read_index = start << GRANULAR_PITCH_READ_SHIFT; + self->grains[g].read_rate = self->read_rate; + self->grains[g].phase = 0; + self->grains[g].length = self->grain_size; + return; + } + } +} + +audioio_get_buffer_result_t audiodelays_granular_pitch_shift_get_buffer(audiodelays_granular_pitch_shift_obj_t *self, bool single_channel_output, uint8_t channel, + uint8_t **buffer, uint32_t *buffer_length) { + + // Grain scheduler + enveloped grain playback with dry/wet `mix` blending. + // Grains are launched at a fixed spacing (grain_size / density) and each + // active grain reads the capture buffer at its own pitch-shifted (fractional, + // linearly interpolated) read rate, scaled by a Hann amplitude envelope so + // overlapping grains fade in/out and add without seam clicks. The summed + // grains are normalized by grain_gain for ~unity overlap-add gain, then + // crossfaded against the dry input via the `mix` slot. The 8/16-bit, + // signed/unsigned, and mono/stereo (planar capture, buf_offset) paths are all + // handled below, mirroring PitchShift. + + if (!single_channel_output) { + channel = 0; + } + + // Switch our buffers to the other buffer + self->last_buf_idx = !self->last_buf_idx; + + // If we are using 16 bit samples we need a 16 bit pointer, 8 bit needs an 8 bit pointer + int16_t *word_buffer = (int16_t *)self->buffer[self->last_buf_idx]; + int8_t *hword_buffer = self->buffer[self->last_buf_idx]; + uint32_t length = self->buffer_len / (self->base.bits_per_sample / 8); + + // The capture buffer (delay line) is always stored as 16-bit, planar per + // channel: channel c occupies capture_buffer[c * capture_len .. ). + int16_t *capture_buffer = self->capture_buffer; + + // Grains are launched this many frames apart (overlap factor `density`). + uint32_t grain_spacing = self->grain_size / self->density; + if (grain_spacing == 0) { + grain_spacing = 1; + } + + // Loop over the entire length of our buffer to fill it, this may require several calls to get data from the sample + while (length != 0) { + // Check if there is no more sample to play, we will either load more data, reset the sample if loop is on or clear the sample + if (self->sample_buffer_length == 0) { + if (!self->more_data) { // The sample has indicated it has no more data to play + if (self->loop && self->sample) { // If we are supposed to loop reset the sample to the start + audiosample_reset_buffer(self->sample, false, 0); + } else { // If we were not supposed to loop the sample, stop playing it + self->sample = NULL; + } + } + if (self->sample) { + // Load another sample buffer to play + audioio_get_buffer_result_t result = audiosample_get_buffer(self->sample, false, 0, (uint8_t **)&self->sample_remaining_buffer, &self->sample_buffer_length); + if (result == GET_BUFFER_ERROR) { + self->sample = NULL; + self->sample_buffer_length = 0; + self->more_data = false; + } else { + // Track length in terms of words. + self->sample_buffer_length /= (self->base.bits_per_sample / 8); + self->more_data = result == GET_BUFFER_MORE_DATA; + } + } + } + + if (self->sample == NULL) { + if (self->base.samples_signed) { + memset(word_buffer, 0, length * (self->base.bits_per_sample / 8)); + } else { + // For unsigned samples set to the middle which is "quiet" + if (MP_LIKELY(self->base.bits_per_sample == 16)) { + for (uint32_t i = 0; i < length; i++) { + word_buffer[i] = (int16_t)0x8000; + } + } else { + memset(hword_buffer, 128, length * (self->base.bits_per_sample / 8)); + } + } + + // tick all block inputs + shared_bindings_synthio_lfo_tick(self->base.sample_rate, length / self->base.channel_count); + (void)synthio_block_slot_get(&self->semitones); + (void)synthio_block_slot_get(&self->mix); + + length = 0; + } else { + // we have a sample to play and apply effect + // Determine how many bytes we can process to our buffer, the less of the sample we have left and our buffer remaining + uint32_t n = MIN(MIN(self->sample_buffer_length, length), SYNTHIO_MAX_DUR * self->base.channel_count); + + int16_t *sample_src = (int16_t *)self->sample_remaining_buffer; // for 16-bit samples + int8_t *sample_hsrc = (int8_t *)self->sample_remaining_buffer; // for 8-bit samples + + // get the effect values we need from the BlockInput. + shared_bindings_synthio_lfo_tick(self->base.sample_rate, n / self->base.channel_count); + mp_float_t semitones = synthio_block_slot_get(&self->semitones); + // Doubled (0.0..2.0) so the crossfade below can hold both dry and wet + // at full gain around the midpoint, matching PitchShift's mix curve. + mp_float_t mix = synthio_block_slot_get_limited(&self->mix, MICROPY_FLOAT_CONST(0.0), MICROPY_FLOAT_CONST(1.0)) * MICROPY_FLOAT_CONST(2.0); + + // Only recalculate rate if semitones has changed + if (memcmp(&semitones, &self->current_semitones, sizeof(mp_float_t))) { + granular_pitch_shift_recalculate_rate(self, semitones); + } + + for (uint32_t i = 0; i < n; i++) { + bool buf_offset = (channel == 1 || i % self->base.channel_count == 1); + + int32_t sample_word = 0; + if (MP_LIKELY(self->base.bits_per_sample == 16)) { + sample_word = sample_src[i]; + } else { + if (self->base.samples_signed) { + sample_word = sample_hsrc[i]; + } else { + // Changing from an 8 bit unsigned to signed into a 32-bit signed + sample_word = (int8_t)(((uint8_t)sample_hsrc[i]) ^ 0x80); + } + } + + // Write the incoming sample into the capture buffer (the delay + // line grains read from) at the per-channel write cursor. + capture_buffer[self->write_index + self->capture_len * buf_offset] = (int16_t)sample_word; + + // Sum all active grains. Each grain reads the capture buffer at + // its own fractional read cursor (linearly interpolated between + // adjacent words), which is what produces the pitch shift, then + // is scaled by its amplitude envelope (Hann, indexed by the + // grain's phase) so grains fade in/out and overlap-add without + // seam clicks. + int32_t word = 0; + for (uint32_t g = 0; g < GRANULAR_MAX_GRAINS; g++) { + if (!self->grains[g].active) { + continue; + } + uint32_t read_index_fp = self->grains[g].read_index; + uint32_t ipart = read_index_fp >> GRANULAR_PITCH_READ_SHIFT; + uint32_t frac = read_index_fp & ((1 << GRANULAR_PITCH_READ_SHIFT) - 1); + uint32_t index_lo = ipart % self->capture_len; + uint32_t index_hi = (ipart + 1) % self->capture_len; + int32_t sample_lo = capture_buffer[index_lo + self->capture_len * buf_offset]; + int32_t sample_hi = capture_buffer[index_hi + self->capture_len * buf_offset]; + int32_t grain_out = sample_lo + (((sample_hi - sample_lo) * (int32_t)frac) >> GRANULAR_PITCH_READ_SHIFT); + // Apply the grain envelope (Q15). phase < length == envelope_len. + int32_t env = self->envelope_table[self->grains[g].phase]; + word += (grain_out * env) >> 15; + } + + // Normalize the overlap-add gain of the enveloped grains back to + // ~unity (int64 guards the Q15 multiply against overflow). This is + // the fully-wet (pitch-shifted) sample. + word = (int32_t)(((int64_t)word * (int64_t)self->grain_gain) >> 15); + + // Dry/wet crossfade: `mix` is doubled to 0.0..2.0 so both terms + // sit at full gain around the midpoint, then synthio_mix_down_sample + // scales/soft-clips the summed pair back into range (same curve as + // PitchShift). mix=0.0 -> dry input, mix=1.0 -> fully wet. + word = (int32_t)((sample_word * MIN(MICROPY_FLOAT_CONST(2.0) - mix, MICROPY_FLOAT_CONST(1.0))) + (word * MIN(mix, MICROPY_FLOAT_CONST(1.0)))); + word = synthio_mix_down_sample(word, SYNTHIO_MIX_DOWN_SCALE(2)); + + if (MP_LIKELY(self->base.bits_per_sample == 16)) { + word_buffer[i] = (int16_t)word; + if (!self->base.samples_signed) { + word_buffer[i] ^= 0x8000; + } + } else { + int8_t mixed = (int8_t)word; + if (self->base.samples_signed) { + hword_buffer[i] = mixed; + } else { + hword_buffer[i] = (uint8_t)mixed ^ 0x80; + } + } + + // Per-frame shared work (once per frame: mono every sample, + // interleaved stereo on the right-channel sample) so both + // channels read consistent grain state before it advances. + if (self->base.channel_count == 1 || buf_offset) { + // Advance and retire active grains (they were read above). + for (uint32_t g = 0; g < GRANULAR_MAX_GRAINS; g++) { + if (!self->grains[g].active) { + continue; + } + self->grains[g].read_index += self->grains[g].read_rate; + self->grains[g].phase++; + if (self->grains[g].phase >= self->grains[g].length) { + self->grains[g].active = false; + } + } + + // Launch a new grain when the scheduler counter elapses. + if (self->samples_until_next_grain == 0) { + granular_pitch_shift_launch_grain(self); + self->samples_until_next_grain = grain_spacing; + } else { + self->samples_until_next_grain--; + } + + // Advance the per-channel write cursor. + self->write_index++; + if (self->write_index >= self->capture_len) { + self->write_index = 0; + } + } + } + + // Update the remaining length and the buffer positions based on how much we wrote into our buffer + length -= n; + word_buffer += n; + hword_buffer += n; + self->sample_remaining_buffer += (n * (self->base.bits_per_sample / 8)); + self->sample_buffer_length -= n; + } + } + + // Finally pass our buffer and length to the calling audio function + *buffer = (uint8_t *)self->buffer[self->last_buf_idx]; + *buffer_length = self->buffer_len; + + return GET_BUFFER_MORE_DATA; +} diff --git a/shared-module/audiodelays/GranularPitchShift.h b/shared-module/audiodelays/GranularPitchShift.h new file mode 100644 index 00000000000..26ee4804f36 --- /dev/null +++ b/shared-module/audiodelays/GranularPitchShift.h @@ -0,0 +1,104 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT +#pragma once + +#include "py/obj.h" + +#include "shared-module/audiocore/__init__.h" +#include "shared-module/synthio/__init__.h" +#include "shared-module/synthio/block.h" + +// Fixed-point fractional bits for grain read cursors and read rate. A grain's +// read_index and read_rate are stored as (words << GRANULAR_PITCH_READ_SHIFT), +// mirroring PITCH_READ_SHIFT from PitchShift.h. +#define GRANULAR_PITCH_READ_SHIFT (8) + +// Maximum number of concurrently active grains. `density` is clamped to this at +// construction so the grain pool is a fixed, deterministic allocation. +#define GRANULAR_MAX_GRAINS (8) + +extern const mp_obj_type_t audiodelays_granular_pitch_shift_type; + +// A single grain: a short, independently-scheduled, enveloped read of the +// capture buffer. Retired when `phase` reaches `length`. +typedef struct { + bool active; + uint32_t read_index; // words << GRANULAR_PITCH_READ_SHIFT into the capture buffer + uint32_t read_rate; // words << GRANULAR_PITCH_READ_SHIFT, the pitch-shift increment + uint32_t phase; // samples elapsed since the grain launched + uint32_t length; // grain length in samples (== grain_size) +} audiodelays_granular_grain_t; + +typedef struct { + audiosample_base_t base; + synthio_block_slot_t semitones; + mp_float_t current_semitones; + synthio_block_slot_t mix; + + // Double playback buffers (what we hand back to the audio component). + int8_t *buffer[2]; + uint8_t last_buf_idx; + uint32_t buffer_len; // max buffer in bytes + + // Current sample source bookkeeping. + uint8_t *sample_remaining_buffer; + uint32_t sample_buffer_length; + + bool loop; + bool more_data; + + // Capture buffer (the delay line grains read from). Always stored as 16-bit + // internally, planar per channel: channel c occupies + // capture_buffer[c * capture_len .. (c + 1) * capture_len). + int16_t *capture_buffer; + uint32_t capture_len; // words per channel + uint32_t write_index; // words, per-channel write cursor (0 .. capture_len) + + // Grain pool + scheduler. + audiodelays_granular_grain_t grains[GRANULAR_MAX_GRAINS]; + uint32_t samples_until_next_grain; + + uint32_t grain_size; // samples per grain + uint32_t density; // number of overlapping grains (<= GRANULAR_MAX_GRAINS) + + // Granular jitter: randomizes each grain's start position within the capture + // buffer. 0.0 is fully deterministic (grains always start grain_size words + // behind the write cursor); 1.0 spreads the start up to a further grain_size + // words backward, giving the classic granular "cloud" texture. Jitter is + // always backward (further behind the write cursor) so it never reads ahead + // of captured audio. + mp_float_t spread; + uint32_t rng_state; // xorshift32 state for grain-start jitter + + // Q15 (0..32768) normalization applied to the enveloped grain sum so the + // overlap-add gain of `density` Hann grains stays ~unity (Hann satisfies + // COLA at these hops with a summed gain of density/2, so the factor is + // 2/density, capped at 1.0 so a single grain is never amplified). + uint32_t grain_gain; + + // Precomputed amplitude envelope (raised-cosine / Hann), Q15 (0..32767), + // indexed directly by a grain's phase (envelope_len == grain_size). + int16_t *envelope_table; + uint32_t envelope_len; + + // Fixed-point read-rate increment computed from `semitones`, applied to each + // launched grain's read_rate. + uint32_t read_rate; // words << GRANULAR_PITCH_READ_SHIFT + + mp_obj_t sample; +} audiodelays_granular_pitch_shift_obj_t; + +void granular_pitch_shift_recalculate_rate(audiodelays_granular_pitch_shift_obj_t *self, mp_float_t semitones); + +void audiodelays_granular_pitch_shift_reset_buffer(audiodelays_granular_pitch_shift_obj_t *self, + bool single_channel_output, + uint8_t channel); + +audioio_get_buffer_result_t audiodelays_granular_pitch_shift_get_buffer(audiodelays_granular_pitch_shift_obj_t *self, + bool single_channel_output, + uint8_t channel, + uint8_t **buffer, + uint32_t *buffer_length); // length in bytes diff --git a/shared-module/audiodelays/MultiTapDelay.c b/shared-module/audiodelays/MultiTapDelay.c new file mode 100644 index 00000000000..6519f748d4e --- /dev/null +++ b/shared-module/audiodelays/MultiTapDelay.c @@ -0,0 +1,485 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Cooper Dalrymple +// +// SPDX-License-Identifier: MIT +#include "shared-bindings/audiodelays/MultiTapDelay.h" +#include "shared-bindings/audiocore/__init__.h" + +#include +#include "py/runtime.h" +#include + +void common_hal_audiodelays_multi_tap_delay_construct(audiodelays_multi_tap_delay_obj_t *self, uint32_t max_delay_ms, + mp_obj_t delay_ms, mp_obj_t decay, mp_obj_t mix, mp_obj_t taps, + uint32_t buffer_size, uint8_t bits_per_sample, + bool samples_signed, uint8_t channel_count, uint32_t sample_rate) { + + // Basic settings every effect and audio sample has + // These are the effects values, not the source sample(s) + self->base.bits_per_sample = bits_per_sample; // Most common is 16, but 8 is also supported in many places + self->base.samples_signed = samples_signed; // Are the samples we provide signed (common is true) + self->base.channel_count = channel_count; // Channels can be 1 for mono or 2 for stereo + self->base.sample_rate = sample_rate; // Sample rate for the effect, this generally needs to match all audio objects + self->base.single_buffer = false; + self->base.max_buffer_length = buffer_size; + + // To smooth things out as CircuitPython is doing other tasks most audio objects have a buffer + // A double buffer is set up here so the audio output can use DMA on buffer 1 while we + // write to and create buffer 2. + // This buffer is what is passed to the audio component that plays the effect. + // Samples are set sequentially. For stereo audio they are passed L/R/L/R/... + self->buffer_len = buffer_size; // in bytes + + self->buffer[0] = m_malloc_maybe_without_collect(self->buffer_len); + if (self->buffer[0] == NULL) { + common_hal_audiodelays_multi_tap_delay_deinit(self); + m_malloc_fail(self->buffer_len); + } + memset(self->buffer[0], 0, self->buffer_len); + + self->buffer[1] = m_malloc_maybe_without_collect(self->buffer_len); + if (self->buffer[1] == NULL) { + common_hal_audiodelays_multi_tap_delay_deinit(self); + m_malloc_fail(self->buffer_len); + } + memset(self->buffer[1], 0, self->buffer_len); + + self->last_buf_idx = 1; // Which buffer to use first, toggle between 0 and 1 + + // Initialize other values most effects will need. + self->sample = NULL; // The current playing sample + self->sample_remaining_buffer = NULL; // Pointer to the start of the sample buffer we have not played + self->sample_buffer_length = 0; // How many samples do we have left to play (these may be 16 bit!) + self->loop = false; // When the sample is done do we loop to the start again or stop (e.g. in a wav file) + self->more_data = false; // Is there still more data to read from the sample or did we finish + + // The below section sets up the multi-tap delay effect's starting values. For a different effect this section will change + + // If we did not receive a BlockInput we need to create a default float value + if (decay == MP_OBJ_NULL) { + decay = mp_obj_new_float(MICROPY_FLOAT_CONST(0.7)); + } + synthio_block_assign_slot(decay, &self->decay, MP_QSTR_decay); + + if (mix == MP_OBJ_NULL) { + mix = mp_obj_new_float(MICROPY_FLOAT_CONST(0.25)); + } + synthio_block_assign_slot(mix, &self->mix, MP_QSTR_mix); + + // Allocate the delay buffer for the max possible delay, delay is always 16-bit + self->max_delay_ms = max_delay_ms; + self->max_delay_buffer_len = (uint32_t)(self->base.sample_rate / MICROPY_FLOAT_CONST(1000.0) * max_delay_ms) * (self->base.channel_count * sizeof(uint16_t)); // bytes + self->delay_buffer = m_malloc_maybe_without_collect(self->max_delay_buffer_len); + if (self->delay_buffer == NULL) { + common_hal_audiodelays_multi_tap_delay_deinit(self); + m_malloc_fail(self->max_delay_buffer_len); + } + memset(self->delay_buffer, 0, self->max_delay_buffer_len); + + // calculate the length of a single sample in milliseconds + self->sample_ms = MICROPY_FLOAT_CONST(1000.0) / self->base.sample_rate; + + // calculate everything needed for the current delay + common_hal_audiodelays_multi_tap_delay_set_delay_ms(self, delay_ms); + self->delay_buffer_pos = 0; + self->delay_buffer_right_pos = 0; + + // Initialize our tap values + self->tap_positions = NULL; + self->tap_levels = NULL; + self->tap_offsets = NULL; + self->tap_len = 0; + common_hal_audiodelays_multi_tap_delay_set_taps(self, taps); +} + +void common_hal_audiodelays_multi_tap_delay_deinit(audiodelays_multi_tap_delay_obj_t *self) { + audiosample_mark_deinit(&self->base); + self->delay_buffer = NULL; + self->buffer[0] = NULL; + self->buffer[1] = NULL; + + self->tap_positions = NULL; + self->tap_levels = NULL; + self->tap_offsets = NULL; +} + +mp_float_t common_hal_audiodelays_multi_tap_delay_get_delay_ms(audiodelays_multi_tap_delay_obj_t *self) { + return self->delay_ms; +} + +void common_hal_audiodelays_multi_tap_delay_set_delay_ms(audiodelays_multi_tap_delay_obj_t *self, mp_obj_t delay_ms) { + self->delay_ms = mp_obj_get_float(delay_ms); + + // Require that delay is at least 1 sample long + self->delay_ms = MAX(self->delay_ms, self->sample_ms); + + // Calculate the current delay buffer length in bytes + self->delay_buffer_len = (uint32_t)(self->base.sample_rate / MICROPY_FLOAT_CONST(1000.0) * self->delay_ms) * (self->base.channel_count * sizeof(uint16_t)); + + // Limit to valid range + if (self->delay_buffer_len < self->buffer_len) { + // If the delay buffer is smaller than our audio buffer, weird things happen + self->delay_buffer_len = self->buffer_len; + } + if (self->delay_buffer_len > self->max_delay_buffer_len) { + self->delay_buffer_len = self->max_delay_buffer_len; + } + + // Clear the now unused part of the buffer or some weird artifacts appear + memset(self->delay_buffer + self->delay_buffer_len, 0, self->max_delay_buffer_len - self->delay_buffer_len); + + // Update tap offsets if we have any + recalculate_tap_offsets(self); +} + +mp_obj_t common_hal_audiodelays_multi_tap_delay_get_decay(audiodelays_multi_tap_delay_obj_t *self) { + return self->decay.obj; +} + +void common_hal_audiodelays_multi_tap_delay_set_decay(audiodelays_multi_tap_delay_obj_t *self, mp_obj_t decay) { + synthio_block_assign_slot(decay, &self->decay, MP_QSTR_decay); +} + +mp_obj_t common_hal_audiodelays_multi_tap_delay_get_mix(audiodelays_multi_tap_delay_obj_t *self) { + return self->mix.obj; +} + +void common_hal_audiodelays_multi_tap_delay_set_mix(audiodelays_multi_tap_delay_obj_t *self, mp_obj_t mix) { + synthio_block_assign_slot(mix, &self->mix, MP_QSTR_mix); +} + +mp_obj_t common_hal_audiodelays_multi_tap_delay_get_taps(audiodelays_multi_tap_delay_obj_t *self) { + if (!self->tap_len) { + return mp_const_none; + } else { + mp_obj_tuple_t *taps = mp_obj_new_tuple(self->tap_len, NULL); + for (size_t i = 0; i < self->tap_len; i++) { + mp_obj_tuple_t *pair = mp_obj_new_tuple(2, NULL); + pair->items[0] = mp_obj_new_float(self->tap_positions[i]); + pair->items[1] = mp_obj_new_float(self->tap_levels[i]); + taps->items[i] = pair; + } + return taps; + } +} + +void validate_tap_value(mp_obj_t item, qstr arg_name) { + if (mp_obj_is_small_int(item)) { + mp_arg_validate_int_range(mp_obj_get_int(item), 0, 1, arg_name); + } else { + mp_arg_validate_obj_float_range(item, 0, 1, arg_name); + } +} + +mp_float_t get_tap_value(mp_obj_t item) { + mp_float_t value; + if (mp_obj_is_small_int(item)) { + value = (mp_float_t)mp_obj_get_int(item); + } else { + value = mp_obj_float_get(item); + } + return value; +} + +void common_hal_audiodelays_multi_tap_delay_set_taps(audiodelays_multi_tap_delay_obj_t *self, mp_obj_t taps_in) { + if (taps_in != mp_const_none && !MP_OBJ_TYPE_HAS_SLOT(mp_obj_get_type(taps_in), iter)) { + mp_raise_TypeError_varg( + MP_ERROR_TEXT("%q must be of type %q, not %q"), + MP_QSTR_taps, MP_QSTR_iterable, mp_obj_get_type(taps_in)->name); + } + + size_t len, i; + mp_obj_t *items; + + if (taps_in == mp_const_none) { + len = 0; + items = NULL; + } else { + // convert object to tuple if it wasn't before + taps_in = MP_OBJ_TYPE_GET_SLOT(&mp_type_tuple, make_new)( + &mp_type_tuple, 1, 0, &taps_in); + + mp_obj_tuple_get(taps_in, &len, &items); + mp_arg_validate_length_min(len, 1, MP_QSTR_items); + + for (i = 0; i < len; i++) { + mp_obj_t item = items[i]; + if (mp_obj_is_tuple_compatible(item)) { + size_t len1; + mp_obj_t *items1; + mp_obj_tuple_get(item, &len1, &items1); + mp_arg_validate_length(len1, 2, MP_QSTR_items); + + for (size_t j = 0; j < len1; j++) { + validate_tap_value(items1[j], j ? MP_QSTR_level : MP_QSTR_position); + } + } else if (mp_obj_is_float(item) || mp_obj_is_small_int(item)) { + validate_tap_value(item, MP_QSTR_position); + } else { + mp_raise_TypeError_varg( + MP_ERROR_TEXT("%q in %q must be of type %q or %q, not %q"), + MP_QSTR_object, + MP_QSTR_taps, + MP_QSTR_iterable, + MP_QSTR_float, + mp_obj_get_type(item)->name); + } + + } + } + + self->tap_positions = m_renew(mp_float_t, + self->tap_positions, + self->tap_len, + len); + self->tap_levels = m_renew(mp_float_t, + self->tap_levels, + self->tap_len, + len); + self->tap_offsets = m_renew(uint32_t, + self->tap_offsets, + self->tap_len, + len); + self->tap_len = len; + + for (i = 0; i < len; i++) { + mp_obj_t item = items[i]; + if (mp_obj_is_tuple_compatible(item)) { + size_t len1; + mp_obj_t *items1; + mp_obj_tuple_get(item, &len1, &items1); + + self->tap_positions[i] = get_tap_value(items1[0]); + self->tap_levels[i] = get_tap_value(items1[1]); + } else { + self->tap_positions[i] = get_tap_value(item); + self->tap_levels[i] = MICROPY_FLOAT_CONST(1.0); + } + } + + recalculate_tap_offsets(self); +} + +void recalculate_tap_offsets(audiodelays_multi_tap_delay_obj_t *self) { + if (!self->tap_len) { + return; + } + + uint32_t delay_buffer_len = self->delay_buffer_len / self->base.channel_count / sizeof(uint16_t); + for (size_t i = 0; i < self->tap_len; i++) { + self->tap_offsets[i] = (uint32_t)(delay_buffer_len * self->tap_positions[i]); + } +} + +void audiodelays_multi_tap_delay_reset_buffer(audiodelays_multi_tap_delay_obj_t *self, + bool single_channel_output, + uint8_t channel) { + + memset(self->buffer[0], 0, self->buffer_len); + memset(self->buffer[1], 0, self->buffer_len); + memset(self->delay_buffer, 0, self->max_delay_buffer_len); +} + +bool common_hal_audiodelays_multi_tap_delay_get_playing(audiodelays_multi_tap_delay_obj_t *self) { + return self->sample != NULL; +} + +void common_hal_audiodelays_multi_tap_delay_play(audiodelays_multi_tap_delay_obj_t *self, mp_obj_t sample, bool loop) { + audiosample_must_match(&self->base, sample, false); + + self->sample = sample; + self->loop = loop; + + audiosample_reset_buffer(self->sample, false, 0); + audioio_get_buffer_result_t result = audiosample_get_buffer(self->sample, false, 0, (uint8_t **)&self->sample_remaining_buffer, &self->sample_buffer_length); + + // Track remaining sample length in terms of bytes per sample + self->sample_buffer_length /= (self->base.bits_per_sample / 8); + // Store if we have more data in the sample to retrieve + self->more_data = result == GET_BUFFER_MORE_DATA; + + return; +} + +void common_hal_audiodelays_multi_tap_delay_stop(audiodelays_multi_tap_delay_obj_t *self) { + // When the sample is set to stop playing do any cleanup here + // For delay we clear the sample but the delay continues until the object reading our effect stops + self->sample = NULL; + return; +} + +audioio_get_buffer_result_t audiodelays_multi_tap_delay_get_buffer(audiodelays_multi_tap_delay_obj_t *self, bool single_channel_output, uint8_t channel, + uint8_t **buffer, uint32_t *buffer_length) { + + if (!single_channel_output) { + channel = 0; + } + + // Switch our buffers to the other buffer + self->last_buf_idx = !self->last_buf_idx; + + // If we are using 16 bit samples we need a 16 bit pointer, 8 bit needs an 8 bit pointer + int16_t *word_buffer = (int16_t *)self->buffer[self->last_buf_idx]; + int8_t *hword_buffer = self->buffer[self->last_buf_idx]; + uint32_t length = self->buffer_len / (self->base.bits_per_sample / 8); + + // The delay buffer is always stored as a 16-bit value internally + int16_t *delay_buffer = (int16_t *)self->delay_buffer; + uint32_t delay_buffer_len = self->delay_buffer_len / self->base.channel_count / sizeof(uint16_t); + + uint32_t delay_buffer_pos = self->delay_buffer_pos; + if (single_channel_output && channel == 1) { + delay_buffer_pos = self->delay_buffer_right_pos; + } + + int32_t mix_down_scale = SYNTHIO_MIX_DOWN_SCALE(self->tap_len); + + // Loop over the entire length of our buffer to fill it, this may require several calls to get data from the sample + while (length != 0) { + // Check if there is no more sample to play, we will either load more data, reset the sample if loop is on or clear the sample + if (self->sample_buffer_length == 0) { + if (!self->more_data) { // The sample has indicated it has no more data to play + if (self->loop && self->sample) { // If we are supposed to loop reset the sample to the start + audiosample_reset_buffer(self->sample, false, 0); + } else { // If we were not supposed to loop the sample, stop playing it but we still need to play the delay + self->sample = NULL; + } + } + if (self->sample) { + // Load another sample buffer to play + audioio_get_buffer_result_t result = audiosample_get_buffer(self->sample, false, 0, (uint8_t **)&self->sample_remaining_buffer, &self->sample_buffer_length); + if (result == GET_BUFFER_ERROR) { + self->sample = NULL; + self->sample_buffer_length = 0; + self->more_data = false; + } else { + // Track length in terms of words. + self->sample_buffer_length /= (self->base.bits_per_sample / 8); + self->more_data = result == GET_BUFFER_MORE_DATA; + } + } + } + + // Determine how many bytes we can process to our buffer, the less of the sample we have left and our buffer remaining + uint32_t n; + if (self->sample == NULL) { + n = MIN(length, SYNTHIO_MAX_DUR * self->base.channel_count); + } else { + n = MIN(MIN(self->sample_buffer_length, length), SYNTHIO_MAX_DUR * self->base.channel_count); + } + + // get the effect values we need from the BlockInput. These may change at run time so you need to do bounds checking if required + shared_bindings_synthio_lfo_tick(self->base.sample_rate, n / self->base.channel_count); + mp_float_t mix = synthio_block_slot_get_limited(&self->mix, MICROPY_FLOAT_CONST(0.0), MICROPY_FLOAT_CONST(1.0)) * MICROPY_FLOAT_CONST(2.0); + mp_float_t decay = synthio_block_slot_get_limited(&self->decay, MICROPY_FLOAT_CONST(0.0), MICROPY_FLOAT_CONST(1.0)); + + int16_t *sample_src = NULL; + int8_t *sample_hsrc = NULL; + if (self->sample != NULL) { + // we have a sample to play and delay + sample_src = (int16_t *)self->sample_remaining_buffer; // for 16-bit samples + sample_hsrc = (int8_t *)self->sample_remaining_buffer; // for 8-bit samples + } + + for (uint32_t i = 0; i < n; i++) { + uint32_t delay_buffer_offset = delay_buffer_len * ((single_channel_output && channel == 1) || (!single_channel_output && (i % self->base.channel_count) == 1)); + + int32_t sample_word = 0; + if (self->sample != NULL) { + if (MP_LIKELY(self->base.bits_per_sample == 16)) { + sample_word = sample_src[i]; + } else { + if (self->base.samples_signed) { + sample_word = sample_hsrc[i]; + } else { + // Be careful here changing from an 8 bit unsigned to signed into a 32-bit signed + sample_word = (int8_t)(((uint8_t)sample_hsrc[i]) ^ 0x80); + } + } + } + + // Pull words from delay buffer at tap positions, apply level and mix down + int32_t word = 0; + int32_t delay_word; + if (self->tap_len) { + size_t tap_pos; + for (size_t j = 0; j < self->tap_len; j++) { + tap_pos = (delay_buffer_pos + delay_buffer_len - self->tap_offsets[j]) % delay_buffer_len; + delay_word = delay_buffer[tap_pos + delay_buffer_offset]; + word += (int32_t)(delay_word * self->tap_levels[j]); + } + + if (self->tap_len > 1) { + word = synthio_mix_down_sample(word, mix_down_scale); + } + } + + // Update delay buffer with sample and decay + delay_word = delay_buffer[delay_buffer_pos + delay_buffer_offset]; + + // If no taps are provided, use as standard delay + if (!self->tap_len) { + word = delay_word; + } + + // Apply decay and add sample + delay_word = (int32_t)(delay_word * decay) + sample_word; + + if (MP_LIKELY(self->base.bits_per_sample == 16)) { + delay_word = synthio_mix_down_sample(delay_word, SYNTHIO_MIX_DOWN_SCALE(2)); + delay_buffer[delay_buffer_pos + delay_buffer_offset] = (int16_t)delay_word; + } else { + // Do not have mix_down for 8 bit so just hard cap samples into 1 byte + delay_word = MIN(MAX(delay_word, -128), 127); + delay_buffer[delay_buffer_pos + delay_buffer_offset] = (int8_t)delay_word; + } + + // Mix sample with tap output + word = (int32_t)((sample_word * MIN(MICROPY_FLOAT_CONST(2.0) - mix, MICROPY_FLOAT_CONST(1.0))) + + (word * MIN(mix, MICROPY_FLOAT_CONST(1.0)))); + word = synthio_mix_down_sample(word, SYNTHIO_MIX_DOWN_SCALE(2)); + + if (MP_LIKELY(self->base.bits_per_sample == 16)) { + word_buffer[i] = (int16_t)word; + if (!self->base.samples_signed) { + word_buffer[i] ^= 0x8000; + } + } else { + int8_t mixed = (int16_t)word; + if (self->base.samples_signed) { + hword_buffer[i] = mixed; + } else { + hword_buffer[i] = (uint8_t)mixed ^ 0x80; + } + } + + if ((self->base.channel_count == 1 || single_channel_output || (!single_channel_output && (i % self->base.channel_count) == 1)) + && ++delay_buffer_pos >= delay_buffer_len) { + delay_buffer_pos = 0; + } + } + + // Update the remaining length and the buffer positions based on how much we wrote into our buffer + length -= n; + word_buffer += n; + hword_buffer += n; + if (self->sample != NULL) { + self->sample_remaining_buffer += (n * (self->base.bits_per_sample / 8)); + self->sample_buffer_length -= n; + } + } + + if (single_channel_output && channel == 1) { + self->delay_buffer_right_pos = delay_buffer_pos; + } else { + self->delay_buffer_pos = delay_buffer_pos; + } + + // Finally pass our buffer and length to the calling audio function + *buffer = (uint8_t *)self->buffer[self->last_buf_idx]; + *buffer_length = self->buffer_len; + + // MultiTapDelay always returns more data but some effects may return GET_BUFFER_DONE or GET_BUFFER_ERROR (see audiocore/__init__.h) + return GET_BUFFER_MORE_DATA; +} diff --git a/shared-module/audiodelays/MultiTapDelay.h b/shared-module/audiodelays/MultiTapDelay.h new file mode 100644 index 00000000000..ebe310b05f7 --- /dev/null +++ b/shared-module/audiodelays/MultiTapDelay.h @@ -0,0 +1,60 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Cooper Dalrymple +// +// SPDX-License-Identifier: MIT +#pragma once + +#include "py/obj.h" + +#include "shared-module/audiocore/__init__.h" +#include "shared-module/synthio/__init__.h" +#include "shared-module/synthio/block.h" + +extern const mp_obj_type_t audiodelays_multi_tap_delay_type; + +typedef struct { + audiosample_base_t base; + uint32_t max_delay_ms; + mp_float_t delay_ms; + mp_float_t sample_ms; + synthio_block_slot_t decay; + synthio_block_slot_t mix; + + mp_float_t *tap_positions; + mp_float_t *tap_levels; + uint32_t *tap_offsets; + size_t tap_len; + + int8_t *buffer[2]; + uint8_t last_buf_idx; + uint32_t buffer_len; // max buffer in bytes + + uint8_t *sample_remaining_buffer; + uint32_t sample_buffer_length; + + bool loop; + bool more_data; + + int8_t *delay_buffer; + uint32_t delay_buffer_len; // bytes + uint32_t max_delay_buffer_len; // bytes + uint32_t delay_buffer_pos; + uint32_t delay_buffer_right_pos; + + mp_obj_t sample; +} audiodelays_multi_tap_delay_obj_t; + +void validate_tap_value(mp_obj_t item, qstr arg_name); +mp_float_t get_tap_value(mp_obj_t item); +void recalculate_tap_offsets(audiodelays_multi_tap_delay_obj_t *self); + +void audiodelays_multi_tap_delay_reset_buffer(audiodelays_multi_tap_delay_obj_t *self, + bool single_channel_output, + uint8_t channel); + +audioio_get_buffer_result_t audiodelays_multi_tap_delay_get_buffer(audiodelays_multi_tap_delay_obj_t *self, + bool single_channel_output, + uint8_t channel, + uint8_t **buffer, + uint32_t *buffer_length); // length in bytes diff --git a/shared-module/audiodelays/PitchShift.c b/shared-module/audiodelays/PitchShift.c index 743ba403d79..809efaf77b1 100644 --- a/shared-module/audiodelays/PitchShift.c +++ b/shared-module/audiodelays/PitchShift.c @@ -31,14 +31,14 @@ void common_hal_audiodelays_pitch_shift_construct(audiodelays_pitch_shift_obj_t // Samples are set sequentially. For stereo audio they are passed L/R/L/R/... self->buffer_len = buffer_size; // in bytes - self->buffer[0] = m_malloc(self->buffer_len); + self->buffer[0] = m_malloc_without_collect(self->buffer_len); if (self->buffer[0] == NULL) { common_hal_audiodelays_pitch_shift_deinit(self); m_malloc_fail(self->buffer_len); } memset(self->buffer[0], 0, self->buffer_len); - self->buffer[1] = m_malloc(self->buffer_len); + self->buffer[1] = m_malloc_without_collect(self->buffer_len); if (self->buffer[1] == NULL) { common_hal_audiodelays_pitch_shift_deinit(self); m_malloc_fail(self->buffer_len); @@ -58,10 +58,12 @@ void common_hal_audiodelays_pitch_shift_construct(audiodelays_pitch_shift_obj_t synthio_block_assign_slot(semitones, &self->semitones, MP_QSTR_semitones); synthio_block_assign_slot(mix, &self->mix, MP_QSTR_mix); + self->freeze = false; // Allocate the window buffer + mp_arg_validate_int_min(window, sizeof(uint16_t) * channel_count, MP_QSTR_window); self->window_len = window; // bytes - self->window_buffer = m_malloc(self->window_len); + self->window_buffer = m_malloc_without_collect(self->window_len); if (self->window_buffer == NULL) { common_hal_audiodelays_pitch_shift_deinit(self); m_malloc_fail(self->window_len); @@ -71,7 +73,7 @@ void common_hal_audiodelays_pitch_shift_construct(audiodelays_pitch_shift_obj_t // Allocate the overlap buffer self->overlap_len = overlap; // bytes if (self->overlap_len) { - self->overlap_buffer = m_malloc(self->overlap_len); + self->overlap_buffer = m_malloc_without_collect(self->overlap_len); if (self->overlap_buffer == NULL) { common_hal_audiodelays_pitch_shift_deinit(self); m_malloc_fail(self->overlap_len); @@ -126,9 +128,18 @@ void common_hal_audiodelays_pitch_shift_set_mix(audiodelays_pitch_shift_obj_t *s synthio_block_assign_slot(arg, &self->mix, MP_QSTR_mix); } +bool common_hal_audiodelays_pitch_shift_get_freeze(audiodelays_pitch_shift_obj_t *self) { + return self->freeze; +} + +void common_hal_audiodelays_pitch_shift_set_freeze(audiodelays_pitch_shift_obj_t *self, bool freeze) { + self->freeze = freeze; +} + void audiodelays_pitch_shift_reset_buffer(audiodelays_pitch_shift_obj_t *self, bool single_channel_output, uint8_t channel) { + self->freeze = false; memset(self->buffer[0], 0, self->buffer_len); memset(self->buffer[1], 0, self->buffer_len); @@ -143,7 +154,7 @@ bool common_hal_audiodelays_pitch_shift_get_playing(audiodelays_pitch_shift_obj_ } void common_hal_audiodelays_pitch_shift_play(audiodelays_pitch_shift_obj_t *self, mp_obj_t sample, bool loop) { - audiosample_must_match(&self->base, sample); + audiosample_must_match(&self->base, sample, false); self->sample = sample; self->loop = loop; @@ -205,9 +216,15 @@ audioio_get_buffer_result_t audiodelays_pitch_shift_get_buffer(audiodelays_pitch if (self->sample) { // Load another sample buffer to play audioio_get_buffer_result_t result = audiosample_get_buffer(self->sample, false, 0, (uint8_t **)&self->sample_remaining_buffer, &self->sample_buffer_length); - // Track length in terms of words. - self->sample_buffer_length /= (self->base.bits_per_sample / 8); - self->more_data = result == GET_BUFFER_MORE_DATA; + if (result == GET_BUFFER_ERROR) { + self->sample = NULL; + self->sample_buffer_length = 0; + self->more_data = false; + } else { + // Track length in terms of words. + self->sample_buffer_length /= (self->base.bits_per_sample / 8); + self->more_data = result == GET_BUFFER_MORE_DATA; + } } } @@ -217,7 +234,9 @@ audioio_get_buffer_result_t audiodelays_pitch_shift_get_buffer(audiodelays_pitch } else { // For unsigned samples set to the middle which is "quiet" if (MP_LIKELY(self->base.bits_per_sample == 16)) { - memset(word_buffer, 32768, length * (self->base.bits_per_sample / 8)); + for (uint32_t si = 0; si < length; si++) { + word_buffer[si] = (int16_t)0x8000; + } } else { memset(hword_buffer, 128, length * (self->base.bits_per_sample / 8)); } @@ -262,15 +281,17 @@ audioio_get_buffer_result_t audiodelays_pitch_shift_get_buffer(audiodelays_pitch } } - if (overlap_size) { - // Copy last sample from overlap and store in buffer - window_buffer[self->window_index + window_size * buf_offset] = overlap_buffer[self->overlap_index + overlap_size * buf_offset]; + if (!self->freeze) { + if (overlap_size) { + // Copy last sample from overlap and store in buffer + window_buffer[self->window_index + window_size * buf_offset] = overlap_buffer[self->overlap_index + overlap_size * buf_offset]; - // Save current sample in overlap - overlap_buffer[self->overlap_index + overlap_size * buf_offset] = (int16_t)sample_word; - } else { - // Write sample to buffer - window_buffer[self->window_index + window_size * buf_offset] = (int16_t)sample_word; + // Save current sample in overlap + overlap_buffer[self->overlap_index + overlap_size * buf_offset] = (int16_t)sample_word; + } else { + // Write sample to buffer + window_buffer[self->window_index + window_size * buf_offset] = (int16_t)sample_word; + } } // Determine how far we are into the overlap @@ -310,17 +331,19 @@ audioio_get_buffer_result_t audiodelays_pitch_shift_get_buffer(audiodelays_pitch } if (self->base.channel_count == 1 || buf_offset) { - // Increment window buffer write pointer - self->window_index++; - if (self->window_index >= window_size) { - self->window_index = 0; - } + if (!self->freeze) { + // Increment window buffer write pointer + self->window_index++; + if (self->window_index >= window_size) { + self->window_index = 0; + } - // Increment overlap buffer pointer - if (overlap_size) { - self->overlap_index++; - if (self->overlap_index >= overlap_size) { - self->overlap_index = 0; + // Increment overlap buffer pointer + if (overlap_size) { + self->overlap_index++; + if (self->overlap_index >= overlap_size) { + self->overlap_index = 0; + } } } diff --git a/shared-module/audiodelays/PitchShift.h b/shared-module/audiodelays/PitchShift.h index dddcfa4efc0..f156186b7f6 100644 --- a/shared-module/audiodelays/PitchShift.h +++ b/shared-module/audiodelays/PitchShift.h @@ -20,6 +20,7 @@ typedef struct { synthio_block_slot_t semitones; mp_float_t current_semitones; synthio_block_slot_t mix; + bool freeze; uint32_t window_len; uint32_t overlap_len; diff --git a/shared-module/audiofilewriter/AudioFileWriter.c b/shared-module/audiofilewriter/AudioFileWriter.c new file mode 100644 index 00000000000..db60281c6ea --- /dev/null +++ b/shared-module/audiofilewriter/AudioFileWriter.c @@ -0,0 +1,441 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/audiofilewriter/AudioFileWriter.h" +#include "shared-bindings/audiocore/__init__.h" +#include "shared-module/audiocore/__init__.h" + +#include + +#include "py/mperrno.h" +#include "py/runtime.h" +#include "py/stream.h" + +#include "supervisor/background_callback.h" +#include "supervisor/shared/tick.h" + +// --------------------------------------------------------------------------- +// Little-endian header helpers +// --------------------------------------------------------------------------- + +static void put_u16le(uint8_t *p, uint16_t v) { + p[0] = (uint8_t)v; + p[1] = (uint8_t)(v >> 8); +} + +static void put_u32le(uint8_t *p, uint32_t v) { + p[0] = (uint8_t)v; + p[1] = (uint8_t)(v >> 8); + p[2] = (uint8_t)(v >> 16); + p[3] = (uint8_t)(v >> 24); +} + +// --------------------------------------------------------------------------- +// Active-writer registry, walked once per supervisor tick. +// +// The list head lives in MP_STATE_VM (see MP_REGISTER_ROOT_POINTER below) so +// that (a) active writers and their reg_next chain are GC-rooted while +// recording, and (b) the list is wiped automatically when the VM heap is +// recreated on soft reset. +// --------------------------------------------------------------------------- + +#define REGISTRY_HEAD ((audiofilewriter_audiofilewriter_obj_t *)MP_STATE_VM(audiofilewriter_linked_list)) + +// Add self to the registry. Called from Python (play()) context, so it must +// guard against a background tick walking the list mid-mutation. +static void audiofilewriter_register(audiofilewriter_audiofilewriter_obj_t *self) { + background_callback_prevent(); + // Avoid double-linking if already present. + bool present = false; + for (audiofilewriter_audiofilewriter_obj_t *w = REGISTRY_HEAD; w != NULL; w = w->reg_next) { + if (w == self) { + present = true; + break; + } + } + if (!present) { + self->reg_next = REGISTRY_HEAD; + MP_STATE_VM(audiofilewriter_linked_list) = self; + } + background_callback_allow(); +} + +// Remove self from the registry. Callers must ensure no background tick is +// walking the list concurrently: either they are the background tick itself +// (single-threaded, so safe), or they wrap the call in prevent/allow. +static void audiofilewriter_unregister(audiofilewriter_audiofilewriter_obj_t *self) { + audiofilewriter_audiofilewriter_obj_t **pp = (audiofilewriter_audiofilewriter_obj_t **)&MP_STATE_VM(audiofilewriter_linked_list); + while (*pp != NULL) { + if (*pp == self) { + *pp = self->reg_next; + self->reg_next = NULL; + return; + } + pp = &(*pp)->reg_next; + } +} + +// Without a file the writer still fetches the next buffer from the source at +// the source's real-time rate, but drops the audio: nothing is buffered, +// written or patched. +static bool audiofilewriter_has_file(audiofilewriter_audiofilewriter_obj_t *self) { + return self->file != mp_const_none; +} + +// --------------------------------------------------------------------------- +// RAM ring +// --------------------------------------------------------------------------- + +// Copy len bytes from src into the ring. The caller guarantees there is room. +// 8-bit signed PCM is flipped to unsigned to match the WAV convention. +static void audiofilewriter_ring_write(audiofilewriter_audiofilewriter_obj_t *self, const uint8_t *src, uint32_t len) { + bool flip = (self->bits_per_sample == 8 && self->samples_signed); + uint32_t i = 0; + while (i < len) { + uint32_t span = self->ring_size - self->ring_head; + if (span > (len - i)) { + span = len - i; + } + if (flip) { + for (uint32_t j = 0; j < span; j++) { + self->ring[self->ring_head + j] = src[i + j] ^ 0x80; + } + } else { + memcpy(self->ring + self->ring_head, src + i, span); + } + self->ring_head += span; + if (self->ring_head == self->ring_size) { + self->ring_head = 0; + } + i += span; + } + self->ring_count += len; +} + +// Drain the ring to the file. Returns false on a write error. Non-raising: +// safe to call from background-task context. +static bool audiofilewriter_flush(audiofilewriter_audiofilewriter_obj_t *self) { + if (!audiofilewriter_has_file(self)) { + return true; + } + while (self->ring_count > 0) { + uint32_t span = self->ring_size - self->ring_tail; + if (span > self->ring_count) { + span = self->ring_count; + } + int err = 0; + mp_uint_t wrote = mp_stream_write_exactly(self->file, self->ring + self->ring_tail, span, &err); + if (err != 0 || wrote != span) { + return false; + } + self->ring_tail += span; + if (self->ring_tail == self->ring_size) { + self->ring_tail = 0; + } + self->ring_count -= span; + self->data_bytes += span; + } + return true; +} + +// --------------------------------------------------------------------------- +// Header patching + finalize +// --------------------------------------------------------------------------- + +static void audiofilewriter_patch_header(audiofilewriter_audiofilewriter_obj_t *self) { + if (!audiofilewriter_has_file(self)) { + return; + } + uint8_t sz[4]; + int err = 0; + + // RIFF chunk size lives at header_offset + 4. + put_u32le(sz, 36 + self->data_bytes); + if (mp_stream_seek(self->file, self->header_offset + 4, MP_SEEK_SET, &err) == (mp_off_t)-1) { + return; + } + mp_stream_write_exactly(self->file, sz, 4, &err); + + // data chunk size lives at header_offset + 40. + put_u32le(sz, self->data_bytes); + if (mp_stream_seek(self->file, self->header_offset + 40, MP_SEEK_SET, &err) == (mp_off_t)-1) { + return; + } + mp_stream_write_exactly(self->file, sz, 4, &err); + + // Leave the cursor at the end of the PCM so the caller can keep appending + // or simply close the file. + mp_stream_seek(self->file, self->header_offset + 44 + self->data_bytes, MP_SEEK_SET, &err); +} + +// Stop pumping, drain, patch the header, and release the source. Idempotent: +// only the first call (while playing) does work. Non-raising. +static void audiofilewriter_finalize(audiofilewriter_audiofilewriter_obj_t *self) { + if (!self->playing) { + return; + } + // Stop the pump first so a background tick can't re-enter us. + self->playing = false; + + audiofilewriter_flush(self); + audiofilewriter_patch_header(self); + + supervisor_disable_tick(); + audiofilewriter_unregister(self); + self->sample = MP_OBJ_NULL; +} + +// --------------------------------------------------------------------------- +// The pump: one real-time-paced step per supervisor tick +// --------------------------------------------------------------------------- + +static void audiofilewriter_pump(audiofilewriter_audiofilewriter_obj_t *self) { + if (!self->playing) { + return; + } + + // Each fetch of the next buffer from the source returns at most one + // source buffer, so pacing works in whole-buffer units. + int64_t frames_per_fetch = (int64_t)(self->source_max_buffer / self->bytes_per_frame); + if (frames_per_fetch < 1) { + frames_per_fetch = 1; + } + + // budget_frames counts how many frames are due from the source. Add the + // frames that real time says have played since the last tick. + uint64_t now = supervisor_ticks_ms64(); + uint64_t elapsed = now - self->last_tick_ms; + self->last_tick_ms = now; + // Ignore long gaps (GC pause, SD stall) so we don't try to catch up an + // unbounded backlog all at once. + if (elapsed > 100) { + elapsed = 100; + } + // Keep the fraction of a frame, which is most of the rounding error at + // 44.1 kHz and 22.05 kHz. + uint64_t scaled = elapsed * self->sample_rate + self->budget_remainder; + self->budget_frames += (int64_t)(scaled / 1000); + self->budget_remainder = (uint32_t)(scaled % 1000); + // Let no more than one source buffer of frames be due at once. A live + // source keeps its captured audio in its own fixed-size buffer; if we fall + // further behind than that, the extra audio has already been lost, so + // catching up can't recover it. It would only fetch the source's buffers + // back to back until it runs out and returns silence, turning one stall + // into a long glitch. With this limit a stall causes at most one short gap. + if (self->budget_frames > frames_per_fetch) { + self->budget_frames = frames_per_fetch; + } + + // Fetch the next buffer from the source whenever any audio is due, the way + // an audio output asks for its next buffer while the current one plays. + // Don't wait until a whole maximum-size buffer is due: a source can return + // less than its maximum (USBIn returns half). Fetching up to 4 buffers per + // tick catches up after a stall. Stop when the ring has no room for a full + // source buffer. + for (int fetches = 0; fetches < 4; fetches++) { + if (self->source_done || self->budget_frames <= 0 || + (audiofilewriter_has_file(self) && + (self->ring_size - self->ring_count) < self->source_max_buffer)) { + break; + } + uint8_t *buf = NULL; + uint32_t len = 0; + audioio_get_buffer_result_t res = + audiosample_get_buffer(self->sample, false, 0, &buf, &len); + if (res == GET_BUFFER_ERROR) { + self->source_done = true; + break; + } + if (len > 0 && buf != NULL) { + // Defend against a source that hands back more than it advertised. + if (len > self->source_max_buffer) { + len = self->source_max_buffer; + } + if (audiofilewriter_has_file(self)) { + audiofilewriter_ring_write(self, buf, len); + } + self->budget_frames -= (int64_t)(len / self->bytes_per_frame); + } + if (res == GET_BUFFER_DONE) { + self->source_done = true; + } + if (len == 0) { + break; + } + } + + if (!audiofilewriter_flush(self)) { + // File write failed; give up gracefully rather than spin. + self->source_done = true; + } + + if (self->source_done && self->ring_count == 0) { + audiofilewriter_finalize(self); + } +} + +void audiofilewriter_background(void) { + audiofilewriter_audiofilewriter_obj_t *self = REGISTRY_HEAD; + while (self != NULL) { + // Capture next before pumping: pump() may finalize self, which unlinks + // it from the registry (but leaves our saved next pointer valid). + audiofilewriter_audiofilewriter_obj_t *next = self->reg_next; + audiofilewriter_pump(self); + self = next; + } +} + +// Called during soft reset (VM teardown). Any writer still active is abandoned: +// we don't try to touch its file (it may already be gone), we just balance the +// tick-enable count and drop it from the list. +void audiofilewriter_reset(void) { + audiofilewriter_audiofilewriter_obj_t *self = REGISTRY_HEAD; + while (self != NULL) { + audiofilewriter_audiofilewriter_obj_t *next = self->reg_next; + if (self->playing) { + self->playing = false; + supervisor_disable_tick(); + } + self->reg_next = NULL; + self = next; + } + MP_STATE_VM(audiofilewriter_linked_list) = NULL; +} + +// --------------------------------------------------------------------------- +// common-hal surface +// --------------------------------------------------------------------------- + +void common_hal_audiofilewriter_audiofilewriter_construct(audiofilewriter_audiofilewriter_obj_t *self, + mp_obj_t file, uint32_t buffer_size) { + self->ring = NULL; + self->ring_size = 0; + if (file != mp_const_none) { + // The file must be a writable, seekable binary stream (a file or BytesIO). + mp_get_stream_raise(file, MP_STREAM_OP_WRITE | MP_STREAM_OP_IOCTL); + self->ring_size = buffer_size; + self->ring = m_malloc_without_collect(buffer_size); + } + + self->file = file; + self->sample = MP_OBJ_NULL; + self->ring_head = 0; + self->ring_tail = 0; + self->ring_count = 0; + self->playing = false; + self->source_done = false; + self->reg_next = NULL; +} + +bool common_hal_audiofilewriter_audiofilewriter_deinited(audiofilewriter_audiofilewriter_obj_t *self) { + return self->file == MP_OBJ_NULL; +} + +void common_hal_audiofilewriter_audiofilewriter_deinit(audiofilewriter_audiofilewriter_obj_t *self) { + if (self->playing) { + common_hal_audiofilewriter_audiofilewriter_stop(self); + } + self->ring = NULL; + self->file = MP_OBJ_NULL; + self->sample = MP_OBJ_NULL; +} + +void common_hal_audiofilewriter_audiofilewriter_play(audiofilewriter_audiofilewriter_obj_t *self, mp_obj_t sample_obj) { + if (self->playing) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Already in progress")); + } + + audiosample_base_t *sample = audiosample_check(sample_obj); + uint32_t rate = audiosample_get_sample_rate(sample); + uint8_t channels = audiosample_get_channel_count(sample); + uint8_t bits = audiosample_get_bits_per_sample(sample); + bool single_buffer, samples_signed; + uint32_t max_buffer_length; + uint8_t spacing; + audiosample_get_buffer_structure(sample, false, &single_buffer, &samples_signed, + &max_buffer_length, &spacing); + + if ((bits != 8 && bits != 16) || channels < 1 || channels > 2) { + mp_raise_ValueError(MP_ERROR_TEXT("Only 8/16-bit mono/stereo is supported")); + } + if (max_buffer_length == 0 || + (audiofilewriter_has_file(self) && self->ring_size < max_buffer_length)) { + mp_raise_ValueError(MP_ERROR_TEXT("buffer_size too small for source")); + } + + self->sample_rate = rate; + self->channel_count = channels; + self->bits_per_sample = bits; + self->samples_signed = samples_signed; + self->bytes_per_frame = (uint8_t)(channels * (bits / 8)); + self->source_max_buffer = max_buffer_length; + + if (audiofilewriter_has_file(self)) { + // Remember where the header starts so stop() can patch its size fields, + // then write a placeholder header with zeroed sizes. + int err = 0; + mp_off_t off = mp_stream_seek(self->file, 0, MP_SEEK_CUR, &err); + if (off == (mp_off_t)-1) { + mp_raise_OSError(err ? err : MP_EIO); + } + self->header_offset = (uint32_t)off; + + uint32_t block_align = self->bytes_per_frame; + uint32_t byte_rate = rate * block_align; + uint8_t hdr[44]; + memcpy(hdr + 0, "RIFF", 4); + put_u32le(hdr + 4, 36); // RIFF size (patched at stop) + memcpy(hdr + 8, "WAVE", 4); + memcpy(hdr + 12, "fmt ", 4); + put_u32le(hdr + 16, 16); // fmt chunk size + put_u16le(hdr + 20, 1); // PCM + put_u16le(hdr + 22, channels); + put_u32le(hdr + 24, rate); + put_u32le(hdr + 28, byte_rate); + put_u16le(hdr + 32, (uint16_t)block_align); + put_u16le(hdr + 34, bits); + memcpy(hdr + 36, "data", 4); + put_u32le(hdr + 40, 0); // data size (patched at stop) + + err = 0; + mp_uint_t wrote = mp_stream_write_exactly(self->file, hdr, sizeof(hdr), &err); + if (err != 0 || wrote != sizeof(hdr)) { + mp_raise_OSError(err ? err : MP_EIO); + } + } + + audiosample_reset_buffer(sample_obj, false, 0); + + self->sample = sample_obj; + self->ring_head = 0; + self->ring_tail = 0; + self->ring_count = 0; + self->budget_frames = 0; + self->budget_remainder = 0; + self->data_bytes = 0; + self->source_done = false; + self->last_tick_ms = supervisor_ticks_ms64(); + self->playing = true; + + audiofilewriter_register(self); + supervisor_enable_tick(); +} + +void common_hal_audiofilewriter_audiofilewriter_stop(audiofilewriter_audiofilewriter_obj_t *self) { + if (!self->playing) { + return; + } + // Keep the background pump out while we finalize from Python context. + background_callback_prevent(); + audiofilewriter_finalize(self); + background_callback_allow(); +} + +bool common_hal_audiofilewriter_audiofilewriter_get_playing(audiofilewriter_audiofilewriter_obj_t *self) { + return self->playing; +} + +MP_REGISTER_ROOT_POINTER(mp_obj_t audiofilewriter_linked_list); diff --git a/shared-module/audiofilewriter/AudioFileWriter.h b/shared-module/audiofilewriter/AudioFileWriter.h new file mode 100644 index 00000000000..7c9bf38979f --- /dev/null +++ b/shared-module/audiofilewriter/AudioFileWriter.h @@ -0,0 +1,71 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include + +#include "py/obj.h" + +// A streaming WAV *sink*: it consumes an audiosample source (a mic, synthio, +// or an effect chain) and writes the resulting PCM to a file. Unlike WaveFile +// it is NOT an audiosample, it is the thing that drives a source, playing the +// role an AudioOut would. +typedef struct _audiofilewriter_audiofilewriter_obj_t { + mp_obj_base_t base; + + // Output stream (anything with write + MP_STREAM_SEEK ioctl: a file or a + // BytesIO). Held so it stays referenced while recording. None to fetch + // buffers from the source and drop them; MP_OBJ_NULL once deinited. + mp_obj_t file; + // The source being recorded. Only valid (and referenced) while playing. + mp_obj_t sample; + + // Format, captured from the source at play() time. AudioFileWriter is the + // format authority for the WAV header. + uint32_t sample_rate; + uint8_t channel_count; + uint8_t bits_per_sample; + bool samples_signed; + uint8_t bytes_per_frame; // channel_count * bits_per_sample / 8 + uint32_t source_max_buffer; // largest buffer the source can hand back, bytes + + // RAM ring that decouples SD-write latency from the source. Written by the + // pump, drained to the file by the pump. Only touched from background-task + // context (never an ISR), so no locking is needed. NULL without a file. + uint8_t *ring; + uint32_t ring_size; // capacity in bytes + uint32_t ring_head; // write cursor + uint32_t ring_tail; // read cursor + uint32_t ring_count; // bytes currently buffered + + // Real-time pacing: budget_frames is the number of frames due from the + // source. It goes up by sample_rate frames for each second of elapsed + // supervisor ticks and down by the frames in each buffer fetched. The next + // buffer is fetched from the source only while it is above zero. + int64_t budget_frames; + uint32_t budget_remainder; // thousandths of a frame not yet in budget_frames + uint64_t last_tick_ms; + + // Absolute file offset of the RIFF header start, so stop() can seek back and + // patch the two size fields once the final length is known. + uint32_t header_offset; + uint32_t data_bytes; // total PCM bytes handed to the file + + bool playing; + bool source_done; // source returned DONE/ERROR; drain then finalize + + // Intrusive linked list of active writers, walked once per supervisor tick. + struct _audiofilewriter_audiofilewriter_obj_t *reg_next; +} audiofilewriter_audiofilewriter_obj_t; + +// Called once per supervisor tick (from supervisor_background_tick), in +// background-task context. Pumps every active writer. +void audiofilewriter_background(void); + +// Called during soft reset to abandon any writer left recording. +void audiofilewriter_reset(void); diff --git a/shared-module/audiofilewriter/__init__.c b/shared-module/audiofilewriter/__init__.c new file mode 100644 index 00000000000..584c821b996 --- /dev/null +++ b/shared-module/audiofilewriter/__init__.c @@ -0,0 +1,5 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT diff --git a/shared-module/audiofilters/Distortion.c b/shared-module/audiofilters/Distortion.c index b1f22c48545..d235de59614 100644 --- a/shared-module/audiofilters/Distortion.c +++ b/shared-module/audiofilters/Distortion.c @@ -40,14 +40,14 @@ void common_hal_audiofilters_distortion_construct(audiofilters_distortion_obj_t // Samples are set sequentially. For stereo audio they are passed L/R/L/R/... self->buffer_len = buffer_size; // in bytes - self->buffer[0] = m_malloc(self->buffer_len); + self->buffer[0] = m_malloc_without_collect(self->buffer_len); if (self->buffer[0] == NULL) { common_hal_audiofilters_distortion_deinit(self); m_malloc_fail(self->buffer_len); } memset(self->buffer[0], 0, self->buffer_len); - self->buffer[1] = m_malloc(self->buffer_len); + self->buffer[1] = m_malloc_without_collect(self->buffer_len); if (self->buffer[1] == NULL) { common_hal_audiofilters_distortion_deinit(self); m_malloc_fail(self->buffer_len); @@ -141,7 +141,7 @@ bool common_hal_audiofilters_distortion_get_playing(audiofilters_distortion_obj_ } void common_hal_audiofilters_distortion_play(audiofilters_distortion_obj_t *self, mp_obj_t sample, bool loop) { - audiosample_must_match(&self->base, sample); + audiosample_must_match(&self->base, sample, false); self->sample = sample; self->loop = loop; @@ -174,7 +174,11 @@ audioio_get_buffer_result_t audiofilters_distortion_get_buffer(audiofilters_dist self->last_buf_idx = !self->last_buf_idx; // If we are using 16 bit samples we need a 16 bit pointer, 8 bit needs an 8 bit pointer + // buffer[] was allocated on the heap, so it is aligned for 16-bit access. + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wcast-align" int16_t *word_buffer = (int16_t *)self->buffer[self->last_buf_idx]; + #pragma GCC diagnostic pop int8_t *hword_buffer = self->buffer[self->last_buf_idx]; uint32_t length = self->buffer_len / (self->base.bits_per_sample / 8); @@ -192,9 +196,15 @@ audioio_get_buffer_result_t audiofilters_distortion_get_buffer(audiofilters_dist if (self->sample) { // Load another sample buffer to play audioio_get_buffer_result_t result = audiosample_get_buffer(self->sample, false, 0, (uint8_t **)&self->sample_remaining_buffer, &self->sample_buffer_length); - // Track length in terms of words. - self->sample_buffer_length /= (self->base.bits_per_sample / 8); - self->more_data = result == GET_BUFFER_MORE_DATA; + if (result == GET_BUFFER_ERROR) { + self->sample = NULL; + self->sample_buffer_length = 0; + self->more_data = false; + } else { + // Track length in terms of words. + self->sample_buffer_length /= (self->base.bits_per_sample / 8); + self->more_data = result == GET_BUFFER_MORE_DATA; + } } } @@ -204,7 +214,9 @@ audioio_get_buffer_result_t audiofilters_distortion_get_buffer(audiofilters_dist } else { // For unsigned samples set to the middle which is "quiet" if (MP_LIKELY(self->base.bits_per_sample == 16)) { - memset(word_buffer, 32768, length * (self->base.bits_per_sample / 8)); + for (uint32_t si = 0; si < length; si++) { + word_buffer[si] = (int16_t)0x8000; + } } else { memset(hword_buffer, 128, length * (self->base.bits_per_sample / 8)); } @@ -223,7 +235,11 @@ audioio_get_buffer_result_t audiofilters_distortion_get_buffer(audiofilters_dist // Determine how many bytes we can process to our buffer, the less of the sample we have left and our buffer remaining uint32_t n = MIN(MIN(self->sample_buffer_length, length), SYNTHIO_MAX_DUR * self->base.channel_count); + // The source's buffer is aligned, and it is only advanced in whole samples. + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wcast-align" int16_t *sample_src = (int16_t *)self->sample_remaining_buffer; // for 16-bit samples + #pragma GCC diagnostic pop int8_t *sample_hsrc = (int8_t *)self->sample_remaining_buffer; // for 8-bit samples // get the effect values we need from the BlockInput. These may change at run time so you need to do bounds checking if required @@ -319,7 +335,7 @@ audioio_get_buffer_result_t audiofilters_distortion_get_buffer(audiofilters_dist // Hard clip if (!self->soft_clip) { - word = MIN(MAX(word, -32767), 32768); + word = MIN(MAX(word, -32767), 32767); } if (MP_LIKELY(self->base.bits_per_sample == 16)) { diff --git a/shared-module/audiofilters/Filter.c b/shared-module/audiofilters/Filter.c index 10876c44f7c..ae907e365b4 100644 --- a/shared-module/audiofilters/Filter.c +++ b/shared-module/audiofilters/Filter.c @@ -5,8 +5,8 @@ // SPDX-License-Identifier: MIT #include "shared-bindings/audiofilters/Filter.h" #include "shared-bindings/audiocore/__init__.h" +#include "shared-module/synthio/Biquad.h" -#include "shared-module/synthio/BlockBiquad.h" #include #include "py/runtime.h" @@ -31,17 +31,17 @@ void common_hal_audiofilters_filter_construct(audiofilters_filter_obj_t *self, // Samples are set sequentially. For stereo audio they are passed L/R/L/R/... self->buffer_len = buffer_size; // in bytes - self->buffer[0] = m_malloc(self->buffer_len); + self->buffer[0] = m_malloc_without_collect(self->buffer_len); memset(self->buffer[0], 0, self->buffer_len); - self->buffer[1] = m_malloc(self->buffer_len); + self->buffer[1] = m_malloc_without_collect(self->buffer_len); memset(self->buffer[1], 0, self->buffer_len); self->last_buf_idx = 1; // Which buffer to use first, toggle between 0 and 1 // This buffer will be used to process samples through the biquad filter - self->filter_buffer = m_malloc(SYNTHIO_MAX_DUR * sizeof(int32_t)); - memset(self->filter_buffer, 0, SYNTHIO_MAX_DUR * sizeof(int32_t)); + self->filter_buffer = m_malloc_without_collect(SYNTHIO_MAX_DUR * self->base.channel_count * sizeof(int32_t)); + memset(self->filter_buffer, 0, SYNTHIO_MAX_DUR * self->base.channel_count * sizeof(int32_t)); // Initialize other values most effects will need. self->sample = NULL; // The current playing sample @@ -59,64 +59,17 @@ void common_hal_audiofilters_filter_construct(audiofilters_filter_obj_t *self, void common_hal_audiofilters_filter_deinit(audiofilters_filter_obj_t *self) { audiosample_mark_deinit(&self->base); + audiofilters_deinit_filter_chain(&self->filter); self->buffer[0] = NULL; self->buffer[1] = NULL; - self->filter = mp_const_none; - self->filter_buffer = NULL; - self->filter_states = NULL; } void common_hal_audiofilters_filter_set_filter(audiofilters_filter_obj_t *self, mp_obj_t filter_in) { - size_t n_items; - mp_obj_t *items; - mp_obj_t *filter_objs; - - if (filter_in == mp_const_none) { - n_items = 0; - filter_objs = NULL; - } else if (MP_OBJ_TYPE_HAS_SLOT(mp_obj_get_type(filter_in), iter)) { - // convert object to tuple if it wasn't before - filter_in = MP_OBJ_TYPE_GET_SLOT(&mp_type_tuple, make_new)( - &mp_type_tuple, 1, 0, &filter_in); - mp_obj_tuple_get(filter_in, &n_items, &items); - for (size_t i = 0; i < n_items; i++) { - if (!synthio_is_any_biquad(items[i])) { - mp_raise_TypeError_varg( - MP_ERROR_TEXT("%q in %q must be of type %q, not %q"), - MP_QSTR_object, - MP_QSTR_filter, - MP_QSTR_AnyBiquad, - mp_obj_get_type(items[i])->name); - } - } - filter_objs = items; - } else { - n_items = 1; - if (!synthio_is_any_biquad(filter_in)) { - mp_raise_TypeError_varg( - MP_ERROR_TEXT("%q must be of type %q or %q, not %q"), - MP_QSTR_filter, MP_QSTR_AnyBiquad, MP_QSTR_iterable, mp_obj_get_type(filter_in)->name); - } - filter_objs = &self->filter; - } - - // everything has been checked, so we can do the following without fear - - self->filter = filter_in; - self->filter_objs = filter_objs; - self->filter_states = m_renew(biquad_filter_state, - self->filter_states, - self->filter_states_len, - n_items); - self->filter_states_len = n_items; - - for (size_t i = 0; i < n_items; i++) { - synthio_biquad_filter_assign(&self->filter_states[i], items[i]); - } + audiofilters_assign_filter_chain(&self->filter, filter_in, self->base.channel_count); } mp_obj_t common_hal_audiofilters_filter_get_filter(audiofilters_filter_obj_t *self) { - return self->filter; + return self->filter.obj; } mp_obj_t common_hal_audiofilters_filter_get_mix(audiofilters_filter_obj_t *self) { @@ -133,13 +86,9 @@ void audiofilters_filter_reset_buffer(audiofilters_filter_obj_t *self, memset(self->buffer[0], 0, self->buffer_len); memset(self->buffer[1], 0, self->buffer_len); - memset(self->filter_buffer, 0, SYNTHIO_MAX_DUR * sizeof(int32_t)); + memset(self->filter_buffer, 0, SYNTHIO_MAX_DUR * self->base.channel_count * sizeof(int32_t)); - if (self->filter_states) { - for (uint8_t i = 0; i < self->filter_states_len; i++) { - synthio_biquad_filter_reset(&self->filter_states[i]); - } - } + audiofilters_reset_filter_chain(&self->filter, self->base.channel_count); } bool common_hal_audiofilters_filter_get_playing(audiofilters_filter_obj_t *self) { @@ -147,7 +96,7 @@ bool common_hal_audiofilters_filter_get_playing(audiofilters_filter_obj_t *self) } void common_hal_audiofilters_filter_play(audiofilters_filter_obj_t *self, mp_obj_t sample, bool loop) { - audiosample_must_match(&self->base, sample); + audiosample_must_match(&self->base, sample, false); self->sample = sample; self->loop = loop; @@ -181,7 +130,11 @@ audioio_get_buffer_result_t audiofilters_filter_get_buffer(audiofilters_filter_o self->last_buf_idx = !self->last_buf_idx; // If we are using 16 bit samples we need a 16 bit pointer, 8 bit needs an 8 bit pointer + // buffer[] was allocated on the heap, so it is aligned for 16-bit access. + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wcast-align" int16_t *word_buffer = (int16_t *)self->buffer[self->last_buf_idx]; + #pragma GCC diagnostic pop int8_t *hword_buffer = self->buffer[self->last_buf_idx]; uint32_t length = self->buffer_len / (self->base.bits_per_sample / 8); @@ -199,9 +152,15 @@ audioio_get_buffer_result_t audiofilters_filter_get_buffer(audiofilters_filter_o if (self->sample) { // Load another sample buffer to play audioio_get_buffer_result_t result = audiosample_get_buffer(self->sample, false, 0, (uint8_t **)&self->sample_remaining_buffer, &self->sample_buffer_length); - // Track length in terms of words. - self->sample_buffer_length /= (self->base.bits_per_sample / 8); - self->more_data = result == GET_BUFFER_MORE_DATA; + if (result == GET_BUFFER_ERROR) { + self->sample = NULL; + self->sample_buffer_length = 0; + self->more_data = false; + } else { + // Track length in terms of words. + self->sample_buffer_length /= (self->base.bits_per_sample / 8); + self->more_data = result == GET_BUFFER_MORE_DATA; + } } } @@ -211,12 +170,8 @@ audioio_get_buffer_result_t audiofilters_filter_get_buffer(audiofilters_filter_o (void)synthio_block_slot_get(&self->mix); // Tick biquad filters - for (uint8_t j = 0; j < self->filter_states_len; j++) { - mp_obj_t filter_obj = self->filter_objs[j]; - if (mp_obj_is_type(filter_obj, &synthio_block_biquad_type_obj)) { - common_hal_synthio_block_biquad_tick(filter_obj, &self->filter_states[j]); - } - } + audiofilters_tick_filter_chain(&self->filter); + if (self->base.samples_signed) { memset(word_buffer, 0, length * (self->base.bits_per_sample / 8)); } else { @@ -237,14 +192,18 @@ audioio_get_buffer_result_t audiofilters_filter_get_buffer(audiofilters_filter_o // Determine how many bytes we can process to our buffer, the less of the sample we have left and our buffer remaining uint32_t n = MIN(MIN(self->sample_buffer_length, length), SYNTHIO_MAX_DUR * self->base.channel_count); + // The source's buffer is aligned, and it is only advanced in whole samples. + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wcast-align" int16_t *sample_src = (int16_t *)self->sample_remaining_buffer; // for 16-bit samples + #pragma GCC diagnostic pop int8_t *sample_hsrc = (int8_t *)self->sample_remaining_buffer; // for 8-bit samples // get the effect values we need from the BlockInput. These may change at run time so you need to do bounds checking if required shared_bindings_synthio_lfo_tick(self->base.sample_rate, n / self->base.channel_count); mp_float_t mix = synthio_block_slot_get_limited(&self->mix, MICROPY_FLOAT_CONST(0.0), MICROPY_FLOAT_CONST(1.0)); - if (mix <= MICROPY_FLOAT_CONST(0.01) || !self->filter_states) { // if mix is zero pure sample only or no biquad filter objects are provided + if (mix <= MICROPY_FLOAT_CONST(0.01) || !self->filter.states) { // if mix is zero pure sample only or no biquad filter objects are provided for (uint32_t i = 0; i < n; i++) { if (MP_LIKELY(self->base.bits_per_sample == 16)) { word_buffer[i] = sample_src[i]; @@ -255,48 +214,52 @@ audioio_get_buffer_result_t audiofilters_filter_get_buffer(audiofilters_filter_o } else { uint32_t i = 0; while (i < n) { - uint32_t n_samples = MIN(SYNTHIO_MAX_DUR, n - i); + uint32_t n_samples = MIN(SYNTHIO_MAX_DUR, (n - i) >> (self->base.channel_count - 1)); // Fill filter buffer with samples - for (uint32_t j = 0; j < n_samples; j++) { + for (uint32_t j = 0; j < n_samples * self->base.channel_count; j++) { + bool buf_offset = (j % self->base.channel_count) == 1; + uint32_t k = j / self->base.channel_count; if (MP_LIKELY(self->base.bits_per_sample == 16)) { - self->filter_buffer[j] = sample_src[i + j]; + self->filter_buffer[k + SYNTHIO_MAX_DUR * buf_offset] = sample_src[i + j]; } else { if (self->base.samples_signed) { - self->filter_buffer[j] = sample_hsrc[i + j]; + self->filter_buffer[k + SYNTHIO_MAX_DUR * buf_offset] = sample_hsrc[i + j]; } else { // Be careful here changing from an 8 bit unsigned to signed into a 32-bit signed - self->filter_buffer[j] = (int8_t)(((uint8_t)sample_hsrc[i + j]) ^ 0x80); + self->filter_buffer[k + SYNTHIO_MAX_DUR * buf_offset] = (int8_t)(((uint8_t)sample_hsrc[i + j]) ^ 0x80); } } } // Process biquad filters - for (uint8_t j = 0; j < self->filter_states_len; j++) { - mp_obj_t filter_obj = self->filter_objs[j]; - if (mp_obj_is_type(filter_obj, &synthio_block_biquad_type_obj)) { - common_hal_synthio_block_biquad_tick(filter_obj, &self->filter_states[j]); + for (size_t j = 0; j < self->filter.objs_len; j++) { + mp_obj_t filter_obj = self->filter.objs[j]; + common_hal_synthio_biquad_tick(filter_obj); + for (uint8_t k = 0; k < self->base.channel_count; k++) { + synthio_biquad_filter_samples(filter_obj, &self->filter.states[j * self->base.channel_count + k], self->filter_buffer + k * SYNTHIO_MAX_DUR, n_samples); } - synthio_biquad_filter_samples(&self->filter_states[j], self->filter_buffer, n_samples); } // Mix processed signal with original sample and transfer to output buffer - for (uint32_t j = 0; j < n_samples; j++) { + for (uint32_t j = 0; j < n_samples * self->base.channel_count; j++) { + bool buf_offset = (j % self->base.channel_count) == 1; + uint32_t k = j / self->base.channel_count; if (MP_LIKELY(self->base.bits_per_sample == 16)) { - word_buffer[i + j] = synthio_mix_down_sample((int32_t)((sample_src[i + j] * (MICROPY_FLOAT_CONST(1.0) - mix)) + (self->filter_buffer[j] * mix)), SYNTHIO_MIX_DOWN_SCALE(2)); + word_buffer[i + j] = synthio_mix_down_sample((int32_t)((sample_src[i + j] * (MICROPY_FLOAT_CONST(1.0) - mix)) + (self->filter_buffer[k + SYNTHIO_MAX_DUR * buf_offset] * mix)), SYNTHIO_MIX_DOWN_SCALE(2)); if (!self->base.samples_signed) { word_buffer[i + j] ^= 0x8000; } } else { if (self->base.samples_signed) { - hword_buffer[i + j] = (int8_t)((sample_hsrc[i + j] * (MICROPY_FLOAT_CONST(1.0) - mix)) + (self->filter_buffer[j] * mix)); + hword_buffer[i + j] = (int8_t)((sample_hsrc[i + j] * (MICROPY_FLOAT_CONST(1.0) - mix)) + (self->filter_buffer[k + SYNTHIO_MAX_DUR * buf_offset] * mix)); } else { - hword_buffer[i + j] = (uint8_t)(((int8_t)(((uint8_t)sample_hsrc[i + j]) ^ 0x80) * (MICROPY_FLOAT_CONST(1.0) - mix)) + (self->filter_buffer[j] * mix)) ^ 0x80; + hword_buffer[i + j] = (uint8_t)(((int8_t)(((uint8_t)sample_hsrc[i + j]) ^ 0x80) * (MICROPY_FLOAT_CONST(1.0) - mix)) + (self->filter_buffer[k + SYNTHIO_MAX_DUR * buf_offset] * mix)) ^ 0x80; } } } - i += n_samples; + i += n_samples * self->base.channel_count; } } diff --git a/shared-module/audiofilters/Filter.h b/shared-module/audiofilters/Filter.h index 4447f8a2988..6cb352d4273 100644 --- a/shared-module/audiofilters/Filter.h +++ b/shared-module/audiofilters/Filter.h @@ -9,6 +9,7 @@ #include "shared-bindings/synthio/Biquad.h" #include "shared-module/audiocore/__init__.h" +#include "shared-module/audiofilters/__init__.h" #include "shared-module/synthio/__init__.h" #include "shared-module/synthio/block.h" #include "shared-module/synthio/Biquad.h" @@ -17,13 +18,9 @@ extern const mp_obj_type_t audiofilters_filter_type; typedef struct { audiosample_base_t base; - mp_obj_t filter; + audiofilters_filter_chain_t filter; synthio_block_slot_t mix; - mp_obj_t *filter_objs; - size_t filter_states_len; - biquad_filter_state *filter_states; - int8_t *buffer[2]; uint8_t last_buf_idx; uint32_t buffer_len; // max buffer in bytes diff --git a/shared-module/audiofilters/Phaser.c b/shared-module/audiofilters/Phaser.c new file mode 100644 index 00000000000..367bc4b3f84 --- /dev/null +++ b/shared-module/audiofilters/Phaser.c @@ -0,0 +1,316 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Cooper Dalrymple +// +// SPDX-License-Identifier: MIT +#include "shared-bindings/audiofilters/Phaser.h" +#include "shared-bindings/audiocore/__init__.h" + +#include +#include "py/runtime.h" + +void common_hal_audiofilters_phaser_construct(audiofilters_phaser_obj_t *self, + mp_obj_t frequency, mp_obj_t feedback, mp_obj_t mix, uint8_t stages, + uint32_t buffer_size, uint8_t bits_per_sample, + bool samples_signed, uint8_t channel_count, uint32_t sample_rate) { + + // Basic settings every effect and audio sample has + // These are the effects values, not the source sample(s) + self->base.bits_per_sample = bits_per_sample; // Most common is 16, but 8 is also supported in many places + self->base.samples_signed = samples_signed; // Are the samples we provide signed (common is true) + self->base.channel_count = channel_count; // Channels can be 1 for mono or 2 for stereo + self->base.sample_rate = sample_rate; // Sample rate for the effect, this generally needs to match all audio objects + self->base.single_buffer = false; + self->base.max_buffer_length = buffer_size; + + // To smooth things out as CircuitPython is doing other tasks most audio objects have a buffer + // A double buffer is set up here so the audio output can use DMA on buffer 1 while we + // write to and create buffer 2. + // This buffer is what is passed to the audio component that plays the effect. + // Samples are set sequentially. For stereo audio they are passed L/R/L/R/... + self->buffer_len = buffer_size; // in bytes + + self->buffer[0] = m_malloc_without_collect(self->buffer_len); + memset(self->buffer[0], 0, self->buffer_len); + + self->buffer[1] = m_malloc_without_collect(self->buffer_len); + memset(self->buffer[1], 0, self->buffer_len); + + self->last_buf_idx = 1; // Which buffer to use first, toggle between 0 and 1 + + // Initialize other values most effects will need. + self->sample = NULL; // The current playing sample + self->sample_remaining_buffer = NULL; // Pointer to the start of the sample buffer we have not played + self->sample_buffer_length = 0; // How many samples do we have left to play (these may be 16 bit!) + self->loop = false; // When the sample is done do we loop to the start again or stop (e.g. in a wav file) + self->more_data = false; // Is there still more data to read from the sample or did we finish + + // The below section sets up the effect's starting values. + + // Create buffer to hold the last processed word + self->word_buffer = m_malloc_without_collect(self->base.channel_count * sizeof(int16_t)); + memset(self->word_buffer, 0, self->base.channel_count * sizeof(int16_t)); + + self->nyquist = (mp_float_t)self->base.sample_rate / 2; + + if (feedback == mp_const_none) { + feedback = mp_obj_new_float(MICROPY_FLOAT_CONST(0.7)); + } + + synthio_block_assign_slot(frequency, &self->frequency, MP_QSTR_frequency); + synthio_block_assign_slot(feedback, &self->feedback, MP_QSTR_feedback); + synthio_block_assign_slot(mix, &self->mix, MP_QSTR_mix); + + common_hal_audiofilters_phaser_set_stages(self, stages); +} + +void common_hal_audiofilters_phaser_deinit(audiofilters_phaser_obj_t *self) { + audiosample_mark_deinit(&self->base); + self->buffer[0] = NULL; + self->buffer[1] = NULL; + self->word_buffer = NULL; + self->allpass_buffer = NULL; +} + +mp_obj_t common_hal_audiofilters_phaser_get_frequency(audiofilters_phaser_obj_t *self) { + return self->frequency.obj; +} + +void common_hal_audiofilters_phaser_set_frequency(audiofilters_phaser_obj_t *self, mp_obj_t arg) { + synthio_block_assign_slot(arg, &self->frequency, MP_QSTR_frequency); +} + +mp_obj_t common_hal_audiofilters_phaser_get_feedback(audiofilters_phaser_obj_t *self) { + return self->feedback.obj; +} + +void common_hal_audiofilters_phaser_set_feedback(audiofilters_phaser_obj_t *self, mp_obj_t arg) { + synthio_block_assign_slot(arg, &self->feedback, MP_QSTR_feedback); +} + +mp_obj_t common_hal_audiofilters_phaser_get_mix(audiofilters_phaser_obj_t *self) { + return self->mix.obj; +} + +void common_hal_audiofilters_phaser_set_mix(audiofilters_phaser_obj_t *self, mp_obj_t arg) { + synthio_block_assign_slot(arg, &self->mix, MP_QSTR_mix); +} + +uint8_t common_hal_audiofilters_phaser_get_stages(audiofilters_phaser_obj_t *self) { + return self->stages; +} + +void common_hal_audiofilters_phaser_set_stages(audiofilters_phaser_obj_t *self, uint8_t arg) { + if (!arg) { + arg = 1; + } + + self->allpass_buffer = (int16_t *)m_realloc(self->allpass_buffer, + #if MICROPY_MALLOC_USES_ALLOCATED_SIZE + self->base.channel_count * self->stages * sizeof(int16_t), // Old size + #endif + self->base.channel_count * arg * sizeof(int16_t)); + self->stages = arg; + + memset(self->allpass_buffer, 0, self->base.channel_count * self->stages * sizeof(int16_t)); +} + +void audiofilters_phaser_reset_buffer(audiofilters_phaser_obj_t *self, + bool single_channel_output, + uint8_t channel) { + + memset(self->buffer[0], 0, self->buffer_len); + memset(self->buffer[1], 0, self->buffer_len); + memset(self->word_buffer, 0, self->base.channel_count * sizeof(int16_t)); + memset(self->allpass_buffer, 0, self->base.channel_count * self->stages * sizeof(int16_t)); +} + +bool common_hal_audiofilters_phaser_get_playing(audiofilters_phaser_obj_t *self) { + return self->sample != NULL; +} + +void common_hal_audiofilters_phaser_play(audiofilters_phaser_obj_t *self, mp_obj_t sample, bool loop) { + audiosample_must_match(&self->base, sample, false); + + self->sample = sample; + self->loop = loop; + + audiosample_reset_buffer(self->sample, false, 0); + audioio_get_buffer_result_t result = audiosample_get_buffer(self->sample, false, 0, (uint8_t **)&self->sample_remaining_buffer, &self->sample_buffer_length); + + // Track remaining sample length in terms of bytes per sample + self->sample_buffer_length /= (self->base.bits_per_sample / 8); + // Store if we have more data in the sample to retrieve + self->more_data = result == GET_BUFFER_MORE_DATA; + + return; +} + +void common_hal_audiofilters_phaser_stop(audiofilters_phaser_obj_t *self) { + // When the sample is set to stop playing do any cleanup here + self->sample = NULL; + return; +} + +audioio_get_buffer_result_t audiofilters_phaser_get_buffer(audiofilters_phaser_obj_t *self, bool single_channel_output, uint8_t channel, + uint8_t **buffer, uint32_t *buffer_length) { + (void)channel; + + if (!single_channel_output) { + channel = 0; + } + + // Switch our buffers to the other buffer + self->last_buf_idx = !self->last_buf_idx; + + // If we are using 16 bit samples we need a 16 bit pointer, 8 bit needs an 8 bit pointer + // buffer[] was allocated on the heap, so it is aligned for 16-bit access. + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wcast-align" + int16_t *word_buffer = (int16_t *)self->buffer[self->last_buf_idx]; + #pragma GCC diagnostic pop + int8_t *hword_buffer = self->buffer[self->last_buf_idx]; + uint32_t length = self->buffer_len / (self->base.bits_per_sample / 8); + + // Loop over the entire length of our buffer to fill it, this may require several calls to get data from the sample + while (length != 0) { + // Check if there is no more sample to play, we will either load more data, reset the sample if loop is on or clear the sample + if (self->sample_buffer_length == 0) { + if (!self->more_data) { // The sample has indicated it has no more data to play + if (self->loop && self->sample) { // If we are supposed to loop reset the sample to the start + audiosample_reset_buffer(self->sample, false, 0); + } else { // If we were not supposed to loop the sample, stop playing it + self->sample = NULL; + } + } + if (self->sample) { + // Load another sample buffer to play + audioio_get_buffer_result_t result = audiosample_get_buffer(self->sample, false, 0, (uint8_t **)&self->sample_remaining_buffer, &self->sample_buffer_length); + if (result == GET_BUFFER_ERROR) { + self->sample = NULL; + self->sample_buffer_length = 0; + self->more_data = false; + } else { + // Track length in terms of words. + self->sample_buffer_length /= (self->base.bits_per_sample / 8); + self->more_data = result == GET_BUFFER_MORE_DATA; + } + } + } + + if (self->sample == NULL) { + // tick all block inputs + shared_bindings_synthio_lfo_tick(self->base.sample_rate, length / self->base.channel_count); + (void)synthio_block_slot_get(&self->frequency); + (void)synthio_block_slot_get(&self->feedback); + (void)synthio_block_slot_get(&self->mix); + + if (self->base.samples_signed) { + memset(word_buffer, 0, length * (self->base.bits_per_sample / 8)); + } else { + // For unsigned samples set to the middle which is "quiet" + if (MP_LIKELY(self->base.bits_per_sample == 16)) { + uint16_t *uword_buffer = (uint16_t *)word_buffer; + while (length--) { + *uword_buffer++ = 32768; + } + } else { + memset(hword_buffer, 128, length * (self->base.bits_per_sample / 8)); + } + } + + length = 0; + } else { + // we have a sample to play and filter + // Determine how many bytes we can process to our buffer, the less of the sample we have left and our buffer remaining + uint32_t n = MIN(MIN(self->sample_buffer_length, length), SYNTHIO_MAX_DUR * self->base.channel_count); + + // The source's buffer is aligned, and it is only advanced in whole samples. + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wcast-align" + int16_t *sample_src = (int16_t *)self->sample_remaining_buffer; // for 16-bit samples + #pragma GCC diagnostic pop + int8_t *sample_hsrc = (int8_t *)self->sample_remaining_buffer; // for 8-bit samples + + // get the effect values we need from the BlockInput. These may change at run time so you need to do bounds checking if required + shared_bindings_synthio_lfo_tick(self->base.sample_rate, n / self->base.channel_count); + mp_float_t frequency = synthio_block_slot_get_limited(&self->frequency, MICROPY_FLOAT_CONST(0.0), self->nyquist); + int16_t feedback = (int16_t)(synthio_block_slot_get_limited(&self->feedback, MICROPY_FLOAT_CONST(0.1), MICROPY_FLOAT_CONST(0.9)) * 32767); + int16_t mix = (int16_t)(synthio_block_slot_get_limited(&self->mix, MICROPY_FLOAT_CONST(0.0), MICROPY_FLOAT_CONST(1.0)) * 32767); + + if (mix <= 328) { // if mix is zero (0.01 in fixed point), pure sample only + for (uint32_t i = 0; i < n; i++) { + if (MP_LIKELY(self->base.bits_per_sample == 16)) { + word_buffer[i] = sample_src[i]; + } else { + hword_buffer[i] = sample_hsrc[i]; + } + } + } else { + // Update all-pass filter coefficient + frequency /= self->nyquist; // scale relative to frequency range + int16_t allpasscoef = (int16_t)((MICROPY_FLOAT_CONST(1.0) - frequency) / (MICROPY_FLOAT_CONST(1.0) + frequency) * 32767); + + for (uint32_t i = 0; i < n; i++) { + bool right_channel = (single_channel_output && channel == 1) || (!single_channel_output && (i % self->base.channel_count) == 1); + uint32_t allpass_buffer_offset = self->stages * right_channel; + + int32_t sample_word = 0; + if (MP_LIKELY(self->base.bits_per_sample == 16)) { + sample_word = sample_src[i]; + } else { + if (self->base.samples_signed) { + sample_word = sample_hsrc[i]; + } else { + // Be careful here changing from an 8 bit unsigned to signed into a 32-bit signed + sample_word = (int8_t)(((uint8_t)sample_hsrc[i]) ^ 0x80); + } + } + + int32_t word = synthio_sat16(sample_word + synthio_sat16((int32_t)self->word_buffer[right_channel] * feedback, 15), 0); + int32_t allpass_word = 0; + + // Update all-pass filters + for (uint32_t j = 0; j < self->stages; j++) { + allpass_word = synthio_sat16(synthio_sat16(word * -allpasscoef, 15) + self->allpass_buffer[j + allpass_buffer_offset], 0); + self->allpass_buffer[j + allpass_buffer_offset] = synthio_sat16(synthio_sat16(allpass_word * allpasscoef, 15) + word, 0); + word = allpass_word; + } + self->word_buffer[(bool)allpass_buffer_offset] = (int16_t)word; + + // Add original sample + effect + word = sample_word + (int32_t)(synthio_sat16(word * mix, 15)); + word = synthio_mix_down_sample(word, 2); + + if (MP_LIKELY(self->base.bits_per_sample == 16)) { + word_buffer[i] = word; + if (!self->base.samples_signed) { + word_buffer[i] ^= 0x8000; + } + } else { + int8_t out = word; + if (self->base.samples_signed) { + hword_buffer[i] = out; + } else { + hword_buffer[i] = (uint8_t)out ^ 0x80; + } + } + } + } + + // Update the remaining length and the buffer positions based on how much we wrote into our buffer + length -= n; + word_buffer += n; + hword_buffer += n; + self->sample_remaining_buffer += (n * (self->base.bits_per_sample / 8)); + self->sample_buffer_length -= n; + } + } + + // Finally pass our buffer and length to the calling audio function + *buffer = (uint8_t *)self->buffer[self->last_buf_idx]; + *buffer_length = self->buffer_len; + + // Phaser always returns more data but some effects may return GET_BUFFER_DONE or GET_BUFFER_ERROR (see audiocore/__init__.h) + return GET_BUFFER_MORE_DATA; +} diff --git a/shared-module/audiofilters/Phaser.h b/shared-module/audiofilters/Phaser.h new file mode 100644 index 00000000000..f627b147014 --- /dev/null +++ b/shared-module/audiofilters/Phaser.h @@ -0,0 +1,49 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Cooper Dalrymple +// +// SPDX-License-Identifier: MIT +#pragma once + +#include "py/obj.h" + +#include "shared-module/audiocore/__init__.h" +#include "shared-module/synthio/__init__.h" +#include "shared-module/synthio/block.h" + +extern const mp_obj_type_t audiofilters_phaser_type; + +typedef struct { + audiosample_base_t base; + synthio_block_slot_t frequency; + synthio_block_slot_t feedback; + synthio_block_slot_t mix; + uint8_t stages; + + mp_float_t nyquist; + + int8_t *buffer[2]; + uint8_t last_buf_idx; + uint32_t buffer_len; // max buffer in bytes + + uint8_t *sample_remaining_buffer; + uint32_t sample_buffer_length; + + bool loop; + bool more_data; + + int16_t *allpass_buffer; + int16_t *word_buffer; + + mp_obj_t sample; +} audiofilters_phaser_obj_t; + +void audiofilters_phaser_reset_buffer(audiofilters_phaser_obj_t *self, + bool single_channel_output, + uint8_t channel); + +audioio_get_buffer_result_t audiofilters_phaser_get_buffer(audiofilters_phaser_obj_t *self, + bool single_channel_output, + uint8_t channel, + uint8_t **buffer, + uint32_t *buffer_length); // length in bytes diff --git a/shared-module/audiofilters/__init__.c b/shared-module/audiofilters/__init__.c index 83929b4c4fb..7f23afcc59c 100644 --- a/shared-module/audiofilters/__init__.c +++ b/shared-module/audiofilters/__init__.c @@ -3,3 +3,74 @@ // SPDX-FileCopyrightText: Copyright (c) 2024 Cooper Dalrymple // // SPDX-License-Identifier: MIT + +#include "shared-module/audiofilters/__init__.h" + +void audiofilters_assign_filter_chain(audiofilters_filter_chain_t *self, mp_obj_t filter_in, uint8_t channel_count) { + size_t n_items; + mp_obj_t *items; + + if (filter_in == mp_const_none) { + n_items = 0; + items = NULL; + } else if (mp_obj_is_type(filter_in, &mp_type_tuple)) { + mp_obj_tuple_get(filter_in, &n_items, &items); + for (size_t i = 0; i < n_items; i++) { + if (!mp_obj_is_type(items[i], &synthio_biquad_type_obj)) { + mp_raise_TypeError_varg( + MP_ERROR_TEXT("%q in %q must be of type %q, not %q"), + MP_QSTR_object, + MP_QSTR_filter, + MP_QSTR_Biquad, + mp_obj_get_type(items[i])->name); + } + } + } else { + n_items = 1; + if (!mp_obj_is_type(filter_in, &synthio_biquad_type_obj)) { + mp_raise_TypeError_varg( + MP_ERROR_TEXT("%q must be of type %q or %q, not %q"), + MP_QSTR_filter, MP_QSTR_Biquad, MP_QSTR_tuple, mp_obj_get_type(filter_in)->name); + } + items = &self->obj; + } + + // everything has been checked, so we can do the following without fear + + self->obj = filter_in; + self->states = m_renew(biquad_filter_state, + self->states, + self->objs_len * channel_count, + n_items * channel_count); + self->objs = items; + self->objs_len = n_items; +} + +void audiofilters_reset_filter_chain(audiofilters_filter_chain_t *self, uint8_t channel_count) { + if (self->states) { + for (size_t i = 0; i < self->objs_len * channel_count; i++) { + synthio_biquad_filter_reset(&self->states[i]); + } + } +} + +void audiofilters_tick_filter_chain(audiofilters_filter_chain_t *self) { + for (size_t j = 0; j < self->objs_len; j++) { + common_hal_synthio_biquad_tick(self->objs[j]); + } +} + +int32_t audiofilters_process_filter_chain(audiofilters_filter_chain_t *self, uint8_t channel_count, uint8_t channel, int32_t word) { + // Process biquad filters + for (size_t j = 0; j < self->objs_len; j++) { + word = synthio_biquad_filter_sample(self->objs[j], &self->states[j * channel_count + channel], word); + } + return word; +} + +void audiofilters_deinit_filter_chain(audiofilters_filter_chain_t *self) { + self->obj = mp_const_none; + self->objs = NULL; + self->objs_len = 0; + self->states = NULL; +} diff --git a/shared-module/audiofilters/__init__.h b/shared-module/audiofilters/__init__.h index 29d2f672655..2a5a933d96f 100644 --- a/shared-module/audiofilters/__init__.h +++ b/shared-module/audiofilters/__init__.h @@ -5,3 +5,19 @@ // SPDX-License-Identifier: MIT #pragma once + +#include "py/obj.h" +#include "shared-module/synthio/Biquad.h" + +typedef struct audiofilters_filter_chain { + mp_obj_t obj; + mp_obj_t *objs; + size_t objs_len; + biquad_filter_state *states; +} audiofilters_filter_chain_t; + +void audiofilters_assign_filter_chain(audiofilters_filter_chain_t *filter_chain, mp_obj_t filter_in, uint8_t channel_count); +void audiofilters_reset_filter_chain(audiofilters_filter_chain_t *filter_chain, uint8_t channel_count); +void audiofilters_tick_filter_chain(audiofilters_filter_chain_t *filter_chain); +int32_t audiofilters_process_filter_chain(audiofilters_filter_chain_t *filter_chain, uint8_t channel_count, uint8_t channel, int32_t word); +void audiofilters_deinit_filter_chain(audiofilters_filter_chain_t *self); diff --git a/shared-module/audiofreeverb/Freeverb.c b/shared-module/audiofreeverb/Freeverb.c new file mode 100644 index 00000000000..0da6a893c46 --- /dev/null +++ b/shared-module/audiofreeverb/Freeverb.c @@ -0,0 +1,378 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Mark Komus +// +// SPDX-License-Identifier: MIT +// +// Based on FreeVerb - https://github.com/sinshu/freeverb/tree/main +// Fixed point ideas from - Paul Stoffregen in the Teensy audio library https://github.com/PaulStoffregen/Audio/blob/master/effect_freeverb.cpp +// +#include "shared-bindings/audiofreeverb/Freeverb.h" +#include "shared-bindings/audiocore/__init__.h" +#include "shared-module/synthio/__init__.h" + +#include +#include "py/runtime.h" +#include + +void common_hal_audiofreeverb_freeverb_construct(audiofreeverb_freeverb_obj_t *self, mp_obj_t roomsize, mp_obj_t damp, mp_obj_t pre_filter, mp_obj_t post_filter, mp_obj_t mix, + uint32_t buffer_size, uint8_t bits_per_sample, + bool samples_signed, uint8_t channel_count, uint32_t sample_rate) { + + // Basic settings every effect and audio sample has + // These are the effects values, not the source sample(s) + self->base.bits_per_sample = bits_per_sample; // Most common is 16, but 8 is also supported in many places + self->base.samples_signed = samples_signed; // Are the samples we provide signed (common is true) + self->base.channel_count = channel_count; // Channels can be 1 for mono or 2 for stereo + self->base.sample_rate = sample_rate; // Sample rate for the effect, this generally needs to match all audio objects + self->base.single_buffer = false; + self->base.max_buffer_length = buffer_size; + + // To smooth things out as CircuitPython is doing other tasks most audio objects have a buffer + // A double buffer is set up here so the audio output can use DMA on buffer 1 while we + // write to and create buffer 2. + // This buffer is what is passed to the audio component that plays the effect. + // Samples are set sequentially. For stereo audio they are passed L/R/L/R/... + self->buffer_len = buffer_size; // in bytes + + self->buffer[0] = m_malloc_maybe_without_collect(self->buffer_len); + if (self->buffer[0] == NULL) { + common_hal_audiofreeverb_freeverb_deinit(self); + m_malloc_fail(self->buffer_len); + } + memset(self->buffer[0], 0, self->buffer_len); + + self->buffer[1] = m_malloc_maybe_without_collect(self->buffer_len); + if (self->buffer[1] == NULL) { + common_hal_audiofreeverb_freeverb_deinit(self); + m_malloc_fail(self->buffer_len); + } + memset(self->buffer[1], 0, self->buffer_len); + + self->last_buf_idx = 1; // Which buffer to use first, toggle between 0 and 1 + + // Initialize other values most effects will need. + self->sample = NULL; // The current playing sample + self->sample_remaining_buffer = NULL; // Pointer to the start of the sample buffer we have not played + self->sample_buffer_length = 0; // How many samples do we have left to play (these may be 16 bit!) + self->loop = false; // When the sample is done do we loop to the start again or stop (e.g. in a wav file) + self->more_data = false; // Is there still more data to read from the sample or did we finish + + // The below section sets up the reverb effect's starting values. For a different effect this section will change + common_hal_audiofreeverb_freeverb_set_pre_filter(self, pre_filter); + common_hal_audiofreeverb_freeverb_set_post_filter(self, post_filter); + + if (roomsize == MP_OBJ_NULL) { + roomsize = mp_obj_new_float(MICROPY_FLOAT_CONST(0.5)); + } + synthio_block_assign_slot(roomsize, &self->roomsize, MP_QSTR_roomsize); + common_hal_audiofreeverb_freeverb_set_roomsize(self, roomsize); + + if (damp == MP_OBJ_NULL) { + damp = mp_obj_new_float(MICROPY_FLOAT_CONST(0.5)); + } + synthio_block_assign_slot(damp, &self->damp, MP_QSTR_damp); + common_hal_audiofreeverb_freeverb_set_damp(self, damp); + + if (mix == MP_OBJ_NULL) { + mix = mp_obj_new_float(MICROPY_FLOAT_CONST(0.5)); + } + synthio_block_assign_slot(mix, &self->mix, MP_QSTR_mix); + common_hal_audiofreeverb_freeverb_set_mix(self, mix); + + // Set up the comb filters + // These values come from FreeVerb and are selected for the best reverb sound + self->combbuffersizes[0] = self->combbuffersizes[8] = 1116; + self->combbuffersizes[1] = self->combbuffersizes[9] = 1188; + self->combbuffersizes[2] = self->combbuffersizes[10] = 1277; + self->combbuffersizes[3] = self->combbuffersizes[11] = 1356; + self->combbuffersizes[4] = self->combbuffersizes[12] = 1422; + self->combbuffersizes[5] = self->combbuffersizes[13] = 1491; + self->combbuffersizes[6] = self->combbuffersizes[14] = 1557; + self->combbuffersizes[7] = self->combbuffersizes[15] = 1617; + for (uint32_t i = 0; i < 8 * channel_count; i++) { + self->combbuffers[i] = m_malloc_maybe_without_collect(self->combbuffersizes[i] * sizeof(uint16_t)); + if (self->combbuffers[i] == NULL) { + common_hal_audiofreeverb_freeverb_deinit(self); + m_malloc_fail(self->combbuffersizes[i]); + } + memset(self->combbuffers[i], 0, self->combbuffersizes[i] * sizeof(uint16_t)); + + self->combbufferindex[i] = 0; + self->combfitlers[i] = 0; + } + + // Set up the allpass filters + // These values come from FreeVerb and are selected for the best reverb sound + self->allpassbuffersizes[0] = self->allpassbuffersizes[4] = 556; + self->allpassbuffersizes[1] = self->allpassbuffersizes[5] = 441; + self->allpassbuffersizes[2] = self->allpassbuffersizes[6] = 341; + self->allpassbuffersizes[3] = self->allpassbuffersizes[7] = 225; + for (uint32_t i = 0; i < 4 * channel_count; i++) { + self->allpassbuffers[i] = m_malloc_maybe_without_collect(self->allpassbuffersizes[i] * sizeof(uint16_t)); + if (self->allpassbuffers[i] == NULL) { + common_hal_audiofreeverb_freeverb_deinit(self); + m_malloc_fail(self->allpassbuffersizes[i]); + } + memset(self->allpassbuffers[i], 0, self->allpassbuffersizes[i] * sizeof(uint16_t)); + + self->allpassbufferindex[i] = 0; + } +} + +bool common_hal_audiofreeverb_freeverb_deinited(audiofreeverb_freeverb_obj_t *self) { + if (self->buffer[0] == NULL) { + return true; + } + return false; +} + +void common_hal_audiofreeverb_freeverb_deinit(audiofreeverb_freeverb_obj_t *self) { + audiosample_mark_deinit(&self->base); + audiofilters_deinit_filter_chain(&self->pre_filter); + audiofilters_deinit_filter_chain(&self->post_filter); + self->buffer[0] = NULL; + self->buffer[1] = NULL; +} + +mp_obj_t common_hal_audiofreeverb_freeverb_get_roomsize(audiofreeverb_freeverb_obj_t *self) { + return self->roomsize.obj; +} + +void common_hal_audiofreeverb_freeverb_set_roomsize(audiofreeverb_freeverb_obj_t *self, mp_obj_t roomsize_obj) { + synthio_block_assign_slot(roomsize_obj, &self->roomsize, MP_QSTR_roomsize); +} + +int16_t audiofreeverb_freeverb_get_roomsize_fixedpoint(mp_float_t n) { + if (n > (mp_float_t)MICROPY_FLOAT_CONST(1.0)) { + n = MICROPY_FLOAT_CONST(1.0); + } else if (n < (mp_float_t)MICROPY_FLOAT_CONST(0.0)) { + n = MICROPY_FLOAT_CONST(0.0); + } + + return (int16_t)(n * (mp_float_t)MICROPY_FLOAT_CONST(9175.04)) + 22937; // 9175.04 = 0.28f in fixed point 22937 = 0.7f +} + +mp_obj_t common_hal_audiofreeverb_freeverb_get_damp(audiofreeverb_freeverb_obj_t *self) { + return self->damp.obj; +} + +void common_hal_audiofreeverb_freeverb_set_damp(audiofreeverb_freeverb_obj_t *self, mp_obj_t damp) { + synthio_block_assign_slot(damp, &self->damp, MP_QSTR_damp); +} + +void audiofreeverb_freeverb_get_damp_fixedpoint(mp_float_t n, int16_t *damp1, int16_t *damp2) { + if (n > (mp_float_t)MICROPY_FLOAT_CONST(1.0)) { + n = MICROPY_FLOAT_CONST(1.0); + } else if (n < (mp_float_t)MICROPY_FLOAT_CONST(0.0)) { + n = MICROPY_FLOAT_CONST(0.0); + } + + *damp1 = (int16_t)(n * (mp_float_t)MICROPY_FLOAT_CONST(13107.2)); // 13107.2 = 0.4f scaling factor + *damp2 = (int16_t)(32768 - *damp1); // inverse of x1 damp2 = 1.0 - damp1 +} + +mp_obj_t common_hal_audiofreeverb_freeverb_get_pre_filter(audiofreeverb_freeverb_obj_t *self) { + return self->pre_filter.obj; +} + +void common_hal_audiofreeverb_freeverb_set_pre_filter(audiofreeverb_freeverb_obj_t *self, mp_obj_t filter_in) { + audiofilters_assign_filter_chain(&self->pre_filter, filter_in, self->base.channel_count); +} + +mp_obj_t common_hal_audiofreeverb_freeverb_get_post_filter(audiofreeverb_freeverb_obj_t *self) { + return self->post_filter.obj; +} + +void common_hal_audiofreeverb_freeverb_set_post_filter(audiofreeverb_freeverb_obj_t *self, mp_obj_t filter_in) { + audiofilters_assign_filter_chain(&self->post_filter, filter_in, self->base.channel_count); +} + +mp_obj_t common_hal_audiofreeverb_freeverb_get_mix(audiofreeverb_freeverb_obj_t *self) { + return self->mix.obj; +} + +void common_hal_audiofreeverb_freeverb_set_mix(audiofreeverb_freeverb_obj_t *self, mp_obj_t mix) { + synthio_block_assign_slot(mix, &self->mix, MP_QSTR_mix); +} + +void audiofreeverb_freeverb_get_mix_fixedpoint(mp_float_t mix, int16_t *mix_sample, int16_t *mix_effect) { + mix = mix * (mp_float_t)MICROPY_FLOAT_CONST(2.0); + *mix_sample = (int16_t)(MIN((mp_float_t)MICROPY_FLOAT_CONST(2.0) - mix, (mp_float_t)MICROPY_FLOAT_CONST(1.0)) * 32767); + *mix_effect = (int16_t)(MIN(mix, (mp_float_t)MICROPY_FLOAT_CONST(1.0)) * 32767); +} + +void audiofreeverb_freeverb_reset_buffer(audiofreeverb_freeverb_obj_t *self, + bool single_channel_output, + uint8_t channel) { + + memset(self->buffer[0], 0, self->buffer_len); + memset(self->buffer[1], 0, self->buffer_len); + + audiofilters_reset_filter_chain(&self->pre_filter, self->base.channel_count); + audiofilters_reset_filter_chain(&self->post_filter, self->base.channel_count); +} + +bool common_hal_audiofreeverb_freeverb_get_playing(audiofreeverb_freeverb_obj_t *self) { + return self->sample != NULL; +} + +void common_hal_audiofreeverb_freeverb_play(audiofreeverb_freeverb_obj_t *self, mp_obj_t sample, bool loop) { + audiosample_must_match(&self->base, sample, false); + + self->sample = sample; + self->loop = loop; + + audiosample_reset_buffer(self->sample, false, 0); + audioio_get_buffer_result_t result = audiosample_get_buffer(self->sample, false, 0, (uint8_t **)&self->sample_remaining_buffer, &self->sample_buffer_length); + + // Track remaining sample length in terms of bytes per sample + self->sample_buffer_length /= (self->base.bits_per_sample / 8); + // Store if we have more data in the sample to retrieve + self->more_data = result == GET_BUFFER_MORE_DATA; + + return; +} + +void common_hal_audiofreeverb_freeverb_stop(audiofreeverb_freeverb_obj_t *self) { + // When the sample is set to stop playing do any cleanup here + // For reverb we clear the sample but the reverb continues until the object reading our effect stops + self->sample = NULL; + return; +} + +audioio_get_buffer_result_t audiofreeverb_freeverb_get_buffer(audiofreeverb_freeverb_obj_t *self, bool single_channel_output, uint8_t channel, + uint8_t **buffer, uint32_t *buffer_length) { + + // Switch our buffers to the other buffer + self->last_buf_idx = !self->last_buf_idx; + + // 16 bit samples we need a 16 bit pointer + int16_t *word_buffer = (int16_t *)self->buffer[self->last_buf_idx]; + uint32_t length = self->buffer_len / (self->base.bits_per_sample / 8); + + // Loop over the entire length of our buffer to fill it, this may require several calls to get data from the sample + while (length != 0) { + // Check if there is no more sample to play, we will either load more data, reset the sample if loop is on or clear the sample + if (self->sample_buffer_length == 0) { + if (!self->more_data) { // The sample has indicated it has no more data to play + if (self->loop && self->sample) { // If we are supposed to loop reset the sample to the start + audiosample_reset_buffer(self->sample, false, 0); + } else { // If we were not supposed to loop the sample, stop playing it but we still need to play the reverb + self->sample = NULL; + } + } + if (self->sample) { + // Load another sample buffer to play + audioio_get_buffer_result_t result = audiosample_get_buffer(self->sample, false, 0, (uint8_t **)&self->sample_remaining_buffer, &self->sample_buffer_length); + if (result == GET_BUFFER_ERROR) { + self->sample = NULL; + self->sample_buffer_length = 0; + self->more_data = false; + } else { + // Track length in terms of words. + self->sample_buffer_length /= (self->base.bits_per_sample / 8); + self->more_data = result == GET_BUFFER_MORE_DATA; + } + } + } + + // Determine how many bytes we can process to our buffer, the less of the sample we have left and our buffer remaining + uint32_t n; + if (self->sample == NULL) { + n = MIN(length, SYNTHIO_MAX_DUR * self->base.channel_count); + } else { + n = MIN(MIN(self->sample_buffer_length, length), SYNTHIO_MAX_DUR * self->base.channel_count); + } + + // get the effect values we need from the BlockInput. These may change at run time so you need to do bounds checking if required + shared_bindings_synthio_lfo_tick(self->base.sample_rate, n / self->base.channel_count); + mp_float_t damp = synthio_block_slot_get_limited(&self->damp, MICROPY_FLOAT_CONST(0.0), MICROPY_FLOAT_CONST(1.0)); + int16_t damp1, damp2; + audiofreeverb_freeverb_get_damp_fixedpoint(damp, &damp1, &damp2); + + mp_float_t mix = synthio_block_slot_get_limited(&self->mix, MICROPY_FLOAT_CONST(0.0), MICROPY_FLOAT_CONST(1.0)); + int16_t mix_sample, mix_effect; + audiofreeverb_freeverb_get_mix_fixedpoint(mix, &mix_sample, &mix_effect); + + mp_float_t roomsize = synthio_block_slot_get_limited(&self->roomsize, MICROPY_FLOAT_CONST(0.0), MICROPY_FLOAT_CONST(1.0)); + int16_t feedback = audiofreeverb_freeverb_get_roomsize_fixedpoint(roomsize); + + // Tick biquad filters + audiofilters_tick_filter_chain(&self->pre_filter); + audiofilters_tick_filter_chain(&self->post_filter); + + int16_t *sample_src = (int16_t *)self->sample_remaining_buffer; + + uint32_t channel_comb_offset = 0, channel_allpass_offset = 0; + + for (uint32_t i = 0; i < n; i++) { + int32_t sample_word = 0; + if (self->sample != NULL) { + sample_word = sample_src[i]; + } + + int32_t word, sum; + int16_t input, bufout, output; + + // Apply filters as Pre-EQ + input = (int16_t)audiofilters_process_filter_chain(&self->pre_filter, self->base.channel_count, n % self->base.channel_count, sample_word); + + input = synthio_sat16((int32_t)input * 8738, 17); // Initial input scaled down so we can add reverb + sum = 0; + + // Calculate each of the 8 comb buffers + for (uint32_t j = 0 + channel_comb_offset; j < 8 + channel_comb_offset; j++) { + bufout = self->combbuffers[j][self->combbufferindex[j]]; + sum += bufout; + self->combfitlers[j] = synthio_sat16(bufout * damp2 + self->combfitlers[j] * damp1, 15); + self->combbuffers[j][self->combbufferindex[j]] = synthio_sat16(input + synthio_sat16(self->combfitlers[j] * feedback, 15), 0); + if (++self->combbufferindex[j] >= self->combbuffersizes[j]) { + self->combbufferindex[j] = 0; + } + } + + output = synthio_sat16(sum * 31457, 17); // 31457 = 0.24f with shift of 17 + + // Calculate each of the 4 all pass buffers + for (uint32_t j = 0 + channel_allpass_offset; j < 4 + channel_allpass_offset; j++) { + bufout = self->allpassbuffers[j][self->allpassbufferindex[j]]; + self->allpassbuffers[j][self->allpassbufferindex[j]] = output + (bufout >> 1); // bufout >> 1 same as bufout*0.5f + output = synthio_sat16(bufout - output, 1); + if (++self->allpassbufferindex[j] >= self->allpassbuffersizes[j]) { + self->allpassbufferindex[j] = 0; + } + } + + // Apply filters as Post-EQ + output = (int16_t)audiofilters_process_filter_chain(&self->post_filter, self->base.channel_count, n % self->base.channel_count, (int32_t)output); + + word = output * 30; // Add some volume back don't have to saturate as next step will + + word = synthio_sat16(sample_word * mix_sample, 15) + synthio_sat16(word * mix_effect, 15); + word = synthio_mix_down_sample(word, SYNTHIO_MIX_DOWN_SCALE(2)); + word_buffer[i] = (int16_t)word; + + if ((self->base.channel_count == 2) && (channel_comb_offset == 0)) { + channel_comb_offset = 8; + channel_allpass_offset = 4; + } else { + channel_comb_offset = 0; + channel_allpass_offset = 0; + } + } + + // Update the remaining length and the buffer positions based on how much we wrote into our buffer + length -= n; + word_buffer += n; + self->sample_remaining_buffer += (n * (self->base.bits_per_sample / 8)); + self->sample_buffer_length -= n; + } + + // Finally pass our buffer and length to the calling audio function + *buffer = (uint8_t *)self->buffer[self->last_buf_idx]; + *buffer_length = self->buffer_len; + + // Reverb always returns more data but some effects may return GET_BUFFER_DONE or GET_BUFFER_ERROR (see audiocore/__init__.h) + return GET_BUFFER_MORE_DATA; +} diff --git a/shared-module/audiofreeverb/Freeverb.h b/shared-module/audiofreeverb/Freeverb.h new file mode 100644 index 00000000000..1a60a64d39e --- /dev/null +++ b/shared-module/audiofreeverb/Freeverb.h @@ -0,0 +1,60 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Mark Komus +// +// SPDX-License-Identifier: MIT +#pragma once + +#include "py/obj.h" + +#include "shared-module/audiocore/__init__.h" +#include "shared-module/audiofilters/__init__.h" +#include "shared-module/synthio/__init__.h" +#include "shared-module/synthio/block.h" +#include "shared-module/synthio/Biquad.h" + +extern const mp_obj_type_t audiofreeverb_freeverb_type; + +typedef struct { + audiosample_base_t base; + synthio_block_slot_t roomsize; + synthio_block_slot_t damp; + audiofilters_filter_chain_t pre_filter; + audiofilters_filter_chain_t post_filter; + synthio_block_slot_t mix; + + int8_t *buffer[2]; + uint8_t last_buf_idx; + uint32_t buffer_len; // max buffer in bytes + + uint8_t *sample_remaining_buffer; + uint32_t sample_buffer_length; + + bool loop; + bool more_data; + + int16_t combbuffersizes[16]; + int16_t *combbuffers[16]; + int16_t combbufferindex[16]; + int16_t combfitlers[16]; + + int16_t allpassbuffersizes[8]; + int16_t *allpassbuffers[8]; + int16_t allpassbufferindex[8]; + + mp_obj_t sample; +} audiofreeverb_freeverb_obj_t; + +void audiofreeverb_freeverb_reset_buffer(audiofreeverb_freeverb_obj_t *self, + bool single_channel_output, + uint8_t channel); + +audioio_get_buffer_result_t audiofreeverb_freeverb_get_buffer(audiofreeverb_freeverb_obj_t *self, + bool single_channel_output, + uint8_t channel, + uint8_t **buffer, + uint32_t *buffer_length); // length in bytes + +int16_t audiofreeverb_freeverb_get_roomsize_fixedpoint(mp_float_t n); +void audiofreeverb_freeverb_get_damp_fixedpoint(mp_float_t n, int16_t *damp1, int16_t *damp2); +void audiofreeverb_freeverb_get_mix_fixedpoint(mp_float_t mix, int16_t *mix_sample, int16_t *mix_effect); diff --git a/shared-module/audiofreeverb/__init__.c b/shared-module/audiofreeverb/__init__.c new file mode 100644 index 00000000000..94cd4caa3bd --- /dev/null +++ b/shared-module/audiofreeverb/__init__.c @@ -0,0 +1,5 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Mark Komus +// +// SPDX-License-Identifier: MIT diff --git a/shared-module/audiofreeverb/__init__.h b/shared-module/audiofreeverb/__init__.h new file mode 100644 index 00000000000..66463561f54 --- /dev/null +++ b/shared-module/audiofreeverb/__init__.h @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Mark Komus +// +// SPDX-License-Identifier: MIT + +#pragma once diff --git a/shared-module/audioi2sin/__init__.h b/shared-module/audioi2sin/__init__.h new file mode 100644 index 00000000000..852616ee3a7 --- /dev/null +++ b/shared-module/audioi2sin/__init__.h @@ -0,0 +1,71 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include + +// Rescale an already-normalized signed sample and write it to `buffer` at sample +// index `idx`. `s` is the sign-extended int32 value of the sample at `in_depth` +// scale (the per-port `i2sin_normalize_signed` produces it from the raw FIFO +// word, handling wire-format details like left-justification). This helper does +// the depth conversion + unsigned-WAV flip + container store, which is identical +// across ports. +// +// This path runs only when the caller set `output_bit_depth`, i.e. asked for a +// real bit-depth rescale: upscaling bit-replicates so full-scale input maps to +// full-scale output (e.g. 16-bit 0xFFFF -> 24-bit 0xFFFFFF) and downscaling +// arithmetic-shifts right. This is distinct from the implicit container width +// set by the array typecode (e.g. a 24-bit sample carried in a 32-bit 'i' slot), +// which only sign-extends and is handled by the default (non-converting) path. +// Output element size follows `out_depth`: 1 byte at 8, 2 bytes at 16, 4 bytes +// at 24 or 32. +static inline void shared_audioi2sin_write_converted(void *buffer, uint32_t idx, + int32_t s, uint8_t in_depth, uint8_t out_depth, bool samples_signed) { + int32_t shifted; + if (out_depth > in_depth) { + // Explicit upscale: left-justify the in_depth-bit sample at the top of a + // 32-bit word and replicate the pattern downward so full-scale input + // maps to full-scale output (e.g. 16-bit 0xFFFF -> 24-bit 0xFFFFFF). Two + // steps cover every supported ratio (widest is 8 -> 32); the guard skips + // the second step (and the resulting shift-by->=32 UB) when one suffices. + uint32_t top = (uint32_t)s << (32 - in_depth); + top |= top >> in_depth; + if (in_depth * 2 < out_depth) { + top |= top >> (in_depth * 2); + } + // Arithmetic-shift the high out_depth bits down, sign-extending to int32 + // so a 24-bit value in a 32-bit slot decodes correctly (no-op at 32). + shifted = (int32_t)top >> (32 - out_depth); + } else if (out_depth == in_depth) { + shifted = s; + } else { + shifted = s >> (in_depth - out_depth); + } + uint32_t u = (uint32_t)shifted; + if (!samples_signed) { + // I2S delivers signed PCM; flip the sign bit to match the WAV unsigned + // convention, at the output bit width. + if (out_depth >= 32) { + u ^= 0x80000000u; + } else { + uint32_t mask = (1u << out_depth) - 1u; + u = (u & mask) ^ (1u << (out_depth - 1)); + } + } + switch (out_depth) { + case 8: + ((uint8_t *)buffer)[idx] = (uint8_t)(u & 0xffu); + break; + case 16: + ((uint16_t *)buffer)[idx] = (uint16_t)(u & 0xffffu); + break; + default: // 24 or 32 + ((uint32_t *)buffer)[idx] = u; + break; + } +} diff --git a/shared-module/audiomixer/Mixer.c b/shared-module/audiomixer/Mixer.c index 775ab41d42f..4f5ed98c261 100644 --- a/shared-module/audiomixer/Mixer.c +++ b/shared-module/audiomixer/Mixer.c @@ -26,13 +26,13 @@ void common_hal_audiomixer_mixer_construct(audiomixer_mixer_obj_t *self, uint32_t sample_rate) { self->len = buffer_size / 2 / sizeof(uint32_t) * sizeof(uint32_t); - self->first_buffer = m_malloc(self->len); + self->first_buffer = m_malloc_without_collect(self->len); if (self->first_buffer == NULL) { common_hal_audiomixer_mixer_deinit(self); m_malloc_fail(self->len); } - self->second_buffer = m_malloc(self->len); + self->second_buffer = m_malloc_without_collect(self->len); if (self->second_buffer == NULL) { common_hal_audiomixer_mixer_deinit(self); m_malloc_fail(self->len); @@ -66,13 +66,13 @@ void audiomixer_mixer_reset_buffer(audiomixer_mixer_obj_t *self, bool single_channel_output, uint8_t channel) { for (uint8_t i = 0; i < self->voice_count; i++) { - common_hal_audiomixer_mixervoice_stop(self->voice[i]); + common_hal_audiomixer_mixervoice_reset_buffer(self->voice[i]); } } __attribute__((always_inline)) static inline uint32_t add16signed(uint32_t a, uint32_t b) { - #if (defined(__ARM_ARCH_7EM__) && (__ARM_ARCH_7EM__ == 1)) + #if defined(__ARM_FEATURE_DSP) && __ARM_FEATURE_DSP return __QADD16(a, b); #else uint32_t result = 0; @@ -92,24 +92,25 @@ static inline uint32_t add16signed(uint32_t a, uint32_t b) { } __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; +static inline uint32_t mult16signed(uint32_t val, int32_t lomul, int32_t himul) { + #if defined(__ARM_FEATURE_DSP) && __ARM_FEATURE_DSP + // A level of 1.0 is 1 << 15, so shifting by 16 would overflow into the sign bit. + lomul <<= 15; + himul <<= 15; 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 + enum { shift = 14 }; // smulw shifts by 16, so 14 more gives (val * mul) >> 15 + __asm__ volatile ("smulwb %0, %1, %2" : "=r" (lo) : "r" (lomul), "r" (val)); + __asm__ volatile ("smulwt %0, %1, %2" : "=r" (hi) : "r" (himul), "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 = (int32_t)(ai * mod_mul); + int32_t intermediate = (ai * (i ? himul : lomul)) >> 15; if (intermediate > SHRT_MAX) { intermediate = SHRT_MAX; } else if (intermediate < SHRT_MIN) { @@ -123,7 +124,7 @@ static inline uint32_t mult16signed(uint32_t val, int32_t mul) { } static inline uint32_t tounsigned8(uint32_t val) { - #if (defined(__ARM_ARCH_7EM__) && (__ARM_ARCH_7EM__ == 1)) + #if defined(__ARM_FEATURE_DSP) && __ARM_FEATURE_DSP return __UADD8(val, 0x80808080); #else return val ^ 0x80808080; @@ -131,7 +132,7 @@ static inline uint32_t tounsigned8(uint32_t val) { } static inline uint32_t tounsigned16(uint32_t val) { - #if (defined(__ARM_ARCH_7EM__) && (__ARM_ARCH_7EM__ == 1)) + #if defined(__ARM_FEATURE_DSP) && __ARM_FEATURE_DSP return __UADD16(val, 0x80008000); #else return val ^ 0x80008000; @@ -139,7 +140,7 @@ static inline uint32_t tounsigned16(uint32_t val) { } static inline uint32_t tosigned16(uint32_t val) { - #if (defined(__ARM_ARCH_7EM__) && (__ARM_ARCH_7EM__ == 1)) + #if defined(__ARM_FEATURE_DSP) && __ARM_FEATURE_DSP return __UADD16(val, 0x80008000); #else return val ^ 0x80008000; @@ -154,9 +155,73 @@ static inline uint32_t pack8(uint32_t val) { return ((val & 0xff000000) >> 16) | ((val & 0xff00) >> 8); } +static inline uint32_t copy16lsb(uint32_t val) { + #if defined(__ARM_FEATURE_DSP) && __ARM_FEATURE_DSP + return __PKHBT(val, val, 16); + #else + val &= 0x0000ffff; + return val | (val << 16); + #endif +} + +static inline uint32_t copy16msb(uint32_t val) { + #if defined(__ARM_FEATURE_DSP) && __ARM_FEATURE_DSP + return __PKHTB(val, val, 16); + #else + val &= 0xffff0000; + return val | (val >> 16); + #endif +} + +#if CIRCUITPY_AUDIOMIXER_USE_PORT_MIX +// Mix with the port's vector code once the active levels equal the pending levels, so +// assignmul() has nothing left to do. Returns how many words, starting at index 0, it +// handled; the caller does the rest. +static uint32_t mix_with_port(uint32_t *dst, const uint32_t *src, uint32_t n, + int32_t lomul, int32_t himul, bool accumulate) { + // The port needs dst aligned to 16 bytes. + uint32_t i = 0; + for (; i < n && ((uintptr_t)(dst + i) & 15) != 0; i++) { + uint32_t word = mult16signed(src[i], lomul, himul); + dst[i] = accumulate ? add16signed(word, dst[i]) : word; + } + return i + audiomixer_port_mix_signed_16_bit(dst + i, src + i, n - i, lomul, himul, accumulate); +} +#endif + +// Rather than immediately changing the loudness of audio playback, we keep a separate buffer of +// the "active" loudness and wait until we meet the conditions of a "zero crossing". A zero crossing +// occurs when either the current value is 0 or the value changes from negative to positive or +// vice-versa. This is detected by keeping a copy of the previous frame of audio data and checking +// to see if the sign of the value has changed. By only changing loudness during zero crossings, we +// avoid audible pops/clicks which can be unpleasant. +static void assignmul(uint32_t word, uint32_t *last_word, int32_t *active_lomul, int32_t *active_himul, int32_t pending_lomul, int32_t pending_himul) { + // If the active loudness already matches the pending loudness, exit early. + if (MP_LIKELY(*active_lomul == pending_lomul) && MP_LIKELY(*active_himul == pending_himul)) { + return; + } + + // Check for a zero crossing: current value is 0 or has changed sign from the previous value. + // We check for the sign change by bitmasking only the top bits of each 16-bit signed value + // packed into the 32-bit word (two's complement). If either bit doesn't match the previous + // value, a sign change has occurred on either the left or right channel. + if ((word & 0xffff0000) == 0 || (word & 0x0000ffff) == 0 || (*last_word != 0 && ((*last_word) & 0x80008000) != (word & 0x80008000))) { + // Copy over our pending loudness. Will cause future calls to `assignmul` to exit early. + *active_lomul = pending_lomul; + *active_himul = pending_himul; + } else { + // Update our copy of the previous word for future comparisons (an initial value of 0 is + // ignored). + *last_word = word; + } +} + +#define ALMOST_ONE (MICROPY_FLOAT_CONST(32767.) / 32768) + 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) { + audiosample_base_t *sample = MP_OBJ_TO_PTR(voice->sample); while (length != 0) { if (voice->buffer_length == 0) { if (!voice->more_data) { @@ -170,6 +235,12 @@ 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); + if (result == GET_BUFFER_ERROR) { + voice->sample = NULL; + voice->buffer_length = 0; + voice->more_data = false; + break; + } // Track length in terms of words. voice->buffer_length /= sizeof(uint32_t); voice->more_data = result == GET_BUFFER_MORE_DATA; @@ -179,75 +250,222 @@ static void mix_down_one_voice(audiomixer_mixer_obj_t *self, uint32_t *src = voice->remaining_buffer; #if CIRCUITPY_SYNTHIO - uint32_t n = MIN(MIN(voice->buffer_length, length), SYNTHIO_MAX_DUR * self->base.channel_count); + uint32_t n; + if (MP_LIKELY(self->base.channel_count == sample->channel_count)) { + n = MIN(MIN(voice->buffer_length, length), SYNTHIO_MAX_DUR * self->base.channel_count); + } else { + n = MIN(MIN(voice->buffer_length << 1, length), SYNTHIO_MAX_DUR * self->base.channel_count); + } // Get the current level from the BlockInput. These may change at run time so you need to do bounds checking if required. shared_bindings_synthio_lfo_tick(self->base.sample_rate, n / self->base.channel_count); uint16_t level = (uint16_t)(synthio_block_slot_get_limited(&voice->level, MICROPY_FLOAT_CONST(0.0), MICROPY_FLOAT_CONST(1.0)) * (1 << 15)); + int16_t panning = synthio_block_slot_get_scaled(&voice->panning, -ALMOST_ONE, ALMOST_ONE); #else - uint32_t n = MIN(voice->buffer_length, length); + uint32_t n; + if (MP_LIKELY(self->base.channel_count == sample->channel_count)) { + n = MIN(voice->buffer_length, length); + } else { + n = MIN(voice->buffer_length << 1, length); + } uint16_t level = voice->level; + int16_t panning = voice->panning; #endif + uint16_t left_panning_scaled = 32768, right_panning_scaled = 32768; + if (MP_LIKELY(self->base.channel_count == 2)) { + if (panning >= 0) { + left_panning_scaled = 32768 - panning; + } else { + right_panning_scaled = 32768 + panning; + } + } + + int32_t pending_lo_level = level; + int32_t pending_hi_level = level; + if (MP_LIKELY(self->base.channel_count == 2)) { + pending_lo_level = (left_panning_scaled * pending_lo_level) >> 15; + pending_hi_level = (right_panning_scaled * pending_hi_level) >> 15; + } + + if (voice->snap_to_level) { + voice->active_lo_level = pending_lo_level; + voice->active_hi_level = pending_hi_level; + voice->snap_to_level = false; + } + + int32_t active_lo_level = voice->active_lo_level; + int32_t active_hi_level = voice->active_hi_level; + uint32_t last_word = 0; + // First active voice gets copied over verbatim. if (!voices_active) { if (MP_LIKELY(self->base.bits_per_sample == 16)) { if (MP_LIKELY(self->base.samples_signed)) { - for (uint32_t i = 0; i < n; i++) { - uint32_t v = src[i]; - word_buffer[i] = mult16signed(v, level); + if (MP_LIKELY(self->base.channel_count == sample->channel_count)) { + uint32_t i = 0; + #if CIRCUITPY_AUDIOMIXER_USE_PORT_MIX + if (active_lo_level == pending_lo_level && active_hi_level == pending_hi_level) { + i = mix_with_port(word_buffer, src, n, active_lo_level, active_hi_level, false); + } + #endif + for (; i < n; i++) { + uint32_t word = src[i]; + assignmul(word, &last_word, &active_lo_level, &active_hi_level, pending_lo_level, pending_hi_level); + word_buffer[i] = mult16signed(word, active_lo_level, active_hi_level); + } + } else { + for (uint32_t i = 0; i + 1 < n; i += 2) { + uint32_t word = src[i >> 1]; + uint32_t word_lsb = copy16lsb(word); + assignmul(word_lsb, &last_word, &active_lo_level, &active_hi_level, pending_lo_level, pending_hi_level); + word_buffer[i] = mult16signed(word_lsb, active_lo_level, active_hi_level); + word = copy16msb(word); + assignmul(word, &last_word, &active_lo_level, &active_hi_level, pending_lo_level, pending_hi_level); + word_buffer[i + 1] = mult16signed(word, active_lo_level, active_hi_level); + } } } else { - for (uint32_t i = 0; i < n; i++) { - uint32_t v = src[i]; - v = tosigned16(v); - word_buffer[i] = mult16signed(v, level); + if (MP_LIKELY(self->base.channel_count == sample->channel_count)) { + for (uint32_t i = 0; i < n; i++) { + uint32_t word = src[i]; + word = tosigned16(word); + assignmul(word, &last_word, &active_lo_level, &active_hi_level, pending_lo_level, pending_hi_level); + word_buffer[i] = mult16signed(word, active_lo_level, active_hi_level); + } + } else { + for (uint32_t i = 0; i + 1 < n; i += 2) { + uint32_t word = src[i >> 1]; + word = tosigned16(word); + uint32_t word_lsb = copy16lsb(word); + assignmul(word_lsb, &last_word, &active_lo_level, &active_hi_level, pending_lo_level, pending_hi_level); + word_buffer[i] = mult16signed(word_lsb, active_lo_level, active_hi_level); + word = copy16msb(word); + assignmul(word, &last_word, &active_lo_level, &active_hi_level, pending_lo_level, pending_hi_level); + word_buffer[i + 1] = mult16signed(word, active_lo_level, active_hi_level); + } } } } else { uint16_t *hword_buffer = (uint16_t *)word_buffer; uint16_t *hsrc = (uint16_t *)src; - for (uint32_t i = 0; i < n * 2; i++) { - uint32_t word = unpack8(hsrc[i]); - if (MP_LIKELY(!self->base.samples_signed)) { - word = tosigned16(word); + if (MP_LIKELY(self->base.channel_count == sample->channel_count)) { + for (uint32_t i = 0; i < n * 2; i++) { + uint32_t word = unpack8(hsrc[i]); + if (MP_LIKELY(!self->base.samples_signed)) { + word = tosigned16(word); + } + assignmul(word, &last_word, &active_lo_level, &active_hi_level, pending_lo_level, pending_hi_level); + word = mult16signed(word, active_lo_level, active_hi_level); + hword_buffer[i] = pack8(word); + } + } else { + for (uint32_t i = 0; i + 1 < n * 2; i += 2) { + uint32_t word = unpack8(hsrc[i >> 1]); + if (MP_LIKELY(!self->base.samples_signed)) { + word = tosigned16(word); + } + uint32_t word_lsb = copy16lsb(word); + assignmul(word_lsb, &last_word, &active_lo_level, &active_hi_level, pending_lo_level, pending_hi_level); + hword_buffer[i] = pack8(mult16signed(word_lsb, active_lo_level, active_hi_level)); + word = copy16msb(word); + assignmul(word, &last_word, &active_lo_level, &active_hi_level, pending_lo_level, pending_hi_level); + hword_buffer[i + 1] = pack8(mult16signed(word, active_lo_level, active_hi_level)); } - word = mult16signed(word, level); - hword_buffer[i] = pack8(word); } } } else { if (MP_LIKELY(self->base.bits_per_sample == 16)) { if (MP_LIKELY(self->base.samples_signed)) { - for (uint32_t i = 0; i < n; i++) { - uint32_t word = src[i]; - word_buffer[i] = add16signed(mult16signed(word, level), word_buffer[i]); + if (MP_LIKELY(self->base.channel_count == sample->channel_count)) { + uint32_t i = 0; + #if CIRCUITPY_AUDIOMIXER_USE_PORT_MIX + if (active_lo_level == pending_lo_level && active_hi_level == pending_hi_level) { + i = mix_with_port(word_buffer, src, n, active_lo_level, active_hi_level, true); + } + #endif + for (; i < n; i++) { + uint32_t word = src[i]; + assignmul(word, &last_word, &active_lo_level, &active_hi_level, pending_lo_level, pending_hi_level); + word_buffer[i] = add16signed(mult16signed(word, active_lo_level, active_hi_level), word_buffer[i]); + } + } else { + for (uint32_t i = 0; i + 1 < n; i += 2) { + uint32_t word = src[i >> 1]; + uint32_t word_lsb = copy16lsb(word); + assignmul(word_lsb, &last_word, &active_lo_level, &active_hi_level, pending_lo_level, pending_hi_level); + word_buffer[i] = add16signed(mult16signed(word_lsb, active_lo_level, active_hi_level), word_buffer[i]); + word = copy16msb(word); + assignmul(word, &last_word, &active_lo_level, &active_hi_level, pending_lo_level, pending_hi_level); + word_buffer[i + 1] = add16signed(mult16signed(word, active_lo_level, active_hi_level), word_buffer[i + 1]); + } } } else { - for (uint32_t i = 0; i < n; i++) { - uint32_t word = src[i]; - word = tosigned16(word); - word_buffer[i] = add16signed(mult16signed(word, level), word_buffer[i]); + if (MP_LIKELY(self->base.channel_count == sample->channel_count)) { + for (uint32_t i = 0; i < n; i++) { + uint32_t word = src[i]; + word = tosigned16(word); + assignmul(word, &last_word, &active_lo_level, &active_hi_level, pending_lo_level, pending_hi_level); + word_buffer[i] = add16signed(mult16signed(word, active_lo_level, active_hi_level), word_buffer[i]); + } + } else { + for (uint32_t i = 0; i + 1 < n; i += 2) { + uint32_t word = src[i >> 1]; + word = tosigned16(word); + uint32_t word_lsb = copy16lsb(word); + assignmul(word_lsb, &last_word, &active_lo_level, &active_hi_level, pending_lo_level, pending_hi_level); + word_buffer[i] = add16signed(mult16signed(word_lsb, active_lo_level, active_hi_level), word_buffer[i]); + word = copy16msb(word); + assignmul(word, &last_word, &active_lo_level, &active_hi_level, pending_lo_level, pending_hi_level); + word_buffer[i + 1] = add16signed(mult16signed(word, active_lo_level, active_hi_level), word_buffer[i + 1]); + } } } } else { uint16_t *hword_buffer = (uint16_t *)word_buffer; uint16_t *hsrc = (uint16_t *)src; - for (uint32_t i = 0; i < n * 2; i++) { - uint32_t word = unpack8(hsrc[i]); - if (MP_LIKELY(!self->base.samples_signed)) { - word = tosigned16(word); + if (MP_LIKELY(self->base.channel_count == sample->channel_count)) { + for (uint32_t i = 0; i < n * 2; i++) { + uint32_t word = unpack8(hsrc[i]); + if (MP_LIKELY(!self->base.samples_signed)) { + word = tosigned16(word); + } + assignmul(word, &last_word, &active_lo_level, &active_hi_level, pending_lo_level, pending_hi_level); + word = mult16signed(word, active_lo_level, active_hi_level); + word = add16signed(word, unpack8(hword_buffer[i])); + hword_buffer[i] = pack8(word); + } + } else { + for (uint32_t i = 0; i + 1 < n * 2; i += 2) { + uint32_t word = unpack8(hsrc[i >> 1]); + if (MP_LIKELY(!self->base.samples_signed)) { + word = tosigned16(word); + } + uint32_t word_lsb = copy16lsb(word); + assignmul(word_lsb, &last_word, &active_lo_level, &active_hi_level, pending_lo_level, pending_hi_level); + hword_buffer[i] = pack8(add16signed(mult16signed(word_lsb, active_lo_level, active_hi_level), unpack8(hword_buffer[i]))); + word = copy16msb(word); + assignmul(word, &last_word, &active_lo_level, &active_hi_level, pending_lo_level, pending_hi_level); + hword_buffer[i + 1] = pack8(add16signed(mult16signed(word, active_lo_level, active_hi_level), unpack8(hword_buffer[i + 1]))); } - word = mult16signed(word, level); - word = add16signed(word, unpack8(hword_buffer[i])); - hword_buffer[i] = pack8(word); } } } length -= n; word_buffer += n; - voice->remaining_buffer += n; - voice->buffer_length -= n; + if (MP_LIKELY(self->base.channel_count == sample->channel_count)) { + voice->remaining_buffer += n; + voice->buffer_length -= n; + } else { + voice->remaining_buffer += n >> 1; + voice->buffer_length -= n >> 1; + } + + // Force the active level to match the pending level in the case that the conditions of a + // zero crossing weren't met within the last `SYNTHIO_MAX_DUR` frames. Will ensure minimal + // delay in level or panning changes at the potential expensive of an audible pop. + voice->active_lo_level = pending_lo_level; + voice->active_hi_level = pending_hi_level; } if (length && !voices_active) { diff --git a/shared-module/audiomixer/Mixer.h b/shared-module/audiomixer/Mixer.h index b793fa12a2d..139b55d91b8 100644 --- a/shared-module/audiomixer/Mixer.h +++ b/shared-module/audiomixer/Mixer.h @@ -37,3 +37,13 @@ audioio_get_buffer_result_t audiomixer_mixer_get_buffer(audiomixer_mixer_obj_t * uint8_t channel, uint8_t **buffer, uint32_t *buffer_length); // length in bytes + +#if CIRCUITPY_AUDIOMIXER_USE_PORT_MIX +// Provided by the port. Scales the signed 16-bit sample pairs in src by lomul and himul +// (0 to 32768, where 32768 is 1.0) and stores them in dst, or adds them to dst with +// saturation when accumulate is true. The results match the scalar mixing code. dst must +// be aligned to 16 bytes. Returns how many words, starting at index 0, it handled, which +// may be 0; the caller mixes the rest. +uint32_t audiomixer_port_mix_signed_16_bit(uint32_t *dst, const uint32_t *src, uint32_t n, + int32_t lomul, int32_t himul, bool accumulate); +#endif diff --git a/shared-module/audiomixer/MixerVoice.c b/shared-module/audiomixer/MixerVoice.c index a63229cf5af..98de562aee5 100644 --- a/shared-module/audiomixer/MixerVoice.c +++ b/shared-module/audiomixer/MixerVoice.c @@ -16,6 +16,7 @@ void common_hal_audiomixer_mixervoice_construct(audiomixer_mixervoice_obj_t *self) { self->sample = NULL; common_hal_audiomixer_mixervoice_set_level(self, mp_obj_new_float(1.0)); + common_hal_audiomixer_mixervoice_set_panning(self, mp_obj_new_float(0.0)); } void common_hal_audiomixer_mixervoice_set_parent(audiomixer_mixervoice_obj_t *self, audiomixer_mixer_obj_t *parent) { @@ -38,6 +39,22 @@ void common_hal_audiomixer_mixervoice_set_level(audiomixer_mixervoice_obj_t *sel #endif } +mp_obj_t common_hal_audiomixer_mixervoice_get_panning(audiomixer_mixervoice_obj_t *self) { + #if CIRCUITPY_SYNTHIO + return self->panning.obj; + #else + return mp_obj_new_float((mp_float_t)self->panning / ((1 << 15) - 1)); + #endif +} + +void common_hal_audiomixer_mixervoice_set_panning(audiomixer_mixervoice_obj_t *self, mp_obj_t arg) { + #if CIRCUITPY_SYNTHIO + synthio_block_assign_slot(arg, &self->panning, MP_QSTR_panning); + #else + self->panning = (int16_t)(mp_arg_validate_obj_float_range(arg, -1, 1, MP_QSTR_panning) * ((1 << 15) - 1)); + #endif +} + bool common_hal_audiomixer_mixervoice_get_loop(audiomixer_mixervoice_obj_t *self) { return self->loop; } @@ -47,17 +64,24 @@ void common_hal_audiomixer_mixervoice_set_loop(audiomixer_mixervoice_obj_t *self } void common_hal_audiomixer_mixervoice_play(audiomixer_mixervoice_obj_t *self, mp_obj_t sample_in, bool loop) { - audiosample_must_match(&self->parent->base, sample_in); + audiosample_must_match(&self->parent->base, sample_in, true); // cast is safe, checked by must_match audiosample_base_t *sample = MP_OBJ_TO_PTR(sample_in); self->sample = sample; 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); - // Track length in terms of words. - self->buffer_length /= sizeof(uint32_t); - self->more_data = result == GET_BUFFER_MORE_DATA; + common_hal_audiomixer_mixervoice_reset_buffer(self); +} + +void common_hal_audiomixer_mixervoice_reset_buffer(audiomixer_mixervoice_obj_t *self) { + if (self->sample != NULL) { + self->snap_to_level = true; + audiosample_reset_buffer(self->sample, false, 0); + audioio_get_buffer_result_t result = audiosample_get_buffer(self->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) { @@ -67,3 +91,9 @@ bool common_hal_audiomixer_mixervoice_get_playing(audiomixer_mixervoice_obj_t *s void common_hal_audiomixer_mixervoice_stop(audiomixer_mixervoice_obj_t *self) { self->sample = NULL; } + +void common_hal_audiomixer_mixervoice_end(audiomixer_mixervoice_obj_t *self) { + if (self->sample != NULL) { + self->loop = false; + } +} diff --git a/shared-module/audiomixer/MixerVoice.h b/shared-module/audiomixer/MixerVoice.h index dd909551545..0c179562552 100644 --- a/shared-module/audiomixer/MixerVoice.h +++ b/shared-module/audiomixer/MixerVoice.h @@ -19,11 +19,17 @@ typedef struct { mp_obj_t sample; bool loop; bool more_data; + // Start at the current level instead of waiting for a zero crossing. + bool snap_to_level; uint32_t *remaining_buffer; uint32_t buffer_length; #if CIRCUITPY_SYNTHIO synthio_block_slot_t level; + synthio_block_slot_t panning; #else uint16_t level; + int16_t panning; #endif + int32_t active_lo_level; + int32_t active_hi_level; } audiomixer_mixervoice_obj_t; diff --git a/shared-module/audiomp3/MP3Decoder.c b/shared-module/audiomp3/MP3Decoder.c index 3710b825216..a23a73291d1 100644 --- a/shared-module/audiomp3/MP3Decoder.c +++ b/shared-module/audiomp3/MP3Decoder.c @@ -115,13 +115,21 @@ static void stream_set_blocking(audiomp3_mp3file_obj_t *self, bool block_ok) { * false otherwise. (The input buffer will be padded to the end with * 0 bytes, which do not interfere with MP3 decoding) * - * Raises OSError if stream_read fails. + * Sets self->read_error and self->eof if stream_read fails, instead of raising, because this also + * runs where nothing can catch an exception (a port's audio fill task). * * Sets self->eof if any read of the file returns 0 bytes */ static bool mp3file_update_inbuf_always(audiomp3_mp3file_obj_t *self, bool block_ok) { + // Every return from this function must be preceded by background_callback_allow(); + background_callback_prevent(); + audiocore_lock(); + if (self->eof || INPUT_BUFFER_SPACE(self->inbuf) == 0) { - return INPUT_BUFFER_AVAILABLE(self->inbuf) > 0; + bool result = INPUT_BUFFER_AVAILABLE(self->inbuf) > 0; + audiocore_unlock(); + background_callback_allow(); + return result; } stream_set_blocking(self, block_ok); @@ -135,7 +143,8 @@ static bool mp3file_update_inbuf_always(audiomp3_mp3file_obj_t *self, bool block self->inbuf.read_off = 0; } - for (size_t to_read; !self->eof && (to_read = INPUT_BUFFER_SPACE(self->inbuf)) > 0;) { + for (size_t to_read; !self->eof && INPUT_BUFFER_SPACE(self->inbuf) > 0 && + (to_read = (size_t)INPUT_BUFFER_SPACE(self->inbuf)) > 0;) { uint8_t *write_ptr = self->inbuf.buf + self->inbuf.write_off; ssize_t n_read = stream_read(self->stream, write_ptr, to_read); @@ -145,7 +154,8 @@ static bool mp3file_update_inbuf_always(audiomp3_mp3file_obj_t *self, bool block break; } self->eof = true; - mp_raise_OSError(errcode); + self->read_error = errcode; + break; } if (n_read == 0) { @@ -160,7 +170,11 @@ static bool mp3file_update_inbuf_always(audiomp3_mp3file_obj_t *self, bool block } // Return true iff there are at least some useful bytes in the buffer - return INPUT_BUFFER_AVAILABLE(self->inbuf) > 0; + bool result = INPUT_BUFFER_AVAILABLE(self->inbuf) > 0; + + audiocore_unlock(); + background_callback_allow(); + return result; } /** Update the inbuf from a background callback. @@ -234,7 +248,8 @@ static void mp3file_skip_id3v2(audiomp3_mp3file_obj_t *self, bool block_ok) { size -= to_consume; // Next, seek in the file after the header - if (stream_lseek(self->stream, SEEK_CUR, size) == 0) { + off_t before = stream_lseek(self->stream, 0, SEEK_CUR); + if (before >= 0 && stream_lseek(self->stream, size, SEEK_CUR) == before + size) { return; } @@ -305,7 +320,7 @@ void common_hal_audiomp3_mp3file_construct(audiomp3_mp3file_obj_t *self, self->inbuf.size = buffer_size - 2 * MAX_BUFFER_LEN; } else { self->inbuf.size = DEFAULT_INPUT_BUFFER_SIZE; - self->inbuf.buf = m_malloc(DEFAULT_INPUT_BUFFER_SIZE); + self->inbuf.buf = m_malloc_without_collect(DEFAULT_INPUT_BUFFER_SIZE); if (self->inbuf.buf == NULL) { common_hal_audiomp3_mp3file_deinit(self); m_malloc_fail(DEFAULT_INPUT_BUFFER_SIZE); @@ -315,13 +330,13 @@ void common_hal_audiomp3_mp3file_construct(audiomp3_mp3file_obj_t *self, self->pcm_buffer[0] = (int16_t *)(void *)buffer; self->pcm_buffer[1] = (int16_t *)(void *)(buffer + MAX_BUFFER_LEN); } else { - self->pcm_buffer[0] = m_malloc(MAX_BUFFER_LEN); + self->pcm_buffer[0] = m_malloc_without_collect(MAX_BUFFER_LEN); if (self->pcm_buffer[0] == NULL) { common_hal_audiomp3_mp3file_deinit(self); m_malloc_fail(MAX_BUFFER_LEN); } - self->pcm_buffer[1] = m_malloc(MAX_BUFFER_LEN); + self->pcm_buffer[1] = m_malloc_without_collect(MAX_BUFFER_LEN); if (self->pcm_buffer[1] == NULL) { common_hal_audiomp3_mp3file_deinit(self); m_malloc_fail(MAX_BUFFER_LEN); @@ -340,14 +355,14 @@ void common_hal_audiomp3_mp3file_construct(audiomp3_mp3file_obj_t *self, common_hal_audiomp3_mp3file_set_file(self, stream); } -void common_hal_audiomp3_mp3file_set_file(audiomp3_mp3file_obj_t *self, mp_obj_t stream) { - background_callback_prevent(); - +// Call with background callbacks prevented. +static bool mp3file_set_file_and_get_frame_info(audiomp3_mp3file_obj_t *self, mp_obj_t stream, MP3FrameInfo *fi) { self->stream = stream; mp_load_method_maybe(stream, MP_QSTR_settimeout, self->settimeout_args); INPUT_BUFFER_CLEAR(self->inbuf); self->eof = 0; + self->read_error = 0; self->block_ok = false; stream_set_blocking(self, true); @@ -373,9 +388,29 @@ void common_hal_audiomp3_mp3file_set_file(audiomp3_mp3file_obj_t *self, mp_obj_t memset(decoder->IMDCTInfoPS, 0, sizeof(IMDCTInfo)); memset(decoder->SubbandInfoPS, 0, sizeof(SubbandInfo)); + return mp3file_get_next_frame_info(self, fi, true); +} + +void common_hal_audiomp3_mp3file_set_file(audiomp3_mp3file_obj_t *self, mp_obj_t stream) { + background_callback_prevent(); + audiocore_lock(); + MP3FrameInfo fi; - bool result = mp3file_get_next_frame_info(self, &fi, true); + bool result; + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + result = mp3file_set_file_and_get_frame_info(self, stream, &fi); + nlr_pop(); + } else { + audiocore_unlock(); + background_callback_allow(); + nlr_jump(nlr.ret_val); + } + audiocore_unlock(); background_callback_allow(); + if (self->read_error) { + mp_raise_OSError(self->read_error); + } if (!result) { mp_raise_msg(&mp_type_RuntimeError, MP_ERROR_TEXT("Failed to parse MP3 file")); @@ -392,6 +427,7 @@ void common_hal_audiomp3_mp3file_set_file(audiomp3_mp3file_obj_t *self, mp_obj_t } void common_hal_audiomp3_mp3file_deinit(audiomp3_mp3file_obj_t *self) { + audiocore_lock(); audiosample_mark_deinit(&self->base); if (self->decoder) { MP3FreeDecoder(self->decoder); @@ -403,6 +439,7 @@ void common_hal_audiomp3_mp3file_deinit(audiomp3_mp3file_obj_t *self) { self->stream = mp_const_none; self->settimeout_args[0] = MP_OBJ_NULL; self->samples_decoded = 0; + audiocore_unlock(); } void audiomp3_mp3file_reset_buffer(audiomp3_mp3file_obj_t *self, @@ -414,14 +451,17 @@ void audiomp3_mp3file_reset_buffer(audiomp3_mp3file_obj_t *self, // We don't reset the buffer index in case we're looping and we have an odd number of buffer // loads background_callback_prevent(); - if (self->eof && stream_lseek(self->stream, SEEK_SET, 0) == 0) { + audiocore_lock(); + if (self->eof && stream_lseek(self->stream, 0, SEEK_SET) == 0) { INPUT_BUFFER_CLEAR(self->inbuf); self->eof = 0; + self->read_error = 0; self->samples_decoded = 0; self->other_channel = -1; mp3file_skip_id3v2(self, false); mp3file_find_sync_word(self, false); } + audiocore_unlock(); background_callback_allow(); } @@ -437,6 +477,10 @@ audioio_get_buffer_result_t audiomp3_mp3file_get_buffer(audiomp3_mp3file_obj_t * } return GET_BUFFER_ERROR; } + if (self->read_error) { + *buffer_length = 0; + return GET_BUFFER_ERROR; + } if (!single_channel_output) { channel = 0; } @@ -465,7 +509,7 @@ audioio_get_buffer_result_t audiomp3_mp3file_get_buffer(audiomp3_mp3file_obj_t * if (!mp3file_find_sync_word(self, false)) { memset(buffer, 0, self->base.max_buffer_length); *buffer_length = 0; - return self->eof ? GET_BUFFER_DONE : GET_BUFFER_ERROR; + return self->eof && !self->read_error ? GET_BUFFER_DONE : GET_BUFFER_ERROR; } int bytes_left = BYTES_LEFT(self); uint8_t *inbuf = READ_PTR(self); @@ -481,8 +525,9 @@ audioio_get_buffer_result_t audiomp3_mp3file_get_buffer(audiomp3_mp3file_obj_t * if (self->eof || (err != ERR_MP3_INDATA_UNDERFLOW && err != ERR_MP3_MAINDATA_UNDERFLOW)) { memset(buffer, 0, self->base.max_buffer_length); *buffer_length = 0; + bool underflow = (err == ERR_MP3_INDATA_UNDERFLOW || err == ERR_MP3_MAINDATA_UNDERFLOW); self->eof = true; - return GET_BUFFER_ERROR; + return underflow ? GET_BUFFER_DONE : GET_BUFFER_ERROR; } } @@ -507,14 +552,14 @@ audioio_get_buffer_result_t audiomp3_mp3file_get_buffer(audiomp3_mp3file_obj_t * return result; } -float common_hal_audiomp3_mp3file_get_rms_level(audiomp3_mp3file_obj_t *self) { - float sumsq = 0.f; +mp_float_t common_hal_audiomp3_mp3file_get_rms_level(audiomp3_mp3file_obj_t *self) { + mp_float_t sumsq = MICROPY_FLOAT_CONST(0.0); // Assumes no DC component to the audio. Is that a safe assumption? int16_t *buffer = (int16_t *)(void *)self->pcm_buffer[self->buffer_index]; for (size_t i = 0; i < self->base.max_buffer_length / sizeof(int16_t); i++) { - sumsq += (float)buffer[i] * buffer[i]; + sumsq += (mp_float_t)buffer[i] * buffer[i]; } - return sqrtf(sumsq) / (self->base.max_buffer_length / sizeof(int16_t)); + return MICROPY_FLOAT_C_FUN(sqrt)(sumsq) / (self->base.max_buffer_length / sizeof(int16_t)); } uint32_t common_hal_audiomp3_mp3file_get_samples_decoded(audiomp3_mp3file_obj_t *self) { diff --git a/shared-module/audiomp3/MP3Decoder.h b/shared-module/audiomp3/MP3Decoder.h index 9af3300047b..a12eb80a815 100644 --- a/shared-module/audiomp3/MP3Decoder.h +++ b/shared-module/audiomp3/MP3Decoder.h @@ -33,6 +33,7 @@ typedef struct { uint8_t buffer_index; bool eof; bool block_ok; + int read_error; // errno from a failed stream read, 0 if none. Raised from Python context. mp_obj_t settimeout_args[3]; int8_t other_channel; diff --git a/shared-module/audiospeed/Resampler.c b/shared-module/audiospeed/Resampler.c new file mode 100644 index 00000000000..cd1ac681246 --- /dev/null +++ b/shared-module/audiospeed/Resampler.c @@ -0,0 +1,44 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Cooper Dalrymple +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/audiospeed/Resampler.h" + +static void calculate_rate(audiospeed_base_t *self, uint32_t sample_rate) { + if (self->source != NULL && sample_rate) { + self->speed.rate_fp = (uint32_t)((mp_float_t)self->base.sample_rate / sample_rate * (1 << SPEED_SHIFT)); + } else { + audiospeed_set_rate(&self->speed, mp_const_none); + } +} + +void common_hal_audiospeed_resampler_construct(audiospeed_resampler_obj_t *self, mp_obj_t source) { + audiospeed_construct(&self->base, source, mp_const_none); // default rate 1.0 + self->sample_rate = 0; +} + +void common_hal_audiospeed_resampler_deinit(audiospeed_resampler_obj_t *self) { + audiospeed_deinit(&self->base); +} + +mp_obj_t common_hal_audiospeed_resampler_get_rate(audiospeed_resampler_obj_t *self) { + return audiospeed_get_rate(&self->base.speed); +} + +void audiospeed_resampler_set_sample_rate(audiospeed_resampler_obj_t *self, uint32_t sample_rate) { + self->sample_rate = sample_rate; + calculate_rate(&self->base, self->sample_rate); +} + +void audiospeed_resampler_reset_buffer(audiospeed_resampler_obj_t *self, + bool single_channel_output, uint8_t channel) { + audiospeed_reset_buffer(&self->base, single_channel_output, channel); +} + +audioio_get_buffer_result_t audiospeed_resampler_get_buffer(audiospeed_resampler_obj_t *self, + bool single_channel_output, uint8_t channel, + uint8_t **buffer, uint32_t *buffer_length) { + return audiospeed_get_buffer(&self->base, single_channel_output, channel, buffer, buffer_length); +} diff --git a/shared-module/audiospeed/Resampler.h b/shared-module/audiospeed/Resampler.h new file mode 100644 index 00000000000..a105c5c2ab9 --- /dev/null +++ b/shared-module/audiospeed/Resampler.h @@ -0,0 +1,22 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Cooper Dalrymple +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" +#include "shared-module/audiocore/__init__.h" +#include "shared-module/audiospeed/__init__.h" + +typedef struct { + audiospeed_base_t base; + uint32_t sample_rate; +} audiospeed_resampler_obj_t; + +void audiospeed_resampler_reset_buffer(audiospeed_resampler_obj_t *self, + bool single_channel_output, uint8_t channel); +audioio_get_buffer_result_t audiospeed_resampler_get_buffer(audiospeed_resampler_obj_t *self, + bool single_channel_output, uint8_t channel, + uint8_t **buffer, uint32_t *buffer_length); diff --git a/shared-module/audiospeed/SpeedChanger.c b/shared-module/audiospeed/SpeedChanger.c new file mode 100644 index 00000000000..1bf21dfab7a --- /dev/null +++ b/shared-module/audiospeed/SpeedChanger.c @@ -0,0 +1,42 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tod Kurt +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/audiospeed/SpeedChanger.h" + +#include +#include "py/runtime.h" +#include "py/gc.h" + +#include "shared-module/audiocore/__init__.h" +#include "shared-bindings/audiocore/__init__.h" + +void common_hal_audiospeed_speedchanger_construct(audiospeed_speedchanger_obj_t *self, + mp_obj_t source, mp_obj_t rate_obj) { + audiospeed_construct(self, source, rate_obj); +} + +void common_hal_audiospeed_speedchanger_deinit(audiospeed_speedchanger_obj_t *self) { + audiospeed_deinit(self); +} + +void common_hal_audiospeed_speedchanger_set_rate(audiospeed_speedchanger_obj_t *self, mp_obj_t rate_obj) { + audiospeed_set_rate(&self->speed, rate_obj); +} + +mp_obj_t common_hal_audiospeed_speedchanger_get_rate(audiospeed_speedchanger_obj_t *self) { + return audiospeed_get_rate(&self->speed); +} + +void audiospeed_speedchanger_reset_buffer(audiospeed_speedchanger_obj_t *self, + bool single_channel_output, uint8_t channel) { + audiospeed_reset_buffer(self, single_channel_output, channel); +} + +audioio_get_buffer_result_t audiospeed_speedchanger_get_buffer(audiospeed_speedchanger_obj_t *self, + bool single_channel_output, uint8_t channel, + uint8_t **buffer, uint32_t *buffer_length) { + return audiospeed_get_buffer(self, single_channel_output, channel, buffer, buffer_length); +} diff --git a/shared-module/audiospeed/SpeedChanger.h b/shared-module/audiospeed/SpeedChanger.h new file mode 100644 index 00000000000..34969e42bd6 --- /dev/null +++ b/shared-module/audiospeed/SpeedChanger.h @@ -0,0 +1,19 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tod Kurt +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" +#include "shared-module/audiocore/__init__.h" +#include "shared-module/audiospeed/__init__.h" + +typedef audiospeed_base_t audiospeed_speedchanger_obj_t; + +void audiospeed_speedchanger_reset_buffer(audiospeed_speedchanger_obj_t *self, + bool single_channel_output, uint8_t channel); +audioio_get_buffer_result_t audiospeed_speedchanger_get_buffer(audiospeed_speedchanger_obj_t *self, + bool single_channel_output, uint8_t channel, + uint8_t **buffer, uint32_t *buffer_length); diff --git a/shared-module/audiospeed/__init__.c b/shared-module/audiospeed/__init__.c new file mode 100644 index 00000000000..19c4c9bf20d --- /dev/null +++ b/shared-module/audiospeed/__init__.c @@ -0,0 +1,176 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tod Kurt +// +// SPDX-License-Identifier: MIT + +#include + +#include "py/gc.h" +#include "py/objproperty.h" +#include "py/runtime.h" + +#include "shared-module/audiocore/__init__.h" +#include "shared-module/audiospeed/__init__.h" +#include "shared-bindings/audiocore/__init__.h" + +// Convert a Python float to 16.16 fixed-point rate +uint32_t audiospeed_rate_to_fp(mp_obj_t rate_obj) { + mp_float_t rate = mp_arg_validate_obj_float_range(rate_obj, 0.001, 1000.0, MP_QSTR_rate); + return (uint32_t)(rate * (1 << SPEED_SHIFT)); +} + +// Convert 16.16 fixed-point rate to Python float +mp_obj_t audiospeed_fp_to_rate(uint32_t rate_fp) { + return mp_obj_new_float((mp_float_t)rate_fp / (1 << SPEED_SHIFT)); +} + +void audiospeed_construct(audiospeed_base_t *self, mp_obj_t source, mp_obj_t rate_obj) { + audiosample_base_t *src_base = audiosample_check(source); + + self->source = source; + self->src_buffer = NULL; + self->src_buffer_length = 0; + self->src_sample_count = 0; + self->source_done = false; + self->source_exhausted = false; + + + // Copy format from source + self->base.sample_rate = src_base->sample_rate; + self->base.channel_count = src_base->channel_count; + self->base.bits_per_sample = src_base->bits_per_sample; + self->base.samples_signed = src_base->samples_signed; + self->base.single_buffer = false; + + audiospeed_set_rate(&self->speed, rate_obj); + audiospeed_reset_phase(&self->speed); + + uint8_t bytes_per_frame = (src_base->bits_per_sample / 8) * src_base->channel_count; + self->output_buffer_length = OUTPUT_BUFFER_FRAMES * bytes_per_frame; + self->base.max_buffer_length = self->output_buffer_length; + + self->output_buffer = m_malloc_without_collect(self->output_buffer_length); + if (self->output_buffer == NULL) { + m_malloc_fail(self->output_buffer_length); + } +} + +void audiospeed_deinit(audiospeed_base_t *self) { + self->output_buffer = NULL; + self->source = MP_OBJ_NULL; + audiosample_mark_deinit(&self->base); +} + +// Fetch the next buffer from the source. Returns false if no data available. +bool audiospeed_fetch_source_buffer(audiospeed_base_t *self) { + if (self->source_exhausted || self->source == NULL) { + return false; + } + uint8_t *buf = NULL; + uint32_t len = 0; + audioio_get_buffer_result_t result = audiosample_get_buffer(self->source, false, 0, &buf, &len); + if (result == GET_BUFFER_ERROR) { + self->source_exhausted = true; + return false; + } + if (len == 0) { + self->source_exhausted = true; + return false; + } + self->src_buffer = buf; + self->src_buffer_length = len; + uint8_t bytes_per_frame = (self->base.bits_per_sample / 8) * self->base.channel_count; + self->src_sample_count = len / bytes_per_frame; + self->source_done = (result == GET_BUFFER_DONE); + // Reset phase to index within this new buffer + audiospeed_reset_phase(&self->speed); + return true; +} + +void audiospeed_reset_buffer(audiospeed_base_t *self, bool single_channel_output, uint8_t channel) { + if (single_channel_output && channel == 1) { + return; + } + audiosample_reset_buffer(self->source, false, 0); + audiospeed_reset_phase(&self->speed); + self->src_buffer = NULL; + self->src_buffer_length = 0; + self->src_sample_count = 0; + self->source_done = false; + self->source_exhausted = false; +} + +audioio_get_buffer_result_t audiospeed_get_buffer(audiospeed_base_t *self, bool single_channel_output, uint8_t channel, + uint8_t **buffer, uint32_t *buffer_length) { + + // Ensure we have a source buffer + if (self->src_buffer == NULL) { + if (!audiospeed_fetch_source_buffer(self)) { + *buffer = NULL; + *buffer_length = 0; + return GET_BUFFER_DONE; + } + } + + uint8_t bytes_per_sample = self->base.bits_per_sample / 8; + uint8_t channels = self->base.channel_count; + uint8_t bytes_per_frame = bytes_per_sample * channels; + uint32_t out_frames = 0; + uint32_t max_out_frames = self->output_buffer_length / bytes_per_frame; + + if (bytes_per_sample == 1) { + // 8-bit samples + uint8_t *out = self->output_buffer; + while (out_frames < max_out_frames) { + uint32_t src_index = audiospeed_get_index(&self->speed); + // Advance to next source buffer if needed + if (src_index >= self->src_sample_count) { + if (self->source_done) { + self->source_exhausted = true; + break; + } + if (!audiospeed_fetch_source_buffer(self)) { + break; + } + src_index = 0; // phase was reset by fetch + } + uint8_t *src = self->src_buffer + src_index * bytes_per_frame; + for (uint8_t c = 0; c < channels; c++) { + *out++ = src[c]; + } + out_frames++; + audiospeed_increment_phase(&self->speed); + } + } else { + // 16-bit samples + int16_t *out = (int16_t *)self->output_buffer; + while (out_frames < max_out_frames) { + uint32_t src_index = audiospeed_get_index(&self->speed); + if (src_index >= self->src_sample_count) { + if (self->source_done) { + self->source_exhausted = true; + break; + } + if (!audiospeed_fetch_source_buffer(self)) { + break; + } + src_index = 0; + } + int16_t *src = (int16_t *)(self->src_buffer + src_index * bytes_per_frame); + for (uint8_t c = 0; c < channels; c++) { + *out++ = src[c]; + } + out_frames++; + audiospeed_increment_phase(&self->speed); + } + } + + *buffer = self->output_buffer; + *buffer_length = out_frames * bytes_per_frame; + + if (out_frames == 0) { + return GET_BUFFER_DONE; + } + return self->source_exhausted ? GET_BUFFER_DONE : GET_BUFFER_MORE_DATA; +} diff --git a/shared-module/audiospeed/__init__.h b/shared-module/audiospeed/__init__.h new file mode 100644 index 00000000000..4a36a8b79b7 --- /dev/null +++ b/shared-module/audiospeed/__init__.h @@ -0,0 +1,72 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tod Kurt +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include + +#include "py/objproperty.h" +#include "shared-module/audiocore/__init__.h" + +// Fixed-point 16.16 format +#define SPEED_SHIFT 16 +#define SPEED_DEFAULT (1 << SPEED_SHIFT) // default 1.0 + +typedef struct { + // Phase accumulator and rate in 16.16 fixed-point (units: source frames) + uint32_t phase; + uint32_t rate_fp; // 16.16 fixed-point rate +} audiospeed_speed_t; + +uint32_t audiospeed_rate_to_fp(mp_obj_t rate_obj); +mp_obj_t audiospeed_fp_to_rate(uint32_t rate_fp); + +static inline void audiospeed_set_rate(audiospeed_speed_t *self, mp_obj_t rate_obj) { + if (rate_obj != mp_const_none) { + self->rate_fp = audiospeed_rate_to_fp(rate_obj); + } else { + self->rate_fp = SPEED_DEFAULT; + } +} + +static inline mp_obj_t audiospeed_get_rate(audiospeed_speed_t *self) { + return audiospeed_fp_to_rate(self->rate_fp); +} + +static inline void audiospeed_reset_phase(audiospeed_speed_t *self) { + self->phase = 0; +} + +static inline void audiospeed_increment_phase(audiospeed_speed_t *self) { + self->phase += self->rate_fp; +} + +static inline uint32_t audiospeed_get_index(audiospeed_speed_t *self) { + return self->phase >> SPEED_SHIFT; +} + +#define OUTPUT_BUFFER_FRAMES 128 + +typedef struct { + audiosample_base_t base; + mp_obj_t source; + uint8_t *output_buffer; + uint32_t output_buffer_length; // in bytes, allocated size + // Source buffer cache + uint8_t *src_buffer; + uint32_t src_buffer_length; // in bytes + uint32_t src_sample_count; // in frames + audiospeed_speed_t speed; + bool source_done; // source returned DONE on last get_buffer + bool source_exhausted; // source DONE and we consumed all of it +} audiospeed_base_t; + +void audiospeed_construct(audiospeed_base_t *self, mp_obj_t source, mp_obj_t rate_obj); +void audiospeed_deinit(audiospeed_base_t *self); +bool audiospeed_fetch_source_buffer(audiospeed_base_t *self); +void audiospeed_reset_buffer(audiospeed_base_t *self, bool single_channel_output, uint8_t channel); +audioio_get_buffer_result_t audiospeed_get_buffer(audiospeed_base_t *self, bool single_channel_output, uint8_t channel, + uint8_t **buffer, uint32_t *buffer_length); diff --git a/shared-module/audiotap/LevelReader.c b/shared-module/audiotap/LevelReader.c new file mode 100644 index 00000000000..64e4b1bedcd --- /dev/null +++ b/shared-module/audiotap/LevelReader.c @@ -0,0 +1,113 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT +#include "shared-bindings/audiotap/LevelReader.h" +#include "shared-bindings/audiocore/__init__.h" + +#include +#include + +#include "py/runtime.h" + +void common_hal_audiotap_levelreader_construct(audiotap_levelreader_obj_t *self, audiotap_tap_obj_t *tap) { + audiosample_check_for_deinit(&tap->base); + if (tap->levels != NULL) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("%q in use"), MP_QSTR_tap); + } + self->tap = tap; + self->peak = 0; + self->peak_reset = false; + self->sum_squares = 0; + self->level_count = 0; + self->rms_reset = false; + // The levels must start from 0 before the tap's writer can see them. + __sync_synchronize(); + tap->levels = self; +} + +bool common_hal_audiotap_levelreader_deinited(audiotap_levelreader_obj_t *self) { + return self->tap == NULL; +} + +void common_hal_audiotap_levelreader_deinit(audiotap_levelreader_obj_t *self) { + audiotap_tap_obj_t *tap = self->tap; + if (tap == NULL) { + return; + } + // The tap stops measuring. If its writer is measuring right now, it + // finishes with this object, which is still allocated, and no harm done. + if (tap->levels == self) { + tap->levels = NULL; + } + self->tap = NULL; +} + +// The sample at i, as a signed 16 bit value. +static int32_t sample_at(const audiosample_base_t *format, const uint8_t *data, uint32_t i) { + if (MP_LIKELY(format->bits_per_sample == 16)) { + // data is the source's 16 bit buffer, advanced only in whole samples, + // so it is aligned. + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wcast-align" + uint16_t raw = ((const uint16_t *)data)[i]; + #pragma GCC diagnostic pop + return format->samples_signed ? (int16_t)raw : (int16_t)(raw ^ 0x8000); + } + uint8_t raw = data[i]; + return (format->samples_signed ? (int8_t)raw : (int8_t)(raw ^ 0x80)) * 256; +} + +void audiotap_levelreader_measure(audiotap_levelreader_obj_t *self, + const audiosample_base_t *format, const uint8_t *data, uint32_t count) { + if (self->peak_reset) { + self->peak = 0; + self->peak_reset = false; + } + if (self->rms_reset) { + self->sum_squares = 0; + self->level_count = 0; + self->rms_reset = false; + } + uint32_t peak = self->peak; + uint64_t sum = 0; + for (uint32_t i = 0; i < count; i++) { + int32_t value = sample_at(format, data, i); + uint32_t magnitude = value < 0 ? -value : value; + if (magnitude > peak) { + peak = magnitude; + } + sum += (uint64_t)(value * value); + } + self->peak = peak; + self->sum_squares += (float)sum / (32768.0f * 32768.0f); + self->level_count += count; +} + +static void check_tap(audiotap_levelreader_obj_t *self) { + audiosample_check_for_deinit(&self->tap->base); +} + +mp_float_t common_hal_audiotap_levelreader_get_peak(audiotap_levelreader_obj_t *self) { + check_tap(self); + if (self->peak_reset) { + // No audio passed since the last read. + return 0; + } + mp_float_t peak = (mp_float_t)self->peak / MICROPY_FLOAT_CONST(32768.0); + self->peak_reset = true; + return peak; +} + +mp_float_t common_hal_audiotap_levelreader_get_rms(audiotap_levelreader_obj_t *self) { + check_tap(self); + if (self->rms_reset) { + // No audio passed since the last read. + return 0; + } + uint32_t count = self->level_count; + float sum_squares = self->sum_squares; + self->rms_reset = true; + return count > 0 ? MICROPY_FLOAT_C_FUN(sqrt)((mp_float_t)sum_squares / count) : 0; +} diff --git a/shared-module/audiotap/LevelReader.h b/shared-module/audiotap/LevelReader.h new file mode 100644 index 00000000000..6fc5de3853d --- /dev/null +++ b/shared-module/audiotap/LevelReader.h @@ -0,0 +1,32 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT +#pragma once + +#include "py/obj.h" + +#include "shared-module/audiotap/Tap.h" + +extern const mp_obj_type_t audiotap_levelreader_type; + +typedef struct audiotap_levelreader_obj { + mp_obj_base_t base; + + // The tap whose audio is measured. NULL once deinitialized. + audiotap_tap_obj_t *tap; + + // Levels of the audio since each was last read. Reading one asks for its + // reset, and the tap's writer does it, so that only the writer changes them. + volatile uint32_t peak; // largest magnitude, 0 to 32768 + volatile bool peak_reset; + volatile float sum_squares; // of samples scaled to -1.0 to 1.0 + volatile uint32_t level_count; // samples summed + volatile bool rms_reset; +} audiotap_levelreader_obj_t; + +// Called by the tap for each run of samples that passes through it, by +// whatever plays the tap. It may be an interrupt, so this never allocates. +void audiotap_levelreader_measure(audiotap_levelreader_obj_t *self, + const audiosample_base_t *format, const uint8_t *data, uint32_t count); diff --git a/shared-module/audiotap/Tap.c b/shared-module/audiotap/Tap.c new file mode 100644 index 00000000000..1ecaed5ddfb --- /dev/null +++ b/shared-module/audiotap/Tap.c @@ -0,0 +1,290 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT +#include "shared-bindings/audiotap/Tap.h" +#include "shared-module/audiotap/LevelReader.h" +#include "shared-bindings/audiocore/__init__.h" + +#include +#include + +#include "py/runtime.h" + +void common_hal_audiotap_tap_construct(audiotap_tap_obj_t *self, mp_float_t capacity) { + // The format comes from the first sample played. Until then the tap is + // 16 bit mono at 0 Hz, which nothing plays: a channel count of 0 would + // mark it deinitialized. + self->base.bits_per_sample = 16; + self->base.samples_signed = true; + self->base.channel_count = 1; + self->base.sample_rate = 0; + self->base.single_buffer = false; + self->base.max_buffer_length = 0; + + self->silence = NULL; + self->silence_len = 0; + + self->sample = NULL; + self->sample_remaining_buffer = NULL; + self->sample_buffer_length = 0; + self->loop = false; + self->more_data = false; + + self->capacity_seconds = capacity; + self->ring = NULL; + self->capacity = 0; + self->write_pos = 0; + self->read_pos = 0; + self->overflow = false; + + self->levels = NULL; +} + +void common_hal_audiotap_tap_deinit(audiotap_tap_obj_t *self) { + audiosample_mark_deinit(&self->base); + self->sample = NULL; + self->silence = NULL; + self->ring = NULL; + self->capacity = 0; + self->levels = NULL; +} + +void audiotap_tap_reset_buffer(audiotap_tap_obj_t *self, + bool single_channel_output, + uint8_t channel) { + (void)self; + (void)single_channel_output; + (void)channel; + // Nothing to reset: the tap passes on the source's buffers, and the ring + // belongs to the reader, so what it holds stays readable. +} + +bool common_hal_audiotap_tap_get_playing(audiotap_tap_obj_t *self) { + return self->sample != NULL; +} + +// Takes the format of the first sample played and allocates for it. +static void take_format(audiotap_tap_obj_t *self, mp_obj_t sample) { + const audiosample_base_t *source = audiosample_check(sample); + audiosample_check_for_deinit(source); + if (source->bits_per_sample != 8 && source->bits_per_sample != 16) { + mp_raise_ValueError(MP_ERROR_TEXT("bits_per_sample must be 8 or 16")); + } + const uint32_t sample_bytes = source->bits_per_sample / 8; + const uint32_t frame_bytes = sample_bytes * source->channel_count; + + // Silence for when the source has no audio, no longer than the source's + // buffers and in whole frames. + uint32_t silence_len = MIN(MAX(source->max_buffer_length, frame_bytes), 512); + silence_len -= silence_len % frame_bytes; + int8_t *silence = m_malloc_without_collect(silence_len); + if (source->samples_signed) { + memset(silence, 0, silence_len); + } else if (sample_bytes == 2) { + // We know the buffer is aligned because we allocated it onto the heap ourselves. + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wcast-align" + uint16_t *words = (uint16_t *)silence; + #pragma GCC diagnostic pop + for (uint32_t i = 0; i < silence_len / 2; i++) { + words[i] = 0x8000; + } + } else { + memset(silence, 0x80, silence_len); + } + + // Rounded, so that a capacity such as 0.7 s, which a float holds as a hair + // under, does not lose a frame. + uint32_t capacity = (uint32_t)(self->capacity_seconds * source->sample_rate + MICROPY_FLOAT_CONST(0.5)) * source->channel_count; + uint8_t *ring = NULL; + if (capacity > 0) { + ring = m_malloc_without_collect(capacity * sample_bytes); + } + + // Nothing plays the tap before it has a format, so the reader is the + // only one using these yet. + self->silence = silence; + self->silence_len = silence_len; + self->ring = ring; + self->capacity = capacity; + self->write_pos = 0; + self->read_pos = 0; + + self->base.bits_per_sample = source->bits_per_sample; + self->base.samples_signed = source->samples_signed; + self->base.channel_count = source->channel_count; + self->base.sample_rate = source->sample_rate; + self->base.max_buffer_length = MAX(source->max_buffer_length, silence_len); +} + +void common_hal_audiotap_tap_play(audiotap_tap_obj_t *self, mp_obj_t sample, bool loop) { + if (self->silence == NULL) { + take_format(self, sample); + } else { + audiosample_must_match(&self->base, sample, false); + } + + audiosample_reset_buffer(sample, false, 0); + self->loop = loop; + self->sample_buffer_length = 0; + // Ask the source for its first buffer. + self->more_data = true; + self->sample = sample; +} + +void common_hal_audiotap_tap_stop(audiotap_tap_obj_t *self) { + self->sample = NULL; +} + +// Positions run from 0 to 2 * capacity. +static uint32_t ring_used(uint32_t capacity, uint32_t write, uint32_t read) { + return write >= read ? write - read : write + 2 * capacity - read; +} + +static uint32_t ring_index(uint32_t capacity, uint32_t pos) { + return pos >= capacity ? pos - capacity : pos; +} + +static uint32_t ring_advance(uint32_t capacity, uint32_t pos, uint32_t count) { + pos += count; + return pos >= 2 * capacity ? pos - 2 * capacity : pos; +} + +// Called by whatever plays the tap, for each run of samples from the source. +// It may be an interrupt, so it never allocates and changes only write_pos and +// the attached LevelReader's levels. +static void tap_capture(audiotap_tap_obj_t *self, const uint8_t *data, uint32_t count) { + if (count == 0) { + return; + } + + audiotap_levelreader_obj_t *levels = self->levels; + if (levels != NULL) { + audiotap_levelreader_measure(levels, &self->base, data, count); + } + + if (self->ring == NULL) { + return; + } + const uint32_t capacity = self->capacity; + const uint32_t sample_bytes = self->base.bits_per_sample / 8; + uint32_t write = self->write_pos; + uint32_t free = capacity - ring_used(capacity, write, self->read_pos); + if (count > free) { + // The reader fell behind. Moving read_pos to keep the newest audio + // would race with it, so drop what doesn't fit. + count = free; + self->overflow = true; + } + while (count > 0) { + uint32_t index = ring_index(capacity, write); + uint32_t run = MIN(count, capacity - index); + memcpy(self->ring + index * sample_bytes, data, run * sample_bytes); + data += run * sample_bytes; + count -= run; + write = ring_advance(capacity, write, run); + } + // The samples must be in the ring before the reader can see them. + __sync_synchronize(); + self->write_pos = write; +} + +uint32_t common_hal_audiotap_tap_get_available(audiotap_tap_obj_t *self) { + if (self->ring == NULL) { + return 0; + } + return ring_used(self->capacity, self->write_pos, self->read_pos); +} + +uint32_t common_hal_audiotap_tap_readinto(audiotap_tap_obj_t *self, uint8_t *buffer, uint32_t length) { + if (self->ring == NULL) { + return 0; + } + const uint32_t capacity = self->capacity; + const uint32_t sample_bytes = self->base.bits_per_sample / 8; + uint32_t read = self->read_pos; + uint32_t write = self->write_pos; + __sync_synchronize(); + uint32_t count = MIN(length - length % self->base.channel_count, + ring_used(capacity, write, read)); + uint32_t done = 0; + while (done < count) { + uint32_t index = ring_index(capacity, read); + uint32_t run = MIN(count - done, capacity - index); + memcpy(buffer + done * sample_bytes, self->ring + index * sample_bytes, run * sample_bytes); + done += run; + read = ring_advance(capacity, read, run); + } + // Copy out before the writer may reuse the space. + __sync_synchronize(); + self->read_pos = read; + return count; +} + +void common_hal_audiotap_tap_clear(audiotap_tap_obj_t *self) { + self->read_pos = self->write_pos; +} + +bool common_hal_audiotap_tap_get_overflow(audiotap_tap_obj_t *self) { + bool overflow = self->overflow; + self->overflow = false; + return overflow; +} + +audioio_get_buffer_result_t audiotap_tap_get_buffer(audiotap_tap_obj_t *self, bool single_channel_output, uint8_t channel, + uint8_t **buffer, uint32_t *buffer_length) { + (void)single_channel_output; + (void)channel; + + if (self->silence == NULL) { + // Deinitialized while something still plays it. + *buffer = NULL; + *buffer_length = 0; + return GET_BUFFER_DONE; + } + + const uint32_t sample_bytes = self->base.bits_per_sample / 8; + if (self->sample_buffer_length == 0 && self->sample != NULL) { + if (!self->more_data) { + if (self->loop) { + audiosample_reset_buffer(self->sample, false, 0); + } else { + self->sample = NULL; + } + } + if (self->sample != NULL) { + audioio_get_buffer_result_t result = audiosample_get_buffer(self->sample, false, 0, + (uint8_t **)&self->sample_remaining_buffer, &self->sample_buffer_length); + if (result == GET_BUFFER_ERROR) { + self->sample = NULL; + self->sample_buffer_length = 0; + self->more_data = false; + } else { + self->sample_buffer_length /= sample_bytes; + self->more_data = result == GET_BUFFER_MORE_DATA; + } + } + } + + if (self->sample == NULL || self->sample_buffer_length == 0) { + // Like the effects, a tap plays silence when it has no audio, and + // rather than ask a source that has nothing yet again in a loop. + *buffer = (uint8_t *)self->silence; + *buffer_length = self->silence_len; + return GET_BUFFER_MORE_DATA; + } + + // Pass on the source's own buffer, in whole frames no longer than what + // the player expects, which a later sample's buffers may be. + const uint32_t channel_count = self->base.channel_count; + const uint32_t max_samples = self->base.max_buffer_length / sample_bytes / channel_count * channel_count; + uint32_t n = MIN(self->sample_buffer_length, max_samples); + tap_capture(self, self->sample_remaining_buffer, n); + *buffer = self->sample_remaining_buffer; + *buffer_length = n * sample_bytes; + self->sample_remaining_buffer += n * sample_bytes; + self->sample_buffer_length -= n; + return GET_BUFFER_MORE_DATA; +} diff --git a/shared-module/audiotap/Tap.h b/shared-module/audiotap/Tap.h new file mode 100644 index 00000000000..acad4dda132 --- /dev/null +++ b/shared-module/audiotap/Tap.h @@ -0,0 +1,58 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT +#pragma once + +#include "py/obj.h" + +#include "shared-module/audiocore/__init__.h" + +extern const mp_obj_type_t audiotap_tap_type; + +struct audiotap_levelreader_obj; + +typedef struct { + audiosample_base_t base; + + // Played while there is no audio to pass through. Allocated, like the + // ring, when the first sample is played, which also sets the format. + int8_t *silence; + uint32_t silence_len; // in bytes + + // The part of the source's buffer not passed through yet. It stays the + // source's until the source is asked for its next buffer. + uint8_t *sample_remaining_buffer; + uint32_t sample_buffer_length; // in samples + + bool loop; + bool more_data; + + mp_obj_t sample; + + // A copy of the audio that passed through, for readinto(). Whatever plays + // the tap writes it, from a background task or an interrupt, and the VM + // reads it, so each side moves only its own position. Both positions run + // from 0 to 2 * capacity, which tells a full ring from an empty one. + mp_float_t capacity_seconds; + uint8_t *ring; + uint32_t capacity; // in samples, a whole number of frames + volatile uint32_t write_pos; + volatile uint32_t read_pos; + // Audio was dropped because the ring was full. Cleared when read. + volatile bool overflow; + + // Measures the audio that passes through, when a LevelReader is attached. + struct audiotap_levelreader_obj *volatile levels; +} audiotap_tap_obj_t; + +void audiotap_tap_reset_buffer(audiotap_tap_obj_t *self, + bool single_channel_output, + uint8_t channel); + +audioio_get_buffer_result_t audiotap_tap_get_buffer(audiotap_tap_obj_t *self, + bool single_channel_output, + uint8_t channel, + uint8_t **buffer, + uint32_t *buffer_length); // length in bytes diff --git a/shared-module/audiotap/__init__.c b/shared-module/audiotap/__init__.c new file mode 100644 index 00000000000..c10944ee211 --- /dev/null +++ b/shared-module/audiotap/__init__.c @@ -0,0 +1,8 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// Nothing to do here. The module's only state is in its Tap and LevelReader +// objects. diff --git a/shared-module/aurora_epaper/aurora_framebuffer.c b/shared-module/aurora_epaper/aurora_framebuffer.c index 65b08e15b1c..649f5a7df3f 100644 --- a/shared-module/aurora_epaper/aurora_framebuffer.c +++ b/shared-module/aurora_epaper/aurora_framebuffer.c @@ -69,34 +69,28 @@ void common_hal_aurora_epaper_framebuffer_construct( // CS 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); - common_hal_never_reset_pin(chip_select); // RST common_hal_digitalio_digitalinout_construct(&self->reset, reset); common_hal_digitalio_digitalinout_switch_to_output(&self->reset, true, DRIVE_MODE_PUSH_PULL); - common_hal_never_reset_pin(reset); // BUSY common_hal_digitalio_digitalinout_construct(&self->busy, busy); common_hal_digitalio_digitalinout_switch_to_input(&self->busy, PULL_NONE); - common_hal_never_reset_pin(busy); // DC common_hal_digitalio_digitalinout_construct(&self->discharge, discharge); common_hal_digitalio_digitalinout_switch_to_output(&self->discharge, true, DRIVE_MODE_PUSH_PULL); - common_hal_never_reset_pin(discharge); // Power pin (if set) if (power != NULL) { common_hal_digitalio_digitalinout_construct(&self->power, power); common_hal_digitalio_digitalinout_switch_to_output(&self->power, true, DRIVE_MODE_PUSH_PULL); - common_hal_never_reset_pin(power); } else { self->power.pin = NULL; } self->bus = spi; - common_hal_busio_spi_never_reset(self->bus); self->width = width; self->height = height; @@ -535,13 +529,11 @@ void common_hal_aurora_epaper_framebuffer_deinit(aurora_epaper_framebuffer_obj_t common_hal_busio_spi_deinit(self->bus); } - common_hal_reset_pin(self->chip_select.pin); - common_hal_reset_pin(self->reset.pin); - common_hal_reset_pin(self->busy.pin); - common_hal_reset_pin(self->discharge.pin); - if (self->power.pin != NULL) { - common_hal_reset_pin(self->power.pin); - } + common_hal_digitalio_digitalinout_deinit(&self->chip_select); + common_hal_digitalio_digitalinout_deinit(&self->reset); + common_hal_digitalio_digitalinout_deinit(&self->busy); + common_hal_digitalio_digitalinout_deinit(&self->discharge); + common_hal_digitalio_digitalinout_deinit(&self->power); port_free(self->bufinfo.buf); port_free(self->pframe.buf); diff --git a/shared-module/bitbangio/I2C.c b/shared-module/bitbangio/I2C.c index 0089bdc1e1e..f88dd04ee62 100644 --- a/shared-module/bitbangio/I2C.c +++ b/shared-module/bitbangio/I2C.c @@ -8,10 +8,15 @@ #include "py/mperrno.h" #include "py/obj.h" #include "py/runtime.h" +#include "py/gc.h" #include "common-hal/microcontroller/Pin.h" #include "shared-bindings/microcontroller/__init__.h" +#include "shared-bindings/microcontroller/Pin.h" #include "shared-bindings/digitalio/DigitalInOut.h" +#include "shared-bindings/digitalio/DigitalInOutProtocol.h" +#include "shared-bindings/util.h" +#include "supervisor/port.h" static void delay(bitbangio_i2c_obj_t *self) { // We need to use an accurate delay to get acceptable I2C @@ -19,61 +24,81 @@ static void delay(bitbangio_i2c_obj_t *self) { common_hal_mcu_delay_us(self->us_delay); } -static void scl_low(bitbangio_i2c_obj_t *self) { - common_hal_digitalio_digitalinout_set_value(&self->scl, false); +static bool scl_low(bitbangio_i2c_obj_t *self) { + return digitalinout_protocol_set_value(self->scl, false) == 0; } -static void scl_release(bitbangio_i2c_obj_t *self) { - common_hal_digitalio_digitalinout_set_value(&self->scl, true); +static bool scl_release(bitbangio_i2c_obj_t *self) { + if (digitalinout_protocol_set_value(self->scl, true) != 0) { + return false; + } uint32_t count = self->us_timeout; delay(self); // For clock stretching, wait for the SCL pin to be released, with timeout. - common_hal_digitalio_digitalinout_switch_to_input(&self->scl, PULL_UP); - for (; !common_hal_digitalio_digitalinout_get_value(&self->scl) && count; --count) { + digitalinout_protocol_switch_to_input(self->scl, PULL_UP); + bool value; + for (; count; --count) { + if (digitalinout_protocol_get_value(self->scl, &value) != 0) { + return false; + } + if (value) { + break; + } common_hal_mcu_delay_us(1); } - common_hal_digitalio_digitalinout_switch_to_output(&self->scl, true, DRIVE_MODE_OPEN_DRAIN); + digitalinout_protocol_switch_to_output(self->scl, true, DRIVE_MODE_OPEN_DRAIN); // raise exception on timeout if (count == 0) { mp_raise_msg_varg(&mp_type_TimeoutError, MP_ERROR_TEXT("%q too long"), MP_QSTR_timeout); } + return true; } -static void sda_low(bitbangio_i2c_obj_t *self) { - common_hal_digitalio_digitalinout_set_value(&self->sda, false); +static bool sda_low(bitbangio_i2c_obj_t *self) { + return digitalinout_protocol_set_value(self->sda, false) == 0; } -static void sda_release(bitbangio_i2c_obj_t *self) { - common_hal_digitalio_digitalinout_set_value(&self->sda, true); +static bool sda_release(bitbangio_i2c_obj_t *self) { + return digitalinout_protocol_set_value(self->sda, true) == 0; } -static bool sda_read(bitbangio_i2c_obj_t *self) { - common_hal_digitalio_digitalinout_switch_to_input(&self->sda, PULL_UP); - bool value = common_hal_digitalio_digitalinout_get_value(&self->sda); - common_hal_digitalio_digitalinout_switch_to_output(&self->sda, true, DRIVE_MODE_OPEN_DRAIN); - return value; +static bool sda_read(bitbangio_i2c_obj_t *self, bool *value) { + digitalinout_protocol_switch_to_input(self->sda, PULL_UP); + if (digitalinout_protocol_get_value(self->sda, value) != 0) { + return false; + } + digitalinout_protocol_switch_to_output(self->sda, true, DRIVE_MODE_OPEN_DRAIN); + return true; } -static void start(bitbangio_i2c_obj_t *self) { - sda_release(self); +static bool start(bitbangio_i2c_obj_t *self) { + if (!sda_release(self)) { + return false; + } delay(self); scl_release(self); sda_low(self); delay(self); + return true; } -static void stop(bitbangio_i2c_obj_t *self) { +static bool stop(bitbangio_i2c_obj_t *self) { delay(self); - sda_low(self); + if (!sda_low(self)) { + return false; + } delay(self); scl_release(self); sda_release(self); delay(self); + return true; } static int write_byte(bitbangio_i2c_obj_t *self, uint8_t val) { delay(self); - scl_low(self); + if (!scl_low(self)) { + return -1; + } for (int i = 7; i >= 0; i--) { if ((val >> i) & 1) { @@ -90,7 +115,10 @@ static int write_byte(bitbangio_i2c_obj_t *self, uint8_t val) { delay(self); scl_release(self); - int ret = sda_read(self); + bool ret; + if (!sda_read(self, &ret)) { + return -1; + } delay(self); scl_low(self); @@ -99,13 +127,17 @@ static int write_byte(bitbangio_i2c_obj_t *self, uint8_t val) { static bool read_byte(bitbangio_i2c_obj_t *self, uint8_t *val, bool ack) { delay(self); - scl_low(self); + if (!scl_low(self)) { + return false; + } delay(self); uint8_t data = 0; for (int i = 7; i >= 0; i--) { scl_release(self); - data = (data << 1) | sda_read(self); + bool bit; + sda_read(self, &bit); + data = (data << 1) | bit; scl_low(self); delay(self); } @@ -123,43 +155,73 @@ static bool read_byte(bitbangio_i2c_obj_t *self, uint8_t *val, bool ack) { return true; } +static void mark_deinit(bitbangio_i2c_obj_t *self) { + self->scl = MP_OBJ_NULL; + self->sda = MP_OBJ_NULL; + self->own_scl = false; + self->own_sda = false; +} + void shared_module_bitbangio_i2c_construct(bitbangio_i2c_obj_t *self, - const mcu_pin_obj_t *scl, - const mcu_pin_obj_t *sda, + mp_obj_t scl, + mp_obj_t sda, uint32_t frequency, uint32_t us_timeout) { + mark_deinit(self); + self->us_timeout = us_timeout; self->us_delay = 500000 / frequency; if (self->us_delay == 0) { self->us_delay = 1; } - digitalinout_result_t result = common_hal_digitalio_digitalinout_construct(&self->scl, scl); - if (result != DIGITALINOUT_OK) { - return; - } - result = common_hal_digitalio_digitalinout_construct(&self->sda, sda); - if (result != DIGITALINOUT_OK) { - common_hal_digitalio_digitalinout_deinit(&self->scl); - return; - } - common_hal_digitalio_digitalinout_switch_to_output(&self->scl, true, DRIVE_MODE_OPEN_DRAIN); - common_hal_digitalio_digitalinout_switch_to_output(&self->sda, true, DRIVE_MODE_OPEN_DRAIN); - stop(self); + // Allocate the pins in the same place as self. + bool use_port_allocation = !gc_alloc_possible() || !gc_ptr_on_heap(self); + + // Convert scl from Pin to DigitalInOutProtocol + self->scl = digitalinout_protocol_from_pin(scl, MP_QSTR_scl, false, use_port_allocation, &self->own_scl); + + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + // Convert sda from Pin to DigitalInOutProtocol + bool own_sda; + self->sda = digitalinout_protocol_from_pin(sda, MP_QSTR_sda, false, use_port_allocation, &own_sda); + self->own_sda = own_sda; + + digitalinout_protocol_switch_to_output(self->scl, true, DRIVE_MODE_OPEN_DRAIN); + digitalinout_protocol_switch_to_output(self->sda, true, DRIVE_MODE_OPEN_DRAIN); + + if (!stop(self)) { + mp_raise_OSError(MP_EIO); + } + nlr_pop(); + } else { + shared_module_bitbangio_i2c_deinit(self); + nlr_jump(nlr.ret_val); + } } bool shared_module_bitbangio_i2c_deinited(bitbangio_i2c_obj_t *self) { // If one is deinited, both will be. - return common_hal_digitalio_digitalinout_deinited(&self->scl); + return self->scl == MP_OBJ_NULL; } void shared_module_bitbangio_i2c_deinit(bitbangio_i2c_obj_t *self) { if (shared_module_bitbangio_i2c_deinited(self)) { return; } - common_hal_digitalio_digitalinout_deinit(&self->scl); - common_hal_digitalio_digitalinout_deinit(&self->sda); + // Only deinit and free the pins if we own them + if (self->own_scl) { + digitalinout_protocol_deinit(self->scl); + circuitpy_free_obj(self->scl); + } + if (self->own_sda) { + digitalinout_protocol_deinit(self->sda); + circuitpy_free_obj(self->sda); + } + // Mark deinited; the pin objects may have been freed above. + mark_deinit(self); } bool shared_module_bitbangio_i2c_try_lock(bitbangio_i2c_obj_t *self) { @@ -182,24 +244,34 @@ void shared_module_bitbangio_i2c_unlock(bitbangio_i2c_obj_t *self) { } bool shared_module_bitbangio_i2c_probe(bitbangio_i2c_obj_t *self, uint8_t addr) { - start(self); - bool ok = write_byte(self, addr << 1); + if (!start(self)) { + mp_raise_OSError(MP_EIO); + } + int result = write_byte(self, addr << 1); stop(self); - return ok; + if (result < 0) { + mp_raise_OSError(MP_EIO); + } + return result; } 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) { // start the I2C transaction - start(self); + if (!start(self)) { + return MP_EIO; + } uint8_t status = 0; - if (!write_byte(self, addr << 1)) { + int result = write_byte(self, addr << 1); + if (result < 0) { + status = MP_EIO; + } else if (!result) { status = MP_ENODEV; } if (status == 0) { for (uint32_t i = 0; i < len; i++) { - if (!write_byte(self, data[i])) { + if (write_byte(self, data[i]) <= 0) { status = MP_EIO; break; } @@ -215,9 +287,14 @@ 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) { // start the I2C transaction - start(self); + if (!start(self)) { + return MP_EIO; + } uint8_t status = 0; - if (!write_byte(self, (addr << 1) | 1)) { + int addr_result = write_byte(self, (addr << 1) | 1); + if (addr_result < 0) { + status = MP_EIO; + } else if (!addr_result) { status = MP_ENODEV; } diff --git a/shared-module/bitbangio/I2C.h b/shared-module/bitbangio/I2C.h index 3908a3dd374..0cec9186e9b 100644 --- a/shared-module/bitbangio/I2C.h +++ b/shared-module/bitbangio/I2C.h @@ -12,9 +12,11 @@ typedef struct { mp_obj_base_t base; - digitalio_digitalinout_obj_t scl; - digitalio_digitalinout_obj_t sda; + mp_obj_t scl; + mp_obj_t sda; uint32_t us_delay; uint32_t us_timeout; volatile bool locked; + bool own_scl; + bool own_sda; } bitbangio_i2c_obj_t; diff --git a/shared-module/bitbangio/SPI.c b/shared-module/bitbangio/SPI.c index 56e978985ed..7af84089510 100644 --- a/shared-module/bitbangio/SPI.c +++ b/shared-module/bitbangio/SPI.c @@ -7,65 +7,69 @@ #include "py/mpconfig.h" #include "py/obj.h" #include "py/runtime.h" +#include "py/gc.h" #include "common-hal/microcontroller/Pin.h" #include "shared-bindings/bitbangio/SPI.h" #include "shared-bindings/digitalio/DigitalInOut.h" +#include "shared-bindings/digitalio/DigitalInOutProtocol.h" #include "shared-bindings/microcontroller/__init__.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/util.h" +#include "supervisor/port.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) { - digitalinout_result_t result = common_hal_digitalio_digitalinout_construct(&self->clock, clock); - if (result != DIGITALINOUT_OK) { - mp_raise_ValueError_varg(MP_ERROR_TEXT("%q init failed"), MP_QSTR_clock); - } - common_hal_digitalio_digitalinout_switch_to_output(&self->clock, self->polarity == 1, DRIVE_MODE_PUSH_PULL); + mp_obj_t clock, mp_obj_t mosi, mp_obj_t miso) { - if (mosi != NULL) { - result = common_hal_digitalio_digitalinout_construct(&self->mosi, mosi); - if (result != DIGITALINOUT_OK) { - common_hal_digitalio_digitalinout_deinit(&self->clock); - mp_raise_ValueError_varg(MP_ERROR_TEXT("%q init failed"), MP_QSTR_mosi); - } - self->has_mosi = true; - common_hal_digitalio_digitalinout_switch_to_output(&self->mosi, false, DRIVE_MODE_PUSH_PULL); - } + // Allocate the pins in the same place as self. + bool use_port_allocation = !gc_alloc_possible() || !gc_ptr_on_heap(self); - if (miso != NULL) { - // Starts out as input by default, no need to change. - result = common_hal_digitalio_digitalinout_construct(&self->miso, miso); - if (result != DIGITALINOUT_OK) { - common_hal_digitalio_digitalinout_deinit(&self->clock); - if (mosi != NULL) { - common_hal_digitalio_digitalinout_deinit(&self->mosi); - } - mp_raise_ValueError_varg(MP_ERROR_TEXT("%q init failed"), MP_QSTR_miso); - } - self->has_miso = true; + // Convert clock from Pin to DigitalInOutProtocol + self->clock = digitalinout_protocol_from_pin(clock, MP_QSTR_clock, false, use_port_allocation, &self->own_clock); + digitalinout_protocol_switch_to_output(self->clock, self->polarity == 1, DRIVE_MODE_PUSH_PULL); + + // Convert mosi from Pin to DigitalInOutProtocol (optional) + self->mosi = digitalinout_protocol_from_pin(mosi, MP_QSTR_mosi, true, use_port_allocation, &self->own_mosi); + self->has_mosi = (self->mosi != mp_const_none); + if (self->has_mosi) { + digitalinout_protocol_switch_to_output(self->mosi, false, DRIVE_MODE_PUSH_PULL); } + + // Convert miso from Pin to DigitalInOutProtocol (optional) + self->miso = digitalinout_protocol_from_pin(miso, MP_QSTR_miso, true, use_port_allocation, &self->own_miso); + self->has_miso = (self->miso != mp_const_none); + // MISO starts out as input by default, no need to change + self->delay_half = 5; self->polarity = 0; self->phase = 0; } bool shared_module_bitbangio_spi_deinited(bitbangio_spi_obj_t *self) { - return common_hal_digitalio_digitalinout_deinited(&self->clock); + return self->clock == MP_OBJ_NULL; } void shared_module_bitbangio_spi_deinit(bitbangio_spi_obj_t *self) { if (shared_module_bitbangio_spi_deinited(self)) { return; } - common_hal_digitalio_digitalinout_deinit(&self->clock); - if (self->has_mosi) { - common_hal_digitalio_digitalinout_deinit(&self->mosi); + // Only deinit and free the pins if we own them + if (self->own_clock) { + digitalinout_protocol_deinit(self->clock); + circuitpy_free_obj(self->clock); + } + if (self->has_mosi && self->own_mosi) { + digitalinout_protocol_deinit(self->mosi); + circuitpy_free_obj(self->mosi); } - if (self->has_miso) { - common_hal_digitalio_digitalinout_deinit(&self->miso); + if (self->has_miso && self->own_miso) { + digitalinout_protocol_deinit(self->miso); + circuitpy_free_obj(self->miso); } + // Mark deinited; the pin objects may have been freed above. + self->clock = MP_OBJ_NULL; } void shared_module_bitbangio_spi_configure(bitbangio_spi_obj_t *self, @@ -80,7 +84,7 @@ void shared_module_bitbangio_spi_configure(bitbangio_spi_obj_t *self, // If the polarity has changed, make sure we re-initialize the idle state // of the clock as well. self->polarity = polarity; - common_hal_digitalio_digitalinout_switch_to_output(&self->clock, polarity == 1, DRIVE_MODE_PUSH_PULL); + digitalinout_protocol_switch_to_output(self->clock, polarity == 1, DRIVE_MODE_PUSH_PULL); } self->phase = phase; } @@ -121,9 +125,15 @@ bool shared_module_bitbangio_spi_write(bitbangio_spi_obj_t *self, const uint8_t for (size_t i = 0; i < len; ++i) { uint8_t data_out = data[i]; for (int j = 0; j < 8; ++j, data_out <<= 1) { - common_hal_digitalio_digitalinout_set_value(&self->mosi, (data_out >> 7) & 1); - common_hal_digitalio_digitalinout_set_value(&self->clock, 1 - self->polarity); - common_hal_digitalio_digitalinout_set_value(&self->clock, self->polarity); + if (i == 0 && j == 0) { + if (digitalinout_protocol_set_value(self->mosi, (data_out >> 7) & 1) != 0) { + return false; + } + } else { + digitalinout_protocol_set_value(self->mosi, (data_out >> 7) & 1); + } + digitalinout_protocol_set_value(self->clock, 1 - self->polarity); + digitalinout_protocol_set_value(self->clock, self->polarity); } if (dest != NULL) { dest[i] = data_in; @@ -136,16 +146,22 @@ bool shared_module_bitbangio_spi_write(bitbangio_spi_obj_t *self, const uint8_t for (size_t i = 0; i < len; ++i) { uint8_t data_out = data[i]; for (int j = 0; j < 8; ++j, data_out <<= 1) { - common_hal_digitalio_digitalinout_set_value(&self->mosi, (data_out >> 7) & 1); + if (i == 0 && j == 0) { + if (digitalinout_protocol_set_value(self->mosi, (data_out >> 7) & 1) != 0) { + return false; + } + } else { + digitalinout_protocol_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); + digitalinout_protocol_set_value(self->clock, 1 - self->polarity); common_hal_mcu_delay_us(delay_half); - common_hal_digitalio_digitalinout_set_value(&self->clock, self->polarity); + digitalinout_protocol_set_value(self->clock, self->polarity); } else { - common_hal_digitalio_digitalinout_set_value(&self->clock, 1 - self->polarity); + digitalinout_protocol_set_value(self->clock, 1 - self->polarity); common_hal_mcu_delay_us(delay_half); - common_hal_digitalio_digitalinout_set_value(&self->clock, self->polarity); + digitalinout_protocol_set_value(self->clock, self->polarity); common_hal_mcu_delay_us(delay_half); } } @@ -176,14 +192,18 @@ bool shared_module_bitbangio_spi_read(bitbangio_spi_obj_t *self, uint8_t *data, if (delay_half <= MICROPY_PY_MACHINE_SPI_MIN_DELAY) { // Clock out zeroes while we read. if (self->has_mosi) { - common_hal_digitalio_digitalinout_set_value(&self->mosi, false); + if (digitalinout_protocol_set_value(self->mosi, false) != 0) { + return false; + } } for (size_t i = 0; i < len; ++i) { uint8_t data_in = 0; for (int j = 0; j < 8; ++j, data_out <<= 1) { - common_hal_digitalio_digitalinout_set_value(&self->clock, 1 - self->polarity); - data_in = (data_in << 1) | common_hal_digitalio_digitalinout_get_value(&self->miso); - common_hal_digitalio_digitalinout_set_value(&self->clock, self->polarity); + digitalinout_protocol_set_value(self->clock, 1 - self->polarity); + bool bit; + digitalinout_protocol_get_value(self->miso, &bit); + data_in = (data_in << 1) | bit; + digitalinout_protocol_set_value(self->clock, self->polarity); } data[i] = data_in; } @@ -191,28 +211,32 @@ bool shared_module_bitbangio_spi_read(bitbangio_spi_obj_t *self, uint8_t *data, } #endif if (self->has_mosi) { - common_hal_digitalio_digitalinout_set_value(&self->mosi, false); + if (digitalinout_protocol_set_value(self->mosi, false) != 0) { + return 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, data_out <<= 1) { if (self->has_mosi) { - common_hal_digitalio_digitalinout_set_value(&self->mosi, (data_out >> 7) & 1); + digitalinout_protocol_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); + digitalinout_protocol_set_value(self->clock, 1 - self->polarity); } else { - common_hal_digitalio_digitalinout_set_value(&self->clock, 1 - self->polarity); + digitalinout_protocol_set_value(self->clock, 1 - self->polarity); common_hal_mcu_delay_us(delay_half); } - data_in = (data_in << 1) | common_hal_digitalio_digitalinout_get_value(&self->miso); + bool bit; + digitalinout_protocol_get_value(self->miso, &bit); + data_in = (data_in << 1) | bit; if (self->phase == 0) { common_hal_mcu_delay_us(delay_half); - common_hal_digitalio_digitalinout_set_value(&self->clock, self->polarity); + digitalinout_protocol_set_value(self->clock, self->polarity); } else { - common_hal_digitalio_digitalinout_set_value(&self->clock, self->polarity); + digitalinout_protocol_set_value(self->clock, self->polarity); common_hal_mcu_delay_us(delay_half); } } @@ -248,10 +272,18 @@ bool shared_module_bitbangio_spi_transfer(bitbangio_spi_obj_t *self, const uint8 uint8_t data_out = dout[i]; uint8_t data_in = 0; for (int j = 0; j < 8; ++j, data_out <<= 1) { - common_hal_digitalio_digitalinout_set_value(&self->mosi, (data_out >> 7) & 1); - common_hal_digitalio_digitalinout_set_value(&self->clock, 1 - self->polarity); - data_in = (data_in << 1) | common_hal_digitalio_digitalinout_get_value(&self->miso); - common_hal_digitalio_digitalinout_set_value(&self->clock, self->polarity); + if (i == 0 && j == 0) { + if (digitalinout_protocol_set_value(self->mosi, (data_out >> 7) & 1) != 0) { + return false; + } + } else { + digitalinout_protocol_set_value(self->mosi, (data_out >> 7) & 1); + } + digitalinout_protocol_set_value(self->clock, 1 - self->polarity); + bool bit; + digitalinout_protocol_get_value(self->miso, &bit); + data_in = (data_in << 1) | bit; + digitalinout_protocol_set_value(self->clock, self->polarity); } din[i] = data_in; @@ -267,20 +299,28 @@ bool shared_module_bitbangio_spi_transfer(bitbangio_spi_obj_t *self, const uint8 uint8_t data_out = dout[i]; uint8_t data_in = 0; for (int j = 0; j < 8; ++j, data_out <<= 1) { - common_hal_digitalio_digitalinout_set_value(&self->mosi, (data_out >> 7) & 1); + if (i == 0 && j == 0) { + if (digitalinout_protocol_set_value(self->mosi, (data_out >> 7) & 1) != 0) { + return false; + } + } else { + digitalinout_protocol_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); + digitalinout_protocol_set_value(self->clock, 1 - self->polarity); } else { - common_hal_digitalio_digitalinout_set_value(&self->clock, 1 - self->polarity); + digitalinout_protocol_set_value(self->clock, 1 - self->polarity); common_hal_mcu_delay_us(delay_half); } - data_in = (data_in << 1) | common_hal_digitalio_digitalinout_get_value(&self->miso); + bool bit; + digitalinout_protocol_get_value(self->miso, &bit); + data_in = (data_in << 1) | bit; if (self->phase == 0) { common_hal_mcu_delay_us(delay_half); - common_hal_digitalio_digitalinout_set_value(&self->clock, self->polarity); + digitalinout_protocol_set_value(self->clock, self->polarity); } else { - common_hal_digitalio_digitalinout_set_value(&self->clock, self->polarity); + digitalinout_protocol_set_value(self->clock, self->polarity); common_hal_mcu_delay_us(delay_half); } } diff --git a/shared-module/bitbangio/SPI.h b/shared-module/bitbangio/SPI.h index c19170af7c4..5f3c109b7f6 100644 --- a/shared-module/bitbangio/SPI.h +++ b/shared-module/bitbangio/SPI.h @@ -12,13 +12,16 @@ typedef struct { mp_obj_base_t base; - digitalio_digitalinout_obj_t clock; - digitalio_digitalinout_obj_t mosi; - digitalio_digitalinout_obj_t miso; + mp_obj_t clock; + mp_obj_t mosi; + mp_obj_t miso; uint32_t delay_half; bool has_miso : 1; bool has_mosi : 1; uint8_t polarity : 1; uint8_t phase : 1; volatile bool locked : 1; + bool own_clock; + bool own_mosi; + bool own_miso; } bitbangio_spi_obj_t; diff --git a/shared-module/bitmapfilter/__init__.c b/shared-module/bitmapfilter/__init__.c index cdce674628c..2a54ab7443b 100644 --- a/shared-module/bitmapfilter/__init__.c +++ b/shared-module/bitmapfilter/__init__.c @@ -21,7 +21,7 @@ #include #define port_free free #define port_malloc(sz, hint) (malloc(sz)) -#define port_realloc realloc +#define port_realloc(ptr, size, dma_capable) realloc(ptr, size) #else #include "supervisor/port_heap.h" #endif @@ -48,7 +48,7 @@ static void *scratchpad_alloc(size_t sz) { } else { if (scratchpad) { if (sz > scratchpad_size) { - void *tmp = port_realloc(scratchpad, sz); + void *tmp = port_realloc(scratchpad, sz, false); if (!tmp) { port_free(scratchpad); scratchpad = NULL; diff --git a/shared-module/bitmaptools/__init__.c b/shared-module/bitmaptools/__init__.c index 8a41e387e51..0116b6810aa 100644 --- a/shared-module/bitmaptools/__init__.c +++ b/shared-module/bitmaptools/__init__.c @@ -23,6 +23,145 @@ #define BITMAP_DEBUG(...) (void)0 // #define BITMAP_DEBUG(...) mp_printf(&mp_plat_print, __VA_ARGS__) +#if CIRCUITPY_BITMAPTOOLS_FAST_ROTOZOOM +#include "shared-module/bitmaptools/__init__.h" + +// Fixed-point path for rotozoom. +// +// The generic loop walks the source in mp_float_t and truncates to pick each source +// pixel. A 16.16 fixed-point walk picks the same pixels when every one of those float +// operations is exact: no rotation (u depends only on x, v only on y), and the steps and +// start points are multiples of 2^-k with every intermediate value below 2^(24-k). + +#define ROTOZOOM_FRACTION_BITS 16 + +// Store f * 2^16 in *fixed if that is an integer with |value| < 2^31. Returns false +// otherwise (NaN and inf included). +static bool rotozoom_to_fixed(mp_float_t f, int32_t *fixed) { + // Exact: scaling by a power of two. + mp_float_t scaled = f * MICROPY_FLOAT_CONST(65536.0); + if (!(scaled > MICROPY_FLOAT_CONST(-2147483648.0) && scaled < MICROPY_FLOAT_CONST(2147483648.0))) { + return false; + } + int32_t value = (int32_t)scaled; + if ((mp_float_t)value < scaled || (mp_float_t)value > scaled) { + return false; + } + *fixed = value; + return true; +} + +MP_WEAK void bitmaptools_rotozoom_row(void *dest_pixels, const void *source_row, + uint32_t u, uint32_t du, int count, uint8_t bits_per_value, + uint32_t skip_index, bool skip_index_none) { + if (bits_per_value == 16) { + uint16_t *dest = dest_pixels; + const uint16_t *source = source_row; + for (int i = 0; i < count; i++, u += du) { + uint16_t pixel = source[u >> ROTOZOOM_FRACTION_BITS]; + if (skip_index_none || pixel != skip_index) { + dest[i] = pixel; + } + } + } else { + uint8_t *dest = dest_pixels; + const uint8_t *source = source_row; + for (int i = 0; i < count; i++, u += du) { + uint8_t pixel = source[u >> ROTOZOOM_FRACTION_BITS]; + if (skip_index_none || pixel != skip_index) { + dest[i] = pixel; + } + } + } +} + +// Returns true when it has written every pixel the generic loop would write, and false, +// with nothing written, when the walk would not be exact. +static bool rotozoom_fixed_point(displayio_bitmap_t *dest, + int16_t minx, int16_t miny, int16_t maxx, int16_t maxy, + displayio_bitmap_t *source, + int16_t source_clip0_x, int16_t source_clip0_y, + int16_t source_clip1_x, int16_t source_clip1_y, + mp_float_t duRow, mp_float_t dvRow, mp_float_t duCol, mp_float_t dvCol, + mp_float_t startu, mp_float_t startv, + uint32_t skip_index, bool skip_index_none) { + + // No rotation: u must not change down a column and v must not change along a row. + // Range tests because -Wfloat-equal forbids ==; NaN fails them. + if (!(duCol >= 0 && duCol <= 0) || !(dvRow >= 0 && dvRow <= 0) + || !(duRow > 0) || !(dvCol > 0)) { + return false; + } + uint8_t bits_per_value = source->bits_per_value; + if (bits_per_value != dest->bits_per_value || (bits_per_value != 8 && bits_per_value != 16)) { + return false; + } + if (minx > maxx || miny > maxy) { + return false; + } + + int32_t u_step, v_step, u_start, v_start; + if (!rotozoom_to_fixed(duRow, &u_step) || !rotozoom_to_fixed(dvCol, &v_step) + || !rotozoom_to_fixed(startu, &u_start) || !rotozoom_to_fixed(startv, &v_start)) { + return false; + } + + // Every value the generic loop computes is a multiple of 2^-fraction_bits, so it is + // exact while below 2^(24 - fraction_bits), which is 2^(40 - fraction_bits) in 16.16 + // units. u and v are linear in x and y, so the end points bound them. The generic + // loop computes u = startu + minx * duRow, then adds duRow up to maxx + 1; v likewise + // down the rows. The lowest set bit of the four values sets fraction_bits, and + // u_step > 0, so the OR is not zero. + uint32_t all_bits = (uint32_t)(u_step | v_step | u_start | v_start); + int fraction_bits = MAX(0, ROTOZOOM_FRACTION_BITS - __builtin_ctz(all_bits)); + int64_t limit = (int64_t)1 << (40 - fraction_bits); + int64_t ends[] = { + (int64_t)minx * u_step, u_start + (int64_t)minx * u_step, u_start + ((int64_t)maxx + 1) * u_step, + (int64_t)miny * v_step, v_start + (int64_t)miny * v_step, v_start + ((int64_t)maxy + 1) * v_step, + }; + for (size_t i = 0; i < MP_ARRAY_SIZE(ends); i++) { + if (ends[i] <= -limit || ends[i] >= limit) { + return false; + } + } + + // u rises with x, so the columns that sample inside the source clip are one run, the + // same on every row. The clips are within the bitmap, so every sampled pixel is in + // bounds and u, v are >= 0 there. + int64_t clip_u_start = (int64_t)source_clip0_x << ROTOZOOM_FRACTION_BITS; + int64_t clip_u_end = (int64_t)source_clip1_x << ROTOZOOM_FRACTION_BITS; + int64_t clip_v_start = (int64_t)source_clip0_y << ROTOZOOM_FRACTION_BITS; + int64_t clip_v_end = (int64_t)source_clip1_y << ROTOZOOM_FRACTION_BITS; + int32_t x_first = minx; + while (x_first <= maxx && u_start + (int64_t)x_first * u_step < clip_u_start) { + x_first++; + } + int32_t x_last = maxx; + while (x_last >= x_first && u_start + (int64_t)x_last * u_step >= clip_u_end) { + x_last--; + } + if (x_first > x_last) { + // No column samples the source, so the generic loop writes nothing either. + return true; + } + // In [clip_u_start, clip_u_end), so below 2^31. + uint32_t u_first = (uint32_t)(u_start + (int64_t)x_first * u_step); + size_t bytes_per_value = bits_per_value / 8; + + for (int32_t y = miny; y <= maxy; y++) { + int64_t v = v_start + (int64_t)y * v_step; + if (v < clip_v_start || v >= clip_v_end) { + continue; + } + const uint32_t *source_row = source->data + (v >> ROTOZOOM_FRACTION_BITS) * source->stride; + uint8_t *dest_pixels = (uint8_t *)(dest->data + y * dest->stride) + x_first * bytes_per_value; + bitmaptools_rotozoom_row(dest_pixels, source_row, u_first, u_step, + x_last - x_first + 1, bits_per_value, skip_index, skip_index_none); + } + return true; +} +#endif + 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, @@ -183,9 +322,17 @@ void common_hal_bitmaptools_rotozoom(displayio_bitmap_t *self, int16_t ox, int16 mp_float_t rowu = startu + miny * duCol; mp_float_t rowv = startv + miny * dvCol; - displayio_area_t dirty_area = {minx, miny, maxx + 1, maxy + 1, NULL}; + displayio_area_t dirty_area = {minx, miny, maxx + 1, maxy + 1 }; displayio_bitmap_set_dirty_area(self, &dirty_area); + #if CIRCUITPY_BITMAPTOOLS_FAST_ROTOZOOM + if (rotozoom_fixed_point(self, minx, miny, maxx, maxy, source, + source_clip0_x, source_clip0_y, source_clip1_x, source_clip1_y, + duRow, dvRow, duCol, dvCol, startu, startv, skip_index, skip_index_none)) { + return; + } + #endif + for (y = miny; y <= maxy; y++) { mp_float_t u = rowu + minx * duRow; mp_float_t v = rowv + minx * dvRow; @@ -204,6 +351,21 @@ void common_hal_bitmaptools_rotozoom(displayio_bitmap_t *self, int16_t ox, int16 } } +void common_hal_bitmaptools_replace_color(displayio_bitmap_t *destination, + uint32_t old_color, + uint32_t new_color) { + + int16_t x, y; + for (x = 0; x < destination->width; x++) { + for (y = 0; y < destination->height; y++) { + uint32_t pixel_val = common_hal_displayio_bitmap_get_pixel(destination, x, y); + if (pixel_val == old_color) { + displayio_bitmap_write_pixel(destination, x, y, new_color); + } + } + } +} + void common_hal_bitmaptools_fill_region(displayio_bitmap_t *destination, int16_t x1, int16_t y1, int16_t x2, int16_t y2, @@ -212,10 +374,10 @@ void common_hal_bitmaptools_fill_region(displayio_bitmap_t *destination, // // input checks should ensure that x1 < x2 and y1 < y2 and are within the bitmap region - displayio_area_t area = { x1, y1, x2, y2, NULL }; + displayio_area_t area = { x1, y1, x2, y2 }; displayio_area_canon(&area); - displayio_area_t bitmap_area = { 0, 0, destination->width, destination->height, NULL }; + displayio_area_t bitmap_area = { 0, 0, destination->width, destination->height }; displayio_area_compute_overlap(&area, &bitmap_area, &area); // update the dirty rectangle @@ -367,7 +529,7 @@ void common_hal_bitmaptools_boundary_fill(displayio_bitmap_t *destination, } // set dirty the area so displayio will draw - displayio_area_t area = { minx, miny, maxx + 1, maxy + 1, NULL}; + displayio_area_t area = { minx, miny, maxx + 1, maxy + 1 }; displayio_bitmap_set_dirty_area(destination, &area); } @@ -475,8 +637,8 @@ void common_hal_bitmaptools_draw_line(displayio_bitmap_t *destination, ybb0 = y1; ybb1 = y0 + 1; } - displayio_area_t area = { xbb0, ybb0, xbb1, ybb1, NULL }; - displayio_area_t bitmap_area = { 0, 0, destination->width, destination->height, NULL }; + 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); @@ -522,8 +684,8 @@ void common_hal_bitmaptools_draw_polygon(displayio_bitmap_t *destination, void * draw_line(destination, xprev, yprev, x0, y0, value); } - displayio_area_t area = { xmin, ymin, xmax, ymax, NULL }; - displayio_area_t bitmap_area = { 0, 0, destination->width, destination->height, NULL }; + displayio_area_t area = { xmin, ymin, xmax + 1, ymax + 1 }; + 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); } @@ -554,16 +716,16 @@ void common_hal_bitmaptools_arrayblit(displayio_bitmap_t *self, void *data, int } } } - displayio_area_t area = { x1, y1, x2, y2, NULL }; + displayio_area_t area = { x1, y1, x2, y2 }; displayio_bitmap_set_dirty_area(self, &area); } void common_hal_bitmaptools_readinto(displayio_bitmap_t *self, mp_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; - const mp_stream_p_t *file_proto = mp_get_stream_raise(file, MP_STREAM_OP_READ); + mp_get_stream_raise(file, MP_STREAM_OP_READ); - displayio_area_t a = {0, 0, self->width, self->height, NULL}; + 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); @@ -578,8 +740,9 @@ void common_hal_bitmaptools_readinto(displayio_bitmap_t *self, mp_obj_t *file, i const int y_draw = reverse_rows ? (self->height) - 1 - y : y; + // A stream such as a socket can return part of a row, so read until the row is complete. int error = 0; - mp_uint_t bytes_read = file_proto->read(file, rowdata32, rowsize, &error); + mp_uint_t bytes_read = mp_stream_read_exactly(file, rowdata32, rowsize, &error); if (error) { mp_raise_OSError(error); } @@ -732,10 +895,10 @@ static void fill_row(displayio_bitmap_t *bitmap, int swap, int16_t *luminance_da static void write_pixels(displayio_bitmap_t *bitmap, int y, bool *data) { if (bitmap->bits_per_value == 1) { - uint32_t *pixel_data = (uint32_t *)(bitmap->data + bitmap->stride * y); - for (int i = 0; i < bitmap->width; i++) { - uint32_t p = 0; - for (int j = 0; j < 32; j++) { + uint8_t *pixel_data = (uint8_t *)(bitmap->data + bitmap->stride * y); + for (int i = 0; i < (bitmap->width + 7) / 8; i++) { + uint8_t p = 0; + for (int j = 0; j < 8; j++) { p = (p << 1); if (*data++) { p |= 1; @@ -772,6 +935,7 @@ void common_hal_bitmaptools_dither(displayio_bitmap_t *dest_bitmap, displayio_bi }; // out holds one output row of pixels, and is padded to be a multiple of 32 so that the 1bpp storage loop can be simplified bool out[(width + 31) / 32 * 32]; + memset(out + width, 0, sizeof(out) - width); fill_row(source_bitmap, swap, rows[0], 0, info->mx); fill_row(source_bitmap, swap, rows[1], 1, info->mx); @@ -837,17 +1001,20 @@ void common_hal_bitmaptools_dither(displayio_bitmap_t *dest_bitmap, displayio_bi fill_row(source_bitmap, swap, rows[2], y + 3, info->mx); } - displayio_area_t a = { 0, 0, width, height, NULL }; + displayio_area_t a = { 0, 0, width, height }; displayio_bitmap_set_dirty_area(dest_bitmap, &a); } void common_hal_bitmaptools_alphablend(displayio_bitmap_t *dest, displayio_bitmap_t *source1, displayio_bitmap_t *source2, displayio_colorspace_t colorspace, mp_float_t factor1, mp_float_t factor2, - bitmaptools_blendmode_t blendmode, uint32_t skip_source1_index, bool skip_source1_index_none, uint32_t skip_source2_index, bool skip_source2_index_none) { - displayio_area_t a = {0, 0, dest->width, dest->height, NULL}; + bitmaptools_blendmode_t blendmode, uint32_t skip_source1_index, bool skip_source1_index_none, uint32_t skip_source2_index, bool skip_source2_index_none, + displayio_bitmap_t *mask) { + displayio_area_t a = {0, 0, dest->width, dest->height }; displayio_bitmap_set_dirty_area(dest, &a); - int ifactor1 = (int)(factor1 * 256); - int ifactor2 = (int)(factor2 * 256); + int ifactor1_base = (int)(factor1 * 256); + int ifactor2_base = (int)(factor2 * 256); + int ifactor1 = ifactor1_base; + int ifactor2 = ifactor2_base; bool blend_source1, blend_source2; if (colorspace == DISPLAYIO_COLORSPACE_L8) { @@ -855,10 +1022,20 @@ void common_hal_bitmaptools_alphablend(displayio_bitmap_t *dest, displayio_bitma uint8_t *dptr = (uint8_t *)(dest->data + y * dest->stride); uint8_t *sptr1 = (uint8_t *)(source1->data + y * source1->stride); uint8_t *sptr2 = (uint8_t *)(source2->data + y * source2->stride); + uint8_t *mptr = mask ? (uint8_t *)(mask->data + y * mask->stride) : NULL; int pixel; for (int x = 0; x < dest->width; x++) { blend_source1 = skip_source1_index_none || *sptr1 != (uint8_t)skip_source1_index; blend_source2 = skip_source2_index_none || *sptr2 != (uint8_t)skip_source2_index; + if (mptr) { + uint8_t m = *mptr; + // Scale source2's contribution by the mask (0..255) + ifactor2 = (ifactor2_base * m + 127) / 255; + if (m == 0) { + // Mask says fully transparent: drop source2 entirely + blend_source2 = false; + } + } if (blend_source1 && blend_source2) { // Premultiply by the alpha factor int sda = *sptr1++ *ifactor1; @@ -871,7 +1048,8 @@ void common_hal_bitmaptools_alphablend(displayio_bitmap_t *dest, displayio_bitma blend = sca + sda * (256 - ifactor2) / 256; } // Divide by the alpha factor - pixel = (blend / (ifactor1 + ifactor2 - ifactor1 * ifactor2 / 256)); + int denom = ifactor1 + ifactor2 - ifactor1 * ifactor2 / 256; + pixel = (denom > 0) ? (blend / denom) : 0; } else if (blend_source1) { // Apply iFactor1 to source1 only pixel = *sptr1++ *ifactor1 / 256; @@ -883,6 +1061,9 @@ void common_hal_bitmaptools_alphablend(displayio_bitmap_t *dest, displayio_bitma pixel = *dptr; } *dptr++ = MIN(255, MAX(0, pixel)); + if (mptr) { + mptr++; + } } } } else { @@ -892,6 +1073,7 @@ void common_hal_bitmaptools_alphablend(displayio_bitmap_t *dest, displayio_bitma uint16_t *dptr = (uint16_t *)(dest->data + y * dest->stride); uint16_t *sptr1 = (uint16_t *)(source1->data + y * source1->stride); uint16_t *sptr2 = (uint16_t *)(source2->data + y * source2->stride); + uint8_t *mptr = mask ? (uint8_t *)(mask->data + y * mask->stride) : NULL; for (int x = 0; x < dest->width; x++) { int spix1 = *sptr1++; int spix2 = *sptr2++; @@ -907,11 +1089,24 @@ void common_hal_bitmaptools_alphablend(displayio_bitmap_t *dest, displayio_bitma blend_source1 = skip_source1_index_none || spix1 != (int)skip_source1_index; blend_source2 = skip_source2_index_none || spix2 != (int)skip_source2_index; + if (mptr) { + uint8_t m = *mptr++; + ifactor2 = (ifactor2_base * m + 127) / 255; + if (m == 0) { + blend_source2 = false; + } + } + if (blend_source1 && blend_source2) { // Blend based on the SVG alpha compositing specs // https://dev.w3.org/SVG/modules/compositing/master/#alphaCompositing int ifactor_blend = ifactor1 + ifactor2 - ifactor1 * ifactor2 / 256; + if (ifactor_blend <= 0) { + // Both factors are zero at this pixel; keep destination. + dptr++; + continue; + } // Premultiply the colors by the alpha factor int red_dca = ((spix1 & r_mask) >> 8) * ifactor1; @@ -1021,12 +1216,12 @@ void common_hal_bitmaptools_draw_circle(displayio_bitmap_t *destination, int16_t xbb0, xbb1, ybb0, ybb1; xbb0 = x - radius; - xbb1 = x + radius; + xbb1 = x + radius + 1; ybb0 = y - radius; - ybb1 = y + radius; + ybb1 = y + radius + 1; - displayio_area_t area = { xbb0, ybb0, xbb1, ybb1, NULL }; - displayio_area_t bitmap_area = { 0, 0, destination->width, destination->height, NULL }; + 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); @@ -1034,9 +1229,55 @@ void common_hal_bitmaptools_draw_circle(displayio_bitmap_t *destination, draw_circle(destination, x, y, radius, value); } +// Copy whole rows with memmove when no per-pixel decisions are needed. +static bool blit_rows_fast(displayio_bitmap_t *destination, displayio_bitmap_t *source, + int16_t x, int16_t y, int16_t x1, int16_t y1, int16_t x2, int16_t y2) { + uint8_t bits_per_value = source->bits_per_value; + if (bits_per_value != destination->bits_per_value || bits_per_value < 8) { + return false; + } + if (x1 < 0 || y1 < 0 || x2 > source->width || y2 > source->height) { + return false; + } + int sx = x1, sy = y1, dx = x, dy = y; + int w = x2 - x1, h = y2 - y1; + if (dx < 0) { + sx -= dx; + w += dx; + dx = 0; + } + if (dy < 0) { + sy -= dy; + h += dy; + dy = 0; + } + if (dx + w > destination->width) { + w = destination->width - dx; + } + if (dy + h > destination->height) { + h = destination->height - dy; + } + if (w <= 0 || h <= 0) { + return true; // nothing lands in the destination + } + size_t bytes_per_value = bits_per_value / 8; + size_t row_bytes = (size_t)w * bytes_per_value; + // When a bitmap is blitted onto itself and the destination rows sit below the + // source rows, copy bottom-up so no source row is overwritten before it is read. + bool bottom_up = destination == source && dy > sy; + for (int j = 0; j < h; j++) { + int row = bottom_up ? h - 1 - j : j; + const uint8_t *src_row = (const uint8_t *)(source->data + (size_t)(sy + row) * source->stride) + (size_t)sx * bytes_per_value; + uint8_t *dst_row = (uint8_t *)(destination->data + (size_t)(dy + row) * destination->stride) + (size_t)dx * bytes_per_value; + memmove(dst_row, src_row, row_bytes); + } + return true; +} + void common_hal_bitmaptools_blit(displayio_bitmap_t *destination, displayio_bitmap_t *source, int16_t x, int16_t y, int16_t x1, int16_t y1, int16_t x2, int16_t y2, uint32_t skip_source_index, bool skip_source_index_none, uint32_t skip_dest_index, bool skip_dest_index_none) { + // ESP_LOGI(TAG, "blit start"); if (destination->read_only) { mp_raise_RuntimeError(MP_ERROR_TEXT("Read-only")); @@ -1056,7 +1297,7 @@ void common_hal_bitmaptools_blit(displayio_bitmap_t *destination, displayio_bitm dirty_y_max = destination->height; } - displayio_area_t a = { x, y, dirty_x_max, dirty_y_max, NULL}; + displayio_area_t a = { x, y, dirty_x_max, dirty_y_max }; displayio_bitmap_set_dirty_area(destination, &a); bool x_reverse = false; @@ -1070,6 +1311,12 @@ void common_hal_bitmaptools_blit(displayio_bitmap_t *destination, displayio_bitm y_reverse = true; } + if (skip_source_index_none && skip_dest_index_none && + blit_rows_fast(destination, source, x, y, x1, y1, x2, y2)) { + // ESP_LOGI(TAG, "blit_rows_fast succeeded"); + return; + } + // simplest version - use internal functions for get/set pixels for (int16_t i = 0; i < (x2 - x1); i++) { @@ -1100,4 +1347,5 @@ void common_hal_bitmaptools_blit(displayio_bitmap_t *destination, displayio_bitm } } } + // ESP_LOGI(TAG, "blit end"); } diff --git a/shared-module/bitmaptools/__init__.h b/shared-module/bitmaptools/__init__.h new file mode 100644 index 00000000000..2f3d12d1d26 --- /dev/null +++ b/shared-module/bitmaptools/__init__.h @@ -0,0 +1,20 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mikey Sklar for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include + +// One row of the fixed-point rotozoom path: for i in [0, count), copy source pixel +// (u + i * du) >> 16 to dest_pixels[i], skipping skip_index unless skip_index_none. +// bits_per_value is 8 or 16, the same for both bitmaps, and u stays below 2^31. +// +// The default is portable C. A port may replace it with a faster version. Never raises, +// never allocates. +void bitmaptools_rotozoom_row(void *dest_pixels, const void *source_row, + uint32_t u, uint32_t du, int count, uint8_t bits_per_value, + uint32_t skip_index, bool skip_index_none); diff --git a/shared-module/board/__init__.c b/shared-module/board/__init__.c index 96735c8dbaa..31d4cb5b21e 100644 --- a/shared-module/board/__init__.c +++ b/shared-module/board/__init__.c @@ -25,6 +25,10 @@ #include "shared-module/sharpdisplay/SharpMemoryFramebuffer.h" #endif +#if CIRCUITPY_AIRLIFT +#include "shared-module/_airlift/transport.h" +#endif + #if CIRCUITPY_AURORA_EPAPER #include "shared-bindings/aurora_epaper/aurora_framebuffer.h" #include "shared-module/aurora_epaper/aurora_framebuffer.h" @@ -42,14 +46,13 @@ typedef struct { static const board_i2c_pin_t i2c_pin[CIRCUITPY_BOARD_I2C] = CIRCUITPY_BOARD_I2C_PIN; static busio_i2c_obj_t i2c_obj[CIRCUITPY_BOARD_I2C]; static bool i2c_obj_created[CIRCUITPY_BOARD_I2C]; +// Number of board-owned users, such as an IO expander, that keep using the bus. +static uint8_t i2c_retain_count[CIRCUITPY_BOARD_I2C]; -bool common_hal_board_is_i2c(mp_obj_t obj) { - for (uint8_t instance = 0; instance < CIRCUITPY_BOARD_I2C; instance++) { - if (obj == &i2c_obj[instance]) { - return true; - } +void board_i2c_retain(uint8_t instance) { + if (i2c_retain_count[instance] < UINT8_MAX) { + i2c_retain_count[instance]++; } - return false; } mp_obj_t common_hal_board_get_i2c(const mp_int_t instance) { @@ -89,15 +92,6 @@ static const board_spi_pin_t spi_pin[CIRCUITPY_BOARD_SPI] = CIRCUITPY_BOARD_SPI_ static busio_spi_obj_t spi_obj[CIRCUITPY_BOARD_SPI]; static bool spi_obj_created[CIRCUITPY_BOARD_SPI]; -bool common_hal_board_is_spi(mp_obj_t obj) { - for (uint8_t instance = 0; instance < CIRCUITPY_BOARD_SPI; instance++) { - if (obj == &spi_obj[instance]) { - return true; - } - } - return false; -} - mp_obj_t common_hal_board_get_spi(const mp_int_t instance) { return spi_obj_created[instance] ? &spi_obj[instance] : NULL; } @@ -136,15 +130,6 @@ static const board_uart_pin_t uart_pin[CIRCUITPY_BOARD_UART] = CIRCUITPY_BOARD_U static busio_uart_obj_t uart_obj[CIRCUITPY_BOARD_UART]; static bool uart_obj_created[CIRCUITPY_BOARD_UART]; -bool common_hal_board_is_uart(mp_obj_t obj) { - for (uint8_t instance = 0; instance < CIRCUITPY_BOARD_UART; instance++) { - if (obj == &uart_obj[instance]) { - return true; - } - } - return false; -} - mp_obj_t common_hal_board_get_uart(const mp_int_t instance) { return uart_obj_created[instance] ? &uart_obj[instance] : NULL; } @@ -174,11 +159,11 @@ mp_obj_t common_hal_board_create_uart(const mp_int_t instance) { void reset_board_buses(void) { #if CIRCUITPY_BOARD_I2C for (uint8_t instance = 0; instance < CIRCUITPY_BOARD_I2C; instance++) { - bool display_using_i2c = false; + bool keep_bus = i2c_retain_count[instance] > 0; #if CIRCUITPY_I2CDISPLAYBUS for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) { if (display_buses[i].bus_base.type == &i2cdisplaybus_i2cdisplaybus_type && display_buses[i].i2cdisplay_bus.bus == &i2c_obj[instance]) { - display_using_i2c = true; + keep_bus = true; break; } } @@ -186,7 +171,7 @@ void reset_board_buses(void) { if (i2c_obj_created[instance]) { // make sure I2C lock is not held over a soft reset common_hal_busio_i2c_unlock(&i2c_obj[instance]); - if (!display_using_i2c) { + if (!keep_bus) { common_hal_busio_i2c_deinit(&i2c_obj[instance]); i2c_obj_created[instance] = false; } @@ -212,13 +197,21 @@ void reset_board_buses(void) { } #endif #if CIRCUITPY_AURORA_EPAPER - if (bus_type == &aurora_epaper_framebuffer_type && display_buses[i].aurora_epaper.bus == &spi_obj[instance]) { + if (bus_type == &aurora_framebuffer_type && display_buses[i].aurora_epaper.bus == &spi_obj[instance]) { display_using_spi = true; break; } #endif } #endif + #if CIRCUITPY_AIRLIFT + // The ESP32 co-processor keeps the bus between VM runs. Don't let a lock + // left by user code block it. + if (airlift_transport_using_spi(&spi_obj[instance])) { + common_hal_busio_spi_unlock(&spi_obj[instance]); + display_using_spi = true; + } + #endif if (spi_obj_created[instance]) { if (!display_using_spi) { common_hal_busio_spi_deinit(&spi_obj[instance]); diff --git a/shared-module/board/__init__.h b/shared-module/board/__init__.h index a179478cd71..b35d4ce5bed 100644 --- a/shared-module/board/__init__.h +++ b/shared-module/board/__init__.h @@ -6,4 +6,14 @@ #pragma once +#include + +#include "py/mpconfig.h" + void reset_board_buses(void); + +#if CIRCUITPY_BOARD_I2C +// Add one board-owned user, such as an IO expander, of board I2C bus `instance`. +// reset_board_buses() keeps the bus while it has a user. Does not raise or allocate. +void board_i2c_retain(uint8_t instance); +#endif diff --git a/shared-module/busdisplay/BusDisplay.c b/shared-module/busdisplay/BusDisplay.c deleted file mode 100644 index 001f2f20c03..00000000000 --- a/shared-module/busdisplay/BusDisplay.c +++ /dev/null @@ -1,428 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2018 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "shared-bindings/busdisplay/BusDisplay.h" - -#include "py/runtime.h" -#if CIRCUITPY_FOURWIRE -#include "shared-bindings/fourwire/FourWire.h" -#endif -#if CIRCUITPY_I2CDISPLAYBUS -#include "shared-bindings/i2cdisplaybus/I2CDisplayBus.h" -#endif -#if CIRCUITPY_PARALLELDISPLAYBUS -#include "shared-bindings/paralleldisplaybus/ParallelBus.h" -#endif -#include "shared-bindings/microcontroller/Pin.h" -#include "shared-bindings/time/__init__.h" -#include "shared-module/displayio/__init__.h" -#include "shared-module/displayio/display_core.h" -#include "supervisor/shared/display.h" -#include "supervisor/shared/tick.h" - -#if CIRCUITPY_TINYUSB -#include "supervisor/usb.h" -#endif - -#include -#include - -#define DELAY 0x80 - -void common_hal_busdisplay_busdisplay_construct(busdisplay_busdisplay_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 *init_sequence, uint16_t init_sequence_len, const mcu_pin_obj_t *backlight_pin, - uint16_t brightness_command, mp_float_t 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, uint16_t backlight_pwm_frequency) { - - // Turn off auto-refresh as we init. - self->auto_refresh = false; - uint16_t ram_width = 0x100; - uint16_t ram_height = 0x100; - if (single_byte_bounds) { - ram_width = 0xff; - ram_height = 0xff; - } - displayio_display_core_construct(&self->core, width, height, rotation, - color_depth, grayscale, pixels_in_byte_share_row, bytes_per_cell, reverse_pixels_in_byte, reverse_bytes_in_word); - displayio_display_bus_construct(&self->bus, bus, ram_width, ram_height, colstart, rowstart, - set_column_command, set_row_command, NO_COMMAND, NO_COMMAND, data_as_commands, false /* always_toggle_chip_select */, - SH1107_addressing && color_depth == 1, false /*address_little_endian */); - - self->write_ram_command = write_ram_command; - self->brightness_command = brightness_command; - self->first_manual_refresh = !auto_refresh; - self->backlight_on_high = backlight_on_high; - - self->native_frames_per_second = native_frames_per_second; - self->native_ms_per_frame = 1000 / native_frames_per_second; - - uint32_t i = 0; - while (i < init_sequence_len) { - uint8_t *cmd = init_sequence + i; - uint8_t data_size = *(cmd + 1); - bool delay = (data_size & DELAY) != 0; - data_size &= ~DELAY; - uint8_t *data = cmd + 2; - while (!displayio_display_bus_begin_transaction(&self->bus)) { - RUN_BACKGROUND_TASKS; - } - if (self->bus.data_as_commands) { - uint8_t full_command[data_size + 1]; - full_command[0] = cmd[0]; - memcpy(full_command + 1, data, data_size); - self->bus.send(self->bus.bus, DISPLAY_COMMAND, CHIP_SELECT_TOGGLE_EVERY_BYTE, full_command, data_size + 1); - } else { - self->bus.send(self->bus.bus, DISPLAY_COMMAND, CHIP_SELECT_TOGGLE_EVERY_BYTE, cmd, 1); - self->bus.send(self->bus.bus, DISPLAY_DATA, CHIP_SELECT_UNTOUCHED, data, data_size); - } - displayio_display_bus_end_transaction(&self->bus); - uint16_t delay_length_ms = 10; - if (delay) { - data_size++; - delay_length_ms = *(cmd + 1 + data_size); - if (delay_length_ms == 255) { - delay_length_ms = 500; - } - } - common_hal_time_delay_ms(delay_length_ms); - i += 2 + data_size; - } - - // Always set the backlight type in case we're reusing memory. - 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_PWMIO) - pwmout_result_t result = common_hal_pwmio_pwmout_construct(&self->backlight_pwm, backlight_pin, 0, backlight_pwm_frequency, false); - if (result != PWMOUT_OK) { - self->backlight_inout.base.type = &digitalio_digitalinout_type; - common_hal_digitalio_digitalinout_construct(&self->backlight_inout, backlight_pin); - common_hal_never_reset_pin(backlight_pin); - } else { - self->backlight_pwm.base.type = &pwmio_pwmout_type; - common_hal_pwmio_pwmout_never_reset(&self->backlight_pwm); - } - #else - // Otherwise default to digital - self->backlight_inout.base.type = &digitalio_digitalinout_type; - common_hal_digitalio_digitalinout_construct(&self->backlight_inout, backlight_pin); - common_hal_never_reset_pin(backlight_pin); - #endif - } - - common_hal_busdisplay_busdisplay_set_brightness(self, brightness); - - // Set the group after initialization otherwise we may send pixels while we delay in - // initialization. - if (!circuitpython_splash.in_group) { - common_hal_busdisplay_busdisplay_set_root_group(self, &circuitpython_splash); - } - common_hal_busdisplay_busdisplay_set_auto_refresh(self, auto_refresh); -} - -uint16_t common_hal_busdisplay_busdisplay_get_width(busdisplay_busdisplay_obj_t *self) { - return displayio_display_core_get_width(&self->core); -} - -uint16_t common_hal_busdisplay_busdisplay_get_height(busdisplay_busdisplay_obj_t *self) { - return displayio_display_core_get_height(&self->core); -} - -mp_float_t common_hal_busdisplay_busdisplay_get_brightness(busdisplay_busdisplay_obj_t *self) { - return self->current_brightness; -} - -bool common_hal_busdisplay_busdisplay_set_brightness(busdisplay_busdisplay_obj_t *self, mp_float_t 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_PWMIO) - bool ispwm = (self->backlight_pwm.base.type == &pwmio_pwmout_type) ? true : false; - #else - bool ispwm = false; - #endif - - if (ispwm) { - #if (CIRCUITPY_PWMIO) - common_hal_pwmio_pwmout_set_duty_cycle(&self->backlight_pwm, (uint16_t)(0xffff * brightness)); - ok = true; - #else - ok = false; - #endif - } else if (self->backlight_inout.base.type == &digitalio_digitalinout_type) { - common_hal_digitalio_digitalinout_set_value(&self->backlight_inout, brightness > 0.99); - ok = true; - } else if (self->brightness_command != NO_BRIGHTNESS_COMMAND) { - ok = displayio_display_bus_begin_transaction(&self->bus); - if (ok) { - if (self->bus.data_as_commands) { - uint8_t set_brightness[2] = {self->brightness_command, (uint8_t)(0xff * brightness)}; - self->bus.send(self->bus.bus, DISPLAY_COMMAND, CHIP_SELECT_TOGGLE_EVERY_BYTE, set_brightness, 2); - } else { - uint8_t command = self->brightness_command; - uint8_t hex_brightness = 0xff * brightness; - self->bus.send(self->bus.bus, DISPLAY_COMMAND, CHIP_SELECT_TOGGLE_EVERY_BYTE, &command, 1); - self->bus.send(self->bus.bus, DISPLAY_DATA, CHIP_SELECT_UNTOUCHED, &hex_brightness, 1); - } - displayio_display_bus_end_transaction(&self->bus); - } - - } - if (ok) { - self->current_brightness = brightness; - } - return ok; -} - -mp_obj_t common_hal_busdisplay_busdisplay_get_bus(busdisplay_busdisplay_obj_t *self) { - return self->bus.bus; -} - -mp_obj_t common_hal_busdisplay_busdisplay_get_root_group(busdisplay_busdisplay_obj_t *self) { - if (self->core.current_group == NULL) { - return mp_const_none; - } - return self->core.current_group; -} - -static const displayio_area_t *_get_refresh_areas(busdisplay_busdisplay_obj_t *self) { - if (self->core.full_refresh) { - self->core.area.next = NULL; - return &self->core.area; - } else if (self->core.current_group != NULL) { - return displayio_group_get_refresh_areas(self->core.current_group, NULL); - } - return NULL; -} - -static void _send_pixels(busdisplay_busdisplay_obj_t *self, uint8_t *pixels, uint32_t length) { - if (!self->bus.data_as_commands) { - self->bus.send(self->bus.bus, DISPLAY_COMMAND, CHIP_SELECT_TOGGLE_EVERY_BYTE, &self->write_ram_command, 1); - } - self->bus.send(self->bus.bus, DISPLAY_DATA, CHIP_SELECT_UNTOUCHED, pixels, length); -} - -static bool _refresh_area(busdisplay_busdisplay_obj_t *self, const displayio_area_t *area) { - uint16_t buffer_size = 128; // In uint32_ts - - displayio_area_t clipped; - // Clip the area to the display by overlapping the areas. If there is no overlap then we're done. - if (!displayio_display_core_clip_area(&self->core, area, &clipped)) { - return true; - } - uint16_t rows_per_buffer = displayio_area_height(&clipped); - uint8_t pixels_per_word = (sizeof(uint32_t) * 8) / self->core.colorspace.depth; - uint16_t pixels_per_buffer = displayio_area_size(&clipped); - - uint16_t subrectangles = 1; - // for SH1107 and other boundary constrained controllers - // write one single row at a time - if (self->bus.SH1107_addressing) { - subrectangles = rows_per_buffer / 8; // page addressing mode writes 8 rows at a time - rows_per_buffer = 8; - } else if (displayio_area_size(&clipped) > buffer_size * pixels_per_word) { - rows_per_buffer = buffer_size * pixels_per_word / displayio_area_width(&clipped); - if (rows_per_buffer == 0) { - rows_per_buffer = 1; - } - // If pixels are packed by column then ensure rows_per_buffer is on a byte boundary. - if (self->core.colorspace.depth < 8 && !self->core.colorspace.pixels_in_byte_share_row) { - uint8_t pixels_per_byte = 8 / self->core.colorspace.depth; - if (rows_per_buffer % pixels_per_byte != 0) { - rows_per_buffer -= rows_per_buffer % pixels_per_byte; - } - } - subrectangles = displayio_area_height(&clipped) / rows_per_buffer; - if (displayio_area_height(&clipped) % rows_per_buffer != 0) { - subrectangles++; - } - pixels_per_buffer = rows_per_buffer * displayio_area_width(&clipped); - buffer_size = pixels_per_buffer / pixels_per_word; - if (pixels_per_buffer % pixels_per_word) { - buffer_size += 1; - } - } - - // Allocated and shared as a uint32_t array so the compiler knows the - // alignment everywhere. - uint32_t buffer[buffer_size]; - uint32_t mask_length = (pixels_per_buffer / 32) + 1; - uint32_t mask[mask_length]; - uint16_t remaining_rows = displayio_area_height(&clipped); - - for (uint16_t j = 0; j < subrectangles; j++) { - displayio_area_t subrectangle = { - .x1 = clipped.x1, - .y1 = clipped.y1 + rows_per_buffer * j, - .x2 = clipped.x2, - .y2 = clipped.y1 + rows_per_buffer * (j + 1) - }; - if (remaining_rows < rows_per_buffer) { - subrectangle.y2 = subrectangle.y1 + remaining_rows; - } - remaining_rows -= rows_per_buffer; - - displayio_display_bus_set_region_to_update(&self->bus, &self->core, &subrectangle); - - uint16_t subrectangle_size_bytes; - if (self->core.colorspace.depth >= 8) { - subrectangle_size_bytes = displayio_area_size(&subrectangle) * (self->core.colorspace.depth / 8); - } else { - subrectangle_size_bytes = displayio_area_size(&subrectangle) / (8 / self->core.colorspace.depth); - } - - memset(mask, 0, mask_length * sizeof(mask[0])); - memset(buffer, 0, buffer_size * sizeof(buffer[0])); - - displayio_display_core_fill_area(&self->core, &subrectangle, mask, buffer); - - // Can't acquire display bus; skip the rest of the data. - if (!displayio_display_bus_is_free(&self->bus)) { - return false; - } - - displayio_display_bus_begin_transaction(&self->bus); - _send_pixels(self, (uint8_t *)buffer, subrectangle_size_bytes); - displayio_display_bus_end_transaction(&self->bus); - - // TODO(tannewt): Make refresh displays faster so we don't starve other - // background tasks. - #if CIRCUITPY_TINYUSB - usb_background(); - #endif - } - return true; -} - -static void _refresh_display(busdisplay_busdisplay_obj_t *self) { - if (!displayio_display_bus_is_free(&self->bus)) { - // A refresh on this bus is already in progress. Try next display. - return; - } - displayio_display_core_start_refresh(&self->core); - const displayio_area_t *current_area = _get_refresh_areas(self); - while (current_area != NULL) { - _refresh_area(self, current_area); - current_area = current_area->next; - } - displayio_display_core_finish_refresh(&self->core); -} - -void common_hal_busdisplay_busdisplay_set_rotation(busdisplay_busdisplay_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) { - int tmp = self->core.width; - self->core.width = self->core.height; - self->core.height = tmp; - } - displayio_display_core_set_rotation(&self->core, rotation); - if (self == &displays[0].display) { - supervisor_stop_terminal(); - supervisor_start_terminal(self->core.width, self->core.height); - } - if (self->core.current_group != NULL) { - displayio_group_update_transform(self->core.current_group, &self->core.transform); - } -} - -uint16_t common_hal_busdisplay_busdisplay_get_rotation(busdisplay_busdisplay_obj_t *self) { - return self->core.rotation; -} - - -bool common_hal_busdisplay_busdisplay_refresh(busdisplay_busdisplay_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 != NO_FPS_LIMIT)) { - 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. - if (current_ms_since_real_refresh > maximum_ms_per_real_frame) { - mp_raise_RuntimeError(MP_ERROR_TEXT("Below minimum frame rate")); - } - uint32_t current_ms_since_last_call = current_time - self->last_refresh_call; - self->last_refresh_call = current_time; - // Skip the actual refresh to help catch up. - if (current_ms_since_last_call > target_ms_per_frame) { - return false; - } - uint32_t remaining_time = target_ms_per_frame - (current_ms_since_real_refresh % target_ms_per_frame); - // We're ahead of the game so wait until we align with the frame rate. - while (supervisor_ticks_ms64() - self->last_refresh_call < remaining_time) { - RUN_BACKGROUND_TASKS; - } - } - self->first_manual_refresh = false; - _refresh_display(self); - return true; -} - -bool common_hal_busdisplay_busdisplay_get_auto_refresh(busdisplay_busdisplay_obj_t *self) { - return self->auto_refresh; -} - -void common_hal_busdisplay_busdisplay_set_auto_refresh(busdisplay_busdisplay_obj_t *self, - bool auto_refresh) { - self->first_manual_refresh = !auto_refresh; - if (auto_refresh != self->auto_refresh) { - if (auto_refresh) { - supervisor_enable_tick(); - } else { - supervisor_disable_tick(); - } - } - self->auto_refresh = auto_refresh; -} - -mp_obj_t common_hal_busdisplay_busdisplay_set_root_group(busdisplay_busdisplay_obj_t *self, displayio_group_t *root_group) { - bool ok = displayio_display_core_set_root_group(&self->core, root_group); - if (!ok) { - mp_raise_ValueError(MP_ERROR_TEXT("Group already used")); - } - return mp_const_none; -} - -void busdisplay_busdisplay_background(busdisplay_busdisplay_obj_t *self) { - if (self->auto_refresh && (supervisor_ticks_ms64() - self->core.last_refresh) > self->native_ms_per_frame) { - _refresh_display(self); - } -} - -void release_busdisplay(busdisplay_busdisplay_obj_t *self) { - common_hal_busdisplay_busdisplay_set_auto_refresh(self, false); - release_display_core(&self->core); - #if (CIRCUITPY_PWMIO) - if (self->backlight_pwm.base.type == &pwmio_pwmout_type) { - common_hal_pwmio_pwmout_deinit(&self->backlight_pwm); - } else if (self->backlight_inout.base.type == &digitalio_digitalinout_type) { - common_hal_digitalio_digitalinout_deinit(&self->backlight_inout); - } - #else - common_hal_digitalio_digitalinout_deinit(&self->backlight_inout); - #endif -} - -void reset_busdisplay(busdisplay_busdisplay_obj_t *self) { - common_hal_busdisplay_busdisplay_set_auto_refresh(self, true); - circuitpython_splash.x = 0; // reset position in case someone moved it. - circuitpython_splash.y = 0; - supervisor_start_terminal(self->core.width, self->core.height); - if (!circuitpython_splash.in_group) { - common_hal_busdisplay_busdisplay_set_root_group(self, &circuitpython_splash); - } -} - -void busdisplay_busdisplay_collect_ptrs(busdisplay_busdisplay_obj_t *self) { - displayio_display_core_collect_ptrs(&self->core); - displayio_display_bus_collect_ptrs(&self->bus); -} diff --git a/shared-module/busdisplay/BusDisplay.h b/shared-module/busdisplay/BusDisplay.h index 87e09a821e5..e7f5d9d5a5c 100644 --- a/shared-module/busdisplay/BusDisplay.h +++ b/shared-module/busdisplay/BusDisplay.h @@ -7,37 +7,30 @@ #pragma once #include "shared-bindings/digitalio/DigitalInOut.h" -#include "shared-bindings/displayio/Group.h" #if CIRCUITPY_PWMIO #include "shared-bindings/pwmio/PWMOut.h" #endif -#include "shared-module/displayio/area.h" -#include "shared-module/displayio/bus_core.h" -#include "shared-module/displayio/display_core.h" +// Backlight state shared by both BusDisplay backends. +typedef union { + digitalio_digitalinout_obj_t inout; + #if CIRCUITPY_PWMIO + pwmio_pwmout_obj_t pwm; + #endif +} busdisplay_backlight_t; -typedef struct { - mp_obj_base_t base; - displayio_display_core_t core; - displayio_display_bus_t bus; - union { - digitalio_digitalinout_obj_t backlight_inout; - #if CIRCUITPY_PWMIO - pwmio_pwmout_obj_t backlight_pwm; - #endif - }; - uint64_t last_refresh_call; - mp_float_t current_brightness; - uint16_t brightness_command; - uint16_t native_frames_per_second; - uint16_t native_ms_per_frame; - uint8_t write_ram_command; - bool auto_refresh; - bool first_manual_refresh; - bool backlight_on_high; -} busdisplay_busdisplay_obj_t; +void busdisplay_backlight_construct(busdisplay_backlight_t *self, const mcu_pin_obj_t *pin, + uint16_t pwm_frequency); +bool busdisplay_backlight_set(busdisplay_backlight_t *self, mp_float_t brightness); +void busdisplay_backlight_deinit(busdisplay_backlight_t *self); -void busdisplay_busdisplay_background(busdisplay_busdisplay_obj_t *self); -void release_busdisplay(busdisplay_busdisplay_obj_t *self); -void reset_busdisplay(busdisplay_busdisplay_obj_t *self); -void busdisplay_busdisplay_collect_ptrs(busdisplay_busdisplay_obj_t *self); +// The BusDisplay implementation has two backends selected at build time with +// CIRCUITPY_DISPLAYIO_LVGL: +// +// legacy/ - the original scanline compositor, built on display_core/bus_core. +// lvgl/ - an LVGL display with its own draw buffers and flush callback. +#if CIRCUITPY_DISPLAYIO_LVGL +#include "shared-module/busdisplay/lvgl/BusDisplay.h" +#else +#include "shared-module/busdisplay/legacy/BusDisplay.h" +#endif diff --git a/shared-module/busdisplay/__init__.c b/shared-module/busdisplay/__init__.c index 6283dbe0c6a..6caf4de9d9e 100644 --- a/shared-module/busdisplay/__init__.c +++ b/shared-module/busdisplay/__init__.c @@ -4,4 +4,53 @@ // // SPDX-License-Identifier: MIT -// Nothing now. +#include "shared-module/busdisplay/BusDisplay.h" + +#include "shared-bindings/microcontroller/Pin.h" + +void busdisplay_backlight_construct(busdisplay_backlight_t *self, const mcu_pin_obj_t *pin, + uint16_t pwm_frequency) { + // Always set the backlight type in case we're reusing memory. + self->inout.base.type = &mp_type_NoneType; + if (pin == NULL || !common_hal_mcu_pin_is_free(pin)) { + return; + } + #if CIRCUITPY_PWMIO + pwmout_result_t result = common_hal_pwmio_pwmout_construct(&self->pwm, pin, 0, pwm_frequency, false); + if (result != PWMOUT_OK) { + self->inout.base.type = &digitalio_digitalinout_type; + common_hal_digitalio_digitalinout_construct(&self->inout, pin); + } else { + self->pwm.base.type = &pwmio_pwmout_type; + } + #else + self->inout.base.type = &digitalio_digitalinout_type; + common_hal_digitalio_digitalinout_construct(&self->inout, pin); + #endif +} + +bool busdisplay_backlight_set(busdisplay_backlight_t *self, mp_float_t brightness) { + #if CIRCUITPY_PWMIO + if (self->pwm.base.type == &pwmio_pwmout_type) { + common_hal_pwmio_pwmout_set_duty_cycle(&self->pwm, (uint16_t)(0xffff * brightness)); + return true; + } + #endif + if (self->inout.base.type == &digitalio_digitalinout_type) { + common_hal_digitalio_digitalinout_set_value(&self->inout, brightness > 0.99); + return true; + } + return false; +} + +void busdisplay_backlight_deinit(busdisplay_backlight_t *self) { + #if CIRCUITPY_PWMIO + if (self->pwm.base.type == &pwmio_pwmout_type) { + common_hal_pwmio_pwmout_deinit(&self->pwm); + return; + } + #endif + if (self->inout.base.type == &digitalio_digitalinout_type) { + common_hal_digitalio_digitalinout_deinit(&self->inout); + } +} diff --git a/shared-module/busdisplay/legacy/BusDisplay.c b/shared-module/busdisplay/legacy/BusDisplay.c new file mode 100644 index 00000000000..03e2741b93b --- /dev/null +++ b/shared-module/busdisplay/legacy/BusDisplay.c @@ -0,0 +1,400 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/busdisplay/BusDisplay.h" + +#include "py/mphal.h" +#include "py/runtime.h" +#if CIRCUITPY_FOURWIRE +#include "shared-bindings/fourwire/FourWire.h" +#endif +#if CIRCUITPY_I2CDISPLAYBUS +#include "shared-bindings/i2cdisplaybus/I2CDisplayBus.h" +#endif +#if CIRCUITPY_PARALLELDISPLAYBUS +#include "shared-bindings/paralleldisplaybus/ParallelBus.h" +#endif +#include "shared/runtime/interrupt_char.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/time/__init__.h" +#include "shared-module/displayio/__init__.h" +#include "shared-module/displayio/display_core.h" +#include "supervisor/shared/display.h" +#include "supervisor/shared/tick.h" + +#if CIRCUITPY_WEB_WORKFLOW +#include "supervisor/shared/web_workflow/display_stream.h" +#endif + +#if CIRCUITPY_TINYUSB +#include "supervisor/usb.h" +#endif + +#include +#include + + +void common_hal_busdisplay_busdisplay_construct(busdisplay_busdisplay_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 *init_sequence, uint16_t init_sequence_len, const mcu_pin_obj_t *backlight_pin, + uint16_t brightness_command, mp_float_t 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, uint16_t backlight_pwm_frequency) { + + // Turn off auto-refresh as we init. + self->auto_refresh = false; + uint16_t ram_width = 0x100; + uint16_t ram_height = 0x100; + if (single_byte_bounds) { + ram_width = 0xff; + ram_height = 0xff; + } + displayio_display_core_construct(&self->core, width, height, rotation, + color_depth, grayscale, pixels_in_byte_share_row, bytes_per_cell, reverse_pixels_in_byte, reverse_bytes_in_word); + displayio_display_bus_construct(&self->bus, bus, ram_width, ram_height, colstart, rowstart, + set_column_command, set_row_command, NO_COMMAND, NO_COMMAND, data_as_commands, false /* always_toggle_chip_select */, + SH1107_addressing && color_depth == 1, false /*address_little_endian */); + + self->write_ram_command = write_ram_command; + self->brightness_command = brightness_command; + self->first_manual_refresh = !auto_refresh; + self->backlight_on_high = backlight_on_high; + + self->native_frames_per_second = native_frames_per_second; + self->native_ms_per_frame = 1000 / native_frames_per_second; + + displayio_display_bus_send_init_sequence(&self->bus, init_sequence, init_sequence_len); + + busdisplay_backlight_construct(&self->backlight, backlight_pin, backlight_pwm_frequency); + + common_hal_busdisplay_busdisplay_set_brightness(self, brightness); + + // Set the group after initialization otherwise we may send pixels while we delay in + // initialization. + if (!circuitpython_splash.in_group) { + common_hal_busdisplay_busdisplay_set_root_group(self, &circuitpython_splash); + } + common_hal_busdisplay_busdisplay_set_auto_refresh(self, auto_refresh); +} + +uint16_t common_hal_busdisplay_busdisplay_get_width(busdisplay_busdisplay_obj_t *self) { + return displayio_display_core_get_width(&self->core); +} + +uint16_t common_hal_busdisplay_busdisplay_get_height(busdisplay_busdisplay_obj_t *self) { + return displayio_display_core_get_height(&self->core); +} + +mp_float_t common_hal_busdisplay_busdisplay_get_brightness(busdisplay_busdisplay_obj_t *self) { + return self->current_brightness; +} + +bool common_hal_busdisplay_busdisplay_set_brightness(busdisplay_busdisplay_obj_t *self, mp_float_t brightness) { + if (!self->backlight_on_high) { + brightness = 1.0 - brightness; + } + bool ok = busdisplay_backlight_set(&self->backlight, brightness); + + if (!ok && self->brightness_command != NO_BRIGHTNESS_COMMAND) { + ok = displayio_display_bus_begin_transaction(&self->bus); + if (ok) { + if (self->bus.data_as_commands) { + uint8_t set_brightness[2] = {self->brightness_command, (uint8_t)(0xff * brightness)}; + self->bus.send(self->bus.bus, DISPLAY_COMMAND, CHIP_SELECT_TOGGLE_EVERY_BYTE, set_brightness, 2); + } else { + uint8_t command = self->brightness_command; + uint8_t hex_brightness = 0xff * brightness; + self->bus.send(self->bus.bus, DISPLAY_COMMAND, CHIP_SELECT_TOGGLE_EVERY_BYTE, &command, 1); + self->bus.send(self->bus.bus, DISPLAY_DATA, CHIP_SELECT_UNTOUCHED, &hex_brightness, 1); + } + displayio_display_bus_end_transaction(&self->bus); + } + + } + if (ok) { + self->current_brightness = brightness; + } + return ok; +} + +mp_obj_t common_hal_busdisplay_busdisplay_get_bus(busdisplay_busdisplay_obj_t *self) { + return self->bus.bus; +} + +mp_obj_t common_hal_busdisplay_busdisplay_get_root_group(busdisplay_busdisplay_obj_t *self) { + if (self->core.current_group == NULL) { + return mp_const_none; + } + return self->core.current_group; +} + +static const displayio_area_t *_get_refresh_areas(busdisplay_busdisplay_obj_t *self) { + if (self->core.full_refresh) { + self->core.area.next = NULL; + return &self->core.area; + } else if (self->core.current_group != NULL) { + return displayio_group_get_refresh_areas(self->core.current_group, NULL); + } + return NULL; +} + +static void _send_pixels(busdisplay_busdisplay_obj_t *self, uint8_t *pixels, uint32_t length) { + if (!self->bus.data_as_commands) { + self->bus.send(self->bus.bus, DISPLAY_COMMAND, CHIP_SELECT_TOGGLE_EVERY_BYTE, &self->write_ram_command, 1); + } + self->bus.send(self->bus.bus, DISPLAY_DATA, CHIP_SELECT_UNTOUCHED, pixels, length); +} + +// Whether the bus sends in the background. Always false without async SPI, so that code is +// left out. Not a local variable: GCC would then compile the refresh loop twice. +#define SEND_ASYNC(self) (CIRCUITPY_BUSIO_SPI_ASYNC && (self)->bus.send_async != NULL) + +// The data half of _send_pixels, handed to the bus without waiting for it to be sent. +static void _send_pixels_async(busdisplay_busdisplay_obj_t *self, uint8_t *pixels, uint32_t length) { + if (!self->bus.data_as_commands) { + self->bus.send(self->bus.bus, DISPLAY_COMMAND, CHIP_SELECT_TOGGLE_EVERY_BYTE, &self->write_ram_command, 1); + } + self->bus.send_async(self->bus.bus, DISPLAY_DATA, CHIP_SELECT_UNTOUCHED, pixels, length); +} + +// Call only with the bus transaction closed: a background task may use the same bus. +static void _run_background_tasks(void) { + // Run background tasks so they can run during an explicit refresh. + // Auto-refresh won't run background tasks here because it is a background task itself. + RUN_BACKGROUND_TASKS; + + // Run USB background tasks so they can run during an implicit refresh. + #if CIRCUITPY_TINYUSB + usb_background(); + #endif +} + +static bool _refresh_area(busdisplay_busdisplay_obj_t *self, const displayio_area_t *area) { + uint16_t buffer_size = CIRCUITPY_DISPLAY_AREA_BUFFER_SIZE / sizeof(uint32_t); // In uint32_ts + + displayio_area_t clipped; + // Clip the area to the display by overlapping the areas. If there is no overlap then we're done. + if (!displayio_display_core_clip_area(&self->core, area, &clipped)) { + return true; + } + #if CIRCUITPY_WEB_WORKFLOW + display_stream_area_updated(&self->core, &clipped); + #endif + uint16_t rows_per_buffer = displayio_area_height(&clipped); + uint16_t cols_per_buffer = displayio_area_width(&clipped); + uint8_t pixels_per_word = (sizeof(uint32_t) * 8) / self->core.colorspace.depth; + uint16_t pixels_per_buffer = displayio_area_size(&clipped); + + uint16_t subrectangles = 1; + // for SH1107 and other boundary constrained controllers + // write one single row at a time + if (self->bus.SH1107_addressing) { + subrectangles = rows_per_buffer / 8; // page addressing mode writes 8 rows at a time + rows_per_buffer = 8; + } else if (displayio_area_size(&clipped) > buffer_size * pixels_per_word) { + uint16_t buffer_pixels = buffer_size * pixels_per_word; + if (self->core.transform.transpose_xy && self->core.colorspace.depth >= 8) { + // Rotated 90 or 270: a panel column is a source row. Send bands of columns so sources + // are read along their rows, which OnDiskBitmap needs to avoid a file seek per pixel. + rows_per_buffer = MIN(rows_per_buffer, buffer_pixels); + cols_per_buffer = buffer_pixels / rows_per_buffer; + } else { + rows_per_buffer = buffer_pixels / cols_per_buffer; + if (rows_per_buffer == 0) { + rows_per_buffer = 1; + } + // If pixels are packed by column then ensure rows_per_buffer is on a byte boundary. + if (self->core.colorspace.depth < 8 && !self->core.colorspace.pixels_in_byte_share_row) { + uint8_t pixels_per_byte = 8 / self->core.colorspace.depth; + if (rows_per_buffer % pixels_per_byte != 0) { + rows_per_buffer -= rows_per_buffer % pixels_per_byte; + } + } + } + subrectangles = ((displayio_area_height(&clipped) + rows_per_buffer - 1) / rows_per_buffer) * + ((displayio_area_width(&clipped) + cols_per_buffer - 1) / cols_per_buffer); + pixels_per_buffer = rows_per_buffer * cols_per_buffer; + buffer_size = (pixels_per_buffer + pixels_per_word - 1) / pixels_per_word; + } + + // Allocated and shared as a uint32_t array so the compiler knows the + // alignment everywhere. + uint32_t mask_length = (pixels_per_buffer / 32) + 1; + // With an asynchronous bus, one buffer is composited while the other is being sent. + uint32_t buffers[SEND_ASYNC(self) ? 2 : 1][buffer_size]; + uint32_t mask[mask_length]; + uint8_t fill_index = 0; + bool sending = false; + + displayio_area_t subrectangle = clipped; + subrectangle.next = NULL; + + for (uint16_t j = 0; j < subrectangles; j++) { + // Down the rows of a band first, then to the next band of columns. + if (subrectangle.y1 >= clipped.y2) { + subrectangle.y1 = clipped.y1; + subrectangle.x1 += cols_per_buffer; + } + subrectangle.x2 = MIN(subrectangle.x1 + cols_per_buffer, clipped.x2); + subrectangle.y2 = MIN(subrectangle.y1 + rows_per_buffer, clipped.y2); + + uint16_t subrectangle_size_bytes; + if (self->core.colorspace.depth >= 8) { + subrectangle_size_bytes = displayio_area_size(&subrectangle) * (self->core.colorspace.depth / 8); + } else { + subrectangle_size_bytes = displayio_area_size(&subrectangle) / (8 / self->core.colorspace.depth); + } + + uint32_t *buffer = buffers[fill_index]; + memset(mask, 0, mask_length * sizeof(mask[0])); + memset(buffer, 0, buffer_size * sizeof(buffer[0])); + + displayio_display_core_fill_area(&self->core, &subrectangle, mask, buffer); + + // The previous strip must be sent before the region commands for this one. + if (sending) { + displayio_display_bus_flush(&self->bus); + displayio_display_bus_end_transaction(&self->bus); + sending = false; + _run_background_tasks(); + } + + displayio_display_bus_set_region_to_update(&self->bus, &self->core.colorspace, &subrectangle); + + // Can't acquire display bus; skip the rest of the data. + if (!displayio_display_bus_begin_transaction(&self->bus)) { + return false; + } + if (SEND_ASYNC(self)) { + _send_pixels_async(self, (uint8_t *)buffer, subrectangle_size_bytes); + sending = true; + fill_index ^= 1; + } else { + _send_pixels(self, (uint8_t *)buffer, subrectangle_size_bytes); + displayio_display_bus_end_transaction(&self->bus); + } + subrectangle.y1 = subrectangle.y2; + if (!sending) { + _run_background_tasks(); + } + } + + // Drain any remaining asynchronous transfers. + displayio_display_bus_flush(&self->bus); + if (sending) { + displayio_display_bus_end_transaction(&self->bus); + } + + return true; +} + +static void _refresh_display(busdisplay_busdisplay_obj_t *self) { + if (!displayio_display_bus_is_free(&self->bus)) { + // A refresh on this bus is already in progress. Try next display. + return; + } + if (!displayio_display_core_start_refresh(&self->core)) { + // Refresh for this display already in progress. + return; + } + + const displayio_area_t *current_area = _get_refresh_areas(self); + while (current_area != NULL) { + _refresh_area(self, current_area); + current_area = current_area->next; + } + displayio_display_core_finish_refresh(&self->core); +} + +void common_hal_busdisplay_busdisplay_set_rotation(busdisplay_busdisplay_obj_t *self, int rotation) { + displayio_display_core_set_rotation_and_update(&self->core, rotation, &self->base); +} + +uint16_t common_hal_busdisplay_busdisplay_get_rotation(busdisplay_busdisplay_obj_t *self) { + return self->core.rotation; +} + + +bool common_hal_busdisplay_busdisplay_refresh(busdisplay_busdisplay_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 != NO_FPS_LIMIT)) { + 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. + if (current_ms_since_real_refresh > maximum_ms_per_real_frame) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Below minimum frame rate")); + } + uint32_t current_ms_since_last_call = current_time - self->last_refresh_call; + self->last_refresh_call = current_time; + // Skip the actual refresh to help catch up. + if (current_ms_since_last_call > target_ms_per_frame) { + return false; + } + uint32_t remaining_time = target_ms_per_frame - (current_ms_since_real_refresh % target_ms_per_frame); + // We're ahead of the game so wait until we align with the frame rate. + while (supervisor_ticks_ms64() - self->last_refresh_call < remaining_time) { + RUN_BACKGROUND_TASKS; + } + } + self->first_manual_refresh = false; + _refresh_display(self); + return true; +} + +bool common_hal_busdisplay_busdisplay_get_auto_refresh(busdisplay_busdisplay_obj_t *self) { + return self->auto_refresh; +} + +void common_hal_busdisplay_busdisplay_set_auto_refresh(busdisplay_busdisplay_obj_t *self, + bool auto_refresh) { + self->first_manual_refresh = !auto_refresh; + if (auto_refresh != self->auto_refresh) { + if (auto_refresh) { + supervisor_enable_tick(); + } else { + supervisor_disable_tick(); + } + } + self->auto_refresh = auto_refresh; +} + +mp_obj_t common_hal_busdisplay_busdisplay_set_root_group(busdisplay_busdisplay_obj_t *self, displayio_group_t *root_group) { + bool ok = displayio_display_core_set_root_group(&self->core, root_group); + if (!ok) { + mp_raise_ValueError(MP_ERROR_TEXT("Group already used")); + } + return mp_const_none; +} + +void busdisplay_busdisplay_background(busdisplay_busdisplay_obj_t *self) { + if (self->auto_refresh && (supervisor_ticks_ms64() - self->core.last_refresh) > self->native_ms_per_frame) { + _refresh_display(self); + } +} + +void release_busdisplay(busdisplay_busdisplay_obj_t *self) { + common_hal_busdisplay_busdisplay_set_auto_refresh(self, false); + release_display_core(&self->core); + busdisplay_backlight_deinit(&self->backlight); +} + +void reset_busdisplay(busdisplay_busdisplay_obj_t *self) { + common_hal_busdisplay_busdisplay_set_auto_refresh(self, true); + circuitpython_splash.x = 0; // reset position in case someone moved it. + circuitpython_splash.y = 0; + supervisor_start_terminal(self->core.width, self->core.height); + // Show the splash if it is free, otherwise nothing. Other groups are on the VM heap. + if (!displayio_display_core_set_root_group(&self->core, &circuitpython_splash)) { + displayio_display_core_set_root_group(&self->core, NULL); + } +} + +void busdisplay_busdisplay_collect_ptrs(busdisplay_busdisplay_obj_t *self) { + displayio_display_core_collect_ptrs(&self->core); + displayio_display_bus_collect_ptrs(&self->bus); +} diff --git a/shared-module/busdisplay/legacy/BusDisplay.h b/shared-module/busdisplay/legacy/BusDisplay.h new file mode 100644 index 00000000000..a268bc5cb05 --- /dev/null +++ b/shared-module/busdisplay/legacy/BusDisplay.h @@ -0,0 +1,38 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-bindings/digitalio/DigitalInOut.h" +#include "shared-bindings/displayio/Group.h" +#if CIRCUITPY_PWMIO +#include "shared-bindings/pwmio/PWMOut.h" +#endif + +#include "shared-module/displayio/area.h" +#include "shared-module/displayio/bus_core.h" +#include "shared-module/displayio/display_core.h" + +typedef struct { + mp_obj_base_t base; + displayio_display_core_t core; + displayio_display_bus_t bus; + busdisplay_backlight_t backlight; + uint64_t last_refresh_call; + mp_float_t current_brightness; + uint16_t brightness_command; + uint16_t native_frames_per_second; + uint16_t native_ms_per_frame; + uint8_t write_ram_command; + bool auto_refresh; + bool first_manual_refresh; + bool backlight_on_high; +} busdisplay_busdisplay_obj_t; + +void busdisplay_busdisplay_background(busdisplay_busdisplay_obj_t *self); +void release_busdisplay(busdisplay_busdisplay_obj_t *self); +void reset_busdisplay(busdisplay_busdisplay_obj_t *self); +void busdisplay_busdisplay_collect_ptrs(busdisplay_busdisplay_obj_t *self); diff --git a/shared-module/busdisplay/lvgl/BusDisplay.c b/shared-module/busdisplay/lvgl/BusDisplay.c new file mode 100644 index 00000000000..c4028e7d321 --- /dev/null +++ b/shared-module/busdisplay/lvgl/BusDisplay.c @@ -0,0 +1,460 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// LVGL BusDisplay implementation for fourwire/SPI displays +// Direct render via LVGL partial buffers, SPI flush +#include "shared-bindings/busdisplay/BusDisplay.h" +#include "shared-bindings/fourwire/FourWire.h" +#include "shared-bindings/displayio/Group.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/time/__init__.h" +#include "shared-module/displayio/__init__.h" +#include "shared-module/displayio/lvgl/lvgl_internal.h" +#include "supervisor/port.h" +#include "supervisor/port_heap.h" +#include "supervisor/shared/display.h" +#include "py/runtime.h" +#include "py/gc.h" +#include +#include "lvgl.h" +#include "lvgl/draw/lv_draw_utils.h" + +// Port allocations must be aligned enough for LVGL draw buffers and the PPA. +MP_STATIC_ASSERT(MICROPY_BYTES_PER_GC_BLOCK % LV_DRAW_BUF_ALIGN == 0); + +#define LVGL_DRAW_BUF_LINES 10 + +static void busdisplay_lvgl_flush_cb(lv_display_t *disp, const lv_area_t *area, uint8_t *px_map) { + busdisplay_busdisplay_obj_t *self = lv_display_get_user_data(disp); + lv_display_rotation_t rotation = lv_display_get_rotation(disp); + lv_area_t rotated_area; + if (rotation != LV_DISPLAY_ROTATION_0) { + int32_t width = lv_area_get_width(area); + int32_t height = lv_area_get_height(area); + rotated_area = *area; + lv_display_rotate_area(disp, &rotated_area); + uint32_t src_stride = lv_draw_buf_width_to_stride(width, self->lv_color_format); + uint32_t dest_stride = lv_draw_buf_width_to_stride( + lv_area_get_width(&rotated_area), self->lv_color_format); + if ((size_t)dest_stride * lv_area_get_height(&rotated_area) > + self->lv_rotation_buf_size) { + lv_display_flush_ready(disp); + return; + } + lv_color_format_t rotate_format = self->lv_color_format; + if (rotate_format == LV_COLOR_FORMAT_RGB565_SWAPPED) { + rotate_format = LV_COLOR_FORMAT_RGB565; + } + lv_draw_rotate(px_map, self->lv_rotation_buf, width, height, + src_stride, dest_stride, rotation, rotate_format); + area = &rotated_area; + px_map = self->lv_rotation_buf; + } + uint16_t w = area->x2 - area->x1 + 1; + uint16_t h = area->y2 - area->y1 + 1; + size_t len = (size_t)w * h * ((self->color_depth + 7) / 8); + if (self->color_depth == 16 && self->reverse_bytes_in_word) { + // reverse_bytes_in_word (the default) sends the high byte first. + // Partial render mode redraws the buffer for every flush, so swap it in place. + uint8_t *end = px_map + (size_t)w * h * 2; + for (uint8_t *p = px_map; p < end; p += 2) { + uint8_t low = p[0]; + p[0] = p[1]; + p[1] = low; + } + } + if (self->color_depth == 1) { + len = (w * h + 7) / 8; + if (self->bytes_per_cell > 1) { + len *= self->bytes_per_cell; + } + } + + if (!displayio_display_bus_is_free(&self->bus)) { + // Don't run background tasks from here: on ports that render LVGL on a task, this flush + // would otherwise execute background callbacks (including the BusDisplay proxy) from + // inside LVGL's render. Block instead and let the bus owner run. + while (!displayio_display_bus_begin_transaction(&self->bus)) { + port_task_sleep_ms(1); + } + displayio_display_bus_end_transaction(&self->bus); + } + if (self->bus.bus == mp_const_none) { + lv_display_flush_ready(disp); + return; + } + + displayio_area_t displayio_area = { + .x1 = area->x1, + .y1 = area->y1, + .x2 = area->x2 + 1, + .y2 = area->y2 + 1, + }; + displayio_display_bus_set_region_to_update(&self->bus, &self->colorspace, &displayio_area); + + while (!displayio_display_bus_begin_transaction(&self->bus)) { + port_task_sleep_ms(1); + } + if (!self->bus.data_as_commands) { + uint8_t command = self->write_ram_command; + self->bus.send(self->bus.bus, DISPLAY_COMMAND, CHIP_SELECT_TOGGLE_EVERY_BYTE, &command, 1); + } + self->bus.send(self->bus.bus, DISPLAY_DATA, CHIP_SELECT_UNTOUCHED, px_map, len); + displayio_display_bus_end_transaction(&self->bus); + + lv_display_flush_ready(disp); +} + +static lv_color_format_t busdisplay_lvgl_color_format(busdisplay_busdisplay_obj_t *self) { + switch (self->color_depth) { + case 16: + return LV_COLOR_FORMAT_RGB565; + case 24: + return LV_COLOR_FORMAT_RGB888; + case 32: + return LV_COLOR_FORMAT_ARGB8888; + case 8: + return LV_COLOR_FORMAT_L8; + case 1: + return LV_COLOR_FORMAT_I1; + default: + return LV_COLOR_FORMAT_RGB565; + } +} + +typedef struct { + nlr_jump_callback_node_t node; + busdisplay_busdisplay_obj_t *self; + bool locked; +} busdisplay_construct_cleanup_t; + +static void busdisplay_construct_abort(void *ctx) { + busdisplay_construct_cleanup_t *cleanup = ctx; + busdisplay_busdisplay_obj_t *self = cleanup->self; + if (!cleanup->locked) { + displayio_lvgl_lock(); + } + if (self->root_group != NULL) { + displayio_lvgl_set_root_group(NULL); + self->root_group = NULL; + } + if (self->lv_display != NULL) { + lv_display_delete(self->lv_display); + self->lv_display = NULL; + } + port_free(self->lv_buf1); + port_free(self->lv_buf2); + port_free(self->lv_rotation_buf); + self->lv_buf1 = NULL; + self->lv_buf2 = NULL; + self->lv_rotation_buf = NULL; + self->lv_buf_size = 0; + self->lv_rotation_buf_size = 0; + busdisplay_backlight_deinit(&self->backlight); + self->deinited = true; + self->base.type = &mp_type_NoneType; + displayio_lvgl_unlock(); +} + +void common_hal_busdisplay_busdisplay_construct(busdisplay_busdisplay_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 *init_sequence, uint16_t init_sequence_len, const mcu_pin_obj_t *backlight_pin, + uint16_t brightness_command, mp_float_t 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, uint16_t backlight_pwm_frequency) { + + self->lv_display = NULL; + self->lv_buf1 = NULL; + self->lv_buf2 = NULL; + self->lv_rotation_buf = NULL; + self->lv_buf_size = 0; + self->lv_rotation_buf_size = 0; + self->root_group = NULL; + self->backlight.inout.base.type = &mp_type_NoneType; + self->auto_refresh = false; + busdisplay_construct_cleanup_t cleanup = { .self = self, .locked = false }; + nlr_push_jump_callback(&cleanup.node, busdisplay_construct_abort); + // Packed pixels require panel-specific packing and LVGL's indexed palette + // header must not be sent to the panel as pixels. + if (color_depth < 8) { + mp_raise_NotImplementedError(MP_ERROR_TEXT("Format not supported")); + } + + uint16_t ram_width = 0x100; + uint16_t ram_height = 0x100; + if (single_byte_bounds) { + ram_width = 0xff; + ram_height = 0xff; + } + displayio_display_bus_construct(&self->bus, bus, ram_width, ram_height, colstart, rowstart, + set_column_command, set_row_command, NO_COMMAND, NO_COMMAND, data_as_commands, + false /* always_toggle_chip_select */, SH1107_addressing && color_depth == 1, + false /* address_little_endian */); + self->width = width; + self->height = height; + self->rotation = 0; + self->color_depth = color_depth; + self->grayscale = grayscale; + self->pixels_in_byte_share_row = pixels_in_byte_share_row; + self->bytes_per_cell = bytes_per_cell; + self->reverse_pixels_in_byte = reverse_pixels_in_byte; + self->reverse_bytes_in_word = reverse_bytes_in_word; + self->colorspace.depth = color_depth; + self->colorspace.grayscale = grayscale; + self->colorspace.grayscale_bit = 8 - color_depth; + self->colorspace.pixels_in_byte_share_row = pixels_in_byte_share_row; + self->colorspace.bytes_per_cell = bytes_per_cell; + self->colorspace.reverse_pixels_in_byte = reverse_pixels_in_byte; + self->colorspace.reverse_bytes_in_word = reverse_bytes_in_word; + self->write_ram_command = write_ram_command; + self->brightness_command = brightness_command; + self->backlight_on_high = backlight_on_high; + self->auto_refresh = false; + self->first_manual_refresh = !auto_refresh; + self->native_frames_per_second = native_frames_per_second; + self->native_ms_per_frame = 1000 / (native_frames_per_second ? native_frames_per_second : 60); + self->current_brightness = brightness; + self->deinited = false; + self->root_group = NULL; + busdisplay_backlight_construct(&self->backlight, backlight_pin, backlight_pwm_frequency); + common_hal_busdisplay_busdisplay_set_brightness(self, brightness); + + displayio_display_bus_send_init_sequence(&self->bus, init_sequence, init_sequence_len); + + displayio_lvgl_port_init(); + // Hold the render lock across the whole setup so the render task can't see a half-configured + // display. The port lock is recursive. + displayio_lvgl_lock(); + cleanup.locked = true; + + // Create LVGL display + self->lv_display = lv_display_create(width, height); + if (self->lv_display == NULL) { + mp_raise_RuntimeError(MP_ERROR_TEXT("LVGL display create failed")); + } + lv_display_set_user_data(self->lv_display, self); + self->lv_color_format = busdisplay_lvgl_color_format(self); + lv_display_set_color_format(self->lv_display, self->lv_color_format); + + // Allocate draw buffers via port_malloc. Displays outlive the VM, so these + // can't come from the garbage collected heap. + size_t bpp = (color_depth + 7) / 8; + if (bpp == 0) { + bpp = 1; + } + size_t buf_lines = LVGL_DRAW_BUF_LINES; + if (buf_lines > height) { + buf_lines = height; + } + size_t buf_size = width * buf_lines * bpp; + // Align to 4 bytes + buf_size = (buf_size + 3) & ~3; + // Ports with LVGL keep port_malloc() allocations aligned for the PPA and LVGL draw + // buffers. + self->lv_buf1 = port_malloc(buf_size, false); + self->lv_buf2 = port_malloc(buf_size, false); + self->lv_rotation_buf = port_malloc(buf_size, false); + if (self->lv_buf1 == NULL || self->lv_buf2 == NULL || self->lv_rotation_buf == NULL) { + mp_raise_msg(&mp_type_MemoryError, MP_ERROR_TEXT("LVGL buffer alloc failed")); + } + self->lv_buf_size = buf_size; + self->lv_rotation_buf_size = buf_size; + lv_display_set_buffers(self->lv_display, self->lv_buf1, self->lv_buf2, buf_size, LV_DISPLAY_RENDER_MODE_PARTIAL); + lv_display_set_flush_cb(self->lv_display, busdisplay_lvgl_flush_cb); + + // BusDisplay's flush drives the display bus and may run background tasks, so ports that + // render LVGL on a separate task route this display's refresh through a proxy that runs + // lv_refr_now() on the CircuitPython thread. Ports that render BusDisplay on their own LVGL + // thread (Zephyr) leave the refresh timer alone. + displayio_lvgl_port_install_busdisplay_refresh(self->lv_display); + + displayio_lvgl_init(); + + // Set initial root group to splash - make this display default first + self->root_group = &circuitpython_splash; + lv_display_set_default(self->lv_display); + displayio_lvgl_register_display(self->lv_display); + displayio_lvgl_set_root_group(&circuitpython_splash); + nlr_pop_jump_callback(false); + displayio_lvgl_unlock(); + + if (rotation != 0) { + common_hal_busdisplay_busdisplay_set_rotation(self, rotation); + } + + common_hal_busdisplay_busdisplay_set_auto_refresh(self, auto_refresh); +} + +// Stubs for remaining API - to be implemented +uint16_t common_hal_busdisplay_busdisplay_get_width(busdisplay_busdisplay_obj_t *self) { + return self->width; +} +uint16_t common_hal_busdisplay_busdisplay_get_height(busdisplay_busdisplay_obj_t *self) { + return self->height; +} +uint16_t common_hal_busdisplay_busdisplay_get_rotation(busdisplay_busdisplay_obj_t *self) { + return self->rotation; +} +void common_hal_busdisplay_busdisplay_set_rotation(busdisplay_busdisplay_obj_t *self, int rotation) { + rotation %= 360; + bool transposed = (self->rotation == 90 || self->rotation == 270); + bool will_transposed = (rotation == 90 || rotation == 270); + if (transposed != will_transposed) { + int tmp = self->width; + self->width = self->height; + self->height = tmp; + } + self->rotation = rotation; + + nlr_jump_callback_node_t cleanup; + displayio_lvgl_lock_with_cleanup(&cleanup); + if (self->lv_display != NULL) { + // LVGL rotates the opposite way from displayio for the transposed orientations. + lv_display_rotation_t lv_rotation; + switch (rotation) { + case 90: + lv_rotation = LV_DISPLAY_ROTATION_270; + break; + case 270: + lv_rotation = LV_DISPLAY_ROTATION_90; + break; + case 180: + lv_rotation = LV_DISPLAY_ROTATION_180; + break; + default: + lv_rotation = LV_DISPLAY_ROTATION_0; + break; + } + lv_display_set_rotation(self->lv_display, lv_rotation); + lv_display_set_default(self->lv_display); + } + + if (self == &displays[0].display) { + supervisor_stop_terminal(); + supervisor_start_terminal(self->width, self->height); + } + if (self->root_group != NULL) { + displayio_lvgl_set_root_group(self->root_group); + } + lv_obj_t *screen = lv_screen_active(); + if (screen != NULL) { + lv_obj_invalidate(screen); + } + displayio_lvgl_unlock_with_cleanup(); +} +bool common_hal_busdisplay_busdisplay_get_auto_refresh(busdisplay_busdisplay_obj_t *self) { + return self->auto_refresh; +} +void common_hal_busdisplay_busdisplay_set_auto_refresh(busdisplay_busdisplay_obj_t *self, bool auto_refresh) { + self->auto_refresh = auto_refresh; +} +bool common_hal_busdisplay_busdisplay_refresh(busdisplay_busdisplay_obj_t *self, uint32_t target_ms_per_frame, uint32_t maximum_ms_per_real_frame) { + if (self->lv_display) { + // The renderer refreshes on its own thread too, so this has to exclude it. + displayio_lvgl_lock(); + lv_refr_now(self->lv_display); + displayio_lvgl_unlock(); + } + return true; +} +mp_obj_t common_hal_busdisplay_busdisplay_get_bus(busdisplay_busdisplay_obj_t *self) { + return self->bus.bus; +} +mp_obj_t common_hal_busdisplay_busdisplay_get_root_group(busdisplay_busdisplay_obj_t *self) { + return self->root_group ? self->root_group : mp_const_none; +} +mp_obj_t common_hal_busdisplay_busdisplay_set_root_group(busdisplay_busdisplay_obj_t *self, displayio_group_t *root_group) { + self->root_group = root_group; + nlr_jump_callback_node_t cleanup; + displayio_lvgl_lock_with_cleanup(&cleanup); + // Group can only be on one display at a time. + if (root_group != NULL) { + lv_display_set_default(self->lv_display); + } + displayio_lvgl_set_root_group(root_group); + displayio_lvgl_unlock_with_cleanup(); + return mp_const_none; +} +mp_float_t common_hal_busdisplay_busdisplay_get_brightness(busdisplay_busdisplay_obj_t *self) { + return self->current_brightness; +} +bool common_hal_busdisplay_busdisplay_set_brightness(busdisplay_busdisplay_obj_t *self, mp_float_t brightness) { + if (!self->backlight_on_high) { + brightness = 1.0 - brightness; + } + bool ok = busdisplay_backlight_set(&self->backlight, brightness); + if (ok) { + self->current_brightness = brightness; + } + return ok; +} +bool common_hal_busdisplay_busdisplay_get_dither(busdisplay_busdisplay_obj_t *self) { + return false; +} +void common_hal_busdisplay_busdisplay_set_dither(busdisplay_busdisplay_obj_t *self, bool dither) { +} +void busdisplay_busdisplay_background(busdisplay_busdisplay_obj_t *self) { + // The port's LVGL render task owns the pump. Keeping this free of lv_timer_handler() + // guarantees LVGL only renders on its own tick, a frame boundary, or display.refresh(). + (void)self; +} +void release_busdisplay(busdisplay_busdisplay_obj_t *self) { + self->deinited = true; + nlr_jump_callback_node_t cleanup; + displayio_lvgl_lock_with_cleanup(&cleanup); + displayio_lvgl_set_root_group(NULL); + if (self->lv_display != NULL) { + lv_display_delete(self->lv_display); + self->lv_display = NULL; + } + displayio_lvgl_unlock_with_cleanup(); + // Draw buffers are allocated from the port heap, not LVGL's heap, so free them + // explicitly after the display that referenced them is gone. + port_free(self->lv_buf1); + port_free(self->lv_buf2); + port_free(self->lv_rotation_buf); + self->lv_buf1 = NULL; + self->lv_buf2 = NULL; + self->lv_rotation_buf = NULL; + self->lv_buf_size = 0; + self->lv_rotation_buf_size = 0; + self->root_group = NULL; + busdisplay_backlight_deinit(&self->backlight); + self->base.type = &mp_type_NoneType; +} +void reset_busdisplay(busdisplay_busdisplay_obj_t *self) { + common_hal_busdisplay_busdisplay_set_auto_refresh(self, true); + circuitpython_splash.x = 0; // reset position in case someone moved it. + circuitpython_splash.y = 0; + supervisor_start_terminal(self->width, self->height); + // Show the splash if it is free, otherwise nothing. Other groups are on the VM heap. + if (!circuitpython_splash.in_group) { + nlr_jump_callback_node_t cleanup; + displayio_lvgl_lock_with_cleanup(&cleanup); + self->root_group = &circuitpython_splash; + displayio_lvgl_set_root_group(&circuitpython_splash); + if (self->lv_display != NULL) { + lv_refr_now(self->lv_display); + } + displayio_lvgl_unlock_with_cleanup(); + } else { + self->root_group = NULL; + nlr_jump_callback_node_t cleanup; + displayio_lvgl_lock_with_cleanup(&cleanup); + displayio_lvgl_set_root_group(NULL); + if (self->lv_display != NULL) { + lv_refr_now(self->lv_display); + } + displayio_lvgl_unlock_with_cleanup(); + } +} +void busdisplay_busdisplay_collect_ptrs(busdisplay_busdisplay_obj_t *self) { + gc_collect_ptr(self->root_group); + displayio_display_bus_collect_ptrs(&self->bus); +} diff --git a/shared-module/busdisplay/lvgl/BusDisplay.h b/shared-module/busdisplay/lvgl/BusDisplay.h new file mode 100644 index 00000000000..6f719b372ff --- /dev/null +++ b/shared-module/busdisplay/lvgl/BusDisplay.h @@ -0,0 +1,60 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "lvgl.h" + +#include "shared-bindings/digitalio/DigitalInOut.h" +#include "shared-bindings/displayio/Group.h" +#include "shared-module/displayio/bus_core.h" +#if CIRCUITPY_PWMIO +#include "shared-bindings/pwmio/PWMOut.h" +#endif + +// LVGL-backed BusDisplay. There is no display_core/bus_core; the display owns an +// lv_display_t and keeps the display bus as an mp_obj_t so the GC can see it. +typedef struct { + mp_obj_base_t base; + // Bus the display is attached to (fourwire, etc.). + displayio_display_bus_t bus; + // LVGL display handle - owns draw buffers and flush CB + lv_display_t *lv_display; + lv_color_format_t lv_color_format; + void *lv_buf1; + void *lv_buf2; + size_t lv_buf_size; + void *lv_rotation_buf; + size_t lv_rotation_buf_size; + displayio_group_t *root_group; + // Display geometry / commands retained for flush + uint16_t width; + uint16_t height; + uint16_t rotation; + uint16_t color_depth; + _displayio_colorspace_t colorspace; + 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 write_ram_command; + busdisplay_backlight_t backlight; + uint64_t last_refresh_call; + mp_float_t current_brightness; + uint16_t brightness_command; + uint16_t native_frames_per_second; + uint16_t native_ms_per_frame; + bool auto_refresh; + bool first_manual_refresh; + bool backlight_on_high; + bool deinited; +} busdisplay_busdisplay_obj_t; + +void busdisplay_busdisplay_background(busdisplay_busdisplay_obj_t *self); +void release_busdisplay(busdisplay_busdisplay_obj_t *self); +void reset_busdisplay(busdisplay_busdisplay_obj_t *self); +void busdisplay_busdisplay_collect_ptrs(busdisplay_busdisplay_obj_t *self); diff --git a/shared-module/busio/SPI.c b/shared-module/busio/SPI.c new file mode 100644 index 00000000000..e7f0d0b6e26 --- /dev/null +++ b/shared-module/busio/SPI.c @@ -0,0 +1,129 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/busio/SPI.h" + +#include "py/runtime.h" +#include "supervisor/background_callback.h" +#include "shared/runtime/interrupt_char.h" + +// False when interrupted (Ctrl-C); the operation is then still running. +static bool wait(circuitpy_async_flag_t *done) { + while (!CIRCUITPY_ASYNC_FLAG_IS_SET(done)) { + RUN_BACKGROUND_TASKS; + if (mp_hal_is_interrupted()) { + return false; + } + } + return true; +} + +#if CIRCUITPY_BUSIO_SPI_ASYNC +// Finish a write_start(). No background tasks: the caller holds the bus inside a transaction, +// and one of them may want it. +static void end_sent(busio_spi_obj_t *self) { + if (self->sent == NULL) { + return; + } + while (!CIRCUITPY_ASYNC_FLAG_IS_SET(self->sent)) { + } + common_hal_async_spi_spi_transfer_finish(&self->async_spi, self->sent_context, self->sent); + self->sent = NULL; +} +#endif + +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, bool half_duplex) { + if (half_duplex) { + mp_raise_NotImplementedError_varg(MP_ERROR_TEXT("%q"), MP_QSTR_half_duplex); + } + common_hal_async_spi_spi_construct(&self->async_spi, clock, mosi, miso); + self->sent = NULL; +} + +bool common_hal_busio_spi_deinited(busio_spi_obj_t *self) { + return common_hal_async_spi_spi_deinited(&self->async_spi); +} + +void common_hal_busio_spi_mark_deinit(busio_spi_obj_t *self) { + common_hal_async_spi_spi_mark_deinit(&self->async_spi); +} + +void common_hal_busio_spi_deinit(busio_spi_obj_t *self) { + common_hal_async_spi_spi_deinit(&self->async_spi); +} + +bool common_hal_busio_spi_configure(busio_spi_obj_t *self, uint32_t baudrate, uint8_t polarity, + uint8_t phase, uint8_t bits) { + common_hal_async_spi_spi_configure(&self->async_spi, baudrate, polarity, phase, bits); + return true; +} + +// The same lock as async_spi's, so C code and async code share the bus the same way. +bool common_hal_busio_spi_try_lock(busio_spi_obj_t *self) { + if (common_hal_busio_spi_deinited(self)) { + return false; + } + return circuitpy_async_lock_try(common_hal_async_spi_spi_get_lock(&self->async_spi)); +} + +bool common_hal_busio_spi_has_lock(busio_spi_obj_t *self) { + return circuitpy_async_lock_held(common_hal_async_spi_spi_get_lock(&self->async_spi)); +} + +void common_hal_busio_spi_unlock(busio_spi_obj_t *self) { + circuitpy_async_lock_release(common_hal_async_spi_spi_get_lock(&self->async_spi)); +} + +// Finish the transfer started with self->done. +static bool finish(busio_spi_obj_t *self, void *context) { + if (!wait(&self->done)) { + common_hal_async_spi_spi_transfer_cancel(&self->async_spi, context, &self->done); + mp_handle_pending(true); // raises the KeyboardInterrupt + return false; + } + return common_hal_async_spi_spi_transfer_finish(&self->async_spi, context, &self->done); +} + +bool common_hal_busio_spi_write(busio_spi_obj_t *self, const uint8_t *data, size_t len) { + return finish(self, common_hal_async_spi_spi_write_start(&self->async_spi, data, len, &self->done)); +} + +bool common_hal_busio_spi_read(busio_spi_obj_t *self, uint8_t *data, size_t len, + uint8_t write_value) { + return finish(self, common_hal_async_spi_spi_readinto_start(&self->async_spi, data, len, write_value, + &self->done)); +} + +bool common_hal_busio_spi_transfer(busio_spi_obj_t *self, const uint8_t *data_out, + uint8_t *data_in, size_t len) { + return finish(self, common_hal_async_spi_spi_write_readinto_start(&self->async_spi, data_out, data_in, + len, &self->done)); +} + +#if CIRCUITPY_BUSIO_SPI_ASYNC +void common_hal_busio_spi_write_start(busio_spi_obj_t *self, const uint8_t *data, size_t len, + circuitpy_async_flag_t *done) { + self->sent_context = common_hal_async_spi_spi_write_start(&self->async_spi, data, len, done); + self->sent = done; +} + +void common_hal_busio_spi_end(busio_spi_obj_t *self) { + end_sent(self); +} +#endif + +uint32_t common_hal_busio_spi_get_frequency(busio_spi_obj_t *self) { + return common_hal_async_spi_spi_get_frequency(&self->async_spi); +} + +uint8_t common_hal_busio_spi_get_phase(busio_spi_obj_t *self) { + return common_hal_async_spi_spi_get_phase(&self->async_spi); +} + +uint8_t common_hal_busio_spi_get_polarity(busio_spi_obj_t *self) { + return common_hal_async_spi_spi_get_polarity(&self->async_spi); +} diff --git a/shared-module/busio/SPI.h b/shared-module/busio/SPI.h new file mode 100644 index 00000000000..e38f6d7e331 --- /dev/null +++ b/shared-module/busio/SPI.h @@ -0,0 +1,21 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +// busio.SPI built on a port's async_spi implementation: every blocking call starts an async +// transfer and waits for it. A port that has async_spi includes this header from its +// common-hal/busio/SPI.h and sets CIRCUITPY_ASYNC_SPI = 1 in its mpconfigport.mk. + +#pragma once + +#include "shared-bindings/async_spi/SPI.h" + +typedef struct { + mp_obj_base_t base; + async_spi_spi_obj_t async_spi; + circuitpy_async_flag_t done; // of the blocking transfer in progress + circuitpy_async_flag_t *sent; // of a write_start() not yet ended, NULL otherwise + void *sent_context; +} busio_spi_obj_t; diff --git a/shared-module/cryptography/__init__.c b/shared-module/cryptography/__init__.c new file mode 100644 index 00000000000..30ab92a1b09 --- /dev/null +++ b/shared-module/cryptography/__init__.c @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +// Nothing here diff --git a/shared-module/cryptography/exceptions/__init__.c b/shared-module/cryptography/exceptions/__init__.c new file mode 100644 index 00000000000..30ab92a1b09 --- /dev/null +++ b/shared-module/cryptography/exceptions/__init__.c @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +// Nothing here diff --git a/shared-module/cryptography/hazmat/__init__.c b/shared-module/cryptography/hazmat/__init__.c new file mode 100644 index 00000000000..30ab92a1b09 --- /dev/null +++ b/shared-module/cryptography/hazmat/__init__.c @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +// Nothing here diff --git a/shared-module/cryptography/hazmat/primitives/__init__.c b/shared-module/cryptography/hazmat/primitives/__init__.c new file mode 100644 index 00000000000..30ab92a1b09 --- /dev/null +++ b/shared-module/cryptography/hazmat/primitives/__init__.c @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +// Nothing here diff --git a/shared-module/cryptography/hazmat/primitives/asymmetric/__init__.c b/shared-module/cryptography/hazmat/primitives/asymmetric/__init__.c new file mode 100644 index 00000000000..30ab92a1b09 --- /dev/null +++ b/shared-module/cryptography/hazmat/primitives/asymmetric/__init__.c @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +// Nothing here diff --git a/shared-module/cryptography/hazmat/primitives/asymmetric/ec/EllipticCurvePublicKey.c b/shared-module/cryptography/hazmat/primitives/asymmetric/ec/EllipticCurvePublicKey.c new file mode 100644 index 00000000000..d52a9f27b17 --- /dev/null +++ b/shared-module/cryptography/hazmat/primitives/asymmetric/ec/EllipticCurvePublicKey.c @@ -0,0 +1,75 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#include + +#include "py/runtime.h" + +#include "mbedtls/psa_util.h" + +#include "shared-bindings/cryptography/exceptions/__init__.h" +#include "shared-module/cryptography/hazmat/primitives/asymmetric/ec/EllipticCurvePublicKey.h" + +#define P256_KEY_BITS 256 +// SEC1 uncompressed point: 0x04 || X || Y, X and Y each 32 bytes for P-256. +#define P256_POINT_LEN 65 + +void common_hal_cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_construct( + cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_obj_t *self, + mp_obj_t curve, const uint8_t *point, size_t point_len) { + mp_arg_validate_length(point_len, P256_POINT_LEN, MP_QSTR_data); + if (point[0] != 0x04) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("Invalid %q"), MP_QSTR_data); + } + + // PSA is already initialized by ssl / hashlib / hardwarekey, but + // psa_crypto_init() is idempotent and keeps this module working on a + // build with none of those (see common-hal/hardwarekey/HardwareKey.c's + // identical call for the same reason). + if (psa_crypto_init() != PSA_SUCCESS) { + mp_raise_RuntimeError(NULL); + } + + psa_key_attributes_t attr = PSA_KEY_ATTRIBUTES_INIT; + psa_set_key_type(&attr, PSA_KEY_TYPE_ECC_PUBLIC_KEY(PSA_ECC_FAMILY_SECP_R1)); + psa_set_key_bits(&attr, P256_KEY_BITS); + psa_set_key_usage_flags(&attr, PSA_KEY_USAGE_VERIFY_HASH); + psa_set_key_algorithm(&attr, PSA_ALG_ECDSA(PSA_ALG_SHA_256)); + + psa_key_id_t key_id = 0; + psa_status_t status = psa_import_key(&attr, point, point_len, &key_id); + if (status != PSA_SUCCESS) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("Invalid %q"), MP_QSTR_data); + } + + self->curve = curve; + memcpy(self->point, point, P256_POINT_LEN); + self->key_id = key_id; +} + +void common_hal_cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_verify( + cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_obj_t *self, + const uint8_t *signature, size_t signature_len, const uint8_t *digest, size_t digest_len) { + mp_arg_validate_length(digest_len, 32, MP_QSTR_digest); + + // PSA's own ECDSA signature format is raw r||s, not the ASN.1 DER real + // PyCA's verify() takes -- mbedtls_ecdsa_der_to_raw() is the same, + // already-in-this-tree conversion esp_crt_bundle.c uses for ECDSA + // cert-chain verification via PSA. + uint8_t raw_sig[MBEDTLS_ECDSA_MAX_LEN]; + size_t raw_sig_len = 0; + int ret = mbedtls_ecdsa_der_to_raw(P256_KEY_BITS, signature, signature_len, + raw_sig, sizeof(raw_sig), &raw_sig_len); + if (ret != 0) { + mp_raise_cryptography_InvalidSignature(MP_ERROR_TEXT("Invalid %q"), MP_QSTR_signature); + } + + psa_status_t status = psa_verify_hash(self->key_id, PSA_ALG_ECDSA(PSA_ALG_SHA_256), + digest, digest_len, raw_sig, raw_sig_len); + if (status != PSA_SUCCESS) { + mp_raise_cryptography_InvalidSignature(MP_ERROR_TEXT("Invalid %q"), MP_QSTR_signature); + } +} diff --git a/shared-module/cryptography/hazmat/primitives/asymmetric/ec/EllipticCurvePublicKey.h b/shared-module/cryptography/hazmat/primitives/asymmetric/ec/EllipticCurvePublicKey.h new file mode 100644 index 00000000000..3a2487780dc --- /dev/null +++ b/shared-module/cryptography/hazmat/primitives/asymmetric/ec/EllipticCurvePublicKey.h @@ -0,0 +1,49 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include + +#include "py/obj.h" + +#include "psa/crypto.h" + +// Produced only by +// cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey.from_encoded_point(). +// Unlike DigitalSignatureKey, this holds no secret material and needs no +// port-specific driver: importing a public point and verifying against it +// are both plain, portable PSA crypto calls, so this type is entirely +// portable (no common-hal split). +typedef struct { + mp_obj_base_t base; + // Backref to the curve singleton this was loaded for, for the `curve` + // property. Always cryptography_hazmat_primitives_asymmetric_ec_secp256r1_obj + // today, but kept as a field (not hardcoded in the property getter) so a + // second curve, if one is ever added, doesn't need a new key type. + mp_obj_t curve; + // The uncompressed SEC1 point (0x04 || X || Y) this key was constructed + // from, kept verbatim for public_bytes(). Always 65 bytes for P-256. + uint8_t point[65]; + psa_key_id_t key_id; +} cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_obj_t; + +// Validates point_len/point (must be a 65-byte 0x04-prefixed SEC1 point for +// P-256) and imports it into PSA as a PSA_KEY_TYPE_ECC_PUBLIC_KEY. Raises +// ValueError on a malformed point. +void common_hal_cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_construct( + cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_obj_t *self, + mp_obj_t curve, const uint8_t *point, size_t point_len); + +// psa_verify_hash() against self->key_id, after converting `signature` from +// DER to the raw r||s format PSA expects. `digest` must be a 32-byte SHA-256 +// digest (the Prehashed contract) -- raises ValueError if it isn't that +// length, or cryptography.exceptions.InvalidSignature if the signature is +// malformed or does not verify. +void common_hal_cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_verify( + cryptography_hazmat_primitives_asymmetric_ec_ellipticcurvepublickey_obj_t *self, + const uint8_t *signature, size_t signature_len, const uint8_t *digest, size_t digest_len); diff --git a/shared-module/cryptography/hazmat/primitives/asymmetric/ec/__init__.c b/shared-module/cryptography/hazmat/primitives/asymmetric/ec/__init__.c new file mode 100644 index 00000000000..30ab92a1b09 --- /dev/null +++ b/shared-module/cryptography/hazmat/primitives/asymmetric/ec/__init__.c @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +// Nothing here diff --git a/shared-module/cryptography/hazmat/primitives/asymmetric/padding/__init__.c b/shared-module/cryptography/hazmat/primitives/asymmetric/padding/__init__.c new file mode 100644 index 00000000000..30ab92a1b09 --- /dev/null +++ b/shared-module/cryptography/hazmat/primitives/asymmetric/padding/__init__.c @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +// Nothing here diff --git a/shared-module/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c b/shared-module/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c new file mode 100644 index 00000000000..eb376c77003 --- /dev/null +++ b/shared-module/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.c @@ -0,0 +1,61 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#include "py/runtime.h" + +#include "shared-module/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.h" + +mp_int_t common_hal_cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_get_key_size( + cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_obj_t *self) { + return self->key_size; +} + +psa_key_id_t common_hal_cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_get_key_id( + cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_obj_t *self) { + return self->key_id; +} + +// Portable: once ensure_algorithm() (port-specific) has produced a PSA key id +// for the DS peripheral, signing is the same PSA call as any other opaque +// RSA key. The DS peripheral hashes+pads internally when driven this way, so +// callers never see a raw RSA exponentiation primitive. +void common_hal_cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_sign( + cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_obj_t *self, + const uint8_t *data, size_t data_len, uint8_t *sig_out, size_t sig_out_len) { + common_hal_cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_ensure_algorithm(self, + PSA_ALG_RSA_PKCS1V15_SIGN(PSA_ALG_ANY_HASH), + PSA_KEY_USAGE_SIGN_MESSAGE | PSA_KEY_USAGE_SIGN_HASH); + + size_t sig_len = 0; + psa_status_t status = psa_sign_message(self->key_id, + PSA_ALG_RSA_PKCS1V15_SIGN(PSA_ALG_SHA_256), + data, data_len, sig_out, sig_out_len, &sig_len); + if (status != PSA_SUCCESS) { + mp_raise_RuntimeError(NULL); + } +} + +// Portable: once ensure_algorithm() (port-specific) has produced a PSA key id +// committed to `alg`, decryption is the same PSA call as any other opaque RSA +// key. The DS peripheral removes the padding internally, so *output_len is the +// recovered plaintext length, not key_size / 8. +void common_hal_cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_decrypt( + cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_obj_t *self, + psa_algorithm_t alg, const uint8_t *ciphertext, size_t ciphertext_len, + uint8_t *plaintext_out, size_t plaintext_out_size, size_t *output_len) { + common_hal_cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_ensure_algorithm(self, + alg, PSA_KEY_USAGE_DECRYPT); + + psa_status_t status = psa_asymmetric_decrypt(self->key_id, alg, + ciphertext, ciphertext_len, NULL, 0, plaintext_out, plaintext_out_size, output_len); + if (status == PSA_ERROR_NOT_SUPPORTED && PSA_ALG_IS_RSA_OAEP(alg)) { + mp_raise_NotImplementedError( + MP_ERROR_TEXT("OAEP requires this build to enable TLS 1.3 support")); + } + if (status != PSA_SUCCESS) { + mp_raise_RuntimeError(NULL); + } +} diff --git a/shared-module/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.h b/shared-module/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.h new file mode 100644 index 00000000000..d151628531c --- /dev/null +++ b/shared-module/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.h @@ -0,0 +1,84 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include + +#include "py/obj.h" + +#include "psa/crypto.h" + +#include "shared-module/hardwarekey/HardwareKey.h" + +// Produced only by cryptography.hazmat.primitives.asymmetric.rsa.load_digital_signature_key(). +// Holds the state a Digital Signature (RSA) key needs that a generic +// HardwareKey has no business carrying: the decrypted-params-derived key +// size, which PSA algorithm the key has committed to, and the PSA key id once +// it's actually been imported. +typedef struct { + mp_obj_base_t base; + // Backref to the HardwareKey this was loaded from. Used internally (repr, + // error messages, indexing the port's per-slot cache via + // common_hal_hardwarekey_hardwarekey_get_key_slot()) -- not exposed to Python. + mp_obj_t source_key; + mp_int_t key_size; + // The PSA algorithm key_id was imported under, once ensure_algorithm() has + // run for the first time. PSA_ALG_NONE (0) until then. Reusing an RSA key + // under more than one algorithm is a real cryptographic risk, not just a + // PSA API nicety, so this key commits to the first algorithm it's + // actually used with. + psa_algorithm_t committed_alg; + psa_key_id_t key_id; + // Snapshot, at construction time, of the port's per-slot cache generation + // counter. A slot's cache is shared C-level state, not owned by any one + // DigitalSignatureKey object; loading a new key for the same slot bumps the + // generation, so an older, not-yet-committed object can tell its cached + // ds_params were replaced out from under it instead of silently importing + // the wrong key material. See ensure_algorithm() below. + uint32_t generation; +} cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_obj_t; + +mp_int_t common_hal_cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_get_key_size( + cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_obj_t *self); +// The PSA key id, for ssl's mbedtls_pk_wrap_psa(). 0 until ensure_algorithm() +// has committed and imported a key. +psa_key_id_t common_hal_cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_get_key_id( + cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_obj_t *self); + +// Port-specific: only the port knows how to turn a ds_params blob into a PSA +// key reference. Caches ds_params and computes key_size, but does NOT import a +// PSA key yet -- see ensure_algorithm() below for why. Raises ValueError on a +// malformed blob. +void common_hal_cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_construct( + cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_obj_t *self, + hardwarekey_hardwarekey_obj_t *source_key, const uint8_t *ds_params, size_t ds_params_len); + +// Port-specific: on the first call, imports self->key_id under exactly `alg` +// and `usage`. On a later call, either confirms `alg` matches what was already +// committed (no-op) or raises ValueError -- this key already committed to a +// different algorithm. Also raises ValueError if this object's cached +// ds_params were superseded by a later load_digital_signature_key() call for +// the same key slot before this object ever committed (see `generation` +// above). +void common_hal_cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_ensure_algorithm( + cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_obj_t *self, + psa_algorithm_t alg, psa_key_usage_t usage); + +// Portable: psa_sign_message() against self->key_id. sig_out must be +// key_size / 8 bytes. +void common_hal_cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_sign( + cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_obj_t *self, + const uint8_t *data, size_t data_len, uint8_t *sig_out, size_t sig_out_len); + +// Portable: psa_asymmetric_decrypt() against self->key_id. plaintext_out must +// be at least key_size / 8 bytes; the actual plaintext length (after padding +// removal) is returned via *output_len. +void common_hal_cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_decrypt( + cryptography_hazmat_primitives_asymmetric_rsa_digitalsignaturekey_obj_t *self, + psa_algorithm_t alg, const uint8_t *ciphertext, size_t ciphertext_len, + uint8_t *plaintext_out, size_t plaintext_out_size, size_t *output_len); diff --git a/shared-module/cryptography/hazmat/primitives/asymmetric/rsa/__init__.c b/shared-module/cryptography/hazmat/primitives/asymmetric/rsa/__init__.c new file mode 100644 index 00000000000..30ab92a1b09 --- /dev/null +++ b/shared-module/cryptography/hazmat/primitives/asymmetric/rsa/__init__.c @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +// Nothing here diff --git a/shared-module/cryptography/hazmat/primitives/asymmetric/utils/__init__.c b/shared-module/cryptography/hazmat/primitives/asymmetric/utils/__init__.c new file mode 100644 index 00000000000..30ab92a1b09 --- /dev/null +++ b/shared-module/cryptography/hazmat/primitives/asymmetric/utils/__init__.c @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +// Nothing here diff --git a/shared-module/cryptography/hazmat/primitives/hashes/__init__.c b/shared-module/cryptography/hazmat/primitives/hashes/__init__.c new file mode 100644 index 00000000000..30ab92a1b09 --- /dev/null +++ b/shared-module/cryptography/hazmat/primitives/hashes/__init__.c @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +// Nothing here diff --git a/shared-module/displayio/Bitmap.c b/shared-module/displayio/Bitmap.c deleted file mode 100644 index d5236f6b4f6..00000000000 --- a/shared-module/displayio/Bitmap.c +++ /dev/null @@ -1,223 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2018 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "shared-bindings/displayio/Bitmap.h" - -#include - -#include "py/runtime.h" -#include "py/gc.h" - -enum { ALIGN_BITS = 8 * sizeof(uint32_t) }; - -static int stride(uint32_t width, uint32_t bits_per_value) { - uint32_t row_width = width * bits_per_value; - // align to uint32_t - return (row_width + ALIGN_BITS - 1) / ALIGN_BITS; -} - -void common_hal_displayio_bitmap_construct(displayio_bitmap_t *self, uint32_t width, - uint32_t height, uint32_t bits_per_value) { - common_hal_displayio_bitmap_construct_from_buffer(self, width, height, bits_per_value, NULL, false); -} - -void common_hal_displayio_bitmap_construct_from_buffer(displayio_bitmap_t *self, uint32_t width, - uint32_t height, uint32_t bits_per_value, uint32_t *data, bool read_only) { - self->width = width; - self->height = height; - self->stride = stride(width, bits_per_value); - self->data_alloc = false; - if (!data) { - data = m_malloc(self->stride * height * sizeof(uint32_t)); - self->data_alloc = true; - } - self->data = data; - self->read_only = read_only; - self->bits_per_value = bits_per_value; - - if (bits_per_value > 8 && bits_per_value != 16 && bits_per_value != 32) { - mp_raise_NotImplementedError(MP_ERROR_TEXT("Invalid bits per value")); - } - - // Division and modulus can be slow because it has to handle any integer. We know bits_per_value - // is a power of two. We divide and mod by bits_per_value to compute the offset into the byte - // array. So, we can the offset computation to simplify to a shift for division and mask for mod. - - 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 < 8 / bits_per_value) { - self->x_shift++; - power_of_two <<= 1; - } - self->x_mask = (1u << self->x_shift) - 1u; // Used as a modulus on the x value - self->bitmask = (1u << bits_per_value) - 1u; - - self->dirty_area.x1 = 0; - self->dirty_area.x2 = width; - self->dirty_area.y1 = 0; - self->dirty_area.y2 = height; -} - -void common_hal_displayio_bitmap_deinit(displayio_bitmap_t *self) { - if (self->data_alloc) { - gc_free(self->data); - } - self->data = NULL; -} - -bool common_hal_displayio_bitmap_deinited(displayio_bitmap_t *self) { - return self->data == NULL; -} - -uint16_t common_hal_displayio_bitmap_get_height(displayio_bitmap_t *self) { - return self->height; -} - -uint16_t common_hal_displayio_bitmap_get_width(displayio_bitmap_t *self) { - return self->width; -} - -uint32_t common_hal_displayio_bitmap_get_bits_per_value(displayio_bitmap_t *self) { - return self->bits_per_value; -} - -uint32_t common_hal_displayio_bitmap_get_pixel(displayio_bitmap_t *self, int16_t x, int16_t y) { - if (x >= self->width || x < 0 || y >= self->height || y < 0) { - return 0; - } - int32_t row_start = y * self->stride; - uint32_t *row = self->data + row_start; - uint8_t bytes_per_value = self->bits_per_value / 8; - uint8_t values_per_byte = 8 / self->bits_per_value; - if (bytes_per_value < 1) { - uint8_t bits = ((uint8_t *)row)[x >> self->x_shift]; - uint8_t bit_position = (values_per_byte - (x & self->x_mask) - 1) * self->bits_per_value; - return (bits >> bit_position) & self->bitmask; - } else { - if (bytes_per_value == 1) { - return ((uint8_t *)row)[x]; - } else if (bytes_per_value == 2) { - return ((uint16_t *)row)[x]; - } else if (bytes_per_value == 4) { - return ((uint32_t *)row)[x]; - } - } - return 0; -} - -void displayio_bitmap_set_dirty_area(displayio_bitmap_t *self, const displayio_area_t *dirty_area) { - if (self->read_only) { - mp_raise_RuntimeError(MP_ERROR_TEXT("Read-only")); - } - - 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, NULL}; - displayio_area_compute_overlap(&area, &bitmap_area, &self->dirty_area); -} - -void displayio_bitmap_write_pixel(displayio_bitmap_t *self, int16_t x, int16_t y, uint32_t value) { - if (self->read_only) { - mp_raise_RuntimeError(MP_ERROR_TEXT("Read-only")); - } - // Writes the color index value into a pixel position - // Must update the dirty area separately - - // Don't write if out of area - if (0 > x || x >= self->width || 0 > y || y >= self->height) { - return; - } - - // Update one pixel of data - int32_t row_start = y * self->stride; - uint32_t *row = self->data + row_start; - uint8_t bytes_per_value = self->bits_per_value / 8; - uint8_t values_per_byte = 8 / self->bits_per_value; - if (bytes_per_value < 1) { - uint8_t bits = ((uint8_t *)row)[x >> self->x_shift]; - uint8_t bit_position = (values_per_byte - (x & self->x_mask) - 1) * self->bits_per_value; - bits &= ~(self->bitmask << bit_position); - bits |= (value & self->bitmask) << bit_position; - ((uint8_t *)row)[x >> self->x_shift] = bits; - } else { - if (bytes_per_value == 1) { - ((uint8_t *)row)[x] = value; - } else if (bytes_per_value == 2) { - ((uint16_t *)row)[x] = value; - } else if (bytes_per_value == 4) { - ((uint32_t *)row)[x] = value; - } - } -} - -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(MP_ERROR_TEXT("Read-only")); - } - // update the dirty region - displayio_area_t a = {x, y, x + 1, y + 1, NULL}; - 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 || self->read_only) { - return tail; - } - self->dirty_area.next = tail; - return &self->dirty_area; -} - -void displayio_bitmap_finish_refresh(displayio_bitmap_t *self) { - if (self->read_only) { - return; - } - self->dirty_area.x1 = 0; - self->dirty_area.x2 = 0; -} - -void common_hal_displayio_bitmap_fill(displayio_bitmap_t *self, uint32_t value) { - if (self->read_only) { - mp_raise_RuntimeError(MP_ERROR_TEXT("Read-only")); - } - displayio_area_t a = {0, 0, self->width, self->height, NULL}; - 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)); - } - // copy it in - 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(uint32_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 a4a57587207..7c7edfb7f2d 100644 --- a/shared-module/displayio/Bitmap.h +++ b/shared-module/displayio/Bitmap.h @@ -10,24 +10,13 @@ #include #include "py/obj.h" -#include "shared-module/displayio/area.h" -typedef struct { - mp_obj_base_t base; - uint16_t width; - uint16_t height; - uint32_t *data; - uint16_t stride; // uint32_t's - uint8_t bits_per_value; - uint8_t x_shift; - size_t x_mask; - displayio_area_t dirty_area; - uint16_t bitmask; - bool read_only; - bool data_alloc; // did bitmap allocate data or someone else -} displayio_bitmap_t; +// The pixel storage format (uint32_t word rows, MSB-first sub-byte values) and the +// higher-level dirty API are shared by both compositing backends; the dirty-tracking +// fields and scanline refresh API differ. See legacy/Bitmap.h and lvgl/Bitmap.h. -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); -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); +#if CIRCUITPY_DISPLAYIO_LVGL +#include "shared-module/displayio/lvgl/Bitmap.h" +#else +#include "shared-module/displayio/legacy/Bitmap.h" +#endif diff --git a/shared-module/displayio/ColorConverter.c b/shared-module/displayio/ColorConverter.c deleted file mode 100644 index cf5136f4e6b..00000000000 --- a/shared-module/displayio/ColorConverter.c +++ /dev/null @@ -1,356 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2018 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "shared-bindings/displayio/ColorConverter.h" - -#include "py/misc.h" -#include "py/runtime.h" - -#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_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, displayio_colorspace_t input_colorspace) { - self->dither = dither; - self->transparent_color = NO_TRANSPARENT_COLOR; - self->input_colorspace = input_colorspace; - self->output_colorspace.depth = 16; -} - -uint16_t displayio_colorconverter_compute_rgb565(uint32_t color_rgb888) { - uint32_t r5 = (color_rgb888 >> 19); - uint32_t g6 = (color_rgb888 >> 10) & 0x3f; - uint32_t b5 = (color_rgb888 >> 3) & 0x1f; - return r5 << 11 | g6 << 5 | b5; -} - -uint8_t displayio_colorconverter_compute_rgb332(uint32_t color_rgb888) { - uint32_t r3 = (color_rgb888 >> 21); - uint32_t g3 = (color_rgb888 >> 13) & 0x7; - uint32_t b2 = (color_rgb888 >> 6) & 0x3; - return r3 << 5 | g3 << 2 | b2; -} - -uint8_t displayio_colorconverter_compute_rgbd(uint32_t color_rgb888) { - uint32_t r1 = (color_rgb888 >> 23) & 0x1; - uint32_t g1 = (color_rgb888 >> 15) & 0x1; - uint32_t b1 = (color_rgb888 >> 7) & 0x1; - return r1 << 3 | g1 << 2 | b1 << 1 /* | dummy */; -} - -uint8_t displayio_colorconverter_compute_luma(uint32_t color_rgb888) { - uint32_t r8 = (color_rgb888 >> 16); - uint32_t g8 = (color_rgb888 >> 8) & 0xff; - uint32_t b8 = color_rgb888 & 0xff; - return (r8 * 19 + g8 * 182 + b8 * 54) / 255; -} - -uint8_t displayio_colorconverter_compute_chroma(uint32_t color_rgb888) { - uint32_t r8 = (color_rgb888 >> 16); - uint32_t g8 = (color_rgb888 >> 8) & 0xff; - uint32_t b8 = color_rgb888 & 0xff; - uint8_t max = MAX(r8, MAX(g8, b8)); - uint8_t min = MIN(r8, MIN(g8, b8)); - return max - min; -} - -uint8_t displayio_colorconverter_compute_hue(uint32_t color_rgb888) { - uint32_t r8 = (color_rgb888 >> 16); - uint32_t g8 = (color_rgb888 >> 8) & 0xff; - uint32_t b8 = color_rgb888 & 0xff; - uint8_t max = MAX(r8, MAX(g8, b8)); - uint8_t min = MIN(r8, MIN(g8, b8)); - uint8_t c = max - min; - if (c == 0) { - return 0; - } - - int32_t hue = 0; - if (max == r8) { - hue = (((int32_t)(g8 - b8) * 40) / c) % 240; - } else if (max == g8) { - hue = (((int32_t)(b8 - r8) + (2 * c)) * 40) / c; - } else if (max == b8) { - hue = (((int32_t)(r8 - g8) + (4 * c)) * 40) / c; - } - if (hue < 0) { - hue += 240; - } - - return hue; -} - -uint8_t displayio_colorconverter_compute_sevencolor(uint32_t color_rgb888) { - // This is DDX=1, the default for the displays. - uint8_t chroma = displayio_colorconverter_compute_chroma(color_rgb888); - if (chroma >= 64) { - uint8_t hue = displayio_colorconverter_compute_hue(color_rgb888); - // Red 0 - if (hue < 10) { - return 0x4; - } - // Orange 21 - if (hue < 21 + 10) { - return 0x6; - } - // Yellow 42 - if (hue < 42 + 21) { - return 0x5; - } - // Green 85 - if (hue < 85 + 42) { - return 0x2; - } - // Blue 170 - if (hue < 170 + 42) { - return 0x3; - } - - // The rest is red to 255 - return 0x4; - } else { - uint8_t luma = displayio_colorconverter_compute_luma(color_rgb888); - if (luma >= 128) { - return 0x1; // White - } else { - return 0x0; // Black - } - } -} - -void displayio_colorconverter_compute_tricolor(const _displayio_colorspace_t *colorspace, uint8_t pixel_hue, 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) { - if (colorspace->grayscale) { - *color = 0; - } else { - *color = 1; - } - } else if (!colorspace->grayscale) { - *color = 0; - } -} - -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; - - displayio_output_pixel_t output_pixel; - output_pixel.pixel = 0; - output_pixel.opaque = false; - - displayio_colorconverter_convert(self, colorspace, &input_pixel, &output_pixel); - - (*output_color) = output_pixel.pixel; -} - -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) { - return self->dither; -} - -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(MP_ERROR_TEXT("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; - // NO_TRANSPARENT_COLOR will never equal a valid color - self->transparent_color = NO_TRANSPARENT_COLOR; -} - - -// Convert a single input pixel to RGB888 -uint32_t displayio_colorconverter_convert_pixel(displayio_colorspace_t colorspace, uint32_t pixel) { - switch (colorspace) { - case DISPLAYIO_COLORSPACE_RGB565_SWAPPED: - pixel = __builtin_bswap16(pixel); - MP_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); - MP_FALLTHROUGH; - case DISPLAYIO_COLORSPACE_RGB555: { - uint32_t r8 = (pixel >> 10) & 0x1f; - uint32_t g8 = (pixel >> 5) & 0x1f; - uint32_t b8 = pixel & 0x1f; - r8 = (r8 << 3) | ((r8 >> 2) & 0b111); - g8 = (g8 << 3) | ((g8 >> 2) & 0b111); - b8 = (b8 << 3) | ((b8 >> 2) & 0b111); - pixel = (r8 << 16) | (g8 << 8) | b8; - } - break; - - case DISPLAYIO_COLORSPACE_BGR565_SWAPPED: - pixel = __builtin_bswap16(pixel); - MP_FALLTHROUGH; - case DISPLAYIO_COLORSPACE_BGR565: { - uint32_t b8 = (pixel >> 11) << 3; - uint32_t g8 = ((pixel >> 5) << 2) & 0xff; - uint32_t r8 = (pixel << 3) & 0xff; - pixel = (r8 << 16) | (g8 << 8) | b8; - } - break; - - case DISPLAYIO_COLORSPACE_BGR555_SWAPPED: - pixel = __builtin_bswap16(pixel); - MP_FALLTHROUGH; - case DISPLAYIO_COLORSPACE_BGR555: { - uint32_t b8 = (pixel >> 10) & 0x1f; - uint32_t g8 = (pixel >> 5) & 0x1f; - uint32_t r8 = pixel & 0x1f; - r8 = (r8 << 3) | ((r8 >> 2) & 0b111); - g8 = (g8 << 3) | ((g8 >> 2) & 0b111); - b8 = (b8 << 3) | ((b8 >> 2) & 0b111); - pixel = (r8 << 16) | (g8 << 8) | b8; - } - break; - - default: - case DISPLAYIO_COLORSPACE_RGB888: - break; - - case DISPLAYIO_COLORSPACE_L8: { - uint32_t l8 = pixel & 0xff; - pixel = l8 * 0x010101; - } - break; - } - - return pixel; -} - -void displayio_convert_color(const _displayio_colorspace_t *colorspace, bool dither, const displayio_input_pixel_t *input_pixel, displayio_output_pixel_t *output_color) { - uint32_t pixel = input_pixel->pixel; - if (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)); - - 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)); - } else { - int bitmask = 0xFF >> colorspace->depth; - b8 = MIN(255, b8 + (randb & bitmask)); - r8 = MIN(255, r8 + (randr & bitmask)); - g8 = MIN(255, g8 + (randg & bitmask)); - } - pixel = r8 << 16 | g8 << 8 | b8; - } - - if (colorspace->depth == 16) { - uint16_t packed = displayio_colorconverter_compute_rgb565(pixel); - if (colorspace->reverse_bytes_in_word) { - // swap bytes - packed = __builtin_bswap16(packed); - } - output_color->pixel = packed; - output_color->opaque = true; - return; - } else if (colorspace->tricolor) { - uint8_t luma = displayio_colorconverter_compute_luma(pixel); - output_color->pixel = luma >> (8 - colorspace->depth); - if (displayio_colorconverter_compute_chroma(pixel) <= 16) { - if (!colorspace->grayscale) { - output_color->pixel = 0; - } - output_color->opaque = true; - return; - } - uint8_t pixel_hue = displayio_colorconverter_compute_hue(pixel); - displayio_colorconverter_compute_tricolor(colorspace, pixel_hue, &output_color->pixel); - return; - } 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; - output_color->opaque = true; - return; - } else if (colorspace->depth == 32 || colorspace->depth == 24) { - output_color->pixel = pixel; - output_color->opaque = true; - return; - } else if (colorspace->depth == 8 && !colorspace->grayscale) { - uint8_t packed = displayio_colorconverter_compute_rgb332(pixel); - output_color->pixel = packed; - output_color->opaque = true; - return; - } else if (colorspace->depth == 4) { - uint8_t packed; - if (colorspace->sevencolor) { - packed = displayio_colorconverter_compute_sevencolor(pixel); - } else { - packed = displayio_colorconverter_compute_rgbd(pixel); - } - output_color->pixel = packed; - output_color->opaque = true; - return; - } - output_color->opaque = false; -} - -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) { - output_color->opaque = false; - return; - } - - if (!self->dither && self->cached_colorspace == colorspace && self->cached_input_pixel == input_pixel->pixel) { - output_color->pixel = self->cached_output_color; - return; - } - - displayio_input_pixel_t rgb888_pixel = *input_pixel; - rgb888_pixel.pixel = displayio_colorconverter_convert_pixel(self->input_colorspace, input_pixel->pixel); - displayio_convert_color(colorspace, self->dither, &rgb888_pixel, output_color); - - if (!self->dither) { - self->cached_colorspace = colorspace; - self->cached_input_pixel = input_pixel->pixel; - self->cached_output_color = output_color->pixel; - } -} - - - -// Currently no refresh logic is needed for a ColorConverter. -bool displayio_colorconverter_needs_refresh(displayio_colorconverter_t *self) { - return false; -} - -void displayio_colorconverter_finish_refresh(displayio_colorconverter_t *self) { -} diff --git a/shared-module/displayio/ColorConverter.h b/shared-module/displayio/ColorConverter.h index 60efc132f9a..8cab1f4b2b4 100644 --- a/shared-module/displayio/ColorConverter.h +++ b/shared-module/displayio/ColorConverter.h @@ -12,6 +12,9 @@ #include "py/obj.h" #include "shared-module/displayio/Palette.h" +// Stored in transparent_color when no color is transparent. It is outside the 24 bit color range. +#define NO_TRANSPARENT_COLOR (0x1000000) + typedef struct displayio_colorconverter { mp_obj_base_t base; bool dither; @@ -41,5 +44,7 @@ uint8_t displayio_colorconverter_compute_rgbd(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); +uint8_t displayio_colorconverter_compute_sixcolor(uint32_t color_rgb888); uint8_t displayio_colorconverter_compute_sevencolor(uint32_t color_rgb888); -void displayio_colorconverter_compute_tricolor(const _displayio_colorspace_t *colorspace, uint8_t pixel_hue, uint32_t *color); +void displayio_colorconverter_compute_tricolor(const _displayio_colorspace_t *colorspace, uint8_t pixel_chroma, uint8_t pixel_hue, uint32_t *color); +void displayio_colorconverter_compute_fourcolor(const _displayio_colorspace_t *colorspace, uint8_t pixel_chroma, uint8_t pixel_hue, uint32_t *color); diff --git a/shared-module/displayio/Group.c b/shared-module/displayio/Group.c deleted file mode 100644 index e2a1a527062..00000000000 --- a/shared-module/displayio/Group.c +++ /dev/null @@ -1,466 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2018 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "shared-bindings/displayio/Group.h" - -#include "py/runtime.h" -#include "py/objlist.h" -#include "shared-bindings/displayio/TileGrid.h" - -#if CIRCUITPY_VECTORIO -#include "shared-bindings/vectorio/VectorShape.h" -#endif - -static void check_readonly(displayio_group_t *self) { - if (self->readonly) { - mp_raise_RuntimeError(MP_ERROR_TEXT("Read-only")); - } -} - -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) { - return self->hidden; -} - -void common_hal_displayio_group_set_hidden(displayio_group_t *self, bool hidden) { - if (self->hidden == hidden) { - return; - } - check_readonly(self); - self->hidden = hidden; - if (self->hidden_by_parent) { - return; - } - for (size_t i = 0; i < self->members->len; i++) { - mp_obj_t layer; - layer = mp_obj_cast_to_native_base( - self->members->items[i], &displayio_tilegrid_type); - if (layer != MP_OBJ_NULL) { - displayio_tilegrid_set_hidden_by_parent(layer, hidden); - continue; - } - layer = mp_obj_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; - } - #if CIRCUITPY_VECTORIO - const vectorio_draw_protocol_t *draw_protocol = mp_proto_get(MP_QSTR_protocol_draw, self->members->items[i]); - if (draw_protocol != NULL) { - layer = draw_protocol->draw_get_protocol_self(self->members->items[i]); - draw_protocol->draw_protocol_impl->draw_set_dirty(layer); - continue; - } - #endif - } -} - -void displayio_group_set_hidden_by_parent(displayio_group_t *self, bool hidden) { - if (self->hidden_by_parent == hidden) { - return; - } - check_readonly(self); - self->hidden_by_parent = hidden; - // If we're already hidden, then we're done. - if (self->hidden) { - return; - } - for (size_t i = 0; i < self->members->len; i++) { - mp_obj_t layer; - layer = mp_obj_cast_to_native_base( - self->members->items[i], &displayio_tilegrid_type); - if (layer != MP_OBJ_NULL) { - displayio_tilegrid_set_hidden_by_parent(layer, hidden); - continue; - } - layer = mp_obj_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; - } - #if CIRCUITPY_VECTORIO - const vectorio_draw_protocol_t *draw_protocol = mp_proto_get(MP_QSTR_protocol_draw, self->members->items[i]); - if (draw_protocol != NULL) { - layer = draw_protocol->draw_get_protocol_self(self->members->items[i]); - draw_protocol->draw_protocol_impl->draw_set_dirty(layer); - continue; - } - #endif - } -} - -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 first = true; - for (size_t i = 0; i < self->members->len; i++) { - mp_obj_t layer; - displayio_area_t layer_area; - layer = mp_obj_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 { - layer = mp_obj_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_union(area, &layer_area, area); - } - } - if (self->item_removed) { - if (first) { - displayio_area_copy(&self->dirty_area, area); - first = false; - } else { - displayio_area_union(area, &self->dirty_area, area); - } - } - return !first; -} - -static void _update_child_transforms(displayio_group_t *self) { - if (!self->in_group) { - return; - } - for (size_t i = 0; i < self->members->len; i++) { - mp_obj_t layer; - #if CIRCUITPY_VECTORIO - const vectorio_draw_protocol_t *draw_protocol = mp_proto_get(MP_QSTR_protocol_draw, self->members->items[i]); - if (draw_protocol != NULL) { - layer = draw_protocol->draw_get_protocol_self(self->members->items[i]); - draw_protocol->draw_protocol_impl->draw_update_transform(layer, &self->absolute_transform); - continue; - } - #endif - layer = mp_obj_cast_to_native_base( - self->members->items[i], &displayio_tilegrid_type); - if (layer != MP_OBJ_NULL) { - displayio_tilegrid_update_transform(layer, &self->absolute_transform); - continue; - } - layer = mp_obj_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) { - self->in_group = parent_transform != NULL; - if (self->in_group) { - int16_t x = self->x; - int16_t y = self->y; - if (parent_transform->transpose_xy) { - x = y; - y = self->x; - } - self->absolute_transform.x = parent_transform->x + parent_transform->dx * x; - self->absolute_transform.y = parent_transform->y + parent_transform->dy * y; - self->absolute_transform.dx = parent_transform->dx * self->scale; - self->absolute_transform.dy = parent_transform->dy * self->scale; - self->absolute_transform.transpose_xy = parent_transform->transpose_xy; - self->absolute_transform.mirror_x = parent_transform->mirror_x; - self->absolute_transform.mirror_y = parent_transform->mirror_y; - - self->absolute_transform.scale = parent_transform->scale * self->scale; - } - _update_child_transforms(self); -} - -void common_hal_displayio_group_set_scale(displayio_group_t *self, uint32_t scale) { - if (self->scale == scale) { - return; - } - check_readonly(self); - uint8_t parent_scale = self->absolute_transform.scale / self->scale; - self->absolute_transform.dx = self->absolute_transform.dx / self->scale * scale; - self->absolute_transform.dy = self->absolute_transform.dy / self->scale * scale; - self->absolute_transform.scale = parent_scale * scale; - self->scale = scale; - _update_child_transforms(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) { - if (self->x == x) { - return; - } - check_readonly(self); - if (self->absolute_transform.transpose_xy) { - int16_t dy = self->absolute_transform.dy / self->scale; - self->absolute_transform.y += dy * (x - self->x); - } else { - int16_t dx = self->absolute_transform.dx / self->scale; - self->absolute_transform.x += dx * (x - self->x); - } - - self->x = x; - _update_child_transforms(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) { - if (self->y == y) { - return; - } - check_readonly(self); - if (self->absolute_transform.transpose_xy) { - int8_t dx = self->absolute_transform.dx / self->scale; - self->absolute_transform.x += dx * (y - self->y); - } else { - int8_t dy = self->absolute_transform.dy / self->scale; - self->absolute_transform.y += dy * (y - self->y); - } - self->y = y; - _update_child_transforms(self); -} - -static void _add_layer(displayio_group_t *self, mp_obj_t layer) { - check_readonly(self); - #if CIRCUITPY_VECTORIO - const vectorio_draw_protocol_t *draw_protocol = mp_proto_get(MP_QSTR_protocol_draw, layer); - if (draw_protocol != NULL) { - draw_protocol->draw_protocol_impl->draw_update_transform(draw_protocol->draw_get_protocol_self(layer), &self->absolute_transform); - return; - } - #endif - mp_obj_t native_layer = mp_obj_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(MP_ERROR_TEXT("Layer already in a group")); - } else { - tilegrid->in_group = true; - } - displayio_tilegrid_update_transform(tilegrid, &self->absolute_transform); - displayio_tilegrid_set_hidden_by_parent( - tilegrid, self->hidden || self->hidden_by_parent); - return; - } - native_layer = mp_obj_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(MP_ERROR_TEXT("Layer already in a group")); - } else { - group->in_group = true; - } - displayio_group_update_transform(group, &self->absolute_transform); - displayio_group_set_hidden_by_parent( - group, self->hidden || self->hidden_by_parent); - return; - } - mp_raise_ValueError(MP_ERROR_TEXT("Layer must be a Group or TileGrid subclass")); -} - -static void _remove_layer(displayio_group_t *self, size_t index) { - check_readonly(self); - mp_obj_t layer; - displayio_area_t layer_area; - bool rendered_last_frame = false; - #if CIRCUITPY_VECTORIO - const vectorio_draw_protocol_t *draw_protocol = mp_proto_get(MP_QSTR_protocol_draw, self->members->items[index]); - if (draw_protocol != NULL) { - layer = draw_protocol->draw_get_protocol_self(self->members->items[index]); - bool has_dirty_area = draw_protocol->draw_protocol_impl->draw_get_dirty_area(layer, &layer_area); - rendered_last_frame = has_dirty_area; - draw_protocol->draw_protocol_impl->draw_update_transform(layer, NULL); - } - #endif - layer = mp_obj_cast_to_native_base( - self->members->items[index], &displayio_tilegrid_type); - if (layer != MP_OBJ_NULL) { - displayio_tilegrid_t *tilegrid = layer; - tilegrid->in_group = false; - rendered_last_frame = displayio_tilegrid_get_previous_area(tilegrid, &layer_area); - displayio_tilegrid_update_transform(tilegrid, NULL); - } - layer = mp_obj_cast_to_native_base( - self->members->items[index], &displayio_group_type); - if (layer != MP_OBJ_NULL) { - displayio_group_t *group = layer; - group->in_group = false; - rendered_last_frame = displayio_group_get_previous_area(group, &layer_area); - displayio_group_update_transform(group, NULL); - } - if (!rendered_last_frame) { - return; - } - if (!self->item_removed) { - displayio_area_copy(&layer_area, &self->dirty_area); - } else { - 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) { - _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) { - _remove_layer(self, index); - return mp_obj_list_pop(self->members, index); -} - -mp_int_t common_hal_displayio_group_index(displayio_group_t *self, mp_obj_t layer) { - mp_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->members->len; -} - -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) { - _add_layer(self, layer); - _remove_layer(self, index); - mp_obj_list_store(self->members, MP_OBJ_NEW_SMALL_INT(index), layer); -} - -void displayio_group_construct(displayio_group_t *self, mp_obj_list_t *members, uint32_t scale, mp_int_t x, mp_int_t y) { - self->x = x; - self->y = y; - self->members = members; - self->item_removed = false; - self->scale = scale; - self->in_group = false; - self->readonly = 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) { - // Track if any of the layers finishes filling in the given area. We can ignore any remaining - // layers at that point. - if (self->hidden == false) { - for (int32_t i = self->members->len - 1; i >= 0; i--) { - mp_obj_t layer; - #if CIRCUITPY_VECTORIO - const vectorio_draw_protocol_t *draw_protocol = mp_proto_get(MP_QSTR_protocol_draw, self->members->items[i]); - if (draw_protocol != NULL) { - layer = draw_protocol->draw_get_protocol_self(self->members->items[i]); - if (draw_protocol->draw_protocol_impl->draw_fill_area(layer, colorspace, area, mask, buffer)) { - return true; - } - continue; - } - #endif - layer = mp_obj_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)) { - return true; - } - continue; - } - layer = mp_obj_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)) { - return true; - } - continue; - } - } - } - return false; -} - -void displayio_group_finish_refresh(displayio_group_t *self) { - self->item_removed = false; - for (int32_t i = self->members->len - 1; i >= 0; i--) { - mp_obj_t layer; - #if CIRCUITPY_VECTORIO - const vectorio_draw_protocol_t *draw_protocol = mp_proto_get(MP_QSTR_protocol_draw, self->members->items[i]); - if (draw_protocol != NULL) { - layer = draw_protocol->draw_get_protocol_self(self->members->items[i]); - draw_protocol->draw_protocol_impl->draw_finish_refresh(layer); - continue; - } - #endif - layer = mp_obj_cast_to_native_base( - self->members->items[i], &displayio_tilegrid_type); - if (layer != MP_OBJ_NULL) { - displayio_tilegrid_finish_refresh(layer); - continue; - } - layer = mp_obj_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) { - if (self->item_removed) { - self->dirty_area.next = tail; - tail = &self->dirty_area; - } - - for (int32_t i = self->members->len - 1; i >= 0; i--) { - mp_obj_t layer; - #if CIRCUITPY_VECTORIO - const vectorio_draw_protocol_t *draw_protocol = mp_proto_get(MP_QSTR_protocol_draw, self->members->items[i]); - if (draw_protocol != NULL) { - layer = draw_protocol->draw_get_protocol_self(self->members->items[i]); - tail = draw_protocol->draw_protocol_impl->draw_get_refresh_areas(layer, tail); - continue; - } - #endif - layer = mp_obj_cast_to_native_base( - self->members->items[i], &displayio_tilegrid_type); - if (layer != MP_OBJ_NULL) { - if (!displayio_tilegrid_get_rendered_hidden(layer)) { - tail = displayio_tilegrid_get_refresh_areas(layer, tail); - } - continue; - } - layer = mp_obj_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; - } - } - - return tail; -} diff --git a/shared-module/displayio/Group.h b/shared-module/displayio/Group.h index 9ff6c7dca0f..fbff3ddd028 100644 --- a/shared-module/displayio/Group.h +++ b/shared-module/displayio/Group.h @@ -11,29 +11,24 @@ #include "py/obj.h" #include "py/objlist.h" -#include "shared-module/displayio/area.h" #include "shared-module/displayio/Palette.h" -typedef struct { - mp_obj_base_t base; - 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; - bool item_removed : 1; - bool in_group : 1; - bool hidden : 1; - bool hidden_by_parent : 1; - bool readonly : 1; - uint8_t padding : 3; -} displayio_group_t; - -void displayio_group_construct(displayio_group_t *self, mp_obj_list_t *members, uint32_t scale, mp_int_t x, mp_int_t y); -void displayio_group_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); -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); +// The compositing core (Group and TileGrid) has two implementations, selected at build +// time with CIRCUITPY_DISPLAYIO_LVGL: +// +// legacy/ — the original scanline compositing core used by display_core.c and every +// BusDisplay/EPaperDisplay/FramebufferDisplay variant. +// lvgl/ — an implementation that mirrors Groups and TileGrids into an LVGL object tree +// which is rendered by LVGL. Groups are plain lv_obj containers. A TileGrid is a +// single lv_image (single-tile sprites) or an lv_obj container with one lv_image per +// tile. Images share the source bitmap's pixel data directly when the source format +// matches the display format; otherwise a custom LVGL image decoder converts tiles. +#if CIRCUITPY_DISPLAYIO_LVGL +#include "shared-module/displayio/lvgl/Group.h" +// The protocol slot an LVGL-backed Group exposes to its parent Group. Legacy Groups are found +// by type, so the slot stays empty there. See displayio/lvgl/lvgl_protocol.h. +#define DISPLAYIO_GROUP_LVGL_PROTOCOL &displayio_lvgl_group_protocol +#else +#include "shared-module/displayio/legacy/Group.h" +#define DISPLAYIO_GROUP_LVGL_PROTOCOL NULL +#endif diff --git a/shared-module/displayio/OnDiskBitmap.c b/shared-module/displayio/OnDiskBitmap.c deleted file mode 100644 index 9411f08e372..00000000000 --- a/shared-module/displayio/OnDiskBitmap.c +++ /dev/null @@ -1,224 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2018 Scott Shawcroft for Adafruit Industries -// SPDX-FileCopyrightText: Copyright (c) 2025 SamantazFox -// -// SPDX-License-Identifier: MIT - -#include "shared-bindings/displayio/OnDiskBitmap.h" -#include "shared-bindings/displayio/ColorConverter.h" -#include "shared-bindings/displayio/Palette.h" -#include "shared-module/displayio/ColorConverter.h" -#include "shared-module/displayio/Palette.h" - -#include - -#include "py/mperrno.h" -#include "py/runtime.h" - - -#define DISPLAYIO_ODBMP_DEBUG(...) (void)0 -// #define DISPLAYIO_ODBMP_DEBUG(...) mp_printf(&mp_plat_print __VA_OPT__(,) __VA_ARGS__) - - -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) { - // Load the wave - self->file = file; - uint16_t bmp_header[69]; - f_rewind(&self->file->fp); - UINT bytes_read; - - // Read the minimum amount of bytes required to parse a BITMAPCOREHEADER. - // If needed, we will read more bytes down below. - if (f_read(&self->file->fp, bmp_header, 26, &bytes_read) != FR_OK) { - mp_raise_OSError(MP_EIO); - } - DISPLAYIO_ODBMP_DEBUG("bytes_read: %d\n", bytes_read); - if (bytes_read != 26 || memcmp(bmp_header, "BM", 2) != 0) { - mp_arg_error_invalid(MP_QSTR_file); - } - - // Read header size to determine if more header bytes needs to be read. - uint32_t header_size = read_word(bmp_header, 7); - DISPLAYIO_ODBMP_DEBUG("header_size: %d\n", header_size); - - if (header_size == 40 || header_size == 108 || header_size == 124) { - // Read the remaining header bytes - if (f_read(&self->file->fp, bmp_header + 13, header_size - 12, &bytes_read) != FR_OK) { - mp_raise_OSError(MP_EIO); - } - DISPLAYIO_ODBMP_DEBUG("bytes_read: %d\n", bytes_read); - if (bytes_read != (header_size - 12)) { - mp_arg_error_invalid(MP_QSTR_file); - } - } else if (header_size != 12) { - mp_raise_ValueError_varg(MP_ERROR_TEXT("Only Windows format, uncompressed BMP supported: given header size is %d"), header_size); - } - - - uint32_t compression = read_word(bmp_header, 15); - DISPLAYIO_ODBMP_DEBUG("compression: %d\n", compression); - - // 0 is uncompressed; 3 is bitfield compressed. 1 and 2 are RLE compression. - if (compression != 0 && compression != 3) { - mp_raise_ValueError(MP_ERROR_TEXT("RLE-compressed BMP not supported")); - } - - // We can't cast because we're not aligned. - self->data_offset = read_word(bmp_header, 5); - - self->bitfield_compressed = (compression == 3); - self->bits_per_pixel = bmp_header[14]; - self->width = read_word(bmp_header, 9); - self->height = read_word(bmp_header, 11); - - DISPLAYIO_ODBMP_DEBUG("data offset: %d\n", self->data_offset); - DISPLAYIO_ODBMP_DEBUG("width: %d\n", self->width); - DISPLAYIO_ODBMP_DEBUG("height: %d\n", self->height); - DISPLAYIO_ODBMP_DEBUG("bpp: %d\n", self->bits_per_pixel); - - - displayio_colorconverter_t *colorconverter = - mp_obj_malloc(displayio_colorconverter_t, &displayio_colorconverter_type); - common_hal_displayio_colorconverter_construct(colorconverter, false, DISPLAYIO_COLORSPACE_RGB888); - self->colorconverter = colorconverter; - - if (self->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); - self->b_bitmask = read_word(bmp_header, 31); - - } else { // no compression or short header means 5:5:5 - self->r_bitmask = 0x7c00; - self->g_bitmask = 0x3e0; - self->b_bitmask = 0x1f; - } - } else if (self->bits_per_pixel <= 8) { // indexed - uint32_t number_of_colors = 0; - if (header_size >= 40) { - number_of_colors = read_word(bmp_header, 23); - } - if (number_of_colors == 0) { - number_of_colors = 1 << self->bits_per_pixel; - } - - displayio_palette_t *palette = mp_obj_malloc(displayio_palette_t, &displayio_palette_type); - common_hal_displayio_palette_construct(palette, number_of_colors, false); - - if (number_of_colors > 1) { - uint16_t palette_size = number_of_colors * sizeof(uint32_t); - uint16_t palette_offset = 0xe + header_size; - - uint32_t *palette_data = m_malloc(palette_size); - - f_rewind(&self->file->fp); - f_lseek(&self->file->fp, palette_offset); - - UINT palette_bytes_read; - if (f_read(&self->file->fp, palette_data, palette_size, &palette_bytes_read) != FR_OK) { - mp_raise_OSError(MP_EIO); - } - if (palette_bytes_read != palette_size) { - mp_raise_ValueError(MP_ERROR_TEXT("Unable to read color palette data")); - } - for (uint16_t i = 0; i < number_of_colors; i++) { - common_hal_displayio_palette_set_color(palette, i, palette_data[i]); - } - - #if MICROPY_MALLOC_USES_ALLOCATED_SIZE - m_free(palette_data, palette_size); - #else - m_free(palette_data); - #endif - } else { - common_hal_displayio_palette_set_color(palette, 0, 0x0); - common_hal_displayio_palette_set_color(palette, 1, 0xffffff); - } - self->palette = palette; - } - - 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) { - self->stride = (self->width * bytes_per_pixel); - // Rows are word aligned. - if (self->stride % 4 != 0) { - self->stride += 4 - self->stride % 4; - } - } else { - uint32_t bit_stride = self->width * self->bits_per_pixel; - if (bit_stride % 32 != 0) { - bit_stride += 32 - bit_stride % 32; - } - self->stride = (bit_stride / 8); - } - -} - - -uint32_t common_hal_displayio_ondiskbitmap_get_pixel(displayio_ondiskbitmap_t *self, - 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 pixels_per_byte = 8 / self->bits_per_pixel; - 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; - } - // We don't cache here because the underlying FS caches sectors. - f_lseek(&self->file->fp, location); - UINT bytes_read; - uint32_t pixel_data = 0; - uint32_t result = f_read(&self->file->fp, &pixel_data, bytes_per_pixel, &bytes_read); - if (result == FR_OK) { - uint32_t tmp = 0; - uint8_t red; - uint8_t green; - uint8_t blue; - if (bytes_per_pixel == 1) { - uint8_t offset = (x % pixels_per_byte) * self->bits_per_pixel; - uint8_t mask = (1 << self->bits_per_pixel) - 1; - - return (pixel_data >> ((8 - self->bits_per_pixel) - offset)) & mask; - } 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); - blue = ((pixel_data & self->b_bitmask) >> 0); - } else { // 555 - 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); - return tmp; - } else if ((bytes_per_pixel == 4) && (self->bitfield_compressed)) { - return pixel_data & 0x00FFFFFF; - } else { - return pixel_data; - } - } - return 0; -} - -uint16_t common_hal_displayio_ondiskbitmap_get_height(displayio_ondiskbitmap_t *self) { - return self->height; -} - -uint16_t common_hal_displayio_ondiskbitmap_get_width(displayio_ondiskbitmap_t *self) { - return self->width; -} - -mp_obj_t common_hal_displayio_ondiskbitmap_get_pixel_shader(displayio_ondiskbitmap_t *self) { - return MP_OBJ_FROM_PTR(self->pixel_shader_base); -} diff --git a/shared-module/displayio/OnDiskBitmap.h b/shared-module/displayio/OnDiskBitmap.h index 6fe5b880cd6..96b39efa7f1 100644 --- a/shared-module/displayio/OnDiskBitmap.h +++ b/shared-module/displayio/OnDiskBitmap.h @@ -6,28 +6,10 @@ #pragma once -#include -#include - -#include "py/obj.h" - -#include "extmod/vfs_fat.h" - -typedef struct { - mp_obj_base_t base; - uint16_t width; - uint16_t height; - uint16_t data_offset; - uint16_t stride; - uint32_t r_bitmask; - uint32_t g_bitmask; - uint32_t b_bitmask; - pyb_file_obj_t *file; - union { - mp_obj_base_t *pixel_shader_base; - struct displayio_palette *palette; - struct displayio_colorconverter *colorconverter; - }; - bool bitfield_compressed; - uint8_t bits_per_pixel; -} displayio_ondiskbitmap_t; +// The BMP parser and pixel access have separate legacy and LVGL implementations. The LVGL +// version also keeps decoder state for streaming pixels from the file. +#if CIRCUITPY_DISPLAYIO_LVGL +#include "shared-module/displayio/lvgl/OnDiskBitmap.h" +#else +#include "shared-module/displayio/legacy/OnDiskBitmap.h" +#endif diff --git a/shared-module/displayio/Palette.c b/shared-module/displayio/Palette.c deleted file mode 100644 index d80f1c47da1..00000000000 --- a/shared-module/displayio/Palette.c +++ /dev/null @@ -1,92 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2018 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "shared-bindings/displayio/Palette.h" - -#include "shared-module/displayio/ColorConverter.h" - -void common_hal_displayio_palette_construct(displayio_palette_t *self, uint16_t color_count, bool dither) { - self->color_count = color_count; - self->colors = (_displayio_color_t *)m_malloc(color_count * sizeof(_displayio_color_t)); - self->dither = dither; -} - -void common_hal_displayio_palette_set_dither(displayio_palette_t *self, bool dither) { - self->dither = dither; -} - -bool common_hal_displayio_palette_get_dither(displayio_palette_t *self) { - return self->dither; -} - -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) { - self->colors[palette_index].transparent = true; - self->needs_refresh = true; -} - -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) { - if (self->colors[palette_index].rgb888 == color) { - return; - } - self->colors[palette_index].rgb888 = color; - self->colors[palette_index].cached_colorspace = NULL; - self->needs_refresh = true; -} - -uint32_t common_hal_displayio_palette_get_color(displayio_palette_t *self, uint32_t palette_index) { - return self->colors[palette_index].rgb888; -} - -void displayio_palette_get_color(displayio_palette_t *self, const _displayio_colorspace_t *colorspace, const displayio_input_pixel_t *input_pixel, displayio_output_pixel_t *output_color) { - uint32_t palette_index = input_pixel->pixel; - if (palette_index > self->color_count || self->colors[palette_index].transparent) { - output_color->opaque = false; - return; - } - - // Cache results when not dithering. - _displayio_color_t *color = &self->colors[palette_index]; - // Check the grayscale settings because EPaperDisplay will change them on - // the same object. - if (!self->dither && - color->cached_colorspace == colorspace && - color->cached_colorspace_grayscale_bit == colorspace->grayscale_bit && - color->cached_colorspace_grayscale == colorspace->grayscale) { - output_color->pixel = self->colors[palette_index].cached_color; - return; - } - - displayio_input_pixel_t rgb888_pixel = *input_pixel; - rgb888_pixel.pixel = self->colors[palette_index].rgb888; - displayio_convert_color(colorspace, self->dither, &rgb888_pixel, output_color); - if (!self->dither) { - color->cached_colorspace = colorspace; - color->cached_color = output_color->pixel; - color->cached_colorspace_grayscale = colorspace->grayscale; - color->cached_colorspace_grayscale_bit = colorspace->grayscale_bit; - } -} - -bool displayio_palette_needs_refresh(displayio_palette_t *self) { - return self->needs_refresh; -} - -void displayio_palette_finish_refresh(displayio_palette_t *self) { - self->needs_refresh = false; -} diff --git a/shared-module/displayio/Palette.h b/shared-module/displayio/Palette.h index 092b934b66a..086c377f302 100644 --- a/shared-module/displayio/Palette.h +++ b/shared-module/displayio/Palette.h @@ -15,10 +15,12 @@ typedef struct { uint8_t depth; uint8_t bytes_per_cell; uint8_t tricolor_hue; - uint8_t tricolor_luma; + uint8_t fourcolor_hue; uint8_t grayscale_bit; // The lowest grayscale bit. Normally 8 - depth. bool grayscale; bool tricolor; + bool fourcolor; + bool sixcolor; // Spectra6 e-ink screens. bool sevencolor; // Acep e-ink screens. bool pixels_in_byte_share_row; bool reverse_pixels_in_byte; @@ -58,7 +60,8 @@ typedef struct displayio_palette { } displayio_palette_t; +#if !CIRCUITPY_DISPLAYIO_LVGL void displayio_palette_get_color(displayio_palette_t *palette, const _displayio_colorspace_t *colorspace, const displayio_input_pixel_t *input_pixel, displayio_output_pixel_t *output_color); -; +#endif 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 deleted file mode 100644 index f36e9e32ac1..00000000000 --- a/shared-module/displayio/Shape.c +++ /dev/null @@ -1,126 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2019 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "shared-bindings/displayio/Shape.h" - -#include - -#include "py/runtime.h" -#include "py/misc.h" - -void common_hal_displayio_shape_construct(displayio_shape_t *self, uint32_t width, - uint32_t height, bool mirror_x, bool mirror_y) { - self->mirror_x = mirror_x; - self->mirror_y = mirror_y; - self->width = width; - if (self->mirror_x) { - width /= 2; - width += self->width % 2; - } - self->half_width = width; - - self->height = height; - if (self->mirror_y) { - height /= 2; - height += self->height % 2; - } - self->half_height = height; - - self->data = m_malloc(height * sizeof(uint32_t)); - - for (uint16_t i = 0; i < height; i++) { - self->data[2 * i] = 0; - 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; -} - -void common_hal_displayio_shape_set_boundary(displayio_shape_t *self, uint16_t y, uint16_t start_x, uint16_t end_x) { - uint16_t max_y = self->height - 1; - if (self->mirror_y) { - max_y = self->half_height - 1; - } - mp_arg_validate_int_range(y, 0, max_y, MP_QSTR_y); - uint16_t max_x = self->width - 1; - if (self->mirror_x) { - max_x = self->half_width - 1; - } - mp_arg_validate_int_range(start_x, 0, max_x, MP_QSTR_start_x); - mp_arg_validate_int_range(end_x, 0, max_x, MP_QSTR_end_x); - - uint16_t lower_x, upper_x, lower_y, upper_y; - - // find x-boundaries for updating based on current data and start_x, end_x, and mirror_x - lower_x = MIN(start_x, self->data[2 * y]); - - if (self->mirror_x) { - upper_x = self->width - lower_x + 1; // dirty rectangles are treated with max value exclusive - } else { - upper_x = MAX(end_x, self->data[2 * y + 1]) + 1; // dirty rectangles are treated with max value exclusive - } - - // find y-boundaries based on y and mirror_y - lower_y = y; - - if (self->mirror_y) { - upper_y = self->height - lower_y + 1; // dirty rectangles are treated with max value exclusive - } else { - upper_y = y + 1; // dirty rectangles are treated with max value exclusive - } - - self->data[2 * y] = start_x; // update the data array with the new boundaries - self->data[2 * y + 1] = end_x; - - if (self->dirty_area.x1 == self->dirty_area.x2) { // Dirty region is empty - self->dirty_area.x1 = lower_x; - self->dirty_area.x2 = upper_x; - self->dirty_area.y1 = lower_y; - self->dirty_area.y2 = upper_y; - - } else { // Dirty region is not empty - self->dirty_area.x1 = MIN(lower_x, self->dirty_area.x1); - self->dirty_area.x2 = MAX(upper_x, self->dirty_area.x2); - - self->dirty_area.y1 = MIN(lower_y, self->dirty_area.y1); - self->dirty_area.y2 = MAX(upper_y, self->dirty_area.y2); - } -} - -uint32_t common_hal_displayio_shape_get_pixel(void *obj, int16_t x, int16_t y) { - displayio_shape_t *self = obj; - if (x >= self->width || x < 0 || y >= self->height || y < 0) { - return 0; - } - if (self->mirror_x && x >= self->half_width) { - x = self->width - x - 1; - } - if (self->mirror_y && y >= self->half_height) { - y = self->height - y - 1; - } - uint16_t start_x = self->data[2 * y]; - uint16_t end_x = self->data[2 * y + 1]; - if (x < start_x || x > end_x) { - return 0; - } - return 1; -} - -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; - } - self->dirty_area.next = tail; - return &self->dirty_area; -} - -void displayio_shape_finish_refresh(displayio_shape_t *self) { - self->dirty_area.x1 = 0; - self->dirty_area.x2 = 0; -} diff --git a/shared-module/displayio/Shape.h b/shared-module/displayio/Shape.h deleted file mode 100644 index 20ee182023f..00000000000 --- a/shared-module/displayio/Shape.h +++ /dev/null @@ -1,28 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2019 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#pragma once - -#include -#include - -#include "py/obj.h" -#include "shared-module/displayio/area.h" - -typedef struct { - mp_obj_base_t base; - uint16_t width; - uint16_t height; - uint16_t half_width; - uint16_t half_height; - 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); diff --git a/shared-module/displayio/TileGrid.c b/shared-module/displayio/TileGrid.c deleted file mode 100644 index e0d18d0accf..00000000000 --- a/shared-module/displayio/TileGrid.c +++ /dev/null @@ -1,678 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2018 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "shared-bindings/displayio/TileGrid.h" - -#include "py/runtime.h" -#include "shared-bindings/displayio/Bitmap.h" -#include "shared-bindings/displayio/ColorConverter.h" -#include "shared-bindings/displayio/OnDiskBitmap.h" -#include "shared-bindings/displayio/Palette.h" -#if CIRCUITPY_TILEPALETTEMAPPER -#include "shared-bindings/tilepalettemapper/TilePaletteMapper.h" -#endif - -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) { - 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 *); - 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; - } - self->inline_tiles = true; - } else { - self->tiles = (uint8_t *)m_malloc(total_tiles); - for (uint32_t i = 0; i < total_tiles; i++) { - self->tiles[i] = default_tile; - } - self->inline_tiles = false; - } - self->bitmap_width_in_tiles = bitmap_width_in_tiles; - self->tiles_in_bitmap = bitmap_width_in_tiles * bitmap_height_in_tiles; - self->width_in_tiles = width; - self->height_in_tiles = height; - self->x = x; - self->y = y; - self->pixel_width = width * tile_width; - self->pixel_height = height * tile_height; - self->tile_width = tile_width; - self->tile_height = tile_height; - self->bitmap = bitmap; - self->pixel_shader = pixel_shader; - self->in_group = false; - self->hidden = false; - self->hidden_by_parent = false; - self->previous_area.x1 = 0xffff; - self->previous_area.x2 = self->previous_area.x1; - 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) { - return self->hidden; -} - -bool displayio_tilegrid_get_rendered_hidden(displayio_tilegrid_t *self) { - return self->rendered_hidden; -} - -void common_hal_displayio_tilegrid_set_hidden(displayio_tilegrid_t *self, bool hidden) { - self->hidden = hidden; - self->rendered_hidden = false; - if (!hidden) { - self->full_change = true; - } -} - -void displayio_tilegrid_set_hidden_by_parent(displayio_tilegrid_t *self, bool hidden) { - self->hidden_by_parent = hidden; - self->rendered_hidden = false; - if (!hidden) { - self->full_change = true; - } -} - -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; - } - displayio_area_copy(&self->previous_area, area); - return true; -} - -static void _update_current_x(displayio_tilegrid_t *self) { - uint16_t width; - if (self->transpose_xy) { - width = self->pixel_height; - } else { - width = self->pixel_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 = 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; - self->current_area.x1 = temp; - } - } -} - -static void _update_current_y(displayio_tilegrid_t *self) { - uint16_t height; - if (self->transpose_xy) { - height = self->pixel_width; - } else { - height = self->pixel_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 = 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; - self->current_area.y1 = temp; - } - } -} - -void displayio_tilegrid_update_transform(displayio_tilegrid_t *self, - const displayio_buffer_transform_t *absolute_transform) { - self->in_group = absolute_transform != NULL; - self->absolute_transform = absolute_transform; - if (absolute_transform != NULL) { - self->moved = true; - - _update_current_x(self); - _update_current_y(self); - } -} - -mp_int_t common_hal_displayio_tilegrid_get_x(displayio_tilegrid_t *self) { - return self->x; -} -void common_hal_displayio_tilegrid_set_x(displayio_tilegrid_t *self, mp_int_t x) { - if (self->x == x) { - return; - } - - self->moved = true; - - self->x = x; - if (self->absolute_transform != NULL) { - _update_current_x(self); - } -} -mp_int_t common_hal_displayio_tilegrid_get_y(displayio_tilegrid_t *self) { - return self->y; -} - -void common_hal_displayio_tilegrid_set_y(displayio_tilegrid_t *self, mp_int_t y) { - if (self->y == y) { - return; - } - self->moved = true; - self->y = y; - if (self->absolute_transform != NULL) { - _update_current_y(self); - } -} - -mp_obj_t common_hal_displayio_tilegrid_get_pixel_shader(displayio_tilegrid_t *self) { - return self->pixel_shader; -} - -void common_hal_displayio_tilegrid_set_pixel_shader(displayio_tilegrid_t *self, mp_obj_t pixel_shader) { - self->pixel_shader = pixel_shader; - self->full_change = true; -} - -mp_obj_t common_hal_displayio_tilegrid_get_bitmap(displayio_tilegrid_t *self) { - return self->bitmap; -} - -void common_hal_displayio_tilegrid_set_bitmap(displayio_tilegrid_t *self, mp_obj_t bitmap) { - self->bitmap = bitmap; - self->full_change = true; -} - -uint16_t common_hal_displayio_tilegrid_get_width(displayio_tilegrid_t *self) { - return self->width_in_tiles; -} - -uint16_t common_hal_displayio_tilegrid_get_height(displayio_tilegrid_t *self) { - return self->height_in_tiles; -} - -uint16_t common_hal_displayio_tilegrid_get_tile_width(displayio_tilegrid_t *self) { - return self->tile_width; -} - -uint16_t common_hal_displayio_tilegrid_get_tile_height(displayio_tilegrid_t *self) { - return self->tile_height; -} - -uint8_t common_hal_displayio_tilegrid_get_tile(displayio_tilegrid_t *self, uint16_t x, uint16_t y) { - uint8_t *tiles = self->tiles; - if (self->inline_tiles) { - tiles = (uint8_t *)&self->tiles; - } - if (tiles == NULL) { - return 0; - } - return tiles[y * self->width_in_tiles + x]; -} - -void common_hal_displayio_tilegrid_set_tile(displayio_tilegrid_t *self, uint16_t x, uint16_t y, uint8_t tile_index) { - if (tile_index >= self->tiles_in_bitmap) { - mp_raise_ValueError(MP_ERROR_TEXT("Tile index out of bounds")); - } - uint8_t *tiles = self->tiles; - if (self->inline_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; - if (!self->partial_change) { - tile_area = &self->dirty_area; - } else { - tile_area = &temp_area; - } - int16_t tx = (x - self->top_left_x) % self->width_in_tiles; - if (tx < 0) { - tx += self->width_in_tiles; - } - tile_area->x1 = tx * self->tile_width; - tile_area->x2 = tile_area->x1 + self->tile_width; - int16_t ty = (y - self->top_left_y) % self->height_in_tiles; - if (ty < 0) { - ty += self->height_in_tiles; - } - tile_area->y1 = ty * self->tile_height; - tile_area->y2 = tile_area->y1 + self->tile_height; - - if (self->partial_change) { - displayio_area_union(&self->dirty_area, &temp_area, &self->dirty_area); - } - - self->partial_change = true; -} - -void common_hal_displayio_tilegrid_set_all_tiles(displayio_tilegrid_t *self, uint8_t tile_index) { - if (tile_index >= self->tiles_in_bitmap) { - mp_raise_ValueError(MP_ERROR_TEXT("Tile index out of bounds")); - } - uint8_t *tiles = self->tiles; - if (self->inline_tiles) { - tiles = (uint8_t *)&self->tiles; - } - if (tiles == NULL) { - return; - } - - for (uint16_t x = 0; x < self->width_in_tiles; x++) { - for (uint16_t y = 0; y < self->height_in_tiles; y++) { - tiles[y * self->width_in_tiles + x] = tile_index; - } - } - - self->full_change = true; -} - -bool common_hal_displayio_tilegrid_get_flip_x(displayio_tilegrid_t *self) { - return self->flip_x; -} - -void common_hal_displayio_tilegrid_set_flip_x(displayio_tilegrid_t *self, bool flip_x) { - if (self->flip_x == flip_x) { - return; - } - self->flip_x = flip_x; - self->full_change = true; -} - -bool common_hal_displayio_tilegrid_get_flip_y(displayio_tilegrid_t *self) { - return self->flip_y; -} - -void common_hal_displayio_tilegrid_set_flip_y(displayio_tilegrid_t *self, bool flip_y) { - if (self->flip_y == flip_y) { - return; - } - self->flip_y = flip_y; - self->full_change = true; -} - -bool common_hal_displayio_tilegrid_get_transpose_xy(displayio_tilegrid_t *self) { - return self->transpose_xy; -} - -void common_hal_displayio_tilegrid_set_transpose_xy(displayio_tilegrid_t *self, bool transpose_xy) { - if (self->transpose_xy == transpose_xy) { - return; - } - self->transpose_xy = transpose_xy; - - // Square TileGrids do not change dimensions when transposed. - if (self->pixel_width == self->pixel_height) { - self->full_change = true; - return; - } - - _update_current_x(self); - _update_current_y(self); - - self->moved = true; -} - -bool common_hal_displayio_tilegrid_contains(displayio_tilegrid_t *self, uint16_t x, uint16_t y) { - uint16_t right_edge = self->x + (self->width_in_tiles * self->tile_width); - uint16_t bottom_edge = self->y + (self->height_in_tiles * self->tile_height); - return x >= self->x && x < right_edge && - y >= self->y && y < bottom_edge; -} - -void common_hal_displayio_tilegrid_set_top_left(displayio_tilegrid_t *self, uint16_t x, uint16_t y) { - self->top_left_x = x; - self->top_left_y = y; - 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) { - // If no tiles are present we have no impact. - uint8_t *tiles = self->tiles; - if (self->inline_tiles) { - tiles = (uint8_t *)&self->tiles; - } - if (tiles == NULL) { - return false; - } - - bool hidden = self->hidden || self->hidden_by_parent; - if (hidden) { - return false; - } - - displayio_area_t overlap; - if (!displayio_area_compute_overlap(area, &self->current_area, &overlap)) { - return false; - } - - int16_t x_stride = 1; - int16_t y_stride = displayio_area_width(area); - - bool flip_x = self->flip_x; - bool flip_y = self->flip_y; - if (self->transpose_xy != self->absolute_transform->transpose_xy) { - bool temp_flip = flip_x; - flip_x = flip_y; - flip_y = temp_flip; - } - - // How many pixels are outside of our area between us and the start of the row. - uint16_t start = 0; - if ((self->absolute_transform->dx < 0) != flip_x) { - start += (area->x2 - area->x1 - 1) * x_stride; - x_stride *= -1; - } - if ((self->absolute_transform->dy < 0) != flip_y) { - start += (area->y2 - area->y1 - 1) * y_stride; - y_stride *= -1; - } - - // Track if this layer finishes filling in the given area. We can ignore any remaining - // layers at that point. - bool full_coverage = displayio_area_equal(area, &overlap); - - // TODO(tannewt): Skip coverage tracking if all pixels outside the overlap have already been - // set and our palette is all opaque. - - // TODO(tannewt): Check to see if the pixel_shader has any transparency. If it doesn't then we - // 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); - - int16_t start_x = (transformed.x1 - self->current_area.x1); - int16_t end_x = (transformed.x2 - self->current_area.x1); - int16_t start_y = (transformed.y1 - self->current_area.y1); - int16_t end_y = (transformed.y2 - self->current_area.y1); - - int16_t y_shift = 0; - int16_t x_shift = 0; - if ((self->absolute_transform->dx < 0) != flip_x) { - x_shift = area->x2 - overlap.x2; - } else { - x_shift = overlap.x1 - area->x1; - } - if ((self->absolute_transform->dy < 0) != flip_y) { - y_shift = area->y2 - overlap.y2; - } else { - y_shift = overlap.y1 - area->y1; - } - - // This untransposes x and y so it aligns with bitmap rows. - if (self->transpose_xy != self->absolute_transform->transpose_xy) { - int16_t temp_stride = x_stride; - x_stride = y_stride; - y_stride = temp_stride; - int16_t temp_shift = x_shift; - x_shift = y_shift; - y_shift = temp_shift; - } - - displayio_input_pixel_t input_pixel; - displayio_output_pixel_t output_pixel; - - for (input_pixel.y = start_y; input_pixel.y < end_y; ++input_pixel.y) { - int16_t row_start = start + (input_pixel.y - start_y + y_shift) * y_stride; // in pixels - int16_t local_y = input_pixel.y / self->absolute_transform->scale; - for (input_pixel.x = start_x; input_pixel.x < end_x; ++input_pixel.x) { - // Compute the destination pixel in the buffer and mask based on the transformations. - int16_t offset = row_start + (input_pixel.x - start_x + x_shift) * x_stride; // in pixels - - // This is super useful for debugging out of range accesses. Uncomment to use. - // if (offset < 0 || offset >= (int32_t) displayio_area_size(area)) { - // asm("bkpt"); - // } - - // Check the mask first to see if the pixel has already been set. - if ((mask[offset / 32] & (1 << (offset % 32))) != 0) { - continue; - } - int16_t local_x = input_pixel.x / self->absolute_transform->scale; - uint16_t x_tile_index = (local_x / self->tile_width + self->top_left_x) % self->width_in_tiles; - uint16_t y_tile_index = (local_y / self->tile_height + self->top_left_y) % self->height_in_tiles; - uint16_t tile_location = y_tile_index * self->width_in_tiles + x_tile_index; - input_pixel.tile = tiles[tile_location]; - 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; - - output_pixel.pixel = 0; - input_pixel.pixel = 0; - - // We always want to read bitmap pixels by row first and then transpose into the destination - // buffer because most bitmaps are row associated. - if (mp_obj_is_type(self->bitmap, &displayio_bitmap_type)) { - input_pixel.pixel = common_hal_displayio_bitmap_get_pixel(self->bitmap, input_pixel.tile_x, input_pixel.tile_y); - } else if (mp_obj_is_type(self->bitmap, &displayio_ondiskbitmap_type)) { - input_pixel.pixel = common_hal_displayio_ondiskbitmap_get_pixel(self->bitmap, input_pixel.tile_x, input_pixel.tile_y); - } - - output_pixel.opaque = true; - #if CIRCUITPY_TILEPALETTEMAPPER - if (mp_obj_is_type(self->pixel_shader, &tilepalettemapper_tilepalettemapper_type)) { - tilepalettemapper_tilepalettemapper_get_color(self->pixel_shader, colorspace, &input_pixel, &output_pixel, x_tile_index, y_tile_index); - } - #endif - if (self->pixel_shader == mp_const_none) { - output_pixel.pixel = input_pixel.pixel; - } else if (mp_obj_is_type(self->pixel_shader, &displayio_palette_type)) { - displayio_palette_get_color(self->pixel_shader, colorspace, &input_pixel, &output_pixel); - } else if (mp_obj_is_type(self->pixel_shader, &displayio_colorconverter_type)) { - displayio_colorconverter_convert(self->pixel_shader, colorspace, &input_pixel, &output_pixel); - } - if (!output_pixel.opaque) { - // A pixel is transparent so we haven't fully covered the area ourselves. - full_coverage = false; - } else { - mask[offset / 32] |= 1 << (offset % 32); - if (colorspace->depth == 16) { - *(((uint16_t *)buffer) + offset) = output_pixel.pixel; - } else if (colorspace->depth == 32) { - *(((uint32_t *)buffer) + offset) = output_pixel.pixel; - } else if (colorspace->depth == 24) { - memcpy(((uint8_t *)buffer) + offset * 3, &output_pixel.pixel, 3); - } else if (colorspace->depth == 8) { - *(((uint8_t *)buffer) + offset) = output_pixel.pixel; - } else if (colorspace->depth < 8) { - uint8_t pixels_per_byte = 8 / colorspace->depth; - - // Reorder the offsets to pack multiple rows into a byte (meaning they share a column). - if (!colorspace->pixels_in_byte_share_row) { - uint16_t width = displayio_area_width(area); - uint16_t row = offset / width; - uint16_t col = offset % width; - // Dividing by pixels_per_byte does truncated division even if we multiply it back out. - offset = col * pixels_per_byte + (row / pixels_per_byte) * pixels_per_byte * width + row % pixels_per_byte; - // Also useful for validating that the bitpacking worked correctly. - // if (offset > displayio_area_size(area)) { - // asm("bkpt"); - // } - } - uint8_t shift = (offset % pixels_per_byte) * colorspace->depth; - if (colorspace->reverse_pixels_in_byte) { - // 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; - } - } - } - } - return full_coverage; -} - -void displayio_tilegrid_finish_refresh(displayio_tilegrid_t *self) { - bool first_draw = self->previous_area.x1 == self->previous_area.x2; - bool hidden = self->hidden || self->hidden_by_parent; - if (!first_draw && hidden) { - self->previous_area.x2 = self->previous_area.x1; - } else if (self->moved || first_draw) { - displayio_area_copy(&self->current_area, &self->previous_area); - } - - self->moved = false; - self->full_change = false; - self->partial_change = false; - if (mp_obj_is_type(self->pixel_shader, &displayio_palette_type)) { - displayio_palette_finish_refresh(self->pixel_shader); - } else if (mp_obj_is_type(self->pixel_shader, &displayio_colorconverter_type)) { - displayio_colorconverter_finish_refresh(self->pixel_shader); - } - #if CIRCUITPY_TILEPALETTEMAPPER - if (mp_obj_is_type(self->pixel_shader, &tilepalettemapper_tilepalettemapper_type)) { - tilepalettemapper_tilepalettemapper_finish_refresh(self->pixel_shader); - } - #endif - if (mp_obj_is_type(self->bitmap, &displayio_bitmap_type)) { - displayio_bitmap_finish_refresh(self->bitmap); - } else if (mp_obj_is_type(self->bitmap, &displayio_ondiskbitmap_type)) { - // OnDiskBitmap changes will trigger a complete reload so no need to - // track changes. - } - // TODO(tannewt): We could double buffer changes to position and move them over here. - // 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) { - 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. - if (hidden) { - self->rendered_hidden = true; - if (!first_draw) { - self->previous_area.next = tail; - return &self->previous_area; - } else { - return tail; - } - } else if (self->moved && !first_draw) { - displayio_area_union(&self->previous_area, &self->current_area, &self->dirty_area); - if (displayio_area_size(&self->dirty_area) <= 2U * self->pixel_width * self->pixel_height) { - self->dirty_area.next = tail; - return &self->dirty_area; - } - self->previous_area.next = tail; - self->current_area.next = &self->previous_area; - return &self->current_area; - } - - // 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); - 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. - if (self->tiles_in_bitmap == 1) { - displayio_area_copy(refresh_area, &self->dirty_area); - self->partial_change = true; - } else { - self->full_change = true; - } - } - } - - self->full_change = self->full_change || - (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)); - #if CIRCUITPY_TILEPALETTEMAPPER - self->full_change = self->full_change || - (mp_obj_is_type(self->pixel_shader, &tilepalettemapper_tilepalettemapper_type) && - tilepalettemapper_tilepalettemapper_needs_refresh(self->pixel_shader)); - #endif - - if (self->full_change || first_draw) { - self->current_area.next = tail; - return &self->current_area; - } - - if (self->partial_change) { - int16_t x = self->x; - int16_t y = self->y; - if (self->absolute_transform->transpose_xy) { - int16_t temp = y; - y = x; - x = temp; - } - int16_t x1 = self->dirty_area.x1; - int16_t x2 = self->dirty_area.x2; - if (self->flip_x) { - x1 = self->pixel_width - x1; - x2 = self->pixel_width - x2; - } - int16_t y1 = self->dirty_area.y1; - int16_t y2 = self->dirty_area.y2; - if (self->flip_y) { - y1 = self->pixel_height - y1; - y2 = self->pixel_height - y2; - } - if (self->transpose_xy != self->absolute_transform->transpose_xy) { - int16_t temp1 = y1, temp2 = y2; - y1 = x1; - x1 = temp1; - y2 = x2; - x2 = temp2; - } - self->dirty_area.x1 = self->absolute_transform->x + self->absolute_transform->dx * (x + x1); - self->dirty_area.y1 = self->absolute_transform->y + self->absolute_transform->dy * (y + y1); - self->dirty_area.x2 = self->absolute_transform->x + self->absolute_transform->dx * (x + x2); - self->dirty_area.y2 = self->absolute_transform->y + self->absolute_transform->dy * (y + y2); - if (self->dirty_area.y2 < self->dirty_area.y1) { - int16_t temp = self->dirty_area.y2; - self->dirty_area.y2 = self->dirty_area.y1; - self->dirty_area.y1 = temp; - } - if (self->dirty_area.x2 < self->dirty_area.x1) { - int16_t temp = self->dirty_area.x2; - self->dirty_area.x2 = self->dirty_area.x1; - self->dirty_area.x1 = temp; - } - - self->dirty_area.next = tail; - return &self->dirty_area; - } - return tail; -} diff --git a/shared-module/displayio/TileGrid.h b/shared-module/displayio/TileGrid.h index 36d2c9a69b6..413bd3ef352 100644 --- a/shared-module/displayio/TileGrid.h +++ b/shared-module/displayio/TileGrid.h @@ -10,61 +10,15 @@ #include #include "py/obj.h" -#include "shared-module/displayio/area.h" #include "shared-module/displayio/Palette.h" -typedef struct { - mp_obj_base_t base; - mp_obj_t bitmap; - mp_obj_t pixel_shader; - int16_t x; - int16_t y; - uint16_t pixel_width; - uint16_t pixel_height; - uint16_t bitmap_width_in_tiles; - ; - uint16_t tiles_in_bitmap; - uint16_t width_in_tiles; - uint16_t height_in_tiles; - uint16_t tile_width; - uint16_t tile_height; - uint16_t top_left_x; - uint16_t top_left_y; - 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; - bool rendered_hidden : 1; - uint8_t padding : 6; -} displayio_tilegrid_t; - -void displayio_tilegrid_set_hidden_by_parent(displayio_tilegrid_t *self, bool hidden); - -// 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); - -// 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); - -// 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); -void displayio_tilegrid_finish_refresh(displayio_tilegrid_t *self); - -bool displayio_tilegrid_get_rendered_hidden(displayio_tilegrid_t *self); -void displayio_tilegrid_validate_pixel_shader(mp_obj_t pixel_shader); +// See Group.h for the compositing core backend selection. +#if CIRCUITPY_DISPLAYIO_LVGL +#include "shared-module/displayio/lvgl/TileGrid.h" +// The protocol slot an LVGL-backed TileGrid exposes to its Group. Legacy TileGrids are found +// by type, so the slot stays empty there. See displayio/lvgl/lvgl_protocol.h. +#define DISPLAYIO_TILEGRID_LVGL_PROTOCOL &displayio_lvgl_tilegrid_protocol +#else +#include "shared-module/displayio/legacy/TileGrid.h" +#define DISPLAYIO_TILEGRID_LVGL_PROTOCOL NULL +#endif diff --git a/shared-module/displayio/__init__.c b/shared-module/displayio/__init__.c deleted file mode 100644 index 4b467b75589..00000000000 --- a/shared-module/displayio/__init__.c +++ /dev/null @@ -1,494 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2018 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include - -#include "shared-module/displayio/__init__.h" -#include "shared-bindings/displayio/__init__.h" - -#include "shared/runtime/interrupt_char.h" -#include "py/runtime.h" -#include "shared-bindings/board/__init__.h" -#include "shared-bindings/busio/I2C.h" -#include "shared-bindings/displayio/Bitmap.h" -#include "shared-bindings/displayio/Group.h" -#include "shared-bindings/displayio/Palette.h" -#include "shared-module/displayio/area.h" -#include "supervisor/shared/display.h" -#include "supervisor/shared/reload.h" - -#include "py/mpconfig.h" - -#if CIRCUITPY_BUSDISPLAY -#include "shared-bindings/busdisplay/BusDisplay.h" -#endif - -#if CIRCUITPY_DOTCLOCKFRAMEBUFFER -#include "shared-bindings/dotclockframebuffer/DotClockFramebuffer.h" -#endif - -#if CIRCUITPY_SHARPDISPLAY -#include "shared-bindings/sharpdisplay/SharpMemoryFramebuffer.h" -#include "shared-module/sharpdisplay/SharpMemoryFramebuffer.h" -#endif - -#if CIRCUITPY_AURORA_EPAPER -#include "shared-bindings/aurora_epaper/aurora_framebuffer.h" -#include "shared-module/aurora_epaper/aurora_framebuffer.h" -#endif - -#ifdef BOARD_USE_INTERNAL_SPI -#include "supervisor/spi_flash_api.h" -#endif - -// The default indicates no primary display -static int primary_display_number = -1; - -primary_display_bus_t display_buses[CIRCUITPY_DISPLAY_LIMIT]; -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 || CIRCUITPY_IS31FL3741 || CIRCUITPY_VIDEOCORE || CIRCUITPY_PICODVI -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; - if (display->framebuffer == obj) { - return true; - } - } - } - return false; -} -#endif - - -void displayio_background(void) { - if (mp_hal_is_interrupted()) { - return; - } - if (autoreload_ready()) { - // Reload is about to happen, so don't redisplay. - return; - } - - for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) { - mp_const_obj_t display_type = displays[i].display_base.type; - if (display_type == NULL || display_type == &mp_type_NoneType) { - // Skip null display. - continue; - } - if (false) { - #if CIRCUITPY_BUSDISPLAY - } else if (display_type == &busdisplay_busdisplay_type) { - busdisplay_busdisplay_background(&displays[i].display); - #endif - #if CIRCUITPY_FRAMEBUFFERIO - } else if (display_type == &framebufferio_framebufferdisplay_type) { - framebufferio_framebufferdisplay_background(&displays[i].framebuffer_display); - #endif - #if CIRCUITPY_EPAPERDISPLAY - } else if (display_type == &epaperdisplay_epaperdisplay_type) { - epaperdisplay_epaperdisplay_background(&displays[i].epaper_display); - #endif - } - } - -} - -static void common_hal_displayio_release_displays_impl(bool keep_primary) { - // Release displays before busses so that they can send any final commands to turn the display - // off properly. - if (!keep_primary) { - primary_display_number = -1; - } - for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) { - if (i == primary_display_number) { - continue; - } - mp_const_obj_t display_type = displays[i].display_base.type; - if (display_type == NULL || display_type == &mp_type_NoneType) { - continue; - #if CIRCUITPY_BUSDISPLAY - } else if (display_type == &busdisplay_busdisplay_type) { - release_busdisplay(&displays[i].display); - #endif - #if CIRCUITPY_EPAPERDISPLAY - } else if (display_type == &epaperdisplay_epaperdisplay_type) { - release_epaperdisplay(&displays[i].epaper_display); - #endif - #if CIRCUITPY_FRAMEBUFFERIO - } else if (display_type == &framebufferio_framebufferdisplay_type) { - release_framebufferdisplay(&displays[i].framebuffer_display); - #endif - } - displays[i].display_base.type = &mp_type_NoneType; - } - for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) { - mp_const_obj_t bus_type = display_buses[i].bus_base.type; - if (bus_type == NULL || bus_type == &mp_type_NoneType) { - continue; - #if CIRCUITPY_FOURWIRE - } else if (bus_type == &fourwire_fourwire_type) { - common_hal_fourwire_fourwire_deinit(&display_buses[i].fourwire_bus); - #endif - #if CIRCUITPY_I2CDISPLAYBUS - } else if (bus_type == &i2cdisplaybus_i2cdisplaybus_type) { - common_hal_i2cdisplaybus_i2cdisplaybus_deinit(&display_buses[i].i2cdisplay_bus); - #endif - #if CIRCUITPY_DOTCLOCKFRAMEBUFFER - } else if (bus_type == &dotclockframebuffer_framebuffer_type) { - common_hal_dotclockframebuffer_framebuffer_deinit(&display_buses[i].dotclock); - #endif - #if CIRCUITPY_PARALLELDISPLAYBUS - } else if (bus_type == ¶lleldisplaybus_parallelbus_type) { - common_hal_paralleldisplaybus_parallelbus_deinit(&display_buses[i].parallel_bus); - #endif - #if CIRCUITPY_RGBMATRIX - } else if (bus_type == &rgbmatrix_RGBMatrix_type) { - common_hal_rgbmatrix_rgbmatrix_deinit(&display_buses[i].rgbmatrix); - #endif - #if CIRCUITPY_IS31FL3741 - } else if (bus_type == &is31fl3741_framebuffer_type) { - common_hal_is31fl3741_framebuffer_deinit(&display_buses[i].is31fl3741); - #endif - #if CIRCUITPY_SHARPDISPLAY - } else if (bus_type == &sharpdisplay_framebuffer_type) { - common_hal_sharpdisplay_framebuffer_deinit(&display_buses[i].sharpdisplay); - #endif - #if CIRCUITPY_VIDEOCORE - } else if (bus_type == &videocore_framebuffer_type) { - common_hal_videocore_framebuffer_deinit(&display_buses[i].videocore); - #endif - #if CIRCUITPY_PICODVI - } else if (bus_type == &picodvi_framebuffer_type) { - common_hal_picodvi_framebuffer_deinit(&display_buses[i].picodvi); - #endif - } - display_buses[i].bus_base.type = &mp_type_NoneType; - } - - supervisor_stop_terminal(); -} - -void common_hal_displayio_release_displays(void) { - common_hal_displayio_release_displays_impl(false); -} - -void reset_displays(void) { - // In CircuitPython 10, release secondary displays before doing anything else: - // common_hal_displayio_release_displays_impl(true); - - // 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++) { - mp_const_obj_t display_bus_type = display_buses[i].bus_base.type; - if (display_bus_type == NULL || display_bus_type == &mp_type_NoneType) { - continue; - #if CIRCUITPY_FOURWIRE - } else if (display_bus_type == &fourwire_fourwire_type) { - fourwire_fourwire_obj_t *fourwire = &display_buses[i].fourwire_bus; - if (((size_t)fourwire->bus) < ((size_t)&display_buses) || - ((size_t)fourwire->bus) > ((size_t)&display_buses + CIRCUITPY_DISPLAY_LIMIT * sizeof(primary_display_bus_t))) { - busio_spi_obj_t *original_spi = fourwire->bus; - #if CIRCUITPY_BOARD_SPI - // We don't need to move original_spi if it is a board.SPI object because it is - // statically allocated already. (Doing so would also make it impossible to reference in - // a subsequent VM run.) - if (common_hal_board_is_spi(original_spi)) { - continue; - } - #endif - #ifdef BOARD_USE_INTERNAL_SPI - 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 display buses that use the same spi bus and swap them too. - for (uint8_t j = i + 1; j < CIRCUITPY_DISPLAY_LIMIT; j++) { - if (display_buses[j].fourwire_bus.base.type == &fourwire_fourwire_type && - display_buses[j].fourwire_bus.bus == original_spi) { - display_buses[j].fourwire_bus.bus = &fourwire->inline_bus; - } - } - } - #endif - #if CIRCUITPY_I2CDISPLAYBUS - } else if (display_bus_type == &i2cdisplaybus_i2cdisplaybus_type) { - i2cdisplaybus_i2cdisplaybus_obj_t *i2c = &display_buses[i].i2cdisplay_bus; - // Check to see if we need to inline the I2C bus. - if (((size_t)i2c->bus) < ((size_t)&display_buses) || - ((size_t)i2c->bus) > ((size_t)&display_buses + CIRCUITPY_DISPLAY_LIMIT * sizeof(primary_display_bus_t))) { - busio_i2c_obj_t *original_i2c = i2c->bus; - #if CIRCUITPY_BOARD_I2C - // We don't need to move original_i2c if it is a board.I2C object because it is - // statically allocated already. (Doing so would also make it impossible to reference in - // a subsequent VM run.) - if (common_hal_board_is_i2c(original_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 (display_buses[j].i2cdisplay_bus.base.type == &i2cdisplaybus_i2cdisplaybus_type && - display_buses[j].i2cdisplay_bus.bus == original_i2c) { - display_buses[j].i2cdisplay_bus.bus = &i2c->inline_bus; - } - } - // Mark the old i2c object so it is considered deinit. - common_hal_busio_i2c_mark_deinit(original_i2c); - } - #endif - #if CIRCUITPY_RGBMATRIX - } else if (display_bus_type == &rgbmatrix_RGBMatrix_type) { - rgbmatrix_rgbmatrix_obj_t *pm = &display_buses[i].rgbmatrix; - if (!any_display_uses_this_framebuffer(&pm->base)) { - common_hal_rgbmatrix_rgbmatrix_deinit(pm); - } else { - common_hal_rgbmatrix_rgbmatrix_set_paused(pm, true); - } - #endif - #if CIRCUITPY_IS31FL3741 - } else if (display_bus_type == &is31fl3741_framebuffer_type) { - is31fl3741_framebuffer_obj_t *is31fb = &display_buses[i].is31fl3741; - - if (((uint32_t)is31fb->is31fl3741->i2c) < ((uint32_t)&display_buses) || - ((uint32_t)is31fb->is31fl3741->i2c) > ((uint32_t)&display_buses + CIRCUITPY_DISPLAY_LIMIT)) { - #if CIRCUITPY_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 (common_hal_board_is_i2c(is31fb->is31fl3741->i2c)) { - continue; - } - #endif - - is31fl3741_IS31FL3741_obj_t *original_is31 = is31fb->is31fl3741; - memcpy(&is31fb->inline_is31fl3741, original_is31, sizeof(is31fl3741_IS31FL3741_obj_t)); - is31fb->is31fl3741 = &is31fb->inline_is31fl3741; - - busio_i2c_obj_t *original_i2c = is31fb->is31fl3741->i2c; - memcpy(&is31fb->is31fl3741->inline_i2c, original_i2c, sizeof(busio_i2c_obj_t)); - is31fb->is31fl3741->i2c = &is31fb->is31fl3741->inline_i2c; - } - - if (!any_display_uses_this_framebuffer(&is31fb->base)) { - common_hal_is31fl3741_framebuffer_deinit(is31fb); - } else { - common_hal_is31fl3741_framebuffer_set_paused(is31fb, true); - } - #endif - #if CIRCUITPY_SHARPDISPLAY - } else if (display_bus_type == &sharpdisplay_framebuffer_type) { - sharpdisplay_framebuffer_obj_t *sharp = &display_buses[i].sharpdisplay; - common_hal_sharpdisplay_framebuffer_reset(sharp); - #endif - #if CIRCUITPY_VIDEOCORE - } else if (display_bus_type == &videocore_framebuffer_type) { - videocore_framebuffer_obj_t *vc = &display_buses[i].videocore; - if (!any_display_uses_this_framebuffer(&vc->base)) { - common_hal_videocore_framebuffer_deinit(vc); - } - // The framebuffer is allocated outside of the heap so it doesn't - // need to be moved. - #endif - #if CIRCUITPY_PICODVI - } else if (display_bus_type == &picodvi_framebuffer_type) { - picodvi_framebuffer_obj_t *vc = &display_buses[i].picodvi; - if (!any_display_uses_this_framebuffer(&vc->base)) { - common_hal_picodvi_framebuffer_deinit(vc); - } - #endif - #if CIRCUITPY_AURORA_EPAPER - } else if (display_bus_type == &aurora_framebuffer_type) { - #if CIRCUITPY_BOARD_SPI - aurora_epaper_framebuffer_obj_t *aurora = &display_buses[i].aurora_epaper; - if (common_hal_board_is_spi(aurora->bus)) { - common_hal_aurora_epaper_framebuffer_set_free_bus(false); - } - #endif - // Set to None, gets deinit'd up by display_base - display_buses[i].bus_base.type = &mp_type_NoneType; - #endif - } else { - // Not an active display bus. - continue; - } - } - - for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) { - // Reset the displayed group. Only the first will get the terminal but - // that's ok. - mp_const_obj_t display_type = displays[i].display_base.type; - if (display_type == NULL || display_type == &mp_type_NoneType) { - continue; - #if CIRCUITPY_BUSDISPLAY - } else if (display_type == &busdisplay_busdisplay_type) { - reset_busdisplay(&displays[i].display); - #endif - #if CIRCUITPY_EPAPERDISPLAY - } else if (display_type == &epaperdisplay_epaperdisplay_type) { - epaperdisplay_epaperdisplay_obj_t *display = &displays[i].epaper_display; - epaperdisplay_epaperdisplay_reset(display); - #endif - #if CIRCUITPY_FRAMEBUFFERIO - } else if (display_type == &framebufferio_framebufferdisplay_type) { - framebufferio_framebufferdisplay_reset(&displays[i].framebuffer_display); - #endif - } - } -} - -void displayio_gc_collect(void) { - for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) { - mp_const_obj_t display_bus_type = display_buses[i].bus_base.type; - if (display_bus_type == NULL || display_bus_type == &mp_type_NoneType) { - continue; - } - #if CIRCUITPY_RGBMATRIX - if (display_bus_type == &rgbmatrix_RGBMatrix_type) { - rgbmatrix_rgbmatrix_collect_ptrs(&display_buses[i].rgbmatrix); - } - #endif - #if CIRCUITPY_IS31FL3741 - if (display_bus_type == &is31fl3741_framebuffer_type) { - is31fl3741_framebuffer_collect_ptrs(&display_buses[i].is31fl3741); - } - #endif - #if CIRCUITPY_SHARPDISPLAY - if (display_bus_type == &sharpdisplay_framebuffer_type) { - common_hal_sharpdisplay_framebuffer_collect_ptrs(&display_buses[i].sharpdisplay); - } - #endif - #if CIRCUITPY_AURORA_EPAPER - if (display_bus_type == &aurora_framebuffer_type) { - common_hal_aurora_epaper_framebuffer_collect_ptrs(&display_buses[i].aurora_epaper); - } - #endif - } - - for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) { - mp_const_obj_t display_type = displays[i].display_base.type; - if (display_type == NULL || display_type == &mp_type_NoneType) { - continue; - - // Alternatively, we could use gc_collect_root over the whole object, - // but this is more precise, and is the only field that needs marking. - #if CIRCUITPY_BUSDISPLAY - } else if (display_type == &busdisplay_busdisplay_type) { - busdisplay_busdisplay_collect_ptrs(&displays[i].display); - #endif - #if CIRCUITPY_FRAMEBUFFERIO - } else if (display_type == &framebufferio_framebufferdisplay_type) { - framebufferio_framebufferdisplay_collect_ptrs(&displays[i].framebuffer_display); - #endif - #if CIRCUITPY_EPAPERDISPLAY - } else if (display_type == &epaperdisplay_epaperdisplay_type) { - epaperdisplay_epaperdisplay_collect_ptrs(&displays[i].epaper_display); - #endif - } - } -} - -static bool is_display_active(mp_obj_base_t *display_maybe) { - return display_maybe->type != &mp_type_NoneType && display_maybe->type != NULL; -} - -primary_display_t *allocate_display(void) { - for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) { - if (!is_display_active(&displays[i].display_base)) { - // Clear this memory so it is in a known state before init. - memset(&displays[i], 0, sizeof(displays[i])); - // Default to None so that it works as board.DISPLAY. - displays[i].display_base.type = &mp_type_NoneType; - return &displays[i]; - } - } - return NULL; -} - -primary_display_t *allocate_display_or_raise(void) { - primary_display_t *result = allocate_display(); - if (result) { - return result; - } - mp_raise_RuntimeError(MP_ERROR_TEXT("Too many displays")); -} - -primary_display_bus_t *allocate_display_bus(void) { - for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) { - mp_const_obj_t display_bus_type = display_buses[i].bus_base.type; - if (display_bus_type == NULL || display_bus_type == &mp_type_NoneType) { - // Clear this memory so it is in a known state before init. - memset(&display_buses[i], 0, sizeof(display_buses[i])); - display_buses[i].bus_base.type = &mp_type_NoneType; - return &display_buses[i]; - } - } - return NULL; -} - -primary_display_bus_t *allocate_display_bus_or_raise(void) { - primary_display_bus_t *result = allocate_display_bus(); - if (result) { - return result; - } - mp_raise_RuntimeError(MP_ERROR_TEXT("Too many display busses; forgot displayio.release_displays() ?")); -} - -mp_obj_t common_hal_displayio_get_primary_display(void) { - if (primary_display_number == -1 || primary_display_number >= CIRCUITPY_DISPLAY_LIMIT) { - return mp_const_none; - } - mp_obj_base_t *primary_display = &displays[primary_display_number].display_base; - if (is_display_active(primary_display)) { - return MP_OBJ_FROM_PTR(primary_display); - } - return mp_const_none; -} - -void common_hal_displayio_set_primary_display(mp_obj_t new_primary_display) { - if (new_primary_display == mp_const_none) { - primary_display_number = -1; - return; - } - for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) { - mp_obj_t display = MP_OBJ_FROM_PTR(&displays[i]); - if (new_primary_display == display && is_display_active(display)) { - primary_display_number = i; - return; - } - } - // object was not a display after all... - mp_raise_TypeError_varg(MP_ERROR_TEXT("%q must be of type %q or %q, not %q"), MP_QSTR_Display, MP_QSTR_AnyDisplay, MP_QSTR_None, mp_obj_get_type(new_primary_display)->name); -} - -void common_hal_displayio_auto_primary_display(void) { - if (primary_display_number != -1) { - return; - } - for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) { - if (is_display_active(&displays[i].display_base)) { - primary_display_number = i; - return; - } - } -} diff --git a/shared-module/displayio/__init__.h b/shared-module/displayio/__init__.h index 29b8c64c972..c4508aef23c 100644 --- a/shared-module/displayio/__init__.h +++ b/shared-module/displayio/__init__.h @@ -4,111 +4,25 @@ // // SPDX-License-Identifier: MIT -#if CIRCUITPY_BUSDISPLAY -#include "shared-bindings/busdisplay/BusDisplay.h" -#endif -#if CIRCUITPY_AURORA_EPAPER -#include "shared-module/aurora_epaper/aurora_framebuffer.h" -#endif -#include "shared-bindings/displayio/Group.h" -#if CIRCUITPY_EPAPERDISPLAY -#include "shared-bindings/epaperdisplay/EPaperDisplay.h" -#endif -#if CIRCUITPY_FRAMEBUFFERIO -#include "shared-bindings/framebufferio/FramebufferDisplay.h" -#endif -#if CIRCUITPY_FOURWIRE -#include "shared-bindings/fourwire/FourWire.h" -#endif -#if CIRCUITPY_I2CDISPLAYBUS -#include "shared-bindings/i2cdisplaybus/I2CDisplayBus.h" -#endif -#if CIRCUITPY_PARALLELDISPLAYBUS -#include "shared-bindings/paralleldisplaybus/ParallelBus.h" -#endif -#if CIRCUITPY_RGBMATRIX -#include "shared-bindings/rgbmatrix/RGBMatrix.h" -#endif -#if CIRCUITPY_IS31FL3741 -#include "shared-bindings/is31fl3741/FrameBuffer.h" -#endif -#if CIRCUITPY_SHARPDISPLAY -#include "shared-module/sharpdisplay/SharpMemoryFramebuffer.h" -#endif -#if CIRCUITPY_DOTCLOCKFRAMEBUFFER -#include "common-hal/dotclockframebuffer/DotClockFramebuffer.h" -#endif -// Port unique frame buffers. -#if CIRCUITPY_VIDEOCORE -#include "bindings/videocore/Framebuffer.h" -#endif -#if CIRCUITPY_PICODVI -#include "bindings/picodvi/Framebuffer.h" -#endif - #pragma once -typedef struct { - union { - mp_obj_base_t bus_base; - #if CIRCUITPY_FOURWIRE - fourwire_fourwire_obj_t fourwire_bus; - #endif - #if CIRCUITPY_I2CDISPLAYBUS - i2cdisplaybus_i2cdisplaybus_obj_t i2cdisplay_bus; - #endif - #if CIRCUITPY_PARALLELDISPLAYBUS - paralleldisplaybus_parallelbus_obj_t parallel_bus; - #endif - #if CIRCUITPY_RGBMATRIX - rgbmatrix_rgbmatrix_obj_t rgbmatrix; - #endif - #if CIRCUITPY_IS31FL3741 - is31fl3741_framebuffer_obj_t is31fl3741; - #endif - #if CIRCUITPY_SHARPDISPLAY - sharpdisplay_framebuffer_obj_t sharpdisplay; - #endif - #if CIRCUITPY_VIDEOCORE - videocore_framebuffer_obj_t videocore; - #endif - #if CIRCUITPY_PICODVI - picodvi_framebuffer_obj_t picodvi; - #endif - #if CIRCUITPY_DOTCLOCKFRAMEBUFFER - dotclockframebuffer_framebuffer_obj_t dotclock; - #endif - #if CIRCUITPY_AURORA_EPAPER - aurora_epaper_framebuffer_obj_t aurora_epaper; - #endif - }; -} primary_display_bus_t; - -typedef struct { - union { - mp_obj_base_t display_base; - #if CIRCUITPY_BUSDISPLAY - busdisplay_busdisplay_obj_t display; - #endif - #if CIRCUITPY_EPAPERDISPLAY - epaperdisplay_epaperdisplay_obj_t epaper_display; - #endif - #if CIRCUITPY_FRAMEBUFFERIO - framebufferio_framebufferdisplay_obj_t framebuffer_display; - #endif - }; -} primary_display_t; - -extern primary_display_bus_t display_buses[CIRCUITPY_DISPLAY_LIMIT]; -extern primary_display_t displays[CIRCUITPY_DISPLAY_LIMIT]; +#include "shared-bindings/displayio/Group.h" extern displayio_group_t circuitpython_splash; void displayio_background(void); void reset_displays(void); +#if CIRCUITPY_EPAPERDISPLAY_FAST +// Raises if a display using lag_frames can't finish its drive, before any display is released. +void displayio_prepare_release_displays(void); +#endif +// Both compositor backends implement this. It roots the displayed object tree into the +// GC so that user displays survive garbage collection. void displayio_gc_collect(void); -primary_display_t *allocate_display(void); -primary_display_t *allocate_display_or_raise(void); -primary_display_bus_t *allocate_display_bus(void); -primary_display_bus_t *allocate_display_bus_or_raise(void); +#include "shared-module/displayio/legacy/__init__.h" + +// Static slot registries for displays and buses. LVGL and the legacy compositor both use +// them so that board resets, release_displays() and GC can find active displays. +extern primary_display_bus_t display_buses[CIRCUITPY_DISPLAY_LIMIT]; +extern primary_display_t displays[CIRCUITPY_DISPLAY_LIMIT]; diff --git a/shared-module/displayio/area.c b/shared-module/displayio/area.c index 6a79e2aeeea..edeb6ecdff8 100644 --- a/shared-module/displayio/area.c +++ b/shared-module/displayio/area.c @@ -8,6 +8,21 @@ #include "py/misc.h" +// Identity transform. Shared by vectorio and the legacy compositor; the LVGL +// compositor ignores display transforms. +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 displayio_area_copy(const displayio_area_t *src, displayio_area_t *dst) { dst->x1 = src->x1; dst->y1 = src->y1; @@ -63,12 +78,12 @@ bool displayio_area_empty(const displayio_area_t *a) { void displayio_area_canon(displayio_area_t *a) { if (a->x1 > a->x2) { - int16_t t = a->x1; + int32_t t = a->x1; a->x1 = a->x2; a->x2 = t; } if (a->y1 > a->y2) { - int16_t t = a->y1; + int32_t t = a->y1; a->y1 = a->y2; a->y2 = t; } @@ -131,8 +146,8 @@ void displayio_area_transform_within(bool mirror_x, bool mirror_y, bool transpos transformed->y2 = original->y2; } if (transpose_xy) { - int16_t y1 = transformed->y1; - int16_t y2 = transformed->y2; + int32_t y1 = transformed->y1; + int32_t y2 = transformed->y2; transformed->y1 = whole->y1 + (transformed->x1 - whole->x1); transformed->y2 = whole->y1 + (transformed->x2 - whole->x1); transformed->x2 = whole->x1 + (y2 - whole->y1); diff --git a/shared-module/displayio/area.h b/shared-module/displayio/area.h index eed54613a5a..028e38d9c1f 100644 --- a/shared-module/displayio/area.h +++ b/shared-module/displayio/area.h @@ -9,6 +9,12 @@ #include #include +#if CIRCUITPY_DISPLAYIO_LVGL +#include "lvgl.h" +// LVGL owns invalidation and tracks its own areas, so displayio only needs the +// coordinate type there. The linked-list area below is a scanline-compositor detail. +typedef lv_area_t displayio_area_t; +#else // Implementations are in area.c typedef struct _displayio_area_t displayio_area_t; @@ -19,6 +25,7 @@ struct _displayio_area_t { int16_t y2; const displayio_area_t *next; // Next area in the linked list. }; +#endif typedef struct { uint16_t x; diff --git a/shared-module/displayio/bus_core.c b/shared-module/displayio/bus_core.c index e01b9d9eef6..8e668f553a4 100644 --- a/shared-module/displayio/bus_core.c +++ b/shared-module/displayio/bus_core.c @@ -7,7 +7,9 @@ #include "shared-module/displayio/bus_core.h" #include "py/gc.h" +#include "py/mphal.h" #include "py/runtime.h" +#include "shared/runtime/interrupt_char.h" #if CIRCUITPY_FOURWIRE #include "shared-bindings/fourwire/FourWire.h" #endif @@ -17,6 +19,9 @@ #if CIRCUITPY_PARALLELDISPLAYBUS #include "shared-bindings/paralleldisplaybus/ParallelBus.h" #endif +#if CIRCUITPY_QSPIBUS +#include "shared-bindings/qspibus/QSPIBus.h" +#endif #include "shared-bindings/microcontroller/Pin.h" #include "shared-bindings/time/__init__.h" #include "shared-module/displayio/__init__.h" @@ -27,9 +32,31 @@ #include #include +#define DELAY 0x80 + #define DISPLAYIO_CORE_DEBUG(...) (void)0 // #define DISPLAYIO_CORE_DEBUG(...) mp_printf(&mp_plat_print __VA_OPT__(,) __VA_ARGS__) +void displayio_display_bus_validate(mp_obj_t bus) { + if ( + #if CIRCUITPY_PARALLELDISPLAYBUS + mp_obj_is_type(bus, ¶lleldisplaybus_parallelbus_type) || + #endif + #if CIRCUITPY_FOURWIRE + mp_obj_is_type(bus, &fourwire_fourwire_type) || + #endif + #if CIRCUITPY_I2CDISPLAYBUS + mp_obj_is_type(bus, &i2cdisplaybus_i2cdisplaybus_type) || + #endif + #if CIRCUITPY_QSPIBUS + mp_obj_is_type(bus, &qspibus_qspibus_type) || + #endif + false) { + return; + } + mp_raise_ValueError(MP_ERROR_TEXT("Unsupported display bus type")); +} + void displayio_display_bus_construct(displayio_display_bus_t *self, mp_obj_t bus, uint16_t ram_width, uint16_t ram_height, int16_t colstart, int16_t rowstart, uint16_t column_command, uint16_t row_command, uint16_t set_current_column_command, uint16_t set_current_row_command, @@ -49,6 +76,11 @@ void displayio_display_bus_construct(displayio_display_bus_t *self, self->SH1107_addressing = SH1107_addressing; self->address_little_endian = address_little_endian; + self->flush = NULL; + #if CIRCUITPY_BUSIO_SPI_ASYNC + self->send_async = NULL; + #endif + #if CIRCUITPY_PARALLELDISPLAYBUS if (mp_obj_is_type(bus, ¶lleldisplaybus_parallelbus_type)) { self->bus_reset = common_hal_paralleldisplaybus_parallelbus_reset; @@ -67,6 +99,10 @@ void displayio_display_bus_construct(displayio_display_bus_t *self, self->send = common_hal_fourwire_fourwire_send; self->end_transaction = common_hal_fourwire_fourwire_end_transaction; self->collect_ptrs = common_hal_fourwire_fourwire_collect_ptrs; + #if CIRCUITPY_BUSIO_SPI_ASYNC + self->send_async = common_hal_fourwire_fourwire_send_async; + self->flush = common_hal_fourwire_fourwire_flush; + #endif } else #endif #if CIRCUITPY_I2CDISPLAYBUS @@ -79,17 +115,33 @@ void displayio_display_bus_construct(displayio_display_bus_t *self, self->collect_ptrs = common_hal_i2cdisplaybus_i2cdisplaybus_collect_ptrs; } else #endif + #if CIRCUITPY_QSPIBUS + if (mp_obj_is_type(bus, &qspibus_qspibus_type)) { + self->bus_reset = common_hal_qspibus_qspibus_reset; + self->bus_free = common_hal_qspibus_qspibus_bus_free; + self->begin_transaction = common_hal_qspibus_qspibus_begin_transaction; + self->send = common_hal_qspibus_qspibus_send; + self->end_transaction = common_hal_qspibus_qspibus_end_transaction; + self->flush = common_hal_qspibus_qspibus_flush; + self->collect_ptrs = common_hal_qspibus_qspibus_collect_ptrs; + } else + #endif { mp_raise_ValueError(MP_ERROR_TEXT("Unsupported display bus type")); } self->bus = bus; } +// This is just a hint, and is not a reliable result, since the bus could be grabbed in between this called +// and the attempt to use the bus. Use displayio_display_bus_begin_transaction(), which is atomic. bool displayio_display_bus_is_free(displayio_display_bus_t *self) { return !self->bus || self->bus_free(self->bus); } -bool displayio_display_bus_begin_transaction(displayio_display_bus_t *self) { +MP_WARN_UNUSED_RESULT bool displayio_display_bus_begin_transaction(displayio_display_bus_t *self) { + if (!self->bus) { + return false; + } mp_obj_base_t *bus_base = MP_OBJ_TO_PTR(self->bus); if (bus_base->type == &mp_type_NoneType) { return false; @@ -101,21 +153,59 @@ void displayio_display_bus_end_transaction(displayio_display_bus_t *self) { self->end_transaction(self->bus); } -void displayio_display_bus_set_region_to_update(displayio_display_bus_t *self, displayio_display_core_t *display, displayio_area_t *area) { +void displayio_display_bus_send_init_sequence(displayio_display_bus_t *self, + const uint8_t *init_sequence, uint16_t init_sequence_len) { + uint32_t i = 0; + while (i < init_sequence_len) { + const uint8_t *cmd = init_sequence + i; + uint8_t data_size = *(cmd + 1); + bool delay = (data_size & DELAY) != 0; + data_size &= ~DELAY; + const uint8_t *data = cmd + 2; + while (!displayio_display_bus_begin_transaction(self)) { + RUN_BACKGROUND_TASKS; + if (mp_hal_is_interrupted()) { + mp_raise_RuntimeError_varg(MP_ERROR_TEXT("%q init failed"), MP_QSTR_display); + } + } + if (self->data_as_commands) { + uint8_t full_command[data_size + 1]; + full_command[0] = cmd[0]; + memcpy(full_command + 1, data, data_size); + self->send(self->bus, DISPLAY_COMMAND, CHIP_SELECT_TOGGLE_EVERY_BYTE, full_command, data_size + 1); + } else { + self->send(self->bus, DISPLAY_COMMAND, data_size > 0 ? CHIP_SELECT_TOGGLE_EVERY_BYTE : CHIP_SELECT_UNTOUCHED, cmd, 1); + self->send(self->bus, DISPLAY_DATA, CHIP_SELECT_UNTOUCHED, data, data_size); + } + displayio_display_bus_end_transaction(self); + uint16_t delay_length_ms = 10; + if (delay) { + data_size++; + delay_length_ms = *(cmd + 1 + data_size); + if (delay_length_ms == 255) { + delay_length_ms = 500; + } + } + common_hal_time_delay_ms(delay_length_ms); + i += 2 + data_size; + } +} + +void displayio_display_bus_set_region_to_update(displayio_display_bus_t *self, const _displayio_colorspace_t *colorspace, displayio_area_t *area) { uint16_t x1 = area->x1 + self->colstart; uint16_t x2 = area->x2 + self->colstart; uint16_t y1 = area->y1 + self->rowstart; uint16_t y2 = area->y2 + self->rowstart; // Collapse down the dimension where multiple pixels are in a byte. - if (display->colorspace.depth < 8) { - uint8_t pixels_per_byte = 8 / display->colorspace.depth; - if (display->colorspace.pixels_in_byte_share_row) { - x1 /= pixels_per_byte * display->colorspace.bytes_per_cell; - x2 /= pixels_per_byte * display->colorspace.bytes_per_cell; + if (colorspace->depth < 8) { + uint8_t pixels_per_byte = 8 / colorspace->depth; + if (colorspace->pixels_in_byte_share_row) { + x1 /= pixels_per_byte * colorspace->bytes_per_cell; + x2 /= pixels_per_byte * colorspace->bytes_per_cell; } else { - y1 /= pixels_per_byte * display->colorspace.bytes_per_cell; - y2 /= pixels_per_byte * display->colorspace.bytes_per_cell; + y1 /= pixels_per_byte * colorspace->bytes_per_cell; + y2 /= pixels_per_byte * colorspace->bytes_per_cell; } } @@ -128,7 +218,9 @@ void displayio_display_bus_set_region_to_update(displayio_display_bus_t *self, d } // Set column. - displayio_display_bus_begin_transaction(self); + if (!displayio_display_bus_begin_transaction(self)) { + return; + } uint8_t data[5]; data[0] = self->column_command; uint8_t data_length = 1; @@ -167,7 +259,9 @@ void displayio_display_bus_set_region_to_update(displayio_display_bus_t *self, d if (self->set_current_column_command != NO_COMMAND) { uint8_t command = self->set_current_column_command; - displayio_display_bus_begin_transaction(self); + if (!displayio_display_bus_begin_transaction(self)) { + return; + } self->send(self->bus, DISPLAY_COMMAND, chip_select, &command, 1); // Only send the first half of data because it is the first coordinate. self->send(self->bus, DISPLAY_DATA, chip_select, data, data_length / 2); @@ -176,7 +270,9 @@ void displayio_display_bus_set_region_to_update(displayio_display_bus_t *self, d // Set row. - displayio_display_bus_begin_transaction(self); + if (!displayio_display_bus_begin_transaction(self)) { + return; + } data[0] = self->row_command; data_length = 1; if (!self->data_as_commands) { @@ -211,7 +307,9 @@ void displayio_display_bus_set_region_to_update(displayio_display_bus_t *self, d if (self->set_current_row_command != NO_COMMAND) { uint8_t command = self->set_current_row_command; - displayio_display_bus_begin_transaction(self); + if (!displayio_display_bus_begin_transaction(self)) { + return; + } self->send(self->bus, DISPLAY_COMMAND, chip_select, &command, 1); // Only send the first half of data because it is the first coordinate. self->send(self->bus, DISPLAY_DATA, chip_select, data, data_length / 2); @@ -219,6 +317,12 @@ void displayio_display_bus_set_region_to_update(displayio_display_bus_t *self, d } } +void displayio_display_bus_flush(displayio_display_bus_t *self) { + if (self->flush != NULL) { + self->flush(self->bus); + } +} + void displayio_display_bus_collect_ptrs(displayio_display_bus_t *self) { self->collect_ptrs(self->bus); } diff --git a/shared-module/displayio/bus_core.h b/shared-module/displayio/bus_core.h index 838454c92e6..4f3dcd6043e 100644 --- a/shared-module/displayio/bus_core.h +++ b/shared-module/displayio/bus_core.h @@ -11,6 +11,7 @@ #include "shared-module/displayio/area.h" #include "shared-module/displayio/display_core.h" +#include "shared-module/displayio/Palette.h" #define NO_COMMAND 0x100 @@ -20,7 +21,12 @@ typedef struct { display_bus_bus_free bus_free; display_bus_begin_transaction begin_transaction; display_bus_send send; + // Optional. Like send, but may return before the data is sent: the data must not change and + // the bus must not be used until flush returns. NULL when the bus has no such mode; only set + // and read when CIRCUITPY_BUSIO_SPI_ASYNC. + display_bus_send send_async; display_bus_end_transaction end_transaction; + display_bus_flush flush; display_bus_collect_ptrs collect_ptrs; uint16_t ram_width; uint16_t ram_height; @@ -38,6 +44,10 @@ typedef struct { bool address_little_endian; } displayio_display_bus_t; +// Raise ValueError if bus isn't a supported display bus type. Call it before allocating a +// display, so a bad bus doesn't leave a half-built display in its slot. +void displayio_display_bus_validate(mp_obj_t bus); + void displayio_display_bus_construct(displayio_display_bus_t *self, mp_obj_t bus, uint16_t ram_width, uint16_t ram_height, int16_t colstart, int16_t rowstart, uint16_t column_command, uint16_t row_command, uint16_t set_current_column_command, uint16_t set_current_row_command, @@ -47,7 +57,16 @@ bool displayio_display_bus_is_free(displayio_display_bus_t *self); bool displayio_display_bus_begin_transaction(displayio_display_bus_t *self); void displayio_display_bus_end_transaction(displayio_display_bus_t *self); -void displayio_display_bus_set_region_to_update(displayio_display_bus_t *self, displayio_display_core_t *display, displayio_area_t *area); +void displayio_display_bus_set_region_to_update(displayio_display_bus_t *self, const _displayio_colorspace_t *colorspace, displayio_area_t *area); + +// Send a BusDisplay-style init sequence. Each command is command, length byte (with 0x80 +// marking a delay), data, optional delay in ms. +void displayio_display_bus_send_init_sequence(displayio_display_bus_t *self, + const uint8_t *init_sequence, uint16_t init_sequence_len); + +// Drain any pending asynchronous transfers on the bus. +// No-op for synchronous buses (FourWire, I2C, ParallelBus). +void displayio_display_bus_flush(displayio_display_bus_t *self); void release_display_bus(displayio_display_bus_t *self); diff --git a/shared-module/displayio/display_core.c b/shared-module/displayio/display_core.c index dfcddde7796..a3a1a16a7f0 100644 --- a/shared-module/displayio/display_core.c +++ b/shared-module/displayio/display_core.c @@ -40,15 +40,20 @@ void displayio_display_core_construct(displayio_display_core_t *self, self->height = height; displayio_display_core_set_rotation(self, rotation); + + // If nothing has claimed the primary display yet, this display becomes it. A display created + // by user code (for example a USB video framebuffer) must be kept across the end of the VM so + // that the supervisor terminal and REPL have somewhere to draw. + common_hal_displayio_auto_primary_display(); } void displayio_display_core_set_rotation(displayio_display_core_t *self, int rotation) { - int height = self->height; - int width = self->width; - rotation = rotation % 360; self->rotation = rotation; + #if !CIRCUITPY_DISPLAYIO_LVGL + int height = self->height; + int width = self->width; self->transform.x = 0; self->transform.y = 0; self->transform.scale = 1; @@ -98,7 +103,30 @@ void displayio_display_core_set_rotation(displayio_display_core_t *self, self->transform.dy = -1; } } + #endif +} + +#if !CIRCUITPY_DISPLAYIO_LVGL +// Keep this out of line so each display implementation and its binding don't get separate copies. +MP_NOINLINE void displayio_display_core_set_rotation_and_update(displayio_display_core_t *self, + int rotation, mp_obj_base_t *display) { + bool transposed = (self->rotation == 90 || self->rotation == 270); + bool will_transposed = (rotation == 90 || rotation == 270); + if (transposed != will_transposed) { + int tmp = self->width; + self->width = self->height; + self->height = tmp; + } + displayio_display_core_set_rotation(self, rotation); + if (display == &displays[0].display_base) { + supervisor_stop_terminal(); + supervisor_start_terminal(self->width, self->height); + } + if (self->current_group != NULL) { + displayio_group_update_transform(self->current_group, &self->transform); + } } +#endif bool displayio_display_core_set_root_group(displayio_display_core_t *self, displayio_group_t *root_group) { @@ -112,15 +140,27 @@ bool displayio_display_core_set_root_group(displayio_display_core_t *self, displ return false; } if (self->current_group != NULL) { + // Deactivate the outgoing tree recursively. This clears its transforms + // and tells layers (such as a VideoBuffer) that they are no longer + // shown. + #if !CIRCUITPY_DISPLAYIO_LVGL + displayio_group_update_transform(self->current_group, NULL); + #endif self->current_group->in_group = false; } if (root_group != NULL) { + // The LVGL compositor updates its own state when the group is attached; the + // legacy compositor re-applies transforms at the start of every display refresh. + #if !CIRCUITPY_DISPLAYIO_LVGL displayio_group_update_transform(root_group, &self->transform); + #endif root_group->in_group = true; } self->current_group = root_group; + #if !CIRCUITPY_DISPLAYIO_LVGL self->full_refresh = true; + #endif return true; } @@ -140,6 +180,7 @@ bool displayio_display_core_get_dither(displayio_display_core_t *self) { return self->colorspace.dither; } +#if !CIRCUITPY_DISPLAYIO_LVGL bool displayio_display_core_start_refresh(displayio_display_core_t *self) { if (self->refresh_in_progress) { return false; @@ -150,17 +191,23 @@ bool displayio_display_core_start_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); - } self->full_refresh = false; self->refresh_in_progress = false; self->last_refresh = supervisor_ticks_ms64(); + if (self->current_group != NULL) { + displayio_group_finish_refresh(self->current_group); + } } +#endif + void release_display_core(displayio_display_core_t *self) { if (self->current_group != NULL) { + // Deactivate the tree so layers stop acting on it (e.g. a VideoBuffer + // pauses its source). + #if !CIRCUITPY_DISPLAYIO_LVGL + displayio_group_update_transform(self->current_group, NULL); + #endif self->current_group->in_group = false; } } @@ -168,38 +215,3 @@ void release_display_core(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) { - if (self->current_group != NULL) { - return displayio_group_fill_area(self->current_group, &self->colorspace, area, mask, buffer); - } - return false; -} - -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; - } - // Expand the area if we have multiple pixels per byte and we need to byte - // align the bounds. - if (self->colorspace.depth < 8) { - uint8_t pixels_per_byte = 8 / self->colorspace.depth * self->colorspace.bytes_per_cell; - if (self->colorspace.pixels_in_byte_share_row) { - if (clipped->x1 % pixels_per_byte != 0) { - clipped->x1 -= clipped->x1 % pixels_per_byte; - } - if (clipped->x2 % pixels_per_byte != 0) { - clipped->x2 += pixels_per_byte - clipped->x2 % pixels_per_byte; - } - } else { - if (clipped->y1 % pixels_per_byte != 0) { - clipped->y1 -= clipped->y1 % pixels_per_byte; - } - if (clipped->y2 % pixels_per_byte != 0) { - clipped->y2 += pixels_per_byte - clipped->y2 % pixels_per_byte; - } - } - } - return true; -} diff --git a/shared-module/displayio/display_core.h b/shared-module/displayio/display_core.h index f3fe2023636..c4bcbad8a4c 100644 --- a/shared-module/displayio/display_core.h +++ b/shared-module/displayio/display_core.h @@ -9,22 +9,27 @@ #include "shared-bindings/displayio/__init__.h" #include "shared-bindings/displayio/Group.h" +#if !CIRCUITPY_DISPLAYIO_LVGL #include "shared-module/displayio/area.h" +#endif #define NO_COMMAND 0x100 typedef struct { displayio_group_t *current_group; uint64_t last_refresh; - displayio_buffer_transform_t transform; - displayio_area_t area; uint16_t width; uint16_t height; uint16_t rotation; _displayio_colorspace_t colorspace; + #if !CIRCUITPY_DISPLAYIO_LVGL + // Scanline-compositor refresh state. LVGL invalidates its own objects. + displayio_buffer_transform_t transform; + displayio_area_t area; bool full_refresh; // New group means we need to refresh the whole display. bool refresh_in_progress; + #endif } displayio_display_core_t; void displayio_display_core_construct(displayio_display_core_t *self, @@ -43,11 +48,16 @@ void displayio_display_core_set_rotation(displayio_display_core_t *self, int rot void release_display_core(displayio_display_core_t *self); +#if !CIRCUITPY_DISPLAYIO_LVGL +void displayio_display_core_set_rotation_and_update(displayio_display_core_t *self, int rotation, + mp_obj_base_t *display); + 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); - 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); +#endif + +void displayio_display_core_collect_ptrs(displayio_display_core_t *self); diff --git a/shared-module/displayio/legacy/Bitmap.c b/shared-module/displayio/legacy/Bitmap.c new file mode 100644 index 00000000000..df222d2a72c --- /dev/null +++ b/shared-module/displayio/legacy/Bitmap.c @@ -0,0 +1,225 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/displayio/Bitmap.h" + +#include + +#include "py/runtime.h" +#include "py/gc.h" + +enum { ALIGN_BITS = 8 * sizeof(uint32_t) }; + +static int stride(uint32_t width, uint32_t bits_per_value) { + uint32_t row_width = width * bits_per_value; + // align to uint32_t + return (row_width + ALIGN_BITS - 1) / ALIGN_BITS; +} + +void common_hal_displayio_bitmap_construct(displayio_bitmap_t *self, uint32_t width, + uint32_t height, uint32_t bits_per_value) { + common_hal_displayio_bitmap_construct_from_buffer(self, width, height, bits_per_value, NULL, false); +} + +void common_hal_displayio_bitmap_construct_from_buffer(displayio_bitmap_t *self, uint32_t width, + uint32_t height, uint32_t bits_per_value, uint32_t *data, bool read_only) { + self->width = width; + self->height = height; + self->stride = stride(width, bits_per_value); + self->data_alloc = false; + if (!data) { + data = m_malloc_without_collect(self->stride * height * sizeof(uint32_t)); + self->data_alloc = true; + } + self->data = data; + self->read_only = read_only; + self->bits_per_value = bits_per_value; + + if (bits_per_value > 8 && bits_per_value != 16 && bits_per_value != 32) { + mp_raise_NotImplementedError(MP_ERROR_TEXT("Invalid bits per value")); + } + + // Division and modulus can be slow because it has to handle any integer. We know bits_per_value + // is a power of two. We divide and mod by bits_per_value to compute the offset into the byte + // array. So, we can the offset computation to simplify to a shift for division and mask for mod. + + 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 < 8 / bits_per_value) { + self->x_shift++; + power_of_two <<= 1; + } + self->x_mask = (1u << self->x_shift) - 1u; // Used as a modulus on the x value + self->bitmask = (1u << bits_per_value) - 1u; + + self->dirty_area.x1 = 0; + self->dirty_area.x2 = width; + self->dirty_area.y1 = 0; + self->dirty_area.y2 = height; +} + +void common_hal_displayio_bitmap_deinit(displayio_bitmap_t *self) { + if (self->data_alloc && self->data != NULL) { + gc_free(self->data); + } + self->data = NULL; +} + +bool common_hal_displayio_bitmap_deinited(displayio_bitmap_t *self) { + return self->data == NULL; +} + +uint16_t common_hal_displayio_bitmap_get_height(displayio_bitmap_t *self) { + return self->height; +} + +uint16_t common_hal_displayio_bitmap_get_width(displayio_bitmap_t *self) { + return self->width; +} + +uint32_t common_hal_displayio_bitmap_get_bits_per_value(displayio_bitmap_t *self) { + return self->bits_per_value; +} + +uint32_t common_hal_displayio_bitmap_get_pixel(displayio_bitmap_t *self, int16_t x, int16_t y) { + if (x >= self->width || x < 0 || y >= self->height || y < 0) { + return 0; + } + int32_t row_start = y * self->stride; + uint32_t *row = self->data + row_start; + uint8_t bytes_per_value = self->bits_per_value / 8; + if (bytes_per_value < 1) { + uint8_t values_per_byte = 8 / self->bits_per_value; + uint8_t bits = ((uint8_t *)row)[x >> self->x_shift]; + uint8_t bit_position = (values_per_byte - (x & self->x_mask) - 1) * self->bits_per_value; + return (bits >> bit_position) & self->bitmask; + } else { + if (bytes_per_value == 1) { + return ((uint8_t *)row)[x]; + } else if (bytes_per_value == 2) { + return ((uint16_t *)row)[x]; + } else if (bytes_per_value == 4) { + return ((uint32_t *)row)[x]; + } + } + return 0; +} + +void displayio_bitmap_set_dirty(displayio_bitmap_t *self, int16_t x1, int16_t y1, int16_t x2, int16_t y2) { + if (self->read_only) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Read-only")); + } + + displayio_area_t area = {x1, y1, x2, y2, NULL}; + displayio_area_canon(&area); + displayio_area_union(&area, &self->dirty_area, &area); + displayio_area_t bitmap_area = {0, 0, self->width, self->height, NULL}; + displayio_area_compute_overlap(&area, &bitmap_area, &self->dirty_area); +} + +void displayio_bitmap_set_dirty_area(displayio_bitmap_t *self, const displayio_area_t *area) { + displayio_bitmap_set_dirty(self, area->x1, area->y1, area->x2, area->y2); +} + +void displayio_bitmap_write_pixel(displayio_bitmap_t *self, int16_t x, int16_t y, uint32_t value) { + if (self->read_only) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Read-only")); + } + // Writes the color index value into a pixel position + // Must update the dirty area separately + + // Don't write if out of area + if (0 > x || x >= self->width || 0 > y || y >= self->height) { + return; + } + + // Update one pixel of data + int32_t row_start = y * self->stride; + uint32_t *row = self->data + row_start; + uint8_t bytes_per_value = self->bits_per_value / 8; + uint8_t values_per_byte = 8 / self->bits_per_value; + if (bytes_per_value < 1) { + uint8_t bits = ((uint8_t *)row)[x >> self->x_shift]; + uint8_t bit_position = (values_per_byte - (x & self->x_mask) - 1) * self->bits_per_value; + bits &= ~(self->bitmask << bit_position); + bits |= (value & self->bitmask) << bit_position; + ((uint8_t *)row)[x >> self->x_shift] = bits; + } else { + if (bytes_per_value == 1) { + ((uint8_t *)row)[x] = value; + } else if (bytes_per_value == 2) { + ((uint16_t *)row)[x] = value; + } else if (bytes_per_value == 4) { + ((uint32_t *)row)[x] = value; + } + } +} + +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(MP_ERROR_TEXT("Read-only")); + } + // update the dirty region + displayio_bitmap_set_dirty(self, x, y, x + 1, y + 1); + + // write the pixel + displayio_bitmap_write_pixel(self, x, y, value); + +} + +displayio_area_t *displayio_bitmap_get_refresh_areas(displayio_bitmap_t *self, displayio_area_t *tail) { + if (self->dirty_area.x1 == self->dirty_area.x2 || self->read_only) { + return tail; + } + self->dirty_area.next = tail; + return &self->dirty_area; +} + +void displayio_bitmap_finish_refresh(displayio_bitmap_t *self) { + if (self->read_only) { + return; + } + self->dirty_area.x1 = 0; + self->dirty_area.x2 = 0; +} + +void common_hal_displayio_bitmap_fill(displayio_bitmap_t *self, uint32_t value) { + if (self->read_only) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Read-only")); + } + displayio_bitmap_set_dirty(self, 0, 0, self->width, self->height); + + // 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)); + } + // copy it in + 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(uint32_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/legacy/Bitmap.h b/shared-module/displayio/legacy/Bitmap.h new file mode 100644 index 00000000000..0146af1848a --- /dev/null +++ b/shared-module/displayio/legacy/Bitmap.h @@ -0,0 +1,35 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include + +#include "py/obj.h" +#include "shared-module/displayio/area.h" + +typedef struct { + mp_obj_base_t base; + uint16_t width; + uint16_t height; + uint32_t *data; + uint16_t stride; // uint32_t's + uint8_t bits_per_value; + uint8_t x_shift; + size_t x_mask; + displayio_area_t dirty_area; + uint16_t bitmask; + bool read_only; + bool data_alloc; // did bitmap allocate data or someone else +} 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); +void displayio_bitmap_write_pixel(displayio_bitmap_t *self, int16_t x, int16_t y, uint32_t value); +void displayio_bitmap_set_dirty(displayio_bitmap_t *self, int16_t x1, int16_t y1, int16_t x2, int16_t y2); +// Compatibility for callers that still pass an area. +void displayio_bitmap_set_dirty_area(displayio_bitmap_t *self, const displayio_area_t *area); diff --git a/shared-module/displayio/legacy/ColorConverter.c b/shared-module/displayio/legacy/ColorConverter.c new file mode 100644 index 00000000000..76dc06b3660 --- /dev/null +++ b/shared-module/displayio/legacy/ColorConverter.c @@ -0,0 +1,415 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/displayio/ColorConverter.h" + +#include "py/misc.h" +#include "py/runtime.h" + +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, displayio_colorspace_t input_colorspace) { + self->dither = dither; + self->transparent_color = NO_TRANSPARENT_COLOR; + self->input_colorspace = input_colorspace; + self->output_colorspace.depth = 16; +} + +uint16_t displayio_colorconverter_compute_rgb565(uint32_t color_rgb888) { + uint32_t r5 = (color_rgb888 >> 19); + uint32_t g6 = (color_rgb888 >> 10) & 0x3f; + uint32_t b5 = (color_rgb888 >> 3) & 0x1f; + return r5 << 11 | g6 << 5 | b5; +} + +uint8_t displayio_colorconverter_compute_rgb332(uint32_t color_rgb888) { + uint32_t r3 = (color_rgb888 >> 21); + uint32_t g3 = (color_rgb888 >> 13) & 0x7; + uint32_t b2 = (color_rgb888 >> 6) & 0x3; + return r3 << 5 | g3 << 2 | b2; +} + +uint8_t displayio_colorconverter_compute_rgbd(uint32_t color_rgb888) { + uint32_t r1 = (color_rgb888 >> 23) & 0x1; + uint32_t g1 = (color_rgb888 >> 15) & 0x1; + uint32_t b1 = (color_rgb888 >> 7) & 0x1; + return r1 << 3 | g1 << 2 | b1 << 1 /* | dummy */; +} + +uint8_t displayio_colorconverter_compute_luma(uint32_t color_rgb888) { + uint32_t r8 = (color_rgb888 >> 16); + uint32_t g8 = (color_rgb888 >> 8) & 0xff; + uint32_t b8 = color_rgb888 & 0xff; + return (r8 * 19 + g8 * 182 + b8 * 54) / 255; +} + +uint8_t displayio_colorconverter_compute_chroma(uint32_t color_rgb888) { + uint32_t r8 = (color_rgb888 >> 16); + uint32_t g8 = (color_rgb888 >> 8) & 0xff; + uint32_t b8 = color_rgb888 & 0xff; + uint8_t max = MAX(r8, MAX(g8, b8)); + uint8_t min = MIN(r8, MIN(g8, b8)); + return max - min; +} + +uint8_t displayio_colorconverter_compute_hue(uint32_t color_rgb888) { + uint32_t r8 = (color_rgb888 >> 16); + uint32_t g8 = (color_rgb888 >> 8) & 0xff; + uint32_t b8 = color_rgb888 & 0xff; + uint8_t max = MAX(r8, MAX(g8, b8)); + uint8_t min = MIN(r8, MIN(g8, b8)); + uint8_t c = max - min; + if (c == 0) { + return 0; + } + + int32_t hue = 0; + if (max == r8) { + hue = (((int32_t)(g8 - b8) * 40) / c) % 240; + } else if (max == g8) { + hue = (((int32_t)(b8 - r8) + (2 * c)) * 40) / c; + } else if (max == b8) { + hue = (((int32_t)(r8 - g8) + (4 * c)) * 40) / c; + } + if (hue < 0) { + hue += 240; + } + + return hue; +} + +uint8_t displayio_colorconverter_compute_sixcolor(uint32_t color_rgb888) { + // This is DDX=1, the default for the displays. + uint8_t chroma = displayio_colorconverter_compute_chroma(color_rgb888); + if (chroma >= 64) { + uint8_t hue = displayio_colorconverter_compute_hue(color_rgb888); + // Red 0 + if (hue < 10) { + return 0x3; + } + // Yellow 42 + if (hue < 42 + 21) { + return 0x2; + } + // Green 85 + if (hue < 85 + 42) { + return 0x6; + } + // Blue 170 + if (hue < 170 + 42) { + return 0x5; + } + + // The rest is red to 255 + return 0x3; + } else { + uint8_t luma = displayio_colorconverter_compute_luma(color_rgb888); + if (luma >= 128) { + return 0x1; // White + } else { + return 0x0; // Black + } + } +} + +uint8_t displayio_colorconverter_compute_sevencolor(uint32_t color_rgb888) { + // This is DDX=1, the default for the displays. + uint8_t chroma = displayio_colorconverter_compute_chroma(color_rgb888); + if (chroma >= 64) { + uint8_t hue = displayio_colorconverter_compute_hue(color_rgb888); + // Red 0 + if (hue < 10) { + return 0x4; + } + // Orange 21 + if (hue < 21 + 10) { + return 0x6; + } + // Yellow 42 + if (hue < 42 + 21) { + return 0x5; + } + // Green 85 + if (hue < 85 + 42) { + return 0x2; + } + // Blue 170 + if (hue < 170 + 42) { + return 0x3; + } + + // The rest is red to 255 + return 0x4; + } else { + uint8_t luma = displayio_colorconverter_compute_luma(color_rgb888); + if (luma >= 128) { + return 0x1; // White + } else { + return 0x0; // Black + } + } +} + +void displayio_colorconverter_compute_tricolor(const _displayio_colorspace_t *colorspace, uint8_t pixel_chroma, uint8_t pixel_hue, uint32_t *color) { + if (pixel_chroma <= 16) { + if (!colorspace->grayscale) { + *color = 0; + } + return; + } + int16_t hue_diff = colorspace->tricolor_hue - pixel_hue; + if ((-10 <= hue_diff && hue_diff <= 10) || hue_diff <= -220 || hue_diff >= 220) { + if (colorspace->grayscale) { + *color = 0; + } else { + *color = 1; + } + } else if (!colorspace->grayscale) { + *color = 0; + } +} + +void displayio_colorconverter_compute_fourcolor(const _displayio_colorspace_t *colorspace, uint8_t pixel_chroma, uint8_t pixel_hue, uint32_t *color) { + *color >>= 1; + if (pixel_chroma <= 16) { + return; + } + int16_t hue_diff = colorspace->tricolor_hue - pixel_hue; + if ((-10 <= hue_diff && hue_diff <= 10) || hue_diff <= -220 || hue_diff >= 220) { + *color = 2; + } + int16_t hue_diff2 = colorspace->fourcolor_hue - pixel_hue; + if ((-10 <= hue_diff2 && hue_diff2 <= 10) || hue_diff2 <= -220 || hue_diff2 >= 220) { + *color = 3; + } +} + +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; + + displayio_output_pixel_t output_pixel; + output_pixel.pixel = 0; + output_pixel.opaque = false; + + displayio_colorconverter_convert(self, colorspace, &input_pixel, &output_pixel); + + (*output_color) = output_pixel.pixel; +} + +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) { + return self->dither; +} + +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(MP_ERROR_TEXT("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; + // NO_TRANSPARENT_COLOR will never equal a valid color + self->transparent_color = NO_TRANSPARENT_COLOR; +} + + +// Convert a single input pixel to RGB888 +uint32_t displayio_colorconverter_convert_pixel(displayio_colorspace_t colorspace, uint32_t pixel) { + switch (colorspace) { + case DISPLAYIO_COLORSPACE_RGB565_SWAPPED: + pixel = __builtin_bswap16(pixel); + MP_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); + MP_FALLTHROUGH; + case DISPLAYIO_COLORSPACE_RGB555: { + uint32_t r8 = (pixel >> 10) & 0x1f; + uint32_t g8 = (pixel >> 5) & 0x1f; + uint32_t b8 = pixel & 0x1f; + r8 = (r8 << 3) | ((r8 >> 2) & 0b111); + g8 = (g8 << 3) | ((g8 >> 2) & 0b111); + b8 = (b8 << 3) | ((b8 >> 2) & 0b111); + pixel = (r8 << 16) | (g8 << 8) | b8; + } + break; + + case DISPLAYIO_COLORSPACE_BGR565_SWAPPED: + pixel = __builtin_bswap16(pixel); + MP_FALLTHROUGH; + case DISPLAYIO_COLORSPACE_BGR565: { + uint32_t b8 = (pixel >> 11) << 3; + uint32_t g8 = ((pixel >> 5) << 2) & 0xff; + uint32_t r8 = (pixel << 3) & 0xff; + pixel = (r8 << 16) | (g8 << 8) | b8; + } + break; + + case DISPLAYIO_COLORSPACE_BGR555_SWAPPED: + pixel = __builtin_bswap16(pixel); + MP_FALLTHROUGH; + case DISPLAYIO_COLORSPACE_BGR555: { + uint32_t b8 = (pixel >> 10) & 0x1f; + uint32_t g8 = (pixel >> 5) & 0x1f; + uint32_t r8 = pixel & 0x1f; + r8 = (r8 << 3) | ((r8 >> 2) & 0b111); + g8 = (g8 << 3) | ((g8 >> 2) & 0b111); + b8 = (b8 << 3) | ((b8 >> 2) & 0b111); + pixel = (r8 << 16) | (g8 << 8) | b8; + } + break; + + default: + case DISPLAYIO_COLORSPACE_RGB888: + break; + + case DISPLAYIO_COLORSPACE_L8: { + uint32_t l8 = pixel & 0xff; + pixel = l8 * 0x010101; + } + break; + + case DISPLAYIO_COLORSPACE_L1: { + uint32_t l1 = pixel & 0x1; + pixel = l1 * 0xffffff; + } + break; + } + + return pixel; +} + +void displayio_convert_color(const _displayio_colorspace_t *colorspace, bool dither, const displayio_input_pixel_t *input_pixel, displayio_output_pixel_t *output_color) { + uint32_t pixel = input_pixel->pixel; + if (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)); + + 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)); + } else { + int bitmask = 0xFF >> colorspace->depth; + b8 = MIN(255, b8 + (randb & bitmask)); + r8 = MIN(255, r8 + (randr & bitmask)); + g8 = MIN(255, g8 + (randg & bitmask)); + } + pixel = r8 << 16 | g8 << 8 | b8; + } + + if (colorspace->depth == 16) { + uint16_t packed = displayio_colorconverter_compute_rgb565(pixel); + if (colorspace->reverse_bytes_in_word) { + // swap bytes + packed = __builtin_bswap16(packed); + } + output_color->pixel = packed; + output_color->opaque = true; + return; + } else if (colorspace->tricolor || colorspace->fourcolor) { + uint8_t luma = displayio_colorconverter_compute_luma(pixel); + uint8_t pixel_chroma = displayio_colorconverter_compute_chroma(pixel); + output_color->pixel = luma >> (8 - colorspace->depth); + uint8_t pixel_hue = displayio_colorconverter_compute_hue(pixel); + if (colorspace->tricolor) { + displayio_colorconverter_compute_tricolor(colorspace, pixel_chroma, pixel_hue, &output_color->pixel); + } else if (colorspace->fourcolor) { + displayio_colorconverter_compute_fourcolor(colorspace, pixel_chroma, pixel_hue, &output_color->pixel); + } + output_color->opaque = true; + return; + } 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; + output_color->opaque = true; + return; + } else if (colorspace->depth == 32 || colorspace->depth == 24) { + output_color->pixel = pixel; + output_color->opaque = true; + return; + } else if (colorspace->depth == 8 && !colorspace->grayscale) { + uint8_t packed = displayio_colorconverter_compute_rgb332(pixel); + output_color->pixel = packed; + output_color->opaque = true; + return; + } else if (colorspace->depth == 4) { + uint8_t packed; + if (colorspace->sixcolor) { + packed = displayio_colorconverter_compute_sixcolor(pixel); + } else if (colorspace->sevencolor) { + packed = displayio_colorconverter_compute_sevencolor(pixel); + } else { + packed = displayio_colorconverter_compute_rgbd(pixel); + } + output_color->pixel = packed; + output_color->opaque = true; + return; + } + output_color->opaque = false; +} + +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) { + output_color->opaque = false; + return; + } + + if (!self->dither && self->cached_colorspace == colorspace && self->cached_input_pixel == input_pixel->pixel) { + output_color->pixel = self->cached_output_color; + return; + } + + displayio_input_pixel_t rgb888_pixel = *input_pixel; + rgb888_pixel.pixel = displayio_colorconverter_convert_pixel(self->input_colorspace, input_pixel->pixel); + displayio_convert_color(colorspace, self->dither, &rgb888_pixel, output_color); + + if (!self->dither) { + self->cached_colorspace = colorspace; + self->cached_input_pixel = input_pixel->pixel; + self->cached_output_color = output_color->pixel; + } +} + + + +// Currently no refresh logic is needed for a ColorConverter. +bool displayio_colorconverter_needs_refresh(displayio_colorconverter_t *self) { + return false; +} + +void displayio_colorconverter_finish_refresh(displayio_colorconverter_t *self) { +} diff --git a/shared-module/displayio/legacy/Group.c b/shared-module/displayio/legacy/Group.c new file mode 100644 index 00000000000..ae0a01320f2 --- /dev/null +++ b/shared-module/displayio/legacy/Group.c @@ -0,0 +1,557 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/displayio/Group.h" + +#include "py/runtime.h" +#include "py/objlist.h" +#include "shared-bindings/displayio/TileGrid.h" + +#if CIRCUITPY_VECTORIO || CIRCUITPY_VIDEOCORE +#include "shared-bindings/vectorio/VectorShape.h" +#endif + +static void check_readonly(displayio_group_t *self) { + if (self->readonly) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Read-only")); + } +} + +void common_hal_displayio_group_construct(displayio_group_t *self, mp_obj_t scale_obj, mp_int_t x, mp_int_t y) { + uint32_t scale = mp_arg_validate_int_range(mp_obj_get_int(scale_obj), 1, 32767, MP_QSTR_scale); + 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) { + return self->hidden; +} + +void common_hal_displayio_group_set_hidden(displayio_group_t *self, bool hidden) { + if (self->hidden == hidden) { + return; + } + check_readonly(self); + self->hidden = hidden; + if (self->hidden_by_parent) { + return; + } + for (size_t i = 0; i < self->members->len; i++) { + mp_obj_t layer; + layer = mp_obj_cast_to_native_base( + self->members->items[i], &displayio_tilegrid_type); + if (layer != MP_OBJ_NULL) { + displayio_tilegrid_set_hidden_by_parent(layer, hidden); + continue; + } + layer = mp_obj_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; + } + #if CIRCUITPY_VECTORIO || CIRCUITPY_VIDEOCORE + const vectorio_draw_protocol_t *draw_protocol = mp_proto_get(MP_QSTR_protocol_draw, self->members->items[i]); + if (draw_protocol != NULL) { + layer = draw_protocol->draw_get_protocol_self(self->members->items[i]); + if (draw_protocol->draw_protocol_impl->draw_set_hidden != NULL) { + draw_protocol->draw_protocol_impl->draw_set_hidden(layer, hidden); + } else { + draw_protocol->draw_protocol_impl->draw_set_dirty(layer); + } + continue; + } + #endif + } +} + +void displayio_group_set_hidden_by_parent(displayio_group_t *self, bool hidden) { + if (self->hidden_by_parent == hidden) { + return; + } + check_readonly(self); + self->hidden_by_parent = hidden; + // If we're already hidden, then we're done. + if (self->hidden) { + return; + } + for (size_t i = 0; i < self->members->len; i++) { + mp_obj_t layer; + layer = mp_obj_cast_to_native_base( + self->members->items[i], &displayio_tilegrid_type); + if (layer != MP_OBJ_NULL) { + displayio_tilegrid_set_hidden_by_parent(layer, hidden); + continue; + } + layer = mp_obj_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; + } + #if CIRCUITPY_VECTORIO || CIRCUITPY_VIDEOCORE + const vectorio_draw_protocol_t *draw_protocol = mp_proto_get(MP_QSTR_protocol_draw, self->members->items[i]); + if (draw_protocol != NULL) { + layer = draw_protocol->draw_get_protocol_self(self->members->items[i]); + if (draw_protocol->draw_protocol_impl->draw_set_hidden != NULL) { + draw_protocol->draw_protocol_impl->draw_set_hidden(layer, hidden); + } else { + draw_protocol->draw_protocol_impl->draw_set_dirty(layer); + } + continue; + } + #endif + } +} + +mp_obj_t common_hal_displayio_group_get_scale(displayio_group_t *self) { + return MP_OBJ_NEW_SMALL_INT(self->scale); +} + +bool displayio_group_get_previous_area(displayio_group_t *self, displayio_area_t *area) { + bool first = true; + for (size_t i = 0; i < self->members->len; i++) { + mp_obj_t layer; + displayio_area_t layer_area; + layer = mp_obj_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 { + layer = mp_obj_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_union(area, &layer_area, area); + } + } + if (self->item_removed) { + if (first) { + displayio_area_copy(&self->dirty_area, area); + first = false; + } else { + displayio_area_union(area, &self->dirty_area, area); + } + } + return !first; +} + +static void _update_child_transforms(displayio_group_t *self) { + // Draw protocol layers get NULL while inactive. TileGrids and nested + // Groups always get the (zeroed when inactive) transform, since it also + // tracks their group membership. + #if CIRCUITPY_VECTORIO || CIRCUITPY_VIDEOCORE + displayio_buffer_transform_t *draw_transform = + self->active ? &self->absolute_transform : NULL; + #endif + for (size_t i = 0; i < self->members->len; i++) { + mp_obj_t layer; + #if CIRCUITPY_VECTORIO || CIRCUITPY_VIDEOCORE + const vectorio_draw_protocol_t *draw_protocol = mp_proto_get(MP_QSTR_protocol_draw, self->members->items[i]); + if (draw_protocol != NULL) { + layer = draw_protocol->draw_get_protocol_self(self->members->items[i]); + draw_protocol->draw_protocol_impl->draw_update_transform(layer, draw_transform); + continue; + } + #endif + layer = mp_obj_cast_to_native_base( + self->members->items[i], &displayio_tilegrid_type); + if (layer != MP_OBJ_NULL) { + displayio_tilegrid_update_transform(layer, &self->absolute_transform); + continue; + } + layer = mp_obj_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) { + self->active = parent_transform != NULL && parent_transform->scale != 0; + if (self->active) { + int16_t x = self->x; + int16_t y = self->y; + if (parent_transform->transpose_xy) { + x = y; + y = self->x; + } + self->absolute_transform.x = parent_transform->x + parent_transform->dx * x; + self->absolute_transform.y = parent_transform->y + parent_transform->dy * y; + self->absolute_transform.dx = parent_transform->dx * self->scale; + self->absolute_transform.dy = parent_transform->dy * self->scale; + self->absolute_transform.transpose_xy = parent_transform->transpose_xy; + self->absolute_transform.mirror_x = parent_transform->mirror_x; + self->absolute_transform.mirror_y = parent_transform->mirror_y; + + self->absolute_transform.scale = parent_transform->scale * self->scale; + } else { + // Clear the transform so inactive layers can't act on a stale one. + displayio_buffer_transform_t no_transform = {}; + self->absolute_transform = no_transform; + } + _update_child_transforms(self); +} + +void common_hal_displayio_group_set_scale(displayio_group_t *self, mp_obj_t scale_obj) { + uint32_t scale = mp_arg_validate_int_min(mp_obj_get_int(scale_obj), 1, MP_QSTR_scale); + if (self->scale == scale) { + return; + } + check_readonly(self); + uint8_t parent_scale = self->absolute_transform.scale / self->scale; + self->absolute_transform.dx = self->absolute_transform.dx / self->scale * scale; + self->absolute_transform.dy = self->absolute_transform.dy / self->scale * scale; + self->absolute_transform.scale = parent_scale * scale; + self->scale = scale; + _update_child_transforms(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) { + if (self->x == x) { + return; + } + check_readonly(self); + if (self->absolute_transform.transpose_xy) { + int16_t dy = self->absolute_transform.dy / self->scale; + self->absolute_transform.y += dy * (x - self->x); + } else { + int16_t dx = self->absolute_transform.dx / self->scale; + self->absolute_transform.x += dx * (x - self->x); + } + + self->x = x; + _update_child_transforms(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) { + if (self->y == y) { + return; + } + check_readonly(self); + if (self->absolute_transform.transpose_xy) { + int8_t dx = self->absolute_transform.dx / self->scale; + self->absolute_transform.x += dx * (y - self->y); + } else { + int8_t dy = self->absolute_transform.dy / self->scale; + self->absolute_transform.y += dy * (y - self->y); + } + self->y = y; + _update_child_transforms(self); +} + +static void _add_layer(displayio_group_t *self, mp_obj_t layer) { + check_readonly(self); + #if CIRCUITPY_VECTORIO || CIRCUITPY_VIDEOCORE + const vectorio_draw_protocol_t *draw_protocol = mp_proto_get(MP_QSTR_protocol_draw, layer); + if (draw_protocol != NULL) { + mp_obj_t protocol_self = draw_protocol->draw_get_protocol_self(layer); + if (draw_protocol->draw_protocol_impl->draw_set_in_group(protocol_self, true)) { + mp_raise_ValueError(MP_ERROR_TEXT("Layer already in a group")); + } + draw_protocol->draw_protocol_impl->draw_update_transform( + protocol_self, self->active ? &self->absolute_transform : NULL); + return; + } + #endif + mp_obj_t native_layer = mp_obj_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(MP_ERROR_TEXT("Layer already in a group")); + } else { + tilegrid->in_group = true; + } + displayio_tilegrid_update_transform(tilegrid, &self->absolute_transform); + displayio_tilegrid_set_hidden_by_parent( + tilegrid, self->hidden || self->hidden_by_parent); + return; + } + native_layer = mp_obj_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(MP_ERROR_TEXT("Layer already in a group")); + } else { + group->in_group = true; + } + displayio_group_update_transform(group, &self->absolute_transform); + displayio_group_set_hidden_by_parent( + group, self->hidden || self->hidden_by_parent); + return; + } + mp_raise_ValueError(MP_ERROR_TEXT("Layer must be a Group or TileGrid subclass")); +} + +static void _remove_layer(displayio_group_t *self, size_t index) { + check_readonly(self); + mp_obj_t layer; + displayio_area_t layer_area; + bool rendered_last_frame = false; + #if CIRCUITPY_VECTORIO || CIRCUITPY_VIDEOCORE + const vectorio_draw_protocol_t *draw_protocol = mp_proto_get(MP_QSTR_protocol_draw, self->members->items[index]); + if (draw_protocol != NULL) { + layer = draw_protocol->draw_get_protocol_self(self->members->items[index]); + bool has_dirty_area = draw_protocol->draw_protocol_impl->draw_get_dirty_area(layer, &layer_area); + rendered_last_frame = has_dirty_area; + draw_protocol->draw_protocol_impl->draw_update_transform(layer, NULL); + draw_protocol->draw_protocol_impl->draw_set_in_group(layer, false); + } + #endif + layer = mp_obj_cast_to_native_base( + self->members->items[index], &displayio_tilegrid_type); + if (layer != MP_OBJ_NULL) { + displayio_tilegrid_t *tilegrid = layer; + tilegrid->in_group = false; + rendered_last_frame = displayio_tilegrid_get_previous_area(tilegrid, &layer_area); + displayio_tilegrid_update_transform(tilegrid, NULL); + } + layer = mp_obj_cast_to_native_base( + self->members->items[index], &displayio_group_type); + if (layer != MP_OBJ_NULL) { + displayio_group_t *group = layer; + group->in_group = false; + rendered_last_frame = displayio_group_get_previous_area(group, &layer_area); + displayio_group_update_transform(group, NULL); + } + if (!rendered_last_frame) { + return; + } + if (!self->item_removed) { + displayio_area_copy(&layer_area, &self->dirty_area); + } else { + 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) { + _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) { + _remove_layer(self, index); + return mp_obj_list_pop(self->members, index); +} + +mp_int_t common_hal_displayio_group_index(displayio_group_t *self, mp_obj_t layer) { + mp_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->members->len; +} + +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) { + _add_layer(self, layer); + _remove_layer(self, index); + mp_obj_list_store(self->members, MP_OBJ_NEW_SMALL_INT(index), layer); +} + +void displayio_group_construct(displayio_group_t *self, mp_obj_list_t *members, uint32_t scale, mp_int_t x, mp_int_t y) { + self->x = x; + self->y = y; + self->members = members; + self->item_removed = false; + self->scale = scale; + self->in_group = false; + self->active = false; + self->readonly = 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) { + // Track if any of the layers finishes filling in the given area. We can ignore any remaining + // layers at that point. + if (self->hidden == false) { + for (int32_t i = self->members->len - 1; i >= 0; i--) { + mp_obj_t layer; + #if CIRCUITPY_VECTORIO || CIRCUITPY_VIDEOCORE + const vectorio_draw_protocol_t *draw_protocol = mp_proto_get(MP_QSTR_protocol_draw, self->members->items[i]); + if (draw_protocol != NULL) { + layer = draw_protocol->draw_get_protocol_self(self->members->items[i]); + if (draw_protocol->draw_protocol_impl->draw_fill_area(layer, colorspace, area, mask, buffer)) { + return true; + } + continue; + } + #endif + layer = mp_obj_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)) { + return true; + } + continue; + } + layer = mp_obj_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)) { + return true; + } + continue; + } + } + } + return false; +} + +void displayio_group_finish_refresh(displayio_group_t *self) { + self->item_removed = false; + for (int32_t i = self->members->len - 1; i >= 0; i--) { + mp_obj_t layer; + #if CIRCUITPY_VECTORIO || CIRCUITPY_VIDEOCORE + const vectorio_draw_protocol_t *draw_protocol = mp_proto_get(MP_QSTR_protocol_draw, self->members->items[i]); + if (draw_protocol != NULL) { + layer = draw_protocol->draw_get_protocol_self(self->members->items[i]); + draw_protocol->draw_protocol_impl->draw_finish_refresh(layer); + continue; + } + #endif + layer = mp_obj_cast_to_native_base( + self->members->items[i], &displayio_tilegrid_type); + if (layer != MP_OBJ_NULL) { + displayio_tilegrid_finish_refresh(layer); + continue; + } + layer = mp_obj_cast_to_native_base( + self->members->items[i], &displayio_group_type); + if (layer != MP_OBJ_NULL) { + displayio_group_finish_refresh(layer); + continue; + } + } +} + +static displayio_area_t *group_get_refresh_areas_impl(displayio_group_t *self, displayio_area_t *tail) { + if (self->item_removed) { + self->dirty_area.next = tail; + tail = &self->dirty_area; + } + + for (int32_t i = self->members->len - 1; i >= 0; i--) { + mp_obj_t layer; + #if CIRCUITPY_VECTORIO || CIRCUITPY_VIDEOCORE + const vectorio_draw_protocol_t *draw_protocol = mp_proto_get(MP_QSTR_protocol_draw, self->members->items[i]); + if (draw_protocol != NULL) { + layer = draw_protocol->draw_get_protocol_self(self->members->items[i]); + tail = draw_protocol->draw_protocol_impl->draw_get_refresh_areas(layer, tail); + continue; + } + #endif + layer = mp_obj_cast_to_native_base( + self->members->items[i], &displayio_tilegrid_type); + if (layer != MP_OBJ_NULL) { + if (!displayio_tilegrid_get_rendered_hidden(layer)) { + tail = displayio_tilegrid_get_refresh_areas(layer, tail); + } + continue; + } + layer = mp_obj_cast_to_native_base( + self->members->items[i], &displayio_group_type); + if (layer != MP_OBJ_NULL) { + tail = group_get_refresh_areas_impl(layer, tail); + continue; + } + } + + return tail; +} + +// Filter the dirty-rect list by containment: unlink every area that is fully contained +// in another area in the list (a changing text label is the common case - the group +// dirties the whole label region via item_removed plus one area per glyph, and the +// glyph areas all sit inside the label region). Dropping a covered area is lossless: +// the same pixels are refreshed by the survivor, in fewer transfers. +// +// The nodes are OWNED BY THE ITEMS (TileGrid reuses dirty_area as its tile-space dirty +// accumulator between frames, vectorio keeps its current_area, ...), so their +// coordinates must never be modified here. The ONLY mutation is the .next relink, +// which is safe because every provider unconditionally reassigns .next at link time on +// every get_refresh_areas call and never reads it back. +// +// Nodes at and past `tail` belong to the caller, so the sweep uses `tail` as its end +// sentinel and never looks past it (every in-tree caller passes tail == NULL). +// +// One pass suffices: coordinates never change and unlinking preserves the relative +// order of the remaining nodes, so every pair of surviving nodes is examined. Equal +// areas satisfy the containment test in both directions; testing b-inside-a FIRST +// keeps the earlier node and drops the later one - the two tests must stay an else-if +// chain or equal areas would drop BOTH nodes and lose the area entirely. +static displayio_area_t *filter_out_redundant_areas(displayio_area_t *head, + const displayio_area_t *tail) { + displayio_area_t *a_prev = NULL; + displayio_area_t *a = head; + while (a != tail) { + // The casts from the const .next field are safe: every node before `tail` is a + // mutable item-owned struct; only the field's declared type is pointer-to-const. + displayio_area_t *b_prev = a; + displayio_area_t *b = (displayio_area_t *)a->next; + bool a_dropped = false; + while (b != tail) { + if (b->x1 >= a->x1 && b->y1 >= a->y1 && b->x2 <= a->x2 && b->y2 <= a->y2) { + // b is contained in a (equal areas land here): unlink b. + b_prev->next = b->next; + b = (displayio_area_t *)b_prev->next; + } else if (a->x1 >= b->x1 && a->y1 >= b->y1 && a->x2 <= b->x2 && a->y2 <= b->y2) { + // a is strictly contained in the later b: unlink a and move on. + if (a_prev == NULL) { + head = (displayio_area_t *)a->next; + } else { + a_prev->next = a->next; + } + a_dropped = true; + break; + } else { + b_prev = b; + b = (displayio_area_t *)b->next; + } + } + if (a_dropped) { + a = (a_prev == NULL) ? head : (displayio_area_t *)a_prev->next; + } else { + a_prev = a; + a = (displayio_area_t *)a->next; + } + } + return head; +} + +// Public entry point: displays call this once on their root group, so the whole tree's +// list is filtered in one place and no display type needs its own copy of the logic. +displayio_area_t *displayio_group_get_refresh_areas(displayio_group_t *self, displayio_area_t *tail) { + displayio_area_t *areas = group_get_refresh_areas_impl(self, tail); + return filter_out_redundant_areas(areas, tail); +} diff --git a/shared-module/displayio/legacy/Group.h b/shared-module/displayio/legacy/Group.h new file mode 100644 index 00000000000..d0a3bd353ec --- /dev/null +++ b/shared-module/displayio/legacy/Group.h @@ -0,0 +1,40 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#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_base_t base; + 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; + bool item_removed : 1; + bool in_group : 1; + bool active : 1; + bool hidden : 1; + bool hidden_by_parent : 1; + bool readonly : 1; + uint8_t padding : 2; +} displayio_group_t; + +void displayio_group_construct(displayio_group_t *self, mp_obj_list_t *members, uint32_t scale, mp_int_t x, mp_int_t y); +void displayio_group_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); +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); diff --git a/shared-module/displayio/legacy/OnDiskBitmap.c b/shared-module/displayio/legacy/OnDiskBitmap.c new file mode 100644 index 00000000000..c1ce7c50349 --- /dev/null +++ b/shared-module/displayio/legacy/OnDiskBitmap.c @@ -0,0 +1,311 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018 Scott Shawcroft for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2025 SamantazFox +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/displayio/OnDiskBitmap.h" +#include "shared-bindings/displayio/ColorConverter.h" +#include "shared-bindings/displayio/Palette.h" +#include "shared-module/displayio/ColorConverter.h" +#include "shared-module/displayio/Palette.h" + +#include + +#include "py/mperrno.h" +#include "py/runtime.h" +#include "py/stream.h" +#if CIRCUITPY_STORAGE_MAP_FILE +#include "shared-bindings/storage/__init__.h" +#endif + + +#define DISPLAYIO_ODBMP_DEBUG(...) (void)0 +// #define DISPLAYIO_ODBMP_DEBUG(...) mp_printf(&mp_plat_print __VA_OPT__(,) __VA_ARGS__) + + +#if CIRCUITPY_STORAGE_MAP_FILE +static void add_run(void *self_in, const uint8_t *addr, size_t len, uint32_t block) { + displayio_ondiskbitmap_t *self = self_in; + if (self->map_count < MP_ARRAY_SIZE(self->map)) { + self->map[self->map_count].addr = addr; + self->map[self->map_count].len = len; + self->map_count++; + } else { + self->map_count = MP_ARRAY_SIZE(self->map) + 1; // too fragmented: read through the cache + } +} + +// Flash address of len bytes at offset if they lie in one run, else NULL. +static const uint8_t *map_at(displayio_ondiskbitmap_t *self, uint32_t offset, uint32_t len) { + for (uint8_t i = 0; i < self->map_count; i++) { + if (offset < self->map[i].len) { + return offset + len <= self->map[i].len ? self->map[i].addr + offset : NULL; + } + offset -= self->map[i].len; + } + return NULL; +} + +const uint8_t *displayio_ondiskbitmap_row(displayio_ondiskbitmap_t *self, int16_t y) { + return map_at(self, self->data_offset + (self->height - y - 1) * self->stride, self->width); +} +#endif + +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, mp_obj_t file) { + self->file = file; + self->cache_len = 0; + uint16_t bmp_header[69]; + int errcode = 0; + + mp_stream_seek(file, 0, MP_SEEK_SET, &errcode); + if (errcode != 0) { + mp_raise_OSError(errcode); + } + + // Read the minimum amount of bytes required to parse a BITMAPCOREHEADER. + // If needed, we will read more bytes down below. + mp_uint_t bytes_read = mp_stream_rw(file, bmp_header, 26, &errcode, MP_STREAM_RW_ONCE); + if (errcode != 0) { + mp_raise_OSError(errcode); + } + if (bytes_read != 26 || memcmp(bmp_header, "BM", 2) != 0) { + mp_arg_error_invalid(MP_QSTR_file); + } + + // Read header size to determine if more header bytes needs to be read. + uint32_t header_size = read_word(bmp_header, 7); + DISPLAYIO_ODBMP_DEBUG("header_size: %d\n", header_size); + + if (header_size == 40 || header_size == 108 || header_size == 124) { + // Read the remaining header bytes + bytes_read = mp_stream_rw(file, bmp_header + 13, header_size - 12, &errcode, MP_STREAM_RW_ONCE); + if (errcode != 0) { + mp_raise_OSError(errcode); + } + DISPLAYIO_ODBMP_DEBUG("bytes_read: %d\n", bytes_read); + if (bytes_read != (header_size - 12)) { + mp_arg_error_invalid(MP_QSTR_file); + } + } else if (header_size != 12) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("Only Windows format, uncompressed BMP supported: given header size is %d"), header_size); + } + + + uint32_t compression = read_word(bmp_header, 15); + DISPLAYIO_ODBMP_DEBUG("compression: %d\n", compression); + + // 0 is uncompressed; 3 is bitfield compressed. 1 and 2 are RLE compression. + if (compression != 0 && compression != 3) { + mp_raise_ValueError(MP_ERROR_TEXT("RLE-compressed BMP not supported")); + } + + // We can't cast because we're not aligned. + self->data_offset = read_word(bmp_header, 5); + + self->bitfield_compressed = (compression == 3); + self->bits_per_pixel = bmp_header[14]; + self->width = read_word(bmp_header, 9); + self->height = read_word(bmp_header, 11); + + DISPLAYIO_ODBMP_DEBUG("data offset: %d\n", self->data_offset); + DISPLAYIO_ODBMP_DEBUG("width: %d\n", self->width); + DISPLAYIO_ODBMP_DEBUG("height: %d\n", self->height); + DISPLAYIO_ODBMP_DEBUG("bpp: %d\n", self->bits_per_pixel); + + + displayio_colorconverter_t *colorconverter = + mp_obj_malloc(displayio_colorconverter_t, &displayio_colorconverter_type); + common_hal_displayio_colorconverter_construct(colorconverter, false, DISPLAYIO_COLORSPACE_RGB888); + self->colorconverter = colorconverter; + + if (self->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); + self->b_bitmask = read_word(bmp_header, 31); + + } else { // no compression or short header means 5:5:5 + self->r_bitmask = 0x7c00; + self->g_bitmask = 0x3e0; + self->b_bitmask = 0x1f; + } + } else if (self->bits_per_pixel <= 8) { // indexed + uint32_t number_of_colors = 0; + if (header_size >= 40) { + number_of_colors = read_word(bmp_header, 23); + } + if (number_of_colors == 0) { + number_of_colors = 1 << self->bits_per_pixel; + } + + displayio_palette_t *palette = mp_obj_malloc(displayio_palette_t, &displayio_palette_type); + common_hal_displayio_palette_construct(palette, number_of_colors, false); + + if (number_of_colors > 1) { + uint16_t palette_size = number_of_colors * sizeof(uint32_t); + uint16_t palette_offset = 0xe + header_size; + + uint32_t *palette_data = m_malloc_without_collect(palette_size); + + mp_stream_seek(file, palette_offset, MP_SEEK_SET, &errcode); + if (errcode != 0) { + mp_raise_OSError(errcode); + } + + mp_uint_t palette_bytes_read = mp_stream_rw(file, palette_data, palette_size, &errcode, MP_STREAM_RW_ONCE); + if (errcode != 0) { + mp_raise_OSError(errcode); + } + if (palette_bytes_read != palette_size) { + mp_raise_ValueError(MP_ERROR_TEXT("Unable to read color palette data")); + } + for (uint16_t i = 0; i < number_of_colors; i++) { + common_hal_displayio_palette_set_color(palette, i, palette_data[i]); + } + + #if MICROPY_MALLOC_USES_ALLOCATED_SIZE + m_free(palette_data, palette_size); + #else + m_free(palette_data); + #endif + } else { + common_hal_displayio_palette_set_color(palette, 0, 0x0); + common_hal_displayio_palette_set_color(palette, 1, 0xffffff); + } + self->palette = palette; + } + + 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) { + self->stride = (self->width * bytes_per_pixel); + // Rows are word aligned. + if (self->stride % 4 != 0) { + self->stride += 4 - self->stride % 4; + } + } else { + uint32_t bit_stride = self->width * self->bits_per_pixel; + if (bit_stride % 32 != 0) { + bit_stride += 32 - bit_stride % 32; + } + self->stride = (bit_stride / 8); + } + + #if CIRCUITPY_STORAGE_MAP_FILE + self->map_count = 0; + if (storage_map_runs(file, add_run, self) != 0 || self->map_count > MP_ARRAY_SIZE(self->map)) { + self->map_count = 0; + } + // BMP rows don't start on a 4-byte boundary, so in a split file some row crosses a run. + self->rows_mapped = self->bits_per_pixel == 8 && + map_at(self, self->data_offset, (uint32_t)(self->height - 1) * self->stride + self->width) != NULL; + #endif +} + + +void common_hal_displayio_ondiskbitmap_deinit(displayio_ondiskbitmap_t *self) { + if (common_hal_displayio_ondiskbitmap_deinited(self)) { + return; + } + mp_stream_close(self->file); + self->file = NULL; + #if CIRCUITPY_STORAGE_MAP_FILE + // A TileGrid may still draw this bitmap, so it must stop reading rows from mapped flash. + self->rows_mapped = false; + #endif +} + +bool common_hal_displayio_ondiskbitmap_deinited(displayio_ondiskbitmap_t *self) { + return self->file == NULL; +} + +uint32_t common_hal_displayio_ondiskbitmap_get_pixel(displayio_ondiskbitmap_t *self, + int16_t x, int16_t y) { + if (common_hal_displayio_ondiskbitmap_deinited(self) || + 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 pixels_per_byte = 8 / self->bits_per_pixel; + 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; + } + uint32_t pixel_data = 0; + #if CIRCUITPY_STORAGE_MAP_FILE + if (self->map_count > 0) { + // Byte by byte, so a pixel split across two runs reads right too. The cache can't + // help there: it shares memory with the run table. + for (uint8_t i = 0; i < bytes_per_pixel; i++) { + const uint8_t *p = map_at(self, location + i, 1); + if (p == NULL) { + return 0; + } + ((uint8_t *)&pixel_data)[i] = *p; + } + } else + #endif + { + int errcode = 0; + if (location < self->cache_start || location + bytes_per_pixel > self->cache_start + self->cache_len) { + mp_stream_seek(self->file, location, MP_SEEK_SET, &errcode); + if (errcode != 0) { + return 0; + } + self->cache_start = location; + self->cache_len = mp_stream_rw(self->file, self->cache, sizeof(self->cache), &errcode, MP_STREAM_RW_ONCE); + if (errcode != 0 || self->cache_len < bytes_per_pixel) { + self->cache_len = 0; + return 0; + } + } + memcpy(&pixel_data, self->cache + (location - self->cache_start), bytes_per_pixel); + } + uint32_t tmp = 0; + uint8_t red; + uint8_t green; + uint8_t blue; + if (bytes_per_pixel == 1) { + uint8_t offset = (x % pixels_per_byte) * self->bits_per_pixel; + uint8_t mask = (1 << self->bits_per_pixel) - 1; + + return (pixel_data >> ((8 - self->bits_per_pixel) - offset)) & mask; + } 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); + blue = ((pixel_data & self->b_bitmask) >> 0); + } else { // 555 + 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); + return tmp; + } else if ((bytes_per_pixel == 4) && (self->bitfield_compressed)) { + return pixel_data & 0x00FFFFFF; + } else { + return pixel_data; + } +} + +uint16_t common_hal_displayio_ondiskbitmap_get_height(displayio_ondiskbitmap_t *self) { + return self->height; +} + +uint16_t common_hal_displayio_ondiskbitmap_get_width(displayio_ondiskbitmap_t *self) { + return self->width; +} + +mp_obj_t common_hal_displayio_ondiskbitmap_get_pixel_shader(displayio_ondiskbitmap_t *self) { + return MP_OBJ_FROM_PTR(self->pixel_shader_base); +} diff --git a/shared-module/displayio/legacy/OnDiskBitmap.h b/shared-module/displayio/legacy/OnDiskBitmap.h new file mode 100644 index 00000000000..c3ce4c417ab --- /dev/null +++ b/shared-module/displayio/legacy/OnDiskBitmap.h @@ -0,0 +1,54 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include + +#include "py/obj.h" + +typedef struct { + mp_obj_base_t base; + uint16_t width; + uint16_t height; + uint32_t data_offset; + uint16_t stride; + uint32_t r_bitmask; + uint32_t g_bitmask; + uint32_t b_bitmask; + mp_obj_t file; + union { + mp_obj_base_t *pixel_shader_base; + struct displayio_palette *palette; + struct displayio_colorconverter *colorconverter; + }; + bool bitfield_compressed; + uint8_t bits_per_pixel; + // The last bytes read from the file. Pixels are read along rows, so most reads hit it. + uint8_t cache_len; + #if CIRCUITPY_STORAGE_MAP_FILE + // Flash runs the pixels are read from instead of the cache; 0 = read through the cache. + uint8_t map_count; + // 8-bit file with every row inside one run, so TileGrid can read whole rows. + bool rows_mapped; + #endif + uint32_t cache_start; + union { + uint8_t cache[64]; + #if CIRCUITPY_STORAGE_MAP_FILE + struct { + const uint8_t *addr; + uint32_t len; + } map[8]; + #endif + }; +} displayio_ondiskbitmap_t; + +#if CIRCUITPY_STORAGE_MAP_FILE +// Row y of an 8-bit file in flash, or NULL if it spans two runs or the file isn't mapped. +const uint8_t *displayio_ondiskbitmap_row(displayio_ondiskbitmap_t *self, int16_t y); +#endif diff --git a/shared-module/displayio/legacy/Palette.c b/shared-module/displayio/legacy/Palette.c new file mode 100644 index 00000000000..bb0035f1eb5 --- /dev/null +++ b/shared-module/displayio/legacy/Palette.c @@ -0,0 +1,92 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/displayio/Palette.h" + +#include "shared-module/displayio/ColorConverter.h" + +void common_hal_displayio_palette_construct(displayio_palette_t *self, uint16_t color_count, bool dither) { + self->color_count = color_count; + self->colors = (_displayio_color_t *)m_malloc_without_collect(color_count * sizeof(_displayio_color_t)); + self->dither = dither; +} + +void common_hal_displayio_palette_set_dither(displayio_palette_t *self, bool dither) { + self->dither = dither; +} + +bool common_hal_displayio_palette_get_dither(displayio_palette_t *self) { + return self->dither; +} + +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) { + self->colors[palette_index].transparent = true; + self->needs_refresh = true; +} + +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) { + if (self->colors[palette_index].rgb888 == color) { + return; + } + self->colors[palette_index].rgb888 = color; + self->colors[palette_index].cached_colorspace = NULL; + self->needs_refresh = true; +} + +uint32_t common_hal_displayio_palette_get_color(displayio_palette_t *self, uint32_t palette_index) { + return self->colors[palette_index].rgb888; +} + +void displayio_palette_get_color(displayio_palette_t *self, const _displayio_colorspace_t *colorspace, const displayio_input_pixel_t *input_pixel, displayio_output_pixel_t *output_color) { + uint32_t palette_index = input_pixel->pixel; + if (palette_index >= self->color_count || self->colors[palette_index].transparent) { + output_color->opaque = false; + return; + } + + // Cache results when not dithering. + _displayio_color_t *color = &self->colors[palette_index]; + // Check the grayscale settings because EPaperDisplay will change them on + // the same object. + if (!self->dither && + color->cached_colorspace == colorspace && + color->cached_colorspace_grayscale_bit == colorspace->grayscale_bit && + color->cached_colorspace_grayscale == colorspace->grayscale) { + output_color->pixel = self->colors[palette_index].cached_color; + return; + } + + displayio_input_pixel_t rgb888_pixel = *input_pixel; + rgb888_pixel.pixel = self->colors[palette_index].rgb888; + displayio_convert_color(colorspace, self->dither, &rgb888_pixel, output_color); + if (!self->dither) { + color->cached_colorspace = colorspace; + color->cached_color = output_color->pixel; + color->cached_colorspace_grayscale = colorspace->grayscale; + color->cached_colorspace_grayscale_bit = colorspace->grayscale_bit; + } +} + +bool displayio_palette_needs_refresh(displayio_palette_t *self) { + return self->needs_refresh; +} + +void displayio_palette_finish_refresh(displayio_palette_t *self) { + self->needs_refresh = false; +} diff --git a/shared-module/displayio/legacy/TileGrid.c b/shared-module/displayio/legacy/TileGrid.c new file mode 100644 index 00000000000..4d3988f2e27 --- /dev/null +++ b/shared-module/displayio/legacy/TileGrid.c @@ -0,0 +1,953 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/displayio/TileGrid.h" + +#include "py/runtime.h" +#include "shared-bindings/displayio/Bitmap.h" +#include "shared-bindings/displayio/ColorConverter.h" +#include "shared-bindings/displayio/OnDiskBitmap.h" +#include "shared-bindings/displayio/Palette.h" +#if CIRCUITPY_TILEPALETTEMAPPER +#include "shared-bindings/tilepalettemapper/TilePaletteMapper.h" +#endif + +#include "supervisor/shared/serial.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, uint16_t default_tile) { + + uint32_t total_tiles = width * height; + self->bitmap_width_in_tiles = bitmap_width_in_tiles; + self->tiles_in_bitmap = bitmap_width_in_tiles * bitmap_height_in_tiles; + + // Determine if we need uint16_t or uint8_t for tile indices + bool use_uint16 = self->tiles_in_bitmap > 255; + + // Sprites will only have one tile so save a little memory by inlining values in the pointer. + uint8_t inline_tiles = sizeof(void *) / (use_uint16 ? sizeof(uint16_t) : sizeof(uint8_t)); + + if (total_tiles <= inline_tiles) { + self->tiles = 0; + // Pack values into the pointer since there are only a few. + if (use_uint16) { + for (uint32_t i = 0; i < inline_tiles && i < total_tiles; i++) { + ((uint16_t *)&self->tiles)[i] = default_tile; + } + } else { + for (uint32_t i = 0; i < inline_tiles && i < total_tiles; i++) { + ((uint8_t *)&self->tiles)[i] = (uint8_t)default_tile; + } + } + self->inline_tiles = true; + } else { + if (use_uint16) { + uint16_t *tiles16 = (uint16_t *)m_malloc_without_collect(total_tiles * sizeof(uint16_t)); + for (uint32_t i = 0; i < total_tiles; i++) { + tiles16[i] = default_tile; + } + self->tiles = tiles16; + } else { + uint8_t *tiles8 = (uint8_t *)m_malloc_without_collect(total_tiles); + for (uint32_t i = 0; i < total_tiles; i++) { + tiles8[i] = (uint8_t)default_tile; + } + self->tiles = tiles8; + } + self->inline_tiles = false; + } + + self->width_in_tiles = width; + self->height_in_tiles = height; + self->x = x; + self->y = y; + self->pixel_width = width * tile_width; + self->pixel_height = height * tile_height; + self->tile_width = tile_width; + self->tile_height = tile_height; + self->bitmap = bitmap; + self->pixel_shader = pixel_shader; + self->in_group = false; + self->hidden = false; + self->hidden_by_parent = false; + self->previous_area.x1 = 0xffff; + self->previous_area.x2 = self->previous_area.x1; + self->flip_x = false; + self->flip_y = false; + self->transpose_xy = false; + self->absolute_transform = NULL; + #if CIRCUITPY_TILEPALETTEMAPPER + if (mp_obj_is_type(self->pixel_shader, &tilepalettemapper_tilepalettemapper_type)) { + tilepalettemapper_tilepalettemapper_bind(self->pixel_shader, self); + } + #endif +} + + +bool common_hal_displayio_tilegrid_get_hidden(displayio_tilegrid_t *self) { + return self->hidden; +} + +bool displayio_tilegrid_get_rendered_hidden(displayio_tilegrid_t *self) { + return self->rendered_hidden; +} + +void common_hal_displayio_tilegrid_set_hidden(displayio_tilegrid_t *self, bool hidden) { + self->hidden = hidden; + self->rendered_hidden = false; + if (!hidden) { + self->full_change = true; + } +} + +void displayio_tilegrid_set_hidden_by_parent(displayio_tilegrid_t *self, bool hidden) { + self->hidden_by_parent = hidden; + self->rendered_hidden = false; + if (!hidden) { + self->full_change = true; + } +} + +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; + } + displayio_area_copy(&self->previous_area, area); + return true; +} + +static void _update_current_x(displayio_tilegrid_t *self) { + uint16_t width; + if (self->transpose_xy) { + width = self->pixel_height; + } else { + width = self->pixel_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 = 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; + self->current_area.x1 = temp; + } + } +} + +static void _update_current_y(displayio_tilegrid_t *self) { + uint16_t height; + if (self->transpose_xy) { + height = self->pixel_width; + } else { + height = self->pixel_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 = 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; + self->current_area.y1 = temp; + } + } +} + +void displayio_tilegrid_update_transform(displayio_tilegrid_t *self, + const displayio_buffer_transform_t *absolute_transform) { + self->in_group = absolute_transform != NULL; + self->absolute_transform = absolute_transform; + if (absolute_transform != NULL) { + self->moved = true; + + _update_current_x(self); + _update_current_y(self); + } +} + +mp_int_t common_hal_displayio_tilegrid_get_x(displayio_tilegrid_t *self) { + return self->x; +} +void common_hal_displayio_tilegrid_set_x(displayio_tilegrid_t *self, mp_int_t x) { + if (self->x == x) { + return; + } + + self->moved = true; + + self->x = x; + if (self->absolute_transform != NULL) { + _update_current_x(self); + } +} +mp_int_t common_hal_displayio_tilegrid_get_y(displayio_tilegrid_t *self) { + return self->y; +} + +void common_hal_displayio_tilegrid_set_y(displayio_tilegrid_t *self, mp_int_t y) { + if (self->y == y) { + return; + } + self->moved = true; + self->y = y; + if (self->absolute_transform != NULL) { + _update_current_y(self); + } +} + +mp_obj_t common_hal_displayio_tilegrid_get_pixel_shader(displayio_tilegrid_t *self) { + return self->pixel_shader; +} + +void common_hal_displayio_tilegrid_set_pixel_shader(displayio_tilegrid_t *self, mp_obj_t pixel_shader) { + self->pixel_shader = pixel_shader; + self->full_change = true; + #if CIRCUITPY_TILEPALETTEMAPPER + if (mp_obj_is_type(self->pixel_shader, &tilepalettemapper_tilepalettemapper_type)) { + tilepalettemapper_tilepalettemapper_bind(self->pixel_shader, self); + } + #endif +} + +mp_obj_t common_hal_displayio_tilegrid_get_bitmap(displayio_tilegrid_t *self) { + return self->bitmap; +} + +void common_hal_displayio_tilegrid_set_bitmap(displayio_tilegrid_t *self, mp_obj_t bitmap) { + self->bitmap = bitmap; + self->full_change = true; +} + +uint16_t common_hal_displayio_tilegrid_get_width(displayio_tilegrid_t *self) { + return self->width_in_tiles; +} + +uint16_t common_hal_displayio_tilegrid_get_height(displayio_tilegrid_t *self) { + return self->height_in_tiles; +} + +uint16_t common_hal_displayio_tilegrid_get_tile_width(displayio_tilegrid_t *self) { + return self->tile_width; +} + +uint16_t common_hal_displayio_tilegrid_get_tile_height(displayio_tilegrid_t *self) { + return self->tile_height; +} + +uint16_t common_hal_displayio_tilegrid_get_tile(displayio_tilegrid_t *self, uint16_t x, uint16_t y) { + void *tiles = self->tiles; + if (self->inline_tiles) { + tiles = &self->tiles; + } + if (tiles == NULL) { + return 0; + } + + uint32_t index = y * self->width_in_tiles + x; + if (self->tiles_in_bitmap > 255) { + return ((uint16_t *)tiles)[index]; + } else { + return ((uint8_t *)tiles)[index]; + } +} + +void displayio_tilegrid_mark_tile_dirty(displayio_tilegrid_t *self, uint16_t x, uint16_t y) { + displayio_area_t temp_area; + displayio_area_t *tile_area; + if (!self->partial_change) { + tile_area = &self->dirty_area; + } else { + tile_area = &temp_area; + } + int16_t tx = (x - self->top_left_x) % self->width_in_tiles; + if (tx < 0) { + tx += self->width_in_tiles; + } + tile_area->x1 = tx * self->tile_width; + tile_area->x2 = tile_area->x1 + self->tile_width; + int16_t ty = (y - self->top_left_y) % self->height_in_tiles; + if (ty < 0) { + ty += self->height_in_tiles; + } + tile_area->y1 = ty * self->tile_height; + tile_area->y2 = tile_area->y1 + self->tile_height; + + if (self->partial_change) { + displayio_area_union(&self->dirty_area, &temp_area, &self->dirty_area); + } + self->partial_change = true; +} + +void common_hal_displayio_tilegrid_set_tile(displayio_tilegrid_t *self, uint16_t x, uint16_t y, uint16_t tile_index) { + if (tile_index >= self->tiles_in_bitmap) { + mp_raise_ValueError(MP_ERROR_TEXT("Tile index out of bounds")); + } + + void *tiles = self->tiles; + if (self->inline_tiles) { + tiles = &self->tiles; + } + if (tiles == NULL) { + return; + } + + uint32_t index = y * self->width_in_tiles + x; + if (self->tiles_in_bitmap > 255) { + ((uint16_t *)tiles)[index] = tile_index; + } else { + ((uint8_t *)tiles)[index] = (uint8_t)tile_index; + } + displayio_tilegrid_mark_tile_dirty(self, x, y); +} + +void common_hal_displayio_tilegrid_set_all_tiles(displayio_tilegrid_t *self, uint16_t tile_index) { + if (tile_index >= self->tiles_in_bitmap) { + mp_raise_ValueError(MP_ERROR_TEXT("Tile index out of bounds")); + } + + void *tiles = self->tiles; + if (self->inline_tiles) { + tiles = &self->tiles; + } + if (tiles == NULL) { + return; + } + + if (self->tiles_in_bitmap > 255) { + uint16_t *tiles16 = (uint16_t *)tiles; + for (uint16_t y = 0; y < self->height_in_tiles; y++) { + for (uint16_t x = 0; x < self->width_in_tiles; x++) { + tiles16[y * self->width_in_tiles + x] = tile_index; + } + } + } else { + uint8_t *tiles8 = (uint8_t *)tiles; + for (uint16_t y = 0; y < self->height_in_tiles; y++) { + for (uint16_t x = 0; x < self->width_in_tiles; x++) { + tiles8[y * self->width_in_tiles + x] = (uint8_t)tile_index; + } + } + } + + self->full_change = true; +} + +bool common_hal_displayio_tilegrid_get_flip_x(displayio_tilegrid_t *self) { + return self->flip_x; +} + +void common_hal_displayio_tilegrid_set_flip_x(displayio_tilegrid_t *self, bool flip_x) { + if (self->flip_x == flip_x) { + return; + } + self->flip_x = flip_x; + self->full_change = true; +} + +bool common_hal_displayio_tilegrid_get_flip_y(displayio_tilegrid_t *self) { + return self->flip_y; +} + +void common_hal_displayio_tilegrid_set_flip_y(displayio_tilegrid_t *self, bool flip_y) { + if (self->flip_y == flip_y) { + return; + } + self->flip_y = flip_y; + self->full_change = true; +} + +bool common_hal_displayio_tilegrid_get_transpose_xy(displayio_tilegrid_t *self) { + return self->transpose_xy; +} + +void common_hal_displayio_tilegrid_set_transpose_xy(displayio_tilegrid_t *self, bool transpose_xy) { + if (self->transpose_xy == transpose_xy) { + return; + } + self->transpose_xy = transpose_xy; + + // Square TileGrids do not change dimensions when transposed. + if (self->pixel_width == self->pixel_height) { + self->full_change = true; + return; + } + + _update_current_x(self); + _update_current_y(self); + + self->moved = true; +} + +bool common_hal_displayio_tilegrid_contains(displayio_tilegrid_t *self, uint16_t x, uint16_t y) { + uint16_t right_edge = self->x + (self->width_in_tiles * self->tile_width); + uint16_t bottom_edge = self->y + (self->height_in_tiles * self->tile_height); + return x >= self->x && x < right_edge && + y >= self->y && y < bottom_edge; +} + +void common_hal_displayio_tilegrid_set_top_left(displayio_tilegrid_t *self, uint16_t x, uint16_t y) { + self->top_left_x = x; + self->top_left_y = y; + self->full_change = true; +} + +// Any transparent color above this value can never match a 16 bit pixel. +#define MAX_16BIT_PIXEL_VALUE (0xffff) + +// One row of the common case: an 8 or 16 bpp Bitmap or a mapped 8 bpp OnDiskBitmap, a Palette +// without dithering, a 16 bpp display and no scaling. Also a 16 bpp Bitmap with an RGB565 +// ColorConverter without dithering, whose pixels reach a 16 bpp display unchanged apart from +// byte order. Reads go along a bitmap row and land x_stride pixels apart in buffer, which +// covers flips and rotated displays. Same result as the per-pixel loop in +// displayio_tilegrid_fill_area, without the per-pixel calls. Returns false if a pixel was +// transparent. +static bool _fill_row_fast(displayio_tilegrid_t *self, const void *tiles, + displayio_bitmap_t *bitmap, displayio_ondiskbitmap_t *odb, displayio_palette_t *palette, + displayio_colorconverter_t *converter, + const _displayio_colorspace_t *colorspace, uint32_t *mask, uint16_t *buffer, + int32_t offset, int16_t x_stride, uint16_t x, uint16_t y, int16_t count, int16_t x_in_tile, + uint16_t x_tile_index, uint16_t row_tile_location, int16_t y_in_tile) { + bool covered = true; + uint16_t tile_width = self->tile_width; + bool swap = converter != NULL && + (converter->input_colorspace == DISPLAYIO_COLORSPACE_RGB565_SWAPPED) != colorspace->reverse_bytes_in_word; + while (count > 0) { + uint16_t tile_location = row_tile_location + x_tile_index; + // uint8_t like displayio_input_pixel_t.tile, which the per-pixel loop goes through. + uint8_t tile = (self->tiles_in_bitmap > 255) ? + ((const uint16_t *)tiles)[tile_location] : ((const uint8_t *)tiles)[tile_location]; + int16_t bx = (tile % self->bitmap_width_in_tiles) * tile_width + x_in_tile; + int16_t by = (tile / self->bitmap_width_in_tiles) * self->tile_height + y_in_tile; + int16_t run = tile_width - x_in_tile; + if (run > count) { + run = count; + } + int16_t bitmap_width, bitmap_height; + uint8_t bits_per_value; + const void *row; + #if CIRCUITPY_STORAGE_MAP_FILE + if (odb != NULL) { + // Every row of a mapped 8-bit BMP lies in one flash run (rows_mapped). + bitmap_width = odb->width; + bitmap_height = odb->height; + bits_per_value = 8; + row = displayio_ondiskbitmap_row(odb, by); + } else + #endif + { + bitmap_width = bitmap->width; + bitmap_height = bitmap->height; + bits_per_value = bitmap->bits_per_value; + row = bitmap->data + by * bitmap->stride; + } + bool row_inside = by >= 0 && by < bitmap_height; + if (converter != NULL) { + // A separate loop, so the Palette loop below stays as fast as before. With no + // transparent color, copy 32 pixels at a time where none of them is set yet. + // Blocks need consecutive destination pixels, so only when x_stride is 1. + bool blocks = x_stride == 1 && converter->transparent_color > MAX_16BIT_PIXEL_VALUE && + row_inside && bx >= 0 && bx + run <= bitmap_width; + for (int16_t i = 0; i < run; i++, offset += x_stride, bx++) { + while (blocks && (offset & 31) == 0 && run - i >= 32 && mask[offset >> 5] == 0) { + const uint16_t *in = (const uint16_t *)row + bx; + uint16_t *out = buffer + offset; + if (swap) { + for (int k = 0; k < 32; k++) { + out[k] = __builtin_bswap16(in[k]); + } + } else { + memcpy(out, in, 32 * sizeof(uint16_t)); + } + mask[offset >> 5] = 0xffffffff; + i += 32; + offset += 32; + bx += 32; + } + if (i >= run) { + break; + } + uint32_t bit = 1u << (offset & 31); + if (mask[offset >> 5] & bit) { + continue; + } + uint32_t pixel = 0; // get_pixel returns 0 outside the bitmap + if (row_inside && bx >= 0 && bx < bitmap_width) { + pixel = ((const uint16_t *)row)[bx]; + } + if (pixel == converter->transparent_color) { + covered = false; + continue; + } + mask[offset >> 5] |= bit; + buffer[offset] = swap ? __builtin_bswap16(pixel) : pixel; + } + x += run; + } else { + for (int16_t i = 0; i < run; i++, offset += x_stride, bx++, x++) { + uint32_t bit = 1u << (offset & 31); + if (mask[offset >> 5] & bit) { + continue; + } + uint32_t index = 0; // get_pixel returns 0 outside the bitmap + if (row_inside && bx >= 0 && bx < bitmap_width) { + index = (bits_per_value == 8) ? + ((const uint8_t *)row)[bx] : ((const uint16_t *)row)[bx]; + } + if (index >= palette->color_count || palette->colors[index].transparent) { + covered = false; + continue; + } + const _displayio_color_t *color = &palette->colors[index]; + uint16_t pixel; + if (color->cached_colorspace == colorspace && + color->cached_colorspace_grayscale_bit == colorspace->grayscale_bit && + color->cached_colorspace_grayscale == colorspace->grayscale) { + pixel = color->cached_color; + } else { + displayio_input_pixel_t input_pixel = { + .pixel = index, .x = x, .y = y, .tile = tile, .tile_x = bx, .tile_y = by, + }; + displayio_output_pixel_t output_pixel = { .pixel = 0, .opaque = true }; + displayio_palette_get_color(palette, colorspace, &input_pixel, &output_pixel); + pixel = output_pixel.pixel; + } + mask[offset >> 5] |= bit; + buffer[offset] = pixel; + } + } + count -= run; + x_in_tile = 0; + if (++x_tile_index == self->width_in_tiles) { + x_tile_index = 0; + } + } + return covered; +} + +#if CIRCUITPY_STORAGE_MAP_FILE +// The mapped 8-bit OnDiskBitmap with a plain Palette that _fill_row_fast can draw, or NULL. +// Kept out of line so displayio_tilegrid_fill_area's pixel loop compiles as before. +static MP_NOINLINE displayio_ondiskbitmap_t *_row_ondiskbitmap(displayio_tilegrid_t *self) { + if (!mp_obj_is_type(self->bitmap, &displayio_ondiskbitmap_type) || + !mp_obj_is_type(self->pixel_shader, &displayio_palette_type)) { + return NULL; + } + displayio_ondiskbitmap_t *odb = self->bitmap; + displayio_palette_t *palette = self->pixel_shader; + return odb->rows_mapped && !palette->dither ? odb : NULL; +} +#endif + +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. + void *tiles = self->tiles; + if (self->inline_tiles) { + tiles = &self->tiles; + } + if (tiles == NULL) { + return false; + } + + bool hidden = self->hidden || self->hidden_by_parent; + if (hidden) { + return false; + } + + displayio_area_t overlap; + if (!displayio_area_compute_overlap(area, &self->current_area, &overlap)) { + return false; + } + + int16_t x_stride = 1; + int16_t y_stride = displayio_area_width(area); + + bool flip_x = self->flip_x; + bool flip_y = self->flip_y; + if (self->transpose_xy != self->absolute_transform->transpose_xy) { + bool temp_flip = flip_x; + flip_x = flip_y; + flip_y = temp_flip; + } + + // How many pixels are outside of our area between us and the start of the row. + uint16_t start = 0; + if ((self->absolute_transform->dx < 0) != flip_x) { + start += (area->x2 - area->x1 - 1) * x_stride; + x_stride *= -1; + } + if ((self->absolute_transform->dy < 0) != flip_y) { + start += (area->y2 - area->y1 - 1) * y_stride; + y_stride *= -1; + } + + // Track if this layer finishes filling in the given area. We can ignore any remaining + // layers at that point. + bool full_coverage = displayio_area_equal(area, &overlap); + + // TODO(tannewt): Skip coverage tracking if all pixels outside the overlap have already been + // set and our palette is all opaque. + + // TODO(tannewt): Check to see if the pixel_shader has any transparency. If it doesn't then we + // 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); + + int16_t start_x = (transformed.x1 - self->current_area.x1); + int16_t end_x = (transformed.x2 - self->current_area.x1); + int16_t start_y = (transformed.y1 - self->current_area.y1); + int16_t end_y = (transformed.y2 - self->current_area.y1); + + int16_t y_shift = 0; + int16_t x_shift = 0; + if ((self->absolute_transform->dx < 0) != flip_x) { + x_shift = area->x2 - overlap.x2; + } else { + x_shift = overlap.x1 - area->x1; + } + if ((self->absolute_transform->dy < 0) != flip_y) { + y_shift = area->y2 - overlap.y2; + } else { + y_shift = overlap.y1 - area->y1; + } + + // This untransposes x and y so it aligns with bitmap rows. + if (self->transpose_xy != self->absolute_transform->transpose_xy) { + int16_t temp_stride = x_stride; + x_stride = y_stride; + y_stride = temp_stride; + int16_t temp_shift = x_shift; + x_shift = y_shift; + y_shift = temp_shift; + } + + displayio_input_pixel_t input_pixel; + displayio_output_pixel_t output_pixel; + + uint16_t scale = self->absolute_transform->scale; + uint16_t tile_width = self->tile_width; + uint16_t width_in_tiles = self->width_in_tiles; + + displayio_bitmap_t *row_bitmap = NULL; + displayio_ondiskbitmap_t *row_odb = NULL; + displayio_palette_t *row_palette = NULL; + displayio_colorconverter_t *row_converter = NULL; + if (scale == 1 && colorspace->depth == 16 && + mp_obj_is_type(self->bitmap, &displayio_bitmap_type)) { + displayio_bitmap_t *bitmap = self->bitmap; + if (mp_obj_is_type(self->pixel_shader, &displayio_palette_type)) { + displayio_palette_t *palette = self->pixel_shader; + if ((bitmap->bits_per_value == 8 || bitmap->bits_per_value == 16) && !palette->dither) { + row_bitmap = bitmap; + row_palette = palette; + } + } else if (mp_obj_is_type(self->pixel_shader, &displayio_colorconverter_type)) { + displayio_colorconverter_t *converter = self->pixel_shader; + if (bitmap->bits_per_value == 16 && !converter->dither && + (converter->input_colorspace == DISPLAYIO_COLORSPACE_RGB565 || + converter->input_colorspace == DISPLAYIO_COLORSPACE_RGB565_SWAPPED)) { + row_bitmap = bitmap; + row_converter = converter; + } + } + } + #if CIRCUITPY_STORAGE_MAP_FILE + if (row_bitmap == NULL && scale == 1 && colorspace->depth == 16) { + row_odb = _row_ondiskbitmap(self); + if (row_odb != NULL) { + row_palette = self->pixel_shader; + } + } + #endif + + for (input_pixel.y = start_y; input_pixel.y < end_y; ++input_pixel.y) { + int16_t row_start = start + (input_pixel.y - start_y + y_shift) * y_stride; // in pixels + int16_t local_y = input_pixel.y / scale; + uint16_t y_tile_index = (local_y / self->tile_height + self->top_left_y) % self->height_in_tiles; + uint16_t row_tile_location = y_tile_index * width_in_tiles; + int16_t y_in_tile = local_y % self->tile_height; + + // The x terms are stepped along the row instead of divided for every pixel. + int16_t local_x = start_x / scale; + uint16_t x_in_scale = start_x % scale; + int16_t x_in_tile = local_x % tile_width; + uint16_t x_tile_index = (local_x / tile_width + self->top_left_x) % width_in_tiles; + int32_t cached_tile = -1; + int16_t tile_base_x = 0; + int16_t tile_base_y = 0; + + if (row_bitmap != NULL || row_odb != NULL) { + if (!_fill_row_fast(self, tiles, row_bitmap, row_odb, row_palette, row_converter, + colorspace, mask, (uint16_t *)buffer, row_start + x_shift * x_stride, x_stride, + start_x, input_pixel.y, end_x - start_x, x_in_tile, x_tile_index, + row_tile_location, y_in_tile)) { + full_coverage = false; + } + continue; + } + + for (input_pixel.x = start_x; input_pixel.x < end_x; ++input_pixel.x) { + if (input_pixel.x != start_x && ++x_in_scale == scale) { + x_in_scale = 0; + local_x++; + if (++x_in_tile == tile_width) { + x_in_tile = 0; + if (++x_tile_index == width_in_tiles) { + x_tile_index = 0; + } + } + } + + // Compute the destination pixel in the buffer and mask based on the transformations. + int16_t offset = row_start + (input_pixel.x - start_x + x_shift) * x_stride; // in pixels + + // This is super useful for debugging out of range accesses. Uncomment to use. + // if (offset < 0 || offset >= (int32_t) displayio_area_size(area)) { + // asm("bkpt"); + // } + + // Check the mask first to see if the pixel has already been set. + if ((mask[offset / 32] & (1 << (offset % 32))) != 0) { + continue; + } + uint16_t tile_location = row_tile_location + x_tile_index; + + if (self->tiles_in_bitmap > 255) { + input_pixel.tile = ((uint16_t *)tiles)[tile_location]; + } else { + input_pixel.tile = ((uint8_t *)tiles)[tile_location]; + } + if (input_pixel.tile != cached_tile) { + cached_tile = input_pixel.tile; + tile_base_x = (input_pixel.tile % self->bitmap_width_in_tiles) * tile_width; + tile_base_y = (input_pixel.tile / self->bitmap_width_in_tiles) * self->tile_height; + } + input_pixel.tile_x = tile_base_x + x_in_tile; + input_pixel.tile_y = tile_base_y + y_in_tile; + + output_pixel.pixel = 0; + input_pixel.pixel = 0; + + // We always want to read bitmap pixels by row first and then transpose into the destination + // buffer because most bitmaps are row associated. + if (mp_obj_is_type(self->bitmap, &displayio_bitmap_type)) { + input_pixel.pixel = common_hal_displayio_bitmap_get_pixel(self->bitmap, input_pixel.tile_x, input_pixel.tile_y); + } else if (mp_obj_is_type(self->bitmap, &displayio_ondiskbitmap_type)) { + input_pixel.pixel = common_hal_displayio_ondiskbitmap_get_pixel(self->bitmap, input_pixel.tile_x, input_pixel.tile_y); + } + + output_pixel.opaque = true; + #if CIRCUITPY_TILEPALETTEMAPPER + if (mp_obj_is_type(self->pixel_shader, &tilepalettemapper_tilepalettemapper_type)) { + tilepalettemapper_tilepalettemapper_get_color(self->pixel_shader, colorspace, &input_pixel, &output_pixel, x_tile_index, y_tile_index); + } + #endif + if (self->pixel_shader == mp_const_none) { + output_pixel.pixel = input_pixel.pixel; + } else if (mp_obj_is_type(self->pixel_shader, &displayio_palette_type)) { + displayio_palette_get_color(self->pixel_shader, colorspace, &input_pixel, &output_pixel); + } else if (mp_obj_is_type(self->pixel_shader, &displayio_colorconverter_type)) { + displayio_colorconverter_convert(self->pixel_shader, colorspace, &input_pixel, &output_pixel); + } + if (!output_pixel.opaque) { + // A pixel is transparent so we haven't fully covered the area ourselves. + full_coverage = false; + } else { + mask[offset / 32] |= 1 << (offset % 32); + if (colorspace->depth == 16) { + *(((uint16_t *)buffer) + offset) = output_pixel.pixel; + } else if (colorspace->depth == 32) { + *(((uint32_t *)buffer) + offset) = output_pixel.pixel; + } else if (colorspace->depth == 24) { + memcpy(((uint8_t *)buffer) + offset * 3, &output_pixel.pixel, 3); + } else if (colorspace->depth == 8) { + *(((uint8_t *)buffer) + offset) = output_pixel.pixel; + } else if (colorspace->depth < 8) { + uint8_t pixels_per_byte = 8 / colorspace->depth; + + // Reorder the offsets to pack multiple rows into a byte (meaning they share a column). + if (!colorspace->pixels_in_byte_share_row) { + uint16_t width = displayio_area_width(area); + uint16_t row = offset / width; + uint16_t col = offset % width; + // Dividing by pixels_per_byte does truncated division even if we multiply it back out. + offset = col * pixels_per_byte + (row / pixels_per_byte) * pixels_per_byte * width + row % pixels_per_byte; + // Also useful for validating that the bitpacking worked correctly. + // if (offset > displayio_area_size(area)) { + // asm("bkpt"); + // } + } + uint8_t shift = (offset % pixels_per_byte) * colorspace->depth; + if (colorspace->reverse_pixels_in_byte) { + // 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; + } + } + } + } + return full_coverage; +} + +void displayio_tilegrid_finish_refresh(displayio_tilegrid_t *self) { + bool first_draw = self->previous_area.x1 == self->previous_area.x2; + bool hidden = self->hidden || self->hidden_by_parent; + if (!first_draw && hidden) { + self->previous_area.x2 = self->previous_area.x1; + } else if (self->moved || first_draw) { + displayio_area_copy(&self->current_area, &self->previous_area); + } + + self->moved = false; + self->full_change = false; + self->partial_change = false; + if (mp_obj_is_type(self->pixel_shader, &displayio_palette_type)) { + displayio_palette_finish_refresh(self->pixel_shader); + } else if (mp_obj_is_type(self->pixel_shader, &displayio_colorconverter_type)) { + displayio_colorconverter_finish_refresh(self->pixel_shader); + } + if (mp_obj_is_type(self->bitmap, &displayio_bitmap_type)) { + displayio_bitmap_finish_refresh(self->bitmap); + } else if (mp_obj_is_type(self->bitmap, &displayio_ondiskbitmap_type)) { + // OnDiskBitmap changes will trigger a complete reload so no need to + // track changes. + } + // TODO(tannewt): We could double buffer changes to position and move them over here. + // 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) { + 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. + if (hidden) { + self->rendered_hidden = true; + if (!first_draw) { + self->previous_area.next = tail; + return &self->previous_area; + } else { + return tail; + } + } else if (self->moved && !first_draw) { + displayio_area_union(&self->previous_area, &self->current_area, &self->dirty_area); + if (displayio_area_size(&self->dirty_area) <= 2U * self->pixel_width * self->pixel_height) { + self->dirty_area.next = tail; + return &self->dirty_area; + } + self->previous_area.next = tail; + self->current_area.next = &self->previous_area; + return &self->current_area; + } + + // 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); + 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. + if (self->tiles_in_bitmap == 1) { + displayio_area_copy(refresh_area, &self->dirty_area); + self->partial_change = true; + } else { + self->full_change = true; + } + } + } + + self->full_change = self->full_change || + (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)); + + if (self->full_change || first_draw) { + self->current_area.next = tail; + return &self->current_area; + } + + if (self->partial_change) { + int16_t x = self->x; + int16_t y = self->y; + if (self->absolute_transform->transpose_xy) { + int16_t temp = y; + y = x; + x = temp; + } + int16_t x1 = self->dirty_area.x1; + int16_t x2 = self->dirty_area.x2; + if (self->flip_x) { + x1 = self->pixel_width - x1; + x2 = self->pixel_width - x2; + } + int16_t y1 = self->dirty_area.y1; + int16_t y2 = self->dirty_area.y2; + if (self->flip_y) { + y1 = self->pixel_height - y1; + y2 = self->pixel_height - y2; + } + if (self->transpose_xy != self->absolute_transform->transpose_xy) { + int16_t temp1 = y1, temp2 = y2; + y1 = x1; + x1 = temp1; + y2 = x2; + x2 = temp2; + } + self->dirty_area.x1 = self->absolute_transform->x + self->absolute_transform->dx * (x + x1); + self->dirty_area.y1 = self->absolute_transform->y + self->absolute_transform->dy * (y + y1); + self->dirty_area.x2 = self->absolute_transform->x + self->absolute_transform->dx * (x + x2); + self->dirty_area.y2 = self->absolute_transform->y + self->absolute_transform->dy * (y + y2); + if (self->dirty_area.y2 < self->dirty_area.y1) { + int16_t temp = self->dirty_area.y2; + self->dirty_area.y2 = self->dirty_area.y1; + self->dirty_area.y1 = temp; + } + if (self->dirty_area.x2 < self->dirty_area.x1) { + int16_t temp = self->dirty_area.x2; + self->dirty_area.x2 = self->dirty_area.x1; + self->dirty_area.x1 = temp; + } + + self->dirty_area.next = tail; + return &self->dirty_area; + } + return tail; +} diff --git a/shared-module/displayio/legacy/TileGrid.h b/shared-module/displayio/legacy/TileGrid.h new file mode 100644 index 00000000000..0051cc0ebf1 --- /dev/null +++ b/shared-module/displayio/legacy/TileGrid.h @@ -0,0 +1,72 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include + +#include "py/obj.h" +#include "shared-module/displayio/area.h" +#include "shared-module/displayio/Palette.h" + +typedef struct { + mp_obj_base_t base; + mp_obj_t bitmap; + mp_obj_t pixel_shader; + int16_t x; + int16_t y; + uint16_t pixel_width; + uint16_t pixel_height; + uint16_t bitmap_width_in_tiles; + ; + uint16_t tiles_in_bitmap; + uint16_t width_in_tiles; + uint16_t height_in_tiles; + uint16_t tile_width; + uint16_t tile_height; + uint16_t top_left_x; + uint16_t top_left_y; + void *tiles; // Can be either uint8_t* or uint16_t* depending on tiles_in_bitmap + 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; + bool rendered_hidden : 1; + uint8_t padding : 6; +} displayio_tilegrid_t; + +void displayio_tilegrid_set_hidden_by_parent(displayio_tilegrid_t *self, bool hidden); + +// 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); + +// 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); + +// 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); +void displayio_tilegrid_finish_refresh(displayio_tilegrid_t *self); + +bool displayio_tilegrid_get_rendered_hidden(displayio_tilegrid_t *self); +void displayio_tilegrid_validate_pixel_shader(mp_obj_t pixel_shader); + +void displayio_tilegrid_mark_tile_dirty(displayio_tilegrid_t *self, uint16_t x, uint16_t y); diff --git a/shared-module/displayio/legacy/__init__.c b/shared-module/displayio/legacy/__init__.c new file mode 100644 index 00000000000..4bf92777275 --- /dev/null +++ b/shared-module/displayio/legacy/__init__.c @@ -0,0 +1,639 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include + +#include "shared-module/displayio/__init__.h" +#include "shared-bindings/displayio/__init__.h" + +#include "shared/runtime/interrupt_char.h" +#include "py/gc.h" +#include "py/runtime.h" +#include "shared-bindings/board/__init__.h" +#include "shared-bindings/busio/I2C.h" +#include "shared-bindings/busio/SPI.h" +#include "shared-bindings/displayio/Bitmap.h" +#include "shared-bindings/displayio/Group.h" +#include "shared-bindings/displayio/Palette.h" +#include "supervisor/shared/display.h" +#include "supervisor/shared/reload.h" + +#include "py/mpconfig.h" + +#if CIRCUITPY_BUSDISPLAY +#include "shared-bindings/busdisplay/BusDisplay.h" +#endif + +#if CIRCUITPY_DOTCLOCKFRAMEBUFFER +#include "shared-bindings/dotclockframebuffer/DotClockFramebuffer.h" +#endif + +#if CIRCUITPY_IS31FL3741 +#include "shared-bindings/is31fl3741/IS31FL3741.h" +#endif + +#if CIRCUITPY_SHARPDISPLAY +#include "shared-bindings/sharpdisplay/SharpMemoryFramebuffer.h" +#include "shared-module/sharpdisplay/SharpMemoryFramebuffer.h" +#endif + +#if CIRCUITPY_AURORA_EPAPER +#include "shared-bindings/aurora_epaper/aurora_framebuffer.h" +#include "shared-module/aurora_epaper/aurora_framebuffer.h" +#endif + +#if CIRCUITPY_PICODVI_AUDIOOUT +#include "common-hal/picodvi/AudioOut.h" +#endif + +#if CIRCUITPY_MIPIDSI +#include "shared-bindings/mipidsi/Display.h" +#endif +#if CIRCUITPY_ZEPHYR_DISPLAY +#include "bindings/zephyr_display/Display.h" +#endif + +#ifdef BOARD_USE_INTERNAL_SPI +#include "supervisor/spi_flash_api.h" +#endif + +// The default indicates no primary display +static int primary_display_number = -1; +// True when the primary display was set with supervisor.runtime.display. +static bool primary_display_set_by_user = false; + +primary_display_bus_t display_buses[CIRCUITPY_DISPLAY_LIMIT]; +primary_display_t displays[CIRCUITPY_DISPLAY_LIMIT]; + +#if CIRCUITPY_RGBMATRIX || CIRCUITPY_IS31FL3741 || CIRCUITPY_PICODVI || CIRCUITPY_MIPIDSI +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; + if (display->framebuffer == obj) { + return true; + } + } + } + return false; +} +#endif + + +void displayio_background(void) { + if (mp_hal_is_interrupted()) { + return; + } + if (autoreload_ready()) { + // Reload is about to happen, so don't redisplay. + return; + } + + for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) { + mp_const_obj_t display_type = displays[i].display_base.type; + if (display_type == NULL || display_type == &mp_type_NoneType) { + // Skip null display. + continue; + } + if (false) { + #if CIRCUITPY_BUSDISPLAY + } else if (display_type == &busdisplay_busdisplay_type) { + busdisplay_busdisplay_background(&displays[i].display); + #endif + #if CIRCUITPY_FRAMEBUFFERIO + } else if (display_type == &framebufferio_framebufferdisplay_type) { + framebufferio_framebufferdisplay_background(&displays[i].framebuffer_display); + #endif + #if CIRCUITPY_EPAPERDISPLAY + } else if (display_type == &epaperdisplay_epaperdisplay_type) { + epaperdisplay_epaperdisplay_background(&displays[i].epaper_display); + #endif + #if CIRCUITPY_ZEPHYR_DISPLAY + } else if (display_type == &zephyr_display_display_type) { + zephyr_display_display_background(&displays[i].zephyr_display); + #endif + } + } + +} + +// Displays and buses are allocated separately, so a display's bus may be at a different index. +static mp_obj_t get_display_bus(int display_number) { + if (display_number < 0 || display_number >= CIRCUITPY_DISPLAY_LIMIT) { + return NULL; + } + primary_display_t *display = &displays[display_number]; + if (false) { + #if CIRCUITPY_BUSDISPLAY + } else if (display->display_base.type == &busdisplay_busdisplay_type) { + return display->display.bus.bus; + #endif + #if CIRCUITPY_EPAPERDISPLAY + } else if (display->display_base.type == &epaperdisplay_epaperdisplay_type) { + return display->epaper_display.epaper.bus.bus; + #endif + #if CIRCUITPY_FRAMEBUFFERIO + } else if (display->display_base.type == &framebufferio_framebufferdisplay_type) { + return display->framebuffer_display.framebuffer; + #endif + } + return NULL; +} + +// Release the display in displays[i], if any. keeping_primary is true when code has finished +// and the primary display is being kept. +static void release_display_slot(int i, bool keeping_primary) { + mp_const_obj_t display_type = displays[i].display_base.type; + if (display_type == NULL || display_type == &mp_type_NoneType) { + return; + #if CIRCUITPY_BUSDISPLAY + } else if (display_type == &busdisplay_busdisplay_type) { + release_busdisplay(&displays[i].display); + #endif + #if CIRCUITPY_EPAPERDISPLAY + } else if (display_type == &epaperdisplay_epaperdisplay_type) { + #if CIRCUITPY_EPAPERDISPLAY_FAST + if (keeping_primary) { + epaperdisplay_epaperdisplay_end_held_bus(&displays[i].epaper_display); + } + #endif + release_epaperdisplay(&displays[i].epaper_display); + #endif + #if CIRCUITPY_FRAMEBUFFERIO + } else if (display_type == &framebufferio_framebufferdisplay_type) { + release_framebufferdisplay(&displays[i].framebuffer_display); + #endif + #if CIRCUITPY_ZEPHYR_DISPLAY + } else if (display_type == &zephyr_display_display_type) { + release_zephyr_display(&displays[i].zephyr_display); + #endif + } + displays[i].display_base.type = &mp_type_NoneType; +} + +// Release the display bus in display_buses[i], if any. +static void release_display_bus_slot(int i) { + mp_const_obj_t bus_type = display_buses[i].bus_base.type; + if (bus_type == NULL || bus_type == &mp_type_NoneType) { + return; + #if CIRCUITPY_FOURWIRE + } else if (bus_type == &fourwire_fourwire_type) { + common_hal_fourwire_fourwire_deinit(&display_buses[i].fourwire_bus); + #endif + #if CIRCUITPY_I2CDISPLAYBUS + } else if (bus_type == &i2cdisplaybus_i2cdisplaybus_type) { + common_hal_i2cdisplaybus_i2cdisplaybus_deinit(&display_buses[i].i2cdisplay_bus); + #endif + #if CIRCUITPY_DOTCLOCKFRAMEBUFFER + } else if (bus_type == &dotclockframebuffer_framebuffer_type) { + common_hal_dotclockframebuffer_framebuffer_deinit(&display_buses[i].dotclock); + #endif + #if CIRCUITPY_PARALLELDISPLAYBUS + } else if (bus_type == ¶lleldisplaybus_parallelbus_type) { + common_hal_paralleldisplaybus_parallelbus_deinit(&display_buses[i].parallel_bus); + #endif + #if CIRCUITPY_RGBMATRIX + } else if (bus_type == &rgbmatrix_RGBMatrix_type) { + common_hal_rgbmatrix_rgbmatrix_deinit(&display_buses[i].rgbmatrix); + #endif + #if CIRCUITPY_IS31FL3741 + } else if (bus_type == &is31fl3741_framebuffer_type) { + common_hal_is31fl3741_framebuffer_deinit(&display_buses[i].is31fl3741); + #endif + #if CIRCUITPY_SHARPDISPLAY + } else if (bus_type == &sharpdisplay_framebuffer_type) { + common_hal_sharpdisplay_framebuffer_deinit(&display_buses[i].sharpdisplay); + #endif + #if CIRCUITPY_PICODVI + } else if (bus_type == &picodvi_framebuffer_type) { + common_hal_picodvi_framebuffer_deinit(&display_buses[i].picodvi); + #endif + #if CIRCUITPY_MIPIDSI + } else if (bus_type == &mipidsi_display_type) { + common_hal_mipidsi_display_deinit(&display_buses[i].mipidsi); + #endif + #if CIRCUITPY_QSPIBUS + } else if (bus_type == &qspibus_qspibus_type) { + common_hal_qspibus_qspibus_deinit(&display_buses[i].qspi_bus); + #endif + } + display_buses[i].bus_base.type = &mp_type_NoneType; +} + +void displayio_release_displays_slots(int keep_index) { + // Release displays before busses so that they can send any final commands to turn the display + // off properly. + for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) { + if (i != keep_index) { + release_display_slot(i, keep_index >= 0); + } + } + mp_obj_t keep_bus = get_display_bus(keep_index); + for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) { + if (MP_OBJ_FROM_PTR(&display_buses[i]) != keep_bus) { + release_display_bus_slot(i); + } + } +} + +static void common_hal_displayio_release_displays_impl(bool keep_primary) { + int keep_index = keep_primary ? primary_display_number : -1; + if (!keep_primary) { + primary_display_number = -1; + primary_display_set_by_user = false; + } + displayio_release_displays_slots(keep_index); + if (!keep_primary) { + supervisor_stop_terminal(); + } +} + +#if CIRCUITPY_EPAPERDISPLAY_FAST +void displayio_prepare_release_displays(void) { + for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) { + if (displays[i].display_base.type == &epaperdisplay_epaperdisplay_type) { + epaperdisplay_epaperdisplay_prepare_release(&displays[i].epaper_display); + } + } +} +#endif + +void common_hal_displayio_release_displays(void) { + common_hal_displayio_release_displays_impl(false); +} + +void common_hal_displayio_deinit_display(mp_obj_t display) { + int display_number = -1; + for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) { + if (MP_OBJ_FROM_PTR(&displays[i]) == display) { + display_number = i; + break; + } + } + if (display_number == -1) { + return; + } + mp_const_obj_t display_type = displays[display_number].display_base.type; + if (display_type == NULL || display_type == &mp_type_NoneType) { + // Already released. + return; + } + + #if CIRCUITPY_EPAPERDISPLAY_FAST + // This can raise RuntimeError. It runs before anything is released, so an error + // leaves the display as it was. + if (display_type == &epaperdisplay_epaperdisplay_type) { + epaperdisplay_epaperdisplay_prepare_release(&displays[display_number].epaper_display); + } + #endif + + // get_display_bus() returns NULL for a released display, so look up the bus first. + mp_obj_t bus = get_display_bus(display_number); + release_display_slot(display_number, false); + + // Release the bus too, unless another display still uses it. + if (bus != NULL) { + bool bus_in_use = false; + for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) { + if (get_display_bus(i) == bus) { + bus_in_use = true; + break; + } + } + if (!bus_in_use) { + for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) { + if (MP_OBJ_FROM_PTR(&display_buses[i]) == bus) { + release_display_bus_slot(i); + break; + } + } + } + } + + if (display_number == primary_display_number) { + primary_display_number = -1; + primary_display_set_by_user = false; + supervisor_stop_terminal(); + } +} + +void reset_displays(void) { + // Release secondary displays. + common_hal_displayio_release_displays_impl(/*keep_primary*/ true); + + // 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++) { + mp_const_obj_t display_bus_type = display_buses[i].bus_base.type; + if (display_bus_type == NULL || display_bus_type == &mp_type_NoneType) { + display_buses[i].bus_base.type = &mp_type_NoneType; + continue; + #if CIRCUITPY_FOURWIRE + } else if (display_bus_type == &fourwire_fourwire_type) { + fourwire_fourwire_obj_t *fourwire = &display_buses[i].fourwire_bus; + if (((size_t)fourwire->bus) < ((size_t)&display_buses) || + ((size_t)fourwire->bus) > ((size_t)&display_buses + CIRCUITPY_DISPLAY_LIMIT * sizeof(primary_display_bus_t))) { + busio_spi_obj_t *original_spi = fourwire->bus; + if (!gc_ptr_on_heap(original_spi)) { + continue; + } + memcpy(&fourwire->inline_bus, original_spi, sizeof(busio_spi_obj_t)); + fourwire->bus = &fourwire->inline_bus; + + // Check for other display buses that use the same spi bus and swap them too. + for (uint8_t j = i + 1; j < CIRCUITPY_DISPLAY_LIMIT; j++) { + if (display_buses[j].fourwire_bus.base.type == &fourwire_fourwire_type && + display_buses[j].fourwire_bus.bus == original_spi) { + display_buses[j].fourwire_bus.bus = &fourwire->inline_bus; + } + } + // Mark the old SPI object so it is considered deinit. + common_hal_busio_spi_mark_deinit(original_spi); + } + #endif + #if CIRCUITPY_I2CDISPLAYBUS + } else if (display_bus_type == &i2cdisplaybus_i2cdisplaybus_type) { + i2cdisplaybus_i2cdisplaybus_obj_t *i2c = &display_buses[i].i2cdisplay_bus; + // Check to see if we need to inline the I2C bus. + if (((size_t)i2c->bus) < ((size_t)&display_buses) || + ((size_t)i2c->bus) > ((size_t)&display_buses + CIRCUITPY_DISPLAY_LIMIT * sizeof(primary_display_bus_t))) { + busio_i2c_obj_t *original_i2c = i2c->bus; + if (!gc_ptr_on_heap(original_i2c)) { + continue; + } + 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 (display_buses[j].i2cdisplay_bus.base.type == &i2cdisplaybus_i2cdisplaybus_type && + display_buses[j].i2cdisplay_bus.bus == original_i2c) { + display_buses[j].i2cdisplay_bus.bus = &i2c->inline_bus; + } + } + // Mark the old i2c object so it is considered deinit. + common_hal_busio_i2c_mark_deinit(original_i2c); + } + #endif + #if CIRCUITPY_RGBMATRIX + } else if (display_bus_type == &rgbmatrix_RGBMatrix_type) { + rgbmatrix_rgbmatrix_obj_t *pm = &display_buses[i].rgbmatrix; + if (!any_display_uses_this_framebuffer(&pm->base)) { + common_hal_rgbmatrix_rgbmatrix_deinit(pm); + } else { + common_hal_rgbmatrix_rgbmatrix_set_paused(pm, true); + } + #endif + #if CIRCUITPY_IS31FL3741 + } else if (display_bus_type == &is31fl3741_framebuffer_type) { + is31fl3741_framebuffer_obj_t *is31fb = &display_buses[i].is31fl3741; + + if (((size_t)is31fb->is31fl3741->i2c) < ((size_t)&display_buses) || + ((size_t)is31fb->is31fl3741->i2c) > ((size_t)&display_buses + CIRCUITPY_DISPLAY_LIMIT * sizeof(primary_display_bus_t))) { + is31fl3741_IS31FL3741_obj_t *original_is31 = is31fb->is31fl3741; + if (gc_ptr_on_heap(original_is31)) { + memcpy(&is31fb->inline_is31fl3741, original_is31, sizeof(is31fl3741_IS31FL3741_obj_t)); + is31fb->is31fl3741 = &is31fb->inline_is31fl3741; + // Mark the old IS31FL3741 object so it is considered deinit. + common_hal_is31fl3741_IS31FL3741_mark_deinit(original_is31); + } + + busio_i2c_obj_t *original_i2c = is31fb->is31fl3741->i2c; + if (gc_ptr_on_heap(original_i2c)) { + memcpy(&is31fb->is31fl3741->inline_i2c, original_i2c, sizeof(busio_i2c_obj_t)); + is31fb->is31fl3741->i2c = &is31fb->is31fl3741->inline_i2c; + // Mark the old i2c object so it is considered deinit. + common_hal_busio_i2c_mark_deinit(original_i2c); + } + } + + if (!any_display_uses_this_framebuffer(&is31fb->base)) { + common_hal_is31fl3741_framebuffer_deinit(is31fb); + } else { + common_hal_is31fl3741_framebuffer_set_paused(is31fb, true); + } + #endif + #if CIRCUITPY_SHARPDISPLAY + } else if (display_bus_type == &sharpdisplay_framebuffer_type) { + sharpdisplay_framebuffer_obj_t *sharp = &display_buses[i].sharpdisplay; + common_hal_sharpdisplay_framebuffer_reset(sharp); + #endif + #if CIRCUITPY_PICODVI + } else if (display_bus_type == &picodvi_framebuffer_type) { + picodvi_framebuffer_obj_t *vc = &display_buses[i].picodvi; + if (!any_display_uses_this_framebuffer(&vc->base)) { + common_hal_picodvi_framebuffer_deinit(vc); + } + #endif + #if CIRCUITPY_AURORA_EPAPER + } else if (display_bus_type == &aurora_framebuffer_type) { + aurora_epaper_framebuffer_obj_t *aurora = &display_buses[i].aurora_epaper; + if (gc_ptr_on_heap(aurora->bus)) { + common_hal_aurora_epaper_framebuffer_set_free_bus(aurora, false); + } + // Set to None, gets deinit'd up by display_base + display_buses[i].bus_base.type = &mp_type_NoneType; + #endif + #if CIRCUITPY_MIPIDSI + } else if (display_bus_type == &mipidsi_display_type) { + mipidsi_display_obj_t *display = &display_buses[i].mipidsi; + if (!any_display_uses_this_framebuffer(&display->base)) { + common_hal_mipidsi_display_deinit(display); + } + #endif + } else { + // Not an active display bus. + continue; + } + } + + for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) { + // Reset the displayed group. Only the first will get the terminal but + // that's ok. + mp_const_obj_t display_type = displays[i].display_base.type; + if (display_type == NULL || display_type == &mp_type_NoneType) { + continue; + #if CIRCUITPY_BUSDISPLAY + } else if (display_type == &busdisplay_busdisplay_type) { + reset_busdisplay(&displays[i].display); + #endif + #if CIRCUITPY_EPAPERDISPLAY + } else if (display_type == &epaperdisplay_epaperdisplay_type) { + epaperdisplay_epaperdisplay_obj_t *display = &displays[i].epaper_display; + epaperdisplay_epaperdisplay_reset(display); + #endif + #if CIRCUITPY_FRAMEBUFFERIO + } else if (display_type == &framebufferio_framebufferdisplay_type) { + framebufferio_framebufferdisplay_reset(&displays[i].framebuffer_display); + #endif + #if CIRCUITPY_ZEPHYR_DISPLAY + } else if (display_type == &zephyr_display_display_type) { + zephyr_display_display_reset(&displays[i].zephyr_display); + #endif + } + } +} + +void displayio_display_slots_gc_collect(void) { + for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) { + mp_const_obj_t display_bus_type = display_buses[i].bus_base.type; + if (display_bus_type == NULL || display_bus_type == &mp_type_NoneType) { + continue; + } + #if CIRCUITPY_RGBMATRIX + if (display_bus_type == &rgbmatrix_RGBMatrix_type) { + rgbmatrix_rgbmatrix_collect_ptrs(&display_buses[i].rgbmatrix); + } + #endif + #if CIRCUITPY_IS31FL3741 + if (display_bus_type == &is31fl3741_framebuffer_type) { + is31fl3741_framebuffer_collect_ptrs(&display_buses[i].is31fl3741); + } + #endif + #if CIRCUITPY_SHARPDISPLAY + if (display_bus_type == &sharpdisplay_framebuffer_type) { + common_hal_sharpdisplay_framebuffer_collect_ptrs(&display_buses[i].sharpdisplay); + } + #endif + #if CIRCUITPY_AURORA_EPAPER + if (display_bus_type == &aurora_framebuffer_type) { + common_hal_aurora_epaper_framebuffer_collect_ptrs(&display_buses[i].aurora_epaper); + } + #endif + #if CIRCUITPY_PICODVI_AUDIOOUT + if (display_bus_type == &picodvi_framebuffer_type) { + picodvi_audioout_collect_ptrs(&display_buses[i].picodvi); + } + #endif + } + + for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) { + mp_const_obj_t display_type = displays[i].display_base.type; + if (display_type == NULL || display_type == &mp_type_NoneType) { + continue; + + // Alternatively, we could use gc_collect_root over the whole object, + // but this is more precise, and is the only field that needs marking. + #if CIRCUITPY_BUSDISPLAY + } else if (display_type == &busdisplay_busdisplay_type) { + busdisplay_busdisplay_collect_ptrs(&displays[i].display); + #endif + #if CIRCUITPY_FRAMEBUFFERIO + } else if (display_type == &framebufferio_framebufferdisplay_type) { + framebufferio_framebufferdisplay_collect_ptrs(&displays[i].framebuffer_display); + #endif + #if CIRCUITPY_EPAPERDISPLAY + } else if (display_type == &epaperdisplay_epaperdisplay_type) { + epaperdisplay_epaperdisplay_collect_ptrs(&displays[i].epaper_display); + #endif + #if CIRCUITPY_ZEPHYR_DISPLAY + } else if (display_type == &zephyr_display_display_type) { + zephyr_display_display_collect_ptrs(&displays[i].zephyr_display); + #endif + } + } +} + +#if !CIRCUITPY_DISPLAYIO_LVGL +void displayio_gc_collect(void) { + displayio_display_slots_gc_collect(); +} +#endif + +static bool is_display_active(mp_obj_base_t *display_maybe) { + return display_maybe->type != &mp_type_NoneType && display_maybe->type != NULL; +} + +primary_display_t *allocate_display(void) { + for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) { + if (!is_display_active(&displays[i].display_base)) { + // Clear this memory so it is in a known state before init. + memset(&displays[i], 0, sizeof(displays[i])); + // Default to None so that it works as board.DISPLAY. + displays[i].display_base.type = &mp_type_NoneType; + return &displays[i]; + } + } + return NULL; +} + +primary_display_t *allocate_display_or_raise(void) { + primary_display_t *result = allocate_display(); + if (result) { + return result; + } + mp_raise_RuntimeError(MP_ERROR_TEXT("Too many displays")); +} + +primary_display_bus_t *allocate_display_bus(void) { + for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) { + mp_const_obj_t display_bus_type = display_buses[i].bus_base.type; + if (display_bus_type == NULL || display_bus_type == &mp_type_NoneType) { + // Clear this memory so it is in a known state before init. + memset(&display_buses[i], 0, sizeof(display_buses[i])); + display_buses[i].bus_base.type = &mp_type_NoneType; + return &display_buses[i]; + } + } + return NULL; +} + +primary_display_bus_t *allocate_display_bus_or_raise(void) { + primary_display_bus_t *result = allocate_display_bus(); + if (result) { + return result; + } + mp_raise_RuntimeError(MP_ERROR_TEXT("Too many display buses; deinit() unused displays")); +} + +mp_obj_t common_hal_displayio_get_primary_display(void) { + if (primary_display_number == -1 || primary_display_number >= CIRCUITPY_DISPLAY_LIMIT) { + return mp_const_none; + } + mp_obj_base_t *primary_display = &displays[primary_display_number].display_base; + if (is_display_active(primary_display)) { + return MP_OBJ_FROM_PTR(primary_display); + } + return mp_const_none; +} + +void common_hal_displayio_set_primary_display(mp_obj_t new_primary_display) { + if (new_primary_display == mp_const_none) { + primary_display_number = -1; + primary_display_set_by_user = false; + return; + } + for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) { + mp_obj_t display = MP_OBJ_FROM_PTR(&displays[i]); + if (!is_display_active(display)) { + continue; + } + // Python subclass instances hold the native display in subobj[0]. + mp_obj_t native = mp_obj_cast_to_native_base(new_primary_display, + MP_OBJ_FROM_PTR(displays[i].display_base.type)); + if (native == display) { + primary_display_number = i; + primary_display_set_by_user = true; + return; + } + } + // object was not a display after all... + mp_raise_TypeError_varg(MP_ERROR_TEXT("%q must be of type %q or %q, not %q"), MP_QSTR_Display, MP_QSTR_AnyDisplay, MP_QSTR_None, mp_obj_get_type(new_primary_display)->name); +} + +bool common_hal_displayio_primary_display_set_by_user(void) { + return primary_display_set_by_user; +} + +void common_hal_displayio_auto_primary_display(void) { + if (primary_display_number != -1) { + return; + } + for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) { + if (is_display_active(&displays[i].display_base)) { + primary_display_number = i; + return; + } + } +} diff --git a/shared-module/displayio/legacy/__init__.h b/shared-module/displayio/legacy/__init__.h new file mode 100644 index 00000000000..5be85a66e3c --- /dev/null +++ b/shared-module/displayio/legacy/__init__.h @@ -0,0 +1,130 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#if CIRCUITPY_BUSDISPLAY +#include "shared-bindings/busdisplay/BusDisplay.h" +#endif +#if CIRCUITPY_AURORA_EPAPER +#include "shared-module/aurora_epaper/aurora_framebuffer.h" +#endif +#include "shared-bindings/displayio/Group.h" +#if CIRCUITPY_EPAPERDISPLAY +#include "shared-bindings/epaperdisplay/EPaperDisplay.h" +#endif +#if CIRCUITPY_FRAMEBUFFERIO +#include "shared-bindings/framebufferio/FramebufferDisplay.h" +#endif +#if CIRCUITPY_FOURWIRE +#include "shared-bindings/fourwire/FourWire.h" +#endif +#if CIRCUITPY_I2CDISPLAYBUS +#include "shared-bindings/i2cdisplaybus/I2CDisplayBus.h" +#endif +#if CIRCUITPY_PARALLELDISPLAYBUS +#include "shared-bindings/paralleldisplaybus/ParallelBus.h" +#endif +#if CIRCUITPY_RGBMATRIX +#include "shared-bindings/rgbmatrix/RGBMatrix.h" +#endif +#if CIRCUITPY_IS31FL3741 +#include "shared-bindings/is31fl3741/FrameBuffer.h" +#endif +#if CIRCUITPY_SHARPDISPLAY +#include "shared-module/sharpdisplay/SharpMemoryFramebuffer.h" +#endif +#if CIRCUITPY_DOTCLOCKFRAMEBUFFER +#include "common-hal/dotclockframebuffer/DotClockFramebuffer.h" +#endif +#if CIRCUITPY_MIPIDSI +#include "shared-bindings/mipidsi/Display.h" +#endif +#if CIRCUITPY_QSPIBUS +#include "shared-bindings/qspibus/QSPIBus.h" +#endif +#if CIRCUITPY_ZEPHYR_DISPLAY +#include "bindings/zephyr_display/Display.h" +#endif +// Port unique frame buffers. +#if CIRCUITPY_PICODVI +#include "bindings/picodvi/Framebuffer.h" +#endif + +#pragma once + +typedef struct { + union { + mp_obj_base_t bus_base; + #if CIRCUITPY_FOURWIRE + fourwire_fourwire_obj_t fourwire_bus; + #endif + #if CIRCUITPY_I2CDISPLAYBUS + i2cdisplaybus_i2cdisplaybus_obj_t i2cdisplay_bus; + #endif + #if CIRCUITPY_PARALLELDISPLAYBUS + paralleldisplaybus_parallelbus_obj_t parallel_bus; + #endif + #if CIRCUITPY_RGBMATRIX + rgbmatrix_rgbmatrix_obj_t rgbmatrix; + #endif + #if CIRCUITPY_IS31FL3741 + is31fl3741_framebuffer_obj_t is31fl3741; + #endif + #if CIRCUITPY_SHARPDISPLAY + sharpdisplay_framebuffer_obj_t sharpdisplay; + #endif + #if CIRCUITPY_PICODVI + picodvi_framebuffer_obj_t picodvi; + #endif + #if CIRCUITPY_DOTCLOCKFRAMEBUFFER + dotclockframebuffer_framebuffer_obj_t dotclock; + #endif + #if CIRCUITPY_AURORA_EPAPER + aurora_epaper_framebuffer_obj_t aurora_epaper; + #endif + #if CIRCUITPY_MIPIDSI + mipidsi_display_obj_t mipidsi; + #endif + #if CIRCUITPY_QSPIBUS + qspibus_qspibus_obj_t qspi_bus; + #endif + }; +} primary_display_bus_t; + +typedef struct { + union { + mp_obj_base_t display_base; + #if CIRCUITPY_BUSDISPLAY + busdisplay_busdisplay_obj_t display; + #endif + #if CIRCUITPY_EPAPERDISPLAY + epaperdisplay_epaperdisplay_obj_t epaper_display; + #endif + #if CIRCUITPY_FRAMEBUFFERIO + framebufferio_framebufferdisplay_obj_t framebuffer_display; + #endif + #if CIRCUITPY_ZEPHYR_DISPLAY + zephyr_display_display_obj_t zephyr_display; + #endif + }; +} primary_display_t; + +extern displayio_group_t circuitpython_splash; + +void displayio_background(void); +void reset_displays(void); +void displayio_gc_collect(void); + +// The legacy display slot registry is also used by the LVGL compositor so that +// displayio.release_displays() can find and release displays. +// Release every slot except keep_index (pass -1 for all). +void displayio_release_displays_slots(int keep_index); +// Root the GC objects referenced by displays in the slot registry. +void displayio_display_slots_gc_collect(void); + +primary_display_t *allocate_display(void); +primary_display_t *allocate_display_or_raise(void); +primary_display_bus_t *allocate_display_bus(void); +primary_display_bus_t *allocate_display_bus_or_raise(void); diff --git a/shared-module/displayio/legacy/display_core_scanline.c b/shared-module/displayio/legacy/display_core_scanline.c new file mode 100644 index 00000000000..46a00fe9592 --- /dev/null +++ b/shared-module/displayio/legacy/display_core_scanline.c @@ -0,0 +1,47 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// Scanline (legacy) compositor helpers that display the group tree. Defined here +// instead of in ../display_core.c so that display-side modules such as busdisplay, +// epaperdisplay and framebufferio implement them on top of the legacy compositor +// while LVGL-backed builds do not carry the scanline rendering machinery at all. + +#include "shared-module/displayio/display_core.h" + +bool displayio_display_core_fill_area(displayio_display_core_t *self, displayio_area_t *area, uint32_t *mask, uint32_t *buffer) { + if (self->current_group != NULL) { + return displayio_group_fill_area(self->current_group, &self->colorspace, area, mask, buffer); + } + return false; +} + +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; + } + // Expand the area if we have multiple pixels per byte and we need to byte + // align the bounds. + if (self->colorspace.depth < 8) { + uint8_t pixels_per_byte = 8 / self->colorspace.depth * self->colorspace.bytes_per_cell; + if (self->colorspace.pixels_in_byte_share_row) { + if (clipped->x1 % pixels_per_byte != 0) { + clipped->x1 -= clipped->x1 % pixels_per_byte; + } + if (clipped->x2 % pixels_per_byte != 0) { + clipped->x2 += pixels_per_byte - clipped->x2 % pixels_per_byte; + } + } else { + if (clipped->y1 % pixels_per_byte != 0) { + clipped->y1 -= clipped->y1 % pixels_per_byte; + } + if (clipped->y2 % pixels_per_byte != 0) { + clipped->y2 += pixels_per_byte - clipped->y2 % pixels_per_byte; + } + } + } + return true; +} diff --git a/shared-module/displayio/lvgl/Bitmap.c b/shared-module/displayio/lvgl/Bitmap.c new file mode 100644 index 00000000000..21f3ef12448 --- /dev/null +++ b/shared-module/displayio/lvgl/Bitmap.c @@ -0,0 +1,228 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/displayio/Bitmap.h" + +#include + +#include "py/runtime.h" +#include "py/gc.h" +#include "shared-module/displayio/lvgl/lvgl_internal.h" + +#if CIRCUITPY_ESPIDF +#include "esp_log.h" +static const char *TAG = "CP"; +#endif + +enum { ALIGN_BITS = 8 * sizeof(uint32_t) }; + +static int stride(uint32_t width, uint32_t bits_per_value) { + uint32_t row_width = width * bits_per_value; + // align to uint32_t + return (row_width + ALIGN_BITS - 1) / ALIGN_BITS; +} + +void common_hal_displayio_bitmap_construct(displayio_bitmap_t *self, uint32_t width, + uint32_t height, uint32_t bits_per_value) { + common_hal_displayio_bitmap_construct_from_buffer(self, width, height, bits_per_value, NULL, false); +} + +void common_hal_displayio_bitmap_construct_from_buffer(displayio_bitmap_t *self, uint32_t width, + uint32_t height, uint32_t bits_per_value, uint32_t *data, bool read_only) { + if (bits_per_value > 8 && bits_per_value != 16 && bits_per_value != 32) { + mp_raise_NotImplementedError(MP_ERROR_TEXT("Invalid bits per value")); + } + + self->width = width; + self->height = height; + self->stride = stride(width, bits_per_value); + self->data_alloc = false; + if (!data) { + size_t allocation_size = self->stride * height * sizeof(uint32_t); + #if CIRCUITPY_ESPIDF + ESP_LOGI(TAG, "Allocating data for %ux%u bitmap of size %zu", self->stride, height, allocation_size); + #endif + data = m_malloc_without_collect(allocation_size); + self->data_alloc = true; + } + self->data = data; + self->read_only = read_only; + self->bits_per_value = bits_per_value; + self->lv_watch_head = NULL; + + // Division and modulus can be slow because it has to handle any integer. We know bits_per_value + // is a power of two. We divide and mod by bits_per_value to compute the offset into the byte + // array. So, we can the offset computation to simplify to a shift for division and mask for mod. + + 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 < 8 / bits_per_value) { + self->x_shift++; + power_of_two <<= 1; + } + self->x_mask = (1u << self->x_shift) - 1u; // Used as a modulus on the x value + self->bitmask = (1u << bits_per_value) - 1u; + +} + +void common_hal_displayio_bitmap_deinit(displayio_bitmap_t *self) { + // Stop every mirror and cached decode from sampling the storage before freeing it. + // The render task must not run between clearing the descriptors and freeing the pixels. + displayio_lvgl_lock(); + uint32_t *data = self->data; + self->data = NULL; + displayio_lvgl_tilegrid_bitmap_changed(self, 0, 0, self->width, self->height); + if (self->data_alloc && data != NULL) { + gc_free(data); + } + displayio_lvgl_unlock(); +} + +bool common_hal_displayio_bitmap_deinited(displayio_bitmap_t *self) { + return self->data == NULL; +} + +uint16_t common_hal_displayio_bitmap_get_height(displayio_bitmap_t *self) { + return self->height; +} + +uint16_t common_hal_displayio_bitmap_get_width(displayio_bitmap_t *self) { + return self->width; +} + +uint32_t common_hal_displayio_bitmap_get_bits_per_value(displayio_bitmap_t *self) { + return self->bits_per_value; +} + +uint32_t common_hal_displayio_bitmap_get_pixel(displayio_bitmap_t *self, int16_t x, int16_t y) { + if (x >= self->width || x < 0 || y >= self->height || y < 0) { + return 0; + } + int32_t row_start = y * self->stride; + uint32_t *row = self->data + row_start; + uint8_t bytes_per_value = self->bits_per_value >> 3; + if (bytes_per_value == 0) { + // values_per_byte is a power of two, and x_shift is its log2. + uint8_t values_per_byte = 1 << self->x_shift; + uint8_t bits = ((uint8_t *)row)[x >> self->x_shift]; + uint8_t bit_position = (values_per_byte - (x & self->x_mask) - 1) * self->bits_per_value; + return (bits >> bit_position) & self->bitmask; + } else { + if (bytes_per_value == 1) { + return ((uint8_t *)row)[x]; + } else if (bytes_per_value == 2) { + return ((uint16_t *)row)[x]; + } else if (bytes_per_value == 4) { + return ((uint32_t *)row)[x]; + } + } + return 0; +} + +void displayio_bitmap_set_dirty(displayio_bitmap_t *self, int16_t x1, int16_t y1, int16_t x2, int16_t y2) { + // Nothing draws this bitmap, so no mirror needs to know. This is the common case while a + // shape is being rasterized into a fresh Bitmap: avoid the LVGL lock and mirror walk. + if (self->data == NULL || self->lv_watch_head == NULL) { + return; + } + displayio_lvgl_tilegrid_bitmap_changed(self, x1, y1, x2, y2); +} + +void displayio_bitmap_set_dirty_area(displayio_bitmap_t *self, const displayio_area_t *area) { + displayio_bitmap_set_dirty(self, area->x1, area->y1, area->x2, area->y2); +} + +// Store one pixel. The caller has already checked read_only, bounds and data. +static void _write_pixel_unchecked(displayio_bitmap_t *self, int16_t x, int16_t y, uint32_t value) { + int32_t row_start = y * self->stride; + uint32_t *row = self->data + row_start; + uint8_t bytes_per_value = self->bits_per_value >> 3; + if (bytes_per_value == 0) { + // values_per_byte is a power of two, and x_shift is its log2. + uint8_t values_per_byte = 1 << self->x_shift; + uint8_t bits = ((uint8_t *)row)[x >> self->x_shift]; + uint8_t bit_position = (values_per_byte - (x & self->x_mask) - 1) * self->bits_per_value; + bits &= ~(self->bitmask << bit_position); + bits |= (value & self->bitmask) << bit_position; + ((uint8_t *)row)[x >> self->x_shift] = bits; + } else { + if (bytes_per_value == 1) { + ((uint8_t *)row)[x] = value; + } else if (bytes_per_value == 2) { + ((uint16_t *)row)[x] = value; + } else if (bytes_per_value == 4) { + ((uint32_t *)row)[x] = value; + } + } +} + +void displayio_bitmap_write_pixel(displayio_bitmap_t *self, int16_t x, int16_t y, uint32_t value) { + if (self->read_only) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Read-only")); + } + // Writes the color index value into a pixel position + // Must update the dirty area separately + + // Don't write if out of area + if (0 > x || x >= self->width || 0 > y || y >= self->height) { + return; + } + + _write_pixel_unchecked(self, x, y, value); +} + +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(MP_ERROR_TEXT("Read-only")); + } + // An out of bounds write changes nothing, so don't dirty the display for it. The Python + // binding raises first; C callers may write clipped shapes. + if (0 > x || x >= self->width || 0 > y || y >= self->height || self->data == NULL) { + return; + } + _write_pixel_unchecked(self, x, y, value); + // Mark after writing: the render task can draw at any time, and the area it consumes must + // already hold the new pixels. + displayio_bitmap_set_dirty(self, x, y, x + 1, y + 1); +} + +void common_hal_displayio_bitmap_fill(displayio_bitmap_t *self, uint32_t value) { + if (self->read_only) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Read-only")); + } + // 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)); + } + // copy it in + for (uint32_t i = 0; i < self->stride * self->height; i++) { + self->data[i] = word; + } + // Mark after writing, so a render that starts during the fill can't consume the change. + displayio_bitmap_set_dirty(self, 0, 0, self->width, self->height); +} + +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(uint32_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/lvgl/Bitmap.h b/shared-module/displayio/lvgl/Bitmap.h new file mode 100644 index 00000000000..3ecbc725277 --- /dev/null +++ b/shared-module/displayio/lvgl/Bitmap.h @@ -0,0 +1,51 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include + +#include "py/obj.h" +#include "shared-module/displayio/area.h" + +// LVGL-based version of displayio Bitmap. Same pixel storage as the legacy version (rows +// packed into uint32_t words, sub-byte values MSB-first). +// +// Deliberately no LVGL state: a TileGrid composes the tiles it shows into its own buffer, and +// reads this Bitmap's pixels (through its Palette) while doing it. So a Bitmap never owns an +// image or a palette copy; a write only has to tell the TileGrids showing it which pixels +// changed. Those grids are kept on lv_watch_head, so the write path never walks the global +// mirror list and skips LVGL entirely when nothing is showing this Bitmap. + +// Forward declaration: the attached TileGrids that draw this bitmap form a list through +// their lv_bitmap_next pointer. +struct displayio_tilegrid; + +typedef struct { + mp_obj_base_t base; + uint16_t width; + uint16_t height; + uint32_t *data; + uint16_t stride; // uint32_t's + uint8_t bits_per_value; + uint8_t x_shift; + size_t x_mask; + uint16_t bitmask; + bool read_only; + bool data_alloc; // did bitmap allocate data or someone else + // Attached TileGrids drawing this bitmap. Empty means a pixel write has nothing to + // notify, so it can skip the LVGL lock and the mirror walk entirely. + struct displayio_tilegrid *lv_watch_head; +} displayio_bitmap_t; + +void displayio_bitmap_write_pixel(displayio_bitmap_t *self, int16_t x, int16_t y, uint32_t value); +// Higher-level dirty notification. The rectangular region is in bitmap pixel coordinates. The +// TileGrids drawing this bitmap note the region and re-read it before the next refresh, since +// writers mark the area *before* they change the pixels. +void displayio_bitmap_set_dirty(displayio_bitmap_t *self, int16_t x1, int16_t y1, int16_t x2, int16_t y2); +// Compatibility for callers that still pass an area, such as bitmaptools. +void displayio_bitmap_set_dirty_area(displayio_bitmap_t *self, const displayio_area_t *area); diff --git a/shared-module/displayio/lvgl/ColorConverter.c b/shared-module/displayio/lvgl/ColorConverter.c new file mode 100644 index 00000000000..d4e64ee286e --- /dev/null +++ b/shared-module/displayio/lvgl/ColorConverter.c @@ -0,0 +1,411 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/displayio/ColorConverter.h" + +#include "py/misc.h" +#include "py/runtime.h" + +#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_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, displayio_colorspace_t input_colorspace) { + self->dither = dither; + self->transparent_color = NO_TRANSPARENT_COLOR; + self->input_colorspace = input_colorspace; + self->output_colorspace.depth = 16; +} + +uint16_t displayio_colorconverter_compute_rgb565(uint32_t color_rgb888) { + uint32_t r5 = (color_rgb888 >> 19); + uint32_t g6 = (color_rgb888 >> 10) & 0x3f; + uint32_t b5 = (color_rgb888 >> 3) & 0x1f; + return r5 << 11 | g6 << 5 | b5; +} + +uint8_t displayio_colorconverter_compute_rgb332(uint32_t color_rgb888) { + uint32_t r3 = (color_rgb888 >> 21); + uint32_t g3 = (color_rgb888 >> 13) & 0x7; + uint32_t b2 = (color_rgb888 >> 6) & 0x3; + return r3 << 5 | g3 << 2 | b2; +} + +uint8_t displayio_colorconverter_compute_rgbd(uint32_t color_rgb888) { + uint32_t r1 = (color_rgb888 >> 23) & 0x1; + uint32_t g1 = (color_rgb888 >> 15) & 0x1; + uint32_t b1 = (color_rgb888 >> 7) & 0x1; + return r1 << 3 | g1 << 2 | b1 << 1 /* | dummy */; +} + +uint8_t displayio_colorconverter_compute_luma(uint32_t color_rgb888) { + uint32_t r8 = (color_rgb888 >> 16); + uint32_t g8 = (color_rgb888 >> 8) & 0xff; + uint32_t b8 = color_rgb888 & 0xff; + return (r8 * 19 + g8 * 182 + b8 * 54) / 255; +} + +uint8_t displayio_colorconverter_compute_chroma(uint32_t color_rgb888) { + uint32_t r8 = (color_rgb888 >> 16); + uint32_t g8 = (color_rgb888 >> 8) & 0xff; + uint32_t b8 = color_rgb888 & 0xff; + uint8_t max = MAX(r8, MAX(g8, b8)); + uint8_t min = MIN(r8, MIN(g8, b8)); + return max - min; +} + +uint8_t displayio_colorconverter_compute_hue(uint32_t color_rgb888) { + uint32_t r8 = (color_rgb888 >> 16); + uint32_t g8 = (color_rgb888 >> 8) & 0xff; + uint32_t b8 = color_rgb888 & 0xff; + uint8_t max = MAX(r8, MAX(g8, b8)); + uint8_t min = MIN(r8, MIN(g8, b8)); + uint8_t c = max - min; + if (c == 0) { + return 0; + } + + int32_t hue = 0; + if (max == r8) { + hue = (((int32_t)(g8 - b8) * 40) / c) % 240; + } else if (max == g8) { + hue = (((int32_t)(b8 - r8) + (2 * c)) * 40) / c; + } else if (max == b8) { + hue = (((int32_t)(r8 - g8) + (4 * c)) * 40) / c; + } + if (hue < 0) { + hue += 240; + } + + return hue; +} + +uint8_t displayio_colorconverter_compute_sixcolor(uint32_t color_rgb888) { + // This is DDX=1, the default for the displays. + uint8_t chroma = displayio_colorconverter_compute_chroma(color_rgb888); + if (chroma >= 64) { + uint8_t hue = displayio_colorconverter_compute_hue(color_rgb888); + // Red 0 + if (hue < 10) { + return 0x3; + } + // Yellow 42 + if (hue < 42 + 21) { + return 0x2; + } + // Green 85 + if (hue < 85 + 42) { + return 0x6; + } + // Blue 170 + if (hue < 170 + 42) { + return 0x5; + } + + // The rest is red to 255 + return 0x3; + } else { + uint8_t luma = displayio_colorconverter_compute_luma(color_rgb888); + if (luma >= 128) { + return 0x1; // White + } else { + return 0x0; // Black + } + } +} + +uint8_t displayio_colorconverter_compute_sevencolor(uint32_t color_rgb888) { + // This is DDX=1, the default for the displays. + uint8_t chroma = displayio_colorconverter_compute_chroma(color_rgb888); + if (chroma >= 64) { + uint8_t hue = displayio_colorconverter_compute_hue(color_rgb888); + // Red 0 + if (hue < 10) { + return 0x4; + } + // Orange 21 + if (hue < 21 + 10) { + return 0x6; + } + // Yellow 42 + if (hue < 42 + 21) { + return 0x5; + } + // Green 85 + if (hue < 85 + 42) { + return 0x2; + } + // Blue 170 + if (hue < 170 + 42) { + return 0x3; + } + + // The rest is red to 255 + return 0x4; + } else { + uint8_t luma = displayio_colorconverter_compute_luma(color_rgb888); + if (luma >= 128) { + return 0x1; // White + } else { + return 0x0; // Black + } + } +} + +void displayio_colorconverter_compute_tricolor(const _displayio_colorspace_t *colorspace, uint8_t pixel_chroma, uint8_t pixel_hue, uint32_t *color) { + if (pixel_chroma <= 16) { + if (!colorspace->grayscale) { + *color = 0; + } + return; + } + int16_t hue_diff = colorspace->tricolor_hue - pixel_hue; + if ((-10 <= hue_diff && hue_diff <= 10) || hue_diff <= -220 || hue_diff >= 220) { + if (colorspace->grayscale) { + *color = 0; + } else { + *color = 1; + } + } else if (!colorspace->grayscale) { + *color = 0; + } +} + +void displayio_colorconverter_compute_fourcolor(const _displayio_colorspace_t *colorspace, uint8_t pixel_chroma, uint8_t pixel_hue, uint32_t *color) { + *color >>= 1; + if (pixel_chroma <= 16) { + return; + } + int16_t hue_diff = colorspace->tricolor_hue - pixel_hue; + if ((-10 <= hue_diff && hue_diff <= 10) || hue_diff <= -220 || hue_diff >= 220) { + *color = 2; + } + int16_t hue_diff2 = colorspace->fourcolor_hue - pixel_hue; + if ((-10 <= hue_diff2 && hue_diff2 <= 10) || hue_diff2 <= -220 || hue_diff2 >= 220) { + *color = 3; + } +} + +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; + + displayio_output_pixel_t output_pixel; + output_pixel.pixel = 0; + output_pixel.opaque = false; + + displayio_colorconverter_convert(self, colorspace, &input_pixel, &output_pixel); + + (*output_color) = output_pixel.pixel; +} + +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) { + return self->dither; +} + +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(MP_ERROR_TEXT("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; + // NO_TRANSPARENT_COLOR will never equal a valid color + self->transparent_color = NO_TRANSPARENT_COLOR; +} + + +// Convert a single input pixel to RGB888 +uint32_t displayio_colorconverter_convert_pixel(displayio_colorspace_t colorspace, uint32_t pixel) { + switch (colorspace) { + case DISPLAYIO_COLORSPACE_RGB565_SWAPPED: + pixel = __builtin_bswap16(pixel); + MP_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); + MP_FALLTHROUGH; + case DISPLAYIO_COLORSPACE_RGB555: { + uint32_t r8 = (pixel >> 10) & 0x1f; + uint32_t g8 = (pixel >> 5) & 0x1f; + uint32_t b8 = pixel & 0x1f; + r8 = (r8 << 3) | ((r8 >> 2) & 0b111); + g8 = (g8 << 3) | ((g8 >> 2) & 0b111); + b8 = (b8 << 3) | ((b8 >> 2) & 0b111); + pixel = (r8 << 16) | (g8 << 8) | b8; + } + break; + + case DISPLAYIO_COLORSPACE_BGR565_SWAPPED: + pixel = __builtin_bswap16(pixel); + MP_FALLTHROUGH; + case DISPLAYIO_COLORSPACE_BGR565: { + uint32_t b8 = (pixel >> 11) << 3; + uint32_t g8 = ((pixel >> 5) << 2) & 0xff; + uint32_t r8 = (pixel << 3) & 0xff; + pixel = (r8 << 16) | (g8 << 8) | b8; + } + break; + + case DISPLAYIO_COLORSPACE_BGR555_SWAPPED: + pixel = __builtin_bswap16(pixel); + MP_FALLTHROUGH; + case DISPLAYIO_COLORSPACE_BGR555: { + uint32_t b8 = (pixel >> 10) & 0x1f; + uint32_t g8 = (pixel >> 5) & 0x1f; + uint32_t r8 = pixel & 0x1f; + r8 = (r8 << 3) | ((r8 >> 2) & 0b111); + g8 = (g8 << 3) | ((g8 >> 2) & 0b111); + b8 = (b8 << 3) | ((b8 >> 2) & 0b111); + pixel = (r8 << 16) | (g8 << 8) | b8; + } + break; + + default: + case DISPLAYIO_COLORSPACE_RGB888: + break; + + case DISPLAYIO_COLORSPACE_L8: { + uint32_t l8 = pixel & 0xff; + pixel = l8 * 0x010101; + } + break; + } + + return pixel; +} + +void displayio_convert_color(const _displayio_colorspace_t *colorspace, bool dither, const displayio_input_pixel_t *input_pixel, displayio_output_pixel_t *output_color) { + uint32_t pixel = input_pixel->pixel; + if (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)); + + 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)); + } else { + int bitmask = 0xFF >> colorspace->depth; + b8 = MIN(255, b8 + (randb & bitmask)); + r8 = MIN(255, r8 + (randr & bitmask)); + g8 = MIN(255, g8 + (randg & bitmask)); + } + pixel = r8 << 16 | g8 << 8 | b8; + } + + if (colorspace->depth == 16) { + uint16_t packed = displayio_colorconverter_compute_rgb565(pixel); + if (colorspace->reverse_bytes_in_word) { + // swap bytes + packed = __builtin_bswap16(packed); + } + output_color->pixel = packed; + output_color->opaque = true; + return; + } else if (colorspace->tricolor || colorspace->fourcolor) { + uint8_t luma = displayio_colorconverter_compute_luma(pixel); + uint8_t pixel_chroma = displayio_colorconverter_compute_chroma(pixel); + output_color->pixel = luma >> (8 - colorspace->depth); + uint8_t pixel_hue = displayio_colorconverter_compute_hue(pixel); + if (colorspace->tricolor) { + displayio_colorconverter_compute_tricolor(colorspace, pixel_chroma, pixel_hue, &output_color->pixel); + } else if (colorspace->fourcolor) { + displayio_colorconverter_compute_fourcolor(colorspace, pixel_chroma, pixel_hue, &output_color->pixel); + } + output_color->opaque = true; + return; + } 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; + output_color->opaque = true; + return; + } else if (colorspace->depth == 32 || colorspace->depth == 24) { + output_color->pixel = pixel; + output_color->opaque = true; + return; + } else if (colorspace->depth == 8 && !colorspace->grayscale) { + uint8_t packed = displayio_colorconverter_compute_rgb332(pixel); + output_color->pixel = packed; + output_color->opaque = true; + return; + } else if (colorspace->depth == 4) { + uint8_t packed; + if (colorspace->sixcolor) { + packed = displayio_colorconverter_compute_sixcolor(pixel); + } else if (colorspace->sevencolor) { + packed = displayio_colorconverter_compute_sevencolor(pixel); + } else { + packed = displayio_colorconverter_compute_rgbd(pixel); + } + output_color->pixel = packed; + output_color->opaque = true; + return; + } + output_color->opaque = false; +} + +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) { + output_color->opaque = false; + return; + } + + if (!self->dither && self->cached_colorspace == colorspace && self->cached_input_pixel == input_pixel->pixel) { + output_color->pixel = self->cached_output_color; + return; + } + + displayio_input_pixel_t rgb888_pixel = *input_pixel; + rgb888_pixel.pixel = displayio_colorconverter_convert_pixel(self->input_colorspace, input_pixel->pixel); + displayio_convert_color(colorspace, self->dither, &rgb888_pixel, output_color); + + if (!self->dither) { + self->cached_colorspace = colorspace; + self->cached_input_pixel = input_pixel->pixel; + self->cached_output_color = output_color->pixel; + } +} + + + +// Currently no refresh logic is needed for a ColorConverter. +bool displayio_colorconverter_needs_refresh(displayio_colorconverter_t *self) { + return false; +} + +void displayio_colorconverter_finish_refresh(displayio_colorconverter_t *self) { +} diff --git a/shared-module/displayio/lvgl/Group.c b/shared-module/displayio/lvgl/Group.c new file mode 100644 index 00000000000..28a4f25dc99 --- /dev/null +++ b/shared-module/displayio/lvgl/Group.c @@ -0,0 +1,731 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// LVGL-based displayio Group implementation. Each Group is mirrored into a plain lv_obj +// container; members are appended as children so the lv object tree's child order matches +// the displayio z-order (later members draw on top). Group scale is applied by scaling +// child positions and images directly. That keeps displayio's nearest-neighbor +// scaling and per-child invalidation; LVGL transform styles use an ARGB8888 transform +// layer and bilinear filtering instead. +// +// The compositor pushes every state change into the LVGL mirror synchronously, under the +// port's LVGL lock: LVGL itself renders on an RTOS thread (e.g. a Zephyr workqueue), and +// this keeps tree mutation off the render thread. + +#include "shared-bindings/displayio/Group.h" + +#include +#include + +#include "py/gc.h" +#include "py/objtype.h" +#include "py/runtime.h" +#include "py/objlist.h" +#include "shared-bindings/displayio/TileGrid.h" +#include "shared-bindings/displayio/__init__.h" +#include "shared-module/displayio/__init__.h" +#include "shared-module/displayio/lvgl/lvgl_internal.h" +#include "shared-module/displayio/lvgl/lvgl_protocol.h" + +#if CIRCUITPY_VIDEOCORE +#include "shared-module/videocore/VideoBuffer.h" +#endif + +#if CIRCUITPY_DISPLAYIO_LVGL + +// Resolve a member's protocol and, in place, the object it implements the protocol on. Layers +// mirror themselves into the LVGL tree through protocol_lvgl, so nothing here has to know a +// member's type. See lvgl_protocol.h. +static const lvgl_protocol_t *_layer_protocol(mp_obj_t *layer) { + const lvgl_protocol_t *protocol = mp_proto_get(MP_QSTR_protocol_lvgl, *layer); + if (protocol != NULL && protocol->protocol_self != NULL) { + *layer = protocol->protocol_self(*layer); + protocol = mp_proto_get(MP_QSTR_protocol_lvgl, *layer); + } + return protocol; +} + +static displayio_group_t *cp_lvgl_root_group = NULL; +static bool cp_lvgl_inited = false; +bool displayio_lvgl_refresh_yield = false; + +// The port lock is recursive. Keeping the recursion at the port instead of counting here matters +// once LVGL renders on its own task: a shared depth counter would let the render task believe it +// owns a lock that the CircuitPython task is holding. +void displayio_lvgl_lock(void) { + displayio_lvgl_port_lock(); +} + +void displayio_lvgl_unlock(void) { + displayio_lvgl_port_unlock(); +} + +static void _unlock_on_exception(void *ctx) { + (void)ctx; + displayio_lvgl_unlock(); +} + +void displayio_lvgl_lock_with_cleanup(nlr_jump_callback_node_t *cleanup) { + displayio_lvgl_lock(); + nlr_push_jump_callback(cleanup, _unlock_on_exception); +} + +void displayio_lvgl_unlock_with_cleanup(void) { + nlr_pop_jump_callback(true); +} + +// Groups are mirrored as transparent, screen sized LVGL objects at the screen origin and +// their members are positioned in screen coordinates (lv_abs_x/y is the group's origin on +// the screen). A group's LVGL object never moves or resizes, so moving a member only +// redraws the member's old and new area. (A group sized to its content would be redrawn +// from its origin to its farthest member whenever a member moves.) +// +static uint32_t _scale_to_q8(mp_float_t scale) { + // Keep the stored scale at or below the requested value. All Q8 steps are supported by + // LVGL's software renderer, so the closest one is the truncated fixed-point value. + return (uint32_t)(scale * LV_SCALE_NONE); +} + +static mp_float_t _validate_scale(mp_obj_t scale_obj) { + mp_float_t scale = mp_arg_validate_obj_float_range(scale_obj, 0, 32767, MP_QSTR_scale); + if (scale < (mp_float_t)1 / LV_SCALE_NONE) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("%q out of range"), MP_QSTR_scale); + } + return scale; +} + +// Recompute members' inherited scale and screen positions after this group's scale or +// position changed. Returns false when a member rejects the transform; some members may +// already have taken it then, so callers restore the group's own transform and push again. +static bool _update_children(displayio_group_t *self) { + uint32_t child_scale = displayio_lvgl_compose_scale(self->lv_scale, self->scale); + for (size_t i = 0; i < self->members->len; i++) { + mp_obj_t layer = self->members->items[i]; + const lvgl_protocol_t *protocol = _layer_protocol(&layer); + if (protocol == NULL || protocol->set_transform == NULL) { + continue; + } + if (!protocol->set_transform(layer, self->lv_abs_x, self->lv_abs_y, child_scale)) { + return false; + } + } + return true; +} + +static void check_readonly(displayio_group_t *self) { + if (self->readonly) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Read-only")); + } +} + +// Bitmap writers mark the dirty area before writing, and TileGrid writes only set bits, so the +// composed buffers are brought up to date here: at the start of a refresh, after the writes and +// before anything is drawn. The lock is held, and LVGL doesn't render while this runs. +static void refresh_start_cb(lv_event_t *e) { + (void)e; + // Take any video frames that landed since the last background tick, so a + // manual display.refresh() shows them too. + #if CIRCUITPY_VIDEOCORE + displayio_lvgl_video_background(); + #endif + displayio_lvgl_tilegrid_refresh_all(); +} + +void displayio_lvgl_register_display(lv_display_t *display) { + if (display == NULL) { + return; + } + displayio_lvgl_lock(); + // Match the legacy compositor, where undrawn pixels are zero (black). LVGL draws its bottom + // layer -- white, out of the box -- wherever nothing else covers an area, so the screen has to + // be opaque black. This belongs to each display rather than the one-time init: displays are + // deleted and re-created on every soft reload (and by the display classes themselves), and a + // screen without this style comes up white. + lv_obj_t *screen = lv_display_get_screen_active(display); + if (screen != NULL) { + lv_obj_set_style_bg_color(screen, lv_color_black(), 0); + lv_obj_set_style_bg_opa(screen, LV_OPA_COVER, 0); + lv_obj_clear_flag(screen, LV_OBJ_FLAG_SCROLLABLE); + } + lv_display_add_event_cb(display, refresh_start_cb, LV_EVENT_REFR_START, NULL); + displayio_lvgl_unlock(); +} + +// Whether any active display mirrored into LVGL still wants automatic repaints. The display slots +// are the shared registry (the same ones the legacy compositor uses), so this works for both +// display classes the compositor supports. +bool displayio_lvgl_auto_refresh(void) { + for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) { + mp_const_obj_t display_type = displays[i].display_base.type; + if (display_type == NULL || display_type == &mp_type_NoneType) { + continue; + } + #if CIRCUITPY_BUSDISPLAY + if (display_type == &busdisplay_busdisplay_type) { + if (displays[i].display.auto_refresh) { + return true; + } + continue; + } + #endif + #if CIRCUITPY_FRAMEBUFFERIO + if (display_type == &framebufferio_framebufferdisplay_type) { + if (displays[i].framebuffer_display.auto_refresh) { + return true; + } + continue; + } + #endif + } + // No display yet: pumping LVGL is harmless and keeps its own timers running. + return true; +} + +// Render the displays that can't run on the render task. The guard keeps the proxy from +// re-entering LVGL rendering if a background callback is processed while a refresh is already +// active on the CircuitPython thread, including an explicit display.refresh() that is running +// background tasks mid-render. +void displayio_lvgl_refresh_unsafe_displays(void) { + #if CIRCUITPY_BUSDISPLAY + static bool refreshing = false; + if (refreshing || displayio_lvgl_refresh_yield) { + return; + } + refreshing = true; + displayio_lvgl_lock(); + for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) { + mp_const_obj_t display_type = displays[i].display_base.type; + if (display_type != &busdisplay_busdisplay_type) { + continue; + } + busdisplay_busdisplay_obj_t *busdisplay = &displays[i].display; + if (busdisplay->auto_refresh && busdisplay->lv_display != NULL) { + lv_refr_now(busdisplay->lv_display); + } + } + displayio_lvgl_unlock(); + refreshing = false; + #endif +} + +// Render the framebuffer displays that pace themselves from a frame boundary. Like the BusDisplay +// proxy, this runs on the CircuitPython thread and takes the LVGL lock; a frame callback may be +// running on the render task at the same time, so the lock serializes them. +void displayio_lvgl_refresh_paced_displays(void) { + #if CIRCUITPY_FRAMEBUFFERIO + static bool refreshing = false; + // An explicit display.refresh() runs background tasks while it renders. A frame callback + // queued among them must not start a nested render; it draws at the next frame instead. + if (refreshing || displayio_lvgl_refresh_yield) { + return; + } + refreshing = true; + displayio_lvgl_lock(); + for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) { + mp_const_obj_t display_type = displays[i].display_base.type; + if (display_type != &framebufferio_framebufferdisplay_type) { + continue; + } + framebufferio_framebufferdisplay_obj_t *display = &displays[i].framebuffer_display; + if (display->lv_paced && display->auto_refresh && display->lv_display != NULL) { + lv_refr_now(display->lv_display); + } + } + displayio_lvgl_unlock(); + refreshing = false; + #endif +} + +void displayio_lvgl_init(void) { + if (cp_lvgl_inited) { + return; + } + displayio_lvgl_lock(); + // The OnDiskBitmap decoder has to be in place before any TileGrid attaches. Once a display + // exists the compositor is in use; until then leave this unset so the decoder is initialized + // by the display that does show up. + if (lv_screen_active() != NULL) { + displayio_lvgl_ondiskbitmap_decoder_init(); + cp_lvgl_inited = true; + } + displayio_lvgl_unlock(); +} + +void displayio_group_construct(displayio_group_t *self, mp_obj_list_t *members, mp_obj_t scale, mp_int_t x, mp_int_t y) { + self->x = x; + self->y = y; + self->members = members; + self->item_removed = false; + self->scale = _scale_to_q8(_validate_scale(scale)); + self->requested_scale = scale; + self->in_group = false; + self->readonly = false; + self->lv_obj = NULL; + self->lv_scale = LV_SCALE_NONE; + self->lv_abs_x = x; + self->lv_abs_y = y; +} + +void common_hal_displayio_group_construct(displayio_group_t *self, mp_obj_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) { + return self->hidden; +} + +// Update the mirror object for a group's effective visibility. +static void _update_lvgl_visible(displayio_group_t *self) { + if (self->lv_obj == NULL) { + return; + } + if (self->hidden || self->hidden_by_parent) { + lv_obj_add_flag(self->lv_obj, LV_OBJ_FLAG_HIDDEN); + } else { + lv_obj_clear_flag(self->lv_obj, LV_OBJ_FLAG_HIDDEN); + } +} + +static void _propagate_hidden(displayio_group_t *self, bool hidden) { + for (size_t i = 0; i < self->members->len; i++) { + mp_obj_t layer = self->members->items[i]; + const lvgl_protocol_t *protocol = _layer_protocol(&layer); + if (protocol != NULL && protocol->set_hidden_by_parent != NULL) { + protocol->set_hidden_by_parent(layer, hidden); + } + } +} + +void common_hal_displayio_group_set_hidden(displayio_group_t *self, bool hidden) { + if (self->hidden == hidden) { + return; + } + check_readonly(self); + self->hidden = hidden; + if (self->hidden_by_parent) { + return; + } + _propagate_hidden(self, hidden); + nlr_jump_callback_node_t cleanup; + displayio_lvgl_lock_with_cleanup(&cleanup); + _update_lvgl_visible(self); + displayio_lvgl_unlock_with_cleanup(); +} + +void displayio_group_set_hidden_by_parent(displayio_group_t *self, bool hidden) { + if (self->hidden_by_parent == hidden) { + return; + } + check_readonly(self); + self->hidden_by_parent = hidden; + if (self->hidden) { + return; + } + _propagate_hidden(self, hidden); + nlr_jump_callback_node_t cleanup; + displayio_lvgl_lock_with_cleanup(&cleanup); + _update_lvgl_visible(self); + displayio_lvgl_unlock_with_cleanup(); +} + +mp_obj_t common_hal_displayio_group_get_scale(displayio_group_t *self) { + return self->requested_scale; +} + +void common_hal_displayio_group_set_scale(displayio_group_t *self, mp_obj_t scale) { + mp_float_t scale_value = _validate_scale(scale); + if (self->requested_scale == scale) { + return; + } + check_readonly(self); + uint32_t scale_q8 = _scale_to_q8(scale_value); + if (self->scale == scale_q8) { + self->requested_scale = scale; + return; + } + if (self->lv_obj == NULL) { + self->scale = scale_q8; + self->requested_scale = scale; + return; + } + uint32_t previous_scale = self->scale; + mp_obj_t previous_requested_scale = self->requested_scale; + self->scale = scale_q8; + self->requested_scale = scale; + nlr_jump_callback_node_t cleanup; + displayio_lvgl_lock_with_cleanup(&cleanup); + bool accepted = _update_children(self); + if (!accepted) { + // A member can't be shown at this scale. Put the group back the way it was, push that + // to the members that already took the new scale, and report it. + self->scale = previous_scale; + self->requested_scale = previous_requested_scale; + _update_children(self); + } + displayio_lvgl_unlock_with_cleanup(); + if (!accepted) { + mp_raise_ValueError(MP_ERROR_TEXT("Layer does not support scaling")); + } +} + +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) { + if (self->x == x) { + return; + } + check_readonly(self); + // The origin is in screen pixels, so the move is scaled by the parent chain. + self->lv_abs_x += displayio_lvgl_scale_coordinate(x, self->lv_scale) - + displayio_lvgl_scale_coordinate(self->x, self->lv_scale); + self->x = x; + if (self->lv_obj != NULL) { + nlr_jump_callback_node_t cleanup; + displayio_lvgl_lock_with_cleanup(&cleanup); + // Every layer can be translated; only set_scale() can be rejected. + (void)_update_children(self); + displayio_lvgl_unlock_with_cleanup(); + } +} + +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) { + if (self->y == y) { + return; + } + check_readonly(self); + // The origin is in screen pixels, so the move is scaled by the parent chain. + self->lv_abs_y += displayio_lvgl_scale_coordinate(y, self->lv_scale) - + displayio_lvgl_scale_coordinate(self->y, self->lv_scale); + self->y = y; + if (self->lv_obj != NULL) { + nlr_jump_callback_node_t cleanup; + displayio_lvgl_lock_with_cleanup(&cleanup); + // Every layer can be translated; only set_scale() can be rejected. + (void)_update_children(self); + displayio_lvgl_unlock_with_cleanup(); + } +} + +// Resolve a group member to its mirror object, or NULL if it has none yet. +static lv_obj_t *_member_mirror(mp_obj_t layer) { + const lvgl_protocol_t *protocol = _layer_protocol(&layer); + return protocol == NULL ? NULL : protocol->root_obj(layer); +} + +// Create the mirror for a member that doesn't have one yet. Unsupported layers stay NULL. +static lv_obj_t *_attach_member(displayio_group_t *self, mp_obj_t layer) { + const lvgl_protocol_t *protocol = _layer_protocol(&layer); + if (protocol == NULL) { + return NULL; + } + protocol->attach(layer, self->lv_obj); + return protocol->root_obj(layer); +} + +// Adopt a member: validate that it can join, update Python-visible state, and push it into +// the mirror if the group is mirrored. +static void _adopt_member(displayio_group_t *self, mp_obj_t layer) { + const lvgl_protocol_t *protocol = _layer_protocol(&layer); + if (protocol == NULL || protocol->set_in_group == NULL) { + mp_raise_ValueError(MP_ERROR_TEXT("Layer must be a Group, TileGrid, vector shape or VideoBuffer")); + } + if (protocol->set_in_group(layer, true)) { + mp_raise_ValueError(MP_ERROR_TEXT("Layer already in a group")); + } + // Transform/visibility updates can raise too (for example when resuming video). + // A rejected adoption must not leave an otherwise unused layer marked in_group. + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + if (protocol->set_transform != NULL && + !protocol->set_transform(layer, self->lv_abs_x, self->lv_abs_y, + displayio_lvgl_compose_scale(self->lv_scale, self->scale))) { + mp_raise_ValueError(MP_ERROR_TEXT("Layer does not support scaling")); + } + if (protocol->set_hidden_by_parent != NULL) { + protocol->set_hidden_by_parent(layer, self->hidden || self->hidden_by_parent); + } + nlr_pop(); + } else { + protocol->set_in_group(layer, false); + nlr_jump(nlr.ret_val); + } +} + +// Release a member and remove its mirror. Must be called under the displayio lock. +static void _release_member(displayio_group_t *self, mp_obj_t layer) { + const lvgl_protocol_t *protocol = _layer_protocol(&layer); + if (protocol == NULL) { + return; + } + if (protocol->set_in_group != NULL) { + protocol->set_in_group(layer, false); + } + protocol->detach(layer); +} + +// Push the mirror children into the same order as the members list. Newly added members +// get mirrors here; children that no longer belong to a member are deleted. Must be +// called under the displayio lock. +static void _sync_members(displayio_group_t *self) { + if (self->lv_obj == NULL) { + return; + } + size_t child_index = 0; + for (size_t i = 0; i < self->members->len; i++) { + mp_obj_t layer = self->members->items[i]; + lv_obj_t *obj = _member_mirror(layer); + if (obj == NULL) { + // Not mirrored yet: try to attach it now (unsupported layers stay NULL). + obj = _attach_member(self, layer); + } + if (obj == NULL) { + continue; + } + if (lv_obj_get_parent(obj) != self->lv_obj) { + lv_obj_set_parent(obj, self->lv_obj); + } + if (lv_obj_get_index(obj) != (int32_t)child_index) { + lv_obj_move_to_index(obj, child_index); + } + child_index++; + } + // Delete mirrors of members that were removed from the group. + while ((uint32_t)lv_obj_get_child_count(self->lv_obj) > child_index) { + lv_obj_t *child = lv_obj_get_child(self->lv_obj, (int32_t)(lv_obj_get_child_count(self->lv_obj) - 1)); + lv_obj_delete(child); + } + // Newly attached members need their position, scale and absolute offset pushed in. Every + // member already accepted this transform in _adopt_member(). + (void)_update_children(self); +} + +void common_hal_displayio_group_insert(displayio_group_t *self, size_t index, mp_obj_t layer) { + check_readonly(self); + nlr_jump_callback_node_t cleanup; + displayio_lvgl_lock_with_cleanup(&cleanup); + _adopt_member(self, layer); + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + mp_obj_list_insert(self->members, index, layer); + nlr_pop(); + } else { + mp_obj_t native = layer; + const lvgl_protocol_t *protocol = _layer_protocol(&native); + protocol->set_in_group(native, false); + nlr_jump(nlr.ret_val); + } + if (self->lv_obj != NULL) { + _sync_members(self); + } + displayio_lvgl_unlock_with_cleanup(); +} + +mp_obj_t common_hal_displayio_group_pop(displayio_group_t *self, size_t index) { + check_readonly(self); + mp_obj_t layer = self->members->items[index]; + nlr_jump_callback_node_t cleanup; + displayio_lvgl_lock_with_cleanup(&cleanup); + _release_member(self, layer); + mp_obj_list_pop(self->members, index); + if (self->lv_obj != NULL) { + _sync_members(self); + } + displayio_lvgl_unlock_with_cleanup(); + return layer; +} + +mp_int_t common_hal_displayio_group_index(displayio_group_t *self, mp_obj_t layer) { + mp_obj_t args[] = {self->members, layer}; + mp_obj_t *index = mp_seq_index_obj(self->members->items, self->members->len, 2, args); + return MP_OBJ_SMALL_INT_VALUE(index); +} + +size_t common_hal_displayio_group_get_len(displayio_group_t *self) { + return self->members->len; +} + +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) { + check_readonly(self); + mp_obj_t previous = self->members->items[index]; + if (previous == layer) { + return; + } + nlr_jump_callback_node_t cleanup; + displayio_lvgl_lock_with_cleanup(&cleanup); + // Validate the replacement before detaching the current member. Failed assignment + // must leave both the Python list and its LVGL mirrors intact. + _adopt_member(self, layer); + _release_member(self, previous); + mp_obj_list_store(self->members, MP_OBJ_NEW_SMALL_INT(index), layer); + if (self->lv_obj != NULL) { + _sync_members(self); + } + displayio_lvgl_unlock_with_cleanup(); +} + +// protocol_lvgl implementation. A Group is a member of another Group like any other layer; +// its own position and scale are inherited, so it recomputes its origin from the parent's. +// +// A Python subclass of Group (PageLayout, a Tile, ...) is an mp_obj_instance_t that holds the +// native Group in subobj[0], so every function below has to see that native object instead of +// the instance. Resolving it here keeps the type slot on the native type. +static mp_obj_t _group_protocol_self(mp_obj_t layer) { + mp_obj_t native = mp_obj_cast_to_native_base(layer, MP_OBJ_FROM_PTR(&displayio_group_type)); + if (native == MP_OBJ_NULL) { + return layer; + } + mp_obj_assert_native_inited(native); + return native; +} + +static lv_obj_t *_group_protocol_root_obj(mp_obj_t layer) { + return ((displayio_group_t *)MP_OBJ_TO_PTR(layer))->lv_obj; +} + +static void _group_protocol_attach(mp_obj_t layer, lv_obj_t *parent) { + displayio_lvgl_group_attach(MP_OBJ_TO_PTR(layer), parent); +} + +static void _group_protocol_detach(mp_obj_t layer) { + displayio_lvgl_group_detach(MP_OBJ_TO_PTR(layer)); +} + +static bool _group_protocol_set_transform(mp_obj_t layer, int32_t abs_x, int32_t abs_y, + uint32_t scale) { + displayio_group_t *self = MP_OBJ_TO_PTR(layer); + self->lv_scale = scale; + // abs_x/y is where this group's parent origin is on the screen; shift by this group's + // own position, scaled the same way as its members are. + self->lv_abs_x = abs_x + displayio_lvgl_scale_coordinate(self->x, scale); + self->lv_abs_y = abs_y + displayio_lvgl_scale_coordinate(self->y, scale); + if (self->lv_obj == NULL) { + return true; + } + return _update_children(self); +} + +static void _group_protocol_set_hidden_by_parent(mp_obj_t layer, bool hidden) { + displayio_group_set_hidden_by_parent(MP_OBJ_TO_PTR(layer), hidden); +} + +static bool _group_protocol_set_in_group(mp_obj_t layer, bool in_group) { + displayio_group_t *self = MP_OBJ_TO_PTR(layer); + bool was_in_group = self->in_group; + self->in_group = in_group; + return was_in_group; +} + +const lvgl_protocol_t displayio_lvgl_group_protocol = { + MP_PROTO_IMPLEMENT(MP_QSTR_protocol_lvgl) + .protocol_self = _group_protocol_self, + .root_obj = _group_protocol_root_obj, + .attach = _group_protocol_attach, + .detach = _group_protocol_detach, + .set_transform = _group_protocol_set_transform, + .set_hidden_by_parent = _group_protocol_set_hidden_by_parent, + .set_in_group = _group_protocol_set_in_group, +}; + +void displayio_lvgl_group_attach(displayio_group_t *self, lv_obj_t *parent) { + if (self->lv_obj == NULL) { + self->lv_obj = lv_obj_create(parent); + if (self->lv_obj == NULL) { + return; + } + // Plain, transparent, screen sized container at the screen origin. See + // _update_children() for why it doesn't follow the group's position. + lv_obj_remove_style_all(self->lv_obj); + lv_obj_clear_flag(self->lv_obj, LV_OBJ_FLAG_CLICKABLE); + lv_obj_clear_flag(self->lv_obj, LV_OBJ_FLAG_SCROLLABLE); + lv_obj_add_flag(self->lv_obj, LV_OBJ_FLAG_OVERFLOW_VISIBLE); + lv_obj_set_size(self->lv_obj, lv_pct(100), lv_pct(100)); + lv_obj_set_pos(self->lv_obj, 0, 0); + _update_lvgl_visible(self); + } else if (lv_obj_get_parent(self->lv_obj) != parent) { + lv_obj_set_parent(self->lv_obj, parent); + } + _sync_members(self); +} + +void displayio_lvgl_group_detach(displayio_group_t *self) { + if (self->lv_obj == NULL) { + return; + } + // Detach the members first so their object pointers don't dangle when the lv tree + // is deleted below us. + for (size_t i = 0; i < self->members->len; i++) { + mp_obj_t layer = self->members->items[i]; + const lvgl_protocol_t *protocol = _layer_protocol(&layer); + if (protocol != NULL) { + protocol->detach(layer); + } + } + lv_obj_delete(self->lv_obj); + self->lv_obj = NULL; +} + +void displayio_lvgl_set_root_group(displayio_group_t *group) { + displayio_lvgl_init(); + if (!cp_lvgl_inited) { + // The port never created the LVGL screen (no display); nothing to mirror. + return; + } + nlr_jump_callback_node_t cleanup; + displayio_lvgl_lock_with_cleanup(&cleanup); + if (cp_lvgl_root_group == group) { + displayio_lvgl_unlock_with_cleanup(); + return; + } + if (cp_lvgl_root_group != NULL) { + displayio_lvgl_group_detach(cp_lvgl_root_group); + } + cp_lvgl_root_group = group; + if (cp_lvgl_root_group != NULL) { + // The root group's origin is its own position. + group->lv_scale = LV_SCALE_NONE; + group->lv_abs_x = group->x; + group->lv_abs_y = group->y; + displayio_lvgl_group_attach(cp_lvgl_root_group, lv_screen_active()); + } + // Repaint the whole screen. The incoming tree may not cover everything the outgoing one did + // (the terminal leaves the top row for its status bar and logo), so the screen background has + // to replace the old content there instead of leaving it on the display. + lv_obj_t *screen = lv_screen_active(); + if (screen != NULL) { + lv_obj_invalidate(screen); + } + displayio_lvgl_unlock_with_cleanup(); +} + +void displayio_gc_collect(void) { + void *root_ptrs[1] = { cp_lvgl_root_group }; + if (root_ptrs[0] != NULL) { + gc_collect_root(root_ptrs, 1); + } + // The shader registry holds vectorio pointers in port memory; root them explicitly. + displayio_lvgl_mirror_gc(); + // So does the compositor's list of attached TileGrids. + displayio_lvgl_tilegrid_gc_collect(); + // Displays live in the static slot registry, which the GC can't see. + displayio_display_slots_gc_collect(); + #if CIRCUITPY_VIDEOCORE + // So does the compositor's list of attached VideoBuffer mirrors. + displayio_lvgl_video_gc_collect(); + #endif +} + +#endif // CIRCUITPY_DISPLAYIO_LVGL diff --git a/shared-module/displayio/lvgl/Group.h b/shared-module/displayio/lvgl/Group.h new file mode 100644 index 00000000000..06411b4775e --- /dev/null +++ b/shared-module/displayio/lvgl/Group.h @@ -0,0 +1,62 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include + +#include "py/obj.h" +#include "py/objlist.h" +#include "shared-module/displayio/Palette.h" +#include "shared-module/displayio/lvgl/lvgl_protocol.h" + +#include "lvgl.h" + +// LVGL-based version of displayio Group. The Python-visible state is mirrored into an +// LVGL object tree: a Group maps to a plain lv_obj container whose children are the +// mirrors of its TileGrid and subgroup members. Only the fields below are used by this +// implementation; the scanline compositor's transform/area state lives in +// shared-module/displayio/legacy/Group.h. + +typedef struct { + mp_obj_base_t base; + mp_obj_list_t *members; + int16_t x; + int16_t y; + uint32_t scale; // Own scale in LVGL's Q8 format; LV_SCALE_NONE is 1x. + // Keep the requested value for Python readback. In particular, consecutive animation + // values may quantize to the same Q8 step but must not become stuck at the old value. + mp_obj_t requested_scale; + bool item_removed : 1; + bool in_group : 1; + bool hidden : 1; + bool hidden_by_parent : 1; + bool readonly : 1; + uint8_t padding : 3; + // LVGL mirror state. + lv_obj_t *lv_obj; // Plain lv_obj container created when the group is attached. + uint32_t lv_scale; // Inherited parent scale in Q8 format. + // Absolute position of this group's coordinate origin. Children use it to keep their + // own absolute position (needed by vectorio's contains()) in sync. + int32_t lv_abs_x; + int32_t lv_abs_y; +} displayio_group_t; + +void displayio_group_construct(displayio_group_t *self, mp_obj_list_t *members, mp_obj_t scale, mp_int_t x, mp_int_t y); +void displayio_group_set_hidden_by_parent(displayio_group_t *self, bool hidden); + +// Shared LVGL compositor API. Implemented in shared-module/displayio/lvgl/Group.c. +void displayio_lvgl_init(void); +void displayio_lvgl_tick(void); // Run LVGL timers from the background task. +void displayio_lvgl_set_root_group(displayio_group_t *group); // NULL detaches. + +// Group mirror lifecycle. Implemented in Group.c and called by the compositor. +void displayio_lvgl_group_attach(displayio_group_t *self, lv_obj_t *parent); +void displayio_lvgl_group_detach(displayio_group_t *self); + +// How a parent Group attaches, positions and hides this Group. See lvgl_protocol.h. +extern const lvgl_protocol_t displayio_lvgl_group_protocol; diff --git a/shared-module/displayio/lvgl/ImageRoot.c b/shared-module/displayio/lvgl/ImageRoot.c new file mode 100644 index 00000000000..491f493a867 --- /dev/null +++ b/shared-module/displayio/lvgl/ImageRoot.c @@ -0,0 +1,53 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// Descriptor-level invalidation, shared by OnDiskBitmap. See ImageRoot.h. + +#include "shared-module/displayio/lvgl/ImageRoot.h" + +#if CIRCUITPY_DISPLAYIO_LVGL + +void displayio_lvgl_image_root_add(displayio_lvgl_image_root_t **roots, lv_obj_t *obj) { + for (displayio_lvgl_image_root_t *root = *roots; root != NULL; root = root->next) { + if (root->obj == obj) { + return; + } + } + displayio_lvgl_image_root_t *root = lv_malloc_zeroed(sizeof(*root)); + if (root == NULL) { + return; + } + root->obj = obj; + root->next = *roots; + *roots = root; +} + +void displayio_lvgl_image_root_remove(displayio_lvgl_image_root_t **roots, lv_obj_t *obj) { + displayio_lvgl_image_root_t **link = roots; + while (*link != NULL) { + if ((*link)->obj == obj) { + displayio_lvgl_image_root_t *found = *link; + *link = found->next; + lv_free(found); + return; + } + link = &(*link)->next; + } +} + +void displayio_lvgl_image_invalidate_all(displayio_lvgl_image_root_t *roots, + const lv_image_dsc_t *dsc) { + if (dsc->data == NULL) { + return; + } + for (displayio_lvgl_image_root_t *root = roots; root != NULL; root = root->next) { + // A TileGrid mirror is either the image itself or a container holding the images, and + // both cover exactly the grid's area. + lv_obj_invalidate(root->obj); + } +} + +#endif // CIRCUITPY_DISPLAYIO_LVGL diff --git a/shared-module/displayio/lvgl/ImageRoot.h b/shared-module/displayio/lvgl/ImageRoot.h new file mode 100644 index 00000000000..cf97b400f29 --- /dev/null +++ b/shared-module/displayio/lvgl/ImageRoot.h @@ -0,0 +1,33 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include + +#include "py/obj.h" + +#include "lvgl.h" + +// Descriptor-level invalidation. An image descriptor can be drawn by several lv_objs (an +// OnDiskBitmap hands one descriptor per decode mode to every TileGrid that shows the file), +// so the owner keeps the list of objects to invalidate when the descriptor's content changes. +// +// The composed TileGrid path doesn't need this: its descriptors belong to the TileGrid, which +// invalidates its own objects. + +typedef struct displayio_lvgl_image_root { + lv_obj_t *obj; + struct displayio_lvgl_image_root *next; +} displayio_lvgl_image_root_t; + +// Add/remove an object that draws a descriptor. Idempotent. Caller holds the LVGL lock. +void displayio_lvgl_image_root_add(displayio_lvgl_image_root_t **roots, lv_obj_t *obj); +void displayio_lvgl_image_root_remove(displayio_lvgl_image_root_t **roots, lv_obj_t *obj); +// Invalidate every object that draws the descriptor. Caller holds the LVGL lock. +void displayio_lvgl_image_invalidate_all(displayio_lvgl_image_root_t *roots, + const lv_image_dsc_t *dsc); diff --git a/shared-module/displayio/lvgl/OnDiskBitmap.c b/shared-module/displayio/lvgl/OnDiskBitmap.c new file mode 100644 index 00000000000..14c0ef5b2e3 --- /dev/null +++ b/shared-module/displayio/lvgl/OnDiskBitmap.c @@ -0,0 +1,816 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018 Scott Shawcroft for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2025 SamantazFox +// +// SPDX-License-Identifier: MIT + +// LVGL-based displayio OnDiskBitmap implementation. +// +// The BMP is parsed here, but the pixels stay in the file. A custom LVGL image decoder +// (registered by displayio_lvgl_init()) serves them to LVGL: +// +// - When the file lives in mapped flash (CIRCUITPY_STORAGE_MAP_FILE), each request is a +// one-row draw buffer that points straight at the flash bytes. No copy, no seek. +// - Otherwise, the whole image is decoded into an lv_draw_buf when a TileGrid attaches +// (on the CircuitPython thread, so the render thread never touches VFS). That is the +// memory cost OnDiskBitmap normally avoids, but it is the only thread-safe option for +// files on SD cards. +// - A TileGrid that inherits a scale needs a whole image too: LVGL can't transform a +// partially decoded image. +// +// The file owns one lv_image_dsc_t per decode mode (streaming rows and whole image), whose +// `data` points at this object and whose `reserved` carries the decoder tag. TileGrids share +// them, so a Palette change reaches every image drawn from the file without going through a +// TileGrid. For indexed files the Palette is converted to lv_color32_t entries here, and the +// decoder expands rows through them. + +#include "shared-bindings/displayio/OnDiskBitmap.h" +#include "shared-bindings/displayio/ColorConverter.h" +#include "shared-bindings/displayio/Palette.h" +#include "shared-module/displayio/ColorConverter.h" +#include "shared-module/displayio/Palette.h" +#include "shared-module/displayio/lvgl/lvgl_internal.h" +// Private image-decoder descriptor (lives in different directories in LVGL trees). +#include "lvgl_private.h" + +#include + +#include "py/mperrno.h" +#include "py/runtime.h" +#include "py/stream.h" +#if CIRCUITPY_STORAGE_MAP_FILE +#include "shared-bindings/storage/__init__.h" +#endif + + +#define DISPLAYIO_ODBMP_DEBUG(...) (void)0 +// #define DISPLAYIO_ODBMP_DEBUG(...) mp_printf(&mp_plat_print __VA_OPT__(,) __VA_ARGS__) + +// Tags an lv_image_dsc_t as describing a displayio OnDiskBitmap. Shared with TileGrid.c. +const char displayio_lvgl_ondiskbitmap_tag = 0; + +typedef struct odb_decoder { + displayio_ondiskbitmap_t *odb; + // One-row scratch used when a mapped row is split across flash runs or needs conversion. + uint8_t *row_data; + uint32_t row_stride; + lv_draw_buf_t row; + lv_draw_buf_t wrap; +} odb_decoder_t; + +// The decoder opens once per draw of every image, so its scratch lives on the OnDiskBitmap +// instead of being allocated and freed each time. Opens never nest: LVGL draws one task at a +// time on its own thread, and `open`/`close` are the only places that touch it. +static void odb_decoder_free(displayio_ondiskbitmap_t *odb) { + odb_decoder_t *s = (odb_decoder_t *)odb->lv_decoder; + if (s == NULL) { + return; + } + if (s->row_data != NULL) { + lv_free(s->row_data); + } + lv_free(s); + odb->lv_decoder = NULL; +} + +static uint32_t read_word(uint16_t *bmp_header, uint16_t index) { + return bmp_header[index] | bmp_header[index + 1] << 16; +} + +// Bytes of pixel data in one row, without the BMP row padding. +static uint32_t row_bytes(displayio_ondiskbitmap_t *self) { + return ((uint32_t)self->width * self->bits_per_pixel + 7) / 8; +} + +// True when file rows have to be converted instead of passed through to LVGL (indexed +// pixels expand through the Palette, 555/bitfield 16bpp becomes XRGB8888). +static bool row_converts(displayio_ondiskbitmap_t *self) { + return self->bits_per_pixel <= 8 || + (self->bits_per_pixel == 16 && self->g_bitmask != 0x07e0); +} + +lv_color_format_t displayio_ondiskbitmap_lv_color_format(displayio_ondiskbitmap_t *self) { + switch (self->bits_per_pixel) { + case 1: + case 2: + case 4: + case 8: + // The software renderer only blends I1 natively, so indexed rows are + // expanded through the Palette to ARGB8888 (transparent entries keep alpha 0). + return LV_COLOR_FORMAT_ARGB8888; + case 16: + // 565 is LVGL's native little-endian RGB565; 555 and bitfields are converted. + return row_converts(self) ? LV_COLOR_FORMAT_XRGB8888 : LV_COLOR_FORMAT_RGB565; + case 24: + // BMP stores B, G, R, which is LVGL's RGB888 byte order. + return LV_COLOR_FORMAT_RGB888; + case 32: + // BMP stores B, G, R, X; LVGL's XRGB8888 ignores the top byte like the legacy + // compositor does. + return LV_COLOR_FORMAT_XRGB8888; + default: + return LV_COLOR_FORMAT_UNKNOWN; + } +} + +static void ensure_full_image(displayio_ondiskbitmap_t *self); + +// Rebuild the decoder's LVGL copy of the Palette after it changed. +static void refresh_palette(displayio_ondiskbitmap_t *self) { + if (self->lv_palette == NULL || self->palette == NULL) { + return; + } + displayio_lvgl_palette_fill(self->palette, self->lv_palette, + 1u << self->bits_per_pixel); + self->lv_palette_generation++; + // The decoded image has the old palette baked in; redo it on the CP thread. + if (self->lv_decoded != NULL && self->lv_decoded_generation != self->lv_palette_generation) { + lv_draw_buf_destroy(self->lv_decoded); + self->lv_decoded = NULL; + ensure_full_image(self); + } +} + +#if CIRCUITPY_STORAGE_MAP_FILE +static void add_run(void *self_in, const uint8_t *addr, size_t len, uint32_t block) { + displayio_ondiskbitmap_t *self = self_in; + if (self->map_count < MP_ARRAY_SIZE(self->map)) { + self->map[self->map_count].addr = addr; + self->map[self->map_count].len = len; + self->map_count++; + } else { + self->map_count = MP_ARRAY_SIZE(self->map) + 1; // too fragmented: decode into RAM instead + } +} + +// Flash address of len bytes at offset if they lie in one run, else NULL. +static const uint8_t *map_at(displayio_ondiskbitmap_t *self, uint32_t offset, uint32_t len) { + for (uint8_t i = 0; i < self->map_count && i < MP_ARRAY_SIZE(self->map); i++) { + if (offset < self->map[i].len) { + return offset + len <= self->map[i].len ? self->map[i].addr + offset : NULL; + } + offset -= self->map[i].len; + } + return NULL; +} + +// Copy len bytes at offset out of the mapped runs. Works across run boundaries by going +// byte by byte; returns false if the file isn't mapped at that offset. +static bool copy_mapped(displayio_ondiskbitmap_t *self, uint32_t offset, uint32_t len, uint8_t *dst) { + const uint8_t *p = map_at(self, offset, len); + if (p != NULL) { + memcpy(dst, p, len); + return true; + } + for (uint32_t i = 0; i < len; i++) { + p = map_at(self, offset + i, 1); + if (p == NULL) { + return false; + } + dst[i] = *p; + } + return true; +} + +// Row y of an 8-bit file in flash, or NULL if it spans two runs or the file isn't mapped. +const uint8_t *displayio_ondiskbitmap_row(displayio_ondiskbitmap_t *self, int16_t y) { + uint32_t file_y = self->top_down ? y : self->height - y - 1; + return map_at(self, self->data_offset + file_y * self->stride, self->width); +} +#endif + +static bool is_mapped(displayio_ondiskbitmap_t *self) { + #if CIRCUITPY_STORAGE_MAP_FILE + return self->map_count > 0 && self->map_count <= MP_ARRAY_SIZE(self->map); + #else + (void)self; + return false; + #endif +} + +// Read one whole row of pixel data into dst. Runs on the CircuitPython thread. +static bool read_row(displayio_ondiskbitmap_t *self, uint32_t file_y, uint8_t *dst, uint32_t len) { + uint32_t offset = self->data_offset + file_y * self->stride; + #if CIRCUITPY_STORAGE_MAP_FILE + if (is_mapped(self)) { + return copy_mapped(self, offset, len, dst); + } + #endif + int errcode = 0; + mp_stream_seek(self->file, offset, MP_SEEK_SET, &errcode); + if (errcode != 0) { + return false; + } + mp_uint_t n = mp_stream_rw(self->file, dst, len, &errcode, MP_STREAM_RW_ONCE); + return errcode == 0 && n == len; +} + +// Pull one BGR channel out of a 16bpp pixel with arbitrary bitfields. +static uint8_t extract_channel(uint32_t pixel, uint32_t mask) { + if (mask == 0) { + return 0; + } + uint32_t shift = 0; + while (((mask >> shift) & 1u) == 0) { + shift++; + } + uint32_t max = mask >> shift; + return (uint8_t)((((pixel & mask) >> shift) * 255u + max / 2) / max); +} + +// Convert a 16bpp row (BGR in little-endian) to XRGB8888. +static void convert_row_16(displayio_ondiskbitmap_t *self, const uint8_t *src, uint8_t *dst, + uint32_t width) { + for (uint32_t x = 0; x < width; x++) { + uint16_t pixel = src[0] | (src[1] << 8); + dst[0] = extract_channel(pixel, self->b_bitmask); + dst[1] = extract_channel(pixel, self->g_bitmask); + dst[2] = extract_channel(pixel, self->r_bitmask); + dst[3] = 0xff; + src += 2; + dst += 4; + } +} + +// Expand one indexed row (MSB first, like BMP) through the Palette to ARGB8888. +static void convert_row_indexed(displayio_ondiskbitmap_t *self, const uint8_t *src, uint8_t *dst, + uint32_t width) { + uint32_t mask = (1u << self->bits_per_pixel) - 1u; + for (uint32_t x = 0; x < width; x++) { + uint32_t bit = x * self->bits_per_pixel; + uint8_t shift = 8 - self->bits_per_pixel - (bit & 7); + uint32_t index = (src[bit >> 3] >> shift) & mask; + lv_color32_t color = self->lv_palette[index]; + dst[0] = color.blue; + dst[1] = color.green; + dst[2] = color.red; + dst[3] = color.alpha; + dst += 4; + } +} + +// Decode the whole image into RAM. Called on the CircuitPython thread while a TileGrid +// attaches (or starts scaling), never from the render thread. +static lv_draw_buf_t *decode_all(displayio_ondiskbitmap_t *self) { + lv_color_format_t cf = displayio_ondiskbitmap_lv_color_format(self); + if (cf == LV_COLOR_FORMAT_UNKNOWN) { + return NULL; + } + lv_draw_buf_t *buf = lv_draw_buf_create(self->width, self->height, cf, LV_STRIDE_AUTO); + if (buf == NULL) { + return NULL; + } + uint32_t src_len = row_bytes(self); + uint8_t *src = lv_malloc(src_len); + if (src == NULL) { + lv_draw_buf_destroy(buf); + return NULL; + } + bool converts = row_converts(self); + uint32_t dst_stride = buf->header.stride; + for (uint32_t y = 0; y < self->height; y++) { + uint32_t file_y = self->top_down ? y : self->height - 1 - y; + if (!read_row(self, file_y, src, src_len)) { + lv_free(src); + lv_draw_buf_destroy(buf); + return NULL; + } + uint8_t *dst = (uint8_t *)buf->data + y * dst_stride; + if (self->bits_per_pixel <= 8) { + convert_row_indexed(self, src, dst, self->width); + } else if (converts) { + convert_row_16(self, src, dst, self->width); + } else { + memcpy(dst, src, src_len); + } + } + lv_free(src); + return buf; +} + +// Does any attached TileGrid need the whole image in RAM / as one draw buffer? +static bool uses_full_image(displayio_ondiskbitmap_t *self) { + return self->lv_full_users > 0 || !is_mapped(self); +} + +static void ensure_full_image(displayio_ondiskbitmap_t *self) { + if (self->lv_decoded != NULL) { + return; + } + // A top-down, contiguous mapped file of a direct color format can be drawn from + // flash directly (see decoder open); indexed rows need the palette expansion. + if (!row_converts(self) && self->lv_mapped_all != NULL && self->top_down && + self->height > 0) { + return; + } + self->lv_decoded = decode_all(self); + self->lv_decoded_generation = self->lv_palette_generation; +} + +// Build the descriptor for one decode mode. LVGL's decoder recognizes an OnDiskBitmap by +// these two fields: data points at the file object and reserved carries the tag. +static void init_dsc(displayio_ondiskbitmap_t *self, lv_image_dsc_t *dsc) { + lv_image_dsc_t *d = dsc; + lv_memzero(d, sizeof(*d)); + lv_color_format_t cf = displayio_ondiskbitmap_lv_color_format(self); + d->header.magic = LV_IMAGE_HEADER_MAGIC; + d->header.cf = cf; + d->header.w = self->width; + d->header.h = self->height; + d->header.stride = lv_draw_buf_width_to_stride(self->width, cf); + d->data = (const uint8_t *)self; + d->reserved = &displayio_lvgl_ondiskbitmap_tag; +} + +const lv_image_dsc_t *displayio_ondiskbitmap_lv_acquire(displayio_ondiskbitmap_t *self, bool full, + lv_obj_t *root) { + uint8_t mode = full ? 1 : 0; + self->lv_users++; + if (full) { + self->lv_full_users++; + } + if (uses_full_image(self)) { + ensure_full_image(self); + } + init_dsc(self, &self->lv_dsc[mode]); + displayio_lvgl_image_root_add((displayio_lvgl_image_root_t **)&self->lv_roots[mode], root); + if (self->lv_users == 1 && self->palette != NULL) { + // Indexed files draw through their own Palette, so it has to reach the decoder. + displayio_lvgl_shader_register_user(MP_OBJ_FROM_PTR(self->palette), self, + DISPLAYIO_LVGL_USER_ONDISKBITMAP); + } + return &self->lv_dsc[mode]; +} + +void displayio_ondiskbitmap_lv_release(displayio_ondiskbitmap_t *self, bool full, lv_obj_t *root) { + uint8_t mode = full ? 1 : 0; + displayio_lvgl_image_root_remove((displayio_lvgl_image_root_t **)&self->lv_roots[mode], root); + lv_image_cache_drop(&self->lv_dsc[mode]); + if (self->lv_users > 0) { + self->lv_users--; + } + if (full && self->lv_full_users > 0) { + self->lv_full_users--; + } + if (self->lv_users == 0) { + self->lv_full_users = 0; + lv_memzero(&self->lv_dsc[0], sizeof(self->lv_dsc[0])); + lv_memzero(&self->lv_dsc[1], sizeof(self->lv_dsc[1])); + if (self->palette != NULL) { + displayio_lvgl_shader_unregister_user(MP_OBJ_FROM_PTR(self->palette), self); + } + if (self->lv_decoded != NULL) { + lv_draw_buf_destroy(self->lv_decoded); + self->lv_decoded = NULL; + } + odb_decoder_free(self); + } else if (!uses_full_image(self) && self->lv_decoded != NULL) { + // Back to streaming rows: give the RAM copy back. + lv_draw_buf_destroy(self->lv_decoded); + self->lv_decoded = NULL; + } +} + +void displayio_ondiskbitmap_lv_palette_changed(displayio_ondiskbitmap_t *self) { + refresh_palette(self); + for (uint8_t mode = 0; mode < 2; mode++) { + lv_image_cache_drop(&self->lv_dsc[mode]); + displayio_lvgl_image_invalidate_all( + (displayio_lvgl_image_root_t *)self->lv_roots[mode], &self->lv_dsc[mode]); + } +} + +// --- LVGL image decoder ------------------------------------------------------ + +static lv_result_t odb_decoder_info(lv_image_decoder_t *decoder, lv_image_decoder_dsc_t *dsc, + lv_image_header_t *header) { + (void)decoder; + if (dsc->src_type != LV_IMAGE_SRC_VARIABLE) { + return LV_RESULT_INVALID; + } + const lv_image_dsc_t *src = dsc->src; + if (src->reserved != &displayio_lvgl_ondiskbitmap_tag || src->data == NULL) { + return LV_RESULT_INVALID; + } + displayio_ondiskbitmap_t *odb = (displayio_ondiskbitmap_t *)(void *)src->data; + lv_color_format_t cf = displayio_ondiskbitmap_lv_color_format(odb); + if (cf == LV_COLOR_FORMAT_UNKNOWN) { + return LV_RESULT_INVALID; + } + header->cf = cf; + header->w = odb->width; + header->h = odb->height; + header->stride = lv_draw_buf_width_to_stride(odb->width, cf); + return LV_RESULT_OK; +} + +static lv_result_t odb_decoder_open(lv_image_decoder_t *decoder, lv_image_decoder_dsc_t *dsc) { + (void)decoder; + const lv_image_dsc_t *src = dsc->src; + displayio_ondiskbitmap_t *odb = (displayio_ondiskbitmap_t *)(void *)src->data; + lv_color_format_t cf = dsc->header.cf; + if (cf == LV_COLOR_FORMAT_UNKNOWN) { + return LV_RESULT_INVALID; + } + + odb_decoder_t *s = (odb_decoder_t *)odb->lv_decoder; + if (s == NULL) { + s = lv_malloc_zeroed(sizeof(odb_decoder_t)); + if (s == NULL) { + return LV_RESULT_INVALID; + } + s->odb = odb; + odb->lv_decoder = s; + } + dsc->user_data = s; + + if (uses_full_image(odb)) { + if (odb->lv_decoded != NULL) { + dsc->decoded = odb->lv_decoded; + return LV_RESULT_OK; + } + if (!row_converts(odb) && odb->lv_mapped_all != NULL && odb->top_down && + odb->height > 0) { + uint32_t size = (uint32_t)odb->stride * odb->height; + if (lv_draw_buf_init(&s->wrap, odb->width, odb->height, cf, odb->stride, + (void *)odb->lv_mapped_all, size) == LV_RESULT_OK) { + dsc->decoded = &s->wrap; + return LV_RESULT_OK; + } + } + // Fall through to row streaming when the file is mapped. + } + + if (s->row_data == NULL) { + s->row_stride = lv_draw_buf_width_to_stride(odb->width, cf); + if (s->row_stride < odb->stride) { + s->row_stride = odb->stride; + } + s->row_data = lv_malloc(s->row_stride); + if (s->row_data == NULL) { + return LV_RESULT_INVALID; + } + } + return LV_RESULT_OK; +} + +static lv_result_t odb_decoder_get_area(lv_image_decoder_t *decoder, lv_image_decoder_dsc_t *dsc, + const lv_area_t *full_area, lv_area_t *decoded_area) { + (void)decoder; + odb_decoder_t *s = dsc->user_data; + displayio_ondiskbitmap_t *odb = s->odb; + + if (decoded_area->y1 == LV_COORD_MIN) { + *decoded_area = *full_area; + decoded_area->y2 = decoded_area->y1; + } else { + decoded_area->y1++; + decoded_area->y2++; + if (decoded_area->y1 > full_area->y2) { + return LV_RESULT_INVALID; + } + } + + // Serve whole rows in image coordinates. LVGL intersects the decoded area with the + // clip area, so this also covers a TileGrid cell showing a horizontal window. + decoded_area->x1 = 0; + decoded_area->x2 = odb->width - 1; + + if (decoded_area->y1 < 0 || decoded_area->y1 >= odb->height) { + return LV_RESULT_INVALID; + } + uint32_t y = decoded_area->y1; + lv_color_format_t cf = dsc->header.cf; + const uint8_t *row = NULL; + + #if CIRCUITPY_STORAGE_MAP_FILE + uint32_t file_y = odb->top_down ? y : odb->height - 1 - y; + uint32_t offset = odb->data_offset + file_y * odb->stride; + uint32_t len = row_bytes(odb); + if (is_mapped(odb)) { + row = map_at(odb, offset, len); + if (row == NULL) { + // The row crosses a run boundary; copy it together in RAM. + if (!copy_mapped(odb, offset, len, s->row_data)) { + return LV_RESULT_INVALID; + } + row = s->row_data; + } + } + #else + (void)y; + #endif + if (row == NULL) { + // Not mapped. Attach decodes the whole image, so streaming here would mean the + // decode failed; don't touch the file from the render thread. + return LV_RESULT_INVALID; + } + + if (row_converts(odb)) { + if (odb->bits_per_pixel <= 8) { + convert_row_indexed(odb, row, s->row_data, odb->width); + } else { + convert_row_16(odb, row, s->row_data, odb->width); + } + if (lv_draw_buf_init(&s->row, odb->width, 1, cf, s->row_stride, s->row_data, + s->row_stride) != LV_RESULT_OK) { + return LV_RESULT_INVALID; + } + } else if (lv_draw_buf_init(&s->row, odb->width, 1, cf, odb->stride, (void *)row, + odb->stride) != LV_RESULT_OK) { + return LV_RESULT_INVALID; + } + dsc->decoded = &s->row; + return LV_RESULT_OK; +} + +static void odb_decoder_close(lv_image_decoder_t *decoder, lv_image_decoder_dsc_t *dsc) { + (void)decoder; + // The scratch stays on the OnDiskBitmap for the next draw. + dsc->user_data = NULL; +} + +void displayio_lvgl_ondiskbitmap_decoder_init(void) { + lv_image_decoder_t *dec = lv_image_decoder_create(); + if (dec == NULL) { + return; + } + lv_image_decoder_set_info_cb(dec, odb_decoder_info); + lv_image_decoder_set_open_cb(dec, odb_decoder_open); + lv_image_decoder_set_get_area_cb(dec, odb_decoder_get_area); + lv_image_decoder_set_close_cb(dec, odb_decoder_close); + dec->name = "CP OnDiskBitmap"; +} + +// --- displayio API ----------------------------------------------------------- + +void common_hal_displayio_ondiskbitmap_construct(displayio_ondiskbitmap_t *self, mp_obj_t file) { + self->file = file; + self->cache_len = 0; + self->cache_start = 0; + self->lv_mapped_all = NULL; + self->lv_decoded = NULL; + self->lv_palette = NULL; + self->lv_palette_generation = 0; + self->lv_decoded_generation = 0; + lv_memzero(self->lv_dsc, sizeof(self->lv_dsc)); + self->lv_decoder = NULL; + self->lv_roots[0] = NULL; + self->lv_roots[1] = NULL; + self->lv_users = 0; + self->lv_full_users = 0; + uint16_t bmp_header[69]; + int errcode = 0; + + mp_stream_seek(file, 0, MP_SEEK_SET, &errcode); + if (errcode != 0) { + mp_raise_OSError(errcode); + } + + // Read the minimum amount of bytes required to parse a BITMAPCOREHEADER. + // If needed, we will read more bytes down below. + mp_uint_t bytes_read = mp_stream_rw(file, bmp_header, 26, &errcode, MP_STREAM_RW_ONCE); + if (errcode != 0) { + mp_raise_OSError(errcode); + } + if (bytes_read != 26 || memcmp(bmp_header, "BM", 2) != 0) { + mp_arg_error_invalid(MP_QSTR_file); + } + + // Read header size to determine if more header bytes needs to be read. + uint32_t header_size = read_word(bmp_header, 7); + DISPLAYIO_ODBMP_DEBUG("header_size: %d\n", header_size); + + if (header_size == 40 || header_size == 108 || header_size == 124) { + // Read the remaining header bytes + bytes_read = mp_stream_rw(file, bmp_header + 13, header_size - 12, &errcode, MP_STREAM_RW_ONCE); + if (errcode != 0) { + mp_raise_OSError(errcode); + } + DISPLAYIO_ODBMP_DEBUG("bytes_read: %d\n", bytes_read); + if (bytes_read != (header_size - 12)) { + mp_arg_error_invalid(MP_QSTR_file); + } + } else if (header_size != 12) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("Only Windows format, uncompressed BMP supported: given header size is %d"), header_size); + } + + + uint32_t compression = read_word(bmp_header, 15); + DISPLAYIO_ODBMP_DEBUG("compression: %d\n", compression); + + // 0 is uncompressed; 3 is bitfield compressed. 1 and 2 are RLE compression. + if (compression != 0 && compression != 3) { + mp_raise_ValueError(MP_ERROR_TEXT("RLE-compressed BMP not supported")); + } + + // We can't cast because we're not aligned. + self->data_offset = read_word(bmp_header, 5); + + self->bitfield_compressed = (compression == 3); + self->bits_per_pixel = bmp_header[14]; + self->width = read_word(bmp_header, 9); + // A negative height means the rows are stored top to bottom. + int32_t bmp_height = (int16_t)read_word(bmp_header, 11); + self->top_down = bmp_height < 0; + if (bmp_height < 0) { + bmp_height = -bmp_height; + } + self->height = (uint16_t)bmp_height; + + DISPLAYIO_ODBMP_DEBUG("data offset: %d\n", self->data_offset); + DISPLAYIO_ODBMP_DEBUG("width: %d\n", self->width); + DISPLAYIO_ODBMP_DEBUG("height: %d\n", self->height); + DISPLAYIO_ODBMP_DEBUG("bpp: %d\n", self->bits_per_pixel); + + + displayio_colorconverter_t *colorconverter = + mp_obj_malloc(displayio_colorconverter_t, &displayio_colorconverter_type); + common_hal_displayio_colorconverter_construct(colorconverter, false, DISPLAYIO_COLORSPACE_RGB888); + self->colorconverter = colorconverter; + + if (self->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); + self->b_bitmask = read_word(bmp_header, 31); + + } else { // no compression or short header means 5:5:5 + self->r_bitmask = 0x7c00; + self->g_bitmask = 0x3e0; + self->b_bitmask = 0x1f; + } + } else if (self->bits_per_pixel <= 8) { // indexed + uint32_t number_of_colors = 0; + if (header_size >= 40) { + number_of_colors = read_word(bmp_header, 23); + } + if (number_of_colors == 0) { + number_of_colors = 1 << self->bits_per_pixel; + } + + displayio_palette_t *palette = mp_obj_malloc(displayio_palette_t, &displayio_palette_type); + common_hal_displayio_palette_construct(palette, number_of_colors, false); + + if (number_of_colors > 1) { + uint16_t palette_size = number_of_colors * sizeof(uint32_t); + uint16_t palette_offset = 0xe + header_size; + + uint32_t *palette_data = m_malloc_without_collect(palette_size); + + mp_stream_seek(file, palette_offset, MP_SEEK_SET, &errcode); + if (errcode != 0) { + mp_raise_OSError(errcode); + } + + mp_uint_t palette_bytes_read = mp_stream_rw(file, palette_data, palette_size, &errcode, MP_STREAM_RW_ONCE); + if (errcode != 0) { + mp_raise_OSError(errcode); + } + if (palette_bytes_read != palette_size) { + mp_raise_ValueError(MP_ERROR_TEXT("Unable to read color palette data")); + } + for (uint16_t i = 0; i < number_of_colors; i++) { + common_hal_displayio_palette_set_color(palette, i, palette_data[i]); + } + + #if MICROPY_MALLOC_USES_ALLOCATED_SIZE + m_free(palette_data, palette_size); + #else + m_free(palette_data); + #endif + } else { + common_hal_displayio_palette_set_color(palette, 0, 0x0); + common_hal_displayio_palette_set_color(palette, 1, 0xffffff); + } + self->palette = palette; + + // The decoder expands indexed rows through this LVGL copy of the palette. + uint32_t lv_palette_count = 1u << self->bits_per_pixel; + self->lv_palette = m_malloc_without_collect(lv_palette_count * sizeof(lv_color32_t)); + refresh_palette(self); + } + + 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) { + self->stride = (self->width * bytes_per_pixel); + // Rows are word aligned. + if (self->stride % 4 != 0) { + self->stride += 4 - self->stride % 4; + } + } else { + uint32_t bit_stride = self->width * self->bits_per_pixel; + if (bit_stride % 32 != 0) { + bit_stride += 32 - bit_stride % 32; + } + self->stride = (bit_stride / 8); + } + + #if CIRCUITPY_STORAGE_MAP_FILE + self->map_count = 0; + self->rows_mapped = false; + if (storage_map_runs(file, add_run, self) != 0 || self->map_count > MP_ARRAY_SIZE(self->map)) { + self->map_count = 0; + } + if (self->map_count > 0 && self->height > 0) { + // Whole pixel block in one run? Then a transform can draw straight from flash. + uint32_t size = (uint32_t)(self->height - 1) * self->stride + row_bytes(self); + self->lv_mapped_all = map_at(self, self->data_offset, size); + } + #endif +} + + +void common_hal_displayio_ondiskbitmap_deinit(displayio_ondiskbitmap_t *self) { + if (common_hal_displayio_ondiskbitmap_deinited(self)) { + return; + } + mp_stream_close(self->file); + self->file = NULL; + #if CIRCUITPY_STORAGE_MAP_FILE + // A TileGrid may still draw this bitmap, so it must stop reading rows from mapped + // flash: the file is closed and the mapping can go away. Nothing decodes after this, + // so a redraw paints color 0 like the legacy compositor does. + displayio_lvgl_lock(); + self->map_count = 0; + self->lv_mapped_all = NULL; + displayio_lvgl_unlock(); + #endif +} + +bool common_hal_displayio_ondiskbitmap_deinited(displayio_ondiskbitmap_t *self) { + return self->file == NULL; +} + +uint32_t common_hal_displayio_ondiskbitmap_get_pixel(displayio_ondiskbitmap_t *self, + int16_t x, int16_t y) { + if (common_hal_displayio_ondiskbitmap_deinited(self) || + 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 pixels_per_byte = 8 / self->bits_per_pixel; + uint32_t file_y = self->top_down ? y : self->height - y - 1; + if (pixels_per_byte == 0) { + location = self->data_offset + file_y * self->stride + x * bytes_per_pixel; + } else { + location = self->data_offset + file_y * self->stride + x / pixels_per_byte; + } + int errcode = 0; + if (location < self->cache_start || location + bytes_per_pixel > self->cache_start + self->cache_len) { + mp_stream_seek(self->file, location, MP_SEEK_SET, &errcode); + if (errcode != 0) { + return 0; + } + self->cache_start = location; + self->cache_len = mp_stream_rw(self->file, self->cache, sizeof(self->cache), &errcode, MP_STREAM_RW_ONCE); + if (errcode != 0 || self->cache_len < bytes_per_pixel) { + self->cache_len = 0; + return 0; + } + } + uint32_t pixel_data = 0; + memcpy(&pixel_data, self->cache + (location - self->cache_start), bytes_per_pixel); + uint32_t tmp = 0; + uint8_t red; + uint8_t green; + uint8_t blue; + if (bytes_per_pixel == 1) { + uint8_t offset = (x % pixels_per_byte) * self->bits_per_pixel; + uint8_t mask = (1 << self->bits_per_pixel) - 1; + + return (pixel_data >> ((8 - self->bits_per_pixel) - offset)) & mask; + } 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); + blue = ((pixel_data & self->b_bitmask) >> 0); + } else { // 555 + 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); + return tmp; + } else if ((bytes_per_pixel == 4) && (self->bitfield_compressed)) { + return pixel_data & 0x00FFFFFF; + } else { + return pixel_data; + } +} + +uint16_t common_hal_displayio_ondiskbitmap_get_height(displayio_ondiskbitmap_t *self) { + return self->height; +} + +uint16_t common_hal_displayio_ondiskbitmap_get_width(displayio_ondiskbitmap_t *self) { + return self->width; +} + +mp_obj_t common_hal_displayio_ondiskbitmap_get_pixel_shader(displayio_ondiskbitmap_t *self) { + return MP_OBJ_FROM_PTR(self->pixel_shader_base); +} diff --git a/shared-module/displayio/lvgl/OnDiskBitmap.h b/shared-module/displayio/lvgl/OnDiskBitmap.h new file mode 100644 index 00000000000..ec924d6ed3a --- /dev/null +++ b/shared-module/displayio/lvgl/OnDiskBitmap.h @@ -0,0 +1,89 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include + +#include "py/obj.h" +#include "lvgl.h" + +typedef struct { + mp_obj_base_t base; + uint16_t width; + uint16_t height; + uint32_t data_offset; + uint16_t stride; + uint32_t r_bitmask; + uint32_t g_bitmask; + uint32_t b_bitmask; + mp_obj_t file; + union { + mp_obj_base_t *pixel_shader_base; + struct displayio_palette *palette; + struct displayio_colorconverter *colorconverter; + }; + bool bitfield_compressed; + uint8_t bits_per_pixel; + // The last bytes read from the file. Pixels are read along rows, so most reads hit it. + uint8_t cache_len; + #if CIRCUITPY_STORAGE_MAP_FILE + // Flash runs the pixels are read from instead of the cache; 0 = read through the cache. + uint8_t map_count; + // 8-bit file with every row inside one run, so TileGrid can read whole rows. + bool rows_mapped; + #endif + uint32_t cache_start; + union { + uint8_t cache[64]; + #if CIRCUITPY_STORAGE_MAP_FILE + struct { + const uint8_t *addr; + uint32_t len; + } map[8]; + #endif + }; + // A negative BMP height means the rows are stored top to bottom. + bool top_down; + // LVGL backend state. The pixels are exposed through a custom image decoder (see + // shared-module/displayio/lvgl/OnDiskBitmap.c) so the file can be drawn without + // loading it into RAM when it lives in mapped flash. + const uint8_t *lv_mapped_all; + lv_draw_buf_t *lv_decoded; + lv_color32_t *lv_palette; + uint32_t lv_palette_generation; + uint32_t lv_decoded_generation; + // One image per decode mode, shared by every TileGrid drawing the file that way: [0] + // streams rows, [1] holds the whole decode (unmapped files and scaled TileGrids). + lv_image_dsc_t lv_dsc[2]; + struct displayio_lvgl_image_root *lv_roots[2]; + // The decoder's scratch (row buffer and draw buffer wrappers), owned here so that opening + // an image per draw doesn't allocate. See odb_decoder_open(). + struct odb_decoder *lv_decoder; + uint16_t lv_users; + uint16_t lv_full_users; +} displayio_ondiskbitmap_t; + +#if CIRCUITPY_STORAGE_MAP_FILE +// Row y of an 8-bit file in flash, or NULL if it spans two runs or the file isn't mapped. +const uint8_t *displayio_ondiskbitmap_row(displayio_ondiskbitmap_t *self, int16_t y); +#endif + +// Image decoder used by OnDiskBitmap. The descriptors it hands out carry this address in +// reserved and point data at the OnDiskBitmap. +extern const char displayio_lvgl_ondiskbitmap_tag; +void displayio_lvgl_ondiskbitmap_decoder_init(void); +lv_color_format_t displayio_ondiskbitmap_lv_color_format(displayio_ondiskbitmap_t *self); +// Attach/detach a TileGrid's root object as a user of the file's LVGL image. full requests a +// whole image (the file isn't in mapped flash, or the TileGrid inherits a scale). The +// returned descriptor stays valid until the matching release. Caller holds the LVGL lock. +const lv_image_dsc_t *displayio_ondiskbitmap_lv_acquire(displayio_ondiskbitmap_t *self, bool full, + lv_obj_t *root); +void displayio_ondiskbitmap_lv_release(displayio_ondiskbitmap_t *self, bool full, lv_obj_t *root); +// The file's Palette changed: rebuild the decoder's LVGL palette and the whole decode, and +// invalidate every image drawn from the file. +void displayio_ondiskbitmap_lv_palette_changed(displayio_ondiskbitmap_t *self); diff --git a/shared-module/displayio/lvgl/Palette.c b/shared-module/displayio/lvgl/Palette.c new file mode 100644 index 00000000000..7f5a38fb0c2 --- /dev/null +++ b/shared-module/displayio/lvgl/Palette.c @@ -0,0 +1,237 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/displayio/Palette.h" + +#include "py/gc.h" +#include "py/runtime.h" +#include "shared-module/displayio/ColorConverter.h" +#include "shared-module/displayio/lvgl/Bitmap.h" +#include "shared-module/displayio/lvgl/OnDiskBitmap.h" +#include "shared-module/displayio/lvgl/Palette.h" +#include "shared-module/displayio/lvgl/lvgl_internal.h" + +#if CIRCUITPY_VECTORIO +#include "shared-module/vectorio/VectorShape.h" +#endif + +// --- The shader registry ----------------------------------------------------- +// +// Bitmaps keep their views in the Bitmap itself, but Palettes are shared and may be `const`, +// so whoever draws with one registers in this port-memory registry keyed by the +// shader object. A Palette change then walks the list and updates each mirror. + +typedef struct { + void *shader; // displayio Palette or ColorConverter object. + displayio_lvgl_mirror_user_t *users; + // LVGL's view of a Palette's colors, shared by every image drawing with it. NULL for + // ColorConverters and until an indexed image needs it. + lv_color32_t *colors; + struct displayio_lvgl_mirror_entry *next; // as displayio_lvgl_mirror_entry_t +} displayio_lvgl_mirror_entry_t; + +static displayio_lvgl_mirror_entry_t *mirror_registry = NULL; + +static displayio_lvgl_mirror_entry_t *_mirror_entry(void *shader) { + for (displayio_lvgl_mirror_entry_t *entry = mirror_registry; entry != NULL; entry = (displayio_lvgl_mirror_entry_t *)entry->next) { + if (entry->shader == shader) { + return entry; + } + } + return NULL; +} + +void displayio_lvgl_shader_register_user(mp_obj_t pixel_shader, void *user, uint8_t kind) { + void *shader = MP_OBJ_TO_PTR(pixel_shader); + displayio_lvgl_mirror_entry_t *entry = _mirror_entry(shader); + if (entry == NULL) { + entry = lv_malloc(sizeof(displayio_lvgl_mirror_entry_t)); + if (entry == NULL) { + return; + } + entry->shader = shader; + entry->users = NULL; + entry->colors = NULL; + entry->next = NULL; + displayio_lvgl_mirror_entry_t **link = (displayio_lvgl_mirror_entry_t **)&mirror_registry; + while (*link != NULL) { + link = (displayio_lvgl_mirror_entry_t **)&(*link)->next; + } + *link = entry; + } + for (displayio_lvgl_mirror_user_t *existing = entry->users; existing != NULL; existing = existing->next) { + if (existing->user == user) { + return; + } + } + displayio_lvgl_mirror_user_t *new_user = lv_malloc(sizeof(displayio_lvgl_mirror_user_t)); + if (new_user == NULL) { + return; + } + new_user->user = user; + new_user->kind = kind; + new_user->next = entry->users; + entry->users = new_user; +} + +void displayio_lvgl_shader_unregister_user(mp_obj_t pixel_shader, void *user) { + displayio_lvgl_mirror_entry_t *entry = _mirror_entry(MP_OBJ_TO_PTR(pixel_shader)); + if (entry == NULL) { + return; + } + displayio_lvgl_mirror_user_t **link = &entry->users; + while (*link != NULL) { + if ((*link)->user == user) { + displayio_lvgl_mirror_user_t *found = *link; + *link = found->next; + lv_free(found); + break; + } + link = &(*link)->next; + } + if (entry->users == NULL) { + // Walk with entry-typed links to remove the entry itself. + displayio_lvgl_mirror_entry_t **prev_entry_link = &mirror_registry; + while (*prev_entry_link != entry) { + prev_entry_link = (displayio_lvgl_mirror_entry_t **)&(*prev_entry_link)->next; + } + *prev_entry_link = (displayio_lvgl_mirror_entry_t *)entry->next; + lv_free(entry->colors); + lv_free(entry); + } +} + +void displayio_lvgl_shader_notify(mp_obj_t pixel_shader) { + displayio_lvgl_mirror_entry_t *entry = _mirror_entry(MP_OBJ_TO_PTR(pixel_shader)); + if (entry == NULL) { + return; + } + displayio_lvgl_lock(); + if (entry->colors != NULL && mp_obj_is_type(pixel_shader, &displayio_palette_type)) { + displayio_lvgl_palette_fill(MP_OBJ_TO_PTR(pixel_shader), entry->colors, + LV_COLOR_INDEXED_PALETTE_SIZE(LV_COLOR_FORMAT_I8)); + } + for (displayio_lvgl_mirror_user_t *user = entry->users; user != NULL; user = user->next) { + switch (user->kind) { + case DISPLAYIO_LVGL_USER_TILEGRID: + displayio_lvgl_tilegrid_shader_changed(user->user); + break; + case DISPLAYIO_LVGL_USER_ONDISKBITMAP: + displayio_ondiskbitmap_lv_palette_changed(user->user); + break; + #if CIRCUITPY_VECTORIO + case DISPLAYIO_LVGL_USER_VECTOR_SHAPE: + displayio_lvgl_vector_shape_shader_changed(user->user); + break; + #endif + default: + break; + } + } + displayio_lvgl_unlock(); +} + +void displayio_lvgl_mirror_gc(void) { + for (displayio_lvgl_mirror_entry_t *entry = mirror_registry; entry != NULL; entry = (displayio_lvgl_mirror_entry_t *)entry->next) { + for (displayio_lvgl_mirror_user_t *user = entry->users; user != NULL; user = user->next) { + if (user->kind != DISPLAYIO_LVGL_USER_VECTOR_SHAPE && + user->kind != DISPLAYIO_LVGL_USER_TILEGRID) { + // OnDiskBitmaps live in port memory and hold no Python objects of their own. + continue; + } + gc_collect_ptr(user->user); + } + } +} + +// --- Palette ----------------------------------------------------------------- + +void displayio_lvgl_palette_fill(displayio_palette_t *palette, lv_color32_t *colors, + uint32_t count) { + for (uint32_t i = 0; i < count; i++) { + if (i >= palette->color_count || palette->colors[i].transparent) { + colors[i] = (lv_color32_t) {0}; + continue; + } + uint32_t rgb888 = palette->colors[i].rgb888; + colors[i] = lv_color32_make((rgb888 >> 16) & 0xff, (rgb888 >> 8) & 0xff, rgb888 & 0xff, + LV_OPA_COVER); + } +} + +const lv_color32_t *displayio_lvgl_shader_palette(mp_obj_t pixel_shader) { + displayio_lvgl_mirror_entry_t *entry = _mirror_entry(MP_OBJ_TO_PTR(pixel_shader)); + if (entry == NULL || !mp_obj_is_type(pixel_shader, &displayio_palette_type)) { + return NULL; + } + if (entry->colors == NULL) { + // 256 entries (the largest indexed palette) so the address stays stable when the + // same Palette is used with bitmaps of different depths. + entry->colors = lv_malloc(LV_COLOR_INDEXED_PALETTE_SIZE(LV_COLOR_FORMAT_I8) * sizeof(lv_color32_t)); + if (entry->colors == NULL) { + return NULL; + } + displayio_lvgl_palette_fill(MP_OBJ_TO_PTR(pixel_shader), entry->colors, + LV_COLOR_INDEXED_PALETTE_SIZE(LV_COLOR_FORMAT_I8)); + } + return entry->colors; +} + +void common_hal_displayio_palette_construct(displayio_palette_t *self, uint16_t color_count, bool dither) { + self->color_count = color_count; + self->colors = (_displayio_color_t *)m_malloc_without_collect(color_count * sizeof(_displayio_color_t)); + self->dither = dither; +} + +void common_hal_displayio_palette_set_dither(displayio_palette_t *self, bool dither) { + self->dither = dither; +} + +bool common_hal_displayio_palette_get_dither(displayio_palette_t *self) { + return self->dither; +} + +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; + displayio_lvgl_shader_notify(MP_OBJ_FROM_PTR(self)); +} + +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; + displayio_lvgl_shader_notify(MP_OBJ_FROM_PTR(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) { + if (self->colors[palette_index].rgb888 == color) { + return; + } + self->colors[palette_index].rgb888 = color; + self->colors[palette_index].cached_colorspace = NULL; + self->needs_refresh = true; + displayio_lvgl_shader_notify(MP_OBJ_FROM_PTR(self)); +} + +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_needs_refresh(displayio_palette_t *self) { + return self->needs_refresh; +} + +void displayio_palette_finish_refresh(displayio_palette_t *self) { + self->needs_refresh = false; +} diff --git a/shared-module/displayio/lvgl/Palette.h b/shared-module/displayio/lvgl/Palette.h new file mode 100644 index 00000000000..91ee95bd6b3 --- /dev/null +++ b/shared-module/displayio/lvgl/Palette.h @@ -0,0 +1,48 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-module/displayio/Bitmap.h" +#include "shared-module/displayio/Palette.h" + +#include "lvgl.h" + +// Palette changes notify the LVGL images that draw with it. Those mirrors register here; +// Bitmaps keep pointers to their views themselves. The objects may be `const` statistics (the +// supervisor's generated splash resources), so the registry lives in port memory rather +// than in them. + +// What a registered user is, which decides how a Palette change reaches it. +typedef enum { + DISPLAYIO_LVGL_USER_ONDISKBITMAP = 0, // user is a displayio_ondiskbitmap_t. + DISPLAYIO_LVGL_USER_TILEGRID, // user is a displayio_tilegrid_t. + DISPLAYIO_LVGL_USER_VECTOR_SHAPE, // user is a vectorio_vector_shape_t. +} displayio_lvgl_user_kind_t; + +typedef struct displayio_lvgl_mirror_user { + void *user; + uint8_t kind; // displayio_lvgl_user_kind_t + struct displayio_lvgl_mirror_user *next; +} displayio_lvgl_mirror_user_t; + +void displayio_lvgl_shader_register_user(mp_obj_t pixel_shader, void *user, uint8_t kind); +void displayio_lvgl_shader_unregister_user(mp_obj_t pixel_shader, void *user); +// The pixel shader's content changed: every mirror that draws with it has to update. +void displayio_lvgl_shader_notify(mp_obj_t pixel_shader); +// Root the registry's user pointers during GC. +void displayio_lvgl_mirror_gc(void); + +// Write count LVGL palette entries for palette. Entries past its end and transparent ones +// are fully transparent, which leaves those pixels to the layers below. +void displayio_lvgl_palette_fill(displayio_palette_t *palette, lv_color32_t *colors, + uint32_t count); + +// The shared LVGL palette of `pixel_shader`, allocated and filled on first use. It lives in +// the shader's registry entry, so it is shared by every image drawing with the Palette and +// released when the last of them unregisters. Returns NULL for a non-Palette shader or when +// there is no memory. Call after registering a user. +const lv_color32_t *displayio_lvgl_shader_palette(mp_obj_t pixel_shader); diff --git a/shared-module/displayio/lvgl/TileGrid.c b/shared-module/displayio/lvgl/TileGrid.c new file mode 100644 index 00000000000..460fda8a3bb --- /dev/null +++ b/shared-module/displayio/lvgl/TileGrid.c @@ -0,0 +1,1816 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// LVGL-based displayio TileGrid implementation. +// +// A TileGrid owns one composed buffer holding exactly one tile grid of pixels, in tile-matrix +// order: the pixels of tiles[] cell (i, j) live at (i * tile_width, j * tile_height), with the +// tile indirection and the palette already resolved. Cells are composed through LVGL's own draw +// pipeline (a hidden lv_canvas plus lv_draw_image() per changed cell), so the shim has no pixel +// loop: palette expansion, alpha, format conversion and clipping are LVGL's work. +// +// The display shows that buffer through up to four lv_images ("views"): the 2x2 split of the +// wrapped window that displayio's scrolling describes, where display column i shows matrix column +// (i + top_left_x) % width_in_tiles. A scroll therefore re-points the views and invalidates; no +// pixels move and no cell is re-sourced. The common cases (no scroll, or scrolling by whole rows +// with top_left_x == 0) are one and two views. +// +// A single-cell grid of a direct color source skips the buffer entirely: one view draws the source +// pixels as they are, which is what plain image viewers and the boot logo want. +// +// Composition resolves the palette, so a Bitmap never owns an LVGL image, a descriptor or a +// palette copy. It only tells the TileGrids drawing it which pixels changed +// (displayio_bitmap_set_dirty()), and they re-read that area before the next refresh. +// +// Everything here runs synchronously on the CircuitPython thread under the port's LVGL lock, +// except the compose pass, which runs at the start of an LVGL refresh with the lock already held +// by the renderer (see displayio_lvgl_register_display()). + +#include "shared-bindings/displayio/TileGrid.h" + +#include "py/gc.h" +#include "py/objtype.h" +#include "py/runtime.h" +#include "shared-bindings/displayio/Bitmap.h" +#include "shared-bindings/displayio/ColorConverter.h" +#include "shared-bindings/displayio/OnDiskBitmap.h" +#include "shared-bindings/displayio/Palette.h" +#include "shared-bindings/displayio/__init__.h" +#include "shared-module/displayio/lvgl/lvgl_internal.h" + +#include "misc/cache/instance/lv_image_cache.h" + +#if CIRCUITPY_DISPLAYIO_LVGL + +// Tile-index debug logging goes through ESP_LOG, not mp_printf: mp_printf ends up in +// serial_write_substring(), which writes the display terminal, which calls back into +// common_hal_displayio_tilegrid_set_tile() -- recursion, then a crash. The IDF log console is a +// separate sink, so it can be used from the write path and from the compose pass. +// +// Off by default: this prints several lines per grid per refresh, which buries the heap and +// out-of-memory logging in lvgl_port.c and port.c. Flip to 1 to watch the compose pass; the +// memory logging is independent and stays on either way. +#define DISPLAYIO_TILEGRID_DEBUG_ENABLED 0 + +#if DISPLAYIO_TILEGRID_DEBUG_ENABLED && CIRCUITPY_ESPIDF +#include "esp_log.h" +#define DISPLAYIO_TILEGRID_DEBUG(...) ESP_LOGI("TileGrid", __VA_ARGS__) +#else +#define DISPLAYIO_TILEGRID_DEBUG(...) ((void)0) +#endif + +// Tile index 0 is the blank tile: the terminal fills itself with spaces, and every tiles[] array +// starts zeroed. Logging those hides the glyph changes we care about. +#define DISPLAYIO_TILEGRID_BLANK_TILE 0 + +static void _cell_display_area(displayio_tilegrid_t *self, uint32_t x, uint32_t y, lv_area_t *area); + +static void _raise_unsupported(void) { + mp_raise_NotImplementedError(MP_ERROR_TEXT("LVGL displayio backend does not support flips/transpose yet")); +} + +// --- Attached mirrors ------------------------------------------------------- + +// Every attached TileGrid. The compose pass walks it, the Bitmap write path looks for the grids +// that draw a bitmap in it, and displayio_lvgl_tilegrid_gc_collect() roots it: the list lives in +// port memory, which the GC can't see. +static displayio_tilegrid_t *mirror_head = NULL; + +static bool _is_linked(displayio_tilegrid_t *self) { + for (displayio_tilegrid_t *other = mirror_head; other != NULL; other = other->lv_next) { + if (other == self) { + return true; + } + } + return false; +} + +// A Bitmap keeps its own list of the attached grids drawing it. A pixel write only walks the +// grids that can actually be affected, and an empty list means the write can skip LVGL entirely. +// Only the CircuitPython thread mutates these lists, under the LVGL lock. +static void _watch_bitmap(displayio_tilegrid_t *self) { + if (!mp_obj_is_type(self->bitmap, &displayio_bitmap_type)) { + return; + } + displayio_bitmap_t *bitmap = MP_OBJ_TO_PTR(self->bitmap); + self->lv_bitmap_next = bitmap->lv_watch_head; + bitmap->lv_watch_head = self; +} + +static void _unwatch_bitmap(displayio_tilegrid_t *self) { + if (!mp_obj_is_type(self->bitmap, &displayio_bitmap_type)) { + return; + } + displayio_bitmap_t *bitmap = MP_OBJ_TO_PTR(self->bitmap); + displayio_tilegrid_t **link = &bitmap->lv_watch_head; + while (*link != NULL) { + if (*link == self) { + *link = self->lv_bitmap_next; + break; + } + link = &(*link)->lv_bitmap_next; + } + self->lv_bitmap_next = NULL; +} + +static void _link_mirror(displayio_tilegrid_t *self) { + if (_is_linked(self)) { + return; + } + self->lv_next = mirror_head; + mirror_head = self; + _watch_bitmap(self); +} + +static void _unlink_mirror(displayio_tilegrid_t *self) { + bool linked = false; + displayio_tilegrid_t **link = &mirror_head; + while (*link != NULL) { + if (*link == self) { + *link = self->lv_next; + linked = true; + break; + } + link = &(*link)->lv_next; + } + self->lv_next = NULL; + if (linked) { + _unwatch_bitmap(self); + } +} + +void displayio_lvgl_tilegrid_gc_collect(void) { + for (displayio_tilegrid_t *self = mirror_head; self != NULL; self = self->lv_next) { + gc_collect_ptr(self); + } +} + +// --- Cells ----------------------------------------------------------------- + +static uint32_t _cell_count(displayio_tilegrid_t *self) { + return (uint32_t)self->width_in_tiles * self->height_in_tiles; +} + +// Tile pixel origin in the source bitmap for a tile index. +static void _tile_origin(displayio_tilegrid_t *self, uint16_t tile_index, uint16_t *x0, uint16_t *y0) { + *x0 = (tile_index % self->bitmap_width_in_tiles) * self->tile_width; + *y0 = (tile_index / self->bitmap_width_in_tiles) * self->tile_height; +} + +// Read one index from an indexed source row. LVGL packs indices MSB first within each byte. +static uint8_t _source_index(const uint8_t *row, uint32_t x, uint8_t bpp) { + uint32_t bit = x * bpp; + return (row[bit >> 3] >> (8 - bpp - (bit & 7))) & ((1u << bpp) - 1); +} + +// Whether a tile holds only palette entry 0. A compose buffer is cleared to zero, so when entry 0 +// matches that value, such a cell can be left out of the compose draw entirely. +static bool _tile_is_blank(displayio_tilegrid_t *self, uint16_t tile_index) { + const lv_image_dsc_t *src = self->lv_src; + if (src == NULL || src->data == NULL) { + return false; + } + uint8_t bpp = lv_color_format_get_bpp(src->header.cf); + if (bpp != 1 && bpp != 2 && bpp != 4 && bpp != 8) { + return false; + } + uint16_t x0, y0; + _tile_origin(self, tile_index, &x0, &y0); + for (uint16_t y = 0; y < self->tile_height; y++) { + const uint8_t *row = src->data + (uint32_t)(y0 + y) * src->header.stride; + for (uint16_t x = 0; x < self->tile_width; x++) { + if (_source_index(row, x0 + x, bpp) != 0) { + return false; + } + } + } + return true; +} + +// Read the tile index stored for a cell of the tile matrix, in the same order as the composed +// buffer: cell (i, j) shows tiles[j * width_in_tiles + i]. +static uint16_t _tile_index(displayio_tilegrid_t *self, uint32_t cell_index) { + if (self->tiles == NULL) { + return 0; + } + if (self->tiles_in_bitmap > 255) { + return ((uint16_t *)self->tiles)[cell_index]; + } + return ((uint8_t *)self->tiles)[cell_index]; +} + +// A composed grid is brought up to date by the compose pass, which runs at the start of a refresh +// (LV_EVENT_REFR_START, before LVGL reads its invalid-area list), so a change has to invalidate +// something or LVGL never runs a refresh and the grid stays stale forever. Invalidate the area the +// changed cell occupies on screen: that is the same rectangle the compose pass would invalidate, +// and it keeps `display.refresh()`/auto_refresh-independent redraws honest even before the compose +// runs. Only the first change of a burst does this -- invalidating every changed cell would +// overflow LVGL's invalidation buffer (LV_INV_BUF_SIZE, 32 rects) and repaint the whole screen -- +// and the compose pass invalidates the union of everything it recomposed in the same pass. +// `cell` < 0 means "not one cell", i.e. invalidate the whole grid. +static void _wake_refresh(displayio_tilegrid_t *self, int32_t cell) { + if (self->lv_obj == NULL || lv_obj_get_display(self->lv_obj) == NULL) { + // Not attached yet: attaching marks everything dirty, so a later write wakes it. + return; + } + if (cell < 0 || self->lv_full_dirty || self->width_in_tiles == 0 || + self->height_in_tiles == 0) { + DISPLAYIO_TILEGRID_DEBUG("wake %p whole obj", self); + lv_obj_invalidate(self->lv_obj); + return; + } + lv_area_t area; + _cell_display_area(self, (uint32_t)cell % self->width_in_tiles, + (uint32_t)cell / self->width_in_tiles, &area); + if (area.x2 < area.x1) { + DISPLAYIO_TILEGRID_DEBUG("wake %p whole obj (no cell area)", self); + lv_obj_invalidate(self->lv_obj); + return; + } + // The area comes back in container coordinates; LVGL invalidates in screen coordinates. + lv_area_t obj_coords; + lv_obj_get_coords(self->lv_obj, &obj_coords); + lv_area_move(&area, obj_coords.x1, obj_coords.y1); + DISPLAYIO_TILEGRID_DEBUG("wake %p cell %ld at (%ld,%ld)-(%ld,%ld)", self, (long)cell, + (long)area.x1, (long)area.y1, (long)area.x2, (long)area.y2); + lv_obj_invalidate_area(self->lv_obj, &area); +} + +// Grid of one cell whose tile is the whole bitmap, drawn 1:1 with no flips: bitmap coordinates +// are the grid's own coordinates, so a changed rectangle maps straight across. This covers both +// direct grids and composed ones (an indexed bitmap behind a Palette). +static bool _is_identity(displayio_tilegrid_t *self) { + if (self->width_in_tiles != 1 || self->height_in_tiles != 1 || + self->lv_scale != LV_SCALE_NONE || self->flip_x || self->flip_y || + self->transpose_xy || !mp_obj_is_type(self->bitmap, &displayio_bitmap_type)) { + return false; + } + displayio_bitmap_t *bitmap = MP_OBJ_TO_PTR(self->bitmap); + return self->tile_width == bitmap->width && self->tile_height == bitmap->height; +} + +static void _mark_work(displayio_tilegrid_t *self) { + if (self->lv_work) { + return; + } + self->lv_work = true; + _wake_refresh(self, -1); +} + +static void _mark_all(displayio_tilegrid_t *self) { + self->lv_full_dirty = true; + _mark_work(self); +} + +static void _mark_views(displayio_tilegrid_t *self) { + self->lv_views_dirty = true; + _mark_work(self); +} + +static void _mark_cell(displayio_tilegrid_t *self, uint32_t cell) { + if (self->lv_cell_dirty == NULL || cell >= _cell_count(self)) { + _mark_all(self); + return; + } + uint32_t *word = &self->lv_cell_dirty[cell / 32]; + uint32_t bit = 1u << (cell % 32); + bool was_working = self->lv_work; + if ((*word & bit) == 0) { + *word |= bit; + self->lv_dirty_count++; + } + self->lv_work = true; + if (!was_working) { + _wake_refresh(self, (int32_t)cell); + } +} + +static bool _cell_is_marked(displayio_tilegrid_t *self, uint32_t cell) { + return (self->lv_cell_dirty[cell / 32] & (1u << (cell % 32))) != 0; +} + +static void _clear_cell(displayio_tilegrid_t *self, uint32_t cell) { + if (self->lv_cell_dirty != NULL) { + self->lv_cell_dirty[cell / 32] &= ~(1u << (cell % 32)); + } +} + +// The supervisor pokes grid dimensions straight into the static terminal grids, so the bitset is +// checked against the current dimensions instead of assuming it still fits. +static void _ensure_cell_bits(displayio_tilegrid_t *self) { + uint32_t words = (_cell_count(self) + 31) / 32; + if (words == 0) { + words = 1; + } + if (self->lv_cell_dirty != NULL && self->lv_cell_words >= words) { + return; + } + if (self->lv_cell_dirty != NULL) { + lv_free(self->lv_cell_dirty); + } + self->lv_cell_dirty = lv_malloc_zeroed(words * sizeof(uint32_t)); + self->lv_cell_words = words; + self->lv_dirty_count = 0; + self->lv_full_dirty = true; +} + +// --- The source atlas ------------------------------------------------------- + +// The LVGL color format that draws bitmap with pixel_shader. Raises NotImplementedError for the +// combinations that haven't been ported to LVGL. +static lv_color_format_t _source_cf(mp_obj_t bitmap, mp_obj_t pixel_shader) { + if (mp_obj_is_type(bitmap, &displayio_ondiskbitmap_type)) { + displayio_ondiskbitmap_t *odb = MP_OBJ_TO_PTR(bitmap); + lv_color_format_t cf = displayio_ondiskbitmap_lv_color_format(odb); + if (cf == LV_COLOR_FORMAT_UNKNOWN) { + mp_raise_NotImplementedError(MP_ERROR_TEXT("Format not supported")); + } + // The file owns its pixel shader (Palette for indexed files, pass-through + // ColorConverter otherwise), so a different one can't be applied. + mp_obj_t odb_shader = common_hal_displayio_ondiskbitmap_get_pixel_shader(odb); + if (MP_OBJ_TO_PTR(pixel_shader) != MP_OBJ_TO_PTR(odb_shader)) { + mp_raise_NotImplementedError(MP_ERROR_TEXT("OnDiskBitmap requires its own pixel_shader")); + } + return cf; + } + if (mp_obj_is_type(bitmap, &displayio_bitmap_type)) { + uint8_t bpp = ((displayio_bitmap_t *)MP_OBJ_TO_PTR(bitmap))->bits_per_value; + if (mp_obj_is_type(pixel_shader, &displayio_palette_type)) { + switch (bpp) { + case 1: + return LV_COLOR_FORMAT_I1; + case 2: + return LV_COLOR_FORMAT_I2; + case 4: + return LV_COLOR_FORMAT_I4; + case 8: + return LV_COLOR_FORMAT_I8; + } + } else if (mp_obj_is_type(pixel_shader, &displayio_colorconverter_type)) { + displayio_colorconverter_t *converter = MP_OBJ_TO_PTR(pixel_shader); + if (converter->transparent_color == NO_TRANSPARENT_COLOR) { + if (bpp == 16 && converter->input_colorspace == DISPLAYIO_COLORSPACE_RGB565) { + return LV_COLOR_FORMAT_RGB565; + } + if (bpp == 16 && converter->input_colorspace == DISPLAYIO_COLORSPACE_RGB565_SWAPPED) { + return LV_COLOR_FORMAT_RGB565_SWAPPED; + } + if (bpp == 32 && converter->input_colorspace == DISPLAYIO_COLORSPACE_RGB888) { + return LV_COLOR_FORMAT_XRGB8888; + } + if (bpp == 8 && converter->input_colorspace == DISPLAYIO_COLORSPACE_L8) { + return LV_COLOR_FORMAT_L8; + } + } + } + } + mp_raise_NotImplementedError(MP_ERROR_TEXT("Format not supported")); +} + +// displayio's only alpha is the palette's per-index "transparent" flag (plus indices past the end +// of the palette). A composed buffer has to carry that through to the display, so those grids +// compose to ARGB8888 with real alpha, and everything else composes to RGB565, which the display +// path takes directly. +static bool _palette_has_transparency(displayio_palette_t *palette, uint32_t slots) { + for (uint32_t i = 0; i < palette->color_count; i++) { + if (palette->colors[i].transparent) { + return true; + } + } + return palette->color_count < slots; +} + +static bool _source_has_alpha(displayio_tilegrid_t *self, lv_color_format_t cf) { + if (mp_obj_is_type(self->bitmap, &displayio_ondiskbitmap_type)) { + displayio_ondiskbitmap_t *odb = MP_OBJ_TO_PTR(self->bitmap); + if (odb->bits_per_pixel > 8 || odb->palette == NULL) { + return false; + } + return _palette_has_transparency(odb->palette, 1u << odb->bits_per_pixel); + } + if (!LV_COLOR_FORMAT_IS_INDEXED(cf) || !mp_obj_is_type(self->pixel_shader, &displayio_palette_type)) { + return false; + } + return _palette_has_transparency(MP_OBJ_TO_PTR(self->pixel_shader), + LV_COLOR_INDEXED_PALETTE_SIZE(cf)); +} + +static bool _source_is_indexed(displayio_tilegrid_t *self) { + if (mp_obj_is_type(self->bitmap, &displayio_ondiskbitmap_type)) { + // OnDiskBitmap always expands indexed files to a direct color format. + return false; + } + return LV_COLOR_FORMAT_IS_INDEXED(_source_cf(self->bitmap, self->pixel_shader)); +} + +static bool _has_fractional_scale(displayio_tilegrid_t *self) { + return (self->lv_scale & (LV_SCALE_NONE - 1)) != 0; +} + +// A single cell showing a direct color source is exactly the source pixels, so there is nothing +// to compose and nothing to copy. Fractional scales use a composed image with one duplicated +// bottom/right pixel, because LVGL's nearest-neighbor transform otherwise omits those edges. +static bool _wants_direct(displayio_tilegrid_t *self) { + return self->width_in_tiles == 1 && self->height_in_tiles == 1 && + !_source_is_indexed(self) && !_has_fractional_scale(self); +} + +// Point the source descriptor at the whole bitmap. Caller holds the lock and has no source bound. +static bool _bind_source(displayio_tilegrid_t *self) { + lv_color_format_t cf; + if (mp_obj_is_type(self->bitmap, &displayio_ondiskbitmap_type)) { + displayio_ondiskbitmap_t *odb = MP_OBJ_TO_PTR(self->bitmap); + cf = displayio_ondiskbitmap_lv_color_format(odb); + if (cf == LV_COLOR_FORMAT_UNKNOWN) { + DISPLAYIO_TILEGRID_DEBUG("bind %p ondisk bitmap has no LVGL format", self); + return false; + } + // LVGL can't transform a partially decoded image, but a composed grid draws its cells + // unscaled and scales the views of its own buffer instead. + self->lv_src_odb_full = self->lv_direct && self->lv_scale != LV_SCALE_NONE; + self->lv_src = displayio_ondiskbitmap_lv_acquire(odb, self->lv_src_odb_full, self->lv_obj); + self->lv_argb = _source_has_alpha(self, cf); + return self->lv_src != NULL; + } + + displayio_bitmap_t *bitmap = MP_OBJ_TO_PTR(self->bitmap); + cf = _source_cf(self->bitmap, self->pixel_shader); + uint32_t stride = (uint32_t)bitmap->stride * sizeof(uint32_t); + lv_image_dsc_t *dsc = &self->lv_src_dsc; + lv_memzero(dsc, sizeof(*dsc)); + dsc->header.magic = LV_IMAGE_HEADER_MAGIC; + dsc->header.cf = cf; + dsc->header.w = bitmap->width; + dsc->header.h = bitmap->height; + dsc->header.stride = stride; + if (LV_COLOR_FORMAT_IS_INDEXED(cf)) { + // The indices are handed to LVGL in place and the palette is a separate, shared LVGL + // view of the displayio Palette (see displayio_lvgl_shader_palette()), so neither the + // bitmap nor the palette is copied into the TileGrid. + if (bitmap->data == NULL) { + DISPLAYIO_TILEGRID_DEBUG("bind %p bitmap has no data", self); + return false; + } + dsc->header.flags |= LV_IMAGE_FLAGS_PALETTE_EXTERNAL; + dsc->data = (const uint8_t *)bitmap->data; + dsc->data_size = (uint32_t)stride * bitmap->height; + displayio_lvgl_shader_register_user(self->pixel_shader, self, + DISPLAYIO_LVGL_USER_TILEGRID); + dsc->palette = displayio_lvgl_shader_palette(self->pixel_shader); + if (dsc->palette == NULL) { + DISPLAYIO_TILEGRID_DEBUG("bind %p palette has no LVGL view", self); + displayio_lvgl_shader_unregister_user(self->pixel_shader, self); + return false; + } + } else if (bitmap->data != NULL) { + dsc->data = (const uint8_t *)bitmap->data; + dsc->data_size = (uint32_t)stride * bitmap->height; + } + self->lv_src = dsc; + self->lv_argb = _source_has_alpha(self, cf); + DISPLAYIO_TILEGRID_DEBUG("bind %p cf %d %dx%d stride %lu data %p palette %p", + self, (int)cf, bitmap->width, bitmap->height, (unsigned long)stride, dsc->data, + dsc->palette); + return true; +} + +// Undo _bind_source(). Caller holds the lock. +static void _unbind_source(displayio_tilegrid_t *self) { + if (self->lv_src == &self->lv_src_dsc) { + // A Bitmap source is a descriptor over the Bitmap's own pixels. Nothing is owned, but + // the Palette registry and the image cache still point at it. + lv_image_cache_drop(&self->lv_src_dsc); + displayio_lvgl_shader_unregister_user(self->pixel_shader, self); + lv_memzero(&self->lv_src_dsc, sizeof(self->lv_src_dsc)); + } else if (self->lv_src != NULL && mp_obj_is_type(self->bitmap, &displayio_ondiskbitmap_type)) { + displayio_ondiskbitmap_lv_release(MP_OBJ_TO_PTR(self->bitmap), self->lv_src_odb_full, + self->lv_obj); + } + self->lv_src = NULL; + self->lv_src_odb_full = false; +} + +// --- Objects --------------------------------------------------------------- + +// lv_obj_set_pos() only records a style that a later layout pass applies, and lv_obj_move_to() +// leaves that style behind, so an unrelated size change would then snap the object back to where +// the style says. Set both: the coordinates are right immediately and nothing can undo them. +static void _place(lv_obj_t *obj, int32_t x, int32_t y) { + lv_obj_set_style_x(obj, x, 0); + lv_obj_set_style_y(obj, y, 0); + lv_obj_move_to(obj, x, y); +} + +// Place the mirror in screen coordinates. +static void _set_lv_pos(displayio_tilegrid_t *self) { + if (self->lv_obj == NULL) { + return; + } + _place(self->lv_obj, self->lv_origin_x + displayio_lvgl_scale_coordinate(self->x, self->lv_scale), + self->lv_origin_y + displayio_lvgl_scale_coordinate(self->y, self->lv_scale)); +} + +// Scale a view from its top left corner. Moving a pivot makes LVGL lay out the whole screen, and +// the pivot only matters once the view is scaled. +static void _set_view_scale(lv_obj_t *img, uint32_t scale) { + if (scale != LV_SCALE_NONE) { + lv_image_set_pivot(img, 0, 0); + } + lv_image_set_antialias(img, false); + lv_image_set_scale(img, scale); +} + +// Create one view: an lv_image that shows one window of the composed buffer, +// scaled about its top left corner. +static lv_obj_t *_create_view(displayio_tilegrid_t *self, lv_obj_t *parent) { + lv_obj_t *img = lv_image_create(parent); + if (img == NULL) { + return NULL; + } + lv_obj_clear_flag(img, LV_OBJ_FLAG_CLICKABLE); + lv_obj_clear_flag(img, LV_OBJ_FLAG_SCROLLABLE); + lv_image_set_inner_align(img, LV_IMAGE_ALIGN_TOP_LEFT); + _set_view_scale(img, self->lv_scale); + return img; +} + +static bool _ensure_canvas(displayio_tilegrid_t *self) { + if (self->lv_canvas != NULL) { + return true; + } + lv_obj_t *canvas = lv_canvas_create(self->lv_obj); + if (canvas == NULL) { + return false; + } + // The canvas is only here to provide a layer and a display for the compose pass; it is hidden + // and never draws itself. + lv_obj_remove_style_all(canvas); + lv_obj_add_flag(canvas, LV_OBJ_FLAG_HIDDEN); + lv_obj_clear_flag(canvas, LV_OBJ_FLAG_CLICKABLE); + lv_obj_clear_flag(canvas, LV_OBJ_FLAG_SCROLLABLE); + self->lv_canvas = canvas; + return true; +} + +// Build the container the views live in. One object per TileGrid keeps the group's z-order right, +// and the container carries the grid's position and scale so moving a grid never touches its +// views. +static bool _create_objects(displayio_tilegrid_t *self, lv_obj_t *parent) { + lv_obj_t *container = lv_obj_create(parent); + if (container == NULL) { + return false; + } + // Plain, transparent, no layout: the views are placed explicitly, so the LAYOUT_UPDATE that + // lv_obj_set_size() carries resolves to a pass over a handful of children. + lv_obj_remove_style_all(container); + lv_obj_add_flag(container, LV_OBJ_FLAG_OVERFLOW_VISIBLE); + lv_obj_clear_flag(container, LV_OBJ_FLAG_CLICKABLE); + lv_obj_clear_flag(container, LV_OBJ_FLAG_SCROLLABLE); + lv_obj_set_size(container, displayio_lvgl_scale_coordinate(self->pixel_width, self->lv_scale), + displayio_lvgl_scale_coordinate(self->pixel_height, self->lv_scale)); + self->lv_obj = container; + return _ensure_canvas(self); +} + +// Tear the objects down. The composed buffer is ours (a canvas never frees its draw buffer), so it +// goes after the tree that might still reference it. Caller holds the lock. +static void _destroy_objects(displayio_tilegrid_t *self) { + lv_draw_buf_t *buf = self->lv_buf; + self->lv_buf = NULL; + if (self->lv_obj != NULL) { + lv_obj_delete(self->lv_obj); + } + self->lv_obj = NULL; + self->lv_canvas = NULL; + self->lv_view_count = 0; + for (uint8_t i = 0; i < DISPLAYIO_LVGL_TILEGRID_VIEWS; i++) { + self->lv_views[i] = NULL; + } + if (buf != NULL) { + lv_draw_buf_destroy(buf); + } +} + +// --- The composed buffer --------------------------------------------------- + +static bool _ensure_buffer(displayio_tilegrid_t *self) { + // Fractional transforms otherwise omit the outermost source pixels. Reserve one extra + // right column and bottom row; composition duplicates the edges into them so LVGL's + // center-based sampling covers the whole scaled image. + uint32_t w = self->pixel_width + (_has_fractional_scale(self) ? 1 : 0); + uint32_t h = self->pixel_height + (_has_fractional_scale(self) ? 1 : 0); + if (w == 0 || h == 0 || self->lv_obj == NULL) { + return false; + } + lv_color_format_t cf = self->lv_argb ? LV_COLOR_FORMAT_ARGB8888 : LV_COLOR_FORMAT_RGB565; + if (self->lv_buf != NULL && self->lv_buf->header.w == w && self->lv_buf->header.h == h && + self->lv_buf->header.cf == cf) { + return true; + } + if (!_ensure_canvas(self)) { + return false; + } + lv_draw_buf_t *old = self->lv_buf; + // ESP_LOGI(TAG, "creating draw buf %d x %d", w, h); + lv_draw_buf_t *buf = lv_draw_buf_create(w, h, cf, 0); + if (buf == NULL) { + return false; + } + lv_canvas_set_draw_buf(self->lv_canvas, buf); + self->lv_buf = buf; + if (old != NULL) { + lv_draw_buf_destroy(old); + } + _ensure_cell_bits(self); + _mark_all(self); + _mark_views(self); + return true; +} + +// One run of the scroll window: pixels [src, src + len) of the buffer go to display offset dst. +typedef struct { + uint32_t src; + uint32_t len; + uint32_t dst; +} _run_t; + +static void _runs(uint32_t offset, uint32_t extent, _run_t runs[2], uint8_t *count) { + if (offset == 0) { + runs[0].src = 0; + runs[0].len = extent; + runs[0].dst = 0; + *count = 1; + return; + } + runs[0].src = offset; + runs[0].len = extent - offset; + runs[0].dst = 0; + runs[1].src = 0; + runs[1].len = offset; + runs[1].dst = extent - offset; + *count = 2; +} + +// Create views up to `needed`. Returns false when one can't be allocated. +static bool _ensure_views(displayio_tilegrid_t *self, uint8_t needed) { + for (uint8_t i = 0; i < needed; i++) { + if (self->lv_views[i] == NULL) { + self->lv_views[i] = _create_view(self, self->lv_obj); + if (self->lv_views[i] == NULL) { + // Out of memory: try again on the next refresh. + self->lv_views_dirty = true; + return false; + } + } + } + return true; +} + +// Point the views at the current window of the buffer, or at the source itself on the direct path. +// Caller holds the lock. +static void _layout_views(displayio_tilegrid_t *self) { + self->lv_views_dirty = false; + if (self->lv_obj == NULL) { + return; + } + // Views are created on demand, so an unscrolled grid has one and the direct path has one too. + if (self->lv_direct) { + if (!_ensure_views(self, 1)) { + return; + } + // The view is the source: the tile's origin in the atlas becomes a negative offset, in + // scaled pixels, so that the tile's top left lands on the grid's top left. + uint16_t x0, y0; + _tile_origin(self, _tile_index(self, 0), &x0, &y0); + lv_image_set_src(self->lv_views[0], + self->lv_src != NULL && self->lv_src->data != NULL ? self->lv_src : NULL); + lv_image_set_offset_x(self->lv_views[0], -displayio_lvgl_scale_coordinate(x0, self->lv_scale)); + lv_image_set_offset_y(self->lv_views[0], -displayio_lvgl_scale_coordinate(y0, self->lv_scale)); + lv_obj_set_size(self->lv_views[0], displayio_lvgl_scale_coordinate(self->tile_width, self->lv_scale), + displayio_lvgl_scale_coordinate(self->tile_height, self->lv_scale)); + lv_obj_clear_flag(self->lv_views[0], LV_OBJ_FLAG_HIDDEN); + _place(self->lv_views[0], 0, 0); + for (uint8_t i = 1; i < DISPLAYIO_LVGL_TILEGRID_VIEWS; i++) { + if (self->lv_views[i] != NULL) { + lv_obj_add_flag(self->lv_views[i], LV_OBJ_FLAG_HIDDEN); + } + } + self->lv_view_count = 1; + return; + } + if (self->lv_buf == NULL || self->width_in_tiles == 0 || self->height_in_tiles == 0 || + self->pixel_width == 0 || self->pixel_height == 0) { + return; + } + uint32_t grid_w = self->pixel_width; + uint32_t grid_h = self->pixel_height; + uint32_t tx = (self->top_left_x % self->width_in_tiles) * self->tile_width; + uint32_t ty = (self->top_left_y % self->height_in_tiles) * self->tile_height; + _run_t rows[2]; + _run_t cols[2]; + uint8_t row_count; + uint8_t col_count; + _runs(ty, grid_h, rows, &row_count); + _runs(tx, grid_w, cols, &col_count); + if (!_ensure_views(self, row_count * col_count)) { + return; + } + + uint32_t stride = self->lv_buf->header.stride; + lv_color_format_t cf = self->lv_buf->header.cf; + uint32_t bytes_per_pixel = lv_color_format_get_size(cf); + uint8_t view = 0; + for (uint8_t r = 0; r < row_count; r++) { + for (uint8_t c = 0; c < col_count; c++) { + lv_image_dsc_t *dsc = &self->lv_view_dsc[view]; + lv_memzero(dsc, sizeof(*dsc)); + dsc->header.magic = LV_IMAGE_HEADER_MAGIC; + dsc->header.cf = cf; + uint32_t src_w = cols[c].len; + uint32_t src_h = rows[r].len; + if (_has_fractional_scale(self)) { + // Only the run touching the composed image's bottom/right owns + // the duplicated padding pixels. + src_w += cols[c].src + cols[c].len == grid_w; + src_h += rows[r].src + rows[r].len == grid_h; + } + dsc->header.w = src_w; + dsc->header.h = src_h; + dsc->header.stride = stride; + dsc->data = self->lv_buf->data + rows[r].src * stride + + cols[c].src * bytes_per_pixel; + dsc->data_size = stride * src_h; + lv_obj_t *img = self->lv_views[view]; + lv_image_set_src(img, dsc); + lv_image_set_offset_x(img, 0); + lv_image_set_offset_y(img, 0); + lv_obj_set_size(img, displayio_lvgl_scale_coordinate(cols[c].len, self->lv_scale), + displayio_lvgl_scale_coordinate(rows[r].len, self->lv_scale)); + lv_obj_clear_flag(img, LV_OBJ_FLAG_HIDDEN); + _place(img, displayio_lvgl_scale_coordinate(cols[c].dst, self->lv_scale), + displayio_lvgl_scale_coordinate(rows[r].dst, self->lv_scale)); + DISPLAYIO_TILEGRID_DEBUG( + "views %p view %d buf %p cf %d %dx%d stride %lu data %p at (%d,%d)", + self, view, self->lv_buf->data, (int)cf, cols[c].len, rows[r].len, + (unsigned long)stride, (void *)dsc->data, (int)displayio_lvgl_scale_coordinate(cols[c].dst, self->lv_scale), + (int)displayio_lvgl_scale_coordinate(rows[r].dst, self->lv_scale)); + view++; + } + } + self->lv_view_count = view; + DISPLAYIO_TILEGRID_DEBUG( + "views %p count %d grid %lux%lu scroll (%lu,%lu) -> (%lu,%lu) scale %u", + self, view, (unsigned long)grid_w, (unsigned long)grid_h, + (unsigned long)(self->top_left_x % self->width_in_tiles), + (unsigned long)(self->top_left_y % self->height_in_tiles), (unsigned long)tx, + (unsigned long)ty, (unsigned)self->lv_scale); + for (uint8_t i = view; i < DISPLAYIO_LVGL_TILEGRID_VIEWS; i++) { + if (self->lv_views[i] != NULL) { + lv_obj_add_flag(self->lv_views[i], LV_OBJ_FLAG_HIDDEN); + } + } +} + +// --- Compose --------------------------------------------------------------- + +// Grow `area` to cover `other` too. +static void _union_area(lv_area_t *area, const lv_area_t *other) { + if (other->x1 < area->x1) { + area->x1 = other->x1; + } + if (other->y1 < area->y1) { + area->y1 = other->y1; + } + if (other->x2 > area->x2) { + area->x2 = other->x2; + } + if (other->y2 > area->y2) { + area->y2 = other->y2; + } +} + +// LVGL's nearest-neighbor extent is based on the outer source-pixel centers. +// Duplicate the final source row and column into one pixel of padding so the +// real edges are sampled at fractional scales. This is one pixel per composed +// TileGrid, not per atlas tile. +static void _duplicate_fractional_edges(displayio_tilegrid_t *self, lv_area_t *dirty) { + if (!_has_fractional_scale(self)) { + return; + } + uint32_t w = self->pixel_width; + uint32_t h = self->pixel_height; + uint32_t bpp = lv_color_format_get_size(self->lv_buf->header.cf); + uint32_t stride = self->lv_buf->header.stride; + uint8_t *data = self->lv_buf->data; + for (uint32_t y = 0; y < h; y++) { + memcpy(data + y * stride + w * bpp, data + y * stride + (w - 1) * bpp, bpp); + } + memcpy(data + h * stride, data + (h - 1) * stride, (w + 1) * bpp); + + lv_area_t right = {(int32_t)w, 0, (int32_t)w, (int32_t)h}; + lv_area_t bottom = {0, (int32_t)h, (int32_t)w, (int32_t)h}; + _union_area(dirty, &right); + _union_area(dirty, &bottom); +} + +// Cells whose tile overlaps the changed source rect need composing. This is the inverse of the +// tile map; the terminal's 560 byte compares are free next to a frame. +static void _mark_cells_for_source(displayio_tilegrid_t *self, int32_t x1, int32_t y1, + int32_t x2, int32_t y2) { + if (self->lv_full_dirty) { + return; + } + uint32_t cells = _cell_count(self); + for (uint32_t cell = 0; cell < cells; cell++) { + uint16_t x0, y0; + _tile_origin(self, _tile_index(self, cell), &x0, &y0); + if ((int32_t)x0 < x2 && (int32_t)x0 + self->tile_width > x1 && + (int32_t)y0 < y2 && (int32_t)y0 + self->tile_height > y1) { + _mark_cell(self, cell); + } + } +} + +// The bitmap's pixels changed, so drop any decoded view and mark the cells the area reaches. +// Indexed sources are drawn from the Bitmap's own memory, so there is nothing to copy here. +static void _sync_source(displayio_tilegrid_t *self) { + if (!self->lv_src_dirty) { + return; + } + self->lv_src_dirty = false; + if (self->lv_src != NULL) { + lv_image_cache_drop(self->lv_src); + } + _mark_cells_for_source(self, self->lv_src_x1, self->lv_src_y1, self->lv_src_x2, + self->lv_src_y2); +} + +// Where cell (x, y) of the tile matrix lands on the display, in container coordinates. +static void _cell_display_area(displayio_tilegrid_t *self, uint32_t x, uint32_t y, lv_area_t *area) { + int32_t grid_w = self->pixel_width; + int32_t grid_h = self->pixel_height; + if (grid_w <= 0 || grid_h <= 0 || self->width_in_tiles == 0 || self->height_in_tiles == 0) { + *area = (lv_area_t) {0, 0, -1, -1}; + return; + } + int32_t tx = (self->top_left_x % self->width_in_tiles) * self->tile_width; + int32_t ty = (self->top_left_y % self->height_in_tiles) * self->tile_height; + int32_t px = ((int32_t)x * self->tile_width - tx) % grid_w; + int32_t py = ((int32_t)y * self->tile_height - ty) % grid_h; + if (px < 0) { + px += grid_w; + } + if (py < 0) { + py += grid_h; + } + area->x1 = displayio_lvgl_scale_coordinate(px, self->lv_scale); + area->y1 = displayio_lvgl_scale_coordinate(py, self->lv_scale); + area->x2 = displayio_lvgl_scale_coordinate(px + self->tile_width, self->lv_scale) - 1; + area->y2 = displayio_lvgl_scale_coordinate(py + self->tile_height, self->lv_scale) - 1; +} + +// The most cells a compose pass queues before drawing them. LVGL walks the whole task list to add +// or dispatch each task, so drawing a long queue at once takes time with the square of its length. +#define DISPLAYIO_LVGL_COMPOSE_BATCH 64 + +// Zero the cells about to be composed: transparent for ARGB8888, black for RGB565. +// lv_draw_image() leaves transparent source pixels untouched, so they keep the cleared value. +// A full compose clears the whole buffer; otherwise each run of changed cells in a tile row is +// cleared with one lv_draw_buf_clear(). +static void _clear_changed_cells(displayio_tilegrid_t *self, bool full) { + if (full) { + lv_draw_buf_clear(self->lv_buf, NULL); + return; + } + uint32_t tiles_w = self->width_in_tiles; + for (uint32_t cy = 0; cy < self->height_in_tiles; cy++) { + uint32_t cx = 0; + while (cx < tiles_w) { + if (!_cell_is_marked(self, cy * tiles_w + cx)) { + cx++; + continue; + } + uint32_t first = cx; + while (cx < tiles_w && _cell_is_marked(self, cy * tiles_w + cx)) { + cx++; + } + lv_area_t run = { + .x1 = first * self->tile_width, + .y1 = cy * self->tile_height, + .x2 = cx * self->tile_width - 1, + .y2 = (cy + 1) * self->tile_height - 1, + }; + lv_draw_buf_clear(self->lv_buf, &run); + } + } +} + +// Compose every cell that changed into the buffer. Returns false when nothing was drawn so the +// caller can skip the invalidation. `dirty` comes back as the union of the composed cells, in +// container coordinates. +// clip, when not NULL, limits a partial compose of a single-cell identity grid to the pixels +// that changed. It is in buffer coordinates and inside the cell. +static bool _compose(displayio_tilegrid_t *self, const lv_area_t *clip, lv_area_t *dirty) { + if (!self->lv_full_dirty && self->lv_dirty_count == 0) { + return false; + } + if (self->lv_buf == NULL || self->lv_canvas == NULL) { + DISPLAYIO_TILEGRID_DEBUG("compose %p no buffer: buf %p canvas %p", + self, self->lv_buf, self->lv_canvas); + return false; + } + bool full = self->lv_full_dirty; + if (full) { + clip = NULL; + } + bool any = false; + lv_area_t buf_dirty = {0, 0, -1, -1}; + lv_area_t drawn_cell_area = {0, 0, -1, -1}; + + // A cell whose tile is all palette entry 0 can be left untouched: the cleared buffer already + // holds entry 0's color (black in RGB565, transparent in ARGB8888). Tile index 0 isn't + // necessarily blank (it is for the terminal's space glyph, but it's an ordinary tile in any + // other atlas), so check the tile's pixels instead of assuming it. + // A partial compose redraws its clip either way, so it doesn't need the tile scan. + bool skip_blank = clip == NULL && + self->lv_src == &self->lv_src_dsc && self->lv_src->palette != NULL && + LV_COLOR_FORMAT_IS_INDEXED(self->lv_src->header.cf) && + (self->lv_argb ? self->lv_src->palette[0].alpha == 0 : + (self->lv_src->palette[0].red | self->lv_src->palette[0].green | + self->lv_src->palette[0].blue) == 0) && + _tile_is_blank(self, 0); + + // A cell is a cropped window of the atlas, not an image allowed to grow beyond it, so the + // layer's clip area is narrowed to the cell while its draw task is created; lv_draw_add_task() + // saves the clip area into the task. + lv_layer_t layer; + lv_canvas_init_layer(self->lv_canvas, &layer); + lv_area_t layer_clip = layer._clip_area; + uint32_t queued = 0; + + uint32_t cells = _cell_count(self); + // An opaque source drawn into the only cell rewrites every pixel of it, so clearing first + // is wasted work. + bool covers = cells == 1 && !self->lv_argb && self->lv_src != NULL && + self->lv_src->data != NULL && + !(skip_blank && _tile_index(self, 0) == DISPLAYIO_TILEGRID_BLANK_TILE); + if (!covers) { + if (clip != NULL) { + lv_draw_buf_clear(self->lv_buf, clip); + } else { + _clear_changed_cells(self, full); + } + } + + uint32_t tiles_w = self->width_in_tiles; + for (uint32_t cell = 0; cell < cells; cell++) { + if (!full && !_cell_is_marked(self, cell)) { + continue; + } + uint32_t cx = cell % tiles_w; + uint32_t cy = cell / tiles_w; + lv_area_t cell_area = { + .x1 = cx * self->tile_width, + .y1 = cy * self->tile_height, + }; + cell_area.x2 = cell_area.x1 + self->tile_width - 1; + cell_area.y2 = cell_area.y1 + self->tile_height - 1; + + if (self->lv_src != NULL && self->lv_src->data != NULL) { + uint16_t x0, y0; + uint16_t tile_index = _tile_index(self, cell); + bool blank = tile_index == DISPLAYIO_TILEGRID_BLANK_TILE; + if (!(blank && skip_blank)) { + _tile_origin(self, tile_index, &x0, &y0); + if (!blank) { + DISPLAYIO_TILEGRID_DEBUG( + "compose %p cell %d (%d,%d) tile %d origin (%d,%d) full %d", + self, cell, cx, cy, tile_index, x0, y0, full); + } + drawn_cell_area = cell_area; + lv_draw_image_dsc_t dsc; + lv_draw_image_dsc_init(&dsc); + dsc.src = self->lv_src; + dsc.antialias = 0; + layer._clip_area = clip != NULL ? *clip : cell_area; + // The whole atlas is placed so that the tile's origin lands on the cell's corner; + // the clip above limits the draw to the cell. + int32_t dest_x = cell_area.x1 - (int32_t)x0; + int32_t dest_y = cell_area.y1 - (int32_t)y0; + lv_area_t coords = { + .x1 = dest_x, + .y1 = dest_y, + .x2 = dest_x + (int32_t)self->lv_src->header.w - 1, + .y2 = dest_y + (int32_t)self->lv_src->header.h - 1, + }; + lv_draw_image(&layer, &dsc, &coords); + layer._clip_area = layer_clip; + queued++; + if (queued == DISPLAYIO_LVGL_COMPOSE_BATCH) { + lv_canvas_finish_layer(self->lv_canvas, &layer); + // A big compose (a re-rendered text grid) can outlast the audio buffers. + if (displayio_lvgl_refresh_yield) { + RUN_BACKGROUND_TASKS; + } + lv_canvas_init_layer(self->lv_canvas, &layer); + queued = 0; + } + } + } + _clear_cell(self, cell); + lv_area_t cell_display; + _cell_display_area(self, cx, cy, &cell_display); + if (clip != NULL) { + // Identity grid: buffer, cell and grid coordinates are the same. + cell_area = *clip; + cell_display = *clip; + } + if (!any) { + buf_dirty = cell_area; + *dirty = cell_display; + any = true; + } else { + _union_area(&buf_dirty, &cell_area); + _union_area(dirty, &cell_display); + } + } + self->lv_dirty_count = 0; + self->lv_full_dirty = false; + + if (!any) { + DISPLAYIO_TILEGRID_DEBUG("compose %p drew nothing: src %p srcdata %p buf %d x %d", + self, self->lv_src, self->lv_src == NULL ? NULL : self->lv_src->data, + (int)self->lv_buf->header.w, (int)self->lv_buf->header.h); + } + + lv_canvas_finish_layer(self->lv_canvas, &layer); + if (any) { + _duplicate_fractional_edges(self, &buf_dirty); + // The compose pass may have run in software, so write those lines out before a DMA + // consumer (the display flush, or the PPA on the display pass) reads the buffer. + lv_draw_buf_flush_cache(self->lv_buf, &buf_dirty); + if (drawn_cell_area.x2 < drawn_cell_area.x1) { + DISPLAYIO_TILEGRID_DEBUG("compose %p done, nothing drawn", self); + return any; + } + #if DISPLAYIO_TILEGRID_DEBUG_ENABLED + // Did the draw actually put pixels in the buffer? Zero here means the compose draw wrote + // nothing, so the problem is upstream of the views; non-zero means the buffer has content + // and the display side is at fault. Scans the composed cell, so it only runs when the + // logging that uses it is compiled in. + uint32_t stride = self->lv_buf->header.stride; + uint32_t bpp = lv_color_format_get_size(self->lv_buf->header.cf); + const uint8_t *sample = self->lv_buf->data + drawn_cell_area.y1 * stride + + drawn_cell_area.x1 * bpp; + uint32_t nonzero = 0; + for (int32_t y = 0; y <= drawn_cell_area.y2 - drawn_cell_area.y1; y++) { + for (int32_t x = 0; x < (drawn_cell_area.x2 - drawn_cell_area.x1 + 1) * (int32_t)bpp; x++) { + nonzero += sample[y * stride + x] != 0; + } + } + DISPLAYIO_TILEGRID_DEBUG("compose %p done buf %p cell (%d,%d)-(%d,%d) nonzero %lu", + self, self->lv_buf->data, (int)drawn_cell_area.x1, (int)drawn_cell_area.y1, + (int)drawn_cell_area.x2, (int)drawn_cell_area.y2, (unsigned long)nonzero); + #endif + } + return any; +} + +// --- Refresh --------------------------------------------------------------- + +static void _refresh(displayio_tilegrid_t *self) { + if (!self->lv_work) { + return; + } + if (self->lv_obj == NULL) { + self->lv_work = false; + DISPLAYIO_TILEGRID_DEBUG("refresh %p unattached, dropping work", self); + return; + } + lv_display_t *display = lv_obj_get_display(self->lv_obj); + if (display == NULL) { + DISPLAYIO_TILEGRID_DEBUG("refresh %p no display, work stays pending", self); + return; + } + DISPLAYIO_TILEGRID_DEBUG("refresh %p direct %d buf %p canvas %p full %d views %d dirty %lu", + self, self->lv_direct, self->lv_buf, self->lv_canvas, self->lv_full_dirty, + self->lv_views_dirty, (unsigned long)self->lv_dirty_count); + DISPLAYIO_TILEGRID_DEBUG("refresh %p obj %dx%d at (%d,%d) scale %u hidden %d", + self, (int)lv_obj_get_width(self->lv_obj), (int)lv_obj_get_height(self->lv_obj), + (int)lv_obj_get_x(self->lv_obj), (int)lv_obj_get_y(self->lv_obj), (unsigned)self->lv_scale, + (int)lv_obj_has_flag(self->lv_obj, LV_OBJ_FLAG_HIDDEN)); + bool full = self->lv_full_dirty || self->lv_views_dirty; + bool changed = false; + lv_area_t dirty = {0, 0, -1, -1}; + + // Batch: the compose pass rewrites many objects and only the final invalidation matters. + lv_display_enable_invalidation(display, false); + if (self->lv_direct) { + // The view is the source pixels, so a content change is a plain invalidation. + changed = self->lv_src_dirty; + // Direct sources can still need a cached conversion (RGB565_SWAPPED, for + // example). Pixel writes must invalidate that decode just like composed sources. + if (changed && self->lv_src != NULL) { + lv_image_cache_drop(self->lv_src); + } + if (changed && _is_identity(self)) { + dirty.x1 = self->lv_src_x1; + dirty.y1 = self->lv_src_y1; + dirty.x2 = self->lv_src_x2 - 1; + dirty.y2 = self->lv_src_y2 - 1; + } + self->lv_src_dirty = false; + if (self->lv_views_dirty) { + _layout_views(self); + } + // Composed grids clear this in _compose(); direct grids have no compose pass. + self->lv_full_dirty = false; + } else { + if (!_ensure_buffer(self)) { + // Out of memory (or a zero-sized grid): there is nothing to compose into. Keep the + // pending work (lv_full_dirty/lv_dirty_count) so the next invalidation retries, but + // don't invalidate here. Invalidating is what makes LVGL run a refresh, and the + // refresh is what calls this function, so invalidating on failure spins the renderer + // at 100% retrying the allocation (and flooding the log) forever. + lv_display_enable_invalidation(display, true); + self->lv_work = false; + DISPLAYIO_TILEGRID_DEBUG("refresh %p no buffer, backing off", self); + return; + } + // A bitmap write is the only pending change to a single-cell identity grid: recompose + // just the written pixels instead of the whole cell. + lv_area_t written; + bool partial = _is_identity(self) && self->lv_src_dirty && !self->lv_full_dirty && + !self->lv_views_dirty && self->lv_dirty_count == 0; + if (partial) { + written.x1 = LV_MAX(self->lv_src_x1, 0); + written.y1 = LV_MAX(self->lv_src_y1, 0); + written.x2 = LV_MIN(self->lv_src_x2, (int32_t)self->tile_width) - 1; + written.y2 = LV_MIN(self->lv_src_y2, (int32_t)self->tile_height) - 1; + partial = written.x2 >= written.x1 && written.y2 >= written.y1; + } + _sync_source(self); + if (self->lv_views_dirty) { + _layout_views(self); + } + changed = _compose(self, partial ? &written : NULL, &dirty); + } + lv_display_enable_invalidation(display, true); + + if (full || changed) { + lv_area_t area; + lv_obj_get_coords(self->lv_obj, &area); + if (!full && dirty.x2 >= dirty.x1) { + lv_area_move(&dirty, area.x1, area.y1); + DISPLAYIO_TILEGRID_DEBUG("refresh %p invalidate area (%d,%d)-(%d,%d)", + self, (int)dirty.x1, (int)dirty.y1, (int)dirty.x2, (int)dirty.y2); + lv_obj_invalidate_area(self->lv_obj, &dirty); + } else { + DISPLAYIO_TILEGRID_DEBUG("refresh %p invalidate whole obj at (%d,%d)-(%d,%d)", + self, (int)area.x1, (int)area.y1, (int)area.x2, (int)area.y2); + lv_obj_invalidate(self->lv_obj); + } + } else { + DISPLAYIO_TILEGRID_DEBUG("refresh %p nothing to invalidate", self); + } + self->lv_work = false; +} + +void displayio_lvgl_tilegrid_refresh_all(void) { + for (displayio_tilegrid_t *self = mirror_head; self != NULL; self = self->lv_next) { + _refresh(self); + } +} + +// --- Bitmap and Palette plumbing ------------------------------------------ + +void displayio_lvgl_tilegrid_bitmap_changed(displayio_bitmap_t *bitmap, int16_t x1, int16_t y1, + int16_t x2, int16_t y2) { + if (bitmap->lv_watch_head == NULL) { + return; + } + displayio_lvgl_lock(); + bool gone = bitmap->data == NULL; + for (displayio_tilegrid_t *self = bitmap->lv_watch_head; self != NULL; + self = self->lv_bitmap_next) { + if (self->lv_obj == NULL) { + continue; + } + if (gone) { + // A cached decoder can borrow the Bitmap's pixels too. Drop it while the + // storage still exists, then stop the source descriptor from exposing it. + if (self->lv_src == &self->lv_src_dsc) { + lv_image_cache_drop(self->lv_src); + self->lv_src_dsc.data = NULL; + } + _mark_all(self); + _mark_views(self); + continue; + } + if (self->lv_src_dirty) { + self->lv_src_x1 = LV_MIN(self->lv_src_x1, x1); + self->lv_src_y1 = LV_MIN(self->lv_src_y1, y1); + self->lv_src_x2 = LV_MAX(self->lv_src_x2, x2); + self->lv_src_y2 = LV_MAX(self->lv_src_y2, y2); + } else { + self->lv_src_x1 = x1; + self->lv_src_y1 = y1; + self->lv_src_x2 = x2; + self->lv_src_y2 = y2; + self->lv_src_dirty = true; + } + if (_is_identity(self) && !self->lv_full_dirty && + lv_obj_get_display(self->lv_obj) != NULL) { + // Wake LVGL once per batch of writes, for the first written pixels instead of the + // whole grid. The refresh then invalidates everything written since (lv_src_*). + if (self->lv_work) { + continue; + } + lv_area_t area = { x1, y1, x2 - 1, y2 - 1 }; + lv_area_t obj_coords; + lv_obj_get_coords(self->lv_obj, &obj_coords); + lv_area_move(&area, obj_coords.x1, obj_coords.y1); + // LVGL drops an invalidation it can't see, so only rely on a visible one. + if (lv_obj_area_is_visible(self->lv_obj, &area)) { + self->lv_work = true; + lv_obj_invalidate_area(self->lv_obj, &area); + continue; + } + } + _mark_work(self); + } + displayio_lvgl_unlock(); +} + +void displayio_lvgl_tilegrid_shader_changed(displayio_tilegrid_t *self) { + if (self->lv_obj == NULL) { + return; + } + nlr_jump_callback_node_t cleanup; + displayio_lvgl_lock_with_cleanup(&cleanup); + if (self->lv_src == &self->lv_src_dsc) { + // The shared palette array was updated in place, so only the decoded view is stale. + lv_image_cache_drop(self->lv_src); + } + if (!self->lv_direct) { + // Gaining or losing transparency changes the composed buffer's format. + lv_color_format_t cf = _source_cf(self->bitmap, self->pixel_shader); + bool argb = _source_has_alpha(self, cf); + if (argb != self->lv_argb) { + self->lv_argb = argb; + _mark_views(self); + } + } + _mark_all(self); + displayio_lvgl_unlock_with_cleanup(); +} + +// --- Lifecycle ------------------------------------------------------------- + +// Bind the source for the current bitmap and pixel shader and schedule a full compose. Caller +// holds the lock and has no source bound. +static bool _rebind(displayio_tilegrid_t *self) { + self->lv_direct = _wants_direct(self); + if (!_bind_source(self)) { + return false; + } + // The supervisor resizes and positions its static terminal grids directly before + // rebinding their bitmap. Keep the mirror geometry in sync too: resizing the canvas + // or its views does not resize or move their container, and LVGL clips invalidation + // to that container even when OVERFLOW_VISIBLE is set. + lv_obj_set_size(self->lv_obj, displayio_lvgl_scale_coordinate(self->pixel_width, self->lv_scale), + displayio_lvgl_scale_coordinate(self->pixel_height, self->lv_scale)); + _set_lv_pos(self); + _mark_all(self); + _mark_views(self); + return true; +} + +void displayio_lvgl_tilegrid_attach(displayio_tilegrid_t *self, lv_obj_t *parent) { + if (!self->in_group || parent == NULL) { + return; + } + // ESP_LOGI(TAG, "attaching tilegrid %p to parent %p", self, parent); + nlr_jump_callback_node_t cleanup; + displayio_lvgl_lock_with_cleanup(&cleanup); + if (self->lv_obj == NULL) { + if (_create_objects(self, parent)) { + _rebind(self); + _set_lv_pos(self); + _link_mirror(self); + } else { + // Do not root a failed attachment forever. Discard a partially created + // container too; a later group sync can retry attaching it. + _destroy_objects(self); + } + } else if (lv_obj_get_parent(self->lv_obj) != parent) { + lv_obj_set_parent(self->lv_obj, parent); + } + displayio_lvgl_unlock_with_cleanup(); +} + +void displayio_lvgl_tilegrid_detach(displayio_tilegrid_t *self) { + displayio_lvgl_lock(); + _unbind_source(self); + _destroy_objects(self); + _unlink_mirror(self); + // This allocation is outside the Python heap, so collecting the TileGrid cannot + // free it. Drop it even when attachment failed before creating an LVGL object. + lv_free(self->lv_cell_dirty); + self->lv_cell_dirty = NULL; + self->lv_cell_words = 0; + self->lv_dirty_count = 0; + self->lv_full_dirty = true; + self->lv_views_dirty = true; + self->lv_src_dirty = false; + self->lv_work = false; + displayio_lvgl_unlock(); +} + +// Apply the inherited scale chain to the grid. TileGrids have no scale of their own; they render +// at the scale of the parent group chain. +void displayio_lvgl_tilegrid_update_scale(displayio_tilegrid_t *self) { + if (self->lv_obj == NULL) { + return; + } + nlr_jump_callback_node_t cleanup; + displayio_lvgl_lock_with_cleanup(&cleanup); + bool was_direct = self->lv_direct; + if (was_direct != _wants_direct(self)) { + // Fractional direct images need the composed path's edge padding. + _unbind_source(self); + if (!was_direct && self->lv_buf != NULL) { + lv_draw_buf_destroy(self->lv_buf); + self->lv_buf = NULL; + } + _rebind(self); + } else if (mp_obj_is_type(self->bitmap, &displayio_ondiskbitmap_type) && self->lv_direct && + (self->lv_scale != LV_SCALE_NONE) != self->lv_src_odb_full) { + // Re-source: whether the file's rows can be streamed changed with the scale. + _unbind_source(self); + _bind_source(self); + } + if (!self->lv_direct) { + lv_obj_set_size(self->lv_obj, displayio_lvgl_scale_coordinate(self->pixel_width, self->lv_scale), + displayio_lvgl_scale_coordinate(self->pixel_height, self->lv_scale)); + } + for (uint8_t i = 0; i < DISPLAYIO_LVGL_TILEGRID_VIEWS; i++) { + if (self->lv_views[i] != NULL) { + _set_view_scale(self->lv_views[i], self->lv_scale); + } + } + _set_lv_pos(self); + _mark_views(self); + displayio_lvgl_unlock_with_cleanup(); +} + +// protocol_lvgl implementation. Group owns the tree; these only translate its calls into the +// TileGrid mirror operations above. +// +// A Python subclass of TileGrid (a Label, a RoundRect, ...) is an mp_obj_instance_t that holds +// the native TileGrid in subobj[0], so every function below has to see that native object +// instead of the instance. Resolving it here keeps the type slot on the native type. +static mp_obj_t _tilegrid_protocol_self(mp_obj_t layer) { + mp_obj_t native = mp_obj_cast_to_native_base(layer, MP_OBJ_FROM_PTR(&displayio_tilegrid_type)); + if (native == MP_OBJ_NULL) { + return layer; + } + mp_obj_assert_native_inited(native); + return native; +} + +static lv_obj_t *_tilegrid_protocol_root_obj(mp_obj_t layer) { + return ((displayio_tilegrid_t *)MP_OBJ_TO_PTR(layer))->lv_obj; +} + +static void _tilegrid_protocol_attach(mp_obj_t layer, lv_obj_t *parent) { + displayio_lvgl_tilegrid_attach(MP_OBJ_TO_PTR(layer), parent); +} + +static void _tilegrid_protocol_detach(mp_obj_t layer) { + displayio_lvgl_tilegrid_detach(MP_OBJ_TO_PTR(layer)); +} + +static bool _tilegrid_protocol_set_transform(mp_obj_t layer, int32_t abs_x, int32_t abs_y, + uint32_t scale) { + displayio_tilegrid_t *self = MP_OBJ_TO_PTR(layer); + // A TileGrid has no position or scale of its own: it places itself from the parent + // origin plus its own x/y, and renders at the scale of the parent chain. + self->lv_scale = scale; + self->lv_origin_x = abs_x; + self->lv_origin_y = abs_y; + if (self->lv_obj != NULL) { + displayio_lvgl_lock(); + _set_lv_pos(self); + displayio_lvgl_unlock(); + displayio_lvgl_tilegrid_update_scale(self); + } + return true; +} + +static void _tilegrid_protocol_set_hidden_by_parent(mp_obj_t layer, bool hidden) { + displayio_tilegrid_set_hidden_by_parent(MP_OBJ_TO_PTR(layer), hidden); +} + +static bool _tilegrid_protocol_set_in_group(mp_obj_t layer, bool in_group) { + displayio_tilegrid_t *self = MP_OBJ_TO_PTR(layer); + bool was_in_group = self->in_group; + self->in_group = in_group; + return was_in_group; +} + +const lvgl_protocol_t displayio_lvgl_tilegrid_protocol = { + MP_PROTO_IMPLEMENT(MP_QSTR_protocol_lvgl) + .protocol_self = _tilegrid_protocol_self, + .root_obj = _tilegrid_protocol_root_obj, + .attach = _tilegrid_protocol_attach, + .detach = _tilegrid_protocol_detach, + .set_transform = _tilegrid_protocol_set_transform, + .set_hidden_by_parent = _tilegrid_protocol_set_hidden_by_parent, + .set_in_group = _tilegrid_protocol_set_in_group, +}; + +// --- displayio API --------------------------------------------------------- + +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, uint16_t default_tile) { + // Raise before anything is allocated if LVGL can't draw this combination. + _source_cf(bitmap, pixel_shader); + + uint32_t total_tiles = width * height; + self->bitmap_width_in_tiles = bitmap_width_in_tiles; + self->tiles_in_bitmap = bitmap_width_in_tiles * bitmap_height_in_tiles; + + // Determine if we need uint16_t or uint8_t for tile indices + bool use_uint16 = self->tiles_in_bitmap > 255; + + // ESP_LOGI(TAG, "allocating tile grid %d x %d", width, height); + if (use_uint16) { + uint16_t *tiles16 = (uint16_t *)m_malloc_without_collect(total_tiles * sizeof(uint16_t)); + for (uint32_t i = 0; i < total_tiles; i++) { + tiles16[i] = default_tile; + } + self->tiles = tiles16; + } else { + uint8_t *tiles8 = (uint8_t *)m_malloc_without_collect(total_tiles); + for (uint32_t i = 0; i < total_tiles; i++) { + tiles8[i] = (uint8_t)default_tile; + } + self->tiles = tiles8; + } + + self->width_in_tiles = width; + self->height_in_tiles = height; + self->x = x; + self->y = y; + self->pixel_width = width * tile_width; + self->pixel_height = height * tile_height; + self->tile_width = tile_width; + self->tile_height = tile_height; + self->bitmap = bitmap; + self->pixel_shader = pixel_shader; + self->in_group = false; + self->hidden = false; + self->hidden_by_parent = false; + self->flip_x = false; + self->flip_y = false; + self->transpose_xy = false; + self->top_left_x = 0; + self->top_left_y = 0; + self->lv_obj = NULL; + self->lv_canvas = NULL; + self->lv_buf = NULL; + self->lv_src = NULL; + self->lv_cell_dirty = NULL; + self->lv_cell_words = 0; + self->lv_dirty_count = 0; + self->lv_full_dirty = true; + self->lv_work = false; + self->lv_views_dirty = true; + self->lv_src_dirty = false; + self->lv_direct = false; + self->lv_src_odb_full = false; + self->lv_argb = false; + self->lv_view_count = 0; + self->lv_next = NULL; + self->lv_bitmap_next = NULL; + self->lv_scale = LV_SCALE_NONE; + self->lv_origin_x = 0; + self->lv_origin_y = 0; + for (uint8_t i = 0; i < DISPLAYIO_LVGL_TILEGRID_VIEWS; i++) { + self->lv_views[i] = NULL; + } + lv_memzero(&self->lv_src_dsc, sizeof(self->lv_src_dsc)); + lv_memzero(self->lv_view_dsc, sizeof(self->lv_view_dsc)); +} + +bool common_hal_displayio_tilegrid_get_hidden(displayio_tilegrid_t *self) { + return self->hidden; +} + +bool displayio_tilegrid_get_rendered_hidden(displayio_tilegrid_t *self) { + (void)self; + return false; +} + +void displayio_tilegrid_set_hidden_by_parent(displayio_tilegrid_t *self, bool hidden) { + self->hidden_by_parent = hidden; + if (self->lv_obj != NULL) { + displayio_lvgl_lock(); + if (self->hidden || self->hidden_by_parent) { + lv_obj_add_flag(self->lv_obj, LV_OBJ_FLAG_HIDDEN); + } else { + lv_obj_clear_flag(self->lv_obj, LV_OBJ_FLAG_HIDDEN); + } + displayio_lvgl_unlock(); + } +} + +void common_hal_displayio_tilegrid_set_hidden(displayio_tilegrid_t *self, bool hidden) { + self->hidden = hidden; + displayio_tilegrid_set_hidden_by_parent(self, self->hidden_by_parent); +} + +// Mark the cell of the tile matrix that shows tile (x, y) of the grid for recomposing. +void displayio_tilegrid_mark_tile_dirty(displayio_tilegrid_t *self, uint16_t x, uint16_t y) { + if (self->lv_obj == NULL || self->width_in_tiles == 0 || self->height_in_tiles == 0) { + // Not mirrored yet; binding composes everything. + return; + } + displayio_lvgl_lock(); + uint32_t cell = (uint32_t)(y % self->height_in_tiles) * self->width_in_tiles + + (x % self->width_in_tiles); + _mark_cell(self, cell); + displayio_lvgl_unlock(); +} + +mp_int_t common_hal_displayio_tilegrid_get_x(displayio_tilegrid_t *self) { + return self->x; +} + +void common_hal_displayio_tilegrid_set_x(displayio_tilegrid_t *self, mp_int_t x) { + if (self->x == x) { + return; + } + self->x = x; + if (self->lv_obj != NULL) { + displayio_lvgl_lock(); + _set_lv_pos(self); + displayio_lvgl_unlock(); + } +} + +mp_int_t common_hal_displayio_tilegrid_get_y(displayio_tilegrid_t *self) { + return self->y; +} + +void common_hal_displayio_tilegrid_set_y(displayio_tilegrid_t *self, mp_int_t y) { + if (self->y == y) { + return; + } + self->y = y; + if (self->lv_obj != NULL) { + displayio_lvgl_lock(); + _set_lv_pos(self); + displayio_lvgl_unlock(); + } +} + +mp_obj_t common_hal_displayio_tilegrid_get_pixel_shader(displayio_tilegrid_t *self) { + return self->pixel_shader; +} + +void common_hal_displayio_tilegrid_set_pixel_shader(displayio_tilegrid_t *self, mp_obj_t pixel_shader) { + _source_cf(self->bitmap, pixel_shader); + if (self->lv_obj == NULL) { + self->pixel_shader = pixel_shader; + return; + } + nlr_jump_callback_node_t cleanup; + displayio_lvgl_lock_with_cleanup(&cleanup); + // Give up the old shader's source while the descriptor still belongs to it. + _unbind_source(self); + self->pixel_shader = pixel_shader; + _rebind(self); + displayio_lvgl_unlock_with_cleanup(); +} + +mp_obj_t common_hal_displayio_tilegrid_get_bitmap(displayio_tilegrid_t *self) { + return self->bitmap; +} + +void common_hal_displayio_tilegrid_set_bitmap(displayio_tilegrid_t *self, mp_obj_t bitmap) { + _source_cf(bitmap, self->pixel_shader); + if (self->lv_obj == NULL) { + self->bitmap = bitmap; + return; + } + nlr_jump_callback_node_t cleanup; + displayio_lvgl_lock_with_cleanup(&cleanup); + bool linked = _is_linked(self); + // Release the old bitmap's source before the reference to it is replaced. + _unbind_source(self); + if (linked) { + _unwatch_bitmap(self); + } + self->bitmap = bitmap; + _rebind(self); + if (linked) { + _watch_bitmap(self); + } + displayio_lvgl_unlock_with_cleanup(); +} + +uint16_t common_hal_displayio_tilegrid_get_width(displayio_tilegrid_t *self) { + return self->width_in_tiles; +} + +uint16_t common_hal_displayio_tilegrid_get_height(displayio_tilegrid_t *self) { + return self->height_in_tiles; +} + +uint16_t common_hal_displayio_tilegrid_get_tile_width(displayio_tilegrid_t *self) { + return self->tile_width; +} + +uint16_t common_hal_displayio_tilegrid_get_tile_height(displayio_tilegrid_t *self) { + return self->tile_height; +} + +uint16_t common_hal_displayio_tilegrid_get_tile(displayio_tilegrid_t *self, uint16_t x, uint16_t y) { + if (self->tiles == NULL) { + return 0; + } + + uint32_t index = y * self->width_in_tiles + x; + if (self->tiles_in_bitmap > 255) { + return ((uint16_t *)self->tiles)[index]; + } + return ((uint8_t *)self->tiles)[index]; +} + +void common_hal_displayio_tilegrid_set_tile(displayio_tilegrid_t *self, uint16_t x, uint16_t y, uint16_t tile_index) { + if (tile_index >= self->tiles_in_bitmap) { + mp_raise_ValueError(MP_ERROR_TEXT("Tile index out of bounds")); + } + + if (self->tiles == NULL) { + return; + } + + uint32_t index = y * self->width_in_tiles + x; + uint16_t old_tile_index; + if (self->tiles_in_bitmap > 255) { + old_tile_index = ((uint16_t *)self->tiles)[index]; + ((uint16_t *)self->tiles)[index] = tile_index; + } else { + old_tile_index = ((uint8_t *)self->tiles)[index]; + ((uint8_t *)self->tiles)[index] = (uint8_t)tile_index; + } + if (old_tile_index != tile_index && tile_index != DISPLAYIO_TILEGRID_BLANK_TILE) { + DISPLAYIO_TILEGRID_DEBUG( + "set_tile %p (%d,%d) tile %d -> %d cell %d mirrored %d", + self, x, y, old_tile_index, tile_index, index, + self->lv_obj != NULL && self->width_in_tiles != 0 && self->height_in_tiles != 0); + } + displayio_tilegrid_mark_tile_dirty(self, x, y); +} + +void common_hal_displayio_tilegrid_set_all_tiles(displayio_tilegrid_t *self, uint16_t tile_index) { + if (tile_index >= self->tiles_in_bitmap) { + mp_raise_ValueError(MP_ERROR_TEXT("Tile index out of bounds")); + } + + if (self->tiles == NULL) { + return; + } + + uint32_t changed = 0; + if (self->tiles_in_bitmap > 255) { + uint16_t *tiles16 = (uint16_t *)self->tiles; + for (uint16_t y = 0; y < self->height_in_tiles; y++) { + for (uint16_t x = 0; x < self->width_in_tiles; x++) { + uint32_t i = y * self->width_in_tiles + x; + if (tiles16[i] != tile_index) { + changed++; + } + tiles16[i] = tile_index; + } + } + } else { + uint8_t *tiles8 = (uint8_t *)self->tiles; + for (uint16_t y = 0; y < self->height_in_tiles; y++) { + for (uint16_t x = 0; x < self->width_in_tiles; x++) { + uint32_t i = y * self->width_in_tiles + x; + if (tiles8[i] != (uint8_t)tile_index) { + changed++; + } + tiles8[i] = (uint8_t)tile_index; + } + } + } + if (changed > 0) { + DISPLAYIO_TILEGRID_DEBUG( + "set_all_tiles %p tile %d changed %d of %d cells mirrored %d", + self, tile_index, changed, self->width_in_tiles * self->height_in_tiles, + self->lv_obj != NULL); + } + + if (self->lv_obj != NULL) { + displayio_lvgl_lock(); + _mark_all(self); + displayio_lvgl_unlock(); + } +} + +bool common_hal_displayio_tilegrid_get_flip_x(displayio_tilegrid_t *self) { + return self->flip_x; +} + +void common_hal_displayio_tilegrid_set_flip_x(displayio_tilegrid_t *self, bool flip_x) { + if (self->flip_x == flip_x) { + return; + } + if (flip_x) { + _raise_unsupported(); + } + self->flip_x = flip_x; + if (self->lv_obj != NULL) { + displayio_lvgl_lock(); + _mark_all(self); + displayio_lvgl_unlock(); + } +} + +bool common_hal_displayio_tilegrid_get_flip_y(displayio_tilegrid_t *self) { + return self->flip_y; +} + +void common_hal_displayio_tilegrid_set_flip_y(displayio_tilegrid_t *self, bool flip_y) { + if (self->flip_y == flip_y) { + return; + } + if (flip_y) { + _raise_unsupported(); + } + self->flip_y = flip_y; + if (self->lv_obj != NULL) { + displayio_lvgl_lock(); + _mark_all(self); + displayio_lvgl_unlock(); + } +} + +bool common_hal_displayio_tilegrid_get_transpose_xy(displayio_tilegrid_t *self) { + return self->transpose_xy; +} + +void common_hal_displayio_tilegrid_set_transpose_xy(displayio_tilegrid_t *self, bool transpose_xy) { + if (self->transpose_xy == transpose_xy) { + return; + } + if (transpose_xy) { + _raise_unsupported(); + } + self->transpose_xy = transpose_xy; + if (self->lv_obj != NULL) { + displayio_lvgl_lock(); + _mark_all(self); + displayio_lvgl_unlock(); + } +} + +bool common_hal_displayio_tilegrid_contains(displayio_tilegrid_t *self, uint16_t x, uint16_t y) { + uint16_t right_edge = self->x + (self->width_in_tiles * self->tile_width); + uint16_t bottom_edge = self->y + (self->height_in_tiles * self->tile_height); + return x >= self->x && x < right_edge && + y >= self->y && y < bottom_edge; +} + +// Scrolling moves the window over the composed buffer, not the pixels: no cell is re-sourced and +// nothing is copied, the views just point somewhere else. +void common_hal_displayio_tilegrid_set_top_left(displayio_tilegrid_t *self, uint16_t x, uint16_t y) { + // Only the wrapped position matters; the buffer doesn't know the window moved. + uint16_t old_x = self->width_in_tiles == 0 ? 0 : self->top_left_x % self->width_in_tiles; + uint16_t old_y = self->height_in_tiles == 0 ? 0 : self->top_left_y % self->height_in_tiles; + uint16_t new_x = self->width_in_tiles == 0 ? 0 : x % self->width_in_tiles; + uint16_t new_y = self->height_in_tiles == 0 ? 0 : y % self->height_in_tiles; + self->top_left_x = x; + self->top_left_y = y; + if (old_x == new_x && old_y == new_y) { + // Same window: nothing moves. + return; + } + if (self->lv_obj != NULL) { + displayio_lvgl_lock(); + _mark_views(self); + displayio_lvgl_unlock(); + } +} + +#endif // CIRCUITPY_DISPLAYIO_LVGL diff --git a/shared-module/displayio/lvgl/TileGrid.h b/shared-module/displayio/lvgl/TileGrid.h new file mode 100644 index 00000000000..045847536f2 --- /dev/null +++ b/shared-module/displayio/lvgl/TileGrid.h @@ -0,0 +1,117 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include + +#include "py/obj.h" +#include "shared-module/displayio/Bitmap.h" +#include "shared-module/displayio/Palette.h" +#include "shared-module/displayio/lvgl/lvgl_protocol.h" + +#include "lvgl.h" + +// LVGL-based version of displayio TileGrid. +// +// A TileGrid owns one composed buffer holding exactly one tile grid of pixels, in tile-matrix +// order: cell (i, j) of tiles[] is at (i * tile_width, j * tile_height). The tiles are drawn +// into it through LVGL's draw pipeline, so the palette and the tile indirection are resolved +// once, when a cell changes, instead of on every frame. +// +// The display shows that buffer through up to four lv_images ("views"), because displayio +// scrolls by moving a wrapped window over the tile matrix. A scroll re-points the views and +// invalidates; no pixels move. See lvgl/TileGrid.c for the whole design. +// +// Dirty tracking: the buffer is composed at the start of an LVGL refresh (see +// displayio_lvgl_tilegrid_refresh_all()), so the write path only has to set bits. + +// A wrapped window over the composed buffer is at most two row runs by two column runs. +#define DISPLAYIO_LVGL_TILEGRID_VIEWS 4 + +typedef struct displayio_tilegrid { + mp_obj_base_t base; + mp_obj_t bitmap; + mp_obj_t pixel_shader; + int16_t x; + int16_t y; + uint16_t pixel_width; + uint16_t pixel_height; + uint16_t bitmap_width_in_tiles; + uint16_t tiles_in_bitmap; + uint16_t width_in_tiles; + uint16_t height_in_tiles; + uint16_t tile_width; + uint16_t tile_height; + uint16_t top_left_x; + uint16_t top_left_y; + void *tiles; // Can be either uint8_t* or uint16_t* depending on tiles_in_bitmap + bool in_group : 1; + bool flip_x : 1; + bool flip_y : 1; + bool transpose_xy : 1; + bool hidden : 1; + bool hidden_by_parent : 1; + uint16_t padding : 10; + // LVGL mirror state. + lv_obj_t *lv_obj; // Container of the views, or the single image on the direct path. + lv_obj_t *lv_views[DISPLAYIO_LVGL_TILEGRID_VIEWS]; + lv_image_dsc_t lv_view_dsc[DISPLAYIO_LVGL_TILEGRID_VIEWS]; + uint8_t lv_view_count; + lv_draw_buf_t *lv_buf; // Composed pixels; owned by lv_canvas once it exists. + lv_obj_t *lv_canvas; // Hidden canvas that hosts the compose layer. + // The source atlas: the whole bitmap as one LVGL image, drawn one cell at a time. + const lv_image_dsc_t *lv_src; + lv_image_dsc_t lv_src_dsc; // Our own descriptor for a Bitmap source. + // A single-cell grid of a direct color source shows those pixels as they are instead of + // copying them into a composed buffer. + bool lv_direct; + bool lv_src_odb_full; // lv_src is the whole-image OnDiskBitmap decode. + bool lv_argb; // Composed buffer carries alpha (the source has transparent pixels). + // Cells of the composed buffer that need composing, one bit per cell. + uint32_t *lv_cell_dirty; + uint32_t lv_cell_words; + uint32_t lv_dirty_count; + bool lv_full_dirty; + bool lv_work; // Has something to do at the next refresh. + bool lv_views_dirty; // The scroll window moved; re-point the views. + // Pixels of the source changed. Writers mark the area before they change it, so the + // next compose pass rereads the bitmap and recomposes the cells the area reaches. + int16_t lv_src_x1; + int16_t lv_src_y1; + int16_t lv_src_x2; + int16_t lv_src_y2; + bool lv_src_dirty; + struct displayio_tilegrid *lv_next; // The compositor's list of attached TileGrids. + struct displayio_tilegrid *lv_bitmap_next; // The Bitmap's list of grids drawing it. + uint32_t lv_scale; // Scale inherited from the parent group, in Q8 format. + int32_t lv_origin_x; // The parent group's origin in screen pixels. + int32_t lv_origin_y; +} displayio_tilegrid_t; + +void displayio_tilegrid_set_hidden_by_parent(displayio_tilegrid_t *self, bool hidden); +bool displayio_tilegrid_get_rendered_hidden(displayio_tilegrid_t *self); +void displayio_tilegrid_mark_tile_dirty(displayio_tilegrid_t *self, uint16_t x, uint16_t y); + +// TileGrid mirror lifecycle, implemented in TileGrid.c and called by Group.c. +void displayio_lvgl_tilegrid_attach(displayio_tilegrid_t *self, lv_obj_t *parent); +void displayio_lvgl_tilegrid_detach(displayio_tilegrid_t *self); +void displayio_lvgl_tilegrid_update_scale(displayio_tilegrid_t *self); + +// Compose whatever changed since the last refresh. Called at the start of every LVGL refresh, +// before anything is drawn, with the LVGL lock already held by the renderer. +void displayio_lvgl_tilegrid_refresh_all(void); +// The pixels of bitmap changed (or went away). Called from the Bitmap write path. +void displayio_lvgl_tilegrid_bitmap_changed(displayio_bitmap_t *bitmap, + int16_t x1, int16_t y1, int16_t x2, int16_t y2); +// The Palette this TileGrid draws with changed. +void displayio_lvgl_tilegrid_shader_changed(displayio_tilegrid_t *self); +// Root the attached TileGrids during GC. They live in a port-memory list. +void displayio_lvgl_tilegrid_gc_collect(void); + +// How Group attaches, positions and hides a TileGrid. See lvgl_protocol.h. +extern const lvgl_protocol_t displayio_lvgl_tilegrid_protocol; diff --git a/shared-module/displayio/lvgl/lvgl_internal.h b/shared-module/displayio/lvgl/lvgl_internal.h new file mode 100644 index 00000000000..340a40f8d52 --- /dev/null +++ b/shared-module/displayio/lvgl/lvgl_internal.h @@ -0,0 +1,97 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// Internal declarations shared by the files that implement the LVGL-based +// displayio compositing core (shared-module/displayio/lvgl/). + +#pragma once + +#include +#include + +#include "py/obj.h" +#include "py/nlr.h" +#include "shared-module/displayio/Group.h" +#include "shared-module/displayio/TileGrid.h" +#include "shared-module/displayio/Bitmap.h" +#include "shared-module/displayio/Palette.h" +#include "shared-module/displayio/OnDiskBitmap.h" +#include "shared-module/displayio/lvgl/ImageRoot.h" +#include "shared-module/displayio/lvgl/Palette.h" + +#if CIRCUITPY_DISPLAYIO_LVGL + +// LVGL image scales are Q8 fixed point: 256 means 1x. Use a 64-bit intermediate +// so nested groups and large coordinates cannot overflow the multiplication. +static inline int32_t displayio_lvgl_scale_coordinate(int32_t value, uint32_t scale) { + return (int32_t)(((int64_t)value * scale + (LV_SCALE_NONE / 2)) >> 8); +} + +static inline uint32_t displayio_lvgl_compose_scale(uint32_t parent, uint32_t own) { + return (uint32_t)(((uint64_t)parent * own + (LV_SCALE_NONE / 2)) >> 8); +} + +// Port hook: initialize LVGL itself and its tick source. Implemented by each port's +// common-hal and safe to call repeatedly. +void displayio_lvgl_port_init(void); + +// Port-supplied recursion-safe lock around LVGL. The RTOS renders LVGL on its own +// thread (e.g. a Zephyr workqueue or the ESP32 LVGL task), so CircuitPython-side mirror +// mutations must be excluded from rendering. The lock must be recursive: the shared +// wrappers may nest, and the render thread uses the same lock. +void displayio_lvgl_port_lock(void); +void displayio_lvgl_port_unlock(void); + +// Port hook: arrange for BusDisplay refreshes to run on the CircuitPython thread when the port +// renders LVGL on a task. Called once per BusDisplay, after its refresh timer exists. Ports that +// render BusDisplay on their own LVGL thread (Zephyr) do nothing. +void displayio_lvgl_port_install_busdisplay_refresh(lv_display_t *display); + +// Port hook: a framebuffer reached a frame boundary. May be called from an interrupt handler, so +// ports that have a render task must defer it safely and render on the task. In task context, the +// ESP port renders synchronously. +void displayio_lvgl_port_frame_boundary(void); + +// Shared lock wrappers. All display-side (CP thread) LVGL calls must happen inside these. +void displayio_lvgl_lock(void); +void displayio_lvgl_unlock(void); + +// CircuitPython-thread mutations that may raise must register an unlock on exception. +// The caller owns the stack node until unlock_with_cleanup(). Do not use these from +// the render task, which has no active Python exception/cleanup stack. +void displayio_lvgl_lock_with_cleanup(nlr_jump_callback_node_t *cleanup); +void displayio_lvgl_unlock_with_cleanup(void); + +// Set up LVGL for displayio. Called by the port's display constructor. +void displayio_lvgl_init(void); + +// Register displayio's per-display state: the screen background and the refresh hooks, including +// the compose pass that brings every attached TileGrid's buffer up to date before each refresh +// draws anything. Called once per LVGL display, after it is created (and made default). +void displayio_lvgl_register_display(lv_display_t *display); + +// True when the displays the compositor drives still want automatic repaints +// (display.auto_refresh). A port's render task consults this so turning auto_refresh off stops +// repaints without also stopping the rest of the port's background work. +bool displayio_lvgl_auto_refresh(void); + +// Render displays that can't flush from the LVGL task (currently BusDisplay when the port asks +// for it). Called on the CircuitPython thread by the port's proxy, under the LVGL lock. +void displayio_lvgl_refresh_unsafe_displays(void); + +// Render the framebuffer displays that pace themselves from a frame boundary. Called on the +// CircuitPython thread (directly or from the render task after an ISR notification), under the +// LVGL lock. +void displayio_lvgl_refresh_paced_displays(void); + +// True while an explicit display.refresh() renders on the CircuitPython thread. Long +// render steps (TileGrid compose, display flush) run background tasks when it is set. +extern bool displayio_lvgl_refresh_yield; + +// Attach/detach the compositor's root group. Implemented in lvgl/Group.c. NULL detach. +void displayio_lvgl_set_root_group(displayio_group_t *group); + +#endif // CIRCUITPY_DISPLAYIO_LVGL diff --git a/shared-module/displayio/lvgl/lvgl_protocol.h b/shared-module/displayio/lvgl/lvgl_protocol.h new file mode 100644 index 00000000000..a14b3a823ab --- /dev/null +++ b/shared-module/displayio/lvgl/lvgl_protocol.h @@ -0,0 +1,67 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include + +#include "py/obj.h" +#include "py/proto.h" + +#include "lvgl.h" + +// Everything an LVGL-backed displayio layer has to provide to displayio.Group, independent +// of its type. This is the LVGL counterpart of the scanline compositor's protocol_draw (see +// shared-bindings/vectorio/__init__.h): Group mirrors its members into the LVGL object tree +// through these calls and nothing else in the compositor needs to know what a member is. +// +// The layer owns its mirror. Once attached, LVGL owns the lv_obj, so a layer never sets the +// mirror's parent or z-order itself; Group does that through root_obj(). +// +// A type has a single protocol slot, so a layer implements either this (LVGL builds) or +// protocol_draw (legacy builds), never both. Each backend's dispatcher header picks the +// right object with a *_LVGL_PROTOCOL macro; it is NULL in legacy builds. +// +// Group calls every method above with the LVGL lock held, and passes the object protocol_self +// resolved. Implementations may take the lock again (it is depth counted). +typedef struct _lvgl_protocol_t { + MP_PROTOCOL_HEAD // MP_QSTR_protocol_lvgl + + // The object the rest of the calls are made on, or the layer itself when the protocol is + // implemented on the layer. This must resolve two things: vectorio's shapes (the + // Python-visible Rectangle, Circle or Polygon owns the wrapper that holds the shape's + // compositor state, so it forwards to that wrapper) and Python subclasses of a layer (a + // PageLayout, Tile or Label is an mp_obj_instance_t whose native base is in subobj[0]). + // May be NULL. + mp_obj_t (*protocol_self)(mp_obj_t self); + + // The layer's root lv_obj, or NULL before attach(). Group uses it for z-order and + // reparenting. + lv_obj_t *(*root_obj)(mp_obj_t self); + + // Create the mirror under parent if needed, reparent it, and push every Python-visible + // property into it. + void (*attach)(mp_obj_t self, lv_obj_t *parent); + + // Delete the mirror and any port allocations behind it, and clear root_obj. Must leave + // the layer reusable: a later attach() rebuilds the mirror. Does not touch group state. + void (*detach)(mp_obj_t self); + + // Push the inherited transform. abs_x/abs_y is the parent group's origin in screen + // pixels and scale is the composed scale of the whole ancestor chain; this layer's own + // position and scale are not applied here. scale is the composed scale in Q8 format + // (LV_SCALE_NONE is 1x). Return false when the layer can't be shown that way; Group then + // restores its own transform, pushes that again, and raises ValueError. + bool (*set_transform)(mp_obj_t self, int32_t abs_x, int32_t abs_y, uint32_t scale); + + // Propagate an ancestor's hidden state. NULL means always drawn while attached. + void (*set_hidden_by_parent)(mp_obj_t self, bool hidden); + + // Set or clear group membership, returning the previous value so Group can reject a + // layer that is already in one. NULL means the layer can't be a group member. + bool (*set_in_group)(mp_obj_t self, bool in_group); +} lvgl_protocol_t; diff --git a/shared-module/emmcio/__init__.c b/shared-module/emmcio/__init__.c new file mode 100644 index 00000000000..3eaab720ea6 --- /dev/null +++ b/shared-module/emmcio/__init__.c @@ -0,0 +1,104 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-module/emmcio/__init__.h" + +#if CIRCUITPY_EMMC_USB + +#include "py/mpstate.h" + +#include "extmod/vfs.h" +#include "extmod/vfs_fat.h" +#include "lib/oofatfs/ff.h" + +#include "supervisor/filesystem.h" +#include "supervisor/shared/safe_mode.h" +#include "supervisor/shared/settings.h" + +#include "shared-bindings/microcontroller/Pin.h" + +#include "common-hal/emmcio/EMMC.h" + +#if !defined(DEFAULT_EMMC_CLOCK) || !defined(DEFAULT_EMMC_COMMAND) || !defined(DEFAULT_EMMC_DATA) +#error "CIRCUITPY_EMMC_USB needs DEFAULT_EMMC_CLOCK, DEFAULT_EMMC_COMMAND and DEFAULT_EMMC_DATA in mpconfigboard.h" +#endif + +// RST_n and the I/O rail gate are optional: a board that hard-wires either one +// simply does not define it. +#ifndef DEFAULT_EMMC_RESET +#define DEFAULT_EMMC_RESET NULL +#endif +#ifndef DEFAULT_EMMC_VCCQ +#define DEFAULT_EMMC_VCCQ NULL +#endif + + +static mp_vfs_mount_t _emmc_vfs; +static fs_user_mount_t _emmc_usermount; + +static bool _tried; + +#define AUTOMOUNT_BUDGET_US 5000000u + +static void automount_give_up(void) { + common_hal_emmcio_emmc_clear_deadline(); + // Leave the card powered down and the pins released + emmcio_automount_abandon(); +} + +void automount_emmc(void) { + if (_tried) { + return; + } + _tried = true; + + if (get_safe_mode() != SAFE_MODE_NONE) { + return; + } + + bool enabled = true; + (void)settings_get_bool("CIRCUITPY_EMMC_USB", &enabled); + if (!enabled) { + return; + } + + common_hal_emmcio_emmc_set_deadline(AUTOMOUNT_BUDGET_US); + + mp_obj_t dev = emmcio_automount_construct(DEFAULT_EMMC_CLOCK, DEFAULT_EMMC_COMMAND, + DEFAULT_EMMC_DATA, DEFAULT_EMMC_RESET, DEFAULT_EMMC_VCCQ, true, true); + if (dev == MP_OBJ_NULL) { + automount_give_up(); + return; + } + + fs_user_mount_t *vfs = &_emmc_usermount; + vfs->base.type = &mp_fat_vfs_type; + vfs->fatfs.drv = vfs; + // Initialise underlying block device. + vfs->blockdev.block_size = FF_MIN_SS; + mp_vfs_blockdev_init(&vfs->blockdev, dev); + + if (f_mount(&vfs->fatfs) != FR_OK) { + automount_give_up(); + return; + } + + // Same as CIRCUITPY: while a host has the drive, the host owns writing. + filesystem_set_concurrent_write_protection((supervisor_vfs_t *)vfs, true); + filesystem_set_writable_by_usb((supervisor_vfs_t *)vfs, true); + + mp_vfs_mount_t *emmc_vfs = &_emmc_vfs; + emmc_vfs->str = CIRCUITPY_EMMC_MOUNT_PATH; + emmc_vfs->len = sizeof(CIRCUITPY_EMMC_MOUNT_PATH) - 1; + emmc_vfs->obj = MP_OBJ_FROM_PTR(&_emmc_usermount); + emmc_vfs->next = MP_STATE_VM(vfs_mount_table); + MP_STATE_VM(vfs_mount_table) = emmc_vfs; + + // The budget covers bring-up and the mount only + common_hal_emmcio_emmc_clear_deadline(); +} + +#endif // CIRCUITPY_EMMC_USB diff --git a/shared-module/emmcio/__init__.h b/shared-module/emmcio/__init__.h new file mode 100644 index 00000000000..5bef585e438 --- /dev/null +++ b/shared-module/emmcio/__init__.h @@ -0,0 +1,29 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +#if CIRCUITPY_EMMC_USB + +#ifndef CIRCUITPY_EMMC_MOUNT_PATH +#define CIRCUITPY_EMMC_MOUNT_PATH "/sd" +#endif + +void automount_emmc(void); + +bool emmcio_is_automounted(void); + +#else + +#include + +static inline bool emmcio_is_automounted(void) { + return false; +} + +#endif diff --git a/shared-module/epaperdisplay/EPaperDisplay.c b/shared-module/epaperdisplay/EPaperDisplay.c index 14fbc3341b5..3334763ad18 100644 --- a/shared-module/epaperdisplay/EPaperDisplay.c +++ b/shared-module/epaperdisplay/EPaperDisplay.c @@ -6,504 +6,19 @@ #include "shared-bindings/epaperdisplay/EPaperDisplay.h" -#include "py/gc.h" -#include "py/runtime.h" -#include "shared/runtime/interrupt_char.h" -#include "shared-bindings/displayio/ColorConverter.h" -#include "shared-bindings/microcontroller/Pin.h" -#include "shared-bindings/time/__init__.h" #include "shared-module/displayio/__init__.h" #include "supervisor/shared/display.h" -#include "supervisor/shared/tick.h" -#if CIRCUITPY_TINYUSB -#include "supervisor/usb.h" -#endif - -#include -#include - -#define DELAY 0x80 - -void common_hal_epaperdisplay_epaperdisplay_construct(epaperdisplay_epaperdisplay_obj_t *self, - mp_obj_t bus, const uint8_t *start_sequence, uint16_t start_sequence_len, mp_float_t start_up_time, - 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, - const uint8_t *refresh_sequence, uint16_t refresh_sequence_len, 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, bool acep, bool two_byte_sequence_length, bool address_little_endian) { - uint16_t color_depth = 1; - bool core_grayscale = true; - if (highlight_color != 0x000000) { - self->core.colorspace.tricolor = true; - self->core.colorspace.tricolor_hue = displayio_colorconverter_compute_hue(highlight_color); - self->core.colorspace.tricolor_luma = displayio_colorconverter_compute_luma(highlight_color); - } else { - self->core.colorspace.tricolor = false; - } - self->acep = acep; - self->core.colorspace.sevencolor = acep; - if (acep) { - color_depth = 4; // bits. 7 colors + clean - grayscale = false; - core_grayscale = false; - } - - displayio_display_core_construct(&self->core, width, height, rotation, color_depth, core_grayscale, true, 1, true, true); - displayio_display_bus_construct(&self->bus, bus, ram_width, ram_height, - colstart, rowstart, - set_column_window_command, set_row_window_command, set_current_column_command, set_current_row_command, - false /* data_as_commands */, chip_select, - false /* SH1107_addressing */, address_little_endian); - - self->write_black_ram_command = write_black_ram_command; - self->black_bits_inverted = black_bits_inverted; - self->write_color_ram_command = write_color_ram_command; - self->color_bits_inverted = color_bits_inverted; - self->refresh_time = refresh_time * 1000; - self->busy_state = busy_state; - self->refreshing = false; - self->milliseconds_per_frame = seconds_per_frame * 1000; - self->chip_select = chip_select ? CHIP_SELECT_TOGGLE_EVERY_BYTE : CHIP_SELECT_UNTOUCHED; - self->grayscale = grayscale; - - self->start_sequence = start_sequence; - self->start_sequence_len = start_sequence_len; - self->start_up_time_ms = start_up_time * 1000; - self->stop_sequence = stop_sequence; - self->stop_sequence_len = stop_sequence_len; - self->refresh_sequence = refresh_sequence; - self->refresh_sequence_len = refresh_sequence_len; - - self->busy.base.type = &mp_type_NoneType; - self->two_byte_sequence_length = two_byte_sequence_length; - if (busy_pin != NULL) { - self->busy.base.type = &digitalio_digitalinout_type; - common_hal_digitalio_digitalinout_construct(&self->busy, busy_pin); - common_hal_never_reset_pin(busy_pin); - } - - // Clear the color memory if it isn't in use. - if (highlight_color == 0x00 && write_color_ram_command != NO_COMMAND) { - // TODO: Clear - } - - // Set the group after initialization otherwise we may send pixels while we delay in - // initialization. - common_hal_epaperdisplay_epaperdisplay_set_root_group(self, &circuitpython_splash); -} - -bool common_hal_epaperdisplay_epaperdisplay_set_root_group(epaperdisplay_epaperdisplay_obj_t *self, displayio_group_t *root_group) { - return displayio_display_core_set_root_group(&self->core, root_group); -} - -static const displayio_area_t *epaperdisplay_epaperdisplay_get_refresh_areas(epaperdisplay_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; - if (self->core.current_group != NULL) { - first_area = displayio_group_get_refresh_areas(self->core.current_group, NULL); - } - if (first_area != NULL && self->bus.row_command == NO_COMMAND) { - // Do a full refresh if the display doesn't support partial updates. - self->core.area.next = NULL; - return &self->core.area; - } - return first_area; -} - -uint16_t common_hal_epaperdisplay_epaperdisplay_get_width(epaperdisplay_epaperdisplay_obj_t *self) { - return displayio_display_core_get_width(&self->core); -} - -uint16_t common_hal_epaperdisplay_epaperdisplay_get_height(epaperdisplay_epaperdisplay_obj_t *self) { - return displayio_display_core_get_height(&self->core); -} - -static void wait_for_busy(epaperdisplay_epaperdisplay_obj_t *self) { - if (self->busy.base.type == &mp_type_NoneType) { - return; - } - while (common_hal_digitalio_digitalinout_get_value(&self->busy) == self->busy_state && - !mp_hal_is_interrupted()) { - RUN_BACKGROUND_TASKS; - } -} - -static void send_command_sequence(epaperdisplay_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; - uint8_t data_size = *(cmd + 1); - bool delay = (data_size & DELAY) != 0; - const uint8_t *data = cmd + 2; - data_size &= ~DELAY; - if (self->two_byte_sequence_length) { - data_size = ((data_size & ~DELAY) << 8) + *(cmd + 2); - data = cmd + 3; - } - displayio_display_bus_begin_transaction(&self->bus); - self->bus.send(self->bus.bus, DISPLAY_COMMAND, self->chip_select, cmd, 1); - self->bus.send(self->bus.bus, DISPLAY_DATA, self->chip_select, data, data_size); - displayio_display_bus_end_transaction(&self->bus); - uint16_t delay_length_ms = 0; - if (delay) { - data_size++; - delay_length_ms = *(cmd + 1 + data_size + self->two_byte_sequence_length); - if (delay_length_ms == 255) { - delay_length_ms = 500; - } - } - common_hal_time_delay_ms(delay_length_ms); - if (should_wait_for_busy) { - wait_for_busy(self); - } - if (mp_hal_is_interrupted()) { - return; - } - i += 2 + data_size; - if (self->two_byte_sequence_length) { - i++; - } - } -} - -void epaperdisplay_epaperdisplay_change_refresh_mode_parameters(epaperdisplay_epaperdisplay_obj_t *self, - mp_buffer_info_t *start_sequence, float seconds_per_frame) { - self->start_sequence = (uint8_t *)start_sequence->buf; - self->start_sequence_len = start_sequence->len; - self->milliseconds_per_frame = seconds_per_frame * 1000; -} - -static void epaperdisplay_epaperdisplay_start_refresh(epaperdisplay_epaperdisplay_obj_t *self) { - if (!displayio_display_bus_is_free(&self->bus)) { - // Can't acquire display bus; skip updating this display. Try next display. - return; - } - - // run start sequence - self->bus.bus_reset(self->bus.bus); - - common_hal_time_delay_ms(self->start_up_time_ms); - - send_command_sequence(self, true, self->start_sequence, self->start_sequence_len); - if (mp_hal_is_interrupted()) { - return; - } - displayio_display_core_start_refresh(&self->core); -} - -uint32_t common_hal_epaperdisplay_epaperdisplay_get_time_to_refresh(epaperdisplay_epaperdisplay_obj_t *self) { - if (self->core.last_refresh == 0) { - return 0; - } - // Refresh at seconds per frame rate. - uint32_t elapsed_time = supervisor_ticks_ms64() - self->core.last_refresh; - if (elapsed_time > self->milliseconds_per_frame) { - return 0; - } - return self->milliseconds_per_frame - elapsed_time; -} - -static void epaperdisplay_epaperdisplay_finish_refresh(epaperdisplay_epaperdisplay_obj_t *self) { - // Actually refresh the display now that all pixel RAM has been updated. - send_command_sequence(self, false, self->refresh_sequence, self->refresh_sequence_len); - - supervisor_enable_tick(); - self->refreshing = true; - - displayio_display_core_finish_refresh(&self->core); -} - -mp_obj_t common_hal_epaperdisplay_epaperdisplay_get_bus(epaperdisplay_epaperdisplay_obj_t *self) { - return self->bus.bus; -} - -void common_hal_epaperdisplay_epaperdisplay_set_rotation(epaperdisplay_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) { - int tmp = self->core.width; - self->core.width = self->core.height; - self->core.height = tmp; - } - displayio_display_core_set_rotation(&self->core, rotation); - if (self == &displays[0].epaper_display) { - supervisor_stop_terminal(); - supervisor_start_terminal(self->core.width, self->core.height); - } - if (self->core.current_group != NULL) { - displayio_group_update_transform(self->core.current_group, &self->core.transform); - } -} - -uint16_t common_hal_epaperdisplay_epaperdisplay_get_rotation(epaperdisplay_epaperdisplay_obj_t *self) { - return self->core.rotation; -} - -mp_obj_t common_hal_epaperdisplay_epaperdisplay_get_root_group(epaperdisplay_epaperdisplay_obj_t *self) { - if (self->core.current_group == NULL) { - return mp_const_none; - } - return self->core.current_group; -} - -static bool epaperdisplay_epaperdisplay_refresh_area(epaperdisplay_epaperdisplay_obj_t *self, const displayio_area_t *area) { - uint16_t buffer_size = 128; // In uint32_ts - - displayio_area_t clipped; - // Clip the area to the display by overlapping the areas. If there is no overlap then we're done. - if (!displayio_display_core_clip_area(&self->core, area, &clipped)) { - return true; - } - uint16_t subrectangles = 1; - uint16_t rows_per_buffer = displayio_area_height(&clipped); - uint8_t pixels_per_word = (sizeof(uint32_t) * 8) / self->core.colorspace.depth; - uint16_t pixels_per_buffer = displayio_area_size(&clipped); - if (displayio_area_size(&clipped) > buffer_size * pixels_per_word) { - rows_per_buffer = buffer_size * pixels_per_word / displayio_area_width(&clipped); - if (rows_per_buffer == 0) { - rows_per_buffer = 1; - } - subrectangles = displayio_area_height(&clipped) / rows_per_buffer; - if (displayio_area_height(&clipped) % rows_per_buffer != 0) { - subrectangles++; - } - pixels_per_buffer = rows_per_buffer * displayio_area_width(&clipped); - buffer_size = pixels_per_buffer / pixels_per_word; - if (pixels_per_buffer % pixels_per_word) { - buffer_size += 1; - } - } - - // Allocated and shared as a uint32_t array so the compiler knows the - // alignment everywhere. - uint32_t buffer[buffer_size]; - volatile uint32_t mask_length = (pixels_per_buffer / 32) + 1; - uint32_t mask[mask_length]; - - uint8_t passes = 1; - if (self->write_color_ram_command != NO_COMMAND) { - passes = 2; - } - for (uint8_t pass = 0; pass < passes; pass++) { - uint16_t remaining_rows = displayio_area_height(&clipped); - - if (self->bus.row_command != NO_COMMAND) { - displayio_display_bus_set_region_to_update(&self->bus, &self->core, &clipped); - } - - uint8_t write_command = self->write_black_ram_command; - if (pass == 1) { - write_command = self->write_color_ram_command; - } - displayio_display_bus_begin_transaction(&self->bus); - self->bus.send(self->bus.bus, DISPLAY_COMMAND, self->chip_select, &write_command, 1); - displayio_display_bus_end_transaction(&self->bus); - - for (uint16_t j = 0; j < subrectangles; j++) { - displayio_area_t subrectangle = { - .x1 = clipped.x1, - .y1 = clipped.y1 + rows_per_buffer * j, - .x2 = clipped.x2, - .y2 = clipped.y1 + rows_per_buffer * (j + 1) - }; - if (remaining_rows < rows_per_buffer) { - subrectangle.y2 = subrectangle.y1 + remaining_rows; - } - remaining_rows -= rows_per_buffer; - - - uint16_t subrectangle_size_bytes = displayio_area_size(&subrectangle) / (8 / self->core.colorspace.depth); - - memset(mask, 0, mask_length * sizeof(mask[0])); - memset(buffer, 0, buffer_size * sizeof(buffer[0])); - - if (!self->acep) { - self->core.colorspace.grayscale = true; - self->core.colorspace.grayscale_bit = 7; - } - if (pass == 1) { - if (self->grayscale) { // 4-color grayscale - self->core.colorspace.grayscale_bit = 6; - displayio_display_core_fill_area(&self->core, &subrectangle, mask, buffer); - } else if (self->core.colorspace.tricolor) { - self->core.colorspace.grayscale = false; - displayio_display_core_fill_area(&self->core, &subrectangle, mask, buffer); - } else if (self->core.colorspace.sevencolor) { - displayio_display_core_fill_area(&self->core, &subrectangle, mask, buffer); - } - } else { - displayio_display_core_fill_area(&self->core, &subrectangle, mask, buffer); - } - - // Invert it all. - if ((pass == 1 && self->color_bits_inverted) || - (pass == 0 && self->black_bits_inverted)) { - for (uint16_t k = 0; k < buffer_size; k++) { - buffer[k] = ~buffer[k]; - } - } - - if (!displayio_display_bus_begin_transaction(&self->bus)) { - // Can't acquire display bus; skip the rest of the data. Try next display. - return false; - } - self->bus.send(self->bus.bus, DISPLAY_DATA, self->chip_select, (uint8_t *)buffer, subrectangle_size_bytes); - displayio_display_bus_end_transaction(&self->bus); - - // TODO(tannewt): Make refresh displays faster so we don't starve other - // background tasks. - #if CIRCUITPY_TINYUSB - usb_background(); - #endif - } - } - - return true; -} - -static bool _clean_area(epaperdisplay_epaperdisplay_obj_t *self) { - uint16_t width = displayio_display_core_get_width(&self->core); - uint16_t height = displayio_display_core_get_height(&self->core); - - uint8_t buffer[width / 2]; - memset(buffer, 0x77, width / 2); - - uint8_t write_command = self->write_black_ram_command; - displayio_display_bus_begin_transaction(&self->bus); - self->bus.send(self->bus.bus, DISPLAY_COMMAND, self->chip_select, &write_command, 1); - displayio_display_bus_end_transaction(&self->bus); - - for (uint16_t j = 0; j < height; j++) { - if (!displayio_display_bus_begin_transaction(&self->bus)) { - // Can't acquire display bus; skip the rest of the data. Try next display. - return false; - } - self->bus.send(self->bus.bus, DISPLAY_DATA, self->chip_select, buffer, width / 2); - displayio_display_bus_end_transaction(&self->bus); - - // TODO(tannewt): Make refresh displays faster so we don't starve other - // background tasks. - #if CIRCUITPY_TINYUSB - usb_background(); - #endif - } - - return true; -} - -bool common_hal_epaperdisplay_epaperdisplay_refresh(epaperdisplay_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) { - supervisor_disable_tick(); - self->refreshing = false; - // Run stop sequence but don't wait for busy because busy is set when sleeping. - send_command_sequence(self, false, self->stop_sequence, self->stop_sequence_len); - } else { - return false; - } - } - if (self->core.current_group == NULL) { - return true; - } - // Refresh at seconds per frame rate. - if (common_hal_epaperdisplay_epaperdisplay_get_time_to_refresh(self) > 0) { - return false; - } - if (!displayio_display_bus_is_free(&self->bus)) { - // Can't acquire display bus; skip updating this display. Try next display. - return false; - } - const displayio_area_t *current_area = epaperdisplay_epaperdisplay_get_refresh_areas(self); - if (current_area == NULL) { - return true; - } - if (self->acep) { - epaperdisplay_epaperdisplay_start_refresh(self); - _clean_area(self); - epaperdisplay_epaperdisplay_finish_refresh(self); - while (self->refreshing && !mp_hal_is_interrupted()) { - RUN_BACKGROUND_TASKS; - } - } - if (mp_hal_is_interrupted()) { - return false; - } - - epaperdisplay_epaperdisplay_start_refresh(self); - while (current_area != NULL) { - epaperdisplay_epaperdisplay_refresh_area(self, current_area); - current_area = current_area->next; - } - epaperdisplay_epaperdisplay_finish_refresh(self); - return true; -} - -void epaperdisplay_epaperdisplay_background(epaperdisplay_epaperdisplay_obj_t *self) { - if (self->refreshing) { - bool refresh_done = false; - if (self->busy.base.type == &digitalio_digitalinout_type) { - bool busy = common_hal_digitalio_digitalinout_get_value(&self->busy); - refresh_done = busy != self->busy_state; - } else { - refresh_done = supervisor_ticks_ms64() - self->core.last_refresh > self->refresh_time; - } - if (refresh_done) { - supervisor_disable_tick(); - self->refreshing = false; - // Run stop sequence but don't wait for busy because busy is set when sleeping. - send_command_sequence(self, false, self->stop_sequence, self->stop_sequence_len); - } - } -} - -bool common_hal_epaperdisplay_epaperdisplay_get_busy(epaperdisplay_epaperdisplay_obj_t *self) { - epaperdisplay_epaperdisplay_background(self); - return self->refreshing; -} - -void release_epaperdisplay(epaperdisplay_epaperdisplay_obj_t *self) { - if (self->refreshing) { - wait_for_busy(self); - supervisor_disable_tick(); - self->refreshing = false; - // Run stop sequence but don't wait for busy because busy is set when sleeping. - send_command_sequence(self, false, self->stop_sequence, self->stop_sequence_len); - } - - release_display_core(&self->core); - if (self->busy.base.type == &digitalio_digitalinout_type) { - common_hal_digitalio_digitalinout_deinit(&self->busy); - } -} - -void epaperdisplay_epaperdisplay_reset(epaperdisplay_epaperdisplay_obj_t *self) { - displayio_display_core_set_root_group(&self->core, &circuitpython_splash); - self->core.full_refresh = true; -} - -void epaperdisplay_epaperdisplay_collect_ptrs(epaperdisplay_epaperdisplay_obj_t *self) { - displayio_display_core_collect_ptrs(&self->core); - displayio_display_bus_collect_ptrs(&self->bus); - gc_collect_ptr((void *)self->start_sequence); - gc_collect_ptr((void *)self->stop_sequence); - gc_collect_ptr((void *)self->refresh_sequence); +#if CIRCUITPY_EPAPERDISPLAY_FAST +bool common_hal_epaperdisplay_epaperdisplay_has_lag_frames(epaperdisplay_epaperdisplay_obj_t *self) { + return self->epaper.lag.frames > 0; } +#endif size_t maybe_refresh_epaperdisplay(void) { for (uint8_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT; i++) { if (displays[i].epaper_display.base.type != &epaperdisplay_epaperdisplay_type || - displays[i].epaper_display.core.current_group != &circuitpython_splash) { + displays[i].epaper_display.epaper.core.current_group != &circuitpython_splash) { // Skip regular displays and those not showing the splash. continue; } diff --git a/shared-module/epaperdisplay/EPaperDisplay.h b/shared-module/epaperdisplay/EPaperDisplay.h index 7c72bf1f954..e053872403f 100644 --- a/shared-module/epaperdisplay/EPaperDisplay.h +++ b/shared-module/epaperdisplay/EPaperDisplay.h @@ -1,50 +1,40 @@ // This file is part of the CircuitPython project: https://circuitpython.org // // SPDX-FileCopyrightText: Copyright (c) 2019 Scott Shawcroft for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries // // SPDX-License-Identifier: MIT #pragma once -#include "shared-bindings/displayio/Group.h" - -#include "shared-module/displayio/area.h" -#include "shared-module/displayio/bus_core.h" -#include "shared-module/displayio/display_core.h" -#include "common-hal/digitalio/DigitalInOut.h" - -typedef struct { - mp_obj_base_t base; - displayio_display_core_t core; - displayio_display_bus_t bus; - digitalio_digitalinout_obj_t busy; - uint32_t milliseconds_per_frame; - const uint8_t *start_sequence; - const uint8_t *stop_sequence; - const uint8_t *refresh_sequence; - uint16_t start_sequence_len; - uint16_t stop_sequence_len; - uint16_t refresh_sequence_len; - uint16_t start_up_time_ms; - uint16_t refresh_time; - uint16_t write_black_ram_command; - uint16_t write_color_ram_command; - uint8_t hue; - bool busy_state; - bool black_bits_inverted; - bool color_bits_inverted; - bool refreshing; - bool grayscale; - bool acep; - bool two_byte_sequence_length; - display_chip_select_behavior_t chip_select; -} epaperdisplay_epaperdisplay_obj_t; +// The EPaperDisplay implementation has two backends selected at build time with +// CIRCUITPY_DISPLAYIO_LVGL: +// +// legacy/ - renders with the scanline compositor through display_core. +// lvgl/ - renders with LVGL, then converts the composed RGB pixels into the +// packed pixel planes the panel understands. The converted planes are +// kept in a framebuffer of their own so partial updates and the fast +// lag drive do not have to read pixels back from the panel. +#if CIRCUITPY_DISPLAYIO_LVGL +#include "shared-module/epaperdisplay/lvgl/EPaperDisplay.h" +#else +#include "shared-module/epaperdisplay/legacy/EPaperDisplay.h" +#endif void epaperdisplay_epaperdisplay_change_refresh_mode_parameters(epaperdisplay_epaperdisplay_obj_t *self, - mp_buffer_info_t *start_sequence, float seconds_per_frame); + mp_buffer_info_t *start_sequence, mp_buffer_info_t *refresh_sequence, float seconds_per_frame); void epaperdisplay_epaperdisplay_background(epaperdisplay_epaperdisplay_obj_t *self); void epaperdisplay_epaperdisplay_reset(epaperdisplay_epaperdisplay_obj_t *self); void release_epaperdisplay(epaperdisplay_epaperdisplay_obj_t *self); +#if CIRCUITPY_EPAPERDISPLAY_FAST +// The VM is over: a fast display ends whatever transaction still holds its bus, since its +// stop sequence would wait for the bus forever. Other displays are left alone. Does not raise. +void epaperdisplay_epaperdisplay_end_held_bus(epaperdisplay_epaperdisplay_obj_t *self); +// Waits up to 30 s for the bus so a release can finish the drive. Raises what interrupted it, or +// RuntimeError if the bus stays held, with the display and its drive unchanged. Only call it where +// an exception can be caught. Doesn't allocate. +void epaperdisplay_epaperdisplay_prepare_release(epaperdisplay_epaperdisplay_obj_t *self); +#endif size_t maybe_refresh_epaperdisplay(void); void epaperdisplay_epaperdisplay_collect_ptrs(epaperdisplay_epaperdisplay_obj_t *self); diff --git a/shared-module/epaperdisplay/epaper_core.c b/shared-module/epaperdisplay/epaper_core.c new file mode 100644 index 00000000000..299488c626d --- /dev/null +++ b/shared-module/epaperdisplay/epaper_core.c @@ -0,0 +1,478 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// Operations on the state shared by the legacy and LVGL EPaperDisplay implementations. + +#include "shared-bindings/epaperdisplay/EPaperDisplay.h" + +#include "py/gc.h" +#include "py/runtime.h" +#include "shared/runtime/interrupt_char.h" +#include "shared-bindings/digitalio/DigitalInOut.h" +#include "shared-bindings/displayio/ColorConverter.h" +#if CIRCUITPY_EPAPERDISPLAY_FAST && CIRCUITPY_WATCHDOG +#include "shared-bindings/watchdog/WatchDogTimer.h" +#endif +#include "shared-bindings/microcontroller/__init__.h" +#include "shared-bindings/time/__init__.h" +#include "shared-module/epaperdisplay/lag_drive.h" +#include "supervisor/port.h" +#include "supervisor/shared/tick.h" + +#include + +#define DELAY 0x80 + +void epaperdisplay_epaper_core_construct(epaperdisplay_epaper_core_t *self, + const epaperdisplay_construct_args_t *args) { + uint16_t color_depth = 1; + bool core_grayscale = true; + if (args->highlight_color != 0x000000) { + self->core.colorspace.tricolor = true; + self->core.colorspace.tricolor_hue = displayio_colorconverter_compute_hue(args->highlight_color); + } else { + self->core.colorspace.tricolor = false; + } + if (args->highlight_color != 0x000000 && args->highlight_color2 != 0x000000) { + self->core.colorspace.tricolor = false; + self->core.colorspace.fourcolor = true; + self->core.colorspace.fourcolor_hue = displayio_colorconverter_compute_hue(args->highlight_color2); + } else { + self->core.colorspace.fourcolor = false; + } + self->acep = args->acep || args->spectra6; + self->core.colorspace.sixcolor = args->spectra6; + self->core.colorspace.sevencolor = args->acep; + bool grayscale = args->grayscale; + if (self->acep) { + color_depth = 4; // bits. 7 colors + clean + grayscale = false; + core_grayscale = false; + } + if ((args->highlight_color != 0x000000 || args->highlight_color2 != 0x000000) && args->write_color_ram_command == NO_COMMAND) { + color_depth = 2; + core_grayscale = false; + grayscale = false; + } + + displayio_display_core_construct(&self->core, args->width, args->height, args->rotation % 360, + color_depth, core_grayscale, true, 1, true, true); + displayio_display_bus_construct(&self->bus, args->bus, args->ram_width, args->ram_height, + args->colstart, args->rowstart, + args->set_column_window_command, args->set_row_window_command, args->set_current_column_command, args->set_current_row_command, + false /* data_as_commands */, args->always_toggle_chip_select, + false /* SH1107_addressing */, args->address_little_endian); + + #if CIRCUITPY_EPAPERDISPLAY_FAST + self->lag.slots = NULL; + self->lag.frames = 0; + self->lag.busy_deadline = 0; + self->lag.bus_held = false; + self->lag.state_lost = false; + self->lag.slot_overwriting = false; + self->lag.commit = LAG_COMMIT_NONE; + self->lag.holding_interrupts = false; + self->lag.held_exception = MP_OBJ_NULL; + self->clean_sequence = args->clean_sequence; + self->clean_sequence_len = args->clean_sequence_len; + self->write_previous_ram_command = args->write_previous_ram_command; + #endif // CIRCUITPY_EPAPERDISPLAY_FAST + + self->write_black_ram_command = args->write_black_ram_command; + self->black_bits_inverted = args->black_bits_inverted; + self->write_color_ram_command = args->write_color_ram_command; + self->color_bits_inverted = args->color_bits_inverted; + self->refresh_time = args->refresh_time * 1000; + self->busy_state = args->busy_state; + self->refreshing = false; + self->milliseconds_per_frame = args->seconds_per_frame * 1000; + self->chip_select = args->always_toggle_chip_select ? CHIP_SELECT_TOGGLE_EVERY_BYTE : CHIP_SELECT_UNTOUCHED; + self->grayscale = grayscale; + self->start_sequence = args->start_sequence; + self->start_sequence_len = args->start_sequence_len; + self->start_up_time_ms = args->start_up_time * 1000; + self->stop_sequence = args->stop_sequence; + self->stop_sequence_len = args->stop_sequence_len; + self->refresh_sequence = args->refresh_sequence; + self->refresh_sequence_len = args->refresh_sequence_len; + #if CIRCUITPY_EPAPERDISPLAY_FAST + self->fast = args->fast; + self->awake = false; + self->needs_start = false; + #endif + + self->busy.base.type = &mp_type_NoneType; + self->two_byte_sequence_length = args->two_byte_sequence_length; + if (args->busy_pin != NULL) { + self->busy.base.type = &digitalio_digitalinout_type; + common_hal_digitalio_digitalinout_construct(&self->busy, args->busy_pin); + } + + // Clear the color memory if it isn't in use. + if (args->highlight_color == 0x00 && args->highlight_color2 == 0x00 && args->write_color_ram_command != NO_COMMAND) { + // TODO: Clear + } +} + +uint16_t epaperdisplay_epaper_core_get_width(epaperdisplay_epaper_core_t *self) { + return displayio_display_core_get_width(&self->core); +} + +uint16_t epaperdisplay_epaper_core_get_height(epaperdisplay_epaper_core_t *self) { + return displayio_display_core_get_height(&self->core); +} + +#if CIRCUITPY_EPAPERDISPLAY_FAST +// BUSY can take a moment to rise after an update command, and reading it low before then would +// look like a finished update. If it never rises, nothing has started or it was too quick to see, +// so this returns false after 2 ms. Short enough that an interrupt doesn't have to end it. +bool epaperdisplay_epaper_core_wait_for_update_start(epaperdisplay_epaper_core_t *self) { + for (uint8_t wait = 0; wait < 200; wait++) { + if (common_hal_digitalio_digitalinout_get_value(&self->busy) == self->busy_state) { + return true; + } + common_hal_mcu_delay_us(10); + RUN_BACKGROUND_TASKS; + port_task_yield(); + } + return false; +} +#endif // CIRCUITPY_EPAPERDISPLAY_FAST + +#if CIRCUITPY_EPAPERDISPLAY_FAST +// When a wait for BUSY or the bus gives up, or 0 for never. Lag drive always has an end, so a +// stuck panel can't hold up a caller that holds interrupts or has no way to be interrupted. +static uint64_t display_wait_deadline(epaperdisplay_epaper_core_t *self) { + if (self->lag.busy_deadline != 0 || self->lag.frames == 0) { + return self->lag.busy_deadline; + } + return supervisor_ticks_ms64() + EPAPER_WAIT_TIMEOUT_MS; +} + +// Between hold and release a waveform or a panel reset is under way, and cutting it short leaves +// the panel dark. Whatever interrupts (Ctrl-C, a reload, a watchdog) waits for the release. +bool epaperdisplay_epaper_core_interrupted(epaperdisplay_epaper_core_t *self) { + if (!self->lag.holding_interrupts) { + return mp_hal_is_interrupted(); + } + if (mp_hal_is_interrupted()) { + if (self->lag.held_exception == MP_OBJ_NULL) { + self->lag.held_exception = MP_STATE_THREAD(mp_pending_exception); + } + MP_STATE_THREAD(mp_pending_exception) = MP_OBJ_NULL; + } + #if CIRCUITPY_WATCHDOG + // A stored waveform takes seconds, and a reset mid-waveform leaves the panel dark. These waits + // are bounded, so a hang still ends. + if (common_hal_watchdog_get_mode(&common_hal_mcu_watchdogtimer_obj) != WATCHDOGMODE_NONE) { + common_hal_watchdog_feed(&common_hal_mcu_watchdogtimer_obj); + } + #endif + return false; +} + +static bool display_send_command(epaperdisplay_epaper_core_t *self, const uint8_t *command, + const uint8_t *data, uint32_t length) { + for (uint8_t attempt = 0; attempt < 3; attempt++) { + if (epaperdisplay_lag_send(self, DISPLAY_COMMAND, command, 1) && epaperdisplay_lag_send(self, DISPLAY_DATA, data, length)) { + return true; + } + // The send stopped, and it may have arrived. If it was an update, sending it again would + // drive every pixel a second time. BUSY high says it landed. A command with no data could + // be an update that BUSY hasn't shown yet, so don't risk it: the drive is now unknown. + if (epaperdisplay_epaper_core_wait_for_update_start(self)) { + return true; + } + if (length == 0) { + self->lag.state_lost = true; + return false; + } + } + return false; +} +#else // CIRCUITPY_EPAPERDISPLAY_FAST +#define display_wait_deadline(self) ((uint64_t)0) +#define epaperdisplay_epaper_core_interrupted(self) mp_hal_is_interrupted() +#define display_send_command(self, command, data, length) ( \ + (self)->bus.send((self)->bus.bus, DISPLAY_COMMAND, (self)->chip_select, command, 1), \ + (self)->bus.send((self)->bus.bus, DISPLAY_DATA, (self)->chip_select, data, length), \ + true) +#endif // CIRCUITPY_EPAPERDISPLAY_FAST + +// A delay ends early when interrupted, which a held interrupt must not do. +void epaperdisplay_epaper_core_delay_ms(epaperdisplay_epaper_core_t *self, uint32_t delay_ms) { + #if CIRCUITPY_EPAPERDISPLAY_FAST + uint64_t start = supervisor_ticks_ms64(); + uint32_t elapsed = 0; + while (true) { + common_hal_time_delay_ms(delay_ms - elapsed); + elapsed = supervisor_ticks_ms64() - start; + if (!self->lag.holding_interrupts || elapsed >= delay_ms) { + return; + } + epaperdisplay_epaper_core_interrupted(self); + } + #else + (void)self; + common_hal_time_delay_ms(delay_ms); + #endif +} + +void epaperdisplay_epaper_core_wait_for_busy(epaperdisplay_epaper_core_t *self) { + if (self->busy.base.type == &mp_type_NoneType) { + return; + } + const uint64_t deadline = display_wait_deadline(self); + while (common_hal_digitalio_digitalinout_get_value(&self->busy) == self->busy_state && + !epaperdisplay_epaper_core_interrupted(self)) { + if (deadline != 0 && supervisor_ticks_ms64() > deadline) { + return; + } + RUN_BACKGROUND_TASKS; + port_task_yield(); + } +} + +// True if every command went out. Lag drive counts an update only if its last command did. +bool epaperdisplay_epaper_core_send_command_sequence(epaperdisplay_epaper_core_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; + uint8_t data_size = *(cmd + 1); + bool delay = (data_size & DELAY) != 0; + const uint8_t *data = cmd + 2; + data_size &= ~DELAY; + if (self->two_byte_sequence_length) { + data_size = ((data_size & ~DELAY) << 8) + *(cmd + 2); + data = cmd + 3; + } + bool have_bus; + const uint64_t deadline = display_wait_deadline(self); + while (!(have_bus = displayio_display_bus_begin_transaction(&self->bus)) && + !epaperdisplay_epaper_core_interrupted(self) && (deadline == 0 || supervisor_ticks_ms64() <= deadline)) { + RUN_BACKGROUND_TASKS; + } + #if CIRCUITPY_EPAPERDISPLAY_FAST + if (!have_bus && self->lag.frames > 0) { + return false; + } + self->lag.bus_held = have_bus; + #endif // CIRCUITPY_EPAPERDISPLAY_FAST + const bool sent = display_send_command(self, cmd, data, data_size); + displayio_display_bus_end_transaction(&self->bus); + #if CIRCUITPY_EPAPERDISPLAY_FAST + self->lag.bus_held = false; + #endif // CIRCUITPY_EPAPERDISPLAY_FAST + if (!sent) { + return false; + } + uint16_t delay_length_ms = 0; + if (delay) { + data_size++; + delay_length_ms = *(cmd + 1 + data_size + self->two_byte_sequence_length); + if (delay_length_ms == 255) { + delay_length_ms = 500; + } + } + epaperdisplay_epaper_core_delay_ms(self, delay_length_ms); + if (should_wait_for_busy) { + #if CIRCUITPY_EPAPERDISPLAY_FAST + if (self->lag.frames > 0) { + epaperdisplay_epaper_core_wait_for_update_start(self); + } + #endif + epaperdisplay_epaper_core_wait_for_busy(self); + } + #if !CIRCUITPY_EPAPERDISPLAY_FAST + if (mp_hal_is_interrupted()) { + return true; + } + #endif + i += 2 + data_size; + if (self->two_byte_sequence_length) { + i++; + } + #if CIRCUITPY_EPAPERDISPLAY_FAST + if (epaperdisplay_epaper_core_interrupted(self)) { + return i >= sequence_len; + } + #endif + } + return true; +} + +void epaperdisplay_epaper_core_change_refresh_mode_parameters(epaperdisplay_epaper_core_t *self, + mp_buffer_info_t *start_sequence, mp_buffer_info_t *refresh_sequence, float seconds_per_frame) { + #if CIRCUITPY_EPAPERDISPLAY_FAST + if (self->lag.frames > 0) { + // Finish the drive with the waveform that started it, and rewrite both planes after. + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + epaperdisplay_lag_flush(self); + epaperdisplay_epaper_core_wait_for_busy(self); + nlr_pop(); + } else { + epaperdisplay_lag_raise(self, nlr.ret_val); + } + if (self->lag.settle > 0 || self->lag.commit != LAG_COMMIT_NONE) { + // Still owed: keep the mode that started it. + if (!mp_hal_is_interrupted()) { + mp_raise_RuntimeError_varg(MP_ERROR_TEXT("%q in use"), MP_QSTR_display_bus); + } + return; + } + self->lag.force_full = true; + } + #endif // CIRCUITPY_EPAPERDISPLAY_FAST + self->start_sequence = (uint8_t *)start_sequence->buf; + self->start_sequence_len = start_sequence->len; + #if CIRCUITPY_EPAPERDISPLAY_FAST + // NULL keeps the current refresh sequence. + if (refresh_sequence != NULL) { + self->refresh_sequence = (uint8_t *)refresh_sequence->buf; + self->refresh_sequence_len = refresh_sequence->len; + } + #endif + self->milliseconds_per_frame = seconds_per_frame * 1000; + #if CIRCUITPY_EPAPERDISPLAY_FAST + self->needs_start = true; + #endif +} + +#if CIRCUITPY_EPAPERDISPLAY_FAST +// For a panel kept awake. Ctrl-C raises from a send in progress, and that transaction is still +// open. The caller still has things to do first, so the interrupt raises later. +void epaperdisplay_epaper_core_send_stop_sequence_guarded(epaperdisplay_epaper_core_t *self) { + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + epaperdisplay_epaper_core_send_command_sequence(self, false, self->stop_sequence, self->stop_sequence_len); + nlr_pop(); + } else { + if (!displayio_display_bus_is_free(&self->bus)) { + displayio_display_bus_end_transaction(&self->bus); + } + mp_sched_exception(nlr.ret_val); + } +} +#endif // CIRCUITPY_EPAPERDISPLAY_FAST + +uint32_t epaperdisplay_epaper_core_get_time_to_refresh(epaperdisplay_epaper_core_t *self) { + if (self->core.last_refresh == 0) { + return 0; + } + // Refresh at seconds per frame rate. + uint32_t elapsed_time = supervisor_ticks_ms64() - self->core.last_refresh; + if (elapsed_time > self->milliseconds_per_frame) { + return 0; + } + return self->milliseconds_per_frame - elapsed_time; +} + +#if CIRCUITPY_EPAPERDISPLAY_FAST +// False if the panel is still updating when the wait is over. +bool epaperdisplay_epaper_core_wait_for_update_end(epaperdisplay_epaper_core_t *self) { + epaperdisplay_epaper_core_wait_for_update_start(self); + const uint64_t deadline = supervisor_ticks_ms64() + EPAPER_WAIT_TIMEOUT_MS; + bool busy; + while ((busy = common_hal_digitalio_digitalinout_get_value(&self->busy) == self->busy_state) && + !mp_hal_is_interrupted() && supervisor_ticks_ms64() <= deadline) { + RUN_BACKGROUND_TASKS; + port_task_yield(); + } + return !busy; +} +#endif // CIRCUITPY_EPAPERDISPLAY_FAST + +mp_obj_t epaperdisplay_epaper_core_get_bus(epaperdisplay_epaper_core_t *self) { + return self->bus.bus; +} + +uint16_t epaperdisplay_epaper_core_get_rotation(epaperdisplay_epaper_core_t *self) { + return self->core.rotation; +} + +mp_obj_t epaperdisplay_epaper_core_get_root_group(epaperdisplay_epaper_core_t *self) { + if (self->core.current_group == NULL) { + return mp_const_none; + } + return self->core.current_group; +} + +void epaperdisplay_epaper_core_background(epaperdisplay_epaper_core_t *self) { + if (self->refreshing) { + bool refresh_done = false; + if (self->busy.base.type == &digitalio_digitalinout_type) { + bool busy = common_hal_digitalio_digitalinout_get_value(&self->busy); + refresh_done = busy != self->busy_state; + } else { + refresh_done = supervisor_ticks_ms64() - self->core.last_refresh > self->refresh_time; + } + if (refresh_done) { + supervisor_disable_tick(); + self->refreshing = false; + #if CIRCUITPY_EPAPERDISPLAY_FAST + if (!self->fast) { + // Run stop sequence but don't wait for busy after it, because some panels set busy + // when sleeping. + epaperdisplay_epaper_core_send_command_sequence(self, false, self->stop_sequence, self->stop_sequence_len); + } + #else + // Run stop sequence but don't wait for busy after it, because some panels set busy + // when sleeping. + epaperdisplay_epaper_core_send_command_sequence(self, false, self->stop_sequence, self->stop_sequence_len); + #endif + } + #if CIRCUITPY_EPAPERDISPLAY_FAST + else { + epaperdisplay_lag_give_up_if_stuck(self); + } + #endif + } +} + +bool epaperdisplay_epaper_core_get_busy(epaperdisplay_epaper_core_t *self) { + epaperdisplay_epaper_core_background(self); + return self->refreshing; +} + +#if CIRCUITPY_EPAPERDISPLAY_FAST +void epaperdisplay_epaper_core_prepare_release(epaperdisplay_epaper_core_t *self) { + if (self->lag.frames == 0 || (!self->awake && !self->lag.state_lost)) { + return; + } + const uint64_t deadline = supervisor_ticks_ms64() + EPAPER_WAIT_TIMEOUT_MS; + while (!displayio_display_bus_is_free(&self->bus)) { + mp_handle_pending(true); + if (supervisor_ticks_ms64() > deadline) { + mp_raise_RuntimeError_varg(MP_ERROR_TEXT("%q in use"), MP_QSTR_display_bus); + } + RUN_BACKGROUND_TASKS; + } +} +#endif // CIRCUITPY_EPAPERDISPLAY_FAST + +#if CIRCUITPY_EPAPERDISPLAY_FAST +void epaperdisplay_epaper_core_end_held_bus(epaperdisplay_epaper_core_t *self) { + // The VM is over, so whatever holds the bus can never let it go: end it here. + if (self->fast && !displayio_display_bus_is_free(&self->bus)) { + displayio_display_bus_end_transaction(&self->bus); + self->lag.bus_held = false; + } +} +#endif // CIRCUITPY_EPAPERDISPLAY_FAST + +void epaperdisplay_epaper_core_collect_ptrs(epaperdisplay_epaper_core_t *self) { + displayio_display_core_collect_ptrs(&self->core); + displayio_display_bus_collect_ptrs(&self->bus); + gc_collect_ptr((void *)self->start_sequence); + gc_collect_ptr((void *)self->stop_sequence); + gc_collect_ptr((void *)self->refresh_sequence); + #if CIRCUITPY_EPAPERDISPLAY_FAST + gc_collect_ptr((void *)self->clean_sequence); + gc_collect_ptr(self->lag.held_exception); + #endif // CIRCUITPY_EPAPERDISPLAY_FAST +} diff --git a/shared-module/epaperdisplay/epaper_core.h b/shared-module/epaperdisplay/epaper_core.h new file mode 100644 index 00000000000..6a1fa317ef2 --- /dev/null +++ b/shared-module/epaperdisplay/epaper_core.h @@ -0,0 +1,136 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "common-hal/digitalio/DigitalInOut.h" +#include "shared-module/displayio/area.h" +#include "shared-module/displayio/bus_core.h" +#include "shared-module/displayio/display_core.h" + +// Defined by the selected implementation; only the pointer is needed by the common core. +typedef struct epaperdisplay_epaperdisplay_obj_t epaperdisplay_epaperdisplay_obj_t; +typedef struct epaperdisplay_construct_args_t epaperdisplay_construct_args_t; + +#if CIRCUITPY_EPAPERDISPLAY_FAST +// Lag drive state shared by both backends. FAST writes the last frame to the previous RAM, so each +// changed pixel is driven once. Lag writes the frame from frames refreshes ago, so a changed pixel +// is driven frames times, the same number each way. The ring is only used when frames > 0. +typedef struct { + uint8_t **slots; + uint64_t busy_deadline; // When not 0, stop waiting for BUSY or the bus after this tick. + // What interrupted while interrupts are held. A send can raise one from the heap, so it is + // marked in epaperdisplay_epaper_core_collect_ptrs(). + mp_obj_t held_exception; + bool holding_interrupts; + bool bus_held; // Inside a transaction, so an exception must end it. + bool last_try; // Shutdown's reset after a stuck wait: the deadline is not renewed. + bool state_lost; // What the panel received is unknown, so it needs a stored-waveform refresh. + bool slot_overwriting; // The oldest frame in the ring is being replaced. + bool commit_drive; // The owed step has pixels to drive. + uint8_t commit; // What the newest step in the ring still has to send. + displayio_area_t commit_box; + uint64_t update_start; // When the running update was sent. + // What each of the last frames + 1 steps rendered, in pixels. + displayio_area_t *boxes; + uint32_t slot_size; + uint16_t stride; + uint16_t rows; + uint8_t frames; + uint8_t head; // Slot of the newest frame. + uint8_t box_index; // Entry in boxes for this step. + uint8_t settle; // Steps owed until every plane pair matches the newest frame. + bool force_full; // Write everything on the next step. +} epaperdisplay_lag_t; +#endif + +// State and operations shared by the legacy and LVGL EPaperDisplay implementations. Keeping this +// separate from epaperdisplay_epaperdisplay_obj_t lets the common code and lag drive operate +// without knowing either implementation's object layout. +typedef struct { + displayio_display_core_t core; + displayio_display_bus_t bus; + digitalio_digitalinout_obj_t busy; + uint32_t milliseconds_per_frame; + const uint8_t *start_sequence; + const uint8_t *stop_sequence; + const uint8_t *refresh_sequence; + uint16_t start_sequence_len; + uint16_t stop_sequence_len; + uint16_t refresh_sequence_len; + uint16_t start_up_time_ms; + uint16_t refresh_time; + uint16_t write_black_ram_command; + uint16_t write_color_ram_command; + #if CIRCUITPY_EPAPERDISPLAY_FAST + uint16_t write_previous_ram_command; + #endif + uint8_t hue; + bool busy_state; + bool black_bits_inverted; + bool color_bits_inverted; + bool refreshing; + bool grayscale; + bool acep; + bool two_byte_sequence_length; + #if CIRCUITPY_EPAPERDISPLAY_FAST + bool fast; + bool awake; + bool needs_start; // update_refresh_mode() changed the start sequence. + #endif + display_chip_select_behavior_t chip_select; + + #if CIRCUITPY_EPAPERDISPLAY_FAST + const uint8_t *clean_sequence; + uint32_t clean_sequence_len; + epaperdisplay_lag_t lag; + epaperdisplay_epaperdisplay_obj_t *display; + #endif +} epaperdisplay_epaper_core_t; + +void epaperdisplay_epaper_core_construct(epaperdisplay_epaper_core_t *self, + const epaperdisplay_construct_args_t *args); + +uint16_t epaperdisplay_epaper_core_get_width(epaperdisplay_epaper_core_t *self); +uint16_t epaperdisplay_epaper_core_get_height(epaperdisplay_epaper_core_t *self); +uint16_t epaperdisplay_epaper_core_get_rotation(epaperdisplay_epaper_core_t *self); +mp_obj_t epaperdisplay_epaper_core_get_root_group(epaperdisplay_epaper_core_t *self); +mp_obj_t epaperdisplay_epaper_core_get_bus(epaperdisplay_epaper_core_t *self); +uint32_t epaperdisplay_epaper_core_get_time_to_refresh(epaperdisplay_epaper_core_t *self); +bool epaperdisplay_epaper_core_get_busy(epaperdisplay_epaper_core_t *self); +void epaperdisplay_epaper_core_background(epaperdisplay_epaper_core_t *self); +void epaperdisplay_epaper_core_change_refresh_mode_parameters(epaperdisplay_epaper_core_t *self, + mp_buffer_info_t *start_sequence, mp_buffer_info_t *refresh_sequence, float seconds_per_frame); +void epaperdisplay_epaper_core_collect_ptrs(epaperdisplay_epaper_core_t *self); + +// Waits for BUSY to clear or an interrupt. On a lag display the wait is bounded. +void epaperdisplay_epaper_core_wait_for_busy(epaperdisplay_epaper_core_t *self); +// Sends a start, stop or refresh sequence. True if every command went out. +bool epaperdisplay_epaper_core_send_command_sequence(epaperdisplay_epaper_core_t *self, + bool should_wait_for_busy, const uint8_t *sequence, uint32_t sequence_len); +// Delays, but while interrupts are held an interrupt doesn't cut it short. +void epaperdisplay_epaper_core_delay_ms(epaperdisplay_epaper_core_t *self, uint32_t delay_ms); + +#if CIRCUITPY_EPAPERDISPLAY_FAST +void epaperdisplay_epaper_core_prepare_release(epaperdisplay_epaper_core_t *self); +void epaperdisplay_epaper_core_end_held_bus(epaperdisplay_epaper_core_t *self); +void epaperdisplay_epaper_core_send_stop_sequence_guarded(epaperdisplay_epaper_core_t *self); +bool epaperdisplay_epaper_core_wait_for_update_end(epaperdisplay_epaper_core_t *self); +bool epaperdisplay_epaper_core_interrupted(epaperdisplay_epaper_core_t *self); +bool epaperdisplay_epaper_core_wait_for_update_start(epaperdisplay_epaper_core_t *self); +// Backend operations needed by lag drive. Implementations can use display to reach their own state. +void epaperdisplay_backend_full_area(epaperdisplay_epaper_core_t *self, displayio_area_t *area); +bool epaperdisplay_backend_clip_area(epaperdisplay_epaper_core_t *self, const displayio_area_t *area, + displayio_area_t *clipped); +void epaperdisplay_backend_render_area(epaperdisplay_epaper_core_t *self, const displayio_area_t *area, + uint8_t *frame, uint16_t frame_stride, bool white); +void epaperdisplay_backend_finish_refresh(epaperdisplay_epaper_core_t *self); +void epaperdisplay_backend_set_full_refresh(epaperdisplay_epaper_core_t *self, bool full_refresh); +void epaperdisplay_backend_set_refresh_in_progress(epaperdisplay_epaper_core_t *self, bool in_progress); +// Implemented by the selected backend. A fast display that is already awake skips the start +// sequence unless it changed. +void epaperdisplay_epaper_core_start_refresh(epaperdisplay_epaper_core_t *self); +#endif diff --git a/shared-module/epaperdisplay/lag_drive.c b/shared-module/epaperdisplay/lag_drive.c new file mode 100644 index 00000000000..4ecbe50f242 --- /dev/null +++ b/shared-module/epaperdisplay/lag_drive.c @@ -0,0 +1,772 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#include "shared-module/epaperdisplay/lag_drive.h" + +#if CIRCUITPY_EPAPERDISPLAY_FAST + +#include "py/gc.h" +#include "py/runtime.h" +#include "shared/runtime/interrupt_char.h" +#include "shared-bindings/digitalio/DigitalInOut.h" +#include "supervisor/port_heap.h" +#include "supervisor/shared/tick.h" + +#include +#include + +// SSD168x only: NOP. These controllers keep the last RAM byte until the next command and lose it to +// a reset, so a RAM write ends with this. Lag drive is only for displays where it is harmless. +#define LAG_RAM_COMMIT_COMMAND 0x7f + +static void lag_after_raise(epaperdisplay_epaper_core_t *self); +static bool lag_clean(epaperdisplay_epaper_core_t *self, uint8_t frames, bool full); + +static bool lag_clip_area(epaperdisplay_epaper_core_t *self, const displayio_area_t *area, + displayio_area_t *clipped) { + return epaperdisplay_backend_clip_area(self, area, clipped); +} + +// Clip the whole panel to whole bytes of pixels. Filling a plane or forcing a full step uses it. +static bool lag_full_area(epaperdisplay_epaper_core_t *self, displayio_area_t *area) { + displayio_area_t whole; + epaperdisplay_backend_full_area(self, &whole); + return epaperdisplay_backend_clip_area(self, &whole, area); +} + +static void lag_finish_refresh(epaperdisplay_epaper_core_t *self) { + epaperdisplay_backend_finish_refresh(self); +} + +static void lag_set_full_refresh(epaperdisplay_epaper_core_t *self, bool full_refresh) { + epaperdisplay_backend_set_full_refresh(self, full_refresh); +} + +static void lag_set_refresh_in_progress(epaperdisplay_epaper_core_t *self, bool in_progress) { + epaperdisplay_backend_set_refresh_in_progress(self, in_progress); +} + +static bool lag_deadline_passed(epaperdisplay_epaper_core_t *self) { + return self->lag.busy_deadline != 0 && supervisor_ticks_ms64() > self->lag.busy_deadline; +} + +static void lag_hold_interrupts(epaperdisplay_epaper_core_t *self) { + self->lag.holding_interrupts = true; + if (self->lag.busy_deadline == 0) { + self->lag.busy_deadline = supervisor_ticks_ms64() + EPAPER_WAIT_TIMEOUT_MS; + } + epaperdisplay_epaper_core_interrupted(self); +} + +void epaperdisplay_lag_release_interrupts(epaperdisplay_epaper_core_t *self) { + if (!self->lag.holding_interrupts) { + return; + } + self->lag.holding_interrupts = false; + self->lag.busy_deadline = 0; + if (self->lag.held_exception != MP_OBJ_NULL) { + mp_sched_exception(self->lag.held_exception); + self->lag.held_exception = MP_OBJ_NULL; + } +} + +// A transfer in progress raises when something interrupts. On a port with async SPI that can be +// any transfer, however short. While holding, that returns false: the transfer stopped partway, +// so the caller goes back to where the RAM or command can start again. +bool epaperdisplay_lag_send(epaperdisplay_epaper_core_t *self, display_byte_type_t type, + const uint8_t *data, uint32_t length) { + if (!self->lag.holding_interrupts) { + self->bus.send(self->bus.bus, type, self->chip_select, data, length); + return true; + } + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + self->bus.send(self->bus.bus, type, self->chip_select, data, length); + nlr_pop(); + return true; + } + MP_STATE_THREAD(mp_pending_exception) = nlr.ret_val; + epaperdisplay_epaper_core_interrupted(self); + return false; +} + +// set_region_to_update() has its own transaction, so a raise from it leaves the bus locked. +static bool lag_set_region(epaperdisplay_epaper_core_t *self, displayio_area_t *box) { + for (volatile uint8_t attempt = 0; attempt < 3; attempt++) { + // It skips its commands if it can't get the bus, which would leave the old window. + if (!displayio_display_bus_is_free(&self->bus)) { + return false; + } + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + self->lag.bus_held = true; + displayio_display_bus_set_region_to_update(&self->bus, &self->core.colorspace, box); + self->lag.bus_held = false; + nlr_pop(); + return true; + } + if (self->lag.bus_held) { + if (!displayio_display_bus_is_free(&self->bus)) { + displayio_display_bus_end_transaction(&self->bus); + } + self->lag.bus_held = false; + } + if (!self->lag.holding_interrupts) { + nlr_jump(nlr.ret_val); + } + MP_STATE_THREAD(mp_pending_exception) = nlr.ret_val; + epaperdisplay_epaper_core_interrupted(self); + } + return false; +} + +// Lag drive. Plane 0x26 holds frame N-lag instead of N-1. Each step drives a pixel toward black +// where N is black and N-lag is white, toward white where N is white and N-lag is black, and not +// at all where they match. +// +// That keeps the drive balanced without counting. Each frame is used twice: pixels are driven +// toward it in the step where it is N, and away from it lag steps later, where it is N-lag. So a +// pixel that ends the way it started has been driven the same amount toward black and toward +// white. For example, lag 3 and a pixel that is black for 2 steps (both planes start white): +// +// step 1 2 3 4 5 6 +// frame N W B B W W W +// frame N-3 W W W W B B +// drive - B B - W W 2 toward black, 2 toward white +// +// A change that holds for lag steps or more is driven lag steps, so a bigger lag drives harder. +// When frames stop changing, lag more steps finish the drive. Each frame is rendered once into +// the ring and the planes are sent from there. +// +// The ring has lag slots, N-1 to N-lag, and N replaces N-lag in its slot. The box to send must +// be known before that, so it comes from the areas that were rendered, not from comparing frames. +// Frames N and N-lag can only differ inside the areas of the last lag steps. Sending the areas of +// the last lag + 1 steps also covers what the previous step left unequal, so the planes are +// equal outside the box: a byte there is either outside the last box too, so equal by induction, +// or was last written with frames that have not changed there since. + +void epaperdisplay_lag_construct(epaperdisplay_epaper_core_t *self, mp_obj_base_t *base, uint8_t lag_frames) { + displayio_area_t whole; + epaperdisplay_backend_full_area(self, &whole); + self->lag.stride = (whole.x2 + 7) / 8; + self->lag.rows = whole.y2; + self->lag.slot_size = self->lag.stride * self->lag.rows; + self->lag.frames = lag_frames; + self->lag.head = 0; + self->lag.box_index = 0; + self->lag.settle = 0; + // The panel's RAM is unknown, so the first step writes everything. + self->lag.force_full = true; + size_t meta_size = lag_frames * sizeof(uint8_t *) + (lag_frames + 1) * sizeof(displayio_area_t); + self->lag.slots = port_malloc(meta_size, false); + bool ok = self->lag.slots != NULL; + if (ok) { + memset(self->lag.slots, 0, meta_size); + self->lag.boxes = (displayio_area_t *)(self->lag.slots + lag_frames); + } + for (uint8_t i = 0; ok && i < lag_frames; i++) { + self->lag.slots[i] = port_malloc(self->lag.slot_size, true); + ok = self->lag.slots[i] != NULL; + } + if (!ok) { + epaperdisplay_lag_free(self); + base->type = &mp_type_NoneType; + m_malloc_fail(self->lag.slot_size); + } + // History starts white, the state a cleared panel is in. + for (uint8_t i = 0; i < lag_frames; i++) { + memset(self->lag.slots[i], self->black_bits_inverted ? 0x00 : 0xff, self->lag.slot_size); + } +} + +void epaperdisplay_lag_free(epaperdisplay_epaper_core_t *self) { + if (self->lag.slots != NULL) { + for (uint8_t i = 0; i < self->lag.frames; i++) { + if (self->lag.slots[i] != NULL) { + port_free(self->lag.slots[i]); + } + } + port_free(self->lag.slots); + self->lag.slots = NULL; + } + self->lag.frames = 0; +} + +static void lag_render_area(epaperdisplay_epaper_core_t *self, const displayio_area_t *area, uint8_t *frame, bool white) { + displayio_area_t clipped; + if (!lag_clip_area(self, area, &clipped)) { + return; + } + epaperdisplay_backend_render_area(self, &clipped, frame, self->lag.stride, white); +} + +static bool lag_send_ram_commit(epaperdisplay_epaper_core_t *self) { + const uint8_t command = LAG_RAM_COMMIT_COMMAND; + return epaperdisplay_lag_send(self, DISPLAY_COMMAND, &command, 1); +} + +// Rows are gathered so a narrow box doesn't cost one SPI transfer per row. +static bool lag_send_plane(epaperdisplay_epaper_core_t *self, uint8_t command, const uint8_t *frame, const displayio_area_t *box) { + if (!epaperdisplay_lag_send(self, DISPLAY_COMMAND, &command, 1)) { + return false; + } + uint16_t bytes_per_row = displayio_area_width(box) / 8; + const uint8_t *in = frame + box->y1 * self->lag.stride + box->x1 / 8; + if (bytes_per_row == self->lag.stride) { + return epaperdisplay_lag_send(self, DISPLAY_DATA, in, displayio_area_height(box) * bytes_per_row) && lag_send_ram_commit(self); + } + uint8_t chunk[512]; + size_t used = 0; + for (int16_t y = box->y1; y < box->y2; y++) { + if (bytes_per_row > sizeof(chunk)) { + if (!epaperdisplay_lag_send(self, DISPLAY_DATA, in, bytes_per_row)) { + return false; + } + in += self->lag.stride; + continue; + } + if (used + bytes_per_row > sizeof(chunk)) { + if (!epaperdisplay_lag_send(self, DISPLAY_DATA, chunk, used)) { + return false; + } + used = 0; + } + memcpy(chunk + used, in, bytes_per_row); + used += bytes_per_row; + in += self->lag.stride; + } + return epaperdisplay_lag_send(self, DISPLAY_DATA, chunk, used) && lag_send_ram_commit(self); +} + +// A send stopped by a held interrupt leaves the RAM pointer partway, so start over from the region. +static bool lag_write_plane(epaperdisplay_epaper_core_t *self, uint8_t command, const uint8_t *frame, displayio_area_t *box) { + for (uint8_t attempt = 0; attempt < 3; attempt++) { + if (!lag_set_region(self, box) || !displayio_display_bus_begin_transaction(&self->bus)) { + return false; + } + self->lag.bus_held = true; + const bool sent = lag_send_plane(self, command, frame, box); + displayio_display_bus_end_transaction(&self->bus); + self->lag.bus_held = false; + if (sent) { + return true; + } + } + return false; +} + +// Finish a step whose frame is already in the ring: frame N to its plane, then the update. Each +// part stays owed until it has gone out, so a pixel is only counted as driven if it was. Interrupts +// wait, since a send they stop can't be told from one that arrived. False if the bus can't be had. +static bool lag_commit_step(epaperdisplay_epaper_core_t *self) { + const bool was_holding = self->lag.holding_interrupts; + lag_hold_interrupts(self); + bool ok = true; + if (self->lag.commit == LAG_COMMIT_PLANE) { + ok = lag_write_plane(self, self->write_black_ram_command, self->lag.slots[self->lag.head], &self->lag.commit_box); + if (ok) { + self->lag.commit = LAG_COMMIT_ACTIVATE; + } + } + if (ok && self->lag.commit == LAG_COMMIT_ACTIVATE) { + // Nothing can differ when the box is empty, so an update would only take time. + if (self->lag.commit_drive) { + ok = epaperdisplay_epaper_core_send_command_sequence(self, false, self->refresh_sequence, self->refresh_sequence_len); + if (ok) { + epaperdisplay_epaper_core_wait_for_update_start(self); + supervisor_enable_tick(); + self->refreshing = true; + self->lag.update_start = supervisor_ticks_ms64(); + } + } + if (ok) { + self->lag.commit = LAG_COMMIT_NONE; + } + } + if (!was_holding) { + epaperdisplay_lag_release_interrupts(self); + } + return ok; +} + +// Send one step: frame N-lag to the previous plane, then frame N, rendered from areas (may be +// NULL) over its slot, or white in those areas without rendering, to the other. The history +// doesn't advance if the bus can't be had before the slot is touched, so a retry does the same +// step. Once it has, the step is owed and true is returned, whatever happens to the rest. +static bool lag_step(epaperdisplay_epaper_core_t *self, const displayio_area_t *areas, + uint8_t area_count, bool white) { + uint8_t lag = self->lag.frames; + uint8_t next = (self->lag.head + 1) % lag; + uint8_t *frame = self->lag.slots[next]; + displayio_area_t *boxes = self->lag.boxes; + uint8_t index = self->lag.box_index; + #if CIRCUITPY_DISPLAYIO_LVGL + bool changed = area_count > 0; + for (uint8_t i = 0; i < area_count; i++) { + displayio_area_t clipped; + if (lag_clip_area(self, &areas[i], &clipped)) { + displayio_area_union(&boxes[index], &clipped, &boxes[index]); + } + } + #else + (void)area_count; + bool changed = areas != NULL; + for (const displayio_area_t *area = areas; area != NULL; area = area->next) { + displayio_area_t clipped; + if (lag_clip_area(self, area, &clipped)) { + displayio_area_union(&boxes[index], &clipped, &boxes[index]); + } + } + #endif + // The oldest entry is lag steps back: only needed to make the planes equal again. + uint8_t oldest = (index + 1) % (lag + 1); + displayio_area_t drive_box = {0}; + for (uint8_t i = 0; i <= lag; i++) { + if (i != oldest) { + displayio_area_union(&drive_box, &boxes[i], &drive_box); + } + } + displayio_area_t write_box; + if (self->lag.force_full) { + if (!lag_full_area(self, &write_box)) { + write_box = (displayio_area_t) {0}; + } + } else { + displayio_area_union(&drive_box, &boxes[oldest], &write_box); + } + bool write = !displayio_area_empty(&write_box); + + if (write && !lag_write_plane(self, self->write_previous_ram_command, frame, &write_box)) { + return false; + } + // N-1 and N-lag only differ inside the box. + self->lag.slot_overwriting = true; + if (write && next != self->lag.head) { + const uint8_t *in = self->lag.slots[self->lag.head] + write_box.y1 * self->lag.stride + write_box.x1 / 8; + uint8_t *out = frame + write_box.y1 * self->lag.stride + write_box.x1 / 8; + uint16_t bytes_per_row = displayio_area_width(&write_box) / 8; + for (int16_t y = write_box.y1; y < write_box.y2; y++) { + memcpy(out, in, bytes_per_row); + in += self->lag.stride; + out += self->lag.stride; + } + } + #if CIRCUITPY_DISPLAYIO_LVGL + for (uint8_t i = 0; i < area_count; i++) { + lag_render_area(self, &areas[i], frame, white); + } + #else + for (const displayio_area_t *area = areas; area != NULL; area = area->next) { + lag_render_area(self, area, frame, white); + } + #endif + // The slot no longer holds N-lag, so from here the step has to finish or that drive is lost. + self->lag.slot_overwriting = false; + self->lag.head = next; + self->lag.box_index = oldest; + boxes[oldest] = (displayio_area_t) {0}; + if (changed) { + self->lag.settle = lag; + } else if (self->lag.settle > 0) { + self->lag.settle--; + } + self->lag.force_full = false; + self->lag.commit_box = write_box; + self->lag.commit_drive = !displayio_area_empty(&drive_box); + self->lag.commit = write ? LAG_COMMIT_PLANE : LAG_COMMIT_ACTIVATE; + lag_commit_step(self); + return true; +} + +static bool lag_refresh_unguarded(epaperdisplay_epaper_core_t *self, const displayio_area_t *areas, + uint8_t area_count) { + displayio_area_t whole; + if (!self->awake || self->lag.state_lost) { + // The panel may still hold anything, including ghosts from a run that lost power. + if (!lag_clean(self, 0, true) || mp_hal_is_interrupted()) { + return false; + } + if (!lag_full_area(self, &whole)) { + return false; + } + areas = &whole; + area_count = 1; + } + if (self->lag.commit != LAG_COMMIT_NONE) { + // The areas stay marked, so the next refresh draws them. + return lag_commit_step(self); + } + #if CIRCUITPY_DISPLAYIO_LVGL + if (area_count == 0 && self->lag.settle == 0) { + #else + if (areas == NULL && self->lag.settle == 0) { + #endif + return true; + } + if (self->needs_start) { + lag_hold_interrupts(self); + epaperdisplay_epaper_core_start_refresh(self); + epaperdisplay_lag_release_interrupts(self); + } else { + epaperdisplay_epaper_core_start_refresh(self); + } + bool ok = !self->needs_start && lag_step(self, areas, area_count, false); + if (ok) { + lag_finish_refresh(self); + } else { + lag_set_refresh_in_progress(self, false); + } + return ok; +} + +// An update takes far less than the limit, so a panel still BUSY is stuck, and only a reset can +// help. That has to wait for the next refresh or the shutdown, since the bus may be in use here. +// Until then a script polling busy can go on. +void epaperdisplay_lag_give_up_if_stuck(epaperdisplay_epaper_core_t *self) { + if (self->lag.frames > 0 && !self->lag.holding_interrupts && + supervisor_ticks_ms64() - self->lag.update_start > EPAPER_WAIT_TIMEOUT_MS) { + supervisor_disable_tick(); + self->refreshing = false; + self->awake = false; + self->lag.state_lost = true; + } +} + +// False if the update is still running: interrupted, or the panel is stuck. RAM writes and a reset +// would land on that update, so nothing more can be sent. +static bool lag_wait_idle(epaperdisplay_epaper_core_t *self) { + epaperdisplay_epaper_core_wait_for_busy(self); + return common_hal_digitalio_digitalinout_get_value(&self->busy) != self->busy_state; +} + +// The deadline bounds each piece of work, not the whole drive, which can be 32 updates and a clean. +// Only called after progress, so a bus that is never free still runs out. +static void lag_renew_deadline(epaperdisplay_epaper_core_t *self) { + if (self->lag.busy_deadline != 0 && !self->lag.last_try) { + self->lag.busy_deadline = supervisor_ticks_ms64() + EPAPER_WAIT_TIMEOUT_MS; + } +} + +// Give every changed pixel the rest of its drive so the panel is left DC balanced. +void epaperdisplay_lag_flush(epaperdisplay_epaper_core_t *self) { + if (self->lag.frames == 0 || !self->awake) { + return; + } + while (self->lag.settle > 0 || self->lag.commit != LAG_COMMIT_NONE) { + if (!lag_wait_idle(self) || epaperdisplay_epaper_core_interrupted(self)) { + return; + } + if (self->refreshing) { + supervisor_disable_tick(); + self->refreshing = false; + } + if (self->lag.commit != LAG_COMMIT_NONE ? !lag_commit_step(self) : !lag_step(self, NULL, 0, false)) { + return; + } + lag_renew_deadline(self); + } +} + +bool epaperdisplay_lag_refresh(epaperdisplay_epaper_core_t *self, const displayio_area_t *areas, + uint8_t area_count) { + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + bool ok = lag_refresh_unguarded(self, areas, area_count); + nlr_pop(); + return ok; + } + epaperdisplay_lag_raise(self, nlr.ret_val); +} + +// Fill a whole RAM plane with one color from a small buffer. +static bool lag_send_solid(epaperdisplay_epaper_core_t *self, uint8_t command, bool white) { + if (!epaperdisplay_lag_send(self, DISPLAY_COMMAND, &command, 1)) { + return false; + } + uint8_t chunk[512]; + memset(chunk, white != self->black_bits_inverted ? 0xff : 0x00, sizeof(chunk)); + size_t remaining = self->lag.slot_size; + while (remaining > 0) { + size_t count = MIN(remaining, sizeof(chunk)); + if (!epaperdisplay_lag_send(self, DISPLAY_DATA, chunk, count)) { + return false; + } + remaining -= count; + } + return lag_send_ram_commit(self); +} + +static bool lag_write_solid(epaperdisplay_epaper_core_t *self, uint8_t command, bool white) { + displayio_area_t box; + if (!lag_full_area(self, &box)) { + return true; + } + for (uint8_t attempt = 0; attempt < 3; attempt++) { + if (!lag_set_region(self, &box) || !displayio_display_bus_begin_transaction(&self->bus)) { + return false; + } + self->lag.bus_held = true; + const bool sent = lag_send_solid(self, command, white); + displayio_display_bus_end_transaction(&self->bus); + self->lag.bus_held = false; + if (sent) { + return true; + } + } + return false; +} + +// Updates with the planes as they are. Background tasks run, so a video keeps decoding. Returns how +// many went out. +static uint8_t lag_wipe_phase(epaperdisplay_epaper_core_t *self, uint8_t frames) { + for (uint8_t i = 0; i < frames; i++) { + lag_renew_deadline(self); + if (!epaperdisplay_epaper_core_send_command_sequence(self, false, self->refresh_sequence, self->refresh_sequence_len)) { + return i; + } + epaperdisplay_epaper_core_wait_for_update_start(self); + if (!lag_wait_idle(self)) { + return i + 1; // A stuck panel: writes would be dropped, so nothing more can help. + } + } + return frames; +} + +// Both planes must be white. Every pixel gets frames toward black, then the same number toward white, +// and both planes are white again at the end. The caller holds interrupts, so the phases stay +// together. If that can't be done the drive is unknown, and only a stored-waveform refresh is safe. +static void lag_wipe(epaperdisplay_epaper_core_t *self, uint8_t frames) { + bool ok = lag_write_solid(self, self->write_black_ram_command, false); + if (ok) { + const uint8_t toward_black = lag_wipe_phase(self, frames); + lag_renew_deadline(self); + ok = toward_black == frames && lag_wait_idle(self) && + lag_write_solid(self, self->write_previous_ram_command, false) && + lag_write_solid(self, self->write_black_ram_command, true) && + lag_wipe_phase(self, frames) == frames && + lag_write_solid(self, self->write_previous_ram_command, true); + } + if (!ok) { + self->lag.state_lost = true; + } +} + +// A normal step to white, then the owed steps. Everything changed so far gets all of its drive, +// and the ring and both planes end up white with nothing owed. False if interrupted first, with +// the drive still owed. +static bool lag_to_white(epaperdisplay_epaper_core_t *self) { + while (true) { + if (!lag_wait_idle(self) || epaperdisplay_epaper_core_interrupted(self)) { + return false; + } + if (self->refreshing) { + supervisor_disable_tick(); + self->refreshing = false; + } + if (self->lag.commit == LAG_COMMIT_NONE) { + break; + } + if (!lag_commit_step(self)) { + return false; + } + } + displayio_area_t whole; + if (!lag_full_area(self, &whole)) { + return false; + } + if (!lag_step(self, &whole, 1, true)) { + return false; + } + lag_renew_deadline(self); + epaperdisplay_lag_flush(self); + if (self->lag.settle > 0 || self->lag.commit != LAG_COMMIT_NONE || !lag_wait_idle(self)) { + return false; + } + if (self->refreshing) { + supervisor_disable_tick(); + self->refreshing = false; + } + return true; +} + +// An exception came out of a bus send (Ctrl-C during a long transfer raises) or a render. Without +// this the bus stays locked and chip select low, and everything after waits for it. The next +// step writes all of both planes, since this one may have stopped partway through either. +static void lag_abandon_step(epaperdisplay_epaper_core_t *self) { + if (self->lag.bus_held) { + displayio_display_bus_end_transaction(&self->bus); + self->lag.bus_held = false; + } + lag_set_refresh_in_progress(self, false); + self->lag.force_full = true; + if (self->lag.slot_overwriting) { + // The drive it held can't be sent any more. + self->lag.slot_overwriting = false; + self->lag.state_lost = true; + } +} + +static void lag_after_raise(epaperdisplay_epaper_core_t *self) { + lag_abandon_step(self); + epaperdisplay_lag_release_interrupts(self); +} + +// Raise once: what was held, if anything, instead of both that and this. +MP_NORETURN void epaperdisplay_lag_raise(epaperdisplay_epaper_core_t *self, mp_obj_t raised) { + if (self->lag.held_exception != MP_OBJ_NULL) { + raised = self->lag.held_exception; + self->lag.held_exception = MP_OBJ_NULL; + } + lag_after_raise(self); + nlr_jump(raised); +} + +static bool lag_wake(epaperdisplay_epaper_core_t *self) { + self->awake = false; + self->bus.bus_reset(self->bus.bus); + epaperdisplay_epaper_core_delay_ms(self, self->start_up_time_ms); + if (!epaperdisplay_epaper_core_send_command_sequence(self, true, self->start_sequence, self->start_sequence_len)) { + return false; + } + self->awake = true; + self->needs_start = false; + return true; +} + +// What the panel received is unknown, so paying back could drive pixels the wrong way. Forget the +// drive and let the stored waveform, which is balanced by itself, bring the panel to white. +static bool lag_recover(epaperdisplay_epaper_core_t *self) { + // An update that may have started shouldn't be cut. A stuck panel has already been waited for. + if (self->awake) { + epaperdisplay_epaper_core_wait_for_busy(self); + } + if (!lag_wake(self) || !lag_wait_idle(self)) { + return false; + } + lag_renew_deadline(self); + if (!lag_write_solid(self, self->write_previous_ram_command, true) || + !lag_write_solid(self, self->write_black_ram_command, true) || + !epaperdisplay_epaper_core_send_command_sequence(self, true, self->clean_sequence, self->clean_sequence_len) || + !lag_wait_idle(self)) { + return false; + } + lag_renew_deadline(self); + if (!lag_wake(self)) { + return false; + } + for (uint8_t i = 0; i < self->lag.frames; i++) { + memset(self->lag.slots[i], self->black_bits_inverted ? 0x00 : 0xff, self->lag.slot_size); + } + memset(self->lag.boxes, 0, (self->lag.frames + 1) * sizeof(displayio_area_t)); + self->lag.settle = 0; + self->lag.commit = LAG_COMMIT_NONE; + self->lag.force_full = false; + self->lag.state_lost = false; + return true; +} + +// A clean can't stop partway, so an interrupt raises when it ends. False if the bus can't be had. +static bool lag_clean(epaperdisplay_epaper_core_t *self, uint8_t frames, bool full) { + if (!displayio_display_bus_is_free(&self->bus)) { + return false; + } + lag_hold_interrupts(self); + lag_set_full_refresh(self, true); + bool ok; + if (self->lag.state_lost) { + ok = lag_recover(self); + } else { + ok = self->awake || lag_wake(self); + ok = ok && lag_to_white(self); + if (ok && full) { + lag_renew_deadline(self); + self->lag.force_full = true; + ok = epaperdisplay_epaper_core_send_command_sequence(self, true, self->clean_sequence, self->clean_sequence_len) && lag_wait_idle(self); + if (ok) { + lag_renew_deadline(self); + ok = lag_wake(self); + lag_renew_deadline(self); + } + } + } + if (ok && frames > 0) { + lag_wipe(self, frames); + } + epaperdisplay_lag_release_interrupts(self); + return ok; +} + +bool epaperdisplay_epaper_core_clean(epaperdisplay_epaper_core_t *self, uint8_t frames, bool full) { + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + bool ok = lag_clean(self, frames, full); + nlr_pop(); + return ok; + } + epaperdisplay_lag_raise(self, nlr.ret_val); +} + +// Leave the panel white and balanced when the display goes away: release, or the end of the VM, +// where nothing can catch an exception. Interrupts stay held until release_epaperdisplay() has sent +// the stop sequence. All of it is bounded so a stuck panel can't hang shutdown. Doesn't allocate. +void epaperdisplay_lag_shutdown(epaperdisplay_epaper_core_t *self) { + if (self->lag.frames == 0 || (!self->awake && !self->lag.state_lost)) { + return; // Nothing was drawn. + } + lag_after_raise(self); // Anything still held from before is ours to end. + lag_hold_interrupts(self); + volatile bool done = false; + // Each raise abandons the step and the loop starts it again, up to 4 times. + volatile uint8_t raises = 0; + while (!done && !lag_deadline_passed(self) && raises < 4) { + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + if (self->lag.state_lost) { + done = lag_recover(self); + } else if (lag_to_white(self)) { + lag_renew_deadline(self); + done = epaperdisplay_epaper_core_send_command_sequence(self, true, self->clean_sequence, self->clean_sequence_len); + } + nlr_pop(); + RUN_BACKGROUND_TASKS; // Whatever holds the bus may let it go. + } else { + lag_abandon_step(self); + raises++; + if (self->lag.held_exception == MP_OBJ_NULL) { + self->lag.held_exception = nlr.ret_val; + } + } + } + epaperdisplay_epaper_core_wait_for_busy(self); + if (self->refreshing) { + supervisor_disable_tick(); + self->refreshing = false; + } + // BUSY outlasted the wait. One reset may free the panel for the stored waveform. If BUSY stays + // high after it, nothing more is sent, and the deadline isn't renewed, so this is the last wait. + if (!done && raises < 4 && common_hal_digitalio_digitalinout_get_value(&self->busy) == self->busy_state) { + self->lag.busy_deadline = supervisor_ticks_ms64() + EPAPER_WAIT_TIMEOUT_MS; + self->lag.last_try = true; + self->awake = false; + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + self->bus.bus_reset(self->bus.bus); + epaperdisplay_epaper_core_delay_ms(self, self->start_up_time_ms); + if (lag_wait_idle(self)) { + lag_recover(self); + } + nlr_pop(); + } else { + lag_abandon_step(self); + if (self->lag.held_exception == MP_OBJ_NULL) { + self->lag.held_exception = nlr.ret_val; + } + } + self->lag.last_try = false; + } +} + +#endif // CIRCUITPY_EPAPERDISPLAY_FAST diff --git a/shared-module/epaperdisplay/lag_drive.h b/shared-module/epaperdisplay/lag_drive.h new file mode 100644 index 00000000000..c182b5ecb44 --- /dev/null +++ b/shared-module/epaperdisplay/lag_drive.h @@ -0,0 +1,46 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-module/epaperdisplay/epaper_core.h" + +#if CIRCUITPY_EPAPERDISPLAY_FAST +// Longer than one update or stored-waveform refresh takes. This bounds each wait for an update on +// a lag display, and the wait before writing the previous RAM. A stock display's waits have no bound. +#define EPAPER_WAIT_TIMEOUT_MS 30000 + +// What the newest lag step still has to send: nothing, its plane, or the update that shows it. +enum { LAG_COMMIT_NONE, LAG_COMMIT_PLANE, LAG_COMMIT_ACTIVATE }; + +// Allocates the frame ring outside the VM heap. Raises MemoryError if it can't. +void epaperdisplay_lag_construct(epaperdisplay_epaper_core_t *self, mp_obj_base_t *base, uint8_t lag_frames); +// Sends the rest of the drive owed. Returns early if interrupted or the panel is stuck. +void epaperdisplay_lag_flush(epaperdisplay_epaper_core_t *self); +// Frees the frame ring. +void epaperdisplay_lag_free(epaperdisplay_epaper_core_t *self); +// Marks a panel BUSY for longer than EPAPER_WAIT_TIMEOUT_MS as lost, for the next refresh to reset. +void epaperdisplay_lag_give_up_if_stuck(epaperdisplay_epaper_core_t *self); +// Abandons the step in progress, ends any hold on interrupts, then raises. An interrupt saved +// during the hold is raised instead of raised. +MP_NORETURN void epaperdisplay_lag_raise(epaperdisplay_epaper_core_t *self, mp_obj_t raised); +// Sends one lag step for areas, or only the owed drive when there are none. False if the step +// couldn't be sent: interrupted, the panel is stuck, or the start sequence changed. The areas +// stay marked and the drive stays owed. +// LVGL builds keep dirty areas in an array, because displayio_area_t is lv_area_t and has no list +// link there. Other builds ignore area_count. NULL must be paired with area_count == 0. +bool epaperdisplay_lag_refresh(epaperdisplay_epaper_core_t *self, const displayio_area_t *areas, + uint8_t area_count); +// Ends a hold on interrupts and schedules any interrupt saved during it. +void epaperdisplay_lag_release_interrupts(epaperdisplay_epaper_core_t *self); +// Sends bytes on the bus. False only while interrupts are held and the transfer was interrupted. +bool epaperdisplay_lag_send(epaperdisplay_epaper_core_t *self, display_byte_type_t type, + const uint8_t *data, uint32_t length); +// Leaves the panel white and balanced when the display goes away. Doesn't raise or allocate. +void epaperdisplay_lag_shutdown(epaperdisplay_epaper_core_t *self); +// Brings every pixel to white with balanced drive, optionally using the clean sequence first. +bool epaperdisplay_epaper_core_clean(epaperdisplay_epaper_core_t *self, uint8_t frames, bool full); +#endif // CIRCUITPY_EPAPERDISPLAY_FAST diff --git a/shared-module/epaperdisplay/legacy/EPaperDisplay.c b/shared-module/epaperdisplay/legacy/EPaperDisplay.c new file mode 100644 index 00000000000..725c42ab96f --- /dev/null +++ b/shared-module/epaperdisplay/legacy/EPaperDisplay.c @@ -0,0 +1,598 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/epaperdisplay/EPaperDisplay.h" + +#include "py/runtime.h" +#include "shared/runtime/interrupt_char.h" +#include "shared-bindings/time/__init__.h" +#include "shared-module/displayio/__init__.h" +#include "shared-module/epaperdisplay/lag_drive.h" +#include "supervisor/shared/display.h" +#include "supervisor/shared/tick.h" + +#if CIRCUITPY_TINYUSB +#include "supervisor/usb.h" +#endif + +#include +#include + +// lag_drive.c calls these only when it is built. Otherwise they stay static, as before it. +#if CIRCUITPY_EPAPERDISPLAY_FAST +#define LAG_SHARED +#else +#define LAG_SHARED static +#endif + +void common_hal_epaperdisplay_epaperdisplay_construct(epaperdisplay_epaperdisplay_obj_t *self, + const epaperdisplay_construct_args_t *args) { + #if CIRCUITPY_EPAPERDISPLAY_FAST + self->epaper.display = self; + #endif + epaperdisplay_epaper_core_construct(&self->epaper, args); + + #if CIRCUITPY_EPAPERDISPLAY_FAST + if (args->lag_frames > 0) { + epaperdisplay_lag_construct(&self->epaper, &self->base, args->lag_frames); + } + #endif // CIRCUITPY_EPAPERDISPLAY_FAST + + // Set the group after initialization otherwise we may send pixels while we delay in + // initialization. + common_hal_epaperdisplay_epaperdisplay_set_root_group(self, &circuitpython_splash); +} + +bool common_hal_epaperdisplay_epaperdisplay_set_root_group(epaperdisplay_epaperdisplay_obj_t *self, displayio_group_t *root_group) { + return displayio_display_core_set_root_group(&self->epaper.core, root_group); +} + +static const displayio_area_t *epaperdisplay_epaperdisplay_get_refresh_areas(epaperdisplay_epaperdisplay_obj_t *self) { + if (self->epaper.core.full_refresh) { + self->epaper.core.area.next = NULL; + return &self->epaper.core.area; + } + const displayio_area_t *first_area = NULL; + if (self->epaper.core.current_group != NULL) { + first_area = displayio_group_get_refresh_areas(self->epaper.core.current_group, NULL); + } + if (first_area != NULL && self->epaper.bus.row_command == NO_COMMAND) { + // Do a full refresh if the display doesn't support partial updates. + self->epaper.core.area.next = NULL; + return &self->epaper.core.area; + } + return first_area; +} + +LAG_SHARED void epaperdisplay_epaper_core_start_refresh(epaperdisplay_epaper_core_t *self) { + if (!displayio_display_bus_is_free(&self->bus)) { + // Can't acquire display bus; skip updating this display. Try next display. + return; + } + if (!displayio_display_core_start_refresh(&self->core)) { + // Refresh on this display already in progress. + return; + } + + #if CIRCUITPY_EPAPERDISPLAY_FAST + if (self->fast && self->awake) { + if (!self->needs_start) { + // The panel is still configured from the previous refresh. + return; + } + epaperdisplay_epaper_core_wait_for_busy(self); + // SSD168x controllers commit the last RAM byte when the next command arrives, so a reset + // can't come straight after a RAM write. + epaperdisplay_epaper_core_send_stop_sequence_guarded(self); + self->awake = false; + } + #endif + + // run start sequence + self->bus.bus_reset(self->bus.bus); + + epaperdisplay_epaper_core_delay_ms(self, self->start_up_time_ms); + + #if CIRCUITPY_EPAPERDISPLAY_FAST + if (!epaperdisplay_epaper_core_send_command_sequence(self, true, self->start_sequence, self->start_sequence_len) || + epaperdisplay_epaper_core_interrupted(self)) { + return; + } + self->awake = true; + self->needs_start = false; + #else + epaperdisplay_epaper_core_send_command_sequence(self, true, self->start_sequence, self->start_sequence_len); + #endif +} + +#if CIRCUITPY_EPAPERDISPLAY_FAST +void epaperdisplay_backend_full_area(epaperdisplay_epaper_core_t *self, displayio_area_t *area) { + *area = self->core.area; + area->next = NULL; +} + +bool epaperdisplay_backend_clip_area(epaperdisplay_epaper_core_t *self, const displayio_area_t *area, + displayio_area_t *clipped) { + bool ok = displayio_display_core_clip_area(&self->core, area, clipped); + clipped->next = NULL; + return ok; +} + +void epaperdisplay_backend_render_area(epaperdisplay_epaper_core_t *self, const displayio_area_t *area, + uint8_t *frame, uint16_t frame_stride, bool white) { + uint16_t width = displayio_area_width(area); + uint16_t bytes_per_row = width / 8; + if (white) { + for (int16_t row = area->y1; row < area->y2; row++) { + memset(frame + row * frame_stride + area->x1 / 8, self->black_bits_inverted ? 0x00 : 0xff, + bytes_per_row); + } + return; + } + uint16_t rows_per_buffer = MAX(1, 128 * 32 / width); + size_t words = (rows_per_buffer * width + 31) / 32; + uint32_t buffer[words]; + uint32_t mask[words]; + + self->core.colorspace.grayscale = true; + self->core.colorspace.grayscale_bit = 7; + for (int16_t y = area->y1; y < area->y2; y += rows_per_buffer) { + displayio_area_t subrectangle = { + .x1 = area->x1, + .y1 = y, + .x2 = area->x2, + .y2 = MIN(y + rows_per_buffer, area->y2), + }; + memset(mask, 0, sizeof(mask)); + memset(buffer, 0, sizeof(buffer)); + displayio_display_core_fill_area(&self->core, &subrectangle, mask, buffer); + if (self->black_bits_inverted) { + for (size_t k = 0; k < words; k++) { + buffer[k] = ~buffer[k]; + } + } + const uint8_t *in = (const uint8_t *)buffer; + for (int16_t row = subrectangle.y1; row < subrectangle.y2; row++) { + memcpy(frame + row * frame_stride + area->x1 / 8, in, bytes_per_row); + in += bytes_per_row; + } + // Run background tasks like a regular refresh does. + RUN_BACKGROUND_TASKS; + } +} + +void epaperdisplay_backend_finish_refresh(epaperdisplay_epaper_core_t *self) { + displayio_display_core_finish_refresh(&self->core); +} + +void epaperdisplay_backend_set_full_refresh(epaperdisplay_epaper_core_t *self, bool full_refresh) { + self->core.full_refresh = full_refresh; +} + +void epaperdisplay_backend_set_refresh_in_progress(epaperdisplay_epaper_core_t *self, bool in_progress) { + self->core.refresh_in_progress = in_progress; +} +#endif + +#if CIRCUITPY_EPAPERDISPLAY_FAST +static bool epaperdisplay_epaperdisplay_refresh_area(epaperdisplay_epaperdisplay_obj_t *self, const displayio_area_t *area, bool write_previous); + +static void epaperdisplay_epaperdisplay_finish_refresh(epaperdisplay_epaperdisplay_obj_t *self, const displayio_area_t *areas) { + // Actually refresh the display now that all pixel RAM has been updated. + epaperdisplay_epaper_core_send_command_sequence(&self->epaper, false, self->epaper.refresh_sequence, self->epaper.refresh_sequence_len); + const uint64_t refresh_start = supervisor_ticks_ms64(); + bool previous_written = true; + mp_obj_t raised = MP_OBJ_NULL; + + if (self->epaper.write_previous_ram_command != NO_COMMAND && areas != NULL) { + // Copy the new image into the previous image RAM so the next partial update compares + // against what is on screen. The controller ignores RAM writes while it is updating. + if (self->epaper.busy.base.type == &mp_type_NoneType) { + common_hal_time_delay_ms(self->epaper.refresh_time); + } else { + previous_written = epaperdisplay_epaper_core_wait_for_update_end(&self->epaper); + } + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + while (areas != NULL && previous_written) { + previous_written = !mp_hal_is_interrupted() && + epaperdisplay_epaperdisplay_refresh_area(self, areas, true); + areas = areas->next; + } + nlr_pop(); + } else { + // Ctrl-C raises from a transfer in progress, and that transaction is still open. + raised = nlr.ret_val; + previous_written = false; + if (!displayio_display_bus_is_free(&self->epaper.bus)) { + displayio_display_bus_end_transaction(&self->epaper.bus); + } + } + } + + supervisor_enable_tick(); + self->epaper.refreshing = true; + + displayio_display_core_finish_refresh(&self->epaper.core); + // The update began before the wait above, and refresh_time and seconds_per_frame count from it. + self->epaper.core.last_refresh = refresh_start; + if (!previous_written) { + // The previous RAM is stale, so the next update has to write everything. + self->epaper.core.full_refresh = true; + } + if (raised != MP_OBJ_NULL) { + nlr_jump(raised); + } +} +#else +static void epaperdisplay_epaperdisplay_finish_refresh(epaperdisplay_epaperdisplay_obj_t *self, const displayio_area_t *areas) { + // Actually refresh the display now that all pixel RAM has been updated. + epaperdisplay_epaper_core_send_command_sequence(&self->epaper, false, self->epaper.refresh_sequence, self->epaper.refresh_sequence_len); + + supervisor_enable_tick(); + self->epaper.refreshing = true; + + displayio_display_core_finish_refresh(&self->epaper.core); +} +#endif // CIRCUITPY_EPAPERDISPLAY_FAST + +void common_hal_epaperdisplay_epaperdisplay_set_rotation(epaperdisplay_epaperdisplay_obj_t *self, int rotation) { + displayio_display_core_set_rotation_and_update(&self->epaper.core, rotation, &self->base); +} + +static bool epaperdisplay_epaperdisplay_refresh_area(epaperdisplay_epaperdisplay_obj_t *self, const displayio_area_t *area, bool write_previous) { + uint16_t buffer_size = 128; // In uint32_ts + + displayio_area_t clipped; + // Clip the area to the display by overlapping the areas. If there is no overlap then we're done. + if (!displayio_display_core_clip_area(&self->epaper.core, area, &clipped)) { + return true; + } + uint16_t subrectangles = 1; + uint16_t rows_per_buffer = displayio_area_height(&clipped); + uint8_t pixels_per_word = (sizeof(uint32_t) * 8) / self->epaper.core.colorspace.depth; + uint16_t pixels_per_buffer = displayio_area_size(&clipped); + if (displayio_area_size(&clipped) > buffer_size * pixels_per_word) { + rows_per_buffer = buffer_size * pixels_per_word / displayio_area_width(&clipped); + if (rows_per_buffer == 0) { + rows_per_buffer = 1; + } + subrectangles = displayio_area_height(&clipped) / rows_per_buffer; + if (displayio_area_height(&clipped) % rows_per_buffer != 0) { + subrectangles++; + } + pixels_per_buffer = rows_per_buffer * displayio_area_width(&clipped); + buffer_size = pixels_per_buffer / pixels_per_word; + if (pixels_per_buffer % pixels_per_word) { + buffer_size += 1; + } + } + + // Allocated and shared as a uint32_t array so the compiler knows the + // alignment everywhere. + uint32_t buffer[buffer_size]; + volatile uint32_t mask_length = (pixels_per_buffer / 32) + 1; + uint32_t mask[mask_length]; + + uint8_t passes = 1; + if (self->epaper.write_color_ram_command != NO_COMMAND && !write_previous) { + passes = 2; + } + for (uint8_t pass = 0; pass < passes; pass++) { + uint16_t remaining_rows = displayio_area_height(&clipped); + + if (self->epaper.bus.row_command != NO_COMMAND) { + displayio_display_bus_set_region_to_update(&self->epaper.bus, &self->epaper.core.colorspace, &clipped); + } + + uint8_t write_command = self->epaper.write_black_ram_command; + if (pass == 1) { + write_command = self->epaper.write_color_ram_command; + } + #if CIRCUITPY_EPAPERDISPLAY_FAST + else if (write_previous) { + write_command = self->epaper.write_previous_ram_command; + } + #endif + if (!displayio_display_bus_begin_transaction(&self->epaper.bus)) { + // Display bus not available now. + return false; + } + self->epaper.bus.send(self->epaper.bus.bus, DISPLAY_COMMAND, self->epaper.chip_select, &write_command, 1); + displayio_display_bus_end_transaction(&self->epaper.bus); + + for (uint16_t j = 0; j < subrectangles; j++) { + displayio_area_t subrectangle = { + .x1 = clipped.x1, + .y1 = clipped.y1 + rows_per_buffer * j, + .x2 = clipped.x2, + .y2 = clipped.y1 + rows_per_buffer * (j + 1) + }; + if (remaining_rows < rows_per_buffer) { + subrectangle.y2 = subrectangle.y1 + remaining_rows; + } + remaining_rows -= rows_per_buffer; + + + uint16_t subrectangle_size_bytes = displayio_area_size(&subrectangle) / (8 / self->epaper.core.colorspace.depth); + + memset(mask, 0, mask_length * sizeof(mask[0])); + memset(buffer, 0, buffer_size * sizeof(buffer[0])); + + if (!self->epaper.acep) { + self->epaper.core.colorspace.grayscale = true; + self->epaper.core.colorspace.grayscale_bit = 7; + } + if (pass == 1) { + if (self->epaper.grayscale) { // 4-color grayscale + self->epaper.core.colorspace.grayscale_bit = 6; + displayio_display_core_fill_area(&self->epaper.core, &subrectangle, mask, buffer); + } else if (self->epaper.core.colorspace.tricolor) { + self->epaper.core.colorspace.grayscale = false; + displayio_display_core_fill_area(&self->epaper.core, &subrectangle, mask, buffer); + } else if (self->epaper.core.colorspace.sixcolor || self->epaper.core.colorspace.sevencolor) { + displayio_display_core_fill_area(&self->epaper.core, &subrectangle, mask, buffer); + } + } else { + displayio_display_core_fill_area(&self->epaper.core, &subrectangle, mask, buffer); + } + + // Invert it all. + if ((pass == 1 && self->epaper.color_bits_inverted) || + (pass == 0 && self->epaper.black_bits_inverted)) { + for (uint16_t k = 0; k < buffer_size; k++) { + buffer[k] = ~buffer[k]; + } + } + + if (!displayio_display_bus_begin_transaction(&self->epaper.bus)) { + // Can't acquire display bus; skip the rest of the data. Try next display. + return false; + } + self->epaper.bus.send(self->epaper.bus.bus, DISPLAY_DATA, self->epaper.chip_select, (uint8_t *)buffer, subrectangle_size_bytes); + displayio_display_bus_end_transaction(&self->epaper.bus); + + // Run background tasks so they can run during an explicit refresh. + // Auto-refresh won't run background tasks here because it is a background task itself. + RUN_BACKGROUND_TASKS; + + // Run USB background tasks so they can run during an implicit refresh. + #if CIRCUITPY_TINYUSB + usb_background(); + #endif + } + } + + return true; +} + +static bool _clean_area(epaperdisplay_epaperdisplay_obj_t *self) { + uint16_t width = displayio_display_core_get_width(&self->epaper.core); + uint16_t height = displayio_display_core_get_height(&self->epaper.core); + + uint8_t buffer[width / 2]; + memset(buffer, 0x77, width / 2); + + uint8_t write_command = self->epaper.write_black_ram_command; + if (!displayio_display_bus_begin_transaction(&self->epaper.bus)) { + return false; + } + self->epaper.bus.send(self->epaper.bus.bus, DISPLAY_COMMAND, self->epaper.chip_select, &write_command, 1); + displayio_display_bus_end_transaction(&self->epaper.bus); + + for (uint16_t j = 0; j < height; j++) { + if (!displayio_display_bus_begin_transaction(&self->epaper.bus)) { + // Can't acquire display bus; skip the rest of the data. Try next display. + return false; + } + self->epaper.bus.send(self->epaper.bus.bus, DISPLAY_DATA, self->epaper.chip_select, buffer, width / 2); + displayio_display_bus_end_transaction(&self->epaper.bus); + + // TODO(tannewt): Make refresh displays faster so we don't starve other + // background tasks. + #if CIRCUITPY_TINYUSB + usb_background(); + #endif + } + + return true; +} + +bool common_hal_epaperdisplay_epaperdisplay_refresh(epaperdisplay_epaperdisplay_obj_t *self) { + + if (self->epaper.refreshing && self->epaper.busy.base.type == &digitalio_digitalinout_type) { + if (common_hal_digitalio_digitalinout_get_value(&self->epaper.busy) != self->epaper.busy_state) { + supervisor_disable_tick(); + self->epaper.refreshing = false; + #if CIRCUITPY_EPAPERDISPLAY_FAST + if (!self->epaper.fast) { + // Run stop sequence but don't wait for busy after it, because some panels set busy + // when sleeping. + epaperdisplay_epaper_core_send_command_sequence(&self->epaper, false, self->epaper.stop_sequence, self->epaper.stop_sequence_len); + } + #else + // Run stop sequence but don't wait for busy after it, because some panels set busy + // when sleeping. + epaperdisplay_epaper_core_send_command_sequence(&self->epaper, false, self->epaper.stop_sequence, self->epaper.stop_sequence_len); + #endif + } else { + #if CIRCUITPY_EPAPERDISPLAY_FAST + epaperdisplay_lag_give_up_if_stuck(&self->epaper); + #endif + return false; + } + } + if (self->epaper.core.current_group == NULL) { + #if CIRCUITPY_EPAPERDISPLAY_FAST + // Nothing to draw, but the drive already started is still owed. + if (self->epaper.lag.frames > 0 && self->epaper.awake) { + return epaperdisplay_lag_refresh(&self->epaper, NULL, 0); + } + #endif + return true; + } + // Refresh at seconds per frame rate. + if (common_hal_epaperdisplay_epaperdisplay_get_time_to_refresh(self) > 0) { + return false; + } + if (!displayio_display_bus_is_free(&self->epaper.bus)) { + // Can't acquire display bus; skip updating this display. Try next display. + return false; + } + const displayio_area_t *current_area = epaperdisplay_epaperdisplay_get_refresh_areas(self); + #if CIRCUITPY_EPAPERDISPLAY_FAST + if (self->epaper.lag.frames > 0) { + return epaperdisplay_lag_refresh(&self->epaper, current_area, 0); + } + #endif // CIRCUITPY_EPAPERDISPLAY_FAST + if (current_area == NULL) { + return true; + } + if (self->epaper.acep) { + epaperdisplay_epaper_core_start_refresh(&self->epaper); + _clean_area(self); + epaperdisplay_epaperdisplay_finish_refresh(self, NULL); + while (self->epaper.refreshing && !mp_hal_is_interrupted()) { + RUN_BACKGROUND_TASKS; + } + } + if (mp_hal_is_interrupted()) { + return false; + } + + epaperdisplay_epaper_core_start_refresh(&self->epaper); + const displayio_area_t *first_area = current_area; + while (current_area != NULL) { + epaperdisplay_epaperdisplay_refresh_area(self, current_area, false); + current_area = current_area->next; + } + epaperdisplay_epaperdisplay_finish_refresh(self, first_area); + return true; +} + +void release_epaperdisplay(epaperdisplay_epaperdisplay_obj_t *self) { + #if CIRCUITPY_EPAPERDISPLAY_FAST + epaperdisplay_lag_shutdown(&self->epaper); + epaperdisplay_lag_free(&self->epaper); + #endif // CIRCUITPY_EPAPERDISPLAY_FAST + if (self->epaper.refreshing) { + // Mark the refresh as done before waiting for busy. Otherwise the background task could + // end the refresh during the wait by running the stop sequence, and on panels that set + // busy when sleeping, such as the SSD1680, the wait would never end. + supervisor_disable_tick(); + self->epaper.refreshing = false; + epaperdisplay_epaper_core_wait_for_busy(&self->epaper); + + // Run stop sequence but don't wait for busy after it, because some panels set busy when + // sleeping. + #if CIRCUITPY_EPAPERDISPLAY_FAST + if (self->epaper.fast) { + epaperdisplay_epaper_core_send_stop_sequence_guarded(&self->epaper); + } else { + epaperdisplay_epaper_core_send_command_sequence(&self->epaper, false, self->epaper.stop_sequence, self->epaper.stop_sequence_len); + } + #else + epaperdisplay_epaper_core_send_command_sequence(&self->epaper, false, self->epaper.stop_sequence, self->epaper.stop_sequence_len); + #endif + } + #if CIRCUITPY_EPAPERDISPLAY_FAST + else if (self->epaper.fast && self->epaper.awake) { + epaperdisplay_epaper_core_send_stop_sequence_guarded(&self->epaper); + } + self->epaper.awake = false; + #endif + #if CIRCUITPY_EPAPERDISPLAY_FAST + epaperdisplay_lag_release_interrupts(&self->epaper); + #endif // CIRCUITPY_EPAPERDISPLAY_FAST + + release_display_core(&self->epaper.core); + if (self->epaper.busy.base.type == &digitalio_digitalinout_type) { + common_hal_digitalio_digitalinout_deinit(&self->epaper.busy); + } +} + +void epaperdisplay_epaperdisplay_reset(epaperdisplay_epaperdisplay_obj_t *self) { + #if CIRCUITPY_EPAPERDISPLAY_FAST + if (self->epaper.lag.frames > 0) { + // Only a primary display gets here; reset_displays() has released the others. The heap is + // still here but the sequences won't be, and the display would otherwise persist to draw + // the splash with them. Finish now and stay asleep. Its bus still holds the pins until + // the next VM ends or release_displays(). + epaperdisplay_epaper_core_end_held_bus(&self->epaper); + release_epaperdisplay(self); + self->base.type = &mp_type_NoneType; + return; + } + #endif // CIRCUITPY_EPAPERDISPLAY_FAST + displayio_display_core_set_root_group(&self->epaper.core, &circuitpython_splash); + self->epaper.core.full_refresh = true; + #if CIRCUITPY_EPAPERDISPLAY_FAST + // Let the panel sleep after the next refresh when code isn't running. + if (self->epaper.fast && self->epaper.awake && !self->epaper.refreshing) { + // Nothing can catch a raise from a send. A reload may be pending. + epaperdisplay_epaper_core_end_held_bus(&self->epaper); + epaperdisplay_epaper_core_send_stop_sequence_guarded(&self->epaper); + self->epaper.awake = false; + } + self->epaper.fast = false; + #endif +} + +uint16_t common_hal_epaperdisplay_epaperdisplay_get_width(epaperdisplay_epaperdisplay_obj_t *self) { + return epaperdisplay_epaper_core_get_width(&self->epaper); +} + +uint16_t common_hal_epaperdisplay_epaperdisplay_get_height(epaperdisplay_epaperdisplay_obj_t *self) { + return epaperdisplay_epaper_core_get_height(&self->epaper); +} + +uint16_t common_hal_epaperdisplay_epaperdisplay_get_rotation(epaperdisplay_epaperdisplay_obj_t *self) { + return epaperdisplay_epaper_core_get_rotation(&self->epaper); +} + +mp_obj_t common_hal_epaperdisplay_epaperdisplay_get_root_group(epaperdisplay_epaperdisplay_obj_t *self) { + return epaperdisplay_epaper_core_get_root_group(&self->epaper); +} + +mp_obj_t common_hal_epaperdisplay_epaperdisplay_get_bus(epaperdisplay_epaperdisplay_obj_t *self) { + return epaperdisplay_epaper_core_get_bus(&self->epaper); +} + +uint32_t common_hal_epaperdisplay_epaperdisplay_get_time_to_refresh(epaperdisplay_epaperdisplay_obj_t *self) { + return epaperdisplay_epaper_core_get_time_to_refresh(&self->epaper); +} + +bool common_hal_epaperdisplay_epaperdisplay_get_busy(epaperdisplay_epaperdisplay_obj_t *self) { + return epaperdisplay_epaper_core_get_busy(&self->epaper); +} + +void epaperdisplay_epaperdisplay_change_refresh_mode_parameters(epaperdisplay_epaperdisplay_obj_t *self, + mp_buffer_info_t *start_sequence, mp_buffer_info_t *refresh_sequence, float seconds_per_frame) { + epaperdisplay_epaper_core_change_refresh_mode_parameters(&self->epaper, + start_sequence, refresh_sequence, seconds_per_frame); +} + +void epaperdisplay_epaperdisplay_background(epaperdisplay_epaperdisplay_obj_t *self) { + epaperdisplay_epaper_core_background(&self->epaper); +} + +void epaperdisplay_epaperdisplay_collect_ptrs(epaperdisplay_epaperdisplay_obj_t *self) { + epaperdisplay_epaper_core_collect_ptrs(&self->epaper); +} + +#if CIRCUITPY_EPAPERDISPLAY_FAST +void epaperdisplay_epaperdisplay_prepare_release(epaperdisplay_epaperdisplay_obj_t *self) { + epaperdisplay_epaper_core_prepare_release(&self->epaper); +} + +void epaperdisplay_epaperdisplay_end_held_bus(epaperdisplay_epaperdisplay_obj_t *self) { + epaperdisplay_epaper_core_end_held_bus(&self->epaper); +} + +bool common_hal_epaperdisplay_epaperdisplay_clean(epaperdisplay_epaperdisplay_obj_t *self, uint8_t frames, bool full) { + return epaperdisplay_epaper_core_clean(&self->epaper, frames, full); +} +#endif diff --git a/shared-module/epaperdisplay/legacy/EPaperDisplay.h b/shared-module/epaperdisplay/legacy/EPaperDisplay.h new file mode 100644 index 00000000000..81a57f71b76 --- /dev/null +++ b/shared-module/epaperdisplay/legacy/EPaperDisplay.h @@ -0,0 +1,14 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-module/epaperdisplay/epaper_core.h" + +struct epaperdisplay_epaperdisplay_obj_t { + mp_obj_base_t base; + epaperdisplay_epaper_core_t epaper; +}; diff --git a/shared-module/epaperdisplay/lvgl/EPaperDisplay.c b/shared-module/epaperdisplay/lvgl/EPaperDisplay.c new file mode 100644 index 00000000000..69ecc180586 --- /dev/null +++ b/shared-module/epaperdisplay/lvgl/EPaperDisplay.c @@ -0,0 +1,975 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Scott Shawcroft for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/epaperdisplay/EPaperDisplay.h" + +#include "py/runtime.h" +#include "shared-bindings/displayio/ColorConverter.h" +#include "shared-bindings/time/__init__.h" +#include "shared-module/displayio/__init__.h" +#include "shared-module/displayio/lvgl/lvgl_internal.h" +#include "shared-module/epaperdisplay/lag_drive.h" +#include "supervisor/port_heap.h" +#include "supervisor/shared/display.h" +#include "supervisor/shared/tick.h" + +#include "lvgl.h" +#include "lvgl/draw/lv_draw_utils.h" + +#if CIRCUITPY_TINYUSB +#include "supervisor/usb.h" +#endif + +#include +#include + +// LVGL draw buffer height. The flush callback converts complete rows, so this only needs to +// cover a useful part of the screen at a time. +#define EPAPER_LVGL_DRAW_BUF_LINES 20 + +static void epaperdisplay_lvgl_flush_cb(lv_display_t *disp, const lv_area_t *area, uint8_t *px_map); +static void epaperdisplay_lvgl_mark_dirty(epaperdisplay_epaperdisplay_obj_t *self, const displayio_area_t *area); +static void epaperdisplay_lvgl_clear_dirty(epaperdisplay_epaperdisplay_obj_t *self); + +static void epaperdisplay_lvgl_free_buffers(epaperdisplay_epaperdisplay_obj_t *self) { + port_free(self->lv_buf); + port_free(self->lv_rotation_buf); + port_free(self->black_buf); + port_free(self->color_buf); + self->lv_buf = NULL; + self->lv_rotation_buf = NULL; + self->black_buf = NULL; + self->color_buf = NULL; + self->lv_buf_size = 0; + self->lv_rotation_buf_size = 0; + #if CIRCUITPY_EPAPERDISPLAY_FAST + epaperdisplay_lag_free(&self->epaper); + #endif +} + +void common_hal_epaperdisplay_epaperdisplay_construct(epaperdisplay_epaperdisplay_obj_t *self, + const epaperdisplay_construct_args_t *args) { + #if CIRCUITPY_EPAPERDISPLAY_FAST + self->epaper.display = self; + #endif + uint16_t rotation = args->rotation % 360; + epaperdisplay_epaper_core_construct(&self->epaper, args); + + // The converted framebuffer. The panel planes are packed like the controller RAM: + // most significant pixel first, regardless of the LVGL source format. These allocations + // outlive the VM, so they come from the port heap. + self->lv_display = NULL; + self->lv_color_format = LV_COLOR_FORMAT_RGB565; + self->lv_buf = NULL; + self->lv_buf_size = 0; + self->lv_rotation_buf = NULL; + self->lv_rotation_buf_size = 0; + // The constructor's width and height are logical dimensions at the requested rotation. + // LVGL's original resolution and the converted planes use the controller's native RAM + // orientation instead, which is fixed for the lifetime of the display. + bool transposed = rotation == 90 || rotation == 270; + self->canvas_width = transposed ? args->height : args->width; + self->canvas_height = transposed ? args->width : args->height; + self->canvas_depth = self->epaper.core.colorspace.depth; + self->canvas_stride = (self->canvas_width * self->canvas_depth + 7) / 8; + self->black_buf = NULL; + self->color_buf = NULL; + self->dirty_count = 0; + self->dirty_full = false; + self->refresh_in_progress = false; + self->full_refresh = true; + + #if CIRCUITPY_EPAPERDISPLAY_FAST + if (args->lag_frames > 0) { + epaperdisplay_lag_construct(&self->epaper, &self->base, args->lag_frames); + } + #endif // CIRCUITPY_EPAPERDISPLAY_FAST + + size_t canvas_size = (size_t)self->canvas_stride * self->canvas_height; + self->black_buf = port_malloc(canvas_size, false); + if (self->black_buf == NULL) { + epaperdisplay_lvgl_free_buffers(self); + self->base.type = &mp_type_NoneType; + mp_raise_msg(&mp_type_MemoryError, MP_ERROR_TEXT("LVGL buffer alloc failed")); + } + memset(self->black_buf, 0, canvas_size); + if (args->write_color_ram_command != NO_COMMAND && !self->epaper.acep) { + self->color_buf = port_malloc(canvas_size, false); + if (self->color_buf == NULL) { + epaperdisplay_lvgl_free_buffers(self); + self->base.type = &mp_type_NoneType; + mp_raise_msg(&mp_type_MemoryError, MP_ERROR_TEXT("LVGL buffer alloc failed")); + } + memset(self->color_buf, 0, canvas_size); + } + + // Set up LVGL. The display's buffers and flush callback have to exist before the + // compositor can see it as the default display. + displayio_lvgl_port_init(); + displayio_lvgl_lock(); + self->lv_display = lv_display_create(self->canvas_width, self->canvas_height); + if (self->lv_display == NULL) { + displayio_lvgl_unlock(); + epaperdisplay_lvgl_free_buffers(self); + self->base.type = &mp_type_NoneType; + mp_raise_RuntimeError(MP_ERROR_TEXT("LVGL display create failed")); + } + lv_display_set_user_data(self->lv_display, self); + lv_display_set_color_format(self->lv_display, self->lv_color_format); + lv_display_set_flush_cb(self->lv_display, epaperdisplay_lvgl_flush_cb); + + uint16_t max_dimension = MAX(args->width, args->height); + uint16_t lines = MIN(EPAPER_LVGL_DRAW_BUF_LINES, self->canvas_height); + size_t lv_buf_size = lv_draw_buf_width_to_stride(max_dimension, self->lv_color_format) * lines; + lv_buf_size = (lv_buf_size + LV_DRAW_BUF_ALIGN - 1) & ~(LV_DRAW_BUF_ALIGN - 1); + self->lv_buf = port_malloc(lv_buf_size, false); + self->lv_rotation_buf = port_malloc(lv_buf_size, false); + if (self->lv_buf == NULL || self->lv_rotation_buf == NULL) { + lv_display_delete(self->lv_display); + self->lv_display = NULL; + displayio_lvgl_unlock(); + epaperdisplay_lvgl_free_buffers(self); + self->base.type = &mp_type_NoneType; + mp_raise_msg(&mp_type_MemoryError, MP_ERROR_TEXT("LVGL buffer alloc failed")); + } + self->lv_buf_size = lv_buf_size; + self->lv_rotation_buf_size = lv_buf_size; + lv_display_set_buffers(self->lv_display, self->lv_buf, NULL, self->lv_buf_size, + LV_DISPLAY_RENDER_MODE_PARTIAL); + + displayio_lvgl_init(); + lv_display_set_default(self->lv_display); + displayio_lvgl_register_display(self->lv_display); + displayio_display_core_set_root_group(&self->epaper.core, &circuitpython_splash); + displayio_lvgl_set_root_group(&circuitpython_splash); + displayio_lvgl_unlock(); + + if (rotation != 0) { + common_hal_epaperdisplay_epaperdisplay_set_rotation(self, rotation); + } +} + +bool common_hal_epaperdisplay_epaperdisplay_set_root_group(epaperdisplay_epaperdisplay_obj_t *self, displayio_group_t *root_group) { + bool ok = displayio_display_core_set_root_group(&self->epaper.core, root_group); + if (!ok) { + return false; + } + nlr_jump_callback_node_t cleanup; + displayio_lvgl_lock_with_cleanup(&cleanup); + if (self->lv_display != NULL) { + lv_display_set_default(self->lv_display); + } + displayio_lvgl_set_root_group(root_group); + self->full_refresh = true; + self->dirty_full = true; + displayio_lvgl_unlock_with_cleanup(); + return true; +} + +// The whole physical panel, which is also the coordinate space the flush callback and the +// controller commands use. +static void epaperdisplay_lvgl_full_area(epaperdisplay_epaperdisplay_obj_t *self, displayio_area_t *area) { + area->x1 = 0; + area->y1 = 0; + area->x2 = self->canvas_width; + area->y2 = self->canvas_height; +} + +// Clip an area to the panel and grow it to a whole byte of packed pixels. The controller +// addresses packed RAM in whole bytes, so a partial byte at either edge has to be sent too. +static bool epaperdisplay_lvgl_clip_area(epaperdisplay_epaperdisplay_obj_t *self, const displayio_area_t *area, + displayio_area_t *clipped) { + displayio_area_t whole; + epaperdisplay_lvgl_full_area(self, &whole); + if (!displayio_area_compute_overlap(&whole, area, clipped)) { + return false; + } + uint8_t depth = self->canvas_depth; + if (depth < 8 && self->epaper.core.colorspace.pixels_in_byte_share_row) { + uint8_t pixels_per_byte = 8 / depth * self->epaper.core.colorspace.bytes_per_cell; + clipped->x1 -= clipped->x1 % pixels_per_byte; + if (clipped->x2 % pixels_per_byte != 0) { + clipped->x2 += pixels_per_byte - clipped->x2 % pixels_per_byte; + } + if (clipped->x1 < 0) { + clipped->x1 = 0; + } + // The packed rows have room for the padding pixels in the last byte. They are written + // as zero (or white when inverted) and sent with the rest of the row. + int32_t packed_width = self->canvas_stride * pixels_per_byte; + if (clipped->x2 > packed_width) { + clipped->x2 = packed_width; + } + } + return !displayio_area_empty(clipped); +} + +#if CIRCUITPY_EPAPERDISPLAY_FAST +// Copy an already-clipped area from the converted framebuffer into a lag frame, or fill it white. +static void epaperdisplay_lvgl_render_area(epaperdisplay_epaperdisplay_obj_t *self, + const displayio_area_t *area, uint8_t *frame, uint16_t frame_stride, bool white) { + uint16_t bytes_per_row = displayio_area_width(area) / 8; + for (int16_t row = area->y1; row < area->y2; row++) { + uint8_t *dest = frame + row * frame_stride + area->x1 / 8; + if (white) { + memset(dest, self->epaper.black_bits_inverted ? 0x00 : 0xff, bytes_per_row); + } else { + const uint8_t *source = self->black_buf + row * self->canvas_stride + area->x1 / 8; + memcpy(dest, source, bytes_per_row); + } + } +} +#endif + +static bool epaperdisplay_lvgl_begin_refresh(epaperdisplay_epaperdisplay_obj_t *self) { + if (self->refresh_in_progress) { + return false; + } + self->refresh_in_progress = true; + self->epaper.core.last_refresh = supervisor_ticks_ms64(); + return true; +} + +static void epaperdisplay_lvgl_finish_refresh(epaperdisplay_epaperdisplay_obj_t *self) { + self->full_refresh = false; + self->refresh_in_progress = false; + self->epaper.core.last_refresh = supervisor_ticks_ms64(); + epaperdisplay_lvgl_clear_dirty(self); +} + +static void epaperdisplay_lvgl_clear_dirty(epaperdisplay_epaperdisplay_obj_t *self) { + self->dirty_count = 0; + self->dirty_full = false; +} + +static bool epaperdisplay_lvgl_area_contains(const displayio_area_t *outer, const displayio_area_t *inner) { + return outer->x1 <= inner->x1 && outer->y1 <= inner->y1 && + outer->x2 >= inner->x2 && outer->y2 >= inner->y2; +} + +// Keep the areas LVGL flushed since the panel was last updated. Sending them individually +// preserves more of the panel's partial-update window than one screen-sized box would. +static void epaperdisplay_lvgl_mark_dirty(epaperdisplay_epaperdisplay_obj_t *self, const displayio_area_t *area) { + if (self->dirty_full) { + return; + } + displayio_area_t clipped; + if (!epaperdisplay_lvgl_clip_area(self, area, &clipped)) { + return; + } + for (uint8_t i = 0; i < self->dirty_count; i++) { + if (epaperdisplay_lvgl_area_contains(&self->dirty[i], &clipped)) { + return; + } + } + if (self->dirty_count < EPAPER_LVGL_MAX_DIRTY) { + self->dirty[self->dirty_count++] = clipped; + return; + } + // Too many small changes. Merge everything, including this one, into a single box. + displayio_area_t merged = clipped; + for (uint8_t i = 0; i < self->dirty_count; i++) { + displayio_area_union(&merged, &self->dirty[i], &merged); + } + self->dirty[0] = merged; + self->dirty_count = 1; +} + +#if CIRCUITPY_EPAPERDISPLAY_FAST +void epaperdisplay_backend_full_area(epaperdisplay_epaper_core_t *self, displayio_area_t *area) { + epaperdisplay_lvgl_full_area(self->display, area); +} + +bool epaperdisplay_backend_clip_area(epaperdisplay_epaper_core_t *self, const displayio_area_t *area, + displayio_area_t *clipped) { + return epaperdisplay_lvgl_clip_area(self->display, area, clipped); +} + +void epaperdisplay_backend_render_area(epaperdisplay_epaper_core_t *self, const displayio_area_t *area, + uint8_t *frame, uint16_t frame_stride, bool white) { + epaperdisplay_lvgl_render_area(self->display, area, frame, frame_stride, white); + RUN_BACKGROUND_TASKS; +} + +void epaperdisplay_backend_finish_refresh(epaperdisplay_epaper_core_t *self) { + epaperdisplay_lvgl_finish_refresh(self->display); +} + +void epaperdisplay_backend_set_full_refresh(epaperdisplay_epaper_core_t *self, bool full_refresh) { + epaperdisplay_epaperdisplay_obj_t *obj = self->display; + obj->full_refresh = full_refresh; +} + +void epaperdisplay_backend_set_refresh_in_progress(epaperdisplay_epaper_core_t *self, bool in_progress) { + epaperdisplay_epaperdisplay_obj_t *obj = self->display; + obj->refresh_in_progress = in_progress; +} +#endif + +// Store one converted panel pixel in a packed plane. Bits run most significant first and each +// row starts on a byte boundary, which is what the controllers and the legacy compositor write. +static void epaperdisplay_lvgl_store_pixel(epaperdisplay_epaperdisplay_obj_t *self, uint8_t *buf, + uint16_t x, uint16_t y, uint8_t value, bool inverted) { + uint8_t depth = self->canvas_depth; + uint8_t pixels_per_byte = 8 / depth; + uint8_t mask = (1u << depth) - 1u; + value &= mask; + if (inverted) { + value ^= mask; + } + uint16_t byte_index = y * self->canvas_stride + x / pixels_per_byte; + uint8_t shift = (pixels_per_byte - 1 - (x % pixels_per_byte)) * depth; + buf[byte_index] = (buf[byte_index] & ~(mask << shift)) | (value << shift); +} + +static uint32_t epaperdisplay_lvgl_rgb565_to_rgb888(uint16_t pixel) { + uint32_t r8 = (pixel >> 11) << 3; + uint32_t g8 = ((pixel >> 5) << 2) & 0xff; + uint32_t b8 = (pixel << 3) & 0xff; + return (r8 << 16) | (g8 << 8) | b8; +} + +static void epaperdisplay_lvgl_flush_cb(lv_display_t *disp, const lv_area_t *area, uint8_t *px_map) { + epaperdisplay_epaperdisplay_obj_t *self = lv_display_get_user_data(disp); + lv_display_rotation_t rotation = lv_display_get_rotation(disp); + const uint8_t *src = px_map; + lv_area_t rotated_area; + uint32_t src_stride = lv_draw_buf_width_to_stride(lv_area_get_width(area), self->lv_color_format); + + if (rotation != LV_DISPLAY_ROTATION_0) { + rotated_area = *area; + lv_display_rotate_area(disp, &rotated_area); + uint32_t dest_stride = lv_draw_buf_width_to_stride( + lv_area_get_width(&rotated_area), self->lv_color_format); + if ((size_t)dest_stride * lv_area_get_height(&rotated_area) > self->lv_rotation_buf_size) { + // The rotation buffer is sized for the longest edge. A larger flush means the + // display geometry changed without reconfiguring; drop this frame rather than + // writing past the buffer. + lv_display_flush_ready(disp); + return; + } + lv_color_format_t rotate_format = self->lv_color_format; + if (rotate_format == LV_COLOR_FORMAT_RGB565_SWAPPED) { + rotate_format = LV_COLOR_FORMAT_RGB565; + } + lv_draw_rotate(px_map, self->lv_rotation_buf, lv_area_get_width(area), + lv_area_get_height(area), src_stride, dest_stride, rotation, rotate_format); + area = &rotated_area; + src = self->lv_rotation_buf; + src_stride = dest_stride; + } + + _displayio_colorspace_t black_cs = self->epaper.core.colorspace; + if (!self->epaper.acep) { + black_cs.grayscale = true; + black_cs.grayscale_bit = 7; + } + _displayio_colorspace_t color_cs = self->epaper.core.colorspace; + bool color_convert = false; + if (self->color_buf != NULL) { + if (self->epaper.grayscale) { + color_cs.grayscale = true; + color_cs.grayscale_bit = 6; + color_convert = true; + } else if (color_cs.tricolor) { + color_cs.grayscale = false; + color_convert = true; + } else if (color_cs.sixcolor || color_cs.sevencolor) { + color_convert = true; + } + } + + for (int32_t y = area->y1; y <= area->y2; y++) { + // px_map (or the rotated copy) starts at the flush area's first pixel. + const uint8_t *row = src + (y - area->y1) * src_stride; + for (int32_t x = area->x1; x <= area->x2; x++) { + uint16_t source_pixel; + memcpy(&source_pixel, row, sizeof(source_pixel)); + row += sizeof(source_pixel); + uint32_t rgb = epaperdisplay_lvgl_rgb565_to_rgb888(source_pixel); + displayio_input_pixel_t input_pixel = { + .pixel = rgb, + .x = x, + .y = y, + .tile_x = x, + .tile_y = y, + }; + displayio_output_pixel_t output_pixel; + output_pixel.pixel = 0; + output_pixel.opaque = false; + displayio_convert_color(&black_cs, black_cs.dither, &input_pixel, &output_pixel); + epaperdisplay_lvgl_store_pixel(self, self->black_buf, x, y, + output_pixel.pixel, self->epaper.black_bits_inverted); + + if (self->color_buf != NULL) { + if (color_convert) { + displayio_convert_color(&color_cs, color_cs.dither, &input_pixel, &output_pixel); + } else { + output_pixel.pixel = 0; + } + epaperdisplay_lvgl_store_pixel(self, self->color_buf, x, y, + output_pixel.pixel, self->epaper.color_bits_inverted); + } + } + } + + // LVGL area coordinates are inclusive; displayio's are exclusive. + displayio_area_t dirty_area = { + .x1 = area->x1, + .y1 = area->y1, + .x2 = area->x2 + 1, + .y2 = area->y2 + 1, + }; + epaperdisplay_lvgl_mark_dirty(self, &dirty_area); + lv_display_flush_ready(disp); +} + +static void epaperdisplay_lvgl_start_refresh(epaperdisplay_epaperdisplay_obj_t *self) { + epaperdisplay_epaper_core_t *core = &self->epaper; + if (!displayio_display_bus_is_free(&core->bus)) { + // Can't acquire display bus; skip updating this display. Try next display. + return; + } + if (!epaperdisplay_lvgl_begin_refresh(self)) { + // Refresh on this display already in progress. + return; + } + + #if CIRCUITPY_EPAPERDISPLAY_FAST + if (core->fast && core->awake) { + if (!core->needs_start) { + // The panel is still configured from the previous refresh. + return; + } + epaperdisplay_epaper_core_wait_for_busy(core); + // SSD168x controllers commit the last RAM byte when the next command arrives, so a reset + // can't come straight after a RAM write. + epaperdisplay_epaper_core_send_stop_sequence_guarded(core); + core->awake = false; + } + #endif + + // run start sequence + core->bus.bus_reset(core->bus.bus); + + epaperdisplay_epaper_core_delay_ms(core, core->start_up_time_ms); + + #if CIRCUITPY_EPAPERDISPLAY_FAST + if (!epaperdisplay_epaper_core_send_command_sequence(core, true, core->start_sequence, core->start_sequence_len) || + epaperdisplay_epaper_core_interrupted(core)) { + return; + } + core->awake = true; + core->needs_start = false; + #else + epaperdisplay_epaper_core_send_command_sequence(core, true, core->start_sequence, core->start_sequence_len); + #endif +} + +#if CIRCUITPY_EPAPERDISPLAY_FAST +void epaperdisplay_epaper_core_start_refresh(epaperdisplay_epaper_core_t *self) { + epaperdisplay_lvgl_start_refresh(self->display); +} +#endif + +static bool epaperdisplay_epaperdisplay_refresh_area(epaperdisplay_epaperdisplay_obj_t *self, + const displayio_area_t *area, bool write_previous); + +#if CIRCUITPY_EPAPERDISPLAY_FAST +static void epaperdisplay_epaperdisplay_finish_refresh(epaperdisplay_epaperdisplay_obj_t *self, + const displayio_area_t *areas, uint8_t area_count) { + // Actually refresh the display now that all pixel RAM has been updated. + epaperdisplay_epaper_core_send_command_sequence(&self->epaper, false, self->epaper.refresh_sequence, self->epaper.refresh_sequence_len); + const uint64_t refresh_start = supervisor_ticks_ms64(); + bool previous_written = true; + mp_obj_t raised = MP_OBJ_NULL; + + if (self->epaper.write_previous_ram_command != NO_COMMAND && area_count > 0) { + // Copy the new image into the previous image RAM so the next partial update compares + // against what is on screen. The controller ignores RAM writes while it is updating. + if (self->epaper.busy.base.type == &mp_type_NoneType) { + common_hal_time_delay_ms(self->epaper.refresh_time); + } else { + previous_written = epaperdisplay_epaper_core_wait_for_update_end(&self->epaper); + } + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + for (uint8_t i = 0; i < area_count && previous_written; i++) { + previous_written = !mp_hal_is_interrupted() && + epaperdisplay_epaperdisplay_refresh_area(self, &areas[i], true); + } + nlr_pop(); + } else { + // Ctrl-C raises from a transfer in progress, and that transaction is still open. + raised = nlr.ret_val; + previous_written = false; + if (!displayio_display_bus_is_free(&self->epaper.bus)) { + displayio_display_bus_end_transaction(&self->epaper.bus); + } + } + } + + supervisor_enable_tick(); + self->epaper.refreshing = true; + + epaperdisplay_lvgl_finish_refresh(self); + // The update began before the wait above, and refresh_time and seconds_per_frame count from it. + self->epaper.core.last_refresh = refresh_start; + if (!previous_written) { + // The previous RAM is stale, so the next update has to write everything. + self->full_refresh = true; + } + if (raised != MP_OBJ_NULL) { + nlr_jump(raised); + } +} +#else +static void epaperdisplay_epaperdisplay_finish_refresh(epaperdisplay_epaperdisplay_obj_t *self, + const displayio_area_t *areas, uint8_t area_count) { + // Actually refresh the display now that all pixel RAM has been updated. + epaperdisplay_epaper_core_send_command_sequence(&self->epaper, false, self->epaper.refresh_sequence, self->epaper.refresh_sequence_len); + + supervisor_enable_tick(); + self->epaper.refreshing = true; + + epaperdisplay_lvgl_finish_refresh(self); +} +#endif // CIRCUITPY_EPAPERDISPLAY_FAST + +void common_hal_epaperdisplay_epaperdisplay_set_rotation(epaperdisplay_epaperdisplay_obj_t *self, int rotation) { + // Only the logical dimensions change here. The canvas and LVGL's original resolution stay + // in the controller's native RAM orientation established by the constructor. + bool transposed = (self->epaper.core.rotation == 90 || self->epaper.core.rotation == 270); + bool will_transposed = (rotation == 90 || rotation == 270); + if (transposed != will_transposed) { + int tmp = self->epaper.core.width; + self->epaper.core.width = self->epaper.core.height; + self->epaper.core.height = tmp; + } + displayio_display_core_set_rotation(&self->epaper.core, rotation); + if (self->lv_display != NULL) { + // LVGL rotates the opposite way from displayio for the transposed orientations. + lv_display_rotation_t lv_rotation; + switch (rotation) { + case 90: + lv_rotation = LV_DISPLAY_ROTATION_270; + break; + case 270: + lv_rotation = LV_DISPLAY_ROTATION_90; + break; + case 180: + lv_rotation = LV_DISPLAY_ROTATION_180; + break; + default: + lv_rotation = LV_DISPLAY_ROTATION_0; + break; + } + nlr_jump_callback_node_t cleanup; + displayio_lvgl_lock_with_cleanup(&cleanup); + lv_display_set_rotation(self->lv_display, lv_rotation); + lv_display_set_default(self->lv_display); + self->full_refresh = true; + self->dirty_full = true; + displayio_lvgl_unlock_with_cleanup(); + } + if (self == &displays[0].epaper_display) { + supervisor_stop_terminal(); + supervisor_start_terminal(self->epaper.core.width, self->epaper.core.height); + } + if (self->epaper.core.current_group != NULL) { + nlr_jump_callback_node_t cleanup; + displayio_lvgl_lock_with_cleanup(&cleanup); + displayio_lvgl_set_root_group(self->epaper.core.current_group); + displayio_lvgl_unlock_with_cleanup(); + } +} + +// Send one packed plane from the converted framebuffer. The area must already be clipped to +// whole bytes of pixels. +static bool epaperdisplay_lvgl_send_plane(epaperdisplay_epaperdisplay_obj_t *self, uint8_t command, + const uint8_t *buf, const displayio_area_t *area) { + displayio_area_t region = *area; + if (self->epaper.bus.row_command != NO_COMMAND) { + displayio_display_bus_set_region_to_update(&self->epaper.bus, &self->epaper.core.colorspace, ®ion); + } + if (!displayio_display_bus_begin_transaction(&self->epaper.bus)) { + return false; + } + self->epaper.bus.send(self->epaper.bus.bus, DISPLAY_COMMAND, self->epaper.chip_select, &command, 1); + displayio_display_bus_end_transaction(&self->epaper.bus); + + uint16_t bytes_per_row = displayio_area_width(area) * self->canvas_depth / 8; + uint16_t first_byte = area->x1 * self->canvas_depth / 8; + uint8_t chunk[512]; + size_t used = 0; + for (int16_t y = area->y1; y < area->y2; y++) { + const uint8_t *row = buf + y * self->canvas_stride + first_byte; + if (bytes_per_row > sizeof(chunk)) { + if (!displayio_display_bus_begin_transaction(&self->epaper.bus)) { + return false; + } + self->epaper.bus.send(self->epaper.bus.bus, DISPLAY_DATA, self->epaper.chip_select, row, bytes_per_row); + displayio_display_bus_end_transaction(&self->epaper.bus); + } else { + if (used + bytes_per_row > sizeof(chunk)) { + if (!displayio_display_bus_begin_transaction(&self->epaper.bus)) { + return false; + } + self->epaper.bus.send(self->epaper.bus.bus, DISPLAY_DATA, self->epaper.chip_select, chunk, used); + displayio_display_bus_end_transaction(&self->epaper.bus); + used = 0; + } + memcpy(chunk + used, row, bytes_per_row); + used += bytes_per_row; + } + // Run background tasks so they can run during an explicit refresh. + // Auto-refresh won't run background tasks here because it is a background task itself. + RUN_BACKGROUND_TASKS; + + // Run USB background tasks so they can run during an implicit refresh. + #if CIRCUITPY_TINYUSB + usb_background(); + #endif + } + if (used > 0) { + if (!displayio_display_bus_begin_transaction(&self->epaper.bus)) { + return false; + } + self->epaper.bus.send(self->epaper.bus.bus, DISPLAY_DATA, self->epaper.chip_select, chunk, used); + displayio_display_bus_end_transaction(&self->epaper.bus); + } + return true; +} + +static bool epaperdisplay_epaperdisplay_refresh_area(epaperdisplay_epaperdisplay_obj_t *self, + const displayio_area_t *area, bool write_previous) { + displayio_area_t clipped; + // Clip the area to the display by overlapping the areas. If there is no overlap then we're done. + if (!epaperdisplay_lvgl_clip_area(self, area, &clipped)) { + return true; + } + if (write_previous) { + #if CIRCUITPY_EPAPERDISPLAY_FAST + if (self->epaper.write_previous_ram_command != NO_COMMAND) { + return epaperdisplay_lvgl_send_plane(self, self->epaper.write_previous_ram_command, + self->black_buf, &clipped); + } + #endif + return true; + } + if (!epaperdisplay_lvgl_send_plane(self, self->epaper.write_black_ram_command, self->black_buf, &clipped)) { + return false; + } + if (self->epaper.write_color_ram_command != NO_COMMAND && self->color_buf != NULL) { + if (!epaperdisplay_lvgl_send_plane(self, self->epaper.write_color_ram_command, self->color_buf, &clipped)) { + return false; + } + } + return true; +} + +static bool _clean_area(epaperdisplay_epaperdisplay_obj_t *self) { + uint16_t width = self->canvas_width; + uint16_t height = self->canvas_height; + + uint8_t buffer[width / 2]; + memset(buffer, 0x77, width / 2); + + uint8_t write_command = self->epaper.write_black_ram_command; + if (!displayio_display_bus_begin_transaction(&self->epaper.bus)) { + return false; + } + self->epaper.bus.send(self->epaper.bus.bus, DISPLAY_COMMAND, self->epaper.chip_select, &write_command, 1); + displayio_display_bus_end_transaction(&self->epaper.bus); + + for (uint16_t j = 0; j < height; j++) { + if (!displayio_display_bus_begin_transaction(&self->epaper.bus)) { + // Can't acquire display bus; skip the rest of the data. Try next display. + return false; + } + self->epaper.bus.send(self->epaper.bus.bus, DISPLAY_DATA, self->epaper.chip_select, buffer, width / 2); + displayio_display_bus_end_transaction(&self->epaper.bus); + + // TODO(tannewt): Make refresh displays faster so we don't starve other + // background tasks. + #if CIRCUITPY_TINYUSB + usb_background(); + #endif + } + + return true; +} + +bool common_hal_epaperdisplay_epaperdisplay_refresh(epaperdisplay_epaperdisplay_obj_t *self) { + + if (self->epaper.refreshing && self->epaper.busy.base.type == &digitalio_digitalinout_type) { + if (common_hal_digitalio_digitalinout_get_value(&self->epaper.busy) != self->epaper.busy_state) { + supervisor_disable_tick(); + self->epaper.refreshing = false; + #if CIRCUITPY_EPAPERDISPLAY_FAST + if (!self->epaper.fast) { + // Run stop sequence but don't wait for busy after it, because some panels set busy + // when sleeping. + epaperdisplay_epaper_core_send_command_sequence(&self->epaper, false, self->epaper.stop_sequence, self->epaper.stop_sequence_len); + } + #else + // Run stop sequence but don't wait for busy after it, because some panels set busy + // when sleeping. + epaperdisplay_epaper_core_send_command_sequence(&self->epaper, false, self->epaper.stop_sequence, self->epaper.stop_sequence_len); + #endif + } else { + #if CIRCUITPY_EPAPERDISPLAY_FAST + epaperdisplay_lag_give_up_if_stuck(&self->epaper); + #endif + return false; + } + } + if (self->epaper.core.current_group == NULL) { + #if CIRCUITPY_EPAPERDISPLAY_FAST + // Nothing to draw, but the drive already started is still owed. + if (self->epaper.lag.frames > 0 && self->epaper.awake) { + nlr_jump_callback_node_t cleanup; + displayio_lvgl_lock_with_cleanup(&cleanup); + bool ok = epaperdisplay_lag_refresh(&self->epaper, NULL, 0); + displayio_lvgl_unlock_with_cleanup(); + return ok; + } + #endif + return true; + } + // Refresh at seconds per frame rate. + if (common_hal_epaperdisplay_epaperdisplay_get_time_to_refresh(self) > 0) { + return false; + } + if (!displayio_display_bus_is_free(&self->epaper.bus)) { + // Can't acquire display bus; skip updating this display. Try next display. + return false; + } + + // Hold the LVGL lock from the compose and flush that brings the converted framebuffer up to + // date through the transfers that read it. The render task otherwise shares this display. + nlr_jump_callback_node_t cleanup; + displayio_lvgl_lock_with_cleanup(&cleanup); + + if (self->full_refresh && self->lv_display != NULL) { + self->dirty_full = true; + lv_obj_t *screen = lv_display_get_screen_active(self->lv_display); + if (screen != NULL) { + lv_obj_invalidate(screen); + } + } + if (self->lv_display != NULL) { + lv_refr_now(self->lv_display); + } + + displayio_area_t areas[EPAPER_LVGL_MAX_DIRTY]; + uint8_t area_count = 0; + if (self->dirty_full || self->epaper.bus.row_command == NO_COMMAND) { + // Without a RAM window, a short transfer would start at the controller's current cursor + // instead of the dirty area's coordinates, leaving a mixture of old and new frames. + epaperdisplay_lvgl_full_area(self, &areas[0]); + area_count = 1; + } else if (self->dirty_count > 0) { + memcpy(areas, self->dirty, self->dirty_count * sizeof(areas[0])); + area_count = self->dirty_count; + } + + #if CIRCUITPY_EPAPERDISPLAY_FAST + if (self->epaper.lag.frames > 0) { + bool ok = epaperdisplay_lag_refresh(&self->epaper, area_count > 0 ? areas : NULL, area_count); + displayio_lvgl_unlock_with_cleanup(); + return ok; + } + #endif // CIRCUITPY_EPAPERDISPLAY_FAST + + if (area_count == 0) { + displayio_lvgl_unlock_with_cleanup(); + return true; + } + + if (self->epaper.acep) { + epaperdisplay_lvgl_start_refresh(self); + _clean_area(self); + epaperdisplay_epaperdisplay_finish_refresh(self, NULL, 0); + while (self->epaper.refreshing && !mp_hal_is_interrupted()) { + RUN_BACKGROUND_TASKS; + } + } + if (mp_hal_is_interrupted()) { + displayio_lvgl_unlock_with_cleanup(); + return false; + } + + epaperdisplay_lvgl_start_refresh(self); + for (uint8_t i = 0; i < area_count; i++) { + epaperdisplay_epaperdisplay_refresh_area(self, &areas[i], false); + } + epaperdisplay_epaperdisplay_finish_refresh(self, areas, area_count); + displayio_lvgl_unlock_with_cleanup(); + return true; +} + +void release_epaperdisplay(epaperdisplay_epaperdisplay_obj_t *self) { + #if CIRCUITPY_EPAPERDISPLAY_FAST + epaperdisplay_lag_shutdown(&self->epaper); + epaperdisplay_lag_free(&self->epaper); + #endif // CIRCUITPY_EPAPERDISPLAY_FAST + if (self->epaper.refreshing) { + // Mark the refresh as done before waiting for busy. Otherwise the background task could + // end the refresh during the wait by running the stop sequence, and on panels that set + // busy when sleeping, such as the SSD1680, the wait would never end. + supervisor_disable_tick(); + self->epaper.refreshing = false; + epaperdisplay_epaper_core_wait_for_busy(&self->epaper); + + // Run stop sequence but don't wait for busy after it, because some panels set busy when + // sleeping. + #if CIRCUITPY_EPAPERDISPLAY_FAST + if (self->epaper.fast) { + epaperdisplay_epaper_core_send_stop_sequence_guarded(&self->epaper); + } else { + epaperdisplay_epaper_core_send_command_sequence(&self->epaper, false, self->epaper.stop_sequence, self->epaper.stop_sequence_len); + } + #else + epaperdisplay_epaper_core_send_command_sequence(&self->epaper, false, self->epaper.stop_sequence, self->epaper.stop_sequence_len); + #endif + } + #if CIRCUITPY_EPAPERDISPLAY_FAST + else if (self->epaper.fast && self->epaper.awake) { + epaperdisplay_epaper_core_send_stop_sequence_guarded(&self->epaper); + } + self->epaper.awake = false; + #endif + #if CIRCUITPY_EPAPERDISPLAY_FAST + epaperdisplay_lag_release_interrupts(&self->epaper); + #endif // CIRCUITPY_EPAPERDISPLAY_FAST + + if (self->lv_display != NULL) { + nlr_jump_callback_node_t cleanup; + displayio_lvgl_lock_with_cleanup(&cleanup); + displayio_lvgl_set_root_group(NULL); + lv_display_delete(self->lv_display); + self->lv_display = NULL; + displayio_lvgl_unlock_with_cleanup(); + } + // These allocations are from the port heap and outlive the VM, so free them explicitly. + port_free(self->lv_buf); + port_free(self->lv_rotation_buf); + self->lv_buf = NULL; + self->lv_rotation_buf = NULL; + self->lv_buf_size = 0; + self->lv_rotation_buf_size = 0; + port_free(self->black_buf); + port_free(self->color_buf); + self->black_buf = NULL; + self->color_buf = NULL; + self->dirty_count = 0; + self->dirty_full = false; + self->refresh_in_progress = false; + release_display_core(&self->epaper.core); + if (self->epaper.busy.base.type == &digitalio_digitalinout_type) { + common_hal_digitalio_digitalinout_deinit(&self->epaper.busy); + } +} + +void epaperdisplay_epaperdisplay_reset(epaperdisplay_epaperdisplay_obj_t *self) { + #if CIRCUITPY_EPAPERDISPLAY_FAST + if (self->epaper.lag.frames > 0) { + // Only a primary display gets here; reset_displays() has released the others. The heap is + // still here but the sequences won't be, and the display would otherwise persist to draw + // the splash with them. Finish now and stay asleep. Its bus still holds the pins until + // the next VM ends or release_displays(). + epaperdisplay_epaper_core_end_held_bus(&self->epaper); + release_epaperdisplay(self); + self->base.type = &mp_type_NoneType; + return; + } + #endif // CIRCUITPY_EPAPERDISPLAY_FAST + displayio_display_core_set_root_group(&self->epaper.core, &circuitpython_splash); + if (self->lv_display != NULL) { + nlr_jump_callback_node_t cleanup; + displayio_lvgl_lock_with_cleanup(&cleanup); + self->full_refresh = true; + self->dirty_full = true; + lv_display_set_default(self->lv_display); + displayio_lvgl_set_root_group(&circuitpython_splash); + lv_obj_t *screen = lv_display_get_screen_active(self->lv_display); + if (screen != NULL) { + lv_obj_invalidate(screen); + } + displayio_lvgl_unlock_with_cleanup(); + } else { + self->full_refresh = true; + self->dirty_full = true; + } + #if CIRCUITPY_EPAPERDISPLAY_FAST + // Let the panel sleep after the next refresh when code isn't running. + if (self->epaper.fast && self->epaper.awake && !self->epaper.refreshing) { + // Nothing can catch a raise from a send. A reload may be pending. + epaperdisplay_epaper_core_end_held_bus(&self->epaper); + epaperdisplay_epaper_core_send_stop_sequence_guarded(&self->epaper); + self->epaper.awake = false; + } + self->epaper.fast = false; + #endif +} + +uint16_t common_hal_epaperdisplay_epaperdisplay_get_width(epaperdisplay_epaperdisplay_obj_t *self) { + return epaperdisplay_epaper_core_get_width(&self->epaper); +} + +uint16_t common_hal_epaperdisplay_epaperdisplay_get_height(epaperdisplay_epaperdisplay_obj_t *self) { + return epaperdisplay_epaper_core_get_height(&self->epaper); +} + +uint16_t common_hal_epaperdisplay_epaperdisplay_get_rotation(epaperdisplay_epaperdisplay_obj_t *self) { + return epaperdisplay_epaper_core_get_rotation(&self->epaper); +} + +mp_obj_t common_hal_epaperdisplay_epaperdisplay_get_root_group(epaperdisplay_epaperdisplay_obj_t *self) { + return epaperdisplay_epaper_core_get_root_group(&self->epaper); +} + +mp_obj_t common_hal_epaperdisplay_epaperdisplay_get_bus(epaperdisplay_epaperdisplay_obj_t *self) { + return epaperdisplay_epaper_core_get_bus(&self->epaper); +} + +uint32_t common_hal_epaperdisplay_epaperdisplay_get_time_to_refresh(epaperdisplay_epaperdisplay_obj_t *self) { + return epaperdisplay_epaper_core_get_time_to_refresh(&self->epaper); +} + +bool common_hal_epaperdisplay_epaperdisplay_get_busy(epaperdisplay_epaperdisplay_obj_t *self) { + return epaperdisplay_epaper_core_get_busy(&self->epaper); +} + +void epaperdisplay_epaperdisplay_change_refresh_mode_parameters(epaperdisplay_epaperdisplay_obj_t *self, + mp_buffer_info_t *start_sequence, mp_buffer_info_t *refresh_sequence, float seconds_per_frame) { + epaperdisplay_epaper_core_change_refresh_mode_parameters(&self->epaper, + start_sequence, refresh_sequence, seconds_per_frame); +} + +void epaperdisplay_epaperdisplay_background(epaperdisplay_epaperdisplay_obj_t *self) { + epaperdisplay_epaper_core_background(&self->epaper); +} + +void epaperdisplay_epaperdisplay_collect_ptrs(epaperdisplay_epaperdisplay_obj_t *self) { + epaperdisplay_epaper_core_collect_ptrs(&self->epaper); +} + +#if CIRCUITPY_EPAPERDISPLAY_FAST +void epaperdisplay_epaperdisplay_prepare_release(epaperdisplay_epaperdisplay_obj_t *self) { + epaperdisplay_epaper_core_prepare_release(&self->epaper); +} + +void epaperdisplay_epaperdisplay_end_held_bus(epaperdisplay_epaperdisplay_obj_t *self) { + epaperdisplay_epaper_core_end_held_bus(&self->epaper); +} + +bool common_hal_epaperdisplay_epaperdisplay_clean(epaperdisplay_epaperdisplay_obj_t *self, uint8_t frames, bool full) { + return epaperdisplay_epaper_core_clean(&self->epaper, frames, full); +} +#endif diff --git a/shared-module/epaperdisplay/lvgl/EPaperDisplay.h b/shared-module/epaperdisplay/lvgl/EPaperDisplay.h new file mode 100644 index 00000000000..34d89d0f604 --- /dev/null +++ b/shared-module/epaperdisplay/lvgl/EPaperDisplay.h @@ -0,0 +1,47 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Scott Shawcroft for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-module/epaperdisplay/epaper_core.h" + +#include "lvgl.h" + +// Dirty rectangles kept since the last panel refresh. When more than this arrive they are +// merged into one bounding box, which is still correct because every one is inside it. +#define EPAPER_LVGL_MAX_DIRTY 8 + +struct epaperdisplay_epaperdisplay_obj_t { + mp_obj_base_t base; + epaperdisplay_epaper_core_t epaper; + + // LVGL display. The draw buffer is RGB565; the flush callback converts it into the + // packed panel planes below. + lv_display_t *lv_display; + lv_color_format_t lv_color_format; + uint8_t *lv_buf; + size_t lv_buf_size; + uint8_t *lv_rotation_buf; + size_t lv_rotation_buf_size; + + // The converted framebuffer. Each byte holds (8 / canvas_depth) panel pixels, most + // significant pixel first, exactly as the panel RAM does. black_buf always exists. + // color_buf exists when the panel has a separate color RAM. + uint8_t *black_buf; + uint8_t *color_buf; + uint16_t canvas_stride; + uint16_t canvas_width; // Physical panel width, not the rotated display width. + uint16_t canvas_height; + uint8_t canvas_depth; + + // Areas the flush callback changed since the last panel refresh. + displayio_area_t dirty[EPAPER_LVGL_MAX_DIRTY]; + uint8_t dirty_count; + bool dirty_full; + bool refresh_in_progress; + bool full_refresh; +}; diff --git a/shared-module/fontio/BuiltinFont.c b/shared-module/fontio/BuiltinFont.c index e24fe9c7f37..03ef933c55c 100644 --- a/shared-module/fontio/BuiltinFont.c +++ b/shared-module/fontio/BuiltinFont.c @@ -16,7 +16,8 @@ mp_obj_t common_hal_fontio_builtinfont_get_bitmap(const fontio_builtinfont_t *se } mp_obj_t common_hal_fontio_builtinfont_get_bounding_box(const fontio_builtinfont_t *self) { - mp_obj_t *items = m_new(mp_obj_t, 2); + // Stack allocation is ok because tuple copies the values out. + mp_obj_t items[2]; items[0] = MP_OBJ_NEW_SMALL_INT(self->width); items[1] = MP_OBJ_NEW_SMALL_INT(self->height); return mp_obj_new_tuple(2, items); diff --git a/shared-module/fourwire/FourWire.c b/shared-module/fourwire/FourWire.c index 0a168fa1563..ebc11dccfbd 100644 --- a/shared-module/fourwire/FourWire.c +++ b/shared-module/fourwire/FourWire.c @@ -11,47 +11,41 @@ #include "py/gc.h" #include "shared-bindings/busio/SPI.h" #include "shared-bindings/digitalio/DigitalInOut.h" +#include "shared-bindings/digitalio/DigitalInOutProtocol.h" #include "shared-bindings/microcontroller/Pin.h" #include "shared-bindings/microcontroller/__init__.h" #include "shared-bindings/time/__init__.h" +#include "supervisor/port.h" void common_hal_fourwire_fourwire_construct(fourwire_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, + busio_spi_obj_t *spi, mp_obj_t command, + mp_obj_t chip_select, mp_obj_t reset, uint32_t baudrate, uint8_t polarity, uint8_t phase) { self->bus = spi; - common_hal_busio_spi_never_reset(self->bus); self->frequency = baudrate; self->polarity = polarity; self->phase = phase; + // Allocate the pins in the same place as self. + bool use_port_allocation = !gc_alloc_possible() || !gc_ptr_on_heap(self); - self->command.base.type = &mp_type_NoneType; - if (command != NULL) { - 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); - common_hal_never_reset_pin(command); + self->command = digitalinout_protocol_from_pin(command, MP_QSTR_command, true, use_port_allocation, &self->own_command); + if (self->command != mp_const_none) { + digitalinout_protocol_switch_to_output(self->command, true, DRIVE_MODE_PUSH_PULL); } - 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); - common_hal_never_reset_pin(reset); + + self->reset = digitalinout_protocol_from_pin(reset, MP_QSTR_reset, true, use_port_allocation, &self->own_reset); + if (self->reset != mp_const_none) { + digitalinout_protocol_switch_to_output(self->reset, true, DRIVE_MODE_PUSH_PULL); common_hal_fourwire_fourwire_reset(self); } - self->chip_select.base.type = &mp_type_NoneType; - if (chip_select != NULL) { - 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); - common_hal_never_reset_pin(chip_select); + self->chip_select = digitalinout_protocol_from_pin(chip_select, MP_QSTR_chip_select, true, use_port_allocation, &self->own_chip_select); + if (self->chip_select != mp_const_none) { + digitalinout_protocol_switch_to_output(self->chip_select, true, DRIVE_MODE_PUSH_PULL); } - } void common_hal_fourwire_fourwire_deinit(fourwire_fourwire_obj_t *self) { @@ -59,19 +53,33 @@ void common_hal_fourwire_fourwire_deinit(fourwire_fourwire_obj_t *self) { common_hal_busio_spi_deinit(self->bus); } - common_hal_reset_pin(self->command.pin); - common_hal_reset_pin(self->chip_select.pin); - common_hal_reset_pin(self->reset.pin); + // Only deinit and free the pins if we own them + if (self->command != mp_const_none && self->own_command) { + digitalinout_protocol_deinit(self->command); + circuitpy_free_obj(self->command); + } + if (self->chip_select != mp_const_none && self->own_chip_select) { + digitalinout_protocol_deinit(self->chip_select); + circuitpy_free_obj(self->chip_select); + } + if (self->reset != mp_const_none && self->own_reset) { + digitalinout_protocol_deinit(self->reset); + circuitpy_free_obj(self->reset); + } } bool common_hal_fourwire_fourwire_reset(mp_obj_t obj) { fourwire_fourwire_obj_t *self = MP_OBJ_TO_PTR(obj); - if (self->reset.base.type == &mp_type_NoneType) { + if (self->reset == mp_const_none) { + return false; + } + if (digitalinout_protocol_set_value(self->reset, false) != 0) { return false; } - common_hal_digitalio_digitalinout_set_value(&self->reset, false); common_hal_mcu_delay_us(1000); - common_hal_digitalio_digitalinout_set_value(&self->reset, true); + if (digitalinout_protocol_set_value(self->reset, true) != 0) { + return false; + } common_hal_mcu_delay_us(1000); return true; } @@ -92,16 +100,23 @@ bool common_hal_fourwire_fourwire_begin_transaction(mp_obj_t obj) { } common_hal_busio_spi_configure(self->bus, self->frequency, self->polarity, self->phase, 8); - if (self->chip_select.base.type != &mp_type_NoneType) { - common_hal_digitalio_digitalinout_set_value(&self->chip_select, false); + if (self->chip_select != mp_const_none) { + // IO Expander CS can fail due to an I2C lock. + if (digitalinout_protocol_set_value(self->chip_select, false) != 0) { + common_hal_busio_spi_unlock(self->bus); + return false; + } } return true; } void common_hal_fourwire_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) { + if (data_length == 0) { + return; + } fourwire_fourwire_obj_t *self = MP_OBJ_TO_PTR(obj); - if (self->command.base.type == &mp_type_NoneType) { + if (self->command == mp_const_none) { // When the data/command pin is not specified, we simulate a 9-bit SPI mode, by // adding a data/command bit to every byte, and then splitting the resulting data back // into 8-bit chunks for transmission. If the length of the data being transmitted @@ -133,24 +148,24 @@ void common_hal_fourwire_fourwire_send(mp_obj_t obj, display_byte_type_t data_ty if (bits > 0) { buffer = buffer << (8 - bits); common_hal_busio_spi_write(self->bus, &buffer, 1); - if (self->chip_select.base.type != &mp_type_NoneType) { + if (self->chip_select != mp_const_none) { // toggle CS to discard superfluous bits - common_hal_digitalio_digitalinout_set_value(&self->chip_select, true); + digitalinout_protocol_set_value(self->chip_select, true); common_hal_mcu_delay_us(1); - common_hal_digitalio_digitalinout_set_value(&self->chip_select, false); + digitalinout_protocol_set_value(self->chip_select, false); } } } else { - common_hal_digitalio_digitalinout_set_value(&self->command, data_type == DISPLAY_DATA); + digitalinout_protocol_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 // IC latches commands based on it. for (size_t i = 0; i < data_length; i++) { common_hal_busio_spi_write(self->bus, &data[i], 1); - if (self->chip_select.base.type != &mp_type_NoneType) { - common_hal_digitalio_digitalinout_set_value(&self->chip_select, true); + if (self->chip_select != mp_const_none) { + digitalinout_protocol_set_value(self->chip_select, true); common_hal_mcu_delay_us(1); - common_hal_digitalio_digitalinout_set_value(&self->chip_select, false); + digitalinout_protocol_set_value(self->chip_select, false); } } } else { @@ -159,10 +174,33 @@ void common_hal_fourwire_fourwire_send(mp_obj_t obj, display_byte_type_t data_ty } } +#if CIRCUITPY_BUSIO_SPI_ASYNC +void common_hal_fourwire_fourwire_send_async(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) { + fourwire_fourwire_obj_t *self = MP_OBJ_TO_PTR(obj); + // Without a DC pin every byte carries a DC bit, and the toggling mode pulses CS per byte: + // both are sent byte by byte, so they stay synchronous. + if (self->command == mp_const_none || chip_select == CHIP_SELECT_TOGGLE_EVERY_BYTE) { + common_hal_fourwire_fourwire_send(obj, data_type, chip_select, data, data_length); + return; + } + if (data_length == 0) { + return; + } + digitalinout_protocol_set_value(self->command, data_type == DISPLAY_DATA); + common_hal_busio_spi_write_start(self->bus, data, data_length, &self->sent); +} + +void common_hal_fourwire_fourwire_flush(mp_obj_t obj) { + fourwire_fourwire_obj_t *self = MP_OBJ_TO_PTR(obj); + common_hal_busio_spi_end(self->bus); +} +#endif + void common_hal_fourwire_fourwire_end_transaction(mp_obj_t obj) { fourwire_fourwire_obj_t *self = MP_OBJ_TO_PTR(obj); - if (self->chip_select.base.type != &mp_type_NoneType) { - common_hal_digitalio_digitalinout_set_value(&self->chip_select, true); + if (self->chip_select != mp_const_none) { + digitalinout_protocol_set_value(self->chip_select, true); } common_hal_busio_spi_unlock(self->bus); } diff --git a/shared-module/fourwire/FourWire.h b/shared-module/fourwire/FourWire.h index 629a426b3b0..1abf74fcadc 100644 --- a/shared-module/fourwire/FourWire.h +++ b/shared-module/fourwire/FourWire.h @@ -6,6 +6,8 @@ #pragma once +#include + #include "common-hal/busio/SPI.h" #include "common-hal/digitalio/DigitalInOut.h" #include "shared-module/displayio/Group.h" @@ -14,10 +16,16 @@ typedef struct { mp_obj_base_t base; busio_spi_obj_t *bus; busio_spi_obj_t inline_bus; - digitalio_digitalinout_obj_t command; - digitalio_digitalinout_obj_t chip_select; - digitalio_digitalinout_obj_t reset; + mp_obj_t command; + mp_obj_t chip_select; + mp_obj_t reset; uint32_t frequency; uint8_t polarity; uint8_t phase; + bool own_command; + bool own_chip_select; + bool own_reset; + #if CIRCUITPY_BUSIO_SPI_ASYNC + circuitpy_async_flag_t sent; // set once the last send_async has been sent + #endif } fourwire_fourwire_obj_t; diff --git a/shared-module/framebufferio/FramebufferDisplay.c b/shared-module/framebufferio/FramebufferDisplay.c deleted file mode 100644 index c9fe52e0e40..00000000000 --- a/shared-module/framebufferio/FramebufferDisplay.c +++ /dev/null @@ -1,349 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2018 Scott Shawcroft for Adafruit Industries -// SPDX-FileCopyrightText: Copyright (c) 2020 Jeff Epler for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include "shared-bindings/framebufferio/FramebufferDisplay.h" - -#include "py/gc.h" -#include "py/runtime.h" -#include "shared-bindings/microcontroller/Pin.h" -#include "shared-bindings/time/__init__.h" -#include "shared-module/displayio/__init__.h" -#include "shared-module/displayio/display_core.h" -#include "supervisor/shared/display.h" -#include "supervisor/shared/tick.h" - -#if CIRCUITPY_TINYUSB -#include "supervisor/usb.h" -#endif - -#include -#include - -#define fb_getter_default(method, default_value) \ - (self->framebuffer_protocol->method \ - ? 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) { - // Turn off auto-refresh as we init. - self->auto_refresh = false; - self->framebuffer = framebuffer; - self->framebuffer_protocol = mp_proto_get_or_throw(MP_QSTR_protocol_framebuffer, framebuffer); - - uint16_t depth = fb_getter_default(get_color_depth, 16); - displayio_display_core_construct( - &self->core, - self->framebuffer_protocol->get_width(self->framebuffer), - self->framebuffer_protocol->get_height(self->framebuffer), - 0, // rotation - depth, - fb_getter_default(get_grayscale, (depth < 8)), - fb_getter_default(get_pixels_in_byte_share_row, false), - 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->framebuffer_protocol->get_bufinfo(self->framebuffer, &self->bufinfo); - size_t framebuffer_size = self->first_pixel_offset + self->row_stride * (self->core.height - 1) + self->core.width * self->core.colorspace.depth / 8; - - mp_arg_validate_length_min(self->bufinfo.len, framebuffer_size, MP_QSTR_framebuffer); - - self->first_manual_refresh = !auto_refresh; - - self->native_frames_per_second = fb_getter_default(get_native_frames_per_second, 60); - self->native_ms_per_frame = 1000 / self->native_frames_per_second; - - if (rotation != 0) { - common_hal_framebufferio_framebufferdisplay_set_rotation(self, rotation); - } - - // Set the group after initialization otherwise we may send pixels while we delay in - // initialization. - displayio_display_core_set_root_group(&self->core, &circuitpython_splash); - common_hal_framebufferio_framebufferdisplay_set_auto_refresh(self, auto_refresh); -} - -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) { - return displayio_display_core_get_height(&self->core); -} - -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 ok = false; - if (self->framebuffer_protocol->set_brightness) { - self->framebuffer_protocol->set_brightness(self->framebuffer, brightness); - ok = true; - } - return ok; -} - -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) { - if (self->core.full_refresh) { - self->core.area.next = NULL; - return &self->core.area; - } else if (self->core.current_group != NULL) { - return displayio_group_get_refresh_areas(self->core.current_group, NULL); - } - 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) { - uint16_t buffer_size = CIRCUITPY_DISPLAY_AREA_BUFFER_SIZE / sizeof(uint32_t); // In uint32_ts - - displayio_area_t clipped; - // Clip the area to the display by overlapping the areas. If there is no overlap then we're done. - if (!displayio_display_core_clip_area(&self->core, area, &clipped)) { - return true; - } - uint16_t subrectangles = 1; - - // If pixels are packed by row then rows are on byte boundaries - if (self->core.colorspace.depth < 8 && self->core.colorspace.pixels_in_byte_share_row) { - int div = 8 / self->core.colorspace.depth; - clipped.x1 = (clipped.x1 / div) * div; - clipped.x2 = ((clipped.x2 + div - 1) / div) * div; - } - - uint16_t rows_per_buffer = displayio_area_height(&clipped); - uint8_t pixels_per_word = (sizeof(uint32_t) * 8) / self->core.colorspace.depth; - uint16_t pixels_per_buffer = displayio_area_size(&clipped); - if (displayio_area_size(&clipped) > buffer_size * pixels_per_word) { - rows_per_buffer = buffer_size * pixels_per_word / displayio_area_width(&clipped); - if (rows_per_buffer == 0) { - rows_per_buffer = 1; - } - // If pixels are packed by column then ensure rows_per_buffer is on a byte boundary. - if (self->core.colorspace.depth < 8 && !self->core.colorspace.pixels_in_byte_share_row) { - uint8_t pixels_per_byte = 8 / self->core.colorspace.depth; - if (rows_per_buffer % pixels_per_byte != 0) { - rows_per_buffer -= rows_per_buffer % pixels_per_byte; - } - } - subrectangles = displayio_area_height(&clipped) / rows_per_buffer; - if (displayio_area_height(&clipped) % rows_per_buffer != 0) { - subrectangles++; - } - pixels_per_buffer = rows_per_buffer * displayio_area_width(&clipped); - buffer_size = pixels_per_buffer / pixels_per_word; - if (pixels_per_buffer % pixels_per_word) { - buffer_size += 1; - } - } - - // Allocated and shared as a uint32_t array so the compiler knows the - // alignment everywhere. - uint32_t buffer[buffer_size]; - uint32_t mask_length = (pixels_per_buffer / 32) + 1; - uint32_t mask[mask_length]; - uint16_t remaining_rows = displayio_area_height(&clipped); - - for (uint16_t j = 0; j < subrectangles; j++) { - displayio_area_t subrectangle = { - .x1 = clipped.x1, - .y1 = clipped.y1 + rows_per_buffer * j, - .x2 = clipped.x2, - .y2 = clipped.y1 + rows_per_buffer * (j + 1) - }; - - if (remaining_rows < rows_per_buffer) { - subrectangle.y2 = subrectangle.y1 + remaining_rows; - } - remaining_rows -= rows_per_buffer; - - memset(mask, 0, mask_length * sizeof(mask[0])); - memset(buffer, 0, buffer_size * sizeof(buffer[0])); - - displayio_display_core_fill_area(&self->core, &subrectangle, mask, buffer); - - uint8_t *buf = (uint8_t *)self->bufinfo.buf, *endbuf = buf + self->bufinfo.len; - (void)endbuf; // Hint to compiler that endbuf is "used" even if NDEBUG - buf += self->first_pixel_offset; - - 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; - 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); - MARK_ROW_DIRTY(i); - memcpy(dest, src, rowsize); - dest += rowstride; - src += rowsize; - } - - // TODO(tannewt): Make refresh displays faster so we don't starve other - // background tasks. - #if CIRCUITPY_TINYUSB - usb_background(); - #endif - } - return true; -} - -static void _refresh_display(framebufferio_framebufferdisplay_obj_t *self) { - self->framebuffer_protocol->get_bufinfo(self->framebuffer, &self->bufinfo); - if (!self->bufinfo.buf) { - return; - } - displayio_display_core_start_refresh(&self->core); - const displayio_area_t *current_area = _get_refresh_areas(self); - if (current_area) { - bool transposed = (self->core.rotation == 90 || self->core.rotation == 270); - int row_count = transposed ? self->core.width : self->core.height; - uint8_t dirty_row_bitmask[(row_count + 7) / 8]; - memset(dirty_row_bitmask, 0, sizeof(dirty_row_bitmask)); - self->framebuffer_protocol->get_bufinfo(self->framebuffer, &self->bufinfo); - while (current_area != NULL) { - _refresh_area(self, current_area, dirty_row_bitmask); - current_area = current_area->next; - } - self->framebuffer_protocol->swapbuffers(self->framebuffer, dirty_row_bitmask); - } - displayio_display_core_finish_refresh(&self->core); -} - -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) { - int tmp = self->core.width; - self->core.width = self->core.height; - self->core.height = tmp; - } - displayio_display_core_set_rotation(&self->core, rotation); - if (self == &displays[0].framebuffer_display) { - supervisor_stop_terminal(); - supervisor_start_terminal(self->core.width, self->core.height); - } - if (self->core.current_group != NULL) { - displayio_group_update_transform(self->core.current_group, &self->core.transform); - } -} - -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) { - if (!self->auto_refresh && !self->first_manual_refresh && (target_ms_per_frame != NO_FPS_LIMIT)) { - 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. - if (current_ms_since_real_refresh > maximum_ms_per_real_frame) { - mp_raise_RuntimeError(MP_ERROR_TEXT("Below minimum frame rate")); - } - uint32_t current_ms_since_last_call = current_time - self->last_refresh_call; - self->last_refresh_call = current_time; - // Skip the actual refresh to help catch up. - if (current_ms_since_last_call > target_ms_per_frame) { - return false; - } - uint32_t remaining_time = target_ms_per_frame - (current_ms_since_real_refresh % target_ms_per_frame); - // We're ahead of the game so wait until we align with the frame rate. - while (supervisor_ticks_ms64() - self->last_refresh_call < remaining_time) { - RUN_BACKGROUND_TASKS; - } - } - self->first_manual_refresh = false; - _refresh_display(self); - return true; -} - -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) { - self->first_manual_refresh = !auto_refresh; - if (auto_refresh != self->auto_refresh) { - if (auto_refresh) { - supervisor_enable_tick(); - } else { - supervisor_disable_tick(); - } - } - self->auto_refresh = auto_refresh; -} - -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) { - _update_backlight(self); - - if (self->auto_refresh && (supervisor_ticks_ms64() - self->core.last_refresh) > self->native_ms_per_frame) { - _refresh_display(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) { - gc_collect_ptr(self->framebuffer); - displayio_display_core_collect_ptrs(&self->core); -} - -void framebufferio_framebufferdisplay_reset(framebufferio_framebufferdisplay_obj_t *self) { - const mp_obj_type_t *fb_type = mp_obj_get_type(self->framebuffer); - if (fb_type != NULL && fb_type != &mp_type_NoneType) { - common_hal_framebufferio_framebufferdisplay_set_auto_refresh(self, true); - displayio_display_core_set_root_group(&self->core, &circuitpython_splash); - self->core.full_refresh = true; - } else { - release_framebufferdisplay(self); - } -} - -mp_obj_t common_hal_framebufferio_framebufferdisplay_get_root_group(framebufferio_framebufferdisplay_obj_t *self) { - if (self->core.current_group == NULL) { - return mp_const_none; - } - return self->core.current_group; -} - -mp_obj_t common_hal_framebufferio_framebufferdisplay_set_root_group(framebufferio_framebufferdisplay_obj_t *self, displayio_group_t *root_group) { - bool ok = displayio_display_core_set_root_group(&self->core, root_group); - if (!ok) { - mp_raise_ValueError(MP_ERROR_TEXT("Group already used")); - } - return mp_const_none; -} diff --git a/shared-module/framebufferio/FramebufferDisplay.h b/shared-module/framebufferio/FramebufferDisplay.h index 871d34abcbe..a1761382353 100644 --- a/shared-module/framebufferio/FramebufferDisplay.h +++ b/shared-module/framebufferio/FramebufferDisplay.h @@ -7,77 +7,8 @@ #pragma once -#include "py/obj.h" -#include "py/proto.h" - -#include "shared-bindings/displayio/Group.h" - -#include "shared-module/displayio/area.h" -#include "shared-module/displayio/display_core.h" - -typedef struct { - mp_obj_base_t base; - displayio_display_core_t core; - mp_obj_t framebuffer; - const struct _framebuffer_p_t *framebuffer_protocol; - mp_buffer_info_t bufinfo; - uint64_t last_refresh_call; - uint16_t native_frames_per_second; - uint16_t native_ms_per_frame; - uint16_t first_pixel_offset; - uint16_t row_stride; - bool auto_refresh; - 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_collect_ptrs(framebufferio_framebufferdisplay_obj_t *self); - -mp_obj_t common_hal_framebufferio_framebufferdisplay_get_framebuffer(framebufferio_framebufferdisplay_obj_t *self); - -typedef bool (*framebuffer_get_reverse_pixels_in_byte_fun)(mp_obj_t); -typedef bool (*framebuffer_get_reverse_pixels_in_word_fun)(mp_obj_t); -typedef bool (*framebuffer_set_brightness_fun)(mp_obj_t, mp_float_t); -typedef int (*framebuffer_get_bytes_per_cell_fun)(mp_obj_t); -typedef int (*framebuffer_get_color_depth_fun)(mp_obj_t); -typedef int (*framebuffer_get_first_pixel_offset_fun)(mp_obj_t); -typedef bool (*framebuffer_get_grayscale_fun)(mp_obj_t); -typedef int (*framebuffer_get_height_fun)(mp_obj_t); -typedef int (*framebuffer_get_native_frames_per_second_fun)(mp_obj_t); -typedef bool (*framebuffer_get_pixels_in_byte_share_row_fun)(mp_obj_t); -typedef int (*framebuffer_get_row_stride_fun)(mp_obj_t); -typedef int (*framebuffer_get_width_fun)(mp_obj_t); -typedef mp_float_t (*framebuffer_get_brightness_fun)(mp_obj_t); -typedef void (*framebuffer_deinit_fun)(mp_obj_t); -typedef void (*framebuffer_get_bufinfo_fun)(mp_obj_t, mp_buffer_info_t *bufinfo); -typedef void (*framebuffer_swapbuffers_fun)(mp_obj_t, uint8_t *dirty_row_bitmask); - -typedef struct _framebuffer_p_t { - MP_PROTOCOL_HEAD // MP_QSTR_protocol_framebuffer - - // Mandatory - framebuffer_get_bufinfo_fun get_bufinfo; - framebuffer_swapbuffers_fun swapbuffers; - framebuffer_deinit_fun deinit; - framebuffer_get_width_fun get_width; - framebuffer_get_height_fun get_height; - - // Optional getters - framebuffer_get_bytes_per_cell_fun get_bytes_per_cell; // default: 2 - framebuffer_get_color_depth_fun get_color_depth; // default: 16 - framebuffer_get_first_pixel_offset_fun get_first_pixel_offset; // default: 0 - framebuffer_get_grayscale_fun get_grayscale; // default: grayscale if depth < 8 - framebuffer_get_native_frames_per_second_fun get_native_frames_per_second; // default: 60 - framebuffer_get_pixels_in_byte_share_row_fun get_pixels_in_byte_share_row; // default: false - framebuffer_get_reverse_pixels_in_byte_fun get_reverse_pixels_in_byte; // default: false - framebuffer_get_reverse_pixels_in_word_fun get_reverse_pixels_in_word; // default: false - framebuffer_get_row_stride_fun get_row_stride; // default: 0 (no extra row padding) - - // Optional -- default is no brightness control - framebuffer_get_brightness_fun get_brightness; - framebuffer_set_brightness_fun set_brightness; - -} framebuffer_p_t; +#if CIRCUITPY_DISPLAYIO_LVGL +#include "shared-module/framebufferio/lvgl/FramebufferDisplay.h" +#else +#include "shared-module/framebufferio/legacy/FramebufferDisplay.h" +#endif diff --git a/shared-module/framebufferio/__init__.h b/shared-module/framebufferio/__init__.h index c9069db9fd7..5b840d8e6e9 100644 --- a/shared-module/framebufferio/__init__.h +++ b/shared-module/framebufferio/__init__.h @@ -5,3 +5,8 @@ // SPDX-License-Identifier: MIT #pragma once + +// Optional frame-boundary callback. The framebuffer invokes it once per frame from a +// task/background context, never an interrupt handler. A display uses it to pace rendering to +// the source (for example a UVC frame or a panel vsync) instead of the autorefresh tick. +typedef void (*framebuffer_frame_callback_t)(void *user_data); diff --git a/shared-module/framebufferio/legacy/FramebufferDisplay.c b/shared-module/framebufferio/legacy/FramebufferDisplay.c new file mode 100644 index 00000000000..f8fbd83fd5d --- /dev/null +++ b/shared-module/framebufferio/legacy/FramebufferDisplay.c @@ -0,0 +1,376 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018 Scott Shawcroft for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2020 Jeff Epler for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/framebufferio/FramebufferDisplay.h" + +#include "py/gc.h" +#include "py/runtime.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/time/__init__.h" +#include "shared-module/displayio/__init__.h" +#include "shared-module/displayio/display_core.h" +#include "supervisor/background_callback.h" +#include "supervisor/shared/display.h" +#include "supervisor/shared/tick.h" + +#if CIRCUITPY_WEB_WORKFLOW +#include "supervisor/shared/web_workflow/display_stream.h" +#endif + + +#if CIRCUITPY_TINYUSB +#include "supervisor/usb.h" +#endif + +#include +#include + +#define fb_getter_default(method, default_value) \ + (self->framebuffer_protocol->method \ + ? 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) { + // Turn off auto-refresh as we init. + self->auto_refresh = false; + self->framebuffer = framebuffer; + self->framebuffer_protocol = mp_proto_get_or_throw(MP_QSTR_protocol_framebuffer, framebuffer); + + uint16_t depth = fb_getter_default(get_color_depth, 16); + displayio_display_core_construct( + &self->core, + self->framebuffer_protocol->get_width(self->framebuffer), + self->framebuffer_protocol->get_height(self->framebuffer), + 0, // rotation + depth, + fb_getter_default(get_grayscale, (depth < 8)), + fb_getter_default(get_pixels_in_byte_share_row, false), + 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->framebuffer_protocol->get_bufinfo(self->framebuffer, &self->bufinfo); + size_t framebuffer_size = self->first_pixel_offset + self->row_stride * (self->core.height - 1) + self->core.width * self->core.colorspace.depth / 8; + + mp_arg_validate_length_min(self->bufinfo.len, framebuffer_size, MP_QSTR_framebuffer); + + self->first_manual_refresh = !auto_refresh; + + self->native_frames_per_second = fb_getter_default(get_native_frames_per_second, 60); + self->native_ms_per_frame = 1000 / self->native_frames_per_second; + + + if (rotation != 0) { + common_hal_framebufferio_framebufferdisplay_set_rotation(self, rotation); + } + + // Set the group after initialization otherwise we may send pixels while we delay in + // initialization. + displayio_display_core_set_root_group(&self->core, &circuitpython_splash); + common_hal_framebufferio_framebufferdisplay_set_auto_refresh(self, auto_refresh); +} + +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) { + return displayio_display_core_get_height(&self->core); +} + +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 ok = false; + if (self->framebuffer_protocol->set_brightness) { + self->framebuffer_protocol->set_brightness(self->framebuffer, brightness); + ok = true; + } + return ok; +} + +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) { + if (self->core.full_refresh) { + self->core.area.next = NULL; + return &self->core.area; + } else if (self->core.current_group != NULL) { + return displayio_group_get_refresh_areas(self->core.current_group, NULL); + } + 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) { + uint16_t buffer_size = CIRCUITPY_DISPLAY_AREA_BUFFER_SIZE / sizeof(uint32_t); // In uint32_ts + + displayio_area_t clipped; + // Clip the area to the display by overlapping the areas. If there is no overlap then we're done. + if (!displayio_display_core_clip_area(&self->core, area, &clipped)) { + return true; + } + uint16_t subrectangles = 1; + + // If pixels are packed by row then rows are on byte boundaries + if (self->core.colorspace.depth < 8 && self->core.colorspace.pixels_in_byte_share_row) { + int div = 8 / self->core.colorspace.depth; + clipped.x1 = (clipped.x1 / div) * div; + clipped.x2 = ((clipped.x2 + div - 1) / div) * div; + } + + uint16_t rows_per_buffer = displayio_area_height(&clipped); + uint16_t cols_per_buffer = displayio_area_width(&clipped); + uint8_t pixels_per_word = (sizeof(uint32_t) * 8) / self->core.colorspace.depth; + uint16_t pixels_per_buffer = displayio_area_size(&clipped); + if (displayio_area_size(&clipped) > buffer_size * pixels_per_word) { + uint32_t buffer_pixels = buffer_size * pixels_per_word; + if (self->core.transform.transpose_xy && self->core.colorspace.depth >= 8) { + // Rotated 90 or 270: a panel column is a source row. Square tiles keep both the + // source reads and the framebuffer writes within a few cache lines. + uint16_t side = 1 << ((31 - __builtin_clz(buffer_pixels)) / 2); + rows_per_buffer = MIN(rows_per_buffer, side); + cols_per_buffer = buffer_pixels / rows_per_buffer; + } else { + rows_per_buffer = buffer_pixels / cols_per_buffer; + if (rows_per_buffer == 0) { + rows_per_buffer = 1; + } + // If pixels are packed by column then ensure rows_per_buffer is on a byte boundary. + if (self->core.colorspace.depth < 8 && !self->core.colorspace.pixels_in_byte_share_row) { + uint8_t pixels_per_byte = 8 / self->core.colorspace.depth; + if (rows_per_buffer % pixels_per_byte != 0) { + rows_per_buffer -= rows_per_buffer % pixels_per_byte; + } + } + } + subrectangles = ((displayio_area_height(&clipped) + rows_per_buffer - 1) / rows_per_buffer) * + ((displayio_area_width(&clipped) + cols_per_buffer - 1) / cols_per_buffer); + pixels_per_buffer = rows_per_buffer * cols_per_buffer; + buffer_size = (pixels_per_buffer + pixels_per_word - 1) / pixels_per_word; + } + + // Allocated and shared as a uint32_t array so the compiler knows the + // alignment everywhere. + uint32_t buffer[buffer_size]; + uint32_t mask_length = (pixels_per_buffer / 32) + 1; + uint32_t mask[mask_length]; + + displayio_area_t subrectangle = clipped; + subrectangle.next = NULL; + + for (uint16_t j = 0; j < subrectangles; j++) { + // Down the rows of a band first, then to the next band of columns. + if (subrectangle.y1 >= clipped.y2) { + subrectangle.y1 = clipped.y1; + subrectangle.x1 += cols_per_buffer; + } + subrectangle.x2 = MIN(subrectangle.x1 + cols_per_buffer, clipped.x2); + subrectangle.y2 = MIN(subrectangle.y1 + rows_per_buffer, clipped.y2); + + memset(mask, 0, mask_length * sizeof(mask[0])); + memset(buffer, 0, buffer_size * sizeof(buffer[0])); + + bool covered = displayio_display_core_fill_area(&self->core, &subrectangle, mask, buffer); + + // A framebuffer-target VideoBuffer that is the only layer here reports + // full coverage without claiming pixels: its frame is already in the + // framebuffer, so don't overwrite it with the empty scratch. + bool write_back = true; + if (covered) { + write_back = false; + for (uint32_t m = 0; m < mask_length; m++) { + if (mask[m] != 0) { + write_back = true; + break; + } + } + } + + uint8_t *buf = (uint8_t *)self->bufinfo.buf, *endbuf = buf + self->bufinfo.len; + (void)endbuf; // Hint to compiler that endbuf is "used" even if NDEBUG + buf += self->first_pixel_offset; + + 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; + 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); + MARK_ROW_DIRTY(i); + if (write_back) { + memcpy(dest, src, rowsize); + } + dest += rowstride; + src += rowsize; + } + #if CIRCUITPY_WEB_WORKFLOW + display_stream_area_updated(&self->core, &subrectangle); + #endif + // Run background tasks so they can run during a refresh. Auto-refresh allows + // them in framebufferio_framebufferdisplay_background(). + RUN_BACKGROUND_TASKS; + + // Run USB background tasks so they can run during an implicit refresh. + #if CIRCUITPY_TINYUSB + usb_background(); + #endif + subrectangle.y1 = subrectangle.y2; + } + return true; +} + +static void _refresh_display(framebufferio_framebufferdisplay_obj_t *self) { + self->framebuffer_protocol->get_bufinfo(self->framebuffer, &self->bufinfo); + if (!self->bufinfo.buf) { + return; + } + if (!displayio_display_core_start_refresh(&self->core)) { + // Refresh on this display already in progress. + return; + } + const displayio_area_t *current_area = _get_refresh_areas(self); + if (current_area) { + bool transposed = (self->core.rotation == 90 || self->core.rotation == 270); + int row_count = transposed ? self->core.width : self->core.height; + uint8_t dirty_row_bitmask[(row_count + 7) / 8]; + memset(dirty_row_bitmask, 0, sizeof(dirty_row_bitmask)); + self->framebuffer_protocol->get_bufinfo(self->framebuffer, &self->bufinfo); + while (current_area != NULL) { + _refresh_area(self, current_area, dirty_row_bitmask); + current_area = current_area->next; + } + self->framebuffer_protocol->swapbuffers(self->framebuffer, dirty_row_bitmask); + } + displayio_display_core_finish_refresh(&self->core); +} + +void common_hal_framebufferio_framebufferdisplay_set_rotation(framebufferio_framebufferdisplay_obj_t *self, int rotation) { + displayio_display_core_set_rotation_and_update(&self->core, rotation, &self->base); +} + +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) { + if (!self->auto_refresh && !self->first_manual_refresh && (target_ms_per_frame != NO_FPS_LIMIT)) { + 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. + if (current_ms_since_real_refresh > maximum_ms_per_real_frame) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Below minimum frame rate")); + } + uint32_t current_ms_since_last_call = current_time - self->last_refresh_call; + self->last_refresh_call = current_time; + // Skip the actual refresh to help catch up. + if (current_ms_since_last_call > target_ms_per_frame) { + return false; + } + uint32_t remaining_time = target_ms_per_frame - (current_ms_since_real_refresh % target_ms_per_frame); + // We're ahead of the game so wait until we align with the frame rate. + while (supervisor_ticks_ms64() - self->last_refresh_call < remaining_time) { + RUN_BACKGROUND_TASKS; + } + } + self->first_manual_refresh = false; + _refresh_display(self); + return true; +} + +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) { + self->first_manual_refresh = !auto_refresh; + if (auto_refresh != self->auto_refresh) { + if (auto_refresh) { + supervisor_enable_tick(); + } else { + supervisor_disable_tick(); + } + } + self->auto_refresh = auto_refresh; +} + +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) { + _update_backlight(self); + + if (self->auto_refresh && (supervisor_ticks_ms64() - self->core.last_refresh) > self->native_ms_per_frame) { + // Auto-refresh runs inside a background callback, which blocks other callbacks. + // Allow callbacks so RUN_BACKGROUND_TASKS in _refresh_area() can run them. + // refresh_in_progress stops a nested refresh of this display. + background_callback_allow(); + _refresh_display(self); + background_callback_prevent(); + } +} + +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) { + gc_collect_ptr(self->framebuffer); + displayio_display_core_collect_ptrs(&self->core); +} + +void framebufferio_framebufferdisplay_reset(framebufferio_framebufferdisplay_obj_t *self) { + const mp_obj_type_t *fb_type = mp_obj_get_type(self->framebuffer); + if (fb_type != NULL && fb_type != &mp_type_NoneType) { + common_hal_framebufferio_framebufferdisplay_set_auto_refresh(self, true); + displayio_display_core_set_root_group(&self->core, &circuitpython_splash); + self->core.full_refresh = true; + } else { + release_framebufferdisplay(self); + } +} + +mp_obj_t common_hal_framebufferio_framebufferdisplay_get_root_group(framebufferio_framebufferdisplay_obj_t *self) { + if (self->core.current_group == NULL) { + return mp_const_none; + } + return self->core.current_group; +} + +mp_obj_t common_hal_framebufferio_framebufferdisplay_set_root_group(framebufferio_framebufferdisplay_obj_t *self, displayio_group_t *root_group) { + bool ok = displayio_display_core_set_root_group(&self->core, root_group); + if (!ok) { + mp_raise_ValueError(MP_ERROR_TEXT("Group already used")); + } + return mp_const_none; +} diff --git a/shared-module/framebufferio/legacy/FramebufferDisplay.h b/shared-module/framebufferio/legacy/FramebufferDisplay.h new file mode 100644 index 00000000000..9e98e5f5d04 --- /dev/null +++ b/shared-module/framebufferio/legacy/FramebufferDisplay.h @@ -0,0 +1,88 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Scott Shawcroft for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2020 Jeff Epler for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-module/framebufferio/__init__.h" +#include "py/obj.h" +#include "py/proto.h" + +#include "shared-bindings/displayio/Group.h" + + +#include "shared-module/displayio/display_core.h" + +typedef struct { + mp_obj_base_t base; + displayio_display_core_t core; + mp_obj_t framebuffer; + const struct _framebuffer_p_t *framebuffer_protocol; + mp_buffer_info_t bufinfo; + uint64_t last_refresh_call; + uint16_t native_frames_per_second; + uint16_t native_ms_per_frame; + uint16_t first_pixel_offset; + uint16_t row_stride; + bool auto_refresh; + 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_collect_ptrs(framebufferio_framebufferdisplay_obj_t *self); + +mp_obj_t common_hal_framebufferio_framebufferdisplay_get_framebuffer(framebufferio_framebufferdisplay_obj_t *self); + +typedef bool (*framebuffer_get_reverse_pixels_in_byte_fun)(mp_obj_t); +typedef bool (*framebuffer_get_reverse_pixels_in_word_fun)(mp_obj_t); +typedef bool (*framebuffer_set_brightness_fun)(mp_obj_t, mp_float_t); +typedef int (*framebuffer_get_bytes_per_cell_fun)(mp_obj_t); +typedef int (*framebuffer_get_color_depth_fun)(mp_obj_t); +typedef int (*framebuffer_get_first_pixel_offset_fun)(mp_obj_t); +typedef bool (*framebuffer_get_grayscale_fun)(mp_obj_t); +typedef int (*framebuffer_get_height_fun)(mp_obj_t); +typedef int (*framebuffer_get_native_frames_per_second_fun)(mp_obj_t); +typedef bool (*framebuffer_get_pixels_in_byte_share_row_fun)(mp_obj_t); +typedef int (*framebuffer_get_row_stride_fun)(mp_obj_t); +typedef int (*framebuffer_get_width_fun)(mp_obj_t); +typedef mp_float_t (*framebuffer_get_brightness_fun)(mp_obj_t); +typedef void (*framebuffer_deinit_fun)(mp_obj_t); +typedef void (*framebuffer_get_bufinfo_fun)(mp_obj_t, mp_buffer_info_t *bufinfo); +typedef void (*framebuffer_swapbuffers_fun)(mp_obj_t, uint8_t *dirty_row_bitmask); +typedef void (*framebuffer_set_frame_callback_fun)(mp_obj_t, framebuffer_frame_callback_t, void *); + +typedef struct _framebuffer_p_t { + MP_PROTOCOL_HEAD // MP_QSTR_protocol_framebuffer + + // Mandatory + framebuffer_get_bufinfo_fun get_bufinfo; + framebuffer_swapbuffers_fun swapbuffers; + framebuffer_deinit_fun deinit; + framebuffer_get_width_fun get_width; + framebuffer_get_height_fun get_height; + + // Optional getters + framebuffer_get_bytes_per_cell_fun get_bytes_per_cell; // default: 2 + framebuffer_get_color_depth_fun get_color_depth; // default: 16 + framebuffer_get_first_pixel_offset_fun get_first_pixel_offset; // default: 0 + framebuffer_get_grayscale_fun get_grayscale; // default: grayscale if depth < 8 + framebuffer_get_native_frames_per_second_fun get_native_frames_per_second; // default: 60 + framebuffer_get_pixels_in_byte_share_row_fun get_pixels_in_byte_share_row; // default: false + framebuffer_get_reverse_pixels_in_byte_fun get_reverse_pixels_in_byte; // default: false + framebuffer_get_reverse_pixels_in_word_fun get_reverse_pixels_in_word; // default: false + framebuffer_get_row_stride_fun get_row_stride; // default: 0 (no extra row padding) + + // Optional -- default is no brightness control + framebuffer_get_brightness_fun get_brightness; + framebuffer_set_brightness_fun set_brightness; + + // Optional -- called at each frame boundary. Pass a NULL callback to clear it. + framebuffer_set_frame_callback_fun set_frame_callback; + +} framebuffer_p_t; diff --git a/shared-module/framebufferio/lvgl/FramebufferDisplay.c b/shared-module/framebufferio/lvgl/FramebufferDisplay.c new file mode 100644 index 00000000000..9f6c06dbb84 --- /dev/null +++ b/shared-module/framebufferio/lvgl/FramebufferDisplay.c @@ -0,0 +1,620 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018 Scott Shawcroft for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2020 Jeff Epler for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/framebufferio/FramebufferDisplay.h" + +#include "py/gc.h" +#include "py/runtime.h" +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/time/__init__.h" +#include "shared-module/displayio/__init__.h" +#include "shared-module/displayio/display_core.h" +#include "supervisor/shared/display.h" +#include "supervisor/shared/tick.h" + +#include "shared-module/displayio/lvgl/lvgl_internal.h" +#if CIRCUITPY_VIDEOCORE +#include "shared-module/videocore/VideoBuffer.h" +#endif +#include "supervisor/port_heap.h" +#if CIRCUITPY_WEB_WORKFLOW +#include "supervisor/shared/web_workflow/display_stream.h" +#endif + +#if CIRCUITPY_ESPIDF +#include "esp_attr.h" +#include +#define FRAMEBUFFERIO_LVGL_FRAME_CB IRAM_ATTR +#else +#define FRAMEBUFFERIO_LVGL_FRAME_CB +#endif + +#include "lvgl.h" +#include "lvgl/draw/lv_draw_utils.h" + +// Port allocations must be aligned enough for LVGL draw buffers and the PPA. +MP_STATIC_ASSERT(MICROPY_BYTES_PER_GC_BLOCK % LV_DRAW_BUF_ALIGN == 0); + +#if CIRCUITPY_TINYUSB +#include "supervisor/usb.h" +#endif + +#include +#include + +#define fb_getter_default(method, default_value) \ + (self->framebuffer_protocol->method \ + ? self->framebuffer_protocol->method(self->framebuffer) \ + : (default_value)) + + +// Rendering directly into a display's scanout framebuffer while its DMA is active can +// cause tearing or corruption on some controllers. Use the aligned partial buffer path +// by default; enable this only after validating direct rendering on a given port. +#define FRAMEBUFFERIO_LVGL_DIRECT 0 + +// Height of the aligned draw buffer used when the provided framebuffer can't be +// rendered into directly (for example, because it isn't aligned for LVGL's draw units). +#define FRAMEBUFFERIO_LVGL_PARTIAL_LINES 20 + +#define MARK_ROW_DIRTY(r) (self->lv_dirty_row_bitmask[(r) / 8] |= (1 << ((r) & 7))) + +static lv_color_format_t framebufferio_lvgl_color_format(framebufferio_framebufferdisplay_obj_t *self) { + switch (self->core.colorspace.depth) { + case 16: + return self->core.colorspace.reverse_bytes_in_word ? LV_COLOR_FORMAT_RGB565_SWAPPED : LV_COLOR_FORMAT_RGB565; + case 24: + return LV_COLOR_FORMAT_RGB888; + case 32: + return LV_COLOR_FORMAT_ARGB8888; + case 8: + return LV_COLOR_FORMAT_L8; + case 4: + return LV_COLOR_FORMAT_I4; + case 2: + return LV_COLOR_FORMAT_I2; + case 1: + return LV_COLOR_FORMAT_I1; + default: + return LV_COLOR_FORMAT_RGB565; + } +} + +static bool framebufferio_lvgl_can_render_direct(framebufferio_framebufferdisplay_obj_t *self) { + // Rotation is handled while flushing, which requires an intermediate buffer. + if (self->core.rotation != 0) { + return false; + } + uint8_t depth = self->core.colorspace.depth; + if (depth < 8 || depth % 8 != 0) { + return false; + } + size_t bytes_per_pixel = depth / 8; + if (self->row_stride != self->core.width * bytes_per_pixel || + self->row_stride != lv_draw_buf_width_to_stride(self->core.width, self->lv_color_format)) { + return false; + } + if (self->bufinfo.buf == NULL) { + return false; + } + // PPA also requires its output buffer size to be cache-line aligned. + if ((self->row_stride * self->core.height) % LV_DRAW_BUF_ALIGN != 0) { + return false; + } + uint8_t *framebuffer = (uint8_t *)self->bufinfo.buf + self->first_pixel_offset; + return lv_draw_buf_align(framebuffer, self->lv_color_format) == framebuffer; +} + +static void framebufferio_lvgl_free_partial_buf(framebufferio_framebufferdisplay_obj_t *self) { + if (self->lv_buf != NULL) { + port_free(self->lv_buf); + self->lv_buf = NULL; + self->lv_buf_size = 0; + } +} + +static bool framebufferio_lvgl_ensure_partial_buf(framebufferio_framebufferdisplay_obj_t *self) { + if (self->lv_buf != NULL) { + return true; + } + uint16_t max_width = self->core.width > self->core.height ? self->core.width : self->core.height; + size_t lines = FRAMEBUFFERIO_LVGL_PARTIAL_LINES; + if (lines > max_width) { + lines = max_width; + } + size_t buf_size = lv_draw_buf_width_to_stride(max_width, self->lv_color_format) * lines; + // The PPA draw unit requires its output buffer size to be cache-line aligned too. + buf_size = (buf_size + LV_DRAW_BUF_ALIGN - 1) & ~(LV_DRAW_BUF_ALIGN - 1); + self->lv_buf = port_malloc(buf_size, false); + if (self->lv_buf == NULL) { + return false; + } + self->lv_buf_size = buf_size; + return true; +} + +static bool framebufferio_lvgl_configure_buffers(framebufferio_framebufferdisplay_obj_t *self) { + if (FRAMEBUFFERIO_LVGL_DIRECT && framebufferio_lvgl_can_render_direct(self)) { + framebufferio_lvgl_free_partial_buf(self); + uint8_t *framebuffer = (uint8_t *)self->bufinfo.buf + self->first_pixel_offset; + lv_display_set_buffers(self->lv_display, framebuffer, NULL, + self->row_stride * self->core.height, LV_DISPLAY_RENDER_MODE_DIRECT); + self->lv_direct = true; + return true; + } + + if (!framebufferio_lvgl_ensure_partial_buf(self)) { + return false; + } + lv_display_set_buffers(self->lv_display, self->lv_buf, NULL, self->lv_buf_size, + LV_DISPLAY_RENDER_MODE_PARTIAL); + self->lv_direct = false; + return true; +} + +// Framebuffers that can signal a frame boundary pace LVGL instead of using the autorefresh tick. +// The refresh timer callback only pauses the timer: invalidations resume it, but nothing is drawn +// until the framebuffer reports a frame. That batches all changes made within one frame. +static void framebufferio_lvgl_paced_refr_cb(lv_timer_t *timer) { + lv_timer_pause(timer); +} + +// Called by the framebuffer at its frame boundary. It may run from an ISR (DPI vsync), so this +// must stay in IRAM on ESP and only hand off to the port hook. +static void FRAMEBUFFERIO_LVGL_FRAME_CB framebufferio_lvgl_frame_cb(void *user_data) { + framebufferio_framebufferdisplay_obj_t *self = user_data; + if (!self->auto_refresh || self->lv_display == NULL) { + return; + } + displayio_lvgl_port_frame_boundary(); +} + +static void framebufferio_lvgl_flush_cb(lv_display_t *disp, const lv_area_t *area, uint8_t *px_map) { + framebufferio_framebufferdisplay_obj_t *self = lv_display_get_user_data(disp); + lv_color_format_t color_format = lv_display_get_color_format(disp); + lv_display_rotation_t rotation = lv_display_get_rotation(disp); + uint16_t width = lv_area_get_width(area); + uint16_t height = lv_area_get_height(area); + size_t bytes_per_pixel = (self->core.colorspace.depth + 7) / 8; + uint8_t *framebuffer = (uint8_t *)self->bufinfo.buf + self->first_pixel_offset; + + if (rotation == LV_DISPLAY_ROTATION_0) { + if (!self->lv_direct) { + size_t source_stride = lv_draw_buf_width_to_stride(width, color_format); + size_t row_bytes = (width * self->core.colorspace.depth + 7) / 8; + for (uint16_t y = 0; y < height; y++) { + uint8_t *dest = framebuffer + (area->y1 + y) * self->row_stride + area->x1 * bytes_per_pixel; + memcpy(dest, px_map + y * source_stride, row_bytes); + } + } + for (uint16_t y = area->y1; y <= area->y2; y++) { + MARK_ROW_DIRTY(y); + } + #if CIRCUITPY_WEB_WORKFLOW + display_stream_area_updated(&self->core, area); + #endif + } else { + lv_area_t rotated_area = *area; + lv_display_rotate_area(disp, &rotated_area); + size_t source_stride = lv_draw_buf_width_to_stride(width, color_format); + uint8_t *dest = framebuffer + rotated_area.y1 * self->row_stride + rotated_area.x1 * bytes_per_pixel; + // RGB565_SWAPPED uses the same 16-bit pixel layout for the purpose of moving pixels. + lv_color_format_t rotate_format = color_format; + if (rotate_format == LV_COLOR_FORMAT_RGB565_SWAPPED) { + rotate_format = LV_COLOR_FORMAT_RGB565; + } + lv_draw_rotate(px_map, dest, width, height, source_stride, self->row_stride, rotation, rotate_format); + for (uint16_t y = rotated_area.y1; y <= rotated_area.y2; y++) { + MARK_ROW_DIRTY(y); + } + #if CIRCUITPY_WEB_WORKFLOW + // The stream reads the framebuffer, so it needs the area in the panel's orientation. + display_stream_area_updated(&self->core, &rotated_area); + #endif + } + + // Publish each flushed area now. LVGL doesn't reliably report the last flush part in all + // port/display combinations, and relying on it can leave new pixels in the CPU cache forever. + self->framebuffer_protocol->swapbuffers(self->framebuffer, self->lv_dirty_row_bitmask); + memset(self->lv_dirty_row_bitmask, 0, self->lv_dirty_row_bitmask_size); + lv_display_flush_ready(disp); + + // A refresh can take longer than the audio buffers last. Like the legacy + // framebufferio, let background tasks run between chunks of an explicit refresh. + if (displayio_lvgl_refresh_yield) { + RUN_BACKGROUND_TASKS; + } +} + + +typedef struct { + nlr_jump_callback_node_t node; + framebufferio_framebufferdisplay_obj_t *self; + bool locked; +} framebufferdisplay_construct_cleanup_t; + +static void framebufferdisplay_construct_abort(void *ctx) { + framebufferdisplay_construct_cleanup_t *cleanup = ctx; + framebufferio_framebufferdisplay_obj_t *self = cleanup->self; + if (!cleanup->locked) { + displayio_lvgl_lock(); + } + self->auto_refresh = false; + if (self->lv_paced) { + self->framebuffer_protocol->set_frame_callback(self->framebuffer, NULL, NULL); + self->lv_paced = false; + } + if (self->core.current_group != NULL) { + displayio_lvgl_set_root_group(NULL); + release_display_core(&self->core); + self->core.current_group = NULL; + } + if (self->lv_display != NULL) { + lv_display_delete(self->lv_display); + self->lv_display = NULL; + } + framebufferio_lvgl_free_partial_buf(self); + port_free(self->lv_dirty_row_bitmask); + self->lv_dirty_row_bitmask = NULL; + self->lv_dirty_row_bitmask_size = 0; + // A failed display constructor does not take ownership of the framebuffer. + self->framebuffer = mp_const_none; + self->base.type = &mp_type_NoneType; + displayio_lvgl_unlock(); +} + +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; + self->framebuffer_protocol = NULL; + self->core.current_group = NULL; + self->lv_display = NULL; + self->lv_color_format = LV_COLOR_FORMAT_UNKNOWN; + self->lv_buf = NULL; + self->lv_buf_size = 0; + self->lv_dirty_row_bitmask = NULL; + self->lv_dirty_row_bitmask_size = 0; + self->lv_direct = false; + self->lv_paced = false; + framebufferdisplay_construct_cleanup_t cleanup = { .self = self, .locked = false }; + nlr_push_jump_callback(&cleanup.node, framebufferdisplay_construct_abort); + self->framebuffer_protocol = mp_proto_get_or_throw(MP_QSTR_protocol_framebuffer, framebuffer); + + uint16_t depth = fb_getter_default(get_color_depth, 16); + // The flush path copies whole pixels. Packed sub-byte framebuffers need a + // separate bit-addressed transfer path; accepting them would overrun rows. + if (depth < 8) { + mp_raise_NotImplementedError(MP_ERROR_TEXT("Format not supported")); + } + displayio_display_core_construct( + &self->core, + self->framebuffer_protocol->get_width(self->framebuffer), + self->framebuffer_protocol->get_height(self->framebuffer), + 0, // rotation + depth, + fb_getter_default(get_grayscale, (depth < 8)), + fb_getter_default(get_pixels_in_byte_share_row, false), + 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->framebuffer_protocol->get_bufinfo(self->framebuffer, &self->bufinfo); + size_t framebuffer_size = self->first_pixel_offset + self->row_stride * (self->core.height - 1) + self->core.width * self->core.colorspace.depth / 8; + + mp_arg_validate_length_min(self->bufinfo.len, framebuffer_size, MP_QSTR_framebuffer); + + self->first_manual_refresh = !auto_refresh; + + self->native_frames_per_second = fb_getter_default(get_native_frames_per_second, 60); + self->native_ms_per_frame = 1000 / self->native_frames_per_second; + + displayio_lvgl_port_init(); + // Hold the render lock across the whole setup. The render task must not see this display as + // the default before it has buffers and a flush callback. The port lock is recursive, so the + // displayio_lvgl_* helpers below may take it again. + displayio_lvgl_lock(); + cleanup.locked = true; + + self->lv_display = lv_display_create(self->core.width, self->core.height); + if (self->lv_display == NULL) { + mp_raise_RuntimeError(MP_ERROR_TEXT("LVGL display create failed")); + } + lv_display_set_user_data(self->lv_display, self); + lv_display_set_default(self->lv_display); + displayio_lvgl_register_display(self->lv_display); + self->lv_color_format = framebufferio_lvgl_color_format(self); + lv_display_set_color_format(self->lv_display, self->lv_color_format); + lv_display_set_flush_cb(self->lv_display, framebufferio_lvgl_flush_cb); + if (self->framebuffer_protocol->set_frame_callback != NULL) { + lv_timer_t *refr_timer = lv_display_get_refr_timer(self->lv_display); + if (refr_timer != NULL) { + lv_timer_set_cb(refr_timer, framebufferio_lvgl_paced_refr_cb); + self->lv_paced = true; + self->framebuffer_protocol->set_frame_callback(self->framebuffer, + framebufferio_lvgl_frame_cb, self); + } + } + uint16_t max_dimension = self->core.width > self->core.height ? self->core.width : self->core.height; + self->lv_dirty_row_bitmask_size = (max_dimension + 7) / 8; + self->lv_dirty_row_bitmask = port_malloc(self->lv_dirty_row_bitmask_size, false); + if (self->lv_dirty_row_bitmask == NULL) { + mp_raise_msg(&mp_type_MemoryError, MP_ERROR_TEXT("LVGL dirty row alloc failed")); + } + memset(self->lv_dirty_row_bitmask, 0, self->lv_dirty_row_bitmask_size); + displayio_lvgl_init(); + if (!framebufferio_lvgl_configure_buffers(self)) { + mp_raise_msg(&mp_type_MemoryError, MP_ERROR_TEXT("LVGL buffer alloc failed")); + } + #if CIRCUITPY_ESPIDF + ESP_LOGI("LVGL", "FramebufferDisplay %ux%u depth %u (%s)", + self->core.width, self->core.height, self->core.colorspace.depth, + self->lv_direct ? "direct" : "partial"); + #endif + + if (rotation != 0) { + common_hal_framebufferio_framebufferdisplay_set_rotation(self, rotation); + } + + // Set the group after initialization otherwise we may send pixels while we delay in + // initialization. + displayio_display_core_set_root_group(&self->core, &circuitpython_splash); + displayio_lvgl_set_root_group(&circuitpython_splash); + nlr_pop_jump_callback(false); + displayio_lvgl_unlock(); + common_hal_framebufferio_framebufferdisplay_set_auto_refresh(self, auto_refresh); +} + +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) { + return displayio_display_core_get_height(&self->core); +} + +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 ok = false; + if (self->framebuffer_protocol->set_brightness) { + self->framebuffer_protocol->set_brightness(self->framebuffer, brightness); + ok = true; + } + return ok; +} + +mp_obj_t common_hal_framebufferio_framebufferdisplay_get_framebuffer(framebufferio_framebufferdisplay_obj_t *self) { + return self->framebuffer; +} + + +void common_hal_framebufferio_framebufferdisplay_set_rotation(framebufferio_framebufferdisplay_obj_t *self, int rotation) { + rotation %= 360; + // LVGL rotates the opposite way from displayio for the transposed orientations. + lv_display_rotation_t lv_rotation; + switch (rotation) { + case 90: + lv_rotation = LV_DISPLAY_ROTATION_270; + break; + case 270: + lv_rotation = LV_DISPLAY_ROTATION_90; + break; + case 180: + lv_rotation = LV_DISPLAY_ROTATION_180; + break; + default: + lv_rotation = LV_DISPLAY_ROTATION_0; + break; + } + #if CIRCUITPY_VIDEOCORE + // A framebuffer-target VideoBuffer writes into the framebuffer's physical + // memory, so it can't follow LVGL's whole-scene rotation. + if (self->lv_display != NULL && + !displayio_lvgl_video_can_rotate(self->lv_display, lv_rotation)) { + mp_raise_ValueError(MP_ERROR_TEXT("VideoBuffer can't stream into a rotated display")); + } + #endif + bool transposed = (self->core.rotation == 90 || self->core.rotation == 270); + bool will_transposed = (rotation == 90 || rotation == 270); + if (transposed != will_transposed) { + int tmp = self->core.width; + self->core.width = self->core.height; + self->core.height = tmp; + } + displayio_display_core_set_rotation(&self->core, rotation); + if (self->lv_display != NULL) { + nlr_jump_callback_node_t cleanup; + displayio_lvgl_lock_with_cleanup(&cleanup); + lv_display_set_rotation(self->lv_display, lv_rotation); + if (!framebufferio_lvgl_configure_buffers(self)) { + displayio_lvgl_unlock_with_cleanup(); + mp_raise_msg(&mp_type_MemoryError, MP_ERROR_TEXT("LVGL buffer alloc failed")); + } + lv_display_set_default(self->lv_display); + if (self == &displays[0].framebuffer_display) { + supervisor_stop_terminal(); + supervisor_start_terminal(self->core.width, self->core.height); + } + if (self->core.current_group != NULL) { + displayio_lvgl_set_root_group(self->core.current_group); + } + lv_obj_t *screen = lv_screen_active(); + if (screen != NULL) { + lv_obj_invalidate(screen); + } + displayio_lvgl_unlock_with_cleanup(); + } +} + +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) { + if (!self->auto_refresh && !self->first_manual_refresh && (target_ms_per_frame != NO_FPS_LIMIT)) { + 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. + if (current_ms_since_real_refresh > maximum_ms_per_real_frame) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Below minimum frame rate")); + } + uint32_t current_ms_since_last_call = current_time - self->last_refresh_call; + self->last_refresh_call = current_time; + // Skip the actual refresh to help catch up. + if (current_ms_since_last_call > target_ms_per_frame) { + return false; + } + uint32_t remaining_time = target_ms_per_frame - (current_ms_since_real_refresh % target_ms_per_frame); + // We're ahead of the game so wait until we align with the frame rate. + while (supervisor_ticks_ms64() - self->last_refresh_call < remaining_time) { + RUN_BACKGROUND_TASKS; + } + } + self->first_manual_refresh = false; + if (self->lv_display != NULL) { + // The renderer refreshes on its own thread too, so this has to exclude it. + displayio_lvgl_lock(); + displayio_lvgl_refresh_yield = true; + lv_refr_now(self->lv_display); + displayio_lvgl_refresh_yield = false; + displayio_lvgl_unlock(); + } + self->core.last_refresh = supervisor_ticks_ms64(); + return true; +} + +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) { + self->first_manual_refresh = !auto_refresh; + // No supervisor_enable/disable_tick() here: under LVGL that would stop the whole supervisor + // background tick (filesystem, USB, BLE, port work). The port's LVGL pump asks + // displayio_lvgl_auto_refresh() instead, so this flag only decides whether the compositor + // repaints on its own. + self->auto_refresh = auto_refresh; + // A paced display only renders at its frame boundary, which already checks auto_refresh. An + // unpaced one renders from LVGL's refresh timer whenever something is invalidated, so swap + // that timer's callback: pause-only while auto_refresh is off (display.refresh() still + // renders through lv_refr_now()), LVGL's own refresh when it is on. + if (self->lv_display != NULL && !self->lv_paced) { + lv_timer_t *refr_timer = lv_display_get_refr_timer(self->lv_display); + if (refr_timer != NULL) { + lv_timer_set_cb(refr_timer, + auto_refresh ? lv_display_refr_timer : framebufferio_lvgl_paced_refr_cb); + if (auto_refresh) { + // Draw what changed while auto_refresh was off. + lv_timer_resume(refr_timer); + } + } + } +} + +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) { + _update_backlight(self); + // The port's LVGL render task owns the pump. Keeping this free of lv_timer_handler() + // guarantees LVGL only renders on its own tick, a frame boundary, or display.refresh(). +} + +void release_framebufferdisplay(framebufferio_framebufferdisplay_obj_t *self) { + common_hal_framebufferio_framebufferdisplay_set_auto_refresh(self, false); + if (self->framebuffer_protocol->set_frame_callback != NULL) { + self->framebuffer_protocol->set_frame_callback(self->framebuffer, NULL, NULL); + } + // Hold the lock across detaching the tree and deleting the display so the render task can't + // be in the middle of a flush when its buffers go away. + nlr_jump_callback_node_t cleanup; + displayio_lvgl_lock_with_cleanup(&cleanup); + self->lv_paced = false; + displayio_lvgl_set_root_group(NULL); + if (self->lv_display != NULL) { + lv_display_delete(self->lv_display); + self->lv_display = NULL; + } + displayio_lvgl_unlock_with_cleanup(); + framebufferio_lvgl_free_partial_buf(self); + if (self->lv_dirty_row_bitmask != NULL) { + port_free(self->lv_dirty_row_bitmask); + self->lv_dirty_row_bitmask = NULL; + self->lv_dirty_row_bitmask_size = 0; + } + 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) { + gc_collect_ptr(self->framebuffer); + displayio_display_core_collect_ptrs(&self->core); +} + +void framebufferio_framebufferdisplay_reset(framebufferio_framebufferdisplay_obj_t *self) { + const mp_obj_type_t *fb_type = mp_obj_get_type(self->framebuffer); + if (fb_type != NULL && fb_type != &mp_type_NoneType) { + common_hal_framebufferio_framebufferdisplay_set_auto_refresh(self, true); + displayio_display_core_set_root_group(&self->core, &circuitpython_splash); + nlr_jump_callback_node_t cleanup; + displayio_lvgl_lock_with_cleanup(&cleanup); + if (self->lv_display != NULL) { + lv_display_set_default(self->lv_display); + } + displayio_lvgl_set_root_group(&circuitpython_splash); + // Render the terminal now. The REPL starts next, and the display may not get another + // background tick before its first writes; make sure the framebuffer already holds the + // splash rather than whatever the user's code left on screen. + if (self->lv_display != NULL) { + lv_refr_now(self->lv_display); + } + displayio_lvgl_unlock_with_cleanup(); + } else { + release_framebufferdisplay(self); + } +} + +mp_obj_t common_hal_framebufferio_framebufferdisplay_get_root_group(framebufferio_framebufferdisplay_obj_t *self) { + if (self->core.current_group == NULL) { + return mp_const_none; + } + return self->core.current_group; +} + +mp_obj_t common_hal_framebufferio_framebufferdisplay_set_root_group(framebufferio_framebufferdisplay_obj_t *self, displayio_group_t *root_group) { + bool ok = displayio_display_core_set_root_group(&self->core, root_group); + if (!ok) { + mp_raise_ValueError(MP_ERROR_TEXT("Group already used")); + } + nlr_jump_callback_node_t cleanup; + displayio_lvgl_lock_with_cleanup(&cleanup); + lv_display_set_default(self->lv_display); + displayio_lvgl_set_root_group(root_group); + displayio_lvgl_unlock_with_cleanup(); + return mp_const_none; +} diff --git a/shared-module/framebufferio/lvgl/FramebufferDisplay.h b/shared-module/framebufferio/lvgl/FramebufferDisplay.h new file mode 100644 index 00000000000..639b4af317b --- /dev/null +++ b/shared-module/framebufferio/lvgl/FramebufferDisplay.h @@ -0,0 +1,101 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2019 Scott Shawcroft for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2020 Jeff Epler for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "shared-module/framebufferio/__init__.h" +#include "py/obj.h" +#include "py/proto.h" + +#include "shared-bindings/displayio/Group.h" + +#include "lvgl.h" + +#include "shared-module/displayio/display_core.h" + +typedef struct { + mp_obj_base_t base; + displayio_display_core_t core; + mp_obj_t framebuffer; + const struct _framebuffer_p_t *framebuffer_protocol; + mp_buffer_info_t bufinfo; + uint64_t last_refresh_call; + uint16_t native_frames_per_second; + uint16_t native_ms_per_frame; + uint16_t first_pixel_offset; + uint16_t row_stride; + bool auto_refresh; + bool first_manual_refresh; + // The LVGL display renders either directly into the provided framebuffer or into + // an aligned partial buffer that the flush callback copies into it. + lv_display_t *lv_display; + lv_color_format_t lv_color_format; + uint8_t *lv_buf; + size_t lv_buf_size; + uint8_t *lv_dirty_row_bitmask; + size_t lv_dirty_row_bitmask_size; + bool lv_direct; + // The framebuffer reports frame boundaries, so this display renders on those instead of the + // LVGL autorefresh tick. + bool lv_paced; +} 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_collect_ptrs(framebufferio_framebufferdisplay_obj_t *self); + +mp_obj_t common_hal_framebufferio_framebufferdisplay_get_framebuffer(framebufferio_framebufferdisplay_obj_t *self); + +typedef bool (*framebuffer_get_reverse_pixels_in_byte_fun)(mp_obj_t); +typedef bool (*framebuffer_get_reverse_pixels_in_word_fun)(mp_obj_t); +typedef bool (*framebuffer_set_brightness_fun)(mp_obj_t, mp_float_t); +typedef int (*framebuffer_get_bytes_per_cell_fun)(mp_obj_t); +typedef int (*framebuffer_get_color_depth_fun)(mp_obj_t); +typedef int (*framebuffer_get_first_pixel_offset_fun)(mp_obj_t); +typedef bool (*framebuffer_get_grayscale_fun)(mp_obj_t); +typedef int (*framebuffer_get_height_fun)(mp_obj_t); +typedef int (*framebuffer_get_native_frames_per_second_fun)(mp_obj_t); +typedef bool (*framebuffer_get_pixels_in_byte_share_row_fun)(mp_obj_t); +typedef int (*framebuffer_get_row_stride_fun)(mp_obj_t); +typedef int (*framebuffer_get_width_fun)(mp_obj_t); +typedef mp_float_t (*framebuffer_get_brightness_fun)(mp_obj_t); +typedef void (*framebuffer_deinit_fun)(mp_obj_t); +typedef void (*framebuffer_get_bufinfo_fun)(mp_obj_t, mp_buffer_info_t *bufinfo); +typedef void (*framebuffer_swapbuffers_fun)(mp_obj_t, uint8_t *dirty_row_bitmask); +typedef void (*framebuffer_set_frame_callback_fun)(mp_obj_t, framebuffer_frame_callback_t, void *); + +typedef struct _framebuffer_p_t { + MP_PROTOCOL_HEAD // MP_QSTR_protocol_framebuffer + + // Mandatory + framebuffer_get_bufinfo_fun get_bufinfo; + framebuffer_swapbuffers_fun swapbuffers; + framebuffer_deinit_fun deinit; + framebuffer_get_width_fun get_width; + framebuffer_get_height_fun get_height; + + // Optional getters + framebuffer_get_bytes_per_cell_fun get_bytes_per_cell; // default: 2 + framebuffer_get_color_depth_fun get_color_depth; // default: 16 + framebuffer_get_first_pixel_offset_fun get_first_pixel_offset; // default: 0 + framebuffer_get_grayscale_fun get_grayscale; // default: grayscale if depth < 8 + framebuffer_get_native_frames_per_second_fun get_native_frames_per_second; // default: 60 + framebuffer_get_pixels_in_byte_share_row_fun get_pixels_in_byte_share_row; // default: false + framebuffer_get_reverse_pixels_in_byte_fun get_reverse_pixels_in_byte; // default: false + framebuffer_get_reverse_pixels_in_word_fun get_reverse_pixels_in_word; // default: false + framebuffer_get_row_stride_fun get_row_stride; // default: 0 (no extra row padding) + + // Optional -- default is no brightness control + framebuffer_get_brightness_fun get_brightness; + framebuffer_set_brightness_fun set_brightness; + + // Optional -- called at each frame boundary. Pass a NULL callback to clear it. + framebuffer_set_frame_callback_fun set_frame_callback; + +} framebuffer_p_t; diff --git a/shared-module/getpass/__init__.c b/shared-module/getpass/__init__.c index 5263ff637d6..446e1b1d280 100644 --- a/shared-module/getpass/__init__.c +++ b/shared-module/getpass/__init__.c @@ -15,7 +15,7 @@ mp_obj_t shared_module_getpass_getpass(const char *prompt, mp_print_t *print) { if (print == NULL) { mp_hal_stdout_tx_str(prompt); } else { - mp_printf(print, prompt); + mp_print_str(print, prompt); } for (;;) { diff --git a/shared-module/gifio/GifWriter.c b/shared-module/gifio/GifWriter.c index 8747f4a486c..d875a844d9f 100644 --- a/shared-module/gifio/GifWriter.c +++ b/shared-module/gifio/GifWriter.c @@ -18,6 +18,12 @@ #define BLOCK_SIZE (126) // (2^7) - 2 // (DO NOT CHANGE!) +#define GIF_HEADER_SIZE (13 + 128 * 3 + 19) +// Each frame writes a 19 byte header ahead of the block data (8 for the +// graphic control extension, 11 for the image descriptor) and a 3 byte end +// code after it. +#define GIF_FRAME_OVERHEAD (19 + 3) + static void handle_error(gifio_gifwriter_t *self) { if (self->error != 0) { mp_raise_OSError(self->error); @@ -68,9 +74,9 @@ void shared_module_gifio_gifwriter_construct(gifio_gifwriter_t *self, mp_obj_t * self->dither = dither; self->own_file = own_file; - size_t nblocks = (width * height + 125) / 126; - self->size = nblocks * 128 + 4; - self->data = m_malloc(self->size); + size_t nblocks = (width * height + BLOCK_SIZE - 1) / BLOCK_SIZE; + self->size = MAX(GIF_HEADER_SIZE, nblocks * 128 + GIF_FRAME_OVERHEAD); + self->data = m_malloc_without_collect(self->size); self->cur = 0; self->error = 0; @@ -155,6 +161,15 @@ static const uint8_t g_bayer[4][4] = { }; void shared_module_gifio_gifwriter_add_frame(gifio_gifwriter_t *self, const mp_buffer_info_t *bufinfo, int16_t delay) { + int pixel_count = self->width * self->height; + int blocks = (pixel_count + BLOCK_SIZE - 1) / BLOCK_SIZE; + + size_t needed_bytes = (self->colorspace == DISPLAYIO_COLORSPACE_L8) + ? (size_t)pixel_count + : 2u * (size_t)pixel_count; + mp_get_index(&mp_type_memoryview, bufinfo->len, + MP_OBJ_NEW_SMALL_INT(needed_bytes - 1), false); + if (delay) { write_data(self, (uint8_t []) {'!', 0xF9, 0x04, 0x04}, 4); write_word(self, delay); @@ -167,13 +182,9 @@ void shared_module_gifio_gifwriter_add_frame(gifio_gifwriter_t *self, const mp_b write_word(self, self->height); write_data(self, (uint8_t []) {0x00, 0x07}, 2); // 7-bits - int pixel_count = self->width * self->height; - int blocks = (pixel_count + BLOCK_SIZE - 1) / BLOCK_SIZE; - uint8_t *data = self->data + self->cur; if (self->colorspace == DISPLAYIO_COLORSPACE_L8) { - mp_get_index(&mp_type_memoryview, bufinfo->len, MP_OBJ_NEW_SMALL_INT(pixel_count - 1), false); uint8_t *pixels = bufinfo->buf; for (int i = 0; i < blocks; i++) { @@ -187,7 +198,6 @@ void shared_module_gifio_gifwriter_add_frame(gifio_gifwriter_t *self, const mp_b } } } else if (!self->dither) { - mp_get_index(&mp_type_memoryview, bufinfo->len, MP_OBJ_NEW_SMALL_INT(2 * pixel_count - 1), false); uint16_t *pixels = bufinfo->buf; for (int i = 0; i < blocks; i++) { @@ -208,7 +218,6 @@ void shared_module_gifio_gifwriter_add_frame(gifio_gifwriter_t *self, const mp_b } } } else { - mp_get_index(&mp_type_memoryview, bufinfo->len, MP_OBJ_NEW_SMALL_INT(2 * pixel_count - 1), false); uint16_t *pixels = bufinfo->buf; int x = 0, y = 0; diff --git a/shared-module/gifio/OnDiskGif.c b/shared-module/gifio/OnDiskGif.c index 2b95e875c71..e974264f9bb 100644 --- a/shared-module/gifio/OnDiskGif.c +++ b/shared-module/gifio/OnDiskGif.c @@ -12,12 +12,11 @@ #include "py/mperrno.h" #include "py/runtime.h" +#include "py/stream.h" static int32_t GIFReadFile(GIFFILE *pFile, uint8_t *pBuf, int32_t iLen) { - uint32_t iBytesRead; - iBytesRead = iLen; - pyb_file_obj_t *f = pFile->fHandle; + uint32_t iBytesRead = iLen; // Note: If you read a file all the way to the last byte, seek() stops working if ((pFile->iSize - pFile->iPos) < iLen) { iBytesRead = pFile->iSize - pFile->iPos - 1; // <-- ugly work-around @@ -25,21 +24,25 @@ static int32_t GIFReadFile(GIFFILE *pFile, uint8_t *pBuf, int32_t iLen) { if (iBytesRead <= 0) { return 0; } - UINT bytes_read; - if (f_read(&f->fp, pBuf, iBytesRead, &bytes_read) != FR_OK) { - mp_raise_OSError(MP_EIO); + int errcode = 0; + mp_uint_t bytes_read = mp_stream_rw(MP_OBJ_FROM_PTR(pFile->fHandle), pBuf, + iBytesRead, &errcode, MP_STREAM_RW_ONCE); + if (errcode != 0) { + mp_raise_OSError(errcode); } - pFile->iPos = f->fp.fptr; + pFile->iPos += bytes_read; return bytes_read; } /* GIFReadFile() */ static int32_t GIFSeekFile(GIFFILE *pFile, int32_t iPosition) { - pyb_file_obj_t *f = pFile->fHandle; - - f_lseek(&f->fp, iPosition); - pFile->iPos = f->fp.fptr; - return pFile->iPos; + int errcode = 0; + mp_off_t pos = mp_stream_seek(MP_OBJ_FROM_PTR(pFile->fHandle), iPosition, MP_SEEK_SET, &errcode); + if (pos < 0) { + mp_raise_OSError(errcode); + } + pFile->iPos = pos; + return pos; } /* GIFSeekFile() */ static void GIFDraw(GIFDRAW *pDraw) { @@ -127,7 +130,7 @@ static void GIFDraw(GIFDRAW *pDraw) { } } -void common_hal_gifio_ondiskgif_construct(gifio_ondiskgif_t *self, pyb_file_obj_t *file, bool use_palette) { +void common_hal_gifio_ondiskgif_construct(gifio_ondiskgif_t *self, mp_obj_t file, bool use_palette) { self->file = file; if (use_palette == true) { @@ -142,21 +145,32 @@ void common_hal_gifio_ondiskgif_construct(gifio_ondiskgif_t *self, pyb_file_obj_ self->gif.pfnDraw = GIFDraw; self->gif.pfnClose = NULL; self->gif.pfnOpen = NULL; - self->gif.GIFFile.fHandle = self->file; - - f_rewind(&self->file->fp); - self->gif.GIFFile.iSize = (int32_t)f_size(&self->file->fp); - - int result = GIF_init(&self->gif); - if (result != 1) { - switch (self->gif.iError) { - case GIF_TOO_WIDE: - mp_raise_ValueError_varg(MP_ERROR_TEXT("%q must be <= %d"), MP_QSTR_width, MAX_WIDTH); - break; - default: - mp_arg_error_invalid(MP_QSTR_file); - break; - } + self->gif.GIFFile.fHandle = MP_OBJ_TO_PTR(self->file); + + int errcode = 0; + mp_stream_seek(self->file, 0, MP_SEEK_SET, &errcode); + if (errcode != 0) { + mp_raise_OSError(errcode); + } + mp_off_t size = mp_stream_seek(self->file, 0, MP_SEEK_END, &errcode); + if (size < 0) { + mp_raise_OSError(errcode); + } + mp_stream_seek(self->file, 0, MP_SEEK_SET, &errcode); + if (errcode != 0) { + mp_raise_OSError(errcode); + } + self->gif.GIFFile.iSize = (int32_t)size; + + // Measure the canvas first, then hand the decoder a line buffer of that width. + if (GIF_init(&self->gif, NULL, 0) != 1) { + mp_arg_error_invalid(MP_QSTR_file); + } + // One line of 8-bit pixels. It holds no pointers, so the GC doesn't scan it. + int width = self->gif.iCanvasWidth; + unsigned char *line_buf = m_malloc_without_collect(width); + if (GIF_init(&self->gif, line_buf, width) != 1) { + mp_arg_error_invalid(MP_QSTR_file); } int bpp = 16; @@ -182,7 +196,12 @@ void common_hal_gifio_ondiskgif_construct(gifio_ondiskgif_t *self, pyb_file_obj_ } void common_hal_gifio_ondiskgif_deinit(gifio_ondiskgif_t *self) { + if (common_hal_gifio_ondiskgif_deinited(self)) { + return; + } self->file = NULL; + m_del(uint8_t, self->gif.ucLineBuf, self->gif.iCanvasWidth); + self->gif.ucLineBuf = NULL; common_hal_displayio_bitmap_deinit(self->bitmap); self->bitmap = NULL; self->palette = NULL; @@ -233,14 +252,7 @@ uint32_t common_hal_gifio_ondiskgif_next_frame(gifio_ondiskgif_t *self, bool set result = GIF_playFrame(&self->gif, &nextDelay, self); if ((result >= 0) && (setDirty)) { - displayio_area_t dirty_area = { - .x1 = 0, - .y1 = 0, - .x2 = self->bitmap->width, - .y2 = self->bitmap->height, - }; - - displayio_bitmap_set_dirty_area(self->bitmap, &dirty_area); + displayio_bitmap_set_dirty(self->bitmap, 0, 0, self->bitmap->width, self->bitmap->height); } return nextDelay; diff --git a/shared-module/gifio/OnDiskGif.h b/shared-module/gifio/OnDiskGif.h index ee9c40ad33a..808b6baa89f 100644 --- a/shared-module/gifio/OnDiskGif.h +++ b/shared-module/gifio/OnDiskGif.h @@ -15,12 +15,10 @@ #include "shared-module/displayio/Bitmap.h" #include "shared-module/displayio/Palette.h" -#include "extmod/vfs_fat.h" - typedef struct { mp_obj_base_t base; GIFIMAGE gif; - pyb_file_obj_t *file; + mp_obj_t file; displayio_bitmap_t *bitmap; displayio_palette_t *palette; int32_t duration; diff --git a/shared-module/hardwarekey/HardwareKey.c b/shared-module/hardwarekey/HardwareKey.c new file mode 100644 index 00000000000..8ce6a418d00 --- /dev/null +++ b/shared-module/hardwarekey/HardwareKey.c @@ -0,0 +1,27 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#include "shared-module/hardwarekey/HardwareKey.h" + +// These accessors are port-independent. The one port-specific step -- turning a +// hardware key slot into self->key_id -- happens when the port fills in its +// per-slot HardwareKey objects at startup. + +mp_int_t common_hal_hardwarekey_hardwarekey_get_key_slot(hardwarekey_hardwarekey_obj_t *self) { + return self->key_slot; +} + +hardwarekey_purpose_t common_hal_hardwarekey_hardwarekey_get_purpose(hardwarekey_hardwarekey_obj_t *self) { + return self->purpose; +} + +bool common_hal_hardwarekey_hardwarekey_get_exportable(hardwarekey_hardwarekey_obj_t *self) { + return self->exportable; +} + +psa_key_id_t common_hal_hardwarekey_hardwarekey_get_key_id(hardwarekey_hardwarekey_obj_t *self) { + return self->key_id; +} diff --git a/shared-module/hardwarekey/HardwareKey.h b/shared-module/hardwarekey/HardwareKey.h new file mode 100644 index 00000000000..dda12168b2a --- /dev/null +++ b/shared-module/hardwarekey/HardwareKey.h @@ -0,0 +1,59 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include + +#include "py/obj.h" + +#include "psa/crypto.h" + +// What a hardware key slot is provisioned for. UNUSED means no key has been +// burned into the slot (or it is burned for something this module does not +// expose); the slot is present in `board` but not usable. +typedef enum { + HARDWAREKEY_PURPOSE_UNUSED = 0, + HARDWAREKEY_PURPOSE_HMAC, + // A Digital Signature (RSA) key. Unlike HMAC, the key material isn't + // fully in the eFuse block itself -- the slot only holds the AES key + // that decrypts an externally-supplied, already-encrypted RSA private + // key (`ds_params`) inside the DS peripheral. So a DS-purpose slot is + // usable only after + // cryptography.hazmat.primitives.asymmetric.rsa.load_digital_signature_key() + // has turned it into a DigitalSignatureKey. + HARDWAREKEY_PURPOSE_DS, +} hardwarekey_purpose_t; + +// The handle is portable: it holds a PSA key id. How that id gets created -- +// which hardware key store, which slot -- is the one port-specific step, done +// when the port populates its per-slot HardwareKey objects at startup. +typedef struct { + mp_obj_base_t base; + psa_key_id_t key_id; + mp_int_t key_slot; + hardwarekey_purpose_t purpose; + bool exportable; + // Name this key is exposed under in `board` (e.g. MP_QSTR_EFUSE_KEY0), for + // repr(). MP_QSTRnull if the object was not placed in `board`. + qstr name; +} hardwarekey_hardwarekey_obj_t; + +// HardwareKey objects are created by the port at startup, one per hardware key +// slot, and placed in `board`; application code never constructs them. The +// per-port startup code fills in key_id, key_slot, purpose, exportable and name. +// An HMAC key is used by passing the object to hmac.new(); a DS key is used by +// passing the object to +// cryptography.hazmat.primitives.asymmetric.rsa.load_digital_signature_key(), +// which returns a DigitalSignatureKey (see +// shared-module/cryptography/hazmat/primitives/asymmetric/rsa/DigitalSignatureKey.h). + +mp_int_t common_hal_hardwarekey_hardwarekey_get_key_slot(hardwarekey_hardwarekey_obj_t *self); +hardwarekey_purpose_t common_hal_hardwarekey_hardwarekey_get_purpose(hardwarekey_hardwarekey_obj_t *self); +bool common_hal_hardwarekey_hardwarekey_get_exportable(hardwarekey_hardwarekey_obj_t *self); +// The PSA key id, for hmac.new(). 0 if the slot is unused. +psa_key_id_t common_hal_hardwarekey_hardwarekey_get_key_id(hardwarekey_hardwarekey_obj_t *self); diff --git a/shared-module/hashlib/Hash.c b/shared-module/hashlib/Hash.c index a454966d993..4b46198ac5d 100644 --- a/shared-module/hashlib/Hash.c +++ b/shared-module/hashlib/Hash.c @@ -7,32 +7,23 @@ #include "shared-bindings/hashlib/Hash.h" #include "shared-module/hashlib/__init__.h" -#include "mbedtls/ssl.h" +#include "psa/crypto.h" void common_hal_hashlib_hash_update(hashlib_hash_obj_t *self, const uint8_t *data, size_t datalen) { - if (self->hash_type == MBEDTLS_SSL_HASH_SHA1) { - mbedtls_sha1_update_ret(&self->sha1, data, datalen); - return; - } + psa_hash_update(&self->hash_op, data, datalen); } void common_hal_hashlib_hash_digest(hashlib_hash_obj_t *self, uint8_t *data, size_t datalen) { if (datalen < common_hal_hashlib_hash_get_digest_size(self)) { return; } - if (self->hash_type == MBEDTLS_SSL_HASH_SHA1) { - // We copy the sha1 state so we can continue to update if needed or get - // the digest a second time. - mbedtls_sha1_context copy; - mbedtls_sha1_clone(©, &self->sha1); - mbedtls_sha1_finish_ret(&self->sha1, data); - mbedtls_sha1_clone(&self->sha1, ©); - } + // Clone the operation so we can continue to update or get digest again. + psa_hash_operation_t clone = PSA_HASH_OPERATION_INIT; + psa_hash_clone(&self->hash_op, &clone); + size_t hash_len; + psa_hash_finish(&clone, data, datalen, &hash_len); } size_t common_hal_hashlib_hash_get_digest_size(hashlib_hash_obj_t *self) { - if (self->hash_type == MBEDTLS_SSL_HASH_SHA1) { - return 20; - } - return 0; + return PSA_HASH_LENGTH(self->hash_alg); } diff --git a/shared-module/hashlib/Hash.h b/shared-module/hashlib/Hash.h index ccc82037cb7..961335eea7a 100644 --- a/shared-module/hashlib/Hash.h +++ b/shared-module/hashlib/Hash.h @@ -6,13 +6,10 @@ #pragma once -#include "mbedtls/sha1.h" +#include "psa/crypto.h" typedef struct { mp_obj_base_t base; - union { - mbedtls_sha1_context sha1; - }; - // Of MBEDTLS_SSL_HASH_* - uint8_t hash_type; + psa_hash_operation_t hash_op; + psa_algorithm_t hash_alg; } hashlib_hash_obj_t; diff --git a/shared-module/hashlib/__init__.c b/shared-module/hashlib/__init__.c index be3a9f18959..11d5395bf91 100644 --- a/shared-module/hashlib/__init__.c +++ b/shared-module/hashlib/__init__.c @@ -7,15 +7,24 @@ #include "shared-bindings/hashlib/__init__.h" #include "shared-module/hashlib/__init__.h" -#include "mbedtls/ssl.h" - +#include "psa/crypto.h" bool common_hal_hashlib_new(hashlib_hash_obj_t *self, const char *algorithm) { - if (strcmp(algorithm, "sha1") == 0) { - self->hash_type = MBEDTLS_SSL_HASH_SHA1; - mbedtls_sha1_init(&self->sha1); - mbedtls_sha1_starts_ret(&self->sha1); - return true; + if (strcmp(algorithm, "md5") == 0) { + self->hash_alg = PSA_ALG_MD5; + } else if (strcmp(algorithm, "sha1") == 0) { + self->hash_alg = PSA_ALG_SHA_1; + } else if (strcmp(algorithm, "sha256") == 0) { + self->hash_alg = PSA_ALG_SHA_256; + } else { + return false; + } + // PSA has to be initialized before any of it is used. OK to psa_crypto_init() + // multiple times. On espressif, ESP-IDF has already done this during its own system + // init and this call is a no-op. + if (psa_crypto_init() != PSA_SUCCESS) { + return false; } - return false; + self->hash_op = psa_hash_operation_init(); + return psa_hash_setup(&self->hash_op, self->hash_alg) == PSA_SUCCESS; } diff --git a/shared-module/hashlib/__init__.h b/shared-module/hashlib/__init__.h index f72882a1c03..2088d352f20 100644 --- a/shared-module/hashlib/__init__.h +++ b/shared-module/hashlib/__init__.h @@ -6,11 +6,3 @@ // SPDX-License-Identifier: MIT #pragma once - -#include "mbedtls/version.h" - -#if MBEDTLS_VERSION_NUMBER < 0x02070000 || MBEDTLS_VERSION_NUMBER >= 0x03000000 -#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 diff --git a/shared-module/hmac/HMAC.c b/shared-module/hmac/HMAC.c new file mode 100644 index 00000000000..20b89e0a16c --- /dev/null +++ b/shared-module/hmac/HMAC.c @@ -0,0 +1,125 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#include + +#include "py/runtime.h" + +#include "shared-bindings/hmac/HMAC.h" +#include "shared-module/hmac/__init__.h" + +#include "psa/crypto.h" + +#define HMAC_ALG(self) (PSA_ALG_HMAC((self)->hash_alg)) + +// On failure, resets mac_op (per the PSA multipart contract: an operation +// that errors out must be aborted before it can be discarded) and raises. +static void check_psa(hmac_hmac_obj_t *self, psa_status_t status) { + if (status != PSA_SUCCESS) { + psa_mac_abort(&self->mac_op); + mp_raise_RuntimeError(NULL); + } +} + +void common_hal_hmac_new(hmac_hmac_obj_t *self, const uint8_t *key, size_t key_len, + psa_key_id_t borrowed_key_id, psa_algorithm_t hash_alg) { + self->hash_alg = hash_alg; + self->finished = false; + self->digest_len = 0; + self->mac_op = psa_mac_operation_init(); + self->buffered = (borrowed_key_id != 0); + if (self->buffered) { + vstr_init(&self->buf, 0); + } + + if (psa_crypto_init() != PSA_SUCCESS) { + mp_raise_RuntimeError(NULL); + } + + if (borrowed_key_id != 0) { + self->key_id = borrowed_key_id; + self->owns_key = false; + } else { + psa_key_attributes_t attr = PSA_KEY_ATTRIBUTES_INIT; + psa_set_key_type(&attr, PSA_KEY_TYPE_HMAC); + psa_set_key_bits(&attr, key_len * 8); + psa_set_key_algorithm(&attr, HMAC_ALG(self)); + psa_set_key_usage_flags(&attr, PSA_KEY_USAGE_SIGN_MESSAGE); + psa_set_key_lifetime(&attr, PSA_KEY_LIFETIME_VOLATILE); + if (psa_import_key(&attr, key, key_len, &self->key_id) != PSA_SUCCESS) { + mp_raise_RuntimeError(NULL); + } + self->owns_key = true; + } + + psa_status_t status = psa_mac_sign_setup(&self->mac_op, self->key_id, HMAC_ALG(self)); + if (status != PSA_SUCCESS) { + if (self->owns_key) { + psa_destroy_key(self->key_id); + self->owns_key = false; + } + if (status == PSA_ERROR_NOT_PERMITTED) { + // A hardware-backed key can be locked to one digest algorithm -- + // a common restriction for this kind of peripheral. + mp_raise_ValueError(MP_ERROR_TEXT("key does not support this digest")); + } + mp_raise_RuntimeError(NULL); + } +} + +void common_hal_hmac_update(hmac_hmac_obj_t *self, const uint8_t *data, size_t data_len) { + if (self->finished) { + mp_raise_RuntimeError(NULL); + } + if (self->buffered) { + vstr_add_strn(&self->buf, (const char *)data, data_len); + return; + } + check_psa(self, psa_mac_update(&self->mac_op, data, data_len)); +} + +void common_hal_hmac_digest(hmac_hmac_obj_t *self, uint8_t *out, size_t out_len) { + if (!self->finished) { + if (self->buffered) { + if (self->buf.len == 0) { + // Some hardware-backed keys' PSA drivers reject a + // zero-length psa_mac_update() outright (and skipping the + // call entirely would leave the result at all-zero bytes + // from setup -- a wrong answer, not an error), so an empty + // message can't be computed through this path. + psa_mac_abort(&self->mac_op); + mp_raise_ValueError(MP_ERROR_TEXT("HMAC of an empty message is not supported with a hardware key")); + } + check_psa(self, psa_mac_update(&self->mac_op, (const uint8_t *)self->buf.buf, self->buf.len)); + } + psa_status_t status = psa_mac_sign_finish(&self->mac_op, self->digest, sizeof(self->digest), + &self->digest_len); + // The operation is spent either way -- successful finish or not, it + // can't be resumed, so the owned key's job is done too. + if (self->owns_key) { + psa_destroy_key(self->key_id); + self->owns_key = false; + } + check_psa(self, status); + self->finished = true; + } + memcpy(out, self->digest, out_len); +} + +size_t common_hal_hmac_get_digest_size(hmac_hmac_obj_t *self) { + return PSA_HASH_LENGTH(self->hash_alg); +} + +size_t common_hal_hmac_get_block_size(hmac_hmac_obj_t *self) { + return PSA_HASH_BLOCK_LENGTH(self->hash_alg); +} + +const char *common_hal_hmac_get_name(hmac_hmac_obj_t *self) { + if (self->hash_alg == PSA_ALG_SHA_1) { + return "hmac-sha1"; + } + return "hmac-sha256"; +} diff --git a/shared-module/hmac/__init__.c b/shared-module/hmac/__init__.c new file mode 100644 index 00000000000..7d3670dfcc7 --- /dev/null +++ b/shared-module/hmac/__init__.c @@ -0,0 +1,42 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#include + +#include "mbedtls/constant_time.h" +#include "shared-module/hmac/__init__.h" + +bool hmac_hash_alg_from_name(const char *name, psa_algorithm_t *hash_alg) { + if (strcmp(name, "sha256") == 0) { + *hash_alg = PSA_ALG_SHA_256; + } else if (strcmp(name, "sha1") == 0) { + *hash_alg = PSA_ALG_SHA_1; + } else { + return false; + } + return true; +} + +bool common_hal_hmac_compare_digest(const uint8_t *a, size_t a_len, const uint8_t *b, size_t b_len) { + // Same shape as CPython's _tscmp: the running time depends only on len(a), + // never on where (or whether) the two inputs first differ. The byte + // comparison itself is mbedtls_ct_memcmp(), which is hardened (volatile + // accesses, no early-exit branch) against being optimized into a + // variable-time comparison. + const uint8_t *right = b; + int mismatch = 0; + + if (a_len != b_len) { + // Compare a against itself so the call still does a_len bytes of work, + // then force a mismatch. + right = a; + mismatch = 1; + } + + mismatch |= mbedtls_ct_memcmp(a, right, a_len); + + return mismatch == 0; +} diff --git a/shared-module/hmac/__init__.h b/shared-module/hmac/__init__.h new file mode 100644 index 00000000000..677ed0aab81 --- /dev/null +++ b/shared-module/hmac/__init__.h @@ -0,0 +1,55 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Mabey +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include +#include + +#include "py/misc.h" +#include "py/obj.h" + +#include "psa/crypto.h" + +typedef struct { + mp_obj_base_t base; + // The digest algorithm the HMAC is built on, e.g. PSA_ALG_SHA_256. + psa_algorithm_t hash_alg; + // The PSA multipart MAC operation. update() normally streams straight + // into this (see `buffered` below for the exception); PSA has no + // psa_mac_clone(), so unlike shared-module/hashlib's Hash this can't be + // rewound -- digest() finishes it exactly once and caches the result. + psa_mac_operation_t mac_op; + // The PSA key used by mac_op. For a bytes key, imported at construction + // time and destroyed once mac_op is finished (owns_key true). For a key + // borrowed from a hardwarekey.HardwareKey, that object owns the key and + // owns_key is false. + psa_key_id_t key_id; + bool owns_key; + // True for a borrowed hardware key whose PSA driver doesn't implement + // real multipart MAC support: some hardware-backed HMAC peripherals only + // expose a one-shot compute primitive, so a PSA driver built on one may + // independently compute the HMAC of just each update() call's bytes and + // discard prior state -- silently giving the wrong answer if update() is + // called more than once. When true, update() accumulates into `buf` + // instead and digest() feeds it to mac_op in one call. Bytes keys stream + // normally -- this only affects the (typically short) hardware-key path. + bool buffered; + vstr_t buf; + // Set once digest()/hexdigest() has finished mac_op. update() raises + // after this; further digest() calls just return the cached bytes. + bool finished; + uint8_t digest[PSA_HASH_MAX_SIZE]; + size_t digest_len; +} hmac_hmac_obj_t; + +// Maps a CPython digest name ("sha1", "sha256") to a PSA hash algorithm. +// Returns false for an unsupported name. +bool hmac_hash_alg_from_name(const char *name, psa_algorithm_t *hash_alg); + +// Constant-time equality, matching hmac.compare_digest() / CPython's _tscmp. +bool common_hal_hmac_compare_digest(const uint8_t *a, size_t a_len, const uint8_t *b, size_t b_len); diff --git a/shared-module/i2cdisplaybus/I2CDisplayBus.c b/shared-module/i2cdisplaybus/I2CDisplayBus.c index 47b5865d158..1e8b029d858 100644 --- a/shared-module/i2cdisplaybus/I2CDisplayBus.c +++ b/shared-module/i2cdisplaybus/I2CDisplayBus.c @@ -27,7 +27,6 @@ void common_hal_i2cdisplaybus_i2cdisplaybus_construct(i2cdisplaybus_i2cdisplaybu 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); - common_hal_never_reset_pin(reset); common_hal_i2cdisplaybus_i2cdisplaybus_reset(self); } @@ -40,7 +39,6 @@ void common_hal_i2cdisplaybus_i2cdisplaybus_construct(i2cdisplaybus_i2cdisplaybu // Write to the device and return 0 on success or an appropriate error code from mperrno.h self->bus = i2c; - common_hal_busio_i2c_never_reset(self->bus); self->address = device_address; } @@ -49,8 +47,6 @@ void common_hal_i2cdisplaybus_i2cdisplaybus_deinit(i2cdisplaybus_i2cdisplaybus_o if (self->bus == &self->inline_bus) { common_hal_busio_i2c_deinit(self->bus); } - // TODO figure out how to undo never_reset. maybe only mark never_reset when - // we subsume objects off the mp heap. self->bus = NULL; diff --git a/shared-module/i2cioexpander/IOExpander.c b/shared-module/i2cioexpander/IOExpander.c new file mode 100644 index 00000000000..24d81e18eea --- /dev/null +++ b/shared-module/i2cioexpander/IOExpander.c @@ -0,0 +1,203 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/i2cioexpander/IOExpander.h" +#include "shared-bindings/i2cioexpander/IOPin.h" + +#include + +#include "py/gc.h" +#include "py/runtime.h" +#include "shared-bindings/busio/I2C.h" +#include "supervisor/port.h" + +static void mark_deinit(i2cioexpander_ioexpander_obj_t *self) { + self->i2c = NULL; + self->pins = NULL; +} + +void common_hal_i2cioexpander_ioexpander_construct( + i2cioexpander_ioexpander_obj_t *self, + mp_obj_t i2c, + uint8_t address, + uint8_t num_pins, + uint16_t set_value_reg, + uint16_t get_value_reg, + uint16_t set_direction_reg) { + + mark_deinit(self); + + self->address = address; + self->num_pins = num_pins; + self->output_value = 0; + self->output_mask = 0; + + // Parse optional register addresses + self->has_set_value = (set_value_reg != NO_REGISTER); + if (self->has_set_value) { + self->set_value_reg = set_value_reg; + } + + self->has_get_value = (get_value_reg != NO_REGISTER); + if (self->has_get_value) { + self->get_value_reg = get_value_reg; + } + + self->has_set_direction = (set_direction_reg != NO_REGISTER); + if (self->has_set_direction) { + self->set_direction_reg = set_direction_reg; + } + + bool allocate_in_port_heap = !gc_alloc_possible() || !gc_ptr_on_heap(self); + + // Allocate tuple with space for pin objects in items[] + size_t tuple_size = offsetof(mp_obj_tuple_t, items) + sizeof(mp_obj_t) * num_pins; + mp_obj_tuple_t *pins_tuple = allocate_in_port_heap ? port_malloc(tuple_size, false) : m_malloc(tuple_size); + pins_tuple->base.type = &mp_type_tuple; + pins_tuple->len = num_pins; + + // Create IOPin objects for each pin + size_t pin_size = sizeof(i2cioexpander_iopin_obj_t); + for (uint8_t i = 0; i < num_pins; i++) { + i2cioexpander_iopin_obj_t *pin = allocate_in_port_heap ? port_malloc(pin_size, false) : m_malloc(pin_size); + pin->base.type = &i2cioexpander_iopin_type; + i2cioexpander_iopin_construct(pin, self, i); + pins_tuple->items[i] = MP_OBJ_FROM_PTR(pin); + } + + self->pins = pins_tuple; + self->i2c = (busio_i2c_obj_t *)i2c; +} + +void common_hal_i2cioexpander_ioexpander_deinit(i2cioexpander_ioexpander_obj_t *self) { + if (common_hal_i2cioexpander_ioexpander_deinited(self)) { + return; + } + if (gc_alloc_possible() && !gc_ptr_on_heap(self)) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Cannot deinitialize board IOExpander")); + } + // The IOPins and their tuple are on the GC heap, and user code may still + // hold them, so leave them for the GC instead of freeing them. + mark_deinit(self); +} + +bool common_hal_i2cioexpander_ioexpander_deinited(i2cioexpander_ioexpander_obj_t *self) { + return self->i2c == NULL; +} + +mp_negative_errno_t common_hal_i2cioexpander_ioexpander_get_input_value(i2cioexpander_ioexpander_obj_t *self, size_t *value) { + uint8_t buffer[2]; + uint8_t num_bytes = (self->num_pins > 8) ? 2 : 1; + + while (!common_hal_busio_i2c_try_lock(self->i2c)) { + RUN_BACKGROUND_TASKS; + } + + mp_negative_errno_t result; + if (self->has_get_value) { + // Send register address then read + result = common_hal_busio_i2c_write_read( + self->i2c, self->address, &self->get_value_reg, 1, buffer, num_bytes); + } else { + // Read directly without register address + result = common_hal_busio_i2c_read(self->i2c, self->address, buffer, num_bytes); + } + common_hal_busio_i2c_unlock(self->i2c); + + if (result != 0) { + return result; + } + + if (num_bytes == 2) { + *value = buffer[0] | (buffer[1] << 8); + } else { + *value = buffer[0]; + } + return 0; +} + +void common_hal_i2cioexpander_ioexpander_get_output_value(i2cioexpander_ioexpander_obj_t *self, size_t *value) { + *value = self->output_value; +} + +mp_negative_errno_t common_hal_i2cioexpander_ioexpander_set_output_value(i2cioexpander_ioexpander_obj_t *self, size_t value) { + uint8_t buffer[5]; + uint8_t num_bytes = 0; + + // Add register address if provided + if (self->has_set_value) { + buffer[num_bytes++] = self->set_value_reg; + } + + size_t current_value = self->output_value; + if (current_value == value) { + return 0; + } + size_t diff = current_value ^ value; + + // Add value byte(s) but only if a high bit is changed + buffer[num_bytes++] = value & 0xFF; + if (self->num_pins > 8 && (diff >> 8) != 0) { + buffer[num_bytes++] = (value >> 8) & 0xFF; + } + if (self->num_pins > 16 && (diff >> 16) != 0) { + buffer[num_bytes++] = (value >> 16) & 0xFF; + } + if (self->num_pins > 24 && (diff >> 24) != 0) { + buffer[num_bytes++] = (value >> 24) & 0xFF; + } + + if (!common_hal_busio_i2c_try_lock(self->i2c)) { + return -MP_EBUSY; + } + + mp_negative_errno_t result = common_hal_busio_i2c_write(self->i2c, self->address, buffer, num_bytes); + common_hal_busio_i2c_unlock(self->i2c); + if (result == 0) { + self->output_value = value; + } + return result; +} + +void common_hal_i2cioexpander_ioexpander_get_output_mask(i2cioexpander_ioexpander_obj_t *self, size_t *mask) { + *mask = self->output_mask; +} + +mp_negative_errno_t common_hal_i2cioexpander_ioexpander_set_output_mask(i2cioexpander_ioexpander_obj_t *self, size_t mask) { + self->output_mask = mask; + + // Only write to device if direction register is provided + if (!self->has_set_direction) { + return 0; + } + + uint8_t buffer[3]; + uint8_t num_bytes = 0; + + // Add register address + buffer[num_bytes++] = self->set_direction_reg; + + // Invert the mask so 0 indicates output. We taken 1 for output to match output enable. + size_t inverted_mask = ~mask; + + // Add mask byte(s) + buffer[num_bytes++] = inverted_mask & 0xFF; + if (self->num_pins > 8) { + buffer[num_bytes++] = (inverted_mask >> 8) & 0xFF; + } + + if (!common_hal_busio_i2c_try_lock(self->i2c)) { + return -MP_EBUSY; + } + + mp_negative_errno_t result = common_hal_busio_i2c_write(self->i2c, self->address, buffer, num_bytes); + common_hal_busio_i2c_unlock(self->i2c); + return result; +} + +mp_obj_t common_hal_i2cioexpander_ioexpander_get_pins(i2cioexpander_ioexpander_obj_t *self) { + return MP_OBJ_FROM_PTR(self->pins); +} diff --git a/shared-module/i2cioexpander/IOExpander.h b/shared-module/i2cioexpander/IOExpander.h new file mode 100644 index 00000000000..e225bfc75c7 --- /dev/null +++ b/shared-module/i2cioexpander/IOExpander.h @@ -0,0 +1,41 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include + +#include "py/obj.h" +#include "py/objtuple.h" +#include "shared-bindings/busio/I2C.h" + +#define NO_REGISTER (0x100) + +typedef struct { + mp_obj_base_t base; + busio_i2c_obj_t *i2c; + uint8_t address; + uint8_t num_pins; + uint8_t set_value_reg; + uint8_t get_value_reg; + uint8_t set_direction_reg; + size_t output_value; + size_t output_mask; + bool has_set_value; + bool has_get_value; + bool has_set_direction; + mp_obj_tuple_t *pins; +} i2cioexpander_ioexpander_obj_t; + +void common_hal_i2cioexpander_ioexpander_construct( + i2cioexpander_ioexpander_obj_t *self, + mp_obj_t i2c, + uint8_t address, + uint8_t num_pins, + uint16_t set_value_reg, + uint16_t get_value_reg, + uint16_t set_direction_reg); diff --git a/shared-module/i2cioexpander/IOPin.c b/shared-module/i2cioexpander/IOPin.c new file mode 100644 index 00000000000..db20c083267 --- /dev/null +++ b/shared-module/i2cioexpander/IOPin.c @@ -0,0 +1,151 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/i2cioexpander/IOPin.h" +#include "shared-bindings/i2cioexpander/IOExpander.h" + +#include "py/runtime.h" + +mp_negative_errno_t i2cioexpander_iopin_construct( + i2cioexpander_iopin_obj_t *self, + i2cioexpander_ioexpander_obj_t *expander, + uint8_t pin_number) { + + if (pin_number >= expander->num_pins) { + return MP_EINVAL; // Reusing this for "invalid pin" + } + + self->expander = expander; + self->pin_number = pin_number; + self->direction = DIRECTION_INPUT; + + return 0; +} + +void common_hal_i2cioexpander_iopin_deinit(i2cioexpander_iopin_obj_t *self) { + if (common_hal_i2cioexpander_iopin_deinited(self)) { + return; + } + // Switch to input on deinit. + common_hal_i2cioexpander_iopin_switch_to_input(self, PULL_NONE); +} + +bool common_hal_i2cioexpander_iopin_deinited(i2cioexpander_iopin_obj_t *self) { + return self->expander == NULL || common_hal_i2cioexpander_ioexpander_deinited(self->expander); +} + +digitalinout_result_t common_hal_i2cioexpander_iopin_switch_to_input( + i2cioexpander_iopin_obj_t *self, + digitalio_pull_t pull) { + + if (pull != PULL_NONE) { + // IO expanders typically don't support pull resistors + #if CIRCUITPY_DIGITALIO_HAVE_INVALID_PULL + return DIGITALINOUT_INVALID_PULL; + #endif + } + + self->direction = DIRECTION_INPUT; + + // Clear the output mask bit for this pin + size_t new_mask = self->expander->output_mask & ~(1 << self->pin_number); + common_hal_i2cioexpander_ioexpander_set_output_mask(self->expander, new_mask); + + return DIGITALINOUT_OK; +} + +digitalinout_result_t common_hal_i2cioexpander_iopin_switch_to_output( + i2cioexpander_iopin_obj_t *self, + bool value, + digitalio_drive_mode_t drive_mode) { + + if (drive_mode != DRIVE_MODE_PUSH_PULL) { + // IO expanders typically only support push-pull + #if CIRCUITPY_DIGITALIO_HAVE_INVALID_DRIVE_MODE + return DIGITALINOUT_INVALID_DRIVE_MODE; + #endif + } + + self->direction = DIRECTION_OUTPUT; + + // Set the value first + size_t new_value = self->expander->output_value; + if (value) { + new_value |= (1 << self->pin_number); + } else { + new_value &= ~(1 << self->pin_number); + } + common_hal_i2cioexpander_ioexpander_set_output_value(self->expander, new_value); + + // Set the output mask bit for this pin + size_t new_mask = self->expander->output_mask | (1 << self->pin_number); + common_hal_i2cioexpander_ioexpander_set_output_mask(self->expander, new_mask); + + return DIGITALINOUT_OK; +} + +digitalio_direction_t common_hal_i2cioexpander_iopin_get_direction(i2cioexpander_iopin_obj_t *self) { + return self->direction; +} + +mp_negative_errno_t common_hal_i2cioexpander_iopin_set_value(i2cioexpander_iopin_obj_t *self, bool value) { + size_t current_value; + common_hal_i2cioexpander_ioexpander_get_output_value(self->expander, ¤t_value); + size_t new_value; + if (value) { + new_value = current_value | (1 << self->pin_number); + } else { + new_value = current_value & ~(1 << self->pin_number); + } + if (new_value != current_value) { + return common_hal_i2cioexpander_ioexpander_set_output_value(self->expander, new_value); + } + return 0; +} + +mp_negative_errno_t common_hal_i2cioexpander_iopin_get_value(i2cioexpander_iopin_obj_t *self, bool *value) { + size_t full_value; + mp_negative_errno_t result = common_hal_i2cioexpander_ioexpander_get_input_value(self->expander, &full_value); + if (result != 0) { + return result; + } + *value = (full_value & (1 << self->pin_number)) != 0; + return 0; +} + +digitalinout_result_t common_hal_i2cioexpander_iopin_set_drive_mode( + i2cioexpander_iopin_obj_t *self, + digitalio_drive_mode_t drive_mode) { + + if (drive_mode != DRIVE_MODE_PUSH_PULL) { + #if CIRCUITPY_DIGITALIO_HAVE_INVALID_DRIVE_MODE + return DIGITALINOUT_INVALID_DRIVE_MODE; + #endif + } + + return DIGITALINOUT_OK; +} + +digitalio_drive_mode_t common_hal_i2cioexpander_iopin_get_drive_mode(i2cioexpander_iopin_obj_t *self) { + return DRIVE_MODE_PUSH_PULL; +} + +digitalinout_result_t common_hal_i2cioexpander_iopin_set_pull( + i2cioexpander_iopin_obj_t *self, + digitalio_pull_t pull) { + + if (pull != PULL_NONE) { + #if CIRCUITPY_DIGITALIO_HAVE_INVALID_PULL + return DIGITALINOUT_INVALID_PULL; + #endif + } + + return DIGITALINOUT_OK; +} + +digitalio_pull_t common_hal_i2cioexpander_iopin_get_pull(i2cioexpander_iopin_obj_t *self) { + return PULL_NONE; +} diff --git a/shared-module/i2cioexpander/IOPin.h b/shared-module/i2cioexpander/IOPin.h new file mode 100644 index 00000000000..0c4da8a0213 --- /dev/null +++ b/shared-module/i2cioexpander/IOPin.h @@ -0,0 +1,26 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include + +#include "py/obj.h" +#include "shared-bindings/digitalio/Direction.h" +#include "shared-bindings/digitalio/DriveMode.h" +#include "shared-bindings/digitalio/Pull.h" +#include "shared-bindings/digitalio/DigitalInOut.h" +#include "shared-module/i2cioexpander/IOExpander.h" + +typedef struct { + mp_obj_base_t base; + i2cioexpander_ioexpander_obj_t *expander; + uint8_t pin_number; + digitalio_direction_t direction; +} i2cioexpander_iopin_obj_t; + +extern const mp_obj_type_t i2cioexpander_iopin_type; diff --git a/shared-module/i2cioexpander/__init__.c b/shared-module/i2cioexpander/__init__.c new file mode 100644 index 00000000000..43e652db897 --- /dev/null +++ b/shared-module/i2cioexpander/__init__.c @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// Nothing now. diff --git a/shared-module/is31fl3741/FrameBuffer.c b/shared-module/is31fl3741/FrameBuffer.c index 7f4660d857c..f54c9974404 100644 --- a/shared-module/is31fl3741/FrameBuffer.c +++ b/shared-module/is31fl3741/FrameBuffer.c @@ -27,16 +27,11 @@ void common_hal_is31fl3741_framebuffer_construct(is31fl3741_framebuffer_obj_t *s self->is31fl3741 = is31; - common_hal_busio_i2c_never_reset(self->is31fl3741->i2c); - mp_obj_t *items; size_t len; + // The binding has checked the mapping's length. mp_obj_tuple_get(mapping, &len, &items); - if (len != (size_t)(self->scale_width * self->scale_height * 3)) { - mp_raise_ValueError(MP_ERROR_TEXT("LED mappings must match display size")); - } - self->mapping = port_malloc(sizeof(uint16_t) * len, false); if (self->mapping == NULL) { m_malloc_fail(sizeof(uint16_t) * len); @@ -97,8 +92,6 @@ void common_hal_is31fl3741_framebuffer_reconstruct(is31fl3741_framebuffer_obj_t } void common_hal_is31fl3741_framebuffer_deinit(is31fl3741_framebuffer_obj_t *self) { - common_hal_is31fl3741_end_transaction(self->is31fl3741); // in case we still had a lock - common_hal_is31fl3741_IS31FL3741_deinit(self->is31fl3741); if (self->mapping != NULL) { @@ -126,7 +119,7 @@ bool common_hal_is31fl3741_framebuffer_get_paused(is31fl3741_framebuffer_obj_t * } void common_hal_is31fl3741_framebuffer_refresh(is31fl3741_framebuffer_obj_t *self, uint8_t *dirtyrows) { - if (!self->paused) { + if (!self->paused && !common_hal_is31fl3741_IS31FL3741_deinited(self->is31fl3741)) { common_hal_is31fl3741_begin_transaction(self->is31fl3741); uint8_t dirty_row_flags = 0xFF; diff --git a/shared-module/is31fl3741/IS31FL3741.c b/shared-module/is31fl3741/IS31FL3741.c index 35ee08107b9..15d72e9544c 100644 --- a/shared-module/is31fl3741/IS31FL3741.c +++ b/shared-module/is31fl3741/IS31FL3741.c @@ -16,26 +16,38 @@ #include "shared-bindings/util.h" #include "shared-bindings/busio/I2C.h" +void common_hal_is31fl3741_IS31FL3741_mark_deinit(is31fl3741_IS31FL3741_obj_t *self) { + self->i2c = NULL; +} + void common_hal_is31fl3741_IS31FL3741_construct(is31fl3741_IS31FL3741_obj_t *self, busio_i2c_obj_t *i2c, uint8_t addr) { + common_hal_is31fl3741_IS31FL3741_mark_deinit(self); + // Probe the bus to see if a device acknowledges the given address. if (!common_hal_busio_i2c_probe(i2c, addr)) { - self->base.type = &mp_type_NoneType; mp_raise_ValueError_varg(MP_ERROR_TEXT("Unable to find I2C Display at %x"), addr); } - self->i2c = i2c; self->device_address = addr; + self->i2c = i2c; +} + +bool common_hal_is31fl3741_IS31FL3741_deinited(is31fl3741_IS31FL3741_obj_t *self) { + return self->i2c == NULL; } void common_hal_is31fl3741_IS31FL3741_deinit(is31fl3741_IS31FL3741_obj_t *self) { + if (common_hal_is31fl3741_IS31FL3741_deinited(self)) { + return; + } + common_hal_is31fl3741_end_transaction(self); // in case we still had a lock if (self->i2c == &self->inline_i2c) { common_hal_busio_i2c_deinit(self->i2c); - self->i2c = NULL; } - self->base.type = NULL; + common_hal_is31fl3741_IS31FL3741_mark_deinit(self); } void common_hal_is31fl3741_write(is31fl3741_IS31FL3741_obj_t *is31, const mp_obj_t *mapping, const uint8_t *pixels, size_t numBytes) { diff --git a/shared-module/jpegio/JpegDecoder.c b/shared-module/jpegio/JpegDecoder.c index 484ba8e7ccd..42590fb0b51 100644 --- a/shared-module/jpegio/JpegDecoder.c +++ b/shared-module/jpegio/JpegDecoder.c @@ -5,6 +5,8 @@ // SPDX-License-Identifier: MIT #include "py/runtime.h" +#include "py/objtype.h" +#include "py/stream.h" #include "shared-bindings/jpegio/JpegDecoder.h" #include "shared-bindings/bitmaptools/__init__.h" @@ -46,14 +48,24 @@ static void check_jresult(JRESULT j) { msg = MP_ERROR_TEXT("Right format but not supported"); break; case JDR_FMT3: - msg = MP_ERROR_TEXT("Not supported JPEG standard"); + msg = MP_ERROR_TEXT("Unsupported JPEG (may be progressive)"); break; } mp_raise_RuntimeError(msg); } -void common_hal_jpegio_jpegdecoder_construct(jpegio_jpegdecoder_obj_t *self) { +void common_hal_jpegio_jpegdecoder_construct(jpegio_jpegdecoder_obj_t *self, bool software_ok) { self->data_obj = MP_OBJ_NULL; + self->software_ok = software_ok; + #if CIRCUITPY_JPEGIO_HW + jpegio_jpegdecoder_hw_init(self); + #endif +} + +void common_hal_jpegio_jpegdecoder_deinit(jpegio_jpegdecoder_obj_t *self) { + #if CIRCUITPY_JPEGIO_HW + jpegio_jpegdecoder_hw_deinit(self); + #endif } void common_hal_jpegio_jpegdecoder_close(jpegio_jpegdecoder_obj_t *self) { @@ -89,7 +101,7 @@ static size_t file_input(JDEC *jd, uint8_t *dest, size_t len) { read = file_input(jd, buf, to_discard); total += read; } while (read != 0 && total != len); - return len; + return total; } int errcode = 0; @@ -102,6 +114,15 @@ static size_t file_input(JDEC *jd, uint8_t *dest, size_t len) { mp_obj_t common_hal_jpegio_jpegdecoder_set_source_file(jpegio_jpegdecoder_obj_t *self, mp_obj_t file_obj) { self->data_obj = file_obj; + #if CIRCUITPY_JPEGIO_FAST + self->stream_start_position = -1; + // Seeking a Python io.IOBase subclass calls its ioctl method, which may not + // exist, so only native streams are read whole. + if (mp_obj_is_native_type(mp_obj_get_type(file_obj)) && mp_get_stream(file_obj)->ioctl != NULL) { + int errcode; + self->stream_start_position = mp_stream_seek(file_obj, 0, MP_SEEK_CUR, &errcode); + } + #endif return common_hal_jpegio_jpegdecoder_decode_common(self, file_input); } @@ -123,41 +144,26 @@ mp_obj_t common_hal_jpegio_jpegdecoder_set_source_buffer(jpegio_jpegdecoder_obj_ return common_hal_jpegio_jpegdecoder_decode_common(self, buffer_input); } -#define DECODER_CONTINUE (1) -#define DECODER_INTERRUPT (0) -static int bitmap_output(JDEC *jd, void *data, JRECT *rect) { - jpegio_jpegdecoder_obj_t *self = CONTAINER_OF(jd, jpegio_jpegdecoder_obj_t, decoder); - int src_width = rect->right - rect->left + 1, src_pixel_stride = src_width /* in units of pixels! */, src_height = rect->bottom - rect->top + 1; - - displayio_bitmap_t src = { - .width = src_width, - .height = src_height, - .data = data, - .stride = src_pixel_stride / 2, /* in units of uint32_t */ - .bits_per_value = 16, - .x_shift = 1, - .x_mask = 1, - .bitmask = 0xffff, - }; - +bool jpegio_jpegdecoder_blit_rect(jpegio_jpegdecoder_obj_t *self, displayio_bitmap_t *src, int left, int top) { + int src_width = src->width, src_height = src->height; int x = self->x; int y = self->y; - int x1 = self->lim.x1 - rect->left; - int x2 = self->lim.x2 - rect->left; - int y1 = self->lim.y1 - rect->top; - int y2 = self->lim.y2 - rect->top; + int x1 = self->lim.x1 - left; + int x2 = self->lim.x2 - left; + int y1 = self->lim.y1 - top; + int y2 = self->lim.y2 - top; - if (y2 < y1) { + if (y2 <= 0) { // The last row in the source image to copy FROM is above of this, so // no more pixels on any rows - return DECODER_INTERRUPT; + return false; } y2 = MIN(y2, src_height); - if (x2 < x1) { + if (x2 <= 0) { // The last column in the source image to copy FROM is left of this, so // no more pixels on this row but could be on subsequent rows - return DECODER_CONTINUE; + return true; } x2 = MIN(x2, src_width); @@ -181,10 +187,76 @@ static int bitmap_output(JDEC *jd, void *data, JRECT *rect) { assert(x2 <= src_width); assert(y2 <= src_height); - common_hal_bitmaptools_blit(self->dest, &src, x, y, x1, y1, x2, y2, self->skip_source_index, self->skip_source_index_none, self->skip_dest_index, self->skip_dest_index_none); - return 1; + common_hal_bitmaptools_blit(self->dest, src, x, y, x1, y1, x2, y2, self->skip_source_index, self->skip_source_index_none, self->skip_dest_index, self->skip_dest_index_none); + return true; } +#define DECODER_CONTINUE (1) +#define DECODER_INTERRUPT (0) +static int bitmap_output(JDEC *jd, void *data, JRECT *rect) { + jpegio_jpegdecoder_obj_t *self = CONTAINER_OF(jd, jpegio_jpegdecoder_obj_t, decoder); + int src_width = rect->right - rect->left + 1, src_pixel_stride = src_width /* in units of pixels! */, src_height = rect->bottom - rect->top + 1; + + displayio_bitmap_t src = { + .width = src_width, + .height = src_height, + .data = data, + .stride = src_pixel_stride / 2, /* in units of uint32_t */ + .bits_per_value = 16, + .x_shift = 1, + .x_mask = 1, + .bitmask = 0xffff, + }; + + return jpegio_jpegdecoder_blit_rect(self, &src, rect->left, rect->top) ? DECODER_CONTINUE : DECODER_INTERRUPT; +} + +#if CIRCUITPY_JPEGIO_FAST +// Read a seekable file or stream, from where the JPEG starts to the end, into +// memory and pass it to the port's decoder. If the port declines, the stream is +// put back where TJpgDec left it, so TJpgDec can continue. +static bool fast_decode_stream(jpegio_jpegdecoder_obj_t *self, int scale) { + mp_obj_t stream = self->data_obj; + mp_off_t start = self->stream_start_position; + if (start == (mp_off_t)-1) { + return false; + } + int errcode; + mp_off_t pos = mp_stream_seek(stream, 0, MP_SEEK_CUR, &errcode); + if (pos == (mp_off_t)-1) { + return false; + } + mp_off_t end = mp_stream_seek(stream, 0, MP_SEEK_END, &errcode); + bool ok = false; + if (end != (mp_off_t)-1 && end > start) { + size_t size = end - start; + uint8_t *data = m_malloc_maybe(size); + if (data != NULL && mp_stream_seek(stream, start, MP_SEEK_SET, &errcode) == start && + mp_stream_rw(stream, data, size, &errcode, MP_STREAM_RW_READ) == size) { + mp_buffer_info_t jpeg = { .buf = data, .len = size }; + ok = jpegio_jpegdecoder_fast_decode(self, &jpeg, scale); + } + m_free(data); + } + if (!ok) { + mp_stream_seek(stream, pos, MP_SEEK_SET, &errcode); + } + return ok; +} + +static bool fast_decode(jpegio_jpegdecoder_obj_t *self, int scale) { + if (!jpegio_jpegdecoder_fast_supported(self, scale)) { + return false; + } + if (self->decoder.infunc == file_input) { + return fast_decode_stream(self, scale); + } + mp_buffer_info_t jpeg; + return mp_get_buffer(self->data_obj, &jpeg, MP_BUFFER_READ) && + jpegio_jpegdecoder_fast_decode(self, &jpeg, scale); +} +#endif + void common_hal_jpegio_jpegdecoder_decode_into( jpegio_jpegdecoder_obj_t *self, displayio_bitmap_t *bitmap, int scale, int16_t x, int16_t y, @@ -204,6 +276,31 @@ void common_hal_jpegio_jpegdecoder_decode_into( self->skip_dest_index_none = skip_dest_index_none; self->dest = bitmap; + + #if CIRCUITPY_JPEGIO_HW + mp_buffer_info_t jpeg; + if (self->decoder.infunc == buffer_input && + mp_get_buffer(self->data_obj, &jpeg, MP_BUFFER_READ)) { + if (jpegio_jpegdecoder_hw_decode(self, &jpeg, scale)) { + common_hal_jpegio_jpegdecoder_close(self); + return; + } + } else if (!self->software_ok) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("Invalid %q"), MP_QSTR_data_source); + } + #else + if (!self->software_ok) { + mp_raise_ValueError(MP_ERROR_TEXT("Operation or feature not supported")); + } + #endif + + #if CIRCUITPY_JPEGIO_FAST + if (fast_decode(self, scale)) { + common_hal_jpegio_jpegdecoder_close(self); + return; + } + #endif + JRESULT result = jd_decomp(&self->decoder, bitmap_output, scale); common_hal_jpegio_jpegdecoder_close(self); if (result != JDR_INTR) { diff --git a/shared-module/jpegio/JpegDecoder.h b/shared-module/jpegio/JpegDecoder.h index 2585b364545..cdd3cb21d5d 100644 --- a/shared-module/jpegio/JpegDecoder.h +++ b/shared-module/jpegio/JpegDecoder.h @@ -24,4 +24,54 @@ typedef struct jpegio_jpegdecoder_obj { uint32_t skip_source_index, skip_dest_index; bool skip_source_index_none, skip_dest_index_none; uint8_t scale; + bool software_ok; + #if CIRCUITPY_JPEGIO_HW + void *hw_decoder; // port state for the hardware decoder, NULL if unavailable + #endif + #if CIRCUITPY_JPEGIO_FAST + mp_off_t stream_start_position; // where the JPEG starts in a seekable stream, or -1 + #endif } jpegio_jpegdecoder_obj_t; + +// Copies `src`, whose top left pixel is pixel (left, top) of the decoded image, +// into `self->dest`, clipped to the crop area and placed at `self->x`, `self->y`. +// Returns false if `src` starts below the crop area, so no later rows are needed. +// Raises only if `self->dest` is read-only. +bool jpegio_jpegdecoder_blit_rect(jpegio_jpegdecoder_obj_t *self, displayio_bitmap_t *src, int left, int top); + +#if CIRCUITPY_JPEGIO_HW +// Ports with JPEG decode hardware provide this. Called when the decoder object is +// constructed. Sets `self->hw_decoder`, or NULL if the hardware is unavailable, in which +// case decode() uses TJpgDec. Must not raise. +void jpegio_jpegdecoder_hw_init(jpegio_jpegdecoder_obj_t *self); + +// Ports with JPEG decode hardware provide this. It is called by decode() only when the +// source passed to open() is an in-memory buffer; `jpeg` is that whole buffer. The decode +// arguments (x, y, lim, skip indices) are already stored in `self`, and `self->dest` is +// the target bitmap. +// Returns true if the port decoded the image into `self->dest`. Returns false to decode +// with TJpgDec instead, which rewrites every pixel the image covers. If +// `self->software_ok` is false, raises ValueError instead of returning false. +bool jpegio_jpegdecoder_hw_decode(jpegio_jpegdecoder_obj_t *self, const mp_buffer_info_t *jpeg, int scale); + +// Ports with JPEG decode hardware provide this. It releases `self->hw_decoder`, if set, +// and sets it to NULL. Called when the decoder object is collected. Must not raise. +void jpegio_jpegdecoder_hw_deinit(jpegio_jpegdecoder_obj_t *self); +#endif + +#if CIRCUITPY_JPEGIO_FAST +// Ports with a faster software decoder provide these two. decode() calls them when +// software decoding is allowed, before TJpgDec. The decode arguments and `self->dest` +// are set as for jpegio_jpegdecoder_hw_decode, and `self->decoder` holds the header +// TJpgDec parsed in open(). + +// Returns true if the port's decoder may handle this image with these arguments. +// Called before a file or stream is read into memory, so it must be cheap. Must not raise. +bool jpegio_jpegdecoder_fast_supported(jpegio_jpegdecoder_obj_t *self, int scale); + +// Called only after jpegio_jpegdecoder_fast_supported returned true, with the whole JPEG +// in `jpeg`: the buffer passed to open(), or a file or stream read into memory. +// Returns true if the port decoded the image into `self->dest`. Returns false to decode +// with TJpgDec instead, which rewrites every pixel the image covers. Must not raise. +bool jpegio_jpegdecoder_fast_decode(jpegio_jpegdecoder_obj_t *self, const mp_buffer_info_t *jpeg, int scale); +#endif diff --git a/shared-module/keypad/EventQueue.c b/shared-module/keypad/EventQueue.c index e5b362a045d..3130d8b59a1 100644 --- a/shared-module/keypad/EventQueue.c +++ b/shared-module/keypad/EventQueue.c @@ -15,9 +15,14 @@ #define EVENT_SIZE_BYTES (sizeof(uint16_t) + sizeof(mp_obj_t)) -void common_hal_keypad_eventqueue_construct(keypad_eventqueue_obj_t *self, size_t max_events) { +void common_hal_keypad_eventqueue_construct(keypad_eventqueue_obj_t *self, size_t max_events, bool use_gc_allocator) { // Event queue is 16-bit values. - ringbuf_alloc(&self->encoded_events, max_events * EVENT_SIZE_BYTES); + const size_t size = max_events * EVENT_SIZE_BYTES; + if (use_gc_allocator) { + ringbuf_alloc(&self->encoded_events, size); + } else { + ringbuf_init(&self->encoded_events, port_malloc(size, false), size); + } self->overflowed = false; self->event_handler = NULL; } diff --git a/shared-module/keypad/KeyMatrix.c b/shared-module/keypad/KeyMatrix.c index 67a55468535..ebd34e5f108 100644 --- a/shared-module/keypad/KeyMatrix.c +++ b/shared-module/keypad/KeyMatrix.c @@ -32,31 +32,39 @@ static mp_uint_t row_column_to_key_number(keypad_keymatrix_obj_t *self, mp_uint_ void common_hal_keypad_keymatrix_construct(keypad_keymatrix_obj_t *self, mp_uint_t num_row_pins, const mcu_pin_obj_t *row_pins[], mp_uint_t num_column_pins, const mcu_pin_obj_t *column_pins[], bool columns_to_anodes, mp_float_t interval, size_t max_events, uint8_t debounce_threshold) { + common_hal_keypad_deinit_core(self); + mp_obj_t row_dios[num_row_pins]; for (size_t row = 0; row < num_row_pins; row++) { - digitalio_digitalinout_obj_t *dio = - mp_obj_malloc(digitalio_digitalinout_obj_t, &digitalio_digitalinout_type); - common_hal_digitalio_digitalinout_construct(dio, row_pins[row]); - common_hal_digitalio_digitalinout_switch_to_input(dio, columns_to_anodes ? PULL_UP : PULL_DOWN); - row_dios[row] = dio; + row_dios[row] = mp_obj_malloc(digitalio_digitalinout_obj_t, &digitalio_digitalinout_type); } self->row_digitalinouts = mp_obj_new_tuple(num_row_pins, row_dios); mp_obj_t column_dios[num_column_pins]; for (size_t column = 0; column < num_column_pins; column++) { - digitalio_digitalinout_obj_t *dio = - mp_obj_malloc(digitalio_digitalinout_obj_t, &digitalio_digitalinout_type); - dio->base.type = &digitalio_digitalinout_type; - common_hal_digitalio_digitalinout_construct(dio, column_pins[column]); - common_hal_digitalio_digitalinout_switch_to_input(dio, columns_to_anodes ? PULL_UP : PULL_DOWN); - column_dios[column] = dio; + column_dios[column] = mp_obj_malloc(digitalio_digitalinout_obj_t, &digitalio_digitalinout_type); } self->column_digitalinouts = mp_obj_new_tuple(num_column_pins, column_dios); self->columns_to_anodes = columns_to_anodes; self->funcs = &keymatrix_funcs; - keypad_construct_common((keypad_scanner_obj_t *)self, interval, max_events, debounce_threshold); + keypad_eventqueue_obj_t *events = + keypad_allocate_common((keypad_scanner_obj_t *)self, interval, max_events, debounce_threshold, true); + + for (size_t row = 0; row < num_row_pins; row++) { + digitalio_digitalinout_obj_t *dio = row_dios[row]; + common_hal_digitalio_digitalinout_construct(dio, row_pins[row]); + common_hal_digitalio_digitalinout_switch_to_input(dio, columns_to_anodes ? PULL_UP : PULL_DOWN); + } + + for (size_t column = 0; column < num_column_pins; column++) { + digitalio_digitalinout_obj_t *dio = column_dios[column]; + common_hal_digitalio_digitalinout_construct(dio, column_pins[column]); + common_hal_digitalio_digitalinout_switch_to_input(dio, columns_to_anodes ? PULL_UP : PULL_DOWN); + } + + keypad_start_common((keypad_scanner_obj_t *)self, events); } void common_hal_keypad_keymatrix_deinit(keypad_keymatrix_obj_t *self) { diff --git a/shared-module/keypad/Keys.c b/shared-module/keypad/Keys.c index 39d50f95e32..6b81f43c0af 100644 --- a/shared-module/keypad/Keys.c +++ b/shared-module/keypad/Keys.c @@ -25,24 +25,29 @@ static keypad_scanner_funcs_t keys_funcs = { }; void common_hal_keypad_keys_construct(keypad_keys_obj_t *self, mp_uint_t num_pins, const mcu_pin_obj_t *pins[], bool value_when_pressed, bool pull, mp_float_t interval, size_t max_events, uint8_t debounce_threshold) { - mp_obj_t dios[num_pins]; + common_hal_keypad_deinit_core(self); + mp_obj_t dios[num_pins]; for (size_t i = 0; i < num_pins; i++) { - digitalio_digitalinout_obj_t *dio = - mp_obj_malloc(digitalio_digitalinout_obj_t, &digitalio_digitalinout_type); - common_hal_digitalio_digitalinout_construct(dio, pins[i]); - if (pull) { - common_hal_digitalio_digitalinout_set_pull(dio, value_when_pressed ? PULL_DOWN : PULL_UP); - } - dios[i] = dio; + dios[i] = mp_obj_malloc(digitalio_digitalinout_obj_t, &digitalio_digitalinout_type); } self->digitalinouts = mp_obj_new_tuple(num_pins, dios); self->value_when_pressed = value_when_pressed; self->funcs = &keys_funcs; - keypad_construct_common((keypad_scanner_obj_t *)self, interval, max_events, debounce_threshold); + keypad_eventqueue_obj_t *events = + keypad_allocate_common((keypad_scanner_obj_t *)self, interval, max_events, debounce_threshold, true); + + for (size_t i = 0; i < num_pins; i++) { + digitalio_digitalinout_obj_t *dio = dios[i]; + common_hal_digitalio_digitalinout_construct(dio, pins[i]); + if (pull) { + common_hal_digitalio_digitalinout_set_pull(dio, value_when_pressed ? PULL_DOWN : PULL_UP); + } + } + keypad_start_common((keypad_scanner_obj_t *)self, events); } void common_hal_keypad_keys_deinit(keypad_keys_obj_t *self) { diff --git a/shared-module/keypad/ShiftRegisterKeys.c b/shared-module/keypad/ShiftRegisterKeys.c index f65c9a0532f..55252025b9c 100644 --- a/shared-module/keypad/ShiftRegisterKeys.c +++ b/shared-module/keypad/ShiftRegisterKeys.c @@ -26,33 +26,24 @@ static keypad_scanner_funcs_t shiftregisterkeys_funcs = { void common_hal_keypad_shiftregisterkeys_construct(keypad_shiftregisterkeys_obj_t *self, const mcu_pin_obj_t *clock_pin, mp_uint_t num_data_pins, const mcu_pin_obj_t *data_pins[], const mcu_pin_obj_t *latch_pin, bool value_to_latch, mp_uint_t num_key_counts, size_t key_counts[], bool value_when_pressed, mp_float_t interval, size_t max_events, uint8_t debounce_threshold) { + common_hal_keypad_deinit_core(self); + digitalio_digitalinout_obj_t *clock = mp_obj_malloc(digitalio_digitalinout_obj_t, &digitalio_digitalinout_type); - common_hal_digitalio_digitalinout_construct(clock, clock_pin); - common_hal_digitalio_digitalinout_switch_to_output(clock, false, DRIVE_MODE_PUSH_PULL); self->clock = clock; - digitalio_digitalinout_obj_t *latch = m_new_obj(digitalio_digitalinout_obj_t); - latch->base.type = &digitalio_digitalinout_type; - - common_hal_digitalio_digitalinout_construct(latch, latch_pin); - common_hal_digitalio_digitalinout_switch_to_output(latch, true, DRIVE_MODE_PUSH_PULL); + digitalio_digitalinout_obj_t *latch = mp_obj_malloc(digitalio_digitalinout_obj_t, &digitalio_digitalinout_type); self->latch = latch; mp_obj_t dios[num_data_pins]; - for (size_t i = 0; i < num_data_pins; i++) { - digitalio_digitalinout_obj_t *dio = m_new_obj(digitalio_digitalinout_obj_t); - dio->base.type = &digitalio_digitalinout_type; - common_hal_digitalio_digitalinout_construct(dio, data_pins[i]); - common_hal_digitalio_digitalinout_switch_to_input(dio, PULL_NONE); - dios[i] = dio; + dios[i] = mp_obj_malloc(digitalio_digitalinout_obj_t, &digitalio_digitalinout_type); } // Allocate a tuple object with the data pins self->data_pins = mp_obj_new_tuple(num_data_pins, dios); - self->key_counts = (mp_uint_t *)m_malloc(sizeof(mp_uint_t) * num_key_counts); + self->key_counts = (mp_uint_t *)m_malloc_without_collect(sizeof(mp_uint_t) * num_key_counts); self->num_key_counts = num_key_counts; // copy to an m_malloc() and on the fly record pin with largest Shift register @@ -74,7 +65,22 @@ void common_hal_keypad_shiftregisterkeys_construct(keypad_shiftregisterkeys_obj_ self->value_when_pressed = value_when_pressed; self->funcs = &shiftregisterkeys_funcs; - keypad_construct_common((keypad_scanner_obj_t *)self, interval, max_events, debounce_threshold); + keypad_eventqueue_obj_t *events = + keypad_allocate_common((keypad_scanner_obj_t *)self, interval, max_events, debounce_threshold, true); + + common_hal_digitalio_digitalinout_construct(clock, clock_pin); + common_hal_digitalio_digitalinout_switch_to_output(clock, false, DRIVE_MODE_PUSH_PULL); + + common_hal_digitalio_digitalinout_construct(latch, latch_pin); + common_hal_digitalio_digitalinout_switch_to_output(latch, true, DRIVE_MODE_PUSH_PULL); + + for (size_t i = 0; i < num_data_pins; i++) { + digitalio_digitalinout_obj_t *dio = dios[i]; + common_hal_digitalio_digitalinout_construct(dio, data_pins[i]); + common_hal_digitalio_digitalinout_switch_to_input(dio, PULL_NONE); + } + + keypad_start_common((keypad_scanner_obj_t *)self, events); } void common_hal_keypad_shiftregisterkeys_deinit(keypad_shiftregisterkeys_obj_t *self) { diff --git a/shared-module/keypad/__init__.c b/shared-module/keypad/__init__.c index 80e61f3ec7b..57c66a27519 100644 --- a/shared-module/keypad/__init__.c +++ b/shared-module/keypad/__init__.c @@ -37,18 +37,6 @@ void keypad_tick(void) { } } -void keypad_reset(void) { - keypad_scanner_obj_t *scanner = MP_STATE_VM(keypad_scanners_linked_list); - keypad_scanner_obj_t *next = MP_STATE_VM(keypad_scanners_linked_list); - while (scanner) { - next = scanner->next; - if (!scanner->never_reset) { - keypad_deregister_scanner(scanner); - } - scanner = next; - } -} - // Register a Keys, KeyMatrix, etc. that will be scanned in the background void keypad_register_scanner(keypad_scanner_obj_t *scanner) { supervisor_acquire_lock(&keypad_scanners_linked_list_lock); @@ -85,19 +73,28 @@ void keypad_deregister_scanner(keypad_scanner_obj_t *scanner) { supervisor_release_lock(&keypad_scanners_linked_list_lock); } -void keypad_construct_common(keypad_scanner_obj_t *self, mp_float_t interval, size_t max_events, uint8_t debounce_threshold) { +keypad_eventqueue_obj_t *keypad_allocate_common(keypad_scanner_obj_t *self, mp_float_t interval, size_t max_events, uint8_t debounce_threshold, bool use_gc_allocator) { size_t key_count = common_hal_keypad_generic_get_key_count(self); - self->debounce_counter = (int8_t *)m_malloc(sizeof(int8_t) * key_count); + self->debounce_counter = + use_gc_allocator + ? (int8_t *)m_malloc_without_collect(sizeof(int8_t) * key_count) + : (int8_t *)port_malloc_zero(sizeof(int8_t) * key_count, false); self->interval_ticks = (mp_uint_t)(interval * 1024); // interval * 1000 * (1024/1000) - keypad_eventqueue_obj_t *events = mp_obj_malloc(keypad_eventqueue_obj_t, &keypad_eventqueue_type); - common_hal_keypad_eventqueue_construct(events, max_events); - self->events = events; + keypad_eventqueue_obj_t *events = + use_gc_allocator + ? mp_obj_malloc(keypad_eventqueue_obj_t, &keypad_eventqueue_type) + : mp_obj_port_malloc(keypad_eventqueue_obj_t, &keypad_eventqueue_type); + common_hal_keypad_eventqueue_construct(events, max_events, use_gc_allocator); self->debounce_threshold = debounce_threshold; - self->never_reset = false; + return events; +} + +void keypad_start_common(keypad_scanner_obj_t *self, keypad_eventqueue_obj_t *events) { + self->events = events; // Add self to the list of active keypad scanners. keypad_register_scanner(self); @@ -133,10 +130,6 @@ bool keypad_debounce(keypad_scanner_obj_t *self, mp_uint_t key_number, bool curr return false; } -void keypad_never_reset(keypad_scanner_obj_t *self) { - self->never_reset = true; -} - void common_hal_keypad_generic_reset(void *self_in) { keypad_scanner_obj_t *self = self_in; size_t key_count = common_hal_keypad_generic_get_key_count(self); diff --git a/shared-module/keypad/__init__.h b/shared-module/keypad/__init__.h index a7d21753f66..24fb6cda4f2 100644 --- a/shared-module/keypad/__init__.h +++ b/shared-module/keypad/__init__.h @@ -25,8 +25,7 @@ typedef struct _keypad_scanner_funcs_t { int8_t *debounce_counter; \ struct _keypad_eventqueue_obj_t *events; \ mp_uint_t interval_ticks; \ - uint8_t debounce_threshold; \ - bool never_reset + uint8_t debounce_threshold typedef struct _keypad_scanner_obj_t { KEYPAD_SCANNER_COMMON_FIELDS; @@ -35,13 +34,16 @@ typedef struct _keypad_scanner_obj_t { extern supervisor_lock_t keypad_scanners_linked_list_lock; void keypad_tick(void); -void keypad_reset(void); void keypad_register_scanner(keypad_scanner_obj_t *scanner); void keypad_deregister_scanner(keypad_scanner_obj_t *scanner); -void keypad_construct_common(keypad_scanner_obj_t *scanner, mp_float_t interval, size_t max_events, uint8_t debounce_cycles); +// Allocate a scanner's debounce counters and event queue. Call before +// claiming any pins. The scanner's funcs and key count must already be set. +struct _keypad_eventqueue_obj_t *keypad_allocate_common(keypad_scanner_obj_t *scanner, mp_float_t interval, size_t max_events, uint8_t debounce_cycles, bool use_gc_allocator); +// Make the scanner live with the event queue from keypad_allocate_common(), +// and start scanning. Call after the pins are set up. +void keypad_start_common(keypad_scanner_obj_t *scanner, struct _keypad_eventqueue_obj_t *events); bool keypad_debounce(keypad_scanner_obj_t *self, mp_uint_t key_number, bool current); -void keypad_never_reset(keypad_scanner_obj_t *self); size_t common_hal_keypad_generic_get_key_count(void *scanner); void common_hal_keypad_deinit_core(void *scanner); diff --git a/shared-module/keypad_demux/DemuxKeyMatrix.c b/shared-module/keypad_demux/DemuxKeyMatrix.c index b90669d772f..7728c2e799d 100644 --- a/shared-module/keypad_demux/DemuxKeyMatrix.c +++ b/shared-module/keypad_demux/DemuxKeyMatrix.c @@ -31,38 +31,57 @@ static mp_uint_t row_column_to_key_number(keypad_demux_demuxkeymatrix_obj_t *sel return row * common_hal_keypad_demux_demuxkeymatrix_get_column_count(self) + column; } -void common_hal_keypad_demux_demuxkeymatrix_construct(keypad_demux_demuxkeymatrix_obj_t *self, mp_uint_t num_row_addr_pins, const mcu_pin_obj_t *row_addr_pins[], mp_uint_t num_column_pins, const mcu_pin_obj_t *column_pins[], bool columns_to_anodes, bool transpose, mp_float_t interval, size_t max_events, uint8_t debounce_threshold) { +void common_hal_keypad_demux_demuxkeymatrix_construct(keypad_demux_demuxkeymatrix_obj_t *self, mp_uint_t num_row_addr_pins, const mcu_pin_obj_t *row_addr_pins[], mp_uint_t num_column_pins, const mcu_pin_obj_t *column_pins[], bool columns_to_anodes, bool transpose, mp_float_t interval, size_t max_events, uint8_t debounce_threshold, bool use_gc_allocator) { + common_hal_keypad_deinit_core(self); + + mp_obj_t row_addr_dios[num_row_addr_pins]; + for (size_t row = 0; row < num_row_addr_pins; row++) { + row_addr_dios[row] = + use_gc_allocator + ? mp_obj_malloc(digitalio_digitalinout_obj_t, &digitalio_digitalinout_type) + : mp_obj_port_malloc(digitalio_digitalinout_obj_t, &digitalio_digitalinout_type); + } + self->row_addr_digitalinouts = + use_gc_allocator + ? mp_obj_new_tuple(num_row_addr_pins, row_addr_dios) + : mp_obj_new_port_tuple(num_row_addr_pins, row_addr_dios); + + mp_obj_t column_dios[num_column_pins]; + for (size_t column = 0; column < num_column_pins; column++) { + column_dios[column] = + use_gc_allocator + ? mp_obj_malloc(digitalio_digitalinout_obj_t, &digitalio_digitalinout_type) + : mp_obj_port_malloc(digitalio_digitalinout_obj_t, &digitalio_digitalinout_type); + } + self->column_digitalinouts = + use_gc_allocator + ? mp_obj_new_tuple(num_column_pins, column_dios) + : mp_obj_new_port_tuple(num_column_pins, column_dios); + + self->columns_to_anodes = columns_to_anodes; + self->transpose = transpose; + self->funcs = &keymatrix_funcs; + + keypad_eventqueue_obj_t *events = + keypad_allocate_common((keypad_scanner_obj_t *)self, interval, max_events, debounce_threshold, use_gc_allocator); // the multiplexed pins are outputs so we can set the address for the target row // the sense of the address pins themselves doesn't change with columns_to_anodes // but the value output on the selected row line will be !columns_to_anodes - mp_obj_t row_addr_dios[num_row_addr_pins]; for (size_t row = 0; row < num_row_addr_pins; row++) { - digitalio_digitalinout_obj_t *dio = - mp_obj_malloc(digitalio_digitalinout_obj_t, &digitalio_digitalinout_type); + digitalio_digitalinout_obj_t *dio = row_addr_dios[row]; common_hal_digitalio_digitalinout_construct(dio, row_addr_pins[row]); common_hal_digitalio_digitalinout_switch_to_output(dio, false, DRIVE_MODE_PUSH_PULL); - row_addr_dios[row] = dio; } - self->row_addr_digitalinouts = mp_obj_new_tuple(num_row_addr_pins, row_addr_dios); // the column pins are always inputs, with default state based on columns_to_anodes - mp_obj_t column_dios[num_column_pins]; for (size_t column = 0; column < num_column_pins; column++) { - digitalio_digitalinout_obj_t *dio = - mp_obj_malloc(digitalio_digitalinout_obj_t, &digitalio_digitalinout_type); - dio->base.type = &digitalio_digitalinout_type; + digitalio_digitalinout_obj_t *dio = column_dios[column]; common_hal_digitalio_digitalinout_construct(dio, column_pins[column]); common_hal_digitalio_digitalinout_switch_to_input(dio, columns_to_anodes ? PULL_UP : PULL_DOWN); - column_dios[column] = dio; } - self->column_digitalinouts = mp_obj_new_tuple(num_column_pins, column_dios); - - self->columns_to_anodes = columns_to_anodes; - self->transpose = transpose; - self->funcs = &keymatrix_funcs; - keypad_construct_common((keypad_scanner_obj_t *)self, interval, max_events, debounce_threshold); + keypad_start_common((keypad_scanner_obj_t *)self, events); } void common_hal_keypad_demux_demuxkeymatrix_deinit(keypad_demux_demuxkeymatrix_obj_t *self) { @@ -154,13 +173,3 @@ static void demuxkeymatrix_scan_now(void *self_in, mp_obj_t timestamp) { } } } - -void demuxkeymatrix_never_reset(keypad_demux_demuxkeymatrix_obj_t *self) { - keypad_never_reset((keypad_scanner_obj_t *)self); - for (size_t row_addr = 0; row_addr < self->row_addr_digitalinouts->len; row_addr++) { - common_hal_digitalio_digitalinout_never_reset(self->row_addr_digitalinouts->items[row_addr]); - } - for (size_t column = 0; column < self->column_digitalinouts->len; column++) { - common_hal_digitalio_digitalinout_never_reset(self->column_digitalinouts->items[column]); - } -} diff --git a/shared-module/keypad_demux/DemuxKeyMatrix.h b/shared-module/keypad_demux/DemuxKeyMatrix.h index fe315775dd2..5ec6a4b3c8b 100644 --- a/shared-module/keypad_demux/DemuxKeyMatrix.h +++ b/shared-module/keypad_demux/DemuxKeyMatrix.h @@ -22,4 +22,3 @@ typedef struct { } keypad_demux_demuxkeymatrix_obj_t; void keypad_demux_demuxkeymatrix_scan(keypad_demux_demuxkeymatrix_obj_t *self); -void demuxkeymatrix_never_reset(keypad_demux_demuxkeymatrix_obj_t *self); diff --git a/shared-module/lvfontio/OnDiskFont.c b/shared-module/lvfontio/OnDiskFont.c new file mode 100644 index 00000000000..a93b8485b7f --- /dev/null +++ b/shared-module/lvfontio/OnDiskFont.c @@ -0,0 +1,882 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include + +#include "shared-bindings/lvfontio/OnDiskFont.h" +#include "py/runtime.h" +#include "py/mperrno.h" +#include "py/stream.h" +#include "py/objstr.h" +#include "py/gc.h" +#include "shared-bindings/displayio/Bitmap.h" +#include "supervisor/shared/translate/translate.h" +#include "supervisor/port.h" +#include "supervisor/shared/serial.h" +#include "supervisor/filesystem.h" + +// Helper functions for memory allocation. On failure, deinit the font, then raise when using +// the GC heap or return NULL when using the port heap. +static void *check_allocation(lvfontio_ondiskfont_t *self, size_t size, void *ptr) { + if (ptr != NULL) { + return ptr; + } + common_hal_lvfontio_ondiskfont_deinit(self); + if (self->use_gc_allocator) { + m_malloc_fail(size); + } + return NULL; +} + +// For memory that may hold pointers to other heap allocations. +static inline void *allocate_memory(lvfontio_ondiskfont_t *self, size_t size) { + void *ptr = self->use_gc_allocator ? m_malloc_maybe(size) : port_malloc(size, false); + return check_allocation(self, size, ptr); +} + +// For memory that never holds pointers, so the garbage collector does not scan it. +static inline void *allocate_pointer_free_memory(lvfontio_ondiskfont_t *self, size_t size) { + void *ptr = self->use_gc_allocator ? m_malloc_maybe_without_collect(size) : port_malloc(size, false); + return check_allocation(self, size, ptr); +} + +static inline void free_memory(lvfontio_ondiskfont_t *self, void *ptr) { + if (self->use_gc_allocator) { + m_free(ptr); + } else { + port_free(ptr); + } +} + +// Forward declarations for helper functions +static int16_t find_codepoint_slot(lvfontio_ondiskfont_t *self, uint32_t codepoint); +static bool slot_has_active_full_width_partner(lvfontio_ondiskfont_t *self, uint16_t slot); +static uint16_t find_free_slot(lvfontio_ondiskfont_t *self, uint32_t codepoint); +static bool read_bits(supervisor_vfs_file_t *file, size_t num_bits, uint8_t *byte_val, uint8_t *remaining_bits, uint32_t *result); +static bool read_glyph_dimensions(supervisor_vfs_file_t *file, lvfontio_ondiskfont_t *self, uint32_t *advance_width, int32_t *bbox_x, int32_t *bbox_y, uint32_t *bbox_w, uint32_t *bbox_h, uint8_t *byte_val, uint8_t *remaining_bits); + +static bool read_file(supervisor_vfs_file_t *file, void *buf, size_t len) { + size_t bytes_read; + supervisor_fs_err_t err = supervisor_vfs_read_file(file, buf, len, &bytes_read); + return err == SUPERVISOR_FS_OK && bytes_read >= len; +} + +static bool seek_file(supervisor_vfs_file_t *file, size_t offset) { + return supervisor_vfs_seek_file(file, offset) == SUPERVISOR_FS_OK; +} + +// Load font header data from file +static bool load_font_header(lvfontio_ondiskfont_t *self, supervisor_vfs_file_t *file, size_t *max_slots) { + // Start at the beginning of the file + if (!seek_file(file, 0)) { + return false; + } + + uint8_t buffer[8]; + bool found_head = false; + bool found_cmap = false; + bool found_loca = false; + bool found_glyf = false; + + + size_t current_position = 0; + + // Read sections until we find all the sections we need or reach end of file + while (true) { + // Read section size (4 bytes) + if (!read_file(file, buffer, 4)) { + break; // Read error or end of file + } + + uint32_t section_size = buffer[0] | (buffer[1] << 8) | + (buffer[2] << 16) | (buffer[3] << 24); + + if (section_size == 0) { + break; // End of sections marker + } + + // Read section marker (4 bytes) + if (!read_file(file, buffer, 4)) { + break; // Read error or unexpected end of file + } + + + // Make a null-terminated copy of the section marker for debug printing + char section_marker[5] = {0}; + memcpy(section_marker, buffer, 4); + + // Process different section types + if (memcmp(buffer, "head", 4) == 0) { + // Read head section data (35 bytes) + uint8_t head_buf[35]; + if (!read_file(file, head_buf, sizeof(head_buf))) { + break; + } + + // Skip version (4 bytes) and padding (1 byte) + // Parse font metrics at offset 6 + self->header.font_size = head_buf[6] | (head_buf[7] << 8); + self->header.ascent = head_buf[8] | (head_buf[9] << 8); + self->header.default_advance_width = head_buf[22] | (head_buf[23] << 8); + + // Parse format information + self->header.index_to_loc_format = head_buf[26]; + self->header.bits_per_pixel = head_buf[29]; + self->header.glyph_bbox_xy_bits = head_buf[30]; + self->header.glyph_bbox_wh_bits = head_buf[31]; + self->header.glyph_advance_bits = head_buf[32]; + + // Calculate derived values + self->header.glyph_header_bits = self->header.glyph_advance_bits + + 2 * self->header.glyph_bbox_xy_bits + + 2 * self->header.glyph_bbox_wh_bits; + self->header.glyph_header_bytes = (self->header.glyph_header_bits + 7) / 8; + + found_head = true; + } else if (memcmp(buffer, "cmap", 4) == 0) { + // Read subtable count + uint8_t cmap_header[4]; + if (!read_file(file, cmap_header, sizeof(cmap_header))) { + break; + } + + uint32_t subtable_count = cmap_header[0] | (cmap_header[1] << 8) | + (cmap_header[2] << 16) | (cmap_header[3] << 24); + + // Allocate memory for cmap ranges + self->cmap_range_count = subtable_count; + self->cmap_ranges = allocate_pointer_free_memory(self, sizeof(lvfontio_cmap_range_t) * subtable_count); + if (self->cmap_ranges == NULL) { + return false; + } + + // Read each subtable + for (uint16_t i = 0; i < subtable_count; i++) { + uint8_t subtable_buf[16]; + if (!read_file(file, subtable_buf, sizeof(subtable_buf))) { + break; + } + + // Read data_offset (4 bytes) + uint32_t data_offset = subtable_buf[0] | (subtable_buf[1] << 8) | + (subtable_buf[2] << 16) | (subtable_buf[3] << 24); + + // Read range_start, range_length, glyph_offset + uint32_t range_start = subtable_buf[4] | (subtable_buf[5] << 8) | + (subtable_buf[6] << 16) | (subtable_buf[7] << 24); + uint16_t range_length = subtable_buf[8] | (subtable_buf[9] << 8); + uint16_t glyph_offset = subtable_buf[10] | (subtable_buf[11] << 8); + uint16_t entries_count = subtable_buf[12] | (subtable_buf[13] << 8); + + // Get format type (0=sparse mapping, 1=range mapping, 2=range to range, 3=direct mapping) + uint8_t format_type = subtable_buf[14]; + // Check for supported format types (0, 2, and 3) + if (format_type != 0 && format_type != 2 && format_type != 3) { + continue; + } + + // Store the range information + self->cmap_ranges[i].range_start = range_start; + self->cmap_ranges[i].range_end = range_start + range_length; + self->cmap_ranges[i].glyph_offset = glyph_offset; + self->cmap_ranges[i].format_type = format_type; + self->cmap_ranges[i].data_offset = current_position + data_offset; + self->cmap_ranges[i].entries_count = entries_count; + } + + found_cmap = true; + } else if (memcmp(buffer, "loca", 4) == 0) { + // Read max_cid + uint8_t loca_header[4]; + if (!read_file(file, loca_header, sizeof(loca_header))) { + break; + } + + // Store max_cid value + self->max_cid = loca_header[0] | (loca_header[1] << 8) | + (loca_header[2] << 16) | (loca_header[3] << 24); + + // Store location of the loca table offset data + self->loca_table_offset = current_position + 12; + + found_loca = true; + } else if (memcmp(buffer, "glyf", 4) == 0) { + // Store start of glyf table + self->glyf_table_offset = current_position; + size_t advances[2] = {0, 0}; + size_t advance_count[2] = {0, 0}; + uint32_t max_advance = 0; + bool proportional = false; + + if (self->header.default_advance_width != 0) { + advances[0] = self->header.default_advance_width; + } + + // Set the default advance width based on the first character in the + // file. + size_t cid = 0; + while (cid < self->max_cid - 1) { + // Read glyph header fields + uint32_t glyph_advance; + int32_t bbox_x, bbox_y; + uint32_t bbox_w, bbox_h; + + uint8_t byte_val = 0; + uint8_t remaining_bits = 0; + + // Use the helper function to read glyph dimensions + if (!read_glyph_dimensions(file, self, &glyph_advance, &bbox_x, &bbox_y, &bbox_w, &bbox_h, &byte_val, &remaining_bits)) { + break; + } + + // Throw away the bitmap bits. + read_bits(file, self->header.bits_per_pixel * bbox_w * bbox_h, &byte_val, &remaining_bits, NULL); + + max_advance = MAX(max_advance, glyph_advance); + if (glyph_advance == 0) { + // Ignore zero-advance glyphs when inferring the terminal cell width. + // Some fonts include placeholders/control glyphs with zero advance, + // which would otherwise skew default_advance_width too small. + } else if (advances[0] == glyph_advance) { + advance_count[0]++; + } else if (advances[1] == glyph_advance) { + advance_count[1]++; + } else if (advance_count[0] == 0) { + advances[0] = glyph_advance; + advance_count[0] = 1; + } else if (advance_count[1] == 0) { + advances[1] = glyph_advance; + advance_count[1] = 1; + } else { + // A third width: not half and full width cells. Keep walking for the widest. + proportional = true; + } + cid++; + } + + if (self->header.default_advance_width == 0 && proportional) { + // Every glyph gets one cell as wide as the widest glyph. + if (max_advance > UINT8_MAX) { + return false; + } + self->header.default_advance_width = max_advance; + *max_slots = self->max_cid; + } else if (self->header.default_advance_width == 0) { + if (advance_count[1] == 0) { + self->header.default_advance_width = advances[0]; + *max_slots = advance_count[0]; + } else { + if (advances[0] > advances[1]) { + self->header.default_advance_width = advances[0] / 2; + *max_slots = advance_count[0] * 2 + advance_count[1]; + } else { + self->header.default_advance_width = advances[1] / 2; + *max_slots = advance_count[1] * 2 + advance_count[0]; + } + } + } else { + // Glyphs may have no advance of their own when the header sets it. + *max_slots = self->max_cid; + } + + if (self->header.default_advance_width == 0) { + self->header.default_advance_width = 1; + } + if (*max_slots == 0) { + *max_slots = 1; + } + found_glyf = true; + } + + current_position += section_size; + + // Skip to the end of the section + if (!seek_file(file, current_position)) { + break; + } + + // If we found all needed sections, we can stop + if (found_head && found_cmap && found_loca && found_glyf) { + break; + } + } + + // Check if we found all required sections + if (!found_head || !found_cmap || !found_loca || !found_glyf) { + return false; + } + + return true; +} + +// Get character ID (glyph index) for a codepoint +static int32_t get_char_id(lvfontio_ondiskfont_t *self, uint32_t codepoint) { + // Find codepoint in cmap ranges + for (uint16_t i = 0; i < self->cmap_range_count; i++) { + // Check if codepoint is in range for this subtable + if (codepoint >= self->cmap_ranges[i].range_start && + codepoint < self->cmap_ranges[i].range_end) { + + // Handle according to format type + switch (self->cmap_ranges[i].format_type) { + case 0: { // Sparse mapping - need to look up in a sparse table + if (!self->file_is_open) { + return -1; + } + + // Calculate the relative position within the range + uint32_t idx = codepoint - self->cmap_ranges[i].range_start; + + if (idx >= self->cmap_ranges[i].entries_count) { + return -1; + } + + // Calculate the absolute data position in the file + uint32_t data_pos = self->cmap_ranges[i].data_offset + idx; // 1 byte per entry + if (!seek_file(&self->file, data_pos)) { + return -1; + } + + // Read the glyph ID (1 byte) + uint8_t glyph_id; + if (!read_file(&self->file, &glyph_id, 1)) { + return -1; + } + + + return self->cmap_ranges[i].glyph_offset + glyph_id; + } + + case 2: // Range to range - calculate based on offset within range + uint16_t idx = codepoint - self->cmap_ranges[i].range_start; + uint16_t glyph_id = self->cmap_ranges[i].glyph_offset + idx; + return glyph_id; + + case 3: { // Direct mapping - need to look up in the table + if (!self->file_is_open) { + return -1; + } + + if (!seek_file(&self->file, self->cmap_ranges[i].data_offset)) { + return -1; + } + uint16_t codepoint_delta = codepoint - self->cmap_ranges[i].range_start; + + for (size_t j = 0; j < self->cmap_ranges[i].entries_count; j++) { + // Read code point at the index + uint16_t candidate_codepoint_delta; + if (!read_file(&self->file, &candidate_codepoint_delta, 2)) { + return -1; + } + + if (candidate_codepoint_delta == codepoint_delta) { + return self->cmap_ranges[i].glyph_offset + j; + } + } + return -1; + } + + default: + return -1; + } + } + } + + return -1; // Not found +} + +// Load glyph bitmap data into a slot +// This function assumes the file is already open and positioned after reading the glyph dimensions +static bool load_glyph_bitmap(supervisor_vfs_file_t *file, lvfontio_ondiskfont_t *self, uint32_t codepoint, uint16_t slot, + uint32_t glyph_advance, int32_t bbox_x, int32_t bbox_y, uint32_t bbox_w, uint32_t bbox_h, + uint8_t *byte_val, uint8_t *remaining_bits) { + // Store codepoint at slot + self->codepoints[slot] = codepoint; + self->reference_counts[slot] = 1; + + // Read bitmap data pixel by pixel + uint16_t x_offset = slot * self->header.default_advance_width; + uint16_t y_offset = self->header.ascent - bbox_y - bbox_h; + for (uint16_t y = 0; y < bbox_h; y++) { + for (uint16_t x = 0; x < bbox_w; x++) { + uint32_t pixel_value; + if (!read_bits(file, self->header.bits_per_pixel, byte_val, remaining_bits, &pixel_value)) { + return false; + } + + // Adjust for bbox position within the glyph bounding box + int16_t bitmap_x = x_offset + x + bbox_x; + int16_t bitmap_y = y_offset + y; + + // Make sure we're in bounds + if (bitmap_x >= 0 && + bitmap_x < self->header.default_advance_width * self->max_glyphs && + bitmap_y >= 0 && + bitmap_y < self->header.font_size) { + common_hal_displayio_bitmap_set_pixel( + self->bitmap, + bitmap_x, + bitmap_y, + pixel_value + ); + } + } + } + + return true; +} + +// Constructor +void common_hal_lvfontio_ondiskfont_construct(lvfontio_ondiskfont_t *self, + const char *file_path, + uint16_t max_glyphs, + bool use_gc_allocator) { + + // Store the allocation mode + self->use_gc_allocator = use_gc_allocator; + // Store parameters + self->file_path = file_path; // Store the provided path string directly + self->max_glyphs = max_glyphs; + self->cmap_ranges = NULL; + self->file_is_open = false; + // Initialize to NULL so an early deinit (e.g. header load failure) is safe. + self->bitmap = NULL; + self->codepoints = NULL; + self->reference_counts = NULL; + + // Determine which filesystem to use based on the path + const char *path_under_mount; + supervisor_vfs_t *vfs = filesystem_for_path(file_path, &path_under_mount); + + if (vfs == NULL || !supervisor_vfs_supported(vfs)) { + // Not found, or a filesystem the supervisor API can't access. + if (self->use_gc_allocator) { + mp_raise_ValueError(MP_ERROR_TEXT("File not found")); + } + return; + } + + // Open the file and keep it open for the lifetime of the object. Reads don't take the + // filesystem lock: it is the write lock, and USB MSC holds it while the host can write. + supervisor_fs_err_t err = supervisor_vfs_open_file(vfs, path_under_mount, SUPERVISOR_FS_OPEN_READ, 0, &self->file); + if (err != SUPERVISOR_FS_OK) { + if (self->use_gc_allocator) { + mp_raise_ValueError(MP_ERROR_TEXT("File not found")); + } + return; + } + + self->file_is_open = true; + + // Load font headers + size_t max_slots; + if (!load_font_header(self, &self->file, &max_slots)) { + common_hal_lvfontio_ondiskfont_deinit(self); + if (self->use_gc_allocator) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("Invalid %q"), MP_QSTR_file); + } + return; + } + // Cap the number of slots to the number of slots needed by the font. That way + // small font files don't need a bunch of extra cache space. + max_glyphs = MIN(max_glyphs, max_slots); + self->max_glyphs = max_glyphs; + + // Allocate codepoints array. allocate_pointer_free_memory will raise an exception if + // allocation fails and the VM is active. + self->codepoints = allocate_pointer_free_memory(self, sizeof(uint32_t) * max_glyphs); + if (self->codepoints == NULL) { + return; + } + + // Initialize codepoints to invalid + for (uint16_t i = 0; i < max_glyphs; i++) { + self->codepoints[i] = LVFONTIO_INVALID_CODEPOINT; + } + + // Allocate reference counts + self->reference_counts = allocate_pointer_free_memory(self, sizeof(uint16_t) * max_glyphs); + if (self->reference_counts == NULL) { + return; + } + + // Initialize reference counts to 0 + memset(self->reference_counts, 0, sizeof(uint16_t) * max_glyphs); + + self->half_width_px = self->header.default_advance_width; + + // Create bitmap for glyph cache + displayio_bitmap_t *bitmap = allocate_memory(self, sizeof(displayio_bitmap_t)); + bitmap->base.type = &displayio_bitmap_type; + if (bitmap == NULL) { + return; + } + + // Calculate bitmap stride + uint32_t bits_per_pixel = 1 << self->header.bits_per_pixel; + uint32_t width = self->header.default_advance_width * max_glyphs; + uint32_t row_width = width * bits_per_pixel; + uint16_t stride = (row_width + 31) / 32; // Align to uint32_t (32 bits) + + // Allocate buffer for bitmap data + uint32_t buffer_size = stride * self->header.font_size * sizeof(uint32_t); + uint32_t *bitmap_buffer = allocate_pointer_free_memory(self, buffer_size); + if (bitmap_buffer == NULL) { + return; + } + + // Zero out bitmap buffer + memset(bitmap_buffer, 0, buffer_size); + + // Construct bitmap with allocated buffer + common_hal_displayio_bitmap_construct_from_buffer(bitmap, + self->header.default_advance_width * max_glyphs, + self->header.font_size, + 1 << self->header.bits_per_pixel, + bitmap_buffer, + false); + self->bitmap = bitmap; +} + +void common_hal_lvfontio_ondiskfont_deinit(lvfontio_ondiskfont_t *self) { + if (!self->file_is_open) { + return; + } + if (self->bitmap != NULL) { + common_hal_displayio_bitmap_deinit(self->bitmap); + self->bitmap = NULL; + } + + if (self->codepoints != NULL) { + free_memory(self, self->codepoints); + self->codepoints = NULL; + } + + if (self->reference_counts != NULL) { + free_memory(self, self->reference_counts); + self->reference_counts = NULL; + } + + + + if (self->cmap_ranges != NULL) { + free_memory(self, self->cmap_ranges); + self->cmap_ranges = NULL; + } + + supervisor_vfs_close_file(&self->file); + self->file_is_open = false; +} + +bool common_hal_lvfontio_ondiskfont_deinited(lvfontio_ondiskfont_t *self) { + return !self->file_is_open; +} + +mp_obj_t common_hal_lvfontio_ondiskfont_get_bitmap(const lvfontio_ondiskfont_t *self) { + return MP_OBJ_FROM_PTR(self->bitmap); +} + +mp_obj_t common_hal_lvfontio_ondiskfont_get_bounding_box(const lvfontio_ondiskfont_t *self) { + mp_obj_t bbox[2]; + bbox[0] = MP_OBJ_NEW_SMALL_INT(self->header.default_advance_width); + bbox[1] = MP_OBJ_NEW_SMALL_INT(self->header.font_size); + return mp_obj_new_tuple(2, bbox); +} + +void common_hal_lvfontio_ondiskfont_get_dimensions(const lvfontio_ondiskfont_t *self, + uint16_t *width, uint16_t *height) { + if (width != NULL) { + *width = self->header.default_advance_width; + } + if (height != NULL) { + *height = self->header.font_size; + } +} + +int16_t common_hal_lvfontio_ondiskfont_cache_glyph(lvfontio_ondiskfont_t *self, uint32_t codepoint, bool *is_full_width) { + // Check if already cached + int16_t existing_slot = find_codepoint_slot(self, codepoint); + if (existing_slot >= 0) { + // Glyph is already cached, increment reference count(s). + self->reference_counts[existing_slot]++; + + // Check if this is a full-width character by looking for a second slot + // with the same codepoint right after this one, wrapping at the end. + uint16_t next_slot = (existing_slot + 1) % self->max_glyphs; + bool cached_is_full_width = next_slot != existing_slot && self->codepoints[next_slot] == codepoint; + + if (cached_is_full_width) { + self->reference_counts[next_slot]++; + } + + if (is_full_width != NULL) { + *is_full_width = cached_is_full_width; + } + + return existing_slot; + } + + // First check if the glyph is full-width before allocating slots + // This way we know if we need one or two slots before committing + bool is_full_width_glyph = false; + + // Check if file is already open + if (!self->file_is_open) { + + return -1; + } + + // Find character ID from codepoint + int32_t char_id = get_char_id(self, codepoint); + if (char_id < 0 || (uint32_t)char_id >= self->max_cid) { + return -1; // Invalid character + } + + // Get glyph offset from location table + uint32_t glyph_offset = 0; + uint32_t loca_offset = self->loca_table_offset + char_id * + (self->header.index_to_loc_format == 1 ? 4 : 2); + + if (!seek_file(&self->file, loca_offset)) { + return -1; + } + + if (self->header.index_to_loc_format == 1) { + // 4-byte offset + uint8_t offset_buf[4]; + if (!read_file(&self->file, offset_buf, sizeof(offset_buf))) { + return -1; + } + glyph_offset = offset_buf[0] | (offset_buf[1] << 8) | + (offset_buf[2] << 16) | (offset_buf[3] << 24); + } else { + // 2-byte offset + uint8_t offset_buf[2]; + if (!read_file(&self->file, offset_buf, sizeof(offset_buf))) { + return -1; + } + glyph_offset = offset_buf[0] | (offset_buf[1] << 8); + } + // Seek to glyph data + if (!seek_file(&self->file, self->glyf_table_offset + glyph_offset)) { + return -1; + } + + // Read glyph header fields to determine width + uint32_t glyph_advance; + int32_t bbox_x, bbox_y; + uint32_t bbox_w, bbox_h; + + // Initialize bit reading state + uint8_t byte_val = 0; + uint8_t remaining_bits = 0; + + // Use the helper function to read glyph dimensions + if (!read_glyph_dimensions(&self->file, self, &glyph_advance, &bbox_x, &bbox_y, &bbox_w, &bbox_h, &byte_val, &remaining_bits)) { + return -1; + } + + // Check if the glyph is full-width based on its advance width + // Full-width characters typically have an advance width close to or greater than the font height + is_full_width_glyph = glyph_advance > self->half_width_px; + + // Now we know if we need one or two slots + uint16_t slots_needed = is_full_width_glyph ? 2 : 1; + + // Find an appropriate slot (or consecutive slots for full-width) + uint16_t slot = UINT16_MAX; + + if (slots_needed == 1) { + // For regular width, find a free slot starting at codepoint's position + slot = find_free_slot(self, codepoint); + } else { + // For full-width, find two consecutive free slots + for (uint16_t i = 0; i < self->max_glyphs - 1; i++) { + if (self->codepoints[i] == LVFONTIO_INVALID_CODEPOINT && + self->reference_counts[i] == 0 && + self->codepoints[i + 1] == LVFONTIO_INVALID_CODEPOINT && + self->reference_counts[i + 1] == 0) { + slot = i; + break; + } + } + } + + // Check if we found appropriate slot(s) + if (slot == UINT16_MAX) { + return -1; // No slots available + } + + // Load glyph into the slot + if (!load_glyph_bitmap(&self->file, self, codepoint, slot, glyph_advance, + bbox_x, bbox_y, bbox_w, bbox_h, &byte_val, &remaining_bits)) { + return -1; // Failed to load glyph + } + + // For full-width characters, mark both slots with the same codepoint + if (is_full_width_glyph && slot + 1 < self->max_glyphs) { + self->codepoints[slot + 1] = codepoint; + self->reference_counts[slot + 1] = 1; + } + + if (is_full_width != NULL) { + *is_full_width = is_full_width_glyph; + } + + return slot; +} + +void common_hal_lvfontio_ondiskfont_release_glyph(lvfontio_ondiskfont_t *self, uint32_t slot) { + if (slot >= self->max_glyphs) { + return; + } + + if (self->reference_counts[slot] > 0) { + self->reference_counts[slot]--; + } +} + +static int16_t find_codepoint_slot(lvfontio_ondiskfont_t *self, uint32_t codepoint) { + size_t offset = codepoint % self->max_glyphs; + for (uint16_t i = 0; i < self->max_glyphs; i++) { + int16_t slot = (i + offset) % self->max_glyphs; + if (self->codepoints[slot] == codepoint) { + // If this is the second slot of a full-width glyph pair, return the + // first slot so callers always get a canonical index. + if (slot > 0 && self->codepoints[slot - 1] == codepoint) { + return slot - 1; + } + return slot; + } + } + return -1; +} + +static bool slot_has_active_full_width_partner(lvfontio_ondiskfont_t *self, uint16_t slot) { + uint32_t codepoint = self->codepoints[slot]; + if (codepoint == LVFONTIO_INVALID_CODEPOINT) { + return false; + } + + // Don't evict one half of a full-width pair while the other half is still in use. + uint16_t prev_slot = (slot + self->max_glyphs - 1) % self->max_glyphs; + uint16_t next_slot = (slot + 1) % self->max_glyphs; + + if (self->codepoints[prev_slot] == codepoint && self->reference_counts[prev_slot] > 0) { + return true; + } + if (self->codepoints[next_slot] == codepoint && self->reference_counts[next_slot] > 0) { + return true; + } + + return false; +} + +static uint16_t find_free_slot(lvfontio_ondiskfont_t *self, uint32_t codepoint) { + size_t offset = codepoint % self->max_glyphs; + + // First look for completely unused slots, starting at the offset + for (uint16_t i = 0; i < self->max_glyphs; i++) { + int16_t slot = (i + offset) % self->max_glyphs; + if (self->codepoints[slot] == LVFONTIO_INVALID_CODEPOINT && self->reference_counts[slot] == 0) { + return slot; + } + } + + // If none found, look for slots with zero reference count, starting at the offset. + // Avoid reusing one half of an active full-width glyph pair. + for (uint16_t i = 0; i < self->max_glyphs; i++) { + int16_t slot = (i + offset) % self->max_glyphs; + if (self->reference_counts[slot] == 0 && !slot_has_active_full_width_partner(self, slot)) { + return slot; + } + } + + // No slots available + return UINT16_MAX; +} + +static bool read_glyph_dimensions(supervisor_vfs_file_t *file, lvfontio_ondiskfont_t *self, + uint32_t *advance_width, int32_t *bbox_x, int32_t *bbox_y, + uint32_t *bbox_w, uint32_t *bbox_h, + uint8_t *byte_val, uint8_t *remaining_bits) { + uint32_t temp_value; + + // Read glyph_advance + if (!read_bits(file, self->header.glyph_advance_bits, byte_val, remaining_bits, &temp_value)) { + return false; + } + *advance_width = temp_value; + + // Read bbox_x (signed) + if (!read_bits(file, self->header.glyph_bbox_xy_bits, byte_val, remaining_bits, &temp_value)) { + return false; + } + // Convert to signed value if needed + if (temp_value & (1 << (self->header.glyph_bbox_xy_bits - 1))) { + *bbox_x = temp_value - (1 << self->header.glyph_bbox_xy_bits); + } else { + *bbox_x = temp_value; + } + + // Read bbox_y (signed) + if (!read_bits(file, self->header.glyph_bbox_xy_bits, byte_val, remaining_bits, &temp_value)) { + return false; + } + // Convert to signed value if needed + if (temp_value & (1 << (self->header.glyph_bbox_xy_bits - 1))) { + *bbox_y = temp_value - (1 << self->header.glyph_bbox_xy_bits); + } else { + *bbox_y = temp_value; + } + + // Read bbox_w + if (!read_bits(file, self->header.glyph_bbox_wh_bits, byte_val, remaining_bits, &temp_value)) { + return false; + } + *bbox_w = temp_value; + + // Read bbox_h + if (!read_bits(file, self->header.glyph_bbox_wh_bits, byte_val, remaining_bits, &temp_value)) { + return false; + } + *bbox_h = temp_value; + + return true; +} + +static bool read_bits(supervisor_vfs_file_t *file, size_t num_bits, uint8_t *byte_val, uint8_t *remaining_bits, uint32_t *result) { + uint32_t value = 0; + // Bits will be lost when num_bits > 32. However, this is good for skipping bits. + size_t bits_needed = num_bits; + + while (bits_needed > 0) { + // If no bits remaining, read a new byte + if (*remaining_bits == 0) { + if (!read_file(file, byte_val, 1)) { + return false; + } + *remaining_bits = 8; + } + + // Calculate how many bits to take from current byte + uint8_t bits_to_take = (*remaining_bits < bits_needed) ? *remaining_bits : bits_needed; + value = (value << bits_to_take) | (*byte_val >> (8 - bits_to_take)); + + // Update state + *remaining_bits -= bits_to_take; + bits_needed -= bits_to_take; + + // Shift byte for next read + *byte_val <<= bits_to_take; + *byte_val &= 0xFF; + } + + if (result != NULL) { + *result = value; + } + return true; +} diff --git a/shared-module/lvfontio/OnDiskFont.h b/shared-module/lvfontio/OnDiskFont.h new file mode 100644 index 00000000000..ccac850ec10 --- /dev/null +++ b/shared-module/lvfontio/OnDiskFont.h @@ -0,0 +1,75 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" +#include "shared-module/displayio/Bitmap.h" + +#include "supervisor/filesystem.h" + +#define LVFONTIO_INVALID_CODEPOINT 0xFFFFFFFF + +// LV Font header information +typedef struct { + // Font size and metrics + uint16_t font_size; + uint16_t ascent; + uint16_t default_advance_width; + + // Encoding formats + uint8_t index_to_loc_format; + uint8_t bits_per_pixel; + uint8_t glyph_bbox_xy_bits; + uint8_t glyph_bbox_wh_bits; + uint8_t glyph_advance_bits; + + // Calculated values + uint8_t glyph_header_bits; + uint8_t glyph_header_bytes; +} lvfontio_header_t; + +// Mapping of codepoint ranges to glyph IDs +typedef struct { + uint32_t range_start; // Start of codepoint range + uint32_t range_end; // End of codepoint range (exclusive) + uint16_t glyph_offset; // Offset to apply to codepoint + uint8_t format_type; // Format type: 0=sparse mapping, 2=range to range, 3=direct mapping + uint16_t entries_count; // Number of entries in sparse data + uint32_t data_offset; // File offset to the cmap data +} lvfontio_cmap_range_t; + +typedef struct { + mp_obj_base_t base; + // Bitmap containing cached glyphs + displayio_bitmap_t *bitmap; + // Source of font file path (either a const char* or a copied string) + const char *file_path; + // Array mapping glyph indices to codepoints + uint32_t *codepoints; + // Array of reference counts for each glyph slot + uint16_t *reference_counts; // Use uint16_t to handle higher reference counts + // Maximum number of glyphs to cache at once + uint16_t max_glyphs; + // Flag indicating whether to use m_malloc (true) or port_malloc (false) + bool use_gc_allocator; + uint8_t half_width_px; + + supervisor_vfs_file_t file; + bool file_is_open; + + // Font metrics information loaded from file + lvfontio_header_t header; + + // CMAP information + lvfontio_cmap_range_t *cmap_ranges; + uint16_t cmap_range_count; + + // Offsets for tables in the file + uint32_t loca_table_offset; + uint32_t glyf_table_offset; + uint32_t max_cid; +} lvfontio_ondiskfont_t; diff --git a/shared-module/lvfontio/__init__.c b/shared-module/lvfontio/__init__.c new file mode 100644 index 00000000000..d0eee6d0a52 --- /dev/null +++ b/shared-module/lvfontio/__init__.c @@ -0,0 +1,5 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2024 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT diff --git a/shared-module/max3421e/Max3421E.c b/shared-module/max3421e/Max3421E.c index 4946e4e7d8d..e80847f6a35 100644 --- a/shared-module/max3421e/Max3421E.c +++ b/shared-module/max3421e/Max3421E.c @@ -46,7 +46,18 @@ void common_hal_max3421e_max3421e_construct(max3421e_max3421e_obj_t *self, common_hal_digitalio_digitalinout_construct(&self->irq, irq); - common_hal_max3421e_max3421e_init_irq(self); + // init_irq() can raise, for example on an irq pin without an external + // interrupt. bus is still NULL, so the object reads as deinited and its + // finaliser won't release the pins: release them here. + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + common_hal_max3421e_max3421e_init_irq(self); + nlr_pop(); + } else { + common_hal_digitalio_digitalinout_deinit(&self->chip_select); + common_hal_digitalio_digitalinout_deinit(&self->irq); + nlr_jump(nlr.ret_val); + } self->bus = spi; self->baudrate = baudrate; @@ -83,7 +94,7 @@ void common_hal_max3421e_max3421e_deinit(max3421e_max3421e_obj_t *self) { // anyway. Don't run background tasks because this function is used by // tuh_task() which is run as a background task. #if CFG_TUSB_OS == OPT_OS_NONE -void osal_task_delay(uint32_t msec) { +void tusb_time_delay_ms_api(uint32_t msec) { uint32_t end_time = common_hal_time_monotonic_ms() + msec; while (common_hal_time_monotonic_ms() < end_time) { if (tuh_callback.prev != NULL) { @@ -122,6 +133,25 @@ void max3421e_interrupt_handler(max3421e_max3421e_obj_t *arg) { common_hal_max3421e_max3421e_irq_enabled(self, false); } +// tuh_max3421_spi_cs_api() can't wait for a bus that other code holds (Python +// code, a display refresh or an SD card read can all run background tasks while +// holding it), so it skips the transfer. TinyUSB then acts on register values it +// never read, and a dropped transfer start leaves busy_lock set with no +// transfer-done interrupt to clear it, so the host stalls until reset. +// usb_background() asks this first and runs tuh_task() later instead. +bool max3421e_spi_busy(void) { + max3421e_max3421e_obj_t *self = _active; + if (self == NULL || common_hal_max3421e_max3421e_deinited(self) || + common_hal_busio_spi_deinited(self->bus)) { + return false; + } + if (!common_hal_busio_spi_try_lock(self->bus)) { + return true; + } + common_hal_busio_spi_unlock(self->bus); + return false; +} + // API to control MAX3421 SPI CS void tuh_max3421_spi_cs_api(uint8_t rhport, bool active) { max3421e_max3421e_obj_t *self = _active; diff --git a/shared-module/max3421e/Max3421E.h b/shared-module/max3421e/Max3421E.h index 5710451a57a..dae6a7b3fb4 100644 --- a/shared-module/max3421e/Max3421E.h +++ b/shared-module/max3421e/Max3421E.h @@ -34,3 +34,7 @@ void common_hal_max3421e_max3421e_irq_enabled(max3421e_max3421e_obj_t *self, boo // Queue up the actual interrupt handler for when the SPI bus is free. void max3421e_interrupt_handler(max3421e_max3421e_obj_t *self); + +// True when something else holds the SPI bus the MAX3421E shares, so the host +// task must wait: its transfers would be dropped. +bool max3421e_spi_busy(void); diff --git a/shared-module/memorymonitor/AllocationSize.c b/shared-module/memorymonitor/AllocationSize.c index f68401a252f..8c73f15db7e 100644 --- a/shared-module/memorymonitor/AllocationSize.c +++ b/shared-module/memorymonitor/AllocationSize.c @@ -60,6 +60,9 @@ void memorymonitor_allocationsizes_track_allocation(size_t block_count) { power_of_two++; block_count >>= 1; } + if (power_of_two >= ALLOCATION_SIZE_BUCKETS) { + power_of_two = ALLOCATION_SIZE_BUCKETS - 1; + } while (as != NULL) { as->buckets[power_of_two]++; as = as->next; diff --git a/shared-module/msgpack/__init__.c b/shared-module/msgpack/__init__.c index a98fb02de39..71f1b7b1983 100644 --- a/shared-module/msgpack/__init__.c +++ b/shared-module/msgpack/__init__.c @@ -9,7 +9,9 @@ #include "py/obj.h" #include "py/binary.h" +#include "py/cstack.h" #include "py/objarray.h" +#include "py/objint.h" #include "py/objlist.h" #include "py/objstringio.h" #include "py/parsenum.h" @@ -174,19 +176,51 @@ static mp_map_elem_t *dict_iter_next(mp_obj_dict_t *dict, size_t *cur) { return NULL; } -static void pack_int(msgpack_stream_t *s, int32_t x) { - if (x > -32 && x < 128) { - write1(s, x); - } else if ((int8_t)x == x) { - write1(s, 0xd0); - write1(s, x); - } else if ((int16_t)x == x) { - write1(s, 0xd1); - write2(s, x); - } else { - write1(s, 0xd2); - write4(s, x); +// Write x in the shortest format that holds it: unsigned formats for values >= 0, signed formats +// for negative values. Return false, having written nothing, if x does not fit in 64 bits. +static bool pack_int(msgpack_stream_t *s, mp_obj_t x) { + #if MICROPY_LONGINT_IMPL != MICROPY_LONGINT_IMPL_NONE + if (!mp_obj_is_small_int(x) && MP_OBJ_SMALL_INT_VALUE(mp_obj_int_bit_length_impl(x)) > 64) { + return false; + } + #endif + + bool negative = mp_obj_int_sign(x) < 0; + uint8_t buf[8]; + mp_obj_int_to_bytes(x, sizeof(buf), buf, true, negative, false); + // Below -2**63 the truncated value loses its sign bit. + if (negative && !(buf[0] & 0x80)) { + return false; + } + + // Skip the high bytes that only repeat the sign. A negative value keeps its top bit set. + uint8_t fill = negative ? 0xff : 0; + size_t skip = 0; + while (skip < sizeof(buf) - 1 && buf[skip] == fill) { + skip++; + } + if (negative && !(buf[skip] & 0x80)) { + skip--; + } + size_t needed = sizeof(buf) - skip; + + uint8_t low = buf[sizeof(buf) - 1]; + if (needed == 1 && (negative ? low >= 0xe0 : low < 0x80)) { + // positive or negative fixint + write1(s, low); + return true; } + + // Both families have consecutive codes for 8, 16, 32 and 64 bits. + uint8_t code = negative ? 0xd0 : 0xcc; + size_t len = 1; + while (len < needed) { + len *= 2; + code++; + } + write1(s, code); + write(s, buf + sizeof(buf) - len, len); + return true; } static void pack_bin(msgpack_stream_t *s, const uint8_t *data, size_t len) { @@ -254,10 +288,9 @@ static void pack_dict(msgpack_stream_t *s, size_t len) { } static void pack(mp_obj_t obj, msgpack_stream_t *s, mp_obj_t default_handler) { - if (mp_obj_is_small_int(obj)) { - // int - int32_t x = MP_OBJ_SMALL_INT_VALUE(obj); - pack_int(s, x); + mp_cstack_check(); + if (mp_obj_is_int(obj) && pack_int(s, obj)) { + // int that fits in 64 bits; a larger one falls through to default_handler } else if (mp_obj_is_str(obj)) { // string size_t len; @@ -293,11 +326,11 @@ 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; + union Float { float f; uint32_t u; }; union Float data; - data.f = mp_obj_float_get(obj); + data.f = (float)mp_obj_float_get(obj); write1(s, 0xca); write4(s, data.u); } else if (obj == mp_const_none) { @@ -326,7 +359,14 @@ static void pack(mp_obj_t obj, msgpack_stream_t *s, mp_obj_t default_handler) { static mp_obj_t unpack(msgpack_stream_t *s, mp_obj_t ext_hook, bool use_list); +static void check_container_size(size_t count, size_t elem_size, qstr name) { + if (count > SIZE_MAX / elem_size) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("%q too long"), name); + } +} + static mp_obj_t unpack_array_elements(msgpack_stream_t *s, size_t size, mp_obj_t ext_hook, bool use_list) { + check_container_size(size, sizeof(mp_obj_t), MP_QSTR_array); if (use_list) { mp_obj_list_t *t = MP_OBJ_TO_PTR(mp_obj_new_list(size, NULL)); for (size_t i = 0; i < size; i++) { @@ -372,6 +412,7 @@ static mp_obj_t unpack_ext(msgpack_stream_t *s, size_t size, mp_obj_t ext_hook) } static mp_obj_t unpack(msgpack_stream_t *s, mp_obj_t ext_hook, bool use_list) { + mp_cstack_check(); uint8_t code = read1(s); if (((code & 0b10000000) == 0) || ((code & 0b11100000) == 0b11100000)) { // int @@ -394,7 +435,9 @@ static mp_obj_t unpack(msgpack_stream_t *s, mp_obj_t ext_hook, bool use_list) { size_t len = code & 0b1111; mp_obj_dict_t *d = MP_OBJ_TO_PTR(mp_obj_new_dict(len)); for (size_t i = 0; i < len; i++) { - mp_obj_dict_store(d, unpack(s, ext_hook, use_list), unpack(s, ext_hook, use_list)); + mp_obj_t key = unpack(s, ext_hook, use_list); + mp_obj_t value = unpack(s, ext_hook, use_list); + mp_obj_dict_store(d, key, value); } return MP_OBJ_FROM_PTR(d); } @@ -429,12 +472,12 @@ static mp_obj_t unpack(msgpack_stream_t *s, mp_obj_t ext_hook, bool use_list) { return mp_obj_new_int_from_ll((int64_t)read8(s)); case 0xca: { // float union Float { - mp_float_t f; + float f; uint32_t u; }; union Float data; data.u = read4(s); - return mp_obj_new_float(data.f); + return mp_obj_new_float((mp_float_t)data.f); } case 0xcb: { // double union Double { @@ -460,9 +503,12 @@ static mp_obj_t unpack(msgpack_stream_t *s, mp_obj_t ext_hook, bool use_list) { case 0xdf: { // map 16 & 32 size_t len = read_size(s, code - 0xde + 1); + check_container_size(len, sizeof(mp_map_elem_t), MP_QSTR_map); mp_obj_dict_t *d = MP_OBJ_TO_PTR(mp_obj_new_dict(len)); for (size_t i = 0; i < len; i++) { - mp_obj_dict_store(d, unpack(s, ext_hook, use_list), unpack(s, ext_hook, use_list)); + mp_obj_t key = unpack(s, ext_hook, use_list); + mp_obj_t value = unpack(s, ext_hook, use_list); + mp_obj_dict_store(d, key, value); } return MP_OBJ_FROM_PTR(d); } diff --git a/shared-module/os/__init__.c b/shared-module/os/__init__.c index 6afe64dd62d..c62119fcf18 100644 --- a/shared-module/os/__init__.c +++ b/shared-module/os/__init__.c @@ -6,6 +6,7 @@ // // SPDX-License-Identifier: MIT +#include #include #include "extmod/vfs.h" @@ -16,6 +17,16 @@ #include "py/runtime.h" #include "shared-bindings/os/__init__.h" +#if CIRCUITPY_SETTINGS_TOML +#include "supervisor/shared/settings.h" +#endif + +#if CIRCUITPY_WIFI +#include "shared-bindings/wifi/__init__.h" +#elif CIRCUITPY_MII +#include "shared-bindings/mii/__init__.h" +#endif + // This provides all VFS related OS functions so that ports can share the code // as needed. @@ -63,10 +74,86 @@ 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); } +const char *common_hal_os_path_abspath(const char *path) { + const char *cwd; + if (path[0] == '/') { + cwd = ""; + } else { + cwd = MP_STATE_VM(cwd_path); + if (cwd == NULL) { + char *new_cwd = m_malloc_without_collect(2); + strcpy(new_cwd, "/"); + MP_STATE_VM(cwd_path) = new_cwd; + cwd = new_cwd; + } + } + + // Store the current output length for previous components so we can rewind to before them. + char *full_path = m_malloc_without_collect(strlen(cwd) + strlen(path) + 2); + size_t full_path_len = 0; + memcpy(full_path, cwd, strlen(cwd)); + full_path_len += strlen(cwd); + if (full_path_len > 0 && full_path[full_path_len - 1] != '/') { + full_path[full_path_len++] = '/'; + } + memcpy(full_path + full_path_len, path, strlen(path) + 1); + + // Scan to see if the path has any `..` in it and return the same string if it doesn't + bool found_dot_dot = false; + size_t slash_count = 0; + for (size_t i = 0; i < strlen(full_path); i++) { + if (full_path[i] == '/') { + slash_count++; + } + if (i + 2 < strlen(full_path) && full_path[i] == '/' && full_path[i + 1] == '.' && full_path[i + 2] == '.' && (i + 3 == strlen(full_path) || full_path[i + 3] == '/')) { + found_dot_dot = true; + } + } + if (!found_dot_dot) { + return full_path; + } + + size_t slashes[slash_count]; + size_t output_len = 0; + size_t component_len = 0; + slash_count = 0; + + // Remove `..` and `.` + size_t original_len = strlen(full_path); + for (size_t i = 0; i <= original_len; i++) { + full_path[output_len++] = full_path[i]; + // Treat the final nul character as a slash. + if (full_path[i] == '/' || full_path[i] == '\0') { + if (component_len == 1 && full_path[i - 1] == '.') { + // Remove the dot + output_len = slashes[slash_count - 1]; + } else if (component_len == 2 && full_path[i - 1] == '.' && full_path[i - 2] == '.') { + // Remove the double dot and the previous component if it exists. + // Never rewind past the root: if the root is the only recorded + // boundary (slash_count == 1), ".." at the root is a no-op instead of + // underflowing slash_count to SIZE_MAX and reading slashes[SIZE_MAX] + // out of bounds (matches POSIX "cd .. from / stays at /" semantics). + if (slash_count > 1) { + slash_count--; + } + output_len = slashes[slash_count - 1]; + } else { + slashes[slash_count] = output_len; + slash_count++; + } + component_len = 0; + } else { + component_len++; + } + } + full_path[output_len] = '\0'; + return full_path; +} + void common_hal_os_chdir(const char *path) { + const char *new_cwd = common_hal_os_path_abspath(path); mp_obj_t path_out; - mp_vfs_mount_t *vfs = lookup_dir_path(path, &path_out); - MP_STATE_VM(vfs_cur) = vfs; + mp_vfs_mount_t *vfs = lookup_dir_path(new_cwd, &path_out); if (vfs == MP_VFS_ROOT) { // If we change to the root dir and a VFS is mounted at the root then // we must change that VFS's current dir to the root dir so that any @@ -81,30 +168,35 @@ void common_hal_os_chdir(const char *path) { } else { mp_vfs_proxy_call(vfs, MP_QSTR_chdir, 1, &path_out); } + MP_STATE_VM(cwd_path) = new_cwd; + MP_STATE_VM(vfs_cur) = vfs; } mp_obj_t common_hal_os_getcwd(void) { - return mp_vfs_getcwd(); + const char *cwd = MP_STATE_VM(cwd_path); + if (cwd == NULL) { + return MP_OBJ_NEW_QSTR(MP_QSTR__slash_); + } + return mp_obj_new_str_of_type(&mp_type_str, (const byte *)cwd, strlen(cwd)); } mp_obj_t common_hal_os_listdir(const char *path) { + const char *abspath = common_hal_os_path_abspath(path); mp_obj_t path_out; - mp_vfs_mount_t *vfs = lookup_dir_path(path, &path_out); - - mp_vfs_ilistdir_it_t iter; - mp_obj_t iter_obj = MP_OBJ_FROM_PTR(&iter); - + mp_vfs_mount_t *vfs = lookup_dir_path(abspath, &path_out); if (vfs == MP_VFS_ROOT) { - // list the root directory - iter.base.type = &mp_type_polymorph_iter; - iter.iternext = mp_vfs_ilistdir_it_iternext; - iter.cur.vfs = MP_STATE_VM(vfs_mount_table); - iter.is_str = true; - iter.is_iter = false; - } else { - iter_obj = mp_vfs_proxy_call(vfs, MP_QSTR_ilistdir, 1, &path_out); + vfs = MP_STATE_VM(vfs_mount_table); + while (vfs != NULL) { + if (vfs->len == 1) { + break; + } + vfs = vfs->next; + } + path_out = MP_OBJ_NEW_QSTR(MP_QSTR__slash_); } + mp_obj_t iter_obj = mp_vfs_proxy_call(vfs, MP_QSTR_ilistdir, 1, &path_out); + mp_obj_t dir_list = mp_obj_new_list(0, NULL); mp_obj_t next; while ((next = mp_iternext(iter_obj)) != MP_OBJ_STOP_ITERATION) { @@ -116,8 +208,9 @@ mp_obj_t common_hal_os_listdir(const char *path) { } void common_hal_os_mkdir(const char *path) { + const char *abspath = common_hal_os_path_abspath(path); mp_obj_t path_out; - mp_vfs_mount_t *vfs = lookup_dir_path(path, &path_out); + mp_vfs_mount_t *vfs = lookup_dir_path(abspath, &path_out); if (vfs == MP_VFS_ROOT || (vfs != MP_VFS_NONE && !strcmp(mp_obj_str_get_str(path_out), "/"))) { mp_raise_OSError(MP_EEXIST); } @@ -125,8 +218,9 @@ void common_hal_os_mkdir(const char *path) { } void common_hal_os_remove(const char *path) { + const char *abspath = common_hal_os_path_abspath(path); mp_obj_t path_out; - mp_vfs_mount_t *vfs = lookup_path(path, &path_out); + mp_vfs_mount_t *vfs = lookup_path(abspath, &path_out); mp_vfs_proxy_call(vfs, MP_QSTR_remove, 1, &path_out); } @@ -142,14 +236,16 @@ void common_hal_os_rename(const char *old_path, const char *new_path) { } void common_hal_os_rmdir(const char *path) { + const char *abspath = common_hal_os_path_abspath(path); mp_obj_t path_out; - mp_vfs_mount_t *vfs = lookup_dir_path(path, &path_out); + mp_vfs_mount_t *vfs = lookup_dir_path(abspath, &path_out); mp_vfs_proxy_call(vfs, MP_QSTR_rmdir, 1, &path_out); } mp_obj_t common_hal_os_stat(const char *path) { + const char *abspath = common_hal_os_path_abspath(path); mp_obj_t path_out; - mp_vfs_mount_t *vfs = lookup_path(path, &path_out); + mp_vfs_mount_t *vfs = lookup_path(abspath, &path_out); if (vfs == MP_VFS_ROOT) { mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(10, NULL)); t->items[0] = MP_OBJ_NEW_SMALL_INT(MP_S_IFDIR); // st_mode @@ -162,8 +258,9 @@ mp_obj_t common_hal_os_stat(const char *path) { } mp_obj_t common_hal_os_statvfs(const char *path) { + const char *abspath = common_hal_os_path_abspath(path); mp_obj_t path_out; - mp_vfs_mount_t *vfs = lookup_path(path, &path_out); + mp_vfs_mount_t *vfs = lookup_path(abspath, &path_out); if (vfs == MP_VFS_ROOT) { // statvfs called on the root directory, see if there's anything mounted there for (vfs = MP_STATE_VM(vfs_mount_table); vfs != NULL; vfs = vfs->next) { @@ -194,8 +291,61 @@ mp_obj_t common_hal_os_statvfs(const char *path) { } void common_hal_os_utime(const char *path, mp_obj_t times) { + const char *abspath = common_hal_os_path_abspath(path); mp_obj_t args[2]; - mp_vfs_mount_t *vfs = lookup_path(path, &args[0]); + mp_vfs_mount_t *vfs = lookup_path(abspath, &args[0]); args[1] = times; mp_vfs_proxy_call(vfs, MP_QSTR_utime, 2, args); } + +#if CIRCUITPY_SETTINGS_TOML +mp_obj_t common_hal_os_getenv(const char *key, mp_obj_t default_) { + vstr_t vstr; + vstr_init(&vstr, 64); + + settings_err_t result = settings_get_raw_vstr(key, &vstr); + if (result == SETTINGS_OK) { + return mp_obj_new_str_from_vstr(&vstr); + } + return default_; +} +#endif + +MP_REGISTER_ROOT_POINTER(const char *cwd_path); + +#if CIRCUITPY_WIFI || CIRCUITPY_MII +void common_hal_os_get_nodename(char *buf, size_t buf_size) { + if (buf_size == 0) { + return; + } + buf[0] = '\0'; + + #if CIRCUITPY_WIFI + if (wifi_is_initialized()) { + strlcpy(buf, wifi_get_hostname_raw(), buf_size); + } else { + // Report the hostname common_hal_wifi_init() will set. + #if CIRCUITPY_SETTINGS_TOML + if (settings_get_str("CIRCUITPY_WIFI_HOSTNAME", buf, buf_size) != SETTINGS_OK) { + buf[0] = '\0'; + } + #endif + if (buf[0] == '\0') { + wifi_get_default_hostname(buf, buf_size); + } + } + #elif CIRCUITPY_MII + const char *hostname = mii_get_hostname_raw(); + if (hostname[0] != '\0') { + strlcpy(buf, hostname, buf_size); + } else { + // Report the hostname the Ethernet constructor will set. + mii_get_default_hostname(buf, buf_size); + } + #endif + + if (buf[0] == '\0') { + strlcpy(buf, MICROPY_HW_MCU_NAME, buf_size); + } +} +#endif diff --git a/shared-module/os/__init__.h b/shared-module/os/__init__.h index be9c077b200..830f7629509 100644 --- a/shared-module/os/__init__.h +++ b/shared-module/os/__init__.h @@ -6,23 +6,5 @@ #pragma once -typedef enum { - GETENV_OK = 0, - GETENV_ERR_OPEN, - GETENV_ERR_UNICODE, - GETENV_ERR_LENGTH, - GETENV_ERR_NOT_FOUND, - GETENV_ERR_UNEXPECTED = 0xff00, // logical or'd with the byte value -} os_getenv_err_t; - -// Allocation free version that returns the full length of the value. -// If it fits, the return value is 0-terminated. The passed in buffer -// may be modified even if an error is returned. Allocation free. -// An error that is not 'open' or 'not found' is printed on the repl. -os_getenv_err_t common_hal_os_getenv_str(const char *key, char *value, size_t value_len); - -// Returns GETENV_OK and sets value to the read value. Returns -// GETENV_ERR_... if the value was not numeric. allocation-free. -// If any error code is returned, value is guaranteed not modified -// An error that is not 'open' or 'not found' is printed on the repl. -os_getenv_err_t common_hal_os_getenv_int(const char *key, mp_int_t *value); +// Not made available to the VM but used by other modules to normalize paths. +const char *common_hal_os_path_abspath(const char *path); diff --git a/shared-module/os/getenv.c b/shared-module/os/getenv.c deleted file mode 100644 index c7bfadf3418..00000000000 --- a/shared-module/os/getenv.c +++ /dev/null @@ -1,417 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2022 Scott Shawcroft for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -// These functions are separate from __init__.c so that os.getenv() can be -// tested in the unix "coverage" build, without bringing in "our" os module - -#include -#include -#include - -#include "shared-bindings/os/__init__.h" -#include "shared-module/os/__init__.h" - -#include "py/gc.h" -#include "py/misc.h" -#include "py/mpstate.h" -#include "py/mpprint.h" -#include "py/objstr.h" -#include "py/parsenum.h" -#include "py/runtime.h" -#include "supervisor/filesystem.h" - -#define GETENV_PATH "/settings.toml" - -#include "extmod/vfs.h" -#include "extmod/vfs_fat.h" - -#if CIRCUITPY_OS_GETENV -typedef FIL file_arg; -static bool open_file(const char *name, file_arg *active_file) { - #if defined(UNIX) - nlr_buf_t nlr; - if (nlr_push(&nlr) == 0) { - mp_obj_t file_obj = mp_call_function_2(MP_OBJ_FROM_PTR(&mp_builtin_open_obj), mp_obj_new_str(name, strlen(name)), MP_ROM_QSTR(MP_QSTR_rb)); - mp_arg_validate_type(file_obj, &mp_type_vfs_fat_fileio, MP_QSTR_file); - pyb_file_obj_t *file = MP_OBJ_TO_PTR(file_obj); - *active_file = file->fp; - nlr_pop(); - return true; - } else { - return false; - } - #else - fs_user_mount_t *fs_mount = filesystem_circuitpy(); - if (fs_mount == NULL) { - return false; - } - FATFS *fatfs = &fs_mount->fatfs; - FRESULT result = f_open(fatfs, active_file, name, FA_READ); - return result == FR_OK; - #endif -} -static void close_file(file_arg *active_file) { - // nothing -} -static bool is_eof(file_arg *active_file) { - return f_eof(active_file) || f_error(active_file); -} - -// Return 0 if there is no next character (EOF). -static uint8_t get_next_byte(FIL *active_file) { - uint8_t character = 0; - UINT quantity_read; - // If there's an error or quantity_read is 0, character will remain 0. - f_read(active_file, &character, 1, &quantity_read); - return character; -} -static void seek_eof(file_arg *active_file) { - f_lseek(active_file, f_size(active_file)); -} - -// For a fixed buffer, record the required size rather than throwing -static void vstr_add_byte_nonstd(vstr_t *vstr, byte b) { - if (!vstr->fixed_buf || vstr->alloc > vstr->len) { - vstr_add_byte(vstr, b); - } else { - vstr->len++; - } -} - -// For a fixed buffer, record the required size rather than throwing -static void vstr_add_char_nonstd(vstr_t *vstr, unichar c) { - size_t ulen = - (c < 0x80) ? 1 : - (c < 0x800) ? 2 : - (c < 0x10000) ? 3 : 4; - if (!vstr->fixed_buf || vstr->alloc > vstr->len + ulen) { - vstr_add_char(vstr, c); - } else { - vstr->len += ulen; - } -} - -static void next_line(file_arg *active_file) { - uint8_t character; - do { - character = get_next_byte(active_file); - } while (character != 0 && character != '\n'); -} - -// Discard whitespace, except for newlines, returning the next character after the whitespace. -// Return 0 if there is no next character (EOF). -static uint8_t consume_whitespace(file_arg *active_file) { - uint8_t character; - do { - character = get_next_byte(active_file); - } while (character != '\n' && character != 0 && unichar_isspace(character)); - return character; -} - -// Starting at the start of a new line, determines if the key matches the given -// key. -// -// If result is true, the key matches and file pointer is pointing just after the "=". -// If the result is false, the key does NOT match and the file pointer is -// pointing at the start of the next line, if any -static bool key_matches(file_arg *active_file, const char *key) { - uint8_t character; - character = consume_whitespace(active_file); - if (character == '[' || character == 0) { - seek_eof(active_file); - return false; - } - while (*key) { - if (character != *key++) { - // A character didn't match the key, so it's not a match - // If the non-matching char was not the end of the line, - // then consume the rest of the line - if (character != '\n') { - next_line(active_file); - } - return false; - } - character = get_next_byte(active_file); - } - // the next character could be whitespace; consume if necessary - if (unichar_isspace(character)) { - character = consume_whitespace(active_file); - } - // If we're not looking at the "=" then the key didn't match - if (character != '=') { - // A character didn't match the key, so it's not a match - // If the non-matching char was not the end of the line, - // then consume the rest of the line - if (character != '\n') { - next_line(active_file); - } - return false; - } - return true; -} - -static os_getenv_err_t read_unicode_escape(file_arg *active_file, int sz, vstr_t *buf) { - char hex_buf[sz + 1]; - for (int i = 0; i < sz; i++) { - hex_buf[i] = get_next_byte(active_file); - } - hex_buf[sz] = 0; - char *end; - unsigned long c = strtoul(hex_buf, &end, 16); - if (end != &hex_buf[sz]) { - return GETENV_ERR_UNEXPECTED | *end; - } - if (c >= 0x110000) { - return GETENV_ERR_UNICODE; - } - vstr_add_char_nonstd(buf, c); - return GETENV_OK; -} - -// Read a quoted string -static os_getenv_err_t read_string_value(file_arg *active_file, vstr_t *buf) { - while (true) { - int character = get_next_byte(active_file); - switch (character) { - case 0: - case '\n': - return GETENV_ERR_UNEXPECTED | character; - - case '"': - character = consume_whitespace(active_file); - switch (character) { - case '#': - next_line(active_file); - MP_FALLTHROUGH; - case 0: - case '\n': - return GETENV_OK; - default: - return GETENV_ERR_UNEXPECTED | character; - } - - case '\\': - character = get_next_byte(active_file); - switch (character) { - case 0: - case '\n': - return GETENV_ERR_UNEXPECTED | character; - case 'b': - character = '\b'; - break; - case 'r': - character = '\r'; - break; - case 'n': - character = '\n'; - break; - case 't': - character = '\t'; - break; - case 'v': - character = '\v'; - break; - case 'f': - character = '\f'; - break; - case 'U': - case 'u': { - int sz = (character == 'u') ? 4 : 8; - os_getenv_err_t res; - res = read_unicode_escape(active_file, sz, buf); - if (res != GETENV_OK) { - return res; - } - continue; - } - // default falls through, other escaped characters - // represent themselves - } - MP_FALLTHROUGH; - default: - vstr_add_byte_nonstd(buf, character); - } - } -} - -// Read a numeric value (non-quoted value) as a string -static os_getenv_err_t read_bare_value(file_arg *active_file, vstr_t *buf, int first_character) { - int character = first_character; - while (true) { - switch (character) { - case 0: - case '\n': - return GETENV_OK; - case '#': - next_line(active_file); - return GETENV_OK; - default: - vstr_add_byte_nonstd(buf, character); - } - character = get_next_byte(active_file); - } -} - -static mp_int_t read_value(file_arg *active_file, vstr_t *buf, bool *quoted) { - uint8_t character; - character = consume_whitespace(active_file); - *quoted = (character == '"'); - - if (*quoted) { - return read_string_value(active_file, buf); - } else { - return read_bare_value(active_file, buf, character); - } -} - -static os_getenv_err_t os_getenv_vstr(const char *path, const char *key, vstr_t *buf, bool *quoted) { - file_arg active_file; - if (!open_file(path, &active_file)) { - return GETENV_ERR_OPEN; - } - - os_getenv_err_t result = GETENV_ERR_NOT_FOUND; - while (!is_eof(&active_file)) { - if (key_matches(&active_file, key)) { - result = read_value(&active_file, buf, quoted); - break; - } - } - close_file(&active_file); - return result; -} - -static os_getenv_err_t os_getenv_buf_terminated(const char *key, char *value, size_t value_len, bool *quoted) { - vstr_t buf; - vstr_init_fixed_buf(&buf, value_len, value); - os_getenv_err_t result = os_getenv_vstr(GETENV_PATH, key, &buf, quoted); - - if (result == GETENV_OK) { - vstr_add_byte_nonstd(&buf, 0); - memcpy(value, buf.buf, MIN(buf.len, value_len)); - if (buf.len > value_len) { // this length includes trailing NUL - result = GETENV_ERR_LENGTH; - } - } - return result; -} - -static void print_dont_raise(const mp_obj_type_t *exc_type, mp_rom_error_text_t fmt, ...) { - va_list argptr; - va_start(argptr, fmt); - mp_vcprintf(&mp_plat_print, fmt, argptr); - mp_printf(&mp_plat_print, "\n"); - va_end(argptr); -} - -static void handle_getenv_error(os_getenv_err_t error, void (*handle)(const mp_obj_type_t *exc_type, mp_rom_error_text_t fmt, ...)) { - if (error == GETENV_OK) { - return; - } - if (error & GETENV_ERR_UNEXPECTED) { - byte character = (error & 0xff); - char buf[8]; - vstr_t vstr; - vstr_init_fixed_buf(&vstr, sizeof(buf), buf); - mp_print_t print = { .data = &vstr, .print_strn = (mp_print_strn_t)vstr_add_strn }; - - if (character) { - mp_str_print_quoted(&print, &character, 1, true); - } else { - mp_str_print_quoted(&print, (byte *)"EOF", 3, true); - } - handle(&mp_type_ValueError, MP_ERROR_TEXT("Invalid byte %.*s"), vstr.len, vstr.buf); - } else { - switch (error) { - case GETENV_ERR_OPEN: - handle(&mp_type_ValueError, MP_ERROR_TEXT("%S"), MP_ERROR_TEXT("File not found")); - break; - case GETENV_ERR_UNICODE: - handle(&mp_type_ValueError, MP_ERROR_TEXT("%S"), MP_ERROR_TEXT("Invalid unicode escape")); - break; - case GETENV_ERR_NOT_FOUND: - handle(&mp_type_ValueError, MP_ERROR_TEXT("%S"), MP_ERROR_TEXT("Key not found")); - break; - default: - handle(&mp_type_RuntimeError, MP_ERROR_TEXT("%S"), MP_ERROR_TEXT("Internal error")); - break; - } - } -} - -static void common_hal_os_getenv_showerr(const char *key, os_getenv_err_t result) { - if (result != GETENV_OK && result != GETENV_ERR_OPEN && result != GETENV_ERR_NOT_FOUND) { - mp_cprintf(&mp_plat_print, MP_ERROR_TEXT("An error occurred while retrieving '%s':\n"), key); - handle_getenv_error(result, print_dont_raise); - } -} - -static -os_getenv_err_t common_hal_os_getenv_str_inner(const char *key, char *value, size_t value_len) { - bool quoted; - os_getenv_err_t result = os_getenv_buf_terminated(key, value, value_len, "ed); - if (result == GETENV_OK && !quoted) { - result = GETENV_ERR_UNEXPECTED | value[0]; - } - return result; -} - -os_getenv_err_t common_hal_os_getenv_str(const char *key, char *value, size_t value_len) { - os_getenv_err_t result = common_hal_os_getenv_str_inner(key, value, value_len); - common_hal_os_getenv_showerr(key, result); - return result; -} - -mp_obj_t common_hal_os_getenv_path(const char *path, const char *key, mp_obj_t default_) { - vstr_t buf; - bool quoted; - - vstr_init(&buf, 64); - os_getenv_err_t result = os_getenv_vstr(path, key, &buf, "ed); - if (result == GETENV_ERR_NOT_FOUND || result == GETENV_ERR_OPEN) { - return default_; - } - handle_getenv_error(result, mp_raise_msg_varg); - - if (quoted) { - return mp_obj_new_str_from_vstr(&buf); - } else { - return mp_parse_num_integer(buf.buf, buf.len, 0, NULL); - } -} - -mp_obj_t common_hal_os_getenv(const char *key, mp_obj_t default_) { - return common_hal_os_getenv_path(GETENV_PATH, key, default_); -} - -static os_getenv_err_t common_hal_os_getenv_int_inner(const char *key, mp_int_t *value) { - char buf[16]; - bool quoted; - os_getenv_err_t result = os_getenv_buf_terminated(key, buf, sizeof(buf), "ed); - if (result != GETENV_OK) { - return result; - } - if (quoted) { - return GETENV_ERR_UNEXPECTED | '"'; - } - char *end; - long num = strtol(buf, &end, 0); - while (unichar_isspace(*end)) { - end++; - } - if (end == buf || *end) { // If the whole buffer was not consumed it's an error - return GETENV_ERR_UNEXPECTED | *end; - } - *value = (mp_int_t)num; - return GETENV_OK; -} - -os_getenv_err_t common_hal_os_getenv_int(const char *key, mp_int_t *value) { - os_getenv_err_t result = common_hal_os_getenv_int_inner(key, value); - common_hal_os_getenv_showerr(key, result); - return result; -} -#endif diff --git a/shared-module/picogame/Bitmap.h b/shared-module/picogame/Bitmap.h new file mode 100644 index 00000000000..887d904b203 --- /dev/null +++ b/shared-module/picogame/Bitmap.h @@ -0,0 +1,35 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT +// +// picogame: 2D game engine for the PicoPad and similar boards. +// Bitmap = an image atlas of one or more equal-size frames, arbitrary width/height. + +#pragma once + +#include +#include +#include "py/obj.h" + +enum { + PICOGAME_FMT_RGB565 = 0, // 2 bytes/pixel, values in display wire order + PICOGAME_FMT_PAL8 = 1, // 1 byte/pixel index into palette (wire-order RGB565) +}; + +typedef struct { + mp_obj_base_t base; + mp_obj_t data_obj; // keep the source buffer alive + mp_obj_t palette_obj; // keep the palette buffer alive (MP_OBJ_NULL for RGB565) + const uint8_t *data; // pixel data + const uint16_t *palette; // wire-order RGB565 entries (PAL8), else NULL + uint16_t width, height; // size of a single frame + uint16_t stride; // atlas width in pixels (>= width * frames for a horizontal atlas) + uint16_t transparent; // transparent key: palette index (PAL8) or wire color (RGB565) + uint16_t pal_entries; // palette length in entries (PAL8; 0 for RGB565). Informational: the + // blitter does NOT clamp - indices must be < this (see PAL8 blit contract). + uint8_t format; // PICOGAME_FMT_* + uint8_t frames; + bool has_transparent; +} picogame_bitmap_obj_t; diff --git a/shared-module/picogame/Canvas.c b/shared-module/picogame/Canvas.c new file mode 100644 index 00000000000..a7f058634f6 --- /dev/null +++ b/shared-module/picogame/Canvas.c @@ -0,0 +1,510 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +#include + +#include "shared-module/picogame/Canvas.h" +#include "shared-module/picogame/Bitmap.h" +#include "shared-module/picogame/__init__.h" +#if CIRCUITPY_FONTIO +#include "shared-module/fontio/BuiltinFont.h" +#endif +#include "shared-bindings/displayio/Bitmap.h" + +// Thin wrappers over the shared int32 accumulator (dx1,dy1,dx2,dy2 are contiguous int32 at the +// struct tail). See picogame_dirty_* in __init__.c. +void picogame_canvas_dirty_reset(picogame_canvas_obj_t *cv) { + picogame_dirty_reset(&cv->dx1); +} + +void picogame_canvas_dirty_union(picogame_canvas_obj_t *cv, int x1, int y1, int x2, int y2) { + picogame_dirty_union(&cv->dx1, x1, y1, x2, y2); +} + +bool picogame_canvas_take_dirty(picogame_canvas_obj_t *cv, int *x1, int *y1, int *x2, int *y2) { + return picogame_dirty_take(&cv->dx1, x1, y1, x2, y2); +} + +// Union a canvas-local rect (clamped to the surface) into the dirty rect (scene coords). +static void mark(picogame_canvas_obj_t *cv, int lx1, int ly1, int lx2, int ly2) { + if (lx1 < 0) { + lx1 = 0; + } + if (ly1 < 0) { + ly1 = 0; + } + if (lx2 > cv->w) { + lx2 = cv->w; + } + if (ly2 > cv->h) { + ly2 = cv->h; + } + if (lx1 >= lx2 || ly1 >= ly2) { + return; + } + picogame_dirty_union(&cv->dx1, cv->x + lx1, cv->y + ly1, cv->x + lx2, cv->y + ly2); +} + +// NOT inlined on purpose: the shape primitives call put() many times (circle = +// 8 calls/iteration). Inlining bloated them (circle was ~1.4 KB); a real call keeps +// them small. Shapes aren't the hot path (the sprite/tilemap blits don't use put). +static __attribute__((noinline)) void put(picogame_canvas_obj_t *cv, int x, int y, uint16_t c) { + // Unsigned compares also reject negative coordinates. + if ((unsigned)x < (unsigned)cv->w && (unsigned)y < (unsigned)cv->h) { + cv->data[y * cv->w + x] = c; + } +} + +// Fill `n` RGB565 pixels at `p` with `color`, word-filling two pixels per store (half the writes of +// a 16-bit loop); memset for the common 0 case. Handles a leading odd (2-byte-but-not-4-byte) address +// so it stays safe on Cortex-M0+ (RP2040), which faults on an unaligned 32-bit access - a StripDraw +// view's rows into the render strip can start on an odd pixel. This is the per-frame path for +// view.clear / Sky / HUD-bar / Fade fills, so the word-fill is worth it. +// Not in SRAM: every caller is in flash, and the long-branch veneer made it slower. +void picogame_fill565(uint16_t *p, int n, uint16_t color) { + if (n <= 0) { + return; + } + // Short spans (triangle rows, wall runs) skip the word path's setup. + if (n <= 4) { + do { + *p++ = color; + } while (--n); + return; + } + if (color == 0) { + memset(p, 0, (size_t)n * 2); + return; + } + if ((uintptr_t)p & 3) { // align to 4 bytes: one leading pixel + *p++ = color; + n--; + } + uint32_t w = (uint32_t)color | ((uint32_t)color << 16); + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wcast-align" + uint32_t *w32 = (uint32_t *)p; // now 4-byte aligned + #pragma GCC diagnostic pop + picogame_fill_words(w32, n >> 1, w); + if (n & 1) { // trailing odd pixel + p[n - 1] = color; + } +} + + +void picogame_canvas_clear(picogame_canvas_obj_t *cv, uint16_t color) { + picogame_fill565(cv->data, cv->w * cv->h, color); + mark(cv, 0, 0, cv->w, cv->h); +} + +void picogame_canvas_pixel(picogame_canvas_obj_t *cv, int x, int y, uint16_t color) { + put(cv, x, y, color); + mark(cv, x, y, x + 1, y + 1); +} + +void picogame_canvas_fill_rect(picogame_canvas_obj_t *cv, int x, int y, int w, int h, uint16_t color) { + int x2 = x + w, y2 = y + h; + int cx1 = x < 0 ? 0 : x, cy1 = y < 0 ? 0 : y; + int cx2 = x2 > cv->w ? cv->w : x2, cy2 = y2 > cv->h ? cv->h : y2; + for (int yy = cy1; yy < cy2; yy++) { + picogame_fill565(cv->data + yy * cv->w + cx1, cx2 - cx1, color); + } + mark(cv, x, y, x2, y2); +} + +void picogame_canvas_blit(picogame_canvas_obj_t *cv, picogame_bitmap_obj_t *bm, + int x, int y, int frame, bool flip_x, bool flip_y) { + // Composite a bitmap FRAME into the canvas buffer (honours the bitmap's transparent key). + // Reuses the sprite blit path, targeting the canvas's own RGB565 surface instead of a strip. + picogame_blit_bitmap(cv->data, cv->w, cv->h, 0, 0, bm, x, y, frame, flip_x, flip_y, false, NULL); + mark(cv, x, y, x + bm->width, y + bm->height); +} + +void picogame_canvas_rect(picogame_canvas_obj_t *cv, int x, int y, int w, int h, uint16_t color) { + picogame_canvas_fill_rect(cv, x, y, w, 1, color); + picogame_canvas_fill_rect(cv, x, y + h - 1, w, 1, color); + picogame_canvas_fill_rect(cv, x, y, 1, h, color); + picogame_canvas_fill_rect(cv, x + w - 1, y, 1, h, color); +} + +void picogame_canvas_line(picogame_canvas_obj_t *cv, int x0, int y0, int x1, int y1, uint16_t color) { + int dx = x1 - x0, dy = y1 - y0; + int adx = dx < 0 ? -dx : dx; + int ady = dy < 0 ? -dy : dy; + int sx = dx < 0 ? -1 : 1; + int sy = dy < 0 ? -1 : 1; + int err = adx - ady; + int x = x0, y = y0; + while (true) { + put(cv, x, y, color); + if (x == x1 && y == y1) { + break; + } + int e2 = 2 * err; + if (e2 > -ady) { + err -= ady; + x += sx; + } + if (e2 < adx) { + err += adx; + y += sy; + } + } + int lx1 = x0 < x1 ? x0 : x1, ly1 = y0 < y1 ? y0 : y1; + int lx2 = (x0 > x1 ? x0 : x1) + 1, ly2 = (y0 > y1 ? y0 : y1) + 1; + mark(cv, lx1, ly1, lx2, ly2); +} + +// Clamp a row span to the surface and word-fill it (the span-pass idiom shared by the filled +// shapes; the per-pixel put() loops it replaced clipped and indexed every pixel). +// Not inlined: each inlined copy carried both divides. +static __attribute__((noinline)) int64_t edge_slope(int32_t dx, int32_t dy) { + if (dx >= -32768 && dx <= 32767) { + return (int32_t)(dx << 16) / dy; + } + return ((int64_t)dx << 16) / dy; +} + +static void span565(picogame_canvas_obj_t *cv, int y, int xs, int xe, uint16_t color) { + if (y < 0 || y >= cv->h) { + return; + } + if (xs < 0) { + xs = 0; + } + if (xe >= cv->w) { + xe = cv->w - 1; + } + if (xs <= xe) { + picogame_fill565(&cv->data[y * cv->w + xs], xe - xs + 1, color); + } +} + +void picogame_canvas_fill_circle(picogame_canvas_obj_t *cv, int cx, int cy, int r, uint16_t color) { + // A filled circle IS fill_ellipse(r, r) - the ellipse row condition s^2*ry2 <= rr - dy^2*rx2 + // collapses to s^2 <= r^2 - dy^2 (host-proven byte-exact over 36k cases). Same delegation the + // OUTLINE circle already does; only r == 0 needs care (the ellipse rejects rx <= 0, a zero-radius + // circle is one pixel). Flash: this replaced a ~320 B twin of the ellipse body. + if (r < 0) { + return; + } + if (r == 0) { + picogame_canvas_pixel(cv, cx, cy, color); + return; + } + picogame_canvas_fill_ellipse(cv, cx, cy, r, r, color); +} + +void picogame_canvas_circle(picogame_canvas_obj_t *cv, int cx, int cy, int r, uint16_t color) { + picogame_canvas_ellipse(cv, cx, cy, r, r, color); // a circle is an ellipse with rx == ry +} + +void picogame_canvas_ring(picogame_canvas_obj_t *cv, int cx, int cy, int r, int thick, uint16_t color) { + if (r < 0) { + return; + } + int inner = r - thick; + if (inner < 0) { + inner = 0; + } + // Mirrored rows + decremental outer/inner widths, two word-filled spans per row - see fill_circle. + int out = r, ins = inner; + for (int dy = 0; dy <= r; dy++) { + long rr = (long)r * r - (long)dy * dy; // long (like ellipse): int r*r overflows at big radii + while ((long)out * out > rr) { + out--; + } + int two_seg = dy <= inner; + if (two_seg) { + int ri = inner * inner - dy * dy; + while (ins * ins > ri) { + ins--; + } + } + for (int half = 0; half < (dy ? 2 : 1); half++) { + int y = half ? cy - dy : cy + dy; + if (two_seg) { + span565(cv, y, cx - out, cx - ins - 1, color); + span565(cv, y, cx + ins + 1, cx + out, color); + } else { + span565(cv, y, cx - out, cx + out, color); + } + } + } + mark(cv, cx - r, cy - r, cx + r + 1, cy + r + 1); +} + +void picogame_canvas_triangle(picogame_canvas_obj_t *cv, + int x0, int y0, int x1, int y1, int x2, int y2, uint16_t color) { + picogame_canvas_line(cv, x0, y0, x1, y1, color); + picogame_canvas_line(cv, x1, y1, x2, y2, color); + picogame_canvas_line(cv, x2, y2, x0, y0, color); +} + +void picogame_canvas_fill_triangle(picogame_canvas_obj_t *cv, + int x0, int y0, int x1, int y1, int x2, int y2, uint16_t color) { + int X[3] = { x0, x1, x2 }, Y[3] = { y0, y1, y2 }; + for (int i = 0; i < 2; i++) { + for (int j = i + 1; j < 3; j++) { + if (Y[j] < Y[i]) { + int t = Y[i]; + Y[i] = Y[j]; + Y[j] = t; + t = X[i]; + X[i] = X[j]; + X[j] = t; + } + } + } + // Scanline fill via 16.16 edge DDA + word-filled spans. One 64-bit divide per EDGE replaces two + // 32-bit divides per ROW (M0+ has no HW divide, ~75 cyc each; a 20-row wall paid ~40 divides), + // and each row goes through fill565 (word stores) instead of a per-pixel clipped put(). Rows and + // spans clamp to the canvas up front, so a mostly off-screen triangle costs only its visible rows + // (the old loop walked EVERY row of huge triangles and clipped per pixel - quadratic blowup). + // Edge x differs from the old divide by at most 1 px (trunc vs floor; host-verified over 100k + // triangles), and convex quads - the box faces the 3D demos draw - stay seam-hole-free. + int w = cv->w, h = cv->h; + if (Y[0] < h && Y[2] >= 0) { + int64_t sAC = (Y[2] != Y[0]) ? edge_slope(X[2] - X[0], Y[2] - Y[0]) : 0; + int64_t sAB = (Y[1] != Y[0]) ? edge_slope(X[1] - X[0], Y[1] - Y[0]) : 0; + int64_t sBC = (Y[2] != Y[1]) ? edge_slope(X[2] - X[1], Y[2] - Y[1]) : 0; + uint16_t *data = cv->data; + // top half: rows [Y0, Y1) walk edges A->C and A->B + int ys = Y[0] < 0 ? 0 : Y[0]; + int ye = (Y[1] - 1) < (h - 1) ? (Y[1] - 1) : (h - 1); + // skip is 0 unless the triangle is clipped at the top, so the int64 multiplies + // usually do not run. + int skip = ys - Y[0]; + int64_t accAC = (int64_t)X[0] << 16; + int64_t acc2 = accAC; + if (skip) { + accAC += sAC * skip; + acc2 += sAB * skip; + } + for (int y = ys; y <= ye; y++) { + int xac = (int)(accAC >> 16); + int xsh = (int)(acc2 >> 16); + int xs = xac < xsh ? xac : xsh, xe = xac < xsh ? xsh : xac; + if (xs < 0) { + xs = 0; + } + if (xe >= w) { + xe = w - 1; + } + if (xs <= xe) { + picogame_fill565(&data[y * w + xs], xe - xs + 1, color); + } + accAC += sAC; + acc2 += sAB; + } + // bottom half: rows [Y1, Y2] walk edges A->C and B->C (a flat bottom degenerates to sBC=0) + ys = Y[1] < 0 ? 0 : Y[1]; + ye = Y[2] < (h - 1) ? Y[2] : (h - 1); + accAC = ((int64_t)X[0] << 16) + sAC * (ys - Y[0]); // spans the whole top half: rarely 0 + acc2 = (int64_t)X[1] << 16; + skip = ys - Y[1]; + if (skip) { + acc2 += sBC * skip; + } + for (int y = ys; y <= ye; y++) { + int xac = (int)(accAC >> 16); + int xsh = (int)(acc2 >> 16); + int xs = xac < xsh ? xac : xsh, xe = xac < xsh ? xsh : xac; + if (xs < 0) { + xs = 0; + } + if (xe >= w) { + xe = w - 1; + } + if (xs <= xe) { + picogame_fill565(&data[y * w + xs], xe - xs + 1, color); + } + accAC += sAC; + acc2 += sBC; + } + } + int mnx = X[0] < X[1] ? X[0] : X[1]; + mnx = mnx < X[2] ? mnx : X[2]; + int mxx = X[0] > X[1] ? X[0] : X[1]; + mxx = mxx > X[2] ? mxx : X[2]; + mark(cv, mnx, Y[0], mxx + 1, Y[2] + 1); +} + +void picogame_canvas_ellipse(picogame_canvas_obj_t *cv, int cx, int cy, int rx, int ry, uint16_t color) { + if (rx <= 0 || ry <= 0) { + return; + } + // 32-bit `long`: rx2*ry2 stays in range while rx*ry <= 46340 (both radii <~210 px). That covers any + // canvas that fits in RAM on this target. A larger ellipse (only reachable on a big-RAM board with an + // oversized canvas) renders a wrong shape - never a fault, since put() clips every pixel to the canvas. + long rx2 = (long)rx * rx, ry2 = (long)ry * ry, rr = rx2 * ry2; + for (int dy = -ry; dy <= ry; dy++) { + int s = 0; + while ((long)(s + 1) * (s + 1) * ry2 + (long)dy * dy * rx2 <= rr) { + s++; + } + put(cv, cx - s, cy + dy, color); + put(cv, cx + s, cy + dy, color); + } + for (int dx = -rx; dx <= rx; dx++) { + int s = 0; + while ((long)(s + 1) * (s + 1) * rx2 + (long)dx * dx * ry2 <= rr) { + s++; + } + put(cv, cx + dx, cy - s, color); + put(cv, cx + dx, cy + s, color); + } + mark(cv, cx - rx, cy - ry, cx + rx + 1, cy + ry + 1); +} + +void picogame_canvas_fill_ellipse(picogame_canvas_obj_t *cv, int cx, int cy, int rx, int ry, uint16_t color) { + if (rx <= 0 || ry <= 0) { + return; + } + // 32-bit `long`: rx2*ry2 stays in range while rx*ry <= 46340 (both radii <~210 px). That covers any + // canvas that fits in RAM on this target. A larger ellipse (only reachable on a big-RAM board with an + // oversized canvas) renders a wrong shape - never a fault, since put() clips every pixel to the canvas. + long rx2 = (long)rx * rx, ry2 = (long)ry * ry, rr = rx2 * ry2; + // Mirrored rows + decremental width, spans word-filled - see fill_circle. + int s = rx; + for (int dy = 0; dy <= ry; dy++) { + long lim = rr - (long)dy * dy * rx2; // s*s*ry2 <= lim <=> the old (s+1)-increment bound + while ((long)s * s * ry2 > lim) { + s--; + } + span565(cv, cy + dy, cx - s, cx + s, color); + if (dy) { + span565(cv, cy - dy, cx - s, cx + s, color); + } + } + mark(cv, cx - rx, cy - ry, cx + rx + 1, cy + ry + 1); +} + +void picogame_canvas_fill_round_rect(picogame_canvas_obj_t *cv, int x, int y, int w, int h, int r, uint16_t color) { + if (r > w / 2) { + r = w / 2; + } + if (r > h / 2) { + r = h / 2; + } + if (r < 0) { + r = 0; + } + picogame_canvas_fill_rect(cv, x + r, y, w - 2 * r, h, color); + picogame_canvas_fill_rect(cv, x, y + r, r, h - 2 * r, color); + picogame_canvas_fill_rect(cv, x + w - r, y + r, r, h - 2 * r, color); + picogame_canvas_fill_circle(cv, x + r, y + r, r, color); + picogame_canvas_fill_circle(cv, x + w - r - 1, y + r, r, color); + picogame_canvas_fill_circle(cv, x + r, y + h - r - 1, r, color); + picogame_canvas_fill_circle(cv, x + w - r - 1, y + h - r - 1, r, color); +} + +void picogame_canvas_frame3d(picogame_canvas_obj_t *cv, int x, int y, int w, int h, uint16_t light, uint16_t dark) { + picogame_canvas_fill_rect(cv, x, y, w, 1, light); + picogame_canvas_fill_rect(cv, x, y, 1, h, light); + picogame_canvas_fill_rect(cv, x, y + h - 1, w, 1, dark); + picogame_canvas_fill_rect(cv, x + w - 1, y, 1, h, dark); +} + +void picogame_blit_canvas( + uint16_t *buf, int region_w, int strip_top, int strip_h, int x0, + picogame_canvas_obj_t *cv, int ox, int oy) { + // Reuse the bitmap blitter by viewing the canvas as a 1-frame RGB565 bitmap. + picogame_bitmap_obj_t bm; + bm.data = (const uint8_t *)cv->data; + bm.palette = NULL; + bm.width = cv->w; + bm.height = cv->h; + bm.stride = cv->w; + bm.transparent = cv->transparent; + bm.format = PICOGAME_FMT_RGB565; + bm.frames = 1; + bm.has_transparent = cv->has_transparent; + picogame_blit_bitmap(buf, region_w, strip_h, x0, strip_top, &bm, + cv->x + ox, cv->y + oy, 0, false, false, false, NULL); +} + +// Composite a string's glyphs straight into the surface in C: rasterize each glyph from the +// font's 1-bit atlas on the fly (no Python glyph cache, no per-call Bitmap/Sprite). Because the +// StripDraw `view` is a Canvas pointing at the live strip buffer, view.text() draws immediate-mode +// text into the frame with zero retained RAM - the same primitive serves retained Canvas screens. +#if CIRCUITPY_FONTIO +void picogame_canvas_text(picogame_canvas_obj_t *cv, int x, int y, const char *text, + uint16_t fg, uint16_t bg, bool has_bg, const void *font) { + const fontio_builtinfont_t *f = font; + displayio_bitmap_t *sheet = (displayio_bitmap_t *)f->bitmap; + int fw = f->width, fh = f->height; + int tpr = sheet->width / fw; // glyph tiles per atlas row + int x0 = x; + // Hoist the canvas target + read the 1-bpp glyph atlas DIRECTLY (no per-pixel get_pixel/put calls). + // Clip each glyph rect to the canvas ONCE, then the inner loop is atlas-bit -> direct store. This is + // the per-frame path for StripDraw HUD text (repainted every frame), so it's worth the directness. + uint16_t *cdata = cv->data; + int cw = cv->w, ch = cv->h; + bool onebit = (sheet->bits_per_value == 1); // terminalio.FONT is 1-bpp; other fonts take the fallback + const uint8_t *sdata = (const uint8_t *)sheet->data; + int sstride_b = sheet->stride * 4; // atlas row stride in BYTES (stride counts uint32) + // Copy to locals: the uint16_t store may alias sheet->bitmask, so the fields + // would be reloaded for every pixel. + int sx_shift = sheet->x_shift; + size_t sx_mask = sheet->x_mask; + uint16_t sbitmask = sheet->bitmask; + for (const uint8_t *p = (const uint8_t *)text; *p; p++) { + uint8_t gi = fontio_builtinfont_get_glyph_index(f, *p); + if (gi != 0xff) { // 0xff = no glyph -> blank advance + int tx = (gi % tpr) * fw, ty = (gi / tpr) * fh; + int gx0 = (x < 0) ? -x : 0; // clip the glyph rect to the canvas once + int gx1 = (x + fw > cw) ? cw - x : fw; + int gy0 = (y < 0) ? -y : 0; + int gy1 = (y + fh > ch) ? ch - y : fh; + for (int gy = gy0; gy < gy1; gy++) { + uint16_t *drow = cdata + (y + gy) * cw + x; // dst; index by gx (x+gx is in-bounds) + int sy = ty + gy; + if (onebit) { + const uint8_t *srow = sdata + (size_t)sy * sstride_b; + for (int gx = gx0; gx < gx1; gx++) { + int sx = tx + gx; + if ((srow[sx >> sx_shift] >> (sx_mask - ((size_t)sx & sx_mask))) & sbitmask) { + drow[gx] = fg; + } else if (has_bg) { + drow[gx] = bg; + } + } + } else { + for (int gx = gx0; gx < gx1; gx++) { + if (common_hal_displayio_bitmap_get_pixel(sheet, tx + gx, sy)) { + drow[gx] = fg; + } else if (has_bg) { + drow[gx] = bg; + } + } + } + } + } + x += fw; + } + mark(cv, x0, y, x, y + fh); +} +#endif + +// Fill a screen-space triangle batch with per-triangle band reject - shared by the +// Canvas.fill_triangles binding and the compositor's Triangles layer (one loop, one place). +void picogame_fill_triangle_batch(picogame_canvas_obj_t *cv, const int16_t *v, + const uint16_t *col, int n, int xo, int yo) { + int cw = cv->w, ch = cv->h; + for (int i = 0; i < n; i++) { + const int16_t *p = v + i * 6; + int y0 = p[1] + yo, y1 = p[3] + yo, y2 = p[5] + yo; + if ((y0 < 0 && y1 < 0 && y2 < 0) || (y0 >= ch && y1 >= ch && y2 >= ch)) { + continue; + } + int x0 = p[0] + xo, x1 = p[2] + xo, x2 = p[4] + xo; + if ((x0 < 0 && x1 < 0 && x2 < 0) || (x0 >= cw && x1 >= cw && x2 >= cw)) { + continue; + } + picogame_canvas_fill_triangle(cv, x0, y0, x1, y1, x2, y2, col[i]); + } +} diff --git a/shared-module/picogame/Canvas.h b/shared-module/picogame/Canvas.h new file mode 100644 index 00000000000..edf0b03381d --- /dev/null +++ b/shared-module/picogame/Canvas.h @@ -0,0 +1,60 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT +// +// picogame Canvas: a RAM RGB565 surface (any size) you draw primitives into, +// composited as a Scene layer. The general home for shapes (fill_rect, line, +// circle, pixel) - accumulates a dirty rect (scene coords) so only redrawn +// areas repaint. Colors are wire-order (picogame.rgb565). + +#pragma once + +#include +#include +#include "py/obj.h" +#include "shared-module/picogame/Bitmap.h" + +typedef struct { + mp_obj_base_t base; + uint16_t *data; // w*h wire-order RGB565 + mp_obj_t data_obj; // backing buffer kept alive (MP_OBJ_NULL if m_new'd) + uint16_t w, h; + int32_t x, y; // scene position (int32: a canvas can sit past +-32767 px in a big world) + uint16_t transparent; + bool has_transparent; + int32_t dx1, dy1, dx2, dy2; // accumulated dirty rect (scene coords; int32, see x/y) +} picogame_canvas_obj_t; + +void picogame_canvas_dirty_reset(picogame_canvas_obj_t *cv); +// Grow the dirty rect to also cover a scene-coord rect (no surface clamping). +void picogame_canvas_dirty_union(picogame_canvas_obj_t *cv, int x1, int y1, int x2, int y2); +bool picogame_canvas_take_dirty(picogame_canvas_obj_t *cv, int *x1, int *y1, int *x2, int *y2); + +void picogame_canvas_clear(picogame_canvas_obj_t *cv, uint16_t color); +void picogame_canvas_pixel(picogame_canvas_obj_t *cv, int x, int y, uint16_t color); +void picogame_canvas_fill_rect(picogame_canvas_obj_t *cv, int x, int y, int w, int h, uint16_t color); +void picogame_canvas_blit(picogame_canvas_obj_t *cv, picogame_bitmap_obj_t *bm, int x, int y, int frame, bool flip_x, bool flip_y); +void picogame_canvas_rect(picogame_canvas_obj_t *cv, int x, int y, int w, int h, uint16_t color); +void picogame_canvas_line(picogame_canvas_obj_t *cv, int x0, int y0, int x1, int y1, uint16_t color); +void picogame_canvas_fill_circle(picogame_canvas_obj_t *cv, int cx, int cy, int r, uint16_t color); +void picogame_canvas_circle(picogame_canvas_obj_t *cv, int cx, int cy, int r, uint16_t color); +void picogame_canvas_ring(picogame_canvas_obj_t *cv, int cx, int cy, int r, int thick, uint16_t color); +void picogame_canvas_triangle(picogame_canvas_obj_t *cv, int x0, int y0, int x1, int y1, int x2, int y2, uint16_t color); +void picogame_canvas_fill_triangle(picogame_canvas_obj_t *cv, int x0, int y0, int x1, int y1, int x2, int y2, uint16_t color); +void picogame_canvas_ellipse(picogame_canvas_obj_t *cv, int cx, int cy, int rx, int ry, uint16_t color); +void picogame_canvas_fill_ellipse(picogame_canvas_obj_t *cv, int cx, int cy, int rx, int ry, uint16_t color); +void picogame_canvas_fill_round_rect(picogame_canvas_obj_t *cv, int x, int y, int w, int h, int r, uint16_t color); +void picogame_canvas_frame3d(picogame_canvas_obj_t *cv, int x, int y, int w, int h, uint16_t light, uint16_t dark); +void picogame_canvas_text(picogame_canvas_obj_t *cv, int x, int y, const char *text, + uint16_t fg, uint16_t bg, bool has_bg, const void *font); +// Fill n RGB565 pixels at p (word stores; any 2-byte alignment). +void picogame_fill565(uint16_t *p, int n, uint16_t color); + +void picogame_blit_canvas( + uint16_t *buf, int region_w, int strip_top, int strip_h, int x0, + picogame_canvas_obj_t *cv, int ox, int oy); + +void picogame_fill_triangle_batch(picogame_canvas_obj_t *cv, const int16_t *v, + const uint16_t *col, int n, int xo, int yo); diff --git a/shared-module/picogame/Display.c b/shared-module/picogame/Display.c new file mode 100644 index 00000000000..a20bbe6e574 --- /dev/null +++ b/shared-module/picogame/Display.c @@ -0,0 +1,118 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +#include "shared-module/picogame/Display.h" + +#include "py/runtime.h" +#include "shared-module/picogame/__init__.h" +#include "shared-module/displayio/display_core.h" +#include "shared-bindings/displayio/__init__.h" + +void common_hal_picogame_display_construct(picogame_display_obj_t *self, + busdisplay_busdisplay_obj_t *display, bool rgb444) { + self->display = display; + #if CIRCUITPY_PICOGAME_RGB444 + self->rgb444 = rgb444; + #else + if (rgb444) { + mp_raise_NotImplementedError(MP_ERROR_TEXT("Operation or feature not supported")); + } + self->rgb444 = false; + #endif + + // Strips go out through the display bus. With an asynchronous send the next strip is blitted + // while this one is on the wire; without one they go out one after another. + self->async_send = false; + #if CIRCUITPY_BUSIO_SPI_ASYNC + self->async_send = display->bus.send_async != NULL; + #endif + + #if CIRCUITPY_PICOGAME_RGB444 + // Tell the panel which pixel format we'll send (COLMOD). Asserting it here also recovers from + // a previous program that left the panel in the other format (the setting survives soft reset). + picogame_set_pixel_format(display, rgb444); + #endif +} + +void common_hal_picogame_display_render(picogame_display_obj_t *self, + mp_obj_t *items, uint8_t *kinds, size_t n, + uint16_t *buf_a, uint16_t *buf_b, size_t buf_pixels, + int16_t x0, int16_t y0, int16_t x1, int16_t y1, uint16_t background, + int ox, int oy) { + + busdisplay_busdisplay_obj_t *display = self->display; + + // RGB444 packs 2 px into 3 bytes, so each strip row must be an even number of pixels + // (whole bytes). Widen the region to even bounds; the extra <=1 px per side just repaints. + #if CIRCUITPY_PICOGAME_RGB444 + if (self->rgb444) { + x0 &= ~1; + x1 = (x1 + 1) & ~1; + if (x1 > display->core.width) { + x1 = display->core.width; + } + } + #endif + + // Compute geometry + open the GRAM window (set region, begin transaction, RAMWR). + int region_w, strip_h; + int cx0 = x0, cy0 = y0, cx1 = x1, cy1 = y1; // strip_begin clamps these to the panel in place + if (!picogame_strip_begin(display, &cx0, &cy0, &cx1, &cy1, buf_pixels, ®ion_w, &strip_h)) { + return; + } + + uint16_t *bufs[2] = { buf_a, buf_b }; + int cur = 0; + #if CIRCUITPY_PICOGAME_RGB444 + const bool rgb444 = self->rgb444; // hoist: invariant across all strips + #endif + + // A StripDraw callback may latch a BaseException (Ctrl-C / auto-reload). Like the portable + // picogame_render_region, we must re-raise it -- but only AFTER the strip in flight is sent + // and the bus transaction closes, so hold it here and propagate below. + mp_obj_t pending = MP_OBJ_NULL; + + for (int sy = cy0; sy < cy1; sy += strip_h) { + int sh = picogame_imin(strip_h, cy1 - sy); + uint16_t *buf = bufs[cur]; + + // Blit this strip while the *other* buffer is still being sent. + pending = picogame_blit_strip_layers(buf, region_w, sy, sh, cx0, items, kinds, n, background, ox, oy); + + // RGB444: pack the just-blitted RGB565 strip in place (2 px -> 3 bytes) before sending. + #if CIRCUITPY_PICOGAME_RGB444 + size_t nbytes = rgb444 + ? picogame_pack_rgb444(buf, (size_t)region_w * sh) + : (size_t)region_w * sh * 2; + #else + size_t nbytes = (size_t)region_w * sh * 2; + #endif + + #if CIRCUITPY_BUSIO_SPI_ASYNC + if (self->async_send) { + // The bus ends the previous strip's send first, so its buffer is free for the next blit. + display->bus.send_async(display->bus.bus, DISPLAY_DATA, + CHIP_SELECT_UNTOUCHED, (uint8_t *)buf, nbytes); + } else + #endif + { + display->bus.send(display->bus.bus, DISPLAY_DATA, + CHIP_SELECT_UNTOUCHED, (uint8_t *)buf, nbytes); + } + cur ^= 1; + if (pending != MP_OBJ_NULL) { // callback interrupted: this strip is queued, now stop + flush + break; + } + } + + // The last strip must be on the wire before CS rises, as busdisplay's refresh does it. + displayio_display_bus_flush(&display->bus); + displayio_display_bus_end_transaction(&display->bus); + + if (pending != MP_OBJ_NULL) { // bus now closed -> safe to re-raise (Ctrl-C / reload) + nlr_raise(MP_OBJ_TO_PTR(pending)); + } +} diff --git a/shared-module/picogame/Display.h b/shared-module/picogame/Display.h new file mode 100644 index 00000000000..694da4a660d --- /dev/null +++ b/shared-module/picogame/Display.h @@ -0,0 +1,31 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +// Fast display backend on a port with async busio SPI: wraps an existing busdisplay and sends +// each strip with busio's write_start() so the CPU blits the next strip while the current one +// goes out. Reuses the busdisplay's bus, window opcodes and dimensions. + +#pragma once + +#include "py/obj.h" +#include "shared-bindings/busdisplay/BusDisplay.h" +#include "shared-module/picogame/Sprite.h" + +typedef struct { + mp_obj_base_t base; + busdisplay_busdisplay_obj_t *display; + bool async_send; // the display bus sends a strip asynchronously, so a blit overlaps a send + bool rgb444; // pack strips to 12-bit RGB444 before sending (~25% less SPI traffic) +} picogame_display_obj_t; + +void common_hal_picogame_display_construct(picogame_display_obj_t *self, + busdisplay_busdisplay_obj_t *display, bool rgb444); + +void common_hal_picogame_display_render(picogame_display_obj_t *self, + mp_obj_t *items, uint8_t *kinds, size_t n, + uint16_t *buf_a, uint16_t *buf_b, size_t buf_pixels, + int16_t x0, int16_t y0, int16_t x1, int16_t y1, uint16_t background, + int ox, int oy); diff --git a/shared-module/picogame/Particles.c b/shared-module/picogame/Particles.c new file mode 100644 index 00000000000..577826c3618 --- /dev/null +++ b/shared-module/picogame/Particles.c @@ -0,0 +1,202 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +#include "shared-module/picogame/Particles.h" +#include "shared-module/picogame/__init__.h" + +static uint32_t s_prng = 0x1234abcdu; + +static int32_t prng_range(int32_t lo, int32_t hi) { + s_prng ^= s_prng << 13; + s_prng ^= s_prng >> 17; + s_prng ^= s_prng << 5; + if (hi <= lo) { + return lo; + } + return lo + (int32_t)(s_prng % (uint32_t)(hi - lo + 1)); +} + +static void swap_remove(picogame_particles_obj_t *ps, int i) { + int last = ps->count - 1; + ps->px[i] = ps->px[last]; + ps->py[i] = ps->py[last]; + ps->vx[i] = ps->vx[last]; + ps->vy[i] = ps->vy[last]; + ps->life[i] = ps->life[last]; + ps->life0[i] = ps->life0[last]; + ps->color[i] = ps->color[last]; + ps->count--; +} + +// Blend wire-order RGB565 `wire` toward `to`: num/den of `wire`, the rest of `to` (per channel). +// With to = 0 this is the classic dim toward black. +static inline uint16_t lerp_wire565(uint16_t wire, uint16_t to, int num, int den) { + uint16_t c = (uint16_t)((wire >> 8) | (wire << 8)); // wire -> native + uint16_t t = (uint16_t)((to >> 8) | (to << 8)); + // One Q8 reciprocal for all three channels (0 <= q <= 256). At most 1 LSB darker. + int q = (num << 8) / den; + int p = 256 - q; + int r = (((c >> 11) & 0x1F) * q + ((t >> 11) & 0x1F) * p) >> 8; + int g = (((c >> 5) & 0x3F) * q + ((t >> 5) & 0x3F) * p) >> 8; + int b = ((c & 0x1F) * q + (t & 0x1F) * p) >> 8; + uint16_t out = (uint16_t)((r << 11) | (g << 5) | b); + return (uint16_t)((out >> 8) | (out << 8)); // native -> wire +} + +void picogame_particles_emit(picogame_particles_obj_t *ps, int x, int y, + int count, int speed, int life, uint16_t color) { + int sp = speed * 256; // px/tick -> 8.8 + for (int k = 0; k < count && ps->count < ps->cap; k++) { + int i = ps->count++; + ps->px[i] = x << 8; + ps->py[i] = y << 8; + ps->vx[i] = (int16_t)prng_range(-sp, sp); + ps->vy[i] = (int16_t)prng_range(-sp, sp); + ps->life[i] = life; + ps->life0[i] = (uint16_t)(life > 0 ? life : 1); + ps->color[i] = color; + } +} + +void picogame_particles_update(picogame_particles_obj_t *ps) { + int16_t g = ps->gravity; + int x1 = 0x7fffffff, y1 = 0x7fffffff, x2 = -0x7fffffff - 1, y2 = -0x7fffffff - 1; // INT32: big-world + int sz = ps->size; + int i = 0; + while (i < ps->count) { + ps->px[i] += ps->vx[i]; + ps->py[i] += ps->vy[i]; + ps->vy[i] += g; + if (ps->life[i] == 0) { + swap_remove(ps, i); + continue; // re-process the swapped-in particle + } + ps->life[i]--; + int sx = ps->px[i] >> 8; + int sy = ps->py[i] >> 8; + if (ps->stretch) { // the streak's tail lies one velocity back + int tx = (ps->px[i] - ps->vx[i]) >> 8; + int ty = (ps->py[i] - ps->vy[i]) >> 8; + if (tx < x1) { + x1 = tx; + } + if (ty < y1) { + y1 = ty; + } + if (tx + sz > x2) { + x2 = tx + sz; + } + if (ty + sz > y2) { + y2 = ty + sz; + } + } + if (sx < x1) { + x1 = sx; + } + if (sy < y1) { + y1 = sy; + } + if (sx + sz > x2) { + x2 = sx + sz; + } + if (sy + sz > y2) { + y2 = sy + sz; + } + i++; + } + // current-frame bbox becomes "previous" on the next take_dirty + ps->px1 = ps->cx1; + ps->py1 = ps->cy1; + ps->px2 = ps->cx2; + ps->py2 = ps->cy2; + if (ps->count > 0) { + ps->cx1 = x1; + ps->cy1 = y1; + ps->cx2 = x2; + ps->cy2 = y2; + } else { + picogame_dirty_reset(&ps->cx1); // empty -> INT32 sentinels (cx1,cy1,cx2,cy2 are contiguous) + } +} + +bool picogame_particles_take_dirty(picogame_particles_obj_t *ps, + int *x1, int *y1, int *x2, int *y2) { + int ax1 = ps->cx1 < ps->px1 ? ps->cx1 : ps->px1; + int ay1 = ps->cy1 < ps->py1 ? ps->cy1 : ps->py1; + int ax2 = ps->cx2 > ps->px2 ? ps->cx2 : ps->px2; + int ay2 = ps->cy2 > ps->py2 ? ps->cy2 : ps->py2; + // consume the previous box so a static system stops reporting dirty + ps->px1 = ps->cx1; + ps->py1 = ps->cy1; + ps->px2 = ps->cx2; + ps->py2 = ps->cy2; + if (ax1 >= ax2 || ay1 >= ay2) { + return false; + } + *x1 = ax1; + *y1 = ay1; + *x2 = ax2; + *y2 = ay2; + return true; +} + +void picogame_particles_clear(picogame_particles_obj_t *ps) { + // Move the currently-drawn region into "previous" and empty "current", so the next + // take_dirty reports the old pixels ONCE (erasing the cleared particles) then goes quiet. + ps->px1 = ps->cx1; + ps->py1 = ps->cy1; + ps->px2 = ps->cx2; + ps->py2 = ps->cy2; + picogame_dirty_reset(&ps->cx1); // empty -> INT32 sentinels (cx1,cy1,cx2,cy2 are contiguous) + ps->count = 0; +} + +void picogame_blit_particles( + uint16_t *buf, int region_w, int strip_top, int strip_h, int x0, + picogame_particles_obj_t *ps, int ox, int oy) { + int sz = ps->size; + int rx2 = x0 + region_w; + int ry2 = strip_top + strip_h; + // Reject on Y first: a strip spans the full width, so X rarely rejects. + const int32_t *pxs = ps->px, *pys = ps->py; + int ylo = strip_top - sz - oy; // py >> 8 <= ylo -> entirely above + int yhi = ry2 - oy; // py >> 8 >= yhi -> entirely below + int count = ps->count; + int steps = ps->stretch; + for (int i = 0; i < count; i++) { + int sy8 = pys[i] >> 8; + if (steps == 0 && (sy8 <= ylo || sy8 >= yhi)) { // a streak's tail may still reach the strip + continue; + } + uint16_t c = ps->color[i]; + if (ps->fade) { + c = lerp_wire565(c, ps->fade_to, ps->life[i], ps->life0[i]); + } + // copy j of steps+1 sits j/steps of one velocity back: head at the particle, tail one tick behind + for (int j = 0; j <= steps; j++) { + int32_t bx = pxs[i], by = pys[i]; + if (j) { + bx -= ps->vx[i] * j / steps; + by -= ps->vy[i] * j / steps; + } + int sx = (bx >> 8) + ox; + int sy = (by >> 8) + oy; + int xs = picogame_imax(sx, x0); + int ys = picogame_imax(sy, strip_top); + int xe = picogame_imin(sx + sz, rx2); + int ye = picogame_imin(sy + sz, ry2); + if (xs >= xe || ys >= ye) { + continue; + } + for (int y = ys; y < ye; y++) { + uint16_t *dst = buf + (y - strip_top) * region_w + (xs - x0); + for (int x = xs; x < xe; x++) { + *dst++ = c; + } + } + } + } +} diff --git a/shared-module/picogame/Particles.h b/shared-module/picogame/Particles.h new file mode 100644 index 00000000000..05032fd9d0b --- /dev/null +++ b/shared-module/picogame/Particles.h @@ -0,0 +1,47 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT +// +// picogame particle system: a pooled set of small moving dots rendered as one +// Scene layer (individual sprites would be far too heavy). Positions/velocities +// are 24.8 / 8.8 fixed-point for sub-pixel motion. Tracks a dirty rect spanning +// the previous and current frames so moving particles leave no trails. + +#pragma once + +#include +#include +#include "py/obj.h" + +typedef struct { + mp_obj_base_t base; + int32_t *px, *py; // position, 24.8 fixed-point, scene coords + int16_t *vx, *vy; // velocity, 8.8 fixed-point per tick + uint16_t *life; // ticks remaining + uint16_t *life0; // life at spawn (for the fade ramp) + uint16_t *color; // wire-order RGB565 + uint16_t cap, count; + int16_t gravity; // 8.8, added to vy each tick + uint8_t size; // particle size in pixels + uint8_t stretch; // 0 = a dot; N = N more copies back along the velocity (a speed streak) + bool fade; // blend each particle toward fade_to as it ages + uint16_t fade_to; // wire-order RGB565 the fade ends at (0 = black, the classic dim) + // dirty bounding boxes (scene coords): previous frame and current frame. + // int32 (not int16): positions are 24.8 in int32, so emitters past +-32767 px would truncate. + int32_t cx1, cy1, cx2, cy2; + int32_t px1, py1, px2, py2; +} picogame_particles_obj_t; + +void picogame_particles_emit(picogame_particles_obj_t *ps, int x, int y, + int count, int speed, int life, uint16_t color); +void picogame_particles_update(picogame_particles_obj_t *ps); +// Remove all particles, marking their last-drawn region dirty once so they get erased. +void picogame_particles_clear(picogame_particles_obj_t *ps); +// Returns true + the dirty rect (scene coords) spanning last+current frames. +bool picogame_particles_take_dirty(picogame_particles_obj_t *ps, + int *x1, int *y1, int *x2, int *y2); +void picogame_blit_particles( + uint16_t *buf, int region_w, int strip_top, int strip_h, int x0, + picogame_particles_obj_t *ps, int ox, int oy); diff --git a/shared-module/picogame/Scene.c b/shared-module/picogame/Scene.c new file mode 100644 index 00000000000..b50a6c7a9b1 --- /dev/null +++ b/shared-module/picogame/Scene.c @@ -0,0 +1,251 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +#include "shared-module/picogame/Scene.h" +#include "shared-module/picogame/__init__.h" +#include "shared-module/picogame/Bitmap.h" +#include "shared-module/picogame/Tilemap.h" +#include "shared-module/picogame/Particles.h" +#include "shared-module/picogame/Canvas.h" + +// Raw change rects collected before merging. Caps how many disjoint changes we +// track in one frame; on overflow we safely fall back to a full-screen repaint. +#define PICOGAME_RAW_RECTS 64 + +static inline bool rects_overlap(const picogame_rect_t *a, const picogame_rect_t *b) { + return a->x1 < b->x2 && b->x1 < a->x2 && a->y1 < b->y2 && b->y1 < a->y2; +} + +static inline void rect_merge(picogame_rect_t *a, const picogame_rect_t *b) { + if (b->x1 < a->x1) { + a->x1 = b->x1; + } + if (b->y1 < a->y1) { + a->y1 = b->y1; + } + if (b->x2 > a->x2) { + a->x2 = b->x2; + } + if (b->y2 > a->y2) { + a->y2 = b->y2; + } +} + +static inline long rect_area(const picogame_rect_t *r) { + return (long)(r->x2 - r->x1) * (long)(r->y2 - r->y1); +} + +// Compute up to `max_rects` mostly-disjoint dirty rectangles (screen coords) and +// update the per-sprite snapshots. Returns the rect count (0 = nothing changed). +// Collecting per-change rects (instead of one union) means scattered movers no +// longer inflate the repaint to the whole screen. +// Out-of-line rect append for compute_dirty_rects below: the old macro expanded ~30 B +// four times; a real (noinline) call keeps each site at argument setup only. +// The rect is CLIPPED to the screen first: a change wholly off-screen (the off-screen half of +// a wrapping parallax pair, a sprite parked outside) takes no slot at all - a scrolling +// background made of many wide strips would otherwise burn two slots per strip and push a +// busy scene into the full-repaint overflow every frame - and a partly visible one is +// stored at its visible size, so the merge pass works on what actually gets repainted. +static __attribute__((noinline)) void add_rect(picogame_rect_t *raw, int *nr, bool *overflow, + int screen_w, int screen_h, int x1, int y1, int x2, int y2) { + if (x1 < 0) { + x1 = 0; + } + if (y1 < 0) { + y1 = 0; + } + if (x2 > screen_w) { + x2 = screen_w; + } + if (y2 > screen_h) { + y2 = screen_h; + } + if (x1 >= x2 || y1 >= y2) { + return; // nothing visible changed + } + if (*nr < PICOGAME_RAW_RECTS) { + raw[*nr].x1 = x1; + raw[*nr].y1 = y1; + raw[*nr].x2 = x2; + raw[*nr].y2 = y2; + (*nr)++; + } else { + *overflow = true; + } +} + +int picogame_scene_compute_dirty_rects( + mp_obj_t *items, uint8_t *kinds, picogame_snapshot_t *snap, size_t n, + int screen_w, int screen_h, int ox, int oy, + picogame_rect_t *out, int max_rects) { + + picogame_rect_t raw[PICOGAME_RAW_RECTS]; + int nr = 0; + bool overflow = false; + + // Rects are stored in SCREEN coords: non-fixed items get the view offset added + // here (per item), fixed (HUD) items don't - so no uniform offset at the end. + #define ADD_RECT(ax, ay, bx, by) \ + add_rect(raw, &nr, &overflow, screen_w, screen_h, (ax) + iox, (ay) + ioy, (bx) + iox, (by) + ioy) + + for (size_t i = 0; i < n; i++) { + uint8_t rawk = kinds[i]; + uint8_t kind = rawk & PICOGAME_KIND_MASK; + // StripDraw and Triangles always composite in screen coordinates (the draw + // path never applies the view offset to them), so their dirty rects must not + // shift with the view either - otherwise a scrolled scene repaints an + // unrelated region and leaves the layer's real change stale on screen. + bool screen_space = kind == PICOGAME_KIND_STRIPDRAW || kind == PICOGAME_KIND_TRIANGLES; + int iox = ((rawk & PICOGAME_KIND_FIXED) || screen_space) ? 0 : ox; + int ioy = ((rawk & PICOGAME_KIND_FIXED) || screen_space) ? 0 : oy; + if (kind != PICOGAME_KIND_SPRITE) { + int tx1, ty1, tx2, ty2; + bool d = false; + if (kind == PICOGAME_KIND_TILEMAP) { + d = picogame_tilemap_take_dirty(MP_OBJ_TO_PTR(items[i]), &tx1, &ty1, &tx2, &ty2); + } else if (kind == PICOGAME_KIND_PARTICLES) { + d = picogame_particles_take_dirty(MP_OBJ_TO_PTR(items[i]), &tx1, &ty1, &tx2, &ty2); + } else if (kind == PICOGAME_KIND_CANVAS) { + d = picogame_canvas_take_dirty(MP_OBJ_TO_PTR(items[i]), &tx1, &ty1, &tx2, &ty2); + } else if (kind == PICOGAME_KIND_STRIPDRAW) { + // No retained pixels to diff. always_dirty -> repaint the whole rect every frame + // (animated content). Otherwise repaint only the accumulated invalidate() rect - the + // same take_dirty contract as Canvas/Tilemap, so on-change UI repaints just its region + // (and still re-runs when another layer's dirty rect overlaps it). + picogame_stripdraw_obj_t *sd = MP_OBJ_TO_PTR(items[i]); + if (sd->always_dirty) { + tx1 = sd->x; + ty1 = sd->y; + tx2 = sd->x + sd->w; + ty2 = sd->y + sd->h; + d = true; + } else { + d = picogame_dirty_take(&sd->dx1, &tx1, &ty1, &tx2, &ty2); + } + } else if (kind == PICOGAME_KIND_TRIANGLES) { + // Screen-space batch: count-set marked a full-screen dirty (clipped later). + picogame_triangles_obj_t *t = MP_OBJ_TO_PTR(items[i]); + d = picogame_dirty_take(&t->dx1, &tx1, &ty1, &tx2, &ty2); + } + if (d) { + ADD_RECT(tx1, ty1, tx2, ty2); + } + continue; + } + + picogame_sprite_obj_t *s = MP_OBJ_TO_PTR(items[i]); + picogame_snapshot_t *sn = &snap[i]; + + // Snapshot tracks the drawn screen AABB (already includes scale + rotation), + // so position/anchor/size/scale/angle/bitmap changes are all detected. + int ax1, ay1, ax2, ay2; + picogame_sprite_aabb(s, &ax1, &ay1, &ax2, &ay2); + picogame_bitmap_obj_t *bm = s->bitmap; + bool changed = (ax1 != sn->x) || (ay1 != sn->y) || + ((ax2 - ax1) != sn->w) || ((ay2 - ay1) != sn->h) || + (s->frame != sn->frame) || (s->flags != sn->flags) || + (s->scale != sn->scale) || (s->angle != sn->angle) || + (s->seq != sn->seq) || // touch(): in-place bitmap content change + (s->dither != sn->dither) || // translucency level animation + (s->flash_color != sn->flash_color) || // flash/tint colour-only change (flag stays set) + ((void *)bm != sn->bitmap); + if (!changed) { + continue; + } + + // Old rect = previous AABB (snapshot); new rect = current AABB. + if (sn->flags & PICOGAME_SPR_VISIBLE) { + ADD_RECT(sn->x, sn->y, sn->x + sn->w, sn->y + sn->h); + } + if (s->flags & PICOGAME_SPR_VISIBLE) { + ADD_RECT(ax1, ay1, ax2, ay2); + } + + sn->x = ax1; + sn->y = ay1; + sn->w = ax2 - ax1; + sn->h = ay2 - ay1; + sn->bitmap = (void *)bm; + sn->frame = s->frame; + sn->flags = s->flags; + sn->scale = s->scale; + sn->angle = s->angle; + sn->seq = s->seq; + sn->dither = s->dither; + sn->flash_color = s->flash_color; + } +#undef ADD_RECT + + if (nr == 0) { + return 0; + } + // Too many changes to track individually -> one full-screen repaint is both + // correct and likely cheaper than dozens of windows. + if (overflow) { + out[0].x1 = 0; + out[0].y1 = 0; + out[0].x2 = screen_w; + out[0].y2 = screen_h; + return 1; + } + + // Merge overlapping rects (avoids painting the same pixels twice) until stable. + bool again = true; + while (again) { + again = false; + for (int i = 0; i < nr; i++) { + for (int j = i + 1; j < nr; j++) { + if (rects_overlap(&raw[i], &raw[j])) { + rect_merge(&raw[i], &raw[j]); + raw[j] = raw[nr - 1]; + nr--; + again = true; + j--; + } + } + } + } + + // Cap the count by repeatedly merging the pair that wastes the fewest pixels. + while (nr > max_rects) { + int bi = 0, bj = 1; + long best = -1; + for (int i = 0; i < nr; i++) { + long area_i = rect_area(&raw[i]); // loop-invariant in j -> hoist out + for (int j = i + 1; j < nr; j++) { + picogame_rect_t u = raw[i]; + rect_merge(&u, &raw[j]); + long waste = rect_area(&u) - area_i - rect_area(&raw[j]); + if (best < 0 || waste < best) { + best = waste; + bi = i; + bj = j; + } + } + } + rect_merge(&raw[bi], &raw[bj]); + raw[bj] = raw[nr - 1]; + nr--; + } + + // Rects are already in screen coords (offset applied per item). Clip + drop empties. + int outn = 0; + for (int i = 0; i < nr; i++) { + int x1 = picogame_imax(raw[i].x1, 0); + int y1 = picogame_imax(raw[i].y1, 0); + int x2 = picogame_imin(raw[i].x2, screen_w); + int y2 = picogame_imin(raw[i].y2, screen_h); + if (x1 >= x2 || y1 >= y2) { + continue; + } + out[outn].x1 = x1; + out[outn].y1 = y1; + out[outn].x2 = x2; + out[outn].y2 = y2; + outn++; + } + return outn; +} diff --git a/shared-module/picogame/Scene.h b/shared-module/picogame/Scene.h new file mode 100644 index 00000000000..74277777e24 --- /dev/null +++ b/shared-module/picogame/Scene.h @@ -0,0 +1,80 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT +// +// picogame retained-mode scene with dirty-rectangle tracking. The scene owns a +// list of sprites and a snapshot of their state from the previous frame; each +// refresh diffs against the snapshot to compute the changed regions and repaints +// only those: up to PICOGAME_MAX_DIRTY_RECTS (6) mostly-disjoint rectangles, each +// rendered into its own clamped SPI window, so several separated moving objects +// stay cheap; beyond that they merge toward a fuller redraw. + +#pragma once + +#include +#include +#include +#include "py/obj.h" +#include "shared-module/picogame/Sprite.h" + +typedef struct { + int32_t x, y; + int32_t w, h; // drawn SCENE-space AABB (top-left + size) when last drawn - already accounts + // for scale + rotation, so it is the old-rect on any change. int32 (not int16): + // sprite coords are 24.8 in int32, so a big scrolling world exceeds +-32767 px + void *bitmap; // bitmap identity when last drawn (detect graphic swaps); never + // dereferenced - compared for inequality only, so it is safe + // even if the previous bitmap has since been freed + uint16_t scale; // draw scale (8.8) when last drawn - detect scale changes + int16_t angle; // rotation when last drawn - detect rotation changes + uint16_t flags; + uint16_t flash_color; // flash/tint/add colour when last drawn - detect a colour-only change + // (the effect flag stays set, so without this red->blue wouldn't repaint) + uint8_t frame; + uint8_t seq; // sprite.seq when last drawn - detect touch() (in-place content change) + uint8_t dither; // dither level when last drawn - detect translucency animation +} picogame_snapshot_t; + +typedef struct { + int x1, y1, x2, y2; // screen-space dirty rectangle [x1,x2) x [y1,y2) +} picogame_rect_t; + +typedef struct { + mp_obj_base_t base; + mp_obj_t display; // picogame.Display (transport; also kept alive) + mp_obj_t buf_a; // strip buffer A (kept alive) + mp_obj_t buf_b; // strip buffer B (kept alive) + mp_obj_t *items; // sprite / tilemap objects (GC-scanned -> stay alive) + uint8_t *kinds; // PICOGAME_KIND_* per item + picogame_snapshot_t *snap; // previous-frame state; snap[i] is unused when + // kinds[i] == TILEMAP (tilemaps track their own dirty rect) + uint16_t count; + uint16_t cap; + uint16_t background; + int32_t ox, oy; // view offset: screen position of scene origin (camera/centering); int32 so a + // large-world camera can scroll past +-32767 px without truncating the offset + int16_t top, bottom, left, right; // reserved insets (px): the scene renders only the + // play rect [left, w-right) x [top, h-bottom) and never touches the + // border around it - the app owns it (HUD bars, side panels, frame). + bool cleared; // false until the first full-screen paint (covers stale pixels) + bool fast; // true: display is a fast picogame.Display (DMA); false: a plain + // busdisplay rendered via the portable bus.send fallback + #if CIRCUITPY_PICOGAME_FRAMEBUFFER + bool fb_target; // true: self->display is a picogame.Framebuffer (RAM scanout buffer); + // refresh() composites dirty rects straight into it, no bus. Mutually + // exclusive with `fast` and the busdisplay path. + #endif + mp_obj_t dirty_rect; // reusable [x1,y1,x2,y2] list returned by refresh() (no + // per-frame tuple allocation / GC churn) +} picogame_scene_obj_t; + +// Diff items against snapshots and produce up to `max_rects` mostly-disjoint +// dirty rectangles (screen coords), updating snapshots / draining layer dirties. +// Returns the rect count (0 = nothing changed). Scattered movers yield several +// small rects instead of one screen-spanning union. +int picogame_scene_compute_dirty_rects( + mp_obj_t *items, uint8_t *kinds, picogame_snapshot_t *snap, size_t n, + int screen_w, int screen_h, int ox, int oy, + picogame_rect_t *out, int max_rects); diff --git a/shared-module/picogame/Sprite.h b/shared-module/picogame/Sprite.h new file mode 100644 index 00000000000..635392fef13 --- /dev/null +++ b/shared-module/picogame/Sprite.h @@ -0,0 +1,49 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT +// +// picogame: a positioned, animatable instance of a Bitmap. + +#pragma once + +#include +#include "py/obj.h" +#include "shared-module/picogame/Bitmap.h" + +enum { + PICOGAME_SPR_VISIBLE = 1 << 0, + PICOGAME_SPR_FLIP_X = 1 << 1, + PICOGAME_SPR_FLIP_Y = 1 << 2, + PICOGAME_SPR_SHADOW = 1 << 3, // draw opaque pixels as a darkened destination (shadow/dim) + PICOGAME_SPR_FLASH = 1 << 4, // draw opaque pixels as a solid colour (hit-flash) + PICOGAME_SPR_DITHER = 1 << 5, // skip pixels via a Bayer pattern -> fake transparency + PICOGAME_SPR_TINT = 1 << 6, // multiply opaque pixels by a colour (keeps shading) + PICOGAME_SPR_TRANSPOSE = 1 << 7, // swap x/y -> cheap 90deg (with flips = all 8 orientations) + PICOGAME_SPR_ADD = 1 << 8, // add opaque pixels (times a colour) to the destination: light +}; + +typedef struct { + mp_obj_base_t base; + picogame_bitmap_obj_t *bitmap; + mp_obj_t data; // arbitrary user payload (game state); GC-scanned + int32_t x, y; // position, 24.8 fixed-point (1/256 px), scene coords + uint16_t anchor_x; // pivot as a 1/256 fraction of width: 0=left, 128~=center, 256=right + uint16_t anchor_y; // pivot as a 1/256 fraction of height: 0=top, 128~=center, 256=bottom + uint16_t scale; // uniform draw scale, 8.8 fixed-point (256 = 1.0x); nearest-neighbour + int16_t angle; // rotation about the anchor, whole degrees (0 = axis-aligned fast path) + uint16_t flash_color; // FLASH mode: wire-order RGB565 that replaces opaque pixels (TINT/ADD: the colour) + uint16_t flags; + uint8_t frame; + uint8_t seq; // bumped by touch() to force a repaint after an in-place bitmap mutation + uint8_t dither; // DITHER mode: transparency level 0..16 (0=opaque, 16=invisible) + // ---- affine transform cache (angle != 0 path). Filled lazily on first use, invalidated + // by the scale/angle/bitmap/anchor setters (xf_valid = 0). POSITION-INDEPENDENT: the bbox + // is relative to the sprite's integer position, ic/is are the 16.16 inverse-map steps. + // Saves the trig LUT + 4-corner bbox + two software divides that otherwise re-run once per + // STRIP the sprite touches (~6x/frame at strip_h=8) plus once for the dirty-rect AABB. + uint8_t xf_valid; + int16_t xf_minx, xf_miny, xf_maxx, xf_maxy; // corners bbox relative to (x>>8, y>>8) + int32_t xf_ic, xf_is; // inverse-map steps (16.16) +} picogame_sprite_obj_t; diff --git a/shared-module/picogame/Tilemap.c b/shared-module/picogame/Tilemap.c new file mode 100644 index 00000000000..5be8efb1c37 --- /dev/null +++ b/shared-module/picogame/Tilemap.c @@ -0,0 +1,100 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +#include "shared-module/picogame/Tilemap.h" +#include "shared-module/picogame/__init__.h" + +// Floor division for b > 0. +static inline int floordiv(int a, int b) { + return (a >= 0) ? (a / b) : -(((-a) + b - 1) / b); +} + +// log2 of a power-of-2 (small tile dims), without a __ctzsi2 lib call on the M0+ (no CLZ/RBIT). +static inline int pow2_shift(unsigned v) { + int n = 0; + while (v > 1u) { + v >>= 1; + n++; + } + return n; +} + +// Thin wrappers over the shared int32 accumulator (dx1,dy1,dx2,dy2 are contiguous int32 at the +// struct tail). See picogame_dirty_* in __init__.c. +void picogame_tilemap_dirty_reset(picogame_tilemap_obj_t *tm) { + picogame_dirty_reset(&tm->dx1); +} + +void picogame_tilemap_dirty_union(picogame_tilemap_obj_t *tm, int x1, int y1, int x2, int y2) { + picogame_dirty_union(&tm->dx1, x1, y1, x2, y2); +} + +bool picogame_tilemap_take_dirty(picogame_tilemap_obj_t *tm, int *x1, int *y1, int *x2, int *y2) { + return picogame_dirty_take(&tm->dx1, x1, y1, x2, y2); +} + +void picogame_tilemap_extent(picogame_tilemap_obj_t *tm, int *x1, int *y1, int *x2, int *y2) { + int tw = tm->tileset ? tm->tileset->width : 0; + int th = tm->tileset ? tm->tileset->height : 0; + *x1 = tm->x; + *y1 = tm->y; + *x2 = tm->x + (int)tm->map_w * tw; + *y2 = tm->y + (int)tm->map_h * th; +} + +void picogame_blit_tilemap( + uint16_t *buf, int region_w, int strip_top, int strip_h, int x0, + picogame_tilemap_obj_t *tm, int ox, int oy) { + picogame_bitmap_obj_t *ts = tm->tileset; + if (ts == NULL) { + return; + } + int tw = ts->width; + int th = ts->height; + int nframes = ts->frames; + + // Tilemap origin in screen coords (scene position + view offset). + int tmx = tm->x + ox; + int tmy = tm->y + oy; + + // Region in screen coords. + int rx1 = x0, ry1 = strip_top; + int rx2 = x0 + region_w, ry2 = strip_top + strip_h; + + // Tile index range overlapping the region. Tile dims are almost always powers of two (8, 16), + // where floor division is an arithmetic shift (signed >> floors toward -inf, exactly what + // floordiv does) - which skips 4 idiv per strip on the tilemap background. Non-pow2 tiles fall + // back to floordiv. (shx>=0 signals the pow2 fast path; the ctz runs twice per call, not per tile.) + int shx = (tw & (tw - 1)) ? -1 : pow2_shift((unsigned)tw); + int shy = (th & (th - 1)) ? -1 : pow2_shift((unsigned)th); + int tx_lo = (shx >= 0) ? ((rx1 - tmx) >> shx) : floordiv(rx1 - tmx, tw); + int tx_hi = (shx >= 0) ? ((rx2 - 1 - tmx) >> shx) : floordiv(rx2 - 1 - tmx, tw); + int ty_lo = (shy >= 0) ? ((ry1 - tmy) >> shy) : floordiv(ry1 - tmy, th); + int ty_hi = (shy >= 0) ? ((ry2 - 1 - tmy) >> shy) : floordiv(ry2 - 1 - tmy, th); + tx_lo = picogame_imax(tx_lo, 0); + ty_lo = picogame_imax(ty_lo, 0); + tx_hi = picogame_imin(tx_hi, (int)tm->map_w - 1); + ty_hi = picogame_imin(ty_hi, (int)tm->map_h - 1); + + const uint8_t *map = tm->map; // hoist per-tile decode invariants out of the inner loop + const uint8_t *orient = tm->orient; + int map_w = (int)tm->map_w; + for (int ty = ty_lo; ty <= ty_hi; ty++) { + int dy = tmy + ty * th; + size_t row = (size_t)ty * map_w; + for (int tx = tx_lo; tx <= tx_hi; tx++) { + size_t cell = row + tx; + uint8_t idx = map[cell]; + if (idx >= nframes) { + continue; + } + uint8_t o = orient ? orient[cell] : 0; + int dx = tmx + tx * tw; + picogame_blit_bitmap(buf, region_w, strip_h, x0, strip_top, + ts, dx, dy, idx, (o & 1) != 0, (o & 2) != 0, (o & 4) != 0, NULL); + } + } +} diff --git a/shared-module/picogame/Tilemap.h b/shared-module/picogame/Tilemap.h new file mode 100644 index 00000000000..e06e0a626b1 --- /dev/null +++ b/shared-module/picogame/Tilemap.h @@ -0,0 +1,44 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT +// +// picogame Tilemap: a grid of tile indices into a tileset Bitmap (each tile = one +// frame of the bitmap). Rendered as a Scene layer; maintains an accumulated dirty +// rectangle (screen coords) so only changed tiles/areas are repainted. + +#pragma once + +#include +#include +#include "py/obj.h" +#include "shared-module/picogame/Bitmap.h" + +typedef struct { + mp_obj_base_t base; + picogame_bitmap_obj_t *tileset; // each frame is a tile (tileset->width x height) + mp_obj_t tileset_obj; // keep alive + uint8_t *map; // map_w*map_h tile indices + mp_obj_t map_obj; // keep alive + uint8_t *orient; // map_w*map_h orientation bits (bit0 flipX, bit1 flipY, + // bit2 transpose); NULL until a tile sets an orientation + mp_obj_t orient_obj; // keep alive (lazily allocated) + uint16_t map_w, map_h; + int32_t x, y; // pixel position of tile (0,0) (int32: big maps scroll past +-32767) + int32_t dx1, dy1, dx2, dy2; // accumulated dirty rect (scene coords; int32, see x/y); x1>=x2 => empty +} picogame_tilemap_obj_t; + +void picogame_tilemap_dirty_reset(picogame_tilemap_obj_t *tm); +void picogame_tilemap_dirty_union(picogame_tilemap_obj_t *tm, int x1, int y1, int x2, int y2); +// Returns true and fills the dirty rect if non-empty, then resets it. +bool picogame_tilemap_take_dirty(picogame_tilemap_obj_t *tm, int *x1, int *y1, int *x2, int *y2); + +// On-screen bounding box of the whole map. +void picogame_tilemap_extent(picogame_tilemap_obj_t *tm, int *x1, int *y1, int *x2, int *y2); + +// Blit the tiles intersecting the strip region into buf. (ox, oy) is the view +// offset added to the tilemap position (scene space -> screen space). +void picogame_blit_tilemap( + uint16_t *buf, int region_w, int strip_top, int strip_h, int x0, + picogame_tilemap_obj_t *tm, int ox, int oy); diff --git a/shared-module/picogame/__init__.c b/shared-module/picogame/__init__.c new file mode 100644 index 00000000000..0b27a22c098 --- /dev/null +++ b/shared-module/picogame/__init__.c @@ -0,0 +1,1413 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT +// +// picogame portable render core: strip-based, arbitrary-size blitting. +// Painter's order: clear strip to background, draw layers/sprites bottom-to-top. + +#include +#include +#include "py/runtime.h" +#include "shared-module/picogame/pg_compat.h" +#include "shared-module/picogame/__init__.h" +#include "shared-module/picogame/Tilemap.h" +#include "shared-module/picogame/Particles.h" +#include "shared-module/picogame/Canvas.h" +#include "shared-bindings/busdisplay/BusDisplay.h" +#include "shared-module/displayio/display_core.h" +#include "shared-bindings/displayio/__init__.h" + +// Shared dirty-rect accumulator over a contiguous int32 [x1,y1,x2,y2]. Canvas and Tilemap both end in +// `int32_t dx1,dy1,dx2,dy2`, so their public dirty fns are thin wrappers passing &self->dx1 here. +// Sentinels are the INT32 extremes (not int16) so a big-world scene coord past +-32767 px still +// accumulates correctly. +void picogame_dirty_reset(int32_t *r) { + r[0] = 0x7fffffff; + r[1] = 0x7fffffff; + r[2] = -0x7fffffff - 1; + r[3] = -0x7fffffff - 1; +} + +void picogame_dirty_union(int32_t *r, int x1, int y1, int x2, int y2) { + if (x1 < r[0]) { + r[0] = x1; + } + if (y1 < r[1]) { + r[1] = y1; + } + if (x2 > r[2]) { + r[2] = x2; + } + if (y2 > r[3]) { + r[3] = y2; + } +} + +bool picogame_dirty_take(int32_t *r, int *x1, int *y1, int *x2, int *y2) { + bool dirty = (r[0] < r[2]) && (r[1] < r[3]); + if (dirty) { + *x1 = r[0]; + *y1 = r[1]; + *x2 = r[2]; + *y2 = r[3]; + } + picogame_dirty_reset(r); + return dirty; +} + +// Halve each RGB565 channel of a wire-order pixel (50% darken, for shadow mode). +static inline uint16_t picogame_darken(uint16_t wire) { + uint16_t c = (uint16_t)((wire >> 8) | (wire << 8)); // wire -> native RGB565 + // Halve all three channels at once: >>1 shifts every channel right; the 0x7BEF mask clears the two + // bits that would bleed across channel boundaries (R's LSB into G's MSB, G's LSB into B's MSB) + + // R's now-0 top bit. Bit-identical to the per-channel r>>1/g>>1/b>>1 above, ~half the instructions. + uint16_t o = (uint16_t)((c >> 1) & 0x7BEF); + return (uint16_t)((o >> 8) | (o << 8)); // native -> wire +} + +// 4x4 ordered (Bayer) dither thresholds, 0..15. +static const uint8_t picogame_bayer4[4][4] = { + { 0, 8, 2, 10 }, + { 12, 4, 14, 6 }, + { 3, 11, 1, 9 }, + { 15, 7, 13, 5 }, +}; + +// Multiply two wire-order RGB565 pixels per channel (TINT: colour the source, keep its shading). +static inline uint16_t picogame_mul565(uint16_t a, uint16_t b) { + uint16_t ca = (uint16_t)((a >> 8) | (a << 8)); + uint16_t cb = (uint16_t)((b >> 8) | (b << 8)); + // /31 and /63 via reciprocal-multiply (bit-identical over the full product domain 0..961 / 0..3969): + // avoids a soft-divide per tinted pixel on M0+ (no HW divide); pure integer, fine on every MCU. + uint16_t r = (uint16_t)((((ca >> 11) & 0x1f) * ((cb >> 11) & 0x1f) * 529) >> 14); + uint16_t g = (uint16_t)((((ca >> 5) & 0x3f) * ((cb >> 5) & 0x3f) * 2081) >> 17); + uint16_t bl = (uint16_t)(((ca & 0x1f) * (cb & 0x1f) * 529) >> 14); + uint16_t o = (uint16_t)((r << 11) | (g << 5) | bl); + return (uint16_t)((o >> 8) | (o << 8)); +} + +// a + b per channel, saturating (wire-order RGB565): the destination lit by a glow pixel. +static inline uint16_t picogame_add565(uint16_t a, uint16_t b) { + uint16_t ca = (uint16_t)((a >> 8) | (a << 8)); + uint16_t cb = (uint16_t)((b >> 8) | (b << 8)); + uint16_t r = (uint16_t)(((ca >> 11) & 0x1f) + ((cb >> 11) & 0x1f)); + uint16_t g = (uint16_t)(((ca >> 5) & 0x3f) + ((cb >> 5) & 0x3f)); + uint16_t bl = (uint16_t)((ca & 0x1f) + (cb & 0x1f)); + if (r > 0x1f) { + r = 0x1f; + } + if (g > 0x3f) { + g = 0x3f; + } + if (bl > 0x1f) { + bl = 0x1f; + } + uint16_t o = (uint16_t)((r << 11) | (g << 5) | bl); + return (uint16_t)((o >> 8) | (o << 8)); +} + +// One copy, not one per blit path: picogame_fx_put is inlined into every blitter, and the add +// with its multiply is the biggest case. A PAL8 sprite arrives with the colour baked into its +// palette (colour = white). +__attribute__((noinline)) static void picogame_fx_add_put(uint16_t *dst, uint16_t src, uint16_t color) { + if (color != 0xffff) { + src = picogame_mul565(src, color); + } + *dst = picogame_add565(*dst, src); +} + +// Write one opaque source pixel through the effect. (x, y) are screen coords (for DITHER). +static inline void picogame_fx_put(uint16_t *dst, uint16_t src, int x, int y, const picogame_fx_t *fx) { + if (fx == NULL) { + *dst = src; + return; + } + // ADD stays out of the switch: a sixth case turns every inlined copy of it into a jump table + // (measured +176 B of rodata over the five-way chain). + if (fx->mode == PICOGAME_FX_ADD) { + picogame_fx_add_put(dst, src, fx->color); + return; + } + switch (fx->mode) { + case PICOGAME_FX_SHADOW: + *dst = picogame_darken(*dst); + break; + case PICOGAME_FX_FLASH: + *dst = fx->color; + break; + case PICOGAME_FX_TINT: + *dst = picogame_mul565(src, fx->color); // colour the sprite, keep its shading + break; + case PICOGAME_FX_DITHER: + if (picogame_bayer4[y & 3][x & 3] >= fx->level) { + *dst = src; // else: pixel skipped -> shows through + } + break; + default: + *dst = src; + break; + } +} + +// Copy one row. memcpy when both pointers share word alignment; otherwise a +// halfword loop, because the bootrom memcpy is slow for misaligned copies. +static inline void picogame_row_copy(uint16_t *dst, const uint16_t *src, int n) { + if ((((uintptr_t)dst ^ (uintptr_t)src) & 2u) == 0) { + memcpy(dst, src, (size_t)n * 2u); + return; + } + #pragma GCC unroll 4 + for (int i = 0; i < n; i++) { + dst[i] = src[i]; + } +} + +// Fetch one source pixel from HOISTED scalars: the caller lifts format/data/palette/transparency +// out of the bitmap struct ONCE before its loop, so this does no per-pixel reload of bm fields (a +// `*dst` uint16_t store would otherwise force GCC to reload bm's uint16_t members every pixel). `idx` +// is the linear source offset (srow + sx). Returns false on the transparent key. Used by the scaled / +// affine / transpose paths; the unscaled fast path inlines the read directly. + +void picogame_blit_bitmap( + uint16_t *buf, int bw, int bh, int ox, int oy, + picogame_bitmap_obj_t *bm, int dx0, int dy0, int frame, bool fx, bool fy, + bool transpose, const picogame_fx_t *fxm) { + if (bm == NULL) { + return; + } + // Point fxm at a stack copy: its fields (uint16_t color) can't then alias the *dst stores, so the + // effect params stay in registers across the pixel loop instead of reloading every pixel. + picogame_fx_t fxl; + if (fxm != NULL) { + fxl = *fxm; + fxm = &fxl; + } + int sw = bm->width; + int sh = bm->height; + + // Guard the frame index: sprite.frame is a free uint8_t, so an out-of-range + // value (bad wrap / overflow in game code) would read past the sheet data. + // Wrap into [0, frames) - cheap and animation-friendly. + if (bm->frames > 1) { + if (frame >= bm->frames) { // common case is in range: pay a compare, not a divide + frame %= bm->frames; + } + } else { + frame = 0; + } + + int frame_col0 = frame * sw; + int stride0 = bm->stride; + + // Transpose path: swap source x/y (a cheap 90deg rotate when combined with flips -> all 8 + // orientations, no cos/sin/affine). The drawn footprint swaps to sh x sw. Per-pixel sampling + // (no per-row srow precompute), used only when requested; flips + fx still apply. + if (transpose) { + int dw = sh, dh = sw; // footprint swaps + int xs = picogame_imax(dx0, ox), ys = picogame_imax(dy0, oy); + int xe = picogame_imin(dx0 + dw, ox + bw), ye = picogame_imin(dy0 + dh, oy + bh); + if (xs >= xe || ys >= ye) { + return; + } + int t_fmt = bm->format; // hoist bm fields once (see src_pixel_s) + const uint8_t *t_data = bm->data; + const uint16_t *t_pal = bm->palette; + int32_t t_key = picogame_key_of(bm); + for (int y = ys; y < ye; y++) { + int ly = y - dy0; // -> source X (0..sw-1) + int su = fx ? sw - 1 - ly : ly; // per-row: source column is constant across the row + uint16_t *dst = buf + (y - oy) * bw + (xs - ox); + int lx = xs - dx0; + int sv = fy ? sh - 1 - lx : lx; // source row: step it, no per-pixel ternary + int svstep = fy ? -1 : 1; + for (int x = xs; x < xe; x++) { + uint16_t val; + if (src_pixel_s(t_fmt, t_data, t_pal, t_key, + sv * stride0 + frame_col0 + su, &val)) { + picogame_fx_put(dst, val, x, y, fxm); + } + dst++; + sv += svstep; + } + } + return; + } + + int x_start = picogame_imax(dx0, ox); + int y_start = picogame_imax(dy0, oy); + int x_end = picogame_imin(dx0 + sw, ox + bw); + int y_end = picogame_imin(dy0 + sh, oy + bh); + if (x_start >= x_end || y_start >= y_end) { + return; + } + + int frame_col = frame * sw; + int stride = bm->stride; + bool transp = bm->has_transparent; + int run = x_end - x_start; + int nrows = y_end - y_start; + + // Row invariants are computed once; GCC only unswitches the innermost loop. + int sy0 = y_start - dy0; + int systep = 1; + if (fy) { + sy0 = sh - 1 - sy0; + systep = -1; + } + int sx0 = x_start - dx0; + int xstep = 1; + if (fx) { + sx0 = sw - 1 - sx0; + xstep = -1; + } + int srow = sy0 * stride + frame_col; + int srow_step = systep * stride; + uint16_t *dstrow = buf + (y_start - oy) * bw + (x_start - ox); + + if (bm->format == PICOGAME_FMT_PAL8) { + const uint8_t *data = bm->data; + const uint16_t *pal = bm->palette; + uint8_t key = (uint8_t)bm->transparent; + // Contract: PAL8 indices MUST be < palette length (caller's responsibility). An out-of-range + // index is undefined behaviour: it reads past the palette - usually a garbage colour, but on + // some heap layouts / platforms (e.g. ESP32-S3 heap_caps regions) it CAN fault. We deliberately + // do NOT clamp per pixel: that cost ~3 cyc/px (cmp+sbcs+ands) here, ~8% on blit-bound frames. + // + // TO RESTORE FULL BOUNDS-SAFETY (at that cost) reinstate the clamp - add `unsigned pe = + // bm->pal_entries;` here and `if (idx >= pe) { idx = 0; }` after each `idx = data[...]` in BOTH + // loops below, and the matching guard in src_pixel() (search "blit contract"). + // + // Keep the transp flag here, not a -1 key: GCC clones these loops on the flag, + // and a sentinel made opaque PAL8 33% slower. + if (fxm == NULL) { // plain copy (most sprites): no per-pixel fx branch/call + for (int i = 0; i < nrows; i++) { + uint16_t *dst = dstrow; + int sx = sx0; + #pragma GCC unroll 4 // hot path: unrolling the plain sprite blit is ~6% faster on M0+ (measured), +0.6KB + for (int x = 0; x < run; x++) { + uint8_t idx = data[srow + sx]; + if (!transp || idx != key) { + *dst = pal[idx]; + } + dst++; + sx += xstep; + } + srow += srow_step; + dstrow += bw; + } + } else { + // The effect path keeps x/y as loop variables: DITHER uses screen coordinates. + for (int y = y_start; y < y_end; y++) { + uint16_t *dst = dstrow; + int sx = sx0; + for (int x = x_start; x < x_end; x++) { + uint8_t idx = data[srow + sx]; + if (!transp || idx != key) { + picogame_fx_put(dst, pal[idx], x, y, fxm); + } + dst++; + sx += xstep; + } + srow += srow_step; + dstrow += bw; + } + } + } else { // PICOGAME_FMT_RGB565 + // bm->data is a GC-allocated Python buffer (>=4-byte aligned), so the 16-bit + // view is safe; xtensa's -Wcast-align can't see that, so silence it here. + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wcast-align" + const uint16_t *data = (const uint16_t *)bm->data; + #pragma GCC diagnostic pop + uint16_t key = bm->transparent; + if (fxm == NULL && !transp && !fx) { + // Opaque, not x-flipped: one block copy per row. + for (int i = 0; i < nrows; i++) { + picogame_row_copy(dstrow, &data[srow + sx0], run); + srow += srow_step; + dstrow += bw; + } + } else if (fxm == NULL) { // plain copy (most sprites): no per-pixel fx branch/call + for (int i = 0; i < nrows; i++) { + uint16_t *dst = dstrow; + int sx = sx0; + #pragma GCC unroll 4 // hot path: unrolling the plain sprite blit is ~6% faster on M0+ (measured), +0.6KB + for (int x = 0; x < run; x++) { + uint16_t v = data[srow + sx]; + if (!transp || v != key) { + *dst = v; + } + dst++; + sx += xstep; + } + srow += srow_step; + dstrow += bw; + } + } else { + // The effect path keeps x/y as loop variables: DITHER uses screen coordinates. + for (int y = y_start; y < y_end; y++) { + uint16_t *dst = dstrow; + int sx = sx0; + for (int x = x_start; x < x_end; x++) { + uint16_t v = data[srow + sx]; + if (!transp || v != key) { + picogame_fx_put(dst, v, x, y, fxm); + } + dst++; + sx += xstep; + } + srow += srow_step; + dstrow += bw; + } + } + } +} + + +void picogame_blit_bitmap_scaled( + uint16_t *buf, int bw, int bh, int ox, int oy, + picogame_bitmap_obj_t *bm, int dx0, int dy0, int frame, bool fx, bool fy, + uint16_t scale, const picogame_fx_t *fxm) { + if (bm == NULL || scale == 0) { + return; + } + picogame_fx_t fxl; // stack copy: fields don't alias *dst (see blit_bitmap) + if (fxm != NULL) { + fxl = *fxm; + fxm = &fxl; + } + int sw = bm->width, sh = bm->height; + if (bm->frames > 1) { + if (frame >= bm->frames) { // common case is in range: pay a compare, not a divide + frame %= bm->frames; + } + } else { + frame = 0; + } + int dw = (sw * scale) >> 8, dh = (sh * scale) >> 8; + if (dw <= 0 || dh <= 0) { + return; + } + int x_start = picogame_imax(dx0, ox), y_start = picogame_imax(dy0, oy); + int x_end = picogame_imin(dx0 + dw, ox + bw), y_end = picogame_imin(dy0 + dh, oy + bh); + if (x_start >= x_end || y_start >= y_end) { + return; + } + int frame_col = frame * sw, stride = bm->stride; + int s_fmt = bm->format; // hoist bm fields once (see src_pixel_s) + const uint8_t *s_data = bm->data; + const uint16_t *s_pal = bm->palette; + bool s_transp = bm->has_transparent; // still selects the opaque fast paths below + int32_t s_key = picogame_key_of(bm); + if (scale == 512 && !fx && !fy && fxm == NULL && !s_transp && s_fmt == PICOGAME_FMT_RGB565 + && (((uintptr_t)s_data & 1) == 0)) { + // 2x integer upscale fast path - the half-res-canvas genre's per-frame blit (a full-screen + // RGB565 bitmap shown through a scale-2 sprite). At scale 512 the DDA step is exactly 2^15, + // so sampling collapses to (rel >> 1): write each source pixel twice, and when two dest rows + // share a source row, memcpy the second from the first (half the reads). Byte-exact vs the + // generic loop (host-verified over 300k random windows/clips/parities). + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wcast-align" + const uint16_t *sd16 = (const uint16_t *)s_data; + #pragma GCC diagnostic pop + int prev_sy = -1; + uint16_t *prev_row = NULL; + int nwin = x_end - x_start; + for (int y = y_start; y < y_end; y++) { + int sy = (y - dy0) >> 1; + uint16_t *drow = buf + (y - oy) * bw + (x_start - ox); + if (sy == prev_sy && prev_row != NULL) { + memcpy(drow, prev_row, (size_t)nwin * 2); + } else { + const uint16_t *srow = sd16 + sy * stride + frame_col; + int rel = x_start - dx0; + uint16_t *d = drow; + int n = nwin; + if (rel & 1) { // leading odd dest column + *d++ = srow[rel >> 1]; + rel++; + n--; + } + const uint16_t *sp = srow + (rel >> 1); + while (n >= 2) { + uint16_t v = *sp++; + d[0] = v; + d[1] = v; + d += 2; + n -= 2; + } + if (n) { + *d = *sp; + } + } + prev_sy = sy; + prev_row = drow; + } + return; + } + if (scale >= 512 && (scale & (scale - 1)) == 0 && !fx && !fy && fxm == NULL && !s_transp + && s_fmt == PICOGAME_FMT_PAL8) { + // Integer upscale, PAL8 - the same idea as the RGB565 2x path above (which exists for the + // half-res-canvas genre), for the format the engine's art actually uses, and for ANY integer + // factor rather than just 2. At an integer scale the DDA collapses: every source pixel maps + // to exactly `nrep` dest pixels and every source row to `nrep` dest rows, so a row is + // rasterized once and its repeats are memcpy'd. + // + // WHY IT MATTERS - it is a RAM technique, not just a speed one: art kept at 1/nrep and + // upscaled costs 1/nrep^2 of the bitmap. A 320x100 PAL8 parallax band is 31.2 kB at 1:1 but + // 7.8 kB at half size, and RP2040 has 25-40 kB of heap. Making the upscale cheap is what + // makes that trade attractive instead of merely possible. + // + // Transparency is deliberately NOT handled here: a skipped pixel must keep ITS OWN row's + // background, so the repeats cannot be memcpy'd, and measurement showed the remaining win + // (0.1-0.2 ms on the small transparent sprites that actually exist) did not justify the flash. + const int nrep = scale >> 8; + const int dy_rel = y_start - dy0, dx_rel = x_start - dx0; + int sy = dy_rel / nrep; + int rem = nrep - (dy_rel % nrep); // dest rows this source row still owns + const int sx0 = dx_rel / nrep, hoff = dx_rel % nrep; + const int nwin = x_end - x_start; + bool draw = true; + uint16_t *rep_from = NULL; + for (int y = y_start; y < y_end; y++) { + uint16_t *drow = buf + (y - oy) * bw + (x_start - ox); + if (draw) { + const uint8_t *sp = s_data + sy * stride + frame_col + sx0; + uint16_t *d = drow; + int n = nwin; + int first = nrep - hoff; // the leading source pixel may be partly clipped + if (first > n) { + first = n; + } + uint16_t c = s_pal[*sp++]; + for (int i = 0; i < first; i++) { + *d++ = c; + } + n -= first; + if (nrep == 2) { // the common case, unrolled: two stores, no counter + while (n >= 2) { + c = s_pal[*sp++]; + d[0] = c; + d[1] = c; + d += 2; + n -= 2; + } + } else { + while (n >= nrep) { + c = s_pal[*sp++]; + for (int i = 0; i < nrep; i++) { + *d++ = c; + } + n -= nrep; + } + } + if (n) { // trailing partial group + c = s_pal[*sp]; + while (n--) { + *d++ = c; + } + } + rep_from = drow; + draw = false; + } else { + memcpy(drow, rep_from, (size_t)nwin * 2); + } + if (--rem == 0) { + sy++; + rem = nrep; + draw = true; + } + } + return; + } + uint32_t step = ((uint32_t)1 << 24) / scale; // source px per dest px, 16.16 + // No per-row sy>=sh / per-pixel sx>=sw clamp: with dw=(sd*scale)>>8 and step=floor(2^24/scale), + // the sampled index ((dw-1)*step)>>16 provably never reaches the source dimension (exhaustively + // verified over the ENTIRE uint16 x uint16 (scale, dim) domain, 0 violations), and xacc> 16); + if (fy) { + sy = sh - 1 - sy; + } + int srow = sy * stride + frame_col; + uint16_t *drow = buf + (y - oy) * bw; + uint32_t xacc = (uint32_t)(x_start - dx0) * step; + for (int x = x_start; x < x_end; x++) { + int sx = (int)(xacc >> 16); + xacc += step; + if (fx) { + sx = sw - 1 - sx; + } + uint16_t val; + if (src_pixel_s(s_fmt, s_data, s_pal, s_key, srow + sx, &val)) { + picogame_fx_put(&drow[x - ox], val, x, y, fxm); + } + } + } +} + +// Quarter-wave Q15 sine table (0..90 deg) -> fixed-point trig for the rotation setup, so the +// affine path needs no float `sinf`/`cosf` (RP2040 has no FPU). cos(d) = sin(d+90). +static const int16_t pg_sin_q15_quad[91] = { + 0, 572, 1144, 1715, 2286, 2856, 3425, 3993, 4560, 5126, + 5690, 6252, 6813, 7371, 7927, 8481, 9032, 9580, 10126, 10668, + 11207, 11743, 12275, 12803, 13328, 13848, 14364, 14876, 15383, 15886, + 16383, 16876, 17364, 17846, 18323, 18794, 19260, 19720, 20173, 20621, + 21062, 21497, 21925, 22347, 22762, 23170, 23571, 23964, 24351, 24730, + 25101, 25465, 25821, 26169, 26509, 26841, 27165, 27481, 27788, 28087, + 28377, 28659, 28932, 29196, 29451, 29697, 29934, 30162, 30381, 30591, + 30791, 30982, 31163, 31335, 31498, 31650, 31794, 31927, 32051, 32165, + 32269, 32364, 32448, 32523, 32587, 32642, 32687, 32722, 32747, 32762, + 32767, +}; +// deg must already be in 0..360 (360 == 0). +int32_t picogame_sin_q15_reduced(int deg) { + if (deg <= 90) { + return pg_sin_q15_quad[deg]; + } + if (deg <= 180) { + return pg_sin_q15_quad[180 - deg]; + } + if (deg <= 270) { + return -pg_sin_q15_quad[deg - 180]; + } + return -pg_sin_q15_quad[360 - deg]; +} +static int32_t pg_sin_q15(int deg) { + deg %= 360; + if (deg < 0) { + deg += 360; + } + return picogame_sin_q15_reduced(deg); +} +static int32_t pg_cos_q15(int deg) { + return pg_sin_q15(deg + 90); +} + +// Forward-transform a w*h rect's 4 corners through (integer pivot, 8.8 scale, Q15 rotation) and +// return the screen-space AABB. INTEGER (Q16) - measured ~40x faster than the old float version on +// the M0+ flagship (soft-float), and faster on every target (measured affine_q16 vs affine_float). +// Runs once per rotated sprite (not per pixel). Each corner is FLOORED (arithmetic >>23 = /(256*32768)), +// so the returned box is <= the true min and the callers' +1/+2 keep the box CONTAINING the sprite +// (the affine blitter clips per pixel anyway, so a >=1px-too-large box only repaints, never clips). +static void corners_bbox(int sw, int sh, int px, int py, int pivx, int pivy, + int32_t scale, int32_t cos_q, int32_t sin_q, int *minx, int *miny, int *maxx, int *maxy) { + int nx = 1 << 30, xx = -(1 << 30), ny = 1 << 30, xy = -(1 << 30); + int cxs[4] = { 0, sw, 0, sw }, cys[4] = { 0, 0, sh, sh }; + for (int k = 0; k < 4; k++) { + int64_t du = (int64_t)(cxs[k] - pivx) * scale; // (corner - pivot) in pixels<<8 + int64_t dv = (int64_t)(cys[k] - pivy) * scale; + int X = px + (int)((du * cos_q - dv * sin_q) >> 23); // >>23 = /(256 * 32768): drop the 8.8 + Q15 + int Y = py + (int)((du * sin_q + dv * cos_q) >> 23); + if (X < nx) { + nx = X; + } + if (X > xx) { + xx = X; + } + if (Y < ny) { + ny = Y; + } + if (Y > xy) { + xy = Y; + } + } + *minx = nx; + *miny = ny; + *maxx = xx; + *maxy = xy; +} + +// Fill the sprite's affine cache (position-relative bbox + 16.16 inverse-map steps) if stale. +// The trig LUT, the 4-corner bbox and the TWO SOFTWARE DIVIDES below used to re-run once per +// strip a rotated sprite touched (~6x/frame at strip_h=8) plus once for the dirty-rect AABB; +// now once per angle/scale/bitmap/anchor change (those setters clear xf_valid). +static void sprite_xform_fill(picogame_sprite_obj_t *s) { + if (s->xf_valid) { + return; + } + int w = (s->bitmap != NULL) ? s->bitmap->width : 0; + int h = (s->bitmap != NULL) ? s->bitmap->height : 0; + int pivx = ((int)s->anchor_x * w) >> 8, pivy = ((int)s->anchor_y * h) >> 8; + int32_t cos_q = pg_cos_q15(s->angle), sin_q = pg_sin_q15(s->angle); // Q15 LUT trig + int minx, miny, maxx, maxy; + corners_bbox(w, h, 0, 0, pivx, pivy, (int32_t)s->scale, cos_q, sin_q, + &minx, &miny, &maxx, &maxy); + // Saturate into the int16 cache fields: an extreme scale x size (public scale allows + // ~256x) could exceed +-32767; a saturated bbox only over/under-covers the clip - the + // blitter clips per strip anyway - instead of wrapping into a wrong-sign rect. + s->xf_minx = (int16_t)(minx < -32768 ? -32768 : (minx > 32767 ? 32767 : minx)); + s->xf_miny = (int16_t)(miny < -32768 ? -32768 : (miny > 32767 ? 32767 : miny)); + s->xf_maxx = (int16_t)(maxx < -32768 ? -32768 : (maxx > 32767 ? 32767 : maxx)); + s->xf_maxy = (int16_t)(maxy < -32768 ? -32768 : (maxy > 32767 ? 32767 : maxy)); + // inverse map (16.16 fixed-point): u = pivx + (ic*(X-px) + is*(Y-py)); + // v = pivy + (-is*(X-px) + ic*(Y-py)) + // ic = (cs/sf)*65536 = cos_q15 * 512 / scale - computed in pure integer (no float). + int32_t nic = cos_q * 512, nis = sin_q * 512; + int sc = (int)s->scale; + if (sc < 1) { + sc = 1; // scale is setter-clamped >= 1; belt for a zeroed struct + } + s->xf_ic = (nic >= 0 ? nic + sc / 2 : nic - sc / 2) / sc; + s->xf_is = (nis >= 0 ? nis + sc / 2 : nis - sc / 2) / sc; + s->xf_valid = 1; +} + +void picogame_blit_bitmap_affine( + uint16_t *buf, int bw, int bh, int ox, int oy, + picogame_bitmap_obj_t *bm, int px, int py, int pivx, int pivy, + int frame, bool fx, bool fy, + int minx, int miny, int maxx, int maxy, int32_t ic, int32_t is, + const picogame_fx_t *fxm) { + if (bm == NULL) { + return; + } + picogame_fx_t fxl; // stack copy: fields don't alias *dst (see blit_bitmap) + if (fxm != NULL) { + fxl = *fxm; + fxm = &fxl; + } + int sw = bm->width, sh = bm->height; + if (bm->frames > 1) { + if (frame >= bm->frames) { // common case is in range: pay a compare, not a divide + frame %= bm->frames; + } + } else { + frame = 0; + } + int frame_col = frame * sw, stride = bm->stride; + int a_fmt = bm->format; // hoist bm fields once (see src_pixel_s) + const uint8_t *a_data = bm->data; + const uint16_t *a_pal = bm->palette; + int32_t a_key = picogame_key_of(bm); + int x_start = picogame_imax(minx, ox), y_start = picogame_imax(miny, oy); + int x_end = picogame_imin(maxx + 1, ox + bw), y_end = picogame_imin(maxy + 1, oy + bh); + if (x_start >= x_end || y_start >= y_end) { + return; + } + // Fold flip_x/flip_y into the inverse map ONCE, so the inner loop samples the FINAL source coord + // directly - no per-pixel `sw-1-iu`/`sh-1-iv` and no fx/fy branch (one loop variant, fewer live + // values -> fewer register spills). Exact: mirroring u is u'=(sw-1)-u; through the 16.16 floor that + // is `((sw-1-pivx)<<16 + 0xFFFF) - (ic*dxf + is*dyf)`, i.e. negate the u steps + bias the pivot by + // 0xFFFF (so floor(u') == (sw-1) - floor(u) for every in-range pixel). Bit-identical output. + int32_t uxc = ic, uyc = is, upiv = (int32_t)pivx << 16; // u = upiv + uxc*dxf + uyc*dyf + int32_t vxc = -is, vyc = ic, vpiv = (int32_t)pivy << 16; // v = vpiv + vxc*dxf + vyc*dyf + if (fx) { + uxc = -ic; + uyc = -is; + upiv = ((int32_t)(sw - 1 - pivx) << 16) + 0xFFFF; + } + if (fy) { + vxc = is; + vyc = -ic; + vpiv = ((int32_t)(sh - 1 - pivy) << 16) + 0xFFFF; + } + // 32-bit 16.16 accumulators (cheaper than 64-bit on the M0+). Peak magnitude stays well within + // int32 for any sane sprite on a handheld screen. The bounds check keeps an out-of-range sample + // memory-safe (at worst a skipped pixel), never a crash. + for (int y = y_start; y < y_end; y++) { + int dyf = y - py; + int dxf = x_start - px; + int32_t uacc = upiv + uxc * dxf + uyc * dyf; + int32_t vacc = vpiv + vxc * dxf + vyc * dyf; + uint16_t *drow = buf + (y - oy) * bw; + for (int x = x_start; x < x_end; x++) { + int su = uacc >> 16, sv = vacc >> 16; // already the flipped source coords + uacc += uxc; + vacc += vxc; + // Unsigned compares also reject negative coordinates. + if ((unsigned)su < (unsigned)sw && (unsigned)sv < (unsigned)sh) { + uint16_t val; + if (src_pixel_s(a_fmt, a_data, a_pal, a_key, + sv * stride + frame_col + su, &val)) { + picogame_fx_put(&drow[x - ox], val, x, y, fxm); + } + } + } + } +} + +void picogame_sprite_aabb(const picogame_sprite_obj_t *s, int *x1, int *y1, int *x2, int *y2) { + int w = (s->bitmap != NULL) ? s->bitmap->width : 0; + int h = (s->bitmap != NULL) ? s->bitmap->height : 0; + if (s->angle == 0) { + int sw = (w * s->scale) >> 8, sh = (h * s->scale) >> 8; + if ((s->flags & PICOGAME_SPR_TRANSPOSE) && s->scale == 256) { // transpose only on the fast + int t = sw; // path (scale==256); scaled blitter ignores it, so + sw = sh; // swapping here for scale!=256 would mistrack -> trail + sh = t; + } + int tx = (s->x >> 8) - ((int)s->anchor_x * sw >> 8); + int ty = (s->y >> 8) - ((int)s->anchor_y * sh >> 8); + *x1 = tx; + *y1 = ty; + *x2 = tx + sw; + *y2 = ty + sh; + return; + } + // cache-fill mutates only the derived xf_* fields - logically const for callers + sprite_xform_fill((picogame_sprite_obj_t *)s); + int px = s->x >> 8, py = s->y >> 8; + *x1 = px + s->xf_minx - 1; + *y1 = py + s->xf_miny - 1; + *x2 = px + s->xf_maxx + 2; + *y2 = py + s->xf_maxy + 2; +} + +// TINT on a PAL8 sprite is baked into a stack palette (see blit_sprite) when the palette fits this +// cap, else it falls back to the per-pixel tint. 64 entries = 128 B of transient stack. +#define PICOGAME_TINT_PAL_CAP 64 + +// clip_x/clip_y = the strip buffer's screen origin; vx/vy = view offset added to +// the sprite's scene position to get its screen position. +static void blit_sprite(uint16_t *buf, int bw, int bh, int clip_x, int clip_y, + picogame_sprite_obj_t *spr, int vx, int vy) { + bool fx = (spr->flags & PICOGAME_SPR_FLIP_X) != 0; + bool fy = (spr->flags & PICOGAME_SPR_FLIP_Y) != 0; + bool tr = (spr->flags & PICOGAME_SPR_TRANSPOSE) != 0; // 90deg transpose (fast path only) + // One effect at a time (dither > flash > tint > shadow priority); NULL = no effect (fast path). + picogame_fx_t fxm = { PICOGAME_FX_NONE, 0, 0 }; + if (spr->flags & PICOGAME_SPR_DITHER) { + fxm.mode = PICOGAME_FX_DITHER; + fxm.level = spr->dither; + } else if (spr->flags & PICOGAME_SPR_FLASH) { + fxm.mode = PICOGAME_FX_FLASH; + fxm.color = spr->flash_color; + } else if (spr->flags & PICOGAME_SPR_TINT) { + fxm.mode = PICOGAME_FX_TINT; + fxm.color = spr->flash_color; // shared colour field (flash/tint exclusive) + } else if (spr->flags & PICOGAME_SPR_ADD) { + fxm.mode = PICOGAME_FX_ADD; + fxm.color = spr->flash_color; + } else if (spr->flags & PICOGAME_SPR_SHADOW) { + fxm.mode = PICOGAME_FX_SHADOW; + } + const picogame_fx_t *fxp = (fxm.mode == PICOGAME_FX_NONE) ? NULL : &fxm; + // TINT of a PAL8 sprite is a pure function of the palette index -> bake it into a stack palette + // ONCE and blit plain, instead of picogame_mul565 per pixel (~4x on tinted PAL8 sprites; the + // dominant sprite format). Small palettes only; larger ones keep the per-pixel tint. Transparency + // is keyed on the INDEX before the palette lookup, so the (unused) tinted key entry is harmless. + // ADD bakes its colour the same way and then adds the palette as it is (colour = white). + picogame_bitmap_obj_t *bmuse = spr->bitmap; + picogame_bitmap_obj_t bmtint; + uint16_t tpal[PICOGAME_TINT_PAL_CAP]; + if (fxp != NULL && (fxm.mode == PICOGAME_FX_TINT || fxm.mode == PICOGAME_FX_ADD) && bmuse != NULL && + bmuse->format == PICOGAME_FMT_PAL8 && bmuse->pal_entries <= PICOGAME_TINT_PAL_CAP && + fxm.color != 0xffff) { + for (int i = 0; i < bmuse->pal_entries; i++) { + tpal[i] = picogame_mul565(bmuse->palette[i], fxm.color); + } + bmtint = *bmuse; // shallow copy; override only the palette + bmtint.palette = tpal; + bmuse = &bmtint; + if (fxm.mode == PICOGAME_FX_TINT) { + fxp = NULL; // tint now baked in -> plain (fast) blit + } else { + fxm.color = 0xffff; // the add still runs per pixel, now without the multiply + } + } + if (spr->angle == 0 && spr->scale == 256) { + int tx, ty; + picogame_sprite_topleft(spr, &tx, &ty); + picogame_blit_bitmap(buf, bw, bh, clip_x, clip_y, bmuse, + tx + vx, ty + vy, spr->frame, fx, fy, tr, fxp); + } else if (spr->angle == 0) { + int tx, ty; + picogame_sprite_topleft(spr, &tx, &ty); + picogame_blit_bitmap_scaled(buf, bw, bh, clip_x, clip_y, bmuse, + tx + vx, ty + vy, spr->frame, fx, fy, spr->scale, fxp); + } else { + sprite_xform_fill(spr); // once per angle/scale change, not per strip + int w = (spr->bitmap != NULL) ? spr->bitmap->width : 0; + int h = (spr->bitmap != NULL) ? spr->bitmap->height : 0; + int pivx = ((int)spr->anchor_x * w) >> 8, pivy = ((int)spr->anchor_y * h) >> 8; + int px = (spr->x >> 8) + vx, py = (spr->y >> 8) + vy; + picogame_blit_bitmap_affine(buf, bw, bh, clip_x, clip_y, bmuse, + px, py, pivx, pivy, spr->frame, fx, fy, + px + spr->xf_minx, py + spr->xf_miny, px + spr->xf_maxx, py + spr->xf_maxy, + spr->xf_ic, spr->xf_is, fxp); + } +} + +mp_obj_t picogame_blit_strip_layers( + uint16_t *buf, int region_w, int strip_top, int strip_h, int x0, + mp_obj_t *items, uint8_t *kinds, size_t n, uint16_t background, int ox, int oy) { + mp_obj_t pending = MP_OBJ_NULL; // a BaseException latched from a StripDraw callback + int npix = region_w * strip_h; + if (background == 0) { + memset(buf, 0, (size_t)npix * 2); // common case (black/clear) -> fast bulk clear + } else { + // word-fill: two packed pixels per uint32 (half the stores). CAUTION: this composites into + // BOTH a GC strip buffer (SPI path, >=4-byte aligned) AND, on framebuffer targets, a raw row + // pointer fb + sy*stride + x0 that starts at an ODD pixel when x0 is odd -> only 2-byte + // aligned. GCC lowers the fill to STRD/STM, which raise an unaligned UsageFault on Cortex-M + // even with CCR.UNALIGN_TRP clear (STRD/STM always require word alignment). So peel one + // leading pixel to reach 4-byte alignment (mirrors picogame_fb_to_native), bulk word-fill, + // then an odd trailing pixel. + uint32_t w = (uint32_t)background | ((uint32_t)background << 16); + int i = 0; + if (npix > 0 && ((uintptr_t)buf & 2u) != 0) { + buf[0] = background; + i = 1; + } + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wcast-align" + uint32_t *w32 = (uint32_t *)(buf + i); // now 4-byte aligned + #pragma GCC diagnostic pop + int nw = (npix - i) >> 1; + picogame_fill_words(w32, nw, w); + i += nw << 1; + if (i < npix) { // odd trailing pixel + buf[i] = background; + } + } + for (size_t i = 0; i < n; i++) { + uint8_t raw = (kinds != NULL) ? kinds[i] : PICOGAME_KIND_SPRITE; + uint8_t kind = raw & PICOGAME_KIND_MASK; + // Fixed (HUD) items are drawn in screen space -> no view offset. + int iox = (raw & PICOGAME_KIND_FIXED) ? 0 : ox; + int ioy = (raw & PICOGAME_KIND_FIXED) ? 0 : oy; + if (kind == PICOGAME_KIND_TILEMAP) { + picogame_blit_tilemap(buf, region_w, strip_top, strip_h, x0, + MP_OBJ_TO_PTR(items[i]), iox, ioy); + } else if (kind == PICOGAME_KIND_PARTICLES) { + picogame_blit_particles(buf, region_w, strip_top, strip_h, x0, + MP_OBJ_TO_PTR(items[i]), iox, ioy); + } else if (kind == PICOGAME_KIND_CANVAS) { + picogame_blit_canvas(buf, region_w, strip_top, strip_h, x0, + MP_OBJ_TO_PTR(items[i]), iox, ioy); + } else if (kind == PICOGAME_KIND_STRIPDRAW) { + // Immediate mode: hand the callback a view of the part of THIS strip that + // overlaps the layer's rect (so it can only paint within its rect - a + // full-view fill stays inside it). Skip strips the rect doesn't touch. + picogame_stripdraw_obj_t *sd = MP_OBJ_TO_PTR(items[i]); + int ry0 = sd->y, ry1 = sd->y + sd->h; + int s0 = strip_top > ry0 ? strip_top : ry0; // first screen row to draw + int st_end = strip_top + strip_h; + int s1 = st_end < ry1 ? st_end : ry1; // one past last screen row + if (s0 >= s1) { + continue; // strip is outside the layer + } + picogame_canvas_obj_t *v = MP_OBJ_TO_PTR(sd->view); + v->data = buf + (s0 - strip_top) * region_w; // view row 0 == screen row s0 + v->w = region_w; + v->h = s1 - s0; + v->x = 0; + v->y = 0; + v->has_transparent = false; + mp_obj_t cbargs[5] = { + sd->view, + MP_OBJ_NEW_SMALL_INT(x0), + MP_OBJ_NEW_SMALL_INT(s0), + MP_OBJ_NEW_SMALL_INT(region_w), + MP_OBJ_NEW_SMALL_INT(s1 - s0), + }; + // We're inside an open display bus transaction here, so a raised + // exception must NOT unwind past it (that would wedge the bus / leave a + // DMA running). Catch it, keep the transaction intact, and latch so the + // traceback prints once instead of every strip every frame. + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + mp_call_function_n_kw(sd->callback, 5, 0, cbargs); + nlr_pop(); + } else { + mp_obj_t exc = MP_OBJ_FROM_PTR(nlr.ret_val); + if (!mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(exc)), + MP_OBJ_FROM_PTR(&mp_type_Exception))) { + // A BaseException (KeyboardInterrupt / ReloadException / SystemExit) must reach the + // supervisor - latch it and stop; the caller re-raises it once the display + // transaction has safely closed, so Ctrl-C and USB auto-reload actually work. + pending = exc; + break; + } + if (!sd->faulted) { + sd->faulted = true; + mp_obj_print_exception(&mp_plat_print, exc); + } + } + } else if (kind == PICOGAME_KIND_TRIANGLES) { + // Retained screen-space triangle batch: pure C per strip (no Python callback, + // so this path needs no Python re-entry mid-compose). Cheap band + // reject vs THIS strip, then the Canvas rasteriser through a stack view over + // the strip buffer. Screen-space by design: the view offset is not applied. + picogame_triangles_obj_t *t = MP_OBJ_TO_PTR(items[i]); + picogame_canvas_obj_t v; + v.data = buf; + v.data_obj = MP_OBJ_NULL; + v.w = region_w; + v.h = strip_h; + v.x = 0; + v.y = 0; + v.transparent = 0; + v.has_transparent = false; + picogame_canvas_dirty_reset(&v); + int xo = -x0; + int yo = -strip_top; + picogame_fill_triangle_batch(&v, t->verts, t->colors, t->count, xo, yo); + } else { + picogame_sprite_obj_t *spr = MP_OBJ_TO_PTR(items[i]); + if (!(spr->flags & PICOGAME_SPR_VISIBLE)) { + continue; + } + // CIRCUITPY-CHANGE: skip strips the sprite does not touch before entering the + // blitter, which picks the effect and may bake a palette first. + int ax1, ay1, ax2, ay2; + picogame_sprite_aabb(spr, &ax1, &ay1, &ax2, &ay2); + if (ay1 + ioy >= strip_top + strip_h || ay2 + ioy <= strip_top || + ax1 + iox >= x0 + region_w || ax2 + iox <= x0) { + continue; + } + blit_sprite(buf, region_w, strip_h, x0, strip_top, spr, iox, ioy); + } + } + return pending; +} + +bool picogame_strip_begin( + picogame_output_t *display, + int *x0p, int *y0p, int *x1p, int *y1p, size_t buffer_pixels, + int *region_w, int *strip_h) { + // Clamp the window to the panel (post-rotation w/h): an out-of-range region makes the controller + // wrap/garble rows. Callers usually pass clamped dirty rects, but StripDraw / direct render_region + // can hand us a rect that runs off the panel. Clamp AND write back through the pointers so the + // caller's strip loop + blit origin use the SAME clamped bounds (else only the GRAM window is + // clamped while the data loop still pushes off-panel rows -> the wrap/garble we're preventing). + int pw = display->core.width, ph = display->core.height; + int x0 = *x0p, y0 = *y0p, x1 = *x1p, y1 = *y1p; + if (x0 < 0) { + x0 = 0; + } + if (y0 < 0) { + y0 = 0; + } + if (x1 > pw) { + x1 = pw; + } + if (y1 > ph) { + y1 = ph; + } + *x0p = x0; + *y0p = y0; + *x1p = x1; + *y1p = y1; + int rw = x1 - x0; + int rh = y1 - y0; + if (rw <= 0 || rh <= 0) { + return false; + } + int sh = (int)(buffer_pixels / (size_t)rw); + if (sh < 1) { + mp_raise_ValueError(MP_ERROR_TEXT("buffer too small")); + } + if (sh > rh) { + sh = rh; + } + + displayio_area_t area; + area.x1 = x0; + area.y1 = y0; + area.x2 = x1; + area.y2 = y1; + area.next = NULL; + displayio_display_bus_set_region_to_update(&display->bus, &display->core.colorspace, &area); + + while (!displayio_display_bus_begin_transaction(&display->bus)) { + RUN_BACKGROUND_TASKS; + } + display->bus.send(display->bus.bus, DISPLAY_COMMAND, + CHIP_SELECT_TOGGLE_EVERY_BYTE, &display->write_ram_command, 1); + + *region_w = rw; + *strip_h = sh; + return true; +} + +#if CIRCUITPY_PICOGAME_RGB444 +// The display currently switched to RGB444, or NULL. The strip path packs for it and +// picogame_reset() restores it to RGB565 at the end of the program. +static picogame_output_t *rgb444_display = NULL; +#endif + +// --- output transport seam (busdisplay backend): the ONLY per-strip display ops the generic +// picogame_render_region orchestrator below touches, so a non-CircuitPython port (MicroPython +// framebuf/SPI) swaps just strip_begin + these two + set_invert/set_pixel_format. See __init__.h. +static inline void picogame_out_strip_send(picogame_output_t *display, const uint8_t *data, size_t nbytes) { + display->bus.send(display->bus.bus, DISPLAY_DATA, CHIP_SELECT_UNTOUCHED, data, nbytes); +} +static inline void picogame_out_strip_end(picogame_output_t *display) { + displayio_display_bus_end_transaction(&display->bus); +} + +void picogame_render_region( + picogame_output_t *display, + mp_obj_t *items, uint8_t *kinds, size_t n, + uint16_t *buffer, size_t buffer_pixels, + int16_t x0, int16_t y0, int16_t x1, int16_t y1, + uint16_t background, int ox, int oy) { + + #if CIRCUITPY_PICOGAME_RGB444 + // RGB444 packs 2 px into 3 bytes, so widen the region to even x bounds. + bool rgb444 = (display == rgb444_display); + if (rgb444) { + x0 &= ~1; + x1 = (x1 + 1) & ~1; + } + #endif + int region_w, strip_h; + int cx0 = x0, cy0 = y0, cx1 = x1, cy1 = y1; // strip_begin clamps these to the panel in place + if (!picogame_strip_begin(display, &cx0, &cy0, &cx1, &cy1, buffer_pixels, ®ion_w, &strip_h)) { + return; + } + for (int sy = cy0; sy < cy1; sy += strip_h) { + int sh = picogame_imin(strip_h, cy1 - sy); + mp_obj_t exc = picogame_blit_strip_layers(buffer, region_w, sy, sh, cx0, items, kinds, n, background, ox, oy); + size_t nbytes = (size_t)region_w * sh * 2; + #if CIRCUITPY_PICOGAME_RGB444 + if (rgb444) { + nbytes = picogame_pack_rgb444(buffer, (size_t)region_w * sh); // in place, 3/4 the bytes + } + #endif + picogame_out_strip_send(display, (uint8_t *)buffer, nbytes); + if (exc != MP_OBJ_NULL) { // a StripDraw callback raised a BaseException: close the + picogame_out_strip_end(display); // bus, then re-raise (Ctrl-C / reload) + nlr_raise(MP_OBJ_TO_PTR(exc)); + } + } + picogame_out_strip_end(display); +} + +// Toggle the panel's hardware colour inversion (INVON 0x21 / INVOFF 0x20). Instant, sends NO +// pixel data - a brief invert is a free full-screen "flash" (a 1-bit negative hit look). +void picogame_set_invert(picogame_output_t *display, bool on) { + uint8_t cmd = on ? 0x21 : 0x20; + while (!displayio_display_bus_begin_transaction(&display->bus)) { + RUN_BACKGROUND_TASKS; + } + display->bus.send(display->bus.bus, DISPLAY_COMMAND, CHIP_SELECT_TOGGLE_EVERY_BYTE, &cmd, 1); + displayio_display_bus_end_transaction(&display->bus); +} + +#if CIRCUITPY_PICOGAME_RGB444 +// The RGB444 machinery (this + pack_rgb444 + the Display rgb444 path) is compiled in ONLY when a +// board sets CIRCUITPY_PICOGAME_RGB444=1. It is a transfer-bound-only win (on a CPU-balanced panel +// like the PicoPad's the pack ~= the SPI byte saving, so it loses); default off (port ?= 0) until +// multi-platform experience justifies flipping the default. See pack_rgb444's measured-optimal note. +// Set the panel pixel format (COLMOD 0x3A): rgb444 -> 12-bit RGB444 (0x53), else 16-bit RGB565 +// (0x55). Asserting it on every Display construct also recovers from a previous program that left +// the panel in the other format (survives soft reset). + +void picogame_set_pixel_format(picogame_output_t *display, bool rgb444) { + uint8_t cmd = 0x3A; + uint8_t param = rgb444 ? 0x53 : 0x55; + while (!displayio_display_bus_begin_transaction(&display->bus)) { + RUN_BACKGROUND_TASKS; + } + display->bus.send(display->bus.bus, DISPLAY_COMMAND, CHIP_SELECT_TOGGLE_EVERY_BYTE, &cmd, 1); + display->bus.send(display->bus.bus, DISPLAY_DATA, CHIP_SELECT_UNTOUCHED, ¶m, 1); + displayio_display_bus_end_transaction(&display->bus); + rgb444_display = rgb444 ? display : NULL; +} + +// Called at the end of a program, before reset_displays() takes the bus away. +void picogame_reset(void) { + if (rgb444_display == NULL) { + return; + } + // A released display has a None bus. + if (mp_obj_get_type(rgb444_display->bus.bus) == &mp_type_NoneType) { + rgb444_display = NULL; + return; + } + picogame_set_pixel_format(rgb444_display, false); // clears rgb444_display +} + +// Pack a strip of `npix` (must be even) WIRE-order RGB565 pixels IN-PLACE to ST7789 12-bit RGB444 +// (2 px -> 3 bytes): R0G0 / B0R1 / G1B1. Returns the packed byte count. Cuts SPI traffic ~25%. +// In-place is safe: the write offset (1.5*i) always trails the read offset (2*i). +size_t picogame_pack_rgb444(uint16_t *buf, size_t npix) { + // Pack wire RGB565 -> ST7789 12-bit RGB444 (2 px -> 3 bytes) in place; the write offset (1.5*i) + // always trails the read offset (2*i). NB: the byte-swap to native order is LOAD-BEARING, not + // waste - it nibble-aligns the channels so each extracts in ~2 ops; extracting straight from the + // wire value makes GREEN (split across the byte boundary) cost ~5 ops and is SLOWER on device + // (measured, M0+). Likewise do NOT wide-unroll (8 registers -> spills). This tight form is the + // measured-optimal pack; RGB444 still loses to RGB565 on a CPU-balanced panel (pack ~= the SPI + // byte saving), so it is a transfer-bound-only option (default off). + uint8_t *out = (uint8_t *)buf; + size_t o = 0; + for (size_t i = 0; i + 1 < npix; i += 2) { + uint32_t w0 = buf[i], w1 = buf[i + 1]; + uint32_t n0 = (w0 >> 8) | (w0 << 8); // wire -> native RGB565 + uint32_t n1 = (w1 >> 8) | (w1 << 8); + uint8_t r0 = (n0 >> 12) & 0xF, g0 = (n0 >> 7) & 0xF, b0 = (n0 >> 1) & 0xF; + uint8_t r1 = (n1 >> 12) & 0xF, g1 = (n1 >> 7) & 0xF, b1 = (n1 >> 1) & 0xF; + out[o++] = (r0 << 4) | g0; + out[o++] = (b0 << 4) | r1; + out[o++] = (g1 << 4) | b1; + } + return o; +} +#endif // CIRCUITPY_PICOGAME_RGB444 + +void picogame_render( + picogame_output_t *display, + mp_obj_t *items, size_t n, + uint16_t *buffer, size_t buffer_pixels, + int16_t x0, int16_t y0, int16_t x1, int16_t y1, + uint16_t background) { + picogame_render_region(display, items, NULL, n, buffer, buffer_pixels, + x0, y0, x1, y1, background, 0, 0); +} + +#if CIRCUITPY_PICOGAME_FRAMEBUFFER +// Full-frame RAM-framebuffer backend. Same layered compositor as the SPI strip path +// (picogame_blit_strip_layers -> identical kinds dispatch, view offset, StripDraw), +// but the destination is a caller-owned framebuffer instead of a bus window - no +// transaction, no strip transfer. This is the shared render target for scanout-buffer +// platforms (RP2350 DVI/HSTX, the desktop sim, the WASM playground): the framebuffer +// IS the composite surface, so a region is composited straight into fb in place. +// +// fb : destination, wire-order RGB565, fb_stride*fb_h pixels (caller-owned). +// fb_stride : framebuffer row stride in pixels (>= x1); rows may be wider than x1. +// items/kinds/n, background, ox/oy : the scene layer list, as picogame_render_region. +// [x0,y0,x1,y1): the framebuffer region to (re)composite - a dirty rect, or the frame. +// Bounds are clamped to [0,fb_stride) x [0,fb_h); an empty region is a no-op. +// Returns a latched BaseException raised by a StripDraw callback (the caller re-raises +// it), or MP_OBJ_NULL - the SAME contract as the strip path, minus the bus to close. +// Convert a contiguous run of `n` pixels in place from wire-order to native RGB565. +// `((v&0x00ff00ff)<<8)|((v&0xff00ff00)>>8)` byte-swaps both halfwords of a 32-bit word at once +// (GCC lowers it to a single Cortex REV16), so two pixels per word; unrolled x4 (8 px/iter) so the +// ldr/str stream pipelines on zero-wait SRAM. A run may start at an odd x (partial dirty rect), so +// peel one leading pixel to keep the word accesses 4-byte aligned (unaligned faults on M0+). +// Portable + little-endian, so it also serves the WASM native565 canvas target. +// Emulated full-screen invert for framebuffer targets (RP2350 DVI, the WASM playground) that lack a +// panel's hardware INVON/INVOFF: a flag XORed into the wire->native conversion below, so composited +// pixels come out as their negative. Toggling it (picogame_fb_set_invert) latches a one-shot "the +// whole frame must recomposite" so the flip covers the ENTIRE screen, not just the current dirty +// rects - mirroring a panel INVON, which flips everything already scanned out. The XOR folds into the +// existing REV16 byte-swap for ~free (one extra op per word). +static bool s_fb_invert = false; +static bool s_fb_invert_dirty = false; + +void picogame_fb_set_invert(bool on) { + if (on != s_fb_invert) { + s_fb_invert = on; + s_fb_invert_dirty = true; // one full-frame recomposite so the flip is global, then latch off + } +} + +bool picogame_fb_take_invert_dirty(void) { + bool d = s_fb_invert_dirty; + s_fb_invert_dirty = false; + return d; +} + +static void picogame_fb_to_native(uint16_t *px, int n) { + uint32_t inv = s_fb_invert ? 0xFFFFFFFFu : 0u; // emulated negative flash (0 = normal pass) + int i = 0; + if (n > 0 && ((uintptr_t)px & 2u) != 0) { + px[0] = (uint16_t)(__builtin_bswap16(px[0]) ^ (uint16_t)inv); + i = 1; + } + int pairs = (n - i) >> 1; + uint32_t *w = (uint32_t *)(px + i); + int p = 0; + for (; p + 4 <= pairs; p += 4) { + uint32_t v0 = w[p], v1 = w[p + 1], v2 = w[p + 2], v3 = w[p + 3]; + w[p] = (((v0 & 0x00ff00ffu) << 8) | ((v0 & 0xff00ff00u) >> 8)) ^ inv; + w[p + 1] = (((v1 & 0x00ff00ffu) << 8) | ((v1 & 0xff00ff00u) >> 8)) ^ inv; + w[p + 2] = (((v2 & 0x00ff00ffu) << 8) | ((v2 & 0xff00ff00u) >> 8)) ^ inv; + w[p + 3] = (((v3 & 0x00ff00ffu) << 8) | ((v3 & 0xff00ff00u) >> 8)) ^ inv; + } + for (; p < pairs; p++) { + uint32_t v = w[p]; + w[p] = (((v & 0x00ff00ffu) << 8) | ((v & 0xff00ff00u) >> 8)) ^ inv; + } + i += pairs << 1; + if (i < n) { + px[i] = (uint16_t)(__builtin_bswap16(px[i]) ^ (uint16_t)inv); + } +} + +// Fused wire->native byte-swap AND copy in one pass: read `n` wire pixels from `src`, write them +// NATIVE to `dst` (folding in the emulated invert XOR). Saves the separate in-place swap + memcpy +// (one whole band read+write) on the full-width publish path. REQUIRES src AND dst 4-byte aligned +// (the caller uses it only for a contiguous full-width band, where both are). +static void picogame_fb_to_native_copy(uint16_t *dst, const uint16_t *src, int n) { + uint32_t inv = s_fb_invert ? 0xFFFFFFFFu : 0u; + int pairs = n >> 1; + const uint32_t *s = (const uint32_t *)src; + uint32_t *d = (uint32_t *)dst; + int p = 0; + for (; p + 4 <= pairs; p += 4) { + uint32_t v0 = s[p], v1 = s[p + 1], v2 = s[p + 2], v3 = s[p + 3]; + d[p] = (((v0 & 0x00ff00ffu) << 8) | ((v0 & 0xff00ff00u) >> 8)) ^ inv; + d[p + 1] = (((v1 & 0x00ff00ffu) << 8) | ((v1 & 0xff00ff00u) >> 8)) ^ inv; + d[p + 2] = (((v2 & 0x00ff00ffu) << 8) | ((v2 & 0xff00ff00u) >> 8)) ^ inv; + d[p + 3] = (((v3 & 0x00ff00ffu) << 8) | ((v3 & 0xff00ff00u) >> 8)) ^ inv; + } + for (; p < pairs; p++) { + uint32_t v = s[p]; + d[p] = (((v & 0x00ff00ffu) << 8) | ((v & 0xff00ff00u) >> 8)) ^ inv; + } + if (n & 1) { + dst[n - 1] = (uint16_t)(__builtin_bswap16(src[n - 1]) ^ (uint16_t)inv); + } +} + +// Wire-order RGB565 -> RGB332 publish copy for 8-bit picodvi scanout targets (RRRGGGBB, +// the same quantization displayio's ColorConverter uses), folding in the emulated invert. +// A wire pixel w holds native v byte-swapped: hi(v) = low byte of w, lo(v) = high byte. +// R3 = top 3 of R5 = hi & 0xE0; G3 = top 3 of G6 = (hi & 0x07) << 2; +// B2 = top 2 of B5 = (lo >> 3) & 0x03 +static void picogame_fb_to_rgb332_copy(uint8_t *dst, const uint16_t *src, int n) { + uint8_t inv = s_fb_invert ? 0xFF : 0x00; + for (int i = 0; i < n; i++) { + uint16_t w = src[i]; + uint8_t hi = (uint8_t)w; // wire low byte = native high byte + uint8_t lo = (uint8_t)(w >> 8); + dst[i] = (uint8_t)((hi & 0xE0u) | ((hi & 0x07u) << 2) | ((lo >> 3) & 0x03u)) ^ inv; + } +} + +// Publish-copy context for one framebuffer region: just what fb_publish_band needs. +typedef struct { + uint16_t *fb; + int fb_stride, fmt; + int x0, region_w; + bool full_width; +} fb_bands_arg_t; + +// Publish one FINISHED band from a scratch strip into the fb (wire/native/RGB332, +// full- or partial-width). Shared by the serial loop and both cores of the split. +static void fb_publish_band(const fb_bands_arg_t *a, uint16_t *scratch, int by, int bh) { + uint16_t *fb = a->fb; + int fb_stride = a->fb_stride; + int region_w = a->region_w; + int fmt = a->fmt; + if (a->full_width) { + size_t npix = (size_t)region_w * (size_t)bh; + if (fmt == PICOGAME_FB_RGB332) { + picogame_fb_to_rgb332_copy( + (uint8_t *)fb + (size_t)by * (size_t)fb_stride, scratch, (int)npix); + } else if (fmt == PICOGAME_FB_NATIVE565) { + // Fold the wire->native byte-swap INTO the publish copy (no separate in-place swap). + picogame_fb_to_native_copy(fb + (size_t)by * (size_t)fb_stride, scratch, (int)npix); + } else { + memcpy(fb + (size_t)by * (size_t)fb_stride, scratch, npix * 2u); // wire: HW reads as-is + } + } else if (fmt == PICOGAME_FB_RGB332) { + // Partial-width 8-bit: quantize row by row straight into the byte fb (strided). + for (int r = 0; r < bh; r++) { + picogame_fb_to_rgb332_copy( + (uint8_t *)fb + (size_t)(by + r) * (size_t)fb_stride + a->x0, + scratch + (size_t)r * region_w, region_w); + } + } else { + // Partial-width: swap the scratch in place (NATIVE), then copy row by row (strided). + if (fmt == PICOGAME_FB_NATIVE565) { + picogame_fb_to_native(scratch, region_w * bh); + } + for (int r = 0; r < bh; r++) { + memcpy(fb + (size_t)(by + r) * fb_stride + a->x0, + scratch + (size_t)r * region_w, (size_t)region_w * 2u); + } + } +} + +mp_obj_t picogame_render_framebuffer( + uint16_t *fb, int fb_stride, int fb_h, int fmt, + uint16_t *scratch, int scratch_rows, + mp_obj_t *items, uint8_t *kinds, size_t n, + int x0, int y0, int x1, int y1, + uint16_t background, int ox, int oy) { + if (x0 < 0) { + x0 = 0; + } + if (y0 < 0) { + y0 = 0; + } + if (x1 > fb_stride) { + x1 = fb_stride; + } + if (y1 > fb_h) { + y1 = fb_h; + } + if (x1 <= x0 || y1 <= y0) { + return MP_OBJ_NULL; + } + int region_w = x1 - x0; + + // Tear-free NATIVE path: the framebuffer is a LIVE scanout buffer (picodvi/HDMI reads it + // continuously), so it must NEVER transiently hold wire-order pixels - a beam sampling a + // half-composed region would read byte-swapped bytes (R/B swapped -> pink). Compose+byte-swap + // into a PRIVATE scratch strip, then memcpy the finished NATIVE band into the fb; the fb only + // ever receives fully-native runs. Any residual seam is old-vs-new NATIVE content (a plain + // single-buffer tear, no colour shift) - reduced by the caller's optional vblank sync. Bands of + // scratch_rows keep the scratch small. (Wire targets / no scratch fall through to the direct + // path below, which is correct because a wire fb needs no conversion.) + if (scratch != NULL && scratch_rows > 0) { + // Full-width band: rows are contiguous in BOTH scratch and fb, so the whole band publishes in + // one pass with 4-byte-aligned pointers (fb_stride even). Partial-width rows are strided. + fb_bands_arg_t a = { + fb, fb_stride, fmt, x0, region_w, + (x0 == 0 && region_w == fb_stride) + }; + int nbands = (y1 - y0 + scratch_rows - 1) / scratch_rows; + for (int b = 0; b < nbands; b++) { + int by = y0 + b * scratch_rows; + int bh = (y1 - by) < scratch_rows ? (y1 - by) : scratch_rows; + // Compose region_w x bh OFF-SCREEN into the scratch (wire order) so the beam never sees a + // half-composited region (no sprite/HUD flicker), then publish the FINISHED band into the + // fb. Published even on a latched exception so the fb is never left half-updated. + mp_obj_t exc = picogame_blit_strip_layers( + scratch, region_w, by, bh, x0, items, kinds, n, background, ox, oy); + fb_publish_band(&a, scratch, by, bh); + if (exc != MP_OBJ_NULL) { + return exc; // StripDraw raised; caller re-raises (cleared stays false -> full repaint) + } + } + return MP_OBJ_NULL; + } + // The compositor (blitters, effects, palettes) works in wire order throughout; a NATIVE + // target is converted in place only after a region is fully composed. On a latched StripDraw + // exception the region was partially composed in wire order - convert it anyway so the fb is + // never left half wire / half native (the Scene keeps cleared=false until its render loop + // finishes, so the refresh after the exception repaints the full frame). + + // Fast path: a FULL-WIDTH region has contiguous rows, so the whole rect IS one valid strip + // buffer. Composite it in a SINGLE strip_layers call (h = the whole band) instead of one call + // per row - this amortizes all the per-row/per-layer setup (tile-blit dispatch, clip tests, + // background fill, and crucially one StripDraw Python callback per band instead of per row) + // over the band, and converts the whole contiguous region in one pass. This is the + // full-repaint / camera-scroll case (set_view -> cleared=false -> a full-screen dirty rect). + // (An RGB332 target never reaches these direct paths: its constructor always allocates + // the scratch strip, and the compositor can only write 16-bit wire pixels - composing + // in place inside a byte framebuffer would corrupt it.) + if (x0 == 0 && x1 == fb_stride) { + uint16_t *base = fb + (size_t)y0 * (size_t)fb_stride; + mp_obj_t exc = picogame_blit_strip_layers( + base, fb_stride, y0, y1 - y0, 0, items, kinds, n, background, ox, oy); + if (fmt == PICOGAME_FB_NATIVE565) { + picogame_fb_to_native(base, (y1 - y0) * fb_stride); + } + return exc; // MP_OBJ_NULL on success, else a latched StripDraw exception + } + + // Partial-width region: rows are non-contiguous, so composite (and convert) row by row. + for (int sy = y0; sy < y1; sy++) { + uint16_t *row = fb + (size_t)sy * (size_t)fb_stride + x0; + mp_obj_t exc = picogame_blit_strip_layers( + row, region_w, sy, 1, x0, items, kinds, n, background, ox, oy); + if (fmt == PICOGAME_FB_NATIVE565) { + picogame_fb_to_native(row, region_w); + } + if (exc != MP_OBJ_NULL) { + return exc; // StripDraw raised a BaseException; caller re-raises (no bus open) + } + } + return MP_OBJ_NULL; +} +#endif // CIRCUITPY_PICOGAME_FRAMEBUFFER diff --git a/shared-module/picogame/__init__.h b/shared-module/picogame/__init__.h new file mode 100644 index 00000000000..b74d2f9b86a --- /dev/null +++ b/shared-module/picogame/__init__.h @@ -0,0 +1,321 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include +#include +#include "py/obj.h" +#include "shared-bindings/busdisplay/BusDisplay.h" +#include "shared-module/picogame/Bitmap.h" +#include "shared-module/picogame/Sprite.h" + +// Fill nw 32-bit words with w, four per iteration. w32 must be 4-byte aligned. +static inline void picogame_fill_words(uint32_t *w32, int nw, uint32_t w) { + for (int b = nw >> 2; b > 0; b--) { + w32[0] = w; + w32[1] = w; + w32[2] = w; + w32[3] = w; + w32 += 4; + } + if (nw & 2) { + w32[0] = w; + w32[1] = w; + w32 += 2; + } + if (nw & 1) { + w32[0] = w; + } +} + +// Sample one texel as wire RGB565; false = transparent (skip). Shared by the sprite/canvas +// blit paths so they inline one copy (see the blit contract: PAL8 indices must be < palette len). +// key is the transparent value, or -1 for an opaque bitmap (never matches). +static inline bool src_pixel_s(int format, const uint8_t *data, const uint16_t *pal, + int32_t key, int idx, uint16_t *out) { + if (format == PICOGAME_FMT_PAL8) { + uint8_t i = data[idx]; + if ((int32_t)i == key) { + return false; + } + *out = pal[i]; // indices must be < palette length (see blit contract) + return true; + } + // GC buffer is >=4-byte aligned; silence xtensa -Wcast-align (see picogame_blit_bitmap). + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wcast-align" + uint16_t v = ((const uint16_t *)data)[idx]; + #pragma GCC diagnostic pop + if ((int32_t)v == key) { + return false; + } + *out = v; + return true; +} + +// The transparent key of bm, or -1 when it is opaque. +static inline int32_t picogame_key_of(const picogame_bitmap_obj_t *bm) { + return bm->has_transparent ? (int32_t)bm->transparent : -1; +} + + +// Scene layer kinds (tags stored alongside items so blit/dirty can dispatch +// without cross-referencing shared-bindings type objects). +enum { + PICOGAME_KIND_SPRITE = 0, + PICOGAME_KIND_TILEMAP = 1, + PICOGAME_KIND_PARTICLES = 2, + PICOGAME_KIND_CANVAS = 3, + PICOGAME_KIND_STRIPDRAW = 4, + PICOGAME_KIND_TRIANGLES = 5, + // High bit on a kind = "fixed": the item ignores the scene view offset + // (camera), so HUD / score / dialog stay put while the world scrolls. + PICOGAME_KIND_FIXED = 0x80, + PICOGAME_KIND_MASK = 0x7f, +}; + +// StripDraw: immediate-mode layer. Holds NO pixel buffer - instead its `callback` +// is invoked once per render strip with a Canvas "view" repointed at the live strip +// buffer, so the user draws primitives straight into the strip (zero RAM vs a Canvas, +// which costs w*h*2 bytes). Its rect is repainted every frame (it's for animated / +// scanline content: pseudo-3D, gradients, procedural backgrounds). The view's local +// (0,0) maps to screen (vx, vy) handed to the callback. `faulted` latches after the +// callback raises once, so a buggy callback prints one traceback, not one per strip. +typedef struct { + mp_obj_base_t base; + mp_obj_t callback; // draw(view, vx, vy, vw, vh): vx/vy = screen origin of view (0,0) + mp_obj_t view; // a reused picogame_canvas_obj_t (data repointed each strip) + int32_t x, y, w, h; // scene rect (int32: scene coords, big-world safe) + int32_t dx1, dy1, dx2, dy2; // accumulated dirty rect (scene coords) when !always_dirty - the same + // picogame_dirty_* accumulator Canvas/Tilemap use, so invalidate() can mark + // a sub-rect and the Scene repaints only that region (not the whole layer). + bool faulted; + bool always_dirty; // True: repaint every frame (animated). False: only the dirty rect (on-change UI). +} picogame_stripdraw_obj_t; + +// Triangles: a retained SCREEN-SPACE triangle batch the compositor rasterises entirely +// in C (per strip, band-rejected) - no Python callback per strip, so unlike StripDraw it +// stays composable without re-entering Python mid-frame. verts (int16 x0,y0,x1,y1,x2,y2 per tri) and +// colors (uint16 wire RGB565 per tri) are CALLER-OWNED arrays (refs held for GC; fill +// them in place). Setting `count` selects how many draw and marks the layer dirty +// full-screen (a 3D frame repaints everything anyway). +typedef struct { + mp_obj_base_t base; + mp_obj_t verts_obj, colors_obj; // GC anchors for the caller's arrays + const int16_t *verts; + const uint16_t *colors; + uint16_t count, cap; // cap = what the buffers can hold + int32_t dx1, dy1, dx2, dy2; // dirty accumulator (count-set -> full screen) +} picogame_triangles_obj_t; + +static inline int picogame_imin(int a, int b) { + return a < b ? a : b; +} +static inline int picogame_imax(int a, int b) { + return a > b ? a : b; +} + +// Drawn top-left in scene pixels: the logical position minus the anchor offset +// (anchor is a 1/256 fraction of the bitmap size). Used by BOTH the blitter and +// the dirty-rect tracker so they always agree on where the sprite lands. +static inline void picogame_sprite_topleft(const picogame_sprite_obj_t *s, int *tx, int *ty) { + int w = (s->bitmap != NULL) ? s->bitmap->width : 0; + int h = (s->bitmap != NULL) ? s->bitmap->height : 0; + int sw = (w * s->scale) >> 8; // anchor is a fraction of the SCALED size + int sh = (h * s->scale) >> 8; + // The blitter only honours transpose on the fast path (scale==256); the scaled blitter ignores it. + // Swap the footprint ONLY when scale==256, or aabb/topleft disagree with what's drawn (trailing). + if ((s->flags & PICOGAME_SPR_TRANSPOSE) && s->scale == 256) { // 90deg transpose swaps footprint + int t = sw; // picogame_sprite_aabb, or the blit top-left and the + sw = sh; // tracked dirty rect disagree (sprite trails) + sh = t; + } + *tx = (s->x >> 8) - ((int)s->anchor_x * sw >> 8); + *ty = (s->y >> 8) - ((int)s->anchor_y * sh >> 8); +} + +// Drawn screen-space bounding box of a sprite (accounts for scale + rotation). +// Used by the dirty-rect tracker so it always covers the transformed sprite. +void picogame_sprite_aabb(const picogame_sprite_obj_t *s, int *x1, int *y1, int *x2, int *y2); + +// Per-pixel blit effect, shared by all three blit paths. One mode at a time; a NULL +// pointer means "no effect" (the fast path). SHADOW darkens the destination, FLASH +// replaces opaque pixels with `color`, DITHER skips pixels via a Bayer pattern (0..16 +// transparency) for fake translucency without alpha. +// ADD adds the pixel (times `color`) to the destination with per-channel saturation: light. +enum { PICOGAME_FX_NONE = 0, PICOGAME_FX_SHADOW, PICOGAME_FX_FLASH, PICOGAME_FX_DITHER, PICOGAME_FX_TINT, PICOGAME_FX_ADD }; +typedef struct { + uint8_t mode; + uint16_t color; // FLASH: solid colour to write; TINT/ADD: colour to multiply by (wire RGB565) + uint8_t level; // DITHER: 0..16 transparency (higher = more pixels skipped) +} picogame_fx_t; + +// Shared dirty-rect accumulator over a contiguous int32 [x1,y1,x2,y2] (Canvas + Tilemap both end in +// dx1,dy1,dx2,dy2). INT32 sentinels so big-world (>32767 px) scene coords still accumulate. +void picogame_dirty_reset(int32_t *r); +void picogame_dirty_union(int32_t *r, int x1, int y1, int x2, int y2); +bool picogame_dirty_take(int32_t *r, int *x1, int *y1, int *x2, int *y2); + +// Blit one frame of a bitmap at screen (dx0, dy0) into the strip buffer that +// covers [ox, ox+bw) x [oy, oy+bh). Shared by sprites and tilemap tiles. +// fxm: per-pixel effect (NULL = plain colour copy). +void picogame_blit_bitmap( + uint16_t *buf, int bw, int bh, int ox, int oy, + picogame_bitmap_obj_t *bm, int dx0, int dy0, int frame, bool flip_x, bool flip_y, + bool transpose, const picogame_fx_t *fxm); + +// Nearest-neighbour scaled blit (axis-aligned); scale is 8.8 fixed-point. +void picogame_blit_bitmap_scaled( + uint16_t *buf, int bw, int bh, int ox, int oy, + picogame_bitmap_obj_t *bm, int dx0, int dy0, int frame, bool flip_x, bool flip_y, + uint16_t scale, const picogame_fx_t *fxm); + +// Full affine blit (scale + rotation about the anchor); (px,py)=screen anchor point, +// (pivx,pivy)=that anchor in SOURCE pixels. Nearest-neighbour inverse map. The transform is +// PRECOMPUTED by the caller (the sprite's xf_* cache): minx..maxy = the screen-space corner +// bbox, ic/is = the 16.16 inverse-map steps - so a per-strip call does no trig/divides. +void picogame_blit_bitmap_affine( + uint16_t *buf, int bw, int bh, int ox, int oy, + picogame_bitmap_obj_t *bm, int px, int py, int pivx, int pivy, + int frame, bool flip_x, bool flip_y, + int minx, int miny, int maxx, int maxy, int32_t ic, int32_t is, + const picogame_fx_t *fxm); + +// ===== OUTPUT TRANSPORT SEAM ===================================================== +// picogame's compositor (picogame_blit_strip_layers) is OUTPUT-AGNOSTIC: it composites +// scene layers into a plain wire-order RGB565 strip buffer, knowing nothing about the +// destination. A physical display is reached only through the small transport contract +// below, so a non-CircuitPython port (e.g. a MicroPython framebuf/SPI backend) can reuse +// the whole compositor AND the generic picogame_render_region orchestrator and reimplement +// ONLY these few functions. `picogame_output_t` is the opaque display handle they take. +// (A RAM-framebuffer destination is a separate backend: picogame_render_framebuffer.) +// +// Strip-path contract a backend provides: +// picogame_strip_begin - open a window for [x0,y0,x1,y1); return strip geometry +// picogame_out_strip_send - push one composited strip (region_w*sh px, wire RGB565; packed to +// RGB444 first when that panel is in 12-bit mode) +// picogame_out_strip_end - close the transaction +// picogame_set_invert - panel hardware colour inversion (a free full-screen flash) +// picogame_set_pixel_format - panel COLMOD (RGB565/RGB444), when CIRCUITPY_PICOGAME_RGB444 +// +// CircuitPython backend: picogame_output_t == busdisplay; the impl lives in __init__.c. +typedef busdisplay_busdisplay_obj_t picogame_output_t; + +// Q15 sine of a whole-degree angle in 0..360, from the quarter-wave table. +int32_t picogame_sin_q15_reduced(int deg); + +// floor((a * dd) / 65536) with 32-bit multiplies. Exact for a <= 2^16, dd <= 2^24. +static inline int32_t pg_mulshr16(uint32_t a, uint32_t dd) { + return (int32_t)(a * (dd >> 16) + ((a * (dd & 0xFFFF)) >> 16)); +} + +// Fill a strip with background, then composite items (sprites and tilemaps) in +// order (items[0] = bottom). kinds[i] selects the type; kinds == NULL means +// every item is a sprite. (ox, oy) is the view offset added to item positions +// (scene space -> screen space) for camera/centering. +// Returns a latched BaseException (Ctrl-C / ReloadException) raised by a StripDraw callback, or +// MP_OBJ_NULL. The caller must re-raise it AFTER closing the display transaction. +mp_obj_t picogame_blit_strip_layers( + uint16_t *buf, int region_w, int strip_top, int strip_h, int x0, + mp_obj_t *items, uint8_t *kinds, size_t n, uint16_t background, int ox, int oy); + +// Compute strip geometry and open a render window on the display (set region, +// begin transaction, send RAMWR). Returns false if the region is empty; raises +// if the buffer is too small for the region width. Fills *region_w and *strip_h. +bool picogame_strip_begin( + picogame_output_t *display, + int *x0, int *y0, int *x1, int *y1, size_t buffer_pixels, + int *region_w, int *strip_h); // clamps *x0..*y1 to the panel in place (caller loops on them) + +// Portable backend: strip-render a layered scene region to ANY busdisplay via +// its (blocking) bus.send - single buffer, no DMA. Same layer dispatch as the +// fast path (kinds + view offset), so it is the cross-port fallback for Scene on +// targets without the platform DMA Display. `kinds == NULL` => all sprites. +void picogame_render_region( + picogame_output_t *display, + mp_obj_t *items, uint8_t *kinds, size_t n, + uint16_t *buffer, size_t buffer_pixels, + int16_t x0, int16_t y0, int16_t x1, int16_t y1, + uint16_t background, int ox, int oy); + +// Toggle the panel's hardware colour inversion (INVON/INVOFF) - a free full-screen flash. +void picogame_set_invert(picogame_output_t *display, bool on); + +#if CIRCUITPY_PICOGAME_FRAMEBUFFER +// Emulated invert for a picogame.Framebuffer target (no hardware INVON): set the flag (XORed into the +// wire->native conversion) and, via take_invert_dirty(), force one whole-frame recomposite on toggle. +void picogame_fb_set_invert(bool on); +bool picogame_fb_take_invert_dirty(void); +#endif + +#if CIRCUITPY_PICOGAME_RGB444 // compiled in only on boards that opt into RGB444 (default off) +// Set panel pixel format (COLMOD): rgb444 -> 12-bit RGB444, else 16-bit RGB565. +void picogame_set_pixel_format(picogame_output_t *display, bool rgb444); + +// Put a panel left in RGB444 back to RGB565 at the end of a program, so the console stays +// readable. Call before reset_displays(). +void picogame_reset(void); + +// Pack `npix` (even) wire-order RGB565 pixels in `buf` IN-PLACE to 12-bit RGB444; returns bytes. +size_t picogame_pack_rgb444(uint16_t *buf, size_t npix); +#endif + +// Universal sprite-only convenience wrapper over picogame_render_region. +void picogame_render( + picogame_output_t *display, + mp_obj_t *items, size_t n, + uint16_t *buffer, size_t buffer_pixels, + int16_t x0, int16_t y0, int16_t x1, int16_t y1, + uint16_t background); + +#if CIRCUITPY_PICOGAME_FRAMEBUFFER +// Rows per compose band for the tear-free NATIVE framebuffer path: composite+byte-swap into a +// private scratch strip, then memcpy the finished NATIVE band into the live scanout buffer - so a +// picodvi/HDMI beam scanning the framebuffer never samples a half-composed WIRE-order region (which +// would read as byte-swapped / pink). Small band = small scratch (width*this*2 bytes). +#define PICOGAME_FB_SCRATCH_H 16 +// A render TARGET that is a caller-owned RAM framebuffer (wire-order RGB565), used in +// place of a BusDisplay for scanout-buffer platforms: the WASM playground (heap +// buffer read out to a canvas), the desktop sim, and FruitJam (the DVI/HSTX scanout +// buffer). Holds a WriteableBuffer alive + a typed view of it; allocation is the +// caller's (a bytearray in WASM, the DVI buffer memoryview on FruitJam), so the engine +// stays platform-neutral. Scene / render can target this instead of a display. +// Output pixel format of a picogame.Framebuffer target. The compositor always works in +// wire-order RGB565; the format only selects the publish conversion. +enum { + PICOGAME_FB_WIRE565 = 0, // no conversion (WASM playground / sim readout) + PICOGAME_FB_NATIVE565 = 1, // byte-swap to native RGB565 (picodvi 16-bit scanout) + PICOGAME_FB_RGB332 = 2, // quantize to RGB332 bytes (picodvi 8-bit scanout, e.g. + // Fruit Jam 640x480 - its max resolution is 8bpp-only) +}; + +typedef struct { + mp_obj_base_t base; + mp_obj_t buffer; // the backing WriteableBuffer (kept alive) + uint16_t *fb; // typed view of buffer.buf: width*height px - RGB565 (2 B/px) for the + // 565 formats; cast to uint8_t* per-pixel bytes for PICOGAME_FB_RGB332 + int width; + int height; + uint8_t fmt; // PICOGAME_FB_* output format (see enum above) + mp_obj_t scratch_buf; // GC-kept bytearray backing `scratch`; mp_const_none if none + uint16_t *scratch; // private compose strip: width*scratch_rows px, or NULL + int scratch_rows; // rows in `scratch` (PICOGAME_FB_SCRATCH_H), 0 if none +} picogame_framebuffer_obj_t; + +// Full-frame RAM-framebuffer backend: same layered compositor as the SPI strip path +// but composited straight into a caller-owned wire-order RGB565 framebuffer (no bus). +// The shared render target for scanout-buffer platforms (RP2350 DVI/HSTX, sim, WASM). +// [x0,y0,x1,y1) is the region to (re)composite (clamped to the framebuffer). Returns a +// latched StripDraw BaseException for the caller to re-raise, or MP_OBJ_NULL. +mp_obj_t picogame_render_framebuffer( + uint16_t *fb, int fb_stride, int fb_h, int fmt, + uint16_t *scratch, int scratch_rows, + mp_obj_t *items, uint8_t *kinds, size_t n, + int x0, int y0, int x1, int y1, + uint16_t background, int ox, int oy); +#endif // CIRCUITPY_PICOGAME_FRAMEBUFFER diff --git a/shared-module/picogame/pg_compat.h b/shared-module/picogame/pg_compat.h new file mode 100644 index 00000000000..92c4168f6d8 --- /dev/null +++ b/shared-module/picogame/pg_compat.h @@ -0,0 +1,64 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT +// +// pg_compat.h — the small CircuitPython core-API delta the picogame engine relies on, +// OWNED BY THE ENGINE (not injected by a build-level force-`-include`). On CircuitPython +// this is a pure pass-through (every symbol is native); on a bare MicroPython build it +// supplies the ~9-symbol delta CP added over MicroPython. This lets the SAME engine C +// compile on both without a per-build shim impersonating CircuitPython. +// +// Engine TUs `#include "shared-module/picogame/pg_compat.h"` where they use any of these +// (it replaces the former `#include "py/objproperty.h"` in the bindings TUs). The function +// bodies for the MicroPython branch live in pg_compat_mp.c (compiled ONLY on MicroPython). +#pragma once + +#include "py/runtime.h" + +#if defined(CIRCUITPY) +// CircuitPython: everything below is native — pure pass-through. +#include "py/objproperty.h" +#else +// MicroPython: the core-API delta the engine needs that bare MicroPython lacks. +#include "py/obj.h" + +#ifndef RUN_BACKGROUND_TASKS +#define RUN_BACKGROUND_TASKS (mp_handle_pending(MP_HANDLE_PENDING_CALLBACKS_AND_EXCEPTIONS)) +#endif +#ifndef m_malloc_without_collect +#define m_malloc_without_collect(n) m_malloc(n) +#endif +#ifndef mp_raise_RuntimeError +#define mp_raise_RuntimeError(msg) mp_raise_msg(&mp_type_RuntimeError, (msg)) +#endif + +mp_int_t mp_arg_validate_int_min(mp_int_t i, mp_int_t min, qstr arg_name); +mp_int_t mp_arg_validate_int_range(mp_int_t i, mp_int_t min, mp_int_t max, qstr arg_name); +mp_obj_t mp_arg_validate_type(mp_obj_t obj, const mp_obj_type_t *type, qstr arg_name); +NORETURN void mp_raise_ValueError_varg(mp_rom_error_text_t fmt, ...); +NORETURN void mp_raise_TypeError_varg(mp_rom_error_text_t fmt, ...); +mp_obj_t mp_obj_new_bytearray_of_zeros(size_t n); + +// CircuitPython's MP_PROPERTY_GETTER / MP_PROPERTY_GETSET convenience macros. Bare +// MicroPython keeps the property object private to py/objproperty.c; redeclare the +// struct with MP's EXACT layout + the macros in the non-native form (identical to +// CircuitPython's own !MICROPY_PY_OBJ_PROPERTY_NATIVE branch), so the generated +// property objects are ABI-compatible with MP's mp_type_property. +#if MICROPY_PY_BUILTINS_PROPERTY +typedef struct _mp_obj_property_t { + mp_obj_base_t base; + mp_obj_t proxy[3]; // getter, setter, deleter +} mp_obj_property_getset_t; +#ifndef MP_PROPERTY_GETTER +#define MP_PROPERTY_GETTER(P, G) \ + const mp_obj_property_getset_t P = { .base.type = &mp_type_property, .proxy = {G, MP_ROM_NONE, MP_ROM_NONE} } +#endif +#ifndef MP_PROPERTY_GETSET +#define MP_PROPERTY_GETSET(P, G, S) \ + const mp_obj_property_getset_t P = { .base.type = &mp_type_property, .proxy = {G, S, MP_ROM_NONE} } +#endif +#endif // MICROPY_PY_BUILTINS_PROPERTY + +#endif // CIRCUITPY diff --git a/shared-module/picogame3d/__init__.c b/shared-module/picogame3d/__init__.c new file mode 100644 index 00000000000..f30b8c1d313 --- /dev/null +++ b/shared-module/picogame3d/__init__.c @@ -0,0 +1,227 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +#include "shared-module/picogame3d/__init__.h" +#include "shared-module/picogame/__init__.h" + +// Mark rows y0..h of the canvas dirty (the full width), in scene coordinates. +static void mark_rows(picogame_canvas_obj_t *cv, int y0) { + if (y0 < cv->h && cv->w > 0) { + picogame_canvas_dirty_union(cv, cv->x, cv->y + y0, cv->x + cv->w, cv->y + cv->h); + } +} + +// Number of low zero bits (log2 for a power of 2; 0 for non-pow2, caught by caller). +static int log2_pow2(unsigned v) { + int n = 0; + while ((v & 1) == 0 && v > 1) { + v >>= 1; + n++; + } + return n; +} + +// Fill pixels xs..xe (inclusive) of one canvas row, clipped to the row width. +static inline void row_span(uint16_t *row, int w, int xs, int xe, uint16_t color) { + if (xs < 0) { + xs = 0; + } + if (xe >= w) { + xe = w - 1; + } + if (xs <= xe) { + picogame_fill565(row + xs, xe - xs + 1, color); + } +} + +// One racing-road strip, all rows in one call (the OutRun-genre "draw_road" scanline loop - profiled +// at ~20-25 ms of Python on picobike: ~4 fill_rect boundary crossings + an int(float) phase per row). +// ri0 = the road-table row of THIS surface's row 0 (vy - horizon_base); negative rows are sky. +// tab = int16[ntab][5]: {edge_w, dash_hw, wb05_q8, wb07_q8, flags(bit0 = dashes allowed)} - static per +// game. rl/rr = per-frame integer road edges (road_edges output). d05/d07 = the frame's scrolling +// stripe/dash phases in Q8; the row's band parity is ((d05+wb05)>>8)&1, matching the Python +// int(d05f + wb05f) & 1 (both non-negative). colors = uint16[6]: {sky, road_a, road_b, rumble_a, +// rumble_b, dash}. Grass underneath and the finish-line chequer stay the caller's job (one fill_rect +// per strip / a few rows near the lap line - no reason to carry them in C). +void picogame3d_road(picogame_canvas_obj_t *cv, int ri0, + const int16_t *tab, int ntab, const int16_t *rl, const int16_t *rr, + int32_t d05_q8, int32_t d07_q8, const uint16_t *colors) { + int w = cv->w; + for (int ly = 0; ly < cv->h; ly++) { + int ri = ri0 + ly; + uint16_t *row = &cv->data[ly * w]; + if (ri < 0) { // above the horizon: sky + picogame_fill565(row, w, colors[0]); + continue; + } + if (ri >= ntab) { + ri = ntab - 1; + } + const int16_t *t = tab + ri * 5; + int band = (int)(((d05_q8 + t[2]) >> 8) & 1); + uint16_t road = band ? colors[1] : colors[2]; + uint16_t rumble = band ? colors[3] : colors[4]; + int l = rl[ri], r = rr[ri]; + if (r <= l) { + continue; + } + row_span(row, w, l, r - 1, road); // fill_rect(l, w=r-l) covers l..r-1 + int ew = t[0]; + row_span(row, w, l, l + ew - 1, rumble); + row_span(row, w, r - ew, r - 1, rumble); + if ((t[4] & 1) && (((d07_q8 + t[3]) >> 8) & 1)) { + int mid = (l + r) >> 1, dw = t[1]; + row_span(row, w, mid - dw, mid + dw - 1, colors[5]); + } + } + mark_rows(cv, 0); +} + +// Context + row walker for the mode7 loop (each row derives rowdist/steps from its own sy). +typedef struct { + picogame_canvas_obj_t *cv; + const uint8_t *data; + const uint16_t *pal; + int fmt, stride, shx, shy, mx, my, horizon, y_off; + int32_t z, rx0, ry0, rsx, rsy, cam_x, cam_y; + bool transp; + int32_t key; +} mode7_ctx_t; + +static void mode7_rows(void *arg, int lo, int hi) { + mode7_ctx_t *c = arg; + picogame_canvas_obj_t *cv = c->cv; + int w = cv->w; + #if defined(PICOGAME_HAS_INTERP) + int ltw = 16 - c->shx; + int lth = 16 - c->shy; + bool use_interp = (c->fmt == PICOGAME_FMT_PAL8) && !c->transp && c->pal != NULL + && c->stride == c->mx + 1 + && ltw >= 1 && lth >= 1 && ltw + lth <= 16; // lane1 shift = shy-ltw must be >= 0 + #endif + for (int sy = lo; sy < hi; sy++) { + int denom = (sy + c->y_off) - c->horizon; + if (denom <= 0) { + continue; + } + // 32-bit throughout (no 64-bit mul helper on the M0+): rowdist*coeff stays + // within int32 for sane camera params - the Python helper keeps z and the + // ray deltas small; extreme values degrade to wrong pixels, never a crash. + int32_t rowdist = c->z / denom; + int32_t stepx = (rowdist * c->rsx) >> 16; + int32_t stepy = (rowdist * c->rsy) >> 16; + int32_t fx = c->cam_x + ((rowdist * c->rx0) >> 16); + int32_t fy = c->cam_y + ((rowdist * c->ry0) >> 16); + uint16_t *drow = cv->data + sy * w; + #if defined(PICOGAME_HAS_INTERP) + if (use_interp) { + picogame3d_mode7_row_interp(drow, w, c->data, c->pal, + (uint32_t)fx, (uint32_t)fy, stepx, stepy, c->shx, c->shy, ltw, lth); + continue; + } + #endif + for (int sx = 0; sx < w; sx++) { + int tx = (fx >> c->shx) & c->mx, ty = (fy >> c->shy) & c->my; + uint16_t val; + if (src_pixel_s(c->fmt, c->data, c->pal, c->key, ty * c->stride + tx, &val)) { + drow[sx] = val; + } + fx += stepx; + fy += stepy; + } + } +} + +void picogame3d_mode7(picogame_canvas_obj_t *cv, picogame_bitmap_obj_t *tex, + int horizon, int y_off, int32_t z, int32_t rx0, int32_t ry0, int32_t rsx, int32_t rsy, + int32_t cam_x, int32_t cam_y) { + // Perspective ground plane (Mode-7 / floorcaster). For each screen row below + // `horizon`, distance = z / (row - horizon) (16.16); the texture-space coord + // of the left edge is cam + distance*ray0, stepping by distance*rayDelta per + // pixel; sample `tex` (power-of-2, so wrap = a mask, and world 1.0 = one tile + // via a shift, no multiply). Integer throughout - no FPU needed (RP2040). + if (tex == NULL) { + return; + } + int tw = tex->width, th = tex->height; + if ((tw & (tw - 1)) || (th & (th - 1))) { // require power-of-2 dims + return; + } + int shx = 16 - log2_pow2((unsigned)tw); // world(1.0) -> one full tile + int shy = 16 - log2_pow2((unsigned)th); + int mx = tw - 1, my = th - 1, stride = tex->stride; + int fmt = tex->format; + const uint8_t *data = tex->data; + const uint16_t *pal = tex->palette; + bool transp = tex->has_transparent; // still gates the interp fast path above + int32_t key = picogame_key_of(tex); + // sy is a row WITHIN this surface (a StripDraw view is a Canvas onto one strip); + // the absolute screen row is sy + y_off, so the horizon test uses that. y_off = 0 + // for a full-screen Canvas, = the strip's screen y for a StripDraw view (0-RAM floor). + int y0 = horizon - y_off + 1; + if (y0 < 0) { + y0 = 0; + } + mode7_ctx_t ctx = { + cv, data, pal, fmt, stride, shx, shy, mx, my, horizon, y_off, + z, rx0, ry0, rsx, rsy, cam_x, cam_y, transp, key + }; + mode7_rows(&ctx, y0, cv->h); + mark_rows(cv, y0); +} + +// sin of a Q16 degree angle: lerp between whole-degree LUT entries. The racing-road curvature is +// DOUBLE-integrated over ~170 rows, which amplifies whole-degree quantization into visible pixels +// (host-measured 9 px); one lerp per curvature eval brings the road within 1 px of the float original. +static int32_t pg_sin_q15_lerp(int64_t deg_q16) { + // Reduce once; d0 + 1 is then at most 360, which the table handles. + int d0 = (int)(deg_q16 >> 16) % 360; + if (d0 < 0) { + d0 += 360; + } + int32_t frac = (int32_t)(deg_q16 & 0xFFFF); + int32_t a = picogame_sin_q15_reduced(d0); + // Adjacent entries differ by < 600 and frac < 2^16, so this fits in 32 bits. + return a + (((picogame_sin_q15_reduced(d0 + 1) - a) * frac) >> 16); +} + +// (s * amp) >> 15 with 32-bit multiplies. Exact for |s| <= 2^15 and any int32 amp. +static inline int32_t pg_mulshr15(int32_t s, int32_t amp) { + uint32_t hi = (uint32_t)(amp >> 15) * (uint32_t)s; + int32_t lo = ((amp & 0x7FFF) * s) >> 15; + return (int32_t)(hi + (uint32_t)lo); +} + +// One racing-road frame's curve pass: the bottom-up curvature accumulator + per-row integer edges +// (the OutRun-genre "compute_road" loop - profiled at ~8-10 ms of Python on picobike; this is the +// batch-boundary rule in action: one C call does the frame's whole row loop). Fixed-point throughout: +// cx/ddx accumulate in Q16, curvature = two LUT sines of the world distance. cfg (int32[7]): +// [f1_q20, f2_q20, amp1k_q16, amp2k_q16, world_step, curve_step, d_row_off] - frequencies in +// Q20 degrees/world-unit (Q16 phase-drifts over a long run), amplitudes premultiplied by the +// per-row gain k, curvature re-evaluated every curve_step rows (it varies slowly). Edge stores use +// trunc-toward-zero to match the Python original's int(). Host-proven <=1 px absolute AND row-delta +// smoothness vs the float reference over 8k+ frames (road_edges_test.c). +void picogame3d_road_edges(int16_t *rl, int16_t *rr, const int32_t *hw_q16, int n, + int32_t cx_q16, int32_t dist, const int32_t *cfg) { + int32_t f1 = cfg[0], f2 = cfg[1], a1k = cfg[2], a2k = cfg[3]; + int32_t wstep = cfg[4], cstep = cfg[5], drow = cfg[6]; + int32_t cx = cx_q16, ddx = 0, ck = 0; + int cnt = 0; + for (int i = n - 1; i >= 0; i--) { + if (cnt == 0) { + int32_t d = dist + (drow - i) * wstep; + ck = pg_mulshr15(pg_sin_q15_lerp(((int64_t)d * f1) >> 4), a1k) + + pg_mulshr15(pg_sin_q15_lerp(((int64_t)d * f2) >> 4), a2k); + cnt = cstep; + } + cnt--; + ddx += ck; + cx += ddx; + int32_t vl = cx - hw_q16[i], vr = cx + hw_q16[i]; + rl[i] = (int16_t)(vl >= 0 ? (vl >> 16) : -((-vl) >> 16)); + rr[i] = (int16_t)(vr >= 0 ? (vr >> 16) : -((-vr) >> 16)); + } +} diff --git a/shared-module/picogame3d/__init__.h b/shared-module/picogame3d/__init__.h new file mode 100644 index 00000000000..caace3d22f9 --- /dev/null +++ b/shared-module/picogame3d/__init__.h @@ -0,0 +1,50 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Vladimir Smitka +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include "shared-module/picogame/Bitmap.h" +#include "shared-module/picogame/Canvas.h" + +// Hardware-FPU boards run project() on plain float32 - faster than the soft-float-equivalent +// fixed path and free of 16.16 range limits; no-FPU targets (Cortex-M0+) use integer 16.16. +// Only ONE path is compiled per board. The default follows the architecture; a build can +// override it with -DCIRCUITPY_PICOGAME3D_FLOAT=0/1. Xtensa has an FPU but uses the fixed path: +// its float divide is a library call that is slower than the 16.16 path. +// Python reads `picogame3d.FLOAT` to pack camera/point buffers to match. +#ifndef CIRCUITPY_PICOGAME3D_FLOAT +#if (defined(__ARM_FP) && (__ARM_FP != 0)) || (defined(__riscv_flen) && (__riscv_flen > 0)) +#define CIRCUITPY_PICOGAME3D_FLOAT (1) +#else +#define CIRCUITPY_PICOGAME3D_FLOAT (0) +#endif +#endif + +// Mode-7 perspective ground plane: fill rows below `horizon` with a receding view +// of `tex` (power-of-2 dims). Args are 16.16 fixed-point (a Python helper computes +// them from camera angle/pos/fov). See picogame3d_mode7 for the exact math. +void picogame3d_mode7(picogame_canvas_obj_t *cv, picogame_bitmap_obj_t *tex, + int horizon, int y_off, int32_t z, int32_t rx0, int32_t ry0, int32_t rsx, int32_t rsy, + int32_t cam_x, int32_t cam_y); + +// One racing-road strip: per-row spans (road/rumbles/dashes/sky) from precomputed tables. +void picogame3d_road(picogame_canvas_obj_t *cv, int ri0, + const int16_t *tab, int ntab, const int16_t *rl, const int16_t *rr, + int32_t d05_q8, int32_t d07_q8, const uint16_t *colors); + +// Racing-road curve pass (see the implementation comment in __init__.c). +void picogame3d_road_edges(int16_t *rl, int16_t *rr, const int32_t *hw_q16, int n, + int32_t cx_q16, int32_t dist, const int32_t *cfg); + +#if defined(PICOGAME_HAS_INTERP) +// rp2-port SIO-interpolator mode7 row walker. Fast path only: +// PAL8, opaque, stride == tw, log2(tw)+log2(th) <= 16; the caller guards and falls back. +void picogame3d_mode7_row_interp(uint16_t *dst, int n, + const uint8_t *tex, const uint16_t *pal, + uint32_t fx, uint32_t fy, int32_t stepx, int32_t stepy, + int shx, int shy, int ltw, int lth); +#endif diff --git a/shared-module/rainbowio/__init__.c b/shared-module/rainbowio/__init__.c index 8fdc8867666..20fd83a4fc4 100644 --- a/shared-module/rainbowio/__init__.c +++ b/shared-module/rainbowio/__init__.c @@ -7,7 +7,10 @@ #include "shared-bindings/rainbowio/__init__.h" int32_t colorwheel(mp_float_t pos) { - pos = pos - ((uint32_t)(pos / 256) * 256); + pos = pos - (mp_float_t)((int32_t)(pos / 256) * 256); + if (pos < 0) { + pos += 256; + } int shift1, shift2; if (pos < 85) { shift1 = 8; diff --git a/shared-module/random/__init__.c b/shared-module/random/__init__.c index 26d11313962..a45da46574a 100644 --- a/shared-module/random/__init__.c +++ b/shared-module/random/__init__.c @@ -20,9 +20,11 @@ static uint32_t yasmarang_pad = 0xeda4baba, yasmarang_n = 69, yasmarang_d = 233; static uint8_t yasmarang_dat = 0; +static bool yasmarang_seeded = false; static uint32_t yasmarang(void) { - if (yasmarang_pad == 0xeda4baba) { + if (!yasmarang_seeded) { + yasmarang_seeded = true; if (!common_hal_os_urandom((uint8_t *)&yasmarang_pad, sizeof(uint32_t))) { yasmarang_pad = common_hal_time_monotonic_ms() & 0xffffffff; } @@ -57,6 +59,7 @@ void shared_modules_random_seed(mp_uint_t seed) { yasmarang_n = 69; yasmarang_d = 233; yasmarang_dat = 0; + yasmarang_seeded = true; } mp_uint_t shared_modules_random_getrandbits(uint8_t n) { @@ -79,6 +82,16 @@ mp_int_t shared_modules_random_randrange(mp_int_t start, mp_int_t stop, mp_int_t return start + step * yasmarang_randbelow(n); } +mp_int_t shared_modules_random_randint(mp_int_t a, mp_int_t b) { + // Compute the span unsigned so that b - a + 1 cannot overflow for any a <= b. + mp_uint_t n = (mp_uint_t)b - (mp_uint_t)a + 1; + if (n == 0) { + // a and b cover the full mp_int_t range: any value is in range. + return a + (mp_int_t)yasmarang(); + } + return a + yasmarang_randbelow(n); +} + // returns a number in the range [0..1) using Yasmarang to fill in the fraction bits static mp_float_t yasmarang_float(void) { #if MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE diff --git a/shared-module/rgbmatrix/RGBMatrix.c b/shared-module/rgbmatrix/RGBMatrix.c index db14c6a6b0d..554fd84c323 100644 --- a/shared-module/rgbmatrix/RGBMatrix.c +++ b/shared-module/rgbmatrix/RGBMatrix.c @@ -15,6 +15,7 @@ #include "common-hal/rgbmatrix/RGBMatrix.h" #include "shared-module/rgbmatrix/allocator.h" #include "shared-bindings/rgbmatrix/RGBMatrix.h" +#include "shared-bindings/digitalio/DigitalInOut.h" #include "shared-bindings/microcontroller/Pin.h" #include "shared-bindings/microcontroller/__init__.h" #include "shared-bindings/util.h" @@ -22,18 +23,120 @@ extern Protomatter_core *_PM_protoPtr; -static void common_hal_rgbmatrix_rgbmatrix_construct1(rgbmatrix_rgbmatrix_obj_t *self, mp_obj_t framebuffer); +static void common_hal_rgbmatrix_rgbmatrix_construct1(rgbmatrix_rgbmatrix_obj_t *self, mp_obj_t framebuffer, ProtomatterRowAddressMode row_address_mode); -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) { +static void preflight_pins_or_throw(const mcu_pin_obj_t *clock_pin_obj, const mcu_pin_obj_t **rgb_pin_objs, uint8_t rgb_pin_count, bool allow_inefficient) { + if (rgb_pin_count <= 0 || rgb_pin_count % 6 != 0 || rgb_pin_count > 30) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("The length of rgb_pins must be 6, 12, 18, 24, or 30")); + } + +// Most ports have a strict requirement for how the rgbmatrix pins are laid +// out; these two micros don't. Special-case it here. + #if !defined(CONFIG_IDF_TARGET_ESP32S3) && !defined(CONFIG_IDF_TARGET_ESP32S2) + uint8_t clock_pin = common_hal_mcu_pin_number(clock_pin_obj); + uint32_t port = clock_pin / 32; + uint32_t bit_mask = 1 << (clock_pin % 32); + + for (uint8_t i = 0; i < rgb_pin_count; i++) { + uint8_t pin_number = common_hal_mcu_pin_number(rgb_pin_objs[i]); + uint32_t pin_port = pin_number / 32; + + if (pin_port != port) { + mp_raise_ValueError_varg( + MP_ERROR_TEXT("rgb_pins[%d] is not on the same port as clock"), i); + } + + uint32_t pin_mask = 1 << (pin_number % 32); + if (pin_mask & bit_mask) { + mp_raise_ValueError_varg( + MP_ERROR_TEXT("rgb_pins[%d] duplicates another pin assignment"), i); + } + + bit_mask |= pin_mask; + } + + if (allow_inefficient) { + return; + } + + uint8_t byte_mask = 0; + if (bit_mask & 0x000000FF) { + byte_mask |= 0b0001; + } + if (bit_mask & 0x0000FF00) { + byte_mask |= 0b0010; + } + if (bit_mask & 0x00FF0000) { + byte_mask |= 0b0100; + } + if (bit_mask & 0xFF000000) { + byte_mask |= 0b1000; + } + + uint8_t bytes_per_element = 0xff; + uint8_t ideal_bytes_per_element = (rgb_pin_count + 7) / 8; + + switch (byte_mask) { + case 0b0001: + case 0b0010: + case 0b0100: + case 0b1000: + bytes_per_element = 1; + break; + + case 0b0011: + case 0b1100: + bytes_per_element = 2; + break; + + default: + bytes_per_element = 4; + break; + } + + if (bytes_per_element != ideal_bytes_per_element) { + mp_raise_ValueError_varg( + MP_ERROR_TEXT("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"), + bytes_per_element, ideal_bytes_per_element); + } + #endif +} + +// Claim each pin by wrapping it in a DigitalInOut object owned by the matrix. +// The DigitalInOut lives on the port heap (not the VM heap) because the matrix +// itself lives in the static display bus storage and survives VM resets. +static void store_pin_digitalinout(rgbmatrix_rgbmatrix_obj_t *self, const mcu_pin_obj_t *pin) { + digitalio_digitalinout_obj_t *digitalinout = mp_obj_port_malloc(digitalio_digitalinout_obj_t, &digitalio_digitalinout_type); + if (digitalinout == NULL) { + m_malloc_fail(sizeof(digitalio_digitalinout_obj_t)); + } + common_hal_digitalio_digitalinout_construct(digitalinout, pin); + self->pin_digitalinouts[self->pin_digitalinout_count++] = digitalinout; +} + +void common_hal_rgbmatrix_rgbmatrix_construct(rgbmatrix_rgbmatrix_obj_t *self, int width, int bit_depth, uint8_t rgb_count, const mcu_pin_obj_t **rgb_pins, uint8_t addr_count, const mcu_pin_obj_t **addr_pins, const mcu_pin_obj_t *clock_pin, const mcu_pin_obj_t *latch_pin, const mcu_pin_obj_t *oe_pin, bool doublebuffer, mp_obj_t framebuffer, int8_t tile, bool serpentine, void *timer, uint8_t row_addr_count, ProtomatterRowAddressMode row_address_mode) { self->width = width; self->bit_depth = bit_depth; self->rgb_count = rgb_count; - memcpy(self->rgb_pins, rgb_pins, rgb_count); + preflight_pins_or_throw(clock_pin, rgb_pins, rgb_count, true); + // Claim and configure each pin by wrapping it in a DigitalInOut owned by the + // matrix. This runs before Protomatter configures the pins so its setup wins. + for (uint8_t i = 0; i < rgb_count; i++) { + store_pin_digitalinout(self, rgb_pins[i]); + self->rgb_pins[i] = common_hal_mcu_pin_number(rgb_pins[i]); + } self->addr_count = addr_count; - memcpy(self->addr_pins, addr_pins, addr_count); - self->clock_pin = clock_pin; - self->oe_pin = oe_pin; - self->latch_pin = latch_pin; + self->row_addr_count = row_addr_count; + for (uint8_t i = 0; i < addr_count; i++) { + store_pin_digitalinout(self, addr_pins[i]); + self->addr_pins[i] = common_hal_mcu_pin_number(addr_pins[i]); + } + store_pin_digitalinout(self, clock_pin); + self->clock_pin = common_hal_mcu_pin_number(clock_pin); + store_pin_digitalinout(self, oe_pin); + self->oe_pin = common_hal_mcu_pin_number(oe_pin); + store_pin_digitalinout(self, latch_pin); + self->latch_pin = common_hal_mcu_pin_number(latch_pin); self->doublebuffer = doublebuffer; self->tile = tile; self->serpentine = serpentine; @@ -46,10 +149,11 @@ void common_hal_rgbmatrix_rgbmatrix_construct(rgbmatrix_rgbmatrix_obj_t *self, i self->width = width; self->bufsize = 2 * width * common_hal_rgbmatrix_rgbmatrix_get_height(self); - common_hal_rgbmatrix_rgbmatrix_construct1(self, framebuffer); + common_hal_rgbmatrix_rgbmatrix_construct1(self, framebuffer, row_address_mode); } -static void common_hal_rgbmatrix_rgbmatrix_construct1(rgbmatrix_rgbmatrix_obj_t *self, mp_obj_t framebuffer) { +static void common_hal_rgbmatrix_rgbmatrix_construct1(rgbmatrix_rgbmatrix_obj_t *self, mp_obj_t framebuffer, ProtomatterRowAddressMode row_address_mode) { + self->framebuffer = framebuffer; if (framebuffer != mp_const_none) { mp_get_buffer_raise(self->framebuffer, &self->bufinfo, MP_BUFFER_READ); if (mp_get_buffer(self->framebuffer, &self->bufinfo, MP_BUFFER_RW)) { @@ -67,16 +171,15 @@ static void common_hal_rgbmatrix_rgbmatrix_construct1(rgbmatrix_rgbmatrix_obj_t self->bufinfo.len = self->bufsize; self->bufinfo.typecode = 'H' | MP_OBJ_ARRAY_TYPECODE_FLAG_RW; } - self->framebuffer = framebuffer; memset(&self->protomatter, 0, sizeof(self->protomatter)); - ProtomatterStatus stat = _PM_init(&self->protomatter, + ProtomatterStatus stat = _PM_init_with_row_address_mode(&self->protomatter, self->width, self->bit_depth, self->rgb_count / 6, self->rgb_pins, - self->addr_count, self->addr_pins, + self->row_addr_count, self->addr_pins, self->clock_pin, self->latch_pin, self->oe_pin, self->doublebuffer, self->serpentine ? -self->tile : self->tile, - self->timer); + self->timer, row_address_mode); if (stat == PROTOMATTER_OK) { _PM_protoPtr = &self->protomatter; @@ -114,22 +217,20 @@ static void common_hal_rgbmatrix_rgbmatrix_construct1(rgbmatrix_rgbmatrix_obj_t self->paused = 0; } -static void free_pin(uint8_t *pin) { - if (*pin != COMMON_HAL_MCU_NO_PIN) { - common_hal_mcu_pin_reset_number(*pin); - } - *pin = COMMON_HAL_MCU_NO_PIN; -} - -static void free_pin_seq(uint8_t *seq, int count) { - for (int i = 0; i < count; i++) { - free_pin(&seq[i]); +static void deinit_pin_digitalinouts(rgbmatrix_rgbmatrix_obj_t *self) { + for (uint8_t i = 0; i < self->pin_digitalinout_count; i++) { + common_hal_digitalio_digitalinout_deinit(self->pin_digitalinouts[i]); + port_free(self->pin_digitalinouts[i]); + self->pin_digitalinouts[i] = NULL; } + self->pin_digitalinout_count = 0; } extern int pm_row_count; static void common_hal_rgbmatrix_rgbmatrix_deinit1(rgbmatrix_rgbmatrix_obj_t *self) { - common_hal_rgbmatrix_timer_disable(self->timer); + if (self->timer) { + common_hal_rgbmatrix_timer_disable(self->timer); + } if (_PM_protoPtr == &self->protomatter) { _PM_protoPtr = NULL; @@ -160,11 +261,7 @@ void common_hal_rgbmatrix_rgbmatrix_deinit(rgbmatrix_rgbmatrix_obj_t *self) { self->timer = 0; } - free_pin_seq(self->rgb_pins, self->rgb_count); - free_pin_seq(self->addr_pins, self->addr_count); - free_pin(&self->clock_pin); - free_pin(&self->latch_pin); - free_pin(&self->oe_pin); + deinit_pin_digitalinouts(self); self->base.type = &mp_type_NoneType; } @@ -221,6 +318,6 @@ int common_hal_rgbmatrix_rgbmatrix_get_width(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; + int computed_height = (self->rgb_count / 3) * (1 << self->row_addr_count) * self->tile; return computed_height; } diff --git a/shared-module/rgbmatrix/RGBMatrix.h b/shared-module/rgbmatrix/RGBMatrix.h index 197bbb264af..6104293b5e9 100644 --- a/shared-module/rgbmatrix/RGBMatrix.h +++ b/shared-module/rgbmatrix/RGBMatrix.h @@ -8,6 +8,7 @@ #include "py/obj.h" #include "lib/protomatter/src/core.h" +#include "shared-bindings/digitalio/DigitalInOut.h" extern const mp_obj_type_t rgbmatrix_RGBMatrix_type; typedef struct { @@ -21,11 +22,15 @@ typedef struct { uint8_t rgb_pins[30]; uint8_t addr_pins[10]; uint8_t clock_pin, latch_pin, oe_pin; - uint8_t rgb_count, addr_count; + uint8_t rgb_count, addr_count, row_addr_count; uint8_t bit_depth; bool core_is_initialized; bool paused; bool doublebuffer; bool serpentine; int8_t tile; + // DigitalInOut objects that own each of the pins. They claim the pins and + // release them when they are deinitialized. + digitalio_digitalinout_obj_t *pin_digitalinouts[30 + 10 + 3]; + uint8_t pin_digitalinout_count; } rgbmatrix_rgbmatrix_obj_t; diff --git a/shared-module/sdcardio/SDCard.c b/shared-module/sdcardio/SDCard.c index a8e6248577a..35d247bfa91 100644 --- a/shared-module/sdcardio/SDCard.c +++ b/shared-module/sdcardio/SDCard.c @@ -7,15 +7,18 @@ // This implementation largely follows the structure of adafruit_sdcard.py #include "extmod/vfs.h" - #include "shared-bindings/busio/SPI.h" #include "shared-bindings/digitalio/DigitalInOut.h" #include "shared-bindings/sdcardio/SDCard.h" #include "shared-bindings/time/__init__.h" #include "shared-bindings/util.h" #include "shared-module/sdcardio/SDCard.h" +#include "supervisor/shared/tick.h" #include "py/mperrno.h" +#include "py/mphal.h" +#include "py/gc.h" +#include "supervisor/port.h" #if 0 #define DEBUG_PRINT(...) ((void)mp_printf(&mp_plat_print,##__VA_ARGS__)) @@ -23,7 +26,17 @@ #define DEBUG_PRINT(...) ((void)0) #endif -#define CMD_TIMEOUT (200) +// https://nodeloop.org/guides/sd-card-spi-init-guide/ is an excellent source of info for SPI card use. + +// https://www.taterli.com/wp-content/uploads/2017/05/Physical-Layer-Simplified-SpecificationV6.0.pdf +// specifies timeouts for read (100 ms), write (250 ms), erase (depends on size), and other operations. +// cmd timeout was 250, but did not work on some cards. +// See https://github.com/adafruit/circuitpython/issues/10954 +#define CMD_TIMEOUT_MS (500) +#define SPI_TIMEOUT_MS (250) +// Init ready timeout. +#define READY_TIMEOUT_MS (300) + #define R1_IDLE_STATE (1 << 0) #define R1_ILLEGAL_COMMAND (1 << 2) @@ -32,35 +45,50 @@ #define TOKEN_STOP_TRAN (0xFD) #define TOKEN_DATA (0xFE) +bool common_hal_sdcardio_sdcard_deinited(sdcardio_sdcard_obj_t *self) { + // Also check SPI bus was deinited out from under us. + if (!self->bus || common_hal_busio_spi_deinited(self->bus)) { + return true; + } + return false; +} + +void common_hal_sdcardio_sdcard_mark_deinit(sdcardio_sdcard_obj_t *self) { + self->bus = NULL; +} + static void common_hal_sdcardio_check_for_deinit(sdcardio_sdcard_obj_t *self) { - if (!self->bus) { + if (common_hal_sdcardio_sdcard_deinited(self)) { raise_deinited_error(); } } static bool lock_and_configure_bus(sdcardio_sdcard_obj_t *self) { - common_hal_sdcardio_check_for_deinit(self); + if (common_hal_sdcardio_sdcard_deinited(self)) { + return false; + } - if (!common_hal_busio_spi_try_lock(self->bus)) { + if (!common_hal_busio_spi_wait_for_lock(self->bus, SPI_TIMEOUT_MS)) { return false; } - common_hal_busio_spi_configure(self->bus, self->baudrate, 0, 0, 8); - common_hal_digitalio_digitalinout_set_value(&self->cs, false); - return true; -} -static void lock_bus_or_throw(sdcardio_sdcard_obj_t *self) { - if (!lock_and_configure_bus(self)) { - mp_raise_OSError(EAGAIN); + // Make sure we can still use the SPI bus after grabbing the lock. + // The VM might be in the process of shutting down, and there could be a race. + if (!vm_is_running() && !self->persistent_mount) { + common_hal_busio_spi_unlock(self->bus); + return false; } + + common_hal_busio_spi_configure(self->bus, self->baudrate, 0, 0, 8); + digitalinout_protocol_set_value(self->cs, false); + return true; } 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; i < bytes; i++) { - common_hal_busio_spi_write(self->bus, buf, 1); - } + uint8_t buf[bytes]; + memset(buf, 0xff, bytes); + digitalinout_protocol_set_value(self->cs, true); + common_hal_busio_spi_write(self->bus, buf, bytes); } static void extraclock_and_unlock_bus(sdcardio_sdcard_obj_t *self) { @@ -83,21 +111,35 @@ static uint8_t CRC7(const uint8_t *data, uint8_t n) { return (crc << 1) | 1; } -#define READY_TIMEOUT_NS (300 * 1000 * 1000) // 300ms -static int wait_for_ready(sdcardio_sdcard_obj_t *self) { - uint64_t deadline = common_hal_time_monotonic_ns() + READY_TIMEOUT_NS; - while (common_hal_time_monotonic_ns() < deadline) { +// Assumes that the spi lock has been acquired. +// +// Mask the incoming value with mask. Use 0xff to not mask. +// if not_match is true, wait for something NOT matching the value. +// Return the response as an int32_t (which is always >= 0), or -1 if timed out. +static int32_t wait_for_masked_response(sdcardio_sdcard_obj_t *self, uint8_t mask, uint8_t response, bool not_match, uint32_t timeout_ms) { + uint64_t deadline = supervisor_ticks_ms64() + timeout_ms; + while (supervisor_ticks_ms64() < deadline) { uint8_t b; common_hal_busio_spi_read(self->bus, &b, 1, 0xff); - if (b == 0xff) { - return 0; + if (((b & mask) == response) ^ not_match) { + return b; } } - return -ETIMEDOUT; + return -1; +} + +// Wait for the given response byte. +static bool wait_for_response(sdcardio_sdcard_obj_t *self, uint8_t response) { + return wait_for_masked_response(self, 0xff, response, false, CMD_TIMEOUT_MS) != -1; +} + +// Wait for 0xff, with a specific timeout. +static bool wait_for_ready(sdcardio_sdcard_obj_t *self) { + return wait_for_masked_response(self, 0xff, 0xff, false, READY_TIMEOUT_MS) != -1; } // Note: this is never called while "in cmd25" (in fact, it's only used by `exit_cmd25`) -static bool cmd_nodata(sdcardio_sdcard_obj_t *self, int cmd, int response) { +static mp_negative_errno_t cmd_nodata(sdcardio_sdcard_obj_t *self, int cmd, int response) { uint8_t cmdbuf[2] = {cmd, 0xff}; assert(!self->in_cmd25); @@ -105,17 +147,14 @@ static bool cmd_nodata(sdcardio_sdcard_obj_t *self, int cmd, int response) { common_hal_busio_spi_write(self->bus, cmdbuf, sizeof(cmdbuf)); // Wait for the response (response[7] == response) - for (int i = 0; i < CMD_TIMEOUT; i++) { - common_hal_busio_spi_read(self->bus, cmdbuf, 1, 0xff); - if (cmdbuf[0] == response) { - return 0; - } + if (wait_for_response(self, response)) { + return 0; } - return -EIO; + return -MP_EIO; } -static int exit_cmd25(sdcardio_sdcard_obj_t *self) { +static mp_negative_errno_t exit_cmd25(sdcardio_sdcard_obj_t *self) { if (self->in_cmd25) { DEBUG_PRINT("exit cmd25\n"); self->in_cmd25 = false; @@ -126,7 +165,7 @@ static int exit_cmd25(sdcardio_sdcard_obj_t *self) { // In Python API, defaults are response=None, data_block=True, wait=True static int cmd(sdcardio_sdcard_obj_t *self, int cmd, int arg, void *response_buf, size_t response_len, bool data_block, bool wait) { - int r = exit_cmd25(self); + mp_negative_errno_t r = exit_cmd25(self); if (r < 0) { return r; } @@ -141,48 +180,43 @@ static int cmd(sdcardio_sdcard_obj_t *self, int cmd, int arg, void *response_buf cmdbuf[5] = CRC7(cmdbuf, 5); if (wait) { - r = wait_for_ready(self); - if (r < 0) { - return r; + if (!wait_for_ready(self)) { + return -MP_ETIMEDOUT; } } common_hal_busio_spi_write(self->bus, cmdbuf, sizeof(cmdbuf)); // Wait for the response (response[7] == 0) - bool response_received = false; - for (int i = 0; i < CMD_TIMEOUT; i++) { - common_hal_busio_spi_read(self->bus, cmdbuf, 1, 0xff); - if ((cmdbuf[0] & 0x80) == 0) { - response_received = true; - break; - } - } - - if (!response_received) { - return -EIO; + // Now wait for cmd response, which is the high bit being 0. + int32_t response = wait_for_masked_response(self, 0x80, 0, false, CMD_TIMEOUT_MS); + if (response == -1) { + return -MP_EIO; } if (response_buf) { if (data_block) { cmdbuf[1] = 0xff; - do { - // Wait for the start block byte - common_hal_busio_spi_read(self->bus, cmdbuf + 1, 1, 0xff); - } while (cmdbuf[1] != 0xfe); + if (!wait_for_response(self, 0xfe)) { + return -MP_EIO; + } } - common_hal_busio_spi_read(self->bus, response_buf, response_len, 0xff); + if (!common_hal_busio_spi_read(self->bus, response_buf, response_len, 0xff)) { + return -MP_EIO; + } if (data_block) { // Read and discard the CRC-CCITT checksum - common_hal_busio_spi_read(self->bus, cmdbuf + 1, 2, 0xff); + if (!common_hal_busio_spi_read(self->bus, cmdbuf + 1, 2, 0xff)) { + return -MP_EIO; + } } } - return cmdbuf[0]; + return response; } static int block_cmd(sdcardio_sdcard_obj_t *self, int cmd_, int block, void *response_buf, size_t response_len, bool data_block, bool wait) { @@ -190,7 +224,8 @@ static int block_cmd(sdcardio_sdcard_obj_t *self, int cmd_, int block, void *res } static mp_rom_error_text_t init_card_v1(sdcardio_sdcard_obj_t *self) { - for (int i = 0; i < CMD_TIMEOUT; i++) { + uint64_t deadline = supervisor_ticks_ms64() + CMD_TIMEOUT_MS; + while (supervisor_ticks_ms64() < deadline) { if (cmd(self, 41, 0, NULL, 0, true, true) == 0) { return NULL; } @@ -199,7 +234,8 @@ static mp_rom_error_text_t init_card_v1(sdcardio_sdcard_obj_t *self) { } static mp_rom_error_text_t init_card_v2(sdcardio_sdcard_obj_t *self) { - for (int i = 0; i < CMD_TIMEOUT; i++) { + uint64_t deadline = supervisor_ticks_ms64() + CMD_TIMEOUT_MS; + while (supervisor_ticks_ms64() < deadline) { uint8_t ocr[4]; common_hal_time_delay_ms(50); cmd(self, 58, 0, ocr, sizeof(ocr), false, true); @@ -216,9 +252,11 @@ static mp_rom_error_text_t init_card_v2(sdcardio_sdcard_obj_t *self) { } static mp_rom_error_text_t init_card(sdcardio_sdcard_obj_t *self) { + // https://nodeloop.org/guides/sd-card-spi-init-guide/ recommends at least 74 bit clocks + // and says 80 bit clocks(10*8) is common. Value below is bytes, not bits. clock_card(self, 10); - common_hal_digitalio_digitalinout_set_value(&self->cs, false); + digitalinout_protocol_set_value(self->cs, false); assert(!self->in_cmd25); self->in_cmd25 = false; // should be false already @@ -274,7 +312,7 @@ static mp_rom_error_text_t init_card(sdcardio_sdcard_obj_t *self) { } if (csd_version == 1) { - self->sectors = ((csd[8] << 8 | csd[9]) + 1) * 1024; + self->sectors = (((csd[7] & 0x3F) << 16 | csd[8] << 8 | csd[9]) + 1) * 1024; } else { uint32_t block_length = 1 << (csd[5] & 0xF); uint32_t c_size = ((csd[6] & 0x3) << 10) | (csd[7] << 2) | ((csd[8] & 0xC) >> 6); @@ -294,34 +332,75 @@ static mp_rom_error_text_t init_card(sdcardio_sdcard_obj_t *self) { return NULL; } -void common_hal_sdcardio_sdcard_construct(sdcardio_sdcard_obj_t *self, busio_spi_obj_t *bus, const mcu_pin_obj_t *cs, int baudrate) { - self->bus = bus; - common_hal_digitalio_digitalinout_construct(&self->cs, cs); - common_hal_digitalio_digitalinout_switch_to_output(&self->cs, true, DRIVE_MODE_PUSH_PULL); +// Mark the object deinited, then release the CS pin if this object owns it. +static void mark_deinit_and_release_cs(sdcardio_sdcard_obj_t *self) { + common_hal_sdcardio_sdcard_mark_deinit(self); + if (self->own_cs) { + digitalinout_protocol_deinit(self->cs); + circuitpy_free_obj(self->cs); + self->own_cs = false; + } +} + +mp_rom_error_text_t sdcardio_sdcard_construct(sdcardio_sdcard_obj_t *self, busio_spi_obj_t *bus, mp_obj_t cs, int baudrate, bool persistent_mount) { + // Ensure the object starts in its deinit state, so its finaliser does + // nothing if this raises before the bus is set. + common_hal_sdcardio_sdcard_mark_deinit(self); + self->own_cs = false; + self->persistent_mount = persistent_mount; + + // Allocate the pins in the same place as self. + bool use_port_allocation = !gc_alloc_possible() || !gc_ptr_on_heap(self); + + self->cs = digitalinout_protocol_from_pin(cs, MP_QSTR_cs, false, use_port_allocation, &self->own_cs); + digitalinout_protocol_switch_to_output(self->cs, true, DRIVE_MODE_PUSH_PULL); self->cdv = 512; self->sectors = 0; + + // During initialization, talk to the SPI card between 100 khZ and 400 kHz. After that, can use full speed. self->baudrate = 250000; - lock_bus_or_throw(self); + // Set the bus last: the object is live from here, and talking to the card needs it. + self->bus = bus; + + if (!lock_and_configure_bus(self)) { + mark_deinit_and_release_cs(self); + mp_raise_OSError(EAGAIN); + } mp_rom_error_text_t result = init_card(self); extraclock_and_unlock_bus(self); if (result != NULL) { - common_hal_digitalio_digitalinout_deinit(&self->cs); - mp_raise_OSError_msg(result); + // Leave the object deinited, so its finaliser doesn't use the freed CS pin. + mark_deinit_and_release_cs(self); + return result; } self->baudrate = baudrate; + return NULL; +} + + +void common_hal_sdcardio_sdcard_construct(sdcardio_sdcard_obj_t *self, busio_spi_obj_t *bus, mp_obj_t cs, int baudrate) { + // User mounted, so persistent_mount=false. + mp_rom_error_text_t result = sdcardio_sdcard_construct(self, bus, cs, baudrate, false); + if (result != NULL) { + mp_raise_OSError_msg(result); + } } void common_hal_sdcardio_sdcard_deinit(sdcardio_sdcard_obj_t *self) { - if (!self->bus) { + // Already deinited. + if (self->bus == NULL) { return; } - common_hal_sdcardio_sdcard_sync(self); - self->bus = 0; - common_hal_digitalio_digitalinout_deinit(&self->cs); + // The SPI bus may already be deinited, for example board.SPI() at the end of the VM. + // Then skip the sync, but still release the CS pin. + if (!common_hal_busio_spi_deinited(self->bus)) { + common_hal_sdcardio_sdcard_sync(self); + } + mark_deinit_and_release_cs(self); } int common_hal_sdcardio_sdcard_get_blockcount(sdcardio_sdcard_obj_t *self) { @@ -330,23 +409,25 @@ int common_hal_sdcardio_sdcard_get_blockcount(sdcardio_sdcard_obj_t *self) { } static int readinto(sdcardio_sdcard_obj_t *self, void *buf, size_t size) { - uint8_t aux[2] = {0, 0}; - while (aux[0] != 0xfe) { - common_hal_busio_spi_read(self->bus, aux, 1, 0xff); + + if (!wait_for_response(self, 0xfe)) { + return -MP_EIO; } common_hal_busio_spi_read(self->bus, buf, size, 0xff); // Read checksum and throw it away - common_hal_busio_spi_read(self->bus, aux, sizeof(aux), 0xff); + uint8_t checksum[2]; + common_hal_busio_spi_read(self->bus, checksum, sizeof(checksum), 0xff); return 0; } +// The mp_uint_t is misleading; negative errors can be returned. mp_uint_t sdcardio_sdcard_readblocks(mp_obj_t self_in, uint8_t *buf, uint32_t start_block, uint32_t nblocks) { // deinit check is in lock_and_configure_bus() sdcardio_sdcard_obj_t *self = MP_OBJ_TO_PTR(self_in); if (!lock_and_configure_bus(self)) { - return MP_EAGAIN; + return -MP_ETIMEDOUT; } int r = 0; size_t buflen = 512 * nblocks; @@ -365,6 +446,9 @@ mp_uint_t sdcardio_sdcard_readblocks(mp_obj_t self_in, uint8_t *buf, uint32_t st ptr += 512; } + // Keep the first error: the CMD12 status below must not overwrite a failed read. + int read_r = r; + // End the multi-block read r = cmd(self, 12, 0, NULL, 0, true, false); @@ -377,8 +461,12 @@ mp_uint_t sdcardio_sdcard_readblocks(mp_obj_t self_in, uint8_t *buf, uint32_t st } r = single_byte; } + if (read_r != 0) { + r = read_r; + } } extraclock_and_unlock_bus(self); + // Negative errors reach the Python binding, which raises OSError. return r; } @@ -391,7 +479,9 @@ int common_hal_sdcardio_sdcard_readblocks(sdcardio_sdcard_obj_t *self, uint32_t } static int _write(sdcardio_sdcard_obj_t *self, uint8_t token, void *buf, size_t size) { - wait_for_ready(self); + if (!wait_for_ready(self)) { + return -MP_ETIMEDOUT; + } uint8_t cmd[2]; cmd[0] = token; @@ -414,12 +504,12 @@ static int _write(sdcardio_sdcard_obj_t *self, uint8_t token, void *buf, size_t // with STATUS 010 indicating "data accepted", and other status bit // combinations indicating failure. // In practice, I was seeing cmd[0] as 0xe5, indicating success - for (int i = 0; i < CMD_TIMEOUT; i++) { + uint64_t deadline = supervisor_ticks_ms64() + CMD_TIMEOUT_MS; + while (supervisor_ticks_ms64() < deadline) { common_hal_busio_spi_read(self->bus, cmd, 1, 0xff); - DEBUG_PRINT("i=%02d cmd[0] = 0x%02x\n", i, cmd[0]); if ((cmd[0] & 0b00010001) == 0b00000001) { if ((cmd[0] & 0x1f) != 0x5) { - return -EIO; + return -MP_EIO; } else { break; } @@ -427,9 +517,11 @@ static int _write(sdcardio_sdcard_obj_t *self, uint8_t token, void *buf, size_t } // Wait for the write to finish - do { - common_hal_busio_spi_read(self->bus, cmd, 1, 0xff); - } while (cmd[0] == 0); + + // Wait for a non-zero value. + if (wait_for_masked_response(self, 0xff /*mask*/, 0, true /*not_match*/, CMD_TIMEOUT_MS) == -1) { + return -MP_EIO; + } // Success return 0; @@ -439,7 +531,7 @@ mp_uint_t sdcardio_sdcard_writeblocks(mp_obj_t self_in, uint8_t *buf, uint32_t s // deinit check is in lock_and_configure_bus() sdcardio_sdcard_obj_t *self = MP_OBJ_TO_PTR(self_in); if (!lock_and_configure_bus(self)) { - return MP_EAGAIN; + return -MP_ETIMEDOUT; } if (!self->in_cmd25 || start_block != self->next_block) { @@ -471,23 +563,21 @@ mp_uint_t sdcardio_sdcard_writeblocks(mp_obj_t self_in, uint8_t *buf, uint32_t s return 0; } -int common_hal_sdcardio_sdcard_sync(sdcardio_sdcard_obj_t *self) { +mp_negative_errno_t common_hal_sdcardio_sdcard_sync(sdcardio_sdcard_obj_t *self) { // deinit check is in lock_and_configure_bus() - lock_and_configure_bus(self); + if (!lock_and_configure_bus(self)) { + return -MP_ETIMEDOUT; + } int r = exit_cmd25(self); extraclock_and_unlock_bus(self); return r; } -int common_hal_sdcardio_sdcard_writeblocks(sdcardio_sdcard_obj_t *self, uint32_t start_block, mp_buffer_info_t *buf) { - // deinit check is in lock_and_configure_bus() +mp_negative_errno_t common_hal_sdcardio_sdcard_writeblocks(sdcardio_sdcard_obj_t *self, uint32_t start_block, mp_buffer_info_t *buf) { if (buf->len % 512 != 0) { mp_raise_ValueError_varg(MP_ERROR_TEXT("Buffer must be a multiple of %d bytes"), 512); } - lock_and_configure_bus(self); - int r = sdcardio_sdcard_writeblocks(MP_OBJ_FROM_PTR(self), buf->buf, start_block, buf->len / 512); - extraclock_and_unlock_bus(self); - return r; + return sdcardio_sdcard_writeblocks(MP_OBJ_FROM_PTR(self), buf->buf, start_block, buf->len / 512); } bool sdcardio_sdcard_ioctl(mp_obj_t self_in, size_t cmd, size_t arg, mp_int_t *out_value) { @@ -495,11 +585,8 @@ bool sdcardio_sdcard_ioctl(mp_obj_t self_in, size_t cmd, size_t arg, mp_int_t *o *out_value = 0; switch (cmd) { case MP_BLOCKDEV_IOCTL_DEINIT: - common_hal_sdcardio_sdcard_sync(self); - break; // TODO properly case MP_BLOCKDEV_IOCTL_SYNC: - common_hal_sdcardio_sdcard_sync(self); - break; + return common_hal_sdcardio_sdcard_sync(self) == 0; case MP_BLOCKDEV_IOCTL_BLOCK_COUNT: *out_value = common_hal_sdcardio_sdcard_get_blockcount(self); break; diff --git a/shared-module/sdcardio/SDCard.h b/shared-module/sdcardio/SDCard.h index 0b315395aad..6af68c274cd 100644 --- a/shared-module/sdcardio/SDCard.h +++ b/shared-module/sdcardio/SDCard.h @@ -17,10 +17,16 @@ typedef struct { mp_obj_base_t base; busio_spi_obj_t *bus; - digitalio_digitalinout_obj_t cs; + mp_obj_t cs; int cdv; int baudrate; uint32_t sectors; uint32_t next_block; bool in_cmd25; + // Automounted SD cards are usually persistent across VM's. Note this as needed to allow access + // when the VM is not running. + bool persistent_mount; + bool own_cs; } sdcardio_sdcard_obj_t; + +mp_rom_error_text_t sdcardio_sdcard_construct(sdcardio_sdcard_obj_t *self, busio_spi_obj_t *bus, mp_obj_t cs, int baudrate, bool persistent_mount); diff --git a/shared-module/sdcardio/__init__.c b/shared-module/sdcardio/__init__.c index 72d32ef2b2c..47566c23042 100644 --- a/shared-module/sdcardio/__init__.c +++ b/shared-module/sdcardio/__init__.c @@ -3,3 +3,145 @@ // SPDX-FileCopyrightText: Copyright (c) 2024 Adafruit Industries LLC // // SPDX-License-Identifier: MIT + +#include "shared-module/sdcardio/__init__.h" + +#include "py/obj.h" + +#include "extmod/vfs_fat.h" + +#include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/busio/SPI.h" +#include "shared-bindings/digitalio/DigitalInOut.h" +#include "shared-bindings/sdcardio/SDCard.h" + +#include "supervisor/filesystem.h" +#include "supervisor/shared/settings.h" + +#ifdef DEFAULT_SD_CARD_DETECT +static digitalio_digitalinout_obj_t sd_card_detect_pin; +static sdcardio_sdcard_obj_t sdcard; + +static mp_vfs_mount_t _sdcard_vfs; +fs_user_mount_t _sdcard_usermount; + +static bool _init_error = false; +static bool _automounted = false; + +#ifdef DEFAULT_SD_MOSI +static busio_spi_obj_t busio_spi_obj; +#else +#include "shared-bindings/board/__init__.h" +#endif +#endif + +void sdcardio_init(void) { + #ifdef DEFAULT_SD_CARD_DETECT + sd_card_detect_pin.base.type = &digitalio_digitalinout_type; + common_hal_digitalio_digitalinout_construct(&sd_card_detect_pin, DEFAULT_SD_CARD_DETECT); + common_hal_digitalio_digitalinout_switch_to_input(&sd_card_detect_pin, PULL_UP); + #endif +} + +void automount_sd_card(void) { + #ifdef DEFAULT_SD_CARD_DETECT + #if CIRCUITPY_SETTINGS_TOML + // Honor the runtime CIRCUITPY_SDCARD_USB setting. When disabled, never + // claim the shared SD pins (SCK/MOSI/MISO/CS) via SPI, so they remain free + // for other uses such as sdioio, which drives the same physical pins. + // Read once and cache, matching usb_msc_flash.c's handling. + static int8_t _sdcard_usb_enabled = -1; // -1 unknown, 0 false, 1 true + if (_sdcard_usb_enabled < 0) { + bool setting = true; + (void)settings_get_bool("CIRCUITPY_SDCARD_USB", &setting); + _sdcard_usb_enabled = setting ? 1 : 0; + } + if (!_sdcard_usb_enabled) { + return; + } + #endif + if (common_hal_digitalio_digitalinout_get_value(&sd_card_detect_pin) != DEFAULT_SD_CARD_INSERTED) { + // No card. + _init_error = false; + if (_automounted) { + // Unmount the card. + mp_vfs_mount_t *cur = MP_STATE_VM(vfs_mount_table); + if (cur == &_sdcard_vfs) { + MP_STATE_VM(vfs_mount_table) = cur->next; + } else { + while (cur->next != &_sdcard_vfs && cur != NULL) { + cur = cur->next; + } + if (cur != NULL) { + cur->next = _sdcard_vfs.next; + } + } + _sdcard_vfs.next = NULL; + + #ifdef DEFAULT_SD_MOSI + common_hal_busio_spi_deinit(&busio_spi_obj); + #endif + // Release the CS pin, so the card can be set up again when it's + // reinserted. When the bus was deinited above, deinit() skips the + // sync to the removed card. + common_hal_sdcardio_sdcard_deinit(&sdcard); + _automounted = false; + } + return; + } else if (_init_error || _automounted) { + // We've already tried and failed to init the card, or it's still mounted. Don't try again. + return; + } + + busio_spi_obj_t *spi_obj; + #ifndef DEFAULT_SD_MOSI + spi_obj = MP_OBJ_TO_PTR(common_hal_board_create_spi(0)); + #else + spi_obj = &busio_spi_obj; + spi_obj->base.type = &busio_spi_type; + common_hal_busio_spi_construct(spi_obj, DEFAULT_SD_SCK, DEFAULT_SD_MOSI, DEFAULT_SD_MISO, false); + #endif + sdcard.base.type = &sdcardio_SDCard_type; + mp_obj_t cs_obj = MP_OBJ_FROM_PTR(DEFAULT_SD_CS); + mp_rom_error_text_t error = sdcardio_sdcard_construct(&sdcard, spi_obj, cs_obj, 25000000, true); + if (error != NULL) { + // Failed to communicate with the card. + _automounted = false; + _init_error = true; + #ifdef DEFAULT_SD_MOSI + common_hal_busio_spi_deinit(spi_obj); + #endif + return; + } + fs_user_mount_t *vfs = &_sdcard_usermount; + vfs->base.type = &mp_fat_vfs_type; + vfs->fatfs.drv = vfs; + + // Initialise underlying block device + vfs->blockdev.block_size = FF_MIN_SS; // default, will be populated by call to MP_BLOCKDEV_IOCTL_BLOCK_SIZE + mp_vfs_blockdev_init(&vfs->blockdev, &sdcard); + + // mount the block device so the VFS methods can be used + FRESULT res = f_mount(&vfs->fatfs); + if (res != FR_OK) { + _automounted = false; + _init_error = true; + common_hal_sdcardio_sdcard_deinit(&sdcard); + #ifdef DEFAULT_SD_MOSI + common_hal_busio_spi_deinit(spi_obj); + #endif + return; + } + + filesystem_set_concurrent_write_protection((supervisor_vfs_t *)vfs, true); + filesystem_set_writable_by_usb((supervisor_vfs_t *)vfs, false); + + mp_vfs_mount_t *sdcard_vfs = &_sdcard_vfs; + sdcard_vfs->str = "/sd"; + sdcard_vfs->len = 3; + sdcard_vfs->obj = MP_OBJ_FROM_PTR(&_sdcard_usermount); + sdcard_vfs->next = MP_STATE_VM(vfs_mount_table); + MP_STATE_VM(vfs_mount_table) = sdcard_vfs; + _automounted = true; + #endif // DEFAULT_SD_CARD_DETECT +} diff --git a/shared-module/sdcardio/__init__.h b/shared-module/sdcardio/__init__.h index c9069db9fd7..59b4cf892f2 100644 --- a/shared-module/sdcardio/__init__.h +++ b/shared-module/sdcardio/__init__.h @@ -5,3 +5,6 @@ // SPDX-License-Identifier: MIT #pragma once + +void sdcardio_init(void); +void automount_sd_card(void); diff --git a/shared-module/sharpdisplay/SharpMemoryFramebuffer.c b/shared-module/sharpdisplay/SharpMemoryFramebuffer.c index 3c6eaf065df..b8136ea47a4 100644 --- a/shared-module/sharpdisplay/SharpMemoryFramebuffer.c +++ b/shared-module/sharpdisplay/SharpMemoryFramebuffer.c @@ -54,13 +54,12 @@ static bool common_hal_sharpdisplay_framebuffer_get_pixels_in_byte_share_row(sha } void common_hal_sharpdisplay_framebuffer_reset(sharpdisplay_framebuffer_obj_t *self) { - if (self->bus != &self->inline_bus - #if CIRCUITPY_BOARD_SPI - && !common_hal_board_is_spi(self->bus) - #endif - ) { - memcpy(&self->inline_bus, self->bus, sizeof(busio_spi_obj_t)); + if (self->bus != &self->inline_bus && gc_ptr_on_heap(self->bus)) { + busio_spi_obj_t *original_spi = self->bus; + memcpy(&self->inline_bus, original_spi, sizeof(busio_spi_obj_t)); self->bus = &self->inline_bus; + // Mark the old SPI object so it is considered deinit. + common_hal_busio_spi_mark_deinit(original_spi); } } @@ -109,7 +108,7 @@ void common_hal_sharpdisplay_framebuffer_deinit(sharpdisplay_framebuffer_obj_t * common_hal_busio_spi_deinit(self->bus); } - common_hal_reset_pin(self->chip_select.pin); + common_hal_digitalio_digitalinout_deinit(&self->chip_select); port_free(self->bufinfo.buf); @@ -126,10 +125,8 @@ void common_hal_sharpdisplay_framebuffer_construct( bool jdi_display) { 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); - common_hal_never_reset_pin(chip_select); self->bus = spi; - common_hal_busio_spi_never_reset(self->bus); self->width = width; self->height = height; diff --git a/shared-module/ssl/SSLContext.c b/shared-module/ssl/SSLContext.c index e58074ea3ea..4c440973657 100644 --- a/shared-module/ssl/SSLContext.c +++ b/shared-module/ssl/SSLContext.c @@ -12,7 +12,20 @@ #include "lib/mbedtls_config/crt_bundle.h" +#include "psa/crypto.h" + void common_hal_ssl_sslcontext_construct(ssl_sslcontext_obj_t *self) { + // TLS is built on PSA crypto, which has to be initialized before any of it is + // used. OK to psa_crypto_init() multiple times. On espressif, ESP-IDF has already done this during + // its own system init and this call is a no-op. + if (psa_crypto_init() != PSA_SUCCESS) { + mp_raise_RuntimeError_varg(MP_ERROR_TEXT("%q init failed"), MP_QSTR_ssl); + } + self->cert_buf.buf = NULL; + self->cert_buf.len = 0; + self->key_buf.buf = NULL; + self->key_buf.len = 0; + self->check_name = true; common_hal_ssl_sslcontext_set_default_verify_paths(self); } @@ -39,7 +52,10 @@ void common_hal_ssl_sslcontext_set_check_hostname(ssl_sslcontext_obj_t *self, bo self->check_name = value; } -void common_hal_ssl_sslcontext_load_cert_chain(ssl_sslcontext_obj_t *self, mp_buffer_info_t *cert_buf, mp_buffer_info_t *key_buf) { +void common_hal_ssl_sslcontext_load_cert_chain(ssl_sslcontext_obj_t *self, mp_buffer_info_t *cert_buf, mp_buffer_info_t *key_buf, psa_key_id_t hw_key_id) { self->cert_buf = *cert_buf; - self->key_buf = *key_buf; + self->hw_key_id = hw_key_id; + if (hw_key_id == 0) { + self->key_buf = *key_buf; + } } diff --git a/shared-module/ssl/SSLContext.h b/shared-module/ssl/SSLContext.h index 293f3143ebc..c04706d066b 100644 --- a/shared-module/ssl/SSLContext.h +++ b/shared-module/ssl/SSLContext.h @@ -9,6 +9,7 @@ #include "py/obj.h" #include "mbedtls/ssl.h" +#include "psa/crypto.h" typedef struct { mp_obj_base_t base; @@ -17,4 +18,8 @@ typedef struct { size_t cacert_bytes; int (*crt_bundle_attach)(mbedtls_ssl_config *conf); mp_buffer_info_t cert_buf, key_buf; + // When nonzero, the client-certificate private key is an opaque PSA key + // (e.g. a hardwarekey.HardwareKey backed by the Digital Signature + // peripheral) and key_buf is unused. + psa_key_id_t hw_key_id; } ssl_sslcontext_obj_t; diff --git a/shared-module/ssl/SSLSocket.c b/shared-module/ssl/SSLSocket.c index 129a48d00d6..4819412e07a 100644 --- a/shared-module/ssl/SSLSocket.c +++ b/shared-module/ssl/SSLSocket.c @@ -6,45 +6,95 @@ // // SPDX-License-Identifier: MIT +// Needed to reach mbedtls_pk_context's private pub_raw/pub_raw_len fields -- +// see the mbedtls_pk_wrap_psa() workaround in +// common_hal_ssl_sslcontext_wrap_socket() below. +#define MBEDTLS_ALLOW_PRIVATE_ACCESS + +#include + #include "shared-bindings/ssl/SSLSocket.h" #include "shared-bindings/ssl/SSLContext.h" #include "shared/runtime/interrupt_char.h" #include "shared/netutils/netutils.h" +#include "mbedtls/version.h" +#include "psa/crypto.h" #include "py/mperrno.h" #include "py/mphal.h" -#include "py/objstr.h" +#include "py/objarray.h" #include "py/runtime.h" #include "py/stream.h" #include "supervisor/shared/tick.h" #include "shared-bindings/socketpool/enum.h" -#include "mbedtls/version.h" - #define MP_STREAM_POLL_RDWR (MP_STREAM_POLL_RD | MP_STREAM_POLL_WR) #if defined(MBEDTLS_ERROR_C) #include "../../lib/mbedtls_errors/mp_mbedtls_errors.c" #endif -#if MBEDTLS_VERSION_MAJOR >= 3 -#include "shared-bindings/os/__init__.h" -#endif - #ifdef MBEDTLS_DEBUG_C #include "mbedtls/debug.h" static void mbedtls_debug(void *ctx, int level, const char *file, int line, const char *str) { (void)ctx; (void)level; - mp_printf(&mp_plat_print, "DBG:%s:%04d: %s\n", file, line, str); + mp_printf(&mp_plat_print, "DBG:%s:%04d: %s", file, line, str); } #define DEBUG_PRINT(fmt, ...) mp_printf(&mp_plat_print, "DBG:%s:%04d: " fmt "\n", __FILE__, __LINE__,##__VA_ARGS__) #else #define DEBUG_PRINT(...) do {} while (0) #endif -static NORETURN void mbedtls_raise_error(int err) { +// Raise an OSError for an mbedtls error code. +// `flags` is a bitmask from mbedtls_ssl_get_verify_result(), or 0 if not a verify error. +static MP_NORETURN void mbedtls_raise_error_flags(int err, uint32_t flags) { + // In mbedtls 4.x with TF-PSA-Crypto 1.x, the legacy mbedtls error constants + // were renumbered into the PSA status space (mbedtls/compat-3-crypto.h), so + // crypto-layer failures surface from the TLS layer as PSA statuses + // (-132 .. -153). These collide both with legacy mbedtls codes and with the + // socket errno passthrough below, so translate them to conventional POSIX + // errnos first. + switch (err) { + case PSA_ERROR_GENERIC_ERROR: + case PSA_ERROR_COMMUNICATION_FAILURE: + case PSA_ERROR_STORAGE_FAILURE: + case PSA_ERROR_HARDWARE_FAILURE: + case PSA_ERROR_INSUFFICIENT_ENTROPY: + case PSA_ERROR_INSUFFICIENT_DATA: + case PSA_ERROR_SERVICE_FAILURE: + case PSA_ERROR_CORRUPTION_DETECTED: + case PSA_ERROR_DATA_CORRUPT: + mp_raise_OSError(MP_EIO); + case PSA_ERROR_NOT_PERMITTED: + case PSA_ERROR_BAD_STATE: + mp_raise_OSError(MP_EPERM); + case PSA_ERROR_NOT_SUPPORTED: + mp_raise_OSError(MP_EOPNOTSUPP); + case PSA_ERROR_BUFFER_TOO_SMALL: + mp_raise_OSError(MP_ENOBUFS); + case PSA_ERROR_ALREADY_EXISTS: + mp_raise_OSError(MP_EEXIST); + case PSA_ERROR_DOES_NOT_EXIST: + mp_raise_OSError(MP_ENOENT); + case PSA_ERROR_INVALID_HANDLE: + mp_raise_OSError(MP_EBADF); + case PSA_ERROR_INSUFFICIENT_MEMORY: + mp_raise_OSError(MP_ENOMEM); + case PSA_ERROR_INSUFFICIENT_STORAGE: + mp_raise_OSError(MP_ENOSPC); + case PSA_ERROR_INVALID_SIGNATURE: + case PSA_ERROR_INVALID_PADDING: + case PSA_ERROR_INVALID_ARGUMENT: + case PSA_ERROR_DATA_INVALID: + default: + if (err >= -153 && err <= -132) { + mp_raise_OSError(MP_EINVAL); + } + break; + } + // _mbedtls_ssl_send and _mbedtls_ssl_recv (below) turn positive error codes from the // underlying socket into negative codes to pass them through mbedtls. Here we turn them // positive again so they get interpreted as the OSError they really are. The @@ -57,37 +107,78 @@ static NORETURN void mbedtls_raise_error(int err) { mp_raise_OSError(MP_EWOULDBLOCK); } + // All ones means mbedtls says it has nothing to report: it set to all ones + // when a verify callback fails, and mbedtls_ssl_get_verify_result() returns + // this when there is no session at all. + if (flags == UINT32_MAX) { + flags = 0; + } + #if defined(MBEDTLS_ERROR_C) // Including mbedtls_strerror takes about 1.5KB due to the error strings. // MBEDTLS_ERROR_C is the define used by mbedtls to conditionally include mbedtls_strerror. // It is set/unset in the MBEDTLS_CONFIG_FILE which is defined in the Makefile. - // Try to allocate memory for the message - #define ERR_STR_MAX 80 // mbedtls_strerror truncates if it doesn't fit - mp_obj_str_t *o_str = m_new_obj_maybe(mp_obj_str_t); - byte *o_str_buf = m_new_maybe(byte, ERR_STR_MAX); - if (o_str == NULL || o_str_buf == NULL) { + // Large enough for the longest mbedtls_strerror() output, which is about 100 + // characters when it joins a high-level and a low-level name with '+', and for + // the longest certificate verification failure name, which is 81 characters. + #define ERR_STR_MAX 128 // mbedtls_strerror truncates if it doesn't fit + // One byte larger than the bound passed to mbedtls_strerror(), so that the + // strncpy() inside it has a bound smaller than the size of buf. Truncation + // there is safe and deliberate, but an equal bound trips -Wstringop-truncation. + char buf[ERR_STR_MAX + 1]; + + // Assemble the error message in a vstr. + // If we run out of heap, catch the MemoryError and fall back to just the error number. + mp_obj_t exc; + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + vstr_t vstr; + vstr_init(&vstr, ERR_STR_MAX); + + mbedtls_strerror(err, buf, ERR_STR_MAX); + vstr_add_str(&vstr, buf); + + #if !defined(MBEDTLS_X509_REMOVE_INFO) + // Call mbedtls_x509_crt_verify_info() to get the error string + // for each individual verify error bit. + // This allows for easier string management. + // Several verify errorbits are often set at once: + // mbedtls or's together the error flags of every certificate in the chain. + // For instance, a cert served under the wrong name and signed by an + // unknown CA reports CN_MISMATCH and NOT_TRUSTED together. + for (uint32_t bit = 1; bit != 0; bit <<= 1) { + if ((flags & bit) == 0) { + continue; + } + // The prefix is added to the beginning of the message. + // We drop the supplied trailing newline. + int info_len = mbedtls_x509_crt_verify_info(buf, ERR_STR_MAX, "; ", bit); + if (info_len > 1) { + // -1 to drop the newline. + vstr_add_strn(&vstr, buf, info_len - 1); + } + } + #endif + + mp_obj_t args[2] = { MP_OBJ_NEW_SMALL_INT(err), mp_obj_new_str_from_utf8_vstr(&vstr) }; + exc = mp_obj_exception_make_new(&mp_type_OSError, 2, 0, args); + nlr_pop(); + } else { + // Could not build the message, so report the number by itself. mp_raise_OSError(err); } - - // print the error message into the allocated buffer - mbedtls_strerror(err, (char *)o_str_buf, ERR_STR_MAX); - size_t len = strlen((char *)o_str_buf); - - // Put the exception object together - o_str->base.type = &mp_type_str; - o_str->data = o_str_buf; - o_str->len = len; - o_str->hash = qstr_compute_hash(o_str->data, o_str->len); - // raise - mp_obj_t args[2] = { MP_OBJ_NEW_SMALL_INT(err), MP_OBJ_FROM_PTR(o_str)}; - nlr_raise(mp_obj_exception_make_new(&mp_type_OSError, 2, 0, args)); + nlr_raise(exc); #else - // mbedtls is compiled without error strings so we simply return the err number + // mbedtls is compiled without error strings, so just return the err number mp_raise_OSError(err); // err is typically a large negative number #endif } +static MP_NORETURN void mbedtls_raise_error(int err) { + mbedtls_raise_error_flags(err, 0); +} + // Because ssl_socket_send and ssl_socket_recv_into are callbacks from mbedtls code, // it is not OK to exit them by raising an exception (nlr_jump'ing through // foreign code is not permitted). Instead, preserve the error number of any OSError @@ -144,8 +235,6 @@ static void ssl_socket_close(ssl_sslsocket_obj_t *self) { if (nlr_push(&nlr) == 0) { mp_call_method_n_kw(0, 0, self->close_args); nlr_pop(); - } else { - nlr_pop(); } } @@ -200,16 +289,6 @@ static int _mbedtls_ssl_recv(void *ctx, byte *buf, size_t len) { } -#if MBEDTLS_VERSION_MAJOR >= 3 -static int urandom_adapter(void *unused, unsigned char *buf, size_t n) { - int result = common_hal_os_urandom(buf, n); - if (result) { - return 0; - } - return MBEDTLS_ERR_SSL_INTERNAL_ERROR; -} -#endif - ssl_sslsocket_obj_t *common_hal_ssl_sslcontext_wrap_socket(ssl_sslcontext_obj_t *self, mp_obj_t socket, bool server_side, const char *server_hostname) { @@ -222,6 +301,8 @@ ssl_sslsocket_obj_t *common_hal_ssl_sslcontext_wrap_socket(ssl_sslcontext_obj_t o->ssl_context = self; o->sock_obj = socket; o->poll_mask = 0; + // A missing method raises below. Keep the finaliser away until the object is complete. + o->closed = true; mp_load_method(socket, MP_QSTR_accept, o->accept_args); mp_load_method(socket, MP_QSTR_bind, o->bind_args); @@ -232,26 +313,19 @@ ssl_sslsocket_obj_t *common_hal_ssl_sslcontext_wrap_socket(ssl_sslcontext_obj_t mp_load_method(socket, MP_QSTR_send, o->send_args); mp_load_method(socket, MP_QSTR_settimeout, o->settimeout_args); mp_load_method(socket, MP_QSTR_setsockopt, o->setsockopt_args); + o->closed = false; mbedtls_ssl_init(&o->ssl); mbedtls_ssl_config_init(&o->conf); mbedtls_x509_crt_init(&o->cacert); mbedtls_x509_crt_init(&o->cert); mbedtls_pk_init(&o->pkey); - mbedtls_ctr_drbg_init(&o->ctr_drbg); #ifdef MBEDTLS_DEBUG_C // Debug level (0-4) 1=warning, 2=info, 3=debug, 4=verbose mbedtls_debug_set_threshold(4); #endif - mbedtls_entropy_init(&o->entropy); - const byte seed[] = "upy"; - int ret = mbedtls_ctr_drbg_seed(&o->ctr_drbg, mbedtls_entropy_func, &o->entropy, seed, sizeof(seed)); - if (ret != 0) { - goto cleanup; - } - - ret = mbedtls_ssl_config_defaults(&o->conf, + int ret = mbedtls_ssl_config_defaults(&o->conf, server_side ? MBEDTLS_SSL_IS_SERVER : MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_STREAM, MBEDTLS_SSL_PRESET_DEFAULT); @@ -259,7 +333,9 @@ ssl_sslsocket_obj_t *common_hal_ssl_sslcontext_wrap_socket(ssl_sslcontext_obj_t goto cleanup; } - if (self->crt_bundle_attach != NULL) { + if (self->crt_bundle_attach != NULL && !server_side) { + // The root bundle checks servers. A server checks clients only + // against a CA loaded with load_verify_locations(). mbedtls_ssl_conf_authmode(&o->conf, MBEDTLS_SSL_VERIFY_REQUIRED); self->crt_bundle_attach(&o->conf); } else if (self->cacert_buf && self->cacert_bytes) { @@ -273,7 +349,6 @@ ssl_sslsocket_obj_t *common_hal_ssl_sslcontext_wrap_socket(ssl_sslcontext_obj_t } else { mbedtls_ssl_conf_authmode(&o->conf, MBEDTLS_SSL_VERIFY_NONE); } - mbedtls_ssl_conf_rng(&o->conf, mbedtls_ctr_drbg_random, &o->ctr_drbg); #ifdef MBEDTLS_DEBUG_C mbedtls_ssl_conf_dbg(&o->conf, mbedtls_debug, NULL); #endif @@ -293,15 +368,31 @@ ssl_sslsocket_obj_t *common_hal_ssl_sslcontext_wrap_socket(ssl_sslcontext_obj_t mbedtls_ssl_set_bio(&o->ssl, o, _mbedtls_ssl_send, _mbedtls_ssl_recv, NULL); if (self->cert_buf.buf != NULL) { - #if MBEDTLS_VERSION_MAJOR >= 3 - ret = mbedtls_pk_parse_key(&o->pkey, self->key_buf.buf, self->key_buf.len + 1, NULL, 0, urandom_adapter, NULL); - #else - ret = mbedtls_pk_parse_key(&o->pkey, self->key_buf.buf, self->key_buf.len + 1, NULL, 0); - #endif + // Parsed first so its public key is available for the + // mbedtls_pk_wrap_psa() workaround below. + ret = mbedtls_x509_crt_parse(&o->cert, self->cert_buf.buf, self->cert_buf.len + 1); if (ret != 0) { goto cleanup; } - ret = mbedtls_x509_crt_parse(&o->cert, self->cert_buf.buf, self->cert_buf.len + 1); + + if (self->hw_key_id != 0) { + // mbedtls_pk_wrap_psa() unconditionally calls + // psa_export_public_key() on the handle as part of wrapping it, + // but the DS peripheral's PSA driver has no export_public_key + // entry point (the private key, and anything derivable from it, + // never leaves the peripheral by design), so that call fails + // before the wrap can complete. It skips the export once + // pub_raw_len is already set, so pre-populate it from the + // certificate's own public key -- the public half of this same + // key, by construction. (mbedtls_pk_write_pubkey_psa() would do + // this copy too, but it needs MBEDTLS_PK_WRITE_C, which not every + // port enables, so copy the field directly instead.) + memcpy(o->pkey.pub_raw, o->cert.pk.pub_raw, o->cert.pk.pub_raw_len); + o->pkey.pub_raw_len = o->cert.pk.pub_raw_len; + ret = mbedtls_pk_wrap_psa(&o->pkey, self->hw_key_id); + } else { + ret = mbedtls_pk_parse_key(&o->pkey, self->key_buf.buf, self->key_buf.len + 1, NULL, 0); + } if (ret != 0) { goto cleanup; } @@ -313,18 +404,16 @@ ssl_sslsocket_obj_t *common_hal_ssl_sslcontext_wrap_socket(ssl_sslcontext_obj_t } return o; cleanup: + o->closed = true; + ssl_socket_close(o); mbedtls_pk_free(&o->pkey); mbedtls_x509_crt_free(&o->cert); mbedtls_x509_crt_free(&o->cacert); mbedtls_ssl_free(&o->ssl); mbedtls_ssl_config_free(&o->conf); - mbedtls_ctr_drbg_free(&o->ctr_drbg); - mbedtls_entropy_free(&o->entropy); if (ret == MBEDTLS_ERR_SSL_ALLOC_FAILED) { mp_raise_type(&mp_type_MemoryError); - } else if (ret == MBEDTLS_ERR_PK_BAD_INPUT_DATA) { - mp_raise_ValueError(MP_ERROR_TEXT("invalid key")); } else if (ret == MBEDTLS_ERR_X509_BAD_INPUT_DATA) { mp_raise_ValueError(MP_ERROR_TEXT("invalid cert")); } else { @@ -382,8 +471,6 @@ void common_hal_ssl_sslsocket_close(ssl_sslsocket_obj_t *self) { 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); } static void do_handshake(ssl_sslsocket_obj_t *self) { @@ -403,22 +490,28 @@ static void do_handshake(ssl_sslsocket_obj_t *self) { cleanup: self->closed = true; + ssl_socket_close(self); + + // Verification flags are only valid for CERT_VERIFY_FAILED. + // Read them before mbedtls_ssl_free() below: they live in the ssl context's + // session_negotiate and are gone once it is freed. + uint32_t verify_flags = 0; + if (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED) { + verify_flags = mbedtls_ssl_get_verify_result(&self->ssl); + } + 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); if (ret == MBEDTLS_ERR_SSL_ALLOC_FAILED) { mp_raise_type(&mp_type_MemoryError); - } else if (ret == MBEDTLS_ERR_PK_BAD_INPUT_DATA) { - mp_raise_ValueError(MP_ERROR_TEXT("invalid key")); } else if (ret == MBEDTLS_ERR_X509_BAD_INPUT_DATA) { mp_raise_ValueError(MP_ERROR_TEXT("invalid cert")); } else { - mbedtls_raise_error(ret); + mbedtls_raise_error_flags(ret, verify_flags); } } diff --git a/shared-module/ssl/SSLSocket.h b/shared-module/ssl/SSLSocket.h index f7f3d1ae83c..f3bb858a00d 100644 --- a/shared-module/ssl/SSLSocket.h +++ b/shared-module/ssl/SSLSocket.h @@ -15,15 +15,11 @@ #include "mbedtls/ssl.h" #include "mbedtls/x509_crt.h" #include "mbedtls/pk.h" -#include "mbedtls/entropy.h" -#include "mbedtls/ctr_drbg.h" typedef struct ssl_sslsocket_obj { mp_obj_base_t base; mp_obj_t sock_obj; ssl_sslcontext_obj_t *ssl_context; - mbedtls_entropy_context entropy; - mbedtls_ctr_drbg_context ctr_drbg; mbedtls_ssl_context ssl; mbedtls_ssl_config conf; mbedtls_x509_crt cacert; diff --git a/shared-module/storage/__init__.c b/shared-module/storage/__init__.c index 2bf265c1dc1..066e1e55a18 100644 --- a/shared-module/storage/__init__.c +++ b/shared-module/storage/__init__.c @@ -18,6 +18,17 @@ #include "shared-bindings/storage/__init__.h" #include "supervisor/filesystem.h" #include "supervisor/flash.h" +#include "supervisor/shared/reload.h" +#if CIRCUITPY_STORAGE_MAP_FILE +#include "extmod/vfs_fat.h" +#include "lib/oofatfs/ff.h" +#include "py/objarray.h" +#include "py/objlist.h" +#include "py/stream.h" +#if CIRCUITPY_SETTINGS_TOML +#include "supervisor/shared/settings.h" +#endif +#endif #if CIRCUITPY_USB_DEVICE #include "supervisor/usb.h" @@ -27,10 +38,15 @@ #include "tusb.h" // Is the MSC device enabled? -bool storage_usb_is_enabled; +static volatile bool storage_usb_is_enabled; +// CIRCUITPY's USB writability when the drive was disabled. It is restored on enable +// unless a remount() changed it in the meantime. +static bool usb_writable_before_disable; +static bool restore_usb_writable; void storage_usb_set_defaults(void) { storage_usb_is_enabled = CIRCUITPY_USB_MSC_ENABLED_DEFAULT; + restore_usb_writable = false; } bool storage_usb_enabled(void) { @@ -38,20 +54,56 @@ bool storage_usb_enabled(void) { } static bool usb_drive_set_enabled(bool enabled) { - // We can't change the descriptors once we're connected. - if (tud_connected()) { - return false; + if (enabled) { + // Set this before the LUN reports ready: the host reads write-protect status when it remounts. + if (restore_usb_writable) { + filesystem_set_internal_writable_by_usb(usb_writable_before_disable); + restore_usb_writable = false; + } + } else if (storage_usb_is_enabled) { + supervisor_vfs_t *circuitpy = filesystem_circuitpy(); + usb_writable_before_disable = circuitpy != NULL && + (circuitpy->common.blockdev.flags & MP_BLOCKDEV_FLAG_USB_WRITABLE) != 0; + restore_usb_writable = true; } - filesystem_set_internal_writable_by_usb(enabled); + // We can't change the descriptors once we're connected, but we can make the LUN be ready or not ready. storage_usb_is_enabled = enabled; + if (tud_connected()) { + // The TEST UNIT READY callback in usb_msc_flash.c checks the value of storage_usb_is_enabled. + // If it's false, TEST UNIT READY will report "not ready" + // Linux and macOS send a TEST UNIT READY poll about every 1.1 seconds or faster. + // Windows polls every 2.1 seconds or so. + // So wait long enough for host to send a TEST UNIT READY and receive a reply. + mp_hal_delay_ms(2500); + } + if (!enabled) { + filesystem_set_internal_writable_by_usb(false); + // USB MSC may still hold the lock from when it reported the drive writable. + usb_msc_release_circuitpy_lock(); + } return true; } bool common_hal_storage_disable_usb_drive(void) { + if (tud_connected()) { + // Complain if already connected. Use `storage.unsafe_disable_usb_drive()` in that case. + return false; + } + return usb_drive_set_enabled(false); +} + +bool common_hal_storage_unsafe_disable_usb_drive(void) { return usb_drive_set_enabled(false); } bool common_hal_storage_enable_usb_drive(void) { + // A file open for writing or a workflow transfer holds the filesystem lock. + // The host would then see the drive as read-only, and keep it that way after the lock is released. + supervisor_vfs_t *circuitpy = filesystem_circuitpy(); + if (!storage_usb_is_enabled && circuitpy != NULL && + (circuitpy->common.blockdev.flags & MP_BLOCKDEV_FLAG_LOCKED) != 0) { + mp_raise_RuntimeError(MP_ERROR_TEXT("File write in progress")); + } return usb_drive_set_enabled(true); } #else @@ -59,6 +111,10 @@ bool common_hal_storage_disable_usb_drive(void) { return false; } +bool common_hal_storage_unsafe_disable_usb_drive(void) { + return false; +} + bool common_hal_storage_enable_usb_drive(void) { return false; } @@ -82,10 +138,11 @@ static mp_obj_t mp_vfs_proxy_call(mp_vfs_mount_t *vfs, qstr meth_name, size_t n_ } void common_hal_storage_mount(mp_obj_t vfs_obj, const char *mount_path, bool readonly) { + const char *abs_mount_path = common_hal_os_path_abspath(mount_path); // create new object mp_vfs_mount_t *vfs = m_new_obj(mp_vfs_mount_t); - vfs->str = mount_path; - vfs->len = strlen(mount_path); + vfs->str = abs_mount_path; + vfs->len = strlen(abs_mount_path); vfs->obj = vfs_obj; vfs->next = NULL; @@ -98,7 +155,7 @@ void common_hal_storage_mount(mp_obj_t vfs_obj, const char *mount_path, bool rea if (strcmp(vfs->str, "/") != 0) { nlr_buf_t nlr; if (nlr_push(&nlr) == 0) { - mp_obj_t mount_point_stat = common_hal_os_stat(mount_path); + mp_obj_t mount_point_stat = common_hal_os_stat(abs_mount_path); nlr_pop(); mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mount_point_stat); if ((MP_OBJ_SMALL_INT_VALUE(t->items[0]) & MP_S_IFDIR) == 0) { @@ -112,7 +169,7 @@ void common_hal_storage_mount(mp_obj_t vfs_obj, const char *mount_path, bool rea // check that the destination mount point is unused const char *path_out; - mp_vfs_mount_t *existing_mount = mp_vfs_lookup_path(mount_path, &path_out); + mp_vfs_mount_t *existing_mount = mp_vfs_lookup_path(abs_mount_path, &path_out); if (existing_mount != MP_VFS_NONE && existing_mount != MP_VFS_ROOT) { if (vfs->len != 1 && existing_mount->len == 1) { // if root dir is mounted, still allow to mount something within a subdir of root @@ -125,6 +182,14 @@ 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); + fs_user_mount_t *vfs_fat = MP_OBJ_TO_PTR(vfs_obj); + // Filesystem is read-only to USB if writable by CircuitPython, and vice versa. + // The flag helpers take a supervisor_vfs_t; a mounted VfsFat is always a + // fs_user_mount_t, whose base + blockdev prefix matches both vfs + // kinds. + filesystem_set_writable_by_usb((supervisor_vfs_t *)vfs_fat, readonly); + filesystem_set_concurrent_write_protection((supervisor_vfs_t *)vfs_fat, true); + // Insert the vfs into the mount table by pushing it onto the front of the // mount table. mp_vfs_mount_t **vfsp = &MP_STATE_VM(vfs_mount_table); @@ -157,8 +222,9 @@ void common_hal_storage_umount_object(mp_obj_t vfs_obj) { } static mp_obj_t storage_object_from_path(const char *mount_path) { + const char *abs_mount_path = common_hal_os_path_abspath(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) { + if (strcmp(abs_mount_path, (*vfsp)->str) == 0) { return (*vfsp)->obj; } } @@ -173,19 +239,43 @@ mp_obj_t common_hal_storage_getmount(const char *mount_path) { return storage_object_from_path(mount_path); } -void common_hal_storage_remount(const char *mount_path, bool readonly, bool disable_concurrent_write_protection) { - if (strcmp(mount_path, "/") != 0) { - mp_raise_OSError(MP_EINVAL); +static void remount_vfs(supervisor_vfs_t *fs_mount, bool readonly, bool disable_concurrent_write_protection) { + #if CIRCUITPY_USB_DEVICE && CIRCUITPY_USB_MSC + if (!blockdev_lock(fs_mount)) { + if (usb_msc_holds_lock(&fs_mount->fat)) { + mp_raise_RuntimeError(MP_ERROR_TEXT("Cannot remount path when visible via USB.")); + } + // A file open for writing or a workflow transfer holds the lock. + mp_raise_RuntimeError(MP_ERROR_TEXT("File write in progress")); } + #endif + + filesystem_set_writable_by_usb(fs_mount, readonly); + filesystem_set_concurrent_write_protection(fs_mount, !disable_concurrent_write_protection); + blockdev_unlock(fs_mount); #if CIRCUITPY_USB_DEVICE && CIRCUITPY_USB_MSC - if (!usb_msc_ejected() && storage_usb_is_enabled) { - mp_raise_RuntimeError(MP_ERROR_TEXT("Cannot remount '/' when visible via USB.")); + if (fs_mount == filesystem_circuitpy()) { + // remount() wins over the state saved when the USB drive was disabled. + restore_usb_writable = false; } + usb_msc_remount(&fs_mount->fat); #endif +} + +void common_hal_storage_remount(const char *mount_path, bool readonly, bool disable_concurrent_write_protection) { + const char *path_under_mount; + const char *abs_mount_path = common_hal_os_path_abspath(mount_path); + supervisor_vfs_t *fs_mount = filesystem_for_path(abs_mount_path, &path_under_mount); + if (path_under_mount[0] != 0 && strcmp(abs_mount_path, "/") != 0) { + mp_raise_OSError(MP_EINVAL); + } + if (fs_mount == NULL) { + // Nothing is mounted there (or there is no filesystem at all). + mp_raise_OSError(MP_EINVAL); + } - filesystem_set_internal_writable_by_usb(readonly); - filesystem_set_internal_concurrent_write_protection(!disable_concurrent_write_protection); + remount_vfs(fs_mount, readonly, disable_concurrent_write_protection); } void common_hal_storage_erase_filesystem(bool extended) { @@ -201,3 +291,286 @@ void common_hal_storage_erase_filesystem(bool extended) { common_hal_mcu_reset(); // We won't actually get here, since we're resetting. } + +#if CIRCUITPY_STORAGE_MAP_FILE +// Flash mappings can outlive the Python VM, so read this setting only at boot. +static bool storage_map_file_enabled = true; + +void storage_map_file_init(void) { + #if CIRCUITPY_SETTINGS_TOML + settings_get_bool("CIRCUITPY_STORAGE_MAP_FILE", &storage_map_file_enabled); + #endif +} + +// Start clusters of the files mapped since the VM started; a write to one of them is refused +// until reload. +MP_REGISTER_ROOT_POINTER(mp_obj_t storage_mapped_files); + +#if CIRCUITPY_STORAGE_MAP_IMPORT +// Readers of the .mpy files imported in place, linked through next_reader. They stay +// until reload: their runs are in use. +MP_REGISTER_ROOT_POINTER(void *storage_mapped_imports); +#endif + +void storage_map_file_reset(void) { + MP_STATE_VM(storage_mapped_files) = MP_OBJ_NULL; + // A held workflow write may ask for a reload after the VM has already stopped. Drop + // that request: left pending, it makes the BLE workflow drop its replies. + MP_STATE_THREAD(mp_pending_exception) = MP_OBJ_NULL; + #if CIRCUITPY_STORAGE_MAP_IMPORT + common_hal_mcu_disable_interrupts(); // the USB task may be checking the list + MP_STATE_VM(storage_mapped_imports) = NULL; + common_hal_mcu_enable_interrupts(); + #if CIRCUITPY_USB_DEVICE && CIRCUITPY_USB_MSC + usb_msc_finish_deferred_write(); // the code it would have overwritten is gone + #endif + #endif +} + +static bool mapped_files_contain(DWORD sclust) { + mp_obj_list_t *mapped = MP_OBJ_TO_PTR(MP_STATE_VM(storage_mapped_files)); + for (size_t i = 0; i < mapped->len; i++) { + if (MP_OBJ_SMALL_INT_VALUE(mapped->items[i]) == (mp_int_t)sclust) { + return true; + } + } + return false; +} + +static void mapped_files_add(DWORD sclust) { + if (MP_STATE_VM(storage_mapped_files) == MP_OBJ_NULL) { + MP_STATE_VM(storage_mapped_files) = mp_obj_new_list(0, NULL); + } + if (!mapped_files_contain(sclust)) { + mp_obj_list_append(MP_STATE_VM(storage_mapped_files), MP_OBJ_NEW_SMALL_INT(sclust)); + } +} + +// Not inlined into its raising wrapper: the supervisor file writers call it too. +MP_NOINLINE bool storage_map_file_in_use(fs_user_mount_t *vfs, const char *path) { + // A bare fs_user_mount_t (e.g. an SD card mount) shares the supervisor_vfs_t + // prefix, so the cast is safe. If CIRCUITPY is littlefs, the FAT mount can + // never be the CIRCUITPY mount, so no mapped file can match either. + if (MP_STATE_VM(storage_mapped_files) == MP_OBJ_NULL || + (supervisor_vfs_t *)vfs != filesystem_circuitpy()) { + return false; + } + FIL fp; + if (f_open(&vfs->fatfs, &fp, path, FA_READ) != FR_OK) { + return false; // no such file yet + } + DWORD sclust = fp.obj.sclust; + f_close(&fp); + return mapped_files_contain(sclust); +} + +void storage_map_file_check_writable(fs_user_mount_t *vfs, const char *path) { + if (storage_map_file_in_use(vfs, path)) { + mp_raise_OSError(MP_EACCES); // mapped: its flash bytes are in use + } +} +#endif + +#if CIRCUITPY_STORAGE_MAP_FILE +int storage_map_runs(mp_obj_t file_in, storage_map_run_fn_t fn, void *ctx) { + if (!storage_map_file_enabled) { + return MP_EOPNOTSUPP; + } + if (!mp_obj_is_type(file_in, &mp_type_vfs_fat_fileio)) { + return MP_EOPNOTSUPP; // only a FAT volume stores a file as flash bytes + } + pyb_file_obj_t *file = MP_OBJ_TO_PTR(file_in); + FATFS *fatfs = file->fp.obj.fs; + if (fatfs == NULL || (file->fp.flag & FA_WRITE)) { + return MP_EINVAL; // closed, or not open for reading only + } + supervisor_vfs_t *fs_mount = filesystem_circuitpy(); + // A littlefs CIRCUITPY or another mount (an SD card) doesn't store files as mapped flash bytes. + if (fs_mount == NULL || fs_mount->common.base.type != &mp_fat_vfs_type || + fatfs != &fs_mount->fat.fatfs) { + return MP_EOPNOTSUPP; + } + DWORD *tbl = file->fp.cltbl; + if (tbl == NULL) { + return MP_ENOMEM; // open() could not allocate the cluster map + } + FSIZE_t left = f_size(&file->fp); + if (left == 0) { + return 0; + } + supervisor_flash_flush(); // write back any RAM sector cache + // Walk the cluster runs of the link map open() built and split a run wherever the port's + // mapping is not contiguous, e.g. at the seam of a drive that spans two flash partitions. + size_t nruns = (size_t)((tbl[0] - 2) / 2); + for (size_t i = 0; i < nruns && left > 0; i++) { + DWORD sector = fatfs->database + (tbl[2 + 2 * i] - 2) * fatfs->csize; + FSIZE_t span = (FSIZE_t)tbl[1 + 2 * i] * fatfs->csize * FF_MIN_SS; + if (span > left) { + span = left; // the last run is clipped to the dir-entry size + } + while (span > 0) { + uint32_t contiguous; + const uint8_t *addr = supervisor_flash_xip_address(sector, &contiguous); + if (addr == NULL) { + return MP_EOPNOTSUPP; // this build cannot map the drive here + } + FSIZE_t piece = (FSIZE_t)contiguous * FF_MIN_SS; + if (piece > span) { + piece = span; + } + fn(ctx, addr, (size_t)piece, sector); + span -= piece; + left -= piece; + sector += contiguous; + } + } + return left != 0 ? MP_EIO : 0; // chain shorter than the dir-entry size: corrupt +} + +static void append_view(void *views, const uint8_t *addr, size_t len, uint32_t block) { + // read-only: a stray write raises instead of silently hitting the flash window + mp_obj_list_append(MP_OBJ_FROM_PTR(views), mp_obj_new_memoryview('B', len, (void *)addr)); +} +#endif + +mp_obj_t common_hal_storage_map_file(mp_obj_t file_in) { + #if CIRCUITPY_STORAGE_MAP_FILE + mp_obj_list_t *views = MP_OBJ_TO_PTR(mp_obj_new_list(0, NULL)); + int err = storage_map_runs(file_in, append_view, views); + if (err == MP_ENOMEM) { + mp_raise_type(&mp_type_MemoryError); + } + if (err != 0) { + mp_raise_OSError(err); + } + if (views->len == 0) { + return mp_const_empty_tuple; // an empty file has no clusters to protect + } + pyb_file_obj_t *file = MP_OBJ_TO_PTR(file_in); + mapped_files_add(file->fp.obj.sclust); + return mp_obj_new_tuple(views->len, views->items); + #else + (void)file_in; + mp_raise_type(&mp_type_NotImplementedError); // this port does not map its drive + #endif +} + +#if CIRCUITPY_STORAGE_MAP_IMPORT +#ifndef CIRCUITPY_STORAGE_MAP_GUARD_BLOCKS +#define CIRCUITPY_STORAGE_MAP_GUARD_BLOCKS (1) +#endif + +// Reads a .mpy straight from its flash runs. Data inside one run is used in place; the +// loader copies anything that spans two runs. +typedef struct { + const uint8_t *addr; + size_t len; + uint32_t block; // first drive block, for the USB write guard +} map_run_t; + +typedef struct _map_reader_t { + struct _map_reader_t *next_reader; // the import before this one + const uint8_t *cur; + const uint8_t *end; // end of the current run + size_t next_run; // index of the run after the current one + size_t run_count; + map_run_t runs[]; +} map_reader_t; + +static void count_run(void *ctx, const uint8_t *addr, size_t len, uint32_t block) { + (*(size_t *)ctx)++; +} + +static void add_run(void *ctx, const uint8_t *addr, size_t len, uint32_t block) { + map_reader_t *r = ctx; + r->runs[r->run_count] = (map_run_t) {addr, len, block}; + r->run_count++; +} + +// Steps to the next run when the current one is used up. False at the end of the file. +static bool map_reader_fill(map_reader_t *r) { + while (r->cur == r->end) { + if (r->next_run == r->run_count) { + return false; + } + r->cur = r->runs[r->next_run].addr; + r->end = r->cur + r->runs[r->next_run].len; + r->next_run++; + } + return true; +} + +mp_uint_t storage_map_reader_readbyte(void *data) { + map_reader_t *r = data; + if (!map_reader_fill(r)) { + return MP_READER_EOF; + } + return *r->cur++; +} + +const uint8_t *storage_map_reader_try_read_rom(void *data, size_t len) { + map_reader_t *r = data; + map_reader_fill(r); + // A str in flash needs its NUL after it, so data may fill a run exactly only at the end + // of the file, where no str ends. + size_t avail = r->end - r->cur; + if (len > avail || (len == avail && r->next_run != r->run_count)) { + return NULL; + } + const uint8_t *addr = r->cur; + r->cur += len; + return addr; +} + +bool storage_map_import_uses_blocks(uint32_t lba, uint32_t count) { + // A port that erases a whole sector while the VM can run rewrites the neighbours too. + const uint32_t sector = CIRCUITPY_STORAGE_MAP_GUARD_BLOCKS; + uint32_t end = (lba + count + sector - 1) / sector * sector; + lba -= lba % sector; + for (map_reader_t *r = MP_STATE_VM(storage_mapped_imports); r != NULL; r = r->next_reader) { + for (size_t j = 0; j < r->run_count; j++) { + const map_run_t *run = &r->runs[j]; + if (run->block < end && lba < run->block + (run->len + FF_MIN_SS - 1) / FF_MIN_SS) { + return true; + } + } + } + return false; +} + +static void map_reader_close(void *data) { + // Kept in storage_mapped_imports until reload. +} + +bool storage_map_file_reader(mp_reader_t *reader, qstr filename) { + // The REPL can't be stopped while it waits for input, so a host write could not be held + // off until its imports are gone. Load them into RAM instead. + if (autoreload_is_suspended(AUTORELOAD_SUSPEND_REPL)) { + return false; + } + mp_obj_t args[2] = { + MP_OBJ_NEW_QSTR(filename), + MP_OBJ_NEW_QSTR(MP_QSTR_rb), + }; + mp_obj_t file = mp_vfs_open(MP_ARRAY_SIZE(args), &args[0], (mp_map_t *)&mp_const_empty_map); + map_reader_t *r = NULL; + size_t n = 0; + if (storage_map_runs(file, count_run, &n) == 0 && n > 0) { + r = m_new_obj_var(map_reader_t, runs, map_run_t, n); + r->cur = r->end = NULL; + r->next_run = r->run_count = 0; + storage_map_runs(file, add_run, r); + mapped_files_add(((pyb_file_obj_t *)MP_OBJ_TO_PTR(file))->fp.obj.sclust); + r->next_reader = MP_STATE_VM(storage_mapped_imports); + MP_STATE_VM(storage_mapped_imports) = r; + } + mp_stream_close(file); + if (r == NULL) { + return false; + } + reader->data = r; + reader->readbyte = storage_map_reader_readbyte; + reader->close = map_reader_close; + return true; +} +#endif diff --git a/shared-module/struct/__init__.c b/shared-module/struct/__init__.c index 715b5043021..ce71d06b754 100644 --- a/shared-module/struct/__init__.c +++ b/shared-module/struct/__init__.c @@ -14,7 +14,8 @@ #include "shared-bindings/struct/__init__.h" static void struct_validate_format(char fmt) { - #if MICROPY_NONSTANDARD_TYPECODES + #if MICROPY_PY_STRUCT_UNSAFE_TYPECODES + if (fmt == 'S' || fmt == 'O') { mp_raise_RuntimeError(MP_ERROR_TEXT("'S' and 'O' are not supported format types")); } @@ -46,7 +47,7 @@ static mp_uint_t get_fmt_num(const char **p) { while (unichar_isdigit(*++num)) { len++; } - mp_uint_t val = (mp_uint_t)MP_OBJ_SMALL_INT_VALUE(mp_parse_num_integer(*p, len, 10, NULL)); + mp_uint_t val = (mp_uint_t)mp_obj_get_int(mp_parse_num_integer(*p, len, 10, NULL)); *p = num; return val; } diff --git a/shared-module/synthio/Biquad.c b/shared-module/synthio/Biquad.c index 1418b86fd17..b93f497ba96 100644 --- a/shared-module/synthio/Biquad.c +++ b/shared-module/synthio/Biquad.c @@ -1,3 +1,4 @@ + // This file is part of the CircuitPython project: https://circuitpython.org // // SPDX-FileCopyrightText: Copyright (c) 2023 Jeff Epler for Adafruit Industries @@ -6,108 +7,276 @@ #include #include "shared-bindings/synthio/Biquad.h" -#include "shared-bindings/synthio/BlockBiquad.h" #include "shared-module/synthio/Biquad.h" +#include "shared-module/synthio/block.h" +#include "shared-bindings/synthio/__init__.h" -mp_obj_t common_hal_synthio_new_lpf(mp_float_t w0, mp_float_t Q) { - mp_float_t s = MICROPY_FLOAT_C_FUN(sin)(w0); - mp_float_t c = MICROPY_FLOAT_C_FUN(cos)(w0); - mp_float_t alpha = s / (2 * Q); - mp_float_t a0 = 1 + alpha; - mp_float_t a1 = -2 * c; - mp_float_t a2 = 1 - alpha; - mp_float_t b0 = (1 - c) / 2; - mp_float_t b1 = 1 - c; - mp_float_t b2 = (1 - c) / 2; - - mp_obj_t out_args[] = { - mp_obj_new_float(a1 / a0), - mp_obj_new_float(a2 / a0), - mp_obj_new_float(b0 / a0), - mp_obj_new_float(b1 / a0), - mp_obj_new_float(b2 / a0), - }; - - return namedtuple_make_new((const mp_obj_type_t *)&synthio_biquad_type_obj, MP_ARRAY_SIZE(out_args), 0, out_args); -} - -mp_obj_t common_hal_synthio_new_hpf(mp_float_t w0, mp_float_t Q) { - mp_float_t s = MICROPY_FLOAT_C_FUN(sin)(w0); - mp_float_t c = MICROPY_FLOAT_C_FUN(cos)(w0); - mp_float_t alpha = s / (2 * Q); - mp_float_t a0 = 1 + alpha; - mp_float_t a1 = -2 * c; - mp_float_t a2 = 1 - alpha; - mp_float_t b0 = (1 + c) / 2; - mp_float_t b1 = -(1 + c); - mp_float_t b2 = (1 + c) / 2; - - mp_obj_t out_args[] = { - mp_obj_new_float(a1 / a0), - mp_obj_new_float(a2 / a0), - mp_obj_new_float(b0 / a0), - mp_obj_new_float(b1 / a0), - mp_obj_new_float(b2 / a0), - }; - - return namedtuple_make_new((const mp_obj_type_t *)&synthio_biquad_type_obj, MP_ARRAY_SIZE(out_args), 0, out_args); -} - -mp_obj_t common_hal_synthio_new_bpf(mp_float_t w0, mp_float_t Q) { - mp_float_t s = MICROPY_FLOAT_C_FUN(sin)(w0); - mp_float_t c = MICROPY_FLOAT_C_FUN(cos)(w0); - mp_float_t alpha = s / (2 * Q); - mp_float_t a0 = 1 + alpha; - mp_float_t a1 = -2 * c; - mp_float_t a2 = 1 - alpha; - mp_float_t b0 = alpha; - mp_float_t b1 = 0; - mp_float_t b2 = -alpha; - - mp_obj_t out_args[] = { - mp_obj_new_float(a1 / a0), - mp_obj_new_float(a2 / a0), - mp_obj_new_float(b0 / a0), - mp_obj_new_float(b1 / a0), - mp_obj_new_float(b2 / a0), - }; - - return namedtuple_make_new((const mp_obj_type_t *)&synthio_biquad_type_obj, MP_ARRAY_SIZE(out_args), 0, out_args); -} - -static int32_t biquad_scale_arg_obj(mp_obj_t arg) { - return (int32_t)MICROPY_FLOAT_C_FUN(round)(MICROPY_FLOAT_C_FUN(ldexp)(mp_obj_get_float(arg), BIQUAD_SHIFT)); -} -void synthio_biquad_filter_assign(biquad_filter_state *st, mp_obj_t biquad_obj) { - if (biquad_obj == mp_const_none) { - return; +typedef struct { + mp_float_t s, c; +} sincos_result_t; + +#include // uint32_t + +// The famous Quake approximate square root function +static mp_float_t Q_rsqrt(mp_float_t number_in) { + float number = (float)number_in; + union { + float f; + uint32_t i; + } conv = { .f = (float)number }; + conv.i = 0x5f3759df - (conv.i >> 1); + conv.f *= 1.5F - (number * 0.5F * conv.f * conv.f); + return (mp_float_t)conv.f; +} + +static mp_float_t fast_sqrt(mp_float_t number) { + return number * Q_rsqrt(number); +} + +// Sine and cosine of theta, evaluated together. theta is the filter's angle +// 2 * pi * f / sample_rate, which is in [0, pi] up to Nyquist. +// +// Reflect into [0, pi / 2] (sin(pi - t) = sin(t), cos(pi - t) = -cos(t)), then +// into [0, pi / 4] by swapping the two (sin(pi / 2 - t) = cos(t)). On that +// interval a four-term polynomial for each, fitted to minimise the worst-case +// error, is accurate to the last bit or two of a float. +static void fast_sincos(mp_float_t theta, sincos_result_t *result) { + bool negate_cos = theta > (M_PI / 2); + mp_float_t t = negate_cos ? (M_PI - theta) : theta; + bool swap = t > (M_PI / 4); + if (swap) { + t = (M_PI / 2) - t; } - if (mp_obj_is_type(biquad_obj, &synthio_block_biquad_type_obj)) { - return; + mp_float_t t2 = t * t; + mp_float_t s = t * (1 + t2 * (-0.16666651 + t2 * (0.0083319786 + t2 * -0.00019495635))); + mp_float_t c = 1 + t2 * (-0.5 + t2 * (0.041666647 + t2 * (-0.0013887368 + t2 * 0.000024438452))); + mp_float_t sin_theta = swap ? c : s; + mp_float_t cos_theta = swap ? s : c; + result->s = sin_theta; + result->c = negate_cos ? -cos_theta : cos_theta; +} + +mp_obj_t common_hal_synthio_biquad_new(synthio_filter_mode mode) { + synthio_biquad_t *self = mp_obj_malloc(synthio_biquad_t, &synthio_biquad_type_obj); + self->mode = mode; + self->shift = BIQUAD_DEFAULT_SHIFT; + return MP_OBJ_FROM_PTR(self); +} + +synthio_filter_mode common_hal_synthio_biquad_get_mode(synthio_biquad_t *self) { + return self->mode; +} + +mp_obj_t common_hal_synthio_biquad_get_Q(synthio_biquad_t *self) { + return self->Q.obj; +} + +void common_hal_synthio_biquad_set_Q(synthio_biquad_t *self, mp_obj_t Q) { + synthio_block_assign_slot(Q, &self->Q, MP_QSTR_Q); +} + +mp_obj_t common_hal_synthio_biquad_get_A(synthio_biquad_t *self) { + return self->A.obj; +} + +void common_hal_synthio_biquad_set_A(synthio_biquad_t *self, mp_obj_t A) { + synthio_block_assign_slot(A, &self->A, MP_QSTR_A); +} + +mp_obj_t common_hal_synthio_biquad_get_frequency(synthio_biquad_t *self) { + return self->f0.obj; +} + +void common_hal_synthio_biquad_set_frequency(synthio_biquad_t *self, mp_obj_t frequency) { + synthio_block_assign_slot(frequency, &self->f0, MP_QSTR_frequency); +} + +static int32_t biquad_scale_arg_float(mp_float_t arg, int shift) { + mp_float_t scaled = MICROPY_FLOAT_C_FUN(round)(MICROPY_FLOAT_C_FUN(ldexp)(arg, shift)); + // biquad_choose_shift() leaves room for this; the clamp is so that a + // rounding tick at the very top of the range cannot wrap the sign. + if (scaled >= 2147483648.0) { + return INT32_MAX; + } + if (scaled <= -2147483648.0) { + return INT32_MIN; + } + return (int32_t)scaled; +} + +// The most fractional bits that all five coefficients can share and still fit +// in an int32_t, up to BIQUAD_MAX_SHIFT. A plain low-pass tops out just under 2 +// (that is a1) and gets 30; a shelf with 24 dB of gain reaches almost 32 and gets 26. +static int biquad_choose_shift(const mp_float_t *coefficients, size_t count) { + mp_float_t largest = 1; + for (size_t i = 0; i < count; i++) { + mp_float_t magnitude = MICROPY_FLOAT_C_FUN(fabs)(coefficients[i]); + if (magnitude > largest) { + largest = magnitude; + } + } + int exponent; + MICROPY_FLOAT_C_FUN(frexp)(largest, &exponent); // largest < 2 ** exponent + int shift = 31 - exponent; + if (shift > BIQUAD_MAX_SHIFT) { + shift = BIQUAD_MAX_SHIFT; } - if (mp_obj_is_type(biquad_obj, (const mp_obj_type_t *)&synthio_biquad_type_obj)) { - mp_obj_tuple_t *biquad = (mp_obj_tuple_t *)MP_OBJ_TO_PTR(biquad_obj); - st->a1 = biquad_scale_arg_obj(biquad->items[0]); - st->a2 = biquad_scale_arg_obj(biquad->items[1]); - st->b0 = biquad_scale_arg_obj(biquad->items[2]); - st->b1 = biquad_scale_arg_obj(biquad->items[3]); - st->b2 = biquad_scale_arg_obj(biquad->items[4]); + // The rounding term in the filter needs at least one bit. + return shift < 1 ? 1 : shift; +} + +static int float_equal_or_update( + mp_float_t *cached, + mp_float_t new) { + // uses memcmp to avoid error about equality float comparison + if (memcmp(cached, &new, sizeof(mp_float_t))) { + *cached = new; + return false; + } + return true; +} + +void common_hal_synthio_biquad_tick(mp_obj_t self_in) { + synthio_biquad_t *self = MP_OBJ_TO_PTR(self_in); + + mp_float_t W0 = synthio_block_slot_get(&self->f0) * synthio_global_W_scale; + mp_float_t Q = synthio_block_slot_get(&self->Q); + mp_float_t A = + (self->mode >= SYNTHIO_PEAKING_EQ) ? synthio_block_slot_get(&self->A) : 0; + + // n.b., assumes that the `mode` field is read-only + // n.b., use of `&` is deliberate, avoids short-circuiting behavior + if (float_equal_or_update(&self->cached_W0, W0) + & float_equal_or_update(&self->cached_Q, Q) + & float_equal_or_update(&self->cached_A, A)) { return; } - mp_raise_TypeError_varg(MP_ERROR_TEXT("%q must be of type %q or %q, not %q"), MP_QSTR_filter, MP_QSTR_Biquad, MP_QSTR_BlockBiquad, mp_obj_get_type(biquad_obj)->name); + sincos_result_t sc; + fast_sincos(W0, &sc); + + mp_float_t alpha = sc.s / (2 * Q); + + mp_float_t a0, a1, a2, b0, b1, b2; + + switch (self->mode) { + default: + a0 = 1 + alpha; + a1 = -2 * sc.c; + a2 = 1 - alpha; + + switch (self->mode) { + default: + case SYNTHIO_LOW_PASS: + b2 = b0 = (1 - sc.c) * .5; + b1 = 1 - sc.c; + break; + + case SYNTHIO_HIGH_PASS: + b2 = b0 = (1 + sc.c) * .5; + b1 = -(1 + sc.c); + break; + + case SYNTHIO_BAND_PASS: + b0 = alpha; + b1 = 0; + b2 = -b0; + break; + + case SYNTHIO_NOTCH: + b0 = 1; + b1 = -2 * sc.c; + b2 = 1; + } + + break; + + case SYNTHIO_PEAKING_EQ: + b0 = 1 + alpha * A; + b1 = -2 * sc.c; + b2 = 1 - alpha * A; + a0 = 1 + alpha / A; + a1 = -2 * sc.c; + a2 = 1 - alpha / A; + break; + + case SYNTHIO_LOW_SHELF: { + mp_float_t sqrt_A = fast_sqrt(A); + b0 = A * ((A + 1) - (A - 1) * sc.c + 2 * sqrt_A * alpha); + b1 = 2 * A * ((A - 1) - (A + 1) * sc.c); + b2 = A * ((A + 1) - (A - 1) * sc.c - 2 * sqrt_A * alpha); + a0 = (A + 1) + (A - 1) * sc.c + 2 * sqrt_A * alpha; + a1 = -2 * ((A - 1) + (A + 1) * sc.c); + a2 = (A + 1) + (A - 1) * sc.c - 2 * sqrt_A * alpha; + } + break; + + case SYNTHIO_HIGH_SHELF: { + mp_float_t sqrt_A = fast_sqrt(A); + b0 = A * ((A + 1) + (A - 1) * sc.c + 2 * sqrt_A * alpha); + b1 = -2 * A * ((A - 1) + (A + 1) * sc.c); + b2 = A * ((A + 1) + (A - 1) * sc.c - 2 * sqrt_A * alpha); + a0 = (A + 1) - (A - 1) * sc.c + 2 * sqrt_A * alpha; + a1 = 2 * ((A - 1) - (A + 1) * sc.c); + a2 = (A + 1) - (A - 1) * sc.c - 2 * sqrt_A * alpha; + } + break; + } + mp_float_t recip_a0 = 1 / a0; + + a1 *= recip_a0; + a2 *= recip_a0; + b0 *= recip_a0; + b1 *= recip_a0; + b2 *= recip_a0; + + mp_float_t coefficients[] = {a1, a2, b0, b1, b2}; + int shift = biquad_choose_shift(coefficients, MP_ARRAY_SIZE(coefficients)); + self->shift = shift; + self->a1 = biquad_scale_arg_float(a1, shift); + self->a2 = biquad_scale_arg_float(a2, shift); + self->b0 = biquad_scale_arg_float(b0, shift); + self->b1 = biquad_scale_arg_float(b1, shift); + self->b2 = biquad_scale_arg_float(b2, shift); } void synthio_biquad_filter_reset(biquad_filter_state *st) { - memset(&st->x, 0, 4 * sizeof(int16_t)); + memset(st, 0, sizeof(*st)); +} + +// Returns the new feedback state: the output with BIQUAD_STATE_SHIFT bits +// below the sample. Near 0 Hz a biquad turns each unit of error in its feedback +// into thousands of units of output, so the feedback must not be rounded to +// whole samples. The coefficients can have up to 30 fractional bits, so the +// sum of products needs 64 bits. +static inline int32_t biquad_filter_sample(int32_t input, int32_t a1, int32_t a2, int32_t b0, int32_t b1, int32_t b2, int shift, int32_t x0, int32_t x1, int32_t y0, int32_t y1) { + int64_t acc = ((int64_t)b0 * input + (int64_t)b1 * x0 + (int64_t)b2 * x1) * (1 << BIQUAD_STATE_SHIFT) + - (int64_t)a1 * y0 - (int64_t)a2 * y1; + // Add half a step, then shift, to round to nearest. + acc = (acc + ((int64_t)1 << (shift - 1))) >> shift; + if (acc > BIQUAD_STATE_MAX) { + return BIQUAD_STATE_MAX; + } + if (acc < BIQUAD_STATE_MIN) { + return BIQUAD_STATE_MIN; + } + return acc; } -void synthio_biquad_filter_samples(biquad_filter_state *st, int32_t *buffer, size_t n_samples) { - int32_t a1 = st->a1; - int32_t a2 = st->a2; - int32_t b0 = st->b0; - int32_t b1 = st->b1; - int32_t b2 = st->b2; +// The state is already within the range of a sample, so rounding is all it needs. +static inline int32_t biquad_state_to_sample(int32_t y) { + return (y + (1 << (BIQUAD_STATE_SHIFT - 1))) >> BIQUAD_STATE_SHIFT; +} + +void synthio_biquad_filter_samples(mp_obj_t self_in, biquad_filter_state *st, int32_t *buffer, size_t n_samples) { + synthio_biquad_t *self = MP_OBJ_TO_PTR(self_in); + + int32_t a1 = self->a1; + int32_t a2 = self->a2; + int32_t b0 = self->b0; + int32_t b1 = self->b1; + int32_t b2 = self->b2; + int shift = self->shift; int32_t x0 = st->x[0]; int32_t x1 = st->x[1]; @@ -116,16 +285,29 @@ void synthio_biquad_filter_samples(biquad_filter_state *st, int32_t *buffer, siz for (size_t n = n_samples; n; --n, ++buffer) { int32_t input = *buffer; - int32_t output = (b0 * input + b1 * x0 + b2 * x1 - a1 * y0 - a2 * y1 + (1 << (BIQUAD_SHIFT - 1))) >> BIQUAD_SHIFT; + int32_t y = biquad_filter_sample(input, a1, a2, b0, b1, b2, shift, x0, x1, y0, y1); x1 = x0; x0 = input; y1 = y0; - y0 = output; - *buffer = output; + y0 = y; + *buffer = biquad_state_to_sample(y); } st->x[0] = x0; st->x[1] = x1; st->y[0] = y0; st->y[1] = y1; } + +int32_t synthio_biquad_filter_sample(mp_obj_t self_in, biquad_filter_state *st, int32_t input) { + synthio_biquad_t *self = MP_OBJ_TO_PTR(self_in); + + int32_t y = biquad_filter_sample(input, self->a1, self->a2, self->b0, self->b1, self->b2, self->shift, st->x[0], st->x[1], st->y[0], st->y[1]); + + st->x[1] = st->x[0]; + st->x[0] = input; + st->y[1] = st->y[0]; + st->y[0] = y; + + return biquad_state_to_sample(y); +} diff --git a/shared-module/synthio/Biquad.h b/shared-module/synthio/Biquad.h index a0dac47a2f9..fc364b329e4 100644 --- a/shared-module/synthio/Biquad.h +++ b/shared-module/synthio/Biquad.h @@ -1,3 +1,4 @@ + // This file is part of the CircuitPython project: https://circuitpython.org // // SPDX-FileCopyrightText: Copyright (c) 2023 Jeff Epler for Adafruit Industries @@ -6,15 +7,34 @@ #pragma once -#include "py/obj.h" +#include "shared-bindings/synthio/Biquad.h" +#include "shared-module/synthio/block.h" -#define BIQUAD_SHIFT (15) +// The coefficients are fixed point with a per-filter number of fractional bits, +// kept in `shift`. It is chosen when the filter is updated, between 1 and this. +#define BIQUAD_MAX_SHIFT (30) +#define BIQUAD_DEFAULT_SHIFT (15) -typedef struct { +// The feedback state `y` has this many fractional bits below the output sample. +#define BIQUAD_STATE_SHIFT (12) +#define BIQUAD_STATE_MAX (32767 * (1 << BIQUAD_STATE_SHIFT)) +#define BIQUAD_STATE_MIN (-32768 * (1 << BIQUAD_STATE_SHIFT)) + +typedef struct synthio_biquad { + mp_obj_base_t base; + synthio_filter_mode mode; + synthio_block_slot_t f0, Q, A; + mp_float_t cached_W0, cached_Q, cached_A; int32_t a1, a2, b0, b1, b2; - int32_t x[2], y[2]; + uint8_t shift; +} synthio_biquad_t; + +typedef struct { + int32_t x[2]; + int32_t y[2]; // in units of 1 / (1 << BIQUAD_STATE_SHIFT) of a sample } biquad_filter_state; -void synthio_biquad_filter_assign(biquad_filter_state *st, mp_obj_t biquad_obj); +void common_hal_synthio_biquad_tick(mp_obj_t self_in); void synthio_biquad_filter_reset(biquad_filter_state *st); -void synthio_biquad_filter_samples(biquad_filter_state *st, int32_t *buffer, size_t n_samples); +void synthio_biquad_filter_samples(mp_obj_t self_in, biquad_filter_state *st, int32_t *buffer, size_t n_samples); +int32_t synthio_biquad_filter_sample(mp_obj_t self_in, biquad_filter_state *st, int32_t input); diff --git a/shared-module/synthio/BlockBiquad.c b/shared-module/synthio/BlockBiquad.c deleted file mode 100644 index 9940d2da9ac..00000000000 --- a/shared-module/synthio/BlockBiquad.c +++ /dev/null @@ -1,193 +0,0 @@ - -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2023 Jeff Epler for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#include -#include "shared-bindings/synthio/BlockBiquad.h" -#include "shared-module/synthio/BlockBiquad.h" -#include "shared-module/synthio/block.h" - -typedef struct { - mp_float_t s, c; -} sincos_result_t; - -#include // uint32_t - -// The famous Quake approximate square root function -static mp_float_t Q_rsqrt(mp_float_t number_in) { - float number = (float)number_in; - union { - float f; - uint32_t i; - } conv = { .f = (float)number }; - conv.i = 0x5f3759df - (conv.i >> 1); - conv.f *= 1.5F - (number * 0.5F * conv.f * conv.f); - return (mp_float_t)conv.f; -} - -static mp_float_t fast_sqrt(mp_float_t number) { - return number * Q_rsqrt(number); -} - -#define FOUR_OVER_PI (4 / M_PI) -static void fast_sincos(mp_float_t theta, sincos_result_t *result) { - mp_float_t x = (theta * FOUR_OVER_PI) - 1; - mp_float_t x2 = x * x, x3 = x2 * x, x4 = x2 * x2, x5 = x2 * x3; - mp_float_t c0 = 0.70708592, - c1x = -0.55535724 * x, - c2x2 = -0.21798592 * x2, - c3x3 = 0.05707685 * x3, - c4x4 = 0.0109 * x4, - c5x5 = -0.00171961 * x5; - - mp_float_t evens = c4x4 + c2x2 + c0, odds = c5x5 + c3x3 + c1x; - result->c = evens + odds; - result->s = evens - odds; -} - -mp_obj_t common_hal_synthio_block_biquad_new(synthio_filter_mode mode) { - synthio_block_biquad_t *self = mp_obj_malloc(synthio_block_biquad_t, &synthio_block_biquad_type_obj); - self->mode = mode; - return MP_OBJ_FROM_PTR(self); -} - -synthio_filter_mode common_hal_synthio_block_biquad_get_mode(synthio_block_biquad_t *self) { - return self->mode; -} - -mp_obj_t common_hal_synthio_block_biquad_get_Q(synthio_block_biquad_t *self) { - return self->Q.obj; -} - -void common_hal_synthio_block_biquad_set_Q(synthio_block_biquad_t *self, mp_obj_t Q) { - synthio_block_assign_slot(Q, &self->Q, MP_QSTR_Q); -} - -mp_obj_t common_hal_synthio_block_biquad_get_A(synthio_block_biquad_t *self) { - return self->A.obj; -} - -void common_hal_synthio_block_biquad_set_A(synthio_block_biquad_t *self, mp_obj_t A) { - synthio_block_assign_slot(A, &self->A, MP_QSTR_A); -} - -mp_obj_t common_hal_synthio_block_biquad_get_frequency(synthio_block_biquad_t *self) { - return self->f0.obj; -} - -void common_hal_synthio_block_biquad_set_frequency(synthio_block_biquad_t *self, mp_obj_t frequency) { - synthio_block_assign_slot(frequency, &self->f0, MP_QSTR_frequency); -} - -static int32_t biquad_scale_arg_float(mp_float_t arg) { - return (int32_t)MICROPY_FLOAT_C_FUN(round)(MICROPY_FLOAT_C_FUN(ldexp)(arg, BIQUAD_SHIFT)); -} - -static int float_equal_or_update( - mp_float_t *cached, - mp_float_t new) { - // uses memcmp to avoid error about equality float comparison - if (memcmp(cached, &new, sizeof(mp_float_t))) { - *cached = new; - return false; - } - return true; -} - -void common_hal_synthio_block_biquad_tick(mp_obj_t self_in, biquad_filter_state *filter_state) { - synthio_block_biquad_t *self = MP_OBJ_TO_PTR(self_in); - - mp_float_t W0 = synthio_block_slot_get(&self->f0) * synthio_global_W_scale; - mp_float_t Q = synthio_block_slot_get(&self->Q); - mp_float_t A = - (self->mode >= SYNTHIO_PEAKING_EQ) ? synthio_block_slot_get(&self->A) : 0; - - // n.b., assumes that the `mode` field is read-only - // n.b., use of `&` is deliberate, avoids short-circuiting behavior - if (float_equal_or_update(&self->cached_W0, W0) - & float_equal_or_update(&self->cached_Q, Q) - & float_equal_or_update(&self->cached_A, A)) { - return; - } - - sincos_result_t sc; - fast_sincos(W0, &sc); - - mp_float_t alpha = sc.s / (2 * Q); - - mp_float_t a0, a1, a2, b0, b1, b2; - - switch (self->mode) { - default: - a0 = 1 + alpha; - a1 = -2 * sc.c; - a2 = 1 - alpha; - - switch (self->mode) { - default: - case SYNTHIO_LOW_PASS: - b2 = b0 = (1 - sc.c) * .5; - b1 = 1 - sc.c; - break; - - case SYNTHIO_HIGH_PASS: - b2 = b0 = (1 + sc.c) * .5; - b1 = -(1 + sc.c); - break; - - case SYNTHIO_BAND_PASS: - b0 = alpha; - b1 = 0; - b2 = -b0; - break; - - case SYNTHIO_NOTCH: - b0 = 1; - b1 = -2 * sc.c; - b2 = 1; - } - - break; - - case SYNTHIO_PEAKING_EQ: - b0 = 1 + alpha * A; - b1 = -2 * sc.c; - b2 = 1 + alpha * A; - a0 = 1 + alpha / A; - a1 = -2 * sc.c; - a2 = 1 - alpha / A; - break; - - case SYNTHIO_LOW_SHELF: { - mp_float_t sqrt_A = fast_sqrt(A); - b0 = A * ((A + 1) - (A - 1) * sc.c + 2 * sqrt_A * alpha); - b1 = 2 * A * ((A - 1) - (A + 1) * sc.c); - b2 = A * ((A + 1) - (A - 1) * sc.c - 2 * sqrt_A * alpha); - a0 = (A + 1) + (A - 1) * sc.c + 2 * sqrt_A * alpha; - a1 = -2 * ((A - 1) + (A + 1) * sc.c); - a2 = (A + 1) + (A - 1) * sc.c - 2 * sqrt_A * alpha; - } - break; - - case SYNTHIO_HIGH_SHELF: { - mp_float_t sqrt_A = fast_sqrt(A); - b0 = A * ((A + 1) + (A - 1) * sc.c + 2 * sqrt_A * alpha); - b1 = -2 * A * ((A - 1) + (A + 1) * sc.c); - b2 = A * ((A + 1) + (A - 1) * sc.c - 2 * sqrt_A * alpha); - a0 = (A + 1) - (A - 1) * sc.c + 2 * sqrt_A * alpha; - a1 = 2 * ((A - 1) - (A + 1) * sc.c); - a2 = (A + 1) - (A - 1) * sc.c - 2 * sqrt_A * alpha; - } - break; - } - mp_float_t recip_a0 = 1 / a0; - - filter_state->a1 = biquad_scale_arg_float(a1 * recip_a0); - filter_state->a2 = biquad_scale_arg_float(a2 * recip_a0); - filter_state->b0 = biquad_scale_arg_float(b0 * recip_a0); - filter_state->b1 = biquad_scale_arg_float(b1 * recip_a0); - filter_state->b2 = biquad_scale_arg_float(b2 * recip_a0); -} diff --git a/shared-module/synthio/BlockBiquad.h b/shared-module/synthio/BlockBiquad.h deleted file mode 100644 index 529b8425304..00000000000 --- a/shared-module/synthio/BlockBiquad.h +++ /dev/null @@ -1,21 +0,0 @@ - -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2023 Jeff Epler for Adafruit Industries -// -// SPDX-License-Identifier: MIT - -#pragma once - -#include "shared-bindings/synthio/BlockBiquad.h" -#include "shared-module/synthio/Biquad.h" -#include "shared-module/synthio/block.h" - -typedef struct synthio_block_biquad { - mp_obj_base_t base; - synthio_filter_mode mode; - synthio_block_slot_t f0, Q, A; - mp_float_t cached_W0, cached_Q, cached_A; -} synthio_block_biquad_t; - -void common_hal_synthio_block_biquad_tick(mp_obj_t self_in, biquad_filter_state *filter_state); diff --git a/shared-module/synthio/MidiTrack.c b/shared-module/synthio/MidiTrack.c index 94430289bda..23641c12a2c 100644 --- a/shared-module/synthio/MidiTrack.c +++ b/shared-module/synthio/MidiTrack.c @@ -10,40 +10,109 @@ static void record_midi_stream_error(synthio_miditrack_obj_t *self) { - self->error_location = self->pos; + // keep the first error; later ones are usually fallout from this one + if (self->error_location < 0) { + self->error_location = self->pos; + } self->pos = self->track.len; } -static mp_obj_t parse_note(synthio_miditrack_obj_t *self) { - uint8_t *buffer = self->track.buf; - size_t len = self->track.len; - if (self->pos + 1 >= len) { +// Check that `count` more bytes are available, ending the track if not. +static bool need_bytes(synthio_miditrack_obj_t *self, size_t count) { + if (count > self->track.len - self->pos) { record_midi_stream_error(self); + return false; + } + return true; +} + +// A duration can be longer than span.dur (a uint16_t) can hold, so the +// remainder is kept in `pending` and handed over a chunk at a time. +static void set_remaining(synthio_miditrack_obj_t *self, uint32_t samples) { + uint16_t chunk = samples > UINT16_MAX ? UINT16_MAX : (uint16_t)samples; + self->synth.span.dur = chunk; + self->pending = samples - chunk; +} + +// Returns the note in the low 8 bits and the velocity in the next 8, or -1 +// if the pair could not be read. +static int parse_note(synthio_miditrack_obj_t *self) { + uint8_t *buffer = self->track.buf; + if (!need_bytes(self, 2)) { + return -1; } - uint8_t note = buffer[(self->pos)++]; - if (note > 127 || buffer[(self->pos)++] > 127) { + uint8_t note = buffer[self->pos++]; + uint8_t velocity = buffer[self->pos++]; + if (note > 127 || velocity > 127) { record_midi_stream_error(self); + return -1; } - return MP_OBJ_NEW_SMALL_INT(note); + return note | (velocity << 8); } -static int decode_duration(synthio_miditrack_obj_t *self) { +// MIDI variable-length quantity: up to 4 bytes of 7 bits each. +static uint32_t decode_varint(synthio_miditrack_obj_t *self) { uint8_t *buffer = self->track.buf; - size_t len = self->track.len; - uint8_t c; - uint32_t delta = 0; - do { - c = buffer[self->pos++]; - delta <<= 7; - delta |= c & 0x7f; - } while ((c & 0x80) && (self->pos < len)); - - // errors cannot be raised from the background task, so simply end the track. - if (c & 0x80) { - self->pos = self->track.len; + uint32_t value = 0; + for (size_t i = 0; i < 4; i++) { + if (!need_bytes(self, 1)) { + return 0; + } + uint8_t c = buffer[self->pos++]; + value = (value << 7) | (c & 0x7f); + if (!(c & 0x80)) { + return value; + } + } + // a fifth continuation byte cannot be part of a valid quantity + record_midi_stream_error(self); + return 0; +} + +static void decode_duration(synthio_miditrack_obj_t *self) { + uint32_t delta = decode_varint(self); + uint64_t samples = (uint64_t)delta * self->synth.base.sample_rate / self->tempo; + set_remaining(self, samples > UINT32_MAX ? UINT32_MAX : (uint32_t)samples); +} + +// Meta (0xFF) and system exclusive (0xF0/0xF7) events both carry an explicit +// length, so they can be skipped exactly rather than guessed at. +static void decode_system_event(synthio_miditrack_obj_t *self, uint8_t status) { + uint8_t *buffer = self->track.buf; + if (status == 0xFF) { + if (!need_bytes(self, 1)) { + return; + } + uint8_t type = buffer[self->pos++]; + uint32_t length = decode_varint(self); + if (!need_bytes(self, length)) { + return; + } + if (type == 0x2F) { // End of Track + self->pos = self->track.len; + return; + } + if (type == 0x51 && length == 3 && self->ticks_per_beat != 0) { // Set Tempo + uint32_t us_per_beat = (buffer[self->pos] << 16) | + (buffer[self->pos + 1] << 8) | buffer[self->pos + 2]; + if (us_per_beat != 0) { + uint32_t ticks = (uint32_t)(((uint64_t)self->ticks_per_beat * 1000000) / us_per_beat); + if (ticks != 0) { + self->tempo = ticks; + } + } + } + self->pos += length; + } else if (status == 0xF0 || status == 0xF7) { + uint32_t length = decode_varint(self); + if (!need_bytes(self, length)) { + return; + } + self->pos += length; + } else { + // system common and real-time bytes have no meaning in a file record_midi_stream_error(self); } - return delta * self->synth.base.sample_rate / self->tempo; } // invariant: pointing at a MIDI message @@ -51,15 +120,35 @@ static void decode_until_pause(synthio_miditrack_obj_t *self) { uint8_t *buffer = self->track.buf; size_t len = self->track.len; do { - switch (buffer[self->pos++] >> 4) { - case 8: { // Note Off - mp_obj_t note = parse_note(self); - synthio_span_change_note(&self->synth, note, SYNTHIO_SILENCE); + if (self->pos >= len) { + break; + } + uint8_t status = buffer[self->pos]; + if (status & 0x80) { + self->pos++; + // a channel message arms running status; a system one cancels it + self->running_status = (status < 0xF0) ? status : 0; + } else { + // running status: the status byte is omitted and the previous + // channel message is implied + status = self->running_status; + if (status == 0) { + record_midi_stream_error(self); break; } - case 9: { // Note On - mp_obj_t note = parse_note(self); - synthio_span_change_note(&self->synth, SYNTHIO_SILENCE, note); + } + switch (status >> 4) { + case 8: // Note Off + case 9: { // Note On, but a velocity of zero means Note Off + int parsed = parse_note(self); + if (parsed >= 0) { + mp_obj_t note = MP_OBJ_NEW_SMALL_INT(parsed & 0xff); + if ((status >> 4) == 9 && (parsed >> 8) != 0) { + synthio_span_change_note(&self->synth, SYNTHIO_SILENCE, note); + } else { + synthio_span_change_note(&self->synth, note, SYNTHIO_SILENCE); + } + } break; } case 10: @@ -69,37 +158,41 @@ static void decode_until_pause(synthio_miditrack_obj_t *self) { break; case 12: case 13: // one data byte to ignore - if (self->pos >= len || buffer[self->pos++] > 127) { + if (need_bytes(self, 1) && buffer[self->pos++] > 127) { record_midi_stream_error(self); } break; - case 15: // the full syntax is too complicated, just assume it's "End of Track" event - self->pos = len; + default: // 15: meta or system exclusive + decode_system_event(self, status); break; - default: // invalid event - record_midi_stream_error(self); } if (self->pos < len) { - self->synth.span.dur = decode_duration(self); + decode_duration(self); } - } while (self->pos < len && self->synth.span.dur == 0); + } while (self->pos < len && self->synth.span.dur == 0 && self->pending == 0); } static void start_parse(synthio_miditrack_obj_t *self) { self->pos = 0; self->error_location = -1; - self->synth.span.dur = decode_duration(self); - if (self->synth.span.dur == 0) { + self->pending = 0; + self->running_status = 0; + // a tempo map applies from the top of the track, so rewind it too + self->tempo = self->base_tempo; + decode_duration(self); + if (self->synth.span.dur == 0 && self->pending == 0) { // the usual case: the file starts with some MIDI event, not a delay decode_until_pause(self); } } 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, - mp_obj_t waveform_obj, mp_obj_t filter_obj, mp_obj_t envelope_obj) { + const uint8_t *buffer, uint32_t len, uint32_t tempo, uint32_t ticks_per_beat, + uint32_t sample_rate, mp_obj_t waveform_obj, mp_obj_t filter_obj, + mp_obj_t envelope_obj) { - self->tempo = tempo; + self->tempo = self->base_tempo = tempo; + self->ticks_per_beat = ticks_per_beat; self->track.buf = (void *)buffer; self->track.len = len; @@ -116,6 +209,19 @@ mp_int_t common_hal_synthio_miditrack_get_error_location(synthio_miditrack_obj_t return self->error_location; } +mp_int_t common_hal_synthio_miditrack_get_tempo(synthio_miditrack_obj_t *self) { + return self->tempo; +} + +void common_hal_synthio_miditrack_set_tempo(synthio_miditrack_obj_t *self, mp_int_t value) { + mp_int_t val = mp_arg_validate_int_min(value, 1, MP_QSTR_tempo); + uint64_t remaining = (uint64_t)self->synth.span.dur + self->pending; + remaining = remaining * self->tempo / val; + set_remaining(self, remaining > UINT32_MAX ? UINT32_MAX : (uint32_t)remaining); + // becomes the new baseline, so that looping does not undo it + self->tempo = self->base_tempo = val; +} + void synthio_miditrack_reset_buffer(synthio_miditrack_obj_t *self, bool single_channel_output, uint8_t channel) { synthio_synth_reset_buffer(&self->synth, single_channel_output, channel); @@ -131,7 +237,10 @@ audioio_get_buffer_result_t synthio_miditrack_get_buffer(synthio_miditrack_obj_t synthio_synth_synthesize(&self->synth, buffer, buffer_length, single_channel_output ? 0 : channel); if (self->synth.span.dur == 0) { - if (self->pos == self->track.len) { + if (self->pending != 0) { + // still inside a gap too long for a single span + set_remaining(self, self->pending); + } else if (self->pos == self->track.len) { return GET_BUFFER_DONE; } else { decode_until_pause(self); diff --git a/shared-module/synthio/MidiTrack.h b/shared-module/synthio/MidiTrack.h index 1e4d5cba2da..e8a6a9bf864 100644 --- a/shared-module/synthio/MidiTrack.h +++ b/shared-module/synthio/MidiTrack.h @@ -16,7 +16,16 @@ typedef struct { // invariant: after initial startup, pos always points just after an encoded duration, i.e., at a midi message (or at EOF) size_t pos; mp_int_t error_location; + // current tempo in ticks per second, and the value to rewind it to uint32_t tempo; + uint32_t base_tempo; + // samples of the current delay that did not fit in span.dur + uint32_t pending; + // ticks per quarter note (15 bits in the file header), or 0 when the + // timing is absolute (SMPTE) and Set Tempo events do not apply + uint16_t ticks_per_beat; + // last channel status byte, for events that omit it (running status) + uint8_t running_status; } synthio_miditrack_obj_t; diff --git a/shared-module/synthio/Note.c b/shared-module/synthio/Note.c index 0e612914ec7..270d8ec21b4 100644 --- a/shared-module/synthio/Note.c +++ b/shared-module/synthio/Note.c @@ -25,7 +25,11 @@ mp_obj_t common_hal_synthio_note_get_filter_obj(synthio_note_obj_t *self) { } void common_hal_synthio_note_set_filter(synthio_note_obj_t *self, mp_obj_t filter_in) { - synthio_biquad_filter_assign(&self->filter_state, filter_in); + if (filter_in != mp_const_none && !mp_obj_is_type(filter_in, &synthio_biquad_type_obj)) { + mp_raise_TypeError_varg( + MP_ERROR_TEXT("%q must be of type %q, not %q"), + MP_QSTR_filter, MP_QSTR_Biquad, mp_obj_get_type(filter_in)->name); + } self->filter_obj = filter_in; } @@ -192,13 +196,11 @@ static uint32_t pitch_bend(uint32_t frequency_scaled, int32_t bend_value) { uint32_t synthio_note_step(synthio_note_obj_t *self, int32_t sample_rate, int16_t dur, int16_t loudness[2]) { int panning = synthio_block_slot_get_scaled(&self->panning, -ALMOST_ONE, ALMOST_ONE); - int left_panning_scaled, right_panning_scaled; + int left_panning_scaled = 32768, right_panning_scaled = 32768; if (panning >= 0) { - left_panning_scaled = 32768; - right_panning_scaled = 32767 - panning; + left_panning_scaled = 32768 - panning; } else { - right_panning_scaled = 32768; - left_panning_scaled = 32767 + panning; + right_panning_scaled = 32768 + panning; } int amplitude = synthio_block_slot_get_scaled(&self->amplitude, -ALMOST_ONE, ALMOST_ONE); diff --git a/shared-module/synthio/__init__.c b/shared-module/synthio/__init__.c index bb39daf0839..29c1fb55a56 100644 --- a/shared-module/synthio/__init__.c +++ b/shared-module/synthio/__init__.c @@ -9,7 +9,6 @@ #include "shared-bindings/audiocore/__init__.h" #include "shared-bindings/synthio/__init__.h" #include "shared-module/synthio/Biquad.h" -#include "shared-module/synthio/BlockBiquad.h" #include "shared-module/synthio/Note.h" #include "py/runtime.h" #include @@ -25,7 +24,6 @@ static const int16_t square_wave[] = {-32768, 32767}; static const uint16_t notes[] = {8372, 8870, 9397, 9956, 10548, 11175, 11840, 12544, 13290, 14080, 14917, 15804}; // 9th octave - static int64_t round_float_to_int64(mp_float_t f) { return (int64_t)(f + MICROPY_FLOAT_CONST(0.5)); } @@ -205,21 +203,20 @@ static bool synth_note_into_buffer(synthio_synth_t *synth, int chan, int32_t *ou uint32_t lim = waveform_length << SYNTHIO_FREQUENCY_SHIFT; uint32_t accum = synth->accum[chan]; - if (dds_rate > lim / 2) { + if (dds_rate > (lim - offset) / 2) { // beyond nyquist, can't play note return false; } - // can happen if note waveform gets set mid-note, but the expensive modulo is usually avoided - if (accum > lim) { - accum = accum % lim + offset; + if (accum >= lim) { + accum = accum < offset ? offset : offset + (accum - offset) % (lim - offset); } // first, fill with waveform for (uint16_t i = 0; i < dur; i++) { accum += dds_rate; // because dds_rate is low enough, the subtraction is guaranteed to go back into range, no expensive modulo needed - if (accum > lim) { + if (accum >= lim) { accum = accum - lim + offset; } int16_t idx = accum >> SYNTHIO_FREQUENCY_SHIFT; @@ -228,31 +225,30 @@ static bool synth_note_into_buffer(synthio_synth_t *synth, int chan, int32_t *ou synth->accum[chan] = accum; if (ring_dds_rate) { - if (ring_dds_rate > lim / 2) { + accum = synth->ring_accum[chan]; + offset = ring_waveform_start << SYNTHIO_FREQUENCY_SHIFT; + lim = ring_waveform_length << SYNTHIO_FREQUENCY_SHIFT; + + if (ring_dds_rate > (lim - offset) / 2) { // beyond nyquist, can't play ring (but did synth main sound so // return true) return true; } - // now modulate by ring and accumulate - accum = synth->ring_accum[chan]; - offset = ring_waveform_start << SYNTHIO_FREQUENCY_SHIFT; - lim = ring_waveform_length << SYNTHIO_FREQUENCY_SHIFT; - // can happen if note waveform gets set mid-note, but the expensive modulo is usually avoided - if (accum > lim) { - accum = accum % lim + offset; + if (accum >= lim) { + accum = accum < offset ? offset : offset + (accum - offset) % (lim - offset); } for (uint16_t i = 0; i < dur; i++) { accum += ring_dds_rate; // because dds_rate is low enough, the subtraction is guaranteed to go back into range, no expensive modulo needed - if (accum > lim) { + if (accum >= lim) { accum = accum - lim + offset; } int16_t idx = accum >> SYNTHIO_FREQUENCY_SHIFT; - int16_t wi = (ring_waveform[idx] * out_buffer32[i]) / 32768; - out_buffer32[i] = wi; + int32_t wi = (ring_waveform[idx] * out_buffer32[i]) / 32768; + out_buffer32[i] = wi > 32767 ? 32767 : wi; } synth->ring_accum[chan] = accum; } @@ -270,17 +266,54 @@ static mp_obj_t synthio_synth_get_note_filter(mp_obj_t note_obj) { return mp_const_none; } -static void sum_with_loudness(int32_t *out_buffer32, int32_t *tmp_buffer32, int16_t loudness[2], size_t dur, int synth_chan) { +// Rather than immediately changing the loudness of audio playback, we keep a separate buffer of +// the "active" loudness and wait until we meet the conditions of a "zero crossing". A zero crossing +// occurs when either the current value is 0 or the value changes from negative to positive or +// vice-versa. This is detected by keeping a copy of the previous frame of audio data and checking +// to see if the sign of the value has changed. By only changing loudness during zero crossings, we +// avoid audible pops/clicks which can be unpleasant. +static void assign_loudness(int32_t word, int32_t *last_word, int16_t active_loudness[2], int16_t pending_loudness[2]) { + // If the active loudness already matches the pending loudness, exit early. + if (MP_LIKELY(active_loudness[0] == pending_loudness[0]) && MP_LIKELY(active_loudness[1] == pending_loudness[1])) { + return; + } + + // Check for a zero crossing: current value is 0 or has changed sign from the previous value. + if (word == 0 || (*last_word != 0 && ((*last_word > 0) == (word < 0) || (*last_word < 0) == (word > 0)))) { + // Copy over our pending loudness. Will cause future calls to `assign_loudness` to exit + // early. + active_loudness[0] = pending_loudness[0]; + active_loudness[1] = pending_loudness[1]; + } else { + // Update our copy of the previous word for future comparisons (an initial value of 0 is + // ignored). + *last_word = word; + } +} + +static void sum_with_loudness(int32_t *out_buffer32, int32_t *tmp_buffer32, int16_t active_loudness[2], int16_t pending_loudness[2], size_t dur, int synth_chan) { + int32_t word, last_word = 0; if (synth_chan == 1) { for (size_t i = 0; i < dur; i++) { - *out_buffer32++ += (*tmp_buffer32++ *loudness[0]) >> 16; + word = *tmp_buffer32++; + assign_loudness(word, &last_word, active_loudness, pending_loudness); + *out_buffer32++ += synthio_sat16((word * active_loudness[0]), 16); } } else { for (size_t i = 0; i < dur; i++) { - *out_buffer32++ += (*tmp_buffer32 * loudness[0]) >> 16; - *out_buffer32++ += (*tmp_buffer32++ *loudness[1]) >> 16; + word = *tmp_buffer32; + assign_loudness(word, &last_word, active_loudness, pending_loudness); + *out_buffer32++ += synthio_sat16((word * active_loudness[0]), 16); + *out_buffer32++ += synthio_sat16((word * active_loudness[1]), 16); + tmp_buffer32++; } } + + // Force the active loudness to match the pending loudness just in case the conditions of a + // zero crossing weren't met within the last `SYNTHIO_MAX_DUR` frames. Will ensure minimal + // delay in amplitude or panning changes at the potential expensive of an audible pop. + active_loudness[0] = pending_loudness[0]; + active_loudness[1] = pending_loudness[1]; } void synthio_synth_synthesize(synthio_synth_t *synth, uint8_t **bufptr, uint32_t *buffer_length, uint8_t channel) { @@ -327,14 +360,12 @@ void synthio_synth_synthesize(synthio_synth_t *synth, uint8_t **bufptr, uint32_t mp_obj_t filter_obj = synthio_synth_get_note_filter(note_obj); if (filter_obj != mp_const_none) { synthio_note_obj_t *note = MP_OBJ_TO_PTR(note_obj); - if (mp_obj_is_type(filter_obj, &synthio_block_biquad_type_obj)) { - common_hal_synthio_block_biquad_tick(filter_obj, ¬e->filter_state); - } - synthio_biquad_filter_samples(¬e->filter_state, tmp_buffer32, dur); + common_hal_synthio_biquad_tick(filter_obj); + synthio_biquad_filter_samples(filter_obj, ¬e->filter_state, tmp_buffer32, dur); } // adjust loudness by envelope - sum_with_loudness(out_buffer32, tmp_buffer32, loudness, dur, synth->base.channel_count); + sum_with_loudness(out_buffer32, tmp_buffer32, synth->active_loudness[chan], loudness, dur, synth->base.channel_count); } int16_t *out_buffer16 = (int16_t *)(void *)synth->buffers[synth->buffer_index]; @@ -384,8 +415,8 @@ void synthio_synth_init(synthio_synth_t *synth, uint32_t sample_rate, int channe synthio_synth_parse_waveform(&synth->waveform_bufinfo, waveform_obj); mp_arg_validate_int_range(channel_count, 1, 2, MP_QSTR_channel_count); synth->buffer_length = SYNTHIO_MAX_DUR * SYNTHIO_BYTES_PER_SAMPLE * channel_count; - synth->buffers[0] = m_malloc(synth->buffer_length); - synth->buffers[1] = m_malloc(synth->buffer_length); + synth->buffers[0] = m_malloc_without_collect(synth->buffer_length); + synth->buffers[1] = m_malloc_without_collect(synth->buffer_length); synth->base.channel_count = channel_count; synth->base.single_buffer = false; synth->other_channel = -1; @@ -443,8 +474,15 @@ static int find_channel_with_note(synthio_synth_t *synth, mp_obj_t note) { bool synthio_span_change_note(synthio_synth_t *synth, mp_obj_t old_note, mp_obj_t new_note) { int channel; if (new_note != SYNTHIO_SILENCE && (channel = find_channel_with_note(synth, new_note)) != -1) { - // note already playing, re-enter attack phase - synth->envelope_state[channel].state = SYNTHIO_ENVELOPE_STATE_ATTACK; + if (synth->envelope_state[channel].level == 0) { + // released and already decayed to silence, but not yet reaped: + // treat this like a fresh press, not a swell from 0 + synthio_envelope_state_init(&synth->envelope_state[channel], synthio_synth_get_note_envelope(synth, new_note)); + synth->accum[channel] = 0; + } else { + // note already playing, re-enter attack phase + synth->envelope_state[channel].state = SYNTHIO_ENVELOPE_STATE_ATTACK; + } return true; } channel = find_channel_with_note(synth, old_note); diff --git a/shared-module/synthio/__init__.h b/shared-module/synthio/__init__.h index 3711abf10de..91d0179ecf1 100644 --- a/shared-module/synthio/__init__.h +++ b/shared-module/synthio/__init__.h @@ -21,7 +21,10 @@ #include "shared-module/audiocore/__init__.h" #include "shared-bindings/synthio/__init__.h" #include "shared-bindings/synthio/Biquad.h" -#include "shared-bindings/synthio/BlockBiquad.h" + +#if defined(__ARM_FEATURE_SAT) && __ARM_FEATURE_SAT +#include +#endif typedef struct { uint16_t dur; @@ -56,6 +59,7 @@ typedef struct synthio_synth { uint32_t accum[CIRCUITPY_SYNTHIO_MAX_CHANNELS]; uint32_t ring_accum[CIRCUITPY_SYNTHIO_MAX_CHANNELS]; synthio_envelope_state_t envelope_state[CIRCUITPY_SYNTHIO_MAX_CHANNELS]; + int16_t active_loudness[CIRCUITPY_SYNTHIO_MAX_CHANNELS][2]; } synthio_synth_t; typedef struct { @@ -97,7 +101,20 @@ extern mp_float_t synthio_global_rate_scale, synthio_global_W_scale; extern uint8_t synthio_global_tick; void shared_bindings_synthio_lfo_tick(uint32_t sample_rate, uint16_t num_samples); -static inline bool synthio_is_any_biquad(mp_obj_t biquad_maybe) { - return mp_obj_is_type(biquad_maybe, &synthio_block_biquad_type_obj) - || mp_obj_is_type(biquad_maybe, (const mp_obj_type_t *)&synthio_biquad_type_obj); +// cleaner sat16 by http://www.moseleyinstruments.com/ +static inline int16_t synthio_sat16(int32_t n, int rshift) { + // Round towards 0 to avoid recirculating round-off noise. + n += (n >> 31) & ((1 << rshift) - 1); + n >>= rshift; + #if defined(__ARM_FEATURE_SAT) && __ARM_FEATURE_SAT + return __ssat(n, 16); + #else + if (n > 32767) { + return 32767; + } + if (n < -32768) { + return -32768; + } + return n; + #endif } diff --git a/shared-module/terminalio/Terminal.c b/shared-module/terminalio/Terminal.c index 2828d0d3800..74348cf6d14 100644 --- a/shared-module/terminalio/Terminal.c +++ b/shared-module/terminalio/Terminal.c @@ -10,20 +10,150 @@ #include "shared-bindings/displayio/TileGrid.h" #include "shared-bindings/displayio/Palette.h" #include "shared-bindings/terminalio/Terminal.h" +#include "shared-bindings/fontio/BuiltinFont.h" +#if CIRCUITPY_LVFONTIO +#include "shared-bindings/lvfontio/OnDiskFont.h" +#endif #if CIRCUITPY_STATUS_BAR #include "shared-bindings/supervisor/__init__.h" #include "shared-bindings/supervisor/StatusBar.h" #endif +#include "supervisor/shared/serial.h" + +uint16_t terminalio_terminal_get_glyph_index(mp_obj_t font, mp_uint_t codepoint, bool *is_full_width) { + if (is_full_width != NULL) { + *is_full_width = false; // Default to not full width + } + + #if CIRCUITPY_LVFONTIO + if (mp_obj_is_type(font, &lvfontio_ondiskfont_type)) { + // For LV fonts, we need to cache the glyph first + lvfontio_ondiskfont_t *lv_font = MP_OBJ_TO_PTR(font); + bool full_width = false; + int16_t slot = common_hal_lvfontio_ondiskfont_cache_glyph(lv_font, codepoint, &full_width); + + if (is_full_width != NULL) { + *is_full_width = full_width; + } + + if (slot == -1) { + // Not found or couldn't cache + return 0xffff; + } + return (uint16_t)slot; + } + #endif + + #if CIRCUITPY_FONTIO + if (mp_obj_is_type(font, &fontio_builtinfont_type)) { + // Use the standard fontio function + fontio_builtinfont_t *fontio_font = MP_OBJ_TO_PTR(font); + uint8_t index = fontio_builtinfont_get_glyph_index(fontio_font, codepoint); + if (index == 0xff) { + return 0xffff; + } + return index; + } + #endif + + // Unsupported font type + return 0xffff; +} + +static void wrap_cursor(uint16_t width, uint16_t height, uint16_t *cursor_x, uint16_t *cursor_y) { + if (*cursor_x >= width) { + *cursor_y = *cursor_y + 1; + *cursor_x %= width; + } + if (*cursor_y >= height) { + *cursor_y %= height; + } +} + +static void release_current_glyph(displayio_tilegrid_t *tilegrid, mp_obj_t font, uint16_t x, uint16_t y) { + #if CIRCUITPY_LVFONTIO + if (!mp_obj_is_type(font, &lvfontio_ondiskfont_type)) { + return; + } + uint16_t current_tile = common_hal_displayio_tilegrid_get_tile(tilegrid, x, y); + if (current_tile == 0) { + } + common_hal_lvfontio_ondiskfont_release_glyph(MP_OBJ_TO_PTR(font), current_tile); + #endif +} + +static void terminalio_terminal_set_tile(terminalio_terminal_obj_t *self, bool status_bar, mp_uint_t character, bool release_glyphs) { + displayio_tilegrid_t *tilegrid = self->scroll_area; + uint16_t *x = &self->cursor_x; + uint16_t *y = &self->cursor_y; + uint16_t w = self->scroll_area->width_in_tiles; + uint16_t h = self->scroll_area->height_in_tiles; + if (status_bar) { + tilegrid = self->status_bar; + x = &self->status_x; + y = &self->status_y; + w = self->status_bar->width_in_tiles; + h = self->status_bar->height_in_tiles; + } + if (release_glyphs) { + release_current_glyph(tilegrid, self->font, *x, *y); + } + bool is_full_width; + uint16_t new_tile = terminalio_terminal_get_glyph_index(self->font, character, &is_full_width); + if (new_tile == 0xffff) { + // Missing glyph. + return; + } + // If there is only half width left, then fill it with a space and wrap to the next line. + if (is_full_width && *x == w - 1) { + uint16_t space = terminalio_terminal_get_glyph_index(self->font, ' ', NULL); + common_hal_displayio_tilegrid_set_tile(tilegrid, *x, *y, space); + *x = *x + 1; + wrap_cursor(w, h, x, y); + if (release_glyphs) { + release_current_glyph(tilegrid, self->font, *x, *y); + } + } + common_hal_displayio_tilegrid_set_tile(tilegrid, *x, *y, new_tile); + *x = *x + 1; + wrap_cursor(w, h, x, y); + if (is_full_width) { + if (release_glyphs) { + release_current_glyph(tilegrid, self->font, *x, *y); + } + common_hal_displayio_tilegrid_set_tile(tilegrid, *x, *y, new_tile + 1); + *x = *x + 1; + wrap_cursor(w, h, x, y); + } +} + +// Helper function to set all tiles in a tilegrid with optional glyph release +static void terminalio_terminal_set_all_tiles(terminalio_terminal_obj_t *self, bool status_bar, mp_uint_t character, bool release_glyphs) { + uint16_t *x = &self->cursor_x; + uint16_t *y = &self->cursor_y; + if (status_bar) { + x = &self->status_x; + y = &self->status_y; + } + *x = 0; + *y = 0; + terminalio_terminal_set_tile(self, status_bar, character, release_glyphs); + while (*x != 0 || *y != 0) { + terminalio_terminal_set_tile(self, status_bar, character, release_glyphs); + } +} + void terminalio_terminal_clear_status_bar(terminalio_terminal_obj_t *self) { if (self->status_bar) { - common_hal_displayio_tilegrid_set_all_tiles(self->status_bar, 0); + terminalio_terminal_set_all_tiles(self, true, ' ', true); } } + void common_hal_terminalio_terminal_construct(terminalio_terminal_obj_t *self, - displayio_tilegrid_t *scroll_area, const fontio_builtinfont_t *font, + displayio_tilegrid_t *scroll_area, mp_obj_t font, displayio_tilegrid_t *status_bar) { self->cursor_x = 0; self->cursor_y = 0; @@ -35,9 +165,9 @@ void common_hal_terminalio_terminal_construct(terminalio_terminal_obj_t *self, self->first_row = 0; self->vt_scroll_top = 0; self->vt_scroll_end = self->scroll_area->height_in_tiles - 1; - common_hal_displayio_tilegrid_set_all_tiles(self->scroll_area, 0); + terminalio_terminal_set_all_tiles(self, false, ' ', false); if (self->status_bar) { - common_hal_displayio_tilegrid_set_all_tiles(self->status_bar, 0); + terminalio_terminal_set_all_tiles(self, true, ' ', false); } common_hal_displayio_tilegrid_set_top_left(self->scroll_area, 0, 1); @@ -67,16 +197,28 @@ size_t common_hal_terminalio_terminal_write(terminalio_terminal_obj_t *self, con return color_value; } - displayio_palette_t *terminal_palette = self->scroll_area->pixel_shader; + // Color attributes are stored in entries 0 and 1 of a Palette. Other shaders have no such + // entries, so the attributes are ignored for them. + displayio_palette_t *terminal_palette = NULL; + if (mp_obj_is_type(self->scroll_area->pixel_shader, &displayio_palette_type) && + common_hal_displayio_palette_get_len(self->scroll_area->pixel_shader) >= 2) { + terminal_palette = self->scroll_area->pixel_shader; + } #endif const byte *i = data; + const byte *end = data + len; uint16_t start_y = self->cursor_y; - while (i < data + len) { + while (i < end) { unichar c = utf8_get_char(i); - i = utf8_next_char(i); + i++; + // utf8_next_char() assumes NUL-terminated data but callers pass + // length-delimited buffers, so bound the continuation-byte scan. + while (i < end && UTF8_IS_CONT(*i)) { + i++; + } if (self->in_osc_command) { - if (c == 0x1b && i[0] == '\\') { + if (c == 0x1b && i < end && i[0] == '\\') { self->in_osc_command = false; self->status_x = 0; self->status_y = 0; @@ -85,30 +227,28 @@ size_t common_hal_terminalio_terminal_write(terminalio_terminal_obj_t *self, con self->osc_command == 0 && self->status_bar != NULL && self->status_y < self->status_bar->height_in_tiles) { - uint8_t tile_index = fontio_builtinfont_get_glyph_index(self->font, c); - if (tile_index != 0xff) { - // Clear the tile grid before we start putting new info. - if (self->status_x == 0 && self->status_y == 0) { - common_hal_displayio_tilegrid_set_all_tiles(self->status_bar, 0); - } - common_hal_displayio_tilegrid_set_tile(self->status_bar, self->status_x, self->status_y, tile_index); - self->status_x++; - if (self->status_x >= self->status_bar->width_in_tiles) { - self->status_y++; - self->status_x %= self->status_bar->width_in_tiles; - } + // Clear the tile grid before we start putting new info. + bool at_start = self->status_x == 0 && self->status_y == 0; + if (at_start) { + terminalio_terminal_set_all_tiles(self, true, ' ', true); + } + terminalio_terminal_set_tile(self, true, c, true); + // The cursor wraps to the first tile when the bar is full. Move it past the last + // row so the height check above skips the rest of the title. A missing first glyph + // leaves the cursor at the first tile without wrapping, so at_start rules that out. + if (!at_start && self->status_x == 0 && self->status_y == 0) { + self->status_y = self->status_bar->height_in_tiles; } } continue; } - // Always handle ASCII. - if (c < 128) { - if (c >= 0x20 && c <= 0x7e) { - uint8_t tile_index = fontio_builtinfont_get_glyph_index(self->font, c); - common_hal_displayio_tilegrid_set_tile(self->scroll_area, self->cursor_x, self->cursor_y, tile_index); - self->cursor_x++; - } else if (c == '\r') { + if (c < 0x20) { + if (c == '\r') { self->cursor_x = 0; + } else if (c == '\t') { + for (uint8_t space_i = 0; space_i < 4; space_i++) { + terminalio_terminal_set_tile(self, false, ' ', true); + } } else if (c == '\n') { self->cursor_y++; // Commands below are used by MicroPython in the REPL @@ -124,6 +264,10 @@ size_t common_hal_terminalio_terminal_write(terminalio_terminal_obj_t *self, con uint8_t n_args = 1; #endif for (; j < 6; j++) { + if (i + j >= end) { + c = 0; + break; + } if ('0' <= i[j] && i[j] <= '9') { vt_args[0] = vt_args[0] * 10 + (i[j] - '0'); } else { @@ -131,10 +275,14 @@ size_t common_hal_terminalio_terminal_write(terminalio_terminal_obj_t *self, con break; } } - if (i[0] == '[') { + if (i < end && i[0] == '[') { for (uint8_t i_args = 1; i_args < 3 && c == ';'; i_args++) { vt_args[i_args] = 0; for (++j; j < 12; j++) { + if (i + j >= end) { + c = 0; + break; + } if ('0' <= i[j] && i[j] <= '9') { vt_args[i_args] = vt_args[i_args] * 10 + (i[j] - '0'); #if CIRCUITPY_TERMINALIO_VT100 @@ -146,7 +294,7 @@ size_t common_hal_terminalio_terminal_write(terminalio_terminal_obj_t *self, con } } } - if (c == '?') { + if (c == '?' && i + 4 < end) { #if CIRCUITPY_TERMINALIO_VT100 if (i[2] == '2' && i[3] == '5') { // cursor visibility commands @@ -162,6 +310,8 @@ size_t common_hal_terminalio_terminal_write(terminalio_terminal_obj_t *self, con #endif } else { if (c == 'K') { + int16_t original_cursor_x = self->cursor_x; + int16_t original_cursor_y = self->cursor_y; int16_t clr_start = self->cursor_x; int16_t clr_end = self->scroll_area->width_in_tiles; #if CIRCUITPY_TERMINALIO_VT100 @@ -171,11 +321,14 @@ size_t common_hal_terminalio_terminal_write(terminalio_terminal_obj_t *self, con } else if (vt_args[0] == 2) { clr_start = 0; } + self->cursor_x = clr_start; #endif // Clear the (start/rest/all) of the line. for (uint16_t k = clr_start; k < clr_end; k++) { - common_hal_displayio_tilegrid_set_tile(self->scroll_area, k, self->cursor_y, 0); + terminalio_terminal_set_tile(self, false, ' ', true); } + self->cursor_x = original_cursor_x; + self->cursor_y = original_cursor_y; } else if (c == 'D') { if (vt_args[0] > self->cursor_x) { self->cursor_x = 0; @@ -186,7 +339,7 @@ size_t common_hal_terminalio_terminal_write(terminalio_terminal_obj_t *self, con if (vt_args[0] == 2) { common_hal_displayio_tilegrid_set_top_left(self->scroll_area, 0, 0); self->cursor_x = self->cursor_y = start_y = 0; - common_hal_displayio_tilegrid_set_all_tiles(self->scroll_area, 0); + terminalio_terminal_set_all_tiles(self, false, ' ', true); } } else if (c == 'H') { if (vt_args[0] > 0) { @@ -206,7 +359,7 @@ size_t common_hal_terminalio_terminal_write(terminalio_terminal_obj_t *self, con self->cursor_y = vt_args[0]; start_y = self->cursor_y; #if CIRCUITPY_TERMINALIO_VT100 - } else if (c == 'm') { + } else if (c == 'm' && terminal_palette != NULL) { for (uint8_t i_args = 0; i_args < n_args; i_args++) { if ((vt_args[i_args] >= 40 && vt_args[i_args] <= 47) || (vt_args[i_args] >= 30 && vt_args[i_args] <= 37)) { common_hal_displayio_palette_set_color(terminal_palette, 1 - (vt_args[i_args] / 40), _select_color(vt_args[i_args] % 10)); @@ -232,7 +385,7 @@ size_t common_hal_terminalio_terminal_write(terminalio_terminal_obj_t *self, con i += j + 1; } #if CIRCUITPY_TERMINALIO_VT100 - } else if (i[0] == 'M') { + } else if (i < end && i[0] == 'M') { if (self->cursor_y != SCRNMOD(self->vt_scroll_top)) { if (self->cursor_y > 0) { self->cursor_y = self->cursor_y - 1; @@ -240,16 +393,20 @@ size_t common_hal_terminalio_terminal_write(terminalio_terminal_obj_t *self, con self->cursor_y = self->scroll_area->height_in_tiles - 1; } } else { - if (self->vt_scroll_top != 0 || self->vt_scroll_end != self->scroll_area->height_in_tiles) { + if (self->vt_scroll_top != 0 || self->vt_scroll_end != self->scroll_area->height_in_tiles - 1) { // Scroll range defined, manually move tiles to perform scroll for (int16_t irow = self->vt_scroll_end - 1; irow >= self->vt_scroll_top; irow--) { for (int16_t icol = 0; icol < self->scroll_area->width_in_tiles; icol++) { common_hal_displayio_tilegrid_set_tile(self->scroll_area, icol, SCRNMOD(irow + 1), common_hal_displayio_tilegrid_get_tile(self->scroll_area, icol, SCRNMOD(irow))); } } + self->cursor_x = 0; + int16_t old_y = self->cursor_y; + // Fill the row with spaces. for (int16_t icol = 0; icol < self->scroll_area->width_in_tiles; icol++) { - common_hal_displayio_tilegrid_set_tile(self->scroll_area, icol, self->cursor_y, 0); + terminalio_terminal_set_tile(self, false, ' ', true); } + self->cursor_y = old_y; } else { // Full screen scroll, just set new top_y pointer and clear row if (self->cursor_y > 0) { @@ -257,8 +414,12 @@ size_t common_hal_terminalio_terminal_write(terminalio_terminal_obj_t *self, con } else { common_hal_displayio_tilegrid_set_top_left(self->scroll_area, 0, self->scroll_area->height_in_tiles - 1); } - for (uint16_t icol = 0; icol < self->scroll_area->width_in_tiles; icol++) { - common_hal_displayio_tilegrid_set_tile(self->scroll_area, icol, self->scroll_area->top_left_y, 0); + + self->cursor_x = 0; + self->cursor_y = self->scroll_area->top_left_y; + // Fill the row with spaces. + for (int16_t icol = 0; icol < self->scroll_area->width_in_tiles; icol++) { + terminalio_terminal_set_tile(self, false, ' ', true); } self->cursor_y = self->scroll_area->top_left_y; } @@ -266,23 +427,18 @@ size_t common_hal_terminalio_terminal_write(terminalio_terminal_obj_t *self, con } start_y = self->cursor_y; i++; - } else if (i[0] == 'D') { + } else if (i < end && i[0] == 'D') { self->cursor_y++; i++; #endif - } else if (i[0] == ']' && c == ';') { + } else if (i < end && i[0] == ']' && c == ';') { self->in_osc_command = true; self->osc_command = vt_args[0]; i += j + 1; } } } else { - uint8_t tile_index = fontio_builtinfont_get_glyph_index(self->font, c); - if (tile_index != 0xff) { - common_hal_displayio_tilegrid_set_tile(self->scroll_area, self->cursor_x, self->cursor_y, tile_index); - self->cursor_x++; - - } + terminalio_terminal_set_tile(self, false, c, true); } if (self->cursor_x >= self->scroll_area->width_in_tiles) { self->cursor_y++; @@ -294,7 +450,7 @@ size_t common_hal_terminalio_terminal_write(terminalio_terminal_obj_t *self, con if (self->cursor_y != start_y) { if (((self->cursor_y + self->scroll_area->height_in_tiles) - 1) % self->scroll_area->height_in_tiles == SCRNMOD(self->vt_scroll_end)) { #if CIRCUITPY_TERMINALIO_VT100 - if (self->vt_scroll_top != 0 || self->vt_scroll_end != self->scroll_area->height_in_tiles) { + if (self->vt_scroll_top != 0 || self->vt_scroll_end != self->scroll_area->height_in_tiles - 1) { // Scroll range defined, manually move tiles to perform scroll self->cursor_y = SCRNMOD(self->vt_scroll_end); @@ -305,22 +461,35 @@ size_t common_hal_terminalio_terminal_write(terminalio_terminal_obj_t *self, con } } #endif - if (self->vt_scroll_top == 0 && self->vt_scroll_end == self->scroll_area->height_in_tiles) { + if (self->vt_scroll_top == 0 && self->vt_scroll_end == self->scroll_area->height_in_tiles - 1) { // Full screen scroll, just set new top_y pointer common_hal_displayio_tilegrid_set_top_left(self->scroll_area, 0, (self->cursor_y + self->scroll_area->height_in_tiles + 1) % self->scroll_area->height_in_tiles); } // clear the new row in case of scroll up + self->cursor_x = 0; + int16_t old_y = self->cursor_y; for (int16_t icol = 0; icol < self->scroll_area->width_in_tiles; icol++) { - common_hal_displayio_tilegrid_set_tile(self->scroll_area, icol, self->cursor_y, 0); + terminalio_terminal_set_tile(self, false, ' ', true); } self->cursor_x = 0; + self->cursor_y = old_y; } start_y = self->cursor_y; } } + if (i > end) { + i = end; + } return i - data; } +uint16_t common_hal_terminalio_terminal_get_cursor_x(terminalio_terminal_obj_t *self) { + return self->cursor_x; +} +uint16_t common_hal_terminalio_terminal_get_cursor_y(terminalio_terminal_obj_t *self) { + return self->cursor_y; +} + bool common_hal_terminalio_terminal_ready_to_tx(terminalio_terminal_obj_t *self) { return self->scroll_area != NULL; } diff --git a/shared-module/terminalio/Terminal.h b/shared-module/terminalio/Terminal.h index d617f571aed..8bf294cb27f 100644 --- a/shared-module/terminalio/Terminal.h +++ b/shared-module/terminalio/Terminal.h @@ -15,7 +15,7 @@ typedef struct { mp_obj_base_t base; - const fontio_builtinfont_t *font; + mp_obj_t font; // Can be fontio_builtinfont_t or lvfontio_ondiskfont_t uint16_t cursor_x; uint16_t cursor_y; displayio_tilegrid_t *scroll_area; @@ -30,3 +30,4 @@ typedef struct { } terminalio_terminal_obj_t; extern void terminalio_terminal_clear_status_bar(terminalio_terminal_obj_t *self); +uint16_t terminalio_terminal_get_glyph_index(mp_obj_t font, mp_uint_t codepoint, bool *is_full_width); diff --git a/shared-module/tilepalettemapper/TilePaletteMapper.c b/shared-module/tilepalettemapper/TilePaletteMapper.c index f27c507fdca..13711b2c253 100644 --- a/shared-module/tilepalettemapper/TilePaletteMapper.c +++ b/shared-module/tilepalettemapper/TilePaletteMapper.c @@ -8,29 +8,13 @@ #include "shared-bindings/tilepalettemapper/TilePaletteMapper.h" #include "shared-bindings/displayio/Palette.h" #include "shared-bindings/displayio/ColorConverter.h" +#include "shared-bindings/displayio/TileGrid.h" void common_hal_tilepalettemapper_tilepalettemapper_construct(tilepalettemapper_tilepalettemapper_t *self, - mp_obj_t pixel_shader, uint16_t input_color_count, uint16_t width, uint16_t height) { - + mp_obj_t pixel_shader, uint16_t input_color_count) { self->pixel_shader = pixel_shader; - self->width_in_tiles = width; - self->height_in_tiles = height; self->input_color_count = input_color_count; - self->needs_refresh = false; - int mappings_len = width * height; - self->tile_mappings = (uint32_t **)m_malloc(mappings_len * sizeof(uint32_t *)); - for (int i = 0; i < mappings_len; i++) { - self->tile_mappings[i] = (uint32_t *)m_malloc(input_color_count * sizeof(uint32_t)); - if (mp_obj_is_type(self->pixel_shader, &displayio_palette_type)) { - for (uint16_t j = 0; j < input_color_count; j++) { - self->tile_mappings[i][j] = j; - } - } else if (mp_obj_is_type(self->pixel_shader, &displayio_colorconverter_type)) { - for (uint16_t j = 0; j < input_color_count; j++) { - self->tile_mappings[i][j] = 0; - } - } - } + self->tilegrid = mp_const_none; } uint16_t common_hal_tilepalettemapper_tilepalettemapper_get_width(tilepalettemapper_tilepalettemapper_t *self) { @@ -45,6 +29,10 @@ mp_obj_t common_hal_tilepalettemapper_tilepalettemapper_get_pixel_shader(tilepal return self->pixel_shader; } +mp_obj_t common_hal_tilepalettemapper_tilepalettemapper_get_tilegrid(tilepalettemapper_tilepalettemapper_t *self) { + return self->tilegrid; +} + mp_obj_t common_hal_tilepalettemapper_tilepalettemapper_get_mapping(tilepalettemapper_tilepalettemapper_t *self, uint16_t x, uint16_t y) { int index = x + y * self->width_in_tiles; mp_obj_t result[self->input_color_count]; @@ -67,7 +55,7 @@ void common_hal_tilepalettemapper_tilepalettemapper_set_mapping(tilepalettemappe mp_arg_validate_int_range(mapping_val, 0, palette_max, MP_QSTR_mapping_value); self->tile_mappings[y * self->width_in_tiles + x][i] = mapping_val; } - self->needs_refresh = true; + displayio_tilegrid_mark_tile_dirty(self->tilegrid, x, y); } void tilepalettemapper_tilepalettemapper_get_color(tilepalettemapper_tilepalettemapper_t *self, const _displayio_colorspace_t *colorspace, displayio_input_pixel_t *input_pixel, displayio_output_pixel_t *output_color, uint16_t x_tile_index, uint16_t y_tile_index) { @@ -91,10 +79,26 @@ void tilepalettemapper_tilepalettemapper_get_color(tilepalettemapper_tilepalette } -bool tilepalettemapper_tilepalettemapper_needs_refresh(tilepalettemapper_tilepalettemapper_t *self) { - return self->needs_refresh; -} +void tilepalettemapper_tilepalettemapper_bind(tilepalettemapper_tilepalettemapper_t *self, displayio_tilegrid_t *tilegrid) { + if (self->tilegrid != mp_const_none) { + mp_raise_RuntimeError(MP_ERROR_TEXT("TilePaletteMapper may only be bound to a TileGrid once")); + } + self->tilegrid = tilegrid; + self->width_in_tiles = common_hal_displayio_tilegrid_get_width(tilegrid); + self->height_in_tiles = common_hal_displayio_tilegrid_get_height(tilegrid); -void tilepalettemapper_tilepalettemapper_finish_refresh(tilepalettemapper_tilepalettemapper_t *self) { - self->needs_refresh = false; + int mappings_len = self->width_in_tiles * self->height_in_tiles; + self->tile_mappings = (uint32_t **)m_malloc(mappings_len * sizeof(uint32_t *)); + for (int i = 0; i < mappings_len; i++) { + self->tile_mappings[i] = (uint32_t *)m_malloc_without_collect(self->input_color_count * sizeof(uint32_t)); + if (mp_obj_is_type(self->pixel_shader, &displayio_palette_type)) { + for (uint16_t j = 0; j < self->input_color_count; j++) { + self->tile_mappings[i][j] = j; + } + } else if (mp_obj_is_type(self->pixel_shader, &displayio_colorconverter_type)) { + for (uint16_t j = 0; j < self->input_color_count; j++) { + self->tile_mappings[i][j] = 0; + } + } + } } diff --git a/shared-module/tilepalettemapper/TilePaletteMapper.h b/shared-module/tilepalettemapper/TilePaletteMapper.h index 98226ae7e04..d1f535eda11 100644 --- a/shared-module/tilepalettemapper/TilePaletteMapper.h +++ b/shared-module/tilepalettemapper/TilePaletteMapper.h @@ -12,18 +12,17 @@ #include "py/obj.h" #include "shared-module/displayio/Palette.h" +#include "shared-module/displayio/TileGrid.h" typedef struct { mp_obj_base_t base; mp_obj_t pixel_shader; + mp_obj_t tilegrid; uint16_t width_in_tiles; uint16_t height_in_tiles; uint16_t input_color_count; uint32_t **tile_mappings; - bool needs_refresh; } tilepalettemapper_tilepalettemapper_t; -bool tilepalettemapper_tilepalettemapper_needs_refresh(tilepalettemapper_tilepalettemapper_t *self); -void tilepalettemapper_tilepalettemapper_finish_refresh(tilepalettemapper_tilepalettemapper_t *self); - void tilepalettemapper_tilepalettemapper_get_color(tilepalettemapper_tilepalettemapper_t *self, const _displayio_colorspace_t *colorspace, displayio_input_pixel_t *input_pixel, displayio_output_pixel_t *output_color, uint16_t x_tile_index, uint16_t y_tile_index); +void tilepalettemapper_tilepalettemapper_bind(tilepalettemapper_tilepalettemapper_t *self, displayio_tilegrid_t *tilegrid); diff --git a/shared-module/touchio/TouchIn.c b/shared-module/touchio/TouchIn.c index 9334b369f65..c81d8bcf26d 100644 --- a/shared-module/touchio/TouchIn.c +++ b/shared-module/touchio/TouchIn.c @@ -12,15 +12,18 @@ #include "py/mphal.h" #include "shared-bindings/touchio/TouchIn.h" #include "shared-bindings/microcontroller/Pin.h" +#include "shared-bindings/digitalio/Pull.h" -// This is a capacitive touch sensing routine using a single digital -// pin. The pin should be connected to the sensing pad, and to ground +// This is a capacitive touch sensing routine using a single digital pin. +// For pull==PULL_DOWN, the pin should be connected to the sensing pad and to ground // via a 1Mohm or thereabout drain resistor. When a reading is taken, // the pin's capacitance is charged by setting it to a digital output // 'high' for a few microseconds, and then it is changed to a high // impedance input. We measure how long it takes to discharge through // the resistor (around 50us), using a busy-waiting loop, and average // over N_SAMPLES cycles to reduce the effects of noise. +// For the pull=PULL_UP case, the 1M resistor is connected to 3v3, the pin is +// driven 'low' then measure how long it takes to go 'high'. #define N_SAMPLES 10 #define TIMEOUT_TICKS 10000 @@ -28,18 +31,19 @@ static uint16_t get_raw_reading(touchio_touchin_obj_t *self) { uint16_t ticks = 0; - + // state to charge pin to: if pull-down or None, pull HIGH, if pull-up, pull LOW + bool pincharge = !(self->pull == PULL_UP); for (uint16_t i = 0; i < N_SAMPLES; i++) { - // set pad to digital output high for 10us to charge it + // set pad to digital output 'pincharge' for 10us to charge it - common_hal_digitalio_digitalinout_switch_to_output(self->digitalinout, true, DRIVE_MODE_PUSH_PULL); + common_hal_digitalio_digitalinout_switch_to_output(self->digitalinout, pincharge, DRIVE_MODE_PUSH_PULL); mp_hal_delay_us(10); // set pad back to an input and take some samples common_hal_digitalio_digitalinout_switch_to_input(self->digitalinout, PULL_NONE); - while (common_hal_digitalio_digitalinout_get_value(self->digitalinout)) { + while (common_hal_digitalio_digitalinout_get_value(self->digitalinout) == pincharge) { if (ticks >= TIMEOUT_TICKS) { return TIMEOUT_TICKS; } @@ -49,16 +53,21 @@ static uint16_t get_raw_reading(touchio_touchin_obj_t *self) { return ticks; } -void common_hal_touchio_touchin_construct(touchio_touchin_obj_t *self, const mcu_pin_obj_t *pin) { - common_hal_mcu_pin_claim(pin); +void common_hal_touchio_touchin_construct(touchio_touchin_obj_t *self, const mcu_pin_obj_t *pin, const digitalio_pull_t pull) { self->digitalinout = mp_obj_malloc(digitalio_digitalinout_obj_t, &digitalio_digitalinout_type); common_hal_digitalio_digitalinout_construct(self->digitalinout, pin); + self->pull = pull; + uint16_t raw_reading = get_raw_reading(self); if (raw_reading == TIMEOUT_TICKS) { common_hal_touchio_touchin_deinit(self); - mp_raise_ValueError(MP_ERROR_TEXT("No pulldown on pin; 1Mohm recommended")); + if (self->pull == PULL_UP) { + mp_raise_ValueError(MP_ERROR_TEXT("No pullup on pin; 1Mohm recommended")); + } else { + mp_raise_ValueError(MP_ERROR_TEXT("No pulldown on pin; 1Mohm recommended")); + } } self->threshold = raw_reading * 1.05 + 100; } @@ -76,7 +85,7 @@ void common_hal_touchio_touchin_deinit(touchio_touchin_obj_t *self) { self->digitalinout = MP_OBJ_NULL; } -void touchin_reset() { +void touchin_reset(void) { } bool common_hal_touchio_touchin_get_value(touchio_touchin_obj_t *self) { diff --git a/shared-module/touchio/TouchIn.h b/shared-module/touchio/TouchIn.h index a03811a1823..1d35b904f35 100644 --- a/shared-module/touchio/TouchIn.h +++ b/shared-module/touchio/TouchIn.h @@ -15,6 +15,7 @@ typedef struct { mp_obj_base_t base; digitalio_digitalinout_obj_t *digitalinout; + digitalio_pull_t pull; uint16_t threshold; } touchio_touchin_obj_t; diff --git a/shared-module/usb/core/Device.c b/shared-module/usb/core/Device.c index 0a52b925fac..39a3b21e447 100644 --- a/shared-module/usb/core/Device.c +++ b/shared-module/usb/core/Device.c @@ -1,12 +1,15 @@ // This file is part of the CircuitPython project: https://circuitpython.org // // SPDX-FileCopyrightText: Copyright (c) 2022 Scott Shawcroft for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2025 Sam Blenny // // SPDX-License-Identifier: MIT #include "shared-bindings/usb/core/Device.h" #include "tusb_config.h" +#include "supervisor/port.h" +#include "supervisor/port_heap.h" #include "lib/tinyusb/src/host/hcd.h" #include "lib/tinyusb/src/host/usbh.h" @@ -18,9 +21,39 @@ #include "supervisor/shared/tick.h" #include "supervisor/usb.h" +#if CIRCUITPY_USB_HOST_BULK +#include "shared-bindings/usb_host_bulk/InStream.h" +#else +static inline void usb_host_bulk_stop_device(uint8_t device_address) { + (void)device_address; +} + +static inline bool usb_host_bulk_endpoint_busy(uint8_t device_address, uint8_t endpoint) { + (void)device_address; + (void)endpoint; + return false; +} + +static inline void usb_host_bulk_device_deinit(usb_core_device_obj_t *device) { + (void)device; +} +#endif + +#if CIRCUITPY_USB_HOST_AUDIO +#include "shared-module/usb_host_audio/USBIn.h" +#else +static inline void usb_host_audio_stop_device(uint8_t device_address) { + (void)device_address; +} +#endif + +// The TinyUSB callbacks below run in tuh_task(), which is a task of its own on +// some ports (CIRCUITPY_USB_HOST_TASK) and for the MAX3421E on espressif. What +// they set is read by the VM. + // Track what device numbers are mounted. We can't use tuh_ready() because it is // true before enumeration completes and TinyUSB drivers are started. -static size_t _mounted_devices = 0; +static volatile size_t _mounted_devices = 0; void tuh_mount_cb(uint8_t dev_addr) { _mounted_devices |= 1 << dev_addr; @@ -28,10 +61,33 @@ void tuh_mount_cb(uint8_t dev_addr) { void tuh_umount_cb(uint8_t dev_addr) { _mounted_devices &= ~(1 << dev_addr); + usb_host_bulk_stop_device(dev_addr); } -static xfer_result_t _xfer_result; -static size_t _actual_len; +static volatile xfer_result_t _xfer_result; +static volatile size_t _actual_len; + +#if !CIRCUITPY_ALL_MEMORY_DMA_CAPABLE +// Helper to ensure buffer is DMA-capable for transfer operations +static uint8_t *_ensure_dma_buffer(usb_core_device_obj_t *self, const uint8_t *buffer, size_t len, bool for_write) { + if (port_buffer_is_dma_capable(buffer, len)) { + return (uint8_t *)buffer; // Already DMA-capable, use directly + } + + uint8_t *dma_buffer = port_malloc(len, true); // true = DMA capable + if (dma_buffer == NULL) { + return NULL; // Allocation failed + } + + // Copy data to DMA buffer if writing + if (for_write && buffer != NULL) { + memcpy(dma_buffer, buffer, len); + } + + return dma_buffer; +} + +#endif bool common_hal_usb_core_device_construct(usb_core_device_obj_t *self, uint8_t device_address) { if (!tuh_inited()) { mp_raise_RuntimeError(MP_ERROR_TEXT("No usb host port initialized")); @@ -45,7 +101,7 @@ bool common_hal_usb_core_device_construct(usb_core_device_obj_t *self, uint8_t d } self->device_address = device_address; self->first_langid = 0; - _xfer_result = 0xff; + _xfer_result = XFER_RESULT_INVALID; return true; } @@ -57,6 +113,9 @@ void common_hal_usb_core_device_deinit(usb_core_device_obj_t *self) { if (common_hal_usb_core_device_deinited(self)) { return; } + usb_host_bulk_device_deinit(self); + // A usb_host_audio stream ends with its endpoint, without a completion. + usb_host_audio_stop_device(self->device_address); size_t open_size = sizeof(self->open_endpoints); for (size_t i = 0; i < open_size; i++) { if (self->open_endpoints[i] != 0) { @@ -70,35 +129,159 @@ void common_hal_usb_core_device_deinit(usb_core_device_obj_t *self) { uint16_t common_hal_usb_core_device_get_idVendor(usb_core_device_obj_t *self) { uint16_t vid; uint16_t pid; - tuh_vid_pid_get(self->device_address, &vid, &pid); + if (!tuh_vid_pid_get(self->device_address, &vid, &pid)) { + mp_raise_usb_core_USBError(NULL); + } return vid; } uint16_t common_hal_usb_core_device_get_idProduct(usb_core_device_obj_t *self) { uint16_t vid; uint16_t pid; - tuh_vid_pid_get(self->device_address, &vid, &pid); + if (!tuh_vid_pid_get(self->device_address, &vid, &pid)) { + mp_raise_usb_core_USBError(NULL); + } return pid; } static void _transfer_done_cb(tuh_xfer_t *xfer) { - // Store the result so we stop waiting for the transfer. - _xfer_result = xfer->result; // The passed in xfer is not the original one we passed in, so we need to // copy any info out that we want (like actual_len.) _actual_len = xfer->actual_len; + // Store the result so we stop waiting for the transfer. The waiter reads + // _actual_len once it sees the result, so the result has to come last. + __atomic_thread_fence(__ATOMIC_RELEASE); + _xfer_result = xfer->result; +} + +// The result of the transfer, once the callback has stored it. +static xfer_result_t _get_xfer_result(void) { + xfer_result_t result = _xfer_result; + // _actual_len is read after this, and must be at least as new. + __atomic_thread_fence(__ATOMIC_ACQUIRE); + return result; } static bool _wait_for_callback(void) { while (!mp_hal_is_interrupted() && - _xfer_result == 0xff) { + _xfer_result == XFER_RESULT_INVALID) { // The background tasks include TinyUSB which will call the function // we provided above. In other words, the callback isn't in an interrupt. RUN_BACKGROUND_TASKS; } - xfer_result_t result = _xfer_result; - _xfer_result = 0xff; - return result == XFER_RESULT_SUCCESS; + if (mp_hal_is_interrupted()) { + // Handle case of VM being interrupted by Ctrl-C or autoreload + return false; + } + // Handle callback result code from TinyUSB + xfer_result_t result = _get_xfer_result(); + _xfer_result = XFER_RESULT_INVALID; + switch (result) { + case XFER_RESULT_SUCCESS: + return true; + case XFER_RESULT_ABORTED: + case XFER_RESULT_FAILED: + mp_raise_usb_core_USBError(NULL); + break; + case XFER_RESULT_STALLED: + mp_raise_usb_core_USBError(MP_ERROR_TEXT("Pipe error")); + break; + case XFER_RESULT_TIMEOUT: + case XFER_RESULT_INVALID: + mp_raise_usb_core_USBTimeoutError(); + break; + } + return false; +} + +static void _prepare_for_transfer(void) { + // Prepare for transfer. Unless there is a timeout, these static globals will + // get modified by the _transfer_done_cb() callback when tinyusb finishes the + // transfer or encounters an error condition. + _xfer_result = XFER_RESULT_INVALID; + _actual_len = 0; +} + +static void _abort_transfer(tuh_xfer_t *xfer) { + bool aborted = tuh_edpt_abort_xfer(xfer->daddr, xfer->ep_addr); + if (aborted) { + // If the transfer was aborted, then we can continue. + return; + } + uint32_t start_time = supervisor_ticks_ms32(); + // If not, we need to wait for it to finish, otherwise we may free memory out from under it. + // Limit the wait time to 10 milliseconds to avoid blocking indefinitely. + while (_xfer_result == XFER_RESULT_INVALID && (supervisor_ticks_ms32() - start_time < 10)) { + // The background tasks include TinyUSB which will call the function + // we provided above. In other words, the callback isn't in an interrupt. + RUN_BACKGROUND_TASKS; + } +} + +// Only frees the transfer buffer on error. +static size_t _handle_timed_transfer_callback(tuh_xfer_t *xfer, mp_int_t timeout, bool our_buffer, bool raise_on_timeout) { + if (xfer == NULL) { + mp_raise_usb_core_USBError(NULL); + return 0; + } + uint32_t start_time = supervisor_ticks_ms32(); + while ((timeout == 0 || supervisor_ticks_ms32() - start_time < (uint32_t)timeout) && + !mp_hal_is_interrupted() && + _xfer_result == XFER_RESULT_INVALID) { + // The background tasks include TinyUSB which will call the function + // we provided above. In other words, the callback isn't in an interrupt. + RUN_BACKGROUND_TASKS; + } + if (mp_hal_is_interrupted()) { + // Handle case of VM being interrupted by Ctrl-C or autoreload + _abort_transfer(xfer); + return 0; + } + // Handle transfer result code from TinyUSB + xfer_result_t result = _get_xfer_result(); + _xfer_result = XFER_RESULT_INVALID; + // Free the bounce buffer only on paths that raise: raising unwinds past + // the caller's cleanup, so it must be freed here. Paths that return + // normally leave ownership with the caller, which copies out of and + // frees the buffer itself (freeing on both sides would be a double free). + bool will_raise = result == XFER_RESULT_ABORTED || result == XFER_RESULT_FAILED || + result == XFER_RESULT_STALLED || + (result == XFER_RESULT_TIMEOUT && raise_on_timeout); + if (our_buffer && will_raise) { + port_free(xfer->buffer); + } + switch (result) { + case XFER_RESULT_SUCCESS: + return _actual_len; + case XFER_RESULT_ABORTED: + case XFER_RESULT_FAILED: + mp_raise_usb_core_USBError(NULL); + break; + case XFER_RESULT_STALLED: + mp_raise_usb_core_USBError(MP_ERROR_TEXT("Pipe error")); + break; + case XFER_RESULT_TIMEOUT: + // This timeout comes from TinyUSB, so assume that it has stopped the + // transfer (note: timeout logic may be unimplemented on TinyUSB side) + if (!raise_on_timeout) { + return 0; + } + mp_raise_usb_core_USBTimeoutError(); + break; + case XFER_RESULT_INVALID: + // This timeout comes from CircuitPython, not TinyUSB, so tell TinyUSB + // to stop the transfer. + _abort_transfer(xfer); + if (!raise_on_timeout) { + return 0; // the caller owns (and frees) the buffer + } + if (our_buffer) { + port_free(xfer->buffer); + } + mp_raise_usb_core_USBTimeoutError(); + break; + } + return 0; } static mp_obj_t _get_string(const uint16_t *temp_buf) { @@ -109,24 +292,48 @@ static mp_obj_t _get_string(const uint16_t *temp_buf) { return utf16le_to_string(temp_buf + 1, utf16_len); } -static void _get_langid(usb_core_device_obj_t *self) { +static bool _get_descriptor(usb_core_device_obj_t *self, uint8_t type, uint8_t index, + uint16_t language, void *buffer, size_t len) { + // TinyUSB's descriptor helpers pass buffers directly to DMA. Use our own + // control transfer function because it has cache-safe buffer handling and + // USBError propagation. + mp_int_t count = common_hal_usb_core_device_ctrl_transfer(self, 0x80, TUSB_REQ_GET_DESCRIPTOR, + (type << 8) | index, language, buffer, len, 1000); + if (mp_hal_is_interrupted()) { + return false; + } + if (count == 0) { + mp_raise_usb_core_USBError(NULL); + } + return true; +} + +static bool _get_langid(usb_core_device_obj_t *self) { if (self->first_langid != 0) { - return; + return true; } // Two control bytes and one uint16_t language code. uint16_t temp_buf[2]; - if (!tuh_descriptor_get_string(self->device_address, 0, 0, temp_buf, sizeof(temp_buf), _transfer_done_cb, 0) || - !_wait_for_callback()) { - return; + if (!_get_descriptor(self, TUSB_DESC_STRING, 0, 0, temp_buf, sizeof(temp_buf))) { + return false; } self->first_langid = temp_buf[1]; + return true; } mp_obj_t common_hal_usb_core_device_get_serial_number(usb_core_device_obj_t *self) { uint16_t temp_buf[127]; - _get_langid(self); - if (!tuh_descriptor_get_serial_string(self->device_address, self->first_langid, temp_buf, sizeof(temp_buf), _transfer_done_cb, 0) || - !_wait_for_callback()) { + tusb_desc_device_t descriptor; + // First, be sure not to ask TinyUSB for a non-existent string (avoid error) + if (!tuh_descriptor_get_device_local(self->device_address, &descriptor)) { + return mp_const_none; + } + if (descriptor.iSerialNumber == 0) { + return mp_const_none; + } + // Device does provide this string, so continue + if (!_get_langid(self) || + !_get_descriptor(self, TUSB_DESC_STRING, descriptor.iSerialNumber, self->first_langid, temp_buf, sizeof(temp_buf))) { return mp_const_none; } return _get_string(temp_buf); @@ -134,9 +341,17 @@ mp_obj_t common_hal_usb_core_device_get_serial_number(usb_core_device_obj_t *sel mp_obj_t common_hal_usb_core_device_get_product(usb_core_device_obj_t *self) { uint16_t temp_buf[127]; - _get_langid(self); - if (!tuh_descriptor_get_product_string(self->device_address, self->first_langid, temp_buf, sizeof(temp_buf), _transfer_done_cb, 0) || - !_wait_for_callback()) { + tusb_desc_device_t descriptor; + // First, be sure not to ask TinyUSB for a non-existent string (avoid error) + if (!tuh_descriptor_get_device_local(self->device_address, &descriptor)) { + return mp_const_none; + } + if (descriptor.iProduct == 0) { + return mp_const_none; + } + // Device does provide this string, so continue + if (!_get_langid(self) || + !_get_descriptor(self, TUSB_DESC_STRING, descriptor.iProduct, self->first_langid, temp_buf, sizeof(temp_buf))) { return mp_const_none; } return _get_string(temp_buf); @@ -144,9 +359,17 @@ mp_obj_t common_hal_usb_core_device_get_product(usb_core_device_obj_t *self) { mp_obj_t common_hal_usb_core_device_get_manufacturer(usb_core_device_obj_t *self) { uint16_t temp_buf[127]; - _get_langid(self); - if (!tuh_descriptor_get_manufacturer_string(self->device_address, self->first_langid, temp_buf, sizeof(temp_buf), _transfer_done_cb, 0) || - !_wait_for_callback()) { + tusb_desc_device_t descriptor; + // First, be sure not to ask TinyUSB for a non-existent string (avoid error) + if (!tuh_descriptor_get_device_local(self->device_address, &descriptor)) { + return mp_const_none; + } + if (descriptor.iManufacturer == 0) { + return mp_const_none; + } + // Device does provide this string, so continue + if (!_get_langid(self) || + !_get_descriptor(self, TUSB_DESC_STRING, descriptor.iManufacturer, self->first_langid, temp_buf, sizeof(temp_buf))) { return mp_const_none; } return _get_string(temp_buf); @@ -154,33 +377,42 @@ mp_obj_t common_hal_usb_core_device_get_manufacturer(usb_core_device_obj_t *self mp_int_t common_hal_usb_core_device_get_bus(usb_core_device_obj_t *self) { - hcd_devtree_info_t devtree; - hcd_devtree_get_info(self->device_address, &devtree); - return devtree.rhport; + tuh_bus_info_t bus_info; + if (!tuh_bus_info_get(self->device_address, &bus_info)) { + return 0; + } + return bus_info.rhport; } mp_obj_t common_hal_usb_core_device_get_port_numbers(usb_core_device_obj_t *self) { - hcd_devtree_info_t devtree; - hcd_devtree_get_info(self->device_address, &devtree); - if (devtree.hub_addr == 0) { + tuh_bus_info_t bus_info; + if (!tuh_bus_info_get(self->device_address, &bus_info)) { + return mp_const_none; + } + if (bus_info.hub_addr == 0) { return mp_const_none; } // USB allows for 5 hubs deep chaining. So we're at most 5 ports deep. mp_obj_t ports[5]; size_t port_count = 0; - while (devtree.hub_addr != 0 && port_count < MP_ARRAY_SIZE(ports)) { + tuh_bus_info_t current_bus_info = bus_info; + while (current_bus_info.hub_addr != 0 && port_count < MP_ARRAY_SIZE(ports)) { // Reverse the order of the ports so most downstream comes last. - ports[MP_ARRAY_SIZE(ports) - 1 - port_count] = MP_OBJ_NEW_SMALL_INT(devtree.hub_port); + ports[MP_ARRAY_SIZE(ports) - 1 - port_count] = MP_OBJ_NEW_SMALL_INT(current_bus_info.hub_port); port_count++; - hcd_devtree_get_info(devtree.hub_addr, &devtree); + if (!tuh_bus_info_get(current_bus_info.hub_addr, ¤t_bus_info)) { + break; + } } return mp_obj_new_tuple(port_count, ports + (MP_ARRAY_SIZE(ports) - port_count)); } mp_int_t common_hal_usb_core_device_get_speed(usb_core_device_obj_t *self) { - hcd_devtree_info_t devtree; - hcd_devtree_get_info(self->device_address, &devtree); - switch (devtree.speed) { + tuh_bus_info_t bus_info; + if (!tuh_bus_info_get(self->device_address, &bus_info)) { + return 0; + } + switch (bus_info.speed) { case TUSB_SPEED_HIGH: return PYUSB_SPEED_HIGH; case TUSB_SPEED_FULL: @@ -195,59 +427,39 @@ mp_int_t common_hal_usb_core_device_get_speed(usb_core_device_obj_t *self) { void common_hal_usb_core_device_set_configuration(usb_core_device_obj_t *self, mp_int_t configuration) { // We assume that the config index is one less than the value. uint8_t config_index = configuration - 1; + usb_host_bulk_stop_device(self->device_address); + usb_host_audio_stop_device(self->device_address); // Get the configuration descriptor and cache it. We'll use it later to open // endpoints. // Get only the config descriptor first. tusb_desc_configuration_t desc; - if (!tuh_descriptor_get_configuration(self->device_address, config_index, &desc, sizeof(desc), _transfer_done_cb, 0) || - !_wait_for_callback()) { + if (!_get_descriptor(self, TUSB_DESC_CONFIGURATION, config_index, 0, &desc, sizeof(desc))) { return; } // Get the config descriptor plus interfaces and endpoints. self->configuration_descriptor = m_realloc(self->configuration_descriptor, desc.wTotalLength); - if (!tuh_descriptor_get_configuration(self->device_address, config_index, self->configuration_descriptor, desc.wTotalLength, _transfer_done_cb, 0) || - !_wait_for_callback()) { + if (!_get_descriptor(self, TUSB_DESC_CONFIGURATION, config_index, 0, self->configuration_descriptor, desc.wTotalLength)) { return; } + _prepare_for_transfer(); tuh_configuration_set(self->device_address, configuration, _transfer_done_cb, 0); _wait_for_callback(); } -static size_t _xfer(tuh_xfer_t *xfer, mp_int_t timeout) { - _xfer_result = 0xff; +// Raises an exception on failure. Returns the number of bytes transferred (maybe zero) on success. +static size_t _xfer(tuh_xfer_t *xfer, mp_int_t timeout, bool our_buffer, bool raise_on_timeout) { + _prepare_for_transfer(); xfer->complete_cb = _transfer_done_cb; if (!tuh_edpt_xfer(xfer)) { + if (our_buffer) { + port_free(xfer->buffer); + } mp_raise_usb_core_USBError(NULL); return 0; } - uint32_t start_time = supervisor_ticks_ms32(); - while ((timeout == 0 || supervisor_ticks_ms32() - start_time < (uint32_t)timeout) && - !mp_hal_is_interrupted() && - _xfer_result == 0xff) { - // The background tasks include TinyUSB which will call the function - // we provided above. In other words, the callback isn't in an interrupt. - RUN_BACKGROUND_TASKS; - } - if (mp_hal_is_interrupted()) { - tuh_edpt_abort_xfer(xfer->daddr, xfer->ep_addr); - return 0; - } - xfer_result_t result = _xfer_result; - _xfer_result = 0xff; - if (result == XFER_RESULT_STALLED) { - mp_raise_usb_core_USBError(MP_ERROR_TEXT("Pipe error")); - } - if (result == 0xff) { - tuh_edpt_abort_xfer(xfer->daddr, xfer->ep_addr); - mp_raise_usb_core_USBTimeoutError(); - } - if (result == XFER_RESULT_SUCCESS) { - return _actual_len; - } - - return 0; + return _handle_timed_transfer_callback(xfer, timeout, our_buffer, raise_on_timeout); } static bool _open_endpoint(usb_core_device_obj_t *self, mp_int_t endpoint) { @@ -299,38 +511,113 @@ static bool _open_endpoint(usb_core_device_obj_t *self, mp_int_t endpoint) { return open; } +bool common_hal_usb_core_device_open_endpoint(usb_core_device_obj_t *self, mp_int_t endpoint) { + return _open_endpoint(self, endpoint); +} + +static void _check_endpoint_free(usb_core_device_obj_t *self, mp_int_t endpoint) { + if (usb_host_bulk_endpoint_busy(self->device_address, endpoint)) { + mp_raise_usb_core_USBError(MP_ERROR_TEXT("%q in use"), MP_QSTR_endpoint); + } +} + mp_int_t common_hal_usb_core_device_write(usb_core_device_obj_t *self, mp_int_t endpoint, const uint8_t *buffer, mp_int_t len, mp_int_t timeout) { + _check_endpoint_free(self, endpoint); if (!_open_endpoint(self, endpoint)) { mp_raise_usb_core_USBError(NULL); return 0; } + + #if !CIRCUITPY_ALL_MEMORY_DMA_CAPABLE + // Ensure buffer is in DMA-capable memory + uint8_t *dma_buffer = _ensure_dma_buffer(self, buffer, len, true); // true = for write + if (dma_buffer == NULL) { + mp_raise_msg(&mp_type_MemoryError, MP_ERROR_TEXT("Could not allocate DMA capable buffer")); + return 0; + } + #else + uint8_t *dma_buffer = (uint8_t *)buffer; // All memory is DMA-capable + #endif + tuh_xfer_t xfer; xfer.daddr = self->device_address; xfer.ep_addr = endpoint; - xfer.buffer = (uint8_t *)buffer; + xfer.buffer = dma_buffer; xfer.buflen = len; - return _xfer(&xfer, timeout); + size_t result = _xfer(&xfer, timeout, dma_buffer != buffer, true); + #if !CIRCUITPY_ALL_MEMORY_DMA_CAPABLE + if (dma_buffer != buffer) { + port_free(dma_buffer); + } + #endif + return result; } -mp_int_t common_hal_usb_core_device_read(usb_core_device_obj_t *self, mp_int_t endpoint, uint8_t *buffer, mp_int_t len, mp_int_t timeout) { +mp_int_t common_hal_usb_core_device_read(usb_core_device_obj_t *self, mp_int_t endpoint, uint8_t *buffer, mp_int_t len, mp_int_t timeout, bool raise_on_timeout) { + _check_endpoint_free(self, endpoint); if (!_open_endpoint(self, endpoint)) { mp_raise_usb_core_USBError(NULL); return 0; } + + #if !CIRCUITPY_ALL_MEMORY_DMA_CAPABLE + // Ensure buffer is in DMA-capable memory + uint8_t *dma_buffer = _ensure_dma_buffer(self, buffer, len, false); // false = for read + if (dma_buffer == NULL) { + mp_raise_msg(&mp_type_MemoryError, MP_ERROR_TEXT("Could not allocate DMA capable buffer")); + return 0; + } + #else + uint8_t *dma_buffer = buffer; // All memory is DMA-capable + #endif + tuh_xfer_t xfer; xfer.daddr = self->device_address; xfer.ep_addr = endpoint; - xfer.buffer = buffer; + xfer.buffer = dma_buffer; xfer.buflen = len; - return _xfer(&xfer, timeout); + mp_int_t result = _xfer(&xfer, timeout, dma_buffer != buffer, raise_on_timeout); + + #if !CIRCUITPY_ALL_MEMORY_DMA_CAPABLE + // Copy data back to original buffer if needed + if (dma_buffer != buffer) { + memcpy(buffer, dma_buffer, result); + port_free(dma_buffer); + } + #endif + + return result; } mp_int_t common_hal_usb_core_device_ctrl_transfer(usb_core_device_obj_t *self, mp_int_t bmRequestType, mp_int_t bRequest, mp_int_t wValue, mp_int_t wIndex, uint8_t *buffer, mp_int_t len, mp_int_t timeout) { + // Stop a stream before the device changes or disables its endpoint. + if (len == 0 && ((bmRequestType == 0x01 && bRequest == TUSB_REQ_SET_INTERFACE) || + (bmRequestType == 0x00 && bRequest == TUSB_REQ_SET_CONFIGURATION))) { + usb_host_bulk_stop_device(self->device_address); + usb_host_audio_stop_device(self->device_address); + } // Timeout is in ms. + #if !CIRCUITPY_ALL_MEMORY_DMA_CAPABLE + // Determine if this is a write (host-to-device) or read (device-to-host) transfer + bool is_write = (bmRequestType & 0x80) == 0; // Bit 7: 0=host-to-device, 1=device-to-host + + // Ensure buffer is in DMA-capable memory + uint8_t *dma_buffer = NULL; + if (len > 0 && buffer != NULL) { + dma_buffer = _ensure_dma_buffer(self, buffer, len, is_write); + if (dma_buffer == NULL) { + mp_raise_msg(&mp_type_MemoryError, MP_ERROR_TEXT("Could not allocate DMA capable buffer")); + return 0; + } + } + #else + uint8_t *dma_buffer = buffer; // All memory is DMA-capable + #endif + tusb_control_request_t request = { .bmRequestType = bmRequestType, .bRequest = bRequest, @@ -342,42 +629,31 @@ mp_int_t common_hal_usb_core_device_ctrl_transfer(usb_core_device_obj_t *self, .daddr = self->device_address, .ep_addr = 0, .setup = &request, - .buffer = buffer, + .buffer = dma_buffer, .complete_cb = _transfer_done_cb, }; - _xfer_result = 0xff; - + _prepare_for_transfer(); if (!tuh_control_xfer(&xfer)) { + if (dma_buffer != buffer) { + port_free(dma_buffer); + } mp_raise_usb_core_USBError(NULL); return 0; } - uint32_t start_time = supervisor_ticks_ms32(); - while ((timeout == 0 || supervisor_ticks_ms32() - start_time < (uint32_t)timeout) && - !mp_hal_is_interrupted() && - _xfer_result == 0xff) { - // The background tasks include TinyUSB which will call the function - // we provided above. In other words, the callback isn't in an interrupt. - RUN_BACKGROUND_TASKS; - } - if (mp_hal_is_interrupted()) { - tuh_edpt_abort_xfer(xfer.daddr, xfer.ep_addr); - return 0; - } - xfer_result_t result = _xfer_result; - _xfer_result = 0xff; - if (result == XFER_RESULT_STALLED) { - mp_raise_usb_core_USBError(MP_ERROR_TEXT("Pipe error")); - } - if (result == 0xff) { - tuh_edpt_abort_xfer(xfer.daddr, xfer.ep_addr); - mp_raise_usb_core_USBTimeoutError(); - } - if (result == XFER_RESULT_SUCCESS) { - return len; + mp_int_t result = (mp_int_t)_handle_timed_transfer_callback(&xfer, timeout, dma_buffer != buffer, true); + + #if !CIRCUITPY_ALL_MEMORY_DMA_CAPABLE + if (dma_buffer != buffer) { + // Copy data back to original buffer if this was a read transfer + if (buffer != NULL && !is_write) { + memcpy(buffer, dma_buffer, result); + } + port_free(dma_buffer); } + #endif - return 0; + return result; } bool common_hal_usb_core_device_is_kernel_driver_active(usb_core_device_obj_t *self, mp_int_t interface) { diff --git a/shared-module/usb_audio/USBMicrophone.c b/shared-module/usb_audio/USBMicrophone.c new file mode 100644 index 00000000000..26a185ff0e9 --- /dev/null +++ b/shared-module/usb_audio/USBMicrophone.c @@ -0,0 +1,174 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#include + +#include "py/misc.h" +#include "py/runtime.h" + +#include "shared-bindings/usb_audio/USBMicrophone.h" +#include "shared-module/usb_audio/__init__.h" +#include "shared-module/usb_audio/usb_audio_descriptors.h" +#include "shared-module/audiocore/__init__.h" + +// Only one microphone may feed the single USB IN endpoint at a time. This points +// at the USBMicrophone whose play() was called most recently, or NULL when none +// is streaming. The USB background task pulls from it via +// usb_audio_usbmicrophone_background_fill(). +static usb_audio_usbmicrophone_obj_t *active_microphone = NULL; + +void common_hal_usb_audio_usbmicrophone_construct(usb_audio_usbmicrophone_obj_t *self) { + self->sample = MP_OBJ_NULL; + self->buffer = NULL; + self->buffer_length = 0; + self->loop = false; + self->playing = false; + self->paused = false; + self->deinited = false; + self->more_data = false; +} + +void common_hal_usb_audio_usbmicrophone_deinit(usb_audio_usbmicrophone_obj_t *self) { + common_hal_usb_audio_usbmicrophone_stop(self); + self->deinited = true; +} + +bool common_hal_usb_audio_usbmicrophone_deinited(usb_audio_usbmicrophone_obj_t *self) { + return self->deinited; +} + +void common_hal_usb_audio_usbmicrophone_play(usb_audio_usbmicrophone_obj_t *self, mp_obj_t sample, bool loop) { + // The negotiated USB format is fixed 16-bit signed LE PCM at the rate/channel + // count chosen by usb_audio.enable() in boot.py. Resampling and format + // conversion are out of scope, so the source must already match exactly. This + // mirrors how audiocore's audiosample_must_match() validates an output's input + // (and reuses its error messages), but checks against the USB format rather + // than another audiosample. + audiosample_base_t *sample_base = audiosample_check(sample); + if (audiosample_get_sample_rate(sample_base) != usb_audio_sample_rate) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("The sample's %q does not match"), MP_QSTR_sample_rate); + } + if (audiosample_get_channel_count(sample_base) != usb_audio_channel_count) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("The sample's %q does not match"), MP_QSTR_channel_count); + } + if (audiosample_get_bits_per_sample(sample_base) != USB_AUDIO_BITS_PER_SAMPLE) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("The sample's %q does not match"), MP_QSTR_bits_per_sample); + } + if (!sample_base->samples_signed) { + mp_raise_ValueError_varg(MP_ERROR_TEXT("The sample's %q does not match"), MP_QSTR_signedness); + } + + // Start at the beginning and arm the pull loop to request the first chunk. + audiosample_reset_buffer(sample, false, 0); + self->sample = sample; + self->buffer = NULL; + self->buffer_length = 0; + self->loop = loop; + self->playing = true; + self->paused = false; + self->more_data = true; + // Take over the single USB IN endpoint from any other microphone. + active_microphone = self; +} + +void common_hal_usb_audio_usbmicrophone_stop(usb_audio_usbmicrophone_obj_t *self) { + self->sample = MP_OBJ_NULL; + self->buffer = NULL; + self->buffer_length = 0; + self->playing = false; + self->paused = false; + self->more_data = false; + if (active_microphone == self) { + active_microphone = NULL; + } +} + +bool common_hal_usb_audio_usbmicrophone_get_playing(usb_audio_usbmicrophone_obj_t *self) { + return self->playing && !self->paused; +} + +void common_hal_usb_audio_usbmicrophone_pause(usb_audio_usbmicrophone_obj_t *self) { + self->paused = true; +} + +void common_hal_usb_audio_usbmicrophone_resume(usb_audio_usbmicrophone_obj_t *self) { + self->paused = false; +} + +bool common_hal_usb_audio_usbmicrophone_get_paused(usb_audio_usbmicrophone_obj_t *self) { + return self->playing && self->paused; +} + +size_t usb_audio_usbmicrophone_background_fill(uint8_t *out, size_t max_bytes) { + usb_audio_usbmicrophone_obj_t *self = active_microphone; + if (self == NULL || !self->playing || self->paused || self->sample == MP_OBJ_NULL) { + return 0; + } + + // The negotiated USB format is 16-bit signed PCM. For this step the + // bound sample is assumed to already be in that format (e.g. a 16-bit signed + // audiocore.RawSample), so its bytes are copied straight through. + size_t filled = 0; + while (filled < max_bytes) { + if (self->buffer_length == 0) { + if (!self->more_data) { + // The previous chunk was the sample's last and we've played it + // out. Loop back to the start or stop. + if (self->loop) { + audiosample_reset_buffer(self->sample, false, 0); + self->more_data = true; + } else { + common_hal_usb_audio_usbmicrophone_stop(self); + break; + } + } + audioio_get_buffer_result_t result = + audiosample_get_buffer(self->sample, false, 0, &self->buffer, &self->buffer_length); + if (result == GET_BUFFER_ERROR) { + common_hal_usb_audio_usbmicrophone_stop(self); + break; + } + self->more_data = (result == GET_BUFFER_MORE_DATA); + if (self->buffer_length == 0) { + // No samples available right now (underrun); the caller fills the + // rest of the frame with silence and we retry next tick. + break; + } + } + + // Bytes written to out, and bytes consumed from the sample's chunk. They + // differ when a mono sample feeds the always-stereo USB stream. + size_t written; + size_t consumed; + if (MP_LIKELY(usb_audio_channel_count == USB_AUDIO_N_CHANNELS)) { + written = consumed = MIN(self->buffer_length, max_bytes - filled); + memcpy(out + filled, self->buffer, written); + } else { + // Mono source: duplicate each sample into both USB channels. Work in + // whole stereo frames so a partial frame can never be emitted, and + // cap by both what the chunk holds and what still fits in out. + size_t frames = MIN(self->buffer_length / USB_AUDIO_N_BYTES_PER_SAMPLE, + (max_bytes - filled) / USB_AUDIO_BYTES_PER_FRAME); + const int16_t *in = (const int16_t *)(const void *)self->buffer; + int16_t *dest = (int16_t *)(void *)(out + filled); + for (size_t i = 0; i < frames; i++) { + dest[2 * i] = dest[2 * i + 1] = in[i]; + } + written = frames * USB_AUDIO_BYTES_PER_FRAME; + consumed = frames * USB_AUDIO_N_BYTES_PER_SAMPLE; + } + if (written == 0) { + // Less than one whole frame of room left in out (or nothing to copy): + // stop rather than spin. The caller pads the remainder with silence. + break; + } + self->buffer += consumed; + self->buffer_length -= consumed; + filled += written; + } + + return filled; +} diff --git a/shared-module/usb_audio/USBMicrophone.h b/shared-module/usb_audio/USBMicrophone.h new file mode 100644 index 00000000000..74f167e8e43 --- /dev/null +++ b/shared-module/usb_audio/USBMicrophone.h @@ -0,0 +1,33 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +typedef struct usb_audio_usbmicrophone_obj { + mp_obj_base_t base; + // The audiosample currently bound for streaming, or MP_OBJ_NULL. + mp_obj_t sample; + // Cursor into the chunk last returned by audiosample_get_buffer(): the next + // unread byte and the number of bytes still unread in that chunk. + uint8_t *buffer; + uint32_t buffer_length; + bool loop; + bool playing; + bool paused; + bool deinited; + // False once audiosample_get_buffer() reported GET_BUFFER_DONE for the + // current chunk; the chunk is still played out, then we loop or stop. + bool more_data; +} usb_audio_usbmicrophone_obj_t; + +// Pull up to max_bytes of audio (in the negotiated USB PCM format) from whichever +// USBMicrophone is currently playing, writing it into out. Returns the number of +// bytes written, which is < max_bytes (possibly 0) when nothing is streaming or +// the source underruns; the caller pads the remainder with silence. Called from +// the USB background task in shared-module/usb_audio/__init__.c. +size_t usb_audio_usbmicrophone_background_fill(uint8_t *out, size_t max_bytes); diff --git a/shared-module/usb_audio/USBSpeaker.c b/shared-module/usb_audio/USBSpeaker.c new file mode 100644 index 00000000000..c04ee9b280d --- /dev/null +++ b/shared-module/usb_audio/USBSpeaker.c @@ -0,0 +1,267 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#include + +#include "py/misc.h" + +#include "shared-bindings/usb_audio/USBSpeaker.h" +#include "shared-bindings/audiocore/__init__.h" +#include "shared-bindings/microcontroller/__init__.h" +#include "shared-module/usb_audio/__init__.h" + +#include "tusb.h" + +// The ring is sized independently of the TinyUSB headers (see USBSpeaker.h); +// check it still matches the OUT endpoint's software FIFO so the push side can be +// reasoned about against the USB plumbing. +MP_STATIC_ASSERT(USB_AUDIO_SPEAKER_RING_SIZE == CFG_TUD_AUDIO_FUNC_1_EP_OUT_SW_BUF_SZ); + +// Only one speaker can be fed by the single USB OUT endpoint at a time. This +// points at the most recently constructed USBSpeaker, or NULL when none exists, +// mirroring active_microphone in USBMicrophone.c. The USB background task pushes +// received bytes into it via usb_audio_usbspeaker_background_drain(). +static usb_audio_usbspeaker_obj_t *active_speaker = NULL; + +void common_hal_usb_audio_usbspeaker_construct(usb_audio_usbspeaker_obj_t *self) { + // The pipeline treats the speaker as an ordinary audiosample source, so + // populate base from the format negotiated by usb_audio.enable(). The UAC2 + // format we present is 16-bit signed LE PCM, which is exactly what the + // CircuitPython audio pipeline carries, so no conversion is needed. + self->base.sample_rate = usb_audio_sample_rate; + self->base.bits_per_sample = USB_AUDIO_BITS_PER_SAMPLE; + self->base.channel_count = usb_audio_channel_count; + self->base.samples_signed = true; + self->base.single_buffer = false; + self->base.max_buffer_length = USB_AUDIO_SPEAKER_OUTPUT_BUFFER_SIZE; + + self->ring_head = 0; + self->ring_tail = 0; + self->ring_count = 0; + self->output_index = 0; + + // The most recently created speaker receives the host's OUT stream. + active_speaker = self; +} + +void common_hal_usb_audio_usbspeaker_deinit(usb_audio_usbspeaker_obj_t *self) { + // Stop directing USB OUT data at this object. The producer (drain) and this + // deinit both run in non-interrupt context, so the pointer swap needs no + // interrupt guard. + if (active_speaker == self) { + active_speaker = NULL; + } + audiosample_mark_deinit(&self->base); +} + +bool common_hal_usb_audio_usbspeaker_deinited(usb_audio_usbspeaker_obj_t *self) { + return audiosample_deinited(&self->base); +} + +bool common_hal_usb_audio_usbspeaker_get_connected(usb_audio_usbspeaker_obj_t *self) { + (void)self; + // True while the host has opened the OUT streaming interface, i.e. it is + // actively sending audio. Speaker-specific so it stays correct when a mic + // shares the same headset function. + return usb_audio_speaker_streaming(); +} + +// --------------------------------------------------------------------+ +// Receive ring (push side, producer = USB background task) +// --------------------------------------------------------------------+ +// +// The ring decouples the two independently clocked stages from +// usb_audio_output_plan.md: USB push (paced by the host's SOF clock, in the +// background task) and the audiosample pull (paced by the output backend's +// sample clock, in its refill interrupt). It is a single-producer/ +// single-consumer ring across an interrupt boundary: +// +// * Producer: usb_audio_usbspeaker_background_drain(), task context. +// * Consumer: usb_audio_usbspeaker_get_buffer(), output DMA/refill ISR. +// +// The consumer is an interrupt, so it can never be preempted by the producer and +// needs no guard of its own. The producer can be preempted by the consumer, and +// its drop-oldest overrun handling touches both cursors, so it does its whole +// read-modify-write with interrupts disabled. + +void usb_audio_usbspeaker_streaming_reset(void) { + usb_audio_usbspeaker_obj_t *self = active_speaker; + if (self == NULL) { + return; + } + common_hal_mcu_disable_interrupts(); + self->ring_head = 0; + self->ring_tail = 0; + self->ring_count = 0; + common_hal_mcu_enable_interrupts(); +} + +void usb_audio_usbspeaker_background_drain(const uint8_t *in, size_t n) { + usb_audio_usbspeaker_obj_t *self = active_speaker; + if (self == NULL || n == 0) { + return; + } + if (n >= USB_AUDIO_SPEAKER_RING_SIZE) { + // A single chunk larger than the whole ring can only contribute its + // newest tail. (Cannot happen with USB packets << ring size, but keep + // the copies provably in-bounds.) + in += n - USB_AUDIO_SPEAKER_RING_SIZE; + n = USB_AUDIO_SPEAKER_RING_SIZE; + } + + common_hal_mcu_disable_interrupts(); + + size_t free_space = USB_AUDIO_SPEAKER_RING_SIZE - self->ring_count; + if (n > free_space) { + // Overrun: advance the read cursor past the oldest bytes we're about to + // overwrite, keeping latency bounded and following the newest host audio. + size_t drop = n - free_space; + self->ring_tail = (self->ring_tail + drop) % USB_AUDIO_SPEAKER_RING_SIZE; + self->ring_count -= drop; + } + + // Copy in one or two segments, wrapping at the end of the ring. + size_t first = MIN(n, USB_AUDIO_SPEAKER_RING_SIZE - self->ring_head); + memcpy(&self->ring[self->ring_head], in, first); + if (n > first) { + memcpy(&self->ring[0], in + first, n - first); + } + self->ring_head = (self->ring_head + n) % USB_AUDIO_SPEAKER_RING_SIZE; + self->ring_count += n; + + common_hal_mcu_enable_interrupts(); +} + +uint32_t common_hal_usb_audio_usbspeaker_read(usb_audio_usbspeaker_obj_t *self, + void *buffer, uint32_t length) { + // Hand the most recent host audio to Python so it can be analysed (e.g. an + // audio-reactive effect or VU meter). This drains the ring just like the + // output backend's get_buffer() does, so it is an alternative *consumer*: + // a USBSpeaker being read this way must not also be play()ed to an output + // backend at the same time, or the two consumers would race on the single + // SPSC ring. + // + // Unlike get_buffer() (which runs in the output refill ISR and so needs no + // guard) this runs in VM/task context and can be preempted by the USB + // producer, so it brackets its read-modify-write with interrupts disabled, + // mirroring usb_audio_usbspeaker_background_drain(). + // The ring holds wire-format frames (always USB_AUDIO_N_CHANNELS channels). + // `length` and the return value count entries in `buffer`, i.e. 16-bit + // samples: a stereo speaker writes one per channel of each frame, a mono one + // keeps only each frame's left channel. + bool mono = usb_audio_channel_count != USB_AUDIO_N_CHANNELS; + size_t samples_per_frame = mono ? 1 : USB_AUDIO_N_CHANNELS; + size_t want = (size_t)(length / samples_per_frame) * USB_AUDIO_BYTES_PER_FRAME; + + common_hal_mcu_disable_interrupts(); + size_t to_copy = MIN(self->ring_count, want); + // Never split a frame across calls (the ring always holds whole UAC2 frames, + // but stay defensive so the returned count is always a whole number). + to_copy -= to_copy % USB_AUDIO_BYTES_PER_FRAME; + + size_t first = MIN(to_copy, USB_AUDIO_SPEAKER_RING_SIZE - self->ring_tail); + if (MP_LIKELY(!mono)) { + memcpy(buffer, &self->ring[self->ring_tail], first); + if (to_copy > first) { + memcpy((uint8_t *)buffer + first, &self->ring[0], to_copy - first); + } + } else { + int16_t *word_out = (int16_t *)buffer; + const int16_t *word_ring = (const int16_t *)(const void *)self->ring; + size_t base = self->ring_tail / USB_AUDIO_N_BYTES_PER_SAMPLE; + size_t written = 0; + for (size_t i = 0; i < first / USB_AUDIO_N_BYTES_PER_SAMPLE; i += USB_AUDIO_N_CHANNELS) { + word_out[written++] = word_ring[base + i]; + } + for (size_t i = 0; i < (to_copy - first) / USB_AUDIO_N_BYTES_PER_SAMPLE; i += USB_AUDIO_N_CHANNELS) { + word_out[written++] = word_ring[i]; + } + } + self->ring_tail = (self->ring_tail + to_copy) % USB_AUDIO_SPEAKER_RING_SIZE; + self->ring_count -= to_copy; + common_hal_mcu_enable_interrupts(); + + return to_copy / USB_AUDIO_BYTES_PER_FRAME * samples_per_frame; +} + +// --------------------------------------------------------------------+ +// audiosample protocol (pull side, consumer = output backend) +// --------------------------------------------------------------------+ + +void usb_audio_usbspeaker_reset_buffer(usb_audio_usbspeaker_obj_t *self, + bool single_channel_output, uint8_t channel) { + (void)single_channel_output; + (void)channel; + // Begin playback from live audio rather than whatever was buffered before: + // drop the ring and restart the double-buffer. Guarded because some ports may + // call reset_buffer outside the initial setup. + common_hal_mcu_disable_interrupts(); + self->ring_head = 0; + self->ring_tail = 0; + self->ring_count = 0; + common_hal_mcu_enable_interrupts(); + self->output_index = 0; +} + +audioio_get_buffer_result_t usb_audio_usbspeaker_get_buffer(usb_audio_usbspeaker_obj_t *self, + bool single_channel_output, uint8_t channel, uint8_t **buffer, uint32_t *buffer_length) { + + uint32_t half = self->base.max_buffer_length / 2; + uint8_t *out = self->output_buffer + half * self->output_index; + self->output_index = 1 - self->output_index; + + // Consumer side of the SPSC ring (runs in the output backend's refill ISR). + // It is never preempted by the producer, so no interrupt guard is required. + size_t to_copy = MIN(self->ring_count, (size_t)half); + + // Bytes produced in out. The ring always holds wire-format (stereo) frames; + // a mono sample keeps only the left channel of each, so it produces half. + bool mono = usb_audio_channel_count != USB_AUDIO_N_CHANNELS; + size_t produced = mono ? to_copy / 2 : to_copy; + + size_t first = MIN(to_copy, USB_AUDIO_SPEAKER_RING_SIZE - self->ring_tail); + if (MP_LIKELY(!mono)) { + memcpy(out, &self->ring[self->ring_tail], first); + if (to_copy > first) { + memcpy(out + first, &self->ring[0], to_copy - first); + } + } else { + // Take the left sample of each stereo frame, across up to two ring + // segments. Indices are in int16 units, counted from the segment start. + int16_t *word_out = (int16_t *)(void *)out; + const int16_t *word_ring = (const int16_t *)(const void *)self->ring; + size_t base = self->ring_tail / USB_AUDIO_N_BYTES_PER_SAMPLE; + size_t written = 0; + for (size_t i = 0; i < first / USB_AUDIO_N_BYTES_PER_SAMPLE; i += USB_AUDIO_N_CHANNELS) { + word_out[written++] = word_ring[base + i]; + } + for (size_t i = 0; i < (to_copy - first) / USB_AUDIO_N_BYTES_PER_SAMPLE; i += USB_AUDIO_N_CHANNELS) { + word_out[written++] = word_ring[i]; + } + } + self->ring_tail = (self->ring_tail + to_copy) % USB_AUDIO_SPEAKER_RING_SIZE; + self->ring_count -= to_copy; + + // Bytes the caller will be handed, which is all a mono sample can fill. + uint32_t out_length = mono ? half / 2 : half; + if (produced < out_length) { + // Underrun: pad the remainder with silence. Samples are signed, so + // silence is 0. This is the consume-side of the pacing failure mode + // tracked in the usb-audio-artifact-pacing memory: we never spin. + memset(out + produced, 0, out_length - produced); + } + + // Computed the same way as audiocore.RawSample so stereo (interleaved ring) + // can extend it. + if (single_channel_output) { + out += (channel % self->base.channel_count) * (self->base.bits_per_sample / 8); + } + + *buffer = out; + *buffer_length = out_length; + // A live USB stream is infinite; never report DONE or the backend would stop. + return GET_BUFFER_MORE_DATA; +} diff --git a/shared-module/usb_audio/USBSpeaker.h b/shared-module/usb_audio/USBSpeaker.h new file mode 100644 index 00000000000..0760676b53a --- /dev/null +++ b/shared-module/usb_audio/USBSpeaker.h @@ -0,0 +1,73 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include + +#include "py/obj.h" + +#include "shared-module/audiocore/__init__.h" +#include "shared-module/usb_audio/usb_audio_descriptors.h" + +// One half-buffer of the audiosample double-buffer holds this many frames. The +// output backend pulls a half each get_buffer() call, so this sets the pull +// granularity and the silence-pad chunk on underrun. It is deliberately +// independent of the USB OUT software FIFO (the ring below) so the push and pull +// stages can be tuned separately, and small enough that two halves sit +// comfortably inside the ring. +#define USB_AUDIO_SPEAKER_FRAMES_PER_BUFFER (128) + +// Bytes per audio frame in the negotiated UAC2 format (stereo 16-bit). +#define USB_AUDIO_SPEAKER_BYTES_PER_FRAME (USB_AUDIO_N_BYTES_PER_SAMPLE * USB_AUDIO_N_CHANNELS) + +// Full owned double-buffer: two halves of FRAMES_PER_BUFFER frames each. Matches +// audiocore.RawSample's convention where base.max_buffer_length is the whole +// buffer and get_buffer() returns half of it. +#define USB_AUDIO_SPEAKER_OUTPUT_BUFFER_SIZE (2 * USB_AUDIO_SPEAKER_FRAMES_PER_BUFFER * USB_AUDIO_SPEAKER_BYTES_PER_FRAME) + +// Host -> board receive ring size. Mirrors CFG_TUD_AUDIO_FUNC_1_EP_OUT_SW_BUF_SZ +// (16 * the full-speed OUT wMaxPacketSize) but is spelled out from the format +// constants so this struct definition stays free of the TinyUSB headers. A +// MP_STATIC_ASSERT in USBSpeaker.c checks the two stay equal. +#define USB_AUDIO_SPEAKER_OUT_PACKET_SIZE ((USB_AUDIO_MAX_SAMPLE_RATE / 1000 + 1) * USB_AUDIO_SPEAKER_BYTES_PER_FRAME) +#define USB_AUDIO_SPEAKER_RING_SIZE (16 * USB_AUDIO_SPEAKER_OUT_PACKET_SIZE) + +typedef struct usb_audio_usbspeaker_obj { + // First member so the object can be used directly as an audiosample source. + audiosample_base_t base; + + // Host -> board receive ring (the "push" stage). Filled by the USB + // background task via usb_audio_usbspeaker_background_drain() and drained by + // get_buffer(). Single producer (task), single consumer (output DMA ISR); + // see the concurrency notes in USBSpeaker.c. + uint8_t ring[USB_AUDIO_SPEAKER_RING_SIZE]; + size_t ring_head; // next write offset + size_t ring_tail; // next read offset + size_t ring_count; // valid bytes currently in the ring + + // Owned double-buffer returned to the output backend by get_buffer(). + uint8_t output_buffer[USB_AUDIO_SPEAKER_OUTPUT_BUFFER_SIZE]; + uint8_t output_index; // 0 or 1: which half get_buffer() fills next +} usb_audio_usbspeaker_obj_t; + +// audiosample protocol implementation. Not exposed to Python because get_buffer() +// runs in the output backend's refill interrupt. +void usb_audio_usbspeaker_reset_buffer(usb_audio_usbspeaker_obj_t *self, + bool single_channel_output, uint8_t channel); +audioio_get_buffer_result_t usb_audio_usbspeaker_get_buffer(usb_audio_usbspeaker_obj_t *self, + bool single_channel_output, uint8_t channel, uint8_t **buffer, uint32_t *buffer_length); + +// Push n bytes received on the USB OUT endpoint into the active speaker's ring. +// Called from the USB background task (see usb_audio_task()). No-op when no +// speaker is active. Overrun policy: drop the oldest buffered bytes. +void usb_audio_usbspeaker_background_drain(const uint8_t *in, size_t n); + +// Drop anything buffered in the active speaker's ring so a (re)opened stream +// starts from live audio. Called when the host opens/closes the OUT streaming +// interface. +void usb_audio_usbspeaker_streaming_reset(void); diff --git a/shared-module/usb_audio/__init__.c b/shared-module/usb_audio/__init__.c new file mode 100644 index 00000000000..3b1171e90d9 --- /dev/null +++ b/shared-module/usb_audio/__init__.c @@ -0,0 +1,714 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/usb_audio/__init__.h" +#include "shared-bindings/usb_audio/USBMicrophone.h" +#include "shared-bindings/usb_audio/USBSpeaker.h" +#include "shared-module/usb_audio/__init__.h" +#include "shared-module/usb_audio/USBMicrophone.h" +#include "shared-module/usb_audio/USBSpeaker.h" +#include "shared-module/usb_audio/usb_audio_descriptors.h" + +#include + +#include "py/misc.h" +#include "py/mphal.h" +#include "py/runtime.h" +#include "supervisor/port.h" +#include "supervisor/shared/tick.h" +#include "supervisor/usb.h" +#include "tusb.h" + +// Scratch chunk the microphone task hands to TinyUSB. It is written from the USB +// background task for as long as the device is enabled, which outlives every VM, +// so it comes from the port heap rather than the MicroPython heap. Sized by +// enable() for 1 ms at the negotiated rate, in the wire format (always +// USB_AUDIO_N_CHANNELS channels), so a board that never calls enable() pays +// nothing for it. +static int16_t *usb_audio_mic_samples; +static size_t usb_audio_mic_samples_len; + +static bool usb_audio_is_enabled = false; + +// The host opens each AudioStreaming interface independently (alt 0 = idle, alt 1 +// = streaming), so the two directions of a headset are tracked separately. For +// the single-direction microphone/speaker only the matching flag is ever set. +static bool usb_audio_mic_streaming = false; +static bool usb_audio_spk_streaming = false; + +// AudioStreaming interface numbers assigned when the descriptor is built, used to +// route the host's set-interface requests to the right direction. 0xff until a +// descriptor that includes that direction has been emitted. +static uint8_t usb_audio_mic_as_itf = 0xff; +static uint8_t usb_audio_spk_as_itf = 0xff; + +uint32_t usb_audio_sample_rate; +uint8_t usb_audio_channel_count; +bool usb_audio_microphone_enabled; +bool usb_audio_speaker_enabled; + +// Audio control state surfaced to the host. One extra entry for the master channel 0. +static int8_t usb_audio_mute[USB_AUDIO_N_CHANNELS + 1]; +static int16_t usb_audio_volume[USB_AUDIO_N_CHANNELS + 1]; + +bool shared_module_usb_audio_enable(mp_int_t sample_rate, mp_int_t channel_count, bool microphone, bool speaker) { + if (tud_connected()) { + return false; + } + + // One scratch chunk (1 ms at the sample rate); we loop until the FIFO reaches + // the setpoint. enable() may be called more than once, so release any chunk + // sized for a previous rate before taking a new one. + port_free(usb_audio_mic_samples); + usb_audio_mic_samples_len = sample_rate / 1000 * USB_AUDIO_BYTES_PER_FRAME; + usb_audio_mic_samples = port_malloc_zero(usb_audio_mic_samples_len, false); + if (usb_audio_mic_samples == NULL) { + usb_audio_mic_samples_len = 0; + return false; + } + + usb_audio_sample_rate = sample_rate; + usb_audio_channel_count = channel_count; + usb_audio_microphone_enabled = microphone; + usb_audio_speaker_enabled = speaker; + usb_audio_is_enabled = true; + + return true; +} + +bool shared_module_usb_audio_disable(void) { + if (tud_connected()) { + return false; + } + usb_audio_is_enabled = false; + port_free(usb_audio_mic_samples); + usb_audio_mic_samples = NULL; + usb_audio_mic_samples_len = 0; + return true; +} + +bool usb_audio_enabled(void) { + return usb_audio_is_enabled; +} + +bool usb_audio_streaming(void) { + return usb_audio_mic_streaming || usb_audio_spk_streaming; +} + +// True while the host has the speaker (OUT) stream open, i.e. it is actively +// sending audio. Used by USBSpeaker.connected so it reflects the speaker +// direction specifically even when a mic shares the same headset function. +bool usb_audio_speaker_streaming(void) { + return usb_audio_spk_streaming; +} + +void usb_audio_setup_singletons(void) { + // USBMicrophone and USBSpeaker are singletons rather than constructible + // classes (like usb_midi.ports). The host-facing format and direction are + // fixed by usb_audio.enable() in boot.py and persist in C globals, but the + // instances themselves live on the GC heap, which is reset between boot.py + // and code.py, so they are rebuilt here once per VM. Each is created only + // when its direction was enabled; otherwise it is left as None. + // + // The objects are held in MP_STATE_VM root pointers so the GC keeps them + // alive for the whole VM (the module globals table is static data and is not + // a GC root, so a reference from there alone would be swept). Rooting the + // microphone also traces its bound audiosample (self->sample). They are then + // installed in the module globals so they are reachable as the + // usb_audio.usb_microphone / usb_audio.usb_speaker attributes. + mp_obj_t microphone = mp_const_none; + mp_obj_t speaker = mp_const_none; + + if (usb_audio_is_enabled) { + const bool has_input = usb_audio_microphone_enabled; + const bool has_output = usb_audio_speaker_enabled; + + if (has_input) { + usb_audio_usbmicrophone_obj_t *self = + mp_obj_malloc_with_finaliser(usb_audio_usbmicrophone_obj_t, &usb_audio_USBMicrophone_type); + common_hal_usb_audio_usbmicrophone_construct(self); + microphone = MP_OBJ_FROM_PTR(self); + } + if (has_output) { + usb_audio_usbspeaker_obj_t *self = + mp_obj_malloc_with_finaliser(usb_audio_usbspeaker_obj_t, &usb_audio_USBSpeaker_type); + common_hal_usb_audio_usbspeaker_construct(self); + speaker = MP_OBJ_FROM_PTR(self); + } + } + + MP_STATE_VM(usb_audio_microphone_singleton) = microphone; + MP_STATE_VM(usb_audio_speaker_singleton) = speaker; + + mp_map_lookup(&usb_audio_module_globals.map, MP_ROM_QSTR(MP_QSTR_usb_microphone), MP_MAP_LOOKUP)->value = + microphone; + mp_map_lookup(&usb_audio_module_globals.map, MP_ROM_QSTR(MP_QSTR_usb_speaker), MP_MAP_LOOKUP)->value = + speaker; +} + +// Hand-rolled UAC2 speaker (host -> board) descriptor WITHOUT an async +// feedback endpoint. This mirrors TinyUSB's TUD_AUDIO20_SPEAKER_STEREO_FB_DESCRIPTOR +// (lib/tinyusb/src/device/usbd.h) but drops the trailing feedback endpoint, so +// the streaming alt-setting declares a single OUT endpoint (_nEPs = 0x01). The +// entity IDs match the mic descriptor (see usb_audio_descriptors.h); only the +// terminal roles reverse: the input terminal is the USB-streaming side and the +// output terminal is the desktop speaker, and the AS interface links the input +// terminal (0x01). Async feedback for true clock matching is a later step. +#define USB_AUDIO_SPEAKER_DESCRIPTOR(_itfnum, _stridx, _nBytesPerSample, _nBitsUsedPerSample, _epout, _epsize) \ + /* Standard Interface Association Descriptor (IAD) */ \ + TUD_AUDIO20_DESC_IAD(/*_firstitf*/ _itfnum, /*_nitfs*/ 0x02, /*_stridx*/ 0x00), \ + /* Standard AC Interface Descriptor(4.7.1) */ \ + TUD_AUDIO20_DESC_STD_AC(/*_itfnum*/ _itfnum, /*_nEPs*/ 0x00, /*_stridx*/ _stridx), \ + /* Class-Specific AC Interface Header Descriptor(4.7.2) */ \ + TUD_AUDIO20_DESC_CS_AC(/*_bcdADC*/ 0x0200, /*_category*/ AUDIO20_FUNC_DESKTOP_SPEAKER, /*_totallen*/ TUD_AUDIO20_DESC_CLK_SRC_LEN + TUD_AUDIO20_DESC_INPUT_TERM_LEN + TUD_AUDIO20_DESC_OUTPUT_TERM_LEN + TUD_AUDIO20_DESC_FEATURE_UNIT_LEN(2), /*_ctrl*/ AUDIO20_CS_AS_INTERFACE_CTRL_LATENCY_POS), \ + /* Clock Source Descriptor(4.7.2.1) */ \ + TUD_AUDIO20_DESC_CLK_SRC(/*_clkid*/ USB_AUDIO_ENTITY_CLOCK_SOURCE, /*_attr*/ AUDIO20_CLOCK_SOURCE_ATT_INT_FIX_CLK, /*_ctrl*/ (AUDIO20_CTRL_R << AUDIO20_CLOCK_SOURCE_CTRL_CLK_FRQ_POS), /*_assocTerm*/ USB_AUDIO_ENTITY_INPUT_TERMINAL, /*_stridx*/ 0x00), \ + /* Input Terminal Descriptor(4.7.2.4) -- USB streaming in from the host */ \ + TUD_AUDIO20_DESC_INPUT_TERM(/*_termid*/ USB_AUDIO_ENTITY_INPUT_TERMINAL, /*_termtype*/ AUDIO_TERM_TYPE_USB_STREAMING, /*_assocTerm*/ 0x00, /*_clkid*/ USB_AUDIO_ENTITY_CLOCK_SOURCE, /*_nchannelslogical*/ USB_AUDIO_N_CHANNELS, /*_channelcfg*/ AUDIO20_CHANNEL_CONFIG_NON_PREDEFINED, /*_idxchannelnames*/ 0x00, /*_ctrl*/ 0 * (AUDIO20_CTRL_R << AUDIO20_IN_TERM_CTRL_CONNECTOR_POS), /*_stridx*/ 0x00), \ + /* Output Terminal Descriptor(4.7.2.5) -- desktop speaker */ \ + TUD_AUDIO20_DESC_OUTPUT_TERM(/*_termid*/ USB_AUDIO_ENTITY_OUTPUT_TERMINAL, /*_termtype*/ AUDIO_TERM_TYPE_OUT_DESKTOP_SPEAKER, /*_assocTerm*/ USB_AUDIO_ENTITY_INPUT_TERMINAL, /*_srcid*/ USB_AUDIO_ENTITY_FEATURE_UNIT, /*_clkid*/ USB_AUDIO_ENTITY_CLOCK_SOURCE, /*_ctrl*/ 0x0000, /*_stridx*/ 0x00), \ + /* Feature Unit Descriptor(4.7.2.8) */ \ + TUD_AUDIO20_DESC_FEATURE_UNIT(/*_unitid*/ USB_AUDIO_ENTITY_FEATURE_UNIT, /*_srcid*/ USB_AUDIO_ENTITY_INPUT_TERMINAL, /*_stridx*/ 0x00, /*_ctrlch0master*/ AUDIO20_CTRL_RW << AUDIO20_FEATURE_UNIT_CTRL_MUTE_POS | AUDIO20_CTRL_RW << AUDIO20_FEATURE_UNIT_CTRL_VOLUME_POS, /*_ctrlch1*/ AUDIO20_CTRL_RW << AUDIO20_FEATURE_UNIT_CTRL_MUTE_POS | AUDIO20_CTRL_RW << AUDIO20_FEATURE_UNIT_CTRL_VOLUME_POS, /*_ctrlch2*/ AUDIO20_CTRL_RW << AUDIO20_FEATURE_UNIT_CTRL_MUTE_POS | AUDIO20_CTRL_RW << AUDIO20_FEATURE_UNIT_CTRL_VOLUME_POS), \ + /* Standard AS Interface Descriptor(4.9.1) -- alt 0, zero bandwidth */ \ + TUD_AUDIO20_DESC_STD_AS_INT(/*_itfnum*/ (uint8_t)((_itfnum) + 1), /*_altset*/ 0x00, /*_nEPs*/ 0x00, /*_stridx*/ 0x00), \ + /* Standard AS Interface Descriptor(4.9.1) -- alt 1, one OUT endpoint */ \ + TUD_AUDIO20_DESC_STD_AS_INT(/*_itfnum*/ (uint8_t)((_itfnum) + 1), /*_altset*/ 0x01, /*_nEPs*/ 0x01, /*_stridx*/ 0x00), \ + /* Class-Specific AS Interface Descriptor(4.9.2) -- linked to the input terminal */ \ + TUD_AUDIO20_DESC_CS_AS_INT(/*_termid*/ USB_AUDIO_ENTITY_INPUT_TERMINAL, /*_ctrl*/ AUDIO20_CTRL_NONE, /*_formattype*/ AUDIO20_FORMAT_TYPE_I, /*_formats*/ AUDIO20_DATA_FORMAT_TYPE_I_PCM, /*_nchannelsphysical*/ USB_AUDIO_N_CHANNELS, /*_channelcfg*/ AUDIO20_CHANNEL_CONFIG_NON_PREDEFINED, /*_stridx*/ 0x00), \ + /* Type I Format Type Descriptor(2.3.1.6 - Audio Formats) */ \ + TUD_AUDIO20_DESC_TYPE_I_FORMAT(_nBytesPerSample, _nBitsUsedPerSample), \ + /* Standard AS Isochronous Audio Data Endpoint Descriptor(4.10.1.1) */ \ + TUD_AUDIO20_DESC_STD_AS_ISO_EP(/*_ep*/ _epout, /*_attr*/ (uint8_t)((uint8_t)TUSB_XFER_ISOCHRONOUS | (uint8_t)TUSB_ISO_EP_ATT_ADAPTIVE | (uint8_t)TUSB_ISO_EP_ATT_DATA), /*_maxEPsize*/ _epsize, /*_interval*/ 0x01), \ + /* Class-Specific AS Isochronous Audio Data Endpoint Descriptor(4.10.1.2) */ \ + TUD_AUDIO20_DESC_CS_AS_ISO_EP(/*_attr*/ AUDIO20_CS_AS_ISO_DATA_EP_ATT_NON_MAX_PACKETS_OK, /*_ctrl*/ AUDIO20_CTRL_NONE, /*_lockdelayunit*/ AUDIO20_CS_AS_ISO_DATA_EP_LOCK_DELAY_UNIT_UNDEFINED, /*_lockdelay*/ 0x0000) + +// Hand-rolled UAC2 microphone (board -> host) descriptor WITHOUT an async +// feedback endpoint. This mirrors TinyUSB's TUD_AUDIO20_MIC_ONE_CH_DESCRIPTOR +// (lib/tinyusb/src/device/usbd.h) but drops the trailing feedback endpoint, so +// the streaming alt-setting declares a single IN endpoint (_nEPs = 0x00). Async +// feedback for true clock matching is a later step. +#define USB_AUDIO_MIC_DESCRIPTOR(_itfnum, _stridx, _nBytesPerSample, _nBitsUsedPerSample, _epin, _epsize) \ + /* Standard Interface Association Descriptor (IAD) */ \ + TUD_AUDIO20_DESC_IAD(/*_firstitf*/ _itfnum, /*_nitfs*/ 0x02, /*_stridx*/ 0x00), \ + /* Standard AC Interface Descriptor(4.7.1) */ \ + TUD_AUDIO20_DESC_STD_AC(/*_itfnum*/ _itfnum, /*_nEPs*/ 0x00, /*_stridx*/ _stridx), \ + /* Class-Specific AC Interface Header Descriptor(4.7.2) */ \ + TUD_AUDIO20_DESC_CS_AC(/*_bcdADC*/ 0x0200, /*_category*/ AUDIO20_FUNC_MICROPHONE, /*_totallen*/ TUD_AUDIO20_DESC_CLK_SRC_LEN + TUD_AUDIO20_DESC_INPUT_TERM_LEN + TUD_AUDIO20_DESC_OUTPUT_TERM_LEN + TUD_AUDIO20_DESC_FEATURE_UNIT_LEN(2), /*_ctrl*/ AUDIO20_CS_AS_INTERFACE_CTRL_LATENCY_POS), \ + /* Clock Source Descriptor(4.7.2.1) */ \ + TUD_AUDIO20_DESC_CLK_SRC(/*_clkid*/ USB_AUDIO_ENTITY_CLOCK_SOURCE, /*_attr*/ AUDIO20_CLOCK_SOURCE_ATT_INT_FIX_CLK, /*_ctrl*/ (AUDIO20_CTRL_R << AUDIO20_CLOCK_SOURCE_CTRL_CLK_FRQ_POS), /*_assocTerm*/ USB_AUDIO_ENTITY_INPUT_TERMINAL, /*_stridx*/ 0x00), \ + /* Input Terminal Descriptor(4.7.2.4) -- microphone */ \ + TUD_AUDIO20_DESC_INPUT_TERM(/*_termid*/ USB_AUDIO_ENTITY_INPUT_TERMINAL, /*_termtype*/ AUDIO_TERM_TYPE_IN_GENERIC_MIC, /*_assocTerm*/ USB_AUDIO_ENTITY_OUTPUT_TERMINAL, /*_clkid*/ USB_AUDIO_ENTITY_CLOCK_SOURCE, /*_nchannelslogical*/ USB_AUDIO_N_CHANNELS, /*_channelcfg*/ AUDIO20_CHANNEL_CONFIG_NON_PREDEFINED, /*_idxchannelnames*/ 0x00, /*_ctrl*/ AUDIO20_CTRL_R << AUDIO20_IN_TERM_CTRL_CONNECTOR_POS, /*_stridx*/ 0x00), \ + /* Output Terminal Descriptor(4.7.2.5) -- USB streaming */ \ + TUD_AUDIO20_DESC_OUTPUT_TERM(/*_termid*/ USB_AUDIO_ENTITY_OUTPUT_TERMINAL, /*_termtype*/ AUDIO_TERM_TYPE_USB_STREAMING, /*_assocTerm*/ USB_AUDIO_ENTITY_INPUT_TERMINAL, /*_srcid*/ USB_AUDIO_ENTITY_FEATURE_UNIT, /*_clkid*/ USB_AUDIO_ENTITY_CLOCK_SOURCE, /*_ctrl*/ 0x0000, /*_stridx*/ 0x00), \ + /* Feature Unit Descriptor(4.7.2.8) */ \ + TUD_AUDIO20_DESC_FEATURE_UNIT(/*_unitid*/ USB_AUDIO_ENTITY_FEATURE_UNIT, /*_srcid*/ USB_AUDIO_ENTITY_INPUT_TERMINAL, /*_stridx*/ 0x00, /*_ctrlch0master*/ AUDIO20_CTRL_RW << AUDIO20_FEATURE_UNIT_CTRL_MUTE_POS | AUDIO20_CTRL_RW << AUDIO20_FEATURE_UNIT_CTRL_VOLUME_POS, /*_ctrlch1*/ AUDIO20_CTRL_RW << AUDIO20_FEATURE_UNIT_CTRL_MUTE_POS | AUDIO20_CTRL_RW << AUDIO20_FEATURE_UNIT_CTRL_VOLUME_POS, /*_ctrlch2*/ AUDIO20_CTRL_RW << AUDIO20_FEATURE_UNIT_CTRL_MUTE_POS | AUDIO20_CTRL_RW << AUDIO20_FEATURE_UNIT_CTRL_VOLUME_POS), \ + /* Standard AS Interface Descriptor(4.9.1) */ \ + /* Interface 1, Alternate 0 - default alternate setting with 0 bandwidth */ \ + TUD_AUDIO20_DESC_STD_AS_INT(/*_itfnum*/ (uint8_t)((_itfnum) + 1), /*_altset*/ 0x00, /*_nEPs*/ 0x00, /*_stridx*/ 0x00), \ + /* Standard AS Interface Descriptor(4.9.1) */ \ + /* Interface 1, Alternate 1 - alternate interface for data streaming */ \ + TUD_AUDIO20_DESC_STD_AS_INT(/*_itfnum*/ (uint8_t)((_itfnum) + 1), /*_altset*/ 0x01, /*_nEPs*/ 0x01, /*_stridx*/ 0x00), \ + /* Class-Specific AS Interface Descriptor(4.9.2) */ \ + TUD_AUDIO20_DESC_CS_AS_INT(/*_termid*/ USB_AUDIO_ENTITY_OUTPUT_TERMINAL, /*_ctrl*/ AUDIO20_CTRL_NONE, /*_formattype*/ AUDIO20_FORMAT_TYPE_I, /*_formats*/ AUDIO20_DATA_FORMAT_TYPE_I_PCM, /*_nchannelsphysical*/ USB_AUDIO_N_CHANNELS, /*_channelcfg*/ AUDIO20_CHANNEL_CONFIG_NON_PREDEFINED, /*_stridx*/ 0x00), \ + /* Type I Format Type Descriptor(2.3.1.6 - Audio Formats) */ \ + TUD_AUDIO20_DESC_TYPE_I_FORMAT(_nBytesPerSample, _nBitsUsedPerSample), \ + /* Standard AS Isochronous Audio Data Endpoint Descriptor(4.10.1.1) */ \ + TUD_AUDIO20_DESC_STD_AS_ISO_EP(/*_ep*/ _epin, /*_attr*/ (uint8_t)((uint8_t)TUSB_XFER_ISOCHRONOUS | (uint8_t)TUSB_ISO_EP_ATT_ASYNCHRONOUS | (uint8_t)TUSB_ISO_EP_ATT_DATA), /*_maxEPsize*/ _epsize, /*_interval*/ 0x01), \ + /* Class-Specific AS Isochronous Audio Data Endpoint Descriptor(4.10.1.2) */ \ + TUD_AUDIO20_DESC_CS_AS_ISO_EP(/*_attr*/ AUDIO20_CS_AS_ISO_DATA_EP_ATT_NON_MAX_PACKETS_OK, /*_ctrl*/ AUDIO20_CTRL_NONE, /*_lockdelayunit*/ AUDIO20_CS_AS_ISO_DATA_EP_LOCK_DELAY_UNIT_UNDEFINED, /*_lockdelay*/ 0x0000) + +// Hand-rolled UAC2 headset (microphone + speaker both enabled): one audio function +// presenting both a speaker (host -> board OUT) and a microphone (board -> host +// IN) at once. This combines USB_AUDIO_SPEAKER_DESCRIPTOR's speaker chain with +// USB_AUDIO_MIC_DESCRIPTOR's mic chain under a single IAD. The two chains +// must use distinct entity IDs (USB_AUDIO_HS_ENTITY_*; see usb_audio_descriptors.h) +// because they live in the same AudioControl interface, and they share one clock +// source. The function spans three interfaces: AudioControl (_itfnum), the +// speaker AudioStreaming interface (_itfnum + 1, OUT endpoint), and the mic +// AudioStreaming interface (_itfnum + 2, IN endpoint). Neither stream has an +// async feedback endpoint, matching the single-direction descriptors. +#define USB_AUDIO_HEADSET_DESCRIPTOR(_itfnum, _stridx, _nBytesPerSample, _nBitsUsedPerSample, _epout, _epin, _epsize) \ + /* Standard Interface Association Descriptor (IAD) -- 3 interfaces */ \ + TUD_AUDIO20_DESC_IAD(/*_firstitf*/ _itfnum, /*_nitfs*/ 0x03, /*_stridx*/ 0x00), \ + /* Standard AC Interface Descriptor(4.7.1) */ \ + TUD_AUDIO20_DESC_STD_AC(/*_itfnum*/ _itfnum, /*_nEPs*/ 0x00, /*_stridx*/ _stridx), \ + /* Class-Specific AC Interface Header Descriptor(4.7.2) -- clock + both chains */ \ + TUD_AUDIO20_DESC_CS_AC(/*_bcdADC*/ 0x0200, /*_category*/ AUDIO20_FUNC_HEADSET, /*_totallen*/ TUD_AUDIO20_DESC_CLK_SRC_LEN + 2 * (TUD_AUDIO20_DESC_INPUT_TERM_LEN + TUD_AUDIO20_DESC_FEATURE_UNIT_LEN(2) + TUD_AUDIO20_DESC_OUTPUT_TERM_LEN), /*_ctrl*/ AUDIO20_CS_AS_INTERFACE_CTRL_LATENCY_POS), \ + /* Clock Source Descriptor(4.7.2.1) -- shared by both chains */ \ + TUD_AUDIO20_DESC_CLK_SRC(/*_clkid*/ USB_AUDIO_HS_ENTITY_CLOCK_SOURCE, /*_attr*/ AUDIO20_CLOCK_SOURCE_ATT_INT_FIX_CLK, /*_ctrl*/ (AUDIO20_CTRL_R << AUDIO20_CLOCK_SOURCE_CTRL_CLK_FRQ_POS), /*_assocTerm*/ 0x00, /*_stridx*/ 0x00), \ + /* --- Speaker chain (host -> board) --- */ \ + /* Input Terminal Descriptor(4.7.2.4) -- USB streaming in from the host */ \ + TUD_AUDIO20_DESC_INPUT_TERM(/*_termid*/ USB_AUDIO_HS_ENTITY_SPK_INPUT_TERMINAL, /*_termtype*/ AUDIO_TERM_TYPE_USB_STREAMING, /*_assocTerm*/ 0x00, /*_clkid*/ USB_AUDIO_HS_ENTITY_CLOCK_SOURCE, /*_nchannelslogical*/ USB_AUDIO_N_CHANNELS, /*_channelcfg*/ AUDIO20_CHANNEL_CONFIG_NON_PREDEFINED, /*_idxchannelnames*/ 0x00, /*_ctrl*/ 0 * (AUDIO20_CTRL_R << AUDIO20_IN_TERM_CTRL_CONNECTOR_POS), /*_stridx*/ 0x00), \ + /* Feature Unit Descriptor(4.7.2.8) */ \ + TUD_AUDIO20_DESC_FEATURE_UNIT(/*_unitid*/ USB_AUDIO_HS_ENTITY_SPK_FEATURE_UNIT, /*_srcid*/ USB_AUDIO_HS_ENTITY_SPK_INPUT_TERMINAL, /*_stridx*/ 0x00, /*_ctrlch0master*/ AUDIO20_CTRL_RW << AUDIO20_FEATURE_UNIT_CTRL_MUTE_POS | AUDIO20_CTRL_RW << AUDIO20_FEATURE_UNIT_CTRL_VOLUME_POS, /*_ctrlch1*/ AUDIO20_CTRL_RW << AUDIO20_FEATURE_UNIT_CTRL_MUTE_POS | AUDIO20_CTRL_RW << AUDIO20_FEATURE_UNIT_CTRL_VOLUME_POS, /*_ctrlch2*/ AUDIO20_CTRL_RW << AUDIO20_FEATURE_UNIT_CTRL_MUTE_POS | AUDIO20_CTRL_RW << AUDIO20_FEATURE_UNIT_CTRL_VOLUME_POS), \ + /* Output Terminal Descriptor(4.7.2.5) -- desktop speaker */ \ + TUD_AUDIO20_DESC_OUTPUT_TERM(/*_termid*/ USB_AUDIO_HS_ENTITY_SPK_OUTPUT_TERMINAL, /*_termtype*/ AUDIO_TERM_TYPE_OUT_DESKTOP_SPEAKER, /*_assocTerm*/ 0x00, /*_srcid*/ USB_AUDIO_HS_ENTITY_SPK_FEATURE_UNIT, /*_clkid*/ USB_AUDIO_HS_ENTITY_CLOCK_SOURCE, /*_ctrl*/ 0x0000, /*_stridx*/ 0x00), \ + /* --- Mic chain (board -> host) --- */ \ + /* Input Terminal Descriptor(4.7.2.4) -- generic microphone */ \ + TUD_AUDIO20_DESC_INPUT_TERM(/*_termid*/ USB_AUDIO_HS_ENTITY_MIC_INPUT_TERMINAL, /*_termtype*/ AUDIO_TERM_TYPE_IN_GENERIC_MIC, /*_assocTerm*/ 0x00, /*_clkid*/ USB_AUDIO_HS_ENTITY_CLOCK_SOURCE, /*_nchannelslogical*/ USB_AUDIO_N_CHANNELS, /*_channelcfg*/ AUDIO20_CHANNEL_CONFIG_NON_PREDEFINED, /*_idxchannelnames*/ 0x00, /*_ctrl*/ AUDIO20_CTRL_R << AUDIO20_IN_TERM_CTRL_CONNECTOR_POS, /*_stridx*/ 0x00), \ + /* Feature Unit Descriptor(4.7.2.8) */ \ + TUD_AUDIO20_DESC_FEATURE_UNIT(/*_unitid*/ USB_AUDIO_HS_ENTITY_MIC_FEATURE_UNIT, /*_srcid*/ USB_AUDIO_HS_ENTITY_MIC_INPUT_TERMINAL, /*_stridx*/ 0x00, /*_ctrlch0master*/ AUDIO20_CTRL_RW << AUDIO20_FEATURE_UNIT_CTRL_MUTE_POS | AUDIO20_CTRL_RW << AUDIO20_FEATURE_UNIT_CTRL_VOLUME_POS, /*_ctrlch1*/ AUDIO20_CTRL_RW << AUDIO20_FEATURE_UNIT_CTRL_MUTE_POS | AUDIO20_CTRL_RW << AUDIO20_FEATURE_UNIT_CTRL_VOLUME_POS, /*_ctrlch2*/ AUDIO20_CTRL_RW << AUDIO20_FEATURE_UNIT_CTRL_MUTE_POS | AUDIO20_CTRL_RW << AUDIO20_FEATURE_UNIT_CTRL_VOLUME_POS), \ + /* Output Terminal Descriptor(4.7.2.5) -- USB streaming out to the host */ \ + TUD_AUDIO20_DESC_OUTPUT_TERM(/*_termid*/ USB_AUDIO_HS_ENTITY_MIC_OUTPUT_TERMINAL, /*_termtype*/ AUDIO_TERM_TYPE_USB_STREAMING, /*_assocTerm*/ 0x00, /*_srcid*/ USB_AUDIO_HS_ENTITY_MIC_FEATURE_UNIT, /*_clkid*/ USB_AUDIO_HS_ENTITY_CLOCK_SOURCE, /*_ctrl*/ 0x0000, /*_stridx*/ 0x00), \ + /* --- Speaker AudioStreaming interface (_itfnum + 1) --- */ \ + /* Standard AS Interface Descriptor(4.9.1) -- alt 0, zero bandwidth */ \ + TUD_AUDIO20_DESC_STD_AS_INT(/*_itfnum*/ (uint8_t)((_itfnum) + 1), /*_altset*/ 0x00, /*_nEPs*/ 0x00, /*_stridx*/ 0x00), \ + /* Standard AS Interface Descriptor(4.9.1) -- alt 1, one OUT endpoint */ \ + TUD_AUDIO20_DESC_STD_AS_INT(/*_itfnum*/ (uint8_t)((_itfnum) + 1), /*_altset*/ 0x01, /*_nEPs*/ 0x01, /*_stridx*/ 0x00), \ + /* Class-Specific AS Interface Descriptor(4.9.2) -- linked to the speaker input terminal */ \ + TUD_AUDIO20_DESC_CS_AS_INT(/*_termid*/ USB_AUDIO_HS_ENTITY_SPK_INPUT_TERMINAL, /*_ctrl*/ AUDIO20_CTRL_NONE, /*_formattype*/ AUDIO20_FORMAT_TYPE_I, /*_formats*/ AUDIO20_DATA_FORMAT_TYPE_I_PCM, /*_nchannelsphysical*/ USB_AUDIO_N_CHANNELS, /*_channelcfg*/ AUDIO20_CHANNEL_CONFIG_NON_PREDEFINED, /*_stridx*/ 0x00), \ + /* Type I Format Type Descriptor(2.3.1.6 - Audio Formats) */ \ + TUD_AUDIO20_DESC_TYPE_I_FORMAT(_nBytesPerSample, _nBitsUsedPerSample), \ + /* Standard AS Isochronous Audio Data Endpoint Descriptor(4.10.1.1) */ \ + TUD_AUDIO20_DESC_STD_AS_ISO_EP(/*_ep*/ _epout, /*_attr*/ (uint8_t)((uint8_t)TUSB_XFER_ISOCHRONOUS | (uint8_t)TUSB_ISO_EP_ATT_ADAPTIVE | (uint8_t)TUSB_ISO_EP_ATT_DATA), /*_maxEPsize*/ _epsize, /*_interval*/ 0x01), \ + /* Class-Specific AS Isochronous Audio Data Endpoint Descriptor(4.10.1.2) */ \ + TUD_AUDIO20_DESC_CS_AS_ISO_EP(/*_attr*/ AUDIO20_CS_AS_ISO_DATA_EP_ATT_NON_MAX_PACKETS_OK, /*_ctrl*/ AUDIO20_CTRL_NONE, /*_lockdelayunit*/ AUDIO20_CS_AS_ISO_DATA_EP_LOCK_DELAY_UNIT_UNDEFINED, /*_lockdelay*/ 0x0000), \ + /* --- Mic AudioStreaming interface (_itfnum + 2) --- */ \ + /* Standard AS Interface Descriptor(4.9.1) -- alt 0, zero bandwidth */ \ + TUD_AUDIO20_DESC_STD_AS_INT(/*_itfnum*/ (uint8_t)((_itfnum) + 2), /*_altset*/ 0x00, /*_nEPs*/ 0x00, /*_stridx*/ 0x00), \ + /* Standard AS Interface Descriptor(4.9.1) -- alt 1, one IN endpoint */ \ + TUD_AUDIO20_DESC_STD_AS_INT(/*_itfnum*/ (uint8_t)((_itfnum) + 2), /*_altset*/ 0x01, /*_nEPs*/ 0x01, /*_stridx*/ 0x00), \ + /* Class-Specific AS Interface Descriptor(4.9.2) -- linked to the mic output terminal */ \ + TUD_AUDIO20_DESC_CS_AS_INT(/*_termid*/ USB_AUDIO_HS_ENTITY_MIC_OUTPUT_TERMINAL, /*_ctrl*/ AUDIO20_CTRL_NONE, /*_formattype*/ AUDIO20_FORMAT_TYPE_I, /*_formats*/ AUDIO20_DATA_FORMAT_TYPE_I_PCM, /*_nchannelsphysical*/ USB_AUDIO_N_CHANNELS, /*_channelcfg*/ AUDIO20_CHANNEL_CONFIG_NON_PREDEFINED, /*_stridx*/ 0x00), \ + /* Type I Format Type Descriptor(2.3.1.6 - Audio Formats) */ \ + TUD_AUDIO20_DESC_TYPE_I_FORMAT(_nBytesPerSample, _nBitsUsedPerSample), \ + /* Standard AS Isochronous Audio Data Endpoint Descriptor(4.10.1.1) */ \ + TUD_AUDIO20_DESC_STD_AS_ISO_EP(/*_ep*/ _epin, /*_attr*/ (uint8_t)((uint8_t)TUSB_XFER_ISOCHRONOUS | (uint8_t)TUSB_ISO_EP_ATT_ASYNCHRONOUS | (uint8_t)TUSB_ISO_EP_ATT_DATA), /*_maxEPsize*/ _epsize, /*_interval*/ 0x01), \ + /* Class-Specific AS Isochronous Audio Data Endpoint Descriptor(4.10.1.2) */ \ + TUD_AUDIO20_DESC_CS_AS_ISO_EP(/*_attr*/ AUDIO20_CS_AS_ISO_DATA_EP_ATT_NON_MAX_PACKETS_OK, /*_ctrl*/ AUDIO20_CTRL_NONE, /*_lockdelayunit*/ AUDIO20_CS_AS_ISO_DATA_EP_LOCK_DELAY_UNIT_UNDEFINED, /*_lockdelay*/ 0x0000) + +// Combined headset: both a microphone (board -> host IN) and a speaker +// (host -> board OUT) under one audio function. +static bool usb_audio_direction_is_input_output(void) { + return usb_audio_microphone_enabled && usb_audio_speaker_enabled; +} + +// Speaker only (host -> board OUT), no microphone. +static bool usb_audio_direction_is_output(void) { + return usb_audio_speaker_enabled && !usb_audio_microphone_enabled; +} + +size_t usb_audio_descriptor_length(void) { + if (usb_audio_direction_is_input_output()) { + return USB_AUDIO_HEADSET_DESC_LEN; + } + if (usb_audio_direction_is_output()) { + return USB_AUDIO_SPEAKER_DESC_LEN; + } + return USB_AUDIO_MIC_DESC_LEN; +} + +size_t usb_audio_add_descriptor(uint8_t *descriptor_buf, descriptor_counts_t *descriptor_counts, uint8_t *current_interface_string) { + // Pick the isochronous endpoint number. By default it follows the same + // sequential allocation as every other interface. On ports that pin ISO to a + // fixed, dedicated endpoint (USB_AUDIO_ISO_EP_NUM != 0; see the header for the + // nRF52 case), we use that number instead and leave the sequential counters + // untouched: the dedicated ISO endpoint is a separate hardware resource, so + // it must not consume one of the regular endpoint numbers the other + // interfaces draw from. + const bool forced_iso_ep = (USB_AUDIO_ISO_EP_NUM != 0); + const uint8_t iso_ep_num = forced_iso_ep ? USB_AUDIO_ISO_EP_NUM : descriptor_counts->current_endpoint; + + if (usb_audio_direction_is_input_output()) { + // Combined headset: a speaker AudioStreaming interface (OUT) and a mic + // AudioStreaming interface (IN) under one AudioControl interface, so one + // isochronous endpoint in each direction. + // + // Sequential-allocation ports (e.g. RP2) take a distinct number for each + // direction. Ports that pin ISO to a dedicated endpoint number + // (forced_iso_ep, e.g. nRF52) use that one number for BOTH directions: + // the constraint there is the endpoint *number*, not the direction. The + // nRF52 USBD has a separate ISOIN and ISOOUT on endpoint 8, and TinyUSB + // splits the ISO buffer (ISOSPLIT = HalfIN) when both are open, so 0x08 + // and 0x88 can run at the same time. As in the single-direction branches + // below, the dedicated ISO endpoint is separate hardware and must not + // consume the sequential endpoint numbers the other interfaces draw from. + const uint8_t ep_out = forced_iso_ep ? iso_ep_num : descriptor_counts->current_endpoint; + const uint8_t ep_in = forced_iso_ep ? iso_ep_num : (descriptor_counts->current_endpoint + 1); + + usb_add_interface_name(*current_interface_string, NULL, "Headset"); + + const uint8_t usb_audio_descriptor[] = { + USB_AUDIO_HEADSET_DESCRIPTOR( + /*_itfnum*/ descriptor_counts->current_interface, + /*_stridx*/ *current_interface_string, + /*_nBytesPerSample*/ USB_AUDIO_N_BYTES_PER_SAMPLE, + /*_nBitsUsedPerSample*/ USB_AUDIO_BITS_PER_SAMPLE, + /*_epout*/ ep_out, + /*_epin*/ ep_in | 0x80, + /*_epsize*/ CFG_TUD_AUDIO_FUNC_1_EP_OUT_SZ_MAX) + }; + + // Speaker AS is the first interface after AudioControl, mic AS the second. + usb_audio_spk_as_itf = descriptor_counts->current_interface + 1; + usb_audio_mic_as_itf = descriptor_counts->current_interface + 2; + + (*current_interface_string)++; + // One IAD wrapping an AudioControl + two AudioStreaming interfaces, plus a + // single isochronous endpoint in each direction. On sequential-allocation + // ports the two directions take separate endpoint numbers, consuming two of + // the port's endpoint pairs. On forced_iso_ep ports both directions share + // the dedicated ISO endpoint, which is separate hardware and consumes none. + descriptor_counts->current_interface += 3; + if (!forced_iso_ep) { + descriptor_counts->num_out_endpoints += 1; + descriptor_counts->num_in_endpoints += 1; + descriptor_counts->current_endpoint += 2; + } + + memcpy(descriptor_buf, usb_audio_descriptor, sizeof(usb_audio_descriptor)); + + return sizeof(usb_audio_descriptor); + } + + if (usb_audio_direction_is_output()) { + usb_add_interface_name(*current_interface_string, NULL, "Speaker"); + + // The AudioStreaming interface follows the AudioControl interface. + usb_audio_spk_as_itf = descriptor_counts->current_interface + 1; + + const uint8_t usb_audio_descriptor[] = { + USB_AUDIO_SPEAKER_DESCRIPTOR( + /*_itfnum*/ descriptor_counts->current_interface, + /*_stridx*/ *current_interface_string, + /*_nBytesPerSample*/ USB_AUDIO_N_BYTES_PER_SAMPLE, + /*_nBitsUsedPerSample*/ USB_AUDIO_BITS_PER_SAMPLE, + /*_epout*/ iso_ep_num, + /*_epsize*/ CFG_TUD_AUDIO_FUNC_1_EP_OUT_SZ_MAX) + }; + + (*current_interface_string)++; + // One IAD wrapping an AudioControl + an AudioStreaming interface, plus a + // single isochronous OUT endpoint. + descriptor_counts->current_interface += 2; + if (!forced_iso_ep) { + descriptor_counts->num_out_endpoints += 1; + descriptor_counts->current_endpoint += 1; + } + + memcpy(descriptor_buf, usb_audio_descriptor, sizeof(usb_audio_descriptor)); + + return sizeof(usb_audio_descriptor); + } + + usb_add_interface_name(*current_interface_string, NULL, "Microphone"); + + // The AudioStreaming interface follows the AudioControl interface. + usb_audio_mic_as_itf = descriptor_counts->current_interface + 1; + + const uint8_t usb_audio_descriptor[] = { + USB_AUDIO_MIC_DESCRIPTOR( + /*_itfnum*/ descriptor_counts->current_interface, + /*_stridx*/ *current_interface_string, + /*_nBytesPerSample*/ USB_AUDIO_N_BYTES_PER_SAMPLE, + /*_nBitsUsedPerSample*/ USB_AUDIO_BITS_PER_SAMPLE, + /*_epin*/ iso_ep_num | 0x80, + /*_epsize*/ CFG_TUD_AUDIO_FUNC_1_EP_IN_SZ_MAX) + }; + + (*current_interface_string)++; + // One IAD wrapping an AudioControl + an AudioStreaming interface, plus a + // single isochronous IN endpoint. + descriptor_counts->current_interface += 2; + if (!forced_iso_ep) { + descriptor_counts->num_in_endpoints += 1; + descriptor_counts->current_endpoint += 1; + } + + memcpy(descriptor_buf, usb_audio_descriptor, sizeof(usb_audio_descriptor)); + + return sizeof(usb_audio_descriptor); +} + +// --------------------------------------------------------------------+ +// Speaker (host -> board) receive task +// --------------------------------------------------------------------+ + +// Drain everything the host has delivered to the OUT endpoint since the last +// pass into the active USBSpeaker's ring. TinyUSB's weak rx-done handler has +// already moved the isochronous data into ep_out_ff; we copy it out here, in +// task (non-ISR) context, matching the project's "defer ISR work" rule. The ring +// itself, and the overrun/underrun handling, live in USBSpeaker.c so the data +// sits in the audiosample source the output backend pulls from. +static void usb_audio_speaker_task(void) { + // One USB packet of scratch; we loop until ep_out_ff is empty. + static uint8_t chunk[CFG_TUD_AUDIO_FUNC_1_EP_OUT_SZ_MAX]; + + while (tud_audio_available() > 0) { + uint16_t got = tud_audio_read(chunk, sizeof(chunk)); + if (got == 0) { + break; + } + // tud_audio_read() never returns more than the buffer it was given, but + // clamp so the compiler can prove the drain copies stay within chunk[] + // once this loop is inlined into it. + if (got > sizeof(chunk)) { + got = sizeof(chunk); + } + usb_audio_usbspeaker_background_drain(chunk, got); + } +} + +// --------------------------------------------------------------------+ +// Microphone (board -> host) transmit task +// --------------------------------------------------------------------+ + +static void usb_audio_microphone_task(void) { + // Pace production by the IN FIFO level. Each pass we top the software FIFO + // back up to its half-full setpoint, generating only the samples the host has + // actually drained since the last pass. This limits our production rate to the + // host's true consumption rate (its USB SOF / audio clock), keeps the FIFO + // around the level TinyUSB's flow control targets so it can send steady + // nominal-size packets, and automatically catches up after any scheduling gap + // (GCpause, other background work) in a single pass instead of underrunning. + // Underruns here showed up to the host as discrete sample-drop/insert splices, + // i.e. the erratic ticking on a held tone. + tu_fifo_t *ep_in_ff = tud_audio_get_ep_in_ff(); + uint16_t const target = tu_fifo_depth(ep_in_ff) / 2; + + uint16_t count; + while ((count = tu_fifo_count(ep_in_ff)) < target) { + size_t want = target - count; + if (want > usb_audio_mic_samples_len) { + want = usb_audio_mic_samples_len; + } + + // Pull the next chunk from whichever USBMicrophone is playing. + bool underran = false; + size_t filled = usb_audio_usbmicrophone_background_fill((uint8_t *)usb_audio_mic_samples, want); + if (filled == 0) { + // No source attached, paused, or fully drained: keep the endpoint + // alive with silence so the host never sees a starved stream. + memset((uint8_t *)usb_audio_mic_samples, 0, want); + } else if (filled < want) { + // The source momentarily underran. Send just what it produced and + // let the FIFO cushion ride until it catches up next pass, rather + // than flooding the stream with a burst of silence. + want = filled; + underran = true; + } + + if (tud_audio_write((uint8_t *)usb_audio_mic_samples, (uint16_t)want) == 0) { + break; // FIFO unexpectedly full / host not ready + } + if (underran) { + break; + } + } +} + +void usb_audio_task(void) { + // Each direction is gated on the host having opened its AudioStreaming + // interface. For a headset both run in the same pass: drain the host's + // speaker audio and refill the mic stream independently. The single-direction + // modes simply never have the other flag set. + if (usb_audio_spk_streaming) { + usb_audio_speaker_task(); + } + if (usb_audio_mic_streaming) { + usb_audio_microphone_task(); + } +} + +// --------------------------------------------------------------------+ +// TinyUSB audio class callbacks (weak symbols overridden here) +// --------------------------------------------------------------------+ + +// Host opened/closed the AudioStreaming alternate setting. The host selects each +// direction's interface independently (a headset has two), so route by interface +// number to the matching streaming flag rather than assuming a single stream. +bool tud_audio_set_itf_cb(uint8_t rhport, tusb_control_request_t const *p_request) { + (void)rhport; + uint8_t const itf = (uint8_t)tu_u16_low(p_request->wIndex); + bool const streaming = (tu_u16_low(p_request->wValue) != 0); + + if (itf == usb_audio_spk_as_itf) { + usb_audio_spk_streaming = streaming; + // Start each speaker streaming session from live audio: drop anything + // left in the OUT FIFO/ring from a previous session. + tud_audio_clear_ep_out_ff(); + usb_audio_usbspeaker_streaming_reset(); + } else if (itf == usb_audio_mic_as_itf) { + usb_audio_mic_streaming = streaming; + if (streaming) { + // Prime the FIFO for the first frame; after that each completed + // transfer schedules the next refill via tud_audio_tx_done_isr(). + usb_background_schedule(); + } + } + return true; +} + +// Invoked from the audio class transfer-complete path once the next packet has +// been loaded into the EP IN buffer. TinyUSB services audio completions in ISR +// context, so they never queue a USB event. A port that pumps the optional class +// tasks from a task loop sitting behind tud_task() therefore never refills the +// microphone FIFO. Scheduling the refill here keeps usb_audio independent of how +// a port drives TinyUSB. +bool tud_audio_tx_done_isr(uint8_t rhport, uint16_t n_bytes_sent, uint8_t func_id, + uint8_t ep_in, uint8_t cur_alt_setting) { + (void)rhport; + (void)n_bytes_sent; + (void)func_id; + (void)ep_in; + (void)cur_alt_setting; + + usb_background_schedule(); + return true; +} + +bool tud_audio_set_itf_close_ep_cb(uint8_t rhport, tusb_control_request_t const *p_request) { + (void)rhport; + uint8_t const itf = (uint8_t)tu_u16_low(p_request->wIndex); + + if (itf == usb_audio_spk_as_itf) { + usb_audio_spk_streaming = false; + tud_audio_clear_ep_out_ff(); + usb_audio_usbspeaker_streaming_reset(); + } else if (itf == usb_audio_mic_as_itf) { + usb_audio_mic_streaming = false; + } + return true; +} + +// Class-specific SET requests for an entity (we accept mute/volume on the feature unit). +bool tud_audio_set_req_entity_cb(uint8_t rhport, tusb_control_request_t const *p_request, uint8_t *pBuff) { + (void)rhport; + + uint8_t const channelNum = (uint8_t)tu_u16_low(p_request->wValue); + uint8_t const ctrlSel = (uint8_t)tu_u16_high(p_request->wValue); + uint8_t const entityID = (uint8_t)tu_u16_high(p_request->wIndex); + + // Only current-value requests are supported. + TU_VERIFY(p_request->bRequest == AUDIO20_CS_REQ_CUR); + + // A headset exposes a feature unit per direction; the speaker's id matches the + // single-direction USB_AUDIO_ENTITY_FEATURE_UNIT, the mic adds a second one. + // Mute/volume state is shared across them. + if (entityID == USB_AUDIO_ENTITY_FEATURE_UNIT || + entityID == USB_AUDIO_HS_ENTITY_MIC_FEATURE_UNIT) { + if (channelNum > USB_AUDIO_N_CHANNELS) { + return false; + } + switch (ctrlSel) { + case AUDIO20_FU_CTRL_MUTE: + TU_VERIFY(p_request->wLength == sizeof(audio20_control_cur_1_t)); + usb_audio_mute[channelNum] = ((audio20_control_cur_1_t *)pBuff)->bCur; + return true; + + case AUDIO20_FU_CTRL_VOLUME: + TU_VERIFY(p_request->wLength == sizeof(audio20_control_cur_2_t)); + usb_audio_volume[channelNum] = ((audio20_control_cur_2_t *)pBuff)->bCur; + return true; + + default: + return false; + } + } + return false; +} + +// Class-specific GET requests for an entity (clock source, feature unit, input terminal). +bool tud_audio_get_req_entity_cb(uint8_t rhport, tusb_control_request_t const *p_request) { + (void)rhport; + + uint8_t const channelNum = (uint8_t)tu_u16_low(p_request->wValue); + uint8_t const ctrlSel = (uint8_t)tu_u16_high(p_request->wValue); + uint8_t const entityID = (uint8_t)tu_u16_high(p_request->wIndex); + + // Input terminal connector control. The single-mic descriptor uses + // USB_AUDIO_ENTITY_INPUT_TERMINAL; the headset's microphone input terminal is + // a distinct id. (The USB-streaming input terminals don't advertise a readable + // connector control, so the host won't query them here.) + if (entityID == USB_AUDIO_ENTITY_INPUT_TERMINAL || + entityID == USB_AUDIO_HS_ENTITY_MIC_INPUT_TERMINAL) { + switch (ctrlSel) { + case AUDIO20_TE_CTRL_CONNECTOR: { + audio20_desc_channel_cluster_t ret; + ret.bNrChannels = USB_AUDIO_N_CHANNELS; + ret.bmChannelConfig = (audio20_channel_config_t)0; + ret.iChannelNames = 0; + return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &ret, sizeof(ret)); + } + default: + return false; + } + } + + // Feature unit (mute/volume) for either the speaker or mic chain. + if (entityID == USB_AUDIO_ENTITY_FEATURE_UNIT || + entityID == USB_AUDIO_HS_ENTITY_MIC_FEATURE_UNIT) { + if (channelNum > USB_AUDIO_N_CHANNELS) { + return false; + } + switch (ctrlSel) { + case AUDIO20_FU_CTRL_MUTE: + return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &usb_audio_mute[channelNum], sizeof(usb_audio_mute[channelNum])); + + case AUDIO20_FU_CTRL_VOLUME: + switch (p_request->bRequest) { + case AUDIO20_CS_REQ_CUR: + return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &usb_audio_volume[channelNum], sizeof(usb_audio_volume[channelNum])); + + case AUDIO20_CS_REQ_RANGE: { + audio20_control_range_2_n_t(1) ret; + ret.wNumSubRanges = 1; + ret.subrange[0].bMin = -90 * 256; // -90 dB + ret.subrange[0].bMax = 90 * 256; // +90 dB + ret.subrange[0].bRes = 256; // 1 dB steps + return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &ret, sizeof(ret)); + } + + default: + return false; + } + + default: + return false; + } + } + + // Clock source (sample rate set in usb_audio.enable()). + if (entityID == USB_AUDIO_ENTITY_CLOCK_SOURCE) { + switch (ctrlSel) { + case AUDIO20_CS_CTRL_SAM_FREQ: + switch (p_request->bRequest) { + case AUDIO20_CS_REQ_CUR: { + audio20_control_cur_4_t cur = { .bCur = (int32_t)usb_audio_sample_rate }; + return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &cur, sizeof(cur)); + } + + case AUDIO20_CS_REQ_RANGE: { + audio20_control_range_4_n_t(1) ret; + ret.wNumSubRanges = 1; + ret.subrange[0].bMin = (int32_t)usb_audio_sample_rate; + ret.subrange[0].bMax = (int32_t)usb_audio_sample_rate; + ret.subrange[0].bRes = 0; + return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &ret, sizeof(ret)); + } + + default: + return false; + } + + case AUDIO20_CS_CTRL_CLK_VALID: { + audio20_control_cur_1_t cur = { .bCur = 1 }; + return tud_audio_buffer_and_schedule_control_xfer(rhport, p_request, &cur, sizeof(cur)); + } + + default: + return false; + } + } + + return false; +} + +// Keep the per-VM singleton instances (and, for the microphone, its bound +// audiosample) alive for the GC. Installed in the module globals by +// usb_audio_setup_singletons() and reset to NULL at each VM start. +MP_REGISTER_ROOT_POINTER(mp_obj_t usb_audio_microphone_singleton); +MP_REGISTER_ROOT_POINTER(mp_obj_t usb_audio_speaker_singleton); diff --git a/shared-module/usb_audio/__init__.h b/shared-module/usb_audio/__init__.h new file mode 100644 index 00000000000..5730e6ef60b --- /dev/null +++ b/shared-module/usb_audio/__init__.h @@ -0,0 +1,59 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include +#include + +#include "py/obj.h" +#include "supervisor/usb.h" + +// Enable/disable the USB Audio Class (UAC2) interface. These may only be +// called before USB is connected (i.e. from boot.py); they return false +// otherwise. At least one of microphone/speaker must be true; enabling both +// presents a combined headset. +bool shared_module_usb_audio_enable(mp_int_t sample_rate, mp_int_t channel_count, bool microphone, bool speaker); +bool shared_module_usb_audio_disable(void); + +// True once enable() has been called successfully. +bool usb_audio_enabled(void); + +// True while the host has opened either AudioStreaming alternate setting, i.e. it +// is actively listening or sending. This is the real "stream the audio now" +// signal. +bool usb_audio_streaming(void); + +// True while the host has the speaker (host -> board OUT) stream open. Distinct +// from usb_audio_streaming() so USBSpeaker can report its own direction even when +// it shares a headset function with a microphone. +bool usb_audio_speaker_streaming(void); + +// Negotiated audio format, valid when usb_audio_enabled() is true. +extern uint32_t usb_audio_sample_rate; +extern uint8_t usb_audio_channel_count; + +// Which streams were requested in enable(), valid when usb_audio_enabled() is +// true. Both true presents a combined headset. +extern bool usb_audio_microphone_enabled; +extern bool usb_audio_speaker_enabled; + +// Descriptor injection hooks, called from supervisor/shared/usb/usb_desc.c. +size_t usb_audio_descriptor_length(void); +size_t usb_audio_add_descriptor(uint8_t *descriptor_buf, descriptor_counts_t *descriptor_counts, uint8_t *current_interface_string); + +// Background task that streams samples to the host, called from +// supervisor/shared/usb/usb.c. +void usb_audio_task(void); + +// (Re)create the USBMicrophone and USBSpeaker singleton instances for the +// current VM and install them as the usb_audio.usb_microphone and +// usb_audio.usb_speaker module attributes (or None when that direction was not +// enabled in boot.py). Called once per VM from usb_setup_with_vm(), mirroring +// usb_midi_setup_ports(): the instances live on the GC heap, which is reset +// between boot.py and code.py, so they must be rebuilt each time. +void usb_audio_setup_singletons(void); diff --git a/shared-module/usb_audio/tusb_config.h b/shared-module/usb_audio/tusb_config.h new file mode 100644 index 00000000000..d7bfb65b148 --- /dev/null +++ b/shared-module/usb_audio/tusb_config.h @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#pragma once diff --git a/shared-module/usb_audio/usb_audio_descriptors.h b/shared-module/usb_audio/usb_audio_descriptors.h new file mode 100644 index 00000000000..8fba956a2a6 --- /dev/null +++ b/shared-module/usb_audio/usb_audio_descriptors.h @@ -0,0 +1,147 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries LLC +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include + +// Fixed audio format for the UAC2 microphone profile. These must have no other +// dependencies because this header is included from the TinyUSB tusb_config.h +// (to size the IN endpoint) as well as from the descriptor/binding code. + +// Actual length, in bytes, of the audio function descriptor emitted for the +// current direction (mic, speaker, or headset). usb_desc.c reads this while +// assembling the configuration descriptor, adding it to total_descriptor_length +// so wTotalLength covers the exact bytes the audio function emits. That value +// MUST equal the descriptor we actually emitted: the three directions differ in +// length, so a compile-time maximum would over-report for the shorter ones and +// make the host swallow the interfaces that follow audio (CDC/MSC), breaking +// their enumeration. The full definition lives in __init__.c (also declared in +// __init__.h for the descriptor builder). +size_t usb_audio_descriptor_length(void); + +// The isochronous IN endpoint's wMaxPacketSize in the USB descriptor is computed +// for this rate, so it is the highest rate usb_audio.enable() will accept. +#define USB_AUDIO_MAX_SAMPLE_RATE (48000) +#define USB_AUDIO_N_CHANNELS (2) + +// 16-bit signed LE PCM. +#define USB_AUDIO_N_BYTES_PER_SAMPLE (2) +#define USB_AUDIO_BITS_PER_SAMPLE (USB_AUDIO_N_BYTES_PER_SAMPLE * 8) + +// Bytes per audio frame on the wire. The descriptors always declare +// USB_AUDIO_N_CHANNELS channels, whatever channel_count the sample has, so this +// is the granularity every buffer handed to/from TinyUSB must be a multiple of. +#define USB_AUDIO_BYTES_PER_FRAME (USB_AUDIO_N_BYTES_PER_SAMPLE * USB_AUDIO_N_CHANNELS) + +// Endpoint number for the single isochronous audio data endpoint. Most device +// controllers accept an ISO endpoint on any number, so the descriptor builder +// just takes the next sequential one (signalled by 0 here). The nRF52 USBD, +// however, implements isochronous transfers only on a fixed, dedicated endpoint +// number (8): its dcd_edpt_open() rejects any other number for an ISO endpoint, +// so the stream silently never opens and the host sees a mic/speaker that +// transfers no data. Such ports override this (e.g. -DUSB_AUDIO_ISO_EP_NUM=8 in +// the port's mpconfigport.mk) to force the audio endpoint onto that number. +#ifndef USB_AUDIO_ISO_EP_NUM +#define USB_AUDIO_ISO_EP_NUM (0) +#endif + +// Fixed UAC2 entity IDs baked into USB_AUDIO_MIC_DESCRIPTOR and the +// hand-rolled speaker descriptor (USB_AUDIO_SPEAKER_DESCRIPTOR in __init__.c). +// The speaker reuses the same IDs as the mic; only the terminal roles reverse +// (input terminal = USB streaming, output terminal = desktop speaker). +#define USB_AUDIO_ENTITY_INPUT_TERMINAL (0x01) +#define USB_AUDIO_ENTITY_FEATURE_UNIT (0x02) +#define USB_AUDIO_ENTITY_OUTPUT_TERMINAL (0x03) +#define USB_AUDIO_ENTITY_CLOCK_SOURCE (0x04) + +// Combined headset (microphone + speaker both enabled) topology. A single audio function +// carries both a speaker chain (host -> board) and a mic chain (board -> host), +// so every unit/terminal needs an ID unique across the whole function -- unlike +// the single-direction descriptors above, which can reuse the same small set. +// The clock source is shared by both chains. (USB_AUDIO_HEADSET_DESCRIPTOR in +// __init__.c bakes these in.) +#define USB_AUDIO_HS_ENTITY_CLOCK_SOURCE (0x04) +#define USB_AUDIO_HS_ENTITY_SPK_INPUT_TERMINAL (0x01) // USB streaming in from host +#define USB_AUDIO_HS_ENTITY_SPK_FEATURE_UNIT (0x02) +#define USB_AUDIO_HS_ENTITY_SPK_OUTPUT_TERMINAL (0x03) // desktop speaker +#define USB_AUDIO_HS_ENTITY_MIC_INPUT_TERMINAL (0x05) // generic microphone +#define USB_AUDIO_HS_ENTITY_MIC_FEATURE_UNIT (0x06) +#define USB_AUDIO_HS_ENTITY_MIC_OUTPUT_TERMINAL (0x07) // USB streaming out to host + +// Length of the no-feedback speaker descriptor. It uses the same set of +// sub-descriptors as USB_AUDIO_MIC_DESCRIPTOR (except one isochronous data +// endpoint, no feedback endpoint), so this is identical to +// USB_AUDIO_MIC_DESC_LEN -- but spell it out independently so the two +// can diverge later (e.g. stereo) without silently mis-sizing the descriptor. +// These TUD_AUDIO20_DESC_*_LEN macros come from TinyUSB's usbd.h; this expression +// is only expanded where that header is already included (never at the point +// tusb_config.h includes us), so the header stays dependency-free. +#define USB_AUDIO_SPEAKER_DESC_LEN (TUD_AUDIO20_DESC_IAD_LEN \ + + TUD_AUDIO20_DESC_STD_AC_LEN \ + + TUD_AUDIO20_DESC_CS_AC_LEN \ + + TUD_AUDIO20_DESC_CLK_SRC_LEN \ + + TUD_AUDIO20_DESC_INPUT_TERM_LEN \ + + TUD_AUDIO20_DESC_OUTPUT_TERM_LEN \ + + TUD_AUDIO20_DESC_FEATURE_UNIT_LEN(2) \ + + TUD_AUDIO20_DESC_STD_AS_LEN \ + + TUD_AUDIO20_DESC_STD_AS_LEN \ + + TUD_AUDIO20_DESC_CS_AS_INT_LEN \ + + TUD_AUDIO20_DESC_TYPE_I_FORMAT_LEN \ + + TUD_AUDIO20_DESC_STD_AS_ISO_EP_LEN \ + + TUD_AUDIO20_DESC_CS_AS_ISO_EP_LEN) + +#define USB_AUDIO_MIC_DESC_LEN (TUD_AUDIO20_DESC_IAD_LEN \ + + TUD_AUDIO20_DESC_STD_AC_LEN \ + + TUD_AUDIO20_DESC_CS_AC_LEN \ + + TUD_AUDIO20_DESC_CLK_SRC_LEN \ + /* mic chain: microphone input terminal -> feature unit -> USB-streaming out */ \ + + TUD_AUDIO20_DESC_INPUT_TERM_LEN \ + + TUD_AUDIO20_DESC_OUTPUT_TERM_LEN \ + + TUD_AUDIO20_DESC_FEATURE_UNIT_LEN(2) \ + /* mic AudioStreaming interface (alt 0 + alt 1 with IN endpoint) */ \ + + TUD_AUDIO20_DESC_STD_AS_LEN \ + + TUD_AUDIO20_DESC_STD_AS_LEN \ + + TUD_AUDIO20_DESC_CS_AS_INT_LEN \ + + TUD_AUDIO20_DESC_TYPE_I_FORMAT_LEN \ + + TUD_AUDIO20_DESC_STD_AS_ISO_EP_LEN \ + + TUD_AUDIO20_DESC_CS_AS_ISO_EP_LEN) + +// Length of the combined headset descriptor (microphone + speaker both enabled): one IAD +// wrapping a single AudioControl interface plus two AudioStreaming interfaces +// (speaker OUT + mic IN). The AC interface declares one shared clock, plus an +// input terminal / feature unit / output terminal for each of the two chains; +// each AS interface contributes a zero-bandwidth alt 0 and a streaming alt 1 +// with one isochronous data endpoint (no feedback endpoint, matching the +// single-direction descriptors). See USB_AUDIO_HEADSET_DESCRIPTOR in __init__.c. +// Expanded only where TinyUSB's usbd.h is already included (never at the point +// tusb_config.h includes us), so this header stays dependency-free. +#define USB_AUDIO_HEADSET_DESC_LEN (TUD_AUDIO20_DESC_IAD_LEN \ + + TUD_AUDIO20_DESC_STD_AC_LEN \ + + TUD_AUDIO20_DESC_CS_AC_LEN \ + + TUD_AUDIO20_DESC_CLK_SRC_LEN \ + /* speaker chain: USB-streaming input terminal -> feature unit -> speaker */ \ + + TUD_AUDIO20_DESC_INPUT_TERM_LEN \ + + TUD_AUDIO20_DESC_FEATURE_UNIT_LEN(2) \ + + TUD_AUDIO20_DESC_OUTPUT_TERM_LEN \ + /* mic chain: microphone input terminal -> feature unit -> USB-streaming out */ \ + + TUD_AUDIO20_DESC_INPUT_TERM_LEN \ + + TUD_AUDIO20_DESC_FEATURE_UNIT_LEN(2) \ + + TUD_AUDIO20_DESC_OUTPUT_TERM_LEN \ + /* speaker AudioStreaming interface (alt 0 + alt 1 with OUT endpoint) */ \ + + TUD_AUDIO20_DESC_STD_AS_LEN \ + + TUD_AUDIO20_DESC_STD_AS_LEN \ + + TUD_AUDIO20_DESC_CS_AS_INT_LEN \ + + TUD_AUDIO20_DESC_TYPE_I_FORMAT_LEN \ + + TUD_AUDIO20_DESC_STD_AS_ISO_EP_LEN \ + + TUD_AUDIO20_DESC_CS_AS_ISO_EP_LEN \ + /* mic AudioStreaming interface (alt 0 + alt 1 with IN endpoint) */ \ + + TUD_AUDIO20_DESC_STD_AS_LEN \ + + TUD_AUDIO20_DESC_STD_AS_LEN \ + + TUD_AUDIO20_DESC_CS_AS_INT_LEN \ + + TUD_AUDIO20_DESC_TYPE_I_FORMAT_LEN \ + + TUD_AUDIO20_DESC_STD_AS_ISO_EP_LEN \ + + TUD_AUDIO20_DESC_CS_AS_ISO_EP_LEN) diff --git a/shared-module/usb_cdc/__init__.c b/shared-module/usb_cdc/__init__.c index 0248c0f180f..deb41c9abfc 100644 --- a/shared-module/usb_cdc/__init__.c +++ b/shared-module/usb_cdc/__init__.c @@ -105,7 +105,7 @@ static const uint8_t usb_cdc_descriptor_template[] = { 0xFF, // 54 bEndpointAddress (OUT/H2D) [SET AT RUNTIME] #define CDC_DATA_OUT_ENDPOINT_INDEX 54 0x02, // 55 bmAttributes (Bulk) - #if USB_HIGHSPEED + #if CIRCUITPY_USB_DEVICE_HIGH_SPEED == 1 0x00, 0x02, // 56,57 wMaxPacketSize 512 #else 0x40, 0x00, // 56,57 wMaxPacketSize 64 @@ -118,7 +118,7 @@ static const uint8_t usb_cdc_descriptor_template[] = { 0xFF, // 61 bEndpointAddress (IN/D2H) [SET AT RUNTIME: 0x80 | number] #define CDC_DATA_IN_ENDPOINT_INDEX 61 0x02, // 62 bmAttributes (Bulk) - #if USB_HIGHSPEED + #if CIRCUITPY_USB_DEVICE_HIGH_SPEED == 1 0x00, 0x02, // 63,64 wMaxPacketSize 512 #else 0x40, 0x00, // 63,64 wMaxPacketSize 64 @@ -126,10 +126,10 @@ static const uint8_t usb_cdc_descriptor_template[] = { 0x00, // 65 bInterval 0 (unit depends on device speed) }; -static const char console_cdc_comm_interface_name[] = USB_INTERFACE_NAME " CDC control"; -static const char data_cdc_comm_interface_name[] = USB_INTERFACE_NAME " CDC2 control"; -static const char console_cdc_data_interface_name[] = USB_INTERFACE_NAME " CDC data"; -static const char data_cdc_data_interface_name[] = USB_INTERFACE_NAME " CDC2 data"; +static const char console_cdc_comm_interface_name[] = "CDC control"; +static const char data_cdc_comm_interface_name[] = "CDC2 control"; +static const char console_cdc_data_interface_name[] = "CDC data"; +static const char data_cdc_data_interface_name[] = "CDC2 data"; // .idx is set later. @@ -204,12 +204,22 @@ size_t usb_cdc_add_descriptor(uint8_t *descriptor_buf, descriptor_counts_t *desc descriptor_counts->num_out_endpoints++; descriptor_counts->current_endpoint++; - usb_add_interface_string(*current_interface_string, + #if CIRCUITPY_FULL_BUILD + const char *custom_control_interface_name = + console ? custom_usb_cdc_console_control_interface_name : custom_usb_cdc_data_control_interface_name; + const char *custom_data_interface_name = + console ? custom_usb_cdc_console_data_interface_name : custom_usb_cdc_data_data_interface_name; + #else + const char *custom_control_interface_name = NULL; + const char *custom_data_interface_name = NULL; + #endif + + usb_add_interface_name(*current_interface_string, custom_control_interface_name, console ? console_cdc_comm_interface_name : data_cdc_comm_interface_name); descriptor_buf[CDC_COMM_INTERFACE_STRING_INDEX] = *current_interface_string; (*current_interface_string)++; - usb_add_interface_string(*current_interface_string, + usb_add_interface_name(*current_interface_string, custom_data_interface_name, console ? console_cdc_data_interface_name : data_cdc_data_interface_name); descriptor_buf[CDC_DATA_INTERFACE_STRING_INDEX] = *current_interface_string; (*current_interface_string)++; @@ -326,7 +336,7 @@ static const uint8_t usb_vendor_descriptor_template[] = { 0xFF, // 11 bEndpointAddress (IN/D2H) [SET AT RUNTIME: number] #define VENDOR_OUT_ENDPOINT_INDEX 11 0x02, // 12 bmAttributes (Bulk) - #if USB_HIGHSPEED + #if CIRCUITPY_USB_DEVICE_HIGH_SPEED == 1 0x00, 0x02, // 13,14 wMaxPacketSize 512 #else 0x40, 0x00, // 13,14 wMaxPacketSize 64 @@ -343,7 +353,7 @@ static const uint8_t usb_vendor_descriptor_template[] = { 0x0 // 22 bInterval 0 }; -static const char vendor_interface_name[] = USB_INTERFACE_NAME " WebUSB"; +static const char vendor_interface_name[] = "WebUSB"; bool usb_vendor_enabled(void) { @@ -356,10 +366,10 @@ size_t usb_vendor_descriptor_length(void) { static uint8_t *ms_os_20_descriptor = NULL; -size_t vendor_ms_os_20_descriptor_length() { +size_t vendor_ms_os_20_descriptor_length(void) { return ms_os_20_descriptor != NULL ? sizeof(ms_os_20_descriptor_template) : 0; } -uint8_t const *vendor_ms_os_20_descriptor() { +uint8_t const *vendor_ms_os_20_descriptor(void) { return ms_os_20_descriptor; } @@ -386,7 +396,7 @@ size_t usb_vendor_add_descriptor(uint8_t *descriptor_buf, descriptor_counts_t *d descriptor_counts->num_out_endpoints++; descriptor_counts->current_endpoint++; - usb_add_interface_string(*current_interface_string, vendor_interface_name); + usb_add_interface_name(*current_interface_string, NULL, vendor_interface_name); descriptor_buf[VENDOR_INTERFACE_STRING_INDEX] = *current_interface_string; (*current_interface_string)++; diff --git a/shared-module/usb_hid/Device.c b/shared-module/usb_hid/Device.c index d6c4697210f..adcea84904e 100644 --- a/shared-module/usb_hid/Device.c +++ b/shared-module/usb_hid/Device.c @@ -12,45 +12,10 @@ #include "shared-bindings/usb_hid/Device.h" #include "shared-module/usb_hid/__init__.h" #include "shared-module/usb_hid/Device.h" +#include "shared-module/usb_hid/report_descriptors.h" #include "supervisor/shared/tick.h" #include "tusb.h" -static const uint8_t keyboard_report_descriptor[] = { - 0x05, 0x01, // Usage Page (Generic Desktop Ctrls) - 0x09, 0x06, // Usage (Keyboard) - 0xA1, 0x01, // Collection (Application) - 0x85, 0x01, // Report ID (1) - 0x05, 0x07, // Usage Page (Kbrd/Keypad) - 0x19, 0xE0, // Usage Minimum (0xE0) - 0x29, 0xE7, // Usage Maximum (0xE7) - 0x15, 0x00, // Logical Minimum (0) - 0x25, 0x01, // Logical Maximum (1) - 0x75, 0x01, // Report Size (1) - 0x95, 0x08, // Report Count (8) - 0x81, 0x02, // Input (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position) - 0x95, 0x01, // Report Count (1) - 0x75, 0x08, // Report Size (8) - 0x81, 0x01, // Input (Const,Array,Abs,No Wrap,Linear,Preferred State,No Null Position) - 0x95, 0x05, // Report Count (5) - 0x75, 0x01, // Report Size (1) - 0x05, 0x08, // Usage Page (LEDs) - 0x19, 0x01, // Usage Minimum (Num Lock) - 0x29, 0x05, // Usage Maximum (Kana) - 0x91, 0x02, // Output (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position,Non-volatile) - 0x95, 0x01, // Report Count (1) - 0x75, 0x03, // Report Size (3) - 0x91, 0x01, // Output (Const,Array,Abs,No Wrap,Linear,Preferred State,No Null Position,Non-volatile) - 0x95, 0x06, // Report Count (6) - 0x75, 0x08, // Report Size (8) - 0x15, 0x00, // Logical Minimum (0) - 0x26, 0xFF, 0x00, // Logical Maximum (255) - 0x05, 0x07, // Usage Page (Kbrd/Keypad) - 0x19, 0x00, // Usage Minimum (0x00) - 0x2A, 0xFF, 0x00, // Usage Maximum (0xFF) - 0x81, 0x00, // Input (Data,Array,Abs,No Wrap,Linear,Preferred State,No Null Position) - 0xC0, // End Collection -}; - const usb_hid_device_obj_t usb_hid_device_keyboard_obj = { .base = { .type = &usb_hid_device_type, @@ -65,42 +30,6 @@ const usb_hid_device_obj_t usb_hid_device_keyboard_obj = { .out_report_lengths = { 1, }, }; -static const uint8_t mouse_report_descriptor[] = { - 0x05, 0x01, // Usage Page (Generic Desktop Ctrls) - 0x09, 0x02, // Usage (Mouse) - 0xA1, 0x01, // Collection (Application) - 0x09, 0x01, // Usage (Pointer) - 0xA1, 0x00, // Collection (Physical) - 0x85, 0x02, // 10, 11 Report ID (2) - 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 -}; - const usb_hid_device_obj_t usb_hid_device_mouse_obj = { .base = { .type = &usb_hid_device_type, @@ -115,21 +44,6 @@ const usb_hid_device_obj_t usb_hid_device_mouse_obj = { .out_report_lengths = { 0, }, }; -static const uint8_t consumer_control_report_descriptor[] = { - 0x05, 0x0C, // Usage Page (Consumer) - 0x09, 0x01, // Usage (Consumer Control) - 0xA1, 0x01, // Collection (Application) - 0x85, 0x03, // Report ID (3) - 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 -}; - const usb_hid_device_obj_t usb_hid_device_consumer_control_obj = { .base = { .type = &usb_hid_device_type, @@ -216,6 +130,19 @@ void common_hal_usb_hid_device_send_report(usb_hid_device_obj_t *self, uint8_t * mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("USB busy")); } + const uint8_t boot_device = usb_hid_boot_device(); + if (boot_device != 0 && tud_hid_get_protocol() == HID_PROTOCOL_BOOT) { + // In boot protocol the host reads the fixed boot report, which carries no report ID, + // and ignores every device other than the boot device. + if (self->usage_page == HID_USAGE_PAGE_DESKTOP && + ((boot_device == 1 && self->usage == HID_USAGE_DESKTOP_KEYBOARD) || + (boot_device == 2 && self->usage == HID_USAGE_DESKTOP_MOUSE))) { + report_id = 0; + } else { + return; + } + } + if (!tud_hid_report(report_id, report, len)) { mp_raise_msg(&mp_type_OSError, MP_ERROR_TEXT("USB error")); } diff --git a/shared-module/usb_hid/__init__.c b/shared-module/usb_hid/__init__.c index 4d0d5fc2e3d..26ca5108743 100644 --- a/shared-module/usb_hid/__init__.c +++ b/shared-module/usb_hid/__init__.c @@ -145,8 +145,6 @@ size_t usb_hid_descriptor_length(void) { // This is the interface descriptor, not the report descriptor. size_t usb_hid_add_descriptor(uint8_t *descriptor_buf, descriptor_counts_t *descriptor_counts, uint8_t *current_interface_string, uint16_t report_descriptor_length, uint8_t boot_device) { - const char *usb_hid_interface_name; - memcpy(descriptor_buf, usb_hid_descriptor_template, sizeof(usb_hid_descriptor_template)); descriptor_buf[HID_DESCRIPTOR_INTERFACE_INDEX] = descriptor_counts->current_interface; @@ -157,12 +155,7 @@ size_t usb_hid_add_descriptor(uint8_t *descriptor_buf, descriptor_counts_t *desc descriptor_buf[HID_DESCRIPTOR_INTERFACE_PROTOCOL_INDEX] = boot_device; // 1: keyboard, 2: mouse } - if (custom_usb_hid_interface_name == NULL) { - usb_hid_interface_name = USB_INTERFACE_NAME " HID"; - } else { - usb_hid_interface_name = custom_usb_hid_interface_name; - } - usb_add_interface_string(*current_interface_string, usb_hid_interface_name); + usb_add_interface_name(*current_interface_string, custom_usb_hid_interface_name, "HID"); descriptor_buf[HID_DESCRIPTOR_INTERFACE_STRING_INDEX] = *current_interface_string; (*current_interface_string)++; diff --git a/shared-module/usb_hid/report_descriptors.c b/shared-module/usb_hid/report_descriptors.c new file mode 100644 index 00000000000..fe629153c78 --- /dev/null +++ b/shared-module/usb_hid/report_descriptors.c @@ -0,0 +1,96 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018 hathach for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// Standard HID report descriptors shared between ports. + +#include "shared-module/usb_hid/report_descriptors.h" + +const uint8_t keyboard_report_descriptor[] = { + 0x05, 0x01, // Usage Page (Generic Desktop Ctrls) + 0x09, 0x06, // Usage (Keyboard) + 0xA1, 0x01, // Collection (Application) + 0x85, 0x01, // Report ID (1) + 0x05, 0x07, // Usage Page (Kbrd/Keypad) + 0x19, 0xE0, // Usage Minimum (0xE0) + 0x29, 0xE7, // Usage Maximum (0xE7) + 0x15, 0x00, // Logical Minimum (0) + 0x25, 0x01, // Logical Maximum (1) + 0x75, 0x01, // Report Size (1) + 0x95, 0x08, // Report Count (8) + 0x81, 0x02, // Input (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position) + 0x95, 0x01, // Report Count (1) + 0x75, 0x08, // Report Size (8) + 0x81, 0x01, // Input (Const,Array,Abs,No Wrap,Linear,Preferred State,No Null Position) + 0x95, 0x05, // Report Count (5) + 0x75, 0x01, // Report Size (1) + 0x05, 0x08, // Usage Page (LEDs) + 0x19, 0x01, // Usage Minimum (Num Lock) + 0x29, 0x05, // Usage Maximum (Kana) + 0x91, 0x02, // Output (Data,Var,Abs,No Wrap,Linear,Preferred State,No Null Position,Non-volatile) + 0x95, 0x01, // Report Count (1) + 0x75, 0x03, // Report Size (3) + 0x91, 0x01, // Output (Const,Array,Abs,No Wrap,Linear,Preferred State,No Null Position,Non-volatile) + 0x95, 0x06, // Report Count (6) + 0x75, 0x08, // Report Size (8) + 0x15, 0x00, // Logical Minimum (0) + 0x26, 0xFF, 0x00, // Logical Maximum (255) + 0x05, 0x07, // Usage Page (Kbrd/Keypad) + 0x19, 0x00, // Usage Minimum (0x00) + 0x2A, 0xFF, 0x00, // Usage Maximum (0xFF) + 0x81, 0x00, // Input (Data,Array,Abs,No Wrap,Linear,Preferred State,No Null Position) + 0xC0, // End Collection +}; + +const uint8_t mouse_report_descriptor[] = { + 0x05, 0x01, // Usage Page (Generic Desktop Ctrls) + 0x09, 0x02, // Usage (Mouse) + 0xA1, 0x01, // Collection (Application) + 0x09, 0x01, // Usage (Pointer) + 0xA1, 0x00, // Collection (Physical) + 0x85, 0x02, // 10, 11 Report ID (2) + 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 +}; + +const uint8_t consumer_control_report_descriptor[] = { + 0x05, 0x0C, // Usage Page (Consumer) + 0x09, 0x01, // Usage (Consumer Control) + 0xA1, 0x01, // Collection (Application) + 0x85, 0x03, // Report ID (3) + 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 +}; diff --git a/shared-module/usb_hid/report_descriptors.h b/shared-module/usb_hid/report_descriptors.h new file mode 100644 index 00000000000..94a9a752f6a --- /dev/null +++ b/shared-module/usb_hid/report_descriptors.h @@ -0,0 +1,19 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2018 hathach for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// Standard HID report descriptors shared between ports. These are plain byte +// arrays with no dependencies, so ports using TinyUSB and ports using other +// USB stacks can both use them. They are defined in report_descriptors.c. +// The explicit sizes let callers use sizeof() and are checked by the compiler +// against the definitions. + +#pragma once + +#include + +extern const uint8_t keyboard_report_descriptor[67]; +extern const uint8_t mouse_report_descriptor[64]; +extern const uint8_t consumer_control_report_descriptor[25]; diff --git a/shared-module/usb_host_audio/USBIn.c b/shared-module/usb_host_audio/USBIn.c new file mode 100644 index 00000000000..eb61ba219d7 --- /dev/null +++ b/shared-module/usb_host_audio/USBIn.c @@ -0,0 +1,654 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/usb_host_audio/USBIn.h" + +#include + +#include "tusb.h" +#include "host/hcd.h" +#include "host/usbh_pvt.h" + +#include "py/runtime.h" +#include "shared/runtime/interrupt_char.h" +#include "shared-bindings/microcontroller/__init__.h" +#include "shared-bindings/usb/core/__init__.h" +#include "shared-bindings/usb/core/Device.h" +#include "shared-bindings/usb_host/Port.h" +#include "supervisor/port.h" +#include "supervisor/port_heap.h" +#include "supervisor/shared/tick.h" + +// Room for a good number of records per transfer, for when the ring in the +// host controller has a backlog. +#define USBIN_MIN_XFER_BUFFER (1024) +// The host controller marks lost packets with a record of this length. +#define USBIN_LOST_RECORD (0xffff) +// get_buffer() averages the frames waiting over about 2^this calls. +#define USBIN_LEVEL_SHIFT (6) +// record() gives up when the microphone sends nothing for this long. +#define USBIN_RECORD_TIMEOUT_MS (1000) +// deinit() waits this long for the device to stop streaming. A request without +// a data stage takes at most 50 ms. +#define USBIN_STOP_TIMEOUT_MS (100) +// The stream ends after this many failed transfers in a row. A microphone that +// was unplugged or stopped sending fails every one. +#define USBIN_MAX_FAILURES (32) +// Frame numbers are compared modulo this. Host controllers count to a multiple of it. +#define USBIN_FRAME_MASK (0x7ff) +// An aborted transfer of a periodic endpoint ends at the end of the frame. +#define USBIN_ABORT_SETTLE_US (2000) + +// The host controller receives one isochronous IN stream at a time, so there is +// one streaming object at most. TinyUSB copies the transfer and calls back with +// only user_data, which carries _seq so that a completion which was already on +// its way when its stream ended is recognised and dropped. +// Only the VM changes these, and the completion callback reads them. +static usb_host_audio_usbin_obj_t *_active; +static uintptr_t _seq; + +// The completion callback runs in tuh_task(), which may be a task of its own +// (CIRCUITPY_USB_HOST_TASK). It holds this lock while it uses _active, writes +// the ring and queues the next transfer, and the VM holds it while it changes +// _active or _seq, aborts the transfer or uses the ring. Then a callback never +// queues a transfer, or writes the ring, of a stream that the VM ended and is +// freeing, and the ring has one user at a time. The VM never holds it while it +// waits for TinyUSB, which would wait for the callback, and holds it only for +// a copy into or out of the ring. The callback holds it no longer than it +// takes to store one transfer. +// +// The lock is real wherever TinyUSB is built for an OS (OSAL_MUTEX_REQUIRED), +// and it is not recursive: taking it again on the same core waits forever. +// On RP2 (OPT_OS_PICO) it is a pico-sdk mutex. There tuh_task() and the audio +// refill are both background callbacks on core 0, and the VM doesn't run +// background callbacks while it holds the lock, so it is never contended. +// Without an OS it does nothing. +#if OSAL_MUTEX_REQUIRED +static osal_mutex_def_t _lock_def; +static osal_mutex_t _lock; +#else +#define _lock NULL +#endif + +static void _lock_take(void) { + (void)osal_mutex_lock(_lock, OSAL_TIMEOUT_WAIT_FOREVER); +} + +static void _lock_give(void) { + (void)osal_mutex_unlock(_lock); +} + +// The PCM ring holds whole frames. It is used with the lock held. + +// Room for this many bytes of narrowed samples on the stack. +#define USBIN_NARROW_CHUNK (128) + +// Called by the completion callback only. +static void _ring_append(usb_host_audio_usbin_obj_t *self, const uint8_t *data, uint32_t frames) { + uint32_t room = ringbuf_num_empty(&self->ring) / self->frame_bytes; + if (frames > room) { + // Nothing is reading fast enough. Keep the older audio, which comes + // before the gap, and drop what doesn't fit. The reader skips ahead. + frames = room; + self->overflowed = true; + self->overflow = true; + } + if (self->bit_depth <= 16) { + ringbuf_put_n(&self->ring, data, frames * self->frame_bytes); + return; + } + // Keep the top two bytes of each little endian 3 or 4 byte sample. + const uint32_t sample_bytes = self->bit_depth / 8; + uint32_t samples = frames * self->base.channel_count; + uint8_t narrowed[USBIN_NARROW_CHUNK]; + while (samples > 0) { + uint32_t n = MIN(samples, sizeof(narrowed) / 2); + for (uint32_t i = 0; i < n; i++) { + narrowed[2 * i] = data[sample_bytes - 2]; + narrowed[2 * i + 1] = data[sample_bytes - 1]; + data += sample_bytes; + } + ringbuf_put_n(&self->ring, narrowed, 2 * n); + samples -= n; + } +} + +// The frames waiting in the ring. +static uint32_t _ring_count(usb_host_audio_usbin_obj_t *self) { + return ringbuf_num_filled(&self->ring) / self->frame_bytes; +} + +// Takes frames, which must be waiting, out of the ring into dest, or drops them +// when dest is NULL. +static void _ring_take(usb_host_audio_usbin_obj_t *self, uint8_t *dest, uint32_t frames) { + if (dest != NULL) { + ringbuf_get_n(&self->ring, dest, frames * self->frame_bytes); + } else { + ringbuf_discard_n(&self->ring, frames * self->frame_bytes); + } +} + +static void _transfer_done_cb(tuh_xfer_t *xfer); +static void _stream_done(usb_host_audio_usbin_obj_t *self, tuh_xfer_t *xfer); + +// Called with the lock held. +static bool _queue_transfer(usb_host_audio_usbin_obj_t *self) { + #if !CIRCUITPY_USB_HOST_ISO_RECORDS + // The transfer receives the packet of the endpoint's next service interval. + // Those that went by since the last transfer was queued are lost. + uint16_t frame = hcd_frame_number(TUH_OPT_RHPORT) & USBIN_FRAME_MASK; + if (self->frame_known) { + uint16_t elapsed = (frame - self->queued_frame) & USBIN_FRAME_MASK; + if (elapsed > self->frame_interval) { + self->overflow = true; + } + } + self->queued_frame = frame; + self->frame_known = true; + #endif + tuh_xfer_t xfer = { + .daddr = self->device_address, + .ep_addr = self->endpoint, + .buffer = self->xfer_buffer, + .buflen = self->xfer_buffer_len, + .complete_cb = _transfer_done_cb, + .user_data = _seq, + }; + self->streaming = tuh_edpt_xfer(&xfer); + return self->streaming; +} + +// Runs inside tuh_task(): a background callback on the VM, or a task of its +// own (CIRCUITPY_USB_HOST_TASK) that runs while the VM is busy. +static void _transfer_done_cb(tuh_xfer_t *xfer) { + _lock_take(); + usb_host_audio_usbin_obj_t *self = _active; + if (self == NULL || xfer->user_data != _seq) { + // Late completion of a stream that already ended. + _lock_give(); + return; + } + _stream_done(self, xfer); + _lock_give(); +} + +// Stores the audio of a completed transfer and queues the next one. Called +// with the lock held. +static void _stream_done(usb_host_audio_usbin_obj_t *self, tuh_xfer_t *xfer) { + #if CIRCUITPY_USB_HOST_ISO_RECORDS + if (xfer->result != XFER_RESULT_SUCCESS) { + self->streaming = false; + return; + } + // The transfer holds whole records: a little endian uint16_t length, then + // one packet's payload. + const uint8_t *buf = self->xfer_buffer; + uint32_t len = MIN(xfer->actual_len, self->xfer_buffer_len); + uint32_t pos = 0; + while (pos + 2 <= len) { + uint32_t record_len = buf[pos] | (buf[pos + 1] << 8); + pos += 2; + if (record_len == USBIN_LOST_RECORD) { + self->overflow = true; + continue; + } + record_len = MIN(record_len, len - pos); + _ring_append(self, buf + pos, record_len / self->wire_frame_bytes); + pos += record_len; + } + #else + if (xfer->result == XFER_RESULT_SUCCESS) { + // The transfer holds one packet. + self->failures = 0; + uint32_t len = MIN(xfer->actual_len, self->xfer_buffer_len); + _ring_append(self, self->xfer_buffer, len / self->wire_frame_bytes); + } else if (xfer->result == XFER_RESULT_FAILED && self->failures < USBIN_MAX_FAILURES) { + // A packet that was damaged or not received in its frame. Isochronous + // packets are not retried. + self->failures++; + self->overflow = true; + } else { + self->streaming = false; + return; + } + #endif + _queue_transfer(self); +} + +// The descriptor of endpoint in the device's configuration, or NULL. Sets +// interface to the number of the interface whose alternate setting has it. +static const tusb_desc_endpoint_t *_find_endpoint(usb_core_device_obj_t *device, uint8_t endpoint, + uint8_t *interface) { + *interface = USBIN_NO_INTERFACE; + const uint8_t *desc = device->configuration_descriptor; + if (desc == NULL) { + return NULL; + } + const uint8_t *end = desc + tu_le16toh(((const tusb_desc_configuration_t *)desc)->wTotalLength); + uint8_t current = USBIN_NO_INTERFACE; + for (const uint8_t *p = tu_desc_next(desc); p < end; p = tu_desc_next(p)) { + if (tu_desc_type(p) == TUSB_DESC_INTERFACE) { + current = ((const tusb_desc_interface_t *)p)->bInterfaceNumber; + } else if (tu_desc_type(p) == TUSB_DESC_ENDPOINT && + ((const tusb_desc_endpoint_t *)p)->bEndpointAddress == endpoint) { + *interface = current; + return (const tusb_desc_endpoint_t *)p; + } + } + return NULL; +} + +// Select alternate setting 0, which stops the microphone sending. usb.core +// ends the transfer first, as it does for the same request from Python. This +// runs when unwinding from an exception and in the finaliser, so it neither +// raises nor waits long. +static void _stop_device(usb_host_audio_usbin_obj_t *self) { + if (self->interface == USBIN_NO_INTERFACE || common_hal_usb_core_device_deinited(self->device)) { + return; + } + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + common_hal_usb_core_device_ctrl_transfer(self->device, + TUSB_DIR_OUT | (TUSB_REQ_TYPE_STANDARD << 5) | TUSB_REQ_RCPT_INTERFACE, + TUSB_REQ_SET_INTERFACE, 0, self->interface, NULL, 0, USBIN_STOP_TIMEOUT_MS); + nlr_pop(); + } +} + +void common_hal_usb_host_audio_usbin_construct(usb_host_audio_usbin_obj_t *self, + usb_core_device_obj_t *device, uint8_t endpoint, uint32_t sample_rate, + uint8_t channel_count, uint8_t bit_depth, bool samples_signed, + uint16_t max_packet_size, uint32_t buffer_frames, uint32_t iso_buffer_size) { + // The finaliser may run on an object that a raise below left half made. + self->xfer_buffer = NULL; + if (_active != NULL) { + if (common_hal_usb_host_audio_usbin_get_streaming(_active)) { + // The host controller would hand the one stream it receives to the + // newer endpoint and fail the older one. + mp_raise_RuntimeError_varg(MP_ERROR_TEXT("%q in use"), MP_QSTR_USBIn); + } + // Its stream ended, so it is of no more use. Don't make the caller + // find and deinit an object that it may not even have any more. + common_hal_usb_host_audio_usbin_deinit(_active); + } + + self->device = device; + self->device_address = device->device_address; + self->endpoint = endpoint; + self->bit_depth = bit_depth; + self->wire_frame_bytes = (bit_depth / 8) * channel_count; + // The audio pipeline carries 8 and 16 bit samples, so 24 and 32 bit ones are narrowed. + self->base.bits_per_sample = bit_depth == 8 ? 8 : 16; + self->base.channel_count = channel_count; + self->base.sample_rate = sample_rate; + self->base.samples_signed = samples_signed; + self->base.single_buffer = false; + self->frame_bytes = (self->base.bits_per_sample / 8) * channel_count; + self->buffer_frames = buffer_frames; + self->output_half_bytes = buffer_frames * self->frame_bytes; + self->base.max_buffer_length = self->output_half_bytes * 2; + self->output_buffer = NULL; + self->output_index = 0; + ringbuf_init(&self->ring, NULL, 0); + self->primed = false; + self->overflowed = false; + self->overflow = false; + self->streaming = false; + #if OSAL_MUTEX_REQUIRED + if (_lock == NULL) { + _lock = osal_mutex_create(&_lock_def); + } + #endif + + if (!common_hal_usb_core_device_open_endpoint(device, endpoint)) { + mp_raise_usb_core_USBError(NULL); + } + const tusb_desc_endpoint_t *endpoint_desc = _find_endpoint(device, endpoint, &self->interface); + + #if CIRCUITPY_USB_HOST_ISO_RECORDS + (void)endpoint_desc; + // The host controller keeps the packets that arrive between transfers in a + // ring of its own. Only one isochronous stream at a time can use it. + if (!common_hal_usb_host_port_claim_iso_buffer(iso_buffer_size)) { + mp_raise_RuntimeError_varg(MP_ERROR_TEXT("%q in use"), MP_QSTR_usb_host); + } + + // A record that doesn't fit in the transfer buffer is dropped by the host + // controller, so leave room for the largest packet and its length. + self->xfer_buffer_len = MAX(USBIN_MIN_XFER_BUFFER, max_packet_size + 2); + #else + (void)iso_buffer_size; + // Each transfer receives one packet. A longer one would ask for more + // packets in the same frame. + uint8_t interval = 1; + if (endpoint_desc != NULL) { + max_packet_size = tu_edpt_packet_size(endpoint_desc); + interval = endpoint_desc->bInterval; + } + mp_arg_validate_int_min(max_packet_size, 1, MP_QSTR_max_packet_size); + self->xfer_buffer_len = max_packet_size; + self->frame_interval = 1 << (MIN(MAX(interval, 1), 16) - 1); + self->frame_known = false; + self->aborted = false; + self->failures = 0; + #endif + size_t ring_bytes = buffer_frames * USBIN_RING_BUFFERS * self->frame_bytes; + uint8_t *ring = port_malloc(ring_bytes, false); + // The host controller writes the transfer buffer. + self->xfer_buffer = port_malloc(self->xfer_buffer_len, true); + if (ring == NULL || self->xfer_buffer == NULL) { + #if CIRCUITPY_USB_HOST_ISO_RECORDS + common_hal_usb_host_port_release_iso_buffer(); + #endif + port_free(ring); + port_free(self->xfer_buffer); + self->xfer_buffer = NULL; + m_malloc_fail(ring_bytes + self->xfer_buffer_len); + } + ringbuf_init(&self->ring, ring, ring_bytes); + + _lock_take(); + _seq++; + _active = self; + bool queued = _queue_transfer(self); + _lock_give(); + if (!queued) { + common_hal_usb_host_audio_usbin_deinit(self); + mp_raise_usb_core_USBError(NULL); + } +} + +bool common_hal_usb_host_audio_usbin_deinited(usb_host_audio_usbin_obj_t *self) { + return self->xfer_buffer == NULL; +} + +void common_hal_usb_host_audio_usbin_deinit(usb_host_audio_usbin_obj_t *self) { + if (common_hal_usb_host_audio_usbin_deinited(self)) { + return; + } + if (common_hal_usb_host_audio_usbin_get_streaming(self)) { + // Don't leave the microphone sending to an endpoint that is no longer + // polled. A stream that already ended was stopped by whoever ended it, + // and its interface may be streaming for someone else by now. + _stop_device(self); + } + if (_active == self) { + _lock_take(); + if (self->streaming) { + // It fails when the device is gone, and then its endpoints are + // closed already. + tuh_edpt_abort_xfer(self->device_address, self->endpoint); + #if !CIRCUITPY_USB_HOST_ISO_RECORDS + self->aborted = true; + #endif + } + // Drop a completion that is queued already. + _seq++; + _active = NULL; + _lock_give(); + #if CIRCUITPY_USB_HOST_ISO_RECORDS + // Whatever ended the stream also stopped the host controller writing + // to its ring, and once the abort returned it no longer writes the + // transfer buffer. + common_hal_usb_host_port_release_iso_buffer(); + #endif + } + #if !CIRCUITPY_USB_HOST_ISO_RECORDS + if (self->aborted) { + // The aborted transfer may still receive its packet. + common_hal_mcu_delay_us(USBIN_ABORT_SETTLE_US); + } + #endif + self->streaming = false; + port_free(self->xfer_buffer); + port_free(self->ring.buf); + port_free(self->output_buffer); + self->xfer_buffer = NULL; + ringbuf_deinit(&self->ring); + self->output_buffer = NULL; + self->device = NULL; +} + +void usb_host_audio_reset(void) { + if (_active != NULL) { + common_hal_usb_host_audio_usbin_deinit(_active); + } +} + +void usb_host_audio_stop_device(uint8_t device_address) { + usb_host_audio_usbin_obj_t *self = _active; + if (self == NULL || self->device_address != device_address) { + return; + } + _lock_take(); + if (self->streaming) { + // The host controller stops polling the endpoint when it sends the + // request. A transfer queued after that would start polling it again, + // which some devices answer by no longer answering control requests. + tuh_edpt_abort_xfer(self->device_address, self->endpoint); + self->streaming = false; + #if !CIRCUITPY_USB_HOST_ISO_RECORDS + self->aborted = true; + #endif + } + // Drop a completion that is queued already, so it queues nothing. + _seq++; + _lock_give(); +} + +uint32_t common_hal_usb_host_audio_usbin_record_to_buffer(usb_host_audio_usbin_obj_t *self, + uint8_t *buffer, uint32_t length) { + uint32_t frames = length / self->base.channel_count; + uint32_t done = 0; + // A full ring keeps the older audio, so what is waiting comes before any + // gap and is recorded too. + uint32_t last_audio = supervisor_ticks_ms32(); + while (done < frames) { + _lock_take(); + uint32_t take = MIN(frames - done, _ring_count(self)); + _ring_take(self, buffer + done * self->frame_bytes, take); + _lock_give(); + if (take > 0) { + done += take; + last_audio = supervisor_ticks_ms32(); + continue; + } + if (!common_hal_usb_host_audio_usbin_get_streaming(self) || mp_hal_is_interrupted() || + supervisor_ticks_ms32() - last_audio > USBIN_RECORD_TIMEOUT_MS) { + break; + } + // TinyUSB fills the ring, in the background tasks or in a task of its own. + RUN_BACKGROUND_TASKS; + } + return done * self->base.channel_count; +} + +uint8_t common_hal_usb_host_audio_usbin_get_bit_depth(usb_host_audio_usbin_obj_t *self) { + return self->bit_depth; +} + +bool common_hal_usb_host_audio_usbin_get_samples_signed(usb_host_audio_usbin_obj_t *self) { + return self->base.samples_signed; +} + +bool common_hal_usb_host_audio_usbin_get_streaming(usb_host_audio_usbin_obj_t *self) { + // Unplugging the device ends the transfer without a completion. (usb.core + // stops the stream itself before it closes the endpoint.) The endpoint + // isn't busy for a moment after each completion, until the callback queues + // the next transfer, which a callback in a task of its own may be doing + // right now, so that doesn't tell. + if (self->streaming && !tuh_mounted(self->device_address)) { + self->streaming = false; + } + return self->streaming; +} + +bool common_hal_usb_host_audio_usbin_get_overflow(usb_host_audio_usbin_obj_t *self) { + _lock_take(); + bool overflow = self->overflow; + self->overflow = false; + _lock_give(); + return overflow; +} + +void common_hal_usb_host_audio_usbin_reset_buffer(usb_host_audio_usbin_obj_t *self, + bool single_channel_output, uint8_t channel) { + (void)single_channel_output; + (void)channel; + if (common_hal_usb_host_audio_usbin_deinited(self)) { + return; + } + if (self->output_buffer == NULL) { + // The output backend's DMA may read this buffer directly. After the + // two halves there is room for the frames that _stretch() works from. + size_t size = self->base.max_buffer_length + (self->buffer_frames + 1) * self->frame_bytes; + self->output_buffer = port_malloc(size, true); + if (self->output_buffer == NULL) { + m_malloc_fail(size); + } + } + self->output_index = 0; + // Start on live audio rather than on what piled up while nothing played. + // Dropping that is not an overflow. + _lock_take(); + ringbuf_clear(&self->ring); + self->overflowed = false; + self->overflow = false; + _lock_give(); + self->primed = false; +} + +static void _fill_silence(usb_host_audio_usbin_obj_t *self, uint8_t *buffer, uint32_t bytes) { + if (self->base.samples_signed) { + memset(buffer, 0, bytes); + } else if (self->base.bits_per_sample == 8) { + memset(buffer, 0x80, bytes); + } else { + for (uint32_t i = 0; i < bytes; i += 2) { + buffer[i] = 0; + buffer[i + 1] = 0x80; + } + } +} + +// Make buffer_frames frames in out from the in_frames frames in in, by linear +// interpolation. The first and last frames are kept as they are, so that +// consecutive buffers still join up. +static void _stretch(usb_host_audio_usbin_obj_t *self, uint8_t *out, const uint8_t *in, uint32_t in_frames) { + const uint32_t channels = self->base.channel_count; + const uint32_t out_frames = self->buffer_frames; + // 16.16 fixed point position in the input + const uint32_t step = ((in_frames - 1) << 16) / (out_frames - 1); + const bool is_16 = self->base.bits_per_sample == 16; + const bool is_signed = self->base.samples_signed; + uint32_t pos = 0; + for (uint32_t i = 0; i < out_frames; i++, pos += step) { + uint32_t index = pos >> 16; + // 15 bits, so that its product with a difference of samples fits. + int32_t frac = (pos & 0xffff) >> 1; + if (i == out_frames - 1 || index >= in_frames - 1) { + index = in_frames - 1; + frac = 0; + } + for (uint32_t c = 0; c < channels; c++) { + uint32_t a_at = index * channels + c; + uint32_t b_at = frac ? a_at + channels : a_at; + uint32_t out_at = i * channels + c; + int32_t a, b; + if (is_16) { + // in and out are in output_buffer, which we allocated ourselves, + // at offsets of whole 16 bit frames, so they are aligned. + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wcast-align" + a = is_signed ? ((const int16_t *)in)[a_at] : ((const uint16_t *)in)[a_at]; + b = is_signed ? ((const int16_t *)in)[b_at] : ((const uint16_t *)in)[b_at]; + ((uint16_t *)out)[out_at] = a + (((b - a) * frac) >> 15); + #pragma GCC diagnostic pop + } else { + a = is_signed ? ((const int8_t *)in)[a_at] : in[a_at]; + b = is_signed ? ((const int8_t *)in)[b_at] : in[b_at]; + out[out_at] = a + (((b - a) * frac) >> 15); + } + } + } +} + +// Called by the output backend's refill, so it must never block. It waits for +// the lock at most while the completion callback stores one transfer. +audioio_get_buffer_result_t common_hal_usb_host_audio_usbin_get_buffer( + usb_host_audio_usbin_obj_t *self, bool single_channel_output, uint8_t channel, + uint8_t **buffer, uint32_t *buffer_length) { + if (common_hal_usb_host_audio_usbin_deinited(self) || self->output_buffer == NULL) { + *buffer = NULL; + *buffer_length = 0; + return GET_BUFFER_DONE; + } + uint8_t *out = self->output_buffer + self->output_half_bytes * self->output_index; + self->output_index = 1 - self->output_index; + + uint32_t target = self->buffer_frames * USBIN_TARGET_BUFFERS; + _lock_take(); + uint32_t count = _ring_count(self); + if (self->overflowed) { + // The consumer stalled or runs slower than the microphone. Skip ahead + // so that the latency stays bounded. + self->overflowed = false; + if (count > target) { + _ring_take(self, NULL, count - target); + count = target; + } + } + if (!self->primed && count >= target) { + self->primed = true; + self->level = count << USBIN_LEVEL_SHIFT; + self->drift = 0; + } + if (self->primed && count >= self->buffer_frames) { + // The microphone's clock and the consumer's drift apart, which shows + // as a slow change of how much audio is waiting. The count at any one + // call depends on when both sides were last serviced, so follow its + // average. Make a buffer from one frame more or less than it holds, the + // more often the further that average is from the target: the sum of + // the differences says when. That spreads the corrections evenly, + // where correcting only beyond a threshold would bunch them up into + // an audible wobble of the pitch. + self->level += (int32_t)count - (int32_t)(self->level >> USBIN_LEVEL_SHIFT); + const int32_t every = self->buffer_frames; + self->drift += (int32_t)(self->level >> USBIN_LEVEL_SHIFT) - (int32_t)target; + self->drift = MAX(-2 * every, MIN(2 * every, self->drift)); + uint32_t take = self->buffer_frames; + if (self->drift >= every && count > take) { + take++; + self->drift -= every; + } else if (self->drift <= -every) { + take--; + self->drift += every; + } + if (take == self->buffer_frames) { + _ring_take(self, out, take); + _lock_give(); + } else { + uint8_t *stretch = self->output_buffer + self->output_half_bytes * 2; + _ring_take(self, stretch, take); + _lock_give(); + _stretch(self, out, stretch, take); + } + } else { + _lock_give(); + // Play silence until enough audio is waiting again to ride out the + // jitter in how both sides are serviced. + self->primed = false; + _fill_silence(self, out, self->output_half_bytes); + } + + if (single_channel_output) { + out += (channel % self->base.channel_count) * (self->base.bits_per_sample / 8); + } + *buffer = out; + *buffer_length = self->output_half_bytes; + // A live microphone is an infinite stream; never report DONE or the backend stops. + return GET_BUFFER_MORE_DATA; +} diff --git a/shared-module/usb_host_audio/USBIn.h b/shared-module/usb_host_audio/USBIn.h new file mode 100644 index 00000000000..a1ab1092595 --- /dev/null +++ b/shared-module/usb_host_audio/USBIn.h @@ -0,0 +1,94 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" +#include "py/ringbuf.h" + +#include "shared-module/audiocore/__init__.h" +#include "shared-module/usb/core/Device.h" + +// The PCM ring holds this many get_buffer() buffers. Playback starts, and +// restarts after an underrun, once USBIN_TARGET_BUFFERS of them are waiting. +// The ring is what holds the stream while its consumer is held up. Where +// TinyUSB runs in a task of its own, packets keep arriving while the VM is +// held up by other work. A consumer that doesn't catch up afterwards, such as +// an audio output, is left with up to that much more latency, which drift +// correction then takes out slowly. +#ifndef USBIN_RING_BUFFERS +#if CIRCUITPY_USB_HOST_TASK +#define USBIN_RING_BUFFERS (32) +#else +#define USBIN_RING_BUFFERS (8) +#endif +#endif +#define USBIN_TARGET_BUFFERS (2) +#define USBIN_NO_INTERFACE (0xff) + +typedef struct { + // so USBIn can be used directly as an audiosample source. + audiosample_base_t base; + // Keeps the device object, which owns the open endpoint, alive. + usb_core_device_obj_t *device; + uint8_t device_address; + uint8_t endpoint; + // The streaming interface that has endpoint, or USBIN_NO_INTERFACE. + uint8_t interface; + uint8_t bit_depth; // on the wire; base.bits_per_sample is what we produce + uint8_t wire_frame_bytes; + uint8_t frame_bytes; + // A transfer is queued. False once the stream stopped + volatile bool streaming; + // Both buffers below are outside the VM heap; NULL xfer_buffer means deinited. + uint8_t *xfer_buffer; + uint16_t xfer_buffer_len; + // Converted PCM frames, whole ones only. Filled by the transfer's + // completion callback, which runs in tuh_task(), and drained by + // get_buffer(), record() and reset_buffer() on the VM. tuh_task() may be a + // task of its own (CIRCUITPY_USB_HOST_TASK), so the ring, overflowed and + // overflow are only used with the lock in USBIn.c held. The buffer is + // outside the VM heap. + ringbuf_t ring; + uint32_t buffer_frames; + bool primed; + // The ring was full and audio was dropped; get_buffer() skips ahead. + bool overflowed; + // Audio was dropped since the user last read the overflow property. + bool overflow; + // Average of the frames waiting as get_buffer() finds them, scaled by 2^USBIN_LEVEL_SHIFT. + uint32_t level; + // Sum of how far level was from the target, less what was corrected. + int32_t drift; + // Owned double-buffer returned to the output backend by get_buffer(), + // followed by scratch space for drift correction. Allocated lazily on the + // first reset_buffer() so record()-only use pays no extra RAM. + // base.max_buffer_length is the two halves; get_buffer() returns + // output_half_bytes of it. + uint8_t *output_buffer; + uint32_t output_half_bytes; + uint8_t output_index; + #if !CIRCUITPY_USB_HOST_ISO_RECORDS + // The host controller frame number when the last transfer was queued. + uint16_t queued_frame; + // Frames (microframes at high speed) between the endpoint's packets. + uint16_t frame_interval; + // queued_frame is set. + bool frame_known; + // A transfer was aborted. The host controller may write the transfer + // buffer until the end of the frame. + bool aborted; + // Transfers in a row that failed. + uint8_t failures; + #endif +} usb_host_audio_usbin_obj_t; + +// Stops a stream left running by the VM that just finished. +void usb_host_audio_reset(void); +// Stops receiving from the device before a control request changes or +// disables its endpoints. The object keeps the audio received so far. +// Never raises or allocates. +void usb_host_audio_stop_device(uint8_t device_address); diff --git a/shared-module/usb_host_audio/__init__.c b/shared-module/usb_host_audio/__init__.c new file mode 100644 index 00000000000..ae8f2b17d90 --- /dev/null +++ b/shared-module/usb_host_audio/__init__.c @@ -0,0 +1,7 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// Nothing here. The module's code is in USBIn.c. diff --git a/shared-module/usb_midi/__init__.c b/shared-module/usb_midi/__init__.c index 3808801ff7e..ae8d6a601cb 100644 --- a/shared-module/usb_midi/__init__.c +++ b/shared-module/usb_midi/__init__.c @@ -106,7 +106,7 @@ static const uint8_t usb_midi_descriptor_template[] = { 0xFF, // 66 bEndpointAddress (OUT/H2D) [SET AT RUNTIME] #define MIDI_STREAMING_OUT_ENDPOINT_INDEX (66) 0x02, // 67 bmAttributes (Bulk) - #if USB_HIGHSPEED + #if CIRCUITPY_USB_DEVICE_HIGH_SPEED == 1 0x00, 0x02, // 68,69 wMaxPacketSize (512) #else 0x40, 0x00, // 68,69 wMaxPacketSize (64) @@ -126,7 +126,7 @@ static const uint8_t usb_midi_descriptor_template[] = { 0xFF, // 78 bEndpointAddress (IN/D2H) [SET AT RUNTIME: 0x80 | number] #define MIDI_STREAMING_IN_ENDPOINT_INDEX (78) 0x02, // 79 bmAttributes (Bulk) - #if USB_HIGHSPEED + #if CIRCUITPY_USB_DEVICE_HIGH_SPEED == 1 0x00, 0x02, // 80, 81 wMaxPacketSize (512) #else 0x40, 0x00, // 80, 81 wMaxPacketSize (64) @@ -163,11 +163,6 @@ char *custom_usb_midi_in_jack_name = NULL; char *custom_usb_midi_out_jack_name = NULL; size_t usb_midi_add_descriptor(uint8_t *descriptor_buf, descriptor_counts_t *descriptor_counts, uint8_t *current_interface_string) { - const char *midi_streaming_interface_name; - const char *midi_audio_control_interface_name; - const char *midi_in_jack_name; - const char *midi_out_jack_name; - memcpy(descriptor_buf, usb_midi_descriptor_template, sizeof(usb_midi_descriptor_template)); descriptor_buf[MIDI_AUDIO_CONTROL_INTERFACE_NUMBER_INDEX] = descriptor_counts->current_interface; @@ -191,43 +186,19 @@ size_t usb_midi_add_descriptor(uint8_t *descriptor_buf, descriptor_counts_t *des descriptor_buf[MIDI_STREAMING_INTERFACE_NUMBER_INDEX_2] = descriptor_counts->current_interface; descriptor_counts->current_interface++; - if (custom_usb_midi_streaming_interface_name == NULL) { - midi_streaming_interface_name = USB_INTERFACE_NAME " MIDI"; - } else { - midi_streaming_interface_name = custom_usb_midi_streaming_interface_name; - } - - usb_add_interface_string(*current_interface_string, midi_streaming_interface_name); + usb_add_interface_name(*current_interface_string, custom_usb_midi_streaming_interface_name, "MIDI"); descriptor_buf[MIDI_STREAMING_INTERFACE_STRING_INDEX] = *current_interface_string; (*current_interface_string)++; - if (custom_usb_midi_audio_control_interface_name == NULL) { - midi_audio_control_interface_name = USB_INTERFACE_NAME " Audio"; - } else { - midi_audio_control_interface_name = custom_usb_midi_audio_control_interface_name; - } - - usb_add_interface_string(*current_interface_string, midi_audio_control_interface_name); + usb_add_interface_name(*current_interface_string, custom_usb_midi_audio_control_interface_name, "Audio"); descriptor_buf[MIDI_AUDIO_CONTROL_INTERFACE_STRING_INDEX] = *current_interface_string; (*current_interface_string)++; - if (custom_usb_midi_in_jack_name == NULL) { - midi_in_jack_name = USB_INTERFACE_NAME " usb_midi.ports[0]"; - } else { - midi_in_jack_name = custom_usb_midi_in_jack_name; - } - - usb_add_interface_string(*current_interface_string, midi_in_jack_name); + usb_add_interface_name(*current_interface_string, custom_usb_midi_in_jack_name, "usb_midi.ports[0]"); descriptor_buf[MIDI_IN_JACK_STRING_INDEX] = *current_interface_string; (*current_interface_string)++; - if (custom_usb_midi_out_jack_name == NULL) { - midi_out_jack_name = USB_INTERFACE_NAME " usb_midi.ports[0]"; - } else { - midi_out_jack_name = custom_usb_midi_out_jack_name; - } - - usb_add_interface_string(*current_interface_string, midi_out_jack_name); + usb_add_interface_name(*current_interface_string, custom_usb_midi_out_jack_name, "usb_midi.ports[0]"); descriptor_buf[MIDI_OUT_JACK_STRING_INDEX] = *current_interface_string; (*current_interface_string)++; diff --git a/shared-module/usb_video/USBFramebuffer.c b/shared-module/usb_video/USBFramebuffer.c index 6cbe137191c..e0bf016e125 100644 --- a/shared-module/usb_video/USBFramebuffer.c +++ b/shared-module/usb_video/USBFramebuffer.c @@ -22,6 +22,21 @@ void shared_module_usb_video_uvcframebuffer_refresh(usb_video_uvcframebuffer_obj shared_module_usb_video_swapbuffers(); } +void shared_module_usb_video_uvcframebuffer_swapbuffers(usb_video_uvcframebuffer_obj_t *self, const uint8_t *dirty_row_bitmap) { + shared_module_usb_video_swapbuffers_dirty(dirty_row_bitmap); +} + +void shared_module_usb_video_uvcframebuffer_set_frame_callback(usb_video_uvcframebuffer_obj_t *self, framebuffer_frame_callback_t cb, void *data) { + self->frame_cb = cb; + self->frame_cb_data = data; +} + +void shared_module_usb_video_uvcframebuffer_frame_boundary(usb_video_uvcframebuffer_obj_t *self) { + if (self->frame_cb != NULL) { + self->frame_cb(self->frame_cb_data); + } +} + int shared_module_usb_video_uvcframebuffer_get_width(usb_video_uvcframebuffer_obj_t *self) { return usb_video_frame_width; } diff --git a/shared-module/usb_video/USBFramebuffer.h b/shared-module/usb_video/USBFramebuffer.h index 0db85ac378c..398ea2b4710 100644 --- a/shared-module/usb_video/USBFramebuffer.h +++ b/shared-module/usb_video/USBFramebuffer.h @@ -8,6 +8,10 @@ #include "py/obj.h" +#include "shared-module/framebufferio/__init__.h" + typedef struct usb_video_uvcframebuffer_obj { mp_obj_base_t base; + framebuffer_frame_callback_t frame_cb; + void *frame_cb_data; } usb_video_uvcframebuffer_obj_t; diff --git a/shared-module/usb_video/__init__.c b/shared-module/usb_video/__init__.c index 241c9d768f8..e7e1bd574a7 100644 --- a/shared-module/usb_video/__init__.c +++ b/shared-module/usb_video/__init__.c @@ -9,26 +9,46 @@ #include "class/video/video_device.h" #include "shared-bindings/displayio/Bitmap.h" #include "shared-bindings/usb_video/__init__.h" +#include "shared-bindings/usb_video/USBFramebuffer.h" #include "shared-module/bitmapfilter/macros.h" #include "shared-module/usb_video/__init__.h" #include "shared-module/usb_video/uvc_usb_descriptors.h" +#if CIRCUITPY_DISPLAYIO_LVGL +#include "shared-module/displayio/lvgl/lvgl_internal.h" +#endif #include "supervisor/background_callback.h" #include "supervisor/shared/tick.h" #include "device/usbd.h" +// High-speed bulk endpoints must advertise 512-byte packets. The UVC payload +// buffer size is independent: a payload smaller than this is a short packet. +#if CIRCUITPY_USB_DEVICE_HIGH_SPEED == 1 +#define USB_VIDEO_BULK_PACKET_SIZE 512 +#else +#define USB_VIDEO_BULK_PACKET_SIZE 64 +#endif + static bool do_convert = true; static unsigned frame_num = 0; static unsigned tx_busy = 0; static unsigned interval_ms = 1000 / DEFAULT_FRAME_RATE; +// Rows of the RGB565 framebuffer that changed since the last UVC frame was converted. The +// display's flush tells us which rows it wrote, so only those rows need the RGB565 -> YUYV +// conversion; the rest of the YUYV buffer still holds the previous frame. +static uint8_t *dirty_rows; +static size_t dirty_rows_size; +static bool convert_all = true; + // TODO must dynamically allocate this, otherwise everyone pays for it static uint8_t *frame_buffer_yuyv; uint16_t *usb_video_framebuffer_rgb565; static bool usb_video_is_enabled = false; uint16_t usb_video_frame_width, usb_video_frame_height; +static mp_int_t usb_video_frame_rate = DEFAULT_FRAME_RATE; -bool shared_module_usb_video_enable(mp_int_t frame_width, mp_int_t frame_height) { +bool shared_module_usb_video_enable(mp_int_t frame_width, mp_int_t frame_height, mp_int_t frame_rate) { if (tud_connected()) { return false; } @@ -43,6 +63,8 @@ bool shared_module_usb_video_enable(mp_int_t frame_width, mp_int_t frame_height) usb_video_frame_width = frame_width; usb_video_frame_height = frame_height; + usb_video_frame_rate = frame_rate; + interval_ms = 1000 / frame_rate; size_t framebuffer_size = usb_video_frame_width * usb_video_frame_height * 2; frame_buffer_yuyv = port_malloc(framebuffer_size, false); @@ -58,6 +80,14 @@ bool shared_module_usb_video_enable(mp_int_t frame_width, mp_int_t frame_height) memset(frame_buffer_yuyv, 0, framebuffer_size); memset(usb_video_framebuffer_rgb565, 0, framebuffer_size); + dirty_rows_size = (usb_video_frame_height + 7) / 8; + dirty_rows = port_malloc(dirty_rows_size, false); + if (dirty_rows != NULL) { + memset(dirty_rows, 0, dirty_rows_size); + } + convert_all = true; + do_convert = true; + usb_video_is_enabled = true; return true; @@ -70,8 +100,12 @@ bool shared_module_usb_video_disable(void) { usb_video_is_enabled = false; port_free(frame_buffer_yuyv); port_free(usb_video_framebuffer_rgb565); + port_free(dirty_rows); frame_buffer_yuyv = NULL; usb_video_framebuffer_rgb565 = NULL; + dirty_rows = NULL; + dirty_rows_size = 0; + convert_all = true; return true; } @@ -81,22 +115,17 @@ bool usb_video_enabled(void) { size_t usb_video_descriptor_length(void) { #if CFG_TUD_VIDEO_STREAMING_BULK - return sizeof((char[]) {TUD_VIDEO_CAPTURE_DESCRIPTOR_UNCOMPR_BULK(0, 0, DEFAULT_FRAME_WIDTH, DEFAULT_FRAME_HEIGHT, DEFAULT_FRAME_RATE, CFG_TUD_VIDEO_STREAMING_EP_BUFSIZE, 0, 0)}); + return sizeof((char[]) {TUD_VIDEO_CAPTURE_DESCRIPTOR_UNCOMPR_BULK(0, 0, DEFAULT_FRAME_WIDTH, DEFAULT_FRAME_HEIGHT, usb_video_frame_rate, USB_VIDEO_BULK_PACKET_SIZE, 0, 0)}); #else - return sizeof((char[]) {TUD_VIDEO_CAPTURE_DESCRIPTOR_UNCOMPR(0, 0, DEFAULT_FRAME_WIDTH, DEFAULT_FRAME_HEIGHT, DEFAULT_FRAME_RATE, 64, 0, 0)}); + return sizeof((char[]) {TUD_VIDEO_CAPTURE_DESCRIPTOR_UNCOMPR(0, 0, DEFAULT_FRAME_WIDTH, DEFAULT_FRAME_HEIGHT, usb_video_frame_rate, CFG_TUD_VIDEO_STREAMING_EP_BUFSIZE, 0, 0)}); #endif } -static void convert_framebuffer_maybe(void) { - if (!do_convert) { - return; // new data not ready yet - } - do_convert = false; // assumes this happens via background, not interrupt - - uint8_t *dest = frame_buffer_yuyv; - uint16_t *src = usb_video_framebuffer_rgb565; +static void convert_row(uint16_t y) { + uint8_t *dest = frame_buffer_yuyv + (size_t)y * usb_video_frame_width * 2; + uint16_t *src = usb_video_framebuffer_rgb565 + (size_t)y * usb_video_frame_width; - for (int i = 0; i < usb_video_frame_width * usb_video_frame_height / 2; i++) { + for (int x = 0; x < usb_video_frame_width; x += 2) { uint16_t p1 = IMAGE_GET_RGB565_PIXEL_FAST(src, 0); uint16_t p2 = IMAGE_GET_RGB565_PIXEL_FAST(src, 1); src += 2; @@ -116,24 +145,85 @@ static void convert_framebuffer_maybe(void) { } } +static void convert_framebuffer_maybe(void) { + if (!do_convert) { + return; // new data not ready yet + } + do_convert = false; // assumes this happens via background, not interrupt + + if (convert_all || dirty_rows == NULL) { + for (uint16_t y = 0; y < usb_video_frame_height; y++) { + convert_row(y); + } + convert_all = false; + if (dirty_rows != NULL) { + memset(dirty_rows, 0, dirty_rows_size); + } + return; + } + + for (uint16_t y = 0; y < usb_video_frame_height; y++) { + uint8_t bit = 1 << (y & 7); + if (dirty_rows[y >> 3] & bit) { + convert_row(y); + dirty_rows[y >> 3] &= ~bit; + } + } +} + +// Under LVGL the framebuffer can be flushed by the port's render task while the UVC background +// callback converts it. Both paths take the displayio LVGL lock, so the dirty rows this reads are +// not being changed and the pixels it copies are not being rewritten. Without LVGL every step is +// on the CircuitPython thread already. +static void convert_framebuffer_locked(void) { + #if CIRCUITPY_DISPLAYIO_LVGL + displayio_lvgl_lock(); + convert_framebuffer_maybe(); + displayio_lvgl_unlock(); + #else + convert_framebuffer_maybe(); + #endif +} + +// The frame boundary is the UVC frame rate. A FramebufferDisplay pacing itself off this callback +// renders the latest display state before the rows are converted, so the frame on the wire +// matches the framebuffer. +static void usb_video_frame_boundary(void) { + shared_module_usb_video_uvcframebuffer_frame_boundary(&usb_video_uvcframebuffer_singleton_obj); +} + void shared_module_usb_video_swapbuffers(void) { + convert_all = true; + do_convert = true; +} + +void shared_module_usb_video_swapbuffers_dirty(const uint8_t *dirty_row_bitmap) { + // Under LVGL this is called from the display flush path, which holds the displayio LVGL lock + // against convert_framebuffer_locked(). + if (dirty_row_bitmap == NULL || dirty_rows == NULL) { + convert_all = true; + } else { + for (size_t i = 0; i < dirty_rows_size; i++) { + dirty_rows[i] |= dirty_row_bitmap[i]; + } + } do_convert = true; } size_t usb_video_add_descriptor(uint8_t *descriptor_buf, descriptor_counts_t *descriptor_counts, uint8_t *current_interface_string) { - usb_add_interface_string(*current_interface_string, "CircuitPython UVC"); + usb_add_interface_name(*current_interface_string, NULL, "UVC"); const uint8_t usb_video_descriptor[] = { #if CFG_TUD_VIDEO_STREAMING_BULK - TUD_VIDEO_CAPTURE_DESCRIPTOR_UNCOMPR_BULK(*current_interface_string, descriptor_counts->current_endpoint | 0x80, usb_video_frame_width, usb_video_frame_height, DEFAULT_FRAME_RATE, 64, descriptor_counts->current_interface, descriptor_counts->current_interface + 1) + TUD_VIDEO_CAPTURE_DESCRIPTOR_UNCOMPR_BULK(*current_interface_string, descriptor_counts->current_endpoint | 0x80, usb_video_frame_width, usb_video_frame_height, usb_video_frame_rate, USB_VIDEO_BULK_PACKET_SIZE, descriptor_counts->current_interface, descriptor_counts->current_interface + 1) #else - TUD_VIDEO_CAPTURE_DESCRIPTOR_UNCOMPR(*current_interface_string, descriptor_counts->current_endpoint | 0x80, usb_video_frame_width, usb_video_frame_height, DEFAULT_FRAME_RATE, CFG_TUD_VIDEO_STREAMING_EP_BUFSIZE, descriptor_counts->current_interface, descriptor_counts->current_interface + 1) + TUD_VIDEO_CAPTURE_DESCRIPTOR_UNCOMPR(*current_interface_string, descriptor_counts->current_endpoint | 0x80, usb_video_frame_width, usb_video_frame_height, usb_video_frame_rate, CFG_TUD_VIDEO_STREAMING_EP_BUFSIZE, descriptor_counts->current_interface, descriptor_counts->current_interface + 1) #endif }; (*current_interface_string)++; + // UVC has two interfaces: video control and video streaming. descriptor_counts->current_interface += 2; descriptor_counts->num_in_endpoints++; descriptor_counts->current_endpoint++; - descriptor_counts->current_interface++; memcpy(descriptor_buf, usb_video_descriptor, sizeof(usb_video_descriptor)); @@ -157,9 +247,12 @@ static void usb_video_cb_fun(void *unused) { if (!already_sent) { already_sent = 1; start_ms = supervisor_ticks_ms32(); - convert_framebuffer_maybe(); + usb_video_frame_boundary(); + convert_framebuffer_locked(); bool result = tud_video_n_frame_xfer(0, 0, (void *)frame_buffer_yuyv, usb_video_frame_width * usb_video_frame_height * 16 / 8); - (void)result; + if (result) { + tx_busy = 1; + } } unsigned cur = supervisor_ticks_ms32(); @@ -171,11 +264,17 @@ static void usb_video_cb_fun(void *unused) { background_callback_add(&usb_video_cb, usb_video_cb_fun, NULL); // re-queue return; } - start_ms += interval_ms; - - convert_framebuffer_maybe(); + usb_video_frame_boundary(); + convert_framebuffer_locked(); bool result = tud_video_n_frame_xfer(0, 0, (void *)frame_buffer_yuyv, usb_video_frame_width * usb_video_frame_height * 16 / 8); - (void)result; + if (result) { + tx_busy = 1; + start_ms += interval_ms; + } else { + // No completion callback will arrive when the transfer wasn't queued, so keep the + // background callback alive and try again. + background_callback_add(&usb_video_cb, usb_video_cb_fun, NULL); + } } diff --git a/shared-module/usb_video/uvc_usb_descriptors.h b/shared-module/usb_video/uvc_usb_descriptors.h index ad9e5470cdc..0f4c04d810b 100644 --- a/shared-module/usb_video/uvc_usb_descriptors.h +++ b/shared-module/usb_video/uvc_usb_descriptors.h @@ -17,7 +17,7 @@ #define DEFAULT_FRAME_WIDTH 128 #define DEFAULT_FRAME_HEIGHT 96 -#define DEFAULT_FRAME_RATE 10 +#define DEFAULT_FRAME_RATE 15 #define TUD_VIDEO_CAPTURE_DESC_UNCOMPR_LEN ( \ TUD_VIDEO_DESC_IAD_LEN \ diff --git a/shared-module/vectorio/Circle.c b/shared-module/vectorio/Circle.c index 6f7ee2f3406..91cbe91b2a6 100644 --- a/shared-module/vectorio/Circle.c +++ b/shared-module/vectorio/Circle.c @@ -12,10 +12,12 @@ #include "stdlib.h" -void common_hal_vectorio_circle_construct(vectorio_circle_t *self, uint16_t radius, uint16_t color_index) { +void common_hal_vectorio_circle_construct(vectorio_circle_t *self, uint16_t radius, uint16_t color_index, uint16_t outline_width, int32_t outline_color_index) { self->radius = radius; self->on_dirty.obj = NULL; self->color_index = color_index + 1; + self->outline_width = outline_width; + self->outline_color_index = outline_color_index < 0 ? 0 : outline_color_index + 1; } void common_hal_vectorio_circle_set_on_dirty(vectorio_circle_t *self, vectorio_event_t on_dirty) { @@ -26,22 +28,33 @@ void common_hal_vectorio_circle_set_on_dirty(vectorio_circle_t *self, vectorio_e } -uint32_t common_hal_vectorio_circle_get_pixel(void *obj, int16_t x, int16_t y) { - vectorio_circle_t *self = obj; - int16_t radius = self->radius; - x = abs(x); - y = abs(y); +// Coverage of a circle of the given radius, for a point x/y pixels right of and below its +// center. (x + y <= radius) implies x*x + y*y <= radius*radius, which keeps the pixels nearest +// the center from paying for the multiplication. +static bool circle_covers(int32_t x, int32_t y, int32_t radius) { + x = x < 0 ? -x : x; + y = y < 0 ? -y : y; if (x + y <= radius) { - return self->color_index; + return true; } - if (x > radius) { - return 0; + if (x > radius || y > radius) { + return false; } - if (y > radius) { + return x * x + y * y <= radius * radius; +} + +uint32_t common_hal_vectorio_circle_get_pixel(void *obj, int16_t x, int16_t y) { + vectorio_circle_t *self = obj; + int32_t radius = self->radius; + if (!circle_covers(x, y, radius)) { return 0; } - const bool pythagorasSmallerThanRadius = (int32_t)x * x + (int32_t)y * y <= (int32_t)radius * radius; - return pythagorasSmallerThanRadius ? self->color_index : 0; + // A zero outline_color_index means no outline was set, and then the fill reaches the edge. + if (self->outline_width > 0 && self->outline_color_index != 0 && + !circle_covers(x, y, radius - self->outline_width)) { + return self->outline_color_index; + } + return self->color_index; } @@ -66,6 +79,19 @@ void common_hal_vectorio_circle_set_radius(void *obj, int16_t radius) { } } +uint16_t common_hal_vectorio_circle_get_outline_width(void *obj) { + vectorio_circle_t *self = obj; + return self->outline_width; +} + +void common_hal_vectorio_circle_set_outline_width(void *obj, uint16_t outline_width) { + vectorio_circle_t *self = obj; + self->outline_width = outline_width; + if (self->on_dirty.obj != NULL) { + self->on_dirty.event(self->on_dirty.obj); + } +} + uint16_t common_hal_vectorio_circle_get_color_index(void *obj) { vectorio_circle_t *self = obj; return self->color_index - 1; @@ -79,6 +105,19 @@ void common_hal_vectorio_circle_set_color_index(void *obj, uint16_t color_index) } } +int32_t common_hal_vectorio_circle_get_outline_color_index(void *obj) { + vectorio_circle_t *self = obj; + return self->outline_color_index == 0 ? -1 : self->outline_color_index - 1; +} + +void common_hal_vectorio_circle_set_outline_color_index(void *obj, int32_t outline_color_index) { + vectorio_circle_t *self = obj; + self->outline_color_index = outline_color_index < 0 ? 0 : outline_color_index + 1; + if (self->on_dirty.obj != NULL) { + self->on_dirty.event(self->on_dirty.obj); + } +} + mp_obj_t common_hal_vectorio_circle_get_draw_protocol(void *circle) { vectorio_circle_t *self = circle; return self->draw_protocol_instance; diff --git a/shared-module/vectorio/Circle.h b/shared-module/vectorio/Circle.h index 48d20b28d5c..561361dd0ab 100644 --- a/shared-module/vectorio/Circle.h +++ b/shared-module/vectorio/Circle.h @@ -16,6 +16,11 @@ typedef struct { mp_obj_base_t base; uint16_t radius; uint16_t color_index; + // The outline is a ring inside the circle's outer edge, so it changes the circle's + // appearance but not its footprint. outline_color_index is biased by one like + // color_index, so that 0 can mean "no outline" as well as "not covered". + uint16_t outline_width; + uint16_t outline_color_index; vectorio_event_t on_dirty; mp_obj_t draw_protocol_instance; } vectorio_circle_t; diff --git a/shared-module/vectorio/Polygon.c b/shared-module/vectorio/Polygon.c index 212d519e298..03a6160f930 100644 --- a/shared-module/vectorio/Polygon.c +++ b/shared-module/vectorio/Polygon.c @@ -161,11 +161,12 @@ uint32_t common_hal_vectorio_polygon_get_pixel(void *obj, int16_t x, int16_t y) int16_t winding_number = 0; int16_t x1 = self->points_list[0]; int16_t y1 = self->points_list[1]; - for (uint16_t i = 2; i <= self->len + 1; ++i) { + for (uint16_t i = 2; i <= self->len; i += 2) { VECTORIO_POLYGON_DEBUG(" {(%3d, %3d),", x1, y1); - int16_t x2 = self->points_list[i % self->len]; - ++i; - int16_t y2 = self->points_list[i % self->len]; + // The last edge closes the polygon back to the first point. + uint16_t next = i == self->len ? 0 : i; + int16_t x2 = self->points_list[next]; + int16_t y2 = self->points_list[next + 1]; VECTORIO_POLYGON_DEBUG(" (%3d, %3d)}\n", x2, y2); if (y1 <= y) { if (y2 > y && line_side(x1, y1, x2, y2, x, y) < 0) { diff --git a/shared-module/vectorio/Rectangle.c b/shared-module/vectorio/Rectangle.c index 42cdf7cca96..145af405780 100644 --- a/shared-module/vectorio/Rectangle.c +++ b/shared-module/vectorio/Rectangle.c @@ -12,10 +12,15 @@ #include "stdlib.h" -void common_hal_vectorio_rectangle_construct(vectorio_rectangle_t *self, uint32_t width, uint32_t height, uint16_t color_index) { +void common_hal_vectorio_rectangle_construct(vectorio_rectangle_t *self, uint32_t width, uint32_t height, uint16_t color_index, uint16_t radius, uint16_t outline_width, int32_t outline_color_index) { self->width = width; self->height = height; self->color_index = color_index + 1; + self->radius = radius; + self->outline_width = outline_width; + self->outline_color_index = outline_color_index < 0 ? 0 : outline_color_index + 1; + // set_on_dirty() uses this to detect a second parent, so it has to start empty. + self->on_dirty.obj = NULL; } void common_hal_vectorio_rectangle_set_on_dirty(vectorio_rectangle_t *self, vectorio_event_t on_dirty) { @@ -25,12 +30,60 @@ void common_hal_vectorio_rectangle_set_on_dirty(vectorio_rectangle_t *self, vect self->on_dirty = on_dirty; } +// Coverage of a rounded rectangle of the given extent whose top left pixel is (0, 0). The +// corner arcs are centered one radius in from each corner, which is the same center +// display_shapes' midpoint circle uses, so swapping implementations moves few pixels. +// +// Distances are doubled so that pixel centers land on integers instead of half pixels. +// The bindings ensure that `radius` is at most half of the shortest side. +static bool rectangle_covers(int32_t x, int32_t y, uint16_t width, uint16_t height, uint16_t radius) { + if (x < 0 || y < 0 || x >= (int32_t)width || y >= (int32_t)height) { + return false; + } + if (radius == 0) { + return true; + } + // 2x+1 is twice the pixel's center, so these are the distances from the nearest corner + // arc's center in halves of a pixel. 0 means the pixel is on one of the flat sides. + int32_t twice_radius = 2 * (int32_t)radius; + int32_t twice_x = 2 * x + 1; + int32_t twice_y = 2 * y + 1; + int32_t dx = 0; + int32_t dy = 0; + if (twice_x < twice_radius) { + dx = twice_radius - twice_x; + } else if (twice_x > 2 * (int32_t)width - twice_radius) { + dx = twice_x - (2 * (int32_t)width - twice_radius); + } + if (twice_y < twice_radius) { + dy = twice_radius - twice_y; + } else if (twice_y > 2 * (int32_t)height - twice_radius) { + dy = twice_y - (2 * (int32_t)height - twice_radius); + } + if (dx == 0 || dy == 0) { + return true; + } + return (int64_t)dx * dx + (int64_t)dy * dy <= (int64_t)twice_radius * twice_radius; +} + uint32_t common_hal_vectorio_rectangle_get_pixel(void *obj, int16_t x, int16_t y) { vectorio_rectangle_t *self = obj; - if (x >= 0 && y >= 0 && x < self->width && y < self->height) { - return self->color_index; + uint16_t radius = self->radius; + if (!rectangle_covers(x, y, self->width, self->height, radius)) { + return 0; + } + uint16_t outline_width = self->outline_width; + // A zero outline_color_index means no outline was set, and then the fill reaches the edge. + if (outline_width > 0 && self->outline_color_index != 0) { + // The outline is the band between the outer edge and a copy of the rectangle inset by + // the outline width. Inset corners stay concentric, so the inner radius shrinks too. + uint16_t inner_radius = radius > outline_width ? radius - outline_width : 0; + if (!rectangle_covers(x - outline_width, y - outline_width, + self->width - 2 * outline_width, self->height - 2 * outline_width, inner_radius)) { + return self->outline_color_index; + } } - return 0; + return self->color_index; } @@ -74,6 +127,32 @@ void common_hal_vectorio_rectangle_set_height(void *obj, int16_t height) { } } +uint16_t common_hal_vectorio_rectangle_get_radius(void *obj) { + vectorio_rectangle_t *self = obj; + return self->radius; +} + +void common_hal_vectorio_rectangle_set_radius(void *obj, uint16_t radius) { + vectorio_rectangle_t *self = obj; + self->radius = radius; + if (self->on_dirty.obj != NULL) { + self->on_dirty.event(self->on_dirty.obj); + } +} + +uint16_t common_hal_vectorio_rectangle_get_outline_width(void *obj) { + vectorio_rectangle_t *self = obj; + return self->outline_width; +} + +void common_hal_vectorio_rectangle_set_outline_width(void *obj, uint16_t outline_width) { + vectorio_rectangle_t *self = obj; + self->outline_width = outline_width; + if (self->on_dirty.obj != NULL) { + self->on_dirty.event(self->on_dirty.obj); + } +} + uint16_t common_hal_vectorio_rectangle_get_color_index(void *obj) { vectorio_rectangle_t *self = obj; return self->color_index - 1; @@ -86,3 +165,16 @@ void common_hal_vectorio_rectangle_set_color_index(void *obj, uint16_t color_ind self->on_dirty.event(self->on_dirty.obj); } } + +int32_t common_hal_vectorio_rectangle_get_outline_color_index(void *obj) { + vectorio_rectangle_t *self = obj; + return self->outline_color_index == 0 ? -1 : self->outline_color_index - 1; +} + +void common_hal_vectorio_rectangle_set_outline_color_index(void *obj, int32_t outline_color_index) { + vectorio_rectangle_t *self = obj; + self->outline_color_index = outline_color_index < 0 ? 0 : outline_color_index + 1; + if (self->on_dirty.obj != NULL) { + self->on_dirty.event(self->on_dirty.obj); + } +} diff --git a/shared-module/vectorio/Rectangle.h b/shared-module/vectorio/Rectangle.h index 6733f74d170..e989a94fc95 100644 --- a/shared-module/vectorio/Rectangle.h +++ b/shared-module/vectorio/Rectangle.h @@ -16,6 +16,16 @@ typedef struct { uint16_t width; uint16_t height; uint16_t color_index; + // The corner radius and the outline width are in the rectangle's own pixels, and neither + // may exceed half of the shortest side. The outline is drawn inside the rectangle's + // bounds, so neither one changes the rectangle's footprint. + // + // outline_color_index is biased by one like color_index, so that 0 can mean "no outline" + // as well as "not covered" (see VectorShape.h). A radius or outline width change is a + // pure appearance change: the coverage stays inside the same bounds. + uint16_t radius; + uint16_t outline_width; + uint16_t outline_color_index; vectorio_event_t on_dirty; mp_obj_t draw_protocol_instance; } vectorio_rectangle_t; diff --git a/shared-module/vectorio/VectorShape.c b/shared-module/vectorio/VectorShape.c deleted file mode 100644 index 75e1de8b960..00000000000 --- a/shared-module/vectorio/VectorShape.c +++ /dev/null @@ -1,557 +0,0 @@ -// This file is part of the CircuitPython project: https://circuitpython.org -// -// SPDX-FileCopyrightText: Copyright (c) 2020 by kvc0/WarriorOfWire -// -// SPDX-License-Identifier: MIT - -#include "stdlib.h" - -#include "shared-module/vectorio/__init__.h" -#include "shared-bindings/vectorio/VectorShape.h" - -#include "py/misc.h" -#include "py/runtime.h" -#include "shared-bindings/time/__init__.h" -#include "shared-bindings/displayio/ColorConverter.h" -#include "shared-bindings/displayio/Palette.h" - -#include "shared-bindings/vectorio/Circle.h" -#include "shared-bindings/vectorio/Polygon.h" -#include "shared-bindings/vectorio/Rectangle.h" - -// Lifecycle actions. -#define VECTORIO_SHAPE_DEBUG(...) (void)0 -// #define VECTORIO_SHAPE_DEBUG(...) mp_printf(&mp_plat_print, __VA_ARGS__) - - -// Used in both logging and ifdefs, for extra variables -// #define VECTORIO_PERF(...) mp_printf(&mp_plat_print, __VA_ARGS__) - - -// Really verbose. -#define VECTORIO_SHAPE_PIXEL_DEBUG(...) (void)0 -// #define VECTORIO_SHAPE_PIXEL_DEBUG(...) mp_printf(&mp_plat_print, __VA_ARGS__) - -#define U32_TO_BINARY_FMT "%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c" -#define U32_TO_BINARY(u32) \ - (u32 & 0x80000000 ? '1' : '0'), \ - (u32 & 0x40000000 ? '1' : '0'), \ - (u32 & 0x20000000 ? '1' : '0'), \ - (u32 & 0x10000000 ? '1' : '0'), \ - (u32 & 0x8000000 ? '1' : '0'), \ - (u32 & 0x4000000 ? '1' : '0'), \ - (u32 & 0x2000000 ? '1' : '0'), \ - (u32 & 0x1000000 ? '1' : '0'), \ - (u32 & 0x800000 ? '1' : '0'), \ - (u32 & 0x400000 ? '1' : '0'), \ - (u32 & 0x200000 ? '1' : '0'), \ - (u32 & 0x100000 ? '1' : '0'), \ - (u32 & 0x80000 ? '1' : '0'), \ - (u32 & 0x40000 ? '1' : '0'), \ - (u32 & 0x20000 ? '1' : '0'), \ - (u32 & 0x10000 ? '1' : '0'), \ - (u32 & 0x8000 ? '1' : '0'), \ - (u32 & 0x4000 ? '1' : '0'), \ - (u32 & 0x2000 ? '1' : '0'), \ - (u32 & 0x1000 ? '1' : '0'), \ - (u32 & 0x800 ? '1' : '0'), \ - (u32 & 0x400 ? '1' : '0'), \ - (u32 & 0x200 ? '1' : '0'), \ - (u32 & 0x100 ? '1' : '0'), \ - (u32 & 0x80 ? '1' : '0'), \ - (u32 & 0x40 ? '1' : '0'), \ - (u32 & 0x20 ? '1' : '0'), \ - (u32 & 0x10 ? '1' : '0'), \ - (u32 & 0x8 ? '1' : '0'), \ - (u32 & 0x4 ? '1' : '0'), \ - (u32 & 0x2 ? '1' : '0'), \ - (u32 & 0x1 ? '1' : '0') - -static void short_bound_check(mp_int_t i, qstr name) { - mp_arg_validate_int_range(i, SHRT_MIN, SHRT_MAX, name); -} - -inline __attribute__((always_inline)) -static void area_transpose(displayio_area_t *to_transpose) { - int16_t swap = to_transpose->y1; - to_transpose->y1 = to_transpose->x1; - to_transpose->x1 = swap; - swap = to_transpose->y2; - to_transpose->y2 = to_transpose->x2; - to_transpose->x2 = swap; -} - -inline __attribute__((always_inline)) -static void _get_screen_area(vectorio_vector_shape_t *self, displayio_area_t *out_area) { - VECTORIO_SHAPE_DEBUG("%p get_screen_area (%3d,%3d) tform:{x:%d y:%d dx:%d dy:%d scl:%d w:%d h:%d mx:%d my:%d tr:%d}", self, self->x, self->y, - 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); - - int16_t x; - int16_t y; - if (self->absolute_transform->transpose_xy) { - x = self->absolute_transform->x + self->absolute_transform->dx * self->y; - y = self->absolute_transform->y + self->absolute_transform->dy * self->x; - if (self->absolute_transform->dx < 1) { - x -= 1; - out_area->y1 = out_area->y1 * -1 + 1; - out_area->y2 = out_area->y2 * -1 + 1; - } - if (self->absolute_transform->dy < 1) { - y -= 1; - out_area->x1 = out_area->x1 * -1 + 1; - out_area->x2 = out_area->x2 * -1 + 1; - } - area_transpose(out_area); - } else { - x = self->absolute_transform->x + self->absolute_transform->dx * self->x; - y = self->absolute_transform->y + self->absolute_transform->dy * self->y; - - if (self->absolute_transform->dx < 1) { - x -= 1; - out_area->x1 = out_area->x1 * -1 + 1; - out_area->x2 = out_area->x2 * -1 + 1; - } - if (self->absolute_transform->dy < 1) { - y -= 1; - out_area->y1 = out_area->y1 * -1 + 1; - out_area->y2 = out_area->y2 * -1 + 1; - } - } - displayio_area_canon(out_area); - displayio_area_shift(out_area, x, y); - - VECTORIO_SHAPE_DEBUG(" out:{(%5d,%5d), (%5d,%5d)}\n", out_area->x1, out_area->y1, out_area->x2, out_area->y2); -} - -// Get the target pixel based on the shape's coordinate space -static void screen_to_shape_coordinates(vectorio_vector_shape_t *self, uint16_t x, uint16_t y, int16_t *out_shape_x, int16_t *out_shape_y) { - if (self->absolute_transform->transpose_xy) { - *out_shape_x = y - self->absolute_transform->y - self->absolute_transform->dy * self->x; - *out_shape_y = x - self->absolute_transform->x - self->absolute_transform->dx * self->y; - - VECTORIO_SHAPE_PIXEL_DEBUG(" a(%3d, %3d)", *out_shape_x, *out_shape_y); - if (self->absolute_transform->dx < 1) { - *out_shape_y *= -1; - *out_shape_y -= 1; - } - if (self->absolute_transform->dy < 1) { - *out_shape_x *= -1; - *out_shape_x -= 1; - } - } else { - *out_shape_x = x - self->absolute_transform->x - self->absolute_transform->dx * self->x; - *out_shape_y = y - self->absolute_transform->y - self->absolute_transform->dy * self->y; - - VECTORIO_SHAPE_PIXEL_DEBUG(" a(%3d, %3d)", *out_shape_x, *out_shape_y); - if (self->absolute_transform->dx < 1) { - *out_shape_x *= -1; - *out_shape_x -= 1; - } - if (self->absolute_transform->dy < 1) { - *out_shape_y *= -1; - *out_shape_y -= 1; - } - // It's mirrored via dx. Maybe we need to add support for also separately mirroring? - // if (self->absolute_transform->mirror_x) { - // pixel_to_get_x = (shape_area.x2 - shape_area.x1) - (pixel_to_get_x - shape_area.x1) + shape_area.x1 - 1; - // } - // if (self->absolute_transform->mirror_y) { - // pixel_to_get_y = (shape_area.y2 - shape_area.y1) - (pixel_to_get_y - shape_area.y1) + +shape_area.y1 - 1; - // } - } - VECTORIO_SHAPE_PIXEL_DEBUG(" b(%3d, %3d)", *out_shape_x, *out_shape_y); -} - -static void check_bounds_and_set_x(vectorio_vector_shape_t *self, mp_int_t x) { - short_bound_check(x, MP_QSTR_x); - self->x = x; -} - -static void check_bounds_and_set_y(vectorio_vector_shape_t *self, mp_int_t y) { - short_bound_check(y, MP_QSTR_y); - self->y = y; -} - - -// For use by Group to know where it needs to redraw on layer removal. -bool vectorio_vector_shape_get_dirty_area(vectorio_vector_shape_t *self, displayio_area_t *out_area) { - out_area->x1 = out_area->x2; - displayio_area_union( - &self->ephemeral_dirty_area, - &self->current_area, - out_area - ); - return true; // For now just always redraw. -} - - -// This must be invoked after each time a shape changes its position, shape or appearance in any way. -void common_hal_vectorio_vector_shape_set_dirty(void *vector_shape) { - vectorio_vector_shape_t *self = vector_shape; - // In screen space. Need to offset the shape space. - displayio_area_t current_area; - _get_screen_area(self, ¤t_area); - VECTORIO_SHAPE_DEBUG("%p shape_dirty new:{(%3d,%3d), (%3d,%3d)} dirty:{(%3d,%3d), (%3d,%3d)}", - self, - current_area.x1, current_area.y1, current_area.x2, current_area.y2, - self->ephemeral_dirty_area.x1, self->ephemeral_dirty_area.y1, self->ephemeral_dirty_area.x2, self->ephemeral_dirty_area.y2); - - bool moved = !displayio_area_equal(¤t_area, &self->current_area); - if (moved) { - displayio_area_union(&self->current_area, &self->ephemeral_dirty_area, &self->ephemeral_dirty_area); - VECTORIO_SHAPE_DEBUG(" stale:{(%3d,%3d), (%3d,%3d)} -> expanded:{(%3d,%3d), (%3d,%3d)}\n", - self->current_area.x1, self->current_area.y1, self->current_area.x2, self->current_area.y2, - self->ephemeral_dirty_area.x1, self->ephemeral_dirty_area.y1, self->ephemeral_dirty_area.x2, self->ephemeral_dirty_area.y2); - - // Dirty area tracks the shape's footprint between draws. It's reset on refresh finish. - displayio_area_copy(¤t_area, &self->current_area); - } - self->current_area_dirty = true; -} - - -void common_hal_vectorio_vector_shape_construct(vectorio_vector_shape_t *self, - vectorio_ishape_t ishape, - mp_obj_t pixel_shader, int32_t x, int32_t y) { - VECTORIO_SHAPE_DEBUG("%p vector_shape_construct x:%3d, y:%3d\n", self, x, y); - check_bounds_and_set_x(self, x); - check_bounds_and_set_y(self, y); - self->pixel_shader = pixel_shader; - self->ishape = ishape; - self->absolute_transform = &null_transform; // Critical to have a valid transform before getting screen area. - self->ephemeral_dirty_area.x1 = self->ephemeral_dirty_area.x2; // Cheat to set area to 0 - self->ephemeral_dirty_area.next = NULL; - self->current_area_dirty = true; - _get_screen_area(self, &self->current_area); -} - -bool common_hal_vectorio_vector_shape_contains(vectorio_vector_shape_t *self, mp_int_t x, mp_int_t y) { - VECTORIO_SHAPE_DEBUG("%p contains(%d, %d)", self); - short_bound_check(x, MP_QSTR_x); - short_bound_check(y, MP_QSTR_y); - int16_t shape_x; - int16_t shape_y; - screen_to_shape_coordinates(self, x, y, &shape_x, &shape_y); - bool shape_contains_coordinates = 0 != self->ishape.get_pixel(self->ishape.shape, shape_x, shape_y); - return shape_contains_coordinates; -} - - -mp_int_t common_hal_vectorio_vector_shape_get_x(vectorio_vector_shape_t *self) { - VECTORIO_SHAPE_DEBUG("%p get_x\n", self); - return self->x; -} - - -void common_hal_vectorio_vector_shape_set_x(vectorio_vector_shape_t *self, mp_int_t x) { - VECTORIO_SHAPE_DEBUG("%p set_x %d\n", self, x); - if (self->x == x) { - return; - } - check_bounds_and_set_x(self, x); - common_hal_vectorio_vector_shape_set_dirty(self); -} - - -mp_int_t common_hal_vectorio_vector_shape_get_y(vectorio_vector_shape_t *self) { - VECTORIO_SHAPE_DEBUG("%p get_y\n", self); - return self->y; -} - - -void common_hal_vectorio_vector_shape_set_y(vectorio_vector_shape_t *self, mp_int_t y) { - VECTORIO_SHAPE_DEBUG("%p set_y %d\n", self, y); - if (self->y == y) { - return; - } - check_bounds_and_set_y(self, y); - common_hal_vectorio_vector_shape_set_dirty(self); -} - -mp_obj_tuple_t *common_hal_vectorio_vector_shape_get_location(vectorio_vector_shape_t *self) { - VECTORIO_SHAPE_DEBUG("%p get_location\n", self); - mp_obj_tuple_t *pair = MP_OBJ_TO_PTR(mp_obj_new_tuple(2, NULL)); - pair->items[0] = mp_obj_new_int((mp_int_t)self->x); - pair->items[1] = mp_obj_new_int((mp_int_t)self->y); - return pair; -} - - -void common_hal_vectorio_vector_shape_set_location(vectorio_vector_shape_t *self, mp_obj_t xy) { - VECTORIO_SHAPE_DEBUG("%p set_location\n", self); - size_t tuple_len = 0; - mp_obj_t *tuple_items; - mp_obj_tuple_get(xy, &tuple_len, &tuple_items); - mp_arg_validate_length(tuple_len, 2, MP_QSTR_location); - - mp_int_t x = mp_arg_validate_type_int(tuple_items[0], MP_QSTR_x); - mp_int_t y = mp_arg_validate_type_int(tuple_items[1], MP_QSTR_y); - bool dirty = false; - if (self->x != x) { - check_bounds_and_set_x(self, x); - dirty = true; - } - if (self->y != y) { - check_bounds_and_set_y(self, y); - dirty = true; - } - if (dirty) { - common_hal_vectorio_vector_shape_set_dirty(self); - } -} - -mp_int_t common_hal_vectorio_vector_shape_get_hidden(vectorio_vector_shape_t *self) { - VECTORIO_SHAPE_DEBUG("%p get_hidden\n", self); - return self->hidden; -} - -void common_hal_vectorio_vector_shape_set_hidden(vectorio_vector_shape_t *self, bool hidden) { - VECTORIO_SHAPE_DEBUG("%p set_hidden %d\n", self, x); - self->hidden = hidden; - common_hal_vectorio_vector_shape_set_dirty(self); -} - -mp_obj_t common_hal_vectorio_vector_shape_get_pixel_shader(vectorio_vector_shape_t *self) { - VECTORIO_SHAPE_DEBUG("%p get_pixel_shader\n", self); - return self->pixel_shader; -} - -void common_hal_vectorio_vector_shape_set_pixel_shader(vectorio_vector_shape_t *self, mp_obj_t pixel_shader) { - VECTORIO_SHAPE_DEBUG("%p set_pixel_shader\n", self); - self->pixel_shader = pixel_shader; - common_hal_vectorio_vector_shape_set_dirty(self); -} - -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 - uint64_t start = common_hal_time_monotonic_ns(); - uint64_t pixel_time = 0; - #endif - - if (self->hidden) { - return false; - } - - VECTORIO_SHAPE_DEBUG("%p fill_area: fill: {(%5d,%5d), (%5d,%5d)}", - self, - area->x1, area->y1, area->x2, area->y2 - ); - displayio_area_t overlap; - if (!displayio_area_compute_overlap(area, &self->current_area, &overlap)) { - VECTORIO_SHAPE_DEBUG(" no overlap\n"); - return false; - } - VECTORIO_SHAPE_DEBUG(", overlap: {(%3d,%3d), (%3d,%3d)}", overlap.x1, overlap.y1, overlap.x2, overlap.y2); - - bool full_coverage = displayio_area_equal(area, &overlap); - - uint8_t pixels_per_byte = 8 / colorspace->depth; - VECTORIO_SHAPE_DEBUG(" xy:(%3d %3d) tform:{x:%d y:%d dx:%d dy:%d scl:%d w:%d h:%d mx:%d my:%d tr:%d}", - self->x, self->y, - 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 - ); - - uint16_t linestride_px = displayio_area_width(area); - uint16_t line_dirty_offset_px = (overlap.y1 - area->y1) * linestride_px; - uint16_t column_dirty_offset_px = overlap.x1 - area->x1; - VECTORIO_SHAPE_DEBUG(", linestride:%3d line_offset:%3d col_offset:%3d depth:%2d ppb:%2d shape:%s", - linestride_px, line_dirty_offset_px, column_dirty_offset_px, colorspace->depth, pixels_per_byte, mp_obj_get_type_str(self->ishape.shape)); - - displayio_input_pixel_t input_pixel; - displayio_output_pixel_t output_pixel; - - displayio_area_t shape_area; - self->ishape.get_area(self->ishape.shape, &shape_area); - - uint16_t mask_start_px = line_dirty_offset_px; - for (input_pixel.y = overlap.y1; input_pixel.y < overlap.y2; ++input_pixel.y) { - mask_start_px += column_dirty_offset_px; - for (input_pixel.x = overlap.x1; input_pixel.x < overlap.x2; ++input_pixel.x) { - // Check the mask first to see if the pixel has already been set. - uint16_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; - VECTORIO_SHAPE_PIXEL_DEBUG("\n%p pixel_index: %5u mask_bit: %2u mask: "U32_TO_BINARY_FMT, self, pixel_index, mask_bit, U32_TO_BINARY(*mask_doubleword)); - if ((*mask_doubleword & (1u << mask_bit)) != 0) { - VECTORIO_SHAPE_PIXEL_DEBUG(" masked"); - continue; - } - output_pixel.pixel = 0; - - // Cast input screen coordinates to shape coordinates to pick the pixel to draw - int16_t pixel_to_get_x; - int16_t pixel_to_get_y; - screen_to_shape_coordinates(self, input_pixel.x, input_pixel.y, &pixel_to_get_x, &pixel_to_get_y); - - 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 - uint64_t pre_pixel = common_hal_time_monotonic_ns(); - #endif - input_pixel.pixel = self->ishape.get_pixel(self->ishape.shape, pixel_to_get_x, pixel_to_get_y); - #ifdef VECTORIO_PERF - uint64_t post_pixel = common_hal_time_monotonic_ns(); - pixel_time += post_pixel - pre_pixel; - #endif - VECTORIO_SHAPE_PIXEL_DEBUG(" -> %d", input_pixel.pixel); - - // vectorio shapes use 0 to mean "area is not covered." - // We can skip all the rest of the work for this pixel if it's not currently covered by the shape. - if (input_pixel.pixel == 0) { - VECTORIO_SHAPE_PIXEL_DEBUG(" (encountered transparent pixel; input area is not fully covered)"); - full_coverage = false; - } else { - // Pixel is not transparent. Let's pull the pixel value index down to 0-base for more error-resistant palettes. - input_pixel.pixel -= 1; - output_pixel.opaque = true; - - if (self->pixel_shader == mp_const_none) { - output_pixel.pixel = input_pixel.pixel; - } else if (mp_obj_is_type(self->pixel_shader, &displayio_palette_type)) { - displayio_palette_get_color(self->pixel_shader, colorspace, &input_pixel, &output_pixel); - } else if (mp_obj_is_type(self->pixel_shader, &displayio_colorconverter_type)) { - displayio_colorconverter_convert(self->pixel_shader, colorspace, &input_pixel, &output_pixel); - } - - // We double-check this to fast-path the case when a pixel is not covered by the shape & not call the color converter unnecessarily. - if (!output_pixel.opaque) { - VECTORIO_SHAPE_PIXEL_DEBUG(" (encountered transparent pixel from colorconverter; input area is not fully covered)"); - full_coverage = false; - } - - *mask_doubleword |= 1u << mask_bit; - if (colorspace->depth == 16) { - VECTORIO_SHAPE_PIXEL_DEBUG(" buffer = %04x 16", output_pixel.pixel); - *(((uint16_t *)buffer) + pixel_index) = output_pixel.pixel; - } else if (colorspace->depth == 32) { - VECTORIO_SHAPE_PIXEL_DEBUG(" buffer = %04x 32", output_pixel.pixel); - *(((uint32_t *)buffer) + pixel_index) = output_pixel.pixel; - } else if (colorspace->depth == 8) { - VECTORIO_SHAPE_PIXEL_DEBUG(" buffer = %02x 8", 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) { - uint16_t row = pixel_index / linestride_px; - uint16_t col = pixel_index % linestride_px; - pixel_index = col * pixels_per_byte + (row / pixels_per_byte) * pixels_per_byte * linestride_px + row % pixels_per_byte; - } - uint8_t shift = (pixel_index % pixels_per_byte) * colorspace->depth; - if (colorspace->reverse_pixels_in_byte) { - // Reverse the shift by subtracting it from the leftmost shift. - shift = (pixels_per_byte - 1) * colorspace->depth - shift; - } - VECTORIO_SHAPE_PIXEL_DEBUG(" buffer = %2d %d", output_pixel.pixel, colorspace->depth); - ((uint8_t *)buffer)[pixel_index / pixels_per_byte] |= output_pixel.pixel << shift; - } - } - } - mask_start_px += linestride_px - column_dirty_offset_px; - } - #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", - mp_obj_get_type_str(self->ishape.shape), - (overlap.x2 - overlap.x1) * (overlap.y2 - overlap.y1), - (double)((end - start) / 1000000.0), - (double)(MAX(1, pixels * (1000000000.0 / (end - start)))), - (double)(pixel_time / 1000.0), - (double)(pixel_time / 1000.0 / pixels) - ); - #endif - VECTORIO_SHAPE_DEBUG(" -> pixels:%4d\n", (overlap.x2 - overlap.x1) * (overlap.y2 - overlap.y1)); - return full_coverage; -} - - -void vectorio_vector_shape_finish_refresh(vectorio_vector_shape_t *self) { - if (displayio_area_empty(&self->ephemeral_dirty_area) && !self->current_area_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); - // Reset dirty area to nothing - self->ephemeral_dirty_area.x1 = self->ephemeral_dirty_area.x2; // Cheat to set area to empty - self->ephemeral_dirty_area.next = NULL; - - self->current_area_dirty = false; // We don't clear current area so we can remember what to clean up if we move - self->current_area.next = NULL; - - VECTORIO_SHAPE_DEBUG("%p finish_refresh now:{(%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); - - if (mp_obj_is_type(self->pixel_shader, &displayio_palette_type)) { - displayio_palette_finish_refresh(self->pixel_shader); - } else if (mp_obj_is_type(self->pixel_shader, &displayio_colorconverter_type)) { - displayio_colorconverter_finish_refresh(self->pixel_shader); - } -} - - -// 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) { - if (self->current_area_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)) - ) { - if (!displayio_area_empty(&self->ephemeral_dirty_area)) { - // Both are dirty, check if we should combine the areas or draw separately - // Draws as few pixels as possible both when animations move short distances and large distances. - // The display core implementation currently doesn't combine areas to reduce redrawing of masked areas. If it does, - // this could be simplified to just return the 2 possibly overlapping areas. - displayio_area_t area_swap; - displayio_area_compute_overlap(&self->ephemeral_dirty_area, &self->current_area, &area_swap); - uint32_t overlap_size = displayio_area_size(&area_swap); - displayio_area_union(&self->ephemeral_dirty_area, &self->current_area, &area_swap); // Leave area_swap as the union area for later. - uint32_t union_size = displayio_area_size(&area_swap); - uint32_t current_size = displayio_area_size(&self->current_area); - uint32_t dirty_size = displayio_area_size(&self->ephemeral_dirty_area); - - VECTORIO_SHAPE_DEBUG("%p get_refresh_area: dirty{(%3d,%3d), (%3d,%3d)} + current{(%3d,%3d), (%3d,%3d)} = union{(%3d,%3d), (%3d,%3d)}: union%d - dirty%d - curr%d + overlap%d = excluded%d : ", self, - self->ephemeral_dirty_area.x1, self->ephemeral_dirty_area.y1, self->ephemeral_dirty_area.x2, self->ephemeral_dirty_area.y2, - self->current_area.x1, self->current_area.y1, self->current_area.x2, self->current_area.y2, - area_swap.x1, area_swap.y1, area_swap.x2, area_swap.y2, - union_size, dirty_size, current_size, overlap_size, (int32_t)union_size - dirty_size - current_size + overlap_size - ); - - if ((int32_t)union_size - dirty_size - current_size + overlap_size <= MIN(dirty_size, current_size)) { - // The excluded / non-overlapping area from the disjoint dirty and current areas is smaller - // than the smallest area we need to draw. Redrawing the overlapping area would cost more - // than just drawing the union disjoint area once. - VECTORIO_SHAPE_DEBUG("combining to take disjoint area\n"); - displayio_area_copy(&area_swap, &self->ephemeral_dirty_area); - } else { - // The excluded area between the 2 dirty areas is larger than the smallest dirty area. It would be - // more costly to combine these areas than possibly redraw some overlap. - VECTORIO_SHAPE_DEBUG("excluded area too large, drawing separate area\n"); - self->current_area.next = tail; - tail = &self->current_area; - } - - self->ephemeral_dirty_area.next = tail; - tail = &self->ephemeral_dirty_area; - } else { - self->current_area.next = tail; - tail = &self->current_area; - VECTORIO_SHAPE_DEBUG("%p get_refresh_area: redrawing current: {(%3d,%3d), (%3d,%3d)}\n", self, self->current_area.x1, self->current_area.y1, self->current_area.x2, self->current_area.y2); - } - } else if (!displayio_area_empty(&self->ephemeral_dirty_area)) { - self->ephemeral_dirty_area.next = tail; - tail = &self->ephemeral_dirty_area; - VECTORIO_SHAPE_DEBUG("%p get_refresh_area redrawing dirty: {(%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); - } - return tail; -} - -void vectorio_vector_shape_update_transform(vectorio_vector_shape_t *self, displayio_buffer_transform_t *group_transform) { - self->absolute_transform = group_transform == NULL ? &null_transform : group_transform; - common_hal_vectorio_vector_shape_set_dirty(self); -} diff --git a/shared-module/vectorio/VectorShape.h b/shared-module/vectorio/VectorShape.h index db77fc0acb9..70840ec7c8e 100644 --- a/shared-module/vectorio/VectorShape.h +++ b/shared-module/vectorio/VectorShape.h @@ -4,55 +4,54 @@ // // SPDX-License-Identifier: MIT - #pragma once #include #include #include "py/obj.h" + +// Everything a vectorio shape has to provide to the compositor, independent of backend: +// +// get_pixel(x, y) - the shape's coverage test, in the shape's own coordinate space where +// (0, 0) is the shape's origin. Returns 0 for "not covered" and the shape's color +// index biased by one otherwise. (The bias keeps 0, which means "not covered", from +// ever naming a palette entry.) +// +// Everything else is backend specific: +// +// legacy/ - the scanline compositor. Shapes report a bounding area, the compositor fills +// screen spans through get_pixel(), and shapes track dirty areas so the display core +// knows what to repaint. +// lvgl/ - the LVGL compositor. Shapes are mirrored into lv_obj widgets that LVGL draws +// and invalidates itself, so there is no area and no span filling at all. +typedef uint32_t get_pixel_function(mp_obj_t shape, int16_t x, int16_t y); + +#if !CIRCUITPY_DISPLAYIO_LVGL #include "shared-module/displayio/area.h" -#include "shared-module/displayio/Palette.h" typedef void get_area_function(mp_obj_t shape, displayio_area_t *out_area); -typedef uint32_t get_pixel_function(mp_obj_t shape, int16_t x, int16_t y); +#endif -// This struct binds a shape's common Shape support functions (its vector shape interface) -// to its instance pointer. We only check at construction time what the type of the -// associated shape is and link the correct functions up. -// Later when using the shape for drawing logic these functions may be invoked -// unconditionally. This simplifies the addition of new types and restricts the -// respective responsibilities of VectorShape and actual shape implementations. +// This struct binds a shape's support functions to its instance pointer. A shape's type is +// only inspected when its vector shape is constructed; after that the compositor can call +// these unconditionally. That keeps the shape implementations and the vector shape +// wrapper responsible for their own pieces. typedef struct { mp_obj_t shape; + #if !CIRCUITPY_DISPLAYIO_LVGL get_area_function *get_area; + #endif get_pixel_function *get_pixel; } vectorio_ishape_t; -typedef struct { - mp_obj_base_t base; - vectorio_ishape_t ishape; - mp_obj_t pixel_shader; - int16_t x; - int16_t y; - displayio_buffer_transform_t *absolute_transform; - // Tracks current shape footprint and expands outward as the shape dirties and changes. - // This is suboptimal if you move your shape far. Could add more state to only redraw - // exactly what we left behind. - displayio_area_t ephemeral_dirty_area; - displayio_area_t current_area; - bool current_area_dirty; - bool hidden; -} vectorio_vector_shape_t; - -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); - -// Area is always in absolute screen coordinates. -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); - -// Fills in out_area with the maximum bounds of all related pixels in the last rendered frame. Returns -// false if the vector shape wasn't rendered in the last frame. -bool vectorio_vector_shape_get_previous_area(vectorio_vector_shape_t *self, displayio_area_t *out_area); -void vectorio_vector_shape_finish_refresh(vectorio_vector_shape_t *self); +#if CIRCUITPY_DISPLAYIO_LVGL +#include "shared-module/vectorio/lvgl/VectorShape.h" +// The protocol slot an LVGL-backed shape exposes to its Group. Legacy shapes are found by +// type through protocol_draw, so the slot stays empty there. See +// displayio/lvgl/lvgl_protocol.h. +#define VECTORIO_VECTOR_SHAPE_LVGL_PROTOCOL &displayio_lvgl_vector_shape_protocol +#else +#include "shared-module/vectorio/legacy/VectorShape.h" +#define VECTORIO_VECTOR_SHAPE_LVGL_PROTOCOL NULL +#endif diff --git a/shared-module/vectorio/legacy/VectorShape.c b/shared-module/vectorio/legacy/VectorShape.c new file mode 100644 index 00000000000..0ae48eb1054 --- /dev/null +++ b/shared-module/vectorio/legacy/VectorShape.c @@ -0,0 +1,571 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 by kvc0/WarriorOfWire +// +// SPDX-License-Identifier: MIT + +#if CIRCUITPY_VECTORIO + +#include "stdlib.h" + +#include "shared-module/vectorio/__init__.h" +#include "shared-bindings/vectorio/VectorShape.h" + +#include "py/misc.h" +#include "py/runtime.h" +#include "shared-bindings/time/__init__.h" +#include "shared-bindings/displayio/ColorConverter.h" +#include "shared-bindings/displayio/Palette.h" + +#include "shared-bindings/vectorio/Circle.h" +#include "shared-bindings/vectorio/Polygon.h" +#include "shared-bindings/vectorio/Rectangle.h" + +// Lifecycle actions. +#define VECTORIO_SHAPE_DEBUG(...) (void)0 +// #define VECTORIO_SHAPE_DEBUG(...) mp_printf(&mp_plat_print, __VA_ARGS__) + + +// Used in both logging and ifdefs, for extra variables +// #define VECTORIO_PERF(...) mp_printf(&mp_plat_print, __VA_ARGS__) + + +// Really verbose. +#define VECTORIO_SHAPE_PIXEL_DEBUG(...) (void)0 +// #define VECTORIO_SHAPE_PIXEL_DEBUG(...) mp_printf(&mp_plat_print, __VA_ARGS__) + +#define U32_TO_BINARY_FMT "%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c%c" +#define U32_TO_BINARY(u32) \ + (u32 & 0x80000000 ? '1' : '0'), \ + (u32 & 0x40000000 ? '1' : '0'), \ + (u32 & 0x20000000 ? '1' : '0'), \ + (u32 & 0x10000000 ? '1' : '0'), \ + (u32 & 0x8000000 ? '1' : '0'), \ + (u32 & 0x4000000 ? '1' : '0'), \ + (u32 & 0x2000000 ? '1' : '0'), \ + (u32 & 0x1000000 ? '1' : '0'), \ + (u32 & 0x800000 ? '1' : '0'), \ + (u32 & 0x400000 ? '1' : '0'), \ + (u32 & 0x200000 ? '1' : '0'), \ + (u32 & 0x100000 ? '1' : '0'), \ + (u32 & 0x80000 ? '1' : '0'), \ + (u32 & 0x40000 ? '1' : '0'), \ + (u32 & 0x20000 ? '1' : '0'), \ + (u32 & 0x10000 ? '1' : '0'), \ + (u32 & 0x8000 ? '1' : '0'), \ + (u32 & 0x4000 ? '1' : '0'), \ + (u32 & 0x2000 ? '1' : '0'), \ + (u32 & 0x1000 ? '1' : '0'), \ + (u32 & 0x800 ? '1' : '0'), \ + (u32 & 0x400 ? '1' : '0'), \ + (u32 & 0x200 ? '1' : '0'), \ + (u32 & 0x100 ? '1' : '0'), \ + (u32 & 0x80 ? '1' : '0'), \ + (u32 & 0x40 ? '1' : '0'), \ + (u32 & 0x20 ? '1' : '0'), \ + (u32 & 0x10 ? '1' : '0'), \ + (u32 & 0x8 ? '1' : '0'), \ + (u32 & 0x4 ? '1' : '0'), \ + (u32 & 0x2 ? '1' : '0'), \ + (u32 & 0x1 ? '1' : '0') + +static void short_bound_check(mp_int_t i, qstr name) { + mp_arg_validate_int_range(i, SHRT_MIN, SHRT_MAX, name); +} + +inline __attribute__((always_inline)) +static void area_transpose(displayio_area_t *to_transpose) { + int16_t swap = to_transpose->y1; + to_transpose->y1 = to_transpose->x1; + to_transpose->x1 = swap; + swap = to_transpose->y2; + to_transpose->y2 = to_transpose->x2; + to_transpose->x2 = swap; +} + +inline __attribute__((always_inline)) +static void _get_screen_area(vectorio_vector_shape_t *self, displayio_area_t *out_area) { + VECTORIO_SHAPE_DEBUG("%p get_screen_area (%3d,%3d) tform:{x:%d y:%d dx:%d dy:%d scl:%d w:%d h:%d mx:%d my:%d tr:%d}", self, self->x, self->y, + 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); + + int16_t x; + int16_t y; + if (self->absolute_transform->transpose_xy) { + x = self->absolute_transform->x + self->absolute_transform->dx * self->y; + y = self->absolute_transform->y + self->absolute_transform->dy * self->x; + if (self->absolute_transform->dx < 1) { + x -= 1; + out_area->y1 = out_area->y1 * -1 + 1; + out_area->y2 = out_area->y2 * -1 + 1; + } + if (self->absolute_transform->dy < 1) { + y -= 1; + out_area->x1 = out_area->x1 * -1 + 1; + out_area->x2 = out_area->x2 * -1 + 1; + } + area_transpose(out_area); + } else { + x = self->absolute_transform->x + self->absolute_transform->dx * self->x; + y = self->absolute_transform->y + self->absolute_transform->dy * self->y; + + if (self->absolute_transform->dx < 1) { + x -= 1; + out_area->x1 = out_area->x1 * -1 + 1; + out_area->x2 = out_area->x2 * -1 + 1; + } + if (self->absolute_transform->dy < 1) { + y -= 1; + out_area->y1 = out_area->y1 * -1 + 1; + out_area->y2 = out_area->y2 * -1 + 1; + } + } + displayio_area_canon(out_area); + displayio_area_shift(out_area, x, y); + + VECTORIO_SHAPE_DEBUG(" out:{(%5d,%5d), (%5d,%5d)}\n", out_area->x1, out_area->y1, out_area->x2, out_area->y2); +} + +// Get the target pixel based on the shape's coordinate space +static void screen_to_shape_coordinates(vectorio_vector_shape_t *self, uint16_t x, uint16_t y, int16_t *out_shape_x, int16_t *out_shape_y) { + if (self->absolute_transform->transpose_xy) { + *out_shape_x = y - self->absolute_transform->y - self->absolute_transform->dy * self->x; + *out_shape_y = x - self->absolute_transform->x - self->absolute_transform->dx * self->y; + + VECTORIO_SHAPE_PIXEL_DEBUG(" a(%3d, %3d)", *out_shape_x, *out_shape_y); + if (self->absolute_transform->dx < 1) { + *out_shape_y *= -1; + *out_shape_y -= 1; + } + if (self->absolute_transform->dy < 1) { + *out_shape_x *= -1; + *out_shape_x -= 1; + } + } else { + *out_shape_x = x - self->absolute_transform->x - self->absolute_transform->dx * self->x; + *out_shape_y = y - self->absolute_transform->y - self->absolute_transform->dy * self->y; + + VECTORIO_SHAPE_PIXEL_DEBUG(" a(%3d, %3d)", *out_shape_x, *out_shape_y); + if (self->absolute_transform->dx < 1) { + *out_shape_x *= -1; + *out_shape_x -= 1; + } + if (self->absolute_transform->dy < 1) { + *out_shape_y *= -1; + *out_shape_y -= 1; + } + // It's mirrored via dx. Maybe we need to add support for also separately mirroring? + // if (self->absolute_transform->mirror_x) { + // pixel_to_get_x = (shape_area.x2 - shape_area.x1) - (pixel_to_get_x - shape_area.x1) + shape_area.x1 - 1; + // } + // if (self->absolute_transform->mirror_y) { + // pixel_to_get_y = (shape_area.y2 - shape_area.y1) - (pixel_to_get_y - shape_area.y1) + +shape_area.y1 - 1; + // } + } + VECTORIO_SHAPE_PIXEL_DEBUG(" b(%3d, %3d)", *out_shape_x, *out_shape_y); +} + +static void check_bounds_and_set_x(vectorio_vector_shape_t *self, mp_int_t x) { + short_bound_check(x, MP_QSTR_x); + self->x = x; +} + +static void check_bounds_and_set_y(vectorio_vector_shape_t *self, mp_int_t y) { + short_bound_check(y, MP_QSTR_y); + self->y = y; +} + + +// For use by Group to know where it needs to redraw on layer removal. +bool vectorio_vector_shape_get_dirty_area(vectorio_vector_shape_t *self, displayio_area_t *out_area) { + out_area->x1 = out_area->x2; + displayio_area_union( + &self->ephemeral_dirty_area, + &self->current_area, + out_area + ); + return true; // For now just always redraw. +} + + +// This must be invoked after each time a shape changes its position, shape or appearance in any way. +void common_hal_vectorio_vector_shape_set_dirty(void *vector_shape) { + vectorio_vector_shape_t *self = vector_shape; + // In screen space. Need to offset the shape space. + displayio_area_t current_area; + _get_screen_area(self, ¤t_area); + VECTORIO_SHAPE_DEBUG("%p shape_dirty new:{(%3d,%3d), (%3d,%3d)} dirty:{(%3d,%3d), (%3d,%3d)}", + self, + current_area.x1, current_area.y1, current_area.x2, current_area.y2, + self->ephemeral_dirty_area.x1, self->ephemeral_dirty_area.y1, self->ephemeral_dirty_area.x2, self->ephemeral_dirty_area.y2); + + bool moved = !displayio_area_equal(¤t_area, &self->current_area); + if (moved) { + displayio_area_union(&self->current_area, &self->ephemeral_dirty_area, &self->ephemeral_dirty_area); + VECTORIO_SHAPE_DEBUG(" stale:{(%3d,%3d), (%3d,%3d)} -> expanded:{(%3d,%3d), (%3d,%3d)}\n", + self->current_area.x1, self->current_area.y1, self->current_area.x2, self->current_area.y2, + self->ephemeral_dirty_area.x1, self->ephemeral_dirty_area.y1, self->ephemeral_dirty_area.x2, self->ephemeral_dirty_area.y2); + + // Dirty area tracks the shape's footprint between draws. It's reset on refresh finish. + displayio_area_copy(¤t_area, &self->current_area); + } + self->current_area_dirty = true; +} + + +void common_hal_vectorio_vector_shape_construct(vectorio_vector_shape_t *self, + vectorio_ishape_t ishape, + mp_obj_t pixel_shader, int32_t x, int32_t y) { + VECTORIO_SHAPE_DEBUG("%p vector_shape_construct x:%3d, y:%3d\n", self, x, y); + check_bounds_and_set_x(self, x); + check_bounds_and_set_y(self, y); + self->pixel_shader = pixel_shader; + self->ishape = ishape; + self->absolute_transform = &null_transform; // Critical to have a valid transform before getting screen area. + self->ephemeral_dirty_area.x1 = self->ephemeral_dirty_area.x2; // Cheat to set area to 0 + self->ephemeral_dirty_area.next = NULL; + self->current_area_dirty = true; + _get_screen_area(self, &self->current_area); +} + +bool common_hal_vectorio_vector_shape_contains(vectorio_vector_shape_t *self, mp_int_t x, mp_int_t y) { + VECTORIO_SHAPE_DEBUG("%p contains(%d, %d)", self); + short_bound_check(x, MP_QSTR_x); + short_bound_check(y, MP_QSTR_y); + int16_t shape_x; + int16_t shape_y; + screen_to_shape_coordinates(self, x, y, &shape_x, &shape_y); + bool shape_contains_coordinates = 0 != self->ishape.get_pixel(self->ishape.shape, shape_x, shape_y); + return shape_contains_coordinates; +} + + +mp_int_t common_hal_vectorio_vector_shape_get_x(vectorio_vector_shape_t *self) { + VECTORIO_SHAPE_DEBUG("%p get_x\n", self); + return self->x; +} + + +void common_hal_vectorio_vector_shape_set_x(vectorio_vector_shape_t *self, mp_int_t x) { + VECTORIO_SHAPE_DEBUG("%p set_x %d\n", self, x); + if (self->x == x) { + return; + } + check_bounds_and_set_x(self, x); + common_hal_vectorio_vector_shape_set_dirty(self); +} + + +mp_int_t common_hal_vectorio_vector_shape_get_y(vectorio_vector_shape_t *self) { + VECTORIO_SHAPE_DEBUG("%p get_y\n", self); + return self->y; +} + + +void common_hal_vectorio_vector_shape_set_y(vectorio_vector_shape_t *self, mp_int_t y) { + VECTORIO_SHAPE_DEBUG("%p set_y %d\n", self, y); + if (self->y == y) { + return; + } + check_bounds_and_set_y(self, y); + common_hal_vectorio_vector_shape_set_dirty(self); +} + +mp_obj_tuple_t *common_hal_vectorio_vector_shape_get_location(vectorio_vector_shape_t *self) { + VECTORIO_SHAPE_DEBUG("%p get_location\n", self); + mp_obj_tuple_t *pair = MP_OBJ_TO_PTR(mp_obj_new_tuple(2, NULL)); + pair->items[0] = mp_obj_new_int((mp_int_t)self->x); + pair->items[1] = mp_obj_new_int((mp_int_t)self->y); + return pair; +} + + +void common_hal_vectorio_vector_shape_set_location(vectorio_vector_shape_t *self, mp_obj_t xy) { + VECTORIO_SHAPE_DEBUG("%p set_location\n", self); + size_t tuple_len = 0; + mp_obj_t *tuple_items; + mp_obj_tuple_get(xy, &tuple_len, &tuple_items); + mp_arg_validate_length(tuple_len, 2, MP_QSTR_location); + + mp_int_t x = mp_arg_validate_type_int(tuple_items[0], MP_QSTR_x); + mp_int_t y = mp_arg_validate_type_int(tuple_items[1], MP_QSTR_y); + bool dirty = false; + if (self->x != x) { + check_bounds_and_set_x(self, x); + dirty = true; + } + if (self->y != y) { + check_bounds_and_set_y(self, y); + dirty = true; + } + if (dirty) { + common_hal_vectorio_vector_shape_set_dirty(self); + } +} + +mp_int_t common_hal_vectorio_vector_shape_get_hidden(vectorio_vector_shape_t *self) { + VECTORIO_SHAPE_DEBUG("%p get_hidden\n", self); + return self->hidden; +} + +void common_hal_vectorio_vector_shape_set_hidden(vectorio_vector_shape_t *self, bool hidden) { + VECTORIO_SHAPE_DEBUG("%p set_hidden %d\n", self, x); + self->hidden = hidden; + common_hal_vectorio_vector_shape_set_dirty(self); +} + +mp_obj_t common_hal_vectorio_vector_shape_get_pixel_shader(vectorio_vector_shape_t *self) { + VECTORIO_SHAPE_DEBUG("%p get_pixel_shader\n", self); + return self->pixel_shader; +} + +void common_hal_vectorio_vector_shape_set_pixel_shader(vectorio_vector_shape_t *self, mp_obj_t pixel_shader) { + VECTORIO_SHAPE_DEBUG("%p set_pixel_shader\n", self); + self->pixel_shader = pixel_shader; + common_hal_vectorio_vector_shape_set_dirty(self); +} + +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 + uint64_t start = common_hal_time_monotonic_ns(); + uint64_t pixel_time = 0; + #endif + + if (self->hidden) { + return false; + } + + VECTORIO_SHAPE_DEBUG("%p fill_area: fill: {(%5d,%5d), (%5d,%5d)}", + self, + area->x1, area->y1, area->x2, area->y2 + ); + displayio_area_t overlap; + if (!displayio_area_compute_overlap(area, &self->current_area, &overlap)) { + VECTORIO_SHAPE_DEBUG(" no overlap\n"); + return false; + } + VECTORIO_SHAPE_DEBUG(", overlap: {(%3d,%3d), (%3d,%3d)}", overlap.x1, overlap.y1, overlap.x2, overlap.y2); + + bool full_coverage = displayio_area_equal(area, &overlap); + + uint8_t pixels_per_byte = 8 / colorspace->depth; + VECTORIO_SHAPE_DEBUG(" xy:(%3d %3d) tform:{x:%d y:%d dx:%d dy:%d scl:%d w:%d h:%d mx:%d my:%d tr:%d}", + self->x, self->y, + 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 + ); + + uint16_t linestride_px = displayio_area_width(area); + uint16_t line_dirty_offset_px = (overlap.y1 - area->y1) * linestride_px; + uint16_t column_dirty_offset_px = overlap.x1 - area->x1; + VECTORIO_SHAPE_DEBUG(", linestride:%3d line_offset:%3d col_offset:%3d depth:%2d ppb:%2d shape:%s", + linestride_px, line_dirty_offset_px, column_dirty_offset_px, colorspace->depth, pixels_per_byte, mp_obj_get_type_str(self->ishape.shape)); + + displayio_input_pixel_t input_pixel; + displayio_output_pixel_t output_pixel; + + displayio_area_t shape_area; + self->ishape.get_area(self->ishape.shape, &shape_area); + + uint16_t mask_start_px = line_dirty_offset_px; + for (input_pixel.y = overlap.y1; input_pixel.y < overlap.y2; ++input_pixel.y) { + mask_start_px += column_dirty_offset_px; + for (input_pixel.x = overlap.x1; input_pixel.x < overlap.x2; ++input_pixel.x) { + // Check the mask first to see if the pixel has already been set. + uint16_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; + VECTORIO_SHAPE_PIXEL_DEBUG("\n%p pixel_index: %5u mask_bit: %2u mask: "U32_TO_BINARY_FMT, self, pixel_index, mask_bit, U32_TO_BINARY(*mask_doubleword)); + if ((*mask_doubleword & (1u << mask_bit)) != 0) { + VECTORIO_SHAPE_PIXEL_DEBUG(" masked"); + continue; + } + output_pixel.pixel = 0; + + // Cast input screen coordinates to shape coordinates to pick the pixel to draw + int16_t pixel_to_get_x; + int16_t pixel_to_get_y; + screen_to_shape_coordinates(self, input_pixel.x, input_pixel.y, &pixel_to_get_x, &pixel_to_get_y); + + 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 + uint64_t pre_pixel = common_hal_time_monotonic_ns(); + #endif + input_pixel.pixel = self->ishape.get_pixel(self->ishape.shape, pixel_to_get_x, pixel_to_get_y); + #ifdef VECTORIO_PERF + uint64_t post_pixel = common_hal_time_monotonic_ns(); + pixel_time += post_pixel - pre_pixel; + #endif + VECTORIO_SHAPE_PIXEL_DEBUG(" -> %d", input_pixel.pixel); + + // vectorio shapes use 0 to mean "area is not covered." + // We can skip all the rest of the work for this pixel if it's not currently covered by the shape. + if (input_pixel.pixel == 0) { + VECTORIO_SHAPE_PIXEL_DEBUG(" (encountered transparent pixel; input area is not fully covered)"); + full_coverage = false; + } else { + // Pixel is not transparent. Let's pull the pixel value index down to 0-base for more error-resistant palettes. + input_pixel.pixel -= 1; + output_pixel.opaque = true; + + if (self->pixel_shader == mp_const_none) { + output_pixel.pixel = input_pixel.pixel; + } else if (mp_obj_is_type(self->pixel_shader, &displayio_palette_type)) { + displayio_palette_get_color(self->pixel_shader, colorspace, &input_pixel, &output_pixel); + } else if (mp_obj_is_type(self->pixel_shader, &displayio_colorconverter_type)) { + displayio_colorconverter_convert(self->pixel_shader, colorspace, &input_pixel, &output_pixel); + } + + // We double-check this to fast-path the case when a pixel is not covered by the shape & not call the color converter unnecessarily. + if (!output_pixel.opaque) { + VECTORIO_SHAPE_PIXEL_DEBUG(" (encountered transparent pixel from colorconverter; input area is not fully covered)"); + full_coverage = false; + } + + *mask_doubleword |= 1u << mask_bit; + if (colorspace->depth == 16) { + VECTORIO_SHAPE_PIXEL_DEBUG(" buffer = %04x 16", output_pixel.pixel); + *(((uint16_t *)buffer) + pixel_index) = output_pixel.pixel; + } else if (colorspace->depth == 32) { + VECTORIO_SHAPE_PIXEL_DEBUG(" buffer = %04x 32", output_pixel.pixel); + *(((uint32_t *)buffer) + pixel_index) = output_pixel.pixel; + } else if (colorspace->depth == 24) { + VECTORIO_SHAPE_PIXEL_DEBUG(" buffer = %06x 24", output_pixel.pixel); + memcpy(((uint8_t *)buffer) + pixel_index * 3, &output_pixel.pixel, 3); + } else if (colorspace->depth == 8) { + VECTORIO_SHAPE_PIXEL_DEBUG(" buffer = %02x 8", 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) { + uint16_t row = pixel_index / linestride_px; + uint16_t col = pixel_index % linestride_px; + pixel_index = col * pixels_per_byte + (row / pixels_per_byte) * pixels_per_byte * linestride_px + row % pixels_per_byte; + } + uint8_t shift = (pixel_index % pixels_per_byte) * colorspace->depth; + if (colorspace->reverse_pixels_in_byte) { + // Reverse the shift by subtracting it from the leftmost shift. + shift = (pixels_per_byte - 1) * colorspace->depth - shift; + } + VECTORIO_SHAPE_PIXEL_DEBUG(" buffer = %2d %d", output_pixel.pixel, colorspace->depth); + ((uint8_t *)buffer)[pixel_index / pixels_per_byte] |= output_pixel.pixel << shift; + } + } + } + mask_start_px += linestride_px - column_dirty_offset_px; + } + #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", + mp_obj_get_type_str(self->ishape.shape), + (overlap.x2 - overlap.x1) * (overlap.y2 - overlap.y1), + (double)((end - start) / 1000000.0), + (double)(MAX(1, pixels * (1000000000.0 / (end - start)))), + (double)(pixel_time / 1000.0), + (double)(pixel_time / 1000.0 / pixels) + ); + #endif + VECTORIO_SHAPE_DEBUG(" -> pixels:%4d\n", (overlap.x2 - overlap.x1) * (overlap.y2 - overlap.y1)); + return full_coverage; +} + + +void vectorio_vector_shape_finish_refresh(vectorio_vector_shape_t *self) { + if (displayio_area_empty(&self->ephemeral_dirty_area) && !self->current_area_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); + // Reset dirty area to nothing + self->ephemeral_dirty_area.x1 = self->ephemeral_dirty_area.x2; // Cheat to set area to empty + self->ephemeral_dirty_area.next = NULL; + + self->current_area_dirty = false; // We don't clear current area so we can remember what to clean up if we move + self->current_area.next = NULL; + + VECTORIO_SHAPE_DEBUG("%p finish_refresh now:{(%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); + + if (mp_obj_is_type(self->pixel_shader, &displayio_palette_type)) { + displayio_palette_finish_refresh(self->pixel_shader); + } else if (mp_obj_is_type(self->pixel_shader, &displayio_colorconverter_type)) { + displayio_colorconverter_finish_refresh(self->pixel_shader); + } +} + + +// 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) { + if (self->current_area_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)) + ) { + if (!displayio_area_empty(&self->ephemeral_dirty_area)) { + // Both are dirty, check if we should combine the areas or draw separately + // Draws as few pixels as possible both when animations move short distances and large distances. + // The display core implementation currently doesn't combine areas to reduce redrawing of masked areas. If it does, + // this could be simplified to just return the 2 possibly overlapping areas. + displayio_area_t area_swap; + displayio_area_compute_overlap(&self->ephemeral_dirty_area, &self->current_area, &area_swap); + uint32_t overlap_size = displayio_area_size(&area_swap); + displayio_area_union(&self->ephemeral_dirty_area, &self->current_area, &area_swap); // Leave area_swap as the union area for later. + uint32_t union_size = displayio_area_size(&area_swap); + uint32_t current_size = displayio_area_size(&self->current_area); + uint32_t dirty_size = displayio_area_size(&self->ephemeral_dirty_area); + + VECTORIO_SHAPE_DEBUG("%p get_refresh_area: dirty{(%3d,%3d), (%3d,%3d)} + current{(%3d,%3d), (%3d,%3d)} = union{(%3d,%3d), (%3d,%3d)}: union%d - dirty%d - curr%d + overlap%d = excluded%d : ", self, + self->ephemeral_dirty_area.x1, self->ephemeral_dirty_area.y1, self->ephemeral_dirty_area.x2, self->ephemeral_dirty_area.y2, + self->current_area.x1, self->current_area.y1, self->current_area.x2, self->current_area.y2, + area_swap.x1, area_swap.y1, area_swap.x2, area_swap.y2, + union_size, dirty_size, current_size, overlap_size, (int32_t)union_size - dirty_size - current_size + overlap_size + ); + + if ((int32_t)union_size - dirty_size - current_size + overlap_size <= MIN(dirty_size, current_size)) { + // The excluded / non-overlapping area from the disjoint dirty and current areas is smaller + // than the smallest area we need to draw. Redrawing the overlapping area would cost more + // than just drawing the union disjoint area once. + VECTORIO_SHAPE_DEBUG("combining to take disjoint area\n"); + displayio_area_copy(&area_swap, &self->ephemeral_dirty_area); + } else { + // The excluded area between the 2 dirty areas is larger than the smallest dirty area. It would be + // more costly to combine these areas than possibly redraw some overlap. + VECTORIO_SHAPE_DEBUG("excluded area too large, drawing separate area\n"); + self->current_area.next = tail; + tail = &self->current_area; + } + + self->ephemeral_dirty_area.next = tail; + tail = &self->ephemeral_dirty_area; + } else { + self->current_area_dirty = true; + self->current_area.next = tail; + tail = &self->current_area; + VECTORIO_SHAPE_DEBUG("%p get_refresh_area: redrawing current: {(%3d,%3d), (%3d,%3d)}\n", self, self->current_area.x1, self->current_area.y1, self->current_area.x2, self->current_area.y2); + } + } else if (!displayio_area_empty(&self->ephemeral_dirty_area)) { + self->ephemeral_dirty_area.next = tail; + tail = &self->ephemeral_dirty_area; + VECTORIO_SHAPE_DEBUG("%p get_refresh_area redrawing dirty: {(%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); + } + return tail; +} + +void vectorio_vector_shape_update_transform(vectorio_vector_shape_t *self, displayio_buffer_transform_t *group_transform) { + self->absolute_transform = group_transform == NULL ? &null_transform : group_transform; + common_hal_vectorio_vector_shape_set_dirty(self); +} + +bool vectorio_vector_shape_set_in_group(vectorio_vector_shape_t *self, bool in_group) { + bool was_in_group = self->in_group; + self->in_group = in_group; + return was_in_group; +} + +#endif // CIRCUITPY_VECTORIO diff --git a/shared-module/vectorio/legacy/VectorShape.h b/shared-module/vectorio/legacy/VectorShape.h new file mode 100644 index 00000000000..d45cdbe33a6 --- /dev/null +++ b/shared-module/vectorio/legacy/VectorShape.h @@ -0,0 +1,50 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2020 by kvc0/WarriorOfWire +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include + +#include "py/obj.h" +#include "shared-module/displayio/area.h" +#include "shared-module/displayio/Palette.h" + +// Legacy scanline compositor state for a vector shape. +// +// The shape's footprint is tracked in screen space twice: current_area is where the shape +// is now and ephemeral_dirty_area is the accumulation of where it has been since the last +// refresh. get_refresh_areas() hands both to the display core so it can repaint exactly the +// pixels that changed. absolute_transform mirrors the parent groups' transforms so that +// screen coordinates can be mapped back into the shape's own coordinate space. +typedef struct { + mp_obj_base_t base; + vectorio_ishape_t ishape; + mp_obj_t pixel_shader; + int16_t x; + int16_t y; + displayio_buffer_transform_t *absolute_transform; + // Tracks current shape footprint and expands outward as the shape dirties and changes. + // This is suboptimal if you move your shape far. Could add more state to only redraw + // exactly what we left behind. + displayio_area_t ephemeral_dirty_area; + displayio_area_t current_area; + bool current_area_dirty; + bool hidden; + bool in_group; +} vectorio_vector_shape_t; + +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); + +// Area is always in absolute screen coordinates. +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); + +// Fills in out_area with the maximum bounds of all related pixels in the last rendered frame. Returns +// false if the vector shape wasn't rendered in the last frame. +bool vectorio_vector_shape_get_previous_area(vectorio_vector_shape_t *self, displayio_area_t *out_area); +void vectorio_vector_shape_finish_refresh(vectorio_vector_shape_t *self); diff --git a/shared-module/vectorio/lvgl/VectorShape.c b/shared-module/vectorio/lvgl/VectorShape.c new file mode 100644 index 00000000000..80813e80e2a --- /dev/null +++ b/shared-module/vectorio/lvgl/VectorShape.c @@ -0,0 +1,563 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// LVGL implementation of the vectorio VectorShape wrapper. See lvgl/VectorShape.h for the +// design. In short: a shape is one lv_obj, LVGL does all drawing and invalidation, and none +// of the scanline compositor's area/mask/dirty-area machinery exists here. + +#include "shared-bindings/vectorio/VectorShape.h" + +#include + +#include "py/runtime.h" + +#include "shared-bindings/displayio/ColorConverter.h" +#include "shared-bindings/displayio/Palette.h" +#include "shared-bindings/vectorio/Circle.h" +#include "shared-bindings/vectorio/Polygon.h" +#include "shared-bindings/vectorio/Rectangle.h" +#include "shared-module/displayio/lvgl/lvgl_internal.h" +#include "shared-module/vectorio/__init__.h" + +#if CIRCUITPY_VECTORIO && CIRCUITPY_DISPLAYIO_LVGL + +#define COVERAGE_OPAQUE 0xff + +static bool _is_polygon(vectorio_vector_shape_t *self) { + return mp_obj_is_type(self->ishape.shape, &vectorio_polygon_type); +} + +// The shape's color_index is biased by one so that 0 can always mean "not covered". +static uint16_t _biased_color_index(vectorio_vector_shape_t *self) { + if (mp_obj_is_type(self->ishape.shape, &vectorio_rectangle_type)) { + return ((vectorio_rectangle_t *)MP_OBJ_TO_PTR(self->ishape.shape))->color_index; + } + if (mp_obj_is_type(self->ishape.shape, &vectorio_circle_type)) { + return ((vectorio_circle_t *)MP_OBJ_TO_PTR(self->ishape.shape))->color_index; + } + return ((vectorio_polygon_t *)MP_OBJ_TO_PTR(self->ishape.shape))->color_index; +} + +// The shape's outline color index, still biased by one like its color_index. Polygon has no +// outline: it draws through an A8 mask image, which has no border of its own. +static uint16_t _biased_outline_color_index(vectorio_vector_shape_t *self) { + if (mp_obj_is_type(self->ishape.shape, &vectorio_rectangle_type)) { + return ((vectorio_rectangle_t *)MP_OBJ_TO_PTR(self->ishape.shape))->outline_color_index; + } + if (mp_obj_is_type(self->ishape.shape, &vectorio_circle_type)) { + return ((vectorio_circle_t *)MP_OBJ_TO_PTR(self->ishape.shape))->outline_color_index; + } + return 0; +} + +// Corner radius and outline width in the shape's own pixels. A circle is drawn with +// LV_RADIUS_CIRCLE instead of a stored radius, so its radius is not read here. +static uint16_t _shape_radius(vectorio_vector_shape_t *self) { + if (mp_obj_is_type(self->ishape.shape, &vectorio_rectangle_type)) { + return ((vectorio_rectangle_t *)MP_OBJ_TO_PTR(self->ishape.shape))->radius; + } + return 0; +} + +static uint16_t _shape_outline_width(vectorio_vector_shape_t *self) { + if (mp_obj_is_type(self->ishape.shape, &vectorio_rectangle_type)) { + return ((vectorio_rectangle_t *)MP_OBJ_TO_PTR(self->ishape.shape))->outline_width; + } + if (mp_obj_is_type(self->ishape.shape, &vectorio_circle_type)) { + return ((vectorio_circle_t *)MP_OBJ_TO_PTR(self->ishape.shape))->outline_width; + } + return 0; +} + +// Resolve the pixel shader to the color to paint. Returns false when nothing should be +// drawn at all, which is what the "not covered" color index, a transparent palette entry +// and a ColorConverter's transparent color all mean. +static bool _resolve_color(mp_obj_t pixel_shader, uint16_t biased_index, lv_color_t *color) { + if (biased_index == 0 || pixel_shader == mp_const_none) { + return false; + } + uint32_t index = (uint32_t)biased_index - 1; + if (mp_obj_is_type(pixel_shader, &displayio_palette_type)) { + displayio_palette_t *palette = MP_OBJ_TO_PTR(pixel_shader); + if (index >= common_hal_displayio_palette_get_len(palette) || + common_hal_displayio_palette_is_transparent(palette, index)) { + return false; + } + *color = lv_color_hex(common_hal_displayio_palette_get_color(palette, index)); + return true; + } + displayio_colorconverter_t *converter = MP_OBJ_TO_PTR(pixel_shader); + if (index == converter->transparent_color) { + return false; + } + // A ColorConverter maps a pixel in its input colorspace onto the display's output + // colorspace. LVGL does the output conversion itself while blending, so all that is + // needed here is the rgb888 value of the input pixel. + *color = lv_color_hex(displayio_colorconverter_convert_pixel( + (displayio_colorspace_t)converter->input_colorspace, index)); + return true; +} + +// The shape's extent in its own coordinate space. Rectangles start at the origin, circles +// are centered on it, and polygons use the bounds of their points. This is the same +// geometry the legacy compositor gets from get_area(), just computed where it is needed +// instead of being part of the shape's contract. +// +// The bounds are inclusive of both ends, matching the pixel range the legacy compositor +// asks get_pixel() about: the rectangle covers [0, width) x [0, height), the circle covers +// [-radius, radius] on both axes and the polygon covers the bounding box of its points. +static void _shape_bounds(vectorio_vector_shape_t *self, int32_t *x1, int32_t *y1, int32_t *x2, int32_t *y2) { + if (mp_obj_is_type(self->ishape.shape, &vectorio_rectangle_type)) { + vectorio_rectangle_t *rectangle = MP_OBJ_TO_PTR(self->ishape.shape); + *x1 = 0; + *y1 = 0; + *x2 = rectangle->width - 1; + *y2 = rectangle->height - 1; + return; + } + if (mp_obj_is_type(self->ishape.shape, &vectorio_circle_type)) { + vectorio_circle_t *circle = MP_OBJ_TO_PTR(self->ishape.shape); + *x1 = -(int32_t)circle->radius; + *y1 = -(int32_t)circle->radius; + *x2 = (int32_t)circle->radius; + *y2 = (int32_t)circle->radius; + return; + } + vectorio_polygon_t *polygon = MP_OBJ_TO_PTR(self->ishape.shape); + if (polygon->points_list == NULL || polygon->len < 2) { + *x1 = 0; + *y1 = 0; + *x2 = 0; + *y2 = 0; + return; + } + int32_t min_x = polygon->points_list[0]; + int32_t max_x = min_x; + int32_t min_y = polygon->points_list[1]; + int32_t max_y = min_y; + for (uint16_t i = 2; i + 1 < polygon->len; i += 2) { + int32_t x = polygon->points_list[i]; + int32_t y = polygon->points_list[i + 1]; + if (x < min_x) { + min_x = x; + } + if (x > max_x) { + max_x = x; + } + if (y < min_y) { + min_y = y; + } + if (y > max_y) { + max_y = y; + } + } + *x1 = min_x; + *y1 = min_y; + *x2 = max_x; + *y2 = max_y; +} + +static void _update_visible(vectorio_vector_shape_t *self) { + if (self->lv_obj == NULL) { + return; + } + if (self->hidden || self->hidden_by_parent) { + lv_obj_add_flag(self->lv_obj, LV_OBJ_FLAG_HIDDEN); + } else { + lv_obj_clear_flag(self->lv_obj, LV_OBJ_FLAG_HIDDEN); + } +} + +// Rebuild the polygon coverage mask. LVGL treats an A8 image as a mask and blends it with +// the image recolor color, so the mask only needs to say where the shape is, not what color +// it is. Group scale is baked into the mask resolution, including fractional Q8 scales, which +// reproduces displayio's nearest-neighbor sampling of the shape. +static void _refresh_mask(vectorio_vector_shape_t *self, int32_t x1, int32_t y1, int32_t w, + int32_t h, uint32_t scale) { + if (self->mask == NULL || (int32_t)self->mask->header.w != w || (int32_t)self->mask->header.h != h) { + // The image borrows the mask. Clear its source before freeing the old buffer: + // if the replacement allocation fails it must draw nothing, not freed memory. + lv_image_set_src(self->lv_obj, NULL); + if (self->mask != NULL) { + lv_draw_buf_destroy(self->mask); + self->mask = NULL; + } + self->mask = lv_draw_buf_create(w, h, LV_COLOR_FORMAT_A8, 0); + if (self->mask == NULL) { + return; + } + // Hand the new buffer to the image. The bin decoder wraps a variable A8 image + // instead of copying it, so rewriting the pixels below is visible without dropping + // any cache entry. + lv_image_set_src(self->lv_obj, self->mask); + } + uint32_t stride = self->mask->header.stride; + for (int32_t y = 0; y < h; y++) { + uint8_t *row = self->mask->data + (uint32_t)y * stride; + int16_t shape_y = y1 + (int64_t)y * LV_SCALE_NONE / scale; + for (int32_t x = 0; x < w; x++) { + row[x] = self->ishape.get_pixel(self->ishape.shape, + x1 + (int64_t)x * LV_SCALE_NONE / scale, shape_y) == 0 ? 0 : COVERAGE_OPAQUE; + } + } +} + +// lv_obj_set_pos() only records a style that a later layout pass applies, and lv_obj_move_to() +// leaves that style behind, so an unrelated size change would snap the object back. Set both: the +// coordinates are right immediately and nothing can undo them. +static void _place(lv_obj_t *obj, int32_t x, int32_t y) { + lv_obj_set_style_x(obj, x, 0); + lv_obj_set_style_y(obj, y, 0); + lv_obj_move_to(obj, x, y); +} + +// Push every Python-visible property of the shape into its mirror. Called under the LVGL +// lock from everything that can change the shape. `rebuild_mask` is false for a pure move, +// which is the one change that can't affect the polygon's coverage. +static void _sync_mirror(vectorio_vector_shape_t *self, bool rebuild_mask) { + if (self->lv_obj == NULL) { + return; + } + int32_t x1; + int32_t y1; + int32_t x2; + int32_t y2; + _shape_bounds(self, &x1, &y1, &x2, &y2); + uint32_t scale = self->abs_scale == 0 ? LV_SCALE_NONE : self->abs_scale; + int32_t source_w = x2 - x1 + 1; + int32_t source_h = y2 - y1 + 1; + // A shape with an empty source extent (a rectangle with no width or height) covers no + // pixels at all. A nonempty shape still gets one output pixel when scaled far down. + bool empty = source_w < 1 || source_h < 1; + int32_t w = displayio_lvgl_scale_coordinate(source_w, scale); + int32_t h = displayio_lvgl_scale_coordinate(source_h, scale); + if (w < 1) { + w = 1; + } + if (h < 1) { + h = 1; + } + + bool polygon = _is_polygon(self); + // abs_x/y is the parent group's origin on the screen; groups are screen sized + // objects at the screen origin, so members are positioned in screen coordinates. + _place(self->lv_obj, self->abs_x + displayio_lvgl_scale_coordinate(self->x + x1, scale), + self->abs_y + displayio_lvgl_scale_coordinate(self->y + y1, scale)); + if (lv_obj_get_width(self->lv_obj) != w || lv_obj_get_height(self->lv_obj) != h) { + lv_obj_set_size(self->lv_obj, w, h); + // A new size means a new mask buffer too. + rebuild_mask = true; + } + + lv_color_t color; + bool painted = !empty && _resolve_color(self->pixel_shader, _biased_color_index(self), &color); + + if (polygon) { + if (rebuild_mask) { + _refresh_mask(self, x1, y1, w, h, scale); + } + if (painted) { + lv_obj_set_style_image_recolor(self->lv_obj, color, 0); + } + lv_obj_set_style_image_recolor_opa(self->lv_obj, painted ? LV_OPA_COVER : LV_OPA_TRANSP, 0); + return; + } + + // The fill and the outline are style properties of the same lv_obj, so LVGL draws the + // corners once for the fill and once for the border and neither is recomputed by us. A + // scaled group scales the object's size, so the shape's own pixels have to be scaled too + // to keep the corners and the outline proportional. + bool circle = mp_obj_is_type(self->ishape.shape, &vectorio_circle_type); + int32_t radius = circle ? LV_RADIUS_CIRCLE : + displayio_lvgl_scale_coordinate(_shape_radius(self), scale); + uint16_t outline_width = _shape_outline_width(self); + lv_color_t outline_color; + bool outlined = !empty && outline_width > 0 && + _resolve_color(self->pixel_shader, _biased_outline_color_index(self), &outline_color); + + lv_obj_set_style_radius(self->lv_obj, radius, 0); + lv_obj_set_style_border_width(self->lv_obj, + outlined ? displayio_lvgl_scale_coordinate(outline_width, scale) : 0, 0); + if (painted) { + lv_obj_set_style_bg_color(self->lv_obj, color, 0); + } + lv_obj_set_style_bg_opa(self->lv_obj, painted ? LV_OPA_COVER : LV_OPA_TRANSP, 0); + if (outlined) { + lv_obj_set_style_border_color(self->lv_obj, outline_color, 0); + } + lv_obj_set_style_border_opa(self->lv_obj, outlined ? LV_OPA_COVER : LV_OPA_TRANSP, 0); +} + +// A move changes nothing but where the shape is, so the polygon mask survives it. +static void _set_dirty(vectorio_vector_shape_t *self, bool rebuild_mask) { + if (self->lv_obj == NULL) { + return; + } + displayio_lvgl_lock(); + // The shape's old area has to be redrawn too, and batching below would drop that + // invalidation once the move has already happened. + lv_obj_invalidate(self->lv_obj); + // Batch: the sync writes several styles and only the final invalidation matters. + lv_display_t *display = lv_obj_get_display(self->lv_obj); + if (display != NULL) { + lv_display_enable_invalidation(display, false); + } + _sync_mirror(self, rebuild_mask); + if (display != NULL) { + lv_display_enable_invalidation(display, true); + } + lv_obj_invalidate(self->lv_obj); + displayio_lvgl_unlock(); +} + +void common_hal_vectorio_vector_shape_construct(vectorio_vector_shape_t *self, + vectorio_ishape_t ishape, mp_obj_t pixel_shader, int32_t x, int32_t y) { + x = mp_arg_validate_int_range(x, SHRT_MIN, SHRT_MAX, MP_QSTR_x); + y = mp_arg_validate_int_range(y, SHRT_MIN, SHRT_MAX, MP_QSTR_y); + self->x = x; + self->y = y; + self->pixel_shader = pixel_shader; + self->ishape = ishape; + self->abs_x = 0; + self->abs_y = 0; + self->abs_scale = LV_SCALE_NONE; + self->lv_obj = NULL; + self->mask = NULL; + self->hidden = false; + self->hidden_by_parent = false; + self->in_group = false; +} + +// This must be invoked after each time a shape changes its position, shape or appearance +// in any way. +void common_hal_vectorio_vector_shape_set_dirty(void *vector_shape) { + // The shape itself changed (points, size, color index), so its coverage has to be redone. + _set_dirty(vector_shape, true); +} + +static int32_t _screen_to_shape(int32_t screen, int32_t origin, uint32_t scale) { + int64_t relative = ((int64_t)screen - origin) * LV_SCALE_NONE; + if (relative < 0) { + // Floor division so that negative coordinates map to the pixel that contains them. + return -((-relative + scale - 1) / scale); + } + return relative / scale; +} + +bool common_hal_vectorio_vector_shape_contains(vectorio_vector_shape_t *self, mp_int_t x, mp_int_t y) { + x = mp_arg_validate_int_range(x, SHRT_MIN, SHRT_MAX, MP_QSTR_x); + y = mp_arg_validate_int_range(y, SHRT_MIN, SHRT_MAX, MP_QSTR_y); + uint32_t scale = self->abs_scale == 0 ? LV_SCALE_NONE : self->abs_scale; + int32_t origin_x = self->abs_x + displayio_lvgl_scale_coordinate(self->x, scale); + int32_t origin_y = self->abs_y + displayio_lvgl_scale_coordinate(self->y, scale); + int16_t shape_x = (int16_t)_screen_to_shape(x, origin_x, scale); + int16_t shape_y = (int16_t)_screen_to_shape(y, origin_y, scale); + return self->ishape.get_pixel(self->ishape.shape, shape_x, shape_y) != 0; +} + +mp_int_t common_hal_vectorio_vector_shape_get_x(vectorio_vector_shape_t *self) { + return self->x; +} + +void common_hal_vectorio_vector_shape_set_x(vectorio_vector_shape_t *self, mp_int_t x) { + if (self->x == x) { + return; + } + self->x = mp_arg_validate_int_range(x, SHRT_MIN, SHRT_MAX, MP_QSTR_x); + _set_dirty(self, false); +} + +mp_int_t common_hal_vectorio_vector_shape_get_y(vectorio_vector_shape_t *self) { + return self->y; +} + +void common_hal_vectorio_vector_shape_set_y(vectorio_vector_shape_t *self, mp_int_t y) { + if (self->y == y) { + return; + } + self->y = mp_arg_validate_int_range(y, SHRT_MIN, SHRT_MAX, MP_QSTR_y); + _set_dirty(self, false); +} + +mp_obj_tuple_t *common_hal_vectorio_vector_shape_get_location(vectorio_vector_shape_t *self) { + mp_obj_tuple_t *pair = MP_OBJ_TO_PTR(mp_obj_new_tuple(2, NULL)); + pair->items[0] = mp_obj_new_int((mp_int_t)self->x); + pair->items[1] = mp_obj_new_int((mp_int_t)self->y); + return pair; +} + +void common_hal_vectorio_vector_shape_set_location(vectorio_vector_shape_t *self, mp_obj_t xy) { + size_t tuple_len = 0; + mp_obj_t *tuple_items; + mp_obj_tuple_get(xy, &tuple_len, &tuple_items); + mp_arg_validate_length(tuple_len, 2, MP_QSTR_location); + + mp_int_t x = mp_arg_validate_type_int(tuple_items[0], MP_QSTR_x); + mp_int_t y = mp_arg_validate_type_int(tuple_items[1], MP_QSTR_y); + x = mp_arg_validate_int_range(x, SHRT_MIN, SHRT_MAX, MP_QSTR_x); + y = mp_arg_validate_int_range(y, SHRT_MIN, SHRT_MAX, MP_QSTR_y); + if (self->x == x && self->y == y) { + return; + } + self->x = x; + self->y = y; + _set_dirty(self, false); +} + +mp_int_t common_hal_vectorio_vector_shape_get_hidden(vectorio_vector_shape_t *self) { + return self->hidden; +} + +void common_hal_vectorio_vector_shape_set_hidden(vectorio_vector_shape_t *self, bool hidden) { + self->hidden = hidden; + if (self->lv_obj != NULL) { + displayio_lvgl_lock(); + _update_visible(self); + displayio_lvgl_unlock(); + } + _set_dirty(self, false); +} + +mp_obj_t common_hal_vectorio_vector_shape_get_pixel_shader(vectorio_vector_shape_t *self) { + return self->pixel_shader; +} + +void common_hal_vectorio_vector_shape_set_pixel_shader(vectorio_vector_shape_t *self, mp_obj_t pixel_shader) { + if (self->pixel_shader != pixel_shader) { + displayio_lvgl_shader_unregister_user(self->pixel_shader, self); + self->pixel_shader = pixel_shader; + if (self->lv_obj != NULL) { + displayio_lvgl_shader_register_user(pixel_shader, + self, DISPLAYIO_LVGL_USER_VECTOR_SHAPE); + } + } + // A different shader is a different color, not different coverage. + _set_dirty(self, false); +} + +bool vectorio_vector_shape_set_in_group(vectorio_vector_shape_t *self, bool in_group) { + bool was_in_group = self->in_group; + self->in_group = in_group; + return was_in_group; +} + +void displayio_lvgl_vector_shape_attach(vectorio_vector_shape_t *self, lv_obj_t *parent) { + if (parent == NULL || !self->in_group) { + return; + } + displayio_lvgl_lock(); + if (self->lv_obj == NULL) { + bool polygon = _is_polygon(self); + self->lv_obj = polygon ? lv_image_create(parent) : lv_obj_create(parent); + if (self->lv_obj == NULL) { + displayio_lvgl_unlock(); + return; + } + // Take the theme out of the picture so the shape is exactly what we style it to be. + lv_obj_remove_style_all(self->lv_obj); + lv_obj_set_style_pad_all(self->lv_obj, 0, 0); + lv_obj_set_style_border_width(self->lv_obj, 0, 0); + lv_obj_set_style_border_side(self->lv_obj, LV_BORDER_SIDE_FULL, 0); + lv_obj_set_style_radius(self->lv_obj, 0, 0); + lv_obj_set_style_bg_opa(self->lv_obj, LV_OPA_TRANSP, 0); + lv_obj_set_style_opa(self->lv_obj, LV_OPA_COVER, 0); + if (polygon) { + lv_obj_set_style_image_opa(self->lv_obj, LV_OPA_COVER, 0); + } + lv_obj_clear_flag(self->lv_obj, LV_OBJ_FLAG_CLICKABLE); + lv_obj_clear_flag(self->lv_obj, LV_OBJ_FLAG_SCROLLABLE); + _update_visible(self); + _sync_mirror(self, true); + } else if (lv_obj_get_parent(self->lv_obj) != parent) { + lv_obj_set_parent(self->lv_obj, parent); + } + displayio_lvgl_shader_register_user(self->pixel_shader, + self, DISPLAYIO_LVGL_USER_VECTOR_SHAPE); + displayio_lvgl_unlock(); +} + +void displayio_lvgl_vector_shape_detach(vectorio_vector_shape_t *self) { + displayio_lvgl_shader_unregister_user(self->pixel_shader, self); + if (self->lv_obj == NULL) { + return; + } + displayio_lvgl_lock(); + lv_obj_delete(self->lv_obj); + self->lv_obj = NULL; + if (self->mask != NULL) { + lv_draw_buf_destroy(self->mask); + self->mask = NULL; + } + displayio_lvgl_unlock(); +} + +void displayio_lvgl_vector_shape_set_transform(vectorio_vector_shape_t *self, int32_t abs_x, + int32_t abs_y, uint32_t scale) { + if (self->abs_x == abs_x && self->abs_y == abs_y && self->abs_scale == scale) { + return; + } + self->abs_x = abs_x; + self->abs_y = abs_y; + uint32_t previous_scale = self->abs_scale; + self->abs_scale = scale == 0 ? LV_SCALE_NONE : scale; + // The mask is rasterized at the scaled resolution, so a scale change rebuilds it. + _set_dirty(self, self->abs_scale != previous_scale); +} + +void displayio_lvgl_vector_shape_set_hidden_by_parent(vectorio_vector_shape_t *self, bool hidden) { + self->hidden_by_parent = hidden; + if (self->lv_obj != NULL) { + displayio_lvgl_lock(); + _update_visible(self); + lv_obj_invalidate(self->lv_obj); + displayio_lvgl_unlock(); + } +} + +void displayio_lvgl_vector_shape_shader_changed(vectorio_vector_shape_t *self) { + // Called with the LVGL lock held by the shader's notify path. + _sync_mirror(self, false); +} + +// protocol_lvgl implementation. Group owns the tree; these only translate its calls into the +// shape mirror operations above. +static lv_obj_t *_vector_shape_protocol_root_obj(mp_obj_t layer) { + return ((vectorio_vector_shape_t *)MP_OBJ_TO_PTR(layer))->lv_obj; +} + +static void _vector_shape_protocol_attach(mp_obj_t layer, lv_obj_t *parent) { + displayio_lvgl_vector_shape_attach(MP_OBJ_TO_PTR(layer), parent); +} + +static void _vector_shape_protocol_detach(mp_obj_t layer) { + displayio_lvgl_vector_shape_detach(MP_OBJ_TO_PTR(layer)); +} + +static bool _vector_shape_protocol_set_transform(mp_obj_t layer, int32_t abs_x, + int32_t abs_y, uint32_t scale) { + displayio_lvgl_vector_shape_set_transform(MP_OBJ_TO_PTR(layer), abs_x, abs_y, scale); + return true; +} + +static void _vector_shape_protocol_set_hidden_by_parent(mp_obj_t layer, bool hidden) { + displayio_lvgl_vector_shape_set_hidden_by_parent(MP_OBJ_TO_PTR(layer), hidden); +} + +static bool _vector_shape_protocol_set_in_group(mp_obj_t layer, bool in_group) { + return vectorio_vector_shape_set_in_group(MP_OBJ_TO_PTR(layer), in_group); +} + +const lvgl_protocol_t displayio_lvgl_vector_shape_protocol = { + MP_PROTO_IMPLEMENT(MP_QSTR_protocol_lvgl) + .root_obj = _vector_shape_protocol_root_obj, + .attach = _vector_shape_protocol_attach, + .detach = _vector_shape_protocol_detach, + .set_transform = _vector_shape_protocol_set_transform, + .set_hidden_by_parent = _vector_shape_protocol_set_hidden_by_parent, + .set_in_group = _vector_shape_protocol_set_in_group, +}; + +#endif // CIRCUITPY_VECTORIO && CIRCUITPY_DISPLAYIO_LVGL diff --git a/shared-module/vectorio/lvgl/VectorShape.h b/shared-module/vectorio/lvgl/VectorShape.h new file mode 100644 index 00000000000..3aac6ac0bfb --- /dev/null +++ b/shared-module/vectorio/lvgl/VectorShape.h @@ -0,0 +1,68 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include + +#include "py/obj.h" + +#include "shared-module/displayio/lvgl/lvgl_protocol.h" + +#include "lvgl.h" + +// LVGL compositor state for a vector shape. +// +// Each shape is mirrored into exactly one lv_obj, so LVGL owns drawing, clipping and +// invalidation. There are no dirty areas, no masks and no screen-space footprint here; +// that bookkeeping only exists because the scanline compositor has no invalidation. +// +// Rectangle, Circle - a plain lv_obj drawn entirely with styles (background color and +// opacity, plus LV_RADIUS_CIRCLE for circles). No draw callback and no per-shape +// pixel memory. +// Polygon - an lv_image whose source is an A8 coverage mask rasterized from the shape's +// winding rule, tinted with the image recolor styles. The mask is rebuilt when the +// shape changes, so a frame costs one A8 blend. +// +// Group scale is applied in Q8 fixed point by scaling the mirror's position, size and mask +// resolution instead of using lv_obj transform styles. Transform styles route the object through an +// ARGB8888 transform layer that cannot be sliced, which would defeat partial redraw and replace +// displayio's nearest-neighbor scaling with bilinear filtering. See +// shared-module/displayio/lvgl/Group.c for the same reasoning applied to TileGrids. + +typedef struct { + mp_obj_base_t base; + vectorio_ishape_t ishape; + mp_obj_t pixel_shader; + int16_t x; + int16_t y; + // Absolute position of the parent group's origin plus the group scale inherited from + // it. Groups are screen sized objects at the screen origin, so the mirror is placed + // in screen coordinates from these. + int32_t abs_x; + int32_t abs_y; + uint32_t abs_scale; + lv_obj_t *lv_obj; // Mirror: lv_obj for rectangles and circles, lv_image for polygons. + lv_draw_buf_t *mask; // Polygon coverage (A8), NULL for the style-drawn shapes. + bool hidden : 1; + bool hidden_by_parent : 1; + bool in_group : 1; + uint8_t padding : 5; +} vectorio_vector_shape_t; + +// Mirror lifecycle. Implemented in shared-module/vectorio/lvgl/VectorShape.c and called +// from shared-module/displayio/lvgl/Group.c, which owns the object tree. +void displayio_lvgl_vector_shape_attach(vectorio_vector_shape_t *self, lv_obj_t *parent); +void displayio_lvgl_vector_shape_detach(vectorio_vector_shape_t *self); +void displayio_lvgl_vector_shape_set_transform(vectorio_vector_shape_t *self, int32_t abs_x, + int32_t abs_y, uint32_t scale); +void displayio_lvgl_vector_shape_set_hidden_by_parent(vectorio_vector_shape_t *self, bool hidden); +// A pixel shader this shape registered with has changed. +void displayio_lvgl_vector_shape_shader_changed(vectorio_vector_shape_t *self); + +// How Group attaches, positions and hides a shape. See lvgl_protocol.h. +extern const lvgl_protocol_t displayio_lvgl_vector_shape_protocol; diff --git a/shared-module/videocore/VideoBuffer.c b/shared-module/videocore/VideoBuffer.c new file mode 100644 index 00000000000..928f82a1046 --- /dev/null +++ b/shared-module/videocore/VideoBuffer.c @@ -0,0 +1,679 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include + +#include "shared-module/videocore/VideoBuffer.h" + +#include "py/runtime.h" + +#include "shared-bindings/displayio/Group.h" +#include "shared-bindings/microcontroller/__init__.h" +#include "shared-bindings/videocore/VideoBuffer.h" +#include "shared-bindings/videocore/__init__.h" +#include "shared-module/displayio/Group.h" +#include "shared-module/videocore/__init__.h" + +#if CIRCUITPY_FRAMEBUFFERIO +#include "shared-bindings/framebufferio/FramebufferDisplay.h" +#endif + +// Add the screen area of a frame that landed at frame to vacated_area. Uses +// only the cached framebuffer geometry since this runs in interrupt context. +// A shifted frame can start mid-row and wrap its rows; then cover the full +// width. +static void videocore_videobuffer_add_vacated_frame(videocore_videobuffer_obj_t *self, const void *frame) { + const size_t bytes_per_pixel = self->source_bits_per_pixel / 8; + const uint8_t *pixels = self->fb_pixels; + if (pixels == NULL || bytes_per_pixel == 0 || self->fb_row_stride == 0 || + (const uint8_t *)frame < pixels) { + return; // Plain buffer frames are never shown where they land. + } + const size_t offset = (const uint8_t *)frame - pixels; + if (offset >= self->fb_pixels_len) { + return; + } + displayio_area_t area = { + .x1 = (offset % self->fb_row_stride) / bytes_per_pixel, + .y1 = offset / self->fb_row_stride, + }; + area.x2 = area.x1 + self->source_width; + area.y2 = area.y1 + self->source_height; + if (area.x2 > self->fb_width) { + area.x1 = 0; + area.x2 = self->fb_width; + area.y2 += 1; + } + displayio_area_union(&self->vacated_area.area, &area, &self->vacated_area.area); +} + +// Called from interrupt context or a background task when the source lands a +// frame, so keep it tiny. +static void videocore_videobuffer_on_frame(void *ctx, const void *frame, const displayio_area_t *changed) { + videocore_videobuffer_obj_t *self = ctx; + if (frame != self->stream_base) { + // It landed where the video used to be (the frame in flight when it + // moved or paused). Repaint there, since that area may already have + // been repainted. + videocore_videobuffer_add_vacated_frame(self, frame); + } + videocore_videobuffer_backend_on_frame(self, frame, changed); +} + +// Called from interrupt context or a background task when the source reached +// the end of its stream. Only flag it: end_stream stops the source later, the +// way audio outputs stop a finished sample. +static void videocore_videobuffer_on_stream_end(void *ctx) { + videocore_videobuffer_obj_t *self = ctx; + self->source_ended = true; +} + +// Drop any landed frame the refresh hasn't taken yet. +void videocore_videobuffer_forget_frame(videocore_videobuffer_obj_t *self) { + videocore_videobuffer_backend_forget_frame(self); +} + +// Cache the framebuffer geometry for on_frame (see fb_pixels). +static void videocore_videobuffer_cache_fb_geometry(videocore_videobuffer_obj_t *self, + const mp_buffer_info_t *bufinfo, mp_int_t fb_width, mp_int_t fb_height, + mp_int_t row_stride, mp_int_t first_pixel_offset) { + self->fb_pixels = (const uint8_t *)bufinfo->buf + first_pixel_offset; + self->fb_pixels_len = bufinfo->len - first_pixel_offset; + self->fb_row_stride = row_stride; + self->fb_width = fb_width; + self->fb_height = fb_height; +} + +// Compute the rect (in screen coordinates, which are the framebuffer's +// physical coordinates) that a frame written at the logical position x/y +// covers. A framebuffer target's frames are never rotated, and a rotated +// display is rejected when its transform is applied, so the transform only +// translates: the rect is source_width wide and source_height tall. A video +// that isn't shown has no transform, which translates by nothing, so the +// areas reported while detached stay sensible. +static void videocore_videobuffer_frame_rect(videocore_videobuffer_obj_t *self, + mp_int_t x, mp_int_t y, videocore_area_t *area) { + const displayio_buffer_transform_t *t = &self->absolute_transform; + area->area.x1 = t->x + x; + area->area.y1 = t->y + y; + area->area.x2 = area->area.x1 + self->source_width; + area->area.y2 = area->area.y1 + self->source_height; + area->next = NULL; +} + + +// Map a point in the source's coordinates (0, 0 to source_width/ +// source_height) to screen coordinates, which are the framebuffer's physical +// coordinates. A plain buffer target is rotated with the display as displayio +// copies its pixels, so both axes can be mirrored and swapped. The transform +// is only ever a translation plus mirroring and/or transposing (scale 1), +// which this relies on. While the video isn't shown there is no transform, so +// the point keeps its plain x/y position. +static void videocore_videobuffer_source_point(videocore_videobuffer_obj_t *self, + mp_int_t source_x, mp_int_t source_y, mp_int_t *screen_x, mp_int_t *screen_y) { + const displayio_buffer_transform_t *t = &self->absolute_transform; + const mp_int_t x = self->x + source_x; + const mp_int_t y = self->y + source_y; + if (t->scale == 0) { + // Not on a display, so there is no transform to apply. Keep the plain + // position so the areas reported while detached stay sensible. + *screen_x = x; + *screen_y = y; + } else if (t->transpose_xy) { + // The local y axis becomes screen x and the local x axis screen y. + *screen_x = t->x + t->dx * y; + *screen_y = t->y + t->dy * x; + } else { + *screen_x = t->x + t->dx * x; + *screen_y = t->y + t->dy * y; + } +} + +// Map a rect in source coordinates to the screen rect it covers once it is +// rotated. Mirroring and transposing a rect keeps it axis aligned, only +// swapping its width and height on a transposed (90 or 270 degree) display. +void videocore_videobuffer_source_rect(videocore_videobuffer_obj_t *self, + const displayio_area_t *source, videocore_area_t *screen) { + mp_int_t x1; + mp_int_t y1; + mp_int_t x2; + mp_int_t y2; + videocore_videobuffer_source_point(self, source->x1, source->y1, &x1, &y1); + videocore_videobuffer_source_point(self, source->x2, source->y2, &x2, &y2); + screen->area.x1 = MIN(x1, x2); + screen->area.y1 = MIN(y1, y2); + screen->area.x2 = MAX(x1, x2); + screen->area.y2 = MAX(y1, y2); + screen->next = NULL; +} + +// Recompute the rendered rect of the video from the x/y position and the +// absolute transform. A framebuffer target only follows the transform's +// position because its frames are never rotated. A plain buffer target is +// rotated with the display, so its whole frame is transformed. +void videocore_videobuffer_update_area(videocore_videobuffer_obj_t *self) { + if (self->framebuffer_protocol != NULL) { + videocore_videobuffer_frame_rect(self, self->x, self->y, &self->current_area); + return; + } + displayio_area_t whole = { + .x2 = self->source_width, + .y2 = self->source_height, + }; + videocore_videobuffer_source_rect(self, &whole, &self->current_area); +} + +// Bytes in one row of a source frame. 1-bit pixels are packed and each row is +// padded to a whole byte. Framebuffer targets always use whole bytes (see +// read_source_format). +static size_t videocore_videobuffer_row_bytes(mp_int_t width, mp_int_t bits_per_pixel) { + return ((size_t)width * bits_per_pixel + 7) / 8; +} + +static size_t videocore_videobuffer_source_row_bytes(videocore_videobuffer_obj_t *self) { + return videocore_videobuffer_row_bytes(self->source_width, self->source_bits_per_pixel); +} + +// Bytes a frame covers in a framebuffer with this row stride, from its first +// pixel. A contiguous DMA (the camera) writes frame_bytes in a row; a source +// that honors the stride (a GIF) ends its last row (height - 1) strides in. +// The frame must fit either way. +static mp_int_t videocore_videobuffer_frame_span(videocore_videobuffer_obj_t *self, mp_int_t row_stride) { + const mp_int_t strided = (self->source_height - 1) * row_stride + + videocore_videobuffer_source_row_bytes(self); + return MAX((mp_int_t)self->source_frame_bytes, strided); +} + +// Compute the destination for the current position, including a containing +// group's translation. Raises unless the whole frame fits in the target, +// whether the source writes it contiguously or at the target's stride. +// move_dest() is the non-raising variant used from displayio. +static void videocore_videobuffer_compute_destination( + videocore_videobuffer_obj_t *self, videocore_destination_t *dest) { + const size_t bytes_per_pixel = self->source_bits_per_pixel / 8; + const size_t row_bytes = videocore_videobuffer_source_row_bytes(self); + + if (self->framebuffer_protocol == NULL) { + // Raw buffer mode: frames are written compactly from the start. + dest->base = self->bufinfo.buf; + dest->stride = row_bytes; + dest->row_bytes = row_bytes; + dest->height = self->source_height; + // draw_fill_area swaps the bytes for displays that need it. + dest->reverse_bytes_in_word = false; + dest->on_stream_end = videocore_videobuffer_on_stream_end; + if (self->bufinfo.len < self->source_frame_bytes) { + mp_raise_ValueError(MP_ERROR_TEXT("Buffer too small")); + } + return; + } + + mp_buffer_info_t bufinfo; + self->framebuffer_protocol->get_bufinfo(self->framebuffer, &bufinfo); + if (bufinfo.buf == NULL) { + mp_raise_ValueError(MP_ERROR_TEXT("framebuffer went away")); + } + + const mp_int_t fb_width = FB_GETTER(get_width, 0); + const mp_int_t fb_height = FB_GETTER(get_height, 0); + const mp_int_t row_stride = FB_GETTER(get_row_stride, fb_width * self->source_bits_per_pixel / 8); + const mp_int_t first_pixel_offset = FB_GETTER(get_first_pixel_offset, 0); + + // Frames keep the framebuffer's orientation: the containing group's + // transform only translates them. The whole frame must stay within the + // framebuffer and the buffer. + videocore_area_t rect; + videocore_videobuffer_frame_rect(self, self->x, self->y, &rect); + if (self->x < 0 || self->y < 0 || + rect.area.x1 < 0 || rect.area.y1 < 0 || + rect.area.x2 > fb_width || rect.area.y2 > fb_height || + first_pixel_offset + rect.area.y1 * row_stride + rect.area.x1 * bytes_per_pixel + + videocore_videobuffer_frame_span(self, row_stride) > + bufinfo.len) { + mp_raise_ValueError(MP_ERROR_TEXT("video doesn't fit in framebuffer")); + } + videocore_videobuffer_cache_fb_geometry( + self, &bufinfo, fb_width, fb_height, row_stride, first_pixel_offset); + + dest->base = (uint8_t *)bufinfo.buf + first_pixel_offset + + rect.area.y1 * row_stride + rect.area.x1 * bytes_per_pixel; + dest->stride = row_stride; + dest->row_bytes = row_bytes; + dest->height = self->source_height; + dest->reverse_bytes_in_word = FB_GETTER(get_reverse_pixels_in_word, false); + dest->on_stream_end = videocore_videobuffer_on_stream_end; +} + +// Move the framebuffer destination for a new absolute position, capping the +// shift so the frame stays completely within the framebuffer. Best effort: +// never raises, because this runs from displayio's refresh. +void videocore_videobuffer_move_dest(videocore_videobuffer_obj_t *self) { + if (!self->playing || self->paused) { + return; + } + mp_buffer_info_t bufinfo; + self->framebuffer_protocol->get_bufinfo(self->framebuffer, &bufinfo); + if (bufinfo.buf == NULL) { + return; + } + const size_t bytes_per_pixel = self->source_bits_per_pixel / 8; + const size_t row_bytes = videocore_videobuffer_source_row_bytes(self); + const mp_int_t fb_width = FB_GETTER(get_width, 0); + const mp_int_t fb_height = FB_GETTER(get_height, 0); + const mp_int_t row_stride = FB_GETTER(get_row_stride, fb_width * self->source_bits_per_pixel / 8); + const mp_int_t first_pixel_offset = FB_GETTER(get_first_pixel_offset, 0); + if (row_stride <= 0 || bytes_per_pixel == 0) { + return; + } + + videocore_area_t rect; + videocore_videobuffer_frame_rect(self, self->x, self->y, &rect); + mp_int_t shift_x = MAX(rect.area.x1, 0); + mp_int_t shift_y = MAX(rect.area.y1, 0); + // Cap the start and the end. Cap the rows first: enough rows must fit + // above the frame for it to fit at all. + const mp_int_t max_end = (mp_int_t)bufinfo.len - first_pixel_offset - + videocore_videobuffer_frame_span(self, row_stride); + const mp_int_t buf_max_y = max_end / row_stride; + const mp_int_t max_y = MIN(fb_height - self->source_height, buf_max_y); + if (shift_y > max_y) { + shift_y = MAX(max_y, 0); + } + const mp_int_t buf_max_x = + (max_end - shift_y * row_stride) / (mp_int_t)bytes_per_pixel; + const mp_int_t max_x = MIN(fb_width - self->source_width, buf_max_x); + if (shift_x > max_x) { + shift_x = MAX(max_x, 0); + } + videocore_videobuffer_cache_fb_geometry( + self, &bufinfo, fb_width, fb_height, row_stride, first_pixel_offset); + + videocore_destination_t dest = { + .base = bufinfo.buf + first_pixel_offset + shift_y * row_stride + shift_x * bytes_per_pixel, + .stride = row_stride, + .row_bytes = row_bytes, + .height = self->source_height, + .reverse_bytes_in_word = FB_GETTER(get_reverse_pixels_in_word, false), + .on_stream_end = videocore_videobuffer_on_stream_end, + }; + // A rejected destination leaves the stream where it was. + if (videosource_set_destination(self->source, &dest, videocore_videobuffer_on_frame, self)) { + self->stream_base = dest.base; + videocore_videobuffer_backend_source_changed(self); + } +} + +void common_hal_videocore_videobuffer_construct(videocore_videobuffer_obj_t *self, mp_obj_t framebuffer, + mp_int_t bits_per_pixel) { + // Initialise what the finaliser uses before anything can raise. + self->source = mp_const_none; + self->stream_base = NULL; + self->playing = false; + // The finaliser can run after any of the raises below, so the backend state + // has to be valid before anything else can fail. + videocore_videobuffer_backend_construct(self); + displayio_area_t empty = {}; + self->current_area.area = empty; + self->current_area.next = NULL; + self->vacated_area.area = empty; + self->vacated_area.next = NULL; + self->framebuffer = framebuffer; + self->framebuffer_protocol = mp_proto_get(MP_QSTR_protocol_framebuffer, framebuffer); + if (self->framebuffer_protocol != NULL) { + if (self->framebuffer_protocol->get_bufinfo == NULL || + self->framebuffer_protocol->get_width == NULL || + self->framebuffer_protocol->get_height == NULL) { + mp_raise_ValueError(MP_ERROR_TEXT("framebuffer missing required functions")); + } + self->bits_per_pixel = FB_GETTER(get_color_depth, 16); + } else if (!mp_get_buffer(framebuffer, &self->bufinfo, MP_BUFFER_WRITE)) { + // Not a framebuffer and not a writable buffer such as a bytearray or + // memoryview. + mp_raise_TypeError_varg(MP_ERROR_TEXT("%q must be of type %q or %q, not %q"), + MP_QSTR_framebuffer, MP_QSTR_buffer, MP_QSTR_framebuffer, + mp_obj_get_type(framebuffer)->name); + } else { + self->bits_per_pixel = bits_per_pixel; + } + + self->x = 0; + self->y = 0; + self->fb_pixels = NULL; + self->fb_pixels_len = 0; + self->fb_row_stride = 0; + self->fb_width = 0; + self->fb_height = 0; + self->in_group = false; + self->hidden = false; + self->stale_size = false; + self->source_ended = false; + displayio_buffer_transform_t empty_transform = {}; + self->absolute_transform = empty_transform; + // Nothing is shown until a Group attached to a display updates our + // transform. + self->paused = true; +} + +// Record the started source's frame format, which is fixed until stop. May +// raise. +static void videocore_videobuffer_read_source_format(videocore_videobuffer_obj_t *self) { + mp_obj_t source = self->source; + const videosource_p_t *protocol = videosource_check(source); + + mp_int_t bits_per_pixel = protocol->get_bits_per_pixel(source); + // Whole bytes per pixel, or 1 bit packed into each byte. + if (bits_per_pixel % 8 != 0 && bits_per_pixel != 1) { + mp_raise_ValueError(MP_ERROR_TEXT("video format must be byte aligned")); + } + mp_int_t width = protocol->get_width(source); + mp_int_t height = protocol->get_height(source); + size_t frame_bytes = (size_t)height * videocore_videobuffer_row_bytes(width, bits_per_pixel); + + if (self->framebuffer_protocol != NULL) { + mp_int_t color_depth = FB_GETTER(get_color_depth, 16); + if (color_depth % 8 != 0 || bits_per_pixel != color_depth) { + mp_raise_ValueError(MP_ERROR_TEXT("video format doesn't match framebuffer")); + } + } else { + videocore_videobuffer_backend_check_buffer_format(self, bits_per_pixel); + } + + self->source_width = width; + self->source_height = height; + self->source_bits_per_pixel = bits_per_pixel; + self->source_frame_bytes = frame_bytes; + + if (self->framebuffer_protocol == NULL && (mp_int_t)self->bufinfo.len < (mp_int_t)frame_bytes) { + mp_raise_ValueError(MP_ERROR_TEXT("Buffer too small")); + } +} + +// Point a started source at the current destination and let it stream. Runs +// from Python contexts (play and draw_update_transform) so it may raise. +static void videocore_videobuffer_start_stream(videocore_videobuffer_obj_t *self) { + videocore_destination_t dest; + videocore_videobuffer_compute_destination(self, &dest); + + // The source streams from now on; on_frame reports each frame. + if (!videosource_set_destination(self->source, &dest, videocore_videobuffer_on_frame, self)) { + mp_raise_ValueError(MP_ERROR_TEXT("video source rejected the destination")); + } + self->stream_base = dest.base; + self->paused = false; + videocore_videobuffer_backend_stream_changed(self); +} + +// Un-show a framebuffer target by pausing its source. The play session and +// the source's hardware stay alive, but no frames are written to the target. +// Best effort: this also runs during display reset, so errors are ignored. +static void videocore_videobuffer_pause_stream(videocore_videobuffer_obj_t *self) { + if (self->paused || self->source == mp_const_none) { + return; // Already paused, or nothing has been started yet. + } + // Drop the destination before pausing the source: the source finishes its + // pause at the next frame boundary, so the frame being written still + // lands after this, and on_frame adds it to vacated_area to repaint over. + self->stream_base = NULL; + self->paused = true; + videocore_videobuffer_backend_stream_changed(self); + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + videosource_pause(self->source); + nlr_pop(); + } + videocore_videobuffer_forget_frame(self); +} + +// Re-show a framebuffer target by pointing its paused source at the current +// destination and resuming it. Position changes while hidden are applied here; +// the source's format was fixed at play(), so reject a changed source rather +// than resuming into a wrong-sized frame. +static void videocore_videobuffer_resume_stream(videocore_videobuffer_obj_t *self) { + const videosource_p_t *protocol = videosource_check(self->source); + if (protocol->get_width(self->source) != self->source_width || + protocol->get_height(self->source) != self->source_height || + protocol->get_bits_per_pixel(self->source) != self->source_bits_per_pixel) { + self->stale_size = true; + return; + } + + videocore_destination_t dest; + videocore_videobuffer_compute_destination(self, &dest); + if (!videosource_set_destination(self->source, &dest, videocore_videobuffer_on_frame, self)) { + mp_raise_ValueError(MP_ERROR_TEXT("video source rejected the destination")); + } + videosource_resume(self->source); + self->stream_base = dest.base; + self->paused = false; + // Wait for the first frame at the new destination. + videocore_videobuffer_forget_frame(self); + videocore_videobuffer_backend_stream_changed(self); +} + +// Stop a source that reached the end of its stream. stream_base stays, so the +// last frame stays shown until stop() or the next play(). Never raises. +void videocore_videobuffer_end_stream(videocore_videobuffer_obj_t *self) { + if (!self->playing || !self->source_ended) { + return; + } + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + videosource_stop(self->source); + nlr_pop(); + } + self->playing = false; + self->source = mp_const_none; +} + +// Start, resume or pause a framebuffer target's source to match whether it is +// shown (on a display and not hidden). While hidden the source stays active +// but paused, so showing it again is quick. +void videocore_videobuffer_update_stream(videocore_videobuffer_obj_t *self) { + if (self->framebuffer_protocol == NULL) { + return; // Plain buffer targets always stream. + } + // An ended source must not resume. + videocore_videobuffer_end_stream(self); + const bool shown = videocore_videobuffer_backend_shown(self); + if (!self->playing) { + // Remember whether the target is shown so play() can start the source + // in the right state. + self->paused = !shown; + if (!shown) { + // A repaint overwrites an ended stream's last frame. + self->stream_base = NULL; + } + videocore_videobuffer_backend_stream_changed(self); + return; + } + if (shown && !self->stale_size) { + if (self->paused) { + videocore_videobuffer_resume_stream(self); + } + } else if (!shown && !self->paused) { + videocore_videobuffer_pause_stream(self); + } + videocore_videobuffer_backend_stream_changed(self); +} + +void common_hal_videocore_videobuffer_play(videocore_videobuffer_obj_t *self, mp_obj_t source) { + videocore_videobuffer_end_stream(self); + if (self->playing) { + mp_raise_RuntimeError(MP_ERROR_TEXT("already playing")); + } + if (!videosource_set_bits_per_pixel(source, self->bits_per_pixel)) { + mp_arg_error_invalid(MP_QSTR_bits_per_pixel); + } + self->stale_size = false; + self->source_ended = false; + videocore_videobuffer_forget_frame(self); + // An ended stream's last frame stays until repainted, and the format is about to change. + self->stream_base = NULL; + + // A framebuffer target only streams while shown. When it isn't, start the + // source paused rather than pausing it afterwards, so no frame slips out + // in between. Plain buffer targets always stream. + const bool start_paused = self->framebuffer_protocol != NULL && self->paused; + // If this raises the source may be playing elsewhere, so leave it alone. + videosource_play(source, start_paused); + self->source = source; + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + videocore_videobuffer_read_source_format(self); + videocore_videobuffer_update_area(self); + self->playing = true; + // A paused source gets its destination when the VideoBuffer is shown. + if (!start_paused) { + videocore_videobuffer_start_stream(self); + } + videocore_videobuffer_backend_source_changed(self); + nlr_pop(); + } else { + videocore_videobuffer_stop_quiet(self); + nlr_raise(nlr.ret_val); + } +} + +void common_hal_videocore_videobuffer_set_position(videocore_videobuffer_obj_t *self, mp_int_t x, mp_int_t y) { + if (self->framebuffer_protocol != NULL && x != 0) { + // A contiguous source (the camera) ignores the stride, so every frame + // row must land on a framebuffer row: the video's x must be 0. + mp_raise_ValueError(MP_ERROR_TEXT("video in a framebuffer must be at x == 0")); + } + videocore_videobuffer_end_stream(self); + // Repaint where the video used to be. Union (rather than overwrite) so a + // move before the previous one was refreshed isn't lost. + videocore_videobuffer_backend_dirty_current_area(self); + self->x = x; + self->y = y; + videocore_videobuffer_update_area(self); + if (self->framebuffer_protocol == NULL) { + // Draw the last frame at its new position. + videocore_videobuffer_backend_dirty_current_area(self); + } + if (!self->playing && self->framebuffer_protocol != NULL) { + // A repaint overwrites an ended stream's last frame. + self->stream_base = NULL; + } + if (!self->playing || self->paused || self->framebuffer_protocol == NULL) { + // Raw buffer targets are rendered by displayio; their capture + // destination doesn't move with the position. A paused framebuffer + // target has no destination to move yet. + videocore_videobuffer_backend_source_changed(self); + return; + } + // The source's frame size was fixed when play() was called. Reject + // sources that changed it (e.g. a sensor mode change) rather than + // blitting at stale geometry. + const videosource_p_t *protocol = videosource_check(self->source); + mp_int_t width = protocol->get_width(self->source); + mp_int_t height = protocol->get_height(self->source); + mp_int_t bits_per_pixel = protocol->get_bits_per_pixel(self->source); + if (width != self->source_width || height != self->source_height || + bits_per_pixel != self->source_bits_per_pixel) { + mp_raise_ValueError(MP_ERROR_TEXT("video size changed since play; stop and play again")); + } + // The source picks up the new destination on its next frame. A rejected + // destination leaves the stream where it was. + videocore_destination_t dest; + videocore_videobuffer_compute_destination(self, &dest); + if (videosource_set_destination(self->source, &dest, videocore_videobuffer_on_frame, self)) { + self->stream_base = dest.base; + } + videocore_videobuffer_backend_source_changed(self); +} + +static void videocore_videobuffer_clear(videocore_videobuffer_obj_t *self) { + self->playing = false; + videocore_videobuffer_forget_frame(self); + self->stream_base = NULL; + self->source = mp_const_none; + videocore_videobuffer_backend_stream_changed(self); +} + +void common_hal_videocore_videobuffer_stop(videocore_videobuffer_obj_t *self) { + // Stop the source; the camera also stops the sensor so its settings can + // be changed. That may raise: surface it, after cleaning up, since the + // stream did stop. + if (self->source != mp_const_none) { + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + videosource_stop(self->source); + nlr_pop(); + } else { + videocore_videobuffer_clear(self); + nlr_raise(nlr.ret_val); + } + } + videocore_videobuffer_clear(self); +} + +// Stop without raising: runs from background contexts (reload). A failed +// stop is best-effort; the source's own finaliser stops it as well. +void videocore_videobuffer_stop_quiet(videocore_videobuffer_obj_t *self) { + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + if (self->source != mp_const_none) { + videosource_stop(self->source); + } + nlr_pop(); + } + videocore_videobuffer_clear(self); +} + +bool common_hal_videocore_videobuffer_get_playing(videocore_videobuffer_obj_t *self) { + videocore_videobuffer_end_stream(self); + return self->playing; +} + +mp_obj_t common_hal_videocore_videobuffer_get_source(videocore_videobuffer_obj_t *self) { + videocore_videobuffer_end_stream(self); + return self->source; +} + +// Root group validation: a VideoBuffer that streams straight into a +// framebuffer bypasses displayio rendering, so it may only be shown on a +// display that renders that same framebuffer, and only while that display is +// unrotated: its frames go straight into the framebuffer's memory, while LVGL +// rotates everything it renders. Plain buffer targets are drawn or sampled by +// the compositor, so they rotate with the display and are fine anywhere. +void videocore_videobuffer_validate_framebuffer_target(videocore_videobuffer_obj_t *self, + mp_obj_t display, mp_int_t rotation) { + if (rotation != 0) { + mp_raise_ValueError(MP_ERROR_TEXT("VideoBuffer can't stream into a rotated display")); + } + if (display == self->framebuffer) { + return; + } + #if CIRCUITPY_FRAMEBUFFERIO + // A FramebufferDisplay renders the framebuffer it wraps. That is the only + // kind of display a framebuffer-target VideoBuffer can be shown on. + mp_obj_t native_display = mp_obj_cast_to_native_base(display, &framebufferio_framebufferdisplay_type); + if (native_display != MP_OBJ_NULL) { + framebufferio_framebufferdisplay_obj_t *fd = MP_OBJ_TO_PTR(native_display); + if (fd->framebuffer == self->framebuffer) { + return; + } + } + #endif + mp_raise_ValueError(MP_ERROR_TEXT("VideoBuffer is playing into a different framebuffer")); +} + +// Walks the group tree and lets the backend check each VideoBuffer it finds. +static void videocore_validate_member(mp_obj_t member, mp_obj_t display, mp_int_t rotation) { + displayio_group_t *group = mp_obj_cast_to_native_base(member, &displayio_group_type); + if (group != MP_OBJ_NULL) { + for (size_t i = 0; i < group->members->len; i++) { + videocore_validate_member(group->members->items[i], display, rotation); + } + return; + } + videocore_videobuffer_backend_validate_member(member, display, rotation); +} + +void videocore_validate_root_group(mp_obj_t root_group, mp_obj_t display, mp_int_t rotation) { + videocore_validate_member(root_group, display, rotation); +} diff --git a/shared-module/videocore/VideoBuffer.h b/shared-module/videocore/VideoBuffer.h new file mode 100644 index 00000000000..e7c69fee760 --- /dev/null +++ b/shared-module/videocore/VideoBuffer.h @@ -0,0 +1,138 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include + +#include "py/obj.h" + +#include "shared-module/displayio/area.h" + +// Screen areas handed between VideoBuffer's shared state and its backend. The legacy +// compositor walks linked lists of them, so keep the link in a wrapper: displayio_area_t +// itself is just lv_area_t in LVGL builds. +typedef struct _videocore_area_t { + displayio_area_t area; + const struct _videocore_area_t *next; +} videocore_area_t; + +#include "shared-module/framebufferio/FramebufferDisplay.h" // framebuffer protocol +#include "shared-module/videocore/__init__.h" + +typedef struct _videocore_videobuffer_obj_t videocore_videobuffer_obj_t; + +// The compositor-specific half of a VideoBuffer lives in one of the two backend directories. +// See legacy/VideoBuffer.h and lvgl/VideoBuffer.h. +#if CIRCUITPY_DISPLAYIO_LVGL +#include "shared-module/videocore/lvgl/VideoBuffer.h" +// The protocol slot a VideoBuffer exposes to its Group. Legacy VideoBuffers are part of the +// draw protocol; LVGL ones provide protocol_lvgl. +#define VIDEOCORE_VIDEOBUFFER_PROTOCOL &videocore_videobuffer_lvgl_protocol +#else +#include "shared-module/videocore/legacy/VideoBuffer.h" +#define VIDEOCORE_VIDEOBUFFER_PROTOCOL &videocore_videobuffer_draw_protocol +#endif + +struct _videocore_videobuffer_obj_t { + mp_obj_base_t base; + // Object frames are streamed into: an object implementing the framebuffer + // protocol, such as mipidsi.Display, or a writable buffer such as a + // bytearray or memoryview. + mp_obj_t framebuffer; + const framebuffer_p_t *framebuffer_protocol; + // Target buffer info in raw buffer mode (framebuffer_protocol == NULL). + mp_buffer_info_t bufinfo; + // The video source being played, or None. + mp_obj_t source; + // Destination position of the video within its Group. + mp_int_t x; + mp_int_t y; + mp_int_t source_width; + mp_int_t source_height; + mp_int_t source_bits_per_pixel; + size_t source_frame_bytes; + // The pixel format play() asks the source for: the plain buffer's, or + // the framebuffer's color depth. + mp_int_t bits_per_pixel; + // Base of the destination the source last accepted, or NULL when there + // is none. + const void *stream_base; + // Screen area of frames that landed where the video used to be: the frame + // in flight when the destination moves or the source pauses still lands + // at the old destination, possibly after that area was repainted. Grown + // by on_frame in interrupt context; the refresh moves it into its own + // dirty bookkeeping with interrupts disabled. + videocore_area_t vacated_area; + // Framebuffer geometry cached for the destination and for on_frame, which + // can't call the framebuffer protocol from interrupt context. fb_pixels is + // NULL for plain buffer targets. fb_width and fb_height are the + // framebuffer's physical geometry. + const uint8_t *fb_pixels; + size_t fb_pixels_len; + size_t fb_row_stride; + mp_int_t fb_width; + mp_int_t fb_height; + // The rect currently rendered, in screen coordinates, which are the + // framebuffer's physical coordinates. + videocore_area_t current_area; + // Maps the video's Group-local coordinates to screen coordinates, which are + // the framebuffer's physical coordinates. + displayio_buffer_transform_t absolute_transform; + bool in_group; + // Set by the group when hidden; while hidden the video doesn't show and + // a framebuffer target's source is paused (it is revalidated on unhide). + bool hidden; + // True when the source's sizing no longer matches what play() captured: + // the video won't show until stop and play again. + bool stale_size; + bool playing; + // Set from interrupt context or a background task when the source reached + // the end of its stream; the VideoBuffer then stops it lazily. + volatile bool source_ended; + // True while a framebuffer target isn't shown, so its source is paused. + // Tracked while stopped too, so play() can start the source paused. + // Plain buffer targets are never paused. + bool paused; + // Compositor-specific mirror or draw state. + videocore_videobuffer_backend_t backend; +}; + +// Read an optional framebuffer protocol getter, or default_value when it is NULL. +#define FB_GETTER(method, default_value) \ + (self->framebuffer_protocol->method \ + ? self->framebuffer_protocol->method(self->framebuffer) \ + : (default_value)) + +void common_hal_videocore_videobuffer_construct(videocore_videobuffer_obj_t *self, mp_obj_t framebuffer, + mp_int_t bits_per_pixel); +void common_hal_videocore_videobuffer_play(videocore_videobuffer_obj_t *self, mp_obj_t source); +void common_hal_videocore_videobuffer_set_position(videocore_videobuffer_obj_t *self, mp_int_t x, mp_int_t y); +void common_hal_videocore_videobuffer_stop(videocore_videobuffer_obj_t *self); +// Stop without raising (from the finaliser). A failed stop is best-effort; +// the source's own finaliser stops it as well. +void videocore_videobuffer_stop_quiet(videocore_videobuffer_obj_t *self); +bool common_hal_videocore_videobuffer_get_playing(videocore_videobuffer_obj_t *self); +mp_obj_t common_hal_videocore_videobuffer_get_source(videocore_videobuffer_obj_t *self); + +// Update the stream to match whether the VideoBuffer is shown (on a display, +// attached, and not hidden). May raise when resuming a framebuffer target. +void videocore_videobuffer_update_stream(videocore_videobuffer_obj_t *self); +// Recompute the rect the video covers from its position and transform. +void videocore_videobuffer_update_area(videocore_videobuffer_obj_t *self); +// Map a rect in source coordinates to the screen rect it covers once rotated. +void videocore_videobuffer_source_rect(videocore_videobuffer_obj_t *self, + const displayio_area_t *source, videocore_area_t *screen); +// Follow a move of a playing framebuffer target. Best effort, never raises. +void videocore_videobuffer_move_dest(videocore_videobuffer_obj_t *self); +// Drop any landed frame the next refresh hasn't taken yet. +void videocore_videobuffer_forget_frame(videocore_videobuffer_obj_t *self); +// Stop a source that reached the end of its stream. Never raises. +void videocore_videobuffer_end_stream(videocore_videobuffer_obj_t *self); +// Raise when a framebuffer target can't be shown on this display. +void videocore_videobuffer_validate_framebuffer_target(videocore_videobuffer_obj_t *self, + mp_obj_t display, mp_int_t rotation); diff --git a/shared-module/videocore/__init__.c b/shared-module/videocore/__init__.c new file mode 100644 index 00000000000..412da7ab3ea --- /dev/null +++ b/shared-module/videocore/__init__.c @@ -0,0 +1,59 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-module/videocore/__init__.h" +#include "shared-module/videocore/VideoBuffer.h" + +const videosource_p_t *videosource_check(mp_obj_t obj) { + return (const videosource_p_t *)mp_proto_get_or_throw(MP_QSTR_protocol_videosource, obj); +} + +void videosource_play(mp_obj_t source, bool paused) { + const videosource_p_t *protocol = videosource_check(source); + if (protocol->play != NULL) { + protocol->play(source, paused); + } +} + +void videosource_stop(mp_obj_t source) { + const videosource_p_t *protocol = videosource_check(source); + if (protocol->stop != NULL) { + protocol->stop(source); + } +} + +void videosource_pause(mp_obj_t source) { + videosource_check(source)->pause(source); +} + +void videosource_resume(mp_obj_t source) { + videosource_check(source)->resume(source); +} + +bool videosource_set_destination(mp_obj_t source, const videocore_destination_t *dest, + videocore_on_frame_fun on_frame, void *ctx) { + return videosource_check(source)->set_destination(source, dest, on_frame, ctx); +} + +mp_int_t videosource_get_width(mp_obj_t source) { + return videosource_check(source)->get_width(source); +} + +mp_int_t videosource_get_height(mp_obj_t source) { + return videosource_check(source)->get_height(source); +} + +mp_int_t videosource_get_bits_per_pixel(mp_obj_t source) { + return videosource_check(source)->get_bits_per_pixel(source); +} + +bool videosource_set_bits_per_pixel(mp_obj_t source, mp_int_t bits_per_pixel) { + const videosource_p_t *protocol = videosource_check(source); + if (protocol->set_bits_per_pixel == NULL) { + return protocol->get_bits_per_pixel(source) == bits_per_pixel; + } + return protocol->set_bits_per_pixel(source, bits_per_pixel); +} diff --git a/shared-module/videocore/__init__.h b/shared-module/videocore/__init__.h new file mode 100644 index 00000000000..fae86c38272 --- /dev/null +++ b/shared-module/videocore/__init__.h @@ -0,0 +1,126 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include +#include + +#include "py/obj.h" +#include "py/proto.h" +#include "shared-module/displayio/area.h" + +// Called from interrupt context or a background task, with the ctx given to +// set_destination, when the source will write no more frames. +typedef void (*videocore_on_stream_end_fun)(void *ctx); + +// Destination for a video stream. The caller checks that the whole frame +// fits before handing it to a source. +typedef struct { + // First pixel of the destination. + uint8_t *base; + // Destination row stride, in bytes. + size_t stride; + // Source frame row size, in bytes. + size_t row_bytes; + // Source frame height, in rows. + size_t height; + // 16-bit pixels go high byte first instead of low byte first. + bool reverse_bytes_in_word; + // Never NULL. Sources that never end, such as a camera, don't call it. + videocore_on_stream_end_fun on_stream_end; +} videocore_destination_t; + +// Called from interrupt context or a background task when a frame has landed. +// frame is the destination base it landed at: usually the latest accepted +// destination, but a frame already being written when the destination changed +// (or when the source was paused) still lands at the previous one. changed is +// the part that differs from the previous frame at that destination, in source +// frame coordinates. NULL means +// the whole frame changed and the next frame repaints all of it, so this one may +// be dropped. A source whose next frame may be partial reports the whole frame +// as a rect instead. The first frame at a new destination must cover it all. +typedef void (*videocore_on_frame_fun)(void *ctx, const void *frame, const displayio_area_t *changed); + +// Protocol implemented by video streamers such as mipicsi.Camera. A source +// streams continuously while playing (unless paused); the target sets (and can +// change) where the pixels go by calling set_destination() at any time, +// including between frames. +// +// This is the video equivalent of the audiosample protocol in the audiocore +// module, inverted: instead of the target pulling frames, the source writes +// where it is told to. +typedef struct _videosource_p_t { + MP_PROTOCOL_HEAD // MP_QSTR_protocol_videosource + + // Start the source's hardware (e.g. start the sensor). Called from + // VideoBuffer.play, so it may raise, including when the source is + // already playing. No frames are written before set_destination(). When + // paused is true, start as if pause() had already been called. May be + // NULL. + void (*play)(mp_obj_t self, bool paused); + + // Pause streaming without stopping the camera or releasing its hardware: + // e.g. stop the CSI controller's DMA while the sensor keeps streaming. + // No frames are written until resume(). Called when a framebuffer target + // stops being shown. set_destination() while paused updates where resume() + // will stream. May raise; VideoBuffer ignores errors since it also pauses + // during display reset. + void (*pause)(mp_obj_t self); + + // Resume streaming after pause() into the most recent destination. Called + // from Python contexts (when the framebuffer target is shown again), so it + // may raise; the source must stay paused if it does. + void (*resume)(mp_obj_t self); + + // Direct frames into dest, starting with the next frame. Never raises: + // returns whether the source accepted dest. on_frame(ctx, frame, changed) + // is called each time a frame lands, with the base it landed at. + bool (*set_destination)(mp_obj_t self, const videocore_destination_t *dest, + videocore_on_frame_fun on_frame, void *ctx); + + // Stop streaming and release the hardware (e.g. stop the sensor so its + // settings can be changed). Called from VideoBuffer.stop, so it may + // raise. May be NULL. + void (*stop)(mp_obj_t self); + + // Width of the frames the source streams, in pixels. + mp_int_t (*get_width)(mp_obj_t self); + // Height of the frames the source streams, in lines. + mp_int_t (*get_height)(mp_obj_t self); + // Bits per pixel of the frames the source streams. + mp_int_t (*get_bits_per_pixel)(mp_obj_t self); + // Stream frames with this many bits per pixel from the next play. Called + // by VideoBuffer.play before play(). Returns whether the source can. May be + // NULL when the source only streams get_bits_per_pixel(). + bool (*set_bits_per_pixel)(mp_obj_t self, mp_int_t bits_per_pixel); +} videosource_p_t; + +// Protocol dispatch helpers. play and stop are no-ops when the source doesn't +// implement them; the rest are required. +void videosource_play(mp_obj_t source, bool paused); +void videosource_stop(mp_obj_t source); +void videosource_pause(mp_obj_t source); +void videosource_resume(mp_obj_t source); + +// Return the videosource protocol of obj or raise TypeError. +const videosource_p_t *videosource_check(mp_obj_t obj); + +bool videosource_set_destination(mp_obj_t source, const videocore_destination_t *dest, + videocore_on_frame_fun on_frame, void *ctx); +mp_int_t videosource_get_width(mp_obj_t source); +mp_int_t videosource_get_height(mp_obj_t source); +mp_int_t videosource_get_bits_per_pixel(mp_obj_t source); +// Ask source to stream bits_per_pixel. Returns whether it will. +bool videosource_set_bits_per_pixel(mp_obj_t source, mp_int_t bits_per_pixel); + +// Raise when the group tree contains a VideoBuffer that can't be shown on +// this display: one that streams into a framebuffer other than the one this +// display renders, or a framebuffer target on a rotated display. rotation is +// the display's rotation in degrees. Called when a group is made a display's +// root group. Implemented in shared-module/videocore/VideoBuffer.c. +void videocore_validate_root_group(mp_obj_t root_group, mp_obj_t display, mp_int_t rotation); diff --git a/shared-module/videocore/legacy/VideoBuffer.c b/shared-module/videocore/legacy/VideoBuffer.c new file mode 100644 index 00000000000..c8b138b2ec9 --- /dev/null +++ b/shared-module/videocore/legacy/VideoBuffer.c @@ -0,0 +1,581 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// Legacy scanline compositor implementation of videocore.VideoBuffer. The shared +// stream/target state lives in shared-module/videocore/VideoBuffer.c; this file owns the +// draw protocol and the dirty-area bookkeeping the scanline compositor needs. + +#include + +#include "shared-module/videocore/VideoBuffer.h" + +#include "py/runtime.h" + +#include "shared-bindings/microcontroller/__init__.h" +#include "shared-bindings/videocore/VideoBuffer.h" + +void videocore_videobuffer_backend_construct(videocore_videobuffer_obj_t *self) { + displayio_area_t empty = {}; + self->backend.frame_ready = false; + self->backend.frame_changed_area.area = empty; + self->backend.frame_changed_area.next = NULL; + self->backend.frame_replaceable = false; + self->backend.frame_dirty_area.area = empty; + self->backend.frame_dirty_area.next = NULL; + self->backend.ephemeral_dirty_area.area = empty; + self->backend.ephemeral_dirty_area.next = NULL; +} + +bool videocore_videobuffer_backend_shown(videocore_videobuffer_obj_t *self) { + return self->absolute_transform.scale != 0 && !self->hidden; +} + +void videocore_videobuffer_backend_stream_changed(videocore_videobuffer_obj_t *self) { + (void)self; +} + +void videocore_videobuffer_backend_source_changed(videocore_videobuffer_obj_t *self) { + (void)self; +} + +void videocore_videobuffer_backend_check_buffer_format(videocore_videobuffer_obj_t *self, + mp_int_t bits_per_pixel) { + // The scanline compositor checks the display's depth when it copies the frame. + (void)self; + (void)bits_per_pixel; +} + +// Called from interrupt context. A frame that landed where the video used to be was +// already added to the shared vacated_area by the common on_frame() dispatcher. +void videocore_videobuffer_backend_on_frame(videocore_videobuffer_obj_t *self, + const void *frame, const displayio_area_t *changed) { + if (frame != self->stream_base) { + return; + } + const displayio_area_t whole_frame = { + .x2 = self->source_width, + .y2 = self->source_height, + }; + if (changed == NULL) { + self->backend.frame_changed_area.area = whole_frame; + self->backend.frame_replaceable = true; + } else { + // Keep a bad source rect from dirtying other layers. + displayio_area_t clipped; + if (!displayio_area_compute_overlap(changed, &whole_frame, &clipped)) { + return; + } + displayio_area_union(&self->backend.frame_changed_area.area, &clipped, + &self->backend.frame_changed_area.area); + self->backend.frame_replaceable = false; + } + self->backend.frame_ready = true; +} + +void videocore_videobuffer_backend_forget_frame(videocore_videobuffer_obj_t *self) { + displayio_area_t empty = {}; + common_hal_mcu_disable_interrupts(); + self->backend.frame_ready = false; + self->backend.frame_changed_area.area = empty; + common_hal_mcu_enable_interrupts(); +} + +// Add the currently rendered rect to the dirty area so the next refresh repaints what a +// move leaves behind. Accumulates across moves. Does nothing while the video isn't shown. +void videocore_videobuffer_backend_dirty_current_area(videocore_videobuffer_obj_t *self) { + if (self->absolute_transform.scale == 0 || self->hidden) { + return; + } + displayio_area_union(&self->backend.ephemeral_dirty_area.area, &self->current_area.area, + &self->backend.ephemeral_dirty_area.area); +} + +void videocore_videobuffer_backend_validate_member(mp_obj_t member, mp_obj_t display, + mp_int_t rotation) { + const vectorio_draw_protocol_t *draw_protocol = mp_proto_get(MP_QSTR_protocol_draw, member); + if (draw_protocol == NULL) { + return; + } + mp_obj_t layer = draw_protocol->draw_get_protocol_self(member); + if (mp_obj_get_type(layer) != &videocore_videobuffer_type) { + return; + } + videocore_videobuffer_obj_t *self = MP_OBJ_TO_PTR(layer); + if (self->framebuffer_protocol == NULL) { + return; // Plain buffer targets are drawn, and rotated, by displayio. + } + videocore_videobuffer_validate_framebuffer_target(self, display, rotation); +} + +// The source pixel that a screen pixel shows along one axis. d and origin come +// from the transform. A mirrored axis (d < 0) runs the other way, so the source +// pixel ends at the origin edge instead of starting there. +static mp_int_t videocore_videobuffer_source_axis(int8_t d, mp_int_t screen, + mp_int_t origin, mp_int_t offset) { + if (d > 0) { + return screen - origin - offset; + } + return origin - screen - 1 - offset; +} + +// Bytes in one row of a source frame. 1-bit pixels are packed and each row is +// padded to a whole byte. (The shared code has the same helper; it is static there.) +static size_t videocore_videobuffer_source_row_bytes(videocore_videobuffer_obj_t *self) { + return ((size_t)self->source_width * self->source_bits_per_pixel + 7) / 8; +} + +// Draw protocol implementation. displayio copies plain-buffer frames into the +// display. Framebuffer-target frames are already in place; fill_area only +// copies them into displayio's scratch buffer when other layers overlap. + +static mp_obj_t videocore_videobuffer_draw_protocol_self(mp_obj_t protocol_container) { + return protocol_container; +} + +// Whether a layer above already claimed a pixel near the overlap. Checks whole words, which may +// include pixels between overlap rows or just outside the overlap. That can only make the caller +// take its slower path; it never misses a claimed pixel. +static bool videocore_videobuffer_overlap_claimed(const uint32_t *mask, const displayio_area_t *area, + const displayio_area_t *overlap) { + const size_t span_px = displayio_area_width(area); + const size_t first_px = (size_t)(overlap->y1 - area->y1) * span_px + (overlap->x1 - area->x1); + const size_t end_px = (size_t)(overlap->y2 - 1 - area->y1) * span_px + (overlap->x2 - area->x1); + for (size_t word = first_px / 32; word <= (end_px - 1) / 32; word++) { + if (mask[word] != 0) { + return true; + } + } + return false; +} + +// Copy a 1 bit per pixel plain buffer into a 1 bit display's buffer. Both are MSB first with +// 1 = white, the same as a monochrome EPaperDisplay's first RAM pass before any inversion. +// On a rotated display each screen pixel is walked back to its source pixel, as the 16 bit copy +// does. Whole bytes are copied when the source runs forwards along screen x, the rects line up +// and nothing above claimed these pixels. +static bool videocore_videobuffer_fill_area_1bit(videocore_videobuffer_obj_t *self, + const _displayio_colorspace_t *colorspace, const displayio_area_t *area, const displayio_area_t *overlap, + bool full_coverage, uint32_t *mask, uint32_t *buffer) { + // Every grayscale bit of a 1 bit pixel is that pixel, so this also serves each grayscale pass. + if (!colorspace->pixels_in_byte_share_row || !colorspace->reverse_pixels_in_byte || + !colorspace->grayscale) { + return false; + } + const size_t span_px = displayio_area_width(area); + const size_t width = displayio_area_width(overlap); + const size_t row_bytes = videocore_videobuffer_source_row_bytes(self); + const size_t x_in_area = overlap->x1 - area->x1; + const uint8_t *frame = self->stream_base; + uint8_t *out = (uint8_t *)buffer; + + // While the video isn't shown there is no transform and the orientations match. + const displayio_buffer_transform_t *t = &self->absolute_transform; + const bool shown = t->scale != 0; + const int8_t dx = shown ? t->dx : 1; + const int8_t dy = shown ? t->dy : 1; + const bool transpose = shown && t->transpose_xy; + const mp_int_t origin_x = shown ? t->x : 0; + const mp_int_t origin_y = shown ? t->y : 0; + const bool contiguous = !transpose && dx > 0; + // The first source column of every row when the source runs along screen x. + const mp_int_t first_x = videocore_videobuffer_source_axis(dx, overlap->x1, origin_x, self->x); + + const bool whole_bytes = contiguous && span_px % 8 == 0 && x_in_area % 8 == 0 && first_x % 8 == 0 && + width % 8 == 0 && !videocore_videobuffer_overlap_claimed(mask, area, overlap); + for (int16_t y = overlap->y1; y < overlap->y2; y++) { + const size_t px = (size_t)(y - area->y1) * span_px + x_in_area; + if (!contiguous) { + // Mirrored or transposed: walk each screen pixel back to its source pixel. Screen x + // steps along a source row, or down a source column on a transposed display. + mp_int_t source_x; + mp_int_t source_y; + if (transpose) { + source_x = videocore_videobuffer_source_axis(dy, y, origin_y, self->x); + source_y = videocore_videobuffer_source_axis(dx, overlap->x1, origin_x, self->y); + } else { + source_x = videocore_videobuffer_source_axis(dx, overlap->x1, origin_x, self->x); + source_y = videocore_videobuffer_source_axis(dy, y, origin_y, self->y); + } + for (size_t i = 0; i < width; i++) { + const size_t p = px + i; + if (mask[p / 32] & (1u << (p % 32))) { + continue; + } + const mp_int_t step = (mp_int_t)i * dx; + const mp_int_t fx = transpose ? source_x : source_x + step; + const mp_int_t fy = transpose ? source_y + step : source_y; + if (frame[(size_t)fy * row_bytes + (size_t)fx / 8] & (0x80 >> (fx % 8))) { + out[p / 8] |= 0x80 >> (p % 8); + } + mask[p / 32] |= 1u << (p % 32); + } + continue; + } + const size_t x_in_frame = first_x; + const mp_int_t source_y = videocore_videobuffer_source_axis(dy, y, origin_y, self->y); + const uint8_t *row = frame + (size_t)source_y * row_bytes; + if (whole_bytes) { + memcpy(out + px / 8, row + x_in_frame / 8, width / 8); + // Full coverage ends the layer walk, so filling the mask once below is enough. + if (!full_coverage) { + for (size_t p = px; p < px + width; p++) { + mask[p / 32] |= 1u << (p % 32); + } + } + continue; + } + for (size_t i = 0; i < width; i++) { + const size_t p = px + i; + if (mask[p / 32] & (1u << (p % 32))) { + continue; + } + const size_t f = x_in_frame + i; + if (row[f / 8] & (0x80 >> (f % 8))) { + out[p / 8] |= 0x80 >> (p % 8); + } + mask[p / 32] |= 1u << (p % 32); + } + } + if (whole_bytes && full_coverage) { + // A FramebufferDisplay writes nothing back when the mask is empty. + memset(mask, 0xff, (displayio_area_size(area) + 31) / 32 * sizeof(uint32_t)); + } + return full_coverage; +} + +static bool videocore_videobuffer_draw_fill_area(mp_obj_t self_in, const _displayio_colorspace_t *colorspace, const displayio_area_t *area, uint32_t *mask, uint32_t *buffer) { + videocore_videobuffer_obj_t *self = MP_OBJ_TO_PTR(self_in); + // buffer isn't necessarily the framebuffer. It may be a scratch buffer. + if (self->stream_base == NULL || self->hidden) { + return false; + } + + displayio_area_t overlap; + if (!displayio_area_compute_overlap(area, &self->current_area.area, &overlap)) { + return false; + } + const bool full_coverage = displayio_area_equal(area, &overlap); + const uint16_t span_px = displayio_area_width(area); + const size_t overlap_width = displayio_area_width(&overlap); + + if (self->framebuffer_protocol != NULL) { + // The source already wrote these pixels into the framebuffer. If + // nothing else covers this area, claim no pixels so the display skips + // its write-back. Otherwise copy the video's unclaimed pixels into + // the scratch buffer and claim them, since the scratch buffer is + // written back over the framebuffer. + const size_t bytes_per_pixel = self->source_bits_per_pixel / 8; + const mp_int_t fb_width = FB_GETTER(get_width, 0); + const mp_int_t row_stride = FB_GETTER(get_row_stride, fb_width * self->source_bits_per_pixel / 8); + const uint8_t *frame = (const uint8_t *)self->stream_base; + uint8_t *out = (uint8_t *)buffer; + + if (full_coverage && !videocore_videobuffer_overlap_claimed(mask, area, &overlap)) { + // Sole coverer: nothing was composed, so the driver skips the copy. + return true; + } + + for (int16_t y = overlap.y1; y < overlap.y2; y++) { + const size_t px = (size_t)(y - area->y1) * span_px + (overlap.x1 - area->x1); + const int16_t fy = y - self->current_area.area.y1; + const uint8_t *row = frame + (size_t)fy * row_stride + + (size_t)(overlap.x1 - self->current_area.area.x1) * bytes_per_pixel; + size_t i = 0; + while (i < overlap_width) { + // Skip pixels a higher layer already claimed or drew. + while (i < overlap_width && (mask[(px + i) / 32] & (1u << ((px + i) % 32)))) { + i++; + } + const size_t start = i; + while (i < overlap_width && !(mask[(px + i) / 32] & (1u << ((px + i) % 32)))) { + mask[(px + i) / 32] |= 1u << ((px + i) % 32); + i++; + } + if (i > start) { + memcpy( + out + (px + start) * bytes_per_pixel, + row + start * bytes_per_pixel, + (i - start) * bytes_per_pixel); + } + } + } + return full_coverage; + } + + if (colorspace->depth == 1 && self->source_bits_per_pixel == 1) { + return videocore_videobuffer_fill_area_1bit(self, colorspace, area, &overlap, full_coverage, mask, buffer); + } + + // Raw buffer target: copy the pixels, with no color conversion: the + // display depth must match the video's pixel format byte for byte. + if (colorspace->depth != self->source_bits_per_pixel || colorspace->depth != 16) { + return false; + } + + const size_t bytes_per_pixel = self->source_bits_per_pixel / 8; + const uint8_t *frame = (const uint8_t *)self->stream_base; + // displayio renders in screen coordinates (the framebuffer's physical + // ones) while the frame is stored in the source's own orientation, so + // walk from each screen pixel back to its source pixel. A plain buffer + // target is rotated with the display; while the video isn't shown there + // is no transform and the orientations match. + const displayio_buffer_transform_t *t = &self->absolute_transform; + const bool shown = t->scale != 0; + const int8_t dx = shown ? t->dx : 1; + const int8_t dy = shown ? t->dy : 1; + const bool transpose = shown && t->transpose_xy; + const mp_int_t origin_x = shown ? t->x : 0; + const mp_int_t origin_y = shown ? t->y : 0; + // Source pixels run along screen x only when the frame isn't transposed, + // and forwards only when screen x isn't mirrored. + const bool contiguous = !transpose && dx > 0; + + for (int16_t y = overlap.y1; y < overlap.y2; y++) { + const size_t px = (size_t)(y - area->y1) * span_px + (overlap.x1 - area->x1); + uint16_t *out = (uint16_t *)buffer + px; + // The first source pixel this row shows. The frame's column and row + // follow the transform, which swaps them on a transposed display. + mp_int_t source_x; + mp_int_t source_y; + if (transpose) { + source_x = videocore_videobuffer_source_axis(dy, y, origin_y, self->x); + source_y = videocore_videobuffer_source_axis(dx, overlap.x1, origin_x, self->y); + } else { + source_x = videocore_videobuffer_source_axis(dx, overlap.x1, origin_x, self->x); + source_y = videocore_videobuffer_source_axis(dy, y, origin_y, self->y); + } + // Where the next screen x leads: the next source column, or on a + // transposed display the next source row. + const ptrdiff_t step = transpose + ? (ptrdiff_t)dx * (ptrdiff_t)self->source_width * (ptrdiff_t)bytes_per_pixel + : (ptrdiff_t)dx * (ptrdiff_t)bytes_per_pixel; + const uint8_t *in = frame + + ((size_t)source_y * self->source_width + (size_t)source_x) * bytes_per_pixel; + if (contiguous) { + size_t i = 0; + while (i < overlap_width) { + // Skip pixels a higher layer already claimed or drew. + while (i < overlap_width && (mask[(px + i) / 32] & (1u << ((px + i) % 32)))) { + i++; + } + const size_t start = i; + while (i < overlap_width && !(mask[(px + i) / 32] & (1u << ((px + i) % 32)))) { + mask[(px + i) / 32] |= 1u << ((px + i) % 32); + i++; + } + if (i > start) { + memcpy( + out + start, + in + start * bytes_per_pixel, + (i - start) * bytes_per_pixel); + if (colorspace->reverse_bytes_in_word) { + for (size_t j = start; j < i; j++) { + out[j] = __builtin_bswap16(out[j]); + } + } + } + } + } else { + // Mirrored or transposed: the source pixels between screen pixels + // aren't next to each other, so copy them one by one. + for (size_t i = 0; i < overlap_width; i++) { + if (mask[(px + i) / 32] & (1u << ((px + i) % 32))) { + continue; + } + mask[(px + i) / 32] |= 1u << ((px + i) % 32); + uint16_t value; + memcpy(&value, in + (ptrdiff_t)i * step, bytes_per_pixel); + if (colorspace->reverse_bytes_in_word) { + value = __builtin_bswap16(value); + } + out[i] = value; + } + } + } + return full_coverage; +} + +static bool videocore_videobuffer_draw_get_dirty_area(mp_obj_t self_in, displayio_area_t *out_area) { + videocore_videobuffer_obj_t *self = MP_OBJ_TO_PTR(self_in); + out_area->x1 = out_area->x2; + displayio_area_union(&self->backend.ephemeral_dirty_area.area, &self->current_area.area, out_area); + return true; +} + +static void videocore_videobuffer_draw_update_transform(mp_obj_t self_in, displayio_buffer_transform_t *group_transform) { + videocore_videobuffer_obj_t *self = MP_OBJ_TO_PTR(self_in); + // Remember where the video was so a move can repaint the pixels it + // vacates. The area is only valid while the video is shown; a layer being + // attached or detached is handled by the display's full refresh. + displayio_area_t previous_area = self->current_area.area; + const bool was_shown = self->absolute_transform.scale != 0 && !self->hidden; + // A group that isn't attached to a display has no transform, and its + // update_transform clears the absolute transform we receive. A real + // (shown) transform always has scale >= 1. + if (group_transform == NULL || group_transform->scale == 0) { + displayio_buffer_transform_t no_transform = {}; + self->absolute_transform = no_transform; + } else { + // Validate the transform. A framebuffer target streams rows straight + // into the framebuffer's memory, so it can't turn with a rotated + // display. This is also checked when a group becomes the display's + // root group, but rotation can change afterwards. + if (self->framebuffer_protocol != NULL && + (group_transform->mirror_x || group_transform->mirror_y || + group_transform->transpose_xy)) { + mp_raise_ValueError(MP_ERROR_TEXT("VideoBuffer can't stream into a rotated display")); + } + // A plain buffer target is copied into the display, so a rotated + // display works: its transform mirrors and/or transposes the logical + // position, which the copy applies to the frame. Neither can scale. + if (group_transform->scale != 1 || + group_transform->dx == 0 || group_transform->dy == 0) { + mp_raise_ValueError(MP_ERROR_TEXT("VideoBuffer does not support transforms")); + } + self->absolute_transform = *group_transform; + } + + // A framebuffer target starts or stops with whether it is shown (the + // absolute transform is known now). This runs from Python contexts, so a + // (re)start may raise. + videocore_videobuffer_update_stream(self); + + videocore_videobuffer_update_area(self); + + // Moved by a containing Group (or a transform change): dirty the rect it + // used to occupy so the refresh repaints those pixels instead of leaving + // the previous frame there. + if (was_shown && self->absolute_transform.scale != 0 && + !displayio_area_equal(&previous_area, &self->current_area.area)) { + displayio_area_union( + &self->backend.ephemeral_dirty_area.area, &previous_area, &self->backend.ephemeral_dirty_area.area); + if (self->framebuffer_protocol == NULL) { + // Draw the last frame at its new position. + videocore_videobuffer_backend_dirty_current_area(self); + } else if (!self->playing) { + // A repaint overwrites an ended stream's last frame. + self->stream_base = NULL; + } + } + + // Framebuffer targets stream straight into the buffer: move the + // destination along with the shift. Best effort, since this can't raise: + // the shift may land the start mid-row, which won't look right but is + // obvious; the frame is capped to stay completely within the buffer. + if (self->framebuffer_protocol != NULL) { + videocore_videobuffer_move_dest(self); + } +} + +static void videocore_videobuffer_draw_finish_refresh(mp_obj_t self_in) { + videocore_videobuffer_obj_t *self = MP_OBJ_TO_PTR(self_in); + displayio_area_t empty = {}; + self->backend.ephemeral_dirty_area.area = empty; + self->backend.ephemeral_dirty_area.next = NULL; + // A frame that landed during the refresh waits for the next one, unless its + // successor repaints everything anyway. + if (self->backend.frame_replaceable) { + videocore_videobuffer_forget_frame(self); + } + videocore_videobuffer_end_stream(self); +} + +static displayio_area_t *videocore_videobuffer_draw_get_refresh_areas(mp_obj_t self_in, displayio_area_t *tail) { + videocore_videobuffer_obj_t *self = MP_OBJ_TO_PTR(self_in); + // Take what landed so far in one step: a frame landing from here on waits + // for the next refresh. + displayio_area_t empty = {}; + common_hal_mcu_disable_interrupts(); + displayio_area_t vacated = self->vacated_area.area; + const bool frame_ready = self->backend.frame_ready; + self->backend.frame_dirty_area.area = self->backend.frame_changed_area.area; + self->vacated_area.area = empty; + self->vacated_area.next = NULL; + self->backend.frame_ready = false; + self->backend.frame_changed_area.area = empty; + common_hal_mcu_enable_interrupts(); + // Frames that landed where the video used to be, possibly over the repaint + // of that area: repaint there again. + displayio_area_union(&self->backend.ephemeral_dirty_area.area, &vacated, &self->backend.ephemeral_dirty_area.area); + // Always repaint the area the video vacated, even once it is hidden or + // stopped, so its last frame doesn't stay on the target. + if (!displayio_area_empty(&self->backend.ephemeral_dirty_area.area)) { + // The video moved or was hidden: repaint with the lower layers. + tail = videocore_area_link(&self->backend.ephemeral_dirty_area, tail); + } + if (self->stream_base == NULL || self->paused || self->hidden || self->stale_size) { + return tail; + } + if (frame_ready) { + // New frame: copy the part that changed. A plain buffer target is + // rotated as it is copied, so map the changed source pixels to the + // screen; a framebuffer target's frame lands unrotated at the current + // area, so shift them there. + if (self->framebuffer_protocol == NULL) { + displayio_area_t changed = self->backend.frame_dirty_area.area; + videocore_videobuffer_source_rect(self, &changed, &self->backend.frame_dirty_area); + } else { + displayio_area_shift( + &self->backend.frame_dirty_area.area, self->current_area.area.x1, self->current_area.area.y1); + } + tail = videocore_area_link(&self->backend.frame_dirty_area, tail); + } + return tail; +} + +static void videocore_videobuffer_draw_set_dirty(mp_obj_t self_in) { + (void)self_in; +} + +static void videocore_videobuffer_draw_set_hidden(mp_obj_t self_in, bool hidden) { + videocore_videobuffer_obj_t *self = MP_OBJ_TO_PTR(self_in); + if (self->hidden == hidden) { + return; + } + videocore_videobuffer_end_stream(self); + self->hidden = hidden; + // Repaint what the video showed or vacated. + self->backend.ephemeral_dirty_area.area = self->current_area.area; + if (!hidden && self->playing) { + // The source normally can't change while the sensor stays streaming, + // but validate its sizing again in case it did: if it no longer + // matches, don't raise; simply stop showing the stream until stop and + // play again. + const videosource_p_t *protocol = mp_proto_get(MP_QSTR_protocol_videosource, self->source); + if (protocol != NULL && + (protocol->get_width(self->source) != self->source_width || + protocol->get_height(self->source) != self->source_height || + protocol->get_bits_per_pixel(self->source) != self->source_bits_per_pixel)) { + self->stale_size = true; + } + } + // Hiding or unhiding a framebuffer target pauses or resumes its source. + videocore_videobuffer_update_stream(self); +} + +static bool videocore_videobuffer_draw_set_in_group(mp_obj_t self_in, bool in_group) { + videocore_videobuffer_obj_t *self = MP_OBJ_TO_PTR(self_in); + bool was_in_group = self->in_group; + self->in_group = in_group; + return was_in_group; +} + +static vectorio_draw_protocol_impl_t videocore_videobuffer_draw_protocol_impl = { + .draw_fill_area = videocore_videobuffer_draw_fill_area, + .draw_get_dirty_area = videocore_videobuffer_draw_get_dirty_area, + .draw_update_transform = videocore_videobuffer_draw_update_transform, + .draw_finish_refresh = videocore_videobuffer_draw_finish_refresh, + .draw_get_refresh_areas = videocore_videobuffer_draw_get_refresh_areas, + .draw_set_dirty = videocore_videobuffer_draw_set_dirty, + .draw_set_hidden = videocore_videobuffer_draw_set_hidden, + .draw_set_in_group = videocore_videobuffer_draw_set_in_group, +}; + +const vectorio_draw_protocol_t videocore_videobuffer_draw_protocol = { + MP_PROTO_IMPLEMENT(MP_QSTR_protocol_draw) + .draw_get_protocol_self = videocore_videobuffer_draw_protocol_self, + .draw_protocol_impl = &videocore_videobuffer_draw_protocol_impl, +}; diff --git a/shared-module/videocore/legacy/VideoBuffer.h b/shared-module/videocore/legacy/VideoBuffer.h new file mode 100644 index 00000000000..5b134491a31 --- /dev/null +++ b/shared-module/videocore/legacy/VideoBuffer.h @@ -0,0 +1,67 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include + +#include "py/obj.h" + +#include "shared-bindings/vectorio/__init__.h" // draw protocol +#include "shared-module/displayio/area.h" + +struct _videocore_videobuffer_obj_t; + +// Legacy scanline compositor state for a VideoBuffer. +// +// Frames land in the source's destination directly. The draw protocol reports where the +// video is now (current_area, shared with the stream code) and where it has been since the +// last refresh (ephemeral_dirty_area) so displayio repaints exactly what changed. A frame +// that lands at a destination the video no longer occupies is reported through the shared +// vacated_area. +typedef struct { + // Set from interrupt context when the source lands a frame in the destination; cleared + // when the refresh takes the changed area. + volatile bool frame_ready; + // What changed in the frames landed since the last refresh, in source coordinates. + // Grown with frame_ready and cleared with it. + videocore_area_t frame_changed_area; + // The last frame landed passed NULL, so the next one repaints everything. + volatile bool frame_replaceable; + // frame_changed_area in screen coordinates, as handed to the refresh. + videocore_area_t frame_dirty_area; + // Rect the video has occupied since the last refresh, for repainting what it leaves + // behind when it moves or is hidden. + videocore_area_t ephemeral_dirty_area; +} videocore_videobuffer_backend_t; + +// Draw protocol that lets a VideoBuffer be added to a displayio Group. +// displayio copies plain-buffer frames into the display; framebuffer-target +// frames are already in place, so displayio only marks their rows. +extern const vectorio_draw_protocol_t videocore_videobuffer_draw_protocol; + +// Chain node's area in front of tail and return the new list head. The scanline compositor +// walks displayio_area_t.next, which LVGL's lv_area_t doesn't have, so the link lives in +// the wrapper. +static inline displayio_area_t *videocore_area_link(videocore_area_t *node, displayio_area_t *tail) { + node->area.next = tail; + return &node->area; +} + +// Backend hooks called by the shared stream code. See shared-module/videocore/VideoBuffer.c. +void videocore_videobuffer_backend_construct(struct _videocore_videobuffer_obj_t *self); +void videocore_videobuffer_backend_on_frame(struct _videocore_videobuffer_obj_t *self, + const void *frame, const displayio_area_t *changed); +void videocore_videobuffer_backend_forget_frame(struct _videocore_videobuffer_obj_t *self); +bool videocore_videobuffer_backend_shown(struct _videocore_videobuffer_obj_t *self); +void videocore_videobuffer_backend_stream_changed(struct _videocore_videobuffer_obj_t *self); +void videocore_videobuffer_backend_source_changed(struct _videocore_videobuffer_obj_t *self); +void videocore_videobuffer_backend_dirty_current_area(struct _videocore_videobuffer_obj_t *self); +void videocore_videobuffer_backend_check_buffer_format(struct _videocore_videobuffer_obj_t *self, + mp_int_t bits_per_pixel); +void videocore_videobuffer_backend_validate_member(mp_obj_t member, mp_obj_t display, + mp_int_t rotation); diff --git a/shared-module/videocore/lvgl/VideoBuffer.c b/shared-module/videocore/lvgl/VideoBuffer.c new file mode 100644 index 00000000000..7d78dcce78f --- /dev/null +++ b/shared-module/videocore/lvgl/VideoBuffer.c @@ -0,0 +1,492 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// LVGL implementation of videocore.VideoBuffer. See lvgl/VideoBuffer.h and +// shared-module/displayio/lvgl/lvgl_protocol.h. +// +// A VideoBuffer is one lv_image that samples the source's current destination +// directly: the user's buffer for a plain-buffer target, or the framebuffer +// band a framebuffer target streams into. Frames are written in place, so a +// landed frame only has to invalidate the image; there is no copy and no +// second render path. Invalidation is deferred out of the source's interrupt +// context to displayio_lvgl_video_background(), which runs on the +// CircuitPython thread at every supervisor tick. + +#include "shared-module/videocore/VideoBuffer.h" + +#include + +#include "py/gc.h" +#include "py/objtype.h" +#include "py/runtime.h" + +#include "shared-bindings/microcontroller/__init__.h" +#include "shared-bindings/videocore/VideoBuffer.h" +#include "shared-module/displayio/lvgl/lvgl_internal.h" +#include "shared-module/videocore/__init__.h" + +#include "misc/cache/instance/lv_image_cache.h" + +#if CIRCUITPY_VIDEOCORE && CIRCUITPY_DISPLAYIO_LVGL + +// Attached mirrors. The list lives in port memory, so displayio_gc_collect() +// roots it explicitly. +static videocore_videobuffer_obj_t *lvgl_videos = NULL; + +static void _register(videocore_videobuffer_obj_t *self) { + if (self->backend.lv_registered) { + return; + } + self->backend.lv_next = lvgl_videos; + lvgl_videos = self; + self->backend.lv_registered = true; +} + +static void _unregister(videocore_videobuffer_obj_t *self) { + if (!self->backend.lv_registered) { + return; + } + for (videocore_videobuffer_obj_t **link = &lvgl_videos; *link != NULL; link = &(*link)->backend.lv_next) { + if (*link == self) { + *link = self->backend.lv_next; + break; + } + } + self->backend.lv_next = NULL; + self->backend.lv_registered = false; +} + +// The LVGL format of the pixels the source writes. +static lv_color_format_t _video_color_format(videocore_videobuffer_obj_t *self) { + switch (self->source_bits_per_pixel) { + case 16: + if (self->framebuffer_protocol != NULL && + self->framebuffer_protocol->get_reverse_pixels_in_word != NULL && + self->framebuffer_protocol->get_reverse_pixels_in_word(self->framebuffer)) { + return LV_COLOR_FORMAT_RGB565_SWAPPED; + } + return LV_COLOR_FORMAT_RGB565; + case 24: + return LV_COLOR_FORMAT_RGB888; + case 32: + return LV_COLOR_FORMAT_XRGB8888; + default: + return LV_COLOR_FORMAT_UNKNOWN; + } +} + +// Bytes between rows of the destination the mirror samples. +static uint32_t _video_stride(videocore_videobuffer_obj_t *self) { + if (self->framebuffer_protocol != NULL) { + return self->fb_row_stride; + } + return (uint32_t)self->source_width * self->source_bits_per_pixel / 8; +} + +// lv_obj_set_pos() only records a style that a later layout pass applies, and +// lv_obj_move_to() leaves that style behind, so an unrelated size change would +// snap the object back. Set both: the coordinates are right immediately and +// nothing can undo them. +static void _place(lv_obj_t *obj, int32_t x, int32_t y) { + lv_obj_set_style_x(obj, x, 0); + lv_obj_set_style_y(obj, y, 0); + lv_obj_move_to(obj, x, y); +} + +// Drop any cached decode of the current source. A descriptor that was never +// handed to LVGL has no cache entry. +static void _drop_cached_source(videocore_videobuffer_obj_t *self) { + if (self->backend.lv_dsc.header.magic == LV_IMAGE_HEADER_MAGIC) { + lv_image_cache_drop(&self->backend.lv_dsc); + } +} + +// Repaint the area an object covered. Used before moving or hiding it, when +// invalidating the object itself no longer covers where it was. +static void _invalidate_screen_area(lv_obj_t *obj, const lv_area_t *area) { + lv_obj_t *screen = lv_obj_get_screen(obj); + if (screen != NULL) { + lv_obj_invalidate_area(screen, area); + } +} + +// Point the mirror at the current destination and place it where the video is. +// Called under the LVGL lock from every state change. +static void _sync_mirror(videocore_videobuffer_obj_t *self) { + if (self->backend.lv_obj == NULL) { + return; + } + + const uint8_t *data = (const uint8_t *)self->stream_base; + lv_color_format_t cf = _video_color_format(self); + const bool visible = data != NULL && cf != LV_COLOR_FORMAT_UNKNOWN && + self->source_width > 0 && self->source_height > 0 && !self->hidden; + + lv_area_t old_coords; + lv_obj_get_coords(self->backend.lv_obj, &old_coords); + const bool was_hidden = lv_obj_has_flag(self->backend.lv_obj, LV_OBJ_FLAG_HIDDEN); + + if (!visible) { + if (!was_hidden) { + // Repaint the last frame with whatever is underneath it before it + // goes away. + lv_obj_invalidate(self->backend.lv_obj); + lv_obj_add_flag(self->backend.lv_obj, LV_OBJ_FLAG_HIDDEN); + } else if (old_coords.x1 != 0 || old_coords.y1 != 0) { + // A stopped or moved video may have left pixels on the screen + // while its mirror was already hidden. + _invalidate_screen_area(self->backend.lv_obj, &old_coords); + } + return; + } + + const uint32_t stride = _video_stride(self); + const uint32_t row_bytes = (uint32_t)self->source_width * self->source_bits_per_pixel / 8; + const uint32_t data_size = stride * (self->source_height - 1) + row_bytes; + + if (data != self->backend.lv_data || cf != self->backend.lv_cf || + self->source_width != self->backend.lv_width || self->source_height != self->backend.lv_height || + stride != self->backend.lv_stride) { + // The storage or the way it is read changed. Drop cached decodes of the + // old view; per-frame pixel writes do not need this. + _drop_cached_source(self); + lv_memzero(&self->backend.lv_dsc, sizeof(self->backend.lv_dsc)); + self->backend.lv_dsc.header.magic = LV_IMAGE_HEADER_MAGIC; + self->backend.lv_dsc.header.cf = cf; + self->backend.lv_dsc.header.w = self->source_width; + self->backend.lv_dsc.header.h = self->source_height; + self->backend.lv_dsc.header.stride = stride; + self->backend.lv_dsc.data = data; + self->backend.lv_dsc.data_size = data_size; + self->backend.lv_data = data; + self->backend.lv_cf = cf; + self->backend.lv_width = self->source_width; + self->backend.lv_height = self->source_height; + self->backend.lv_stride = stride; + lv_image_set_src(self->backend.lv_obj, &self->backend.lv_dsc); + } + + // The position is the parent's origin plus the video's scaled own position. + // LVGL applies the scale to the image itself, using an intermediate buffer when the + // draw unit needs one, while the video source keeps writing unscaled frames. + const int32_t x = self->absolute_transform.x + + displayio_lvgl_scale_coordinate(self->x, self->backend.lv_scale); + const int32_t y = self->absolute_transform.y + + displayio_lvgl_scale_coordinate(self->y, self->backend.lv_scale); + if (lv_obj_get_x(self->backend.lv_obj) != x || lv_obj_get_y(self->backend.lv_obj) != y) { + if (!was_hidden) { + lv_obj_invalidate(self->backend.lv_obj); + } + _place(self->backend.lv_obj, x, y); + } + if (lv_obj_get_width(self->backend.lv_obj) != self->source_width || + lv_obj_get_height(self->backend.lv_obj) != self->source_height) { + if (!was_hidden) { + lv_obj_invalidate(self->backend.lv_obj); + } + lv_obj_set_size(self->backend.lv_obj, self->source_width, self->source_height); + } + lv_image_set_scale(self->backend.lv_obj, self->backend.lv_scale); + if (was_hidden) { + lv_obj_clear_flag(self->backend.lv_obj, LV_OBJ_FLAG_HIDDEN); + } + lv_obj_invalidate(self->backend.lv_obj); +} + +void videocore_videobuffer_backend_construct(videocore_videobuffer_obj_t *self) { + self->backend.lv_obj = NULL; + self->backend.lv_data = NULL; + self->backend.lv_cf = LV_COLOR_FORMAT_UNKNOWN; + self->backend.lv_width = 0; + self->backend.lv_height = 0; + self->backend.lv_stride = 0; + self->backend.lv_scale = LV_SCALE_NONE; + self->backend.lv_next = NULL; + self->backend.lv_registered = false; + self->backend.lv_pending = false; + lv_memzero(&self->backend.lv_dsc, sizeof(self->backend.lv_dsc)); +} + +bool videocore_videobuffer_backend_shown(videocore_videobuffer_obj_t *self) { + return self->absolute_transform.scale != 0 && !self->hidden && + self->backend.lv_obj != NULL; +} + +void videocore_videobuffer_backend_check_buffer_format(videocore_videobuffer_obj_t *self, + mp_int_t bits_per_pixel) { + // LVGL samples the buffer itself, so it has to know the pixel format. + (void)self; + if (bits_per_pixel != 16 && bits_per_pixel != 24 && bits_per_pixel != 32) { + mp_raise_ValueError(MP_ERROR_TEXT("video format must be 16, 24 or 32 bits per pixel")); + } +} + +void videocore_videobuffer_backend_dirty_current_area(videocore_videobuffer_obj_t *self) { + // LVGL invalidates the mirror itself when it moves. + (void)self; +} + +// Called from interrupt context. The common dispatcher already added a frame that landed at +// an old destination to vacated_area. +void videocore_videobuffer_backend_on_frame(videocore_videobuffer_obj_t *self, + const void *frame, const displayio_area_t *changed) { + (void)frame; + (void)changed; + self->backend.lv_pending = true; +} + +void videocore_videobuffer_backend_forget_frame(videocore_videobuffer_obj_t *self) { + common_hal_mcu_disable_interrupts(); + // Keep a pending repaint of a vacated area: an in-flight frame still has to be erased + // even though the frame itself no longer needs drawing. + if (displayio_area_empty(&self->vacated_area.area)) { + self->backend.lv_pending = false; + } + common_hal_mcu_enable_interrupts(); +} + +void videocore_videobuffer_backend_validate_member(mp_obj_t member, mp_obj_t display, + mp_int_t rotation) { + const lvgl_protocol_t *protocol = mp_proto_get(MP_QSTR_protocol_lvgl, member); + if (protocol == NULL) { + return; + } + mp_obj_t layer = protocol->protocol_self != NULL ? protocol->protocol_self(member) : member; + if (mp_obj_get_type(layer) != &videocore_videobuffer_type) { + return; + } + videocore_videobuffer_obj_t *self = MP_OBJ_TO_PTR(layer); + if (self->framebuffer_protocol == NULL) { + return; // Plain buffer targets are sampled by LVGL and rotate with the display. + } + videocore_videobuffer_validate_framebuffer_target(self, display, rotation); +} + +void videocore_videobuffer_backend_source_changed(videocore_videobuffer_obj_t *self) { + if (self->backend.lv_obj == NULL) { + // Not attached: there is no mirror to update. attach() syncs from the + // current state, including a frame that already landed. + return; + } + displayio_lvgl_lock(); + _sync_mirror(self); + displayio_lvgl_unlock(); +} + +void videocore_videobuffer_backend_stream_changed(videocore_videobuffer_obj_t *self) { + if (self->backend.lv_obj == NULL) { + return; + } + displayio_lvgl_lock(); + _sync_mirror(self); + displayio_lvgl_unlock(); +} + +// protocol_lvgl implementation. + +static lv_obj_t *_video_protocol_root_obj(mp_obj_t layer) { + return ((videocore_videobuffer_obj_t *)MP_OBJ_TO_PTR(layer))->backend.lv_obj; +} + +static void _video_protocol_attach(mp_obj_t layer, lv_obj_t *parent) { + videocore_videobuffer_obj_t *self = MP_OBJ_TO_PTR(layer); + if (parent == NULL) { + return; + } + nlr_jump_callback_node_t cleanup; + displayio_lvgl_lock_with_cleanup(&cleanup); + // A framebuffer target's pixels land in the framebuffer's physical memory, + // so it can only be shown on an unrotated display. LVGL rotates the whole + // scene at flush time, which would make the image and its pixels disagree. + if (self->framebuffer_protocol != NULL) { + lv_display_t *display = lv_obj_get_display(parent); + if (display != NULL && lv_display_get_rotation(display) != LV_DISPLAY_ROTATION_0) { + displayio_lvgl_unlock_with_cleanup(); + mp_raise_ValueError(MP_ERROR_TEXT("VideoBuffer can't stream into a rotated display")); + } + } + if (self->backend.lv_obj == NULL) { + self->backend.lv_obj = lv_image_create(parent); + if (self->backend.lv_obj == NULL) { + displayio_lvgl_unlock_with_cleanup(); + return; + } + lv_obj_clear_flag(self->backend.lv_obj, LV_OBJ_FLAG_CLICKABLE); + lv_obj_clear_flag(self->backend.lv_obj, LV_OBJ_FLAG_SCROLLABLE); + lv_image_set_inner_align(self->backend.lv_obj, LV_IMAGE_ALIGN_TOP_LEFT); + lv_image_set_pivot(self->backend.lv_obj, 0, 0); + lv_image_set_antialias(self->backend.lv_obj, false); + lv_image_set_scale(self->backend.lv_obj, LV_SCALE_NONE); + _register(self); + } else if (lv_obj_get_parent(self->backend.lv_obj) != parent) { + lv_obj_set_parent(self->backend.lv_obj, parent); + } + // The transform may already be known from when the member joined the + // group; apply it now that there is a mirror and a display to drive. + videocore_videobuffer_update_stream(self); + _sync_mirror(self); + displayio_lvgl_unlock_with_cleanup(); +} + +static void _video_protocol_detach(mp_obj_t layer) { + videocore_videobuffer_obj_t *self = MP_OBJ_TO_PTR(layer); + displayio_lvgl_lock(); + _unregister(self); + if (self->backend.lv_obj != NULL) { + lv_obj_delete(self->backend.lv_obj); + self->backend.lv_obj = NULL; + } + self->backend.lv_data = NULL; + self->backend.lv_cf = LV_COLOR_FORMAT_UNKNOWN; + self->backend.lv_width = 0; + self->backend.lv_height = 0; + self->backend.lv_stride = 0; + _drop_cached_source(self); + lv_memzero(&self->backend.lv_dsc, sizeof(self->backend.lv_dsc)); + // No mirror means the video isn't shown, which pauses a framebuffer target + // until it is attached again. + videocore_videobuffer_update_stream(self); + displayio_lvgl_unlock(); +} + +static bool _video_protocol_set_transform(mp_obj_t layer, int32_t abs_x, int32_t abs_y, + uint32_t scale) { + videocore_videobuffer_obj_t *self = MP_OBJ_TO_PTR(layer); + nlr_jump_callback_node_t cleanup; + displayio_lvgl_lock_with_cleanup(&cleanup); + self->backend.lv_scale = scale; + displayio_buffer_transform_t transform = { + .x = abs_x, + .y = abs_y, + .dx = 1, + .dy = 1, + // The shared streaming code uses scale as a shown/hidden marker and moves the + // unscaled DMA destination. The LVGL mirror holds the actual Q8 scale. + .scale = scale == 0 ? 0 : 1, + }; + self->absolute_transform = transform; + videocore_videobuffer_update_area(self); + // May resume a paused framebuffer target, so it may raise. + videocore_videobuffer_update_stream(self); + // A playing framebuffer target follows the group's translation by moving + // its DMA destination with it. + if (self->framebuffer_protocol != NULL) { + videocore_videobuffer_move_dest(self); + } + _sync_mirror(self); + displayio_lvgl_unlock_with_cleanup(); + return true; +} + +static void _video_protocol_set_hidden_by_parent(mp_obj_t layer, bool hidden) { + videocore_videobuffer_obj_t *self = MP_OBJ_TO_PTR(layer); + if (self->hidden == hidden) { + return; + } + self->hidden = hidden; + nlr_jump_callback_node_t cleanup; + displayio_lvgl_lock_with_cleanup(&cleanup); + videocore_videobuffer_update_stream(self); + _sync_mirror(self); + displayio_lvgl_unlock_with_cleanup(); +} + +static bool _video_protocol_set_in_group(mp_obj_t layer, bool in_group) { + videocore_videobuffer_obj_t *self = MP_OBJ_TO_PTR(layer); + bool was_in_group = self->in_group; + self->in_group = in_group; + return was_in_group; +} + +// A Python subclass of VideoBuffer is an mp_obj_instance_t that holds the native VideoBuffer in +// subobj[0]. Resolve it here so the methods above never see the instance. +static mp_obj_t _video_protocol_self(mp_obj_t layer) { + mp_obj_t native = mp_obj_cast_to_native_base(layer, + MP_OBJ_FROM_PTR(&videocore_videobuffer_type)); + if (native == MP_OBJ_NULL) { + return layer; + } + mp_obj_assert_native_inited(native); + return native; +} + +const lvgl_protocol_t videocore_videobuffer_lvgl_protocol = { + MP_PROTO_IMPLEMENT(MP_QSTR_protocol_lvgl) + .protocol_self = _video_protocol_self, + .root_obj = _video_protocol_root_obj, + .attach = _video_protocol_attach, + .detach = _video_protocol_detach, + .set_transform = _video_protocol_set_transform, + .set_hidden_by_parent = _video_protocol_set_hidden_by_parent, + .set_in_group = _video_protocol_set_in_group, +}; + +void displayio_lvgl_video_background(void) { + bool pending = false; + for (videocore_videobuffer_obj_t *self = lvgl_videos; self != NULL; self = self->backend.lv_next) { + if (self->backend.lv_pending) { + pending = true; + break; + } + } + if (!pending) { + return; + } + displayio_lvgl_lock(); + for (videocore_videobuffer_obj_t *self = lvgl_videos; self != NULL; self = self->backend.lv_next) { + if (self->backend.lv_obj == NULL) { + continue; + } + displayio_area_t empty = {}; + displayio_area_t vacated; + // Take what landed so far in one step: a frame landing from here on + // waits for the next background pass. + common_hal_mcu_disable_interrupts(); + if (!self->backend.lv_pending) { + common_hal_mcu_enable_interrupts(); + continue; + } + vacated = self->vacated_area.area; + self->vacated_area.area = empty; + self->vacated_area.next = NULL; + self->backend.lv_pending = false; + common_hal_mcu_enable_interrupts(); + + if (!displayio_area_empty(&vacated)) { + // A frame in flight landed where the video used to be. Repaint that + // area so the stale frame doesn't stay on top of the new layout. + // This has to happen even while hidden: the frame can land after + // the last repaint of the area. + _invalidate_screen_area(self->backend.lv_obj, &vacated); + } + if (self->hidden) { + continue; + } + // The image already points at the destination the frame landed in, so + // re-rendering the image samples the new pixels. + lv_obj_invalidate(self->backend.lv_obj); + } + displayio_lvgl_unlock(); +} + +void displayio_lvgl_video_gc_collect(void) { + gc_collect_root((void **)&lvgl_videos, 1); +} + +bool displayio_lvgl_video_can_rotate(lv_display_t *display, lv_display_rotation_t rotation) { + if (rotation == LV_DISPLAY_ROTATION_0) { + return true; + } + for (videocore_videobuffer_obj_t *self = lvgl_videos; self != NULL; self = self->backend.lv_next) { + if (self->framebuffer_protocol != NULL && self->backend.lv_obj != NULL && + lv_obj_get_display(self->backend.lv_obj) == display) { + return false; + } + } + return true; +} + +#endif // CIRCUITPY_VIDEOCORE && CIRCUITPY_DISPLAYIO_LVGL diff --git a/shared-module/videocore/lvgl/VideoBuffer.h b/shared-module/videocore/lvgl/VideoBuffer.h new file mode 100644 index 00000000000..5f7a4f2b65b --- /dev/null +++ b/shared-module/videocore/lvgl/VideoBuffer.h @@ -0,0 +1,75 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include + +#include "py/obj.h" + +#include "shared-module/displayio/area.h" + +struct _videocore_videobuffer_obj_t; +#include "shared-module/displayio/lvgl/lvgl_protocol.h" + +#include "lvgl.h" + +// LVGL compositor state for a VideoBuffer. +// +// The video is one lv_image that samples the source's current destination directly: the +// user's buffer for a plain-buffer target, or the framebuffer band a framebuffer target +// streams into. Frames are rewritten in place, so a landed frame only invalidates the +// image; there is no copy. The shared stream code reports frame arrivals and stream +// changes through the backend hooks below. +typedef struct { + // The image view of the current destination. + lv_obj_t *lv_obj; + lv_image_dsc_t lv_dsc; + // Descriptor contents last pushed into LVGL, so a move can drop the image cache and + // repoint the view without doing either on every frame. + const uint8_t *lv_data; + lv_color_format_t lv_cf; + uint16_t lv_width; + uint16_t lv_height; + uint16_t lv_stride; + // Inherited Group scale in Q8 format. LVGL transforms the sampled image through an + // intermediate buffer when needed, leaving the source destination unscaled. + uint32_t lv_scale; + // The compositor's list of attached mirrors, rooted during GC. + struct _videocore_videobuffer_obj_t *lv_next; + bool lv_registered; + // Set from interrupt context when a frame (or a vacated frame) needs an invalidation. + // Lets the background tick skip the LVGL lock when idle. + volatile bool lv_pending; +} videocore_videobuffer_backend_t; + +// How the LVGL compositor attaches and positions a VideoBuffer. See +// displayio/lvgl/lvgl_protocol.h. +extern const lvgl_protocol_t videocore_videobuffer_lvgl_protocol; + +// Backend hooks called by the shared stream code. See shared-module/videocore/VideoBuffer.c. +void videocore_videobuffer_backend_construct(struct _videocore_videobuffer_obj_t *self); +void videocore_videobuffer_backend_on_frame(struct _videocore_videobuffer_obj_t *self, + const void *frame, const displayio_area_t *changed); +void videocore_videobuffer_backend_forget_frame(struct _videocore_videobuffer_obj_t *self); +bool videocore_videobuffer_backend_shown(struct _videocore_videobuffer_obj_t *self); +void videocore_videobuffer_backend_stream_changed(struct _videocore_videobuffer_obj_t *self); +void videocore_videobuffer_backend_source_changed(struct _videocore_videobuffer_obj_t *self); +void videocore_videobuffer_backend_dirty_current_area(struct _videocore_videobuffer_obj_t *self); +void videocore_videobuffer_backend_check_buffer_format(struct _videocore_videobuffer_obj_t *self, + mp_int_t bits_per_pixel); +void videocore_videobuffer_backend_validate_member(mp_obj_t member, mp_obj_t display, + mp_int_t rotation); + +// Invalidate the screen rects frames landed in since the last call. Runs from the +// supervisor tick and at the start of a refresh, on the CircuitPython thread. +void displayio_lvgl_video_background(void); +// Root the attached mirrors during GC. They live in a port-memory list. +void displayio_lvgl_video_gc_collect(void); +// False when a framebuffer target is attached to display and can't stream into it at the +// given rotation. +bool displayio_lvgl_video_can_rotate(lv_display_t *display, lv_display_rotation_t rotation); diff --git a/shared-module/videogif/GifDecoder.c b/shared-module/videogif/GifDecoder.c new file mode 100644 index 00000000000..a018d58688e --- /dev/null +++ b/shared-module/videogif/GifDecoder.c @@ -0,0 +1,490 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mikey Sklar for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "shared-bindings/videogif/GifDecoder.h" + +#include + +#include "py/mpstate.h" +#include "py/runtime.h" +#include "py/stream.h" +#include "shared-module/displayio/ColorConverter.h" +#include "supervisor/port_heap.h" +#include "supervisor/shared/tick.h" + +#define PLAYING_HEAD MP_STATE_VM(videogif_playing_list) + +// Python code always gets at least this long between two frames, even when +// decoding falls behind the GIF's delays. +#define VIDEOGIF_MIN_GAP_MS 5 + +// Late frames decoded in one background call to catch up. Each one holds up +// USB and audio for one decode. +#define VIDEOGIF_MAX_LATE_FRAMES 3 + +// 1 bit per pixel: an RGB888 palette entry is white when its luma is at least +// half, so any black and white palette maps exactly. +static bool videogif_is_white(const uint8_t *rgb) { + return displayio_colorconverter_compute_luma((rgb[0] << 16) | (rgb[1] << 8) | rgb[2]) >= 128; +} + +static inline void videogif_put_pixel(videogif_gifdecoder_obj_t *self, uint8_t *row, int x, uint16_t value) { + if (self->bits_per_pixel == 1) { + const uint8_t mask = 0x80 >> (x % 8); + if (value) { + row[x / 8] |= mask; + } else { + row[x / 8] &= ~mask; + } + } else { + memcpy(row + x * 2, &value, 2); + } +} + +static displayio_area_t videogif_canvas(videogif_gifdecoder_obj_t *self) { + const displayio_area_t canvas = { + .x2 = self->gif->iCanvasWidth, + .y2 = self->gif->iCanvasHeight, + }; + return canvas; +} + +// Fill area with the background color: the global palette entry the logical +// screen descriptor names. +static void videogif_fill(videogif_gifdecoder_obj_t *self, const displayio_area_t *area) { + const uint8_t index = self->gif->ucBackground; + uint16_t value; + if (self->bits_per_pixel == 1) { + value = videogif_is_white((const uint8_t *)self->gif->pPalette + index * 3); + } else { + value = self->gif->pPalette[index]; + } + for (int y = area->y1; y < area->y2; y++) { + uint8_t *row = self->destination.base + y * self->destination.stride; + for (int x = area->x1; x < area->x2; x++) { + videogif_put_pixel(self, row, x, value); + } + } +} + +// Clear what the next frame is drawn over: the whole canvas after a restart, +// or the last frame's rect when its disposal method is 2. Waits until the +// frame is known to exist and AnimatedGIF has read the palette. +static void videogif_start_frame(videogif_gifdecoder_obj_t *self) { + if (self->fill_canvas) { + const displayio_area_t canvas = videogif_canvas(self); + videogif_fill(self, &canvas); + } else if (self->erase_last_frame) { + videogif_fill(self, &self->frame_area); + } + self->fill_canvas = false; + self->erase_last_frame = false; +} + +// AnimatedGIF calls this for each decoded line of a frame. Transparent pixels +// are skipped: the destination still holds the previous frame there. +static void videogif_draw_line(GIFDRAW *draw) { + videogif_gifdecoder_obj_t *self = draw->pUser; + if (self->new_frame) { + self->new_frame = false; + videogif_start_frame(self); + if (self->bits_per_pixel == 1) { + memset(self->white, 0, sizeof(self->white)); + for (int i = 0; i < 256; i++) { + if (videogif_is_white(draw->pPalette24 + i * 3)) { + self->white[i / 8] |= 1 << (i % 8); + } + } + } + } + + const int y = draw->iY + draw->y; + int width = draw->iWidth; + if (draw->iX + width > self->gif->iCanvasWidth) { + width = self->gif->iCanvasWidth - draw->iX; + } + if (y >= self->gif->iCanvasHeight || width < 1) { + return; + } + uint8_t *row = self->destination.base + y * self->destination.stride; + const uint8_t *pixels = draw->pPixels; + for (int i = 0; i < width; i++) { + const uint8_t index = pixels[i]; + if (draw->ucHasTransparency && index == draw->ucTransparent) { + continue; + } + uint16_t value; + if (self->bits_per_pixel == 1) { + value = (self->white[index / 8] >> (index % 8)) & 1; + } else { + value = draw->pPalette[index]; + } + videogif_put_pixel(self, row, draw->iX + i, value); + } +} + +static int32_t videogif_read_file(GIFFILE *gif_file, uint8_t *buffer, int32_t length) { + // A read that would reach the end stops one byte short, the same as gifio: + // seeking stops working once the last byte is read. + if (gif_file->iSize - gif_file->iPos < length) { + length = gif_file->iSize - gif_file->iPos - 1; + } + if (length <= 0) { + return 0; + } + int errcode = 0; + mp_uint_t bytes_read = mp_stream_rw(MP_OBJ_FROM_PTR(gif_file->fHandle), buffer, length, + &errcode, MP_STREAM_RW_ONCE); + if (errcode != 0) { + mp_raise_OSError(errcode); + } + gif_file->iPos += bytes_read; + return bytes_read; +} + +static int32_t videogif_seek_file(GIFFILE *gif_file, int32_t position) { + int errcode = 0; + mp_off_t new_position = mp_stream_seek(MP_OBJ_FROM_PTR(gif_file->fHandle), position, + MP_SEEK_SET, &errcode); + if (new_position < 0) { + mp_raise_OSError(errcode); + } + gif_file->iPos = new_position; + return new_position; +} + +// Read the GIF header from file, which is already open. +static void videogif_open_gif(GIFIMAGE *gif, mp_obj_t file) { + gif->iError = GIF_SUCCESS; + gif->pfnRead = videogif_read_file; + gif->pfnSeek = videogif_seek_file; + gif->pfnClose = NULL; + gif->pfnOpen = NULL; + gif->GIFFile.fHandle = MP_OBJ_TO_PTR(file); + + int errcode = 0; + mp_off_t size = mp_stream_seek(file, 0, MP_SEEK_END, &errcode); + if (size < 0) { + mp_raise_OSError(errcode); + } + mp_stream_seek(file, 0, MP_SEEK_SET, &errcode); + if (errcode != 0) { + mp_raise_OSError(errcode); + } + gif->GIFFile.iSize = (int32_t)size; + + // Measure the canvas first, then hand the decoder a line buffer of that width. + if (GIF_init(gif, NULL, 0) != 1) { + mp_arg_error_invalid(MP_QSTR_filename); + } + // One line of 8-bit pixels, sized to the canvas. Outside the VM heap like gif itself, and + // freed with it in deinit. + int width = gif->iCanvasWidth; + unsigned char *line_buf = port_malloc(width, false); + if (line_buf == NULL) { + m_malloc_fail(width); + } + if (GIF_init(gif, line_buf, width) != 1) { + mp_arg_error_invalid(MP_QSTR_filename); + } +} + +void common_hal_videogif_gifdecoder_construct(videogif_gifdecoder_obj_t *self, mp_obj_t file) { + // Outside the VM heap so it doesn't need a large gap there or grow it. Its + // only heap pointers, the file and self, are held by self too. The + // finaliser frees it. + self->gif = port_malloc(sizeof(GIFIMAGE), false); + if (self->gif == NULL) { + m_malloc_fail(sizeof(GIFIMAGE)); + } + GIF_begin(self->gif, GIF_PALETTE_RGB565_LE); + self->gif->pfnDraw = videogif_draw_line; + self->file = file; + self->bits_per_pixel = 16; + videogif_open_gif(self->gif, file); +} + +bool common_hal_videogif_gifdecoder_deinited(videogif_gifdecoder_obj_t *self) { + return self->file == NULL; +} + +// Tell the destination no more frames are coming, once per play. +static void videogif_end_stream(videogif_gifdecoder_obj_t *self) { + if (self->destination.on_stream_end != NULL) { + self->destination.on_stream_end(self->on_frame_context); + self->destination.on_stream_end = NULL; + } +} + +void common_hal_videogif_gifdecoder_deinit(videogif_gifdecoder_obj_t *self) { + videogif_end_stream(self); + common_hal_videogif_gifdecoder_stop(self); + if (self->gif != NULL) { + if (self->gif->ucLineBuf != NULL) { + port_free(self->gif->ucLineBuf); + } + port_free(self->gif); + self->gif = NULL; + } + if (self->file != NULL) { + mp_stream_close(self->file); + } + self->file = NULL; +} + +// The VideoBuffer may still ask a deinitialized decoder for its size. +mp_int_t common_hal_videogif_gifdecoder_get_width(videogif_gifdecoder_obj_t *self) { + return self->gif != NULL ? self->gif->iCanvasWidth : 0; +} + +mp_int_t common_hal_videogif_gifdecoder_get_height(videogif_gifdecoder_obj_t *self) { + return self->gif != NULL ? self->gif->iCanvasHeight : 0; +} + +mp_int_t common_hal_videogif_gifdecoder_get_bits_per_pixel(videogif_gifdecoder_obj_t *self) { + return self->bits_per_pixel; +} + +bool common_hal_videogif_gifdecoder_set_bits_per_pixel(videogif_gifdecoder_obj_t *self, + mp_int_t bits_per_pixel) { + if (bits_per_pixel == self->bits_per_pixel) { + return true; + } + if (self->playing || self->gif == NULL || (bits_per_pixel != 1 && bits_per_pixel != 16)) { + return false; + } + self->bits_per_pixel = bits_per_pixel; + // 1 bit per pixel needs the RGB888 palette to compute luma. play() + // restarts, which reads the GIF header again with this palette type. + self->gif->ucPaletteType = bits_per_pixel == 1 ? GIF_PALETTE_RGB888 : GIF_PALETTE_RGB565_LE; + return true; +} + +// Keep the supervisor tick on only while a frame can come due. +static void videogif_update_tick(videogif_gifdecoder_obj_t *self) { + const bool ticking = self->playing && !self->paused && !self->finished; + if (ticking == self->ticking) { + return; + } + self->ticking = ticking; + if (ticking) { + supervisor_enable_tick(); + } else { + supervisor_disable_tick(); + } +} + +// Start again from the first frame as soon as possible. +static void videogif_restart(videogif_gifdecoder_obj_t *self) { + self->restart = true; + self->finished = false; + self->next_frame_ms = supervisor_ticks_ms64(); + videogif_update_tick(self); +} + +// No more frames: the last loop played, or a frame or the file can't be read. +static void videogif_finish(videogif_gifdecoder_obj_t *self) { + self->finished = true; + videogif_update_tick(self); + videogif_end_stream(self); +} + +void common_hal_videogif_gifdecoder_play(videogif_gifdecoder_obj_t *self, bool paused) { + if (self->playing) { + mp_raise_RuntimeError(MP_ERROR_TEXT("already playing")); + } + self->playing = true; + self->paused = paused; + self->shown = false; + self->loops_done = 0; + const videocore_destination_t none = {}; + self->destination = none; + self->next = PLAYING_HEAD; + PLAYING_HEAD = self; + videogif_restart(self); +} + +void common_hal_videogif_gifdecoder_stop(videogif_gifdecoder_obj_t *self) { + if (!self->playing) { + return; + } + self->playing = false; + const videocore_destination_t none = {}; + self->destination = none; + videogif_gifdecoder_obj_t **link = &PLAYING_HEAD; + while (*link != self) { + link = &(*link)->next; + } + *link = self->next; + self->next = NULL; + videogif_update_tick(self); +} + +void common_hal_videogif_gifdecoder_pause(videogif_gifdecoder_obj_t *self) { + self->paused = true; + videogif_update_tick(self); +} + +void common_hal_videogif_gifdecoder_resume(videogif_gifdecoder_obj_t *self) { + self->paused = false; + if (self->shown) { + // The destination may have been drawn over while paused, and frames + // only draw what changed, so end rather than draw over a stale image. + videogif_finish(self); + } else { + videogif_restart(self); + } +} + +bool common_hal_videogif_gifdecoder_set_destination(videogif_gifdecoder_obj_t *self, + const videocore_destination_t *destination, videocore_on_frame_fun on_frame, void *context) { + // A new destination doesn't hold the previous frame to draw the next one + // over. The first one of a play starts the GIF; a later one ends it. + const bool moved = destination->base != self->destination.base || + destination->stride != self->destination.stride; + self->destination = *destination; + self->on_frame = on_frame; + self->on_frame_context = context; + if (moved && self->shown) { + videogif_finish(self); + } else if (moved) { + if (self->bits_per_pixel == 16) { + // Restarting reads the GIF header again, which converts the + // global color table to this byte order. + self->gif->ucPaletteType = destination->reverse_bytes_in_word ? + GIF_PALETTE_RGB565_BE : GIF_PALETTE_RGB565_LE; + } + videogif_restart(self); + } + return true; +} + +// The end of a loop: start over, unless that was the last one. Like web +// browsers, a GIF without a loop count plays once and a loop count of n +// repeats it n times. +static void videogif_end_loop(videogif_gifdecoder_obj_t *self) { + self->restart = true; + if (self->repeat_count != 0 && ++self->loops_done > self->repeat_count) { + videogif_finish(self); + } +} + +// Draw the next frame into the destination and report what changed. +static void videogif_step(videogif_gifdecoder_obj_t *self) { + const displayio_area_t canvas = videogif_canvas(self); + const bool whole_frame = self->restart; + displayio_area_t changed = {}; + if (whole_frame) { + self->restart = false; + self->fill_canvas = true; + GIF_reset(self->gif); + } else if (self->disposal == 2) { + // Restore to background before the next frame, if there is one. + self->erase_last_frame = true; + changed = self->frame_area; + } + + self->new_frame = true; + self->gif->iError = GIF_SUCCESS; + int delay_ms; + const bool more = GIF_playFrame(self->gif, &delay_ms, self) == 1; + if (self->gif->iError == GIF_EMPTY_FRAME && !whole_frame) { + // Data after the last frame: the loop is over without another frame, + // so the last frame isn't disposed of and nothing changed. + self->erase_last_frame = false; + videogif_end_loop(self); + return; + } + // A frame missing lines is broken, even when no error is set. + if (self->gif->iError != GIF_SUCCESS || self->gif->iYCount > 0) { + // A broken frame: stop without reporting it. + videogif_finish(self); + return; + } + // In case the frame drew no lines. + videogif_start_frame(self); + if (whole_frame) { + // AnimatedGIF reads the loop count with the first frame. + self->repeat_count = self->gif->iRepeatCount; + } + + const displayio_area_t frame = { + .x1 = self->gif->iX, + .y1 = self->gif->iY, + .x2 = self->gif->iX + self->gif->iWidth, + .y2 = self->gif->iY + self->gif->iHeight, + }; + if (!displayio_area_compute_overlap(&frame, &canvas, &self->frame_area)) { + self->frame_area.x1 = self->frame_area.x2; + } + // The disposal method is bits 2-4 of the graphic control extension's + // packed fields. + self->disposal = (self->gif->ucGIFBits >> 2) & 7; + displayio_area_union(&changed, &self->frame_area, &changed); + if (whole_frame) { + // A rect, not NULL: the next frame may be partial, so this one must + // not be dropped. + changed = canvas; + } + + // Like web browsers, show frames with a delay of 0 or 1 centiseconds for + // 100 ms. AnimatedGIF already reports 0 as 100 ms. + if (delay_ms <= 10) { + delay_ms = 100; + } + self->next_frame_ms += delay_ms; + // Only marks the area: frames decoded in one background call are redrawn + // once, together. + self->on_frame(self->on_frame_context, self->destination.base, &changed); + self->shown = true; + if (!more) { + videogif_end_loop(self); + } +} + +void videogif_background(void) { + if (PLAYING_HEAD == NULL) { + return; + } + const uint64_t now = supervisor_ticks_ms64(); + for (videogif_gifdecoder_obj_t *self = PLAYING_HEAD; self != NULL; self = self->next) { + if (!self->ticking || self->destination.base == NULL || now < self->next_frame_ms) { + continue; + } + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + // Keep to the GIF's timing: decode the frames that are due, up to + // a limit. Still behind after that, fall behind and leave Python a + // gap first. + for (int i = 0; i < VIDEOGIF_MAX_LATE_FRAMES && self->ticking && + now >= self->next_frame_ms; i++) { + videogif_step(self); + } + self->next_frame_ms = MAX(self->next_frame_ms, supervisor_ticks_ms64() + VIDEOGIF_MIN_GAP_MS); + nlr_pop(); + } else { + // The file can't be read: stop where it is. + videogif_finish(self); + } + } +} + +void videogif_reset(void) { + videogif_gifdecoder_obj_t *self = PLAYING_HEAD; + while (self != NULL) { + videogif_gifdecoder_obj_t *next = self->next; + self->playing = false; + // Forget on_stream_end too: at gc_deinit the VideoBuffer may be swept first. + const videocore_destination_t none = {}; + self->destination = none; + self->next = NULL; + videogif_update_tick(self); + self = next; + } + PLAYING_HEAD = NULL; +} + +MP_REGISTER_ROOT_POINTER(struct videogif_gifdecoder_obj *videogif_playing_list); diff --git a/shared-module/videogif/GifDecoder.h b/shared-module/videogif/GifDecoder.h new file mode 100644 index 00000000000..4e6cf9297ee --- /dev/null +++ b/shared-module/videogif/GifDecoder.h @@ -0,0 +1,75 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Mikey Sklar for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include + +#include "py/obj.h" + +#include "lib/AnimatedGIF/AnimatedGIF_circuitpy.h" +#include "shared-module/displayio/area.h" +#include "shared-module/videocore/__init__.h" + +typedef struct videogif_gifdecoder_obj { + mp_obj_base_t base; + // Next decoder in the list of playing decoders that the background task + // steps (see videogif_background). + struct videogif_gifdecoder_obj *next; + // The open GIF file, or NULL once deinitialized. + mp_obj_t file; + // Where frames go, set by videocore.VideoBuffer. base is NULL until the + // first set_destination of a play. + videocore_destination_t destination; + videocore_on_frame_fun on_frame; + void *on_frame_context; + // When the next frame is due, in supervisor milliseconds. + uint64_t next_frame_ms; + // The last frame's rect and disposal method, needed to restore it to the + // background before the next frame when its disposal method is 2. + displayio_area_t frame_area; + // The GIF's NETSCAPE loop count (0 loops forever, -1 when there is none) + // and how many times it has played through. + int32_t repeat_count; + int32_t loops_done; + uint8_t disposal; + // 1 or 16. + uint8_t bits_per_pixel; + // For 1 bit per pixel: which palette entries are white, one bit each, + // for the palette of the frame being decoded. + uint8_t white[256 / 8]; + bool playing; + bool paused; + // Played its last loop, or stopped on an error: no more frames are due. + bool finished; + // The supervisor tick is enabled for this decoder. + bool ticking; + // A frame has been shown since play. After that, a new destination or a + // resume ends the stream instead of starting the GIF again. + bool shown; + // Start again from the first frame: on play, at the first destination or + // resume of a play, and after the last frame. + bool restart; + // Before the first line of the next frame, fill the canvas with the + // background color, or restore the last frame's rect to it (disposal + // method 2). See videogif_start_frame. + bool fill_canvas; + bool erase_last_frame; + // The next line drawn is the first of its frame. + bool new_frame; + // AnimatedGIF decoder state, freed by deinit. NULL once deinitialized. + GIFIMAGE *gif; +} videogif_gifdecoder_obj_t; + +// Step every playing decoder whose next frame is due. Runs from the +// supervisor background tick, which is enabled while any decoder has frames +// to show. +void videogif_background(void); + +// Stop every playing decoder without touching its file or destination. Called +// on soft reset, before the displays and their framebuffers go away. +void videogif_reset(void); diff --git a/shared-module/warnings/__init__.c b/shared-module/warnings/__init__.c index ad2f14b1c5b..9961c6caa7f 100644 --- a/shared-module/warnings/__init__.c +++ b/shared-module/warnings/__init__.c @@ -21,9 +21,8 @@ void common_hal_warnings_warn(const char *message, const mp_obj_type_t *category return; } if (action == WARNINGS_ERROR) { - mp_raise_msg_str(category, message); - // Doesn't get here - return; + nlr_raise(mp_call_function_1(MP_OBJ_FROM_PTR(category), + mp_obj_new_str(message, strlen(message)))); } mp_printf(MICROPY_ERROR_PRINTER, "%q: %s\n", category->name, message); } diff --git a/shared-module/watchdog/__init__.c b/shared-module/watchdog/__init__.c index 3f47e210702..9520382b376 100644 --- a/shared-module/watchdog/__init__.c +++ b/shared-module/watchdog/__init__.c @@ -23,5 +23,5 @@ void watchdog_reset(void) { return; } } - common_hal_watchdog_deinit(self); + common_hal_watchdog_reset(self); } diff --git a/shared-module/zlib/__init__.c b/shared-module/zlib/__init__.c index 031432a215f..7becb6faf73 100644 --- a/shared-module/zlib/__init__.c +++ b/shared-module/zlib/__init__.c @@ -37,7 +37,7 @@ mp_obj_t common_hal_zlib_decompress(mp_obj_t data, mp_int_t wbits) { DEBUG_printf("sizeof(TINF_DATA)=" UINT_FMT "\n", sizeof(*decomp)); uzlib_uncompress_init(decomp, NULL, 0); mp_uint_t dest_buf_size = (bufinfo.len + 15) & ~15; - byte *dest_buf = m_new(byte, dest_buf_size); + byte *dest_buf = m_malloc_without_collect(dest_buf_size); decomp->dest = dest_buf; decomp->dest_limit = dest_buf + dest_buf_size; diff --git a/shared/libc/abort_.c b/shared/libc/abort_.c index 3051eae81e0..54eab67d3fb 100644 --- a/shared/libc/abort_.c +++ b/shared/libc/abort_.c @@ -1,7 +1,7 @@ #include -NORETURN void abort_(void); +MP_NORETURN void abort_(void); -NORETURN void abort_(void) { +MP_NORETURN void abort_(void) { mp_raise_msg(&mp_type_RuntimeError, MP_ERROR_TEXT("abort() called")); } diff --git a/shared/libc/string0.c b/shared/libc/string0.c index 5a9e0ff853a..614581734cb 100644 --- a/shared/libc/string0.c +++ b/shared/libc/string0.c @@ -28,6 +28,7 @@ #include // CIRCUITPY-CHANGE: additional includes +#include // for the atoi() prototype #include #include "py/mpconfig.h" @@ -54,14 +55,14 @@ void *memcpy(void *dst, const void *src, size_t n) { if (n & 2) { // copy half-word - *(uint16_t*)d = *(const uint16_t*)s; - d = (uint32_t*)((uint16_t*)d + 1); - s = (const uint32_t*)((const uint16_t*)s + 1); + *(uint16_t *)d = *(const uint16_t *)s; + d = (uint32_t *)((uint16_t *)d + 1); + s = (const uint32_t *)((const uint16_t *)s + 1); } if (n & 1) { // copy byte - *((uint8_t*)d) = *((const uint8_t*)s); + *((uint8_t *)d) = *((const uint8_t *)s); } } else #endif @@ -88,10 +89,10 @@ void *__memcpy_chk(void *dest, const void *src, size_t len, size_t slen) { } void *memmove(void *dest, const void *src, size_t n) { - if (src < dest && (uint8_t*)dest < (const uint8_t*)src + n) { + if (src < dest && (uint8_t *)dest < (const uint8_t *)src + n) { // need to copy backwards - uint8_t *d = (uint8_t*)dest + n - 1; - const uint8_t *s = (const uint8_t*)src + n - 1; + uint8_t *d = (uint8_t *)dest + n - 1; + const uint8_t *s = (const uint8_t *)src + n - 1; for (; n > 0; n--) { *d-- = *s--; } @@ -112,11 +113,11 @@ void *memset(void *s, int c, size_t n) { *s32++ = 0; } if (n & 2) { - *((uint16_t*)s32) = 0; - s32 = (uint32_t*)((uint16_t*)s32 + 1); + *((uint16_t *)s32) = 0; + s32 = (uint32_t *)((uint16_t *)s32 + 1); } if (n & 1) { - *((uint8_t*)s32) = 0; + *((uint8_t *)s32) = 0; } } else #endif @@ -138,8 +139,11 @@ int memcmp(const void *s1, const void *s2, size_t n) { while (n--) { char c1 = *s1_8++; char c2 = *s2_8++; - if (c1 < c2) return -1; - else if (c1 > c2) return 1; + if (c1 < c2) { + return -1; + } else if (c1 > c2) { + return 1; + } } return 0; } @@ -149,8 +153,9 @@ void *memchr(const void *s, int c, size_t n) { const unsigned char *p = s; do { - if (*p++ == c) - return ((void *)(p - 1)); + if (*p++ == c) { + return (void *)(p - 1); + } } while (--n != 0); } return 0; @@ -168,12 +173,19 @@ int strcmp(const char *s1, const char *s2) { while (*s1 && *s2) { char c1 = *s1++; // XXX UTF8 get char, next char char c2 = *s2++; // XXX UTF8 get char, next char - if (c1 < c2) return -1; - else if (c1 > c2) return 1; + if (c1 < c2) { + return -1; + } else if (c1 > c2) { + return 1; + } + } + if (*s2) { + return -1; + } else if (*s1) { + return 1; + } else { + return 0; } - if (*s2) return -1; - else if (*s1) return 1; - else return 0; } int strncmp(const char *s1, const char *s2, size_t n) { @@ -181,13 +193,21 @@ int strncmp(const char *s1, const char *s2, size_t n) { char c1 = *s1++; // XXX UTF8 get char, next char char c2 = *s2++; // XXX UTF8 get char, next char n--; - if (c1 < c2) return -1; - else if (c1 > c2) return 1; + if (c1 < c2) { + return -1; + } else if (c1 > c2) { + return 1; + } + } + if (n == 0) { + return 0; + } else if (*s2) { + return -1; + } else if (*s1) { + return 1; + } else { + return 0; } - if (n == 0) return 0; - else if (*s2) return -1; - else if (*s1) return 1; - else return 0; } char *strcpy(char *dest, const char *src) { @@ -202,21 +222,21 @@ char *strcpy(char *dest, const char *src) { // Public Domain implementation of strncpy from: // http://en.wikibooks.org/wiki/C_Programming/Strings#The_strncpy_function char *strncpy(char *s1, const char *s2, size_t n) { - char *dst = s1; - const char *src = s2; - /* Copy bytes, one at a time. */ - while (n > 0) { - n--; - if ((*dst++ = *src++) == '\0') { - /* If we get here, we found a null character at the end - of s2, so use memset to put null bytes at the end of - s1. */ - memset(dst, '\0', n); - break; - } - } - return s1; - } + char *dst = s1; + const char *src = s2; + /* Copy bytes, one at a time. */ + while (n > 0) { + n--; + if ((*dst++ = *src++) == '\0') { + /* If we get here, we found a null character at the end + of s2, so use memset to put null bytes at the end of + s1. */ + memset(dst, '\0', n); + break; + } + } + return s1; +} // needed because gcc optimises strcpy + strcat to this char *stpcpy(char *dest, const char *src) { @@ -241,29 +261,31 @@ char *strcat(char *dest, const char *src) { // Public Domain implementation of strchr from: // http://en.wikibooks.org/wiki/C_Programming/Strings#The_strchr_function -char *strchr(const char *s, int c) -{ +char *strchr(const char *s, int c) { /* Scan s for the character. When this loop is finished, s will either point to the end of the string or the character we were looking for. */ - while (*s != '\0' && *s != (char)c) + while (*s != '\0' && *s != (char)c) { s++; - return ((*s == c) ? (char *) s : 0); + } + return (*s == c) ? (char *)s : 0; } // Public Domain implementation of strstr from: // http://en.wikibooks.org/wiki/C_Programming/Strings#The_strstr_function -char *strstr(const char *haystack, const char *needle) -{ +char *strstr(const char *haystack, const char *needle) { size_t needlelen; /* Check for the null needle case. */ - if (*needle == '\0') - return (char *) haystack; + if (*needle == '\0') { + return (char *)haystack; + } needlelen = strlen(needle); - for (; (haystack = strchr(haystack, *needle)) != 0; haystack++) - if (strncmp(haystack, needle, needlelen) == 0) - return (char *) haystack; + for (; (haystack = strchr(haystack, *needle)) != 0; haystack++) { + if (strncmp(haystack, needle, needlelen) == 0) { + return (char *)haystack; + } + } return 0; } @@ -282,3 +304,13 @@ size_t strcspn(const char *s, const char *reject) { } return s - ss; } + +// Decimal-only, non-negative integers; no leading whitespace handling. +// Marked weak so a libc-provided atoi() takes precedence if available. +__attribute__((weak)) int atoi(const char *num) { + int value = 0; + while (*num >= '0' && *num <= '9') { + value = value * 10 + (*num++ - '0'); + } + return value; +} diff --git a/shared/memzip/lexermemzip.c b/shared/memzip/lexermemzip.c index aef64ffa0a7..a31fc7f1cdc 100644 --- a/shared/memzip/lexermemzip.c +++ b/shared/memzip/lexermemzip.c @@ -5,8 +5,7 @@ #include "py/mperrno.h" #include "memzip.h" -mp_lexer_t *mp_lexer_new_from_file(qstr filename) -{ +mp_lexer_t *mp_lexer_new_from_file(qstr filename) { void *data; size_t len; diff --git a/shared/memzip/make-memzip.py b/shared/memzip/make-memzip.py index 92a5d6168bb..c060745e6cf 100755 --- a/shared/memzip/make-memzip.py +++ b/shared/memzip/make-memzip.py @@ -7,13 +7,12 @@ # This is somewhat like frozen modules in python, but allows arbitrary files # to be used. -from __future__ import print_function - import argparse import os +import pathlib +import shutil import subprocess import sys -import types def create_zip(zip_filename, zip_dir): @@ -28,7 +27,7 @@ def create_zip(zip_filename, zip_dir): def create_c_from_file(c_filename, zip_filename): with open(zip_filename, "rb") as zip_file: - with open(c_filename, "wb") as c_file: + with open(c_filename, "wt") as c_file: print("#include ", file=c_file) print("", file=c_file) print("const uint8_t memzip_data[] = {", file=c_file) @@ -38,10 +37,7 @@ def create_c_from_file(c_filename, zip_filename): break print(" ", end="", file=c_file) for byte in buf: - if isinstance(byte, types.StringType): - print(" 0x{:02x},".format(ord(byte)), end="", file=c_file) - else: - print(" 0x{:02x},".format(byte), end="", file=c_file) + print(" 0x{:02x},".format(byte), end="", file=c_file) print("", file=c_file) print("};", file=c_file) @@ -69,10 +65,20 @@ def main(): parser.add_argument(dest="source_dir", default="memzip_files") args = parser.parse_args(sys.argv[1:]) + output_zip = pathlib.Path(args.zip_filename) + if output_zip.suffix != ".zip": + args.zip_filename = output_zip.with_suffix(".zip") + output_c = pathlib.Path(args.c_filename) + if output_c.suffix != ".c": + args.c_filename = output_c.with_suffix(".c") + print("args.zip_filename =", args.zip_filename) print("args.c_filename =", args.c_filename) print("args.source_dir =", args.source_dir) + if not shutil.which("zip"): + raise FileNotFoundError("zip archiver not available") + create_zip(args.zip_filename, args.source_dir) create_c_from_file(args.c_filename, args.zip_filename) diff --git a/shared/memzip/memzip.c b/shared/memzip/memzip.c index 3fbea8e1e91..32fd27ffeb4 100644 --- a/shared/memzip/memzip.c +++ b/shared/memzip/memzip.c @@ -65,8 +65,7 @@ bool memzip_is_dir(const char *filename) { } -MEMZIP_RESULT memzip_locate(const char *filename, void **data, size_t *len) -{ +MEMZIP_RESULT memzip_locate(const char *filename, void **data, size_t *len) { const MEMZIP_FILE_HDR *file_hdr = memzip_find_file_header(filename); if (file_hdr == NULL) { return MZ_NO_FILE; diff --git a/shared/memzip/memzip.h b/shared/memzip/memzip.h index 667e2df7e13..fe27d9584a3 100644 --- a/shared/memzip/memzip.h +++ b/shared/memzip/memzip.h @@ -3,17 +3,17 @@ #define MEMZIP_FILE_HEADER_SIGNATURE 0x04034b50 typedef struct { - uint32_t signature; - uint16_t version; - uint16_t flags; - uint16_t compression_method; - uint16_t last_mod_time; - uint16_t last_mod_date; - uint32_t crc32; - uint32_t compressed_size; - uint32_t uncompressed_size; - uint16_t filename_len; - uint16_t extra_len; + uint32_t signature; + uint16_t version; + uint16_t flags; + uint16_t compression_method; + uint16_t last_mod_time; + uint16_t last_mod_date; + uint32_t crc32; + uint32_t compressed_size; + uint32_t uncompressed_size; + uint16_t filename_len; + uint16_t extra_len; /* char filename[filename_len] */ /* uint8_t extra[extra_len] */ @@ -23,22 +23,22 @@ typedef struct #define MEMZIP_CENTRAL_DIRECTORY_SIGNATURE 0x02014b50 typedef struct { - uint32_t signature; - uint16_t version_made_by; - uint16_t version_read_with; - uint16_t flags; - uint16_t compression_method; - uint16_t last_mod_time; - uint16_t last_mod_date; - uint32_t crc32; - uint32_t compressed_size; - uint32_t uncompressed_size; - uint16_t filename_len; - uint16_t extra_len; - uint16_t disk_num; - uint16_t internal_file_attributes; - uint32_t external_file_attributes; - uint32_t file_header_offset; + uint32_t signature; + uint16_t version_made_by; + uint16_t version_read_with; + uint16_t flags; + uint16_t compression_method; + uint16_t last_mod_time; + uint16_t last_mod_date; + uint32_t crc32; + uint32_t compressed_size; + uint32_t uncompressed_size; + uint16_t filename_len; + uint16_t extra_len; + uint16_t disk_num; + uint16_t internal_file_attributes; + uint32_t external_file_attributes; + uint32_t file_header_offset; /* char filename[filename_len] */ /* uint8_t extra[extra_len] */ @@ -48,14 +48,14 @@ typedef struct #define MEMZIP_END_OF_CENTRAL_DIRECTORY_SIGNATURE 0x06054b50 typedef struct { - uint32_t signature; - uint16_t disk_num; - uint16_t central_directory_disk; - uint16_t num_central_directories_this_disk; - uint16_t total_central_directories; - uint32_t central_directory_size; - uint32_t central_directory_offset; - uint16_t comment_len; + uint32_t signature; + uint16_t disk_num; + uint16_t central_directory_disk; + uint16_t num_central_directories_this_disk; + uint16_t total_central_directories; + uint32_t central_directory_size; + uint32_t central_directory_offset; + uint16_t comment_len; /* char comment[comment_len] */ @@ -71,10 +71,10 @@ typedef enum { } MEMZIP_RESULT; typedef struct { - uint32_t file_size; - uint16_t last_mod_date; - uint16_t last_mod_time; - uint8_t is_dir; + uint32_t file_size; + uint16_t last_mod_date; + uint16_t last_mod_time; + uint8_t is_dir; } MEMZIP_FILE_INFO; diff --git a/shared/netutils/dhcpserver.c b/shared/netutils/dhcpserver.c index 6d9cdb97d1f..038b794e864 100644 --- a/shared/netutils/dhcpserver.c +++ b/shared/netutils/dhcpserver.c @@ -69,11 +69,9 @@ #define PORT_DHCP_SERVER (67) #define PORT_DHCP_CLIENT (68) -#define DEFAULT_DNS MAKE_IP4(192, 168, 4, 1) #define DEFAULT_LEASE_TIME_S (24 * 60 * 60) // in seconds #define MAC_LEN (6) -#define MAKE_IP4(a, b, c, d) ((a) << 24 | (b) << 16 | (c) << 8 | (d)) typedef struct { uint8_t op; // message opcode @@ -287,8 +285,10 @@ static void dhcp_server_process(void *arg, struct udp_pcb *upcb, struct pbuf *p, opt_write_n(&opt, DHCP_OPT_SERVER_ID, 4, &ip_2_ip4(&d->ip)->addr); opt_write_n(&opt, DHCP_OPT_SUBNET_MASK, 4, &ip_2_ip4(&d->nm)->addr); - opt_write_n(&opt, DHCP_OPT_ROUTER, 4, &ip_2_ip4(&d->ip)->addr); // aka gateway; can have multiple addresses - opt_write_u32(&opt, DHCP_OPT_DNS, DEFAULT_DNS); // can have multiple addresses + if (d->send_router) { + opt_write_n(&opt, DHCP_OPT_ROUTER, 4, &ip_2_ip4(&d->ip)->addr); // aka gateway; can have multiple addresses + } + opt_write_n(&opt, DHCP_OPT_DNS, 4, &ip_2_ip4(&d->ip)->addr); opt_write_u32(&opt, DHCP_OPT_IP_LEASE_TIME, DEFAULT_LEASE_TIME_S); *opt++ = DHCP_OPT_END; struct netif *netif = ip_current_input_netif(); @@ -302,6 +302,7 @@ void dhcp_server_init(dhcp_server_t *d, ip_addr_t *ip, ip_addr_t *nm) { ip_addr_copy(d->ip, *ip); ip_addr_copy(d->nm, *nm); memset(d->lease, 0, sizeof(d->lease)); + d->send_router = true; if (dhcp_socket_new_dgram(&d->udp, d, dhcp_server_process) != 0) { return; } diff --git a/shared/netutils/dhcpserver.h b/shared/netutils/dhcpserver.h index 2349d2ea427..24224d6aadd 100644 --- a/shared/netutils/dhcpserver.h +++ b/shared/netutils/dhcpserver.h @@ -41,6 +41,7 @@ typedef struct _dhcp_server_t { ip_addr_t nm; dhcp_server_lease_t lease[DHCPS_MAX_IP]; struct udp_pcb *udp; + bool send_router; // advertise server IP as default gateway } dhcp_server_t; void dhcp_server_init(dhcp_server_t *d, ip_addr_t *ip, ip_addr_t *nm); diff --git a/shared/netutils/netutils.c b/shared/netutils/netutils.c index 84b4405c41d..cd1422f7c80 100644 --- a/shared/netutils/netutils.c +++ b/shared/netutils/netutils.c @@ -63,7 +63,13 @@ void netutils_parse_ipv4_addr(mp_obj_t addr_in, uint8_t *out_ip, netutils_endian return; } const char *s = addr_str; - const char *s_top = addr_str + addr_len; + const char *s_top; + // Scan for the end of valid address characters + for (s_top = addr_str; s_top < addr_str + addr_len; s_top++) { + if (!(*s_top == '.' || (*s_top >= '0' && *s_top <= '9'))) { + break; + } + } for (mp_uint_t i = 3; ; i--) { mp_uint_t val = 0; for (; s < s_top && *s != '.'; s++) { diff --git a/shared/netutils/trace.c b/shared/netutils/trace.c index a6dfb42c28f..24af4d5ca31 100644 --- a/shared/netutils/trace.c +++ b/shared/netutils/trace.c @@ -56,7 +56,7 @@ static const char *ethertype_str(uint16_t type) { } void netutils_ethernet_trace(const mp_print_t *print, size_t len, const uint8_t *buf, unsigned int flags) { - mp_printf(print, "[% 8d] ETH%cX len=%u", mp_hal_ticks_ms(), flags & NETUTILS_TRACE_IS_TX ? 'T' : 'R', len); + mp_printf(print, "[% 8u] ETH%cX len=%u", (unsigned)mp_hal_ticks_ms(), flags & NETUTILS_TRACE_IS_TX ? 'T' : 'R', len); mp_printf(print, " dst=%02x:%02x:%02x:%02x:%02x:%02x", buf[0], buf[1], buf[2], buf[3], buf[4], buf[5]); mp_printf(print, " src=%02x:%02x:%02x:%02x:%02x:%02x", buf[6], buf[7], buf[8], buf[9], buf[10], buf[11]); diff --git a/shared/readline/readline.c b/shared/readline/readline.c index 12acf158978..23ff6c56d29 100644 --- a/shared/readline/readline.c +++ b/shared/readline/readline.c @@ -114,6 +114,7 @@ typedef struct _readline_t { // CIRCUITPY-CHANGE uint8_t utf8_cont_chars; char escape_seq_buf[1]; + char last_nl; #if MICROPY_REPL_AUTO_INDENT uint8_t auto_indent_state; #endif @@ -151,6 +152,17 @@ static size_t cursor_count_word(int forward) { } #endif +// Function returns true if newline character shall be processed. +static bool process_nl(int c) { + if ((c == '\r' || c == '\n') && (rl.last_nl == 0 || rl.last_nl == c)) { + rl.last_nl = c; + return true; + } + + rl.last_nl = 0; + return false; +} + int readline_process_char(int c) { // CIRCUITPY-CHANGE size_t last_line_len = utf8_charlen((byte *)rl.line->buf, rl.line->len); @@ -221,7 +233,7 @@ int readline_process_char(int c) { } else if (c == CHAR_CTRL_W) { goto backward_kill_word; #endif - } else if (c == '\r') { + } else if (process_nl(c)) { // newline mp_hal_stdout_tx_str("\r\n"); readline_push_history(vstr_null_terminated_str(rl.line) + rl.orig_line_len); diff --git a/shared/runtime/buffer_helper.c b/shared/runtime/buffer_helper.c index a1f7f7bb7f6..dc743032f9d 100644 --- a/shared/runtime/buffer_helper.c +++ b/shared/runtime/buffer_helper.c @@ -6,6 +6,9 @@ #include "shared/runtime/buffer_helper.h" +#include "py/binary.h" +#include "py/runtime.h" + void normalize_buffer_bounds(int32_t *start, int32_t end, size_t *length) { if (end < 0) { end += *length; @@ -14,6 +17,9 @@ void normalize_buffer_bounds(int32_t *start, int32_t end, size_t *length) { } if (*start < 0) { *start += *length; + if (*start < 0) { + *start = 0; + } } if (end < *start) { *length = 0; @@ -21,3 +27,13 @@ void normalize_buffer_bounds(int32_t *start, int32_t end, size_t *length) { *length = end - *start; } } + +uint8_t *buffer_slice(mp_obj_t buffer, int32_t start, int32_t end, mp_uint_t flags, size_t *len) { + mp_buffer_info_t bufinfo; + mp_get_buffer_raise(buffer, &bufinfo, flags); + int stride_in_bytes = mp_binary_get_size('@', bufinfo.typecode, NULL); + size_t length = bufinfo.len / stride_in_bytes; + normalize_buffer_bounds(&start, end, &length); + *len = length * stride_in_bytes; + return (uint8_t *)bufinfo.buf + start * stride_in_bytes; +} diff --git a/shared/runtime/buffer_helper.h b/shared/runtime/buffer_helper.h index 6d6f43243db..4295354edbc 100644 --- a/shared/runtime/buffer_helper.h +++ b/shared/runtime/buffer_helper.h @@ -9,4 +9,10 @@ #include #include +#include "py/obj.h" + void normalize_buffer_bounds(int32_t *start, int32_t end, size_t *length); + +// buffer[start:end], with start and end in elements. Returns the slice's address and sets *len +// to its length in bytes. +uint8_t *buffer_slice(mp_obj_t buffer, int32_t start, int32_t end, mp_uint_t flags, size_t *len); diff --git a/shared/runtime/gchelper.h b/shared/runtime/gchelper.h index 645ee837f51..9617bc7f9fe 100644 --- a/shared/runtime/gchelper.h +++ b/shared/runtime/gchelper.h @@ -41,6 +41,12 @@ typedef uintptr_t gc_helper_regs_t[4]; typedef uintptr_t gc_helper_regs_t[10]; #elif defined(__aarch64__) typedef uintptr_t gc_helper_regs_t[11]; // x19-x29 +#elif defined(__riscv) && (__riscv_xlen <= 64) +typedef uintptr_t gc_helper_regs_t[12]; // S0-S11 +#elif defined(__loongarch__) && defined(__loongarch64) +typedef uintptr_t gc_helper_regs_t[10]; // S0-S9 +#elif defined(__powerpc__) && defined(__powerpc64__) +typedef uintptr_t gc_helper_regs_t[18]; // r14-r31 #endif #endif diff --git a/shared/runtime/gchelper_generic.c b/shared/runtime/gchelper_generic.c index 4ef2e73f7a2..dcca800d512 100644 --- a/shared/runtime/gchelper_generic.c +++ b/shared/runtime/gchelper_generic.c @@ -42,13 +42,14 @@ // stack already by the caller. #if defined(__x86_64__) +// CIRCUITPY-CHANGE: use __asm__ instead of asm static void gc_helper_get_regs(gc_helper_regs_t arr) { - register long rbx asm ("rbx"); - register long rbp asm ("rbp"); - register long r12 asm ("r12"); - register long r13 asm ("r13"); - register long r14 asm ("r14"); - register long r15 asm ("r15"); + register long rbx __asm__ ("rbx"); + register long rbp __asm__ ("rbp"); + register long r12 __asm__ ("r12"); + register long r13 __asm__ ("r13"); + register long r14 __asm__ ("r14"); + register long r15 __asm__ ("r15"); #ifdef __clang__ // TODO: // This is dirty workaround for Clang. It tries to get around @@ -56,12 +57,12 @@ static void gc_helper_get_regs(gc_helper_regs_t arr) { // 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)); + __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; @@ -74,10 +75,10 @@ static void gc_helper_get_regs(gc_helper_regs_t arr) { #elif defined(__i386__) static void gc_helper_get_regs(gc_helper_regs_t arr) { - register long ebx asm ("ebx"); - register long esi asm ("esi"); - register long edi asm ("edi"); - register long ebp asm ("ebp"); + register long ebx __asm__ ("ebx"); + register long esi __asm__ ("esi"); + register long edi __asm__ ("edi"); + register long ebp __asm__ ("ebp"); #ifdef __clang__ // TODO: // This is dirty workaround for Clang. It tries to get around @@ -85,10 +86,10 @@ static void gc_helper_get_regs(gc_helper_regs_t arr) { // 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)); + __asm__ ("" : "=r" (ebx)); + __asm__ ("" : "=r" (esi)); + __asm__ ("" : "=r" (edi)); + __asm__ ("" : "=r" (ebp)); #endif arr[0] = ebx; arr[1] = esi; @@ -101,16 +102,20 @@ static void gc_helper_get_regs(gc_helper_regs_t arr) { // Fallback implementation, prefer gchelper_thumb1.s or gchelper_thumb2.s static void gc_helper_get_regs(gc_helper_regs_t arr) { - register long r4 asm ("r4"); - register long r5 asm ("r5"); - register long r6 asm ("r6"); - register long r7 asm ("r7"); - register long r8 asm ("r8"); - register long r9 asm ("r9"); - register long r10 asm ("r10"); - register long r11 asm ("r11"); - register long r12 asm ("r12"); - register long r13 asm ("r13"); + #ifdef __clang__ + #pragma clang diagnostic push + #pragma clang diagnostic ignored "-Wuninitialized" + #endif + register long r4 __asm__ ("r4"); + register long r5 __asm__ ("r5"); + register long r6 __asm__ ("r6"); + register long r7 __asm__ ("r7"); + register long r8 __asm__ ("r8"); + register long r9 __asm__ ("r9"); + register long r10 __asm__ ("r10"); + register long r11 __asm__ ("r11"); + register long r12 __asm__ ("r12"); + register long r13 __asm__ ("r13"); arr[0] = r4; arr[1] = r5; arr[2] = r6; @@ -121,22 +126,25 @@ static void gc_helper_get_regs(gc_helper_regs_t arr) { arr[7] = r11; arr[8] = r12; arr[9] = r13; + #ifdef __clang__ + #pragma clang diagnostic pop + #endif } #elif defined(__aarch64__) static void gc_helper_get_regs(gc_helper_regs_t arr) { - const register long x19 asm ("x19"); - const register long x20 asm ("x20"); - const register long x21 asm ("x21"); - const register long x22 asm ("x22"); - const register long x23 asm ("x23"); - const register long x24 asm ("x24"); - const register long x25 asm ("x25"); - const register long x26 asm ("x26"); - const register long x27 asm ("x27"); - const register long x28 asm ("x28"); - const register long x29 asm ("x29"); + const register long x19 __asm__ ("x19"); + const register long x20 __asm__ ("x20"); + const register long x21 __asm__ ("x21"); + const register long x22 __asm__ ("x22"); + const register long x23 __asm__ ("x23"); + const register long x24 __asm__ ("x24"); + const register long x25 __asm__ ("x25"); + const register long x26 __asm__ ("x26"); + const register long x27 __asm__ ("x27"); + const register long x28 __asm__ ("x28"); + const register long x29 __asm__ ("x29"); arr[0] = x19; arr[1] = x20; arr[2] = x21; @@ -150,6 +158,105 @@ static void gc_helper_get_regs(gc_helper_regs_t arr) { arr[10] = x29; } +#elif defined(__riscv) && (__riscv_xlen <= 64) + +// Fallback implementation for RV32I and RV64I, prefer gchelper_rv32i.s +// for RV32I targets or gchelper_rv64i.s for RV64I targets. + +static void gc_helper_get_regs(gc_helper_regs_t arr) { + register uintptr_t s0 __asm__ ("x8"); + register uintptr_t s1 __asm__ ("x9"); + register uintptr_t s2 __asm__ ("x18"); + register uintptr_t s3 __asm__ ("x19"); + register uintptr_t s4 __asm__ ("x20"); + register uintptr_t s5 __asm__ ("x21"); + register uintptr_t s6 __asm__ ("x22"); + register uintptr_t s7 __asm__ ("x23"); + register uintptr_t s8 __asm__ ("x24"); + register uintptr_t s9 __asm__ ("x25"); + register uintptr_t s10 __asm__ ("x26"); + register uintptr_t s11 __asm__ ("x27"); + arr[0] = s0; + arr[1] = s1; + arr[2] = s2; + arr[3] = s3; + arr[4] = s4; + arr[5] = s5; + arr[6] = s6; + arr[7] = s7; + arr[8] = s8; + arr[9] = s9; + arr[10] = s10; + arr[11] = s11; +} + +#elif defined(__loongarch__) && defined(__loongarch64) + +// Fallback implementation for LOONG64, prefer gchelper_loong64.s. +static void gc_helper_get_regs(gc_helper_regs_t arr) { + register uintptr_t s0 asm ("r23"); + register uintptr_t s1 asm ("r24"); + register uintptr_t s2 asm ("r25"); + register uintptr_t s3 asm ("r26"); + register uintptr_t s4 asm ("r27"); + register uintptr_t s5 asm ("r28"); + register uintptr_t s6 asm ("r29"); + register uintptr_t s7 asm ("r30"); + register uintptr_t s8 asm ("r31"); + register uintptr_t s9 asm ("r22"); + arr[0] = s0; + arr[1] = s1; + arr[2] = s2; + arr[3] = s3; + arr[4] = s4; + arr[5] = s5; + arr[6] = s6; + arr[7] = s7; + arr[8] = s8; + arr[9] = s9; +} + +#elif defined(__powerpc__) && defined(__powerpc64__) + +static void gc_helper_get_regs(gc_helper_regs_t arr) { + register uintptr_t r14 __asm("r14"); + register uintptr_t r15 __asm("r15"); + register uintptr_t r16 __asm("r16"); + register uintptr_t r17 __asm("r17"); + register uintptr_t r18 __asm("r18"); + register uintptr_t r19 __asm("r19"); + register uintptr_t r20 __asm("r20"); + register uintptr_t r21 __asm("r21"); + register uintptr_t r22 __asm("r22"); + register uintptr_t r23 __asm("r23"); + register uintptr_t r24 __asm("r24"); + register uintptr_t r25 __asm("r25"); + register uintptr_t r26 __asm("r26"); + register uintptr_t r27 __asm("r27"); + register uintptr_t r28 __asm("r28"); + register uintptr_t r29 __asm("r29"); + register uintptr_t r30 __asm("r30"); + register uintptr_t r31 __asm("r31"); + arr[0] = r14; + arr[1] = r15; + arr[2] = r16; + arr[3] = r17; + arr[4] = r18; + arr[5] = r19; + arr[6] = r20; + arr[7] = r21; + arr[8] = r22; + arr[9] = r23; + arr[10] = r24; + arr[11] = r25; + arr[12] = r26; + arr[13] = r27; + arr[14] = r28; + arr[15] = r29; + arr[16] = r30; + arr[17] = r31; +} + #else #error "Architecture not supported for gc_helper_get_regs. Set MICROPY_GCREGS_SETJMP to use the fallback implementation." diff --git a/shared/runtime/gchelper_loong64.s b/shared/runtime/gchelper_loong64.s new file mode 100644 index 00000000000..5180e1e24df --- /dev/null +++ b/shared/runtime/gchelper_loong64.s @@ -0,0 +1,50 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2026 Alessandro Gatti + * + * 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. + */ + + .global gc_helper_get_regs_and_sp + .type gc_helper_get_regs_and_sp, @function + +gc_helper_get_regs_and_sp: + + /* Store registers into the given array. */ + + st.d $r23, $r4, 0 /* Save S0. */ + st.d $r24, $r4, 8 /* Save S1. */ + st.d $r25, $r4, 16 /* Save S2. */ + st.d $r26, $r4, 24 /* Save S3. */ + st.d $r27, $r4, 32 /* Save S4. */ + st.d $r28, $r4, 40 /* Save S5. */ + st.d $r29, $r4, 48 /* Save S6. */ + st.d $r30, $r4, 56 /* Save S7. */ + st.d $r31, $r4, 64 /* Save S8. */ + st.d $r22, $r4, 72 /* Save S9. */ + + /* Return the stack pointer. */ + + add.d $r4, $r0, $r3 + jirl $r0, $r1, 0 + + .size gc_helper_get_regs_and_sp, .-gc_helper_get_regs_and_sp diff --git a/shared/runtime/gchelper_rv32i.s b/shared/runtime/gchelper_rv32i.s new file mode 100644 index 00000000000..64248e771a8 --- /dev/null +++ b/shared/runtime/gchelper_rv32i.s @@ -0,0 +1,52 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2024 Alessandro Gatti + * + * 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. + */ + + .global gc_helper_get_regs_and_sp + .type gc_helper_get_regs_and_sp, @function + +gc_helper_get_regs_and_sp: + + /* Store registers into the given array. */ + + sw x8, 0(x10) /* Save S0. */ + sw x9, 4(x10) /* Save S1. */ + sw x18, 8(x10) /* Save S2. */ + sw x19, 12(x10) /* Save S3. */ + sw x20, 16(x10) /* Save S4. */ + sw x21, 20(x10) /* Save S5. */ + sw x22, 24(x10) /* Save S6. */ + sw x23, 28(x10) /* Save S7. */ + sw x24, 32(x10) /* Save S8. */ + sw x25, 36(x10) /* Save S9. */ + sw x26, 40(x10) /* Save S10. */ + sw x27, 44(x10) /* Save S11. */ + + /* Return the stack pointer. */ + + add x10, x0, x2 + jalr x0, x1, 0 + + .size gc_helper_get_regs_and_sp, .-gc_helper_get_regs_and_sp diff --git a/shared/runtime/gchelper_rv64i.s b/shared/runtime/gchelper_rv64i.s new file mode 100644 index 00000000000..147a0e2bf5b --- /dev/null +++ b/shared/runtime/gchelper_rv64i.s @@ -0,0 +1,52 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2024 Alessandro Gatti + * + * 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. + */ + + .global gc_helper_get_regs_and_sp + .type gc_helper_get_regs_and_sp, @function + +gc_helper_get_regs_and_sp: + + /* Store registers into the given array. */ + + sd x8, 0(x10) /* Save S0. */ + sd x9, 8(x10) /* Save S1. */ + sd x18, 16(x10) /* Save S2. */ + sd x19, 24(x10) /* Save S3. */ + sd x20, 32(x10) /* Save S4. */ + sd x21, 40(x10) /* Save S5. */ + sd x22, 48(x10) /* Save S6. */ + sd x23, 56(x10) /* Save S7. */ + sd x24, 64(x10) /* Save S8. */ + sd x25, 72(x10) /* Save S9. */ + sd x26, 80(x10) /* Save S10. */ + sd x27, 88(x10) /* Save S11. */ + + /* Return the stack pointer. */ + + add x10, x0, x2 + jalr x0, x1, 0 + + .size gc_helper_get_regs_and_sp, .-gc_helper_get_regs_and_sp diff --git a/shared/runtime/interrupt_char.c b/shared/runtime/interrupt_char.c index 5cec1988f41..1f270201719 100644 --- a/shared/runtime/interrupt_char.c +++ b/shared/runtime/interrupt_char.c @@ -31,6 +31,7 @@ #if MICROPY_KBD_EXCEPTION +// CIRCUITPY-CHANGE #ifdef __ZEPHYR__ #include diff --git a/shared/runtime/interrupt_char.h b/shared/runtime/interrupt_char.h index c4a465456a8..44fd4b45a61 100644 --- a/shared/runtime/interrupt_char.h +++ b/shared/runtime/interrupt_char.h @@ -29,6 +29,7 @@ // CIRCUITPY-CHANGE #include +// CIRCUITPY-CHANGE #ifdef __ZEPHYR__ #include diff --git a/shared/runtime/mpirq.c b/shared/runtime/mpirq.c deleted file mode 100644 index 6111b9b10cf..00000000000 --- a/shared/runtime/mpirq.c +++ /dev/null @@ -1,136 +0,0 @@ -/* - * 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 "shared/runtime/mpirq.h" - -#if MICROPY_ENABLE_SCHEDULER - -/****************************************************************************** - DECLARE PUBLIC DATA - ******************************************************************************/ - -const mp_arg_t mp_irq_init_args[] = { - { MP_QSTR_handler, MP_ARG_OBJ, {.u_rom_obj = MP_ROM_NONE} }, - { 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); - mp_irq_init(self, methods, parent); - return self; -} - -void mp_irq_init(mp_irq_obj_t *self, const mp_irq_methods_t *methods, mp_obj_t parent) { - self->base.type = &mp_irq_type; - self->methods = (mp_irq_methods_t *)methods; - self->parent = parent; - self->handler = mp_const_none; - self->ishard = false; -} - -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 scheduler to - // prevent any scheduled callbacks from running, and lock the GC to - // prevent any memory allocations. - mp_sched_lock(); - 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; - mp_printf(MICROPY_ERROR_PRINTER, "Uncaught exception in IRQ callback handler\n"); - mp_obj_print_exception(MICROPY_ERROR_PRINTER, MP_OBJ_FROM_PTR(nlr.ret_val)); - } - gc_unlock(); - mp_sched_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); - -MP_DEFINE_CONST_OBJ_TYPE( - mp_irq_type, - MP_QSTR_irq, - MP_TYPE_FLAG_NONE, - call, mp_irq_call, - locals_dict, &mp_irq_locals_dict - ); - -#endif // MICROPY_ENABLE_SCHEDULER diff --git a/shared/runtime/mpirq.h b/shared/runtime/mpirq.h deleted file mode 100644 index dd423c01011..00000000000 --- a/shared/runtime/mpirq.h +++ /dev/null @@ -1,82 +0,0 @@ -/* - * 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 - -#include "py/runtime.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_uint_t (*mp_irq_trigger_fun_t)(mp_obj_t self, mp_uint_t trigger); -typedef mp_uint_t (*mp_irq_info_fun_t)(mp_obj_t self, mp_uint_t info_type); - -enum { - MP_IRQ_INFO_FLAGS, - MP_IRQ_INFO_TRIGGERS, -}; - -typedef struct _mp_irq_methods_t { - mp_irq_trigger_fun_t trigger; - mp_irq_info_fun_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_init(mp_irq_obj_t *self, 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/shared/runtime/pyexec.c b/shared/runtime/pyexec.c index 050a14ef82e..0c10ebf0e94 100644 --- a/shared/runtime/pyexec.c +++ b/shared/runtime/pyexec.c @@ -31,28 +31,24 @@ // CIRCUITPY-CHANGE: add #include "py/mphal.h" + #include "py/compile.h" #include "py/runtime.h" #include "py/repl.h" #include "py/gc.h" #include "py/frozenmod.h" #include "py/mphal.h" -// CIRCUITPY-CHANGE: prevent undefined warning -#if defined(MICROPY_HW_ENABLE_USB) && MICROPY_HW_ENABLE_USB -#include "irq.h" -#include "usb.h" -#endif #include "shared/readline/readline.h" #include "shared/runtime/pyexec.h" +#include "extmod/modplatform.h" #include "genhdr/mpversion.h" -// CIRCUITPY-CHANGE: atexit support +// CIRCUITPY-CHANGE: add atexit support #if CIRCUITPY_ATEXIT #include "shared-module/atexit/__init__.h" #endif pyexec_mode_kind_t pyexec_mode_kind = PYEXEC_MODE_FRIENDLY_REPL; -int pyexec_system_exit = 0; #if MICROPY_REPL_INFO static bool repl_display_debugging_info = 0; @@ -85,62 +81,74 @@ static int parse_compile_execute(const void *source, mp_parse_input_kind_t input MICROPY_BOARD_BEFORE_PYTHON_EXEC(input_kind, exec_flags); #endif - // by default a SystemExit exception returns 0 - pyexec_system_exit = 0; - nlr_buf_t nlr; nlr.ret_val = NULL; if (nlr_push(&nlr) == 0) { - mp_obj_t module_fun; - // CIRCUITPY-CHANGE + #if MICROPY_PYEXEC_ENABLE_VM_ABORT + nlr_set_abort(&nlr); + #endif + + // CIRCUITPY-CHANGE: move declaration for easier handling of atexit #if. + // Also make it possible to determine if module_fun was set. + mp_obj_t module_fun = NULL; + + // CIRCUITPY-CHANGE: add atexit support #if CIRCUITPY_ATEXIT - if (!(exec_flags & EXEC_FLAG_SOURCE_IS_ATEXIT)) + if (exec_flags & EXEC_FLAG_SOURCE_IS_ATEXIT) { + atexit_callback_t *callback = (atexit_callback_t *)source; + mp_call_function_n_kw(callback->func, callback->n_pos, callback->n_kw, callback->args); + } else #endif - // CIRCUITPY-CHANGE: multiple code changes - { - #if MICROPY_MODULE_FROZEN_MPY - if (exec_flags & EXEC_FLAG_SOURCE_IS_RAW_CODE) { - // source is a raw_code object, create the function - const mp_frozen_module_t *frozen = source; - mp_module_context_t *ctx = m_new_obj(mp_module_context_t); - ctx->module.globals = mp_globals_get(); - ctx->constants = frozen->constants; - module_fun = mp_make_function_from_proto_fun(frozen->proto_fun, ctx, NULL); - } else - #endif - { - #if MICROPY_ENABLE_COMPILER - mp_lexer_t *lex; - if (exec_flags & EXEC_FLAG_SOURCE_IS_VSTR) { - const vstr_t *vstr = source; - lex = mp_lexer_new_from_str_len(MP_QSTR__lt_stdin_gt_, vstr->buf, vstr->len, 0); - } else if (exec_flags & EXEC_FLAG_SOURCE_IS_READER) { - lex = mp_lexer_new(MP_QSTR__lt_stdin_gt_, *(mp_reader_t *)source); - } else if (exec_flags & EXEC_FLAG_SOURCE_IS_FILENAME) { - lex = mp_lexer_new_from_file(qstr_from_str(source)); - } else { - lex = (mp_lexer_t *)source; - } - // source is a lexer, parse and compile the script - qstr source_name = lex->source_name; - // CIRCUITPY-CHANGE - #if MICROPY_PY___FILE__ - if (input_kind == MP_PARSE_FILE_INPUT) { - mp_store_global(MP_QSTR___file__, MP_OBJ_NEW_QSTR(source_name)); - } - #endif - mp_parse_tree_t parse_tree = mp_parse(lex, input_kind); - module_fun = mp_compile(&parse_tree, source_name, exec_flags & EXEC_FLAG_IS_REPL); - #else - mp_raise_msg(&mp_type_RuntimeError, MP_ERROR_TEXT("script compilation not supported")); - #endif + #if MICROPY_MODULE_FROZEN_MPY + if (exec_flags & EXEC_FLAG_SOURCE_IS_RAW_CODE) { + // source is a raw_code object, create the function + const mp_frozen_module_t *frozen = source; + mp_module_context_t *ctx = m_new_obj(mp_module_context_t); + ctx->module.globals = mp_globals_get(); + ctx->constants = frozen->constants; + module_fun = mp_make_function_from_proto_fun(frozen->proto_fun, ctx, NULL); + } else + #endif + { + #if MICROPY_ENABLE_COMPILER + mp_lexer_t *lex; + if (exec_flags & EXEC_FLAG_SOURCE_IS_VSTR) { + const vstr_t *vstr = source; + lex = mp_lexer_new_from_str_len(MP_QSTR__lt_stdin_gt_, vstr->buf, vstr->len, 0); + } else if (exec_flags & EXEC_FLAG_SOURCE_IS_READER) { + lex = mp_lexer_new(MP_QSTR__lt_stdin_gt_, *(mp_reader_t *)source); + } else if (exec_flags & EXEC_FLAG_SOURCE_IS_FILENAME) { + lex = mp_lexer_new_from_file(qstr_from_str(source)); + } else { + lex = (mp_lexer_t *)source; } - - // If the code was loaded from a file, collect any garbage before running. + // source is a lexer, parse and compile the script + qstr source_name = lex->source_name; + #if MICROPY_MODULE___FILE__ if (input_kind == MP_PARSE_FILE_INPUT) { - gc_collect(); + mp_store_global(MP_QSTR___file__, MP_OBJ_NEW_QSTR(source_name)); } + #endif + mp_parse_tree_t parse_tree = mp_parse(lex, input_kind); + #if defined(MICROPY_UNIX_COVERAGE) + // allow to print the parse tree in the coverage build + if (MP_STATE_VM(mp_verbose_flag) >= 3) { + printf("----------------\n"); + mp_parse_node_print(&mp_plat_print, parse_tree.root, 0); + printf("----------------\n"); + } + #endif + module_fun = mp_compile(&parse_tree, source_name, exec_flags & EXEC_FLAG_IS_REPL); + #else + mp_raise_msg(&mp_type_RuntimeError, MP_ERROR_TEXT("script compilation not supported")); + #endif + } + + // CIRCUITPY-CHANGE: garbage collect after loading + // If the code was loaded from a file, collect any garbage before running. + if (input_kind == MP_PARSE_FILE_INPUT) { + gc_collect(); } // execute code @@ -150,28 +158,26 @@ static int parse_compile_execute(const void *source, mp_parse_input_kind_t input #if MICROPY_REPL_INFO start = mp_hal_ticks_ms(); #endif - // CIRCUITPY-CHANGE - #if CIRCUITPY_ATEXIT - if (exec_flags & EXEC_FLAG_SOURCE_IS_ATEXIT) { - atexit_callback_t *callback = (atexit_callback_t *)source; - mp_call_function_n_kw(callback->func, callback->n_pos, callback->n_kw, callback->args); - } else + #if MICROPY_PYEXEC_COMPILE_ONLY + if (!mp_compile_only) #endif { - mp_call_function_0(module_fun); + // CIRCUITPY-CHANGE: if atexit function was called, there is nothing to call. + if (module_fun != NULL) { + mp_call_function_0(module_fun); + } } mp_hal_set_interrupt_char(-1); // disable interrupt - mp_handle_pending(true); // handle any pending exceptions (and any callbacks) + mp_handle_pending(MP_HANDLE_PENDING_CALLBACKS_AND_EXCEPTIONS); // handle any pending exceptions (and any callbacks) nlr_pop(); - // CIRCUITPY-CHANGE - ret = 0; + ret = PYEXEC_NORMAL_EXIT; if (exec_flags & EXEC_FLAG_PRINT_EOF) { mp_hal_stdout_tx_strn("\x04", 1); } } else { // uncaught exception mp_hal_set_interrupt_char(-1); // disable interrupt - mp_handle_pending(false); // clear any pending exceptions (and run any callbacks) + mp_handle_pending(MP_HANDLE_PENDING_CALLBACKS_AND_CLEAR_EXCEPTIONS); // clear any pending exceptions (and run any callbacks) if (exec_flags & EXEC_FLAG_SOURCE_IS_READER) { const mp_reader_t *reader = source; @@ -183,36 +189,65 @@ static int parse_compile_execute(const void *source, mp_parse_input_kind_t input mp_hal_stdout_tx_strn("\x04", 1); } - // check for SystemExit - - // CIRCUITPY-CHANGE + // CIRCUITPY-CHANGE: Name and use some values. // nlr.ret_val is an exception object. mp_obj_t exception_obj = (mp_obj_t)nlr.ret_val; + const mp_obj_type_t *exception_obj_type = mp_obj_get_type(exception_obj); - if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(exception_obj)), MP_OBJ_FROM_PTR(&mp_type_SystemExit))) { - // at the moment, the value of SystemExit is unused - ret = pyexec_system_exit; - // CIRCUITPY-CHANGE + #if MICROPY_PYEXEC_ENABLE_VM_ABORT + if (nlr.ret_val == NULL) { // abort + ret = PYEXEC_ABORT; + } else + #endif + + if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(exception_obj_type), MP_OBJ_FROM_PTR(&mp_type_SystemExit))) { // system exit + #if MICROPY_PYEXEC_ENABLE_EXIT_CODE_HANDLING + // None is an exit value of 0; an int is its value; anything else is 1 + mp_obj_t val = mp_obj_exception_get_value(MP_OBJ_FROM_PTR(nlr.ret_val)); + if (val != mp_const_none) { + if (mp_obj_is_int(val)) { + ret = (int)mp_obj_int_get_truncated(val); + } else { + mp_obj_print_helper(MICROPY_ERROR_PRINTER, val, PRINT_STR); + mp_print_str(MICROPY_ERROR_PRINTER, "\n"); + ret = PYEXEC_UNHANDLED_EXCEPTION; + } + } else { + ret = PYEXEC_NORMAL_EXIT; + } + // Set PYEXEC_FORCED_EXIT flag so REPL knows to exit + ret |= PYEXEC_FORCED_EXIT; + #else + ret = PYEXEC_FORCED_EXIT; + #endif + // CIRCUITPY-CHANGE: support DeepSleepRequest #if CIRCUITPY_ALARM - } else if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(mp_obj_get_type(exception_obj)), MP_OBJ_FROM_PTR(&mp_type_DeepSleepRequest))) { + } else if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(exception_obj_type), MP_OBJ_FROM_PTR(&mp_type_DeepSleepRequest))) { ret = PYEXEC_DEEP_SLEEP; #endif + // CIRCUITPY-CHANGE: support ReloadException } else if (exception_obj == MP_OBJ_FROM_PTR(&MP_STATE_VM(mp_reload_exception))) { ret = PYEXEC_RELOAD; - } else { - mp_obj_print_exception(&mp_plat_print, exception_obj); - ret = PYEXEC_EXCEPTION; + } else { // other exception + mp_obj_print_exception(&mp_plat_print, MP_OBJ_FROM_PTR(nlr.ret_val)); + ret = PYEXEC_UNHANDLED_EXCEPTION; + #if MICROPY_PYEXEC_ENABLE_EXIT_CODE_HANDLING + if (mp_obj_is_subclass_fast(MP_OBJ_FROM_PTR(((mp_obj_base_t *)nlr.ret_val)->type), MP_OBJ_FROM_PTR(&mp_type_KeyboardInterrupt))) { // keyboard interrupt + ret = PYEXEC_KEYBOARD_INTERRUPT; + } + #endif } - } + + // CIRCUITPY_CHANGE: Fill in result out argument. if (result != NULL) { result->return_code = ret; - #if CIRCUITPY_ALARM // Don't set the exception object if we exited for deep sleep. - if (ret != 0 && ret != PYEXEC_DEEP_SLEEP) { - #else - if (ret != 0) { + if (ret != 0 + #if CIRCUITPY_ALARM + && ret != PYEXEC_DEEP_SLEEP #endif + ) { mp_obj_t return_value = (mp_obj_t)nlr.ret_val; result->exception = return_value; result->exception_line = -1; @@ -229,6 +264,10 @@ static int parse_compile_execute(const void *source, mp_parse_input_kind_t input } } + #if MICROPY_PYEXEC_ENABLE_VM_ABORT + nlr_set_abort(NULL); + #endif + #if MICROPY_REPL_INFO // display debugging info if wanted if ((exec_flags & EXEC_FLAG_ALLOW_DEBUGGING) && repl_display_debugging_info) { @@ -486,7 +525,10 @@ static int pyexec_friendly_repl_process_char(int c) { // CIRCUITPY-CHANGE: print CircuitPython-style banner. mp_hal_stdout_tx_str(MICROPY_FULL_VERSION_INFO); mp_hal_stdout_tx_str("\r\n"); + #if MICROPY_PY_BUILTINS_HELP + // CIRCUITPY-CHANGE: don't print help info // mp_hal_stdout_tx_str("Type \"help()\" for more information.\r\n"); + #endif goto input_restart; } else if (ret == CHAR_CTRL_C) { // break @@ -503,6 +545,8 @@ static int pyexec_friendly_repl_process_char(int c) { vstr_reset(MP_STATE_VM(repl_line)); repl.paste_mode = true; return 0; + } else if (vstr_len(MP_STATE_VM(repl_line)) == 0) { + goto input_restart; } if (ret < 0) { @@ -572,10 +616,21 @@ MP_REGISTER_ROOT_POINTER(vstr_t * repl_line); #else // MICROPY_REPL_EVENT_DRIVEN +// CIRCUITPY-CHANGE: avoid warnings +#if !defined(MICROPY_HAL_HAS_STDIO_MODE_SWITCH) || !MICROPY_HAL_HAS_STDIO_MODE_SWITCH +// If the port doesn't need any stdio mode switching calls then provide trivial ones. +static inline void mp_hal_stdio_mode_raw(void) { +} +static inline void mp_hal_stdio_mode_orig(void) { +} +#endif + int pyexec_raw_repl(void) { vstr_t line; vstr_init(&line, 32); + mp_hal_stdio_mode_raw(); + raw_repl_reset: mp_hal_stdout_tx_str("raw REPL; CTRL-B to exit\r\n"); @@ -589,6 +644,7 @@ int pyexec_raw_repl(void) { if (vstr_len(&line) == 2 && vstr_str(&line)[0] == CHAR_CTRL_E) { int ret = do_reader_stdin(vstr_str(&line)[1]); if (ret & PYEXEC_FORCED_EXIT) { + mp_hal_stdio_mode_orig(); return ret; } vstr_reset(&line); @@ -601,6 +657,7 @@ int pyexec_raw_repl(void) { mp_hal_stdout_tx_str("\r\n"); vstr_clear(&line); pyexec_mode_kind = PYEXEC_MODE_FRIENDLY_REPL; + mp_hal_stdio_mode_orig(); return 0; } else if (c == CHAR_CTRL_C) { // clear line @@ -621,14 +678,18 @@ int pyexec_raw_repl(void) { // exit for a soft reset mp_hal_stdout_tx_str("\r\n"); vstr_clear(&line); + mp_hal_stdio_mode_orig(); return PYEXEC_FORCED_EXIT; } + // Switch to original terminal mode to execute code, eg to support keyboard interrupt (SIGINT). + mp_hal_stdio_mode_orig(); // CIRCUITPY-CHANGE: add last arg, handle reload int ret = parse_compile_execute(&line, MP_PARSE_FILE_INPUT, EXEC_FLAG_PRINT_EOF | EXEC_FLAG_SOURCE_IS_VSTR, NULL); if (ret & (PYEXEC_FORCED_EXIT | PYEXEC_RELOAD)) { return ret; } + mp_hal_stdio_mode_raw(); } } @@ -636,6 +697,8 @@ int pyexec_friendly_repl(void) { vstr_t line; vstr_init(&line, 32); + mp_hal_stdio_mode_raw(); + friendly_repl_reset: // CIRCUITPY-CHANGE: CircuitPython-style banner. mp_hal_stdout_tx_str("\r\n"); @@ -663,21 +726,6 @@ int pyexec_friendly_repl(void) { for (;;) { input_restart: - - // CIRCUITPY-CHANGE: prevent undef warning - #if defined(MICROPY_HW_ENABLE_USB) && MICROPY_HW_ENABLE_USB - if (usb_vcp_is_enabled()) { - // If the user gets to here and interrupts are disabled then - // they'll never see the prompt, traceback etc. The USB REPL needs - // interrupts to be enabled or no transfers occur. So we try to - // do the user a favor and re-enable interrupts. - if (query_irq() == IRQ_STATE_DISABLED) { - enable_irq(IRQ_STATE_ENABLED); - mp_hal_stdout_tx_str("MPY: enabling IRQs\r\n"); - } - } - #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_THREAD(gc_lock_depth) != 0) { @@ -694,7 +742,7 @@ int pyexec_friendly_repl(void) { ret = readline(&line, mp_repl_get_ps1()); } else { // Uncaught exception - mp_handle_pending(false); // clear any pending exceptions (and run any callbacks) + mp_handle_pending(MP_HANDLE_PENDING_CALLBACKS_AND_CLEAR_EXCEPTIONS); // clear any pending exceptions (and run any callbacks) // Print exceptions but stay in the REPL. There are very few delayed // exceptions. The WatchDogTimer can raise one though. @@ -708,6 +756,7 @@ int pyexec_friendly_repl(void) { mp_hal_stdout_tx_str("\r\n"); vstr_clear(&line); pyexec_mode_kind = PYEXEC_MODE_RAW_REPL; + mp_hal_stdio_mode_orig(); return 0; } else if (ret == CHAR_CTRL_B) { // reset friendly REPL @@ -721,6 +770,7 @@ int pyexec_friendly_repl(void) { // exit for a soft reset mp_hal_stdout_tx_str("\r\n"); vstr_clear(&line); + mp_hal_stdio_mode_orig(); return PYEXEC_FORCED_EXIT; } else if (ret == CHAR_CTRL_E) { // paste mode @@ -765,11 +815,14 @@ int pyexec_friendly_repl(void) { } } + // Switch to original terminal mode to execute code, eg to support keyboard interrupt (SIGINT). + mp_hal_stdio_mode_orig(); // CIRCUITPY-CHANGE: add last arg ret = parse_compile_execute(&line, parse_input_kind, EXEC_FLAG_ALLOW_DEBUGGING | EXEC_FLAG_IS_REPL | EXEC_FLAG_SOURCE_IS_VSTR, NULL); if (ret & (PYEXEC_FORCED_EXIT | PYEXEC_RELOAD)) { return ret; } + mp_hal_stdio_mode_raw(); } } @@ -832,6 +885,11 @@ int pyexec_exit_handler(const void *source, pyexec_result_t *result) { } #endif +int pyexec_vstr(vstr_t *str, bool allow_keyboard_interrupt, pyexec_result_t *result) { + mp_uint_t exec_flags = allow_keyboard_interrupt ? 0 : EXEC_FLAG_NO_INTERRUPT; + return parse_compile_execute(str, MP_PARSE_FILE_INPUT, exec_flags | EXEC_FLAG_SOURCE_IS_VSTR, result); +} + #if MICROPY_REPL_INFO mp_obj_t pyb_set_repl_info(mp_obj_t o_value) { repl_display_debugging_info = mp_obj_get_int(o_value); diff --git a/shared/runtime/pyexec.h b/shared/runtime/pyexec.h index 762b926c9c3..234b201be93 100644 --- a/shared/runtime/pyexec.h +++ b/shared/runtime/pyexec.h @@ -45,23 +45,29 @@ typedef struct { extern pyexec_mode_kind_t pyexec_mode_kind; -// Set this to the value (eg PYEXEC_FORCED_EXIT) that will be propagated through -// the pyexec functions if a SystemExit exception is raised by the running code. -// It will reset to 0 at the start of each execution (eg each REPL entry). -extern int pyexec_system_exit; - #define PYEXEC_FORCED_EXIT (0x100) // CIRCUITPY-CHANGE: additional flags -#define PYEXEC_EXCEPTION (0x200) #define PYEXEC_DEEP_SLEEP (0x400) #define PYEXEC_RELOAD (0x800) +#if MICROPY_PYEXEC_ENABLE_EXIT_CODE_HANDLING +#define PYEXEC_NORMAL_EXIT (0) +#define PYEXEC_UNHANDLED_EXCEPTION (1) +#define PYEXEC_KEYBOARD_INTERRUPT (128 + 2) // same as SIG INT exit code +#define PYEXEC_ABORT (128 + 9) // same as SIG KILL exit code +#else +#define PYEXEC_NORMAL_EXIT (1) +#define PYEXEC_UNHANDLED_EXCEPTION (0) +#define PYEXEC_ABORT PYEXEC_FORCED_EXIT +#endif + int pyexec_raw_repl(void); int pyexec_friendly_repl(void); // CIRCUITPY-CHANGE: result out argument int pyexec_file(const char *filename, pyexec_result_t *result); int pyexec_file_if_exists(const char *filename, pyexec_result_t *result); int pyexec_frozen_module(const char *name, bool allow_keyboard_interrupt, pyexec_result_t *result); +int pyexec_vstr(vstr_t *str, bool allow_keyboard_interrupt, pyexec_result_t *result); void pyexec_event_repl_init(void); int pyexec_event_repl_process_char(int c); extern uint8_t pyexec_repl_active; diff --git a/shared/runtime/semihosting.c b/shared/runtime/semihosting.c deleted file mode 100644 index 18c7f5d57a3..00000000000 --- a/shared/runtime/semihosting.c +++ /dev/null @@ -1,132 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2018 Ayke van Laethem - * - * 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 "semihosting.h" - -// Resources: -// http://embed.rs/articles/2016/semi-hosting-rust/ -// https://wiki.dlang.org/Minimal_semihosted_ARM_Cortex-M_%22Hello_World%22 -// https://github.com/arduino/OpenOCD/blob/master/src/target/arm_semihosting.c - -#define SYS_OPEN 0x01 -#define SYS_WRITEC 0x03 -#define SYS_WRITE 0x05 -#define SYS_READC 0x07 - -// Constants: -#define OPEN_MODE_READ (0) // mode "r" -#define OPEN_MODE_WRITE (4) // mode "w" - -#ifndef __thumb__ -#error Semihosting is only implemented for ARM microcontrollers. -#endif - -static int mp_semihosting_stdout; - -static uint32_t mp_semihosting_call(uint32_t num, const void *arg) { - // A semihosting call works as follows, similar to a SVCall: - // * the call is invoked by a special breakpoint: 0xAB - // * the command is placed in r0 - // * a pointer to the arguments is placed in r1 - // * the return value is placed in r0 - // Note that because it uses the breakpoint instruction, applications - // will hang if they're not connected to a debugger. And they'll be - // stuck in a breakpoint if semihosting is not specifically enabled in - // the debugger. - // Also note that semihosting is extremely slow (sometimes >100ms per - // call). - register uint32_t num_reg __asm__ ("r0") = num; - register const void *args_reg __asm__ ("r1") = arg; - __asm__ __volatile__ ( - "bkpt 0xAB\n" // invoke semihosting call - : "+r" (num_reg) // call number and result - : "r" (args_reg) // arguments - : "memory"); // make sure args aren't optimized away - return num_reg; // r0, which became the result -} - -static int mp_semihosting_open_console(uint32_t mode) { - struct { - char *name; - uint32_t mode; - uint32_t name_len; - } args = { - .name = ":tt", // magic path to console - .mode = mode, // e.g. "r", "w" (see OPEN_MODE_* constants) - .name_len = 3, // strlen(":tt") - }; - return mp_semihosting_call(SYS_OPEN, &args); -} - -void mp_semihosting_init() { - mp_semihosting_stdout = mp_semihosting_open_console(OPEN_MODE_WRITE); -} - -int mp_semihosting_rx_char() { - return mp_semihosting_call(SYS_READC, NULL); -} - -static void mp_semihosting_tx_char(char c) { - mp_semihosting_call(SYS_WRITEC, &c); -} - -uint32_t mp_semihosting_tx_strn(const char *str, size_t len) { - if (len == 0) { - return 0; // nothing to do - } - if (len == 1) { - mp_semihosting_tx_char(*str); // maybe faster? - return 0; - } - - struct { - uint32_t fd; - const char *str; - uint32_t len; - } args = { - .fd = mp_semihosting_stdout, - .str = str, - .len = len, - }; - return mp_semihosting_call(SYS_WRITE, &args); -} - -uint32_t mp_semihosting_tx_strn_cooked(const char *str, size_t len) { - // Write chunks of data until (excluding) the first '\n' character, - // insert a '\r' character, and then continue with the next chunk - // (starting with '\n'). - // Doing byte-by-byte writes would be easier to implement but is far - // too slow. - size_t start = 0; - for (size_t i = 0; i < len; i++) { - if (str[i] == '\n') { - mp_semihosting_tx_strn(str + start, i - start); - mp_semihosting_tx_char('\r'); - start = i; - } - } - return mp_semihosting_tx_strn(str + start, len - start); -} diff --git a/shared/runtime/semihosting.h b/shared/runtime/semihosting.h deleted file mode 100644 index d053a03edaa..00000000000 --- a/shared/runtime/semihosting.h +++ /dev/null @@ -1,51 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2018 Ayke van Laethem - * - * 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_SEMIHOSTING_H -#define MICROPY_INCLUDED_LIB_UTILS_SEMIHOSTING_H - -/* - -To use semi-hosting for a replacement UART: -- Add lib/semihosting/semihosting.c to the Makefile sources. -- Call mp_semihosting_init() in main(), around the time UART is initialized. -- Replace mp_hal_stdin_rx_chr and similar in mphalport.c with the semihosting equivalent. -- Include lib/semihosting/semihosting.h in the relevant files. - -Then make sure the debugger is attached and enables semihosting. In OpenOCD this is -done with ARM semihosting enable followed by reset. The terminal will need further -configuration to work with MicroPython (bash: stty raw -echo). - -*/ - -#include -#include - -void mp_semihosting_init(); -int mp_semihosting_rx_char(); -uint32_t mp_semihosting_tx_strn(const char *str, size_t len); -uint32_t mp_semihosting_tx_strn_cooked(const char *str, size_t len); - -#endif // MICROPY_INCLUDED_LIB_UTILS_SEMIHOSTING_H diff --git a/shared/runtime/semihosting_arm.c b/shared/runtime/semihosting_arm.c new file mode 100644 index 00000000000..f4d168f79bc --- /dev/null +++ b/shared/runtime/semihosting_arm.c @@ -0,0 +1,157 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2018 Ayke van Laethem + * + * 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 "semihosting_arm.h" + +// Resources: +// http://embed.rs/articles/2016/semi-hosting-rust/ +// https://wiki.dlang.org/Minimal_semihosted_ARM_Cortex-M_%22Hello_World%22 +// https://github.com/arduino/OpenOCD/blob/master/src/target/arm_semihosting.c + +#define SYS_OPEN 0x01 +#define SYS_WRITEC 0x03 +#define SYS_WRITE 0x05 +#define SYS_READ 0x06 +#define SYS_READC 0x07 +#define SYS_EXIT 0x18 + +// Constants: +#define OPEN_MODE_READ (0) // mode "r" +#define OPEN_MODE_WRITE (4) // mode "w" + +static int mp_semihosting_stdout; + +static uint32_t mp_semihosting_call(uint32_t num, const void *arg) { + // A semihosting call works as follows, similar to a SVCall: + // * the call is invoked by a special breakpoint: 0xAB + // * the command is placed in r0 + // * a pointer to the arguments is placed in r1 + // * the return value is placed in r0 + // Note that because it uses the breakpoint instruction, applications + // will hang if they're not connected to a debugger. And they'll be + // stuck in a breakpoint if semihosting is not specifically enabled in + // the debugger. + // Also note that semihosting is extremely slow (sometimes >100ms per + // call). + register uint32_t num_reg __asm__ ("r0") = num; + register const void *args_reg __asm__ ("r1") = arg; + __asm__ __volatile__ ( + #if defined(__ARM_ARCH_ISA_ARM) + "svc 0x00123456\n" // invoke semihosting call + #elif defined(__ARM_ARCH_ISA_THUMB) + "bkpt 0xAB\n" // invoke semihosting call + #else + #error Unknown architecture + #endif + : "+r" (num_reg) // call number and result + : "r" (args_reg) // arguments + : "memory"); // make sure args aren't optimized away + return num_reg; // r0, which became the result +} + +static int mp_semihosting_open_console(uint32_t mode) { + struct { + char *name; + uint32_t mode; + uint32_t name_len; + } args = { + .name = ":tt", // magic path to console + .mode = mode, // e.g. "r", "w" (see OPEN_MODE_* constants) + .name_len = 3, // strlen(":tt") + }; + return mp_semihosting_call(SYS_OPEN, &args); +} + +void mp_semihosting_init() { + mp_semihosting_stdout = mp_semihosting_open_console(OPEN_MODE_WRITE); +} + +void mp_semihosting_exit(int status) { + if (status == 0) { + status = 0x20026; + } + mp_semihosting_call(SYS_EXIT, (void *)(uintptr_t)status); +} + +int mp_semihosting_rx_char() { + return mp_semihosting_call(SYS_READC, NULL); +} + +// Returns 0 on success. +int mp_semihosting_rx_chars(char *str, size_t len) { + struct { + uint32_t fd; + const char *str; + uint32_t len; + } args = { + .fd = mp_semihosting_stdout, + .str = str, + .len = len, + }; + return mp_semihosting_call(SYS_READ, &args); +} + +static void mp_semihosting_tx_char(char c) { + mp_semihosting_call(SYS_WRITEC, &c); +} + +uint32_t mp_semihosting_tx_strn(const char *str, size_t len) { + if (len == 0) { + return 0; // nothing to do + } + if (len == 1) { + mp_semihosting_tx_char(*str); // maybe faster? + return 0; + } + + struct { + uint32_t fd; + const char *str; + uint32_t len; + } args = { + .fd = mp_semihosting_stdout, + .str = str, + .len = len, + }; + return mp_semihosting_call(SYS_WRITE, &args); +} + +uint32_t mp_semihosting_tx_strn_cooked(const char *str, size_t len) { + // Write chunks of data until (excluding) the first '\n' character, + // insert a '\r' character, and then continue with the next chunk + // (starting with '\n'). + // Doing byte-by-byte writes would be easier to implement but is far + // too slow. + size_t start = 0; + for (size_t i = 0; i < len; i++) { + if (str[i] == '\n') { + mp_semihosting_tx_strn(str + start, i - start); + mp_semihosting_tx_char('\r'); + start = i; + } + } + return mp_semihosting_tx_strn(str + start, len - start); +} diff --git a/shared/runtime/semihosting_arm.h b/shared/runtime/semihosting_arm.h new file mode 100644 index 00000000000..08fb66578ac --- /dev/null +++ b/shared/runtime/semihosting_arm.h @@ -0,0 +1,55 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2018 Ayke van Laethem + * + * 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_RUNTIME_SEMIHOSTING_ARM_H +#define MICROPY_INCLUDED_SHARED_RUNTIME_SEMIHOSTING_ARM_H + +/* + +To use semi-hosting for a replacement UART: +- Add shared/runtime/semihosting_arm.c to the Makefile sources. +- Call mp_semihosting_init() in main(), around the time UART is initialized. +- Replace mp_hal_stdin_rx_chr and similar in mphalport.c with the semihosting equivalent. +- Include shared/runtime/semihosting_arm.h in the relevant files. + +Then make sure the debugger is attached and enables semihosting. In OpenOCD this is +done with ARM semihosting enable followed by reset. The terminal will need further +configuration to work with MicroPython (bash: stty raw -echo). + +If mp_semihosting_rx_char() doesn't work then try mp_semihosting_rx_chars(str, 1). + +*/ + +#include +#include + +void mp_semihosting_init(); +void mp_semihosting_exit(int status); +int mp_semihosting_rx_char(); +int mp_semihosting_rx_chars(char *str, size_t len); +uint32_t mp_semihosting_tx_strn(const char *str, size_t len); +uint32_t mp_semihosting_tx_strn_cooked(const char *str, size_t len); + +#endif // MICROPY_INCLUDED_SHARED_RUNTIME_SEMIHOSTING_ARM_H diff --git a/shared/runtime/semihosting_rv32.c b/shared/runtime/semihosting_rv32.c new file mode 100644 index 00000000000..1d02b69b23e --- /dev/null +++ b/shared/runtime/semihosting_rv32.c @@ -0,0 +1,481 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2024 Alessandro Gatti + * + * 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 "semihosting_rv32.h" + +#if !defined(__riscv) || !defined(__riscv_xlen) || (__riscv_xlen != 32) +#error "This semihosting support code is only available for RV32 targets." +#endif + +// Features file magic header. +#define MAGIC_SIZE 4 +#define MAGIC_0 0x53 // 'S' +#define MAGIC_1 0x48 // 'H' +#define MAGIC_2 0x46 // 'B' +#define MAGIC_3 0x42 // 'F' + +#define CMDLINE_MIN_BUFFER_SIZE 80 + +#define SYS_OPEN 0x01 +#define SYS_CLOSE 0x02 +#define SYS_WRITEC 0x03 +#define SYS_WRITE0 0x04 +#define SYS_WRITE 0x05 +#define SYS_READ 0x06 +#define SYS_READC 0x07 +#define SYS_ISERROR 0x08 +#define SYS_ISTTY 0x09 +#define SYS_SEEK 0x0A +#define SYS_FLEN 0x0C +#define SYS_TMPNAM 0x0D +#define SYS_REMOVE 0x0E +#define SYS_RENAME 0x0F +#define SYS_CLOCK 0x10 +#define SYS_TIME 0x11 +#define SYS_SYSTEM 0x12 +#define SYS_ERRNO 0x13 +#define SYS_GET_CMDLINE 0x15 +#define SYS_HEAPINFO 0x16 +#define SYS_EXIT 0x18 +#define SYS_EXIT_EXTENDED 0x20 +#define SYS_ELAPSED 0x30 +#define SYS_TICKFREQ 0x31 + +// Extended features availability flags. +static bool exit_extended_available = false; +static bool split_stdout_stderr = false; + +// Perform a semihosting call with the given call number and using the given +// parameters block. +int mp_semihosting_call(uint32_t num, void *arg); + +// Convert the given fopen(3) open mode string into the appropriate integer +// value required by SYS_OPEN. If the mode is invalid, it will return -1. +static int mp_lookup_open_mode(const char *mode); + +// Computes the length of the given string. If it gets passed a NULL pointer +// it will return -1. +static int mp_strlen(const char *string); + +// Check which extended features are advertised by the host system. +static void mp_check_extended_features_availability(void); + +// Write the given string to the host system's debug console. +static int mp_write_to_debug_console(const char *string, size_t length); + +// The host system's STDOUT file handle. +int mp_semihosting_stdout = -1; + +// The host system's STDERR file handle. +int mp_semihosting_stderr = -1; + +int mp_semihosting_open(const char *file_name, const char *file_mode) { + if (file_name == NULL || file_mode == NULL) { + return -1; + } + + int file_name_length = mp_strlen(file_name); + if (file_name_length <= 0) { + return -1; + } + int file_open_mode = mp_lookup_open_mode(file_mode); + if (file_open_mode < 0) { + return -1; + } + + uint32_t arguments[3] = { (uintptr_t)file_name, file_open_mode, file_name_length }; + return mp_semihosting_call(SYS_OPEN, arguments); +} + +int mp_semihosting_close(int handle) { + uint32_t arguments[] = { handle }; + return mp_semihosting_call(SYS_CLOSE, arguments); +} + +void mp_semihosting_writec(char character) { + uint32_t arguments[] = { character }; + mp_semihosting_call(SYS_WRITEC, arguments); +} + +void mp_semihosting_write0(const char *string) { + if (string == NULL) { + return; + } + uint32_t arguments[] = { (uintptr_t)string }; + mp_semihosting_call(SYS_WRITE0, arguments); +} + +int mp_semihosting_write(int handle, const void *data, size_t length) { + if (data == NULL) { + return length; + } + if (length == 0) { + return 0; + } + + uint32_t arguments[] = { handle, (uintptr_t)data, length }; + return mp_semihosting_call(SYS_WRITE, arguments); +} + +int mp_semihosting_read(int handle, void *data, size_t length) { + if (data == NULL) { + return -1; + } + if (length == 0) { + return 0; + } + + uint32_t arguments[] = { handle, (uintptr_t)data, length }; + return mp_semihosting_call(SYS_READ, arguments); +} + +inline int mp_semihosting_readc(void) { + return mp_semihosting_call(SYS_READC, NULL); +} + +int mp_semihosting_iserror(int code) { + uint32_t arguments[] = { code }; + return mp_semihosting_call(SYS_ISERROR, arguments); +} + +int mp_semihosting_istty(int handle) { + uint32_t arguments[] = { handle }; + return mp_semihosting_call(SYS_ISTTY, arguments); +} + +int mp_semihosting_seek(int handle, uint32_t offset) { + uint32_t arguments[] = { handle, offset }; + return mp_semihosting_call(SYS_SEEK, arguments); +} + +int mp_semihosting_flen(int handle) { + uint32_t arguments[] = { handle }; + return mp_semihosting_call(SYS_FLEN, arguments); +} + +int mp_semihosting_tmpnam(uint8_t identifier, void *buffer, size_t buffer_length) { + if (buffer == NULL || buffer_length == 0) { + return -1; + } + + uint32_t arguments[] = { (uintptr_t)buffer, identifier, buffer_length }; + return mp_semihosting_call(SYS_TMPNAM, arguments); +} + +int mp_semihosting_remove(const char *file_name) { + if (file_name == NULL) { + return -1; + } + + int file_name_length = mp_strlen(file_name); + if (file_name_length <= 0) { + return -1; + } + + uint32_t arguments[] = { (uintptr_t)file_name, file_name_length }; + return mp_semihosting_call(SYS_REMOVE, arguments); +} + +int mp_semihosting_rename(const char *old_name, const char *new_name) { + if (old_name == NULL || new_name == NULL) { + return -1; + } + + int old_name_length = mp_strlen(old_name); + if (old_name_length <= 0) { + return -1; + } + + int new_name_length = mp_strlen(new_name); + if (new_name_length <= 0) { + return -1; + } + + uint32_t arguments[] = { + (uintptr_t)old_name, old_name_length, (uintptr_t)new_name, new_name_length + }; + return mp_semihosting_call(SYS_RENAME, arguments); +} + +inline int mp_semihosting_clock(void) { + return mp_semihosting_call(SYS_CLOCK, NULL); +} + +inline int mp_semihosting_time(void) { + return mp_semihosting_call(SYS_TIME, NULL); +} + +int mp_semihosting_system(const char *command) { + if (command == NULL) { + return -1; + } + + int command_length = mp_strlen(command); + if (command_length <= 0) { + return -1; + } + + uint32_t arguments[] = { (uintptr_t)command, command_length }; + return mp_semihosting_call(SYS_SYSTEM, arguments); +} + +inline int mp_semihosting_errno(void) { + return mp_semihosting_call(SYS_ERRNO, NULL); +} + +int mp_semihosting_get_cmdline(void *buffer, size_t buffer_length) { + if (buffer == NULL || buffer_length < CMDLINE_MIN_BUFFER_SIZE) { + return -1; + } + + uint32_t arguments[] = { (uintptr_t)buffer, buffer_length }; + return mp_semihosting_call(SYS_GET_CMDLINE, arguments); +} + +void mp_semihosting_heapinfo(mp_semihosting_heap_info_t *block) { + if (block == NULL) { + return; + } + + uint32_t arguments[] = { (uintptr_t)block }; + mp_semihosting_call(SYS_HEAPINFO, arguments); +} + +void mp_semihosting_exit(uint32_t code, uint32_t subcode) { + uint32_t arguments[] = { code, subcode }; + mp_semihosting_call(SYS_EXIT, arguments); + for (;;) {} +} + +void mp_semihosting_exit_extended(uint32_t code, uint32_t subcode) { + uint32_t arguments[] = { code, subcode }; + mp_semihosting_call(SYS_EXIT_EXTENDED, arguments); + for (;;) {} +} + +int mp_semihosting_elapsed(mp_semihosting_elapsed_ticks_t *ticks) { + if (ticks == NULL) { + return -1; + } + + uint32_t arguments[] = { (uintptr_t)ticks }; + return mp_semihosting_call(SYS_ELAPSED, arguments); +} + +inline int mp_semihosting_tickfreq(void) { + return mp_semihosting_call(SYS_TICKFREQ, NULL); +} + +void mp_semihosting_init() { + mp_check_extended_features_availability(); + mp_semihosting_stdout = mp_semihosting_open(":tt", "w"); + if (split_stdout_stderr) { + mp_semihosting_stderr = mp_semihosting_open(":tt", "a"); + } else { + mp_semihosting_stderr = mp_semihosting_stdout; + } +} + +void mp_check_extended_features_availability(void) { + int features_handle = mp_semihosting_open(":semihosting-features", "r"); + if (features_handle < 0) { + return; + } + + uint8_t magic_buffer[MAGIC_SIZE]; + if (mp_semihosting_flen(features_handle) < sizeof(magic_buffer)) { + mp_semihosting_close(features_handle); + return; + } + + if (mp_semihosting_read(features_handle, magic_buffer, sizeof(magic_buffer)) != 0) { + mp_semihosting_close(features_handle); + return; + } + + if (magic_buffer[0] != MAGIC_0 || + magic_buffer[1] != MAGIC_1 || + magic_buffer[2] != MAGIC_2 || + magic_buffer[3] != MAGIC_3) { + mp_semihosting_close(features_handle); + return; + } + + uint8_t features_byte = 0; + if (mp_semihosting_read(features_handle, &features_byte, sizeof(features_byte)) != 0) { + mp_semihosting_close(features_handle); + return; + } + + mp_semihosting_close(features_handle); + + exit_extended_available = (features_byte & 0x01) != 0; + split_stdout_stderr = (features_byte & 0x02) != 0; +} + +int mp_strlen(const char *string) { + int length = 0; + while (*string++ != 0) { + length += 1; + } + return length; +} + +int mp_lookup_open_mode(const char *mode) { + if (mode == NULL) { + return -1; + } + + int mode_found; + + switch (mode[0]) { + case 'r': + mode_found = 0x00; + break; + case 'w': + mode_found = 0x04; + break; + case 'a': + mode_found = 0x08; + break; + default: + return -1; + } + + switch (mode[1]) { + case 'b': + mode_found |= 0x01; + break; + case '+': + mode_found |= 0x02; + break; + case '\0': + return mode_found; + default: + return -1; + } + + switch (mode[2]) { + case 'b': + if (mode_found & 0x01) { + // 'b' was already seen. + return -1; + } + mode_found |= 1; + break; + case '+': + if (mode_found & 0x02) { + // '+' was already seen. + return -1; + } + mode_found |= 2; + break; + case '\0': + return mode_found; + default: + return -1; + } + + return mode[3] == '\0' ? mode_found : -1; +} + +int mp_semihosting_call(uint32_t num, void *arg) { + register uint32_t call_number_register __asm__ ("x10") = num; + register void *arguments_register __asm__ ("x11") = arg; + + __asm volatile ( + ".option push \n" // Transient options + ".option norvc \n" // Do not emit compressed instructions + ".align 4 \n" // 16 bytes alignment + "slli zero, zero, 0x1F \n" // Entry NOP + "ebreak \n" // Give control to the debugger + "srai zero, zero, 7 \n" // Semihosting call + ".option pop \n" // Restore previous options set + : "+r" (call_number_register) + : "r" (arguments_register) + : "memory" + ); + + return call_number_register; +} + +inline int mp_semihosting_rx_char() { + return mp_semihosting_call(SYS_READC, NULL); +} + +int mp_write_to_debug_console(const char *string, size_t length) { + if (length == 0) { + return 0; + } + + if (length == 1) { + mp_semihosting_writec(*string); + return 0; + } + + return mp_semihosting_write(mp_semihosting_stdout, string, length); +} + +void mp_semihosting_terminate(uint32_t code, uint32_t subcode) { + if (exit_extended_available) { + mp_semihosting_exit_extended(code, subcode); + } else { + mp_semihosting_exit(code, subcode); + } +} + +int mp_semihosting_tx_strn(const char *string, size_t length) { + if (string == NULL) { + return -1; + } + + return mp_write_to_debug_console(string, length); +} + +int mp_semihosting_tx_strn_cooked(const char *string, size_t length) { + if (string == NULL) { + return -1; + } + + if (length == 0) { + return 0; + } + + size_t current_offset = 0; + for (size_t index = 0; index < length; index++) { + if (string[index] != '\n') { + continue; + } + + mp_write_to_debug_console(string + current_offset, index - current_offset); + mp_semihosting_writec('\r'); + current_offset = index; + } + + return mp_write_to_debug_console(string + current_offset, length - current_offset); +} diff --git a/shared/runtime/semihosting_rv32.h b/shared/runtime/semihosting_rv32.h new file mode 100644 index 00000000000..7cabd1692c1 --- /dev/null +++ b/shared/runtime/semihosting_rv32.h @@ -0,0 +1,247 @@ +/* + * This file is part of the MicroPython project, http://micropython.org/ + * + * The MIT License (MIT) + * + * Copyright (c) 2024 Alessandro Gatti + * + * 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_RUNTIME_SEMIHOSTING_RV32_H +#define MICROPY_INCLUDED_SHARED_RUNTIME_SEMIHOSTING_RV32_H + +/* + * To integrate semihosting, make sure to call mp_semihosting_init() first. + * Then, if the host system's STDOUT should be used instead of a UART, replace + * mp_hal_stdin_rx_chr and similar calls in mphalport.c with the semihosting + * equivalents. + * + * At runtime, make sure that the debugger is attached and semihosting is + * enabled on its end. The terminal must be configured in raw mode with local + * echo disabled, on Linux this can be done with "stty raw -echo" on the + * command line. + */ + +/* + * This follows the RISC-V Semihosting specification version 0.3. + * + * That document can be downloaded from + * https://github.com/riscv-non-isa/riscv-semihosting/releases/ + * + * Version 0.3 claims that the current RISC-V Semihosting implementation + * should follow Arm's, and more precisely the "Semihosting for AArch32 + * and AArch64" document, revision 2023Q3. + */ + +#include +#include +#include + +// A container for heap and stack pointers as returned by SYS_HEAPINFO. +typedef struct { + void *heap_base; + void *heap_limit; + void *stack_base; + void *stack_limit; +} mp_semihosting_heap_info_t; + +// A 64-bits value indicating how many ticks were counted since the target +// image's execution started. +typedef struct { + uint32_t low; + uint32_t high; +} mp_semihosting_elapsed_ticks_t; + +// The host system's STDOUT file handle. +extern int mp_semihosting_stdout; + +// The host system's STDERR file handle. If the host system does not support +// explicit STDOUT and STDERR handles, this handle will be aliased to STDOUT +// instead. +extern int mp_semihosting_stderr; + +/* + * Even though exit codes from 0x20000 to 0x20007 are part of the original Arm + * specification document, they are omitted due to them being tied to hardware + * events. Whilst some of them may still have a meaning on the RISC-V + * platform, it is not yet clear which ones are available and which ones are + * not. Thus, only "soft" error codes are provided here although the SYS_EXIT + * and SYS_EXIT_EXTENDED semihosting calls accept any 32-bits integer as an + * exit code. + */ + +enum { + MP_SEMIHOSTING_EXIT_BREAKPOINT = 0x20020, + MP_SEMIHOSTING_EXIT_WATCHPOINT, + MP_SEMIHOSTING_EXIT_STEP_COMPLETE, + MP_SEMIHOSTING_EXIT_RUNTIME_ERROR_UNKNOWN, + MP_SEMIHOSTING_EXIT_INTERNAL_ERROR, + MP_SEMIHOSTING_EXIT_USER_INTERRUPTION, + MP_SEMIHOSTING_EXIT_APPLICATION_EXIT, + MP_SEMIHOSTING_EXIT_STACK_OVERFLOW, + MP_SEMIHOSTING_EXIT_DIVISION_BY_ZERO, + MP_SEMIHOSTING_EXIT_OS_SPECIFIC +}; + +// Initialises semihosting support. +void mp_semihosting_init(); + +// Read a character from the host system's STDIN stream. +int mp_semihosting_rx_char(); + +// Write the given string to the host system's STDOUT stream. +int mp_semihosting_tx_strn(const char *string, size_t length); + +// Write the given string to the host system's STDOUT stream, writing a CR byte +// before each LF byte to be written. +int mp_semihosting_tx_strn_cooked(const char *string, size_t length); + +// Terminates execution with the given code and an optional subcode. This +// will choose the appropriate semihosting call (either SYS_EXIT or +// SYS_EXIT_EXTENDED) depending on the host system's reported capabilities. +noreturn void mp_semihosting_terminate(uint32_t code, uint32_t subcode); + +// Direct semihosting calls access. + +// Open a file on the host system with the given name and file mode. +// The file mode follows fopen(3)'s syntax. The function will return -1 if it +// failed to open the required file, or a file handle number if the operation +// succeeded. To see why the operation failed, call mp_semihosting_errno. +int mp_semihosting_open(const char *file_name, const char *file_mode); + +// Close a file previously opened with mp_semihosting_open. If the file cannot +// be closed, the function will return -1, otherwise it will return 0. To see +// why the operation failed, call mp_semihosting_errno. +int mp_semihosting_close(int handle); + +// Write the given character to the host system's STDOUT file handle. +void mp_semihosting_writec(char character); + +// Write the given NULL-terminated string to the host system's STDOUT file +// handle. +void mp_semihosting_write0(const char *string); + +// Write the given buffer to the given host system file handle. The function +// will return how many characters were left to be written (0 if the operation +// wrote the whole buffer), or -1 if the input buffer pointer is NULL. +int mp_semihosting_write(int handle, const void *data, size_t length); + +// Read from the given host system file handle into the given buffer. The +// function will return how many characters were left to be read (0 if the +// operation read whole buffer), or -1 if the input buffer pointer is NULL. +int mp_semihosting_read(int handle, void *data, size_t length); + +// Read a single character from the host system's STDIN file handle. +int mp_semihosting_readc(void); + +// Check whether the given result code represents an error. The function will +// return a non-zero value if the code is indeed an error, or zero otherwise. +int mp_semihosting_iserror(int code); + +// Check whether the given host system file handle is mapped to an interactive +// device. The function will return 1 if the handle is mapped to an +// interactive device, 0 if it is mapped to a regular file, and anything else +// if an error occurred. +int mp_semihosting_istty(int handle); + +// Move the file pointer on the given host system's file handle to the given +// absolute offset (in bytes). The function will return 0 if the file pointer +// was moved to the requested position, or a negative value if it was not +// possible to do so. To see why the operation failed, call +// mp_semihosting_errno. +int mp_semihosting_seek(int handle, uint32_t offset); + +// Get the length (in bytes) of the host system's file mapped to the given +// handle. The function will return a negative value if an error occurred, or +// the requested file's length (in bytes). +int mp_semihosting_flen(int handle); + +// Create a temporary file on the host system. The function requires a file +// identifier between 0 and 255 (inclusive) that will be bound to the requested +// temporary file. Subsequent calls to mp_semihosting_tmpnam with the same +// identifier will always return the same host system file name. On success, +// the function will fill the given buffer with the host system's file name, +// and will return 0. If the buffer pointer is NULL, the buffer name area is +// too small, or the operation failed on the host system's end, the function +// will return -1 instead. Make sure that the buffer is big enough to contain +// a host system's full path name. +int mp_semihosting_tmpnam(uint8_t identifier, void *buffer, size_t buffer_length); + +// Delete a file on the host system's matching the given file name. The +// function will return 0 if the deletion operation succeeded, or a host system +// dependent error code instead. +int mp_semihosting_remove(const char *file_name); + +// Rename a file on the host system's name matching the given file name to the +// new chosen name. The function will return 0 if the rename operation +// succeeded, or a host system dependent error code instead. +int mp_semihosting_rename(const char *old_name, const char *new_name); + +// Get how many hundredths of a second passed since execution started. If an +// error occurred whilst retrieving clock value, the function will return -1. +int mp_semihosting_clock(void); + +// Get the host system's clock in seconds since midnight of January 1st, 1970 +// at UTC. +int mp_semihosting_time(void); + +// Execute the given command on the host system. The function will return the +// command's result code retrieved on the host system. +int mp_semihosting_system(const char *command); + +// Get the last operation's status code. The function will return the host +// system's errno variable contents, and can be used to see the exact result +// code for failed I/O operations. +int mp_semihosting_errno(void); + +// Get the host system's command line that started execution of the target +// image. The function will fill the given buffer with the command line +// arguments passed to the target executable. The function will return 0 on +// success, or -1 if it failed. Make sure that the buffer can contain at +// least 80 bytes, as it is the minimum supported size defined by the +// specifications document. +int mp_semihosting_get_cmdline(void *buffer, size_t buffer_length); + +// Fill the given heap info structure with the system's stack and heap +// start/end addresses. +void mp_semihosting_heapinfo(mp_semihosting_heap_info_t *block); + +// Terminate the execution with the given reason code and optional subcode. +// This should be preferred over mp_semihosting_exit_extended if the host +// system does not support the SYS_EXIT_EXTENDED semihosting call. In doubt +// use mp_semihosting_terminate instead. +noreturn void mp_semihosting_exit(uint32_t code, uint32_t subcode); + +// Terminate the execution with the given reason code and optional subcode. +// This should be preferred over mp_semihosting_exit if the host system +// supports this semihosting call. In doubt use mp_semihosting_terminate +// instead. +noreturn void mp_semihosting_exit_extended(uint32_t code, uint32_t subcode); + +// Fill the given structure with how many ticks were counted since execution +// started. On success, the function will return 0, or -1 if it was not +// possible to compute the ticks count. +int mp_semihosting_elapsed(mp_semihosting_elapsed_ticks_t *ticks); + +// Get the system's tick frequency. If this value is not known, the function +// will return -1 instead. +int mp_semihosting_tickfreq(void); + +#endif // MICROPY_INCLUDED_SHARED_SEMIHOSTING_RUNTIME_RV32_H diff --git a/shared/runtime/stdout_helpers.c b/shared/runtime/stdout_helpers.c index 5d68747b6aa..0158ae7fe1d 100644 --- a/shared/runtime/stdout_helpers.c +++ b/shared/runtime/stdout_helpers.c @@ -50,7 +50,8 @@ 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) { + // Check i < len first so we never read str[len]. + while (i < len && (last_cr || str[i] != '\n')) { last_cr = str[i] == '\r'; i++; } diff --git a/shared/timeutils/timeutils.c b/shared/timeutils/timeutils.c index 4282a0178dd..0c6916e06dd 100644 --- a/shared/timeutils/timeutils.c +++ b/shared/timeutils/timeutils.c @@ -29,12 +29,27 @@ #include "shared/timeutils/timeutils.h" -// LEAPOCH corresponds to 2000-03-01, which is a mod-400 year, immediately -// after Feb 29. We calculate seconds as a signed integer relative to that. +// To maintain reasonable compatibility with CPython on embedded systems, +// and avoid breaking anytime soon, timeutils functions are required to +// work properly between 1970 and 2099 on all ports. // -// Our timebase is relative to 2000-01-01. - -#define LEAPOCH ((31 + 29) * 86400) +// During that period of time, leap years occur every 4 years without +// exception, so we can keep the code short for 32 bit machines. + +// The last leap day before the required period is Feb 29, 1968. +// This is the number of days to add to get to that date. +#define PREV_LEAP_DAY ((mp_uint_t)(365 + 366 - (31 + 29))) +#define PREV_LEAP_YEAR 1968 + +// On ports where either MICROPY_TIME_SUPPORT_Y2100_AND_BEYOND or +// MICROPY_TIME_SUPPORT_Y1969_AND_BEFORE is enabled, we include extra +// code to support leap years outside of the 'easy' period. +// Computation is then made based on 1600 (a mod-400 year). +// This is the number of days between 1600 and 1968. +#define QC_BASE_DAY 134409 +#define QC_LEAP_YEAR 1600 +// This is the number of leap days between 1600 and 1970 +#define QC_LEAP_DAYS 89 #define DAYS_PER_400Y (365 * 400 + 97) #define DAYS_PER_100Y (365 * 100 + 24) @@ -42,8 +57,20 @@ static const uint16_t days_since_jan1[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; +// type used internally to count small integers relative to epoch +// (using uint when possible produces smaller code on some platforms) +#if MICROPY_TIME_SUPPORT_Y1969_AND_BEFORE +typedef mp_int_t relint_t; +#else +typedef mp_uint_t relint_t; +#endif + bool timeutils_is_leap_year(mp_uint_t year) { + #if MICROPY_TIME_SUPPORT_Y2100_AND_BEYOND || MICROPY_TIME_SUPPORT_Y1969_AND_BEFORE return (year % 4 == 0 && year % 100 != 0) || year % 400 == 0; + #else + return year % 4 == 0; + #endif } // month is one based @@ -65,67 +92,67 @@ mp_uint_t timeutils_year_day(mp_uint_t year, mp_uint_t month, mp_uint_t date) { return yday; } -void timeutils_seconds_since_2000_to_struct_time(mp_uint_t t, timeutils_struct_time_t *tm) { - // The following algorithm was adapted from musl's __secs_to_tm and adapted - // for differences in MicroPython's timebase. - - mp_int_t seconds = t - LEAPOCH; +void timeutils_seconds_since_1970_to_struct_time(timeutils_timestamp_t seconds, timeutils_struct_time_t *tm) { + // The following algorithm was inspired from musl's __secs_to_tm + // and simplified to reduce code footprint in the simple case - mp_int_t days = seconds / 86400; + relint_t days = seconds / 86400; seconds %= 86400; + #if MICROPY_TIME_SUPPORT_Y1969_AND_BEFORE if (seconds < 0) { seconds += 86400; days -= 1; } + #endif tm->tm_hour = seconds / 3600; tm->tm_min = seconds / 60 % 60; tm->tm_sec = seconds % 60; - mp_int_t wday = (days + 2) % 7; // Mar 1, 2000 was a Wednesday (2) + relint_t wday = (days + 3) % 7; // Jan 1, 1970 was a Thursday (3) + #if MICROPY_TIME_SUPPORT_Y1969_AND_BEFORE if (wday < 0) { wday += 7; } + #endif tm->tm_wday = wday; - mp_int_t qc_cycles = days / DAYS_PER_400Y; + days += PREV_LEAP_DAY; + + #if MICROPY_TIME_SUPPORT_Y2100_AND_BEYOND || MICROPY_TIME_SUPPORT_Y1969_AND_BEFORE + // rebase day to the oldest supported date (=> always positive) + mp_uint_t base_year = QC_LEAP_YEAR; + days += QC_BASE_DAY; + mp_uint_t qc_cycles = days / DAYS_PER_400Y; days %= DAYS_PER_400Y; - if (days < 0) { - days += DAYS_PER_400Y; - qc_cycles--; - } - mp_int_t c_cycles = days / DAYS_PER_100Y; + mp_uint_t c_cycles = days / DAYS_PER_100Y; if (c_cycles == 4) { c_cycles--; } days -= (c_cycles * DAYS_PER_100Y); - - mp_int_t q_cycles = days / DAYS_PER_4Y; + #else + mp_uint_t base_year = PREV_LEAP_YEAR; + mp_uint_t qc_cycles = 0; + mp_uint_t c_cycles = 0; + #endif + + mp_uint_t q_cycles = days / DAYS_PER_4Y; + #if MICROPY_TIME_SUPPORT_Y2100_AND_BEYOND || MICROPY_TIME_SUPPORT_Y1969_AND_BEFORE if (q_cycles == 25) { q_cycles--; } + #endif days -= q_cycles * DAYS_PER_4Y; - mp_int_t years = days / 365; + relint_t years = days / 365; if (years == 4) { years--; } days -= (years * 365); - /* We will compute tm_yday at the very end - mp_int_t leap = !years && (q_cycles || !c_cycles); - - tm->tm_yday = days + 31 + 28 + leap; - if (tm->tm_yday >= 365 + leap) { - tm->tm_yday -= 365 + leap; - } - - tm->tm_yday++; // Make one based - */ - - tm->tm_year = 2000 + years + 4 * q_cycles + 100 * c_cycles + 400 * qc_cycles; + tm->tm_year = base_year + years + 4 * q_cycles + 100 * c_cycles + 400 * qc_cycles; // Note: days_in_month[0] corresponds to March - static const int8_t days_in_month[] = {31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 29}; + static const uint8_t days_in_month[] = {31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 29}; mp_int_t month; for (month = 0; days_in_month[month] <= days; month++) { @@ -144,21 +171,28 @@ void timeutils_seconds_since_2000_to_struct_time(mp_uint_t t, timeutils_struct_t } // returns the number of seconds, as an integer, since 2000-01-01 -mp_uint_t timeutils_seconds_since_2000(mp_uint_t year, mp_uint_t month, +timeutils_timestamp_t timeutils_seconds_since_1970(mp_uint_t year, mp_uint_t month, mp_uint_t date, mp_uint_t hour, mp_uint_t minute, mp_uint_t second) { - return - second - + minute * 60 - + hour * 3600 - + (timeutils_year_day(year, month, date) - 1 - + ((year - 2000 + 3) / 4) // add a day each 4 years starting with 2001 - - ((year - 2000 + 99) / 100) // subtract a day each 100 years starting with 2001 - + ((year - 2000 + 399) / 400) // add a day each 400 years starting with 2001 - ) * 86400 - + (year - 2000) * 31536000; + #if MICROPY_TIME_SUPPORT_Y2100_AND_BEYOND || MICROPY_TIME_SUPPORT_Y1969_AND_BEFORE + mp_uint_t ref_year = QC_LEAP_YEAR; + #else + mp_uint_t ref_year = PREV_LEAP_YEAR; + #endif + timeutils_timestamp_t res; + res = ((relint_t)year - 1970) * 365; + res += (year - (ref_year + 1)) / 4; // add a day each 4 years + #if MICROPY_TIME_SUPPORT_Y2100_AND_BEYOND || MICROPY_TIME_SUPPORT_Y1969_AND_BEFORE + res -= (year - (ref_year + 1)) / 100; // subtract a day each 100 years + res += (year - (ref_year + 1)) / 400; // add a day each 400 years + res -= QC_LEAP_DAYS; + #endif + res += timeutils_year_day(year, month, date) - 1; + res *= 86400; + res += hour * 3600 + minute * 60 + second; + return res; } -mp_uint_t timeutils_mktime_2000(mp_uint_t year, mp_int_t month, mp_int_t mday, +timeutils_timestamp_t timeutils_mktime_1970(mp_uint_t year, mp_int_t month, mp_int_t mday, mp_int_t hours, mp_int_t minutes, mp_int_t seconds) { // Normalize the tuple. This allows things like: @@ -211,12 +245,16 @@ mp_uint_t timeutils_mktime_2000(mp_uint_t year, mp_int_t month, mp_int_t mday, year++; } } - return timeutils_seconds_since_2000(year, month, mday, hours, minutes, seconds); + return timeutils_seconds_since_1970(year, month, mday, hours, minutes, seconds); } // Calculate the weekday from the date. // The result is zero based with 0 = Monday. // by Michael Keith and Tom Craver, 1990. int timeutils_calc_weekday(int y, int m, int d) { - return ((d += m < 3 ? y-- : y - 2, 23 * m / 9 + d + 4 + y / 4 - y / 100 + y / 400) + 6) % 7; + return ((d += m < 3 ? y-- : y - 2, 23 * m / 9 + d + 4 + y / 4 + #if MICROPY_TIME_SUPPORT_Y2100_AND_BEYOND || MICROPY_TIME_SUPPORT_Y1969_AND_BEFORE + - y / 100 + y / 400 + #endif + ) + 6) % 7; } diff --git a/shared/timeutils/timeutils.h b/shared/timeutils/timeutils.h index e2a2666e910..35356b462aa 100644 --- a/shared/timeutils/timeutils.h +++ b/shared/timeutils/timeutils.h @@ -27,12 +27,23 @@ #ifndef MICROPY_INCLUDED_LIB_TIMEUTILS_TIMEUTILS_H #define MICROPY_INCLUDED_LIB_TIMEUTILS_TIMEUTILS_H -// CIRCUITPY-CHANGE: MICROPY_EPOCH_IS_1970 -#include "mpconfigport.h" +#include "py/obj.h" +#if MICROPY_PY_BUILTINS_FLOAT && MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE +#include // required for trunc() +#endif + +// `timeutils_timestamp_t` is the type used internally by timeutils to +// represent timestamps, and is always referenced to 1970. +// It may not match the platform-specific `mp_timestamp_t`. +#if MICROPY_TIME_SUPPORT_Y2100_AND_BEYOND || MICROPY_TIME_SUPPORT_Y1969_AND_BEFORE +typedef long long timeutils_timestamp_t; +#else +typedef mp_uint_t timeutils_timestamp_t; +#endif // The number of seconds between 1970/1/1 and 2000/1/1 is calculated using: // time.mktime((2000,1,1,0,0,0,0,0,0)) - time.mktime((1970,1,1,0,0,0,0,0,0)) -#define TIMEUTILS_SECONDS_1970_TO_2000 (946684800ULL) +#define TIMEUTILS_SECONDS_1970_TO_2000 (946684800LL) typedef struct _timeutils_struct_time_t { uint16_t tm_year; // i.e. 2014 @@ -48,62 +59,116 @@ typedef struct _timeutils_struct_time_t { bool timeutils_is_leap_year(mp_uint_t year); mp_uint_t timeutils_days_in_month(mp_uint_t year, mp_uint_t month); mp_uint_t timeutils_year_day(mp_uint_t year, mp_uint_t month, mp_uint_t date); +int timeutils_calc_weekday(int y, int m, int d); -void timeutils_seconds_since_2000_to_struct_time(mp_uint_t t, +void timeutils_seconds_since_1970_to_struct_time(timeutils_timestamp_t t, timeutils_struct_time_t *tm); -mp_uint_t timeutils_seconds_since_2000(mp_uint_t year, mp_uint_t month, +// Year is absolute, month/date are 1-based, hour/minute/second are 0-based. +timeutils_timestamp_t timeutils_seconds_since_1970(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 timeutils_mktime_2000(mp_uint_t year, mp_int_t month, mp_int_t mday, +// Year is absolute, month/mday are 1-based, hours/minutes/seconds are 0-based. +timeutils_timestamp_t timeutils_mktime_1970(mp_uint_t year, mp_int_t month, mp_int_t mday, mp_int_t hours, mp_int_t minutes, mp_int_t seconds); +static inline mp_timestamp_t timeutils_obj_get_timestamp(mp_obj_t o_in) { + #if MICROPY_PY_BUILTINS_FLOAT && MICROPY_FLOAT_IMPL == MICROPY_FLOAT_IMPL_DOUBLE + mp_float_t val = mp_obj_get_float(o_in); + return (mp_timestamp_t)MICROPY_FLOAT_C_FUN(trunc)(val); + #elif MICROPY_TIMESTAMP_IMPL == MICROPY_TIMESTAMP_IMPL_UINT + return mp_obj_get_uint(o_in); + #else + return mp_obj_get_ll(o_in); + #endif +} + +static inline mp_obj_t timeutils_obj_from_timestamp(mp_timestamp_t t) { + #if MICROPY_TIMESTAMP_IMPL == MICROPY_TIMESTAMP_IMPL_UINT + return mp_obj_new_int_from_uint(t); + #else + return mp_obj_new_int_from_ll(t); + #endif +} + +static inline void timeutils_seconds_since_2000_to_struct_time(mp_timestamp_t t, timeutils_struct_time_t *tm) { + timeutils_seconds_since_1970_to_struct_time((timeutils_timestamp_t)(t + TIMEUTILS_SECONDS_1970_TO_2000), tm); +} + +// Year is absolute, month/date are 1-based, hour/minute/second are 0-based. +static inline mp_timestamp_t timeutils_seconds_since_2000(mp_uint_t year, mp_uint_t month, mp_uint_t date, + mp_uint_t hour, mp_uint_t minute, mp_uint_t second) { + return (mp_timestamp_t)timeutils_seconds_since_1970(year, month, date, hour, minute, second) - TIMEUTILS_SECONDS_1970_TO_2000; +} + +// Year is absolute, month/mday are 1-based, hours/minutes/seconds are 0-based. +static inline mp_timestamp_t timeutils_mktime_2000(mp_uint_t year, mp_int_t month, mp_int_t mday, + mp_int_t hours, mp_int_t minutes, mp_int_t seconds) { + return (mp_timestamp_t)timeutils_mktime_1970(year, month, mday, hours, minutes, seconds) - TIMEUTILS_SECONDS_1970_TO_2000; +} + + // Select the Epoch used by the port. #if MICROPY_EPOCH_IS_1970 -static inline void timeutils_seconds_since_epoch_to_struct_time(uint64_t t, timeutils_struct_time_t *tm) { - // TODO this will give incorrect results for dates before 2000/1/1 - timeutils_seconds_since_2000_to_struct_time(t - TIMEUTILS_SECONDS_1970_TO_2000, tm); +static inline void timeutils_seconds_since_epoch_to_struct_time(mp_timestamp_t t, timeutils_struct_time_t *tm) { + timeutils_seconds_since_1970_to_struct_time(t, tm); +} + +// Year is absolute, month/date are 1-based, hour/minute/second are 0-based. +static inline mp_timestamp_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) { + return timeutils_seconds_since_1970(year, month, date, hour, minute, second); } -static inline uint64_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) { - return timeutils_mktime_2000(year, month, mday, hours, minutes, seconds) + TIMEUTILS_SECONDS_1970_TO_2000; +// Year is absolute, month/mday are 1-based, hours/minutes/seconds are 0-based. +static inline mp_timestamp_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) { + return timeutils_mktime_1970(year, month, mday, hours, minutes, seconds); } -static inline uint64_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) { - // TODO this will give incorrect results for dates before 2000/1/1 - return timeutils_seconds_since_2000(year, month, date, hour, minute, second) + TIMEUTILS_SECONDS_1970_TO_2000; +static inline mp_timestamp_t timeutils_seconds_since_epoch_from_nanoseconds_since_1970(int64_t ns) { + return (mp_timestamp_t)(ns / 1000000000LL); } -static inline mp_uint_t timeutils_seconds_since_epoch_from_nanoseconds_since_1970(uint64_t ns) { - return ns / 1000000000ULL; +static inline int64_t timeutils_seconds_since_epoch_to_nanoseconds_since_1970(mp_timestamp_t s) { + return (int64_t)s * 1000000000LL; } -static inline uint64_t timeutils_nanoseconds_since_epoch_to_nanoseconds_since_1970(uint64_t ns) { +static inline int64_t timeutils_nanoseconds_since_epoch_to_nanoseconds_since_1970(int64_t ns) { return ns; } #else // Epoch is 2000 -#define timeutils_seconds_since_epoch_to_struct_time timeutils_seconds_since_2000_to_struct_time -#define timeutils_seconds_since_epoch timeutils_seconds_since_2000 -#define timeutils_mktime timeutils_mktime_2000 +static inline void timeutils_seconds_since_epoch_to_struct_time(mp_timestamp_t t, timeutils_struct_time_t *tm) { + timeutils_seconds_since_2000_to_struct_time(t, tm); +} + +// Year is absolute, month/date are 1-based, hour/minute/second are 0-based. +static inline mp_timestamp_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) { + return timeutils_seconds_since_2000(year, month, date, hour, minute, second); +} + +// Year is absolute, month/mday are 1-based, hours/minutes/seconds are 0-based. +static inline mp_timestamp_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) { + return timeutils_mktime_2000(year, month, mday, hours, minutes, seconds); +} -static inline uint64_t timeutils_seconds_since_epoch_to_nanoseconds_since_1970(mp_uint_t s) { - return ((uint64_t)s + TIMEUTILS_SECONDS_1970_TO_2000) * 1000000000ULL; +static inline mp_timestamp_t timeutils_seconds_since_epoch_from_nanoseconds_since_1970(int64_t ns) { + return (mp_timestamp_t)(ns / 1000000000LL - TIMEUTILS_SECONDS_1970_TO_2000); } -static inline mp_uint_t timeutils_seconds_since_epoch_from_nanoseconds_since_1970(uint64_t ns) { - return ns / 1000000000ULL - TIMEUTILS_SECONDS_1970_TO_2000; +static inline int64_t timeutils_seconds_since_epoch_to_nanoseconds_since_1970(mp_timestamp_t s) { + return ((int64_t)s + TIMEUTILS_SECONDS_1970_TO_2000) * 1000000000LL; } static inline int64_t timeutils_nanoseconds_since_epoch_to_nanoseconds_since_1970(int64_t ns) { - return ns + TIMEUTILS_SECONDS_1970_TO_2000 * 1000000000ULL; + return ns + TIMEUTILS_SECONDS_1970_TO_2000 * 1000000000LL; } #endif -int timeutils_calc_weekday(int y, int m, int d); - #endif // MICROPY_INCLUDED_LIB_TIMEUTILS_TIMEUTILS_H diff --git a/shared/upytesthelper/upytesthelper.c b/shared/upytesthelper/upytesthelper.c deleted file mode 100644 index ba20037f7ac..00000000000 --- a/shared/upytesthelper/upytesthelper.c +++ /dev/null @@ -1,137 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2017 Linaro Limited - * - * 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 "py/gc.h" -#include "py/runtime.h" -#include "py/compile.h" -#include "upytesthelper.h" - -#if !MICROPY_PY_SYS_PATH -#error "upytesthelper requires MICROPY_PY_SYS_PATH=1" -#endif - -#if !MICROPY_PY_SYS_ARGV -#error "upytesthelper requires MICROPY_PY_SYS_ARGV=1" -#endif - -static const char *test_exp_output; -static int test_exp_output_len, test_rem_output_len; -static int test_failed; -static void *heap_start, *heap_end; - -void upytest_set_heap(void *start, void *end) { - heap_start = start; - heap_end = end; -} - -void upytest_set_expected_output(const char *output, unsigned len) { - test_exp_output = output; - test_exp_output_len = test_rem_output_len = len; - test_failed = false; -} - -bool upytest_is_failed(void) { - if (test_failed) { - return true; - } - #if 0 - if (test_rem_output_len != 0) { - printf("remaining len: %d\n", test_rem_output_len); - } - #endif - return test_rem_output_len != 0; -} - -// MP_PLAT_PRINT_STRN() should be redirected to this function. -// It will pass-through any content to mp_hal_stdout_tx_strn_cooked() -// (the default value of MP_PLAT_PRINT_STRN), but will also match -// it to the expected output as set by upytest_set_expected_output(). -// If mismatch happens, upytest_is_failed() returns true. -void upytest_output(const char *str, mp_uint_t len) { - if (!test_failed) { - if (len > test_rem_output_len) { - test_failed = true; - } else { - test_failed = memcmp(test_exp_output, str, len); - #if 0 - if (test_failed) { - printf("failed after char %u, within %d chars, res: %d\n", - test_exp_output_len - test_rem_output_len, (int)len, test_failed); - for (int i = 0; i < len; i++) { - if (str[i] != test_exp_output[i]) { - printf("%d %02x %02x\n", i, str[i], test_exp_output[i]); - } - } - } - #endif - test_exp_output += len; - test_rem_output_len -= len; - } - } - mp_hal_stdout_tx_strn_cooked(str, len); -} - -void upytest_execute_test(const char *src) { - // To provide clean room for each test, interpreter and heap are - // reinitialized before running each. - gc_init(heap_start, heap_end); - mp_init(); - mp_sys_path = mp_obj_new_list(0, NULL); - #if MICROPY_MODULE_FROZEN - mp_obj_list_append(mp_sys_path, MP_OBJ_NEW_QSTR(MP_QSTR__dot_frozen)); - #endif - mp_obj_list_init(mp_sys_argv, 0); - - nlr_buf_t nlr; - if (nlr_push(&nlr) == 0) { - mp_lexer_t *lex = mp_lexer_new_from_str_len(MP_QSTR__lt_stdin_gt_, src, strlen(src), 0); - qstr source_name = lex->source_name; - mp_parse_tree_t parse_tree = mp_parse(lex, MP_PARSE_FILE_INPUT); - mp_obj_t module_fun = mp_compile(&parse_tree, source_name, false); - mp_call_function_0(module_fun); - nlr_pop(); - } else { - mp_obj_t exc = (mp_obj_t)nlr.ret_val; - if (mp_obj_is_subclass_fast(mp_obj_get_type(exc), &mp_type_SystemExit)) { - // Assume that sys.exit() is called to skip the test. - // TODO: That can be always true, we should set up convention to - // use specific exit code as skip indicator. - tinytest_set_test_skipped_(); - goto end; - } - mp_obj_print_exception(&mp_plat_print, exc); - tt_abort_msg("Uncaught exception\n"); - } - - if (upytest_is_failed()) { - tinytest_set_test_failed_(); - } - -end: - mp_deinit(); -} diff --git a/shared/upytesthelper/upytesthelper.h b/shared/upytesthelper/upytesthelper.h deleted file mode 100644 index 3a292befd77..00000000000 --- a/shared/upytesthelper/upytesthelper.h +++ /dev/null @@ -1,37 +0,0 @@ -/* - * This file is part of the MicroPython project, http://micropython.org/ - * - * The MIT License (MIT) - * - * Copyright (c) 2017 Linaro Limited - * - * 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 "py/mpconfig.h" -#include "lib/tinytest/tinytest.h" -#include "lib/tinytest/tinytest_macros.h" - -void upytest_set_heap(void *start, void *end); -void upytest_set_expected_output(const char *output, unsigned len); -void upytest_execute_test(const char *src); -void upytest_output(const char *str, mp_uint_t len); -bool upytest_is_failed(void); diff --git a/stubs/micropython/__init__.pyi b/stubs/micropython/__init__.pyi new file mode 100644 index 00000000000..1bcde6ae813 --- /dev/null +++ b/stubs/micropython/__init__.pyi @@ -0,0 +1,20 @@ +"""Access and control MicroPython internals""" + +def const[T](expr: T) -> T: + """Used to declare that the expression is a constant so that the compiler + can optimise it. The use of this function should be as follows:: + + from micropython import const + + CONST_X = const(123) + CONST_Y = const(2 * CONST_X + 1) + + Constants declared this way are still accessible as global variables from + outside the module they are declared in. On the other hand, if a constant + begins with an underscore then it is hidden, it is not available as a global + variable, and does not take up any memory during execution. + + This `const` function is recognised directly by the MicroPython parser and is + provided as part of the :mod:`micropython` module mainly so that scripts can be + written which run under both CPython and MicroPython, by following the above + pattern.""" diff --git a/supervisor/background_callback.h b/supervisor/background_callback.h index b26a683ad20..8fd22571a21 100644 --- a/supervisor/background_callback.h +++ b/supervisor/background_callback.h @@ -61,9 +61,22 @@ void background_callback_run_all(void); * interrupts are disabled. */ bool background_callback_pending(void); -/* During soft reset, remove all pending callbacks and clear the critical section flag */ +/* During soft reset, remove pending callbacks that are on the GC heap or whose data is on + * the GC heap, and cancel any background_callback_prevent() calls. + * + * Until background_callback_heap_ready() is called, background_callback_add() also drops + * any new callback that is on the heap or whose data is on the heap. Hardware owned by a + * heap object can keep interrupting until the object's finaliser stops it. A callback + * queued during teardown would still be pending after the heap is freed. + */ void background_callback_reset(void); +/* Let background_callback_add() queue callbacks on the GC heap again, after + * background_callback_reset() stopped it. Call once gc_init() has set up the new heap. + * Never fails. + */ +void background_callback_heap_ready(void); + /* Sometimes background callbacks must be blocked. Use these functions to * bracket the section of code where this is the case. These calls nest, and * begins must be balanced with ends. diff --git a/supervisor/fatfs.h b/supervisor/fatfs.h index e212664210d..0dc1f3b6876 100644 --- a/supervisor/fatfs.h +++ b/supervisor/fatfs.h @@ -6,6 +6,14 @@ #pragma once +#include + #include "lib/oofatfs/ff.h" void override_fattime(DWORD time); + +// Current time in nanoseconds past 1970/1/1, read from the same RTC source +// that get_fattime() uses. When there is no RTC, this is the same fixed +// fallback timestamp get_fattime() falls back to, so every filesystem kind +// stamps files with the same "current time". +uint64_t get_fattime_ns(void); diff --git a/supervisor/filesystem.h b/supervisor/filesystem.h index a0445b0510d..860f1c9c116 100644 --- a/supervisor/filesystem.h +++ b/supervisor/filesystem.h @@ -9,9 +9,175 @@ #include #include "extmod/vfs_fat.h" +#if CIRCUITPY_FILESYSTEM_LITTLEFS +#include "extmod/vfs_lfs.h" +#endif + +// A supervisor-managed filesystem object, which is either a FAT fs_user_mount_t +// or, on littlefs builds, an mp_obj_vfs_lfs2_t. Both begin with the same +// mp_obj_base_t + mp_vfs_blockdev_t prefix, so a bare fs_user_mount_t (e.g. an +// SD card mount) can also be cast to supervisor_vfs_t and inspected through +// .common. The two kinds are told apart by base.type: &mp_fat_vfs_type vs +// &mp_type_vfs_lfs2. +typedef union _supervisor_vfs_t { + struct { + mp_obj_base_t base; + mp_vfs_blockdev_t blockdev; + } common; + fs_user_mount_t fat; + #if CIRCUITPY_FILESYSTEM_LITTLEFS + mp_obj_vfs_lfs2_t lfs2; + #endif +} supervisor_vfs_t; extern volatile bool filesystem_flush_requested; +// Supervisor-level filesystem API. These functions work on both FAT and +// littlefs mounts so that supervisor code (workflows, settings) doesn't have to +// care which one is active. These APIs do not raise Python exceptions or use VM +// heap allocated memory so they are safe use when the Python VM isn't active. + +// Open flags for supervisor_vfs_open_file(). +#define SUPERVISOR_FS_OPEN_READ 0x01 +#define SUPERVISOR_FS_OPEN_WRITE 0x02 +// Create the file if it doesn't exist (with WRITE). An existing file keeps its +// contents. +#define SUPERVISOR_FS_OPEN_CREATE 0x04 +// Empty an existing file on open (with WRITE|CREATE). +#define SUPERVISOR_FS_OPEN_TRUNCATE 0x08 + +// Error codes shared by the supervisor filesystem API. +#if CIRCUITPY_FILESYSTEM_LITTLEFS + +// When littlefs is enabled, FatFS and littlefs results are mapped to these +// shared codes so call sites can be shared between FAT and littlefs. +typedef enum { + SUPERVISOR_FS_OK = 0, + SUPERVISOR_FS_NO_FILE, // File or directory doesn't exist. + SUPERVISOR_FS_NO_PATH, // A path component is missing (or bad). + SUPERVISOR_FS_EXIST, // File or directory already exists. + SUPERVISOR_FS_WRITE_PROTECTED, // Filesystem or media is not writable. + SUPERVISOR_FS_NO_SPACE, // No space left on the filesystem. + SUPERVISOR_FS_IO, // Any other error. + SUPERVISOR_FS_BUSY, // The running program uses the file; try again once it stops. +} supervisor_fs_err_t; + +// littlefs mtime attribute id, matching extmod/vfs_lfs.c: +// 64-bit little endian, nanoseconds since 1970/1/1. +#ifndef LFS_ATTR_MTIME +#define LFS_ATTR_MTIME (1) +#endif + +#else + +// On FAT-only builds the errors are FatFS FRESULT values so +// that supervisor_vfs_* calls compile down to plain FatFS calls without any +// error translation, keeping non-littlefs builds the same size as before the +// supervisor filesystem API was added. The littlefs build's enum above maps +// onto the same FRESULT subset that the workflows use. +typedef FRESULT supervisor_fs_err_t; +#define SUPERVISOR_FS_OK FR_OK +#define SUPERVISOR_FS_NO_FILE FR_NO_FILE +#define SUPERVISOR_FS_NO_PATH FR_NO_PATH +#define SUPERVISOR_FS_EXIST FR_EXIST +#define SUPERVISOR_FS_WRITE_PROTECTED FR_WRITE_PROTECTED +#define SUPERVISOR_FS_NO_SPACE FR_DENIED +#define SUPERVISOR_FS_IO FR_INT_ERR +#define SUPERVISOR_FS_BUSY FR_LOCKED // FF_FS_LOCK is 0, so only mapped files + +#endif + +// Handle for a file opened with supervisor_vfs_open_file(). +typedef struct _supervisor_vfs_file_t { + bool open; + #if CIRCUITPY_FILESYSTEM_LITTLEFS + bool lfs; + // Which mount the file is open on. Unused on FAT, where the FIL carries + // its own filesystem. + supervisor_vfs_t *vfs; + #endif + // FAT: timestamp to stamp the file with on close (0 = current time). + DWORD fattime; + union { + FIL fat; + #if CIRCUITPY_FILESYSTEM_LITTLEFS + struct { + lfs2_file_t lfs2; + struct lfs2_file_config cfg; + struct lfs2_attr attr; + uint8_t mtime[8]; + uint8_t buffer[FILESYSTEM_BLOCK_SIZE]; + } lfs; + #endif + } file; +} supervisor_vfs_file_t; + +// Directory handle for supervisor_vfs_opendir(). +typedef struct _supervisor_vfs_dir_t { + bool open; + #if CIRCUITPY_FILESYSTEM_LITTLEFS + bool lfs; + // Directory path used to build per-entry paths for littlefs, which keeps + // modification times in per-path attributes. Unused on FAT. + #define SUPERVISOR_VFS_DIR_PATH_MAX (256) + char path[SUPERVISOR_VFS_DIR_PATH_MAX]; + // Which mount the directory is open on. Unused on FAT. + supervisor_vfs_t *vfs; + #endif + union { + FF_DIR fat; + #if CIRCUITPY_FILESYSTEM_LITTLEFS + lfs2_dir_t lfs2; + #endif + } dir; +} supervisor_vfs_dir_t; + +// Open a file on the given mount. path is relative to the mount. mtime_ns is +// the modification time to use for a newly written file, in nanoseconds past +// 1970/1/1, or 0 to use the current RTC time (the same time get_fattime() +// stamps FAT files with, including its fixed fallback when there is no RTC). On success, file must be closed with +// supervisor_vfs_close_file(). +supervisor_fs_err_t supervisor_vfs_open_file(supervisor_vfs_t *vfs, const char *path, uint32_t flags, + uint64_t mtime_ns, supervisor_vfs_file_t *file); +supervisor_fs_err_t supervisor_vfs_close_file(supervisor_vfs_file_t *file); +// Read at most len bytes into buf. On success *bytes_read holds the number of +// bytes read; it may be less than len, and 0 at end of file. +supervisor_fs_err_t supervisor_vfs_read_file(supervisor_vfs_file_t *file, void *buf, size_t len, size_t *bytes_read); +// Write len bytes. On success *bytes_written holds the number of bytes +// written; it is less than len when the filesystem is full. +supervisor_fs_err_t supervisor_vfs_write_file(supervisor_vfs_file_t *file, const void *buf, size_t len, size_t *bytes_written); +// Seek to an absolute offset from the start of the file. +supervisor_fs_err_t supervisor_vfs_seek_file(supervisor_vfs_file_t *file, size_t offset); +// Current absolute offset from the start of the file. +size_t supervisor_vfs_tell_file(supervisor_vfs_file_t *file); +// File size in bytes. +size_t supervisor_vfs_file_size(supervisor_vfs_file_t *file); +// Truncate the file to the current offset. +supervisor_fs_err_t supervisor_vfs_truncate_file(supervisor_vfs_file_t *file); + +// Stat a file or directory. All output arguments are optional (may be NULL). +// size is 0 for directories. mtime_ns is nanoseconds past the same epoch used +// for the littlefs mtime attribute (1970/1/1) and is 0 when unknown. +supervisor_fs_err_t supervisor_vfs_stat(supervisor_vfs_t *vfs, const char *path, bool *is_dir, size_t *size, uint64_t *mtime_ns); +// Create a directory. mtime_ns is used to stamp it on FAT, 0 to use the +// current RTC time. littlefs directories have no modification time. +supervisor_fs_err_t supervisor_vfs_mkdir(supervisor_vfs_t *vfs, const char *path, uint64_t mtime_ns); +supervisor_fs_err_t supervisor_vfs_rename(supervisor_vfs_t *vfs, const char *old_path, const char *new_path); +supervisor_fs_err_t supervisor_vfs_unlink(supervisor_vfs_t *vfs, const char *path); + +// Open a directory for listing. path is relative to the mount. +supervisor_fs_err_t supervisor_vfs_opendir(supervisor_vfs_t *vfs, const char *path, supervisor_vfs_dir_t *dir); +// Read the next directory entry. On success name holds a null-terminated entry +// name; at the end of the directory, name is empty. The other output arguments +// are optional (may be NULL). +supervisor_fs_err_t supervisor_vfs_readdir(supervisor_vfs_dir_t *dir, char *name, size_t name_len, bool *is_dir, size_t *size, uint64_t *mtime_ns); +supervisor_fs_err_t supervisor_vfs_rewinddir(supervisor_vfs_dir_t *dir); +supervisor_fs_err_t supervisor_vfs_closedir(supervisor_vfs_dir_t *dir); + +// Filesystem geometry in blocks. For FAT these are clusters; for littlefs, +// blocks. +supervisor_fs_err_t supervisor_vfs_statfs(supervisor_vfs_t *vfs, size_t *block_size, size_t *total_blocks, size_t *free_blocks); + void filesystem_background(void); void filesystem_tick(void); bool filesystem_init(bool create_allowed, bool force_create); @@ -19,29 +185,35 @@ void filesystem_flush(void); bool filesystem_present(void); void filesystem_set_internal_writable_by_usb(bool usb_writable); void filesystem_set_internal_concurrent_write_protection(bool concurrent_write_protection); -void filesystem_set_writable_by_usb(fs_user_mount_t *vfs, bool usb_writable); -void filesystem_set_concurrent_write_protection(fs_user_mount_t *vfs, bool concurrent_write_protection); +void filesystem_set_writable_by_usb(supervisor_vfs_t *vfs, bool usb_writable); +void filesystem_set_concurrent_write_protection(supervisor_vfs_t *vfs, bool concurrent_write_protection); +void filesystem_set_ignore_write_protection(fs_user_mount_t *vfs, bool ignore_write_protection); // Whether user code can modify the filesystem. It doesn't depend on the state // of USB. Don't use this for a workflow. In workflows, grab the shared file // system lock. -bool filesystem_is_writable_by_python(fs_user_mount_t *vfs); +bool filesystem_is_writable_by_python(supervisor_vfs_t *vfs); // This controls whether USB tries to grab the underlying block device lock // during enumeration. If another workflow is modifying the filesystem when this // happens, then USB will be readonly. bool filesystem_is_writable_by_usb(fs_user_mount_t *vfs); -fs_user_mount_t *filesystem_circuitpy(void); -fs_user_mount_t *filesystem_for_path(const char *path_in, const char **path_under_mount); -bool filesystem_native_fatfs(fs_user_mount_t *fs_mount); +supervisor_vfs_t *filesystem_circuitpy(void); +supervisor_vfs_t *filesystem_for_path(const char *path_in, const char **path_under_mount); + +// Whether the supervisor-level filesystem API (above) can operate on this +// mount: FAT mounts reachable through FatFS and supervisor littlefs mounts. +// Use it to reject mounts (e.g. non-native or remote filesystems) that the +// workflows cannot access. +bool supervisor_vfs_supported(supervisor_vfs_t *fs_mount); // We have two levels of locking. filesystem_* calls grab a shared blockdev lock to allow // CircuitPython's fatfs code to edit the blocks. blockdev_* calls grab a lock to mutate blocks // directly, excluding any filesystem_* locks. -bool filesystem_lock(fs_user_mount_t *fs_mount); -void filesystem_unlock(fs_user_mount_t *fs_mount); +bool filesystem_lock(supervisor_vfs_t *fs_mount); +void filesystem_unlock(supervisor_vfs_t *fs_mount); -bool blockdev_lock(fs_user_mount_t *fs_mount); -void blockdev_unlock(fs_user_mount_t *fs_mount); +bool blockdev_lock(supervisor_vfs_t *fs_mount); +void blockdev_unlock(supervisor_vfs_t *fs_mount); diff --git a/supervisor/flash.h b/supervisor/flash.h index ca3e42735ff..fdc1713d68f 100644 --- a/supervisor/flash.h +++ b/supervisor/flash.h @@ -28,6 +28,13 @@ struct _fs_user_mount_t; void supervisor_flash_init_vfs(struct _fs_user_mount_t *vfs); void supervisor_flash_flush(void); void supervisor_flash_release_cache(void); +void supervisor_flash_mark_dirty(void); + +#if CIRCUITPY_STORAGE_MAP_FILE +// storage.map_file: flash address of a CIRCUITPY FatFs sector, NULL if the port cannot map the +// drive there; *contiguous receives how many sectors from it are contiguous in the mapping. +const uint8_t *supervisor_flash_xip_address(uint32_t fatfs_sector, uint32_t *contiguous); +#endif void supervisor_flash_set_extended(bool extended); bool supervisor_flash_get_extended(void); diff --git a/supervisor/port.h b/supervisor/port.h index 29c071515c1..3d927318a1c 100644 --- a/supervisor/port.h +++ b/supervisor/port.h @@ -9,6 +9,7 @@ #include #include +#include "py/obj.h" #include "supervisor/shared/safe_mode.h" // Provided by the linker; @@ -23,13 +24,16 @@ extern uint32_t _ebss; safe_mode_t port_init(void); // Reset the microcontroller completely. -void reset_cpu(void) NORETURN; +void reset_cpu(void) MP_NORETURN; + +// Reset port state that must be torn down before anything else is reset. +void reset_port_early(void); // Reset the microcontroller state. void reset_port(void); // Reset to the bootloader -void reset_to_bootloader(void) NORETURN; +void reset_to_bootloader(void) MP_NORETURN; // Get stack limit address uint32_t *port_stack_get_limit(void); @@ -91,15 +95,17 @@ void port_wake_main_task(void); void port_wake_main_task_from_isr(void); // Some ports may use real RTOS tasks besides the background task framework of -// CircuitPython. Calling this will yield to other tasks and then return to the -// CircuitPython task when others are done. -void port_yield(void); - -// Some ports need special handling just after completing boot.py execution. -// This function is called once while boot.py's VM is still valid, and -// then a second time after the VM is finalized. -// A default weak implementation is provided that does nothing. -void port_post_boot_py(bool heap_valid); +// CircuitPython. Calling this will yield to other tasks at the same priority level +// (or higher priority level if pre-emption is not immediate in the RTOS) +// and then return to the CircuitPython task when others are done. +// Note that this does NOT yield to lower priority tasks. Use port_task_sleep_ms() instead. +void port_task_yield(void); + +// On ports using real RTOS tasks, yield to other tasks for at least msecs. +// This will allow lower priority tasks to run. +// On non-RTOS implementations, this just sleeps for msecs and will run CircuitPython +// background tasks. +void port_task_sleep_ms(uint32_t msecs); // Some ports want to add information to boot_out.txt. // A default weak implementation is provided that does nothing. @@ -108,3 +114,25 @@ void port_boot_info(void); // Some ports want to mark additional pointers as gc roots. // A default weak implementation is provided that does nothing. void port_gc_collect(void); + +// Called once the VM heap is torn down and its finalisers have run. Ports free +// memory here that heap objects may point into. +// A default weak implementation is provided that does nothing. +void port_gc_deinit(void); + +// Most ports that implement CIRCUITPY_BOOT_BUTTON use a generic version of +// this function to sense the button. Ports that need to can override this +// function to provide their own implementation. +bool port_boot_button_pressed(void); + +// Allocating objects on the port heap, not the VM heap. +#define mp_obj_port_malloc(struct_type, obj_type) ((struct_type *)mp_obj_port_malloc_helper(sizeof(struct_type), obj_type)) +#define mp_obj_port_malloc_var(struct_type, var_field, var_type, var_num, obj_type) ((struct_type *)mp_obj_port_malloc_helper(offsetof(struct_type, var_field) + sizeof(var_type) * (var_num), obj_type)) + +void *mp_obj_port_malloc_helper(size_t num_bytes, const mp_obj_type_t *type); +mp_obj_t mp_obj_new_port_tuple(size_t n, const mp_obj_t *items); + +// Safely free an object that may have been allocated from either the GC heap or port heap. +// If the pointer is on the GC heap, it will be freed by the GC automatically. +// If the pointer is not on the GC heap, it will be freed with port_free. +void circuitpy_free_obj(mp_obj_t obj); diff --git a/supervisor/port_heap.h b/supervisor/port_heap.h index f035cc2409e..376322ada4d 100644 --- a/supervisor/port_heap.h +++ b/supervisor/port_heap.h @@ -21,9 +21,15 @@ void port_heap_init(void); void *port_malloc(size_t size, bool dma_capable); - +void *port_malloc_zero(size_t size, bool dma_capable); void port_free(void *ptr); -void *port_realloc(void *ptr, size_t size); +void *port_realloc(void *ptr, size_t size, bool dma_capable); + +#if !CIRCUITPY_ALL_MEMORY_DMA_CAPABLE +// Check if the full buffer is in DMA-capable memory and meets cache alignment +// requirements. DMA-capable memory is also accessible during flash operations. +bool port_buffer_is_dma_capable(const void *ptr, size_t len); +#endif size_t port_heap_get_largest_free_size(void); diff --git a/supervisor/shared/async_flag.h b/supervisor/shared/async_flag.h new file mode 100644 index 00000000000..5dd2c726386 --- /dev/null +++ b/supervisor/shared/async_flag.h @@ -0,0 +1,18 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include + +// Flag that marks an operation as done, possibly set from an interrupt. Ports may override these +// before this header is included. +#ifndef CIRCUITPY_ASYNC_FLAG_SET +typedef volatile bool circuitpy_async_flag_t; +#define CIRCUITPY_ASYNC_FLAG_INIT(flag) (*(flag) = false) +#define CIRCUITPY_ASYNC_FLAG_SET(flag) (*(flag) = true) +#define CIRCUITPY_ASYNC_FLAG_IS_SET(flag) (*(flag)) +#endif diff --git a/supervisor/shared/awaitable.c b/supervisor/shared/awaitable.c new file mode 100644 index 00000000000..ed4eb126318 --- /dev/null +++ b/supervisor/shared/awaitable.c @@ -0,0 +1,258 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include + +#include "supervisor/shared/awaitable.h" +#include "py/mperrno.h" +#include "py/runtime.h" +#include "py/stream.h" + +#if MICROPY_PY_ASYNC_AWAIT + +#if MICROPY_PY_ASYNCIO +// Make the running asyncio task wait on the I/O queue until this awaitable polls readable. +// asyncio.core is found through sys.modules, because mp_asyncio_context in modasyncio.c is left +// pointing at the old heap after a soft reload. +static void asyncio_wait(mp_obj_t awaitable) { + mp_map_elem_t *core = mp_map_lookup(&MP_STATE_VM(mp_loaded_modules_dict).map, + MP_OBJ_NEW_QSTR(MP_QSTR_asyncio_dot_core), MP_MAP_LOOKUP); + if (core == NULL) { + return; + } + mp_obj_t cur_task = mp_load_attr(core->value, MP_QSTR_cur_task); + if (cur_task == mp_const_none) { + return; + } + mp_obj_t dest[4]; + mp_load_method(mp_load_attr(core->value, MP_QSTR__io_queue), MP_QSTR__enqueue, dest); + dest[2] = awaitable; + dest[3] = MP_OBJ_NEW_SMALL_INT(0); // wait to read + mp_call_method_n_kw(2, 0, dest); +} +#endif + +// ---- the async function ------------------------------------------------------ + +// Store the arguments; they are parsed by start() when the awaitable is first resumed. +static mp_obj_t async_fun_call(mp_obj_t self_in, size_t n_args, size_t n_kw, const mp_obj_t *args) { + const circuitpy_async_fun_obj_t *fun = MP_OBJ_TO_PTR(self_in); + mp_arg_check_num_sig(n_args, n_kw, fun->sig); + size_t n = n_args + 2 * n_kw; + circuitpy_awaitable_obj_t *aw = mp_obj_malloc_var_with_finaliser(circuitpy_awaitable_obj_t, + args, mp_obj_t, n, &circuitpy_awaitable_type); + aw->fun = fun; + aw->context = NULL; + aw->state = CIRCUITPY_AWAITABLE_NEW; + aw->n_args = n_args; + aw->n_kw = n_kw; + aw->next = NULL; + memcpy(aw->args, args, n * sizeof(mp_obj_t)); + return MP_OBJ_FROM_PTR(aw); +} + +MP_DEFINE_CONST_OBJ_TYPE( + circuitpy_async_fun_type, + MP_QSTR_function, + MP_TYPE_FLAG_BINDS_SELF, + call, async_fun_call + ); + +// ---- the awaitable ----------------------------------------------------------- + +// Finishes the awaitable; stops the operation if it has started. A closed awaitable that +// was never awaited does not start later, as with a closed coroutine. +static void awaitable_cancel(circuitpy_awaitable_obj_t *self) { + uint8_t state = self->state; + self->state = CIRCUITPY_AWAITABLE_FINISHED; + if (state == CIRCUITPY_AWAITABLE_RUNNING) { + self->fun->cancel(self->args[0], self->context, &self->done); + } +} + +static mp_obj_t awaitable_iternext(mp_obj_t self_in) { + circuitpy_awaitable_obj_t *self = MP_OBJ_TO_PTR(self_in); + if (self->state == CIRCUITPY_AWAITABLE_FINISHED) { + // Awaited again: like a finished generator, return None at once. + MP_STATE_THREAD(stop_iteration_arg) = mp_const_none; + return MP_OBJ_STOP_ITERATION; + } + if (self->state == CIRCUITPY_AWAITABLE_NEW) { + mp_map_t kw_args; + mp_map_init_fixed_table(&kw_args, self->n_kw, self->args + self->n_args); + CIRCUITPY_ASYNC_FLAG_INIT(&self->done); + // An exception from start() (bad arguments) propagates out of the await. + self->context = self->fun->start(&self->done, self->n_args, self->args, &kw_args); + self->state = CIRCUITPY_AWAITABLE_RUNNING; + } + if (!CIRCUITPY_ASYNC_FLAG_IS_SET(&self->done)) { + #if MICROPY_PY_ASYNCIO + asyncio_wait(self_in); + #endif + return mp_const_none; + } + self->state = CIRCUITPY_AWAITABLE_FINISHED; + MP_STATE_THREAD(stop_iteration_arg) = self->fun->end(self->args[0], self->context, &self->done); + return MP_OBJ_STOP_ITERATION; +} + +// A value sent in is ignored, as by CPython's awaitables written in C. +static mp_obj_t awaitable_send(mp_obj_t self_in, mp_obj_t value) { + mp_obj_t ret = awaitable_iternext(self_in); + if (ret == MP_OBJ_STOP_ITERATION) { + mp_raise_StopIteration(MP_STATE_THREAD(stop_iteration_arg)); + } + return ret; +} +static MP_DEFINE_CONST_FUN_OBJ_2(awaitable_send_obj, awaitable_send); + +// throw() is how asyncio cancels a task: stop the operation and raise the exception. +static mp_obj_t awaitable_throw(mp_obj_t self_in, mp_obj_t exc) { + awaitable_cancel(MP_OBJ_TO_PTR(self_in)); + nlr_raise(mp_make_raise_obj(exc)); +} +static MP_DEFINE_CONST_FUN_OBJ_2(awaitable_throw_obj, awaitable_throw); + +static mp_obj_t awaitable_close(mp_obj_t self_in) { + awaitable_cancel(MP_OBJ_TO_PTR(self_in)); + return mp_const_none; +} +static MP_DEFINE_CONST_FUN_OBJ_1(awaitable_close_obj, awaitable_close); + +// Readable once the operation has finished. +static mp_uint_t awaitable_ioctl(mp_obj_t self_in, mp_uint_t request, uintptr_t arg, int *errcode) { + circuitpy_awaitable_obj_t *self = MP_OBJ_TO_PTR(self_in); + if (request != MP_STREAM_POLL) { + *errcode = MP_EINVAL; + return MP_STREAM_ERROR; + } + return CIRCUITPY_ASYNC_FLAG_IS_SET(&self->done) ? (arg & MP_STREAM_POLL_RD) : 0; +} + +static const mp_stream_p_t awaitable_stream_p = { + .ioctl = awaitable_ioctl, +}; + +static const mp_rom_map_elem_t awaitable_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR___await__), MP_ROM_PTR(&mp_identity_obj) }, + { MP_ROM_QSTR(MP_QSTR_send), MP_ROM_PTR(&awaitable_send_obj) }, + { MP_ROM_QSTR(MP_QSTR_throw), MP_ROM_PTR(&awaitable_throw_obj) }, + { MP_ROM_QSTR(MP_QSTR_close), MP_ROM_PTR(&awaitable_close_obj) }, + // Runs during GC: an operation still in flight must not write into freed memory. + { MP_ROM_QSTR(MP_QSTR___del__), MP_ROM_PTR(&awaitable_close_obj) }, +}; +static MP_DEFINE_CONST_DICT(awaitable_locals_dict, awaitable_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + circuitpy_awaitable_type, + MP_QSTR_coroutine, + MP_TYPE_FLAG_ITER_IS_ITERNEXT, + iter, awaitable_iternext, + protocol, &awaitable_stream_p, + locals_dict, &awaitable_locals_dict + ); + +// ---- the lock ---------------------------------------------------------------- + +void circuitpy_async_lock_init(circuitpy_async_lock_obj_t *lock) { + lock->base.type = &circuitpy_async_lock_type; + lock->held = false; + lock->waiting = NULL; +} + +bool circuitpy_async_lock_try(circuitpy_async_lock_obj_t *lock) { + if (lock->held) { + return false; + } + lock->held = true; + return true; +} + +void circuitpy_async_lock_release(circuitpy_async_lock_obj_t *lock) { + circuitpy_awaitable_obj_t *next = lock->waiting; + if (next == NULL) { + lock->held = false; + return; + } + // The lock stays held; it is the next one's now. + lock->waiting = next->next; + CIRCUITPY_ASYNC_FLAG_SET(&next->done); +} + +// Each one woken gets the lock in turn and passes it on from its __aexit__; what it does with the +// deinited object raises. +void circuitpy_async_lock_deinit(circuitpy_async_lock_obj_t *lock) { + while (lock->waiting != NULL) { + circuitpy_async_lock_release(lock); + } +} + +// __aenter__: take the lock, or join the end of the line. done is set when it is ours. +static void *lock_enter_start(circuitpy_async_flag_t *done, size_t n_args, const mp_obj_t *pos_args, mp_map_t *kw_args) { + circuitpy_async_lock_obj_t *lock = MP_OBJ_TO_PTR(pos_args[0]); + if (circuitpy_async_lock_try(lock)) { + CIRCUITPY_ASYNC_FLAG_SET(done); + return NULL; + } + circuitpy_awaitable_obj_t *aw = CIRCUITPY_AWAITABLE_OF(done); + circuitpy_awaitable_obj_t **p = &lock->waiting; + while (*p != NULL) { + p = &(*p)->next; + } + *p = aw; + return NULL; +} + +static mp_obj_t lock_enter_end(mp_obj_t self_in, void *context, circuitpy_async_flag_t *done) { + return self_in; +} + +// Cancelled while waiting: leave the line. Cancelled after the lock was handed over but before +// the task ran: pass it on. +static void lock_enter_cancel(mp_obj_t self_in, void *context, circuitpy_async_flag_t *done) { + circuitpy_async_lock_obj_t *lock = MP_OBJ_TO_PTR(self_in); + if (CIRCUITPY_ASYNC_FLAG_IS_SET(done)) { + circuitpy_async_lock_release(lock); + return; + } + circuitpy_awaitable_obj_t *aw = CIRCUITPY_AWAITABLE_OF(done); + for (circuitpy_awaitable_obj_t **p = &lock->waiting; *p != NULL; p = &(*p)->next) { + if (*p == aw) { + *p = aw->next; + return; + } + } +} +static CIRCUITPY_DEFINE_ASYNC_FUN_OBJ_KW(lock_enter_obj, 1, lock_enter_start, lock_enter_end, lock_enter_cancel); + +// __aexit__ returns the lock itself: awaiting it finishes at once with None, so an exception +// in the block is not swallowed. +static mp_obj_t lock_exit(size_t n_args, const mp_obj_t *args) { + circuitpy_async_lock_release(MP_OBJ_TO_PTR(args[0])); + return args[0]; +} +static MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(lock_exit_obj, 4, 4, lock_exit); + +static mp_obj_t lock_iternext(mp_obj_t self_in) { + MP_STATE_THREAD(stop_iteration_arg) = mp_const_none; + return MP_OBJ_STOP_ITERATION; +} + +static const mp_rom_map_elem_t lock_locals_dict_table[] = { + { MP_ROM_QSTR(MP_QSTR___aenter__), MP_ROM_PTR(&lock_enter_obj) }, + { MP_ROM_QSTR(MP_QSTR___aexit__), MP_ROM_PTR(&lock_exit_obj) }, +}; +static MP_DEFINE_CONST_DICT(lock_locals_dict, lock_locals_dict_table); + +MP_DEFINE_CONST_OBJ_TYPE( + circuitpy_async_lock_type, + MP_QSTR_Lock, + MP_TYPE_FLAG_ITER_IS_ITERNEXT, + iter, lock_iternext, + locals_dict, &lock_locals_dict + ); + +#endif // MICROPY_PY_ASYNC_AWAIT diff --git a/supervisor/shared/awaitable.h b/supervisor/shared/awaitable.h new file mode 100644 index 00000000000..a02ce72e25f --- /dev/null +++ b/supervisor/shared/awaitable.h @@ -0,0 +1,106 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +// Awaitable functions implemented in C. +// +// CIRCUITPY_DEFINE_ASYNC_FUN_OBJ_KW(obj_name, n_args_min, start, end, cancel) defines obj_name, +// a callable that takes the same arguments as an MP_DEFINE_CONST_FUN_OBJ_KW function but returns +// an awaitable. A call only checks the number of positional arguments; as with a coroutine in +// CPython, nothing runs and the arguments are parsed only when the awaitable is awaited. Then: +// +// void *start(circuitpy_async_flag_t *done, size_t n_args, const mp_obj_t *pos_args, +// mp_map_t *kw_args) +// parses the arguments, starts the operation and returns a context: state of this one +// operation, or NULL when the object holds it all. The operation sets *done, possibly +// from an interrupt, once it has finished. +// mp_obj_t end(mp_obj_t self_in, void *context, circuitpy_async_flag_t *done) +// finishes the operation once *done is set and returns the result of the await. +// void cancel(mp_obj_t self_in, void *context, circuitpy_async_flag_t *done) +// stops the operation, or finishes it if *done is already set. It must not allocate: it +// may run during GC. +// +// self_in is the first positional argument, the object for a method. done tells which operation +// is meant, if the object has started another one since. +// +// While an operation runs, the awaiting asyncio task waits on asyncio's I/O queue: the awaitable +// is a stream that polls readable once *done is set. + +#pragma once + +#include + +#include "py/obj.h" +#include "supervisor/shared/async_flag.h" + +#if MICROPY_PY_ASYNC_AWAIT + +typedef void *(*circuitpy_awaitable_start_fn)(circuitpy_async_flag_t *done, size_t n_args, + const mp_obj_t *pos_args, mp_map_t *kw_args); +typedef mp_obj_t (*circuitpy_awaitable_end_fn)(mp_obj_t self_in, void *context, + circuitpy_async_flag_t *done); +typedef void (*circuitpy_awaitable_cancel_fn)(mp_obj_t self_in, void *context, + circuitpy_async_flag_t *done); + +// An async function: calling it returns a circuitpy_awaitable_obj_t. +typedef struct { + mp_obj_base_t base; + uint32_t sig; // as made by MP_OBJ_FUN_MAKE_SIG + circuitpy_awaitable_start_fn start; + circuitpy_awaitable_end_fn end; + circuitpy_awaitable_cancel_fn cancel; +} circuitpy_async_fun_obj_t; + +extern const mp_obj_type_t circuitpy_async_fun_type; + +typedef struct _circuitpy_awaitable_obj_t { + mp_obj_base_t base; + const circuitpy_async_fun_obj_t *fun; + void *context; // returned by start() + circuitpy_async_flag_t done; + uint8_t state; // CIRCUITPY_AWAITABLE_NEW, _RUNNING or _FINISHED + uint16_t n_args; + uint16_t n_kw; + struct _circuitpy_awaitable_obj_t *next; // the next one waiting for the same lock + mp_obj_t args[]; // positional arguments, then keyword name/value pairs +} circuitpy_awaitable_obj_t; + +extern const mp_obj_type_t circuitpy_awaitable_type; + +// The awaitable that owns a done flag passed to start(), end() or cancel(). +#define CIRCUITPY_AWAITABLE_OF(done_ptr) \ + ((circuitpy_awaitable_obj_t *)((char *)(done_ptr) - offsetof(circuitpy_awaitable_obj_t, done))) + +// A lock for asyncio code: `async with lock:`. __aenter__ is an awaitable that takes the lock +// or waits in line for it; __aexit__ hands the lock to the next in line. Embed it in the +// object it guards; it allocates nothing. +typedef struct { + mp_obj_base_t base; + bool held; + circuitpy_awaitable_obj_t *waiting; // first in line, linked through next +} circuitpy_async_lock_obj_t; + +extern const mp_obj_type_t circuitpy_async_lock_type; + +void circuitpy_async_lock_init(circuitpy_async_lock_obj_t *lock); +static inline bool circuitpy_async_lock_held(circuitpy_async_lock_obj_t *lock) { + return lock->held; +} +// For C code: takes the lock if it is free. +bool circuitpy_async_lock_try(circuitpy_async_lock_obj_t *lock); +// Hands the lock to the next in line, or frees it. +void circuitpy_async_lock_release(circuitpy_async_lock_obj_t *lock); +// Wakes everyone in line, for the deinit of the object the lock guards. +void circuitpy_async_lock_deinit(circuitpy_async_lock_obj_t *lock); + +enum { CIRCUITPY_AWAITABLE_NEW, CIRCUITPY_AWAITABLE_RUNNING, CIRCUITPY_AWAITABLE_FINISHED }; + +#define CIRCUITPY_DEFINE_ASYNC_FUN_OBJ_KW(obj_name, n_args_min, start, end, cancel) \ + const circuitpy_async_fun_obj_t obj_name = { \ + {&circuitpy_async_fun_type}, MP_OBJ_FUN_MAKE_SIG(n_args_min, MP_OBJ_FUN_ARGS_MAX, true), \ + start, end, cancel \ + } + +#endif // MICROPY_PY_ASYNC_AWAIT diff --git a/supervisor/shared/background_callback.c b/supervisor/shared/background_callback.c index 309210b7a12..430be3d8a31 100644 --- a/supervisor/shared/background_callback.c +++ b/supervisor/shared/background_callback.c @@ -16,6 +16,11 @@ static volatile background_callback_t *volatile callback_head, *volatile callback_tail; +// True from background_callback_reset() until background_callback_heap_ready(), while +// the VM's heap is torn down. While it is set, background_callback_add_core() drops any +// callback that is on the heap or whose data is on the heap. +static bool reject_heap_callbacks; + #ifndef CALLBACK_CRITICAL_BEGIN #define CALLBACK_CRITICAL_BEGIN (common_hal_mcu_disable_interrupts()) #endif @@ -32,6 +37,14 @@ void PLACE_IN_ITCM(background_callback_add_core)(background_callback_t * cb) { CALLBACK_CRITICAL_END; return; } + // During heap teardown, hardware owned by a heap object (such as an I2SOut) keeps + // interrupting until the object's finaliser stops it. A callback queued during teardown + // would still be pending after the heap is freed. Drop any callback that is on the heap + // or whose data is on the heap. + if (reject_heap_callbacks && (gc_ptr_on_heap(cb) || gc_ptr_on_heap(cb->data))) { + CALLBACK_CRITICAL_END; + return; + } cb->next = 0; cb->prev = (background_callback_t *)callback_tail; if (callback_tail) { @@ -58,7 +71,7 @@ inline bool background_callback_pending(void) { static int background_prevention_count; -void PLACE_IN_ITCM(background_callback_run_all)() { +void PLACE_IN_ITCM(background_callback_run_all)(void) { port_background_task(); if (!background_callback_pending()) { return; @@ -69,11 +82,19 @@ void PLACE_IN_ITCM(background_callback_run_all)() { return; } ++background_prevention_count; - background_callback_t *cb = (background_callback_t *)callback_head; - callback_head = NULL; - callback_tail = NULL; - while (cb) { - background_callback_t *next = cb->next; + // Run the callbacks queued now, taking each one off the live queue just before it + // runs. A callback that allows background tasks (like a display auto-refresh) can + // then run the rest in a nested call. Stop at the current tail so callbacks added + // while running wait for the next call. + background_callback_t *last = (background_callback_t *)callback_tail; + while (callback_head) { + background_callback_t *cb = (background_callback_t *)callback_head; + callback_head = cb->next; + if (callback_head) { + callback_head->prev = NULL; + } else { + callback_tail = NULL; + } cb->next = cb->prev = NULL; background_callback_fun fun = cb->fun; void *data = cb->data; @@ -83,19 +104,21 @@ void PLACE_IN_ITCM(background_callback_run_all)() { fun(data); } CALLBACK_CRITICAL_BEGIN; - cb = next; + if (cb == last) { + break; + } } --background_prevention_count; CALLBACK_CRITICAL_END; } -void background_callback_prevent() { +void background_callback_prevent(void) { CALLBACK_CRITICAL_BEGIN; ++background_prevention_count; CALLBACK_CRITICAL_END; } -void background_callback_allow() { +void background_callback_allow(void) { CALLBACK_CRITICAL_BEGIN; --background_prevention_count; CALLBACK_CRITICAL_END; @@ -103,7 +126,7 @@ void background_callback_allow() { // Filter out queued callbacks if they are allocated on the heap. -void background_callback_reset() { +void background_callback_reset(void) { background_callback_t *new_head = NULL; background_callback_t **previous_next = &new_head; background_callback_t *new_tail = NULL; @@ -132,6 +155,13 @@ void background_callback_reset() { callback_head = new_head; callback_tail = new_tail; background_prevention_count = 0; + reject_heap_callbacks = true; + CALLBACK_CRITICAL_END; +} + +void background_callback_heap_ready(void) { + CALLBACK_CRITICAL_BEGIN; + reject_heap_callbacks = false; CALLBACK_CRITICAL_END; } diff --git a/supervisor/shared/bluetooth/bluetooth.c b/supervisor/shared/bluetooth/bluetooth.c index 15e472148f6..3809f78c32f 100644 --- a/supervisor/shared/bluetooth/bluetooth.c +++ b/supervisor/shared/bluetooth/bluetooth.c @@ -10,16 +10,13 @@ #include "shared-bindings/_bleio/__init__.h" #include "shared-bindings/_bleio/Adapter.h" -#if defined(CIRCUITPY_BOOT_BUTTON) -#include "shared-bindings/digitalio/DigitalInOut.h" -#include "shared-bindings/time/__init__.h" -#endif #include "shared-bindings/microcontroller/Processor.h" #include "shared-bindings/microcontroller/ResetReason.h" #include "shared-module/storage/__init__.h" #include "common-hal/_bleio/__init__.h" +#include "supervisor/port.h" #include "supervisor/shared/serial.h" #include "supervisor/shared/status_leds.h" #include "supervisor/shared/tick.h" @@ -31,44 +28,55 @@ #include "supervisor/shared/bluetooth/file_transfer.h" #endif -#if CIRCUITPY_SERIAL_BLE +#if CIRCUITPY_BLE_SERIAL_SERVICE #include "supervisor/shared/bluetooth/serial.h" #endif +// BLE workflow exists if either or both of these are turned on. +#define BLE_WORKFLOW (CIRCUITPY_BLE_FILE_SERVICE || CIRCUITPY_BLE_SERIAL_SERVICE) + +#if BLE_WORKFLOW +#include "shared-bindings/_bleio/Characteristic.h" +#include "shared-bindings/_bleio/Service.h" +#include "shared-bindings/_bleio/UUID.h" +#endif + #if CIRCUITPY_STATUS_BAR #include "supervisor/shared/status_bar.h" #endif -#if CIRCUITPY_WEB_WORKFLOW && CIRCUITPY_WIFI && CIRCUITPY_OS_GETENV -#include "shared-module/os/__init__.h" +#if (BLE_WORKFLOW || (CIRCUITPY_WEB_WORKFLOW && CIRCUITPY_WIFI)) && CIRCUITPY_SETTINGS_TOML +#include "supervisor/shared/settings.h" #endif // This standard advertisement advertises the CircuitPython editing service and a CIRCUITPY short name. -const uint8_t public_advertising_data[] = { 0x02, 0x01, 0x06, // 0-2 Flags - 0x02, 0x0a, 0xec, // 3-5 TX power level -20 - #if CIRCUITPY_BLE_FILE_SERVICE - 0x03, 0x02, 0xbb, 0xfe, // 6 - 9 Incomplete service list (File Transfer service) - #endif - 0x0e, 0xff, 0x22, 0x08, // 10 - 13 Adafruit Manufacturer Data - 0x0a, 0x04, 0x00, // 14 - 16 Creator ID / Creation ID - CIRCUITPY_CREATOR_ID & 0xff, // 17 - 20 Creator ID - (CIRCUITPY_CREATOR_ID >> 8) & 0xff, - (CIRCUITPY_CREATOR_ID >> 16) & 0xff, - (CIRCUITPY_CREATOR_ID >> 24) & 0xff, - CIRCUITPY_CREATION_ID & 0xff, // 21 - 24 Creation ID - (CIRCUITPY_CREATION_ID >> 8) & 0xff, - (CIRCUITPY_CREATION_ID >> 16) & 0xff, - (CIRCUITPY_CREATION_ID >> 24) & 0xff, - 0x05, 0x08, 0x43, 0x49, 0x52, 0x43 // 25 - 31 - Short name +const uint8_t public_advertising_data[] = { + 0x02, 0x01, 0x06, // 0-2 Flags + 0x02, 0x0a, 0xec, // 3-5 TX power level -20 + #if CIRCUITPY_BLE_FILE_SERVICE + 0x03, 0x02, 0xbb, 0xfe, // 6 - 9 Incomplete service list (File Transfer service) + #endif + 0x0e, 0xff, 0x22, 0x08, // 10 - 13 Adafruit Manufacturer Data + 0x0a, 0x04, 0x00, // 14 - 16 Creator ID / Creation ID + CIRCUITPY_CREATOR_ID & 0xff, // 17 - 20 Creator ID + (CIRCUITPY_CREATOR_ID >> 8) & 0xff, + (CIRCUITPY_CREATOR_ID >> 16) & 0xff, + (CIRCUITPY_CREATOR_ID >> 24) & 0xff, + CIRCUITPY_CREATION_ID & 0xff, // 21 - 24 Creation ID + (CIRCUITPY_CREATION_ID >> 8) & 0xff, + (CIRCUITPY_CREATION_ID >> 16) & 0xff, + (CIRCUITPY_CREATION_ID >> 24) & 0xff, + 0x05, 0x08, 0x43, 0x49, 0x52, 0x43 // 25 - 31 - Short name }; -const uint8_t private_advertising_data[] = { 0x02, 0x01, 0x06, // 0-2 Flags - 0x02, 0x0a, 0x00 // 3-5 TX power level 0 +const uint8_t private_advertising_data[] = { + 0x02, 0x01, 0x06, // 0-2 Flags + 0x02, 0x0a, 0x00 // 3-5 TX power level 0 }; // This scan response advertises the full device name (if it fits.) uint8_t circuitpython_scan_response_data[31]; -#if CIRCUITPY_BLE_FILE_SERVICE || CIRCUITPY_SERIAL_BLE +#if BLE_WORKFLOW static bool boot_in_discovery_mode = false; static bool advertising = false; static bool _private_advertising = false; @@ -78,6 +86,11 @@ static bool ble_started = false; #define WORKFLOW_ENABLED 1 #define WORKFLOW_DISABLED 2 +// Value of CIRCUITPY_BLE_WORKFLOW in settings.toml. Defaults to true. +static bool ble_workflow_setting = true; + +// Has BLE workflow been enabled, because it was allow and we've bonded to the workflow host? +// Also controlled by supervisor.runtime.ble_workflow. static uint8_t workflow_state = WORKFLOW_UNSET; static bool was_connected = false; @@ -176,13 +189,23 @@ static void supervisor_bluetooth_start_advertising(void) { advertising = status == 0; } -#endif // CIRCUITPY_BLE_FILE_SERVICE || CIRCUITPY_SERIAL_BLE +#endif // BLE_WORKFLOW #define BLE_DISCOVERY_DATA_GUARD 0xbb0000bb #define BLE_DISCOVERY_DATA_GUARD_MASK 0xff0000ff void supervisor_bluetooth_init(void) { - #if CIRCUITPY_BLE_FILE_SERVICE || CIRCUITPY_SERIAL_BLE + #if BLE_WORKFLOW + + #if CIRCUITPY_SETTINGS_TOML + // Check if the user disabled BLE workflow in settings.toml. The default is that it's enabled. + ble_workflow_setting = true; + settings_get_bool("CIRCUITPY_BLE_WORKFLOW", &ble_workflow_setting); + if (!ble_workflow_setting) { + return; + } + #endif // CIRCUITPY_SETTINGS_TOML + uint32_t reset_state = port_get_saved_word(); uint32_t ble_mode = 0; if ((reset_state & BLE_DISCOVERY_DATA_GUARD_MASK) == BLE_DISCOVERY_DATA_GUARD) { @@ -190,14 +213,17 @@ void supervisor_bluetooth_init(void) { } const mcu_reset_reason_t reset_reason = common_hal_mcu_processor_get_reset_reason(); boot_in_discovery_mode = false; - if (reset_reason != RESET_REASON_POWER_ON && - reset_reason != RESET_REASON_RESET_PIN && - reset_reason != RESET_REASON_UNKNOWN && - reset_reason != RESET_REASON_SOFTWARE) { + + // These are error resets reflecting a problem and should not initiate discovery mode. + if (reset_reason == MCU_RESET_REASON_BROWNOUT || + reset_reason == MCU_RESET_REASON_WATCHDOG || + reset_reason == MCU_RESET_REASON_RESCUE_DEBUG) { return; } + // Same as what is done by `import _bleio`. common_hal_bleio_init(); + if (ble_mode == 0) { port_set_saved_word(BLE_DISCOVERY_DATA_GUARD | (0x01 << 8)); } @@ -206,55 +232,66 @@ void supervisor_bluetooth_init(void) { #if CIRCUITPY_STATUS_LED status_led_init(); #endif - uint64_t start_ticks = supervisor_ticks_ms64(); - uint64_t diff = 0; if (ble_mode != 0) { boot_in_discovery_mode = true; reset_state = 0x0; } bool bonded = common_hal_bleio_adapter_is_bonded_to_central(&common_hal_bleio_adapter_obj); - #if !CIRCUITPY_USB_DEVICE - // Boot into discovery if USB isn't available and we aren't bonded already. - // Checking here allows us to have the status LED solidly on even if no button was - // pressed. - bool wifi_workflow_active = false; - #if CIRCUITPY_WEB_WORKFLOW && CIRCUITPY_WIFI && CIRCUITPY_OS_GETENV - char _api_password[64]; - const size_t api_password_len = sizeof(_api_password) - 1; - os_getenv_err_t result = common_hal_os_getenv_str("CIRCUITPY_WEB_API_PASSWORD", _api_password + 1, api_password_len); - wifi_workflow_active = result == GETENV_OK; - #endif - if (!bonded && !wifi_workflow_active) { - boot_in_discovery_mode = true; - } - #endif - while (diff < 1000) { - #if CIRCUITPY_STATUS_LED - // Blink on for 50 and off for 100 - bool led_on = boot_in_discovery_mode || (diff % 150) <= 50; - if (led_on) { - new_status_color(0x0000ff); - } else { - new_status_color(BLACK); - } + uint64_t start_ticks = supervisor_ticks_ms64(); + uint64_t diff = 0; + + // Don't go into discovery mode when waking from deep sleep. But if we're already bonded, + // BLE workflow can continue after deep sleep. + if (reset_reason != MCU_RESET_REASON_DEEP_SLEEP_ALARM) { + #if !CIRCUITPY_USB_DEVICE + // Boot into discovery if USB isn't available and we aren't bonded already. + // Checking here allows us to have the status LED solidly on even if no button was + // pressed. + + bool wifi_workflow_active = false; + #if CIRCUITPY_WEB_WORKFLOW && CIRCUITPY_WIFI && CIRCUITPY_SETTINGS_TOML + char _api_password[64]; + const size_t api_password_len = sizeof(_api_password) - 1; + settings_err_t result = settings_get_str("CIRCUITPY_WEB_API_PASSWORD", _api_password + 1, api_password_len); + wifi_workflow_active = result == SETTINGS_OK; #endif - // Init the boot button every time in case it is used for LEDs. - #ifdef CIRCUITPY_BOOT_BUTTON - digitalio_digitalinout_obj_t boot_button; - common_hal_digitalio_digitalinout_construct(&boot_button, CIRCUITPY_BOOT_BUTTON); - common_hal_digitalio_digitalinout_switch_to_input(&boot_button, PULL_UP); - common_hal_time_delay_ms(1); - bool button_pressed = !common_hal_digitalio_digitalinout_get_value(&boot_button); - common_hal_digitalio_digitalinout_deinit(&boot_button); - if (button_pressed) { + + if (!bonded && !wifi_workflow_active) { boot_in_discovery_mode = true; } - #endif - diff = supervisor_ticks_ms64() - start_ticks; - } - if (boot_in_discovery_mode) { - common_hal_bleio_adapter_erase_bonding(&common_hal_bleio_adapter_obj); + #endif // !CIRCUITPY_USB_DEVICE + + // A press must begin inside this interval. The safe mode interval just before + // this one also uses the boot button, and a press meant for safe mode can + // still be held down when this interval starts; entering discovery mode from + // it would erase bonding unasked. Require a release first. + bool button_released = !port_boot_button_pressed(); + while (diff < 1000) { + #if CIRCUITPY_STATUS_LED + // Blink on for 50 and off for 100 + bool led_on = boot_in_discovery_mode || (diff % 150) <= 50; + if (led_on) { + new_status_color(0x0000ff); + } else { + new_status_color(BLACK); + } + #endif + if (!port_boot_button_pressed()) { + button_released = true; + } else if (button_released && !boot_in_discovery_mode) { + boot_in_discovery_mode = true; + // Restart the interval so the LED shows solid blue for the full + // 1000 ms, as feedback that the press was accepted and bonding + // will be erased. + start_ticks = supervisor_ticks_ms64(); + } + diff = supervisor_ticks_ms64() - start_ticks; + } + if (boot_in_discovery_mode) { + common_hal_bleio_adapter_erase_bonding(&common_hal_bleio_adapter_obj); + } } + if (boot_in_discovery_mode || bonded) { workflow_state = WORKFLOW_ENABLED; } else { @@ -269,7 +306,7 @@ void supervisor_bluetooth_init(void) { } void supervisor_bluetooth_background(void) { - #if CIRCUITPY_BLE_FILE_SERVICE || CIRCUITPY_SERIAL_BLE + #if BLE_WORKFLOW if (!ble_started) { return; } @@ -300,10 +337,28 @@ void supervisor_bluetooth_background(void) { #endif } +#if BLE_WORKFLOW +// adafXXXX-4369-7263-7569-74507974686e, stored little-endian. The XXXX bytes are +// filled in by common_hal_bleio_uuid_construct(). +const uint8_t circuitpython_base_uuid[16] = {0x6e, 0x68, 0x74, 0x79, 0x50, 0x74, 0x69, 0x75, 0x63, 0x72, 0x69, 0x43, 0x00, 0x00, 0xaf, 0xad }; + +static bleio_service_obj_t guard_service; +static bleio_uuid_obj_t guard_service_uuid; +static bleio_characteristic_obj_t guard_characteristic; +static bleio_uuid_obj_t guard_characteristic_uuid; +static mp_obj_list_t guard_characteristic_list; +static mp_obj_t guard_characteristic_list_items[1]; +#endif + void supervisor_start_bluetooth(void) { - #if CIRCUITPY_BLE_FILE_SERVICE || CIRCUITPY_SERIAL_BLE + #if BLE_WORKFLOW - if (workflow_state != WORKFLOW_ENABLED || ble_started) { + if (ble_started) { + // Called on a VM reset too: run a file command that waited for the VM to stop. + supervisor_bluetooth_background(); + return; + } + if (workflow_state != WORKFLOW_ENABLED) { return; } @@ -313,10 +368,49 @@ void supervisor_start_bluetooth(void) { supervisor_start_bluetooth_file_transfer(); #endif - #if CIRCUITPY_SERIAL_BLE + #if CIRCUITPY_BLE_SERIAL_SERVICE supervisor_start_bluetooth_serial(); #endif + // Create an unused service that will be in the GATT table immediately after + // the BLE workflow services. This protects the workflow services from being + // invalidated if user code creates services. + // + // A peripheral reports its last primary service with End Group Handle 0xffff, + // and hosts cache that literally. So a service that user code adds later lands + // inside the cached range of whichever service was last, and hosts treat the + // addition as a change to that service: Chrome invalidates the page's object + // for it (and has no event to report that to JavaScript), and BlueZ drops it + // from its cache entirely. This guard is created last so that it, + // not a workflow service, is the one affected, and file transfer and serial + // keep working. Costs three attribute handles. + guard_service_uuid.base.type = &bleio_uuid_type; + common_hal_bleio_uuid_construct(&guard_service_uuid, 0x0004, circuitpython_base_uuid); + guard_characteristic_list.base.type = &mp_type_list; + guard_characteristic_list.alloc = 1; + guard_characteristic_list.len = 0; + guard_characteristic_list.items = guard_characteristic_list_items; + guard_characteristic_list_items[0] = MP_OBJ_NULL; + guard_service.base.type = &bleio_service_type; + _common_hal_bleio_service_construct(&guard_service, &guard_service_uuid, false /* is secondary */, &guard_characteristic_list); + + // One read-only characteristic: we need at least one because on espressif + // a service is not registered with NimBLE until its first characteristic is added. + guard_characteristic_uuid.base.type = &bleio_uuid_type; + common_hal_bleio_uuid_construct(&guard_characteristic_uuid, 0x0005, circuitpython_base_uuid); + guard_characteristic.base.type = &bleio_characteristic_type; + common_hal_bleio_characteristic_construct(&guard_characteristic, + &guard_service, + 0, // handle (for remote only) + &guard_characteristic_uuid, + CHAR_PROP_READ, + SECURITY_MODE_ENC_NO_MITM, + SECURITY_MODE_NO_ACCESS, + 1, // max length + true, // fixed length + NULL, // no initial value + NULL); + // Mark as started so that the background call does something. ble_started = true; @@ -331,7 +425,7 @@ void supervisor_start_bluetooth(void) { } void supervisor_stop_bluetooth(void) { - #if CIRCUITPY_BLE_FILE_SERVICE || CIRCUITPY_SERIAL_BLE + #if BLE_WORKFLOW if (!ble_started && workflow_state != WORKFLOW_ENABLED) { return; @@ -343,16 +437,20 @@ void supervisor_stop_bluetooth(void) { supervisor_stop_bluetooth_file_transfer(); #endif - #if CIRCUITPY_SERIAL_BLE + #if CIRCUITPY_BLE_SERIAL_SERVICE supervisor_stop_bluetooth_serial(); #endif + // Tear down the guard service too. + common_hal_bleio_characteristic_deinit(&guard_characteristic); + common_hal_bleio_service_deinit(&guard_service); + #endif } void supervisor_bluetooth_enable_workflow(void) { - #if CIRCUITPY_BLE_FILE_SERVICE || CIRCUITPY_SERIAL_BLE - if (workflow_state == WORKFLOW_DISABLED) { + #if BLE_WORKFLOW + if (!ble_workflow_setting || workflow_state == WORKFLOW_DISABLED) { return; } workflow_state = WORKFLOW_ENABLED; @@ -360,13 +458,13 @@ void supervisor_bluetooth_enable_workflow(void) { } void supervisor_bluetooth_disable_workflow(void) { - #if CIRCUITPY_BLE_FILE_SERVICE || CIRCUITPY_SERIAL_BLE + #if BLE_WORKFLOW workflow_state = WORKFLOW_DISABLED; #endif } bool supervisor_bluetooth_workflow_is_enabled(void) { - #if CIRCUITPY_BLE_FILE_SERVICE || CIRCUITPY_SERIAL_BLE + #if BLE_WORKFLOW if (workflow_state == WORKFLOW_ENABLED) { return true; } diff --git a/supervisor/shared/bluetooth/bluetooth.h b/supervisor/shared/bluetooth/bluetooth.h index 14e74a07c73..0050d702e02 100644 --- a/supervisor/shared/bluetooth/bluetooth.h +++ b/supervisor/shared/bluetooth/bluetooth.h @@ -7,6 +7,9 @@ #pragma once #include +#include + +extern const uint8_t circuitpython_base_uuid[16]; void supervisor_bluetooth_background(void); void supervisor_bluetooth_init(void); diff --git a/supervisor/shared/bluetooth/file_transfer.c b/supervisor/shared/bluetooth/file_transfer.c index 66eccf8cbf2..7947933dae8 100644 --- a/supervisor/shared/bluetooth/file_transfer.c +++ b/supervisor/shared/bluetooth/file_transfer.c @@ -14,7 +14,6 @@ #include "shared-bindings/_bleio/Service.h" #include "shared-bindings/_bleio/UUID.h" -#include "supervisor/fatfs.h" #include "supervisor/filesystem.h" #include "supervisor/shared/reload.h" #include "supervisor/shared/bluetooth/file_transfer.h" @@ -38,6 +37,10 @@ static mp_obj_t characteristic_list_items[2]; // uint32_t so its aligned static uint32_t _buffer[PACKET_BUFFER_SIZE / 4 + 1]; static uint32_t _outgoing1[BLEIO_PACKET_BUFFER_MAX_PACKET_SIZE / 4]; +// TODO: _outgoing2 is unused on espressif, whose NimBLE send calls copy the data +// rather than retaining the buffer as the nordic SoftDevice does. Letting a port +// declare how many outgoing buffers it needs would drop this static allocation +// there; nordic requires both. static uint32_t _outgoing2[BLEIO_PACKET_BUFFER_MAX_PACKET_SIZE / 4]; static ble_event_handler_t static_handler_entry; static bleio_packet_buffer_obj_t _transfer_packet_buffer; @@ -112,24 +115,18 @@ void supervisor_stop_bluetooth_file_transfer(void) { #define ANY_COMMAND 0x00 #define THIS_COMMAND 0x01 +#define HELD_COMMAND 0x02 // the running program uses the file: run this command again once it stops // FATFS has a two second timestamp resolution but the BLE API allows for nanosecond resolution. -// This function truncates the time the time to a resolution storable by FATFS and fills in the -// FATFS encoded version into fattime. -static uint64_t truncate_time(uint64_t input_time, DWORD *fattime) { - timeutils_struct_time_t tm; +// This function truncates the time to a resolution storable by FATFS and returns it. +static uint64_t truncate_time(uint64_t input_time) { uint64_t seconds_since_epoch = timeutils_seconds_since_epoch_from_nanoseconds_since_1970(input_time); - timeutils_seconds_since_epoch_to_struct_time(seconds_since_epoch, &tm); - uint64_t truncated_time = timeutils_nanoseconds_since_epoch_to_nanoseconds_since_1970((seconds_since_epoch / 2) * 2 * 1000000000); - - *fattime = ((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); - return truncated_time; + return timeutils_nanoseconds_since_epoch_to_nanoseconds_since_1970((seconds_since_epoch / 2) * 2 * 1000000000); } // Used by read and write. -static FIL active_file; -static fs_user_mount_t *active_mount; +static supervisor_vfs_file_t active_file; +static supervisor_vfs_t *active_mount; static uint8_t _process_read(const uint8_t *raw_buf, size_t command_len) { struct read_command *command = (struct read_command *)raw_buf; size_t header_size = sizeof(struct read_command); @@ -154,20 +151,18 @@ static uint8_t _process_read(const uint8_t *raw_buf, size_t command_len) { const char *mount_path; active_mount = filesystem_for_path(full_path, &mount_path); - if (active_mount == NULL || !filesystem_native_fatfs(active_mount)) { + if (active_mount == NULL || !supervisor_vfs_supported(active_mount)) { response.status = STATUS_ERROR; common_hal_bleio_packet_buffer_write(&_transfer_packet_buffer, (const uint8_t *)&response, response_size, NULL, 0); return ANY_COMMAND; } - FATFS *fs = &active_mount->fatfs; - FRESULT result = f_open(fs, &active_file, mount_path, FA_READ); - if (result != FR_OK) { + if (supervisor_vfs_open_file(active_mount, mount_path, SUPERVISOR_FS_OPEN_READ, 0, &active_file) != SUPERVISOR_FS_OK) { response.status = STATUS_ERROR; common_hal_bleio_packet_buffer_write(&_transfer_packet_buffer, (const uint8_t *)&response, response_size, NULL, 0); return ANY_COMMAND; } - uint32_t total_length = f_size(&active_file); + uint32_t total_length = supervisor_vfs_file_size(&active_file); // Write out the response header. uint32_t offset = command->chunk_offset; uint32_t chunk_size = command->chunk_size; @@ -176,20 +171,20 @@ static uint8_t _process_read(const uint8_t *raw_buf, size_t command_len) { response.total_length = total_length; response.data_size = chunk_size; common_hal_bleio_packet_buffer_write(&_transfer_packet_buffer, (const uint8_t *)&response, response_size, NULL, 0); - f_lseek(&active_file, offset); + supervisor_vfs_seek_file(&active_file, offset); // Write out the chunk contents. We can do this in small pieces because PacketBuffer // will assemble them into larger packets of its own. size_t chunk_end = offset + chunk_size; while (offset < chunk_end) { size_t quantity_read; size_t read_amount = MIN(response_size, chunk_end - offset); - f_read(&active_file, data_buffer, read_amount, &quantity_read); + supervisor_vfs_read_file(&active_file, data_buffer, read_amount, &quantity_read); offset += quantity_read; // TODO: Do something if the read fails common_hal_bleio_packet_buffer_write(&_transfer_packet_buffer, data_buffer, quantity_read, NULL, 0); } if (offset >= total_length) { - f_close(&active_file); + supervisor_vfs_close_file(&active_file); return ANY_COMMAND; } return READ_PACING; @@ -202,14 +197,14 @@ static uint8_t _process_read_pacing(const uint8_t *raw_buf, size_t command_len) response.status = STATUS_OK; size_t response_size = sizeof(struct read_data); - uint32_t total_length = f_size(&active_file); + uint32_t total_length = supervisor_vfs_file_size(&active_file); // Write out the response header. uint32_t chunk_size = MIN(command->chunk_size, total_length - command->chunk_offset); response.chunk_offset = command->chunk_offset; response.total_length = total_length; response.data_size = chunk_size; common_hal_bleio_packet_buffer_write(&_transfer_packet_buffer, (const uint8_t *)&response, response_size, NULL, 0); - f_lseek(&active_file, command->chunk_offset); + supervisor_vfs_seek_file(&active_file, command->chunk_offset); // Write out the chunk contents. We can do this in small pieces because PacketBuffer // will assemble them into larger packets of its own. size_t chunk_offset = 0; @@ -217,8 +212,8 @@ static uint8_t _process_read_pacing(const uint8_t *raw_buf, size_t command_len) while (chunk_offset < chunk_size) { size_t quantity_read; size_t read_size = MIN(chunk_size - chunk_offset, sizeof(data)); - FRESULT result = f_read(&active_file, &data, read_size, &quantity_read); - if (quantity_read == 0 || result != FR_OK) { + supervisor_fs_err_t result = supervisor_vfs_read_file(&active_file, &data, read_size, &quantity_read); + if (quantity_read == 0 || result != SUPERVISOR_FS_OK) { // TODO: If we can't read everything, then the file must have been shortened. Maybe we // should return 0s to pad it out. break; @@ -227,7 +222,7 @@ static uint8_t _process_read_pacing(const uint8_t *raw_buf, size_t command_len) chunk_offset += quantity_read; } if ((chunk_offset + chunk_size) >= total_length) { - f_close(&active_file); + supervisor_vfs_close_file(&active_file); return ANY_COMMAND; } return READ_PACING; @@ -260,7 +255,7 @@ static uint8_t _process_write(const uint8_t *raw_buf, size_t command_len) { const char *mount_path; active_mount = filesystem_for_path(full_path, &mount_path); - if (active_mount == NULL || !filesystem_native_fatfs(active_mount)) { + if (active_mount == NULL || !supervisor_vfs_supported(active_mount)) { response.status = STATUS_ERROR; common_hal_bleio_packet_buffer_write(&_transfer_packet_buffer, (const uint8_t *)&response, sizeof(struct write_pacing), NULL, 0); return ANY_COMMAND; @@ -271,16 +266,17 @@ static uint8_t _process_write(const uint8_t *raw_buf, size_t command_len) { return ANY_COMMAND; } - FATFS *fs = &active_mount->fatfs; - DWORD fattime; - _truncated_time = truncate_time(command->modification_time, &fattime); - override_fattime(fattime); - FRESULT result = f_open(fs, &active_file, mount_path, FA_WRITE | FA_OPEN_ALWAYS); - if (result != FR_OK) { + _truncated_time = truncate_time(command->modification_time); + supervisor_fs_err_t result = supervisor_vfs_open_file(active_mount, mount_path, + SUPERVISOR_FS_OPEN_WRITE | SUPERVISOR_FS_OPEN_CREATE, command->modification_time, &active_file); + if (result == SUPERVISOR_FS_BUSY) { + filesystem_unlock(active_mount); + return HELD_COMMAND; + } + if (result != SUPERVISOR_FS_OK) { response.status = STATUS_ERROR; common_hal_bleio_packet_buffer_write(&_transfer_packet_buffer, (const uint8_t *)&response, sizeof(struct write_pacing), NULL, 0); filesystem_unlock(active_mount); - override_fattime(0); return ANY_COMMAND; } // Write out the pacing response. @@ -290,10 +286,9 @@ static uint8_t _process_write(const uint8_t *raw_buf, size_t command_len) { size_t chunk_size = MIN(total_write_length - offset, 512 - (offset % 512)); // Special case when truncating the file. (Deleting stuff off the end.) if (chunk_size == 0) { - f_lseek(&active_file, offset); - f_truncate(&active_file); - f_close(&active_file); - override_fattime(0); + supervisor_vfs_seek_file(&active_file, offset); + supervisor_vfs_truncate_file(&active_file); + supervisor_vfs_close_file(&active_file); filesystem_unlock(active_mount); } response.offset = offset; @@ -320,7 +315,6 @@ static uint8_t _process_write_data(const uint8_t *raw_buf, size_t command_len) { response.status = STATUS_ERROR; common_hal_bleio_packet_buffer_write(&_transfer_packet_buffer, (const uint8_t *)&response, sizeof(struct write_pacing), NULL, 0); filesystem_unlock(active_mount); - override_fattime(0); return ANY_COMMAND; } // We need to receive another packet to have the full path. @@ -328,15 +322,14 @@ static uint8_t _process_write_data(const uint8_t *raw_buf, size_t command_len) { return THIS_COMMAND; } uint32_t offset = command->offset; - f_lseek(&active_file, offset); - UINT actual; - f_write(&active_file, command->data, command->data_size, &actual); - if (actual < command->data_size) { // -1 for the null we'll write + supervisor_vfs_seek_file(&active_file, offset); + size_t actual; + supervisor_fs_err_t result = supervisor_vfs_write_file(&active_file, command->data, command->data_size, &actual); + if (actual < command->data_size || result != SUPERVISOR_FS_OK) { // -1 for the null we'll write // TODO: throw away any more packets of path. response.status = STATUS_ERROR; common_hal_bleio_packet_buffer_write(&_transfer_packet_buffer, (const uint8_t *)&response, sizeof(struct write_pacing), NULL, 0); filesystem_unlock(active_mount); - override_fattime(0); return ANY_COMMAND; } offset += command->data_size; @@ -347,9 +340,8 @@ static uint8_t _process_write_data(const uint8_t *raw_buf, size_t command_len) { response.truncated_time = _truncated_time; common_hal_bleio_packet_buffer_write(&_transfer_packet_buffer, (const uint8_t *)&response, sizeof(struct write_pacing), NULL, 0); if (total_write_length == offset) { - f_truncate(&active_file); - f_close(&active_file); - override_fattime(0); + supervisor_vfs_truncate_file(&active_file); + supervisor_vfs_close_file(&active_file); filesystem_unlock(active_mount); // Don't reload until everything is written out of the packet buffer. common_hal_bleio_packet_buffer_flush(&_transfer_packet_buffer); @@ -378,16 +370,19 @@ static uint8_t _process_delete(const uint8_t *raw_buf, size_t command_len) { char *full_path = (char *)((uint8_t *)command) + header_size; full_path[command->path_length] = '\0'; - FRESULT result = supervisor_workflow_delete_recursive(full_path); + supervisor_fs_err_t result = supervisor_workflow_delete_recursive(full_path); + if (result == SUPERVISOR_FS_BUSY) { + return HELD_COMMAND; + } - if (result == FR_WRITE_PROTECTED) { + if (result == SUPERVISOR_FS_WRITE_PROTECTED) { response.status = STATUS_ERROR_READONLY; } - if (result != FR_OK) { + if (result != SUPERVISOR_FS_OK) { response.status = STATUS_ERROR; } common_hal_bleio_packet_buffer_write(&_transfer_packet_buffer, (const uint8_t *)&response, sizeof(struct delete_status), NULL, 0); - if (result == FR_OK) { + if (result == SUPERVISOR_FS_OK) { // Don't reload until everything is written out of the packet buffer. common_hal_bleio_packet_buffer_flush(&_transfer_packet_buffer); } @@ -395,10 +390,11 @@ static uint8_t _process_delete(const uint8_t *raw_buf, size_t command_len) { } // NULL-terminate the path and remove any trailing /. Older versions of the -// protocol require it but newer ones do not. +// protocol require it but newer ones do not. Keep the trailing / for the +// root: both FatFS and littlefs accept "/", but FatFS treats "" as the +// volume's current directory, not the root. static void _terminate_path(char *path, size_t path_length) { - // -1 because fatfs doesn't want a trailing / - if (path[path_length - 1] == '/') { + if (path_length > 1 && path[path_length - 1] == '/') { path[path_length - 1] = '\0'; } else { path[path_length] = '\0'; @@ -424,14 +420,12 @@ static uint8_t _process_mkdir(const uint8_t *raw_buf, size_t command_len) { char *full_path = (char *)command->path; _terminate_path(full_path, command->path_length); - DWORD fattime; - response.truncated_time = truncate_time(command->modification_time, &fattime); - FRESULT result = supervisor_workflow_mkdir(fattime, full_path); - if (result != FR_OK) { + supervisor_fs_err_t result = supervisor_workflow_mkdir(truncate_time(command->modification_time), full_path); + if (result != SUPERVISOR_FS_OK) { response.status = STATUS_ERROR; } common_hal_bleio_packet_buffer_write(&_transfer_packet_buffer, (const uint8_t *)&response, sizeof(struct mkdir_status), NULL, 0); - if (result == FR_OK) { + if (result == SUPERVISOR_FS_OK) { // Don't reload until everything is written out of the packet buffer. common_hal_bleio_packet_buffer_flush(&_transfer_packet_buffer); } @@ -453,6 +447,9 @@ static uint8_t _process_listdir(uint8_t *raw_buf, size_t command_len) { const struct listdir_command *command = (struct listdir_command *)raw_buf; struct listdir_entry *entry = (struct listdir_entry *)raw_buf; size_t header_size = sizeof(struct listdir_command); + bool entry_is_dir; + size_t entry_size; + uint64_t entry_mtime; mp_int_t max_packet_size = common_hal_bleio_packet_buffer_get_outgoing_packet_length(&_transfer_packet_buffer); if (max_packet_size < 0) { // -1 means we're disconnected @@ -477,16 +474,16 @@ static uint8_t _process_listdir(uint8_t *raw_buf, size_t command_len) { const char *mount_path; active_mount = filesystem_for_path(full_path, &mount_path); - if (active_mount == NULL || !filesystem_native_fatfs(active_mount)) { + if (active_mount == NULL || !supervisor_vfs_supported(active_mount)) { entry->command = LISTDIR_ENTRY; entry->status = STATUS_ERROR_NO_FILE; send_listdir_entry_header(entry, max_packet_size); return ANY_COMMAND; } - FATFS *fs = &active_mount->fatfs; - FF_DIR dir; - FRESULT res = f_opendir(fs, &dir, mount_path); + supervisor_vfs_dir_t dir; + memset(&dir, 0, sizeof(dir)); + supervisor_fs_err_t res = supervisor_vfs_opendir(active_mount, mount_path, &dir); entry->command = LISTDIR_ENTRY; entry->status = STATUS_OK; @@ -495,51 +492,44 @@ static uint8_t _process_listdir(uint8_t *raw_buf, size_t command_len) { entry->entry_count = 0; entry->flags = 0; - if (res != FR_OK) { + if (res != SUPERVISOR_FS_OK) { entry->status = STATUS_ERROR_NO_FILE; send_listdir_entry_header(entry, max_packet_size); return ANY_COMMAND; } - FILINFO file_info; - res = f_readdir(&dir, &file_info); - char *fn = file_info.fname; + char fn[FF_MAX_LFN + 1]; + res = supervisor_vfs_readdir(&dir, fn, sizeof(fn), NULL, NULL, NULL); size_t total_entries = 0; - while (res == FR_OK && fn[0] != 0) { - res = f_readdir(&dir, &file_info); + while (res == SUPERVISOR_FS_OK && fn[0] != 0) { + res = supervisor_vfs_readdir(&dir, fn, sizeof(fn), NULL, NULL, NULL); total_entries += 1; } // Rewind the directory. - f_readdir(&dir, NULL); + supervisor_vfs_rewinddir(&dir); entry->entry_count = total_entries; for (size_t i = 0; i < total_entries; i++) { - res = f_readdir(&dir, &file_info); + res = supervisor_vfs_readdir(&dir, fn, sizeof(fn), &entry_is_dir, &entry_size, &entry_mtime); entry->entry_number = i; - uint64_t truncated_time = timeutils_mktime(1980 + (file_info.fdate >> 9), - (file_info.fdate >> 5) & 0xf, - file_info.fdate & 0x1f, - file_info.ftime >> 11, - (file_info.ftime >> 5) & 0x1f, - (file_info.ftime & 0x1f) * 2) * 1000000000ULL; - entry->truncated_time = truncated_time; - if ((file_info.fattrib & AM_DIR) != 0) { + entry->truncated_time = entry_mtime; + if (entry_is_dir) { entry->flags = 1; // Directory entry->file_size = 0; } else { entry->flags = 0; - entry->file_size = file_info.fsize; + entry->file_size = entry_size; } - size_t name_length = strlen(file_info.fname); + size_t name_length = strlen(fn); entry->path_length = name_length; send_listdir_entry_header(entry, max_packet_size); size_t fn_offset = 0; while (fn_offset < name_length) { size_t fn_size = MIN(name_length - fn_offset, 4); - common_hal_bleio_packet_buffer_write(&_transfer_packet_buffer, ((uint8_t *)file_info.fname) + fn_offset, fn_size, NULL, 0); + common_hal_bleio_packet_buffer_write(&_transfer_packet_buffer, ((uint8_t *)fn) + fn_offset, fn_size, NULL, 0); fn_offset += fn_size; } } - f_closedir(&dir); + supervisor_vfs_closedir(&dir); entry->path_length = 0; entry->entry_number = entry->entry_count; entry->flags = 0; @@ -573,14 +563,14 @@ static uint8_t _process_move(const uint8_t *raw_buf, size_t command_len) { char *new_path = old_path + command->old_path_length + 1; new_path[command->new_path_length] = '\0'; - FRESULT result = supervisor_workflow_move(old_path, new_path); - if (result == FR_WRITE_PROTECTED) { + supervisor_fs_err_t result = supervisor_workflow_move(old_path, new_path); + if (result == SUPERVISOR_FS_WRITE_PROTECTED) { response.status = STATUS_ERROR_READONLY; - } else if (result != FR_OK) { + } else if (result != SUPERVISOR_FS_OK) { response.status = STATUS_ERROR; } common_hal_bleio_packet_buffer_write(&_transfer_packet_buffer, (const uint8_t *)&response, sizeof(struct move_status), NULL, 0); - if (result == FR_OK) { + if (result == SUPERVISOR_FS_OK) { // Don't reload until everything is written out of the packet buffer. common_hal_bleio_packet_buffer_flush(&_transfer_packet_buffer); } @@ -600,9 +590,11 @@ void supervisor_bluetooth_file_transfer_background(void) { running = true; mp_int_t size = 1; while (size > 0) { - size = common_hal_bleio_packet_buffer_readinto(&_transfer_packet_buffer, current_command + current_offset, COMMAND_SIZE - current_offset); + // A held command runs again from what is already in the buffer. + size = next_command == HELD_COMMAND ? 0 : + common_hal_bleio_packet_buffer_readinto(&_transfer_packet_buffer, current_command + current_offset, COMMAND_SIZE - current_offset); - if (size == 0) { + if (size == 0 && next_command != HELD_COMMAND) { break; } autoreload_suspend(AUTORELOAD_SUSPEND_BLE); @@ -653,7 +645,7 @@ void supervisor_bluetooth_file_transfer_background(void) { break; } // Preserve the offset if we are waiting for more from this command. - if (next_command != THIS_COMMAND) { + if (next_command != THIS_COMMAND && next_command != HELD_COMMAND) { current_offset = 0; } if (next_command == ANY_COMMAND) { @@ -674,6 +666,6 @@ void supervisor_bluetooth_file_transfer_background(void) { void supervisor_bluetooth_file_transfer_disconnected(void) { next_command = ANY_COMMAND; current_offset = 0; - f_close(&active_file); + supervisor_vfs_close_file(&active_file); autoreload_resume(AUTORELOAD_SUSPEND_BLE); } diff --git a/supervisor/shared/bluetooth/serial.c b/supervisor/shared/bluetooth/serial.c index 86ff1738a2a..037e5e3c7b7 100644 --- a/supervisor/shared/bluetooth/serial.c +++ b/supervisor/shared/bluetooth/serial.c @@ -15,6 +15,7 @@ #include "shared-bindings/_bleio/Service.h" #include "shared-bindings/_bleio/UUID.h" #include "shared-module/storage/__init__.h" +#include "supervisor/shared/bluetooth/bluetooth.h" #include "supervisor/shared/bluetooth/serial.h" #include "common-hal/_bleio/__init__.h" @@ -30,9 +31,6 @@ static bleio_uuid_obj_t supervisor_ble_circuitpython_tx_uuid; static bleio_characteristic_obj_t supervisor_ble_circuitpython_version_characteristic; static bleio_uuid_obj_t supervisor_ble_circuitpython_version_uuid; -// This is the base UUID for the CircuitPython service. -const uint8_t circuitpython_base_uuid[16] = {0x6e, 0x68, 0x74, 0x79, 0x50, 0x74, 0x69, 0x75, 0x63, 0x72, 0x69, 0x43, 0x00, 0x00, 0xaf, 0xad }; - static mp_obj_list_t characteristic_list; static mp_obj_t characteristic_list_items[3]; @@ -40,6 +38,10 @@ static mp_obj_t characteristic_list_items[3]; #error "BLEIO_PACKET_BUFFER_MAX_PACKET_SIZE must be a multiple of 4" #endif static uint32_t _outgoing1[BLEIO_PACKET_BUFFER_MAX_PACKET_SIZE / 4]; +// TODO: _outgoing2 is unused on espressif, whose NimBLE send calls copy the data +// rather than retaining the buffer as the nordic SoftDevice does. Letting a port +// declare how many outgoing buffers it needs would drop this static allocation +// there; nordic requires both. static uint32_t _outgoing2[BLEIO_PACKET_BUFFER_MAX_PACKET_SIZE / 4]; static ble_event_handler_t rx_static_handler_entry; static ble_event_handler_t tx_static_handler_entry; @@ -133,7 +135,7 @@ void supervisor_start_bluetooth_serial(void) { _common_hal_bleio_characteristic_buffer_construct(&_rx_buffer, &supervisor_ble_circuitpython_rx_characteristic, 0.1f, - (uint8_t *)_incoming, sizeof(_incoming) * sizeof(uint32_t), + (uint8_t *)_incoming, sizeof(_incoming), &rx_static_handler_entry, true /* watch for interrupt character */); diff --git a/supervisor/shared/display.c b/supervisor/shared/display.c index 32df5be74ef..b1ad0385cab 100644 --- a/supervisor/shared/display.c +++ b/supervisor/shared/display.c @@ -7,13 +7,23 @@ #include "supervisor/shared/display.h" #include +#include "supervisor/port.h" #include "py/mpstate.h" +#include "py/gc.h" #include "shared-bindings/displayio/Bitmap.h" #include "shared-bindings/displayio/Group.h" #include "shared-bindings/displayio/Palette.h" #include "shared-bindings/displayio/TileGrid.h" +// The static splash bypasses Group's Python constructor. Keep its scale in the +// representation expected by the selected compositor. +#if CIRCUITPY_DISPLAYIO_LVGL +#define SUPERVISOR_SPLASH_SCALE(scale) ((scale) * LV_SCALE_NONE) +#else +#define SUPERVISOR_SPLASH_SCALE(scale) (scale) +#endif + #if CIRCUITPY_RGBMATRIX #include "shared-module/displayio/__init__.h" #endif @@ -36,8 +46,77 @@ #if CIRCUITPY_TERMINALIO #include "supervisor/port.h" -#if CIRCUITPY_OS_GETENV -#include "shared-module/os/__init__.h" + +#if CIRCUITPY_SETTINGS_TOML +#include "supervisor/shared/settings.h" +#endif + +#if CIRCUITPY_LVFONTIO +#include "shared-bindings/lvfontio/OnDiskFont.h" +#include "supervisor/filesystem.h" + +#include "supervisor/shared/serial.h" + +// Check if a custom font file exists and return its path if found +// Returns true if font file exists, false otherwise +static bool check_for_custom_font(const char **font_path_out) { + if (!filesystem_present()) { + return false; + } + + // Check for the font through the supervisor filesystem + // API so it works on FAT and littlefs mounts. + supervisor_vfs_t *vfs = filesystem_circuitpy(); + if (vfs == NULL) { + return false; + } + + const char *default_font_path = "/fonts/terminal.lvfontbin"; + const char *font_path = default_font_path; + + #if CIRCUITPY_SETTINGS_TOML + // Buffer for storing custom font path + static char custom_font_path[128]; + if (settings_get_str("CIRCUITPY_TERMINAL_FONT", custom_font_path, sizeof(custom_font_path)) == SETTINGS_OK) { + // Use custom font path from environment variable + font_path = custom_font_path; + } + #endif + + if (supervisor_vfs_stat(vfs, font_path, NULL, NULL, NULL) == SUPERVISOR_FS_OK) { + if (font_path_out != NULL) { + *font_path_out = font_path; + } + return true; + } + + // If custom font path doesn't exist, use default font + font_path = default_font_path; + + if (supervisor_vfs_stat(vfs, font_path, NULL, NULL, NULL) == SUPERVISOR_FS_OK) { + if (font_path_out != NULL) { + *font_path_out = font_path; + } + return true; + } + + return false; +} + +// Initialize a BuiltinFont object with the specified font file and max_slots +// Returns true on success, false on failure +static bool init_lvfont(lvfontio_ondiskfont_t *font, const char *font_path, uint16_t max_slots) { + if (font == NULL) { + return false; + } + + font->base.type = &lvfontio_ondiskfont_type; + + // Pass false for use_gc_allocator during startup when garbage collector isn't fully initialized + common_hal_lvfontio_ondiskfont_construct(font, font_path, max_slots, false); + + return !common_hal_lvfontio_ondiskfont_deinited(font); +} #endif #endif @@ -52,29 +131,73 @@ static uint8_t *tilegrid_tiles = NULL; static size_t tilegrid_tiles_size = 0; #endif +#if CIRCUITPY_LVFONTIO && CIRCUITPY_TERMINALIO +static lvfontio_ondiskfont_t *lvfont = NULL; +static bool skip_lv_font = false; +#endif + void supervisor_start_terminal(uint16_t width_px, uint16_t height_px) { if (supervisor_terminal_started()) { return; } + + #if CIRCUITPY_TERMINALIO // Default the scale to 2 because we may show blinka without the terminal for // languages that don't have font support. mp_int_t scale = 2; - #if CIRCUITPY_TERMINALIO displayio_tilegrid_t *scroll_area = &supervisor_terminal_scroll_area_text_grid; displayio_tilegrid_t *status_bar = &supervisor_terminal_status_bar_text_grid; - bool reset_tiles = false; - uint16_t width_in_tiles = width_px / scroll_area->tile_width; + bool reset_tiles = tilegrid_tiles == NULL; + + uint16_t glyph_width = 0; + uint16_t glyph_height = 0; + + #if CIRCUITPY_LVFONTIO + // Check if we have a custom terminal font in the filesystem + bool use_lv_font = false; + const char *font_path = NULL; + const uint16_t display_width_px = width_px; + const uint16_t display_height_px = height_px; + + if (!skip_lv_font && check_for_custom_font(&font_path)) { + // Initialize a temporary font just to get dimensions + lvfontio_ondiskfont_t temp_font; + if (init_lvfont(&temp_font, font_path, 1)) { + // The terminal fills itself with spaces. With one slot, caching fails if the space is + // missing or wider than a cell. + if (common_hal_lvfontio_ondiskfont_cache_glyph(&temp_font, ' ', NULL) >= 0) { + // Get the font dimensions + common_hal_lvfontio_ondiskfont_get_dimensions(&temp_font, &glyph_width, &glyph_height); + use_lv_font = true; + reset_tiles = true; + // TODO: We may want to detect when the files modified time hasn't changed. + } + + // Clean up the temp font - we'll create a proper one later + common_hal_lvfontio_ondiskfont_deinit(&temp_font); + } + } + #endif + #if CIRCUITPY_FONTIO + if (glyph_width == 0) { + glyph_width = supervisor_terminal_font.width; + glyph_height = supervisor_terminal_font.height; + } + #endif + + uint16_t width_in_tiles = width_px / glyph_width; + // determine scale based on width - if (width_in_tiles <= 80) { + if (width_in_tiles <= 120) { scale = 1; } - #if CIRCUITPY_OS_GETENV - (void)common_hal_os_getenv_int("CIRCUITPY_TERMINAL_SCALE", &scale); + #if CIRCUITPY_SETTINGS_TOML + (void)settings_get_int("CIRCUITPY_TERMINAL_SCALE", &scale); #endif - width_in_tiles = MAX(1, width_px / (scroll_area->tile_width * scale)); - uint16_t height_in_tiles = MAX(2, height_px / (scroll_area->tile_height * scale)); + width_in_tiles = MAX(1, width_px / (glyph_width * scale)); + uint16_t height_in_tiles = MAX(2, height_px / (glyph_height * scale)); uint16_t total_tiles = width_in_tiles * height_in_tiles; @@ -83,69 +206,134 @@ void supervisor_start_terminal(uint16_t width_px, uint16_t height_px) { (scroll_area->height_in_tiles != height_in_tiles - 1)) { reset_tiles = true; } - // Reuse the previous allocation if possible - if (tilegrid_tiles) { - if (tilegrid_tiles_size != total_tiles) { + + circuitpython_splash.scale = SUPERVISOR_SPLASH_SCALE(scale); + if (!reset_tiles) { + return; + } + + // Adjust the display dimensions to account for scale of the outer group. + width_px /= scale; + height_px /= scale; + + // Number of tiles from the left edge to inset the status bar. + size_t min_left_padding = 0; + status_bar->tile_width = glyph_width; + status_bar->tile_height = glyph_height; + #if CIRCUITPY_REPL_LOGO + // Blinka + 1 px padding minimum + min_left_padding = supervisor_blinka_sprite.pixel_width + 1; + // Align the status bar to the bottom of the logo. + status_bar->y = supervisor_blinka_sprite.pixel_height - status_bar->tile_height; + #else + status_bar->y = 0; + #endif + status_bar->width_in_tiles = (width_px - min_left_padding) / status_bar->tile_width; + status_bar->height_in_tiles = 1; + status_bar->pixel_width = status_bar->width_in_tiles * status_bar->tile_width; + status_bar->pixel_height = status_bar->tile_height; + // Right align the status bar. + status_bar->x = width_px - status_bar->pixel_width; + status_bar->top_left_y = 0; + #if !CIRCUITPY_DISPLAYIO_LVGL + status_bar->full_change = true; + #endif + + scroll_area->tile_width = glyph_width; + scroll_area->tile_height = glyph_height; + scroll_area->width_in_tiles = width_in_tiles; + // Leave space for the status bar, no matter if we have logo or not. + scroll_area->height_in_tiles = height_in_tiles - 1; + scroll_area->pixel_width = scroll_area->width_in_tiles * scroll_area->tile_width; + scroll_area->pixel_height = scroll_area->height_in_tiles * scroll_area->tile_height; + // Right align the scroll area to give margin to the start of each line. + scroll_area->x = width_px - scroll_area->pixel_width; + scroll_area->top_left_y = 0; + // Align the scroll area to the bottom so that the newest line isn't cutoff. The top line + // may be clipped by the status bar and that's ok. + scroll_area->y = height_px - scroll_area->pixel_height; + #if !CIRCUITPY_DISPLAYIO_LVGL + scroll_area->full_change = true; + #endif + + mp_obj_t new_bitmap = mp_const_none; + mp_obj_t new_font = mp_const_none; + + #if CIRCUITPY_LVFONTIO + if (lvfont != NULL) { + common_hal_lvfontio_ondiskfont_deinit(lvfont); + // This will also free internal buffers that may change size. + port_free(lvfont); + lvfont = NULL; + } + + if (use_lv_font) { + // We found a custom terminal font file, use it instead of the built-in font + + lvfont = port_malloc(sizeof(lvfontio_ondiskfont_t), false); + if (lvfont != NULL) { + // Use the number of tiles in the terminal and status bar for the number of slots + // This ensures we have enough slots to display all characters that could appear on screen + uint16_t num_slots = width_in_tiles * height_in_tiles; + + // Initialize the font with our helper function + if (init_lvfont(lvfont, font_path, num_slots)) { + // Get the bitmap from the font + new_bitmap = common_hal_lvfontio_ondiskfont_get_bitmap(lvfont); + new_font = MP_OBJ_FROM_PTR(lvfont); + } else { + // If font initialization failed, free the memory and fall back to built-in font + port_free(lvfont); + lvfont = NULL; + } + } + if (lvfont == NULL) { + // The layout above used the custom font's dimensions, so redo it for the built-in font. + skip_lv_font = true; + supervisor_start_terminal(display_width_px, display_height_px); + skip_lv_font = false; + return; + } + } + #endif + #if CIRCUITPY_FONTIO + if (new_font == mp_const_none) { + new_bitmap = MP_OBJ_FROM_PTR(supervisor_terminal_font.bitmap); + new_font = MP_OBJ_FROM_PTR(&supervisor_terminal_font); + } + #endif + + if (new_font != mp_const_none) { + size_t total_values = common_hal_displayio_bitmap_get_width(new_bitmap) / glyph_width; + if (tilegrid_tiles) { port_free(tilegrid_tiles); tilegrid_tiles = NULL; - tilegrid_tiles_size = 0; - reset_tiles = true; } - } - if (!tilegrid_tiles) { - tilegrid_tiles = port_malloc(total_tiles, false); - reset_tiles = true; + // A TileGrid stores a tile index in one byte when the bitmap has at most 255 tiles and in + // two when it has more (tiles_in_bitmap, which is total_values below). The number of cells + // on screen says nothing about how wide an index is. + size_t bytes_per_tile = 1; + if (total_values > 255) { + // Two bytes per tile. + bytes_per_tile = 2; + } + tilegrid_tiles = port_malloc(total_tiles * bytes_per_tile, false); if (!tilegrid_tiles) { return; } - } - - if (reset_tiles) { - // Adjust the display dimensions to account for scale of the outer group. - width_px /= scale; - height_px /= scale; - - // Number of tiles from the left edge to inset the status bar. - size_t min_left_padding = 0; - #if CIRCUITPY_REPL_LOGO - // Blinka + 1 px padding minimum - min_left_padding = supervisor_blinka_sprite.pixel_width + 1; - // Align the status bar to the bottom of the logo. - status_bar->y = supervisor_blinka_sprite.pixel_height - status_bar->tile_height; - #else - status_bar->y = 0; - #endif - status_bar->width_in_tiles = (width_px - min_left_padding) / status_bar->tile_width; - status_bar->height_in_tiles = 1; - status_bar->pixel_width = status_bar->width_in_tiles * status_bar->tile_width; - status_bar->pixel_height = status_bar->tile_height; - // Right align the status bar. - status_bar->x = width_px - status_bar->pixel_width; - status_bar->top_left_y = 0; status_bar->tiles = tilegrid_tiles; - status_bar->full_change = true; - - scroll_area->width_in_tiles = width_in_tiles; - // Leave space for the status bar, no matter if we have logo or not. - scroll_area->height_in_tiles = height_in_tiles - 1; - scroll_area->pixel_width = scroll_area->width_in_tiles * scroll_area->tile_width; - scroll_area->pixel_height = scroll_area->height_in_tiles * scroll_area->tile_height; - // Right align the scroll area to give margin to the start of each line. - scroll_area->x = width_px - scroll_area->pixel_width; - scroll_area->top_left_y = 0; - // Align the scroll area to the bottom so that the newest line isn't cutoff. The top line - // may be clipped by the status bar and that's ok. - scroll_area->y = height_px - scroll_area->pixel_height; - scroll_area->tiles = tilegrid_tiles + width_in_tiles; - scroll_area->full_change = true; - - common_hal_terminalio_terminal_construct(&supervisor_terminal, scroll_area, &supervisor_terminal_font, status_bar); - - // Do not update status bar until after boot.py has run, in case it is disabled. + status_bar->tiles_in_bitmap = total_values; + status_bar->bitmap_width_in_tiles = total_values; + scroll_area->tiles = tilegrid_tiles + width_in_tiles * bytes_per_tile; + scroll_area->tiles_in_bitmap = total_values; + scroll_area->bitmap_width_in_tiles = total_values; + + common_hal_displayio_tilegrid_set_bitmap(scroll_area, new_bitmap); + common_hal_displayio_tilegrid_set_bitmap(status_bar, new_bitmap); + common_hal_terminalio_terminal_construct(&supervisor_terminal, scroll_area, + new_font, status_bar); } #endif - - circuitpython_splash.scale = scale; } void supervisor_stop_terminal(void) { @@ -212,7 +400,7 @@ displayio_group_t circuitpython_splash = { .base = {.type = &displayio_group_type }, .x = 0, .y = 0, - .scale = 2, + .scale = SUPERVISOR_SPLASH_SCALE(2), .members = &splash_children, .item_removed = false, .in_group = false, diff --git a/supervisor/shared/external_flash/common_commands.h b/supervisor/shared/external_flash/common_commands.h index 539f679d766..f2853e6b509 100644 --- a/supervisor/shared/external_flash/common_commands.h +++ b/supervisor/shared/external_flash/common_commands.h @@ -23,3 +23,4 @@ #define CMD_ENABLE_RESET 0x66 #define CMD_RESET 0x99 #define CMD_WAKE 0xab +#define CMD_GLOBAL_BLOCK_PROTECTION_UNLOCK 0x98 diff --git a/supervisor/shared/external_flash/device.h b/supervisor/shared/external_flash/device.h index 869f7b7a244..d35a84d9c32 100644 --- a/supervisor/shared/external_flash/device.h +++ b/supervisor/shared/external_flash/device.h @@ -24,8 +24,12 @@ typedef struct { // status register. uint8_t quad_enable_bit_mask; + // Device has sector-level write protection bool has_sector_protection : 1; + // Device uses global block protection lock instead of status register bits to enable sector writes + bool use_global_block_protection_lock : 1; + // Supports the 0x0b fast read command with 8 dummy cycles. bool supports_fast_read : 1; diff --git a/supervisor/shared/external_flash/devices.h.jinja b/supervisor/shared/external_flash/devices.h.jinja index 3859559d2b3..3d24b674fed 100644 --- a/supervisor/shared/external_flash/devices.h.jinja +++ b/supervisor/shared/external_flash/devices.h.jinja @@ -17,6 +17,7 @@ .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() }}, \ + .use_global_block_protection_lock = {{ device.use_global_block_protection_lock | lower() }}, \ .supports_fast_read = {{ device.supports_fast_read | lower() }}, \ .supports_qspi = {{ device["6b_quad_read"] | lower() }}, \ .supports_qspi_writes = {{ device["32_qspi_write"] | lower() }}, \ diff --git a/supervisor/shared/external_flash/external_flash.c b/supervisor/shared/external_flash/external_flash.c index b029286fa41..abf232c0d18 100644 --- a/supervisor/shared/external_flash/external_flash.c +++ b/supervisor/shared/external_flash/external_flash.c @@ -268,8 +268,12 @@ void supervisor_flash_init(void) { write_enable(); // Turn off sector protection - uint8_t data[1] = {0x00}; - spi_flash_write_command(CMD_WRITE_STATUS_BYTE1, data, 1); + if (flash_device->use_global_block_protection_lock) { + spi_flash_command(CMD_GLOBAL_BLOCK_PROTECTION_UNLOCK); + } else { + uint8_t data[1] = {0x00}; + spi_flash_write_command(CMD_WRITE_STATUS_BYTE1, data, 1); + } } // Turn off writes in case this is a microcontroller only reset. diff --git a/supervisor/shared/external_flash/spi_flash.c b/supervisor/shared/external_flash/spi_flash.c index f9ed50ac46f..0fde849cd17 100644 --- a/supervisor/shared/external_flash/spi_flash.c +++ b/supervisor/shared/external_flash/spi_flash.c @@ -126,11 +126,9 @@ void spi_flash_init(void) { // Set CS high (disabled). common_hal_digitalio_digitalinout_switch_to_output(&cs_pin, true, DRIVE_MODE_PUSH_PULL); - common_hal_digitalio_digitalinout_never_reset(&cs_pin); supervisor_flash_spi_bus.base.type = &busio_spi_type; common_hal_busio_spi_construct(&supervisor_flash_spi_bus, SPI_FLASH_SCK_PIN, SPI_FLASH_MOSI_PIN, SPI_FLASH_MISO_PIN, false); - common_hal_busio_spi_never_reset(&supervisor_flash_spi_bus); common_hal_busio_spi_configure(&supervisor_flash_spi_bus, SPI_FLASH_MAX_BAUDRATE, 0, 0, 8); return; diff --git a/supervisor/shared/fatfs.c b/supervisor/shared/fatfs.c index 07ab724d7a9..ba437158f73 100644 --- a/supervisor/shared/fatfs.c +++ b/supervisor/shared/fatfs.c @@ -15,6 +15,21 @@ #include "shared/timeutils/timeutils.h" DWORD _time_override = 0; + +// 2016-09-01 16:43:35 UTC, the fallback timestamp used when there is no RTC. +#define FATTIME_FALLBACK_NS (1472748215000000000ULL) + +uint64_t get_fattime_ns(void) { + #if CIRCUITPY_RTC + timeutils_struct_time_t tm; + common_hal_rtc_get_time(&tm); + return (uint64_t)timeutils_mktime_1970(tm.tm_year, tm.tm_mon, tm.tm_mday, + tm.tm_hour, tm.tm_min, tm.tm_sec) * 1000000000ULL; + #else + return FATTIME_FALLBACK_NS; + #endif +} + DWORD get_fattime(void) { if (_time_override > 0) { return _time_override; @@ -25,6 +40,7 @@ DWORD get_fattime(void) { 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 + // Same instant as FATTIME_FALLBACK_NS: 2016-09-01 16:43:35 UTC. return ((2016 - 1980) << 25) | ((9) << 21) | ((1) << 16) | ((16) << 11) | ((43) << 5) | (35 / 2); #endif } diff --git a/supervisor/shared/filesystem.c b/supervisor/shared/filesystem.c index 3532db4bdce..b9728a0f001 100644 --- a/supervisor/shared/filesystem.c +++ b/supervisor/shared/filesystem.c @@ -12,11 +12,36 @@ #include "py/mpstate.h" +#include "shared/timeutils/timeutils.h" +#include "supervisor/fatfs.h" +#if CIRCUITPY_STORAGE_MAP_FILE +#include "shared-bindings/storage/__init__.h" +#include "supervisor/shared/reload.h" +#endif #include "supervisor/flash.h" #include "supervisor/linker.h" +#if CIRCUITPY_FILESYSTEM_LITTLEFS +#include "extmod/vfs_lfs.h" +#include "lib/littlefs/lfs2.h" +#include "supervisor/port_heap.h" +#include "supervisor/shared/tick.h" +#endif + +#if CIRCUITPY_SDCARDIO +#include "shared-module/sdcardio/__init__.h" +#endif + +#if CIRCUITPY_EMMC_USB +#include "shared-module/emmcio/__init__.h" +#endif + static mp_vfs_mount_t _circuitpy_vfs; -static fs_user_mount_t _circuitpy_usermount; +static supervisor_vfs_t _circuitpy_mount; + +#if CIRCUITPY_FILESYSTEM_LITTLEFS +static bool _lfs_freshly_formatted; +#endif #if CIRCUITPY_SAVES_PARTITION_SIZE > 0 static mp_vfs_mount_t _saves_vfs; @@ -26,6 +51,99 @@ static fs_user_mount_t _saves_usermount; static volatile uint32_t filesystem_flush_interval_ms = CIRCUITPY_FILESYSTEM_FLUSH_INTERVAL_MS; volatile bool filesystem_flush_requested = false; +// Mapping between FatFS and littlefs results and the supervisor filesystem +// error codes. +#if CIRCUITPY_FILESYSTEM_LITTLEFS +static supervisor_fs_err_t fat_error(FRESULT res) { + switch (res) { + case FR_OK: + return SUPERVISOR_FS_OK; + case FR_NO_FILE: + return SUPERVISOR_FS_NO_FILE; + case FR_NO_PATH: + case FR_INVALID_NAME: + return SUPERVISOR_FS_NO_PATH; + case FR_EXIST: + return SUPERVISOR_FS_EXIST; + case FR_WRITE_PROTECTED: + return SUPERVISOR_FS_WRITE_PROTECTED; + case FR_DENIED: + // FatFS uses FR_DENIED for read-only media and for no free + // cluster. We can't tell them apart, so report no space. + return SUPERVISOR_FS_NO_SPACE; + case FR_LOCKED: + return SUPERVISOR_FS_BUSY; + default: + return SUPERVISOR_FS_IO; + } +} +#else +// On FAT-only builds supervisor_fs_err_t is FRESULT, so +// FatFS results need no translation. This keeps non-littlefs builds from +// growing when the supervisor filesystem API was added. +#define fat_error(res) ((supervisor_fs_err_t)(res)) +#endif + +// Convert nanoseconds past 1970/1/1 to the FAT timestamp format. +static DWORD fattime_from_ns(uint64_t ns) { + timeutils_struct_time_t tm; + uint64_t seconds = timeutils_seconds_since_epoch_from_nanoseconds_since_1970(ns); + timeutils_seconds_since_epoch_to_struct_time(seconds, &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); +} + +#if CIRCUITPY_FILESYSTEM_LITTLEFS +static supervisor_fs_err_t lfs_error(int err) { + switch (err) { + case LFS2_ERR_OK: + return SUPERVISOR_FS_OK; + case LFS2_ERR_NOENT: + return SUPERVISOR_FS_NO_FILE; + case LFS2_ERR_EXIST: + return SUPERVISOR_FS_EXIST; + case LFS2_ERR_NOTDIR: + case LFS2_ERR_ISDIR: + return SUPERVISOR_FS_NO_PATH; + case LFS2_ERR_NOSPC: + return SUPERVISOR_FS_NO_SPACE; + default: + return SUPERVISOR_FS_IO; + } +} + +// Store nanoseconds past the littlefs mtime epoch (1970/1/1) little-endian. +static void lfs_mtime_store(uint8_t buf[8], uint64_t ns) { + ns = timeutils_nanoseconds_since_epoch_to_nanoseconds_since_1970(ns); + for (size_t i = 0; i < 8; ++i) { + buf[i] = ns; + ns >>= 8; + } +} + +static uint64_t lfs_mtime_load(const uint8_t buf[8]) { + uint64_t ns = 0; + for (size_t i = 8; i > 0; --i) { + ns = ns << 8 | buf[i - 1]; + } + return timeutils_nanoseconds_since_epoch_to_nanoseconds_since_1970(ns); +} + +// Read a file or directory modification time from the littlefs mtime attribute. +static uint64_t lfs_get_path_mtime(lfs2_t *lfs, const char *path) { + uint8_t mtime[8]; + lfs2_ssize_t sz = lfs2_getattr(lfs, path, LFS_ATTR_MTIME, mtime, sizeof(mtime)); + if (sz != (lfs2_ssize_t)sizeof(mtime)) { + return 0; + } + return lfs_mtime_load(mtime); +} + +static bool is_lfs(supervisor_vfs_t *vfs) { + return vfs->common.base.type == &mp_type_vfs_lfs2; +} +#endif + void filesystem_background(void) { if (filesystem_flush_requested) { filesystem_flush_interval_ms = CIRCUITPY_FILESYSTEM_FLUSH_INTERVAL_MS; @@ -48,37 +166,177 @@ inline void filesystem_tick(void) { } } - __attribute__((unused)) // this function MAY be unused -static void make_empty_file(FATFS *fatfs, const char *path) { - FIL fp; - f_open(fatfs, &fp, path, FA_WRITE | FA_CREATE_ALWAYS); - f_close(&fp); +static bool make_empty_file(supervisor_vfs_t *vfs, const char *path) { + supervisor_vfs_file_t fp; + supervisor_fs_err_t err = supervisor_vfs_open_file(vfs, path, + SUPERVISOR_FS_OPEN_WRITE | SUPERVISOR_FS_OPEN_CREATE | SUPERVISOR_FS_OPEN_TRUNCATE, 0, &fp); + if (err != SUPERVISOR_FS_OK) { + return false; + } + return supervisor_vfs_close_file(&fp) == SUPERVISOR_FS_OK; } #if CIRCUITPY_FULL_BUILD -#define MAKE_FILE_WITH_OPTIONAL_CONTENTS(fatfs, filename, string_literal) do { \ +#define MAKE_FILE_WITH_OPTIONAL_CONTENTS(vfs, filename, string_literal) do { \ const byte buffer[] = string_literal; \ - make_file_with_contents(fatfs, filename, buffer, sizeof(buffer) - 1); \ + make_file_with_contents(vfs, filename, buffer, sizeof(buffer) - 1); \ } while (0) -static void make_file_with_contents(FATFS *fatfs, const char *filename, const byte *content, UINT size) { - FIL fs; - // Create or modify existing code.py file - f_open(fatfs, &fs, filename, FA_WRITE | FA_CREATE_ALWAYS); - f_write(&fs, content, size, &size); - f_close(&fs); +static bool make_file_with_contents(supervisor_vfs_t *vfs, const char *filename, const byte *content, UINT size) { + supervisor_vfs_file_t fp; + if (supervisor_vfs_open_file(vfs, filename, + SUPERVISOR_FS_OPEN_WRITE | SUPERVISOR_FS_OPEN_CREATE | SUPERVISOR_FS_OPEN_TRUNCATE, 0, &fp) != SUPERVISOR_FS_OK) { + return false; + } + size_t written; + supervisor_vfs_write_file(&fp, content, size, &written); + return supervisor_vfs_close_file(&fp) == SUPERVISOR_FS_OK && written == size; } #else -#define MAKE_FILE_WITH_OPTIONAL_CONTENTS(fatfs, filename, string_literal) \ - make_empty_file(fatfs, filename) +#define MAKE_FILE_WITH_OPTIONAL_CONTENTS(vfs, filename, string_literal) \ + (void)make_empty_file(vfs, filename) #endif +#if CIRCUITPY_FILESYSTEM_LITTLEFS + +// littlefs block-device adapter for the supervisor flash block device. The +// block size is FILESYSTEM_BLOCK_SIZE so lfs2 blocks map 1:1 onto supervisor +// flash blocks. Reads/writes that are not block-aligned are served through a +// read-modify-write because the supervisor block device is block granular. + +static int lfs_flash_read(const struct lfs2_config *c, lfs2_block_t block, lfs2_off_t off, void *buffer, lfs2_size_t size) { + if (off == 0 && size == FILESYSTEM_BLOCK_SIZE) { + return supervisor_flash_read_blocks(buffer, block, 1) == 0 ? LFS2_ERR_OK : LFS2_ERR_IO; + } + uint8_t tmp[FILESYSTEM_BLOCK_SIZE]; + if (supervisor_flash_read_blocks(tmp, block, 1) != 0) { + return LFS2_ERR_IO; + } + memcpy(buffer, tmp + off, size); + return LFS2_ERR_OK; +} + +static int lfs_flash_prog(const struct lfs2_config *c, lfs2_block_t block, lfs2_off_t off, const void *buffer, lfs2_size_t size) { + supervisor_flash_mark_dirty(); + if (off == 0 && size == FILESYSTEM_BLOCK_SIZE) { + return supervisor_flash_write_blocks(buffer, block, 1) == 0 ? LFS2_ERR_OK : LFS2_ERR_IO; + } + uint8_t tmp[FILESYSTEM_BLOCK_SIZE]; + if (supervisor_flash_read_blocks(tmp, block, 1) != 0) { + return LFS2_ERR_IO; + } + memcpy(tmp + off, buffer, size); + if (supervisor_flash_write_blocks(tmp, block, 1) != 0) { + return LFS2_ERR_IO; + } + return LFS2_ERR_OK; +} + +// The supervisor block device erases as part of its write path, so there is +// nothing to do here. +static int lfs_flash_erase(const struct lfs2_config *c, lfs2_block_t block) { + return LFS2_ERR_OK; +} + +static int lfs_flash_sync(const struct lfs2_config *c) { + supervisor_flash_flush(); + return LFS2_ERR_OK; +} + +static void *lfs_supervisor_alloc(size_t size) { + return port_malloc(size, false); +} + +static bool lfs_write_boot_file(const char *path, const char *contents, size_t size) { + supervisor_vfs_file_t file; + if (supervisor_vfs_open_file(&_circuitpy_mount, path, + SUPERVISOR_FS_OPEN_WRITE | SUPERVISOR_FS_OPEN_CREATE | SUPERVISOR_FS_OPEN_TRUNCATE, 0, &file) != SUPERVISOR_FS_OK) { + return false; + } + size_t written = 0; + supervisor_vfs_write_file(&file, contents, size, &written); + supervisor_fs_err_t err = supervisor_vfs_close_file(&file); + return written == size && err == SUPERVISOR_FS_OK; +} + +#endif // CIRCUITPY_FILESYSTEM_LITTLEFS + // we don't make this function static because it needs a lot of stack and we // want it to be executed without using stack within main() function bool filesystem_init(bool create_allowed, bool force_create) { + mp_vfs_mount_t *circuitpy_vfs = &_circuitpy_vfs; + circuitpy_vfs->len = 0; + + #if CIRCUITPY_FILESYSTEM_LITTLEFS + // init the vfs object. The VM (and its GC) is not running yet, so + // everything here uses static storage or the port allocator. + mp_obj_vfs_lfs2_t *circuitpy = &_circuitpy_mount.lfs2; + memset(circuitpy, 0, sizeof(*circuitpy)); + circuitpy->base.type = &mp_type_vfs_lfs2; + // cur_dir is used to join relative paths (make_path). It cannot be + // allocated on the GC heap because the VM is not running yet, so give it + // a static buffer. It is truncated back to its previous length after each + // join, so it stays short in practice. + static char lfs_cur_dir_buf[128]; + vstr_init_fixed_buf(&circuitpy->cur_dir, sizeof(lfs_cur_dir_buf), lfs_cur_dir_buf); + vstr_add_str(&circuitpy->cur_dir, "/"); + circuitpy->enable_mtime = true; + + struct lfs2_config *config = &circuitpy->config; + memset(config, 0, sizeof(*config)); + config->context = circuitpy; + config->read = lfs_flash_read; + config->prog = lfs_flash_prog; + config->erase = lfs_flash_erase; + config->sync = lfs_flash_sync; + config->block_size = supervisor_flash_get_block_size(); + // Initialize the block device (opens the partition) before asking for its + // geometry; the FAT path does the same via the blockdev INIT ioctl. + supervisor_flash_init(); + config->block_count = supervisor_flash_get_block_count(); + config->read_size = config->block_size; + config->prog_size = config->block_size; + + _lfs_freshly_formatted = false; + if (force_create) { + // Reformat requested (e.g. from safe mode). + if (lfs2_format(&circuitpy->lfs, config) != LFS2_ERR_OK) { + return false; + } + _lfs_freshly_formatted = true; + } + int mount_err; + mp_obj_t mounted = mp_vfs_lfs2_mount_supervisor(circuitpy, lfs_supervisor_alloc, + create_allowed && !force_create, &_lfs_freshly_formatted, &mount_err); + if (mounted == MP_OBJ_NULL) { + return false; + } + (void)mount_err; + + if (_lfs_freshly_formatted) { + #if CIRCUITPY_SDCARDIO + lfs2_mkdir(&circuitpy->lfs, "/sd"); + #endif + + #if CIRCUITPY_SETTINGS_TOML + // settings.toml is not read yet on littlefs filesystems; see + // supervisor/shared/settings.c. Create it empty for forward + // compatibility. + lfs_write_boot_file("/settings.toml", "", 0); + #endif + // make a sample code.py file + lfs_write_boot_file("/code.py", "print(\"Hello World!\")\n", sizeof("print(\"Hello World!\")\n") - 1); + + // create empty lib directory + lfs2_mkdir(&circuitpy->lfs, "/lib"); + + // and ensure everything is flushed + supervisor_flash_flush(); + } + #else // init the vfs object - fs_user_mount_t *circuitpy = &_circuitpy_usermount; + fs_user_mount_t *circuitpy = &_circuitpy_mount.fat; circuitpy->blockdev.flags = 0; supervisor_flash_init_vfs(circuitpy); @@ -92,13 +350,10 @@ bool filesystem_init(bool create_allowed, bool force_create) { saves->blockdev.offset = 0; saves->blockdev.size = CIRCUITPY_SAVES_PARTITION_SIZE; supervisor_flash_init_vfs(saves); - filesystem_set_concurrent_write_protection(saves, true); - filesystem_set_writable_by_usb(saves, false); + filesystem_set_concurrent_write_protection((supervisor_vfs_t *)saves, true); + filesystem_set_writable_by_usb((supervisor_vfs_t *)saves, false); #endif - mp_vfs_mount_t *circuitpy_vfs = &_circuitpy_vfs; - circuitpy_vfs->len = 0; - // try to mount the flash FRESULT res = f_mount(&circuitpy->fatfs); if ((res == FR_NO_FILESYSTEM && create_allowed) || force_create) { @@ -131,21 +386,20 @@ bool filesystem_init(bool create_allowed, bool force_create) { if (res != FR_OK) { return false; } - make_empty_file(&circuitpy->fatfs, "/.fseventsd/no_log"); - make_empty_file(&circuitpy->fatfs, "/.metadata_never_index"); + make_empty_file(&_circuitpy_mount, "/.fseventsd/no_log"); + make_empty_file(&_circuitpy_mount, "/.metadata_never_index"); // Prevent storing trash on all OSes. - make_empty_file(&circuitpy->fatfs, "/.Trashes"); // MacOS - make_empty_file(&circuitpy->fatfs, "/.Trash-1000"); // Linux, XDG trash spec: + make_empty_file(&_circuitpy_mount, "/.Trashes"); // MacOS + make_empty_file(&_circuitpy_mount, "/.Trash-1000"); // Linux, XDG trash spec: // https://specifications.freedesktop.org/trash-spec/trashspec-latest.html #endif #if CIRCUITPY_SDCARDIO || CIRCUITPY_SDIOIO res = f_mkdir(&circuitpy->fatfs, "/sd"); #if CIRCUITPY_FULL_BUILD - MAKE_FILE_WITH_OPTIONAL_CONTENTS(&circuitpy->fatfs, "/sd/placeholder.txt", - "SD cards mounted at /sd will hide this file from Python." - " SD cards are not visible via USB CIRCUITPY.\n"); + MAKE_FILE_WITH_OPTIONAL_CONTENTS(&_circuitpy_mount, "/sd/placeholder.txt", + "SD cards mounted at /sd will hide this file from Python.\n"); #endif #endif @@ -162,18 +416,18 @@ bool filesystem_init(bool create_allowed, bool force_create) { } #if CIRCUITPY_FULL_BUILD if (res == FR_OK) { - MAKE_FILE_WITH_OPTIONAL_CONTENTS(&circuitpy->fatfs, "/saves/placeholder.txt", + MAKE_FILE_WITH_OPTIONAL_CONTENTS(&_circuitpy_mount, "/saves/placeholder.txt", "A separate filesystem mounted at /saves will hide this file from Python." " Saves are visible via USB CPSAVES.\n"); } #endif #endif - #if CIRCUITPY_OS_GETENV - make_empty_file(&circuitpy->fatfs, "/settings.toml"); + #if CIRCUITPY_SETTINGS_TOML + make_empty_file(&_circuitpy_mount, "/settings.toml"); #endif // make a sample code.py file - MAKE_FILE_WITH_OPTIONAL_CONTENTS(&circuitpy->fatfs, "/code.py", "print(\"Hello World!\")\n"); + MAKE_FILE_WITH_OPTIONAL_CONTENTS(&_circuitpy_mount, "/code.py", "print(\"Hello World!\")\n"); // create empty lib directory res = f_mkdir(&circuitpy->fatfs, "/lib"); @@ -186,12 +440,20 @@ bool filesystem_init(bool create_allowed, bool force_create) { } else if (res != FR_OK) { return false; } + #endif // CIRCUITPY_FILESYSTEM_LITTLEFS circuitpy_vfs->str = "/"; circuitpy_vfs->len = 1; circuitpy_vfs->obj = MP_OBJ_FROM_PTR(circuitpy); circuitpy_vfs->next = NULL; + #if CIRCUITPY_STORAGE_EXTEND + // The volume is mounted, so settle whether the drive spans the next-update partition before + // the mount is published. Nothing can query the block count until the mount table points at + // this filesystem, so every reader sees the same value. + supervisor_flash_update_extended(); + #endif + MP_STATE_VM(vfs_mount_table) = circuitpy_vfs; #if CIRCUITPY_SAVES_PARTITION_SIZE > 0 @@ -210,8 +472,24 @@ bool filesystem_init(bool create_allowed, bool force_create) { // It is set to the internal flash filesystem by default. MP_STATE_PORT(vfs_cur) = circuitpy_vfs; - #if CIRCUITPY_STORAGE_EXTEND - supervisor_flash_update_extended(); + #if CIRCUITPY_SDCARDIO + sdcardio_init(); + #if defined(DEFAULT_SD_CARD_DETECT) && CIRCUITPY_SDCARD_USB + // Mount the SD card now so it's ready when USB enumerates. + // Lazy mount from tud_msc_test_unit_ready_cb can lose races with + // macOS's probe timing. Gated on CIRCUITPY_SDCARD_USB to match the + // existing call site in usb_msc_flash.c (guarded by SDCARD_LUN). + // automount_sd_card() itself honors the runtime CIRCUITPY_SDCARD_USB + // setting and is a no-op when it is disabled. + automount_sd_card(); + #endif + #endif + + // Same reason as the SD card above, mount it before USB enumerates rather than + // lazily from tud_msc_test_unit_ready_cb(). Also the same requirement + // that settings.toml is readable. + #if CIRCUITPY_EMMC_USB + automount_emmc(); #endif return true; @@ -226,38 +504,46 @@ void PLACE_IN_ITCM(filesystem_flush)(void) { } void filesystem_set_internal_writable_by_usb(bool writable) { - fs_user_mount_t *vfs = &_circuitpy_usermount; - - filesystem_set_writable_by_usb(vfs, writable); + filesystem_set_writable_by_usb(&_circuitpy_mount, writable); } -void filesystem_set_writable_by_usb(fs_user_mount_t *vfs, bool usb_writable) { +void filesystem_set_writable_by_usb(supervisor_vfs_t *vfs, bool usb_writable) { if (usb_writable) { - vfs->blockdev.flags |= MP_BLOCKDEV_FLAG_USB_WRITABLE; + vfs->common.blockdev.flags |= MP_BLOCKDEV_FLAG_USB_WRITABLE; } else { - vfs->blockdev.flags &= ~MP_BLOCKDEV_FLAG_USB_WRITABLE; + vfs->common.blockdev.flags &= ~MP_BLOCKDEV_FLAG_USB_WRITABLE; } } -bool filesystem_is_writable_by_python(fs_user_mount_t *vfs) { - return (vfs->blockdev.flags & MP_BLOCKDEV_FLAG_CONCURRENT_WRITE_PROTECTED) == 0 || - (vfs->blockdev.flags & MP_BLOCKDEV_FLAG_USB_WRITABLE) == 0; +bool filesystem_is_writable_by_python(supervisor_vfs_t *vfs) { + return ((vfs->common.blockdev.flags & MP_BLOCKDEV_FLAG_CONCURRENT_WRITE_PROTECTED) == 0) || + ((vfs->common.blockdev.flags & MP_BLOCKDEV_FLAG_USB_WRITABLE) == 0) || + ((vfs->common.blockdev.flags & MP_BLOCKDEV_FLAG_IGNORE_WRITE_PROTECTION) != 0); } bool filesystem_is_writable_by_usb(fs_user_mount_t *vfs) { - return (vfs->blockdev.flags & MP_BLOCKDEV_FLAG_CONCURRENT_WRITE_PROTECTED) == 0 || - (vfs->blockdev.flags & MP_BLOCKDEV_FLAG_USB_WRITABLE) != 0; + return ((vfs->blockdev.flags & MP_BLOCKDEV_FLAG_CONCURRENT_WRITE_PROTECTED) == 0) || + ((vfs->blockdev.flags & MP_BLOCKDEV_FLAG_USB_WRITABLE) != 0) || + ((vfs->blockdev.flags & MP_BLOCKDEV_FLAG_IGNORE_WRITE_PROTECTION) != 0); } void filesystem_set_internal_concurrent_write_protection(bool concurrent_write_protection) { - filesystem_set_concurrent_write_protection(&_circuitpy_usermount, concurrent_write_protection); + filesystem_set_concurrent_write_protection(&_circuitpy_mount, concurrent_write_protection); } -void filesystem_set_concurrent_write_protection(fs_user_mount_t *vfs, bool concurrent_write_protection) { +void filesystem_set_concurrent_write_protection(supervisor_vfs_t *vfs, bool concurrent_write_protection) { if (concurrent_write_protection) { - vfs->blockdev.flags |= MP_BLOCKDEV_FLAG_CONCURRENT_WRITE_PROTECTED; + vfs->common.blockdev.flags |= MP_BLOCKDEV_FLAG_CONCURRENT_WRITE_PROTECTED; + } else { + vfs->common.blockdev.flags &= ~MP_BLOCKDEV_FLAG_CONCURRENT_WRITE_PROTECTED; + } +} + +void filesystem_set_ignore_write_protection(fs_user_mount_t *vfs, bool ignore_write_protection) { + if (ignore_write_protection) { + vfs->blockdev.flags |= MP_BLOCKDEV_FLAG_IGNORE_WRITE_PROTECTION; } else { - vfs->blockdev.flags &= ~MP_BLOCKDEV_FLAG_CONCURRENT_WRITE_PROTECTED; + vfs->blockdev.flags &= ~MP_BLOCKDEV_FLAG_IGNORE_WRITE_PROTECTION; } } @@ -265,62 +551,655 @@ bool filesystem_present(void) { return _circuitpy_vfs.len > 0; } -fs_user_mount_t *filesystem_circuitpy(void) { +supervisor_vfs_t *filesystem_circuitpy(void) { if (!filesystem_present()) { return NULL; } - return &_circuitpy_usermount; + return &_circuitpy_mount; } -fs_user_mount_t *filesystem_for_path(const char *path_in, const char **path_under_mount) { +supervisor_vfs_t *filesystem_for_path(const char *path_in, const char **path_under_mount) { mp_vfs_mount_t *vfs = mp_vfs_lookup_path(path_in, path_under_mount); if (vfs == MP_VFS_NONE) { return NULL; } - fs_user_mount_t *fs_mount; + supervisor_vfs_t *fs_mount; *path_under_mount = path_in; if (vfs == MP_VFS_ROOT) { fs_mount = filesystem_circuitpy(); } else { - fs_mount = MP_OBJ_TO_PTR(vfs->obj); + fs_mount = (supervisor_vfs_t *)MP_OBJ_TO_PTR(vfs->obj); // Check if the vfs name is one character long: it must be "/" in that case. // If so don't remove the mount point name. We must use an absolute path // because otherwise the path will be adjusted by os.getcwd() when it's looked up. if (strlen(vfs->str) != 1) { // Remove the mount point directory name, such as "/sd". - path_under_mount += strlen(vfs->str); + *path_under_mount += strlen(vfs->str); } } return fs_mount; } -bool filesystem_native_fatfs(fs_user_mount_t *fs_mount) { - return fs_mount->base.type == &mp_fat_vfs_type && (fs_mount->blockdev.flags & MP_BLOCKDEV_FLAG_NATIVE) != 0; +static bool filesystem_native_fatfs(supervisor_vfs_t *fs_mount) { + return fs_mount->common.base.type == &mp_fat_vfs_type && + (fs_mount->common.blockdev.flags & MP_BLOCKDEV_FLAG_NATIVE) != 0; } -bool filesystem_lock(fs_user_mount_t *fs_mount) { - if (fs_mount->lock_count == 0 && !blockdev_lock(fs_mount)) { +bool filesystem_lock(supervisor_vfs_t *fs_mount) { + #if CIRCUITPY_FILESYSTEM_LITTLEFS + if (fs_mount->common.base.type != &mp_fat_vfs_type) { + // littlefs mounts are never exposed through USB MSC, so there is no + // STA_PROTECT to bypass and no lock_count to track. The blockdev lock + // alone excludes other writers. + return blockdev_lock(fs_mount); + } + #endif + if (fs_mount->fat.lock_count == 0 && !blockdev_lock(fs_mount)) { return false; } - fs_mount->lock_count += 1; + fs_mount->fat.lock_count += 1; + // While a non-USB-MSC writer (BLE file transfer, web + // workflow, storage.remount) holds the filesystem lock, allow the + // FatFS f_open(FA_WRITE) path to bypass STA_PROTECT. Without this, the + // disk_ioctl(IOCTL_STATUS) -> filesystem_is_writable_by_python() check + // added by #10659 always sets STA_PROTECT on USB-device-capable boards, + // so even after the lock is held, f_open returns FR_WRITE_PROTECTED. + // USB MSC takes the lock via blockdev_lock() directly, NOT via + // filesystem_lock(), so this flag is never set on its behalf. + fs_mount->common.blockdev.flags |= MP_BLOCKDEV_FLAG_IGNORE_WRITE_PROTECTION; return true; } -void filesystem_unlock(fs_user_mount_t *fs_mount) { - fs_mount->lock_count -= 1; - if (fs_mount->lock_count == 0) { +void filesystem_unlock(supervisor_vfs_t *fs_mount) { + #if CIRCUITPY_FILESYSTEM_LITTLEFS + if (fs_mount->common.base.type != &mp_fat_vfs_type) { + blockdev_unlock(fs_mount); + return; + } + #endif + fs_mount->fat.lock_count -= 1; + if (fs_mount->fat.lock_count == 0) { + // Clear the bypass when releasing the lock. + fs_mount->common.blockdev.flags &= ~MP_BLOCKDEV_FLAG_IGNORE_WRITE_PROTECTION; blockdev_unlock(fs_mount); } } -bool blockdev_lock(fs_user_mount_t *fs_mount) { - if ((fs_mount->blockdev.flags & MP_BLOCKDEV_FLAG_LOCKED) != 0) { +bool blockdev_lock(supervisor_vfs_t *fs_mount) { + if ((fs_mount->common.blockdev.flags & MP_BLOCKDEV_FLAG_LOCKED) != 0) { return false; } - fs_mount->blockdev.flags |= MP_BLOCKDEV_FLAG_LOCKED; + fs_mount->common.blockdev.flags |= MP_BLOCKDEV_FLAG_LOCKED; return true; } -void blockdev_unlock(fs_user_mount_t *fs_mount) { - fs_mount->blockdev.flags &= ~MP_BLOCKDEV_FLAG_LOCKED; +void blockdev_unlock(supervisor_vfs_t *fs_mount) { + fs_mount->common.blockdev.flags &= ~MP_BLOCKDEV_FLAG_LOCKED; +} + +// Supervisor-level file, directory and filesystem helpers shared between FAT +// and littlefs mounts. All of them take or return supervisor_fs_err_t; paths +// are relative to the given mount. See supervisor/filesystem.h for details. + +bool supervisor_vfs_supported(supervisor_vfs_t *vfs) { + #if CIRCUITPY_FILESYSTEM_LITTLEFS + if (is_lfs(vfs)) { + return true; + } + #endif + return filesystem_native_fatfs(vfs); +} + +#if CIRCUITPY_STORAGE_MAP_FILE +// The running program uses the file's flash bytes (storage.map_file() or an in-place .mpy +// import). Stop it, so the workflow can try again once it is gone. The REPL can't be stopped +// while it waits for input, so there the write just fails. +MP_NOINLINE static supervisor_fs_err_t mapped_file_error(void) { + if (autoreload_is_suspended(AUTORELOAD_SUSPEND_REPL)) { + return fat_error(FR_WRITE_PROTECTED); + } + reload_initiate(RUN_REASON_AUTO_RELOAD); + return fat_error(FR_LOCKED); +} +#endif + +supervisor_fs_err_t supervisor_vfs_open_file(supervisor_vfs_t *vfs, const char *path, uint32_t flags, + uint64_t mtime_ns, supervisor_vfs_file_t *file) { + if (vfs == NULL) { + return SUPERVISOR_FS_NO_FILE; + } + // Only open needs clearing up front; every other field is set on a + // successful open and callers must check the result before using file. + file->open = false; + file->fattime = 0; + #if CIRCUITPY_FILESYSTEM_LITTLEFS + file->vfs = vfs; + if (is_lfs(vfs)) { + struct lfs2_file_config *cfg = &file->file.lfs.cfg; + memset(cfg, 0, sizeof(*cfg)); + cfg->buffer = file->file.lfs.buffer; + // Modification time attribute, committed when a modified file is + // closed. littlefs writes file attributes at close. + if (mtime_ns == 0) { + // No timestamp was requested. Use the same RTC-based time that FAT + // stamps files with via get_fattime(). + mtime_ns = get_fattime_ns(); + } + lfs_mtime_store(file->file.lfs.mtime, mtime_ns); + struct lfs2_attr *attr = &file->file.lfs.attr; + attr->type = LFS_ATTR_MTIME; + attr->buffer = file->file.lfs.mtime; + attr->size = sizeof(file->file.lfs.mtime); + cfg->attrs = attr; + cfg->attr_count = 1; + int lfs_flags; + if ((flags & SUPERVISOR_FS_OPEN_WRITE) != 0) { + lfs_flags = LFS2_O_WRONLY; + } else { + lfs_flags = LFS2_O_RDONLY; + } + if ((flags & SUPERVISOR_FS_OPEN_CREATE) != 0) { + lfs_flags |= LFS2_O_CREAT; + } + if ((flags & SUPERVISOR_FS_OPEN_TRUNCATE) != 0) { + lfs_flags |= LFS2_O_TRUNC; + } + int err = lfs2_file_opencfg(&vfs->lfs2.lfs, &file->file.lfs.lfs2, path, lfs_flags, cfg); + if (err < 0) { + return lfs_error(err); + } + file->open = true; + file->lfs = true; + return SUPERVISOR_FS_OK; + } + #endif + // On FAT-only builds there are no littlefs mounts, and + // every caller has already vetted the mount through + // supervisor_vfs_supported(), so skip the extra checks to keep these + // wrappers as small as plain FatFS calls. + #if CIRCUITPY_FILESYSTEM_LITTLEFS + if (!filesystem_native_fatfs(vfs)) { + return SUPERVISOR_FS_IO; + } + #endif + #if CIRCUITPY_STORAGE_MAP_FILE + if ((flags & SUPERVISOR_FS_OPEN_WRITE) != 0 && storage_map_file_in_use(&vfs->fat, path)) { + return mapped_file_error(); + } + #endif + DWORD fattime = mtime_ns != 0 ? fattime_from_ns(mtime_ns) : 0; + if (fattime != 0) { + // FatFS stamps files when they're closed, so remember the timestamp + // and apply it again in supervisor_vfs_close_file(). + override_fattime(fattime); + } + BYTE fa = 0; + if ((flags & SUPERVISOR_FS_OPEN_READ) != 0) { + fa |= FA_READ; + } + if ((flags & SUPERVISOR_FS_OPEN_WRITE) != 0) { + fa |= FA_WRITE; + } + if ((flags & SUPERVISOR_FS_OPEN_TRUNCATE) != 0) { + fa |= FA_CREATE_ALWAYS; + } else if ((flags & SUPERVISOR_FS_OPEN_CREATE) != 0) { + fa |= FA_OPEN_ALWAYS; + } + FRESULT res = f_open(&vfs->fat.fatfs, &file->file.fat, path, fa); + if (fattime != 0) { + override_fattime(0); + } + if (res != FR_OK) { + return fat_error(res); + } + file->open = true; + #if CIRCUITPY_FILESYSTEM_LITTLEFS + file->lfs = false; + #endif + file->fattime = fattime; + return SUPERVISOR_FS_OK; +} + +supervisor_fs_err_t supervisor_vfs_close_file(supervisor_vfs_file_t *file) { + if (!file->open) { + return SUPERVISOR_FS_OK; + } + file->open = false; + #if CIRCUITPY_FILESYSTEM_LITTLEFS + if (file->lfs) { + // The mtime attribute filled in at open is written out here for a + // modified file. + int err = lfs2_file_close(&file->vfs->lfs2.lfs, &file->file.lfs.lfs2); + return err < 0 ? lfs_error(err) : SUPERVISOR_FS_OK; + } + #endif + if (file->fattime != 0) { + override_fattime(file->fattime); + } + FRESULT res = f_close(&file->file.fat); + if (file->fattime != 0) { + override_fattime(0); + } + return fat_error(res); +} + +supervisor_fs_err_t supervisor_vfs_read_file(supervisor_vfs_file_t *file, void *buf, size_t len, size_t *bytes_read) { + *bytes_read = 0; + if (!file->open) { + return SUPERVISOR_FS_IO; + } + #if CIRCUITPY_FILESYSTEM_LITTLEFS + if (file->lfs) { + lfs2_ssize_t read = lfs2_file_read(&file->vfs->lfs2.lfs, &file->file.lfs.lfs2, buf, len); + if (read < 0) { + return lfs_error(read); + } + *bytes_read = read; + return SUPERVISOR_FS_OK; + } + #endif + UINT read; + FRESULT res = f_read(&file->file.fat, buf, len, &read); + *bytes_read = read; + return fat_error(res); +} + +supervisor_fs_err_t supervisor_vfs_write_file(supervisor_vfs_file_t *file, const void *buf, size_t len, size_t *bytes_written) { + *bytes_written = 0; + if (!file->open) { + return SUPERVISOR_FS_IO; + } + #if CIRCUITPY_FILESYSTEM_LITTLEFS + if (file->lfs) { + lfs2_ssize_t written = lfs2_file_write(&file->vfs->lfs2.lfs, &file->file.lfs.lfs2, buf, len); + if (written < 0) { + return lfs_error(written); + } + *bytes_written = written; + return SUPERVISOR_FS_OK; + } + #endif + UINT written; + FRESULT res = f_write(&file->file.fat, buf, len, &written); + *bytes_written = written; + return fat_error(res); +} + +supervisor_fs_err_t supervisor_vfs_seek_file(supervisor_vfs_file_t *file, size_t offset) { + if (!file->open) { + return SUPERVISOR_FS_IO; + } + #if CIRCUITPY_FILESYSTEM_LITTLEFS + if (file->lfs) { + lfs2_soff_t result = lfs2_file_seek(&file->vfs->lfs2.lfs, &file->file.lfs.lfs2, offset, LFS2_SEEK_SET); + return result < 0 ? lfs_error(result) : SUPERVISOR_FS_OK; + } + #endif + return fat_error(f_lseek(&file->file.fat, offset)); +} + +size_t supervisor_vfs_tell_file(supervisor_vfs_file_t *file) { + if (!file->open) { + return 0; + } + #if CIRCUITPY_FILESYSTEM_LITTLEFS + if (file->lfs) { + return lfs2_file_tell(&file->vfs->lfs2.lfs, &file->file.lfs.lfs2); + } + #endif + return f_tell(&file->file.fat); +} + +size_t supervisor_vfs_file_size(supervisor_vfs_file_t *file) { + if (!file->open) { + return 0; + } + #if CIRCUITPY_FILESYSTEM_LITTLEFS + if (file->lfs) { + return lfs2_file_size(&file->vfs->lfs2.lfs, &file->file.lfs.lfs2); + } + #endif + return f_size(&file->file.fat); +} + +supervisor_fs_err_t supervisor_vfs_truncate_file(supervisor_vfs_file_t *file) { + if (!file->open) { + return SUPERVISOR_FS_IO; + } + #if CIRCUITPY_FILESYSTEM_LITTLEFS + if (file->lfs) { + int err = lfs2_file_truncate(&file->vfs->lfs2.lfs, &file->file.lfs.lfs2, + lfs2_file_tell(&file->vfs->lfs2.lfs, &file->file.lfs.lfs2)); + return err < 0 ? lfs_error(err) : SUPERVISOR_FS_OK; + } + #endif + return fat_error(f_truncate(&file->file.fat)); +} + +supervisor_fs_err_t supervisor_vfs_stat(supervisor_vfs_t *vfs, const char *path, bool *is_dir, size_t *size, uint64_t *mtime_ns) { + if (is_dir != NULL) { + *is_dir = false; + } + if (size != NULL) { + *size = 0; + } + if (mtime_ns != NULL) { + *mtime_ns = 0; + } + #if CIRCUITPY_FILESYSTEM_LITTLEFS + if (is_lfs(vfs)) { + struct lfs2_info info; + int err = lfs2_stat(&vfs->lfs2.lfs, path, &info); + if (err < 0) { + return lfs_error(err); + } + bool directory = info.type == LFS2_TYPE_DIR; + if (is_dir != NULL) { + *is_dir = directory; + } + if (size != NULL && !directory) { + *size = info.size; + } + if (mtime_ns != NULL) { + *mtime_ns = lfs_get_path_mtime(&vfs->lfs2.lfs, path); + } + return SUPERVISOR_FS_OK; + } + #endif + FILINFO file_info; + FRESULT res = f_stat(&vfs->fat.fatfs, path, &file_info); + if (res != FR_OK) { + return fat_error(res); + } + bool directory = (file_info.fattrib & AM_DIR) != 0; + if (is_dir != NULL) { + *is_dir = directory; + } + if (size != NULL && !directory) { + *size = file_info.fsize; + } + if (mtime_ns != NULL) { + *mtime_ns = (uint64_t)timeutils_mktime_1970(1980 + (file_info.fdate >> 9), + (file_info.fdate >> 5) & 0xf, + file_info.fdate & 0x1f, + file_info.ftime >> 11, + (file_info.ftime >> 5) & 0x3f, + (file_info.ftime & 0x1f) * 2) * 1000000000ULL; + } + return SUPERVISOR_FS_OK; +} + +supervisor_fs_err_t supervisor_vfs_mkdir(supervisor_vfs_t *vfs, const char *path, uint64_t mtime_ns) { + #if CIRCUITPY_FILESYSTEM_LITTLEFS + if (is_lfs(vfs)) { + int err = lfs2_mkdir(&vfs->lfs2.lfs, path); + return err < 0 ? lfs_error(err) : SUPERVISOR_FS_OK; + } + #endif + // See supervisor_vfs_open_file() for why this check is littlefs-only. + #if CIRCUITPY_FILESYSTEM_LITTLEFS + if (!filesystem_native_fatfs(vfs)) { + return SUPERVISOR_FS_IO; + } + #endif + DWORD fattime = mtime_ns != 0 ? fattime_from_ns(mtime_ns) : 0; + if (fattime != 0) { + override_fattime(fattime); + } + FRESULT res = f_mkdir(&vfs->fat.fatfs, path); + if (fattime != 0) { + override_fattime(0); + } + return fat_error(res); +} + +supervisor_fs_err_t supervisor_vfs_rename(supervisor_vfs_t *vfs, const char *old_path, const char *new_path) { + #if CIRCUITPY_FILESYSTEM_LITTLEFS + if (is_lfs(vfs)) { + int err = lfs2_rename(&vfs->lfs2.lfs, old_path, new_path); + return err < 0 ? lfs_error(err) : SUPERVISOR_FS_OK; + } + #endif + // See supervisor_vfs_open_file() for why this check is littlefs-only. + #if CIRCUITPY_FILESYSTEM_LITTLEFS + if (!filesystem_native_fatfs(vfs)) { + return SUPERVISOR_FS_IO; + } + #endif + return fat_error(f_rename(&vfs->fat.fatfs, old_path, new_path)); +} + +supervisor_fs_err_t supervisor_vfs_unlink(supervisor_vfs_t *vfs, const char *path) { + #if CIRCUITPY_FILESYSTEM_LITTLEFS + if (is_lfs(vfs)) { + int err = lfs2_remove(&vfs->lfs2.lfs, path); + return err < 0 ? lfs_error(err) : SUPERVISOR_FS_OK; + } + #endif + // See supervisor_vfs_open_file() for why this check is littlefs-only. + #if CIRCUITPY_FILESYSTEM_LITTLEFS + if (!filesystem_native_fatfs(vfs)) { + return SUPERVISOR_FS_IO; + } + #endif + #if CIRCUITPY_STORAGE_MAP_FILE + if (storage_map_file_in_use(&vfs->fat, path)) { + return mapped_file_error(); // its clusters would be reused while in use + } + #endif + return fat_error(f_unlink(&vfs->fat.fatfs, path)); +} + +supervisor_fs_err_t supervisor_vfs_opendir(supervisor_vfs_t *vfs, const char *path, supervisor_vfs_dir_t *dir) { + // Only open needs clearing up front; the rest of dir is initialized by + // f_opendir/lfs2_dir_open on success and callers must check the result + // before using dir. + dir->open = false; + #if CIRCUITPY_FILESYSTEM_LITTLEFS + dir->vfs = vfs; + if (is_lfs(vfs)) { + int err = lfs2_dir_open(&vfs->lfs2.lfs, &dir->dir.lfs2, path); + if (err < 0) { + return lfs_error(err); + } + dir->open = true; + dir->lfs = true; + // Store the path (without a trailing slash) for per-entry mtime + // lookups. If it doesn't fit, mtimes will simply read as 0. + size_t len = strlen(path); + while (len > 0 && path[len - 1] == '/') { + len--; + } + if (len > sizeof(dir->path) - 1) { + len = sizeof(dir->path) - 1; + } + memcpy(dir->path, path, len); + dir->path[len] = '\0'; + return SUPERVISOR_FS_OK; + } + #endif + // See supervisor_vfs_open_file() for why this check is littlefs-only. + #if CIRCUITPY_FILESYSTEM_LITTLEFS + if (!filesystem_native_fatfs(vfs)) { + return SUPERVISOR_FS_IO; + } + #endif + FRESULT res = f_opendir(&vfs->fat.fatfs, &dir->dir.fat, path); + if (res != FR_OK) { + return fat_error(res); + } + dir->open = true; + #if CIRCUITPY_FILESYSTEM_LITTLEFS + dir->lfs = false; + #endif + return SUPERVISOR_FS_OK; +} + +supervisor_fs_err_t supervisor_vfs_readdir(supervisor_vfs_dir_t *dir, char *name, size_t name_len, bool *is_dir, size_t *size, uint64_t *mtime_ns) { + if (is_dir != NULL) { + *is_dir = false; + } + if (size != NULL) { + *size = 0; + } + if (mtime_ns != NULL) { + *mtime_ns = 0; + } + if (!dir->open) { + return SUPERVISOR_FS_IO; + } + #if CIRCUITPY_FILESYSTEM_LITTLEFS + if (dir->lfs) { + struct lfs2_info info; + int res; + do { + res = lfs2_dir_read(&dir->vfs->lfs2.lfs, &dir->dir.lfs2, &info); + if (res < 0) { + return lfs_error(res); + } + if (res == 0) { + // End of the directory. + name[0] = '\0'; + return SUPERVISOR_FS_OK; + } + // littlefs lists the "." and ".." entries; FatFS doesn't, so skip + // them for parity. + } while (info.name[0] == '.' && + (info.name[1] == '\0' || (info.name[1] == '.' && info.name[2] == '\0'))); + size_t name_chars = strlen(info.name); + if (name_chars > name_len - 1) { + name_chars = name_len - 1; + } + memcpy(name, info.name, name_chars); + name[name_chars] = '\0'; + bool directory = info.type == LFS2_TYPE_DIR; + if (is_dir != NULL) { + *is_dir = directory; + } + if (size != NULL && !directory) { + *size = info.size; + } + if (mtime_ns != NULL && !directory) { + // littlefs keeps modification times as per-path attributes, so + // build the entry's full path. The stored directory path is + // temporarily extended to hold the entry name. + size_t len = strlen(dir->path); + if (len + 1 + name_chars + 1 <= sizeof(dir->path)) { + dir->path[len] = '/'; + memcpy(dir->path + len + 1, info.name, name_chars); + dir->path[len + 1 + name_chars] = '\0'; + *mtime_ns = lfs_get_path_mtime(&dir->vfs->lfs2.lfs, dir->path); + dir->path[len] = '\0'; + } + } + return SUPERVISOR_FS_OK; + } + #endif + FILINFO file_info; + FRESULT res = f_readdir(&dir->dir.fat, &file_info); + if (res != FR_OK) { + return fat_error(res); + } + if (file_info.fname[0] == '\0') { + // End of the directory. + name[0] = '\0'; + return SUPERVISOR_FS_OK; + } + size_t name_chars = strlen(file_info.fname); + if (name_chars > name_len - 1) { + name_chars = name_len - 1; + } + memcpy(name, file_info.fname, name_chars); + name[name_chars] = '\0'; + bool directory = (file_info.fattrib & AM_DIR) != 0; + if (is_dir != NULL) { + *is_dir = directory; + } + if (size != NULL && !directory) { + *size = file_info.fsize; + } + if (mtime_ns != NULL) { + *mtime_ns = (uint64_t)timeutils_mktime_1970(1980 + (file_info.fdate >> 9), + (file_info.fdate >> 5) & 0xf, + file_info.fdate & 0x1f, + file_info.ftime >> 11, + (file_info.ftime >> 5) & 0x3f, + (file_info.ftime & 0x1f) * 2) * 1000000000ULL; + } + return SUPERVISOR_FS_OK; +} + +supervisor_fs_err_t supervisor_vfs_rewinddir(supervisor_vfs_dir_t *dir) { + if (!dir->open) { + return SUPERVISOR_FS_IO; + } + #if CIRCUITPY_FILESYSTEM_LITTLEFS + if (dir->lfs) { + int err = lfs2_dir_rewind(&dir->vfs->lfs2.lfs, &dir->dir.lfs2); + return err < 0 ? lfs_error(err) : SUPERVISOR_FS_OK; + } + #endif + f_readdir(&dir->dir.fat, NULL); + return SUPERVISOR_FS_OK; +} + +supervisor_fs_err_t supervisor_vfs_closedir(supervisor_vfs_dir_t *dir) { + if (!dir->open) { + return SUPERVISOR_FS_OK; + } + dir->open = false; + #if CIRCUITPY_FILESYSTEM_LITTLEFS + if (dir->lfs) { + int err = lfs2_dir_close(&dir->vfs->lfs2.lfs, &dir->dir.lfs2); + return err < 0 ? lfs_error(err) : SUPERVISOR_FS_OK; + } + #endif + return fat_error(f_closedir(&dir->dir.fat)); +} + +supervisor_fs_err_t supervisor_vfs_statfs(supervisor_vfs_t *vfs, size_t *block_size, size_t *total_blocks, size_t *free_blocks) { + #if CIRCUITPY_FILESYSTEM_LITTLEFS + if (is_lfs(vfs)) { + struct lfs2_config *config = &vfs->lfs2.config; + if (block_size != NULL) { + *block_size = config->block_size; + } + if (total_blocks != NULL) { + *total_blocks = config->block_count; + } + if (free_blocks != NULL) { + lfs2_ssize_t used = lfs2_fs_size(&vfs->lfs2.lfs); + *free_blocks = used < 0 ? 0 : config->block_count - used; + } + return SUPERVISOR_FS_OK; + } + #endif + // See supervisor_vfs_open_file() for why this check is littlefs-only. + #if CIRCUITPY_FILESYSTEM_LITTLEFS + if (!filesystem_native_fatfs(vfs)) { + return SUPERVISOR_FS_IO; + } + #endif + FATFS *fatfs = &vfs->fat.fatfs; + DWORD free_clusters = 0; + FRESULT res = f_getfree(fatfs, &free_clusters); + if (res != FR_OK) { + return fat_error(res); + } + size_t ssize; + #if FF_MAX_SS != FF_MIN_SS + ssize = fatfs->ssize; + #else + ssize = FF_MIN_SS; + #endif + if (block_size != NULL) { + *block_size = fatfs->csize * ssize; + } + if (total_blocks != NULL) { + *total_blocks = fatfs->n_fatent - 2; + } + if (free_blocks != NULL) { + *free_blocks = free_clusters; + } + return SUPERVISOR_FS_OK; } diff --git a/supervisor/shared/flash.c b/supervisor/shared/flash.c index ccb60efe321..ef7c32aadd9 100644 --- a/supervisor/shared/flash.c +++ b/supervisor/shared/flash.c @@ -149,7 +149,26 @@ static mp_uint_t flash_read_blocks(mp_obj_t self_in, uint8_t *dest, uint32_t blo return supervisor_flash_read_blocks(dest, block_num, num_blocks); } +#if CIRCUITPY_STORAGE_MAP_FILE +// The sector -> block translation of flash_read_blocks(); FatFs has already validated the +// cluster chain, so every sector it hands over lies inside the volume. +const uint8_t *supervisor_flash_xip_address(uint32_t fatfs_sector, uint32_t *contiguous) { + uint32_t block = fatfs_sector - PART1_START_BLOCK; + #if CIRCUITPY_SAVES_PARTITION_SIZE > 0 + block += CIRCUITPY_SAVES_PARTITION_SIZE / FILESYSTEM_BLOCK_SIZE; + #endif + return port_internal_flash_xip_address(block, contiguous); +} +#endif + static volatile bool filesystem_dirty = false; +void supervisor_flash_mark_dirty(void) { + if (!filesystem_dirty) { + // Turn on ticks so that we can flush after a period of time elapses. + supervisor_enable_tick(); + filesystem_dirty = true; + } +} static mp_uint_t flash_write_blocks(mp_obj_t self_in, const uint8_t *src, uint32_t block_num, uint32_t num_blocks) { if (block_num == 0) { @@ -159,31 +178,31 @@ static mp_uint_t flash_write_blocks(mp_obj_t self_in, const uint8_t *src, uint32 // can't write MBR, but pretend we did return 0; } else { - if (!filesystem_dirty) { - // Turn on ticks so that we can flush after a period of time elapses. - supervisor_enable_tick(); - filesystem_dirty = true; - } block_num -= PART1_START_BLOCK; #if CIRCUITPY_SAVES_PARTITION_SIZE > 0 mp_vfs_blockdev_t *self = (mp_vfs_blockdev_t *)self_in; block_num += self->offset / self->block_size; #endif - return supervisor_flash_write_blocks(src, block_num, num_blocks); + mp_uint_t result = supervisor_flash_write_blocks(src, block_num, num_blocks); + // Mark dirty after the write, so a flush running in another thread + // can't clear the flag between marking and caching the block. + supervisor_flash_mark_dirty(); + return result; } } void PLACE_IN_ITCM(supervisor_flash_flush)(void) { + // Clear the flag before flushing. A write that lands during the flush + // marks the filesystem dirty again and turns the tick back on. + if (filesystem_dirty) { + filesystem_dirty = false; + supervisor_disable_tick(); + } #if INTERNAL_FLASH_FILESYSTEM port_internal_flash_flush(); #else supervisor_external_flash_flush(); #endif - // Turn off ticks now that our filesystem has been flushed. - if (filesystem_dirty) { - supervisor_disable_tick(); - } - filesystem_dirty = false; } static mp_obj_t supervisor_flash_obj_readblocks(mp_obj_t self, mp_obj_t block_num, mp_obj_t buf) { diff --git a/supervisor/shared/internal_flash.h b/supervisor/shared/internal_flash.h index 139e86cf49b..df3d2e9f6dd 100644 --- a/supervisor/shared/internal_flash.h +++ b/supervisor/shared/internal_flash.h @@ -8,3 +8,10 @@ #include "supervisor/internal_flash.h" // This is per-port. void port_internal_flash_flush(void); + +#if CIRCUITPY_STORAGE_MAP_FILE +// The memory-mapped address of a drive block, NULL if the port cannot map it; *contiguous +// receives how many blocks from it are contiguous in the mapping. A port that sets +// CIRCUITPY_STORAGE_MAP_FILE implements this. +const uint8_t *port_internal_flash_xip_address(uint32_t block, uint32_t *contiguous); +#endif diff --git a/supervisor/shared/network.c b/supervisor/shared/network.c new file mode 100644 index 00000000000..9a97aae3def --- /dev/null +++ b/supervisor/shared/network.c @@ -0,0 +1,30 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Dan Halbert for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include +#include + +#include "py/misc.h" +#include "supervisor/shared/network.h" + +// Bytes used by everything except the board part: "cpy-", "-", 12 hex digits, +// and the NUL. +#define DEFAULT_HOSTNAME_OVERHEAD (4 + 1 + 12 + 1) + +size_t network_format_default_hostname(char *buf, size_t buf_size, const uint8_t mac[6]) { + const size_t board_id_len = strlen(CIRCUITPY_BOARD_ID); + size_t board_len = MIN(buf_size - DEFAULT_HOSTNAME_OVERHEAD, board_id_len); + size_t board_trim = board_id_len - board_len; + // If trimming leaves a leading "_", drop it too, so the name doesn't start + // with "cpy-_". + if (CIRCUITPY_BOARD_ID[board_trim] == '_') { + board_trim++; + } + int len = snprintf(buf, buf_size, "cpy-%s-%02x%02x%02x%02x%02x%02x", + CIRCUITPY_BOARD_ID + board_trim, + mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); + return len < 0 ? 0 : (size_t)len; +} diff --git a/supervisor/shared/network.h b/supervisor/shared/network.h new file mode 100644 index 00000000000..17f8607359b --- /dev/null +++ b/supervisor/shared/network.h @@ -0,0 +1,23 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Dan Halbert for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include +#include + +// Formats the default network hostname, "cpy--", into buf. +// +// is CIRCUITPY_BOARD_ID, with its start trimmed off so the result fits +// in buf_size bytes, including the terminating NUL. The start is usually the +// manufacturer, so the end is more likely to distinguish the board. is +// the six bytes of mac as lowercase hex. +// +// buf_size must be at least 18, the length of "cpy--", 12 hex digits, and the +// NUL. Always writes a NUL-terminated string to buf. Never allocates or raises. +// +// Returns the length of the string, not counting the NUL. +size_t network_format_default_hostname(char *buf, size_t buf_size, const uint8_t mac[6]); diff --git a/supervisor/shared/port.c b/supervisor/shared/port.c index 72bb45b8a27..757c03b2d39 100644 --- a/supervisor/shared/port.c +++ b/supervisor/shared/port.c @@ -8,19 +8,33 @@ #include +#include "py/mphal.h" #include "py/runtime.h" +#include "py/gc.h" #include "lib/tlsf/tlsf.h" +#ifdef CIRCUITPY_BOOT_BUTTON +#include "shared-bindings/digitalio/DigitalInOut.h" +#include "shared-bindings/time/__init__.h" +#endif + static tlsf_t heap; +MP_WEAK void reset_port_early(void) { +} + MP_WEAK void port_wake_main_task(void) { } MP_WEAK void port_wake_main_task_from_isr(void) { } -MP_WEAK void port_yield(void) { +MP_WEAK void port_task_yield(void) { +} + +MP_WEAK void port_task_sleep_ms(uint32_t msecs) { + mp_hal_delay_ms(msecs); } MP_WEAK void port_boot_info(void) { @@ -38,11 +52,36 @@ MP_WEAK void *port_malloc(size_t size, bool dma_capable) { return block; } +// Ensure allocated memory is zero. +MP_WEAK void *port_malloc_zero(size_t size, bool dma_capable) { + void *ptr = port_malloc(size, dma_capable); + if (ptr) { + memset(ptr, 0, size); + } + return ptr; +} + MP_WEAK void port_free(void *ptr) { tlsf_free(heap, ptr); } -MP_WEAK void *port_realloc(void *ptr, size_t size) { +// Safely free an object that may have been allocated from either the GC heap or port heap. +// If the pointer is on the GC heap, it will be freed by the GC automatically, so we do nothing. +// If the pointer is not on the GC heap (i.e., allocated with port_malloc), we free it with port_free. +// This is safe to call during shutdown when GC may not be available. +void circuitpy_free_obj(mp_obj_t obj) { + if (obj == mp_const_none) { + return; + } + void *ptr = MP_OBJ_TO_PTR(obj); + if (gc_alloc_possible() && gc_ptr_on_heap(ptr)) { + gc_free(ptr); + } else { + port_free(ptr); + } +} + +MP_WEAK void *port_realloc(void *ptr, size_t size, bool dma_capable) { return tlsf_realloc(heap, ptr, size); } @@ -60,3 +99,50 @@ MP_WEAK size_t port_heap_get_largest_free_size(void) { // IDF does this. Not sure why. return tlsf_fit_size(heap, max_size); } + +MP_WEAK bool port_boot_button_pressed(void) { + #if defined(CIRCUITPY_BOOT_BUTTON) + // Init/deinit the boot button every time in case it is used for LEDs. + digitalio_digitalinout_obj_t boot_button; + common_hal_digitalio_digitalinout_construct(&boot_button, CIRCUITPY_BOOT_BUTTON); + common_hal_digitalio_digitalinout_switch_to_input(&boot_button, + CIRCUITPY_BOOT_BUTTON_ACTIVE_HIGH ? PULL_DOWN : PULL_UP); + common_hal_time_delay_ms(1); + bool value = common_hal_digitalio_digitalinout_get_value(&boot_button); + common_hal_digitalio_digitalinout_deinit(&boot_button); + return value == CIRCUITPY_BOOT_BUTTON_ACTIVE_HIGH; + #else + return false; + #endif +} + +// Ports may provide an implementation of this function if it is needed +MP_WEAK void port_gc_collect(void) { +} + +// Ports may provide an implementation of this function if it is needed +MP_WEAK void port_gc_deinit(void) { +} + +// Allocates an object in the port heap, not the VM heap, and also sets type, for mp_obj_malloc{,_var} macros. +MP_NOINLINE void *mp_obj_port_malloc_helper(size_t num_bytes, const mp_obj_type_t *type) { + mp_obj_base_t *base = (mp_obj_base_t *)port_malloc_zero(num_bytes, false); + base->type = type; + return base; +} + +// Creates a tuple on the port heap, not the VM heap. +// Implementation copied from py/objtuple.c. +mp_obj_t mp_obj_new_port_tuple(size_t n, const mp_obj_t *items) { + if (n == 0) { + return mp_const_empty_tuple; + } + mp_obj_tuple_t *o = mp_obj_port_malloc_var(mp_obj_tuple_t, items, mp_obj_t, n, &mp_type_tuple); + o->len = n; + if (items) { + for (size_t i = 0; i < n; i++) { + o->items[i] = items[i]; + } + } + return MP_OBJ_FROM_PTR(o); +} diff --git a/supervisor/shared/reload.c b/supervisor/shared/reload.c index fb7ff0403c2..6e37c558aaa 100644 --- a/supervisor/shared/reload.c +++ b/supervisor/shared/reload.c @@ -35,16 +35,16 @@ void reload_initiate(supervisor_run_reason_t run_reason) { port_wake_main_task(); } -void autoreload_reset() { +void autoreload_reset(void) { last_autoreload_trigger = 0; } -void autoreload_enable() { +void autoreload_enable(void) { autoreload_enabled = true; last_autoreload_trigger = 0; } -void autoreload_disable() { +void autoreload_disable(void) { autoreload_enabled = false; } @@ -52,15 +52,19 @@ void autoreload_suspend(uint32_t suspend_reason_mask) { autoreload_suspended |= suspend_reason_mask; } +bool autoreload_is_suspended(uint32_t suspend_reason_mask) { + return (autoreload_suspended & suspend_reason_mask) != 0; +} + void autoreload_resume(uint32_t suspend_reason_mask) { autoreload_suspended &= ~suspend_reason_mask; } -inline bool autoreload_is_enabled() { +inline bool autoreload_is_enabled(void) { return autoreload_enabled; } -void autoreload_trigger() { +void autoreload_trigger(void) { if (!autoreload_enabled || autoreload_suspended != 0) { return; } @@ -78,7 +82,7 @@ void autoreload_trigger() { } } -bool autoreload_ready() { +bool autoreload_ready(void) { if (last_autoreload_trigger == 0 || autoreload_suspended != 0) { return false; } diff --git a/supervisor/shared/reload.h b/supervisor/shared/reload.h index 9d65270bd4a..32f99f0c1a8 100644 --- a/supervisor/shared/reload.h +++ b/supervisor/shared/reload.h @@ -50,5 +50,6 @@ bool autoreload_pending(void); // immediate reload. // Used during the REPL or during parts of BLE workflow. void autoreload_suspend(uint32_t suspend_reason_mask); +bool autoreload_is_suspended(uint32_t suspend_reason_mask); // Allow autoreloads again, for the given reason(s). void autoreload_resume(uint32_t suspend_reason_mask); diff --git a/supervisor/shared/safe_mode.c b/supervisor/shared/safe_mode.c index 85c49451bc7..4570b05050b 100644 --- a/supervisor/shared/safe_mode.c +++ b/supervisor/shared/safe_mode.c @@ -8,10 +8,6 @@ #include "mphalport.h" -#if defined(CIRCUITPY_BOOT_BUTTON) -#include "shared-bindings/digitalio/DigitalInOut.h" -#include "shared-bindings/time/__init__.h" -#endif #include "shared-bindings/microcontroller/Processor.h" #include "shared-bindings/microcontroller/ResetReason.h" @@ -22,6 +18,14 @@ #include "supervisor/shared/translate/translate.h" #include "supervisor/shared/tick.h" +#if CIRCUITPY_SETTINGS_TOML +#include "supervisor/shared/settings.h" +#endif + +#ifdef __ZEPHYR__ +#include +#endif + #define SAFE_MODE_DATA_GUARD 0xad0000af #define SAFE_MODE_DATA_GUARD_MASK 0xff0000ff @@ -50,10 +54,12 @@ 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_UNKNOWN && - reset_reason != RESET_REASON_SOFTWARE) { + // Skip the safe-mode wait if the reset was due to a problem, + // or was a wake from deep sleep, where the wait would waste time. + if (reset_reason == MCU_RESET_REASON_BROWNOUT || + reset_reason == MCU_RESET_REASON_WATCHDOG || + reset_reason == MCU_RESET_REASON_RESCUE_DEBUG || + reset_reason == MCU_RESET_REASON_DEEP_SLEEP_ALARM) { return SAFE_MODE_NONE; } #if CIRCUITPY_SKIP_SAFE_MODE_WAIT @@ -65,32 +71,40 @@ safe_mode_t wait_for_safe_mode_reset(void) { #if CIRCUITPY_STATUS_LED status_led_init(); #endif + + #define DEFAULT_SAFE_MODE_DELAY_MSECS (1000) + #define DEFAULT_SAFE_MODE_DELAY_SECS (((mp_float_t)DEFAULT_SAFE_MODE_DELAY_MSECS) / 1000.0f) + uint32_t safe_mode_delay_msecs = DEFAULT_SAFE_MODE_DELAY_MSECS; + + #if CIRCUITPY_SETTINGS_TOML + mp_float_t safe_mode_delay_secs = DEFAULT_SAFE_MODE_DELAY_SECS; + // Will update safe_mode_delay_secs if setting is present. + settings_get_float("CIRCUITPY_SAFE_MODE_DELAY", &safe_mode_delay_secs); + if (safe_mode_delay_secs >= 0.0f && safe_mode_delay_secs <= (mp_float_t)UINT32_MAX) { + safe_mode_delay_msecs = safe_mode_delay_secs * 1000; + } + #endif + uint64_t start_ticks = supervisor_ticks_ms64(); uint64_t diff = 0; bool boot_in_safe_mode = false; - while (diff < 1000) { + while (diff < safe_mode_delay_msecs) { #if CIRCUITPY_STATUS_LED - // Blink on for 100, off for 100 - bool led_on = (diff % 250) < 125; + // Blink on for 125, off for 125 + bool led_on = boot_in_safe_mode || (diff % 250) < 125; if (led_on) { new_status_color(SAFE_MODE); } else { new_status_color(BLACK); } #endif - // Init the boot button every time in case it is used for LEDs. - #ifdef CIRCUITPY_BOOT_BUTTON - digitalio_digitalinout_obj_t boot_button; - common_hal_digitalio_digitalinout_construct(&boot_button, CIRCUITPY_BOOT_BUTTON); - common_hal_digitalio_digitalinout_switch_to_input(&boot_button, PULL_UP); - common_hal_time_delay_ms(1); - bool button_pressed = !common_hal_digitalio_digitalinout_get_value(&boot_button); - common_hal_digitalio_digitalinout_deinit(&boot_button); - if (button_pressed) { + if (!boot_in_safe_mode && port_boot_button_pressed()) { boot_in_safe_mode = true; - break; + // Show solid yellow as feedback that the press was accepted, for the + // default duration. + start_ticks = supervisor_ticks_ms64(); + safe_mode_delay_msecs = DEFAULT_SAFE_MODE_DELAY_MSECS; } - #endif diff = supervisor_ticks_ms64() - start_ticks; } #if CIRCUITPY_STATUS_LED @@ -112,10 +126,19 @@ void PLACE_IN_ITCM(safe_mode_on_next_reset)(safe_mode_t reason) { // Don't inline this so it's easy to break on it from GDB. void __attribute__((noinline, )) PLACE_IN_ITCM(reset_into_safe_mode)(safe_mode_t reason) { if (_safe_mode > SAFE_MODE_BROWNOUT && reason > SAFE_MODE_BROWNOUT) { + #ifdef __ZEPHYR__ + printk("Already in safe mode\n"); + printk("Reason: %d\n", reason); + printk("Current safe mode: %d\n", _safe_mode); + while (true) { + k_cpu_idle(); + } + #else while (true) { // This very bad because it means running in safe mode didn't save us. Only ignore brownout // because it may be due to a switch bouncing. } + #endif } safe_mode_on_next_reset(reason); @@ -142,7 +165,7 @@ void print_safe_mode_message(safe_mode_t reason) { case SAFE_MODE_USER: #if defined(BOARD_USER_SAFE_MODE_ACTION) message = BOARD_USER_SAFE_MODE_ACTION; - #elif defined(CIRCUITPY_BOOT_BUTTON) + #elif defined(CIRCUITPY_BOOT_BUTTON) || CIRCUITPY_BOOT_BUTTON_NO_GPIO message = MP_ERROR_TEXT("You pressed the BOOT button at start up"); #else message = MP_ERROR_TEXT("You pressed the reset button during boot."); @@ -197,6 +220,9 @@ void print_safe_mode_message(safe_mode_t reason) { case SAFE_MODE_INTERRUPT_ERROR: message = MP_ERROR_TEXT("Interrupt error."); break; + case SAFE_MODE_LVGL_OUT_OF_MEMORY: + message = MP_ERROR_TEXT("LVGL ran out of memory."); + break; case SAFE_MODE_NLR_JUMP_FAIL: message = MP_ERROR_TEXT("NLR jump failed. Likely memory corruption."); break; diff --git a/supervisor/shared/safe_mode.h b/supervisor/shared/safe_mode.h index 8f4037cbe20..1021cad980c 100644 --- a/supervisor/shared/safe_mode.h +++ b/supervisor/shared/safe_mode.h @@ -17,6 +17,7 @@ typedef enum { SAFE_MODE_GC_ALLOC_OUTSIDE_VM, SAFE_MODE_HARD_FAULT, SAFE_MODE_INTERRUPT_ERROR, + SAFE_MODE_LVGL_OUT_OF_MEMORY, SAFE_MODE_MANUAL, SAFE_MODE_NLR_JUMP_FAIL, SAFE_MODE_NO_CIRCUITPY, @@ -38,6 +39,6 @@ void set_safe_mode(safe_mode_t safe_mode); safe_mode_t wait_for_safe_mode_reset(void); void safe_mode_on_next_reset(safe_mode_t reason); -void reset_into_safe_mode(safe_mode_t reason) NORETURN; +void reset_into_safe_mode(safe_mode_t reason) MP_NORETURN; void print_safe_mode_message(safe_mode_t reason); diff --git a/supervisor/shared/serial.c b/supervisor/shared/serial.c index 94b429b6ab6..d8d88c0a794 100644 --- a/supervisor/shared/serial.c +++ b/supervisor/shared/serial.c @@ -17,7 +17,7 @@ #include "supervisor/shared/serial.h" #include "shared-bindings/microcontroller/Pin.h" -#if CIRCUITPY_SERIAL_BLE +#if CIRCUITPY_BLE_SERIAL_SERVICE #include "supervisor/shared/bluetooth/serial.h" #endif @@ -32,6 +32,7 @@ #if CIRCUITPY_WEB_WORKFLOW #include "supervisor/shared/web_workflow/websocket.h" +#include "supervisor/shared/web_workflow/display_stream.h" #endif #if CIRCUITPY_CONSOLE_UART @@ -191,7 +192,6 @@ void serial_early_init(void) { common_hal_busio_uart_construct(&console_uart, console_tx, console_rx, NULL, NULL, NULL, false, CIRCUITPY_CONSOLE_UART_BAUDRATE, 8, BUSIO_UART_PARITY_NONE, 1, 1.0f, sizeof(console_uart_rx_buf), console_uart_rx_buf, true); - common_hal_busio_uart_never_reset(&console_uart); #endif board_serial_early_init(); @@ -219,7 +219,7 @@ void serial_init(void) { } bool serial_connected(void) { - #if CIRCUITPY_USB_DEVICE && CIRCUITPY_USB_VENDOR + #if CIRCUITPY_TINYUSB && CIRCUITPY_USB_DEVICE && CIRCUITPY_USB_VENDOR if (tud_vendor_connected()) { return true; } @@ -229,17 +229,17 @@ bool serial_connected(void) { return true; #endif - #if CIRCUITPY_SERIAL_BLE + #if CIRCUITPY_BLE_SERIAL_SERVICE if (ble_serial_connected()) { return true; } #endif - #if CIRCUITPY_USB_DEVICE && CIRCUITPY_USB_CDC + #if CIRCUITPY_TINYUSB && CIRCUITPY_USB_DEVICE && CIRCUITPY_USB_CDC if (usb_cdc_console_enabled() && tud_cdc_connected()) { return true; } - #elif CIRCUITPY_USB_DEVICE + #elif CIRCUITPY_TINYUSB && CIRCUITPY_USB_DEVICE if (tud_cdc_connected()) { return true; } @@ -273,7 +273,7 @@ bool serial_connected(void) { } char serial_read(void) { - #if CIRCUITPY_USB_DEVICE && CIRCUITPY_USB_VENDOR + #if CIRCUITPY_TINYUSB && CIRCUITPY_USB_DEVICE && CIRCUITPY_USB_VENDOR if (tud_vendor_connected() && tud_vendor_available() > 0) { char tiny_buffer; tud_vendor_read(&tiny_buffer, 1); @@ -290,7 +290,7 @@ char serial_read(void) { } #endif - #if CIRCUITPY_SERIAL_BLE + #if CIRCUITPY_BLE_SERIAL_SERVICE if (ble_serial_available() > 0) { return ble_serial_read_char(); } @@ -305,6 +305,12 @@ char serial_read(void) { } #endif + #if CIRCUITPY_WEB_WORKFLOW && CIRCUITPY_DISPLAYIO + if (display_stream_available()) { + return display_stream_read_char(); + } + #endif + #if CIRCUITPY_USB_KEYBOARD_WORKFLOW if (usb_keyboard_chars_available() > 0) { return usb_keyboard_read_char(); @@ -327,7 +333,7 @@ char serial_read(void) { return -1; } #endif - #if CIRCUITPY_USB_DEVICE + #if CIRCUITPY_TINYUSB && CIRCUITPY_USB_DEVICE return (char)tud_cdc_read_char(); #endif @@ -338,7 +344,7 @@ uint32_t serial_bytes_available(void) { // There may be multiple serial input channels, so sum the count from all. uint32_t count = 0; - #if CIRCUITPY_USB_DEVICE && CIRCUITPY_USB_VENDOR + #if CIRCUITPY_TINYUSB && CIRCUITPY_USB_DEVICE && CIRCUITPY_USB_VENDOR if (tud_vendor_connected()) { count += tud_vendor_available(); } @@ -348,7 +354,7 @@ uint32_t serial_bytes_available(void) { count += common_hal_busio_uart_rx_characters_available(&console_uart); #endif - #if CIRCUITPY_SERIAL_BLE + #if CIRCUITPY_BLE_SERIAL_SERVICE count += ble_serial_available(); #endif @@ -356,11 +362,15 @@ uint32_t serial_bytes_available(void) { count += websocket_available(); #endif + #if CIRCUITPY_WEB_WORKFLOW && CIRCUITPY_DISPLAYIO + count += display_stream_available(); + #endif + #if CIRCUITPY_USB_KEYBOARD_WORKFLOW count += usb_keyboard_chars_available(); #endif - #if CIRCUITPY_USB_DEVICE && CIRCUITPY_USB_CDC + #if CIRCUITPY_TINYUSB && CIRCUITPY_USB_DEVICE && CIRCUITPY_USB_CDC if (usb_cdc_console_enabled()) { count += tud_cdc_available(); } @@ -399,7 +409,7 @@ uint32_t serial_write_substring(const char *text, uint32_t length) { return length_sent; } - #if CIRCUITPY_USB_DEVICE && CIRCUITPY_USB_VENDOR + #if CIRCUITPY_TINYUSB && CIRCUITPY_USB_DEVICE && CIRCUITPY_USB_VENDOR if (tud_vendor_connected()) { length_sent = tud_vendor_write(text, length); } @@ -409,7 +419,7 @@ uint32_t serial_write_substring(const char *text, uint32_t length) { length_sent = console_uart_write(text, length); #endif - #if CIRCUITPY_SERIAL_BLE + #if CIRCUITPY_BLE_SERIAL_SERVICE ble_serial_write(text, length); #endif @@ -423,7 +433,7 @@ uint32_t serial_write_substring(const char *text, uint32_t length) { } #endif - #if CIRCUITPY_USB_DEVICE + #if CIRCUITPY_TINYUSB && CIRCUITPY_USB_DEVICE // Delay the very first write if (tud_cdc_connected() && !_first_write_done) { mp_hal_delay_ms(50); diff --git a/supervisor/shared/settings.c b/supervisor/shared/settings.c new file mode 100644 index 00000000000..b658770f45f --- /dev/null +++ b/supervisor/shared/settings.c @@ -0,0 +1,627 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2022 Scott Shawcroft for Adafruit Industries +// SPDX-FileCopyrightText: Copyright (c) 2026 Dan Halbert for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include +#include +#include +#include + +#include "py/gc.h" +#include "py/misc.h" +#include "py/mpstate.h" +#include "py/mpprint.h" +#include "py/objstr.h" +#include "py/parsenum.h" +#include "py/runtime.h" +#include "supervisor/filesystem.h" +#include "supervisor/shared/settings.h" + +#define SETTINGS_PATH "/settings.toml" + +#include "extmod/vfs.h" +#include "extmod/vfs_fat.h" + +#if CIRCUITPY_SETTINGS_TOML +#if defined(UNIX) +typedef FIL file_arg; +static bool open_file(const char *name, file_arg *file_handle) { + nlr_buf_t nlr; + if (nlr_push(&nlr) == 0) { + mp_obj_t file_obj = mp_call_function_2( + MP_OBJ_FROM_PTR(&mp_builtin_open_obj), mp_obj_new_str(name, strlen(name)), MP_ROM_QSTR(MP_QSTR_rb)); + mp_arg_validate_type(file_obj, &mp_type_vfs_fat_fileio, MP_QSTR_file); + pyb_file_obj_t *file = MP_OBJ_TO_PTR(file_obj); + *file_handle = file->fp; + nlr_pop(); + return true; + } else { + return false; + } +} + +static void close_file(file_arg *file_handle) { + f_close(file_handle); +} + +static bool is_eof(file_arg *file_handle) { + return f_eof(file_handle) || f_error(file_handle); +} + +// Return 0 if there is no next character (EOF). +static uint8_t get_next_byte(FIL *file_handle) { + uint8_t character = 0; + UINT quantity_read; + // If there's an error or quantity_read is 0, character will remain 0. + f_read(file_handle, &character, 1, &quantity_read); + return character; +} + +static void seek_eof(file_arg *file_handle) { + f_lseek(file_handle, f_size(file_handle)); +} +#else +// Outside of the unix port, settings.toml is read through the supervisor +// filesystem API so it works on both FAT and littlefs mounts. +typedef supervisor_vfs_file_t file_arg; + +static bool open_file(const char *name, file_arg *file_handle) { + supervisor_vfs_t *fs_mount = filesystem_circuitpy(); + if (fs_mount == NULL) { + return false; + } + return supervisor_vfs_open_file(fs_mount, name, SUPERVISOR_FS_OPEN_READ, 0, file_handle) == SUPERVISOR_FS_OK; +} + +static void close_file(file_arg *file_handle) { + supervisor_vfs_close_file(file_handle); +} + +// Reads mark the end of the file by closing the handle. +static bool is_eof(file_arg *file_handle) { + return !file_handle->open; +} + +// Return 0 if there is no next character (EOF). +static uint8_t get_next_byte(file_arg *file_handle) { + uint8_t character = 0; + size_t quantity_read; + // If there's an error or quantity_read is 0, character will remain 0. + supervisor_fs_err_t err = supervisor_vfs_read_file(file_handle, &character, 1, &quantity_read); + // If we hit the end of the file (or an error), close the handle so that + // is_eof() reports the file is done. + if (err != SUPERVISOR_FS_OK || quantity_read == 0) { + close_file(file_handle); + } + return character; +} + +static void seek_eof(file_arg *file_handle) { + supervisor_vfs_seek_file(file_handle, supervisor_vfs_file_size(file_handle)); +} +#endif + +// For a fixed buffer, record the required size rather than throwing +static void vstr_add_byte_nonstd(vstr_t *vstr, byte b) { + if (!vstr->fixed_buf || vstr->alloc > vstr->len) { + vstr_add_byte(vstr, b); + } else { + vstr->len++; + } +} + +// For a fixed buffer, record the required size rather than throwing +static void vstr_add_char_nonstd(vstr_t *vstr, unichar c) { + size_t ulen = + (c < 0x80) ? 1 : + (c < 0x800) ? 2 : + (c < 0x10000) ? 3 : 4; + if (!vstr->fixed_buf || vstr->alloc > vstr->len + ulen) { + vstr_add_char(vstr, c); + } else { + vstr->len += ulen; + } +} + +static void next_line(file_arg *file_handle) { + uint8_t character; + do { + character = get_next_byte(file_handle); + } while (character != 0 && character != '\n'); +} + +// Discard whitespace, except for newlines, returning the next character after the whitespace. +// Return 0 if there is no next character (EOF). +static uint8_t consume_whitespace(file_arg *file_handle) { + uint8_t character; + do { + character = get_next_byte(file_handle); + } while (character != '\n' && character != 0 && unichar_isspace(character)); + return character; +} + +// Starting at the start of a new line, determines if the key matches the given key. +// +// If result is true, the key matches and file pointer is pointing just after the "=". +// If the result is false, the key does NOT match and the file pointer is +// pointing at the start of the next line, if any +static bool key_matches(file_arg *file_handle, const char *key) { + uint8_t character; + character = consume_whitespace(file_handle); + // [section] isn't implemented, so skip to end of file. + if (character == '[' || character == 0) { + seek_eof(file_handle); + return false; + } + while (*key) { + if (character != *key++) { + // A character didn't match the key, so it's not a match + // If the non-matching char was not the end of the line, + // then consume the rest of the line + if (character != '\n') { + next_line(file_handle); + } + return false; + } + character = get_next_byte(file_handle); + } + // the next character could be whitespace; consume if necessary + if (unichar_isspace(character)) { + character = consume_whitespace(file_handle); + } + // If we're not looking at the "=" then the key didn't match + if (character != '=') { + // A character didn't match the key, so it's not a match + // If the non-matching char was not the end of the line, + // then consume the rest of the line + if (character != '\n') { + next_line(file_handle); + } + return false; + } + return true; +} + +// Parse digits in base 2 to 16, skipping any '_' after the first digit. +// Used instead of strtol() and strtoul(), which would pull in about 0.8 kB of libc. +// +// Returns a pointer past the last digit, or NULL if there are no digits or the value +// overflows mp_uint_t. *value is not touched on error. +static const char *parse_digits(const char *str, mp_uint_t base, mp_uint_t *value) { + const char *start = str; + mp_uint_t val = 0; + for (;; str++) { + mp_uint_t dig = (unsigned char)*str; + if (dig == '_' && str != start) { + continue; + } + if ('0' <= dig && dig <= '9') { + dig -= '0'; + } else if ((dig | 0x20) >= 'a') { + // Lowercase; anything past 'z' ends up >= base. + dig = (dig | 0x20) - 'a' + 10; + } else { + break; + } + if (dig >= base) { + break; + } + if (__builtin_mul_overflow(val, base, &val) || __builtin_add_overflow(val, dig, &val)) { + return NULL; + } + } + if (str == start) { + return NULL; + } + *value = val; + return str; +} + +static settings_err_t read_unicode_escape(file_arg *file_handle, int sz, vstr_t *vstr) { + mp_uint_t c = 0; + for (int i = 0; i < sz; i++) { + uint8_t hex = get_next_byte(file_handle); + if (!unichar_isxdigit(hex)) { + return SETTINGS_ERR_BAD_VALUE; + } + c = c * 16 + unichar_xdigit_value(hex); + } + if (c >= 0x110000) { + return SETTINGS_ERR_UNICODE; + } + vstr_add_char_nonstd(vstr, c); + return SETTINGS_OK; +} + +// Read a quoted string +static settings_err_t read_string_value(file_arg *file_handle, vstr_t *vstr) { + while (true) { + int character = get_next_byte(file_handle); + switch (character) { + case 0: + case '\n': + return SETTINGS_ERR_BAD_VALUE; + + case '"': + character = consume_whitespace(file_handle); + switch (character) { + case '#': + next_line(file_handle); + MP_FALLTHROUGH; + case 0: + case '\n': + return SETTINGS_OK; + default: + return SETTINGS_ERR_BAD_VALUE; + } + + case '\\': + character = get_next_byte(file_handle); + switch (character) { + case 0: + case '\n': + return SETTINGS_ERR_BAD_VALUE; + case 'b': + character = '\b'; + break; + case 'r': + character = '\r'; + break; + case 'n': + character = '\n'; + break; + case 't': + character = '\t'; + break; + case 'v': + character = '\v'; + break; + case 'f': + character = '\f'; + break; + case 'U': + case 'u': { + int sz = (character == 'u') ? 4 : 8; + settings_err_t res; + res = read_unicode_escape(file_handle, sz, vstr); + if (res != SETTINGS_OK) { + return res; + } + continue; + } + // default falls through, other escaped characters + // represent themselves + } + MP_FALLTHROUGH; + default: + vstr_add_byte_nonstd(vstr, character); + } + } +} + +// Read a bare value (non-quoted value) as a string +// Trims leading and trailing spaces/tabs, stops at # comment or newline +static settings_err_t read_bare_value(file_arg *file_handle, vstr_t *vstr, int first_character) { + int character = first_character; + size_t trailing_space_count = 0; + + while (true) { + switch (character) { + case 0: + case '\n': + // Remove trailing spaces/tabs and \r + vstr->len -= trailing_space_count; + return SETTINGS_OK; + case '#': + // Remove trailing spaces/tabs and \r before comment + vstr->len -= trailing_space_count; + next_line(file_handle); + return SETTINGS_OK; + case ' ': + case '\t': + case '\r': + // Track potential trailing whitespace + vstr_add_byte_nonstd(vstr, character); + trailing_space_count++; + break; + default: + // Non-whitespace character resets trailing space count + vstr_add_byte_nonstd(vstr, character); + trailing_space_count = 0; + } + character = get_next_byte(file_handle); + } +} + +static mp_int_t read_value(file_arg *file_handle, vstr_t *vstr, bool *quoted) { + uint8_t character; + character = consume_whitespace(file_handle); + *quoted = (character == '"'); + + if (*quoted) { + return read_string_value(file_handle, vstr); + } else if (character == '\n' || character == 0) { + // Empty value is an error + return SETTINGS_ERR_BAD_VALUE; + } else { + return read_bare_value(file_handle, vstr, character); + } +} + +static settings_err_t settings_get_vstr(const char *key, vstr_t *vstr, bool *quoted) { + file_arg file_handle; + if (!open_file(SETTINGS_PATH, &file_handle)) { + return SETTINGS_ERR_OPEN; + } + + settings_err_t result = SETTINGS_ERR_NOT_FOUND; + while (!is_eof(&file_handle)) { + if (key_matches(&file_handle, key)) { + result = read_value(&file_handle, vstr, quoted); + break; + } + } + close_file(&file_handle); + return result; +} + +static settings_err_t settings_get_buf_terminated(const char *key, char *value, size_t value_len, bool *quoted) { + vstr_t vstr; + vstr_init_fixed_buf(&vstr, value_len, value); + settings_err_t result = settings_get_vstr(key, &vstr, quoted); + + if (result == SETTINGS_OK) { + vstr_add_byte_nonstd(&vstr, 0); + memcpy(value, vstr.buf, MIN(vstr.len, value_len)); + if (vstr.len > value_len) { // this length includes trailing NUL + result = SETTINGS_ERR_LENGTH; + } + } + return result; +} + +static void print_error(const char *key, settings_err_t result) { + switch (result) { + case SETTINGS_OK: + case SETTINGS_ERR_OPEN: + case SETTINGS_ERR_NOT_FOUND: + // These errors need not be printed. + // The code asking for the value is not necessarily expecting to find one. + return; + default: + mp_cprintf(&mp_plat_print, MP_ERROR_TEXT("An error occurred while retrieving '%s':\n"), key); + break; + } + + switch (result) { + case SETTINGS_ERR_UNICODE: + mp_cprintf(&mp_plat_print, MP_ERROR_TEXT("Invalid unicode escape")); + break; + case SETTINGS_ERR_BAD_VALUE: + mp_cprintf(&mp_plat_print, MP_ERROR_TEXT("Invalid format")); + break; + default: + mp_cprintf(&mp_plat_print, MP_ERROR_TEXT("Internal error")); + break; + } + mp_printf(&mp_plat_print, "\n"); +} + + +static settings_err_t get_str(const char *key, char *value, size_t value_len) { + bool quoted; + settings_err_t result = settings_get_buf_terminated(key, value, value_len, "ed); + if (result == SETTINGS_OK && !quoted) { + result = SETTINGS_ERR_BAD_VALUE; + } + return result; +} + +settings_err_t settings_get_str(const char *key, char *value, size_t value_len) { + settings_err_t result = get_str(key, value, value_len); + print_error(key, result); + return result; +} + +static settings_err_t get_int(const char *key, mp_int_t *value) { + char buf[16]; + bool quoted; + settings_err_t result = settings_get_buf_terminated(key, buf, sizeof(buf), "ed); + if (result != SETTINGS_OK) { + return result; + } + if (quoted) { + return SETTINGS_ERR_BAD_VALUE; + } + // Accept a superset of TOML: a sign is also allowed before 0x, 0o and 0b, the prefix + // may be uppercase, and underscores need not be between digits. + const char *str = buf; + bool neg = false; + if (*str == '+' || *str == '-') { + neg = *str == '-'; + str++; + } + mp_uint_t base = 10; + if (str[0] == '0') { + char prefix = str[1] | 0x20; + if (prefix == 'x') { + base = 16; + } else if (prefix == 'o') { + base = 8; + } else if (prefix == 'b') { + base = 2; + } + if (base != 10) { + str += 2; + } else if (unichar_isdigit(str[1])) { + // TOML does not allow leading zeros on decimal integers. + return SETTINGS_ERR_BAD_VALUE; + } + } + mp_uint_t magnitude; + str = parse_digits(str, base, &magnitude); + // A negative value can be one larger than MP_INT_MAX. + if (str == NULL || magnitude > (mp_uint_t)MP_INT_MAX + neg) { + return SETTINGS_ERR_BAD_VALUE; + } + while (unichar_isspace(*str)) { + str++; + } + if (*str) { // If the whole buffer was not consumed it's an error + return SETTINGS_ERR_BAD_VALUE; + } + *value = (mp_int_t)(neg ? 0 - magnitude : magnitude); + return SETTINGS_OK; +} + +settings_err_t settings_get_int(const char *key, mp_int_t *value) { + settings_err_t result = get_int(key, value); + print_error(key, result); + return result; +} + +static settings_err_t get_bool(const char *key, bool *value) { + char buf[16]; + bool quoted; + settings_err_t result = settings_get_buf_terminated(key, buf, sizeof(buf), "ed); + if (result != SETTINGS_OK) { + return result; + } + if (quoted) { + return SETTINGS_ERR_BAD_VALUE; + } + + // Check for "true" or "false" (case-sensitive) + if (strcmp(buf, "true") == 0) { + *value = true; + return SETTINGS_OK; + } else if (strcmp(buf, "false") == 0) { + *value = false; + return SETTINGS_OK; + } + + // Not a valid boolean value + return SETTINGS_ERR_BAD_VALUE; +} + +settings_err_t settings_get_bool(const char *key, bool *value) { + settings_err_t result = get_bool(key, value); + print_error(key, result); + return result; +} + +#if MICROPY_PY_BUILTINS_FLOAT +// TOML does not allow leading zeros on decimal integers or on the integer part of floats. +// https://toml.io/en/v1.0.0#integer and https://toml.io/en/v1.0.0#float +static bool has_leading_zero(const char *str) { + if (*str == '+' || *str == '-') { + str++; + } + return str[0] == '0' && unichar_isdigit(str[1]); +} + +static settings_err_t get_float(const char *key, mp_float_t *value) { + char buf[48]; + bool quoted; + settings_err_t result = settings_get_buf_terminated(key, buf, sizeof(buf), "ed); + if (result != SETTINGS_OK) { + return result; + } + if (quoted || has_leading_zero(buf)) { + return SETTINGS_ERR_BAD_VALUE; + } + + const char *str = buf; + const char *end = buf + strlen(buf); + bool neg = false; + + if (str < end && (*str == '+' || *str == '-')) { + neg = (*str == '-'); + str++; + } + + mp_float_t val; + if (end - str >= 3 && str[0] == 'i' && str[1] == 'n' && str[2] == 'f') { + str += 3; + val = (mp_float_t)INFINITY; + } else if (end - str >= 3 && str[0] == 'n' && str[1] == 'a' && str[2] == 'n') { + str += 3; + val = MICROPY_FLOAT_C_FUN(nan)(""); + } else { + const char *num_start = str; + str = mp_parse_float_internal(str, end - str, &val); + if (str == NULL || str == num_start) { + return SETTINGS_ERR_BAD_VALUE; + } + } + + if (str != end) { + return SETTINGS_ERR_BAD_VALUE; + } + + *value = neg ? -val : val; + return SETTINGS_OK; +} + +settings_err_t settings_get_float(const char *key, mp_float_t *value) { + settings_err_t result = get_float(key, value); + print_error(key, result); + return result; +} +#endif + +// Get the raw value as a vstr, whether quoted or bare. Value may be an invalid TOML value. +settings_err_t settings_get_raw_vstr(const char *key, vstr_t *vstr) { + bool quoted; + return settings_get_vstr(key, vstr, "ed); +} + +settings_err_t settings_get_obj(const char *key, mp_obj_t *value) { + vstr_t vstr; + vstr_init(&vstr, 32); + bool quoted; + + settings_err_t result = settings_get_vstr(key, &vstr, "ed); + if (result != SETTINGS_OK) { + return result; + } + + if (quoted) { + // Successfully parsed a quoted string + *value = mp_obj_new_str_from_vstr(&vstr); + return SETTINGS_OK; + } + + // Not a quoted string, try boolean + bool bool_val; + result = get_bool(key, &bool_val); + if (result == SETTINGS_OK) { + *value = mp_obj_new_bool(bool_val); + return SETTINGS_OK; + } + + // Not a boolean, try integer + mp_int_t int_val; + result = get_int(key, &int_val); + if (result == SETTINGS_OK) { + *value = mp_obj_new_int(int_val); + return SETTINGS_OK; + } + + // Not an integer, try float + #if MICROPY_PY_BUILTINS_FLOAT + mp_float_t float_val; + result = get_float(key, &float_val); + if (result == SETTINGS_OK) { + *value = mp_obj_new_float(float_val); + return SETTINGS_OK; + } + #endif + + return SETTINGS_ERR_BAD_VALUE; +} + +#endif diff --git a/supervisor/shared/settings.h b/supervisor/shared/settings.h new file mode 100644 index 00000000000..6d92d45d79a --- /dev/null +++ b/supervisor/shared/settings.h @@ -0,0 +1,64 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2022 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/obj.h" + +typedef enum { + SETTINGS_OK = 0, + // The settings file could not be opened. + SETTINGS_ERR_OPEN, + SETTINGS_ERR_UNICODE, + SETTINGS_ERR_LENGTH, + SETTINGS_ERR_NOT_FOUND, + SETTINGS_ERR_BAD_VALUE, +} settings_err_t; + +// Read a string value from the settings file. +// If it fits, the return value is 0-terminated. The passed-in buffer +// may be modified even if an error is returned. Allocation free. +// An error that is not SETTINGS_ERR_OPEN or SETTINGS_ERR_NOT_FOUND is printed on the repl. +// Returns an error if the value is not a quoted string. +settings_err_t settings_get_str(const char *key, char *value, size_t value_len); + +// Read an integer value from the settings file. +// Returns SETTINGS_OK and sets value to the read value. Returns +// SETTINGS_ERR_... if the value was not numeric. allocation-free. +// If any error code is returned, value is guaranteed not modified +// An error that is not 'open' or 'not found' is printed on the repl. +settings_err_t settings_get_int(const char *key, mp_int_t *value); + +// Read a boolean value from the settings file. +// Returns SETTINGS_OK and sets value to the read value. Returns +// SETTINGS_ERR_... if the value was not a boolean (true or false). allocation-free. +// If any error code is returned, value is guaranteed not modified +// An error that is not 'open' or 'not found' is printed on the repl. +settings_err_t settings_get_bool(const char *key, bool *value); + +#if MICROPY_PY_BUILTINS_FLOAT +// Read a float value from the settings file. +// Returns SETTINGS_OK and sets value to the read value. Returns +// SETTINGS_ERR_... if the value was not a float. allocation-free. +// If any error code is returned, value is guaranteed not modified. +// An error that is not SETTINGS_ERR_OPEN or SETTINGS_ERR_NOT_FOUND is printed on the repl. +settings_err_t settings_get_float(const char *key, mp_float_t *value); +#endif + +// Read a value from the settings file and return as parsed Python object. +// Returns SETTINGS_OK and sets value to a parsed Python object from the RHS value: +// - Quoted strings return as str +// - Bare "true" or "false" return as bool +// - Valid integers return as int +// - Valid floats (containing '.' or 'e'/'E') return as float +// Returns SETTINGS_ERR_... if the value is not parseable as one of these types. +// An error that is not SETTINGS_ERR_OPEN or SETTINGS_ERR_NOT_FOUND is printed on the repl. +settings_err_t settings_get_obj(const char *key, mp_obj_t *value); + +// Read the raw value as a string, whether quoted or bare. +// This is used by os.getenv() to always return strings. +// Does not print errors. +settings_err_t settings_get_raw_vstr(const char *key, vstr_t *vstr); diff --git a/supervisor/shared/status_bar.c b/supervisor/shared/status_bar.c index 8e32eee033e..0f7603bb408 100644 --- a/supervisor/shared/status_bar.c +++ b/supervisor/shared/status_bar.c @@ -5,6 +5,7 @@ // SPDX-License-Identifier: MIT #include +#include #include "genhdr/mpversion.h" #include "py/mpconfig.h" #include "shared-bindings/supervisor/__init__.h" @@ -15,13 +16,14 @@ #if CIRCUITPY_TERMINALIO #include "shared-module/terminalio/Terminal.h" +#include "supervisor/shared/display.h" #endif #if CIRCUITPY_WEB_WORKFLOW #include "supervisor/shared/web_workflow/web_workflow.h" #endif -#if CIRCUITPY_BLE_FILE_SERVICE || CIRCUITPY_SERIAL_BLE +#if CIRCUITPY_BLE_FILE_SERVICE || CIRCUITPY_BLE_SERIAL_SERVICE #include "supervisor/shared/bluetooth/bluetooth.h" #endif @@ -41,37 +43,8 @@ void supervisor_status_bar_clear(void) { } } -void supervisor_status_bar_update(void) { - if (_suspended) { - supervisor_status_bar_request_update(true); - return; - } - _forced_dirty = false; - - shared_module_supervisor_status_bar_updated(&shared_module_supervisor_status_bar_obj); - - // Disable status bar console writes if supervisor.status_bar.console is False. - // Also disable if there is no serial connection now. This avoids sending part - // of the status bar update if the serial connection comes up during the update. - bool disable_console_writes = - !shared_module_supervisor_status_bar_get_console(&shared_module_supervisor_status_bar_obj) || - !serial_connected(); - - // Disable status bar display writes if supervisor.status_bar.display is False. - bool disable_display_writes = - !shared_module_supervisor_status_bar_get_display(&shared_module_supervisor_status_bar_obj); - - // Suppress writes to console and/or display if status bar is not enabled for either or both. - bool prev_console_disable = false; - bool prev_display_disable = false; - - if (disable_console_writes) { - prev_console_disable = serial_console_write_disable(true); - } - if (disable_display_writes) { - prev_display_disable = serial_display_write_disable(true); - } - +// Write the title up to the version, with single spaces between segments. +static void write_title(void) { // Neighboring "..." "..." are concatenated by the compiler. Without this separation, the hex code // doesn't get terminated after two following characters and the value is invalid. // This is the OSC command to set the title and the icon text. It can be up to 255 characters @@ -85,28 +58,63 @@ void supervisor_status_bar_update(void) { #if CIRCUITPY_WEB_WORKFLOW supervisor_web_workflow_status(); - serial_write(" | "); + serial_write(" "); #endif - #if CIRCUITPY_BLE_FILE_SERVICE || CIRCUITPY_SERIAL_BLE + #if CIRCUITPY_BLE_FILE_SERVICE || CIRCUITPY_BLE_SERIAL_SERVICE supervisor_bluetooth_status(); - serial_write(" | "); + serial_write(" "); #endif supervisor_execution_status(); - serial_write(" | "); - serial_write(MICROPY_GIT_TAG); - // Send string terminator - serial_write("\x1b" "\\"); - - // Restore writes to console and/or display. - if (disable_console_writes) { - serial_console_write_disable(prev_console_disable); + serial_write(" "); +} + +void supervisor_status_bar_update(void) { + if (_suspended) { + supervisor_status_bar_request_update(true); + return; } - if (disable_display_writes) { - serial_display_write_disable(prev_display_disable); + _forced_dirty = false; + + shared_module_supervisor_status_bar_updated(&shared_module_supervisor_status_bar_obj); + + // Skip the console if supervisor.status_bar.console is False or there is no serial connection. + // This avoids sending part of the status bar update if the connection comes up during it. + if (shared_module_supervisor_status_bar_get_console(&shared_module_supervisor_status_bar_obj) && + serial_connected()) { + bool prev_display = serial_display_write_disable(true); + write_title(); + serial_write(MICROPY_GIT_TAG); + serial_write("\x1b" "\\"); + serial_display_write_disable(prev_display); } + #if CIRCUITPY_TERMINALIO + // Skip the display if supervisor.status_bar.display is False. A version that does not fit + // is cut so ".." is on the last two tiles. + displayio_tilegrid_t *bar = supervisor_terminal.status_bar; + if (bar != NULL && + shared_module_supervisor_status_bar_get_display(&shared_module_supervisor_status_bar_obj)) { + bool prev_console = serial_console_write_disable(true); + write_title(); + size_t room = bar->width_in_tiles - supervisor_terminal.status_x; + // The terminal moves status_y past the bar once the title reaches its last tile. + if (supervisor_terminal.status_y >= bar->height_in_tiles || room < 2) { + supervisor_terminal.status_x = bar->width_in_tiles - 2; + supervisor_terminal.status_y = 0; + room = 2; + } + if (room >= strlen(MICROPY_GIT_TAG)) { + serial_write(MICROPY_GIT_TAG); + } else { + serial_write_substring(MICROPY_GIT_TAG, room - 2); + serial_write(".."); + } + serial_write("\x1b" "\\"); + serial_console_write_disable(prev_console); + } + #endif } static void status_bar_background(void *data) { @@ -119,7 +127,7 @@ static void status_bar_background(void *data) { dirty = dirty || supervisor_web_workflow_status_dirty(); #endif - #if CIRCUITPY_BLE_FILE_SERVICE || CIRCUITPY_SERIAL_BLE + #if CIRCUITPY_BLE_FILE_SERVICE || CIRCUITPY_BLE_SERIAL_SERVICE dirty = dirty || supervisor_bluetooth_status_dirty(); #endif diff --git a/supervisor/shared/status_leds.c b/supervisor/shared/status_leds.c index 0742b6485eb..b73f5887fba 100644 --- a/supervisor/shared/status_leds.c +++ b/supervisor/shared/status_leds.c @@ -31,6 +31,8 @@ uint8_t rgb_status_brightness = 63; static uint64_t next_start_raw_ticks; static uint8_t status_neopixel_color[3 * MICROPY_HW_NEOPIXEL_COUNT]; static digitalio_digitalinout_obj_t status_neopixel; +// GRB sends G,R,B (most WS2812s). RGB sends R,G,B. +static status_neopixel_order_t status_neopixel_order = MICROPY_HW_NEOPIXEL_ORDER; #elif defined(MICROPY_HW_APA102_MOSI) && defined(MICROPY_HW_APA102_SCK) uint8_t rgb_status_brightness = 50; @@ -112,7 +114,7 @@ static uint32_t current_status_color = 0; #endif static bool status_led_init_in_progress = false; -void status_led_init() { +void status_led_init(void) { if (status_led_init_in_progress) { // Avoid recursion. return; @@ -133,9 +135,9 @@ void status_led_init() { memset(status_apa102_color + 4, 0xff, APA102_BUFFER_LENGTH - 4); #if CIRCUITPY_BITBANG_APA102 shared_module_bitbangio_spi_construct(&status_apa102, - MICROPY_HW_APA102_SCK, - MICROPY_HW_APA102_MOSI, - NULL); + MP_OBJ_FROM_PTR(MICROPY_HW_APA102_SCK), + MP_OBJ_FROM_PTR(MICROPY_HW_APA102_MOSI), + mp_const_none); #else if (!common_hal_busio_spi_deinited(&status_apa102)) { common_hal_busio_spi_deinit(&status_apa102); @@ -186,13 +188,13 @@ void status_led_init() { status_led_init_in_progress = false; } -void status_led_deinit() { +void status_led_deinit(void) { #ifdef MICROPY_HW_NEOPIXEL // Make sure the pin stays low for the reset period. The pin reset may pull // it up and stop the reset period. while (port_get_raw_ticks(NULL) < next_start_raw_ticks) { } - common_hal_reset_pin(MICROPY_HW_NEOPIXEL); + common_hal_digitalio_digitalinout_deinit(&status_neopixel); #elif defined(MICROPY_HW_APA102_MOSI) && defined(MICROPY_HW_APA102_SCK) #if CIRCUITPY_BITBANG_APA102 @@ -240,12 +242,12 @@ void new_status_color(uint32_t rgb) { status_neopixel_color[3 * i + 1] = (rgb_adjusted >> 16) & 0xff; status_neopixel_color[3 * i + 2] = rgb_adjusted & 0xff; - #ifdef MICROPY_HW_NEOPIXEL_ORDER_GRB - // Swap RG to GR - uint8_t temp = status_neopixel_color[3 * i + 0]; - status_neopixel_color[3 * i + 0] = status_neopixel_color[3 * i + 1]; - status_neopixel_color[3 * i + 1] = temp; - #endif + if (status_neopixel_order == STATUS_NEOPIXEL_ORDER_RGB) { + // Swap GR to RG + uint8_t temp = status_neopixel_color[3 * i + 0]; + status_neopixel_color[3 * i + 0] = status_neopixel_color[3 * i + 1]; + status_neopixel_color[3 * i + 1] = temp; + } } common_hal_neopixel_write(&status_neopixel, status_neopixel_color, 3 * MICROPY_HW_NEOPIXEL_COUNT); next_start_raw_ticks = port_get_raw_ticks(NULL) + 2; @@ -287,6 +289,14 @@ void new_status_color(uint32_t rgb) { #endif } +void status_led_set_neopixel_order(status_neopixel_order_t order) { + #ifdef MICROPY_HW_NEOPIXEL + status_neopixel_order = order; + #else + (void)order; + #endif +} + uint32_t color_brightness(uint32_t color, uint8_t brightness) { #if CIRCUITPY_STATUS_LED uint32_t result = ((color & 0xff0000) * brightness / 255) & 0xff0000; @@ -319,12 +329,10 @@ void init_rxtx_leds(void) { #if CIRCUITPY_DIGITALIO && defined(MICROPY_HW_LED_RX) common_hal_digitalio_digitalinout_construct(&rx_led, MICROPY_HW_LED_RX); common_hal_digitalio_digitalinout_switch_to_output(&rx_led, true, DRIVE_MODE_PUSH_PULL); - common_hal_digitalio_digitalinout_never_reset(&rx_led); #endif #if CIRCUITPY_DIGITALIO && defined(MICROPY_HW_LED_TX) common_hal_digitalio_digitalinout_construct(&tx_led, MICROPY_HW_LED_TX); common_hal_digitalio_digitalinout_switch_to_output(&tx_led, true, DRIVE_MODE_PUSH_PULL); - common_hal_digitalio_digitalinout_never_reset(&tx_led); #endif } diff --git a/supervisor/shared/status_leds.h b/supervisor/shared/status_leds.h index 1fd752d31fd..33f38a96d13 100644 --- a/supervisor/shared/status_leds.h +++ b/supervisor/shared/status_leds.h @@ -30,6 +30,19 @@ void status_led_init(void); void status_led_deinit(void); void new_status_color(uint32_t rgb); +typedef enum { + STATUS_NEOPIXEL_ORDER_GRB, + STATUS_NEOPIXEL_ORDER_RGB, +} status_neopixel_order_t; + +// Set the byte order sent to a status NeoPixel, for boards whose variants +// differ in LED order. STATUS_NEOPIXEL_ORDER_GRB sends G,R,B (most WS2812s). +// STATUS_NEOPIXEL_ORDER_RGB sends R,G,B. The default is MICROPY_HW_NEOPIXEL_ORDER. +// Only sets the order; call it from board_init(), and the next status_led_init() +// writes the LED with it. +// Does nothing on boards without MICROPY_HW_NEOPIXEL. +void status_led_set_neopixel_order(status_neopixel_order_t order); + uint32_t color_brightness(uint32_t color, uint8_t brightness); void set_status_brightness(uint8_t level); uint8_t get_status_brightness(void); diff --git a/supervisor/shared/tick.c b/supervisor/shared/tick.c index 24a06e622a1..a6fb814aa9f 100644 --- a/supervisor/shared/tick.c +++ b/supervisor/shared/tick.c @@ -23,10 +23,30 @@ #include "shared-module/displayio/__init__.h" #endif +#if CIRCUITPY_DISPLAYIO && CIRCUITPY_DISPLAYIO_LVGL && CIRCUITPY_VIDEOCORE +#include "shared-module/videocore/VideoBuffer.h" +#endif + #if CIRCUITPY_KEYPAD #include "shared-module/keypad/__init__.h" #endif +#if CIRCUITPY_AUDIOFILEWRITER +#include "shared-module/audiofilewriter/AudioFileWriter.h" +#endif + +#if CIRCUITPY_AIRLIFT && CIRCUITPY_SOCKETPOOL +#include "shared-module/_airlift/socketpool.h" +#endif + +#if CIRCUITPY_VIDEOGIF +#include "shared-module/videogif/GifDecoder.h" +#endif + +#if CIRCUITPY_WEB_WORKFLOW +#include "supervisor/shared/web_workflow/display_stream.h" +#endif + #include "shared-bindings/microcontroller/__init__.h" #if CIRCUITPY_WATCHDOG @@ -53,12 +73,25 @@ static void supervisor_background_tick(void *unused) { bleio_hci_background(); #endif - #if CIRCUITPY_DISPLAYIO + #if CIRCUITPY_DISPLAYIO && !CIRCUITPY_DISPLAYIO_LVGL + // The LVGL compositor renders on an RTOS thread of its own; nothing to pump here. displayio_background(); + #elif CIRCUITPY_DISPLAYIO && CIRCUITPY_DISPLAYIO_LVGL && CIRCUITPY_VIDEOCORE + // Video frames land in interrupt context, so repaint them here, from a + // normal background context, for the next LVGL render. + displayio_lvgl_video_background(); #endif filesystem_background(); + #if CIRCUITPY_AUDIOFILEWRITER + audiofilewriter_background(); + #endif + + #if CIRCUITPY_VIDEOGIF + videogif_background(); + #endif + port_background_tick(); assert_heap_ok(); @@ -82,41 +115,60 @@ void supervisor_tick(void) { keypad_tick(); #endif + #if CIRCUITPY_AIRLIFT && CIRCUITPY_SOCKETPOOL + airlift_socketpool_tick(); + #endif + + #if CIRCUITPY_WEB_WORKFLOW + display_stream_tick(); + #endif + background_callback_add(&tick_callback, supervisor_background_tick, NULL); } -uint64_t supervisor_ticks_ms64() { +static uint64_t _get_raw_subticks(void) { + uint64_t ticks; + uint8_t subticks; + ticks = port_get_raw_ticks(&subticks); + return (ticks << 5) | subticks; +} + +uint64_t supervisor_ticks_ms64(void) { uint64_t result; result = port_get_raw_ticks(NULL); result = result * 1000 / 1024; return result; } -uint32_t supervisor_ticks_ms32() { +uint32_t supervisor_ticks_ms32(void) { return supervisor_ticks_ms64(); } void mp_hal_delay_ms(mp_uint_t delay_ms) { - uint64_t start_tick = port_get_raw_ticks(NULL); - // Adjust the delay to ticks vs ms. - uint64_t delay_ticks = (delay_ms * (uint64_t)1024) / 1000; - uint64_t end_tick = start_tick + delay_ticks; - int64_t remaining = delay_ticks; + uint64_t start_subtick = _get_raw_subticks(); + // Convert delay from ms to subticks + uint64_t delay_subticks = (delay_ms * (uint64_t)32768) / 1000; + uint64_t end_subtick = start_subtick + delay_subticks; + int64_t remaining = delay_subticks; // Loop until we've waited long enough or we've been CTRL-Ced by autoreload // or the user. while (remaining > 0 && !mp_hal_is_interrupted()) { RUN_BACKGROUND_TASKS; - remaining = end_tick - port_get_raw_ticks(NULL); - // We break a bit early so we don't risk setting the alarm before the time when we call - // sleep. - if (remaining < 1) { + // Exit if interrupted while running background tasks + if (mp_hal_is_interrupted()) { break; } - port_interrupt_after_ticks(remaining); - // Idle until an interrupt happens. - port_idle_until_interrupt(); - remaining = end_tick - port_get_raw_ticks(NULL); + // Recalculate remaining delay after running background tasks + remaining = end_subtick - _get_raw_subticks(); + // If remaining delay is less than 1 tick, idle loop until end of delay + int64_t remaining_ticks = remaining / 32; + if (remaining_ticks > 0) { + port_interrupt_after_ticks(remaining_ticks); + // Idle until an interrupt happens. + port_idle_until_interrupt(); + } + remaining = end_subtick - _get_raw_subticks(); } } diff --git a/supervisor/shared/translate/compressed_string.h b/supervisor/shared/translate/compressed_string.h index 89dd75c22ae..7bfe2000b73 100644 --- a/supervisor/shared/translate/compressed_string.h +++ b/supervisor/shared/translate/compressed_string.h @@ -13,38 +13,41 @@ // The format of the compressed data is: // - the size of the uncompressed string in UTF-8 bytes, encoded as a // (compress_max_length_bits)-bit number. compress_max_length_bits is -// computed during dictionary generation time, and happens to be 8 -// for all current platforms. However, it'll probably end up being -// 9 in some translations sometime in the future. This length excludes +// computed during dictionary generation time, and is 8 for all +// current translations except ru, which needs 9. This length excludes // the trailing NUL, though notably decompress_length includes it. // -// - followed by the huffman encoding of the individual code -// points that make up the string. The trailing "\0" is not -// represented by a huffman code, but is implied by the length. -// (building the huffman encoding on UTF-16 code points gave better -// compression than building it on UTF-8 bytes) +// - followed by the huffman encoding of the symbols that make up the +// string. The trailing "\0" is not represented by a huffman code, but +// is implied by the length. // -// - If possible, the code points are represented as uint8_t values, with -// 0..127 representing themselves and 160..255 representing another range -// of Unicode, controlled by translation_offset and translation_offstart. -// If this is not possible, uint16_t values are used. At present, no translation -// requires code points not in the BMP, so this is adequate. +// - Each symbol is coded with one of TRANSLATION_CLASSES canonical Huffman +// tables, chosen by the class of the previously decoded byte: start of +// string or space, lowercase, uppercase, digit, '%', other, or >= 0x80. +// base_class() computes that seven-way class and class_map[] collapses it +// to a table index; the generator picks how many tables pay for themselves. +// The per-table code-length counts are rows of LENGTHS_ROW bytes in +// lengths[], and the symbols of table n are values[values_offset[n]..]. // -// - code points starting at 128 (word_start) and potentially extending -// to 255 (word_end) (but never interfering with the target -// language's used code points) stand for dictionary entries in a -// dictionary with size up to 256 code points. The dictionary entries -// are computed with a heuristic based on frequent substrings of 2 to -// 9 code points. These are called "words" but are not, grammatically -// speaking, words. They're just spans of code points that frequently -// occur together. They are ordered shortest to longest. +// - Symbol values 0..0x7F are ASCII (with 1, 2 and 3 reserved for the +// escapes below). Values from 0x80 up to 0x80 + alphabet_size - 1 are the +// most frequent non-ASCII characters used by the translation, renumbered +// by decreasing frequency; alphabet[] maps them back to Unicode code +// points. Most translations fit their whole non-ASCII repertoire in the +// alphabet. Those that don't (ja, ko) keep the 32 to 80 most frequent +// characters there and escape the rest: value 2 is followed by a +// rare_index_bits-bit index into rare_chars[] (characters used more than +// once), value 3 by a raw 16-bit code point (characters used once, which +// are cheaper without a table entry). All symbols are therefore 8 bits. +// At present, no translation requires code points outside the BMP, so +// this is adequate. // -// - If the translation uses a lot of code points or widely spaced code points, -// then the huffman table entries are UTF-16 code points. But if the translation -// uses only ASCII 7-bit code points plus a SMALL range of higher code points that -// still fit in 8 bits, translation_offset and translation_offstart are used to -// renumber the code points so that they still fit within 8 bits. (it's very beneficial -// for mchar_t to be 8 bits instead of 16!) +// - Symbol values from word_start to word_end stand for dictionary entries +// in a dictionary of up to 256 - word_start entries. The dictionary +// entries are computed with a heuristic based on frequent substrings of 2 +// to 11 symbols. These are called "words" but are not, grammatically +// speaking, words. They're just spans of symbols that frequently occur +// together. They are ordered shortest to longest. // // - dictionary entries are non-overlapping, and the _ending_ index of each // entry is stored in an array. A count of words of each length, from @@ -56,10 +59,11 @@ // - Value 1 ('\1') is used to indicate that a QSTR number follows. the // QSTR is encoded as a fixed number of bits (translation_qstr_bits), e.g., // 10 bits if the highest core qstr is from 512 to 1023 inclusive. -// (maketranslationdata uses a simple heuristic where any qstr >= 3 -// characters long is encoded in this way; this is simple but probably not -// optimal. In fact, the rule of >= 2 characters is better for SOME languages -// on SOME boards.) +// (maketranslationdata uses a simple heuristic where any qstr >= 4 +// characters long may be encoded in this way; whether a given occurrence +// is coded as a qstr or as characters is decided per occurrence by the +// parser, which picks the tokenization of each string that takes the +// fewest bits.) // // The "data" / "tail" construct is so that the struct's last member is a // "flexible array". However, the _only_ member is not permitted to be @@ -76,6 +80,26 @@ typedef struct compressed_string { const uint8_t tail[]; } const *mp_rom_error_text_t; +// Class of the previously decoded byte, which selects the Huffman table for +// the next symbol. Must match base_class() in py/maketranslationdata.py. +typedef enum { + CLASS_START_OR_SPACE = 0, + CLASS_LOWER = 1, + CLASS_UPPER = 2, + CLASS_DIGIT = 3, + CLASS_OTHER = 4, + CLASS_PERCENT = 5, + CLASS_NON_ASCII = 6, +} translation_class_t; + +// Symbol values with a special meaning; every other value is a character or a +// dictionary word. Must match py/maketranslationdata.py. +typedef enum { + SYMBOL_QSTR = 1, // followed by translation_qstr_bits bits of qstr index + SYMBOL_RARE_INDEX = 2, // followed by rare_index_bits bits of rare_chars[] index + SYMBOL_RARE_RAW = 3, // followed by a 16-bit code point +} translation_symbol_t; + // Return the compressed, translated version of a source string // Usually, due to LTO, this is optimized into a load of a constant // pointer. diff --git a/supervisor/shared/translate/translate.c b/supervisor/shared/translate/translate.c index 958e0a2144f..d0c05dda6e5 100644 --- a/supervisor/shared/translate/translate.c +++ b/supervisor/shared/translate/translate.c @@ -23,7 +23,7 @@ void serial_write_compressed(mp_rom_error_text_t compressed) { mp_printf(MP_PYTHON_PRINTER, "%S", compressed); } -static void get_word(int n, const mchar_t **pos, const mchar_t **end) { +static void get_word(int n, const uint8_t **pos, const uint8_t **end) { int len = minlen; int i = 0; *pos = words; @@ -37,14 +37,10 @@ static void get_word(int n, const mchar_t **pos, const mchar_t **end) { *end = *pos + len; } -static void put_utf8(vstr_t *vstr, int u) { - if (u >= translation_offstart) { - u += translation_offset; - } +static void put_utf8(vstr_t *vstr, unsigned u) { if (word_start <= u && u <= word_end) { - uint n = (u - word_start); - const mchar_t *pos, *end; - get_word(n, &pos, &end); + const uint8_t *pos, *end; + get_word(u - word_start, &pos, &end); // 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 @@ -53,9 +49,39 @@ static void put_utf8(vstr_t *vstr, int u) { } return; } + // alphabet_size is a compile-time constant; the test folds away when it is 0. + if (alphabet_size > 0 && u >= 0x80 && u < 0x80 + alphabet_size) { + u = alphabet[u - 0x80]; + } vstr_add_char(vstr, u); } +// The Huffman table used for the next symbol depends on the class of the last +// byte written. Classifying the last byte is the same as classifying the last +// code point: every byte of a multi-byte UTF-8 sequence is >= 0x80. +// This must match base_class() in py/maketranslationdata.py. +static translation_class_t base_class(uint8_t last) { + if (last == ' ') { + return CLASS_START_OR_SPACE; + } + if (last >= 'a' && last <= 'z') { + return CLASS_LOWER; + } + if (last >= 'A' && last <= 'Z') { + return CLASS_UPPER; + } + if (last >= '0' && last <= '9') { + return CLASS_DIGIT; + } + if (last == '%') { + return CLASS_PERCENT; + } + if (last >= 0x80) { + return CLASS_NON_ASCII; + } + return CLASS_OTHER; +} + uint16_t decompress_length(mp_rom_error_text_t compressed) { #ifndef NO_QSTR #if (compress_max_length_bits <= 8) @@ -99,23 +125,34 @@ static void decompress_vstr(mp_rom_error_text_t compressed, vstr_t *decompressed size_t alloc = decompressed->alloc - 1; // Stop one early because the last byte is always NULL. for (; decompressed->len < alloc;) { + // The start of a string is classed like a space. + uint8_t last = decompressed->len ? (uint8_t)decompressed->buf[decompressed->len - 1] : ' '; + uint8_t cls = class_map[base_class(last)]; + const uint8_t *len_row = lengths + cls * LENGTHS_ROW; + uint32_t bits = 0; uint8_t bit_length = 0; - uint32_t max_code = lengths[0]; - uint32_t searched_length = lengths[0]; + uint32_t max_code = len_row[0]; + uint32_t searched_length = len_row[0]; while (true) { bits = (bits << 1) | next_bit(&b); bit_length += 1; if (max_code > 0 && bits < max_code) { break; } - max_code = (max_code << 1) + lengths[bit_length]; - searched_length += lengths[bit_length]; + max_code = (max_code << 1) + len_row[bit_length]; + searched_length += len_row[bit_length]; } - int v = values[searched_length + bits - max_code]; - if (v == 1) { - qstr q = get_nbits(&b, translation_qstr_bits) + 1; // honestly no idea why "+1"... + unsigned v = values[values_offset[cls] + searched_length + bits - max_code]; + if (v == SYMBOL_QSTR) { + qstr q = get_nbits(&b, translation_qstr_bits); vstr_add_str(decompressed, qstr_str(q)); + } else if (rare_index_count > 0 && v == SYMBOL_RARE_INDEX) { + // A non-ASCII character outside the dense alphabet, by table index. + vstr_add_char(decompressed, rare_chars[get_nbits(&b, rare_index_bits)]); + } else if (rare_raw_count > 0 && v == SYMBOL_RARE_RAW) { + // A non-ASCII character used only once, as a raw code point. + vstr_add_char(decompressed, get_nbits(&b, 16)); } else { put_utf8(decompressed, v); } diff --git a/supervisor/shared/translate/translate_impl.h b/supervisor/shared/translate/translate_impl.h index 5139210db30..816292aa050 100644 --- a/supervisor/shared/translate/translate_impl.h +++ b/supervisor/shared/translate/translate_impl.h @@ -13,8 +13,8 @@ #include "supervisor/shared/translate/compressed_string.h" #ifndef NO_QSTR -#define QDEF0(id, hash, len, str) -#define QDEF1(id, hash, len, str) +#define QDEF0(id, hash, len, offset, str) +#define QDEF1(id, hash, len, offset, str) #define TRANSLATION(english_id, number) extern struct compressed_string translation##number; #include "genhdr/qstrdefs.generated.h" #undef QDEF0 @@ -34,8 +34,8 @@ __attribute__((always_inline)) // optimization. __attribute__((no_instrument_function)) mp_rom_error_text_t MP_COMPRESSED_ROM_TEXT(const char *original) { #ifndef NO_QSTR - #define QDEF0(id, hash, len, str) - #define QDEF1(id, hash, len, str) + #define QDEF0(id, hash, len, offset, str) + #define QDEF1(id, hash, len, offset, str) #define TRANSLATION(english_id, number) if (strcmp(original, english_id) == 0) { return (mp_rom_error_text_t)&translation##number; } else #include "genhdr/qstrdefs.generated.h" #undef TRANSLATION diff --git a/supervisor/shared/usb.c b/supervisor/shared/usb.c new file mode 100644 index 00000000000..3aa24e62675 --- /dev/null +++ b/supervisor/shared/usb.c @@ -0,0 +1,73 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2025 Scott Shawcroft for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "supervisor/usb.h" + +#if CIRCUITPY_STORAGE +#include "shared-module/storage/__init__.h" +#endif + +#if CIRCUITPY_USB_DEVICE +#include "shared-bindings/supervisor/__init__.h" + +#if CIRCUITPY_USB_CDC +#include "shared-module/usb_cdc/__init__.h" +#endif + +#if CIRCUITPY_USB_HID +#include "shared-module/usb_hid/__init__.h" +#endif + +#if CIRCUITPY_USB_MIDI +#include "shared-module/usb_midi/__init__.h" +#endif + +#if CIRCUITPY_USB_AUDIO +#include "shared-module/usb_audio/__init__.h" +#endif + +#if CIRCUITPY_USB_VIDEO +#include "shared-module/usb_video/__init__.h" +#endif +#endif + +// Set up USB defaults before any USB changes are made in boot.py +void usb_set_defaults(void) { + #if CIRCUITPY_USB_DEVICE + #if CIRCUITPY_STORAGE && CIRCUITPY_USB_MSC + storage_usb_set_defaults(); + #endif + + #if CIRCUITPY_USB_CDC + usb_cdc_set_defaults(); + #endif + + #if CIRCUITPY_USB_HID + usb_hid_set_defaults(); + #endif + + #if CIRCUITPY_USB_MIDI + usb_midi_set_defaults(); + #endif + #endif +}; + +// Call this when ready to run code.py or a REPL, and a VM has been started. +void usb_setup_with_vm(void) { + #if CIRCUITPY_USB_DEVICE + #if CIRCUITPY_USB_HID + usb_hid_setup_devices(); + #endif + + #if CIRCUITPY_USB_MIDI + usb_midi_setup_ports(); + #endif + + #if CIRCUITPY_USB_AUDIO + usb_audio_setup_singletons(); + #endif + #endif +} diff --git a/supervisor/shared/usb/host_keyboard.c b/supervisor/shared/usb/host_keyboard.c index f99b1e5c42a..566795091b9 100644 --- a/supervisor/shared/usb/host_keyboard.c +++ b/supervisor/shared/usb/host_keyboard.c @@ -28,6 +28,14 @@ static uint8_t _buf[16]; static uint8_t _dev_addr; static uint8_t _interface; +// A keyboard interface that is not boot-protocol, detected at mount time from +// its report descriptor. Composite HID devices (CircuitPython's usb_hid among +// them) present bInterfaceProtocol NONE and prefix each report with a report +// ID, so they fail the boot-protocol check in usb_keyboard_attach(). +static uint8_t _report_kbd_dev_addr; +static uint8_t _report_kbd_interface; +static uint8_t _report_kbd_report_id; + #define FLAG_SHIFT (1) #define FLAG_NUMLOCK (2) #define FLAG_CTRL (4) @@ -36,6 +44,26 @@ static uint8_t _interface; static uint8_t user_keymap[384]; static size_t user_keymap_len = 0; +// The TinyUSB callbacks below run in tuh_task(), which may be a task of its own, +// such as the espressif USB host task (CIRCUITPY_USB_HOST_TASK) or the MAX3421E +// task on espressif, while the VM reads keys, repeats them and attaches and +// detaches the keyboard. This lock keeps them apart. Nothing waits for TinyUSB +// while holding it. +#if OSAL_MUTEX_REQUIRED +static osal_mutex_def_t _lock_def; +static osal_mutex_t _lock; +#else +#define _lock NULL +#endif + +static void _lock_take(void) { + (void)osal_mutex_lock(_lock, OSAL_TIMEOUT_WAIT_FOREVER); +} + +static void _lock_give(void) { + (void)osal_mutex_unlock(_lock); +} + void usb_keymap_set(const uint8_t *buf, size_t len) { user_keymap_len = len = MIN(len, sizeof(user_keymap)); memcpy(user_keymap, buf, len); @@ -197,7 +225,9 @@ static void send_repeat(void) { } static void repeat_f(void *unused) { + _lock_take(); send_repeat(); + _lock_give(); } hid_keyboard_report_t old_report; @@ -298,7 +328,12 @@ static void process_event(uint8_t dev_addr, uint8_t instance, const hid_keyboard uint8_t leds = (caps | (num << 1)); if (leds != old_report.reserved) { - tuh_hid_set_report(dev_addr, instance /*idx*/, 0 /*report_id*/, HID_REPORT_TYPE_OUTPUT /*report_type*/, &leds, sizeof(leds)); + // A report-protocol keyboard needs its report ID on the LED output report too. + uint8_t report_id = 0; + if (dev_addr == _report_kbd_dev_addr && instance == _report_kbd_interface) { + report_id = _report_kbd_report_id; + } + tuh_hid_set_report(dev_addr, instance /*idx*/, report_id, HID_REPORT_TYPE_OUTPUT /*report_type*/, &leds, sizeof(leds)); } old_report = *report; old_report.reserved = leds; @@ -309,7 +344,9 @@ bool usb_keyboard_in_use(uint8_t dev_addr, uint8_t interface) { } void usb_keyboard_detach(uint8_t dev_addr, uint8_t interface) { + _lock_take(); if (!usb_keyboard_in_use(dev_addr, interface)) { + _lock_give(); return; } // No more key repeats @@ -318,53 +355,111 @@ void usb_keyboard_detach(uint8_t dev_addr, uint8_t interface) { tuh_hid_receive_abort(dev_addr, interface); _dev_addr = 0; _interface = 0; + _lock_give(); supervisor_status_bar_request_update(false); } void usb_keyboard_attach(uint8_t dev_addr, uint8_t interface) { + _lock_take(); if (usb_keyboard_in_use(dev_addr, interface) || _dev_addr != 0) { + _lock_give(); return; } uint8_t const itf_protocol = tuh_hid_interface_protocol(dev_addr, interface); - if (itf_protocol == HID_ITF_PROTOCOL_KEYBOARD) { + bool is_boot_keyboard = itf_protocol == HID_ITF_PROTOCOL_KEYBOARD; + // Detected at mount time by tuh_hid_mount_cb(). Device addresses start at + // 1, so a zeroed _report_kbd_dev_addr never matches. + bool is_report_keyboard = dev_addr == _report_kbd_dev_addr && interface == _report_kbd_interface; + if (is_boot_keyboard || is_report_keyboard) { _dev_addr = dev_addr; _interface = interface; tuh_hid_receive_report(dev_addr, interface); } + _lock_give(); supervisor_status_bar_request_update(false); } void tuh_hid_mount_cb(uint8_t dev_addr, uint8_t interface, uint8_t const *desc_report, uint16_t desc_len) { + // A non-boot interface can still be a keyboard, using report protocol. + // Find keyboard usage in its report descriptor so that we poll it too. + // Otherwise its interrupt IN endpoint is never drained, and a CircuitPython + // device plugged into us raises OSError("USB busy") on its second + // send_report() (#10721). + _lock_take(); + if (tuh_hid_interface_protocol(dev_addr, interface) == HID_ITF_PROTOCOL_NONE && + _report_kbd_dev_addr == 0) { + tuh_hid_report_info_t report_info[8]; + uint8_t report_count = + tuh_hid_parse_report_descriptor(report_info, TU_ARRAY_SIZE(report_info), desc_report, desc_len); + for (uint8_t i = 0; i < report_count; i++) { + if (report_info[i].usage_page == HID_USAGE_PAGE_DESKTOP && + report_info[i].usage == HID_USAGE_DESKTOP_KEYBOARD) { + _report_kbd_dev_addr = dev_addr; + _report_kbd_interface = interface; + _report_kbd_report_id = report_info[i].report_id; + break; + } + } + } + _lock_give(); usb_keyboard_attach(dev_addr, interface); } void tuh_hid_umount_cb(uint8_t dev_addr, uint8_t interface) { + _lock_take(); + if (dev_addr == _report_kbd_dev_addr && interface == _report_kbd_interface) { + _report_kbd_dev_addr = 0; + _report_kbd_interface = 0; + _report_kbd_report_id = 0; + } + _lock_give(); usb_keyboard_detach(dev_addr, interface); } void tuh_hid_report_received_cb(uint8_t dev_addr, uint8_t instance, uint8_t const *report, uint16_t len) { - if (len != sizeof(hid_keyboard_report_t)) { - return; - } else { + _lock_take(); + if (len == sizeof(hid_keyboard_report_t)) { process_event(dev_addr, instance, (hid_keyboard_report_t *)report); + } else if (dev_addr == _report_kbd_dev_addr && instance == _report_kbd_interface && + _report_kbd_report_id != 0 && + len == sizeof(hid_keyboard_report_t) + 1 && + report[0] == _report_kbd_report_id) { + // Report-protocol keyboards prefix the report with its report ID. + process_event(dev_addr, instance, (const hid_keyboard_report_t *)(report + 1)); } - // continue to request to receive report + _lock_give(); + // Always request the next report, even when this one wasn't a keyboard + // report we understand (a mouse or consumer control report ID from a + // composite device, for instance), so that the device's endpoint keeps + // draining and polling doesn't stop. tuh_hid_receive_report(dev_addr, instance); } void usb_keyboard_init(void) { + #if OSAL_MUTEX_REQUIRED + // This runs once, at startup. + _lock = osal_mutex_create(&_lock_def); + #endif + _lock_take(); ringbuf_init(&_incoming_ringbuf, _buf, sizeof(_buf)); + _lock_give(); } uint32_t usb_keyboard_chars_available(void) { - return ringbuf_num_filled(&_incoming_ringbuf); + _lock_take(); + uint32_t count = ringbuf_num_filled(&_incoming_ringbuf); + _lock_give(); + return count; } char usb_keyboard_read_char(void) { + char c = -1; + _lock_take(); if (ringbuf_num_filled(&_incoming_ringbuf) > 0) { - return ringbuf_get(&_incoming_ringbuf); + c = ringbuf_get(&_incoming_ringbuf); } - return -1; + _lock_give(); + return c; } void usb_keyboard_status(void) { diff --git a/supervisor/shared/usb/tusb_config.h b/supervisor/shared/usb/tusb_config.h index ce39925f45b..5e7f9265e7a 100644 --- a/supervisor/shared/usb/tusb_config.h +++ b/supervisor/shared/usb/tusb_config.h @@ -79,24 +79,21 @@ extern "C" { #if CIRCUITPY_USB_DEVICE -#if CIRCUITPY_USB_DEVICE_INSTANCE == 0 -#if USB_HIGHSPEED -#define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) +#if CIRCUITPY_USB_DEVICE_HIGH_SPEED == 1 +#define _DEVICE_SPEED OPT_MODE_HIGH_SPEED #else -#define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE) +#define _DEVICE_SPEED 0 #endif + +#if CIRCUITPY_USB_DEVICE_INSTANCE == 0 +#define CFG_TUSB_RHPORT0_MODE (OPT_MODE_DEVICE | _DEVICE_SPEED) #elif CIRCUITPY_USB_DEVICE_INSTANCE == 1 -#if USB_HIGHSPEED -#define CFG_TUSB_RHPORT1_MODE (OPT_MODE_DEVICE | OPT_MODE_HIGH_SPEED) -#else -#define CFG_TUSB_RHPORT1_MODE (OPT_MODE_DEVICE) -#endif +#define CFG_TUSB_RHPORT1_MODE (OPT_MODE_DEVICE | _DEVICE_SPEED) #endif // Use DMA with the USB peripheral. #if defined(CONFIG_IDF_TARGET_ESP32P4) || defined(CONFIG_IDF_TARGET_ESP32S2) || defined(CONFIG_IDF_TARGET_ESP32S3) #define CFG_TUD_DWC2_DMA_ENABLE (1) -#define CFG_TUH_DWC2_DMA_ENABLE (1) #endif // Vendor name included in Inquiry response, max 8 bytes @@ -117,8 +114,33 @@ extern "C" { #define CFG_TUD_HID CIRCUITPY_USB_HID #define CFG_TUD_MIDI CIRCUITPY_USB_MIDI #define CFG_TUD_VENDOR CIRCUITPY_USB_VENDOR +#define CFG_TUD_AUDIO CIRCUITPY_USB_AUDIO #define CFG_TUD_CUSTOM_CLASS 0 +// ------------- AUDIO CLASS (UAC2 microphone) -------------// +#if CIRCUITPY_USB_AUDIO +#include "shared-module/usb_audio/usb_audio_descriptors.h" + +// EP0 buffer for class-specific control requests (sample-freq range, volume range, ...). +#define CFG_TUD_AUDIO_CTRL_BUF_SZ 64 + +#define CFG_TUD_AUDIO_ENABLE_EP_IN 1 +// wMaxPacketSize, sized for the highest supported sample rate. +#define CFG_TUD_AUDIO_FUNC_1_EP_IN_SZ_MAX TUD_AUDIO_EP_SIZE(TUD_OPT_HIGH_SPEED, USB_AUDIO_MAX_SAMPLE_RATE, USB_AUDIO_N_BYTES_PER_SAMPLE, USB_AUDIO_N_CHANNELS) +// Deep software FIFO so the 1 ms refill keeps clear of the underrun floor. +#define CFG_TUD_AUDIO_FUNC_1_EP_IN_SW_BUF_SZ (16 * CFG_TUD_AUDIO_FUNC_1_EP_IN_SZ_MAX) + +// OUT endpoint (host -> board speaker). Compiled into the class driver +// unconditionally; whether it actually enumerates is decided by the emitted +// descriptor (still mic-only until the speaker descriptor lands). Mirrors the +// IN sizing above. +#define CFG_TUD_AUDIO_ENABLE_EP_OUT 1 +// wMaxPacketSize, sized for the highest supported sample rate. +#define CFG_TUD_AUDIO_FUNC_1_EP_OUT_SZ_MAX TUD_AUDIO_EP_SIZE(TUD_OPT_HIGH_SPEED, USB_AUDIO_MAX_SAMPLE_RATE, USB_AUDIO_N_BYTES_PER_SAMPLE, USB_AUDIO_N_CHANNELS) +// Deep software FIFO so the 1 ms drain keeps clear of the overrun ceiling. +#define CFG_TUD_AUDIO_FUNC_1_EP_OUT_SW_BUF_SZ (16 * CFG_TUD_AUDIO_FUNC_1_EP_OUT_SZ_MAX) +#endif + /*------------------------------------------------------------------*/ /* CLASS DRIVER *------------------------------------------------------------------*/ @@ -150,6 +172,10 @@ extern "C" { #if CIRCUITPY_USB_HOST || CIRCUITPY_MAX3421E #define CFG_TUH_ENABLED 1 +#if defined(CONFIG_IDF_TARGET_ESP32P4) +#define CFG_TUH_DWC2_DMA_ENABLE (1) +#endif + // Always use PIO to do host on RP2. #if !CIRCUITPY_MAX3421E #define CFG_TUH_RPI_PIO_USB 1 @@ -157,23 +183,23 @@ extern "C" { #define CFG_TUH_RPI_PIO_USB 1 #endif -#if CIRCUITPY_USB_HOST_INSTANCE == 0 -#if USB_HIGHSPEED -#define CFG_TUSB_RHPORT0_MODE (OPT_MODE_HOST | OPT_MODE_HIGH_SPEED) +#if CIRCUITPY_USB_DEVICE_HIGH_SPEED == 1 || (defined(CONFIG_IDF_TARGET_ESP32P4) && CIRCUITPY_USB_HOST_INSTANCE == 1) || defined(CONFIG_IDF_TARGET_ESP32S31) +#define _HOST_SPEED OPT_MODE_HIGH_SPEED #else -#define CFG_TUSB_RHPORT0_MODE (OPT_MODE_HOST) +#define _HOST_SPEED 0 #endif + +#if CIRCUITPY_USB_HOST_INSTANCE == 0 +#define CFG_TUSB_RHPORT0_MODE (OPT_MODE_HOST | _HOST_SPEED) #elif CIRCUITPY_USB_HOST_INSTANCE == 1 -#if USB_HIGHSPEED -#define CFG_TUSB_RHPORT1_MODE (OPT_MODE_HOST | OPT_MODE_HIGH_SPEED) -#else -#define CFG_TUSB_RHPORT1_MODE (OPT_MODE_HOST) -#endif +#define CFG_TUSB_RHPORT1_MODE (OPT_MODE_HOST | _HOST_SPEED) #endif // Size of buffer to hold descriptors and other data used for enumeration +// CircuitPython itself is 284 bytes of configuration descriptor when both CDC endpoints are +// enabled, plus 4 bytes for alignment. #ifndef CFG_TUH_ENUMERATION_BUFSIZE -#define CFG_TUH_ENUMERATION_BUFSIZE 256 +#define CFG_TUH_ENUMERATION_BUFSIZE (284 + 4) #endif #if CIRCUITPY_USB_KEYBOARD_WORKFLOW @@ -187,7 +213,6 @@ extern "C" { #define CFG_TUH_HUB 2 #define CFG_TUH_CDC 0 #define CFG_TUH_MSC 0 -#define CFG_TUH_VENDOR 0 #define CFG_TUH_API_EDPT_XFER 1 // max device support (excluding hub device) @@ -205,6 +230,7 @@ extern "C" { #define nrf52_errata_187 errata_187 #define nrf52_errata_171 errata_171 #define nrf52_errata_166 errata_166 +#define nrf52_errata_199 errata_199 #ifdef __cplusplus } diff --git a/supervisor/shared/usb/usb.c b/supervisor/shared/usb/usb.c index e67c15d022c..fa8245ae6b2 100644 --- a/supervisor/shared/usb/usb.c +++ b/supervisor/shared/usb/usb.c @@ -7,6 +7,7 @@ #include "py/objstr.h" #include "supervisor/background_callback.h" #include "supervisor/linker.h" +#include "supervisor/port.h" #include "supervisor/shared/tick.h" #include "supervisor/usb.h" #include "shared/readline/readline.h" @@ -38,10 +39,18 @@ #include "shared-module/usb_video/__init__.h" #endif +#if CIRCUITPY_USB_AUDIO +#include "shared-module/usb_audio/__init__.h" +#endif + #endif #include "tusb.h" +#if CIRCUITPY_MAX3421E +#include "shared-module/max3421e/Max3421E.h" +#endif + #if CFG_TUSB_OS == OPT_OS_ZEPHYR #include int CFG_TUSB_DEBUG_PRINTF(const char *format, ...) { @@ -87,6 +96,14 @@ bool usb_enabled(void) { return tusb_inited(); } +bool usb_connected(void) { + #if CIRCUITPY_TINYUSB && CIRCUITPY_USB_DEVICE + return tud_ready(); + #else + return false; + #endif +} + MP_WEAK void post_usb_init(void) { } @@ -144,51 +161,27 @@ void usb_init(void) { #endif } -// Set up USB defaults before any USB changes are made in boot.py -void usb_set_defaults(void) { - #if CIRCUITPY_USB_DEVICE - #if CIRCUITPY_STORAGE && CIRCUITPY_USB_MSC - storage_usb_set_defaults(); - #endif - - #if CIRCUITPY_USB_CDC - usb_cdc_set_defaults(); - #endif - - #if CIRCUITPY_USB_HID - usb_hid_set_defaults(); - #endif - - #if CIRCUITPY_USB_MIDI - usb_midi_set_defaults(); - #endif - #endif -}; - -// Call this when ready to run code.py or a REPL, and a VM has been started. -void usb_setup_with_vm(void) { - #if CIRCUITPY_USB_DEVICE - #if CIRCUITPY_USB_HID - usb_hid_setup_devices(); - #endif - - #if CIRCUITPY_USB_MIDI - usb_midi_setup_ports(); - #endif - #endif -} - void usb_background(void) { if (usb_enabled()) { #if CFG_TUSB_OS == OPT_OS_NONE || CFG_TUSB_OS == OPT_OS_PICO tud_task(); - #if CIRCUITPY_USB_HOST || CIRCUITPY_MAX3421E + #if CIRCUITPY_MAX3421E + if (max3421e_spi_busy()) { + usb_background_schedule(); // try again once the bus is free + } else { + tuh_task(); + } + #elif CIRCUITPY_USB_HOST tuh_task(); #endif #elif CFG_TUSB_OS == OPT_OS_FREERTOS - // Yield to FreeRTOS in case TinyUSB runs in a separate task. Don't use - // port_yield() because it has a longer delay. - vTaskDelay(0); + // TinyUSB may run in a separate task, at the same priority as CircuitPython. + port_task_yield(); + #if CIRCUITPY_USB_HOST && !CIRCUITPY_USB_HOST_TASK + if (tuh_inited()) { + tuh_task_ext(0, false); + } + #endif #endif // No need to flush if there's no REPL. #if CIRCUITPY_USB_DEVICE && CIRCUITPY_USB_CDC @@ -200,10 +193,16 @@ void usb_background(void) { #if CIRCUITPY_USB_DEVICE && CIRCUITPY_USB_VIDEO usb_video_task(); #endif + #if CIRCUITPY_USB_DEVICE && CIRCUITPY_USB_AUDIO + usb_audio_task(); + #endif } } -uint32_t tusb_time_millis_api(void) { +// Ports may override this with a RAM-resident version when TinyUSB code that +// calls it must not execute from flash (e.g. raspberrypi polls +// tuh_task_event_ready(), which calls this, from core1). +MP_WEAK uint32_t tusb_time_millis_api(void) { return supervisor_ticks_ms32(); } diff --git a/supervisor/shared/usb/usb_desc.c b/supervisor/shared/usb/usb_desc.c index 9427171fe9b..56a4dd6af40 100644 --- a/supervisor/shared/usb/usb_desc.c +++ b/supervisor/shared/usb/usb_desc.c @@ -32,6 +32,10 @@ #include "shared-module/usb_video/__init__.h" #endif +#if CIRCUITPY_USB_AUDIO +#include "shared-module/usb_audio/__init__.h" +#endif + #include "shared-bindings/microcontroller/Processor.h" @@ -45,6 +49,8 @@ typedef union { } interface_string_t; static interface_string_t collected_interface_strings[MAX_INTERFACE_STRINGS]; +// Bit n set: string n is a suffix to put after USB_INTERFACE_NAME and a space. +static uint32_t prefixed_interface_strings; static size_t collected_interface_strings_length; static uint8_t current_interface_string; @@ -170,6 +176,12 @@ static bool usb_build_configuration_descriptor(void) { } #endif + #if CIRCUITPY_USB_AUDIO + if (usb_audio_enabled()) { + total_descriptor_length += usb_audio_descriptor_length(); + } + #endif + // Now we know how big the configuration descriptor will be, so we can allocate space for it. configuration_descriptor = (uint8_t *)port_malloc(total_descriptor_length, @@ -259,6 +271,13 @@ static bool usb_build_configuration_descriptor(void) { descriptor_buf_remaining, &descriptor_counts, ¤t_interface_string); } #endif + + #if CIRCUITPY_USB_AUDIO + if (usb_audio_enabled()) { + descriptor_buf_remaining += usb_audio_add_descriptor( + descriptor_buf_remaining, &descriptor_counts, ¤t_interface_string); + } + #endif // Now we know how many interfaces have been used. configuration_descriptor[CONFIG_NUM_INTERFACES_INDEX] = descriptor_counts.current_interface; @@ -272,20 +291,37 @@ static bool usb_build_configuration_descriptor(void) { } // str must not be on the heap. -void usb_add_interface_string(uint8_t interface_string_index, const char str[]) { +void usb_add_interface_name(uint8_t interface_string_index, const char *custom_name, const char *default_suffix) { if (interface_string_index > MAX_INTERFACE_STRINGS) { reset_into_safe_mode(SAFE_MODE_USB_TOO_MANY_INTERFACE_NAMES); } + const char *str = custom_name; + if (str == NULL) { + str = default_suffix; + prefixed_interface_strings |= 1u << interface_string_index; + collected_interface_strings_length += sizeof(USB_INTERFACE_NAME " ") - 1; + } collected_interface_strings[interface_string_index].char_str = str; collected_interface_strings_length += strlen(str); } +void usb_add_interface_string(uint8_t interface_string_index, const char str[]) { + usb_add_interface_name(interface_string_index, str, NULL); +} + static const uint16_t language_id[] = { 0x0304, 0x0409, }; +static uint16_t *ascii_to_le16(uint16_t *dest, const char *str) { + while (*str) { + *dest++ = *str++; + } + return dest; +} + static bool usb_build_interface_string_table(void) { // Allocate space for the le16 String descriptors. // Space needed is 2 bytes for String Descriptor header, then 2 bytes for each character @@ -305,22 +341,20 @@ static bool usb_build_interface_string_table(void) { // Start at 1 to skip the Language ID. for (uint8_t string_index = 1; string_index < current_interface_string; string_index++) { const char *str = collected_interface_strings[string_index].char_str; - const size_t str_len = strlen(str); - // 1 word for descriptor type and length, 1 word for each character. - const uint8_t descriptor_size_words = 1 + str_len; - const uint8_t descriptor_size_bytes = descriptor_size_words * 2; - string_descriptor[0] = 0x0300 | descriptor_size_bytes; - - // Convert to le16. - for (size_t i = 0; i < str_len; i++) { - string_descriptor[i + 1] = str[i]; + // Convert to le16 after 1 word for descriptor type and length. + uint16_t *end = string_descriptor + 1; + if (prefixed_interface_strings & (1u << string_index)) { + end = ascii_to_le16(end, USB_INTERFACE_NAME " "); } + end = ascii_to_le16(end, str); + const uint8_t descriptor_size_bytes = (end - string_descriptor) * 2; + string_descriptor[0] = 0x0300 | descriptor_size_bytes; // Save ptr to string descriptor with le16 str. collected_interface_strings[string_index].descriptor = string_descriptor; // Move to next descriptor slot. - string_descriptor += descriptor_size_words; + string_descriptor = end; } return true; } @@ -341,6 +375,7 @@ bool usb_build_descriptors(const usb_identification_t *identification) { serial_number_hex_string[sizeof(serial_number_hex_string) - 1] = '\0'; current_interface_string = 1; + prefixed_interface_strings = 0; collected_interface_strings_length = 0; return usb_build_device_descriptor(identification) && diff --git a/supervisor/shared/usb/usb_device.c b/supervisor/shared/usb/usb_device.c index ec08b8bf4d7..e3f1a0d4e26 100644 --- a/supervisor/shared/usb/usb_device.c +++ b/supervisor/shared/usb/usb_device.c @@ -156,7 +156,7 @@ bool tud_vendor_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_requ // size. Setting CFG_TUD_CDC_RX_BUFSIZE to the endpoint size and then sending // any character will prevent ctrl-c from working. Require at least a 64 // character buffer. -#if CFG_TUD_CDC_RX_BUFSIZE < CFG_TUD_CDC_EP_BUFSIZE + 64 +#if CFG_TUD_CDC_RX_BUFSIZE < CFG_TUD_CDC_RX_EPSIZE + 64 #error "CFG_TUD_CDC_RX_BUFSIZE must be 64 bytes bigger than endpoint size." #endif @@ -166,6 +166,9 @@ bool tud_vendor_control_xfer_cb(uint8_t rhport, uint8_t stage, tusb_control_requ * @param wanted_char The wanted char (set previously) */ void tud_cdc_rx_wanted_cb(uint8_t itf, char wanted_char) { + // CircuitPython's VM is run in a separate FreeRTOS task from TinyUSB on ESP. + // So, we must notify the other task when a CTRL-C is received. + port_wake_main_task(); // Workaround for using shared/runtime/interrupt_char.c // Compare mp_interrupt_char with wanted_char and ignore if not matched if (mp_interrupt_char == wanted_char) { @@ -177,7 +180,14 @@ void tud_cdc_rx_wanted_cb(uint8_t itf, char wanted_char) { void tud_cdc_send_break_cb(uint8_t itf, uint16_t duration_ms) { if (usb_cdc_console_enabled() && mp_interrupt_char != -1 && itf == 0 && duration_ms > 0) { mp_sched_keyboard_interrupt(); + port_wake_main_task(); } } +void tud_cdc_rx_cb(uint8_t itf) { + (void)itf; + // Workaround for "press any key to enter REPL" response being delayed on espressif. + // Wake main task when any key is pressed. + port_wake_main_task(); +} #endif diff --git a/supervisor/shared/usb/usb_msc_flash.c b/supervisor/shared/usb/usb_msc_flash.c index c7a8232d228..5d97d3eb6e4 100644 --- a/supervisor/shared/usb/usb_msc_flash.c +++ b/supervisor/shared/usb/usb_msc_flash.c @@ -5,31 +5,62 @@ // SPDX-License-Identifier: MIT #include "tusb.h" -// // #include "supervisor/flash.h" // For updating fatfs's cache #include "extmod/vfs.h" #include "extmod/vfs_fat.h" #include "lib/oofatfs/diskio.h" #include "lib/oofatfs/ff.h" +#include "py/gc.h" #include "py/mpstate.h" +#include "py/runtime.h" +#include "shared-bindings/microcontroller/__init__.h" +#include "shared-bindings/storage/__init__.h" #include "shared-module/storage/__init__.h" #include "supervisor/filesystem.h" #include "supervisor/shared/reload.h" +#include "supervisor/shared/settings.h" #define MSC_FLASH_BLOCK_SIZE 512 #if CIRCUITPY_SAVES_PARTITION_SIZE > 0 -#define LUN_COUNT 2 +#define SAVES_COUNT 1 +#define SAVES_LUN (1) #else -#define LUN_COUNT 1 +#define SAVES_COUNT 0 #endif +#if CIRCUITPY_SDCARD_USB +#include "shared-module/sdcardio/__init__.h" + +#define SDCARD_COUNT 1 +#define SDCARD_LUN (1 + SAVES_COUNT) +#else +#define SDCARD_COUNT 0 +#endif + +#if CIRCUITPY_EMMC_USB +#include "shared-module/emmcio/__init__.h" + +#define EMMC_COUNT 1 +#define EMMC_LUN (1 + SAVES_COUNT + SDCARD_COUNT) +#else +#define EMMC_COUNT 0 +#endif + +#define LUN_COUNT (1 + SAVES_COUNT + SDCARD_COUNT + EMMC_COUNT) + // The ellipsis range in the designated initializer of `ejected` is not standard C, // but it works in both gcc and clang. static bool ejected[LUN_COUNT] = { [0 ... (LUN_COUNT - 1)] = true}; -static bool locked[LUN_COUNT] = {false}; +static bool eject_once[LUN_COUNT] = { [0 ... (LUN_COUNT - 1)] = false}; +static bool locked[LUN_COUNT] = { [0 ... (LUN_COUNT - 1)] = false}; + +// Set to true if a write was in a file data or metadata area, +// as opposed to in the filesystem metadata area (e.g., dirty bit). +// Used to determine if an auto-reload is warranted. +static bool content_write[LUN_COUNT] = { [0 ... (LUN_COUNT - 1)] = false}; #include "tusb.h" @@ -53,7 +84,7 @@ static const uint8_t usb_msc_descriptor_template[] = { 0xFF, // 11 bEndpointAddress (IN/D2H) [SET AT RUNTIME: 0x80 | number] #define MSC_IN_ENDPOINT_INDEX (11) 0x02, // 12 bmAttributes (Bulk) - #if USB_HIGHSPEED + #if CIRCUITPY_USB_DEVICE_HIGH_SPEED == 1 0x00, 0x02, // 13,14 wMaxPacketSize 512 #else 0x40, 0x00, // 13,14 wMaxPacketSize 64 @@ -66,7 +97,7 @@ static const uint8_t usb_msc_descriptor_template[] = { 0xFF, // 18 bEndpointAddress (OUT/H2D) [SET AT RUNTIME] #define MSC_OUT_ENDPOINT_INDEX (18) 0x02, // 19 bmAttributes (Bulk) - #if USB_HIGHSPEED + #if CIRCUITPY_USB_DEVICE_HIGH_SPEED == 1 0x00, 0x02, // 20,21 wMaxPacketSize 512 #else 0x40, 0x00, // 20,21 wMaxPacketSize 64 @@ -78,7 +109,7 @@ size_t usb_msc_descriptor_length(void) { return sizeof(usb_msc_descriptor_template); } -static const char storage_interface_name[] = USB_INTERFACE_NAME " Mass Storage"; +static const char storage_interface_name[] = "Mass Storage"; size_t usb_msc_add_descriptor(uint8_t *descriptor_buf, descriptor_counts_t *descriptor_counts, uint8_t *current_interface_string) { memcpy(descriptor_buf, usb_msc_descriptor_template, sizeof(usb_msc_descriptor_template)); @@ -98,80 +129,184 @@ size_t usb_msc_add_descriptor(uint8_t *descriptor_buf, descriptor_counts_t *desc descriptor_counts->num_out_endpoints++; descriptor_counts->current_endpoint++; - usb_add_interface_string(*current_interface_string, storage_interface_name); + usb_add_interface_name(*current_interface_string, NULL, storage_interface_name); descriptor_buf[MSC_INTERFACE_STRING_INDEX] = *current_interface_string; (*current_interface_string)++; return sizeof(usb_msc_descriptor_template); } -// The root FS is always at the end of the list. +// We hardcode LUN -> mount mapping so that it doesn't changes with saves and +// SD card appearing and disappearing. static fs_user_mount_t *get_vfs(int lun) { - // Keep a history of the mounts we pass so we can search back. - mp_vfs_mount_t *mounts[LUN_COUNT]; - mp_vfs_mount_t *current_mount = MP_STATE_VM(vfs_mount_table); - if (current_mount == NULL) { - return NULL; - } - // i is the last entry filled - size_t i = 0; - mounts[i] = current_mount; - while (current_mount->next != NULL) { - current_mount = current_mount->next; - i = (i + 1) % LUN_COUNT; - mounts[i] = current_mount; - } - fs_user_mount_t *vfs = mounts[(i - lun) % LUN_COUNT]->obj; - return vfs; + supervisor_vfs_t *root_vfs = filesystem_circuitpy(); + fs_user_mount_t *root = root_vfs == NULL ? NULL : &root_vfs->fat; + if (lun == 0) { + return root; + } + // Other filesystems must be native because we don't guard against exceptions. + // They must also be off the VM heap so they don't disappear on autoreload. + #ifdef SAVES_LUN + if (lun == SAVES_LUN) { + const char *path_under_mount; + supervisor_vfs_t *saves_mount = filesystem_for_path("/saves", &path_under_mount); + fs_user_mount_t *saves = saves_mount == NULL ? NULL : &saves_mount->fat; + if (saves != root && + (saves->blockdev.flags & MP_BLOCKDEV_FLAG_NATIVE) != 0 && !gc_ptr_on_heap(saves)) { + return saves; + } + } + #endif + #ifdef SDCARD_LUN + if (lun == SDCARD_LUN) { + const char *path_under_mount; + supervisor_vfs_t *sdcard_mount = filesystem_for_path("/sd", &path_under_mount); + fs_user_mount_t *sdcard = sdcard_mount == NULL ? NULL : &sdcard_mount->fat; + // If sdcard ("/sd") is on the root filesystem, nothing has been mounted there, so don't + // return it as a separate filesystem. + // If the SD card was automounted at startup, then it persists across VMs and its fs_user_mount_t is + // not on the heap. + // If the SD card filesystem was mounted by the user using heap objects, + // it should not be used when the VM has stopped running. + if ((sdcard != root) && + ((sdcard->blockdev.flags & MP_BLOCKDEV_FLAG_NATIVE) != 0) && + (vm_is_running() || !gc_ptr_on_heap(sdcard))) { + return sdcard; + } else { + // Clear any ejected state so that a re-insert causes it to reappear. + ejected[SDCARD_LUN] = false; + locked[SDCARD_LUN] = false; + } + } + #endif + #ifdef EMMC_LUN + if (lun == EMMC_LUN) { + const char *path_under_mount; + fs_user_mount_t *emmc; + + supervisor_vfs_t *emmc_mount = filesystem_for_path(CIRCUITPY_EMMC_MOUNT_PATH, &path_under_mount); + emmc = emmc_mount == NULL ? NULL : &emmc_mount->fat; + // Unlike the SD card there is no heap-mount case to allow: the eMMC's + // drive exists only when the supervisor mounted it, and + // that mount is static. A user mount made by code.py stays a Python + // filesystem and never becomes a LUN. + if (emmc != root && + ((emmc->blockdev.flags & MP_BLOCKDEV_FLAG_NATIVE) != 0) && + !gc_ptr_on_heap(emmc)) { + return emmc; + } else { + // Clear any ejected state so that a remount causes it to reappear. + ejected[EMMC_LUN] = false; + locked[EMMC_LUN] = false; + } + } + #endif + return NULL; } +// Release the locks that USB MSC holds. Locks held by others (Python, workflows) are not touched. +static void release_msc_locks(void) { + for (uint8_t i = 0; i < LUN_COUNT; i++) { + if (!locked[i]) { + continue; + } + fs_user_mount_t *vfs = get_vfs(i); + if (vfs != NULL) { + blockdev_unlock((supervisor_vfs_t *)vfs); + } + locked[i] = false; + } +} + +#if CIRCUITPY_STORAGE_MAP_IMPORT +// A write held back until the VM stops; TinyUSB keeps buffer untouched until it completes. +static struct { + uint8_t *buffer; + uint32_t lba; + uint32_t bufsize; +} deferred_write; + +// MSC is one command at a time, so a new command means the host gave up on the held write. +// TinyUSB reuses the buffer for every command, so the write must not be applied later. +#define DROP_DEFERRED_WRITE() (deferred_write.buffer = NULL) +#else +#define DROP_DEFERRED_WRITE() +#endif + static void _usb_msc_uneject(void) { + // A bus reset doesn't call tud_umount_cb(), so USB MSC may still hold its locks. + // Keep them: tud_msc_is_writable_cb() sees locked[] and doesn't lock again. for (uint8_t i = 0; i < LUN_COUNT; i++) { ejected[i] = false; - locked[i] = false; } } void usb_msc_mount(void) { _usb_msc_uneject(); + DROP_DEFERRED_WRITE(); // the host reset the bus } void usb_msc_umount(void) { + release_msc_locks(); +} + +// Release the USB MSC lock on CIRCUITPY (LUN 0), if USB MSC holds it. +// Locks held by others (Python, workflows) are not touched. +void usb_msc_release_circuitpy_lock(void) { + if (!locked[0]) { + return; + } + fs_user_mount_t *vfs = get_vfs(0); + if (vfs != NULL) { + blockdev_unlock((supervisor_vfs_t *)vfs); + } + locked[0] = false; +} + +// Whether USB MSC holds the blockdev lock on this mount. +bool usb_msc_holds_lock(fs_user_mount_t *vfs) { for (uint8_t i = 0; i < LUN_COUNT; i++) { - fs_user_mount_t *vfs = get_vfs(i + 1); - if (vfs == NULL) { - continue; + if (locked[i] && get_vfs(i) == vfs) { + return true; } - blockdev_unlock(vfs); - locked[i] = false; } + return false; } -bool usb_msc_ejected(void) { - bool all_ejected = true; +void usb_msc_remount(fs_user_mount_t *fs_mount) { for (uint8_t i = 0; i < LUN_COUNT; i++) { - all_ejected &= ejected[i]; + fs_user_mount_t *vfs = get_vfs(i); + if (vfs == NULL || vfs != fs_mount) { + continue; + } + ejected[i] = false; + eject_once[i] = true; } - return all_ejected; } uint8_t tud_msc_get_maxlun_cb(void) { return LUN_COUNT; } +// PREVENT ALLOW MEDIUM REMOVAL: TinyUSB routes this to its own dedicated callback, +// NOT tud_msc_scsi_cb. Reply unsupported on all LUNs so the host keeps TUR polling +// on every LUN — eject/storage.remount() works uniformly across CIRCUITPY, SAVES, SD. +bool tud_msc_prevent_allow_medium_removal_cb(uint8_t lun, uint8_t prohibit_removal, uint8_t control) { + (void)prohibit_removal; + (void)control; + tud_msc_set_sense(lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00); + return false; +} + // 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 +// - PREVENT_ALLOW_MEDIUM_REMOVAL, READ10, 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) { + // Note that no command uses a response right now. const void *response = NULL; int32_t resplen = 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; - default: // Set Sense = Invalid Command Operation tud_msc_set_sense(lun, SCSI_SENSE_ILLEGAL_REQUEST, 0x20, 0x00); @@ -196,8 +331,10 @@ int32_t tud_msc_scsi_cb(uint8_t lun, const uint8_t scsi_cmd[16], void *buffer, u 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); + if (vfs != NULL) { + disk_ioctl(vfs, GET_SECTOR_COUNT, block_count); + disk_ioctl(vfs, GET_SECTOR_SIZE, block_size); + } } bool tud_msc_is_writable_cb(uint8_t lun) { @@ -209,11 +346,11 @@ bool tud_msc_is_writable_cb(uint8_t lun) { if (vfs == NULL) { return false; } - if (vfs->blockdev.writeblocks[0] == MP_OBJ_NULL || !filesystem_is_writable_by_usb(vfs)) { + if (!filesystem_is_writable_by_usb(vfs)) { return false; } // Lock the blockdev once we say we're writable. - if (!locked[lun] && !blockdev_lock(vfs)) { + if (!locked[lun] && !blockdev_lock((supervisor_vfs_t *)vfs)) { return false; } locked[lun] = true; @@ -223,11 +360,15 @@ 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) { + DROP_DEFERRED_WRITE(); (void)offset; const uint32_t block_count = bufsize / MSC_FLASH_BLOCK_SIZE; fs_user_mount_t *vfs = get_vfs(lun); + if (vfs == NULL) { + return -1; + } uint32_t disk_block_count; disk_ioctl(vfs, GET_SECTOR_COUNT, &disk_block_count); @@ -235,31 +376,73 @@ int32_t tud_msc_read10_cb(uint8_t lun, uint32_t lba, uint32_t offset, void *buff return -1; } - disk_read(vfs, buffer, lba, block_count); + if (disk_read(vfs, buffer, lba, block_count) != RES_OK) { + // TinyUSB fails the command and reports MEDIUM NOT PRESENT sense. + return TUD_MSC_RET_ERROR; + } return block_count * MSC_FLASH_BLOCK_SIZE; } +#if CIRCUITPY_STORAGE_MAP_IMPORT +void usb_msc_finish_deferred_write(void) { + common_hal_mcu_disable_interrupts(); // the USB task may drop it meanwhile + uint8_t *buffer = deferred_write.buffer; + deferred_write.buffer = NULL; + common_hal_mcu_enable_interrupts(); + if (buffer != NULL) { + int32_t written = tud_msc_write10_cb(0, deferred_write.lba, 0, buffer, deferred_write.bufsize); + tud_msc_async_io_done(written, false); + } +} +#endif + // 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; autoreload_suspend(AUTORELOAD_SUSPEND_USB); + #if CIRCUITPY_STORAGE_MAP_IMPORT + // An imported .mpy runs from these blocks, so stop the VM before they change. On ports with + // a USB task the VM may be clearing the import list, so check and hold in one step. + common_hal_mcu_disable_interrupts(); + bool hold = lun == 0 && storage_map_import_uses_blocks(lba, bufsize / MSC_FLASH_BLOCK_SIZE); + if (hold) { + deferred_write.lba = lba; + deferred_write.bufsize = bufsize; + deferred_write.buffer = buffer; + } + common_hal_mcu_enable_interrupts(); + if (hold) { + reload_initiate(RUN_REASON_AUTO_RELOAD); + return TUD_MSC_RET_ASYNC; + } + #endif + DROP_DEFERRED_WRITE(); + const uint32_t block_count = bufsize / MSC_FLASH_BLOCK_SIZE; fs_user_mount_t *vfs = get_vfs(lun); - disk_write(vfs, buffer, lba, block_count); + if (vfs == NULL) { + return -1; + } + + if (disk_write(vfs, buffer, lba, block_count) != RES_OK) { + // TinyUSB fails the command and reports MEDIUM NOT PRESENT sense. + return TUD_MSC_RET_ERROR; + } // 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 + // CircuitPython let's update the cached FatFs sector if it's the one // we just wrote. + if #if FF_MAX_SS != FF_MIN_SS - if (vfs->fatfs.ssize == MSC_FLASH_BLOCK_SIZE) { + (vfs->fatfs.ssize == MSC_FLASH_BLOCK_SIZE) #else // The compiler can optimize this away. - if (FF_MAX_SS == FILESYSTEM_BLOCK_SIZE) { - #endif + (FF_MAX_SS == FILESYSTEM_BLOCK_SIZE) + #endif + { if (lba == vfs->fatfs.winsect && lba > 0) { memcpy(vfs->fatfs.win, buffer + MSC_FLASH_BLOCK_SIZE * (vfs->fatfs.winsect - lba), @@ -267,17 +450,30 @@ int32_t tud_msc_write10_cb(uint8_t lun, uint32_t lba, uint32_t offset, uint8_t * } } + // A write to an lba below fatbase is in the filesystem metadata (BPB) area or the "Reserved Region", + // and is probably setting or clearing the dirty bit. This should not trigger auto-reload. + // All other writes will trigger auto-reload. + if (lba >= vfs->fatfs.fatbase) { + content_write[lun] = true; + } + return block_count * MSC_FLASH_BLOCK_SIZE; } // 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; - - // This write is complete; initiate an autoreload. autoreload_resume(AUTORELOAD_SUSPEND_USB); - autoreload_trigger(); + + // This write is complete; initiate an autoreload if this was a file data or metadata write, + // not just a dirty-bit write. + if (content_write[lun] && + // Fast path: lun == 0 is CIRCUITPY, which can always trigger auto-reload if enabled. + // Don't autoreload if this lun was mounted by the user: that will cause a VM stop and an unmount. + (lun == 0 || !gc_ptr_on_heap(get_vfs(lun)))) { + autoreload_trigger(); + content_write[lun] = false; + } } // Invoked when received SCSI_CMD_INQUIRY @@ -290,18 +486,52 @@ void tud_msc_inquiry_cb(uint8_t lun, uint8_t vendor_id[8], uint8_t product_id[16 memcpy(product_rev, CFG_TUD_MSC_PRODUCT_REV, strlen(CFG_TUD_MSC_PRODUCT_REV)); } +#ifdef SDCARD_LUN +#if CIRCUITPY_SETTINGS_TOML +typedef enum { + SDCARD_USB_SETTING_NOT_YET_READ = 0, + SDCARD_USB_SETTING_TRUE, + SDCARD_USB_SETTING_FALSE, +} sdcard_usb_setting_state_t; + +static sdcard_usb_setting_state_t _sdcard_usb_setting_state = SDCARD_USB_SETTING_NOT_YET_READ; + +// Read only once to save file access time. +static bool sdcard_usb_enabled(void) { + if (_sdcard_usb_setting_state == SDCARD_USB_SETTING_NOT_YET_READ) { + // Can be changed per board. Most boards would leave this as true (default in circuitpy_mpconfig.h). + bool setting = CIRCUITPY_SDCARD_USB_DEFAULT; + (void)settings_get_bool("CIRCUITPY_SDCARD_USB", &setting); + _sdcard_usb_setting_state = setting ? SDCARD_USB_SETTING_TRUE : SDCARD_USB_SETTING_FALSE; + } + return _sdcard_usb_setting_state == SDCARD_USB_SETTING_TRUE; +} +#else +static bool sdcard_usb_enabled(void) { + return CIRCUITPY_SDCARD_USB; +} +#endif +#endif + // Invoked when received Test Unit Ready command. // return true allowing host to read/write this LUN e.g SD card inserted bool tud_msc_test_unit_ready_cb(uint8_t lun) { if (lun >= LUN_COUNT) { return false; } + DROP_DEFERRED_WRITE(); fs_user_mount_t *current_mount = get_vfs(lun); if (current_mount == NULL) { return false; } - if (ejected[lun]) { + + if (ejected[lun] || eject_once[lun] || (lun == 0 && !storage_usb_enabled()) + #ifdef SDCARD_LUN + || (lun == SDCARD_LUN && !sdcard_usb_enabled()) + #endif + ) { + eject_once[lun] = false; // Set 0x3a for media not present. tud_msc_set_sense(lun, SCSI_SENSE_NOT_READY, 0x3A, 0x00); return false; @@ -327,9 +557,13 @@ bool tud_msc_start_stop_cb(uint8_t lun, uint8_t power_condition, bool start, boo if (disk_ioctl(current_mount, CTRL_SYNC, NULL) != RES_OK) { return false; } else { - blockdev_unlock(current_mount); + // Release the lock only if USB MSC holds it. Locks held by others + // (Python, workflows) are not touched. + if (locked[lun]) { + blockdev_unlock((supervisor_vfs_t *)current_mount); + locked[lun] = false; + } ejected[lun] = true; - locked[lun] = false; } } else { // We can only load if it hasn't been ejected. diff --git a/supervisor/shared/web_workflow/display_stream.c b/supervisor/shared/web_workflow/display_stream.c new file mode 100644 index 00000000000..5944f885136 --- /dev/null +++ b/supervisor/shared/web_workflow/display_stream.c @@ -0,0 +1,1249 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#include "supervisor/shared/web_workflow/display_stream.h" + +#if CIRCUITPY_WEB_WORKFLOW && CIRCUITPY_DISPLAYIO + +#include + +#include "py/mperrno.h" +#include "py/ringbuf.h" +#include "py/runtime.h" +#include "shared/runtime/interrupt_char.h" +#include "shared-bindings/socketpool/Socket.h" +#include "shared-bindings/socketpool/SocketPool.h" +#include "shared-module/displayio/__init__.h" +#include "supervisor/port.h" +#include "supervisor/shared/tick.h" +#include "supervisor/shared/web_workflow/websocket.h" +#include "supervisor/workflow.h" + +#if CIRCUITPY_BUSDISPLAY +#include "shared-bindings/busdisplay/BusDisplay.h" +#endif +#if CIRCUITPY_FRAMEBUFFERIO +#include "shared-bindings/framebufferio/FramebufferDisplay.h" +#endif + +// A Hextile rectangle is cut into tiles of this size. +#define HEXTILE_SIZE (16) +// The display is sent in blocks, each its own rectangle, so that the worst a +// rectangle can take is known before it is encoded. A block is one row of tiles. +#define BLOCK_W (64) +#define BLOCK_H (HEXTILE_SIZE) +#define BLOCK_PIXELS (BLOCK_W * BLOCK_H) +#if CIRCUITPY_MIPIDSI +// DSI panels are bigger, such as the 720x1280 Raspberry Pi Touch Display 2. +#define MAX_SIZE (2048) +typedef uint32_t block_columns_t; +#else +#define MAX_SIZE (1024) +typedef uint16_t block_columns_t; +#endif +// A bit for each column of blocks. +#define BLOCK_COLUMNS (MAX_SIZE / BLOCK_W) +#define BLOCK_ROWS (MAX_SIZE / BLOCK_H) +// Room for one message: the websocket header and the RFB data. +#define MESSAGE_SIZE (8192) +#define WS_HEADER_SIZE (4) +#define PAYLOAD_SIZE (MESSAGE_SIZE - WS_HEADER_SIZE) +#define RECT_HEADER_SIZE (12) +// The rectangle header and every tile as a mask byte and raw pixels. +#define WORST_RECT (RECT_HEADER_SIZE + BLOCK_W / HEXTILE_SIZE + BLOCK_PIXELS * 4) +#define BLOCK_MASK_WORDS (BLOCK_PIXELS / 32 + 1) +// The message, a block in viewer pixels and the mask rendering a block needs. +#define BUFFER_SIZE (MESSAGE_SIZE + BLOCK_PIXELS * 4 + BLOCK_MASK_WORDS * 4) +// How long one background pass may spend encoding and sending. Sends to a +// network co-processor block until the bytes are handed over, so the budget is +// checked between sends of at most SEND_CHUNK bytes: a pass overruns it by one +// chunk at most. +#ifndef PASS_BUDGET_US +#define PASS_BUDGET_US (2000) +#endif +#ifndef SEND_CHUNK +#define SEND_CHUNK (1024) +#endif +// CIRCUITPY_WEB_DISPLAY_RATE_LIMIT caps the bytes sent per second, as at most +// pass_bytes_max per pass. Some network co-processors (AirLift) buffer sends and +// move them at the end of the background run, out of sight of the time budget, +// so the time budget alone doesn't bound what the stream costs there. +// How often the connection is checked and the VNC port accepts. Each can cost a +// command to the network co-processor, so it isn't done every pass. +#define POLL_MS (250) +// Passes that send start at least this far apart, so the stream takes at most +// PASS_BUDGET_US and pass_bytes_max of every PASS_INTERVAL_MS however fast the +// display changes or however slowly the viewer reads. +#define PASS_INTERVAL_MS (20) + +#define ENCODING_RAW (0) +#define ENCODING_HEXTILE (5) +#define ENCODING_DESKTOP_SIZE (-223) + +// What a Hextile tile's mask byte says about the tile. +#define HEXTILE_RAW (1) +#define HEXTILE_BACKGROUND (2) +#define HEXTILE_FOREGROUND (4) +#define HEXTILE_ANY_SUBRECTS (8) +#define HEXTILE_SUBRECTS_COLOURED (16) + +#define SECURITY_NONE (1) + +enum { + STATE_VERSION, + STATE_SECURITY, + STATE_CLIENT_INIT, + STATE_MESSAGE, + STATE_ENCODINGS, + STATE_SKIP, + // Sending a refusal, then closing. + STATE_CLOSING, +}; + +// Native pixel formats of the display. +enum { + FORMAT_NONE, + FORMAT_BGRX8888, + FORMAT_BGR888, + FORMAT_RGB565LE, + FORMAT_RGB565BE, + FORMAT_RGB332, + FORMAT_GRAY8, + FORMAT_RGBD4, + FORMAT_GRAY, +}; + +typedef struct { + uint8_t bits_per_pixel; + uint8_t depth; + bool big_endian; + bool true_colour; + uint16_t max[3]; + uint8_t shift[3]; +} pixel_format_t; + +// The colours a viewer keeps from one Hextile tile to the next in a rectangle. +typedef struct { + uint32_t background; + uint32_t foreground; + bool background_known; + bool foreground_known; +} hextile_colours_t; + +static socketpool_socket_obj_t vnc_listening; +static socketpool_socket_obj_t vnc_incoming; +static uint64_t last_accept_ms; +static mp_int_t vnc_port; +static bool vnc_keys; +static size_t pass_bytes_max = SIZE_MAX; + +static websocket_t ws; +static bool over_websocket; +// Set while a viewer is connected and the buffer is allocated. +static bool streaming; +static uint8_t state; +static uint8_t minor_version; +// The client message being read. +static uint8_t input[20]; +static uint8_t input_len; +static uint8_t input_needed; +// Encodings or cut text bytes still to read. +static uint32_t to_read; + +static uint8_t *message; +// The part of message still to send. +static size_t message_start; +static size_t message_end; +// Bytes put after the websocket header that aren't in a message yet. +static size_t out_len; +static uint32_t *block; +static uint32_t *block_mask; + +// What the viewer asked for. +static pixel_format_t pf; +static pixel_format_t next_pf; +static bool next_pf_set; +static uint8_t channel_bits[3]; +static uint8_t pixel_bytes; +static bool use_hextile; +static bool raw_listed; +static bool desktop_size; +static bool update_requested; +static uint16_t client_width; +static uint16_t client_height; + +// Keys typed into the viewer, for the serial console. +static ringbuf_t keys; +static uint8_t keys_buf[16]; +static bool control_down; + +// The display being streamed. target_fb is set when it's read from a +// framebuffer, otherwise blocks are rendered. +static displayio_display_core_t *target; +#if CIRCUITPY_FRAMEBUFFERIO +static framebufferio_framebufferdisplay_obj_t *target_fb; +#endif +static uint8_t format; +static uint16_t width; +static uint16_t height; +static uint8_t depth; +static bool lsb_first; +static void *pixels; +// When the connection was last checked. +static uint64_t last_poll_ms; +// When the last pass that sent started. +static uint64_t last_pass_ms; +// Ticks left until the next pass is requested, and whether the tick is enabled for it. +static volatile uint8_t pass_countdown; +static bool tick_enabled; + +// Blocks written since they were last sent, a bit per column in each row of blocks, +// and the rows written in each row of blocks: from dirty_top up to dirty_bottom, +// counted from the top of the row of blocks. Only those rows of its blocks are +// sent, so a line of text or a picture coming in a line at a time doesn't send +// every line around it again. +static block_columns_t dirty[BLOCK_ROWS]; +static uint8_t dirty_top[BLOCK_ROWS]; +static uint8_t dirty_bottom[BLOCK_ROWS]; +// The blocks of the update being sent, and how many are left. +static block_columns_t pending[BLOCK_ROWS]; +static uint8_t pending_top[BLOCK_ROWS]; +static uint8_t pending_bottom[BLOCK_ROWS]; +static uint16_t rects_left; +static uint16_t next_block_row; + +void display_stream_init(void) { + socketpool_socket_reset(&ws.socket); + socketpool_socket_reset(&vnc_listening); + socketpool_socket_reset(&vnc_incoming); + ringbuf_init(&keys, keys_buf, sizeof(keys_buf)); +} + +void display_stream_set_vnc(mp_int_t port, bool allow_keys) { + vnc_port = port; + vnc_keys = allow_keys; +} + +void display_stream_set_rate_limit(mp_int_t bytes_per_second) { + if (bytes_per_second <= 0) { + pass_bytes_max = SIZE_MAX; + } else { + pass_bytes_max = MAX(1, (uint64_t)bytes_per_second * PASS_INTERVAL_MS / 1000); + } +} + +void display_stream_listen(socketpool_socketpool_obj_t *pool) { + if (vnc_port <= 0 || !common_hal_socketpool_socket_get_closed(&vnc_listening)) { + return; + } + #if CIRCUITPY_SOCKETPOOL_IPV6 + bool opened = socketpool_socket(pool, SOCKETPOOL_AF_INET6, SOCKETPOOL_SOCK_STREAM, 0, &vnc_listening); + #else + bool opened = socketpool_socket(pool, SOCKETPOOL_AF_INET, SOCKETPOOL_SOCK_STREAM, 0, &vnc_listening); + #endif + if (!opened) { + return; + } + common_hal_socketpool_socket_settimeout(&vnc_listening, 0); + if (common_hal_socketpool_socket_bind(&vnc_listening, "", 0, vnc_port) != 0 || + !common_hal_socketpool_socket_listen(&vnc_listening, 1)) { + common_hal_socketpool_socket_close(&vnc_listening); + } +} + +// Microseconds, for budgets of a few milliseconds: the raw ticks are 1/1024 s +// and their subticks 1/32768 s on every port. Wraps every 71 minutes, so compare +// differences. +static uint32_t _now_us(void) { + uint8_t subticks = 0; + uint64_t ticks = port_get_raw_ticks(&subticks); + return (uint32_t)((ticks * 32 + subticks) * 15625 / 512); +} + +static void _mark_dirty(uint16_t x1, uint16_t y1, uint16_t x2, uint16_t y2) { + if (x1 >= x2 || y1 >= y2) { + return; + } + block_columns_t columns = 0; + for (uint16_t c = x1 / BLOCK_W; c <= (x2 - 1) / BLOCK_W && c < BLOCK_COLUMNS; c++) { + columns |= (block_columns_t)1 << c; + } + uint16_t first = y1 / BLOCK_H; + uint16_t last = (y2 - 1) / BLOCK_H; + for (uint16_t r = first; r <= last && r < BLOCK_ROWS; r++) { + uint8_t top = r == first ? y1 % BLOCK_H : 0; + uint8_t bottom = r == last ? (y2 - 1) % BLOCK_H + 1 : BLOCK_H; + if (dirty[r] == 0) { + dirty_top[r] = top; + dirty_bottom[r] = bottom; + } else { + dirty_top[r] = MIN(dirty_top[r], top); + dirty_bottom[r] = MAX(dirty_bottom[r], bottom); + } + dirty[r] |= columns; + } +} + +static void _mark_all_dirty(void) { + _mark_dirty(0, 0, width, height); +} + +// Some ports only run the web workflow when a socket has data, so the tick asks +// for the next pass, PASS_INTERVAL_MS after the last one. +static void _pass_later(void) { + if (pass_countdown > 0) { + return; + } + if (!tick_enabled) { + supervisor_enable_tick(); + tick_enabled = true; + } + uint64_t since = supervisor_ticks_ms64() - last_pass_ms; + pass_countdown = since >= PASS_INTERVAL_MS ? 1 : PASS_INTERVAL_MS - since; +} + +static void _no_pass_needed(void) { + pass_countdown = 0; + if (tick_enabled) { + supervisor_disable_tick(); + tick_enabled = false; + } +} + +void display_stream_tick(void) { + if (pass_countdown > 0 && --pass_countdown == 0) { + supervisor_workflow_request_background(); + } +} + +static void _stop(void) { + _no_pass_needed(); + if (!common_hal_socketpool_socket_get_closed(&ws.socket)) { + common_hal_socketpool_socket_close(&ws.socket); + } + if (message != NULL) { + port_free(message); + message = NULL; + } + streaming = false; + target = NULL; + #if CIRCUITPY_FRAMEBUFFERIO + target_fb = NULL; + #endif + ringbuf_clear(&keys); +} + +static uint8_t *_out(size_t len) { + uint8_t *p = message + WS_HEADER_SIZE + out_len; + out_len += len; + return p; +} + +static uint8_t *_put16(uint8_t *p, uint16_t v) { + p[0] = v >> 8; + p[1] = v; + return p + 2; +} + +static uint8_t *_put32(uint8_t *p, uint32_t v) { + p = _put16(p, v >> 16); + return _put16(p, v); +} + +static uint32_t _get32(const uint8_t *p) { + return (uint32_t)p[0] << 24 | p[1] << 16 | p[2] << 8 | p[3]; +} + +static void _put_pixel_format(uint8_t *p, const pixel_format_t *f) { + p[0] = f->bits_per_pixel; + p[1] = f->depth; + p[2] = f->big_endian; + p[3] = f->true_colour; + for (int i = 0; i < 3; i++) { + _put16(p + 4 + 2 * i, f->max[i]); + p[10 + i] = f->shift[i]; + } + p[13] = p[14] = p[15] = 0; +} + +// Takes a pixel format the viewer asked for. Returns false for one it can't be +// sent: colour maps, and channels that aren't a whole number of bits. +static bool _set_pixel_format(const pixel_format_t *f) { + if (!f->true_colour || + (f->bits_per_pixel != 8 && f->bits_per_pixel != 16 && f->bits_per_pixel != 32)) { + return false; + } + for (int i = 0; i < 3; i++) { + uint16_t max = f->max[i]; + if (max == 0 || max > 255 || (max & (max + 1)) != 0) { + return false; + } + channel_bits[i] = 32 - __builtin_clz(max); + } + pf = *f; + pixel_bytes = f->bits_per_pixel / 8; + return true; +} + +static void _default_pixel_format(pixel_format_t *f) { + if (format == FORMAT_RGB565LE || format == FORMAT_RGB565BE) { + *f = (pixel_format_t) {16, 16, false, true, {31, 63, 31}, {11, 5, 0}}; + } else { + *f = (pixel_format_t) {32, 24, false, true, {255, 255, 255}, {16, 8, 0}}; + } +} + +void display_stream_handoff(socketpool_socket_obj_t *socket, bool websocket) { + if (streaming && message_start < message_end) { + // A close frame can't go in the middle of a message, so finish it if the + // socket takes it now. A viewer that stopped reading is closed without + // one rather than holding everything up. + int left = message_end - message_start; + if (socketpool_socket_send(&ws.socket, message + message_start, left) < left) { + common_hal_socketpool_socket_close(&ws.socket); + } + } + if (streaming && !over_websocket && !common_hal_socketpool_socket_get_closed(&ws.socket)) { + // Only a websocket viewer gets a close frame. + common_hal_socketpool_socket_close(&ws.socket); + } + if (message != NULL) { + port_free(message); + message = NULL; + } + streaming = false; + websocket_take_socket(&ws, socket); + over_websocket = websocket; + uint32_t *buffer = port_malloc(BUFFER_SIZE, false); + message = (uint8_t *)buffer; + if (message == NULL) { + _stop(); + return; + } + block = buffer + MESSAGE_SIZE / sizeof(uint32_t); + block_mask = block + BLOCK_PIXELS; + message_start = 0; + message_end = 0; + out_len = 0; + target = NULL; + #if CIRCUITPY_FRAMEBUFFERIO + target_fb = NULL; + #endif + format = FORMAT_NONE; + width = 0; + height = 0; + rects_left = 0; + update_requested = false; + use_hextile = false; + desktop_size = false; + next_pf_set = false; + control_down = false; + ringbuf_clear(&keys); + memcpy(_out(12), "RFB 003.008\n", 12); + state = STATE_VERSION; + input_len = 0; + input_needed = 12; + last_poll_ms = supervisor_ticks_ms64(); + last_pass_ms = 0; + streaming = true; + _pass_later(); +} + +void display_stream_area_updated(displayio_display_core_t *core, const displayio_area_t *area) { + if (!streaming) { + return; + } + if (core == target) { + #if CIRCUITPY_DISPLAYIO_LVGL + // An lv_area_t: the second corner is inclusive. + _mark_dirty(area->x1, area->y1, area->x2 + 1, area->y2 + 1); + #else + _mark_dirty(area->x1, area->y1, area->x2, area->y2); + #endif + } + // Another display may be a new one to switch to. + _pass_later(); +} + +static uint8_t _format_of(const _displayio_colorspace_t *colorspace) { + if (colorspace->depth < 8 && !colorspace->pixels_in_byte_share_row) { + return FORMAT_NONE; + } + switch (colorspace->depth) { + case 32: + return FORMAT_BGRX8888; + case 24: + return FORMAT_BGR888; + case 16: + return colorspace->reverse_bytes_in_word ? FORMAT_RGB565BE : FORMAT_RGB565LE; + case 8: + return colorspace->grayscale ? FORMAT_GRAY8 : FORMAT_RGB332; + case 4: + return colorspace->grayscale ? FORMAT_GRAY : FORMAT_RGBD4; + case 2: + case 1: + return FORMAT_GRAY; + } + return FORMAT_NONE; +} + +// Finds the display to stream and notices when it changes. +static void _check_display(void) { + displayio_display_core_t *core = NULL; + void *fb = NULL; + void *new_pixels = NULL; + for (size_t i = 0; i < CIRCUITPY_DISPLAY_LIMIT && core == NULL; i++) { + const mp_obj_type_t *type = displays[i].display_base.type; + #if CIRCUITPY_FRAMEBUFFERIO + if (type == &framebufferio_framebufferdisplay_type) { + fb = &displays[i].framebuffer_display; + core = &displays[i].framebuffer_display.core; + new_pixels = displays[i].framebuffer_display.bufinfo.buf; + } + #endif + // The LVGL compositor's BusDisplay has no display_core and no readable + // pixels, so only framebuffer displays can be streamed there. + #if CIRCUITPY_BUSDISPLAY && !CIRCUITPY_DISPLAYIO_LVGL + if (type == &busdisplay_busdisplay_type) { + core = &displays[i].display.core; + } + #endif + (void)type; + } + uint8_t new_format = FORMAT_NONE; + // The panel's size, whatever the rotation. The legacy compositor keeps it in the + // full refresh area; LVGL tracks invalidation itself, so the core keeps only the size. + #if CIRCUITPY_DISPLAYIO_LVGL + // The LVGL core keeps the rotated size, but the framebuffer read below is in + // the panel's own orientation, so swap them back when transposed. + bool transposed = core != NULL && (core->rotation == 90 || core->rotation == 270); + uint16_t new_width = core != NULL ? (transposed ? core->height : core->width) : width; + uint16_t new_height = core != NULL ? (transposed ? core->width : core->height) : height; + #else + uint16_t new_width = core != NULL ? core->area.x2 : width; + uint16_t new_height = core != NULL ? core->area.y2 : height; + #endif + if (core != NULL) { + new_format = _format_of(&core->colorspace); + if (new_width > MAX_SIZE || new_height > MAX_SIZE) { + new_format = FORMAT_NONE; + } + if (fb != NULL ? new_pixels == NULL : core->colorspace.depth < 8) { + new_format = FORMAT_NONE; + } + if (new_format == FORMAT_NONE) { + core = NULL; + fb = NULL; + new_pixels = NULL; + } + } + if (core == target && + (core == NULL || (new_format == format && new_width == width && new_height == height && + new_pixels == pixels))) { + return; + } + target = core; + #if CIRCUITPY_FRAMEBUFFERIO + target_fb = fb; + #endif + format = new_format; + // Without a display the viewer keeps its size and is shown black. + width = new_width; + height = new_height; + depth = core != NULL ? core->colorspace.depth : 0; + lsb_first = core != NULL && !core->colorspace.reverse_pixels_in_byte; + pixels = new_pixels; + _mark_all_dirty(); +} + +// The pixel at x of row as 0xRRGGBB. +static uint32_t _rgb(const uint8_t *row, uint16_t x) { + uint32_t v; + switch (format) { + case FORMAT_BGRX8888: + row += x * 4; + return row[2] << 16 | row[1] << 8 | row[0]; + case FORMAT_BGR888: + row += x * 3; + return row[2] << 16 | row[1] << 8 | row[0]; + case FORMAT_RGB565LE: + case FORMAT_RGB565BE: { + row += x * 2; + v = format == FORMAT_RGB565LE ? (row[1] << 8 | row[0]) : (row[0] << 8 | row[1]); + uint32_t r = v >> 11, g = (v >> 5) & 0x3f, b = v & 0x1f; + return ((r << 3) | (r >> 2)) << 16 | ((g << 2) | (g >> 4)) << 8 | ((b << 3) | (b >> 2)); + } + case FORMAT_RGB332: { + v = row[x]; + uint32_t r = v >> 5, g = (v >> 2) & 7, b = v & 3; + return (r * 255 / 7) << 16 | (g * 255 / 7) << 8 | b * 0x55; + } + case FORMAT_GRAY8: + return row[x] * 0x010101; + } + uint8_t per_byte = 8 / depth; + uint8_t index = x % per_byte; + uint8_t shift = lsb_first ? index * depth : 8 - depth - index * depth; + v = (row[x / per_byte] >> shift) & ((1 << depth) - 1); + if (format == FORMAT_RGBD4) { + return ((v >> 3) & 1 ? 0xff0000 : 0) | ((v >> 2) & 1 ? 0xff00 : 0) | ((v >> 1) & 1 ? 0xff : 0); + } + return v * 255 / ((1 << depth) - 1) * 0x010101; +} + +static uint32_t _client_pixel(uint32_t rgb) { + return ((rgb >> (24 - channel_bits[0])) & pf.max[0]) << pf.shift[0] | + ((rgb >> (16 - channel_bits[1])) & pf.max[1]) << pf.shift[1] | + ((rgb >> (8 - channel_bits[2])) & pf.max[2]) << pf.shift[2]; +} + +// Fills block with the w x h pixels at x, y in the viewer's format. +static void _load_block(uint16_t x, uint16_t y, uint16_t w, uint16_t h) { + if (target == NULL) { + memset(block, 0, w * h * sizeof(uint32_t)); + return; + } + const uint8_t *src = NULL; + size_t stride = 0; + uint16_t x0 = 0; + #if CIRCUITPY_FRAMEBUFFERIO + if (target_fb != NULL) { + stride = target_fb->row_stride; + src = (const uint8_t *)pixels + target_fb->first_pixel_offset + y * stride; + x0 = x; + } + #endif + // Rendering a bus display's areas again needs the scanline compositor. + #if CIRCUITPY_BUSDISPLAY && !CIRCUITPY_DISPLAYIO_LVGL + if (src == NULL) { + // Rendered into block itself. Converting from the end doesn't overwrite + // a pixel before it's read, since pixels are at most 4 bytes. + displayio_area_t area = { .x1 = x, .y1 = y, .x2 = x + w, .y2 = y + h, .next = NULL }; + stride = w * depth / 8; + memset(block, 0, h * stride); + memset(block_mask, 0, BLOCK_MASK_WORDS * sizeof(uint32_t)); + displayio_display_core_fill_area(target, &area, block_mask, block); + src = (const uint8_t *)block; + } + #endif + for (int j = h - 1; j >= 0; j--) { + const uint8_t *row = src + j * stride; + uint32_t *out = block + j * w; + for (int i = w - 1; i >= 0; i--) { + out[i] = _client_pixel(_rgb(row, x0 + i)); + } + } +} + +static uint8_t *_put_pixel(uint8_t *p, uint32_t v) { + for (uint8_t i = 0; i < pixel_bytes; i++) { + p[i] = pf.big_endian ? v >> (8 * (pixel_bytes - 1 - i)) : v >> (8 * i); + } + return p + pixel_bytes; +} + +// A Hextile tile as plain pixels. Returns the end of it. +static uint8_t *_put_hextile_raw(uint8_t *mask, const uint32_t *tile, uint8_t w, uint8_t h, uint8_t stride, hextile_colours_t *kept) { + *mask = HEXTILE_RAW; + uint8_t *p = mask + 1; + for (uint8_t y = 0; y < h; y++) { + for (uint8_t x = 0; x < w; x++) { + p = _put_pixel(p, tile[y * stride + x]); + } + } + // Viewers differ on what these are after a raw tile. + kept->background_known = false; + kept->foreground_known = false; + return p; +} + +// Writes the w x h pixels as one Hextile tile, as subrectangles on a background +// unless that would take more than the pixels themselves. Returns the end of it. +static uint8_t *_put_hextile_tile(uint8_t *p, const uint32_t *tile, uint8_t w, uint8_t h, uint8_t stride, hextile_colours_t *kept) { + // A majority vote finds the most common colour when more than half the + // pixels have it. Otherwise any colour will do, and the tile likely ends up raw. + uint32_t background = 0; + int16_t votes = 0; + for (uint8_t y = 0; y < h; y++) { + for (uint8_t x = 0; x < w; x++) { + uint32_t v = tile[y * stride + x]; + if (votes == 0) { + background = v; + } + votes += v == background ? 1 : -1; + } + } + uint32_t foreground = background; + bool coloured = false; + for (uint8_t y = 0; y < h; y++) { + for (uint8_t x = 0; x < w; x++) { + uint32_t v = tile[y * stride + x]; + if (foreground == background) { + foreground = v; + } else if (v != background && v != foreground) { + coloured = true; + } + } + } + uint8_t *mask = p++; + *mask = 0; + if (!kept->background_known || kept->background != background) { + *mask |= HEXTILE_BACKGROUND; + p = _put_pixel(p, background); + kept->background = background; + kept->background_known = true; + } + if (foreground == background) { + return p; + } + *mask |= HEXTILE_ANY_SUBRECTS; + if (coloured) { + *mask |= HEXTILE_SUBRECTS_COLOURED; + kept->foreground_known = false; + } else if (!kept->foreground_known || kept->foreground != foreground) { + *mask |= HEXTILE_FOREGROUND; + p = _put_pixel(p, foreground); + kept->foreground = foreground; + kept->foreground_known = true; + } + uint8_t *count = p++; + *count = 0; + const uint8_t *raw_end = mask + 1 + w * h * pixel_bytes; + uint8_t subrect_size = 2 + (coloured ? pixel_bytes : 0); + // Pixels already in a subrectangle, a bit per column. + uint16_t done[HEXTILE_SIZE] = { 0 }; + for (uint8_t y = 0; y < h; y++) { + const uint32_t *row = tile + y * stride; + for (uint8_t x = 0; x < w; x++) { + uint32_t v = row[x]; + if (v == background || (done[y] & (1 << x)) != 0) { + continue; + } + if (p + subrect_size > raw_end) { + return _put_hextile_raw(mask, tile, w, h, stride, kept); + } + uint8_t rect_w = 1; + while (x + rect_w < w && row[x + rect_w] == v) { + rect_w++; + } + uint8_t rect_h = 1; + for (bool same = true; same && y + rect_h < h; rect_h += same) { + const uint32_t *below = row + rect_h * stride + x; + for (uint8_t i = 0; i < rect_w && same; i++) { + same = below[i] == v; + } + } + if (coloured) { + p = _put_pixel(p, v); + } + *p++ = x << 4 | y; + *p++ = (rect_w - 1) << 4 | (rect_h - 1); + *count += 1; + for (uint8_t i = 0; i < rect_h; i++) { + done[y + i] |= ((1 << rect_w) - 1) << x; + } + } + } + return p; +} + +static void _put_rect_header(uint8_t *p, uint16_t x, uint16_t y, uint16_t w, uint16_t h, int32_t encoding) { + p = _put16(p, x); + p = _put16(p, y); + p = _put16(p, w); + p = _put16(p, h); + _put32(p, encoding); +} + +// Adds the rows from y of the block at x, at most h of them, as one rectangle. +static void _put_block_rect(uint16_t x, uint16_t y, uint16_t h) { + uint16_t w = MIN(BLOCK_W, width - x); + h = MIN(h, height - y); + _load_block(x, y, w, h); + _put_rect_header(_out(RECT_HEADER_SIZE), x, y, w, h, use_hextile ? ENCODING_HEXTILE : ENCODING_RAW); + uint8_t *start = _out(0); + uint8_t *p = start; + if (use_hextile) { + hextile_colours_t kept = { 0 }; + for (uint16_t i = 0; i < w; i += HEXTILE_SIZE) { + p = _put_hextile_tile(p, block + i, MIN(HEXTILE_SIZE, w - i), h, w, &kept); + } + } else { + for (size_t i = 0; i < (size_t)w * h; i++) { + p = _put_pixel(p, block[i]); + } + } + _out(p - start); +} + +// Adds the next part of an update to the message, starting an update if one +// was asked for and there is something to send. Returns false when there was +// nothing to add. +static bool _fill(uint32_t end_us) { + _check_display(); + if (rects_left == 0) { + if (next_pf_set) { + next_pf_set = false; + if (!_set_pixel_format(&next_pf)) { + _stop(); + return false; + } + _mark_all_dirty(); + } + if (!update_requested) { + return false; + } + if (width != client_width || height != client_height) { + if (!desktop_size) { + // It can only be told by connecting again. + _stop(); + return false; + } + uint8_t *p = _out(4); + p[0] = 0; + p[1] = 0; + _put16(p + 2, 1); + _put_rect_header(_out(RECT_HEADER_SIZE), 0, 0, width, height, ENCODING_DESKTOP_SIZE); + client_width = width; + client_height = height; + update_requested = false; + _mark_all_dirty(); + return true; + } + uint16_t count = 0; + uint16_t rows = (height + BLOCK_H - 1) / BLOCK_H; + for (uint16_t r = 0; r < rows; r++) { + pending[r] = dirty[r]; + pending_top[r] = dirty_top[r]; + pending_bottom[r] = dirty_bottom[r]; + dirty[r] = 0; + count += __builtin_popcount(pending[r]); + } + if (count == 0) { + return false; + } + uint8_t *p = _out(4); + p[0] = 0; + p[1] = 0; + _put16(p + 2, count); + rects_left = count; + next_block_row = 0; + update_requested = false; + } + bool first = true; + while (rects_left > 0 && out_len + WORST_RECT <= PAYLOAD_SIZE && + (first || (int32_t)(_now_us() - end_us) < 0)) { + while (pending[next_block_row] == 0) { + next_block_row++; + } + uint8_t column = __builtin_ctz(pending[next_block_row]); + pending[next_block_row] &= ~((block_columns_t)1 << column); + _put_block_rect(column * BLOCK_W, next_block_row * BLOCK_H + pending_top[next_block_row], + pending_bottom[next_block_row] - pending_top[next_block_row]); + rects_left--; + first = false; + } + return true; +} + +static void _frame(void) { + if (!over_websocket) { + message_start = WS_HEADER_SIZE; + } else if (out_len <= 125) { + message_start = WS_HEADER_SIZE - 2; + message[message_start + 1] = out_len; + } else { + message_start = 0; + message[1] = 126; + message[2] = out_len >> 8; + message[3] = out_len & 0xff; + } + if (over_websocket) { + // Binary + message[message_start] = 0x80 | 0x2; + } + message_end = WS_HEADER_SIZE + out_len; + out_len = 0; +} + +static int _read(uint8_t *buf, size_t len) { + if (over_websocket) { + size_t n = 0; + while (n < len && websocket_read_payload_byte(&ws, buf + n)) { + n++; + } + return n; + } + int n = socketpool_socket_recv_into(&ws.socket, buf, len); + return n < 0 ? 0 : n; +} + +static void _type(const char *text) { + for (; *text != '\0'; text++) { + if (*text == mp_interrupt_char) { + ringbuf_clear(&keys); + mp_sched_keyboard_interrupt(); + } else if (ringbuf_num_empty(&keys) > 0) { + ringbuf_put(&keys, *text); + } + } +} + +static void _key(bool down, uint32_t keysym) { + if (keysym == 0xffe3 || keysym == 0xffe4) { + control_down = down; + return; + } + if (!down) { + return; + } + char c[2] = { 0, 0 }; + const char *text = c; + if (keysym >= 0x20 && keysym <= 0x7e) { + c[0] = keysym; + if (control_down && keysym >= 0x40) { + c[0] &= 0x1f; + } + } else { + switch (keysym) { + case 0xff0d: // Return + case 0xff8d: // KP_Enter + c[0] = '\r'; + break; + case 0xff08: // BackSpace + c[0] = '\b'; + break; + case 0xff09: // Tab + c[0] = '\t'; + break; + case 0xff1b: // Escape + c[0] = 0x1b; + break; + case 0xff51: // Left + text = "\x1b[D"; + break; + case 0xff52: // Up + text = "\x1b[A"; + break; + case 0xff53: // Right + text = "\x1b[C"; + break; + case 0xff54: // Down + text = "\x1b[B"; + break; + case 0xff50: // Home + text = "\x1b[H"; + break; + case 0xff57: // End + text = "\x1b[F"; + break; + case 0xffff: // Delete + text = "\x1b[3~"; + break; + } + } + _type(text); +} + +static void _refuse(const char *reason) { + // SecurityResult failed, and from 3.8 why. + _put32(_out(4), 1); + if (minor_version >= 8) { + size_t len = strlen(reason); + _put32(_out(4), len); + memcpy(_out(len), reason, len); + } + state = STATE_CLOSING; +} + +static void _server_init(void) { + _check_display(); + client_width = width; + client_height = height; + pixel_format_t f; + _default_pixel_format(&f); + _set_pixel_format(&f); + uint8_t *p = _out(4 + 16); + // Without a display yet the viewer is told 1 x 1 until there is one. + _put16(p, MAX(client_width, 1)); + _put16(p + 2, MAX(client_height, 1)); + _put_pixel_format(p + 4, &pf); + const char *name = MICROPY_HW_BOARD_NAME; + size_t len = strlen(name); + _put32(_out(4), len); + memcpy(_out(len), name, len); + _mark_all_dirty(); +} + +// Handles input once input_needed bytes of it are read. +static void _handle_input(void) { + uint8_t needed = 1; + switch (state) { + case STATE_VERSION: + if (memcmp(input, "RFB 003.", 8) != 0) { + _stop(); + return; + } + minor_version = (input[9] - '0') * 10 + (input[10] - '0'); + if (minor_version >= 8) { + minor_version = 8; + } else if (minor_version != 7) { + minor_version = 3; + } + if (minor_version == 3) { + // The server picks. + _put32(_out(4), SECURITY_NONE); + state = STATE_CLIENT_INIT; + } else { + uint8_t *p = _out(2); + p[0] = 1; + p[1] = SECURITY_NONE; + state = STATE_SECURITY; + } + break; + case STATE_SECURITY: + if (input[0] != SECURITY_NONE) { + _refuse("Unsupported security type"); + break; + } + if (minor_version >= 8) { + _put32(_out(4), 0); + } + state = STATE_CLIENT_INIT; + break; + case STATE_CLIENT_INIT: + // Shared or not, a new viewer takes over. + _server_init(); + state = STATE_MESSAGE; + break; + case STATE_MESSAGE: + if (input_len == 1) { + switch (input[0]) { + case 0: // SetPixelFormat + needed = 20; + break; + case 2: // SetEncodings + needed = 4; + break; + case 3: // FramebufferUpdateRequest + needed = 10; + break; + case 4: // KeyEvent + needed = 8; + break; + case 5: // PointerEvent + needed = 6; + break; + case 6: // ClientCutText + needed = 8; + break; + default: + // Its length isn't known, so nothing after it can be read. + _stop(); + return; + } + input_needed = needed; + return; + } + switch (input[0]) { + case 0: { + const uint8_t *p = input + 4; + next_pf = (pixel_format_t) { + p[0], p[1], p[2] != 0, p[3] != 0, + {p[4] << 8 | p[5], p[6] << 8 | p[7], p[8] << 8 | p[9]}, + {p[10], p[11], p[12]} + }; + next_pf_set = true; + break; + } + case 2: + to_read = input[2] << 8 | input[3]; + use_hextile = false; + raw_listed = false; + desktop_size = false; + if (to_read > 0) { + state = STATE_ENCODINGS; + needed = 4; + } + break; + case 3: + if (input[1] == 0) { + _mark_all_dirty(); + } + update_requested = true; + break; + case 4: + // The VNC port has no password, so it only reaches the REPL if asked to. + if (over_websocket || vnc_keys) { + _key(input[1] != 0, _get32(input + 4)); + } + break; + case 6: + to_read = _get32(input + 4); + if (to_read > 0) { + state = STATE_SKIP; + } + break; + } + break; + case STATE_ENCODINGS: { + int32_t encoding = _get32(input); + if (encoding == ENCODING_HEXTILE && !raw_listed) { + use_hextile = true; + } else if (encoding == ENCODING_RAW) { + raw_listed = true; + } else if (encoding == ENCODING_DESKTOP_SIZE) { + desktop_size = true; + } + if (--to_read > 0) { + needed = 4; + } else { + state = STATE_MESSAGE; + } + break; + } + } + input_len = 0; + input_needed = needed; +} + +static void _read_input(void) { + while (streaming && state != STATE_CLOSING) { + if (state == STATE_SKIP) { + uint8_t skipped[16]; + int n = _read(skipped, MIN(sizeof(skipped), to_read)); + if (n <= 0) { + return; + } + to_read -= n; + if (to_read == 0) { + state = STATE_MESSAGE; + } + continue; + } + int n = _read(input + input_len, input_needed - input_len); + if (n <= 0) { + return; + } + input_len += n; + if (input_len == input_needed) { + _handle_input(); + } + } +} + +static void _accept(void) { + if (common_hal_socketpool_socket_get_closed(&vnc_listening)) { + return; + } + int result = socketpool_socket_accept(&vnc_listening, NULL, &vnc_incoming); + if (result == -MP_EBADF) { + common_hal_socketpool_socket_close(&vnc_listening); + return; + } + if (result > 0) { + common_hal_socketpool_socket_settimeout(&vnc_incoming, 0); + display_stream_handoff(&vnc_incoming, false); + } +} + +void display_stream_background(void) { + uint64_t start = supervisor_ticks_ms64(); + if (start - last_accept_ms >= POLL_MS) { + last_accept_ms = start; + _accept(); + } + if (!streaming) { + return; + } + // A CLOSE from the viewer closes the socket without asking the co-processor. + if (common_hal_socketpool_socket_get_closed(&ws.socket)) { + _stop(); + return; + } + if (start - last_poll_ms >= POLL_MS) { + last_poll_ms = start; + if (!common_hal_socketpool_socket_get_connected(&ws.socket)) { + _stop(); + return; + } + } + // Some ports wake the web workflow until a socket's data is read, so read + // what the viewer sent every time. Replies go in the next message, so not + // in the middle of one. + if (message_start >= message_end) { + _read_input(); + if (!streaming || common_hal_socketpool_socket_get_closed(&ws.socket)) { + _stop(); + return; + } + } + if (start - last_pass_ms < PASS_INTERVAL_MS) { + // Too soon after the last one, whatever woke the web workflow. + _pass_later(); + return; + } + last_pass_ms = start; + uint32_t pass_start_us = _now_us(); + size_t pass_bytes = 0; + do { + if (message_start < message_end) { + if (pass_bytes >= pass_bytes_max) { + break; + } + size_t chunk = MIN(MIN(message_end - message_start, SEND_CHUNK), pass_bytes_max - pass_bytes); + int sent = socketpool_socket_send(&ws.socket, message + message_start, chunk); + if (sent == -MP_EAGAIN) { + break; + } + if (sent < 0) { + _stop(); + return; + } + message_start += sent; + pass_bytes += sent; + continue; + } + if (out_len > 0) { + _frame(); + continue; + } + if (state == STATE_CLOSING) { + _stop(); + return; + } + if (state < STATE_MESSAGE || !_fill(pass_start_us + PASS_BUDGET_US)) { + break; + } + if (!streaming) { + return; + } + } while (_now_us() - pass_start_us < PASS_BUDGET_US); + // Come back for what's left: the rest of a message the socket couldn't take + // yet, or an update the budget ran out on. + if (message_start < message_end || out_len > 0 || rects_left > 0) { + _pass_later(); + } else { + _no_pass_needed(); + } +} + +bool display_stream_connected(void) { + return streaming && state >= STATE_MESSAGE; +} + +uint32_t display_stream_available(void) { + return ringbuf_num_filled(&keys); +} + +char display_stream_read_char(void) { + if (ringbuf_num_filled(&keys) > 0) { + return ringbuf_get(&keys); + } + return -1; +} + +#endif diff --git a/supervisor/shared/web_workflow/display_stream.h b/supervisor/shared/web_workflow/display_stream.h new file mode 100644 index 00000000000..c4bd0ec9a20 --- /dev/null +++ b/supervisor/shared/web_workflow/display_stream.h @@ -0,0 +1,63 @@ +// This file is part of the CircuitPython project: https://circuitpython.org +// +// SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries +// +// SPDX-License-Identifier: MIT + +#pragma once + +#include "py/mpconfig.h" + +#if CIRCUITPY_WEB_WORKFLOW && CIRCUITPY_DISPLAYIO + +#include "shared-bindings/socketpool/Socket.h" +#include "shared-bindings/socketpool/SocketPool.h" +#include "shared-module/displayio/area.h" +#include "shared-module/displayio/display_core.h" + +// Serves the first display with the Remote Framebuffer protocol (RFB 3.8, +// RFC 6143), so VNC viewers can show it. Framebuffer displays are read from +// their framebuffer. Bus displays have none, so changed areas are rendered +// again from the display's group. +// +// It is reached two ways: +// - a websocket at /cp/display/ carrying RFB in binary messages, as noVNC and +// the /cp/display/ page expect. The HTTP request was already authenticated, +// so it offers the None security type. +// - plain TCP on CIRCUITPY_WEB_VNC_PORT for VNC viewers. It is off unless +// settings.toml sets the port. It has no password, offering only the None +// security type, so anyone who can reach it can see the display. Keys are +// ignored there because the console can run code, unless settings.toml sets +// CIRCUITPY_WEB_VNC_KEYS to true. Viewers that insist on a password can't use +// it. Each listener takes one of the six sockets AirLift's co-processor has, +// and can't be closed. +// +// The encodings are Raw and Hextile, which needs no compressor and little code. +// DesktopSize tells the viewer when the display changes size. +// Keys typed into a websocket viewer go to the serial console. +// +// There is one viewer at a time: a new one takes over. A replaced websocket +// viewer is closed with code 4000 (WEBSOCKET_CLOSE_REPLACED). + +void display_stream_init(void); +// Sets the VNC port, 0 for none, and whether keys typed there reach the console. +void display_stream_set_vnc(mp_int_t port, bool allow_keys); +// Sets the most bytes per second the stream sends, 0 for no limit. +void display_stream_set_rate_limit(mp_int_t bytes_per_second); +// Opens the VNC port if there is one and it isn't open. +void display_stream_listen(socketpool_socketpool_obj_t *pool); +// Takes a connected socket: a websocket upgrade request for /cp/display/, or a +// connection to the VNC port. +void display_stream_handoff(socketpool_socket_obj_t *socket, bool websocket); +void display_stream_background(void); +// Called every tick while the stream has the tick enabled. +void display_stream_tick(void); +// Called by a display after it refreshed area. +void display_stream_area_updated(displayio_display_core_t *core, const displayio_area_t *area); + +// Serial console input typed into the viewer. +bool display_stream_connected(void); +uint32_t display_stream_available(void); +char display_stream_read_char(void); + +#endif diff --git a/supervisor/shared/web_workflow/static/display.html b/supervisor/shared/web_workflow/static/display.html new file mode 100644 index 00000000000..47fabbe3b70 --- /dev/null +++ b/supervisor/shared/web_workflow/static/display.html @@ -0,0 +1,43 @@ + + + + Display + + + + + + +

 Display

+
+
+
+ +
+

+ + + + Connecting +

+
+
+
+

+      
+
+
+ Ctrl + + + +
+ + +
+
+
+ + + + diff --git a/supervisor/shared/web_workflow/static/display.js b/supervisor/shared/web_workflow/static/display.js new file mode 100644 index 00000000000..bfb5d68a469 --- /dev/null +++ b/supervisor/shared/web_workflow/static/display.js @@ -0,0 +1,373 @@ +// Shows the device's display. It is sent with the Remote Framebuffer protocol +// (RFC 6143) over the websocket, as described in +// supervisor/shared/web_workflow/display_stream.h. This is a small viewer for +// what the device sends: Raw and Hextile. +// Wrapped so its names don't clash with serial.js on the same page. +(function() { + var canvas = document.getElementById("screen"); + var context = canvas.getContext("2d"); + var view = document.getElementById("view"); + var status_text = document.getElementById("status"); + var ws; + // Set when another page took the display over, so this one doesn't take it back. + var replaced = false; + + var ENCODING_RAW = 0; + var ENCODING_HEXTILE = 5; + var ENCODING_DESKTOP_SIZE = -223; + + // Bytes received and not yet used. + var input = new Uint8Array(0); + var state; + var image = null; + var pixels = null; + var rects_left = 0; + var updates = 0; + var received = 0; + // Degrees clockwise the picture is turned. Only the page turns it, the device + // sends the display as it is. Remembered by the browser where it can. + var rotation = 0; + try { + rotation = (parseInt(localStorage.getItem("display_rotation")) || 0) % 360; + } catch (e) { + } + + // Fits the turned picture to the width of its column and three quarters of + // the window's height. + function layout() { + var turned = rotation % 180 != 0; + var shown_width = turned ? canvas.height : canvas.width; + var shown_height = turned ? canvas.width : canvas.height; + var scale = Math.min(view.clientWidth / shown_width, window.innerHeight * 0.75 / shown_height); + view.style.height = shown_height * scale + "px"; + canvas.style.width = canvas.width * scale + "px"; + canvas.style.height = canvas.height * scale + "px"; + canvas.style.left = (view.clientWidth - canvas.width * scale) / 2 + "px"; + canvas.style.top = (shown_height - canvas.height) * scale / 2 + "px"; + canvas.style.transform = "rotate(" + rotation + "deg)"; + } + + function resize(width, height) { + canvas.width = width; + canvas.height = height; + image = context.createImageData(width, height); + pixels = new Uint32Array(image.data.buffer); + pixels.fill(0xff000000); + layout(); + } + + function send(bytes) { + ws.send(new Uint8Array(bytes)); + } + + function u16(v) { + return [(v >> 8) & 0xff, v & 0xff]; + } + + function u32(v) { + return u16(v >>> 16).concat(u16(v & 0xffff)); + } + + function request_update(incremental) { + send([3, incremental ? 1 : 0].concat(u16(0), u16(0), u16(canvas.width), u16(canvas.height))); + } + + function take(n) { + var bytes = input.subarray(0, n); + input = input.subarray(n); + return bytes; + } + + function get16(b, i) { + return (b[i] << 8) | b[i + 1]; + } + + function get32(b, i) { + return ((b[i] << 24) | (b[i + 1] << 16) | (b[i + 2] << 8) | b[i + 3]) >>> 0; + } + + // Pixels are asked for as 32 bits, red in the low byte, so they are canvas + // pixels (RGBA in little endian memory) once alpha is set. + function pixel(b, i) { + return (0xff000000 | (b[i + 2] << 16) | (b[i + 1] << 8) | b[i]) >>> 0; + } + + function fill_rect(x, y, w, h, v) { + for (var j = y; j < y + h; j++) { + pixels.fill(v, j * canvas.width + x, j * canvas.width + x + w); + } + } + + // Draws the w x h pixels at offset p of b. + function put_raw(x, y, w, h, b, p) { + for (var j = 0; j < h; j++) { + for (var i = 0; i < w; i++, p += 4) { + pixels[(y + j) * canvas.width + x + i] = pixel(b, p); + } + } + } + + // Draws the Hextile rectangle after the header at the start of the input. + // Nothing says how long it is, so returns its length if all of it is here and + // 0 if not. What it drew by then is the same when it's tried again. + function draw_hextile(x, y, w, h) { + var p = 12; + var background = 0; + var foreground = 0; + for (var ty = 0; ty < h; ty += 16) { + for (var tx = 0; tx < w; tx += 16) { + var tw = Math.min(16, w - tx); + var th = Math.min(16, h - ty); + if (p >= input.length) { + return 0; + } + var mask = input[p++]; + if (mask & 1) { + if (p + tw * th * 4 > input.length) { + return 0; + } + put_raw(x + tx, y + ty, tw, th, input, p); + p += tw * th * 4; + continue; + } + var coloured = mask & 16; + // The colours and the subrectangle count that come before the subrectangles. + var header = ((mask & 2) ? 4 : 0) + ((mask & 4) ? 4 : 0) + ((mask & 8) ? 1 : 0); + if (p + header > input.length) { + return 0; + } + if (mask & 2) { + background = pixel(input, p); + p += 4; + } + if (mask & 4) { + foreground = pixel(input, p); + p += 4; + } + var count = (mask & 8) ? input[p++] : 0; + if (p + count * (coloured ? 6 : 2) > input.length) { + return 0; + } + fill_rect(x + tx, y + ty, tw, th, background); + for (var i = 0; i < count; i++) { + var v = foreground; + if (coloured) { + v = pixel(input, p); + p += 4; + } + var at = input[p++]; + var size = input[p++]; + fill_rect(x + tx + (at >> 4), y + ty + (at & 15), (size >> 4) + 1, (size & 15) + 1, v); + } + } + } + return p; + } + + // Uses what it can of the input. Returns false when it needs more. + function step() { + if (state == "version") { + if (input.length < 12) { + return false; + } + take(12); + send(Array.from(new TextEncoder().encode("RFB 003.008\n"))); + state = "security"; + } else if (state == "security") { + if (input.length < 1 || input.length < 1 + input[0]) { + return false; + } + var types = take(1 + input[0]).subarray(1); + if (types.indexOf(1) < 0) { + throw "no security type this page can use"; + } + send([1]); + state = "result"; + } else if (state == "result") { + if (input.length < 4) { + return false; + } + if (get32(take(4), 0) != 0) { + throw "refused"; + } + // Shared, though the device takes over from other viewers anyway. + send([1]); + state = "init"; + } else if (state == "init") { + if (input.length < 24 || input.length < 24 + get32(input, 20)) { + return false; + } + var init = take(24 + get32(input, 20)); + resize(get16(init, 0), get16(init, 2)); + // 32 bits per pixel, depth 24, little endian, true colour, 8 bits each + // with red lowest. + send([0, 0, 0, 0, 32, 24, 0, 1].concat(u16(255), u16(255), u16(255), [0, 8, 16, 0, 0, 0])); + var encodings = [ENCODING_HEXTILE, ENCODING_RAW, ENCODING_DESKTOP_SIZE]; + var message = [2, 0].concat(u16(encodings.length)); + for (var i = 0; i < encodings.length; i++) { + message = message.concat(u32(encodings[i] >>> 0)); + } + send(message); + request_update(false); + state = "message"; + } else if (state == "message") { + if (input.length < 1) { + return false; + } + if (input[0] == 0) { + if (input.length < 4) { + return false; + } + rects_left = get16(take(4), 2); + state = "rect"; + } else if (input[0] == 2) { + take(1); + } else if (input[0] == 3) { + if (input.length < 8 || input.length < 8 + get32(input, 4)) { + return false; + } + take(8 + get32(input, 4)); + } else { + throw "unknown message " + input[0]; + } + } else if (state == "rect") { + if (rects_left == 0) { + context.putImageData(image, 0, 0); + updates++; + state = "message"; + request_update(true); + return true; + } + if (input.length < 12) { + return false; + } + var x = get16(input, 0), y = get16(input, 2), w = get16(input, 4), h = get16(input, 6); + var encoding = get32(input, 8) | 0; + if (encoding == ENCODING_RAW) { + if (input.length < 12 + w * h * 4) { + return false; + } + put_raw(x, y, w, h, input, 12); + take(12 + w * h * 4); + } else if (encoding == ENCODING_HEXTILE) { + var length = draw_hextile(x, y, w, h); + if (length == 0) { + return false; + } + take(length); + } else if (encoding == ENCODING_DESKTOP_SIZE) { + take(12); + resize(w, h); + } else { + throw "unknown encoding " + encoding; + } + rects_left--; + } + return true; + } + + function receive(data) { + received += data.length; + var joined = new Uint8Array(input.length + data.length); + joined.set(input); + joined.set(data, input.length); + input = joined; + try { + while (step()) { + } + } catch (e) { + status_text.textContent = "Error: " + e; + ws.close(); + } + } + + function connect() { + status_text.textContent = "Connecting"; + replaced = false; + input = new Uint8Array(0); + state = "version"; + ws = new WebSocket("ws://" + window.location.host + "/cp/display/"); + ws.binaryType = "arraybuffer"; + ws.onmessage = function(e) { + receive(new Uint8Array(e.data)); + }; + ws.onclose = function(e) { + if (e.code == 4000) { + replaced = true; + status_text.textContent = "Another viewer took over the display. Refresh to show it here."; + return; + } + status_text.textContent = "Disconnected"; + setTimeout(connect, 2000); + }; + } + + var KEYSYMS = { + "Enter": 0xff0d, "Backspace": 0xff08, "Tab": 0xff09, "Escape": 0xff1b, + "ArrowLeft": 0xff51, "ArrowUp": 0xff52, "ArrowRight": 0xff53, "ArrowDown": 0xff54, + "Home": 0xff50, "End": 0xff57, "Delete": 0xffff, "Control": 0xffe3 + }; + + function key_event(e, down) { + var keysym = KEYSYMS[e.key]; + if (keysym === undefined && e.key.length == 1) { + keysym = e.key.charCodeAt(0); + } + if (keysym === undefined || !ws || ws.readyState != WebSocket.OPEN || state == "version") { + return; + } + e.preventDefault(); + send([4, down ? 1 : 0, 0, 0].concat(u32(keysym))); + } + + // Typing on the picture goes to the serial console. + canvas.tabIndex = 0; + canvas.addEventListener("keydown", function(e) { + key_event(e, true); + }); + canvas.addEventListener("keyup", function(e) { + key_event(e, false); + }); + + document.getElementById("refresh").onclick = function() { + if (ws && ws.readyState == WebSocket.OPEN && image != null) { + request_update(false); + } else if (replaced) { + connect(); + } + }; + + function rotate(degrees) { + rotation = degrees % 360; + try { + if (rotation == 0) { + localStorage.removeItem("display_rotation"); + } else { + localStorage.setItem("display_rotation", rotation); + } + } catch (e) { + } + layout(); + } + + document.getElementById("rotate").onclick = function() { + rotate(rotation + 90); + }; + // Back to the display as the device sends it. + document.getElementById("unrotate").onclick = function() { + rotate(0); + }; + window.addEventListener("resize", layout); + layout(); + + setInterval(function() { + if (ws && ws.readyState == WebSocket.OPEN && image != null) { + status_text.textContent = canvas.width + "x" + canvas.height + ", " + + updates + " updates/s, " + (received / 1024).toFixed(1) + " KB/s"; + } + updates = 0; + received = 0; + }, 1000); + + connect(); +})(); diff --git a/supervisor/shared/web_workflow/static/serial.html b/supervisor/shared/web_workflow/static/serial.html index f94308d1867..10f6f0a93e4 100644 --- a/supervisor/shared/web_workflow/static/serial.html +++ b/supervisor/shared/web_workflow/static/serial.html @@ -7,7 +7,7 @@ - +

     
diff --git a/supervisor/shared/web_workflow/static/serial.js b/supervisor/shared/web_workflow/static/serial.js
index c8ee2537bae..90f88d11fdb 100644
--- a/supervisor/shared/web_workflow/static/serial.js
+++ b/supervisor/shared/web_workflow/static/serial.js
@@ -7,7 +7,7 @@ var log = document.getElementById("log");
 
 function set_enabled(enabled) {
   input.disabled = !enabled;
-  var buttons = document.querySelectorAll("button");
+  var buttons = document.querySelectorAll("#controls button");
   for (button of buttons) {
     button.disabled = !enabled;
   }
@@ -15,6 +15,12 @@ function set_enabled(enabled) {
 
 set_enabled(false);
 
+// Scrolls the log's box rather than the page, which may hold more than the log.
+function scroll_to_end() {
+  var box = log.parentElement;
+  box.scrollTop = box.scrollHeight;
+}
+
 function onSubmit() {
     ws.send("\r");
     input.value = "";
@@ -48,11 +54,15 @@ ws.onmessage = function(e) {
   } else {
     log.textContent += e.data;
   }
-  document.querySelector("span").scrollIntoView();
+  scroll_to_end();
 };
 
-ws.onclose = function() {
+ws.onclose = function(e) {
   set_enabled(false);
+  if (e.code == 4000) {
+    log.textContent += "\n[Another page took over the serial connection. Reload to use it here.]\n";
+    scroll_to_end();
+  }
 };
 
 ws.onerror = function(e) {
diff --git a/supervisor/shared/web_workflow/web_workflow.c b/supervisor/shared/web_workflow/web_workflow.c
index eea11bd5fb4..425c75dee16 100644
--- a/supervisor/shared/web_workflow/web_workflow.c
+++ b/supervisor/shared/web_workflow/web_workflow.c
@@ -7,7 +7,9 @@
 // Include strchrnul()
 #define _GNU_SOURCE
 
+#include 
 #include 
+#include 
 #include 
 
 #include "extmod/vfs.h"
@@ -15,15 +17,14 @@
 #include "genhdr/mpversion.h"
 #include "py/mperrno.h"
 #include "py/mpstate.h"
+#include "py/persistentcode.h"
 
-#include "shared-bindings/wifi/Radio.h"
-#include "shared/timeutils/timeutils.h"
-#include "supervisor/fatfs.h"
 #include "supervisor/filesystem.h"
 #include "supervisor/port.h"
 #include "supervisor/shared/reload.h"
 #include "supervisor/shared/web_workflow/web_workflow.h"
 #include "supervisor/shared/web_workflow/websocket.h"
+#include "supervisor/shared/web_workflow/display_stream.h"
 #include "supervisor/shared/workflow.h"
 
 #include "shared-bindings/hashlib/__init__.h"
@@ -42,12 +43,29 @@
 #include "shared-bindings/socketpool/Socket.h"
 #include "shared-bindings/socketpool/SocketPool.h"
 
+#if CIRCUITPY_HOSTNETWORK
+#include "bindings/hostnetwork/__init__.h"
+#endif
+
 #if CIRCUITPY_WIFI
+#include "common-hal/wifi/__init__.h"
 #include "shared-bindings/wifi/__init__.h"
+#include "shared-bindings/wifi/Radio.h"
+#endif
+
+#if CIRCUITPY_MII
+#include "shared-bindings/mii/__init__.h"
+#include "shared-bindings/mii/Ethernet.h"
 #endif
 
-#if CIRCUITPY_OS_GETENV
-#include "shared-module/os/__init__.h"
+#if CIRCUITPY_AIRLIFT
+#include "shared-module/_airlift/network.h"
+#include "shared-module/_airlift/transport.h"
+#include "supervisor/shared/tick.h"
+#endif
+
+#if CIRCUITPY_SETTINGS_TOML
+#include "supervisor/shared/settings.h"
 #endif
 
 enum request_state {
@@ -79,20 +97,30 @@ typedef struct {
     bool json;
     bool websocket;
     bool new_socket;
-    uint32_t websocket_version;
+    bool held;              // a file the running program uses: replied to once the VM stops
     // RFC6455 for websockets says this header should be 24 base64 characters long.
     char websocket_key[24 + 1];
 } _request;
 
+#if CIRCUITPY_WIFI
 static wifi_radio_error_t _wifi_status = WIFI_RADIO_ERROR_NONE;
+#endif
 
-#if CIRCUITPY_STATUS_BAR
+#if CIRCUITPY_STATUS_BAR && (CIRCUITPY_WIFI || CIRCUITPY_HOSTNETWORK || CIRCUITPY_MII || CIRCUITPY_AIRLIFT)
 // Store various last states to compute if status bar needs an update.
 static bool _last_enabled = false;
 static uint32_t _last_ip = 0;
+static mp_int_t _last_web_api_port = 80;
+#endif
+
+#if CIRCUITPY_STATUS_BAR && CIRCUITPY_WIFI
 static wifi_radio_error_t _last_wifi_status = WIFI_RADIO_ERROR_NONE;
 #endif
 
+#if CIRCUITPY_STATUS_BAR && CIRCUITPY_AIRLIFT
+static uint8_t _last_airlift_status = AIRLIFT_WL_NO_SHIELD;
+#endif
+
 #if CIRCUITPY_MDNS
 static mdns_server_obj_t mdns;
 #endif
@@ -171,11 +199,7 @@ static bool _base64_in_place(char *buf, size_t in_len, size_t out_len) {
     return true;
 }
 
-static void _update_encoded_ip(void) {
-    uint32_t ipv4_address = 0;
-    if (common_hal_wifi_radio_get_enabled(&common_hal_wifi_radio_obj)) {
-        ipv4_address = wifi_radio_get_ipv4_address(&common_hal_wifi_radio_obj);
-    }
+static void _update_encoded_ip(uint32_t ipv4_address) {
     if (_encoded_ip != ipv4_address) {
         uint8_t *octets = (uint8_t *)&ipv4_address;
         snprintf(_our_ip_encoded, sizeof(_our_ip_encoded), "%d.%d.%d.%d", octets[0], octets[1], octets[2], octets[3]);
@@ -183,81 +207,276 @@ static void _update_encoded_ip(void) {
     }
 }
 
+static bool _get_web_workflow_ip(uint32_t *ipv4_address) {
+    *ipv4_address = 0;
+    #if CIRCUITPY_WIFI
+    if (!common_hal_wifi_radio_get_enabled(&common_hal_wifi_radio_obj)) {
+        return false;
+    }
+    *ipv4_address = wifi_radio_get_ipv4_address(&common_hal_wifi_radio_obj);
+    return true;
+    #elif CIRCUITPY_HOSTNETWORK
+    // hostnetwork uses the host network namespace and is reachable via localhost.
+    *ipv4_address = 0x0100007f; // 127.0.0.1
+    return true;
+    #elif CIRCUITPY_MII
+    mii_ethernet_obj_t *eth = (mii_ethernet_obj_t *)mii_get_default_instance();
+    if (eth == NULL || !common_hal_mii_ethernet_get_enabled(eth)) {
+        return false;
+    }
+    *ipv4_address = mii_get_ipv4_address();
+    return true;
+    #elif CIRCUITPY_AIRLIFT
+    // Cached, so the status bar doesn't cause SPI traffic.
+    if (!airlift_transport_active()) {
+        return false;
+    }
+    *ipv4_address = airlift_network_ipv4_address();
+    return true;
+    #else
+    return false;
+    #endif
+}
+
+// Get the network interface hostname (the one sent to the DHCP server) when
+// no mDNS server is active to provide one. Never allocates. Returns "" when
+// there isn't one.
+static const char *_get_web_workflow_hostname(void) {
+    #if CIRCUITPY_WIFI
+    if (!common_hal_wifi_radio_get_enabled(&common_hal_wifi_radio_obj)) {
+        return "";
+    }
+    return wifi_get_hostname_raw();
+    #elif CIRCUITPY_MII
+    mii_ethernet_obj_t *eth = (mii_ethernet_obj_t *)mii_get_default_instance();
+    if (eth == NULL || !common_hal_mii_ethernet_get_enabled(eth)) {
+        return "";
+    }
+    return mii_get_hostname_raw();
+    #else
+    return "";
+    #endif
+}
+
+#if CIRCUITPY_STATUS_BAR
+static void _print_web_workflow_endpoint(void) {
+    mp_printf(&mp_plat_print, "%s", _our_ip_encoded);
+    if (web_api_port != 80) {
+        mp_printf(&mp_plat_print, ":%d", web_api_port);
+    }
+}
+#endif
+
 mdns_server_obj_t *supervisor_web_workflow_mdns(mp_obj_t network_interface) {
-    #if CIRCUITPY_MDNS
+    #if CIRCUITPY_MDNS && CIRCUITPY_WIFI
     if (network_interface == &common_hal_wifi_radio_obj &&
         mdns.base.type == &mdns_server_type) {
         return &mdns;
     }
     #endif
+    (void)network_interface;
     return NULL;
 }
 
 #if CIRCUITPY_STATUS_BAR
 bool supervisor_web_workflow_status_dirty(void) {
-    return common_hal_wifi_radio_get_enabled(&common_hal_wifi_radio_obj) != _last_enabled ||
-           _encoded_ip != _last_ip ||
-           _last_wifi_status != _wifi_status;
+    #if CIRCUITPY_WIFI || CIRCUITPY_HOSTNETWORK || CIRCUITPY_MII || CIRCUITPY_AIRLIFT
+    uint32_t ipv4_address = 0;
+    bool enabled = _get_web_workflow_ip(&ipv4_address);
+    if (enabled != _last_enabled || ipv4_address != _last_ip || web_api_port != _last_web_api_port) {
+        return true;
+    }
+    #if CIRCUITPY_WIFI
+    if (_last_wifi_status != _wifi_status) {
+        return true;
+    }
+    #endif
+    #if CIRCUITPY_AIRLIFT
+    if (_last_airlift_status != airlift_network_status()) {
+        return true;
+    }
+    #endif
+    return false;
+    #else
+    return false;
+    #endif
 }
 #endif
 
 #if CIRCUITPY_STATUS_BAR
 void supervisor_web_workflow_status(void) {
-    _last_enabled = common_hal_wifi_radio_get_enabled(&common_hal_wifi_radio_obj);
+    #if CIRCUITPY_WIFI || CIRCUITPY_HOSTNETWORK || CIRCUITPY_MII || CIRCUITPY_AIRLIFT
+    uint32_t ipv4_address = 0;
+    _last_enabled = _get_web_workflow_ip(&ipv4_address);
+    _last_web_api_port = web_api_port;
+
     if (_last_enabled) {
-        uint32_t ipv4_address = wifi_radio_get_ipv4_address(&common_hal_wifi_radio_obj);
+        _update_encoded_ip(ipv4_address);
+        _last_ip = _encoded_ip;
+
         if (ipv4_address != 0) {
-            _update_encoded_ip();
-            _last_ip = _encoded_ip;
-            mp_printf(&mp_plat_print, "%s", _our_ip_encoded);
-            if (web_api_port != 80) {
-                mp_printf(&mp_plat_print, ":%d", web_api_port);
-            }
+            _print_web_workflow_endpoint();
             // TODO: Use these unicode to show signal strength: ▂▄▆█
             return;
         }
-        serial_write_compressed(MP_ERROR_TEXT("Wi-Fi: "));
-        _last_wifi_status = _wifi_status;
-        if (_wifi_status == WIFI_RADIO_ERROR_AUTH_EXPIRE ||
-            _wifi_status == WIFI_RADIO_ERROR_AUTH_FAIL) {
-            serial_write_compressed(MP_ERROR_TEXT("Authentication failure"));
-        } else if (_wifi_status != WIFI_RADIO_ERROR_NONE) {
-            mp_printf(&mp_plat_print, "%d", _wifi_status);
-        } else if (ipv4_address == 0) {
-            _last_ip = 0;
-            serial_write_compressed(MP_ERROR_TEXT("No IP"));
-        } else {
-        }
+    }
+
+    #if CIRCUITPY_WIFI
+    serial_write_compressed(MP_ERROR_TEXT("Wi-Fi: "));
+    _last_wifi_status = _wifi_status;
+    if (!_last_enabled) {
+        serial_write_compressed(MP_ERROR_TEXT("off"));
+    } else if (_wifi_status == WIFI_RADIO_ERROR_AUTH_EXPIRE ||
+               _wifi_status == WIFI_RADIO_ERROR_AUTH_FAIL) {
+        serial_write_compressed(MP_ERROR_TEXT("Authentication failure"));
+    } else if (_wifi_status != WIFI_RADIO_ERROR_NONE) {
+        mp_printf(&mp_plat_print, "%d", _wifi_status);
     } else {
-        // Keep Wi-Fi print separate so its data can be matched with the one above.
-        serial_write_compressed(MP_ERROR_TEXT("Wi-Fi: "));
+        _last_ip = 0;
+        serial_write_compressed(MP_ERROR_TEXT("No IP"));
+    }
+    #elif CIRCUITPY_MII
+    _last_ip = 0;
+    serial_write_compressed(MP_ERROR_TEXT("No IP"));
+    #elif CIRCUITPY_AIRLIFT
+    serial_write_compressed(MP_ERROR_TEXT("Wi-Fi: "));
+    _last_airlift_status = airlift_network_status();
+    if (!_last_enabled) {
         serial_write_compressed(MP_ERROR_TEXT("off"));
+    } else if (_last_airlift_status == AIRLIFT_WL_CONNECT_FAILED) {
+        serial_write_compressed(MP_ERROR_TEXT("Authentication failure"));
+    } else {
+        _last_ip = 0;
+        serial_write_compressed(MP_ERROR_TEXT("No IP"));
+    }
+    #endif
+    #else
+    return;
+    #endif
+}
+#endif
+
+#if CIRCUITPY_WEB_WORKFLOW && CIRCUITPY_SETTINGS_TOML && (CIRCUITPY_WIFI || CIRCUITPY_HOSTNETWORK || CIRCUITPY_MII || CIRCUITPY_AIRLIFT)
+// Reads CIRCUITPY_WEB_API_PASSWORD into _api_password, encoded for HTTP basic
+// auth. Returns false if it isn't set.
+static bool _get_api_password(void) {
+    const size_t api_password_len = sizeof(_api_password) - 1;
+    settings_err_t result = settings_get_str("CIRCUITPY_WEB_API_PASSWORD", _api_password + 1, api_password_len);
+    if (result != SETTINGS_OK) {
+        return false;
     }
+    _api_password[0] = ':';
+    _base64_in_place(_api_password, strlen(_api_password), sizeof(_api_password) - 1);
+    return true;
+}
+#endif
+
+#if CIRCUITPY_WEB_WORKFLOW && CIRCUITPY_SETTINGS_TOML && (CIRCUITPY_WIFI || CIRCUITPY_HOSTNETWORK || CIRCUITPY_MII || CIRCUITPY_AIRLIFT)
+static bool _open_listening(void) {
+    #if CIRCUITPY_SOCKETPOOL_IPV6
+    bool opened = socketpool_socket(&pool, SOCKETPOOL_AF_INET6, SOCKETPOOL_SOCK_STREAM, 0, &listening);
+    #else
+    bool opened = socketpool_socket(&pool, SOCKETPOOL_AF_INET, SOCKETPOOL_SOCK_STREAM, 0, &listening);
+    #endif
+    // Ports with an offloaded network stack can refuse to create a
+    // socket until the interface has an address (this board returns
+    // ENOTCONN before DHCP completes). Binding and listening on the
+    // unset descriptor then fails with EBADF, and reporting success
+    // leaves the supervisor polling a socket that was never opened.
+    //
+    // Returning false avoids that but is not a retry: the background
+    // callback never re-enters this function, so the next attempt is
+    // the next supervisor_workflow_reset(), i.e. a VM restart. A board
+    // that only gets an address after boot will not bring the workflow
+    // up on its own until then. (AirLift boards do retry; see
+    // _airlift_retry_listening().)
+    if (!opened) {
+        return false;
+    }
+    common_hal_socketpool_socket_settimeout(&listening, 0);
+    if (common_hal_socketpool_socket_bind(&listening, "", 0, web_api_port) != 0) {
+        common_hal_socketpool_socket_close(&listening);
+        return false;
+    }
+    if (!common_hal_socketpool_socket_listen(&listening, 1)) {
+        common_hal_socketpool_socket_close(&listening);
+        return false;
+    }
+    #if CIRCUITPY_DISPLAYIO
+    display_stream_listen(&pool);
+    #endif
+    return true;
+}
+#endif
+
+#if CIRCUITPY_AIRLIFT
+// User code may reset the ESP32 or change its network, which closes the
+// listening socket, and nothing calls back when the network comes back. So the
+// background pass reopens it: right away after a reset, otherwise at most every
+// 5 seconds. It is never closed to reopen it; nina-fw can't stop a listener.
+static void _airlift_retry_listening(void) {
+    static uint64_t last_try_ms;
+    static uint32_t last_try_generation;
+    if (!common_hal_socketpool_socket_get_closed(&listening) ||
+        airlift_network_status() != AIRLIFT_WL_CONNECTED) {
+        return;
+    }
+    uint64_t now = supervisor_ticks_ms64();
+    if (last_try_generation == airlift_transport_generation() && now - last_try_ms < 5000) {
+        return;
+    }
+    last_try_ms = now;
+    last_try_generation = airlift_transport_generation();
+    _open_listening();
 }
 #endif
 
 bool supervisor_start_web_workflow(void) {
-    #if CIRCUITPY_WEB_WORKFLOW && CIRCUITPY_WIFI && CIRCUITPY_OS_GETENV
+    #if CIRCUITPY_WEB_WORKFLOW && CIRCUITPY_SETTINGS_TOML && (CIRCUITPY_WIFI || CIRCUITPY_HOSTNETWORK || CIRCUITPY_MII || CIRCUITPY_AIRLIFT)
+
+    #if CIRCUITPY_WIFI
+    mp_obj_t socketpool_radio = MP_OBJ_FROM_PTR(&common_hal_wifi_radio_obj);
+    #elif CIRCUITPY_MII
+    mp_obj_t socketpool_radio = mii_get_default_instance();
+    if (socketpool_radio == NULL) {
+        // The board never registered its ethernet instance.
+        return false;
+    }
+    #elif CIRCUITPY_AIRLIFT
+    mp_obj_t socketpool_radio = MP_OBJ_FROM_PTR(&airlift_socketpool_interface);
+    #else
+    mp_obj_t socketpool_radio = MP_OBJ_FROM_PTR(&common_hal_hostnetwork_obj);
+    #endif
 
+    settings_err_t result;
+
+    #if CIRCUITPY_WIFI || CIRCUITPY_AIRLIFT
     char ssid[33];
     char password[64];
 
-    os_getenv_err_t result = common_hal_os_getenv_str("CIRCUITPY_WIFI_SSID", ssid, sizeof(ssid));
-    if (result != GETENV_OK || strlen(ssid) < 1) {
+    result = settings_get_str("CIRCUITPY_WIFI_SSID", ssid, sizeof(ssid));
+    if (result != SETTINGS_OK || strlen(ssid) < 1) {
         return false;
     }
 
-    result = common_hal_os_getenv_str("CIRCUITPY_WIFI_PASSWORD", password, sizeof(password));
-    if (result == GETENV_ERR_NOT_FOUND) {
+    result = settings_get_str("CIRCUITPY_WIFI_PASSWORD", password, sizeof(password));
+    if (result == SETTINGS_ERR_NOT_FOUND) {
         // if password is unspecified, assume an open network
         password[0] = '\0';
-    } else if (result != GETENV_OK) {
+    } else if (result != SETTINGS_OK) {
         return false;
     }
+    #endif
 
+    #if CIRCUITPY_WIFI
     if (!common_hal_wifi_radio_get_enabled(&common_hal_wifi_radio_obj)) {
         common_hal_wifi_init(false);
         common_hal_wifi_radio_set_enabled(&common_hal_wifi_radio_obj, true);
+        // The radio stays off if Wi-Fi couldn't start, for example with no Wi-Fi firmware on a
+        // co-processor. connect() raises in that case, and there is no VM to catch it here.
+        if (!common_hal_wifi_radio_get_enabled(&common_hal_wifi_radio_obj)) {
+            return false;
+        }
     }
 
     // TODO: Do our own scan so that we can find the channel we want before calling connect.
@@ -275,50 +494,86 @@ bool supervisor_start_web_workflow(void) {
         common_hal_wifi_radio_set_enabled(&common_hal_wifi_radio_obj, false);
         return false;
     }
+    #elif CIRCUITPY_AIRLIFT
+    // Without an API password there's no web workflow, so leave the ESP32 to
+    // user code. Native Wi-Fi connects without one, so this is read here only
+    // for AirLift, before the ESP32 is touched.
+    if (!_get_api_password()) {
+        return false;
+    }
+
+    if (!airlift_transport_init()) {
+        return false;
+    }
+
+    // Returns early if already connected to this network, so the open
+    // connections survive. If it fails, the background keeps trying.
+    airlift_network_join(ssid, password);
+    #endif
+
+    #if CIRCUITPY_MII && !CIRCUITPY_WIFI
+    mii_ethernet_obj_t *eth = (mii_ethernet_obj_t *)mii_get_default_instance();
+    if (eth == NULL) {
+        return false;
+    }
+    // Re-enable the interface in case user code disabled it before a reload.
+    if (!common_hal_mii_ethernet_get_enabled(eth)) {
+        common_hal_mii_ethernet_set_enabled(eth, true);
+    }
+
+    // The listening socket cannot be created until the interface has an
+    // address, so wait out the DHCP lease. This brings the workflow up during
+    // the first VM start instead of after the next one.
+    mii_wait_for_lease();
+    #endif
 
-    // Skip starting the workflow if we're not starting from power on or reset.
+    // Skip starting the workflow if the reset reason reflects a problem.
     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_DEEP_SLEEP_ALARM &&
-        reset_reason != RESET_REASON_UNKNOWN &&
-        reset_reason != RESET_REASON_SOFTWARE) {
+    if (reset_reason == MCU_RESET_REASON_BROWNOUT ||
+        reset_reason == MCU_RESET_REASON_RESCUE_DEBUG) {
         return false;
     }
 
     bool initialized = pool.base.type == &socketpool_socketpool_type;
 
     if (!initialized) {
-        result = common_hal_os_getenv_str("CIRCUITPY_WEB_INSTANCE_NAME", web_instance_name, sizeof(web_instance_name));
-        if (result != GETENV_OK || web_instance_name[0] == '\0') {
+        result = settings_get_str("CIRCUITPY_WEB_INSTANCE_NAME", web_instance_name, sizeof(web_instance_name));
+        if (result != SETTINGS_OK || web_instance_name[0] == '\0') {
             strcpy(web_instance_name, MICROPY_HW_BOARD_NAME);
         }
 
         // (leaves new_port unchanged on any failure)
-        (void)common_hal_os_getenv_int("CIRCUITPY_WEB_API_PORT", &web_api_port);
-
-        const size_t api_password_len = sizeof(_api_password) - 1;
-        result = common_hal_os_getenv_str("CIRCUITPY_WEB_API_PASSWORD", _api_password + 1, api_password_len);
-        if (result == GETENV_OK) {
-            _api_password[0] = ':';
-            _base64_in_place(_api_password, strlen(_api_password), sizeof(_api_password) - 1);
-        } else { // Skip starting web-workflow when no password is passed.
+        (void)settings_get_int("CIRCUITPY_WEB_API_PORT", &web_api_port);
+
+        if (!_get_api_password()) { // Skip starting web-workflow when no password is passed.
             return false;
         }
 
         pool.base.type = &socketpool_socketpool_type;
-        common_hal_socketpool_socketpool_construct(&pool, &common_hal_wifi_radio_obj);
+        common_hal_socketpool_socketpool_construct(&pool, socketpool_radio);
 
         socketpool_socket_reset(&listening);
         socketpool_socket_reset(&active);
 
         websocket_init();
+        #if CIRCUITPY_DISPLAYIO
+        display_stream_init();
+        mp_int_t vnc_port = 0;
+        (void)settings_get_int("CIRCUITPY_WEB_VNC_PORT", &vnc_port);
+        bool vnc_keys = false;
+        (void)settings_get_bool("CIRCUITPY_WEB_VNC_KEYS", &vnc_keys);
+        display_stream_set_vnc(vnc_port, vnc_keys);
+        mp_int_t display_rate_limit = 0;
+        (void)settings_get_int("CIRCUITPY_WEB_DISPLAY_RATE_LIMIT", &display_rate_limit);
+        display_stream_set_rate_limit(display_rate_limit);
+        #endif
     }
 
     initialized = pool.base.type == &socketpool_socketpool_type;
 
     if (initialized) {
-        if (!common_hal_socketpool_socket_get_closed(&active)) {
+        // A held request waits for exactly this reset, so keep its socket.
+        if (!active_request.held && !common_hal_socketpool_socket_get_closed(&active)) {
             common_hal_socketpool_socket_close(&active);
         }
 
@@ -337,16 +592,13 @@ bool supervisor_start_web_workflow(void) {
         }
         #endif
 
-        if (common_hal_socketpool_socket_get_closed(&listening)) {
-            #if CIRCUITPY_SOCKETPOOL_IPV6
-            socketpool_socket(&pool, SOCKETPOOL_AF_INET6, SOCKETPOOL_SOCK_STREAM, 0, &listening);
+        if (common_hal_socketpool_socket_get_closed(&listening) && !_open_listening()) {
+            #if CIRCUITPY_AIRLIFT
+            // Report success anyway, so the background callback is installed:
+            // it keeps trying (_airlift_retry_listening()).
             #else
-            socketpool_socket(&pool, SOCKETPOOL_AF_INET, SOCKETPOOL_SOCK_STREAM, 0, &listening);
+            return false;
             #endif
-            common_hal_socketpool_socket_settimeout(&listening, 0);
-            // Bind to any ip. (Not checking for failures)
-            common_hal_socketpool_socket_bind(&listening, "", 0, web_api_port);
-            common_hal_socketpool_socket_listen(&listening, 1);
         }
         // Wake polling thread (maybe)
         socketpool_socket_poll_resume();
@@ -373,7 +625,7 @@ void web_workflow_send_raw(socketpool_socket_obj_t *socket, bool flush, const ui
             total_sent += sent;
             if (total_sent < len) {
                 // Yield so that network code can run.
-                port_yield();
+                port_task_sleep_ms(4);
             }
         }
     }
@@ -652,11 +904,13 @@ static void _reply_redirect(socketpool_socket_obj_t *socket, _request *request,
 }
 #endif
 
-static void _reply_directory_json(socketpool_socket_obj_t *socket, _request *request, fs_user_mount_t *fs_mount, FF_DIR *dir, const char *request_path, const char *path) {
-    FILINFO file_info;
-    char *fn = file_info.fname;
-    FRESULT res = f_readdir(dir, &file_info);
-    if (res != FR_OK) {
+static void _reply_directory_json(socketpool_socket_obj_t *socket, _request *request, supervisor_vfs_t *fs_mount, supervisor_vfs_dir_t *dir, const char *request_path, const char *path) {
+    char fn[FF_MAX_LFN + 1];
+    bool is_dir = false;
+    size_t file_size = 0;
+    uint64_t mtime_ns = 0;
+    supervisor_fs_err_t res = supervisor_vfs_readdir(dir, fn, sizeof(fn), &is_dir, &file_size, &mtime_ns);
+    if (res != SUPERVISOR_FS_OK) {
         _reply_missing(socket, request);
         return;
     }
@@ -666,18 +920,12 @@ static void _reply_directory_json(socketpool_socket_obj_t *socket, _request *req
     _send_str(socket, "\r\n");
     mp_print_t _socket_print = {socket, _print_chunk};
 
-    // Send mount info.
-    DWORD free_clusters = 0;
-    FATFS *fatfs = &fs_mount->fatfs;
-    f_getfree(fatfs, &free_clusters);
-    size_t ssize;
-    #if FF_MAX_SS != FF_MIN_SS
-    ssize = fatfs->ssize;
-    #else
-    ssize = FF_MIN_SS;
-    #endif
-    uint32_t cluster_size = fatfs->csize * ssize;
-    uint32_t total_clusters = fatfs->n_fatent - 2;
+    // Send mount info. Counts are in filesystem blocks: clusters on FAT,
+    // blocks on littlefs.
+    size_t block_size = 0;
+    size_t total_blocks = 0;
+    size_t free_blocks = 0;
+    supervisor_vfs_statfs(fs_mount, &block_size, &total_blocks, &free_blocks);
 
     const char *writable = "false";
     // Test to see if we can grab the write lock. USB will grab the underlying
@@ -691,20 +939,20 @@ static void _reply_directory_json(socketpool_socket_obj_t *socket, _request *req
         "{\"free\": %u, "
         "\"total\": %u, "
         "\"block_size\": %u, "
-        "\"writable\": %s, ", free_clusters, total_clusters, cluster_size, writable);
+        "\"writable\": %s, ", free_blocks, total_blocks, block_size, writable);
 
     // Send file list
     _send_chunk(socket, "\"files\": [");
     bool first = true;
 
-    while (res == FR_OK && fn[0] != 0) {
+    while (res == SUPERVISOR_FS_OK && fn[0] != 0) {
         if (!first) {
             _send_chunk(socket, ",");
         }
         _send_chunks(socket,
-            "{\"name\": \"", file_info.fname, "\",",
+            "{\"name\": \"", fn, "\",",
             "\"directory\": ", NULL);
-        if ((file_info.fattrib & AM_DIR) != 0) {
+        if (is_dir) {
             _send_chunk(socket, "true");
         } else {
             _send_chunk(socket, "false");
@@ -713,31 +961,31 @@ static void _reply_directory_json(socketpool_socket_obj_t *socket, _request *req
         // LittleFS.
         _send_chunk(socket, ", ");
 
-        uint32_t truncated_time = timeutils_mktime(1980 + (file_info.fdate >> 9),
-            (file_info.fdate >> 5) & 0xf,
-            file_info.fdate & 0x1f,
-            file_info.ftime >> 11,
-            (file_info.ftime >> 5) & 0x3f,
-            (file_info.ftime & 0x1f) * 2);
-
-        // Manually append zeros to make the time nanoseconds. Support for printing 64 bit numbers
-        // varies across chipsets.
-        mp_printf(&_socket_print, "\"modified_ns\": %lu000000000, ", truncated_time);
-        size_t file_size = 0;
-        if ((file_info.fattrib & AM_DIR) == 0) {
-            file_size = file_info.fsize;
+        // mpprint doesn't support 64-bit formats on all targets, so print the
+        // seconds and zero-padded remainder of the nanosecond value separately.
+        mp_uint_t mtime_secs = (mp_uint_t)(mtime_ns / 1000000000ULL);
+        mp_uint_t mtime_frac = (mp_uint_t)(mtime_ns % 1000000000ULL);
+        if (mtime_secs == 0) {
+            // Avoid a leading zero, which isn't valid JSON.
+            mp_printf(&_socket_print, "\"modified_ns\": %u, ", mtime_frac);
+        } else {
+            mp_printf(&_socket_print, "\"modified_ns\": %u%09u, ", mtime_secs, mtime_frac);
+        }
+        if (!is_dir) {
+            mp_printf(&_socket_print, "\"file_size\": %d }", file_size);
+        } else {
+            _send_chunk(socket, "\"file_size\": 0 }");
         }
-        mp_printf(&_socket_print, "\"file_size\": %d }", file_size);
 
         first = false;
-        res = f_readdir(dir, &file_info);
+        res = supervisor_vfs_readdir(dir, fn, sizeof(fn), &is_dir, &file_size, &mtime_ns);
     }
     _send_chunk(socket, "]}");
     _send_chunk(socket, "");
 }
 
-static void _reply_with_file(socketpool_socket_obj_t *socket, _request *request, const char *filename, FIL *active_file) {
-    uint32_t total_length = f_size(active_file);
+static void _reply_with_file(socketpool_socket_obj_t *socket, _request *request, const char *filename, supervisor_vfs_file_t *active_file) {
+    uint32_t total_length = supervisor_vfs_file_size(active_file);
 
     _send_str(socket, "HTTP/1.1 200 OK\r\n");
     mp_print_t _socket_print = {socket, _print_raw};
@@ -762,7 +1010,7 @@ static void _reply_with_file(socketpool_socket_obj_t *socket, _request *request,
     while (total_read < total_length) {
         uint8_t data_buffer[64];
         size_t quantity_read;
-        f_read(active_file, data_buffer, 64, &quantity_read);
+        supervisor_vfs_read_file(active_file, data_buffer, 64, &quantity_read);
         total_read += quantity_read;
         // When getting near the end of the file, disable Nagle's combining algorithm so that
         // data is sent immediately.
@@ -825,7 +1073,6 @@ static void _reply_with_devices_json(socketpool_socket_obj_t *socket, _request *
             "\"instance_name\": \"%s\", "
             "\"port\": %d, "
             "\"ip\": \"%d.%d.%d.%d\"}", hostname, instance_name, port, octets[0], octets[1], octets[2], octets[3]);
-        common_hal_mdns_remoteservice_deinit(&found_devices[i]);
     }
     #endif
     _send_chunk(socket, "]}");
@@ -840,14 +1087,19 @@ static void _reply_with_version_json(socketpool_socket_obj_t *socket, _request *
     mp_print_t _socket_print = {socket, _print_chunk};
 
     const char *hostname = "";
-    const char *instance_name = "";
     #if CIRCUITPY_MDNS
     if (!common_hal_mdns_server_deinited(&mdns)) {
         hostname = common_hal_mdns_server_get_hostname(&mdns);
-        instance_name = common_hal_mdns_server_get_instance_name(&mdns);
     }
     #endif
-    _update_encoded_ip();
+    if (hostname[0] == '\0') {
+        // Fall back to the network interface hostname when no mDNS server is
+        // advertising one.
+        hostname = _get_web_workflow_hostname();
+    }
+    uint32_t ipv4_address = 0;
+    (void)_get_web_workflow_ip(&ipv4_address);
+    _update_encoded_ip(ipv4_address);
     // Note: this leverages the fact that C concats consecutive string literals together.
     mp_printf(&_socket_print,
         "{\"web_api_version\": 4, "
@@ -855,11 +1107,14 @@ static void _reply_with_version_json(socketpool_socket_obj_t *socket, _request *
         "\"build_date\": \"" MICROPY_BUILD_DATE "\", "
         "\"board_name\": \"%s\", "
         "\"mcu_name\": \"" MICROPY_HW_MCU_NAME "\", "
+        #if MICROPY_PERSISTENT_CODE_LOAD_NATIVE
+        "\"architecture\": \"" MPY_FEATURE_ARCH_NAME "\", "
+        #endif
         "\"board_id\": \"" CIRCUITPY_BOARD_ID "\", "
         "\"creator_id\": %u, "
         "\"creation_id\": %u, "
         "\"hostname\": \"%s\", "
-        "\"port\": %d, ", instance_name, CIRCUITPY_CREATOR_ID, CIRCUITPY_CREATION_ID, hostname, web_api_port, _our_ip_encoded);
+        "\"port\": %d, ", MICROPY_HW_BOARD_NAME, CIRCUITPY_CREATOR_ID, CIRCUITPY_CREATION_ID, hostname, web_api_port, _our_ip_encoded);
     #if CIRCUITPY_MICROCONTROLLER && COMMON_HAL_MCU_PROCESSOR_UID_LENGTH > 0
     uint8_t raw_id[COMMON_HAL_MCU_PROCESSOR_UID_LENGTH];
     common_hal_mcu_processor_get_uid(raw_id);
@@ -887,23 +1142,17 @@ static void _reply_with_diskinfo_json(socketpool_socket_obj_t *socket, _request
         if (i > 0) {
             _send_chunk(socket, ",");
         }
-        fs_user_mount_t *fs = MP_OBJ_TO_PTR(vfs->obj);
-        // Skip non-fat and non-native block file systems.
-        if (fs->base.type != &mp_fat_vfs_type || (fs->blockdev.flags & MP_BLOCKDEV_FLAG_NATIVE) == 0) {
+        supervisor_vfs_t *fs = MP_OBJ_TO_PTR(vfs->obj);
+        // Skip filesystems the supervisor can't work with (non-fat and
+        // non-native block file systems).
+        if (!supervisor_vfs_supported(fs)) {
             vfs = vfs->next;
             continue;
         }
-        DWORD free_clusters = 0;
-        FATFS *fatfs = &fs->fatfs;
-        f_getfree(fatfs, &free_clusters);
-        size_t ssize;
-        #if FF_MAX_SS != FF_MIN_SS
-        ssize = fatfs->ssize;
-        #else
-        ssize = FF_MIN_SS;
-        #endif
-        size_t block_size = fatfs->csize * ssize;
-        size_t total_size = fatfs->n_fatent - 2;
+        size_t block_size = 0;
+        size_t total_size = 0;
+        size_t free_blocks = 0;
+        supervisor_vfs_statfs(fs, &block_size, &total_size, &free_blocks);
 
         const char *writable = "false";
         if (filesystem_lock(fs)) {
@@ -915,7 +1164,7 @@ static void _reply_with_diskinfo_json(socketpool_socket_obj_t *socket, _request
             "\"free\": %u, "
             "\"total\": %u, "
             "\"block_size\": %u, "
-            "\"writable\": %s}", vfs->str, free_clusters, total_size, block_size, writable);
+            "\"writable\": %s}", vfs->str, free_blocks, total_size, block_size, writable);
         i++;
         vfs = vfs->next;
     }
@@ -925,21 +1174,6 @@ static void _reply_with_diskinfo_json(socketpool_socket_obj_t *socket, _request
     _send_chunk(socket, "");
 }
 
-
-// FATFS has a two second timestamp resolution but the BLE API allows for nanosecond resolution.
-// This function truncates the time the time to a resolution storable by FATFS and fills in the
-// FATFS encoded version into fattime.
-static uint64_t truncate_time(uint64_t input_time, DWORD *fattime) {
-    timeutils_struct_time_t tm;
-    uint64_t seconds_since_epoch = timeutils_seconds_since_epoch_from_nanoseconds_since_1970(input_time);
-    timeutils_seconds_since_epoch_to_struct_time(seconds_since_epoch, &tm);
-    uint64_t truncated_time = timeutils_nanoseconds_since_epoch_to_nanoseconds_since_1970((seconds_since_epoch / 2) * 2 * 1000000000);
-
-    *fattime = ((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);
-    return truncated_time;
-}
-
 static void _discard_incoming(socketpool_socket_obj_t *socket, size_t amount) {
     size_t discarded = 0;
     while (discarded < amount) {
@@ -956,40 +1190,51 @@ static void _discard_incoming(socketpool_socket_obj_t *socket, size_t amount) {
     }
 }
 
-static void _write_file_and_reply(socketpool_socket_obj_t *socket, _request *request, fs_user_mount_t *fs_mount, const TCHAR *path) {
-    FIL active_file;
+static void _write_file_and_reply(socketpool_socket_obj_t *socket, _request *request, supervisor_vfs_t *fs_mount, const TCHAR *path) {
+    supervisor_vfs_file_t active_file;
 
     if (!filesystem_lock(fs_mount)) {
         _discard_incoming(socket, request->content_length);
         _reply_conflict(socket, request);
         return;
     }
-    if (request->timestamp_ms > 0) {
-        DWORD fattime;
-        truncate_time(request->timestamp_ms * 1000000, &fattime);
-        override_fattime(fattime);
-    }
 
-    FATFS *fs = &fs_mount->fatfs;
-    FRESULT result = f_open(fs, &active_file, path, FA_WRITE);
+    uint64_t mtime_ns = request->timestamp_ms > 0 ? (uint64_t)request->timestamp_ms * 1000000 : 0;
+
+    supervisor_fs_err_t result = supervisor_vfs_open_file(fs_mount, path, SUPERVISOR_FS_OPEN_WRITE, mtime_ns, &active_file);
     bool new_file = false;
     size_t old_length = 0;
-    if (result == FR_NO_FILE) {
+    if (result == SUPERVISOR_FS_NO_FILE) {
         new_file = true;
-        result = f_open(fs, &active_file, path, FA_WRITE | FA_OPEN_ALWAYS);
-    } else {
-        old_length = f_size(&active_file);
+        result = supervisor_vfs_open_file(fs_mount, path,
+            SUPERVISOR_FS_OPEN_WRITE | SUPERVISOR_FS_OPEN_CREATE, mtime_ns, &active_file);
+    } else if (result == SUPERVISOR_FS_OK) {
+        old_length = supervisor_vfs_file_size(&active_file);
     }
 
-    if (result == FR_NO_PATH) {
-        override_fattime(0);
+    if (result == SUPERVISOR_FS_BUSY) {
+        filesystem_unlock(fs_mount);
+        request->held = true;                   // the body stays unread until we try again
+        return;
+    }
+    if (result == SUPERVISOR_FS_NO_PATH) {
         filesystem_unlock(fs_mount);
         _discard_incoming(socket, request->content_length);
         _reply_missing(socket, request);
         return;
     }
-    if (result != FR_OK) {
-        override_fattime(0);
+    if (result == SUPERVISOR_FS_WRITE_PROTECTED) {
+        // The filesystem is held by something else with write access (most
+        // commonly USB-MSC: the host has CIRCUITPY mounted, so CircuitPython
+        // can't write through FatFS). Match the mkdir/move/delete paths and
+        // reply 409 Conflict so clients can show an actionable message
+        // ("eject CIRCUITPY / disable USB MSC") instead of a generic 500.
+        filesystem_unlock(fs_mount);
+        _discard_incoming(socket, request->content_length);
+        _reply_conflict(socket, request);
+        return;
+    }
+    if (result != SUPERVISOR_FS_OK) {
         filesystem_unlock(fs_mount);
         _discard_incoming(socket, request->content_length);
         _reply_server_error(socket, request);
@@ -997,19 +1242,18 @@ static void _write_file_and_reply(socketpool_socket_obj_t *socket, _request *req
     }
 
     // Change the file size to start.
-    f_lseek(&active_file, request->content_length);
-    if (f_tell(&active_file) < request->content_length) {
+    supervisor_vfs_seek_file(&active_file, request->content_length);
+    if (supervisor_vfs_tell_file(&active_file) < request->content_length) {
         if (!new_file) {
             // Truncate the file back to the old length.
-            f_lseek(&active_file, old_length);
-            f_truncate(&active_file);
+            supervisor_vfs_seek_file(&active_file, old_length);
+            supervisor_vfs_truncate_file(&active_file);
         }
-        f_close(&active_file);
+        supervisor_vfs_close_file(&active_file);
 
         if (new_file) {
-            f_unlink(fs, path);
+            supervisor_vfs_unlink(fs_mount, path);
         }
-        override_fattime(0);
         filesystem_unlock(fs_mount);
         // Too large.
         if (request->expect) {
@@ -1022,8 +1266,10 @@ static void _write_file_and_reply(socketpool_socket_obj_t *socket, _request *req
     } else if (request->expect) {
         _reply_continue(socket, request);
     }
-    f_truncate(&active_file);
-    f_rewind(&active_file);
+    // Truncate to content_length (current offset) and rewind so that the body
+    // overwrites the file from the start.
+    supervisor_vfs_truncate_file(&active_file);
+    supervisor_vfs_seek_file(&active_file, 0);
 
     size_t total_read = 0;
     bool error = false;
@@ -1039,18 +1285,17 @@ static void _write_file_and_reply(socketpool_socket_obj_t *socket, _request *req
             break;
         }
         total_read += len;
-        UINT actual;
-        f_write(&active_file, bytes, len, &actual);
-        if (actual < (UINT)len) {
+        size_t actual;
+        supervisor_fs_err_t write_result = supervisor_vfs_write_file(&active_file, bytes, len, &actual);
+        if (actual < (size_t)len || write_result != SUPERVISOR_FS_OK) {
             error = true;
             break;
         }
     }
 
-    f_close(&active_file);
+    supervisor_vfs_close_file(&active_file);
     filesystem_unlock(fs_mount);
 
-    override_fattime(0);
     if (error) {
         _discard_incoming(socket, request->content_length - total_read);
         _reply_server_error(socket, request);
@@ -1073,6 +1318,10 @@ STATIC_FILE(edit_js);
 STATIC_FILE(style_css);
 STATIC_FILE(serial_html);
 STATIC_FILE(serial_js);
+#if CIRCUITPY_DISPLAYIO
+STATIC_FILE(display_html);
+STATIC_FILE(display_js);
+#endif
 STATIC_FILE(blinka_32x32_ico);
 
 static void _reply_static(socketpool_socket_obj_t *socket, _request *request, const uint8_t *response, size_t response_len, const char *content_type) {
@@ -1085,6 +1334,10 @@ static void _reply_static(socketpool_socket_obj_t *socket, _request *request, co
         "Content-Encoding: gzip\r\n",
         "Content-Length: ", encoded_len, "\r\n",
         "Content-Type: ", content_type, "\r\n",
+        #if CIRCUITPY_DEBUG == 0
+        "Cache-Control: max-age=31536000\r\n", // Cache for a year.
+        "Vary: Accept\r\n",
+        #endif
         "\r\n", NULL);
     web_workflow_send_raw(socket, true, response, response_len);
 }
@@ -1110,6 +1363,12 @@ static void _reply_websocket_upgrade(socketpool_socket_obj_t *socket, _request *
         "Connection: Upgrade\r\n",
         "Sec-WebSocket-Accept: ", encoded_accept, "\r\n",
         "\r\n", NULL);
+    #if CIRCUITPY_DISPLAYIO
+    if (strcmp(request->path, "/cp/display/") == 0) {
+        display_stream_handoff(socket, true);
+        return;
+    }
+    #endif
     websocket_handoff(socket);
     // socket is now closed and "disconnected".
 }
@@ -1146,7 +1405,19 @@ static void _decode_percents(char *str) {
     }
 }
 
+// Parse leading decimal digits. Overflow is not checked.
+// Used instead of strtoul() and strtoull(), which would pull in libc code.
+static uint64_t _parse_decimal(const char *str) {
+    uint64_t value = 0;
+    while ('0' <= *str && *str <= '9') {
+        value = value * 10 + (*str - '0');
+        str++;
+    }
+    return value;
+}
+
 static bool _reply(socketpool_socket_obj_t *socket, _request *request) {
+    request->held = false;
     if (request->redirect) {
         #if CIRCUITPY_MDNS
         if (!common_hal_mdns_server_deinited(&mdns)) {
@@ -1192,12 +1463,14 @@ static bool _reply(socketpool_socket_obj_t *socket, _request *request) {
             // Delete is almost identical for files and directories so share the
             // implementation.
             if (strcasecmp(request->method, "DELETE") == 0) {
-                FRESULT result = supervisor_workflow_delete_recursive(path);
-                if (result == FR_WRITE_PROTECTED) {
+                supervisor_fs_err_t result = supervisor_workflow_delete_recursive(path);
+                if (result == SUPERVISOR_FS_BUSY) {
+                    request->held = true;
+                } else if (result == SUPERVISOR_FS_WRITE_PROTECTED) {
                     _reply_conflict(socket, request);
-                } else if (result == FR_NO_PATH || result == FR_NO_FILE) {
+                } else if (result == SUPERVISOR_FS_NO_PATH || result == SUPERVISOR_FS_NO_FILE) {
                     _reply_missing(socket, request);
-                } else if (result != FR_OK) {
+                } else if (result != SUPERVISOR_FS_OK) {
                     _reply_server_error(socket, request);
                 } else {
                     _reply_no_content(socket, request);
@@ -1212,14 +1485,14 @@ static bool _reply(socketpool_socket_obj_t *socket, _request *request) {
                     destination[destinationlen - 1] = '\0';
                 }
 
-                FRESULT result = supervisor_workflow_move(path, destination);
-                if (result == FR_WRITE_PROTECTED) {
+                supervisor_fs_err_t result = supervisor_workflow_move(path, destination);
+                if (result == SUPERVISOR_FS_WRITE_PROTECTED) {
                     _reply_conflict(socket, request);
-                } else if (result == FR_EXIST) { // File exists and won't be overwritten.
+                } else if (result == SUPERVISOR_FS_EXIST) { // File exists and won't be overwritten.
                     _reply_precondition_failed(socket, request);
-                } else if (result == FR_NO_PATH || result == FR_NO_FILE) { // Missing higher directories or target file.
+                } else if (result == SUPERVISOR_FS_NO_PATH || result == SUPERVISOR_FS_NO_FILE) { // Missing higher directories or target file.
                     _reply_missing(socket, request);
-                } else if (result != FR_OK) {
+                } else if (result != SUPERVISOR_FS_OK) {
                     _reply_server_error(socket, request);
                 } else {
                     _reply_created(socket, request);
@@ -1227,18 +1500,15 @@ static bool _reply(socketpool_socket_obj_t *socket, _request *request) {
                 }
                 return false;
             } else if (directory && strcasecmp(request->method, "PUT") == 0) {
-                DWORD fattime = 0;
-                if (request->timestamp_ms > 0) {
-                    truncate_time(request->timestamp_ms * 1000000, &fattime);
-                }
-                FRESULT result = supervisor_workflow_mkdir_parents(fattime, path);
-                if (result == FR_WRITE_PROTECTED) {
+                uint64_t mtime_ns = request->timestamp_ms > 0 ? (uint64_t)request->timestamp_ms * 1000000 : 0;
+                supervisor_fs_err_t result = supervisor_workflow_mkdir_parents(mtime_ns, path);
+                if (result == SUPERVISOR_FS_WRITE_PROTECTED) {
                     _reply_conflict(socket, request);
-                } else if (result == FR_EXIST) {
+                } else if (result == SUPERVISOR_FS_EXIST) {
                     _reply_no_content(socket, request);
-                } else if (result == FR_NO_PATH) {
+                } else if (result == SUPERVISOR_FS_NO_PATH) {
                     _reply_missing(socket, request);
-                } else if (result != FR_OK) {
+                } else if (result != SUPERVISOR_FS_OK) {
                     _reply_server_error(socket, request);
                 } else {
                     _reply_created(socket, request);
@@ -1248,43 +1518,28 @@ static bool _reply(socketpool_socket_obj_t *socket, _request *request) {
             }
 
             // These responses don't use helpers because they stream data in and
-            // out. So, share the mount lookup code.
+            // out. So, share the mount lookup code. filesystem_for_path handles
+            // both the root filesystem and additional mounts, whether they are
+            // FAT or littlefs.
             const char *path_out = NULL;
-            mp_vfs_mount_t *vfs = mp_vfs_lookup_path(path, &path_out);
-            if (vfs == MP_VFS_NONE) {
+            supervisor_vfs_t *fs_mount = filesystem_for_path(path, &path_out);
+            if (fs_mount == NULL || !supervisor_vfs_supported(fs_mount)) {
                 _reply_missing(socket, request);
                 return false;
             }
-            fs_user_mount_t *fs_mount;
-            if (vfs == MP_VFS_ROOT) {
-                fs_mount = filesystem_circuitpy();
-            } else {
-                fs_mount = MP_OBJ_TO_PTR(vfs->obj);
-                // Skip non-fat and non-native block file systems.
-                if (!filesystem_native_fatfs(fs_mount)) {
-                    _reply_missing(socket, request);
-                    return false;
-                }
-                // Check if the vfs name is one character long: it must be "/" in that case.
-                // If so don't remove the mount point name. We must use an absolute path
-                // because otherwise the path will be adjusted by os.getcwd() when it's looked up.
-                if (strlen(vfs->str) != 1) {
-                    // Remove the mount point directory name, such as "/sd".
-                    path += strlen(vfs->str);
-                }
-                pathlen = strlen(path);
+            path = (char *)path_out;
+            pathlen = strlen(path);
 
-            }
-            FATFS *fs = &fs_mount->fatfs;
             if (directory) {
                 if (strcasecmp(request->method, "GET") == 0) {
-                    FF_DIR dir;
-                    FRESULT res = f_opendir(fs, &dir, path);
+                    supervisor_vfs_dir_t dir;
+                    memset(&dir, 0, sizeof(dir));
+                    supervisor_fs_err_t res = supervisor_vfs_opendir(fs_mount, path, &dir);
                     // Put the / back for replies.
                     if (pathlen > 1) {
                         path[pathlen - 1] = '/';
                     }
-                    if (res != FR_OK) {
+                    if (res != SUPERVISOR_FS_OK) {
                         _reply_missing(socket, request);
                         return false;
                     }
@@ -1296,20 +1551,20 @@ static bool _reply(socketpool_socket_obj_t *socket, _request *request) {
                         _reply_missing(socket, request);
                     }
 
-                    f_closedir(&dir);
+                    supervisor_vfs_closedir(&dir);
                 }
             } else { // Dealing with a file.
                 if (strcasecmp(request->method, "GET") == 0) {
-                    FIL active_file;
-                    FRESULT result = f_open(fs, &active_file, path, FA_READ);
+                    supervisor_vfs_file_t active_file;
+                    supervisor_fs_err_t result = supervisor_vfs_open_file(fs_mount, path, SUPERVISOR_FS_OPEN_READ, 0, &active_file);
 
-                    if (result != FR_OK) {
+                    if (result != SUPERVISOR_FS_OK) {
                         _reply_missing(socket, request);
                     } else {
                         _reply_with_file(socket, request, path, &active_file);
                     }
 
-                    f_close(&active_file);
+                    supervisor_vfs_close_file(&active_file);
                 } else if (strcasecmp(request->method, "PUT") == 0) {
                     _write_file_and_reply(socket, request, fs_mount, path);
                     return true;
@@ -1353,6 +1608,20 @@ static bool _reply(socketpool_socket_obj_t *socket, _request *request) {
             } else {
                 _REPLY_STATIC(socket, request, serial_html);
             }
+        #if CIRCUITPY_DISPLAYIO
+        } else if (strcmp(path, "/display/") == 0) {
+            if (!request->authenticated) {
+                if (_api_password[0] != '\0') {
+                    _reply_unauthorized(socket, request);
+                } else {
+                    _reply_forbidden(socket, request);
+                }
+            } else if (request->websocket) {
+                _reply_websocket_upgrade(socket, request);
+            } else {
+                _REPLY_STATIC(socket, request, display_html);
+            }
+        #endif
         } else {
             _reply_missing(socket, request);
         }
@@ -1369,6 +1638,10 @@ static bool _reply(socketpool_socket_obj_t *socket, _request *request) {
             _REPLY_STATIC(socket, request, welcome_js);
         } else if (strcmp(request->path, "/serial.js") == 0) {
             _REPLY_STATIC(socket, request, serial_js);
+        #if CIRCUITPY_DISPLAYIO
+        } else if (strcmp(request->path, "/display.js") == 0) {
+            _REPLY_STATIC(socket, request, display_js);
+        #endif
         } else if (strcmp(request->path, "/edit.js") == 0) {
             _REPLY_STATIC(socket, request, edit_js);
         } else if (strcmp(request->path, "/style.css") == 0) {
@@ -1399,6 +1672,7 @@ static void _reset_request(_request *request) {
     request->expect = false;
     request->json = false;
     request->websocket = false;
+    request->held = false;
 }
 
 static void _process_request(socketpool_socket_obj_t *socket, _request *request) {
@@ -1406,7 +1680,7 @@ static void _process_request(socketpool_socket_obj_t *socket, _request *request)
     bool error = false;
     uint8_t c;
     // This code assumes header lines are terminated with \r\n
-    while (more && !error) {
+    while (more && !error && !request->done) {
 
         int len = socketpool_socket_recv_into(socket, &c, 1);
         if (len != 1) {
@@ -1499,7 +1773,7 @@ static void _process_request(socketpool_socket_obj_t *socket, _request *request)
                         strncpy(request->host, request->header_value, sizeof(request->host) - 1);
                         request->host[sizeof(request->host) - 1] = '\0';
                     } else if (strcasecmp(request->header_key, "Content-Length") == 0) {
-                        request->content_length = strtoul(request->header_value, NULL, 10);
+                        request->content_length = _parse_decimal(request->header_value);
                     } else if (strcasecmp(request->header_key, "Expect") == 0) {
                         request->expect = strcmp(request->header_value, "100-continue") == 0;
                     } else if (strcasecmp(request->header_key, "Accept") == 0) {
@@ -1508,11 +1782,9 @@ static void _process_request(socketpool_socket_obj_t *socket, _request *request)
                         strncpy(request->origin, request->header_value, sizeof(request->origin) - 1);
                         request->origin[sizeof(request->origin) - 1] = '\0';
                     } else if (strcasecmp(request->header_key, "X-Timestamp") == 0) {
-                        request->timestamp_ms = strtoull(request->header_value, NULL, 10);
+                        request->timestamp_ms = _parse_decimal(request->header_value);
                     } else if (strcasecmp(request->header_key, "Upgrade") == 0) {
                         request->websocket = strcmp(request->header_value, "websocket") == 0;
-                    } else if (strcasecmp(request->header_key, "Sec-WebSocket-Version") == 0) {
-                        request->websocket_version = strtoul(request->header_value, NULL, 10);
                     } else if (strcasecmp(request->header_key, "Sec-WebSocket-Key") == 0 &&
                                strlen(request->header_value) == 24) {
                         strcpy(request->websocket_key, request->header_value);
@@ -1545,6 +1817,9 @@ static void _process_request(socketpool_socket_obj_t *socket, _request *request)
         return;
     }
     bool reload = _reply(socket, request);
+    if (request->held) {
+        return;                                 // the VM is stopping; try again then
+    }
     _reset_request(request);
     common_hal_socketpool_socket_close(socket);
     autoreload_resume(AUTORELOAD_SUSPEND_WEB);
@@ -1575,6 +1850,16 @@ static bool supervisor_filesystem_access_could_block(void) {
 }
 
 void supervisor_web_workflow_background(void *data) {
+    #if CIRCUITPY_AIRLIFT
+    // Skip this pass while a command is in flight or the bus is in use, so
+    // nothing here waits for something that can't finish until it returns.
+    if (!airlift_socketpool_background()) {
+        socketpool_socket_poll_resume();
+        return;
+    }
+    _airlift_retry_listening();
+    #endif
+
     // If "/sd" is mounted AND shared with a display, access could block.
     // We don't have a good way to defer a filesystem action way down inside _process_request
     // when this happens, so just postpone if there's a chance of blocking. (#8980)
@@ -1614,10 +1899,20 @@ void supervisor_web_workflow_background(void *data) {
             }
             break;
         }
+        // Nothing to accept from, for example while the listening socket is
+        // closed. Without this the loop never ends.
+        break;
     }
 
     // Let the websocket code run.
     websocket_background();
+    #if CIRCUITPY_DISPLAYIO
+    display_stream_background();
+    #endif
+
+    #if CIRCUITPY_AIRLIFT
+    airlift_socketpool_background_done();
+    #endif
 
     // Resume polling
     socketpool_socket_poll_resume();
diff --git a/supervisor/shared/web_workflow/web_workflow.h b/supervisor/shared/web_workflow/web_workflow.h
index 439964dd333..9ec15a14ddc 100644
--- a/supervisor/shared/web_workflow/web_workflow.h
+++ b/supervisor/shared/web_workflow/web_workflow.h
@@ -8,7 +8,12 @@
 
 #include 
 
+#if CIRCUITPY_MDNS
 #include "shared-bindings/mdns/Server.h"
+#else
+typedef struct mdns_server_obj mdns_server_obj_t;
+#endif
+
 #include "shared-bindings/socketpool/Socket.h"
 
 // This background function should be called repeatedly. It cannot be done based
diff --git a/supervisor/shared/web_workflow/websocket.c b/supervisor/shared/web_workflow/websocket.c
index 67b003b18a4..6b5a0e4ade4 100644
--- a/supervisor/shared/web_workflow/websocket.c
+++ b/supervisor/shared/web_workflow/websocket.c
@@ -16,17 +16,6 @@
 #include "supervisor/shared/status_bar.h"
 #endif
 
-typedef struct {
-    socketpool_socket_obj_t socket;
-    uint8_t opcode;
-    uint8_t frame_len;
-    uint8_t payload_len_size;
-    bool masked;
-    uint8_t mask[4];
-    int frame_index;
-    size_t payload_remaining;
-} _websocket;
-
 // Buffer the incoming serial data in the background so that we can look for the
 // interrupt character.
 static ringbuf_t _incoming_ringbuf;
@@ -34,7 +23,7 @@ static uint8_t _buf[16];
 // make sure background is not called recursively
 static bool in_web_background = false;
 
-static _websocket cp_serial;
+static websocket_t cp_serial;
 
 void websocket_init(void) {
     socketpool_socket_reset(&cp_serial.socket);
@@ -42,15 +31,33 @@ void websocket_init(void) {
     ringbuf_init(&_incoming_ringbuf, _buf, sizeof(_buf));
 }
 
-void websocket_handoff(socketpool_socket_obj_t *socket) {
-    if (!common_hal_socketpool_socket_get_closed(&cp_serial.socket)) {
-        common_hal_socketpool_socket_close(&cp_serial.socket);
+void websocket_send_close(websocket_t *ws, uint16_t code) {
+    if (common_hal_socketpool_socket_get_closed(&ws->socket) ||
+        !common_hal_socketpool_socket_get_connected(&ws->socket)) {
+        return;
     }
+    const uint8_t frame[4] = { 1 << 7 | 0x8, 2, code >> 8, code & 0xff };
+    // Only what the socket takes now: a client that stopped reading must not
+    // hold everything up.
+    socketpool_socket_send(&ws->socket, frame, sizeof(frame));
+}
 
-    socketpool_socket_move(socket, &cp_serial.socket);
-    cp_serial.opcode = 0;
-    cp_serial.frame_index = 0;
-    cp_serial.frame_len = 2;
+void websocket_take_socket(websocket_t *ws, socketpool_socket_obj_t *socket) {
+    if (!common_hal_socketpool_socket_get_closed(&ws->socket)) {
+        // Tell the page it was replaced, so it doesn't reconnect and take the
+        // connection back.
+        websocket_send_close(ws, WEBSOCKET_CLOSE_REPLACED);
+        common_hal_socketpool_socket_close(&ws->socket);
+    }
+
+    socketpool_socket_move(socket, &ws->socket);
+    ws->opcode = 0;
+    ws->frame_index = 0;
+    ws->frame_len = 2;
+}
+
+void websocket_handoff(socketpool_socket_obj_t *socket) {
+    websocket_take_socket(&cp_serial, socket);
 
     #if CIRCUITPY_STATUS_BAR
     // Send the title bar for the new client.
@@ -64,95 +71,98 @@ bool websocket_connected(void) {
            common_hal_socketpool_socket_get_connected(&cp_serial.socket);
 }
 
-static bool _read_byte(uint8_t *c) {
-    int len = socketpool_socket_recv_into(&cp_serial.socket, c, 1);
+static bool _read_byte(websocket_t *ws, uint8_t *c) {
+    int len = socketpool_socket_recv_into(&ws->socket, c, 1);
     if (len < 1) {
         return false;
     }
     return true;
 }
 
-static void _read_next_frame_header(void) {
-    uint8_t h;
-    if (cp_serial.frame_index == 0 && _read_byte(&h)) {
-        cp_serial.frame_index++;
-        cp_serial.opcode = h & 0xf;
+static void _read_next_frame_header(websocket_t *ws) {
+    uint8_t h = 0;
+    if (ws->frame_index == 0 && _read_byte(ws, &h)) {
+        ws->frame_index++;
+        ws->opcode = h & 0xf;
     }
-    if (cp_serial.frame_index == 1 && _read_byte(&h)) {
-        cp_serial.frame_index++;
+    if (ws->frame_index == 1 && _read_byte(ws, &h)) {
+        ws->frame_index++;
         uint8_t len = h & 0x7f;
-        cp_serial.masked = (h >> 7) == 1;
+        ws->masked = (h >> 7) == 1;
         if (len <= 125) {
-            cp_serial.payload_remaining = len;
-            cp_serial.payload_len_size = 0;
+            ws->payload_remaining = len;
+            ws->payload_len_size = 0;
         } else if (len == 126) { // 16 bit length
-            cp_serial.payload_len_size = 2;
+            ws->payload_len_size = 2;
         } else if (len == 127) { // 64 bit length
-            cp_serial.payload_len_size = 8;
+            ws->payload_len_size = 8;
         }
-        cp_serial.frame_len = 2 + cp_serial.payload_len_size;
-        if (cp_serial.masked) {
-            cp_serial.frame_len += 4;
+        ws->frame_len = 2 + ws->payload_len_size;
+        if (ws->masked) {
+            ws->frame_len += 4;
         }
     }
-    while (cp_serial.frame_index >= 2 &&
-           cp_serial.frame_index < (cp_serial.payload_len_size + 2) &&
-           _read_byte(&h)) {
-        cp_serial.frame_index++;
-        cp_serial.payload_remaining = cp_serial.payload_remaining << 8 | h;
-    }
-    int mask_start = cp_serial.payload_len_size + 2;
-    while (cp_serial.frame_index >= mask_start &&
-           cp_serial.frame_index < cp_serial.frame_len &&
-           _read_byte(&h)) {
-        size_t mask_offset = cp_serial.frame_index - mask_start;
-        cp_serial.mask[mask_offset] = h;
-        cp_serial.frame_index++;
-    }
-    // Reply to PINGs and CLOSE.
-    while ((cp_serial.opcode == 0x8 ||
-            cp_serial.opcode == 0x9) &&
-           cp_serial.frame_index >= cp_serial.frame_len) {
-
-        if (cp_serial.frame_index == cp_serial.frame_len) {
+    while (ws->frame_index >= 2 &&
+           ws->frame_index < (ws->payload_len_size + 2) &&
+           _read_byte(ws, &h)) {
+        ws->frame_index++;
+        ws->payload_remaining = ws->payload_remaining << 8 | h;
+    }
+    int mask_start = ws->payload_len_size + 2;
+    while (ws->frame_index >= mask_start &&
+           ws->frame_index < ws->frame_len &&
+           _read_byte(ws, &h)) {
+        size_t mask_offset = ws->frame_index - mask_start;
+        ws->mask[mask_offset] = h;
+        ws->frame_index++;
+    }
+    // Reply to PINGs and CLOSE. Replying can find the client gone, which closes
+    // the socket and drops the payload still to be read.
+    while ((ws->opcode == 0x8 ||
+            ws->opcode == 0x9) &&
+           ws->frame_index >= ws->frame_len &&
+           !common_hal_socketpool_socket_get_closed(&ws->socket)) {
+
+        if (ws->frame_index == ws->frame_len) {
             uint8_t opcode = 0x8; // CLOSE
-            if (cp_serial.opcode == 0x9) {
+            if (ws->opcode == 0x9) {
                 opcode = 0xA; // PONG
             }
             uint8_t frame_header[2];
             frame_header[0] = 1 << 7 | opcode;
-            frame_header[1] = cp_serial.payload_remaining;
-            web_workflow_send_raw(&cp_serial.socket, cp_serial.opcode != 0x9, (const uint8_t *)frame_header, 2);
+            frame_header[1] = ws->payload_remaining;
+            web_workflow_send_raw(&ws->socket, ws->opcode != 0x9, (const uint8_t *)frame_header, 2);
         }
 
-        if (cp_serial.payload_remaining > 0 && _read_byte(&h)) {
+        if (ws->payload_remaining > 0 && _read_byte(ws, &h)) {
             // Send the payload back to the client.
-            cp_serial.frame_index++;
-            cp_serial.payload_remaining--;
-            web_workflow_send_raw(&cp_serial.socket, false, &h, 1);
+            ws->frame_index++;
+            ws->payload_remaining--;
+            web_workflow_send_raw(&ws->socket, false, &h, 1);
         }
 
-        if (cp_serial.payload_remaining == 0) {
-            cp_serial.frame_index = 0;
-            if (cp_serial.opcode == 0x8) {
-                common_hal_socketpool_socket_close(&cp_serial.socket);
+        if (ws->payload_remaining == 0) {
+            ws->frame_index = 0;
+            if (ws->opcode == 0x8) {
+                common_hal_socketpool_socket_close(&ws->socket);
             }
         }
     }
 }
 
-static bool _read_next_payload_byte(uint8_t *c) {
-    _read_next_frame_header();
-    if (cp_serial.opcode == 0x1 &&
-        cp_serial.frame_index >= cp_serial.frame_len &&
-        cp_serial.payload_remaining > 0) {
-        if (_read_byte(c)) {
-            uint8_t mask_offset = (cp_serial.frame_index - cp_serial.frame_len) % 4;
-            *c ^= cp_serial.mask[mask_offset];
-            cp_serial.frame_index++;
-            cp_serial.payload_remaining--;
-            if (cp_serial.payload_remaining == 0) {
-                cp_serial.frame_index = 0;
+bool websocket_read_payload_byte(websocket_t *ws, uint8_t *c) {
+    _read_next_frame_header(ws);
+    // Text, binary or a continuation of either.
+    if (ws->opcode <= 0x2 &&
+        ws->frame_index >= ws->frame_len &&
+        ws->payload_remaining > 0) {
+        if (_read_byte(ws, c)) {
+            uint8_t mask_offset = (ws->frame_index - ws->frame_len) % 4;
+            *c ^= ws->mask[mask_offset];
+            ws->frame_index++;
+            ws->payload_remaining--;
+            if (ws->payload_remaining == 0) {
+                ws->frame_index = 0;
             }
             return true;
         }
@@ -176,7 +186,7 @@ char websocket_read_char(void) {
     return -1;
 }
 
-static void _websocket_send(_websocket *ws, const char *text, size_t len) {
+static void _websocket_send(websocket_t *ws, const char *text, size_t len) {
     if (!websocket_connected()) {
         return;
     }
@@ -225,7 +235,7 @@ void websocket_background(void) {
     in_web_background = true;
     uint8_t c;
     while (ringbuf_num_empty(&_incoming_ringbuf) > 0 &&
-           _read_next_payload_byte(&c)) {
+           websocket_read_payload_byte(&cp_serial, &c)) {
         if (c == mp_interrupt_char) {
             ringbuf_clear(&_incoming_ringbuf);
             mp_sched_keyboard_interrupt();
diff --git a/supervisor/shared/web_workflow/websocket.h b/supervisor/shared/web_workflow/websocket.h
index bbf30a4611d..0eafb53f064 100644
--- a/supervisor/shared/web_workflow/websocket.h
+++ b/supervisor/shared/web_workflow/websocket.h
@@ -11,6 +11,30 @@
 
 #include "shared-bindings/socketpool/Socket.h"
 
+typedef struct {
+    socketpool_socket_obj_t socket;
+    uint8_t opcode;
+    uint8_t frame_len;
+    uint8_t payload_len_size;
+    bool masked;
+    uint8_t mask[4];
+    int frame_index;
+    size_t payload_remaining;
+} websocket_t;
+
+// Close code sent to a client when a newer one takes over its connection.
+#define WEBSOCKET_CLOSE_REPLACED (4000)
+
+// Sends a CLOSE frame with code if the socket can take it without waiting. The
+// caller closes the socket.
+void websocket_send_close(websocket_t *ws, uint16_t code);
+// Moves an upgraded socket into ws, closing the one it had. A connected client
+// is sent WEBSOCKET_CLOSE_REPLACED first.
+void websocket_take_socket(websocket_t *ws, socketpool_socket_obj_t *socket);
+// Reads the next byte of a text or binary message. PINGs are answered and a CLOSE closes
+// the socket. Returns false when no byte is available yet.
+bool websocket_read_payload_byte(websocket_t *ws, uint8_t *c);
+
 void websocket_init(void);
 void websocket_handoff(socketpool_socket_obj_t *socket);
 bool websocket_connected(void);
diff --git a/supervisor/shared/workflow.c b/supervisor/shared/workflow.c
index df2055580fc..8cb7d7a29b7 100644
--- a/supervisor/shared/workflow.c
+++ b/supervisor/shared/workflow.c
@@ -4,12 +4,10 @@
 //
 // SPDX-License-Identifier: MIT
 
-#include 
 #include "py/mpconfig.h"
 #include "py/mpstate.h"
 #include "py/stackctrl.h"
 #include "supervisor/background_callback.h"
-#include "supervisor/fatfs.h"
 #include "supervisor/filesystem.h"
 #include "supervisor/workflow.h"
 #include "supervisor/shared/serial.h"
@@ -18,13 +16,15 @@
 #if CIRCUITPY_BLEIO
 #include "shared-bindings/_bleio/__init__.h"
 #include "supervisor/shared/bluetooth/bluetooth.h"
-#if CIRCUITPY_SERIAL_BLE
+#if CIRCUITPY_BLE_SERIAL_SERVICE
 #include "supervisor/shared/bluetooth/serial.h"
 #endif
 #endif
 
-#if CIRCUITPY_TINYUSB || CIRCUITPY_USB_KEYBOARD_WORKFLOW
+#if CIRCUITPY_USB_DEVICE || CIRCUITPY_USB_KEYBOARD_WORKFLOW
 #include "supervisor/usb.h"
+#endif
+#if CIRCUITPY_TINYUSB
 #include "tusb.h"
 #endif
 
@@ -43,10 +43,12 @@ void supervisor_workflow_reset(void) {
 
     #if CIRCUITPY_WEB_WORKFLOW
     bool result = supervisor_start_web_workflow();
-    if (workflow_background_cb.fun) {
-        if (result) {
-            supervisor_workflow_request_background();
+    if (result) {
+        if (!workflow_background_cb.fun) {
+            // Enable background callbacks if web_workflow startup successful.
+            workflow_background_cb.fun = supervisor_web_workflow_background;
         }
+        supervisor_workflow_request_background();
     }
     #endif
 }
@@ -68,8 +70,8 @@ void supervisor_workflow_request_background(void) {
 bool supervisor_workflow_active(void) {
     #if CIRCUITPY_USB_DEVICE
     // Eventually there might be other non-USB workflows, such as BLE.
-    // tud_ready() checks for usb mounted and not suspended.
-    if (tud_ready()) {
+    // usb_connected() checks for usb mounted and not suspended.
+    if (usb_connected()) {
         return true;
     }
     #endif
@@ -78,7 +80,7 @@ bool supervisor_workflow_active(void) {
         return true;
     }
     #endif
-    #if CIRCUITPY_SERIAL_BLE
+    #if CIRCUITPY_BLE_SERIAL_SERVICE
     if (ble_serial_connected()) {
         return true;
     }
@@ -89,7 +91,7 @@ bool supervisor_workflow_active(void) {
 
 void supervisor_workflow_start(void) {
     // Start USB after giving boot.py a chance to tweak behavior.
-    #if CIRCUITPY_TINYUSB
+    #if CIRCUITPY_USB_DEVICE
     // Setup USB connection after heap is available.
     // It needs the heap to build descriptors.
     usb_init();
@@ -105,149 +107,147 @@ void supervisor_workflow_start(void) {
 
     #if CIRCUITPY_WEB_WORKFLOW
     if (supervisor_start_web_workflow()) {
-        // Enable background callbacks if web_workflow startup successful
-        memset(&workflow_background_cb, 0, sizeof(workflow_background_cb));
+        // Enable background callbacks if web_workflow startup successful.
         workflow_background_cb.fun = supervisor_web_workflow_background;
+        // Kick the first background run now that the callback is installed.
+        supervisor_workflow_request_background();
     }
     #endif
-
-    #if CIRCUITPY_USB_KEYBOARD_WORKFLOW
-    usb_keyboard_init();
-    #endif
 }
 
-FRESULT supervisor_workflow_move(const char *old_path, const char *new_path) {
+supervisor_fs_err_t supervisor_workflow_move(const char *old_path, const char *new_path) {
     const char *old_mount_path;
     const char *new_mount_path;
-    fs_user_mount_t *active_mount = filesystem_for_path(old_path, &old_mount_path);
-    fs_user_mount_t *new_mount = filesystem_for_path(new_path, &new_mount_path);
-    if (active_mount == NULL || new_mount == NULL || active_mount != new_mount || !filesystem_native_fatfs(active_mount)) {
-        return FR_NO_PATH;
+    supervisor_vfs_t *active_mount = filesystem_for_path(old_path, &old_mount_path);
+    supervisor_vfs_t *new_mount = filesystem_for_path(new_path, &new_mount_path);
+    if (active_mount == NULL || new_mount == NULL || active_mount != new_mount || !supervisor_vfs_supported(active_mount)) {
+        return SUPERVISOR_FS_NO_PATH;
     }
     if (!filesystem_lock(active_mount)) {
-        return FR_WRITE_PROTECTED;
+        return SUPERVISOR_FS_WRITE_PROTECTED;
     }
-    FATFS *fs = &active_mount->fatfs;
 
-    FRESULT result = f_rename(fs, old_mount_path, new_mount_path);
+    supervisor_fs_err_t result = supervisor_vfs_rename(active_mount, old_mount_path, new_mount_path);
     filesystem_unlock(active_mount);
     return result;
 }
 
-FRESULT supervisor_workflow_mkdir(DWORD fattime, const char *full_path) {
+supervisor_fs_err_t supervisor_workflow_mkdir(uint64_t mtime_ns, const char *full_path) {
     const char *mount_path;
-    fs_user_mount_t *active_mount = filesystem_for_path(full_path, &mount_path);
-    if (active_mount == NULL || !filesystem_native_fatfs(active_mount)) {
-        return FR_NO_PATH;
+    supervisor_vfs_t *active_mount = filesystem_for_path(full_path, &mount_path);
+    if (active_mount == NULL || !supervisor_vfs_supported(active_mount)) {
+        return SUPERVISOR_FS_NO_PATH;
     }
 
     // If there is a mount on the directory, then the mount_path will be empty.
-    if (strlen(mount_path) == 0) {
-        return FR_EXIST;
+    if (strlen(mount_path) == 0 || strcmp(mount_path, "/") == 0) {
+        return SUPERVISOR_FS_EXIST;
     }
 
     // Check to see if the directory exists already. We don't care about writing
     // it if it already exists.
-    FATFS *fs = &active_mount->fatfs;
-    FILINFO file;
-    FRESULT result = f_stat(fs, mount_path, &file);
-    if (result == FR_OK) {
-        return FR_EXIST;
+    supervisor_fs_err_t result = supervisor_vfs_stat(active_mount, mount_path, NULL, NULL, NULL);
+    if (result == SUPERVISOR_FS_OK) {
+        return SUPERVISOR_FS_EXIST;
     }
 
     if (!filesystem_lock(active_mount)) {
-        return FR_WRITE_PROTECTED;
+        return SUPERVISOR_FS_WRITE_PROTECTED;
     }
 
-    override_fattime(fattime);
-    result = f_mkdir(fs, mount_path);
-    override_fattime(0);
+    result = supervisor_vfs_mkdir(active_mount, mount_path, mtime_ns);
     filesystem_unlock(active_mount);
     return result;
 }
 
-FRESULT supervisor_workflow_mkdir_parents(DWORD fattime, char *path) {
-    override_fattime(fattime);
-    FRESULT result = FR_OK;
+supervisor_fs_err_t supervisor_workflow_mkdir_parents(uint64_t mtime_ns, char *path) {
+    supervisor_fs_err_t result = SUPERVISOR_FS_OK;
     // Make parent directories.
     for (size_t j = 1; j < strlen(path); j++) {
         if (path[j] == '/') {
             path[j] = '\0';
-            result = supervisor_workflow_mkdir(fattime, path);
+            result = supervisor_workflow_mkdir(mtime_ns, path);
             path[j] = '/';
-            if (result != FR_OK && result != FR_EXIST) {
+            if (result != SUPERVISOR_FS_OK && result != SUPERVISOR_FS_EXIST) {
                 break;
             }
         }
     }
     // Make the target directory.
-    if (result == FR_OK || result == FR_EXIST) {
-        result = supervisor_workflow_mkdir(fattime, path);
-        // This may return FR_EXIST when a file with the same name already exists.
+    if (result == SUPERVISOR_FS_OK || result == SUPERVISOR_FS_EXIST) {
+        result = supervisor_workflow_mkdir(mtime_ns, path);
+        // This may return SUPERVISOR_FS_EXIST when a file with the same name already exists.
         // FATFS does the same thing.
     }
-    override_fattime(0);
     return result;
 }
 
-static FRESULT supervisor_workflow_delete_directory_contents(FATFS *fs, const TCHAR *path) {
-    FF_DIR dir;
-    FILINFO file_info;
+static supervisor_fs_err_t supervisor_workflow_delete_directory_contents(supervisor_vfs_t *active_mount, const char *path) {
     // Check the stack since we're putting paths on it.
     if (mp_stack_usage() >= MP_STATE_THREAD(stack_limit)) {
-        return FR_INT_ERR;
-    }
-    FRESULT res = FR_OK;
-    while (res == FR_OK) {
-        res = f_opendir(fs, &dir, path);
-        if (res != FR_OK) {
+        return SUPERVISOR_FS_IO;
+    }
+    supervisor_vfs_dir_t dir;
+    memset(&dir, 0, sizeof(dir));
+    char name[FF_MAX_LFN + 1];
+    supervisor_fs_err_t res = SUPERVISOR_FS_OK;
+    while (res == SUPERVISOR_FS_OK) {
+        res = supervisor_vfs_opendir(active_mount, path, &dir);
+        if (res != SUPERVISOR_FS_OK) {
             break;
         }
-        res = f_readdir(&dir, &file_info);
+        res = supervisor_vfs_readdir(&dir, name, sizeof(name), NULL, NULL, NULL);
         // We close and reopen the directory every time since we're deleting
         // entries and it may invalidate the directory handle.
-        f_closedir(&dir);
-        if (res != FR_OK || file_info.fname[0] == '\0') {
+        supervisor_vfs_closedir(&dir);
+        if (res != SUPERVISOR_FS_OK || name[0] == '\0') {
             break;
         }
         size_t pathlen = strlen(path);
-        size_t fnlen = strlen(file_info.fname);
-        TCHAR full_path[pathlen + 1 + fnlen];
+        size_t fnlen = strlen(name);
+        char full_path[pathlen + 1 + fnlen + 1];
         memcpy(full_path, path, pathlen);
         full_path[pathlen] = '/';
-        size_t full_pathlen = pathlen + 1 + fnlen;
-        memcpy(full_path + pathlen + 1, file_info.fname, fnlen);
-        full_path[full_pathlen] = '\0';
-        if ((file_info.fattrib & AM_DIR) != 0) {
-            res = supervisor_workflow_delete_directory_contents(fs, full_path);
+        memcpy(full_path + pathlen + 1, name, fnlen + 1);
+        if (path[pathlen - 1] == '/') {
+            // Trim the extra slash we put in. This happens when path is "/".
+            memmove(full_path + pathlen, name, fnlen + 1);
         }
-        if (res != FR_OK) {
+        bool is_dir = false;
+        res = supervisor_vfs_stat(active_mount, full_path, &is_dir, NULL, NULL);
+        if (res != SUPERVISOR_FS_OK) {
             break;
         }
-        res = f_unlink(fs, full_path);
+        if (is_dir) {
+            res = supervisor_workflow_delete_directory_contents(active_mount, full_path);
+            if (res != SUPERVISOR_FS_OK) {
+                break;
+            }
+        }
+        res = supervisor_vfs_unlink(active_mount, full_path);
     }
-    f_closedir(&dir);
+    supervisor_vfs_closedir(&dir);
     return res;
 }
 
-FRESULT supervisor_workflow_delete_recursive(const char *full_path) {
+supervisor_fs_err_t supervisor_workflow_delete_recursive(const char *full_path) {
     const char *mount_path;
-    fs_user_mount_t *active_mount = filesystem_for_path(full_path, &mount_path);
-    if (active_mount == NULL || !filesystem_native_fatfs(active_mount)) {
-        return FR_NO_PATH;
+    supervisor_vfs_t *active_mount = filesystem_for_path(full_path, &mount_path);
+    if (active_mount == NULL || !supervisor_vfs_supported(active_mount)) {
+        return SUPERVISOR_FS_NO_PATH;
     }
     if (!filesystem_lock(active_mount)) {
-        return FR_WRITE_PROTECTED;
-    }
-    FATFS *fs = &active_mount->fatfs;
-    FILINFO file;
-    FRESULT result = f_stat(fs, mount_path, &file);
-    if (result == FR_OK) {
-        if ((file.fattrib & AM_DIR) != 0) {
-            result = supervisor_workflow_delete_directory_contents(fs, mount_path);
+        return SUPERVISOR_FS_WRITE_PROTECTED;
+    }
+    supervisor_fs_err_t result = SUPERVISOR_FS_OK;
+    bool is_dir = false;
+    result = supervisor_vfs_stat(active_mount, mount_path, &is_dir, NULL, NULL);
+    if (result == SUPERVISOR_FS_OK) {
+        if (is_dir) {
+            result = supervisor_workflow_delete_directory_contents(active_mount, mount_path);
         }
-        if (result == FR_OK) {
-            result = f_unlink(fs, mount_path);
+        if (result == SUPERVISOR_FS_OK) {
+            result = supervisor_vfs_unlink(active_mount, mount_path);
         }
     }
     filesystem_unlock(active_mount);
diff --git a/supervisor/shared/workflow.h b/supervisor/shared/workflow.h
index e03f9c00573..0698e2edebe 100644
--- a/supervisor/shared/workflow.h
+++ b/supervisor/shared/workflow.h
@@ -6,12 +6,16 @@
 
 #pragma once
 
-#include "lib/oofatfs/ff.h"
+#include 
+
+#include "supervisor/filesystem.h"
 
 extern bool supervisor_workflow_connecting(void);
 
-// File system helpers for workflow code.
-FRESULT supervisor_workflow_move(const char *old_path, const char *new_path);
-FRESULT supervisor_workflow_mkdir(DWORD fattime, const char *full_path);
-FRESULT supervisor_workflow_mkdir_parents(DWORD fattime, char *path);
-FRESULT supervisor_workflow_delete_recursive(const char *full_path);
+// File system helpers for workflow code. All of them take full paths (such as
+// "/code.py"), resolve them to a mount and return supervisor_fs_err_t. Paths
+// may name either FAT or littlefs mounts.
+supervisor_fs_err_t supervisor_workflow_move(const char *old_path, const char *new_path);
+supervisor_fs_err_t supervisor_workflow_mkdir(uint64_t mtime_ns, const char *full_path);
+supervisor_fs_err_t supervisor_workflow_mkdir_parents(uint64_t mtime_ns, char *path);
+supervisor_fs_err_t supervisor_workflow_delete_recursive(const char *full_path);
diff --git a/supervisor/stub/filesystem.c b/supervisor/stub/filesystem.c
index ce9204b95c3..5f867b00af4 100644
--- a/supervisor/stub/filesystem.c
+++ b/supervisor/stub/filesystem.c
@@ -4,6 +4,9 @@
 //
 // SPDX-License-Identifier: MIT
 
+#include 
+#include 
+
 #include "supervisor/filesystem.h"
 
 
@@ -29,13 +32,13 @@ void filesystem_set_internal_writable_by_usb(bool writable) {
     return;
 }
 
-void filesystem_set_writable_by_usb(fs_user_mount_t *vfs, bool usb_writable) {
+void filesystem_set_writable_by_usb(supervisor_vfs_t *vfs, bool usb_writable) {
     (void)vfs;
     (void)usb_writable;
     return;
 }
 
-bool filesystem_is_writable_by_python(fs_user_mount_t *vfs) {
+bool filesystem_is_writable_by_python(supervisor_vfs_t *vfs) {
     (void)vfs;
     return true;
 }
@@ -49,7 +52,7 @@ void filesystem_set_internal_concurrent_write_protection(bool concurrent_write_p
     return;
 }
 
-void filesystem_set_concurrent_write_protection(fs_user_mount_t *vfs, bool concurrent_write_protection) {
+void filesystem_set_concurrent_write_protection(supervisor_vfs_t *vfs, bool concurrent_write_protection) {
     (void)vfs;
     (void)concurrent_write_protection;
     return;
@@ -58,3 +61,146 @@ void filesystem_set_concurrent_write_protection(fs_user_mount_t *vfs, bool concu
 bool filesystem_present(void) {
     return false;
 }
+
+bool filesystem_lock(supervisor_vfs_t *fs_mount) {
+    (void)fs_mount;
+    return true;
+}
+
+void filesystem_unlock(supervisor_vfs_t *fs_mount) {
+    (void)fs_mount;
+}
+
+// Without a filesystem, nothing is supported and all file operations fail.
+bool supervisor_vfs_supported(supervisor_vfs_t *fs_mount) {
+    (void)fs_mount;
+    return false;
+}
+
+supervisor_fs_err_t supervisor_vfs_open_file(supervisor_vfs_t *vfs, const char *path, uint32_t flags,
+    uint64_t mtime_ns, supervisor_vfs_file_t *file) {
+    (void)vfs;
+    (void)path;
+    (void)flags;
+    (void)mtime_ns;
+    (void)file;
+    return SUPERVISOR_FS_IO;
+}
+
+supervisor_fs_err_t supervisor_vfs_close_file(supervisor_vfs_file_t *file) {
+    (void)file;
+    return SUPERVISOR_FS_OK;
+}
+
+supervisor_fs_err_t supervisor_vfs_read_file(supervisor_vfs_file_t *file, void *buf, size_t len, size_t *bytes_read) {
+    (void)file;
+    (void)buf;
+    (void)len;
+    *bytes_read = 0;
+    return SUPERVISOR_FS_IO;
+}
+
+supervisor_fs_err_t supervisor_vfs_write_file(supervisor_vfs_file_t *file, const void *buf, size_t len, size_t *bytes_written) {
+    (void)file;
+    (void)buf;
+    (void)len;
+    *bytes_written = 0;
+    return SUPERVISOR_FS_IO;
+}
+
+supervisor_fs_err_t supervisor_vfs_seek_file(supervisor_vfs_file_t *file, size_t offset) {
+    (void)file;
+    (void)offset;
+    return SUPERVISOR_FS_IO;
+}
+
+size_t supervisor_vfs_tell_file(supervisor_vfs_file_t *file) {
+    (void)file;
+    return 0;
+}
+
+size_t supervisor_vfs_file_size(supervisor_vfs_file_t *file) {
+    (void)file;
+    return 0;
+}
+
+supervisor_fs_err_t supervisor_vfs_truncate_file(supervisor_vfs_file_t *file) {
+    (void)file;
+    return SUPERVISOR_FS_IO;
+}
+
+supervisor_fs_err_t supervisor_vfs_stat(supervisor_vfs_t *vfs, const char *path, bool *is_dir, size_t *size, uint64_t *mtime_ns) {
+    (void)vfs;
+    (void)path;
+    if (is_dir != NULL) {
+        *is_dir = false;
+    }
+    if (size != NULL) {
+        *size = 0;
+    }
+    if (mtime_ns != NULL) {
+        *mtime_ns = 0;
+    }
+    return SUPERVISOR_FS_NO_FILE;
+}
+
+supervisor_fs_err_t supervisor_vfs_mkdir(supervisor_vfs_t *vfs, const char *path, uint64_t mtime_ns) {
+    (void)vfs;
+    (void)path;
+    (void)mtime_ns;
+    return SUPERVISOR_FS_IO;
+}
+
+supervisor_fs_err_t supervisor_vfs_rename(supervisor_vfs_t *vfs, const char *old_path, const char *new_path) {
+    (void)vfs;
+    (void)old_path;
+    (void)new_path;
+    return SUPERVISOR_FS_IO;
+}
+
+supervisor_fs_err_t supervisor_vfs_unlink(supervisor_vfs_t *vfs, const char *path) {
+    (void)vfs;
+    (void)path;
+    return SUPERVISOR_FS_IO;
+}
+
+supervisor_fs_err_t supervisor_vfs_opendir(supervisor_vfs_t *vfs, const char *path, supervisor_vfs_dir_t *dir) {
+    (void)vfs;
+    (void)path;
+    (void)dir;
+    return SUPERVISOR_FS_NO_FILE;
+}
+
+supervisor_fs_err_t supervisor_vfs_readdir(supervisor_vfs_dir_t *dir, char *name, size_t name_len, bool *is_dir, size_t *size, uint64_t *mtime_ns) {
+    (void)dir;
+    (void)name_len;
+    if (is_dir != NULL) {
+        *is_dir = false;
+    }
+    if (size != NULL) {
+        *size = 0;
+    }
+    if (mtime_ns != NULL) {
+        *mtime_ns = 0;
+    }
+    name[0] = '\0';
+    return SUPERVISOR_FS_OK;
+}
+
+supervisor_fs_err_t supervisor_vfs_rewinddir(supervisor_vfs_dir_t *dir) {
+    (void)dir;
+    return SUPERVISOR_FS_IO;
+}
+
+supervisor_fs_err_t supervisor_vfs_closedir(supervisor_vfs_dir_t *dir) {
+    (void)dir;
+    return SUPERVISOR_FS_OK;
+}
+
+supervisor_fs_err_t supervisor_vfs_statfs(supervisor_vfs_t *vfs, size_t *block_size, size_t *total_blocks, size_t *free_blocks) {
+    (void)vfs;
+    (void)block_size;
+    (void)total_blocks;
+    (void)free_blocks;
+    return SUPERVISOR_FS_IO;
+}
diff --git a/supervisor/stub/misc.c b/supervisor/stub/misc.c
deleted file mode 100644
index c0a2a87f9fe..00000000000
--- a/supervisor/stub/misc.c
+++ /dev/null
@@ -1,13 +0,0 @@
-// This file is part of the CircuitPython project: https://circuitpython.org
-//
-// SPDX-FileCopyrightText: Copyright (c) 2022 Jeff Epler for Adafruit Industries
-//
-// SPDX-License-Identifier: MIT
-#include "stdbool.h"
-
-#include "supervisor/port.h"
-#include "py/mpconfig.h"
-
-
-MP_WEAK void port_post_boot_py(bool heap_valid) {
-}
diff --git a/supervisor/supervisor.mk b/supervisor/supervisor.mk
index cb713749389..d382a81a282 100644
--- a/supervisor/supervisor.mk
+++ b/supervisor/supervisor.mk
@@ -1,6 +1,5 @@
 SRC_SUPERVISOR = \
 	main.c \
-	lib/tlsf/tlsf.c \
 	supervisor/port.c \
 	supervisor/shared/background_callback.c \
 	supervisor/shared/board.c \
@@ -19,7 +18,24 @@ SRC_SUPERVISOR = \
 	supervisor/shared/traceback.c \
 	supervisor/shared/translate/translate.c \
 	supervisor/shared/workflow.c \
-	supervisor/stub/misc.c \
+
+ifeq ($(CIRCUITPY_SETTINGS_TOML),1)
+SRC_SUPERVISOR += supervisor/shared/settings.c
+endif
+
+ifeq ($(CIRCUITPY_LIB_TLSF),1)
+SRC_SUPERVISOR += lib/tlsf/tlsf.c
+endif
+
+# Awaitable C functions, for the async_* modules.
+ifeq ($(CIRCUITPY_ASYNC_SPI),1)
+SRC_SUPERVISOR += supervisor/shared/awaitable.c
+endif
+
+# Networking code shared by wifi and mii.
+ifneq ($(filter 1,$(CIRCUITPY_WIFI) $(CIRCUITPY_MII)),)
+SRC_SUPERVISOR += supervisor/shared/network.c
+endif
 
 # For tlsf
 CFLAGS += -D_DEBUG=0
@@ -45,7 +61,7 @@ ifeq ($(CIRCUITPY_BLEIO),1)
   ifeq ($(CIRCUITPY_BLE_FILE_SERVICE),1)
     SRC_SUPERVISOR += supervisor/shared/bluetooth/file_transfer.c
   endif
-  ifeq ($(CIRCUITPY_SERIAL_BLE),1)
+  ifeq ($(CIRCUITPY_BLE_SERIAL_SERVICE),1)
     SRC_SUPERVISOR += supervisor/shared/bluetooth/serial.c
   endif
 endif
@@ -114,13 +130,13 @@ ifeq ($(CIRCUITPY_TINYUSB),1)
     lib/tinyusb/src/common/tusb_fifo.c \
     lib/tinyusb/src/tusb.c \
     supervisor/usb.c \
+    supervisor/shared/usb.c \
     supervisor/shared/usb/usb.c \
 
   ifeq ($(CIRCUITPY_USB_DEVICE),1)
   SRC_SUPERVISOR += \
     lib/tinyusb/src/class/cdc/cdc_device.c \
     lib/tinyusb/src/device/usbd.c \
-    lib/tinyusb/src/device/usbd_control.c \
     supervisor/shared/usb/usb_desc.c \
     supervisor/shared/usb/usb_device.c \
 
@@ -142,6 +158,7 @@ ifeq ($(CIRCUITPY_TINYUSB),1)
       shared-bindings/usb_hid/Device.c \
       shared-module/usb_hid/__init__.c \
       shared-module/usb_hid/Device.c \
+      shared-module/usb_hid/report_descriptors.c \
 
   endif
 
@@ -175,6 +192,20 @@ ifeq ($(CIRCUITPY_TINYUSB),1)
     CFLAGS += -DCFG_TUD_VIDEO=1 -DCFG_TUD_VIDEO_STREAMING=1 -DCFG_TUD_VIDEO_STREAMING_EP_BUFSIZE=256 -DCFG_TUD_VIDEO_STREAMING_BULK=1
   endif
 
+  ifeq ($(CIRCUITPY_USB_AUDIO), 1)
+    SRC_SUPERVISOR += \
+      shared-bindings/usb_audio/__init__.c \
+      shared-module/usb_audio/__init__.c \
+      shared-bindings/usb_audio/USBMicrophone.c \
+      shared-module/usb_audio/USBMicrophone.c \
+      shared-bindings/usb_audio/USBSpeaker.c \
+      shared-module/usb_audio/USBSpeaker.c \
+      lib/tinyusb/src/class/audio/audio_device.c \
+
+    # The CFG_TUD_AUDIO_* class driver settings are defined in
+    # supervisor/shared/usb/tusb_config.h, gated on CIRCUITPY_USB_AUDIO.
+  endif
+
 
   ifeq ($(CIRCUITPY_USB_VENDOR), 1)
     SRC_SUPERVISOR += \
@@ -213,7 +244,8 @@ $(BUILD)/autogen_web_workflow_static.c: ../../tools/gen_web_workflow_static.py $
 
 ifeq ($(CIRCUITPY_WEB_WORKFLOW),1)
   SRC_SUPERVISOR += supervisor/shared/web_workflow/web_workflow.c \
-                    supervisor/shared/web_workflow/websocket.c
+                    supervisor/shared/web_workflow/websocket.c \
+                    supervisor/shared/web_workflow/display_stream.c
   SRC_SUPERVISOR += $(BUILD)/autogen_web_workflow_static.c
 endif
 
@@ -257,14 +289,15 @@ ifeq ($(CIRCUITPY_USB_CDC),1)
 CFLAGS += -DCFG_TUD_CDC=2
 endif
 
-USB_HIGHSPEED ?= 0
-CFLAGS += -DUSB_HIGHSPEED=$(USB_HIGHSPEED)
-
 $(BUILD)/supervisor/shared/translate/translate.o: $(HEADER_BUILD)/qstrdefs.generated.h $(HEADER_BUILD)/compressed_translations.generated.h
 
 CIRCUITPY_DISPLAY_FONT ?= "../../tools/fonts/ter-u12n.bdf"
 CIRCUITPY_FONT_EXTRA_CHARACTERS ?= ""
 
+ifeq ($(CIRCUITPY_DISPLAYIO_LVGL),1)
+CIRCUITPY_GEN_DISPLAY_RESOURCES_LVGL = --lvgl-tilegrid
+endif
+
 $(BUILD)/autogen_display_resources-$(TRANSLATION).c: ../../tools/gen_display_resources.py $(TOP)/locale/$(TRANSLATION).po Makefile | $(HEADER_BUILD)
 	$(STEPECHO) "GEN $@"
 	$(Q)install -d $(BUILD)/genhdr
@@ -272,4 +305,5 @@ $(BUILD)/autogen_display_resources-$(TRANSLATION).c: ../../tools/gen_display_res
 		--font $(CIRCUITPY_DISPLAY_FONT) \
 		--sample_file $(TOP)/locale/$(TRANSLATION).po \
 		--extra_characters $(CIRCUITPY_FONT_EXTRA_CHARACTERS) \
-		--output_c_file $@
+		--output_c_file $@ \
+		$(CIRCUITPY_GEN_DISPLAY_RESOURCES_LVGL)
diff --git a/supervisor/usb.h b/supervisor/usb.h
index 435ecd02cdf..02953509ab5 100644
--- a/supervisor/usb.h
+++ b/supervisor/usb.h
@@ -47,7 +47,10 @@ typedef struct {
 // Shared implementation.
 bool usb_enabled(void);
 void usb_add_interface_string(uint8_t interface_string_index, const char str[]);
+// Add custom_name, or if it is NULL, USB_INTERFACE_NAME, a space, and default_suffix.
+void usb_add_interface_name(uint8_t interface_string_index, const char *custom_name, const char *default_suffix);
 bool usb_build_descriptors(const usb_identification_t *identification);
+bool usb_connected(void);
 void usb_disconnect(void);
 void usb_init(void);
 void usb_set_defaults(void);
@@ -65,7 +68,19 @@ size_t usb_msc_descriptor_length(void);
 size_t usb_msc_add_descriptor(uint8_t *descriptor_buf, descriptor_counts_t *descriptor_counts, uint8_t *current_interface_string);
 void usb_msc_mount(void);
 void usb_msc_umount(void);
-bool usb_msc_ejected(void);
+// Release the USB MSC lock on CIRCUITPY (LUN 0) if USB MSC holds it, so that
+// Python, workflows, and storage.remount() can lock it again.
+// Does nothing if USB MSC does not hold the lock. Does not raise or allocate.
+void usb_msc_release_circuitpy_lock(void);
+
+#include "extmod/vfs_fat.h"
+void usb_msc_remount(fs_user_mount_t *fs_mount);
+// Whether USB MSC holds the blockdev lock on this mount because it reported
+// the drive writable to the host. Does not raise or allocate.
+bool usb_msc_holds_lock(fs_user_mount_t *vfs);
+
+// Finish a host write that waited for the VM to stop running the .mpy it overwrites.
+void usb_msc_finish_deferred_write(void);
 #endif
 
 #if CIRCUITPY_USB_KEYBOARD_WORKFLOW
diff --git a/tests/README.md b/tests/README.md
index 54dd078053e..4edd3e1088e 100644
--- a/tests/README.md
+++ b/tests/README.md
@@ -1,7 +1,57 @@
 # MicroPython Test Suite
 
-This directory contains tests for various functionality areas of MicroPython.
-To run all stable tests, run "run-tests.py" script in this directory.
+This directory contains tests for most parts of MicroPython.  To run it you will need
+CPython 3.8.2 or newer, which is used to validate MicroPython's behaviour.
+
+The tests are organized into several categories:
+- Unit and regression tests: tests for MicroPython's core functionality, including the
+  compiler, runtime, and built-in modules
+- perf_bench: performance benchmarks
+- internal_bench: internal performance benchmarks
+- Serial reliability and performance test
+- Test key/certificates
+- CPython vs MicroPython Differences
+
+## Unit and regression tests
+
+To run all stable tests, run the "run-tests.py" script in this directory.  By default
+that will run the test suite against the unix port of MicroPython.
+
+To run the test suite against a bare-metal target (a board running MicroPython firmware)
+use the `-t` option to specify the serial port.  This will automatically detect the
+target platform and run the appropriate set of tests for that platform.  For example:
+
+    $ ./run-tests.py -t /dev/ttyACM0
+
+That will run tests on the `/dev/ttyACM0` serial port.  You can also use shortcut
+device names like `a` for `/dev/ttyACM` and `c` for `COM`.  Use
+`./run-tests.py --help` to see all of the device possibilities, and other options.
+
+There are three kinds of tests:
+
+* Tests that use `unittest`: these tests require `unittest` to be installed on the
+  target (eg via `mpremote mip install unittest`), and are used to test things that are
+  MicroPython-specific, such as behaviour that is different to CPython, modules that
+  aren't available in CPython, and hardware tests.  These tests are run only under
+  MicroPython and the test passes if the `unittest` runner prints "OK" at the end of the
+  run.  Other output may be printed, eg for use as diagnostics, and this output does not
+  affect the result of the test.
+
+* Tests with a corresponding `.exp` file: similar to the `unittest` tests, these tests
+  are for features that generally cannot be run under CPython.  In this case the test is
+  run under MicroPython only and the output from MicroPython is compared against the
+  provided `.exp` file.  The test passes if the output matches exactly.
+
+* Tests without a corresponding `.exp` file (and don't use `unittest`): these tests are
+  used to test MicroPython behaviour that should precisely match CPython.  These tests
+  are first run under CPython and the output captured, and then run under MicroPython
+  and the output compared to the CPython output.  The test passes if the output matches
+  exactly.  If the output differs then the test fails and the outputs are saved in a
+  `.exp` and a `.out` file respectively.
+
+In all three cases above, the test can usually be run directly on the target MicroPython
+instance, either using the unix port with `micropython `, or on a board with
+`mpremote run `.  This is useful for creating and debugging tests.
 
 Tests of capabilities not supported on all platforms should be written
 to check for the capability being present. If it is not, the test
@@ -15,15 +65,6 @@ condition a test. The run-tests.py script uses small scripts in the
 feature_check directory to check whether each such feature is present,
 and skips the relevant tests if not.
 
-Tests are generally verified by running the test both in MicroPython and
-in CPython and comparing the outputs. If the output differs the test fails
-and the outputs are saved in a .out and a .exp file respectively.
-For tests that cannot be run in CPython, for example because they use
-the machine module, a .exp file can be provided next to the test's .py
-file. A convenient way to generate that is to run the test, let it fail
-(because CPython cannot run it) and then copy the .out file (but not
-before checking it manually!)
-
 When creating new tests, anything that relies on float support should go in the
 float/ subdirectory.  Anything that relies on import x, where x is not a built-in
 module, should go in the import/ subdirectory.
@@ -33,21 +74,19 @@ module, should go in the import/ subdirectory.
 The `perf_bench` directory contains some performance benchmarks that can be used
 to benchmark different MicroPython firmwares or host ports.
 
-The runner utility is `run-perfbench,py`. Execute `./run-perfbench.py --help`
+The runner utility is `run-perfbench.py`. Execute `./run-perfbench.py --help`
 for a full list of command line options.
 
 ### Benchmarking a target
 
-To run tests on a firmware target using `pyboard.py`, run the command line like
+To run tests on a firmware target using a serial port, run the command line like
 this:
 
 ```
-./run-perfbench.py -p -d /dev/ttyACM0 168 100
+./run-perfbench.py -t /dev/ttyACM0 168 100
 ```
 
-* `-p` indicates running on a remote target via pyboard.py, not the host.
-* `-d PORTNAME` is the serial port, `/dev/ttyACM0` is the default if not
-  provided.
+* `-t PORTNAME` is the serial port to use (and it supports shorthand like `a0`).
 * `168` is value `N`, the approximate CPU frequency in MHz (in this case Pyboard
   V1.1 is 168MHz). It's possible to choose other values as well: lower values
   like `10` will run much the tests much quicker, higher values like `1000` will
@@ -107,11 +146,11 @@ Usually you want to know if something is faster or slower than a reference. To
 do this, copy the output of each `run-perfbench.py` run to a text file.
 
 This can be done multiple ways, but one way on Linux/macOS is with the `tee`
-utility: `./run-perfbench.py -p 168 100 | tee pyb-run1.txt`
+utility: `./run-perfbench.py -t a0 168 100 | tee pyb-run1.txt`
 
 Once you have two files with output from two different runs (maybe with
 different code or configuration), compare the runtimes with `./run-perfbench.py
--t pybv-run1.txt pybv-run2.txt` or compare scores with `./run-perfbench.py -s
+-m pybv-run1.txt pybv-run2.txt` or compare scores with `./run-perfbench.py -s
 pybv-run1.txt pybv-run2.txt`:
 
 ```
@@ -175,15 +214,37 @@ internal_bench/bytebuf:
 1 tests performed (3 individual testcases)
 ```
 
+## Serial reliability and performance test
+
+Serial port reliability and performance can be tested using the `serial_test.py` script.
+Pass the name of the port to test against, for example:
+
+    $ ./serial_test.py -t /dev/ttyACM0
+
+If no port is specified then `/dev/ttyACM0` is used as the default.
+
+The test will send data out to the target, and receive data from the target, in various
+chunk sizes.  The throughput of the serial connection will be reported for each sub-test.
+
 ## Test key/certificates
 
-SSL/TLS tests in `multi_net` and `net_inet` use a
-self-signed key/cert pair that is randomly generated and to be used for
-testing/demonstration only. You should always generate your own key/cert.
+SSL/TLS tests in `multi_net` and `net_inet` use self-signed key/cert pairs
+that are randomly generated to be used for testing/demonstration only.
 
-To generate a new self-signed RSA key/cert pair with openssl do:
+To run tests on-device the `.der` files should be copied and the current time
+set to ensure certs validity. This can be done with:
 ```
-$ openssl req -x509 -newkey rsa:2048 -keyout rsa_key.pem -out rsa_cert.pem -days 365 -nodes -subj '/CN=micropython.local/O=MicroPython/C=AU'
+$ mpremote rtc --set cp multi_net/*.der net_inet/*.der :
+```
+
+### Generating new test key/certificates
+
+The keys used for the unit tests are included in the tests folders so don't generally
+need to be re-created by end users. This section is included here for reference only.
+
+A new self-signed RSA key/cert pair can be created with openssl:
+```
+$ openssl req -x509 -newkey rsa:2048 -keyout rsa_key.pem -out rsa_cert.pem -days 3650 -nodes -subj '/CN=micropython.local/O=MicroPython/C=AU'
 ```
 In this case CN is: micropython.local
 
@@ -193,8 +254,93 @@ $ openssl pkey -in rsa_key.pem -out rsa_key.der -outform DER
 $ openssl x509 -in rsa_cert.pem -out rsa_cert.der -outform DER
 ```
 
-To test elliptic curve key/cert pairs, create a key then a certificate using:
+For elliptic curve tests using key/cert pairs, create a key then a certificate using:
+```
+$ openssl ecparam -name prime256v1 -genkey -noout -out ec_key.pem
+$ openssl pkey -in ec_key.pem -out ec_key.der -outform DER
+$ openssl req -new -x509 -key ec_key.pem -out ec_cert.der -outform DER -days 3650 -nodes -subj '/CN=micropython.local/O=MicroPython/C=AU'
+```
+
+## CPython vs MicroPython Differences
+
+The `tests/cpydiff` folder contains test files that document and verify the differences
+between the CPython and MicroPython implementations.
+
+These tests are designed to:
+- Execute the same code on both CPython and MicroPython
+- Document behavioral differences between the two implementations
+- Generate documentation pages that help users understand these differences
+
+### How It Works
+
+1. Each test file contains Python code that demonstrates a specific difference.
+2. The tests are executed on both CPython and MicroPython.
+3. The output from both implementations is captured and compared. If the outputs are the
+   same, the generation will fail (because the outputs should be different).
+4. The results, along with metadata from the file docstrings, are used to generate
+   documentation.
+
+### Documentation Generation
+
+The documentation is automatically generated using:
+```
+tools/gen-cpydiff.py
 ```
-$ openssl ecparam -name prime256v1 -genkey -noout -out ec_key.der -outform DER
-$ openssl req -new -x509 -key ec_key.der -out ec_cert.der -outform DER -days 365 -nodes -subj '/CN=micropython.local/O=MicroPython/C=AU'
+
+This script:
+- Parses the docstring metadata from each test file
+- Runs the tests on both implementations
+- Combines the results to create comprehensive documentation pages
+- Outputs formatted reStructuredText documentation showing the differences
+
+**Note:** This script is automatically executed as part of the documentation publishing
+process when building the docs.
+
+### Test File Format
+
+The test filename should match the categories of the test. For example, a test with
+categories `Syntax,Operators` should be named `syntax_operators_*.py`.
+
+Each test file should include a docstring with the following format, and include a
+minimal code snippet that reproduces the difference when run on both CPython and the
+unix port of MicroPython:
+
+```python
+"""
+categories: Category,Subcategory
+description: Brief description of the difference being tested
+cause: Explanation of why this difference exists
+workaround: How to work around this difference (or "Unknown" if none)
+"""
+# Minimal Python code reproducing the difference
+import sys
+print(sys.implementation.name)
 ```
+
+The categories and subcategories are used to organize the documentation into sections.
+Files with the same category and/or subcategory will be placed in the same section.
+
+Common categories include:
+- Syntax
+- Core (Core language)
+- Types (Builtin types)
+- Modules
+
+### Building the Documentation
+
+The documentation is automatically regenerated during the documentation build process.
+To manually regenerate after adding or modifying tests:
+
+1. Set environment variables if needed:
+   - `MICROPY_MICROPYTHON`: Path to MicroPython executable
+   - `MICROPY_CPYTHON3`: Path to CPython 3.x executable (default: "python3")
+
+2. Run the generation script from the project root:
+   ```
+   python tools/gen-cpydiff.py
+   ```
+
+The generated documentation will be placed in `docs/genrst/` as reStructuredText files.
+
+Also see `docs/README.md` for more information on building the documentation locally
+to validate the rendering of the resulting documentation page(s).
diff --git a/tests/assets/Makefile b/tests/assets/Makefile
new file mode 100644
index 00000000000..6048ee2a405
--- /dev/null
+++ b/tests/assets/Makefile
@@ -0,0 +1,29 @@
+MPY_DIR = ../..
+
+PYTHON := $(command -v python3 2> /dev/null)
+ifndef PYTHON
+PYTHON = python
+endif
+
+# Files created with dd if=/dev/urandom ... - the file name is the CRC32
+# of the data contained in the file itself.
+
+ROMFS_FILES = romfs_source/0x30d83fe5.bin \
+	      romfs_source/0x37bef0eb.bin \
+	      romfs_source/0x442f3b5f.bin \
+	      romfs_source/0x648793fb.bin \
+	      romfs_source/0x913837b6.bin \
+	      romfs_source/0xdb14aac7.bin \
+	      romfs_source/romfs_sentinel.txt
+
+.PHONY: romfs
+romfs: all
+
+.PHONY: clean
+clean:
+	rm -f random_romfs.bin
+
+all: random_romfs.bin
+
+random_romfs.bin: $(ROMFS_FILES)
+	$(PYTHON) $(MPY_DIR)/tools/mpremote/mpremote.py romfs --partition 0 --no-mpy --output $@ build romfs_source
diff --git a/tests/assets/README.md b/tests/assets/README.md
new file mode 100644
index 00000000000..a5f935ee1b9
--- /dev/null
+++ b/tests/assets/README.md
@@ -0,0 +1,8 @@
+This directory contains assets for other tests to use:
+
+- A .mpy built against the current .mpy version that can be used to test
+  freezing without a dependency on mpy-cross (`frozentest.py` and
+  `frozentest.mpy`)
+- A ROMFS image containing random binary files for testing mounting and reading
+  from the partition without having to generate a custom image
+  (`random_romfs.bin`, the `romfs_source` directory, and `Makefile`)
diff --git a/tests/frozen/frozentest.mpy b/tests/assets/frozentest.mpy
similarity index 100%
rename from tests/frozen/frozentest.mpy
rename to tests/assets/frozentest.mpy
diff --git a/tests/frozen/frozentest.py b/tests/assets/frozentest.py
similarity index 90%
rename from tests/frozen/frozentest.py
rename to tests/assets/frozentest.py
index 78cdd60bf04..74bdfb3b267 100644
--- a/tests/frozen/frozentest.py
+++ b/tests/assets/frozentest.py
@@ -1,4 +1,4 @@
-print("uPy")
+print("interned")
 print("a long string that is not interned")
 print("a string that has unicode αβγ chars")
 print(b"bytes 1234\x01")
diff --git a/tests/assets/random_romfs.bin b/tests/assets/random_romfs.bin
new file mode 100644
index 00000000000..387bd7ec476
Binary files /dev/null and b/tests/assets/random_romfs.bin differ
diff --git a/tests/assets/romfs_source/0x30d83fe5.bin b/tests/assets/romfs_source/0x30d83fe5.bin
new file mode 100644
index 00000000000..625e51fb8ae
Binary files /dev/null and b/tests/assets/romfs_source/0x30d83fe5.bin differ
diff --git a/tests/assets/romfs_source/0x37bef0eb.bin b/tests/assets/romfs_source/0x37bef0eb.bin
new file mode 100644
index 00000000000..11e1c67871c
Binary files /dev/null and b/tests/assets/romfs_source/0x37bef0eb.bin differ
diff --git a/tests/assets/romfs_source/0x442f3b5f.bin b/tests/assets/romfs_source/0x442f3b5f.bin
new file mode 100644
index 00000000000..ffe9f8f0e2c
Binary files /dev/null and b/tests/assets/romfs_source/0x442f3b5f.bin differ
diff --git a/tests/assets/romfs_source/0x648793fb.bin b/tests/assets/romfs_source/0x648793fb.bin
new file mode 100644
index 00000000000..f99b58c610a
Binary files /dev/null and b/tests/assets/romfs_source/0x648793fb.bin differ
diff --git a/tests/assets/romfs_source/0x913837b6.bin b/tests/assets/romfs_source/0x913837b6.bin
new file mode 100644
index 00000000000..6511184346a
Binary files /dev/null and b/tests/assets/romfs_source/0x913837b6.bin differ
diff --git a/tests/assets/romfs_source/0xdb14aac7.bin b/tests/assets/romfs_source/0xdb14aac7.bin
new file mode 100644
index 00000000000..51754d4ecd8
Binary files /dev/null and b/tests/assets/romfs_source/0xdb14aac7.bin differ
diff --git a/tests/assets/romfs_source/romfs_sentinel.txt b/tests/assets/romfs_source/romfs_sentinel.txt
new file mode 100644
index 00000000000..6ff9311d70e
--- /dev/null
+++ b/tests/assets/romfs_source/romfs_sentinel.txt
@@ -0,0 +1,3 @@
+*MPY-ROMFS-TEST-PARTITION*
+
+This is a ROMFS partition to be used in MicroPython tests, usually for CI.
diff --git a/tests/basics/annotate_var.py.exp b/tests/basics/annotate_var.py.exp
deleted file mode 100644
index 9b6536e966b..00000000000
--- a/tests/basics/annotate_var.py.exp
+++ /dev/null
@@ -1,5 +0,0 @@
-False
-1
-(1, 2)
-NameError
-1
diff --git a/tests/basics/array_add.py b/tests/basics/array_add.py
index 76ce59f761e..e78615541c3 100644
--- a/tests/basics/array_add.py
+++ b/tests/basics/array_add.py
@@ -14,3 +14,9 @@
 
 a1.extend(array.array('I', [5]))
 print(a1)
+
+a1.extend([6, 7])
+print(a1)
+
+a1.extend(i for i in (8, 9))
+print(a1)
diff --git a/tests/basics/array_int_repr.py b/tests/basics/array_int_repr.py
new file mode 100644
index 00000000000..55a2d5998eb
--- /dev/null
+++ b/tests/basics/array_int_repr.py
@@ -0,0 +1,85 @@
+# Test array integer representations in memory
+#
+# This has to be a unit test because correct internal representation depends on
+# native endianness
+#
+# These test cases should pass on both CPython and MicroPython.
+
+try:
+    from array import array
+    from sys import byteorder
+except ImportError:
+    print("SKIP")
+    raise SystemExit
+
+try:
+    import unittest
+except MemoryError:
+    print("SKIP-TOO-LARGE")  # some small boards can't fit unittest in RAM
+    raise SystemExit
+
+# Ports without bigint support don't support typecode 'q'
+try:
+    array("q", [])
+    array_has_typecode_q = True
+except:
+    array_has_typecode_q = False
+
+
+class TestIntReprs(unittest.TestCase):
+    def _test_repr(self, typecode, values):
+        # create an array with the specified typecode and list of values
+        a = array(typecode, values)
+        a_hex = memoryview(a).hex()
+        print(a, a_hex)
+
+        self.assertEqual(len(a_hex) % len(values), 0)
+        # no array.itemsize in MicroPython, so calculate item size
+        sz = len(a_hex) // 2 // len(values)
+        if hasattr(a, "itemsize"):
+            self.assertEqual(a.itemsize, sz)
+
+        # build alternative hex representation of the array using int.to_bytes()
+        # on each value
+        values_hex = ""
+        for v in values:
+            v_bytes = v.to_bytes(sz, byteorder=byteorder, signed=typecode.islower())
+            values_hex += v_bytes.hex()
+
+        # compare with the raw array contents
+        self.assertEqual(a_hex, values_hex)
+
+    def test_smaller_ints(self):
+        for typecode, initialiser in (
+            ("b", [1, -1, 120, -120]),
+            ("B", [1, 5, 220]),
+            ("h", [5, -1, 32_000, -32_000]),
+            ("H", [5, 1, 32_000, 65_535]),
+            ("i", [5, -1, 32_000, -32_000]),  # CPython only guarantees min 2 bytes, C style!
+            ("I", [5, 1, 32_000, 65_535]),
+            ("l", [5, -1, 2_000_000, -2_000_000, 0x7FFF_FFFF]),
+            ("L", [5, 1, 65_536, 2_000_000, 0x7FFF_FFFF, 0xFFFF_FFFF]),
+        ):
+            self._test_repr(typecode, initialiser)
+
+    @unittest.skipIf(not array_has_typecode_q, "port has no bigint support")
+    def test_bigints(self):
+        # Note: need to be careful not to write any literal expressions that can't be compiled on non-bigint MP
+        a = 0x1FFF_FFF
+        b = 62
+
+        try:
+            # this calculation will trigger OverflowError if bigint is set to long long
+            max_uint64 = [2 ** (b + 1)]
+        except OverflowError:
+            max_uint64 = []
+
+        for typecode, initialiser in (
+            ("q", [a * 5, -a * 10, 2**b, (2**b) * -1]),
+            ("Q", [a * 5, a * 10, 2**b, (2**b) - 1, (2**b) + 1] + max_uint64),
+        ):
+            self._test_repr(typecode, initialiser)
+
+
+if __name__ == "__main__":
+    unittest.main()
diff --git a/tests/basics/array_limits_intbig.py b/tests/basics/array_limits_intbig.py
new file mode 100644
index 00000000000..ec740a87bed
--- /dev/null
+++ b/tests/basics/array_limits_intbig.py
@@ -0,0 +1,124 @@
+# Test behaviour when array module is provided out of bounds values
+#
+# This test is intended to also pass on CPython.
+
+try:
+    from array import array
+except ImportError:
+    print("SKIP")
+    raise SystemExit
+
+try:
+    import unittest
+except MemoryError:
+    print("SKIP-TOO-LARGE")  # some small boards can't fit unittest in RAM
+    raise SystemExit
+
+
+# MicroPython V2.0 will enforce bounds on items (same as CPython), V1.x truncates
+#
+# Note: once  error
-ValueError
-enter
-exit  
-BaseException
diff --git a/tests/basics/async_with2.py b/tests/basics/async_with2.py
index 5bac38236fe..b18fa6bdee1 100644
--- a/tests/basics/async_with2.py
+++ b/tests/basics/async_with2.py
@@ -1,7 +1,7 @@
 # test waiting within async with enter/exit functions
 
 # CIRCUITPY-CHANGE
-# uPy allows normal generators to be awaitables.
+# MicroPython allows normal generators to be awaitables.
 # CircuitPython does not.
 # In CircuitPython you need to have an __await__ method on an awaitable like in CPython;
 #  and like in CPython, generators do not have __await__.
diff --git a/tests/basics/async_with2.py.exp b/tests/basics/async_with2.py.exp
deleted file mode 100644
index 76b173b4c24..00000000000
--- a/tests/basics/async_with2.py.exp
+++ /dev/null
@@ -1,17 +0,0 @@
-enter
-f start: 10
-coro yielded: 11
-coro yielded: 12
-f returned: 13
-body start
-f start: 30
-coro yielded: 31
-coro yielded: 32
-body f returned: 33
-body end
-exit None None
-f start: 20
-coro yielded: 21
-coro yielded: 22
-f returned: 23
-finished
diff --git a/tests/basics/async_with_break.py.exp b/tests/basics/async_with_break.py.exp
deleted file mode 100644
index d077a88fad0..00000000000
--- a/tests/basics/async_with_break.py.exp
+++ /dev/null
@@ -1,15 +0,0 @@
-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.exp b/tests/basics/async_with_return.py.exp
deleted file mode 100644
index d077a88fad0..00000000000
--- a/tests/basics/async_with_return.py.exp
+++ /dev/null
@@ -1,15 +0,0 @@
-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/attrtuple2.py b/tests/basics/attrtuple2.py
new file mode 100644
index 00000000000..081d24b6ae9
--- /dev/null
+++ b/tests/basics/attrtuple2.py
@@ -0,0 +1,25 @@
+# test os.uname() attrtuple, if available
+try:
+    import os
+except ImportError:
+    print("SKIP")
+    raise SystemExit
+
+try:
+    u = os.uname()
+except AttributeError:
+    print("SKIP")
+    raise SystemExit
+
+# test printing of attrtuple
+print(str(u).find("machine=") > 0)
+
+# test read attr
+print(isinstance(u.machine, str))
+
+# test str modulo operator for attrtuple
+impl_str = ("%s " * len(u)) % u
+test_str = ""
+for val in u:
+    test_str += val + " "
+print(impl_str == test_str)
diff --git a/tests/basics/boundmeth1.py b/tests/basics/boundmeth1.py
index fe1b454688d..9f08d9bbb25 100644
--- a/tests/basics/boundmeth1.py
+++ b/tests/basics/boundmeth1.py
@@ -1,6 +1,6 @@
 # tests basics of bound methods
 
-# uPy and CPython differ when printing a bound method, so just print the type
+# MicroPython and CPython differ when printing a bound method, so just print the type
 print(type(repr([].append)))
 
 
diff --git a/tests/basics/builtin_dir.py b/tests/basics/builtin_dir.py
index 1eecbd044b7..2aa89dfe0a2 100644
--- a/tests/basics/builtin_dir.py
+++ b/tests/basics/builtin_dir.py
@@ -1,5 +1,12 @@
 # test builtin dir
 
+try:
+    dir
+except NameError:
+    print("SKIP")
+    raise SystemExit
+
+
 # dir of locals
 print('__name__' in dir())
 
diff --git a/tests/basics/builtin_help.py b/tests/basics/builtin_help.py
index 6ec39653fe9..3d4e4f26bd2 100644
--- a/tests/basics/builtin_help.py
+++ b/tests/basics/builtin_help.py
@@ -14,4 +14,10 @@
 help(micropython) # help for a module
 help('modules') # list available modules
 
+class A:
+    x = 1
+    y = 2
+    del x
+help(A)
+
 print('done') # so last bit of output is predictable
diff --git a/tests/basics/builtin_pow3.py b/tests/basics/builtin_pow3.py
index 4eeef85c276..3009dc0cf80 100644
--- a/tests/basics/builtin_pow3.py
+++ b/tests/basics/builtin_pow3.py
@@ -12,6 +12,16 @@
 print(pow(0, 1, 1))
 print(pow(1, 0, 1))
 print(pow(1, 0, 2))
+print(pow(0, 0, 5))
+print(pow(0, 1, 5))
+print(pow(0, 0, 1))
+
+# a negative modulus gives a result with the sign of the modulus
+print(pow(1, 0, -1))
+print(pow(1, 0, -2))
+print(pow(3, 0, -5))
+print(pow(-3, 0, -5))
+print(pow(3, 4, -5))
 
 # 3 arg pow is defined to only work on integers
 try:
@@ -29,6 +39,12 @@
 except TypeError:
     print("TypeError expected")
 
+# pow(x, y, None) is equivalent to pow(x, y)
+print(pow(0, 1, None))
+print(pow(1, 0, None))
+print(pow(-2, 3, None))
+print(pow(3, 8, None))
+
 # CIRCUITPY-CHANGE
 try:
     print(pow(4, 5, 0))
diff --git a/tests/basics/builtin_pow3_intbig.py b/tests/basics/builtin_pow3_intbig.py
index bedc8b36b7e..c91b4d173dd 100644
--- a/tests/basics/builtin_pow3_intbig.py
+++ b/tests/basics/builtin_pow3_intbig.py
@@ -9,6 +9,9 @@
 
 print(pow(555557, 1000002, 1000003))
 
+# a zero exponent with a large negative modulus
+print(pow(3, 0, -(2**70)))
+
 # Tests for 3 arg pow with large values
 
 # This value happens to be prime
@@ -20,3 +23,8 @@
 print(hex(pow(y, x-1, x))) # Should be 1, since x is prime
 print(hex(pow(y, y-1, x))) # Should be a 'big value'
 print(hex(pow(y, y-1, y))) # Should be a 'big value'
+
+try:
+    print(pow(1, 2, 0))
+except ValueError:
+    print("ValueError")
diff --git a/tests/basics/builtin_range.py b/tests/basics/builtin_range.py
index 66226bad16a..9608a816310 100644
--- a/tests/basics/builtin_range.py
+++ b/tests/basics/builtin_range.py
@@ -32,13 +32,29 @@
 print(range(1, 4)[0:])
 print(range(1, 4)[1:])
 print(range(1, 4)[:-1])
+print(range(4, 1)[:])
+print(range(4, 1)[0:])
+print(range(4, 1)[1:])
+print(range(4, 1)[:-1])
 print(range(7, -2, -4)[:])
 print(range(1, 100, 5)[5:15:3])
 print(range(1, 100, 5)[15:5:-3])
 print(range(100, 1, -5)[5:15:3])
 print(range(100, 1, -5)[15:5:-3])
+print(range(1, 100, 5)[5:15:-3])
+print(range(1, 100, 5)[15:5:3])
+print(range(100, 1, -5)[5:15:-3])
+print(range(100, 1, -5)[15:5:3])
+print(range(1, 100, 5)[5:15:3])
+print(range(1, 100, 5)[15:5:-3])
+print(range(1, 100, -5)[5:15:3])
+print(range(1, 100, -5)[15:5:-3])
+print(range(1, 100, 5)[5:15:-3])
+print(range(1, 100, 5)[15:5:3])
+print(range(1, 100, -5)[5:15:-3])
+print(range(1, 100, -5)[15:5:3])
 
-# for this case uPy gives a different stop value but the listed elements are still correct
+# for this case MicroPython gives a different stop value but the listed elements are still correct
 print(list(range(7, -2, -4)[2:-2:]))
 
 # zero step
diff --git a/tests/basics/builtin_range_maxsize.py b/tests/basics/builtin_range_maxsize.py
new file mode 100644
index 00000000000..b0f3a5e5129
--- /dev/null
+++ b/tests/basics/builtin_range_maxsize.py
@@ -0,0 +1,38 @@
+try:
+    from sys import maxsize
+except ImportError:
+    print("SKIP")
+    raise SystemExit
+
+# Test the range builtin at extreme values. (https://github.com/micropython/micropython/issues/17684)
+#
+# This is written using asserts instead of prints because the value of `maxsize` differs.
+#
+# Numbers & counts right up against the max of mp_int_t also cause overflows, such as
+# objrange.c:115:14: runtime error: signed integer overflow: 9223372036854775807 + 1 cannot be represented in type 'long int'
+# so just avoid them for the purposes of this test.
+
+r = range(-maxsize + 1, -1)
+assert r.start == -maxsize + 1
+assert r.stop == -1
+assert r[0] == -maxsize + 1
+assert r[1] == -maxsize + 2
+assert r[-1] == -2
+assert r[-2] == -3
+
+ir = iter(r)
+assert next(ir) == -maxsize + 1
+assert next(ir) == -maxsize + 2
+
+r = range(0, maxsize - 1)
+assert len(r) == maxsize - 1
+assert r.stop == maxsize - 1
+
+r = range(maxsize, 0, -1)
+assert len(r) == maxsize
+assert r.start == maxsize
+assert r[0] == maxsize
+assert r[1] == maxsize - 1
+ir = iter(r)
+assert next(ir) == maxsize
+assert next(ir) == maxsize - 1
diff --git a/tests/basics/builtin_setattr.py b/tests/basics/builtin_setattr.py
index e4acb14cac3..2c9a452c327 100644
--- a/tests/basics/builtin_setattr.py
+++ b/tests/basics/builtin_setattr.py
@@ -21,5 +21,5 @@ def __init__(self):
 try:
     setattr(int, 'to_bytes', 1)
 except (AttributeError, TypeError):
-    # uPy raises AttributeError, CPython raises TypeError
+    # MicroPython raises AttributeError, CPython raises TypeError
     print('AttributeError/TypeError')
diff --git a/tests/basics/builtin_slice.py b/tests/basics/builtin_slice.py
index 3ff3c3dd04d..cbce3d14ed6 100644
--- a/tests/basics/builtin_slice.py
+++ b/tests/basics/builtin_slice.py
@@ -1,11 +1,44 @@
 # test builtin slice
 
+# ensures that slices passed to user types are heap-allocated and can be
+# safely stored as well as not overridden by subsequent slices.
+
 # print slice
 class A:
     def __getitem__(self, idx):
-        print(idx)
+        print("get", idx)
+        print("abc"[1:])
+        print("get", idx)
+        return idx
+
+    def __setitem__(self, idx, value):
+        print("set", idx)
+        print("abc"[1:])
+        print("set", idx)
+        self.saved_idx = idx
+        return idx
+
+    def __delitem__(self, idx):
+        print("del", idx)
+        print("abc"[1:])
+        print("del", idx)
         return idx
-s = A()[1:2:3]
+
+
+a = A()
+s = a[1:2:3]
+a[4:5:6] = s
+del a[7:8:9]
+
+print(a.saved_idx)
+
+# nested slicing
+print(A()[1 : A()[A()[2:3:4] : 5]])
+
+# tuple slicing
+a[1:2, 4:5, 7:8]
+a[1, 4:5, 7:8, 2]
+a[1:2, a[3:4], 5:6]
 
 # check type
 print(type(s) is slice)
diff --git a/tests/basics/builtin_str_hex.py b/tests/basics/builtin_str_hex.py
index 7390c8eaee1..f77fe7c4fa9 100644
--- a/tests/basics/builtin_str_hex.py
+++ b/tests/basics/builtin_str_hex.py
@@ -3,6 +3,7 @@
     raise SystemExit
 
 for x in (
+    b"",
     b"\x00\x01\x02\x03\x04\x05\x06\x07",
     b"\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f",
     b"\x7f\x80\xff",
@@ -20,5 +21,20 @@
     "08090a0b0c0d0e0f",
     "7f80ff",
     "313233344142434461626364",
+    "ab\tcd\n  ef ",
+    "ab cd ef",
+    "ab cd ef ",
+    " ab cd ef ",
+    # Invalid hex strings:
+    "abcde",  # Odd number of hex digits
+    "ab cd e",
+    "a b cd ef",  # Spaces between hex pairs
+    "ab cd e f ",
+    "abga",  # Invalid hex digits
+    "ab_cd",
+    "ab:cd",
 ):
-    print(bytes.fromhex(x))
+    try:
+        print(bytes.fromhex(x))
+    except ValueError:
+        print("ValueError", x)
diff --git a/tests/basics/builtin_str_hex.py.exp b/tests/basics/builtin_str_hex.py.exp
deleted file mode 100644
index 990dd857076..00000000000
--- a/tests/basics/builtin_str_hex.py.exp
+++ /dev/null
@@ -1,28 +0,0 @@
-0001020304050607
-0001020304050607
-0001020304050607
-00:01:02:03:04:05:06:07
-00:01:02:03:04:05:06:07
-00:01:02:03:04:05:06:07
-08090a0b0c0d0e0f
-08090a0b0c0d0e0f
-08090a0b0c0d0e0f
-08:09:0a:0b:0c:0d:0e:0f
-08:09:0a:0b:0c:0d:0e:0f
-08:09:0a:0b:0c:0d:0e:0f
-7f80ff
-7f80ff
-7f80ff
-7f:80:ff
-7f:80:ff
-7f:80:ff
-313233344142434461626364
-313233344142434461626364
-313233344142434461626364
-31:32:33:34:41:42:43:44:61:62:63:64
-31:32:33:34:41:42:43:44:61:62:63:64
-31:32:33:34:41:42:43:44:61:62:63:64
-b'\x00\x01\x02\x03\x04\x05\x06\x07'
-b'\x08\t\n\x0b\x0c\r\x0e\x0f'
-b'\x7f\x80\xff'
-b'1234ABCDabcd'
diff --git a/tests/basics/builtin_super.py b/tests/basics/builtin_super.py
new file mode 100644
index 00000000000..5f7c3ae017e
--- /dev/null
+++ b/tests/basics/builtin_super.py
@@ -0,0 +1,15 @@
+# Check that super rejects invalid arguments.
+try:
+    super(str, 0)
+except TypeError:
+    print("TypeError")
+
+try:
+    super(str, int)
+except TypeError:
+    print("TypeError")
+
+try:
+    super(0, int)
+except TypeError:
+    print("TypeError")
diff --git a/tests/basics/bytearray_byte_operations.py b/tests/basics/bytearray_byte_operations.py
index 48b08ab2619..794fe8cafa2 100644
--- a/tests/basics/bytearray_byte_operations.py
+++ b/tests/basics/bytearray_byte_operations.py
@@ -2,6 +2,7 @@
 
 print(bytearray(b"hello world").find(b"ll"))
 print(bytearray(b"hello\x00world").rfind(b"l"))
+print(bytearray(b"hello world").find(ord(b"l")))
 
 print(bytearray(b"abc  efg ").strip(b"g a"))
 print(bytearray(b"   spacious   ").lstrip())
@@ -14,10 +15,18 @@
 
 print(bytearray(b"asdfasdf").replace(b"a", b"b"))
 
-print("00\x0000".index("0", 0))
-print("00\x0000".index("0", 3))
-print("00\x0000".rindex("0", 0))
-print("00\x0000".rindex("0", 3))
+print(b"00\x0000".index(b"0", 0))
+print(b"00\x0000".index(b"0", 3))
+print(b"00\x0000".index(ord("0"), 0))
+print(b"00\x0000".index(ord("0"), 3))
+print(b"00\x0000".index(0, 0))
+try:
+    print(b"00\x0000".index(0, 3))
+except ValueError:
+    print("ValueError")
+print(b"00\x0000".index(b"0", 3))
+print(b"00\x0000".rindex(b"0", 0))
+print(b"00\x0000".rindex(b"0", 3))
 
 print(bytearray(b"foobar").endswith(b"bar"))
 print(bytearray(b"1foo").startswith(b"foo", 1))
diff --git a/tests/basics/bytes_find.py b/tests/basics/bytes_find.py
index 75ef9796cd1..1ecbf13b0cf 100644
--- a/tests/basics/bytes_find.py
+++ b/tests/basics/bytes_find.py
@@ -21,6 +21,44 @@
 print(b"0000".find(b'1', 3))
 print(b"0000".find(b'1', 4))
 print(b"0000".find(b'1', 5))
+print(b"0000".find(ord(b'0')))
+print(b"0000".find(ord(b'0'), 0))
+print(b"0000".find(ord(b'0'), 1))
+print(b"0000".find(ord(b'0'), 2))
+print(b"0000".find(ord(b'0'), 3))
+print(b"0000".find(ord(b'0'), 4))
+print(b"0000".find(ord(b'0'), 5))
+print(b"0000".find(ord(b'x'), 3))
+print(b"0000".find(ord(b'1'), 3))
+print(b"0000".find(ord(b'1'), 4))
+print(b"0000".find(ord(b'1'), 5))
 
 # Non-ascii values (make sure not treated as unicode-like)
 print(b"\x80abc".find(b"a", 1))
+
+# Int-like conversion.
+print(b"00\x0000".find(b'0', True))
+
+# Out of bounds int.
+try:
+    print(b"0000".find(b'0', -1))
+except ValueError:
+    print("ValueError")
+try:
+    print(b"0000".find(b'0', 256))
+except ValueError:
+    print("ValueError")
+try:
+    print(b"0000".find(b'0', 91273611))
+except ValueError:
+    print("ValueError")
+
+# Out of bounds search argument.
+try:
+    print(b"0000".find(-1))
+except ValueError:
+    print("ValueError")
+try:
+    print(b"0000".find(256))
+except ValueError:
+    print("ValueError")
diff --git a/tests/basics/bytes_format_modulo.py.exp b/tests/basics/bytes_format_modulo.py.exp
deleted file mode 100644
index 782b7f91fcb..00000000000
--- a/tests/basics/bytes_format_modulo.py.exp
+++ /dev/null
@@ -1,5 +0,0 @@
-b'%'
-b'=1='
-b'=1=2='
-b'=str='
-b"=b'str'="
diff --git a/tests/basics/bytes_index.py b/tests/basics/bytes_index.py
new file mode 100644
index 00000000000..d99b325192e
--- /dev/null
+++ b/tests/basics/bytes_index.py
@@ -0,0 +1,109 @@
+print(b"hello world".index(b"ll"))
+print(b"hello world".index(b"ll", None))
+print(b"hello world".index(b"ll", 1))
+print(b"hello world".index(b"ll", 1, None))
+print(b"hello world".index(b"ll", None, None))
+print(b"hello world".index(b"ll", 1, -1))
+try:
+    print(b"hello world".index(b"ll", 1, 1))
+except ValueError:
+    print("ValueError")
+try:
+    print(b"hello world".index(b"ll", 1, 2))
+except ValueError:
+    print("ValueError")
+try:
+    print(b"hello world".index(b"ll", 1, 3))
+except ValueError:
+    print("ValueError")
+print(b"hello world".index(b"ll", 1, 4))
+print(b"hello world".index(b"ll", 1, 5))
+print(b"hello world".index(b"ll", -100))
+print(b"0000".index(b'0'))
+print(b"0000".index(b'0', 0))
+print(b"0000".index(b'0', 1))
+print(b"0000".index(b'0', 2))
+print(b"0000".index(b'0', 3))
+try:
+    print(b"0000".index(b'0', 4))
+except ValueError:
+    print("ValueError")
+try:
+    print(b"0000".index(b'0', 5))
+except ValueError:
+    print("ValueError")
+try:
+    print(b"0000".index(b'-1', 3))
+except ValueError:
+    print("ValueError")
+try:
+    print(b"0000".index(b'1', 3))
+except ValueError:
+    print("ValueError")
+try:
+    print(b"0000".index(b'1', 4))
+except ValueError:
+    print("ValueError")
+try:
+    print(b"0000".index(b'1', 5))
+except ValueError:
+    print("ValueError")
+print(b"0000".index(ord(b'0')))
+print(b"0000".index(ord(b'0'), 0))
+print(b"0000".index(ord(b'0'), 1))
+print(b"0000".index(ord(b'0'), 2))
+print(b"0000".index(ord(b'0'), 3))
+try:
+    print(b"0000".index(ord(b'0'), 4))
+except ValueError:
+    print("ValueError")
+try:
+    print(b"0000".index(ord(b'0'), 5))
+except ValueError:
+    print("ValueError")
+try:
+    print(b"0000".index(ord(b'x'), 3))
+except ValueError:
+    print("ValueError")
+try:
+    print(b"0000".index(ord(b'1'), 3))
+except ValueError:
+    print("ValueError")
+try:
+    print(b"0000".index(ord(b'1'), 4))
+except ValueError:
+    print("ValueError")
+try:
+    print(b"0000".index(ord(b'1'), 5))
+except ValueError:
+    print("ValueError")
+
+# Non-ascii values (make sure not treated as unicode-like)
+print(b"\x80abc".index(b"a", 1))
+
+# Int-like conversion.
+print(b"00\x0000".index(b'0', True))
+
+# Out of bounds int.
+try:
+    print(b"0000".index(b'0', -1))
+except ValueError:
+    print("ValueError")
+try:
+    print(b"0000".index(b'0', 256))
+except ValueError:
+    print("ValueError")
+try:
+    print(b"0000".index(b'0', 91273611))
+except ValueError:
+    print("ValueError")
+
+# Out of bounds search argument.
+try:
+    print(b"0000".index(-1))
+except ValueError:
+    print("ValueError")
+try:
+    print(b"0000".index(256))
+except ValueError:
+    print("ValueError")
diff --git a/tests/basics/class_bind_self.py b/tests/basics/class_bind_self.py
index 813f876446e..8bece902ca2 100644
--- a/tests/basics/class_bind_self.py
+++ b/tests/basics/class_bind_self.py
@@ -52,7 +52,7 @@ def f4(self, arg): # generator
 print(C.f8(13))
 print(C.f9(14))
 
-# not working in uPy
+# not working in MicroPython
 #class C(list):
 #    # this acts like a method and binds self
 #    f1 = list.extend
diff --git a/tests/basics/class_descriptor.py b/tests/basics/class_descriptor.py
index 54f386230fe..feaed2fbb2a 100644
--- a/tests/basics/class_descriptor.py
+++ b/tests/basics/class_descriptor.py
@@ -1,34 +1,67 @@
 class Descriptor:
     def __get__(self, obj, cls):
-        print('get')
+        print("get")
         print(type(obj) is Main)
         print(cls is Main)
-        return 'result'
+        return "result"
 
     def __set__(self, obj, val):
-        print('set')
+        print("set")
         print(type(obj) is Main)
         print(val)
 
     def __delete__(self, obj):
-        print('delete')
+        print("delete")
         print(type(obj) is Main)
 
+    def __set_name__(self, owner, name):
+        print("set_name", name)
+        print(owner.__name__ == "Main")
+
+
 class Main:
     Forward = Descriptor()
 
+
 m = Main()
 try:
     m.__class__
 except AttributeError:
+    # Target doesn't support __class__.
     print("SKIP")
     raise SystemExit
 
 r = m.Forward
-if 'Descriptor' in repr(r.__class__):
-    print('SKIP')
+if "Descriptor" in repr(r.__class__):
+    # Target doesn't support descriptors.
+    print("SKIP")
     raise SystemExit
 
+# Test assignment and deletion.
+
 print(r)
-m.Forward = 'a'
+m.Forward = "a"
 del m.Forward
+
+# Test that lookup of descriptors like __get__ are not passed into __getattr__.
+
+
+class NonDescriptor:
+    def __getattr__(self, attr):
+        print("getattr", attr)
+
+
+class TestClass:
+    non_descriptor = NonDescriptor()
+
+
+print(isinstance(TestClass().non_descriptor, NonDescriptor))
+
+t = TestClass()
+t.non_descriptor = 123
+print(t.non_descriptor)
+
+try:
+    del TestClass().non_descriptor
+except AttributeError:
+    print("AttributeError")
diff --git a/tests/basics/class_inplace_op2.py.exp b/tests/basics/class_inplace_op2.py.exp
deleted file mode 100644
index 8c323b5178e..00000000000
--- a/tests/basics/class_inplace_op2.py.exp
+++ /dev/null
@@ -1,12 +0,0 @@
-__imul__
-__imatmul__
-__ifloordiv__
-__itruediv__
-__imod__
-__ipow__
-__ior__
-__ixor__
-__iand__
-__ilshift__
-__irshift__
-TypeError
diff --git a/tests/basics/class_ordereddict.py.exp b/tests/basics/class_ordereddict.py.exp
deleted file mode 100644
index b723e327515..00000000000
--- a/tests/basics/class_ordereddict.py.exp
+++ /dev/null
@@ -1 +0,0 @@
-['a', 'b', 'c', 'd', 'e']
diff --git a/tests/basics/class_setname_hazard.py b/tests/basics/class_setname_hazard.py
new file mode 100644
index 00000000000..77c04093462
--- /dev/null
+++ b/tests/basics/class_setname_hazard.py
@@ -0,0 +1,182 @@
+# Test that __set_name__ can access and mutate its owner argument.
+
+
+def skip_if_no_descriptors():
+    class Descriptor:
+        def __get__(self, obj, cls):
+            return
+
+    class TestClass:
+        Forward = Descriptor()
+
+    a = TestClass()
+    try:
+        a.__class__
+    except AttributeError:
+        # Target doesn't support __class__.
+        print("SKIP")
+        raise SystemExit
+
+    b = a.Forward
+    if "Descriptor" in repr(b.__class__):
+        # Target doesn't support descriptors.
+        print("SKIP")
+        raise SystemExit
+
+
+skip_if_no_descriptors()
+
+
+# Test basic accesses and mutations.
+
+
+class GetSibling:
+    def __set_name__(self, owner, name):
+        print(getattr(owner, name + "_sib"))
+
+
+class GetSiblingTest:
+    desc = GetSibling()
+    desc_sib = 111
+
+
+t110 = GetSiblingTest()
+
+
+class SetSibling:
+    def __set_name__(self, owner, name):
+        setattr(owner, name + "_sib", 121)
+
+
+class SetSiblingTest:
+    desc = SetSibling()
+
+
+t120 = SetSiblingTest()
+
+print(t120.desc_sib)
+
+
+class DelSibling:
+    def __set_name__(self, owner, name):
+        delattr(owner, name + "_sib")
+
+
+class DelSiblingTest:
+    desc = DelSibling()
+    desc_sib = 131
+
+
+t130 = DelSiblingTest()
+
+try:
+    print(t130.desc_sib)
+except AttributeError:
+    print("AttributeError")
+
+
+class GetSelf:
+    x = 211
+
+    def __set_name__(self, owner, name):
+        print(getattr(owner, name).x)
+
+
+class GetSelfTest:
+    desc = GetSelf()
+
+
+t210 = GetSelfTest()
+
+
+class SetSelf:
+    def __set_name__(self, owner, name):
+        setattr(owner, name, 221)
+
+
+class SetSelfTest:
+    desc = SetSelf()
+
+
+t220 = SetSelfTest()
+
+print(t220.desc)
+
+
+class DelSelf:
+    def __set_name__(self, owner, name):
+        delattr(owner, name)
+
+
+class DelSelfTest:
+    desc = DelSelf()
+
+
+t230 = DelSelfTest()
+
+try:
+    print(t230.desc)
+except AttributeError:
+    print("AttributeError")
+
+
+# Test exception behavior.
+
+
+class Raise:
+    def __set_name__(self, owner, name):
+        raise Exception()
+
+
+try:
+
+    class RaiseTest:
+        desc = Raise()
+except Exception as e:  # CPython raises RuntimeError, MicroPython propagates the original exception
+    print("Exception")
+
+
+# Ensure removed/overwritten class members still get __set_name__ called.
+
+
+class SetSpecific:
+    def __init__(self, sib_name, sib_replace):
+        self.sib_name = sib_name
+        self.sib_replace = sib_replace
+
+    def __set_name__(self, owner, name):
+        setattr(owner, self.sib_name, self.sib_replace)
+
+
+class SetReplaceTest:
+    a = SetSpecific("b", 312)  # one of these is changed first
+    b = SetSpecific("a", 311)
+
+
+t310 = SetReplaceTest()
+print(t310.a)
+print(t310.b)
+
+
+class DelSpecific:
+    def __init__(self, sib_name):
+        self.sib_name = sib_name
+
+    def __set_name__(self, owner, name):
+        delattr(owner, self.sib_name)
+
+
+class DelReplaceTest:
+    a = DelSpecific("b")  # one of these is removed first
+    b = DelSpecific("a")
+
+
+t320 = DelReplaceTest()
+try:
+    print(t320.a)
+except AttributeError:
+    print("AttributeError")
+try:
+    print(t320.b)
+except AttributeError:
+    print("AttributeError")
diff --git a/tests/basics/class_setname_hazard_rand.py b/tests/basics/class_setname_hazard_rand.py
new file mode 100644
index 00000000000..4c9934c3bf0
--- /dev/null
+++ b/tests/basics/class_setname_hazard_rand.py
@@ -0,0 +1,111 @@
+# Test to make sure there's no sequence hazard even when a __set_name__ implementation
+# mutates and reorders the namespace of its owner class.
+# VERY hard bug to prove out except via a stochastic test.
+
+
+try:
+    from random import choice
+    import re
+except ImportError:
+    print("SKIP")
+    raise SystemExit
+
+
+def skip_if_no_descriptors():
+    class Descriptor:
+        def __get__(self, obj, cls):
+            return
+
+    class TestClass:
+        Forward = Descriptor()
+
+    a = TestClass()
+    try:
+        a.__class__
+    except AttributeError:
+        # Target doesn't support __class__.
+        print("SKIP")
+        raise SystemExit
+
+    b = a.Forward
+    if "Descriptor" in repr(b.__class__):
+        # Target doesn't support descriptors.
+        print("SKIP")
+        raise SystemExit
+
+
+skip_if_no_descriptors()
+
+letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+
+# Would be r"[A-Z]{5}", but not all ports support the {n} quantifier.
+junk_re = re.compile(r"[A-Z][A-Z][A-Z][A-Z][A-Z]")
+
+
+def junk_fill(obj, n=10):  # Add randomly-generated attributes to an object.
+    for i in range(n):
+        name = "".join(choice(letters) for j in range(5))
+        setattr(obj, name, object())
+
+
+def junk_clear(obj):  # Remove attributes added by junk_fill.
+    to_del = [name for name in dir(obj) if junk_re.match(name)]
+    for name in to_del:
+        delattr(obj, name)
+
+
+def junk_sequencer():
+    global runs
+    try:
+        while True:
+            owner, name = yield
+            runs[name] = runs.get(name, 0) + 1
+            junk_fill(owner)
+    finally:
+        junk_clear(owner)
+
+
+class JunkMaker:
+    def __set_name__(self, owner, name):
+        global seq
+        seq.send((owner, name))
+
+
+runs = {}
+seq = junk_sequencer()
+next(seq)
+
+
+class Main:
+    a = JunkMaker()
+    b = JunkMaker()
+    c = JunkMaker()
+    d = JunkMaker()
+    e = JunkMaker()
+    f = JunkMaker()
+    g = JunkMaker()
+    h = JunkMaker()
+    i = JunkMaker()
+    j = JunkMaker()
+    k = JunkMaker()
+    l = JunkMaker()
+    m = JunkMaker()
+    n = JunkMaker()
+    o = JunkMaker()
+    p = JunkMaker()
+    q = JunkMaker()
+    r = JunkMaker()
+    s = JunkMaker()
+    t = JunkMaker()
+    u = JunkMaker()
+    v = JunkMaker()
+    w = JunkMaker()
+    x = JunkMaker()
+    y = JunkMaker()
+    z = JunkMaker()
+
+
+seq.close()
+
+for k in letters.lower():
+    print(k, runs.get(k, 0))
diff --git a/tests/basics/del_attr.py b/tests/basics/del_attr.py
index 8487b97e311..90a8a5a6f83 100644
--- a/tests/basics/del_attr.py
+++ b/tests/basics/del_attr.py
@@ -35,5 +35,5 @@ def f():
 try:
     del int.to_bytes
 except (AttributeError, TypeError):
-    # uPy raises AttributeError, CPython raises TypeError
+    # MicroPython raises AttributeError, CPython raises TypeError
     print('AttributeError/TypeError')
diff --git a/tests/basics/del_global.py b/tests/basics/del_global.py
index d740357b033..e1aa074b97a 100644
--- a/tests/basics/del_global.py
+++ b/tests/basics/del_global.py
@@ -14,7 +14,7 @@ def do_del():
 try:
     do_del()
 except: # NameError:
-    # FIXME uPy returns KeyError for this
+    # FIXME MicroPython returns KeyError for this
     print("NameError")
 
 # delete globals using a list
diff --git a/tests/basics/del_name.py b/tests/basics/del_name.py
index c92be54d3b6..8393b2df92a 100644
--- a/tests/basics/del_name.py
+++ b/tests/basics/del_name.py
@@ -10,7 +10,7 @@
 try:
     del x
 except: # NameError:
-    # FIXME uPy returns KeyError for this
+    # FIXME MicroPython returns KeyError for this
     print("NameError")
 
 class C:
diff --git a/tests/basics/deque2.py b/tests/basics/deque2.py
index 3552d5be37a..ebc0872c7b4 100644
--- a/tests/basics/deque2.py
+++ b/tests/basics/deque2.py
@@ -31,6 +31,16 @@
 d[3] = 5
 print(d[3])
 
+# Access the last element via index, when the last element is at various locations
+d = deque((), 2)
+for i in range(4):
+    d.append(i)
+    print(i, d[-1])
+
+# Write the last element then access all elements from the end
+d[-1] = 4
+print(d[-2], d[-1])
+
 # Accessing indices out of bounds raises IndexError
 try:
     d[4]
diff --git a/tests/basics/deque_micropython.py b/tests/basics/deque_micropython.py
index 5f32bbc496a..fb9771fefeb 100644
--- a/tests/basics/deque_micropython.py
+++ b/tests/basics/deque_micropython.py
@@ -45,12 +45,12 @@
 try:
     d.popleft()
 except IndexError as e:
-    print(repr(e))
+    print(str(e) or 'empty', len(d))
 
 try:
     d.pop()
 except IndexError as e:
-    print(repr(e))
+    print(str(e) or 'empty', len(d))
 
 d.append(5)
 d.append(6)
@@ -58,12 +58,12 @@
 try:
     d.append(7)
 except IndexError as e:
-    print(repr(e))
+    print(str(e) or 'full', len(d))
 
 try:
     d.appendleft(8)
 except IndexError as e:
-    print(repr(e))
+    print(str(e) or 'full', len(d))
 
 print(len(d))
 
@@ -72,4 +72,4 @@
 try:
     d.popleft()
 except IndexError as e:
-    print(repr(e))
+    print(str(e) or 'empty', len(d))
diff --git a/tests/basics/deque_micropython.py.exp b/tests/basics/deque_micropython.py.exp
index f1ff7b77ac8..7869dc8cacc 100644
--- a/tests/basics/deque_micropython.py.exp
+++ b/tests/basics/deque_micropython.py.exp
@@ -6,12 +6,12 @@ None
 1
 2
 3 4
-IndexError('empty',)
-IndexError('empty',)
+empty 0
+empty 0
 2
-IndexError('full',)
-IndexError('full',)
+full 2
+full 2
 2
 5 6
 0
-IndexError('empty',)
+empty 0
diff --git a/tests/basics/dict_views.py b/tests/basics/dict_views.py
index a82f47b6be2..45f3238f1c6 100644
--- a/tests/basics/dict_views.py
+++ b/tests/basics/dict_views.py
@@ -6,6 +6,11 @@
 # print a view with more than one item
 print({1:1, 2:1}.values())
 
+# `bool` and `len` unary ops
+for d in ({}, {1: 2}, {1: 2, 3: 4}):
+    for op in (bool, len):
+        print(op(d.keys()), op(d.values()), op(d.items()))
+
 # unsupported binary op on a dict values view
 try:
     {1:1}.values() + 1
diff --git a/tests/basics/exception_chain.py b/tests/basics/exception_chain.py
index 579756c85fa..96c06c847ab 100644
--- a/tests/basics/exception_chain.py
+++ b/tests/basics/exception_chain.py
@@ -1,5 +1,12 @@
 # CIRCUITPY-CHANGE: exception chaining is supported
 
+import sys
+
+# The unix minimal build doesn't enable MICROPY_WARNINGS (required for this test).
+if getattr(sys.implementation, "_build", None) == "minimal":
+    print("SKIP")
+    raise SystemExit
+
 try:
     Exception().__cause__
 except AttributeError:
diff --git a/tests/basics/frozenset_set.py b/tests/basics/frozenset_set.py
index 3bf456acfd7..2b3c6832609 100644
--- a/tests/basics/frozenset_set.py
+++ b/tests/basics/frozenset_set.py
@@ -8,5 +8,5 @@
 # "Instances of set are compared to instances of frozenset based on their
 # members. For example:"
 print(set('abc') == frozenset('abc'))
-# This doesn't work in uPy
+# This doesn't work in MicroPython
 #print(set('abc') in set([frozenset('abc')]))
diff --git a/tests/basics/fun_callstar_kwarg.py b/tests/basics/fun_callstar_kwarg.py
new file mode 100644
index 00000000000..15bc19e216e
--- /dev/null
+++ b/tests/basics/fun_callstar_kwarg.py
@@ -0,0 +1,8 @@
+# A CPython syntax feature not supported by MicroPython. For more information
+# see `this issue `_.
+# and tests/cpydiff/core_function_star.py
+
+try:
+    exec("f(y=1, *(3,))")
+except SyntaxError as e:
+    print("SyntaxError")
diff --git a/tests/basics/fun_callstar_kwarg.py.exp b/tests/basics/fun_callstar_kwarg.py.exp
new file mode 100644
index 00000000000..8729fc43437
--- /dev/null
+++ b/tests/basics/fun_callstar_kwarg.py.exp
@@ -0,0 +1 @@
+SyntaxError
diff --git a/tests/basics/fun_code.py b/tests/basics/fun_code.py
new file mode 100644
index 00000000000..841357e8aad
--- /dev/null
+++ b/tests/basics/fun_code.py
@@ -0,0 +1,41 @@
+# Test function.__code__ attribute.
+
+try:
+    (lambda: 0).__code__
+except AttributeError:
+    print("SKIP")
+    raise SystemExit
+
+
+def f():
+    return a
+
+
+ftype = type(f)
+
+# Test __code__ access and function constructor.
+code = f.__code__
+print(type(ftype(code, {})) is ftype)
+
+# Test instantiating multiple code's with different globals dicts.
+code = f.__code__
+f1 = ftype(code, {"a": 1})
+f2 = ftype(code, {"a": 2})
+print(f1(), f2())
+
+# Test bad first argument type.
+try:
+    ftype(None, {})
+except TypeError:
+    print("TypeError")
+
+# Test bad second argument type.
+try:
+    ftype(f.__code__, None)
+except TypeError:
+    print("TypeError")
+
+# Test __code__ on functions with children functions.
+code = (lambda: (lambda: a)).__code__
+print(ftype(code, {"a": 1})()())
+print(ftype(code, {"a": 2})()())
diff --git a/tests/basics/fun_code_colines.py b/tests/basics/fun_code_colines.py
new file mode 100644
index 00000000000..a8867770edd
--- /dev/null
+++ b/tests/basics/fun_code_colines.py
@@ -0,0 +1,81 @@
+# Check that we have sensical bytecode offsets in function.__code__.co_lines
+
+def f1(x, y, obj, obj2, obj3):
+    a = x + y # line 4: bc+4 line+4
+    b = x - y # line 5: bc+4 line+1
+    # line 6
+    # line 7
+    # line 8
+    # line 9
+    # line 10
+    # line 11
+    # line 12
+    # line 13
+    # line 14
+    # line 15
+    # line 16
+    # line 17
+    # line 18
+    # line 19
+    c = a * b # line 20: bc+4 line+15
+    obj.a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p.q.r.s.t.u.v.w.x.y.z.fun() # line 21: bc+31 line+1; bc+27 line+0
+    # line 22
+    # line 23
+    # line 24: bc+0 line+3
+    # line 25
+    # line 26
+    # line 27: bc+0 line+3
+    # line 28
+    # line 29
+    obj2.a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p.q.r.s.t.u.v.w.x.y.z.fun() # line 30: bc+31 line+3; bc+27 line+0
+    # line 31
+    # line 32
+    # line 33: bc+0 line+3
+    # line 34
+    # line 35
+    # line 36
+    # line 37
+    # line 38
+    # line 39
+    # line 40
+    # line 41
+    # line 42
+    # line 43
+    # line 44
+    # line 45
+    # line 46
+    # line 47
+    # line 48
+    # line 49
+    # line 50
+    # line 51
+    # line 52
+    # line 53
+    # line 54
+    # line 55
+    # line 56
+    # line 57
+    # line 58
+    # line 59
+    return obj3.a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p.q.r.s.t.u.v.w.x.y.z.fun() # line 60: bc+31 line+27; bc+27 line+0
+
+def f2(x, y):
+    a = x + y # line 63
+    b = x - y # line 64
+    return a * b # line 65
+
+try:
+    f1.__code__.co_lines
+except AttributeError:
+    print("SKIP")
+    raise SystemExit
+
+print("f1")
+for start, end, line_no in f1.__code__.co_lines():
+    print("line {} start: {}".format(line_no, start))
+    print("line {} end: {}".format(line_no, end))
+
+print("f2")
+for start, end, line_no in f2.__code__.co_lines():
+    print("line {} start: {}".format(line_no, start))
+    print("line {} end: {}".format(line_no, end))
diff --git a/tests/basics/fun_code_colines.py.exp b/tests/basics/fun_code_colines.py.exp
new file mode 100644
index 00000000000..19bd4ef6e2a
--- /dev/null
+++ b/tests/basics/fun_code_colines.py.exp
@@ -0,0 +1,20 @@
+f1
+line 4 start: 0
+line 4 end: 4
+line 5 start: 4
+line 5 end: 8
+line 20 start: 8
+line 20 end: 12
+line 21 start: 12
+line 21 end: 70
+line 30 start: 70
+line 30 end: 128
+line 60 start: 128
+line 60 end: 186
+f2
+line 63 start: 0
+line 63 end: 4
+line 64 start: 4
+line 64 end: 8
+line 65 start: 8
+line 65 end: 12
diff --git a/tests/basics/fun_code_full.py b/tests/basics/fun_code_full.py
new file mode 100644
index 00000000000..538863631a6
--- /dev/null
+++ b/tests/basics/fun_code_full.py
@@ -0,0 +1,38 @@
+# Test function.__code__ attributes not available with MICROPY_PY_BUILTINS_CODE <= MICROPY_PY_BUILTINS_CODE_BASIC
+
+try:
+    (lambda: 0).__code__.co_code
+except AttributeError:
+    print("SKIP")
+    raise SystemExit
+
+def f(x, y):
+    a = x + y
+    b = x - y
+    return a * b
+
+code = f.__code__
+
+print(type(code.co_code)) # both bytes (but mpy and cpy have different instruction sets)
+print(code.co_consts) # (not necessarily the same set, but in this function they are)
+print(code.co_filename.rsplit('/')[-1]) # same terminal filename but might be different paths on other ports
+print(type(code.co_firstlineno)) # both ints (but mpy points to first line inside, cpy points to declaration)
+print(code.co_name)
+print(iter(code.co_names) is not None) # both iterable (but mpy returns dict with names as keys, cpy only the names; and not necessarily the same set)
+
+co_lines = code.co_lines()
+
+l = list(co_lines)
+first_start = l[0][0]
+last_end = l[-1][1]
+print(first_start) # co_lines should start at the start of the bytecode
+print(len(code.co_code) - last_end) # and end at the end of the bytecode
+
+prev_end = 0
+for start, end, line_no in l:
+    if end != prev_end:
+        print("non-contiguous")
+        break # the offset ranges should be contiguous
+    prev_end = end
+else:
+    print("contiguous")
diff --git a/tests/basics/fun_code_full.py.exp b/tests/basics/fun_code_full.py.exp
new file mode 100644
index 00000000000..830effadfc6
--- /dev/null
+++ b/tests/basics/fun_code_full.py.exp
@@ -0,0 +1,9 @@
+
+(None,)
+fun_code_full.py
+
+f
+True
+0
+0
+non-contiguous
diff --git a/tests/basics/fun_code_lnotab.py b/tests/basics/fun_code_lnotab.py
new file mode 100644
index 00000000000..9223e5730f0
--- /dev/null
+++ b/tests/basics/fun_code_lnotab.py
@@ -0,0 +1,34 @@
+# Test deprecation of co_lnotab
+
+try:
+    (lambda: 0).__code__.co_code
+except AttributeError:
+    print("SKIP")
+    raise SystemExit
+
+
+import unittest
+import sys
+
+
+mpy_is_v2 = getattr(sys.implementation, '_v2', False)
+
+
+def f():
+    pass
+
+
+class Test(unittest.TestCase):
+
+    @unittest.skipIf(mpy_is_v2, "Removed in MicroPython v2 and later.")
+    def test_co_lnotab_exists(self):
+        self.assertIsInstance(f.__code__.co_lnotab, bytes)
+
+    @unittest.skipUnless(mpy_is_v2, "Not removed before MicroPython v2.")
+    def test_co_lnotab_removed(self):
+        with self.assertRaises(AttributeError):
+            f.__code__.co_lnotab
+
+
+if __name__ == "__main__":
+    unittest.main()
diff --git a/tests/basics/fun_name.py b/tests/basics/fun_name.py
index b2642280a2a..8aac35eeafa 100644
--- a/tests/basics/fun_name.py
+++ b/tests/basics/fun_name.py
@@ -16,7 +16,7 @@ def Fun(self):
     print('SKIP')
     raise SystemExit
 
-# __name__ of a bound native method is not implemented in uPy
+# __name__ of a bound native method is not implemented in MicroPython
 # the test here is to make sure it doesn't crash
 try:
     str((1).to_bytes.__name__)
diff --git a/tests/basics/gc1.py b/tests/basics/gc1.py
index 332bf9744c0..dff9538b14b 100644
--- a/tests/basics/gc1.py
+++ b/tests/basics/gc1.py
@@ -15,13 +15,13 @@
 gc.collect()
 
 if hasattr(gc, 'mem_free'):
-    # uPy has these extra functions
+    # MicroPython has these extra functions
     # just test they execute and return an int
     assert type(gc.mem_free()) is int
     assert type(gc.mem_alloc()) is int
 
 if hasattr(gc, 'threshold'):
-    # uPy has this extra function
+    # MicroPython has this extra function
     # check execution and returns
     assert(gc.threshold(1) is None)
     assert(gc.threshold() == 0)
diff --git a/tests/basics/gen_yield_from_close.py b/tests/basics/gen_yield_from_close.py
index a493a410353..981c810564b 100644
--- a/tests/basics/gen_yield_from_close.py
+++ b/tests/basics/gen_yield_from_close.py
@@ -75,9 +75,9 @@ def gen6():
     yield -1
     try:
         print((yield from gen5()))
-    except GeneratorExit:
+    except GeneratorExit as e:
         print("delegating caught GeneratorExit")
-        raise
+        raise e
     yield 10
     yield 11
 
diff --git a/tests/basics/gen_yield_from_throw_repeat.py b/tests/basics/gen_yield_from_throw_repeat.py
index 67378ff47a1..96636a62443 100644
--- a/tests/basics/gen_yield_from_throw_repeat.py
+++ b/tests/basics/gen_yield_from_throw_repeat.py
@@ -1,4 +1,3 @@
-# CIRCUITPY-CHANGE: micropython does not have this test file
 # Test throwing repeatedly into the same generator, where that generator
 # is yielding from another generator.
 
diff --git a/tests/basics/generator_pend_throw.py b/tests/basics/generator_pend_throw.py
index ae8c21189e9..6cecd418dd0 100644
--- a/tests/basics/generator_pend_throw.py
+++ b/tests/basics/generator_pend_throw.py
@@ -46,7 +46,7 @@ def gen_next():
 try:
     next(g)
 except Exception as e:
-    print("raised", repr(e))
+    print("raised {} {}".format(type(e), str(e) or "generator already executing"))
 
 
 # Verify that you can't pend_throw from within the running coroutine.
@@ -59,7 +59,7 @@ def gen_pend_throw():
 try:
     next(g)
 except Exception as e:
-    print("raised", repr(e))
+    print("raised {} {}".format(type(e), str(e) or "generator already executing"))
 
 
 # Verify that the pend_throw exception can be ignored.
diff --git a/tests/basics/generator_pend_throw.py.exp b/tests/basics/generator_pend_throw.py.exp
index 8a3dadfec7a..56fa68be252 100644
--- a/tests/basics/generator_pend_throw.py.exp
+++ b/tests/basics/generator_pend_throw.py.exp
@@ -3,8 +3,8 @@
 raised ValueError()
 ret was: None
 raised OSError()
-raised ValueError('generator already executing',)
-raised ValueError('generator already executing',)
+raised  generator already executing
+raised  generator already executing
 0
 ignore CancelledError
 1
diff --git a/tests/basics/generator_throw_repeat.py b/tests/basics/generator_throw_repeat.py
index 2b099494d36..6d6ef60a9b0 100644
--- a/tests/basics/generator_throw_repeat.py
+++ b/tests/basics/generator_throw_repeat.py
@@ -1,4 +1,3 @@
-# CIRCUITPY-CHANGE: micropython does not have this test file
 # Test throwing repeatedly into the same generator.
 
 
diff --git a/tests/basics/import_instance_method.py b/tests/basics/import_instance_method.py
new file mode 100644
index 00000000000..d25b70ac5f0
--- /dev/null
+++ b/tests/basics/import_instance_method.py
@@ -0,0 +1,38 @@
+# Test importing a method from a class instance.
+# This is not a common thing to do, but ensures MicroPython has the same semantics as CPython.
+
+import sys
+
+if not hasattr(sys, "modules"):
+    print("SKIP")
+    raise SystemExit
+
+
+class A:
+    def __init__(self, value):
+        self.value = value
+
+    def meth(self):
+        return self.value
+
+    def meth_with_arg(self, a):
+        return [self.value, a]
+
+
+# Register a class instance as the module "mod".
+sys.modules["mod"] = A(1)
+
+# Try importing it as a module.
+import mod
+
+print(mod.meth())
+print(mod.meth_with_arg(2))
+
+# Change the module.
+sys.modules["mod"] = A(3)
+
+# Try importing it using "from ... import".
+from mod import meth, meth_with_arg
+
+print(meth())
+print(meth_with_arg(4))
diff --git a/tests/basics/import_star_nonmodule.py b/tests/basics/import_star_nonmodule.py
new file mode 100644
index 00000000000..8a98ef26ce5
--- /dev/null
+++ b/tests/basics/import_star_nonmodule.py
@@ -0,0 +1,65 @@
+# Test "from x import *" where x is something other than a module.
+
+import sys
+
+try:
+    next(iter([]), 42)
+except TypeError:
+    # Two-argument version of next() not supported.  We are probably not at
+    # MICROPY_CONFIG_ROM_LEVEL_BASIC_FEATURES which is needed for "import *".
+    print("SKIP")
+    raise SystemExit
+
+print("== test with a class as a module ==")
+
+
+class M:
+    x = "a1"
+
+    def __init__(self):
+        self.x = "a2"
+
+
+sys.modules["mod"] = M
+from mod import *
+
+print(x)
+
+sys.modules["mod"] = M()
+from mod import *
+
+print(x)
+
+print("== test with a class as a module that overrides __all__ ==")
+
+
+class M:
+    __all__ = ("y",)
+    x = "b1"
+    y = "b2"
+
+    def __init__(self):
+        self.__all__ = ("x",)
+        self.x = "b3"
+        self.y = "b4"
+
+
+sys.modules["mod"] = M
+x = None
+from mod import *
+
+print(x, y)
+
+sys.modules["mod"] = M()
+from mod import *
+
+print(x, y)
+
+print("== test with objects that don't have a __dict__ ==")
+
+sys.modules["mod"] = 1
+try:
+    from mod import *
+    # MicroPython raises AttributeError, CPython raises ImportError.
+except (AttributeError, ImportError):
+    print("ImportError")
diff --git a/tests/basics/int1.py b/tests/basics/int1.py
index 2d92105c73e..94723af4d00 100644
--- a/tests/basics/int1.py
+++ b/tests/basics/int1.py
@@ -13,6 +13,7 @@
 print(int('+1'))
 print(int('-1'))
 print(int('01'))
+print(int('00'))
 print(int('9'))
 print(int('10'))
 print(int('+10'))
@@ -31,6 +32,7 @@
 print(int('0', 10))
 print(int('1', 10))
 print(int(' \t 1 \t ', 10))
+print(int(' \t 00 \t ', 10))
 print(int('11', 10))
 print(int('11', 16))
 print(int('11', 8))
@@ -52,6 +54,17 @@
 print(int('0o12  \t  ', 8))
 print(int(b"12", 10))
 print(int(b"12"))
+print(int('000 ', 0))
+print(int('000 ', 2))
+print(int('000 ', 8))
+print(int('000 ', 10))
+print(int('000 ', 16))
+print(int('000 ', 36))
+print(int('010 ', 2))
+print(int('010 ', 8))
+print(int('010 ', 10))
+print(int('010 ', 16))
+print(int('010 ', 36))
 
 
 def test(value, base):
@@ -79,6 +92,8 @@ def test(value, base):
 test('0xg', 16)
 test('1 1', 16)
 test('123', 37)
+test('01', 0)
+test('01 ', 0)
 
 # check that we don't parse this as a floating point number
 print(0x1e+1)
diff --git a/tests/basics/int_64_basics.py b/tests/basics/int_64_basics.py
new file mode 100644
index 00000000000..b9d46c7d701
--- /dev/null
+++ b/tests/basics/int_64_basics.py
@@ -0,0 +1,161 @@
+# test support for 64-bit long integers
+# (some ports don't support arbitrary precision but do support these)
+
+# this test is adapted from int_big1.py with numbers kept within 64-bit signed range
+
+# to test arbitrary precision integers
+
+x = 1000000000000000000
+xn = -1000000000000000000
+y = 2000000000000000000
+
+# printing
+print(x)
+print(y)
+print('%#X' % (x - x)) # print prefix
+print('{:#,}'.format(x)) # print with commas
+
+# construction
+print(int(x))
+
+# addition
+print(x + 1)
+print(x + y)
+print(x + xn == 0)
+print(bool(x + xn))
+
+# subtraction
+print(x - 1)
+print(x - y)
+print(y - x)
+print(x - x == 0)
+print(bool(x - x))
+
+# multiplication
+print(x * 2)
+print(1090511627776 * 1048500)
+
+# integer division
+print(x // 2)
+print(y // x)
+
+# bit inversion
+print(~x)
+print(~(-x))
+
+# left shift
+print("left shift positive")
+x = 0x40000000
+for i in range(32):
+    x = x << 1
+    print(x)
+
+# right shift
+print("right shift positive")
+x = 0x2000000000000000  # TODO: why can't second-tip bit be set?
+for i in range(64):
+    x = x >> 1
+    print(x)
+
+# left shift of a negative number
+print("left shift negative")
+for i in range(8):
+    print(-10000000000000000 << i)
+    print(-10000000000000001 << i)
+    print(-10000000000000002 << i)
+    print(-10000000000000003 << i)
+    print(-10000000000000004 << i)
+
+
+# right shift of a negative number
+print("right shift negative")
+for i in range(8):
+    print(-1000000000000000000 >> i)
+    print(-1000000000000000001 >> i)
+    print(-1000000000000000002 >> i)
+    print(-1000000000000000003 >> i)
+    print(-1000000000000000004 >> i)
+
+# conversion from string
+print(int("1234567890123456789"))
+print(int("-1234567890123456789"))
+print(int("1234567890abcdef", 16))
+print(int("1234567890ABCDEF", 16))
+print(int("-1234567890ABCDEF", 16))
+print(int("ijklmnopqrsz", 36))
+
+# numbers close to 64-bit limits
+print(int("-9111222333444555666"))
+print(int("9111222333444555666"))
+
+# numbers with preceding 0s
+print(int("-00000000000000000000009111222333444555666"))
+print(int("0000000000000000000000009111222333444555666"))
+
+# invalid characters in string
+try:
+    print(int("1234567890abcdef"))
+except ValueError:
+    print('ValueError');
+try:
+    print(int("123456789\x01"))
+except ValueError:
+    print('ValueError');
+
+# test parsing ints just on threshold of small to big
+# for 32 bit archs
+x = 1073741823 # small
+x = -1073741823 # small
+x = 1073741824 # big
+x = -1073741824 # big
+# for 64 bit archs
+x = 4611686018427387903 # small
+x = -4611686018427387903 # small
+x = 4611686018427387904 # big
+x = -4611686018427387904 # big
+
+# sys.maxsize is a constant bigint, so test it's compatible with dynamic ones
+import sys
+if hasattr(sys, "maxsize"):
+    print(sys.maxsize - 1 + 1 == sys.maxsize)
+else:
+    print(True)  # No maxsize property in this config
+
+# test extraction of big int value via mp_obj_get_int_maybe
+x = 1 << 62
+print('a' * (x + 4 - x))
+
+# test overflow check in mp_obj_get_int_maybe
+x = 1 << 32
+r = None
+try:
+    r = range(0, x)
+except OverflowError:
+    # 32-bit target, correctly handled the overflow of x
+    print("ok")
+if r is not None:
+    if len(r) == x:
+        # 64-bit target, everything is just a small-int
+        print("ok")
+    else:
+        # 32-bit target that did not handle the overflow of x
+        print("unhandled overflow")
+
+# negative shifts are invalid
+try:
+    print((1 << 48) >> -4)
+except ValueError as e:
+    print(str(e) or "negative shift count")
+
+try:
+    print((1 << 48) << -6)
+except ValueError as e:
+    print(str(e) or "negative shift count")
+
+# Test that the most extreme 64 bit integer values all parse with int()
+print(int("-9223372036854775807"))
+print(int("-9223372036854775808"))
+print(int("9223372036854775807"))
+
+# Test that the most negative 64 bit integer can be formed via arithmetic
+print(-9223372036854775807-1)
diff --git a/tests/basics/int_big_to_small.py b/tests/basics/int_big_to_small.py
new file mode 100644
index 00000000000..c92d263fc28
--- /dev/null
+++ b/tests/basics/int_big_to_small.py
@@ -0,0 +1,33 @@
+try:
+    import micropython
+    micropython.heap_lock
+except:
+    print("SKIP")
+    raise SystemExit
+
+# Skip this test on "REPR B" where (1<<29 + 1) is not a small int.
+k = 1 << 29
+micropython.heap_lock()
+try:
+    k = k + 1
+except MemoryError:
+    print("SKIP")
+    raise SystemExit
+finally:
+    micropython.heap_unlock()
+
+# All less than small int max.
+for d in (0, 27, 1<<29, -1861, -(1<<29)):
+    i = 1<<70
+    print(i)
+    j = (1<<70) + d
+    print(j)
+    # k should now be a small int.
+    k = j - i
+    print(k)
+
+    # Now verify that working with k doesn't allocate (i.e. it's a small int).
+    micropython.heap_lock()
+    print(k + 20)
+    print(k // 20)
+    micropython.heap_unlock()
diff --git a/tests/basics/int_big_to_small.py.exp b/tests/basics/int_big_to_small.py.exp
new file mode 100644
index 00000000000..1d4986e0443
--- /dev/null
+++ b/tests/basics/int_big_to_small.py.exp
@@ -0,0 +1,25 @@
+1180591620717411303424
+1180591620717411303424
+0
+20
+0
+1180591620717411303424
+1180591620717411303451
+27
+47
+1
+1180591620717411303424
+1180591620717948174336
+536870912
+536870932
+26843545
+1180591620717411303424
+1180591620717411301563
+-1861
+-1841
+-94
+1180591620717411303424
+1180591620716874432512
+-536870912
+-536870892
+-26843546
diff --git a/tests/basics/int_big_to_small_int29.py b/tests/basics/int_big_to_small_int29.py
new file mode 100644
index 00000000000..438a74d2bc6
--- /dev/null
+++ b/tests/basics/int_big_to_small_int29.py
@@ -0,0 +1,22 @@
+try:
+    import micropython
+    micropython.heap_lock
+except:
+    print("SKIP")
+    raise SystemExit
+
+# All less than small int max.
+for d in (0, 27, 1<<28, -1861, -(1<<28)):
+    i = 1<<70
+    print(i)
+    j = (1<<70) + d
+    print(j)
+    # k should now be a small int.
+    k = j - i
+    print(k)
+
+    # Now verify that working with k doesn't allocate (i.e. it's a small int).
+    micropython.heap_lock()
+    print(k + 20)
+    print(k // 20)
+    micropython.heap_unlock()
diff --git a/tests/basics/int_big_to_small_int29.py.exp b/tests/basics/int_big_to_small_int29.py.exp
new file mode 100644
index 00000000000..0920101924a
--- /dev/null
+++ b/tests/basics/int_big_to_small_int29.py.exp
@@ -0,0 +1,25 @@
+1180591620717411303424
+1180591620717411303424
+0
+20
+0
+1180591620717411303424
+1180591620717411303451
+27
+47
+1
+1180591620717411303424
+1180591620717679738880
+268435456
+268435476
+13421772
+1180591620717411303424
+1180591620717411301563
+-1861
+-1841
+-94
+1180591620717411303424
+1180591620717142867968
+-268435456
+-268435436
+-13421773
diff --git a/tests/basics/int_bytes.py b/tests/basics/int_bytes.py
index 1f620158ece..7a1edc2ccec 100644
--- a/tests/basics/int_bytes.py
+++ b/tests/basics/int_bytes.py
@@ -1,11 +1,15 @@
-# CIRCUITPY-CHANGE: signed support
+import sys
+
 print((10).to_bytes(1, "little"))
 print((-10).to_bytes(1, "little", signed=True))
 # Test fitting in length that's not a power of two.
-print((0x10000).to_bytes(3, 'little'))
+print((0x10000).to_bytes(3, "little"))
 print((111111).to_bytes(4, "little"))
 print((-111111).to_bytes(4, "little", signed=True))
 print((100).to_bytes(10, "little"))
+print(int.from_bytes(b"\x00\x01\0\0\0\0\0\0", "little"))
+print(int.from_bytes(b"\x01\0\0\0\0\0\0\0", "little"))
+print(int.from_bytes(b"\x00\x01\0\0\0\0\0\0", "little"))
 print((-100).to_bytes(10, "little", signed=True))
 
 # check that extra zero bytes don't change the internal int value
@@ -26,24 +30,73 @@
 except ValueError:
     print("ValueError")
 
-# CIRCUITPY-CHANGE: more tests
-# too small buffer should raise an error
+# zero byte destination should also raise an error
+try:
+    (1).to_bytes(0, "little")
+except OverflowError:
+    print("OverflowError")
+
+# except for converting 0 to a zero-length byte array
+print((0).to_bytes(0, "big"))
+
+# byte length can fit the integer directly
+print((0xFF).to_bytes(1, "little"))
+print((0xFF).to_bytes(1, "big"))
+print((0xEFF).to_bytes(2, "little"))
+print((0xEFF).to_bytes(2, "big"))
+print((0xCDEFF).to_bytes(3, "little"))
+print((0xCDEFF).to_bytes(3, "big"))
+
+# OverFlowError if not big enough
+
 try:
-    (256).to_bytes(1, "little")
+    (0x123).to_bytes(1, "big")
 except OverflowError:
     print("OverflowError")
 
-# negative numbers should raise an error if signed=False
 try:
-    (-256).to_bytes(2, "little")
+    (0x12345).to_bytes(2, "big")
 except OverflowError:
     print("OverflowError")
 
+try:
+    (0x1234567).to_bytes(3, "big")
+except OverflowError:
+    print("OverflowError")
+
+
+# negative representations
+
+print((-1).to_bytes(1, "little", signed=True))
+print((-1).to_bytes(3, "little", signed=True))
+print((-1).to_bytes(1, "big", signed=True))
+print((-1).to_bytes(3, "big", signed=True))
+print((-128).to_bytes(1, "big", signed=True))
+print((-32768).to_bytes(2, "big", signed=True))
+print((-(1 << 23)).to_bytes(3, "big", signed=True))
+
+# negative numbers should raise an error if signed=False, regardless of fitting or not
 try:
     (-256).to_bytes(2, "little", signed=False)
 except OverflowError:
     print("OverflowError")
 
-# byteorder arg can be omitted; default is "big"
-print(int.from_bytes(b"\x01\0"))
-print((100).to_bytes(10))
+try:
+    (-1).to_bytes(1, "little")
+except OverflowError:
+    print("OverflowError")
+
+try:
+    print((-129).to_bytes(1, "big"))
+except OverflowError:
+    print("OverflowError")
+
+try:
+    print((-32769).to_bytes(2, "big"))
+except OverflowError:
+    print("OverflowError")
+
+try:
+    print((-(1 << 23) - 1).to_bytes(2, "big"))
+except OverflowError:
+    print("OverflowError")
diff --git a/tests/basics/int_bytes_int64.py b/tests/basics/int_bytes_int64.py
new file mode 100644
index 00000000000..2ca87f20dee
--- /dev/null
+++ b/tests/basics/int_bytes_int64.py
@@ -0,0 +1,43 @@
+import sys
+
+# Depending on the port, the numbers in this test may be implemented as "small"
+# native 64 bit ints, arbitrary precision large ints, or large integers using 64-bit
+# long longs.
+
+try:
+    x = int.from_bytes(b"\x6f\xab\xcd\x12\x34\x56\x78\xfb", "big")
+except OverflowError:
+    print("SKIP")  # Port can't represent this size of integer at all
+    raise SystemExit
+
+print(hex(x))
+b = x.to_bytes(8, "little")
+print(b)
+print(x.to_bytes(8, "big"))
+
+# padding in output
+print(x.to_bytes(20, "little"))
+print(x.to_bytes(20, "big"))
+
+# check that extra zero bytes don't change the internal int value
+print(int.from_bytes(b + bytes(10), "little") == x)
+
+# can't write to a zero-length bytes object
+try:
+    x.to_bytes(0, "little")
+except OverflowError:
+    print("OverflowError")
+
+# or one that it too short
+try:
+    x.to_bytes(7, "big")
+except OverflowError:
+    print("OverflowError")
+
+# negative representations
+
+x = -x
+
+print(x.to_bytes(8, "little", signed=True))
+print(x.to_bytes(20, "big", signed=True))
+print(x.to_bytes(20, "little", signed=True))
diff --git a/tests/basics/int_bytes_intbig.py b/tests/basics/int_bytes_intbig.py
index e78f55de01f..6d3265ddb1d 100644
--- a/tests/basics/int_bytes_intbig.py
+++ b/tests/basics/int_bytes_intbig.py
@@ -2,11 +2,12 @@
 import skip_if
 skip_if.no_bigint()
 
-# CIRCUITPY-CHANGE: signed support
+import sys
+
 print((2**64).to_bytes(9, "little"))
-print((-2**64).to_bytes(9, "little", signed=True))
+print((-(2**64)).to_bytes(9, "little", signed=True))
 print((2**64).to_bytes(9, "big"))
-print((-2**64).to_bytes(9, "big", signed=True))
+print((-(2**64)).to_bytes(9, "big", signed=True))
 
 b = bytes(range(20))
 
@@ -17,22 +18,76 @@
 print(il.to_bytes(20, "little"))
 print(ib.to_bytes(20, "big"))
 
+# check padding comes out correctly
+print(il.to_bytes(40, "little"))
+print(ib.to_bytes(40, "big"))
+
 # check that extra zero bytes don't change the internal int value
 print(int.from_bytes(b + bytes(10), "little") == int.from_bytes(b, "little"))
 
-# CIRCUITPY-CHANGE: more tests
-# too small buffer should raise an error
+# can't write to a zero-length bytes object
 try:
-    (2**64).to_bytes(8, "little")
+    ib.to_bytes(0, "little")
 except OverflowError:
     print("OverflowError")
 
-# negative numbers should raise an error if signed=False
+# or one that is too short
 try:
-    (-2**64).to_bytes(9, "little")
+    ib.to_bytes(18, "big")
 except OverflowError:
     print("OverflowError")
+
+# including when signed
 try:
-    (-2**64).to_bytes(9, "little", signed=False)
+    ib.to_bytes(18, "big", signed=True)
 except OverflowError:
     print("OverflowError")
+
+# negative representations
+
+# negative numbers should raise an error if signed=False
+try:
+    (-(2**64)).to_bytes(9, "little", signed=False)
+except OverflowError:
+    print("OverflowError")
+
+
+print((-ib).to_bytes(20, "big", signed=True))
+print((ib * -ib).to_bytes(40, "big", signed=True))
+
+# cases where an additional byte is needed for sign bit
+
+MAX_U24 = (2**24) - 1
+MAX_U32 = (2**32) - 1
+MAX_U64 = (2**64) - 1
+
+for ib, nbytes in (
+    (-127, 1),
+    (255, 1),
+    (-255, 1),
+    (65535, 2),
+    (-65535, 2),
+    (-65534, 2),
+    (MAX_U24, 3),
+    (-MAX_U24, 3),
+    (1 - MAX_U24, 3),
+    (MAX_U32, 4),
+    (-MAX_U32, 4),
+    (1 - MAX_U32, 4),
+    (2 - MAX_U32, 4),
+    (MAX_U64, 8),
+    (-MAX_U64, 8),
+    (1 - MAX_U64, 8),
+    (2 - MAX_U64, 8),
+    (2 * MAX_U64, 8),
+    (-2 * MAX_U64, 8),
+):
+    print("ib", hex(ib), "nbytes", nbytes, ":")
+    for signed in False, True:
+        for endian in "little", "big":
+            for nbytes_offs in (-1, 0, 1):
+                try:
+                    as_bytes = ib.to_bytes(nbytes + nbytes_offs, endian, signed=signed)
+                except OverflowError:
+                    as_bytes = "OverflowError"
+                print(as_bytes, "signed", signed, "endian", endian, "nbytes_offs", nbytes_offs)
diff --git a/tests/basics/int_bytes_optional_args_cp311.py b/tests/basics/int_bytes_optional_args_cp311.py
new file mode 100644
index 00000000000..07fdcdd2821
--- /dev/null
+++ b/tests/basics/int_bytes_optional_args_cp311.py
@@ -0,0 +1,9 @@
+# Check optional byteorder argument (CPython 3.11+)
+print((10).to_bytes(1))
+print((100).to_bytes(10))
+print(int.from_bytes(b"\0\0\0\0\0\0\0\0\0\x01"))
+print(int.from_bytes(b"\x01\0"))
+
+# Check optional length argument (CPython 3.11+)
+print((10).to_bytes())
+print((100).to_bytes())
diff --git a/tests/basics/int_bytes_optional_args_cp311.py.exp b/tests/basics/int_bytes_optional_args_cp311.py.exp
new file mode 100644
index 00000000000..6dffa2577fc
--- /dev/null
+++ b/tests/basics/int_bytes_optional_args_cp311.py.exp
@@ -0,0 +1,6 @@
+b'\n'
+b'\x00\x00\x00\x00\x00\x00\x00\x00\x00d'
+1
+256
+b'\n'
+b'd'
diff --git a/tests/basics/io_buffered_writer.py b/tests/basics/io_buffered_writer.py
index 11df0324e24..3cfee0103f7 100644
--- a/tests/basics/io_buffered_writer.py
+++ b/tests/basics/io_buffered_writer.py
@@ -1,10 +1,10 @@
-import io
-
 try:
+    import io
+
     io.BytesIO
     io.BufferedWriter
-except AttributeError:
-    print("SKIP")
+except (AttributeError, ImportError):
+    print('SKIP')
     raise SystemExit
 
 bts = io.BytesIO()
@@ -28,3 +28,27 @@
 
 # hashing a BufferedWriter
 print(type(hash(buf)))
+
+# Test failing flush()
+class MyIO(io.IOBase):
+    def __init__(self):
+        self.count = 0
+
+    def write(self, buf):
+        self.count += 1
+        if self.count < 3:
+            return None
+        print("writing", buf)
+        return len(buf)
+
+
+buf = io.BufferedWriter(MyIO(), 8)
+
+buf.write(b"foobar")
+
+for _ in range(4):
+    try:
+        buf.flush()
+        print("flushed")
+    except OSError:
+        print("OSError")
diff --git a/tests/basics/io_buffered_writer.py.exp b/tests/basics/io_buffered_writer.py.exp
index 2209348f5af..d61eb148b45 100644
--- a/tests/basics/io_buffered_writer.py.exp
+++ b/tests/basics/io_buffered_writer.py.exp
@@ -4,3 +4,8 @@ b'foobarfoobar'
 b'foobarfoobar'
 b'foo'
 
+OSError
+OSError
+writing bytearray(b'foobar')
+flushed
+flushed
diff --git a/tests/basics/io_bytesio_cow.py b/tests/basics/io_bytesio_cow.py
index 2edb7136a96..543c12ad42a 100644
--- a/tests/basics/io_bytesio_cow.py
+++ b/tests/basics/io_bytesio_cow.py
@@ -1,6 +1,12 @@
 # Make sure that write operations on io.BytesIO don't
 # change original object it was constructed from.
-import io
+
+try:
+    import io
+except ImportError:
+    print("SKIP")
+    raise SystemExit
+
 b = b"foobar"
 
 a = io.BytesIO(b)
diff --git a/tests/basics/io_bytesio_ext.py b/tests/basics/io_bytesio_ext.py
index 4d4c60c1363..92e71517811 100644
--- a/tests/basics/io_bytesio_ext.py
+++ b/tests/basics/io_bytesio_ext.py
@@ -1,5 +1,11 @@
 # Extended stream operations on io.BytesIO
-import io
+
+try:
+    import io
+except ImportError:
+    print("SKIP")
+    raise SystemExit
+
 a = io.BytesIO(b"foobar")
 a.seek(10)
 print(a.read(10))
diff --git a/tests/basics/io_bytesio_ext2.py b/tests/basics/io_bytesio_ext2.py
index 414ac90a3b0..f60a6a9a604 100644
--- a/tests/basics/io_bytesio_ext2.py
+++ b/tests/basics/io_bytesio_ext2.py
@@ -1,4 +1,9 @@
-import io
+try:
+    import io
+except ImportError:
+    print("SKIP")
+    raise SystemExit
+
 a = io.BytesIO(b"foobar")
 try:
     a.seek(-10)
diff --git a/tests/basics/io_iobase.py b/tests/basics/io_iobase.py
index b2ee5cd63a6..31f2616310e 100644
--- a/tests/basics/io_iobase.py
+++ b/tests/basics/io_iobase.py
@@ -1,15 +1,17 @@
 import io
 try:
+    import io
+
     io.IOBase
-except AttributeError:
+except (AttributeError, ImportError):
     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))
+        # CPython and MicroPython pass in different types for buf (str vs bytearray)
+        print('write', len(buf))
         return len(buf)
 
-print("test", file=MyIO())
+print('test', file=MyIO())
diff --git a/tests/basics/io_stringio1.py b/tests/basics/io_stringio1.py
index 7d355930f5a..889e3ce6973 100644
--- a/tests/basics/io_stringio1.py
+++ b/tests/basics/io_stringio1.py
@@ -1,4 +1,9 @@
-import io
+try:
+    import io
+except ImportError:
+    print("SKIP")
+    raise SystemExit
+
 a = io.StringIO()
 print('io.StringIO' in repr(a))
 print(a.getvalue())
diff --git a/tests/basics/io_stringio_base.py b/tests/basics/io_stringio_base.py
index 0f65fb3fabc..c8890dab73a 100644
--- a/tests/basics/io_stringio_base.py
+++ b/tests/basics/io_stringio_base.py
@@ -1,7 +1,11 @@
 # Checks that an instance type inheriting from a native base that uses
 # MP_TYPE_FLAG_ITER_IS_STREAM will still have a getiter.
 
-import io
+try:
+    import io
+except ImportError:
+    print("SKIP")
+    raise SystemExit
 
 a = io.StringIO()
 a.write("hello\nworld\nmicro\npython\n")
diff --git a/tests/basics/io_stringio_with.py b/tests/basics/io_stringio_with.py
index a3aa6ec84e0..0155ad5382d 100644
--- a/tests/basics/io_stringio_with.py
+++ b/tests/basics/io_stringio_with.py
@@ -1,4 +1,9 @@
-import io
+try:
+    import io
+except ImportError:
+    print("SKIP")
+    raise SystemExit
+
 # test __enter__/__exit__
 with io.StringIO() as b:
     b.write("foo")
diff --git a/tests/basics/io_write_ext.py b/tests/basics/io_write_ext.py
index 79f7450954e..5af1de7a6c3 100644
--- a/tests/basics/io_write_ext.py
+++ b/tests/basics/io_write_ext.py
@@ -1,11 +1,12 @@
 # This tests extended (MicroPython-specific) form of write:
 # write(buf, len) and write(buf, offset, len)
-import io
 
 try:
+    import io
+
     io.BytesIO
-except AttributeError:
-    print("SKIP")
+except (AttributeError, ImportError):
+    print('SKIP')
     raise SystemExit
 
 buf = io.BytesIO()
diff --git a/tests/basics/lexer.py b/tests/basics/lexer.py
index 181d62db1aa..dfdc0b9900d 100644
--- a/tests/basics/lexer.py
+++ b/tests/basics/lexer.py
@@ -83,3 +83,19 @@ def a(x):
     exec(r"'\U0000000'")
 except SyntaxError:
     print("SyntaxError")
+
+# Properly formed integer literals
+print(eval("00"))
+# badly formed integer literals
+try:
+    eval("01")
+except SyntaxError:
+    print("SyntaxError")
+
+# Bytes 0-8 inclusive are not allowed in input stream.
+# Earlier CPython (eg 3.10.12) raises ValueError, later CPython (eg 3.11.14) raises SyntaxError.
+for invalid_byte_value in range(0, 10):
+    try:
+        print(eval(b"123" + bytes([invalid_byte_value])))
+    except (ValueError, SyntaxError):
+        print("byte {}: SyntaxError".format(invalid_byte_value))
diff --git a/tests/basics/list_pop.py b/tests/basics/list_pop.py
index 87ed456f851..58bcdd91e41 100644
--- a/tests/basics/list_pop.py
+++ b/tests/basics/list_pop.py
@@ -10,7 +10,7 @@
 else:
     raise AssertionError("No IndexError raised")
 
-# popping such that list storage shrinks (tests implementation detail of uPy)
+# popping such that list storage shrinks (tests implementation detail of MicroPython)
 l = list(range(20))
 for i in range(len(l)):
     l.pop()
diff --git a/tests/basics/module2.py b/tests/basics/module2.py
index a135601579c..d1dc18930f0 100644
--- a/tests/basics/module2.py
+++ b/tests/basics/module2.py
@@ -1,4 +1,4 @@
-# uPy behaviour only: builtin modules are read-only
+# MicroPython behaviour only: builtin modules are read-only
 import sys
 try:
     sys.x = 1
diff --git a/tests/basics/namedtuple1.py b/tests/basics/namedtuple1.py
index 362c60583ec..b9689b58423 100644
--- a/tests/basics/namedtuple1.py
+++ b/tests/basics/namedtuple1.py
@@ -21,6 +21,9 @@
 
     print(isinstance(t, tuple))
 
+    # a NamedTuple can be used as a tuple
+    print("(%d, %d)" % t)
+
     # Check tuple can compare equal to namedtuple with same elements
     print(t == (t[0], t[1]), (t[0], t[1]) == t)
 
diff --git a/tests/basics/nanbox_smallint.py b/tests/basics/nanbox_smallint.py
index b3a502e447e..9451ab32846 100644
--- a/tests/basics/nanbox_smallint.py
+++ b/tests/basics/nanbox_smallint.py
@@ -23,17 +23,17 @@
     raise SystemExit
 
 micropython.heap_lock()
-print(int("0x80000000"))
+print(int("0x80000000", 16))
 micropython.heap_unlock()
 
 # This is the most positive small integer.
 micropython.heap_lock()
-print(int("0x3fffffffffff"))
+print(int("0x3fffffffffff", 16))
 micropython.heap_unlock()
 
 # This is the most negative small integer.
 micropython.heap_lock()
-print(int("-0x3fffffffffff") - 1)
+print(int("-0x3fffffffffff", 16) - 1)
 micropython.heap_unlock()
 
 x = 1
diff --git a/tests/basics/parser.py b/tests/basics/parser.py
index 626b67ad7a9..6ae5f05ba45 100644
--- a/tests/basics/parser.py
+++ b/tests/basics/parser.py
@@ -7,7 +7,7 @@
     raise SystemExit
 
 # completely empty string
-# uPy and CPy differ for this case
+# MPy and CPy differ for this case
 #try:
 #    compile("", "stdin", "single")
 #except SyntaxError:
diff --git a/tests/basics/python34.py b/tests/basics/python34.py
index 922234d22db..3071b55eff8 100644
--- a/tests/basics/python34.py
+++ b/tests/basics/python34.py
@@ -28,7 +28,7 @@ def test_syntax(code):
 test_syntax("del ()") # can't delete empty tuple (in 3.6 we can)
 
 # from basics/sys1.py
-# uPy prints version 3.4
+# MicroPython prints version 3.4
 import sys
 print(sys.version[:3])
 print(sys.version_info[0], sys.version_info[1])
diff --git a/tests/basics/python36.py.exp b/tests/basics/python36.py.exp
deleted file mode 100644
index 4b65daafa18..00000000000
--- a/tests/basics/python36.py.exp
+++ /dev/null
@@ -1,5 +0,0 @@
-100000
-165
-65535
-123
-83
diff --git a/tests/basics/self_type_check.py b/tests/basics/self_type_check.py
index 3bd5b3eed60..5f6f6f2ca65 100644
--- a/tests/basics/self_type_check.py
+++ b/tests/basics/self_type_check.py
@@ -3,6 +3,14 @@
 import skip_if
 skip_if.board_in("gemma_m0", "trinket_m0")
 
+import sys
+
+# Minimal builds usually don't enable MICROPY_BUILTIN_METHOD_CHECK_SELF_ARG,
+# which is required for this test.
+if getattr(sys.implementation, "_build", None) == "minimal":
+    print("SKIP")
+    raise SystemExit
+
 list.append
 
 try:
diff --git a/tests/basics/slice_optimise.py b/tests/basics/slice_optimise.py
new file mode 100644
index 00000000000..f663e16b8c2
--- /dev/null
+++ b/tests/basics/slice_optimise.py
@@ -0,0 +1,23 @@
+# Test that the slice-on-stack optimisation does not break various uses of slice
+# (see MP_TYPE_FLAG_SUBSCR_ALLOWS_STACK_SLICE type option).
+#
+# Note: this test has a corresponding .py.exp file because hashing slice objects
+# was not allowed in CPython until 3.12.
+
+try:
+    from collections import OrderedDict
+except ImportError:
+    print("SKIP")
+    raise SystemExit
+
+# Attempt to index with a slice, error should contain the slice (failed key).
+try:
+    dict()[:]
+except KeyError as e:
+    print("KeyError", e.args)
+
+# Put a slice and another object into an OrderedDict, and retrieve them.
+x = OrderedDict()
+x[:"a"] = 1
+x["b"] = 2
+print(list(x.keys()), list(x.values()))
diff --git a/tests/basics/slice_optimise.py.exp b/tests/basics/slice_optimise.py.exp
new file mode 100644
index 00000000000..3fa59aae15a
--- /dev/null
+++ b/tests/basics/slice_optimise.py.exp
@@ -0,0 +1,2 @@
+KeyError (slice(None, None, None),)
+[slice(None, 'a', None), 'b'] [1, 2]
diff --git a/tests/basics/special_methods2.py.exp b/tests/basics/special_methods2.py.exp
deleted file mode 100644
index a9ae75be55c..00000000000
--- a/tests/basics/special_methods2.py.exp
+++ /dev/null
@@ -1,19 +0,0 @@
-__pos__ called
-__pos__ called
-__neg__ called
-__invert__ called
-__mul__ called
-__matmul__ called
-__truediv__ called
-__floordiv__ called
-__iadd__ called
-__isub__ called
-__mod__ called
-__pow__ called
-__or__ called
-__and__ called
-__xor__ called
-__lshift__ called
-__rshift__ called
-['a', 'b', 'c']
-False
diff --git a/tests/basics/string_encode_encoding_case.py b/tests/basics/string_encode_encoding_case.py
new file mode 100644
index 00000000000..813430dc2f0
--- /dev/null
+++ b/tests/basics/string_encode_encoding_case.py
@@ -0,0 +1,11 @@
+# Test that "UTF-8" is accepted as an encoding name, as in CPython.
+# See https://github.com/adafruit/circuitpython/issues/11580
+
+print(bytes("hi", "utf-8"))
+print(bytes("hi", "UTF-8"))
+print("hi".encode("UTF-8"))
+print(b"hi".decode("UTF-8"))
+try:
+    bytes("hi", "latin-1")
+except LookupError:
+    print("LookupError")
diff --git a/tests/basics/string_encode_encoding_case.py.exp b/tests/basics/string_encode_encoding_case.py.exp
new file mode 100644
index 00000000000..1411fda09c3
--- /dev/null
+++ b/tests/basics/string_encode_encoding_case.py.exp
@@ -0,0 +1,5 @@
+b'hi'
+b'hi'
+b'hi'
+hi
+LookupError
diff --git a/tests/basics/string_endswith.py b/tests/basics/string_endswith.py
index 683562d10c3..2b0a063988b 100644
--- a/tests/basics/string_endswith.py
+++ b/tests/basics/string_endswith.py
@@ -5,11 +5,28 @@
 print("foobar".endswith(""))
 print("foobar".endswith("foobarbaz"))
 
-#print("1foobar".startswith("foo", 1))
-#print("1foo".startswith("foo", 1))
-#print("1foo".startswith("1foo", 1))
-#print("1fo".startswith("foo", 1))
-#print("1fo".startswith("foo", 10))
+print("foobar".endswith("bar", 3))
+print("foobar".endswith("bar", 4))
+print("foobar".endswith("foo", 0, 3))
+print("foobar".endswith("foo", 0, 4))
+print("foobar".endswith("foo", 1, 3))
+print("foobar".endswith("foo", 1, 3))
+print("foobar".endswith("oo", 1, 3))
+print("foobar".endswith("o", 2, 3))
+print("foobar".endswith("o", 3, 3))
+print("foobar".endswith("o", 4, 3))
+
+print("foobar".endswith("bar", None, None))
+print("foobar".endswith("bar", None, 3))
+print("foobar".endswith("bar", 3, None))
+print("foobar".endswith("bar", 2, None))
+print("foobar".endswith("foo", None, 3))
+
+print("foobar".endswith(("bar", "foo")))
+print("foobar".endswith(("foo", "bar")))
+print("foobar".endswith(("foo", "bar1")))
+print("foobar".endswith(("bar", )))
+print("foobar".endswith(("foo", )))
 
 try:
     "foobar".endswith(1)
diff --git a/tests/basics/string_endswith_upy.py b/tests/basics/string_endswith_upy.py
deleted file mode 100644
index 06a4e71d2c9..00000000000
--- a/tests/basics/string_endswith_upy.py
+++ /dev/null
@@ -1,6 +0,0 @@
-# MicroPython doesn't support tuple argument
-
-try:
-    "foobar".endswith(("bar", "sth"))
-except TypeError:
-    print("TypeError")
diff --git a/tests/basics/string_endswith_upy.py.exp b/tests/basics/string_endswith_upy.py.exp
deleted file mode 100644
index 6002b71c56e..00000000000
--- a/tests/basics/string_endswith_upy.py.exp
+++ /dev/null
@@ -1 +0,0 @@
-TypeError
diff --git a/tests/basics/string_find.py b/tests/basics/string_find.py
index f9fcad3e579..f37064ad291 100644
--- a/tests/basics/string_find.py
+++ b/tests/basics/string_find.py
@@ -24,6 +24,7 @@
 print("aaaaaaaaaaa".find("bbb", 9, 2))
 
 try:
+    # Only works on bytes/bytearray.
     'abc'.find(1)
 except TypeError:
     print('TypeError')
diff --git a/tests/basics/string_format.py b/tests/basics/string_format.py
index e8600f58361..11e7836a73e 100644
--- a/tests/basics/string_format.py
+++ b/tests/basics/string_format.py
@@ -22,7 +22,17 @@ def test(fmt, *args):
 test("{:4x}", 123)
 test("{:4X}", 123)
 
+test("{:4,d}", 1)
+test("{:4_d}", 1)
+test("{:4_o}", 1)
+test("{:4_b}", 1)
+test("{:4_x}", 1)
+
 test("{:4,d}", 12345678)
+test("{:4_d}", 12345678)
+test("{:4_o}", 12345678)
+test("{:4_b}", 12345678)
+test("{:4_x}", 12345678)
 
 test("{:#4b}", 10)
 test("{:#4o}", 123)
diff --git a/tests/basics/string_format_intbig.py b/tests/basics/string_format_intbig.py
new file mode 100644
index 00000000000..a36c36752e7
--- /dev/null
+++ b/tests/basics/string_format_intbig.py
@@ -0,0 +1,15 @@
+# basic functionality test for {} format string using large integers
+
+
+def test(fmt, *args):
+    print("{:8s}".format(fmt) + ">" + fmt.format(*args) + "<")
+
+
+# Separator formatter
+
+test("{:,}", 123_456_789_012_345_678_901_234_567)
+test("{:,}", 23_456_789_012_345_678_901_234_567)
+test("{:,}", 3_456_789_012_345_678_901_234_567)
+test("{:,}", -123_456_789_012_345_678_901_234_567)
+test("{:,}", -23_456_789_012_345_678_901_234_567)
+test("{:,}", -3_456_789_012_345_678_901_234_567)
diff --git a/tests/basics/string_format_sep.py b/tests/basics/string_format_sep.py
new file mode 100644
index 00000000000..de131fdaf33
--- /dev/null
+++ b/tests/basics/string_format_sep.py
@@ -0,0 +1,9 @@
+try:
+    "%d" % 1
+except TypeError:
+    print("SKIP")
+    raise SystemExit
+
+for v in (0, 0x10, 0x1000, -0x10, -0x1000):
+    for sz in range(1, 12): print(("{:0%d,d}" % sz).format(v))
+    for sz in range(1, 12): print(("{:0%d_x}" % sz).format(v))
diff --git a/tests/basics/string_fstring.py b/tests/basics/string_fstring.py
index 42d093b37b5..03e2d90a8f7 100644
--- a/tests/basics/string_fstring.py
+++ b/tests/basics/string_fstring.py
@@ -31,6 +31,8 @@ def foo(a, b):
 
 # PEP-0498 specifies that handling of double braces '{{' or '}}' should
 # behave like str.format.
+print(f'{{')
+print(f'}}')
 print(f'{{}}')
 print(f'{{{4*10}}}', '{40}')
 
@@ -65,3 +67,21 @@ def foo(a, b):
 # Still allow ! in expressions.
 print(f"{'1' if a != '456' else '0'!r:8s}")
 print(f"{'1' if a != '456' else '0'!s:8s}")
+
+# Concatenation of adjacent f-strings.
+print(f"" f"")
+print(f"a" f"b")
+print(f"{x}" f"{y}")
+print(
+    f"a{x}b---------------------------------"
+    f"cd---------------------------------"
+    f"e{y}f---------------------------------"
+)
+
+# Raw f-strings.
+print(rf"\r\a\w {'f'} \s\t\r\i\n\g")
+print(fr"\r{x}")
+
+# Format specifiers with nested replacement fields
+radix = "x"
+print(f"{314:{radix}}")
diff --git a/tests/basics/string_fstring_debug.py.exp b/tests/basics/string_fstring_debug.py.exp
deleted file mode 100644
index f0309e1c98a..00000000000
--- a/tests/basics/string_fstring_debug.py.exp
+++ /dev/null
@@ -1,9 +0,0 @@
-x=1
-x=00000001
-a x=1 b 2 c
-a x=00000001 b 2 c
-a f() + g("foo") + h()=15 b
-a f() + g("foo") + h()=0000000f b
-a 1,=(1,) b
-a x,y,=(1, 2) b
-a x,1=(1, 1) b
diff --git a/tests/basics/string_fstring_nested.py b/tests/basics/string_fstring_nested.py
new file mode 100644
index 00000000000..82de0bf6470
--- /dev/null
+++ b/tests/basics/string_fstring_nested.py
@@ -0,0 +1,9 @@
+# Test nesting of f-strings within f-strings.
+
+x = 1
+
+# 2-level nesting, with padding.
+print(f"a{f'b{x:2}c':>5}d")
+
+# 4-level nesting using the different styles of quotes.
+print(f"""a{f'''b{f"c{f'd{x}e'}f"}g'''}h""")
diff --git a/tests/basics/string_fstring_nested_py312.py b/tests/basics/string_fstring_nested_py312.py
new file mode 100644
index 00000000000..aa731b1637d
--- /dev/null
+++ b/tests/basics/string_fstring_nested_py312.py
@@ -0,0 +1,7 @@
+# Test nesting of f-strings within f-strings.
+# These test rely on Python 3.12+ to use the same quote style for nesting.
+
+x = 1
+
+# 8-level nesting using the same quote style.
+print(f"a{f"b{f"c{f"d{f"e{f"f{f"g{f"h{x}i"}j"}k"}l"}m"}n"}o"}p")
diff --git a/tests/basics/string_fstring_nested_py312.py.exp b/tests/basics/string_fstring_nested_py312.py.exp
new file mode 100644
index 00000000000..1d624933dff
--- /dev/null
+++ b/tests/basics/string_fstring_nested_py312.py.exp
@@ -0,0 +1 @@
+abcdefgh1ijklmnop
diff --git a/tests/basics/string_index.py b/tests/basics/string_index.py
index 31f6900e6c1..328f2dff54c 100644
--- a/tests/basics/string_index.py
+++ b/tests/basics/string_index.py
@@ -76,3 +76,9 @@
     print("Raised ValueError")
 else:
     print("Did not raise ValueError")
+
+try:
+    # Only works on bytes/bytearray.
+    'abc'.index(1)
+except TypeError:
+    print('TypeError')
diff --git a/tests/basics/string_module_tstring.py b/tests/basics/string_module_tstring.py
new file mode 100644
index 00000000000..83809926926
--- /dev/null
+++ b/tests/basics/string_module_tstring.py
@@ -0,0 +1,6 @@
+# Test basic templatelib functionality.
+# This test requires t-strings support.
+
+from string.templatelib import Template
+
+print("templatelib", isinstance(t"hi", Template))
diff --git a/tests/basics/string_module_tstring.py.exp b/tests/basics/string_module_tstring.py.exp
new file mode 100644
index 00000000000..26dba98f403
--- /dev/null
+++ b/tests/basics/string_module_tstring.py.exp
@@ -0,0 +1 @@
+templatelib True
diff --git a/tests/basics/string_startswith.py b/tests/basics/string_startswith.py
index e63ae3c1866..eefdea82198 100644
--- a/tests/basics/string_startswith.py
+++ b/tests/basics/string_startswith.py
@@ -10,6 +10,25 @@
 print("1fo".startswith("foo", 1))
 print("1fo".startswith("foo", 10))
 
+print("1foobar".startswith("foo", 1, 5))
+print("1foobar".startswith("foo", 1, 4))
+print("1foobar".startswith("foo", 1, 3))
+print("1foobar".startswith("oo", 2, 4))
+print("1foobar".startswith("o", 3, 4))
+print("1foobar".startswith("o", 4, 4))
+print("1foobar".startswith("o", 5, 4))
+
+print("foobar".startswith("foo", None, None))
+print("foobar".startswith("foo", None, 3))
+print("foobar".startswith("foo", None, 2))
+print("foobar".startswith("bar", 3, None))
+
+
+print("foobar".startswith(("foo", "sth")))
+print("foobar".startswith(("sth", "foo")))
+print("foobar".startswith(("sth", "foo2")))
+print("foobar".startswith(("foo", )))
+
 try:
     "foobar".startswith(1)
 except TypeError:
diff --git a/tests/basics/string_startswith_upy.py b/tests/basics/string_startswith_upy.py
deleted file mode 100644
index 9ea1796c218..00000000000
--- a/tests/basics/string_startswith_upy.py
+++ /dev/null
@@ -1,6 +0,0 @@
-# MicroPython doesn't support tuple argument
-
-try:
-    "foobar".startswith(("foo", "sth"))
-except TypeError:
-    print("TypeError")
diff --git a/tests/basics/string_startswith_upy.py.exp b/tests/basics/string_startswith_upy.py.exp
deleted file mode 100644
index 6002b71c56e..00000000000
--- a/tests/basics/string_startswith_upy.py.exp
+++ /dev/null
@@ -1 +0,0 @@
-TypeError
diff --git a/tests/basics/string_tstring_basic.py b/tests/basics/string_tstring_basic.py
new file mode 100644
index 00000000000..aa9de327b59
--- /dev/null
+++ b/tests/basics/string_tstring_basic.py
@@ -0,0 +1,339 @@
+from string.templatelib import Template, Interpolation
+
+print("=== Basic functionality ===")
+t = t"Hello World"
+print(type(t).__name__)
+
+name = "World"
+t2 = t"Hello {name}"
+print(f"Strings: {t2.strings}")
+print(f"Value: {t2.interpolations[0].value}")
+print(f"str(): {str(t2)}")
+
+t_raw = rt"Path: C:\test\{name}"
+print(f"Raw: '{t_raw.strings[0]}'")
+
+t_tr = tr"Path: C:\test\{name}"
+print(f"tr: '{t_tr.strings[0]}'")
+
+print("\n=== Parser tests ===")
+data = {"a": {"b": [1, 2, 3]}}
+t_complex = t"{data['a']['b'][0]}"
+print(f"Complex: {str(t_complex)}")
+
+print(f"None: {str(t'{None}')}")
+print(f"True: {str(t'{True}')}")
+print(f"False: {str(t'{False}')}")
+print(f"Ellipsis: {str(t'{...}')}")
+
+obj = type('Obj', (), {
+    '__getattr__': lambda s, n: s,
+    '__getitem__': lambda s, k: s,
+    '__call__': lambda s, *a: 42,
+    '__str__': lambda s: "42"
+})()
+print(f"Deep nest: {str(t'{obj.a.b[0].c()}')}")
+
+print("\n=== Conversions and formatting ===")
+val = {"key": "value"}
+print(f"repr: {str(t'{val!r}')}")
+print(f"str: {str(t'{val!s}')}")
+# print(f"ascii: {str(t'{val!a}')}")
+
+print(f"Width: '{str(t'{42:10d}')}'")
+print(f"Precision: {str(t'{3.14159:.2f}')}")
+
+x = 42
+t_debug = t"{x=}"
+assert t_debug.strings == ("x=", "")
+assert t_debug.interpolations[0].expression == "x"
+assert t_debug.interpolations[0].conversion == "r"
+assert t_debug.interpolations[0].value == 42
+print(f"Debug: {str(t_debug)}")
+
+y = 10
+t_debug2 = t"{x + y=}"
+assert t_debug2.strings == ("x + y=", "")
+assert t_debug2.interpolations[0].expression == "x + y"
+assert t_debug2.interpolations[0].conversion == "r"
+assert t_debug2.interpolations[0].value == 52
+
+pi = 3.14159
+t_debug3 = t"{pi=:.2f}"
+assert t_debug3.strings == ("pi=", "")
+assert t_debug3.interpolations[0].expression == "pi"
+assert t_debug3.interpolations[0].conversion is None
+assert t_debug3.interpolations[0].format_spec == ".2f"
+assert t_debug3.interpolations[0].value == 3.14159
+
+print("\n=== Constructor tests ===")
+t_empty = Template()
+print(f"Empty: {t_empty.strings}")
+
+t_single = Template("single")
+print(f"Single: {t_single.strings}")
+
+t_multi = Template("a", "b", "c")
+print(f"Multi: {t_multi.strings}")
+
+i1 = Interpolation(1, "x")
+i2 = Interpolation(2, "y")
+t_mixed = Template("start", i1, "middle", i2, "end")
+print(f"Mixed: strings={t_mixed.strings}, values={t_mixed.values}")
+
+print("\n=== Operations ===")
+t1 = t"Hello"
+t2 = t" World"
+t_concat = t1 + t2
+print(f"Concat: '{str(t_concat)}'")
+
+items = list(t"a{1}b{2}c")
+print(f"Iterator: {[type(x).__name__ for x in items]}")
+
+t_attr = t"test{42}"
+print(f"strings attr: {t_attr.strings}")
+print(f"interpolations attr: {len(t_attr.interpolations)}")
+print(f"values attr: {t_attr.values}")
+
+print(f"repr: {repr(t2)[:50]}...")
+
+print("\n=== Escaped braces evaluation ===")
+t_escaped = Template("{", Interpolation(42, "x"), "}", Interpolation(42, "x"), "{{", Interpolation(42, "x"), "}}")
+print(f"Escaped eval: '{str(t_escaped)}'")
+
+t_braces = Template("{{hello}}", Interpolation(1, "a"), " {", Interpolation(2, "b"), "} ", Interpolation(3, "c"), "{{world}}")
+print(f"Braces in strings: '{str(t_braces)}'")
+
+print("\n=== Memory stress test ===")
+for n in [10, 20, 30]:
+    args = []
+    for i in range(n):
+        args.append("s")
+        args.append(Interpolation(i, f"var{i}"))
+    args.append("s")
+    t_mem = Template(*args)
+    result = str(t_mem)
+    print(f"Memory test [{n}]: {len(result)} chars")
+
+large_args = []
+for i in range(20):
+    large_args.append("")
+    large_args.append(Interpolation(i, f"v{i}"))
+large_args.append("")
+t_large = Template(*large_args)
+print(f"Large values: {len(t_large.values)} values")
+
+print("\n=== Nested quotes and braces tests ===")
+t_nested1 = t"{"{}"}"
+print(f"Nested quotes 1: {str(t_nested1)}")
+print(f"  Value: {t_nested1.interpolations[0].value}")
+print(f"  Expression: {t_nested1.interpolations[0].expression}")
+
+t_nested2 = t"{'hello'}"
+print(f"Nested quotes 2: {str(t_nested2)}")
+print(f"  Value: {t_nested2.interpolations[0].value}")
+
+t_nested3 = t'{"world"}'
+print(f"Nested quotes 3: {str(t_nested3)}")
+print(f"  Value: {t_nested3.interpolations[0].value}")
+
+t_nested4 = t"{['a', 'b', 'c'][1]}"
+print(f"Nested quotes 4: {str(t_nested4)}")
+print(f"  Value: {t_nested4.interpolations[0].value}")
+
+d = {"key": "value", "x": 123}
+t_nested5 = t"{d['key']}"
+print(f"Nested quotes 5: {str(t_nested5)}")
+print(f"  Value: {t_nested5.interpolations[0].value}")
+
+t_escaped1 = t'{{""}}'
+print(f"Escaped braces 1: {str(t_escaped1)}")
+print(f"  Strings: {t_escaped1.strings}")
+
+t_escaped2 = t"{{}}}}"
+print(f"Escaped braces 2: {str(t_escaped2)}")
+print(f"  Strings: {t_escaped2.strings}")
+
+x = "test"
+t_mixed = t"{{before}} {x} {{after}}"
+print(f"Mixed escaped: {str(t_mixed)}")
+print(f"  Strings: {t_mixed.strings}")
+print(f"  Value: {t_mixed.interpolations[0].value}")
+
+t_escape = t"{'\n\t'}"
+print(f"Escape sequences: {str(t_escape)}")
+print(f"  Value repr: {repr(t_escape.interpolations[0].value)}")
+
+inner = "{}"
+t_nested_expr = t"{inner}"
+print(f"Nested expr: {str(t_nested_expr)}")
+print(f"  Value: {t_nested_expr.interpolations[0].value}")
+
+print("\n=== Interpolation attribute tests ===")
+i_basic = Interpolation(42, "x")
+print(f"Basic conversion: {i_basic.conversion}")
+# Put in quotes to make empty string visible.
+print(f"Basic format_spec: '{i_basic.format_spec}'")
+
+i_with_conv = Interpolation(42, "x", "s")
+print(f"With conversion: {i_with_conv.conversion}")
+
+i_with_fmt = Interpolation(42, "x", None, ":>10")
+print(f"With format_spec: {i_with_fmt.format_spec}")
+
+i_full = Interpolation(42, "x", "r", ":>10")
+print(f"Full conversion: {i_full.conversion}")
+print(f"Full format_spec: {i_full.format_spec}")
+
+t_conv = t"{42!s}"
+print(f"Template conversion: {t_conv.interpolations[0].conversion}")
+
+t_fmt = t"{42:>10}"
+print(f"Template format_spec: {t_fmt.interpolations[0].format_spec}")
+
+t_both = t"{42!r:>10}"
+print(f"Both conversion: {t_both.interpolations[0].conversion}")
+print(f"Both format_spec: {t_both.interpolations[0].format_spec}")
+
+print("\n=== Escape sequence tests ===")
+print(repr(t"Line1\nLine2"))
+print(repr(t"Path\\to\\file"))
+print(repr(t"It\'s working"))
+print(repr(t"She said \"Hello\""))
+print(repr(t"Bell\a"))
+print(repr(t"Back\bspace"))
+print(repr(t"Tab\there"))
+print(repr(t"Vertical\vtab"))
+print(repr(t"Form\ffeed"))
+print(repr(t"Carriage\rreturn"))
+
+# Valid hex escapes
+print(repr(t"\x41"))
+print(repr(t"\x7F"))
+
+# Valid octal escapes
+print(repr(t"\0"))
+print(repr(t"\7"))
+print(repr(t"\77"))
+print(repr(t"\101"))
+
+print(repr(t"\1a"))
+print(repr(t"\123c"))
+
+# Line continuation
+print(repr(t"First \
+second"))
+print(repr(t"One\
+Two\
+Three"))
+
+# Multiple escapes
+print(repr(t"\n\t\r"))
+
+# Raw strings
+print(repr(rt"\n\t\x41"))
+print(repr(rt"C:\new\test"))
+
+# Triple quoted strings
+print(repr(t"""\n\t\x41"""))
+print(repr(rt"""\n\t\x41"""))
+
+print("\n=== Triple quote edge cases ===")
+doc = '''This is a
+multi-line
+docstring'''
+result1 = t"""Documentation:
+{doc}
+End of doc"""
+print(f"Triple in interpolation: {str(result1)}")
+print(f"   Value: {repr(result1.interpolations[0].value)}")
+
+data = {
+    "users": [
+        {"name": "Alice", "msg": 'Say "Hello"'},
+        {"name": "Bob", "msg": "It's great!"}
+    ]
+}
+complex_nested = t"""Users:
+{data['users'][0]['name']}: {data['users'][0]['msg']}
+{data['users'][1]['name']}: {data['users'][1]['msg']}"""
+print(f"Complex nested: {str(complex_nested)}")
+print(f"   Values: {complex_nested.values}")
+
+import os
+path_sep = os.sep
+raw_with_interp = rt"""Path: C:\Users\{path_sep}Documents
+Raw newline: \n
+Raw tab: \t"""
+print(f"Raw with interpolation: {str(raw_with_interp)}")
+print(f"   String 0 repr: {repr(raw_with_interp.strings[0])}")
+
+long_line = "x" * 50
+long_triple = t"""Start
+{long_line}
+End"""
+print(f"Long line: strings={long_triple.strings}")
+print(f"   Value length: {len(long_triple.values[0])}")
+
+inner = t"inner {42}"
+outer = t"""Outer template:
+{inner}
+End"""
+print(f"Nested templates: {str(outer)}")
+print(f"   Inner value: {outer.values[0]}")
+
+formatted = t"""Math constants:
+Pi: {314:.2f}
+E: {271:.1e}
+Sqrt(2): {141:.0f}"""
+print(f"Formatted values: {repr(formatted)}")
+print(f"    Interpolation count: {len(formatted.interpolations)}")
+print(f"    Format specs: {[i.format_spec for i in formatted.interpolations]}")
+
+x, y, z = 1, 2, 3
+debug_complex = t"""Debug info:
+{x + y=} {x * y * z=} {x < y < z=}"""
+print(f"Debug complex: {repr(debug_complex)}")
+print(f"    Expressions: {[i.expression for i in debug_complex.interpolations]}")
+
+part1 = t"""Part 1
+with newline"""
+part2 = t'''Part 2
+also multiline'''
+concatenated = part1 + part2
+print(f"Concatenated triple: {repr(concatenated)}")
+print(f"    Strings: {concatenated.strings}")
+
+print("\n=== PEP 701 brace compliance ===")
+t_brace1 = t"{{"
+print(f"Escaped {{{{: {t_brace1.strings}")
+assert t_brace1.strings == ('{',)
+
+t_brace2 = t"}}"
+print(f"Escaped }}}}: {t_brace2.strings}")
+assert t_brace2.strings == ('}',)
+
+t_brace3 = t"test{{escape}}here"
+print(f"Mixed: {t_brace3.strings}")
+assert t_brace3.strings == ('test{escape}here',)
+
+print("\n=== Format spec scope resolution ===")
+def test_format_scope():
+    width = 10
+    x = 42
+    t_scope = t"{x:{width}}"
+    print(f"Local vars: width={width}, x={x}")
+    print(f"Format spec: {t_scope.interpolations[0].format_spec}")
+    return t_scope.interpolations[0].format_spec == '10'
+
+result = test_format_scope()
+print(f"Scope test: {'PASS' if result else 'FAIL'}")
+assert result, "Format spec scope resolution failed"
+
+precision = 2
+value = 3.14159
+t_prec = t"{value:.{precision}f}"
+print(f"Precision: format_spec={t_prec.interpolations[0].format_spec}")
+assert t_prec.interpolations[0].format_spec == '.2f'
+
+print("\nBasic tests completed!")
diff --git a/tests/basics/string_tstring_basic.py.exp b/tests/basics/string_tstring_basic.py.exp
new file mode 100644
index 00000000000..60affaad499
--- /dev/null
+++ b/tests/basics/string_tstring_basic.py.exp
@@ -0,0 +1,141 @@
+=== Basic functionality ===
+Template
+Strings: ('Hello ', '')
+Value: World
+str(): Template(strings=('Hello ', ''), interpolations=(Interpolation('World', 'name', None, ''),))
+Raw: 'Path: C:\test\'
+tr: 'Path: C:\test\'
+
+=== Parser tests ===
+Complex: Template(strings=('', ''), interpolations=(Interpolation(1, "data['a']['b'][0]", None, ''),))
+None: Template(strings=('', ''), interpolations=(Interpolation(None, 'None', None, ''),))
+True: Template(strings=('', ''), interpolations=(Interpolation(True, 'True', None, ''),))
+False: Template(strings=('', ''), interpolations=(Interpolation(False, 'False', None, ''),))
+Ellipsis: Template(strings=('', ''), interpolations=(Interpolation(Ellipsis, '...', None, ''),))
+Deep nest: Template(strings=('', ''), interpolations=(Interpolation(42, 'obj.a.b[0].c()', None, ''),))
+
+=== Conversions and formatting ===
+repr: Template(strings=('', ''), interpolations=(Interpolation({'key': 'value'}, 'val', 'r', ''),))
+str: Template(strings=('', ''), interpolations=(Interpolation({'key': 'value'}, 'val', 's', ''),))
+Width: 'Template(strings=('', ''), interpolations=(Interpolation(42, '42', None, '10d'),))'
+Precision: Template(strings=('', ''), interpolations=(Interpolation(3.14159, '3.14159', None, '.2f'),))
+Debug: Template(strings=('x=', ''), interpolations=(Interpolation(42, 'x', 'r', ''),))
+
+=== Constructor tests ===
+Empty: ('',)
+Single: ('single',)
+Multi: ('abc',)
+Mixed: strings=('start', 'middle', 'end'), values=(1, 2)
+
+=== Operations ===
+Concat: 'Template(strings=('Hello World',), interpolations=())'
+Iterator: ['str', 'Interpolation', 'str', 'Interpolation', 'str']
+strings attr: ('test', '')
+interpolations attr: 1
+values attr: (42,)
+repr: Template(strings=(' World',), interpolations=())...
+
+=== Escaped braces evaluation ===
+Escaped eval: 'Template(strings=('{', '}', '{{', '}}'), interpolations=(Interpolation(42, 'x', None, ''), Interpolation(42, 'x', None, ''), Interpolation(42, 'x', None, '')))'
+Braces in strings: 'Template(strings=('{{hello}}', ' {', '} ', '{{world}}'), interpolations=(Interpolation(1, 'a', None, ''), Interpolation(2, 'b', None, ''), Interpolation(3, 'c', None, '')))'
+
+=== Memory stress test ===
+Memory test [10]: 450 chars
+Memory test [20]: 880 chars
+Memory test [30]: 1310 chars
+Large values: 20 values
+
+=== Nested quotes and braces tests ===
+Nested quotes 1: Template(strings=('', ''), interpolations=(Interpolation('{}', '"{}"', None, ''),))
+  Value: {}
+  Expression: "{}"
+Nested quotes 2: Template(strings=('', ''), interpolations=(Interpolation('hello', "'hello'", None, ''),))
+  Value: hello
+Nested quotes 3: Template(strings=('', ''), interpolations=(Interpolation('world', '"world"', None, ''),))
+  Value: world
+Nested quotes 4: Template(strings=('', ''), interpolations=(Interpolation('b', "['a', 'b', 'c'][1]", None, ''),))
+  Value: b
+Nested quotes 5: Template(strings=('', ''), interpolations=(Interpolation('value', "d['key']", None, ''),))
+  Value: value
+Escaped braces 1: Template(strings=('{""}',), interpolations=())
+  Strings: ('{""}',)
+Escaped braces 2: Template(strings=('{}}',), interpolations=())
+  Strings: ('{}}',)
+Mixed escaped: Template(strings=('{before} ', ' {after}'), interpolations=(Interpolation('test', 'x', None, ''),))
+  Strings: ('{before} ', ' {after}')
+  Value: test
+Escape sequences: Template(strings=('', ''), interpolations=(Interpolation('\n\t', "'\\n\\t'", None, ''),))
+  Value repr: '\n\t'
+Nested expr: Template(strings=('', ''), interpolations=(Interpolation('{}', 'inner', None, ''),))
+  Value: {}
+
+=== Interpolation attribute tests ===
+Basic conversion: None
+Basic format_spec: ''
+With conversion: s
+With format_spec: :>10
+Full conversion: r
+Full format_spec: :>10
+Template conversion: s
+Template format_spec: >10
+Both conversion: r
+Both format_spec: >10
+
+=== Escape sequence tests ===
+Template(strings=('Line1\nLine2',), interpolations=())
+Template(strings=('Path\\to\\file',), interpolations=())
+Template(strings=("It's working",), interpolations=())
+Template(strings=('She said "Hello"',), interpolations=())
+Template(strings=('Bell\x07',), interpolations=())
+Template(strings=('Back\x08space',), interpolations=())
+Template(strings=('Tab\there',), interpolations=())
+Template(strings=('Vertical\x0btab',), interpolations=())
+Template(strings=('Form\x0cfeed',), interpolations=())
+Template(strings=('Carriage\rreturn',), interpolations=())
+Template(strings=('A',), interpolations=())
+Template(strings=('\x7f',), interpolations=())
+Template(strings=('\x00',), interpolations=())
+Template(strings=('\x07',), interpolations=())
+Template(strings=('?',), interpolations=())
+Template(strings=('A',), interpolations=())
+Template(strings=('\x01a',), interpolations=())
+Template(strings=('Sc',), interpolations=())
+Template(strings=('First second',), interpolations=())
+Template(strings=('OneTwoThree',), interpolations=())
+Template(strings=('\n\t\r',), interpolations=())
+Template(strings=('\\n\\t\\x41',), interpolations=())
+Template(strings=('C:\\new\\test',), interpolations=())
+Template(strings=('\n\tA',), interpolations=())
+Template(strings=('\\n\\t\\x41',), interpolations=())
+
+=== Triple quote edge cases ===
+Triple in interpolation: Template(strings=('Documentation:\n', '\nEnd of doc'), interpolations=(Interpolation('This is a\nmulti-line\ndocstring', 'doc', None, ''),))
+   Value: 'This is a\nmulti-line\ndocstring'
+Complex nested: Template(strings=('Users:\n', ': ', '\n', ': ', ''), interpolations=(Interpolation('Alice', "data['users'][0]['name']", None, ''), Interpolation('Say "Hello"', "data['users'][0]['msg']", None, ''), Interpolation('Bob', "data['users'][1]['name']", None, ''), Interpolation("It's great!", "data['users'][1]['msg']", None, '')))
+   Values: ('Alice', 'Say "Hello"', 'Bob', "It's great!")
+Raw with interpolation: Template(strings=('Path: C:\\Users\\', 'Documents\nRaw newline: \\n\nRaw tab: \\t'), interpolations=(Interpolation('/', 'path_sep', None, ''),))
+   String 0 repr: 'Path: C:\\Users\\'
+Long line: strings=('Start\n', '\nEnd')
+   Value length: 50
+Nested templates: Template(strings=('Outer template:\n', '\nEnd'), interpolations=(Interpolation(Template(strings=('inner ', ''), interpolations=(Interpolation(42, '42', None, ''),)), 'inner', None, ''),))
+   Inner value: Template(strings=('inner ', ''), interpolations=(Interpolation(42, '42', None, ''),))
+Formatted values: Template(strings=('Math constants:\nPi: ', '\nE: ', '\nSqrt(2): ', ''), interpolations=(Interpolation(314, '314', None, '.2f'), Interpolation(271, '271', None, '.1e'), Interpolation(141, '141', None, '.0f')))
+    Interpolation count: 3
+    Format specs: ['.2f', '.1e', '.0f']
+Debug complex: Template(strings=('Debug info:\nx + y=', ' x * y * z=', ' x < y < z=', ''), interpolations=(Interpolation(3, 'x + y', 'r', ''), Interpolation(6, 'x * y * z', 'r', ''), Interpolation(True, 'x < y < z', 'r', '')))
+    Expressions: ['x + y', 'x * y * z', 'x < y < z']
+Concatenated triple: Template(strings=('Part 1\nwith newlinePart 2\nalso multiline',), interpolations=())
+    Strings: ('Part 1\nwith newlinePart 2\nalso multiline',)
+
+=== PEP 701 brace compliance ===
+Escaped {{: ('{',)
+Escaped }}: ('}',)
+Mixed: ('test{escape}here',)
+
+=== Format spec scope resolution ===
+Local vars: width=10, x=42
+Format spec: 10
+Scope test: PASS
+Precision: format_spec=.2f
+
+Basic tests completed!
diff --git a/tests/basics/string_tstring_basic1.py b/tests/basics/string_tstring_basic1.py
new file mode 100644
index 00000000000..89ee3e0d2d4
--- /dev/null
+++ b/tests/basics/string_tstring_basic1.py
@@ -0,0 +1,131 @@
+print("=== Parser error tests ===")
+try:
+    exec('t_empty = t"{}"')
+    print(f"Empty expr: {t_empty.interpolations[0].value}")
+except SyntaxError as e:
+    print(f"Empty expr: SyntaxError - {e}")
+
+# Whitespace in expression (Python semantics are to strip trailing)
+t_ws = t"{ 42 }"
+print(f"Whitespace: {str(t_ws)}")
+
+print("\n=== Error cases ===")
+try:
+    exec('t"{@}"')
+except SyntaxError:
+    print("Invalid syntax: SyntaxError")
+
+try:
+    long_expr = "x" * 10001
+    exec(f't"{{{long_expr}}}"')
+except (ValueError, SyntaxError, RuntimeError, NameError):
+    print("Long expr: Error")
+
+try:
+    exec('t"hello" "world"')
+except SyntaxError:
+    print("Mixed concat: SyntaxError")
+
+try:
+    exec('bt"test"')
+except SyntaxError:
+    print("bt prefix: SyntaxError")
+
+print("\n=== Escape sequence coverage tests ===")
+
+def expect_invalid_escape(label, expr):
+    try:
+        eval(expr)
+    except SyntaxError:
+        print(f"{label}: SyntaxError")
+    else:
+        print(f"{label}: ERROR (expected SyntaxError)")
+
+# Deprecated escape sequences (CPython warns, MicroPython accepts as literal)
+print(repr(t"\8"))
+print(repr(t"\9"))
+
+# Unknown escape chars
+print(repr(t"\z"))
+print(repr(t"\k"))
+
+# Invalid escapes
+expect_invalid_escape("Invalid \\x escape", 't"\\xGG"')
+expect_invalid_escape("Invalid \\u escape", 't"\\uGGGG"')
+expect_invalid_escape("Invalid \\U escape", 't"\\UGGGGGGGG"')
+
+# Unicode escapes (display format differs)
+print(repr(t"\x00\x01\xFF"))
+print(repr(t"\u0041"))
+print(repr(t"\u03B1"))
+print(repr(t"\u2764"))
+print(repr(t"\U00000041"))
+print(repr(t"\U0001F600"))
+print(repr(t"\x41\u0042\103"))
+
+# Unicode in triple-quoted strings
+unicode_test = t"""Unicode test:
+Emoji: {'\U0001f40d'}
+Special: {'\u03b1 \u03b2 \u03b3'}"""
+print(f"Unicode: {str(unicode_test)}")
+
+print("\n=== Trailing whitespace preservation (PEP 750) ===")
+x = 42
+tmpl_trail = t"{x   }"
+expr = tmpl_trail.interpolations[0].expression
+print(f"Expression with trailing spaces: |{expr}|")
+assert expr == "x", f"Expected 'x' but got '{expr}'"
+assert len(expr) == 1, f"Expected length 1 but got {len(expr)}"
+
+tmpl_both = t"{   x   }"
+expr2 = tmpl_both.interpolations[0].expression
+print(f"Expression with both spaces: |{expr2}|")
+assert expr2 == "   x", f"Expected '   x' but got '{expr2}'"
+assert len(expr2) == 4, f"Expected length 4 but got {len(expr2)}"
+
+tmpl_lead = t"{   x}"
+expr3 = tmpl_lead.interpolations[0].expression
+print(f"Expression with leading spaces: |{expr3}|")
+assert expr3 == "   x", f"Expected '   x' but got '{expr3}'"
+
+# Debug specifiers: leading space preserved, trailing space stripped from expression
+# PEP 750: "Whitespace is preserved in the debug specifier" (in strings part)
+z = 99
+t_debug4 = t"{z =}"
+assert t_debug4.strings == ("z =", "")
+assert t_debug4.interpolations[0].expression == "z"  # Trailing space stripped
+assert t_debug4.interpolations[0].conversion == "r"
+
+t_debug5 = t"{ z=}"
+assert t_debug5.strings == (" z=", "")
+assert t_debug5.interpolations[0].expression == " z"  # Leading space preserved
+assert t_debug5.interpolations[0].conversion == "r"
+
+t_debug6 = t"{ z =}"
+assert t_debug6.strings == (" z =", "")
+assert t_debug6.interpolations[0].expression == " z"  # Leading preserved, trailing stripped
+assert t_debug6.interpolations[0].conversion == "r"
+
+print("Trailing whitespace: PASS")
+
+print("\n=== Error message tests ===")
+try:
+    exec('t"}"')
+except SyntaxError:
+    print("Lone }} rejected (correct)")
+
+try:
+    exec('t"{"')
+except SyntaxError:
+    print("Unterminated {{ rejected (correct)")
+
+print("\n=== Triple quote empty interpolation ===")
+try:
+    exec('''empty_interp = t"""Start
+{}
+End"""''')
+    print(f"Empty interpolation: {str(empty_interp)}")
+except Exception as e:
+    print(f"Empty interpolation error: {type(e).__name__}: {e}")
+
+print("\nIncompatible tests completed!")
diff --git a/tests/basics/string_tstring_basic1.py.exp b/tests/basics/string_tstring_basic1.py.exp
new file mode 100644
index 00000000000..7f2b0d85b60
--- /dev/null
+++ b/tests/basics/string_tstring_basic1.py.exp
@@ -0,0 +1,41 @@
+=== Parser error tests ===
+Empty expr: SyntaxError - malformed f-string
+Whitespace: Template(strings=('', ''), interpolations=(Interpolation(42, ' 42', None, ''),))
+
+=== Error cases ===
+Invalid syntax: SyntaxError
+Long expr: Error
+Mixed concat: SyntaxError
+bt prefix: SyntaxError
+
+=== Escape sequence coverage tests ===
+Template(strings=('\\8',), interpolations=())
+Template(strings=('\\9',), interpolations=())
+Template(strings=('\\z',), interpolations=())
+Template(strings=('\\k',), interpolations=())
+Invalid \x escape: SyntaxError
+Invalid \u escape: SyntaxError
+Invalid \U escape: SyntaxError
+Template(strings=('\x00\x01ÿ',), interpolations=())
+Template(strings=('A',), interpolations=())
+Template(strings=('α',), interpolations=())
+Template(strings=('❤',), interpolations=())
+Template(strings=('A',), interpolations=())
+Template(strings=('😀',), interpolations=())
+Template(strings=('ABC',), interpolations=())
+Unicode: Template(strings=('Unicode test:\nEmoji: ', '\nSpecial: ', ''), interpolations=(Interpolation('🐍', "'\\U0001f40d'", None, ''), Interpolation('α β γ', "'\\u03b1 \\u03b2 \\u03b3'", None, '')))
+
+=== Trailing whitespace preservation (PEP 750) ===
+Expression with trailing spaces: |x|
+Expression with both spaces: |   x|
+Expression with leading spaces: |   x|
+Trailing whitespace: PASS
+
+=== Error message tests ===
+Lone }} rejected (correct)
+Unterminated {{ rejected (correct)
+
+=== Triple quote empty interpolation ===
+Empty interpolation error: SyntaxError: malformed f-string
+
+Incompatible tests completed!
diff --git a/tests/basics/string_tstring_constructor.py b/tests/basics/string_tstring_constructor.py
new file mode 100644
index 00000000000..dc4a09a9578
--- /dev/null
+++ b/tests/basics/string_tstring_constructor.py
@@ -0,0 +1,112 @@
+from string.templatelib import Template, Interpolation
+
+print("=== Constructor basic usage ===")
+t = Template("hello ", Interpolation(42, "x"), "world")
+print(f"Template repr: {repr(t)}")
+
+t_varargs = Template("Hello ", Interpolation("World", "name"), "!")
+print(f"Varargs constructor: strings={t_varargs.strings}, values={t_varargs.values}")
+
+t_concat = Template("A", "B", Interpolation(1, "value"), "C", "D")
+print(f"Varargs merged strings: {t_concat.strings}")
+
+t_leading = Template(Interpolation(1, "x"), " tail")
+print(f"Leading interpolation strings: {t_leading.strings}")
+
+t_trailing = Template("head ", Interpolation(2, "y"))
+print(f"Trailing interpolation strings: {t_trailing.strings}")
+
+t_interps_only = Template(Interpolation(1, "x"), Interpolation(2, "y"))
+print(f"Interpolation only strings: {t_interps_only.strings}")
+
+print("\n=== Special cases ===")
+
+i = Interpolation(42, "x", "s", ":>10")
+try:
+    i.value = 100
+except AttributeError:
+    print("Interp read-only: AttributeError")
+
+t_ws_trim = Template("", Interpolation(None, "   ", None, ""), "")
+print(f"Whitespace trim: '{t_ws_trim}'")
+
+t_debug = Template("", Interpolation(42, "x=", None, ""), "")
+print(f"Debug =: {t_debug}")
+
+
+class Custom:
+    def __repr__(self):
+        return "CustomRepr"
+
+    def __str__(self):
+        return "CustomStr"
+
+
+obj = Custom()
+print(f"Custom !r: {t'{obj!r}'}")
+print(f"Custom !s: {t'{obj!s}'}")
+
+t_empty_start = Template("", Interpolation(1, "1"), "text")
+print(f"Empty start iter: {[type(x).__name__ for x in t_empty_start]}")
+
+t_iter_edge = Template("", Interpolation(1, "1"), "", Interpolation(2, "2"), "")
+iter_items = []
+for item in t_iter_edge:
+    iter_items.append(type(item).__name__)
+print(f"Iterator edge: {iter_items}")
+
+print("\n=== Values property ===")
+for n in range(7):
+    args = []
+    for i in range(n):
+        args.append("")
+        args.append(Interpolation(i, str(i)))
+    args.append("")
+    t = Template(*args)
+    print(f"Values[{n}]: {t.values}")
+
+print("\n=== Multiple consecutive strings ===")
+try:
+    t = Template("first", "second", "third", Interpolation(42, "x"), "fourth", "fifth")
+    if t.strings == ("firstsecondthird", "fourthfifth"):
+        print("Multiple strings concatenated: OK")
+    else:
+        print(f"Multiple strings: strings={t.strings}")
+except Exception as e:
+    print(f"Multiple strings error: {e}")
+
+print("\n=== Template() constructor with many interpolations ===")
+try:
+    exprs = ["a", "b", "c", "d", "e"]
+    interps = [Interpolation(i, exprs[i % len(exprs)]) for i in range(20)]
+    strings = [""] * 21
+    t = Template(*strings, *interps)
+    print(f"Template() constructor: OK ({len(t.interpolations)} interpolations)")
+except Exception as e:
+    print(f"Template() constructor: {type(e).__name__}")
+
+print("\n=== vstr string concatenation ===")
+try:
+    t1 = Template("part1", "part2", "part3", "part4", Interpolation(1, "x"), "end")
+    result = str(t1)
+    print(f"vstr concat: '{result}'")
+except Exception as e:
+    print(f"vstr concat error: {e}")
+
+print("\n=== High byte handling ===")
+try:
+    result = t"\x7f\x80\x81\xfe\xff"
+    first_str = result.strings[0]
+    print(
+        f"High bytes: len={len(first_str)}, first=0x{ord(first_str[0]):02x}, last=0x{ord(first_str[-1]):02x}"
+    )
+except Exception as e:
+    print(f"High bytes error: {e}")
+
+try:
+    result = t"\200\201\377"
+    print(f"Octal high bytes: OK, len={len(result.strings[0])}")
+except Exception as e:
+    print(f"Octal high bytes error: {e}")
+
+print("\nConstructor tests completed!")
diff --git a/tests/basics/string_tstring_constructor.py.exp b/tests/basics/string_tstring_constructor.py.exp
new file mode 100644
index 00000000000..e7d6ea90a9b
--- /dev/null
+++ b/tests/basics/string_tstring_constructor.py.exp
@@ -0,0 +1,40 @@
+=== Constructor basic usage ===
+Template repr: Template(strings=('hello ', 'world'), interpolations=(Interpolation(42, 'x', None, ''),))
+Varargs constructor: strings=('Hello ', '!'), values=('World',)
+Varargs merged strings: ('AB', 'CD')
+Leading interpolation strings: ('', ' tail')
+Trailing interpolation strings: ('head ', '')
+Interpolation only strings: ('', '', '')
+
+=== Special cases ===
+Interp read-only: AttributeError
+Whitespace trim: 'Template(strings=('', ''), interpolations=(Interpolation(None, '   ', None, ''),))'
+Debug =: Template(strings=('', ''), interpolations=(Interpolation(42, 'x=', None, ''),))
+Custom !r: Template(strings=('', ''), interpolations=(Interpolation(CustomRepr, 'obj', 'r', ''),))
+Custom !s: Template(strings=('', ''), interpolations=(Interpolation(CustomRepr, 'obj', 's', ''),))
+Empty start iter: ['Interpolation', 'str']
+Iterator edge: ['Interpolation', 'Interpolation']
+
+=== Values property ===
+Values[0]: ()
+Values[1]: (0,)
+Values[2]: (0, 1)
+Values[3]: (0, 1, 2)
+Values[4]: (0, 1, 2, 3)
+Values[5]: (0, 1, 2, 3, 4)
+Values[6]: (0, 1, 2, 3, 4, 5)
+
+=== Multiple consecutive strings ===
+Multiple strings concatenated: OK
+
+=== Template() constructor with many interpolations ===
+Template() constructor: OK (20 interpolations)
+
+=== vstr string concatenation ===
+vstr concat: 'Template(strings=('part1part2part3part4', 'end'), interpolations=(Interpolation(1, 'x', None, ''),))'
+
+=== High byte handling ===
+High bytes: len=5, first=0x7f, last=0xff
+Octal high bytes: OK, len=3
+
+Constructor tests completed!
diff --git a/tests/basics/string_tstring_constructor1.py b/tests/basics/string_tstring_constructor1.py
new file mode 100644
index 00000000000..1593efa9d79
--- /dev/null
+++ b/tests/basics/string_tstring_constructor1.py
@@ -0,0 +1,24 @@
+# NOTE: Error messages are shortened in MicroPython to avoid stack overflow
+# during ROM compression on constrained platforms (Windows x86, ASan).
+# CPython 3.14 message: "Template.__new__ *args need to be of type 'str' or 'Interpolation', got int"
+# MicroPython message: "Template.__new__ args must be str or Interpolation, got 'int'"
+
+from string.templatelib import Template
+
+print("=== Constructor error messages ===")
+try:
+    Template(strings=("test",))
+except TypeError as e:
+    print(f"Keyword args: {e}")
+
+try:
+    Template("hello", 42, "world")
+except TypeError as e:
+    print(f"Invalid type: {e}")
+
+try:
+    Template("a", 42, "b")
+except TypeError as e:
+    print(f"Invalid type in varargs: {e}")
+
+print("\nConstructor error tests completed!")
diff --git a/tests/basics/string_tstring_constructor1.py.exp b/tests/basics/string_tstring_constructor1.py.exp
new file mode 100644
index 00000000000..932529c97b4
--- /dev/null
+++ b/tests/basics/string_tstring_constructor1.py.exp
@@ -0,0 +1,6 @@
+=== Constructor error messages ===
+Keyword args: function doesn't take keyword arguments
+Invalid type: expected str or Interpolation
+Invalid type in varargs: expected str or Interpolation
+
+Constructor error tests completed!
diff --git a/tests/basics/string_tstring_errors1.py b/tests/basics/string_tstring_errors1.py
new file mode 100644
index 00000000000..7a0c737ef67
--- /dev/null
+++ b/tests/basics/string_tstring_errors1.py
@@ -0,0 +1,246 @@
+from string.templatelib import Template, Interpolation
+
+print("\n=== Edge cases ===")
+t_empty = Template()
+print(f"Empty template: '{t_empty}'")
+
+t_empty_strs = Template("", Interpolation(1, "a"), "", Interpolation(2, "b"), "")
+print(f"Empty strings: {list(t_empty_strs)}")
+
+t_adj = t"{1}{2}{3}"
+print(f"Adjacent: '{t_adj}'")
+
+t_single = Template("only")
+print(f"Single iter: {list(t_single)}")
+
+t_self = t"test"
+print(f"Self+self: '{(t_self + t_self)}'")
+
+print("\n=== Additional coverage tests ===")
+
+t_str_literal = t"{'hello'}"
+print(f"String literal: {t_str_literal}")
+
+path = "/usr/local/bin"
+count = 42
+raw_path = rt"Path: {path}\n"
+print(f"Raw path strings: {raw_path.strings}, value={raw_path.interpolations[0].value}")
+
+raw_regex = rt"Regex: \\d+{count}"
+print(f"Raw regex strings: {raw_regex.strings}, value={raw_regex.interpolations[0].value}")
+
+try:
+    t_str_expr = t'{"test"}'
+    print(f"String expr: '{t_str_expr}'")
+except Exception as e:
+    print(f"String expr error: {e}")
+
+def raise_error():
+    raise ValueError("Special error")
+
+try:
+    t_exc = t"{raise_error()}"
+    print(t_exc)
+except ValueError as e:
+    print(f"Re-raised exception: {e}")
+
+try:
+    large_str = "x" * 100000
+    exec(f'very_long_name_{large_str} = t"test"')
+except (ValueError, MemoryError, SyntaxError, RuntimeError) as e:
+    print("Large template: SyntaxError")
+
+try:
+    exec('''t_triple = t"""Triple "quoted" string"""''')
+    print(f"Triple quoted: '{t_triple}'")
+except Exception as e:
+    print(f"Triple quoted error: {e}")
+
+try:
+    exec(r'''t_raw_triple = rt"""Raw triple\n{42}"""''')
+    print(f"Raw triple: '{t_raw_triple}'")
+except Exception as e:
+    print(f"Raw triple error: {e}")
+
+t_concat1 = t"a{1}b"
+t_concat2 = t"c{2}d{3}e"
+t_concat3 = t_concat1 + t_concat2
+print(f"Complex concat: strings={t_concat3.strings}, values={t_concat3.values}")
+
+t_empty = Template()
+t_nonempty = t"test{42}"
+t_concat_empty = t_empty + t_nonempty
+print(f"Empty concat: '{t_concat_empty}'")
+
+t_self_interp = t"x{1}y"
+t_self_concat = t_self_interp + t_self_interp
+print(f"Self interp concat: values={t_self_concat.values}")
+
+try:
+    exec('t"unterminated')
+except SyntaxError as e:
+    print(f"Lonely string: {type(e).__name__}")
+
+try:
+    t_edge = t""
+    print(f"Empty t-string: '{t_edge}'")
+except Exception as e:
+    print(f"Empty t-string error: {e}")
+
+
+print("\n=== High byte handling ===")
+try:
+    result = t'\x7F\x80\x81\xFE\xFF'
+    first_str = result.strings[0]
+    print(f"High bytes: len={len(first_str)}, first=0x{ord(first_str[0]):02x}, last=0x{ord(first_str[-1]):02x}")
+except Exception as e:
+    print(f"High bytes error: {e}")
+
+try:
+    result = t'\200\201\377'
+    print(f"Octal high bytes: OK, len={len(result.strings[0])}")
+except Exception as e:
+    print(f"Octal high bytes error: {e}")
+
+print("\n=== Deep nesting test ===")
+try:
+    nested = "1" + " + 1" * 150
+    code = f't"{{{nested}}}"'
+    exec(code)
+    print("Deep nesting: OK")
+except Exception as e:
+    print(f"Deep nesting error: {type(e).__name__}")
+
+print("\n=== Trailing whitespace in expression ===")
+try:
+    x = 42
+    code = 't"{x   }"'
+    result = eval(code)
+    print(f"Trailing whitespace: OK")
+except Exception as e:
+    print(f"Trailing whitespace error: {e}")
+
+print("\n=== Single closing brace ===")
+try:
+    exec('t"test }"')
+    print("ERROR: Single } should have raised SyntaxError")
+except SyntaxError as e:
+    print(f"Single }}: SyntaxError - {e}")
+
+print("\n=== Escape in string within interpolation ===")
+
+try:
+    compile('x = 1; t"{x=:"', '', 'exec')
+except SyntaxError:
+    print('Debug unclosed colon: SyntaxError')
+
+try:
+    compile('x = 1; t"{x=!"', '', 'exec')
+except SyntaxError:
+    print('Debug unclosed exclaim: SyntaxError')
+
+try:
+    compile('t"prefix{incomplete"', '', 'exec')
+except SyntaxError as e:
+    print('Unclosed brace literal: SyntaxError')
+
+try:
+    import sys
+    if hasattr(sys.implementation, '_mpy'):
+        compile('f"{x!invalid}"', '', 'exec')
+except SyntaxError:
+    print('Malformed f-string: SyntaxError')
+
+# NOTE: Error messages are shortened in MicroPython to avoid stack overflow
+# during ROM compression on constrained platforms (Windows x86, ASan).
+# CPython 3.14 message: "Template.__new__ *args need to be of type 'str' or 'Interpolation', got int"
+# MicroPython message: "Template.__new__ args must be str or Interpolation, got 'int'"
+
+try:
+    t = Template("string", 123)
+except TypeError as e:
+    print('Type error int:', e)
+
+try:
+    t = Template("a", "b", 3.14)
+except TypeError:
+    print('Type error float: TypeError')
+
+try:
+    compile('t"text { more text"', '', 'exec')
+except SyntaxError as e:
+    print('Unmatched brace:', e)
+
+try:
+    compile('x=1; t"{x= {nested}}"', '', 'exec')
+except SyntaxError:
+    print('Nested debug braces: SyntaxError')
+
+try:
+    compile('t"{x!}"', '', 'exec')
+except SyntaxError:
+    print('Missing conversion: SyntaxError')
+
+try:
+    compile('t"{x!z}"', '', 'exec')
+except SyntaxError as e:
+    print('Invalid conversion:', e)
+
+try:
+    compile('t"{x!r' + chr(0x0b) + ':10}"', '', 'exec')
+except SyntaxError as e:
+    print('Vertical tab:', e)
+
+try:
+    compile('t"{x!r@:10}"', '', 'exec')
+except SyntaxError as e:
+    print('Invalid char after conversion:', e)
+
+# MicroPython doesn't allow space after conversion.
+# try:
+#     x = 'test'
+#     exec('result = t"{x!r :10}"')
+#     print('Space after conversion: OK')
+# except Exception as e:
+#     print(f'Unexpected error: {e}')
+
+try:
+    x = 'test'
+    exec('result = t"{x!s\\t:10}"')
+    print('Tab after conversion: OK')
+except Exception as e:
+    print(f'Unexpected error: {e}')
+
+try:
+    x = 'test'
+    exec('result = t"{x!r\\n:10}"')
+    print('Newline after conversion: OK')
+except Exception as e:
+    print(f'Unexpected error: {e}')
+
+try:
+    x = 'test'
+    exec('result = t"{x!r\\r:10}"')
+    print('CR after conversion: OK')
+except Exception as e:
+    print(f'Unexpected error: {e}')
+
+try:
+    x = 'test'
+    exec('result = t"{x!s\\f:10}"')
+    print('Form-feed after conversion: OK')
+except Exception as e:
+    print(f'Unexpected error: {e}')
+
+print("\n=== Mixed prefixes ===")
+for src in ('ft"{x}"', 'tf"{x}"', 'frt"{x}"', 'rtf"{x}"', 'trf"{x}"'):
+    try:
+        exec(src)
+        print(src.split('"')[0] + ": OK (BUG!)")
+    except SyntaxError as e:
+        prefix = src.split('"')[0]
+        # Check if we get the specific error message or generic one
+        if "'f' and 't' prefixes are incompatible" in str(e):
+            print(f"{prefix}: incompatible prefixes")
+        else:
+            print(f"{prefix}: invalid syntax")
diff --git a/tests/basics/string_tstring_errors1.py.exp b/tests/basics/string_tstring_errors1.py.exp
new file mode 100644
index 00000000000..f8d993770d1
--- /dev/null
+++ b/tests/basics/string_tstring_errors1.py.exp
@@ -0,0 +1,60 @@
+
+=== Edge cases ===
+Empty template: 'Template(strings=('',), interpolations=())'
+Empty strings: [Interpolation(1, 'a', None, ''), Interpolation(2, 'b', None, '')]
+Adjacent: 'Template(strings=('', '', '', ''), interpolations=(Interpolation(1, '1', None, ''), Interpolation(2, '2', None, ''), Interpolation(3, '3', None, '')))'
+Single iter: ['only']
+Self+self: 'Template(strings=('testtest',), interpolations=())'
+
+=== Additional coverage tests ===
+String literal: Template(strings=('', ''), interpolations=(Interpolation('hello', "'hello'", None, ''),))
+Raw path strings: ('Path: ', '\\n'), value=/usr/local/bin
+Raw regex strings: ('Regex: \\\\d+', ''), value=42
+String expr: 'Template(strings=('', ''), interpolations=(Interpolation('test', '"test"', None, ''),))'
+Re-raised exception: Special error
+Large template: SyntaxError
+Triple quoted: 'Template(strings=('Triple "quoted" string',), interpolations=())'
+Raw triple: 'Template(strings=('Raw triple\\n', ''), interpolations=(Interpolation(42, '42', None, ''),))'
+Complex concat: strings=('a', 'bc', 'd', 'e'), values=(1, 2, 3)
+Empty concat: 'Template(strings=('test', ''), interpolations=(Interpolation(42, '42', None, ''),))'
+Self interp concat: values=(1, 1)
+Lonely string: SyntaxError
+Empty t-string: 'Template(strings=('',), interpolations=())'
+
+=== High byte handling ===
+High bytes: len=5, first=0x7f, last=0xff
+Octal high bytes: OK, len=3
+
+=== Deep nesting test ===
+Deep nesting: OK
+
+=== Trailing whitespace in expression ===
+Trailing whitespace: OK
+
+=== Single closing brace ===
+Single }: SyntaxError - malformed f-string
+
+=== Escape in string within interpolation ===
+Debug unclosed colon: SyntaxError
+Debug unclosed exclaim: SyntaxError
+Unclosed brace literal: SyntaxError
+Malformed f-string: SyntaxError
+Type error int: expected str or Interpolation
+Type error float: TypeError
+Unmatched brace: malformed f-string
+Nested debug braces: SyntaxError
+Missing conversion: SyntaxError
+Invalid conversion: invalid syntax
+Vertical tab: invalid syntax
+Invalid char after conversion: invalid syntax
+Unexpected error: invalid syntax
+Unexpected error: invalid syntax
+Unexpected error: invalid syntax
+Unexpected error: invalid syntax
+
+=== Mixed prefixes ===
+ft: invalid syntax
+tf: invalid syntax
+frt: invalid syntax
+rtf: invalid syntax
+trf: invalid syntax
diff --git a/tests/basics/string_tstring_format1.py b/tests/basics/string_tstring_format1.py
new file mode 100644
index 00000000000..54fb0f1e76b
--- /dev/null
+++ b/tests/basics/string_tstring_format1.py
@@ -0,0 +1,186 @@
+print("\n=== Format spec edge cases ===")
+print(f"Empty fmt: {t'{42:}'}")
+print(f"Width: '{t'{42:10}'}'")
+print(f"Conv+fmt: '{t'{42!r:>10}'}'")
+
+width = 10
+print(f"Interp fmt: '{t'{3.14:{width}.2f}'}'")
+
+try:
+    t_escaped = t"Hello {{name}} and {{{{value}}}}"
+    print(f"Escaped braces: '{t_escaped}'")
+except Exception as e:
+    print(f"Escaped braces error: {e}")
+
+try:
+    t_conv_fmt = t"{42!r:}"
+    print(f"Conv empty fmt: '{t_conv_fmt}'")
+except Exception as e:
+    print(f"Conv fmt error: {e}")
+
+print("\n=== Format spec edge cases ===")
+try:
+    x = 42
+    result = t'{x!r:0>+#10.5}'
+    print(f"Full format: '{result}'")
+except Exception as e:
+    print(f"Full format error: {e}")
+
+print("\n=== Format spec with special characters ===")
+try:
+    x = 42
+    result = t"{x:!r}"
+    print(f"Format spec '!r': {result.interpolations[0].format_spec == '!r'}")
+    print(f"Conversion is None: {result.interpolations[0].conversion is None}")
+except Exception as e:
+    print(f"Format spec error: {type(e).__name__}")
+
+print("\nCoverage tests completed!")
+print("\n=== Debug format edge cases ===")
+try:
+    x = 42
+    result = t'{x=!r}'
+    print(f"Debug with conv: '{result}'")
+except SyntaxError as e:
+    print(f"Debug conv: SyntaxError - {e}")
+
+
+print("\n=== Debug specifier tests ===")
+try:
+    value = 42
+    t1 = t'{value=}'
+    print(f"Debug basic: strings={t1.strings}, conv={t1.interpolations[0].conversion}")
+
+    t2 = t'{value=!s}'
+    print(f"Debug !s: strings={t2.strings}, conv={t2.interpolations[0].conversion}")
+
+    t3 = t'{value=:>10}'
+    print(f"Debug fmt: strings={t3.strings}, fmt_spec='{t3.interpolations[0].format_spec}'")
+except Exception as e:
+    print(f"Debug format error: {e}")
+
+
+print("\n=== Large number of interpolations ===")
+for N in (62, 63, 64, 65):
+    x = 1
+    code = 'result = str(t"' + '{x}' * N + '")'
+    exec(code)
+    expected = "Template(strings=" + repr(tuple("" for _ in range(N + 1))) + ", interpolations=(" + ", ".join("Interpolation(1, 'x', None, '')" for _ in range(N)) + "))"
+    print(N, result == expected)
+
+print("\n=== Malformed format specs (valid in CPython) ===")
+x = 42
+value = 42
+result = t'{x:10!r}'
+print(f"Malformed 1: format_spec: '{result.interpolations[0].format_spec}', conversion: {result.interpolations[0].conversion}")
+
+result = t'{value:^10!s}'
+print(f"Malformed 2: format_spec: '{result.interpolations[0].format_spec}', conversion: {result.interpolations[0].conversion}")
+
+result = t'{x:>!10}'
+print(f"Malformed 3: format_spec: '{result.interpolations[0].format_spec}', conversion: {result.interpolations[0].conversion}")
+
+try:
+    exec(r"t'\U00110000'")
+    print("ERROR: Should have failed")
+except SyntaxError as e:
+    print(f"Invalid unicode: SyntaxError - {e}")
+
+class CustomException(Exception):
+    pass
+
+class BadClass:
+    def __getattr__(self, name):
+        raise CustomException("Test exception")
+
+try:
+    bad_obj = BadClass()
+    result = t"{bad_obj.attr}"
+    print("ERROR: Should have raised exception")
+except CustomException as e:
+    print(f"Custom exception re-raised: {e}")
+except Exception as e:
+    print(f"Other exception: {type(e).__name__} - {e}")
+
+print("\nNULL lexer: Tested in heapalloc_fail_tstring.py")
+
+try:
+    exec(r"t'\N{LATIN SMALL LETTER A}'")
+    print("ERROR: \\N{{}} should not be supported")
+except (SyntaxError, NotImplementedError) as e:
+    print(f"\\N{{}} escape: SyntaxError")
+
+try:
+    result = rt'\u0041\U00000042'
+    print(f"Raw Unicode escapes: '{result.strings[0]}'")
+except Exception as e:
+    print(f"Raw Unicode error: {e}")
+
+try:
+    code_with_crlf = 't"line1\\r\\nline2"'
+    exec(code_with_crlf)
+    print("CR LF handling: OK")
+except Exception as e:
+    print(f"CR LF error: {e}")
+
+try:
+    code = ""
+    for i in range(20):
+        code += " " * i + "if True:\n"
+    code += " " * 20 + "x = t'deep indent'"
+    exec(code)
+    print("Deep indent: OK")
+except Exception as e:
+    print(f"Deep indent error: {e}")
+
+try:
+    exec("t'test\\")
+    print("ERROR: Trailing backslash should fail")
+except SyntaxError as e:
+    print(f"Trailing backslash: SyntaxError")
+
+print("\n=== Empty format spec node ===")
+try:
+    x = 42
+    result = t'{x:}'
+    print(f"Empty format after colon: OK")
+except Exception as e:
+    print(f"Empty format spec error: {e}")
+
+
+print("\n=== Format spec with special characters (coverage) ===")
+try:
+    align = "<"
+    width = 5
+    value = "test"
+    result = t'{value:{"^"*width}}'
+    print(f"Double quotes expr: format_spec={repr(result.interpolations[0].format_spec)}")
+except Exception as e:
+    print(f"Double quotes expr error: {type(e).__name__}: {e}")
+
+try:
+    align = "<"
+    width = 5
+    value = "test"
+    result = rt"{value:{align}{width}\\}"
+    print(f"Backslash raw: format_spec={repr(result.interpolations[0].format_spec)}")
+except Exception as e:
+    print(f"Backslash raw error: {type(e).__name__}: {e}")
+
+try:
+    align = "<"
+    width = 5
+    value = "test"
+    result = t"{value:{align}{width}\\}"
+    print(f"Backslash non-raw: format_spec={repr(result.interpolations[0].format_spec)}")
+except Exception as e:
+    print(f"Backslash non-raw error: {type(e).__name__}: {e}")
+
+try:
+    align = "<"
+    width = 5
+    value = "test"
+    result = t"{value:{align}{width}\n\t\r}"
+    print(f"Multiple escapes: format_spec={repr(result.interpolations[0].format_spec)}")
+except Exception as e:
+    print(f"Multiple escapes error: {type(e).__name__}: {e}")
diff --git a/tests/basics/string_tstring_format1.py.exp b/tests/basics/string_tstring_format1.py.exp
new file mode 100644
index 00000000000..601087ccfd3
--- /dev/null
+++ b/tests/basics/string_tstring_format1.py.exp
@@ -0,0 +1,54 @@
+
+=== Format spec edge cases ===
+Empty fmt: Template(strings=('', ''), interpolations=(Interpolation(42, '42', None, ''),))
+Width: 'Template(strings=('', ''), interpolations=(Interpolation(42, '42', None, '10'),))'
+Conv+fmt: 'Template(strings=('', ''), interpolations=(Interpolation(42, '42', 'r', '>10'),))'
+Interp fmt: 'Template(strings=('', ''), interpolations=(Interpolation(3.14, '3.14', None, '10.2f'),))'
+Escaped braces: 'Template(strings=('Hello {name} and {{value}}',), interpolations=())'
+Conv empty fmt: 'Template(strings=('', ''), interpolations=(Interpolation(42, '42', 'r', ''),))'
+
+=== Format spec edge cases ===
+Full format: 'Template(strings=('', ''), interpolations=(Interpolation(42, 'x', 'r', '0>+#10.5'),))'
+
+=== Format spec with special characters ===
+Format spec '!r': True
+Conversion is None: True
+
+Coverage tests completed!
+
+=== Debug format edge cases ===
+Debug with conv: 'Template(strings=('x=', ''), interpolations=(Interpolation(42, 'x', 'r', ''),))'
+
+=== Debug specifier tests ===
+Debug basic: strings=('value=', ''), conv=r
+Debug !s: strings=('value=', ''), conv=s
+Debug fmt: strings=('value=', ''), fmt_spec='>10'
+
+=== Large number of interpolations ===
+62 True
+63 True
+64 True
+65 True
+
+=== Malformed format specs (valid in CPython) ===
+Malformed 1: format_spec: '10!r', conversion: None
+Malformed 2: format_spec: '^10!s', conversion: None
+Malformed 3: format_spec: '>!10', conversion: None
+Invalid unicode: SyntaxError - invalid syntax
+Custom exception re-raised: Test exception
+
+NULL lexer: Tested in heapalloc_fail_tstring.py
+\N{} escape: SyntaxError
+Raw Unicode escapes: '\u0041\U00000042'
+CR LF handling: OK
+Deep indent: OK
+Trailing backslash: SyntaxError
+
+=== Empty format spec node ===
+Empty format after colon: OK
+
+=== Format spec with special characters (coverage) ===
+Double quotes expr: format_spec='^^^^^'
+Backslash raw: format_spec='<5\\\\'
+Backslash non-raw: format_spec='<5\\'
+Multiple escapes: format_spec='<5\n\t\r'
diff --git a/tests/basics/string_tstring_interpolation1.py b/tests/basics/string_tstring_interpolation1.py
new file mode 100644
index 00000000000..da9c469d2b3
--- /dev/null
+++ b/tests/basics/string_tstring_interpolation1.py
@@ -0,0 +1,72 @@
+print("\n=== Bracket/paren depth tracking ===")
+d = {'a': 1, 'b:c': 2}
+items = [10, 20, 30]
+colon_key = t"{d['b:c']}"
+print(f"Colon in key: expr={colon_key.interpolations[0].expression}, value={colon_key.interpolations[0].value}")
+
+slice_expr = t"{items[1:3]}"
+print(f"Slice colon: expr={slice_expr.interpolations[0].expression}, value={slice_expr.interpolations[0].value}")
+
+def pair(x, y=':'):
+    return (x, y)
+
+func_expr = t"{pair(1, 2)}"
+print(f"Function call: expr={func_expr.interpolations[0].expression}, value={func_expr.interpolations[0].value}")
+
+default_expr = t"{pair(3)}"
+print(f"Default arg colon: expr={default_expr.interpolations[0].expression}, value={default_expr.interpolations[0].value}")
+
+matrix = [[1, 2], [3, 4]]
+nested_expr = t"{matrix[0][1]}"
+print(f"Nested brackets: expr={nested_expr.interpolations[0].expression}, value={nested_expr.interpolations[0].value}")
+
+
+print("\n=== Inline template literal tests ===")
+
+try:
+    result = t"outer { t'' }"
+    print(f"Empty nested: {type(result.values[0]).__name__}")
+except Exception as e:
+    print(f"Empty nested: FAIL - {type(e).__name__}: {e}")
+
+try:
+    result = t"outer { t'inner' }"
+    print(f"With content: {type(result.values[0]).__name__}")
+except Exception as e:
+    print(f"With content: FAIL - {type(e).__name__}: {e}")
+
+try:
+    result = t"result: { t'a' + t'b' }"
+    print(f"Concatenation: {type(result.values[0]).__name__}")
+except Exception as e:
+    print(f"Concatenation: FAIL - {type(e).__name__}: {e}")
+
+try:
+    result = t'Single { t"double" }'
+    print(f"Mixed quotes: {type(result.values[0]).__name__}")
+except Exception as e:
+    print(f"Mixed quotes: FAIL - {type(e).__name__}: {e}")
+
+try:
+    x = 42
+    result = t"outer { t'inner {x}' }"
+    print(f"Nested interp: {type(result.values[0]).__name__}")
+except Exception as e:
+    print(f"Nested interp: FAIL - {type(e).__name__}: {e}")
+
+print("\n=== Backslashes not allowed in expressions (PEP 498/750) ===")
+try:
+    code = r"result = t'{\"test\"value\"}'"
+    exec(code)
+    print(f"ERROR: Backslash in expression should raise SyntaxError")
+except SyntaxError as e:
+    print(f"Backslash in expression: SyntaxError")
+
+try:
+    code = r"result = t'{\"\\n\"}'"
+    exec(code)
+    print(f"ERROR: Backslash in expression should raise SyntaxError")
+except SyntaxError as e:
+    print(f"Escaped newline: SyntaxError")
+
+print("\n=== Format spec with special characters ===")
diff --git a/tests/basics/string_tstring_interpolation1.py.exp b/tests/basics/string_tstring_interpolation1.py.exp
new file mode 100644
index 00000000000..8a62f331826
--- /dev/null
+++ b/tests/basics/string_tstring_interpolation1.py.exp
@@ -0,0 +1,20 @@
+
+=== Bracket/paren depth tracking ===
+Colon in key: expr=d['b:c'], value=2
+Slice colon: expr=items[1:3], value=[20, 30]
+Function call: expr=pair(1, 2), value=(1, 2)
+Default arg colon: expr=pair(3), value=(3, ':')
+Nested brackets: expr=matrix[0][1], value=2
+
+=== Inline template literal tests ===
+Empty nested: Template
+With content: Template
+Concatenation: Template
+Mixed quotes: Template
+Nested interp: Template
+
+=== Backslashes not allowed in expressions (PEP 498/750) ===
+Backslash in expression: SyntaxError
+Escaped newline: SyntaxError
+
+=== Format spec with special characters ===
diff --git a/tests/basics/string_tstring_operations.py b/tests/basics/string_tstring_operations.py
new file mode 100644
index 00000000000..3c3222025f8
--- /dev/null
+++ b/tests/basics/string_tstring_operations.py
@@ -0,0 +1,55 @@
+from string.templatelib import Template, Interpolation
+
+print("\n=== Binary operations ===")
+t1 = t"template"
+
+try:
+    t1 + "string"
+except TypeError as e:
+    print(f"Template+str: TypeError")
+
+try:
+    "string" + t1
+except TypeError as e:
+    print(f"str+Template: TypeError")
+
+try:
+    42 + t1
+except TypeError:
+    print("int+Template: TypeError")
+
+for op in ["-", "*", "/", "%", "**", "&", "|", "^", "<<", ">>"]:
+    try:
+        eval(f"t1 {op} t1")
+    except TypeError:
+        print(f"{op}: unsupported")
+
+print("\n=== Template.__add__ with multiple interpolations ===")
+try:
+    exprs = ["a", "b", "c", "d", "e"]
+    interps1 = [Interpolation(i, exprs[i % len(exprs)]) for i in range(20)]
+    strings1 = [""] * 21
+    t1 = Template(*strings1, *interps1)
+
+    interps2 = [Interpolation(i + 20, exprs[i % len(exprs)]) for i in range(20)]
+    strings2 = [""] * 21
+    t2 = Template(*strings2, *interps2)
+
+    result = t1 + t2
+    print(f"Template.__add__: OK ({len(result.interpolations)} interpolations)")
+except Exception as e:
+    print(f"Template.__add__: {type(e).__name__}")
+
+print("\n=== Template + non-string object ===")
+try:
+
+    class CustomObj:
+        pass
+
+    t1 = t"hello"
+    result = t1 + CustomObj()
+    print("ERROR: Should have raised TypeError")
+except TypeError as e:
+    print(f"Template + custom object: TypeError (correct)")
+
+print("\n=== 2-tuple constructor overflow ===")
diff --git a/tests/basics/string_tstring_operations.py.exp b/tests/basics/string_tstring_operations.py.exp
new file mode 100644
index 00000000000..a565db8fec9
--- /dev/null
+++ b/tests/basics/string_tstring_operations.py.exp
@@ -0,0 +1,23 @@
+
+=== Binary operations ===
+Template+str: TypeError
+str+Template: TypeError
+int+Template: TypeError
+-: unsupported
+*: unsupported
+/: unsupported
+%: unsupported
+**: unsupported
+&: unsupported
+|: unsupported
+^: unsupported
+<<: unsupported
+>>: unsupported
+
+=== Template.__add__ with multiple interpolations ===
+Template.__add__: OK (40 interpolations)
+
+=== Template + non-string object ===
+Template + custom object: TypeError (correct)
+
+=== 2-tuple constructor overflow ===
diff --git a/tests/basics/string_tstring_parser1.py b/tests/basics/string_tstring_parser1.py
new file mode 100644
index 00000000000..b8853ccd1e7
--- /dev/null
+++ b/tests/basics/string_tstring_parser1.py
@@ -0,0 +1,288 @@
+from string.templatelib import Template
+
+print("\n=== Empty expression tests ===")
+try:
+    exec("t'{}'")
+    print("ERROR: Empty expression should have raised SyntaxError")
+except SyntaxError as e:
+    print("Empty expr SyntaxError:", e)
+
+try:
+    exec("t'{   }'")
+    print("ERROR: Whitespace-only expression should have raised SyntaxError")
+except SyntaxError as e:
+    print("Whitespace expr SyntaxError:", e)
+
+try:
+    exec("t'{\\n\\t   \\n}'")
+    print("ERROR: Whitespace-only expr should fail")
+except SyntaxError as e:
+    print(f"Whitespace expr: SyntaxError")
+
+try:
+    exec("t'{value'")
+    print("ERROR: Unterminated expr should fail")
+except SyntaxError as e:
+    print(f"Unterminated expr: {type(e).__name__}")
+
+try:
+    exec("t'{   !r}'")
+    print("ERROR: Whitespace-conversion expr should fail")
+except SyntaxError as e:
+    print(f"Whitespace + conversion: {type(e).__name__}")
+
+try:
+    long_expr = 'x' * 104
+    code = f"t'{{{long_expr}}}'"
+    exec(f"{long_expr} = 'test'; result = {code}")
+    print("Long expression: OK")
+except Exception as e:
+    print(f"Long expr error: {type(e).__name__}: {e}")
+
+try:
+    large_str = 'x' * 1099
+    tmpl = Template(large_str)
+    result = str(tmpl)
+    print("Template.__str__ with large string: OK")
+except Exception as e:
+    print(f"Template.__str__ error: {type(e).__name__}: {e}")
+
+try:
+    x = 'a'
+    result = t'{x}'
+    print(f"Basic t-string: OK, result={result}")
+except Exception as e:
+    print(f"Basic t-string error: {type(e).__name__}: {e}")
+
+try:
+    code = 't"' + 'text{nested{x}}more' * 50 + '"'
+    x = 'test'
+    exec(f"x = 'test'; result = {code}")
+    print("Nested interpolations: OK")
+except Exception as e:
+    print(f"Nested interpolations error: {type(e).__name__}: {e}")
+
+width = 5
+x = 42
+try:
+    tmpl = t'{x:{width}{{literal}}}'
+    result = str(tmpl)
+    print(f'Escaped braces result: {result}')
+except ValueError as e:
+    print(f'Escaped braces ValueError: {e}')
+
+print("\n=== Expression parser tests ===")
+try:
+    exec("t'{[{(x,y):[1,2,3]} for x,y in [(1,2),(3,4)]]}'")
+    print("Complex expr: OK")
+except Exception as e:
+    print(f"Complex expr error: {type(e).__name__}")
+
+print("\n=== Lexer edge cases ===")
+print("Lexer NULL case: Tested via heapalloc_fail_tstring.py")
+
+print("\n=== Parser allocation edge cases ===")
+try:
+    deep_expr = "(" * 50 + "x" + ")" * 50
+    exec(f"x = 1; result = t'{{{deep_expr}}}'")
+    print("Deep nesting: OK")
+except Exception as e:
+    print(f"Deep nesting error: {type(e).__name__} - {e}")
+
+try:
+    long_expr = "(" * 100 + "x" + ")" * 100
+    exec(f"x = 1; result = t'{{{long_expr}}}'")
+    print("Very long expression: OK")
+except Exception as e:
+    print(f"Long expression error: {e}")
+
+
+print("\n=== Additional parser regression tests ===")
+
+try:
+    fmt = '"QUOTED"'
+    value = 'raw'
+    tmpl = rt"{value:{fmt}}"
+    print(f"Raw nested spec: {tmpl.interpolations[0].format_spec}")
+except Exception as e:
+    print(f"Raw nested spec error: {type(e).__name__}: {e}")
+
+try:
+    value = 'fmt'
+    tmpl = t'{value:"QUOTED"}'
+    print(f"Escaped quote spec: {tmpl.interpolations[0].format_spec}")
+except Exception as e:
+    print(f"Escaped quote spec error: {type(e).__name__}: {e}")
+
+try:
+    value = 'fmt'
+    tmpl = t"{value:\\n}"
+    print(f"Escaped backslash spec: {tmpl.interpolations[0].format_spec}")
+except Exception as e:
+    print(f"Escaped backslash spec error: {type(e).__name__}: {e}")
+
+try:
+    ns = {}
+    exec("value = 'fmt'\nresult = t\"{value:{'\\\\'}}\"", globals(), ns)
+    tmpl = ns['result']
+    print(f"Nested quoted spec: {tmpl.interpolations[0].format_spec}")
+except Exception as e:
+    print(f"Nested quoted spec error: {type(e).__name__}: {e}")
+
+try:
+    value = 'brace'
+    exec('tmpl = t"{value}}}}tail"')
+    print(f"Literal brace strings: {tmpl.strings}")
+except Exception as e:
+    print(f"Literal brace error: {type(e).__name__}: {e}")
+
+try:
+    exec('t"{value"')
+    print("ERROR: Unterminated field should have raised")
+except SyntaxError as e:
+    print(f"Unterminated field: {e}")
+
+
+print("\n=== Complex expression stress test ===")
+try:
+    vars_dict = {f"x{i}": i for i in range(60)}
+    exec_globals = globals().copy()
+    exec_globals.update(vars_dict)
+    expr_parts = [f"x{i}" for i in range(60)]
+    expr_str = " + ".join(expr_parts)
+    code = f't"{{{expr_str}}}"'
+    result = eval(code, exec_globals)
+    expected = sum(range(60))
+    actual = result.interpolations[0].value
+    if actual == expected:
+        print(f"60 terms: PASS")
+    else:
+        print(f"60 terms: FAIL (expected={expected}, got={actual})")
+except Exception as e:
+    print(f"60 terms: ERROR - {type(e).__name__}: {e}")
+
+try:
+    vars_dict = {f"x{i}": i for i in range(100)}
+    exec_globals = globals().copy()
+    exec_globals.update(vars_dict)
+    expr_parts = [f"x{i}" for i in range(100)]
+    expr_str = " + ".join(expr_parts)
+    code = f't"{{{expr_str}}}"'
+    result = eval(code, exec_globals)
+    expected = sum(range(100))
+    actual = result.interpolations[0].value
+    if actual == expected:
+        print(f"100 terms: PASS")
+    else:
+        print(f"100 terms: FAIL (expected={expected}, got={actual})")
+except Exception as e:
+    print(f"100 terms: ERROR - {type(e).__name__}: {e}")
+
+print("\n=== Stack expansion test (copy_parse_node) ===")
+try:
+    depth = 20
+    nested_expr = "[" * depth + "1" + "]" * depth
+    code = f't"{{{nested_expr}}}"'
+    result = eval(code)
+    if len(str(result.interpolations[0].value)) > 30:
+        print("Stack expansion: OK")
+    else:
+        print(f"Stack expansion: FAIL")
+except Exception as e:
+    print(f"Stack expansion error: {type(e).__name__}")
+
+print("\n=== Format spec with triple-quoted strings ===")
+try:
+    x = 42
+    code = '''t'{x:{"""test"""}}' '''
+    result = eval(code)
+    print(f"Triple-quote in format spec: OK")
+except Exception as e:
+    print(f"Triple-quote error: {type(e).__name__}: {e}")
+
+try:
+    x = 42
+    code = """t"{x:{'''test'''}}" """
+    result = eval(code)
+    print(f"Triple single-quote in format spec: OK")
+except Exception as e:
+    print(f"Triple single-quote error: {type(e).__name__}: {e}")
+
+print("\n=== Format spec parse error (exception handler) ===")
+try:
+    x = 42
+    code = "t\"{x:{1 + (}}\" "  # Unclosed parenthesis
+    result = eval(code)
+    print("ERROR: Should have raised SyntaxError")
+except SyntaxError as e:
+    print(f"Parse error handler: OK")
+except Exception as e:
+    print(f"Unexpected error: {type(e).__name__}: {e}")
+
+try:
+    x = 42
+    code = "t\"{x:{1 2 3}}\" "  # Invalid syntax
+    result = eval(code)
+    print("ERROR: Should have raised SyntaxError")
+except SyntaxError as e:
+    print(f"Parse error handler 2: OK")
+except Exception as e:
+    print(f"Unexpected error 2: {type(e).__name__}: {e}")
+
+print("\n=== Large integer in t-string ===")
+try:
+    # Use eval() to avoid compile-time overflow in longlong variant
+    large_int = eval("10**30")
+    tmpl = t"{large_int}"
+    if tmpl.interpolations[0].value == large_int:
+        print("Large integer: OK")
+    else:
+        print(f"Large integer: FAIL")
+except OverflowError:
+    # longlong variant doesn't support arbitrary precision integers
+    print("Large integer: OK")
+except Exception as e:
+    print(f"Large integer error: {type(e).__name__}: {e}")
+
+print("\n=== Bytes in expression ===")
+try:
+    data = b"test"
+    tmpl = t"{data}"
+    if tmpl.interpolations[0].value == b"test":
+        print("Bytes in expression: OK")
+    else:
+        print(f"Bytes: FAIL")
+except Exception as e:
+    print(f"Bytes error: {type(e).__name__}: {e}")
+
+print("\n=== Boolean constants ===")
+try:
+    tmpl = t"{True} {False}"
+    if tmpl.values == (True, False):
+        print("Boolean constants: OK")
+    else:
+        print(f"Booleans: FAIL")
+except Exception as e:
+    print(f"Boolean error: {type(e).__name__}: {e}")
+
+print("\n=== None constant ===")
+try:
+    tmpl = t"{None}"
+    if tmpl.values[0] is None:
+        print("None constant: OK")
+    else:
+        print(f"None: FAIL")
+except Exception as e:
+    print(f"None error: {type(e).__name__}: {e}")
+
+print("\n=== Deep nesting for rule stack expansion ===")
+try:
+    depth = 80
+    code = '(' * depth + '1' + ')' * depth
+    result = eval(code)
+    if result == 1:
+        print(f"Deep nesting (depth={depth}): OK")
+    else:
+        print(f"Deep nesting: FAIL (result={result})")
+except Exception as e:
+    print(f"Deep nesting error: {type(e).__name__}: {e}")
diff --git a/tests/basics/string_tstring_parser1.py.exp b/tests/basics/string_tstring_parser1.py.exp
new file mode 100644
index 00000000000..cd55b258546
--- /dev/null
+++ b/tests/basics/string_tstring_parser1.py.exp
@@ -0,0 +1,60 @@
+
+=== Empty expression tests ===
+Empty expr SyntaxError: malformed f-string
+Whitespace expr SyntaxError: malformed f-string
+Whitespace expr: SyntaxError
+Unterminated expr: SyntaxError
+Whitespace + conversion: SyntaxError
+Long expression: OK
+Template.__str__ with large string: OK
+Basic t-string: OK, result=Template(strings=('', ''), interpolations=(Interpolation('a', 'x', None, ''),))
+Nested interpolations error: SyntaxError: invalid syntax
+Escaped braces result: Template(strings=('', ''), interpolations=(Interpolation(42, 'x', None, '5{literal}'),))
+
+=== Expression parser tests ===
+Complex expr: OK
+
+=== Lexer edge cases ===
+Lexer NULL case: Tested via heapalloc_fail_tstring.py
+
+=== Parser allocation edge cases ===
+Deep nesting: OK
+Very long expression: OK
+
+=== Additional parser regression tests ===
+Raw nested spec: "QUOTED"
+Escaped quote spec: "QUOTED"
+Escaped backslash spec: \n
+Nested quoted spec: \
+Literal brace error: SyntaxError: malformed f-string
+Unterminated field: malformed f-string
+
+=== Complex expression stress test ===
+60 terms: PASS
+100 terms: PASS
+
+=== Stack expansion test (copy_parse_node) ===
+Stack expansion: OK
+
+=== Format spec with triple-quoted strings ===
+Triple-quote in format spec: OK
+Triple single-quote in format spec: OK
+
+=== Format spec parse error (exception handler) ===
+Parse error handler: OK
+Parse error handler 2: OK
+
+=== Large integer in t-string ===
+Large integer: OK
+
+=== Bytes in expression ===
+Bytes in expression: OK
+
+=== Boolean constants ===
+Boolean constants: OK
+
+=== None constant ===
+None constant: OK
+
+=== Deep nesting for rule stack expansion ===
+Deep nesting (depth=80): OK
diff --git a/tests/basics/string_tstring_whitespace.py b/tests/basics/string_tstring_whitespace.py
new file mode 100644
index 00000000000..08dd7933c38
--- /dev/null
+++ b/tests/basics/string_tstring_whitespace.py
@@ -0,0 +1,25 @@
+print("# Empty expression (whitespace only)")
+try:
+    exec('t"{ }"')
+    print("ERROR: Should have raised SyntaxError")
+except SyntaxError as e:
+    print("Empty expr (space): SyntaxError (correct)")
+
+try:
+    exec('t"{\t}"')
+    print("ERROR: Should have raised SyntaxError")
+except SyntaxError as e:
+    print("Empty expr (tab): SyntaxError (correct)")
+
+try:
+    exec('t"{\n}"')
+    print("ERROR: Should have raised SyntaxError")
+except SyntaxError as e:
+    print("Empty expr (newline): SyntaxError (correct)")
+
+print("\n# Lexer escape sequence: invalid then valid")
+try:
+    exec("t'\\U00200000\\x41'")
+    print("ERROR: Should have raised SyntaxError")
+except SyntaxError as e:
+    print("Invalid escape sequence: SyntaxError (correct)")
diff --git a/tests/basics/string_tstring_whitespace.py.exp b/tests/basics/string_tstring_whitespace.py.exp
new file mode 100644
index 00000000000..f5868faf68f
--- /dev/null
+++ b/tests/basics/string_tstring_whitespace.py.exp
@@ -0,0 +1,7 @@
+# Empty expression (whitespace only)
+Empty expr (space): SyntaxError (correct)
+Empty expr (tab): SyntaxError (correct)
+Empty expr (newline): SyntaxError (correct)
+
+# Lexer escape sequence: invalid then valid
+Invalid escape sequence: SyntaxError (correct)
diff --git a/tests/basics/subclass_native1.py b/tests/basics/subclass_native1.py
index 288a686d1a7..74b377eac91 100644
--- a/tests/basics/subclass_native1.py
+++ b/tests/basics/subclass_native1.py
@@ -21,11 +21,9 @@ class mylist(list):
 # TODO: Faults
 #print(a + a)
 
-def foo():
-    print("hello from foo")
-
+# subclassing a type that doesn't have make_new at the C level (not allowed)
 try:
-    class myfunc(type(foo)):
+    class myfunc(type([].append)):
         pass
 except TypeError:
     print("TypeError")
diff --git a/tests/basics/subclass_native_call.py b/tests/basics/subclass_native_call.py
new file mode 100644
index 00000000000..e77287060cc
--- /dev/null
+++ b/tests/basics/subclass_native_call.py
@@ -0,0 +1,27 @@
+# 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 machine
+    machine.PinBase
+    machine.Signal
+except:
+    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
new file mode 100644
index 00000000000..d81cc0710eb
--- /dev/null
+++ b/tests/basics/subclass_native_call.py.exp
@@ -0,0 +1 @@
+42
diff --git a/tests/basics/subclass_native_exc_new.py b/tests/basics/subclass_native_exc_new.py
index a431392eaa4..87be6c76026 100644
--- a/tests/basics/subclass_native_exc_new.py
+++ b/tests/basics/subclass_native_exc_new.py
@@ -26,7 +26,7 @@ def __new__(cls, *args, **kwargs):
     raise BadException("bad message")
 except Exception as bad:
     # Should be TypeError 'exceptions must derive from BaseException'
-    print(type(bad), bad.args[0])
+    print(type(bad), bad.args or ("exceptions must derive from BaseException",))
 
 try:
     def gen():
@@ -35,4 +35,4 @@ def gen():
     gen().throw(BadException)
 except Exception as genbad:
     # Should be TypeError 'exceptions must derive from BaseException'
-    print(type(genbad), genbad.args[0])
+    print(type(genbad), genbad.args or ("exceptions must derive from BaseException",))
diff --git a/tests/basics/subclass_native_exc_new.py.exp b/tests/basics/subclass_native_exc_new.py.exp
index 65709b2ccf2..d2b770e8aa1 100644
--- a/tests/basics/subclass_native_exc_new.py.exp
+++ b/tests/basics/subclass_native_exc_new.py.exp
@@ -1,6 +1,6 @@
 GoodException __new__
  good message
 BadException __new__
- exceptions must derive from BaseException
+ ('exceptions must derive from BaseException',)
 BadException __new__
- exceptions must derive from BaseException
+ ('exceptions must derive from BaseException',)
diff --git a/tests/basics/subclass_native_init.py b/tests/basics/subclass_native_init.py
index 38d2f23ac38..102befd551f 100644
--- a/tests/basics/subclass_native_init.py
+++ b/tests/basics/subclass_native_init.py
@@ -1,11 +1,44 @@
 # test subclassing a native type and overriding __init__
 
+if not hasattr(object, "__init__"):
+    print("SKIP")
+    raise SystemExit
+
 # overriding list.__init__()
 class L(list):
     def __init__(self, a, b):
         super().__init__([a, b])
 print(L(2, 3))
 
+# with keyword arguments, with star arguments and without because those use different C calls
+class D(dict):
+    def __init__(self, *args, **kwargs):
+        super().__init__(*args, **kwargs)
+print(D())
+print(D([('a', 1)]))
+print(D([('a', 1)], a=2, b=3))
+print(D(a=2, b=3))
+
+class D(dict):
+    def __init__(self):
+        super().__init__()
+print(D())
+
+class D(dict):
+    def __init__(self):
+        super().__init__([])
+print(D())
+
+class D(dict):
+    def __init__(self):
+        super().__init__(a=1)
+print(D())
+
+class D(dict):
+    def __init__(self):
+        super().__init__([], a=1)
+print(D())
+
 # inherits implicitly from object
 class A:
     def __init__(self):
diff --git a/tests/basics/subscr_tuple.py b/tests/basics/subscr_tuple.py
index 0210e24df87..3b2703b829f 100644
--- a/tests/basics/subscr_tuple.py
+++ b/tests/basics/subscr_tuple.py
@@ -1,3 +1,4 @@
+# CIRCUITPY-CHANGE: micropython does not have this test file
 # subscripting a subclassed tuple
 class Foo(tuple):
     pass
diff --git a/tests/basics/syntaxerror.py b/tests/basics/syntaxerror.py
index c0702cb2452..7b6ef9b7550 100644
--- a/tests/basics/syntaxerror.py
+++ b/tests/basics/syntaxerror.py
@@ -86,7 +86,7 @@ def test_syntax(code):
 test_syntax("nonlocal a")
 test_syntax("await 1")
 
-# error on uPy, warning on CPy
+# error on MPy, warning on CPy
 #test_syntax("def f():\n a = 1\n global a")
 
 # default except must be last
@@ -98,7 +98,7 @@ def test_syntax(code):
 # non-keyword after keyword
 test_syntax("f(a=1, 2)")
 
-# doesn't error on uPy but should
+# doesn't error on MPy but should
 #test_syntax("f(1, i for i in i)")
 
 # all elements of dict/set must be pairs or singles
diff --git a/tests/basics/sys1.py b/tests/basics/sys1.py
index 6266440e353..02946abc220 100644
--- a/tests/basics/sys1.py
+++ b/tests/basics/sys1.py
@@ -25,6 +25,18 @@
     # Effectively skip subtests
     print(int)
 
+if hasattr(sys.implementation, '_build'):
+    print(type(sys.implementation._build))
+else:
+    # Effectively skip subtests
+    print(str)
+
+if hasattr(sys.implementation, '_thread'):
+    print(sys.implementation._thread in ("GIL", "unsafe"))
+else:
+    # Effectively skip subtests
+    print(True)
+
 try:
     print(sys.intern('micropython') == 'micropython')
     has_intern = True
diff --git a/tests/basics/sys_tracebacklimit.py b/tests/basics/sys_tracebacklimit.py
index 3ae372b8d52..6f575fde654 100644
--- a/tests/basics/sys_tracebacklimit.py
+++ b/tests/basics/sys_tracebacklimit.py
@@ -30,7 +30,7 @@ def print_exc(e):
         if l.startswith("  File "):
             l = l.split('"')
             print(l[0], l[2])
-        # uPy and CPy tracebacks differ in that CPy prints a source line for
+        # MPy and CPy tracebacks differ in that CPy prints a source line for
         # each traceback entry.  In this case, we know that offending line
         # has 4-space indent, so filter it out.
         elif not l.startswith("    "):
diff --git a/tests/basics/sys_tracebacklimit.py.native.exp b/tests/basics/sys_tracebacklimit.py.native.exp
new file mode 100644
index 00000000000..f9d30c05856
--- /dev/null
+++ b/tests/basics/sys_tracebacklimit.py.native.exp
@@ -0,0 +1,22 @@
+ValueError: value
+
+limit 4
+ValueError: value
+
+limit 3
+ValueError: value
+
+limit 2
+ValueError: value
+
+limit 1
+ValueError: value
+
+limit 0
+ValueError: value
+
+limit -1
+ValueError: value
+
+True
+False
diff --git a/tests/basics/try_finally_break.py.exp b/tests/basics/try_finally_break.py.exp
new file mode 100644
index 00000000000..d0b36985489
--- /dev/null
+++ b/tests/basics/try_finally_break.py.exp
@@ -0,0 +1,25 @@
+1
+2
+5
+a 1
+1
+iter 0
+1
+None
+1
+2
+None
+1
+2
+None
+1
+3
+4
+7
+1
+2
+4
+7
+1
+4
+7
diff --git a/tests/basics/try_finally_break2.py.exp b/tests/basics/try_finally_break2.py.exp
new file mode 100644
index 00000000000..bc5e931fdb4
--- /dev/null
+++ b/tests/basics/try_finally_break2.py.exp
@@ -0,0 +1,17 @@
+4 0 0 1
+4 0 0 2
+4 0 0 3
+4 0 0 4
+4 1 0 1
+4 1 0 2
+4 1 0 3
+4 1 0 4
+4 2 0 1
+4 2 0 2
+4 2 0 3
+4 2 0 4
+4 3 0 1
+4 3 0 2
+4 3 0 3
+4 3 0 4
+None
diff --git a/tests/basics/try_finally_return2.py.exp b/tests/basics/try_finally_return2.py.exp
new file mode 100644
index 00000000000..b4c364f81d9
--- /dev/null
+++ b/tests/basics/try_finally_return2.py.exp
@@ -0,0 +1,19 @@
+finally
+0
+finally 1
+finally 2
+2
+finally 1
+finally 2
+1
+finally 1
+finally 2
+2
+finally
+0
+finally
+0
+finally
+0
+finally
+0
diff --git a/tests/basics/try_finally_return3.py.exp b/tests/basics/try_finally_return3.py.exp
new file mode 100644
index 00000000000..5fef648ea67
--- /dev/null
+++ b/tests/basics/try_finally_return3.py.exp
@@ -0,0 +1,23 @@
+1
+42
+1
+2
+42
+1
+2
+3
+42
+2
+1
+42
+2
+1
+42
+1
+3
+2
+42
+1
+3
+2
+42
diff --git a/tests/basics/try_finally_return4.py.exp b/tests/basics/try_finally_return4.py.exp
new file mode 100644
index 00000000000..f92572ff611
--- /dev/null
+++ b/tests/basics/try_finally_return4.py.exp
@@ -0,0 +1,38 @@
+1
+2
+3
+4
+5
+None
+1
+2
+3
+5
+42
+1
+2
+5
+43
+1
+2
+5
+43
+1
+2
+5
+caught
+1
+2
+5
+caught
+1
+2
+3
+4
+5
+None
+1
+2
+3
+5
+42
diff --git a/tests/basics/try_finally_return5.py.exp b/tests/basics/try_finally_return5.py.exp
new file mode 100644
index 00000000000..dfa403cfd47
--- /dev/null
+++ b/tests/basics/try_finally_return5.py.exp
@@ -0,0 +1,3 @@
+4 0
+return
+43
diff --git a/tests/basics/tuple1.py b/tests/basics/tuple1.py
index 72bb3f01bff..70ae071898e 100644
--- a/tests/basics/tuple1.py
+++ b/tests/basics/tuple1.py
@@ -17,7 +17,7 @@
 x += (10, 11, 12)
 print(x)
 
-# construction of tuple from large iterator (tests implementation detail of uPy)
+# construction of tuple from large iterator (tests implementation detail of MicroPython)
 print(tuple(range(20)))
 
 # unsupported unary operation
diff --git a/tests/basics/tuple_subclass.py b/tests/basics/tuple_subclass.py
new file mode 100644
index 00000000000..a8ee3ff1a4f
--- /dev/null
+++ b/tests/basics/tuple_subclass.py
@@ -0,0 +1,62 @@
+try:
+    from collections import namedtuple
+except ImportError:
+    print("SKIP")
+    raise SystemExit
+
+
+class MyTuple(tuple):
+    pass
+
+
+N = namedtuple("N", ("a", "b"))
+
+
+class MyNamedTuple(N):
+    pass
+
+
+t = (1, 2)
+m = MyTuple((3, 4))
+n = N(5, 6)
+q = MyNamedTuple(7, 8)
+
+print(t + t)
+print(t + m)
+print(t + n)
+print(t + q)
+
+print(m + t)
+print(m + m)
+print(m + n)
+print(m + q)
+
+print(n + t)
+print(n + m)
+print(n + n)
+print(n + q)
+
+print(q + t)
+print(q + m)
+print(q + n)
+print(q + q)
+
+print(t < t)
+print(t < m)
+print(t < n)
+print(t < q)
+
+print(m < t)
+print(m < m)
+print(m < n)
+print(m < q)
+
+print(n < t)
+print(n < m)
+print(n < n)
+print(n < q)
+
+print(q < t)
+print(q < m)
+print(q < n)
+print(q < q)
diff --git a/tests/basics/weakref_callback_exception.py b/tests/basics/weakref_callback_exception.py
new file mode 100644
index 00000000000..df8e5129803
--- /dev/null
+++ b/tests/basics/weakref_callback_exception.py
@@ -0,0 +1,42 @@
+# Test weakref ref/finalize raising an exception within the callback.
+#
+# This test has different output to CPython due to the way that MicroPython
+# prints the exception.
+
+try:
+    import weakref
+except ImportError:
+    print("SKIP")
+    raise SystemExit
+
+import gc
+
+
+class A:
+    def __str__(self):
+        return ""
+
+
+def callback(*args):
+    raise ValueError("weakref callback", args)
+
+
+def test():
+    print("test ref with exception in the callback")
+    a = A()
+    r = weakref.ref(a, callback)
+    a = None
+    clean_the_stack = [0, 0, 0, 0]
+    gc.collect()
+    print("collect done")
+
+    print("test finalize with exception in the callback")
+    a = A()
+    weakref.finalize(a, callback)
+    a = None
+    clean_the_stack = [0, 0, 0, 0]
+    gc.collect()
+    print("collect done")
+
+
+test()
diff --git a/tests/basics/weakref_callback_exception.py.exp b/tests/basics/weakref_callback_exception.py.exp
new file mode 100644
index 00000000000..c2f7796310c
--- /dev/null
+++ b/tests/basics/weakref_callback_exception.py.exp
@@ -0,0 +1,12 @@
+test ref with exception in the callback
+Unhandled exception in weakref callback:
+Traceback (most recent call last):
+  File "\.\+weakref_callback_exception.py", line 21, in callback
+ValueError: ('weakref callback', (,))
+collect done
+test finalize with exception in the callback
+Unhandled exception in weakref callback:
+Traceback (most recent call last):
+  File "\.\+weakref_callback_exception.py", line 21, in callback
+ValueError: ('weakref callback', ())
+collect done
diff --git a/tests/basics/weakref_callback_exception.py.native.exp b/tests/basics/weakref_callback_exception.py.native.exp
new file mode 100644
index 00000000000..a06a35c3b7e
--- /dev/null
+++ b/tests/basics/weakref_callback_exception.py.native.exp
@@ -0,0 +1,8 @@
+test ref with exception in the callback
+Unhandled exception in weakref callback:
+ValueError: ('weakref callback', (,))
+collect done
+test finalize with exception in the callback
+Unhandled exception in weakref callback:
+ValueError: ('weakref callback', ())
+collect done
diff --git a/tests/basics/weakref_finalize_basic.py b/tests/basics/weakref_finalize_basic.py
new file mode 100644
index 00000000000..792cffacb13
--- /dev/null
+++ b/tests/basics/weakref_finalize_basic.py
@@ -0,0 +1,58 @@
+# Test weakref.finalize() functionality that doesn't require gc.collect().
+
+try:
+    import weakref
+except ImportError:
+    print("SKIP")
+    raise SystemExit
+
+# Cannot reference non-heap objects.
+for value in (None, False, True, Ellipsis, 0, "", ()):
+    try:
+        weakref.finalize(value, lambda: None)
+    except TypeError:
+        print(value, "TypeError")
+
+
+# Convert (obj, func, args, kwargs) so CPython and MicroPython have a chance to match.
+def convert_4_tuple(values):
+    if values is None:
+        return None
+    return (type(values[0]).__name__, type(values[1]), values[2], values[3])
+
+
+class A:
+    def __str__(self):
+        return ""
+
+
+print("test alive, peek, detach")
+a = A()
+f = weakref.finalize(a, lambda: None, 1, 2, kwarg=3)
+print("alive", f.alive)
+print("peek", convert_4_tuple(f.peek()))
+print("detach", convert_4_tuple(f.detach()))
+print("alive", f.alive)
+print("peek", convert_4_tuple(f.peek()))
+print("detach", convert_4_tuple(f.detach()))
+print("call", f())
+a = None
+
+print("test alive, peek, call")
+a = A()
+f = weakref.finalize(a, lambda *args, **kwargs: (args, kwargs), 1, 2, kwarg=3)
+print("alive", f.alive)
+print("peek", convert_4_tuple(f.peek()))
+print("call", f())
+print("alive", f.alive)
+print("peek", convert_4_tuple(f.peek()))
+print("call", f())
+print("detach", convert_4_tuple(f.detach()))
+
+print("test call which raises exception")
+a = A()
+f = weakref.finalize(a, lambda: 1 / 0)
+try:
+    f()
+except ZeroDivisionError as er:
+    print("call ZeroDivisionError")
diff --git a/tests/basics/weakref_finalize_collect.py b/tests/basics/weakref_finalize_collect.py
new file mode 100644
index 00000000000..f6e7c14843e
--- /dev/null
+++ b/tests/basics/weakref_finalize_collect.py
@@ -0,0 +1,76 @@
+# Test weakref.finalize() functionality requiring gc.collect().
+# Should be kept in sync with tests/ports/webassembly/weakref_finalize_collect.py.
+
+try:
+    import weakref
+except ImportError:
+    print("SKIP")
+    raise SystemExit
+
+# gc module must be available if weakref is.
+import gc
+
+
+class A:
+    def __str__(self):
+        return ""
+
+
+def callback(*args, **kwargs):
+    print("callback({}, {})".format(args, kwargs))
+    return 42
+
+
+def test():
+    print("test basic use of finalize() with a simple callback")
+    a = A()
+    f = weakref.finalize(a, callback)
+    a = None
+    clean_the_stack = [0, 0, 0, 0]
+    gc.collect()
+    print("alive", f.alive)
+    print("peek", f.peek())
+    print("detach", f.detach())
+    print("call", f())
+
+    print("test that a callback is passed the correct values")
+    a = A()
+    f = weakref.finalize(a, callback, 1, 2, kwarg=3)
+    a = None
+    clean_the_stack = [0, 0, 0, 0]
+    gc.collect()
+    print("alive", f.alive)
+    print("peek", f.peek())
+    print("detach", f.detach())
+    print("call", f())
+
+    print("test that calling the finalizer cancels the finalizer")
+    a = A()
+    f = weakref.finalize(a, callback)
+    print(f())
+    print(a)
+    a = None
+    clean_the_stack = [0, 0, 0, 0]
+    gc.collect()
+
+    print("test that calling detach cancels the finalizer")
+    a = A()
+    f = weakref.finalize(a, callback)
+    print(len(f.detach()))
+    print(a)
+    a = None
+    clean_the_stack = [0, 0, 0, 0]
+    gc.collect()
+
+    print("test that finalize does not get collected before its ref does")
+    a = A()
+    weakref.finalize(a, callback)
+    clean_the_stack = [0, 0, 0, 0]
+    gc.collect()
+    print("free a")
+    a = None
+    clean_the_stack = [0, 0, 0, 0]
+    gc.collect()
+
+
+test()
diff --git a/tests/basics/weakref_multiple_refs.py b/tests/basics/weakref_multiple_refs.py
new file mode 100644
index 00000000000..400e03a17c7
--- /dev/null
+++ b/tests/basics/weakref_multiple_refs.py
@@ -0,0 +1,36 @@
+# Test weakref when multiple weak references are active.
+#
+# This test has different output to CPython due to the order that MicroPython
+# executes weak reference callbacks.
+
+try:
+    import weakref
+except ImportError:
+    print("SKIP")
+    raise SystemExit
+
+# gc module must be available if weakref is.
+import gc
+
+
+class A:
+    def __str__(self):
+        return ""
+
+
+def test():
+    global r1, r2  # needed for webassembly port to retain references to them
+
+    print("test having multiple ref and finalize objects referencing the same thing")
+    a = A()
+    r1 = weakref.ref(a, lambda r: print("ref1", r()))
+    f1 = weakref.finalize(a, lambda: print("finalize1"))
+    r2 = weakref.ref(a, lambda r: print("ref2", r()))
+    f2 = weakref.finalize(a, lambda: print("finalize2"))
+    print(r1(), f1.alive, r2(), f2.alive)
+    a = None
+    clean_the_stack = [0, 0, 0, 0]
+    gc.collect()
+
+
+test()
diff --git a/tests/basics/weakref_multiple_refs.py.exp b/tests/basics/weakref_multiple_refs.py.exp
new file mode 100644
index 00000000000..1f2d366f776
--- /dev/null
+++ b/tests/basics/weakref_multiple_refs.py.exp
@@ -0,0 +1,6 @@
+test having multiple ref and finalize objects referencing the same thing
+ True  True
+finalize2
+finalize1
+ref2 None
+ref1 None
diff --git a/tests/basics/weakref_ref_basic.py b/tests/basics/weakref_ref_basic.py
new file mode 100644
index 00000000000..058045f6c33
--- /dev/null
+++ b/tests/basics/weakref_ref_basic.py
@@ -0,0 +1,14 @@
+# Test weakref.ref() functionality that doesn't require gc.collect().
+
+try:
+    import weakref
+except ImportError:
+    print("SKIP")
+    raise SystemExit
+
+# Cannot reference non-heap objects.
+for value in (None, False, True, Ellipsis, 0, "", ()):
+    try:
+        weakref.ref(value)
+    except TypeError:
+        print(value, "TypeError")
diff --git a/tests/basics/weakref_ref_collect.py b/tests/basics/weakref_ref_collect.py
new file mode 100644
index 00000000000..0e8db977d77
--- /dev/null
+++ b/tests/basics/weakref_ref_collect.py
@@ -0,0 +1,69 @@
+# Test weakref.ref() functionality requiring gc.collect().
+# Should be kept in sync with tests/ports/webassembly/weakref_ref_collect.py.
+
+try:
+    import weakref
+except ImportError:
+    print("SKIP")
+    raise SystemExit
+
+# gc module must be available if weakref is.
+import gc
+
+# Cannot reference non-heap objects.
+for value in (None, False, True, Ellipsis, 0, "", ()):
+    try:
+        weakref.ref(value)
+    except TypeError:
+        print(value, "TypeError")
+
+
+class A:
+    def __str__(self):
+        return ""
+
+
+def callback(r):
+    print("callback", r())
+
+
+def test():
+    print("test basic use of ref() with only one argument")
+    a = A()
+    r = weakref.ref(a)
+    print(r())
+    a = None
+    clean_the_stack = [0, 0, 0, 0]
+    gc.collect()
+    print(r())
+
+    print("test use of ref() with a callback")
+    a = A()
+    r = weakref.ref(a, callback)
+    print(r())
+    a = None
+    clean_the_stack = [0, 0, 0, 0]
+    gc.collect()
+    print(r())
+
+    print("test when weakref gets collected before the object it refs")
+    a = A()
+    r = weakref.ref(a, callback)
+    print(r())
+    r = None
+    clean_the_stack = [0, 0, 0, 0]
+    gc.collect()
+    a = None
+
+    print("test a double reference")
+    a = A()
+    r1 = weakref.ref(a, callback)
+    r2 = weakref.ref(a, callback)
+    print(r1(), r2())
+    a = None
+    clean_the_stack = [0, 0, 0, 0]
+    gc.collect()
+    print(r1(), r2())
+
+
+test()
diff --git a/tests/circuitpython-manual/airlift/esp_wedge.py b/tests/circuitpython-manual/airlift/esp_wedge.py
new file mode 100644
index 00000000000..018cb6d6e9a
--- /dev/null
+++ b/tests/circuitpython-manual/airlift/esp_wedge.py
@@ -0,0 +1,29 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries
+#
+# SPDX-License-Identifier: MIT
+"""Board side of esp_wedge_host.py: wedge the ESP32 on purpose and keep the VM
+running, so the cleanup at the end of the VM run can't fix it. The core should
+notice its own commands failing, hard-reset the ESP32 and bring web workflow
+back. nina-fw 3.1.0 stops answering SPI commands until a hard reset when
+START_SERVER_TCP (0x28) comes before a WiFi join, which _airlift.reset() undoes."""
+
+import struct
+import time
+
+import _airlift
+
+_airlift.reset()
+try:
+    _airlift.transact(0x28, (struct.pack(">H", 5000), (0,), (0,)))
+except OSError as e:
+    print("START_SERVER_TCP before WiFi:", repr(e))
+print("WEDGED")
+end = time.monotonic() + 40
+while time.monotonic() < end:
+    time.sleep(0.1)
+# A VM command works again only if the core reset the ESP32.
+try:
+    print("status after:", _airlift.transact(0x20)[0][0])
+    print("PASS")
+except OSError as e:
+    print("still wedged:", repr(e))
diff --git a/tests/circuitpython-manual/airlift/esp_wedge_host.py b/tests/circuitpython-manual/airlift/esp_wedge_host.py
new file mode 100644
index 00000000000..5228580637c
--- /dev/null
+++ b/tests/circuitpython-manual/airlift/esp_wedge_host.py
@@ -0,0 +1,70 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries
+#
+# SPDX-License-Identifier: MIT
+"""Host test: web workflow recovers on its own from a wedged ESP32. Runs
+esp_wedge.py on the board through run_on_board.py and, from the moment the
+board prints WEDGED, polls web workflow until it answers again.
+Usage: esp_wedge_host.py  [runs]"""
+
+import os
+import subprocess
+import sys
+import threading
+import time
+import urllib.request
+
+ip = sys.argv[1]
+runs = int(sys.argv[2]) if len(sys.argv) > 2 else 1
+here = os.path.dirname(os.path.abspath(__file__))
+
+
+def up():
+    try:
+        with urllib.request.urlopen("http://%s/cp/version.json" % ip, timeout=1) as r:
+            return r.status == 200
+    except OSError:
+        return False
+
+
+passed = 0
+for run in range(runs):
+    time.sleep(2)
+    print("run %d: web workflow up before: %s" % (run + 1, up()))
+    p = subprocess.Popen(
+        [
+            sys.executable,
+            os.path.join(here, "run_on_board.py"),
+            os.path.join(here, "esp_wedge.py"),
+            "70",
+        ],
+        stdout=subprocess.PIPE,
+        text=True,
+    )
+    result = {}
+
+    def poll(t0):
+        while time.monotonic() - t0 < 40:
+            if up():
+                result["back"] = time.monotonic() - t0
+                return
+            time.sleep(0.2)
+
+    poller = None
+    board_pass = False
+    for line in p.stdout:
+        line = line.rstrip()
+        if line:
+            print("  board:", line)
+        board_pass = board_pass or line == "PASS"
+        if line == "WEDGED" and poller is None:
+            poller = threading.Thread(target=poll, args=(time.monotonic(),))
+            poller.start()
+    p.wait()
+    if poller:
+        poller.join()
+    print(
+        "  web workflow back %s"
+        % ("after %.1f s" % result["back"] if "back" in result else "NOT within 40 s")
+    )
+    passed += board_pass and "back" in result
+print("%d of %d passed" % (passed, runs))
diff --git a/tests/circuitpython-manual/airlift/no_web_workflow.py b/tests/circuitpython-manual/airlift/no_web_workflow.py
new file mode 100644
index 00000000000..4e3de121c06
--- /dev/null
+++ b/tests/circuitpython-manual/airlift/no_web_workflow.py
@@ -0,0 +1,24 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries
+#
+# SPDX-License-Identifier: MIT
+"""With no CIRCUITPY_WEB_API_PASSWORD in settings.toml, the core must leave the
+ESP32 alone, so ESP32SPI code that passes its own pins works as before.
+Remove the password, reset the board, then run this with run_on_board.py
+(or as code.py). Expected: "core owns the ESP32: False" and a firmware version."""
+
+import _airlift
+import board
+import busio
+from digitalio import DigitalInOut
+
+from adafruit_esp32spi import adafruit_esp32spi
+
+print("core owns the ESP32:", _airlift.active())
+esp = adafruit_esp32spi.ESP_SPIcontrol(
+    busio.SPI(board.SCK, board.MOSI, board.MISO),
+    DigitalInOut(board.ESP_CS),
+    DigitalInOut(board.ESP_BUSY),
+    DigitalInOut(board.ESP_RESET),
+)
+print("old-style ESP_SPIcontrol firmware:", esp.firmware_version)
+print("status after its own reset:", esp.status)
diff --git a/tests/circuitpython-manual/airlift/readme.md b/tests/circuitpython-manual/airlift/readme.md
new file mode 100644
index 00000000000..bca1cff37ed
--- /dev/null
+++ b/tests/circuitpython-manual/airlift/readme.md
@@ -0,0 +1,67 @@
+# Web workflow over an ESP32 co-processor (`_airlift`)
+
+Manual tests for web workflow on boards whose WiFi is an ESP32 co-processor
+running nina-fw, such as the Adafruit Fruit Jam. They run on a host computer
+on the same network as the board.
+
+## Prerequisites
+
+- The board's `settings.toml` sets `CIRCUITPY_WIFI_SSID`,
+  `CIRCUITPY_WIFI_PASSWORD` and `CIRCUITPY_WEB_API_PASSWORD`. The host tests
+  read the web API password from that file, so pass its path (normally on the
+  mounted CIRCUITPY drive).
+- Python 3 on the host. `run_on_board.py` and `esp_wedge_host.py` also need
+  `pyserial` and the board's USB serial port. The port defaults to the first
+  Fruit Jam in `/dev/serial/by-id`; set `AIRLIFT_TEST_SERIAL` to use another one.
+- Find the board's IP address in the serial console's title bar, or in
+  `http://circuitpython.local/cp/version.json`.
+
+## Tests
+
+Each test prints what it checks and ends with `PASS` or `FAIL`.
+
+- `web_workflow_files_host.py   [upload dir]`: lists `/`,
+  downloads `boot_out.txt`, and uploads, reads back and deletes a 20 KB file.
+  The upload dir defaults to `/saves/`, which web workflow can write to while
+  the host has CIRCUITPY mounted.
+- `web_workflow_download_host.py    [size]`: uploads one
+  file (100 KB by default) to `/saves/` and downloads it `n` times, checking
+  every byte.
+- `web_workflow_serial_host.py  `: drives the REPL through
+  the `/cp/serial/` websocket, including a soft reboot over the same
+  connection.
+- `esp_wedge_host.py  [runs]`: runs `esp_wedge.py` on the board, which
+  leaves the ESP32 unresponsive while the VM keeps running. Web workflow should
+  come back on its own, without a reset of the board.
+- `no_web_workflow.py`: with `CIRCUITPY_WEB_API_PASSWORD` removed from
+  `settings.toml`, the core must leave the ESP32 to user code. Run it with
+  `run_on_board.py no_web_workflow.py`; it needs `adafruit_esp32spi` in `lib/`.
+
+## Expected output
+
+`esp_wedge_host.py`:
+
+```
+run 1: web workflow up before: True
+  board: START_SERVER_TCP before WiFi: TimeoutError('Timed out waiting for SPI char',)
+  board: WEDGED
+  board: status after: 3
+  board: PASS
+  board: [end]
+  board: [end]
+  board: >
+  web workflow back after 4.2 s
+1 of 1 passed
+```
+
+`web_workflow_serial_host.py`:
+
+```
+ctrl-c -> prompt: True
+eval 6*7 -> 42: True 140 ms
+3000-char line arrives whole: True
+ctrl-d -> soft reboot seen: True
+code.py ran after reload: True
+same websocket at the REPL again: True
+eval after reload -> 43: True
+```
diff --git a/tests/circuitpython-manual/airlift/run_on_board.py b/tests/circuitpython-manual/airlift/run_on_board.py
new file mode 100644
index 00000000000..7fe85443ad3
--- /dev/null
+++ b/tests/circuitpython-manual/airlift/run_on_board.py
@@ -0,0 +1,68 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 Tim Cocks for Adafruit Industries
+#
+# SPDX-License-Identifier: MIT
+"""Run a local .py file on the board through the raw REPL and stream its output.
+Usage: run_on_board.py 
+
+
+"""
+
+
+def write_html(boards, info, out_dir):
+    if info["url"]:
+        run = 'From GitHub Actions run {run_id} ({desc}).'.format(
+            url=html.escape(info["url"], quote=True),
+            run_id=html.escape(info["run_id"]),
+            desc=html.escape(describe_run(info)),
+        )
+    else:
+        run = html.escape(describe_run(info))
+    with_region = sum(1 for b in boards if b["region"])
+    counts = f"{len(boards)} boards, {with_region} with a measurable flash region."
+    # The table rows carry only what the page shows; the per-language detail is in
+    # the JSON report. "6}" + "".join(f" {label:>8}" for label in labels))
+    for name in sorted(ports):
+        c = ports[name]
+        print(f"{name:16} {c['boards']:6}" + "".join(f" {c[label]:8}" for label in labels))
+
+
+def main():
+    parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
+    parser.add_argument("records_dir", help="directory holding the per-board size records")
+    parser.add_argument("out_dir", help="where to write the JSON and HTML reports")
+    parser.add_argument(
+        "--version",
+        default=os.environ.get("CP_VERSION"),
+        help="CircuitPython version named in the reports (default: $CP_VERSION)",
+    )
+    parser.add_argument(
+        "--summary",
+        default=os.environ.get("GITHUB_STEP_SUMMARY"),
+        help="append the markdown summary to this file (default: $GITHUB_STEP_SUMMARY)",
+    )
+    args = parser.parse_args()
+
+    records = load_records(args.records_dir)
+    boards = sorted((summarize(r) for r in records.values()), key=sort_key)
+    info = run_info(args.version)
+
+    out_dir = pathlib.Path(args.out_dir)
+    out_dir.mkdir(parents=True, exist_ok=True)
+    write_json(boards, info, out_dir)
+    write_html(boards, info, out_dir)
+
+    summary = markdown_summary(boards)
+    if args.summary:
+        with open(args.summary, "a") as f:
+            f.write(summary)
+    else:
+        print(summary)
+    print_ports(boards)
+
+
+if __name__ == "__main__":
+    main()
diff --git a/tools/ci_set_idf_constraint.py b/tools/ci_set_idf_constraint.py
new file mode 100644
index 00000000000..49c187f4587
--- /dev/null
+++ b/tools/ci_set_idf_constraint.py
@@ -0,0 +1,47 @@
+# SPDX-FileCopyrightText: Copyright (c) 2026 Adafruit Industries LLC
+#
+# SPDX-License-Identifier: MIT
+
+"""Set IDF_CONSTRAINT_FILE for CI.
+
+CI installs requirements-dev.txt for all ports, but on Espressif builds we must
+also apply the matching ESP-IDF constraints file so pip does not upgrade shared
+packages (for example click) beyond what ESP-IDF allows. This script derives the
+active ESP-IDF major.minor version from version.cmake and exports the exact
+constraints file path into GITHUB_ENV for later install steps.
+"""
+
+import os
+import pathlib
+import re
+
+TOP = pathlib.Path(__file__).resolve().parent.parent
+
+
+def main() -> None:
+    version_cmake = TOP / "ports" / "espressif" / "esp-idf" / "tools" / "cmake" / "version.cmake"
+    data = version_cmake.read_text(encoding="utf-8")
+
+    major = re.search(r"IDF_VERSION_MAJOR\s+(\d+)", data)
+    minor = re.search(r"IDF_VERSION_MINOR\s+(\d+)", data)
+    if major is None or minor is None:
+        raise RuntimeError(f"Unable to parse IDF version from {version_cmake}")
+
+    idf_tools_path = os.environ.get("IDF_TOOLS_PATH")
+    if not idf_tools_path:
+        raise RuntimeError("IDF_TOOLS_PATH is not set")
+
+    constraint = (
+        pathlib.Path(idf_tools_path) / f"espidf.constraints.v{major.group(1)}.{minor.group(1)}.txt"
+    )
+
+    github_env = os.environ.get("GITHUB_ENV")
+    if github_env:
+        with open(github_env, "a", encoding="utf-8") as f:
+            f.write(f"IDF_CONSTRAINT_FILE={constraint}\n")
+
+    print(f"Set IDF_CONSTRAINT_FILE={constraint}")
+
+
+if __name__ == "__main__":
+    main()
diff --git a/tools/ci_set_matrix.py b/tools/ci_set_matrix.py
index 11bffbaa755..d5928bff694 100755
--- a/tools/ci_set_matrix.py
+++ b/tools/ci_set_matrix.py
@@ -23,17 +23,18 @@
 
 import re
 import os
+import math
 import sys
 import json
 import pathlib
 import subprocess
+import tomllib
 from concurrent.futures import ThreadPoolExecutor
 
 tools_dir = pathlib.Path(__file__).resolve().parent
 top_dir = tools_dir.parent
 
 sys.path.insert(0, str(tools_dir / "adabot"))
-sys.path.insert(0, str(top_dir / "docs"))
 
 import build_board_info
 from shared_bindings_matrix import (
@@ -47,27 +48,84 @@
     "conf.py",
     "docs",
     "tests",
+    "tools/board_stubs/",
     "tools/ci_changes_per_commit.py",
     "tools/ci_check_duplicate_usb_vid_pid.py",
     "tools/ci_set_matrix.py",
+    "tools/shared_bindings_matrix.py",
+    ".github/workflows/run-tests.yml",
+    ".github/workflows/run-zephyr-tests.yml",
+    ".github/workflows/build-board-custom.yml",
+    ".github/workflows/zephyr-autogen-pr.yml",
+    ".github/workflows/bundle_cron.yml",
+    ".github/workflows/create-website-pr.yml",
+    ".github/workflows/learn_cron.yml",
+    ".github/workflows/notify-on-issue-label.yml",
+    ".github/workflows/pre-commit.yml",
+    ".github/workflows/reports_cron.yml",
+    "ports/zephyr-cp/tests/",
 }
 
 PATTERN_DOCS = (
-    r"^(?:\.github|docs|extmod\/ulab)|"
-    r"^(?:(?:ports\/\w+\/bindings|shared-bindings)\S+\.c|tools\/extract_pyi\.py|\.readthedocs\.yml|conf\.py|requirements-doc\.txt)$|"
+    r"^(?:\.github|docs|extmod\/ulab|tools\/board_stubs\/)|"
+    r"^(?:(?:ports\/\w+\/bindings|shared-bindings)\S+\.c|tools\/extract_pyi\.py|tools\/shared_bindings_matrix\.py|\.readthedocs\.yml|conf\.py|requirements-doc\.txt)$|"
     r"(?:-stubs|\.(?:md|MD|mk|rst|RST)|/Makefile)$"
 )
 
-PATTERN_WINDOWS = {
-    ".github/",
-    "extmod/",
-    "lib/",
-    "mpy-cross/",
-    "ports/unix/",
-    "py/",
-    "tools/",
-    "requirements-dev.txt",
-}
+GITHUB_MATRIX_LIMIT = 256
+
+# The Zephyr tests build native_sim and the two bsim boards out of the shared sources, so a
+# change confined to these cannot reach them: another port, a translation, a frozen library
+# (this port has none), documentation, the board stub tools, the unix test suite or the
+# autogen PR workflow.
+PATTERN_ZEPHYR_TESTS_IGNORE = re.compile(
+    r"^(?:docs|frozen|locale|tests|tools/board_stubs)/|^ports/(?!zephyr-cp/)"
+    r"|^\.github/workflows/zephyr-autogen-pr\.yml$|^tools/shared_bindings_matrix\.py$"
+)
+
+# Files that can't affect the unix coverage tests: other ports and the documentation,
+# including the docs' support matrix code and the board stub tools. The tests build nothing
+# from ports/ except ports/unix. frozen/ is not on this list, because run-tests.py puts the
+# frozen asyncio and Ticks libraries on the module search path.
+PATTERN_TESTS_IGNORE = re.compile(
+    r"^(?:docs|tools/board_stubs)/|^ports/(?!unix/)|^tools/shared_bindings_matrix\.py$"
+)
+
+# Files that can't affect mpy-cross: ports, frozen libraries, the documentation (including
+# the support matrix code and the board stub tools) and the tests. The board builds don't
+# need the mpy-cross and mpy-cross-mac jobs. They use the mpy-cross that the scheduler job
+# builds.
+PATTERN_MPY_CROSS_IGNORE = re.compile(
+    r"^(?:docs|frozen|ports|tests|tools/board_stubs)/|^tools/shared_bindings_matrix\.py$"
+)
+
+# Zephyr boards don't use make, so their module tables can't be computed here. Each
+# board's build writes autogen_board_info.toml next to its circuitpython.toml and that
+# file is committed; a board whose table is missing, unreadable or doesn't name a
+# module is built.
+ZEPHYR_BOARDS = tools_dir.parent / "ports" / "zephyr-cp" / "boards"
+zephyr_modules = None
+
+
+def load_zephyr_modules():
+    modules = {}
+    for board_info in ZEPHYR_BOARDS.glob("*/*/autogen_board_info.toml"):
+        board = f"{board_info.parent.parent.name}_{board_info.parent.name}"
+        try:
+            with board_info.open("rb") as f:
+                modules[board] = tomllib.load(f)["modules"]
+        except Exception as e:  # noqa: BLE001 -- whatever went wrong, the board gets built
+            print(f"  {board}: unusable module table ({e})")
+    return modules
+
+
+def zephyr_board_has_module(board, module):
+    """What the board's committed module table says. An unknown board or module counts
+    as yes, so the board gets built."""
+    global zephyr_modules
+    if zephyr_modules is None:
+        zephyr_modules = load_zephyr_modules()
+    return board not in zephyr_modules or zephyr_modules[board].get(module, True)
 
 
 def git_diff(pattern: str):
@@ -180,7 +238,9 @@ def get_settings(board):
             module_matches = pattern_module.search(file)
             port = port_matches.group(1) if port_matches else None
             if port and not module_matches:
-                if port != "unix":
+                # The port may have been removed entirely. In that case, its
+                # boards are gone too, so there is nothing to build for it.
+                if port != "unix" and port in port_to_board:
                     boards_to_build.update(port_to_board[port])
                 continue
 
@@ -190,11 +250,18 @@ def get_settings(board):
                 # Take a copy, because we remove items from it below. For
                 # instance, if we remove items from, say, all_board_ids, then
                 # the logic to build all boards breaks.
-                boards = set(port_to_board[port] if port else all_board_ids)
-
-                # Zephyr boards don't use make, so build them and don't compute their settings.
-                for board in port_to_board["zephyr-cp"]:
-                    if board in boards:
+                boards = set(port_to_board.get(port, ()) if port else all_board_ids)
+
+                # Zephyr boards don't use make, so decide them here from their committed
+                # module table and leave them out of the settings computation below.
+                module = module_matches.group(2) if module_matches else None
+                for board in list(boards):  # a copy, boards shrinks below
+                    if board_to_port[board] != "zephyr-cp":
+                        continue
+                    boards.remove(board)
+                    if file.startswith("frozen"):
+                        continue  # the port has no frozen modules
+                    if module is None or zephyr_board_has_module(board, module):
                         boards_to_build.add(board)
 
                 for board in boards_to_build:
@@ -257,8 +324,24 @@ def get_settings(board):
         port_to_boards_to_build.setdefault(port, []).append(board)
         print(" ", board)
 
+    # build-boards.yml runs one matrix per port and GitHub allows 256 jobs per matrix.
+    # Split a bigger port into alphabetical runs of equal size, listed like ports;
+    # "split_ports" maps a part back to the real port name, which build.yml passes on, so
+    # the toolchain setup in build-boards.yml stays unchanged.
+    split_ports = {}
+    for port, boards in list(port_to_boards_to_build.items()):
+        parts = math.ceil(len(boards) / GITHUB_MATRIX_LIMIT)
+        if parts > 1:
+            del port_to_boards_to_build[port]
+            size = math.ceil(len(boards) / parts)
+            for index, start in enumerate(range(0, len(boards), size), start=1):
+                name = f"{port}-{index}"
+                port_to_boards_to_build[name] = boards[start : start + size]
+                split_ports[name] = port
+
     if port_to_boards_to_build:
         port_to_boards_to_build["ports"] = sorted(list(port_to_boards_to_build.keys()))
+        port_to_boards_to_build["split_ports"] = split_ports
 
     # Set the step outputs
     set_output("ports", json.dumps(port_to_boards_to_build))
@@ -292,25 +375,40 @@ def set_docs(run: bool):
     set_output("docs", run)
 
 
-def set_windows(run: bool):
+def set_zephyr_tests(run: bool):
     if not run:
-        if last_failed_jobs.get("windows"):
+        if any(job.startswith("zephyr-tests") for job in last_failed_jobs):
             run = True
         else:
             for file in changed_files:
-                for pattern in PATTERN_WINDOWS:
-                    if file.startswith(pattern) and not any(
-                        [file.startswith(path) for path in IGNORE_BOARD]
-                    ):
-                        run = True
-                        break
-                else:
-                    continue
-                break
+                if not PATTERN_ZEPHYR_TESTS_IGNORE.match(file):
+                    run = True
+                    break
+
+    # Set the step outputs
+    print("Running Zephyr tests:", run)
+    set_output("zephyr-tests", run)
+
+
+# These don't check last_failed_jobs. If a tests or mpy-cross job failed on the last checked
+# commit, ci_changes_per_commit.py reports no commit, so all the pull request's changes are
+# checked again.
+def set_tests(run: bool):
+    if not run:
+        run = any(not PATTERN_TESTS_IGNORE.match(file) for file in changed_files)
+
+    # Set the step outputs
+    print("Running tests:", run)
+    set_output("tests", run)
+
+
+def set_mpy_cross(run: bool):
+    if not run:
+        run = any(not PATTERN_MPY_CROSS_IGNORE.match(file) for file in changed_files)
 
     # Set the step outputs
-    print("Building windows:", run)
-    set_output("windows", run)
+    print("Building mpy-cross:", run)
+    set_output("mpy-cross", run)
 
 
 def main():
@@ -318,7 +416,10 @@ def main():
     print("Running: " + ("all" if run_all else "conditionally"))
     # Set jobs
     set_docs(run_all)
-    set_windows(run_all)
+    set_zephyr_tests(run_all)
+    set_tests(run_all)
+    # Pushes upload each version's mpy-cross binaries to S3, so build them every time.
+    set_mpy_cross(run_all or os.environ.get("GITHUB_EVENT_NAME") == "push")
     set_boards(run_all)
 
 
diff --git a/tools/codeformat.py b/tools/codeformat.py
index a648d401ec3..6914c63fafa 100644
--- a/tools/codeformat.py
+++ b/tools/codeformat.py
@@ -231,14 +231,14 @@ def batch(cmd, files, N=200, check=False):
             command = ["python3", "tools/ruff_bindings.py"]
             batch(command, bindings_files(), check=True)
 
-    # Format Python files with black.
+    # Format Python files with "ruff format" (using config in pyproject.toml).
     if format_py:
         command = ["ruff", "format"]
         if args.v:
             command.append("-v")
         else:
             command.append("-q")
-        command.append(".")
+        command.extend(files if files else ["."])
         subprocess.check_call(command, cwd=TOP)
 
 
diff --git a/tools/file2h.py b/tools/file2h.py
index df9cc02fdab..2707d4a16e5 100644
--- a/tools/file2h.py
+++ b/tools/file2h.py
@@ -9,8 +9,6 @@
 #    ;
 # This script simply prints the escaped string straight to stdout
 
-from __future__ import print_function
-
 import sys
 
 # Can either be set explicitly, or left blank to auto-detect
diff --git a/tools/gen_crt_bundle.py b/tools/gen_crt_bundle.py
index da0d8837a95..0207c1d713d 100755
--- a/tools/gen_crt_bundle.py
+++ b/tools/gen_crt_bundle.py
@@ -2,11 +2,14 @@
 #
 # ESP32 x509 certificate bundle generation utility
 #
-# Converts PEM and DER certificates to a custom bundle format which stores just the
-# subject name and public key to reduce space
+# Converts PEM and DER certificates to a custom bundle format which stores just a hash of the
+# subject name and the public key to reduce space
 #
-# The bundle will have the format: number of certificates; crt 1 subject name length; crt 1 public key length;
-# crt 1 subject name; crt 1 public key; crt 2...
+# The bundle will have the format: number of certificates; crt 1 name hash length; crt 1 public key length;
+# crt 1 name hash; crt 1 public key; crt 2...
+#
+# The name hash is the first NAME_HASH_LEN bytes of the SHA-256 of the DER subject name, and the
+# certificates are sorted by it. It only finds the candidate root: the signature check decides.
 #
 # Copyright 2018-2019 Espressif Systems (Shanghai) PTE LTD
 #
@@ -26,6 +29,7 @@
 
 import argparse
 import csv
+import hashlib
 import os
 import re
 import struct
@@ -46,6 +50,16 @@
     raise
 
 ca_bundle_bin_file = "x509_crt_bundle"
+NAME_HASH_LEN = 8  # must match NAME_HASH_LEN in lib/mbedtls_config/crt_bundle.c
+
+
+def name_hash(cert):
+    """The bundle's key for a root: the first NAME_HASH_LEN bytes of the SHA-256 of its DER
+    subject name. The firmware hashes a certificate's issuer name the same way and looks the
+    result up with a binary search, so the bundle must be sorted by this value. Two roots can
+    share a hash; the firmware then tries each of them, and the signature check decides."""
+    return hashlib.sha256(cert.subject.public_bytes(default_backend())).digest()[:NAME_HASH_LEN]
+
 
 quiet = False
 
@@ -132,10 +146,8 @@ def add_from_der(self, crt_str):
         status("Successfully added 1 certificate")
 
     def create_bundle(self):
-        # Sort certificates in order to do binary search when looking up certificates
-        self.certificates = sorted(
-            self.certificates, key=lambda cert: cert.subject.public_bytes(default_backend())
-        )
+        # Sorted by name hash, so the firmware can find a root with a binary search
+        self.certificates = sorted(self.certificates, key=name_hash)
 
         bundle = struct.pack(">H", len(self.certificates))
 
@@ -146,15 +158,15 @@ def create_bundle(self):
                 serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo
             )
 
-            """ Read the subject name as DER format """
-            sub_name_der = crt.subject.public_bytes(default_backend())
+            # The hash stands in for the subject name; see name_hash()
+            sub_name_hash = name_hash(crt)
 
-            name_len = len(sub_name_der)
+            name_len = len(sub_name_hash)
             key_len = len(pub_key_der)
             len_data = struct.pack(">HH", name_len, key_len)
 
             bundle += len_data
-            bundle += sub_name_der
+            bundle += sub_name_hash
             bundle += pub_key_der
 
         return bundle
diff --git a/tools/gen_display_resources.py b/tools/gen_display_resources.py
index 2219b4e86da..97d216ab31b 100644
--- a/tools/gen_display_resources.py
+++ b/tools/gen_display_resources.py
@@ -8,8 +8,8 @@
 import struct
 import sys
 
-sys.path.insert(0, "bitmap_font")
-sys.path.insert(0, "../../tools/bitmap_font")
+sys.path.insert(0, "tools/bitmap_font")  # For running from root
+sys.path.insert(0, "../../tools/bitmap_font")  # For running from a port directory
 
 from adafruit_bitmap_font import bitmap_font
 
@@ -23,8 +23,23 @@
 )
 parser.add_argument("--output_c_file", type=argparse.FileType("w"), required=True)
 
+parser.add_argument(
+    "--lvgl-tilegrid",
+    action="store_true",
+    help="Set when building the LVGL compositing core: TileGrids have no partial_change field",
+)
+
 args = parser.parse_args()
 
+# The legacy TileGrid carries a partial_change flag for scanline dirty tracking; the
+# LVGL TileGrid does not, and the static initializer must match the struct in use.
+if args.lvgl_tilegrid:
+    partial_change_line = ""
+else:
+    partial_change_line = (
+        "    .partial_change = false,\n    .full_change = false,\n    .moved = false,\n"
+    )
+
 
 class BitmapStub:
     def __init__(self, width, height, color_depth):
@@ -76,7 +91,7 @@ def _load_row(self, y, row):
     print("Font missing", missing, "characters", file=sys.stderr)
 
 tile_x, tile_y, dx, dy = f.get_bounding_box()
-total_bits = tile_x * len(all_characters)
+total_bits = tile_x * len(filtered_characters)
 total_bits += 32 - total_bits % 32
 bytes_per_row = total_bits // 8
 b = bytearray(bytes_per_row * tile_y)
@@ -108,6 +123,13 @@ def _load_row(self, y, row):
 #include "shared-bindings/displayio/Palette.h"
 #include "supervisor/shared/display.h"
 
+// LVGL builds keep these bitmaps in RAM. Other builds keep them in flash to save RAM.
+#if CIRCUITPY_DISPLAYIO_LVGL
+#define DISPLAY_RESOURCE_CONST
+#else
+#define DISPLAY_RESOURCE_CONST const
+#endif
+
 """
 )
 
@@ -121,7 +143,7 @@ def _load_row(self, y, row):
     blinka_size = 16
     c_file.write(
         """\
-const uint32_t blinka_bitmap_data[32] = {
+DISPLAY_RESOURCE_CONST uint32_t blinka_bitmap_data[32] = {
     0x11000000, 0x00000011,
     0x11010000, 0x00001053,
     0x11010000, 0x00001156,
@@ -145,7 +167,7 @@ def _load_row(self, y, row):
     blinka_size = 12
     c_file.write(
         """\
-const uint32_t blinka_bitmap_data[28] = {
+DISPLAY_RESOURCE_CONST uint32_t blinka_bitmap_data[28] = {
     0x11010000, 0x00000000,
     0x53110000, 0x00000010,
     0x56110000, 0x00000011,
@@ -164,7 +186,7 @@ def _load_row(self, y, row):
 
 c_file.write(
     """\
-const displayio_bitmap_t blinka_bitmap = {{
+displayio_bitmap_t blinka_bitmap = {{
     .base = {{.type = &displayio_bitmap_type }},
     .width = {0},
     .height = {0},
@@ -225,16 +247,16 @@ def _load_row(self, y, row):
     .top_left_x = {0},
     .top_left_y = {0},
     .tiles = 0,
-    .partial_change = false,
-    .full_change = false,
+{partial_change_line}
     .hidden = false,
     .hidden_by_parent = false,
-    .moved = false,
+#if !CIRCUITPY_DISPLAYIO_LVGL
     .inline_tiles = true,
+#endif
     .in_group = true
 }};
 #endif
-""".format(blinka_size)
+""".format(blinka_size, partial_change_line=partial_change_line)
 )
 
 c_file.write(
@@ -275,15 +297,15 @@ def _load_row(self, y, row):
     .tile_width = {1},
     .tile_height = {2},
     .tiles = NULL,
-    .partial_change = false,
-    .full_change = false,
+{partial_change_line}
     .hidden = false,
     .hidden_by_parent = false,
-    .moved = false,
+#if !CIRCUITPY_DISPLAYIO_LVGL
     .inline_tiles = false,
+#endif
     .in_group = true
 }};
-""".format(len(all_characters), tile_x, tile_y)
+""".format(len(filtered_characters), tile_x, tile_y, partial_change_line=partial_change_line)
 )
 
 c_file.write(
@@ -303,20 +325,20 @@ def _load_row(self, y, row):
     .tile_width = {1},
     .tile_height = {2},
     .tiles = NULL,
-    .partial_change = false,
-    .full_change = false,
+{partial_change_line}
     .hidden = false,
     .hidden_by_parent = false,
-    .moved = false,
+#if !CIRCUITPY_DISPLAYIO_LVGL
     .inline_tiles = false,
+#endif
     .in_group = true
 }};
-""".format(len(all_characters), tile_x, tile_y)
+""".format(len(filtered_characters), tile_x, tile_y, partial_change_line=partial_change_line)
 )
 
 c_file.write(
     """\
-const uint32_t font_bitmap_data[{}] = {{
+DISPLAY_RESOURCE_CONST uint32_t font_bitmap_data[{}] = {{
 """.format(bytes_per_row * tile_y // 4)
 )
 
@@ -345,7 +367,7 @@ def _load_row(self, y, row):
     .bitmask = 0x01,
     .read_only = true
 }};
-""".format(len(all_characters) * tile_x, tile_y, bytes_per_row / 4)
+""".format(len(filtered_characters) * tile_x, tile_y, bytes_per_row / 4)
 )
 
 
@@ -366,7 +388,7 @@ def _load_row(self, y, row):
     """\
 terminalio_terminal_obj_t supervisor_terminal = {
     .base = { .type = &terminalio_terminal_type },
-    .font = &supervisor_terminal_font,
+    .font = MP_OBJ_FROM_PTR(&supervisor_terminal_font),
     .cursor_x = 0,
     .cursor_y = 0,
     .scroll_area = NULL,
diff --git a/tools/insert-usb-ids.py b/tools/insert-usb-ids.py
index 4691d5a710c..1b043e1fef0 100644
--- a/tools/insert-usb-ids.py
+++ b/tools/insert-usb-ids.py
@@ -6,8 +6,6 @@
 # inserts those values into the template file specified by sys.argv[2],
 # printing the result to stdout
 
-from __future__ import print_function
-
 import sys
 import re
 import string
diff --git a/tools/makemanifest.py b/tools/makemanifest.py
index a74a6934aea..97a708a68a3 100644
--- a/tools/makemanifest.py
+++ b/tools/makemanifest.py
@@ -24,7 +24,6 @@
 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 # THE SOFTWARE.
 
-from __future__ import print_function
 import sys
 import os
 import subprocess
@@ -137,6 +136,9 @@ def main():
     )
     cmd_parser.add_argument("-v", "--var", action="append", help="variables to substitute")
     cmd_parser.add_argument("--mpy-tool-flags", default="", help="flags to pass to mpy-tool")
+    cmd_parser.add_argument(
+        "--list-c-modules", action="store_true", help="list C module paths from manifest and exit"
+    )
     cmd_parser.add_argument("files", nargs="+", help="input manifest list")
     args = cmd_parser.parse_args()
 
@@ -151,6 +153,32 @@ def main():
         print("MPY_DIR and PORT_DIR variables must be specified")
         sys.exit(1)
 
+    # Use a lighter mode when only listing C modules: freeze/package/module
+    # become no-ops so the listing doesn't fail on freeze targets that may not
+    # exist for every variant of the board (e.g. alif's modules/$(MCU_CORE)).
+    mode = manifestfile.MODE_LIST_C_MODULES if args.list_c_modules else manifestfile.MODE_FREEZE
+    manifest = manifestfile.ManifestFile(mode, VARS)
+
+    # Include top-level inputs, to generate the manifest
+    for input_manifest in args.files:
+        try:
+            manifest.execute(input_manifest)
+        except manifestfile.ManifestFileError as er:
+            print(
+                'manifest error executing "{}": {}'.format(input_manifest, er.args[0]),
+                file=sys.stderr,
+            )
+            sys.exit(1)
+
+    # If we're just listing C modules, output them and exit
+    if args.list_c_modules:
+        c_modules = manifest.c_modules()
+        if c_modules:
+            # Output one path per line to handle paths with spaces
+            for module in c_modules:
+                print(module)
+        sys.exit(0)
+
     # Get paths to tools
     MPY_CROSS = VARS["MPY_DIR"] + "/mpy-cross/build/mpy-cross"
     if sys.platform == "win32":
@@ -163,16 +191,6 @@ def main():
         print("mpy-cross not found at {}, please build it first".format(MPY_CROSS))
         sys.exit(1)
 
-    manifest = manifestfile.ManifestFile(manifestfile.MODE_FREEZE, VARS)
-
-    # Include top-level inputs, to generate the manifest
-    for input_manifest in args.files:
-        try:
-            manifest.execute(input_manifest)
-        except manifestfile.ManifestFileError as er:
-            print('freeze error executing "{}": {}'.format(input_manifest, er.args[0]))
-            sys.exit(1)
-
     # Process the manifest
     str_paths = []
     mpy_files = []
@@ -245,7 +263,12 @@ def main():
             b'#include "py/emitglue.h"\n'
             b"extern const qstr_pool_t mp_qstr_const_pool;\n"
             b"const qstr_pool_t mp_qstr_frozen_const_pool = {\n"
-            b"    (qstr_pool_t*)&mp_qstr_const_pool, MP_QSTRnumber_of, 0, 0\n"
+            # CIRCUITPY-CHANGE: blob and offsets fields
+            b"    #if MICROPY_QSTR_BYTES_IN_HASH\n"
+            b"    (qstr_pool_t*)&mp_qstr_const_pool, MP_QSTRnumber_of, 0, 0, 0, NULL, NULL, NULL, NULL, {},\n"
+            b"    #else\n"
+            b"    (qstr_pool_t*)&mp_qstr_const_pool, MP_QSTRnumber_of, 0, 0, 0, NULL, NULL, NULL, {},\n"
+            b"    #endif\n"
             b"};\n"
             b'const char mp_frozen_names[] = { MP_FROZEN_STR_NAMES "\\0"};\n'
             b"const mp_raw_code_t *const mp_frozen_mpy_content[] = {NULL};\n"
diff --git a/tools/manifestfile.py b/tools/manifestfile.py
index beaa36d0f5f..2e2ade6783c 100644
--- a/tools/manifestfile.py
+++ b/tools/manifestfile.py
@@ -25,9 +25,9 @@
 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 # THE SOFTWARE.
 
-from __future__ import print_function
 import contextlib
 import os
+import re
 import sys
 import glob
 import tempfile
@@ -41,6 +41,9 @@
 MODE_COMPILE = 2
 # Same as compile, but handles require(..., pypi="name") as a requirements.txt entry.
 MODE_PYPROJECT = 3
+# Same surface as MODE_FREEZE, but freeze/package/module are no-ops so callers
+# can collect c_module() entries without touching files referenced by freeze().
+MODE_LIST_C_MODULES = 4
 
 # In compile mode, .py -> KIND_COMPILE_AS_MPY
 # In freeze mode, .py -> KIND_FREEZE_AS_MPY, .mpy->KIND_FREEZE_MPY
@@ -193,6 +196,8 @@ def __init__(self, mode, path_vars=None):
         self._manifest_files = []
         # List of PyPI dependencies (when mode=MODE_PYPROJECT).
         self._pypi_dependencies = []
+        # List of C module directories.
+        self._c_modules = []
         # Don't allow including the same file twice.
         self._visited = set()
         # Stack of metadata for each level.
@@ -202,7 +207,9 @@ def __init__(self, mode, path_vars=None):
         # List of directories to search for packages.
         self._library_dirs = []
         # Add default micropython-lib libraries if $(MPY_LIB_DIR) has been specified.
-        if self._path_vars["MPY_LIB_DIR"]:
+        # Use .get() to avoid KeyError if MPY_LIB_DIR wasn't passed (shouldn't happen
+        # in normal cmake/make builds, but be defensive for direct tool invocations).
+        if self._path_vars.get("MPY_LIB_DIR"):
             for lib in BASE_LIBRARY_NAMES:
                 self.add_library(lib, os.path.join("$(MPY_LIB_DIR)", lib))
 
@@ -222,11 +229,12 @@ def _manifest_globals(self, kwargs):
             "add_library": self.add_library,
             "package": self.package,
             "module": self.module,
+            "c_module": self.c_module,
             "options": IncludeOptions(**kwargs),
         }
 
         # Extra legacy functions only for freeze mode.
-        if self._mode == MODE_FREEZE:
+        if self._mode in (MODE_FREEZE, MODE_LIST_C_MODULES):
             g.update(
                 {
                     "freeze": self.freeze,
@@ -245,6 +253,9 @@ def pypi_dependencies(self):
         # In MODE_PYPROJECT, this will return a list suitable for requirements.txt.
         return self._pypi_dependencies
 
+    def c_modules(self):
+        return self._c_modules
+
     def execute(self, manifest_file):
         if manifest_file.endswith(".py"):
             # Execute file from filesystem.
@@ -479,6 +490,9 @@ def package(self, package_path, files=None, base_path=".", opt=None):
         """
         self._metadata[-1].check_initialised(self._mode)
 
+        if self._mode == MODE_LIST_C_MODULES:
+            return
+
         # Include "base_path/package_path/**/*.py" --> "package_path/**/*.py"
         self._search(base_path, package_path, files, exts=(".py",), kind=KIND_AUTO, opt=opt)
 
@@ -494,6 +508,9 @@ def module(self, module_path, base_path=".", opt=None):
         """
         self._metadata[-1].check_initialised(self._mode)
 
+        if self._mode == MODE_LIST_C_MODULES:
+            return
+
         # Include "base_path/module_path" --> "module_path"
         base_path = self._resolve_path(base_path)
         _, ext = os.path.splitext(module_path)
@@ -502,7 +519,56 @@ def module(self, module_path, base_path=".", opt=None):
         # TODO: version None
         self._add_file(os.path.join(base_path, module_path), module_path, opt=opt)
 
+    def c_module(self, module_path):
+        """
+        Include a C module directory in the build.
+
+        The module_path should be a directory containing a micropython.mk and/or
+        micropython.cmake file.
+
+        Supports $(VAR) path substitution:
+            c_module("$(MPY_DIR)/examples/usercmodule/cexample")
+            c_module("$(BOARD_DIR)/../../drivers/sensor")
+
+        Can be called multiple times to include multiple C modules.
+
+        Only has effect when collecting modules for the build system
+        (MODE_FREEZE / MODE_LIST_C_MODULES). Silent no-op in MODE_COMPILE /
+        MODE_PYPROJECT, so the same manifest can be evaluated in any mode.
+        """
+        if self._mode not in (MODE_FREEZE, MODE_LIST_C_MODULES):
+            return
+        resolved = self._resolve_path(module_path)
+        # Reject unresolved $(VAR) up front so a bad manifest fails with a
+        # clear message rather than a confusing "path does not exist" containing
+        # the variable literal.
+        unresolved = re.search(r"\$\([^)]+\)", resolved)
+        if unresolved:
+            raise ManifestFileError(
+                "Unresolved variable in c_module() path: {}".format(unresolved.group(0))
+            )
+        module_path = resolved
+        if not os.path.exists(module_path):
+            raise ManifestFileError("C module path does not exist: {}".format(module_path))
+        if not os.path.isdir(module_path):
+            raise ManifestFileError("C module path must be a directory: {}".format(module_path))
+        # Verify the directory contains a micropython.mk or micropython.cmake file.
+        has_mk = os.path.isfile(os.path.join(module_path, "micropython.mk"))
+        has_cmake = os.path.isfile(os.path.join(module_path, "micropython.cmake"))
+        if not has_mk and not has_cmake:
+            raise ManifestFileError(
+                "C module directory must contain micropython.mk or micropython.cmake: {}".format(
+                    module_path
+                )
+            )
+        self._c_modules.append(module_path)
+
     def _freeze_internal(self, path, script, exts, kind, opt):
+        # In list-c-modules mode we only care about c_module() entries; skip
+        # the file-system walk so freeze targets that don't exist (e.g. a
+        # board-conditional modules directory) don't abort the listing.
+        if self._mode == MODE_LIST_C_MODULES:
+            return
         if script is None:
             self._search(path, None, None, exts=exts, kind=kind, opt=opt)
         elif isinstance(script, str) and os.path.isdir(os.path.join(path, script)):
@@ -556,6 +622,8 @@ def freeze_as_str(self, path):
         Freeze the given `path` and all .py scripts within it as a string,
         which will be compiled upon import.
         """
+        if self._mode == MODE_LIST_C_MODULES:
+            return
         self._search(path, None, None, exts=(".py",), kind=KIND_FREEZE_AS_STR)
 
     def freeze_as_mpy(self, path, script=None, opt=None):
diff --git a/tools/merge_micropython.py b/tools/merge_micropython.py
index 37d44c3b7e3..7c4d7650793 100644
--- a/tools/merge_micropython.py
+++ b/tools/merge_micropython.py
@@ -8,7 +8,7 @@
 I add a sys.exit(0) after a section, and once a section runs, I delete it temporarily
 and move on to the next section. -- dhalbert
 
-Updated for v1.22.2 merge - dhalbert
+Updated for v1.25.0 merge - dhalbert
 
 """
 
@@ -18,256 +18,233 @@
 from sh import git
 import sys
 
-out_buf = StringIO()
 
-ports_to_delete = [
-    "bare-arm",
-    "cc3200",
-    "embed",
-    "esp32",
-    "esp8266",
-    "mimxrt",
-    "minimal",
-    "nrf",
-    "pic16bit",
-    "powerpc",
-    "qemu-arm",
-    "renesas-ra",
-    "rp2",
-    "samd",
-    "stm32",
-    "webassembly",
-    "windows",
-    "zephyr",
-]
-for p in ports_to_delete:
-    try:
-        git.rm("-rf", "ports/" + p)
-    except sh.ErrorReturnCode_128:
-        pass
+def rm_paths(base, paths):
+    for path in paths:
+        try:
+            git.rm("-rf", base + "/" + path)
+        except sh.ErrorReturnCode_128:
+            pass
 
-# We inherit stm32 changes into stm because we did a git rename.
-git.status("--porcelain=1", "ports/stm", _out=out_buf)
-out_buf.seek(0)
-line = out_buf.readline()
-while line:
-    state, path = line.split()
-    if state == "UU":
-        git.checkout("--ours", path)
-        git.add(path)
-    elif state == "UA":
-        git.rm(path)
-    line = out_buf.readline()
 
-# MicroPython has their own CI settings. Let's not use them now.
-out_buf = StringIO()
-git.status("--porcelain=1", ".github/workflows", _out=out_buf)
-out_buf.seek(0)
-line = out_buf.readline()
-while line:
-    state, path = line.split()
-    if state == "A":
-        git.rm("-f", path)
-    else:
-        print(state, path)
-    line = out_buf.readline()
-
-# Delete docs and tests for things we don't need anymore
-docs_to_delete = [
-    "conf.py",
-    "develop",
-    "differences",
-    "esp32",
-    "esp8266",
-    "library/bluetooth.rst",
-    "library/btree.rst",
-    "library/cryptolib.rst",
-    "library/esp*.rst",
-    "library/framebuf.rst",
-    "library/hashlib.rst",
-    "library/lcd160cr.rst",
-    "library/machine*.rst",
-    "library/math.rst",
-    "library/network*.rst",
-    "library/os.rst",
-    "library/pyb*.rst",
-    "library/random.rst",
-    "library/rp2*.rst",
-    "library/uos.rst",
-    "library/socket.rst",
-    "library/ssl.rst",
-    "library/stm.rst",
-    "library/struct.rst",
-    "library/_thread.rst",
-    "library/time.rst",
-    "library/uasyncio.rst",
-    "library/uctypes.rst",
-    "library/wipy.rst",
-    "library/wm8960.rst",
-    "library/zephyr*.rst",
-    "library/zlib.rst",
-    "make.bat",
-    "mimxrt",
-    "pyboard",
-    "reference",
-    "renesas-ra",
-    "rp2",
-    "samd",
-    "templates/topindex.html",
-    "wipy",
-    "zephyr",
-]
-for d in docs_to_delete:
-    try:
-        git.rm("-rf", "docs/" + d)
-    except sh.ErrorReturnCode_128:
-        pass
-
-tests_to_delete = [
-    "esp32",
-    "multi_bluetooth",
-    "multi_espnow",
-    "multi_net",
-    "net_hosted",
-    "net_inet",
-    "pyb",
-    "wipy",
-]
-for t in tests_to_delete:
-    try:
-        git.rm("-rf", "tests/" + t)
-    except sh.ErrorReturnCode_128:
-        pass
-
-
-libs_to_delete = [
-    "asf4",
-    "btstack",
-    "libhydrogen",
-    "lwip",
-    "micropython-lib",
-    "mynewt-nimble",
-    "nrfx",
-    "nxp_driver",
-    "pico-sdk",
-    "protobuf-c",
-    "stm32lib",
-    "wiznet5k",
-]
-for l in libs_to_delete:
-    try:
-        git.rm("-rf", "lib/" + l)
-    except sh.ErrorReturnCode_128:
-        pass
-
-extmod_to_delete = [
-    "btstack",
-    "extmod.cmake",
-    "machine_*",
-    "mbedtls",
-    "modbluetooth.*",
-    "modbtree.*",
-    "modframebuf.*",
-    "modlwip.*",
-    "modnetwork.*",
-    "modonewire.*",
-    "moducryptolib.*",
-    "modsocket.*",
-    "modssl_*.*",
-    "modtimeq.*",
-    "modwebsocket.*",
-    "modwebrepl.*",
-    "mpbthci.*",
-    "network_*.*",
-    "nimble",
-]
-for e in extmod_to_delete:
-    try:
-        git.rm("-rf", "extmod/" + e)
-    except sh.ErrorReturnCode_128 as error:
-        print(error)
-
-top_delete = [
-    "drivers",
-    "README.md",
-    "CODEOFCONDUCT.md",
-    "CODECONVENTIONS.md",
-]
-for t in top_delete:
-    try:
-        git.rm("-rf", t)
-    except sh.ErrorReturnCode_128:
-        pass
-
-dot_github_delete = [
-    ".github/dependabot.yml",
-    ".github/FUNDING.yml",
-    ".github/ISSUE_TEMPLATE/documentation.md",
-    ".github/ISSUE_TEMPLATE/security.md",
-    ".github/workflows/code_formatting.yml",
-    ".github/workflows/code_size_comment.yml",
-    ".github/workflows/code_size.yml",
-    ".github/workflows/commit_formatting.yml",
-    ".github/workflows/docs.yml",
-    ".github/workflows/examples.yml",
-    ".github/workflows/mpremote.yml",
-    ".github/workflows/mpy_format.yml",
-    ".github/workflows/mpy_format.yml",
-    ".github/workflows/ports_*.yml",
-]
-for t in dot_github_delete:
-    try:
-        git.rm("-rf", t)
-    except sh.ErrorReturnCode_128:
-        pass
-
-# Always ours:
-always_ours = [
-    ".github",
-    "devices",
-    "supervisor",
-    "shared-bindings",
-    "shared-module",
-    "ports/atmel-samd",
-    "ports/cxd56",
-    "ports/espressif",
-    "ports/mimxrt10xx",
-    "ports/raspberrypi",
-    "ports/stm",
-]
-for ours in always_ours:
-    out_buf = StringIO()
-    git.status("--porcelain=1", ours, _out=out_buf)
-    out_buf.seek(0)
-    line = out_buf.readline()
-    while line:
-        state, path = line.split()
-        if state == "UU":
-            print("ours", path)
-            git.checkout("--ours", path)
-            git.add(path)
-        else:
-            print(state, path)
+def checkout_ours(always_ours):
+    for ours in always_ours:
+        out_buf = StringIO()
+        git.status("--porcelain=1", ours, _out=out_buf)
+        out_buf.seek(0)
         line = out_buf.readline()
+        while line:
+            state, path = line.split()
+            if state == "UU":
+                print("ours", path)
+                git.checkout("--ours", path)
+                git.add(path)
+            else:
+                print(state, path)
+            line = out_buf.readline()
+
+
+rm_paths(
+    "ports",
+    [
+        "alif",
+        "bare-arm",
+        "cc3200",
+        "embed",
+        "esp32",
+        "esp8266",
+        "mimxrt",
+        "minimal",
+        "nrf",
+        "pic16bit",
+        "powerpc",
+        "qemu",
+        "renesas-ra",
+        "rp2",
+        "samd",
+        "stm32",
+        "webassembly",
+        "windows",
+        "zephyr",
+    ],
+)
+
+# Delete MicroPython-specific docs.
+rm_paths(
+    "docs",
+    [
+        "conf.py",
+        "develop",
+        "differences",
+        "esp32",
+        "esp8266",
+        "library/bluetooth.rst",
+        "library/btree.rst",
+        "library/cryptolib.rst",
+        "library/esp*.rst",
+        "library/framebuf.rst",
+        "library/hashlib.rst",
+        "library/lcd160cr.rst",
+        "library/machine*.rst",
+        "library/math.rst",
+        "library/network*.rst",
+        "library/os.rst",
+        "library/pyb*.rst",
+        "library/random.rst",
+        "library/rp2*.rst",
+        "library/uos.rst",
+        "library/socket.rst",
+        "library/ssl.rst",
+        "library/stm.rst",
+        "library/struct.rst",
+        "library/_thread.rst",
+        "library/time.rst",
+        "library/uasyncio.rst",
+        "library/uctypes.rst",
+        "library/vfs.rst",
+        "library/wipy.rst",
+        "library/wm8960.rst",
+        "library/zephyr*.rst",
+        "library/zlib.rst",
+        "make.bat",
+        "mimxrt",
+        "pyboard",
+        "renesas-ra",
+        "rp2",
+        "samd",
+        "templates/topindex.html",
+        "wipy",
+        "zephyr",
+    ],
+)
+
+# Delete MicroPython-specific tests.
+rm_paths(
+    "tests",
+    [
+        "esp32",
+        "multi_bluetooth",
+        "multi_espnow",
+        "multi_net",
+        "multi_pyb_can",
+        "multi_wlan",
+        "net_hosted",
+        "net_inet",
+        "ports",
+        "pyb",
+        "wipy",
+    ],
+)
+
+# libs we don't use
+rm_paths(
+    "lib",
+    [
+        "alif*",
+        "asf4",
+        "btstack",
+        "libhydrogen",
+        "lwip",
+        "mynewt-nimble",
+        "nrfx",
+        "nxp_driver",
+        "pico-sdk",
+        "protobuf-c",
+        "stm32lib",
+        "wiznet5k",
+    ],
+)
+
+# extmod modules we don't use
+rm_paths(
+    "extmod",
+    [
+        "btstack",
+        "extmod.cmake",
+        "machine_*",
+        "mbedtls",
+        "modbluetooth.*",
+        "modbtree.*",
+        "modframebuf.*",
+        "modlwip.*",
+        "modmachine.*",
+        "modnetwork.*",
+        "modonewire.*",
+        "moducryptolib.*",
+        "modsocket.*",
+        "modssl_*",
+        "modtls_*",
+        "modtimeq.*",
+        "modwebsocket.*",
+        "modwebrepl.*",
+        "mpbthci.*",
+        "network_*",
+        "nimble",
+        "virtpin.*",
+    ],
+)
+
+# shared things we don't use
+rm_paths(
+    "shared",
+    [
+        "netutils",
+        "tinyusb",
+        "runtime/softtimer.*",
+    ],
+)
+
+# top-level files and dirs we don't use
+rm_paths(
+    "",
+    [
+        "drivers",
+        "LICENSE_MicroPython",
+        "README.md",
+        "CODEOFCONDUCT.md",
+        "CODECONVENTIONS.md",
+    ],
+)
+
+# .github and CI we don't use
+rm_paths(
+    ".github",
+    [
+        "dependabot.yml",
+        "FUNDING.yml",
+        "ISSUE_TEMPLATE/feature_request.yml",
+        "ISSUE_TEMPLATE/documentation.yml",
+        "ISSUE_TEMPLATE/security.yml",
+        "workflows/biome.yml",
+        "workflows/code_formatting.yml",
+        "workflows/code_size_comment.yml",
+        "workflows/code_size.yml",
+        "workflows/codespell.yml",
+        "workflows/commit_formatting.yml",
+        "workflows/docs.yml",
+        "workflows/examples.ymlworkflows/mpremote.yml",
+        "workflows/mpy_format.yml",
+        "workflows/ports_*.yml",
+        "workflows/ruff.yml",
+    ],
+)
 
-# # Check to see if any files changed only in formatting
-# out_buf = StringIO()
-# git.status("--porcelain=1", ".", _out=out_buf)
-# out_buf.seek(0)
-# line = out_buf.readline()
-# while line:
-#     state = line.split()[0]
-#     if state in ("D", "R", "DD"):
-#         line = out_buf.readline()
-#         continue
-#     state, path = line.split()
-#     log_buf = StringIO()
-#     git.log("--pretty=tformat:%H", "25ae98f..HEAD", path, _out=log_buf, _tty_out=False)
-#     log_buf.seek(0)
-#     commits = []
-#     for line in log_buf.readlines():
-#         commits.append(line.strip())
-#     if state in ["UU", "M"] and commits == ["a52eb88031620a81521b937f2a0651dbac2bb350"]:
-#         git.checkout("--theirs", path)
-#         git.add(path)
-#     line = out_buf.readline()
+# Always ours:
+checkout_ours(
+    [
+        ".github",
+        "devices",
+        "lib/mbedtls_config",
+        "supervisor",
+        "shared-bindings",
+        "shared-module",
+        "ports/atmel-samd",
+        "ports/cxd56",
+        "ports/espressif",
+        "ports/mimxrt10xx",
+        "ports/raspberrypi",
+        "ports/silabs",
+        # We inherit stm32 changes into stm because we did a git rename.
+        "ports/stm",
+    ]
+)
diff --git a/tools/metrics.py b/tools/metrics.py
index 9c5ed1d7d5a..8bb96ba119a 100755
--- a/tools/metrics.py
+++ b/tools/metrics.py
@@ -43,20 +43,23 @@
 
 """
 
-import collections, sys, re, subprocess
+import collections, os, sys, re, shlex, subprocess, multiprocessing
 
-MAKE_FLAGS = ["-j3", "CFLAGS_EXTRA=-DNDEBUG"]
+MAKE_FLAGS = ["-j{}".format(multiprocessing.cpu_count()), "CFLAGS_EXTRA=-DNDEBUG"]
 
 
 class PortData:
-    def __init__(self, name, dir, output, make_flags=None):
+    def __init__(self, name, dir, output, make_flags=None, pre_cmd=None):
         self.name = name
         self.dir = dir
         self.output = output
         self.make_flags = make_flags
         self.needs_mpy_cross = dir not in ("bare-arm", "minimal")
+        self.pre_cmd = pre_cmd
 
 
+mpy_cross_output = "mpy-cross/build/mpy-cross"
+
 port_data = {
     "b": PortData("bare-arm", "bare-arm", "build/firmware.elf"),
     "m": PortData("minimal x86", "minimal", "build/firmware.elf"),
@@ -65,16 +68,29 @@ def __init__(self, name, dir, output, make_flags=None):
     "s": PortData("stm32", "stm32", "build-PYBV10/firmware.elf", "BOARD=PYBV10"),
     "c": PortData("cc3200", "cc3200", "build/WIPY/release/application.axf", "BTARGET=application"),
     "8": PortData("esp8266", "esp8266", "build-ESP8266_GENERIC/firmware.elf"),
-    "3": PortData("esp32", "esp32", "build-ESP32_GENERIC/micropython.elf"),
+    "3": PortData(
+        "esp32",
+        "esp32",
+        "build-ESP32_GENERIC/micropython.elf",
+        pre_cmd=". esp-idf/export.sh",
+    ),
     "x": PortData("mimxrt", "mimxrt", "build-TEENSY40/firmware.elf"),
     "e": PortData("renesas-ra", "renesas-ra", "build-EK_RA6M2/firmware.elf"),
     "r": PortData("nrf", "nrf", "build-PCA10040/firmware.elf"),
-    "p": PortData("rp2", "rp2", "build-RPI_PICO/firmware.elf"),
+    "p": PortData("rp2", "rp2", "build-RPI_PICO_W/firmware.elf", "BOARD=RPI_PICO_W"),
     "d": PortData("samd", "samd", "build-ADAFRUIT_ITSYBITSY_M4_EXPRESS/firmware.elf"),
+    "v": PortData("qemu rv32", "qemu", "build-VIRT_RV32/firmware.elf", "BOARD=VIRT_RV32"),
 }
 
+for port_letter, port in port_data.items():
+    port.pre_cmd = os.environ.get(f"PRE_CMD_{port_letter}", port.pre_cmd)
+
+
+def quoted(args):
+    return " ".join(shlex.quote(word) for word in args)
 
-def syscmd(*args):
+
+def syscmd(*args, pre_cmd=None):
     sys.stdout.flush()
     a2 = []
     for a in args:
@@ -82,6 +98,10 @@ def syscmd(*args):
             a2.append(a)
         elif a:
             a2.extend(a)
+    if pre_cmd is not None:
+        a2_quoted = quoted(a2)
+        a2 = ["bash", "-c", "{} && {}".format(pre_cmd, a2_quoted)]
+        print(a2)
     subprocess.check_call(a2)
 
 
@@ -107,6 +127,8 @@ def read_build_log(filename):
     with open(filename) as f:
         for line in f:
             line = line.strip()
+            if line.startswith("BUILDING ") and "_ref" not in data:
+                data["_ref"] = line.removeprefix("BUILDING ")
             if line.strip() == "COMPUTING SIZES":
                 found_sizes = True
             elif found_sizes:
@@ -138,9 +160,15 @@ def do_diff(args):
     data1 = read_build_log(args[0])
     data2 = read_build_log(args[1])
 
+    ref1 = data1.pop("_ref", "(unknown ref)")
+    ref2 = data2.pop("_ref", "(unknown ref)")
+    print(f"Reference:  {ref1}")
+    print(f"Comparison: {ref2}")
     max_delta = None
     for key, value1 in data1.items():
         value2 = data2[key]
+        if key == mpy_cross_output:
+            name = "mpy-cross"
         for port in port_data.values():
             if key == "ports/{}/{}".format(port.dir, port.output):
                 name = port.name
@@ -180,8 +208,19 @@ def do_clean(args):
     ports = parse_port_list(args)
 
     print("CLEANING")
+
+    if any(port.needs_mpy_cross for port in ports):
+        syscmd("make", "-C", "mpy-cross", "clean")
+
     for port in ports:
-        syscmd("make", "-C", "ports/{}".format(port.dir), port.make_flags, "clean")
+        syscmd(
+            "make",
+            "-C",
+            "ports/{}".format(port.dir),
+            port.make_flags,
+            "clean",
+            pre_cmd=port.pre_cmd,
+        )
 
 
 def do_build(args):
@@ -195,7 +234,14 @@ def do_build(args):
 
     print("BUILDING PORTS")
     for port in ports:
-        syscmd("make", "-C", "ports/{}".format(port.dir), MAKE_FLAGS, port.make_flags)
+        syscmd(
+            "make",
+            "-C",
+            "ports/{}".format(port.dir),
+            MAKE_FLAGS,
+            port.make_flags,
+            pre_cmd=port.pre_cmd,
+        )
 
     do_sizes(args)
 
@@ -206,6 +252,10 @@ def do_sizes(args):
     ports = parse_port_list(args)
 
     print("COMPUTING SIZES")
+
+    if any(port.needs_mpy_cross for port in ports):
+        syscmd("size", mpy_cross_output)
+
     for port in ports:
         syscmd("size", "ports/{}/{}".format(port.dir, port.output))
 
diff --git a/tools/mpy-tool.py b/tools/mpy-tool.py
index 1d46d9700a6..8541d1a0118 100755
--- a/tools/mpy-tool.py
+++ b/tools/mpy-tool.py
@@ -24,40 +24,21 @@
 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 # THE SOFTWARE.
 
-# Python 2/3 compatibility code
-from __future__ import print_function
-import platform
-
-if platform.python_version_tuple()[0] == "2":
-    from binascii import hexlify as hexlify_py2
-
-    str_cons = lambda val, enc=None: str(val)
-    bytes_cons = lambda val, enc=None: bytearray(val)
-    is_str_type = lambda o: isinstance(o, str)
-    is_bytes_type = lambda o: type(o) is bytearray
-    is_int_type = lambda o: isinstance(o, int) or isinstance(o, long)  # noqa: F821
-
-    def hexlify_to_str(b):
-        x = hexlify_py2(b)
-        return ":".join(x[i : i + 2] for i in range(0, len(x), 2))
-
-else:
-    from binascii import hexlify
-
-    str_cons = str
-    bytes_cons = bytes
-    is_str_type = lambda o: isinstance(o, str)
-    is_bytes_type = lambda o: isinstance(o, bytes)
-    is_int_type = lambda o: isinstance(o, int)
+import io
+import struct
+import sys
+from binascii import hexlify
 
-    def hexlify_to_str(b):
-        return str(hexlify(b, ":"), "ascii")
+str_cons = str
+bytes_cons = bytes
+is_str_type = lambda o: isinstance(o, str)
+is_bytes_type = lambda o: isinstance(o, bytes)
+is_int_type = lambda o: isinstance(o, int)
 
 
-# end compatibility code
+def hexlify_to_str(b):
+    return str(hexlify(b, ":"), "ascii")
 
-import sys
-import struct
 
 sys.path.append(sys.path[0] + "/../py")
 import makeqstrdata as qstrutil
@@ -113,6 +94,24 @@ class Config:
 MP_NATIVE_ARCH_ARMV7EMDP = 8
 MP_NATIVE_ARCH_XTENSA = 9
 MP_NATIVE_ARCH_XTENSAWIN = 10
+MP_NATIVE_ARCH_RV32IMC = 11
+MP_NATIVE_ARCH_RV64IMC = 12
+
+MP_NATIVE_ARCH_NAMES = [
+    "NONE",
+    "X86",
+    "X64",
+    "ARMV6",
+    "ARMV6M",
+    "ARMV7M",
+    "ARMV7EM",
+    "ARMV7EMSP",
+    "ARMV7EMDP",
+    "XTENSA",
+    "XTENSAWIN",
+    "RV32IMC",
+    "RV64IMC",
+]
 
 MP_PERSISTENT_OBJ_FUN_TABLE = 0
 MP_PERSISTENT_OBJ_NONE = 1
@@ -141,6 +140,8 @@ class Config:
 MP_BC_FORMAT_VAR_UINT = 2
 MP_BC_FORMAT_OFFSET = 3
 
+MP_NATIVE_ARCH_FLAGS_PRESENT = 0x40
+
 mp_unary_op_method_name = (
     "__pos__",
     "__neg__",
@@ -305,6 +306,25 @@ class Opcode:
         MP_BC_POP_JUMP_IF_TRUE,
         MP_BC_POP_JUMP_IF_FALSE,
     )
+    ALL_OFFSET = (
+        MP_BC_UNWIND_JUMP,
+        MP_BC_JUMP,
+        MP_BC_POP_JUMP_IF_TRUE,
+        MP_BC_POP_JUMP_IF_FALSE,
+        MP_BC_JUMP_IF_TRUE_OR_POP,
+        MP_BC_JUMP_IF_FALSE_OR_POP,
+        MP_BC_SETUP_WITH,
+        MP_BC_SETUP_EXCEPT,
+        MP_BC_SETUP_FINALLY,
+        MP_BC_POP_EXCEPT_JUMP,
+        MP_BC_FOR_ITER,
+    )
+    ALL_WITH_CHILD = (
+        MP_BC_MAKE_FUNCTION,
+        MP_BC_MAKE_FUNCTION_DEFARGS,
+        MP_BC_MAKE_CLOSURE,
+        MP_BC_MAKE_CLOSURE_DEFARGS,
+    )
 
     # Create a dict mapping opcode value to opcode name.
     mapping = ["unknown" for _ in range(256)]
@@ -561,6 +581,7 @@ def __init__(
         mpy_source_file,
         mpy_segments,
         header,
+        arch_flags,
         qstr_table,
         obj_table,
         raw_code,
@@ -573,6 +594,7 @@ def __init__(
         self.mpy_segments = mpy_segments
         self.source_file = qstr_table[0]
         self.header = header
+        self.arch_flags = arch_flags
         self.qstr_table = qstr_table
         self.obj_table = obj_table
         self.raw_code = raw_code
@@ -650,6 +672,14 @@ def disassemble(self):
         print("mpy_source_file:", self.mpy_source_file)
         print("source_file:", self.source_file.str)
         print("header:", hexlify_to_str(self.header))
+        arch_index = (self.header[2] >> 2) & 0x2F
+        if arch_index >= len(MP_NATIVE_ARCH_NAMES):
+            arch_name = "UNKNOWN"
+        else:
+            arch_name = MP_NATIVE_ARCH_NAMES[arch_index]
+        print("arch:", arch_name)
+        if self.header[2] & MP_NATIVE_ARCH_FLAGS_PRESENT != 0:
+            print("arch_flags:", hex(self.arch_flags))
         print("qstr_table[%u]:" % len(self.qstr_table))
         for q in self.qstr_table:
             print("    %s" % q.str)
@@ -735,8 +765,8 @@ def freeze_constant_obj(self, obj_name, obj):
             elif config.MICROPY_LONGINT_IMPL == config.MICROPY_LONGINT_IMPL_NONE:
                 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")
+                print("static const mp_obj_int_t %s = {{&mp_type_int}, %d};" % (obj_name, obj))
+                return "MP_ROM_PTR(&%s)" % obj_name
             elif config.MICROPY_LONGINT_IMPL == config.MICROPY_LONGINT_IMPL_MPZ:
                 neg = 0
                 if obj < 0:
@@ -887,7 +917,7 @@ def __init__(self, parent_name, qstr_table, fun_data, prelude_offset, code_kind)
         self.escaped_name = unique_escaped_name
 
     def disassemble_children(self):
-        print("  children:", [rc.simple_name.str for rc in self.children])
+        self.print_children_annotated()
         for rc in self.children:
             rc.disassemble()
 
@@ -979,6 +1009,75 @@ def freeze_raw_code(self, prelude_ptr=None, type_sig=0):
         raw_code_count += 1
         raw_code_content += 4 * 4
 
+    @staticmethod
+    def decode_lineinfo(line_info: memoryview) -> "tuple[int, int, memoryview]":
+        c = line_info[0]
+        if (c & 0x80) == 0:
+            # 0b0LLBBBBB encoding
+            return (c & 0x1F), (c >> 5), line_info[1:]
+        else:
+            # 0b1LLLBBBB 0bLLLLLLLL encoding (l's LSB in second byte)
+            return (c & 0xF), (((c << 4) & 0x700) | line_info[1]), line_info[2:]
+
+    def get_source_annotation(self, ip: int, file=None) -> dict:
+        bc_offset = ip - self.offset_opcodes
+        try:
+            line_info = memoryview(self.fun_data)[self.offset_line_info : self.offset_opcodes]
+        except AttributeError:
+            return {"file": file, "line": None}
+
+        source_line = 1
+        while line_info:
+            bc_increment, line_increment, line_info = self.decode_lineinfo(line_info)
+            if bc_offset >= bc_increment:
+                bc_offset -= bc_increment
+                source_line += line_increment
+            else:
+                break
+
+        return {"file": file, "line": source_line}
+
+    def get_label(self, ip: "int | None" = None, child_num: "int | None" = None) -> str:
+        if ip is not None:
+            assert child_num is None
+            return "%s.%d" % (self.escaped_name, ip)
+        elif child_num is not None:
+            return "%s.child%d" % (self.escaped_name, child_num)
+        else:
+            return "%s" % self.escaped_name
+
+    def print_children_annotated(self) -> None:
+        """
+        Equivalent to `print("  children:", [child.simple_name.str for child in self.children])`,
+        but also includes json markers for the start and end of each one's name in that line.
+        """
+
+        labels = ["%s.children" % self.escaped_name]
+        annotation_labels = []
+        output = io.StringIO()
+        output.write("  children: [")
+        sep = ", "
+        for i, child in enumerate(self.children):
+            if i != 0:
+                output.write(sep)
+            start_col = output.tell() + 1
+            output.write(child.simple_name.str)
+            end_col = output.tell() + 1
+            labels.append(self.get_label(child_num=i))
+            annotation_labels.append(
+                {
+                    "name": self.get_label(child_num=i),
+                    "target": child.get_label(),
+                    "range": {
+                        "startCol": start_col,
+                        "endCol": end_col,
+                    },
+                },
+            )
+        output.write("]")
+
+        print(output.getvalue(), annotations={"labels": annotation_labels}, labels=labels)
+
 
 class RawCodeBytecode(RawCode):
     def __init__(self, parent_name, qstr_table, obj_table, fun_data):
@@ -987,9 +1086,58 @@ def __init__(self, parent_name, qstr_table, obj_table, fun_data):
             parent_name, qstr_table, fun_data, 0, MP_CODE_BYTECODE
         )
 
+    def get_opcode_annotations_labels(
+        self, opcode: int, ip: int, arg: int, sz: int, arg_pos: int, arg_len: int
+    ) -> "tuple[dict, list[str]]":
+        annotations = {
+            "source": self.get_source_annotation(ip),
+            "disassembly": Opcode.mapping[opcode],
+        }
+        labels = [self.get_label(ip)]
+
+        if opcode in Opcode.ALL_OFFSET:
+            annotations["link"] = {
+                "offset": arg_pos,
+                "length": arg_len,
+                "to": ip + arg + sz,
+            }
+            annotations["labels"] = [
+                {
+                    "name": self.get_label(ip),
+                    "target": self.get_label(ip + arg + sz),
+                    "range": {
+                        "startCol": arg_pos + 1,
+                        "endCol": arg_pos + arg_len + 1,
+                    },
+                },
+            ]
+
+        elif opcode in Opcode.ALL_WITH_CHILD:
+            try:
+                child = self.children[arg]
+            except IndexError:
+                # link out-of-range child to the child array itself
+                target = "%s.children" % self.escaped_name
+            else:
+                # link resolvable child to the actual child
+                target = child.get_label()
+
+            annotations["labels"] = [
+                {
+                    "name": self.get_label(ip),
+                    "target": target,
+                    "range": {
+                        "startCol": arg_pos + 1,
+                        "endCol": arg_pos + arg_len + 1,
+                    },
+                },
+            ]
+
+        return annotations, labels
+
     def disassemble(self):
         bc = self.fun_data
-        print("simple_name:", self.simple_name.str)
+        print("simple_name:", self.simple_name.str, labels=[self.get_label()])
         print("  raw bytecode:", len(bc), hexlify_to_str(bc))
         print("  prelude:", self.prelude_signature)
         print("  args:", [self.qstr_table[i].str for i in self.names[1:]])
@@ -1005,9 +1153,22 @@ def disassemble(self):
                 pass
             else:
                 arg = ""
-            print(
-                "  %-11s %s %s" % (hexlify_to_str(bc[ip : ip + sz]), Opcode.mapping[bc[ip]], arg)
+
+            pre_arg_part = "  %-11s %s" % (
+                hexlify_to_str(bc[ip : ip + sz]),
+                Opcode.mapping[bc[ip]],
             )
+            arg_part = "%s" % arg
+            annotations, labels = self.get_opcode_annotations_labels(
+                opcode=bc[ip],
+                ip=ip,
+                arg=arg,
+                sz=sz,
+                arg_pos=len(pre_arg_part) + 1,
+                arg_len=len(arg_part),
+            )
+
+            print(pre_arg_part, arg_part, annotations=annotations, labels=labels)
             ip += sz
         self.disassemble_children()
 
@@ -1083,6 +1244,8 @@ def __init__(
             MP_NATIVE_ARCH_X64,
             MP_NATIVE_ARCH_XTENSA,
             MP_NATIVE_ARCH_XTENSAWIN,
+            MP_NATIVE_ARCH_RV32IMC,
+            MP_NATIVE_ARCH_RV64IMC,
         ):
             self.fun_data_attributes = '__attribute__((section(".text,\\"ax\\",@progbits # ")))'
         else:
@@ -1098,13 +1261,15 @@ def __init__(
         ):
             # ARMV6 or Xtensa -- four byte align.
             self.fun_data_attributes += " __attribute__ ((aligned (4)))"
-        elif MP_NATIVE_ARCH_ARMV6M <= config.native_arch <= MP_NATIVE_ARCH_ARMV7EMDP:
-            # ARMVxxM -- two byte align.
+        elif (
+            MP_NATIVE_ARCH_ARMV6M <= config.native_arch <= MP_NATIVE_ARCH_ARMV7EMDP
+        ) or MP_NATIVE_ARCH_RV32IMC <= config.native_arch <= MP_NATIVE_ARCH_RV64IMC:
+            # ARMVxxM or RV{32,64}IMC -- two byte align.
             self.fun_data_attributes += " __attribute__ ((aligned (2)))"
 
     def disassemble(self):
         fun_data = self.fun_data
-        print("simple_name:", self.simple_name.str)
+        print("simple_name:", self.simple_name.str, labels=[self.get_label()])
         print(
             "  raw data:",
             len(fun_data),
@@ -1346,6 +1511,8 @@ def read_raw_code(reader, parent_name, qstr_table, obj_table, segments):
 
 
 def read_mpy(filename):
+    import re
+
     with open(filename, "rb") as fileobj:
         reader = MPYReader(filename, fileobj)
         segments = []
@@ -1358,7 +1525,7 @@ def read_mpy(filename):
         if header[1] != config.MPY_VERSION:
             raise MPYReadError(filename, "incompatible .mpy version")
         feature_byte = header[2]
-        mpy_native_arch = feature_byte >> 2
+        mpy_native_arch = (feature_byte >> 2) & 0x2F
         if mpy_native_arch != MP_NATIVE_ARCH_NONE:
             mpy_sub_version = feature_byte & 3
             if mpy_sub_version != config.MPY_SUB_VERSION:
@@ -1369,6 +1536,11 @@ def read_mpy(filename):
                 raise MPYReadError(filename, "native architecture mismatch")
         config.mp_small_int_bits = header[3]
 
+        arch_flags = 0
+        # Read the architecture-specific flag bits if present.
+        if (feature_byte & MP_NATIVE_ARCH_FLAGS_PRESENT) != 0:
+            arch_flags = reader.read_uint()
+
         # Read number of qstrs, and number of objects.
         n_qstr = reader.read_uint()
         n_obj = reader.read_uint()
@@ -1386,7 +1558,10 @@ def read_mpy(filename):
             obj_table.append(read_obj(reader, segments))
 
         # Compute the compiled-module escaped name.
-        cm_escaped_name = qstr_table[0].str.replace("/", "_")[:-3]
+        module_name = qstr_table[0].str
+        if not all(0x7F >= ord(codepoint) >= 0x20 for codepoint in module_name):
+            raise MPYReadError(filename, "cannot have unicode characters in module name")
+        cm_escaped_name = re.sub("[^a-zA-Z0-9_]", "_", "_".join(module_name.split(".")[:-1]))
 
         # Read the outer raw code, which will in turn read all its children.
         raw_code_file_offset = reader.tell()
@@ -1397,6 +1572,7 @@ def read_mpy(filename):
         filename,
         segments,
         header,
+        arch_flags,
         qstr_table,
         obj_table,
         raw_code,
@@ -1502,12 +1678,27 @@ def freeze_mpy(firmware_qstr_idents, compiled_modules):
             print("    %d," % qhash)
             qstr_content += config.MICROPY_QSTR_BYTES_IN_HASH
         print("};")
+    # CIRCUITPY-CHANGE: ROM pools store their strings in one NUL-separated blob
+    # addressed by 16-bit offsets, with a trailing end-of-blob offset. See py/qstr.h.
+    print()
+    print("const char mp_qstr_frozen_const_blob[] =")
+    offsets = []
+    offset = 0
+    for _, _, qstr, qbytes in new:
+        print('    "%s" "\\0"' % qstrutil.escape_bytes(qstr, qbytes))
+        offsets.append(offset)
+        offset += len(qbytes) + 1  # include NUL
+        qstr_content += len(qbytes) + 1
+    print("    ;")
+    if offset >= qstrutil.QSTR_BLOB_MAX:
+        raise SystemExit("frozen qstr blob is too large: %d bytes" % offset)
     print()
-    print("const qstr_len_t mp_qstr_frozen_const_lengths[] = {")
-    for _, _, _, qbytes in new:
-        print("    %d," % len(qbytes))
-        qstr_content += config.MICROPY_QSTR_BYTES_IN_LEN
-        qstr_content += len(qbytes) + 1  # include NUL
+    print("const qstr_offset_t mp_qstr_frozen_const_offsets[] = {")
+    for offset in offsets:
+        print("    %d," % offset)
+        qstr_content += 2
+    print("    sizeof(mp_qstr_frozen_const_blob) - 1,")
+    qstr_content += 2
     print("};")
     print()
     print("extern const qstr_pool_t mp_qstr_const_pool;")
@@ -1519,11 +1710,9 @@ def freeze_mpy(firmware_qstr_idents, compiled_modules):
     print("    %u, // used entries" % len(new))
     if config.MICROPY_QSTR_BYTES_IN_HASH:
         print("    (qstr_hash_t *)mp_qstr_frozen_const_hashes,")
-    print("    (qstr_len_t *)mp_qstr_frozen_const_lengths,")
-    print("    {")
-    for _, _, qstr, qbytes in new:
-        print('        "%s",' % qstrutil.escape_bytes(qstr, qbytes))
-    print("    },")
+    print("    NULL, // lengths; strings live in the blob")
+    print("    mp_qstr_frozen_const_blob,")
+    print("    mp_qstr_frozen_const_offsets,")
     print("};")
 
     # Freeze all modules.
@@ -1566,7 +1755,7 @@ def freeze_mpy(firmware_qstr_idents, compiled_modules):
         if module_name.endswith("/__init__.py"):
             short_name = module_name[: -len("/__init__.py")]
         else:
-            short_name = module_name[: -len(".py")]
+            short_name = ".".join(module_name.split(".")[:-1])
         print('MICROPY_FROZEN_LIST_ITEM("%s", "%s")' % (short_name, module_name))
     print("#endif")
 
@@ -1692,26 +1881,40 @@ def merge_mpy(compiled_modules, output_file):
             merged_mpy.extend(f.read())
     else:
         main_cm_idx = None
+        arch_flags = 0
         for idx, cm in enumerate(compiled_modules):
             feature_byte = cm.header[2]
-            mpy_native_arch = feature_byte >> 2
+            mpy_native_arch = (feature_byte >> 2) & 0x2F
             if mpy_native_arch:
                 # Must use qstr_table and obj_table from this raw_code
                 if main_cm_idx is not None:
                     raise Exception("can't merge files when more than one contains native code")
                 main_cm_idx = idx
+                arch_flags = cm.arch_flags
         if main_cm_idx is not None:
             # Shift main_cm to front of list.
             compiled_modules.insert(0, compiled_modules.pop(main_cm_idx))
 
+        if config.arch_flags is not None:
+            arch_flags = config.arch_flags
+
         header = bytearray(4)
         ## CIRCUITPY-CHANGE: "C" is used for CircuitPython
         header[0] = ord("C")
         header[1] = config.MPY_VERSION
-        header[2] = config.native_arch << 2 | config.MPY_SUB_VERSION if config.native_arch else 0
+        header[2] = (
+            (MP_NATIVE_ARCH_FLAGS_PRESENT if arch_flags != 0 else 0)
+            | config.native_arch << 2
+            | config.MPY_SUB_VERSION
+            if config.native_arch
+            else 0
+        )
         header[3] = config.mp_small_int_bits
         merged_mpy.extend(header)
 
+        if arch_flags != 0:
+            merged_mpy.extend(mp_encode_uint(arch_flags))
+
         n_qstr = 0
         n_obj = 0
         for cm in compiled_modules:
@@ -1767,7 +1970,139 @@ def copy_section(file, offset, offset2):
             f.write(merged_mpy)
 
 
-def main():
+def extract_segments(compiled_modules, basename, kinds_arg):
+    import re
+
+    kind_str = ("META", "QSTR", "OBJ", "CODE")
+    kinds = set()
+    if kinds_arg is not None:
+        for kind in kinds_arg.upper().split(","):
+            if kind in kind_str:
+                kinds.add(kind)
+            else:
+                raise Exception('unknown segment kind "%s"' % (kind,))
+    segments = []
+    for module in compiled_modules:
+        for segment in module.mpy_segments:
+            if not kinds or kind_str[segment.kind] in kinds:
+                segments.append((module.mpy_source_file, module.source_file.str, segment))
+    count_len = len(str(len(segments)))
+    sanitiser = re.compile("[^a-zA-Z0-9_.-]")
+    for counter, entry in enumerate(segments):
+        file_name, source_file, segment = entry
+        output_name = (
+            basename
+            + "_"
+            + str(counter).rjust(count_len, "0")
+            + "_"
+            + sanitiser.sub("_", source_file)
+            + "_"
+            + kind_str[segment.kind]
+            + "_"
+            + sanitiser.sub("_", str(segment.name))
+            + ".bin"
+        )
+        with open(file_name, "rb") as source:
+            with open(output_name, "wb") as output:
+                source.seek(segment.start)
+                output.write(source.read(segment.end - segment.start))
+
+
+class PrintShim:
+    """Base class for interposing extra functionality onto the global `print` method."""
+
+    def __init__(self):
+        self.wrapped_print = None
+
+    def __enter__(self):
+        global print
+
+        if self.wrapped_print is not None:
+            raise RecursionError
+
+        self.wrapped_print = print
+        print = self
+
+        return self
+
+    def __exit__(self, exc_type, exc_value, traceback):
+        global print
+
+        if self.wrapped_print is None:
+            return
+
+        print = self.wrapped_print
+        self.wrapped_print = None
+
+        self.on_exit()
+
+    def on_exit(self):
+        pass
+
+    def __call__(self, *a, **k):
+        return self.wrapped_print(*a, **k)
+
+
+class PrintIgnoreExtraArgs(PrintShim):
+    """Just strip the `annotations` and `labels` kwargs and pass down to the underlying print."""
+
+    def __call__(self, *a, annotations: dict = {}, labels: "list[str]" = (), **k):
+        return super().__call__(*a, **k)
+
+
+class PrintJson(PrintShim):
+    """Output lines as godbolt-compatible JSON with extra annotation info from `annotations` and `labels`, rather than plain text."""
+
+    def __init__(self, fp=sys.stdout, language_id: str = "mpy"):
+        super().__init__()
+        self.fp = fp
+        self.asm = {
+            "asm": [],
+            "labelDefinitions": {},
+            "languageId": language_id,
+        }
+        self.line_number: int = 0
+        self.buf: "io.StringIO | None" = None
+
+    def on_exit(self):
+        import json
+
+        if self.buf is not None:
+            # flush last partial line
+            self.__call__()
+
+        json.dump(self.asm, self.fp)
+
+    def __call__(self, *a, annotations: dict = {}, labels: "list[str]" = (), **k):
+        # ignore prints directed to an explicit output
+        if "file" in k:
+            return super().__call__(*a, **k)
+
+        if self.buf is None:
+            self.buf = io.StringIO()
+
+        super().__call__(*a, file=sys.stderr, **k)
+
+        if "end" in k:
+            # buffer partial-line prints to collect into a single AsmResultLine
+            return super().__call__(*a, file=self.buf, **k)
+        else:
+            retval = super().__call__(*a, file=self.buf, end="", **k)
+            output = self.buf.getvalue()
+            self.buf = None
+
+        asm_line = {"text": output}
+        asm_line.update(annotations)
+        self.asm["asm"].append(asm_line)
+
+        self.line_number += 1
+        for label in labels:
+            self.asm["labelDefinitions"][label] = self.line_number
+
+        return retval
+
+
+def main(args=None):
     global global_qstrs
 
     import argparse
@@ -1780,9 +2115,23 @@ def main():
         "-d", "--disassemble", action="store_true", help="output disassembled contents of files"
     )
     cmd_parser.add_argument("-f", "--freeze", action="store_true", help="freeze files")
+    cmd_parser.add_argument(
+        "-j",
+        "--json",
+        action="store_true",
+        help="output hexdump, disassembly, and frozen code as JSON with extra metadata",
+    )
     cmd_parser.add_argument(
         "--merge", action="store_true", help="merge multiple .mpy files into one"
     )
+    cmd_parser.add_argument(
+        "-e", "--extract", metavar="BASE", type=str, help="write segments into separate files"
+    )
+    cmd_parser.add_argument(
+        "--extract-only",
+        metavar="KIND[,...]",
+        help="extract only segments of the given type (meta, qstr, obj, code)",
+    )
     cmd_parser.add_argument("-q", "--qstr-header", help="qstr header file to freeze against")
     cmd_parser.add_argument(
         "-mlongint-impl",
@@ -1797,9 +2146,15 @@ def main():
         default=16,
         help="mpz digit size used by target (default 16)",
     )
+    cmd_parser.add_argument(
+        "-march-flags",
+        metavar="F",
+        type=int,
+        help="architecture flags value to set in the output file (strips existing flags if not present)",
+    )
     cmd_parser.add_argument("-o", "--output", default=None, help="output file")
     cmd_parser.add_argument("files", nargs="+", help="input .mpy files")
-    args = cmd_parser.parse_args()
+    args = cmd_parser.parse_args(args)
 
     # set config values relevant to target machine
     config.MICROPY_LONGINT_IMPL = {
@@ -1809,6 +2164,7 @@ def main():
     }[args.mlongint_impl]
     config.MPZ_DIG_SIZE = args.mmpz_dig_size
     config.native_arch = MP_NATIVE_ARCH_NONE
+    config.arch_flags = args.march_flags
 
     # set config values for qstrs, and get the existing base set of qstrs
     # already in the firmware
@@ -1832,24 +2188,40 @@ def main():
         print(er, file=sys.stderr)
         sys.exit(1)
 
-    if args.hexdump:
-        hexdump_mpy(compiled_modules)
+    if args.json:
+        if args.freeze:
+            print_shim = PrintJson(sys.stdout, language_id="c")
+        elif args.hexdump:
+            print_shim = PrintJson(sys.stdout, language_id="stderr")
+        elif args.disassemble:
+            print_shim = PrintJson(sys.stdout, language_id="mpy")
+        else:
+            print_shim = PrintJson(sys.stdout)
+    else:
+        print_shim = PrintIgnoreExtraArgs()
 
-    if args.disassemble:
+    with print_shim:
         if args.hexdump:
-            print()
-        disassemble_mpy(compiled_modules)
+            hexdump_mpy(compiled_modules)
 
-    if args.freeze:
-        try:
-            freeze_mpy(firmware_qstr_idents, compiled_modules)
-        except FreezeError as er:
-            print(er, file=sys.stderr)
-            sys.exit(1)
+        if args.disassemble:
+            if args.hexdump:
+                print()
+            disassemble_mpy(compiled_modules)
+
+        if args.freeze:
+            try:
+                freeze_mpy(firmware_qstr_idents, compiled_modules)
+            except FreezeError as er:
+                print(er, file=sys.stderr)
+                sys.exit(1)
 
     if args.merge:
         merge_mpy(compiled_modules, args.output)
 
+    if args.extract:
+        extract_segments(compiled_modules, args.extract, args.extract_only)
+
 
 if __name__ == "__main__":
     main()
diff --git a/tools/mpy_ld.py b/tools/mpy_ld.py
index efde6af6ba5..abb9ab4f4bd 100755
--- a/tools/mpy_ld.py
+++ b/tools/mpy_ld.py
@@ -29,7 +29,8 @@
 """
 
 import sys, os, struct, re
-from elftools.elf import elffile
+from elftools.elf import elffile, relocation
+import ar_util
 
 sys.path.append(os.path.dirname(__file__) + "/../py")
 import makeqstrdata as qstrutil
@@ -37,6 +38,7 @@
 # MicroPython constants
 MPY_VERSION = 6
 MPY_SUB_VERSION = 3
+MPY_ARCH_FLAGS = 0x40
 MP_CODE_BYTECODE = 2
 MP_CODE_NATIVE_VIPER = 4
 MP_NATIVE_ARCH_X86 = 1
@@ -47,18 +49,24 @@
 MP_NATIVE_ARCH_ARMV7EMDP = 8
 MP_NATIVE_ARCH_XTENSA = 9
 MP_NATIVE_ARCH_XTENSAWIN = 10
+MP_NATIVE_ARCH_RV32IMC = 11
+MP_NATIVE_ARCH_RV64IMC = 12
 MP_PERSISTENT_OBJ_STR = 5
-MP_SCOPE_FLAG_VIPERRELOC = 0x10
-MP_SCOPE_FLAG_VIPERRODATA = 0x20
-MP_SCOPE_FLAG_VIPERBSS = 0x40
+## CIRCUITPY-CHANGE: FLAG_ASYNC
+MP_SCOPE_FLAG_VIPERRELOC = 0x20
+MP_SCOPE_FLAG_VIPERRODATA = 0x40
+MP_SCOPE_FLAG_VIPERBSS = 0x80
 MP_SMALL_INT_BITS = 31
-MP_FUN_TABLE_MP_TYPE_TYPE_OFFSET = 73
+## CIRCUITPY-CHANGE (due to added assert_native_inited)
+MP_FUN_TABLE_MP_TYPE_TYPE_OFFSET = 74
 
 # ELF constants
 R_386_32 = 1
+R_RISCV_32 = 1
 R_X86_64_64 = 1
 R_XTENSA_32 = 1
 R_386_PC32 = 2
+R_RISCV_64 = 2
 R_X86_64_PC32 = 2
 R_ARM_ABS32 = 2
 R_386_GOT32 = 3
@@ -69,59 +77,229 @@
 R_386_GOTOFF = 9
 R_386_GOTPC = 10
 R_ARM_THM_CALL = 10
+R_XTENSA_ASM_EXPAND = 11
+R_RISCV_BRANCH = 16
+R_RISCV_JAL = 17
+R_RISCV_CALL = 18
+R_RISCV_CALL_PLT = 19
 R_XTENSA_DIFF32 = 19
 R_XTENSA_SLOT0_OP = 20
+R_RISCV_GOT_HI20 = 20
+R_RISCV_TLS_GD_HI20 = 22
+R_RISCV_PCREL_HI20 = 23
+R_RISCV_PCREL_LO12_I = 24
+R_RISCV_PCREL_LO12_S = 25
 R_ARM_BASE_PREL = 25  # aka R_ARM_GOTPC
 R_ARM_GOT_BREL = 26  # aka R_ARM_GOT32
 R_ARM_THM_JUMP24 = 30
+R_RISCV_HI20 = 26
+R_RISCV_LO12_I = 27
+R_RISCV_LO12_S = 28
+R_RISCV_TPREL_HI20 = 29
+R_RISCV_TPREL_LO12_I = 30
+R_RISCV_TPREL_LO12_S = 31
+R_RISCV_TPREL_ADD = 32
+R_RISCV_ADD8 = 33
+R_RISCV_ADD16 = 34
+R_RISCV_ADD32 = 35
+R_RISCV_ADD64 = 36
+R_RISCV_SUB8 = 37
+R_RISCV_SUB16 = 38
+R_RISCV_SUB32 = 39
+R_RISCV_SUB64 = 40
+R_RISCV_GOT32_PCREL = 41
 R_X86_64_GOTPCREL = 9
 R_X86_64_REX_GOTPCRELX = 42
 R_386_GOT32X = 43
+R_RISCV_ALIGN = 43
+R_RISCV_RVC_BRANCH = 44
+R_RISCV_RVC_JUMP = 45
+R_RISCV_RELAX = 51
+R_RISCV_SUB6 = 52
+R_RISCV_SET6 = 53
+R_RISCV_SET8 = 54
+R_RISCV_SET16 = 55
+R_RISCV_SET32 = 56
+R_RISCV_32_PCREL = 57
+R_RISCV_PLT32 = 59
 R_XTENSA_PDIFF32 = 59
+R_XTENSA_NDIFF32 = 62
+R_RISCV_SET_ULEB128 = 60
+R_RISCV_SUB_ULEB128 = 61
+R_RISCV_TLSDESC_HI20 = 62
+R_RISCV_TLSDESC_LOAD_LO12 = 63
+R_RISCV_TLSDESC_ADD_LO12 = 64
+R_RISCV_TLSDESC_CALL = 65
+R_ARM_GOT_PREL = 96
 
 ################################################################################
 # Architecture configuration
 
 
+def fit_signed(bits, value):
+    return (value >> bits) == 0 or (value >> bits) == -1
+
+
+# Note: all trampoline jump function arguments are raw offsets calculated from
+#       the start of the text segment with no relocation applied beforehand.
+
+
 def asm_jump_x86(entry):
-    return struct.pack("> 11 == 0 or b_off >> 11 == -1, b_off
-    return struct.pack("> 1 & 0x07FF))
+    entry -= 4
+    if fit_signed(11, entry):
+        # Signed value fits in 12 bits.
+        b0 = 0xE000 | ((entry >> 1) & 0x07FF)
+        return struct.pack("
+        #   pop {r0, pc}
+        entry -= 2  # skip "push {r0, lr}"
+        b0 = 0xB400 | 0x0100 | 0x0001  # push, lr, r0
+        b1 = 0xF000 | ((entry >> 12) & 0x07FF)
+        b2 = 0xF800 | ((entry >> 1) & 0x07FF)
+        b3 = 0xBC00 | 0x0100 | 0x0001  # pop, pc, r0
+        return struct.pack("> 11 == 0 or b_off >> 11 == -1:
+    entry -= 4
+    if fit_signed(11, entry):
         # Signed value fits in 12 bits
-        b0 = 0xE000 | (b_off >> 1 & 0x07FF)
-        b1 = 0
+        b0 = 0xE000 | ((entry >> 1) & 0x07FF)
+        return struct.pack("> 12 & 0x07FF)
-        b1 = 0xB800 | (b_off >> 1 & 0x7FF)
-    return struct.pack("> 12) & 0x07FF)
+        b1 = 0xB800 | ((entry >> 1) & 0x07FF)
+        return struct.pack("> 8)
+    if fit_signed(17, entry - 8):
+        jump_op = ((entry - 8) << 6) | 6
+        return struct.pack("> 8)
+    else:
+        raise LinkError("jumps larger than 128KiB are not supported")
+
+
+def asm_jump_riscv(entry):
+    if fit_signed(11, entry):
+        # c.j entry
+        return struct.pack(
+            "> 2)
+            | ((entry & 0x300) << 1)
+            | ((entry & 0x80) >> 1)
+            | ((entry & 0x40) << 1)
+            | ((entry & 0x20) >> 3)
+            | ((entry & 0x10) << 7)
+            | ((entry & 0x0E) << 2),
+        )
+    elif fit_signed(31, entry - 8):
+        # auipc t6, HI(entry)
+        # jalr  zero, t6, LO(entry)
+        upper, lower = split_riscv_address(entry)
+        return struct.pack(
+            "> 16 & 0xFF
 
 
+def split_riscv_address(value):
+    # The address can be represented with just the lowest 12 bits
+    if value < 0 and value > -2048:
+        value = 4096 + value
+        return 0, value
+    # 2s complement
+    if value < 0:
+        value = 0x100000000 + value
+    upper, lower = (value & 0xFFFFF000), (value & 0xFFF)
+    if lower & 0x800 != 0:
+        # Reverse lower part sign extension
+        upper += 0x1000
+    return upper & 0xFFFFFFFF, lower & 0xFFFFFFFF
+
+
 def xxd(text):
     for i in range(0, len(text), 16):
         print("{:08x}:".format(i), end="")
@@ -306,6 +523,7 @@ def __init__(self, arch):
         self.known_syms = {}  # dict of symbols that are defined
         self.unresolved_syms = []  # list of unresolved symbols
         self.mpy_relocs = []  # list of relocations needed in the output .mpy file
+        self.externs = {}  # dict of externally-defined symbols
 
     def check_arch(self, arch_name):
         if arch_name != self.arch.name:
@@ -316,10 +534,9 @@ def print_sections(self):
         for sec in self.sections:
             log(LOG_LEVEL_2, "  {:08x} {} size={}".format(sec.addr, sec.name, len(sec.data)))
 
-    def find_addr(self, name):
+    def find_sym(self, name):
         if name in self.known_syms:
-            s = self.known_syms[name]
-            return s.section.addr + s["st_value"]
+            return self.known_syms[name]
         raise LinkError("unknown symbol: {}".format(name))
 
 
@@ -329,7 +546,7 @@ def build_got_generic(env):
         for r in sec.reloc:
             s = r.sym
             if not (
-                s.entry["st_info"]["bind"] == "STB_GLOBAL"
+                s.entry["st_info"]["bind"] in ("STB_GLOBAL", "STB_WEAK")
                 and r["r_info_type"] in env.arch.arch_got
             ):
                 continue
@@ -395,10 +612,17 @@ def populate_got(env):
         sym = got_entry.sym
         if hasattr(sym, "resolved"):
             sym = sym.resolved
-        sec = sym.section
-        addr = sym["st_value"]
-        got_entry.sec_name = sec.name
-        got_entry.link_addr += sec.addr + addr
+        if sym.name in env.externs:
+            got_entry.sec_name = ".external.fixed_addr"
+            got_entry.link_addr = env.externs[sym.name]
+        elif sym.name in ("memcpy", "memset", "memmove"):
+            got_entry.sec_name = f".external.{sym.name}"
+            got_entry.link_addr = 0
+        else:
+            sec = sym.section
+            addr = sym["st_value"]
+            got_entry.sec_name = sec.name
+            got_entry.link_addr += sec.addr + addr
 
     # Get sorted GOT, sorted by external, text, rodata, bss so relocations can be combined
     got_list = sorted(
@@ -424,6 +648,15 @@ def populate_got(env):
             dest = int(got_entry.name.split("+")[1], 16) // env.arch.word_size
         elif got_entry.sec_name == ".external.mp_fun_table":
             dest = got_entry.sym.mp_fun_table_offset
+        elif got_entry.sec_name == ".external.fixed_addr":
+            # Fixed-address symbols should not be relocated.
+            continue
+        elif got_entry.sec_name.startswith(".external.mem"):
+            # memset/memmove/memcpy
+            if "memset" in got_entry.sec_name:
+                dest = MP_FUN_TABLE_MEMSET
+            else:
+                dest = MP_FUN_TABLE_MEMMOVE
         elif got_entry.sec_name.startswith(".text"):
             dest = ".text"
         elif got_entry.sec_name.startswith(".rodata"):
@@ -470,6 +703,8 @@ def do_relocation_text(env, text_addr, r):
     # Default relocation type and name for logging
     reloc_type = "le32"
     log_name = None
+    addr = None
+    value = None
 
     if (
         env.arch.name == "EM_386"
@@ -530,10 +765,14 @@ def do_relocation_text(env, text_addr, r):
         # Relcation pointing to GOT
         reloc = addr = env.got_entries[s.name].offset
 
-    elif env.arch.name == "EM_X86_64" and r_info_type in (
-        R_X86_64_GOTPCREL,
-        R_X86_64_REX_GOTPCRELX,
-    ):
+    elif (
+        env.arch.name == "EM_X86_64"
+        and r_info_type
+        in (
+            R_X86_64_GOTPCREL,
+            R_X86_64_REX_GOTPCRELX,
+        )
+    ) or (env.arch.name == "EM_ARM" and r_info_type == R_ARM_GOT_PREL):
         # Relcation pointing to GOT
         got_entry = env.got_entries[s.name]
         addr = env.got_section.addr + got_entry.offset
@@ -562,18 +801,63 @@ def do_relocation_text(env, text_addr, r):
         reloc = addr - r_offset
         reloc_type = "xtensa_l32r"
 
-    elif env.arch.name == "EM_XTENSA" and r_info_type in (R_XTENSA_DIFF32, R_XTENSA_PDIFF32):
-        if s.section.name.startswith(".text"):
-            # it looks like R_XTENSA_[P]DIFF32 into .text is already correctly relocated
+    elif env.arch.name == "EM_XTENSA" and r_info_type in (
+        R_XTENSA_DIFF32,
+        R_XTENSA_PDIFF32,
+        R_XTENSA_NDIFF32,
+        R_XTENSA_ASM_EXPAND,
+    ):
+        if not hasattr(s, "section") or s.section.name.startswith(".text"):
+            # Ignore relaxation relocations.
             return
         assert 0
 
+    elif env.arch.name == "EM_RISCV" and r_info_type in (
+        R_RISCV_TLS_GD_HI20,
+        R_RISCV_TLSDESC_HI20,
+        R_RISCV_TLSDESC_LOAD_LO12,
+        R_RISCV_TLSDESC_ADD_LO12,
+        R_RISCV_TLSDESC_CALL,
+    ):
+        # TLS relocations are not supported.
+        raise LinkError("{}: RISC-V TLS relocation: {}".format(s.filename, s.name))
+
+    elif env.arch.name == "EM_RISCV" and r_info_type in (
+        R_RISCV_TPREL_HI20,
+        R_RISCV_TPREL_LO12_I,
+        R_RISCV_TPREL_LO12_S,
+        R_RISCV_TPREL_ADD,
+    ):
+        # ThreadPointer-relative relocations are not supported.
+        raise LinkError("{}: RISC-V TP-relative relocation: {}".format(s.filename, s.name))
+
+    elif env.arch.name == "EM_RISCV" and r_info_type in (R_RISCV_SET_ULEB128, R_RISCV_SUB_ULEB128):
+        # 128-bit value relocations are not supported
+        raise LinkError("{}: RISC-V ULEB128 relocation: {}".format(s.filename, s.name))
+
+    elif env.arch.name == "EM_RISCV" and r_info_type in (R_RISCV_RELAX, R_RISCV_ALIGN):
+        # To keep things simple, no relocations are relaxed and thus no
+        # size optimisation is performed even if there is the chance, along
+        # with no offsets to fix up.
+        return
+
+    elif env.arch.name == "EM_RISCV":
+        (addr, value) = process_riscv32_relocation(env, text_addr, r)
+
+    elif env.arch.name == "EM_ARM" and r_info_type == R_ARM_ABS32:
+        # Absolute relocation, handled as a data relocation.
+        do_relocation_data(env, text_addr, r)
+        return
+
     else:
         # Unknown/unsupported relocation
-        assert 0, r_info_type
+        assert 0, (r_info_type, s.name, s.entry, env.arch.name)
 
     # Write relocation
-    if reloc_type == "le32":
+    if env.arch.name == "EM_RISCV":
+        # This case is already handled by `process_riscv_relocation`.
+        pass
+    elif reloc_type == "le32":
         (existing,) = struct.unpack_from(" {:08x}".format(r_offset, log_name, addr))
+    if addr is not None:
+        log(LOG_LEVEL_3, "  {:08x} {} -> {:08x}".format(r_offset, log_name, addr))
+    else:
+        log(LOG_LEVEL_3, "  {:08x} {} == {:08x}".format(r_offset, log_name, value))
 
 
 def do_relocation_data(env, text_addr, r):
@@ -624,12 +911,16 @@ def do_relocation_data(env, text_addr, r):
         and r_info_type == R_ARM_ABS32
         or env.arch.name == "EM_XTENSA"
         and r_info_type == R_XTENSA_32
+        or env.arch.name == "EM_RISCV"
+        and r_info_type in (R_RISCV_32, R_RISCV_64)
     ):
         # Relocation in data.rel.ro to internal/external symbol
         if env.arch.word_size == 4:
-            struct_type = "> 1)
+                | ((reloc & 0x20) >> 3)
+                | ((reloc & 0x18) << 7)
+                | ((reloc & 0x06) << 2)
+            )
+            & 0xFFFF,
+        )
+    elif reloc_type == "riscv_cj":
+        # Patch the target of a compressed jump opcode
+        (existing,) = struct.unpack_from("> 2)
+                | ((reloc & 0x300) << 1)
+                | ((reloc & 0x80) >> 1)
+                | ((reloc & 0x40) << 1)
+                | ((reloc & 0x20) >> 3)
+                | ((reloc & 0x10) << 7)
+                | ((reloc & 0x0E) << 2)
+            )
+            & 0xFFFF,
+        )
+    elif reloc_type == "riscv_call":
+        # Patch a pair of opcodes forming a call operation
+        upper, lower = split_riscv_address(reloc)
+        (existing,) = struct.unpack_from("> 4)
+                | ((reloc & 0x7E0) << 20)
+                | ((reloc & 0x1E) << 7)
+            )
+            & 0xFFFFFFFF,
+        )
+    elif reloc_type == "riscv_j":
+        # Patch a jump/jump with link opcode
+        (existing,) = struct.unpack_from("")
+                    env.sections.insert(1, section)
+                    r = relocation.Relocation({}, None)
+                    r.index = get_memx_function_index(n)
+                    r.offset = reloc
+                    section.reloc.append(r)
+                    section.reloc_name = "unknown"
+                sym.section = section
             else:
-                raise LinkError("{}: undefined symbol: {}".format(sym.filename, sym.name))
+                undef_errors.append("{}: undefined symbol: {}".format(sym.filename, sym.name))
+
+    for sym in env.externs:
+        if sym in env.known_syms:
+            log(
+                LOG_LEVEL_1,
+                "Symbol {} is a fixed-address symbol at {:08x} and is also provided from an object file".format(
+                    sym, env.externs[sym]
+                ),
+            )
+
+    if undef_errors:
+        raise LinkError("\n".join(undef_errors))
+
+    # Generate the entry trampoline assuming the offset is already known.
+
+    text_alignment = env.find_sym("mpy_init").section.alignment
+    if env.arch.name in ("EM_386", "EM_X86_64"):
+        show_warning = text_alignment not in (1, 4)
+    elif env.arch.name in ("EM_ARM", "EM_XTENSA"):
+        show_warning = text_alignment != 4
+    elif env.arch.name == "EM_RISCV":
+        show_warning = text_alignment != 2
+    else:
+        show_warning = True
+
+    if show_warning:
+        log(
+            LOG_LEVEL_1,
+            f"A .text section with an alignment of {text_alignment} bytes for {env.arch.name} is not tested and may not work",
+        )
+
+    jump = generate_entry_point_jump(env)
+    env.entry_trampoline_len = len(jump)
 
     # Align sections, assign their addresses, and create full_text
-    env.full_text = bytearray(env.arch.asm_jump(8))  # dummy, to be filled in later
+    env.full_text = bytearray(jump)
     env.full_rodata = bytearray(0)
     env.full_bss = bytearray(0)
     for sec in env.sections:
@@ -828,6 +1480,8 @@ def link_objects(env, native_qstr_vals_len):
                 do_relocation_text(env, sec.addr, r)
             elif sec.name.startswith(".data.rel.ro"):
                 do_relocation_data(env, sec.addr, r)
+            elif sec.name.startswith(".internal"):
+                env.mpy_relocs.append((".text", sec.addr + r.offset, r.index))
             else:
                 assert 0, sec.name
 
@@ -835,6 +1489,15 @@ def link_objects(env, native_qstr_vals_len):
 ################################################################################
 # .mpy output
 
+MP_FUN_TABLE_MEMSET = 50
+MP_FUN_TABLE_MEMMOVE = 51
+
+
+def get_memx_function_index(f):
+    if f == "memset":
+        return MP_FUN_TABLE_MEMSET
+    return MP_FUN_TABLE_MEMMOVE
+
 
 class MPYOutput:
     def open(self, fname):
@@ -867,6 +1530,12 @@ def write_qstr(self, s):
             self.write_bytes(b"\x00")
 
     def write_reloc(self, base, offset, dest, n):
+        if dest > 2 and n > 1:
+            # dest>2 cannot encode n, so do it manually.
+            for _ in range(n):
+                self.write_reloc(base, offset, dest, 1)
+                offset += 1
+            return
         need_offset = not (base == self.prev_base and offset == self.prev_offset + 1)
         self.prev_offset = offset + n - 1
         if dest <= 2:
@@ -887,10 +1556,13 @@ def write_reloc(self, base, offset, dest, n):
             self.write_uint(n)
 
 
-def build_mpy(env, entry_offset, fmpy, native_qstr_vals):
-    # Write jump instruction to start of text
-    jump = env.arch.asm_jump(entry_offset)
-    env.full_text[: len(jump)] = jump
+def build_mpy(env, fmpy, internal_name, native_qstr_vals, arch_flags):
+    # Rewrite the entry trampoline if the proper value isn't known earlier, and
+    # ensure the trampoline size remains the same.
+    if env.arch.delayed_entry_offset:
+        jump = generate_entry_point_jump(env)
+        env.full_text[: len(jump)] = jump
+        assert len(jump) == env.entry_trampoline_len
 
     log(LOG_LEVEL_1, "arch:         {}".format(env.arch.name))
     log(LOG_LEVEL_1, "text size:    {}".format(len(env.full_text)))
@@ -904,13 +1576,17 @@ def build_mpy(env, entry_offset, fmpy, native_qstr_vals):
     out = MPYOutput()
     out.open(fmpy)
 
+    header_flags = env.arch.mpy_feature | MPY_SUB_VERSION
+    if arch_flags != 0:
+        header_flags |= MPY_ARCH_FLAGS
+
     # MPY: header
-    out.write_bytes(
-        bytearray(
-            # CIRCUITPY-CHANGE: CircuitPython uses "C"
-            [ord("C"), MPY_VERSION, env.arch.mpy_feature | MPY_SUB_VERSION, MP_SMALL_INT_BITS]
-        )
-    )
+    # CIRCUITPY-CHANGE: CircuitPython uses "C"
+    out.write_bytes(bytearray([ord("C"), MPY_VERSION, header_flags, MP_SMALL_INT_BITS]))
+
+    # MPY: arch flags
+    if arch_flags != 0:
+        out.write_uint(arch_flags)
 
     # MPY: n_qstr
     out.write_uint(1 + len(native_qstr_vals))
@@ -919,7 +1595,7 @@ def build_mpy(env, entry_offset, fmpy, native_qstr_vals):
     out.write_uint(0)
 
     # MPY: qstr table
-    out.write_qstr(fmpy)  # filename
+    out.write_qstr(internal_name)  # filename
     for q in native_qstr_vals:
         out.write_qstr(q)
 
@@ -1005,19 +1681,13 @@ def do_preprocess(args):
         args.output = args.files[0][:-1] + "config.h"
     static_qstrs, qstr_vals = extract_qstrs(args.files)
     with open(args.output, "w") as f:
-        print(
-            "#include \n"
-            "typedef uintptr_t mp_uint_t;\n"
-            "typedef intptr_t mp_int_t;\n"
-            "typedef uintptr_t mp_off_t;",
-            file=f,
-        )
+        print("#include \ntypedef uintptr_t mp_off_t;", file=f)
         for i, q in enumerate(static_qstrs):
             print("#define %s (%u)" % (q, i + 1), file=f)
         for i, q in enumerate(sorted(qstr_vals)):
             print("#define %s (mp_native_qstr_table[%d])" % (q, i + 1), file=f)
         print("extern const uint16_t mp_native_qstr_table[];", file=f)
-        print("extern const mp_uint_t mp_native_obj_table[];", file=f)
+        print("extern const uintptr_t mp_native_obj_table[];", file=f)
 
 
 def do_link(args):
@@ -1034,34 +1704,155 @@ def do_link(args):
     log(LOG_LEVEL_2, "qstr vals: " + ", ".join(native_qstr_vals))
     env = LinkEnv(args.arch)
     try:
-        for file in args.files:
-            load_object_file(env, file)
+        if args.externs:
+            env.externs = parse_linkerscript(args.externs)
+
+        # Load object files
+        for fn in args.files:
+            with open(fn, "rb") as f:
+                load_object_file(env, f, fn)
+
+        if args.libs:
+            ar_util.init_cache(
+                f"{ar_util.DEFAULT_CACHE_BASE_PATH}-{args.arch}", ar_util.DEFAULT_CACHE_PREFIX
+            )
+            # Load archive info
+            archives = []
+            for item in args.libs:
+                archives.extend(ar_util.load_archive(item))
+            # List symbols to look for
+            syms = set(sym.name for sym in env.unresolved_syms)
+            # Resolve symbols from libs
+            lib_objs, _ = ar_util.resolve(archives, syms)
+            # Load extra object files from libs
+            for ar, obj in lib_objs:
+                obj_name = ar.fn + ":" + obj
+                log(LOG_LEVEL_2, "using " + obj_name)
+                with ar.open(obj) as f:
+                    load_object_file(env, f, obj_name)
+
         link_objects(env, len(native_qstr_vals))
-        build_mpy(env, env.find_addr("mpy_init"), args.output, native_qstr_vals)
+        if args.source_name:
+            internal_name = args.source_name
+        else:
+            import pathlib
+
+            path = pathlib.Path(args.output)
+            internal_name = path.name
+        build_mpy(env, args.output, internal_name, native_qstr_vals, args.arch_flags)
     except LinkError as er:
         print("LinkError:", er.args[0])
         sys.exit(1)
 
 
+def parse_linkerscript(source):
+    # This extracts fixed-address symbol lists from linkerscripts, only parsing
+    # a small subset of all possible directives.  Right now the only
+    # linkerscript file this is really tested against is the ESP8266's builtin
+    # ROM functions list ($SDK/ld/eagle.rom.addr.v6.ld).
+    #
+    # The parser should be able to handle symbol entries inside ESP-IDF's ROM
+    # symbol lists for the ESP32 range of MCUs as well (see *.ld files in
+    # $SDK/components/esp_rom//).
+
+    symbols = {}
+
+    LINE_REGEX = re.compile(
+        r"^(?PPROVIDE\()?"  # optional weak marker start
+        r"(?P[a-zA-Z_]\w*)"  # symbol name
+        r"=0x(?P
[\da-fA-F]{1,8})*" # symbol address + r"(?(weak)\));$", # optional weak marker end and line terminator + re.ASCII, + ) + + inside_comment = False + for line in (line.strip() for line in source.readlines()): + if line.startswith("/*") and not inside_comment: + if not line.endswith("*/"): + inside_comment = True + continue + if inside_comment: + if line.endswith("*/"): + inside_comment = False + continue + if line.startswith("//"): + continue + match = LINE_REGEX.match("".join(line.split())) + if not match: + continue + tokens = match.groupdict() + symbol = tokens["symbol"] + address = int(tokens["address"], 16) + if symbol in symbols: + raise ValueError(f"Symbol {symbol} already defined") + symbols[symbol] = address + return symbols + + +RV32_EXTENSIONS = { + "zba": 1 << 0, + "zcmp": 1 << 1, +} + + +def validate_arch_flags(args): + if args.arch_flags is None: + args.arch_flags = 0 + return + if args.arch != "rv32imc": + raise ValueError('Architecture "{}" does not support extra flags'.format(args.arch)) + if (args.arch_flags.startswith("0") and len(args.arch_flags) > 2) or args.arch_flags.isdigit(): + if args.arch_flags[1] in "bB": + base = 2 + elif args.arch_flags[1] in "xX": + base = 16 + else: + base = 10 + args.arch_flags = int(args.arch_flags, base) + else: + flags_value = 0 + for flag in args.arch_flags.lower().split(","): + if flag not in RV32_EXTENSIONS: + raise ValueError('Invalid architecture flags value "{}"'.format(flag)) + flags_value |= RV32_EXTENSIONS[flag] + args.arch_flags = flags_value + + def main(): import argparse - cmd_parser = argparse.ArgumentParser(description="Run scripts on the pyboard.") + cmd_parser = argparse.ArgumentParser(description="Link native object files into a MPY bundle.") cmd_parser.add_argument( "--verbose", "-v", action="count", default=1, help="increase verbosity" ) cmd_parser.add_argument("--arch", default="x64", help="architecture") + cmd_parser.add_argument("--arch-flags", default=None, help="optional architecture flags") + cmd_parser.add_argument( + "--source-name", default=None, help="override the file name written to the .mpy file" + ) cmd_parser.add_argument("--preprocess", action="store_true", help="preprocess source files") cmd_parser.add_argument("--qstrs", default=None, help="file defining additional qstrs") + cmd_parser.add_argument( + "--libs", "-l", dest="libs", action="append", help="static .a libraries to link" + ) cmd_parser.add_argument( "--output", "-o", default=None, help="output .mpy file (default to input with .o->.mpy)" ) + cmd_parser.add_argument( + "--externs", + "-e", + type=argparse.FileType("rt"), + default=None, + help="linkerscript providing fixed-address symbols to augment symbol resolution", + ) cmd_parser.add_argument("files", nargs="+", help="input files") args = cmd_parser.parse_args() global log_level log_level = args.verbose + validate_arch_flags(args) + if args.preprocess: do_preprocess(args) else: diff --git a/tools/pyboard.py b/tools/pyboard.py index 0921d5feae5..c535a619672 100755 --- a/tools/pyboard.py +++ b/tools/pyboard.py @@ -51,6 +51,7 @@ import ast import errno import os +import stat import struct import sys import time @@ -200,8 +201,9 @@ def inWaiting(self): class ProcessPtyToTerminal: - """Execute a process which creates a PTY and prints secondary PTY as - first line of its output, and emulate serial connection using + # CIRCUITPY-CHANGE: the PTY line need not be the first line of output. + """Execute a process which creates a PTY and prints secondary PTY in + a line of its startup output, and emulate serial connection using this PTY.""" def __init__(self, cmd): @@ -216,15 +218,24 @@ def __init__(self, cmd): preexec_fn=os.setsid, stdin=subprocess.PIPE, stdout=subprocess.PIPE, - stderr=subprocess.PIPE, + stderr=subprocess.STDOUT, ) - pty_line = self.subp.stderr.readline().decode("utf-8") - m = re.search(r"/dev/pts/[0-9]+", pty_line) + # CIRCUITPY-CHANGE: skip lines printed before the PTY line, such as + # warnings Zephyr's native_sim prints at startup. + startup_lines = [] + while True: + pty_line = self.subp.stdout.readline().decode("utf-8") + startup_lines.append(pty_line) + m = re.search(r"/dev/pts/[0-9]+", pty_line) + if m or not pty_line: + break if not m: - print("Error: unable to find PTY device in startup line:", pty_line) + print("Error: unable to find PTY device in startup output:", "".join(startup_lines)) self.close() sys.exit(1) pty = m.group() + # Compensate for some boards taking a bit longer to start + time.sleep(0.1) # rtscts, dsrdtr params are to workaround pyserial bug: # http://stackoverflow.com/questions/34831131/pyserial-does-not-play-well-with-virtual-port self.serial = serial.Serial(pty, interCharTimeout=1, rtscts=True, dsrdtr=True) @@ -246,14 +257,22 @@ def inWaiting(self): class Pyboard: def __init__( - self, device, baudrate=115200, user="micro", password="python", wait=0, exclusive=True + self, + device, + baudrate=115200, + user="micro", + password="python", + wait=0, + exclusive=True, + timeout=None, + write_timeout=5, ): self.in_raw_repl = False self.use_raw_paste = True if device.startswith("exec:"): self.serial = ProcessToSerial(device[len("exec:") :]) elif device.startswith("execpty:"): - self.serial = ProcessPtyToTerminal(device[len("qemupty:") :]) + self.serial = ProcessPtyToTerminal(device[len("execpty:") :]) 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) @@ -262,7 +281,12 @@ def __init__( import serial.tools.list_ports # Set options, and exclusive if pyserial supports it - serial_kwargs = {"baudrate": baudrate, "interCharTimeout": 1} + serial_kwargs = { + "baudrate": baudrate, + "timeout": timeout, + "write_timeout": write_timeout, + "interCharTimeout": 1, + } if serial.__version__ >= "3.3": serial_kwargs["exclusive"] = exclusive @@ -299,37 +323,77 @@ def __init__( if delayed: print("") + if device.startswith("execpty:"): + self.is_pty = True + else: + self.is_pty = self._is_pty_device(device) + + @staticmethod + def _is_pty_device(device): + """Detect if device is a PTY (pseudo-terminal), e.g. used by QEMU.""" + if device.startswith("/dev/pts/"): + try: + st = os.stat(device) + if stat.S_ISCHR(st.st_mode) and os.major(st.st_rdev) == 136: + return True + except (OSError, AttributeError): + pass + return False + def close(self): self.serial.close() - def read_until(self, min_num_bytes, ending, timeout=10, data_consumer=None): - # if data_consumer is used then data is not accumulated and the ending must be 1 byte long + def read_until( + self, min_num_bytes, ending, timeout=10, data_consumer=None, timeout_overall=None + ): + """ + min_num_bytes: Obsolete. + ending: Return if 'ending' matches. + timeout [s]: Return if timeout between characters. None: Infinite timeout. + timeout_overall [s]: Return not later than timeout_overall. None: Infinite timeout. + data_consumer: Use callback for incoming characters. + If data_consumer is used then data is not accumulated and the ending must be 1 byte long + + It is not visible to the caller why the function returned. It could be ending or timeout. + """ assert data_consumer is None or len(ending) == 1 + assert isinstance(timeout, (type(None), int, float)) + assert isinstance(timeout_overall, (type(None), int, float)) - data = self.serial.read(min_num_bytes) - if data_consumer: - data_consumer(data) - timeout_count = 0 + data = b"" + begin_overall_s = begin_char_s = time.monotonic() while True: if data.endswith(ending): break - elif self.serial.inWaiting() > 0: + new_data = None + if self.is_pty or self.serial.inWaiting() > 0: new_data = self.serial.read(1) + if new_data: if data_consumer: data_consumer(new_data) data = new_data else: data = data + new_data - timeout_count = 0 + begin_char_s = time.monotonic() else: - timeout_count += 1 - if timeout is not None and timeout_count >= 100 * timeout: + if timeout is not None and time.monotonic() >= begin_char_s + timeout: + break + if ( + timeout_overall is not None + and time.monotonic() >= begin_overall_s + timeout_overall + ): break time.sleep(0.01) return data - def enter_raw_repl(self, soft_reset=True): - self.serial.write(b"\r\x03\x03") # ctrl-C twice: interrupt any running program + def enter_raw_repl(self, soft_reset=True, timeout_overall=10): + try: + self._enter_raw_repl_unprotected(soft_reset, timeout_overall) + except OSError as er: + raise PyboardError("could not enter raw repl: {}".format(er)) + + def _enter_raw_repl_unprotected(self, soft_reset, timeout_overall): + self.serial.write(b"\r\x03") # ctrl-C: interrupt any running program # flush input (without relying on serial.flushInput()) n = self.serial.inWaiting() @@ -340,7 +404,9 @@ def enter_raw_repl(self, soft_reset=True): self.serial.write(b"\r\x01") # ctrl-A: enter raw REPL if soft_reset: - data = self.read_until(1, b"raw REPL; CTRL-B to exit\r\n>") + data = self.read_until( + 1, b"raw REPL; CTRL-B to exit\r\n>", timeout_overall=timeout_overall + ) if not data.endswith(b"raw REPL; CTRL-B to exit\r\n>"): print(data) raise PyboardError("could not enter raw repl") @@ -350,12 +416,12 @@ def enter_raw_repl(self, soft_reset=True): # Waiting for "soft reboot" independently to "raw REPL" (done below) # allows boot.py to print, which will show up after "soft reboot" # and before "raw REPL". - data = self.read_until(1, b"soft reboot\r\n") + data = self.read_until(1, b"soft reboot\r\n", timeout_overall=timeout_overall) if not data.endswith(b"soft reboot\r\n"): print(data) raise PyboardError("could not enter raw repl") - data = self.read_until(1, b"raw REPL; CTRL-B to exit\r\n") + data = self.read_until(1, b"raw REPL; CTRL-B to exit\r\n", timeout_overall=timeout_overall) if not data.endswith(b"raw REPL; CTRL-B to exit\r\n"): print(data) raise PyboardError("could not enter raw repl") @@ -473,8 +539,8 @@ def eval(self, expression, parse=False): return ret # In Python3, call as pyboard.exec(), see the setattr call below. - def exec_(self, command, data_consumer=None): - ret, ret_err = self.exec_raw(command, data_consumer=data_consumer) + def exec_(self, command, timeout=10, data_consumer=None): + ret, ret_err = self.exec_raw(command, timeout, data_consumer) if ret_err: raise PyboardError("exception", ret, ret_err) return ret @@ -485,7 +551,7 @@ def execfile(self, filename): return self.exec_(pyfile) def get_time(self): - t = str(self.eval("pyb.RTC().datetime()"), encoding="utf8")[1:-1].split(", ") + t = str(self.eval("machine.RTC().datetime()"), encoding="utf8")[1:-1].split(", ") return int(t[4]) * 3600 + int(t[5]) * 60 + int(t[6]) def fs_exists(self, src): diff --git a/tools/pydfu.py b/tools/pydfu.py index cd7354818cd..376c697cbd5 100755 --- a/tools/pydfu.py +++ b/tools/pydfu.py @@ -11,8 +11,6 @@ See document UM0391 for a description of the DFuse file. """ -from __future__ import print_function - import argparse import collections import inspect @@ -75,11 +73,7 @@ # USB DFU interface __DFU_INTERFACE = 0 -# Python 3 deprecated getargspec in favour of getfullargspec, but -# Python 2 doesn't have the latter, so detect which one to use -getargspec = getattr(inspect, "getfullargspec", getattr(inspect, "getargspec", None)) - -if "length" in 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) diff --git a/tools/shared_bindings_matrix.py b/tools/shared_bindings_matrix.py new file mode 100644 index 00000000000..c92487a4ca9 --- /dev/null +++ b/tools/shared_bindings_matrix.py @@ -0,0 +1,519 @@ +# The MIT License (MIT) +# +# SPDX-FileCopyrightText: Copyright (c) 2019 Michael Schroeder +# +# 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 json +import os +import pathlib +import re +import subprocess +import tomllib + +from concurrent.futures import ThreadPoolExecutor + +SUPPORTED_PORTS = [ + "analog", + "atmel-samd", + "cxd56", + "espressif", + "mimxrt10xx", + "nordic", + "raspberrypi", + "silabs", + "stm", + "zephyr-cp", +] + +ALIASES_BY_BOARD = { + "circuitplayground_express": [ + "circuitplayground_express_4h", + "circuitplayground_express_digikey_pycon2019", + ], + "pybadge": ["edgebadge"], + "pyportal": ["pyportal_pynt"], + "gemma_m0": ["gemma_m0_pycon2018"], +} + +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", +} + +ADDITIONAL_MODULES = { + "_asyncio": "MICROPY_PY_ASYNCIO", + "_bleio (native)": "CIRCUITPY_BLEIO_NATIVE", + "_bleio (HCI co-processor)": "CIRCUITPY_BLEIO_HCI", + "_eve": "CIRCUITPY__EVE", + "adafruit_bus_device": "CIRCUITPY_BUSDEVICE", + "adafruit_pixelbuf": "CIRCUITPY_PIXELBUF", + "array": "CIRCUITPY_ARRAY", + # always available, so depend on something that's always 1. + "builtins": "CIRCUITPY", + "builtins.pow3": "CIRCUITPY_BUILTINS_POW3", + "busio.SPI": "CIRCUITPY_BUSIO_SPI", + "busio.UART": "CIRCUITPY_BUSIO_UART", + "collections": "CIRCUITPY_COLLECTIONS", + "fontio": "CIRCUITPY_DISPLAYIO", + "io": "CIRCUITPY_IO", + "keypad.KeyMatrix": "CIRCUITPY_KEYPAD_KEYMATRIX", + "keypad.Keys": "CIRCUITPY_KEYPAD_KEYS", + "keypad.ShiftRegisterKeys": "CIRCUITPY_KEYPAD_SHIFTREGISTERKEYS", + "keypad_demux.DemuxKeyMatrix": "CIRCUITPY_KEYPAD_DEMUX", + "os.getenv": "CIRCUITPY_SETTINGS_TOML", + "select": "MICROPY_PY_SELECT_SELECT", + "supervisor.get_setting": "CIRCUITPY_SETTINGS_TOML", + "sys": "CIRCUITPY_SYS", + "terminalio": "CIRCUITPY_DISPLAYIO", + "usb": "CIRCUITPY_PYUSB", + "socketpool.socketpool.AF_INET6": "CIRCUITPY_SOCKETPOOL_IPV6", +} + +MODULES_NOT_IN_BINDINGS = ["binascii", "errno", "json", "re", "ulab"] + +FROZEN_EXCLUDES = ["examples", "docs", "tests", "utils", "conf.py", "setup.py"] +"""Files and dirs at the root of a frozen directory that should be ignored. +This is the same list as in the preprocess_frozen_modules script.""" + +repository_urls = {} +"""Cache of repository URLs for frozen modules.""" + +root_dir = pathlib.Path(__file__).resolve().parent.parent + + +def get_circuitpython_root_dir(): + """The path to the root './circuitpython' directory.""" + return root_dir + + +def get_bindings(): + """Get a list of modules in shared-bindings and ports/*/bindings + based on folder names.""" + shared_bindings_modules = [ + module.name + for module in (get_circuitpython_root_dir() / "shared-bindings").iterdir() + if module.is_dir() + ] + bindings_modules = [] + for d in get_circuitpython_root_dir().glob("ports/*/bindings"): + bindings_modules.extend(module.name for module in d.iterdir() if d.is_dir()) + return ( + shared_bindings_modules + + bindings_modules + + MODULES_NOT_IN_BINDINGS + + list(ADDITIONAL_MODULES.keys()) + ) + + +def get_board_mapping(): + """ + Compiles the list of boards from the directories, with aliases and mapping + to the port. + """ + boards = {} + for port in SUPPORTED_PORTS: + board_path = root_dir / "ports" / port / "boards" + # Zephyr port has vendor specific subdirectories to match zephyr (and + # clean up the boards folder.) + g = "*/*" if port == "zephyr-cp" else "*" + for board_path in board_path.glob(g): + if board_path.is_dir(): + board_id = board_path.name + if port == "zephyr-cp": + vendor = board_path.parent.name + board_id = f"{vendor}_{board_id}" + aliases = ALIASES_BY_BOARD.get(board_path.name, []) + boards[board_id] = { + "port": port, + "download_count": 0, + "aliases": aliases, + "directory": board_path, + } + for alias in aliases: + boards[alias] = { + "port": port, + "download_count": 0, + "alias": True, + "aliases": [], + "directory": board_path, + } + return boards + + +def build_module_map(): + """Establish the base of the JSON file, based on the contents from + `configs`. Base contains the module name and the controlling C macro name. + """ + base = dict() + modules = get_bindings() + for module in modules: + full_name = module + if module in ADDITIONAL_MODULES: + search_identifier = ADDITIONAL_MODULES[module] + else: + search_identifier = "CIRCUITPY_" + module.lstrip("_").upper() + + base[module] = { + "name": full_name, + "key": search_identifier, + } + + return base + + +def get_settings_from_makefile(port_dir, board_name): + """Invoke make to print the value of critical build settings + + This means that the effect of all Makefile directives is taken + into account, without having to re-encode the logic that sets them + in this script, something that has proved error-prone + + This list must explicitly include any setting queried by tools/ci_set_matrix.py. + """ + if os.getenv("NO_BINDINGS_MATRIX"): + return {"CIRCUITPY_BUILD_EXTENSIONS": ".bin"} + + contents = subprocess.run( + [ + "make", + # Don't let make run in parallel; it can mix up the output from the various "print-" targets. + "-j1", + "-C", + port_dir, + "-f", + "Makefile", + f"BOARD={board_name}", + "print-CFLAGS", + "print-CIRCUITPY_BUILD_EXTENSIONS", + "print-FROZEN_MPY_DIRS", + "print-SRC_PATTERNS", + "print-SRC_SUPERVISOR", + ], + encoding="utf-8", + errors="replace", + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + ) + # Make signals errors with exit status 2; 0 and 1 are "non-error" statuses + if contents.returncode not in (0, 1): + error_msg = ( + f"Invoking '{' '.join(contents.args)}' exited with " + f"{contents.returncode}: {contents.stderr}" + ) + raise RuntimeError(error_msg) + + settings = {} + for line in contents.stdout.split("\n"): + if line.startswith("CFLAGS ="): + for m in re.findall(r"-D([A-Z][A-Z0-9_]*)=(\d+)", line): + settings[m[0]] = m[1] + elif m := re.match(r"^([A-Z][A-Z0-9_]*) = (.*)$", line): + settings[m.group(1)] = m.group(2) + + return settings + + +def get_repository_url(directory): + if directory in repository_urls: + return repository_urls[directory] + readme = None + for readme_path in ( + os.path.join(directory, "README.rst"), + os.path.join(os.path.dirname(directory), "README.rst"), + ): + if os.path.exists(readme_path): + readme = readme_path + break + path = None + if readme: + with open(readme, "r") as fp: + for line in fp.readlines(): + if m := re.match( + r"\s+:target:\s+(http\S+(docs.circuitpython|readthedocs)\S+)\s*", + line, + ): + path = m.group(1) + break + if m := re.search(r"<(http[^>]+)>", line): + path = m.group(1) + break + if path is None: + contents = subprocess.run( + ["git", "remote", "get-url", "origin"], + encoding="utf-8", + errors="replace", + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + cwd=directory, + ) + path = contents.stdout.strip() + repository_urls[directory] = path + return path + + +def remove_prefix(s, prefix): + if not s.startswith(prefix): + raise ValueError(f"{s=} does not start with {prefix=}") + return s.removeprefix(prefix) + + +def frozen_modules_from_dirs(frozen_mpy_dirs, withurl): + """ + Go through the list of frozen directories and extract the python modules. + Paths are of the type: + $(TOP)/frozen/Adafruit_CircuitPython_CircuitPlayground + $(TOP)/frozen/circuitpython-stage/meowbit + Python modules are at the root of the path, and are python files or directories + containing python files. Except the ones in the FROZEN_EXCLUDES list. + """ + frozen_modules = [] + for frozen_path in filter(lambda x: x, frozen_mpy_dirs.split(" ")): + frozen_path = remove_prefix(frozen_path, "../../") + source_dir = get_circuitpython_root_dir() / frozen_path + url_repository = get_repository_url(source_dir) + for sub in source_dir.glob("*"): + if sub.name in FROZEN_EXCLUDES: + continue + if sub.name.endswith(".py"): + if withurl: + frozen_modules.append((sub.name[:-3], url_repository)) + else: + frozen_modules.append(sub.name[:-3]) + continue + if next(sub.glob("**/*.py"), None): # tests if not empty + if withurl: + frozen_modules.append((sub.name, url_repository)) + else: + frozen_modules.append(sub.name) + return frozen_modules + + +def lookup_setting(settings, key, default=""): + while True: + value = settings.get(key, default) + if not value.startswith("$"): + break + key = value[2:-1] + return value + + +def get_branded_name(board_id, board_directory, autogen_board_info): + """Return the board's product name, falling back to its board id.""" + if autogen_board_info: + # Many zephyr-cp boards share a name with a native board, so tell them apart. + return autogen_board_info["name"] + " (Zephyr)" + with open(board_directory / "mpconfigboard.h") as f: + board_name_re = re.search(r"(?<=MICROPY_HW_BOARD_NAME)\s+(.+)", f.read()) + if not board_name_re: + return board_id + branded_name = board_name_re.group(1).strip('"') + if '"' in branded_name: # sometimes the closing " is not at line end + branded_name = branded_name[: branded_name.index('"')] + return branded_name + + +def get_mcu_and_flash(board_directory, autogen_board_info): + """Return the board's MCU name and its external flash chips as a quoted, comma-separated string. + + zephyr-cp boards don't record either yet, so they get empty strings. + """ + if autogen_board_info: + return "", "" + with open(board_directory / "mpconfigboard.h") as f: + mcu_re = re.search(r"(?<=MICROPY_HW_MCU_NAME)\s+(.+)", f.read()) + mcu = "" + if mcu_re: + mcu = mcu_re.group(1).strip('"') + if '"' in mcu: # in case the closing " is not at line end + mcu = mcu[: mcu.index('"')] + with open(board_directory / "mpconfigboard.mk") as f: + flash_re = re.search(r"(?<=EXTERNAL_FLASH_DEVICES)\s+=\s+(.+)", f.read()) + flash = "" + if flash_re: + # Multiple flash chips are written in several ways. Normalize them to + # a quoted, comma-separated string. + flash = '"' + flash_re.group(1).replace('"', "") + '"' + return mcu, flash + + +def get_pins(board_directory): + """Return the board's [board_pin, chip_pin] pairs from pins.c.""" + try: + with open(board_directory / "pins.c") as f: + pin_lines = f.readlines() + except FileNotFoundError: # silabs and zephyr-cp boards have no pins.c + return [] + pins = [] + for line in pin_lines: + if pin_re := re.search(r"QSTR_([^\)]+).+pin_([^\)]+)", line): + pins.append([pin_re.group(1), pin_re.group(2)]) + return pins + + +def get_board_modules(settings, autogen_board_info, base): + """Return the sorted names of the modules enabled on the board.""" + if autogen_board_info: + modules = [k for k, enabled in autogen_board_info["modules"].items() if enabled] + else: + modules = [ + info["name"] + for info in base.values() + if int(lookup_setting(settings, info["key"], "0")) + ] + return sorted(modules) + + +def get_board_extensions(board_id, settings): + """Return the file extensions the board's build produces, such as ["uf2"].""" + if "CIRCUITPY_BUILD_EXTENSIONS" not in settings: + raise OSError(f"Board extensions undefined: {board_id}.") + extensions = settings["CIRCUITPY_BUILD_EXTENSIONS"] + if isinstance(extensions, str): + extensions = [extension.strip() for extension in extensions.split(",")] + return extensions + + +def collect_board_data(): + """Gather what support_matrix_by_board() needs about every board, keyed by board id. + + Aliases are left out; support_matrix_by_board() adds them. The result holds + only JSON types, so it can be saved and reused. + + This runs make once for each board outside zephyr-cp, which takes a while. + """ + base = build_module_map() + + def collect(arg): + board_id, board_info = arg + port = board_info["port"] + board_directory = board_info["directory"] + if port == "zephyr-cp": + with (board_directory / "circuitpython.toml").open("rb") as f: + settings = tomllib.load(f) + with (board_directory / "autogen_board_info.toml").open("rb") as f: + autogen_board_info = tomllib.load(f) + else: + port_dir = board_directory.parent.parent + settings = get_settings_from_makefile(str(port_dir), board_directory.name) + autogen_board_info = None + + frozen_libraries = [] + if "FROZEN_MPY_DIRS" in settings: + frozen_libraries = [ + list(library) + for library in sorted( + frozen_modules_from_dirs(settings["FROZEN_MPY_DIRS"], withurl=True) + ) + ] + + mcu, flash = get_mcu_and_flash(board_directory, autogen_board_info) + return board_id, { + "port": port, + "branded_name": get_branded_name(board_id, board_directory, autogen_board_info), + "mcu": mcu, + "flash": flash, + "pins": get_pins(board_directory), + "modules": get_board_modules(settings, autogen_board_info, base), + "extensions": get_board_extensions(board_id, settings), + # [name, repository url] pairs + "frozen_libraries": frozen_libraries, + } + + real_boards = [ + (board_id, board_info) + for board_id, board_info in get_board_mapping().items() + if not board_info.get("alias", False) + ] + with ThreadPoolExecutor(max_workers=os.cpu_count()) as executor: + return dict(executor.map(collect, real_boards)) + + +def write_board_data(path, board_data): + """Save the output of collect_board_data() as JSON.""" + # Keep the board order: when boards share a product name, the last one wins. + with open(path, "w") as f: + json.dump(board_data, f, indent=1) + + +def read_board_data(path): + """Return board data saved by write_board_data(), or None if path doesn't exist.""" + try: + with open(path) as f: + return json.load(f) + except FileNotFoundError: + return None + + +def support_matrix_by_board( + use_branded_name=True, + withurl=True, + add_port=False, + add_chips=False, + add_pins=False, + add_branded_name=False, + board_data=None, +): + """Return each board's modules, frozen libraries and build extensions. + + Aliases get their own entries. Keys are board ids, or product names if + use_branded_name is set. The add_* flags add more fields. + + board_data is the output of collect_board_data(). If it is None, it is collected here. + """ + if board_data is None: + board_data = collect_board_data() + + def board_entry(data): + entry = { + "modules": data["modules"], + "frozen_libraries": [ + tuple(library) if withurl else library[0] for library in data["frozen_libraries"] + ], + "extensions": data["extensions"], + } + if add_branded_name: + entry["branded_name"] = data["branded_name"] + if add_port: + entry["port"] = data["port"] + if add_chips: + entry["mcu"] = data["mcu"] + entry["flash"] = data["flash"] + if add_pins: + entry["pins"] = [tuple(pin) for pin in data["pins"]] + return entry + + boards = [] + for board_id, data in board_data.items(): + boards.append((data["branded_name"] if use_branded_name else board_id, board_entry(data))) + for alias in ALIASES_BY_BOARD.get(board_id, []): + if use_branded_name: + alias = ALIASES_BRAND_NAMES.get(alias, alias.replace("_", " ").title()) + boards.append((alias, board_entry(data))) + + # Several boards can share a product name; the last one listed wins. + return dict(sorted(boards, key=lambda board: board[0])) + + +if __name__ == "__main__": + print(json.dumps(support_matrix_by_board(), indent=2)) diff --git a/tools/tinytest-codegen.py b/tools/tinytest-codegen.py deleted file mode 100755 index 0f0428a8f10..00000000000 --- a/tools/tinytest-codegen.py +++ /dev/null @@ -1,167 +0,0 @@ -#!/usr/bin/env python3 - -# SPDX-FileCopyrightText: 2014 MicroPython & CircuitPython contributors (https://github.com/adafruit/circuitpython/graphs/contributors) -# -# SPDX-License-Identifier: MIT - -import os, sys -from glob import glob -from re import sub -import argparse - - -def escape(s): - s = s.decode() - lookup = { - "\0": "\\0", - "\t": "\\t", - "\n": '\\n"\n"', - "\r": "\\r", - "\\": "\\\\", - '"': '\\"', - } - return '""\n"{}"'.format("".join([lookup[x] if x in lookup else x for x in s])) - - -def chew_filename(t): - return {"func": "test_{}_fn".format(sub(r"/|\.|-", "_", t)), "desc": t} - - -def script_to_map(test_file): - r = {"name": chew_filename(test_file)["func"]} - with open(test_file, "rb") as test: - script = test.readlines() - - # 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)) - - with open(test_file + ".exp", "rb") as f: - r["output"] = escape(f.read()) - - return r - - -def load_profile(profile_file, test_dirs, exclude_tests): - profile_globals = {"test_dirs": test_dirs, "exclude_tests": exclude_tests} - exec(profile_file.read(), profile_globals) - return profile_globals["test_dirs"], profile_globals["exclude_tests"] - - -test_function = ( - "void {name}(void* data) {{\n" - " static const char pystr[] = {script};\n" - " static const char exp[] = {output};\n" - ' printf("\\n");\n' - " upytest_set_expected_output(exp, sizeof(exp) - 1);\n" - " upytest_execute_test(pystr);\n" - ' printf("result: ");\n' - "}}" -) - -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 }},' - -## XXX: may be we could have `--without ` argument... - -test_dirs = set( - ( - "basics", - "extmod", - "float", - "micropython", - "misc", - ) -) - -exclude_tests = set( - ( - # pattern matching in .exp - "basics/bytes_compare3.py", - "extmod/ticks_diff.py", - "extmod/time_ms_us.py", - # unicode char issue - "extmod/json_loads.py", - # doesn't output to python stdout - "extmod/re_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", - # requires double precision floating point to work - "float/float2int_doubleprec_intbig.py", - "float/float_format_ints_doubleprec.py", - "float/float_parse_doubleprec.py", - # different filename in output - "micropython/emg_exc.py", - "micropython/heapalloc_traceback.py", - # don't have emergency exception buffer - "micropython/heapalloc_exc_compressed_emg_exc.py", - # pattern matching in .exp - "micropython/meminfo.py", - # needs sys stdfiles - "misc/print_exception.py", - # settrace .exp files are too large - "misc/sys_settrace_loop.py", - "misc/sys_settrace_generator.py", - "misc/sys_settrace_features.py", - # don't have f-string - "basics/string_fstring.py", - "basics/string_fstring_debug.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.add_argument("--exclude", action="append", help="exclude test by name") -argparser.add_argument( - "--profile", - type=argparse.FileType("rt", encoding="utf-8"), - help="optional profile file providing test directories and exclusion list", -) -args = argparser.parse_args() - -if not args.stdin: - if args.profile: - test_dirs, exclude_tests = load_profile(args.profile, test_dirs, exclude_tests) - if args.exclude: - exclude_tests = exclude_tests.union(args.exclude) - for group in test_dirs: - 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))) - -testgroup_members = [testgroup_member.format(name=group) for group in [""]] - -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")) diff --git a/tools/verifygitlog.py b/tools/verifygitlog.py index ad9385e7ac5..1818b7f89a4 100755 --- a/tools/verifygitlog.py +++ b/tools/verifygitlog.py @@ -38,7 +38,7 @@ def warning(self, text): def git_log(pretty_format, *args): # Delete pretty argument from user args so it doesn't interfere with what we do. - args = ["git", "log"] + [arg for arg in args if "--pretty" not in args] + args = ["git", "log"] + [arg for arg in args if "--pretty" not in arg] args.append("--pretty=format:" + pretty_format) very_verbose("git_log", *args) # Generator yielding each output line. @@ -47,7 +47,7 @@ def git_log(pretty_format, *args): def diagnose_subject_line(subject_line, subject_line_format, err): - err.error("Subject line: " + subject_line) + err.error('Subject line: "' + subject_line + '"') if not subject_line.endswith("."): err.error('* must end with "."') if not re.match(r"^[^!]+: ", subject_line): @@ -96,20 +96,47 @@ def verify_message_body(raw_body, err): if len(subject_line) >= 73: err.error("Subject line must be 72 or fewer characters: " + subject_line) + # Do additional checks on the prefix of the subject line. + verify_subject_line_prefix(subject_line.split(": ")[0], err) + # Second one divides subject and body. if len(raw_body) > 1 and raw_body[1]: err.error("Second message line must be empty: " + raw_body[1]) # Message body lines. for line in raw_body[2:]: - # Long lines with URLs are exempt from the line length rule. - if len(line) >= 76 and "://" not in line: + # Long lines with URLs or human names are exempt from the line length rule. + if len(line) >= 76 and not ( + "://" in line + or line.startswith("Co-authored-by: ") + or line.startswith("Signed-off-by: ") + ): err.error("Message lines should be 75 or less characters: " + line) if not raw_body[-1].startswith("Signed-off-by: ") or "@" not in raw_body[-1]: err.error('Message must be signed-off. Use "git commit -s".') +def verify_subject_line_prefix(prefix, err): + ext = (".c", ".h", ".cpp", ".js", ".rst", ".md") + + if prefix.startswith((".", "/")): + err.error('Subject prefix cannot begin with "." or "/".') + + if prefix.endswith("/"): + err.error('Subject prefix cannot end with "/".') + + if prefix.startswith("ports/"): + err.error( + 'Subject prefix cannot begin with "ports/", start with the name of the port instead.' + ) + + if prefix.endswith(ext): + err.error( + "Subject prefix cannot end with a file extension, use the main part of the filename without the extension." + ) + + def run(args): verbose("run", *args)